blob: ac350ac92fe934caf194194ea3706c29acf8b450 [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 ){
drh1ffede82015-01-30 20:59:27 +0000178 if( iTab ){
179 /* Two or more indexes share the same root page. There must
180 ** be imposter tables. So just return true. The assert is not
181 ** useful in that case. */
182 return 1;
183 }
shane5eff7cf2009-08-10 03:57:58 +0000184 iTab = pIdx->pTable->tnum;
danielk197796d48e92009-06-29 06:00:37 +0000185 }
186 }
187 }else{
188 iTab = iRoot;
189 }
190
191 /* Search for the required lock. Either a write-lock on root-page iTab, a
192 ** write-lock on the schema table, or (if the client is reading) a
193 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
194 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
195 if( pLock->pBtree==pBtree
196 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
197 && pLock->eLock>=eLockType
198 ){
199 return 1;
200 }
201 }
202
203 /* Failed to find the required lock. */
204 return 0;
205}
drh0ee3dbe2009-10-16 15:05:18 +0000206#endif /* SQLITE_DEBUG */
danielk197796d48e92009-06-29 06:00:37 +0000207
drh0ee3dbe2009-10-16 15:05:18 +0000208#ifdef SQLITE_DEBUG
danielk197796d48e92009-06-29 06:00:37 +0000209/*
drh0ee3dbe2009-10-16 15:05:18 +0000210**** This function may be used as part of assert() statements only. ****
danielk197796d48e92009-06-29 06:00:37 +0000211**
drh0ee3dbe2009-10-16 15:05:18 +0000212** Return true if it would be illegal for pBtree to write into the
213** table or index rooted at iRoot because other shared connections are
214** simultaneously reading that same table or index.
215**
216** It is illegal for pBtree to write if some other Btree object that
217** shares the same BtShared object is currently reading or writing
218** the iRoot table. Except, if the other Btree object has the
219** read-uncommitted flag set, then it is OK for the other object to
220** have a read cursor.
221**
222** For example, before writing to any part of the table or index
223** rooted at page iRoot, one should call:
danielk197796d48e92009-06-29 06:00:37 +0000224**
225** assert( !hasReadConflicts(pBtree, iRoot) );
226*/
227static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
228 BtCursor *p;
229 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
230 if( p->pgnoRoot==iRoot
231 && p->pBtree!=pBtree
232 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
233 ){
234 return 1;
235 }
236 }
237 return 0;
238}
239#endif /* #ifdef SQLITE_DEBUG */
240
danielk1977da184232006-01-05 11:34:32 +0000241/*
drh0ee3dbe2009-10-16 15:05:18 +0000242** Query to see if Btree handle p may obtain a lock of type eLock
danielk1977aef0bf62005-12-30 16:28:01 +0000243** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
drhc25eabe2009-02-24 18:57:31 +0000244** SQLITE_OK if the lock may be obtained (by calling
245** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
danielk1977aef0bf62005-12-30 16:28:01 +0000246*/
drhc25eabe2009-02-24 18:57:31 +0000247static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +0000248 BtShared *pBt = p->pBt;
249 BtLock *pIter;
250
drh1fee73e2007-08-29 04:00:57 +0000251 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000252 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
253 assert( p->db!=0 );
danielk1977e0d9e6f2009-07-03 16:25:06 +0000254 assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
drhd677b3d2007-08-20 22:48:41 +0000255
danielk19775b413d72009-04-01 09:41:54 +0000256 /* If requesting a write-lock, then the Btree must have an open write
257 ** transaction on this file. And, obviously, for this to be so there
258 ** must be an open write transaction on the file itself.
259 */
260 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
261 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
262
drh0ee3dbe2009-10-16 15:05:18 +0000263 /* This routine is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000264 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000265 return SQLITE_OK;
266 }
267
danielk1977641b0f42007-12-21 04:47:25 +0000268 /* If some other connection is holding an exclusive lock, the
269 ** requested lock may not be obtained.
270 */
drhc9166342012-01-05 23:32:06 +0000271 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
danielk1977404ca072009-03-16 13:19:36 +0000272 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
273 return SQLITE_LOCKED_SHAREDCACHE;
danielk1977641b0f42007-12-21 04:47:25 +0000274 }
275
danielk1977e0d9e6f2009-07-03 16:25:06 +0000276 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
277 /* The condition (pIter->eLock!=eLock) in the following if(...)
278 ** statement is a simplification of:
279 **
280 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
281 **
282 ** since we know that if eLock==WRITE_LOCK, then no other connection
283 ** may hold a WRITE_LOCK on any table in this file (since there can
284 ** only be a single writer).
285 */
286 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
287 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
288 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
289 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
290 if( eLock==WRITE_LOCK ){
291 assert( p==pBt->pWriter );
drhc9166342012-01-05 23:32:06 +0000292 pBt->btsFlags |= BTS_PENDING;
danielk1977da184232006-01-05 11:34:32 +0000293 }
danielk1977e0d9e6f2009-07-03 16:25:06 +0000294 return SQLITE_LOCKED_SHAREDCACHE;
danielk1977aef0bf62005-12-30 16:28:01 +0000295 }
296 }
297 return SQLITE_OK;
298}
drhe53831d2007-08-17 01:14:38 +0000299#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000300
drhe53831d2007-08-17 01:14:38 +0000301#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000302/*
303** Add a lock on the table with root-page iTable to the shared-btree used
304** by Btree handle p. Parameter eLock must be either READ_LOCK or
305** WRITE_LOCK.
306**
danielk19779d104862009-07-09 08:27:14 +0000307** This function assumes the following:
308**
drh0ee3dbe2009-10-16 15:05:18 +0000309** (a) The specified Btree object p is connected to a sharable
310** database (one with the BtShared.sharable flag set), and
danielk19779d104862009-07-09 08:27:14 +0000311**
drh0ee3dbe2009-10-16 15:05:18 +0000312** (b) No other Btree objects hold a lock that conflicts
danielk19779d104862009-07-09 08:27:14 +0000313** with the requested lock (i.e. querySharedCacheTableLock() has
314** already been called and returned SQLITE_OK).
315**
316** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
317** is returned if a malloc attempt fails.
danielk1977aef0bf62005-12-30 16:28:01 +0000318*/
drhc25eabe2009-02-24 18:57:31 +0000319static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +0000320 BtShared *pBt = p->pBt;
321 BtLock *pLock = 0;
322 BtLock *pIter;
323
drh1fee73e2007-08-29 04:00:57 +0000324 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000325 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
326 assert( p->db!=0 );
drhd677b3d2007-08-20 22:48:41 +0000327
danielk1977e0d9e6f2009-07-03 16:25:06 +0000328 /* A connection with the read-uncommitted flag set will never try to
329 ** obtain a read-lock using this function. The only read-lock obtained
330 ** by a connection in read-uncommitted mode is on the sqlite_master
331 ** table, and that lock is obtained in BtreeBeginTrans(). */
332 assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
333
danielk19779d104862009-07-09 08:27:14 +0000334 /* This function should only be called on a sharable b-tree after it
335 ** has been determined that no other b-tree holds a conflicting lock. */
336 assert( p->sharable );
drhc25eabe2009-02-24 18:57:31 +0000337 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
danielk1977aef0bf62005-12-30 16:28:01 +0000338
339 /* First search the list for an existing lock on this table. */
340 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
341 if( pIter->iTable==iTable && pIter->pBtree==p ){
342 pLock = pIter;
343 break;
344 }
345 }
346
347 /* If the above search did not find a BtLock struct associating Btree p
348 ** with table iTable, allocate one and link it into the list.
349 */
350 if( !pLock ){
drh17435752007-08-16 04:30:38 +0000351 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
danielk1977aef0bf62005-12-30 16:28:01 +0000352 if( !pLock ){
353 return SQLITE_NOMEM;
354 }
355 pLock->iTable = iTable;
356 pLock->pBtree = p;
357 pLock->pNext = pBt->pLock;
358 pBt->pLock = pLock;
359 }
360
361 /* Set the BtLock.eLock variable to the maximum of the current lock
362 ** and the requested lock. This means if a write-lock was already held
363 ** and a read-lock requested, we don't incorrectly downgrade the lock.
364 */
365 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000366 if( eLock>pLock->eLock ){
367 pLock->eLock = eLock;
368 }
danielk1977aef0bf62005-12-30 16:28:01 +0000369
370 return SQLITE_OK;
371}
drhe53831d2007-08-17 01:14:38 +0000372#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000373
drhe53831d2007-08-17 01:14:38 +0000374#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000375/*
drhc25eabe2009-02-24 18:57:31 +0000376** Release all the table locks (locks obtained via calls to
drh0ee3dbe2009-10-16 15:05:18 +0000377** the setSharedCacheTableLock() procedure) held by Btree object p.
danielk1977fa542f12009-04-02 18:28:08 +0000378**
drh0ee3dbe2009-10-16 15:05:18 +0000379** This function assumes that Btree p has an open read or write
drhc9166342012-01-05 23:32:06 +0000380** transaction. If it does not, then the BTS_PENDING flag
danielk1977fa542f12009-04-02 18:28:08 +0000381** may be incorrectly cleared.
danielk1977aef0bf62005-12-30 16:28:01 +0000382*/
drhc25eabe2009-02-24 18:57:31 +0000383static void clearAllSharedCacheTableLocks(Btree *p){
danielk1977641b0f42007-12-21 04:47:25 +0000384 BtShared *pBt = p->pBt;
385 BtLock **ppIter = &pBt->pLock;
danielk1977da184232006-01-05 11:34:32 +0000386
drh1fee73e2007-08-29 04:00:57 +0000387 assert( sqlite3BtreeHoldsMutex(p) );
drhe53831d2007-08-17 01:14:38 +0000388 assert( p->sharable || 0==*ppIter );
danielk1977fa542f12009-04-02 18:28:08 +0000389 assert( p->inTrans>0 );
danielk1977da184232006-01-05 11:34:32 +0000390
danielk1977aef0bf62005-12-30 16:28:01 +0000391 while( *ppIter ){
392 BtLock *pLock = *ppIter;
drhc9166342012-01-05 23:32:06 +0000393 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
danielk1977fa542f12009-04-02 18:28:08 +0000394 assert( pLock->pBtree->inTrans>=pLock->eLock );
danielk1977aef0bf62005-12-30 16:28:01 +0000395 if( pLock->pBtree==p ){
396 *ppIter = pLock->pNext;
danielk1977602b4662009-07-02 07:47:33 +0000397 assert( pLock->iTable!=1 || pLock==&p->lock );
398 if( pLock->iTable!=1 ){
399 sqlite3_free(pLock);
400 }
danielk1977aef0bf62005-12-30 16:28:01 +0000401 }else{
402 ppIter = &pLock->pNext;
403 }
404 }
danielk1977641b0f42007-12-21 04:47:25 +0000405
drhc9166342012-01-05 23:32:06 +0000406 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
danielk1977404ca072009-03-16 13:19:36 +0000407 if( pBt->pWriter==p ){
408 pBt->pWriter = 0;
drhc9166342012-01-05 23:32:06 +0000409 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
danielk1977404ca072009-03-16 13:19:36 +0000410 }else if( pBt->nTransaction==2 ){
drh0ee3dbe2009-10-16 15:05:18 +0000411 /* This function is called when Btree p is concluding its
danielk1977404ca072009-03-16 13:19:36 +0000412 ** transaction. If there currently exists a writer, and p is not
413 ** that writer, then the number of locks held by connections other
414 ** than the writer must be about to drop to zero. In this case
drhc9166342012-01-05 23:32:06 +0000415 ** set the BTS_PENDING flag to 0.
danielk1977404ca072009-03-16 13:19:36 +0000416 **
drhc9166342012-01-05 23:32:06 +0000417 ** If there is not currently a writer, then BTS_PENDING must
danielk1977404ca072009-03-16 13:19:36 +0000418 ** be zero already. So this next line is harmless in that case.
419 */
drhc9166342012-01-05 23:32:06 +0000420 pBt->btsFlags &= ~BTS_PENDING;
danielk1977641b0f42007-12-21 04:47:25 +0000421 }
danielk1977aef0bf62005-12-30 16:28:01 +0000422}
danielk197794b30732009-07-02 17:21:57 +0000423
danielk1977e0d9e6f2009-07-03 16:25:06 +0000424/*
drh0ee3dbe2009-10-16 15:05:18 +0000425** This function changes all write-locks held by Btree p into read-locks.
danielk1977e0d9e6f2009-07-03 16:25:06 +0000426*/
danielk197794b30732009-07-02 17:21:57 +0000427static void downgradeAllSharedCacheTableLocks(Btree *p){
428 BtShared *pBt = p->pBt;
429 if( pBt->pWriter==p ){
430 BtLock *pLock;
431 pBt->pWriter = 0;
drhc9166342012-01-05 23:32:06 +0000432 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
danielk197794b30732009-07-02 17:21:57 +0000433 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
434 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
435 pLock->eLock = READ_LOCK;
436 }
437 }
438}
439
danielk1977aef0bf62005-12-30 16:28:01 +0000440#endif /* SQLITE_OMIT_SHARED_CACHE */
441
drh980b1a72006-08-16 16:42:48 +0000442static void releasePage(MemPage *pPage); /* Forward reference */
443
drh1fee73e2007-08-29 04:00:57 +0000444/*
drh0ee3dbe2009-10-16 15:05:18 +0000445***** This routine is used inside of assert() only ****
446**
447** Verify that the cursor holds the mutex on its BtShared
drh1fee73e2007-08-29 04:00:57 +0000448*/
drh0ee3dbe2009-10-16 15:05:18 +0000449#ifdef SQLITE_DEBUG
drh1fee73e2007-08-29 04:00:57 +0000450static int cursorHoldsMutex(BtCursor *p){
drhff0587c2007-08-29 17:43:19 +0000451 return sqlite3_mutex_held(p->pBt->mutex);
drh1fee73e2007-08-29 04:00:57 +0000452}
453#endif
454
danielk197792d4d7a2007-05-04 12:05:56 +0000455/*
dan5a500af2014-03-11 20:33:04 +0000456** Invalidate the overflow cache of the cursor passed as the first argument.
457** on the shared btree structure pBt.
danielk197792d4d7a2007-05-04 12:05:56 +0000458*/
drh036dbec2014-03-11 23:40:44 +0000459#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
danielk197792d4d7a2007-05-04 12:05:56 +0000460
461/*
462** Invalidate the overflow page-list cache for all cursors opened
463** on the shared btree structure pBt.
464*/
465static void invalidateAllOverflowCache(BtShared *pBt){
466 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000467 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +0000468 for(p=pBt->pCursor; p; p=p->pNext){
469 invalidateOverflowCache(p);
470 }
471}
danielk197796d48e92009-06-29 06:00:37 +0000472
dan5a500af2014-03-11 20:33:04 +0000473#ifndef SQLITE_OMIT_INCRBLOB
danielk197796d48e92009-06-29 06:00:37 +0000474/*
475** This function is called before modifying the contents of a table
drh0ee3dbe2009-10-16 15:05:18 +0000476** to invalidate any incrblob cursors that are open on the
drheeb844a2009-08-08 18:01:07 +0000477** row or one of the rows being modified.
danielk197796d48e92009-06-29 06:00:37 +0000478**
479** If argument isClearTable is true, then the entire contents of the
480** table is about to be deleted. In this case invalidate all incrblob
481** cursors open on any row within the table with root-page pgnoRoot.
482**
483** Otherwise, if argument isClearTable is false, then the row with
484** rowid iRow is being replaced or deleted. In this case invalidate
drh0ee3dbe2009-10-16 15:05:18 +0000485** only those incrblob cursors open on that specific row.
danielk197796d48e92009-06-29 06:00:37 +0000486*/
487static void invalidateIncrblobCursors(
488 Btree *pBtree, /* The database file to check */
danielk197796d48e92009-06-29 06:00:37 +0000489 i64 iRow, /* The rowid that might be changing */
490 int isClearTable /* True if all rows are being deleted */
491){
492 BtCursor *p;
493 BtShared *pBt = pBtree->pBt;
494 assert( sqlite3BtreeHoldsMutex(pBtree) );
495 for(p=pBt->pCursor; p; p=p->pNext){
drh3f387402014-09-24 01:23:00 +0000496 if( (p->curFlags & BTCF_Incrblob)!=0
497 && (isClearTable || p->info.nKey==iRow)
498 ){
danielk197796d48e92009-06-29 06:00:37 +0000499 p->eState = CURSOR_INVALID;
500 }
501 }
502}
503
danielk197792d4d7a2007-05-04 12:05:56 +0000504#else
dan5a500af2014-03-11 20:33:04 +0000505 /* Stub function when INCRBLOB is omitted */
drheeb844a2009-08-08 18:01:07 +0000506 #define invalidateIncrblobCursors(x,y,z)
drh0ee3dbe2009-10-16 15:05:18 +0000507#endif /* SQLITE_OMIT_INCRBLOB */
danielk197792d4d7a2007-05-04 12:05:56 +0000508
drh980b1a72006-08-16 16:42:48 +0000509/*
danielk1977bea2a942009-01-20 17:06:27 +0000510** Set bit pgno of the BtShared.pHasContent bitvec. This is called
511** when a page that previously contained data becomes a free-list leaf
512** page.
513**
514** The BtShared.pHasContent bitvec exists to work around an obscure
515** bug caused by the interaction of two useful IO optimizations surrounding
516** free-list leaf pages:
517**
518** 1) When all data is deleted from a page and the page becomes
519** a free-list leaf page, the page is not written to the database
520** (as free-list leaf pages contain no meaningful data). Sometimes
521** such a page is not even journalled (as it will not be modified,
522** why bother journalling it?).
523**
524** 2) When a free-list leaf page is reused, its content is not read
525** from the database or written to the journal file (why should it
526** be, if it is not at all meaningful?).
527**
528** By themselves, these optimizations work fine and provide a handy
529** performance boost to bulk delete or insert operations. However, if
530** a page is moved to the free-list and then reused within the same
531** transaction, a problem comes up. If the page is not journalled when
532** it is moved to the free-list and it is also not journalled when it
533** is extracted from the free-list and reused, then the original data
534** may be lost. In the event of a rollback, it may not be possible
535** to restore the database to its original configuration.
536**
537** The solution is the BtShared.pHasContent bitvec. Whenever a page is
538** moved to become a free-list leaf page, the corresponding bit is
539** set in the bitvec. Whenever a leaf page is extracted from the free-list,
drh0ee3dbe2009-10-16 15:05:18 +0000540** optimization 2 above is omitted if the corresponding bit is already
danielk1977bea2a942009-01-20 17:06:27 +0000541** set in BtShared.pHasContent. The contents of the bitvec are cleared
542** at the end of every transaction.
543*/
544static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
545 int rc = SQLITE_OK;
546 if( !pBt->pHasContent ){
drhdd3cd972010-03-27 17:12:36 +0000547 assert( pgno<=pBt->nPage );
548 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
drh4c301aa2009-07-15 17:25:45 +0000549 if( !pBt->pHasContent ){
550 rc = SQLITE_NOMEM;
danielk1977bea2a942009-01-20 17:06:27 +0000551 }
552 }
553 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
554 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
555 }
556 return rc;
557}
558
559/*
560** Query the BtShared.pHasContent vector.
561**
562** This function is called when a free-list leaf page is removed from the
563** free-list for reuse. It returns false if it is safe to retrieve the
564** page from the pager layer with the 'no-content' flag set. True otherwise.
565*/
566static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
567 Bitvec *p = pBt->pHasContent;
568 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
569}
570
571/*
572** Clear (destroy) the BtShared.pHasContent bitvec. This should be
573** invoked at the conclusion of each write-transaction.
574*/
575static void btreeClearHasContent(BtShared *pBt){
576 sqlite3BitvecDestroy(pBt->pHasContent);
577 pBt->pHasContent = 0;
578}
579
580/*
drh138eeeb2013-03-27 03:15:23 +0000581** Release all of the apPage[] pages for a cursor.
582*/
583static void btreeReleaseAllCursorPages(BtCursor *pCur){
584 int i;
585 for(i=0; i<=pCur->iPage; i++){
586 releasePage(pCur->apPage[i]);
587 pCur->apPage[i] = 0;
588 }
589 pCur->iPage = -1;
590}
591
592
593/*
drh980b1a72006-08-16 16:42:48 +0000594** Save the current cursor position in the variables BtCursor.nKey
595** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
drhea8ffdf2009-07-22 00:35:23 +0000596**
597** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
598** prior to calling this routine.
drh980b1a72006-08-16 16:42:48 +0000599*/
600static int saveCursorPosition(BtCursor *pCur){
601 int rc;
602
603 assert( CURSOR_VALID==pCur->eState );
604 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000605 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000606
607 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
drhea8ffdf2009-07-22 00:35:23 +0000608 assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
drh980b1a72006-08-16 16:42:48 +0000609
610 /* If this is an intKey table, then the above call to BtreeKeySize()
611 ** stores the integer key in pCur->nKey. In this case this value is
612 ** all that is required. Otherwise, if pCur is not open on an intKey
613 ** table, then malloc space for and store the pCur->nKey bytes of key
614 ** data.
615 */
drh4c301aa2009-07-15 17:25:45 +0000616 if( 0==pCur->apPage[0]->intKey ){
drhda4ca9d2014-09-09 17:27:35 +0000617 void *pKey = sqlite3Malloc( pCur->nKey );
drh980b1a72006-08-16 16:42:48 +0000618 if( pKey ){
drhf49661a2008-12-10 16:45:50 +0000619 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
drh980b1a72006-08-16 16:42:48 +0000620 if( rc==SQLITE_OK ){
621 pCur->pKey = pKey;
622 }else{
drh17435752007-08-16 04:30:38 +0000623 sqlite3_free(pKey);
drh980b1a72006-08-16 16:42:48 +0000624 }
625 }else{
626 rc = SQLITE_NOMEM;
627 }
628 }
danielk197771d5d2c2008-09-29 11:49:47 +0000629 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
drh980b1a72006-08-16 16:42:48 +0000630
631 if( rc==SQLITE_OK ){
drh138eeeb2013-03-27 03:15:23 +0000632 btreeReleaseAllCursorPages(pCur);
drh980b1a72006-08-16 16:42:48 +0000633 pCur->eState = CURSOR_REQUIRESEEK;
634 }
635
danielk197792d4d7a2007-05-04 12:05:56 +0000636 invalidateOverflowCache(pCur);
drh980b1a72006-08-16 16:42:48 +0000637 return rc;
638}
639
drh637f3d82014-08-22 22:26:07 +0000640/* Forward reference */
641static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
642
drh980b1a72006-08-16 16:42:48 +0000643/*
drh0ee3dbe2009-10-16 15:05:18 +0000644** Save the positions of all cursors (except pExcept) that are open on
drh637f3d82014-08-22 22:26:07 +0000645** the table with root-page iRoot. "Saving the cursor position" means that
646** the location in the btree is remembered in such a way that it can be
647** moved back to the same spot after the btree has been modified. This
648** routine is called just before cursor pExcept is used to modify the
649** table, for example in BtreeDelete() or BtreeInsert().
650**
651** Implementation note: This routine merely checks to see if any cursors
652** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
653** event that cursors are in need to being saved.
drh980b1a72006-08-16 16:42:48 +0000654*/
655static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
drh3bdffdd2014-08-23 19:08:09 +0000656 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000657 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000658 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000659 for(p=pBt->pCursor; p; p=p->pNext){
drh637f3d82014-08-22 22:26:07 +0000660 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
661 }
662 return p ? saveCursorsOnList(p, iRoot, pExcept) : SQLITE_OK;
663}
664
665/* This helper routine to saveAllCursors does the actual work of saving
666** the cursors if and when a cursor is found that actually requires saving.
667** The common case is that no cursors need to be saved, so this routine is
668** broken out from its caller to avoid unnecessary stack pointer movement.
669*/
670static int SQLITE_NOINLINE saveCursorsOnList(
drh3f387402014-09-24 01:23:00 +0000671 BtCursor *p, /* The first cursor that needs saving */
672 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
673 BtCursor *pExcept /* Do not save this cursor */
drh637f3d82014-08-22 22:26:07 +0000674){
675 do{
drh138eeeb2013-03-27 03:15:23 +0000676 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
677 if( p->eState==CURSOR_VALID ){
678 int rc = saveCursorPosition(p);
679 if( SQLITE_OK!=rc ){
680 return rc;
681 }
682 }else{
683 testcase( p->iPage>0 );
684 btreeReleaseAllCursorPages(p);
drh980b1a72006-08-16 16:42:48 +0000685 }
686 }
drh637f3d82014-08-22 22:26:07 +0000687 p = p->pNext;
688 }while( p );
drh980b1a72006-08-16 16:42:48 +0000689 return SQLITE_OK;
690}
691
692/*
drhbf700f32007-03-31 02:36:44 +0000693** Clear the current cursor position.
694*/
danielk1977be51a652008-10-08 17:58:48 +0000695void sqlite3BtreeClearCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000696 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000697 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +0000698 pCur->pKey = 0;
699 pCur->eState = CURSOR_INVALID;
700}
701
702/*
danielk19773509a652009-07-06 18:56:13 +0000703** In this version of BtreeMoveto, pKey is a packed index record
704** such as is generated by the OP_MakeRecord opcode. Unpack the
705** record and then call BtreeMovetoUnpacked() to do the work.
706*/
707static int btreeMoveto(
708 BtCursor *pCur, /* Cursor open on the btree to be searched */
709 const void *pKey, /* Packed key if the btree is an index */
710 i64 nKey, /* Integer key for tables. Size of pKey for indices */
711 int bias, /* Bias search to the high end */
712 int *pRes /* Write search results here */
713){
714 int rc; /* Status code */
715 UnpackedRecord *pIdxKey; /* Unpacked index key */
drhb4139222013-11-06 14:36:08 +0000716 char aSpace[200]; /* Temp space for pIdxKey - to avoid a malloc */
dan03e9cfc2011-09-05 14:20:27 +0000717 char *pFree = 0;
danielk19773509a652009-07-06 18:56:13 +0000718
719 if( pKey ){
720 assert( nKey==(i64)(int)nKey );
dan03e9cfc2011-09-05 14:20:27 +0000721 pIdxKey = sqlite3VdbeAllocUnpackedRecord(
722 pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
723 );
danielk19773509a652009-07-06 18:56:13 +0000724 if( pIdxKey==0 ) return SQLITE_NOMEM;
mistachkin0fe5f952011-09-14 18:19:08 +0000725 sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
drh094b7582013-11-30 12:49:28 +0000726 if( pIdxKey->nField==0 ){
727 sqlite3DbFree(pCur->pKeyInfo->db, pFree);
728 return SQLITE_CORRUPT_BKPT;
729 }
danielk19773509a652009-07-06 18:56:13 +0000730 }else{
731 pIdxKey = 0;
732 }
733 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
dan42acb3e2011-09-05 20:16:38 +0000734 if( pFree ){
dan03e9cfc2011-09-05 14:20:27 +0000735 sqlite3DbFree(pCur->pKeyInfo->db, pFree);
danielk19773509a652009-07-06 18:56:13 +0000736 }
737 return rc;
738}
739
740/*
drh980b1a72006-08-16 16:42:48 +0000741** Restore the cursor to the position it was in (or as close to as possible)
742** when saveCursorPosition() was called. Note that this call deletes the
743** saved position info stored by saveCursorPosition(), so there can be
drha3460582008-07-11 21:02:53 +0000744** at most one effective restoreCursorPosition() call after each
drh980b1a72006-08-16 16:42:48 +0000745** saveCursorPosition().
drh980b1a72006-08-16 16:42:48 +0000746*/
danielk197730548662009-07-09 05:07:37 +0000747static int btreeRestoreCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000748 int rc;
drh1fee73e2007-08-29 04:00:57 +0000749 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +0000750 assert( pCur->eState>=CURSOR_REQUIRESEEK );
751 if( pCur->eState==CURSOR_FAULT ){
drh4c301aa2009-07-15 17:25:45 +0000752 return pCur->skipNext;
drhfb982642007-08-30 01:19:59 +0000753 }
drh980b1a72006-08-16 16:42:48 +0000754 pCur->eState = CURSOR_INVALID;
drh4c301aa2009-07-15 17:25:45 +0000755 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
drh980b1a72006-08-16 16:42:48 +0000756 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +0000757 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +0000758 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +0000759 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drh9b47ee32013-08-20 03:13:51 +0000760 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
761 pCur->eState = CURSOR_SKIPNEXT;
762 }
drh980b1a72006-08-16 16:42:48 +0000763 }
764 return rc;
765}
766
drha3460582008-07-11 21:02:53 +0000767#define restoreCursorPosition(p) \
drhfb982642007-08-30 01:19:59 +0000768 (p->eState>=CURSOR_REQUIRESEEK ? \
danielk197730548662009-07-09 05:07:37 +0000769 btreeRestoreCursorPosition(p) : \
drh16a9b832007-05-05 18:39:25 +0000770 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +0000771
drha3460582008-07-11 21:02:53 +0000772/*
drh6848dad2014-08-22 23:33:03 +0000773** Determine whether or not a cursor has moved from the position where
774** it was last placed, or has been invalidated for any other reason.
775** Cursors can move when the row they are pointing at is deleted out
776** from under them, for example. Cursor might also move if a btree
777** is rebalanced.
drha3460582008-07-11 21:02:53 +0000778**
drh6848dad2014-08-22 23:33:03 +0000779** Calling this routine with a NULL cursor pointer returns false.
drh86dd3712014-03-25 11:00:21 +0000780**
drh6848dad2014-08-22 23:33:03 +0000781** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
782** back to where it ought to be if this routine returns true.
drha3460582008-07-11 21:02:53 +0000783*/
drh6848dad2014-08-22 23:33:03 +0000784int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
drhc22284f2014-10-13 16:02:20 +0000785 return pCur->eState!=CURSOR_VALID;
drh6848dad2014-08-22 23:33:03 +0000786}
787
788/*
789** This routine restores a cursor back to its original position after it
790** has been moved by some outside activity (such as a btree rebalance or
791** a row having been deleted out from under the cursor).
792**
793** On success, the *pDifferentRow parameter is false if the cursor is left
794** pointing at exactly the same row. *pDifferntRow is the row the cursor
795** was pointing to has been deleted, forcing the cursor to point to some
796** nearby row.
797**
798** This routine should only be called for a cursor that just returned
799** TRUE from sqlite3BtreeCursorHasMoved().
800*/
801int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
drha3460582008-07-11 21:02:53 +0000802 int rc;
803
drh6848dad2014-08-22 23:33:03 +0000804 assert( pCur!=0 );
805 assert( pCur->eState!=CURSOR_VALID );
drha3460582008-07-11 21:02:53 +0000806 rc = restoreCursorPosition(pCur);
807 if( rc ){
drh6848dad2014-08-22 23:33:03 +0000808 *pDifferentRow = 1;
drha3460582008-07-11 21:02:53 +0000809 return rc;
810 }
drh9b47ee32013-08-20 03:13:51 +0000811 if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
drh6848dad2014-08-22 23:33:03 +0000812 *pDifferentRow = 1;
drha3460582008-07-11 21:02:53 +0000813 }else{
drh6848dad2014-08-22 23:33:03 +0000814 *pDifferentRow = 0;
drha3460582008-07-11 21:02:53 +0000815 }
816 return SQLITE_OK;
817}
818
danielk1977599fcba2004-11-08 07:13:13 +0000819#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000820/*
drha3152892007-05-05 11:48:52 +0000821** Given a page number of a regular database page, return the page
822** number for the pointer-map page that contains the entry for the
823** input page number.
drh5f77b2e2010-08-21 15:09:37 +0000824**
825** Return 0 (not a valid page) for pgno==1 since there is
826** no pointer map associated with page 1. The integrity_check logic
827** requires that ptrmapPageno(*,1)!=1.
danielk1977afcdd022004-10-31 16:25:42 +0000828*/
danielk1977266664d2006-02-10 08:24:21 +0000829static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
danielk197789d40042008-11-17 14:20:56 +0000830 int nPagesPerMapPage;
831 Pgno iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +0000832 assert( sqlite3_mutex_held(pBt->mutex) );
drh5f77b2e2010-08-21 15:09:37 +0000833 if( pgno<2 ) return 0;
drhd677b3d2007-08-20 22:48:41 +0000834 nPagesPerMapPage = (pBt->usableSize/5)+1;
835 iPtrMap = (pgno-2)/nPagesPerMapPage;
836 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +0000837 if( ret==PENDING_BYTE_PAGE(pBt) ){
838 ret++;
839 }
840 return ret;
841}
danielk1977a19df672004-11-03 11:37:07 +0000842
danielk1977afcdd022004-10-31 16:25:42 +0000843/*
danielk1977afcdd022004-10-31 16:25:42 +0000844** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000845**
846** This routine updates the pointer map entry for page number 'key'
847** so that it maps to type 'eType' and parent page number 'pgno'.
drh98add2e2009-07-20 17:11:49 +0000848**
849** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
850** a no-op. If an error occurs, the appropriate error code is written
851** into *pRC.
danielk1977afcdd022004-10-31 16:25:42 +0000852*/
drh98add2e2009-07-20 17:11:49 +0000853static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
danielk19773b8a05f2007-03-19 17:44:26 +0000854 DbPage *pDbPage; /* The pointer map page */
855 u8 *pPtrmap; /* The pointer map data */
856 Pgno iPtrmap; /* The pointer map page number */
857 int offset; /* Offset in pointer map page */
drh98add2e2009-07-20 17:11:49 +0000858 int rc; /* Return code from subfunctions */
859
860 if( *pRC ) return;
danielk1977afcdd022004-10-31 16:25:42 +0000861
drh1fee73e2007-08-29 04:00:57 +0000862 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977266664d2006-02-10 08:24:21 +0000863 /* The master-journal page number must never be used as a pointer map page */
864 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
865
danielk1977ac11ee62005-01-15 12:45:51 +0000866 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000867 if( key==0 ){
drh98add2e2009-07-20 17:11:49 +0000868 *pRC = SQLITE_CORRUPT_BKPT;
869 return;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000870 }
danielk1977266664d2006-02-10 08:24:21 +0000871 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000872 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977687566d2004-11-02 12:56:41 +0000873 if( rc!=SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +0000874 *pRC = rc;
875 return;
danielk1977afcdd022004-10-31 16:25:42 +0000876 }
danielk19778c666b12008-07-18 09:34:57 +0000877 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drhacfc72b2009-06-05 18:44:15 +0000878 if( offset<0 ){
drh98add2e2009-07-20 17:11:49 +0000879 *pRC = SQLITE_CORRUPT_BKPT;
drh4925a552009-07-07 11:39:58 +0000880 goto ptrmap_exit;
drhacfc72b2009-06-05 18:44:15 +0000881 }
drhfc243732011-05-17 15:21:56 +0000882 assert( offset <= (int)pBt->usableSize-5 );
danielk19773b8a05f2007-03-19 17:44:26 +0000883 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000884
drh615ae552005-01-16 23:21:00 +0000885 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
886 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
drh98add2e2009-07-20 17:11:49 +0000887 *pRC= rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000888 if( rc==SQLITE_OK ){
889 pPtrmap[offset] = eType;
890 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000891 }
danielk1977afcdd022004-10-31 16:25:42 +0000892 }
893
drh4925a552009-07-07 11:39:58 +0000894ptrmap_exit:
danielk19773b8a05f2007-03-19 17:44:26 +0000895 sqlite3PagerUnref(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000896}
897
898/*
899** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000900**
901** This routine retrieves the pointer map entry for page 'key', writing
902** the type and parent page number to *pEType and *pPgno respectively.
903** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000904*/
danielk1977aef0bf62005-12-30 16:28:01 +0000905static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000906 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000907 int iPtrmap; /* Pointer map page index */
908 u8 *pPtrmap; /* Pointer map page data */
909 int offset; /* Offset of entry in pointer map */
910 int rc;
911
drh1fee73e2007-08-29 04:00:57 +0000912 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000913
danielk1977266664d2006-02-10 08:24:21 +0000914 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000915 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000916 if( rc!=0 ){
917 return rc;
918 }
danielk19773b8a05f2007-03-19 17:44:26 +0000919 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000920
danielk19778c666b12008-07-18 09:34:57 +0000921 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drhfc243732011-05-17 15:21:56 +0000922 if( offset<0 ){
923 sqlite3PagerUnref(pDbPage);
924 return SQLITE_CORRUPT_BKPT;
925 }
926 assert( offset <= (int)pBt->usableSize-5 );
drh43617e92006-03-06 20:55:46 +0000927 assert( pEType!=0 );
928 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +0000929 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000930
danielk19773b8a05f2007-03-19 17:44:26 +0000931 sqlite3PagerUnref(pDbPage);
drh49285702005-09-17 15:20:26 +0000932 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000933 return SQLITE_OK;
934}
935
danielk197785d90ca2008-07-19 14:25:15 +0000936#else /* if defined SQLITE_OMIT_AUTOVACUUM */
drh98add2e2009-07-20 17:11:49 +0000937 #define ptrmapPut(w,x,y,z,rc)
danielk197785d90ca2008-07-19 14:25:15 +0000938 #define ptrmapGet(w,x,y,z) SQLITE_OK
drh98add2e2009-07-20 17:11:49 +0000939 #define ptrmapPutOvflPtr(x, y, rc)
danielk197785d90ca2008-07-19 14:25:15 +0000940#endif
danielk1977afcdd022004-10-31 16:25:42 +0000941
drh0d316a42002-08-11 20:10:47 +0000942/*
drh271efa52004-05-30 19:19:05 +0000943** Given a btree page and a cell index (0 means the first cell on
944** the page, 1 means the second cell, and so forth) return a pointer
945** to the cell content.
946**
947** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000948*/
drh1688c862008-07-18 02:44:17 +0000949#define findCell(P,I) \
drh3def2352011-11-11 00:27:15 +0000950 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
drh68f2a572011-06-03 17:50:49 +0000951#define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
952
drh43605152004-05-29 21:46:49 +0000953
954/*
drh93a960a2008-07-10 00:32:42 +0000955** This a more complex version of findCell() that works for
drh0a45c272009-07-08 01:49:11 +0000956** pages that do contain overflow cells.
drh43605152004-05-29 21:46:49 +0000957*/
958static u8 *findOverflowCell(MemPage *pPage, int iCell){
959 int i;
drh1fee73e2007-08-29 04:00:57 +0000960 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +0000961 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000962 int k;
drh2cbd78b2012-02-02 19:37:18 +0000963 k = pPage->aiOvfl[i];
drh6d08b4d2004-07-20 12:45:22 +0000964 if( k<=iCell ){
965 if( k==iCell ){
drh2cbd78b2012-02-02 19:37:18 +0000966 return pPage->apOvfl[i];
drh43605152004-05-29 21:46:49 +0000967 }
968 iCell--;
969 }
970 }
danielk19771cc5ed82007-05-16 17:28:43 +0000971 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000972}
973
974/*
975** Parse a cell content block and fill in the CellInfo structure. There
danielk197730548662009-07-09 05:07:37 +0000976** are two versions of this function. btreeParseCell() takes a
977** cell index as the second argument and btreeParseCellPtr()
drh16a9b832007-05-05 18:39:25 +0000978** takes a pointer to the body of the cell as its second argument.
drh43605152004-05-29 21:46:49 +0000979*/
danielk197730548662009-07-09 05:07:37 +0000980static void btreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000981 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000982 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000983 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000984){
drh3e28ff52014-09-24 00:59:08 +0000985 u8 *pIter; /* For scanning through pCell */
drh271efa52004-05-30 19:19:05 +0000986 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000987
drh1fee73e2007-08-29 04:00:57 +0000988 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhab01f612004-05-22 02:55:23 +0000989 assert( pPage->leaf==0 || pPage->leaf==1 );
drh3e28ff52014-09-24 00:59:08 +0000990 if( pPage->intKeyLeaf ){
991 assert( pPage->childPtrSize==0 );
992 pIter = pCell + getVarint32(pCell, nPayload);
drhab1cc582014-09-23 21:25:19 +0000993 pIter += getVarint(pIter, (u64*)&pInfo->nKey);
drh3e28ff52014-09-24 00:59:08 +0000994 }else if( pPage->noPayload ){
995 assert( pPage->childPtrSize==4 );
996 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
997 pInfo->nPayload = 0;
998 pInfo->nLocal = 0;
999 pInfo->iOverflow = 0;
1000 pInfo->pPayload = 0;
1001 return;
drh504b6982006-01-22 21:52:56 +00001002 }else{
drh3e28ff52014-09-24 00:59:08 +00001003 pIter = pCell + pPage->childPtrSize;
drhab1cc582014-09-23 21:25:19 +00001004 pIter += getVarint32(pIter, nPayload);
drh79df1f42008-07-18 00:57:33 +00001005 pInfo->nKey = nPayload;
drh6f11bef2004-05-13 01:12:56 +00001006 }
drh72365832007-03-06 15:53:44 +00001007 pInfo->nPayload = nPayload;
drhab1cc582014-09-23 21:25:19 +00001008 pInfo->pPayload = pIter;
drh0a45c272009-07-08 01:49:11 +00001009 testcase( nPayload==pPage->maxLocal );
1010 testcase( nPayload==pPage->maxLocal+1 );
drhab1cc582014-09-23 21:25:19 +00001011 if( nPayload<=pPage->maxLocal ){
drh271efa52004-05-30 19:19:05 +00001012 /* This is the (easy) common case where the entire payload fits
1013 ** on the local page. No overflow is required.
1014 */
drhab1cc582014-09-23 21:25:19 +00001015 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1016 if( pInfo->nSize<4 ) pInfo->nSize = 4;
drhf49661a2008-12-10 16:45:50 +00001017 pInfo->nLocal = (u16)nPayload;
drh6f11bef2004-05-13 01:12:56 +00001018 pInfo->iOverflow = 0;
drh6f11bef2004-05-13 01:12:56 +00001019 }else{
drh271efa52004-05-30 19:19:05 +00001020 /* If the payload will not fit completely on the local page, we have
1021 ** to decide how much to store locally and how much to spill onto
1022 ** overflow pages. The strategy is to minimize the amount of unused
1023 ** space on overflow pages while keeping the amount of local storage
1024 ** in between minLocal and maxLocal.
1025 **
1026 ** Warning: changing the way overflow payload is distributed in any
1027 ** way will result in an incompatible file format.
1028 */
1029 int minLocal; /* Minimum amount of payload held locally */
1030 int maxLocal; /* Maximum amount of payload held locally */
1031 int surplus; /* Overflow payload available for local storage */
1032
1033 minLocal = pPage->minLocal;
1034 maxLocal = pPage->maxLocal;
1035 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh0a45c272009-07-08 01:49:11 +00001036 testcase( surplus==maxLocal );
1037 testcase( surplus==maxLocal+1 );
drh6f11bef2004-05-13 01:12:56 +00001038 if( surplus <= maxLocal ){
drhf49661a2008-12-10 16:45:50 +00001039 pInfo->nLocal = (u16)surplus;
drh6f11bef2004-05-13 01:12:56 +00001040 }else{
drhf49661a2008-12-10 16:45:50 +00001041 pInfo->nLocal = (u16)minLocal;
drh6f11bef2004-05-13 01:12:56 +00001042 }
drhab1cc582014-09-23 21:25:19 +00001043 pInfo->iOverflow = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell);
drh6f11bef2004-05-13 01:12:56 +00001044 pInfo->nSize = pInfo->iOverflow + 4;
1045 }
drh3aac2dd2004-04-26 14:10:20 +00001046}
danielk197730548662009-07-09 05:07:37 +00001047static void btreeParseCell(
drh43605152004-05-29 21:46:49 +00001048 MemPage *pPage, /* Page containing the cell */
1049 int iCell, /* The cell index. First cell is 0 */
1050 CellInfo *pInfo /* Fill in this structure */
1051){
drhc4683832014-09-23 23:12:53 +00001052 btreeParseCellPtr(pPage, findCell(pPage, iCell), pInfo);
drh43605152004-05-29 21:46:49 +00001053}
drh3aac2dd2004-04-26 14:10:20 +00001054
1055/*
drh43605152004-05-29 21:46:49 +00001056** Compute the total number of bytes that a Cell needs in the cell
1057** data area of the btree-page. The return number includes the cell
1058** data header and the local payload, but not any overflow page or
1059** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +00001060*/
danielk1977ae5558b2009-04-29 11:31:47 +00001061static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
drh3f387402014-09-24 01:23:00 +00001062 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
1063 u8 *pEnd; /* End mark for a varint */
1064 u32 nSize; /* Size value to return */
danielk1977ae5558b2009-04-29 11:31:47 +00001065
1066#ifdef SQLITE_DEBUG
1067 /* The value returned by this function should always be the same as
1068 ** the (CellInfo.nSize) value found by doing a full parse of the
1069 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1070 ** this function verifies that this invariant is not violated. */
1071 CellInfo debuginfo;
danielk197730548662009-07-09 05:07:37 +00001072 btreeParseCellPtr(pPage, pCell, &debuginfo);
danielk1977ae5558b2009-04-29 11:31:47 +00001073#endif
1074
drh3e28ff52014-09-24 00:59:08 +00001075 if( pPage->noPayload ){
1076 pEnd = &pIter[9];
1077 while( (*pIter++)&0x80 && pIter<pEnd );
1078 assert( pPage->childPtrSize==4 );
1079 return (u16)(pIter - pCell);
drhdc41d602014-09-22 19:51:35 +00001080 }
drh3e28ff52014-09-24 00:59:08 +00001081 nSize = *pIter;
1082 if( nSize>=0x80 ){
1083 pEnd = &pIter[9];
1084 nSize &= 0x7f;
1085 do{
1086 nSize = (nSize<<7) | (*++pIter & 0x7f);
1087 }while( *(pIter)>=0x80 && pIter<pEnd );
1088 }
1089 pIter++;
drhdc41d602014-09-22 19:51:35 +00001090 if( pPage->intKey ){
danielk1977ae5558b2009-04-29 11:31:47 +00001091 /* pIter now points at the 64-bit integer key value, a variable length
1092 ** integer. The following block moves pIter to point at the first byte
1093 ** past the end of the key value. */
1094 pEnd = &pIter[9];
1095 while( (*pIter++)&0x80 && pIter<pEnd );
danielk1977ae5558b2009-04-29 11:31:47 +00001096 }
drh0a45c272009-07-08 01:49:11 +00001097 testcase( nSize==pPage->maxLocal );
1098 testcase( nSize==pPage->maxLocal+1 );
drh3e28ff52014-09-24 00:59:08 +00001099 if( nSize<=pPage->maxLocal ){
1100 nSize += (u32)(pIter - pCell);
1101 if( nSize<4 ) nSize = 4;
1102 }else{
danielk1977ae5558b2009-04-29 11:31:47 +00001103 int minLocal = pPage->minLocal;
1104 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
drh0a45c272009-07-08 01:49:11 +00001105 testcase( nSize==pPage->maxLocal );
1106 testcase( nSize==pPage->maxLocal+1 );
danielk1977ae5558b2009-04-29 11:31:47 +00001107 if( nSize>pPage->maxLocal ){
1108 nSize = minLocal;
1109 }
drh3e28ff52014-09-24 00:59:08 +00001110 nSize += 4 + (u16)(pIter - pCell);
danielk1977ae5558b2009-04-29 11:31:47 +00001111 }
drhdc41d602014-09-22 19:51:35 +00001112 assert( nSize==debuginfo.nSize || CORRUPT_DB );
shane60a4b532009-05-06 18:57:09 +00001113 return (u16)nSize;
danielk1977ae5558b2009-04-29 11:31:47 +00001114}
drh0ee3dbe2009-10-16 15:05:18 +00001115
1116#ifdef SQLITE_DEBUG
1117/* This variation on cellSizePtr() is used inside of assert() statements
1118** only. */
drha9121e42008-02-19 14:59:35 +00001119static u16 cellSize(MemPage *pPage, int iCell){
danielk1977ae5558b2009-04-29 11:31:47 +00001120 return cellSizePtr(pPage, findCell(pPage, iCell));
drh43605152004-05-29 21:46:49 +00001121}
danielk1977bc6ada42004-06-30 08:20:16 +00001122#endif
drh3b7511c2001-05-26 13:15:44 +00001123
danielk197779a40da2005-01-16 08:00:01 +00001124#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +00001125/*
danielk197726836652005-01-17 01:33:13 +00001126** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +00001127** to an overflow page, insert an entry into the pointer-map
1128** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +00001129*/
drh98add2e2009-07-20 17:11:49 +00001130static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
drhfa67c3c2008-07-11 02:21:40 +00001131 CellInfo info;
drh98add2e2009-07-20 17:11:49 +00001132 if( *pRC ) return;
drhfa67c3c2008-07-11 02:21:40 +00001133 assert( pCell!=0 );
danielk197730548662009-07-09 05:07:37 +00001134 btreeParseCellPtr(pPage, pCell, &info);
danielk19774dbaa892009-06-16 16:50:22 +00001135 if( info.iOverflow ){
drhfa67c3c2008-07-11 02:21:40 +00001136 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
drh98add2e2009-07-20 17:11:49 +00001137 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
danielk1977ac11ee62005-01-15 12:45:51 +00001138 }
danielk1977ac11ee62005-01-15 12:45:51 +00001139}
danielk197779a40da2005-01-16 08:00:01 +00001140#endif
1141
danielk1977ac11ee62005-01-15 12:45:51 +00001142
drhda200cc2004-05-09 11:51:38 +00001143/*
drh72f82862001-05-24 21:06:34 +00001144** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +00001145** end of the page and all free space is collected into one
1146** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +00001147** pointer array and the cell content area.
drhfdab0262014-11-20 15:30:50 +00001148**
1149** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
1150** b-tree page so that there are no freeblocks or fragment bytes, all
1151** unused bytes are contained in the unallocated space region, and all
1152** cells are packed tightly at the end of the page.
drh365d68f2001-05-11 11:02:46 +00001153*/
shane0af3f892008-11-12 04:55:34 +00001154static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +00001155 int i; /* Loop counter */
peter.d.reid60ec9142014-09-06 16:39:46 +00001156 int pc; /* Address of the i-th cell */
drh43605152004-05-29 21:46:49 +00001157 int hdr; /* Offset to the page header */
1158 int size; /* Size of a cell */
1159 int usableSize; /* Number of usable bytes on a page */
1160 int cellOffset; /* Offset to the cell pointer array */
drh281b21d2008-08-22 12:57:08 +00001161 int cbrk; /* Offset to the cell content area */
drh43605152004-05-29 21:46:49 +00001162 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +00001163 unsigned char *data; /* The page data */
1164 unsigned char *temp; /* Temp area for cell content */
drh588400b2014-09-27 05:00:25 +00001165 unsigned char *src; /* Source of content */
drh17146622009-07-07 17:38:38 +00001166 int iCellFirst; /* First allowable cell index */
1167 int iCellLast; /* Last possible cell index */
1168
drh2af926b2001-05-15 00:39:25 +00001169
danielk19773b8a05f2007-03-19 17:44:26 +00001170 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001171 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +00001172 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +00001173 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00001174 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh588400b2014-09-27 05:00:25 +00001175 temp = 0;
1176 src = data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +00001177 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001178 cellOffset = pPage->cellOffset;
1179 nCell = pPage->nCell;
1180 assert( nCell==get2byte(&data[hdr+3]) );
1181 usableSize = pPage->pBt->usableSize;
drh281b21d2008-08-22 12:57:08 +00001182 cbrk = usableSize;
drh17146622009-07-07 17:38:38 +00001183 iCellFirst = cellOffset + 2*nCell;
1184 iCellLast = usableSize - 4;
drh43605152004-05-29 21:46:49 +00001185 for(i=0; i<nCell; i++){
1186 u8 *pAddr; /* The i-th cell pointer */
1187 pAddr = &data[cellOffset + i*2];
1188 pc = get2byte(pAddr);
drh0a45c272009-07-08 01:49:11 +00001189 testcase( pc==iCellFirst );
1190 testcase( pc==iCellLast );
drh17146622009-07-07 17:38:38 +00001191#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
danielk197730548662009-07-09 05:07:37 +00001192 /* These conditions have already been verified in btreeInitPage()
drh17146622009-07-07 17:38:38 +00001193 ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
1194 */
1195 if( pc<iCellFirst || pc>iCellLast ){
shane0af3f892008-11-12 04:55:34 +00001196 return SQLITE_CORRUPT_BKPT;
1197 }
drh17146622009-07-07 17:38:38 +00001198#endif
1199 assert( pc>=iCellFirst && pc<=iCellLast );
drh588400b2014-09-27 05:00:25 +00001200 size = cellSizePtr(pPage, &src[pc]);
drh281b21d2008-08-22 12:57:08 +00001201 cbrk -= size;
drh17146622009-07-07 17:38:38 +00001202#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
1203 if( cbrk<iCellFirst ){
shane0af3f892008-11-12 04:55:34 +00001204 return SQLITE_CORRUPT_BKPT;
1205 }
drh17146622009-07-07 17:38:38 +00001206#else
1207 if( cbrk<iCellFirst || pc+size>usableSize ){
1208 return SQLITE_CORRUPT_BKPT;
1209 }
1210#endif
drh7157e1d2009-07-09 13:25:32 +00001211 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
drh0a45c272009-07-08 01:49:11 +00001212 testcase( cbrk+size==usableSize );
drh0a45c272009-07-08 01:49:11 +00001213 testcase( pc+size==usableSize );
drh281b21d2008-08-22 12:57:08 +00001214 put2byte(pAddr, cbrk);
drh588400b2014-09-27 05:00:25 +00001215 if( temp==0 ){
1216 int x;
1217 if( cbrk==pc ) continue;
1218 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1219 x = get2byte(&data[hdr+5]);
1220 memcpy(&temp[x], &data[x], (cbrk+size) - x);
1221 src = temp;
1222 }
1223 memcpy(&data[cbrk], &src[pc], size);
drh2af926b2001-05-15 00:39:25 +00001224 }
drh17146622009-07-07 17:38:38 +00001225 assert( cbrk>=iCellFirst );
drh281b21d2008-08-22 12:57:08 +00001226 put2byte(&data[hdr+5], cbrk);
drh43605152004-05-29 21:46:49 +00001227 data[hdr+1] = 0;
1228 data[hdr+2] = 0;
1229 data[hdr+7] = 0;
drh17146622009-07-07 17:38:38 +00001230 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
drhc5053fb2008-11-27 02:22:10 +00001231 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh17146622009-07-07 17:38:38 +00001232 if( cbrk-iCellFirst!=pPage->nFree ){
danielk1977360e6342008-11-12 08:49:51 +00001233 return SQLITE_CORRUPT_BKPT;
1234 }
shane0af3f892008-11-12 04:55:34 +00001235 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +00001236}
1237
drha059ad02001-04-17 20:09:11 +00001238/*
dan8e9ba0c2014-10-14 17:27:04 +00001239** Search the free-list on page pPg for space to store a cell nByte bytes in
1240** size. If one can be found, return a pointer to the space and remove it
1241** from the free-list.
1242**
1243** If no suitable space can be found on the free-list, return NULL.
1244**
drhba0f9992014-10-30 20:48:44 +00001245** This function may detect corruption within pPg. If corruption is
1246** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
dan61e94c92014-10-27 08:02:16 +00001247**
1248** If a slot of at least nByte bytes is found but cannot be used because
1249** there are already at least 60 fragmented bytes on the page, return NULL.
1250** In this case, if pbDefrag parameter is not NULL, set *pbDefrag to true.
dan8e9ba0c2014-10-14 17:27:04 +00001251*/
dan61e94c92014-10-27 08:02:16 +00001252static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc, int *pbDefrag){
dan8e9ba0c2014-10-14 17:27:04 +00001253 const int hdr = pPg->hdrOffset;
1254 u8 * const aData = pPg->aData;
1255 int iAddr;
1256 int pc;
1257 int usableSize = pPg->pBt->usableSize;
1258
1259 for(iAddr=hdr+1; (pc = get2byte(&aData[iAddr]))>0; iAddr=pc){
1260 int size; /* Size of the free slot */
drh113762a2014-11-19 16:36:25 +00001261 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
1262 ** increasing offset. */
dan8e9ba0c2014-10-14 17:27:04 +00001263 if( pc>usableSize-4 || pc<iAddr+4 ){
drhba0f9992014-10-30 20:48:44 +00001264 *pRc = SQLITE_CORRUPT_BKPT;
dan8e9ba0c2014-10-14 17:27:04 +00001265 return 0;
1266 }
drh113762a2014-11-19 16:36:25 +00001267 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
1268 ** freeblock form a big-endian integer which is the size of the freeblock
1269 ** in bytes, including the 4-byte header. */
dan8e9ba0c2014-10-14 17:27:04 +00001270 size = get2byte(&aData[pc+2]);
1271 if( size>=nByte ){
1272 int x = size - nByte;
1273 testcase( x==4 );
1274 testcase( x==3 );
1275 if( x<4 ){
drhfdab0262014-11-20 15:30:50 +00001276 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
1277 ** number of bytes in fragments may not exceed 60. */
dan61e94c92014-10-27 08:02:16 +00001278 if( aData[hdr+7]>=60 ){
1279 if( pbDefrag ) *pbDefrag = 1;
1280 return 0;
1281 }
dan8e9ba0c2014-10-14 17:27:04 +00001282 /* Remove the slot from the free-list. Update the number of
1283 ** fragmented bytes within the page. */
1284 memcpy(&aData[iAddr], &aData[pc], 2);
1285 aData[hdr+7] += (u8)x;
1286 }else if( size+pc > usableSize ){
drhba0f9992014-10-30 20:48:44 +00001287 *pRc = SQLITE_CORRUPT_BKPT;
dan8e9ba0c2014-10-14 17:27:04 +00001288 return 0;
1289 }else{
1290 /* The slot remains on the free-list. Reduce its size to account
1291 ** for the portion used by the new allocation. */
1292 put2byte(&aData[pc+2], x);
1293 }
1294 return &aData[pc + x];
1295 }
1296 }
1297
1298 return 0;
1299}
1300
1301/*
danielk19776011a752009-04-01 16:25:32 +00001302** Allocate nByte bytes of space from within the B-Tree page passed
drh0a45c272009-07-08 01:49:11 +00001303** as the first argument. Write into *pIdx the index into pPage->aData[]
1304** of the first byte of allocated space. Return either SQLITE_OK or
1305** an error code (usually SQLITE_CORRUPT).
drhbd03cae2001-06-02 02:40:57 +00001306**
drh0a45c272009-07-08 01:49:11 +00001307** The caller guarantees that there is sufficient space to make the
1308** allocation. This routine might need to defragment in order to bring
1309** all the space together, however. This routine will avoid using
1310** the first two bytes past the cell pointer area since presumably this
1311** allocation is being made in order to insert a new cell, so we will
1312** also end up needing a new cell pointer.
drh7e3b0a02001-04-28 16:52:40 +00001313*/
drh0a45c272009-07-08 01:49:11 +00001314static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
danielk19776011a752009-04-01 16:25:32 +00001315 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1316 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
drh0a45c272009-07-08 01:49:11 +00001317 int top; /* First byte of cell content area */
drhfefa0942014-11-05 21:21:08 +00001318 int rc = SQLITE_OK; /* Integer return code */
drh0a45c272009-07-08 01:49:11 +00001319 int gap; /* First byte of gap between cell pointers and cell content */
drh43605152004-05-29 21:46:49 +00001320
danielk19773b8a05f2007-03-19 17:44:26 +00001321 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001322 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +00001323 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa67c3c2008-07-11 02:21:40 +00001324 assert( nByte>=0 ); /* Minimum cell size is 4 */
1325 assert( pPage->nFree>=nByte );
1326 assert( pPage->nOverflow==0 );
mistachkina95d8ca2014-10-27 19:42:02 +00001327 assert( nByte < (int)(pPage->pBt->usableSize-8) );
drh43605152004-05-29 21:46:49 +00001328
drh0a45c272009-07-08 01:49:11 +00001329 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1330 gap = pPage->cellOffset + 2*pPage->nCell;
drh75b31dc2014-08-20 00:54:46 +00001331 assert( gap<=65536 );
drhfdab0262014-11-20 15:30:50 +00001332 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
1333 ** and the reserved space is zero (the usual value for reserved space)
1334 ** then the cell content offset of an empty page wants to be 65536.
1335 ** However, that integer is too large to be stored in a 2-byte unsigned
1336 ** integer, so a value of 0 is used in its place. */
1337 top = get2byteNotZero(&data[hdr+5]);
1338 if( gap>top ) return SQLITE_CORRUPT_BKPT;
drh4c04f3c2014-08-20 11:56:14 +00001339
1340 /* If there is enough space between gap and top for one more cell pointer
1341 ** array entry offset, and if the freelist is not empty, then search the
1342 ** freelist looking for a free slot big enough to satisfy the request.
1343 */
drh0a45c272009-07-08 01:49:11 +00001344 testcase( gap+2==top );
1345 testcase( gap+1==top );
1346 testcase( gap==top );
drh4c04f3c2014-08-20 11:56:14 +00001347 if( gap+2<=top && (data[hdr+1] || data[hdr+2]) ){
dan61e94c92014-10-27 08:02:16 +00001348 int bDefrag = 0;
1349 u8 *pSpace = pageFindSlot(pPage, nByte, &rc, &bDefrag);
dan8e9ba0c2014-10-14 17:27:04 +00001350 if( rc ) return rc;
dan61e94c92014-10-27 08:02:16 +00001351 if( bDefrag ) goto defragment_page;
dan8e9ba0c2014-10-14 17:27:04 +00001352 if( pSpace ){
drhfefa0942014-11-05 21:21:08 +00001353 assert( pSpace>=data && (pSpace - data)<65536 );
1354 *pIdx = (int)(pSpace - data);
dan8e9ba0c2014-10-14 17:27:04 +00001355 return SQLITE_OK;
drh9e572e62004-04-23 23:43:10 +00001356 }
1357 }
drh43605152004-05-29 21:46:49 +00001358
drh4c04f3c2014-08-20 11:56:14 +00001359 /* The request could not be fulfilled using a freelist slot. Check
1360 ** to see if defragmentation is necessary.
drh0a45c272009-07-08 01:49:11 +00001361 */
1362 testcase( gap+2+nByte==top );
1363 if( gap+2+nByte>top ){
dan61e94c92014-10-27 08:02:16 +00001364 defragment_page:
drh1fd2d7d2014-12-02 16:16:47 +00001365 assert( pPage->nCell>0 || CORRUPT_DB );
drh0a45c272009-07-08 01:49:11 +00001366 rc = defragmentPage(pPage);
1367 if( rc ) return rc;
drh5d433ce2010-08-14 16:02:52 +00001368 top = get2byteNotZero(&data[hdr+5]);
drh0a45c272009-07-08 01:49:11 +00001369 assert( gap+nByte<=top );
1370 }
1371
1372
drh43605152004-05-29 21:46:49 +00001373 /* Allocate memory from the gap in between the cell pointer array
drhc314dc72009-07-21 11:52:34 +00001374 ** and the cell content area. The btreeInitPage() call has already
1375 ** validated the freelist. Given that the freelist is valid, there
1376 ** is no way that the allocation can extend off the end of the page.
1377 ** The assert() below verifies the previous sentence.
drh43605152004-05-29 21:46:49 +00001378 */
drh0a45c272009-07-08 01:49:11 +00001379 top -= nByte;
drh43605152004-05-29 21:46:49 +00001380 put2byte(&data[hdr+5], top);
drhfcd71b62011-04-05 22:08:24 +00001381 assert( top+nByte <= (int)pPage->pBt->usableSize );
drh0a45c272009-07-08 01:49:11 +00001382 *pIdx = top;
1383 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001384}
1385
1386/*
drh9e572e62004-04-23 23:43:10 +00001387** Return a section of the pPage->aData to the freelist.
drh7fb91642014-08-20 14:37:09 +00001388** The first byte of the new free block is pPage->aData[iStart]
1389** and the size of the block is iSize bytes.
drh306dc212001-05-21 13:45:10 +00001390**
drh5f5c7532014-08-20 17:56:27 +00001391** Adjacent freeblocks are coalesced.
1392**
1393** Note that even though the freeblock list was checked by btreeInitPage(),
1394** that routine will not detect overlap between cells or freeblocks. Nor
1395** does it detect cells or freeblocks that encrouch into the reserved bytes
1396** at the end of the page. So do additional corruption checks inside this
1397** routine and return SQLITE_CORRUPT if any problems are found.
drh7e3b0a02001-04-28 16:52:40 +00001398*/
drh5f5c7532014-08-20 17:56:27 +00001399static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
drh3f387402014-09-24 01:23:00 +00001400 u16 iPtr; /* Address of ptr to next freeblock */
drh5f5c7532014-08-20 17:56:27 +00001401 u16 iFreeBlk; /* Address of the next freeblock */
1402 u8 hdr; /* Page header size. 0 or 100 */
1403 u8 nFrag = 0; /* Reduction in fragmentation */
1404 u16 iOrigSize = iSize; /* Original value of iSize */
1405 u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
1406 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
drh7fb91642014-08-20 14:37:09 +00001407 unsigned char *data = pPage->aData; /* Page content */
drh2af926b2001-05-15 00:39:25 +00001408
drh9e572e62004-04-23 23:43:10 +00001409 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001410 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh7fb91642014-08-20 14:37:09 +00001411 assert( iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
dan23eba452014-10-24 18:43:57 +00001412 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +00001413 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh7fb91642014-08-20 14:37:09 +00001414 assert( iSize>=4 ); /* Minimum cell size is 4 */
drh5f5c7532014-08-20 17:56:27 +00001415 assert( iStart<=iLast );
drh9e572e62004-04-23 23:43:10 +00001416
drh5f5c7532014-08-20 17:56:27 +00001417 /* Overwrite deleted information with zeros when the secure_delete
1418 ** option is enabled */
drhc9166342012-01-05 23:32:06 +00001419 if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
drh7fb91642014-08-20 14:37:09 +00001420 memset(&data[iStart], 0, iSize);
drh5b47efa2010-02-12 18:18:39 +00001421 }
drhfcce93f2006-02-22 03:08:32 +00001422
drh5f5c7532014-08-20 17:56:27 +00001423 /* The list of freeblocks must be in ascending order. Find the
1424 ** spot on the list where iStart should be inserted.
drh0a45c272009-07-08 01:49:11 +00001425 */
drh43605152004-05-29 21:46:49 +00001426 hdr = pPage->hdrOffset;
drh7fb91642014-08-20 14:37:09 +00001427 iPtr = hdr + 1;
drh7bc4c452014-08-20 18:43:44 +00001428 if( data[iPtr+1]==0 && data[iPtr]==0 ){
1429 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
1430 }else{
1431 while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
1432 if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
1433 iPtr = iFreeBlk;
drh9e572e62004-04-23 23:43:10 +00001434 }
drh7bc4c452014-08-20 18:43:44 +00001435 if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
1436 assert( iFreeBlk>iPtr || iFreeBlk==0 );
1437
1438 /* At this point:
1439 ** iFreeBlk: First freeblock after iStart, or zero if none
1440 ** iPtr: The address of a pointer iFreeBlk
1441 **
1442 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
1443 */
1444 if( iFreeBlk && iEnd+3>=iFreeBlk ){
1445 nFrag = iFreeBlk - iEnd;
1446 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
1447 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
1448 iSize = iEnd - iStart;
1449 iFreeBlk = get2byte(&data[iFreeBlk]);
1450 }
1451
drh3f387402014-09-24 01:23:00 +00001452 /* If iPtr is another freeblock (that is, if iPtr is not the freelist
1453 ** pointer in the page header) then check to see if iStart should be
1454 ** coalesced onto the end of iPtr.
drh7bc4c452014-08-20 18:43:44 +00001455 */
1456 if( iPtr>hdr+1 ){
1457 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
1458 if( iPtrEnd+3>=iStart ){
1459 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
1460 nFrag += iStart - iPtrEnd;
1461 iSize = iEnd - iPtr;
1462 iStart = iPtr;
1463 }
1464 }
1465 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
1466 data[hdr+7] -= nFrag;
drh9e572e62004-04-23 23:43:10 +00001467 }
drh7bc4c452014-08-20 18:43:44 +00001468 if( iStart==get2byte(&data[hdr+5]) ){
drh5f5c7532014-08-20 17:56:27 +00001469 /* The new freeblock is at the beginning of the cell content area,
1470 ** so just extend the cell content area rather than create another
1471 ** freelist entry */
drh7bc4c452014-08-20 18:43:44 +00001472 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
drh5f5c7532014-08-20 17:56:27 +00001473 put2byte(&data[hdr+1], iFreeBlk);
1474 put2byte(&data[hdr+5], iEnd);
1475 }else{
1476 /* Insert the new freeblock into the freelist */
1477 put2byte(&data[iPtr], iStart);
1478 put2byte(&data[iStart], iFreeBlk);
1479 put2byte(&data[iStart+2], iSize);
drh4b70f112004-05-02 21:12:19 +00001480 }
drh5f5c7532014-08-20 17:56:27 +00001481 pPage->nFree += iOrigSize;
shanedcc50b72008-11-13 18:29:50 +00001482 return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00001483}
1484
1485/*
drh271efa52004-05-30 19:19:05 +00001486** Decode the flags byte (the first byte of the header) for a page
1487** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +00001488**
1489** Only the following combinations are supported. Anything different
1490** indicates a corrupt database files:
1491**
1492** PTF_ZERODATA
1493** PTF_ZERODATA | PTF_LEAF
1494** PTF_LEAFDATA | PTF_INTKEY
1495** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
drh271efa52004-05-30 19:19:05 +00001496*/
drh44845222008-07-17 18:39:57 +00001497static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +00001498 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +00001499
1500 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +00001501 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00001502 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
drh44845222008-07-17 18:39:57 +00001503 flagByte &= ~PTF_LEAF;
1504 pPage->childPtrSize = 4-4*pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001505 pBt = pPage->pBt;
drh44845222008-07-17 18:39:57 +00001506 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
drhfdab0262014-11-20 15:30:50 +00001507 /* EVIDENCE-OF: R-03640-13415 A value of 5 means the page is an interior
1508 ** table b-tree page. */
1509 assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
1510 /* EVIDENCE-OF: R-20501-61796 A value of 13 means the page is a leaf
1511 ** table b-tree page. */
1512 assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
drh44845222008-07-17 18:39:57 +00001513 pPage->intKey = 1;
drh3e28ff52014-09-24 00:59:08 +00001514 pPage->intKeyLeaf = pPage->leaf;
1515 pPage->noPayload = !pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001516 pPage->maxLocal = pBt->maxLeaf;
1517 pPage->minLocal = pBt->minLeaf;
drh44845222008-07-17 18:39:57 +00001518 }else if( flagByte==PTF_ZERODATA ){
drhfdab0262014-11-20 15:30:50 +00001519 /* EVIDENCE-OF: R-27225-53936 A value of 2 means the page is an interior
1520 ** index b-tree page. */
1521 assert( (PTF_ZERODATA)==2 );
1522 /* EVIDENCE-OF: R-16571-11615 A value of 10 means the page is a leaf
1523 ** index b-tree page. */
1524 assert( (PTF_ZERODATA|PTF_LEAF)==10 );
drh44845222008-07-17 18:39:57 +00001525 pPage->intKey = 0;
drh3e28ff52014-09-24 00:59:08 +00001526 pPage->intKeyLeaf = 0;
1527 pPage->noPayload = 0;
drh271efa52004-05-30 19:19:05 +00001528 pPage->maxLocal = pBt->maxLocal;
1529 pPage->minLocal = pBt->minLocal;
drh44845222008-07-17 18:39:57 +00001530 }else{
drhfdab0262014-11-20 15:30:50 +00001531 /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
1532 ** an error. */
drh44845222008-07-17 18:39:57 +00001533 return SQLITE_CORRUPT_BKPT;
drh271efa52004-05-30 19:19:05 +00001534 }
drhc9166342012-01-05 23:32:06 +00001535 pPage->max1bytePayload = pBt->max1bytePayload;
drh44845222008-07-17 18:39:57 +00001536 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +00001537}
1538
1539/*
drh7e3b0a02001-04-28 16:52:40 +00001540** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001541**
1542** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001543** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001544** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1545** guarantee that the page is well-formed. It only shows that
1546** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001547*/
danielk197730548662009-07-09 05:07:37 +00001548static int btreeInitPage(MemPage *pPage){
drh2af926b2001-05-15 00:39:25 +00001549
danielk197771d5d2c2008-09-29 11:49:47 +00001550 assert( pPage->pBt!=0 );
1551 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001552 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +00001553 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1554 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00001555
1556 if( !pPage->isInit ){
drhf49661a2008-12-10 16:45:50 +00001557 u16 pc; /* Address of a freeblock within pPage->aData[] */
1558 u8 hdr; /* Offset to beginning of page header */
danielk197771d5d2c2008-09-29 11:49:47 +00001559 u8 *data; /* Equal to pPage->aData */
1560 BtShared *pBt; /* The main btree structure */
drhb2eced52010-08-12 02:41:12 +00001561 int usableSize; /* Amount of usable space on each page */
shaneh1df2db72010-08-18 02:28:48 +00001562 u16 cellOffset; /* Offset from start of page to first cell pointer */
drhb2eced52010-08-12 02:41:12 +00001563 int nFree; /* Number of unused bytes on the page */
1564 int top; /* First byte of the cell content area */
drh0a45c272009-07-08 01:49:11 +00001565 int iCellFirst; /* First allowable cell or freeblock offset */
1566 int iCellLast; /* Last possible cell or freeblock offset */
danielk197771d5d2c2008-09-29 11:49:47 +00001567
1568 pBt = pPage->pBt;
1569
danielk1977eaa06f62008-09-18 17:34:44 +00001570 hdr = pPage->hdrOffset;
1571 data = pPage->aData;
drhfdab0262014-11-20 15:30:50 +00001572 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
1573 ** the b-tree page type. */
danielk1977eaa06f62008-09-18 17:34:44 +00001574 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
drhb2eced52010-08-12 02:41:12 +00001575 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
1576 pPage->maskPage = (u16)(pBt->pageSize - 1);
danielk1977eaa06f62008-09-18 17:34:44 +00001577 pPage->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00001578 usableSize = pBt->usableSize;
drhfdab0262014-11-20 15:30:50 +00001579 pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
drh3def2352011-11-11 00:27:15 +00001580 pPage->aDataEnd = &data[usableSize];
1581 pPage->aCellIdx = &data[cellOffset];
drhfdab0262014-11-20 15:30:50 +00001582 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
1583 ** the start of the cell content area. A zero value for this integer is
1584 ** interpreted as 65536. */
drh5d433ce2010-08-14 16:02:52 +00001585 top = get2byteNotZero(&data[hdr+5]);
drhfdab0262014-11-20 15:30:50 +00001586 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
1587 ** number of cells on the page. */
danielk1977eaa06f62008-09-18 17:34:44 +00001588 pPage->nCell = get2byte(&data[hdr+3]);
1589 if( pPage->nCell>MX_CELL(pBt) ){
1590 /* To many cells for a single page. The page must be corrupt */
1591 return SQLITE_CORRUPT_BKPT;
1592 }
drhb908d762009-07-08 16:54:40 +00001593 testcase( pPage->nCell==MX_CELL(pBt) );
drhfdab0262014-11-20 15:30:50 +00001594 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
1595 ** possible for a root page of a table that contains no rows) then the
1596 ** offset to the cell content area will equal the page size minus the
1597 ** bytes of reserved space. */
1598 assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
drh69e931e2009-06-03 21:04:35 +00001599
shane5eff7cf2009-08-10 03:57:58 +00001600 /* A malformed database page might cause us to read past the end
drh69e931e2009-06-03 21:04:35 +00001601 ** of page when parsing a cell.
1602 **
1603 ** The following block of code checks early to see if a cell extends
1604 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
1605 ** returned if it does.
1606 */
drh0a45c272009-07-08 01:49:11 +00001607 iCellFirst = cellOffset + 2*pPage->nCell;
1608 iCellLast = usableSize - 4;
drh3b2a3fa2009-06-09 13:42:24 +00001609#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
drh69e931e2009-06-03 21:04:35 +00001610 {
drh69e931e2009-06-03 21:04:35 +00001611 int i; /* Index into the cell pointer array */
1612 int sz; /* Size of a cell */
1613
drh69e931e2009-06-03 21:04:35 +00001614 if( !pPage->leaf ) iCellLast--;
1615 for(i=0; i<pPage->nCell; i++){
1616 pc = get2byte(&data[cellOffset+i*2]);
drh0a45c272009-07-08 01:49:11 +00001617 testcase( pc==iCellFirst );
1618 testcase( pc==iCellLast );
drh69e931e2009-06-03 21:04:35 +00001619 if( pc<iCellFirst || pc>iCellLast ){
1620 return SQLITE_CORRUPT_BKPT;
1621 }
1622 sz = cellSizePtr(pPage, &data[pc]);
drh0a45c272009-07-08 01:49:11 +00001623 testcase( pc+sz==usableSize );
drh69e931e2009-06-03 21:04:35 +00001624 if( pc+sz>usableSize ){
1625 return SQLITE_CORRUPT_BKPT;
1626 }
1627 }
drh0a45c272009-07-08 01:49:11 +00001628 if( !pPage->leaf ) iCellLast++;
drh69e931e2009-06-03 21:04:35 +00001629 }
1630#endif
1631
drhfdab0262014-11-20 15:30:50 +00001632 /* Compute the total free space on the page
1633 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
1634 ** start of the first freeblock on the page, or is zero if there are no
1635 ** freeblocks. */
danielk1977eaa06f62008-09-18 17:34:44 +00001636 pc = get2byte(&data[hdr+1]);
drhfdab0262014-11-20 15:30:50 +00001637 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
danielk1977eaa06f62008-09-18 17:34:44 +00001638 while( pc>0 ){
drh1bd10f82008-12-10 21:19:56 +00001639 u16 next, size;
drh0a45c272009-07-08 01:49:11 +00001640 if( pc<iCellFirst || pc>iCellLast ){
drhfdab0262014-11-20 15:30:50 +00001641 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
1642 ** always be at least one cell before the first freeblock.
1643 **
1644 ** Or, the freeblock is off the end of the page
1645 */
danielk1977eaa06f62008-09-18 17:34:44 +00001646 return SQLITE_CORRUPT_BKPT;
1647 }
1648 next = get2byte(&data[pc]);
1649 size = get2byte(&data[pc+2]);
dan4361e792009-08-14 17:01:22 +00001650 if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
1651 /* Free blocks must be in ascending order. And the last byte of
drhf2f105d2012-08-20 15:53:54 +00001652 ** the free-block must lie on the database page. */
danielk1977eaa06f62008-09-18 17:34:44 +00001653 return SQLITE_CORRUPT_BKPT;
1654 }
shane85095702009-06-15 16:27:08 +00001655 nFree = nFree + size;
danielk1977eaa06f62008-09-18 17:34:44 +00001656 pc = next;
1657 }
danielk197793c829c2009-06-03 17:26:17 +00001658
1659 /* At this point, nFree contains the sum of the offset to the start
1660 ** of the cell-content area plus the number of free bytes within
1661 ** the cell-content area. If this is greater than the usable-size
1662 ** of the page, then the page must be corrupted. This check also
1663 ** serves to verify that the offset to the start of the cell-content
1664 ** area, according to the page header, lies within the page.
1665 */
1666 if( nFree>usableSize ){
drh49285702005-09-17 15:20:26 +00001667 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001668 }
shane5eff7cf2009-08-10 03:57:58 +00001669 pPage->nFree = (u16)(nFree - iCellFirst);
danielk197771d5d2c2008-09-29 11:49:47 +00001670 pPage->isInit = 1;
1671 }
drh9e572e62004-04-23 23:43:10 +00001672 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001673}
1674
1675/*
drh8b2f49b2001-06-08 00:21:52 +00001676** Set up a raw page so that it looks like a database page holding
1677** no entries.
drhbd03cae2001-06-02 02:40:57 +00001678*/
drh9e572e62004-04-23 23:43:10 +00001679static void zeroPage(MemPage *pPage, int flags){
1680 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001681 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00001682 u8 hdr = pPage->hdrOffset;
1683 u16 first;
drh9e572e62004-04-23 23:43:10 +00001684
danielk19773b8a05f2007-03-19 17:44:26 +00001685 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +00001686 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1687 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00001688 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00001689 assert( sqlite3_mutex_held(pBt->mutex) );
drhc9166342012-01-05 23:32:06 +00001690 if( pBt->btsFlags & BTS_SECURE_DELETE ){
drh5b47efa2010-02-12 18:18:39 +00001691 memset(&data[hdr], 0, pBt->usableSize - hdr);
1692 }
drh1bd10f82008-12-10 21:19:56 +00001693 data[hdr] = (char)flags;
drhfe485992014-02-12 23:52:16 +00001694 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
drh43605152004-05-29 21:46:49 +00001695 memset(&data[hdr+1], 0, 4);
1696 data[hdr+7] = 0;
1697 put2byte(&data[hdr+5], pBt->usableSize);
shaneh1df2db72010-08-18 02:28:48 +00001698 pPage->nFree = (u16)(pBt->usableSize - first);
drh271efa52004-05-30 19:19:05 +00001699 decodeFlags(pPage, flags);
drh43605152004-05-29 21:46:49 +00001700 pPage->cellOffset = first;
drh3def2352011-11-11 00:27:15 +00001701 pPage->aDataEnd = &data[pBt->usableSize];
1702 pPage->aCellIdx = &data[first];
drh43605152004-05-29 21:46:49 +00001703 pPage->nOverflow = 0;
drhb2eced52010-08-12 02:41:12 +00001704 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
1705 pPage->maskPage = (u16)(pBt->pageSize - 1);
drh43605152004-05-29 21:46:49 +00001706 pPage->nCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001707 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00001708}
1709
drh897a8202008-09-18 01:08:15 +00001710
1711/*
1712** Convert a DbPage obtained from the pager into a MemPage used by
1713** the btree layer.
1714*/
1715static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
1716 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
1717 pPage->aData = sqlite3PagerGetData(pDbPage);
1718 pPage->pDbPage = pDbPage;
1719 pPage->pBt = pBt;
1720 pPage->pgno = pgno;
1721 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
1722 return pPage;
1723}
1724
drhbd03cae2001-06-02 02:40:57 +00001725/*
drh3aac2dd2004-04-26 14:10:20 +00001726** Get a page from the pager. Initialize the MemPage.pBt and
1727** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +00001728**
1729** If the noContent flag is set, it means that we do not care about
1730** the content of the page at this time. So do not go to the disk
1731** to fetch the content. Just fill in the content with zeros for now.
1732** If in the future we call sqlite3PagerWrite() on this page, that
1733** means we have started to be concerned about content and the disk
1734** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00001735*/
danielk197730548662009-07-09 05:07:37 +00001736static int btreeGetPage(
drh16a9b832007-05-05 18:39:25 +00001737 BtShared *pBt, /* The btree */
1738 Pgno pgno, /* Number of the page to fetch */
1739 MemPage **ppPage, /* Return the page in this parameter */
drhb00fc3b2013-08-21 23:42:32 +00001740 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
drh16a9b832007-05-05 18:39:25 +00001741){
drh3aac2dd2004-04-26 14:10:20 +00001742 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001743 DbPage *pDbPage;
1744
drhb00fc3b2013-08-21 23:42:32 +00001745 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
drh1fee73e2007-08-29 04:00:57 +00001746 assert( sqlite3_mutex_held(pBt->mutex) );
dan11dcd112013-03-15 18:29:18 +00001747 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
drh3aac2dd2004-04-26 14:10:20 +00001748 if( rc ) return rc;
drh897a8202008-09-18 01:08:15 +00001749 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
drh3aac2dd2004-04-26 14:10:20 +00001750 return SQLITE_OK;
1751}
1752
1753/*
danielk1977bea2a942009-01-20 17:06:27 +00001754** Retrieve a page from the pager cache. If the requested page is not
1755** already in the pager cache return NULL. Initialize the MemPage.pBt and
1756** MemPage.aData elements if needed.
1757*/
1758static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
1759 DbPage *pDbPage;
1760 assert( sqlite3_mutex_held(pBt->mutex) );
1761 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
1762 if( pDbPage ){
1763 return btreePageFromDbPage(pDbPage, pgno, pBt);
1764 }
1765 return 0;
1766}
1767
1768/*
danielk197789d40042008-11-17 14:20:56 +00001769** Return the size of the database file in pages. If there is any kind of
1770** error, return ((unsigned int)-1).
danielk197767fd7a92008-09-10 17:53:35 +00001771*/
drhb1299152010-03-30 22:58:33 +00001772static Pgno btreePagecount(BtShared *pBt){
1773 return pBt->nPage;
1774}
1775u32 sqlite3BtreeLastPage(Btree *p){
1776 assert( sqlite3BtreeHoldsMutex(p) );
1777 assert( ((p->pBt->nPage)&0x8000000)==0 );
drheac5bd72014-07-25 21:35:39 +00001778 return btreePagecount(p->pBt);
danielk197767fd7a92008-09-10 17:53:35 +00001779}
1780
1781/*
danielk197789bc4bc2009-07-21 19:25:24 +00001782** Get a page from the pager and initialize it. This routine is just a
1783** convenience wrapper around separate calls to btreeGetPage() and
1784** btreeInitPage().
1785**
1786** If an error occurs, then the value *ppPage is set to is undefined. It
1787** may remain unchanged, or it may be set to an invalid value.
drhde647132004-05-07 17:57:49 +00001788*/
1789static int getAndInitPage(
dan11dcd112013-03-15 18:29:18 +00001790 BtShared *pBt, /* The database file */
1791 Pgno pgno, /* Number of the page to get */
1792 MemPage **ppPage, /* Write the page pointer here */
drhb00fc3b2013-08-21 23:42:32 +00001793 int bReadonly /* PAGER_GET_READONLY or 0 */
drhde647132004-05-07 17:57:49 +00001794){
1795 int rc;
drh1fee73e2007-08-29 04:00:57 +00001796 assert( sqlite3_mutex_held(pBt->mutex) );
drhb00fc3b2013-08-21 23:42:32 +00001797 assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
danielk197789bc4bc2009-07-21 19:25:24 +00001798
danba3cbf32010-06-30 04:29:03 +00001799 if( pgno>btreePagecount(pBt) ){
1800 rc = SQLITE_CORRUPT_BKPT;
1801 }else{
drhb00fc3b2013-08-21 23:42:32 +00001802 rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
drh29f2bad2013-12-09 01:04:54 +00001803 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
danba3cbf32010-06-30 04:29:03 +00001804 rc = btreeInitPage(*ppPage);
1805 if( rc!=SQLITE_OK ){
1806 releasePage(*ppPage);
1807 }
danielk197789bc4bc2009-07-21 19:25:24 +00001808 }
drhee696e22004-08-30 16:52:17 +00001809 }
danba3cbf32010-06-30 04:29:03 +00001810
1811 testcase( pgno==0 );
1812 assert( pgno!=0 || rc==SQLITE_CORRUPT );
drhde647132004-05-07 17:57:49 +00001813 return rc;
1814}
1815
1816/*
drh3aac2dd2004-04-26 14:10:20 +00001817** Release a MemPage. This should be called once for each prior
danielk197730548662009-07-09 05:07:37 +00001818** call to btreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00001819*/
drh4b70f112004-05-02 21:12:19 +00001820static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001821 if( pPage ){
1822 assert( pPage->aData );
1823 assert( pPage->pBt );
drhda8a3302013-12-13 19:35:21 +00001824 assert( pPage->pDbPage!=0 );
drhbf4bca52007-09-06 22:19:14 +00001825 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1826 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
drh1fee73e2007-08-29 04:00:57 +00001827 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda8a3302013-12-13 19:35:21 +00001828 sqlite3PagerUnrefNotNull(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00001829 }
1830}
1831
1832/*
drha6abd042004-06-09 17:37:22 +00001833** During a rollback, when the pager reloads information into the cache
1834** so that the cache is restored to its original state at the start of
1835** the transaction, for each page restored this routine is called.
1836**
1837** This routine needs to reset the extra data section at the end of the
1838** page to agree with the restored data.
1839*/
danielk1977eaa06f62008-09-18 17:34:44 +00001840static void pageReinit(DbPage *pData){
drh07d183d2005-05-01 22:52:42 +00001841 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00001842 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
danielk1977d217e6f2009-04-01 17:13:51 +00001843 assert( sqlite3PagerPageRefcount(pData)>0 );
danielk197771d5d2c2008-09-29 11:49:47 +00001844 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00001845 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00001846 pPage->isInit = 0;
danielk1977d217e6f2009-04-01 17:13:51 +00001847 if( sqlite3PagerPageRefcount(pData)>1 ){
drh5e8d8872009-03-30 17:19:48 +00001848 /* pPage might not be a btree page; it might be an overflow page
1849 ** or ptrmap page or a free page. In those cases, the following
danielk197730548662009-07-09 05:07:37 +00001850 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
drh5e8d8872009-03-30 17:19:48 +00001851 ** But no harm is done by this. And it is very important that
danielk197730548662009-07-09 05:07:37 +00001852 ** btreeInitPage() be called on every btree page so we make
drh5e8d8872009-03-30 17:19:48 +00001853 ** the call for every page that comes in for re-initing. */
danielk197730548662009-07-09 05:07:37 +00001854 btreeInitPage(pPage);
danielk197771d5d2c2008-09-29 11:49:47 +00001855 }
drha6abd042004-06-09 17:37:22 +00001856 }
1857}
1858
1859/*
drhe5fe6902007-12-07 18:55:28 +00001860** Invoke the busy handler for a btree.
1861*/
danielk19771ceedd32008-11-19 10:22:33 +00001862static int btreeInvokeBusyHandler(void *pArg){
drhe5fe6902007-12-07 18:55:28 +00001863 BtShared *pBt = (BtShared*)pArg;
1864 assert( pBt->db );
1865 assert( sqlite3_mutex_held(pBt->db->mutex) );
1866 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
1867}
1868
1869/*
drhad3e0102004-09-03 23:32:18 +00001870** Open a database file.
1871**
drh382c0242001-10-06 16:33:02 +00001872** zFilename is the name of the database file. If zFilename is NULL
drh75c014c2010-08-30 15:02:28 +00001873** then an ephemeral database is created. The ephemeral database might
1874** be exclusively in memory, or it might use a disk-based memory cache.
1875** Either way, the ephemeral database will be automatically deleted
1876** when sqlite3BtreeClose() is called.
1877**
drhe53831d2007-08-17 01:14:38 +00001878** If zFilename is ":memory:" then an in-memory database is created
1879** that is automatically destroyed when it is closed.
drhc47fd8e2009-04-30 13:30:32 +00001880**
drh33f111d2012-01-17 15:29:14 +00001881** The "flags" parameter is a bitmask that might contain bits like
1882** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
drh75c014c2010-08-30 15:02:28 +00001883**
drhc47fd8e2009-04-30 13:30:32 +00001884** If the database is already opened in the same database connection
1885** and we are in shared cache mode, then the open will fail with an
1886** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
1887** objects in the same database connection since doing so will lead
1888** to problems with locking.
drha059ad02001-04-17 20:09:11 +00001889*/
drh23e11ca2004-05-04 17:27:28 +00001890int sqlite3BtreeOpen(
dan3a6d8ae2011-04-23 15:54:54 +00001891 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
drh3aac2dd2004-04-26 14:10:20 +00001892 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00001893 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001894 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00001895 int flags, /* Options */
1896 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00001897){
drh7555d8e2009-03-20 13:15:30 +00001898 BtShared *pBt = 0; /* Shared part of btree structure */
1899 Btree *p; /* Handle to return */
1900 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
1901 int rc = SQLITE_OK; /* Result code from this function */
1902 u8 nReserve; /* Byte of unused space on each page */
1903 unsigned char zDbHeader[100]; /* Database header content */
danielk1977aef0bf62005-12-30 16:28:01 +00001904
drh75c014c2010-08-30 15:02:28 +00001905 /* True if opening an ephemeral, temporary database */
1906 const int isTempDb = zFilename==0 || zFilename[0]==0;
1907
danielk1977aef0bf62005-12-30 16:28:01 +00001908 /* Set the variable isMemdb to true for an in-memory database, or
drhb0a7c9c2010-12-06 21:09:59 +00001909 ** false for a file-based database.
danielk1977aef0bf62005-12-30 16:28:01 +00001910 */
drhb0a7c9c2010-12-06 21:09:59 +00001911#ifdef SQLITE_OMIT_MEMORYDB
1912 const int isMemdb = 0;
1913#else
1914 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
drh9c67b2a2012-05-28 13:58:00 +00001915 || (isTempDb && sqlite3TempInMemory(db))
1916 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
danielk1977aef0bf62005-12-30 16:28:01 +00001917#endif
1918
drhe5fe6902007-12-07 18:55:28 +00001919 assert( db!=0 );
dan3a6d8ae2011-04-23 15:54:54 +00001920 assert( pVfs!=0 );
drhe5fe6902007-12-07 18:55:28 +00001921 assert( sqlite3_mutex_held(db->mutex) );
drhd4187c72010-08-30 22:15:45 +00001922 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
1923
1924 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
1925 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
1926
1927 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
1928 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
drh153c62c2007-08-24 03:51:33 +00001929
drh75c014c2010-08-30 15:02:28 +00001930 if( isMemdb ){
1931 flags |= BTREE_MEMORY;
1932 }
1933 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
1934 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
1935 }
drh17435752007-08-16 04:30:38 +00001936 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00001937 if( !p ){
1938 return SQLITE_NOMEM;
1939 }
1940 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00001941 p->db = db;
danielk1977602b4662009-07-02 07:47:33 +00001942#ifndef SQLITE_OMIT_SHARED_CACHE
1943 p->lock.pBtree = p;
1944 p->lock.iTable = 1;
1945#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001946
drh198bf392006-01-06 21:52:49 +00001947#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001948 /*
1949 ** If this Btree is a candidate for shared cache, try to find an
1950 ** existing BtShared object that we can share with
1951 */
drh4ab9d252012-05-26 20:08:49 +00001952 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
drhf1f12682009-09-09 14:17:52 +00001953 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
danielk1977adfb9b02007-09-17 07:02:56 +00001954 int nFullPathname = pVfs->mxPathname+1;
drhe5ae5732008-06-15 02:51:47 +00001955 char *zFullPathname = sqlite3Malloc(nFullPathname);
drh30ddce62011-10-15 00:16:30 +00001956 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
drhff0587c2007-08-29 17:43:19 +00001957 p->sharable = 1;
drhff0587c2007-08-29 17:43:19 +00001958 if( !zFullPathname ){
1959 sqlite3_free(p);
1960 return SQLITE_NOMEM;
1961 }
drhafc8b7f2012-05-26 18:06:38 +00001962 if( isMemdb ){
1963 memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
1964 }else{
1965 rc = sqlite3OsFullPathname(pVfs, zFilename,
1966 nFullPathname, zFullPathname);
1967 if( rc ){
1968 sqlite3_free(zFullPathname);
1969 sqlite3_free(p);
1970 return rc;
1971 }
drh070ad6b2011-11-17 11:43:19 +00001972 }
drh30ddce62011-10-15 00:16:30 +00001973#if SQLITE_THREADSAFE
drh7555d8e2009-03-20 13:15:30 +00001974 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
1975 sqlite3_mutex_enter(mutexOpen);
danielk197759f8c082008-06-18 17:09:10 +00001976 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhff0587c2007-08-29 17:43:19 +00001977 sqlite3_mutex_enter(mutexShared);
drh30ddce62011-10-15 00:16:30 +00001978#endif
drh78f82d12008-09-02 00:52:52 +00001979 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
drhff0587c2007-08-29 17:43:19 +00001980 assert( pBt->nRef>0 );
drhd4e0bb02012-05-27 01:19:04 +00001981 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
drhff0587c2007-08-29 17:43:19 +00001982 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
drhc47fd8e2009-04-30 13:30:32 +00001983 int iDb;
1984 for(iDb=db->nDb-1; iDb>=0; iDb--){
1985 Btree *pExisting = db->aDb[iDb].pBt;
1986 if( pExisting && pExisting->pBt==pBt ){
1987 sqlite3_mutex_leave(mutexShared);
1988 sqlite3_mutex_leave(mutexOpen);
1989 sqlite3_free(zFullPathname);
1990 sqlite3_free(p);
1991 return SQLITE_CONSTRAINT;
1992 }
1993 }
drhff0587c2007-08-29 17:43:19 +00001994 p->pBt = pBt;
1995 pBt->nRef++;
1996 break;
1997 }
1998 }
1999 sqlite3_mutex_leave(mutexShared);
2000 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00002001 }
drhff0587c2007-08-29 17:43:19 +00002002#ifdef SQLITE_DEBUG
2003 else{
2004 /* In debug mode, we mark all persistent databases as sharable
2005 ** even when they are not. This exercises the locking code and
2006 ** gives more opportunity for asserts(sqlite3_mutex_held())
2007 ** statements to find locking problems.
2008 */
2009 p->sharable = 1;
2010 }
2011#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002012 }
2013#endif
drha059ad02001-04-17 20:09:11 +00002014 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00002015 /*
2016 ** The following asserts make sure that structures used by the btree are
2017 ** the right size. This is to guard against size changes that result
2018 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00002019 */
drh062cf272015-03-23 19:03:51 +00002020 assert( sizeof(i64)==8 );
2021 assert( sizeof(u64)==8 );
drhe53831d2007-08-17 01:14:38 +00002022 assert( sizeof(u32)==4 );
2023 assert( sizeof(u16)==2 );
2024 assert( sizeof(Pgno)==4 );
2025
2026 pBt = sqlite3MallocZero( sizeof(*pBt) );
2027 if( pBt==0 ){
2028 rc = SQLITE_NOMEM;
2029 goto btree_open_out;
2030 }
danielk197771d5d2c2008-09-29 11:49:47 +00002031 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
drh4775ecd2009-07-24 19:01:19 +00002032 EXTRA_SIZE, flags, vfsFlags, pageReinit);
drhe53831d2007-08-17 01:14:38 +00002033 if( rc==SQLITE_OK ){
drh9b4c59f2013-04-15 17:03:42 +00002034 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
drhe53831d2007-08-17 01:14:38 +00002035 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
2036 }
2037 if( rc!=SQLITE_OK ){
2038 goto btree_open_out;
2039 }
shanehbd2aaf92010-09-01 02:38:21 +00002040 pBt->openFlags = (u8)flags;
danielk19772a50ff02009-04-10 09:47:06 +00002041 pBt->db = db;
danielk19771ceedd32008-11-19 10:22:33 +00002042 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
drhe53831d2007-08-17 01:14:38 +00002043 p->pBt = pBt;
2044
drhe53831d2007-08-17 01:14:38 +00002045 pBt->pCursor = 0;
2046 pBt->pPage1 = 0;
drhc9166342012-01-05 23:32:06 +00002047 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
drh5b47efa2010-02-12 18:18:39 +00002048#ifdef SQLITE_SECURE_DELETE
drhc9166342012-01-05 23:32:06 +00002049 pBt->btsFlags |= BTS_SECURE_DELETE;
drh5b47efa2010-02-12 18:18:39 +00002050#endif
drh113762a2014-11-19 16:36:25 +00002051 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2052 ** determined by the 2-byte integer located at an offset of 16 bytes from
2053 ** the beginning of the database file. */
drhb2eced52010-08-12 02:41:12 +00002054 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
drhe53831d2007-08-17 01:14:38 +00002055 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2056 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002057 pBt->pageSize = 0;
drhe53831d2007-08-17 01:14:38 +00002058#ifndef SQLITE_OMIT_AUTOVACUUM
2059 /* If the magic name ":memory:" will create an in-memory database, then
2060 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2061 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2062 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2063 ** regular file-name. In this case the auto-vacuum applies as per normal.
2064 */
2065 if( zFilename && !isMemdb ){
2066 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2067 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2068 }
2069#endif
2070 nReserve = 0;
2071 }else{
drh113762a2014-11-19 16:36:25 +00002072 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2073 ** determined by the one-byte unsigned integer found at an offset of 20
2074 ** into the database file header. */
drhe53831d2007-08-17 01:14:38 +00002075 nReserve = zDbHeader[20];
drhc9166342012-01-05 23:32:06 +00002076 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
drhe53831d2007-08-17 01:14:38 +00002077#ifndef SQLITE_OMIT_AUTOVACUUM
2078 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2079 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2080#endif
2081 }
drhfa9601a2009-06-18 17:22:39 +00002082 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhc0b61812009-04-30 01:22:41 +00002083 if( rc ) goto btree_open_out;
drhe53831d2007-08-17 01:14:38 +00002084 pBt->usableSize = pBt->pageSize - nReserve;
2085 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
drhe53831d2007-08-17 01:14:38 +00002086
2087#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2088 /* Add the new BtShared object to the linked list sharable BtShareds.
2089 */
2090 if( p->sharable ){
drh30ddce62011-10-15 00:16:30 +00002091 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
drhe53831d2007-08-17 01:14:38 +00002092 pBt->nRef = 1;
drh30ddce62011-10-15 00:16:30 +00002093 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
danielk1977075c23a2008-09-01 18:34:20 +00002094 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
danielk197759f8c082008-06-18 17:09:10 +00002095 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00002096 if( pBt->mutex==0 ){
2097 rc = SQLITE_NOMEM;
drhe5fe6902007-12-07 18:55:28 +00002098 db->mallocFailed = 0;
drh3285db22007-09-03 22:00:39 +00002099 goto btree_open_out;
2100 }
drhff0587c2007-08-29 17:43:19 +00002101 }
drhe53831d2007-08-17 01:14:38 +00002102 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00002103 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2104 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
drhe53831d2007-08-17 01:14:38 +00002105 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00002106 }
drheee46cf2004-11-06 00:02:48 +00002107#endif
drh90f5ecb2004-07-22 01:19:35 +00002108 }
danielk1977aef0bf62005-12-30 16:28:01 +00002109
drhcfed7bc2006-03-13 14:28:05 +00002110#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00002111 /* If the new Btree uses a sharable pBtShared, then link the new
2112 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00002113 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00002114 */
drhe53831d2007-08-17 01:14:38 +00002115 if( p->sharable ){
2116 int i;
2117 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00002118 for(i=0; i<db->nDb; i++){
2119 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00002120 while( pSib->pPrev ){ pSib = pSib->pPrev; }
2121 if( p->pBt<pSib->pBt ){
2122 p->pNext = pSib;
2123 p->pPrev = 0;
2124 pSib->pPrev = p;
2125 }else{
drhabddb0c2007-08-20 13:14:28 +00002126 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
drhe53831d2007-08-17 01:14:38 +00002127 pSib = pSib->pNext;
2128 }
2129 p->pNext = pSib->pNext;
2130 p->pPrev = pSib;
2131 if( p->pNext ){
2132 p->pNext->pPrev = p;
2133 }
2134 pSib->pNext = p;
2135 }
2136 break;
2137 }
2138 }
danielk1977aef0bf62005-12-30 16:28:01 +00002139 }
danielk1977aef0bf62005-12-30 16:28:01 +00002140#endif
2141 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00002142
2143btree_open_out:
2144 if( rc!=SQLITE_OK ){
2145 if( pBt && pBt->pPager ){
2146 sqlite3PagerClose(pBt->pPager);
2147 }
drh17435752007-08-16 04:30:38 +00002148 sqlite3_free(pBt);
2149 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00002150 *ppBtree = 0;
drh75c014c2010-08-30 15:02:28 +00002151 }else{
2152 /* If the B-Tree was successfully opened, set the pager-cache size to the
2153 ** default value. Except, when opening on an existing shared pager-cache,
2154 ** do not change the pager-cache size.
2155 */
2156 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2157 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
2158 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002159 }
drh7555d8e2009-03-20 13:15:30 +00002160 if( mutexOpen ){
2161 assert( sqlite3_mutex_held(mutexOpen) );
2162 sqlite3_mutex_leave(mutexOpen);
2163 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002164 return rc;
drha059ad02001-04-17 20:09:11 +00002165}
2166
2167/*
drhe53831d2007-08-17 01:14:38 +00002168** Decrement the BtShared.nRef counter. When it reaches zero,
2169** remove the BtShared structure from the sharing list. Return
2170** true if the BtShared.nRef counter reaches zero and return
2171** false if it is still positive.
2172*/
2173static int removeFromSharingList(BtShared *pBt){
2174#ifndef SQLITE_OMIT_SHARED_CACHE
drh30ddce62011-10-15 00:16:30 +00002175 MUTEX_LOGIC( sqlite3_mutex *pMaster; )
drhe53831d2007-08-17 01:14:38 +00002176 BtShared *pList;
2177 int removed = 0;
2178
drhd677b3d2007-08-20 22:48:41 +00002179 assert( sqlite3_mutex_notheld(pBt->mutex) );
drh30ddce62011-10-15 00:16:30 +00002180 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
drhe53831d2007-08-17 01:14:38 +00002181 sqlite3_mutex_enter(pMaster);
2182 pBt->nRef--;
2183 if( pBt->nRef<=0 ){
drh78f82d12008-09-02 00:52:52 +00002184 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2185 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
drhe53831d2007-08-17 01:14:38 +00002186 }else{
drh78f82d12008-09-02 00:52:52 +00002187 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
drh34004ce2008-07-11 16:15:17 +00002188 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00002189 pList=pList->pNext;
2190 }
drh34004ce2008-07-11 16:15:17 +00002191 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00002192 pList->pNext = pBt->pNext;
2193 }
2194 }
drh3285db22007-09-03 22:00:39 +00002195 if( SQLITE_THREADSAFE ){
2196 sqlite3_mutex_free(pBt->mutex);
2197 }
drhe53831d2007-08-17 01:14:38 +00002198 removed = 1;
2199 }
2200 sqlite3_mutex_leave(pMaster);
2201 return removed;
2202#else
2203 return 1;
2204#endif
2205}
2206
2207/*
drhf7141992008-06-19 00:16:08 +00002208** Make sure pBt->pTmpSpace points to an allocation of
drh92787cf2014-10-15 11:55:51 +00002209** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
2210** pointer.
drhf7141992008-06-19 00:16:08 +00002211*/
2212static void allocateTempSpace(BtShared *pBt){
2213 if( !pBt->pTmpSpace ){
2214 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
dan14285b72013-10-16 11:39:07 +00002215
2216 /* One of the uses of pBt->pTmpSpace is to format cells before
2217 ** inserting them into a leaf page (function fillInCell()). If
2218 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2219 ** by the various routines that manipulate binary cells. Which
2220 ** can mean that fillInCell() only initializes the first 2 or 3
2221 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2222 ** it into a database page. This is not actually a problem, but it
2223 ** does cause a valgrind error when the 1 or 2 bytes of unitialized
2224 ** data is passed to system call write(). So to avoid this error,
drh92787cf2014-10-15 11:55:51 +00002225 ** zero the first 4 bytes of temp space here.
2226 **
2227 ** Also: Provide four bytes of initialized space before the
2228 ** beginning of pTmpSpace as an area available to prepend the
2229 ** left-child pointer to the beginning of a cell.
2230 */
2231 if( pBt->pTmpSpace ){
2232 memset(pBt->pTmpSpace, 0, 8);
2233 pBt->pTmpSpace += 4;
2234 }
drhf7141992008-06-19 00:16:08 +00002235 }
2236}
2237
2238/*
2239** Free the pBt->pTmpSpace allocation
2240*/
2241static void freeTempSpace(BtShared *pBt){
drh92787cf2014-10-15 11:55:51 +00002242 if( pBt->pTmpSpace ){
2243 pBt->pTmpSpace -= 4;
2244 sqlite3PageFree(pBt->pTmpSpace);
2245 pBt->pTmpSpace = 0;
2246 }
drhf7141992008-06-19 00:16:08 +00002247}
2248
2249/*
drha059ad02001-04-17 20:09:11 +00002250** Close an open database and invalidate all cursors.
2251*/
danielk1977aef0bf62005-12-30 16:28:01 +00002252int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002253 BtShared *pBt = p->pBt;
2254 BtCursor *pCur;
2255
danielk1977aef0bf62005-12-30 16:28:01 +00002256 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00002257 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00002258 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002259 pCur = pBt->pCursor;
2260 while( pCur ){
2261 BtCursor *pTmp = pCur;
2262 pCur = pCur->pNext;
2263 if( pTmp->pBtree==p ){
2264 sqlite3BtreeCloseCursor(pTmp);
2265 }
drha059ad02001-04-17 20:09:11 +00002266 }
danielk1977aef0bf62005-12-30 16:28:01 +00002267
danielk19778d34dfd2006-01-24 16:37:57 +00002268 /* Rollback any active transaction and free the handle structure.
2269 ** The call to sqlite3BtreeRollback() drops any table-locks held by
2270 ** this handle.
2271 */
drh47b7fc72014-11-11 01:33:57 +00002272 sqlite3BtreeRollback(p, SQLITE_OK, 0);
drhe53831d2007-08-17 01:14:38 +00002273 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002274
danielk1977aef0bf62005-12-30 16:28:01 +00002275 /* If there are still other outstanding references to the shared-btree
2276 ** structure, return now. The remainder of this procedure cleans
2277 ** up the shared-btree.
2278 */
drhe53831d2007-08-17 01:14:38 +00002279 assert( p->wantToLock==0 && p->locked==0 );
2280 if( !p->sharable || removeFromSharingList(pBt) ){
2281 /* The pBt is no longer on the sharing list, so we can access
2282 ** it without having to hold the mutex.
2283 **
2284 ** Clean out and delete the BtShared object.
2285 */
2286 assert( !pBt->pCursor );
drhe53831d2007-08-17 01:14:38 +00002287 sqlite3PagerClose(pBt->pPager);
2288 if( pBt->xFreeSchema && pBt->pSchema ){
2289 pBt->xFreeSchema(pBt->pSchema);
2290 }
drhb9755982010-07-24 16:34:37 +00002291 sqlite3DbFree(0, pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00002292 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00002293 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002294 }
2295
drhe53831d2007-08-17 01:14:38 +00002296#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00002297 assert( p->wantToLock==0 );
2298 assert( p->locked==0 );
2299 if( p->pPrev ) p->pPrev->pNext = p->pNext;
2300 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00002301#endif
2302
drhe53831d2007-08-17 01:14:38 +00002303 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00002304 return SQLITE_OK;
2305}
2306
2307/*
drhda47d772002-12-02 04:25:19 +00002308** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00002309**
2310** The maximum number of cache pages is set to the absolute
2311** value of mxPage. If mxPage is negative, the pager will
2312** operate asynchronously - it will not stop to do fsync()s
2313** to insure data is written to the disk surface before
2314** continuing. Transactions still work if synchronous is off,
2315** and the database cannot be corrupted if this program
2316** crashes. But if the operating system crashes or there is
2317** an abrupt power failure when synchronous is off, the database
2318** could be left in an inconsistent and unrecoverable state.
2319** Synchronous is on by default so database corruption is not
2320** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00002321*/
danielk1977aef0bf62005-12-30 16:28:01 +00002322int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2323 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00002324 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002325 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00002326 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00002327 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00002328 return SQLITE_OK;
2329}
2330
drh18c7e402014-03-14 11:46:10 +00002331#if SQLITE_MAX_MMAP_SIZE>0
drhf57b14a2001-09-14 18:54:08 +00002332/*
dan5d8a1372013-03-19 19:28:06 +00002333** Change the limit on the amount of the database file that may be
2334** memory mapped.
2335*/
drh9b4c59f2013-04-15 17:03:42 +00002336int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
dan5d8a1372013-03-19 19:28:06 +00002337 BtShared *pBt = p->pBt;
2338 assert( sqlite3_mutex_held(p->db->mutex) );
2339 sqlite3BtreeEnter(p);
drh9b4c59f2013-04-15 17:03:42 +00002340 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
dan5d8a1372013-03-19 19:28:06 +00002341 sqlite3BtreeLeave(p);
2342 return SQLITE_OK;
2343}
drh18c7e402014-03-14 11:46:10 +00002344#endif /* SQLITE_MAX_MMAP_SIZE>0 */
dan5d8a1372013-03-19 19:28:06 +00002345
2346/*
drh973b6e32003-02-12 14:09:42 +00002347** Change the way data is synced to disk in order to increase or decrease
2348** how well the database resists damage due to OS crashes and power
2349** failures. Level 1 is the same as asynchronous (no syncs() occur and
2350** there is a high probability of damage) Level 2 is the default. There
2351** is a very low but non-zero probability of damage. Level 3 reduces the
2352** probability of damage to near zero but with a write performance reduction.
2353*/
danielk197793758c82005-01-21 08:13:14 +00002354#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drh40c39412013-08-16 20:42:20 +00002355int sqlite3BtreeSetPagerFlags(
drhc97d8462010-11-19 18:23:35 +00002356 Btree *p, /* The btree to set the safety level on */
drh40c39412013-08-16 20:42:20 +00002357 unsigned pgFlags /* Various PAGER_* flags */
drhc97d8462010-11-19 18:23:35 +00002358){
danielk1977aef0bf62005-12-30 16:28:01 +00002359 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00002360 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002361 sqlite3BtreeEnter(p);
drh40c39412013-08-16 20:42:20 +00002362 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
drhd677b3d2007-08-20 22:48:41 +00002363 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00002364 return SQLITE_OK;
2365}
danielk197793758c82005-01-21 08:13:14 +00002366#endif
drh973b6e32003-02-12 14:09:42 +00002367
drh2c8997b2005-08-27 16:36:48 +00002368/*
2369** Return TRUE if the given btree is set to safety level 1. In other
2370** words, return TRUE if no sync() occurs on the disk files.
2371*/
danielk1977aef0bf62005-12-30 16:28:01 +00002372int sqlite3BtreeSyncDisabled(Btree *p){
2373 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002374 int rc;
drhe5fe6902007-12-07 18:55:28 +00002375 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002376 sqlite3BtreeEnter(p);
drhd0679ed2007-08-28 22:24:34 +00002377 assert( pBt && pBt->pPager );
drhd677b3d2007-08-20 22:48:41 +00002378 rc = sqlite3PagerNosync(pBt->pPager);
2379 sqlite3BtreeLeave(p);
2380 return rc;
drh2c8997b2005-08-27 16:36:48 +00002381}
2382
drh973b6e32003-02-12 14:09:42 +00002383/*
drh90f5ecb2004-07-22 01:19:35 +00002384** Change the default pages size and the number of reserved bytes per page.
drhce4869f2009-04-02 20:16:58 +00002385** Or, if the page size has already been fixed, return SQLITE_READONLY
2386** without changing anything.
drh06f50212004-11-02 14:24:33 +00002387**
2388** The page size must be a power of 2 between 512 and 65536. If the page
2389** size supplied does not meet this constraint then the page size is not
2390** changed.
2391**
2392** Page sizes are constrained to be a power of two so that the region
2393** of the database file used for locking (beginning at PENDING_BYTE,
2394** the first byte past the 1GB boundary, 0x40000000) needs to occur
2395** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00002396**
2397** If parameter nReserve is less than zero, then the number of reserved
2398** bytes per page is left unchanged.
drhce4869f2009-04-02 20:16:58 +00002399**
drhc9166342012-01-05 23:32:06 +00002400** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
drhce4869f2009-04-02 20:16:58 +00002401** and autovacuum mode can no longer be changed.
drh90f5ecb2004-07-22 01:19:35 +00002402*/
drhce4869f2009-04-02 20:16:58 +00002403int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
danielk1977a1644fd2007-08-29 12:31:25 +00002404 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002405 BtShared *pBt = p->pBt;
drhf49661a2008-12-10 16:45:50 +00002406 assert( nReserve>=-1 && nReserve<=255 );
drhd677b3d2007-08-20 22:48:41 +00002407 sqlite3BtreeEnter(p);
drhad0961b2015-02-21 00:19:25 +00002408#if SQLITE_HAS_CODEC
2409 if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
2410#endif
drhc9166342012-01-05 23:32:06 +00002411 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
drhd677b3d2007-08-20 22:48:41 +00002412 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00002413 return SQLITE_READONLY;
2414 }
2415 if( nReserve<0 ){
2416 nReserve = pBt->pageSize - pBt->usableSize;
2417 }
drhf49661a2008-12-10 16:45:50 +00002418 assert( nReserve>=0 && nReserve<=255 );
drh06f50212004-11-02 14:24:33 +00002419 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2420 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00002421 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002422 assert( !pBt->pPage1 && !pBt->pCursor );
drhb2eced52010-08-12 02:41:12 +00002423 pBt->pageSize = (u32)pageSize;
drhf7141992008-06-19 00:16:08 +00002424 freeTempSpace(pBt);
drh90f5ecb2004-07-22 01:19:35 +00002425 }
drhfa9601a2009-06-18 17:22:39 +00002426 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhf49661a2008-12-10 16:45:50 +00002427 pBt->usableSize = pBt->pageSize - (u16)nReserve;
drhc9166342012-01-05 23:32:06 +00002428 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
drhd677b3d2007-08-20 22:48:41 +00002429 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00002430 return rc;
drh90f5ecb2004-07-22 01:19:35 +00002431}
2432
2433/*
2434** Return the currently defined page size
2435*/
danielk1977aef0bf62005-12-30 16:28:01 +00002436int sqlite3BtreeGetPageSize(Btree *p){
2437 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00002438}
drh7f751222009-03-17 22:33:00 +00002439
dan0094f372012-09-28 20:23:42 +00002440/*
2441** This function is similar to sqlite3BtreeGetReserve(), except that it
2442** may only be called if it is guaranteed that the b-tree mutex is already
2443** held.
2444**
2445** This is useful in one special case in the backup API code where it is
2446** known that the shared b-tree mutex is held, but the mutex on the
2447** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
2448** were to be called, it might collide with some other operation on the
mistachkin48864df2013-03-21 21:20:32 +00002449** database handle that owns *p, causing undefined behavior.
dan0094f372012-09-28 20:23:42 +00002450*/
2451int sqlite3BtreeGetReserveNoMutex(Btree *p){
drhad0961b2015-02-21 00:19:25 +00002452 int n;
dan0094f372012-09-28 20:23:42 +00002453 assert( sqlite3_mutex_held(p->pBt->mutex) );
drhad0961b2015-02-21 00:19:25 +00002454 n = p->pBt->pageSize - p->pBt->usableSize;
2455 return n;
dan0094f372012-09-28 20:23:42 +00002456}
2457
drh7f751222009-03-17 22:33:00 +00002458/*
2459** Return the number of bytes of space at the end of every page that
2460** are intentually left unused. This is the "reserved" space that is
2461** sometimes used by extensions.
drhad0961b2015-02-21 00:19:25 +00002462**
2463** If SQLITE_HAS_MUTEX is defined then the number returned is the
2464** greater of the current reserved space and the maximum requested
2465** reserve space.
drh7f751222009-03-17 22:33:00 +00002466*/
drhad0961b2015-02-21 00:19:25 +00002467int sqlite3BtreeGetOptimalReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002468 int n;
2469 sqlite3BtreeEnter(p);
drhad0961b2015-02-21 00:19:25 +00002470 n = sqlite3BtreeGetReserveNoMutex(p);
2471#ifdef SQLITE_HAS_CODEC
2472 if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
2473#endif
drhd677b3d2007-08-20 22:48:41 +00002474 sqlite3BtreeLeave(p);
2475 return n;
drh2011d5f2004-07-22 02:40:37 +00002476}
drhf8e632b2007-05-08 14:51:36 +00002477
drhad0961b2015-02-21 00:19:25 +00002478
drhf8e632b2007-05-08 14:51:36 +00002479/*
2480** Set the maximum page count for a database if mxPage is positive.
2481** No changes are made if mxPage is 0 or negative.
2482** Regardless of the value of mxPage, return the maximum page count.
2483*/
2484int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00002485 int n;
2486 sqlite3BtreeEnter(p);
2487 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
2488 sqlite3BtreeLeave(p);
2489 return n;
drhf8e632b2007-05-08 14:51:36 +00002490}
drh5b47efa2010-02-12 18:18:39 +00002491
2492/*
drhc9166342012-01-05 23:32:06 +00002493** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
2494** then make no changes. Always return the value of the BTS_SECURE_DELETE
drh5b47efa2010-02-12 18:18:39 +00002495** setting after the change.
2496*/
2497int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
2498 int b;
drhaf034ed2010-02-12 19:46:26 +00002499 if( p==0 ) return 0;
drh5b47efa2010-02-12 18:18:39 +00002500 sqlite3BtreeEnter(p);
2501 if( newFlag>=0 ){
drhc9166342012-01-05 23:32:06 +00002502 p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
2503 if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
drh5b47efa2010-02-12 18:18:39 +00002504 }
drhc9166342012-01-05 23:32:06 +00002505 b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
drh5b47efa2010-02-12 18:18:39 +00002506 sqlite3BtreeLeave(p);
2507 return b;
2508}
drh90f5ecb2004-07-22 01:19:35 +00002509
2510/*
danielk1977951af802004-11-05 15:45:09 +00002511** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
2512** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
2513** is disabled. The default value for the auto-vacuum property is
2514** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
2515*/
danielk1977aef0bf62005-12-30 16:28:01 +00002516int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00002517#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002518 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00002519#else
danielk1977dddbcdc2007-04-26 14:42:34 +00002520 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002521 int rc = SQLITE_OK;
drh076d4662009-02-18 20:31:18 +00002522 u8 av = (u8)autoVacuum;
drhd677b3d2007-08-20 22:48:41 +00002523
2524 sqlite3BtreeEnter(p);
drhc9166342012-01-05 23:32:06 +00002525 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002526 rc = SQLITE_READONLY;
2527 }else{
drh076d4662009-02-18 20:31:18 +00002528 pBt->autoVacuum = av ?1:0;
2529 pBt->incrVacuum = av==2 ?1:0;
danielk1977951af802004-11-05 15:45:09 +00002530 }
drhd677b3d2007-08-20 22:48:41 +00002531 sqlite3BtreeLeave(p);
2532 return rc;
danielk1977951af802004-11-05 15:45:09 +00002533#endif
2534}
2535
2536/*
2537** Return the value of the 'auto-vacuum' property. If auto-vacuum is
2538** enabled 1 is returned. Otherwise 0.
2539*/
danielk1977aef0bf62005-12-30 16:28:01 +00002540int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00002541#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002542 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00002543#else
drhd677b3d2007-08-20 22:48:41 +00002544 int rc;
2545 sqlite3BtreeEnter(p);
2546 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00002547 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
2548 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
2549 BTREE_AUTOVACUUM_INCR
2550 );
drhd677b3d2007-08-20 22:48:41 +00002551 sqlite3BtreeLeave(p);
2552 return rc;
danielk1977951af802004-11-05 15:45:09 +00002553#endif
2554}
2555
2556
2557/*
drha34b6762004-05-07 13:30:42 +00002558** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00002559** also acquire a readlock on that file.
2560**
2561** SQLITE_OK is returned on success. If the file is not a
2562** well-formed database file, then SQLITE_CORRUPT is returned.
2563** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00002564** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00002565*/
danielk1977aef0bf62005-12-30 16:28:01 +00002566static int lockBtree(BtShared *pBt){
drhc2a4bab2010-04-02 12:46:45 +00002567 int rc; /* Result code from subfunctions */
2568 MemPage *pPage1; /* Page 1 of the database file */
2569 int nPage; /* Number of pages in the database */
2570 int nPageFile = 0; /* Number of pages in the database file */
2571 int nPageHeader; /* Number of pages in the database according to hdr */
drhd677b3d2007-08-20 22:48:41 +00002572
drh1fee73e2007-08-29 04:00:57 +00002573 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977295dc102009-04-01 19:07:03 +00002574 assert( pBt->pPage1==0 );
danielk197789bc4bc2009-07-21 19:25:24 +00002575 rc = sqlite3PagerSharedLock(pBt->pPager);
2576 if( rc!=SQLITE_OK ) return rc;
drhb00fc3b2013-08-21 23:42:32 +00002577 rc = btreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00002578 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00002579
2580 /* Do some checking to help insure the file we opened really is
2581 ** a valid database file.
2582 */
drhc2a4bab2010-04-02 12:46:45 +00002583 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
drh8fb8b532010-08-14 17:12:04 +00002584 sqlite3PagerPagecount(pBt->pPager, &nPageFile);
drhb28e59b2010-06-17 02:13:39 +00002585 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
drhc2a4bab2010-04-02 12:46:45 +00002586 nPage = nPageFile;
drh97b59a52010-03-31 02:31:33 +00002587 }
2588 if( nPage>0 ){
drh43b18e12010-08-17 19:40:08 +00002589 u32 pageSize;
2590 u32 usableSize;
drhb6f41482004-05-14 01:58:11 +00002591 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00002592 rc = SQLITE_NOTADB;
drh113762a2014-11-19 16:36:25 +00002593 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
2594 ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
2595 ** 61 74 20 33 00. */
drhb6f41482004-05-14 01:58:11 +00002596 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00002597 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00002598 }
dan5cf53532010-05-01 16:40:20 +00002599
2600#ifdef SQLITE_OMIT_WAL
2601 if( page1[18]>1 ){
drhc9166342012-01-05 23:32:06 +00002602 pBt->btsFlags |= BTS_READ_ONLY;
dan5cf53532010-05-01 16:40:20 +00002603 }
2604 if( page1[19]>1 ){
2605 goto page1_init_failed;
2606 }
2607#else
dane04dc882010-04-20 18:53:15 +00002608 if( page1[18]>2 ){
drhc9166342012-01-05 23:32:06 +00002609 pBt->btsFlags |= BTS_READ_ONLY;
drh309169a2007-04-24 17:27:51 +00002610 }
dane04dc882010-04-20 18:53:15 +00002611 if( page1[19]>2 ){
drhb6f41482004-05-14 01:58:11 +00002612 goto page1_init_failed;
2613 }
drhe5ae5732008-06-15 02:51:47 +00002614
dana470aeb2010-04-21 11:43:38 +00002615 /* If the write version is set to 2, this database should be accessed
2616 ** in WAL mode. If the log is not already open, open it now. Then
2617 ** return SQLITE_OK and return without populating BtShared.pPage1.
2618 ** The caller detects this and calls this function again. This is
2619 ** required as the version of page 1 currently in the page1 buffer
2620 ** may not be the latest version - there may be a newer one in the log
2621 ** file.
2622 */
drhc9166342012-01-05 23:32:06 +00002623 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
dane04dc882010-04-20 18:53:15 +00002624 int isOpen = 0;
drh7ed91f22010-04-29 22:34:07 +00002625 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
dane04dc882010-04-20 18:53:15 +00002626 if( rc!=SQLITE_OK ){
2627 goto page1_init_failed;
2628 }else if( isOpen==0 ){
2629 releasePage(pPage1);
2630 return SQLITE_OK;
2631 }
dan8b5444b2010-04-27 14:37:47 +00002632 rc = SQLITE_NOTADB;
dane04dc882010-04-20 18:53:15 +00002633 }
dan5cf53532010-05-01 16:40:20 +00002634#endif
dane04dc882010-04-20 18:53:15 +00002635
drh113762a2014-11-19 16:36:25 +00002636 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
2637 ** fractions and the leaf payload fraction values must be 64, 32, and 32.
2638 **
drhe5ae5732008-06-15 02:51:47 +00002639 ** The original design allowed these amounts to vary, but as of
2640 ** version 3.6.0, we require them to be fixed.
2641 */
2642 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
2643 goto page1_init_failed;
2644 }
drh113762a2014-11-19 16:36:25 +00002645 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2646 ** determined by the 2-byte integer located at an offset of 16 bytes from
2647 ** the beginning of the database file. */
drhb2eced52010-08-12 02:41:12 +00002648 pageSize = (page1[16]<<8) | (page1[17]<<16);
drh113762a2014-11-19 16:36:25 +00002649 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
2650 ** between 512 and 65536 inclusive. */
drhb2eced52010-08-12 02:41:12 +00002651 if( ((pageSize-1)&pageSize)!=0
2652 || pageSize>SQLITE_MAX_PAGE_SIZE
2653 || pageSize<=256
drh7dc385e2007-09-06 23:39:36 +00002654 ){
drh07d183d2005-05-01 22:52:42 +00002655 goto page1_init_failed;
2656 }
2657 assert( (pageSize & 7)==0 );
drh113762a2014-11-19 16:36:25 +00002658 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
2659 ** integer at offset 20 is the number of bytes of space at the end of
2660 ** each page to reserve for extensions.
2661 **
2662 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2663 ** determined by the one-byte unsigned integer found at an offset of 20
2664 ** into the database file header. */
danielk1977f653d782008-03-20 11:04:21 +00002665 usableSize = pageSize - page1[20];
shaneh1df2db72010-08-18 02:28:48 +00002666 if( (u32)pageSize!=pBt->pageSize ){
danielk1977f653d782008-03-20 11:04:21 +00002667 /* After reading the first page of the database assuming a page size
2668 ** of BtShared.pageSize, we have discovered that the page-size is
2669 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
2670 ** zero and return SQLITE_OK. The caller will call this function
2671 ** again with the correct page-size.
2672 */
2673 releasePage(pPage1);
drh43b18e12010-08-17 19:40:08 +00002674 pBt->usableSize = usableSize;
2675 pBt->pageSize = pageSize;
drhf7141992008-06-19 00:16:08 +00002676 freeTempSpace(pBt);
drhfa9601a2009-06-18 17:22:39 +00002677 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
2678 pageSize-usableSize);
drh5e483932009-07-10 16:51:30 +00002679 return rc;
danielk1977f653d782008-03-20 11:04:21 +00002680 }
danecac6702011-02-09 18:19:20 +00002681 if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
drhc2a4bab2010-04-02 12:46:45 +00002682 rc = SQLITE_CORRUPT_BKPT;
2683 goto page1_init_failed;
2684 }
drh113762a2014-11-19 16:36:25 +00002685 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
2686 ** be less than 480. In other words, if the page size is 512, then the
2687 ** reserved space size cannot exceed 32. */
drhb33e1b92009-06-18 11:29:20 +00002688 if( usableSize<480 ){
drhb6f41482004-05-14 01:58:11 +00002689 goto page1_init_failed;
2690 }
drh43b18e12010-08-17 19:40:08 +00002691 pBt->pageSize = pageSize;
2692 pBt->usableSize = usableSize;
drh057cd3a2005-02-15 16:23:02 +00002693#ifndef SQLITE_OMIT_AUTOVACUUM
2694 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00002695 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00002696#endif
drh306dc212001-05-21 13:45:10 +00002697 }
drhb6f41482004-05-14 01:58:11 +00002698
2699 /* maxLocal is the maximum amount of payload to store locally for
2700 ** a cell. Make sure it is small enough so that at least minFanout
2701 ** cells can will fit on one page. We assume a 10-byte page header.
2702 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00002703 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00002704 ** 4-byte child pointer
2705 ** 9-byte nKey value
2706 ** 4-byte nData value
2707 ** 4-byte overflow page pointer
drhe22e03e2010-08-18 21:19:03 +00002708 ** So a cell consists of a 2-byte pointer, a header which is as much as
drh43605152004-05-29 21:46:49 +00002709 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
2710 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00002711 */
shaneh1df2db72010-08-18 02:28:48 +00002712 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
2713 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
2714 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
2715 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
drhc9166342012-01-05 23:32:06 +00002716 if( pBt->maxLocal>127 ){
2717 pBt->max1bytePayload = 127;
2718 }else{
mistachkin0547e2f2012-01-08 00:54:02 +00002719 pBt->max1bytePayload = (u8)pBt->maxLocal;
drhc9166342012-01-05 23:32:06 +00002720 }
drh2e38c322004-09-03 18:38:44 +00002721 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00002722 pBt->pPage1 = pPage1;
drhdd3cd972010-03-27 17:12:36 +00002723 pBt->nPage = nPage;
drhb6f41482004-05-14 01:58:11 +00002724 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00002725
drh72f82862001-05-24 21:06:34 +00002726page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00002727 releasePage(pPage1);
2728 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00002729 return rc;
drh306dc212001-05-21 13:45:10 +00002730}
2731
drh85ec3b62013-05-14 23:12:06 +00002732#ifndef NDEBUG
2733/*
2734** Return the number of cursors open on pBt. This is for use
2735** in assert() expressions, so it is only compiled if NDEBUG is not
2736** defined.
2737**
2738** Only write cursors are counted if wrOnly is true. If wrOnly is
2739** false then all cursors are counted.
2740**
2741** For the purposes of this routine, a cursor is any cursor that
peter.d.reid60ec9142014-09-06 16:39:46 +00002742** is capable of reading or writing to the database. Cursors that
drh85ec3b62013-05-14 23:12:06 +00002743** have been tripped into the CURSOR_FAULT state are not counted.
2744*/
2745static int countValidCursors(BtShared *pBt, int wrOnly){
2746 BtCursor *pCur;
2747 int r = 0;
2748 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drh036dbec2014-03-11 23:40:44 +00002749 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
2750 && pCur->eState!=CURSOR_FAULT ) r++;
drh85ec3b62013-05-14 23:12:06 +00002751 }
2752 return r;
2753}
2754#endif
2755
drh306dc212001-05-21 13:45:10 +00002756/*
drhb8ca3072001-12-05 00:21:20 +00002757** If there are no outstanding cursors and we are not in the middle
2758** of a transaction but there is a read lock on the database, then
2759** this routine unrefs the first page of the database file which
2760** has the effect of releasing the read lock.
2761**
drhb8ca3072001-12-05 00:21:20 +00002762** If there is a transaction in progress, this routine is a no-op.
2763*/
danielk1977aef0bf62005-12-30 16:28:01 +00002764static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00002765 assert( sqlite3_mutex_held(pBt->mutex) );
drh85ec3b62013-05-14 23:12:06 +00002766 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
danielk19771bc9ee92009-07-04 15:41:02 +00002767 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
drhb2325b72014-09-24 18:31:07 +00002768 MemPage *pPage1 = pBt->pPage1;
2769 assert( pPage1->aData );
danielk1977c1761e82009-06-25 09:40:03 +00002770 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
drh3aac2dd2004-04-26 14:10:20 +00002771 pBt->pPage1 = 0;
drhb2325b72014-09-24 18:31:07 +00002772 releasePage(pPage1);
drhb8ca3072001-12-05 00:21:20 +00002773 }
2774}
2775
2776/*
drhe39f2f92009-07-23 01:43:59 +00002777** If pBt points to an empty file then convert that empty file
2778** into a new empty database by initializing the first page of
2779** the database.
drh8b2f49b2001-06-08 00:21:52 +00002780*/
danielk1977aef0bf62005-12-30 16:28:01 +00002781static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00002782 MemPage *pP1;
2783 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00002784 int rc;
drhd677b3d2007-08-20 22:48:41 +00002785
drh1fee73e2007-08-29 04:00:57 +00002786 assert( sqlite3_mutex_held(pBt->mutex) );
drhdd3cd972010-03-27 17:12:36 +00002787 if( pBt->nPage>0 ){
2788 return SQLITE_OK;
danielk1977ad0132d2008-06-07 08:58:22 +00002789 }
drh3aac2dd2004-04-26 14:10:20 +00002790 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00002791 assert( pP1!=0 );
2792 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00002793 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00002794 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00002795 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
2796 assert( sizeof(zMagicHeader)==16 );
shaneh1df2db72010-08-18 02:28:48 +00002797 data[16] = (u8)((pBt->pageSize>>8)&0xff);
2798 data[17] = (u8)((pBt->pageSize>>16)&0xff);
drh9e572e62004-04-23 23:43:10 +00002799 data[18] = 1;
2800 data[19] = 1;
drhf49661a2008-12-10 16:45:50 +00002801 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
2802 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
drhe5ae5732008-06-15 02:51:47 +00002803 data[21] = 64;
2804 data[22] = 32;
2805 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00002806 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00002807 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhc9166342012-01-05 23:32:06 +00002808 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
danielk1977003ba062004-11-04 02:57:33 +00002809#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002810 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00002811 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00002812 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00002813 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00002814#endif
drhdd3cd972010-03-27 17:12:36 +00002815 pBt->nPage = 1;
2816 data[31] = 1;
drh8b2f49b2001-06-08 00:21:52 +00002817 return SQLITE_OK;
2818}
2819
2820/*
danb483eba2012-10-13 19:58:11 +00002821** Initialize the first page of the database file (creating a database
2822** consisting of a single page and no schema objects). Return SQLITE_OK
2823** if successful, or an SQLite error code otherwise.
2824*/
2825int sqlite3BtreeNewDb(Btree *p){
2826 int rc;
2827 sqlite3BtreeEnter(p);
2828 p->pBt->nPage = 0;
2829 rc = newDatabase(p->pBt);
2830 sqlite3BtreeLeave(p);
2831 return rc;
2832}
2833
2834/*
danielk1977ee5741e2004-05-31 10:01:34 +00002835** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00002836** is started if the second argument is nonzero, otherwise a read-
2837** transaction. If the second argument is 2 or more and exclusive
2838** transaction is started, meaning that no other process is allowed
2839** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00002840** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00002841** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00002842**
danielk1977ee5741e2004-05-31 10:01:34 +00002843** A write-transaction must be started before attempting any
2844** changes to the database. None of the following routines
2845** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00002846**
drh23e11ca2004-05-04 17:27:28 +00002847** sqlite3BtreeCreateTable()
2848** sqlite3BtreeCreateIndex()
2849** sqlite3BtreeClearTable()
2850** sqlite3BtreeDropTable()
2851** sqlite3BtreeInsert()
2852** sqlite3BtreeDelete()
2853** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00002854**
drhb8ef32c2005-03-14 02:01:49 +00002855** If an initial attempt to acquire the lock fails because of lock contention
2856** and the database was previously unlocked, then invoke the busy handler
2857** if there is one. But if there was previously a read-lock, do not
2858** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
2859** returned when there is already a read-lock in order to avoid a deadlock.
2860**
2861** Suppose there are two processes A and B. A has a read lock and B has
2862** a reserved lock. B tries to promote to exclusive but is blocked because
2863** of A's read lock. A tries to promote to reserved but is blocked by B.
2864** One or the other of the two processes must give way or there can be
2865** no progress. By returning SQLITE_BUSY and not invoking the busy callback
2866** when A already has a read lock, we encourage A to give up and let B
2867** proceed.
drha059ad02001-04-17 20:09:11 +00002868*/
danielk1977aef0bf62005-12-30 16:28:01 +00002869int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
danielk1977404ca072009-03-16 13:19:36 +00002870 sqlite3 *pBlock = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00002871 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00002872 int rc = SQLITE_OK;
2873
drhd677b3d2007-08-20 22:48:41 +00002874 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002875 btreeIntegrity(p);
2876
danielk1977ee5741e2004-05-31 10:01:34 +00002877 /* If the btree is already in a write-transaction, or it
2878 ** is already in a read-transaction and a read-transaction
2879 ** is requested, this is a no-op.
2880 */
danielk1977aef0bf62005-12-30 16:28:01 +00002881 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00002882 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002883 }
dan56c517a2013-09-26 11:04:33 +00002884 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
drhb8ef32c2005-03-14 02:01:49 +00002885
2886 /* Write transactions are not possible on a read-only database */
drhc9166342012-01-05 23:32:06 +00002887 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00002888 rc = SQLITE_READONLY;
2889 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002890 }
2891
danielk1977404ca072009-03-16 13:19:36 +00002892#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +00002893 /* If another database handle has already opened a write transaction
2894 ** on this shared-btree structure and a second write transaction is
danielk1977404ca072009-03-16 13:19:36 +00002895 ** requested, return SQLITE_LOCKED.
danielk1977aef0bf62005-12-30 16:28:01 +00002896 */
drhc9166342012-01-05 23:32:06 +00002897 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
2898 || (pBt->btsFlags & BTS_PENDING)!=0
2899 ){
danielk1977404ca072009-03-16 13:19:36 +00002900 pBlock = pBt->pWriter->db;
2901 }else if( wrflag>1 ){
danielk1977641b0f42007-12-21 04:47:25 +00002902 BtLock *pIter;
2903 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
2904 if( pIter->pBtree!=p ){
danielk1977404ca072009-03-16 13:19:36 +00002905 pBlock = pIter->pBtree->db;
2906 break;
danielk1977641b0f42007-12-21 04:47:25 +00002907 }
2908 }
2909 }
danielk1977404ca072009-03-16 13:19:36 +00002910 if( pBlock ){
2911 sqlite3ConnectionBlocked(p->db, pBlock);
2912 rc = SQLITE_LOCKED_SHAREDCACHE;
2913 goto trans_begun;
2914 }
danielk1977641b0f42007-12-21 04:47:25 +00002915#endif
2916
danielk1977602b4662009-07-02 07:47:33 +00002917 /* Any read-only or read-write transaction implies a read-lock on
2918 ** page 1. So if some other shared-cache client already has a write-lock
2919 ** on page 1, the transaction cannot be opened. */
drh4c301aa2009-07-15 17:25:45 +00002920 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
2921 if( SQLITE_OK!=rc ) goto trans_begun;
danielk1977602b4662009-07-02 07:47:33 +00002922
drhc9166342012-01-05 23:32:06 +00002923 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
2924 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
drhb8ef32c2005-03-14 02:01:49 +00002925 do {
danielk1977295dc102009-04-01 19:07:03 +00002926 /* Call lockBtree() until either pBt->pPage1 is populated or
2927 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
2928 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
2929 ** reading page 1 it discovers that the page-size of the database
2930 ** file is not pBt->pageSize. In this case lockBtree() will update
2931 ** pBt->pageSize to the page-size of the file on disk.
2932 */
2933 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
drh309169a2007-04-24 17:27:51 +00002934
drhb8ef32c2005-03-14 02:01:49 +00002935 if( rc==SQLITE_OK && wrflag ){
drhc9166342012-01-05 23:32:06 +00002936 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
drh309169a2007-04-24 17:27:51 +00002937 rc = SQLITE_READONLY;
2938 }else{
danielk1977d8293352009-04-30 09:10:37 +00002939 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
drh309169a2007-04-24 17:27:51 +00002940 if( rc==SQLITE_OK ){
2941 rc = newDatabase(pBt);
2942 }
drhb8ef32c2005-03-14 02:01:49 +00002943 }
2944 }
2945
danielk1977bd434552009-03-18 10:33:00 +00002946 if( rc!=SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00002947 unlockBtreeIfUnused(pBt);
2948 }
danf9b76712010-06-01 14:12:45 +00002949 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
danielk19771ceedd32008-11-19 10:22:33 +00002950 btreeInvokeBusyHandler(pBt) );
danielk1977aef0bf62005-12-30 16:28:01 +00002951
2952 if( rc==SQLITE_OK ){
2953 if( p->inTrans==TRANS_NONE ){
2954 pBt->nTransaction++;
danielk1977602b4662009-07-02 07:47:33 +00002955#ifndef SQLITE_OMIT_SHARED_CACHE
2956 if( p->sharable ){
drhf2f105d2012-08-20 15:53:54 +00002957 assert( p->lock.pBtree==p && p->lock.iTable==1 );
danielk1977602b4662009-07-02 07:47:33 +00002958 p->lock.eLock = READ_LOCK;
2959 p->lock.pNext = pBt->pLock;
2960 pBt->pLock = &p->lock;
2961 }
2962#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002963 }
2964 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2965 if( p->inTrans>pBt->inTransaction ){
2966 pBt->inTransaction = p->inTrans;
2967 }
danielk1977404ca072009-03-16 13:19:36 +00002968 if( wrflag ){
dan59257dc2010-08-04 11:34:31 +00002969 MemPage *pPage1 = pBt->pPage1;
2970#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977404ca072009-03-16 13:19:36 +00002971 assert( !pBt->pWriter );
2972 pBt->pWriter = p;
drhc9166342012-01-05 23:32:06 +00002973 pBt->btsFlags &= ~BTS_EXCLUSIVE;
2974 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
danielk1977641b0f42007-12-21 04:47:25 +00002975#endif
dan59257dc2010-08-04 11:34:31 +00002976
2977 /* If the db-size header field is incorrect (as it may be if an old
2978 ** client has been writing the database file), update it now. Doing
2979 ** this sooner rather than later means the database size can safely
2980 ** re-read the database size from page 1 if a savepoint or transaction
2981 ** rollback occurs within the transaction.
2982 */
2983 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
2984 rc = sqlite3PagerWrite(pPage1->pDbPage);
2985 if( rc==SQLITE_OK ){
2986 put4byte(&pPage1->aData[28], pBt->nPage);
2987 }
2988 }
2989 }
danielk1977aef0bf62005-12-30 16:28:01 +00002990 }
2991
drhd677b3d2007-08-20 22:48:41 +00002992
2993trans_begun:
danielk1977fd7f0452008-12-17 17:30:26 +00002994 if( rc==SQLITE_OK && wrflag ){
danielk197712dd5492008-12-18 15:45:07 +00002995 /* This call makes sure that the pager has the correct number of
2996 ** open savepoints. If the second parameter is greater than 0 and
2997 ** the sub-journal is not already open, then it will be opened here.
2998 */
danielk1977fd7f0452008-12-17 17:30:26 +00002999 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
3000 }
danielk197712dd5492008-12-18 15:45:07 +00003001
danielk1977aef0bf62005-12-30 16:28:01 +00003002 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00003003 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00003004 return rc;
drha059ad02001-04-17 20:09:11 +00003005}
3006
danielk1977687566d2004-11-02 12:56:41 +00003007#ifndef SQLITE_OMIT_AUTOVACUUM
3008
3009/*
3010** Set the pointer-map entries for all children of page pPage. Also, if
3011** pPage contains cells that point to overflow pages, set the pointer
3012** map entries for the overflow pages as well.
3013*/
3014static int setChildPtrmaps(MemPage *pPage){
3015 int i; /* Counter variable */
3016 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00003017 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00003018 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00003019 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00003020 Pgno pgno = pPage->pgno;
3021
drh1fee73e2007-08-29 04:00:57 +00003022 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197730548662009-07-09 05:07:37 +00003023 rc = btreeInitPage(pPage);
danielk19772df71c72007-05-24 07:22:42 +00003024 if( rc!=SQLITE_OK ){
3025 goto set_child_ptrmaps_out;
3026 }
danielk1977687566d2004-11-02 12:56:41 +00003027 nCell = pPage->nCell;
3028
3029 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00003030 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00003031
drh98add2e2009-07-20 17:11:49 +00003032 ptrmapPutOvflPtr(pPage, pCell, &rc);
danielk197726836652005-01-17 01:33:13 +00003033
danielk1977687566d2004-11-02 12:56:41 +00003034 if( !pPage->leaf ){
3035 Pgno childPgno = get4byte(pCell);
drh98add2e2009-07-20 17:11:49 +00003036 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00003037 }
3038 }
3039
3040 if( !pPage->leaf ){
3041 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh98add2e2009-07-20 17:11:49 +00003042 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00003043 }
3044
3045set_child_ptrmaps_out:
3046 pPage->isInit = isInitOrig;
3047 return rc;
3048}
3049
3050/*
drhf3aed592009-07-08 18:12:49 +00003051** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
3052** that it points to iTo. Parameter eType describes the type of pointer to
3053** be modified, as follows:
danielk1977687566d2004-11-02 12:56:41 +00003054**
3055** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
3056** page of pPage.
3057**
3058** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3059** page pointed to by one of the cells on pPage.
3060**
3061** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3062** overflow page in the list.
3063*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00003064static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00003065 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00003066 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977687566d2004-11-02 12:56:41 +00003067 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00003068 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00003069 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00003070 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00003071 }
danielk1977f78fc082004-11-02 14:40:32 +00003072 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00003073 }else{
drhf49661a2008-12-10 16:45:50 +00003074 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00003075 int i;
3076 int nCell;
3077
danielk197730548662009-07-09 05:07:37 +00003078 btreeInitPage(pPage);
danielk1977687566d2004-11-02 12:56:41 +00003079 nCell = pPage->nCell;
3080
danielk1977687566d2004-11-02 12:56:41 +00003081 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00003082 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00003083 if( eType==PTRMAP_OVERFLOW1 ){
3084 CellInfo info;
danielk197730548662009-07-09 05:07:37 +00003085 btreeParseCellPtr(pPage, pCell, &info);
drhe42a9b42011-08-31 13:27:19 +00003086 if( info.iOverflow
3087 && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
3088 && iFrom==get4byte(&pCell[info.iOverflow])
3089 ){
3090 put4byte(&pCell[info.iOverflow], iTo);
3091 break;
danielk1977687566d2004-11-02 12:56:41 +00003092 }
3093 }else{
3094 if( get4byte(pCell)==iFrom ){
3095 put4byte(pCell, iTo);
3096 break;
3097 }
3098 }
3099 }
3100
3101 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00003102 if( eType!=PTRMAP_BTREE ||
3103 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00003104 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00003105 }
danielk1977687566d2004-11-02 12:56:41 +00003106 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3107 }
3108
3109 pPage->isInit = isInitOrig;
3110 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00003111 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00003112}
3113
danielk1977003ba062004-11-04 02:57:33 +00003114
danielk19777701e812005-01-10 12:59:51 +00003115/*
3116** Move the open database page pDbPage to location iFreePage in the
3117** database. The pDbPage reference remains valid.
drhe64ca7b2009-07-16 18:21:17 +00003118**
3119** The isCommit flag indicates that there is no need to remember that
3120** the journal needs to be sync()ed before database page pDbPage->pgno
3121** can be written to. The caller has already promised not to write to that
3122** page.
danielk19777701e812005-01-10 12:59:51 +00003123*/
danielk1977003ba062004-11-04 02:57:33 +00003124static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00003125 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00003126 MemPage *pDbPage, /* Open page to move */
3127 u8 eType, /* Pointer map 'type' entry for pDbPage */
3128 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00003129 Pgno iFreePage, /* The location to move pDbPage to */
drhe64ca7b2009-07-16 18:21:17 +00003130 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
danielk1977003ba062004-11-04 02:57:33 +00003131){
3132 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
3133 Pgno iDbPage = pDbPage->pgno;
3134 Pager *pPager = pBt->pPager;
3135 int rc;
3136
danielk1977a0bf2652004-11-04 14:30:04 +00003137 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3138 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00003139 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00003140 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00003141
drh85b623f2007-12-13 21:54:09 +00003142 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00003143 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
3144 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00003145 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00003146 if( rc!=SQLITE_OK ){
3147 return rc;
3148 }
3149 pDbPage->pgno = iFreePage;
3150
3151 /* If pDbPage was a btree-page, then it may have child pages and/or cells
3152 ** that point to overflow pages. The pointer map entries for all these
3153 ** pages need to be changed.
3154 **
3155 ** If pDbPage is an overflow page, then the first 4 bytes may store a
3156 ** pointer to a subsequent overflow page. If this is the case, then
3157 ** the pointer map needs to be updated for the subsequent overflow page.
3158 */
danielk1977a0bf2652004-11-04 14:30:04 +00003159 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00003160 rc = setChildPtrmaps(pDbPage);
3161 if( rc!=SQLITE_OK ){
3162 return rc;
3163 }
3164 }else{
3165 Pgno nextOvfl = get4byte(pDbPage->aData);
3166 if( nextOvfl!=0 ){
drh98add2e2009-07-20 17:11:49 +00003167 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
danielk1977003ba062004-11-04 02:57:33 +00003168 if( rc!=SQLITE_OK ){
3169 return rc;
3170 }
3171 }
3172 }
3173
3174 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3175 ** that it points at iFreePage. Also fix the pointer map entry for
3176 ** iPtrPage.
3177 */
danielk1977a0bf2652004-11-04 14:30:04 +00003178 if( eType!=PTRMAP_ROOTPAGE ){
drhb00fc3b2013-08-21 23:42:32 +00003179 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00003180 if( rc!=SQLITE_OK ){
3181 return rc;
3182 }
danielk19773b8a05f2007-03-19 17:44:26 +00003183 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00003184 if( rc!=SQLITE_OK ){
3185 releasePage(pPtrPage);
3186 return rc;
3187 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00003188 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00003189 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003190 if( rc==SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00003191 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003192 }
danielk1977003ba062004-11-04 02:57:33 +00003193 }
danielk1977003ba062004-11-04 02:57:33 +00003194 return rc;
3195}
3196
danielk1977dddbcdc2007-04-26 14:42:34 +00003197/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00003198static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00003199
3200/*
dan51f0b6d2013-02-22 20:16:34 +00003201** Perform a single step of an incremental-vacuum. If successful, return
3202** SQLITE_OK. If there is no work to do (and therefore no point in
3203** calling this function again), return SQLITE_DONE. Or, if an error
3204** occurs, return some other error code.
danielk1977dddbcdc2007-04-26 14:42:34 +00003205**
peter.d.reid60ec9142014-09-06 16:39:46 +00003206** More specifically, this function attempts to re-organize the database so
dan51f0b6d2013-02-22 20:16:34 +00003207** that the last page of the file currently in use is no longer in use.
danielk1977dddbcdc2007-04-26 14:42:34 +00003208**
dan51f0b6d2013-02-22 20:16:34 +00003209** Parameter nFin is the number of pages that this database would contain
3210** were this function called until it returns SQLITE_DONE.
3211**
3212** If the bCommit parameter is non-zero, this function assumes that the
3213** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
peter.d.reid60ec9142014-09-06 16:39:46 +00003214** or an error. bCommit is passed true for an auto-vacuum-on-commit
dan51f0b6d2013-02-22 20:16:34 +00003215** operation, or false for an incremental vacuum.
danielk1977dddbcdc2007-04-26 14:42:34 +00003216*/
dan51f0b6d2013-02-22 20:16:34 +00003217static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
danielk1977dddbcdc2007-04-26 14:42:34 +00003218 Pgno nFreeList; /* Number of pages still on the free-list */
drhdd3cd972010-03-27 17:12:36 +00003219 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003220
drh1fee73e2007-08-29 04:00:57 +00003221 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977fa542f12009-04-02 18:28:08 +00003222 assert( iLastPg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00003223
3224 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003225 u8 eType;
3226 Pgno iPtrPage;
3227
3228 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977fa542f12009-04-02 18:28:08 +00003229 if( nFreeList==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003230 return SQLITE_DONE;
3231 }
3232
3233 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3234 if( rc!=SQLITE_OK ){
3235 return rc;
3236 }
3237 if( eType==PTRMAP_ROOTPAGE ){
3238 return SQLITE_CORRUPT_BKPT;
3239 }
3240
3241 if( eType==PTRMAP_FREEPAGE ){
dan51f0b6d2013-02-22 20:16:34 +00003242 if( bCommit==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003243 /* Remove the page from the files free-list. This is not required
dan51f0b6d2013-02-22 20:16:34 +00003244 ** if bCommit is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00003245 ** truncated to zero after this function returns, so it doesn't
3246 ** matter if it still contains some garbage entries.
3247 */
3248 Pgno iFreePg;
3249 MemPage *pFreePg;
dan51f0b6d2013-02-22 20:16:34 +00003250 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
danielk1977dddbcdc2007-04-26 14:42:34 +00003251 if( rc!=SQLITE_OK ){
3252 return rc;
3253 }
3254 assert( iFreePg==iLastPg );
3255 releasePage(pFreePg);
3256 }
3257 } else {
3258 Pgno iFreePg; /* Index of free page to move pLastPg to */
3259 MemPage *pLastPg;
dan51f0b6d2013-02-22 20:16:34 +00003260 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
3261 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
danielk1977dddbcdc2007-04-26 14:42:34 +00003262
drhb00fc3b2013-08-21 23:42:32 +00003263 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00003264 if( rc!=SQLITE_OK ){
3265 return rc;
3266 }
3267
dan51f0b6d2013-02-22 20:16:34 +00003268 /* If bCommit is zero, this loop runs exactly once and page pLastPg
danielk1977b4626a32007-04-28 15:47:43 +00003269 ** is swapped with the first free page pulled off the free list.
3270 **
dan51f0b6d2013-02-22 20:16:34 +00003271 ** On the other hand, if bCommit is greater than zero, then keep
danielk1977b4626a32007-04-28 15:47:43 +00003272 ** looping until a free-page located within the first nFin pages
3273 ** of the file is found.
3274 */
dan51f0b6d2013-02-22 20:16:34 +00003275 if( bCommit==0 ){
3276 eMode = BTALLOC_LE;
3277 iNear = nFin;
3278 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003279 do {
3280 MemPage *pFreePg;
dan51f0b6d2013-02-22 20:16:34 +00003281 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
danielk1977dddbcdc2007-04-26 14:42:34 +00003282 if( rc!=SQLITE_OK ){
3283 releasePage(pLastPg);
3284 return rc;
3285 }
3286 releasePage(pFreePg);
dan51f0b6d2013-02-22 20:16:34 +00003287 }while( bCommit && iFreePg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00003288 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00003289
dane1df4e32013-03-05 11:27:04 +00003290 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
danielk1977dddbcdc2007-04-26 14:42:34 +00003291 releasePage(pLastPg);
3292 if( rc!=SQLITE_OK ){
3293 return rc;
danielk1977662278e2007-11-05 15:30:12 +00003294 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003295 }
3296 }
3297
dan51f0b6d2013-02-22 20:16:34 +00003298 if( bCommit==0 ){
danbc1a3c62013-02-23 16:40:46 +00003299 do {
danielk19773460d192008-12-27 15:23:13 +00003300 iLastPg--;
danbc1a3c62013-02-23 16:40:46 +00003301 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
3302 pBt->bDoTruncate = 1;
drhdd3cd972010-03-27 17:12:36 +00003303 pBt->nPage = iLastPg;
danielk1977dddbcdc2007-04-26 14:42:34 +00003304 }
3305 return SQLITE_OK;
3306}
3307
3308/*
dan51f0b6d2013-02-22 20:16:34 +00003309** The database opened by the first argument is an auto-vacuum database
3310** nOrig pages in size containing nFree free pages. Return the expected
3311** size of the database in pages following an auto-vacuum operation.
3312*/
3313static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
3314 int nEntry; /* Number of entries on one ptrmap page */
3315 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
3316 Pgno nFin; /* Return value */
3317
3318 nEntry = pBt->usableSize/5;
3319 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
3320 nFin = nOrig - nFree - nPtrmap;
3321 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
3322 nFin--;
3323 }
3324 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3325 nFin--;
3326 }
dan51f0b6d2013-02-22 20:16:34 +00003327
3328 return nFin;
3329}
3330
3331/*
danielk1977dddbcdc2007-04-26 14:42:34 +00003332** A write-transaction must be opened before calling this function.
3333** It performs a single unit of work towards an incremental vacuum.
3334**
3335** If the incremental vacuum is finished after this function has run,
shanebe217792009-03-05 04:20:31 +00003336** SQLITE_DONE is returned. If it is not finished, but no error occurred,
danielk1977dddbcdc2007-04-26 14:42:34 +00003337** SQLITE_OK is returned. Otherwise an SQLite error code.
3338*/
3339int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00003340 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003341 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003342
3343 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00003344 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
3345 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00003346 rc = SQLITE_DONE;
3347 }else{
dan51f0b6d2013-02-22 20:16:34 +00003348 Pgno nOrig = btreePagecount(pBt);
3349 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
3350 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
3351
dan91384712013-02-24 11:50:43 +00003352 if( nOrig<nFin ){
3353 rc = SQLITE_CORRUPT_BKPT;
3354 }else if( nFree>0 ){
dan11dcd112013-03-15 18:29:18 +00003355 rc = saveAllCursors(pBt, 0, 0);
3356 if( rc==SQLITE_OK ){
3357 invalidateAllOverflowCache(pBt);
3358 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
3359 }
dan51f0b6d2013-02-22 20:16:34 +00003360 if( rc==SQLITE_OK ){
3361 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3362 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
3363 }
3364 }else{
3365 rc = SQLITE_DONE;
drhdd3cd972010-03-27 17:12:36 +00003366 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003367 }
drhd677b3d2007-08-20 22:48:41 +00003368 sqlite3BtreeLeave(p);
3369 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003370}
3371
3372/*
danielk19773b8a05f2007-03-19 17:44:26 +00003373** This routine is called prior to sqlite3PagerCommit when a transaction
drhf7b54962013-05-28 12:11:54 +00003374** is committed for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00003375**
3376** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
3377** the database file should be truncated to during the commit process.
3378** i.e. the database has been reorganized so that only the first *pnTrunc
3379** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00003380*/
danielk19773460d192008-12-27 15:23:13 +00003381static int autoVacuumCommit(BtShared *pBt){
danielk1977dddbcdc2007-04-26 14:42:34 +00003382 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00003383 Pager *pPager = pBt->pPager;
drhf94a1732008-09-30 17:18:17 +00003384 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00003385
drh1fee73e2007-08-29 04:00:57 +00003386 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00003387 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00003388 assert(pBt->autoVacuum);
3389 if( !pBt->incrVacuum ){
drhea8ffdf2009-07-22 00:35:23 +00003390 Pgno nFin; /* Number of pages in database after autovacuuming */
3391 Pgno nFree; /* Number of pages on the freelist initially */
drh41d628c2009-07-11 17:04:08 +00003392 Pgno iFree; /* The next page to be freed */
drh41d628c2009-07-11 17:04:08 +00003393 Pgno nOrig; /* Database size before freeing */
danielk1977687566d2004-11-02 12:56:41 +00003394
drhb1299152010-03-30 22:58:33 +00003395 nOrig = btreePagecount(pBt);
danielk1977ef165ce2009-04-06 17:50:03 +00003396 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
3397 /* It is not possible to create a database for which the final page
3398 ** is either a pointer-map page or the pending-byte page. If one
3399 ** is encountered, this indicates corruption.
3400 */
danielk19773460d192008-12-27 15:23:13 +00003401 return SQLITE_CORRUPT_BKPT;
3402 }
danielk1977ef165ce2009-04-06 17:50:03 +00003403
danielk19773460d192008-12-27 15:23:13 +00003404 nFree = get4byte(&pBt->pPage1->aData[36]);
dan51f0b6d2013-02-22 20:16:34 +00003405 nFin = finalDbSize(pBt, nOrig, nFree);
drhc5e47ac2009-06-04 00:11:56 +00003406 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
dan0aed84d2013-03-26 14:16:20 +00003407 if( nFin<nOrig ){
3408 rc = saveAllCursors(pBt, 0, 0);
3409 }
danielk19773460d192008-12-27 15:23:13 +00003410 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
dan51f0b6d2013-02-22 20:16:34 +00003411 rc = incrVacuumStep(pBt, nFin, iFree, 1);
danielk1977dddbcdc2007-04-26 14:42:34 +00003412 }
danielk19773460d192008-12-27 15:23:13 +00003413 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
danielk19773460d192008-12-27 15:23:13 +00003414 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3415 put4byte(&pBt->pPage1->aData[32], 0);
3416 put4byte(&pBt->pPage1->aData[36], 0);
drhdd3cd972010-03-27 17:12:36 +00003417 put4byte(&pBt->pPage1->aData[28], nFin);
danbc1a3c62013-02-23 16:40:46 +00003418 pBt->bDoTruncate = 1;
drhdd3cd972010-03-27 17:12:36 +00003419 pBt->nPage = nFin;
danielk1977dddbcdc2007-04-26 14:42:34 +00003420 }
3421 if( rc!=SQLITE_OK ){
3422 sqlite3PagerRollback(pPager);
3423 }
danielk1977687566d2004-11-02 12:56:41 +00003424 }
3425
dan0aed84d2013-03-26 14:16:20 +00003426 assert( nRef>=sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00003427 return rc;
3428}
danielk1977dddbcdc2007-04-26 14:42:34 +00003429
danielk1977a50d9aa2009-06-08 14:49:45 +00003430#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
3431# define setChildPtrmaps(x) SQLITE_OK
3432#endif
danielk1977687566d2004-11-02 12:56:41 +00003433
3434/*
drh80e35f42007-03-30 14:06:34 +00003435** This routine does the first phase of a two-phase commit. This routine
3436** causes a rollback journal to be created (if it does not already exist)
3437** and populated with enough information so that if a power loss occurs
3438** the database can be restored to its original state by playing back
3439** the journal. Then the contents of the journal are flushed out to
3440** the disk. After the journal is safely on oxide, the changes to the
3441** database are written into the database file and flushed to oxide.
3442** At the end of this call, the rollback journal still exists on the
3443** disk and we are still holding all locks, so the transaction has not
drh51898cf2009-04-19 20:51:06 +00003444** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
drh80e35f42007-03-30 14:06:34 +00003445** commit process.
3446**
3447** This call is a no-op if no write-transaction is currently active on pBt.
3448**
3449** Otherwise, sync the database file for the btree pBt. zMaster points to
3450** the name of a master journal file that should be written into the
3451** individual journal file, or is NULL, indicating no master journal file
3452** (single database transaction).
3453**
3454** When this is called, the master journal should already have been
3455** created, populated with this journal pointer and synced to disk.
3456**
3457** Once this is routine has returned, the only thing required to commit
3458** the write-transaction for this database file is to delete the journal.
3459*/
3460int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
3461 int rc = SQLITE_OK;
3462 if( p->inTrans==TRANS_WRITE ){
3463 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003464 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00003465#ifndef SQLITE_OMIT_AUTOVACUUM
3466 if( pBt->autoVacuum ){
danielk19773460d192008-12-27 15:23:13 +00003467 rc = autoVacuumCommit(pBt);
drh80e35f42007-03-30 14:06:34 +00003468 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00003469 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003470 return rc;
3471 }
3472 }
danbc1a3c62013-02-23 16:40:46 +00003473 if( pBt->bDoTruncate ){
3474 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
3475 }
drh80e35f42007-03-30 14:06:34 +00003476#endif
drh49b9d332009-01-02 18:10:42 +00003477 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
drhd677b3d2007-08-20 22:48:41 +00003478 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003479 }
3480 return rc;
3481}
3482
3483/*
danielk197794b30732009-07-02 17:21:57 +00003484** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
3485** at the conclusion of a transaction.
3486*/
3487static void btreeEndTransaction(Btree *p){
3488 BtShared *pBt = p->pBt;
drh1713afb2013-06-28 01:24:57 +00003489 sqlite3 *db = p->db;
danielk197794b30732009-07-02 17:21:57 +00003490 assert( sqlite3BtreeHoldsMutex(p) );
3491
danbc1a3c62013-02-23 16:40:46 +00003492#ifndef SQLITE_OMIT_AUTOVACUUM
3493 pBt->bDoTruncate = 0;
3494#endif
danc0537fe2013-06-28 19:41:43 +00003495 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
danfa401de2009-10-16 14:55:03 +00003496 /* If there are other active statements that belong to this database
3497 ** handle, downgrade to a read-only transaction. The other statements
3498 ** may still be reading from the database. */
danielk197794b30732009-07-02 17:21:57 +00003499 downgradeAllSharedCacheTableLocks(p);
3500 p->inTrans = TRANS_READ;
3501 }else{
3502 /* If the handle had any kind of transaction open, decrement the
3503 ** transaction count of the shared btree. If the transaction count
3504 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
3505 ** call below will unlock the pager. */
3506 if( p->inTrans!=TRANS_NONE ){
3507 clearAllSharedCacheTableLocks(p);
3508 pBt->nTransaction--;
3509 if( 0==pBt->nTransaction ){
3510 pBt->inTransaction = TRANS_NONE;
3511 }
3512 }
3513
3514 /* Set the current transaction state to TRANS_NONE and unlock the
3515 ** pager if this call closed the only read or write transaction. */
3516 p->inTrans = TRANS_NONE;
3517 unlockBtreeIfUnused(pBt);
3518 }
3519
3520 btreeIntegrity(p);
3521}
3522
3523/*
drh2aa679f2001-06-25 02:11:07 +00003524** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00003525**
drh6e345992007-03-30 11:12:08 +00003526** This routine implements the second phase of a 2-phase commit. The
drh51898cf2009-04-19 20:51:06 +00003527** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
3528** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
3529** routine did all the work of writing information out to disk and flushing the
drh6e345992007-03-30 11:12:08 +00003530** contents so that they are written onto the disk platter. All this
drh51898cf2009-04-19 20:51:06 +00003531** routine has to do is delete or truncate or zero the header in the
3532** the rollback journal (which causes the transaction to commit) and
3533** drop locks.
drh6e345992007-03-30 11:12:08 +00003534**
dan60939d02011-03-29 15:40:55 +00003535** Normally, if an error occurs while the pager layer is attempting to
3536** finalize the underlying journal file, this function returns an error and
3537** the upper layer will attempt a rollback. However, if the second argument
3538** is non-zero then this b-tree transaction is part of a multi-file
3539** transaction. In this case, the transaction has already been committed
3540** (by deleting a master journal file) and the caller will ignore this
3541** functions return code. So, even if an error occurs in the pager layer,
3542** reset the b-tree objects internal state to indicate that the write
3543** transaction has been closed. This is quite safe, as the pager will have
3544** transitioned to the error state.
3545**
drh5e00f6c2001-09-13 13:46:56 +00003546** This will release the write lock on the database file. If there
3547** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00003548*/
dan60939d02011-03-29 15:40:55 +00003549int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
danielk1977aef0bf62005-12-30 16:28:01 +00003550
drh075ed302010-10-14 01:17:30 +00003551 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003552 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003553 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003554
3555 /* If the handle has a write-transaction open, commit the shared-btrees
3556 ** transaction and set the shared state to TRANS_READ.
3557 */
3558 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00003559 int rc;
drh075ed302010-10-14 01:17:30 +00003560 BtShared *pBt = p->pBt;
danielk1977aef0bf62005-12-30 16:28:01 +00003561 assert( pBt->inTransaction==TRANS_WRITE );
3562 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00003563 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
dan60939d02011-03-29 15:40:55 +00003564 if( rc!=SQLITE_OK && bCleanup==0 ){
drhd677b3d2007-08-20 22:48:41 +00003565 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00003566 return rc;
3567 }
drh3da9c042014-12-22 18:41:21 +00003568 p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
danielk1977aef0bf62005-12-30 16:28:01 +00003569 pBt->inTransaction = TRANS_READ;
danbf0e57a2013-05-14 20:36:31 +00003570 btreeClearHasContent(pBt);
danielk1977ee5741e2004-05-31 10:01:34 +00003571 }
danielk1977aef0bf62005-12-30 16:28:01 +00003572
danielk197794b30732009-07-02 17:21:57 +00003573 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00003574 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00003575 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003576}
3577
drh80e35f42007-03-30 14:06:34 +00003578/*
3579** Do both phases of a commit.
3580*/
3581int sqlite3BtreeCommit(Btree *p){
3582 int rc;
drhd677b3d2007-08-20 22:48:41 +00003583 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00003584 rc = sqlite3BtreeCommitPhaseOne(p, 0);
3585 if( rc==SQLITE_OK ){
dan60939d02011-03-29 15:40:55 +00003586 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
drh80e35f42007-03-30 14:06:34 +00003587 }
drhd677b3d2007-08-20 22:48:41 +00003588 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003589 return rc;
3590}
3591
drhc39e0002004-05-07 23:50:57 +00003592/*
drhfb982642007-08-30 01:19:59 +00003593** This routine sets the state to CURSOR_FAULT and the error
drh47b7fc72014-11-11 01:33:57 +00003594** code to errCode for every cursor on any BtShared that pBtree
3595** references. Or if the writeOnly flag is set to 1, then only
3596** trip write cursors and leave read cursors unchanged.
drhfb982642007-08-30 01:19:59 +00003597**
drh47b7fc72014-11-11 01:33:57 +00003598** Every cursor is a candidate to be tripped, including cursors
3599** that belong to other database connections that happen to be
3600** sharing the cache with pBtree.
drhfb982642007-08-30 01:19:59 +00003601**
dan80231042014-11-12 14:56:02 +00003602** This routine gets called when a rollback occurs. If the writeOnly
3603** flag is true, then only write-cursors need be tripped - read-only
3604** cursors save their current positions so that they may continue
3605** following the rollback. Or, if writeOnly is false, all cursors are
3606** tripped. In general, writeOnly is false if the transaction being
3607** rolled back modified the database schema. In this case b-tree root
3608** pages may be moved or deleted from the database altogether, making
3609** it unsafe for read cursors to continue.
3610**
3611** If the writeOnly flag is true and an error is encountered while
3612** saving the current position of a read-only cursor, all cursors,
3613** including all read-cursors are tripped.
3614**
3615** SQLITE_OK is returned if successful, or if an error occurs while
3616** saving a cursor position, an SQLite error code.
drhfb982642007-08-30 01:19:59 +00003617*/
dan80231042014-11-12 14:56:02 +00003618int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
drhfb982642007-08-30 01:19:59 +00003619 BtCursor *p;
dan80231042014-11-12 14:56:02 +00003620 int rc = SQLITE_OK;
3621
drh47b7fc72014-11-11 01:33:57 +00003622 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
dan80231042014-11-12 14:56:02 +00003623 if( pBtree ){
3624 sqlite3BtreeEnter(pBtree);
3625 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
3626 int i;
3627 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
3628 if( p->eState==CURSOR_VALID ){
drhbea3b972014-11-18 20:22:05 +00003629 rc = saveCursorPosition(p);
dan80231042014-11-12 14:56:02 +00003630 if( rc!=SQLITE_OK ){
3631 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
3632 break;
3633 }
3634 }
3635 }else{
3636 sqlite3BtreeClearCursor(p);
3637 p->eState = CURSOR_FAULT;
3638 p->skipNext = errCode;
3639 }
3640 for(i=0; i<=p->iPage; i++){
3641 releasePage(p->apPage[i]);
3642 p->apPage[i] = 0;
3643 }
danielk1977bc2ca9e2008-11-13 14:28:28 +00003644 }
dan80231042014-11-12 14:56:02 +00003645 sqlite3BtreeLeave(pBtree);
drhfb982642007-08-30 01:19:59 +00003646 }
dan80231042014-11-12 14:56:02 +00003647 return rc;
drhfb982642007-08-30 01:19:59 +00003648}
3649
3650/*
drh47b7fc72014-11-11 01:33:57 +00003651** Rollback the transaction in progress.
3652**
3653** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
3654** Only write cursors are tripped if writeOnly is true but all cursors are
3655** tripped if writeOnly is false. Any attempt to use
3656** a tripped cursor will result in an error.
drh5e00f6c2001-09-13 13:46:56 +00003657**
3658** This will release the write lock on the database file. If there
3659** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00003660*/
drh47b7fc72014-11-11 01:33:57 +00003661int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
danielk19778d34dfd2006-01-24 16:37:57 +00003662 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003663 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00003664 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00003665
drh47b7fc72014-11-11 01:33:57 +00003666 assert( writeOnly==1 || writeOnly==0 );
3667 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
drhd677b3d2007-08-20 22:48:41 +00003668 sqlite3BtreeEnter(p);
drh0f198a72012-02-13 16:43:16 +00003669 if( tripCode==SQLITE_OK ){
3670 rc = tripCode = saveAllCursors(pBt, 0, 0);
drh47b7fc72014-11-11 01:33:57 +00003671 if( rc ) writeOnly = 0;
drh0f198a72012-02-13 16:43:16 +00003672 }else{
3673 rc = SQLITE_OK;
danielk19772b8c13e2006-01-24 14:21:24 +00003674 }
drh0f198a72012-02-13 16:43:16 +00003675 if( tripCode ){
dan80231042014-11-12 14:56:02 +00003676 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
3677 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
3678 if( rc2!=SQLITE_OK ) rc = rc2;
drh0f198a72012-02-13 16:43:16 +00003679 }
danielk1977aef0bf62005-12-30 16:28:01 +00003680 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003681
3682 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00003683 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00003684
danielk19778d34dfd2006-01-24 16:37:57 +00003685 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00003686 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00003687 if( rc2!=SQLITE_OK ){
3688 rc = rc2;
3689 }
3690
drh24cd67e2004-05-10 16:18:47 +00003691 /* The rollback may have destroyed the pPage1->aData value. So
danielk197730548662009-07-09 05:07:37 +00003692 ** call btreeGetPage() on page 1 again to make
drh16a9b832007-05-05 18:39:25 +00003693 ** sure pPage1->aData is set correctly. */
drhb00fc3b2013-08-21 23:42:32 +00003694 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh1f5b4672010-04-01 02:22:19 +00003695 int nPage = get4byte(28+(u8*)pPage1->aData);
3696 testcase( nPage==0 );
3697 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
3698 testcase( pBt->nPage!=nPage );
3699 pBt->nPage = nPage;
drh24cd67e2004-05-10 16:18:47 +00003700 releasePage(pPage1);
3701 }
drh85ec3b62013-05-14 23:12:06 +00003702 assert( countValidCursors(pBt, 1)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00003703 pBt->inTransaction = TRANS_READ;
danbf0e57a2013-05-14 20:36:31 +00003704 btreeClearHasContent(pBt);
drh24cd67e2004-05-10 16:18:47 +00003705 }
danielk1977aef0bf62005-12-30 16:28:01 +00003706
danielk197794b30732009-07-02 17:21:57 +00003707 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00003708 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00003709 return rc;
3710}
3711
3712/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003713** Start a statement subtransaction. The subtransaction can be rolled
danielk1977bd434552009-03-18 10:33:00 +00003714** back independently of the main transaction. You must start a transaction
3715** before starting a subtransaction. The subtransaction is ended automatically
3716** if the main transaction commits or rolls back.
drhab01f612004-05-22 02:55:23 +00003717**
3718** Statement subtransactions are used around individual SQL statements
3719** that are contained within a BEGIN...COMMIT block. If a constraint
3720** error occurs within the statement, the effect of that one statement
3721** can be rolled back without having to rollback the entire transaction.
danielk1977bd434552009-03-18 10:33:00 +00003722**
3723** A statement sub-transaction is implemented as an anonymous savepoint. The
3724** value passed as the second parameter is the total number of savepoints,
3725** including the new anonymous savepoint, open on the B-Tree. i.e. if there
3726** are no active savepoints and no other statement-transactions open,
3727** iStatement is 1. This anonymous savepoint can be released or rolled back
3728** using the sqlite3BtreeSavepoint() function.
drh663fc632002-02-02 18:49:19 +00003729*/
danielk1977bd434552009-03-18 10:33:00 +00003730int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
drh663fc632002-02-02 18:49:19 +00003731 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003732 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003733 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00003734 assert( p->inTrans==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00003735 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk1977bd434552009-03-18 10:33:00 +00003736 assert( iStatement>0 );
3737 assert( iStatement>p->db->nSavepoint );
drh5e0ccc22010-03-29 19:36:52 +00003738 assert( pBt->inTransaction==TRANS_WRITE );
3739 /* At the pager level, a statement transaction is a savepoint with
3740 ** an index greater than all savepoints created explicitly using
3741 ** SQL statements. It is illegal to open, release or rollback any
3742 ** such savepoints while the statement transaction savepoint is active.
3743 */
3744 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
drhd677b3d2007-08-20 22:48:41 +00003745 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00003746 return rc;
3747}
3748
3749/*
danielk1977fd7f0452008-12-17 17:30:26 +00003750** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
3751** or SAVEPOINT_RELEASE. This function either releases or rolls back the
danielk197712dd5492008-12-18 15:45:07 +00003752** savepoint identified by parameter iSavepoint, depending on the value
3753** of op.
3754**
3755** Normally, iSavepoint is greater than or equal to zero. However, if op is
3756** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
3757** contents of the entire transaction are rolled back. This is different
3758** from a normal transaction rollback, as no locks are released and the
3759** transaction remains open.
danielk1977fd7f0452008-12-17 17:30:26 +00003760*/
3761int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
3762 int rc = SQLITE_OK;
3763 if( p && p->inTrans==TRANS_WRITE ){
3764 BtShared *pBt = p->pBt;
danielk1977fd7f0452008-12-17 17:30:26 +00003765 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
3766 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
3767 sqlite3BtreeEnter(p);
danielk1977fd7f0452008-12-17 17:30:26 +00003768 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
drh9f0bbf92009-01-02 21:08:09 +00003769 if( rc==SQLITE_OK ){
drhc9166342012-01-05 23:32:06 +00003770 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
3771 pBt->nPage = 0;
3772 }
drh9f0bbf92009-01-02 21:08:09 +00003773 rc = newDatabase(pBt);
drhdd3cd972010-03-27 17:12:36 +00003774 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
drhb9b49bf2010-08-05 03:21:39 +00003775
3776 /* The database size was written into the offset 28 of the header
3777 ** when the transaction started, so we know that the value at offset
3778 ** 28 is nonzero. */
3779 assert( pBt->nPage>0 );
drh9f0bbf92009-01-02 21:08:09 +00003780 }
danielk1977fd7f0452008-12-17 17:30:26 +00003781 sqlite3BtreeLeave(p);
3782 }
3783 return rc;
3784}
3785
3786/*
drh8b2f49b2001-06-08 00:21:52 +00003787** Create a new cursor for the BTree whose root is on the page
danielk19773e8add92009-07-04 17:16:00 +00003788** iTable. If a read-only cursor is requested, it is assumed that
3789** the caller already has at least a read-only transaction open
3790** on the database already. If a write-cursor is requested, then
3791** the caller is assumed to have an open write transaction.
drh1bee3d72001-10-15 00:44:35 +00003792**
3793** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00003794** If wrFlag==1, then the cursor can be used for reading or for
3795** writing if other conditions for writing are also met. These
3796** are the conditions that must be met in order for writing to
3797** be allowed:
drh6446c4d2001-12-15 14:22:18 +00003798**
drhf74b8d92002-09-01 23:20:45 +00003799** 1: The cursor must have been opened with wrFlag==1
3800**
drhfe5d71d2007-03-19 11:54:10 +00003801** 2: Other database connections that share the same pager cache
3802** but which are not in the READ_UNCOMMITTED state may not have
3803** cursors open with wrFlag==0 on the same table. Otherwise
3804** the changes made by this write cursor would be visible to
3805** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00003806**
3807** 3: The database must be writable (not on read-only media)
3808**
3809** 4: There must be an active transaction.
3810**
drh6446c4d2001-12-15 14:22:18 +00003811** No checking is done to make sure that page iTable really is the
3812** root page of a b-tree. If it is not, then the cursor acquired
3813** will not work correctly.
danielk197771d5d2c2008-09-29 11:49:47 +00003814**
drhf25a5072009-11-18 23:01:25 +00003815** It is assumed that the sqlite3BtreeCursorZero() has been called
3816** on pCur to initialize the memory space prior to invoking this routine.
drha059ad02001-04-17 20:09:11 +00003817*/
drhd677b3d2007-08-20 22:48:41 +00003818static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00003819 Btree *p, /* The btree */
3820 int iTable, /* Root page of table to open */
3821 int wrFlag, /* 1 to write. 0 read-only */
3822 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
3823 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00003824){
danielk19773e8add92009-07-04 17:16:00 +00003825 BtShared *pBt = p->pBt; /* Shared b-tree handle */
drhecdc7532001-09-23 02:35:53 +00003826
drh1fee73e2007-08-29 04:00:57 +00003827 assert( sqlite3BtreeHoldsMutex(p) );
drhf49661a2008-12-10 16:45:50 +00003828 assert( wrFlag==0 || wrFlag==1 );
danielk197796d48e92009-06-29 06:00:37 +00003829
danielk1977602b4662009-07-02 07:47:33 +00003830 /* The following assert statements verify that if this is a sharable
3831 ** b-tree database, the connection is holding the required table locks,
3832 ** and that no other connection has any open cursor that conflicts with
3833 ** this lock. */
3834 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
danielk197796d48e92009-06-29 06:00:37 +00003835 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
3836
danielk19773e8add92009-07-04 17:16:00 +00003837 /* Assert that the caller has opened the required transaction. */
3838 assert( p->inTrans>TRANS_NONE );
3839 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
3840 assert( pBt->pPage1 && pBt->pPage1->aData );
3841
drhc9166342012-01-05 23:32:06 +00003842 if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
danielk197796d48e92009-06-29 06:00:37 +00003843 return SQLITE_READONLY;
drha0c9a112004-03-10 13:42:37 +00003844 }
drh3fbb0222014-09-24 19:47:27 +00003845 if( wrFlag ){
3846 allocateTempSpace(pBt);
3847 if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM;
3848 }
drhb1299152010-03-30 22:58:33 +00003849 if( iTable==1 && btreePagecount(pBt)==0 ){
dana205a482011-08-27 18:48:57 +00003850 assert( wrFlag==0 );
3851 iTable = 0;
danielk19773e8add92009-07-04 17:16:00 +00003852 }
danielk1977aef0bf62005-12-30 16:28:01 +00003853
danielk1977aef0bf62005-12-30 16:28:01 +00003854 /* Now that no other errors can occur, finish filling in the BtCursor
danielk19773e8add92009-07-04 17:16:00 +00003855 ** variables and link the cursor into the BtShared list. */
danielk1977172114a2009-07-07 15:47:12 +00003856 pCur->pgnoRoot = (Pgno)iTable;
3857 pCur->iPage = -1;
drh1e968a02008-03-25 00:22:21 +00003858 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00003859 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00003860 pCur->pBt = pBt;
drh4c417182014-03-31 23:57:41 +00003861 assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
3862 pCur->curFlags = wrFlag;
drha059ad02001-04-17 20:09:11 +00003863 pCur->pNext = pBt->pCursor;
3864 if( pCur->pNext ){
3865 pCur->pNext->pPrev = pCur;
3866 }
3867 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00003868 pCur->eState = CURSOR_INVALID;
danielk1977aef0bf62005-12-30 16:28:01 +00003869 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003870}
drhd677b3d2007-08-20 22:48:41 +00003871int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00003872 Btree *p, /* The btree */
3873 int iTable, /* Root page of table to open */
3874 int wrFlag, /* 1 to write. 0 read-only */
3875 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
3876 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00003877){
3878 int rc;
3879 sqlite3BtreeEnter(p);
danielk1977cd3e8f72008-03-25 09:47:35 +00003880 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
drhd677b3d2007-08-20 22:48:41 +00003881 sqlite3BtreeLeave(p);
3882 return rc;
3883}
drh7f751222009-03-17 22:33:00 +00003884
3885/*
3886** Return the size of a BtCursor object in bytes.
3887**
3888** This interfaces is needed so that users of cursors can preallocate
3889** sufficient storage to hold a cursor. The BtCursor object is opaque
3890** to users so they cannot do the sizeof() themselves - they must call
3891** this routine.
3892*/
3893int sqlite3BtreeCursorSize(void){
drhc54055b2009-11-13 17:05:53 +00003894 return ROUND8(sizeof(BtCursor));
danielk1977cd3e8f72008-03-25 09:47:35 +00003895}
3896
drh7f751222009-03-17 22:33:00 +00003897/*
drhf25a5072009-11-18 23:01:25 +00003898** Initialize memory that will be converted into a BtCursor object.
3899**
3900** The simple approach here would be to memset() the entire object
3901** to zero. But it turns out that the apPage[] and aiIdx[] arrays
3902** do not need to be zeroed and they are large, so we can save a lot
3903** of run-time by skipping the initialization of those elements.
3904*/
3905void sqlite3BtreeCursorZero(BtCursor *p){
3906 memset(p, 0, offsetof(BtCursor, iPage));
3907}
3908
3909/*
drh5e00f6c2001-09-13 13:46:56 +00003910** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00003911** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00003912*/
drh3aac2dd2004-04-26 14:10:20 +00003913int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00003914 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00003915 if( pBtree ){
danielk197771d5d2c2008-09-29 11:49:47 +00003916 int i;
danielk1977cd3e8f72008-03-25 09:47:35 +00003917 BtShared *pBt = pCur->pBt;
3918 sqlite3BtreeEnter(pBtree);
danielk1977be51a652008-10-08 17:58:48 +00003919 sqlite3BtreeClearCursor(pCur);
danielk1977cd3e8f72008-03-25 09:47:35 +00003920 if( pCur->pPrev ){
3921 pCur->pPrev->pNext = pCur->pNext;
3922 }else{
3923 pBt->pCursor = pCur->pNext;
3924 }
3925 if( pCur->pNext ){
3926 pCur->pNext->pPrev = pCur->pPrev;
3927 }
danielk197771d5d2c2008-09-29 11:49:47 +00003928 for(i=0; i<=pCur->iPage; i++){
3929 releasePage(pCur->apPage[i]);
3930 }
danielk1977cd3e8f72008-03-25 09:47:35 +00003931 unlockBtreeIfUnused(pBt);
dan85753662014-12-11 16:38:18 +00003932 sqlite3_free(pCur->aOverflow);
danielk1977cd3e8f72008-03-25 09:47:35 +00003933 /* sqlite3_free(pCur); */
3934 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00003935 }
drh8c42ca92001-06-22 19:15:00 +00003936 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003937}
3938
drh5e2f8b92001-05-28 00:41:15 +00003939/*
drh86057612007-06-26 01:04:48 +00003940** Make sure the BtCursor* given in the argument has a valid
3941** BtCursor.info structure. If it is not already valid, call
danielk197730548662009-07-09 05:07:37 +00003942** btreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00003943**
3944** BtCursor.info is a cache of the information in the current cell.
danielk197730548662009-07-09 05:07:37 +00003945** Using this cache reduces the number of calls to btreeParseCell().
drh86057612007-06-26 01:04:48 +00003946**
3947** 2007-06-25: There is a bug in some versions of MSVC that cause the
3948** compiler to crash when getCellInfo() is implemented as a macro.
3949** But there is a measureable speed advantage to using the macro on gcc
3950** (when less compiler optimizations like -Os or -O0 are used and the
peter.d.reid60ec9142014-09-06 16:39:46 +00003951** compiler is not doing aggressive inlining.) So we use a real function
drh86057612007-06-26 01:04:48 +00003952** for MSVC and a macro for everything else. Ticket #2457.
drh9188b382004-05-14 21:12:22 +00003953*/
drh9188b382004-05-14 21:12:22 +00003954#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00003955 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00003956 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00003957 int iPage = pCur->iPage;
drh51c6d962004-06-06 00:42:25 +00003958 memset(&info, 0, sizeof(info));
danielk197730548662009-07-09 05:07:37 +00003959 btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
dan7df42ab2014-01-20 18:25:44 +00003960 assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00003961 }
danielk19771cc5ed82007-05-16 17:28:43 +00003962#else
3963 #define assertCellInfo(x)
3964#endif
drh86057612007-06-26 01:04:48 +00003965#ifdef _MSC_VER
3966 /* Use a real function in MSVC to work around bugs in that compiler. */
3967 static void getCellInfo(BtCursor *pCur){
3968 if( pCur->info.nSize==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003969 int iPage = pCur->iPage;
danielk197730548662009-07-09 05:07:37 +00003970 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
drh036dbec2014-03-11 23:40:44 +00003971 pCur->curFlags |= BTCF_ValidNKey;
drh86057612007-06-26 01:04:48 +00003972 }else{
3973 assertCellInfo(pCur);
3974 }
3975 }
3976#else /* if not _MSC_VER */
3977 /* Use a macro in all other compilers so that the function is inlined */
danielk197771d5d2c2008-09-29 11:49:47 +00003978#define getCellInfo(pCur) \
3979 if( pCur->info.nSize==0 ){ \
3980 int iPage = pCur->iPage; \
drh036dbec2014-03-11 23:40:44 +00003981 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
3982 pCur->curFlags |= BTCF_ValidNKey; \
danielk197771d5d2c2008-09-29 11:49:47 +00003983 }else{ \
3984 assertCellInfo(pCur); \
drh86057612007-06-26 01:04:48 +00003985 }
3986#endif /* _MSC_VER */
drh9188b382004-05-14 21:12:22 +00003987
drhea8ffdf2009-07-22 00:35:23 +00003988#ifndef NDEBUG /* The next routine used only within assert() statements */
3989/*
3990** Return true if the given BtCursor is valid. A valid cursor is one
3991** that is currently pointing to a row in a (non-empty) table.
3992** This is a verification routine is used only within assert() statements.
3993*/
3994int sqlite3BtreeCursorIsValid(BtCursor *pCur){
3995 return pCur && pCur->eState==CURSOR_VALID;
3996}
3997#endif /* NDEBUG */
3998
drh9188b382004-05-14 21:12:22 +00003999/*
drh3aac2dd2004-04-26 14:10:20 +00004000** Set *pSize to the size of the buffer needed to hold the value of
4001** the key for the current entry. If the cursor is not pointing
4002** to a valid entry, *pSize is set to 0.
4003**
drh4b70f112004-05-02 21:12:19 +00004004** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00004005** itself, not the number of bytes in the key.
drhea8ffdf2009-07-22 00:35:23 +00004006**
4007** The caller must position the cursor prior to invoking this routine.
4008**
4009** This routine cannot fail. It always returns SQLITE_OK.
drh7e3b0a02001-04-28 16:52:40 +00004010*/
drh4a1c3802004-05-12 15:15:47 +00004011int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drh1fee73e2007-08-29 04:00:57 +00004012 assert( cursorHoldsMutex(pCur) );
drhc5352b92014-11-17 20:33:07 +00004013 assert( pCur->eState==CURSOR_VALID );
4014 getCellInfo(pCur);
4015 *pSize = pCur->info.nKey;
drhea8ffdf2009-07-22 00:35:23 +00004016 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00004017}
drh2af926b2001-05-15 00:39:25 +00004018
drh72f82862001-05-24 21:06:34 +00004019/*
drh0e1c19e2004-05-11 00:58:56 +00004020** Set *pSize to the number of bytes of data in the entry the
drhea8ffdf2009-07-22 00:35:23 +00004021** cursor currently points to.
4022**
4023** The caller must guarantee that the cursor is pointing to a non-NULL
4024** valid entry. In other words, the calling procedure must guarantee
4025** that the cursor has Cursor.eState==CURSOR_VALID.
4026**
4027** Failure is not possible. This function always returns SQLITE_OK.
4028** It might just as well be a procedure (returning void) but we continue
4029** to return an integer result code for historical reasons.
drh0e1c19e2004-05-11 00:58:56 +00004030*/
4031int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drh1fee73e2007-08-29 04:00:57 +00004032 assert( cursorHoldsMutex(pCur) );
drhea8ffdf2009-07-22 00:35:23 +00004033 assert( pCur->eState==CURSOR_VALID );
drhf94c9482015-03-25 12:05:49 +00004034 assert( pCur->iPage>=0 );
4035 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
drh3e28ff52014-09-24 00:59:08 +00004036 assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
drhea8ffdf2009-07-22 00:35:23 +00004037 getCellInfo(pCur);
drhab1cc582014-09-23 21:25:19 +00004038 *pSize = pCur->info.nPayload;
drhea8ffdf2009-07-22 00:35:23 +00004039 return SQLITE_OK;
drh0e1c19e2004-05-11 00:58:56 +00004040}
4041
4042/*
danielk1977d04417962007-05-02 13:16:30 +00004043** Given the page number of an overflow page in the database (parameter
4044** ovfl), this function finds the page number of the next page in the
4045** linked list of overflow pages. If possible, it uses the auto-vacuum
4046** pointer-map data instead of reading the content of page ovfl to do so.
4047**
4048** If an error occurs an SQLite error code is returned. Otherwise:
4049**
danielk1977bea2a942009-01-20 17:06:27 +00004050** The page number of the next overflow page in the linked list is
4051** written to *pPgnoNext. If page ovfl is the last page in its linked
4052** list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00004053**
danielk1977bea2a942009-01-20 17:06:27 +00004054** If ppPage is not NULL, and a reference to the MemPage object corresponding
4055** to page number pOvfl was obtained, then *ppPage is set to point to that
4056** reference. It is the responsibility of the caller to call releasePage()
4057** on *ppPage to free the reference. In no reference was obtained (because
4058** the pointer-map was used to obtain the value for *pPgnoNext), then
4059** *ppPage is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00004060*/
4061static int getOverflowPage(
drhfa3be902009-07-07 02:44:07 +00004062 BtShared *pBt, /* The database file */
4063 Pgno ovfl, /* Current overflow page number */
danielk1977bea2a942009-01-20 17:06:27 +00004064 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
danielk1977d04417962007-05-02 13:16:30 +00004065 Pgno *pPgnoNext /* OUT: Next overflow page number */
4066){
4067 Pgno next = 0;
danielk1977bea2a942009-01-20 17:06:27 +00004068 MemPage *pPage = 0;
drh1bd10f82008-12-10 21:19:56 +00004069 int rc = SQLITE_OK;
danielk1977d04417962007-05-02 13:16:30 +00004070
drh1fee73e2007-08-29 04:00:57 +00004071 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bea2a942009-01-20 17:06:27 +00004072 assert(pPgnoNext);
danielk1977d04417962007-05-02 13:16:30 +00004073
4074#ifndef SQLITE_OMIT_AUTOVACUUM
4075 /* Try to find the next page in the overflow list using the
4076 ** autovacuum pointer-map pages. Guess that the next page in
4077 ** the overflow list is page number (ovfl+1). If that guess turns
4078 ** out to be wrong, fall back to loading the data of page
4079 ** number ovfl to determine the next page number.
4080 */
4081 if( pBt->autoVacuum ){
4082 Pgno pgno;
4083 Pgno iGuess = ovfl+1;
4084 u8 eType;
4085
4086 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4087 iGuess++;
4088 }
4089
drhb1299152010-03-30 22:58:33 +00004090 if( iGuess<=btreePagecount(pBt) ){
danielk1977d04417962007-05-02 13:16:30 +00004091 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
danielk1977bea2a942009-01-20 17:06:27 +00004092 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
danielk1977d04417962007-05-02 13:16:30 +00004093 next = iGuess;
danielk1977bea2a942009-01-20 17:06:27 +00004094 rc = SQLITE_DONE;
danielk1977d04417962007-05-02 13:16:30 +00004095 }
4096 }
4097 }
4098#endif
4099
danielk1977d8a3f3d2009-07-11 11:45:23 +00004100 assert( next==0 || rc==SQLITE_DONE );
danielk1977bea2a942009-01-20 17:06:27 +00004101 if( rc==SQLITE_OK ){
drhb00fc3b2013-08-21 23:42:32 +00004102 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
danielk1977d8a3f3d2009-07-11 11:45:23 +00004103 assert( rc==SQLITE_OK || pPage==0 );
4104 if( rc==SQLITE_OK ){
danielk1977d04417962007-05-02 13:16:30 +00004105 next = get4byte(pPage->aData);
4106 }
danielk1977443c0592009-01-16 15:21:05 +00004107 }
danielk197745d68822009-01-16 16:23:38 +00004108
danielk1977bea2a942009-01-20 17:06:27 +00004109 *pPgnoNext = next;
4110 if( ppPage ){
4111 *ppPage = pPage;
4112 }else{
4113 releasePage(pPage);
4114 }
4115 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
danielk1977d04417962007-05-02 13:16:30 +00004116}
4117
danielk1977da107192007-05-04 08:32:13 +00004118/*
4119** Copy data from a buffer to a page, or from a page to a buffer.
4120**
4121** pPayload is a pointer to data stored on database page pDbPage.
4122** If argument eOp is false, then nByte bytes of data are copied
4123** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4124** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4125** of data are copied from the buffer pBuf to pPayload.
4126**
4127** SQLITE_OK is returned on success, otherwise an error code.
4128*/
4129static int copyPayload(
4130 void *pPayload, /* Pointer to page data */
4131 void *pBuf, /* Pointer to buffer */
4132 int nByte, /* Number of bytes to copy */
4133 int eOp, /* 0 -> copy from page, 1 -> copy to page */
4134 DbPage *pDbPage /* Page containing pPayload */
4135){
4136 if( eOp ){
4137 /* Copy data from buffer to page (a write operation) */
4138 int rc = sqlite3PagerWrite(pDbPage);
4139 if( rc!=SQLITE_OK ){
4140 return rc;
4141 }
4142 memcpy(pPayload, pBuf, nByte);
4143 }else{
4144 /* Copy data from page to buffer (a read operation) */
4145 memcpy(pBuf, pPayload, nByte);
4146 }
4147 return SQLITE_OK;
4148}
danielk1977d04417962007-05-02 13:16:30 +00004149
4150/*
danielk19779f8d6402007-05-02 17:48:45 +00004151** This function is used to read or overwrite payload information
dan5a500af2014-03-11 20:33:04 +00004152** for the entry that the pCur cursor is pointing to. The eOp
4153** argument is interpreted as follows:
4154**
4155** 0: The operation is a read. Populate the overflow cache.
4156** 1: The operation is a write. Populate the overflow cache.
4157** 2: The operation is a read. Do not populate the overflow cache.
danielk19779f8d6402007-05-02 17:48:45 +00004158**
4159** A total of "amt" bytes are read or written beginning at "offset".
4160** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00004161**
drh3bcdfd22009-07-12 02:32:21 +00004162** The content being read or written might appear on the main page
4163** or be scattered out on multiple overflow pages.
danielk1977da107192007-05-04 08:32:13 +00004164**
dan5a500af2014-03-11 20:33:04 +00004165** If the current cursor entry uses one or more overflow pages and the
4166** eOp argument is not 2, this function may allocate space for and lazily
peter.d.reid60ec9142014-09-06 16:39:46 +00004167** populates the overflow page-list cache array (BtCursor.aOverflow).
dan5a500af2014-03-11 20:33:04 +00004168** Subsequent calls use this cache to make seeking to the supplied offset
4169** more efficient.
danielk1977da107192007-05-04 08:32:13 +00004170**
4171** Once an overflow page-list cache has been allocated, it may be
4172** invalidated if some other cursor writes to the same table, or if
4173** the cursor is moved to a different row. Additionally, in auto-vacuum
4174** mode, the following events may invalidate an overflow page-list cache.
4175**
4176** * An incremental vacuum,
4177** * A commit in auto_vacuum="full" mode,
4178** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00004179*/
danielk19779f8d6402007-05-02 17:48:45 +00004180static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00004181 BtCursor *pCur, /* Cursor pointing to entry to read from */
danielk197789d40042008-11-17 14:20:56 +00004182 u32 offset, /* Begin reading this far into payload */
4183 u32 amt, /* Read this many bytes */
drh3aac2dd2004-04-26 14:10:20 +00004184 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00004185 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00004186){
4187 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00004188 int rc = SQLITE_OK;
danielk19772dec9702007-05-02 16:48:37 +00004189 int iIdx = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004190 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
danielk19770d065412008-11-12 18:21:36 +00004191 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh4c417182014-03-31 23:57:41 +00004192#ifdef SQLITE_DIRECT_OVERFLOW_READ
dan9501a642014-10-01 12:01:10 +00004193 unsigned char * const pBufStart = pBuf;
drh3f387402014-09-24 01:23:00 +00004194 int bEnd; /* True if reading to end of data */
drh4c417182014-03-31 23:57:41 +00004195#endif
drh3aac2dd2004-04-26 14:10:20 +00004196
danielk1977da107192007-05-04 08:32:13 +00004197 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00004198 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004199 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh1fee73e2007-08-29 04:00:57 +00004200 assert( cursorHoldsMutex(pCur) );
drh3f387402014-09-24 01:23:00 +00004201 assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */
danielk1977da107192007-05-04 08:32:13 +00004202
drh86057612007-06-26 01:04:48 +00004203 getCellInfo(pCur);
drhab1cc582014-09-23 21:25:19 +00004204 aPayload = pCur->info.pPayload;
drh4c417182014-03-31 23:57:41 +00004205#ifdef SQLITE_DIRECT_OVERFLOW_READ
drhab1cc582014-09-23 21:25:19 +00004206 bEnd = offset+amt==pCur->info.nPayload;
drh4c417182014-03-31 23:57:41 +00004207#endif
drhab1cc582014-09-23 21:25:19 +00004208 assert( offset+amt <= pCur->info.nPayload );
danielk1977da107192007-05-04 08:32:13 +00004209
drhab1cc582014-09-23 21:25:19 +00004210 if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){
danielk1977da107192007-05-04 08:32:13 +00004211 /* Trying to read or write past the end of the data is an error */
danielk197767fd7a92008-09-10 17:53:35 +00004212 return SQLITE_CORRUPT_BKPT;
drh3aac2dd2004-04-26 14:10:20 +00004213 }
danielk1977da107192007-05-04 08:32:13 +00004214
4215 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00004216 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00004217 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00004218 if( a+offset>pCur->info.nLocal ){
4219 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00004220 }
dan5a500af2014-03-11 20:33:04 +00004221 rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00004222 offset = 0;
drha34b6762004-05-07 13:30:42 +00004223 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00004224 amt -= a;
drhdd793422001-06-28 01:54:48 +00004225 }else{
drhfa1a98a2004-05-14 19:08:17 +00004226 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00004227 }
danielk1977da107192007-05-04 08:32:13 +00004228
dan85753662014-12-11 16:38:18 +00004229
danielk1977da107192007-05-04 08:32:13 +00004230 if( rc==SQLITE_OK && amt>0 ){
danielk197789d40042008-11-17 14:20:56 +00004231 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
danielk1977da107192007-05-04 08:32:13 +00004232 Pgno nextPage;
4233
drhfa1a98a2004-05-14 19:08:17 +00004234 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00004235
drha38c9512014-04-01 01:24:34 +00004236 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
4237 ** Except, do not allocate aOverflow[] for eOp==2.
4238 **
4239 ** The aOverflow[] array is sized at one entry for each overflow page
4240 ** in the overflow chain. The page number of the first overflow page is
4241 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
4242 ** means "not yet known" (the cache is lazily populated).
danielk1977da107192007-05-04 08:32:13 +00004243 */
drh036dbec2014-03-11 23:40:44 +00004244 if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
danielk19772dec9702007-05-02 16:48:37 +00004245 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
dan5a500af2014-03-11 20:33:04 +00004246 if( nOvfl>pCur->nOvflAlloc ){
dan85753662014-12-11 16:38:18 +00004247 Pgno *aNew = (Pgno*)sqlite3Realloc(
4248 pCur->aOverflow, nOvfl*2*sizeof(Pgno)
dan5a500af2014-03-11 20:33:04 +00004249 );
4250 if( aNew==0 ){
4251 rc = SQLITE_NOMEM;
4252 }else{
4253 pCur->nOvflAlloc = nOvfl*2;
4254 pCur->aOverflow = aNew;
4255 }
4256 }
4257 if( rc==SQLITE_OK ){
4258 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
drh036dbec2014-03-11 23:40:44 +00004259 pCur->curFlags |= BTCF_ValidOvfl;
danielk19772dec9702007-05-02 16:48:37 +00004260 }
4261 }
danielk1977da107192007-05-04 08:32:13 +00004262
4263 /* If the overflow page-list cache has been allocated and the
4264 ** entry for the first required overflow page is valid, skip
4265 ** directly to it.
4266 */
drh3f387402014-09-24 01:23:00 +00004267 if( (pCur->curFlags & BTCF_ValidOvfl)!=0
4268 && pCur->aOverflow[offset/ovflSize]
4269 ){
danielk19772dec9702007-05-02 16:48:37 +00004270 iIdx = (offset/ovflSize);
4271 nextPage = pCur->aOverflow[iIdx];
4272 offset = (offset%ovflSize);
4273 }
danielk1977da107192007-05-04 08:32:13 +00004274
4275 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
4276
danielk1977da107192007-05-04 08:32:13 +00004277 /* If required, populate the overflow page-list cache. */
drh036dbec2014-03-11 23:40:44 +00004278 if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
danielk1977da107192007-05-04 08:32:13 +00004279 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
4280 pCur->aOverflow[iIdx] = nextPage;
4281 }
danielk1977da107192007-05-04 08:32:13 +00004282
danielk1977d04417962007-05-02 13:16:30 +00004283 if( offset>=ovflSize ){
4284 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00004285 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00004286 ** data is not required. So first try to lookup the overflow
4287 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00004288 ** function.
drha38c9512014-04-01 01:24:34 +00004289 **
4290 ** Note that the aOverflow[] array must be allocated because eOp!=2
4291 ** here. If eOp==2, then offset==0 and this branch is never taken.
danielk1977d04417962007-05-02 13:16:30 +00004292 */
drha38c9512014-04-01 01:24:34 +00004293 assert( eOp!=2 );
4294 assert( pCur->curFlags & BTCF_ValidOvfl );
dan85753662014-12-11 16:38:18 +00004295 assert( pCur->pBtree->db==pBt->db );
drha38c9512014-04-01 01:24:34 +00004296 if( pCur->aOverflow[iIdx+1] ){
danielk1977da107192007-05-04 08:32:13 +00004297 nextPage = pCur->aOverflow[iIdx+1];
drha38c9512014-04-01 01:24:34 +00004298 }else{
danielk1977da107192007-05-04 08:32:13 +00004299 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
drha38c9512014-04-01 01:24:34 +00004300 }
danielk1977da107192007-05-04 08:32:13 +00004301 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00004302 }else{
danielk19779f8d6402007-05-02 17:48:45 +00004303 /* Need to read this page properly. It contains some of the
4304 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00004305 */
danf4ba1092011-10-08 14:57:07 +00004306#ifdef SQLITE_DIRECT_OVERFLOW_READ
4307 sqlite3_file *fd;
4308#endif
danielk1977cfe9a692004-06-16 12:00:29 +00004309 int a = amt;
danf4ba1092011-10-08 14:57:07 +00004310 if( a + offset > ovflSize ){
4311 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00004312 }
danf4ba1092011-10-08 14:57:07 +00004313
4314#ifdef SQLITE_DIRECT_OVERFLOW_READ
4315 /* If all the following are true:
4316 **
4317 ** 1) this is a read operation, and
4318 ** 2) data is required from the start of this overflow page, and
4319 ** 3) the database is file-backed, and
4320 ** 4) there is no open write-transaction, and
4321 ** 5) the database is not a WAL database,
dan9bc21b52014-03-20 18:56:35 +00004322 ** 6) all data from the page is being read.
dan9501a642014-10-01 12:01:10 +00004323 ** 7) at least 4 bytes have already been read into the output buffer
danf4ba1092011-10-08 14:57:07 +00004324 **
4325 ** then data can be read directly from the database file into the
4326 ** output buffer, bypassing the page-cache altogether. This speeds
4327 ** up loading large records that span many overflow pages.
4328 */
dan5a500af2014-03-11 20:33:04 +00004329 if( (eOp&0x01)==0 /* (1) */
danf4ba1092011-10-08 14:57:07 +00004330 && offset==0 /* (2) */
dan9bc21b52014-03-20 18:56:35 +00004331 && (bEnd || a==ovflSize) /* (6) */
danf4ba1092011-10-08 14:57:07 +00004332 && pBt->inTransaction==TRANS_READ /* (4) */
4333 && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
4334 && pBt->pPage1->aData[19]==0x01 /* (5) */
dan9501a642014-10-01 12:01:10 +00004335 && &pBuf[-4]>=pBufStart /* (7) */
danf4ba1092011-10-08 14:57:07 +00004336 ){
4337 u8 aSave[4];
4338 u8 *aWrite = &pBuf[-4];
dan9501a642014-10-01 12:01:10 +00004339 assert( aWrite>=pBufStart ); /* hence (7) */
danf4ba1092011-10-08 14:57:07 +00004340 memcpy(aSave, aWrite, 4);
dan27d47fb2011-12-21 17:00:16 +00004341 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
danf4ba1092011-10-08 14:57:07 +00004342 nextPage = get4byte(aWrite);
4343 memcpy(aWrite, aSave, 4);
4344 }else
4345#endif
4346
4347 {
4348 DbPage *pDbPage;
dan11dcd112013-03-15 18:29:18 +00004349 rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
dan5a500af2014-03-11 20:33:04 +00004350 ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
dan11dcd112013-03-15 18:29:18 +00004351 );
danf4ba1092011-10-08 14:57:07 +00004352 if( rc==SQLITE_OK ){
4353 aPayload = sqlite3PagerGetData(pDbPage);
4354 nextPage = get4byte(aPayload);
dan5a500af2014-03-11 20:33:04 +00004355 rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
danf4ba1092011-10-08 14:57:07 +00004356 sqlite3PagerUnref(pDbPage);
4357 offset = 0;
4358 }
4359 }
4360 amt -= a;
4361 pBuf += a;
danielk1977cfe9a692004-06-16 12:00:29 +00004362 }
drh2af926b2001-05-15 00:39:25 +00004363 }
drh2af926b2001-05-15 00:39:25 +00004364 }
danielk1977cfe9a692004-06-16 12:00:29 +00004365
danielk1977da107192007-05-04 08:32:13 +00004366 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00004367 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00004368 }
danielk1977da107192007-05-04 08:32:13 +00004369 return rc;
drh2af926b2001-05-15 00:39:25 +00004370}
4371
drh72f82862001-05-24 21:06:34 +00004372/*
drh3aac2dd2004-04-26 14:10:20 +00004373** Read part of the key associated with cursor pCur. Exactly
peter.d.reid60ec9142014-09-06 16:39:46 +00004374** "amt" bytes will be transferred into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00004375** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00004376**
drh5d1a8722009-07-22 18:07:40 +00004377** The caller must ensure that pCur is pointing to a valid row
4378** in the table.
4379**
drh3aac2dd2004-04-26 14:10:20 +00004380** Return SQLITE_OK on success or an error code if anything goes
4381** wrong. An error is returned if "offset+amt" is larger than
4382** the available payload.
drh72f82862001-05-24 21:06:34 +00004383*/
drha34b6762004-05-07 13:30:42 +00004384int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drh1fee73e2007-08-29 04:00:57 +00004385 assert( cursorHoldsMutex(pCur) );
drh5d1a8722009-07-22 18:07:40 +00004386 assert( pCur->eState==CURSOR_VALID );
4387 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
4388 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
4389 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
drh3aac2dd2004-04-26 14:10:20 +00004390}
4391
4392/*
drh3aac2dd2004-04-26 14:10:20 +00004393** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00004394** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00004395** begins at "offset".
4396**
4397** Return SQLITE_OK on success or an error code if anything goes
4398** wrong. An error is returned if "offset+amt" is larger than
4399** the available payload.
drh72f82862001-05-24 21:06:34 +00004400*/
drh3aac2dd2004-04-26 14:10:20 +00004401int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00004402 int rc;
4403
danielk19773588ceb2008-06-10 17:30:26 +00004404#ifndef SQLITE_OMIT_INCRBLOB
4405 if ( pCur->eState==CURSOR_INVALID ){
4406 return SQLITE_ABORT;
4407 }
4408#endif
4409
drh1fee73e2007-08-29 04:00:57 +00004410 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004411 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004412 if( rc==SQLITE_OK ){
4413 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004414 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
4415 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drhfb192682009-07-11 18:26:28 +00004416 rc = accessPayload(pCur, offset, amt, pBuf, 0);
danielk1977da184232006-01-05 11:34:32 +00004417 }
4418 return rc;
drh2af926b2001-05-15 00:39:25 +00004419}
4420
drh72f82862001-05-24 21:06:34 +00004421/*
drh0e1c19e2004-05-11 00:58:56 +00004422** Return a pointer to payload information from the entry that the
4423** pCur cursor is pointing to. The pointer is to the beginning of
drh2a8d2262013-12-09 20:43:22 +00004424** the key if index btrees (pPage->intKey==0) and is the data for
4425** table btrees (pPage->intKey==1). The number of bytes of available
4426** key/data is written into *pAmt. If *pAmt==0, then the value
4427** returned will not be a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00004428**
4429** This routine is an optimization. It is common for the entire key
4430** and data to fit on the local page and for there to be no overflow
4431** pages. When that is so, this routine can be used to access the
4432** key and data without making a copy. If the key and/or data spills
drh7f751222009-03-17 22:33:00 +00004433** onto overflow pages, then accessPayload() must be used to reassemble
drh0e1c19e2004-05-11 00:58:56 +00004434** the key/data and copy it into a preallocated buffer.
4435**
4436** The pointer returned by this routine looks directly into the cached
4437** page of the database. The data might change or move the next time
4438** any btree routine is called.
4439*/
drh2a8d2262013-12-09 20:43:22 +00004440static const void *fetchPayload(
drh0e1c19e2004-05-11 00:58:56 +00004441 BtCursor *pCur, /* Cursor pointing to entry to read from */
drh2a8d2262013-12-09 20:43:22 +00004442 u32 *pAmt /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00004443){
danielk197771d5d2c2008-09-29 11:49:47 +00004444 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
danielk1977da184232006-01-05 11:34:32 +00004445 assert( pCur->eState==CURSOR_VALID );
drh2a8d2262013-12-09 20:43:22 +00004446 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh1fee73e2007-08-29 04:00:57 +00004447 assert( cursorHoldsMutex(pCur) );
drh2a8d2262013-12-09 20:43:22 +00004448 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh86dd3712014-03-25 11:00:21 +00004449 assert( pCur->info.nSize>0 );
drh2a8d2262013-12-09 20:43:22 +00004450 *pAmt = pCur->info.nLocal;
drhab1cc582014-09-23 21:25:19 +00004451 return (void*)pCur->info.pPayload;
drh0e1c19e2004-05-11 00:58:56 +00004452}
4453
4454
4455/*
drhe51c44f2004-05-30 20:46:09 +00004456** For the entry that cursor pCur is point to, return as
4457** many bytes of the key or data as are available on the local
4458** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00004459**
4460** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00004461** or be destroyed on the next call to any Btree routine,
4462** including calls from other threads against the same cache.
4463** Hence, a mutex on the BtShared should be held prior to calling
4464** this routine.
drh0e1c19e2004-05-11 00:58:56 +00004465**
4466** These routines is used to get quick access to key and data
4467** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00004468*/
drh501932c2013-11-21 21:59:53 +00004469const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
drh2a8d2262013-12-09 20:43:22 +00004470 return fetchPayload(pCur, pAmt);
drh0e1c19e2004-05-11 00:58:56 +00004471}
drh501932c2013-11-21 21:59:53 +00004472const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
drh2a8d2262013-12-09 20:43:22 +00004473 return fetchPayload(pCur, pAmt);
drh0e1c19e2004-05-11 00:58:56 +00004474}
4475
4476
4477/*
drh8178a752003-01-05 21:41:40 +00004478** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00004479** page number of the child page to move to.
danielk1977a299d612009-07-13 11:22:10 +00004480**
4481** This function returns SQLITE_CORRUPT if the page-header flags field of
4482** the new child page does not match the flags field of the parent (i.e.
4483** if an intkey page appears to be the parent of a non-intkey page, or
4484** vice-versa).
drh72f82862001-05-24 21:06:34 +00004485*/
drh3aac2dd2004-04-26 14:10:20 +00004486static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00004487 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004488 int i = pCur->iPage;
drh72f82862001-05-24 21:06:34 +00004489 MemPage *pNewPage;
drhd0679ed2007-08-28 22:24:34 +00004490 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00004491
drh1fee73e2007-08-29 04:00:57 +00004492 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004493 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004494 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
dan11dcd112013-03-15 18:29:18 +00004495 assert( pCur->iPage>=0 );
danielk197771d5d2c2008-09-29 11:49:47 +00004496 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
4497 return SQLITE_CORRUPT_BKPT;
4498 }
drhb00fc3b2013-08-21 23:42:32 +00004499 rc = getAndInitPage(pBt, newPgno, &pNewPage,
drh036dbec2014-03-11 23:40:44 +00004500 (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
drh6019e162001-07-02 17:51:45 +00004501 if( rc ) return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004502 pCur->apPage[i+1] = pNewPage;
4503 pCur->aiIdx[i+1] = 0;
4504 pCur->iPage++;
4505
drh271efa52004-05-30 19:19:05 +00004506 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004507 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
danielk1977bd5969a2009-07-11 17:39:42 +00004508 if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
drh49285702005-09-17 15:20:26 +00004509 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00004510 }
drh72f82862001-05-24 21:06:34 +00004511 return SQLITE_OK;
4512}
4513
drhcbd33492015-03-25 13:06:54 +00004514#if SQLITE_DEBUG
danielk1977bf93c562008-09-29 15:53:25 +00004515/*
4516** Page pParent is an internal (non-leaf) tree page. This function
4517** asserts that page number iChild is the left-child if the iIdx'th
4518** cell in page pParent. Or, if iIdx is equal to the total number of
4519** cells in pParent, that page number iChild is the right-child of
4520** the page.
4521*/
4522static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
drhcbd33492015-03-25 13:06:54 +00004523 if( CORRUPT_DB ) return; /* The conditions tested below might not be true
4524 ** in a corrupt database */
danielk1977bf93c562008-09-29 15:53:25 +00004525 assert( iIdx<=pParent->nCell );
4526 if( iIdx==pParent->nCell ){
4527 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
4528 }else{
4529 assert( get4byte(findCell(pParent, iIdx))==iChild );
4530 }
4531}
4532#else
4533# define assertParentIndex(x,y,z)
4534#endif
4535
drh72f82862001-05-24 21:06:34 +00004536/*
drh5e2f8b92001-05-28 00:41:15 +00004537** Move the cursor up to the parent page.
4538**
4539** pCur->idx is set to the cell index that contains the pointer
4540** to the page we are coming from. If we are coming from the
4541** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00004542** the largest cell index.
drh72f82862001-05-24 21:06:34 +00004543*/
danielk197730548662009-07-09 05:07:37 +00004544static void moveToParent(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00004545 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004546 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004547 assert( pCur->iPage>0 );
4548 assert( pCur->apPage[pCur->iPage] );
danielk1977bf93c562008-09-29 15:53:25 +00004549 assertParentIndex(
4550 pCur->apPage[pCur->iPage-1],
4551 pCur->aiIdx[pCur->iPage-1],
4552 pCur->apPage[pCur->iPage]->pgno
4553 );
dan6c2688c2012-01-12 15:05:03 +00004554 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
danbb246c42012-01-12 14:25:55 +00004555
danielk197771d5d2c2008-09-29 11:49:47 +00004556 releasePage(pCur->apPage[pCur->iPage]);
4557 pCur->iPage--;
drh271efa52004-05-30 19:19:05 +00004558 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004559 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drh72f82862001-05-24 21:06:34 +00004560}
4561
4562/*
danielk19778f880a82009-07-13 09:41:45 +00004563** Move the cursor to point to the root page of its b-tree structure.
4564**
4565** If the table has a virtual root page, then the cursor is moved to point
4566** to the virtual root page instead of the actual root page. A table has a
4567** virtual root page when the actual root page contains no cells and a
4568** single child page. This can only happen with the table rooted at page 1.
4569**
4570** If the b-tree structure is empty, the cursor state is set to
4571** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
4572** cell located on the root (or virtual root) page and the cursor state
4573** is set to CURSOR_VALID.
4574**
4575** If this function returns successfully, it may be assumed that the
4576** page-header flags indicate that the [virtual] root-page is the expected
4577** kind of b-tree page (i.e. if when opening the cursor the caller did not
4578** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
4579** indicating a table b-tree, or if the caller did specify a KeyInfo
4580** structure the flags byte is set to 0x02 or 0x0A, indicating an index
4581** b-tree).
drh72f82862001-05-24 21:06:34 +00004582*/
drh5e2f8b92001-05-28 00:41:15 +00004583static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00004584 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00004585 int rc = SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00004586
drh1fee73e2007-08-29 04:00:57 +00004587 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +00004588 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
4589 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
4590 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
4591 if( pCur->eState>=CURSOR_REQUIRESEEK ){
4592 if( pCur->eState==CURSOR_FAULT ){
drh4c301aa2009-07-15 17:25:45 +00004593 assert( pCur->skipNext!=SQLITE_OK );
4594 return pCur->skipNext;
drhfb982642007-08-30 01:19:59 +00004595 }
danielk1977be51a652008-10-08 17:58:48 +00004596 sqlite3BtreeClearCursor(pCur);
drhbf700f32007-03-31 02:36:44 +00004597 }
danielk197771d5d2c2008-09-29 11:49:47 +00004598
4599 if( pCur->iPage>=0 ){
drh4e8fe3f2013-12-06 23:25:27 +00004600 while( pCur->iPage ) releasePage(pCur->apPage[pCur->iPage--]);
dana205a482011-08-27 18:48:57 +00004601 }else if( pCur->pgnoRoot==0 ){
4602 pCur->eState = CURSOR_INVALID;
4603 return SQLITE_OK;
drh777e4c42006-01-13 04:31:58 +00004604 }else{
drh4e8fe3f2013-12-06 23:25:27 +00004605 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
drh036dbec2014-03-11 23:40:44 +00004606 (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
drh4c301aa2009-07-15 17:25:45 +00004607 if( rc!=SQLITE_OK ){
drh777e4c42006-01-13 04:31:58 +00004608 pCur->eState = CURSOR_INVALID;
4609 return rc;
4610 }
danielk1977172114a2009-07-07 15:47:12 +00004611 pCur->iPage = 0;
drhc39e0002004-05-07 23:50:57 +00004612 }
danielk197771d5d2c2008-09-29 11:49:47 +00004613 pRoot = pCur->apPage[0];
4614 assert( pRoot->pgno==pCur->pgnoRoot );
dan7df42ab2014-01-20 18:25:44 +00004615
4616 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
4617 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
4618 ** NULL, the caller expects a table b-tree. If this is not the case,
4619 ** return an SQLITE_CORRUPT error.
4620 **
4621 ** Earlier versions of SQLite assumed that this test could not fail
4622 ** if the root page was already loaded when this function was called (i.e.
4623 ** if pCur->iPage>=0). But this is not so if the database is corrupted
4624 ** in such a way that page pRoot is linked into a second b-tree table
4625 ** (or the freelist). */
4626 assert( pRoot->intKey==1 || pRoot->intKey==0 );
4627 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
4628 return SQLITE_CORRUPT_BKPT;
4629 }
danielk19778f880a82009-07-13 09:41:45 +00004630
danielk197771d5d2c2008-09-29 11:49:47 +00004631 pCur->aiIdx[0] = 0;
drh271efa52004-05-30 19:19:05 +00004632 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004633 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
danielk197771d5d2c2008-09-29 11:49:47 +00004634
drh4e8fe3f2013-12-06 23:25:27 +00004635 if( pRoot->nCell>0 ){
4636 pCur->eState = CURSOR_VALID;
4637 }else if( !pRoot->leaf ){
drh8856d6a2004-04-29 14:42:46 +00004638 Pgno subpage;
drhc85240d2009-06-04 16:14:33 +00004639 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
drh43605152004-05-29 21:46:49 +00004640 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
danielk1977da184232006-01-05 11:34:32 +00004641 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00004642 rc = moveToChild(pCur, subpage);
danielk197771d5d2c2008-09-29 11:49:47 +00004643 }else{
drh4e8fe3f2013-12-06 23:25:27 +00004644 pCur->eState = CURSOR_INVALID;
drh8856d6a2004-04-29 14:42:46 +00004645 }
4646 return rc;
drh72f82862001-05-24 21:06:34 +00004647}
drh2af926b2001-05-15 00:39:25 +00004648
drh5e2f8b92001-05-28 00:41:15 +00004649/*
4650** Move the cursor down to the left-most leaf entry beneath the
4651** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00004652**
4653** The left-most leaf is the one with the smallest key - the first
4654** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00004655*/
4656static int moveToLeftmost(BtCursor *pCur){
4657 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00004658 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00004659 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00004660
drh1fee73e2007-08-29 04:00:57 +00004661 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004662 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004663 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
4664 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
4665 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
drh8178a752003-01-05 21:41:40 +00004666 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00004667 }
drhd677b3d2007-08-20 22:48:41 +00004668 return rc;
drh5e2f8b92001-05-28 00:41:15 +00004669}
4670
drh2dcc9aa2002-12-04 13:40:25 +00004671/*
4672** Move the cursor down to the right-most leaf entry beneath the
4673** page to which it is currently pointing. Notice the difference
4674** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
4675** finds the left-most entry beneath the *entry* whereas moveToRightmost()
4676** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00004677**
4678** The right-most entry is the one with the largest key - the last
4679** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00004680*/
4681static int moveToRightmost(BtCursor *pCur){
4682 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00004683 int rc = SQLITE_OK;
drh1bd10f82008-12-10 21:19:56 +00004684 MemPage *pPage = 0;
drh2dcc9aa2002-12-04 13:40:25 +00004685
drh1fee73e2007-08-29 04:00:57 +00004686 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004687 assert( pCur->eState==CURSOR_VALID );
drhee6438d2014-09-01 13:29:32 +00004688 while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
drh43605152004-05-29 21:46:49 +00004689 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
danielk197771d5d2c2008-09-29 11:49:47 +00004690 pCur->aiIdx[pCur->iPage] = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00004691 rc = moveToChild(pCur, pgno);
drhee6438d2014-09-01 13:29:32 +00004692 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00004693 }
drhee6438d2014-09-01 13:29:32 +00004694 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
4695 assert( pCur->info.nSize==0 );
4696 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
4697 return SQLITE_OK;
drh2dcc9aa2002-12-04 13:40:25 +00004698}
4699
drh5e00f6c2001-09-13 13:46:56 +00004700/* Move the cursor to the first entry in the table. Return SQLITE_OK
4701** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00004702** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00004703*/
drh3aac2dd2004-04-26 14:10:20 +00004704int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00004705 int rc;
drhd677b3d2007-08-20 22:48:41 +00004706
drh1fee73e2007-08-29 04:00:57 +00004707 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004708 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00004709 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004710 if( rc==SQLITE_OK ){
4711 if( pCur->eState==CURSOR_INVALID ){
dana205a482011-08-27 18:48:57 +00004712 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00004713 *pRes = 1;
drhd677b3d2007-08-20 22:48:41 +00004714 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004715 assert( pCur->apPage[pCur->iPage]->nCell>0 );
drhd677b3d2007-08-20 22:48:41 +00004716 *pRes = 0;
4717 rc = moveToLeftmost(pCur);
4718 }
drh5e00f6c2001-09-13 13:46:56 +00004719 }
drh5e00f6c2001-09-13 13:46:56 +00004720 return rc;
4721}
drh5e2f8b92001-05-28 00:41:15 +00004722
drh9562b552002-02-19 15:00:07 +00004723/* Move the cursor to the last entry in the table. Return SQLITE_OK
4724** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00004725** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00004726*/
drh3aac2dd2004-04-26 14:10:20 +00004727int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00004728 int rc;
drhd677b3d2007-08-20 22:48:41 +00004729
drh1fee73e2007-08-29 04:00:57 +00004730 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004731 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19773f632d52009-05-02 10:03:09 +00004732
4733 /* If the cursor already points to the last entry, this is a no-op. */
drh036dbec2014-03-11 23:40:44 +00004734 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
danielk19773f632d52009-05-02 10:03:09 +00004735#ifdef SQLITE_DEBUG
4736 /* This block serves to assert() that the cursor really does point
4737 ** to the last entry in the b-tree. */
4738 int ii;
4739 for(ii=0; ii<pCur->iPage; ii++){
4740 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
4741 }
4742 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
4743 assert( pCur->apPage[pCur->iPage]->leaf );
4744#endif
4745 return SQLITE_OK;
4746 }
4747
drh9562b552002-02-19 15:00:07 +00004748 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004749 if( rc==SQLITE_OK ){
4750 if( CURSOR_INVALID==pCur->eState ){
dana205a482011-08-27 18:48:57 +00004751 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00004752 *pRes = 1;
4753 }else{
4754 assert( pCur->eState==CURSOR_VALID );
4755 *pRes = 0;
4756 rc = moveToRightmost(pCur);
drh036dbec2014-03-11 23:40:44 +00004757 if( rc==SQLITE_OK ){
4758 pCur->curFlags |= BTCF_AtLast;
4759 }else{
4760 pCur->curFlags &= ~BTCF_AtLast;
4761 }
4762
drhd677b3d2007-08-20 22:48:41 +00004763 }
drh9562b552002-02-19 15:00:07 +00004764 }
drh9562b552002-02-19 15:00:07 +00004765 return rc;
4766}
4767
drhe14006d2008-03-25 17:23:32 +00004768/* Move the cursor so that it points to an entry near the key
drhe63d9992008-08-13 19:11:48 +00004769** specified by pIdxKey or intKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00004770**
drhe63d9992008-08-13 19:11:48 +00004771** For INTKEY tables, the intKey parameter is used. pIdxKey
4772** must be NULL. For index tables, pIdxKey is used and intKey
4773** is ignored.
drh3aac2dd2004-04-26 14:10:20 +00004774**
drh5e2f8b92001-05-28 00:41:15 +00004775** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00004776** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00004777** were present. The cursor might point to an entry that comes
4778** before or after the key.
4779**
drh64022502009-01-09 14:11:04 +00004780** An integer is written into *pRes which is the result of
4781** comparing the key with the entry to which the cursor is
4782** pointing. The meaning of the integer written into
4783** *pRes is as follows:
drhbd03cae2001-06-02 02:40:57 +00004784**
4785** *pRes<0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004786** is smaller than intKey/pIdxKey or if the table is empty
drh1a844c32002-12-04 22:29:28 +00004787** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00004788**
4789** *pRes==0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004790** exactly matches intKey/pIdxKey.
drhbd03cae2001-06-02 02:40:57 +00004791**
4792** *pRes>0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004793** is larger than intKey/pIdxKey.
drhd677b3d2007-08-20 22:48:41 +00004794**
drha059ad02001-04-17 20:09:11 +00004795*/
drhe63d9992008-08-13 19:11:48 +00004796int sqlite3BtreeMovetoUnpacked(
4797 BtCursor *pCur, /* The cursor to be moved */
4798 UnpackedRecord *pIdxKey, /* Unpacked index key */
4799 i64 intKey, /* The table key */
4800 int biasRight, /* If true, bias the search to the high end */
4801 int *pRes /* Write search results here */
drhe4d90812007-03-29 05:51:49 +00004802){
drh72f82862001-05-24 21:06:34 +00004803 int rc;
dan3b9330f2014-02-27 20:44:18 +00004804 RecordCompare xRecordCompare;
drhd677b3d2007-08-20 22:48:41 +00004805
drh1fee73e2007-08-29 04:00:57 +00004806 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004807 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19775cb09632009-07-09 11:36:01 +00004808 assert( pRes );
danielk19773fd7cf52009-07-13 07:30:52 +00004809 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
drha2c20e42008-03-29 16:01:04 +00004810
4811 /* If the cursor is already positioned at the point we are trying
4812 ** to move to, then just return without doing any work */
drh036dbec2014-03-11 23:40:44 +00004813 if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
danielk197771d5d2c2008-09-29 11:49:47 +00004814 && pCur->apPage[0]->intKey
4815 ){
drhe63d9992008-08-13 19:11:48 +00004816 if( pCur->info.nKey==intKey ){
drha2c20e42008-03-29 16:01:04 +00004817 *pRes = 0;
4818 return SQLITE_OK;
4819 }
drh036dbec2014-03-11 23:40:44 +00004820 if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
drha2c20e42008-03-29 16:01:04 +00004821 *pRes = -1;
4822 return SQLITE_OK;
4823 }
4824 }
4825
dan1fed5da2014-02-25 21:01:25 +00004826 if( pIdxKey ){
4827 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
dan38fdead2014-04-01 10:19:02 +00004828 pIdxKey->errCode = 0;
dan3b9330f2014-02-27 20:44:18 +00004829 assert( pIdxKey->default_rc==1
4830 || pIdxKey->default_rc==0
4831 || pIdxKey->default_rc==-1
4832 );
drh13a747e2014-03-03 21:46:55 +00004833 }else{
drhb6e8fd12014-03-06 01:56:33 +00004834 xRecordCompare = 0; /* All keys are integers */
dan1fed5da2014-02-25 21:01:25 +00004835 }
4836
drh5e2f8b92001-05-28 00:41:15 +00004837 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004838 if( rc ){
4839 return rc;
4840 }
dana205a482011-08-27 18:48:57 +00004841 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
4842 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
4843 assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
danielk1977da184232006-01-05 11:34:32 +00004844 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00004845 *pRes = -1;
dana205a482011-08-27 18:48:57 +00004846 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
drhc39e0002004-05-07 23:50:57 +00004847 return SQLITE_OK;
4848 }
danielk197771d5d2c2008-09-29 11:49:47 +00004849 assert( pCur->apPage[0]->intKey || pIdxKey );
drh14684382006-11-30 13:05:29 +00004850 for(;;){
drhec3e6b12013-11-25 02:38:55 +00004851 int lwr, upr, idx, c;
drh72f82862001-05-24 21:06:34 +00004852 Pgno chldPg;
danielk197771d5d2c2008-09-29 11:49:47 +00004853 MemPage *pPage = pCur->apPage[pCur->iPage];
drhec3e6b12013-11-25 02:38:55 +00004854 u8 *pCell; /* Pointer to current cell in pPage */
danielk1977171fff32009-07-11 05:06:51 +00004855
4856 /* pPage->nCell must be greater than zero. If this is the root-page
4857 ** the cursor would have been INVALID above and this for(;;) loop
4858 ** not run. If this is not the root-page, then the moveToChild() routine
danielk19773fd7cf52009-07-13 07:30:52 +00004859 ** would have already detected db corruption. Similarly, pPage must
4860 ** be the right kind (index or table) of b-tree page. Otherwise
4861 ** a moveToChild() or moveToRoot() call would have detected corruption. */
danielk1977171fff32009-07-11 05:06:51 +00004862 assert( pPage->nCell>0 );
danielk19773fd7cf52009-07-13 07:30:52 +00004863 assert( pPage->intKey==(pIdxKey==0) );
drh72f82862001-05-24 21:06:34 +00004864 lwr = 0;
4865 upr = pPage->nCell-1;
drhebf10b12013-11-25 17:38:26 +00004866 assert( biasRight==0 || biasRight==1 );
4867 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
drhd793f442013-11-25 14:10:15 +00004868 pCur->aiIdx[pCur->iPage] = (u16)idx;
dana4660bd2014-03-04 16:05:25 +00004869 if( xRecordCompare==0 ){
drhec3e6b12013-11-25 02:38:55 +00004870 for(;;){
danielk197711c327a2009-05-04 19:01:26 +00004871 i64 nCellKey;
drhec3e6b12013-11-25 02:38:55 +00004872 pCell = findCell(pPage, idx) + pPage->childPtrSize;
drh3e28ff52014-09-24 00:59:08 +00004873 if( pPage->intKeyLeaf ){
drh9b2fc612013-11-25 20:14:13 +00004874 while( 0x80 <= *(pCell++) ){
4875 if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
4876 }
drhd172f862006-01-12 15:01:15 +00004877 }
drha2c20e42008-03-29 16:01:04 +00004878 getVarint(pCell, (u64*)&nCellKey);
drhbb933ef2013-11-25 15:01:38 +00004879 if( nCellKey<intKey ){
4880 lwr = idx+1;
4881 if( lwr>upr ){ c = -1; break; }
4882 }else if( nCellKey>intKey ){
4883 upr = idx-1;
4884 if( lwr>upr ){ c = +1; break; }
4885 }else{
4886 assert( nCellKey==intKey );
drh036dbec2014-03-11 23:40:44 +00004887 pCur->curFlags |= BTCF_ValidNKey;
drhec3e6b12013-11-25 02:38:55 +00004888 pCur->info.nKey = nCellKey;
drhd793f442013-11-25 14:10:15 +00004889 pCur->aiIdx[pCur->iPage] = (u16)idx;
drhec3e6b12013-11-25 02:38:55 +00004890 if( !pPage->leaf ){
4891 lwr = idx;
drhebf10b12013-11-25 17:38:26 +00004892 goto moveto_next_layer;
drhec3e6b12013-11-25 02:38:55 +00004893 }else{
4894 *pRes = 0;
4895 rc = SQLITE_OK;
4896 goto moveto_finish;
4897 }
drhd793f442013-11-25 14:10:15 +00004898 }
drhebf10b12013-11-25 17:38:26 +00004899 assert( lwr+upr>=0 );
4900 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
drhec3e6b12013-11-25 02:38:55 +00004901 }
4902 }else{
4903 for(;;){
4904 int nCell;
drhec3e6b12013-11-25 02:38:55 +00004905 pCell = findCell(pPage, idx) + pPage->childPtrSize;
4906
drhb2eced52010-08-12 02:41:12 +00004907 /* The maximum supported page-size is 65536 bytes. This means that
danielk197711c327a2009-05-04 19:01:26 +00004908 ** the maximum number of record bytes stored on an index B-Tree
drhb2eced52010-08-12 02:41:12 +00004909 ** page is less than 16384 bytes and may be stored as a 2-byte
danielk197711c327a2009-05-04 19:01:26 +00004910 ** varint. This information is used to attempt to avoid parsing
4911 ** the entire cell by checking for the cases where the record is
4912 ** stored entirely within the b-tree page by inspecting the first
4913 ** 2 bytes of the cell.
4914 */
drhec3e6b12013-11-25 02:38:55 +00004915 nCell = pCell[0];
drh72b8ef62013-12-06 22:44:51 +00004916 if( nCell<=pPage->max1bytePayload ){
danielk197711c327a2009-05-04 19:01:26 +00004917 /* This branch runs if the record-size field of the cell is a
4918 ** single byte varint and the record fits entirely on the main
4919 ** b-tree page. */
drh3def2352011-11-11 00:27:15 +00004920 testcase( pCell+nCell+1==pPage->aDataEnd );
drh75179de2014-09-16 14:37:35 +00004921 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
danielk197711c327a2009-05-04 19:01:26 +00004922 }else if( !(pCell[1] & 0x80)
4923 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
4924 ){
4925 /* The record-size field is a 2 byte varint and the record
4926 ** fits entirely on the main b-tree page. */
drh3def2352011-11-11 00:27:15 +00004927 testcase( pCell+nCell+2==pPage->aDataEnd );
drh75179de2014-09-16 14:37:35 +00004928 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
drhe51c44f2004-05-30 20:46:09 +00004929 }else{
danielk197711c327a2009-05-04 19:01:26 +00004930 /* The record flows over onto one or more overflow pages. In
4931 ** this case the whole cell needs to be parsed, a buffer allocated
4932 ** and accessPayload() used to retrieve the record into the
4933 ** buffer before VdbeRecordCompare() can be called. */
4934 void *pCellKey;
4935 u8 * const pCellBody = pCell - pPage->childPtrSize;
danielk197730548662009-07-09 05:07:37 +00004936 btreeParseCellPtr(pPage, pCellBody, &pCur->info);
shane60a4b532009-05-06 18:57:09 +00004937 nCell = (int)pCur->info.nKey;
danielk197711c327a2009-05-04 19:01:26 +00004938 pCellKey = sqlite3Malloc( nCell );
danielk19776507ecb2008-03-25 09:56:44 +00004939 if( pCellKey==0 ){
4940 rc = SQLITE_NOMEM;
4941 goto moveto_finish;
4942 }
drhd793f442013-11-25 14:10:15 +00004943 pCur->aiIdx[pCur->iPage] = (u16)idx;
dan5a500af2014-03-11 20:33:04 +00004944 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
drhec9b31f2009-08-25 13:53:49 +00004945 if( rc ){
4946 sqlite3_free(pCellKey);
4947 goto moveto_finish;
4948 }
drh75179de2014-09-16 14:37:35 +00004949 c = xRecordCompare(nCell, pCellKey, pIdxKey);
drhfacf0302008-06-17 15:12:00 +00004950 sqlite3_free(pCellKey);
drhe51c44f2004-05-30 20:46:09 +00004951 }
dan38fdead2014-04-01 10:19:02 +00004952 assert(
4953 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
dana7bf23c2014-05-02 17:12:41 +00004954 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
dan38fdead2014-04-01 10:19:02 +00004955 );
drhbb933ef2013-11-25 15:01:38 +00004956 if( c<0 ){
4957 lwr = idx+1;
4958 }else if( c>0 ){
4959 upr = idx-1;
4960 }else{
4961 assert( c==0 );
drh64022502009-01-09 14:11:04 +00004962 *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00004963 rc = SQLITE_OK;
drhd793f442013-11-25 14:10:15 +00004964 pCur->aiIdx[pCur->iPage] = (u16)idx;
dan38fdead2014-04-01 10:19:02 +00004965 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
drh1e968a02008-03-25 00:22:21 +00004966 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00004967 }
drhebf10b12013-11-25 17:38:26 +00004968 if( lwr>upr ) break;
4969 assert( lwr+upr>=0 );
4970 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
drh72f82862001-05-24 21:06:34 +00004971 }
drh72f82862001-05-24 21:06:34 +00004972 }
drhb07028f2011-10-14 21:49:18 +00004973 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
danielk197771d5d2c2008-09-29 11:49:47 +00004974 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00004975 if( pPage->leaf ){
drhec3e6b12013-11-25 02:38:55 +00004976 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drhbb933ef2013-11-25 15:01:38 +00004977 pCur->aiIdx[pCur->iPage] = (u16)idx;
drhec3e6b12013-11-25 02:38:55 +00004978 *pRes = c;
4979 rc = SQLITE_OK;
4980 goto moveto_finish;
drhebf10b12013-11-25 17:38:26 +00004981 }
4982moveto_next_layer:
4983 if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00004984 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00004985 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00004986 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00004987 }
drhf49661a2008-12-10 16:45:50 +00004988 pCur->aiIdx[pCur->iPage] = (u16)lwr;
drh8178a752003-01-05 21:41:40 +00004989 rc = moveToChild(pCur, chldPg);
drhec3e6b12013-11-25 02:38:55 +00004990 if( rc ) break;
drh72f82862001-05-24 21:06:34 +00004991 }
drh1e968a02008-03-25 00:22:21 +00004992moveto_finish:
drhd2022b02013-11-25 16:23:52 +00004993 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004994 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drhe63d9992008-08-13 19:11:48 +00004995 return rc;
4996}
4997
drhd677b3d2007-08-20 22:48:41 +00004998
drh72f82862001-05-24 21:06:34 +00004999/*
drhc39e0002004-05-07 23:50:57 +00005000** Return TRUE if the cursor is not pointing at an entry of the table.
5001**
5002** TRUE will be returned after a call to sqlite3BtreeNext() moves
5003** past the last entry in the table or sqlite3BtreePrev() moves past
5004** the first entry. TRUE is also returned if the table is empty.
5005*/
5006int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00005007 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
5008 ** have been deleted? This API will need to change to return an error code
5009 ** as well as the boolean result value.
5010 */
5011 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00005012}
5013
5014/*
drhbd03cae2001-06-02 02:40:57 +00005015** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00005016** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00005017** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00005018** this routine was called, then set *pRes=1.
drhe39a7322014-02-03 14:04:11 +00005019**
drhee6438d2014-09-01 13:29:32 +00005020** The main entry point is sqlite3BtreeNext(). That routine is optimized
5021** for the common case of merely incrementing the cell counter BtCursor.aiIdx
5022** to the next cell on the current page. The (slower) btreeNext() helper
5023** routine is called when it is necessary to move to a different page or
5024** to restore the cursor.
5025**
drhe39a7322014-02-03 14:04:11 +00005026** The calling function will set *pRes to 0 or 1. The initial *pRes value
5027** will be 1 if the cursor being stepped corresponds to an SQL index and
5028** if this routine could have been skipped if that SQL index had been
5029** a unique index. Otherwise the caller will have set *pRes to zero.
5030** Zero is the common case. The btree implementation is free to use the
5031** initial *pRes value as a hint to improve performance, but the current
5032** SQLite btree implementation does not. (Note that the comdb2 btree
5033** implementation does use this hint, however.)
drh72f82862001-05-24 21:06:34 +00005034*/
drhee6438d2014-09-01 13:29:32 +00005035static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00005036 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00005037 int idx;
danielk197797a227c2006-01-20 16:32:04 +00005038 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00005039
drh1fee73e2007-08-29 04:00:57 +00005040 assert( cursorHoldsMutex(pCur) );
drh9b47ee32013-08-20 03:13:51 +00005041 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
drhee6438d2014-09-01 13:29:32 +00005042 assert( *pRes==0 );
drhf66f26a2013-08-19 20:04:10 +00005043 if( pCur->eState!=CURSOR_VALID ){
drhee6438d2014-09-01 13:29:32 +00005044 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
drhf66f26a2013-08-19 20:04:10 +00005045 rc = restoreCursorPosition(pCur);
5046 if( rc!=SQLITE_OK ){
5047 return rc;
5048 }
5049 if( CURSOR_INVALID==pCur->eState ){
5050 *pRes = 1;
5051 return SQLITE_OK;
5052 }
drh9b47ee32013-08-20 03:13:51 +00005053 if( pCur->skipNext ){
5054 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5055 pCur->eState = CURSOR_VALID;
5056 if( pCur->skipNext>0 ){
5057 pCur->skipNext = 0;
drh9b47ee32013-08-20 03:13:51 +00005058 return SQLITE_OK;
5059 }
drhf66f26a2013-08-19 20:04:10 +00005060 pCur->skipNext = 0;
drhf66f26a2013-08-19 20:04:10 +00005061 }
danielk1977da184232006-01-05 11:34:32 +00005062 }
danielk1977da184232006-01-05 11:34:32 +00005063
danielk197771d5d2c2008-09-29 11:49:47 +00005064 pPage = pCur->apPage[pCur->iPage];
5065 idx = ++pCur->aiIdx[pCur->iPage];
5066 assert( pPage->isInit );
danbb246c42012-01-12 14:25:55 +00005067
5068 /* If the database file is corrupt, it is possible for the value of idx
5069 ** to be invalid here. This can only occur if a second cursor modifies
5070 ** the page while cursor pCur is holding a reference to it. Which can
5071 ** only happen if the database is corrupt in such a way as to link the
5072 ** page into more than one b-tree structure. */
5073 testcase( idx>pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00005074
danielk197771d5d2c2008-09-29 11:49:47 +00005075 if( idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00005076 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005077 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drhee6438d2014-09-01 13:29:32 +00005078 if( rc ) return rc;
5079 return moveToLeftmost(pCur);
drh72f82862001-05-24 21:06:34 +00005080 }
drh5e2f8b92001-05-28 00:41:15 +00005081 do{
danielk197771d5d2c2008-09-29 11:49:47 +00005082 if( pCur->iPage==0 ){
drh8c1238a2003-01-02 14:43:55 +00005083 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00005084 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00005085 return SQLITE_OK;
5086 }
danielk197730548662009-07-09 05:07:37 +00005087 moveToParent(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00005088 pPage = pCur->apPage[pCur->iPage];
5089 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
drh44845222008-07-17 18:39:57 +00005090 if( pPage->intKey ){
drhee6438d2014-09-01 13:29:32 +00005091 return sqlite3BtreeNext(pCur, pRes);
drh8b18dd42004-05-12 19:18:15 +00005092 }else{
drhee6438d2014-09-01 13:29:32 +00005093 return SQLITE_OK;
drh8b18dd42004-05-12 19:18:15 +00005094 }
drh8178a752003-01-05 21:41:40 +00005095 }
drh3aac2dd2004-04-26 14:10:20 +00005096 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00005097 return SQLITE_OK;
drhee6438d2014-09-01 13:29:32 +00005098 }else{
5099 return moveToLeftmost(pCur);
drh72f82862001-05-24 21:06:34 +00005100 }
drh72f82862001-05-24 21:06:34 +00005101}
drhee6438d2014-09-01 13:29:32 +00005102int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
5103 MemPage *pPage;
5104 assert( cursorHoldsMutex(pCur) );
5105 assert( pRes!=0 );
5106 assert( *pRes==0 || *pRes==1 );
5107 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5108 pCur->info.nSize = 0;
5109 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5110 *pRes = 0;
5111 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
5112 pPage = pCur->apPage[pCur->iPage];
5113 if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
5114 pCur->aiIdx[pCur->iPage]--;
5115 return btreeNext(pCur, pRes);
5116 }
5117 if( pPage->leaf ){
5118 return SQLITE_OK;
5119 }else{
5120 return moveToLeftmost(pCur);
5121 }
5122}
drh72f82862001-05-24 21:06:34 +00005123
drh3b7511c2001-05-26 13:15:44 +00005124/*
drh2dcc9aa2002-12-04 13:40:25 +00005125** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00005126** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00005127** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00005128** this routine was called, then set *pRes=1.
drhe39a7322014-02-03 14:04:11 +00005129**
drhee6438d2014-09-01 13:29:32 +00005130** The main entry point is sqlite3BtreePrevious(). That routine is optimized
5131** for the common case of merely decrementing the cell counter BtCursor.aiIdx
drh3f387402014-09-24 01:23:00 +00005132** to the previous cell on the current page. The (slower) btreePrevious()
5133** helper routine is called when it is necessary to move to a different page
5134** or to restore the cursor.
drhee6438d2014-09-01 13:29:32 +00005135**
drhe39a7322014-02-03 14:04:11 +00005136** The calling function will set *pRes to 0 or 1. The initial *pRes value
5137** will be 1 if the cursor being stepped corresponds to an SQL index and
5138** if this routine could have been skipped if that SQL index had been
5139** a unique index. Otherwise the caller will have set *pRes to zero.
5140** Zero is the common case. The btree implementation is free to use the
5141** initial *pRes value as a hint to improve performance, but the current
5142** SQLite btree implementation does not. (Note that the comdb2 btree
5143** implementation does use this hint, however.)
drh2dcc9aa2002-12-04 13:40:25 +00005144*/
drhee6438d2014-09-01 13:29:32 +00005145static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00005146 int rc;
drh8178a752003-01-05 21:41:40 +00005147 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00005148
drh1fee73e2007-08-29 04:00:57 +00005149 assert( cursorHoldsMutex(pCur) );
drh9b47ee32013-08-20 03:13:51 +00005150 assert( pRes!=0 );
drhee6438d2014-09-01 13:29:32 +00005151 assert( *pRes==0 );
drh9b47ee32013-08-20 03:13:51 +00005152 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
drhee6438d2014-09-01 13:29:32 +00005153 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
5154 assert( pCur->info.nSize==0 );
drhf66f26a2013-08-19 20:04:10 +00005155 if( pCur->eState!=CURSOR_VALID ){
drh7682a472014-09-29 15:00:28 +00005156 rc = restoreCursorPosition(pCur);
drhee6438d2014-09-01 13:29:32 +00005157 if( rc!=SQLITE_OK ){
5158 return rc;
drhf66f26a2013-08-19 20:04:10 +00005159 }
5160 if( CURSOR_INVALID==pCur->eState ){
5161 *pRes = 1;
5162 return SQLITE_OK;
5163 }
drh9b47ee32013-08-20 03:13:51 +00005164 if( pCur->skipNext ){
5165 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5166 pCur->eState = CURSOR_VALID;
5167 if( pCur->skipNext<0 ){
5168 pCur->skipNext = 0;
drh9b47ee32013-08-20 03:13:51 +00005169 return SQLITE_OK;
5170 }
drhf66f26a2013-08-19 20:04:10 +00005171 pCur->skipNext = 0;
drhf66f26a2013-08-19 20:04:10 +00005172 }
danielk1977da184232006-01-05 11:34:32 +00005173 }
danielk1977da184232006-01-05 11:34:32 +00005174
danielk197771d5d2c2008-09-29 11:49:47 +00005175 pPage = pCur->apPage[pCur->iPage];
5176 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00005177 if( !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00005178 int idx = pCur->aiIdx[pCur->iPage];
5179 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
drhee6438d2014-09-01 13:29:32 +00005180 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00005181 rc = moveToRightmost(pCur);
5182 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00005183 while( pCur->aiIdx[pCur->iPage]==0 ){
5184 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00005185 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00005186 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00005187 return SQLITE_OK;
5188 }
danielk197730548662009-07-09 05:07:37 +00005189 moveToParent(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00005190 }
drhee6438d2014-09-01 13:29:32 +00005191 assert( pCur->info.nSize==0 );
5192 assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00005193
5194 pCur->aiIdx[pCur->iPage]--;
5195 pPage = pCur->apPage[pCur->iPage];
drh44845222008-07-17 18:39:57 +00005196 if( pPage->intKey && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00005197 rc = sqlite3BtreePrevious(pCur, pRes);
5198 }else{
5199 rc = SQLITE_OK;
5200 }
drh2dcc9aa2002-12-04 13:40:25 +00005201 }
drh2dcc9aa2002-12-04 13:40:25 +00005202 return rc;
5203}
drhee6438d2014-09-01 13:29:32 +00005204int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
5205 assert( cursorHoldsMutex(pCur) );
5206 assert( pRes!=0 );
5207 assert( *pRes==0 || *pRes==1 );
5208 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5209 *pRes = 0;
5210 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
5211 pCur->info.nSize = 0;
5212 if( pCur->eState!=CURSOR_VALID
5213 || pCur->aiIdx[pCur->iPage]==0
5214 || pCur->apPage[pCur->iPage]->leaf==0
5215 ){
5216 return btreePrevious(pCur, pRes);
5217 }
5218 pCur->aiIdx[pCur->iPage]--;
5219 return SQLITE_OK;
5220}
drh2dcc9aa2002-12-04 13:40:25 +00005221
5222/*
drh3b7511c2001-05-26 13:15:44 +00005223** Allocate a new page from the database file.
5224**
danielk19773b8a05f2007-03-19 17:44:26 +00005225** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00005226** has already been called on the new page.) The new page has also
5227** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00005228** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00005229**
5230** SQLITE_OK is returned on success. Any other return value indicates
5231** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00005232** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00005233**
drh82e647d2013-03-02 03:25:55 +00005234** If the "nearby" parameter is not 0, then an effort is made to
drh199e3cf2002-07-18 11:01:47 +00005235** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00005236** attempt to keep related pages close to each other in the database file,
5237** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00005238**
drh82e647d2013-03-02 03:25:55 +00005239** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
5240** anywhere on the free-list, then it is guaranteed to be returned. If
5241** eMode is BTALLOC_LT then the page returned will be less than or equal
5242** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
5243** are no restrictions on which page is returned.
drh3b7511c2001-05-26 13:15:44 +00005244*/
drh4f0c5872007-03-26 22:05:01 +00005245static int allocateBtreePage(
drh82e647d2013-03-02 03:25:55 +00005246 BtShared *pBt, /* The btree */
5247 MemPage **ppPage, /* Store pointer to the allocated page here */
5248 Pgno *pPgno, /* Store the page number here */
5249 Pgno nearby, /* Search for a page near this one */
5250 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005251){
drh3aac2dd2004-04-26 14:10:20 +00005252 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00005253 int rc;
drh35cd6432009-06-05 14:17:21 +00005254 u32 n; /* Number of pages on the freelist */
drh042d6a12009-06-17 13:57:16 +00005255 u32 k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00005256 MemPage *pTrunk = 0;
5257 MemPage *pPrevTrunk = 0;
drh1662b5a2009-06-04 19:06:09 +00005258 Pgno mxPage; /* Total size of the database file */
drh30e58752002-03-02 20:41:57 +00005259
drh1fee73e2007-08-29 04:00:57 +00005260 assert( sqlite3_mutex_held(pBt->mutex) );
dan09ff9e12013-03-11 11:49:03 +00005261 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
drh3aac2dd2004-04-26 14:10:20 +00005262 pPage1 = pBt->pPage1;
drhb1299152010-03-30 22:58:33 +00005263 mxPage = btreePagecount(pBt);
drh113762a2014-11-19 16:36:25 +00005264 /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
5265 ** stores stores the total number of pages on the freelist. */
drh3aac2dd2004-04-26 14:10:20 +00005266 n = get4byte(&pPage1->aData[36]);
drhdf35a082009-07-09 02:24:35 +00005267 testcase( n==mxPage-1 );
5268 if( n>=mxPage ){
drh1662b5a2009-06-04 19:06:09 +00005269 return SQLITE_CORRUPT_BKPT;
5270 }
drh3aac2dd2004-04-26 14:10:20 +00005271 if( n>0 ){
drh91025292004-05-03 19:49:32 +00005272 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005273 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005274 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
5275
drh82e647d2013-03-02 03:25:55 +00005276 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00005277 ** shows that the page 'nearby' is somewhere on the free-list, then
5278 ** the entire-list will be searched for that page.
5279 */
5280#ifndef SQLITE_OMIT_AUTOVACUUM
dan51f0b6d2013-02-22 20:16:34 +00005281 if( eMode==BTALLOC_EXACT ){
5282 if( nearby<=mxPage ){
5283 u8 eType;
5284 assert( nearby>0 );
5285 assert( pBt->autoVacuum );
5286 rc = ptrmapGet(pBt, nearby, &eType, 0);
5287 if( rc ) return rc;
5288 if( eType==PTRMAP_FREEPAGE ){
5289 searchList = 1;
5290 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005291 }
dan51f0b6d2013-02-22 20:16:34 +00005292 }else if( eMode==BTALLOC_LE ){
5293 searchList = 1;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005294 }
5295#endif
5296
5297 /* Decrement the free-list count by 1. Set iTrunk to the index of the
5298 ** first free-list trunk page. iPrevTrunk is initially 1.
5299 */
danielk19773b8a05f2007-03-19 17:44:26 +00005300 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00005301 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00005302 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005303
5304 /* The code within this loop is run only once if the 'searchList' variable
5305 ** is not true. Otherwise, it runs once for each trunk-page on the
drh82e647d2013-03-02 03:25:55 +00005306 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
5307 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
danielk1977cb1a7eb2004-11-05 12:27:02 +00005308 */
5309 do {
5310 pPrevTrunk = pTrunk;
5311 if( pPrevTrunk ){
drh113762a2014-11-19 16:36:25 +00005312 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
5313 ** is the page number of the next freelist trunk page in the list or
5314 ** zero if this is the last freelist trunk page. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005315 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00005316 }else{
drh113762a2014-11-19 16:36:25 +00005317 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
5318 ** stores the page number of the first page of the freelist, or zero if
5319 ** the freelist is empty. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005320 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00005321 }
drhdf35a082009-07-09 02:24:35 +00005322 testcase( iTrunk==mxPage );
drh1662b5a2009-06-04 19:06:09 +00005323 if( iTrunk>mxPage ){
5324 rc = SQLITE_CORRUPT_BKPT;
5325 }else{
drhb00fc3b2013-08-21 23:42:32 +00005326 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
drh1662b5a2009-06-04 19:06:09 +00005327 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005328 if( rc ){
drhd3627af2006-12-18 18:34:51 +00005329 pTrunk = 0;
5330 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005331 }
drhb07028f2011-10-14 21:49:18 +00005332 assert( pTrunk!=0 );
5333 assert( pTrunk->aData!=0 );
drh113762a2014-11-19 16:36:25 +00005334 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
5335 ** is the number of leaf page pointers to follow. */
5336 k = get4byte(&pTrunk->aData[4]);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005337 if( k==0 && !searchList ){
5338 /* The trunk has no leaves and the list is not being searched.
5339 ** So extract the trunk page itself and use it as the newly
5340 ** allocated page */
5341 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00005342 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00005343 if( rc ){
5344 goto end_allocate_page;
5345 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005346 *pPgno = iTrunk;
5347 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5348 *ppPage = pTrunk;
5349 pTrunk = 0;
5350 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh042d6a12009-06-17 13:57:16 +00005351 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00005352 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00005353 rc = SQLITE_CORRUPT_BKPT;
5354 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005355#ifndef SQLITE_OMIT_AUTOVACUUM
dan51f0b6d2013-02-22 20:16:34 +00005356 }else if( searchList
5357 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
5358 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00005359 /* The list is being searched and this trunk page is the page
5360 ** to allocate, regardless of whether it has leaves.
5361 */
dan51f0b6d2013-02-22 20:16:34 +00005362 *pPgno = iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005363 *ppPage = pTrunk;
5364 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005365 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00005366 if( rc ){
5367 goto end_allocate_page;
5368 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005369 if( k==0 ){
5370 if( !pPrevTrunk ){
5371 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5372 }else{
danf48c3552010-08-23 15:41:24 +00005373 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
5374 if( rc!=SQLITE_OK ){
5375 goto end_allocate_page;
5376 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005377 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
5378 }
5379 }else{
5380 /* The trunk page is required by the caller but it contains
5381 ** pointers to free-list leaves. The first leaf becomes a trunk
5382 ** page in this case.
5383 */
5384 MemPage *pNewTrunk;
5385 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh1662b5a2009-06-04 19:06:09 +00005386 if( iNewTrunk>mxPage ){
5387 rc = SQLITE_CORRUPT_BKPT;
5388 goto end_allocate_page;
5389 }
drhdf35a082009-07-09 02:24:35 +00005390 testcase( iNewTrunk==mxPage );
drhb00fc3b2013-08-21 23:42:32 +00005391 rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005392 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00005393 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005394 }
danielk19773b8a05f2007-03-19 17:44:26 +00005395 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005396 if( rc!=SQLITE_OK ){
5397 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00005398 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005399 }
5400 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
5401 put4byte(&pNewTrunk->aData[4], k-1);
5402 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00005403 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005404 if( !pPrevTrunk ){
drhc5053fb2008-11-27 02:22:10 +00005405 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
danielk1977cb1a7eb2004-11-05 12:27:02 +00005406 put4byte(&pPage1->aData[32], iNewTrunk);
5407 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00005408 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00005409 if( rc ){
5410 goto end_allocate_page;
5411 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005412 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
5413 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005414 }
5415 pTrunk = 0;
5416 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
5417#endif
danielk1977e5765212009-06-17 11:13:28 +00005418 }else if( k>0 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00005419 /* Extract a leaf from the trunk */
drh042d6a12009-06-17 13:57:16 +00005420 u32 closest;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005421 Pgno iPage;
5422 unsigned char *aData = pTrunk->aData;
5423 if( nearby>0 ){
drh042d6a12009-06-17 13:57:16 +00005424 u32 i;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005425 closest = 0;
danf38b65a2013-02-22 20:57:47 +00005426 if( eMode==BTALLOC_LE ){
5427 for(i=0; i<k; i++){
5428 iPage = get4byte(&aData[8+i*4]);
dan87ade192013-02-23 17:49:16 +00005429 if( iPage<=nearby ){
danf38b65a2013-02-22 20:57:47 +00005430 closest = i;
5431 break;
5432 }
5433 }
5434 }else{
5435 int dist;
5436 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
5437 for(i=1; i<k; i++){
5438 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
5439 if( d2<dist ){
5440 closest = i;
5441 dist = d2;
5442 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005443 }
5444 }
5445 }else{
5446 closest = 0;
5447 }
5448
5449 iPage = get4byte(&aData[8+closest*4]);
drhdf35a082009-07-09 02:24:35 +00005450 testcase( iPage==mxPage );
drh1662b5a2009-06-04 19:06:09 +00005451 if( iPage>mxPage ){
5452 rc = SQLITE_CORRUPT_BKPT;
5453 goto end_allocate_page;
5454 }
drhdf35a082009-07-09 02:24:35 +00005455 testcase( iPage==mxPage );
dan51f0b6d2013-02-22 20:16:34 +00005456 if( !searchList
5457 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
5458 ){
danielk1977bea2a942009-01-20 17:06:27 +00005459 int noContent;
shane1f9e6aa2008-06-09 19:27:11 +00005460 *pPgno = iPage;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005461 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
5462 ": %d more free pages\n",
5463 *pPgno, closest+1, k, pTrunk->pgno, n-1));
drh93b4fc72011-04-07 14:47:01 +00005464 rc = sqlite3PagerWrite(pTrunk->pDbPage);
5465 if( rc ) goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005466 if( closest<k-1 ){
5467 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
5468 }
5469 put4byte(&aData[4], k-1);
drh3f387402014-09-24 01:23:00 +00005470 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
drhb00fc3b2013-08-21 23:42:32 +00005471 rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005472 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00005473 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00005474 if( rc!=SQLITE_OK ){
5475 releasePage(*ppPage);
5476 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005477 }
5478 searchList = 0;
5479 }
drhee696e22004-08-30 16:52:17 +00005480 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005481 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00005482 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005483 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00005484 }else{
danbc1a3c62013-02-23 16:40:46 +00005485 /* There are no pages on the freelist, so append a new page to the
5486 ** database image.
5487 **
5488 ** Normally, new pages allocated by this block can be requested from the
5489 ** pager layer with the 'no-content' flag set. This prevents the pager
5490 ** from trying to read the pages content from disk. However, if the
5491 ** current transaction has already run one or more incremental-vacuum
5492 ** steps, then the page we are about to allocate may contain content
5493 ** that is required in the event of a rollback. In this case, do
5494 ** not set the no-content flag. This causes the pager to load and journal
5495 ** the current page content before overwriting it.
5496 **
5497 ** Note that the pager will not actually attempt to load or journal
5498 ** content for any page that really does lie past the end of the database
5499 ** file on disk. So the effects of disabling the no-content optimization
5500 ** here are confined to those pages that lie between the end of the
5501 ** database image and the end of the database file.
5502 */
drh3f387402014-09-24 01:23:00 +00005503 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
danbc1a3c62013-02-23 16:40:46 +00005504
drhdd3cd972010-03-27 17:12:36 +00005505 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
5506 if( rc ) return rc;
5507 pBt->nPage++;
5508 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
danielk1977bea2a942009-01-20 17:06:27 +00005509
danielk1977afcdd022004-10-31 16:25:42 +00005510#ifndef SQLITE_OMIT_AUTOVACUUM
drhdd3cd972010-03-27 17:12:36 +00005511 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
danielk1977afcdd022004-10-31 16:25:42 +00005512 /* If *pPgno refers to a pointer-map page, allocate two new pages
5513 ** at the end of the file instead of one. The first allocated page
5514 ** becomes a new pointer-map page, the second is used by the caller.
5515 */
danielk1977ac861692009-03-28 10:54:22 +00005516 MemPage *pPg = 0;
drhdd3cd972010-03-27 17:12:36 +00005517 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
5518 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
drhb00fc3b2013-08-21 23:42:32 +00005519 rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
danielk1977ac861692009-03-28 10:54:22 +00005520 if( rc==SQLITE_OK ){
5521 rc = sqlite3PagerWrite(pPg->pDbPage);
5522 releasePage(pPg);
5523 }
5524 if( rc ) return rc;
drhdd3cd972010-03-27 17:12:36 +00005525 pBt->nPage++;
5526 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
danielk1977afcdd022004-10-31 16:25:42 +00005527 }
5528#endif
drhdd3cd972010-03-27 17:12:36 +00005529 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
5530 *pPgno = pBt->nPage;
danielk1977afcdd022004-10-31 16:25:42 +00005531
danielk1977599fcba2004-11-08 07:13:13 +00005532 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhb00fc3b2013-08-21 23:42:32 +00005533 rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
drh3b7511c2001-05-26 13:15:44 +00005534 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00005535 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00005536 if( rc!=SQLITE_OK ){
5537 releasePage(*ppPage);
5538 }
drh3a4c1412004-05-09 20:40:11 +00005539 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00005540 }
danielk1977599fcba2004-11-08 07:13:13 +00005541
5542 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00005543
5544end_allocate_page:
5545 releasePage(pTrunk);
5546 releasePage(pPrevTrunk);
danielk1977b247c212008-11-21 09:09:01 +00005547 if( rc==SQLITE_OK ){
5548 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
5549 releasePage(*ppPage);
dan7df42ab2014-01-20 18:25:44 +00005550 *ppPage = 0;
danielk1977b247c212008-11-21 09:09:01 +00005551 return SQLITE_CORRUPT_BKPT;
5552 }
5553 (*ppPage)->isInit = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00005554 }else{
5555 *ppPage = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00005556 }
drh93b4fc72011-04-07 14:47:01 +00005557 assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
drh3b7511c2001-05-26 13:15:44 +00005558 return rc;
5559}
5560
5561/*
danielk1977bea2a942009-01-20 17:06:27 +00005562** This function is used to add page iPage to the database file free-list.
5563** It is assumed that the page is not already a part of the free-list.
drh5e2f8b92001-05-28 00:41:15 +00005564**
danielk1977bea2a942009-01-20 17:06:27 +00005565** The value passed as the second argument to this function is optional.
5566** If the caller happens to have a pointer to the MemPage object
5567** corresponding to page iPage handy, it may pass it as the second value.
5568** Otherwise, it may pass NULL.
5569**
5570** If a pointer to a MemPage object is passed as the second argument,
5571** its reference count is not altered by this function.
drh3b7511c2001-05-26 13:15:44 +00005572*/
danielk1977bea2a942009-01-20 17:06:27 +00005573static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
5574 MemPage *pTrunk = 0; /* Free-list trunk page */
5575 Pgno iTrunk = 0; /* Page number of free-list trunk page */
5576 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
5577 MemPage *pPage; /* Page being freed. May be NULL. */
5578 int rc; /* Return Code */
5579 int nFree; /* Initial number of pages on free-list */
drh8b2f49b2001-06-08 00:21:52 +00005580
danielk1977bea2a942009-01-20 17:06:27 +00005581 assert( sqlite3_mutex_held(pBt->mutex) );
5582 assert( iPage>1 );
5583 assert( !pMemPage || pMemPage->pgno==iPage );
5584
5585 if( pMemPage ){
5586 pPage = pMemPage;
5587 sqlite3PagerRef(pPage->pDbPage);
5588 }else{
5589 pPage = btreePageLookup(pBt, iPage);
5590 }
drh3aac2dd2004-04-26 14:10:20 +00005591
drha34b6762004-05-07 13:30:42 +00005592 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00005593 rc = sqlite3PagerWrite(pPage1->pDbPage);
danielk1977bea2a942009-01-20 17:06:27 +00005594 if( rc ) goto freepage_out;
5595 nFree = get4byte(&pPage1->aData[36]);
5596 put4byte(&pPage1->aData[36], nFree+1);
drh3aac2dd2004-04-26 14:10:20 +00005597
drhc9166342012-01-05 23:32:06 +00005598 if( pBt->btsFlags & BTS_SECURE_DELETE ){
drh5b47efa2010-02-12 18:18:39 +00005599 /* If the secure_delete option is enabled, then
5600 ** always fully overwrite deleted information with zeros.
5601 */
drhb00fc3b2013-08-21 23:42:32 +00005602 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
shaneh84f4b2f2010-02-26 01:46:54 +00005603 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
drh5b47efa2010-02-12 18:18:39 +00005604 ){
5605 goto freepage_out;
5606 }
5607 memset(pPage->aData, 0, pPage->pBt->pageSize);
danielk1977bea2a942009-01-20 17:06:27 +00005608 }
drhfcce93f2006-02-22 03:08:32 +00005609
danielk1977687566d2004-11-02 12:56:41 +00005610 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00005611 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00005612 */
danielk197785d90ca2008-07-19 14:25:15 +00005613 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00005614 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
danielk1977bea2a942009-01-20 17:06:27 +00005615 if( rc ) goto freepage_out;
danielk1977687566d2004-11-02 12:56:41 +00005616 }
danielk1977687566d2004-11-02 12:56:41 +00005617
danielk1977bea2a942009-01-20 17:06:27 +00005618 /* Now manipulate the actual database free-list structure. There are two
5619 ** possibilities. If the free-list is currently empty, or if the first
5620 ** trunk page in the free-list is full, then this page will become a
5621 ** new free-list trunk page. Otherwise, it will become a leaf of the
5622 ** first trunk page in the current free-list. This block tests if it
5623 ** is possible to add the page as a new free-list leaf.
5624 */
5625 if( nFree!=0 ){
drhc046e3e2009-07-15 11:26:44 +00005626 u32 nLeaf; /* Initial number of leaf cells on trunk page */
danielk1977bea2a942009-01-20 17:06:27 +00005627
5628 iTrunk = get4byte(&pPage1->aData[32]);
drhb00fc3b2013-08-21 23:42:32 +00005629 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977bea2a942009-01-20 17:06:27 +00005630 if( rc!=SQLITE_OK ){
5631 goto freepage_out;
5632 }
5633
5634 nLeaf = get4byte(&pTrunk->aData[4]);
drheeb844a2009-08-08 18:01:07 +00005635 assert( pBt->usableSize>32 );
5636 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
danielk1977bea2a942009-01-20 17:06:27 +00005637 rc = SQLITE_CORRUPT_BKPT;
5638 goto freepage_out;
5639 }
drheeb844a2009-08-08 18:01:07 +00005640 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
danielk1977bea2a942009-01-20 17:06:27 +00005641 /* In this case there is room on the trunk page to insert the page
5642 ** being freed as a new leaf.
drh45b1fac2008-07-04 17:52:42 +00005643 **
5644 ** Note that the trunk page is not really full until it contains
5645 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
5646 ** coded. But due to a coding error in versions of SQLite prior to
5647 ** 3.6.0, databases with freelist trunk pages holding more than
5648 ** usableSize/4 - 8 entries will be reported as corrupt. In order
5649 ** to maintain backwards compatibility with older versions of SQLite,
drhc046e3e2009-07-15 11:26:44 +00005650 ** we will continue to restrict the number of entries to usableSize/4 - 8
drh45b1fac2008-07-04 17:52:42 +00005651 ** for now. At some point in the future (once everyone has upgraded
5652 ** to 3.6.0 or later) we should consider fixing the conditional above
5653 ** to read "usableSize/4-2" instead of "usableSize/4-8".
drh113762a2014-11-19 16:36:25 +00005654 **
5655 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
5656 ** avoid using the last six entries in the freelist trunk page array in
5657 ** order that database files created by newer versions of SQLite can be
5658 ** read by older versions of SQLite.
drh45b1fac2008-07-04 17:52:42 +00005659 */
danielk19773b8a05f2007-03-19 17:44:26 +00005660 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00005661 if( rc==SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00005662 put4byte(&pTrunk->aData[4], nLeaf+1);
5663 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
drhc9166342012-01-05 23:32:06 +00005664 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
danielk1977bea2a942009-01-20 17:06:27 +00005665 sqlite3PagerDontWrite(pPage->pDbPage);
5666 }
danielk1977bea2a942009-01-20 17:06:27 +00005667 rc = btreeSetHasContent(pBt, iPage);
drhf5345442007-04-09 12:45:02 +00005668 }
drh3a4c1412004-05-09 20:40:11 +00005669 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
danielk1977bea2a942009-01-20 17:06:27 +00005670 goto freepage_out;
drh3aac2dd2004-04-26 14:10:20 +00005671 }
drh3b7511c2001-05-26 13:15:44 +00005672 }
danielk1977bea2a942009-01-20 17:06:27 +00005673
5674 /* If control flows to this point, then it was not possible to add the
5675 ** the page being freed as a leaf page of the first trunk in the free-list.
5676 ** Possibly because the free-list is empty, or possibly because the
5677 ** first trunk in the free-list is full. Either way, the page being freed
5678 ** will become the new first trunk page in the free-list.
5679 */
drhb00fc3b2013-08-21 23:42:32 +00005680 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
drhc046e3e2009-07-15 11:26:44 +00005681 goto freepage_out;
5682 }
5683 rc = sqlite3PagerWrite(pPage->pDbPage);
5684 if( rc!=SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00005685 goto freepage_out;
5686 }
5687 put4byte(pPage->aData, iTrunk);
5688 put4byte(&pPage->aData[4], 0);
5689 put4byte(&pPage1->aData[32], iPage);
5690 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
5691
5692freepage_out:
5693 if( pPage ){
5694 pPage->isInit = 0;
5695 }
5696 releasePage(pPage);
5697 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00005698 return rc;
5699}
drhc314dc72009-07-21 11:52:34 +00005700static void freePage(MemPage *pPage, int *pRC){
5701 if( (*pRC)==SQLITE_OK ){
5702 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
5703 }
danielk1977bea2a942009-01-20 17:06:27 +00005704}
drh3b7511c2001-05-26 13:15:44 +00005705
5706/*
drh9bfdc252014-09-24 02:05:41 +00005707** Free any overflow pages associated with the given Cell. Write the
5708** local Cell size (the number of bytes on the original page, omitting
5709** overflow) into *pnSize.
drh3b7511c2001-05-26 13:15:44 +00005710*/
drh9bfdc252014-09-24 02:05:41 +00005711static int clearCell(
5712 MemPage *pPage, /* The page that contains the Cell */
5713 unsigned char *pCell, /* First byte of the Cell */
5714 u16 *pnSize /* Write the size of the Cell here */
5715){
danielk1977aef0bf62005-12-30 16:28:01 +00005716 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00005717 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00005718 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00005719 int rc;
drh94440812007-03-06 11:42:19 +00005720 int nOvfl;
shaneh1df2db72010-08-18 02:28:48 +00005721 u32 ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00005722
drh1fee73e2007-08-29 04:00:57 +00005723 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197730548662009-07-09 05:07:37 +00005724 btreeParseCellPtr(pPage, pCell, &info);
drh9bfdc252014-09-24 02:05:41 +00005725 *pnSize = info.nSize;
drh6f11bef2004-05-13 01:12:56 +00005726 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00005727 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00005728 }
drhe42a9b42011-08-31 13:27:19 +00005729 if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
mistachkin70a1b712012-09-28 18:13:35 +00005730 return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
drhe42a9b42011-08-31 13:27:19 +00005731 }
drh6f11bef2004-05-13 01:12:56 +00005732 ovflPgno = get4byte(&pCell[info.iOverflow]);
shane63207ab2009-02-04 01:49:30 +00005733 assert( pBt->usableSize > 4 );
drh94440812007-03-06 11:42:19 +00005734 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00005735 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
5736 assert( ovflPgno==0 || nOvfl>0 );
5737 while( nOvfl-- ){
shane63207ab2009-02-04 01:49:30 +00005738 Pgno iNext = 0;
danielk1977bea2a942009-01-20 17:06:27 +00005739 MemPage *pOvfl = 0;
drhb1299152010-03-30 22:58:33 +00005740 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
danielk1977e589a672009-04-11 16:06:15 +00005741 /* 0 is not a legal page number and page 1 cannot be an
5742 ** overflow page. Therefore if ovflPgno<2 or past the end of the
5743 ** file the database must be corrupt. */
drh49285702005-09-17 15:20:26 +00005744 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00005745 }
danielk1977bea2a942009-01-20 17:06:27 +00005746 if( nOvfl ){
5747 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
5748 if( rc ) return rc;
5749 }
dan887d4b22010-02-25 12:09:16 +00005750
shaneh1da207e2010-03-09 14:41:12 +00005751 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
dan887d4b22010-02-25 12:09:16 +00005752 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
5753 ){
5754 /* There is no reason any cursor should have an outstanding reference
5755 ** to an overflow page belonging to a cell that is being deleted/updated.
5756 ** So if there exists more than one reference to this page, then it
5757 ** must not really be an overflow page and the database must be corrupt.
5758 ** It is helpful to detect this before calling freePage2(), as
5759 ** freePage2() may zero the page contents if secure-delete mode is
5760 ** enabled. If this 'overflow' page happens to be a page that the
5761 ** caller is iterating through or using in some other way, this
5762 ** can be problematic.
5763 */
5764 rc = SQLITE_CORRUPT_BKPT;
5765 }else{
5766 rc = freePage2(pBt, pOvfl, ovflPgno);
5767 }
5768
danielk1977bea2a942009-01-20 17:06:27 +00005769 if( pOvfl ){
5770 sqlite3PagerUnref(pOvfl->pDbPage);
5771 }
drh3b7511c2001-05-26 13:15:44 +00005772 if( rc ) return rc;
danielk1977bea2a942009-01-20 17:06:27 +00005773 ovflPgno = iNext;
drh3b7511c2001-05-26 13:15:44 +00005774 }
drh5e2f8b92001-05-28 00:41:15 +00005775 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00005776}
5777
5778/*
drh91025292004-05-03 19:49:32 +00005779** Create the byte sequence used to represent a cell on page pPage
5780** and write that byte sequence into pCell[]. Overflow pages are
5781** allocated and filled in as necessary. The calling procedure
5782** is responsible for making sure sufficient space has been allocated
5783** for pCell[].
5784**
5785** Note that pCell does not necessary need to point to the pPage->aData
5786** area. pCell might point to some temporary storage. The cell will
5787** be constructed in this temporary area then copied into pPage->aData
5788** later.
drh3b7511c2001-05-26 13:15:44 +00005789*/
5790static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00005791 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00005792 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00005793 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00005794 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00005795 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00005796 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00005797){
drh3b7511c2001-05-26 13:15:44 +00005798 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00005799 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00005800 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00005801 int spaceLeft;
5802 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00005803 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00005804 unsigned char *pPrior;
5805 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00005806 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00005807 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00005808 int nHeader;
drh3b7511c2001-05-26 13:15:44 +00005809
drh1fee73e2007-08-29 04:00:57 +00005810 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00005811
drhc5053fb2008-11-27 02:22:10 +00005812 /* pPage is not necessarily writeable since pCell might be auxiliary
5813 ** buffer space that is separate from the pPage buffer area */
5814 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
5815 || sqlite3PagerIswriteable(pPage->pDbPage) );
5816
drh91025292004-05-03 19:49:32 +00005817 /* Fill in the header. */
drh6200c882014-09-23 22:36:25 +00005818 nHeader = pPage->childPtrSize;
5819 nPayload = nData + nZero;
drh3e28ff52014-09-24 00:59:08 +00005820 if( pPage->intKeyLeaf ){
drh6200c882014-09-23 22:36:25 +00005821 nHeader += putVarint32(&pCell[nHeader], nPayload);
drh6f11bef2004-05-13 01:12:56 +00005822 }else{
drh6200c882014-09-23 22:36:25 +00005823 assert( nData==0 );
5824 assert( nZero==0 );
drh91025292004-05-03 19:49:32 +00005825 }
drh6f11bef2004-05-13 01:12:56 +00005826 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh6f11bef2004-05-13 01:12:56 +00005827
drh6200c882014-09-23 22:36:25 +00005828 /* Fill in the payload size */
drh3aac2dd2004-04-26 14:10:20 +00005829 if( pPage->intKey ){
5830 pSrc = pData;
5831 nSrc = nData;
drh91025292004-05-03 19:49:32 +00005832 nData = 0;
drhf49661a2008-12-10 16:45:50 +00005833 }else{
danielk197731d31b82009-07-13 13:18:07 +00005834 if( NEVER(nKey>0x7fffffff || pKey==0) ){
5835 return SQLITE_CORRUPT_BKPT;
drh20abac22009-01-28 20:21:17 +00005836 }
drh6200c882014-09-23 22:36:25 +00005837 nPayload = (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00005838 pSrc = pKey;
drhf49661a2008-12-10 16:45:50 +00005839 nSrc = (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00005840 }
drh6200c882014-09-23 22:36:25 +00005841 if( nPayload<=pPage->maxLocal ){
5842 n = nHeader + nPayload;
5843 testcase( n==3 );
5844 testcase( n==4 );
5845 if( n<4 ) n = 4;
5846 *pnSize = n;
5847 spaceLeft = nPayload;
5848 pPrior = pCell;
5849 }else{
5850 int mn = pPage->minLocal;
5851 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
5852 testcase( n==pPage->maxLocal );
5853 testcase( n==pPage->maxLocal+1 );
5854 if( n > pPage->maxLocal ) n = mn;
5855 spaceLeft = n;
5856 *pnSize = n + nHeader + 4;
5857 pPrior = &pCell[nHeader+n];
5858 }
drh3aac2dd2004-04-26 14:10:20 +00005859 pPayload = &pCell[nHeader];
drh3b7511c2001-05-26 13:15:44 +00005860
drh6200c882014-09-23 22:36:25 +00005861 /* At this point variables should be set as follows:
5862 **
5863 ** nPayload Total payload size in bytes
5864 ** pPayload Begin writing payload here
5865 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
5866 ** that means content must spill into overflow pages.
5867 ** *pnSize Size of the local cell (not counting overflow pages)
5868 ** pPrior Where to write the pgno of the first overflow page
5869 **
5870 ** Use a call to btreeParseCellPtr() to verify that the values above
5871 ** were computed correctly.
5872 */
5873#if SQLITE_DEBUG
5874 {
5875 CellInfo info;
5876 btreeParseCellPtr(pPage, pCell, &info);
5877 assert( nHeader=(int)(info.pPayload - pCell) );
5878 assert( info.nKey==nKey );
5879 assert( *pnSize == info.nSize );
5880 assert( spaceLeft == info.nLocal );
5881 assert( pPrior == &pCell[info.iOverflow] );
5882 }
5883#endif
5884
5885 /* Write the payload into the local Cell and any extra into overflow pages */
drh3b7511c2001-05-26 13:15:44 +00005886 while( nPayload>0 ){
5887 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00005888#ifndef SQLITE_OMIT_AUTOVACUUM
5889 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00005890 if( pBt->autoVacuum ){
5891 do{
5892 pgnoOvfl++;
5893 } while(
5894 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
5895 );
danielk1977b39f70b2007-05-17 18:28:11 +00005896 }
danielk1977afcdd022004-10-31 16:25:42 +00005897#endif
drhf49661a2008-12-10 16:45:50 +00005898 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00005899#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00005900 /* If the database supports auto-vacuum, and the second or subsequent
5901 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00005902 ** for that page now.
5903 **
5904 ** If this is the first overflow page, then write a partial entry
5905 ** to the pointer-map. If we write nothing to this pointer-map slot,
5906 ** then the optimistic overflow chain processing in clearCell()
mistachkin48864df2013-03-21 21:20:32 +00005907 ** may misinterpret the uninitialized values and delete the
danielk19774ef24492007-05-23 09:52:41 +00005908 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00005909 */
danielk19774ef24492007-05-23 09:52:41 +00005910 if( pBt->autoVacuum && rc==SQLITE_OK ){
5911 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
drh98add2e2009-07-20 17:11:49 +00005912 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
danielk197789a4be82007-05-23 13:34:32 +00005913 if( rc ){
5914 releasePage(pOvfl);
5915 }
danielk1977afcdd022004-10-31 16:25:42 +00005916 }
5917#endif
drh3b7511c2001-05-26 13:15:44 +00005918 if( rc ){
drh9b171272004-05-08 02:03:22 +00005919 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00005920 return rc;
5921 }
drhc5053fb2008-11-27 02:22:10 +00005922
5923 /* If pToRelease is not zero than pPrior points into the data area
5924 ** of pToRelease. Make sure pToRelease is still writeable. */
5925 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
5926
5927 /* If pPrior is part of the data area of pPage, then make sure pPage
5928 ** is still writeable */
5929 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
5930 || sqlite3PagerIswriteable(pPage->pDbPage) );
5931
drh3aac2dd2004-04-26 14:10:20 +00005932 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00005933 releasePage(pToRelease);
5934 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00005935 pPrior = pOvfl->aData;
5936 put4byte(pPrior, 0);
5937 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00005938 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00005939 }
5940 n = nPayload;
5941 if( n>spaceLeft ) n = spaceLeft;
drhc5053fb2008-11-27 02:22:10 +00005942
5943 /* If pToRelease is not zero than pPayload points into the data area
5944 ** of pToRelease. Make sure pToRelease is still writeable. */
5945 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
5946
5947 /* If pPayload is part of the data area of pPage, then make sure pPage
5948 ** is still writeable */
5949 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
5950 || sqlite3PagerIswriteable(pPage->pDbPage) );
5951
drhb026e052007-05-02 01:34:31 +00005952 if( nSrc>0 ){
5953 if( n>nSrc ) n = nSrc;
5954 assert( pSrc );
5955 memcpy(pPayload, pSrc, n);
5956 }else{
5957 memset(pPayload, 0, n);
5958 }
drh3b7511c2001-05-26 13:15:44 +00005959 nPayload -= n;
drhde647132004-05-07 17:57:49 +00005960 pPayload += n;
drh9b171272004-05-08 02:03:22 +00005961 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00005962 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00005963 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00005964 if( nSrc==0 ){
5965 nSrc = nData;
5966 pSrc = pData;
5967 }
drhdd793422001-06-28 01:54:48 +00005968 }
drh9b171272004-05-08 02:03:22 +00005969 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00005970 return SQLITE_OK;
5971}
5972
drh14acc042001-06-10 19:56:58 +00005973/*
5974** Remove the i-th cell from pPage. This routine effects pPage only.
5975** The cell content is not freed or deallocated. It is assumed that
5976** the cell content has been copied someplace else. This routine just
5977** removes the reference to the cell from pPage.
5978**
5979** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00005980*/
drh98add2e2009-07-20 17:11:49 +00005981static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
drh43b18e12010-08-17 19:40:08 +00005982 u32 pc; /* Offset to cell content of cell being deleted */
drh43605152004-05-29 21:46:49 +00005983 u8 *data; /* pPage->aData */
5984 u8 *ptr; /* Used to move bytes around within data[] */
shanedcc50b72008-11-13 18:29:50 +00005985 int rc; /* The return code */
drhc314dc72009-07-21 11:52:34 +00005986 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
drh43605152004-05-29 21:46:49 +00005987
drh98add2e2009-07-20 17:11:49 +00005988 if( *pRC ) return;
5989
drh8c42ca92001-06-22 19:15:00 +00005990 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00005991 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00005992 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00005993 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00005994 data = pPage->aData;
drh3def2352011-11-11 00:27:15 +00005995 ptr = &pPage->aCellIdx[2*idx];
shane0af3f892008-11-12 04:55:34 +00005996 pc = get2byte(ptr);
drhc314dc72009-07-21 11:52:34 +00005997 hdr = pPage->hdrOffset;
5998 testcase( pc==get2byte(&data[hdr+5]) );
5999 testcase( pc+sz==pPage->pBt->usableSize );
drh43b18e12010-08-17 19:40:08 +00006000 if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
drh98add2e2009-07-20 17:11:49 +00006001 *pRC = SQLITE_CORRUPT_BKPT;
6002 return;
shane0af3f892008-11-12 04:55:34 +00006003 }
shanedcc50b72008-11-13 18:29:50 +00006004 rc = freeSpace(pPage, pc, sz);
drh98add2e2009-07-20 17:11:49 +00006005 if( rc ){
6006 *pRC = rc;
6007 return;
shanedcc50b72008-11-13 18:29:50 +00006008 }
drh14acc042001-06-10 19:56:58 +00006009 pPage->nCell--;
drhfdab0262014-11-20 15:30:50 +00006010 if( pPage->nCell==0 ){
6011 memset(&data[hdr+1], 0, 4);
6012 data[hdr+7] = 0;
6013 put2byte(&data[hdr+5], pPage->pBt->usableSize);
6014 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
6015 - pPage->childPtrSize - 8;
6016 }else{
6017 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
6018 put2byte(&data[hdr+3], pPage->nCell);
6019 pPage->nFree += 2;
6020 }
drh14acc042001-06-10 19:56:58 +00006021}
6022
6023/*
6024** Insert a new cell on pPage at cell index "i". pCell points to the
6025** content of the cell.
6026**
6027** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00006028** will not fit, then make a copy of the cell content into pTemp if
6029** pTemp is not null. Regardless of pTemp, allocate a new entry
drh2cbd78b2012-02-02 19:37:18 +00006030** in pPage->apOvfl[] and make it point to the cell content (either
drh43605152004-05-29 21:46:49 +00006031** in pTemp or the original pCell) and also record its index.
6032** Allocating a new entry in pPage->aCell[] implies that
6033** pPage->nOverflow is incremented.
drh14acc042001-06-10 19:56:58 +00006034*/
drh98add2e2009-07-20 17:11:49 +00006035static void insertCell(
drh24cd67e2004-05-10 16:18:47 +00006036 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00006037 int i, /* New cell becomes the i-th cell of the page */
6038 u8 *pCell, /* Content of the new cell */
6039 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00006040 u8 *pTemp, /* Temp storage space for pCell, if needed */
drh98add2e2009-07-20 17:11:49 +00006041 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
6042 int *pRC /* Read and write return code from here */
drh24cd67e2004-05-10 16:18:47 +00006043){
drh383d30f2010-02-26 13:07:37 +00006044 int idx = 0; /* Where to write new cell content in data[] */
drh43605152004-05-29 21:46:49 +00006045 int j; /* Loop counter */
drh43605152004-05-29 21:46:49 +00006046 int end; /* First byte past the last cell pointer in data[] */
6047 int ins; /* Index in data[] where new cell pointer is inserted */
drh43605152004-05-29 21:46:49 +00006048 int cellOffset; /* Address of first cell pointer in data[] */
6049 u8 *data; /* The content of the whole page */
danielk19774dbaa892009-06-16 16:50:22 +00006050
drh98add2e2009-07-20 17:11:49 +00006051 if( *pRC ) return;
6052
drh43605152004-05-29 21:46:49 +00006053 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
danf216e322014-08-14 19:53:37 +00006054 assert( MX_CELL(pPage->pBt)<=10921 );
6055 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
drh2cbd78b2012-02-02 19:37:18 +00006056 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
6057 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
drh1fee73e2007-08-29 04:00:57 +00006058 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc9b9b8a2009-12-03 21:26:52 +00006059 /* The cell should normally be sized correctly. However, when moving a
6060 ** malformed cell from a leaf page to an interior page, if the cell size
6061 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
6062 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
6063 ** the term after the || in the following assert(). */
6064 assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
drh43605152004-05-29 21:46:49 +00006065 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00006066 if( pTemp ){
drhd6176c42014-10-11 17:22:55 +00006067 memcpy(pTemp, pCell, sz);
drh43605152004-05-29 21:46:49 +00006068 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00006069 }
danielk19774dbaa892009-06-16 16:50:22 +00006070 if( iChild ){
6071 put4byte(pCell, iChild);
6072 }
drh43605152004-05-29 21:46:49 +00006073 j = pPage->nOverflow++;
drh2cbd78b2012-02-02 19:37:18 +00006074 assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
6075 pPage->apOvfl[j] = pCell;
6076 pPage->aiOvfl[j] = (u16)i;
drh14acc042001-06-10 19:56:58 +00006077 }else{
danielk19776e465eb2007-08-21 13:11:00 +00006078 int rc = sqlite3PagerWrite(pPage->pDbPage);
6079 if( rc!=SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00006080 *pRC = rc;
6081 return;
danielk19776e465eb2007-08-21 13:11:00 +00006082 }
6083 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00006084 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00006085 cellOffset = pPage->cellOffset;
drh0a45c272009-07-08 01:49:11 +00006086 end = cellOffset + 2*pPage->nCell;
drh43605152004-05-29 21:46:49 +00006087 ins = cellOffset + 2*i;
drh0a45c272009-07-08 01:49:11 +00006088 rc = allocateSpace(pPage, sz, &idx);
drh98add2e2009-07-20 17:11:49 +00006089 if( rc ){ *pRC = rc; return; }
drhc314dc72009-07-21 11:52:34 +00006090 /* The allocateSpace() routine guarantees the following two properties
6091 ** if it returns success */
6092 assert( idx >= end+2 );
drhfcd71b62011-04-05 22:08:24 +00006093 assert( idx+sz <= (int)pPage->pBt->usableSize );
drh43605152004-05-29 21:46:49 +00006094 pPage->nCell++;
drh0a45c272009-07-08 01:49:11 +00006095 pPage->nFree -= (u16)(2 + sz);
drhd6176c42014-10-11 17:22:55 +00006096 memcpy(&data[idx], pCell, sz);
danielk19774dbaa892009-06-16 16:50:22 +00006097 if( iChild ){
6098 put4byte(&data[idx], iChild);
6099 }
drh8f518832013-12-09 02:32:19 +00006100 memmove(&data[ins+2], &data[ins], end-ins);
drh43605152004-05-29 21:46:49 +00006101 put2byte(&data[ins], idx);
drh0a45c272009-07-08 01:49:11 +00006102 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
danielk1977a19df672004-11-03 11:37:07 +00006103#ifndef SQLITE_OMIT_AUTOVACUUM
6104 if( pPage->pBt->autoVacuum ){
6105 /* The cell may contain a pointer to an overflow page. If so, write
6106 ** the entry for the overflow page into the pointer map.
6107 */
drh98add2e2009-07-20 17:11:49 +00006108 ptrmapPutOvflPtr(pPage, pCell, pRC);
danielk1977a19df672004-11-03 11:37:07 +00006109 }
6110#endif
drh14acc042001-06-10 19:56:58 +00006111 }
6112}
6113
6114/*
dan8e9ba0c2014-10-14 17:27:04 +00006115** Array apCell[] contains pointers to nCell b-tree page cells. The
6116** szCell[] array contains the size in bytes of each cell. This function
6117** replaces the current contents of page pPg with the contents of the cell
6118** array.
6119**
6120** Some of the cells in apCell[] may currently be stored in pPg. This
6121** function works around problems caused by this by making a copy of any
6122** such cells before overwriting the page data.
6123**
6124** The MemPage.nFree field is invalidated by this function. It is the
6125** responsibility of the caller to set it correctly.
drhfa1a98a2004-05-14 19:08:17 +00006126*/
dan33ea4862014-10-09 19:35:37 +00006127static void rebuildPage(
6128 MemPage *pPg, /* Edit this page */
dan33ea4862014-10-09 19:35:37 +00006129 int nCell, /* Final number of cells on page */
dan09c68402014-10-11 20:00:24 +00006130 u8 **apCell, /* Array of cells */
6131 u16 *szCell /* Array of cell sizes */
dan33ea4862014-10-09 19:35:37 +00006132){
6133 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
6134 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
6135 const int usableSize = pPg->pBt->usableSize;
6136 u8 * const pEnd = &aData[usableSize];
6137 int i;
6138 u8 *pCellptr = pPg->aCellIdx;
6139 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6140 u8 *pData;
6141
6142 i = get2byte(&aData[hdr+5]);
6143 memcpy(&pTmp[i], &aData[i], usableSize - i);
dan33ea4862014-10-09 19:35:37 +00006144
dan8e9ba0c2014-10-14 17:27:04 +00006145 pData = pEnd;
dan33ea4862014-10-09 19:35:37 +00006146 for(i=0; i<nCell; i++){
6147 u8 *pCell = apCell[i];
6148 if( pCell>aData && pCell<pEnd ){
6149 pCell = &pTmp[pCell - aData];
6150 }
6151 pData -= szCell[i];
6152 memcpy(pData, pCell, szCell[i]);
6153 put2byte(pCellptr, (pData - aData));
6154 pCellptr += 2;
6155 assert( szCell[i]==cellSizePtr(pPg, pCell) );
6156 }
6157
dand7b545b2014-10-13 18:03:27 +00006158 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
dan33ea4862014-10-09 19:35:37 +00006159 pPg->nCell = nCell;
6160 pPg->nOverflow = 0;
6161
6162 put2byte(&aData[hdr+1], 0);
6163 put2byte(&aData[hdr+3], pPg->nCell);
6164 put2byte(&aData[hdr+5], pData - aData);
6165 aData[hdr+7] = 0x00;
6166}
6167
dan8e9ba0c2014-10-14 17:27:04 +00006168/*
6169** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
6170** contains the size in bytes of each such cell. This function attempts to
6171** add the cells stored in the array to page pPg. If it cannot (because
6172** the page needs to be defragmented before the cells will fit), non-zero
6173** is returned. Otherwise, if the cells are added successfully, zero is
6174** returned.
6175**
6176** Argument pCellptr points to the first entry in the cell-pointer array
6177** (part of page pPg) to populate. After cell apCell[0] is written to the
6178** page body, a 16-bit offset is written to pCellptr. And so on, for each
6179** cell in the array. It is the responsibility of the caller to ensure
6180** that it is safe to overwrite this part of the cell-pointer array.
6181**
6182** When this function is called, *ppData points to the start of the
6183** content area on page pPg. If the size of the content area is extended,
6184** *ppData is updated to point to the new start of the content area
6185** before returning.
6186**
6187** Finally, argument pBegin points to the byte immediately following the
6188** end of the space required by this page for the cell-pointer area (for
6189** all cells - not just those inserted by the current call). If the content
6190** area must be extended to before this point in order to accomodate all
6191** cells in apCell[], then the cells do not fit and non-zero is returned.
6192*/
dand7b545b2014-10-13 18:03:27 +00006193static int pageInsertArray(
dan8e9ba0c2014-10-14 17:27:04 +00006194 MemPage *pPg, /* Page to add cells to */
6195 u8 *pBegin, /* End of cell-pointer array */
6196 u8 **ppData, /* IN/OUT: Page content -area pointer */
6197 u8 *pCellptr, /* Pointer to cell-pointer area */
6198 int nCell, /* Number of cells to add to pPg */
dand7b545b2014-10-13 18:03:27 +00006199 u8 **apCell, /* Array of cells */
6200 u16 *szCell /* Array of cell sizes */
6201){
6202 int i;
6203 u8 *aData = pPg->aData;
6204 u8 *pData = *ppData;
dan8e9ba0c2014-10-14 17:27:04 +00006205 const int bFreelist = aData[1] || aData[2];
dan23eba452014-10-24 18:43:57 +00006206 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
dand7b545b2014-10-13 18:03:27 +00006207 for(i=0; i<nCell; i++){
6208 int sz = szCell[i];
drhba0f9992014-10-30 20:48:44 +00006209 int rc;
dand7b545b2014-10-13 18:03:27 +00006210 u8 *pSlot;
drhba0f9992014-10-30 20:48:44 +00006211 if( bFreelist==0 || (pSlot = pageFindSlot(pPg, sz, &rc, 0))==0 ){
dand7b545b2014-10-13 18:03:27 +00006212 pData -= sz;
6213 if( pData<pBegin ) return 1;
6214 pSlot = pData;
6215 }
6216 memcpy(pSlot, apCell[i], sz);
6217 put2byte(pCellptr, (pSlot - aData));
6218 pCellptr += 2;
6219 }
6220 *ppData = pData;
6221 return 0;
6222}
6223
dan8e9ba0c2014-10-14 17:27:04 +00006224/*
6225** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
6226** contains the size in bytes of each such cell. This function adds the
6227** space associated with each cell in the array that is currently stored
6228** within the body of pPg to the pPg free-list. The cell-pointers and other
6229** fields of the page are not updated.
6230**
6231** This function returns the total number of cells added to the free-list.
6232*/
dand7b545b2014-10-13 18:03:27 +00006233static int pageFreeArray(
6234 MemPage *pPg, /* Page to edit */
6235 int nCell, /* Cells to delete */
6236 u8 **apCell, /* Array of cells */
6237 u16 *szCell /* Array of cell sizes */
6238){
6239 u8 * const aData = pPg->aData;
6240 u8 * const pEnd = &aData[pPg->pBt->usableSize];
dan89ca0b32014-10-25 20:36:28 +00006241 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
dand7b545b2014-10-13 18:03:27 +00006242 int nRet = 0;
6243 int i;
6244 u8 *pFree = 0;
6245 int szFree = 0;
6246
6247 for(i=0; i<nCell; i++){
6248 u8 *pCell = apCell[i];
dan89ca0b32014-10-25 20:36:28 +00006249 if( pCell>=pStart && pCell<pEnd ){
dand7b545b2014-10-13 18:03:27 +00006250 int sz = szCell[i];
6251 if( pFree!=(pCell + sz) ){
drhfefa0942014-11-05 21:21:08 +00006252 if( pFree ){
6253 assert( pFree>aData && (pFree - aData)<65536 );
6254 freeSpace(pPg, (u16)(pFree - aData), szFree);
6255 }
dand7b545b2014-10-13 18:03:27 +00006256 pFree = pCell;
6257 szFree = sz;
dan89ca0b32014-10-25 20:36:28 +00006258 if( pFree+sz>pEnd ) return 0;
dand7b545b2014-10-13 18:03:27 +00006259 }else{
6260 pFree = pCell;
6261 szFree += sz;
6262 }
6263 nRet++;
6264 }
6265 }
drhfefa0942014-11-05 21:21:08 +00006266 if( pFree ){
6267 assert( pFree>aData && (pFree - aData)<65536 );
6268 freeSpace(pPg, (u16)(pFree - aData), szFree);
6269 }
dand7b545b2014-10-13 18:03:27 +00006270 return nRet;
6271}
6272
dand7b545b2014-10-13 18:03:27 +00006273/*
drh5ab63772014-11-27 03:46:04 +00006274** apCell[] and szCell[] contains pointers to and sizes of all cells in the
6275** pages being balanced. The current page, pPg, has pPg->nCell cells starting
6276** with apCell[iOld]. After balancing, this page should hold nNew cells
6277** starting at apCell[iNew].
6278**
6279** This routine makes the necessary adjustments to pPg so that it contains
6280** the correct cells after being balanced.
6281**
dand7b545b2014-10-13 18:03:27 +00006282** The pPg->nFree field is invalid when this function returns. It is the
6283** responsibility of the caller to set it correctly.
6284*/
dan09c68402014-10-11 20:00:24 +00006285static void editPage(
6286 MemPage *pPg, /* Edit this page */
6287 int iOld, /* Index of first cell currently on page */
6288 int iNew, /* Index of new first cell on page */
6289 int nNew, /* Final number of cells on page */
6290 u8 **apCell, /* Array of cells */
6291 u16 *szCell /* Array of cell sizes */
6292){
dand7b545b2014-10-13 18:03:27 +00006293 u8 * const aData = pPg->aData;
6294 const int hdr = pPg->hdrOffset;
6295 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
6296 int nCell = pPg->nCell; /* Cells stored on pPg */
6297 u8 *pData;
6298 u8 *pCellptr;
6299 int i;
6300 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
6301 int iNewEnd = iNew + nNew;
dan09c68402014-10-11 20:00:24 +00006302
6303#ifdef SQLITE_DEBUG
dand7b545b2014-10-13 18:03:27 +00006304 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6305 memcpy(pTmp, aData, pPg->pBt->usableSize);
dan09c68402014-10-11 20:00:24 +00006306#endif
6307
dand7b545b2014-10-13 18:03:27 +00006308 /* Remove cells from the start and end of the page */
6309 if( iOld<iNew ){
6310 int nShift = pageFreeArray(
6311 pPg, iNew-iOld, &apCell[iOld], &szCell[iOld]
6312 );
6313 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
6314 nCell -= nShift;
6315 }
6316 if( iNewEnd < iOldEnd ){
6317 nCell -= pageFreeArray(
6318 pPg, iOldEnd-iNewEnd, &apCell[iNewEnd], &szCell[iNewEnd]
6319 );
6320 }
dan09c68402014-10-11 20:00:24 +00006321
drh5ab63772014-11-27 03:46:04 +00006322 pData = &aData[get2byteNotZero(&aData[hdr+5])];
dand7b545b2014-10-13 18:03:27 +00006323 if( pData<pBegin ) goto editpage_fail;
6324
6325 /* Add cells to the start of the page */
6326 if( iNew<iOld ){
drh5ab63772014-11-27 03:46:04 +00006327 int nAdd = MIN(nNew,iOld-iNew);
6328 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
dand7b545b2014-10-13 18:03:27 +00006329 pCellptr = pPg->aCellIdx;
6330 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
6331 if( pageInsertArray(
6332 pPg, pBegin, &pData, pCellptr,
6333 nAdd, &apCell[iNew], &szCell[iNew]
6334 ) ) goto editpage_fail;
6335 nCell += nAdd;
6336 }
6337
6338 /* Add any overflow cells */
6339 for(i=0; i<pPg->nOverflow; i++){
6340 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
6341 if( iCell>=0 && iCell<nNew ){
drhfefa0942014-11-05 21:21:08 +00006342 pCellptr = &pPg->aCellIdx[iCell * 2];
dand7b545b2014-10-13 18:03:27 +00006343 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
6344 nCell++;
6345 if( pageInsertArray(
6346 pPg, pBegin, &pData, pCellptr,
6347 1, &apCell[iCell + iNew], &szCell[iCell + iNew]
6348 ) ) goto editpage_fail;
dan09c68402014-10-11 20:00:24 +00006349 }
dand7b545b2014-10-13 18:03:27 +00006350 }
dan09c68402014-10-11 20:00:24 +00006351
dand7b545b2014-10-13 18:03:27 +00006352 /* Append cells to the end of the page */
6353 pCellptr = &pPg->aCellIdx[nCell*2];
6354 if( pageInsertArray(
6355 pPg, pBegin, &pData, pCellptr,
6356 nNew-nCell, &apCell[iNew+nCell], &szCell[iNew+nCell]
6357 ) ) goto editpage_fail;
dan09c68402014-10-11 20:00:24 +00006358
dand7b545b2014-10-13 18:03:27 +00006359 pPg->nCell = nNew;
6360 pPg->nOverflow = 0;
dan09c68402014-10-11 20:00:24 +00006361
dand7b545b2014-10-13 18:03:27 +00006362 put2byte(&aData[hdr+3], pPg->nCell);
6363 put2byte(&aData[hdr+5], pData - aData);
dan09c68402014-10-11 20:00:24 +00006364
6365#ifdef SQLITE_DEBUG
dan23eba452014-10-24 18:43:57 +00006366 for(i=0; i<nNew && !CORRUPT_DB; i++){
dand7b545b2014-10-13 18:03:27 +00006367 u8 *pCell = apCell[i+iNew];
6368 int iOff = get2byte(&pPg->aCellIdx[i*2]);
6369 if( pCell>=aData && pCell<&aData[pPg->pBt->usableSize] ){
6370 pCell = &pTmp[pCell - aData];
dan09c68402014-10-11 20:00:24 +00006371 }
dand7b545b2014-10-13 18:03:27 +00006372 assert( 0==memcmp(pCell, &aData[iOff], szCell[i+iNew]) );
6373 }
dan09c68402014-10-11 20:00:24 +00006374#endif
6375
dand7b545b2014-10-13 18:03:27 +00006376 return;
dan09c68402014-10-11 20:00:24 +00006377 editpage_fail:
dan09c68402014-10-11 20:00:24 +00006378 /* Unable to edit this page. Rebuild it from scratch instead. */
6379 rebuildPage(pPg, nNew, &apCell[iNew], &szCell[iNew]);
6380}
6381
drh14acc042001-06-10 19:56:58 +00006382/*
drhc3b70572003-01-04 19:44:07 +00006383** The following parameters determine how many adjacent pages get involved
6384** in a balancing operation. NN is the number of neighbors on either side
6385** of the page that participate in the balancing operation. NB is the
6386** total number of pages that participate, including the target page and
6387** NN neighbors on either side.
6388**
6389** The minimum value of NN is 1 (of course). Increasing NN above 1
6390** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
6391** in exchange for a larger degradation in INSERT and UPDATE performance.
6392** The value of NN appears to give the best results overall.
6393*/
6394#define NN 1 /* Number of neighbors on either side of pPage */
6395#define NB (NN*2+1) /* Total pages involved in the balance */
6396
danielk1977ac245ec2005-01-14 13:50:11 +00006397
drh615ae552005-01-16 23:21:00 +00006398#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00006399/*
6400** This version of balance() handles the common special case where
6401** a new entry is being inserted on the extreme right-end of the
6402** tree, in other words, when the new entry will become the largest
6403** entry in the tree.
6404**
drhc314dc72009-07-21 11:52:34 +00006405** Instead of trying to balance the 3 right-most leaf pages, just add
drhf222e712005-01-14 22:55:49 +00006406** a new page to the right-hand side and put the one new entry in
6407** that page. This leaves the right side of the tree somewhat
6408** unbalanced. But odds are that we will be inserting new entries
6409** at the end soon afterwards so the nearly empty page will quickly
6410** fill up. On average.
6411**
6412** pPage is the leaf page which is the right-most page in the tree.
6413** pParent is its parent. pPage must have a single overflow entry
6414** which is also the right-most entry on the page.
danielk1977a50d9aa2009-06-08 14:49:45 +00006415**
6416** The pSpace buffer is used to store a temporary copy of the divider
6417** cell that will be inserted into pParent. Such a cell consists of a 4
6418** byte page number followed by a variable length integer. In other
6419** words, at most 13 bytes. Hence the pSpace buffer must be at
6420** least 13 bytes in size.
drhf222e712005-01-14 22:55:49 +00006421*/
danielk1977a50d9aa2009-06-08 14:49:45 +00006422static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
6423 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
danielk19774dbaa892009-06-16 16:50:22 +00006424 MemPage *pNew; /* Newly allocated page */
danielk19776f235cc2009-06-04 14:46:08 +00006425 int rc; /* Return Code */
6426 Pgno pgnoNew; /* Page number of pNew */
danielk1977ac245ec2005-01-14 13:50:11 +00006427
drh1fee73e2007-08-29 04:00:57 +00006428 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk1977a50d9aa2009-06-08 14:49:45 +00006429 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00006430 assert( pPage->nOverflow==1 );
6431
drh5d433ce2010-08-14 16:02:52 +00006432 /* This error condition is now caught prior to reaching this function */
drh1fd2d7d2014-12-02 16:16:47 +00006433 if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
drhd677b3d2007-08-20 22:48:41 +00006434
danielk1977a50d9aa2009-06-08 14:49:45 +00006435 /* Allocate a new page. This page will become the right-sibling of
6436 ** pPage. Make the parent page writable, so that the new divider cell
6437 ** may be inserted. If both these operations are successful, proceed.
6438 */
drh4f0c5872007-03-26 22:05:01 +00006439 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk19774dbaa892009-06-16 16:50:22 +00006440
danielk1977eaa06f62008-09-18 17:34:44 +00006441 if( rc==SQLITE_OK ){
danielk1977a50d9aa2009-06-08 14:49:45 +00006442
6443 u8 *pOut = &pSpace[4];
drh2cbd78b2012-02-02 19:37:18 +00006444 u8 *pCell = pPage->apOvfl[0];
danielk19776f235cc2009-06-04 14:46:08 +00006445 u16 szCell = cellSizePtr(pPage, pCell);
6446 u8 *pStop;
6447
drhc5053fb2008-11-27 02:22:10 +00006448 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00006449 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
6450 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
dan8e9ba0c2014-10-14 17:27:04 +00006451 rebuildPage(pNew, 1, &pCell, &szCell);
6452 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
danielk19774dbaa892009-06-16 16:50:22 +00006453
6454 /* If this is an auto-vacuum database, update the pointer map
6455 ** with entries for the new page, and any pointer from the
6456 ** cell on the page to an overflow page. If either of these
6457 ** operations fails, the return code is set, but the contents
6458 ** of the parent page are still manipulated by thh code below.
6459 ** That is Ok, at this point the parent page is guaranteed to
6460 ** be marked as dirty. Returning an error code will cause a
6461 ** rollback, undoing any changes made to the parent page.
6462 */
6463 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00006464 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
6465 if( szCell>pNew->minLocal ){
6466 ptrmapPutOvflPtr(pNew, pCell, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006467 }
6468 }
danielk1977eaa06f62008-09-18 17:34:44 +00006469
danielk19776f235cc2009-06-04 14:46:08 +00006470 /* Create a divider cell to insert into pParent. The divider cell
6471 ** consists of a 4-byte page number (the page number of pPage) and
6472 ** a variable length key value (which must be the same value as the
6473 ** largest key on pPage).
danielk1977eaa06f62008-09-18 17:34:44 +00006474 **
danielk19776f235cc2009-06-04 14:46:08 +00006475 ** To find the largest key value on pPage, first find the right-most
6476 ** cell on pPage. The first two fields of this cell are the
6477 ** record-length (a variable length integer at most 32-bits in size)
6478 ** and the key value (a variable length integer, may have any value).
6479 ** The first of the while(...) loops below skips over the record-length
6480 ** field. The second while(...) loop copies the key value from the
danielk1977a50d9aa2009-06-08 14:49:45 +00006481 ** cell on pPage into the pSpace buffer.
danielk1977eaa06f62008-09-18 17:34:44 +00006482 */
danielk1977eaa06f62008-09-18 17:34:44 +00006483 pCell = findCell(pPage, pPage->nCell-1);
danielk19776f235cc2009-06-04 14:46:08 +00006484 pStop = &pCell[9];
6485 while( (*(pCell++)&0x80) && pCell<pStop );
6486 pStop = &pCell[9];
6487 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
6488
danielk19774dbaa892009-06-16 16:50:22 +00006489 /* Insert the new divider cell into pParent. */
drh98add2e2009-07-20 17:11:49 +00006490 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
6491 0, pPage->pgno, &rc);
danielk19776f235cc2009-06-04 14:46:08 +00006492
6493 /* Set the right-child pointer of pParent to point to the new page. */
danielk1977eaa06f62008-09-18 17:34:44 +00006494 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
6495
danielk1977e08a3c42008-09-18 18:17:03 +00006496 /* Release the reference to the new page. */
6497 releasePage(pNew);
danielk1977ac11ee62005-01-15 12:45:51 +00006498 }
6499
danielk1977eaa06f62008-09-18 17:34:44 +00006500 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00006501}
drh615ae552005-01-16 23:21:00 +00006502#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00006503
dane6593d82014-10-24 16:40:49 +00006504#if 0
drhc3b70572003-01-04 19:44:07 +00006505/*
danielk19774dbaa892009-06-16 16:50:22 +00006506** This function does not contribute anything to the operation of SQLite.
6507** it is sometimes activated temporarily while debugging code responsible
6508** for setting pointer-map entries.
6509*/
6510static int ptrmapCheckPages(MemPage **apPage, int nPage){
6511 int i, j;
6512 for(i=0; i<nPage; i++){
6513 Pgno n;
6514 u8 e;
6515 MemPage *pPage = apPage[i];
6516 BtShared *pBt = pPage->pBt;
6517 assert( pPage->isInit );
6518
6519 for(j=0; j<pPage->nCell; j++){
6520 CellInfo info;
6521 u8 *z;
6522
6523 z = findCell(pPage, j);
danielk197730548662009-07-09 05:07:37 +00006524 btreeParseCellPtr(pPage, z, &info);
danielk19774dbaa892009-06-16 16:50:22 +00006525 if( info.iOverflow ){
6526 Pgno ovfl = get4byte(&z[info.iOverflow]);
6527 ptrmapGet(pBt, ovfl, &e, &n);
6528 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
6529 }
6530 if( !pPage->leaf ){
6531 Pgno child = get4byte(z);
6532 ptrmapGet(pBt, child, &e, &n);
6533 assert( n==pPage->pgno && e==PTRMAP_BTREE );
6534 }
6535 }
6536 if( !pPage->leaf ){
6537 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
6538 ptrmapGet(pBt, child, &e, &n);
6539 assert( n==pPage->pgno && e==PTRMAP_BTREE );
6540 }
6541 }
6542 return 1;
6543}
6544#endif
6545
danielk1977cd581a72009-06-23 15:43:39 +00006546/*
6547** This function is used to copy the contents of the b-tree node stored
6548** on page pFrom to page pTo. If page pFrom was not a leaf page, then
6549** the pointer-map entries for each child page are updated so that the
6550** parent page stored in the pointer map is page pTo. If pFrom contained
6551** any cells with overflow page pointers, then the corresponding pointer
6552** map entries are also updated so that the parent page is page pTo.
6553**
6554** If pFrom is currently carrying any overflow cells (entries in the
drh2cbd78b2012-02-02 19:37:18 +00006555** MemPage.apOvfl[] array), they are not copied to pTo.
danielk1977cd581a72009-06-23 15:43:39 +00006556**
danielk197730548662009-07-09 05:07:37 +00006557** Before returning, page pTo is reinitialized using btreeInitPage().
danielk1977cd581a72009-06-23 15:43:39 +00006558**
6559** The performance of this function is not critical. It is only used by
6560** the balance_shallower() and balance_deeper() procedures, neither of
6561** which are called often under normal circumstances.
6562*/
drhc314dc72009-07-21 11:52:34 +00006563static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
6564 if( (*pRC)==SQLITE_OK ){
6565 BtShared * const pBt = pFrom->pBt;
6566 u8 * const aFrom = pFrom->aData;
6567 u8 * const aTo = pTo->aData;
6568 int const iFromHdr = pFrom->hdrOffset;
6569 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
drhdc9b5f82009-12-05 18:34:08 +00006570 int rc;
drhc314dc72009-07-21 11:52:34 +00006571 int iData;
6572
6573
6574 assert( pFrom->isInit );
6575 assert( pFrom->nFree>=iToHdr );
drhfcd71b62011-04-05 22:08:24 +00006576 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
drhc314dc72009-07-21 11:52:34 +00006577
6578 /* Copy the b-tree node content from page pFrom to page pTo. */
6579 iData = get2byte(&aFrom[iFromHdr+5]);
6580 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
6581 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
6582
6583 /* Reinitialize page pTo so that the contents of the MemPage structure
dan89e060e2009-12-05 18:03:50 +00006584 ** match the new data. The initialization of pTo can actually fail under
6585 ** fairly obscure circumstances, even though it is a copy of initialized
6586 ** page pFrom.
6587 */
drhc314dc72009-07-21 11:52:34 +00006588 pTo->isInit = 0;
dan89e060e2009-12-05 18:03:50 +00006589 rc = btreeInitPage(pTo);
6590 if( rc!=SQLITE_OK ){
6591 *pRC = rc;
6592 return;
6593 }
drhc314dc72009-07-21 11:52:34 +00006594
6595 /* If this is an auto-vacuum database, update the pointer-map entries
6596 ** for any b-tree or overflow pages that pTo now contains the pointers to.
6597 */
6598 if( ISAUTOVACUUM ){
6599 *pRC = setChildPtrmaps(pTo);
6600 }
danielk1977cd581a72009-06-23 15:43:39 +00006601 }
danielk1977cd581a72009-06-23 15:43:39 +00006602}
6603
6604/*
danielk19774dbaa892009-06-16 16:50:22 +00006605** This routine redistributes cells on the iParentIdx'th child of pParent
6606** (hereafter "the page") and up to 2 siblings so that all pages have about the
6607** same amount of free space. Usually a single sibling on either side of the
6608** page are used in the balancing, though both siblings might come from one
6609** side if the page is the first or last child of its parent. If the page
6610** has fewer than 2 siblings (something which can only happen if the page
6611** is a root page or a child of a root page) then all available siblings
6612** participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00006613**
danielk19774dbaa892009-06-16 16:50:22 +00006614** The number of siblings of the page might be increased or decreased by
6615** one or two in an effort to keep pages nearly full but not over full.
drh14acc042001-06-10 19:56:58 +00006616**
danielk19774dbaa892009-06-16 16:50:22 +00006617** Note that when this routine is called, some of the cells on the page
6618** might not actually be stored in MemPage.aData[]. This can happen
6619** if the page is overfull. This routine ensures that all cells allocated
6620** to the page and its siblings fit into MemPage.aData[] before returning.
drh14acc042001-06-10 19:56:58 +00006621**
danielk19774dbaa892009-06-16 16:50:22 +00006622** In the course of balancing the page and its siblings, cells may be
6623** inserted into or removed from the parent page (pParent). Doing so
6624** may cause the parent page to become overfull or underfull. If this
6625** happens, it is the responsibility of the caller to invoke the correct
6626** balancing routine to fix this problem (see the balance() routine).
drh8c42ca92001-06-22 19:15:00 +00006627**
drh5e00f6c2001-09-13 13:46:56 +00006628** If this routine fails for any reason, it might leave the database
danielk19776067a9b2009-06-09 09:41:00 +00006629** in a corrupted state. So if this routine fails, the database should
drh5e00f6c2001-09-13 13:46:56 +00006630** be rolled back.
danielk19774dbaa892009-06-16 16:50:22 +00006631**
6632** The third argument to this function, aOvflSpace, is a pointer to a
drhcd09c532009-07-20 19:30:00 +00006633** buffer big enough to hold one page. If while inserting cells into the parent
6634** page (pParent) the parent page becomes overfull, this buffer is
6635** used to store the parent's overflow cells. Because this function inserts
danielk19774dbaa892009-06-16 16:50:22 +00006636** a maximum of four divider cells into the parent page, and the maximum
6637** size of a cell stored within an internal node is always less than 1/4
6638** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
6639** enough for all overflow cells.
6640**
6641** If aOvflSpace is set to a null pointer, this function returns
6642** SQLITE_NOMEM.
drh8b2f49b2001-06-08 00:21:52 +00006643*/
mistachkine7c54162012-10-02 22:54:27 +00006644#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
6645#pragma optimize("", off)
6646#endif
danielk19774dbaa892009-06-16 16:50:22 +00006647static int balance_nonroot(
6648 MemPage *pParent, /* Parent page of siblings being balanced */
6649 int iParentIdx, /* Index of "the page" in pParent */
danielk1977cd581a72009-06-23 15:43:39 +00006650 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
dan428c2182012-08-06 18:50:11 +00006651 int isRoot, /* True if pParent is a root-page */
6652 int bBulk /* True if this call is part of a bulk load */
danielk19774dbaa892009-06-16 16:50:22 +00006653){
drh16a9b832007-05-05 18:39:25 +00006654 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00006655 int nCell = 0; /* Number of cells in apCell[] */
6656 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
danielk1977a4124bd2008-12-23 10:37:47 +00006657 int nNew = 0; /* Number of pages in apNew[] */
danielk19774dbaa892009-06-16 16:50:22 +00006658 int nOld; /* Number of pages in apOld[] */
drh14acc042001-06-10 19:56:58 +00006659 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00006660 int nxDiv; /* Next divider slot in pParent->aCell[] */
shane85095702009-06-15 16:27:08 +00006661 int rc = SQLITE_OK; /* The return code */
shane36840fd2009-06-26 16:32:13 +00006662 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00006663 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00006664 int usableSpace; /* Bytes in pPage beyond the header */
6665 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00006666 int subtotal; /* Subtotal of bytes in cells on one page */
drhe5ae5732008-06-15 02:51:47 +00006667 int iSpace1 = 0; /* First unused byte of aSpace1[] */
danielk19776067a9b2009-06-09 09:41:00 +00006668 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
drhfacf0302008-06-17 15:12:00 +00006669 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00006670 MemPage *apOld[NB]; /* pPage and up to two siblings */
drha2fce642004-06-05 00:01:44 +00006671 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
danielk19774dbaa892009-06-16 16:50:22 +00006672 u8 *pRight; /* Location in parent of right-sibling pointer */
6673 u8 *apDiv[NB-1]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00006674 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
dan09c68402014-10-11 20:00:24 +00006675 int cntOld[NB+2]; /* Old index in aCell[] after i-th page */
drh2a0df922014-10-30 23:14:56 +00006676 int szNew[NB+2]; /* Combined size of cells placed on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00006677 u8 **apCell = 0; /* All cells begin balanced */
drha9121e42008-02-19 14:59:35 +00006678 u16 *szCell; /* Local size of all cells in apCell[] */
danielk19774dbaa892009-06-16 16:50:22 +00006679 u8 *aSpace1; /* Space for copies of dividers cells */
6680 Pgno pgno; /* Temp var to store a page number in */
dane6593d82014-10-24 16:40:49 +00006681 u8 abDone[NB+2]; /* True after i'th new page is populated */
6682 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
drh00fe08a2014-10-31 00:05:23 +00006683 Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
dane6593d82014-10-24 16:40:49 +00006684 u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
dan33ea4862014-10-09 19:35:37 +00006685
6686 memset(abDone, 0, sizeof(abDone));
danielk1977a50d9aa2009-06-08 14:49:45 +00006687 pBt = pParent->pBt;
6688 assert( sqlite3_mutex_held(pBt->mutex) );
6689 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977474b7cc2008-07-09 11:49:46 +00006690
danielk1977e5765212009-06-17 11:13:28 +00006691#if 0
drh43605152004-05-29 21:46:49 +00006692 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
danielk1977e5765212009-06-17 11:13:28 +00006693#endif
drh2e38c322004-09-03 18:38:44 +00006694
danielk19774dbaa892009-06-16 16:50:22 +00006695 /* At this point pParent may have at most one overflow cell. And if
6696 ** this overflow cell is present, it must be the cell with
6697 ** index iParentIdx. This scenario comes about when this function
drhcd09c532009-07-20 19:30:00 +00006698 ** is called (indirectly) from sqlite3BtreeDelete().
6699 */
danielk19774dbaa892009-06-16 16:50:22 +00006700 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
drh2cbd78b2012-02-02 19:37:18 +00006701 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
danielk19774dbaa892009-06-16 16:50:22 +00006702
danielk197711a8a862009-06-17 11:49:52 +00006703 if( !aOvflSpace ){
6704 return SQLITE_NOMEM;
6705 }
6706
danielk1977a50d9aa2009-06-08 14:49:45 +00006707 /* Find the sibling pages to balance. Also locate the cells in pParent
6708 ** that divide the siblings. An attempt is made to find NN siblings on
6709 ** either side of pPage. More siblings are taken from one side, however,
6710 ** if there are fewer than NN siblings on the other side. If pParent
danielk19774dbaa892009-06-16 16:50:22 +00006711 ** has NB or fewer children then all children of pParent are taken.
6712 **
6713 ** This loop also drops the divider cells from the parent page. This
6714 ** way, the remainder of the function does not have to deal with any
drhcd09c532009-07-20 19:30:00 +00006715 ** overflow cells in the parent page, since if any existed they will
6716 ** have already been removed.
6717 */
danielk19774dbaa892009-06-16 16:50:22 +00006718 i = pParent->nOverflow + pParent->nCell;
6719 if( i<2 ){
drhc3b70572003-01-04 19:44:07 +00006720 nxDiv = 0;
danielk19774dbaa892009-06-16 16:50:22 +00006721 }else{
dan7d6885a2012-08-08 14:04:56 +00006722 assert( bBulk==0 || bBulk==1 );
danielk19774dbaa892009-06-16 16:50:22 +00006723 if( iParentIdx==0 ){
6724 nxDiv = 0;
6725 }else if( iParentIdx==i ){
dan7d6885a2012-08-08 14:04:56 +00006726 nxDiv = i-2+bBulk;
drh14acc042001-06-10 19:56:58 +00006727 }else{
dan7d6885a2012-08-08 14:04:56 +00006728 assert( bBulk==0 );
danielk19774dbaa892009-06-16 16:50:22 +00006729 nxDiv = iParentIdx-1;
drh8b2f49b2001-06-08 00:21:52 +00006730 }
dan7d6885a2012-08-08 14:04:56 +00006731 i = 2-bBulk;
danielk19774dbaa892009-06-16 16:50:22 +00006732 }
dan7d6885a2012-08-08 14:04:56 +00006733 nOld = i+1;
danielk19774dbaa892009-06-16 16:50:22 +00006734 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
6735 pRight = &pParent->aData[pParent->hdrOffset+8];
6736 }else{
6737 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
6738 }
6739 pgno = get4byte(pRight);
6740 while( 1 ){
dan11dcd112013-03-15 18:29:18 +00006741 rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
danielk19774dbaa892009-06-16 16:50:22 +00006742 if( rc ){
danielk197789bc4bc2009-07-21 19:25:24 +00006743 memset(apOld, 0, (i+1)*sizeof(MemPage*));
danielk19774dbaa892009-06-16 16:50:22 +00006744 goto balance_cleanup;
6745 }
danielk1977634f2982005-03-28 08:44:07 +00006746 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
danielk19774dbaa892009-06-16 16:50:22 +00006747 if( (i--)==0 ) break;
6748
drh2cbd78b2012-02-02 19:37:18 +00006749 if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
6750 apDiv[i] = pParent->apOvfl[0];
danielk19774dbaa892009-06-16 16:50:22 +00006751 pgno = get4byte(apDiv[i]);
6752 szNew[i] = cellSizePtr(pParent, apDiv[i]);
6753 pParent->nOverflow = 0;
6754 }else{
6755 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
6756 pgno = get4byte(apDiv[i]);
6757 szNew[i] = cellSizePtr(pParent, apDiv[i]);
6758
6759 /* Drop the cell from the parent page. apDiv[i] still points to
6760 ** the cell within the parent, even though it has been dropped.
6761 ** This is safe because dropping a cell only overwrites the first
6762 ** four bytes of it, and this function does not need the first
6763 ** four bytes of the divider cell. So the pointer is safe to use
danielk197711a8a862009-06-17 11:49:52 +00006764 ** later on.
6765 **
drh8a575d92011-10-12 17:00:28 +00006766 ** But not if we are in secure-delete mode. In secure-delete mode,
danielk197711a8a862009-06-17 11:49:52 +00006767 ** the dropCell() routine will overwrite the entire cell with zeroes.
6768 ** In this case, temporarily copy the cell into the aOvflSpace[]
6769 ** buffer. It will be copied out again as soon as the aSpace[] buffer
6770 ** is allocated. */
drhc9166342012-01-05 23:32:06 +00006771 if( pBt->btsFlags & BTS_SECURE_DELETE ){
drh8a575d92011-10-12 17:00:28 +00006772 int iOff;
6773
6774 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
drh43b18e12010-08-17 19:40:08 +00006775 if( (iOff+szNew[i])>(int)pBt->usableSize ){
dan2ed11e72010-02-26 15:09:19 +00006776 rc = SQLITE_CORRUPT_BKPT;
6777 memset(apOld, 0, (i+1)*sizeof(MemPage*));
6778 goto balance_cleanup;
6779 }else{
6780 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
6781 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
6782 }
drh5b47efa2010-02-12 18:18:39 +00006783 }
drh98add2e2009-07-20 17:11:49 +00006784 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006785 }
drh8b2f49b2001-06-08 00:21:52 +00006786 }
6787
drha9121e42008-02-19 14:59:35 +00006788 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00006789 ** alignment */
drha9121e42008-02-19 14:59:35 +00006790 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00006791
drh8b2f49b2001-06-08 00:21:52 +00006792 /*
danielk1977634f2982005-03-28 08:44:07 +00006793 ** Allocate space for memory structures
6794 */
drhfacf0302008-06-17 15:12:00 +00006795 szScratch =
drha9121e42008-02-19 14:59:35 +00006796 nMaxCells*sizeof(u8*) /* apCell */
6797 + nMaxCells*sizeof(u16) /* szCell */
dan33ea4862014-10-09 19:35:37 +00006798 + pBt->pageSize; /* aSpace1 */
drh5279d342014-11-04 13:41:32 +00006799
drhcbd55b02014-11-04 14:22:27 +00006800 /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
6801 ** that is more than 6 times the database page size. */
mistachkin0fbd7352014-12-09 04:26:56 +00006802 assert( szScratch<=6*(int)pBt->pageSize );
drhfacf0302008-06-17 15:12:00 +00006803 apCell = sqlite3ScratchMalloc( szScratch );
danielk197711a8a862009-06-17 11:49:52 +00006804 if( apCell==0 ){
danielk1977634f2982005-03-28 08:44:07 +00006805 rc = SQLITE_NOMEM;
6806 goto balance_cleanup;
6807 }
drha9121e42008-02-19 14:59:35 +00006808 szCell = (u16*)&apCell[nMaxCells];
danielk19774dbaa892009-06-16 16:50:22 +00006809 aSpace1 = (u8*)&szCell[nMaxCells];
drhea598cb2009-04-05 12:22:08 +00006810 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
drh14acc042001-06-10 19:56:58 +00006811
6812 /*
6813 ** Load pointers to all cells on sibling pages and the divider cells
6814 ** into the local apCell[] array. Make copies of the divider cells
dan33ea4862014-10-09 19:35:37 +00006815 ** into space obtained from aSpace1[]. The divider cells have already
6816 ** been removed from pParent.
drh4b70f112004-05-02 21:12:19 +00006817 **
6818 ** If the siblings are on leaf pages, then the child pointers of the
6819 ** divider cells are stripped from the cells before they are copied
drhe5ae5732008-06-15 02:51:47 +00006820 ** into aSpace1[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00006821 ** child pointers. If siblings are not leaves, then all cell in
6822 ** apCell[] include child pointers. Either way, all cells in apCell[]
6823 ** are alike.
drh96f5b762004-05-16 16:24:36 +00006824 **
6825 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
6826 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00006827 */
danielk1977a50d9aa2009-06-08 14:49:45 +00006828 leafCorrection = apOld[0]->leaf*4;
drh3e28ff52014-09-24 00:59:08 +00006829 leafData = apOld[0]->intKeyLeaf;
drh8b2f49b2001-06-08 00:21:52 +00006830 for(i=0; i<nOld; i++){
danielk19774dbaa892009-06-16 16:50:22 +00006831 int limit;
dan33ea4862014-10-09 19:35:37 +00006832 MemPage *pOld = apOld[i];
danielk19774dbaa892009-06-16 16:50:22 +00006833
6834 limit = pOld->nCell+pOld->nOverflow;
drh68f2a572011-06-03 17:50:49 +00006835 if( pOld->nOverflow>0 ){
6836 for(j=0; j<limit; j++){
6837 assert( nCell<nMaxCells );
6838 apCell[nCell] = findOverflowCell(pOld, j);
6839 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
6840 nCell++;
6841 }
6842 }else{
6843 u8 *aData = pOld->aData;
6844 u16 maskPage = pOld->maskPage;
6845 u16 cellOffset = pOld->cellOffset;
6846 for(j=0; j<limit; j++){
6847 assert( nCell<nMaxCells );
6848 apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
6849 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
6850 nCell++;
6851 }
6852 }
dan09c68402014-10-11 20:00:24 +00006853 cntOld[i] = nCell;
danielk19774dbaa892009-06-16 16:50:22 +00006854 if( i<nOld-1 && !leafData){
shane36840fd2009-06-26 16:32:13 +00006855 u16 sz = (u16)szNew[i];
danielk19774dbaa892009-06-16 16:50:22 +00006856 u8 *pTemp;
6857 assert( nCell<nMaxCells );
6858 szCell[nCell] = sz;
6859 pTemp = &aSpace1[iSpace1];
6860 iSpace1 += sz;
drhe22e03e2010-08-18 21:19:03 +00006861 assert( sz<=pBt->maxLocal+23 );
drhfcd71b62011-04-05 22:08:24 +00006862 assert( iSpace1 <= (int)pBt->pageSize );
danielk19774dbaa892009-06-16 16:50:22 +00006863 memcpy(pTemp, apDiv[i], sz);
6864 apCell[nCell] = pTemp+leafCorrection;
6865 assert( leafCorrection==0 || leafCorrection==4 );
shane36840fd2009-06-26 16:32:13 +00006866 szCell[nCell] = szCell[nCell] - leafCorrection;
danielk19774dbaa892009-06-16 16:50:22 +00006867 if( !pOld->leaf ){
6868 assert( leafCorrection==0 );
6869 assert( pOld->hdrOffset==0 );
6870 /* The right pointer of the child page pOld becomes the left
6871 ** pointer of the divider cell */
6872 memcpy(apCell[nCell], &pOld->aData[8], 4);
6873 }else{
6874 assert( leafCorrection==4 );
6875 if( szCell[nCell]<4 ){
dan8f1eb8a2014-12-06 14:56:49 +00006876 /* Do not allow any cells smaller than 4 bytes. If a smaller cell
6877 ** does exist, pad it with 0x00 bytes. */
6878 assert( szCell[nCell]==3 );
danee7172f2014-12-24 18:11:50 +00006879 assert( apCell[nCell]==&aSpace1[iSpace1-3] );
6880 aSpace1[iSpace1++] = 0x00;
danielk19774dbaa892009-06-16 16:50:22 +00006881 szCell[nCell] = 4;
danielk1977ac11ee62005-01-15 12:45:51 +00006882 }
6883 }
drh14acc042001-06-10 19:56:58 +00006884 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00006885 }
drh8b2f49b2001-06-08 00:21:52 +00006886 }
6887
6888 /*
drh6019e162001-07-02 17:51:45 +00006889 ** Figure out the number of pages needed to hold all nCell cells.
6890 ** Store this number in "k". Also compute szNew[] which is the total
6891 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00006892 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00006893 ** cntNew[k] should equal nCell.
6894 **
drh96f5b762004-05-16 16:24:36 +00006895 ** Values computed by this block:
6896 **
6897 ** k: The total number of sibling pages
6898 ** szNew[i]: Spaced used on the i-th sibling page.
6899 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
6900 ** the right of the i-th sibling page.
6901 ** usableSpace: Number of bytes of space available on each sibling.
6902 **
drh8b2f49b2001-06-08 00:21:52 +00006903 */
drh43605152004-05-29 21:46:49 +00006904 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00006905 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00006906 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00006907 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00006908 if( subtotal > usableSpace ){
dand7b545b2014-10-13 18:03:27 +00006909 szNew[k] = subtotal - szCell[i] - 2;
drh6019e162001-07-02 17:51:45 +00006910 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00006911 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00006912 subtotal = 0;
6913 k++;
drh9978c972010-02-23 17:36:32 +00006914 if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
drh6019e162001-07-02 17:51:45 +00006915 }
6916 }
6917 szNew[k] = subtotal;
6918 cntNew[k] = nCell;
6919 k++;
drh96f5b762004-05-16 16:24:36 +00006920
6921 /*
6922 ** The packing computed by the previous block is biased toward the siblings
drh2a0df922014-10-30 23:14:56 +00006923 ** on the left side (siblings with smaller keys). The left siblings are
6924 ** always nearly full, while the right-most sibling might be nearly empty.
6925 ** The next block of code attempts to adjust the packing of siblings to
6926 ** get a better balance.
drh96f5b762004-05-16 16:24:36 +00006927 **
6928 ** This adjustment is more than an optimization. The packing above might
6929 ** be so out of balance as to be illegal. For example, the right-most
6930 ** sibling might be completely empty. This adjustment is not optional.
6931 */
drh6019e162001-07-02 17:51:45 +00006932 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00006933 int szRight = szNew[i]; /* Size of sibling on the right */
6934 int szLeft = szNew[i-1]; /* Size of sibling on the left */
6935 int r; /* Index of right-most cell in left sibling */
6936 int d; /* Index of first cell to the left of right sibling */
6937
6938 r = cntNew[i-1] - 1;
6939 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00006940 assert( d<nMaxCells );
6941 assert( r<nMaxCells );
danf64cc492012-08-08 11:55:15 +00006942 while( szRight==0
6943 || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
6944 ){
drh43605152004-05-29 21:46:49 +00006945 szRight += szCell[d] + 2;
6946 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00006947 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00006948 r = cntNew[i-1] - 1;
6949 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00006950 }
drh96f5b762004-05-16 16:24:36 +00006951 szNew[i] = szRight;
6952 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00006953 }
drh09d0deb2005-08-02 17:13:09 +00006954
drh2a0df922014-10-30 23:14:56 +00006955 /* Sanity check: For a non-corrupt database file one of the follwing
6956 ** must be true:
6957 ** (1) We found one or more cells (cntNew[0])>0), or
6958 ** (2) pPage is a virtual root page. A virtual root page is when
6959 ** the real root page is page 1 and we are the only child of
6960 ** that page.
drh09d0deb2005-08-02 17:13:09 +00006961 */
drh2a0df922014-10-30 23:14:56 +00006962 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
dan33ea4862014-10-09 19:35:37 +00006963 TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
6964 apOld[0]->pgno, apOld[0]->nCell,
6965 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
6966 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
danielk1977e5765212009-06-17 11:13:28 +00006967 ));
6968
drh8b2f49b2001-06-08 00:21:52 +00006969 /*
drh6b308672002-07-08 02:16:37 +00006970 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00006971 */
drheac74422009-06-14 12:47:11 +00006972 if( apOld[0]->pgno<=1 ){
drh9978c972010-02-23 17:36:32 +00006973 rc = SQLITE_CORRUPT_BKPT;
drheac74422009-06-14 12:47:11 +00006974 goto balance_cleanup;
6975 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006976 pageFlags = apOld[0]->aData[0];
drh14acc042001-06-10 19:56:58 +00006977 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00006978 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00006979 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00006980 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00006981 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00006982 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00006983 nNew++;
danielk197728129562005-01-11 10:25:06 +00006984 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00006985 }else{
drh7aa8f852006-03-28 00:24:44 +00006986 assert( i>0 );
dan428c2182012-08-06 18:50:11 +00006987 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
drh6b308672002-07-08 02:16:37 +00006988 if( rc ) goto balance_cleanup;
dan33ea4862014-10-09 19:35:37 +00006989 zeroPage(pNew, pageFlags);
drhda200cc2004-05-09 11:51:38 +00006990 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00006991 nNew++;
dan09c68402014-10-11 20:00:24 +00006992 cntOld[i] = nCell;
danielk19774dbaa892009-06-16 16:50:22 +00006993
6994 /* Set the pointer-map entry for the new sibling page. */
6995 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00006996 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006997 if( rc!=SQLITE_OK ){
6998 goto balance_cleanup;
6999 }
7000 }
drh6b308672002-07-08 02:16:37 +00007001 }
drh8b2f49b2001-06-08 00:21:52 +00007002 }
7003
7004 /*
dan33ea4862014-10-09 19:35:37 +00007005 ** Reassign page numbers so that the new pages are in ascending order.
7006 ** This helps to keep entries in the disk file in order so that a scan
7007 ** of the table is closer to a linear scan through the file. That in turn
7008 ** helps the operating system to deliver pages from the disk more rapidly.
drhf9ffac92002-03-02 19:00:31 +00007009 **
dan33ea4862014-10-09 19:35:37 +00007010 ** An O(n^2) insertion sort algorithm is used, but since n is never more
7011 ** than (NB+2) (a small constant), that should not be a problem.
drhf9ffac92002-03-02 19:00:31 +00007012 **
dan33ea4862014-10-09 19:35:37 +00007013 ** When NB==3, this one optimization makes the database about 25% faster
7014 ** for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00007015 */
dan33ea4862014-10-09 19:35:37 +00007016 for(i=0; i<nNew; i++){
drh00fe08a2014-10-31 00:05:23 +00007017 aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
dan33ea4862014-10-09 19:35:37 +00007018 aPgFlags[i] = apNew[i]->pDbPage->flags;
dan89ca0b32014-10-25 20:36:28 +00007019 for(j=0; j<i; j++){
7020 if( aPgno[j]==aPgno[i] ){
7021 /* This branch is taken if the set of sibling pages somehow contains
7022 ** duplicate entries. This can happen if the database is corrupt.
7023 ** It would be simpler to detect this as part of the loop below, but
drhba0f9992014-10-30 20:48:44 +00007024 ** we do the detection here in order to avoid populating the pager
7025 ** cache with two separate objects associated with the same
7026 ** page number. */
dan89ca0b32014-10-25 20:36:28 +00007027 assert( CORRUPT_DB );
7028 rc = SQLITE_CORRUPT_BKPT;
7029 goto balance_cleanup;
7030 }
7031 }
dan33ea4862014-10-09 19:35:37 +00007032 }
7033 for(i=0; i<nNew; i++){
dan31f4e992014-10-24 20:57:03 +00007034 int iBest = 0; /* aPgno[] index of page number to use */
dan31f4e992014-10-24 20:57:03 +00007035 for(j=1; j<nNew; j++){
drh00fe08a2014-10-31 00:05:23 +00007036 if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
drhf9ffac92002-03-02 19:00:31 +00007037 }
drh00fe08a2014-10-31 00:05:23 +00007038 pgno = aPgOrder[iBest];
7039 aPgOrder[iBest] = 0xffffffff;
dan31f4e992014-10-24 20:57:03 +00007040 if( iBest!=i ){
7041 if( iBest>i ){
7042 sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
7043 }
7044 sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
7045 apNew[i]->pgno = pgno;
drhf9ffac92002-03-02 19:00:31 +00007046 }
7047 }
dan33ea4862014-10-09 19:35:37 +00007048
7049 TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
7050 "%d(%d nc=%d) %d(%d nc=%d)\n",
7051 apNew[0]->pgno, szNew[0], cntNew[0],
danielk19774dbaa892009-06-16 16:50:22 +00007052 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
dan33ea4862014-10-09 19:35:37 +00007053 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
danielk19774dbaa892009-06-16 16:50:22 +00007054 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
dan33ea4862014-10-09 19:35:37 +00007055 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
danielk19774dbaa892009-06-16 16:50:22 +00007056 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
dan33ea4862014-10-09 19:35:37 +00007057 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
7058 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
7059 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
7060 ));
danielk19774dbaa892009-06-16 16:50:22 +00007061
7062 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7063 put4byte(pRight, apNew[nNew-1]->pgno);
drh24cd67e2004-05-10 16:18:47 +00007064
dan33ea4862014-10-09 19:35:37 +00007065 /* If the sibling pages are not leaves, ensure that the right-child pointer
7066 ** of the right-most new sibling page is set to the value that was
7067 ** originally in the same field of the right-most old sibling page. */
7068 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
7069 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
7070 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
7071 }
danielk1977ac11ee62005-01-15 12:45:51 +00007072
dan33ea4862014-10-09 19:35:37 +00007073 /* Make any required updates to pointer map entries associated with
7074 ** cells stored on sibling pages following the balance operation. Pointer
7075 ** map entries associated with divider cells are set by the insertCell()
7076 ** routine. The associated pointer map entries are:
7077 **
7078 ** a) if the cell contains a reference to an overflow chain, the
7079 ** entry associated with the first page in the overflow chain, and
7080 **
7081 ** b) if the sibling pages are not leaves, the child page associated
7082 ** with the cell.
7083 **
7084 ** If the sibling pages are not leaves, then the pointer map entry
7085 ** associated with the right-child of each sibling may also need to be
7086 ** updated. This happens below, after the sibling pages have been
7087 ** populated, not here.
7088 */
7089 if( ISAUTOVACUUM ){
7090 MemPage *pNew = apNew[0];
7091 u8 *aOld = pNew->aData;
7092 int cntOldNext = pNew->nCell + pNew->nOverflow;
7093 int usableSize = pBt->usableSize;
7094 int iNew = 0;
7095 int iOld = 0;
danielk1977634f2982005-03-28 08:44:07 +00007096
dan33ea4862014-10-09 19:35:37 +00007097 for(i=0; i<nCell; i++){
7098 u8 *pCell = apCell[i];
7099 if( i==cntOldNext ){
7100 MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
7101 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
7102 aOld = pOld->aData;
7103 }
7104 if( i==cntNew[iNew] ){
7105 pNew = apNew[++iNew];
7106 if( !leafData ) continue;
7107 }
7108
7109 /* Cell pCell is destined for new sibling page pNew. Originally, it
drhba0f9992014-10-30 20:48:44 +00007110 ** was either part of sibling page iOld (possibly an overflow cell),
dan33ea4862014-10-09 19:35:37 +00007111 ** or else the divider cell to the left of sibling page iOld. So,
7112 ** if sibling page iOld had the same page number as pNew, and if
7113 ** pCell really was a part of sibling page iOld (not a divider or
7114 ** overflow cell), we can skip updating the pointer map entries. */
drhd52d52b2014-12-06 02:05:44 +00007115 if( iOld>=nNew
7116 || pNew->pgno!=aPgno[iOld]
7117 || pCell<aOld
7118 || pCell>=&aOld[usableSize]
7119 ){
dan33ea4862014-10-09 19:35:37 +00007120 if( !leafCorrection ){
7121 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
7122 }
7123 if( szCell[i]>pNew->minLocal ){
7124 ptrmapPutOvflPtr(pNew, pCell, &rc);
danielk19774aeff622007-05-12 09:30:47 +00007125 }
drh4b70f112004-05-02 21:12:19 +00007126 }
drh14acc042001-06-10 19:56:58 +00007127 }
7128 }
dan33ea4862014-10-09 19:35:37 +00007129
7130 /* Insert new divider cells into pParent. */
7131 for(i=0; i<nNew-1; i++){
7132 u8 *pCell;
7133 u8 *pTemp;
7134 int sz;
7135 MemPage *pNew = apNew[i];
7136 j = cntNew[i];
7137
7138 assert( j<nMaxCells );
7139 pCell = apCell[j];
7140 sz = szCell[j] + leafCorrection;
7141 pTemp = &aOvflSpace[iOvflSpace];
7142 if( !pNew->leaf ){
7143 memcpy(&pNew->aData[8], pCell, 4);
7144 }else if( leafData ){
7145 /* If the tree is a leaf-data tree, and the siblings are leaves,
7146 ** then there is no divider cell in apCell[]. Instead, the divider
7147 ** cell consists of the integer key for the right-most cell of
7148 ** the sibling-page assembled above only.
7149 */
7150 CellInfo info;
7151 j--;
7152 btreeParseCellPtr(pNew, apCell[j], &info);
7153 pCell = pTemp;
7154 sz = 4 + putVarint(&pCell[4], info.nKey);
7155 pTemp = 0;
7156 }else{
7157 pCell -= 4;
7158 /* Obscure case for non-leaf-data trees: If the cell at pCell was
7159 ** previously stored on a leaf node, and its reported size was 4
7160 ** bytes, then it may actually be smaller than this
7161 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
7162 ** any cell). But it is important to pass the correct size to
7163 ** insertCell(), so reparse the cell now.
7164 **
7165 ** Note that this can never happen in an SQLite data file, as all
7166 ** cells are at least 4 bytes. It only happens in b-trees used
7167 ** to evaluate "IN (SELECT ...)" and similar clauses.
7168 */
7169 if( szCell[j]==4 ){
7170 assert(leafCorrection==4);
7171 sz = cellSizePtr(pParent, pCell);
7172 }
7173 }
7174 iOvflSpace += sz;
7175 assert( sz<=pBt->maxLocal+23 );
7176 assert( iOvflSpace <= (int)pBt->pageSize );
7177 insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
7178 if( rc!=SQLITE_OK ) goto balance_cleanup;
7179 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7180 }
7181
7182 /* Now update the actual sibling pages. The order in which they are updated
7183 ** is important, as this code needs to avoid disrupting any page from which
7184 ** cells may still to be read. In practice, this means:
7185 **
drhd836d422014-10-31 14:26:36 +00007186 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
7187 ** then it is not safe to update page apNew[iPg] until after
7188 ** the left-hand sibling apNew[iPg-1] has been updated.
dan33ea4862014-10-09 19:35:37 +00007189 **
drhd836d422014-10-31 14:26:36 +00007190 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
7191 ** then it is not safe to update page apNew[iPg] until after
7192 ** the right-hand sibling apNew[iPg+1] has been updated.
dan33ea4862014-10-09 19:35:37 +00007193 **
7194 ** If neither of the above apply, the page is safe to update.
drhd836d422014-10-31 14:26:36 +00007195 **
7196 ** The iPg value in the following loop starts at nNew-1 goes down
7197 ** to 0, then back up to nNew-1 again, thus making two passes over
7198 ** the pages. On the initial downward pass, only condition (1) above
7199 ** needs to be tested because (2) will always be true from the previous
7200 ** step. On the upward pass, both conditions are always true, so the
7201 ** upwards pass simply processes pages that were missed on the downward
7202 ** pass.
dan33ea4862014-10-09 19:35:37 +00007203 */
drhbec021b2014-10-31 12:22:00 +00007204 for(i=1-nNew; i<nNew; i++){
7205 int iPg = i<0 ? -i : i;
drhbec021b2014-10-31 12:22:00 +00007206 assert( iPg>=0 && iPg<nNew );
drhd836d422014-10-31 14:26:36 +00007207 if( abDone[iPg] ) continue; /* Skip pages already processed */
7208 if( i>=0 /* On the upwards pass, or... */
7209 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
dan33ea4862014-10-09 19:35:37 +00007210 ){
dan09c68402014-10-11 20:00:24 +00007211 int iNew;
7212 int iOld;
7213 int nNewCell;
7214
drhd836d422014-10-31 14:26:36 +00007215 /* Verify condition (1): If cells are moving left, update iPg
7216 ** only after iPg-1 has already been updated. */
7217 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
7218
7219 /* Verify condition (2): If cells are moving right, update iPg
7220 ** only after iPg+1 has already been updated. */
7221 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
7222
dan09c68402014-10-11 20:00:24 +00007223 if( iPg==0 ){
7224 iNew = iOld = 0;
7225 nNewCell = cntNew[0];
7226 }else{
7227 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : nCell;
7228 iNew = cntNew[iPg-1] + !leafData;
7229 nNewCell = cntNew[iPg] - iNew;
7230 }
7231
7232 editPage(apNew[iPg], iOld, iNew, nNewCell, apCell, szCell);
drhd836d422014-10-31 14:26:36 +00007233 abDone[iPg]++;
dand7b545b2014-10-13 18:03:27 +00007234 apNew[iPg]->nFree = usableSpace-szNew[iPg];
dan09c68402014-10-11 20:00:24 +00007235 assert( apNew[iPg]->nOverflow==0 );
7236 assert( apNew[iPg]->nCell==nNewCell );
dan33ea4862014-10-09 19:35:37 +00007237 }
7238 }
drhd836d422014-10-31 14:26:36 +00007239
7240 /* All pages have been processed exactly once */
dan33ea4862014-10-09 19:35:37 +00007241 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
7242
drh7aa8f852006-03-28 00:24:44 +00007243 assert( nOld>0 );
7244 assert( nNew>0 );
drh14acc042001-06-10 19:56:58 +00007245
danielk197713bd99f2009-06-24 05:40:34 +00007246 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
7247 /* The root page of the b-tree now contains no cells. The only sibling
7248 ** page is the right-child of the parent. Copy the contents of the
7249 ** child page into the parent, decreasing the overall height of the
7250 ** b-tree structure by one. This is described as the "balance-shallower"
7251 ** sub-algorithm in some documentation.
7252 **
7253 ** If this is an auto-vacuum database, the call to copyNodeContent()
7254 ** sets all pointer-map entries corresponding to database image pages
7255 ** for which the pointer is stored within the content being copied.
7256 **
drh768f2902014-10-31 02:51:41 +00007257 ** It is critical that the child page be defragmented before being
7258 ** copied into the parent, because if the parent is page 1 then it will
7259 ** by smaller than the child due to the database header, and so all the
7260 ** free space needs to be up front.
7261 */
danielk197713bd99f2009-06-24 05:40:34 +00007262 assert( nNew==1 );
dan89ca0b32014-10-25 20:36:28 +00007263 rc = defragmentPage(apNew[0]);
drh768f2902014-10-31 02:51:41 +00007264 testcase( rc!=SQLITE_OK );
7265 assert( apNew[0]->nFree ==
7266 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
7267 || rc!=SQLITE_OK
7268 );
7269 copyNodeContent(apNew[0], pParent, &rc);
7270 freePage(apNew[0], &rc);
dan33ea4862014-10-09 19:35:37 +00007271 }else if( ISAUTOVACUUM && !leafCorrection ){
7272 /* Fix the pointer map entries associated with the right-child of each
7273 ** sibling page. All other pointer map entries have already been taken
7274 ** care of. */
7275 for(i=0; i<nNew; i++){
7276 u32 key = get4byte(&apNew[i]->aData[8]);
7277 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00007278 }
dan33ea4862014-10-09 19:35:37 +00007279 }
danielk19774dbaa892009-06-16 16:50:22 +00007280
dan33ea4862014-10-09 19:35:37 +00007281 assert( pParent->isInit );
7282 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
7283 nOld, nNew, nCell));
danielk19774dbaa892009-06-16 16:50:22 +00007284
dan33ea4862014-10-09 19:35:37 +00007285 /* Free any old pages that were not reused as new pages.
7286 */
7287 for(i=nNew; i<nOld; i++){
7288 freePage(apOld[i], &rc);
7289 }
7290
dane6593d82014-10-24 16:40:49 +00007291#if 0
dan33ea4862014-10-09 19:35:37 +00007292 if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
danielk19774dbaa892009-06-16 16:50:22 +00007293 /* The ptrmapCheckPages() contains assert() statements that verify that
7294 ** all pointer map pages are set correctly. This is helpful while
7295 ** debugging. This is usually disabled because a corrupt database may
7296 ** cause an assert() statement to fail. */
7297 ptrmapCheckPages(apNew, nNew);
7298 ptrmapCheckPages(&pParent, 1);
danielk19774dbaa892009-06-16 16:50:22 +00007299 }
dan33ea4862014-10-09 19:35:37 +00007300#endif
danielk1977cd581a72009-06-23 15:43:39 +00007301
drh8b2f49b2001-06-08 00:21:52 +00007302 /*
drh14acc042001-06-10 19:56:58 +00007303 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00007304 */
drh14acc042001-06-10 19:56:58 +00007305balance_cleanup:
drhfacf0302008-06-17 15:12:00 +00007306 sqlite3ScratchFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00007307 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00007308 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00007309 }
drh14acc042001-06-10 19:56:58 +00007310 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00007311 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00007312 }
danielk1977eaa06f62008-09-18 17:34:44 +00007313
drh8b2f49b2001-06-08 00:21:52 +00007314 return rc;
7315}
mistachkine7c54162012-10-02 22:54:27 +00007316#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
7317#pragma optimize("", on)
7318#endif
drh8b2f49b2001-06-08 00:21:52 +00007319
drh43605152004-05-29 21:46:49 +00007320
7321/*
danielk1977a50d9aa2009-06-08 14:49:45 +00007322** This function is called when the root page of a b-tree structure is
7323** overfull (has one or more overflow pages).
drh43605152004-05-29 21:46:49 +00007324**
danielk1977a50d9aa2009-06-08 14:49:45 +00007325** A new child page is allocated and the contents of the current root
7326** page, including overflow cells, are copied into the child. The root
7327** page is then overwritten to make it an empty page with the right-child
7328** pointer pointing to the new page.
7329**
7330** Before returning, all pointer-map entries corresponding to pages
7331** that the new child-page now contains pointers to are updated. The
7332** entry corresponding to the new right-child pointer of the root
7333** page is also updated.
7334**
7335** If successful, *ppChild is set to contain a reference to the child
7336** page and SQLITE_OK is returned. In this case the caller is required
7337** to call releasePage() on *ppChild exactly once. If an error occurs,
7338** an error code is returned and *ppChild is set to 0.
drh43605152004-05-29 21:46:49 +00007339*/
danielk1977a50d9aa2009-06-08 14:49:45 +00007340static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
7341 int rc; /* Return value from subprocedures */
7342 MemPage *pChild = 0; /* Pointer to a new child page */
shane5eff7cf2009-08-10 03:57:58 +00007343 Pgno pgnoChild = 0; /* Page number of the new child page */
danielk1977a50d9aa2009-06-08 14:49:45 +00007344 BtShared *pBt = pRoot->pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00007345
danielk1977a50d9aa2009-06-08 14:49:45 +00007346 assert( pRoot->nOverflow>0 );
drh1fee73e2007-08-29 04:00:57 +00007347 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bc2ca9e2008-11-13 14:28:28 +00007348
danielk1977a50d9aa2009-06-08 14:49:45 +00007349 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
7350 ** page that will become the new right-child of pPage. Copy the contents
7351 ** of the node stored on pRoot into the new child page.
7352 */
drh98add2e2009-07-20 17:11:49 +00007353 rc = sqlite3PagerWrite(pRoot->pDbPage);
7354 if( rc==SQLITE_OK ){
7355 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
drhc314dc72009-07-21 11:52:34 +00007356 copyNodeContent(pRoot, pChild, &rc);
7357 if( ISAUTOVACUUM ){
7358 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
drh98add2e2009-07-20 17:11:49 +00007359 }
7360 }
7361 if( rc ){
danielk1977a50d9aa2009-06-08 14:49:45 +00007362 *ppChild = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00007363 releasePage(pChild);
danielk1977a50d9aa2009-06-08 14:49:45 +00007364 return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00007365 }
danielk1977a50d9aa2009-06-08 14:49:45 +00007366 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
7367 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
7368 assert( pChild->nCell==pRoot->nCell );
danielk197771d5d2c2008-09-29 11:49:47 +00007369
danielk1977a50d9aa2009-06-08 14:49:45 +00007370 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
7371
7372 /* Copy the overflow cells from pRoot to pChild */
drh2cbd78b2012-02-02 19:37:18 +00007373 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
7374 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
7375 memcpy(pChild->apOvfl, pRoot->apOvfl,
7376 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
danielk1977a50d9aa2009-06-08 14:49:45 +00007377 pChild->nOverflow = pRoot->nOverflow;
danielk1977a50d9aa2009-06-08 14:49:45 +00007378
7379 /* Zero the contents of pRoot. Then install pChild as the right-child. */
7380 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
7381 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
7382
7383 *ppChild = pChild;
7384 return SQLITE_OK;
drh43605152004-05-29 21:46:49 +00007385}
7386
7387/*
danielk197771d5d2c2008-09-29 11:49:47 +00007388** The page that pCur currently points to has just been modified in
7389** some way. This function figures out if this modification means the
7390** tree needs to be balanced, and if so calls the appropriate balancing
danielk1977a50d9aa2009-06-08 14:49:45 +00007391** routine. Balancing routines are:
7392**
7393** balance_quick()
danielk1977a50d9aa2009-06-08 14:49:45 +00007394** balance_deeper()
7395** balance_nonroot()
drh43605152004-05-29 21:46:49 +00007396*/
danielk1977a50d9aa2009-06-08 14:49:45 +00007397static int balance(BtCursor *pCur){
drh43605152004-05-29 21:46:49 +00007398 int rc = SQLITE_OK;
danielk1977a50d9aa2009-06-08 14:49:45 +00007399 const int nMin = pCur->pBt->usableSize * 2 / 3;
7400 u8 aBalanceQuickSpace[13];
7401 u8 *pFree = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00007402
shane75ac1de2009-06-09 18:58:52 +00007403 TESTONLY( int balance_quick_called = 0 );
7404 TESTONLY( int balance_deeper_called = 0 );
danielk1977a50d9aa2009-06-08 14:49:45 +00007405
7406 do {
7407 int iPage = pCur->iPage;
7408 MemPage *pPage = pCur->apPage[iPage];
7409
7410 if( iPage==0 ){
7411 if( pPage->nOverflow ){
7412 /* The root page of the b-tree is overfull. In this case call the
7413 ** balance_deeper() function to create a new child for the root-page
7414 ** and copy the current contents of the root-page to it. The
7415 ** next iteration of the do-loop will balance the child page.
7416 */
7417 assert( (balance_deeper_called++)==0 );
7418 rc = balance_deeper(pPage, &pCur->apPage[1]);
7419 if( rc==SQLITE_OK ){
7420 pCur->iPage = 1;
7421 pCur->aiIdx[0] = 0;
7422 pCur->aiIdx[1] = 0;
7423 assert( pCur->apPage[1]->nOverflow );
7424 }
danielk1977a50d9aa2009-06-08 14:49:45 +00007425 }else{
danielk1977a50d9aa2009-06-08 14:49:45 +00007426 break;
7427 }
7428 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
7429 break;
7430 }else{
7431 MemPage * const pParent = pCur->apPage[iPage-1];
7432 int const iIdx = pCur->aiIdx[iPage-1];
7433
7434 rc = sqlite3PagerWrite(pParent->pDbPage);
7435 if( rc==SQLITE_OK ){
7436#ifndef SQLITE_OMIT_QUICKBALANCE
drh3e28ff52014-09-24 00:59:08 +00007437 if( pPage->intKeyLeaf
danielk1977a50d9aa2009-06-08 14:49:45 +00007438 && pPage->nOverflow==1
drh2cbd78b2012-02-02 19:37:18 +00007439 && pPage->aiOvfl[0]==pPage->nCell
danielk1977a50d9aa2009-06-08 14:49:45 +00007440 && pParent->pgno!=1
7441 && pParent->nCell==iIdx
7442 ){
7443 /* Call balance_quick() to create a new sibling of pPage on which
7444 ** to store the overflow cell. balance_quick() inserts a new cell
7445 ** into pParent, which may cause pParent overflow. If this
peter.d.reid60ec9142014-09-06 16:39:46 +00007446 ** happens, the next iteration of the do-loop will balance pParent
danielk1977a50d9aa2009-06-08 14:49:45 +00007447 ** use either balance_nonroot() or balance_deeper(). Until this
7448 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
7449 ** buffer.
7450 **
7451 ** The purpose of the following assert() is to check that only a
7452 ** single call to balance_quick() is made for each call to this
7453 ** function. If this were not verified, a subtle bug involving reuse
7454 ** of the aBalanceQuickSpace[] might sneak in.
7455 */
7456 assert( (balance_quick_called++)==0 );
7457 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
7458 }else
7459#endif
7460 {
7461 /* In this case, call balance_nonroot() to redistribute cells
7462 ** between pPage and up to 2 of its sibling pages. This involves
7463 ** modifying the contents of pParent, which may cause pParent to
7464 ** become overfull or underfull. The next iteration of the do-loop
7465 ** will balance the parent page to correct this.
7466 **
7467 ** If the parent page becomes overfull, the overflow cell or cells
7468 ** are stored in the pSpace buffer allocated immediately below.
7469 ** A subsequent iteration of the do-loop will deal with this by
7470 ** calling balance_nonroot() (balance_deeper() may be called first,
7471 ** but it doesn't deal with overflow cells - just moves them to a
7472 ** different page). Once this subsequent call to balance_nonroot()
7473 ** has completed, it is safe to release the pSpace buffer used by
7474 ** the previous call, as the overflow cell data will have been
7475 ** copied either into the body of a database page or into the new
7476 ** pSpace buffer passed to the latter call to balance_nonroot().
7477 */
7478 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
drhe0997b32015-03-20 14:57:50 +00007479 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
7480 pCur->hints&BTREE_BULKLOAD);
danielk1977a50d9aa2009-06-08 14:49:45 +00007481 if( pFree ){
7482 /* If pFree is not NULL, it points to the pSpace buffer used
7483 ** by a previous call to balance_nonroot(). Its contents are
7484 ** now stored either on real database pages or within the
7485 ** new pSpace buffer, so it may be safely freed here. */
7486 sqlite3PageFree(pFree);
7487 }
7488
danielk19774dbaa892009-06-16 16:50:22 +00007489 /* The pSpace buffer will be freed after the next call to
7490 ** balance_nonroot(), or just before this function returns, whichever
7491 ** comes first. */
danielk1977a50d9aa2009-06-08 14:49:45 +00007492 pFree = pSpace;
danielk1977a50d9aa2009-06-08 14:49:45 +00007493 }
7494 }
7495
7496 pPage->nOverflow = 0;
7497
7498 /* The next iteration of the do-loop balances the parent page. */
7499 releasePage(pPage);
7500 pCur->iPage--;
drhcbd33492015-03-25 13:06:54 +00007501 assert( pCur->iPage>=0 );
drh43605152004-05-29 21:46:49 +00007502 }
danielk1977a50d9aa2009-06-08 14:49:45 +00007503 }while( rc==SQLITE_OK );
7504
7505 if( pFree ){
7506 sqlite3PageFree(pFree);
drh43605152004-05-29 21:46:49 +00007507 }
7508 return rc;
7509}
7510
drhf74b8d92002-09-01 23:20:45 +00007511
7512/*
drh3b7511c2001-05-26 13:15:44 +00007513** Insert a new record into the BTree. The key is given by (pKey,nKey)
7514** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00007515** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00007516** is left pointing at a random location.
7517**
7518** For an INTKEY table, only the nKey value of the key is used. pKey is
7519** ignored. For a ZERODATA table, the pData and nData are both ignored.
danielk1977de630352009-05-04 11:42:29 +00007520**
7521** If the seekResult parameter is non-zero, then a successful call to
danielk19773509a652009-07-06 18:56:13 +00007522** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
danielk1977de630352009-05-04 11:42:29 +00007523** been performed. seekResult is the search result returned (a negative
7524** number if pCur points at an entry that is smaller than (pKey, nKey), or
peter.d.reid60ec9142014-09-06 16:39:46 +00007525** a positive value if pCur points at an entry that is larger than
danielk1977de630352009-05-04 11:42:29 +00007526** (pKey, nKey)).
7527**
drh3e9ca092009-09-08 01:14:48 +00007528** If the seekResult parameter is non-zero, then the caller guarantees that
7529** cursor pCur is pointing at the existing copy of a row that is to be
7530** overwritten. If the seekResult parameter is 0, then cursor pCur may
7531** point to any entry or to no entry at all and so this function has to seek
danielk1977de630352009-05-04 11:42:29 +00007532** the cursor before the new key can be inserted.
drh3b7511c2001-05-26 13:15:44 +00007533*/
drh3aac2dd2004-04-26 14:10:20 +00007534int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00007535 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00007536 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00007537 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00007538 int nZero, /* Number of extra 0 bytes to append to data */
danielk1977de630352009-05-04 11:42:29 +00007539 int appendBias, /* True if this is likely an append */
danielk19773509a652009-07-06 18:56:13 +00007540 int seekResult /* Result of prior MovetoUnpacked() call */
drh3b7511c2001-05-26 13:15:44 +00007541){
drh3b7511c2001-05-26 13:15:44 +00007542 int rc;
drh3e9ca092009-09-08 01:14:48 +00007543 int loc = seekResult; /* -1: before desired location +1: after */
drh1d452e12009-11-01 19:26:59 +00007544 int szNew = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00007545 int idx;
drh3b7511c2001-05-26 13:15:44 +00007546 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00007547 Btree *p = pCur->pBtree;
7548 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00007549 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00007550 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00007551
drh98add2e2009-07-20 17:11:49 +00007552 if( pCur->eState==CURSOR_FAULT ){
7553 assert( pCur->skipNext!=SQLITE_OK );
7554 return pCur->skipNext;
7555 }
7556
drh1fee73e2007-08-29 04:00:57 +00007557 assert( cursorHoldsMutex(pCur) );
drh3f387402014-09-24 01:23:00 +00007558 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
7559 && pBt->inTransaction==TRANS_WRITE
drhc9166342012-01-05 23:32:06 +00007560 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk197796d48e92009-06-29 06:00:37 +00007561 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
7562
danielk197731d31b82009-07-13 13:18:07 +00007563 /* Assert that the caller has been consistent. If this cursor was opened
7564 ** expecting an index b-tree, then the caller should be inserting blob
7565 ** keys with no associated data. If the cursor was opened expecting an
7566 ** intkey table, the caller should be inserting integer keys with a
7567 ** blob of associated data. */
7568 assert( (pKey==0)==(pCur->pKeyInfo==0) );
7569
danielk19779c3acf32009-05-02 07:36:49 +00007570 /* Save the positions of any other cursors open on this table.
7571 **
danielk19773509a652009-07-06 18:56:13 +00007572 ** In some cases, the call to btreeMoveto() below is a no-op. For
danielk19779c3acf32009-05-02 07:36:49 +00007573 ** example, when inserting data into a table with auto-generated integer
7574 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
7575 ** integer key to use. It then calls this function to actually insert the
danielk19773509a652009-07-06 18:56:13 +00007576 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
danielk19779c3acf32009-05-02 07:36:49 +00007577 ** that the cursor is already where it needs to be and returns without
7578 ** doing any work. To avoid thwarting these optimizations, it is important
7579 ** not to clear the cursor here.
7580 */
drh4c301aa2009-07-15 17:25:45 +00007581 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
7582 if( rc ) return rc;
drhd60f4f42012-03-23 14:23:52 +00007583
drhd60f4f42012-03-23 14:23:52 +00007584 if( pCur->pKeyInfo==0 ){
drhe0670b62014-02-12 21:31:12 +00007585 /* If this is an insert into a table b-tree, invalidate any incrblob
7586 ** cursors open on the row being replaced */
drhd60f4f42012-03-23 14:23:52 +00007587 invalidateIncrblobCursors(p, nKey, 0);
drhe0670b62014-02-12 21:31:12 +00007588
7589 /* If the cursor is currently on the last row and we are appending a
7590 ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto()
7591 ** call */
drh3f387402014-09-24 01:23:00 +00007592 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
7593 && pCur->info.nKey==nKey-1 ){
drhe0670b62014-02-12 21:31:12 +00007594 loc = -1;
7595 }
drhd60f4f42012-03-23 14:23:52 +00007596 }
7597
drh4c301aa2009-07-15 17:25:45 +00007598 if( !loc ){
7599 rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
7600 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00007601 }
danielk1977b980d2212009-06-22 18:03:51 +00007602 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
danielk1977da184232006-01-05 11:34:32 +00007603
danielk197771d5d2c2008-09-29 11:49:47 +00007604 pPage = pCur->apPage[pCur->iPage];
drh4a1c3802004-05-12 15:15:47 +00007605 assert( pPage->intKey || nKey>=0 );
drh44845222008-07-17 18:39:57 +00007606 assert( pPage->leaf || !pPage->intKey );
danielk19778f880a82009-07-13 09:41:45 +00007607
drh3a4c1412004-05-09 20:40:11 +00007608 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
7609 pCur->pgnoRoot, nKey, nData, pPage->pgno,
7610 loc==0 ? "overwrite" : "new entry"));
danielk197771d5d2c2008-09-29 11:49:47 +00007611 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00007612 newCell = pBt->pTmpSpace;
drh3fbb0222014-09-24 19:47:27 +00007613 assert( newCell!=0 );
drhb026e052007-05-02 01:34:31 +00007614 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00007615 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00007616 assert( szNew==cellSizePtr(pPage, newCell) );
drhfcd71b62011-04-05 22:08:24 +00007617 assert( szNew <= MX_CELL_SIZE(pBt) );
danielk197771d5d2c2008-09-29 11:49:47 +00007618 idx = pCur->aiIdx[pCur->iPage];
danielk1977b980d2212009-06-22 18:03:51 +00007619 if( loc==0 ){
drha9121e42008-02-19 14:59:35 +00007620 u16 szOld;
danielk197771d5d2c2008-09-29 11:49:47 +00007621 assert( idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00007622 rc = sqlite3PagerWrite(pPage->pDbPage);
7623 if( rc ){
7624 goto end_insert;
7625 }
danielk197771d5d2c2008-09-29 11:49:47 +00007626 oldCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00007627 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00007628 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00007629 }
drh9bfdc252014-09-24 02:05:41 +00007630 rc = clearCell(pPage, oldCell, &szOld);
drh98add2e2009-07-20 17:11:49 +00007631 dropCell(pPage, idx, szOld, &rc);
drh2e38c322004-09-03 18:38:44 +00007632 if( rc ) goto end_insert;
drh7c717f72001-06-24 20:39:41 +00007633 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00007634 assert( pPage->leaf );
danielk197771d5d2c2008-09-29 11:49:47 +00007635 idx = ++pCur->aiIdx[pCur->iPage];
drh14acc042001-06-10 19:56:58 +00007636 }else{
drh4b70f112004-05-02 21:12:19 +00007637 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00007638 }
drh98add2e2009-07-20 17:11:49 +00007639 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
danielk19773f632d52009-05-02 10:03:09 +00007640 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
drh9bf9e9c2008-12-05 20:01:43 +00007641
mistachkin48864df2013-03-21 21:20:32 +00007642 /* If no error has occurred and pPage has an overflow cell, call balance()
danielk1977a50d9aa2009-06-08 14:49:45 +00007643 ** to redistribute the cells within the tree. Since balance() may move
drh036dbec2014-03-11 23:40:44 +00007644 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
danielk1977a50d9aa2009-06-08 14:49:45 +00007645 ** variables.
danielk19773f632d52009-05-02 10:03:09 +00007646 **
danielk1977a50d9aa2009-06-08 14:49:45 +00007647 ** Previous versions of SQLite called moveToRoot() to move the cursor
7648 ** back to the root page as balance() used to invalidate the contents
danielk197754109bb2009-06-23 11:22:29 +00007649 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
7650 ** set the cursor state to "invalid". This makes common insert operations
7651 ** slightly faster.
danielk19773f632d52009-05-02 10:03:09 +00007652 **
danielk1977a50d9aa2009-06-08 14:49:45 +00007653 ** There is a subtle but important optimization here too. When inserting
7654 ** multiple records into an intkey b-tree using a single cursor (as can
7655 ** happen while processing an "INSERT INTO ... SELECT" statement), it
7656 ** is advantageous to leave the cursor pointing to the last entry in
7657 ** the b-tree if possible. If the cursor is left pointing to the last
7658 ** entry in the table, and the next row inserted has an integer key
7659 ** larger than the largest existing key, it is possible to insert the
7660 ** row without seeking the cursor. This can be a big performance boost.
danielk19773f632d52009-05-02 10:03:09 +00007661 */
danielk1977a50d9aa2009-06-08 14:49:45 +00007662 pCur->info.nSize = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00007663 if( rc==SQLITE_OK && pPage->nOverflow ){
drh036dbec2014-03-11 23:40:44 +00007664 pCur->curFlags &= ~(BTCF_ValidNKey);
danielk1977a50d9aa2009-06-08 14:49:45 +00007665 rc = balance(pCur);
7666
7667 /* Must make sure nOverflow is reset to zero even if the balance()
danielk197754109bb2009-06-23 11:22:29 +00007668 ** fails. Internal data structure corruption will result otherwise.
7669 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
7670 ** from trying to save the current position of the cursor. */
danielk1977a50d9aa2009-06-08 14:49:45 +00007671 pCur->apPage[pCur->iPage]->nOverflow = 0;
danielk197754109bb2009-06-23 11:22:29 +00007672 pCur->eState = CURSOR_INVALID;
danielk19773f632d52009-05-02 10:03:09 +00007673 }
danielk1977a50d9aa2009-06-08 14:49:45 +00007674 assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
drh9bf9e9c2008-12-05 20:01:43 +00007675
drh2e38c322004-09-03 18:38:44 +00007676end_insert:
drh5e2f8b92001-05-28 00:41:15 +00007677 return rc;
7678}
7679
7680/*
drh4b70f112004-05-02 21:12:19 +00007681** Delete the entry that the cursor is pointing to. The cursor
peter.d.reid60ec9142014-09-06 16:39:46 +00007682** is left pointing at an arbitrary location.
drh3b7511c2001-05-26 13:15:44 +00007683*/
drh3aac2dd2004-04-26 14:10:20 +00007684int sqlite3BtreeDelete(BtCursor *pCur){
drhd677b3d2007-08-20 22:48:41 +00007685 Btree *p = pCur->pBtree;
danielk19774dbaa892009-06-16 16:50:22 +00007686 BtShared *pBt = p->pBt;
7687 int rc; /* Return code */
7688 MemPage *pPage; /* Page to delete cell from */
7689 unsigned char *pCell; /* Pointer to cell to delete */
7690 int iCellIdx; /* Index of cell to delete */
7691 int iCellDepth; /* Depth of node containing pCell */
drh9bfdc252014-09-24 02:05:41 +00007692 u16 szCell; /* Size of the cell being deleted */
drh8b2f49b2001-06-08 00:21:52 +00007693
drh1fee73e2007-08-29 04:00:57 +00007694 assert( cursorHoldsMutex(pCur) );
drh64022502009-01-09 14:11:04 +00007695 assert( pBt->inTransaction==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00007696 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
drh036dbec2014-03-11 23:40:44 +00007697 assert( pCur->curFlags & BTCF_WriteFlag );
danielk197796d48e92009-06-29 06:00:37 +00007698 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
7699 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
7700
danielk19774dbaa892009-06-16 16:50:22 +00007701 if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
7702 || NEVER(pCur->eState!=CURSOR_VALID)
7703 ){
7704 return SQLITE_ERROR; /* Something has gone awry. */
drhf74b8d92002-09-01 23:20:45 +00007705 }
danielk1977da184232006-01-05 11:34:32 +00007706
danielk19774dbaa892009-06-16 16:50:22 +00007707 iCellDepth = pCur->iPage;
7708 iCellIdx = pCur->aiIdx[iCellDepth];
7709 pPage = pCur->apPage[iCellDepth];
7710 pCell = findCell(pPage, iCellIdx);
7711
7712 /* If the page containing the entry to delete is not a leaf page, move
7713 ** the cursor to the largest entry in the tree that is smaller than
7714 ** the entry being deleted. This cell will replace the cell being deleted
7715 ** from the internal node. The 'previous' entry is used for this instead
7716 ** of the 'next' entry, as the previous entry is always a part of the
7717 ** sub-tree headed by the child page of the cell being deleted. This makes
7718 ** balancing the tree following the delete operation easier. */
7719 if( !pPage->leaf ){
drhe39a7322014-02-03 14:04:11 +00007720 int notUsed = 0;
drh4c301aa2009-07-15 17:25:45 +00007721 rc = sqlite3BtreePrevious(pCur, &notUsed);
7722 if( rc ) return rc;
danielk19774dbaa892009-06-16 16:50:22 +00007723 }
7724
7725 /* Save the positions of any other cursors open on this table before
7726 ** making any modifications. Make the page containing the entry to be
7727 ** deleted writable. Then free any overflow pages associated with the
drha4ec1d42009-07-11 13:13:11 +00007728 ** entry and finally remove the cell itself from within the page.
7729 */
7730 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
7731 if( rc ) return rc;
drhd60f4f42012-03-23 14:23:52 +00007732
7733 /* If this is a delete operation to remove a row from a table b-tree,
7734 ** invalidate any incrblob cursors open on the row being deleted. */
7735 if( pCur->pKeyInfo==0 ){
7736 invalidateIncrblobCursors(p, pCur->info.nKey, 0);
7737 }
7738
drha4ec1d42009-07-11 13:13:11 +00007739 rc = sqlite3PagerWrite(pPage->pDbPage);
7740 if( rc ) return rc;
drh9bfdc252014-09-24 02:05:41 +00007741 rc = clearCell(pPage, pCell, &szCell);
7742 dropCell(pPage, iCellIdx, szCell, &rc);
drha4ec1d42009-07-11 13:13:11 +00007743 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00007744
danielk19774dbaa892009-06-16 16:50:22 +00007745 /* If the cell deleted was not located on a leaf page, then the cursor
7746 ** is currently pointing to the largest entry in the sub-tree headed
7747 ** by the child-page of the cell that was just deleted from an internal
7748 ** node. The cell from the leaf node needs to be moved to the internal
7749 ** node to replace the deleted cell. */
drh4b70f112004-05-02 21:12:19 +00007750 if( !pPage->leaf ){
danielk19774dbaa892009-06-16 16:50:22 +00007751 MemPage *pLeaf = pCur->apPage[pCur->iPage];
7752 int nCell;
7753 Pgno n = pCur->apPage[iCellDepth+1]->pgno;
7754 unsigned char *pTmp;
danielk1977e6efa742004-11-10 11:55:10 +00007755
danielk19774dbaa892009-06-16 16:50:22 +00007756 pCell = findCell(pLeaf, pLeaf->nCell-1);
7757 nCell = cellSizePtr(pLeaf, pCell);
drhfcd71b62011-04-05 22:08:24 +00007758 assert( MX_CELL_SIZE(pBt) >= nCell );
danielk19774dbaa892009-06-16 16:50:22 +00007759 pTmp = pBt->pTmpSpace;
drh3fbb0222014-09-24 19:47:27 +00007760 assert( pTmp!=0 );
drha4ec1d42009-07-11 13:13:11 +00007761 rc = sqlite3PagerWrite(pLeaf->pDbPage);
drh98add2e2009-07-20 17:11:49 +00007762 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
7763 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
drha4ec1d42009-07-11 13:13:11 +00007764 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00007765 }
danielk19774dbaa892009-06-16 16:50:22 +00007766
7767 /* Balance the tree. If the entry deleted was located on a leaf page,
7768 ** then the cursor still points to that page. In this case the first
7769 ** call to balance() repairs the tree, and the if(...) condition is
7770 ** never true.
7771 **
7772 ** Otherwise, if the entry deleted was on an internal node page, then
7773 ** pCur is pointing to the leaf page from which a cell was removed to
7774 ** replace the cell deleted from the internal node. This is slightly
7775 ** tricky as the leaf node may be underfull, and the internal node may
7776 ** be either under or overfull. In this case run the balancing algorithm
7777 ** on the leaf node first. If the balance proceeds far enough up the
7778 ** tree that we can be sure that any problem in the internal node has
7779 ** been corrected, so be it. Otherwise, after balancing the leaf node,
7780 ** walk the cursor up the tree to the internal node and balance it as
7781 ** well. */
7782 rc = balance(pCur);
7783 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
7784 while( pCur->iPage>iCellDepth ){
7785 releasePage(pCur->apPage[pCur->iPage--]);
7786 }
7787 rc = balance(pCur);
7788 }
7789
danielk19776b456a22005-03-21 04:04:02 +00007790 if( rc==SQLITE_OK ){
7791 moveToRoot(pCur);
7792 }
drh5e2f8b92001-05-28 00:41:15 +00007793 return rc;
drh3b7511c2001-05-26 13:15:44 +00007794}
drh8b2f49b2001-06-08 00:21:52 +00007795
7796/*
drhc6b52df2002-01-04 03:09:29 +00007797** Create a new BTree table. Write into *piTable the page
7798** number for the root page of the new table.
7799**
drhab01f612004-05-22 02:55:23 +00007800** The type of type is determined by the flags parameter. Only the
7801** following values of flags are currently in use. Other values for
7802** flags might not work:
7803**
7804** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
7805** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00007806*/
drhd4187c72010-08-30 22:15:45 +00007807static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
danielk1977aef0bf62005-12-30 16:28:01 +00007808 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00007809 MemPage *pRoot;
7810 Pgno pgnoRoot;
7811 int rc;
drhd4187c72010-08-30 22:15:45 +00007812 int ptfFlags; /* Page-type flage for the root page of new table */
drhd677b3d2007-08-20 22:48:41 +00007813
drh1fee73e2007-08-29 04:00:57 +00007814 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00007815 assert( pBt->inTransaction==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00007816 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk1977e6efa742004-11-10 11:55:10 +00007817
danielk1977003ba062004-11-04 02:57:33 +00007818#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00007819 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00007820 if( rc ){
7821 return rc;
7822 }
danielk1977003ba062004-11-04 02:57:33 +00007823#else
danielk1977687566d2004-11-02 12:56:41 +00007824 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00007825 Pgno pgnoMove; /* Move a page here to make room for the root-page */
7826 MemPage *pPageMove; /* The page to move to. */
7827
danielk197720713f32007-05-03 11:43:33 +00007828 /* Creating a new table may probably require moving an existing database
7829 ** to make room for the new tables root page. In case this page turns
7830 ** out to be an overflow page, delete all overflow page-map caches
7831 ** held by open cursors.
7832 */
danielk197792d4d7a2007-05-04 12:05:56 +00007833 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00007834
danielk1977003ba062004-11-04 02:57:33 +00007835 /* Read the value of meta[3] from the database to determine where the
7836 ** root page of the new table should go. meta[3] is the largest root-page
7837 ** created so far, so the new root-page is (meta[3]+1).
7838 */
danielk1977602b4662009-07-02 07:47:33 +00007839 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00007840 pgnoRoot++;
7841
danielk1977599fcba2004-11-08 07:13:13 +00007842 /* The new root-page may not be allocated on a pointer-map page, or the
7843 ** PENDING_BYTE page.
7844 */
drh72190432008-01-31 14:54:43 +00007845 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00007846 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00007847 pgnoRoot++;
7848 }
7849 assert( pgnoRoot>=3 );
7850
7851 /* Allocate a page. The page that currently resides at pgnoRoot will
7852 ** be moved to the allocated page (unless the allocated page happens
7853 ** to reside at pgnoRoot).
7854 */
dan51f0b6d2013-02-22 20:16:34 +00007855 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
danielk1977003ba062004-11-04 02:57:33 +00007856 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00007857 return rc;
7858 }
danielk1977003ba062004-11-04 02:57:33 +00007859
7860 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00007861 /* pgnoRoot is the page that will be used for the root-page of
7862 ** the new table (assuming an error did not occur). But we were
7863 ** allocated pgnoMove. If required (i.e. if it was not allocated
7864 ** by extending the file), the current page at position pgnoMove
7865 ** is already journaled.
7866 */
drheeb844a2009-08-08 18:01:07 +00007867 u8 eType = 0;
7868 Pgno iPtrPage = 0;
danielk1977003ba062004-11-04 02:57:33 +00007869
danf7679ad2013-04-03 11:38:36 +00007870 /* Save the positions of any open cursors. This is required in
7871 ** case they are holding a reference to an xFetch reference
7872 ** corresponding to page pgnoRoot. */
7873 rc = saveAllCursors(pBt, 0, 0);
danielk1977003ba062004-11-04 02:57:33 +00007874 releasePage(pPageMove);
danf7679ad2013-04-03 11:38:36 +00007875 if( rc!=SQLITE_OK ){
7876 return rc;
7877 }
danielk1977f35843b2007-04-07 15:03:17 +00007878
7879 /* Move the page currently at pgnoRoot to pgnoMove. */
drhb00fc3b2013-08-21 23:42:32 +00007880 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00007881 if( rc!=SQLITE_OK ){
7882 return rc;
7883 }
7884 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drh27731d72009-06-22 12:05:10 +00007885 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
7886 rc = SQLITE_CORRUPT_BKPT;
7887 }
7888 if( rc!=SQLITE_OK ){
danielk1977003ba062004-11-04 02:57:33 +00007889 releasePage(pRoot);
7890 return rc;
7891 }
drhccae6022005-02-26 17:31:26 +00007892 assert( eType!=PTRMAP_ROOTPAGE );
7893 assert( eType!=PTRMAP_FREEPAGE );
danielk19774c999992008-07-16 18:17:55 +00007894 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +00007895 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00007896
7897 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00007898 if( rc!=SQLITE_OK ){
7899 return rc;
7900 }
drhb00fc3b2013-08-21 23:42:32 +00007901 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00007902 if( rc!=SQLITE_OK ){
7903 return rc;
7904 }
danielk19773b8a05f2007-03-19 17:44:26 +00007905 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00007906 if( rc!=SQLITE_OK ){
7907 releasePage(pRoot);
7908 return rc;
7909 }
7910 }else{
7911 pRoot = pPageMove;
7912 }
7913
danielk197742741be2005-01-08 12:42:39 +00007914 /* Update the pointer-map and meta-data with the new root-page number. */
drh98add2e2009-07-20 17:11:49 +00007915 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
danielk1977003ba062004-11-04 02:57:33 +00007916 if( rc ){
7917 releasePage(pRoot);
7918 return rc;
7919 }
drhbf592832010-03-30 15:51:12 +00007920
7921 /* When the new root page was allocated, page 1 was made writable in
7922 ** order either to increase the database filesize, or to decrement the
7923 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
7924 */
7925 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
danielk1977aef0bf62005-12-30 16:28:01 +00007926 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
drhbf592832010-03-30 15:51:12 +00007927 if( NEVER(rc) ){
danielk1977003ba062004-11-04 02:57:33 +00007928 releasePage(pRoot);
7929 return rc;
7930 }
danielk197742741be2005-01-08 12:42:39 +00007931
danielk1977003ba062004-11-04 02:57:33 +00007932 }else{
drh4f0c5872007-03-26 22:05:01 +00007933 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00007934 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00007935 }
7936#endif
danielk19773b8a05f2007-03-19 17:44:26 +00007937 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhd4187c72010-08-30 22:15:45 +00007938 if( createTabFlags & BTREE_INTKEY ){
7939 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
7940 }else{
7941 ptfFlags = PTF_ZERODATA | PTF_LEAF;
7942 }
7943 zeroPage(pRoot, ptfFlags);
danielk19773b8a05f2007-03-19 17:44:26 +00007944 sqlite3PagerUnref(pRoot->pDbPage);
drhd4187c72010-08-30 22:15:45 +00007945 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
drh8b2f49b2001-06-08 00:21:52 +00007946 *piTable = (int)pgnoRoot;
7947 return SQLITE_OK;
7948}
drhd677b3d2007-08-20 22:48:41 +00007949int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
7950 int rc;
7951 sqlite3BtreeEnter(p);
7952 rc = btreeCreateTable(p, piTable, flags);
7953 sqlite3BtreeLeave(p);
7954 return rc;
7955}
drh8b2f49b2001-06-08 00:21:52 +00007956
7957/*
7958** Erase the given database page and all its children. Return
7959** the page to the freelist.
7960*/
drh4b70f112004-05-02 21:12:19 +00007961static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00007962 BtShared *pBt, /* The BTree that contains the table */
drh7ab641f2009-11-24 02:37:02 +00007963 Pgno pgno, /* Page number to clear */
7964 int freePageFlag, /* Deallocate page if true */
7965 int *pnChange /* Add number of Cells freed to this counter */
drh4b70f112004-05-02 21:12:19 +00007966){
danielk1977146ba992009-07-22 14:08:13 +00007967 MemPage *pPage;
drh8b2f49b2001-06-08 00:21:52 +00007968 int rc;
drh4b70f112004-05-02 21:12:19 +00007969 unsigned char *pCell;
7970 int i;
dan8ce71842014-01-14 20:14:09 +00007971 int hdr;
drh9bfdc252014-09-24 02:05:41 +00007972 u16 szCell;
drh8b2f49b2001-06-08 00:21:52 +00007973
drh1fee73e2007-08-29 04:00:57 +00007974 assert( sqlite3_mutex_held(pBt->mutex) );
drhb1299152010-03-30 22:58:33 +00007975 if( pgno>btreePagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00007976 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00007977 }
7978
dan11dcd112013-03-15 18:29:18 +00007979 rc = getAndInitPage(pBt, pgno, &pPage, 0);
danielk1977146ba992009-07-22 14:08:13 +00007980 if( rc ) return rc;
dan8ce71842014-01-14 20:14:09 +00007981 hdr = pPage->hdrOffset;
drh4b70f112004-05-02 21:12:19 +00007982 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00007983 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00007984 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00007985 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00007986 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00007987 }
drh9bfdc252014-09-24 02:05:41 +00007988 rc = clearCell(pPage, pCell, &szCell);
danielk19776b456a22005-03-21 04:04:02 +00007989 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00007990 }
drha34b6762004-05-07 13:30:42 +00007991 if( !pPage->leaf ){
dan8ce71842014-01-14 20:14:09 +00007992 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00007993 if( rc ) goto cleardatabasepage_out;
danielk1977c7af4842008-10-27 13:59:33 +00007994 }else if( pnChange ){
7995 assert( pPage->intKey );
7996 *pnChange += pPage->nCell;
drh2aa679f2001-06-25 02:11:07 +00007997 }
7998 if( freePageFlag ){
drhc314dc72009-07-21 11:52:34 +00007999 freePage(pPage, &rc);
danielk19773b8a05f2007-03-19 17:44:26 +00008000 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
dan8ce71842014-01-14 20:14:09 +00008001 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00008002 }
danielk19776b456a22005-03-21 04:04:02 +00008003
8004cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00008005 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00008006 return rc;
drh8b2f49b2001-06-08 00:21:52 +00008007}
8008
8009/*
drhab01f612004-05-22 02:55:23 +00008010** Delete all information from a single table in the database. iTable is
8011** the page number of the root of the table. After this routine returns,
8012** the root page is empty, but still exists.
8013**
8014** This routine will fail with SQLITE_LOCKED if there are any open
8015** read cursors on the table. Open write cursors are moved to the
8016** root of the table.
danielk1977c7af4842008-10-27 13:59:33 +00008017**
8018** If pnChange is not NULL, then table iTable must be an intkey table. The
8019** integer value pointed to by pnChange is incremented by the number of
8020** entries in the table.
drh8b2f49b2001-06-08 00:21:52 +00008021*/
danielk1977c7af4842008-10-27 13:59:33 +00008022int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
drh8b2f49b2001-06-08 00:21:52 +00008023 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00008024 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00008025 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00008026 assert( p->inTrans==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +00008027
drhc046e3e2009-07-15 11:26:44 +00008028 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
drhd60f4f42012-03-23 14:23:52 +00008029
drhc046e3e2009-07-15 11:26:44 +00008030 if( SQLITE_OK==rc ){
drhd60f4f42012-03-23 14:23:52 +00008031 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
8032 ** is the root of a table b-tree - if it is not, the following call is
8033 ** a no-op). */
8034 invalidateIncrblobCursors(p, 0, 1);
danielk197762c14b32008-11-19 09:05:26 +00008035 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
drh8b2f49b2001-06-08 00:21:52 +00008036 }
drhd677b3d2007-08-20 22:48:41 +00008037 sqlite3BtreeLeave(p);
8038 return rc;
drh8b2f49b2001-06-08 00:21:52 +00008039}
8040
8041/*
drh079a3072014-03-19 14:10:55 +00008042** Delete all information from the single table that pCur is open on.
8043**
8044** This routine only work for pCur on an ephemeral table.
8045*/
8046int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
8047 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
8048}
8049
8050/*
drh8b2f49b2001-06-08 00:21:52 +00008051** Erase all information in a table and add the root of the table to
8052** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00008053** page 1) is never added to the freelist.
8054**
8055** This routine will fail with SQLITE_LOCKED if there are any open
8056** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00008057**
8058** If AUTOVACUUM is enabled and the page at iTable is not the last
8059** root page in the database file, then the last root page
8060** in the database file is moved into the slot formerly occupied by
8061** iTable and that last slot formerly occupied by the last root page
8062** is added to the freelist instead of iTable. In this say, all
8063** root pages are kept at the beginning of the database file, which
8064** is necessary for AUTOVACUUM to work right. *piMoved is set to the
8065** page number that used to be the last root page in the file before
8066** the move. If no page gets moved, *piMoved is set to 0.
8067** The last root page is recorded in meta[3] and the value of
8068** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00008069*/
danielk197789d40042008-11-17 14:20:56 +00008070static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00008071 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00008072 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00008073 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00008074
drh1fee73e2007-08-29 04:00:57 +00008075 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00008076 assert( p->inTrans==TRANS_WRITE );
danielk1977a0bf2652004-11-04 14:30:04 +00008077
danielk1977e6efa742004-11-10 11:55:10 +00008078 /* It is illegal to drop a table if any cursors are open on the
8079 ** database. This is because in auto-vacuum mode the backend may
8080 ** need to move another root-page to fill a gap left by the deleted
8081 ** root page. If an open cursor was using this page a problem would
8082 ** occur.
drhc046e3e2009-07-15 11:26:44 +00008083 **
8084 ** This error is caught long before control reaches this point.
danielk1977e6efa742004-11-10 11:55:10 +00008085 */
drhc046e3e2009-07-15 11:26:44 +00008086 if( NEVER(pBt->pCursor) ){
danielk1977404ca072009-03-16 13:19:36 +00008087 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
8088 return SQLITE_LOCKED_SHAREDCACHE;
drh5df72a52002-06-06 23:16:05 +00008089 }
danielk1977a0bf2652004-11-04 14:30:04 +00008090
drhb00fc3b2013-08-21 23:42:32 +00008091 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00008092 if( rc ) return rc;
danielk1977c7af4842008-10-27 13:59:33 +00008093 rc = sqlite3BtreeClearTable(p, iTable, 0);
danielk19776b456a22005-03-21 04:04:02 +00008094 if( rc ){
8095 releasePage(pPage);
8096 return rc;
8097 }
danielk1977a0bf2652004-11-04 14:30:04 +00008098
drh205f48e2004-11-05 00:43:11 +00008099 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00008100
drh4b70f112004-05-02 21:12:19 +00008101 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00008102#ifdef SQLITE_OMIT_AUTOVACUUM
drhc314dc72009-07-21 11:52:34 +00008103 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00008104 releasePage(pPage);
8105#else
8106 if( pBt->autoVacuum ){
8107 Pgno maxRootPgno;
danielk1977602b4662009-07-02 07:47:33 +00008108 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00008109
8110 if( iTable==maxRootPgno ){
8111 /* If the table being dropped is the table with the largest root-page
8112 ** number in the database, put the root page on the free list.
8113 */
drhc314dc72009-07-21 11:52:34 +00008114 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00008115 releasePage(pPage);
8116 if( rc!=SQLITE_OK ){
8117 return rc;
8118 }
8119 }else{
8120 /* The table being dropped does not have the largest root-page
8121 ** number in the database. So move the page that does into the
8122 ** gap left by the deleted root-page.
8123 */
8124 MemPage *pMove;
8125 releasePage(pPage);
drhb00fc3b2013-08-21 23:42:32 +00008126 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00008127 if( rc!=SQLITE_OK ){
8128 return rc;
8129 }
danielk19774c999992008-07-16 18:17:55 +00008130 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00008131 releasePage(pMove);
8132 if( rc!=SQLITE_OK ){
8133 return rc;
8134 }
drhfe3313f2009-07-21 19:02:20 +00008135 pMove = 0;
drhb00fc3b2013-08-21 23:42:32 +00008136 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
drhc314dc72009-07-21 11:52:34 +00008137 freePage(pMove, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00008138 releasePage(pMove);
8139 if( rc!=SQLITE_OK ){
8140 return rc;
8141 }
8142 *piMoved = maxRootPgno;
8143 }
8144
danielk1977599fcba2004-11-08 07:13:13 +00008145 /* Set the new 'max-root-page' value in the database header. This
8146 ** is the old value less one, less one more if that happens to
8147 ** be a root-page number, less one again if that is the
8148 ** PENDING_BYTE_PAGE.
8149 */
danielk197787a6e732004-11-05 12:58:25 +00008150 maxRootPgno--;
drhe1849652009-07-15 18:15:22 +00008151 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
8152 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00008153 maxRootPgno--;
8154 }
danielk1977599fcba2004-11-08 07:13:13 +00008155 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
8156
danielk1977aef0bf62005-12-30 16:28:01 +00008157 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00008158 }else{
drhc314dc72009-07-21 11:52:34 +00008159 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00008160 releasePage(pPage);
8161 }
8162#endif
drh2aa679f2001-06-25 02:11:07 +00008163 }else{
drhc046e3e2009-07-15 11:26:44 +00008164 /* If sqlite3BtreeDropTable was called on page 1.
8165 ** This really never should happen except in a corrupt
8166 ** database.
8167 */
drha34b6762004-05-07 13:30:42 +00008168 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00008169 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00008170 }
drh8b2f49b2001-06-08 00:21:52 +00008171 return rc;
8172}
drhd677b3d2007-08-20 22:48:41 +00008173int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
8174 int rc;
8175 sqlite3BtreeEnter(p);
dan7733a4d2011-09-02 18:03:16 +00008176 rc = btreeDropTable(p, iTable, piMoved);
drhd677b3d2007-08-20 22:48:41 +00008177 sqlite3BtreeLeave(p);
8178 return rc;
8179}
drh8b2f49b2001-06-08 00:21:52 +00008180
drh001bbcb2003-03-19 03:14:00 +00008181
drh8b2f49b2001-06-08 00:21:52 +00008182/*
danielk1977602b4662009-07-02 07:47:33 +00008183** This function may only be called if the b-tree connection already
8184** has a read or write transaction open on the database.
8185**
drh23e11ca2004-05-04 17:27:28 +00008186** Read the meta-information out of a database file. Meta[0]
8187** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00008188** through meta[15] are available for use by higher layers. Meta[0]
8189** is read-only, the others are read/write.
8190**
8191** The schema layer numbers meta values differently. At the schema
8192** layer (and the SetCookie and ReadCookie opcodes) the number of
8193** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh91618562014-12-19 19:28:02 +00008194**
8195** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
8196** of reading the value out of the header, it instead loads the "DataVersion"
8197** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
8198** database file. It is a number computed by the pager. But its access
8199** pattern is the same as header meta values, and so it is convenient to
8200** read it from this routine.
drh8b2f49b2001-06-08 00:21:52 +00008201*/
danielk1977602b4662009-07-02 07:47:33 +00008202void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
danielk1977aef0bf62005-12-30 16:28:01 +00008203 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00008204
drhd677b3d2007-08-20 22:48:41 +00008205 sqlite3BtreeEnter(p);
danielk1977602b4662009-07-02 07:47:33 +00008206 assert( p->inTrans>TRANS_NONE );
danielk1977e0d9e6f2009-07-03 16:25:06 +00008207 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
danielk1977602b4662009-07-02 07:47:33 +00008208 assert( pBt->pPage1 );
drh23e11ca2004-05-04 17:27:28 +00008209 assert( idx>=0 && idx<=15 );
danielk1977ea897302008-09-19 15:10:58 +00008210
drh91618562014-12-19 19:28:02 +00008211 if( idx==BTREE_DATA_VERSION ){
drh3da9c042014-12-22 18:41:21 +00008212 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
drh91618562014-12-19 19:28:02 +00008213 }else{
8214 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
8215 }
drhae157872004-08-14 19:20:09 +00008216
danielk1977602b4662009-07-02 07:47:33 +00008217 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
8218 ** database, mark the database as read-only. */
danielk1977003ba062004-11-04 02:57:33 +00008219#ifdef SQLITE_OMIT_AUTOVACUUM
drhc9166342012-01-05 23:32:06 +00008220 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
8221 pBt->btsFlags |= BTS_READ_ONLY;
8222 }
danielk1977003ba062004-11-04 02:57:33 +00008223#endif
drhae157872004-08-14 19:20:09 +00008224
drhd677b3d2007-08-20 22:48:41 +00008225 sqlite3BtreeLeave(p);
drh8b2f49b2001-06-08 00:21:52 +00008226}
8227
8228/*
drh23e11ca2004-05-04 17:27:28 +00008229** Write meta-information back into the database. Meta[0] is
8230** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00008231*/
danielk1977aef0bf62005-12-30 16:28:01 +00008232int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
8233 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00008234 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00008235 int rc;
drh23e11ca2004-05-04 17:27:28 +00008236 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00008237 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00008238 assert( p->inTrans==TRANS_WRITE );
8239 assert( pBt->pPage1!=0 );
8240 pP1 = pBt->pPage1->aData;
8241 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
8242 if( rc==SQLITE_OK ){
8243 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00008244#ifndef SQLITE_OMIT_AUTOVACUUM
danielk19770d19f7a2009-06-03 11:25:07 +00008245 if( idx==BTREE_INCR_VACUUM ){
drh64022502009-01-09 14:11:04 +00008246 assert( pBt->autoVacuum || iMeta==0 );
8247 assert( iMeta==0 || iMeta==1 );
8248 pBt->incrVacuum = (u8)iMeta;
drhd677b3d2007-08-20 22:48:41 +00008249 }
drh64022502009-01-09 14:11:04 +00008250#endif
drh5df72a52002-06-06 23:16:05 +00008251 }
drhd677b3d2007-08-20 22:48:41 +00008252 sqlite3BtreeLeave(p);
8253 return rc;
drh8b2f49b2001-06-08 00:21:52 +00008254}
drh8c42ca92001-06-22 19:15:00 +00008255
danielk1977a5533162009-02-24 10:01:51 +00008256#ifndef SQLITE_OMIT_BTREECOUNT
8257/*
8258** The first argument, pCur, is a cursor opened on some b-tree. Count the
8259** number of entries in the b-tree and write the result to *pnEntry.
8260**
8261** SQLITE_OK is returned if the operation is successfully executed.
8262** Otherwise, if an error is encountered (i.e. an IO error or database
8263** corruption) an SQLite error code is returned.
8264*/
8265int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
8266 i64 nEntry = 0; /* Value to return in *pnEntry */
8267 int rc; /* Return code */
dana205a482011-08-27 18:48:57 +00008268
8269 if( pCur->pgnoRoot==0 ){
8270 *pnEntry = 0;
8271 return SQLITE_OK;
8272 }
danielk1977a5533162009-02-24 10:01:51 +00008273 rc = moveToRoot(pCur);
8274
8275 /* Unless an error occurs, the following loop runs one iteration for each
8276 ** page in the B-Tree structure (not including overflow pages).
8277 */
8278 while( rc==SQLITE_OK ){
8279 int iIdx; /* Index of child node in parent */
8280 MemPage *pPage; /* Current page of the b-tree */
8281
8282 /* If this is a leaf page or the tree is not an int-key tree, then
8283 ** this page contains countable entries. Increment the entry counter
8284 ** accordingly.
8285 */
8286 pPage = pCur->apPage[pCur->iPage];
8287 if( pPage->leaf || !pPage->intKey ){
8288 nEntry += pPage->nCell;
8289 }
8290
8291 /* pPage is a leaf node. This loop navigates the cursor so that it
8292 ** points to the first interior cell that it points to the parent of
8293 ** the next page in the tree that has not yet been visited. The
8294 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
8295 ** of the page, or to the number of cells in the page if the next page
8296 ** to visit is the right-child of its parent.
8297 **
8298 ** If all pages in the tree have been visited, return SQLITE_OK to the
8299 ** caller.
8300 */
8301 if( pPage->leaf ){
8302 do {
8303 if( pCur->iPage==0 ){
8304 /* All pages of the b-tree have been visited. Return successfully. */
8305 *pnEntry = nEntry;
drh7efa4262014-12-16 00:08:31 +00008306 return moveToRoot(pCur);
danielk1977a5533162009-02-24 10:01:51 +00008307 }
danielk197730548662009-07-09 05:07:37 +00008308 moveToParent(pCur);
danielk1977a5533162009-02-24 10:01:51 +00008309 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
8310
8311 pCur->aiIdx[pCur->iPage]++;
8312 pPage = pCur->apPage[pCur->iPage];
8313 }
8314
8315 /* Descend to the child node of the cell that the cursor currently
8316 ** points at. This is the right-child if (iIdx==pPage->nCell).
8317 */
8318 iIdx = pCur->aiIdx[pCur->iPage];
8319 if( iIdx==pPage->nCell ){
8320 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
8321 }else{
8322 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
8323 }
8324 }
8325
shanebe217792009-03-05 04:20:31 +00008326 /* An error has occurred. Return an error code. */
danielk1977a5533162009-02-24 10:01:51 +00008327 return rc;
8328}
8329#endif
drhdd793422001-06-28 01:54:48 +00008330
drhdd793422001-06-28 01:54:48 +00008331/*
drh5eddca62001-06-30 21:53:53 +00008332** Return the pager associated with a BTree. This routine is used for
8333** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00008334*/
danielk1977aef0bf62005-12-30 16:28:01 +00008335Pager *sqlite3BtreePager(Btree *p){
8336 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00008337}
drh5eddca62001-06-30 21:53:53 +00008338
drhb7f91642004-10-31 02:22:47 +00008339#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00008340/*
8341** Append a message to the error message string.
8342*/
drh2e38c322004-09-03 18:38:44 +00008343static void checkAppendMsg(
8344 IntegrityCk *pCheck,
drh2e38c322004-09-03 18:38:44 +00008345 const char *zFormat,
8346 ...
8347){
8348 va_list ap;
drh867db832014-09-26 02:41:05 +00008349 char zBuf[200];
drh1dcdbc02007-01-27 02:24:54 +00008350 if( !pCheck->mxErr ) return;
8351 pCheck->mxErr--;
8352 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00008353 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +00008354 if( pCheck->errMsg.nChar ){
8355 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +00008356 }
drh867db832014-09-26 02:41:05 +00008357 if( pCheck->zPfx ){
8358 sqlite3_snprintf(sizeof(zBuf), zBuf, pCheck->zPfx, pCheck->v1, pCheck->v2);
8359 sqlite3StrAccumAppendAll(&pCheck->errMsg, zBuf);
drhf089aa42008-07-08 19:34:06 +00008360 }
8361 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
8362 va_end(ap);
drhb49bc862013-08-21 21:12:10 +00008363 if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
drhc890fec2008-08-01 20:10:08 +00008364 pCheck->mallocFailed = 1;
8365 }
drh5eddca62001-06-30 21:53:53 +00008366}
drhb7f91642004-10-31 02:22:47 +00008367#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00008368
drhb7f91642004-10-31 02:22:47 +00008369#ifndef SQLITE_OMIT_INTEGRITY_CHECK
dan1235bb12012-04-03 17:43:28 +00008370
8371/*
8372** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
8373** corresponds to page iPg is already set.
8374*/
8375static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
8376 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
8377 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
8378}
8379
8380/*
8381** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
8382*/
8383static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
8384 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
8385 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
8386}
8387
8388
drh5eddca62001-06-30 21:53:53 +00008389/*
8390** Add 1 to the reference count for page iPage. If this is the second
8391** reference to the page, add an error message to pCheck->zErrMsg.
peter.d.reid60ec9142014-09-06 16:39:46 +00008392** Return 1 if there are 2 or more references to the page and 0 if
drh5eddca62001-06-30 21:53:53 +00008393** if this is the first reference to the page.
8394**
8395** Also check that the page number is in bounds.
8396*/
drh867db832014-09-26 02:41:05 +00008397static int checkRef(IntegrityCk *pCheck, Pgno iPage){
drh5eddca62001-06-30 21:53:53 +00008398 if( iPage==0 ) return 1;
danielk197789d40042008-11-17 14:20:56 +00008399 if( iPage>pCheck->nPage ){
drh867db832014-09-26 02:41:05 +00008400 checkAppendMsg(pCheck, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00008401 return 1;
8402 }
dan1235bb12012-04-03 17:43:28 +00008403 if( getPageReferenced(pCheck, iPage) ){
drh867db832014-09-26 02:41:05 +00008404 checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00008405 return 1;
8406 }
dan1235bb12012-04-03 17:43:28 +00008407 setPageReferenced(pCheck, iPage);
8408 return 0;
drh5eddca62001-06-30 21:53:53 +00008409}
8410
danielk1977afcdd022004-10-31 16:25:42 +00008411#ifndef SQLITE_OMIT_AUTOVACUUM
8412/*
8413** Check that the entry in the pointer-map for page iChild maps to
8414** page iParent, pointer type ptrType. If not, append an error message
8415** to pCheck.
8416*/
8417static void checkPtrmap(
8418 IntegrityCk *pCheck, /* Integrity check context */
8419 Pgno iChild, /* Child page number */
8420 u8 eType, /* Expected pointer map type */
drh867db832014-09-26 02:41:05 +00008421 Pgno iParent /* Expected pointer map parent page number */
danielk1977afcdd022004-10-31 16:25:42 +00008422){
8423 int rc;
8424 u8 ePtrmapType;
8425 Pgno iPtrmapParent;
8426
8427 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
8428 if( rc!=SQLITE_OK ){
drhb56cd552009-05-01 13:16:54 +00008429 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
drh867db832014-09-26 02:41:05 +00008430 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
danielk1977afcdd022004-10-31 16:25:42 +00008431 return;
8432 }
8433
8434 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
drh867db832014-09-26 02:41:05 +00008435 checkAppendMsg(pCheck,
danielk1977afcdd022004-10-31 16:25:42 +00008436 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
8437 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
8438 }
8439}
8440#endif
8441
drh5eddca62001-06-30 21:53:53 +00008442/*
8443** Check the integrity of the freelist or of an overflow page list.
8444** Verify that the number of pages on the list is N.
8445*/
drh30e58752002-03-02 20:41:57 +00008446static void checkList(
8447 IntegrityCk *pCheck, /* Integrity checking context */
8448 int isFreeList, /* True for a freelist. False for overflow page list */
8449 int iPage, /* Page number for first page in the list */
drh867db832014-09-26 02:41:05 +00008450 int N /* Expected number of pages in the list */
drh30e58752002-03-02 20:41:57 +00008451){
8452 int i;
drh3a4c1412004-05-09 20:40:11 +00008453 int expected = N;
8454 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00008455 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00008456 DbPage *pOvflPage;
8457 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00008458 if( iPage<1 ){
drh867db832014-09-26 02:41:05 +00008459 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00008460 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00008461 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00008462 break;
8463 }
drh867db832014-09-26 02:41:05 +00008464 if( checkRef(pCheck, iPage) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00008465 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh867db832014-09-26 02:41:05 +00008466 checkAppendMsg(pCheck, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00008467 break;
8468 }
danielk19773b8a05f2007-03-19 17:44:26 +00008469 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00008470 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00008471 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00008472#ifndef SQLITE_OMIT_AUTOVACUUM
8473 if( pCheck->pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00008474 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +00008475 }
8476#endif
drh43b18e12010-08-17 19:40:08 +00008477 if( n>(int)pCheck->pBt->usableSize/4-2 ){
drh867db832014-09-26 02:41:05 +00008478 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00008479 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00008480 N--;
8481 }else{
8482 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00008483 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00008484#ifndef SQLITE_OMIT_AUTOVACUUM
8485 if( pCheck->pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00008486 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +00008487 }
8488#endif
drh867db832014-09-26 02:41:05 +00008489 checkRef(pCheck, iFreePage);
drhee696e22004-08-30 16:52:17 +00008490 }
8491 N -= n;
drh30e58752002-03-02 20:41:57 +00008492 }
drh30e58752002-03-02 20:41:57 +00008493 }
danielk1977afcdd022004-10-31 16:25:42 +00008494#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00008495 else{
8496 /* If this database supports auto-vacuum and iPage is not the last
8497 ** page in this overflow list, check that the pointer-map entry for
8498 ** the following page matches iPage.
8499 */
8500 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00008501 i = get4byte(pOvflData);
drh867db832014-09-26 02:41:05 +00008502 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
danielk1977687566d2004-11-02 12:56:41 +00008503 }
danielk1977afcdd022004-10-31 16:25:42 +00008504 }
8505#endif
danielk19773b8a05f2007-03-19 17:44:26 +00008506 iPage = get4byte(pOvflData);
8507 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00008508 }
8509}
drhb7f91642004-10-31 02:22:47 +00008510#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00008511
drhb7f91642004-10-31 02:22:47 +00008512#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00008513/*
8514** Do various sanity checks on a single page of a tree. Return
8515** the tree depth. Root pages return 0. Parents of root pages
8516** return 1, and so forth.
8517**
8518** These checks are done:
8519**
8520** 1. Make sure that cells and freeblocks do not overlap
8521** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00008522** NO 2. Make sure cell keys are in order.
8523** NO 3. Make sure no key is less than or equal to zLowerBound.
8524** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00008525** 5. Check the integrity of overflow pages.
8526** 6. Recursively call checkTreePage on all children.
8527** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00008528** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00008529** the root of the tree.
8530*/
8531static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00008532 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00008533 int iPage, /* Page number of the page to check */
shaneh195475d2010-02-19 04:28:08 +00008534 i64 *pnParentMinKey,
8535 i64 *pnParentMaxKey
drh5eddca62001-06-30 21:53:53 +00008536){
8537 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00008538 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00008539 int hdr, cellStart;
8540 int nCell;
drhda200cc2004-05-09 11:51:38 +00008541 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00008542 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00008543 int usableSize;
shane0af3f892008-11-12 04:55:34 +00008544 char *hit = 0;
shaneh195475d2010-02-19 04:28:08 +00008545 i64 nMinKey = 0;
8546 i64 nMaxKey = 0;
drh867db832014-09-26 02:41:05 +00008547 const char *saved_zPfx = pCheck->zPfx;
8548 int saved_v1 = pCheck->v1;
8549 int saved_v2 = pCheck->v2;
danielk1977ef73ee92004-11-06 12:26:07 +00008550
drh5eddca62001-06-30 21:53:53 +00008551 /* Check that the page exists
8552 */
drhd9cb6ac2005-10-20 07:28:17 +00008553 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00008554 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00008555 if( iPage==0 ) return 0;
drh867db832014-09-26 02:41:05 +00008556 if( checkRef(pCheck, iPage) ) return 0;
8557 pCheck->zPfx = "Page %d: ";
8558 pCheck->v1 = iPage;
drhb00fc3b2013-08-21 23:42:32 +00008559 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drh867db832014-09-26 02:41:05 +00008560 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00008561 "unable to get the page. error code=%d", rc);
drh867db832014-09-26 02:41:05 +00008562 depth = -1;
8563 goto end_of_check;
drh5eddca62001-06-30 21:53:53 +00008564 }
danielk197793caf5a2009-07-11 06:55:33 +00008565
8566 /* Clear MemPage.isInit to make sure the corruption detection code in
8567 ** btreeInitPage() is executed. */
8568 pPage->isInit = 0;
danielk197730548662009-07-09 05:07:37 +00008569 if( (rc = btreeInitPage(pPage))!=0 ){
drh64022502009-01-09 14:11:04 +00008570 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
drh867db832014-09-26 02:41:05 +00008571 checkAppendMsg(pCheck,
danielk197730548662009-07-09 05:07:37 +00008572 "btreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00008573 releasePage(pPage);
drh867db832014-09-26 02:41:05 +00008574 depth = -1;
8575 goto end_of_check;
drh5eddca62001-06-30 21:53:53 +00008576 }
8577
8578 /* Check out all the cells.
8579 */
8580 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00008581 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00008582 u8 *pCell;
danielk197789d40042008-11-17 14:20:56 +00008583 u32 sz;
drh6f11bef2004-05-13 01:12:56 +00008584 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00008585
8586 /* Check payload overflow pages
8587 */
drh867db832014-09-26 02:41:05 +00008588 pCheck->zPfx = "On tree page %d cell %d: ";
8589 pCheck->v1 = iPage;
8590 pCheck->v2 = i;
danielk19771cc5ed82007-05-16 17:28:43 +00008591 pCell = findCell(pPage,i);
danielk197730548662009-07-09 05:07:37 +00008592 btreeParseCellPtr(pPage, pCell, &info);
drhab1cc582014-09-23 21:25:19 +00008593 sz = info.nPayload;
shaneh195475d2010-02-19 04:28:08 +00008594 /* For intKey pages, check that the keys are in order.
8595 */
drhab1cc582014-09-23 21:25:19 +00008596 if( pPage->intKey ){
8597 if( i==0 ){
8598 nMinKey = nMaxKey = info.nKey;
8599 }else if( info.nKey <= nMaxKey ){
drh867db832014-09-26 02:41:05 +00008600 checkAppendMsg(pCheck,
drhab1cc582014-09-23 21:25:19 +00008601 "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
shaneh195475d2010-02-19 04:28:08 +00008602 }
8603 nMaxKey = info.nKey;
8604 }
danielk19775be31f52009-03-30 13:53:43 +00008605 if( (sz>info.nLocal)
8606 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
8607 ){
drhb6f41482004-05-14 01:58:11 +00008608 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00008609 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
8610#ifndef SQLITE_OMIT_AUTOVACUUM
8611 if( pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00008612 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
danielk1977afcdd022004-10-31 16:25:42 +00008613 }
8614#endif
drh867db832014-09-26 02:41:05 +00008615 checkList(pCheck, 0, pgnoOvfl, nPage);
drh5eddca62001-06-30 21:53:53 +00008616 }
8617
8618 /* Check sanity of left child page.
8619 */
drhda200cc2004-05-09 11:51:38 +00008620 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00008621 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00008622#ifndef SQLITE_OMIT_AUTOVACUUM
8623 if( pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00008624 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
danielk1977afcdd022004-10-31 16:25:42 +00008625 }
8626#endif
drh867db832014-09-26 02:41:05 +00008627 d2 = checkTreePage(pCheck, pgno, &nMinKey, i==0?NULL:&nMaxKey);
drhda200cc2004-05-09 11:51:38 +00008628 if( i>0 && d2!=depth ){
drh867db832014-09-26 02:41:05 +00008629 checkAppendMsg(pCheck, "Child page depth differs");
drhda200cc2004-05-09 11:51:38 +00008630 }
8631 depth = d2;
drh5eddca62001-06-30 21:53:53 +00008632 }
drh5eddca62001-06-30 21:53:53 +00008633 }
shaneh195475d2010-02-19 04:28:08 +00008634
drhda200cc2004-05-09 11:51:38 +00008635 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00008636 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh867db832014-09-26 02:41:05 +00008637 pCheck->zPfx = "On page %d at right child: ";
8638 pCheck->v1 = iPage;
danielk1977afcdd022004-10-31 16:25:42 +00008639#ifndef SQLITE_OMIT_AUTOVACUUM
8640 if( pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00008641 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
danielk1977afcdd022004-10-31 16:25:42 +00008642 }
8643#endif
drh867db832014-09-26 02:41:05 +00008644 checkTreePage(pCheck, pgno, NULL, !pPage->nCell?NULL:&nMaxKey);
drhda200cc2004-05-09 11:51:38 +00008645 }
drh5eddca62001-06-30 21:53:53 +00008646
shaneh195475d2010-02-19 04:28:08 +00008647 /* For intKey leaf pages, check that the min/max keys are in order
8648 ** with any left/parent/right pages.
8649 */
drh867db832014-09-26 02:41:05 +00008650 pCheck->zPfx = "Page %d: ";
8651 pCheck->v1 = iPage;
shaneh195475d2010-02-19 04:28:08 +00008652 if( pPage->leaf && pPage->intKey ){
8653 /* if we are a left child page */
8654 if( pnParentMinKey ){
8655 /* if we are the left most child page */
8656 if( !pnParentMaxKey ){
8657 if( nMaxKey > *pnParentMinKey ){
drh867db832014-09-26 02:41:05 +00008658 checkAppendMsg(pCheck,
shaneh195475d2010-02-19 04:28:08 +00008659 "Rowid %lld out of order (max larger than parent min of %lld)",
8660 nMaxKey, *pnParentMinKey);
8661 }
8662 }else{
8663 if( nMinKey <= *pnParentMinKey ){
drh867db832014-09-26 02:41:05 +00008664 checkAppendMsg(pCheck,
shaneh195475d2010-02-19 04:28:08 +00008665 "Rowid %lld out of order (min less than parent min of %lld)",
8666 nMinKey, *pnParentMinKey);
8667 }
8668 if( nMaxKey > *pnParentMaxKey ){
drh867db832014-09-26 02:41:05 +00008669 checkAppendMsg(pCheck,
shaneh195475d2010-02-19 04:28:08 +00008670 "Rowid %lld out of order (max larger than parent max of %lld)",
8671 nMaxKey, *pnParentMaxKey);
8672 }
8673 *pnParentMinKey = nMaxKey;
8674 }
8675 /* else if we're a right child page */
8676 } else if( pnParentMaxKey ){
8677 if( nMinKey <= *pnParentMaxKey ){
drh867db832014-09-26 02:41:05 +00008678 checkAppendMsg(pCheck,
shaneh195475d2010-02-19 04:28:08 +00008679 "Rowid %lld out of order (min less than parent max of %lld)",
8680 nMinKey, *pnParentMaxKey);
8681 }
8682 }
8683 }
8684
drh5eddca62001-06-30 21:53:53 +00008685 /* Check for complete coverage of the page
8686 */
drhda200cc2004-05-09 11:51:38 +00008687 data = pPage->aData;
8688 hdr = pPage->hdrOffset;
drhf7141992008-06-19 00:16:08 +00008689 hit = sqlite3PageMalloc( pBt->pageSize );
drh867db832014-09-26 02:41:05 +00008690 pCheck->zPfx = 0;
drhc890fec2008-08-01 20:10:08 +00008691 if( hit==0 ){
8692 pCheck->mallocFailed = 1;
8693 }else{
drh5d433ce2010-08-14 16:02:52 +00008694 int contentOffset = get2byteNotZero(&data[hdr+5]);
drhd7c7ecd2009-07-14 17:48:06 +00008695 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
shane5780ebd2008-11-11 17:36:30 +00008696 memset(hit+contentOffset, 0, usableSize-contentOffset);
8697 memset(hit, 1, contentOffset);
drhfdab0262014-11-20 15:30:50 +00008698 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
8699 ** number of cells on the page. */
drh2e38c322004-09-03 18:38:44 +00008700 nCell = get2byte(&data[hdr+3]);
drhfdab0262014-11-20 15:30:50 +00008701 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
8702 ** immediately follows the b-tree page header. */
drh2e38c322004-09-03 18:38:44 +00008703 cellStart = hdr + 12 - 4*pPage->leaf;
drhfdab0262014-11-20 15:30:50 +00008704 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
8705 ** integer offsets to the cell contents. */
drh2e38c322004-09-03 18:38:44 +00008706 for(i=0; i<nCell; i++){
8707 int pc = get2byte(&data[cellStart+i*2]);
drh9b78f792010-08-14 21:21:24 +00008708 u32 size = 65536;
drh2e38c322004-09-03 18:38:44 +00008709 int j;
drh8c2bbb62009-07-10 02:52:20 +00008710 if( pc<=usableSize-4 ){
danielk1977daca5432008-08-25 11:57:16 +00008711 size = cellSizePtr(pPage, &data[pc]);
8712 }
drh43b18e12010-08-17 19:40:08 +00008713 if( (int)(pc+size-1)>=usableSize ){
drh867db832014-09-26 02:41:05 +00008714 pCheck->zPfx = 0;
8715 checkAppendMsg(pCheck,
shaneh195475d2010-02-19 04:28:08 +00008716 "Corruption detected in cell %d on page %d",i,iPage);
danielk19777701e812005-01-10 12:59:51 +00008717 }else{
8718 for(j=pc+size-1; j>=pc; j--) hit[j]++;
8719 }
drh2e38c322004-09-03 18:38:44 +00008720 }
drhfdab0262014-11-20 15:30:50 +00008721 /* EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
8722 ** is the offset of the first freeblock, or zero if there are no
8723 ** freeblocks on the page. */
drh8c2bbb62009-07-10 02:52:20 +00008724 i = get2byte(&data[hdr+1]);
8725 while( i>0 ){
8726 int size, j;
8727 assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
8728 size = get2byte(&data[i+2]);
8729 assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
8730 for(j=i+size-1; j>=i; j--) hit[j]++;
drhfdab0262014-11-20 15:30:50 +00008731 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
8732 ** big-endian integer which is the offset in the b-tree page of the next
8733 ** freeblock in the chain, or zero if the freeblock is the last on the
8734 ** chain. */
drh8c2bbb62009-07-10 02:52:20 +00008735 j = get2byte(&data[i]);
drhfdab0262014-11-20 15:30:50 +00008736 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
8737 ** increasing offset. */
drh8c2bbb62009-07-10 02:52:20 +00008738 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
8739 assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
8740 i = j;
drh2e38c322004-09-03 18:38:44 +00008741 }
8742 for(i=cnt=0; i<usableSize; i++){
8743 if( hit[i]==0 ){
8744 cnt++;
8745 }else if( hit[i]>1 ){
drh867db832014-09-26 02:41:05 +00008746 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00008747 "Multiple uses for byte %d of page %d", i, iPage);
8748 break;
8749 }
8750 }
drhfdab0262014-11-20 15:30:50 +00008751 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
8752 ** is stored in the fifth field of the b-tree page header.
8753 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
8754 ** number of fragmented free bytes within the cell content area.
8755 */
drh2e38c322004-09-03 18:38:44 +00008756 if( cnt!=data[hdr+7] ){
drh867db832014-09-26 02:41:05 +00008757 checkAppendMsg(pCheck,
drh8c2bbb62009-07-10 02:52:20 +00008758 "Fragmentation of %d bytes reported as %d on page %d",
drh2e38c322004-09-03 18:38:44 +00008759 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00008760 }
8761 }
drh8c2bbb62009-07-10 02:52:20 +00008762 sqlite3PageFree(hit);
drh4b70f112004-05-02 21:12:19 +00008763 releasePage(pPage);
drh867db832014-09-26 02:41:05 +00008764
8765end_of_check:
8766 pCheck->zPfx = saved_zPfx;
8767 pCheck->v1 = saved_v1;
8768 pCheck->v2 = saved_v2;
drhda200cc2004-05-09 11:51:38 +00008769 return depth+1;
drh5eddca62001-06-30 21:53:53 +00008770}
drhb7f91642004-10-31 02:22:47 +00008771#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00008772
drhb7f91642004-10-31 02:22:47 +00008773#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00008774/*
8775** This routine does a complete check of the given BTree file. aRoot[] is
8776** an array of pages numbers were each page number is the root page of
8777** a table. nRoot is the number of entries in aRoot.
8778**
danielk19773509a652009-07-06 18:56:13 +00008779** A read-only or read-write transaction must be opened before calling
8780** this function.
8781**
drhc890fec2008-08-01 20:10:08 +00008782** Write the number of error seen in *pnErr. Except for some memory
drhe43ba702008-12-05 22:40:08 +00008783** allocation errors, an error message held in memory obtained from
drhc890fec2008-08-01 20:10:08 +00008784** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
drhe43ba702008-12-05 22:40:08 +00008785** returned. If a memory allocation error occurs, NULL is returned.
drh5eddca62001-06-30 21:53:53 +00008786*/
drh1dcdbc02007-01-27 02:24:54 +00008787char *sqlite3BtreeIntegrityCheck(
8788 Btree *p, /* The btree to be checked */
8789 int *aRoot, /* An array of root pages numbers for individual trees */
8790 int nRoot, /* Number of entries in aRoot[] */
8791 int mxErr, /* Stop reporting errors after this many */
8792 int *pnErr /* Write number of errors seen to this variable */
8793){
danielk197789d40042008-11-17 14:20:56 +00008794 Pgno i;
drh5eddca62001-06-30 21:53:53 +00008795 int nRef;
drhaaab5722002-02-19 13:39:21 +00008796 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00008797 BtShared *pBt = p->pBt;
drhf089aa42008-07-08 19:34:06 +00008798 char zErr[100];
drh5eddca62001-06-30 21:53:53 +00008799
drhd677b3d2007-08-20 22:48:41 +00008800 sqlite3BtreeEnter(p);
danielk19773509a652009-07-06 18:56:13 +00008801 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
danielk19773b8a05f2007-03-19 17:44:26 +00008802 nRef = sqlite3PagerRefcount(pBt->pPager);
drh5eddca62001-06-30 21:53:53 +00008803 sCheck.pBt = pBt;
8804 sCheck.pPager = pBt->pPager;
drhb1299152010-03-30 22:58:33 +00008805 sCheck.nPage = btreePagecount(sCheck.pBt);
drh1dcdbc02007-01-27 02:24:54 +00008806 sCheck.mxErr = mxErr;
8807 sCheck.nErr = 0;
drhc890fec2008-08-01 20:10:08 +00008808 sCheck.mallocFailed = 0;
drh867db832014-09-26 02:41:05 +00008809 sCheck.zPfx = 0;
8810 sCheck.v1 = 0;
8811 sCheck.v2 = 0;
drh1dcdbc02007-01-27 02:24:54 +00008812 *pnErr = 0;
drh0de8c112002-07-06 16:32:14 +00008813 if( sCheck.nPage==0 ){
drhd677b3d2007-08-20 22:48:41 +00008814 sqlite3BtreeLeave(p);
drh0de8c112002-07-06 16:32:14 +00008815 return 0;
8816 }
dan1235bb12012-04-03 17:43:28 +00008817
8818 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
8819 if( !sCheck.aPgRef ){
drh1dcdbc02007-01-27 02:24:54 +00008820 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00008821 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00008822 return 0;
danielk1977ac245ec2005-01-14 13:50:11 +00008823 }
drh42cac6d2004-11-20 20:31:11 +00008824 i = PENDING_BYTE_PAGE(pBt);
dan1235bb12012-04-03 17:43:28 +00008825 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
drh32055c22012-12-12 14:30:03 +00008826 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
drhb9755982010-07-24 16:34:37 +00008827 sCheck.errMsg.useMalloc = 2;
drh5eddca62001-06-30 21:53:53 +00008828
8829 /* Check the integrity of the freelist
8830 */
drh867db832014-09-26 02:41:05 +00008831 sCheck.zPfx = "Main freelist: ";
drha34b6762004-05-07 13:30:42 +00008832 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
drh867db832014-09-26 02:41:05 +00008833 get4byte(&pBt->pPage1->aData[36]));
8834 sCheck.zPfx = 0;
drh5eddca62001-06-30 21:53:53 +00008835
8836 /* Check all the tables.
8837 */
danielk197789d40042008-11-17 14:20:56 +00008838 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00008839 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00008840#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00008841 if( pBt->autoVacuum && aRoot[i]>1 ){
drh867db832014-09-26 02:41:05 +00008842 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +00008843 }
8844#endif
drh867db832014-09-26 02:41:05 +00008845 sCheck.zPfx = "List of tree roots: ";
8846 checkTreePage(&sCheck, aRoot[i], NULL, NULL);
8847 sCheck.zPfx = 0;
drh5eddca62001-06-30 21:53:53 +00008848 }
8849
8850 /* Make sure every page in the file is referenced
8851 */
drh1dcdbc02007-01-27 02:24:54 +00008852 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00008853#ifdef SQLITE_OMIT_AUTOVACUUM
dan1235bb12012-04-03 17:43:28 +00008854 if( getPageReferenced(&sCheck, i)==0 ){
drh867db832014-09-26 02:41:05 +00008855 checkAppendMsg(&sCheck, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00008856 }
danielk1977afcdd022004-10-31 16:25:42 +00008857#else
8858 /* If the database supports auto-vacuum, make sure no tables contain
8859 ** references to pointer-map pages.
8860 */
dan1235bb12012-04-03 17:43:28 +00008861 if( getPageReferenced(&sCheck, i)==0 &&
danielk1977266664d2006-02-10 08:24:21 +00008862 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
drh867db832014-09-26 02:41:05 +00008863 checkAppendMsg(&sCheck, "Page %d is never used", i);
danielk1977afcdd022004-10-31 16:25:42 +00008864 }
dan1235bb12012-04-03 17:43:28 +00008865 if( getPageReferenced(&sCheck, i)!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00008866 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
drh867db832014-09-26 02:41:05 +00008867 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
danielk1977afcdd022004-10-31 16:25:42 +00008868 }
8869#endif
drh5eddca62001-06-30 21:53:53 +00008870 }
8871
drh64022502009-01-09 14:11:04 +00008872 /* Make sure this analysis did not leave any unref() pages.
8873 ** This is an internal consistency check; an integrity check
8874 ** of the integrity check.
drh5eddca62001-06-30 21:53:53 +00008875 */
drh64022502009-01-09 14:11:04 +00008876 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
drh867db832014-09-26 02:41:05 +00008877 checkAppendMsg(&sCheck,
drh5eddca62001-06-30 21:53:53 +00008878 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00008879 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00008880 );
drh5eddca62001-06-30 21:53:53 +00008881 }
8882
8883 /* Clean up and report errors.
8884 */
drhd677b3d2007-08-20 22:48:41 +00008885 sqlite3BtreeLeave(p);
dan1235bb12012-04-03 17:43:28 +00008886 sqlite3_free(sCheck.aPgRef);
drhc890fec2008-08-01 20:10:08 +00008887 if( sCheck.mallocFailed ){
8888 sqlite3StrAccumReset(&sCheck.errMsg);
8889 *pnErr = sCheck.nErr+1;
8890 return 0;
8891 }
drh1dcdbc02007-01-27 02:24:54 +00008892 *pnErr = sCheck.nErr;
drhf089aa42008-07-08 19:34:06 +00008893 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
8894 return sqlite3StrAccumFinish(&sCheck.errMsg);
drh5eddca62001-06-30 21:53:53 +00008895}
drhb7f91642004-10-31 02:22:47 +00008896#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00008897
drh73509ee2003-04-06 20:44:45 +00008898/*
drhd4e0bb02012-05-27 01:19:04 +00008899** Return the full pathname of the underlying database file. Return
8900** an empty string if the database is in-memory or a TEMP database.
drhd0679ed2007-08-28 22:24:34 +00008901**
8902** The pager filename is invariant as long as the pager is
8903** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00008904*/
danielk1977aef0bf62005-12-30 16:28:01 +00008905const char *sqlite3BtreeGetFilename(Btree *p){
8906 assert( p->pBt->pPager!=0 );
drhd4e0bb02012-05-27 01:19:04 +00008907 return sqlite3PagerFilename(p->pBt->pPager, 1);
drh73509ee2003-04-06 20:44:45 +00008908}
8909
8910/*
danielk19775865e3d2004-06-14 06:03:57 +00008911** Return the pathname of the journal file for this database. The return
8912** value of this routine is the same regardless of whether the journal file
8913** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00008914**
8915** The pager journal filename is invariant as long as the pager is
8916** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00008917*/
danielk1977aef0bf62005-12-30 16:28:01 +00008918const char *sqlite3BtreeGetJournalname(Btree *p){
8919 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00008920 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00008921}
8922
danielk19771d850a72004-05-31 08:26:49 +00008923/*
8924** Return non-zero if a transaction is active.
8925*/
danielk1977aef0bf62005-12-30 16:28:01 +00008926int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00008927 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00008928 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00008929}
8930
dana550f2d2010-08-02 10:47:05 +00008931#ifndef SQLITE_OMIT_WAL
8932/*
8933** Run a checkpoint on the Btree passed as the first argument.
8934**
8935** Return SQLITE_LOCKED if this or any other connection has an open
8936** transaction on the shared-cache the argument Btree is connected to.
dana58f26f2010-11-16 18:56:51 +00008937**
dancdc1f042010-11-18 12:11:05 +00008938** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
dana550f2d2010-08-02 10:47:05 +00008939*/
dancdc1f042010-11-18 12:11:05 +00008940int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
dana550f2d2010-08-02 10:47:05 +00008941 int rc = SQLITE_OK;
8942 if( p ){
8943 BtShared *pBt = p->pBt;
8944 sqlite3BtreeEnter(p);
8945 if( pBt->inTransaction!=TRANS_NONE ){
8946 rc = SQLITE_LOCKED;
8947 }else{
dancdc1f042010-11-18 12:11:05 +00008948 rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
dana550f2d2010-08-02 10:47:05 +00008949 }
8950 sqlite3BtreeLeave(p);
8951 }
8952 return rc;
8953}
8954#endif
8955
danielk19771d850a72004-05-31 08:26:49 +00008956/*
danielk19772372c2b2006-06-27 16:34:56 +00008957** Return non-zero if a read (or write) transaction is active.
8958*/
8959int sqlite3BtreeIsInReadTrans(Btree *p){
drh64022502009-01-09 14:11:04 +00008960 assert( p );
drhe5fe6902007-12-07 18:55:28 +00008961 assert( sqlite3_mutex_held(p->db->mutex) );
drh64022502009-01-09 14:11:04 +00008962 return p->inTrans!=TRANS_NONE;
danielk19772372c2b2006-06-27 16:34:56 +00008963}
8964
danielk197704103022009-02-03 16:51:24 +00008965int sqlite3BtreeIsInBackup(Btree *p){
8966 assert( p );
8967 assert( sqlite3_mutex_held(p->db->mutex) );
8968 return p->nBackup!=0;
8969}
8970
danielk19772372c2b2006-06-27 16:34:56 +00008971/*
danielk1977da184232006-01-05 11:34:32 +00008972** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +00008973** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +00008974** purposes (for example, to store a high-level schema associated with
8975** the shared-btree). The btree layer manages reference counting issues.
8976**
8977** The first time this is called on a shared-btree, nBytes bytes of memory
8978** are allocated, zeroed, and returned to the caller. For each subsequent
8979** call the nBytes parameter is ignored and a pointer to the same blob
8980** of memory returned.
8981**
danielk1977171bfed2008-06-23 09:50:50 +00008982** If the nBytes parameter is 0 and the blob of memory has not yet been
8983** allocated, a null pointer is returned. If the blob has already been
8984** allocated, it is returned as normal.
8985**
danielk1977da184232006-01-05 11:34:32 +00008986** Just before the shared-btree is closed, the function passed as the
8987** xFree argument when the memory allocation was made is invoked on the
drh4fa7d7c2011-04-03 02:41:00 +00008988** blob of allocated memory. The xFree function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00008989** on the memory, the btree layer does that.
8990*/
8991void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
8992 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00008993 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +00008994 if( !pBt->pSchema && nBytes ){
drhb9755982010-07-24 16:34:37 +00008995 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
danielk1977da184232006-01-05 11:34:32 +00008996 pBt->xFreeSchema = xFree;
8997 }
drh27641702007-08-22 02:56:42 +00008998 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00008999 return pBt->pSchema;
9000}
9001
danielk1977c87d34d2006-01-06 13:00:28 +00009002/*
danielk1977404ca072009-03-16 13:19:36 +00009003** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
9004** btree as the argument handle holds an exclusive lock on the
9005** sqlite_master table. Otherwise SQLITE_OK.
danielk1977c87d34d2006-01-06 13:00:28 +00009006*/
9007int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00009008 int rc;
drhe5fe6902007-12-07 18:55:28 +00009009 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +00009010 sqlite3BtreeEnter(p);
danielk1977404ca072009-03-16 13:19:36 +00009011 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
9012 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
drh27641702007-08-22 02:56:42 +00009013 sqlite3BtreeLeave(p);
9014 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00009015}
9016
drha154dcd2006-03-22 22:10:07 +00009017
9018#ifndef SQLITE_OMIT_SHARED_CACHE
9019/*
9020** Obtain a lock on the table whose root page is iTab. The
9021** lock is a write lock if isWritelock is true or a read lock
9022** if it is false.
9023*/
danielk1977c00da102006-01-07 13:21:04 +00009024int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00009025 int rc = SQLITE_OK;
danielk1977602b4662009-07-02 07:47:33 +00009026 assert( p->inTrans!=TRANS_NONE );
drh6a9ad3d2008-04-02 16:29:30 +00009027 if( p->sharable ){
9028 u8 lockType = READ_LOCK + isWriteLock;
9029 assert( READ_LOCK+1==WRITE_LOCK );
9030 assert( isWriteLock==0 || isWriteLock==1 );
danielk1977602b4662009-07-02 07:47:33 +00009031
drh6a9ad3d2008-04-02 16:29:30 +00009032 sqlite3BtreeEnter(p);
drhc25eabe2009-02-24 18:57:31 +00009033 rc = querySharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00009034 if( rc==SQLITE_OK ){
drhc25eabe2009-02-24 18:57:31 +00009035 rc = setSharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00009036 }
9037 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00009038 }
9039 return rc;
9040}
drha154dcd2006-03-22 22:10:07 +00009041#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00009042
danielk1977b4e9af92007-05-01 17:49:49 +00009043#ifndef SQLITE_OMIT_INCRBLOB
9044/*
9045** Argument pCsr must be a cursor opened for writing on an
9046** INTKEY table currently pointing at a valid table entry.
9047** This function modifies the data stored as part of that entry.
danielk1977ecaecf92009-07-08 08:05:35 +00009048**
9049** Only the data content may only be modified, it is not possible to
9050** change the length of the data stored. If this function is called with
9051** parameters that attempt to write past the end of the existing data,
9052** no modifications are made and SQLITE_CORRUPT is returned.
danielk1977b4e9af92007-05-01 17:49:49 +00009053*/
danielk1977dcbb5d32007-05-04 18:36:44 +00009054int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
danielk1977c9000e62009-07-08 13:55:28 +00009055 int rc;
drh1fee73e2007-08-29 04:00:57 +00009056 assert( cursorHoldsMutex(pCsr) );
drhe5fe6902007-12-07 18:55:28 +00009057 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
drh036dbec2014-03-11 23:40:44 +00009058 assert( pCsr->curFlags & BTCF_Incrblob );
danielk19773588ceb2008-06-10 17:30:26 +00009059
danielk1977c9000e62009-07-08 13:55:28 +00009060 rc = restoreCursorPosition(pCsr);
9061 if( rc!=SQLITE_OK ){
9062 return rc;
9063 }
danielk19773588ceb2008-06-10 17:30:26 +00009064 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
9065 if( pCsr->eState!=CURSOR_VALID ){
9066 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +00009067 }
9068
dan227a1c42013-04-03 11:17:39 +00009069 /* Save the positions of all other cursors open on this table. This is
9070 ** required in case any of them are holding references to an xFetch
9071 ** version of the b-tree page modified by the accessPayload call below.
drh370c9f42013-04-03 20:04:04 +00009072 **
drh3f387402014-09-24 01:23:00 +00009073 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
drh370c9f42013-04-03 20:04:04 +00009074 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
9075 ** saveAllCursors can only return SQLITE_OK.
dan227a1c42013-04-03 11:17:39 +00009076 */
drh370c9f42013-04-03 20:04:04 +00009077 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
9078 assert( rc==SQLITE_OK );
dan227a1c42013-04-03 11:17:39 +00009079
danielk1977c9000e62009-07-08 13:55:28 +00009080 /* Check some assumptions:
danielk1977dcbb5d32007-05-04 18:36:44 +00009081 ** (a) the cursor is open for writing,
danielk1977c9000e62009-07-08 13:55:28 +00009082 ** (b) there is a read/write transaction open,
9083 ** (c) the connection holds a write-lock on the table (if required),
9084 ** (d) there are no conflicting read-locks, and
9085 ** (e) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00009086 */
drh036dbec2014-03-11 23:40:44 +00009087 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
danielk19774f029602009-07-08 18:45:37 +00009088 return SQLITE_READONLY;
9089 }
drhc9166342012-01-05 23:32:06 +00009090 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
9091 && pCsr->pBt->inTransaction==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +00009092 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
9093 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
danielk1977c9000e62009-07-08 13:55:28 +00009094 assert( pCsr->apPage[pCsr->iPage]->intKey );
danielk1977b4e9af92007-05-01 17:49:49 +00009095
drhfb192682009-07-11 18:26:28 +00009096 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00009097}
danielk19772dec9702007-05-02 16:48:37 +00009098
9099/*
dan5a500af2014-03-11 20:33:04 +00009100** Mark this cursor as an incremental blob cursor.
danielk19772dec9702007-05-02 16:48:37 +00009101*/
dan5a500af2014-03-11 20:33:04 +00009102void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
drh036dbec2014-03-11 23:40:44 +00009103 pCur->curFlags |= BTCF_Incrblob;
danielk19772dec9702007-05-02 16:48:37 +00009104}
danielk1977b4e9af92007-05-01 17:49:49 +00009105#endif
dane04dc882010-04-20 18:53:15 +00009106
9107/*
9108** Set both the "read version" (single byte at byte offset 18) and
9109** "write version" (single byte at byte offset 19) fields in the database
9110** header to iVersion.
9111*/
9112int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
9113 BtShared *pBt = pBtree->pBt;
9114 int rc; /* Return code */
9115
dane04dc882010-04-20 18:53:15 +00009116 assert( iVersion==1 || iVersion==2 );
9117
danb9780022010-04-21 18:37:57 +00009118 /* If setting the version fields to 1, do not automatically open the
9119 ** WAL connection, even if the version fields are currently set to 2.
9120 */
drhc9166342012-01-05 23:32:06 +00009121 pBt->btsFlags &= ~BTS_NO_WAL;
9122 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
danb9780022010-04-21 18:37:57 +00009123
9124 rc = sqlite3BtreeBeginTrans(pBtree, 0);
dane04dc882010-04-20 18:53:15 +00009125 if( rc==SQLITE_OK ){
9126 u8 *aData = pBt->pPage1->aData;
danb9780022010-04-21 18:37:57 +00009127 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
danede6eb82010-04-22 06:27:04 +00009128 rc = sqlite3BtreeBeginTrans(pBtree, 2);
danb9780022010-04-21 18:37:57 +00009129 if( rc==SQLITE_OK ){
9130 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
9131 if( rc==SQLITE_OK ){
9132 aData[18] = (u8)iVersion;
9133 aData[19] = (u8)iVersion;
9134 }
9135 }
9136 }
dane04dc882010-04-20 18:53:15 +00009137 }
9138
drhc9166342012-01-05 23:32:06 +00009139 pBt->btsFlags &= ~BTS_NO_WAL;
dane04dc882010-04-20 18:53:15 +00009140 return rc;
9141}
dan428c2182012-08-06 18:50:11 +00009142
9143/*
drhe0997b32015-03-20 14:57:50 +00009144** set the mask of hint flags for cursor pCsr.
dan428c2182012-08-06 18:50:11 +00009145*/
9146void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
drhe0997b32015-03-20 14:57:50 +00009147 assert( mask==BTREE_BULKLOAD || mask==BTREE_SEEK_EQ || mask==0 );
dan428c2182012-08-06 18:50:11 +00009148 pCsr->hints = mask;
9149}
drh781597f2014-05-21 08:21:07 +00009150
drhe0997b32015-03-20 14:57:50 +00009151#ifdef SQLITE_DEBUG
9152/*
9153** Return true if the cursor has a hint specified. This routine is
9154** only used from within assert() statements
9155*/
9156int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
9157 return (pCsr->hints & mask)!=0;
9158}
9159#endif
9160
drh781597f2014-05-21 08:21:07 +00009161/*
9162** Return true if the given Btree is read-only.
9163*/
9164int sqlite3BtreeIsReadonly(Btree *p){
9165 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
9166}
drhdef68892014-11-04 12:11:23 +00009167
9168/*
9169** Return the size of the header added to each page by this module.
9170*/
drh37c057b2014-12-30 00:57:29 +00009171int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }