blob: 39d1e81a3f5fbc1da26920a48a673a182ad7f1f7 [file] [log] [blame]
drha059ad02001-04-17 20:09:11 +00001/*
drh9e572e62004-04-23 23:43:10 +00002** 2004 April 6
drha059ad02001-04-17 20:09:11 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drha059ad02001-04-17 20:09:11 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drha059ad02001-04-17 20:09:11 +000010**
11*************************************************************************
peter.d.reid60ec9142014-09-06 16:39:46 +000012** This file implements an external (disk-based) database using BTrees.
drha3152892007-05-05 11:48:52 +000013** See the header comment on "btreeInt.h" for additional information.
14** Including a description of file format and an overview of operation.
drha059ad02001-04-17 20:09:11 +000015*/
drha3152892007-05-05 11:48:52 +000016#include "btreeInt.h"
paulb95a8862003-04-01 21:16:41 +000017
drh8c42ca92001-06-22 19:15:00 +000018/*
drha3152892007-05-05 11:48:52 +000019** The header string that appears at the beginning of every
20** SQLite database.
drh556b2a22005-06-14 16:04:05 +000021*/
drh556b2a22005-06-14 16:04:05 +000022static const char zMagicHeader[] = SQLITE_FILE_HEADER;
drh08ed44e2001-04-29 23:32:55 +000023
drh8c42ca92001-06-22 19:15:00 +000024/*
drha3152892007-05-05 11:48:52 +000025** Set this global variable to 1 to enable tracing using the TRACE
26** macro.
drh615ae552005-01-16 23:21:00 +000027*/
drhe8f52c52008-07-12 14:52:20 +000028#if 0
danielk1977a50d9aa2009-06-08 14:49:45 +000029int sqlite3BtreeTrace=1; /* True to enable tracing */
drhe8f52c52008-07-12 14:52:20 +000030# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
31#else
32# define TRACE(X)
drh615ae552005-01-16 23:21:00 +000033#endif
drh615ae552005-01-16 23:21:00 +000034
drh5d433ce2010-08-14 16:02:52 +000035/*
36** Extract a 2-byte big-endian integer from an array of unsigned bytes.
37** But if the value is zero, make it 65536.
38**
39** This routine is used to extract the "offset to cell content area" value
40** from the header of a btree page. If the page size is 65536 and the page
41** is empty, the offset should be 65536, but the 2-byte value stores zero.
42** This routine makes the necessary adjustment to 65536.
43*/
44#define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
drh86f8c192007-08-22 00:39:19 +000045
dan09ff9e12013-03-11 11:49:03 +000046/*
47** Values passed as the 5th argument to allocateBtreePage()
48*/
49#define BTALLOC_ANY 0 /* Allocate any page */
50#define BTALLOC_EXACT 1 /* Allocate exact page if possible */
51#define BTALLOC_LE 2 /* Allocate any page <= the parameter */
52
53/*
54** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
55** defined, or 0 if it is. For example:
56**
57** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
58*/
59#ifndef SQLITE_OMIT_AUTOVACUUM
60#define IfNotOmitAV(expr) (expr)
61#else
62#define IfNotOmitAV(expr) 0
63#endif
64
drhe53831d2007-08-17 01:14:38 +000065#ifndef SQLITE_OMIT_SHARED_CACHE
66/*
danielk1977502b4e02008-09-02 14:07:24 +000067** A list of BtShared objects that are eligible for participation
68** in shared cache. This variable has file scope during normal builds,
69** but the test harness needs to access it so we make it global for
70** test builds.
drh7555d8e2009-03-20 13:15:30 +000071**
72** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
drhe53831d2007-08-17 01:14:38 +000073*/
74#ifdef SQLITE_TEST
drh78f82d12008-09-02 00:52:52 +000075BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
drhe53831d2007-08-17 01:14:38 +000076#else
drh78f82d12008-09-02 00:52:52 +000077static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
drhe53831d2007-08-17 01:14:38 +000078#endif
drhe53831d2007-08-17 01:14:38 +000079#endif /* SQLITE_OMIT_SHARED_CACHE */
80
81#ifndef SQLITE_OMIT_SHARED_CACHE
82/*
83** Enable or disable the shared pager and schema features.
84**
85** This routine has no effect on existing database connections.
86** The shared cache setting effects only future calls to
87** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
88*/
89int sqlite3_enable_shared_cache(int enable){
danielk1977502b4e02008-09-02 14:07:24 +000090 sqlite3GlobalConfig.sharedCacheEnabled = enable;
drhe53831d2007-08-17 01:14:38 +000091 return SQLITE_OK;
92}
93#endif
94
drhd677b3d2007-08-20 22:48:41 +000095
danielk1977aef0bf62005-12-30 16:28:01 +000096
97#ifdef SQLITE_OMIT_SHARED_CACHE
98 /*
drhc25eabe2009-02-24 18:57:31 +000099 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
100 ** and clearAllSharedCacheTableLocks()
danielk1977aef0bf62005-12-30 16:28:01 +0000101 ** manipulate entries in the BtShared.pLock linked list used to store
102 ** shared-cache table level locks. If the library is compiled with the
103 ** shared-cache feature disabled, then there is only ever one user
danielk1977da184232006-01-05 11:34:32 +0000104 ** of each BtShared structure and so this locking is not necessary.
105 ** So define the lock related functions as no-ops.
danielk1977aef0bf62005-12-30 16:28:01 +0000106 */
drhc25eabe2009-02-24 18:57:31 +0000107 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
108 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
109 #define clearAllSharedCacheTableLocks(a)
danielk197794b30732009-07-02 17:21:57 +0000110 #define downgradeAllSharedCacheTableLocks(a)
danielk197796d48e92009-06-29 06:00:37 +0000111 #define hasSharedCacheTableLock(a,b,c,d) 1
112 #define hasReadConflicts(a, b) 0
drhe53831d2007-08-17 01:14:38 +0000113#endif
danielk1977aef0bf62005-12-30 16:28:01 +0000114
drhe53831d2007-08-17 01:14:38 +0000115#ifndef SQLITE_OMIT_SHARED_CACHE
danielk197796d48e92009-06-29 06:00:37 +0000116
117#ifdef SQLITE_DEBUG
118/*
drh0ee3dbe2009-10-16 15:05:18 +0000119**** This function is only used as part of an assert() statement. ***
120**
121** Check to see if pBtree holds the required locks to read or write to the
122** table with root page iRoot. Return 1 if it does and 0 if not.
123**
124** For example, when writing to a table with root-page iRoot via
danielk197796d48e92009-06-29 06:00:37 +0000125** Btree connection pBtree:
126**
127** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
128**
drh0ee3dbe2009-10-16 15:05:18 +0000129** When writing to an index that resides in a sharable database, the
danielk197796d48e92009-06-29 06:00:37 +0000130** caller should have first obtained a lock specifying the root page of
drh0ee3dbe2009-10-16 15:05:18 +0000131** the corresponding table. This makes things a bit more complicated,
132** as this module treats each table as a separate structure. To determine
133** the table corresponding to the index being written, this
danielk197796d48e92009-06-29 06:00:37 +0000134** function has to search through the database schema.
135**
drh0ee3dbe2009-10-16 15:05:18 +0000136** Instead of a lock on the table/index rooted at page iRoot, the caller may
danielk197796d48e92009-06-29 06:00:37 +0000137** hold a write-lock on the schema table (root page 1). This is also
138** acceptable.
139*/
140static int hasSharedCacheTableLock(
141 Btree *pBtree, /* Handle that must hold lock */
142 Pgno iRoot, /* Root page of b-tree */
143 int isIndex, /* True if iRoot is the root of an index b-tree */
144 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
145){
146 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
147 Pgno iTab = 0;
148 BtLock *pLock;
149
drh0ee3dbe2009-10-16 15:05:18 +0000150 /* If this database is not shareable, or if the client is reading
danielk197796d48e92009-06-29 06:00:37 +0000151 ** and has the read-uncommitted flag set, then no lock is required.
drh0ee3dbe2009-10-16 15:05:18 +0000152 ** Return true immediately.
153 */
danielk197796d48e92009-06-29 06:00:37 +0000154 if( (pBtree->sharable==0)
155 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
danielk197796d48e92009-06-29 06:00:37 +0000156 ){
157 return 1;
158 }
159
drh0ee3dbe2009-10-16 15:05:18 +0000160 /* If the client is reading or writing an index and the schema is
161 ** not loaded, then it is too difficult to actually check to see if
162 ** the correct locks are held. So do not bother - just return true.
163 ** This case does not come up very often anyhow.
164 */
drh2c5e35f2014-08-05 11:04:21 +0000165 if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
drh0ee3dbe2009-10-16 15:05:18 +0000166 return 1;
167 }
168
danielk197796d48e92009-06-29 06:00:37 +0000169 /* Figure out the root-page that the lock should be held on. For table
170 ** b-trees, this is just the root page of the b-tree being read or
171 ** written. For index b-trees, it is the root page of the associated
172 ** table. */
173 if( isIndex ){
174 HashElem *p;
175 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
176 Index *pIdx = (Index *)sqliteHashData(p);
shane5eff7cf2009-08-10 03:57:58 +0000177 if( pIdx->tnum==(int)iRoot ){
178 iTab = pIdx->pTable->tnum;
danielk197796d48e92009-06-29 06:00:37 +0000179 }
180 }
181 }else{
182 iTab = iRoot;
183 }
184
185 /* Search for the required lock. Either a write-lock on root-page iTab, a
186 ** write-lock on the schema table, or (if the client is reading) a
187 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
188 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
189 if( pLock->pBtree==pBtree
190 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
191 && pLock->eLock>=eLockType
192 ){
193 return 1;
194 }
195 }
196
197 /* Failed to find the required lock. */
198 return 0;
199}
drh0ee3dbe2009-10-16 15:05:18 +0000200#endif /* SQLITE_DEBUG */
danielk197796d48e92009-06-29 06:00:37 +0000201
drh0ee3dbe2009-10-16 15:05:18 +0000202#ifdef SQLITE_DEBUG
danielk197796d48e92009-06-29 06:00:37 +0000203/*
drh0ee3dbe2009-10-16 15:05:18 +0000204**** This function may be used as part of assert() statements only. ****
danielk197796d48e92009-06-29 06:00:37 +0000205**
drh0ee3dbe2009-10-16 15:05:18 +0000206** Return true if it would be illegal for pBtree to write into the
207** table or index rooted at iRoot because other shared connections are
208** simultaneously reading that same table or index.
209**
210** It is illegal for pBtree to write if some other Btree object that
211** shares the same BtShared object is currently reading or writing
212** the iRoot table. Except, if the other Btree object has the
213** read-uncommitted flag set, then it is OK for the other object to
214** have a read cursor.
215**
216** For example, before writing to any part of the table or index
217** rooted at page iRoot, one should call:
danielk197796d48e92009-06-29 06:00:37 +0000218**
219** assert( !hasReadConflicts(pBtree, iRoot) );
220*/
221static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
222 BtCursor *p;
223 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
224 if( p->pgnoRoot==iRoot
225 && p->pBtree!=pBtree
226 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
227 ){
228 return 1;
229 }
230 }
231 return 0;
232}
233#endif /* #ifdef SQLITE_DEBUG */
234
danielk1977da184232006-01-05 11:34:32 +0000235/*
drh0ee3dbe2009-10-16 15:05:18 +0000236** Query to see if Btree handle p may obtain a lock of type eLock
danielk1977aef0bf62005-12-30 16:28:01 +0000237** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
drhc25eabe2009-02-24 18:57:31 +0000238** SQLITE_OK if the lock may be obtained (by calling
239** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
danielk1977aef0bf62005-12-30 16:28:01 +0000240*/
drhc25eabe2009-02-24 18:57:31 +0000241static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +0000242 BtShared *pBt = p->pBt;
243 BtLock *pIter;
244
drh1fee73e2007-08-29 04:00:57 +0000245 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000246 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
247 assert( p->db!=0 );
danielk1977e0d9e6f2009-07-03 16:25:06 +0000248 assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
drhd677b3d2007-08-20 22:48:41 +0000249
danielk19775b413d72009-04-01 09:41:54 +0000250 /* If requesting a write-lock, then the Btree must have an open write
251 ** transaction on this file. And, obviously, for this to be so there
252 ** must be an open write transaction on the file itself.
253 */
254 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
255 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
256
drh0ee3dbe2009-10-16 15:05:18 +0000257 /* This routine is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000258 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000259 return SQLITE_OK;
260 }
261
danielk1977641b0f42007-12-21 04:47:25 +0000262 /* If some other connection is holding an exclusive lock, the
263 ** requested lock may not be obtained.
264 */
drhc9166342012-01-05 23:32:06 +0000265 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
danielk1977404ca072009-03-16 13:19:36 +0000266 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
267 return SQLITE_LOCKED_SHAREDCACHE;
danielk1977641b0f42007-12-21 04:47:25 +0000268 }
269
danielk1977e0d9e6f2009-07-03 16:25:06 +0000270 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
271 /* The condition (pIter->eLock!=eLock) in the following if(...)
272 ** statement is a simplification of:
273 **
274 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
275 **
276 ** since we know that if eLock==WRITE_LOCK, then no other connection
277 ** may hold a WRITE_LOCK on any table in this file (since there can
278 ** only be a single writer).
279 */
280 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
281 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
282 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
283 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
284 if( eLock==WRITE_LOCK ){
285 assert( p==pBt->pWriter );
drhc9166342012-01-05 23:32:06 +0000286 pBt->btsFlags |= BTS_PENDING;
danielk1977da184232006-01-05 11:34:32 +0000287 }
danielk1977e0d9e6f2009-07-03 16:25:06 +0000288 return SQLITE_LOCKED_SHAREDCACHE;
danielk1977aef0bf62005-12-30 16:28:01 +0000289 }
290 }
291 return SQLITE_OK;
292}
drhe53831d2007-08-17 01:14:38 +0000293#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000294
drhe53831d2007-08-17 01:14:38 +0000295#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000296/*
297** Add a lock on the table with root-page iTable to the shared-btree used
298** by Btree handle p. Parameter eLock must be either READ_LOCK or
299** WRITE_LOCK.
300**
danielk19779d104862009-07-09 08:27:14 +0000301** This function assumes the following:
302**
drh0ee3dbe2009-10-16 15:05:18 +0000303** (a) The specified Btree object p is connected to a sharable
304** database (one with the BtShared.sharable flag set), and
danielk19779d104862009-07-09 08:27:14 +0000305**
drh0ee3dbe2009-10-16 15:05:18 +0000306** (b) No other Btree objects hold a lock that conflicts
danielk19779d104862009-07-09 08:27:14 +0000307** with the requested lock (i.e. querySharedCacheTableLock() has
308** already been called and returned SQLITE_OK).
309**
310** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
311** is returned if a malloc attempt fails.
danielk1977aef0bf62005-12-30 16:28:01 +0000312*/
drhc25eabe2009-02-24 18:57:31 +0000313static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +0000314 BtShared *pBt = p->pBt;
315 BtLock *pLock = 0;
316 BtLock *pIter;
317
drh1fee73e2007-08-29 04:00:57 +0000318 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000319 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
320 assert( p->db!=0 );
drhd677b3d2007-08-20 22:48:41 +0000321
danielk1977e0d9e6f2009-07-03 16:25:06 +0000322 /* A connection with the read-uncommitted flag set will never try to
323 ** obtain a read-lock using this function. The only read-lock obtained
324 ** by a connection in read-uncommitted mode is on the sqlite_master
325 ** table, and that lock is obtained in BtreeBeginTrans(). */
326 assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
327
danielk19779d104862009-07-09 08:27:14 +0000328 /* This function should only be called on a sharable b-tree after it
329 ** has been determined that no other b-tree holds a conflicting lock. */
330 assert( p->sharable );
drhc25eabe2009-02-24 18:57:31 +0000331 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
danielk1977aef0bf62005-12-30 16:28:01 +0000332
333 /* First search the list for an existing lock on this table. */
334 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
335 if( pIter->iTable==iTable && pIter->pBtree==p ){
336 pLock = pIter;
337 break;
338 }
339 }
340
341 /* If the above search did not find a BtLock struct associating Btree p
342 ** with table iTable, allocate one and link it into the list.
343 */
344 if( !pLock ){
drh17435752007-08-16 04:30:38 +0000345 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
danielk1977aef0bf62005-12-30 16:28:01 +0000346 if( !pLock ){
347 return SQLITE_NOMEM;
348 }
349 pLock->iTable = iTable;
350 pLock->pBtree = p;
351 pLock->pNext = pBt->pLock;
352 pBt->pLock = pLock;
353 }
354
355 /* Set the BtLock.eLock variable to the maximum of the current lock
356 ** and the requested lock. This means if a write-lock was already held
357 ** and a read-lock requested, we don't incorrectly downgrade the lock.
358 */
359 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000360 if( eLock>pLock->eLock ){
361 pLock->eLock = eLock;
362 }
danielk1977aef0bf62005-12-30 16:28:01 +0000363
364 return SQLITE_OK;
365}
drhe53831d2007-08-17 01:14:38 +0000366#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000367
drhe53831d2007-08-17 01:14:38 +0000368#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000369/*
drhc25eabe2009-02-24 18:57:31 +0000370** Release all the table locks (locks obtained via calls to
drh0ee3dbe2009-10-16 15:05:18 +0000371** the setSharedCacheTableLock() procedure) held by Btree object p.
danielk1977fa542f12009-04-02 18:28:08 +0000372**
drh0ee3dbe2009-10-16 15:05:18 +0000373** This function assumes that Btree p has an open read or write
drhc9166342012-01-05 23:32:06 +0000374** transaction. If it does not, then the BTS_PENDING flag
danielk1977fa542f12009-04-02 18:28:08 +0000375** may be incorrectly cleared.
danielk1977aef0bf62005-12-30 16:28:01 +0000376*/
drhc25eabe2009-02-24 18:57:31 +0000377static void clearAllSharedCacheTableLocks(Btree *p){
danielk1977641b0f42007-12-21 04:47:25 +0000378 BtShared *pBt = p->pBt;
379 BtLock **ppIter = &pBt->pLock;
danielk1977da184232006-01-05 11:34:32 +0000380
drh1fee73e2007-08-29 04:00:57 +0000381 assert( sqlite3BtreeHoldsMutex(p) );
drhe53831d2007-08-17 01:14:38 +0000382 assert( p->sharable || 0==*ppIter );
danielk1977fa542f12009-04-02 18:28:08 +0000383 assert( p->inTrans>0 );
danielk1977da184232006-01-05 11:34:32 +0000384
danielk1977aef0bf62005-12-30 16:28:01 +0000385 while( *ppIter ){
386 BtLock *pLock = *ppIter;
drhc9166342012-01-05 23:32:06 +0000387 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
danielk1977fa542f12009-04-02 18:28:08 +0000388 assert( pLock->pBtree->inTrans>=pLock->eLock );
danielk1977aef0bf62005-12-30 16:28:01 +0000389 if( pLock->pBtree==p ){
390 *ppIter = pLock->pNext;
danielk1977602b4662009-07-02 07:47:33 +0000391 assert( pLock->iTable!=1 || pLock==&p->lock );
392 if( pLock->iTable!=1 ){
393 sqlite3_free(pLock);
394 }
danielk1977aef0bf62005-12-30 16:28:01 +0000395 }else{
396 ppIter = &pLock->pNext;
397 }
398 }
danielk1977641b0f42007-12-21 04:47:25 +0000399
drhc9166342012-01-05 23:32:06 +0000400 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
danielk1977404ca072009-03-16 13:19:36 +0000401 if( pBt->pWriter==p ){
402 pBt->pWriter = 0;
drhc9166342012-01-05 23:32:06 +0000403 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
danielk1977404ca072009-03-16 13:19:36 +0000404 }else if( pBt->nTransaction==2 ){
drh0ee3dbe2009-10-16 15:05:18 +0000405 /* This function is called when Btree p is concluding its
danielk1977404ca072009-03-16 13:19:36 +0000406 ** transaction. If there currently exists a writer, and p is not
407 ** that writer, then the number of locks held by connections other
408 ** than the writer must be about to drop to zero. In this case
drhc9166342012-01-05 23:32:06 +0000409 ** set the BTS_PENDING flag to 0.
danielk1977404ca072009-03-16 13:19:36 +0000410 **
drhc9166342012-01-05 23:32:06 +0000411 ** If there is not currently a writer, then BTS_PENDING must
danielk1977404ca072009-03-16 13:19:36 +0000412 ** be zero already. So this next line is harmless in that case.
413 */
drhc9166342012-01-05 23:32:06 +0000414 pBt->btsFlags &= ~BTS_PENDING;
danielk1977641b0f42007-12-21 04:47:25 +0000415 }
danielk1977aef0bf62005-12-30 16:28:01 +0000416}
danielk197794b30732009-07-02 17:21:57 +0000417
danielk1977e0d9e6f2009-07-03 16:25:06 +0000418/*
drh0ee3dbe2009-10-16 15:05:18 +0000419** This function changes all write-locks held by Btree p into read-locks.
danielk1977e0d9e6f2009-07-03 16:25:06 +0000420*/
danielk197794b30732009-07-02 17:21:57 +0000421static void downgradeAllSharedCacheTableLocks(Btree *p){
422 BtShared *pBt = p->pBt;
423 if( pBt->pWriter==p ){
424 BtLock *pLock;
425 pBt->pWriter = 0;
drhc9166342012-01-05 23:32:06 +0000426 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
danielk197794b30732009-07-02 17:21:57 +0000427 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
428 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
429 pLock->eLock = READ_LOCK;
430 }
431 }
432}
433
danielk1977aef0bf62005-12-30 16:28:01 +0000434#endif /* SQLITE_OMIT_SHARED_CACHE */
435
drh980b1a72006-08-16 16:42:48 +0000436static void releasePage(MemPage *pPage); /* Forward reference */
437
drh1fee73e2007-08-29 04:00:57 +0000438/*
drh0ee3dbe2009-10-16 15:05:18 +0000439***** This routine is used inside of assert() only ****
440**
441** Verify that the cursor holds the mutex on its BtShared
drh1fee73e2007-08-29 04:00:57 +0000442*/
drh0ee3dbe2009-10-16 15:05:18 +0000443#ifdef SQLITE_DEBUG
drh1fee73e2007-08-29 04:00:57 +0000444static int cursorHoldsMutex(BtCursor *p){
drhff0587c2007-08-29 17:43:19 +0000445 return sqlite3_mutex_held(p->pBt->mutex);
drh1fee73e2007-08-29 04:00:57 +0000446}
447#endif
448
danielk197792d4d7a2007-05-04 12:05:56 +0000449/*
dan5a500af2014-03-11 20:33:04 +0000450** Invalidate the overflow cache of the cursor passed as the first argument.
451** on the shared btree structure pBt.
danielk197792d4d7a2007-05-04 12:05:56 +0000452*/
drh036dbec2014-03-11 23:40:44 +0000453#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
danielk197792d4d7a2007-05-04 12:05:56 +0000454
455/*
456** Invalidate the overflow page-list cache for all cursors opened
457** on the shared btree structure pBt.
458*/
459static void invalidateAllOverflowCache(BtShared *pBt){
460 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000461 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +0000462 for(p=pBt->pCursor; p; p=p->pNext){
463 invalidateOverflowCache(p);
464 }
465}
danielk197796d48e92009-06-29 06:00:37 +0000466
dan5a500af2014-03-11 20:33:04 +0000467#ifndef SQLITE_OMIT_INCRBLOB
danielk197796d48e92009-06-29 06:00:37 +0000468/*
469** This function is called before modifying the contents of a table
drh0ee3dbe2009-10-16 15:05:18 +0000470** to invalidate any incrblob cursors that are open on the
drheeb844a2009-08-08 18:01:07 +0000471** row or one of the rows being modified.
danielk197796d48e92009-06-29 06:00:37 +0000472**
473** If argument isClearTable is true, then the entire contents of the
474** table is about to be deleted. In this case invalidate all incrblob
475** cursors open on any row within the table with root-page pgnoRoot.
476**
477** Otherwise, if argument isClearTable is false, then the row with
478** rowid iRow is being replaced or deleted. In this case invalidate
drh0ee3dbe2009-10-16 15:05:18 +0000479** only those incrblob cursors open on that specific row.
danielk197796d48e92009-06-29 06:00:37 +0000480*/
481static void invalidateIncrblobCursors(
482 Btree *pBtree, /* The database file to check */
danielk197796d48e92009-06-29 06:00:37 +0000483 i64 iRow, /* The rowid that might be changing */
484 int isClearTable /* True if all rows are being deleted */
485){
486 BtCursor *p;
487 BtShared *pBt = pBtree->pBt;
488 assert( sqlite3BtreeHoldsMutex(pBtree) );
489 for(p=pBt->pCursor; p; p=p->pNext){
drh3f387402014-09-24 01:23:00 +0000490 if( (p->curFlags & BTCF_Incrblob)!=0
491 && (isClearTable || p->info.nKey==iRow)
492 ){
danielk197796d48e92009-06-29 06:00:37 +0000493 p->eState = CURSOR_INVALID;
494 }
495 }
496}
497
danielk197792d4d7a2007-05-04 12:05:56 +0000498#else
dan5a500af2014-03-11 20:33:04 +0000499 /* Stub function when INCRBLOB is omitted */
drheeb844a2009-08-08 18:01:07 +0000500 #define invalidateIncrblobCursors(x,y,z)
drh0ee3dbe2009-10-16 15:05:18 +0000501#endif /* SQLITE_OMIT_INCRBLOB */
danielk197792d4d7a2007-05-04 12:05:56 +0000502
drh980b1a72006-08-16 16:42:48 +0000503/*
danielk1977bea2a942009-01-20 17:06:27 +0000504** Set bit pgno of the BtShared.pHasContent bitvec. This is called
505** when a page that previously contained data becomes a free-list leaf
506** page.
507**
508** The BtShared.pHasContent bitvec exists to work around an obscure
509** bug caused by the interaction of two useful IO optimizations surrounding
510** free-list leaf pages:
511**
512** 1) When all data is deleted from a page and the page becomes
513** a free-list leaf page, the page is not written to the database
514** (as free-list leaf pages contain no meaningful data). Sometimes
515** such a page is not even journalled (as it will not be modified,
516** why bother journalling it?).
517**
518** 2) When a free-list leaf page is reused, its content is not read
519** from the database or written to the journal file (why should it
520** be, if it is not at all meaningful?).
521**
522** By themselves, these optimizations work fine and provide a handy
523** performance boost to bulk delete or insert operations. However, if
524** a page is moved to the free-list and then reused within the same
525** transaction, a problem comes up. If the page is not journalled when
526** it is moved to the free-list and it is also not journalled when it
527** is extracted from the free-list and reused, then the original data
528** may be lost. In the event of a rollback, it may not be possible
529** to restore the database to its original configuration.
530**
531** The solution is the BtShared.pHasContent bitvec. Whenever a page is
532** moved to become a free-list leaf page, the corresponding bit is
533** set in the bitvec. Whenever a leaf page is extracted from the free-list,
drh0ee3dbe2009-10-16 15:05:18 +0000534** optimization 2 above is omitted if the corresponding bit is already
danielk1977bea2a942009-01-20 17:06:27 +0000535** set in BtShared.pHasContent. The contents of the bitvec are cleared
536** at the end of every transaction.
537*/
538static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
539 int rc = SQLITE_OK;
540 if( !pBt->pHasContent ){
drhdd3cd972010-03-27 17:12:36 +0000541 assert( pgno<=pBt->nPage );
542 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
drh4c301aa2009-07-15 17:25:45 +0000543 if( !pBt->pHasContent ){
544 rc = SQLITE_NOMEM;
danielk1977bea2a942009-01-20 17:06:27 +0000545 }
546 }
547 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
548 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
549 }
550 return rc;
551}
552
553/*
554** Query the BtShared.pHasContent vector.
555**
556** This function is called when a free-list leaf page is removed from the
557** free-list for reuse. It returns false if it is safe to retrieve the
558** page from the pager layer with the 'no-content' flag set. True otherwise.
559*/
560static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
561 Bitvec *p = pBt->pHasContent;
562 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
563}
564
565/*
566** Clear (destroy) the BtShared.pHasContent bitvec. This should be
567** invoked at the conclusion of each write-transaction.
568*/
569static void btreeClearHasContent(BtShared *pBt){
570 sqlite3BitvecDestroy(pBt->pHasContent);
571 pBt->pHasContent = 0;
572}
573
574/*
drh138eeeb2013-03-27 03:15:23 +0000575** Release all of the apPage[] pages for a cursor.
576*/
577static void btreeReleaseAllCursorPages(BtCursor *pCur){
578 int i;
579 for(i=0; i<=pCur->iPage; i++){
580 releasePage(pCur->apPage[i]);
581 pCur->apPage[i] = 0;
582 }
583 pCur->iPage = -1;
584}
585
586
587/*
drh980b1a72006-08-16 16:42:48 +0000588** Save the current cursor position in the variables BtCursor.nKey
589** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
drhea8ffdf2009-07-22 00:35:23 +0000590**
591** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
592** prior to calling this routine.
drh980b1a72006-08-16 16:42:48 +0000593*/
594static int saveCursorPosition(BtCursor *pCur){
595 int rc;
596
597 assert( CURSOR_VALID==pCur->eState );
598 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000599 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000600
601 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
drhea8ffdf2009-07-22 00:35:23 +0000602 assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
drh980b1a72006-08-16 16:42:48 +0000603
604 /* If this is an intKey table, then the above call to BtreeKeySize()
605 ** stores the integer key in pCur->nKey. In this case this value is
606 ** all that is required. Otherwise, if pCur is not open on an intKey
607 ** table, then malloc space for and store the pCur->nKey bytes of key
608 ** data.
609 */
drh4c301aa2009-07-15 17:25:45 +0000610 if( 0==pCur->apPage[0]->intKey ){
drhda4ca9d2014-09-09 17:27:35 +0000611 void *pKey = sqlite3Malloc( pCur->nKey );
drh980b1a72006-08-16 16:42:48 +0000612 if( pKey ){
drhf49661a2008-12-10 16:45:50 +0000613 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
drh980b1a72006-08-16 16:42:48 +0000614 if( rc==SQLITE_OK ){
615 pCur->pKey = pKey;
616 }else{
drh17435752007-08-16 04:30:38 +0000617 sqlite3_free(pKey);
drh980b1a72006-08-16 16:42:48 +0000618 }
619 }else{
620 rc = SQLITE_NOMEM;
621 }
622 }
danielk197771d5d2c2008-09-29 11:49:47 +0000623 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
drh980b1a72006-08-16 16:42:48 +0000624
625 if( rc==SQLITE_OK ){
drh138eeeb2013-03-27 03:15:23 +0000626 btreeReleaseAllCursorPages(pCur);
drh980b1a72006-08-16 16:42:48 +0000627 pCur->eState = CURSOR_REQUIRESEEK;
628 }
629
danielk197792d4d7a2007-05-04 12:05:56 +0000630 invalidateOverflowCache(pCur);
drh980b1a72006-08-16 16:42:48 +0000631 return rc;
632}
633
drh637f3d82014-08-22 22:26:07 +0000634/* Forward reference */
635static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
636
drh980b1a72006-08-16 16:42:48 +0000637/*
drh0ee3dbe2009-10-16 15:05:18 +0000638** Save the positions of all cursors (except pExcept) that are open on
drh637f3d82014-08-22 22:26:07 +0000639** the table with root-page iRoot. "Saving the cursor position" means that
640** the location in the btree is remembered in such a way that it can be
641** moved back to the same spot after the btree has been modified. This
642** routine is called just before cursor pExcept is used to modify the
643** table, for example in BtreeDelete() or BtreeInsert().
644**
645** Implementation note: This routine merely checks to see if any cursors
646** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
647** event that cursors are in need to being saved.
drh980b1a72006-08-16 16:42:48 +0000648*/
649static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
drh3bdffdd2014-08-23 19:08:09 +0000650 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000651 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000652 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000653 for(p=pBt->pCursor; p; p=p->pNext){
drh637f3d82014-08-22 22:26:07 +0000654 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
655 }
656 return p ? saveCursorsOnList(p, iRoot, pExcept) : SQLITE_OK;
657}
658
659/* This helper routine to saveAllCursors does the actual work of saving
660** the cursors if and when a cursor is found that actually requires saving.
661** The common case is that no cursors need to be saved, so this routine is
662** broken out from its caller to avoid unnecessary stack pointer movement.
663*/
664static int SQLITE_NOINLINE saveCursorsOnList(
drh3f387402014-09-24 01:23:00 +0000665 BtCursor *p, /* The first cursor that needs saving */
666 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
667 BtCursor *pExcept /* Do not save this cursor */
drh637f3d82014-08-22 22:26:07 +0000668){
669 do{
drh138eeeb2013-03-27 03:15:23 +0000670 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
671 if( p->eState==CURSOR_VALID ){
672 int rc = saveCursorPosition(p);
673 if( SQLITE_OK!=rc ){
674 return rc;
675 }
676 }else{
677 testcase( p->iPage>0 );
678 btreeReleaseAllCursorPages(p);
drh980b1a72006-08-16 16:42:48 +0000679 }
680 }
drh637f3d82014-08-22 22:26:07 +0000681 p = p->pNext;
682 }while( p );
drh980b1a72006-08-16 16:42:48 +0000683 return SQLITE_OK;
684}
685
686/*
drhbf700f32007-03-31 02:36:44 +0000687** Clear the current cursor position.
688*/
danielk1977be51a652008-10-08 17:58:48 +0000689void sqlite3BtreeClearCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000690 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000691 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +0000692 pCur->pKey = 0;
693 pCur->eState = CURSOR_INVALID;
694}
695
696/*
danielk19773509a652009-07-06 18:56:13 +0000697** In this version of BtreeMoveto, pKey is a packed index record
698** such as is generated by the OP_MakeRecord opcode. Unpack the
699** record and then call BtreeMovetoUnpacked() to do the work.
700*/
701static int btreeMoveto(
702 BtCursor *pCur, /* Cursor open on the btree to be searched */
703 const void *pKey, /* Packed key if the btree is an index */
704 i64 nKey, /* Integer key for tables. Size of pKey for indices */
705 int bias, /* Bias search to the high end */
706 int *pRes /* Write search results here */
707){
708 int rc; /* Status code */
709 UnpackedRecord *pIdxKey; /* Unpacked index key */
drhb4139222013-11-06 14:36:08 +0000710 char aSpace[200]; /* Temp space for pIdxKey - to avoid a malloc */
dan03e9cfc2011-09-05 14:20:27 +0000711 char *pFree = 0;
danielk19773509a652009-07-06 18:56:13 +0000712
713 if( pKey ){
714 assert( nKey==(i64)(int)nKey );
dan03e9cfc2011-09-05 14:20:27 +0000715 pIdxKey = sqlite3VdbeAllocUnpackedRecord(
716 pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
717 );
danielk19773509a652009-07-06 18:56:13 +0000718 if( pIdxKey==0 ) return SQLITE_NOMEM;
mistachkin0fe5f952011-09-14 18:19:08 +0000719 sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
drh094b7582013-11-30 12:49:28 +0000720 if( pIdxKey->nField==0 ){
721 sqlite3DbFree(pCur->pKeyInfo->db, pFree);
722 return SQLITE_CORRUPT_BKPT;
723 }
danielk19773509a652009-07-06 18:56:13 +0000724 }else{
725 pIdxKey = 0;
726 }
727 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
dan42acb3e2011-09-05 20:16:38 +0000728 if( pFree ){
dan03e9cfc2011-09-05 14:20:27 +0000729 sqlite3DbFree(pCur->pKeyInfo->db, pFree);
danielk19773509a652009-07-06 18:56:13 +0000730 }
731 return rc;
732}
733
734/*
drh980b1a72006-08-16 16:42:48 +0000735** Restore the cursor to the position it was in (or as close to as possible)
736** when saveCursorPosition() was called. Note that this call deletes the
737** saved position info stored by saveCursorPosition(), so there can be
drha3460582008-07-11 21:02:53 +0000738** at most one effective restoreCursorPosition() call after each
drh980b1a72006-08-16 16:42:48 +0000739** saveCursorPosition().
drh980b1a72006-08-16 16:42:48 +0000740*/
danielk197730548662009-07-09 05:07:37 +0000741static int btreeRestoreCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000742 int rc;
drh1fee73e2007-08-29 04:00:57 +0000743 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +0000744 assert( pCur->eState>=CURSOR_REQUIRESEEK );
745 if( pCur->eState==CURSOR_FAULT ){
drh4c301aa2009-07-15 17:25:45 +0000746 return pCur->skipNext;
drhfb982642007-08-30 01:19:59 +0000747 }
drh980b1a72006-08-16 16:42:48 +0000748 pCur->eState = CURSOR_INVALID;
drh4c301aa2009-07-15 17:25:45 +0000749 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
drh980b1a72006-08-16 16:42:48 +0000750 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +0000751 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +0000752 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +0000753 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drh9b47ee32013-08-20 03:13:51 +0000754 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
755 pCur->eState = CURSOR_SKIPNEXT;
756 }
drh980b1a72006-08-16 16:42:48 +0000757 }
758 return rc;
759}
760
drha3460582008-07-11 21:02:53 +0000761#define restoreCursorPosition(p) \
drhfb982642007-08-30 01:19:59 +0000762 (p->eState>=CURSOR_REQUIRESEEK ? \
danielk197730548662009-07-09 05:07:37 +0000763 btreeRestoreCursorPosition(p) : \
drh16a9b832007-05-05 18:39:25 +0000764 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +0000765
drha3460582008-07-11 21:02:53 +0000766/*
drh6848dad2014-08-22 23:33:03 +0000767** Determine whether or not a cursor has moved from the position where
768** it was last placed, or has been invalidated for any other reason.
769** Cursors can move when the row they are pointing at is deleted out
770** from under them, for example. Cursor might also move if a btree
771** is rebalanced.
drha3460582008-07-11 21:02:53 +0000772**
drh6848dad2014-08-22 23:33:03 +0000773** Calling this routine with a NULL cursor pointer returns false.
drh86dd3712014-03-25 11:00:21 +0000774**
drh6848dad2014-08-22 23:33:03 +0000775** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
776** back to where it ought to be if this routine returns true.
drha3460582008-07-11 21:02:53 +0000777*/
drh6848dad2014-08-22 23:33:03 +0000778int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
drhc22284f2014-10-13 16:02:20 +0000779 return pCur->eState!=CURSOR_VALID;
drh6848dad2014-08-22 23:33:03 +0000780}
781
782/*
783** This routine restores a cursor back to its original position after it
784** has been moved by some outside activity (such as a btree rebalance or
785** a row having been deleted out from under the cursor).
786**
787** On success, the *pDifferentRow parameter is false if the cursor is left
788** pointing at exactly the same row. *pDifferntRow is the row the cursor
789** was pointing to has been deleted, forcing the cursor to point to some
790** nearby row.
791**
792** This routine should only be called for a cursor that just returned
793** TRUE from sqlite3BtreeCursorHasMoved().
794*/
795int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
drha3460582008-07-11 21:02:53 +0000796 int rc;
797
drh6848dad2014-08-22 23:33:03 +0000798 assert( pCur!=0 );
799 assert( pCur->eState!=CURSOR_VALID );
drha3460582008-07-11 21:02:53 +0000800 rc = restoreCursorPosition(pCur);
801 if( rc ){
drh6848dad2014-08-22 23:33:03 +0000802 *pDifferentRow = 1;
drha3460582008-07-11 21:02:53 +0000803 return rc;
804 }
drh9b47ee32013-08-20 03:13:51 +0000805 if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
drh6848dad2014-08-22 23:33:03 +0000806 *pDifferentRow = 1;
drha3460582008-07-11 21:02:53 +0000807 }else{
drh6848dad2014-08-22 23:33:03 +0000808 *pDifferentRow = 0;
drha3460582008-07-11 21:02:53 +0000809 }
810 return SQLITE_OK;
811}
812
danielk1977599fcba2004-11-08 07:13:13 +0000813#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000814/*
drha3152892007-05-05 11:48:52 +0000815** Given a page number of a regular database page, return the page
816** number for the pointer-map page that contains the entry for the
817** input page number.
drh5f77b2e2010-08-21 15:09:37 +0000818**
819** Return 0 (not a valid page) for pgno==1 since there is
820** no pointer map associated with page 1. The integrity_check logic
821** requires that ptrmapPageno(*,1)!=1.
danielk1977afcdd022004-10-31 16:25:42 +0000822*/
danielk1977266664d2006-02-10 08:24:21 +0000823static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
danielk197789d40042008-11-17 14:20:56 +0000824 int nPagesPerMapPage;
825 Pgno iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +0000826 assert( sqlite3_mutex_held(pBt->mutex) );
drh5f77b2e2010-08-21 15:09:37 +0000827 if( pgno<2 ) return 0;
drhd677b3d2007-08-20 22:48:41 +0000828 nPagesPerMapPage = (pBt->usableSize/5)+1;
829 iPtrMap = (pgno-2)/nPagesPerMapPage;
830 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +0000831 if( ret==PENDING_BYTE_PAGE(pBt) ){
832 ret++;
833 }
834 return ret;
835}
danielk1977a19df672004-11-03 11:37:07 +0000836
danielk1977afcdd022004-10-31 16:25:42 +0000837/*
danielk1977afcdd022004-10-31 16:25:42 +0000838** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000839**
840** This routine updates the pointer map entry for page number 'key'
841** so that it maps to type 'eType' and parent page number 'pgno'.
drh98add2e2009-07-20 17:11:49 +0000842**
843** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
844** a no-op. If an error occurs, the appropriate error code is written
845** into *pRC.
danielk1977afcdd022004-10-31 16:25:42 +0000846*/
drh98add2e2009-07-20 17:11:49 +0000847static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
danielk19773b8a05f2007-03-19 17:44:26 +0000848 DbPage *pDbPage; /* The pointer map page */
849 u8 *pPtrmap; /* The pointer map data */
850 Pgno iPtrmap; /* The pointer map page number */
851 int offset; /* Offset in pointer map page */
drh98add2e2009-07-20 17:11:49 +0000852 int rc; /* Return code from subfunctions */
853
854 if( *pRC ) return;
danielk1977afcdd022004-10-31 16:25:42 +0000855
drh1fee73e2007-08-29 04:00:57 +0000856 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977266664d2006-02-10 08:24:21 +0000857 /* The master-journal page number must never be used as a pointer map page */
858 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
859
danielk1977ac11ee62005-01-15 12:45:51 +0000860 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000861 if( key==0 ){
drh98add2e2009-07-20 17:11:49 +0000862 *pRC = SQLITE_CORRUPT_BKPT;
863 return;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000864 }
danielk1977266664d2006-02-10 08:24:21 +0000865 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000866 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977687566d2004-11-02 12:56:41 +0000867 if( rc!=SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +0000868 *pRC = rc;
869 return;
danielk1977afcdd022004-10-31 16:25:42 +0000870 }
danielk19778c666b12008-07-18 09:34:57 +0000871 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drhacfc72b2009-06-05 18:44:15 +0000872 if( offset<0 ){
drh98add2e2009-07-20 17:11:49 +0000873 *pRC = SQLITE_CORRUPT_BKPT;
drh4925a552009-07-07 11:39:58 +0000874 goto ptrmap_exit;
drhacfc72b2009-06-05 18:44:15 +0000875 }
drhfc243732011-05-17 15:21:56 +0000876 assert( offset <= (int)pBt->usableSize-5 );
danielk19773b8a05f2007-03-19 17:44:26 +0000877 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000878
drh615ae552005-01-16 23:21:00 +0000879 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
880 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
drh98add2e2009-07-20 17:11:49 +0000881 *pRC= rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000882 if( rc==SQLITE_OK ){
883 pPtrmap[offset] = eType;
884 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000885 }
danielk1977afcdd022004-10-31 16:25:42 +0000886 }
887
drh4925a552009-07-07 11:39:58 +0000888ptrmap_exit:
danielk19773b8a05f2007-03-19 17:44:26 +0000889 sqlite3PagerUnref(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000890}
891
892/*
893** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000894**
895** This routine retrieves the pointer map entry for page 'key', writing
896** the type and parent page number to *pEType and *pPgno respectively.
897** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000898*/
danielk1977aef0bf62005-12-30 16:28:01 +0000899static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000900 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000901 int iPtrmap; /* Pointer map page index */
902 u8 *pPtrmap; /* Pointer map page data */
903 int offset; /* Offset of entry in pointer map */
904 int rc;
905
drh1fee73e2007-08-29 04:00:57 +0000906 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000907
danielk1977266664d2006-02-10 08:24:21 +0000908 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000909 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000910 if( rc!=0 ){
911 return rc;
912 }
danielk19773b8a05f2007-03-19 17:44:26 +0000913 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000914
danielk19778c666b12008-07-18 09:34:57 +0000915 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drhfc243732011-05-17 15:21:56 +0000916 if( offset<0 ){
917 sqlite3PagerUnref(pDbPage);
918 return SQLITE_CORRUPT_BKPT;
919 }
920 assert( offset <= (int)pBt->usableSize-5 );
drh43617e92006-03-06 20:55:46 +0000921 assert( pEType!=0 );
922 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +0000923 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000924
danielk19773b8a05f2007-03-19 17:44:26 +0000925 sqlite3PagerUnref(pDbPage);
drh49285702005-09-17 15:20:26 +0000926 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000927 return SQLITE_OK;
928}
929
danielk197785d90ca2008-07-19 14:25:15 +0000930#else /* if defined SQLITE_OMIT_AUTOVACUUM */
drh98add2e2009-07-20 17:11:49 +0000931 #define ptrmapPut(w,x,y,z,rc)
danielk197785d90ca2008-07-19 14:25:15 +0000932 #define ptrmapGet(w,x,y,z) SQLITE_OK
drh98add2e2009-07-20 17:11:49 +0000933 #define ptrmapPutOvflPtr(x, y, rc)
danielk197785d90ca2008-07-19 14:25:15 +0000934#endif
danielk1977afcdd022004-10-31 16:25:42 +0000935
drh0d316a42002-08-11 20:10:47 +0000936/*
drh271efa52004-05-30 19:19:05 +0000937** Given a btree page and a cell index (0 means the first cell on
938** the page, 1 means the second cell, and so forth) return a pointer
939** to the cell content.
940**
941** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000942*/
drh1688c862008-07-18 02:44:17 +0000943#define findCell(P,I) \
drh3def2352011-11-11 00:27:15 +0000944 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
drh68f2a572011-06-03 17:50:49 +0000945#define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
946
drh43605152004-05-29 21:46:49 +0000947
948/*
drh93a960a2008-07-10 00:32:42 +0000949** This a more complex version of findCell() that works for
drh0a45c272009-07-08 01:49:11 +0000950** pages that do contain overflow cells.
drh43605152004-05-29 21:46:49 +0000951*/
952static u8 *findOverflowCell(MemPage *pPage, int iCell){
953 int i;
drh1fee73e2007-08-29 04:00:57 +0000954 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +0000955 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000956 int k;
drh2cbd78b2012-02-02 19:37:18 +0000957 k = pPage->aiOvfl[i];
drh6d08b4d2004-07-20 12:45:22 +0000958 if( k<=iCell ){
959 if( k==iCell ){
drh2cbd78b2012-02-02 19:37:18 +0000960 return pPage->apOvfl[i];
drh43605152004-05-29 21:46:49 +0000961 }
962 iCell--;
963 }
964 }
danielk19771cc5ed82007-05-16 17:28:43 +0000965 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000966}
967
968/*
969** Parse a cell content block and fill in the CellInfo structure. There
danielk197730548662009-07-09 05:07:37 +0000970** are two versions of this function. btreeParseCell() takes a
971** cell index as the second argument and btreeParseCellPtr()
drh16a9b832007-05-05 18:39:25 +0000972** takes a pointer to the body of the cell as its second argument.
drh43605152004-05-29 21:46:49 +0000973*/
danielk197730548662009-07-09 05:07:37 +0000974static void btreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000975 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000976 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000977 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000978){
drh3e28ff52014-09-24 00:59:08 +0000979 u8 *pIter; /* For scanning through pCell */
drh271efa52004-05-30 19:19:05 +0000980 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000981
drh1fee73e2007-08-29 04:00:57 +0000982 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhab01f612004-05-22 02:55:23 +0000983 assert( pPage->leaf==0 || pPage->leaf==1 );
drh3e28ff52014-09-24 00:59:08 +0000984 if( pPage->intKeyLeaf ){
985 assert( pPage->childPtrSize==0 );
986 pIter = pCell + getVarint32(pCell, nPayload);
drhab1cc582014-09-23 21:25:19 +0000987 pIter += getVarint(pIter, (u64*)&pInfo->nKey);
drh3e28ff52014-09-24 00:59:08 +0000988 }else if( pPage->noPayload ){
989 assert( pPage->childPtrSize==4 );
990 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
991 pInfo->nPayload = 0;
992 pInfo->nLocal = 0;
993 pInfo->iOverflow = 0;
994 pInfo->pPayload = 0;
995 return;
drh504b6982006-01-22 21:52:56 +0000996 }else{
drh3e28ff52014-09-24 00:59:08 +0000997 pIter = pCell + pPage->childPtrSize;
drhab1cc582014-09-23 21:25:19 +0000998 pIter += getVarint32(pIter, nPayload);
drh79df1f42008-07-18 00:57:33 +0000999 pInfo->nKey = nPayload;
drh6f11bef2004-05-13 01:12:56 +00001000 }
drh72365832007-03-06 15:53:44 +00001001 pInfo->nPayload = nPayload;
drhab1cc582014-09-23 21:25:19 +00001002 pInfo->pPayload = pIter;
drh0a45c272009-07-08 01:49:11 +00001003 testcase( nPayload==pPage->maxLocal );
1004 testcase( nPayload==pPage->maxLocal+1 );
drhab1cc582014-09-23 21:25:19 +00001005 if( nPayload<=pPage->maxLocal ){
drh271efa52004-05-30 19:19:05 +00001006 /* This is the (easy) common case where the entire payload fits
1007 ** on the local page. No overflow is required.
1008 */
drhab1cc582014-09-23 21:25:19 +00001009 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1010 if( pInfo->nSize<4 ) pInfo->nSize = 4;
drhf49661a2008-12-10 16:45:50 +00001011 pInfo->nLocal = (u16)nPayload;
drh6f11bef2004-05-13 01:12:56 +00001012 pInfo->iOverflow = 0;
drh6f11bef2004-05-13 01:12:56 +00001013 }else{
drh271efa52004-05-30 19:19:05 +00001014 /* If the payload will not fit completely on the local page, we have
1015 ** to decide how much to store locally and how much to spill onto
1016 ** overflow pages. The strategy is to minimize the amount of unused
1017 ** space on overflow pages while keeping the amount of local storage
1018 ** in between minLocal and maxLocal.
1019 **
1020 ** Warning: changing the way overflow payload is distributed in any
1021 ** way will result in an incompatible file format.
1022 */
1023 int minLocal; /* Minimum amount of payload held locally */
1024 int maxLocal; /* Maximum amount of payload held locally */
1025 int surplus; /* Overflow payload available for local storage */
1026
1027 minLocal = pPage->minLocal;
1028 maxLocal = pPage->maxLocal;
1029 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh0a45c272009-07-08 01:49:11 +00001030 testcase( surplus==maxLocal );
1031 testcase( surplus==maxLocal+1 );
drh6f11bef2004-05-13 01:12:56 +00001032 if( surplus <= maxLocal ){
drhf49661a2008-12-10 16:45:50 +00001033 pInfo->nLocal = (u16)surplus;
drh6f11bef2004-05-13 01:12:56 +00001034 }else{
drhf49661a2008-12-10 16:45:50 +00001035 pInfo->nLocal = (u16)minLocal;
drh6f11bef2004-05-13 01:12:56 +00001036 }
drhab1cc582014-09-23 21:25:19 +00001037 pInfo->iOverflow = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell);
drh6f11bef2004-05-13 01:12:56 +00001038 pInfo->nSize = pInfo->iOverflow + 4;
1039 }
drh3aac2dd2004-04-26 14:10:20 +00001040}
danielk197730548662009-07-09 05:07:37 +00001041static void btreeParseCell(
drh43605152004-05-29 21:46:49 +00001042 MemPage *pPage, /* Page containing the cell */
1043 int iCell, /* The cell index. First cell is 0 */
1044 CellInfo *pInfo /* Fill in this structure */
1045){
drhc4683832014-09-23 23:12:53 +00001046 btreeParseCellPtr(pPage, findCell(pPage, iCell), pInfo);
drh43605152004-05-29 21:46:49 +00001047}
drh3aac2dd2004-04-26 14:10:20 +00001048
1049/*
drh43605152004-05-29 21:46:49 +00001050** Compute the total number of bytes that a Cell needs in the cell
1051** data area of the btree-page. The return number includes the cell
1052** data header and the local payload, but not any overflow page or
1053** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +00001054*/
danielk1977ae5558b2009-04-29 11:31:47 +00001055static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
drh3f387402014-09-24 01:23:00 +00001056 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
1057 u8 *pEnd; /* End mark for a varint */
1058 u32 nSize; /* Size value to return */
danielk1977ae5558b2009-04-29 11:31:47 +00001059
1060#ifdef SQLITE_DEBUG
1061 /* The value returned by this function should always be the same as
1062 ** the (CellInfo.nSize) value found by doing a full parse of the
1063 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1064 ** this function verifies that this invariant is not violated. */
1065 CellInfo debuginfo;
danielk197730548662009-07-09 05:07:37 +00001066 btreeParseCellPtr(pPage, pCell, &debuginfo);
danielk1977ae5558b2009-04-29 11:31:47 +00001067#endif
1068
drh3e28ff52014-09-24 00:59:08 +00001069 if( pPage->noPayload ){
1070 pEnd = &pIter[9];
1071 while( (*pIter++)&0x80 && pIter<pEnd );
1072 assert( pPage->childPtrSize==4 );
1073 return (u16)(pIter - pCell);
drhdc41d602014-09-22 19:51:35 +00001074 }
drh3e28ff52014-09-24 00:59:08 +00001075 nSize = *pIter;
1076 if( nSize>=0x80 ){
1077 pEnd = &pIter[9];
1078 nSize &= 0x7f;
1079 do{
1080 nSize = (nSize<<7) | (*++pIter & 0x7f);
1081 }while( *(pIter)>=0x80 && pIter<pEnd );
1082 }
1083 pIter++;
drhdc41d602014-09-22 19:51:35 +00001084 if( pPage->intKey ){
danielk1977ae5558b2009-04-29 11:31:47 +00001085 /* pIter now points at the 64-bit integer key value, a variable length
1086 ** integer. The following block moves pIter to point at the first byte
1087 ** past the end of the key value. */
1088 pEnd = &pIter[9];
1089 while( (*pIter++)&0x80 && pIter<pEnd );
danielk1977ae5558b2009-04-29 11:31:47 +00001090 }
drh0a45c272009-07-08 01:49:11 +00001091 testcase( nSize==pPage->maxLocal );
1092 testcase( nSize==pPage->maxLocal+1 );
drh3e28ff52014-09-24 00:59:08 +00001093 if( nSize<=pPage->maxLocal ){
1094 nSize += (u32)(pIter - pCell);
1095 if( nSize<4 ) nSize = 4;
1096 }else{
danielk1977ae5558b2009-04-29 11:31:47 +00001097 int minLocal = pPage->minLocal;
1098 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
drh0a45c272009-07-08 01:49:11 +00001099 testcase( nSize==pPage->maxLocal );
1100 testcase( nSize==pPage->maxLocal+1 );
danielk1977ae5558b2009-04-29 11:31:47 +00001101 if( nSize>pPage->maxLocal ){
1102 nSize = minLocal;
1103 }
drh3e28ff52014-09-24 00:59:08 +00001104 nSize += 4 + (u16)(pIter - pCell);
danielk1977ae5558b2009-04-29 11:31:47 +00001105 }
drhdc41d602014-09-22 19:51:35 +00001106 assert( nSize==debuginfo.nSize || CORRUPT_DB );
shane60a4b532009-05-06 18:57:09 +00001107 return (u16)nSize;
danielk1977ae5558b2009-04-29 11:31:47 +00001108}
drh0ee3dbe2009-10-16 15:05:18 +00001109
1110#ifdef SQLITE_DEBUG
1111/* This variation on cellSizePtr() is used inside of assert() statements
1112** only. */
drha9121e42008-02-19 14:59:35 +00001113static u16 cellSize(MemPage *pPage, int iCell){
danielk1977ae5558b2009-04-29 11:31:47 +00001114 return cellSizePtr(pPage, findCell(pPage, iCell));
drh43605152004-05-29 21:46:49 +00001115}
danielk1977bc6ada42004-06-30 08:20:16 +00001116#endif
drh3b7511c2001-05-26 13:15:44 +00001117
danielk197779a40da2005-01-16 08:00:01 +00001118#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +00001119/*
danielk197726836652005-01-17 01:33:13 +00001120** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +00001121** to an overflow page, insert an entry into the pointer-map
1122** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +00001123*/
drh98add2e2009-07-20 17:11:49 +00001124static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
drhfa67c3c2008-07-11 02:21:40 +00001125 CellInfo info;
drh98add2e2009-07-20 17:11:49 +00001126 if( *pRC ) return;
drhfa67c3c2008-07-11 02:21:40 +00001127 assert( pCell!=0 );
danielk197730548662009-07-09 05:07:37 +00001128 btreeParseCellPtr(pPage, pCell, &info);
danielk19774dbaa892009-06-16 16:50:22 +00001129 if( info.iOverflow ){
drhfa67c3c2008-07-11 02:21:40 +00001130 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
drh98add2e2009-07-20 17:11:49 +00001131 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
danielk1977ac11ee62005-01-15 12:45:51 +00001132 }
danielk1977ac11ee62005-01-15 12:45:51 +00001133}
danielk197779a40da2005-01-16 08:00:01 +00001134#endif
1135
danielk1977ac11ee62005-01-15 12:45:51 +00001136
drhda200cc2004-05-09 11:51:38 +00001137/*
drh72f82862001-05-24 21:06:34 +00001138** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +00001139** end of the page and all free space is collected into one
1140** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +00001141** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +00001142*/
shane0af3f892008-11-12 04:55:34 +00001143static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +00001144 int i; /* Loop counter */
peter.d.reid60ec9142014-09-06 16:39:46 +00001145 int pc; /* Address of the i-th cell */
drh43605152004-05-29 21:46:49 +00001146 int hdr; /* Offset to the page header */
1147 int size; /* Size of a cell */
1148 int usableSize; /* Number of usable bytes on a page */
1149 int cellOffset; /* Offset to the cell pointer array */
drh281b21d2008-08-22 12:57:08 +00001150 int cbrk; /* Offset to the cell content area */
drh43605152004-05-29 21:46:49 +00001151 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +00001152 unsigned char *data; /* The page data */
1153 unsigned char *temp; /* Temp area for cell content */
drh588400b2014-09-27 05:00:25 +00001154 unsigned char *src; /* Source of content */
drh17146622009-07-07 17:38:38 +00001155 int iCellFirst; /* First allowable cell index */
1156 int iCellLast; /* Last possible cell index */
1157
drh2af926b2001-05-15 00:39:25 +00001158
danielk19773b8a05f2007-03-19 17:44:26 +00001159 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001160 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +00001161 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +00001162 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00001163 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh588400b2014-09-27 05:00:25 +00001164 temp = 0;
1165 src = data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +00001166 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001167 cellOffset = pPage->cellOffset;
1168 nCell = pPage->nCell;
1169 assert( nCell==get2byte(&data[hdr+3]) );
1170 usableSize = pPage->pBt->usableSize;
drh281b21d2008-08-22 12:57:08 +00001171 cbrk = usableSize;
drh17146622009-07-07 17:38:38 +00001172 iCellFirst = cellOffset + 2*nCell;
1173 iCellLast = usableSize - 4;
drh43605152004-05-29 21:46:49 +00001174 for(i=0; i<nCell; i++){
1175 u8 *pAddr; /* The i-th cell pointer */
1176 pAddr = &data[cellOffset + i*2];
1177 pc = get2byte(pAddr);
drh0a45c272009-07-08 01:49:11 +00001178 testcase( pc==iCellFirst );
1179 testcase( pc==iCellLast );
drh17146622009-07-07 17:38:38 +00001180#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
danielk197730548662009-07-09 05:07:37 +00001181 /* These conditions have already been verified in btreeInitPage()
drh17146622009-07-07 17:38:38 +00001182 ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
1183 */
1184 if( pc<iCellFirst || pc>iCellLast ){
shane0af3f892008-11-12 04:55:34 +00001185 return SQLITE_CORRUPT_BKPT;
1186 }
drh17146622009-07-07 17:38:38 +00001187#endif
1188 assert( pc>=iCellFirst && pc<=iCellLast );
drh588400b2014-09-27 05:00:25 +00001189 size = cellSizePtr(pPage, &src[pc]);
drh281b21d2008-08-22 12:57:08 +00001190 cbrk -= size;
drh17146622009-07-07 17:38:38 +00001191#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
1192 if( cbrk<iCellFirst ){
shane0af3f892008-11-12 04:55:34 +00001193 return SQLITE_CORRUPT_BKPT;
1194 }
drh17146622009-07-07 17:38:38 +00001195#else
1196 if( cbrk<iCellFirst || pc+size>usableSize ){
1197 return SQLITE_CORRUPT_BKPT;
1198 }
1199#endif
drh7157e1d2009-07-09 13:25:32 +00001200 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
drh0a45c272009-07-08 01:49:11 +00001201 testcase( cbrk+size==usableSize );
drh0a45c272009-07-08 01:49:11 +00001202 testcase( pc+size==usableSize );
drh281b21d2008-08-22 12:57:08 +00001203 put2byte(pAddr, cbrk);
drh588400b2014-09-27 05:00:25 +00001204 if( temp==0 ){
1205 int x;
1206 if( cbrk==pc ) continue;
1207 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1208 x = get2byte(&data[hdr+5]);
1209 memcpy(&temp[x], &data[x], (cbrk+size) - x);
1210 src = temp;
1211 }
1212 memcpy(&data[cbrk], &src[pc], size);
drh2af926b2001-05-15 00:39:25 +00001213 }
drh17146622009-07-07 17:38:38 +00001214 assert( cbrk>=iCellFirst );
drh281b21d2008-08-22 12:57:08 +00001215 put2byte(&data[hdr+5], cbrk);
drh43605152004-05-29 21:46:49 +00001216 data[hdr+1] = 0;
1217 data[hdr+2] = 0;
1218 data[hdr+7] = 0;
drh17146622009-07-07 17:38:38 +00001219 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
drhc5053fb2008-11-27 02:22:10 +00001220 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh17146622009-07-07 17:38:38 +00001221 if( cbrk-iCellFirst!=pPage->nFree ){
danielk1977360e6342008-11-12 08:49:51 +00001222 return SQLITE_CORRUPT_BKPT;
1223 }
shane0af3f892008-11-12 04:55:34 +00001224 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +00001225}
1226
drha059ad02001-04-17 20:09:11 +00001227/*
dan8e9ba0c2014-10-14 17:27:04 +00001228** Search the free-list on page pPg for space to store a cell nByte bytes in
1229** size. If one can be found, return a pointer to the space and remove it
1230** from the free-list.
1231**
1232** If no suitable space can be found on the free-list, return NULL.
1233**
1234** This function may detect corruption within pPg. If it does and argument
1235** pRc is non-NULL, then *pRc is set to SQLITE_CORRUPT and NULL is returned.
dane6593d82014-10-24 16:40:49 +00001236** Or, if corruption is detected and pRc is NULL, NULL is returned and the
dan8e9ba0c2014-10-14 17:27:04 +00001237** corruption goes unreported.
dan61e94c92014-10-27 08:02:16 +00001238**
1239** If a slot of at least nByte bytes is found but cannot be used because
1240** there are already at least 60 fragmented bytes on the page, return NULL.
1241** In this case, if pbDefrag parameter is not NULL, set *pbDefrag to true.
dan8e9ba0c2014-10-14 17:27:04 +00001242*/
dan61e94c92014-10-27 08:02:16 +00001243static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc, int *pbDefrag){
dan8e9ba0c2014-10-14 17:27:04 +00001244 const int hdr = pPg->hdrOffset;
1245 u8 * const aData = pPg->aData;
1246 int iAddr;
1247 int pc;
1248 int usableSize = pPg->pBt->usableSize;
1249
1250 for(iAddr=hdr+1; (pc = get2byte(&aData[iAddr]))>0; iAddr=pc){
1251 int size; /* Size of the free slot */
1252 if( pc>usableSize-4 || pc<iAddr+4 ){
1253 if( pRc ) *pRc = SQLITE_CORRUPT_BKPT;
1254 return 0;
1255 }
1256 size = get2byte(&aData[pc+2]);
1257 if( size>=nByte ){
1258 int x = size - nByte;
1259 testcase( x==4 );
1260 testcase( x==3 );
1261 if( x<4 ){
dan61e94c92014-10-27 08:02:16 +00001262 if( aData[hdr+7]>=60 ){
1263 if( pbDefrag ) *pbDefrag = 1;
1264 return 0;
1265 }
dan8e9ba0c2014-10-14 17:27:04 +00001266 /* Remove the slot from the free-list. Update the number of
1267 ** fragmented bytes within the page. */
1268 memcpy(&aData[iAddr], &aData[pc], 2);
1269 aData[hdr+7] += (u8)x;
1270 }else if( size+pc > usableSize ){
1271 if( pRc ) *pRc = SQLITE_CORRUPT_BKPT;
1272 return 0;
1273 }else{
1274 /* The slot remains on the free-list. Reduce its size to account
1275 ** for the portion used by the new allocation. */
1276 put2byte(&aData[pc+2], x);
1277 }
1278 return &aData[pc + x];
1279 }
1280 }
1281
1282 return 0;
1283}
1284
1285/*
danielk19776011a752009-04-01 16:25:32 +00001286** Allocate nByte bytes of space from within the B-Tree page passed
drh0a45c272009-07-08 01:49:11 +00001287** as the first argument. Write into *pIdx the index into pPage->aData[]
1288** of the first byte of allocated space. Return either SQLITE_OK or
1289** an error code (usually SQLITE_CORRUPT).
drhbd03cae2001-06-02 02:40:57 +00001290**
drh0a45c272009-07-08 01:49:11 +00001291** The caller guarantees that there is sufficient space to make the
1292** allocation. This routine might need to defragment in order to bring
1293** all the space together, however. This routine will avoid using
1294** the first two bytes past the cell pointer area since presumably this
1295** allocation is being made in order to insert a new cell, so we will
1296** also end up needing a new cell pointer.
drh7e3b0a02001-04-28 16:52:40 +00001297*/
drh0a45c272009-07-08 01:49:11 +00001298static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
danielk19776011a752009-04-01 16:25:32 +00001299 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1300 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
drh0a45c272009-07-08 01:49:11 +00001301 int top; /* First byte of cell content area */
1302 int gap; /* First byte of gap between cell pointers and cell content */
1303 int rc; /* Integer return code */
drh43605152004-05-29 21:46:49 +00001304
danielk19773b8a05f2007-03-19 17:44:26 +00001305 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001306 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +00001307 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa67c3c2008-07-11 02:21:40 +00001308 assert( nByte>=0 ); /* Minimum cell size is 4 */
1309 assert( pPage->nFree>=nByte );
1310 assert( pPage->nOverflow==0 );
mistachkina95d8ca2014-10-27 19:42:02 +00001311 assert( nByte < (int)(pPage->pBt->usableSize-8) );
drh43605152004-05-29 21:46:49 +00001312
drh0a45c272009-07-08 01:49:11 +00001313 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1314 gap = pPage->cellOffset + 2*pPage->nCell;
drh75b31dc2014-08-20 00:54:46 +00001315 assert( gap<=65536 );
1316 top = get2byte(&data[hdr+5]);
1317 if( gap>top ){
1318 if( top==0 ){
1319 top = 65536;
1320 }else{
1321 return SQLITE_CORRUPT_BKPT;
1322 }
1323 }
drh4c04f3c2014-08-20 11:56:14 +00001324
1325 /* If there is enough space between gap and top for one more cell pointer
1326 ** array entry offset, and if the freelist is not empty, then search the
1327 ** freelist looking for a free slot big enough to satisfy the request.
1328 */
drh0a45c272009-07-08 01:49:11 +00001329 testcase( gap+2==top );
1330 testcase( gap+1==top );
1331 testcase( gap==top );
drh4c04f3c2014-08-20 11:56:14 +00001332 if( gap+2<=top && (data[hdr+1] || data[hdr+2]) ){
dan8e9ba0c2014-10-14 17:27:04 +00001333 int rc = SQLITE_OK;
dan61e94c92014-10-27 08:02:16 +00001334 int bDefrag = 0;
1335 u8 *pSpace = pageFindSlot(pPage, nByte, &rc, &bDefrag);
dan8e9ba0c2014-10-14 17:27:04 +00001336 if( rc ) return rc;
dan61e94c92014-10-27 08:02:16 +00001337 if( bDefrag ) goto defragment_page;
dan8e9ba0c2014-10-14 17:27:04 +00001338 if( pSpace ){
1339 *pIdx = pSpace - data;
1340 return SQLITE_OK;
drh9e572e62004-04-23 23:43:10 +00001341 }
1342 }
drh43605152004-05-29 21:46:49 +00001343
drh4c04f3c2014-08-20 11:56:14 +00001344 /* The request could not be fulfilled using a freelist slot. Check
1345 ** to see if defragmentation is necessary.
drh0a45c272009-07-08 01:49:11 +00001346 */
1347 testcase( gap+2+nByte==top );
1348 if( gap+2+nByte>top ){
dan61e94c92014-10-27 08:02:16 +00001349 defragment_page:
drh90555262014-08-20 13:17:43 +00001350 testcase( pPage->nCell==0 );
drh0a45c272009-07-08 01:49:11 +00001351 rc = defragmentPage(pPage);
1352 if( rc ) return rc;
drh5d433ce2010-08-14 16:02:52 +00001353 top = get2byteNotZero(&data[hdr+5]);
drh0a45c272009-07-08 01:49:11 +00001354 assert( gap+nByte<=top );
1355 }
1356
1357
drh43605152004-05-29 21:46:49 +00001358 /* Allocate memory from the gap in between the cell pointer array
drhc314dc72009-07-21 11:52:34 +00001359 ** and the cell content area. The btreeInitPage() call has already
1360 ** validated the freelist. Given that the freelist is valid, there
1361 ** is no way that the allocation can extend off the end of the page.
1362 ** The assert() below verifies the previous sentence.
drh43605152004-05-29 21:46:49 +00001363 */
drh0a45c272009-07-08 01:49:11 +00001364 top -= nByte;
drh43605152004-05-29 21:46:49 +00001365 put2byte(&data[hdr+5], top);
drhfcd71b62011-04-05 22:08:24 +00001366 assert( top+nByte <= (int)pPage->pBt->usableSize );
drh0a45c272009-07-08 01:49:11 +00001367 *pIdx = top;
1368 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001369}
1370
1371/*
drh9e572e62004-04-23 23:43:10 +00001372** Return a section of the pPage->aData to the freelist.
drh7fb91642014-08-20 14:37:09 +00001373** The first byte of the new free block is pPage->aData[iStart]
1374** and the size of the block is iSize bytes.
drh306dc212001-05-21 13:45:10 +00001375**
drh5f5c7532014-08-20 17:56:27 +00001376** Adjacent freeblocks are coalesced.
1377**
1378** Note that even though the freeblock list was checked by btreeInitPage(),
1379** that routine will not detect overlap between cells or freeblocks. Nor
1380** does it detect cells or freeblocks that encrouch into the reserved bytes
1381** at the end of the page. So do additional corruption checks inside this
1382** routine and return SQLITE_CORRUPT if any problems are found.
drh7e3b0a02001-04-28 16:52:40 +00001383*/
drh5f5c7532014-08-20 17:56:27 +00001384static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
drh3f387402014-09-24 01:23:00 +00001385 u16 iPtr; /* Address of ptr to next freeblock */
drh5f5c7532014-08-20 17:56:27 +00001386 u16 iFreeBlk; /* Address of the next freeblock */
1387 u8 hdr; /* Page header size. 0 or 100 */
1388 u8 nFrag = 0; /* Reduction in fragmentation */
1389 u16 iOrigSize = iSize; /* Original value of iSize */
1390 u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
1391 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
drh7fb91642014-08-20 14:37:09 +00001392 unsigned char *data = pPage->aData; /* Page content */
drh2af926b2001-05-15 00:39:25 +00001393
drh9e572e62004-04-23 23:43:10 +00001394 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001395 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh7fb91642014-08-20 14:37:09 +00001396 assert( iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
dan23eba452014-10-24 18:43:57 +00001397 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +00001398 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh7fb91642014-08-20 14:37:09 +00001399 assert( iSize>=4 ); /* Minimum cell size is 4 */
drh5f5c7532014-08-20 17:56:27 +00001400 assert( iStart<=iLast );
drh9e572e62004-04-23 23:43:10 +00001401
drh5f5c7532014-08-20 17:56:27 +00001402 /* Overwrite deleted information with zeros when the secure_delete
1403 ** option is enabled */
drhc9166342012-01-05 23:32:06 +00001404 if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
drh7fb91642014-08-20 14:37:09 +00001405 memset(&data[iStart], 0, iSize);
drh5b47efa2010-02-12 18:18:39 +00001406 }
drhfcce93f2006-02-22 03:08:32 +00001407
drh5f5c7532014-08-20 17:56:27 +00001408 /* The list of freeblocks must be in ascending order. Find the
1409 ** spot on the list where iStart should be inserted.
drh0a45c272009-07-08 01:49:11 +00001410 */
drh43605152004-05-29 21:46:49 +00001411 hdr = pPage->hdrOffset;
drh7fb91642014-08-20 14:37:09 +00001412 iPtr = hdr + 1;
drh7bc4c452014-08-20 18:43:44 +00001413 if( data[iPtr+1]==0 && data[iPtr]==0 ){
1414 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
1415 }else{
1416 while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
1417 if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
1418 iPtr = iFreeBlk;
drh9e572e62004-04-23 23:43:10 +00001419 }
drh7bc4c452014-08-20 18:43:44 +00001420 if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
1421 assert( iFreeBlk>iPtr || iFreeBlk==0 );
1422
1423 /* At this point:
1424 ** iFreeBlk: First freeblock after iStart, or zero if none
1425 ** iPtr: The address of a pointer iFreeBlk
1426 **
1427 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
1428 */
1429 if( iFreeBlk && iEnd+3>=iFreeBlk ){
1430 nFrag = iFreeBlk - iEnd;
1431 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
1432 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
1433 iSize = iEnd - iStart;
1434 iFreeBlk = get2byte(&data[iFreeBlk]);
1435 }
1436
drh3f387402014-09-24 01:23:00 +00001437 /* If iPtr is another freeblock (that is, if iPtr is not the freelist
1438 ** pointer in the page header) then check to see if iStart should be
1439 ** coalesced onto the end of iPtr.
drh7bc4c452014-08-20 18:43:44 +00001440 */
1441 if( iPtr>hdr+1 ){
1442 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
1443 if( iPtrEnd+3>=iStart ){
1444 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
1445 nFrag += iStart - iPtrEnd;
1446 iSize = iEnd - iPtr;
1447 iStart = iPtr;
1448 }
1449 }
1450 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
1451 data[hdr+7] -= nFrag;
drh9e572e62004-04-23 23:43:10 +00001452 }
drh7bc4c452014-08-20 18:43:44 +00001453 if( iStart==get2byte(&data[hdr+5]) ){
drh5f5c7532014-08-20 17:56:27 +00001454 /* The new freeblock is at the beginning of the cell content area,
1455 ** so just extend the cell content area rather than create another
1456 ** freelist entry */
drh7bc4c452014-08-20 18:43:44 +00001457 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
drh5f5c7532014-08-20 17:56:27 +00001458 put2byte(&data[hdr+1], iFreeBlk);
1459 put2byte(&data[hdr+5], iEnd);
1460 }else{
1461 /* Insert the new freeblock into the freelist */
1462 put2byte(&data[iPtr], iStart);
1463 put2byte(&data[iStart], iFreeBlk);
1464 put2byte(&data[iStart+2], iSize);
drh4b70f112004-05-02 21:12:19 +00001465 }
drh5f5c7532014-08-20 17:56:27 +00001466 pPage->nFree += iOrigSize;
shanedcc50b72008-11-13 18:29:50 +00001467 return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00001468}
1469
1470/*
drh271efa52004-05-30 19:19:05 +00001471** Decode the flags byte (the first byte of the header) for a page
1472** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +00001473**
1474** Only the following combinations are supported. Anything different
1475** indicates a corrupt database files:
1476**
1477** PTF_ZERODATA
1478** PTF_ZERODATA | PTF_LEAF
1479** PTF_LEAFDATA | PTF_INTKEY
1480** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
drh271efa52004-05-30 19:19:05 +00001481*/
drh44845222008-07-17 18:39:57 +00001482static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +00001483 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +00001484
1485 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +00001486 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00001487 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
drh44845222008-07-17 18:39:57 +00001488 flagByte &= ~PTF_LEAF;
1489 pPage->childPtrSize = 4-4*pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001490 pBt = pPage->pBt;
drh44845222008-07-17 18:39:57 +00001491 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
1492 pPage->intKey = 1;
drh3e28ff52014-09-24 00:59:08 +00001493 pPage->intKeyLeaf = pPage->leaf;
1494 pPage->noPayload = !pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001495 pPage->maxLocal = pBt->maxLeaf;
1496 pPage->minLocal = pBt->minLeaf;
drh44845222008-07-17 18:39:57 +00001497 }else if( flagByte==PTF_ZERODATA ){
1498 pPage->intKey = 0;
drh3e28ff52014-09-24 00:59:08 +00001499 pPage->intKeyLeaf = 0;
1500 pPage->noPayload = 0;
drh271efa52004-05-30 19:19:05 +00001501 pPage->maxLocal = pBt->maxLocal;
1502 pPage->minLocal = pBt->minLocal;
drh44845222008-07-17 18:39:57 +00001503 }else{
1504 return SQLITE_CORRUPT_BKPT;
drh271efa52004-05-30 19:19:05 +00001505 }
drhc9166342012-01-05 23:32:06 +00001506 pPage->max1bytePayload = pBt->max1bytePayload;
drh44845222008-07-17 18:39:57 +00001507 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +00001508}
1509
1510/*
drh7e3b0a02001-04-28 16:52:40 +00001511** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001512**
1513** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001514** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001515** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1516** guarantee that the page is well-formed. It only shows that
1517** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001518*/
danielk197730548662009-07-09 05:07:37 +00001519static int btreeInitPage(MemPage *pPage){
drh2af926b2001-05-15 00:39:25 +00001520
danielk197771d5d2c2008-09-29 11:49:47 +00001521 assert( pPage->pBt!=0 );
1522 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001523 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +00001524 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1525 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00001526
1527 if( !pPage->isInit ){
drhf49661a2008-12-10 16:45:50 +00001528 u16 pc; /* Address of a freeblock within pPage->aData[] */
1529 u8 hdr; /* Offset to beginning of page header */
danielk197771d5d2c2008-09-29 11:49:47 +00001530 u8 *data; /* Equal to pPage->aData */
1531 BtShared *pBt; /* The main btree structure */
drhb2eced52010-08-12 02:41:12 +00001532 int usableSize; /* Amount of usable space on each page */
shaneh1df2db72010-08-18 02:28:48 +00001533 u16 cellOffset; /* Offset from start of page to first cell pointer */
drhb2eced52010-08-12 02:41:12 +00001534 int nFree; /* Number of unused bytes on the page */
1535 int top; /* First byte of the cell content area */
drh0a45c272009-07-08 01:49:11 +00001536 int iCellFirst; /* First allowable cell or freeblock offset */
1537 int iCellLast; /* Last possible cell or freeblock offset */
danielk197771d5d2c2008-09-29 11:49:47 +00001538
1539 pBt = pPage->pBt;
1540
danielk1977eaa06f62008-09-18 17:34:44 +00001541 hdr = pPage->hdrOffset;
1542 data = pPage->aData;
1543 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
drhb2eced52010-08-12 02:41:12 +00001544 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
1545 pPage->maskPage = (u16)(pBt->pageSize - 1);
danielk1977eaa06f62008-09-18 17:34:44 +00001546 pPage->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00001547 usableSize = pBt->usableSize;
1548 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
drh3def2352011-11-11 00:27:15 +00001549 pPage->aDataEnd = &data[usableSize];
1550 pPage->aCellIdx = &data[cellOffset];
drh5d433ce2010-08-14 16:02:52 +00001551 top = get2byteNotZero(&data[hdr+5]);
danielk1977eaa06f62008-09-18 17:34:44 +00001552 pPage->nCell = get2byte(&data[hdr+3]);
1553 if( pPage->nCell>MX_CELL(pBt) ){
1554 /* To many cells for a single page. The page must be corrupt */
1555 return SQLITE_CORRUPT_BKPT;
1556 }
drhb908d762009-07-08 16:54:40 +00001557 testcase( pPage->nCell==MX_CELL(pBt) );
drh69e931e2009-06-03 21:04:35 +00001558
shane5eff7cf2009-08-10 03:57:58 +00001559 /* A malformed database page might cause us to read past the end
drh69e931e2009-06-03 21:04:35 +00001560 ** of page when parsing a cell.
1561 **
1562 ** The following block of code checks early to see if a cell extends
1563 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
1564 ** returned if it does.
1565 */
drh0a45c272009-07-08 01:49:11 +00001566 iCellFirst = cellOffset + 2*pPage->nCell;
1567 iCellLast = usableSize - 4;
drh3b2a3fa2009-06-09 13:42:24 +00001568#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
drh69e931e2009-06-03 21:04:35 +00001569 {
drh69e931e2009-06-03 21:04:35 +00001570 int i; /* Index into the cell pointer array */
1571 int sz; /* Size of a cell */
1572
drh69e931e2009-06-03 21:04:35 +00001573 if( !pPage->leaf ) iCellLast--;
1574 for(i=0; i<pPage->nCell; i++){
1575 pc = get2byte(&data[cellOffset+i*2]);
drh0a45c272009-07-08 01:49:11 +00001576 testcase( pc==iCellFirst );
1577 testcase( pc==iCellLast );
drh69e931e2009-06-03 21:04:35 +00001578 if( pc<iCellFirst || pc>iCellLast ){
1579 return SQLITE_CORRUPT_BKPT;
1580 }
1581 sz = cellSizePtr(pPage, &data[pc]);
drh0a45c272009-07-08 01:49:11 +00001582 testcase( pc+sz==usableSize );
drh69e931e2009-06-03 21:04:35 +00001583 if( pc+sz>usableSize ){
1584 return SQLITE_CORRUPT_BKPT;
1585 }
1586 }
drh0a45c272009-07-08 01:49:11 +00001587 if( !pPage->leaf ) iCellLast++;
drh69e931e2009-06-03 21:04:35 +00001588 }
1589#endif
1590
danielk1977eaa06f62008-09-18 17:34:44 +00001591 /* Compute the total free space on the page */
1592 pc = get2byte(&data[hdr+1]);
danielk197793c829c2009-06-03 17:26:17 +00001593 nFree = data[hdr+7] + top;
danielk1977eaa06f62008-09-18 17:34:44 +00001594 while( pc>0 ){
drh1bd10f82008-12-10 21:19:56 +00001595 u16 next, size;
drh0a45c272009-07-08 01:49:11 +00001596 if( pc<iCellFirst || pc>iCellLast ){
dan4361e792009-08-14 17:01:22 +00001597 /* Start of free block is off the page */
danielk1977eaa06f62008-09-18 17:34:44 +00001598 return SQLITE_CORRUPT_BKPT;
1599 }
1600 next = get2byte(&data[pc]);
1601 size = get2byte(&data[pc+2]);
dan4361e792009-08-14 17:01:22 +00001602 if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
1603 /* Free blocks must be in ascending order. And the last byte of
drhf2f105d2012-08-20 15:53:54 +00001604 ** the free-block must lie on the database page. */
danielk1977eaa06f62008-09-18 17:34:44 +00001605 return SQLITE_CORRUPT_BKPT;
1606 }
shane85095702009-06-15 16:27:08 +00001607 nFree = nFree + size;
danielk1977eaa06f62008-09-18 17:34:44 +00001608 pc = next;
1609 }
danielk197793c829c2009-06-03 17:26:17 +00001610
1611 /* At this point, nFree contains the sum of the offset to the start
1612 ** of the cell-content area plus the number of free bytes within
1613 ** the cell-content area. If this is greater than the usable-size
1614 ** of the page, then the page must be corrupted. This check also
1615 ** serves to verify that the offset to the start of the cell-content
1616 ** area, according to the page header, lies within the page.
1617 */
1618 if( nFree>usableSize ){
drh49285702005-09-17 15:20:26 +00001619 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001620 }
shane5eff7cf2009-08-10 03:57:58 +00001621 pPage->nFree = (u16)(nFree - iCellFirst);
danielk197771d5d2c2008-09-29 11:49:47 +00001622 pPage->isInit = 1;
1623 }
drh9e572e62004-04-23 23:43:10 +00001624 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001625}
1626
1627/*
drh8b2f49b2001-06-08 00:21:52 +00001628** Set up a raw page so that it looks like a database page holding
1629** no entries.
drhbd03cae2001-06-02 02:40:57 +00001630*/
drh9e572e62004-04-23 23:43:10 +00001631static void zeroPage(MemPage *pPage, int flags){
1632 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001633 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00001634 u8 hdr = pPage->hdrOffset;
1635 u16 first;
drh9e572e62004-04-23 23:43:10 +00001636
danielk19773b8a05f2007-03-19 17:44:26 +00001637 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +00001638 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1639 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00001640 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00001641 assert( sqlite3_mutex_held(pBt->mutex) );
drhc9166342012-01-05 23:32:06 +00001642 if( pBt->btsFlags & BTS_SECURE_DELETE ){
drh5b47efa2010-02-12 18:18:39 +00001643 memset(&data[hdr], 0, pBt->usableSize - hdr);
1644 }
drh1bd10f82008-12-10 21:19:56 +00001645 data[hdr] = (char)flags;
drhfe485992014-02-12 23:52:16 +00001646 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
drh43605152004-05-29 21:46:49 +00001647 memset(&data[hdr+1], 0, 4);
1648 data[hdr+7] = 0;
1649 put2byte(&data[hdr+5], pBt->usableSize);
shaneh1df2db72010-08-18 02:28:48 +00001650 pPage->nFree = (u16)(pBt->usableSize - first);
drh271efa52004-05-30 19:19:05 +00001651 decodeFlags(pPage, flags);
drh43605152004-05-29 21:46:49 +00001652 pPage->cellOffset = first;
drh3def2352011-11-11 00:27:15 +00001653 pPage->aDataEnd = &data[pBt->usableSize];
1654 pPage->aCellIdx = &data[first];
drh43605152004-05-29 21:46:49 +00001655 pPage->nOverflow = 0;
drhb2eced52010-08-12 02:41:12 +00001656 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
1657 pPage->maskPage = (u16)(pBt->pageSize - 1);
drh43605152004-05-29 21:46:49 +00001658 pPage->nCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001659 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00001660}
1661
drh897a8202008-09-18 01:08:15 +00001662
1663/*
1664** Convert a DbPage obtained from the pager into a MemPage used by
1665** the btree layer.
1666*/
1667static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
1668 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
1669 pPage->aData = sqlite3PagerGetData(pDbPage);
1670 pPage->pDbPage = pDbPage;
1671 pPage->pBt = pBt;
1672 pPage->pgno = pgno;
1673 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
1674 return pPage;
1675}
1676
drhbd03cae2001-06-02 02:40:57 +00001677/*
drh3aac2dd2004-04-26 14:10:20 +00001678** Get a page from the pager. Initialize the MemPage.pBt and
1679** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +00001680**
1681** If the noContent flag is set, it means that we do not care about
1682** the content of the page at this time. So do not go to the disk
1683** to fetch the content. Just fill in the content with zeros for now.
1684** If in the future we call sqlite3PagerWrite() on this page, that
1685** means we have started to be concerned about content and the disk
1686** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00001687*/
danielk197730548662009-07-09 05:07:37 +00001688static int btreeGetPage(
drh16a9b832007-05-05 18:39:25 +00001689 BtShared *pBt, /* The btree */
1690 Pgno pgno, /* Number of the page to fetch */
1691 MemPage **ppPage, /* Return the page in this parameter */
drhb00fc3b2013-08-21 23:42:32 +00001692 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
drh16a9b832007-05-05 18:39:25 +00001693){
drh3aac2dd2004-04-26 14:10:20 +00001694 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001695 DbPage *pDbPage;
1696
drhb00fc3b2013-08-21 23:42:32 +00001697 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
drh1fee73e2007-08-29 04:00:57 +00001698 assert( sqlite3_mutex_held(pBt->mutex) );
dan11dcd112013-03-15 18:29:18 +00001699 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
drh3aac2dd2004-04-26 14:10:20 +00001700 if( rc ) return rc;
drh897a8202008-09-18 01:08:15 +00001701 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
drh3aac2dd2004-04-26 14:10:20 +00001702 return SQLITE_OK;
1703}
1704
1705/*
danielk1977bea2a942009-01-20 17:06:27 +00001706** Retrieve a page from the pager cache. If the requested page is not
1707** already in the pager cache return NULL. Initialize the MemPage.pBt and
1708** MemPage.aData elements if needed.
1709*/
1710static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
1711 DbPage *pDbPage;
1712 assert( sqlite3_mutex_held(pBt->mutex) );
1713 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
1714 if( pDbPage ){
1715 return btreePageFromDbPage(pDbPage, pgno, pBt);
1716 }
1717 return 0;
1718}
1719
1720/*
danielk197789d40042008-11-17 14:20:56 +00001721** Return the size of the database file in pages. If there is any kind of
1722** error, return ((unsigned int)-1).
danielk197767fd7a92008-09-10 17:53:35 +00001723*/
drhb1299152010-03-30 22:58:33 +00001724static Pgno btreePagecount(BtShared *pBt){
1725 return pBt->nPage;
1726}
1727u32 sqlite3BtreeLastPage(Btree *p){
1728 assert( sqlite3BtreeHoldsMutex(p) );
1729 assert( ((p->pBt->nPage)&0x8000000)==0 );
drheac5bd72014-07-25 21:35:39 +00001730 return btreePagecount(p->pBt);
danielk197767fd7a92008-09-10 17:53:35 +00001731}
1732
1733/*
danielk197789bc4bc2009-07-21 19:25:24 +00001734** Get a page from the pager and initialize it. This routine is just a
1735** convenience wrapper around separate calls to btreeGetPage() and
1736** btreeInitPage().
1737**
1738** If an error occurs, then the value *ppPage is set to is undefined. It
1739** may remain unchanged, or it may be set to an invalid value.
drhde647132004-05-07 17:57:49 +00001740*/
1741static int getAndInitPage(
dan11dcd112013-03-15 18:29:18 +00001742 BtShared *pBt, /* The database file */
1743 Pgno pgno, /* Number of the page to get */
1744 MemPage **ppPage, /* Write the page pointer here */
drhb00fc3b2013-08-21 23:42:32 +00001745 int bReadonly /* PAGER_GET_READONLY or 0 */
drhde647132004-05-07 17:57:49 +00001746){
1747 int rc;
drh1fee73e2007-08-29 04:00:57 +00001748 assert( sqlite3_mutex_held(pBt->mutex) );
drhb00fc3b2013-08-21 23:42:32 +00001749 assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
danielk197789bc4bc2009-07-21 19:25:24 +00001750
danba3cbf32010-06-30 04:29:03 +00001751 if( pgno>btreePagecount(pBt) ){
1752 rc = SQLITE_CORRUPT_BKPT;
1753 }else{
drhb00fc3b2013-08-21 23:42:32 +00001754 rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
drh29f2bad2013-12-09 01:04:54 +00001755 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
danba3cbf32010-06-30 04:29:03 +00001756 rc = btreeInitPage(*ppPage);
1757 if( rc!=SQLITE_OK ){
1758 releasePage(*ppPage);
1759 }
danielk197789bc4bc2009-07-21 19:25:24 +00001760 }
drhee696e22004-08-30 16:52:17 +00001761 }
danba3cbf32010-06-30 04:29:03 +00001762
1763 testcase( pgno==0 );
1764 assert( pgno!=0 || rc==SQLITE_CORRUPT );
drhde647132004-05-07 17:57:49 +00001765 return rc;
1766}
1767
1768/*
drh3aac2dd2004-04-26 14:10:20 +00001769** Release a MemPage. This should be called once for each prior
danielk197730548662009-07-09 05:07:37 +00001770** call to btreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00001771*/
drh4b70f112004-05-02 21:12:19 +00001772static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001773 if( pPage ){
1774 assert( pPage->aData );
1775 assert( pPage->pBt );
drhda8a3302013-12-13 19:35:21 +00001776 assert( pPage->pDbPage!=0 );
drhbf4bca52007-09-06 22:19:14 +00001777 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1778 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
drh1fee73e2007-08-29 04:00:57 +00001779 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda8a3302013-12-13 19:35:21 +00001780 sqlite3PagerUnrefNotNull(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00001781 }
1782}
1783
1784/*
drha6abd042004-06-09 17:37:22 +00001785** During a rollback, when the pager reloads information into the cache
1786** so that the cache is restored to its original state at the start of
1787** the transaction, for each page restored this routine is called.
1788**
1789** This routine needs to reset the extra data section at the end of the
1790** page to agree with the restored data.
1791*/
danielk1977eaa06f62008-09-18 17:34:44 +00001792static void pageReinit(DbPage *pData){
drh07d183d2005-05-01 22:52:42 +00001793 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00001794 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
danielk1977d217e6f2009-04-01 17:13:51 +00001795 assert( sqlite3PagerPageRefcount(pData)>0 );
danielk197771d5d2c2008-09-29 11:49:47 +00001796 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00001797 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00001798 pPage->isInit = 0;
danielk1977d217e6f2009-04-01 17:13:51 +00001799 if( sqlite3PagerPageRefcount(pData)>1 ){
drh5e8d8872009-03-30 17:19:48 +00001800 /* pPage might not be a btree page; it might be an overflow page
1801 ** or ptrmap page or a free page. In those cases, the following
danielk197730548662009-07-09 05:07:37 +00001802 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
drh5e8d8872009-03-30 17:19:48 +00001803 ** But no harm is done by this. And it is very important that
danielk197730548662009-07-09 05:07:37 +00001804 ** btreeInitPage() be called on every btree page so we make
drh5e8d8872009-03-30 17:19:48 +00001805 ** the call for every page that comes in for re-initing. */
danielk197730548662009-07-09 05:07:37 +00001806 btreeInitPage(pPage);
danielk197771d5d2c2008-09-29 11:49:47 +00001807 }
drha6abd042004-06-09 17:37:22 +00001808 }
1809}
1810
1811/*
drhe5fe6902007-12-07 18:55:28 +00001812** Invoke the busy handler for a btree.
1813*/
danielk19771ceedd32008-11-19 10:22:33 +00001814static int btreeInvokeBusyHandler(void *pArg){
drhe5fe6902007-12-07 18:55:28 +00001815 BtShared *pBt = (BtShared*)pArg;
1816 assert( pBt->db );
1817 assert( sqlite3_mutex_held(pBt->db->mutex) );
1818 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
1819}
1820
1821/*
drhad3e0102004-09-03 23:32:18 +00001822** Open a database file.
1823**
drh382c0242001-10-06 16:33:02 +00001824** zFilename is the name of the database file. If zFilename is NULL
drh75c014c2010-08-30 15:02:28 +00001825** then an ephemeral database is created. The ephemeral database might
1826** be exclusively in memory, or it might use a disk-based memory cache.
1827** Either way, the ephemeral database will be automatically deleted
1828** when sqlite3BtreeClose() is called.
1829**
drhe53831d2007-08-17 01:14:38 +00001830** If zFilename is ":memory:" then an in-memory database is created
1831** that is automatically destroyed when it is closed.
drhc47fd8e2009-04-30 13:30:32 +00001832**
drh33f111d2012-01-17 15:29:14 +00001833** The "flags" parameter is a bitmask that might contain bits like
1834** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
drh75c014c2010-08-30 15:02:28 +00001835**
drhc47fd8e2009-04-30 13:30:32 +00001836** If the database is already opened in the same database connection
1837** and we are in shared cache mode, then the open will fail with an
1838** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
1839** objects in the same database connection since doing so will lead
1840** to problems with locking.
drha059ad02001-04-17 20:09:11 +00001841*/
drh23e11ca2004-05-04 17:27:28 +00001842int sqlite3BtreeOpen(
dan3a6d8ae2011-04-23 15:54:54 +00001843 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
drh3aac2dd2004-04-26 14:10:20 +00001844 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00001845 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001846 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00001847 int flags, /* Options */
1848 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00001849){
drh7555d8e2009-03-20 13:15:30 +00001850 BtShared *pBt = 0; /* Shared part of btree structure */
1851 Btree *p; /* Handle to return */
1852 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
1853 int rc = SQLITE_OK; /* Result code from this function */
1854 u8 nReserve; /* Byte of unused space on each page */
1855 unsigned char zDbHeader[100]; /* Database header content */
danielk1977aef0bf62005-12-30 16:28:01 +00001856
drh75c014c2010-08-30 15:02:28 +00001857 /* True if opening an ephemeral, temporary database */
1858 const int isTempDb = zFilename==0 || zFilename[0]==0;
1859
danielk1977aef0bf62005-12-30 16:28:01 +00001860 /* Set the variable isMemdb to true for an in-memory database, or
drhb0a7c9c2010-12-06 21:09:59 +00001861 ** false for a file-based database.
danielk1977aef0bf62005-12-30 16:28:01 +00001862 */
drhb0a7c9c2010-12-06 21:09:59 +00001863#ifdef SQLITE_OMIT_MEMORYDB
1864 const int isMemdb = 0;
1865#else
1866 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
drh9c67b2a2012-05-28 13:58:00 +00001867 || (isTempDb && sqlite3TempInMemory(db))
1868 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
danielk1977aef0bf62005-12-30 16:28:01 +00001869#endif
1870
drhe5fe6902007-12-07 18:55:28 +00001871 assert( db!=0 );
dan3a6d8ae2011-04-23 15:54:54 +00001872 assert( pVfs!=0 );
drhe5fe6902007-12-07 18:55:28 +00001873 assert( sqlite3_mutex_held(db->mutex) );
drhd4187c72010-08-30 22:15:45 +00001874 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
1875
1876 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
1877 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
1878
1879 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
1880 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
drh153c62c2007-08-24 03:51:33 +00001881
drh75c014c2010-08-30 15:02:28 +00001882 if( isMemdb ){
1883 flags |= BTREE_MEMORY;
1884 }
1885 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
1886 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
1887 }
drh17435752007-08-16 04:30:38 +00001888 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00001889 if( !p ){
1890 return SQLITE_NOMEM;
1891 }
1892 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00001893 p->db = db;
danielk1977602b4662009-07-02 07:47:33 +00001894#ifndef SQLITE_OMIT_SHARED_CACHE
1895 p->lock.pBtree = p;
1896 p->lock.iTable = 1;
1897#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001898
drh198bf392006-01-06 21:52:49 +00001899#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001900 /*
1901 ** If this Btree is a candidate for shared cache, try to find an
1902 ** existing BtShared object that we can share with
1903 */
drh4ab9d252012-05-26 20:08:49 +00001904 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
drhf1f12682009-09-09 14:17:52 +00001905 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
danielk1977adfb9b02007-09-17 07:02:56 +00001906 int nFullPathname = pVfs->mxPathname+1;
drhe5ae5732008-06-15 02:51:47 +00001907 char *zFullPathname = sqlite3Malloc(nFullPathname);
drh30ddce62011-10-15 00:16:30 +00001908 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
drhff0587c2007-08-29 17:43:19 +00001909 p->sharable = 1;
drhff0587c2007-08-29 17:43:19 +00001910 if( !zFullPathname ){
1911 sqlite3_free(p);
1912 return SQLITE_NOMEM;
1913 }
drhafc8b7f2012-05-26 18:06:38 +00001914 if( isMemdb ){
1915 memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
1916 }else{
1917 rc = sqlite3OsFullPathname(pVfs, zFilename,
1918 nFullPathname, zFullPathname);
1919 if( rc ){
1920 sqlite3_free(zFullPathname);
1921 sqlite3_free(p);
1922 return rc;
1923 }
drh070ad6b2011-11-17 11:43:19 +00001924 }
drh30ddce62011-10-15 00:16:30 +00001925#if SQLITE_THREADSAFE
drh7555d8e2009-03-20 13:15:30 +00001926 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
1927 sqlite3_mutex_enter(mutexOpen);
danielk197759f8c082008-06-18 17:09:10 +00001928 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhff0587c2007-08-29 17:43:19 +00001929 sqlite3_mutex_enter(mutexShared);
drh30ddce62011-10-15 00:16:30 +00001930#endif
drh78f82d12008-09-02 00:52:52 +00001931 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
drhff0587c2007-08-29 17:43:19 +00001932 assert( pBt->nRef>0 );
drhd4e0bb02012-05-27 01:19:04 +00001933 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
drhff0587c2007-08-29 17:43:19 +00001934 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
drhc47fd8e2009-04-30 13:30:32 +00001935 int iDb;
1936 for(iDb=db->nDb-1; iDb>=0; iDb--){
1937 Btree *pExisting = db->aDb[iDb].pBt;
1938 if( pExisting && pExisting->pBt==pBt ){
1939 sqlite3_mutex_leave(mutexShared);
1940 sqlite3_mutex_leave(mutexOpen);
1941 sqlite3_free(zFullPathname);
1942 sqlite3_free(p);
1943 return SQLITE_CONSTRAINT;
1944 }
1945 }
drhff0587c2007-08-29 17:43:19 +00001946 p->pBt = pBt;
1947 pBt->nRef++;
1948 break;
1949 }
1950 }
1951 sqlite3_mutex_leave(mutexShared);
1952 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00001953 }
drhff0587c2007-08-29 17:43:19 +00001954#ifdef SQLITE_DEBUG
1955 else{
1956 /* In debug mode, we mark all persistent databases as sharable
1957 ** even when they are not. This exercises the locking code and
1958 ** gives more opportunity for asserts(sqlite3_mutex_held())
1959 ** statements to find locking problems.
1960 */
1961 p->sharable = 1;
1962 }
1963#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001964 }
1965#endif
drha059ad02001-04-17 20:09:11 +00001966 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00001967 /*
1968 ** The following asserts make sure that structures used by the btree are
1969 ** the right size. This is to guard against size changes that result
1970 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00001971 */
drhe53831d2007-08-17 01:14:38 +00001972 assert( sizeof(i64)==8 || sizeof(i64)==4 );
1973 assert( sizeof(u64)==8 || sizeof(u64)==4 );
1974 assert( sizeof(u32)==4 );
1975 assert( sizeof(u16)==2 );
1976 assert( sizeof(Pgno)==4 );
1977
1978 pBt = sqlite3MallocZero( sizeof(*pBt) );
1979 if( pBt==0 ){
1980 rc = SQLITE_NOMEM;
1981 goto btree_open_out;
1982 }
danielk197771d5d2c2008-09-29 11:49:47 +00001983 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
drh4775ecd2009-07-24 19:01:19 +00001984 EXTRA_SIZE, flags, vfsFlags, pageReinit);
drhe53831d2007-08-17 01:14:38 +00001985 if( rc==SQLITE_OK ){
drh9b4c59f2013-04-15 17:03:42 +00001986 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
drhe53831d2007-08-17 01:14:38 +00001987 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
1988 }
1989 if( rc!=SQLITE_OK ){
1990 goto btree_open_out;
1991 }
shanehbd2aaf92010-09-01 02:38:21 +00001992 pBt->openFlags = (u8)flags;
danielk19772a50ff02009-04-10 09:47:06 +00001993 pBt->db = db;
danielk19771ceedd32008-11-19 10:22:33 +00001994 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
drhe53831d2007-08-17 01:14:38 +00001995 p->pBt = pBt;
1996
drhe53831d2007-08-17 01:14:38 +00001997 pBt->pCursor = 0;
1998 pBt->pPage1 = 0;
drhc9166342012-01-05 23:32:06 +00001999 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
drh5b47efa2010-02-12 18:18:39 +00002000#ifdef SQLITE_SECURE_DELETE
drhc9166342012-01-05 23:32:06 +00002001 pBt->btsFlags |= BTS_SECURE_DELETE;
drh5b47efa2010-02-12 18:18:39 +00002002#endif
drhb2eced52010-08-12 02:41:12 +00002003 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
drhe53831d2007-08-17 01:14:38 +00002004 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2005 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002006 pBt->pageSize = 0;
drhe53831d2007-08-17 01:14:38 +00002007#ifndef SQLITE_OMIT_AUTOVACUUM
2008 /* If the magic name ":memory:" will create an in-memory database, then
2009 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2010 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2011 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2012 ** regular file-name. In this case the auto-vacuum applies as per normal.
2013 */
2014 if( zFilename && !isMemdb ){
2015 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2016 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2017 }
2018#endif
2019 nReserve = 0;
2020 }else{
2021 nReserve = zDbHeader[20];
drhc9166342012-01-05 23:32:06 +00002022 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
drhe53831d2007-08-17 01:14:38 +00002023#ifndef SQLITE_OMIT_AUTOVACUUM
2024 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2025 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2026#endif
2027 }
drhfa9601a2009-06-18 17:22:39 +00002028 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhc0b61812009-04-30 01:22:41 +00002029 if( rc ) goto btree_open_out;
drhe53831d2007-08-17 01:14:38 +00002030 pBt->usableSize = pBt->pageSize - nReserve;
2031 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
drhe53831d2007-08-17 01:14:38 +00002032
2033#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2034 /* Add the new BtShared object to the linked list sharable BtShareds.
2035 */
2036 if( p->sharable ){
drh30ddce62011-10-15 00:16:30 +00002037 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
drhe53831d2007-08-17 01:14:38 +00002038 pBt->nRef = 1;
drh30ddce62011-10-15 00:16:30 +00002039 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
danielk1977075c23a2008-09-01 18:34:20 +00002040 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
danielk197759f8c082008-06-18 17:09:10 +00002041 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00002042 if( pBt->mutex==0 ){
2043 rc = SQLITE_NOMEM;
drhe5fe6902007-12-07 18:55:28 +00002044 db->mallocFailed = 0;
drh3285db22007-09-03 22:00:39 +00002045 goto btree_open_out;
2046 }
drhff0587c2007-08-29 17:43:19 +00002047 }
drhe53831d2007-08-17 01:14:38 +00002048 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00002049 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2050 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
drhe53831d2007-08-17 01:14:38 +00002051 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00002052 }
drheee46cf2004-11-06 00:02:48 +00002053#endif
drh90f5ecb2004-07-22 01:19:35 +00002054 }
danielk1977aef0bf62005-12-30 16:28:01 +00002055
drhcfed7bc2006-03-13 14:28:05 +00002056#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00002057 /* If the new Btree uses a sharable pBtShared, then link the new
2058 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00002059 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00002060 */
drhe53831d2007-08-17 01:14:38 +00002061 if( p->sharable ){
2062 int i;
2063 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00002064 for(i=0; i<db->nDb; i++){
2065 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00002066 while( pSib->pPrev ){ pSib = pSib->pPrev; }
2067 if( p->pBt<pSib->pBt ){
2068 p->pNext = pSib;
2069 p->pPrev = 0;
2070 pSib->pPrev = p;
2071 }else{
drhabddb0c2007-08-20 13:14:28 +00002072 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
drhe53831d2007-08-17 01:14:38 +00002073 pSib = pSib->pNext;
2074 }
2075 p->pNext = pSib->pNext;
2076 p->pPrev = pSib;
2077 if( p->pNext ){
2078 p->pNext->pPrev = p;
2079 }
2080 pSib->pNext = p;
2081 }
2082 break;
2083 }
2084 }
danielk1977aef0bf62005-12-30 16:28:01 +00002085 }
danielk1977aef0bf62005-12-30 16:28:01 +00002086#endif
2087 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00002088
2089btree_open_out:
2090 if( rc!=SQLITE_OK ){
2091 if( pBt && pBt->pPager ){
2092 sqlite3PagerClose(pBt->pPager);
2093 }
drh17435752007-08-16 04:30:38 +00002094 sqlite3_free(pBt);
2095 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00002096 *ppBtree = 0;
drh75c014c2010-08-30 15:02:28 +00002097 }else{
2098 /* If the B-Tree was successfully opened, set the pager-cache size to the
2099 ** default value. Except, when opening on an existing shared pager-cache,
2100 ** do not change the pager-cache size.
2101 */
2102 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2103 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
2104 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002105 }
drh7555d8e2009-03-20 13:15:30 +00002106 if( mutexOpen ){
2107 assert( sqlite3_mutex_held(mutexOpen) );
2108 sqlite3_mutex_leave(mutexOpen);
2109 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002110 return rc;
drha059ad02001-04-17 20:09:11 +00002111}
2112
2113/*
drhe53831d2007-08-17 01:14:38 +00002114** Decrement the BtShared.nRef counter. When it reaches zero,
2115** remove the BtShared structure from the sharing list. Return
2116** true if the BtShared.nRef counter reaches zero and return
2117** false if it is still positive.
2118*/
2119static int removeFromSharingList(BtShared *pBt){
2120#ifndef SQLITE_OMIT_SHARED_CACHE
drh30ddce62011-10-15 00:16:30 +00002121 MUTEX_LOGIC( sqlite3_mutex *pMaster; )
drhe53831d2007-08-17 01:14:38 +00002122 BtShared *pList;
2123 int removed = 0;
2124
drhd677b3d2007-08-20 22:48:41 +00002125 assert( sqlite3_mutex_notheld(pBt->mutex) );
drh30ddce62011-10-15 00:16:30 +00002126 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
drhe53831d2007-08-17 01:14:38 +00002127 sqlite3_mutex_enter(pMaster);
2128 pBt->nRef--;
2129 if( pBt->nRef<=0 ){
drh78f82d12008-09-02 00:52:52 +00002130 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2131 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
drhe53831d2007-08-17 01:14:38 +00002132 }else{
drh78f82d12008-09-02 00:52:52 +00002133 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
drh34004ce2008-07-11 16:15:17 +00002134 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00002135 pList=pList->pNext;
2136 }
drh34004ce2008-07-11 16:15:17 +00002137 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00002138 pList->pNext = pBt->pNext;
2139 }
2140 }
drh3285db22007-09-03 22:00:39 +00002141 if( SQLITE_THREADSAFE ){
2142 sqlite3_mutex_free(pBt->mutex);
2143 }
drhe53831d2007-08-17 01:14:38 +00002144 removed = 1;
2145 }
2146 sqlite3_mutex_leave(pMaster);
2147 return removed;
2148#else
2149 return 1;
2150#endif
2151}
2152
2153/*
drhf7141992008-06-19 00:16:08 +00002154** Make sure pBt->pTmpSpace points to an allocation of
drh92787cf2014-10-15 11:55:51 +00002155** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
2156** pointer.
drhf7141992008-06-19 00:16:08 +00002157*/
2158static void allocateTempSpace(BtShared *pBt){
2159 if( !pBt->pTmpSpace ){
2160 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
dan14285b72013-10-16 11:39:07 +00002161
2162 /* One of the uses of pBt->pTmpSpace is to format cells before
2163 ** inserting them into a leaf page (function fillInCell()). If
2164 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2165 ** by the various routines that manipulate binary cells. Which
2166 ** can mean that fillInCell() only initializes the first 2 or 3
2167 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2168 ** it into a database page. This is not actually a problem, but it
2169 ** does cause a valgrind error when the 1 or 2 bytes of unitialized
2170 ** data is passed to system call write(). So to avoid this error,
drh92787cf2014-10-15 11:55:51 +00002171 ** zero the first 4 bytes of temp space here.
2172 **
2173 ** Also: Provide four bytes of initialized space before the
2174 ** beginning of pTmpSpace as an area available to prepend the
2175 ** left-child pointer to the beginning of a cell.
2176 */
2177 if( pBt->pTmpSpace ){
2178 memset(pBt->pTmpSpace, 0, 8);
2179 pBt->pTmpSpace += 4;
2180 }
drhf7141992008-06-19 00:16:08 +00002181 }
2182}
2183
2184/*
2185** Free the pBt->pTmpSpace allocation
2186*/
2187static void freeTempSpace(BtShared *pBt){
drh92787cf2014-10-15 11:55:51 +00002188 if( pBt->pTmpSpace ){
2189 pBt->pTmpSpace -= 4;
2190 sqlite3PageFree(pBt->pTmpSpace);
2191 pBt->pTmpSpace = 0;
2192 }
drhf7141992008-06-19 00:16:08 +00002193}
2194
2195/*
drha059ad02001-04-17 20:09:11 +00002196** Close an open database and invalidate all cursors.
2197*/
danielk1977aef0bf62005-12-30 16:28:01 +00002198int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002199 BtShared *pBt = p->pBt;
2200 BtCursor *pCur;
2201
danielk1977aef0bf62005-12-30 16:28:01 +00002202 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00002203 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00002204 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002205 pCur = pBt->pCursor;
2206 while( pCur ){
2207 BtCursor *pTmp = pCur;
2208 pCur = pCur->pNext;
2209 if( pTmp->pBtree==p ){
2210 sqlite3BtreeCloseCursor(pTmp);
2211 }
drha059ad02001-04-17 20:09:11 +00002212 }
danielk1977aef0bf62005-12-30 16:28:01 +00002213
danielk19778d34dfd2006-01-24 16:37:57 +00002214 /* Rollback any active transaction and free the handle structure.
2215 ** The call to sqlite3BtreeRollback() drops any table-locks held by
2216 ** this handle.
2217 */
drh0f198a72012-02-13 16:43:16 +00002218 sqlite3BtreeRollback(p, SQLITE_OK);
drhe53831d2007-08-17 01:14:38 +00002219 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002220
danielk1977aef0bf62005-12-30 16:28:01 +00002221 /* If there are still other outstanding references to the shared-btree
2222 ** structure, return now. The remainder of this procedure cleans
2223 ** up the shared-btree.
2224 */
drhe53831d2007-08-17 01:14:38 +00002225 assert( p->wantToLock==0 && p->locked==0 );
2226 if( !p->sharable || removeFromSharingList(pBt) ){
2227 /* The pBt is no longer on the sharing list, so we can access
2228 ** it without having to hold the mutex.
2229 **
2230 ** Clean out and delete the BtShared object.
2231 */
2232 assert( !pBt->pCursor );
drhe53831d2007-08-17 01:14:38 +00002233 sqlite3PagerClose(pBt->pPager);
2234 if( pBt->xFreeSchema && pBt->pSchema ){
2235 pBt->xFreeSchema(pBt->pSchema);
2236 }
drhb9755982010-07-24 16:34:37 +00002237 sqlite3DbFree(0, pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00002238 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00002239 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002240 }
2241
drhe53831d2007-08-17 01:14:38 +00002242#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00002243 assert( p->wantToLock==0 );
2244 assert( p->locked==0 );
2245 if( p->pPrev ) p->pPrev->pNext = p->pNext;
2246 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00002247#endif
2248
drhe53831d2007-08-17 01:14:38 +00002249 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00002250 return SQLITE_OK;
2251}
2252
2253/*
drhda47d772002-12-02 04:25:19 +00002254** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00002255**
2256** The maximum number of cache pages is set to the absolute
2257** value of mxPage. If mxPage is negative, the pager will
2258** operate asynchronously - it will not stop to do fsync()s
2259** to insure data is written to the disk surface before
2260** continuing. Transactions still work if synchronous is off,
2261** and the database cannot be corrupted if this program
2262** crashes. But if the operating system crashes or there is
2263** an abrupt power failure when synchronous is off, the database
2264** could be left in an inconsistent and unrecoverable state.
2265** Synchronous is on by default so database corruption is not
2266** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00002267*/
danielk1977aef0bf62005-12-30 16:28:01 +00002268int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2269 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00002270 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002271 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00002272 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00002273 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00002274 return SQLITE_OK;
2275}
2276
drh18c7e402014-03-14 11:46:10 +00002277#if SQLITE_MAX_MMAP_SIZE>0
drhf57b14a2001-09-14 18:54:08 +00002278/*
dan5d8a1372013-03-19 19:28:06 +00002279** Change the limit on the amount of the database file that may be
2280** memory mapped.
2281*/
drh9b4c59f2013-04-15 17:03:42 +00002282int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
dan5d8a1372013-03-19 19:28:06 +00002283 BtShared *pBt = p->pBt;
2284 assert( sqlite3_mutex_held(p->db->mutex) );
2285 sqlite3BtreeEnter(p);
drh9b4c59f2013-04-15 17:03:42 +00002286 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
dan5d8a1372013-03-19 19:28:06 +00002287 sqlite3BtreeLeave(p);
2288 return SQLITE_OK;
2289}
drh18c7e402014-03-14 11:46:10 +00002290#endif /* SQLITE_MAX_MMAP_SIZE>0 */
dan5d8a1372013-03-19 19:28:06 +00002291
2292/*
drh973b6e32003-02-12 14:09:42 +00002293** Change the way data is synced to disk in order to increase or decrease
2294** how well the database resists damage due to OS crashes and power
2295** failures. Level 1 is the same as asynchronous (no syncs() occur and
2296** there is a high probability of damage) Level 2 is the default. There
2297** is a very low but non-zero probability of damage. Level 3 reduces the
2298** probability of damage to near zero but with a write performance reduction.
2299*/
danielk197793758c82005-01-21 08:13:14 +00002300#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drh40c39412013-08-16 20:42:20 +00002301int sqlite3BtreeSetPagerFlags(
drhc97d8462010-11-19 18:23:35 +00002302 Btree *p, /* The btree to set the safety level on */
drh40c39412013-08-16 20:42:20 +00002303 unsigned pgFlags /* Various PAGER_* flags */
drhc97d8462010-11-19 18:23:35 +00002304){
danielk1977aef0bf62005-12-30 16:28:01 +00002305 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00002306 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002307 sqlite3BtreeEnter(p);
drh40c39412013-08-16 20:42:20 +00002308 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
drhd677b3d2007-08-20 22:48:41 +00002309 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00002310 return SQLITE_OK;
2311}
danielk197793758c82005-01-21 08:13:14 +00002312#endif
drh973b6e32003-02-12 14:09:42 +00002313
drh2c8997b2005-08-27 16:36:48 +00002314/*
2315** Return TRUE if the given btree is set to safety level 1. In other
2316** words, return TRUE if no sync() occurs on the disk files.
2317*/
danielk1977aef0bf62005-12-30 16:28:01 +00002318int sqlite3BtreeSyncDisabled(Btree *p){
2319 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002320 int rc;
drhe5fe6902007-12-07 18:55:28 +00002321 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002322 sqlite3BtreeEnter(p);
drhd0679ed2007-08-28 22:24:34 +00002323 assert( pBt && pBt->pPager );
drhd677b3d2007-08-20 22:48:41 +00002324 rc = sqlite3PagerNosync(pBt->pPager);
2325 sqlite3BtreeLeave(p);
2326 return rc;
drh2c8997b2005-08-27 16:36:48 +00002327}
2328
drh973b6e32003-02-12 14:09:42 +00002329/*
drh90f5ecb2004-07-22 01:19:35 +00002330** Change the default pages size and the number of reserved bytes per page.
drhce4869f2009-04-02 20:16:58 +00002331** Or, if the page size has already been fixed, return SQLITE_READONLY
2332** without changing anything.
drh06f50212004-11-02 14:24:33 +00002333**
2334** The page size must be a power of 2 between 512 and 65536. If the page
2335** size supplied does not meet this constraint then the page size is not
2336** changed.
2337**
2338** Page sizes are constrained to be a power of two so that the region
2339** of the database file used for locking (beginning at PENDING_BYTE,
2340** the first byte past the 1GB boundary, 0x40000000) needs to occur
2341** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00002342**
2343** If parameter nReserve is less than zero, then the number of reserved
2344** bytes per page is left unchanged.
drhce4869f2009-04-02 20:16:58 +00002345**
drhc9166342012-01-05 23:32:06 +00002346** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
drhce4869f2009-04-02 20:16:58 +00002347** and autovacuum mode can no longer be changed.
drh90f5ecb2004-07-22 01:19:35 +00002348*/
drhce4869f2009-04-02 20:16:58 +00002349int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
danielk1977a1644fd2007-08-29 12:31:25 +00002350 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002351 BtShared *pBt = p->pBt;
drhf49661a2008-12-10 16:45:50 +00002352 assert( nReserve>=-1 && nReserve<=255 );
drhd677b3d2007-08-20 22:48:41 +00002353 sqlite3BtreeEnter(p);
drhc9166342012-01-05 23:32:06 +00002354 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
drhd677b3d2007-08-20 22:48:41 +00002355 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00002356 return SQLITE_READONLY;
2357 }
2358 if( nReserve<0 ){
2359 nReserve = pBt->pageSize - pBt->usableSize;
2360 }
drhf49661a2008-12-10 16:45:50 +00002361 assert( nReserve>=0 && nReserve<=255 );
drh06f50212004-11-02 14:24:33 +00002362 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2363 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00002364 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002365 assert( !pBt->pPage1 && !pBt->pCursor );
drhb2eced52010-08-12 02:41:12 +00002366 pBt->pageSize = (u32)pageSize;
drhf7141992008-06-19 00:16:08 +00002367 freeTempSpace(pBt);
drh90f5ecb2004-07-22 01:19:35 +00002368 }
drhfa9601a2009-06-18 17:22:39 +00002369 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhf49661a2008-12-10 16:45:50 +00002370 pBt->usableSize = pBt->pageSize - (u16)nReserve;
drhc9166342012-01-05 23:32:06 +00002371 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
drhd677b3d2007-08-20 22:48:41 +00002372 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00002373 return rc;
drh90f5ecb2004-07-22 01:19:35 +00002374}
2375
2376/*
2377** Return the currently defined page size
2378*/
danielk1977aef0bf62005-12-30 16:28:01 +00002379int sqlite3BtreeGetPageSize(Btree *p){
2380 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00002381}
drh7f751222009-03-17 22:33:00 +00002382
drha1f38532012-10-01 12:44:26 +00002383#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
dan0094f372012-09-28 20:23:42 +00002384/*
2385** This function is similar to sqlite3BtreeGetReserve(), except that it
2386** may only be called if it is guaranteed that the b-tree mutex is already
2387** held.
2388**
2389** This is useful in one special case in the backup API code where it is
2390** known that the shared b-tree mutex is held, but the mutex on the
2391** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
2392** were to be called, it might collide with some other operation on the
mistachkin48864df2013-03-21 21:20:32 +00002393** database handle that owns *p, causing undefined behavior.
dan0094f372012-09-28 20:23:42 +00002394*/
2395int sqlite3BtreeGetReserveNoMutex(Btree *p){
2396 assert( sqlite3_mutex_held(p->pBt->mutex) );
2397 return p->pBt->pageSize - p->pBt->usableSize;
2398}
drha1f38532012-10-01 12:44:26 +00002399#endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
dan0094f372012-09-28 20:23:42 +00002400
danbb2b4412011-04-06 17:54:31 +00002401#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh7f751222009-03-17 22:33:00 +00002402/*
2403** Return the number of bytes of space at the end of every page that
2404** are intentually left unused. This is the "reserved" space that is
2405** sometimes used by extensions.
2406*/
danielk1977aef0bf62005-12-30 16:28:01 +00002407int sqlite3BtreeGetReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002408 int n;
2409 sqlite3BtreeEnter(p);
2410 n = p->pBt->pageSize - p->pBt->usableSize;
2411 sqlite3BtreeLeave(p);
2412 return n;
drh2011d5f2004-07-22 02:40:37 +00002413}
drhf8e632b2007-05-08 14:51:36 +00002414
2415/*
2416** Set the maximum page count for a database if mxPage is positive.
2417** No changes are made if mxPage is 0 or negative.
2418** Regardless of the value of mxPage, return the maximum page count.
2419*/
2420int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00002421 int n;
2422 sqlite3BtreeEnter(p);
2423 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
2424 sqlite3BtreeLeave(p);
2425 return n;
drhf8e632b2007-05-08 14:51:36 +00002426}
drh5b47efa2010-02-12 18:18:39 +00002427
2428/*
drhc9166342012-01-05 23:32:06 +00002429** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
2430** then make no changes. Always return the value of the BTS_SECURE_DELETE
drh5b47efa2010-02-12 18:18:39 +00002431** setting after the change.
2432*/
2433int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
2434 int b;
drhaf034ed2010-02-12 19:46:26 +00002435 if( p==0 ) return 0;
drh5b47efa2010-02-12 18:18:39 +00002436 sqlite3BtreeEnter(p);
2437 if( newFlag>=0 ){
drhc9166342012-01-05 23:32:06 +00002438 p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
2439 if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
drh5b47efa2010-02-12 18:18:39 +00002440 }
drhc9166342012-01-05 23:32:06 +00002441 b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
drh5b47efa2010-02-12 18:18:39 +00002442 sqlite3BtreeLeave(p);
2443 return b;
2444}
danielk1977576ec6b2005-01-21 11:55:25 +00002445#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00002446
2447/*
danielk1977951af802004-11-05 15:45:09 +00002448** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
2449** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
2450** is disabled. The default value for the auto-vacuum property is
2451** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
2452*/
danielk1977aef0bf62005-12-30 16:28:01 +00002453int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00002454#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002455 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00002456#else
danielk1977dddbcdc2007-04-26 14:42:34 +00002457 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002458 int rc = SQLITE_OK;
drh076d4662009-02-18 20:31:18 +00002459 u8 av = (u8)autoVacuum;
drhd677b3d2007-08-20 22:48:41 +00002460
2461 sqlite3BtreeEnter(p);
drhc9166342012-01-05 23:32:06 +00002462 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002463 rc = SQLITE_READONLY;
2464 }else{
drh076d4662009-02-18 20:31:18 +00002465 pBt->autoVacuum = av ?1:0;
2466 pBt->incrVacuum = av==2 ?1:0;
danielk1977951af802004-11-05 15:45:09 +00002467 }
drhd677b3d2007-08-20 22:48:41 +00002468 sqlite3BtreeLeave(p);
2469 return rc;
danielk1977951af802004-11-05 15:45:09 +00002470#endif
2471}
2472
2473/*
2474** Return the value of the 'auto-vacuum' property. If auto-vacuum is
2475** enabled 1 is returned. Otherwise 0.
2476*/
danielk1977aef0bf62005-12-30 16:28:01 +00002477int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00002478#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002479 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00002480#else
drhd677b3d2007-08-20 22:48:41 +00002481 int rc;
2482 sqlite3BtreeEnter(p);
2483 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00002484 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
2485 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
2486 BTREE_AUTOVACUUM_INCR
2487 );
drhd677b3d2007-08-20 22:48:41 +00002488 sqlite3BtreeLeave(p);
2489 return rc;
danielk1977951af802004-11-05 15:45:09 +00002490#endif
2491}
2492
2493
2494/*
drha34b6762004-05-07 13:30:42 +00002495** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00002496** also acquire a readlock on that file.
2497**
2498** SQLITE_OK is returned on success. If the file is not a
2499** well-formed database file, then SQLITE_CORRUPT is returned.
2500** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00002501** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00002502*/
danielk1977aef0bf62005-12-30 16:28:01 +00002503static int lockBtree(BtShared *pBt){
drhc2a4bab2010-04-02 12:46:45 +00002504 int rc; /* Result code from subfunctions */
2505 MemPage *pPage1; /* Page 1 of the database file */
2506 int nPage; /* Number of pages in the database */
2507 int nPageFile = 0; /* Number of pages in the database file */
2508 int nPageHeader; /* Number of pages in the database according to hdr */
drhd677b3d2007-08-20 22:48:41 +00002509
drh1fee73e2007-08-29 04:00:57 +00002510 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977295dc102009-04-01 19:07:03 +00002511 assert( pBt->pPage1==0 );
danielk197789bc4bc2009-07-21 19:25:24 +00002512 rc = sqlite3PagerSharedLock(pBt->pPager);
2513 if( rc!=SQLITE_OK ) return rc;
drhb00fc3b2013-08-21 23:42:32 +00002514 rc = btreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00002515 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00002516
2517 /* Do some checking to help insure the file we opened really is
2518 ** a valid database file.
2519 */
drhc2a4bab2010-04-02 12:46:45 +00002520 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
drh8fb8b532010-08-14 17:12:04 +00002521 sqlite3PagerPagecount(pBt->pPager, &nPageFile);
drhb28e59b2010-06-17 02:13:39 +00002522 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
drhc2a4bab2010-04-02 12:46:45 +00002523 nPage = nPageFile;
drh97b59a52010-03-31 02:31:33 +00002524 }
2525 if( nPage>0 ){
drh43b18e12010-08-17 19:40:08 +00002526 u32 pageSize;
2527 u32 usableSize;
drhb6f41482004-05-14 01:58:11 +00002528 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00002529 rc = SQLITE_NOTADB;
drhb6f41482004-05-14 01:58:11 +00002530 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00002531 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00002532 }
dan5cf53532010-05-01 16:40:20 +00002533
2534#ifdef SQLITE_OMIT_WAL
2535 if( page1[18]>1 ){
drhc9166342012-01-05 23:32:06 +00002536 pBt->btsFlags |= BTS_READ_ONLY;
dan5cf53532010-05-01 16:40:20 +00002537 }
2538 if( page1[19]>1 ){
2539 goto page1_init_failed;
2540 }
2541#else
dane04dc882010-04-20 18:53:15 +00002542 if( page1[18]>2 ){
drhc9166342012-01-05 23:32:06 +00002543 pBt->btsFlags |= BTS_READ_ONLY;
drh309169a2007-04-24 17:27:51 +00002544 }
dane04dc882010-04-20 18:53:15 +00002545 if( page1[19]>2 ){
drhb6f41482004-05-14 01:58:11 +00002546 goto page1_init_failed;
2547 }
drhe5ae5732008-06-15 02:51:47 +00002548
dana470aeb2010-04-21 11:43:38 +00002549 /* If the write version is set to 2, this database should be accessed
2550 ** in WAL mode. If the log is not already open, open it now. Then
2551 ** return SQLITE_OK and return without populating BtShared.pPage1.
2552 ** The caller detects this and calls this function again. This is
2553 ** required as the version of page 1 currently in the page1 buffer
2554 ** may not be the latest version - there may be a newer one in the log
2555 ** file.
2556 */
drhc9166342012-01-05 23:32:06 +00002557 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
dane04dc882010-04-20 18:53:15 +00002558 int isOpen = 0;
drh7ed91f22010-04-29 22:34:07 +00002559 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
dane04dc882010-04-20 18:53:15 +00002560 if( rc!=SQLITE_OK ){
2561 goto page1_init_failed;
2562 }else if( isOpen==0 ){
2563 releasePage(pPage1);
2564 return SQLITE_OK;
2565 }
dan8b5444b2010-04-27 14:37:47 +00002566 rc = SQLITE_NOTADB;
dane04dc882010-04-20 18:53:15 +00002567 }
dan5cf53532010-05-01 16:40:20 +00002568#endif
dane04dc882010-04-20 18:53:15 +00002569
drhe5ae5732008-06-15 02:51:47 +00002570 /* The maximum embedded fraction must be exactly 25%. And the minimum
2571 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
2572 ** The original design allowed these amounts to vary, but as of
2573 ** version 3.6.0, we require them to be fixed.
2574 */
2575 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
2576 goto page1_init_failed;
2577 }
drhb2eced52010-08-12 02:41:12 +00002578 pageSize = (page1[16]<<8) | (page1[17]<<16);
2579 if( ((pageSize-1)&pageSize)!=0
2580 || pageSize>SQLITE_MAX_PAGE_SIZE
2581 || pageSize<=256
drh7dc385e2007-09-06 23:39:36 +00002582 ){
drh07d183d2005-05-01 22:52:42 +00002583 goto page1_init_failed;
2584 }
2585 assert( (pageSize & 7)==0 );
danielk1977f653d782008-03-20 11:04:21 +00002586 usableSize = pageSize - page1[20];
shaneh1df2db72010-08-18 02:28:48 +00002587 if( (u32)pageSize!=pBt->pageSize ){
danielk1977f653d782008-03-20 11:04:21 +00002588 /* After reading the first page of the database assuming a page size
2589 ** of BtShared.pageSize, we have discovered that the page-size is
2590 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
2591 ** zero and return SQLITE_OK. The caller will call this function
2592 ** again with the correct page-size.
2593 */
2594 releasePage(pPage1);
drh43b18e12010-08-17 19:40:08 +00002595 pBt->usableSize = usableSize;
2596 pBt->pageSize = pageSize;
drhf7141992008-06-19 00:16:08 +00002597 freeTempSpace(pBt);
drhfa9601a2009-06-18 17:22:39 +00002598 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
2599 pageSize-usableSize);
drh5e483932009-07-10 16:51:30 +00002600 return rc;
danielk1977f653d782008-03-20 11:04:21 +00002601 }
danecac6702011-02-09 18:19:20 +00002602 if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
drhc2a4bab2010-04-02 12:46:45 +00002603 rc = SQLITE_CORRUPT_BKPT;
2604 goto page1_init_failed;
2605 }
drhb33e1b92009-06-18 11:29:20 +00002606 if( usableSize<480 ){
drhb6f41482004-05-14 01:58:11 +00002607 goto page1_init_failed;
2608 }
drh43b18e12010-08-17 19:40:08 +00002609 pBt->pageSize = pageSize;
2610 pBt->usableSize = usableSize;
drh057cd3a2005-02-15 16:23:02 +00002611#ifndef SQLITE_OMIT_AUTOVACUUM
2612 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00002613 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00002614#endif
drh306dc212001-05-21 13:45:10 +00002615 }
drhb6f41482004-05-14 01:58:11 +00002616
2617 /* maxLocal is the maximum amount of payload to store locally for
2618 ** a cell. Make sure it is small enough so that at least minFanout
2619 ** cells can will fit on one page. We assume a 10-byte page header.
2620 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00002621 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00002622 ** 4-byte child pointer
2623 ** 9-byte nKey value
2624 ** 4-byte nData value
2625 ** 4-byte overflow page pointer
drhe22e03e2010-08-18 21:19:03 +00002626 ** So a cell consists of a 2-byte pointer, a header which is as much as
drh43605152004-05-29 21:46:49 +00002627 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
2628 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00002629 */
shaneh1df2db72010-08-18 02:28:48 +00002630 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
2631 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
2632 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
2633 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
drhc9166342012-01-05 23:32:06 +00002634 if( pBt->maxLocal>127 ){
2635 pBt->max1bytePayload = 127;
2636 }else{
mistachkin0547e2f2012-01-08 00:54:02 +00002637 pBt->max1bytePayload = (u8)pBt->maxLocal;
drhc9166342012-01-05 23:32:06 +00002638 }
drh2e38c322004-09-03 18:38:44 +00002639 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00002640 pBt->pPage1 = pPage1;
drhdd3cd972010-03-27 17:12:36 +00002641 pBt->nPage = nPage;
drhb6f41482004-05-14 01:58:11 +00002642 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00002643
drh72f82862001-05-24 21:06:34 +00002644page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00002645 releasePage(pPage1);
2646 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00002647 return rc;
drh306dc212001-05-21 13:45:10 +00002648}
2649
drh85ec3b62013-05-14 23:12:06 +00002650#ifndef NDEBUG
2651/*
2652** Return the number of cursors open on pBt. This is for use
2653** in assert() expressions, so it is only compiled if NDEBUG is not
2654** defined.
2655**
2656** Only write cursors are counted if wrOnly is true. If wrOnly is
2657** false then all cursors are counted.
2658**
2659** For the purposes of this routine, a cursor is any cursor that
peter.d.reid60ec9142014-09-06 16:39:46 +00002660** is capable of reading or writing to the database. Cursors that
drh85ec3b62013-05-14 23:12:06 +00002661** have been tripped into the CURSOR_FAULT state are not counted.
2662*/
2663static int countValidCursors(BtShared *pBt, int wrOnly){
2664 BtCursor *pCur;
2665 int r = 0;
2666 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drh036dbec2014-03-11 23:40:44 +00002667 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
2668 && pCur->eState!=CURSOR_FAULT ) r++;
drh85ec3b62013-05-14 23:12:06 +00002669 }
2670 return r;
2671}
2672#endif
2673
drh306dc212001-05-21 13:45:10 +00002674/*
drhb8ca3072001-12-05 00:21:20 +00002675** If there are no outstanding cursors and we are not in the middle
2676** of a transaction but there is a read lock on the database, then
2677** this routine unrefs the first page of the database file which
2678** has the effect of releasing the read lock.
2679**
drhb8ca3072001-12-05 00:21:20 +00002680** If there is a transaction in progress, this routine is a no-op.
2681*/
danielk1977aef0bf62005-12-30 16:28:01 +00002682static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00002683 assert( sqlite3_mutex_held(pBt->mutex) );
drh85ec3b62013-05-14 23:12:06 +00002684 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
danielk19771bc9ee92009-07-04 15:41:02 +00002685 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
drhb2325b72014-09-24 18:31:07 +00002686 MemPage *pPage1 = pBt->pPage1;
2687 assert( pPage1->aData );
danielk1977c1761e82009-06-25 09:40:03 +00002688 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
drh3aac2dd2004-04-26 14:10:20 +00002689 pBt->pPage1 = 0;
drhb2325b72014-09-24 18:31:07 +00002690 releasePage(pPage1);
drhb8ca3072001-12-05 00:21:20 +00002691 }
2692}
2693
2694/*
drhe39f2f92009-07-23 01:43:59 +00002695** If pBt points to an empty file then convert that empty file
2696** into a new empty database by initializing the first page of
2697** the database.
drh8b2f49b2001-06-08 00:21:52 +00002698*/
danielk1977aef0bf62005-12-30 16:28:01 +00002699static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00002700 MemPage *pP1;
2701 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00002702 int rc;
drhd677b3d2007-08-20 22:48:41 +00002703
drh1fee73e2007-08-29 04:00:57 +00002704 assert( sqlite3_mutex_held(pBt->mutex) );
drhdd3cd972010-03-27 17:12:36 +00002705 if( pBt->nPage>0 ){
2706 return SQLITE_OK;
danielk1977ad0132d2008-06-07 08:58:22 +00002707 }
drh3aac2dd2004-04-26 14:10:20 +00002708 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00002709 assert( pP1!=0 );
2710 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00002711 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00002712 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00002713 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
2714 assert( sizeof(zMagicHeader)==16 );
shaneh1df2db72010-08-18 02:28:48 +00002715 data[16] = (u8)((pBt->pageSize>>8)&0xff);
2716 data[17] = (u8)((pBt->pageSize>>16)&0xff);
drh9e572e62004-04-23 23:43:10 +00002717 data[18] = 1;
2718 data[19] = 1;
drhf49661a2008-12-10 16:45:50 +00002719 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
2720 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
drhe5ae5732008-06-15 02:51:47 +00002721 data[21] = 64;
2722 data[22] = 32;
2723 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00002724 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00002725 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhc9166342012-01-05 23:32:06 +00002726 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
danielk1977003ba062004-11-04 02:57:33 +00002727#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002728 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00002729 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00002730 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00002731 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00002732#endif
drhdd3cd972010-03-27 17:12:36 +00002733 pBt->nPage = 1;
2734 data[31] = 1;
drh8b2f49b2001-06-08 00:21:52 +00002735 return SQLITE_OK;
2736}
2737
2738/*
danb483eba2012-10-13 19:58:11 +00002739** Initialize the first page of the database file (creating a database
2740** consisting of a single page and no schema objects). Return SQLITE_OK
2741** if successful, or an SQLite error code otherwise.
2742*/
2743int sqlite3BtreeNewDb(Btree *p){
2744 int rc;
2745 sqlite3BtreeEnter(p);
2746 p->pBt->nPage = 0;
2747 rc = newDatabase(p->pBt);
2748 sqlite3BtreeLeave(p);
2749 return rc;
2750}
2751
2752/*
danielk1977ee5741e2004-05-31 10:01:34 +00002753** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00002754** is started if the second argument is nonzero, otherwise a read-
2755** transaction. If the second argument is 2 or more and exclusive
2756** transaction is started, meaning that no other process is allowed
2757** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00002758** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00002759** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00002760**
danielk1977ee5741e2004-05-31 10:01:34 +00002761** A write-transaction must be started before attempting any
2762** changes to the database. None of the following routines
2763** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00002764**
drh23e11ca2004-05-04 17:27:28 +00002765** sqlite3BtreeCreateTable()
2766** sqlite3BtreeCreateIndex()
2767** sqlite3BtreeClearTable()
2768** sqlite3BtreeDropTable()
2769** sqlite3BtreeInsert()
2770** sqlite3BtreeDelete()
2771** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00002772**
drhb8ef32c2005-03-14 02:01:49 +00002773** If an initial attempt to acquire the lock fails because of lock contention
2774** and the database was previously unlocked, then invoke the busy handler
2775** if there is one. But if there was previously a read-lock, do not
2776** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
2777** returned when there is already a read-lock in order to avoid a deadlock.
2778**
2779** Suppose there are two processes A and B. A has a read lock and B has
2780** a reserved lock. B tries to promote to exclusive but is blocked because
2781** of A's read lock. A tries to promote to reserved but is blocked by B.
2782** One or the other of the two processes must give way or there can be
2783** no progress. By returning SQLITE_BUSY and not invoking the busy callback
2784** when A already has a read lock, we encourage A to give up and let B
2785** proceed.
drha059ad02001-04-17 20:09:11 +00002786*/
danielk1977aef0bf62005-12-30 16:28:01 +00002787int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
danielk1977404ca072009-03-16 13:19:36 +00002788 sqlite3 *pBlock = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00002789 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00002790 int rc = SQLITE_OK;
2791
drhd677b3d2007-08-20 22:48:41 +00002792 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002793 btreeIntegrity(p);
2794
danielk1977ee5741e2004-05-31 10:01:34 +00002795 /* If the btree is already in a write-transaction, or it
2796 ** is already in a read-transaction and a read-transaction
2797 ** is requested, this is a no-op.
2798 */
danielk1977aef0bf62005-12-30 16:28:01 +00002799 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00002800 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002801 }
dan56c517a2013-09-26 11:04:33 +00002802 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
drhb8ef32c2005-03-14 02:01:49 +00002803
2804 /* Write transactions are not possible on a read-only database */
drhc9166342012-01-05 23:32:06 +00002805 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00002806 rc = SQLITE_READONLY;
2807 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002808 }
2809
danielk1977404ca072009-03-16 13:19:36 +00002810#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +00002811 /* If another database handle has already opened a write transaction
2812 ** on this shared-btree structure and a second write transaction is
danielk1977404ca072009-03-16 13:19:36 +00002813 ** requested, return SQLITE_LOCKED.
danielk1977aef0bf62005-12-30 16:28:01 +00002814 */
drhc9166342012-01-05 23:32:06 +00002815 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
2816 || (pBt->btsFlags & BTS_PENDING)!=0
2817 ){
danielk1977404ca072009-03-16 13:19:36 +00002818 pBlock = pBt->pWriter->db;
2819 }else if( wrflag>1 ){
danielk1977641b0f42007-12-21 04:47:25 +00002820 BtLock *pIter;
2821 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
2822 if( pIter->pBtree!=p ){
danielk1977404ca072009-03-16 13:19:36 +00002823 pBlock = pIter->pBtree->db;
2824 break;
danielk1977641b0f42007-12-21 04:47:25 +00002825 }
2826 }
2827 }
danielk1977404ca072009-03-16 13:19:36 +00002828 if( pBlock ){
2829 sqlite3ConnectionBlocked(p->db, pBlock);
2830 rc = SQLITE_LOCKED_SHAREDCACHE;
2831 goto trans_begun;
2832 }
danielk1977641b0f42007-12-21 04:47:25 +00002833#endif
2834
danielk1977602b4662009-07-02 07:47:33 +00002835 /* Any read-only or read-write transaction implies a read-lock on
2836 ** page 1. So if some other shared-cache client already has a write-lock
2837 ** on page 1, the transaction cannot be opened. */
drh4c301aa2009-07-15 17:25:45 +00002838 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
2839 if( SQLITE_OK!=rc ) goto trans_begun;
danielk1977602b4662009-07-02 07:47:33 +00002840
drhc9166342012-01-05 23:32:06 +00002841 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
2842 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
drhb8ef32c2005-03-14 02:01:49 +00002843 do {
danielk1977295dc102009-04-01 19:07:03 +00002844 /* Call lockBtree() until either pBt->pPage1 is populated or
2845 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
2846 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
2847 ** reading page 1 it discovers that the page-size of the database
2848 ** file is not pBt->pageSize. In this case lockBtree() will update
2849 ** pBt->pageSize to the page-size of the file on disk.
2850 */
2851 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
drh309169a2007-04-24 17:27:51 +00002852
drhb8ef32c2005-03-14 02:01:49 +00002853 if( rc==SQLITE_OK && wrflag ){
drhc9166342012-01-05 23:32:06 +00002854 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
drh309169a2007-04-24 17:27:51 +00002855 rc = SQLITE_READONLY;
2856 }else{
danielk1977d8293352009-04-30 09:10:37 +00002857 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
drh309169a2007-04-24 17:27:51 +00002858 if( rc==SQLITE_OK ){
2859 rc = newDatabase(pBt);
2860 }
drhb8ef32c2005-03-14 02:01:49 +00002861 }
2862 }
2863
danielk1977bd434552009-03-18 10:33:00 +00002864 if( rc!=SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00002865 unlockBtreeIfUnused(pBt);
2866 }
danf9b76712010-06-01 14:12:45 +00002867 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
danielk19771ceedd32008-11-19 10:22:33 +00002868 btreeInvokeBusyHandler(pBt) );
danielk1977aef0bf62005-12-30 16:28:01 +00002869
2870 if( rc==SQLITE_OK ){
2871 if( p->inTrans==TRANS_NONE ){
2872 pBt->nTransaction++;
danielk1977602b4662009-07-02 07:47:33 +00002873#ifndef SQLITE_OMIT_SHARED_CACHE
2874 if( p->sharable ){
drhf2f105d2012-08-20 15:53:54 +00002875 assert( p->lock.pBtree==p && p->lock.iTable==1 );
danielk1977602b4662009-07-02 07:47:33 +00002876 p->lock.eLock = READ_LOCK;
2877 p->lock.pNext = pBt->pLock;
2878 pBt->pLock = &p->lock;
2879 }
2880#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002881 }
2882 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2883 if( p->inTrans>pBt->inTransaction ){
2884 pBt->inTransaction = p->inTrans;
2885 }
danielk1977404ca072009-03-16 13:19:36 +00002886 if( wrflag ){
dan59257dc2010-08-04 11:34:31 +00002887 MemPage *pPage1 = pBt->pPage1;
2888#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977404ca072009-03-16 13:19:36 +00002889 assert( !pBt->pWriter );
2890 pBt->pWriter = p;
drhc9166342012-01-05 23:32:06 +00002891 pBt->btsFlags &= ~BTS_EXCLUSIVE;
2892 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
danielk1977641b0f42007-12-21 04:47:25 +00002893#endif
dan59257dc2010-08-04 11:34:31 +00002894
2895 /* If the db-size header field is incorrect (as it may be if an old
2896 ** client has been writing the database file), update it now. Doing
2897 ** this sooner rather than later means the database size can safely
2898 ** re-read the database size from page 1 if a savepoint or transaction
2899 ** rollback occurs within the transaction.
2900 */
2901 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
2902 rc = sqlite3PagerWrite(pPage1->pDbPage);
2903 if( rc==SQLITE_OK ){
2904 put4byte(&pPage1->aData[28], pBt->nPage);
2905 }
2906 }
2907 }
danielk1977aef0bf62005-12-30 16:28:01 +00002908 }
2909
drhd677b3d2007-08-20 22:48:41 +00002910
2911trans_begun:
danielk1977fd7f0452008-12-17 17:30:26 +00002912 if( rc==SQLITE_OK && wrflag ){
danielk197712dd5492008-12-18 15:45:07 +00002913 /* This call makes sure that the pager has the correct number of
2914 ** open savepoints. If the second parameter is greater than 0 and
2915 ** the sub-journal is not already open, then it will be opened here.
2916 */
danielk1977fd7f0452008-12-17 17:30:26 +00002917 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
2918 }
danielk197712dd5492008-12-18 15:45:07 +00002919
danielk1977aef0bf62005-12-30 16:28:01 +00002920 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002921 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00002922 return rc;
drha059ad02001-04-17 20:09:11 +00002923}
2924
danielk1977687566d2004-11-02 12:56:41 +00002925#ifndef SQLITE_OMIT_AUTOVACUUM
2926
2927/*
2928** Set the pointer-map entries for all children of page pPage. Also, if
2929** pPage contains cells that point to overflow pages, set the pointer
2930** map entries for the overflow pages as well.
2931*/
2932static int setChildPtrmaps(MemPage *pPage){
2933 int i; /* Counter variable */
2934 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00002935 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00002936 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00002937 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002938 Pgno pgno = pPage->pgno;
2939
drh1fee73e2007-08-29 04:00:57 +00002940 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197730548662009-07-09 05:07:37 +00002941 rc = btreeInitPage(pPage);
danielk19772df71c72007-05-24 07:22:42 +00002942 if( rc!=SQLITE_OK ){
2943 goto set_child_ptrmaps_out;
2944 }
danielk1977687566d2004-11-02 12:56:41 +00002945 nCell = pPage->nCell;
2946
2947 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002948 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002949
drh98add2e2009-07-20 17:11:49 +00002950 ptrmapPutOvflPtr(pPage, pCell, &rc);
danielk197726836652005-01-17 01:33:13 +00002951
danielk1977687566d2004-11-02 12:56:41 +00002952 if( !pPage->leaf ){
2953 Pgno childPgno = get4byte(pCell);
drh98add2e2009-07-20 17:11:49 +00002954 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00002955 }
2956 }
2957
2958 if( !pPage->leaf ){
2959 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh98add2e2009-07-20 17:11:49 +00002960 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00002961 }
2962
2963set_child_ptrmaps_out:
2964 pPage->isInit = isInitOrig;
2965 return rc;
2966}
2967
2968/*
drhf3aed592009-07-08 18:12:49 +00002969** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
2970** that it points to iTo. Parameter eType describes the type of pointer to
2971** be modified, as follows:
danielk1977687566d2004-11-02 12:56:41 +00002972**
2973** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2974** page of pPage.
2975**
2976** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2977** page pointed to by one of the cells on pPage.
2978**
2979** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2980** overflow page in the list.
2981*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00002982static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00002983 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00002984 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977687566d2004-11-02 12:56:41 +00002985 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00002986 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00002987 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00002988 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002989 }
danielk1977f78fc082004-11-02 14:40:32 +00002990 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00002991 }else{
drhf49661a2008-12-10 16:45:50 +00002992 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002993 int i;
2994 int nCell;
2995
danielk197730548662009-07-09 05:07:37 +00002996 btreeInitPage(pPage);
danielk1977687566d2004-11-02 12:56:41 +00002997 nCell = pPage->nCell;
2998
danielk1977687566d2004-11-02 12:56:41 +00002999 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00003000 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00003001 if( eType==PTRMAP_OVERFLOW1 ){
3002 CellInfo info;
danielk197730548662009-07-09 05:07:37 +00003003 btreeParseCellPtr(pPage, pCell, &info);
drhe42a9b42011-08-31 13:27:19 +00003004 if( info.iOverflow
3005 && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
3006 && iFrom==get4byte(&pCell[info.iOverflow])
3007 ){
3008 put4byte(&pCell[info.iOverflow], iTo);
3009 break;
danielk1977687566d2004-11-02 12:56:41 +00003010 }
3011 }else{
3012 if( get4byte(pCell)==iFrom ){
3013 put4byte(pCell, iTo);
3014 break;
3015 }
3016 }
3017 }
3018
3019 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00003020 if( eType!=PTRMAP_BTREE ||
3021 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00003022 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00003023 }
danielk1977687566d2004-11-02 12:56:41 +00003024 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3025 }
3026
3027 pPage->isInit = isInitOrig;
3028 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00003029 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00003030}
3031
danielk1977003ba062004-11-04 02:57:33 +00003032
danielk19777701e812005-01-10 12:59:51 +00003033/*
3034** Move the open database page pDbPage to location iFreePage in the
3035** database. The pDbPage reference remains valid.
drhe64ca7b2009-07-16 18:21:17 +00003036**
3037** The isCommit flag indicates that there is no need to remember that
3038** the journal needs to be sync()ed before database page pDbPage->pgno
3039** can be written to. The caller has already promised not to write to that
3040** page.
danielk19777701e812005-01-10 12:59:51 +00003041*/
danielk1977003ba062004-11-04 02:57:33 +00003042static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00003043 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00003044 MemPage *pDbPage, /* Open page to move */
3045 u8 eType, /* Pointer map 'type' entry for pDbPage */
3046 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00003047 Pgno iFreePage, /* The location to move pDbPage to */
drhe64ca7b2009-07-16 18:21:17 +00003048 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
danielk1977003ba062004-11-04 02:57:33 +00003049){
3050 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
3051 Pgno iDbPage = pDbPage->pgno;
3052 Pager *pPager = pBt->pPager;
3053 int rc;
3054
danielk1977a0bf2652004-11-04 14:30:04 +00003055 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3056 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00003057 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00003058 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00003059
drh85b623f2007-12-13 21:54:09 +00003060 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00003061 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
3062 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00003063 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00003064 if( rc!=SQLITE_OK ){
3065 return rc;
3066 }
3067 pDbPage->pgno = iFreePage;
3068
3069 /* If pDbPage was a btree-page, then it may have child pages and/or cells
3070 ** that point to overflow pages. The pointer map entries for all these
3071 ** pages need to be changed.
3072 **
3073 ** If pDbPage is an overflow page, then the first 4 bytes may store a
3074 ** pointer to a subsequent overflow page. If this is the case, then
3075 ** the pointer map needs to be updated for the subsequent overflow page.
3076 */
danielk1977a0bf2652004-11-04 14:30:04 +00003077 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00003078 rc = setChildPtrmaps(pDbPage);
3079 if( rc!=SQLITE_OK ){
3080 return rc;
3081 }
3082 }else{
3083 Pgno nextOvfl = get4byte(pDbPage->aData);
3084 if( nextOvfl!=0 ){
drh98add2e2009-07-20 17:11:49 +00003085 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
danielk1977003ba062004-11-04 02:57:33 +00003086 if( rc!=SQLITE_OK ){
3087 return rc;
3088 }
3089 }
3090 }
3091
3092 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3093 ** that it points at iFreePage. Also fix the pointer map entry for
3094 ** iPtrPage.
3095 */
danielk1977a0bf2652004-11-04 14:30:04 +00003096 if( eType!=PTRMAP_ROOTPAGE ){
drhb00fc3b2013-08-21 23:42:32 +00003097 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00003098 if( rc!=SQLITE_OK ){
3099 return rc;
3100 }
danielk19773b8a05f2007-03-19 17:44:26 +00003101 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00003102 if( rc!=SQLITE_OK ){
3103 releasePage(pPtrPage);
3104 return rc;
3105 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00003106 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00003107 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003108 if( rc==SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00003109 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003110 }
danielk1977003ba062004-11-04 02:57:33 +00003111 }
danielk1977003ba062004-11-04 02:57:33 +00003112 return rc;
3113}
3114
danielk1977dddbcdc2007-04-26 14:42:34 +00003115/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00003116static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00003117
3118/*
dan51f0b6d2013-02-22 20:16:34 +00003119** Perform a single step of an incremental-vacuum. If successful, return
3120** SQLITE_OK. If there is no work to do (and therefore no point in
3121** calling this function again), return SQLITE_DONE. Or, if an error
3122** occurs, return some other error code.
danielk1977dddbcdc2007-04-26 14:42:34 +00003123**
peter.d.reid60ec9142014-09-06 16:39:46 +00003124** More specifically, this function attempts to re-organize the database so
dan51f0b6d2013-02-22 20:16:34 +00003125** that the last page of the file currently in use is no longer in use.
danielk1977dddbcdc2007-04-26 14:42:34 +00003126**
dan51f0b6d2013-02-22 20:16:34 +00003127** Parameter nFin is the number of pages that this database would contain
3128** were this function called until it returns SQLITE_DONE.
3129**
3130** If the bCommit parameter is non-zero, this function assumes that the
3131** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
peter.d.reid60ec9142014-09-06 16:39:46 +00003132** or an error. bCommit is passed true for an auto-vacuum-on-commit
dan51f0b6d2013-02-22 20:16:34 +00003133** operation, or false for an incremental vacuum.
danielk1977dddbcdc2007-04-26 14:42:34 +00003134*/
dan51f0b6d2013-02-22 20:16:34 +00003135static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
danielk1977dddbcdc2007-04-26 14:42:34 +00003136 Pgno nFreeList; /* Number of pages still on the free-list */
drhdd3cd972010-03-27 17:12:36 +00003137 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003138
drh1fee73e2007-08-29 04:00:57 +00003139 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977fa542f12009-04-02 18:28:08 +00003140 assert( iLastPg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00003141
3142 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003143 u8 eType;
3144 Pgno iPtrPage;
3145
3146 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977fa542f12009-04-02 18:28:08 +00003147 if( nFreeList==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003148 return SQLITE_DONE;
3149 }
3150
3151 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3152 if( rc!=SQLITE_OK ){
3153 return rc;
3154 }
3155 if( eType==PTRMAP_ROOTPAGE ){
3156 return SQLITE_CORRUPT_BKPT;
3157 }
3158
3159 if( eType==PTRMAP_FREEPAGE ){
dan51f0b6d2013-02-22 20:16:34 +00003160 if( bCommit==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003161 /* Remove the page from the files free-list. This is not required
dan51f0b6d2013-02-22 20:16:34 +00003162 ** if bCommit is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00003163 ** truncated to zero after this function returns, so it doesn't
3164 ** matter if it still contains some garbage entries.
3165 */
3166 Pgno iFreePg;
3167 MemPage *pFreePg;
dan51f0b6d2013-02-22 20:16:34 +00003168 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
danielk1977dddbcdc2007-04-26 14:42:34 +00003169 if( rc!=SQLITE_OK ){
3170 return rc;
3171 }
3172 assert( iFreePg==iLastPg );
3173 releasePage(pFreePg);
3174 }
3175 } else {
3176 Pgno iFreePg; /* Index of free page to move pLastPg to */
3177 MemPage *pLastPg;
dan51f0b6d2013-02-22 20:16:34 +00003178 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
3179 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
danielk1977dddbcdc2007-04-26 14:42:34 +00003180
drhb00fc3b2013-08-21 23:42:32 +00003181 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00003182 if( rc!=SQLITE_OK ){
3183 return rc;
3184 }
3185
dan51f0b6d2013-02-22 20:16:34 +00003186 /* If bCommit is zero, this loop runs exactly once and page pLastPg
danielk1977b4626a32007-04-28 15:47:43 +00003187 ** is swapped with the first free page pulled off the free list.
3188 **
dan51f0b6d2013-02-22 20:16:34 +00003189 ** On the other hand, if bCommit is greater than zero, then keep
danielk1977b4626a32007-04-28 15:47:43 +00003190 ** looping until a free-page located within the first nFin pages
3191 ** of the file is found.
3192 */
dan51f0b6d2013-02-22 20:16:34 +00003193 if( bCommit==0 ){
3194 eMode = BTALLOC_LE;
3195 iNear = nFin;
3196 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003197 do {
3198 MemPage *pFreePg;
dan51f0b6d2013-02-22 20:16:34 +00003199 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
danielk1977dddbcdc2007-04-26 14:42:34 +00003200 if( rc!=SQLITE_OK ){
3201 releasePage(pLastPg);
3202 return rc;
3203 }
3204 releasePage(pFreePg);
dan51f0b6d2013-02-22 20:16:34 +00003205 }while( bCommit && iFreePg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00003206 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00003207
dane1df4e32013-03-05 11:27:04 +00003208 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
danielk1977dddbcdc2007-04-26 14:42:34 +00003209 releasePage(pLastPg);
3210 if( rc!=SQLITE_OK ){
3211 return rc;
danielk1977662278e2007-11-05 15:30:12 +00003212 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003213 }
3214 }
3215
dan51f0b6d2013-02-22 20:16:34 +00003216 if( bCommit==0 ){
danbc1a3c62013-02-23 16:40:46 +00003217 do {
danielk19773460d192008-12-27 15:23:13 +00003218 iLastPg--;
danbc1a3c62013-02-23 16:40:46 +00003219 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
3220 pBt->bDoTruncate = 1;
drhdd3cd972010-03-27 17:12:36 +00003221 pBt->nPage = iLastPg;
danielk1977dddbcdc2007-04-26 14:42:34 +00003222 }
3223 return SQLITE_OK;
3224}
3225
3226/*
dan51f0b6d2013-02-22 20:16:34 +00003227** The database opened by the first argument is an auto-vacuum database
3228** nOrig pages in size containing nFree free pages. Return the expected
3229** size of the database in pages following an auto-vacuum operation.
3230*/
3231static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
3232 int nEntry; /* Number of entries on one ptrmap page */
3233 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
3234 Pgno nFin; /* Return value */
3235
3236 nEntry = pBt->usableSize/5;
3237 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
3238 nFin = nOrig - nFree - nPtrmap;
3239 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
3240 nFin--;
3241 }
3242 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3243 nFin--;
3244 }
dan51f0b6d2013-02-22 20:16:34 +00003245
3246 return nFin;
3247}
3248
3249/*
danielk1977dddbcdc2007-04-26 14:42:34 +00003250** A write-transaction must be opened before calling this function.
3251** It performs a single unit of work towards an incremental vacuum.
3252**
3253** If the incremental vacuum is finished after this function has run,
shanebe217792009-03-05 04:20:31 +00003254** SQLITE_DONE is returned. If it is not finished, but no error occurred,
danielk1977dddbcdc2007-04-26 14:42:34 +00003255** SQLITE_OK is returned. Otherwise an SQLite error code.
3256*/
3257int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00003258 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003259 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003260
3261 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00003262 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
3263 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00003264 rc = SQLITE_DONE;
3265 }else{
dan51f0b6d2013-02-22 20:16:34 +00003266 Pgno nOrig = btreePagecount(pBt);
3267 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
3268 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
3269
dan91384712013-02-24 11:50:43 +00003270 if( nOrig<nFin ){
3271 rc = SQLITE_CORRUPT_BKPT;
3272 }else if( nFree>0 ){
dan11dcd112013-03-15 18:29:18 +00003273 rc = saveAllCursors(pBt, 0, 0);
3274 if( rc==SQLITE_OK ){
3275 invalidateAllOverflowCache(pBt);
3276 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
3277 }
dan51f0b6d2013-02-22 20:16:34 +00003278 if( rc==SQLITE_OK ){
3279 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3280 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
3281 }
3282 }else{
3283 rc = SQLITE_DONE;
drhdd3cd972010-03-27 17:12:36 +00003284 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003285 }
drhd677b3d2007-08-20 22:48:41 +00003286 sqlite3BtreeLeave(p);
3287 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003288}
3289
3290/*
danielk19773b8a05f2007-03-19 17:44:26 +00003291** This routine is called prior to sqlite3PagerCommit when a transaction
drhf7b54962013-05-28 12:11:54 +00003292** is committed for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00003293**
3294** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
3295** the database file should be truncated to during the commit process.
3296** i.e. the database has been reorganized so that only the first *pnTrunc
3297** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00003298*/
danielk19773460d192008-12-27 15:23:13 +00003299static int autoVacuumCommit(BtShared *pBt){
danielk1977dddbcdc2007-04-26 14:42:34 +00003300 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00003301 Pager *pPager = pBt->pPager;
drhf94a1732008-09-30 17:18:17 +00003302 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00003303
drh1fee73e2007-08-29 04:00:57 +00003304 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00003305 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00003306 assert(pBt->autoVacuum);
3307 if( !pBt->incrVacuum ){
drhea8ffdf2009-07-22 00:35:23 +00003308 Pgno nFin; /* Number of pages in database after autovacuuming */
3309 Pgno nFree; /* Number of pages on the freelist initially */
drh41d628c2009-07-11 17:04:08 +00003310 Pgno iFree; /* The next page to be freed */
drh41d628c2009-07-11 17:04:08 +00003311 Pgno nOrig; /* Database size before freeing */
danielk1977687566d2004-11-02 12:56:41 +00003312
drhb1299152010-03-30 22:58:33 +00003313 nOrig = btreePagecount(pBt);
danielk1977ef165ce2009-04-06 17:50:03 +00003314 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
3315 /* It is not possible to create a database for which the final page
3316 ** is either a pointer-map page or the pending-byte page. If one
3317 ** is encountered, this indicates corruption.
3318 */
danielk19773460d192008-12-27 15:23:13 +00003319 return SQLITE_CORRUPT_BKPT;
3320 }
danielk1977ef165ce2009-04-06 17:50:03 +00003321
danielk19773460d192008-12-27 15:23:13 +00003322 nFree = get4byte(&pBt->pPage1->aData[36]);
dan51f0b6d2013-02-22 20:16:34 +00003323 nFin = finalDbSize(pBt, nOrig, nFree);
drhc5e47ac2009-06-04 00:11:56 +00003324 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
dan0aed84d2013-03-26 14:16:20 +00003325 if( nFin<nOrig ){
3326 rc = saveAllCursors(pBt, 0, 0);
3327 }
danielk19773460d192008-12-27 15:23:13 +00003328 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
dan51f0b6d2013-02-22 20:16:34 +00003329 rc = incrVacuumStep(pBt, nFin, iFree, 1);
danielk1977dddbcdc2007-04-26 14:42:34 +00003330 }
danielk19773460d192008-12-27 15:23:13 +00003331 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
danielk19773460d192008-12-27 15:23:13 +00003332 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3333 put4byte(&pBt->pPage1->aData[32], 0);
3334 put4byte(&pBt->pPage1->aData[36], 0);
drhdd3cd972010-03-27 17:12:36 +00003335 put4byte(&pBt->pPage1->aData[28], nFin);
danbc1a3c62013-02-23 16:40:46 +00003336 pBt->bDoTruncate = 1;
drhdd3cd972010-03-27 17:12:36 +00003337 pBt->nPage = nFin;
danielk1977dddbcdc2007-04-26 14:42:34 +00003338 }
3339 if( rc!=SQLITE_OK ){
3340 sqlite3PagerRollback(pPager);
3341 }
danielk1977687566d2004-11-02 12:56:41 +00003342 }
3343
dan0aed84d2013-03-26 14:16:20 +00003344 assert( nRef>=sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00003345 return rc;
3346}
danielk1977dddbcdc2007-04-26 14:42:34 +00003347
danielk1977a50d9aa2009-06-08 14:49:45 +00003348#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
3349# define setChildPtrmaps(x) SQLITE_OK
3350#endif
danielk1977687566d2004-11-02 12:56:41 +00003351
3352/*
drh80e35f42007-03-30 14:06:34 +00003353** This routine does the first phase of a two-phase commit. This routine
3354** causes a rollback journal to be created (if it does not already exist)
3355** and populated with enough information so that if a power loss occurs
3356** the database can be restored to its original state by playing back
3357** the journal. Then the contents of the journal are flushed out to
3358** the disk. After the journal is safely on oxide, the changes to the
3359** database are written into the database file and flushed to oxide.
3360** At the end of this call, the rollback journal still exists on the
3361** disk and we are still holding all locks, so the transaction has not
drh51898cf2009-04-19 20:51:06 +00003362** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
drh80e35f42007-03-30 14:06:34 +00003363** commit process.
3364**
3365** This call is a no-op if no write-transaction is currently active on pBt.
3366**
3367** Otherwise, sync the database file for the btree pBt. zMaster points to
3368** the name of a master journal file that should be written into the
3369** individual journal file, or is NULL, indicating no master journal file
3370** (single database transaction).
3371**
3372** When this is called, the master journal should already have been
3373** created, populated with this journal pointer and synced to disk.
3374**
3375** Once this is routine has returned, the only thing required to commit
3376** the write-transaction for this database file is to delete the journal.
3377*/
3378int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
3379 int rc = SQLITE_OK;
3380 if( p->inTrans==TRANS_WRITE ){
3381 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003382 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00003383#ifndef SQLITE_OMIT_AUTOVACUUM
3384 if( pBt->autoVacuum ){
danielk19773460d192008-12-27 15:23:13 +00003385 rc = autoVacuumCommit(pBt);
drh80e35f42007-03-30 14:06:34 +00003386 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00003387 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003388 return rc;
3389 }
3390 }
danbc1a3c62013-02-23 16:40:46 +00003391 if( pBt->bDoTruncate ){
3392 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
3393 }
drh80e35f42007-03-30 14:06:34 +00003394#endif
drh49b9d332009-01-02 18:10:42 +00003395 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
drhd677b3d2007-08-20 22:48:41 +00003396 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003397 }
3398 return rc;
3399}
3400
3401/*
danielk197794b30732009-07-02 17:21:57 +00003402** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
3403** at the conclusion of a transaction.
3404*/
3405static void btreeEndTransaction(Btree *p){
3406 BtShared *pBt = p->pBt;
drh1713afb2013-06-28 01:24:57 +00003407 sqlite3 *db = p->db;
danielk197794b30732009-07-02 17:21:57 +00003408 assert( sqlite3BtreeHoldsMutex(p) );
3409
danbc1a3c62013-02-23 16:40:46 +00003410#ifndef SQLITE_OMIT_AUTOVACUUM
3411 pBt->bDoTruncate = 0;
3412#endif
danc0537fe2013-06-28 19:41:43 +00003413 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
danfa401de2009-10-16 14:55:03 +00003414 /* If there are other active statements that belong to this database
3415 ** handle, downgrade to a read-only transaction. The other statements
3416 ** may still be reading from the database. */
danielk197794b30732009-07-02 17:21:57 +00003417 downgradeAllSharedCacheTableLocks(p);
3418 p->inTrans = TRANS_READ;
3419 }else{
3420 /* If the handle had any kind of transaction open, decrement the
3421 ** transaction count of the shared btree. If the transaction count
3422 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
3423 ** call below will unlock the pager. */
3424 if( p->inTrans!=TRANS_NONE ){
3425 clearAllSharedCacheTableLocks(p);
3426 pBt->nTransaction--;
3427 if( 0==pBt->nTransaction ){
3428 pBt->inTransaction = TRANS_NONE;
3429 }
3430 }
3431
3432 /* Set the current transaction state to TRANS_NONE and unlock the
3433 ** pager if this call closed the only read or write transaction. */
3434 p->inTrans = TRANS_NONE;
3435 unlockBtreeIfUnused(pBt);
3436 }
3437
3438 btreeIntegrity(p);
3439}
3440
3441/*
drh2aa679f2001-06-25 02:11:07 +00003442** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00003443**
drh6e345992007-03-30 11:12:08 +00003444** This routine implements the second phase of a 2-phase commit. The
drh51898cf2009-04-19 20:51:06 +00003445** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
3446** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
3447** routine did all the work of writing information out to disk and flushing the
drh6e345992007-03-30 11:12:08 +00003448** contents so that they are written onto the disk platter. All this
drh51898cf2009-04-19 20:51:06 +00003449** routine has to do is delete or truncate or zero the header in the
3450** the rollback journal (which causes the transaction to commit) and
3451** drop locks.
drh6e345992007-03-30 11:12:08 +00003452**
dan60939d02011-03-29 15:40:55 +00003453** Normally, if an error occurs while the pager layer is attempting to
3454** finalize the underlying journal file, this function returns an error and
3455** the upper layer will attempt a rollback. However, if the second argument
3456** is non-zero then this b-tree transaction is part of a multi-file
3457** transaction. In this case, the transaction has already been committed
3458** (by deleting a master journal file) and the caller will ignore this
3459** functions return code. So, even if an error occurs in the pager layer,
3460** reset the b-tree objects internal state to indicate that the write
3461** transaction has been closed. This is quite safe, as the pager will have
3462** transitioned to the error state.
3463**
drh5e00f6c2001-09-13 13:46:56 +00003464** This will release the write lock on the database file. If there
3465** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00003466*/
dan60939d02011-03-29 15:40:55 +00003467int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
danielk1977aef0bf62005-12-30 16:28:01 +00003468
drh075ed302010-10-14 01:17:30 +00003469 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003470 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003471 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003472
3473 /* If the handle has a write-transaction open, commit the shared-btrees
3474 ** transaction and set the shared state to TRANS_READ.
3475 */
3476 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00003477 int rc;
drh075ed302010-10-14 01:17:30 +00003478 BtShared *pBt = p->pBt;
danielk1977aef0bf62005-12-30 16:28:01 +00003479 assert( pBt->inTransaction==TRANS_WRITE );
3480 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00003481 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
dan60939d02011-03-29 15:40:55 +00003482 if( rc!=SQLITE_OK && bCleanup==0 ){
drhd677b3d2007-08-20 22:48:41 +00003483 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00003484 return rc;
3485 }
danielk1977aef0bf62005-12-30 16:28:01 +00003486 pBt->inTransaction = TRANS_READ;
danbf0e57a2013-05-14 20:36:31 +00003487 btreeClearHasContent(pBt);
danielk1977ee5741e2004-05-31 10:01:34 +00003488 }
danielk1977aef0bf62005-12-30 16:28:01 +00003489
danielk197794b30732009-07-02 17:21:57 +00003490 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00003491 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00003492 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003493}
3494
drh80e35f42007-03-30 14:06:34 +00003495/*
3496** Do both phases of a commit.
3497*/
3498int sqlite3BtreeCommit(Btree *p){
3499 int rc;
drhd677b3d2007-08-20 22:48:41 +00003500 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00003501 rc = sqlite3BtreeCommitPhaseOne(p, 0);
3502 if( rc==SQLITE_OK ){
dan60939d02011-03-29 15:40:55 +00003503 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
drh80e35f42007-03-30 14:06:34 +00003504 }
drhd677b3d2007-08-20 22:48:41 +00003505 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003506 return rc;
3507}
3508
drhc39e0002004-05-07 23:50:57 +00003509/*
drhfb982642007-08-30 01:19:59 +00003510** This routine sets the state to CURSOR_FAULT and the error
3511** code to errCode for every cursor on BtShared that pBtree
3512** references.
3513**
3514** Every cursor is tripped, including cursors that belong
3515** to other database connections that happen to be sharing
3516** the cache with pBtree.
3517**
3518** This routine gets called when a rollback occurs.
3519** All cursors using the same cache must be tripped
3520** to prevent them from trying to use the btree after
3521** the rollback. The rollback may have deleted tables
3522** or moved root pages, so it is not sufficient to
3523** save the state of the cursor. The cursor must be
3524** invalidated.
3525*/
3526void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
3527 BtCursor *p;
drh0f198a72012-02-13 16:43:16 +00003528 if( pBtree==0 ) return;
drhfb982642007-08-30 01:19:59 +00003529 sqlite3BtreeEnter(pBtree);
3530 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
danielk1977bc2ca9e2008-11-13 14:28:28 +00003531 int i;
danielk1977be51a652008-10-08 17:58:48 +00003532 sqlite3BtreeClearCursor(p);
drhfb982642007-08-30 01:19:59 +00003533 p->eState = CURSOR_FAULT;
drh4c301aa2009-07-15 17:25:45 +00003534 p->skipNext = errCode;
danielk1977bc2ca9e2008-11-13 14:28:28 +00003535 for(i=0; i<=p->iPage; i++){
3536 releasePage(p->apPage[i]);
3537 p->apPage[i] = 0;
3538 }
drhfb982642007-08-30 01:19:59 +00003539 }
3540 sqlite3BtreeLeave(pBtree);
3541}
3542
3543/*
drhecdc7532001-09-23 02:35:53 +00003544** Rollback the transaction in progress. All cursors will be
3545** invalided by this operation. Any attempt to use a cursor
3546** that was open at the beginning of this operation will result
3547** in an error.
drh5e00f6c2001-09-13 13:46:56 +00003548**
3549** This will release the write lock on the database file. If there
3550** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00003551*/
drh0f198a72012-02-13 16:43:16 +00003552int sqlite3BtreeRollback(Btree *p, int tripCode){
danielk19778d34dfd2006-01-24 16:37:57 +00003553 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003554 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00003555 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00003556
drhd677b3d2007-08-20 22:48:41 +00003557 sqlite3BtreeEnter(p);
drh0f198a72012-02-13 16:43:16 +00003558 if( tripCode==SQLITE_OK ){
3559 rc = tripCode = saveAllCursors(pBt, 0, 0);
3560 }else{
3561 rc = SQLITE_OK;
danielk19772b8c13e2006-01-24 14:21:24 +00003562 }
drh0f198a72012-02-13 16:43:16 +00003563 if( tripCode ){
3564 sqlite3BtreeTripAllCursors(p, tripCode);
3565 }
danielk1977aef0bf62005-12-30 16:28:01 +00003566 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003567
3568 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00003569 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00003570
danielk19778d34dfd2006-01-24 16:37:57 +00003571 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00003572 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00003573 if( rc2!=SQLITE_OK ){
3574 rc = rc2;
3575 }
3576
drh24cd67e2004-05-10 16:18:47 +00003577 /* The rollback may have destroyed the pPage1->aData value. So
danielk197730548662009-07-09 05:07:37 +00003578 ** call btreeGetPage() on page 1 again to make
drh16a9b832007-05-05 18:39:25 +00003579 ** sure pPage1->aData is set correctly. */
drhb00fc3b2013-08-21 23:42:32 +00003580 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh1f5b4672010-04-01 02:22:19 +00003581 int nPage = get4byte(28+(u8*)pPage1->aData);
3582 testcase( nPage==0 );
3583 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
3584 testcase( pBt->nPage!=nPage );
3585 pBt->nPage = nPage;
drh24cd67e2004-05-10 16:18:47 +00003586 releasePage(pPage1);
3587 }
drh85ec3b62013-05-14 23:12:06 +00003588 assert( countValidCursors(pBt, 1)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00003589 pBt->inTransaction = TRANS_READ;
danbf0e57a2013-05-14 20:36:31 +00003590 btreeClearHasContent(pBt);
drh24cd67e2004-05-10 16:18:47 +00003591 }
danielk1977aef0bf62005-12-30 16:28:01 +00003592
danielk197794b30732009-07-02 17:21:57 +00003593 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00003594 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00003595 return rc;
3596}
3597
3598/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003599** Start a statement subtransaction. The subtransaction can be rolled
danielk1977bd434552009-03-18 10:33:00 +00003600** back independently of the main transaction. You must start a transaction
3601** before starting a subtransaction. The subtransaction is ended automatically
3602** if the main transaction commits or rolls back.
drhab01f612004-05-22 02:55:23 +00003603**
3604** Statement subtransactions are used around individual SQL statements
3605** that are contained within a BEGIN...COMMIT block. If a constraint
3606** error occurs within the statement, the effect of that one statement
3607** can be rolled back without having to rollback the entire transaction.
danielk1977bd434552009-03-18 10:33:00 +00003608**
3609** A statement sub-transaction is implemented as an anonymous savepoint. The
3610** value passed as the second parameter is the total number of savepoints,
3611** including the new anonymous savepoint, open on the B-Tree. i.e. if there
3612** are no active savepoints and no other statement-transactions open,
3613** iStatement is 1. This anonymous savepoint can be released or rolled back
3614** using the sqlite3BtreeSavepoint() function.
drh663fc632002-02-02 18:49:19 +00003615*/
danielk1977bd434552009-03-18 10:33:00 +00003616int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
drh663fc632002-02-02 18:49:19 +00003617 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003618 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003619 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00003620 assert( p->inTrans==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00003621 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk1977bd434552009-03-18 10:33:00 +00003622 assert( iStatement>0 );
3623 assert( iStatement>p->db->nSavepoint );
drh5e0ccc22010-03-29 19:36:52 +00003624 assert( pBt->inTransaction==TRANS_WRITE );
3625 /* At the pager level, a statement transaction is a savepoint with
3626 ** an index greater than all savepoints created explicitly using
3627 ** SQL statements. It is illegal to open, release or rollback any
3628 ** such savepoints while the statement transaction savepoint is active.
3629 */
3630 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
drhd677b3d2007-08-20 22:48:41 +00003631 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00003632 return rc;
3633}
3634
3635/*
danielk1977fd7f0452008-12-17 17:30:26 +00003636** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
3637** or SAVEPOINT_RELEASE. This function either releases or rolls back the
danielk197712dd5492008-12-18 15:45:07 +00003638** savepoint identified by parameter iSavepoint, depending on the value
3639** of op.
3640**
3641** Normally, iSavepoint is greater than or equal to zero. However, if op is
3642** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
3643** contents of the entire transaction are rolled back. This is different
3644** from a normal transaction rollback, as no locks are released and the
3645** transaction remains open.
danielk1977fd7f0452008-12-17 17:30:26 +00003646*/
3647int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
3648 int rc = SQLITE_OK;
3649 if( p && p->inTrans==TRANS_WRITE ){
3650 BtShared *pBt = p->pBt;
danielk1977fd7f0452008-12-17 17:30:26 +00003651 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
3652 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
3653 sqlite3BtreeEnter(p);
danielk1977fd7f0452008-12-17 17:30:26 +00003654 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
drh9f0bbf92009-01-02 21:08:09 +00003655 if( rc==SQLITE_OK ){
drhc9166342012-01-05 23:32:06 +00003656 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
3657 pBt->nPage = 0;
3658 }
drh9f0bbf92009-01-02 21:08:09 +00003659 rc = newDatabase(pBt);
drhdd3cd972010-03-27 17:12:36 +00003660 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
drhb9b49bf2010-08-05 03:21:39 +00003661
3662 /* The database size was written into the offset 28 of the header
3663 ** when the transaction started, so we know that the value at offset
3664 ** 28 is nonzero. */
3665 assert( pBt->nPage>0 );
drh9f0bbf92009-01-02 21:08:09 +00003666 }
danielk1977fd7f0452008-12-17 17:30:26 +00003667 sqlite3BtreeLeave(p);
3668 }
3669 return rc;
3670}
3671
3672/*
drh8b2f49b2001-06-08 00:21:52 +00003673** Create a new cursor for the BTree whose root is on the page
danielk19773e8add92009-07-04 17:16:00 +00003674** iTable. If a read-only cursor is requested, it is assumed that
3675** the caller already has at least a read-only transaction open
3676** on the database already. If a write-cursor is requested, then
3677** the caller is assumed to have an open write transaction.
drh1bee3d72001-10-15 00:44:35 +00003678**
3679** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00003680** If wrFlag==1, then the cursor can be used for reading or for
3681** writing if other conditions for writing are also met. These
3682** are the conditions that must be met in order for writing to
3683** be allowed:
drh6446c4d2001-12-15 14:22:18 +00003684**
drhf74b8d92002-09-01 23:20:45 +00003685** 1: The cursor must have been opened with wrFlag==1
3686**
drhfe5d71d2007-03-19 11:54:10 +00003687** 2: Other database connections that share the same pager cache
3688** but which are not in the READ_UNCOMMITTED state may not have
3689** cursors open with wrFlag==0 on the same table. Otherwise
3690** the changes made by this write cursor would be visible to
3691** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00003692**
3693** 3: The database must be writable (not on read-only media)
3694**
3695** 4: There must be an active transaction.
3696**
drh6446c4d2001-12-15 14:22:18 +00003697** No checking is done to make sure that page iTable really is the
3698** root page of a b-tree. If it is not, then the cursor acquired
3699** will not work correctly.
danielk197771d5d2c2008-09-29 11:49:47 +00003700**
drhf25a5072009-11-18 23:01:25 +00003701** It is assumed that the sqlite3BtreeCursorZero() has been called
3702** on pCur to initialize the memory space prior to invoking this routine.
drha059ad02001-04-17 20:09:11 +00003703*/
drhd677b3d2007-08-20 22:48:41 +00003704static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00003705 Btree *p, /* The btree */
3706 int iTable, /* Root page of table to open */
3707 int wrFlag, /* 1 to write. 0 read-only */
3708 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
3709 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00003710){
danielk19773e8add92009-07-04 17:16:00 +00003711 BtShared *pBt = p->pBt; /* Shared b-tree handle */
drhecdc7532001-09-23 02:35:53 +00003712
drh1fee73e2007-08-29 04:00:57 +00003713 assert( sqlite3BtreeHoldsMutex(p) );
drhf49661a2008-12-10 16:45:50 +00003714 assert( wrFlag==0 || wrFlag==1 );
danielk197796d48e92009-06-29 06:00:37 +00003715
danielk1977602b4662009-07-02 07:47:33 +00003716 /* The following assert statements verify that if this is a sharable
3717 ** b-tree database, the connection is holding the required table locks,
3718 ** and that no other connection has any open cursor that conflicts with
3719 ** this lock. */
3720 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
danielk197796d48e92009-06-29 06:00:37 +00003721 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
3722
danielk19773e8add92009-07-04 17:16:00 +00003723 /* Assert that the caller has opened the required transaction. */
3724 assert( p->inTrans>TRANS_NONE );
3725 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
3726 assert( pBt->pPage1 && pBt->pPage1->aData );
3727
drhc9166342012-01-05 23:32:06 +00003728 if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
danielk197796d48e92009-06-29 06:00:37 +00003729 return SQLITE_READONLY;
drha0c9a112004-03-10 13:42:37 +00003730 }
drh3fbb0222014-09-24 19:47:27 +00003731 if( wrFlag ){
3732 allocateTempSpace(pBt);
3733 if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM;
3734 }
drhb1299152010-03-30 22:58:33 +00003735 if( iTable==1 && btreePagecount(pBt)==0 ){
dana205a482011-08-27 18:48:57 +00003736 assert( wrFlag==0 );
3737 iTable = 0;
danielk19773e8add92009-07-04 17:16:00 +00003738 }
danielk1977aef0bf62005-12-30 16:28:01 +00003739
danielk1977aef0bf62005-12-30 16:28:01 +00003740 /* Now that no other errors can occur, finish filling in the BtCursor
danielk19773e8add92009-07-04 17:16:00 +00003741 ** variables and link the cursor into the BtShared list. */
danielk1977172114a2009-07-07 15:47:12 +00003742 pCur->pgnoRoot = (Pgno)iTable;
3743 pCur->iPage = -1;
drh1e968a02008-03-25 00:22:21 +00003744 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00003745 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00003746 pCur->pBt = pBt;
drh4c417182014-03-31 23:57:41 +00003747 assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
3748 pCur->curFlags = wrFlag;
drha059ad02001-04-17 20:09:11 +00003749 pCur->pNext = pBt->pCursor;
3750 if( pCur->pNext ){
3751 pCur->pNext->pPrev = pCur;
3752 }
3753 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00003754 pCur->eState = CURSOR_INVALID;
danielk1977aef0bf62005-12-30 16:28:01 +00003755 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003756}
drhd677b3d2007-08-20 22:48:41 +00003757int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00003758 Btree *p, /* The btree */
3759 int iTable, /* Root page of table to open */
3760 int wrFlag, /* 1 to write. 0 read-only */
3761 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
3762 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00003763){
3764 int rc;
3765 sqlite3BtreeEnter(p);
danielk1977cd3e8f72008-03-25 09:47:35 +00003766 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
drhd677b3d2007-08-20 22:48:41 +00003767 sqlite3BtreeLeave(p);
3768 return rc;
3769}
drh7f751222009-03-17 22:33:00 +00003770
3771/*
3772** Return the size of a BtCursor object in bytes.
3773**
3774** This interfaces is needed so that users of cursors can preallocate
3775** sufficient storage to hold a cursor. The BtCursor object is opaque
3776** to users so they cannot do the sizeof() themselves - they must call
3777** this routine.
3778*/
3779int sqlite3BtreeCursorSize(void){
drhc54055b2009-11-13 17:05:53 +00003780 return ROUND8(sizeof(BtCursor));
danielk1977cd3e8f72008-03-25 09:47:35 +00003781}
3782
drh7f751222009-03-17 22:33:00 +00003783/*
drhf25a5072009-11-18 23:01:25 +00003784** Initialize memory that will be converted into a BtCursor object.
3785**
3786** The simple approach here would be to memset() the entire object
3787** to zero. But it turns out that the apPage[] and aiIdx[] arrays
3788** do not need to be zeroed and they are large, so we can save a lot
3789** of run-time by skipping the initialization of those elements.
3790*/
3791void sqlite3BtreeCursorZero(BtCursor *p){
3792 memset(p, 0, offsetof(BtCursor, iPage));
3793}
3794
3795/*
drh5e00f6c2001-09-13 13:46:56 +00003796** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00003797** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00003798*/
drh3aac2dd2004-04-26 14:10:20 +00003799int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00003800 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00003801 if( pBtree ){
danielk197771d5d2c2008-09-29 11:49:47 +00003802 int i;
danielk1977cd3e8f72008-03-25 09:47:35 +00003803 BtShared *pBt = pCur->pBt;
3804 sqlite3BtreeEnter(pBtree);
danielk1977be51a652008-10-08 17:58:48 +00003805 sqlite3BtreeClearCursor(pCur);
danielk1977cd3e8f72008-03-25 09:47:35 +00003806 if( pCur->pPrev ){
3807 pCur->pPrev->pNext = pCur->pNext;
3808 }else{
3809 pBt->pCursor = pCur->pNext;
3810 }
3811 if( pCur->pNext ){
3812 pCur->pNext->pPrev = pCur->pPrev;
3813 }
danielk197771d5d2c2008-09-29 11:49:47 +00003814 for(i=0; i<=pCur->iPage; i++){
3815 releasePage(pCur->apPage[i]);
3816 }
danielk1977cd3e8f72008-03-25 09:47:35 +00003817 unlockBtreeIfUnused(pBt);
dan5a500af2014-03-11 20:33:04 +00003818 sqlite3DbFree(pBtree->db, pCur->aOverflow);
danielk1977cd3e8f72008-03-25 09:47:35 +00003819 /* sqlite3_free(pCur); */
3820 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00003821 }
drh8c42ca92001-06-22 19:15:00 +00003822 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003823}
3824
drh5e2f8b92001-05-28 00:41:15 +00003825/*
drh86057612007-06-26 01:04:48 +00003826** Make sure the BtCursor* given in the argument has a valid
3827** BtCursor.info structure. If it is not already valid, call
danielk197730548662009-07-09 05:07:37 +00003828** btreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00003829**
3830** BtCursor.info is a cache of the information in the current cell.
danielk197730548662009-07-09 05:07:37 +00003831** Using this cache reduces the number of calls to btreeParseCell().
drh86057612007-06-26 01:04:48 +00003832**
3833** 2007-06-25: There is a bug in some versions of MSVC that cause the
3834** compiler to crash when getCellInfo() is implemented as a macro.
3835** But there is a measureable speed advantage to using the macro on gcc
3836** (when less compiler optimizations like -Os or -O0 are used and the
peter.d.reid60ec9142014-09-06 16:39:46 +00003837** compiler is not doing aggressive inlining.) So we use a real function
drh86057612007-06-26 01:04:48 +00003838** for MSVC and a macro for everything else. Ticket #2457.
drh9188b382004-05-14 21:12:22 +00003839*/
drh9188b382004-05-14 21:12:22 +00003840#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00003841 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00003842 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00003843 int iPage = pCur->iPage;
drh51c6d962004-06-06 00:42:25 +00003844 memset(&info, 0, sizeof(info));
danielk197730548662009-07-09 05:07:37 +00003845 btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
dan7df42ab2014-01-20 18:25:44 +00003846 assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00003847 }
danielk19771cc5ed82007-05-16 17:28:43 +00003848#else
3849 #define assertCellInfo(x)
3850#endif
drh86057612007-06-26 01:04:48 +00003851#ifdef _MSC_VER
3852 /* Use a real function in MSVC to work around bugs in that compiler. */
3853 static void getCellInfo(BtCursor *pCur){
3854 if( pCur->info.nSize==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003855 int iPage = pCur->iPage;
danielk197730548662009-07-09 05:07:37 +00003856 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
drh036dbec2014-03-11 23:40:44 +00003857 pCur->curFlags |= BTCF_ValidNKey;
drh86057612007-06-26 01:04:48 +00003858 }else{
3859 assertCellInfo(pCur);
3860 }
3861 }
3862#else /* if not _MSC_VER */
3863 /* Use a macro in all other compilers so that the function is inlined */
danielk197771d5d2c2008-09-29 11:49:47 +00003864#define getCellInfo(pCur) \
3865 if( pCur->info.nSize==0 ){ \
3866 int iPage = pCur->iPage; \
drh036dbec2014-03-11 23:40:44 +00003867 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
3868 pCur->curFlags |= BTCF_ValidNKey; \
danielk197771d5d2c2008-09-29 11:49:47 +00003869 }else{ \
3870 assertCellInfo(pCur); \
drh86057612007-06-26 01:04:48 +00003871 }
3872#endif /* _MSC_VER */
drh9188b382004-05-14 21:12:22 +00003873
drhea8ffdf2009-07-22 00:35:23 +00003874#ifndef NDEBUG /* The next routine used only within assert() statements */
3875/*
3876** Return true if the given BtCursor is valid. A valid cursor is one
3877** that is currently pointing to a row in a (non-empty) table.
3878** This is a verification routine is used only within assert() statements.
3879*/
3880int sqlite3BtreeCursorIsValid(BtCursor *pCur){
3881 return pCur && pCur->eState==CURSOR_VALID;
3882}
3883#endif /* NDEBUG */
3884
drh9188b382004-05-14 21:12:22 +00003885/*
drh3aac2dd2004-04-26 14:10:20 +00003886** Set *pSize to the size of the buffer needed to hold the value of
3887** the key for the current entry. If the cursor is not pointing
3888** to a valid entry, *pSize is set to 0.
3889**
drh4b70f112004-05-02 21:12:19 +00003890** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00003891** itself, not the number of bytes in the key.
drhea8ffdf2009-07-22 00:35:23 +00003892**
3893** The caller must position the cursor prior to invoking this routine.
3894**
3895** This routine cannot fail. It always returns SQLITE_OK.
drh7e3b0a02001-04-28 16:52:40 +00003896*/
drh4a1c3802004-05-12 15:15:47 +00003897int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drh1fee73e2007-08-29 04:00:57 +00003898 assert( cursorHoldsMutex(pCur) );
drhea8ffdf2009-07-22 00:35:23 +00003899 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3900 if( pCur->eState!=CURSOR_VALID ){
3901 *pSize = 0;
3902 }else{
3903 getCellInfo(pCur);
3904 *pSize = pCur->info.nKey;
drh72f82862001-05-24 21:06:34 +00003905 }
drhea8ffdf2009-07-22 00:35:23 +00003906 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003907}
drh2af926b2001-05-15 00:39:25 +00003908
drh72f82862001-05-24 21:06:34 +00003909/*
drh0e1c19e2004-05-11 00:58:56 +00003910** Set *pSize to the number of bytes of data in the entry the
drhea8ffdf2009-07-22 00:35:23 +00003911** cursor currently points to.
3912**
3913** The caller must guarantee that the cursor is pointing to a non-NULL
3914** valid entry. In other words, the calling procedure must guarantee
3915** that the cursor has Cursor.eState==CURSOR_VALID.
3916**
3917** Failure is not possible. This function always returns SQLITE_OK.
3918** It might just as well be a procedure (returning void) but we continue
3919** to return an integer result code for historical reasons.
drh0e1c19e2004-05-11 00:58:56 +00003920*/
3921int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drh1fee73e2007-08-29 04:00:57 +00003922 assert( cursorHoldsMutex(pCur) );
drhea8ffdf2009-07-22 00:35:23 +00003923 assert( pCur->eState==CURSOR_VALID );
drh3e28ff52014-09-24 00:59:08 +00003924 assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
drhea8ffdf2009-07-22 00:35:23 +00003925 getCellInfo(pCur);
drhab1cc582014-09-23 21:25:19 +00003926 *pSize = pCur->info.nPayload;
drhea8ffdf2009-07-22 00:35:23 +00003927 return SQLITE_OK;
drh0e1c19e2004-05-11 00:58:56 +00003928}
3929
3930/*
danielk1977d04417962007-05-02 13:16:30 +00003931** Given the page number of an overflow page in the database (parameter
3932** ovfl), this function finds the page number of the next page in the
3933** linked list of overflow pages. If possible, it uses the auto-vacuum
3934** pointer-map data instead of reading the content of page ovfl to do so.
3935**
3936** If an error occurs an SQLite error code is returned. Otherwise:
3937**
danielk1977bea2a942009-01-20 17:06:27 +00003938** The page number of the next overflow page in the linked list is
3939** written to *pPgnoNext. If page ovfl is the last page in its linked
3940** list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003941**
danielk1977bea2a942009-01-20 17:06:27 +00003942** If ppPage is not NULL, and a reference to the MemPage object corresponding
3943** to page number pOvfl was obtained, then *ppPage is set to point to that
3944** reference. It is the responsibility of the caller to call releasePage()
3945** on *ppPage to free the reference. In no reference was obtained (because
3946** the pointer-map was used to obtain the value for *pPgnoNext), then
3947** *ppPage is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003948*/
3949static int getOverflowPage(
drhfa3be902009-07-07 02:44:07 +00003950 BtShared *pBt, /* The database file */
3951 Pgno ovfl, /* Current overflow page number */
danielk1977bea2a942009-01-20 17:06:27 +00003952 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
danielk1977d04417962007-05-02 13:16:30 +00003953 Pgno *pPgnoNext /* OUT: Next overflow page number */
3954){
3955 Pgno next = 0;
danielk1977bea2a942009-01-20 17:06:27 +00003956 MemPage *pPage = 0;
drh1bd10f82008-12-10 21:19:56 +00003957 int rc = SQLITE_OK;
danielk1977d04417962007-05-02 13:16:30 +00003958
drh1fee73e2007-08-29 04:00:57 +00003959 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bea2a942009-01-20 17:06:27 +00003960 assert(pPgnoNext);
danielk1977d04417962007-05-02 13:16:30 +00003961
3962#ifndef SQLITE_OMIT_AUTOVACUUM
3963 /* Try to find the next page in the overflow list using the
3964 ** autovacuum pointer-map pages. Guess that the next page in
3965 ** the overflow list is page number (ovfl+1). If that guess turns
3966 ** out to be wrong, fall back to loading the data of page
3967 ** number ovfl to determine the next page number.
3968 */
3969 if( pBt->autoVacuum ){
3970 Pgno pgno;
3971 Pgno iGuess = ovfl+1;
3972 u8 eType;
3973
3974 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
3975 iGuess++;
3976 }
3977
drhb1299152010-03-30 22:58:33 +00003978 if( iGuess<=btreePagecount(pBt) ){
danielk1977d04417962007-05-02 13:16:30 +00003979 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
danielk1977bea2a942009-01-20 17:06:27 +00003980 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
danielk1977d04417962007-05-02 13:16:30 +00003981 next = iGuess;
danielk1977bea2a942009-01-20 17:06:27 +00003982 rc = SQLITE_DONE;
danielk1977d04417962007-05-02 13:16:30 +00003983 }
3984 }
3985 }
3986#endif
3987
danielk1977d8a3f3d2009-07-11 11:45:23 +00003988 assert( next==0 || rc==SQLITE_DONE );
danielk1977bea2a942009-01-20 17:06:27 +00003989 if( rc==SQLITE_OK ){
drhb00fc3b2013-08-21 23:42:32 +00003990 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
danielk1977d8a3f3d2009-07-11 11:45:23 +00003991 assert( rc==SQLITE_OK || pPage==0 );
3992 if( rc==SQLITE_OK ){
danielk1977d04417962007-05-02 13:16:30 +00003993 next = get4byte(pPage->aData);
3994 }
danielk1977443c0592009-01-16 15:21:05 +00003995 }
danielk197745d68822009-01-16 16:23:38 +00003996
danielk1977bea2a942009-01-20 17:06:27 +00003997 *pPgnoNext = next;
3998 if( ppPage ){
3999 *ppPage = pPage;
4000 }else{
4001 releasePage(pPage);
4002 }
4003 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
danielk1977d04417962007-05-02 13:16:30 +00004004}
4005
danielk1977da107192007-05-04 08:32:13 +00004006/*
4007** Copy data from a buffer to a page, or from a page to a buffer.
4008**
4009** pPayload is a pointer to data stored on database page pDbPage.
4010** If argument eOp is false, then nByte bytes of data are copied
4011** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4012** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4013** of data are copied from the buffer pBuf to pPayload.
4014**
4015** SQLITE_OK is returned on success, otherwise an error code.
4016*/
4017static int copyPayload(
4018 void *pPayload, /* Pointer to page data */
4019 void *pBuf, /* Pointer to buffer */
4020 int nByte, /* Number of bytes to copy */
4021 int eOp, /* 0 -> copy from page, 1 -> copy to page */
4022 DbPage *pDbPage /* Page containing pPayload */
4023){
4024 if( eOp ){
4025 /* Copy data from buffer to page (a write operation) */
4026 int rc = sqlite3PagerWrite(pDbPage);
4027 if( rc!=SQLITE_OK ){
4028 return rc;
4029 }
4030 memcpy(pPayload, pBuf, nByte);
4031 }else{
4032 /* Copy data from page to buffer (a read operation) */
4033 memcpy(pBuf, pPayload, nByte);
4034 }
4035 return SQLITE_OK;
4036}
danielk1977d04417962007-05-02 13:16:30 +00004037
4038/*
danielk19779f8d6402007-05-02 17:48:45 +00004039** This function is used to read or overwrite payload information
dan5a500af2014-03-11 20:33:04 +00004040** for the entry that the pCur cursor is pointing to. The eOp
4041** argument is interpreted as follows:
4042**
4043** 0: The operation is a read. Populate the overflow cache.
4044** 1: The operation is a write. Populate the overflow cache.
4045** 2: The operation is a read. Do not populate the overflow cache.
danielk19779f8d6402007-05-02 17:48:45 +00004046**
4047** A total of "amt" bytes are read or written beginning at "offset".
4048** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00004049**
drh3bcdfd22009-07-12 02:32:21 +00004050** The content being read or written might appear on the main page
4051** or be scattered out on multiple overflow pages.
danielk1977da107192007-05-04 08:32:13 +00004052**
dan5a500af2014-03-11 20:33:04 +00004053** If the current cursor entry uses one or more overflow pages and the
4054** eOp argument is not 2, this function may allocate space for and lazily
peter.d.reid60ec9142014-09-06 16:39:46 +00004055** populates the overflow page-list cache array (BtCursor.aOverflow).
dan5a500af2014-03-11 20:33:04 +00004056** Subsequent calls use this cache to make seeking to the supplied offset
4057** more efficient.
danielk1977da107192007-05-04 08:32:13 +00004058**
4059** Once an overflow page-list cache has been allocated, it may be
4060** invalidated if some other cursor writes to the same table, or if
4061** the cursor is moved to a different row. Additionally, in auto-vacuum
4062** mode, the following events may invalidate an overflow page-list cache.
4063**
4064** * An incremental vacuum,
4065** * A commit in auto_vacuum="full" mode,
4066** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00004067*/
danielk19779f8d6402007-05-02 17:48:45 +00004068static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00004069 BtCursor *pCur, /* Cursor pointing to entry to read from */
danielk197789d40042008-11-17 14:20:56 +00004070 u32 offset, /* Begin reading this far into payload */
4071 u32 amt, /* Read this many bytes */
drh3aac2dd2004-04-26 14:10:20 +00004072 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00004073 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00004074){
4075 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00004076 int rc = SQLITE_OK;
danielk19772dec9702007-05-02 16:48:37 +00004077 int iIdx = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004078 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
danielk19770d065412008-11-12 18:21:36 +00004079 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh4c417182014-03-31 23:57:41 +00004080#ifdef SQLITE_DIRECT_OVERFLOW_READ
dan9501a642014-10-01 12:01:10 +00004081 unsigned char * const pBufStart = pBuf;
drh3f387402014-09-24 01:23:00 +00004082 int bEnd; /* True if reading to end of data */
drh4c417182014-03-31 23:57:41 +00004083#endif
drh3aac2dd2004-04-26 14:10:20 +00004084
danielk1977da107192007-05-04 08:32:13 +00004085 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00004086 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004087 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh1fee73e2007-08-29 04:00:57 +00004088 assert( cursorHoldsMutex(pCur) );
drh3f387402014-09-24 01:23:00 +00004089 assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */
danielk1977da107192007-05-04 08:32:13 +00004090
drh86057612007-06-26 01:04:48 +00004091 getCellInfo(pCur);
drhab1cc582014-09-23 21:25:19 +00004092 aPayload = pCur->info.pPayload;
drh4c417182014-03-31 23:57:41 +00004093#ifdef SQLITE_DIRECT_OVERFLOW_READ
drhab1cc582014-09-23 21:25:19 +00004094 bEnd = offset+amt==pCur->info.nPayload;
drh4c417182014-03-31 23:57:41 +00004095#endif
drhab1cc582014-09-23 21:25:19 +00004096 assert( offset+amt <= pCur->info.nPayload );
danielk1977da107192007-05-04 08:32:13 +00004097
drhab1cc582014-09-23 21:25:19 +00004098 if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){
danielk1977da107192007-05-04 08:32:13 +00004099 /* Trying to read or write past the end of the data is an error */
danielk197767fd7a92008-09-10 17:53:35 +00004100 return SQLITE_CORRUPT_BKPT;
drh3aac2dd2004-04-26 14:10:20 +00004101 }
danielk1977da107192007-05-04 08:32:13 +00004102
4103 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00004104 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00004105 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00004106 if( a+offset>pCur->info.nLocal ){
4107 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00004108 }
dan5a500af2014-03-11 20:33:04 +00004109 rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00004110 offset = 0;
drha34b6762004-05-07 13:30:42 +00004111 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00004112 amt -= a;
drhdd793422001-06-28 01:54:48 +00004113 }else{
drhfa1a98a2004-05-14 19:08:17 +00004114 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00004115 }
danielk1977da107192007-05-04 08:32:13 +00004116
4117 if( rc==SQLITE_OK && amt>0 ){
danielk197789d40042008-11-17 14:20:56 +00004118 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
danielk1977da107192007-05-04 08:32:13 +00004119 Pgno nextPage;
4120
drhfa1a98a2004-05-14 19:08:17 +00004121 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00004122
drha38c9512014-04-01 01:24:34 +00004123 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
4124 ** Except, do not allocate aOverflow[] for eOp==2.
4125 **
4126 ** The aOverflow[] array is sized at one entry for each overflow page
4127 ** in the overflow chain. The page number of the first overflow page is
4128 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
4129 ** means "not yet known" (the cache is lazily populated).
danielk1977da107192007-05-04 08:32:13 +00004130 */
drh036dbec2014-03-11 23:40:44 +00004131 if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
danielk19772dec9702007-05-02 16:48:37 +00004132 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
dan5a500af2014-03-11 20:33:04 +00004133 if( nOvfl>pCur->nOvflAlloc ){
4134 Pgno *aNew = (Pgno*)sqlite3DbRealloc(
4135 pCur->pBtree->db, pCur->aOverflow, nOvfl*2*sizeof(Pgno)
4136 );
4137 if( aNew==0 ){
4138 rc = SQLITE_NOMEM;
4139 }else{
4140 pCur->nOvflAlloc = nOvfl*2;
4141 pCur->aOverflow = aNew;
4142 }
4143 }
4144 if( rc==SQLITE_OK ){
4145 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
drh036dbec2014-03-11 23:40:44 +00004146 pCur->curFlags |= BTCF_ValidOvfl;
danielk19772dec9702007-05-02 16:48:37 +00004147 }
4148 }
danielk1977da107192007-05-04 08:32:13 +00004149
4150 /* If the overflow page-list cache has been allocated and the
4151 ** entry for the first required overflow page is valid, skip
4152 ** directly to it.
4153 */
drh3f387402014-09-24 01:23:00 +00004154 if( (pCur->curFlags & BTCF_ValidOvfl)!=0
4155 && pCur->aOverflow[offset/ovflSize]
4156 ){
danielk19772dec9702007-05-02 16:48:37 +00004157 iIdx = (offset/ovflSize);
4158 nextPage = pCur->aOverflow[iIdx];
4159 offset = (offset%ovflSize);
4160 }
danielk1977da107192007-05-04 08:32:13 +00004161
4162 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
4163
danielk1977da107192007-05-04 08:32:13 +00004164 /* If required, populate the overflow page-list cache. */
drh036dbec2014-03-11 23:40:44 +00004165 if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
danielk1977da107192007-05-04 08:32:13 +00004166 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
4167 pCur->aOverflow[iIdx] = nextPage;
4168 }
danielk1977da107192007-05-04 08:32:13 +00004169
danielk1977d04417962007-05-02 13:16:30 +00004170 if( offset>=ovflSize ){
4171 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00004172 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00004173 ** data is not required. So first try to lookup the overflow
4174 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00004175 ** function.
drha38c9512014-04-01 01:24:34 +00004176 **
4177 ** Note that the aOverflow[] array must be allocated because eOp!=2
4178 ** here. If eOp==2, then offset==0 and this branch is never taken.
danielk1977d04417962007-05-02 13:16:30 +00004179 */
drha38c9512014-04-01 01:24:34 +00004180 assert( eOp!=2 );
4181 assert( pCur->curFlags & BTCF_ValidOvfl );
4182 if( pCur->aOverflow[iIdx+1] ){
danielk1977da107192007-05-04 08:32:13 +00004183 nextPage = pCur->aOverflow[iIdx+1];
drha38c9512014-04-01 01:24:34 +00004184 }else{
danielk1977da107192007-05-04 08:32:13 +00004185 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
drha38c9512014-04-01 01:24:34 +00004186 }
danielk1977da107192007-05-04 08:32:13 +00004187 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00004188 }else{
danielk19779f8d6402007-05-02 17:48:45 +00004189 /* Need to read this page properly. It contains some of the
4190 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00004191 */
danf4ba1092011-10-08 14:57:07 +00004192#ifdef SQLITE_DIRECT_OVERFLOW_READ
4193 sqlite3_file *fd;
4194#endif
danielk1977cfe9a692004-06-16 12:00:29 +00004195 int a = amt;
danf4ba1092011-10-08 14:57:07 +00004196 if( a + offset > ovflSize ){
4197 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00004198 }
danf4ba1092011-10-08 14:57:07 +00004199
4200#ifdef SQLITE_DIRECT_OVERFLOW_READ
4201 /* If all the following are true:
4202 **
4203 ** 1) this is a read operation, and
4204 ** 2) data is required from the start of this overflow page, and
4205 ** 3) the database is file-backed, and
4206 ** 4) there is no open write-transaction, and
4207 ** 5) the database is not a WAL database,
dan9bc21b52014-03-20 18:56:35 +00004208 ** 6) all data from the page is being read.
dan9501a642014-10-01 12:01:10 +00004209 ** 7) at least 4 bytes have already been read into the output buffer
danf4ba1092011-10-08 14:57:07 +00004210 **
4211 ** then data can be read directly from the database file into the
4212 ** output buffer, bypassing the page-cache altogether. This speeds
4213 ** up loading large records that span many overflow pages.
4214 */
dan5a500af2014-03-11 20:33:04 +00004215 if( (eOp&0x01)==0 /* (1) */
danf4ba1092011-10-08 14:57:07 +00004216 && offset==0 /* (2) */
dan9bc21b52014-03-20 18:56:35 +00004217 && (bEnd || a==ovflSize) /* (6) */
danf4ba1092011-10-08 14:57:07 +00004218 && pBt->inTransaction==TRANS_READ /* (4) */
4219 && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
4220 && pBt->pPage1->aData[19]==0x01 /* (5) */
dan9501a642014-10-01 12:01:10 +00004221 && &pBuf[-4]>=pBufStart /* (7) */
danf4ba1092011-10-08 14:57:07 +00004222 ){
4223 u8 aSave[4];
4224 u8 *aWrite = &pBuf[-4];
dan9501a642014-10-01 12:01:10 +00004225 assert( aWrite>=pBufStart ); /* hence (7) */
danf4ba1092011-10-08 14:57:07 +00004226 memcpy(aSave, aWrite, 4);
dan27d47fb2011-12-21 17:00:16 +00004227 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
danf4ba1092011-10-08 14:57:07 +00004228 nextPage = get4byte(aWrite);
4229 memcpy(aWrite, aSave, 4);
4230 }else
4231#endif
4232
4233 {
4234 DbPage *pDbPage;
dan11dcd112013-03-15 18:29:18 +00004235 rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
dan5a500af2014-03-11 20:33:04 +00004236 ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
dan11dcd112013-03-15 18:29:18 +00004237 );
danf4ba1092011-10-08 14:57:07 +00004238 if( rc==SQLITE_OK ){
4239 aPayload = sqlite3PagerGetData(pDbPage);
4240 nextPage = get4byte(aPayload);
dan5a500af2014-03-11 20:33:04 +00004241 rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
danf4ba1092011-10-08 14:57:07 +00004242 sqlite3PagerUnref(pDbPage);
4243 offset = 0;
4244 }
4245 }
4246 amt -= a;
4247 pBuf += a;
danielk1977cfe9a692004-06-16 12:00:29 +00004248 }
drh2af926b2001-05-15 00:39:25 +00004249 }
drh2af926b2001-05-15 00:39:25 +00004250 }
danielk1977cfe9a692004-06-16 12:00:29 +00004251
danielk1977da107192007-05-04 08:32:13 +00004252 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00004253 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00004254 }
danielk1977da107192007-05-04 08:32:13 +00004255 return rc;
drh2af926b2001-05-15 00:39:25 +00004256}
4257
drh72f82862001-05-24 21:06:34 +00004258/*
drh3aac2dd2004-04-26 14:10:20 +00004259** Read part of the key associated with cursor pCur. Exactly
peter.d.reid60ec9142014-09-06 16:39:46 +00004260** "amt" bytes will be transferred into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00004261** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00004262**
drh5d1a8722009-07-22 18:07:40 +00004263** The caller must ensure that pCur is pointing to a valid row
4264** in the table.
4265**
drh3aac2dd2004-04-26 14:10:20 +00004266** Return SQLITE_OK on success or an error code if anything goes
4267** wrong. An error is returned if "offset+amt" is larger than
4268** the available payload.
drh72f82862001-05-24 21:06:34 +00004269*/
drha34b6762004-05-07 13:30:42 +00004270int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drh1fee73e2007-08-29 04:00:57 +00004271 assert( cursorHoldsMutex(pCur) );
drh5d1a8722009-07-22 18:07:40 +00004272 assert( pCur->eState==CURSOR_VALID );
4273 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
4274 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
4275 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
drh3aac2dd2004-04-26 14:10:20 +00004276}
4277
4278/*
drh3aac2dd2004-04-26 14:10:20 +00004279** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00004280** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00004281** begins at "offset".
4282**
4283** Return SQLITE_OK on success or an error code if anything goes
4284** wrong. An error is returned if "offset+amt" is larger than
4285** the available payload.
drh72f82862001-05-24 21:06:34 +00004286*/
drh3aac2dd2004-04-26 14:10:20 +00004287int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00004288 int rc;
4289
danielk19773588ceb2008-06-10 17:30:26 +00004290#ifndef SQLITE_OMIT_INCRBLOB
4291 if ( pCur->eState==CURSOR_INVALID ){
4292 return SQLITE_ABORT;
4293 }
4294#endif
4295
drh1fee73e2007-08-29 04:00:57 +00004296 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004297 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004298 if( rc==SQLITE_OK ){
4299 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004300 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
4301 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drhfb192682009-07-11 18:26:28 +00004302 rc = accessPayload(pCur, offset, amt, pBuf, 0);
danielk1977da184232006-01-05 11:34:32 +00004303 }
4304 return rc;
drh2af926b2001-05-15 00:39:25 +00004305}
4306
drh72f82862001-05-24 21:06:34 +00004307/*
drh0e1c19e2004-05-11 00:58:56 +00004308** Return a pointer to payload information from the entry that the
4309** pCur cursor is pointing to. The pointer is to the beginning of
drh2a8d2262013-12-09 20:43:22 +00004310** the key if index btrees (pPage->intKey==0) and is the data for
4311** table btrees (pPage->intKey==1). The number of bytes of available
4312** key/data is written into *pAmt. If *pAmt==0, then the value
4313** returned will not be a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00004314**
4315** This routine is an optimization. It is common for the entire key
4316** and data to fit on the local page and for there to be no overflow
4317** pages. When that is so, this routine can be used to access the
4318** key and data without making a copy. If the key and/or data spills
drh7f751222009-03-17 22:33:00 +00004319** onto overflow pages, then accessPayload() must be used to reassemble
drh0e1c19e2004-05-11 00:58:56 +00004320** the key/data and copy it into a preallocated buffer.
4321**
4322** The pointer returned by this routine looks directly into the cached
4323** page of the database. The data might change or move the next time
4324** any btree routine is called.
4325*/
drh2a8d2262013-12-09 20:43:22 +00004326static const void *fetchPayload(
drh0e1c19e2004-05-11 00:58:56 +00004327 BtCursor *pCur, /* Cursor pointing to entry to read from */
drh2a8d2262013-12-09 20:43:22 +00004328 u32 *pAmt /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00004329){
danielk197771d5d2c2008-09-29 11:49:47 +00004330 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
danielk1977da184232006-01-05 11:34:32 +00004331 assert( pCur->eState==CURSOR_VALID );
drh2a8d2262013-12-09 20:43:22 +00004332 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh1fee73e2007-08-29 04:00:57 +00004333 assert( cursorHoldsMutex(pCur) );
drh2a8d2262013-12-09 20:43:22 +00004334 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh86dd3712014-03-25 11:00:21 +00004335 assert( pCur->info.nSize>0 );
drh2a8d2262013-12-09 20:43:22 +00004336 *pAmt = pCur->info.nLocal;
drhab1cc582014-09-23 21:25:19 +00004337 return (void*)pCur->info.pPayload;
drh0e1c19e2004-05-11 00:58:56 +00004338}
4339
4340
4341/*
drhe51c44f2004-05-30 20:46:09 +00004342** For the entry that cursor pCur is point to, return as
4343** many bytes of the key or data as are available on the local
4344** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00004345**
4346** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00004347** or be destroyed on the next call to any Btree routine,
4348** including calls from other threads against the same cache.
4349** Hence, a mutex on the BtShared should be held prior to calling
4350** this routine.
drh0e1c19e2004-05-11 00:58:56 +00004351**
4352** These routines is used to get quick access to key and data
4353** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00004354*/
drh501932c2013-11-21 21:59:53 +00004355const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
drh2a8d2262013-12-09 20:43:22 +00004356 return fetchPayload(pCur, pAmt);
drh0e1c19e2004-05-11 00:58:56 +00004357}
drh501932c2013-11-21 21:59:53 +00004358const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
drh2a8d2262013-12-09 20:43:22 +00004359 return fetchPayload(pCur, pAmt);
drh0e1c19e2004-05-11 00:58:56 +00004360}
4361
4362
4363/*
drh8178a752003-01-05 21:41:40 +00004364** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00004365** page number of the child page to move to.
danielk1977a299d612009-07-13 11:22:10 +00004366**
4367** This function returns SQLITE_CORRUPT if the page-header flags field of
4368** the new child page does not match the flags field of the parent (i.e.
4369** if an intkey page appears to be the parent of a non-intkey page, or
4370** vice-versa).
drh72f82862001-05-24 21:06:34 +00004371*/
drh3aac2dd2004-04-26 14:10:20 +00004372static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00004373 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004374 int i = pCur->iPage;
drh72f82862001-05-24 21:06:34 +00004375 MemPage *pNewPage;
drhd0679ed2007-08-28 22:24:34 +00004376 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00004377
drh1fee73e2007-08-29 04:00:57 +00004378 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004379 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004380 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
dan11dcd112013-03-15 18:29:18 +00004381 assert( pCur->iPage>=0 );
danielk197771d5d2c2008-09-29 11:49:47 +00004382 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
4383 return SQLITE_CORRUPT_BKPT;
4384 }
drhb00fc3b2013-08-21 23:42:32 +00004385 rc = getAndInitPage(pBt, newPgno, &pNewPage,
drh036dbec2014-03-11 23:40:44 +00004386 (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
drh6019e162001-07-02 17:51:45 +00004387 if( rc ) return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004388 pCur->apPage[i+1] = pNewPage;
4389 pCur->aiIdx[i+1] = 0;
4390 pCur->iPage++;
4391
drh271efa52004-05-30 19:19:05 +00004392 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004393 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
danielk1977bd5969a2009-07-11 17:39:42 +00004394 if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
drh49285702005-09-17 15:20:26 +00004395 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00004396 }
drh72f82862001-05-24 21:06:34 +00004397 return SQLITE_OK;
4398}
4399
danbb246c42012-01-12 14:25:55 +00004400#if 0
danielk1977bf93c562008-09-29 15:53:25 +00004401/*
4402** Page pParent is an internal (non-leaf) tree page. This function
4403** asserts that page number iChild is the left-child if the iIdx'th
4404** cell in page pParent. Or, if iIdx is equal to the total number of
4405** cells in pParent, that page number iChild is the right-child of
4406** the page.
4407*/
4408static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
4409 assert( iIdx<=pParent->nCell );
4410 if( iIdx==pParent->nCell ){
4411 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
4412 }else{
4413 assert( get4byte(findCell(pParent, iIdx))==iChild );
4414 }
4415}
4416#else
4417# define assertParentIndex(x,y,z)
4418#endif
4419
drh72f82862001-05-24 21:06:34 +00004420/*
drh5e2f8b92001-05-28 00:41:15 +00004421** Move the cursor up to the parent page.
4422**
4423** pCur->idx is set to the cell index that contains the pointer
4424** to the page we are coming from. If we are coming from the
4425** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00004426** the largest cell index.
drh72f82862001-05-24 21:06:34 +00004427*/
danielk197730548662009-07-09 05:07:37 +00004428static void moveToParent(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00004429 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004430 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004431 assert( pCur->iPage>0 );
4432 assert( pCur->apPage[pCur->iPage] );
danbb246c42012-01-12 14:25:55 +00004433
4434 /* UPDATE: It is actually possible for the condition tested by the assert
4435 ** below to be untrue if the database file is corrupt. This can occur if
4436 ** one cursor has modified page pParent while a reference to it is held
4437 ** by a second cursor. Which can only happen if a single page is linked
4438 ** into more than one b-tree structure in a corrupt database. */
4439#if 0
danielk1977bf93c562008-09-29 15:53:25 +00004440 assertParentIndex(
4441 pCur->apPage[pCur->iPage-1],
4442 pCur->aiIdx[pCur->iPage-1],
4443 pCur->apPage[pCur->iPage]->pgno
4444 );
danbb246c42012-01-12 14:25:55 +00004445#endif
dan6c2688c2012-01-12 15:05:03 +00004446 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
danbb246c42012-01-12 14:25:55 +00004447
danielk197771d5d2c2008-09-29 11:49:47 +00004448 releasePage(pCur->apPage[pCur->iPage]);
4449 pCur->iPage--;
drh271efa52004-05-30 19:19:05 +00004450 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004451 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drh72f82862001-05-24 21:06:34 +00004452}
4453
4454/*
danielk19778f880a82009-07-13 09:41:45 +00004455** Move the cursor to point to the root page of its b-tree structure.
4456**
4457** If the table has a virtual root page, then the cursor is moved to point
4458** to the virtual root page instead of the actual root page. A table has a
4459** virtual root page when the actual root page contains no cells and a
4460** single child page. This can only happen with the table rooted at page 1.
4461**
4462** If the b-tree structure is empty, the cursor state is set to
4463** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
4464** cell located on the root (or virtual root) page and the cursor state
4465** is set to CURSOR_VALID.
4466**
4467** If this function returns successfully, it may be assumed that the
4468** page-header flags indicate that the [virtual] root-page is the expected
4469** kind of b-tree page (i.e. if when opening the cursor the caller did not
4470** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
4471** indicating a table b-tree, or if the caller did specify a KeyInfo
4472** structure the flags byte is set to 0x02 or 0x0A, indicating an index
4473** b-tree).
drh72f82862001-05-24 21:06:34 +00004474*/
drh5e2f8b92001-05-28 00:41:15 +00004475static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00004476 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00004477 int rc = SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00004478
drh1fee73e2007-08-29 04:00:57 +00004479 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +00004480 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
4481 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
4482 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
4483 if( pCur->eState>=CURSOR_REQUIRESEEK ){
4484 if( pCur->eState==CURSOR_FAULT ){
drh4c301aa2009-07-15 17:25:45 +00004485 assert( pCur->skipNext!=SQLITE_OK );
4486 return pCur->skipNext;
drhfb982642007-08-30 01:19:59 +00004487 }
danielk1977be51a652008-10-08 17:58:48 +00004488 sqlite3BtreeClearCursor(pCur);
drhbf700f32007-03-31 02:36:44 +00004489 }
danielk197771d5d2c2008-09-29 11:49:47 +00004490
4491 if( pCur->iPage>=0 ){
drh4e8fe3f2013-12-06 23:25:27 +00004492 while( pCur->iPage ) releasePage(pCur->apPage[pCur->iPage--]);
dana205a482011-08-27 18:48:57 +00004493 }else if( pCur->pgnoRoot==0 ){
4494 pCur->eState = CURSOR_INVALID;
4495 return SQLITE_OK;
drh777e4c42006-01-13 04:31:58 +00004496 }else{
drh4e8fe3f2013-12-06 23:25:27 +00004497 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
drh036dbec2014-03-11 23:40:44 +00004498 (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
drh4c301aa2009-07-15 17:25:45 +00004499 if( rc!=SQLITE_OK ){
drh777e4c42006-01-13 04:31:58 +00004500 pCur->eState = CURSOR_INVALID;
4501 return rc;
4502 }
danielk1977172114a2009-07-07 15:47:12 +00004503 pCur->iPage = 0;
drhc39e0002004-05-07 23:50:57 +00004504 }
danielk197771d5d2c2008-09-29 11:49:47 +00004505 pRoot = pCur->apPage[0];
4506 assert( pRoot->pgno==pCur->pgnoRoot );
dan7df42ab2014-01-20 18:25:44 +00004507
4508 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
4509 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
4510 ** NULL, the caller expects a table b-tree. If this is not the case,
4511 ** return an SQLITE_CORRUPT error.
4512 **
4513 ** Earlier versions of SQLite assumed that this test could not fail
4514 ** if the root page was already loaded when this function was called (i.e.
4515 ** if pCur->iPage>=0). But this is not so if the database is corrupted
4516 ** in such a way that page pRoot is linked into a second b-tree table
4517 ** (or the freelist). */
4518 assert( pRoot->intKey==1 || pRoot->intKey==0 );
4519 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
4520 return SQLITE_CORRUPT_BKPT;
4521 }
danielk19778f880a82009-07-13 09:41:45 +00004522
danielk197771d5d2c2008-09-29 11:49:47 +00004523 pCur->aiIdx[0] = 0;
drh271efa52004-05-30 19:19:05 +00004524 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004525 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
danielk197771d5d2c2008-09-29 11:49:47 +00004526
drh4e8fe3f2013-12-06 23:25:27 +00004527 if( pRoot->nCell>0 ){
4528 pCur->eState = CURSOR_VALID;
4529 }else if( !pRoot->leaf ){
drh8856d6a2004-04-29 14:42:46 +00004530 Pgno subpage;
drhc85240d2009-06-04 16:14:33 +00004531 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
drh43605152004-05-29 21:46:49 +00004532 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
danielk1977da184232006-01-05 11:34:32 +00004533 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00004534 rc = moveToChild(pCur, subpage);
danielk197771d5d2c2008-09-29 11:49:47 +00004535 }else{
drh4e8fe3f2013-12-06 23:25:27 +00004536 pCur->eState = CURSOR_INVALID;
drh8856d6a2004-04-29 14:42:46 +00004537 }
4538 return rc;
drh72f82862001-05-24 21:06:34 +00004539}
drh2af926b2001-05-15 00:39:25 +00004540
drh5e2f8b92001-05-28 00:41:15 +00004541/*
4542** Move the cursor down to the left-most leaf entry beneath the
4543** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00004544**
4545** The left-most leaf is the one with the smallest key - the first
4546** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00004547*/
4548static int moveToLeftmost(BtCursor *pCur){
4549 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00004550 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00004551 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00004552
drh1fee73e2007-08-29 04:00:57 +00004553 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004554 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004555 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
4556 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
4557 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
drh8178a752003-01-05 21:41:40 +00004558 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00004559 }
drhd677b3d2007-08-20 22:48:41 +00004560 return rc;
drh5e2f8b92001-05-28 00:41:15 +00004561}
4562
drh2dcc9aa2002-12-04 13:40:25 +00004563/*
4564** Move the cursor down to the right-most leaf entry beneath the
4565** page to which it is currently pointing. Notice the difference
4566** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
4567** finds the left-most entry beneath the *entry* whereas moveToRightmost()
4568** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00004569**
4570** The right-most entry is the one with the largest key - the last
4571** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00004572*/
4573static int moveToRightmost(BtCursor *pCur){
4574 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00004575 int rc = SQLITE_OK;
drh1bd10f82008-12-10 21:19:56 +00004576 MemPage *pPage = 0;
drh2dcc9aa2002-12-04 13:40:25 +00004577
drh1fee73e2007-08-29 04:00:57 +00004578 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004579 assert( pCur->eState==CURSOR_VALID );
drhee6438d2014-09-01 13:29:32 +00004580 while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
drh43605152004-05-29 21:46:49 +00004581 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
danielk197771d5d2c2008-09-29 11:49:47 +00004582 pCur->aiIdx[pCur->iPage] = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00004583 rc = moveToChild(pCur, pgno);
drhee6438d2014-09-01 13:29:32 +00004584 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00004585 }
drhee6438d2014-09-01 13:29:32 +00004586 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
4587 assert( pCur->info.nSize==0 );
4588 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
4589 return SQLITE_OK;
drh2dcc9aa2002-12-04 13:40:25 +00004590}
4591
drh5e00f6c2001-09-13 13:46:56 +00004592/* Move the cursor to the first entry in the table. Return SQLITE_OK
4593** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00004594** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00004595*/
drh3aac2dd2004-04-26 14:10:20 +00004596int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00004597 int rc;
drhd677b3d2007-08-20 22:48:41 +00004598
drh1fee73e2007-08-29 04:00:57 +00004599 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004600 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00004601 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004602 if( rc==SQLITE_OK ){
4603 if( pCur->eState==CURSOR_INVALID ){
dana205a482011-08-27 18:48:57 +00004604 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00004605 *pRes = 1;
drhd677b3d2007-08-20 22:48:41 +00004606 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004607 assert( pCur->apPage[pCur->iPage]->nCell>0 );
drhd677b3d2007-08-20 22:48:41 +00004608 *pRes = 0;
4609 rc = moveToLeftmost(pCur);
4610 }
drh5e00f6c2001-09-13 13:46:56 +00004611 }
drh5e00f6c2001-09-13 13:46:56 +00004612 return rc;
4613}
drh5e2f8b92001-05-28 00:41:15 +00004614
drh9562b552002-02-19 15:00:07 +00004615/* Move the cursor to the last entry in the table. Return SQLITE_OK
4616** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00004617** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00004618*/
drh3aac2dd2004-04-26 14:10:20 +00004619int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00004620 int rc;
drhd677b3d2007-08-20 22:48:41 +00004621
drh1fee73e2007-08-29 04:00:57 +00004622 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004623 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19773f632d52009-05-02 10:03:09 +00004624
4625 /* If the cursor already points to the last entry, this is a no-op. */
drh036dbec2014-03-11 23:40:44 +00004626 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
danielk19773f632d52009-05-02 10:03:09 +00004627#ifdef SQLITE_DEBUG
4628 /* This block serves to assert() that the cursor really does point
4629 ** to the last entry in the b-tree. */
4630 int ii;
4631 for(ii=0; ii<pCur->iPage; ii++){
4632 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
4633 }
4634 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
4635 assert( pCur->apPage[pCur->iPage]->leaf );
4636#endif
4637 return SQLITE_OK;
4638 }
4639
drh9562b552002-02-19 15:00:07 +00004640 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004641 if( rc==SQLITE_OK ){
4642 if( CURSOR_INVALID==pCur->eState ){
dana205a482011-08-27 18:48:57 +00004643 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00004644 *pRes = 1;
4645 }else{
4646 assert( pCur->eState==CURSOR_VALID );
4647 *pRes = 0;
4648 rc = moveToRightmost(pCur);
drh036dbec2014-03-11 23:40:44 +00004649 if( rc==SQLITE_OK ){
4650 pCur->curFlags |= BTCF_AtLast;
4651 }else{
4652 pCur->curFlags &= ~BTCF_AtLast;
4653 }
4654
drhd677b3d2007-08-20 22:48:41 +00004655 }
drh9562b552002-02-19 15:00:07 +00004656 }
drh9562b552002-02-19 15:00:07 +00004657 return rc;
4658}
4659
drhe14006d2008-03-25 17:23:32 +00004660/* Move the cursor so that it points to an entry near the key
drhe63d9992008-08-13 19:11:48 +00004661** specified by pIdxKey or intKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00004662**
drhe63d9992008-08-13 19:11:48 +00004663** For INTKEY tables, the intKey parameter is used. pIdxKey
4664** must be NULL. For index tables, pIdxKey is used and intKey
4665** is ignored.
drh3aac2dd2004-04-26 14:10:20 +00004666**
drh5e2f8b92001-05-28 00:41:15 +00004667** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00004668** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00004669** were present. The cursor might point to an entry that comes
4670** before or after the key.
4671**
drh64022502009-01-09 14:11:04 +00004672** An integer is written into *pRes which is the result of
4673** comparing the key with the entry to which the cursor is
4674** pointing. The meaning of the integer written into
4675** *pRes is as follows:
drhbd03cae2001-06-02 02:40:57 +00004676**
4677** *pRes<0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004678** is smaller than intKey/pIdxKey or if the table is empty
drh1a844c32002-12-04 22:29:28 +00004679** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00004680**
4681** *pRes==0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004682** exactly matches intKey/pIdxKey.
drhbd03cae2001-06-02 02:40:57 +00004683**
4684** *pRes>0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004685** is larger than intKey/pIdxKey.
drhd677b3d2007-08-20 22:48:41 +00004686**
drha059ad02001-04-17 20:09:11 +00004687*/
drhe63d9992008-08-13 19:11:48 +00004688int sqlite3BtreeMovetoUnpacked(
4689 BtCursor *pCur, /* The cursor to be moved */
4690 UnpackedRecord *pIdxKey, /* Unpacked index key */
4691 i64 intKey, /* The table key */
4692 int biasRight, /* If true, bias the search to the high end */
4693 int *pRes /* Write search results here */
drhe4d90812007-03-29 05:51:49 +00004694){
drh72f82862001-05-24 21:06:34 +00004695 int rc;
dan3b9330f2014-02-27 20:44:18 +00004696 RecordCompare xRecordCompare;
drhd677b3d2007-08-20 22:48:41 +00004697
drh1fee73e2007-08-29 04:00:57 +00004698 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004699 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19775cb09632009-07-09 11:36:01 +00004700 assert( pRes );
danielk19773fd7cf52009-07-13 07:30:52 +00004701 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
drha2c20e42008-03-29 16:01:04 +00004702
4703 /* If the cursor is already positioned at the point we are trying
4704 ** to move to, then just return without doing any work */
drh036dbec2014-03-11 23:40:44 +00004705 if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
danielk197771d5d2c2008-09-29 11:49:47 +00004706 && pCur->apPage[0]->intKey
4707 ){
drhe63d9992008-08-13 19:11:48 +00004708 if( pCur->info.nKey==intKey ){
drha2c20e42008-03-29 16:01:04 +00004709 *pRes = 0;
4710 return SQLITE_OK;
4711 }
drh036dbec2014-03-11 23:40:44 +00004712 if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
drha2c20e42008-03-29 16:01:04 +00004713 *pRes = -1;
4714 return SQLITE_OK;
4715 }
4716 }
4717
dan1fed5da2014-02-25 21:01:25 +00004718 if( pIdxKey ){
4719 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
dan38fdead2014-04-01 10:19:02 +00004720 pIdxKey->errCode = 0;
dan3b9330f2014-02-27 20:44:18 +00004721 assert( pIdxKey->default_rc==1
4722 || pIdxKey->default_rc==0
4723 || pIdxKey->default_rc==-1
4724 );
drh13a747e2014-03-03 21:46:55 +00004725 }else{
drhb6e8fd12014-03-06 01:56:33 +00004726 xRecordCompare = 0; /* All keys are integers */
dan1fed5da2014-02-25 21:01:25 +00004727 }
4728
drh5e2f8b92001-05-28 00:41:15 +00004729 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004730 if( rc ){
4731 return rc;
4732 }
dana205a482011-08-27 18:48:57 +00004733 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
4734 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
4735 assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
danielk1977da184232006-01-05 11:34:32 +00004736 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00004737 *pRes = -1;
dana205a482011-08-27 18:48:57 +00004738 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
drhc39e0002004-05-07 23:50:57 +00004739 return SQLITE_OK;
4740 }
danielk197771d5d2c2008-09-29 11:49:47 +00004741 assert( pCur->apPage[0]->intKey || pIdxKey );
drh14684382006-11-30 13:05:29 +00004742 for(;;){
drhec3e6b12013-11-25 02:38:55 +00004743 int lwr, upr, idx, c;
drh72f82862001-05-24 21:06:34 +00004744 Pgno chldPg;
danielk197771d5d2c2008-09-29 11:49:47 +00004745 MemPage *pPage = pCur->apPage[pCur->iPage];
drhec3e6b12013-11-25 02:38:55 +00004746 u8 *pCell; /* Pointer to current cell in pPage */
danielk1977171fff32009-07-11 05:06:51 +00004747
4748 /* pPage->nCell must be greater than zero. If this is the root-page
4749 ** the cursor would have been INVALID above and this for(;;) loop
4750 ** not run. If this is not the root-page, then the moveToChild() routine
danielk19773fd7cf52009-07-13 07:30:52 +00004751 ** would have already detected db corruption. Similarly, pPage must
4752 ** be the right kind (index or table) of b-tree page. Otherwise
4753 ** a moveToChild() or moveToRoot() call would have detected corruption. */
danielk1977171fff32009-07-11 05:06:51 +00004754 assert( pPage->nCell>0 );
danielk19773fd7cf52009-07-13 07:30:52 +00004755 assert( pPage->intKey==(pIdxKey==0) );
drh72f82862001-05-24 21:06:34 +00004756 lwr = 0;
4757 upr = pPage->nCell-1;
drhebf10b12013-11-25 17:38:26 +00004758 assert( biasRight==0 || biasRight==1 );
4759 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
drhd793f442013-11-25 14:10:15 +00004760 pCur->aiIdx[pCur->iPage] = (u16)idx;
dana4660bd2014-03-04 16:05:25 +00004761 if( xRecordCompare==0 ){
drhec3e6b12013-11-25 02:38:55 +00004762 for(;;){
danielk197711c327a2009-05-04 19:01:26 +00004763 i64 nCellKey;
drhec3e6b12013-11-25 02:38:55 +00004764 pCell = findCell(pPage, idx) + pPage->childPtrSize;
drh3e28ff52014-09-24 00:59:08 +00004765 if( pPage->intKeyLeaf ){
drh9b2fc612013-11-25 20:14:13 +00004766 while( 0x80 <= *(pCell++) ){
4767 if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
4768 }
drhd172f862006-01-12 15:01:15 +00004769 }
drha2c20e42008-03-29 16:01:04 +00004770 getVarint(pCell, (u64*)&nCellKey);
drhbb933ef2013-11-25 15:01:38 +00004771 if( nCellKey<intKey ){
4772 lwr = idx+1;
4773 if( lwr>upr ){ c = -1; break; }
4774 }else if( nCellKey>intKey ){
4775 upr = idx-1;
4776 if( lwr>upr ){ c = +1; break; }
4777 }else{
4778 assert( nCellKey==intKey );
drh036dbec2014-03-11 23:40:44 +00004779 pCur->curFlags |= BTCF_ValidNKey;
drhec3e6b12013-11-25 02:38:55 +00004780 pCur->info.nKey = nCellKey;
drhd793f442013-11-25 14:10:15 +00004781 pCur->aiIdx[pCur->iPage] = (u16)idx;
drhec3e6b12013-11-25 02:38:55 +00004782 if( !pPage->leaf ){
4783 lwr = idx;
drhebf10b12013-11-25 17:38:26 +00004784 goto moveto_next_layer;
drhec3e6b12013-11-25 02:38:55 +00004785 }else{
4786 *pRes = 0;
4787 rc = SQLITE_OK;
4788 goto moveto_finish;
4789 }
drhd793f442013-11-25 14:10:15 +00004790 }
drhebf10b12013-11-25 17:38:26 +00004791 assert( lwr+upr>=0 );
4792 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
drhec3e6b12013-11-25 02:38:55 +00004793 }
4794 }else{
4795 for(;;){
4796 int nCell;
drhec3e6b12013-11-25 02:38:55 +00004797 pCell = findCell(pPage, idx) + pPage->childPtrSize;
4798
drhb2eced52010-08-12 02:41:12 +00004799 /* The maximum supported page-size is 65536 bytes. This means that
danielk197711c327a2009-05-04 19:01:26 +00004800 ** the maximum number of record bytes stored on an index B-Tree
drhb2eced52010-08-12 02:41:12 +00004801 ** page is less than 16384 bytes and may be stored as a 2-byte
danielk197711c327a2009-05-04 19:01:26 +00004802 ** varint. This information is used to attempt to avoid parsing
4803 ** the entire cell by checking for the cases where the record is
4804 ** stored entirely within the b-tree page by inspecting the first
4805 ** 2 bytes of the cell.
4806 */
drhec3e6b12013-11-25 02:38:55 +00004807 nCell = pCell[0];
drh72b8ef62013-12-06 22:44:51 +00004808 if( nCell<=pPage->max1bytePayload ){
danielk197711c327a2009-05-04 19:01:26 +00004809 /* This branch runs if the record-size field of the cell is a
4810 ** single byte varint and the record fits entirely on the main
4811 ** b-tree page. */
drh3def2352011-11-11 00:27:15 +00004812 testcase( pCell+nCell+1==pPage->aDataEnd );
drh75179de2014-09-16 14:37:35 +00004813 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
danielk197711c327a2009-05-04 19:01:26 +00004814 }else if( !(pCell[1] & 0x80)
4815 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
4816 ){
4817 /* The record-size field is a 2 byte varint and the record
4818 ** fits entirely on the main b-tree page. */
drh3def2352011-11-11 00:27:15 +00004819 testcase( pCell+nCell+2==pPage->aDataEnd );
drh75179de2014-09-16 14:37:35 +00004820 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
drhe51c44f2004-05-30 20:46:09 +00004821 }else{
danielk197711c327a2009-05-04 19:01:26 +00004822 /* The record flows over onto one or more overflow pages. In
4823 ** this case the whole cell needs to be parsed, a buffer allocated
4824 ** and accessPayload() used to retrieve the record into the
4825 ** buffer before VdbeRecordCompare() can be called. */
4826 void *pCellKey;
4827 u8 * const pCellBody = pCell - pPage->childPtrSize;
danielk197730548662009-07-09 05:07:37 +00004828 btreeParseCellPtr(pPage, pCellBody, &pCur->info);
shane60a4b532009-05-06 18:57:09 +00004829 nCell = (int)pCur->info.nKey;
danielk197711c327a2009-05-04 19:01:26 +00004830 pCellKey = sqlite3Malloc( nCell );
danielk19776507ecb2008-03-25 09:56:44 +00004831 if( pCellKey==0 ){
4832 rc = SQLITE_NOMEM;
4833 goto moveto_finish;
4834 }
drhd793f442013-11-25 14:10:15 +00004835 pCur->aiIdx[pCur->iPage] = (u16)idx;
dan5a500af2014-03-11 20:33:04 +00004836 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
drhec9b31f2009-08-25 13:53:49 +00004837 if( rc ){
4838 sqlite3_free(pCellKey);
4839 goto moveto_finish;
4840 }
drh75179de2014-09-16 14:37:35 +00004841 c = xRecordCompare(nCell, pCellKey, pIdxKey);
drhfacf0302008-06-17 15:12:00 +00004842 sqlite3_free(pCellKey);
drhe51c44f2004-05-30 20:46:09 +00004843 }
dan38fdead2014-04-01 10:19:02 +00004844 assert(
4845 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
dana7bf23c2014-05-02 17:12:41 +00004846 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
dan38fdead2014-04-01 10:19:02 +00004847 );
drhbb933ef2013-11-25 15:01:38 +00004848 if( c<0 ){
4849 lwr = idx+1;
4850 }else if( c>0 ){
4851 upr = idx-1;
4852 }else{
4853 assert( c==0 );
drh64022502009-01-09 14:11:04 +00004854 *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00004855 rc = SQLITE_OK;
drhd793f442013-11-25 14:10:15 +00004856 pCur->aiIdx[pCur->iPage] = (u16)idx;
dan38fdead2014-04-01 10:19:02 +00004857 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
drh1e968a02008-03-25 00:22:21 +00004858 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00004859 }
drhebf10b12013-11-25 17:38:26 +00004860 if( lwr>upr ) break;
4861 assert( lwr+upr>=0 );
4862 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
drh72f82862001-05-24 21:06:34 +00004863 }
drh72f82862001-05-24 21:06:34 +00004864 }
drhb07028f2011-10-14 21:49:18 +00004865 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
danielk197771d5d2c2008-09-29 11:49:47 +00004866 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00004867 if( pPage->leaf ){
drhec3e6b12013-11-25 02:38:55 +00004868 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drhbb933ef2013-11-25 15:01:38 +00004869 pCur->aiIdx[pCur->iPage] = (u16)idx;
drhec3e6b12013-11-25 02:38:55 +00004870 *pRes = c;
4871 rc = SQLITE_OK;
4872 goto moveto_finish;
drhebf10b12013-11-25 17:38:26 +00004873 }
4874moveto_next_layer:
4875 if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00004876 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00004877 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00004878 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00004879 }
drhf49661a2008-12-10 16:45:50 +00004880 pCur->aiIdx[pCur->iPage] = (u16)lwr;
drh8178a752003-01-05 21:41:40 +00004881 rc = moveToChild(pCur, chldPg);
drhec3e6b12013-11-25 02:38:55 +00004882 if( rc ) break;
drh72f82862001-05-24 21:06:34 +00004883 }
drh1e968a02008-03-25 00:22:21 +00004884moveto_finish:
drhd2022b02013-11-25 16:23:52 +00004885 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004886 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drhe63d9992008-08-13 19:11:48 +00004887 return rc;
4888}
4889
drhd677b3d2007-08-20 22:48:41 +00004890
drh72f82862001-05-24 21:06:34 +00004891/*
drhc39e0002004-05-07 23:50:57 +00004892** Return TRUE if the cursor is not pointing at an entry of the table.
4893**
4894** TRUE will be returned after a call to sqlite3BtreeNext() moves
4895** past the last entry in the table or sqlite3BtreePrev() moves past
4896** the first entry. TRUE is also returned if the table is empty.
4897*/
4898int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00004899 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
4900 ** have been deleted? This API will need to change to return an error code
4901 ** as well as the boolean result value.
4902 */
4903 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00004904}
4905
4906/*
drhbd03cae2001-06-02 02:40:57 +00004907** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00004908** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00004909** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00004910** this routine was called, then set *pRes=1.
drhe39a7322014-02-03 14:04:11 +00004911**
drhee6438d2014-09-01 13:29:32 +00004912** The main entry point is sqlite3BtreeNext(). That routine is optimized
4913** for the common case of merely incrementing the cell counter BtCursor.aiIdx
4914** to the next cell on the current page. The (slower) btreeNext() helper
4915** routine is called when it is necessary to move to a different page or
4916** to restore the cursor.
4917**
drhe39a7322014-02-03 14:04:11 +00004918** The calling function will set *pRes to 0 or 1. The initial *pRes value
4919** will be 1 if the cursor being stepped corresponds to an SQL index and
4920** if this routine could have been skipped if that SQL index had been
4921** a unique index. Otherwise the caller will have set *pRes to zero.
4922** Zero is the common case. The btree implementation is free to use the
4923** initial *pRes value as a hint to improve performance, but the current
4924** SQLite btree implementation does not. (Note that the comdb2 btree
4925** implementation does use this hint, however.)
drh72f82862001-05-24 21:06:34 +00004926*/
drhee6438d2014-09-01 13:29:32 +00004927static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00004928 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004929 int idx;
danielk197797a227c2006-01-20 16:32:04 +00004930 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00004931
drh1fee73e2007-08-29 04:00:57 +00004932 assert( cursorHoldsMutex(pCur) );
drh9b47ee32013-08-20 03:13:51 +00004933 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
drhee6438d2014-09-01 13:29:32 +00004934 assert( *pRes==0 );
drhf66f26a2013-08-19 20:04:10 +00004935 if( pCur->eState!=CURSOR_VALID ){
drhee6438d2014-09-01 13:29:32 +00004936 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
drhf66f26a2013-08-19 20:04:10 +00004937 rc = restoreCursorPosition(pCur);
4938 if( rc!=SQLITE_OK ){
4939 return rc;
4940 }
4941 if( CURSOR_INVALID==pCur->eState ){
4942 *pRes = 1;
4943 return SQLITE_OK;
4944 }
drh9b47ee32013-08-20 03:13:51 +00004945 if( pCur->skipNext ){
4946 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
4947 pCur->eState = CURSOR_VALID;
4948 if( pCur->skipNext>0 ){
4949 pCur->skipNext = 0;
drh9b47ee32013-08-20 03:13:51 +00004950 return SQLITE_OK;
4951 }
drhf66f26a2013-08-19 20:04:10 +00004952 pCur->skipNext = 0;
drhf66f26a2013-08-19 20:04:10 +00004953 }
danielk1977da184232006-01-05 11:34:32 +00004954 }
danielk1977da184232006-01-05 11:34:32 +00004955
danielk197771d5d2c2008-09-29 11:49:47 +00004956 pPage = pCur->apPage[pCur->iPage];
4957 idx = ++pCur->aiIdx[pCur->iPage];
4958 assert( pPage->isInit );
danbb246c42012-01-12 14:25:55 +00004959
4960 /* If the database file is corrupt, it is possible for the value of idx
4961 ** to be invalid here. This can only occur if a second cursor modifies
4962 ** the page while cursor pCur is holding a reference to it. Which can
4963 ** only happen if the database is corrupt in such a way as to link the
4964 ** page into more than one b-tree structure. */
4965 testcase( idx>pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00004966
danielk197771d5d2c2008-09-29 11:49:47 +00004967 if( idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00004968 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004969 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drhee6438d2014-09-01 13:29:32 +00004970 if( rc ) return rc;
4971 return moveToLeftmost(pCur);
drh72f82862001-05-24 21:06:34 +00004972 }
drh5e2f8b92001-05-28 00:41:15 +00004973 do{
danielk197771d5d2c2008-09-29 11:49:47 +00004974 if( pCur->iPage==0 ){
drh8c1238a2003-01-02 14:43:55 +00004975 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00004976 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00004977 return SQLITE_OK;
4978 }
danielk197730548662009-07-09 05:07:37 +00004979 moveToParent(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00004980 pPage = pCur->apPage[pCur->iPage];
4981 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
drh44845222008-07-17 18:39:57 +00004982 if( pPage->intKey ){
drhee6438d2014-09-01 13:29:32 +00004983 return sqlite3BtreeNext(pCur, pRes);
drh8b18dd42004-05-12 19:18:15 +00004984 }else{
drhee6438d2014-09-01 13:29:32 +00004985 return SQLITE_OK;
drh8b18dd42004-05-12 19:18:15 +00004986 }
drh8178a752003-01-05 21:41:40 +00004987 }
drh3aac2dd2004-04-26 14:10:20 +00004988 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00004989 return SQLITE_OK;
drhee6438d2014-09-01 13:29:32 +00004990 }else{
4991 return moveToLeftmost(pCur);
drh72f82862001-05-24 21:06:34 +00004992 }
drh72f82862001-05-24 21:06:34 +00004993}
drhee6438d2014-09-01 13:29:32 +00004994int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
4995 MemPage *pPage;
4996 assert( cursorHoldsMutex(pCur) );
4997 assert( pRes!=0 );
4998 assert( *pRes==0 || *pRes==1 );
4999 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5000 pCur->info.nSize = 0;
5001 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5002 *pRes = 0;
5003 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
5004 pPage = pCur->apPage[pCur->iPage];
5005 if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
5006 pCur->aiIdx[pCur->iPage]--;
5007 return btreeNext(pCur, pRes);
5008 }
5009 if( pPage->leaf ){
5010 return SQLITE_OK;
5011 }else{
5012 return moveToLeftmost(pCur);
5013 }
5014}
drh72f82862001-05-24 21:06:34 +00005015
drh3b7511c2001-05-26 13:15:44 +00005016/*
drh2dcc9aa2002-12-04 13:40:25 +00005017** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00005018** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00005019** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00005020** this routine was called, then set *pRes=1.
drhe39a7322014-02-03 14:04:11 +00005021**
drhee6438d2014-09-01 13:29:32 +00005022** The main entry point is sqlite3BtreePrevious(). That routine is optimized
5023** for the common case of merely decrementing the cell counter BtCursor.aiIdx
drh3f387402014-09-24 01:23:00 +00005024** to the previous cell on the current page. The (slower) btreePrevious()
5025** helper routine is called when it is necessary to move to a different page
5026** or to restore the cursor.
drhee6438d2014-09-01 13:29:32 +00005027**
drhe39a7322014-02-03 14:04:11 +00005028** The calling function will set *pRes to 0 or 1. The initial *pRes value
5029** will be 1 if the cursor being stepped corresponds to an SQL index and
5030** if this routine could have been skipped if that SQL index had been
5031** a unique index. Otherwise the caller will have set *pRes to zero.
5032** Zero is the common case. The btree implementation is free to use the
5033** initial *pRes value as a hint to improve performance, but the current
5034** SQLite btree implementation does not. (Note that the comdb2 btree
5035** implementation does use this hint, however.)
drh2dcc9aa2002-12-04 13:40:25 +00005036*/
drhee6438d2014-09-01 13:29:32 +00005037static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00005038 int rc;
drh8178a752003-01-05 21:41:40 +00005039 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00005040
drh1fee73e2007-08-29 04:00:57 +00005041 assert( cursorHoldsMutex(pCur) );
drh9b47ee32013-08-20 03:13:51 +00005042 assert( pRes!=0 );
drhee6438d2014-09-01 13:29:32 +00005043 assert( *pRes==0 );
drh9b47ee32013-08-20 03:13:51 +00005044 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
drhee6438d2014-09-01 13:29:32 +00005045 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
5046 assert( pCur->info.nSize==0 );
drhf66f26a2013-08-19 20:04:10 +00005047 if( pCur->eState!=CURSOR_VALID ){
drh7682a472014-09-29 15:00:28 +00005048 rc = restoreCursorPosition(pCur);
drhee6438d2014-09-01 13:29:32 +00005049 if( rc!=SQLITE_OK ){
5050 return rc;
drhf66f26a2013-08-19 20:04:10 +00005051 }
5052 if( CURSOR_INVALID==pCur->eState ){
5053 *pRes = 1;
5054 return SQLITE_OK;
5055 }
drh9b47ee32013-08-20 03:13:51 +00005056 if( pCur->skipNext ){
5057 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5058 pCur->eState = CURSOR_VALID;
5059 if( pCur->skipNext<0 ){
5060 pCur->skipNext = 0;
drh9b47ee32013-08-20 03:13:51 +00005061 return SQLITE_OK;
5062 }
drhf66f26a2013-08-19 20:04:10 +00005063 pCur->skipNext = 0;
drhf66f26a2013-08-19 20:04:10 +00005064 }
danielk1977da184232006-01-05 11:34:32 +00005065 }
danielk1977da184232006-01-05 11:34:32 +00005066
danielk197771d5d2c2008-09-29 11:49:47 +00005067 pPage = pCur->apPage[pCur->iPage];
5068 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00005069 if( !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00005070 int idx = pCur->aiIdx[pCur->iPage];
5071 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
drhee6438d2014-09-01 13:29:32 +00005072 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00005073 rc = moveToRightmost(pCur);
5074 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00005075 while( pCur->aiIdx[pCur->iPage]==0 ){
5076 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00005077 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00005078 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00005079 return SQLITE_OK;
5080 }
danielk197730548662009-07-09 05:07:37 +00005081 moveToParent(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00005082 }
drhee6438d2014-09-01 13:29:32 +00005083 assert( pCur->info.nSize==0 );
5084 assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00005085
5086 pCur->aiIdx[pCur->iPage]--;
5087 pPage = pCur->apPage[pCur->iPage];
drh44845222008-07-17 18:39:57 +00005088 if( pPage->intKey && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00005089 rc = sqlite3BtreePrevious(pCur, pRes);
5090 }else{
5091 rc = SQLITE_OK;
5092 }
drh2dcc9aa2002-12-04 13:40:25 +00005093 }
drh2dcc9aa2002-12-04 13:40:25 +00005094 return rc;
5095}
drhee6438d2014-09-01 13:29:32 +00005096int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
5097 assert( cursorHoldsMutex(pCur) );
5098 assert( pRes!=0 );
5099 assert( *pRes==0 || *pRes==1 );
5100 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5101 *pRes = 0;
5102 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
5103 pCur->info.nSize = 0;
5104 if( pCur->eState!=CURSOR_VALID
5105 || pCur->aiIdx[pCur->iPage]==0
5106 || pCur->apPage[pCur->iPage]->leaf==0
5107 ){
5108 return btreePrevious(pCur, pRes);
5109 }
5110 pCur->aiIdx[pCur->iPage]--;
5111 return SQLITE_OK;
5112}
drh2dcc9aa2002-12-04 13:40:25 +00005113
5114/*
drh3b7511c2001-05-26 13:15:44 +00005115** Allocate a new page from the database file.
5116**
danielk19773b8a05f2007-03-19 17:44:26 +00005117** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00005118** has already been called on the new page.) The new page has also
5119** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00005120** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00005121**
5122** SQLITE_OK is returned on success. Any other return value indicates
5123** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00005124** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00005125**
drh82e647d2013-03-02 03:25:55 +00005126** If the "nearby" parameter is not 0, then an effort is made to
drh199e3cf2002-07-18 11:01:47 +00005127** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00005128** attempt to keep related pages close to each other in the database file,
5129** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00005130**
drh82e647d2013-03-02 03:25:55 +00005131** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
5132** anywhere on the free-list, then it is guaranteed to be returned. If
5133** eMode is BTALLOC_LT then the page returned will be less than or equal
5134** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
5135** are no restrictions on which page is returned.
drh3b7511c2001-05-26 13:15:44 +00005136*/
drh4f0c5872007-03-26 22:05:01 +00005137static int allocateBtreePage(
drh82e647d2013-03-02 03:25:55 +00005138 BtShared *pBt, /* The btree */
5139 MemPage **ppPage, /* Store pointer to the allocated page here */
5140 Pgno *pPgno, /* Store the page number here */
5141 Pgno nearby, /* Search for a page near this one */
5142 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005143){
drh3aac2dd2004-04-26 14:10:20 +00005144 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00005145 int rc;
drh35cd6432009-06-05 14:17:21 +00005146 u32 n; /* Number of pages on the freelist */
drh042d6a12009-06-17 13:57:16 +00005147 u32 k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00005148 MemPage *pTrunk = 0;
5149 MemPage *pPrevTrunk = 0;
drh1662b5a2009-06-04 19:06:09 +00005150 Pgno mxPage; /* Total size of the database file */
drh30e58752002-03-02 20:41:57 +00005151
drh1fee73e2007-08-29 04:00:57 +00005152 assert( sqlite3_mutex_held(pBt->mutex) );
dan09ff9e12013-03-11 11:49:03 +00005153 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
drh3aac2dd2004-04-26 14:10:20 +00005154 pPage1 = pBt->pPage1;
drhb1299152010-03-30 22:58:33 +00005155 mxPage = btreePagecount(pBt);
drh3aac2dd2004-04-26 14:10:20 +00005156 n = get4byte(&pPage1->aData[36]);
drhdf35a082009-07-09 02:24:35 +00005157 testcase( n==mxPage-1 );
5158 if( n>=mxPage ){
drh1662b5a2009-06-04 19:06:09 +00005159 return SQLITE_CORRUPT_BKPT;
5160 }
drh3aac2dd2004-04-26 14:10:20 +00005161 if( n>0 ){
drh91025292004-05-03 19:49:32 +00005162 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005163 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005164 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
5165
drh82e647d2013-03-02 03:25:55 +00005166 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00005167 ** shows that the page 'nearby' is somewhere on the free-list, then
5168 ** the entire-list will be searched for that page.
5169 */
5170#ifndef SQLITE_OMIT_AUTOVACUUM
dan51f0b6d2013-02-22 20:16:34 +00005171 if( eMode==BTALLOC_EXACT ){
5172 if( nearby<=mxPage ){
5173 u8 eType;
5174 assert( nearby>0 );
5175 assert( pBt->autoVacuum );
5176 rc = ptrmapGet(pBt, nearby, &eType, 0);
5177 if( rc ) return rc;
5178 if( eType==PTRMAP_FREEPAGE ){
5179 searchList = 1;
5180 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005181 }
dan51f0b6d2013-02-22 20:16:34 +00005182 }else if( eMode==BTALLOC_LE ){
5183 searchList = 1;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005184 }
5185#endif
5186
5187 /* Decrement the free-list count by 1. Set iTrunk to the index of the
5188 ** first free-list trunk page. iPrevTrunk is initially 1.
5189 */
danielk19773b8a05f2007-03-19 17:44:26 +00005190 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00005191 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00005192 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005193
5194 /* The code within this loop is run only once if the 'searchList' variable
5195 ** is not true. Otherwise, it runs once for each trunk-page on the
drh82e647d2013-03-02 03:25:55 +00005196 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
5197 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
danielk1977cb1a7eb2004-11-05 12:27:02 +00005198 */
5199 do {
5200 pPrevTrunk = pTrunk;
5201 if( pPrevTrunk ){
5202 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00005203 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00005204 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00005205 }
drhdf35a082009-07-09 02:24:35 +00005206 testcase( iTrunk==mxPage );
drh1662b5a2009-06-04 19:06:09 +00005207 if( iTrunk>mxPage ){
5208 rc = SQLITE_CORRUPT_BKPT;
5209 }else{
drhb00fc3b2013-08-21 23:42:32 +00005210 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
drh1662b5a2009-06-04 19:06:09 +00005211 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005212 if( rc ){
drhd3627af2006-12-18 18:34:51 +00005213 pTrunk = 0;
5214 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005215 }
drhb07028f2011-10-14 21:49:18 +00005216 assert( pTrunk!=0 );
5217 assert( pTrunk->aData!=0 );
danielk1977cb1a7eb2004-11-05 12:27:02 +00005218
drh93b4fc72011-04-07 14:47:01 +00005219 k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005220 if( k==0 && !searchList ){
5221 /* The trunk has no leaves and the list is not being searched.
5222 ** So extract the trunk page itself and use it as the newly
5223 ** allocated page */
5224 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00005225 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00005226 if( rc ){
5227 goto end_allocate_page;
5228 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005229 *pPgno = iTrunk;
5230 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5231 *ppPage = pTrunk;
5232 pTrunk = 0;
5233 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh042d6a12009-06-17 13:57:16 +00005234 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00005235 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00005236 rc = SQLITE_CORRUPT_BKPT;
5237 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005238#ifndef SQLITE_OMIT_AUTOVACUUM
dan51f0b6d2013-02-22 20:16:34 +00005239 }else if( searchList
5240 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
5241 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00005242 /* The list is being searched and this trunk page is the page
5243 ** to allocate, regardless of whether it has leaves.
5244 */
dan51f0b6d2013-02-22 20:16:34 +00005245 *pPgno = iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005246 *ppPage = pTrunk;
5247 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005248 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00005249 if( rc ){
5250 goto end_allocate_page;
5251 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005252 if( k==0 ){
5253 if( !pPrevTrunk ){
5254 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5255 }else{
danf48c3552010-08-23 15:41:24 +00005256 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
5257 if( rc!=SQLITE_OK ){
5258 goto end_allocate_page;
5259 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005260 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
5261 }
5262 }else{
5263 /* The trunk page is required by the caller but it contains
5264 ** pointers to free-list leaves. The first leaf becomes a trunk
5265 ** page in this case.
5266 */
5267 MemPage *pNewTrunk;
5268 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh1662b5a2009-06-04 19:06:09 +00005269 if( iNewTrunk>mxPage ){
5270 rc = SQLITE_CORRUPT_BKPT;
5271 goto end_allocate_page;
5272 }
drhdf35a082009-07-09 02:24:35 +00005273 testcase( iNewTrunk==mxPage );
drhb00fc3b2013-08-21 23:42:32 +00005274 rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005275 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00005276 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005277 }
danielk19773b8a05f2007-03-19 17:44:26 +00005278 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005279 if( rc!=SQLITE_OK ){
5280 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00005281 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005282 }
5283 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
5284 put4byte(&pNewTrunk->aData[4], k-1);
5285 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00005286 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005287 if( !pPrevTrunk ){
drhc5053fb2008-11-27 02:22:10 +00005288 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
danielk1977cb1a7eb2004-11-05 12:27:02 +00005289 put4byte(&pPage1->aData[32], iNewTrunk);
5290 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00005291 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00005292 if( rc ){
5293 goto end_allocate_page;
5294 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005295 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
5296 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005297 }
5298 pTrunk = 0;
5299 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
5300#endif
danielk1977e5765212009-06-17 11:13:28 +00005301 }else if( k>0 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00005302 /* Extract a leaf from the trunk */
drh042d6a12009-06-17 13:57:16 +00005303 u32 closest;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005304 Pgno iPage;
5305 unsigned char *aData = pTrunk->aData;
5306 if( nearby>0 ){
drh042d6a12009-06-17 13:57:16 +00005307 u32 i;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005308 closest = 0;
danf38b65a2013-02-22 20:57:47 +00005309 if( eMode==BTALLOC_LE ){
5310 for(i=0; i<k; i++){
5311 iPage = get4byte(&aData[8+i*4]);
dan87ade192013-02-23 17:49:16 +00005312 if( iPage<=nearby ){
danf38b65a2013-02-22 20:57:47 +00005313 closest = i;
5314 break;
5315 }
5316 }
5317 }else{
5318 int dist;
5319 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
5320 for(i=1; i<k; i++){
5321 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
5322 if( d2<dist ){
5323 closest = i;
5324 dist = d2;
5325 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005326 }
5327 }
5328 }else{
5329 closest = 0;
5330 }
5331
5332 iPage = get4byte(&aData[8+closest*4]);
drhdf35a082009-07-09 02:24:35 +00005333 testcase( iPage==mxPage );
drh1662b5a2009-06-04 19:06:09 +00005334 if( iPage>mxPage ){
5335 rc = SQLITE_CORRUPT_BKPT;
5336 goto end_allocate_page;
5337 }
drhdf35a082009-07-09 02:24:35 +00005338 testcase( iPage==mxPage );
dan51f0b6d2013-02-22 20:16:34 +00005339 if( !searchList
5340 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
5341 ){
danielk1977bea2a942009-01-20 17:06:27 +00005342 int noContent;
shane1f9e6aa2008-06-09 19:27:11 +00005343 *pPgno = iPage;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005344 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
5345 ": %d more free pages\n",
5346 *pPgno, closest+1, k, pTrunk->pgno, n-1));
drh93b4fc72011-04-07 14:47:01 +00005347 rc = sqlite3PagerWrite(pTrunk->pDbPage);
5348 if( rc ) goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005349 if( closest<k-1 ){
5350 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
5351 }
5352 put4byte(&aData[4], k-1);
drh3f387402014-09-24 01:23:00 +00005353 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
drhb00fc3b2013-08-21 23:42:32 +00005354 rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005355 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00005356 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00005357 if( rc!=SQLITE_OK ){
5358 releasePage(*ppPage);
5359 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005360 }
5361 searchList = 0;
5362 }
drhee696e22004-08-30 16:52:17 +00005363 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005364 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00005365 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005366 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00005367 }else{
danbc1a3c62013-02-23 16:40:46 +00005368 /* There are no pages on the freelist, so append a new page to the
5369 ** database image.
5370 **
5371 ** Normally, new pages allocated by this block can be requested from the
5372 ** pager layer with the 'no-content' flag set. This prevents the pager
5373 ** from trying to read the pages content from disk. However, if the
5374 ** current transaction has already run one or more incremental-vacuum
5375 ** steps, then the page we are about to allocate may contain content
5376 ** that is required in the event of a rollback. In this case, do
5377 ** not set the no-content flag. This causes the pager to load and journal
5378 ** the current page content before overwriting it.
5379 **
5380 ** Note that the pager will not actually attempt to load or journal
5381 ** content for any page that really does lie past the end of the database
5382 ** file on disk. So the effects of disabling the no-content optimization
5383 ** here are confined to those pages that lie between the end of the
5384 ** database image and the end of the database file.
5385 */
drh3f387402014-09-24 01:23:00 +00005386 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
danbc1a3c62013-02-23 16:40:46 +00005387
drhdd3cd972010-03-27 17:12:36 +00005388 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
5389 if( rc ) return rc;
5390 pBt->nPage++;
5391 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
danielk1977bea2a942009-01-20 17:06:27 +00005392
danielk1977afcdd022004-10-31 16:25:42 +00005393#ifndef SQLITE_OMIT_AUTOVACUUM
drhdd3cd972010-03-27 17:12:36 +00005394 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
danielk1977afcdd022004-10-31 16:25:42 +00005395 /* If *pPgno refers to a pointer-map page, allocate two new pages
5396 ** at the end of the file instead of one. The first allocated page
5397 ** becomes a new pointer-map page, the second is used by the caller.
5398 */
danielk1977ac861692009-03-28 10:54:22 +00005399 MemPage *pPg = 0;
drhdd3cd972010-03-27 17:12:36 +00005400 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
5401 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
drhb00fc3b2013-08-21 23:42:32 +00005402 rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
danielk1977ac861692009-03-28 10:54:22 +00005403 if( rc==SQLITE_OK ){
5404 rc = sqlite3PagerWrite(pPg->pDbPage);
5405 releasePage(pPg);
5406 }
5407 if( rc ) return rc;
drhdd3cd972010-03-27 17:12:36 +00005408 pBt->nPage++;
5409 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
danielk1977afcdd022004-10-31 16:25:42 +00005410 }
5411#endif
drhdd3cd972010-03-27 17:12:36 +00005412 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
5413 *pPgno = pBt->nPage;
danielk1977afcdd022004-10-31 16:25:42 +00005414
danielk1977599fcba2004-11-08 07:13:13 +00005415 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhb00fc3b2013-08-21 23:42:32 +00005416 rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
drh3b7511c2001-05-26 13:15:44 +00005417 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00005418 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00005419 if( rc!=SQLITE_OK ){
5420 releasePage(*ppPage);
5421 }
drh3a4c1412004-05-09 20:40:11 +00005422 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00005423 }
danielk1977599fcba2004-11-08 07:13:13 +00005424
5425 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00005426
5427end_allocate_page:
5428 releasePage(pTrunk);
5429 releasePage(pPrevTrunk);
danielk1977b247c212008-11-21 09:09:01 +00005430 if( rc==SQLITE_OK ){
5431 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
5432 releasePage(*ppPage);
dan7df42ab2014-01-20 18:25:44 +00005433 *ppPage = 0;
danielk1977b247c212008-11-21 09:09:01 +00005434 return SQLITE_CORRUPT_BKPT;
5435 }
5436 (*ppPage)->isInit = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00005437 }else{
5438 *ppPage = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00005439 }
drh93b4fc72011-04-07 14:47:01 +00005440 assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
drh3b7511c2001-05-26 13:15:44 +00005441 return rc;
5442}
5443
5444/*
danielk1977bea2a942009-01-20 17:06:27 +00005445** This function is used to add page iPage to the database file free-list.
5446** It is assumed that the page is not already a part of the free-list.
drh5e2f8b92001-05-28 00:41:15 +00005447**
danielk1977bea2a942009-01-20 17:06:27 +00005448** The value passed as the second argument to this function is optional.
5449** If the caller happens to have a pointer to the MemPage object
5450** corresponding to page iPage handy, it may pass it as the second value.
5451** Otherwise, it may pass NULL.
5452**
5453** If a pointer to a MemPage object is passed as the second argument,
5454** its reference count is not altered by this function.
drh3b7511c2001-05-26 13:15:44 +00005455*/
danielk1977bea2a942009-01-20 17:06:27 +00005456static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
5457 MemPage *pTrunk = 0; /* Free-list trunk page */
5458 Pgno iTrunk = 0; /* Page number of free-list trunk page */
5459 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
5460 MemPage *pPage; /* Page being freed. May be NULL. */
5461 int rc; /* Return Code */
5462 int nFree; /* Initial number of pages on free-list */
drh8b2f49b2001-06-08 00:21:52 +00005463
danielk1977bea2a942009-01-20 17:06:27 +00005464 assert( sqlite3_mutex_held(pBt->mutex) );
5465 assert( iPage>1 );
5466 assert( !pMemPage || pMemPage->pgno==iPage );
5467
5468 if( pMemPage ){
5469 pPage = pMemPage;
5470 sqlite3PagerRef(pPage->pDbPage);
5471 }else{
5472 pPage = btreePageLookup(pBt, iPage);
5473 }
drh3aac2dd2004-04-26 14:10:20 +00005474
drha34b6762004-05-07 13:30:42 +00005475 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00005476 rc = sqlite3PagerWrite(pPage1->pDbPage);
danielk1977bea2a942009-01-20 17:06:27 +00005477 if( rc ) goto freepage_out;
5478 nFree = get4byte(&pPage1->aData[36]);
5479 put4byte(&pPage1->aData[36], nFree+1);
drh3aac2dd2004-04-26 14:10:20 +00005480
drhc9166342012-01-05 23:32:06 +00005481 if( pBt->btsFlags & BTS_SECURE_DELETE ){
drh5b47efa2010-02-12 18:18:39 +00005482 /* If the secure_delete option is enabled, then
5483 ** always fully overwrite deleted information with zeros.
5484 */
drhb00fc3b2013-08-21 23:42:32 +00005485 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
shaneh84f4b2f2010-02-26 01:46:54 +00005486 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
drh5b47efa2010-02-12 18:18:39 +00005487 ){
5488 goto freepage_out;
5489 }
5490 memset(pPage->aData, 0, pPage->pBt->pageSize);
danielk1977bea2a942009-01-20 17:06:27 +00005491 }
drhfcce93f2006-02-22 03:08:32 +00005492
danielk1977687566d2004-11-02 12:56:41 +00005493 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00005494 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00005495 */
danielk197785d90ca2008-07-19 14:25:15 +00005496 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00005497 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
danielk1977bea2a942009-01-20 17:06:27 +00005498 if( rc ) goto freepage_out;
danielk1977687566d2004-11-02 12:56:41 +00005499 }
danielk1977687566d2004-11-02 12:56:41 +00005500
danielk1977bea2a942009-01-20 17:06:27 +00005501 /* Now manipulate the actual database free-list structure. There are two
5502 ** possibilities. If the free-list is currently empty, or if the first
5503 ** trunk page in the free-list is full, then this page will become a
5504 ** new free-list trunk page. Otherwise, it will become a leaf of the
5505 ** first trunk page in the current free-list. This block tests if it
5506 ** is possible to add the page as a new free-list leaf.
5507 */
5508 if( nFree!=0 ){
drhc046e3e2009-07-15 11:26:44 +00005509 u32 nLeaf; /* Initial number of leaf cells on trunk page */
danielk1977bea2a942009-01-20 17:06:27 +00005510
5511 iTrunk = get4byte(&pPage1->aData[32]);
drhb00fc3b2013-08-21 23:42:32 +00005512 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977bea2a942009-01-20 17:06:27 +00005513 if( rc!=SQLITE_OK ){
5514 goto freepage_out;
5515 }
5516
5517 nLeaf = get4byte(&pTrunk->aData[4]);
drheeb844a2009-08-08 18:01:07 +00005518 assert( pBt->usableSize>32 );
5519 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
danielk1977bea2a942009-01-20 17:06:27 +00005520 rc = SQLITE_CORRUPT_BKPT;
5521 goto freepage_out;
5522 }
drheeb844a2009-08-08 18:01:07 +00005523 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
danielk1977bea2a942009-01-20 17:06:27 +00005524 /* In this case there is room on the trunk page to insert the page
5525 ** being freed as a new leaf.
drh45b1fac2008-07-04 17:52:42 +00005526 **
5527 ** Note that the trunk page is not really full until it contains
5528 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
5529 ** coded. But due to a coding error in versions of SQLite prior to
5530 ** 3.6.0, databases with freelist trunk pages holding more than
5531 ** usableSize/4 - 8 entries will be reported as corrupt. In order
5532 ** to maintain backwards compatibility with older versions of SQLite,
drhc046e3e2009-07-15 11:26:44 +00005533 ** we will continue to restrict the number of entries to usableSize/4 - 8
drh45b1fac2008-07-04 17:52:42 +00005534 ** for now. At some point in the future (once everyone has upgraded
5535 ** to 3.6.0 or later) we should consider fixing the conditional above
5536 ** to read "usableSize/4-2" instead of "usableSize/4-8".
5537 */
danielk19773b8a05f2007-03-19 17:44:26 +00005538 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00005539 if( rc==SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00005540 put4byte(&pTrunk->aData[4], nLeaf+1);
5541 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
drhc9166342012-01-05 23:32:06 +00005542 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
danielk1977bea2a942009-01-20 17:06:27 +00005543 sqlite3PagerDontWrite(pPage->pDbPage);
5544 }
danielk1977bea2a942009-01-20 17:06:27 +00005545 rc = btreeSetHasContent(pBt, iPage);
drhf5345442007-04-09 12:45:02 +00005546 }
drh3a4c1412004-05-09 20:40:11 +00005547 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
danielk1977bea2a942009-01-20 17:06:27 +00005548 goto freepage_out;
drh3aac2dd2004-04-26 14:10:20 +00005549 }
drh3b7511c2001-05-26 13:15:44 +00005550 }
danielk1977bea2a942009-01-20 17:06:27 +00005551
5552 /* If control flows to this point, then it was not possible to add the
5553 ** the page being freed as a leaf page of the first trunk in the free-list.
5554 ** Possibly because the free-list is empty, or possibly because the
5555 ** first trunk in the free-list is full. Either way, the page being freed
5556 ** will become the new first trunk page in the free-list.
5557 */
drhb00fc3b2013-08-21 23:42:32 +00005558 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
drhc046e3e2009-07-15 11:26:44 +00005559 goto freepage_out;
5560 }
5561 rc = sqlite3PagerWrite(pPage->pDbPage);
5562 if( rc!=SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00005563 goto freepage_out;
5564 }
5565 put4byte(pPage->aData, iTrunk);
5566 put4byte(&pPage->aData[4], 0);
5567 put4byte(&pPage1->aData[32], iPage);
5568 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
5569
5570freepage_out:
5571 if( pPage ){
5572 pPage->isInit = 0;
5573 }
5574 releasePage(pPage);
5575 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00005576 return rc;
5577}
drhc314dc72009-07-21 11:52:34 +00005578static void freePage(MemPage *pPage, int *pRC){
5579 if( (*pRC)==SQLITE_OK ){
5580 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
5581 }
danielk1977bea2a942009-01-20 17:06:27 +00005582}
drh3b7511c2001-05-26 13:15:44 +00005583
5584/*
drh9bfdc252014-09-24 02:05:41 +00005585** Free any overflow pages associated with the given Cell. Write the
5586** local Cell size (the number of bytes on the original page, omitting
5587** overflow) into *pnSize.
drh3b7511c2001-05-26 13:15:44 +00005588*/
drh9bfdc252014-09-24 02:05:41 +00005589static int clearCell(
5590 MemPage *pPage, /* The page that contains the Cell */
5591 unsigned char *pCell, /* First byte of the Cell */
5592 u16 *pnSize /* Write the size of the Cell here */
5593){
danielk1977aef0bf62005-12-30 16:28:01 +00005594 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00005595 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00005596 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00005597 int rc;
drh94440812007-03-06 11:42:19 +00005598 int nOvfl;
shaneh1df2db72010-08-18 02:28:48 +00005599 u32 ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00005600
drh1fee73e2007-08-29 04:00:57 +00005601 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197730548662009-07-09 05:07:37 +00005602 btreeParseCellPtr(pPage, pCell, &info);
drh9bfdc252014-09-24 02:05:41 +00005603 *pnSize = info.nSize;
drh6f11bef2004-05-13 01:12:56 +00005604 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00005605 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00005606 }
drhe42a9b42011-08-31 13:27:19 +00005607 if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
mistachkin70a1b712012-09-28 18:13:35 +00005608 return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
drhe42a9b42011-08-31 13:27:19 +00005609 }
drh6f11bef2004-05-13 01:12:56 +00005610 ovflPgno = get4byte(&pCell[info.iOverflow]);
shane63207ab2009-02-04 01:49:30 +00005611 assert( pBt->usableSize > 4 );
drh94440812007-03-06 11:42:19 +00005612 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00005613 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
5614 assert( ovflPgno==0 || nOvfl>0 );
5615 while( nOvfl-- ){
shane63207ab2009-02-04 01:49:30 +00005616 Pgno iNext = 0;
danielk1977bea2a942009-01-20 17:06:27 +00005617 MemPage *pOvfl = 0;
drhb1299152010-03-30 22:58:33 +00005618 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
danielk1977e589a672009-04-11 16:06:15 +00005619 /* 0 is not a legal page number and page 1 cannot be an
5620 ** overflow page. Therefore if ovflPgno<2 or past the end of the
5621 ** file the database must be corrupt. */
drh49285702005-09-17 15:20:26 +00005622 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00005623 }
danielk1977bea2a942009-01-20 17:06:27 +00005624 if( nOvfl ){
5625 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
5626 if( rc ) return rc;
5627 }
dan887d4b22010-02-25 12:09:16 +00005628
shaneh1da207e2010-03-09 14:41:12 +00005629 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
dan887d4b22010-02-25 12:09:16 +00005630 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
5631 ){
5632 /* There is no reason any cursor should have an outstanding reference
5633 ** to an overflow page belonging to a cell that is being deleted/updated.
5634 ** So if there exists more than one reference to this page, then it
5635 ** must not really be an overflow page and the database must be corrupt.
5636 ** It is helpful to detect this before calling freePage2(), as
5637 ** freePage2() may zero the page contents if secure-delete mode is
5638 ** enabled. If this 'overflow' page happens to be a page that the
5639 ** caller is iterating through or using in some other way, this
5640 ** can be problematic.
5641 */
5642 rc = SQLITE_CORRUPT_BKPT;
5643 }else{
5644 rc = freePage2(pBt, pOvfl, ovflPgno);
5645 }
5646
danielk1977bea2a942009-01-20 17:06:27 +00005647 if( pOvfl ){
5648 sqlite3PagerUnref(pOvfl->pDbPage);
5649 }
drh3b7511c2001-05-26 13:15:44 +00005650 if( rc ) return rc;
danielk1977bea2a942009-01-20 17:06:27 +00005651 ovflPgno = iNext;
drh3b7511c2001-05-26 13:15:44 +00005652 }
drh5e2f8b92001-05-28 00:41:15 +00005653 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00005654}
5655
5656/*
drh91025292004-05-03 19:49:32 +00005657** Create the byte sequence used to represent a cell on page pPage
5658** and write that byte sequence into pCell[]. Overflow pages are
5659** allocated and filled in as necessary. The calling procedure
5660** is responsible for making sure sufficient space has been allocated
5661** for pCell[].
5662**
5663** Note that pCell does not necessary need to point to the pPage->aData
5664** area. pCell might point to some temporary storage. The cell will
5665** be constructed in this temporary area then copied into pPage->aData
5666** later.
drh3b7511c2001-05-26 13:15:44 +00005667*/
5668static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00005669 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00005670 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00005671 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00005672 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00005673 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00005674 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00005675){
drh3b7511c2001-05-26 13:15:44 +00005676 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00005677 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00005678 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00005679 int spaceLeft;
5680 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00005681 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00005682 unsigned char *pPrior;
5683 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00005684 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00005685 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00005686 int nHeader;
drh3b7511c2001-05-26 13:15:44 +00005687
drh1fee73e2007-08-29 04:00:57 +00005688 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00005689
drhc5053fb2008-11-27 02:22:10 +00005690 /* pPage is not necessarily writeable since pCell might be auxiliary
5691 ** buffer space that is separate from the pPage buffer area */
5692 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
5693 || sqlite3PagerIswriteable(pPage->pDbPage) );
5694
drh91025292004-05-03 19:49:32 +00005695 /* Fill in the header. */
drh6200c882014-09-23 22:36:25 +00005696 nHeader = pPage->childPtrSize;
5697 nPayload = nData + nZero;
drh3e28ff52014-09-24 00:59:08 +00005698 if( pPage->intKeyLeaf ){
drh6200c882014-09-23 22:36:25 +00005699 nHeader += putVarint32(&pCell[nHeader], nPayload);
drh6f11bef2004-05-13 01:12:56 +00005700 }else{
drh6200c882014-09-23 22:36:25 +00005701 assert( nData==0 );
5702 assert( nZero==0 );
drh91025292004-05-03 19:49:32 +00005703 }
drh6f11bef2004-05-13 01:12:56 +00005704 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh6f11bef2004-05-13 01:12:56 +00005705
drh6200c882014-09-23 22:36:25 +00005706 /* Fill in the payload size */
drh3aac2dd2004-04-26 14:10:20 +00005707 if( pPage->intKey ){
5708 pSrc = pData;
5709 nSrc = nData;
drh91025292004-05-03 19:49:32 +00005710 nData = 0;
drhf49661a2008-12-10 16:45:50 +00005711 }else{
danielk197731d31b82009-07-13 13:18:07 +00005712 if( NEVER(nKey>0x7fffffff || pKey==0) ){
5713 return SQLITE_CORRUPT_BKPT;
drh20abac22009-01-28 20:21:17 +00005714 }
drh6200c882014-09-23 22:36:25 +00005715 nPayload = (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00005716 pSrc = pKey;
drhf49661a2008-12-10 16:45:50 +00005717 nSrc = (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00005718 }
drh6200c882014-09-23 22:36:25 +00005719 if( nPayload<=pPage->maxLocal ){
5720 n = nHeader + nPayload;
5721 testcase( n==3 );
5722 testcase( n==4 );
5723 if( n<4 ) n = 4;
5724 *pnSize = n;
5725 spaceLeft = nPayload;
5726 pPrior = pCell;
5727 }else{
5728 int mn = pPage->minLocal;
5729 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
5730 testcase( n==pPage->maxLocal );
5731 testcase( n==pPage->maxLocal+1 );
5732 if( n > pPage->maxLocal ) n = mn;
5733 spaceLeft = n;
5734 *pnSize = n + nHeader + 4;
5735 pPrior = &pCell[nHeader+n];
5736 }
drh3aac2dd2004-04-26 14:10:20 +00005737 pPayload = &pCell[nHeader];
drh3b7511c2001-05-26 13:15:44 +00005738
drh6200c882014-09-23 22:36:25 +00005739 /* At this point variables should be set as follows:
5740 **
5741 ** nPayload Total payload size in bytes
5742 ** pPayload Begin writing payload here
5743 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
5744 ** that means content must spill into overflow pages.
5745 ** *pnSize Size of the local cell (not counting overflow pages)
5746 ** pPrior Where to write the pgno of the first overflow page
5747 **
5748 ** Use a call to btreeParseCellPtr() to verify that the values above
5749 ** were computed correctly.
5750 */
5751#if SQLITE_DEBUG
5752 {
5753 CellInfo info;
5754 btreeParseCellPtr(pPage, pCell, &info);
5755 assert( nHeader=(int)(info.pPayload - pCell) );
5756 assert( info.nKey==nKey );
5757 assert( *pnSize == info.nSize );
5758 assert( spaceLeft == info.nLocal );
5759 assert( pPrior == &pCell[info.iOverflow] );
5760 }
5761#endif
5762
5763 /* Write the payload into the local Cell and any extra into overflow pages */
drh3b7511c2001-05-26 13:15:44 +00005764 while( nPayload>0 ){
5765 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00005766#ifndef SQLITE_OMIT_AUTOVACUUM
5767 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00005768 if( pBt->autoVacuum ){
5769 do{
5770 pgnoOvfl++;
5771 } while(
5772 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
5773 );
danielk1977b39f70b2007-05-17 18:28:11 +00005774 }
danielk1977afcdd022004-10-31 16:25:42 +00005775#endif
drhf49661a2008-12-10 16:45:50 +00005776 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00005777#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00005778 /* If the database supports auto-vacuum, and the second or subsequent
5779 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00005780 ** for that page now.
5781 **
5782 ** If this is the first overflow page, then write a partial entry
5783 ** to the pointer-map. If we write nothing to this pointer-map slot,
5784 ** then the optimistic overflow chain processing in clearCell()
mistachkin48864df2013-03-21 21:20:32 +00005785 ** may misinterpret the uninitialized values and delete the
danielk19774ef24492007-05-23 09:52:41 +00005786 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00005787 */
danielk19774ef24492007-05-23 09:52:41 +00005788 if( pBt->autoVacuum && rc==SQLITE_OK ){
5789 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
drh98add2e2009-07-20 17:11:49 +00005790 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
danielk197789a4be82007-05-23 13:34:32 +00005791 if( rc ){
5792 releasePage(pOvfl);
5793 }
danielk1977afcdd022004-10-31 16:25:42 +00005794 }
5795#endif
drh3b7511c2001-05-26 13:15:44 +00005796 if( rc ){
drh9b171272004-05-08 02:03:22 +00005797 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00005798 return rc;
5799 }
drhc5053fb2008-11-27 02:22:10 +00005800
5801 /* If pToRelease is not zero than pPrior points into the data area
5802 ** of pToRelease. Make sure pToRelease is still writeable. */
5803 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
5804
5805 /* If pPrior is part of the data area of pPage, then make sure pPage
5806 ** is still writeable */
5807 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
5808 || sqlite3PagerIswriteable(pPage->pDbPage) );
5809
drh3aac2dd2004-04-26 14:10:20 +00005810 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00005811 releasePage(pToRelease);
5812 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00005813 pPrior = pOvfl->aData;
5814 put4byte(pPrior, 0);
5815 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00005816 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00005817 }
5818 n = nPayload;
5819 if( n>spaceLeft ) n = spaceLeft;
drhc5053fb2008-11-27 02:22:10 +00005820
5821 /* If pToRelease is not zero than pPayload points into the data area
5822 ** of pToRelease. Make sure pToRelease is still writeable. */
5823 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
5824
5825 /* If pPayload is part of the data area of pPage, then make sure pPage
5826 ** is still writeable */
5827 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
5828 || sqlite3PagerIswriteable(pPage->pDbPage) );
5829
drhb026e052007-05-02 01:34:31 +00005830 if( nSrc>0 ){
5831 if( n>nSrc ) n = nSrc;
5832 assert( pSrc );
5833 memcpy(pPayload, pSrc, n);
5834 }else{
5835 memset(pPayload, 0, n);
5836 }
drh3b7511c2001-05-26 13:15:44 +00005837 nPayload -= n;
drhde647132004-05-07 17:57:49 +00005838 pPayload += n;
drh9b171272004-05-08 02:03:22 +00005839 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00005840 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00005841 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00005842 if( nSrc==0 ){
5843 nSrc = nData;
5844 pSrc = pData;
5845 }
drhdd793422001-06-28 01:54:48 +00005846 }
drh9b171272004-05-08 02:03:22 +00005847 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00005848 return SQLITE_OK;
5849}
5850
drh14acc042001-06-10 19:56:58 +00005851/*
5852** Remove the i-th cell from pPage. This routine effects pPage only.
5853** The cell content is not freed or deallocated. It is assumed that
5854** the cell content has been copied someplace else. This routine just
5855** removes the reference to the cell from pPage.
5856**
5857** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00005858*/
drh98add2e2009-07-20 17:11:49 +00005859static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
drh43b18e12010-08-17 19:40:08 +00005860 u32 pc; /* Offset to cell content of cell being deleted */
drh43605152004-05-29 21:46:49 +00005861 u8 *data; /* pPage->aData */
5862 u8 *ptr; /* Used to move bytes around within data[] */
shanedcc50b72008-11-13 18:29:50 +00005863 int rc; /* The return code */
drhc314dc72009-07-21 11:52:34 +00005864 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
drh43605152004-05-29 21:46:49 +00005865
drh98add2e2009-07-20 17:11:49 +00005866 if( *pRC ) return;
5867
drh8c42ca92001-06-22 19:15:00 +00005868 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00005869 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00005870 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00005871 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00005872 data = pPage->aData;
drh3def2352011-11-11 00:27:15 +00005873 ptr = &pPage->aCellIdx[2*idx];
shane0af3f892008-11-12 04:55:34 +00005874 pc = get2byte(ptr);
drhc314dc72009-07-21 11:52:34 +00005875 hdr = pPage->hdrOffset;
5876 testcase( pc==get2byte(&data[hdr+5]) );
5877 testcase( pc+sz==pPage->pBt->usableSize );
drh43b18e12010-08-17 19:40:08 +00005878 if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
drh98add2e2009-07-20 17:11:49 +00005879 *pRC = SQLITE_CORRUPT_BKPT;
5880 return;
shane0af3f892008-11-12 04:55:34 +00005881 }
shanedcc50b72008-11-13 18:29:50 +00005882 rc = freeSpace(pPage, pc, sz);
drh98add2e2009-07-20 17:11:49 +00005883 if( rc ){
5884 *pRC = rc;
5885 return;
shanedcc50b72008-11-13 18:29:50 +00005886 }
drh14acc042001-06-10 19:56:58 +00005887 pPage->nCell--;
drh9bb7c4f2013-12-09 01:58:11 +00005888 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
drhc314dc72009-07-21 11:52:34 +00005889 put2byte(&data[hdr+3], pPage->nCell);
drh43605152004-05-29 21:46:49 +00005890 pPage->nFree += 2;
drh14acc042001-06-10 19:56:58 +00005891}
5892
5893/*
5894** Insert a new cell on pPage at cell index "i". pCell points to the
5895** content of the cell.
5896**
5897** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00005898** will not fit, then make a copy of the cell content into pTemp if
5899** pTemp is not null. Regardless of pTemp, allocate a new entry
drh2cbd78b2012-02-02 19:37:18 +00005900** in pPage->apOvfl[] and make it point to the cell content (either
drh43605152004-05-29 21:46:49 +00005901** in pTemp or the original pCell) and also record its index.
5902** Allocating a new entry in pPage->aCell[] implies that
5903** pPage->nOverflow is incremented.
drh14acc042001-06-10 19:56:58 +00005904*/
drh98add2e2009-07-20 17:11:49 +00005905static void insertCell(
drh24cd67e2004-05-10 16:18:47 +00005906 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00005907 int i, /* New cell becomes the i-th cell of the page */
5908 u8 *pCell, /* Content of the new cell */
5909 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00005910 u8 *pTemp, /* Temp storage space for pCell, if needed */
drh98add2e2009-07-20 17:11:49 +00005911 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
5912 int *pRC /* Read and write return code from here */
drh24cd67e2004-05-10 16:18:47 +00005913){
drh383d30f2010-02-26 13:07:37 +00005914 int idx = 0; /* Where to write new cell content in data[] */
drh43605152004-05-29 21:46:49 +00005915 int j; /* Loop counter */
drh43605152004-05-29 21:46:49 +00005916 int end; /* First byte past the last cell pointer in data[] */
5917 int ins; /* Index in data[] where new cell pointer is inserted */
drh43605152004-05-29 21:46:49 +00005918 int cellOffset; /* Address of first cell pointer in data[] */
5919 u8 *data; /* The content of the whole page */
danielk19774dbaa892009-06-16 16:50:22 +00005920
drh98add2e2009-07-20 17:11:49 +00005921 if( *pRC ) return;
5922
drh43605152004-05-29 21:46:49 +00005923 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
danf216e322014-08-14 19:53:37 +00005924 assert( MX_CELL(pPage->pBt)<=10921 );
5925 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
drh2cbd78b2012-02-02 19:37:18 +00005926 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
5927 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
drh1fee73e2007-08-29 04:00:57 +00005928 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc9b9b8a2009-12-03 21:26:52 +00005929 /* The cell should normally be sized correctly. However, when moving a
5930 ** malformed cell from a leaf page to an interior page, if the cell size
5931 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
5932 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
5933 ** the term after the || in the following assert(). */
5934 assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
drh43605152004-05-29 21:46:49 +00005935 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00005936 if( pTemp ){
drhd6176c42014-10-11 17:22:55 +00005937 memcpy(pTemp, pCell, sz);
drh43605152004-05-29 21:46:49 +00005938 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00005939 }
danielk19774dbaa892009-06-16 16:50:22 +00005940 if( iChild ){
5941 put4byte(pCell, iChild);
5942 }
drh43605152004-05-29 21:46:49 +00005943 j = pPage->nOverflow++;
drh2cbd78b2012-02-02 19:37:18 +00005944 assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
5945 pPage->apOvfl[j] = pCell;
5946 pPage->aiOvfl[j] = (u16)i;
drh14acc042001-06-10 19:56:58 +00005947 }else{
danielk19776e465eb2007-08-21 13:11:00 +00005948 int rc = sqlite3PagerWrite(pPage->pDbPage);
5949 if( rc!=SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00005950 *pRC = rc;
5951 return;
danielk19776e465eb2007-08-21 13:11:00 +00005952 }
5953 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00005954 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00005955 cellOffset = pPage->cellOffset;
drh0a45c272009-07-08 01:49:11 +00005956 end = cellOffset + 2*pPage->nCell;
drh43605152004-05-29 21:46:49 +00005957 ins = cellOffset + 2*i;
drh0a45c272009-07-08 01:49:11 +00005958 rc = allocateSpace(pPage, sz, &idx);
drh98add2e2009-07-20 17:11:49 +00005959 if( rc ){ *pRC = rc; return; }
drhc314dc72009-07-21 11:52:34 +00005960 /* The allocateSpace() routine guarantees the following two properties
5961 ** if it returns success */
5962 assert( idx >= end+2 );
drhfcd71b62011-04-05 22:08:24 +00005963 assert( idx+sz <= (int)pPage->pBt->usableSize );
drh43605152004-05-29 21:46:49 +00005964 pPage->nCell++;
drh0a45c272009-07-08 01:49:11 +00005965 pPage->nFree -= (u16)(2 + sz);
drhd6176c42014-10-11 17:22:55 +00005966 memcpy(&data[idx], pCell, sz);
danielk19774dbaa892009-06-16 16:50:22 +00005967 if( iChild ){
5968 put4byte(&data[idx], iChild);
5969 }
drh8f518832013-12-09 02:32:19 +00005970 memmove(&data[ins+2], &data[ins], end-ins);
drh43605152004-05-29 21:46:49 +00005971 put2byte(&data[ins], idx);
drh0a45c272009-07-08 01:49:11 +00005972 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
danielk1977a19df672004-11-03 11:37:07 +00005973#ifndef SQLITE_OMIT_AUTOVACUUM
5974 if( pPage->pBt->autoVacuum ){
5975 /* The cell may contain a pointer to an overflow page. If so, write
5976 ** the entry for the overflow page into the pointer map.
5977 */
drh98add2e2009-07-20 17:11:49 +00005978 ptrmapPutOvflPtr(pPage, pCell, pRC);
danielk1977a19df672004-11-03 11:37:07 +00005979 }
5980#endif
drh14acc042001-06-10 19:56:58 +00005981 }
5982}
5983
5984/*
dan8e9ba0c2014-10-14 17:27:04 +00005985** Array apCell[] contains pointers to nCell b-tree page cells. The
5986** szCell[] array contains the size in bytes of each cell. This function
5987** replaces the current contents of page pPg with the contents of the cell
5988** array.
5989**
5990** Some of the cells in apCell[] may currently be stored in pPg. This
5991** function works around problems caused by this by making a copy of any
5992** such cells before overwriting the page data.
5993**
5994** The MemPage.nFree field is invalidated by this function. It is the
5995** responsibility of the caller to set it correctly.
drhfa1a98a2004-05-14 19:08:17 +00005996*/
dan33ea4862014-10-09 19:35:37 +00005997static void rebuildPage(
5998 MemPage *pPg, /* Edit this page */
dan33ea4862014-10-09 19:35:37 +00005999 int nCell, /* Final number of cells on page */
dan09c68402014-10-11 20:00:24 +00006000 u8 **apCell, /* Array of cells */
6001 u16 *szCell /* Array of cell sizes */
dan33ea4862014-10-09 19:35:37 +00006002){
6003 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
6004 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
6005 const int usableSize = pPg->pBt->usableSize;
6006 u8 * const pEnd = &aData[usableSize];
6007 int i;
6008 u8 *pCellptr = pPg->aCellIdx;
6009 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6010 u8 *pData;
6011
6012 i = get2byte(&aData[hdr+5]);
6013 memcpy(&pTmp[i], &aData[i], usableSize - i);
dan33ea4862014-10-09 19:35:37 +00006014
dan8e9ba0c2014-10-14 17:27:04 +00006015 pData = pEnd;
dan33ea4862014-10-09 19:35:37 +00006016 for(i=0; i<nCell; i++){
6017 u8 *pCell = apCell[i];
6018 if( pCell>aData && pCell<pEnd ){
6019 pCell = &pTmp[pCell - aData];
6020 }
6021 pData -= szCell[i];
6022 memcpy(pData, pCell, szCell[i]);
6023 put2byte(pCellptr, (pData - aData));
6024 pCellptr += 2;
6025 assert( szCell[i]==cellSizePtr(pPg, pCell) );
6026 }
6027
dand7b545b2014-10-13 18:03:27 +00006028 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
dan33ea4862014-10-09 19:35:37 +00006029 pPg->nCell = nCell;
6030 pPg->nOverflow = 0;
6031
6032 put2byte(&aData[hdr+1], 0);
6033 put2byte(&aData[hdr+3], pPg->nCell);
6034 put2byte(&aData[hdr+5], pData - aData);
6035 aData[hdr+7] = 0x00;
6036}
6037
dan8e9ba0c2014-10-14 17:27:04 +00006038/*
6039** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
6040** contains the size in bytes of each such cell. This function attempts to
6041** add the cells stored in the array to page pPg. If it cannot (because
6042** the page needs to be defragmented before the cells will fit), non-zero
6043** is returned. Otherwise, if the cells are added successfully, zero is
6044** returned.
6045**
6046** Argument pCellptr points to the first entry in the cell-pointer array
6047** (part of page pPg) to populate. After cell apCell[0] is written to the
6048** page body, a 16-bit offset is written to pCellptr. And so on, for each
6049** cell in the array. It is the responsibility of the caller to ensure
6050** that it is safe to overwrite this part of the cell-pointer array.
6051**
6052** When this function is called, *ppData points to the start of the
6053** content area on page pPg. If the size of the content area is extended,
6054** *ppData is updated to point to the new start of the content area
6055** before returning.
6056**
6057** Finally, argument pBegin points to the byte immediately following the
6058** end of the space required by this page for the cell-pointer area (for
6059** all cells - not just those inserted by the current call). If the content
6060** area must be extended to before this point in order to accomodate all
6061** cells in apCell[], then the cells do not fit and non-zero is returned.
6062*/
dand7b545b2014-10-13 18:03:27 +00006063static int pageInsertArray(
dan8e9ba0c2014-10-14 17:27:04 +00006064 MemPage *pPg, /* Page to add cells to */
6065 u8 *pBegin, /* End of cell-pointer array */
6066 u8 **ppData, /* IN/OUT: Page content -area pointer */
6067 u8 *pCellptr, /* Pointer to cell-pointer area */
6068 int nCell, /* Number of cells to add to pPg */
dand7b545b2014-10-13 18:03:27 +00006069 u8 **apCell, /* Array of cells */
6070 u16 *szCell /* Array of cell sizes */
6071){
6072 int i;
6073 u8 *aData = pPg->aData;
6074 u8 *pData = *ppData;
dan8e9ba0c2014-10-14 17:27:04 +00006075 const int bFreelist = aData[1] || aData[2];
dan23eba452014-10-24 18:43:57 +00006076 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
dand7b545b2014-10-13 18:03:27 +00006077 for(i=0; i<nCell; i++){
6078 int sz = szCell[i];
6079 u8 *pSlot;
dan61e94c92014-10-27 08:02:16 +00006080 if( bFreelist==0 || (pSlot = pageFindSlot(pPg, sz, 0, 0))==0 ){
dand7b545b2014-10-13 18:03:27 +00006081 pData -= sz;
6082 if( pData<pBegin ) return 1;
6083 pSlot = pData;
6084 }
6085 memcpy(pSlot, apCell[i], sz);
6086 put2byte(pCellptr, (pSlot - aData));
6087 pCellptr += 2;
6088 }
6089 *ppData = pData;
6090 return 0;
6091}
6092
dan8e9ba0c2014-10-14 17:27:04 +00006093/*
6094** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
6095** contains the size in bytes of each such cell. This function adds the
6096** space associated with each cell in the array that is currently stored
6097** within the body of pPg to the pPg free-list. The cell-pointers and other
6098** fields of the page are not updated.
6099**
6100** This function returns the total number of cells added to the free-list.
6101*/
dand7b545b2014-10-13 18:03:27 +00006102static int pageFreeArray(
6103 MemPage *pPg, /* Page to edit */
6104 int nCell, /* Cells to delete */
6105 u8 **apCell, /* Array of cells */
6106 u16 *szCell /* Array of cell sizes */
6107){
6108 u8 * const aData = pPg->aData;
6109 u8 * const pEnd = &aData[pPg->pBt->usableSize];
dan89ca0b32014-10-25 20:36:28 +00006110 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
dand7b545b2014-10-13 18:03:27 +00006111 int nRet = 0;
6112 int i;
6113 u8 *pFree = 0;
6114 int szFree = 0;
6115
6116 for(i=0; i<nCell; i++){
6117 u8 *pCell = apCell[i];
dan89ca0b32014-10-25 20:36:28 +00006118 if( pCell>=pStart && pCell<pEnd ){
dand7b545b2014-10-13 18:03:27 +00006119 int sz = szCell[i];
6120 if( pFree!=(pCell + sz) ){
6121 if( pFree ) freeSpace(pPg, pFree - aData, szFree);
6122 pFree = pCell;
6123 szFree = sz;
dan89ca0b32014-10-25 20:36:28 +00006124 if( pFree+sz>pEnd ) return 0;
dand7b545b2014-10-13 18:03:27 +00006125 }else{
6126 pFree = pCell;
6127 szFree += sz;
6128 }
6129 nRet++;
6130 }
6131 }
6132 if( pFree ) freeSpace(pPg, pFree - aData, szFree);
6133 return nRet;
6134}
6135
dand7b545b2014-10-13 18:03:27 +00006136/*
6137** The pPg->nFree field is invalid when this function returns. It is the
6138** responsibility of the caller to set it correctly.
6139*/
dan09c68402014-10-11 20:00:24 +00006140static void editPage(
6141 MemPage *pPg, /* Edit this page */
6142 int iOld, /* Index of first cell currently on page */
6143 int iNew, /* Index of new first cell on page */
6144 int nNew, /* Final number of cells on page */
6145 u8 **apCell, /* Array of cells */
6146 u16 *szCell /* Array of cell sizes */
6147){
dand7b545b2014-10-13 18:03:27 +00006148 u8 * const aData = pPg->aData;
6149 const int hdr = pPg->hdrOffset;
6150 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
6151 int nCell = pPg->nCell; /* Cells stored on pPg */
6152 u8 *pData;
6153 u8 *pCellptr;
6154 int i;
6155 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
6156 int iNewEnd = iNew + nNew;
dan09c68402014-10-11 20:00:24 +00006157
6158#ifdef SQLITE_DEBUG
dand7b545b2014-10-13 18:03:27 +00006159 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6160 memcpy(pTmp, aData, pPg->pBt->usableSize);
dan09c68402014-10-11 20:00:24 +00006161#endif
6162
dand7b545b2014-10-13 18:03:27 +00006163 /* Remove cells from the start and end of the page */
6164 if( iOld<iNew ){
6165 int nShift = pageFreeArray(
6166 pPg, iNew-iOld, &apCell[iOld], &szCell[iOld]
6167 );
6168 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
6169 nCell -= nShift;
6170 }
6171 if( iNewEnd < iOldEnd ){
6172 nCell -= pageFreeArray(
6173 pPg, iOldEnd-iNewEnd, &apCell[iNewEnd], &szCell[iNewEnd]
6174 );
6175 }
dan09c68402014-10-11 20:00:24 +00006176
dand7b545b2014-10-13 18:03:27 +00006177 pData = &aData[get2byte(&aData[hdr+5])];
6178 if( pData<pBegin ) goto editpage_fail;
6179
6180 /* Add cells to the start of the page */
6181 if( iNew<iOld ){
6182 int nAdd = iOld-iNew;
6183 pCellptr = pPg->aCellIdx;
6184 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
6185 if( pageInsertArray(
6186 pPg, pBegin, &pData, pCellptr,
6187 nAdd, &apCell[iNew], &szCell[iNew]
6188 ) ) goto editpage_fail;
6189 nCell += nAdd;
6190 }
6191
6192 /* Add any overflow cells */
6193 for(i=0; i<pPg->nOverflow; i++){
6194 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
6195 if( iCell>=0 && iCell<nNew ){
6196 u8 *pCellptr = &pPg->aCellIdx[iCell * 2];
6197 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
6198 nCell++;
6199 if( pageInsertArray(
6200 pPg, pBegin, &pData, pCellptr,
6201 1, &apCell[iCell + iNew], &szCell[iCell + iNew]
6202 ) ) goto editpage_fail;
dan09c68402014-10-11 20:00:24 +00006203 }
dand7b545b2014-10-13 18:03:27 +00006204 }
dan09c68402014-10-11 20:00:24 +00006205
dand7b545b2014-10-13 18:03:27 +00006206 /* Append cells to the end of the page */
6207 pCellptr = &pPg->aCellIdx[nCell*2];
6208 if( pageInsertArray(
6209 pPg, pBegin, &pData, pCellptr,
6210 nNew-nCell, &apCell[iNew+nCell], &szCell[iNew+nCell]
6211 ) ) goto editpage_fail;
dan09c68402014-10-11 20:00:24 +00006212
dand7b545b2014-10-13 18:03:27 +00006213 pPg->nCell = nNew;
6214 pPg->nOverflow = 0;
dan09c68402014-10-11 20:00:24 +00006215
dand7b545b2014-10-13 18:03:27 +00006216 put2byte(&aData[hdr+3], pPg->nCell);
6217 put2byte(&aData[hdr+5], pData - aData);
dan09c68402014-10-11 20:00:24 +00006218
6219#ifdef SQLITE_DEBUG
dan23eba452014-10-24 18:43:57 +00006220 for(i=0; i<nNew && !CORRUPT_DB; i++){
dand7b545b2014-10-13 18:03:27 +00006221 u8 *pCell = apCell[i+iNew];
6222 int iOff = get2byte(&pPg->aCellIdx[i*2]);
6223 if( pCell>=aData && pCell<&aData[pPg->pBt->usableSize] ){
6224 pCell = &pTmp[pCell - aData];
dan09c68402014-10-11 20:00:24 +00006225 }
dand7b545b2014-10-13 18:03:27 +00006226 assert( 0==memcmp(pCell, &aData[iOff], szCell[i+iNew]) );
6227 }
dan09c68402014-10-11 20:00:24 +00006228#endif
6229
dand7b545b2014-10-13 18:03:27 +00006230 return;
dan09c68402014-10-11 20:00:24 +00006231 editpage_fail:
dan09c68402014-10-11 20:00:24 +00006232 /* Unable to edit this page. Rebuild it from scratch instead. */
6233 rebuildPage(pPg, nNew, &apCell[iNew], &szCell[iNew]);
6234}
6235
drh14acc042001-06-10 19:56:58 +00006236/*
drhc3b70572003-01-04 19:44:07 +00006237** The following parameters determine how many adjacent pages get involved
6238** in a balancing operation. NN is the number of neighbors on either side
6239** of the page that participate in the balancing operation. NB is the
6240** total number of pages that participate, including the target page and
6241** NN neighbors on either side.
6242**
6243** The minimum value of NN is 1 (of course). Increasing NN above 1
6244** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
6245** in exchange for a larger degradation in INSERT and UPDATE performance.
6246** The value of NN appears to give the best results overall.
6247*/
6248#define NN 1 /* Number of neighbors on either side of pPage */
6249#define NB (NN*2+1) /* Total pages involved in the balance */
6250
danielk1977ac245ec2005-01-14 13:50:11 +00006251
drh615ae552005-01-16 23:21:00 +00006252#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00006253/*
6254** This version of balance() handles the common special case where
6255** a new entry is being inserted on the extreme right-end of the
6256** tree, in other words, when the new entry will become the largest
6257** entry in the tree.
6258**
drhc314dc72009-07-21 11:52:34 +00006259** Instead of trying to balance the 3 right-most leaf pages, just add
drhf222e712005-01-14 22:55:49 +00006260** a new page to the right-hand side and put the one new entry in
6261** that page. This leaves the right side of the tree somewhat
6262** unbalanced. But odds are that we will be inserting new entries
6263** at the end soon afterwards so the nearly empty page will quickly
6264** fill up. On average.
6265**
6266** pPage is the leaf page which is the right-most page in the tree.
6267** pParent is its parent. pPage must have a single overflow entry
6268** which is also the right-most entry on the page.
danielk1977a50d9aa2009-06-08 14:49:45 +00006269**
6270** The pSpace buffer is used to store a temporary copy of the divider
6271** cell that will be inserted into pParent. Such a cell consists of a 4
6272** byte page number followed by a variable length integer. In other
6273** words, at most 13 bytes. Hence the pSpace buffer must be at
6274** least 13 bytes in size.
drhf222e712005-01-14 22:55:49 +00006275*/
danielk1977a50d9aa2009-06-08 14:49:45 +00006276static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
6277 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
danielk19774dbaa892009-06-16 16:50:22 +00006278 MemPage *pNew; /* Newly allocated page */
danielk19776f235cc2009-06-04 14:46:08 +00006279 int rc; /* Return Code */
6280 Pgno pgnoNew; /* Page number of pNew */
danielk1977ac245ec2005-01-14 13:50:11 +00006281
drh1fee73e2007-08-29 04:00:57 +00006282 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk1977a50d9aa2009-06-08 14:49:45 +00006283 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00006284 assert( pPage->nOverflow==1 );
6285
drh5d433ce2010-08-14 16:02:52 +00006286 /* This error condition is now caught prior to reaching this function */
mistachkin5f070c72012-10-18 10:35:19 +00006287 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
drhd677b3d2007-08-20 22:48:41 +00006288
danielk1977a50d9aa2009-06-08 14:49:45 +00006289 /* Allocate a new page. This page will become the right-sibling of
6290 ** pPage. Make the parent page writable, so that the new divider cell
6291 ** may be inserted. If both these operations are successful, proceed.
6292 */
drh4f0c5872007-03-26 22:05:01 +00006293 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk19774dbaa892009-06-16 16:50:22 +00006294
danielk1977eaa06f62008-09-18 17:34:44 +00006295 if( rc==SQLITE_OK ){
danielk1977a50d9aa2009-06-08 14:49:45 +00006296
6297 u8 *pOut = &pSpace[4];
drh2cbd78b2012-02-02 19:37:18 +00006298 u8 *pCell = pPage->apOvfl[0];
danielk19776f235cc2009-06-04 14:46:08 +00006299 u16 szCell = cellSizePtr(pPage, pCell);
6300 u8 *pStop;
6301
drhc5053fb2008-11-27 02:22:10 +00006302 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00006303 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
6304 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
dan8e9ba0c2014-10-14 17:27:04 +00006305 rebuildPage(pNew, 1, &pCell, &szCell);
6306 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
danielk19774dbaa892009-06-16 16:50:22 +00006307
6308 /* If this is an auto-vacuum database, update the pointer map
6309 ** with entries for the new page, and any pointer from the
6310 ** cell on the page to an overflow page. If either of these
6311 ** operations fails, the return code is set, but the contents
6312 ** of the parent page are still manipulated by thh code below.
6313 ** That is Ok, at this point the parent page is guaranteed to
6314 ** be marked as dirty. Returning an error code will cause a
6315 ** rollback, undoing any changes made to the parent page.
6316 */
6317 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00006318 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
6319 if( szCell>pNew->minLocal ){
6320 ptrmapPutOvflPtr(pNew, pCell, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006321 }
6322 }
danielk1977eaa06f62008-09-18 17:34:44 +00006323
danielk19776f235cc2009-06-04 14:46:08 +00006324 /* Create a divider cell to insert into pParent. The divider cell
6325 ** consists of a 4-byte page number (the page number of pPage) and
6326 ** a variable length key value (which must be the same value as the
6327 ** largest key on pPage).
danielk1977eaa06f62008-09-18 17:34:44 +00006328 **
danielk19776f235cc2009-06-04 14:46:08 +00006329 ** To find the largest key value on pPage, first find the right-most
6330 ** cell on pPage. The first two fields of this cell are the
6331 ** record-length (a variable length integer at most 32-bits in size)
6332 ** and the key value (a variable length integer, may have any value).
6333 ** The first of the while(...) loops below skips over the record-length
6334 ** field. The second while(...) loop copies the key value from the
danielk1977a50d9aa2009-06-08 14:49:45 +00006335 ** cell on pPage into the pSpace buffer.
danielk1977eaa06f62008-09-18 17:34:44 +00006336 */
danielk1977eaa06f62008-09-18 17:34:44 +00006337 pCell = findCell(pPage, pPage->nCell-1);
danielk19776f235cc2009-06-04 14:46:08 +00006338 pStop = &pCell[9];
6339 while( (*(pCell++)&0x80) && pCell<pStop );
6340 pStop = &pCell[9];
6341 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
6342
danielk19774dbaa892009-06-16 16:50:22 +00006343 /* Insert the new divider cell into pParent. */
drh98add2e2009-07-20 17:11:49 +00006344 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
6345 0, pPage->pgno, &rc);
danielk19776f235cc2009-06-04 14:46:08 +00006346
6347 /* Set the right-child pointer of pParent to point to the new page. */
danielk1977eaa06f62008-09-18 17:34:44 +00006348 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
6349
danielk1977e08a3c42008-09-18 18:17:03 +00006350 /* Release the reference to the new page. */
6351 releasePage(pNew);
danielk1977ac11ee62005-01-15 12:45:51 +00006352 }
6353
danielk1977eaa06f62008-09-18 17:34:44 +00006354 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00006355}
drh615ae552005-01-16 23:21:00 +00006356#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00006357
dane6593d82014-10-24 16:40:49 +00006358#if 0
drhc3b70572003-01-04 19:44:07 +00006359/*
danielk19774dbaa892009-06-16 16:50:22 +00006360** This function does not contribute anything to the operation of SQLite.
6361** it is sometimes activated temporarily while debugging code responsible
6362** for setting pointer-map entries.
6363*/
6364static int ptrmapCheckPages(MemPage **apPage, int nPage){
6365 int i, j;
6366 for(i=0; i<nPage; i++){
6367 Pgno n;
6368 u8 e;
6369 MemPage *pPage = apPage[i];
6370 BtShared *pBt = pPage->pBt;
6371 assert( pPage->isInit );
6372
6373 for(j=0; j<pPage->nCell; j++){
6374 CellInfo info;
6375 u8 *z;
6376
6377 z = findCell(pPage, j);
danielk197730548662009-07-09 05:07:37 +00006378 btreeParseCellPtr(pPage, z, &info);
danielk19774dbaa892009-06-16 16:50:22 +00006379 if( info.iOverflow ){
6380 Pgno ovfl = get4byte(&z[info.iOverflow]);
6381 ptrmapGet(pBt, ovfl, &e, &n);
6382 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
6383 }
6384 if( !pPage->leaf ){
6385 Pgno child = get4byte(z);
6386 ptrmapGet(pBt, child, &e, &n);
6387 assert( n==pPage->pgno && e==PTRMAP_BTREE );
6388 }
6389 }
6390 if( !pPage->leaf ){
6391 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
6392 ptrmapGet(pBt, child, &e, &n);
6393 assert( n==pPage->pgno && e==PTRMAP_BTREE );
6394 }
6395 }
6396 return 1;
6397}
6398#endif
6399
danielk1977cd581a72009-06-23 15:43:39 +00006400/*
6401** This function is used to copy the contents of the b-tree node stored
6402** on page pFrom to page pTo. If page pFrom was not a leaf page, then
6403** the pointer-map entries for each child page are updated so that the
6404** parent page stored in the pointer map is page pTo. If pFrom contained
6405** any cells with overflow page pointers, then the corresponding pointer
6406** map entries are also updated so that the parent page is page pTo.
6407**
6408** If pFrom is currently carrying any overflow cells (entries in the
drh2cbd78b2012-02-02 19:37:18 +00006409** MemPage.apOvfl[] array), they are not copied to pTo.
danielk1977cd581a72009-06-23 15:43:39 +00006410**
danielk197730548662009-07-09 05:07:37 +00006411** Before returning, page pTo is reinitialized using btreeInitPage().
danielk1977cd581a72009-06-23 15:43:39 +00006412**
6413** The performance of this function is not critical. It is only used by
6414** the balance_shallower() and balance_deeper() procedures, neither of
6415** which are called often under normal circumstances.
6416*/
drhc314dc72009-07-21 11:52:34 +00006417static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
6418 if( (*pRC)==SQLITE_OK ){
6419 BtShared * const pBt = pFrom->pBt;
6420 u8 * const aFrom = pFrom->aData;
6421 u8 * const aTo = pTo->aData;
6422 int const iFromHdr = pFrom->hdrOffset;
6423 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
drhdc9b5f82009-12-05 18:34:08 +00006424 int rc;
drhc314dc72009-07-21 11:52:34 +00006425 int iData;
6426
6427
6428 assert( pFrom->isInit );
6429 assert( pFrom->nFree>=iToHdr );
drhfcd71b62011-04-05 22:08:24 +00006430 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
drhc314dc72009-07-21 11:52:34 +00006431
6432 /* Copy the b-tree node content from page pFrom to page pTo. */
6433 iData = get2byte(&aFrom[iFromHdr+5]);
6434 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
6435 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
6436
6437 /* Reinitialize page pTo so that the contents of the MemPage structure
dan89e060e2009-12-05 18:03:50 +00006438 ** match the new data. The initialization of pTo can actually fail under
6439 ** fairly obscure circumstances, even though it is a copy of initialized
6440 ** page pFrom.
6441 */
drhc314dc72009-07-21 11:52:34 +00006442 pTo->isInit = 0;
dan89e060e2009-12-05 18:03:50 +00006443 rc = btreeInitPage(pTo);
6444 if( rc!=SQLITE_OK ){
6445 *pRC = rc;
6446 return;
6447 }
drhc314dc72009-07-21 11:52:34 +00006448
6449 /* If this is an auto-vacuum database, update the pointer-map entries
6450 ** for any b-tree or overflow pages that pTo now contains the pointers to.
6451 */
6452 if( ISAUTOVACUUM ){
6453 *pRC = setChildPtrmaps(pTo);
6454 }
danielk1977cd581a72009-06-23 15:43:39 +00006455 }
danielk1977cd581a72009-06-23 15:43:39 +00006456}
6457
6458/*
danielk19774dbaa892009-06-16 16:50:22 +00006459** This routine redistributes cells on the iParentIdx'th child of pParent
6460** (hereafter "the page") and up to 2 siblings so that all pages have about the
6461** same amount of free space. Usually a single sibling on either side of the
6462** page are used in the balancing, though both siblings might come from one
6463** side if the page is the first or last child of its parent. If the page
6464** has fewer than 2 siblings (something which can only happen if the page
6465** is a root page or a child of a root page) then all available siblings
6466** participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00006467**
danielk19774dbaa892009-06-16 16:50:22 +00006468** The number of siblings of the page might be increased or decreased by
6469** one or two in an effort to keep pages nearly full but not over full.
drh14acc042001-06-10 19:56:58 +00006470**
danielk19774dbaa892009-06-16 16:50:22 +00006471** Note that when this routine is called, some of the cells on the page
6472** might not actually be stored in MemPage.aData[]. This can happen
6473** if the page is overfull. This routine ensures that all cells allocated
6474** to the page and its siblings fit into MemPage.aData[] before returning.
drh14acc042001-06-10 19:56:58 +00006475**
danielk19774dbaa892009-06-16 16:50:22 +00006476** In the course of balancing the page and its siblings, cells may be
6477** inserted into or removed from the parent page (pParent). Doing so
6478** may cause the parent page to become overfull or underfull. If this
6479** happens, it is the responsibility of the caller to invoke the correct
6480** balancing routine to fix this problem (see the balance() routine).
drh8c42ca92001-06-22 19:15:00 +00006481**
drh5e00f6c2001-09-13 13:46:56 +00006482** If this routine fails for any reason, it might leave the database
danielk19776067a9b2009-06-09 09:41:00 +00006483** in a corrupted state. So if this routine fails, the database should
drh5e00f6c2001-09-13 13:46:56 +00006484** be rolled back.
danielk19774dbaa892009-06-16 16:50:22 +00006485**
6486** The third argument to this function, aOvflSpace, is a pointer to a
drhcd09c532009-07-20 19:30:00 +00006487** buffer big enough to hold one page. If while inserting cells into the parent
6488** page (pParent) the parent page becomes overfull, this buffer is
6489** used to store the parent's overflow cells. Because this function inserts
danielk19774dbaa892009-06-16 16:50:22 +00006490** a maximum of four divider cells into the parent page, and the maximum
6491** size of a cell stored within an internal node is always less than 1/4
6492** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
6493** enough for all overflow cells.
6494**
6495** If aOvflSpace is set to a null pointer, this function returns
6496** SQLITE_NOMEM.
drh8b2f49b2001-06-08 00:21:52 +00006497*/
mistachkine7c54162012-10-02 22:54:27 +00006498#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
6499#pragma optimize("", off)
6500#endif
danielk19774dbaa892009-06-16 16:50:22 +00006501static int balance_nonroot(
6502 MemPage *pParent, /* Parent page of siblings being balanced */
6503 int iParentIdx, /* Index of "the page" in pParent */
danielk1977cd581a72009-06-23 15:43:39 +00006504 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
dan428c2182012-08-06 18:50:11 +00006505 int isRoot, /* True if pParent is a root-page */
6506 int bBulk /* True if this call is part of a bulk load */
danielk19774dbaa892009-06-16 16:50:22 +00006507){
drh16a9b832007-05-05 18:39:25 +00006508 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00006509 int nCell = 0; /* Number of cells in apCell[] */
6510 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
danielk1977a4124bd2008-12-23 10:37:47 +00006511 int nNew = 0; /* Number of pages in apNew[] */
danielk19774dbaa892009-06-16 16:50:22 +00006512 int nOld; /* Number of pages in apOld[] */
drh14acc042001-06-10 19:56:58 +00006513 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00006514 int nxDiv; /* Next divider slot in pParent->aCell[] */
shane85095702009-06-15 16:27:08 +00006515 int rc = SQLITE_OK; /* The return code */
shane36840fd2009-06-26 16:32:13 +00006516 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00006517 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00006518 int usableSpace; /* Bytes in pPage beyond the header */
6519 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00006520 int subtotal; /* Subtotal of bytes in cells on one page */
drhe5ae5732008-06-15 02:51:47 +00006521 int iSpace1 = 0; /* First unused byte of aSpace1[] */
danielk19776067a9b2009-06-09 09:41:00 +00006522 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
drhfacf0302008-06-17 15:12:00 +00006523 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00006524 MemPage *apOld[NB]; /* pPage and up to two siblings */
drha2fce642004-06-05 00:01:44 +00006525 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
danielk19774dbaa892009-06-16 16:50:22 +00006526 u8 *pRight; /* Location in parent of right-sibling pointer */
6527 u8 *apDiv[NB-1]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00006528 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
dan09c68402014-10-11 20:00:24 +00006529 int cntOld[NB+2]; /* Old index in aCell[] after i-th page */
drha2fce642004-06-05 00:01:44 +00006530 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00006531 u8 **apCell = 0; /* All cells begin balanced */
drha9121e42008-02-19 14:59:35 +00006532 u16 *szCell; /* Local size of all cells in apCell[] */
danielk19774dbaa892009-06-16 16:50:22 +00006533 u8 *aSpace1; /* Space for copies of dividers cells */
6534 Pgno pgno; /* Temp var to store a page number in */
dane6593d82014-10-24 16:40:49 +00006535 u8 abDone[NB+2]; /* True after i'th new page is populated */
6536 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
6537 u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
dan33ea4862014-10-09 19:35:37 +00006538
6539 memset(abDone, 0, sizeof(abDone));
danielk1977a50d9aa2009-06-08 14:49:45 +00006540 pBt = pParent->pBt;
6541 assert( sqlite3_mutex_held(pBt->mutex) );
6542 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977474b7cc2008-07-09 11:49:46 +00006543
danielk1977e5765212009-06-17 11:13:28 +00006544#if 0
drh43605152004-05-29 21:46:49 +00006545 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
danielk1977e5765212009-06-17 11:13:28 +00006546#endif
drh2e38c322004-09-03 18:38:44 +00006547
danielk19774dbaa892009-06-16 16:50:22 +00006548 /* At this point pParent may have at most one overflow cell. And if
6549 ** this overflow cell is present, it must be the cell with
6550 ** index iParentIdx. This scenario comes about when this function
drhcd09c532009-07-20 19:30:00 +00006551 ** is called (indirectly) from sqlite3BtreeDelete().
6552 */
danielk19774dbaa892009-06-16 16:50:22 +00006553 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
drh2cbd78b2012-02-02 19:37:18 +00006554 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
danielk19774dbaa892009-06-16 16:50:22 +00006555
danielk197711a8a862009-06-17 11:49:52 +00006556 if( !aOvflSpace ){
6557 return SQLITE_NOMEM;
6558 }
6559
danielk1977a50d9aa2009-06-08 14:49:45 +00006560 /* Find the sibling pages to balance. Also locate the cells in pParent
6561 ** that divide the siblings. An attempt is made to find NN siblings on
6562 ** either side of pPage. More siblings are taken from one side, however,
6563 ** if there are fewer than NN siblings on the other side. If pParent
danielk19774dbaa892009-06-16 16:50:22 +00006564 ** has NB or fewer children then all children of pParent are taken.
6565 **
6566 ** This loop also drops the divider cells from the parent page. This
6567 ** way, the remainder of the function does not have to deal with any
drhcd09c532009-07-20 19:30:00 +00006568 ** overflow cells in the parent page, since if any existed they will
6569 ** have already been removed.
6570 */
danielk19774dbaa892009-06-16 16:50:22 +00006571 i = pParent->nOverflow + pParent->nCell;
6572 if( i<2 ){
drhc3b70572003-01-04 19:44:07 +00006573 nxDiv = 0;
danielk19774dbaa892009-06-16 16:50:22 +00006574 }else{
dan7d6885a2012-08-08 14:04:56 +00006575 assert( bBulk==0 || bBulk==1 );
danielk19774dbaa892009-06-16 16:50:22 +00006576 if( iParentIdx==0 ){
6577 nxDiv = 0;
6578 }else if( iParentIdx==i ){
dan7d6885a2012-08-08 14:04:56 +00006579 nxDiv = i-2+bBulk;
drh14acc042001-06-10 19:56:58 +00006580 }else{
dan7d6885a2012-08-08 14:04:56 +00006581 assert( bBulk==0 );
danielk19774dbaa892009-06-16 16:50:22 +00006582 nxDiv = iParentIdx-1;
drh8b2f49b2001-06-08 00:21:52 +00006583 }
dan7d6885a2012-08-08 14:04:56 +00006584 i = 2-bBulk;
danielk19774dbaa892009-06-16 16:50:22 +00006585 }
dan7d6885a2012-08-08 14:04:56 +00006586 nOld = i+1;
danielk19774dbaa892009-06-16 16:50:22 +00006587 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
6588 pRight = &pParent->aData[pParent->hdrOffset+8];
6589 }else{
6590 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
6591 }
6592 pgno = get4byte(pRight);
6593 while( 1 ){
dan11dcd112013-03-15 18:29:18 +00006594 rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
danielk19774dbaa892009-06-16 16:50:22 +00006595 if( rc ){
danielk197789bc4bc2009-07-21 19:25:24 +00006596 memset(apOld, 0, (i+1)*sizeof(MemPage*));
danielk19774dbaa892009-06-16 16:50:22 +00006597 goto balance_cleanup;
6598 }
danielk1977634f2982005-03-28 08:44:07 +00006599 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
danielk19774dbaa892009-06-16 16:50:22 +00006600 if( (i--)==0 ) break;
6601
drh2cbd78b2012-02-02 19:37:18 +00006602 if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
6603 apDiv[i] = pParent->apOvfl[0];
danielk19774dbaa892009-06-16 16:50:22 +00006604 pgno = get4byte(apDiv[i]);
6605 szNew[i] = cellSizePtr(pParent, apDiv[i]);
6606 pParent->nOverflow = 0;
6607 }else{
6608 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
6609 pgno = get4byte(apDiv[i]);
6610 szNew[i] = cellSizePtr(pParent, apDiv[i]);
6611
6612 /* Drop the cell from the parent page. apDiv[i] still points to
6613 ** the cell within the parent, even though it has been dropped.
6614 ** This is safe because dropping a cell only overwrites the first
6615 ** four bytes of it, and this function does not need the first
6616 ** four bytes of the divider cell. So the pointer is safe to use
danielk197711a8a862009-06-17 11:49:52 +00006617 ** later on.
6618 **
drh8a575d92011-10-12 17:00:28 +00006619 ** But not if we are in secure-delete mode. In secure-delete mode,
danielk197711a8a862009-06-17 11:49:52 +00006620 ** the dropCell() routine will overwrite the entire cell with zeroes.
6621 ** In this case, temporarily copy the cell into the aOvflSpace[]
6622 ** buffer. It will be copied out again as soon as the aSpace[] buffer
6623 ** is allocated. */
drhc9166342012-01-05 23:32:06 +00006624 if( pBt->btsFlags & BTS_SECURE_DELETE ){
drh8a575d92011-10-12 17:00:28 +00006625 int iOff;
6626
6627 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
drh43b18e12010-08-17 19:40:08 +00006628 if( (iOff+szNew[i])>(int)pBt->usableSize ){
dan2ed11e72010-02-26 15:09:19 +00006629 rc = SQLITE_CORRUPT_BKPT;
6630 memset(apOld, 0, (i+1)*sizeof(MemPage*));
6631 goto balance_cleanup;
6632 }else{
6633 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
6634 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
6635 }
drh5b47efa2010-02-12 18:18:39 +00006636 }
drh98add2e2009-07-20 17:11:49 +00006637 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006638 }
drh8b2f49b2001-06-08 00:21:52 +00006639 }
6640
drha9121e42008-02-19 14:59:35 +00006641 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00006642 ** alignment */
drha9121e42008-02-19 14:59:35 +00006643 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00006644
drh8b2f49b2001-06-08 00:21:52 +00006645 /*
danielk1977634f2982005-03-28 08:44:07 +00006646 ** Allocate space for memory structures
6647 */
drhfacf0302008-06-17 15:12:00 +00006648 szScratch =
drha9121e42008-02-19 14:59:35 +00006649 nMaxCells*sizeof(u8*) /* apCell */
6650 + nMaxCells*sizeof(u16) /* szCell */
dan33ea4862014-10-09 19:35:37 +00006651 + pBt->pageSize; /* aSpace1 */
drhfacf0302008-06-17 15:12:00 +00006652 apCell = sqlite3ScratchMalloc( szScratch );
danielk197711a8a862009-06-17 11:49:52 +00006653 if( apCell==0 ){
danielk1977634f2982005-03-28 08:44:07 +00006654 rc = SQLITE_NOMEM;
6655 goto balance_cleanup;
6656 }
drha9121e42008-02-19 14:59:35 +00006657 szCell = (u16*)&apCell[nMaxCells];
danielk19774dbaa892009-06-16 16:50:22 +00006658 aSpace1 = (u8*)&szCell[nMaxCells];
drhea598cb2009-04-05 12:22:08 +00006659 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
drh14acc042001-06-10 19:56:58 +00006660
6661 /*
6662 ** Load pointers to all cells on sibling pages and the divider cells
6663 ** into the local apCell[] array. Make copies of the divider cells
dan33ea4862014-10-09 19:35:37 +00006664 ** into space obtained from aSpace1[]. The divider cells have already
6665 ** been removed from pParent.
drh4b70f112004-05-02 21:12:19 +00006666 **
6667 ** If the siblings are on leaf pages, then the child pointers of the
6668 ** divider cells are stripped from the cells before they are copied
drhe5ae5732008-06-15 02:51:47 +00006669 ** into aSpace1[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00006670 ** child pointers. If siblings are not leaves, then all cell in
6671 ** apCell[] include child pointers. Either way, all cells in apCell[]
6672 ** are alike.
drh96f5b762004-05-16 16:24:36 +00006673 **
6674 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
6675 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00006676 */
danielk1977a50d9aa2009-06-08 14:49:45 +00006677 leafCorrection = apOld[0]->leaf*4;
drh3e28ff52014-09-24 00:59:08 +00006678 leafData = apOld[0]->intKeyLeaf;
drh8b2f49b2001-06-08 00:21:52 +00006679 for(i=0; i<nOld; i++){
danielk19774dbaa892009-06-16 16:50:22 +00006680 int limit;
dan33ea4862014-10-09 19:35:37 +00006681 MemPage *pOld = apOld[i];
danielk19774dbaa892009-06-16 16:50:22 +00006682
6683 limit = pOld->nCell+pOld->nOverflow;
drh68f2a572011-06-03 17:50:49 +00006684 if( pOld->nOverflow>0 ){
6685 for(j=0; j<limit; j++){
6686 assert( nCell<nMaxCells );
6687 apCell[nCell] = findOverflowCell(pOld, j);
6688 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
6689 nCell++;
6690 }
6691 }else{
6692 u8 *aData = pOld->aData;
6693 u16 maskPage = pOld->maskPage;
6694 u16 cellOffset = pOld->cellOffset;
6695 for(j=0; j<limit; j++){
6696 assert( nCell<nMaxCells );
6697 apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
6698 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
6699 nCell++;
6700 }
6701 }
dan09c68402014-10-11 20:00:24 +00006702 cntOld[i] = nCell;
danielk19774dbaa892009-06-16 16:50:22 +00006703 if( i<nOld-1 && !leafData){
shane36840fd2009-06-26 16:32:13 +00006704 u16 sz = (u16)szNew[i];
danielk19774dbaa892009-06-16 16:50:22 +00006705 u8 *pTemp;
6706 assert( nCell<nMaxCells );
6707 szCell[nCell] = sz;
6708 pTemp = &aSpace1[iSpace1];
6709 iSpace1 += sz;
drhe22e03e2010-08-18 21:19:03 +00006710 assert( sz<=pBt->maxLocal+23 );
drhfcd71b62011-04-05 22:08:24 +00006711 assert( iSpace1 <= (int)pBt->pageSize );
danielk19774dbaa892009-06-16 16:50:22 +00006712 memcpy(pTemp, apDiv[i], sz);
6713 apCell[nCell] = pTemp+leafCorrection;
6714 assert( leafCorrection==0 || leafCorrection==4 );
shane36840fd2009-06-26 16:32:13 +00006715 szCell[nCell] = szCell[nCell] - leafCorrection;
danielk19774dbaa892009-06-16 16:50:22 +00006716 if( !pOld->leaf ){
6717 assert( leafCorrection==0 );
6718 assert( pOld->hdrOffset==0 );
6719 /* The right pointer of the child page pOld becomes the left
6720 ** pointer of the divider cell */
6721 memcpy(apCell[nCell], &pOld->aData[8], 4);
6722 }else{
6723 assert( leafCorrection==4 );
6724 if( szCell[nCell]<4 ){
6725 /* Do not allow any cells smaller than 4 bytes. */
6726 szCell[nCell] = 4;
danielk1977ac11ee62005-01-15 12:45:51 +00006727 }
6728 }
drh14acc042001-06-10 19:56:58 +00006729 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00006730 }
drh8b2f49b2001-06-08 00:21:52 +00006731 }
6732
6733 /*
drh6019e162001-07-02 17:51:45 +00006734 ** Figure out the number of pages needed to hold all nCell cells.
6735 ** Store this number in "k". Also compute szNew[] which is the total
6736 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00006737 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00006738 ** cntNew[k] should equal nCell.
6739 **
drh96f5b762004-05-16 16:24:36 +00006740 ** Values computed by this block:
6741 **
6742 ** k: The total number of sibling pages
6743 ** szNew[i]: Spaced used on the i-th sibling page.
6744 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
6745 ** the right of the i-th sibling page.
6746 ** usableSpace: Number of bytes of space available on each sibling.
6747 **
drh8b2f49b2001-06-08 00:21:52 +00006748 */
drh43605152004-05-29 21:46:49 +00006749 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00006750 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00006751 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00006752 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00006753 if( subtotal > usableSpace ){
dand7b545b2014-10-13 18:03:27 +00006754 szNew[k] = subtotal - szCell[i] - 2;
drh6019e162001-07-02 17:51:45 +00006755 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00006756 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00006757 subtotal = 0;
6758 k++;
drh9978c972010-02-23 17:36:32 +00006759 if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
drh6019e162001-07-02 17:51:45 +00006760 }
6761 }
6762 szNew[k] = subtotal;
6763 cntNew[k] = nCell;
6764 k++;
drh96f5b762004-05-16 16:24:36 +00006765
6766 /*
6767 ** The packing computed by the previous block is biased toward the siblings
6768 ** on the left side. The left siblings are always nearly full, while the
6769 ** right-most sibling might be nearly empty. This block of code attempts
6770 ** to adjust the packing of siblings to get a better balance.
6771 **
6772 ** This adjustment is more than an optimization. The packing above might
6773 ** be so out of balance as to be illegal. For example, the right-most
6774 ** sibling might be completely empty. This adjustment is not optional.
6775 */
drh6019e162001-07-02 17:51:45 +00006776 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00006777 int szRight = szNew[i]; /* Size of sibling on the right */
6778 int szLeft = szNew[i-1]; /* Size of sibling on the left */
6779 int r; /* Index of right-most cell in left sibling */
6780 int d; /* Index of first cell to the left of right sibling */
6781
6782 r = cntNew[i-1] - 1;
6783 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00006784 assert( d<nMaxCells );
6785 assert( r<nMaxCells );
danf64cc492012-08-08 11:55:15 +00006786 while( szRight==0
6787 || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
6788 ){
drh43605152004-05-29 21:46:49 +00006789 szRight += szCell[d] + 2;
6790 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00006791 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00006792 r = cntNew[i-1] - 1;
6793 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00006794 }
drh96f5b762004-05-16 16:24:36 +00006795 szNew[i] = szRight;
6796 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00006797 }
drh09d0deb2005-08-02 17:13:09 +00006798
danielk19776f235cc2009-06-04 14:46:08 +00006799 /* Either we found one or more cells (cntnew[0])>0) or pPage is
drh09d0deb2005-08-02 17:13:09 +00006800 ** a virtual root page. A virtual root page is when the real root
6801 ** page is page 1 and we are the only child of that page.
drh2f32fba2012-01-02 16:38:57 +00006802 **
6803 ** UPDATE: The assert() below is not necessarily true if the database
6804 ** file is corrupt. The corruption will be detected and reported later
6805 ** in this procedure so there is no need to act upon it now.
drh09d0deb2005-08-02 17:13:09 +00006806 */
drh2f32fba2012-01-02 16:38:57 +00006807#if 0
drh09d0deb2005-08-02 17:13:09 +00006808 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh2f32fba2012-01-02 16:38:57 +00006809#endif
drh8b2f49b2001-06-08 00:21:52 +00006810
dan33ea4862014-10-09 19:35:37 +00006811 TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
6812 apOld[0]->pgno, apOld[0]->nCell,
6813 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
6814 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
danielk1977e5765212009-06-17 11:13:28 +00006815 ));
6816
drh8b2f49b2001-06-08 00:21:52 +00006817 /*
drh6b308672002-07-08 02:16:37 +00006818 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00006819 */
drheac74422009-06-14 12:47:11 +00006820 if( apOld[0]->pgno<=1 ){
drh9978c972010-02-23 17:36:32 +00006821 rc = SQLITE_CORRUPT_BKPT;
drheac74422009-06-14 12:47:11 +00006822 goto balance_cleanup;
6823 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006824 pageFlags = apOld[0]->aData[0];
drh14acc042001-06-10 19:56:58 +00006825 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00006826 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00006827 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00006828 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00006829 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00006830 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00006831 nNew++;
danielk197728129562005-01-11 10:25:06 +00006832 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00006833 }else{
drh7aa8f852006-03-28 00:24:44 +00006834 assert( i>0 );
dan428c2182012-08-06 18:50:11 +00006835 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
drh6b308672002-07-08 02:16:37 +00006836 if( rc ) goto balance_cleanup;
dan33ea4862014-10-09 19:35:37 +00006837 zeroPage(pNew, pageFlags);
drhda200cc2004-05-09 11:51:38 +00006838 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00006839 nNew++;
dan09c68402014-10-11 20:00:24 +00006840 cntOld[i] = nCell;
danielk19774dbaa892009-06-16 16:50:22 +00006841
6842 /* Set the pointer-map entry for the new sibling page. */
6843 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00006844 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006845 if( rc!=SQLITE_OK ){
6846 goto balance_cleanup;
6847 }
6848 }
drh6b308672002-07-08 02:16:37 +00006849 }
drh8b2f49b2001-06-08 00:21:52 +00006850 }
6851
6852 /*
dan33ea4862014-10-09 19:35:37 +00006853 ** Reassign page numbers so that the new pages are in ascending order.
6854 ** This helps to keep entries in the disk file in order so that a scan
6855 ** of the table is closer to a linear scan through the file. That in turn
6856 ** helps the operating system to deliver pages from the disk more rapidly.
drhf9ffac92002-03-02 19:00:31 +00006857 **
dan33ea4862014-10-09 19:35:37 +00006858 ** An O(n^2) insertion sort algorithm is used, but since n is never more
6859 ** than (NB+2) (a small constant), that should not be a problem.
drhf9ffac92002-03-02 19:00:31 +00006860 **
dan33ea4862014-10-09 19:35:37 +00006861 ** When NB==3, this one optimization makes the database about 25% faster
6862 ** for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00006863 */
dan33ea4862014-10-09 19:35:37 +00006864 for(i=0; i<nNew; i++){
6865 aPgno[i] = apNew[i]->pgno;
6866 aPgFlags[i] = apNew[i]->pDbPage->flags;
dan89ca0b32014-10-25 20:36:28 +00006867 for(j=0; j<i; j++){
6868 if( aPgno[j]==aPgno[i] ){
6869 /* This branch is taken if the set of sibling pages somehow contains
6870 ** duplicate entries. This can happen if the database is corrupt.
6871 ** It would be simpler to detect this as part of the loop below, but
6872 ** in order to avoid populating the pager cache with two separate
6873 ** objects associated with the same page number. */
6874 assert( CORRUPT_DB );
6875 rc = SQLITE_CORRUPT_BKPT;
6876 goto balance_cleanup;
6877 }
6878 }
dan33ea4862014-10-09 19:35:37 +00006879 }
6880 for(i=0; i<nNew; i++){
dan31f4e992014-10-24 20:57:03 +00006881 int iBest = 0; /* aPgno[] index of page number to use */
6882 Pgno pgno; /* Page number to use */
6883 for(j=1; j<nNew; j++){
6884 if( aPgno[j]<aPgno[iBest] ) iBest = j;
drhf9ffac92002-03-02 19:00:31 +00006885 }
dan31f4e992014-10-24 20:57:03 +00006886 pgno = aPgno[iBest];
6887 aPgno[iBest] = 0xffffffff;
6888 if( iBest!=i ){
6889 if( iBest>i ){
6890 sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
6891 }
6892 sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
6893 apNew[i]->pgno = pgno;
drhf9ffac92002-03-02 19:00:31 +00006894 }
6895 }
dan33ea4862014-10-09 19:35:37 +00006896
6897 TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
6898 "%d(%d nc=%d) %d(%d nc=%d)\n",
6899 apNew[0]->pgno, szNew[0], cntNew[0],
danielk19774dbaa892009-06-16 16:50:22 +00006900 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
dan33ea4862014-10-09 19:35:37 +00006901 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
danielk19774dbaa892009-06-16 16:50:22 +00006902 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
dan33ea4862014-10-09 19:35:37 +00006903 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
danielk19774dbaa892009-06-16 16:50:22 +00006904 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
dan33ea4862014-10-09 19:35:37 +00006905 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
6906 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
6907 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
6908 ));
danielk19774dbaa892009-06-16 16:50:22 +00006909
6910 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
6911 put4byte(pRight, apNew[nNew-1]->pgno);
drh24cd67e2004-05-10 16:18:47 +00006912
dan33ea4862014-10-09 19:35:37 +00006913 /* If the sibling pages are not leaves, ensure that the right-child pointer
6914 ** of the right-most new sibling page is set to the value that was
6915 ** originally in the same field of the right-most old sibling page. */
6916 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
6917 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
6918 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
6919 }
danielk1977ac11ee62005-01-15 12:45:51 +00006920
dan33ea4862014-10-09 19:35:37 +00006921 /* Make any required updates to pointer map entries associated with
6922 ** cells stored on sibling pages following the balance operation. Pointer
6923 ** map entries associated with divider cells are set by the insertCell()
6924 ** routine. The associated pointer map entries are:
6925 **
6926 ** a) if the cell contains a reference to an overflow chain, the
6927 ** entry associated with the first page in the overflow chain, and
6928 **
6929 ** b) if the sibling pages are not leaves, the child page associated
6930 ** with the cell.
6931 **
6932 ** If the sibling pages are not leaves, then the pointer map entry
6933 ** associated with the right-child of each sibling may also need to be
6934 ** updated. This happens below, after the sibling pages have been
6935 ** populated, not here.
6936 */
6937 if( ISAUTOVACUUM ){
6938 MemPage *pNew = apNew[0];
6939 u8 *aOld = pNew->aData;
6940 int cntOldNext = pNew->nCell + pNew->nOverflow;
6941 int usableSize = pBt->usableSize;
6942 int iNew = 0;
6943 int iOld = 0;
danielk1977634f2982005-03-28 08:44:07 +00006944
dan33ea4862014-10-09 19:35:37 +00006945 for(i=0; i<nCell; i++){
6946 u8 *pCell = apCell[i];
6947 if( i==cntOldNext ){
6948 MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
6949 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
6950 aOld = pOld->aData;
6951 }
6952 if( i==cntNew[iNew] ){
6953 pNew = apNew[++iNew];
6954 if( !leafData ) continue;
6955 }
6956
6957 /* Cell pCell is destined for new sibling page pNew. Originally, it
6958 ** was either part of sibling page iOld (possibly an overflow page),
6959 ** or else the divider cell to the left of sibling page iOld. So,
6960 ** if sibling page iOld had the same page number as pNew, and if
6961 ** pCell really was a part of sibling page iOld (not a divider or
6962 ** overflow cell), we can skip updating the pointer map entries. */
6963 if( pNew->pgno!=aPgno[iOld] || pCell<aOld || pCell>=&aOld[usableSize] ){
6964 if( !leafCorrection ){
6965 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
6966 }
6967 if( szCell[i]>pNew->minLocal ){
6968 ptrmapPutOvflPtr(pNew, pCell, &rc);
danielk19774aeff622007-05-12 09:30:47 +00006969 }
drh4b70f112004-05-02 21:12:19 +00006970 }
drh14acc042001-06-10 19:56:58 +00006971 }
6972 }
dan33ea4862014-10-09 19:35:37 +00006973
6974 /* Insert new divider cells into pParent. */
6975 for(i=0; i<nNew-1; i++){
6976 u8 *pCell;
6977 u8 *pTemp;
6978 int sz;
6979 MemPage *pNew = apNew[i];
6980 j = cntNew[i];
6981
6982 assert( j<nMaxCells );
6983 pCell = apCell[j];
6984 sz = szCell[j] + leafCorrection;
6985 pTemp = &aOvflSpace[iOvflSpace];
6986 if( !pNew->leaf ){
6987 memcpy(&pNew->aData[8], pCell, 4);
6988 }else if( leafData ){
6989 /* If the tree is a leaf-data tree, and the siblings are leaves,
6990 ** then there is no divider cell in apCell[]. Instead, the divider
6991 ** cell consists of the integer key for the right-most cell of
6992 ** the sibling-page assembled above only.
6993 */
6994 CellInfo info;
6995 j--;
6996 btreeParseCellPtr(pNew, apCell[j], &info);
6997 pCell = pTemp;
6998 sz = 4 + putVarint(&pCell[4], info.nKey);
6999 pTemp = 0;
7000 }else{
7001 pCell -= 4;
7002 /* Obscure case for non-leaf-data trees: If the cell at pCell was
7003 ** previously stored on a leaf node, and its reported size was 4
7004 ** bytes, then it may actually be smaller than this
7005 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
7006 ** any cell). But it is important to pass the correct size to
7007 ** insertCell(), so reparse the cell now.
7008 **
7009 ** Note that this can never happen in an SQLite data file, as all
7010 ** cells are at least 4 bytes. It only happens in b-trees used
7011 ** to evaluate "IN (SELECT ...)" and similar clauses.
7012 */
7013 if( szCell[j]==4 ){
7014 assert(leafCorrection==4);
7015 sz = cellSizePtr(pParent, pCell);
7016 }
7017 }
7018 iOvflSpace += sz;
7019 assert( sz<=pBt->maxLocal+23 );
7020 assert( iOvflSpace <= (int)pBt->pageSize );
7021 insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
7022 if( rc!=SQLITE_OK ) goto balance_cleanup;
7023 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7024 }
7025
7026 /* Now update the actual sibling pages. The order in which they are updated
7027 ** is important, as this code needs to avoid disrupting any page from which
7028 ** cells may still to be read. In practice, this means:
7029 **
dan8e9ba0c2014-10-14 17:27:04 +00007030 ** 1) If cells are to be removed from the start of the page and shifted
7031 ** to the left-hand sibling, it is not safe to update the page until
7032 ** the left-hand sibling (apNew[i-1]) has already been updated.
dan33ea4862014-10-09 19:35:37 +00007033 **
dan8e9ba0c2014-10-14 17:27:04 +00007034 ** 2) If cells are to be removed from the end of the page and shifted
7035 ** to the right-hand sibling, it is not safe to update the page until
7036 ** the right-hand sibling (apNew[i+1]) has already been updated.
dan33ea4862014-10-09 19:35:37 +00007037 **
7038 ** If neither of the above apply, the page is safe to update.
7039 */
dan33ea4862014-10-09 19:35:37 +00007040 for(i=0; i<nNew*2; i++){
7041 int iPg = (i>=nNew ? i-nNew : nNew-1-i);
7042 if( abDone[iPg]==0
dan8e9ba0c2014-10-14 17:27:04 +00007043 && (iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1])
7044 && (cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1])
dan33ea4862014-10-09 19:35:37 +00007045 ){
dan09c68402014-10-11 20:00:24 +00007046 int iNew;
7047 int iOld;
7048 int nNewCell;
7049
7050 if( iPg==0 ){
7051 iNew = iOld = 0;
7052 nNewCell = cntNew[0];
7053 }else{
7054 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : nCell;
7055 iNew = cntNew[iPg-1] + !leafData;
7056 nNewCell = cntNew[iPg] - iNew;
7057 }
7058
7059 editPage(apNew[iPg], iOld, iNew, nNewCell, apCell, szCell);
dan33ea4862014-10-09 19:35:37 +00007060 abDone[iPg] = 1;
dand7b545b2014-10-13 18:03:27 +00007061 apNew[iPg]->nFree = usableSpace-szNew[iPg];
dan09c68402014-10-11 20:00:24 +00007062 assert( apNew[iPg]->nOverflow==0 );
7063 assert( apNew[iPg]->nCell==nNewCell );
dan33ea4862014-10-09 19:35:37 +00007064 }
7065 }
7066 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
7067
drh7aa8f852006-03-28 00:24:44 +00007068 assert( nOld>0 );
7069 assert( nNew>0 );
drh14acc042001-06-10 19:56:58 +00007070
danielk197713bd99f2009-06-24 05:40:34 +00007071 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
7072 /* The root page of the b-tree now contains no cells. The only sibling
7073 ** page is the right-child of the parent. Copy the contents of the
7074 ** child page into the parent, decreasing the overall height of the
7075 ** b-tree structure by one. This is described as the "balance-shallower"
7076 ** sub-algorithm in some documentation.
7077 **
7078 ** If this is an auto-vacuum database, the call to copyNodeContent()
7079 ** sets all pointer-map entries corresponding to database image pages
7080 ** for which the pointer is stored within the content being copied.
7081 **
7082 ** The second assert below verifies that the child page is defragmented
7083 ** (it must be, as it was just reconstructed using assemblePage()). This
7084 ** is important if the parent page happens to be page 1 of the database
7085 ** image. */
7086 assert( nNew==1 );
dan89ca0b32014-10-25 20:36:28 +00007087 rc = defragmentPage(apNew[0]);
7088 if( rc==SQLITE_OK ){
7089 assert( apNew[0]->nFree ==
7090 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
7091 );
7092 copyNodeContent(apNew[0], pParent, &rc);
7093 freePage(apNew[0], &rc);
7094 }
dan33ea4862014-10-09 19:35:37 +00007095 }else if( ISAUTOVACUUM && !leafCorrection ){
7096 /* Fix the pointer map entries associated with the right-child of each
7097 ** sibling page. All other pointer map entries have already been taken
7098 ** care of. */
7099 for(i=0; i<nNew; i++){
7100 u32 key = get4byte(&apNew[i]->aData[8]);
7101 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00007102 }
dan33ea4862014-10-09 19:35:37 +00007103 }
danielk19774dbaa892009-06-16 16:50:22 +00007104
dan33ea4862014-10-09 19:35:37 +00007105 assert( pParent->isInit );
7106 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
7107 nOld, nNew, nCell));
danielk19774dbaa892009-06-16 16:50:22 +00007108
dan33ea4862014-10-09 19:35:37 +00007109 /* Free any old pages that were not reused as new pages.
7110 */
7111 for(i=nNew; i<nOld; i++){
7112 freePage(apOld[i], &rc);
7113 }
7114
dane6593d82014-10-24 16:40:49 +00007115#if 0
dan33ea4862014-10-09 19:35:37 +00007116 if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
danielk19774dbaa892009-06-16 16:50:22 +00007117 /* The ptrmapCheckPages() contains assert() statements that verify that
7118 ** all pointer map pages are set correctly. This is helpful while
7119 ** debugging. This is usually disabled because a corrupt database may
7120 ** cause an assert() statement to fail. */
7121 ptrmapCheckPages(apNew, nNew);
7122 ptrmapCheckPages(&pParent, 1);
danielk19774dbaa892009-06-16 16:50:22 +00007123 }
dan33ea4862014-10-09 19:35:37 +00007124#endif
danielk1977cd581a72009-06-23 15:43:39 +00007125
drh8b2f49b2001-06-08 00:21:52 +00007126 /*
drh14acc042001-06-10 19:56:58 +00007127 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00007128 */
drh14acc042001-06-10 19:56:58 +00007129balance_cleanup:
drhfacf0302008-06-17 15:12:00 +00007130 sqlite3ScratchFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00007131 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00007132 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00007133 }
drh14acc042001-06-10 19:56:58 +00007134 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00007135 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00007136 }
danielk1977eaa06f62008-09-18 17:34:44 +00007137
drh8b2f49b2001-06-08 00:21:52 +00007138 return rc;
7139}
mistachkine7c54162012-10-02 22:54:27 +00007140#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
7141#pragma optimize("", on)
7142#endif
drh8b2f49b2001-06-08 00:21:52 +00007143
drh43605152004-05-29 21:46:49 +00007144
7145/*
danielk1977a50d9aa2009-06-08 14:49:45 +00007146** This function is called when the root page of a b-tree structure is
7147** overfull (has one or more overflow pages).
drh43605152004-05-29 21:46:49 +00007148**
danielk1977a50d9aa2009-06-08 14:49:45 +00007149** A new child page is allocated and the contents of the current root
7150** page, including overflow cells, are copied into the child. The root
7151** page is then overwritten to make it an empty page with the right-child
7152** pointer pointing to the new page.
7153**
7154** Before returning, all pointer-map entries corresponding to pages
7155** that the new child-page now contains pointers to are updated. The
7156** entry corresponding to the new right-child pointer of the root
7157** page is also updated.
7158**
7159** If successful, *ppChild is set to contain a reference to the child
7160** page and SQLITE_OK is returned. In this case the caller is required
7161** to call releasePage() on *ppChild exactly once. If an error occurs,
7162** an error code is returned and *ppChild is set to 0.
drh43605152004-05-29 21:46:49 +00007163*/
danielk1977a50d9aa2009-06-08 14:49:45 +00007164static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
7165 int rc; /* Return value from subprocedures */
7166 MemPage *pChild = 0; /* Pointer to a new child page */
shane5eff7cf2009-08-10 03:57:58 +00007167 Pgno pgnoChild = 0; /* Page number of the new child page */
danielk1977a50d9aa2009-06-08 14:49:45 +00007168 BtShared *pBt = pRoot->pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00007169
danielk1977a50d9aa2009-06-08 14:49:45 +00007170 assert( pRoot->nOverflow>0 );
drh1fee73e2007-08-29 04:00:57 +00007171 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bc2ca9e2008-11-13 14:28:28 +00007172
danielk1977a50d9aa2009-06-08 14:49:45 +00007173 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
7174 ** page that will become the new right-child of pPage. Copy the contents
7175 ** of the node stored on pRoot into the new child page.
7176 */
drh98add2e2009-07-20 17:11:49 +00007177 rc = sqlite3PagerWrite(pRoot->pDbPage);
7178 if( rc==SQLITE_OK ){
7179 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
drhc314dc72009-07-21 11:52:34 +00007180 copyNodeContent(pRoot, pChild, &rc);
7181 if( ISAUTOVACUUM ){
7182 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
drh98add2e2009-07-20 17:11:49 +00007183 }
7184 }
7185 if( rc ){
danielk1977a50d9aa2009-06-08 14:49:45 +00007186 *ppChild = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00007187 releasePage(pChild);
danielk1977a50d9aa2009-06-08 14:49:45 +00007188 return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00007189 }
danielk1977a50d9aa2009-06-08 14:49:45 +00007190 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
7191 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
7192 assert( pChild->nCell==pRoot->nCell );
danielk197771d5d2c2008-09-29 11:49:47 +00007193
danielk1977a50d9aa2009-06-08 14:49:45 +00007194 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
7195
7196 /* Copy the overflow cells from pRoot to pChild */
drh2cbd78b2012-02-02 19:37:18 +00007197 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
7198 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
7199 memcpy(pChild->apOvfl, pRoot->apOvfl,
7200 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
danielk1977a50d9aa2009-06-08 14:49:45 +00007201 pChild->nOverflow = pRoot->nOverflow;
danielk1977a50d9aa2009-06-08 14:49:45 +00007202
7203 /* Zero the contents of pRoot. Then install pChild as the right-child. */
7204 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
7205 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
7206
7207 *ppChild = pChild;
7208 return SQLITE_OK;
drh43605152004-05-29 21:46:49 +00007209}
7210
7211/*
danielk197771d5d2c2008-09-29 11:49:47 +00007212** The page that pCur currently points to has just been modified in
7213** some way. This function figures out if this modification means the
7214** tree needs to be balanced, and if so calls the appropriate balancing
danielk1977a50d9aa2009-06-08 14:49:45 +00007215** routine. Balancing routines are:
7216**
7217** balance_quick()
danielk1977a50d9aa2009-06-08 14:49:45 +00007218** balance_deeper()
7219** balance_nonroot()
drh43605152004-05-29 21:46:49 +00007220*/
danielk1977a50d9aa2009-06-08 14:49:45 +00007221static int balance(BtCursor *pCur){
drh43605152004-05-29 21:46:49 +00007222 int rc = SQLITE_OK;
danielk1977a50d9aa2009-06-08 14:49:45 +00007223 const int nMin = pCur->pBt->usableSize * 2 / 3;
7224 u8 aBalanceQuickSpace[13];
7225 u8 *pFree = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00007226
shane75ac1de2009-06-09 18:58:52 +00007227 TESTONLY( int balance_quick_called = 0 );
7228 TESTONLY( int balance_deeper_called = 0 );
danielk1977a50d9aa2009-06-08 14:49:45 +00007229
7230 do {
7231 int iPage = pCur->iPage;
7232 MemPage *pPage = pCur->apPage[iPage];
7233
7234 if( iPage==0 ){
7235 if( pPage->nOverflow ){
7236 /* The root page of the b-tree is overfull. In this case call the
7237 ** balance_deeper() function to create a new child for the root-page
7238 ** and copy the current contents of the root-page to it. The
7239 ** next iteration of the do-loop will balance the child page.
7240 */
7241 assert( (balance_deeper_called++)==0 );
7242 rc = balance_deeper(pPage, &pCur->apPage[1]);
7243 if( rc==SQLITE_OK ){
7244 pCur->iPage = 1;
7245 pCur->aiIdx[0] = 0;
7246 pCur->aiIdx[1] = 0;
7247 assert( pCur->apPage[1]->nOverflow );
7248 }
danielk1977a50d9aa2009-06-08 14:49:45 +00007249 }else{
danielk1977a50d9aa2009-06-08 14:49:45 +00007250 break;
7251 }
7252 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
7253 break;
7254 }else{
7255 MemPage * const pParent = pCur->apPage[iPage-1];
7256 int const iIdx = pCur->aiIdx[iPage-1];
7257
7258 rc = sqlite3PagerWrite(pParent->pDbPage);
7259 if( rc==SQLITE_OK ){
7260#ifndef SQLITE_OMIT_QUICKBALANCE
drh3e28ff52014-09-24 00:59:08 +00007261 if( pPage->intKeyLeaf
danielk1977a50d9aa2009-06-08 14:49:45 +00007262 && pPage->nOverflow==1
drh2cbd78b2012-02-02 19:37:18 +00007263 && pPage->aiOvfl[0]==pPage->nCell
danielk1977a50d9aa2009-06-08 14:49:45 +00007264 && pParent->pgno!=1
7265 && pParent->nCell==iIdx
7266 ){
7267 /* Call balance_quick() to create a new sibling of pPage on which
7268 ** to store the overflow cell. balance_quick() inserts a new cell
7269 ** into pParent, which may cause pParent overflow. If this
peter.d.reid60ec9142014-09-06 16:39:46 +00007270 ** happens, the next iteration of the do-loop will balance pParent
danielk1977a50d9aa2009-06-08 14:49:45 +00007271 ** use either balance_nonroot() or balance_deeper(). Until this
7272 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
7273 ** buffer.
7274 **
7275 ** The purpose of the following assert() is to check that only a
7276 ** single call to balance_quick() is made for each call to this
7277 ** function. If this were not verified, a subtle bug involving reuse
7278 ** of the aBalanceQuickSpace[] might sneak in.
7279 */
7280 assert( (balance_quick_called++)==0 );
7281 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
7282 }else
7283#endif
7284 {
7285 /* In this case, call balance_nonroot() to redistribute cells
7286 ** between pPage and up to 2 of its sibling pages. This involves
7287 ** modifying the contents of pParent, which may cause pParent to
7288 ** become overfull or underfull. The next iteration of the do-loop
7289 ** will balance the parent page to correct this.
7290 **
7291 ** If the parent page becomes overfull, the overflow cell or cells
7292 ** are stored in the pSpace buffer allocated immediately below.
7293 ** A subsequent iteration of the do-loop will deal with this by
7294 ** calling balance_nonroot() (balance_deeper() may be called first,
7295 ** but it doesn't deal with overflow cells - just moves them to a
7296 ** different page). Once this subsequent call to balance_nonroot()
7297 ** has completed, it is safe to release the pSpace buffer used by
7298 ** the previous call, as the overflow cell data will have been
7299 ** copied either into the body of a database page or into the new
7300 ** pSpace buffer passed to the latter call to balance_nonroot().
7301 */
7302 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
dan428c2182012-08-06 18:50:11 +00007303 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
danielk1977a50d9aa2009-06-08 14:49:45 +00007304 if( pFree ){
7305 /* If pFree is not NULL, it points to the pSpace buffer used
7306 ** by a previous call to balance_nonroot(). Its contents are
7307 ** now stored either on real database pages or within the
7308 ** new pSpace buffer, so it may be safely freed here. */
7309 sqlite3PageFree(pFree);
7310 }
7311
danielk19774dbaa892009-06-16 16:50:22 +00007312 /* The pSpace buffer will be freed after the next call to
7313 ** balance_nonroot(), or just before this function returns, whichever
7314 ** comes first. */
danielk1977a50d9aa2009-06-08 14:49:45 +00007315 pFree = pSpace;
danielk1977a50d9aa2009-06-08 14:49:45 +00007316 }
7317 }
7318
7319 pPage->nOverflow = 0;
7320
7321 /* The next iteration of the do-loop balances the parent page. */
7322 releasePage(pPage);
7323 pCur->iPage--;
drh43605152004-05-29 21:46:49 +00007324 }
danielk1977a50d9aa2009-06-08 14:49:45 +00007325 }while( rc==SQLITE_OK );
7326
7327 if( pFree ){
7328 sqlite3PageFree(pFree);
drh43605152004-05-29 21:46:49 +00007329 }
7330 return rc;
7331}
7332
drhf74b8d92002-09-01 23:20:45 +00007333
7334/*
drh3b7511c2001-05-26 13:15:44 +00007335** Insert a new record into the BTree. The key is given by (pKey,nKey)
7336** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00007337** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00007338** is left pointing at a random location.
7339**
7340** For an INTKEY table, only the nKey value of the key is used. pKey is
7341** ignored. For a ZERODATA table, the pData and nData are both ignored.
danielk1977de630352009-05-04 11:42:29 +00007342**
7343** If the seekResult parameter is non-zero, then a successful call to
danielk19773509a652009-07-06 18:56:13 +00007344** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
danielk1977de630352009-05-04 11:42:29 +00007345** been performed. seekResult is the search result returned (a negative
7346** number if pCur points at an entry that is smaller than (pKey, nKey), or
peter.d.reid60ec9142014-09-06 16:39:46 +00007347** a positive value if pCur points at an entry that is larger than
danielk1977de630352009-05-04 11:42:29 +00007348** (pKey, nKey)).
7349**
drh3e9ca092009-09-08 01:14:48 +00007350** If the seekResult parameter is non-zero, then the caller guarantees that
7351** cursor pCur is pointing at the existing copy of a row that is to be
7352** overwritten. If the seekResult parameter is 0, then cursor pCur may
7353** point to any entry or to no entry at all and so this function has to seek
danielk1977de630352009-05-04 11:42:29 +00007354** the cursor before the new key can be inserted.
drh3b7511c2001-05-26 13:15:44 +00007355*/
drh3aac2dd2004-04-26 14:10:20 +00007356int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00007357 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00007358 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00007359 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00007360 int nZero, /* Number of extra 0 bytes to append to data */
danielk1977de630352009-05-04 11:42:29 +00007361 int appendBias, /* True if this is likely an append */
danielk19773509a652009-07-06 18:56:13 +00007362 int seekResult /* Result of prior MovetoUnpacked() call */
drh3b7511c2001-05-26 13:15:44 +00007363){
drh3b7511c2001-05-26 13:15:44 +00007364 int rc;
drh3e9ca092009-09-08 01:14:48 +00007365 int loc = seekResult; /* -1: before desired location +1: after */
drh1d452e12009-11-01 19:26:59 +00007366 int szNew = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00007367 int idx;
drh3b7511c2001-05-26 13:15:44 +00007368 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00007369 Btree *p = pCur->pBtree;
7370 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00007371 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00007372 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00007373
drh98add2e2009-07-20 17:11:49 +00007374 if( pCur->eState==CURSOR_FAULT ){
7375 assert( pCur->skipNext!=SQLITE_OK );
7376 return pCur->skipNext;
7377 }
7378
drh1fee73e2007-08-29 04:00:57 +00007379 assert( cursorHoldsMutex(pCur) );
drh3f387402014-09-24 01:23:00 +00007380 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
7381 && pBt->inTransaction==TRANS_WRITE
drhc9166342012-01-05 23:32:06 +00007382 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk197796d48e92009-06-29 06:00:37 +00007383 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
7384
danielk197731d31b82009-07-13 13:18:07 +00007385 /* Assert that the caller has been consistent. If this cursor was opened
7386 ** expecting an index b-tree, then the caller should be inserting blob
7387 ** keys with no associated data. If the cursor was opened expecting an
7388 ** intkey table, the caller should be inserting integer keys with a
7389 ** blob of associated data. */
7390 assert( (pKey==0)==(pCur->pKeyInfo==0) );
7391
danielk19779c3acf32009-05-02 07:36:49 +00007392 /* Save the positions of any other cursors open on this table.
7393 **
danielk19773509a652009-07-06 18:56:13 +00007394 ** In some cases, the call to btreeMoveto() below is a no-op. For
danielk19779c3acf32009-05-02 07:36:49 +00007395 ** example, when inserting data into a table with auto-generated integer
7396 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
7397 ** integer key to use. It then calls this function to actually insert the
danielk19773509a652009-07-06 18:56:13 +00007398 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
danielk19779c3acf32009-05-02 07:36:49 +00007399 ** that the cursor is already where it needs to be and returns without
7400 ** doing any work. To avoid thwarting these optimizations, it is important
7401 ** not to clear the cursor here.
7402 */
drh4c301aa2009-07-15 17:25:45 +00007403 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
7404 if( rc ) return rc;
drhd60f4f42012-03-23 14:23:52 +00007405
drhd60f4f42012-03-23 14:23:52 +00007406 if( pCur->pKeyInfo==0 ){
drhe0670b62014-02-12 21:31:12 +00007407 /* If this is an insert into a table b-tree, invalidate any incrblob
7408 ** cursors open on the row being replaced */
drhd60f4f42012-03-23 14:23:52 +00007409 invalidateIncrblobCursors(p, nKey, 0);
drhe0670b62014-02-12 21:31:12 +00007410
7411 /* If the cursor is currently on the last row and we are appending a
7412 ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto()
7413 ** call */
drh3f387402014-09-24 01:23:00 +00007414 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
7415 && pCur->info.nKey==nKey-1 ){
drhe0670b62014-02-12 21:31:12 +00007416 loc = -1;
7417 }
drhd60f4f42012-03-23 14:23:52 +00007418 }
7419
drh4c301aa2009-07-15 17:25:45 +00007420 if( !loc ){
7421 rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
7422 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00007423 }
danielk1977b980d2212009-06-22 18:03:51 +00007424 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
danielk1977da184232006-01-05 11:34:32 +00007425
danielk197771d5d2c2008-09-29 11:49:47 +00007426 pPage = pCur->apPage[pCur->iPage];
drh4a1c3802004-05-12 15:15:47 +00007427 assert( pPage->intKey || nKey>=0 );
drh44845222008-07-17 18:39:57 +00007428 assert( pPage->leaf || !pPage->intKey );
danielk19778f880a82009-07-13 09:41:45 +00007429
drh3a4c1412004-05-09 20:40:11 +00007430 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
7431 pCur->pgnoRoot, nKey, nData, pPage->pgno,
7432 loc==0 ? "overwrite" : "new entry"));
danielk197771d5d2c2008-09-29 11:49:47 +00007433 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00007434 newCell = pBt->pTmpSpace;
drh3fbb0222014-09-24 19:47:27 +00007435 assert( newCell!=0 );
drhb026e052007-05-02 01:34:31 +00007436 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00007437 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00007438 assert( szNew==cellSizePtr(pPage, newCell) );
drhfcd71b62011-04-05 22:08:24 +00007439 assert( szNew <= MX_CELL_SIZE(pBt) );
danielk197771d5d2c2008-09-29 11:49:47 +00007440 idx = pCur->aiIdx[pCur->iPage];
danielk1977b980d2212009-06-22 18:03:51 +00007441 if( loc==0 ){
drha9121e42008-02-19 14:59:35 +00007442 u16 szOld;
danielk197771d5d2c2008-09-29 11:49:47 +00007443 assert( idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00007444 rc = sqlite3PagerWrite(pPage->pDbPage);
7445 if( rc ){
7446 goto end_insert;
7447 }
danielk197771d5d2c2008-09-29 11:49:47 +00007448 oldCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00007449 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00007450 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00007451 }
drh9bfdc252014-09-24 02:05:41 +00007452 rc = clearCell(pPage, oldCell, &szOld);
drh98add2e2009-07-20 17:11:49 +00007453 dropCell(pPage, idx, szOld, &rc);
drh2e38c322004-09-03 18:38:44 +00007454 if( rc ) goto end_insert;
drh7c717f72001-06-24 20:39:41 +00007455 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00007456 assert( pPage->leaf );
danielk197771d5d2c2008-09-29 11:49:47 +00007457 idx = ++pCur->aiIdx[pCur->iPage];
drh14acc042001-06-10 19:56:58 +00007458 }else{
drh4b70f112004-05-02 21:12:19 +00007459 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00007460 }
drh98add2e2009-07-20 17:11:49 +00007461 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
danielk19773f632d52009-05-02 10:03:09 +00007462 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
drh9bf9e9c2008-12-05 20:01:43 +00007463
mistachkin48864df2013-03-21 21:20:32 +00007464 /* If no error has occurred and pPage has an overflow cell, call balance()
danielk1977a50d9aa2009-06-08 14:49:45 +00007465 ** to redistribute the cells within the tree. Since balance() may move
drh036dbec2014-03-11 23:40:44 +00007466 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
danielk1977a50d9aa2009-06-08 14:49:45 +00007467 ** variables.
danielk19773f632d52009-05-02 10:03:09 +00007468 **
danielk1977a50d9aa2009-06-08 14:49:45 +00007469 ** Previous versions of SQLite called moveToRoot() to move the cursor
7470 ** back to the root page as balance() used to invalidate the contents
danielk197754109bb2009-06-23 11:22:29 +00007471 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
7472 ** set the cursor state to "invalid". This makes common insert operations
7473 ** slightly faster.
danielk19773f632d52009-05-02 10:03:09 +00007474 **
danielk1977a50d9aa2009-06-08 14:49:45 +00007475 ** There is a subtle but important optimization here too. When inserting
7476 ** multiple records into an intkey b-tree using a single cursor (as can
7477 ** happen while processing an "INSERT INTO ... SELECT" statement), it
7478 ** is advantageous to leave the cursor pointing to the last entry in
7479 ** the b-tree if possible. If the cursor is left pointing to the last
7480 ** entry in the table, and the next row inserted has an integer key
7481 ** larger than the largest existing key, it is possible to insert the
7482 ** row without seeking the cursor. This can be a big performance boost.
danielk19773f632d52009-05-02 10:03:09 +00007483 */
danielk1977a50d9aa2009-06-08 14:49:45 +00007484 pCur->info.nSize = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00007485 if( rc==SQLITE_OK && pPage->nOverflow ){
drh036dbec2014-03-11 23:40:44 +00007486 pCur->curFlags &= ~(BTCF_ValidNKey);
danielk1977a50d9aa2009-06-08 14:49:45 +00007487 rc = balance(pCur);
7488
7489 /* Must make sure nOverflow is reset to zero even if the balance()
danielk197754109bb2009-06-23 11:22:29 +00007490 ** fails. Internal data structure corruption will result otherwise.
7491 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
7492 ** from trying to save the current position of the cursor. */
danielk1977a50d9aa2009-06-08 14:49:45 +00007493 pCur->apPage[pCur->iPage]->nOverflow = 0;
danielk197754109bb2009-06-23 11:22:29 +00007494 pCur->eState = CURSOR_INVALID;
danielk19773f632d52009-05-02 10:03:09 +00007495 }
danielk1977a50d9aa2009-06-08 14:49:45 +00007496 assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
drh9bf9e9c2008-12-05 20:01:43 +00007497
drh2e38c322004-09-03 18:38:44 +00007498end_insert:
drh5e2f8b92001-05-28 00:41:15 +00007499 return rc;
7500}
7501
7502/*
drh4b70f112004-05-02 21:12:19 +00007503** Delete the entry that the cursor is pointing to. The cursor
peter.d.reid60ec9142014-09-06 16:39:46 +00007504** is left pointing at an arbitrary location.
drh3b7511c2001-05-26 13:15:44 +00007505*/
drh3aac2dd2004-04-26 14:10:20 +00007506int sqlite3BtreeDelete(BtCursor *pCur){
drhd677b3d2007-08-20 22:48:41 +00007507 Btree *p = pCur->pBtree;
danielk19774dbaa892009-06-16 16:50:22 +00007508 BtShared *pBt = p->pBt;
7509 int rc; /* Return code */
7510 MemPage *pPage; /* Page to delete cell from */
7511 unsigned char *pCell; /* Pointer to cell to delete */
7512 int iCellIdx; /* Index of cell to delete */
7513 int iCellDepth; /* Depth of node containing pCell */
drh9bfdc252014-09-24 02:05:41 +00007514 u16 szCell; /* Size of the cell being deleted */
drh8b2f49b2001-06-08 00:21:52 +00007515
drh1fee73e2007-08-29 04:00:57 +00007516 assert( cursorHoldsMutex(pCur) );
drh64022502009-01-09 14:11:04 +00007517 assert( pBt->inTransaction==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00007518 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
drh036dbec2014-03-11 23:40:44 +00007519 assert( pCur->curFlags & BTCF_WriteFlag );
danielk197796d48e92009-06-29 06:00:37 +00007520 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
7521 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
7522
danielk19774dbaa892009-06-16 16:50:22 +00007523 if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
7524 || NEVER(pCur->eState!=CURSOR_VALID)
7525 ){
7526 return SQLITE_ERROR; /* Something has gone awry. */
drhf74b8d92002-09-01 23:20:45 +00007527 }
danielk1977da184232006-01-05 11:34:32 +00007528
danielk19774dbaa892009-06-16 16:50:22 +00007529 iCellDepth = pCur->iPage;
7530 iCellIdx = pCur->aiIdx[iCellDepth];
7531 pPage = pCur->apPage[iCellDepth];
7532 pCell = findCell(pPage, iCellIdx);
7533
7534 /* If the page containing the entry to delete is not a leaf page, move
7535 ** the cursor to the largest entry in the tree that is smaller than
7536 ** the entry being deleted. This cell will replace the cell being deleted
7537 ** from the internal node. The 'previous' entry is used for this instead
7538 ** of the 'next' entry, as the previous entry is always a part of the
7539 ** sub-tree headed by the child page of the cell being deleted. This makes
7540 ** balancing the tree following the delete operation easier. */
7541 if( !pPage->leaf ){
drhe39a7322014-02-03 14:04:11 +00007542 int notUsed = 0;
drh4c301aa2009-07-15 17:25:45 +00007543 rc = sqlite3BtreePrevious(pCur, &notUsed);
7544 if( rc ) return rc;
danielk19774dbaa892009-06-16 16:50:22 +00007545 }
7546
7547 /* Save the positions of any other cursors open on this table before
7548 ** making any modifications. Make the page containing the entry to be
7549 ** deleted writable. Then free any overflow pages associated with the
drha4ec1d42009-07-11 13:13:11 +00007550 ** entry and finally remove the cell itself from within the page.
7551 */
7552 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
7553 if( rc ) return rc;
drhd60f4f42012-03-23 14:23:52 +00007554
7555 /* If this is a delete operation to remove a row from a table b-tree,
7556 ** invalidate any incrblob cursors open on the row being deleted. */
7557 if( pCur->pKeyInfo==0 ){
7558 invalidateIncrblobCursors(p, pCur->info.nKey, 0);
7559 }
7560
drha4ec1d42009-07-11 13:13:11 +00007561 rc = sqlite3PagerWrite(pPage->pDbPage);
7562 if( rc ) return rc;
drh9bfdc252014-09-24 02:05:41 +00007563 rc = clearCell(pPage, pCell, &szCell);
7564 dropCell(pPage, iCellIdx, szCell, &rc);
drha4ec1d42009-07-11 13:13:11 +00007565 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00007566
danielk19774dbaa892009-06-16 16:50:22 +00007567 /* If the cell deleted was not located on a leaf page, then the cursor
7568 ** is currently pointing to the largest entry in the sub-tree headed
7569 ** by the child-page of the cell that was just deleted from an internal
7570 ** node. The cell from the leaf node needs to be moved to the internal
7571 ** node to replace the deleted cell. */
drh4b70f112004-05-02 21:12:19 +00007572 if( !pPage->leaf ){
danielk19774dbaa892009-06-16 16:50:22 +00007573 MemPage *pLeaf = pCur->apPage[pCur->iPage];
7574 int nCell;
7575 Pgno n = pCur->apPage[iCellDepth+1]->pgno;
7576 unsigned char *pTmp;
danielk1977e6efa742004-11-10 11:55:10 +00007577
danielk19774dbaa892009-06-16 16:50:22 +00007578 pCell = findCell(pLeaf, pLeaf->nCell-1);
7579 nCell = cellSizePtr(pLeaf, pCell);
drhfcd71b62011-04-05 22:08:24 +00007580 assert( MX_CELL_SIZE(pBt) >= nCell );
danielk19774dbaa892009-06-16 16:50:22 +00007581 pTmp = pBt->pTmpSpace;
drh3fbb0222014-09-24 19:47:27 +00007582 assert( pTmp!=0 );
drha4ec1d42009-07-11 13:13:11 +00007583 rc = sqlite3PagerWrite(pLeaf->pDbPage);
drh98add2e2009-07-20 17:11:49 +00007584 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
7585 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
drha4ec1d42009-07-11 13:13:11 +00007586 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00007587 }
danielk19774dbaa892009-06-16 16:50:22 +00007588
7589 /* Balance the tree. If the entry deleted was located on a leaf page,
7590 ** then the cursor still points to that page. In this case the first
7591 ** call to balance() repairs the tree, and the if(...) condition is
7592 ** never true.
7593 **
7594 ** Otherwise, if the entry deleted was on an internal node page, then
7595 ** pCur is pointing to the leaf page from which a cell was removed to
7596 ** replace the cell deleted from the internal node. This is slightly
7597 ** tricky as the leaf node may be underfull, and the internal node may
7598 ** be either under or overfull. In this case run the balancing algorithm
7599 ** on the leaf node first. If the balance proceeds far enough up the
7600 ** tree that we can be sure that any problem in the internal node has
7601 ** been corrected, so be it. Otherwise, after balancing the leaf node,
7602 ** walk the cursor up the tree to the internal node and balance it as
7603 ** well. */
7604 rc = balance(pCur);
7605 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
7606 while( pCur->iPage>iCellDepth ){
7607 releasePage(pCur->apPage[pCur->iPage--]);
7608 }
7609 rc = balance(pCur);
7610 }
7611
danielk19776b456a22005-03-21 04:04:02 +00007612 if( rc==SQLITE_OK ){
7613 moveToRoot(pCur);
7614 }
drh5e2f8b92001-05-28 00:41:15 +00007615 return rc;
drh3b7511c2001-05-26 13:15:44 +00007616}
drh8b2f49b2001-06-08 00:21:52 +00007617
7618/*
drhc6b52df2002-01-04 03:09:29 +00007619** Create a new BTree table. Write into *piTable the page
7620** number for the root page of the new table.
7621**
drhab01f612004-05-22 02:55:23 +00007622** The type of type is determined by the flags parameter. Only the
7623** following values of flags are currently in use. Other values for
7624** flags might not work:
7625**
7626** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
7627** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00007628*/
drhd4187c72010-08-30 22:15:45 +00007629static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
danielk1977aef0bf62005-12-30 16:28:01 +00007630 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00007631 MemPage *pRoot;
7632 Pgno pgnoRoot;
7633 int rc;
drhd4187c72010-08-30 22:15:45 +00007634 int ptfFlags; /* Page-type flage for the root page of new table */
drhd677b3d2007-08-20 22:48:41 +00007635
drh1fee73e2007-08-29 04:00:57 +00007636 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00007637 assert( pBt->inTransaction==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00007638 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk1977e6efa742004-11-10 11:55:10 +00007639
danielk1977003ba062004-11-04 02:57:33 +00007640#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00007641 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00007642 if( rc ){
7643 return rc;
7644 }
danielk1977003ba062004-11-04 02:57:33 +00007645#else
danielk1977687566d2004-11-02 12:56:41 +00007646 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00007647 Pgno pgnoMove; /* Move a page here to make room for the root-page */
7648 MemPage *pPageMove; /* The page to move to. */
7649
danielk197720713f32007-05-03 11:43:33 +00007650 /* Creating a new table may probably require moving an existing database
7651 ** to make room for the new tables root page. In case this page turns
7652 ** out to be an overflow page, delete all overflow page-map caches
7653 ** held by open cursors.
7654 */
danielk197792d4d7a2007-05-04 12:05:56 +00007655 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00007656
danielk1977003ba062004-11-04 02:57:33 +00007657 /* Read the value of meta[3] from the database to determine where the
7658 ** root page of the new table should go. meta[3] is the largest root-page
7659 ** created so far, so the new root-page is (meta[3]+1).
7660 */
danielk1977602b4662009-07-02 07:47:33 +00007661 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00007662 pgnoRoot++;
7663
danielk1977599fcba2004-11-08 07:13:13 +00007664 /* The new root-page may not be allocated on a pointer-map page, or the
7665 ** PENDING_BYTE page.
7666 */
drh72190432008-01-31 14:54:43 +00007667 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00007668 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00007669 pgnoRoot++;
7670 }
7671 assert( pgnoRoot>=3 );
7672
7673 /* Allocate a page. The page that currently resides at pgnoRoot will
7674 ** be moved to the allocated page (unless the allocated page happens
7675 ** to reside at pgnoRoot).
7676 */
dan51f0b6d2013-02-22 20:16:34 +00007677 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
danielk1977003ba062004-11-04 02:57:33 +00007678 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00007679 return rc;
7680 }
danielk1977003ba062004-11-04 02:57:33 +00007681
7682 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00007683 /* pgnoRoot is the page that will be used for the root-page of
7684 ** the new table (assuming an error did not occur). But we were
7685 ** allocated pgnoMove. If required (i.e. if it was not allocated
7686 ** by extending the file), the current page at position pgnoMove
7687 ** is already journaled.
7688 */
drheeb844a2009-08-08 18:01:07 +00007689 u8 eType = 0;
7690 Pgno iPtrPage = 0;
danielk1977003ba062004-11-04 02:57:33 +00007691
danf7679ad2013-04-03 11:38:36 +00007692 /* Save the positions of any open cursors. This is required in
7693 ** case they are holding a reference to an xFetch reference
7694 ** corresponding to page pgnoRoot. */
7695 rc = saveAllCursors(pBt, 0, 0);
danielk1977003ba062004-11-04 02:57:33 +00007696 releasePage(pPageMove);
danf7679ad2013-04-03 11:38:36 +00007697 if( rc!=SQLITE_OK ){
7698 return rc;
7699 }
danielk1977f35843b2007-04-07 15:03:17 +00007700
7701 /* Move the page currently at pgnoRoot to pgnoMove. */
drhb00fc3b2013-08-21 23:42:32 +00007702 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00007703 if( rc!=SQLITE_OK ){
7704 return rc;
7705 }
7706 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drh27731d72009-06-22 12:05:10 +00007707 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
7708 rc = SQLITE_CORRUPT_BKPT;
7709 }
7710 if( rc!=SQLITE_OK ){
danielk1977003ba062004-11-04 02:57:33 +00007711 releasePage(pRoot);
7712 return rc;
7713 }
drhccae6022005-02-26 17:31:26 +00007714 assert( eType!=PTRMAP_ROOTPAGE );
7715 assert( eType!=PTRMAP_FREEPAGE );
danielk19774c999992008-07-16 18:17:55 +00007716 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +00007717 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00007718
7719 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00007720 if( rc!=SQLITE_OK ){
7721 return rc;
7722 }
drhb00fc3b2013-08-21 23:42:32 +00007723 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00007724 if( rc!=SQLITE_OK ){
7725 return rc;
7726 }
danielk19773b8a05f2007-03-19 17:44:26 +00007727 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00007728 if( rc!=SQLITE_OK ){
7729 releasePage(pRoot);
7730 return rc;
7731 }
7732 }else{
7733 pRoot = pPageMove;
7734 }
7735
danielk197742741be2005-01-08 12:42:39 +00007736 /* Update the pointer-map and meta-data with the new root-page number. */
drh98add2e2009-07-20 17:11:49 +00007737 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
danielk1977003ba062004-11-04 02:57:33 +00007738 if( rc ){
7739 releasePage(pRoot);
7740 return rc;
7741 }
drhbf592832010-03-30 15:51:12 +00007742
7743 /* When the new root page was allocated, page 1 was made writable in
7744 ** order either to increase the database filesize, or to decrement the
7745 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
7746 */
7747 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
danielk1977aef0bf62005-12-30 16:28:01 +00007748 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
drhbf592832010-03-30 15:51:12 +00007749 if( NEVER(rc) ){
danielk1977003ba062004-11-04 02:57:33 +00007750 releasePage(pRoot);
7751 return rc;
7752 }
danielk197742741be2005-01-08 12:42:39 +00007753
danielk1977003ba062004-11-04 02:57:33 +00007754 }else{
drh4f0c5872007-03-26 22:05:01 +00007755 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00007756 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00007757 }
7758#endif
danielk19773b8a05f2007-03-19 17:44:26 +00007759 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhd4187c72010-08-30 22:15:45 +00007760 if( createTabFlags & BTREE_INTKEY ){
7761 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
7762 }else{
7763 ptfFlags = PTF_ZERODATA | PTF_LEAF;
7764 }
7765 zeroPage(pRoot, ptfFlags);
danielk19773b8a05f2007-03-19 17:44:26 +00007766 sqlite3PagerUnref(pRoot->pDbPage);
drhd4187c72010-08-30 22:15:45 +00007767 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
drh8b2f49b2001-06-08 00:21:52 +00007768 *piTable = (int)pgnoRoot;
7769 return SQLITE_OK;
7770}
drhd677b3d2007-08-20 22:48:41 +00007771int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
7772 int rc;
7773 sqlite3BtreeEnter(p);
7774 rc = btreeCreateTable(p, piTable, flags);
7775 sqlite3BtreeLeave(p);
7776 return rc;
7777}
drh8b2f49b2001-06-08 00:21:52 +00007778
7779/*
7780** Erase the given database page and all its children. Return
7781** the page to the freelist.
7782*/
drh4b70f112004-05-02 21:12:19 +00007783static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00007784 BtShared *pBt, /* The BTree that contains the table */
drh7ab641f2009-11-24 02:37:02 +00007785 Pgno pgno, /* Page number to clear */
7786 int freePageFlag, /* Deallocate page if true */
7787 int *pnChange /* Add number of Cells freed to this counter */
drh4b70f112004-05-02 21:12:19 +00007788){
danielk1977146ba992009-07-22 14:08:13 +00007789 MemPage *pPage;
drh8b2f49b2001-06-08 00:21:52 +00007790 int rc;
drh4b70f112004-05-02 21:12:19 +00007791 unsigned char *pCell;
7792 int i;
dan8ce71842014-01-14 20:14:09 +00007793 int hdr;
drh9bfdc252014-09-24 02:05:41 +00007794 u16 szCell;
drh8b2f49b2001-06-08 00:21:52 +00007795
drh1fee73e2007-08-29 04:00:57 +00007796 assert( sqlite3_mutex_held(pBt->mutex) );
drhb1299152010-03-30 22:58:33 +00007797 if( pgno>btreePagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00007798 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00007799 }
7800
dan11dcd112013-03-15 18:29:18 +00007801 rc = getAndInitPage(pBt, pgno, &pPage, 0);
danielk1977146ba992009-07-22 14:08:13 +00007802 if( rc ) return rc;
dan8ce71842014-01-14 20:14:09 +00007803 hdr = pPage->hdrOffset;
drh4b70f112004-05-02 21:12:19 +00007804 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00007805 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00007806 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00007807 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00007808 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00007809 }
drh9bfdc252014-09-24 02:05:41 +00007810 rc = clearCell(pPage, pCell, &szCell);
danielk19776b456a22005-03-21 04:04:02 +00007811 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00007812 }
drha34b6762004-05-07 13:30:42 +00007813 if( !pPage->leaf ){
dan8ce71842014-01-14 20:14:09 +00007814 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00007815 if( rc ) goto cleardatabasepage_out;
danielk1977c7af4842008-10-27 13:59:33 +00007816 }else if( pnChange ){
7817 assert( pPage->intKey );
7818 *pnChange += pPage->nCell;
drh2aa679f2001-06-25 02:11:07 +00007819 }
7820 if( freePageFlag ){
drhc314dc72009-07-21 11:52:34 +00007821 freePage(pPage, &rc);
danielk19773b8a05f2007-03-19 17:44:26 +00007822 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
dan8ce71842014-01-14 20:14:09 +00007823 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00007824 }
danielk19776b456a22005-03-21 04:04:02 +00007825
7826cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00007827 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00007828 return rc;
drh8b2f49b2001-06-08 00:21:52 +00007829}
7830
7831/*
drhab01f612004-05-22 02:55:23 +00007832** Delete all information from a single table in the database. iTable is
7833** the page number of the root of the table. After this routine returns,
7834** the root page is empty, but still exists.
7835**
7836** This routine will fail with SQLITE_LOCKED if there are any open
7837** read cursors on the table. Open write cursors are moved to the
7838** root of the table.
danielk1977c7af4842008-10-27 13:59:33 +00007839**
7840** If pnChange is not NULL, then table iTable must be an intkey table. The
7841** integer value pointed to by pnChange is incremented by the number of
7842** entries in the table.
drh8b2f49b2001-06-08 00:21:52 +00007843*/
danielk1977c7af4842008-10-27 13:59:33 +00007844int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
drh8b2f49b2001-06-08 00:21:52 +00007845 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00007846 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00007847 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00007848 assert( p->inTrans==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +00007849
drhc046e3e2009-07-15 11:26:44 +00007850 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
drhd60f4f42012-03-23 14:23:52 +00007851
drhc046e3e2009-07-15 11:26:44 +00007852 if( SQLITE_OK==rc ){
drhd60f4f42012-03-23 14:23:52 +00007853 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
7854 ** is the root of a table b-tree - if it is not, the following call is
7855 ** a no-op). */
7856 invalidateIncrblobCursors(p, 0, 1);
danielk197762c14b32008-11-19 09:05:26 +00007857 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
drh8b2f49b2001-06-08 00:21:52 +00007858 }
drhd677b3d2007-08-20 22:48:41 +00007859 sqlite3BtreeLeave(p);
7860 return rc;
drh8b2f49b2001-06-08 00:21:52 +00007861}
7862
7863/*
drh079a3072014-03-19 14:10:55 +00007864** Delete all information from the single table that pCur is open on.
7865**
7866** This routine only work for pCur on an ephemeral table.
7867*/
7868int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
7869 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
7870}
7871
7872/*
drh8b2f49b2001-06-08 00:21:52 +00007873** Erase all information in a table and add the root of the table to
7874** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00007875** page 1) is never added to the freelist.
7876**
7877** This routine will fail with SQLITE_LOCKED if there are any open
7878** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00007879**
7880** If AUTOVACUUM is enabled and the page at iTable is not the last
7881** root page in the database file, then the last root page
7882** in the database file is moved into the slot formerly occupied by
7883** iTable and that last slot formerly occupied by the last root page
7884** is added to the freelist instead of iTable. In this say, all
7885** root pages are kept at the beginning of the database file, which
7886** is necessary for AUTOVACUUM to work right. *piMoved is set to the
7887** page number that used to be the last root page in the file before
7888** the move. If no page gets moved, *piMoved is set to 0.
7889** The last root page is recorded in meta[3] and the value of
7890** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00007891*/
danielk197789d40042008-11-17 14:20:56 +00007892static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00007893 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00007894 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00007895 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00007896
drh1fee73e2007-08-29 04:00:57 +00007897 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00007898 assert( p->inTrans==TRANS_WRITE );
danielk1977a0bf2652004-11-04 14:30:04 +00007899
danielk1977e6efa742004-11-10 11:55:10 +00007900 /* It is illegal to drop a table if any cursors are open on the
7901 ** database. This is because in auto-vacuum mode the backend may
7902 ** need to move another root-page to fill a gap left by the deleted
7903 ** root page. If an open cursor was using this page a problem would
7904 ** occur.
drhc046e3e2009-07-15 11:26:44 +00007905 **
7906 ** This error is caught long before control reaches this point.
danielk1977e6efa742004-11-10 11:55:10 +00007907 */
drhc046e3e2009-07-15 11:26:44 +00007908 if( NEVER(pBt->pCursor) ){
danielk1977404ca072009-03-16 13:19:36 +00007909 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
7910 return SQLITE_LOCKED_SHAREDCACHE;
drh5df72a52002-06-06 23:16:05 +00007911 }
danielk1977a0bf2652004-11-04 14:30:04 +00007912
drhb00fc3b2013-08-21 23:42:32 +00007913 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00007914 if( rc ) return rc;
danielk1977c7af4842008-10-27 13:59:33 +00007915 rc = sqlite3BtreeClearTable(p, iTable, 0);
danielk19776b456a22005-03-21 04:04:02 +00007916 if( rc ){
7917 releasePage(pPage);
7918 return rc;
7919 }
danielk1977a0bf2652004-11-04 14:30:04 +00007920
drh205f48e2004-11-05 00:43:11 +00007921 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00007922
drh4b70f112004-05-02 21:12:19 +00007923 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00007924#ifdef SQLITE_OMIT_AUTOVACUUM
drhc314dc72009-07-21 11:52:34 +00007925 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00007926 releasePage(pPage);
7927#else
7928 if( pBt->autoVacuum ){
7929 Pgno maxRootPgno;
danielk1977602b4662009-07-02 07:47:33 +00007930 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00007931
7932 if( iTable==maxRootPgno ){
7933 /* If the table being dropped is the table with the largest root-page
7934 ** number in the database, put the root page on the free list.
7935 */
drhc314dc72009-07-21 11:52:34 +00007936 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00007937 releasePage(pPage);
7938 if( rc!=SQLITE_OK ){
7939 return rc;
7940 }
7941 }else{
7942 /* The table being dropped does not have the largest root-page
7943 ** number in the database. So move the page that does into the
7944 ** gap left by the deleted root-page.
7945 */
7946 MemPage *pMove;
7947 releasePage(pPage);
drhb00fc3b2013-08-21 23:42:32 +00007948 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00007949 if( rc!=SQLITE_OK ){
7950 return rc;
7951 }
danielk19774c999992008-07-16 18:17:55 +00007952 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00007953 releasePage(pMove);
7954 if( rc!=SQLITE_OK ){
7955 return rc;
7956 }
drhfe3313f2009-07-21 19:02:20 +00007957 pMove = 0;
drhb00fc3b2013-08-21 23:42:32 +00007958 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
drhc314dc72009-07-21 11:52:34 +00007959 freePage(pMove, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00007960 releasePage(pMove);
7961 if( rc!=SQLITE_OK ){
7962 return rc;
7963 }
7964 *piMoved = maxRootPgno;
7965 }
7966
danielk1977599fcba2004-11-08 07:13:13 +00007967 /* Set the new 'max-root-page' value in the database header. This
7968 ** is the old value less one, less one more if that happens to
7969 ** be a root-page number, less one again if that is the
7970 ** PENDING_BYTE_PAGE.
7971 */
danielk197787a6e732004-11-05 12:58:25 +00007972 maxRootPgno--;
drhe1849652009-07-15 18:15:22 +00007973 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
7974 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00007975 maxRootPgno--;
7976 }
danielk1977599fcba2004-11-08 07:13:13 +00007977 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
7978
danielk1977aef0bf62005-12-30 16:28:01 +00007979 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00007980 }else{
drhc314dc72009-07-21 11:52:34 +00007981 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00007982 releasePage(pPage);
7983 }
7984#endif
drh2aa679f2001-06-25 02:11:07 +00007985 }else{
drhc046e3e2009-07-15 11:26:44 +00007986 /* If sqlite3BtreeDropTable was called on page 1.
7987 ** This really never should happen except in a corrupt
7988 ** database.
7989 */
drha34b6762004-05-07 13:30:42 +00007990 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00007991 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00007992 }
drh8b2f49b2001-06-08 00:21:52 +00007993 return rc;
7994}
drhd677b3d2007-08-20 22:48:41 +00007995int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
7996 int rc;
7997 sqlite3BtreeEnter(p);
dan7733a4d2011-09-02 18:03:16 +00007998 rc = btreeDropTable(p, iTable, piMoved);
drhd677b3d2007-08-20 22:48:41 +00007999 sqlite3BtreeLeave(p);
8000 return rc;
8001}
drh8b2f49b2001-06-08 00:21:52 +00008002
drh001bbcb2003-03-19 03:14:00 +00008003
drh8b2f49b2001-06-08 00:21:52 +00008004/*
danielk1977602b4662009-07-02 07:47:33 +00008005** This function may only be called if the b-tree connection already
8006** has a read or write transaction open on the database.
8007**
drh23e11ca2004-05-04 17:27:28 +00008008** Read the meta-information out of a database file. Meta[0]
8009** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00008010** through meta[15] are available for use by higher layers. Meta[0]
8011** is read-only, the others are read/write.
8012**
8013** The schema layer numbers meta values differently. At the schema
8014** layer (and the SetCookie and ReadCookie opcodes) the number of
8015** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00008016*/
danielk1977602b4662009-07-02 07:47:33 +00008017void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
danielk1977aef0bf62005-12-30 16:28:01 +00008018 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00008019
drhd677b3d2007-08-20 22:48:41 +00008020 sqlite3BtreeEnter(p);
danielk1977602b4662009-07-02 07:47:33 +00008021 assert( p->inTrans>TRANS_NONE );
danielk1977e0d9e6f2009-07-03 16:25:06 +00008022 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
danielk1977602b4662009-07-02 07:47:33 +00008023 assert( pBt->pPage1 );
drh23e11ca2004-05-04 17:27:28 +00008024 assert( idx>=0 && idx<=15 );
danielk1977ea897302008-09-19 15:10:58 +00008025
danielk1977602b4662009-07-02 07:47:33 +00008026 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
drhae157872004-08-14 19:20:09 +00008027
danielk1977602b4662009-07-02 07:47:33 +00008028 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
8029 ** database, mark the database as read-only. */
danielk1977003ba062004-11-04 02:57:33 +00008030#ifdef SQLITE_OMIT_AUTOVACUUM
drhc9166342012-01-05 23:32:06 +00008031 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
8032 pBt->btsFlags |= BTS_READ_ONLY;
8033 }
danielk1977003ba062004-11-04 02:57:33 +00008034#endif
drhae157872004-08-14 19:20:09 +00008035
drhd677b3d2007-08-20 22:48:41 +00008036 sqlite3BtreeLeave(p);
drh8b2f49b2001-06-08 00:21:52 +00008037}
8038
8039/*
drh23e11ca2004-05-04 17:27:28 +00008040** Write meta-information back into the database. Meta[0] is
8041** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00008042*/
danielk1977aef0bf62005-12-30 16:28:01 +00008043int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
8044 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00008045 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00008046 int rc;
drh23e11ca2004-05-04 17:27:28 +00008047 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00008048 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00008049 assert( p->inTrans==TRANS_WRITE );
8050 assert( pBt->pPage1!=0 );
8051 pP1 = pBt->pPage1->aData;
8052 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
8053 if( rc==SQLITE_OK ){
8054 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00008055#ifndef SQLITE_OMIT_AUTOVACUUM
danielk19770d19f7a2009-06-03 11:25:07 +00008056 if( idx==BTREE_INCR_VACUUM ){
drh64022502009-01-09 14:11:04 +00008057 assert( pBt->autoVacuum || iMeta==0 );
8058 assert( iMeta==0 || iMeta==1 );
8059 pBt->incrVacuum = (u8)iMeta;
drhd677b3d2007-08-20 22:48:41 +00008060 }
drh64022502009-01-09 14:11:04 +00008061#endif
drh5df72a52002-06-06 23:16:05 +00008062 }
drhd677b3d2007-08-20 22:48:41 +00008063 sqlite3BtreeLeave(p);
8064 return rc;
drh8b2f49b2001-06-08 00:21:52 +00008065}
drh8c42ca92001-06-22 19:15:00 +00008066
danielk1977a5533162009-02-24 10:01:51 +00008067#ifndef SQLITE_OMIT_BTREECOUNT
8068/*
8069** The first argument, pCur, is a cursor opened on some b-tree. Count the
8070** number of entries in the b-tree and write the result to *pnEntry.
8071**
8072** SQLITE_OK is returned if the operation is successfully executed.
8073** Otherwise, if an error is encountered (i.e. an IO error or database
8074** corruption) an SQLite error code is returned.
8075*/
8076int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
8077 i64 nEntry = 0; /* Value to return in *pnEntry */
8078 int rc; /* Return code */
dana205a482011-08-27 18:48:57 +00008079
8080 if( pCur->pgnoRoot==0 ){
8081 *pnEntry = 0;
8082 return SQLITE_OK;
8083 }
danielk1977a5533162009-02-24 10:01:51 +00008084 rc = moveToRoot(pCur);
8085
8086 /* Unless an error occurs, the following loop runs one iteration for each
8087 ** page in the B-Tree structure (not including overflow pages).
8088 */
8089 while( rc==SQLITE_OK ){
8090 int iIdx; /* Index of child node in parent */
8091 MemPage *pPage; /* Current page of the b-tree */
8092
8093 /* If this is a leaf page or the tree is not an int-key tree, then
8094 ** this page contains countable entries. Increment the entry counter
8095 ** accordingly.
8096 */
8097 pPage = pCur->apPage[pCur->iPage];
8098 if( pPage->leaf || !pPage->intKey ){
8099 nEntry += pPage->nCell;
8100 }
8101
8102 /* pPage is a leaf node. This loop navigates the cursor so that it
8103 ** points to the first interior cell that it points to the parent of
8104 ** the next page in the tree that has not yet been visited. The
8105 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
8106 ** of the page, or to the number of cells in the page if the next page
8107 ** to visit is the right-child of its parent.
8108 **
8109 ** If all pages in the tree have been visited, return SQLITE_OK to the
8110 ** caller.
8111 */
8112 if( pPage->leaf ){
8113 do {
8114 if( pCur->iPage==0 ){
8115 /* All pages of the b-tree have been visited. Return successfully. */
8116 *pnEntry = nEntry;
8117 return SQLITE_OK;
8118 }
danielk197730548662009-07-09 05:07:37 +00008119 moveToParent(pCur);
danielk1977a5533162009-02-24 10:01:51 +00008120 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
8121
8122 pCur->aiIdx[pCur->iPage]++;
8123 pPage = pCur->apPage[pCur->iPage];
8124 }
8125
8126 /* Descend to the child node of the cell that the cursor currently
8127 ** points at. This is the right-child if (iIdx==pPage->nCell).
8128 */
8129 iIdx = pCur->aiIdx[pCur->iPage];
8130 if( iIdx==pPage->nCell ){
8131 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
8132 }else{
8133 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
8134 }
8135 }
8136
shanebe217792009-03-05 04:20:31 +00008137 /* An error has occurred. Return an error code. */
danielk1977a5533162009-02-24 10:01:51 +00008138 return rc;
8139}
8140#endif
drhdd793422001-06-28 01:54:48 +00008141
drhdd793422001-06-28 01:54:48 +00008142/*
drh5eddca62001-06-30 21:53:53 +00008143** Return the pager associated with a BTree. This routine is used for
8144** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00008145*/
danielk1977aef0bf62005-12-30 16:28:01 +00008146Pager *sqlite3BtreePager(Btree *p){
8147 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00008148}
drh5eddca62001-06-30 21:53:53 +00008149
drhb7f91642004-10-31 02:22:47 +00008150#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00008151/*
8152** Append a message to the error message string.
8153*/
drh2e38c322004-09-03 18:38:44 +00008154static void checkAppendMsg(
8155 IntegrityCk *pCheck,
drh2e38c322004-09-03 18:38:44 +00008156 const char *zFormat,
8157 ...
8158){
8159 va_list ap;
drh867db832014-09-26 02:41:05 +00008160 char zBuf[200];
drh1dcdbc02007-01-27 02:24:54 +00008161 if( !pCheck->mxErr ) return;
8162 pCheck->mxErr--;
8163 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00008164 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +00008165 if( pCheck->errMsg.nChar ){
8166 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +00008167 }
drh867db832014-09-26 02:41:05 +00008168 if( pCheck->zPfx ){
8169 sqlite3_snprintf(sizeof(zBuf), zBuf, pCheck->zPfx, pCheck->v1, pCheck->v2);
8170 sqlite3StrAccumAppendAll(&pCheck->errMsg, zBuf);
drhf089aa42008-07-08 19:34:06 +00008171 }
8172 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
8173 va_end(ap);
drhb49bc862013-08-21 21:12:10 +00008174 if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
drhc890fec2008-08-01 20:10:08 +00008175 pCheck->mallocFailed = 1;
8176 }
drh5eddca62001-06-30 21:53:53 +00008177}
drhb7f91642004-10-31 02:22:47 +00008178#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00008179
drhb7f91642004-10-31 02:22:47 +00008180#ifndef SQLITE_OMIT_INTEGRITY_CHECK
dan1235bb12012-04-03 17:43:28 +00008181
8182/*
8183** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
8184** corresponds to page iPg is already set.
8185*/
8186static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
8187 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
8188 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
8189}
8190
8191/*
8192** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
8193*/
8194static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
8195 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
8196 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
8197}
8198
8199
drh5eddca62001-06-30 21:53:53 +00008200/*
8201** Add 1 to the reference count for page iPage. If this is the second
8202** reference to the page, add an error message to pCheck->zErrMsg.
peter.d.reid60ec9142014-09-06 16:39:46 +00008203** Return 1 if there are 2 or more references to the page and 0 if
drh5eddca62001-06-30 21:53:53 +00008204** if this is the first reference to the page.
8205**
8206** Also check that the page number is in bounds.
8207*/
drh867db832014-09-26 02:41:05 +00008208static int checkRef(IntegrityCk *pCheck, Pgno iPage){
drh5eddca62001-06-30 21:53:53 +00008209 if( iPage==0 ) return 1;
danielk197789d40042008-11-17 14:20:56 +00008210 if( iPage>pCheck->nPage ){
drh867db832014-09-26 02:41:05 +00008211 checkAppendMsg(pCheck, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00008212 return 1;
8213 }
dan1235bb12012-04-03 17:43:28 +00008214 if( getPageReferenced(pCheck, iPage) ){
drh867db832014-09-26 02:41:05 +00008215 checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00008216 return 1;
8217 }
dan1235bb12012-04-03 17:43:28 +00008218 setPageReferenced(pCheck, iPage);
8219 return 0;
drh5eddca62001-06-30 21:53:53 +00008220}
8221
danielk1977afcdd022004-10-31 16:25:42 +00008222#ifndef SQLITE_OMIT_AUTOVACUUM
8223/*
8224** Check that the entry in the pointer-map for page iChild maps to
8225** page iParent, pointer type ptrType. If not, append an error message
8226** to pCheck.
8227*/
8228static void checkPtrmap(
8229 IntegrityCk *pCheck, /* Integrity check context */
8230 Pgno iChild, /* Child page number */
8231 u8 eType, /* Expected pointer map type */
drh867db832014-09-26 02:41:05 +00008232 Pgno iParent /* Expected pointer map parent page number */
danielk1977afcdd022004-10-31 16:25:42 +00008233){
8234 int rc;
8235 u8 ePtrmapType;
8236 Pgno iPtrmapParent;
8237
8238 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
8239 if( rc!=SQLITE_OK ){
drhb56cd552009-05-01 13:16:54 +00008240 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
drh867db832014-09-26 02:41:05 +00008241 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
danielk1977afcdd022004-10-31 16:25:42 +00008242 return;
8243 }
8244
8245 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
drh867db832014-09-26 02:41:05 +00008246 checkAppendMsg(pCheck,
danielk1977afcdd022004-10-31 16:25:42 +00008247 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
8248 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
8249 }
8250}
8251#endif
8252
drh5eddca62001-06-30 21:53:53 +00008253/*
8254** Check the integrity of the freelist or of an overflow page list.
8255** Verify that the number of pages on the list is N.
8256*/
drh30e58752002-03-02 20:41:57 +00008257static void checkList(
8258 IntegrityCk *pCheck, /* Integrity checking context */
8259 int isFreeList, /* True for a freelist. False for overflow page list */
8260 int iPage, /* Page number for first page in the list */
drh867db832014-09-26 02:41:05 +00008261 int N /* Expected number of pages in the list */
drh30e58752002-03-02 20:41:57 +00008262){
8263 int i;
drh3a4c1412004-05-09 20:40:11 +00008264 int expected = N;
8265 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00008266 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00008267 DbPage *pOvflPage;
8268 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00008269 if( iPage<1 ){
drh867db832014-09-26 02:41:05 +00008270 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00008271 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00008272 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00008273 break;
8274 }
drh867db832014-09-26 02:41:05 +00008275 if( checkRef(pCheck, iPage) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00008276 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh867db832014-09-26 02:41:05 +00008277 checkAppendMsg(pCheck, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00008278 break;
8279 }
danielk19773b8a05f2007-03-19 17:44:26 +00008280 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00008281 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00008282 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00008283#ifndef SQLITE_OMIT_AUTOVACUUM
8284 if( pCheck->pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00008285 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +00008286 }
8287#endif
drh43b18e12010-08-17 19:40:08 +00008288 if( n>(int)pCheck->pBt->usableSize/4-2 ){
drh867db832014-09-26 02:41:05 +00008289 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00008290 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00008291 N--;
8292 }else{
8293 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00008294 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00008295#ifndef SQLITE_OMIT_AUTOVACUUM
8296 if( pCheck->pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00008297 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +00008298 }
8299#endif
drh867db832014-09-26 02:41:05 +00008300 checkRef(pCheck, iFreePage);
drhee696e22004-08-30 16:52:17 +00008301 }
8302 N -= n;
drh30e58752002-03-02 20:41:57 +00008303 }
drh30e58752002-03-02 20:41:57 +00008304 }
danielk1977afcdd022004-10-31 16:25:42 +00008305#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00008306 else{
8307 /* If this database supports auto-vacuum and iPage is not the last
8308 ** page in this overflow list, check that the pointer-map entry for
8309 ** the following page matches iPage.
8310 */
8311 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00008312 i = get4byte(pOvflData);
drh867db832014-09-26 02:41:05 +00008313 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
danielk1977687566d2004-11-02 12:56:41 +00008314 }
danielk1977afcdd022004-10-31 16:25:42 +00008315 }
8316#endif
danielk19773b8a05f2007-03-19 17:44:26 +00008317 iPage = get4byte(pOvflData);
8318 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00008319 }
8320}
drhb7f91642004-10-31 02:22:47 +00008321#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00008322
drhb7f91642004-10-31 02:22:47 +00008323#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00008324/*
8325** Do various sanity checks on a single page of a tree. Return
8326** the tree depth. Root pages return 0. Parents of root pages
8327** return 1, and so forth.
8328**
8329** These checks are done:
8330**
8331** 1. Make sure that cells and freeblocks do not overlap
8332** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00008333** NO 2. Make sure cell keys are in order.
8334** NO 3. Make sure no key is less than or equal to zLowerBound.
8335** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00008336** 5. Check the integrity of overflow pages.
8337** 6. Recursively call checkTreePage on all children.
8338** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00008339** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00008340** the root of the tree.
8341*/
8342static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00008343 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00008344 int iPage, /* Page number of the page to check */
shaneh195475d2010-02-19 04:28:08 +00008345 i64 *pnParentMinKey,
8346 i64 *pnParentMaxKey
drh5eddca62001-06-30 21:53:53 +00008347){
8348 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00008349 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00008350 int hdr, cellStart;
8351 int nCell;
drhda200cc2004-05-09 11:51:38 +00008352 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00008353 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00008354 int usableSize;
shane0af3f892008-11-12 04:55:34 +00008355 char *hit = 0;
shaneh195475d2010-02-19 04:28:08 +00008356 i64 nMinKey = 0;
8357 i64 nMaxKey = 0;
drh867db832014-09-26 02:41:05 +00008358 const char *saved_zPfx = pCheck->zPfx;
8359 int saved_v1 = pCheck->v1;
8360 int saved_v2 = pCheck->v2;
danielk1977ef73ee92004-11-06 12:26:07 +00008361
drh5eddca62001-06-30 21:53:53 +00008362 /* Check that the page exists
8363 */
drhd9cb6ac2005-10-20 07:28:17 +00008364 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00008365 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00008366 if( iPage==0 ) return 0;
drh867db832014-09-26 02:41:05 +00008367 if( checkRef(pCheck, iPage) ) return 0;
8368 pCheck->zPfx = "Page %d: ";
8369 pCheck->v1 = iPage;
drhb00fc3b2013-08-21 23:42:32 +00008370 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drh867db832014-09-26 02:41:05 +00008371 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00008372 "unable to get the page. error code=%d", rc);
drh867db832014-09-26 02:41:05 +00008373 depth = -1;
8374 goto end_of_check;
drh5eddca62001-06-30 21:53:53 +00008375 }
danielk197793caf5a2009-07-11 06:55:33 +00008376
8377 /* Clear MemPage.isInit to make sure the corruption detection code in
8378 ** btreeInitPage() is executed. */
8379 pPage->isInit = 0;
danielk197730548662009-07-09 05:07:37 +00008380 if( (rc = btreeInitPage(pPage))!=0 ){
drh64022502009-01-09 14:11:04 +00008381 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
drh867db832014-09-26 02:41:05 +00008382 checkAppendMsg(pCheck,
danielk197730548662009-07-09 05:07:37 +00008383 "btreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00008384 releasePage(pPage);
drh867db832014-09-26 02:41:05 +00008385 depth = -1;
8386 goto end_of_check;
drh5eddca62001-06-30 21:53:53 +00008387 }
8388
8389 /* Check out all the cells.
8390 */
8391 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00008392 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00008393 u8 *pCell;
danielk197789d40042008-11-17 14:20:56 +00008394 u32 sz;
drh6f11bef2004-05-13 01:12:56 +00008395 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00008396
8397 /* Check payload overflow pages
8398 */
drh867db832014-09-26 02:41:05 +00008399 pCheck->zPfx = "On tree page %d cell %d: ";
8400 pCheck->v1 = iPage;
8401 pCheck->v2 = i;
danielk19771cc5ed82007-05-16 17:28:43 +00008402 pCell = findCell(pPage,i);
danielk197730548662009-07-09 05:07:37 +00008403 btreeParseCellPtr(pPage, pCell, &info);
drhab1cc582014-09-23 21:25:19 +00008404 sz = info.nPayload;
shaneh195475d2010-02-19 04:28:08 +00008405 /* For intKey pages, check that the keys are in order.
8406 */
drhab1cc582014-09-23 21:25:19 +00008407 if( pPage->intKey ){
8408 if( i==0 ){
8409 nMinKey = nMaxKey = info.nKey;
8410 }else if( info.nKey <= nMaxKey ){
drh867db832014-09-26 02:41:05 +00008411 checkAppendMsg(pCheck,
drhab1cc582014-09-23 21:25:19 +00008412 "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
shaneh195475d2010-02-19 04:28:08 +00008413 }
8414 nMaxKey = info.nKey;
8415 }
danielk19775be31f52009-03-30 13:53:43 +00008416 if( (sz>info.nLocal)
8417 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
8418 ){
drhb6f41482004-05-14 01:58:11 +00008419 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00008420 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
8421#ifndef SQLITE_OMIT_AUTOVACUUM
8422 if( pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00008423 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
danielk1977afcdd022004-10-31 16:25:42 +00008424 }
8425#endif
drh867db832014-09-26 02:41:05 +00008426 checkList(pCheck, 0, pgnoOvfl, nPage);
drh5eddca62001-06-30 21:53:53 +00008427 }
8428
8429 /* Check sanity of left child page.
8430 */
drhda200cc2004-05-09 11:51:38 +00008431 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00008432 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00008433#ifndef SQLITE_OMIT_AUTOVACUUM
8434 if( pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00008435 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
danielk1977afcdd022004-10-31 16:25:42 +00008436 }
8437#endif
drh867db832014-09-26 02:41:05 +00008438 d2 = checkTreePage(pCheck, pgno, &nMinKey, i==0?NULL:&nMaxKey);
drhda200cc2004-05-09 11:51:38 +00008439 if( i>0 && d2!=depth ){
drh867db832014-09-26 02:41:05 +00008440 checkAppendMsg(pCheck, "Child page depth differs");
drhda200cc2004-05-09 11:51:38 +00008441 }
8442 depth = d2;
drh5eddca62001-06-30 21:53:53 +00008443 }
drh5eddca62001-06-30 21:53:53 +00008444 }
shaneh195475d2010-02-19 04:28:08 +00008445
drhda200cc2004-05-09 11:51:38 +00008446 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00008447 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh867db832014-09-26 02:41:05 +00008448 pCheck->zPfx = "On page %d at right child: ";
8449 pCheck->v1 = iPage;
danielk1977afcdd022004-10-31 16:25:42 +00008450#ifndef SQLITE_OMIT_AUTOVACUUM
8451 if( pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00008452 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
danielk1977afcdd022004-10-31 16:25:42 +00008453 }
8454#endif
drh867db832014-09-26 02:41:05 +00008455 checkTreePage(pCheck, pgno, NULL, !pPage->nCell?NULL:&nMaxKey);
drhda200cc2004-05-09 11:51:38 +00008456 }
drh5eddca62001-06-30 21:53:53 +00008457
shaneh195475d2010-02-19 04:28:08 +00008458 /* For intKey leaf pages, check that the min/max keys are in order
8459 ** with any left/parent/right pages.
8460 */
drh867db832014-09-26 02:41:05 +00008461 pCheck->zPfx = "Page %d: ";
8462 pCheck->v1 = iPage;
shaneh195475d2010-02-19 04:28:08 +00008463 if( pPage->leaf && pPage->intKey ){
8464 /* if we are a left child page */
8465 if( pnParentMinKey ){
8466 /* if we are the left most child page */
8467 if( !pnParentMaxKey ){
8468 if( nMaxKey > *pnParentMinKey ){
drh867db832014-09-26 02:41:05 +00008469 checkAppendMsg(pCheck,
shaneh195475d2010-02-19 04:28:08 +00008470 "Rowid %lld out of order (max larger than parent min of %lld)",
8471 nMaxKey, *pnParentMinKey);
8472 }
8473 }else{
8474 if( nMinKey <= *pnParentMinKey ){
drh867db832014-09-26 02:41:05 +00008475 checkAppendMsg(pCheck,
shaneh195475d2010-02-19 04:28:08 +00008476 "Rowid %lld out of order (min less than parent min of %lld)",
8477 nMinKey, *pnParentMinKey);
8478 }
8479 if( nMaxKey > *pnParentMaxKey ){
drh867db832014-09-26 02:41:05 +00008480 checkAppendMsg(pCheck,
shaneh195475d2010-02-19 04:28:08 +00008481 "Rowid %lld out of order (max larger than parent max of %lld)",
8482 nMaxKey, *pnParentMaxKey);
8483 }
8484 *pnParentMinKey = nMaxKey;
8485 }
8486 /* else if we're a right child page */
8487 } else if( pnParentMaxKey ){
8488 if( nMinKey <= *pnParentMaxKey ){
drh867db832014-09-26 02:41:05 +00008489 checkAppendMsg(pCheck,
shaneh195475d2010-02-19 04:28:08 +00008490 "Rowid %lld out of order (min less than parent max of %lld)",
8491 nMinKey, *pnParentMaxKey);
8492 }
8493 }
8494 }
8495
drh5eddca62001-06-30 21:53:53 +00008496 /* Check for complete coverage of the page
8497 */
drhda200cc2004-05-09 11:51:38 +00008498 data = pPage->aData;
8499 hdr = pPage->hdrOffset;
drhf7141992008-06-19 00:16:08 +00008500 hit = sqlite3PageMalloc( pBt->pageSize );
drh867db832014-09-26 02:41:05 +00008501 pCheck->zPfx = 0;
drhc890fec2008-08-01 20:10:08 +00008502 if( hit==0 ){
8503 pCheck->mallocFailed = 1;
8504 }else{
drh5d433ce2010-08-14 16:02:52 +00008505 int contentOffset = get2byteNotZero(&data[hdr+5]);
drhd7c7ecd2009-07-14 17:48:06 +00008506 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
shane5780ebd2008-11-11 17:36:30 +00008507 memset(hit+contentOffset, 0, usableSize-contentOffset);
8508 memset(hit, 1, contentOffset);
drh2e38c322004-09-03 18:38:44 +00008509 nCell = get2byte(&data[hdr+3]);
8510 cellStart = hdr + 12 - 4*pPage->leaf;
8511 for(i=0; i<nCell; i++){
8512 int pc = get2byte(&data[cellStart+i*2]);
drh9b78f792010-08-14 21:21:24 +00008513 u32 size = 65536;
drh2e38c322004-09-03 18:38:44 +00008514 int j;
drh8c2bbb62009-07-10 02:52:20 +00008515 if( pc<=usableSize-4 ){
danielk1977daca5432008-08-25 11:57:16 +00008516 size = cellSizePtr(pPage, &data[pc]);
8517 }
drh43b18e12010-08-17 19:40:08 +00008518 if( (int)(pc+size-1)>=usableSize ){
drh867db832014-09-26 02:41:05 +00008519 pCheck->zPfx = 0;
8520 checkAppendMsg(pCheck,
shaneh195475d2010-02-19 04:28:08 +00008521 "Corruption detected in cell %d on page %d",i,iPage);
danielk19777701e812005-01-10 12:59:51 +00008522 }else{
8523 for(j=pc+size-1; j>=pc; j--) hit[j]++;
8524 }
drh2e38c322004-09-03 18:38:44 +00008525 }
drh8c2bbb62009-07-10 02:52:20 +00008526 i = get2byte(&data[hdr+1]);
8527 while( i>0 ){
8528 int size, j;
8529 assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
8530 size = get2byte(&data[i+2]);
8531 assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
8532 for(j=i+size-1; j>=i; j--) hit[j]++;
8533 j = get2byte(&data[i]);
8534 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
8535 assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
8536 i = j;
drh2e38c322004-09-03 18:38:44 +00008537 }
8538 for(i=cnt=0; i<usableSize; i++){
8539 if( hit[i]==0 ){
8540 cnt++;
8541 }else if( hit[i]>1 ){
drh867db832014-09-26 02:41:05 +00008542 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00008543 "Multiple uses for byte %d of page %d", i, iPage);
8544 break;
8545 }
8546 }
8547 if( cnt!=data[hdr+7] ){
drh867db832014-09-26 02:41:05 +00008548 checkAppendMsg(pCheck,
drh8c2bbb62009-07-10 02:52:20 +00008549 "Fragmentation of %d bytes reported as %d on page %d",
drh2e38c322004-09-03 18:38:44 +00008550 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00008551 }
8552 }
drh8c2bbb62009-07-10 02:52:20 +00008553 sqlite3PageFree(hit);
drh4b70f112004-05-02 21:12:19 +00008554 releasePage(pPage);
drh867db832014-09-26 02:41:05 +00008555
8556end_of_check:
8557 pCheck->zPfx = saved_zPfx;
8558 pCheck->v1 = saved_v1;
8559 pCheck->v2 = saved_v2;
drhda200cc2004-05-09 11:51:38 +00008560 return depth+1;
drh5eddca62001-06-30 21:53:53 +00008561}
drhb7f91642004-10-31 02:22:47 +00008562#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00008563
drhb7f91642004-10-31 02:22:47 +00008564#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00008565/*
8566** This routine does a complete check of the given BTree file. aRoot[] is
8567** an array of pages numbers were each page number is the root page of
8568** a table. nRoot is the number of entries in aRoot.
8569**
danielk19773509a652009-07-06 18:56:13 +00008570** A read-only or read-write transaction must be opened before calling
8571** this function.
8572**
drhc890fec2008-08-01 20:10:08 +00008573** Write the number of error seen in *pnErr. Except for some memory
drhe43ba702008-12-05 22:40:08 +00008574** allocation errors, an error message held in memory obtained from
drhc890fec2008-08-01 20:10:08 +00008575** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
drhe43ba702008-12-05 22:40:08 +00008576** returned. If a memory allocation error occurs, NULL is returned.
drh5eddca62001-06-30 21:53:53 +00008577*/
drh1dcdbc02007-01-27 02:24:54 +00008578char *sqlite3BtreeIntegrityCheck(
8579 Btree *p, /* The btree to be checked */
8580 int *aRoot, /* An array of root pages numbers for individual trees */
8581 int nRoot, /* Number of entries in aRoot[] */
8582 int mxErr, /* Stop reporting errors after this many */
8583 int *pnErr /* Write number of errors seen to this variable */
8584){
danielk197789d40042008-11-17 14:20:56 +00008585 Pgno i;
drh5eddca62001-06-30 21:53:53 +00008586 int nRef;
drhaaab5722002-02-19 13:39:21 +00008587 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00008588 BtShared *pBt = p->pBt;
drhf089aa42008-07-08 19:34:06 +00008589 char zErr[100];
drh5eddca62001-06-30 21:53:53 +00008590
drhd677b3d2007-08-20 22:48:41 +00008591 sqlite3BtreeEnter(p);
danielk19773509a652009-07-06 18:56:13 +00008592 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
danielk19773b8a05f2007-03-19 17:44:26 +00008593 nRef = sqlite3PagerRefcount(pBt->pPager);
drh5eddca62001-06-30 21:53:53 +00008594 sCheck.pBt = pBt;
8595 sCheck.pPager = pBt->pPager;
drhb1299152010-03-30 22:58:33 +00008596 sCheck.nPage = btreePagecount(sCheck.pBt);
drh1dcdbc02007-01-27 02:24:54 +00008597 sCheck.mxErr = mxErr;
8598 sCheck.nErr = 0;
drhc890fec2008-08-01 20:10:08 +00008599 sCheck.mallocFailed = 0;
drh867db832014-09-26 02:41:05 +00008600 sCheck.zPfx = 0;
8601 sCheck.v1 = 0;
8602 sCheck.v2 = 0;
drh1dcdbc02007-01-27 02:24:54 +00008603 *pnErr = 0;
drh0de8c112002-07-06 16:32:14 +00008604 if( sCheck.nPage==0 ){
drhd677b3d2007-08-20 22:48:41 +00008605 sqlite3BtreeLeave(p);
drh0de8c112002-07-06 16:32:14 +00008606 return 0;
8607 }
dan1235bb12012-04-03 17:43:28 +00008608
8609 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
8610 if( !sCheck.aPgRef ){
drh1dcdbc02007-01-27 02:24:54 +00008611 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00008612 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00008613 return 0;
danielk1977ac245ec2005-01-14 13:50:11 +00008614 }
drh42cac6d2004-11-20 20:31:11 +00008615 i = PENDING_BYTE_PAGE(pBt);
dan1235bb12012-04-03 17:43:28 +00008616 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
drh32055c22012-12-12 14:30:03 +00008617 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
drhb9755982010-07-24 16:34:37 +00008618 sCheck.errMsg.useMalloc = 2;
drh5eddca62001-06-30 21:53:53 +00008619
8620 /* Check the integrity of the freelist
8621 */
drh867db832014-09-26 02:41:05 +00008622 sCheck.zPfx = "Main freelist: ";
drha34b6762004-05-07 13:30:42 +00008623 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
drh867db832014-09-26 02:41:05 +00008624 get4byte(&pBt->pPage1->aData[36]));
8625 sCheck.zPfx = 0;
drh5eddca62001-06-30 21:53:53 +00008626
8627 /* Check all the tables.
8628 */
danielk197789d40042008-11-17 14:20:56 +00008629 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00008630 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00008631#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00008632 if( pBt->autoVacuum && aRoot[i]>1 ){
drh867db832014-09-26 02:41:05 +00008633 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +00008634 }
8635#endif
drh867db832014-09-26 02:41:05 +00008636 sCheck.zPfx = "List of tree roots: ";
8637 checkTreePage(&sCheck, aRoot[i], NULL, NULL);
8638 sCheck.zPfx = 0;
drh5eddca62001-06-30 21:53:53 +00008639 }
8640
8641 /* Make sure every page in the file is referenced
8642 */
drh1dcdbc02007-01-27 02:24:54 +00008643 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00008644#ifdef SQLITE_OMIT_AUTOVACUUM
dan1235bb12012-04-03 17:43:28 +00008645 if( getPageReferenced(&sCheck, i)==0 ){
drh867db832014-09-26 02:41:05 +00008646 checkAppendMsg(&sCheck, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00008647 }
danielk1977afcdd022004-10-31 16:25:42 +00008648#else
8649 /* If the database supports auto-vacuum, make sure no tables contain
8650 ** references to pointer-map pages.
8651 */
dan1235bb12012-04-03 17:43:28 +00008652 if( getPageReferenced(&sCheck, i)==0 &&
danielk1977266664d2006-02-10 08:24:21 +00008653 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
drh867db832014-09-26 02:41:05 +00008654 checkAppendMsg(&sCheck, "Page %d is never used", i);
danielk1977afcdd022004-10-31 16:25:42 +00008655 }
dan1235bb12012-04-03 17:43:28 +00008656 if( getPageReferenced(&sCheck, i)!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00008657 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
drh867db832014-09-26 02:41:05 +00008658 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
danielk1977afcdd022004-10-31 16:25:42 +00008659 }
8660#endif
drh5eddca62001-06-30 21:53:53 +00008661 }
8662
drh64022502009-01-09 14:11:04 +00008663 /* Make sure this analysis did not leave any unref() pages.
8664 ** This is an internal consistency check; an integrity check
8665 ** of the integrity check.
drh5eddca62001-06-30 21:53:53 +00008666 */
drh64022502009-01-09 14:11:04 +00008667 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
drh867db832014-09-26 02:41:05 +00008668 checkAppendMsg(&sCheck,
drh5eddca62001-06-30 21:53:53 +00008669 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00008670 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00008671 );
drh5eddca62001-06-30 21:53:53 +00008672 }
8673
8674 /* Clean up and report errors.
8675 */
drhd677b3d2007-08-20 22:48:41 +00008676 sqlite3BtreeLeave(p);
dan1235bb12012-04-03 17:43:28 +00008677 sqlite3_free(sCheck.aPgRef);
drhc890fec2008-08-01 20:10:08 +00008678 if( sCheck.mallocFailed ){
8679 sqlite3StrAccumReset(&sCheck.errMsg);
8680 *pnErr = sCheck.nErr+1;
8681 return 0;
8682 }
drh1dcdbc02007-01-27 02:24:54 +00008683 *pnErr = sCheck.nErr;
drhf089aa42008-07-08 19:34:06 +00008684 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
8685 return sqlite3StrAccumFinish(&sCheck.errMsg);
drh5eddca62001-06-30 21:53:53 +00008686}
drhb7f91642004-10-31 02:22:47 +00008687#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00008688
drh73509ee2003-04-06 20:44:45 +00008689/*
drhd4e0bb02012-05-27 01:19:04 +00008690** Return the full pathname of the underlying database file. Return
8691** an empty string if the database is in-memory or a TEMP database.
drhd0679ed2007-08-28 22:24:34 +00008692**
8693** The pager filename is invariant as long as the pager is
8694** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00008695*/
danielk1977aef0bf62005-12-30 16:28:01 +00008696const char *sqlite3BtreeGetFilename(Btree *p){
8697 assert( p->pBt->pPager!=0 );
drhd4e0bb02012-05-27 01:19:04 +00008698 return sqlite3PagerFilename(p->pBt->pPager, 1);
drh73509ee2003-04-06 20:44:45 +00008699}
8700
8701/*
danielk19775865e3d2004-06-14 06:03:57 +00008702** Return the pathname of the journal file for this database. The return
8703** value of this routine is the same regardless of whether the journal file
8704** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00008705**
8706** The pager journal filename is invariant as long as the pager is
8707** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00008708*/
danielk1977aef0bf62005-12-30 16:28:01 +00008709const char *sqlite3BtreeGetJournalname(Btree *p){
8710 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00008711 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00008712}
8713
danielk19771d850a72004-05-31 08:26:49 +00008714/*
8715** Return non-zero if a transaction is active.
8716*/
danielk1977aef0bf62005-12-30 16:28:01 +00008717int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00008718 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00008719 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00008720}
8721
dana550f2d2010-08-02 10:47:05 +00008722#ifndef SQLITE_OMIT_WAL
8723/*
8724** Run a checkpoint on the Btree passed as the first argument.
8725**
8726** Return SQLITE_LOCKED if this or any other connection has an open
8727** transaction on the shared-cache the argument Btree is connected to.
dana58f26f2010-11-16 18:56:51 +00008728**
dancdc1f042010-11-18 12:11:05 +00008729** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
dana550f2d2010-08-02 10:47:05 +00008730*/
dancdc1f042010-11-18 12:11:05 +00008731int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
dana550f2d2010-08-02 10:47:05 +00008732 int rc = SQLITE_OK;
8733 if( p ){
8734 BtShared *pBt = p->pBt;
8735 sqlite3BtreeEnter(p);
8736 if( pBt->inTransaction!=TRANS_NONE ){
8737 rc = SQLITE_LOCKED;
8738 }else{
dancdc1f042010-11-18 12:11:05 +00008739 rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
dana550f2d2010-08-02 10:47:05 +00008740 }
8741 sqlite3BtreeLeave(p);
8742 }
8743 return rc;
8744}
8745#endif
8746
danielk19771d850a72004-05-31 08:26:49 +00008747/*
danielk19772372c2b2006-06-27 16:34:56 +00008748** Return non-zero if a read (or write) transaction is active.
8749*/
8750int sqlite3BtreeIsInReadTrans(Btree *p){
drh64022502009-01-09 14:11:04 +00008751 assert( p );
drhe5fe6902007-12-07 18:55:28 +00008752 assert( sqlite3_mutex_held(p->db->mutex) );
drh64022502009-01-09 14:11:04 +00008753 return p->inTrans!=TRANS_NONE;
danielk19772372c2b2006-06-27 16:34:56 +00008754}
8755
danielk197704103022009-02-03 16:51:24 +00008756int sqlite3BtreeIsInBackup(Btree *p){
8757 assert( p );
8758 assert( sqlite3_mutex_held(p->db->mutex) );
8759 return p->nBackup!=0;
8760}
8761
danielk19772372c2b2006-06-27 16:34:56 +00008762/*
danielk1977da184232006-01-05 11:34:32 +00008763** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +00008764** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +00008765** purposes (for example, to store a high-level schema associated with
8766** the shared-btree). The btree layer manages reference counting issues.
8767**
8768** The first time this is called on a shared-btree, nBytes bytes of memory
8769** are allocated, zeroed, and returned to the caller. For each subsequent
8770** call the nBytes parameter is ignored and a pointer to the same blob
8771** of memory returned.
8772**
danielk1977171bfed2008-06-23 09:50:50 +00008773** If the nBytes parameter is 0 and the blob of memory has not yet been
8774** allocated, a null pointer is returned. If the blob has already been
8775** allocated, it is returned as normal.
8776**
danielk1977da184232006-01-05 11:34:32 +00008777** Just before the shared-btree is closed, the function passed as the
8778** xFree argument when the memory allocation was made is invoked on the
drh4fa7d7c2011-04-03 02:41:00 +00008779** blob of allocated memory. The xFree function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00008780** on the memory, the btree layer does that.
8781*/
8782void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
8783 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00008784 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +00008785 if( !pBt->pSchema && nBytes ){
drhb9755982010-07-24 16:34:37 +00008786 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
danielk1977da184232006-01-05 11:34:32 +00008787 pBt->xFreeSchema = xFree;
8788 }
drh27641702007-08-22 02:56:42 +00008789 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00008790 return pBt->pSchema;
8791}
8792
danielk1977c87d34d2006-01-06 13:00:28 +00008793/*
danielk1977404ca072009-03-16 13:19:36 +00008794** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
8795** btree as the argument handle holds an exclusive lock on the
8796** sqlite_master table. Otherwise SQLITE_OK.
danielk1977c87d34d2006-01-06 13:00:28 +00008797*/
8798int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00008799 int rc;
drhe5fe6902007-12-07 18:55:28 +00008800 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +00008801 sqlite3BtreeEnter(p);
danielk1977404ca072009-03-16 13:19:36 +00008802 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
8803 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
drh27641702007-08-22 02:56:42 +00008804 sqlite3BtreeLeave(p);
8805 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00008806}
8807
drha154dcd2006-03-22 22:10:07 +00008808
8809#ifndef SQLITE_OMIT_SHARED_CACHE
8810/*
8811** Obtain a lock on the table whose root page is iTab. The
8812** lock is a write lock if isWritelock is true or a read lock
8813** if it is false.
8814*/
danielk1977c00da102006-01-07 13:21:04 +00008815int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00008816 int rc = SQLITE_OK;
danielk1977602b4662009-07-02 07:47:33 +00008817 assert( p->inTrans!=TRANS_NONE );
drh6a9ad3d2008-04-02 16:29:30 +00008818 if( p->sharable ){
8819 u8 lockType = READ_LOCK + isWriteLock;
8820 assert( READ_LOCK+1==WRITE_LOCK );
8821 assert( isWriteLock==0 || isWriteLock==1 );
danielk1977602b4662009-07-02 07:47:33 +00008822
drh6a9ad3d2008-04-02 16:29:30 +00008823 sqlite3BtreeEnter(p);
drhc25eabe2009-02-24 18:57:31 +00008824 rc = querySharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00008825 if( rc==SQLITE_OK ){
drhc25eabe2009-02-24 18:57:31 +00008826 rc = setSharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00008827 }
8828 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00008829 }
8830 return rc;
8831}
drha154dcd2006-03-22 22:10:07 +00008832#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00008833
danielk1977b4e9af92007-05-01 17:49:49 +00008834#ifndef SQLITE_OMIT_INCRBLOB
8835/*
8836** Argument pCsr must be a cursor opened for writing on an
8837** INTKEY table currently pointing at a valid table entry.
8838** This function modifies the data stored as part of that entry.
danielk1977ecaecf92009-07-08 08:05:35 +00008839**
8840** Only the data content may only be modified, it is not possible to
8841** change the length of the data stored. If this function is called with
8842** parameters that attempt to write past the end of the existing data,
8843** no modifications are made and SQLITE_CORRUPT is returned.
danielk1977b4e9af92007-05-01 17:49:49 +00008844*/
danielk1977dcbb5d32007-05-04 18:36:44 +00008845int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
danielk1977c9000e62009-07-08 13:55:28 +00008846 int rc;
drh1fee73e2007-08-29 04:00:57 +00008847 assert( cursorHoldsMutex(pCsr) );
drhe5fe6902007-12-07 18:55:28 +00008848 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
drh036dbec2014-03-11 23:40:44 +00008849 assert( pCsr->curFlags & BTCF_Incrblob );
danielk19773588ceb2008-06-10 17:30:26 +00008850
danielk1977c9000e62009-07-08 13:55:28 +00008851 rc = restoreCursorPosition(pCsr);
8852 if( rc!=SQLITE_OK ){
8853 return rc;
8854 }
danielk19773588ceb2008-06-10 17:30:26 +00008855 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
8856 if( pCsr->eState!=CURSOR_VALID ){
8857 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +00008858 }
8859
dan227a1c42013-04-03 11:17:39 +00008860 /* Save the positions of all other cursors open on this table. This is
8861 ** required in case any of them are holding references to an xFetch
8862 ** version of the b-tree page modified by the accessPayload call below.
drh370c9f42013-04-03 20:04:04 +00008863 **
drh3f387402014-09-24 01:23:00 +00008864 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
drh370c9f42013-04-03 20:04:04 +00008865 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
8866 ** saveAllCursors can only return SQLITE_OK.
dan227a1c42013-04-03 11:17:39 +00008867 */
drh370c9f42013-04-03 20:04:04 +00008868 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
8869 assert( rc==SQLITE_OK );
dan227a1c42013-04-03 11:17:39 +00008870
danielk1977c9000e62009-07-08 13:55:28 +00008871 /* Check some assumptions:
danielk1977dcbb5d32007-05-04 18:36:44 +00008872 ** (a) the cursor is open for writing,
danielk1977c9000e62009-07-08 13:55:28 +00008873 ** (b) there is a read/write transaction open,
8874 ** (c) the connection holds a write-lock on the table (if required),
8875 ** (d) there are no conflicting read-locks, and
8876 ** (e) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00008877 */
drh036dbec2014-03-11 23:40:44 +00008878 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
danielk19774f029602009-07-08 18:45:37 +00008879 return SQLITE_READONLY;
8880 }
drhc9166342012-01-05 23:32:06 +00008881 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
8882 && pCsr->pBt->inTransaction==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +00008883 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
8884 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
danielk1977c9000e62009-07-08 13:55:28 +00008885 assert( pCsr->apPage[pCsr->iPage]->intKey );
danielk1977b4e9af92007-05-01 17:49:49 +00008886
drhfb192682009-07-11 18:26:28 +00008887 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00008888}
danielk19772dec9702007-05-02 16:48:37 +00008889
8890/*
dan5a500af2014-03-11 20:33:04 +00008891** Mark this cursor as an incremental blob cursor.
danielk19772dec9702007-05-02 16:48:37 +00008892*/
dan5a500af2014-03-11 20:33:04 +00008893void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
drh036dbec2014-03-11 23:40:44 +00008894 pCur->curFlags |= BTCF_Incrblob;
danielk19772dec9702007-05-02 16:48:37 +00008895}
danielk1977b4e9af92007-05-01 17:49:49 +00008896#endif
dane04dc882010-04-20 18:53:15 +00008897
8898/*
8899** Set both the "read version" (single byte at byte offset 18) and
8900** "write version" (single byte at byte offset 19) fields in the database
8901** header to iVersion.
8902*/
8903int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
8904 BtShared *pBt = pBtree->pBt;
8905 int rc; /* Return code */
8906
dane04dc882010-04-20 18:53:15 +00008907 assert( iVersion==1 || iVersion==2 );
8908
danb9780022010-04-21 18:37:57 +00008909 /* If setting the version fields to 1, do not automatically open the
8910 ** WAL connection, even if the version fields are currently set to 2.
8911 */
drhc9166342012-01-05 23:32:06 +00008912 pBt->btsFlags &= ~BTS_NO_WAL;
8913 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
danb9780022010-04-21 18:37:57 +00008914
8915 rc = sqlite3BtreeBeginTrans(pBtree, 0);
dane04dc882010-04-20 18:53:15 +00008916 if( rc==SQLITE_OK ){
8917 u8 *aData = pBt->pPage1->aData;
danb9780022010-04-21 18:37:57 +00008918 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
danede6eb82010-04-22 06:27:04 +00008919 rc = sqlite3BtreeBeginTrans(pBtree, 2);
danb9780022010-04-21 18:37:57 +00008920 if( rc==SQLITE_OK ){
8921 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
8922 if( rc==SQLITE_OK ){
8923 aData[18] = (u8)iVersion;
8924 aData[19] = (u8)iVersion;
8925 }
8926 }
8927 }
dane04dc882010-04-20 18:53:15 +00008928 }
8929
drhc9166342012-01-05 23:32:06 +00008930 pBt->btsFlags &= ~BTS_NO_WAL;
dane04dc882010-04-20 18:53:15 +00008931 return rc;
8932}
dan428c2182012-08-06 18:50:11 +00008933
8934/*
8935** set the mask of hint flags for cursor pCsr. Currently the only valid
8936** values are 0 and BTREE_BULKLOAD.
8937*/
8938void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
8939 assert( mask==BTREE_BULKLOAD || mask==0 );
8940 pCsr->hints = mask;
8941}
drh781597f2014-05-21 08:21:07 +00008942
8943/*
8944** Return true if the given Btree is read-only.
8945*/
8946int sqlite3BtreeIsReadonly(Btree *p){
8947 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
8948}