blob: b99cab89eca1580722ed5a5fc46a26b6da2b5507 [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 ){
mistachkinfad30392016-02-13 23:43:46 +0000353 return SQLITE_NOMEM_BKPT;
danielk1977aef0bf62005-12-30 16:28:01 +0000354 }
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}
drh5e08d0f2016-06-04 21:05:54 +0000453
454/* Verify that the cursor and the BtShared agree about what is the current
455** database connetion. This is important in shared-cache mode. If the database
456** connection pointers get out-of-sync, it is possible for routines like
457** btreeInitPage() to reference an stale connection pointer that references a
458** a connection that has already closed. This routine is used inside assert()
459** statements only and for the purpose of double-checking that the btree code
460** does keep the database connection pointers up-to-date.
461*/
dan7a2347e2016-01-07 16:43:54 +0000462static int cursorOwnsBtShared(BtCursor *p){
463 assert( cursorHoldsMutex(p) );
464 return (p->pBtree->db==p->pBt->db);
465}
drh1fee73e2007-08-29 04:00:57 +0000466#endif
467
danielk197792d4d7a2007-05-04 12:05:56 +0000468/*
dan5a500af2014-03-11 20:33:04 +0000469** Invalidate the overflow cache of the cursor passed as the first argument.
470** on the shared btree structure pBt.
danielk197792d4d7a2007-05-04 12:05:56 +0000471*/
drh036dbec2014-03-11 23:40:44 +0000472#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
danielk197792d4d7a2007-05-04 12:05:56 +0000473
474/*
475** Invalidate the overflow page-list cache for all cursors opened
476** on the shared btree structure pBt.
477*/
478static void invalidateAllOverflowCache(BtShared *pBt){
479 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000480 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +0000481 for(p=pBt->pCursor; p; p=p->pNext){
482 invalidateOverflowCache(p);
483 }
484}
danielk197796d48e92009-06-29 06:00:37 +0000485
dan5a500af2014-03-11 20:33:04 +0000486#ifndef SQLITE_OMIT_INCRBLOB
danielk197796d48e92009-06-29 06:00:37 +0000487/*
488** This function is called before modifying the contents of a table
drh0ee3dbe2009-10-16 15:05:18 +0000489** to invalidate any incrblob cursors that are open on the
drheeb844a2009-08-08 18:01:07 +0000490** row or one of the rows being modified.
danielk197796d48e92009-06-29 06:00:37 +0000491**
492** If argument isClearTable is true, then the entire contents of the
493** table is about to be deleted. In this case invalidate all incrblob
494** cursors open on any row within the table with root-page pgnoRoot.
495**
496** Otherwise, if argument isClearTable is false, then the row with
497** rowid iRow is being replaced or deleted. In this case invalidate
drh0ee3dbe2009-10-16 15:05:18 +0000498** only those incrblob cursors open on that specific row.
danielk197796d48e92009-06-29 06:00:37 +0000499*/
500static void invalidateIncrblobCursors(
501 Btree *pBtree, /* The database file to check */
danielk197796d48e92009-06-29 06:00:37 +0000502 i64 iRow, /* The rowid that might be changing */
503 int isClearTable /* True if all rows are being deleted */
504){
505 BtCursor *p;
drh69180952015-06-25 13:03:10 +0000506 if( pBtree->hasIncrblobCur==0 ) return;
danielk197796d48e92009-06-29 06:00:37 +0000507 assert( sqlite3BtreeHoldsMutex(pBtree) );
drh69180952015-06-25 13:03:10 +0000508 pBtree->hasIncrblobCur = 0;
509 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
510 if( (p->curFlags & BTCF_Incrblob)!=0 ){
511 pBtree->hasIncrblobCur = 1;
512 if( isClearTable || p->info.nKey==iRow ){
513 p->eState = CURSOR_INVALID;
514 }
danielk197796d48e92009-06-29 06:00:37 +0000515 }
516 }
517}
518
danielk197792d4d7a2007-05-04 12:05:56 +0000519#else
dan5a500af2014-03-11 20:33:04 +0000520 /* Stub function when INCRBLOB is omitted */
drheeb844a2009-08-08 18:01:07 +0000521 #define invalidateIncrblobCursors(x,y,z)
drh0ee3dbe2009-10-16 15:05:18 +0000522#endif /* SQLITE_OMIT_INCRBLOB */
danielk197792d4d7a2007-05-04 12:05:56 +0000523
drh980b1a72006-08-16 16:42:48 +0000524/*
danielk1977bea2a942009-01-20 17:06:27 +0000525** Set bit pgno of the BtShared.pHasContent bitvec. This is called
526** when a page that previously contained data becomes a free-list leaf
527** page.
528**
529** The BtShared.pHasContent bitvec exists to work around an obscure
530** bug caused by the interaction of two useful IO optimizations surrounding
531** free-list leaf pages:
532**
533** 1) When all data is deleted from a page and the page becomes
534** a free-list leaf page, the page is not written to the database
535** (as free-list leaf pages contain no meaningful data). Sometimes
536** such a page is not even journalled (as it will not be modified,
537** why bother journalling it?).
538**
539** 2) When a free-list leaf page is reused, its content is not read
540** from the database or written to the journal file (why should it
541** be, if it is not at all meaningful?).
542**
543** By themselves, these optimizations work fine and provide a handy
544** performance boost to bulk delete or insert operations. However, if
545** a page is moved to the free-list and then reused within the same
546** transaction, a problem comes up. If the page is not journalled when
547** it is moved to the free-list and it is also not journalled when it
548** is extracted from the free-list and reused, then the original data
549** may be lost. In the event of a rollback, it may not be possible
550** to restore the database to its original configuration.
551**
552** The solution is the BtShared.pHasContent bitvec. Whenever a page is
553** moved to become a free-list leaf page, the corresponding bit is
554** set in the bitvec. Whenever a leaf page is extracted from the free-list,
drh0ee3dbe2009-10-16 15:05:18 +0000555** optimization 2 above is omitted if the corresponding bit is already
danielk1977bea2a942009-01-20 17:06:27 +0000556** set in BtShared.pHasContent. The contents of the bitvec are cleared
557** at the end of every transaction.
558*/
559static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
560 int rc = SQLITE_OK;
561 if( !pBt->pHasContent ){
drhdd3cd972010-03-27 17:12:36 +0000562 assert( pgno<=pBt->nPage );
563 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
drh4c301aa2009-07-15 17:25:45 +0000564 if( !pBt->pHasContent ){
mistachkinfad30392016-02-13 23:43:46 +0000565 rc = SQLITE_NOMEM_BKPT;
danielk1977bea2a942009-01-20 17:06:27 +0000566 }
567 }
568 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
569 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
570 }
571 return rc;
572}
573
574/*
575** Query the BtShared.pHasContent vector.
576**
577** This function is called when a free-list leaf page is removed from the
578** free-list for reuse. It returns false if it is safe to retrieve the
579** page from the pager layer with the 'no-content' flag set. True otherwise.
580*/
581static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
582 Bitvec *p = pBt->pHasContent;
583 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
584}
585
586/*
587** Clear (destroy) the BtShared.pHasContent bitvec. This should be
588** invoked at the conclusion of each write-transaction.
589*/
590static void btreeClearHasContent(BtShared *pBt){
591 sqlite3BitvecDestroy(pBt->pHasContent);
592 pBt->pHasContent = 0;
593}
594
595/*
drh138eeeb2013-03-27 03:15:23 +0000596** Release all of the apPage[] pages for a cursor.
597*/
598static void btreeReleaseAllCursorPages(BtCursor *pCur){
599 int i;
600 for(i=0; i<=pCur->iPage; i++){
601 releasePage(pCur->apPage[i]);
602 pCur->apPage[i] = 0;
603 }
604 pCur->iPage = -1;
605}
606
danf0ee1d32015-09-12 19:26:11 +0000607/*
608** The cursor passed as the only argument must point to a valid entry
609** when this function is called (i.e. have eState==CURSOR_VALID). This
610** function saves the current cursor key in variables pCur->nKey and
611** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
612** code otherwise.
613**
614** If the cursor is open on an intkey table, then the integer key
615** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
616** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
617** set to point to a malloced buffer pCur->nKey bytes in size containing
618** the key.
619*/
620static int saveCursorKey(BtCursor *pCur){
drha7c90c42016-06-04 20:37:10 +0000621 int rc = SQLITE_OK;
danf0ee1d32015-09-12 19:26:11 +0000622 assert( CURSOR_VALID==pCur->eState );
623 assert( 0==pCur->pKey );
624 assert( cursorHoldsMutex(pCur) );
625
drha7c90c42016-06-04 20:37:10 +0000626 if( pCur->curIntKey ){
627 /* Only the rowid is required for a table btree */
628 pCur->nKey = sqlite3BtreeIntegerKey(pCur);
629 }else{
630 /* For an index btree, save the complete key content */
drhd66c4f82016-06-04 20:58:35 +0000631 void *pKey;
drha7c90c42016-06-04 20:37:10 +0000632 pCur->nKey = sqlite3BtreePayloadSize(pCur);
drhd66c4f82016-06-04 20:58:35 +0000633 pKey = sqlite3Malloc( pCur->nKey );
danf0ee1d32015-09-12 19:26:11 +0000634 if( pKey ){
drhcb3cabd2016-11-25 19:18:28 +0000635 rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
danf0ee1d32015-09-12 19:26:11 +0000636 if( rc==SQLITE_OK ){
637 pCur->pKey = pKey;
638 }else{
639 sqlite3_free(pKey);
640 }
641 }else{
mistachkinfad30392016-02-13 23:43:46 +0000642 rc = SQLITE_NOMEM_BKPT;
danf0ee1d32015-09-12 19:26:11 +0000643 }
644 }
645 assert( !pCur->curIntKey || !pCur->pKey );
646 return rc;
647}
drh138eeeb2013-03-27 03:15:23 +0000648
649/*
drh980b1a72006-08-16 16:42:48 +0000650** Save the current cursor position in the variables BtCursor.nKey
651** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
drhea8ffdf2009-07-22 00:35:23 +0000652**
653** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
654** prior to calling this routine.
drh980b1a72006-08-16 16:42:48 +0000655*/
656static int saveCursorPosition(BtCursor *pCur){
657 int rc;
658
drhd2f83132015-03-25 17:35:01 +0000659 assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
drh980b1a72006-08-16 16:42:48 +0000660 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000661 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000662
drhd2f83132015-03-25 17:35:01 +0000663 if( pCur->eState==CURSOR_SKIPNEXT ){
664 pCur->eState = CURSOR_VALID;
665 }else{
666 pCur->skipNext = 0;
667 }
drh980b1a72006-08-16 16:42:48 +0000668
danf0ee1d32015-09-12 19:26:11 +0000669 rc = saveCursorKey(pCur);
drh980b1a72006-08-16 16:42:48 +0000670 if( rc==SQLITE_OK ){
drh138eeeb2013-03-27 03:15:23 +0000671 btreeReleaseAllCursorPages(pCur);
drh980b1a72006-08-16 16:42:48 +0000672 pCur->eState = CURSOR_REQUIRESEEK;
673 }
674
dane755e102015-09-30 12:59:12 +0000675 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
drh980b1a72006-08-16 16:42:48 +0000676 return rc;
677}
678
drh637f3d82014-08-22 22:26:07 +0000679/* Forward reference */
680static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
681
drh980b1a72006-08-16 16:42:48 +0000682/*
drh0ee3dbe2009-10-16 15:05:18 +0000683** Save the positions of all cursors (except pExcept) that are open on
drh637f3d82014-08-22 22:26:07 +0000684** the table with root-page iRoot. "Saving the cursor position" means that
685** the location in the btree is remembered in such a way that it can be
686** moved back to the same spot after the btree has been modified. This
687** routine is called just before cursor pExcept is used to modify the
688** table, for example in BtreeDelete() or BtreeInsert().
689**
drh27fb7462015-06-30 02:47:36 +0000690** If there are two or more cursors on the same btree, then all such
691** cursors should have their BTCF_Multiple flag set. The btreeCursor()
692** routine enforces that rule. This routine only needs to be called in
693** the uncommon case when pExpect has the BTCF_Multiple flag set.
694**
695** If pExpect!=NULL and if no other cursors are found on the same root-page,
696** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
697** pointless call to this routine.
698**
drh637f3d82014-08-22 22:26:07 +0000699** Implementation note: This routine merely checks to see if any cursors
700** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
701** event that cursors are in need to being saved.
drh980b1a72006-08-16 16:42:48 +0000702*/
703static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
704 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000705 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000706 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000707 for(p=pBt->pCursor; p; p=p->pNext){
drh637f3d82014-08-22 22:26:07 +0000708 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
709 }
drh27fb7462015-06-30 02:47:36 +0000710 if( p ) return saveCursorsOnList(p, iRoot, pExcept);
711 if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
712 return SQLITE_OK;
drh637f3d82014-08-22 22:26:07 +0000713}
714
715/* This helper routine to saveAllCursors does the actual work of saving
716** the cursors if and when a cursor is found that actually requires saving.
717** The common case is that no cursors need to be saved, so this routine is
718** broken out from its caller to avoid unnecessary stack pointer movement.
719*/
720static int SQLITE_NOINLINE saveCursorsOnList(
drh3f387402014-09-24 01:23:00 +0000721 BtCursor *p, /* The first cursor that needs saving */
722 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
723 BtCursor *pExcept /* Do not save this cursor */
drh637f3d82014-08-22 22:26:07 +0000724){
725 do{
drh138eeeb2013-03-27 03:15:23 +0000726 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
drhd2f83132015-03-25 17:35:01 +0000727 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
drh138eeeb2013-03-27 03:15:23 +0000728 int rc = saveCursorPosition(p);
729 if( SQLITE_OK!=rc ){
730 return rc;
731 }
732 }else{
733 testcase( p->iPage>0 );
734 btreeReleaseAllCursorPages(p);
drh980b1a72006-08-16 16:42:48 +0000735 }
736 }
drh637f3d82014-08-22 22:26:07 +0000737 p = p->pNext;
738 }while( p );
drh980b1a72006-08-16 16:42:48 +0000739 return SQLITE_OK;
740}
741
742/*
drhbf700f32007-03-31 02:36:44 +0000743** Clear the current cursor position.
744*/
danielk1977be51a652008-10-08 17:58:48 +0000745void sqlite3BtreeClearCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000746 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000747 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +0000748 pCur->pKey = 0;
749 pCur->eState = CURSOR_INVALID;
750}
751
752/*
danielk19773509a652009-07-06 18:56:13 +0000753** In this version of BtreeMoveto, pKey is a packed index record
754** such as is generated by the OP_MakeRecord opcode. Unpack the
755** record and then call BtreeMovetoUnpacked() to do the work.
756*/
757static int btreeMoveto(
758 BtCursor *pCur, /* Cursor open on the btree to be searched */
759 const void *pKey, /* Packed key if the btree is an index */
760 i64 nKey, /* Integer key for tables. Size of pKey for indices */
761 int bias, /* Bias search to the high end */
762 int *pRes /* Write search results here */
763){
764 int rc; /* Status code */
765 UnpackedRecord *pIdxKey; /* Unpacked index key */
danielk19773509a652009-07-06 18:56:13 +0000766
767 if( pKey ){
768 assert( nKey==(i64)(int)nKey );
drha582b012016-12-21 19:45:54 +0000769 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pCur->pKeyInfo);
mistachkinfad30392016-02-13 23:43:46 +0000770 if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
mistachkin0fe5f952011-09-14 18:19:08 +0000771 sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
drh094b7582013-11-30 12:49:28 +0000772 if( pIdxKey->nField==0 ){
drha582b012016-12-21 19:45:54 +0000773 rc = SQLITE_CORRUPT_BKPT;
774 goto moveto_done;
drh094b7582013-11-30 12:49:28 +0000775 }
danielk19773509a652009-07-06 18:56:13 +0000776 }else{
777 pIdxKey = 0;
778 }
779 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
drha582b012016-12-21 19:45:54 +0000780moveto_done:
781 if( pIdxKey ){
782 sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
danielk19773509a652009-07-06 18:56:13 +0000783 }
784 return rc;
785}
786
787/*
drh980b1a72006-08-16 16:42:48 +0000788** Restore the cursor to the position it was in (or as close to as possible)
789** when saveCursorPosition() was called. Note that this call deletes the
790** saved position info stored by saveCursorPosition(), so there can be
drha3460582008-07-11 21:02:53 +0000791** at most one effective restoreCursorPosition() call after each
drh980b1a72006-08-16 16:42:48 +0000792** saveCursorPosition().
drh980b1a72006-08-16 16:42:48 +0000793*/
danielk197730548662009-07-09 05:07:37 +0000794static int btreeRestoreCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000795 int rc;
drhd2f83132015-03-25 17:35:01 +0000796 int skipNext;
dan7a2347e2016-01-07 16:43:54 +0000797 assert( cursorOwnsBtShared(pCur) );
drhfb982642007-08-30 01:19:59 +0000798 assert( pCur->eState>=CURSOR_REQUIRESEEK );
799 if( pCur->eState==CURSOR_FAULT ){
drh4c301aa2009-07-15 17:25:45 +0000800 return pCur->skipNext;
drhfb982642007-08-30 01:19:59 +0000801 }
drh980b1a72006-08-16 16:42:48 +0000802 pCur->eState = CURSOR_INVALID;
drhd2f83132015-03-25 17:35:01 +0000803 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
drh980b1a72006-08-16 16:42:48 +0000804 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +0000805 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +0000806 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +0000807 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drhd2f83132015-03-25 17:35:01 +0000808 pCur->skipNext |= skipNext;
drh9b47ee32013-08-20 03:13:51 +0000809 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
810 pCur->eState = CURSOR_SKIPNEXT;
811 }
drh980b1a72006-08-16 16:42:48 +0000812 }
813 return rc;
814}
815
drha3460582008-07-11 21:02:53 +0000816#define restoreCursorPosition(p) \
drhfb982642007-08-30 01:19:59 +0000817 (p->eState>=CURSOR_REQUIRESEEK ? \
danielk197730548662009-07-09 05:07:37 +0000818 btreeRestoreCursorPosition(p) : \
drh16a9b832007-05-05 18:39:25 +0000819 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +0000820
drha3460582008-07-11 21:02:53 +0000821/*
drh6848dad2014-08-22 23:33:03 +0000822** Determine whether or not a cursor has moved from the position where
823** it was last placed, or has been invalidated for any other reason.
824** Cursors can move when the row they are pointing at is deleted out
825** from under them, for example. Cursor might also move if a btree
826** is rebalanced.
drha3460582008-07-11 21:02:53 +0000827**
drh6848dad2014-08-22 23:33:03 +0000828** Calling this routine with a NULL cursor pointer returns false.
drh86dd3712014-03-25 11:00:21 +0000829**
drh6848dad2014-08-22 23:33:03 +0000830** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
831** back to where it ought to be if this routine returns true.
drha3460582008-07-11 21:02:53 +0000832*/
drh6848dad2014-08-22 23:33:03 +0000833int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
drhc22284f2014-10-13 16:02:20 +0000834 return pCur->eState!=CURSOR_VALID;
drh6848dad2014-08-22 23:33:03 +0000835}
836
837/*
838** This routine restores a cursor back to its original position after it
839** has been moved by some outside activity (such as a btree rebalance or
840** a row having been deleted out from under the cursor).
841**
842** On success, the *pDifferentRow parameter is false if the cursor is left
843** pointing at exactly the same row. *pDifferntRow is the row the cursor
844** was pointing to has been deleted, forcing the cursor to point to some
845** nearby row.
846**
847** This routine should only be called for a cursor that just returned
848** TRUE from sqlite3BtreeCursorHasMoved().
849*/
850int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
drha3460582008-07-11 21:02:53 +0000851 int rc;
852
drh6848dad2014-08-22 23:33:03 +0000853 assert( pCur!=0 );
854 assert( pCur->eState!=CURSOR_VALID );
drha3460582008-07-11 21:02:53 +0000855 rc = restoreCursorPosition(pCur);
856 if( rc ){
drh6848dad2014-08-22 23:33:03 +0000857 *pDifferentRow = 1;
drha3460582008-07-11 21:02:53 +0000858 return rc;
859 }
drh606a3572015-03-25 18:29:10 +0000860 if( pCur->eState!=CURSOR_VALID ){
drh6848dad2014-08-22 23:33:03 +0000861 *pDifferentRow = 1;
drha3460582008-07-11 21:02:53 +0000862 }else{
drh606a3572015-03-25 18:29:10 +0000863 assert( pCur->skipNext==0 );
drh6848dad2014-08-22 23:33:03 +0000864 *pDifferentRow = 0;
drha3460582008-07-11 21:02:53 +0000865 }
866 return SQLITE_OK;
867}
868
drhf7854c72015-10-27 13:24:37 +0000869#ifdef SQLITE_ENABLE_CURSOR_HINTS
drh28935362013-12-07 20:39:19 +0000870/*
drh0df57012015-08-14 15:05:55 +0000871** Provide hints to the cursor. The particular hint given (and the type
872** and number of the varargs parameters) is determined by the eHintType
873** parameter. See the definitions of the BTREE_HINT_* macros for details.
drh28935362013-12-07 20:39:19 +0000874*/
drh0df57012015-08-14 15:05:55 +0000875void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
drhf7854c72015-10-27 13:24:37 +0000876 /* Used only by system that substitute their own storage engine */
drh28935362013-12-07 20:39:19 +0000877}
drhf7854c72015-10-27 13:24:37 +0000878#endif
879
880/*
881** Provide flag hints to the cursor.
882*/
883void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
884 assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
885 pCur->hints = x;
886}
887
drh28935362013-12-07 20:39:19 +0000888
danielk1977599fcba2004-11-08 07:13:13 +0000889#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000890/*
drha3152892007-05-05 11:48:52 +0000891** Given a page number of a regular database page, return the page
892** number for the pointer-map page that contains the entry for the
893** input page number.
drh5f77b2e2010-08-21 15:09:37 +0000894**
895** Return 0 (not a valid page) for pgno==1 since there is
896** no pointer map associated with page 1. The integrity_check logic
897** requires that ptrmapPageno(*,1)!=1.
danielk1977afcdd022004-10-31 16:25:42 +0000898*/
danielk1977266664d2006-02-10 08:24:21 +0000899static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
danielk197789d40042008-11-17 14:20:56 +0000900 int nPagesPerMapPage;
901 Pgno iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +0000902 assert( sqlite3_mutex_held(pBt->mutex) );
drh5f77b2e2010-08-21 15:09:37 +0000903 if( pgno<2 ) return 0;
drhd677b3d2007-08-20 22:48:41 +0000904 nPagesPerMapPage = (pBt->usableSize/5)+1;
905 iPtrMap = (pgno-2)/nPagesPerMapPage;
906 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +0000907 if( ret==PENDING_BYTE_PAGE(pBt) ){
908 ret++;
909 }
910 return ret;
911}
danielk1977a19df672004-11-03 11:37:07 +0000912
danielk1977afcdd022004-10-31 16:25:42 +0000913/*
danielk1977afcdd022004-10-31 16:25:42 +0000914** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000915**
916** This routine updates the pointer map entry for page number 'key'
917** so that it maps to type 'eType' and parent page number 'pgno'.
drh98add2e2009-07-20 17:11:49 +0000918**
919** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
920** a no-op. If an error occurs, the appropriate error code is written
921** into *pRC.
danielk1977afcdd022004-10-31 16:25:42 +0000922*/
drh98add2e2009-07-20 17:11:49 +0000923static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
danielk19773b8a05f2007-03-19 17:44:26 +0000924 DbPage *pDbPage; /* The pointer map page */
925 u8 *pPtrmap; /* The pointer map data */
926 Pgno iPtrmap; /* The pointer map page number */
927 int offset; /* Offset in pointer map page */
drh98add2e2009-07-20 17:11:49 +0000928 int rc; /* Return code from subfunctions */
929
930 if( *pRC ) return;
danielk1977afcdd022004-10-31 16:25:42 +0000931
drh1fee73e2007-08-29 04:00:57 +0000932 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977266664d2006-02-10 08:24:21 +0000933 /* The master-journal page number must never be used as a pointer map page */
934 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
935
danielk1977ac11ee62005-01-15 12:45:51 +0000936 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000937 if( key==0 ){
drh98add2e2009-07-20 17:11:49 +0000938 *pRC = SQLITE_CORRUPT_BKPT;
939 return;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000940 }
danielk1977266664d2006-02-10 08:24:21 +0000941 iPtrmap = PTRMAP_PAGENO(pBt, key);
drh9584f582015-11-04 20:22:37 +0000942 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
danielk1977687566d2004-11-02 12:56:41 +0000943 if( rc!=SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +0000944 *pRC = rc;
945 return;
danielk1977afcdd022004-10-31 16:25:42 +0000946 }
danielk19778c666b12008-07-18 09:34:57 +0000947 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drhacfc72b2009-06-05 18:44:15 +0000948 if( offset<0 ){
drh98add2e2009-07-20 17:11:49 +0000949 *pRC = SQLITE_CORRUPT_BKPT;
drh4925a552009-07-07 11:39:58 +0000950 goto ptrmap_exit;
drhacfc72b2009-06-05 18:44:15 +0000951 }
drhfc243732011-05-17 15:21:56 +0000952 assert( offset <= (int)pBt->usableSize-5 );
danielk19773b8a05f2007-03-19 17:44:26 +0000953 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000954
drh615ae552005-01-16 23:21:00 +0000955 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
956 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
drh98add2e2009-07-20 17:11:49 +0000957 *pRC= rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000958 if( rc==SQLITE_OK ){
959 pPtrmap[offset] = eType;
960 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000961 }
danielk1977afcdd022004-10-31 16:25:42 +0000962 }
963
drh4925a552009-07-07 11:39:58 +0000964ptrmap_exit:
danielk19773b8a05f2007-03-19 17:44:26 +0000965 sqlite3PagerUnref(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000966}
967
968/*
969** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000970**
971** This routine retrieves the pointer map entry for page 'key', writing
972** the type and parent page number to *pEType and *pPgno respectively.
973** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000974*/
danielk1977aef0bf62005-12-30 16:28:01 +0000975static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000976 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000977 int iPtrmap; /* Pointer map page index */
978 u8 *pPtrmap; /* Pointer map page data */
979 int offset; /* Offset of entry in pointer map */
980 int rc;
981
drh1fee73e2007-08-29 04:00:57 +0000982 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000983
danielk1977266664d2006-02-10 08:24:21 +0000984 iPtrmap = PTRMAP_PAGENO(pBt, key);
drh9584f582015-11-04 20:22:37 +0000985 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +0000986 if( rc!=0 ){
987 return rc;
988 }
danielk19773b8a05f2007-03-19 17:44:26 +0000989 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000990
danielk19778c666b12008-07-18 09:34:57 +0000991 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drhfc243732011-05-17 15:21:56 +0000992 if( offset<0 ){
993 sqlite3PagerUnref(pDbPage);
994 return SQLITE_CORRUPT_BKPT;
995 }
996 assert( offset <= (int)pBt->usableSize-5 );
drh43617e92006-03-06 20:55:46 +0000997 assert( pEType!=0 );
998 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +0000999 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +00001000
danielk19773b8a05f2007-03-19 17:44:26 +00001001 sqlite3PagerUnref(pDbPage);
drh49285702005-09-17 15:20:26 +00001002 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +00001003 return SQLITE_OK;
1004}
1005
danielk197785d90ca2008-07-19 14:25:15 +00001006#else /* if defined SQLITE_OMIT_AUTOVACUUM */
drh98add2e2009-07-20 17:11:49 +00001007 #define ptrmapPut(w,x,y,z,rc)
danielk197785d90ca2008-07-19 14:25:15 +00001008 #define ptrmapGet(w,x,y,z) SQLITE_OK
drh98add2e2009-07-20 17:11:49 +00001009 #define ptrmapPutOvflPtr(x, y, rc)
danielk197785d90ca2008-07-19 14:25:15 +00001010#endif
danielk1977afcdd022004-10-31 16:25:42 +00001011
drh0d316a42002-08-11 20:10:47 +00001012/*
drh271efa52004-05-30 19:19:05 +00001013** Given a btree page and a cell index (0 means the first cell on
1014** the page, 1 means the second cell, and so forth) return a pointer
1015** to the cell content.
1016**
drhf44890a2015-06-27 03:58:15 +00001017** findCellPastPtr() does the same except it skips past the initial
1018** 4-byte child pointer found on interior pages, if there is one.
1019**
drh271efa52004-05-30 19:19:05 +00001020** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +00001021*/
drh1688c862008-07-18 02:44:17 +00001022#define findCell(P,I) \
drh329428e2015-06-30 13:28:18 +00001023 ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
drhf44890a2015-06-27 03:58:15 +00001024#define findCellPastPtr(P,I) \
drh329428e2015-06-30 13:28:18 +00001025 ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
drh68f2a572011-06-03 17:50:49 +00001026
drh43605152004-05-29 21:46:49 +00001027
1028/*
drh5fa60512015-06-19 17:19:34 +00001029** This is common tail processing for btreeParseCellPtr() and
1030** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
1031** on a single B-tree page. Make necessary adjustments to the CellInfo
1032** structure.
drh43605152004-05-29 21:46:49 +00001033*/
drh5fa60512015-06-19 17:19:34 +00001034static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
1035 MemPage *pPage, /* Page containing the cell */
1036 u8 *pCell, /* Pointer to the cell text. */
1037 CellInfo *pInfo /* Fill in this structure */
1038){
1039 /* If the payload will not fit completely on the local page, we have
1040 ** to decide how much to store locally and how much to spill onto
1041 ** overflow pages. The strategy is to minimize the amount of unused
1042 ** space on overflow pages while keeping the amount of local storage
1043 ** in between minLocal and maxLocal.
1044 **
1045 ** Warning: changing the way overflow payload is distributed in any
1046 ** way will result in an incompatible file format.
1047 */
1048 int minLocal; /* Minimum amount of payload held locally */
1049 int maxLocal; /* Maximum amount of payload held locally */
1050 int surplus; /* Overflow payload available for local storage */
1051
1052 minLocal = pPage->minLocal;
1053 maxLocal = pPage->maxLocal;
1054 surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
1055 testcase( surplus==maxLocal );
1056 testcase( surplus==maxLocal+1 );
1057 if( surplus <= maxLocal ){
1058 pInfo->nLocal = (u16)surplus;
1059 }else{
1060 pInfo->nLocal = (u16)minLocal;
drh43605152004-05-29 21:46:49 +00001061 }
drh45ac1c72015-12-18 03:59:16 +00001062 pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
drh43605152004-05-29 21:46:49 +00001063}
1064
1065/*
drh5fa60512015-06-19 17:19:34 +00001066** The following routines are implementations of the MemPage.xParseCell()
1067** method.
danielk19771cc5ed82007-05-16 17:28:43 +00001068**
drh5fa60512015-06-19 17:19:34 +00001069** Parse a cell content block and fill in the CellInfo structure.
1070**
1071** btreeParseCellPtr() => table btree leaf nodes
1072** btreeParseCellNoPayload() => table btree internal nodes
1073** btreeParseCellPtrIndex() => index btree nodes
1074**
1075** There is also a wrapper function btreeParseCell() that works for
1076** all MemPage types and that references the cell by index rather than
1077** by pointer.
drh43605152004-05-29 21:46:49 +00001078*/
drh5fa60512015-06-19 17:19:34 +00001079static void btreeParseCellPtrNoPayload(
1080 MemPage *pPage, /* Page containing the cell */
1081 u8 *pCell, /* Pointer to the cell text. */
1082 CellInfo *pInfo /* Fill in this structure */
1083){
1084 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1085 assert( pPage->leaf==0 );
drh5fa60512015-06-19 17:19:34 +00001086 assert( pPage->childPtrSize==4 );
drh94a31152015-07-01 04:08:40 +00001087#ifndef SQLITE_DEBUG
1088 UNUSED_PARAMETER(pPage);
1089#endif
drh5fa60512015-06-19 17:19:34 +00001090 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
1091 pInfo->nPayload = 0;
1092 pInfo->nLocal = 0;
drh5fa60512015-06-19 17:19:34 +00001093 pInfo->pPayload = 0;
1094 return;
1095}
danielk197730548662009-07-09 05:07:37 +00001096static void btreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +00001097 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +00001098 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +00001099 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +00001100){
drh3e28ff52014-09-24 00:59:08 +00001101 u8 *pIter; /* For scanning through pCell */
drh271efa52004-05-30 19:19:05 +00001102 u32 nPayload; /* Number of bytes of cell payload */
drh56cb04e2015-06-19 18:24:37 +00001103 u64 iKey; /* Extracted Key value */
drh43605152004-05-29 21:46:49 +00001104
drh1fee73e2007-08-29 04:00:57 +00001105 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhab01f612004-05-22 02:55:23 +00001106 assert( pPage->leaf==0 || pPage->leaf==1 );
drh5fa60512015-06-19 17:19:34 +00001107 assert( pPage->intKeyLeaf );
1108 assert( pPage->childPtrSize==0 );
drh56cb04e2015-06-19 18:24:37 +00001109 pIter = pCell;
1110
1111 /* The next block of code is equivalent to:
1112 **
1113 ** pIter += getVarint32(pIter, nPayload);
1114 **
1115 ** The code is inlined to avoid a function call.
1116 */
1117 nPayload = *pIter;
1118 if( nPayload>=0x80 ){
drheeab2c62015-06-19 20:08:39 +00001119 u8 *pEnd = &pIter[8];
drh56cb04e2015-06-19 18:24:37 +00001120 nPayload &= 0x7f;
1121 do{
1122 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1123 }while( (*pIter)>=0x80 && pIter<pEnd );
drh6f11bef2004-05-13 01:12:56 +00001124 }
drh56cb04e2015-06-19 18:24:37 +00001125 pIter++;
1126
1127 /* The next block of code is equivalent to:
1128 **
1129 ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
1130 **
1131 ** The code is inlined to avoid a function call.
1132 */
1133 iKey = *pIter;
1134 if( iKey>=0x80 ){
1135 u8 *pEnd = &pIter[7];
1136 iKey &= 0x7f;
1137 while(1){
1138 iKey = (iKey<<7) | (*++pIter & 0x7f);
1139 if( (*pIter)<0x80 ) break;
1140 if( pIter>=pEnd ){
1141 iKey = (iKey<<8) | *++pIter;
1142 break;
1143 }
1144 }
1145 }
1146 pIter++;
1147
1148 pInfo->nKey = *(i64*)&iKey;
drh72365832007-03-06 15:53:44 +00001149 pInfo->nPayload = nPayload;
drhab1cc582014-09-23 21:25:19 +00001150 pInfo->pPayload = pIter;
drh0a45c272009-07-08 01:49:11 +00001151 testcase( nPayload==pPage->maxLocal );
1152 testcase( nPayload==pPage->maxLocal+1 );
drhab1cc582014-09-23 21:25:19 +00001153 if( nPayload<=pPage->maxLocal ){
drh271efa52004-05-30 19:19:05 +00001154 /* This is the (easy) common case where the entire payload fits
1155 ** on the local page. No overflow is required.
1156 */
drhab1cc582014-09-23 21:25:19 +00001157 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1158 if( pInfo->nSize<4 ) pInfo->nSize = 4;
drhf49661a2008-12-10 16:45:50 +00001159 pInfo->nLocal = (u16)nPayload;
drh6f11bef2004-05-13 01:12:56 +00001160 }else{
drh5fa60512015-06-19 17:19:34 +00001161 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
drh6f11bef2004-05-13 01:12:56 +00001162 }
drh3aac2dd2004-04-26 14:10:20 +00001163}
drh5fa60512015-06-19 17:19:34 +00001164static void btreeParseCellPtrIndex(
1165 MemPage *pPage, /* Page containing the cell */
1166 u8 *pCell, /* Pointer to the cell text. */
1167 CellInfo *pInfo /* Fill in this structure */
1168){
1169 u8 *pIter; /* For scanning through pCell */
1170 u32 nPayload; /* Number of bytes of cell payload */
drh3aac2dd2004-04-26 14:10:20 +00001171
drh5fa60512015-06-19 17:19:34 +00001172 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1173 assert( pPage->leaf==0 || pPage->leaf==1 );
1174 assert( pPage->intKeyLeaf==0 );
drh5fa60512015-06-19 17:19:34 +00001175 pIter = pCell + pPage->childPtrSize;
1176 nPayload = *pIter;
1177 if( nPayload>=0x80 ){
drheeab2c62015-06-19 20:08:39 +00001178 u8 *pEnd = &pIter[8];
drh5fa60512015-06-19 17:19:34 +00001179 nPayload &= 0x7f;
1180 do{
1181 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1182 }while( *(pIter)>=0x80 && pIter<pEnd );
1183 }
1184 pIter++;
1185 pInfo->nKey = nPayload;
1186 pInfo->nPayload = nPayload;
1187 pInfo->pPayload = pIter;
1188 testcase( nPayload==pPage->maxLocal );
1189 testcase( nPayload==pPage->maxLocal+1 );
1190 if( nPayload<=pPage->maxLocal ){
1191 /* This is the (easy) common case where the entire payload fits
1192 ** on the local page. No overflow is required.
1193 */
1194 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1195 if( pInfo->nSize<4 ) pInfo->nSize = 4;
1196 pInfo->nLocal = (u16)nPayload;
drh5fa60512015-06-19 17:19:34 +00001197 }else{
1198 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
drh3aac2dd2004-04-26 14:10:20 +00001199 }
1200}
danielk197730548662009-07-09 05:07:37 +00001201static void btreeParseCell(
drh43605152004-05-29 21:46:49 +00001202 MemPage *pPage, /* Page containing the cell */
1203 int iCell, /* The cell index. First cell is 0 */
1204 CellInfo *pInfo /* Fill in this structure */
1205){
drh5fa60512015-06-19 17:19:34 +00001206 pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
drh43605152004-05-29 21:46:49 +00001207}
drh3aac2dd2004-04-26 14:10:20 +00001208
1209/*
drh5fa60512015-06-19 17:19:34 +00001210** The following routines are implementations of the MemPage.xCellSize
1211** method.
1212**
drh43605152004-05-29 21:46:49 +00001213** Compute the total number of bytes that a Cell needs in the cell
1214** data area of the btree-page. The return number includes the cell
1215** data header and the local payload, but not any overflow page or
1216** the space used by the cell pointer.
drh25ada072015-06-19 15:07:14 +00001217**
drh5fa60512015-06-19 17:19:34 +00001218** cellSizePtrNoPayload() => table internal nodes
1219** cellSizePtr() => all index nodes & table leaf nodes
drh3b7511c2001-05-26 13:15:44 +00001220*/
danielk1977ae5558b2009-04-29 11:31:47 +00001221static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
drh3f387402014-09-24 01:23:00 +00001222 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
1223 u8 *pEnd; /* End mark for a varint */
1224 u32 nSize; /* Size value to return */
danielk1977ae5558b2009-04-29 11:31:47 +00001225
1226#ifdef SQLITE_DEBUG
1227 /* The value returned by this function should always be the same as
1228 ** the (CellInfo.nSize) value found by doing a full parse of the
1229 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1230 ** this function verifies that this invariant is not violated. */
1231 CellInfo debuginfo;
drh5fa60512015-06-19 17:19:34 +00001232 pPage->xParseCell(pPage, pCell, &debuginfo);
danielk1977ae5558b2009-04-29 11:31:47 +00001233#endif
1234
drh3e28ff52014-09-24 00:59:08 +00001235 nSize = *pIter;
1236 if( nSize>=0x80 ){
drheeab2c62015-06-19 20:08:39 +00001237 pEnd = &pIter[8];
drh3e28ff52014-09-24 00:59:08 +00001238 nSize &= 0x7f;
1239 do{
1240 nSize = (nSize<<7) | (*++pIter & 0x7f);
1241 }while( *(pIter)>=0x80 && pIter<pEnd );
1242 }
1243 pIter++;
danielk1977ae5558b2009-04-29 11:31:47 +00001244 if( pPage->intKey ){
danielk1977ae5558b2009-04-29 11:31:47 +00001245 /* pIter now points at the 64-bit integer key value, a variable length
1246 ** integer. The following block moves pIter to point at the first byte
1247 ** past the end of the key value. */
1248 pEnd = &pIter[9];
1249 while( (*pIter++)&0x80 && pIter<pEnd );
danielk1977ae5558b2009-04-29 11:31:47 +00001250 }
drh0a45c272009-07-08 01:49:11 +00001251 testcase( nSize==pPage->maxLocal );
1252 testcase( nSize==pPage->maxLocal+1 );
drh3e28ff52014-09-24 00:59:08 +00001253 if( nSize<=pPage->maxLocal ){
1254 nSize += (u32)(pIter - pCell);
1255 if( nSize<4 ) nSize = 4;
1256 }else{
danielk1977ae5558b2009-04-29 11:31:47 +00001257 int minLocal = pPage->minLocal;
1258 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
drh0a45c272009-07-08 01:49:11 +00001259 testcase( nSize==pPage->maxLocal );
1260 testcase( nSize==pPage->maxLocal+1 );
danielk1977ae5558b2009-04-29 11:31:47 +00001261 if( nSize>pPage->maxLocal ){
1262 nSize = minLocal;
1263 }
drh3e28ff52014-09-24 00:59:08 +00001264 nSize += 4 + (u16)(pIter - pCell);
danielk1977ae5558b2009-04-29 11:31:47 +00001265 }
drhdc41d602014-09-22 19:51:35 +00001266 assert( nSize==debuginfo.nSize || CORRUPT_DB );
shane60a4b532009-05-06 18:57:09 +00001267 return (u16)nSize;
danielk1977ae5558b2009-04-29 11:31:47 +00001268}
drh25ada072015-06-19 15:07:14 +00001269static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
1270 u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
1271 u8 *pEnd; /* End mark for a varint */
1272
1273#ifdef SQLITE_DEBUG
1274 /* The value returned by this function should always be the same as
1275 ** the (CellInfo.nSize) value found by doing a full parse of the
1276 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1277 ** this function verifies that this invariant is not violated. */
1278 CellInfo debuginfo;
drh5fa60512015-06-19 17:19:34 +00001279 pPage->xParseCell(pPage, pCell, &debuginfo);
drh94a31152015-07-01 04:08:40 +00001280#else
1281 UNUSED_PARAMETER(pPage);
drh25ada072015-06-19 15:07:14 +00001282#endif
1283
1284 assert( pPage->childPtrSize==4 );
1285 pEnd = pIter + 9;
1286 while( (*pIter++)&0x80 && pIter<pEnd );
1287 assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
1288 return (u16)(pIter - pCell);
1289}
1290
drh0ee3dbe2009-10-16 15:05:18 +00001291
1292#ifdef SQLITE_DEBUG
1293/* This variation on cellSizePtr() is used inside of assert() statements
1294** only. */
drha9121e42008-02-19 14:59:35 +00001295static u16 cellSize(MemPage *pPage, int iCell){
drh25ada072015-06-19 15:07:14 +00001296 return pPage->xCellSize(pPage, findCell(pPage, iCell));
drh43605152004-05-29 21:46:49 +00001297}
danielk1977bc6ada42004-06-30 08:20:16 +00001298#endif
drh3b7511c2001-05-26 13:15:44 +00001299
danielk197779a40da2005-01-16 08:00:01 +00001300#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +00001301/*
danielk197726836652005-01-17 01:33:13 +00001302** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +00001303** to an overflow page, insert an entry into the pointer-map
1304** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +00001305*/
drh98add2e2009-07-20 17:11:49 +00001306static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
drhfa67c3c2008-07-11 02:21:40 +00001307 CellInfo info;
drh98add2e2009-07-20 17:11:49 +00001308 if( *pRC ) return;
drhfa67c3c2008-07-11 02:21:40 +00001309 assert( pCell!=0 );
drh5fa60512015-06-19 17:19:34 +00001310 pPage->xParseCell(pPage, pCell, &info);
drh45ac1c72015-12-18 03:59:16 +00001311 if( info.nLocal<info.nPayload ){
1312 Pgno ovfl = get4byte(&pCell[info.nSize-4]);
drh98add2e2009-07-20 17:11:49 +00001313 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
danielk1977ac11ee62005-01-15 12:45:51 +00001314 }
danielk1977ac11ee62005-01-15 12:45:51 +00001315}
danielk197779a40da2005-01-16 08:00:01 +00001316#endif
1317
danielk1977ac11ee62005-01-15 12:45:51 +00001318
drhda200cc2004-05-09 11:51:38 +00001319/*
dane6d065a2017-02-24 19:58:22 +00001320** Defragment the page given. This routine reorganizes cells within the
1321** page so that there are no free-blocks on the free-block list.
1322**
1323** Parameter nMaxFrag is the maximum amount of fragmented space that may be
1324** present in the page after this routine returns.
drhfdab0262014-11-20 15:30:50 +00001325**
1326** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
1327** b-tree page so that there are no freeblocks or fragment bytes, all
1328** unused bytes are contained in the unallocated space region, and all
1329** cells are packed tightly at the end of the page.
drh365d68f2001-05-11 11:02:46 +00001330*/
dane6d065a2017-02-24 19:58:22 +00001331static int defragmentPage(MemPage *pPage, int nMaxFrag){
drh43605152004-05-29 21:46:49 +00001332 int i; /* Loop counter */
peter.d.reid60ec9142014-09-06 16:39:46 +00001333 int pc; /* Address of the i-th cell */
drh43605152004-05-29 21:46:49 +00001334 int hdr; /* Offset to the page header */
1335 int size; /* Size of a cell */
1336 int usableSize; /* Number of usable bytes on a page */
1337 int cellOffset; /* Offset to the cell pointer array */
drh281b21d2008-08-22 12:57:08 +00001338 int cbrk; /* Offset to the cell content area */
drh43605152004-05-29 21:46:49 +00001339 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +00001340 unsigned char *data; /* The page data */
1341 unsigned char *temp; /* Temp area for cell content */
drh588400b2014-09-27 05:00:25 +00001342 unsigned char *src; /* Source of content */
drh17146622009-07-07 17:38:38 +00001343 int iCellFirst; /* First allowable cell index */
1344 int iCellLast; /* Last possible cell index */
1345
danielk19773b8a05f2007-03-19 17:44:26 +00001346 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001347 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +00001348 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +00001349 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00001350 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh588400b2014-09-27 05:00:25 +00001351 temp = 0;
1352 src = data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +00001353 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001354 cellOffset = pPage->cellOffset;
1355 nCell = pPage->nCell;
1356 assert( nCell==get2byte(&data[hdr+3]) );
dane6d065a2017-02-24 19:58:22 +00001357 iCellFirst = cellOffset + 2*nCell;
dan30741eb2017-03-03 20:02:53 +00001358 usableSize = pPage->pBt->usableSize;
dane6d065a2017-02-24 19:58:22 +00001359
1360 /* This block handles pages with two or fewer free blocks and nMaxFrag
1361 ** or fewer fragmented bytes. In this case it is faster to move the
1362 ** two (or one) blocks of cells using memmove() and add the required
1363 ** offsets to each pointer in the cell-pointer array than it is to
1364 ** reconstruct the entire page. */
1365 if( (int)data[hdr+7]<=nMaxFrag ){
1366 int iFree = get2byte(&data[hdr+1]);
1367 if( iFree ){
1368 int iFree2 = get2byte(&data[iFree]);
dan30741eb2017-03-03 20:02:53 +00001369
1370 /* pageFindSlot() has already verified that free blocks are sorted
1371 ** in order of offset within the page, and that no block extends
1372 ** past the end of the page. Provided the two free slots do not
1373 ** overlap, this guarantees that the memmove() calls below will not
1374 ** overwrite the usableSize byte buffer, even if the database page
1375 ** is corrupt. */
1376 assert( iFree2==0 || iFree2>iFree );
1377 assert( iFree+get2byte(&data[iFree+2]) <= usableSize );
1378 assert( iFree2==0 || iFree2+get2byte(&data[iFree2+2]) <= usableSize );
1379
dane6d065a2017-02-24 19:58:22 +00001380 if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
1381 u8 *pEnd = &data[cellOffset + nCell*2];
1382 u8 *pAddr;
1383 int sz2 = 0;
1384 int sz = get2byte(&data[iFree+2]);
1385 int top = get2byte(&data[hdr+5]);
1386 if( iFree2 ){
dan30741eb2017-03-03 20:02:53 +00001387 if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_BKPT;
dane6d065a2017-02-24 19:58:22 +00001388 sz2 = get2byte(&data[iFree2+2]);
dan30741eb2017-03-03 20:02:53 +00001389 assert( iFree+sz+sz2+iFree2-(iFree+sz) <= usableSize );
dane6d065a2017-02-24 19:58:22 +00001390 memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
1391 sz += sz2;
1392 }
1393 cbrk = top+sz;
dan30741eb2017-03-03 20:02:53 +00001394 assert( cbrk+(iFree-top) <= usableSize );
dane6d065a2017-02-24 19:58:22 +00001395 memmove(&data[cbrk], &data[top], iFree-top);
1396 for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
1397 pc = get2byte(pAddr);
1398 if( pc<iFree ){ put2byte(pAddr, pc+sz); }
1399 else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
1400 }
1401 goto defragment_out;
1402 }
1403 }
1404 }
1405
drh281b21d2008-08-22 12:57:08 +00001406 cbrk = usableSize;
drh17146622009-07-07 17:38:38 +00001407 iCellLast = usableSize - 4;
drh43605152004-05-29 21:46:49 +00001408 for(i=0; i<nCell; i++){
1409 u8 *pAddr; /* The i-th cell pointer */
1410 pAddr = &data[cellOffset + i*2];
1411 pc = get2byte(pAddr);
drh0a45c272009-07-08 01:49:11 +00001412 testcase( pc==iCellFirst );
1413 testcase( pc==iCellLast );
danielk197730548662009-07-09 05:07:37 +00001414 /* These conditions have already been verified in btreeInitPage()
drh1421d982015-05-27 03:46:18 +00001415 ** if PRAGMA cell_size_check=ON.
drh17146622009-07-07 17:38:38 +00001416 */
1417 if( pc<iCellFirst || pc>iCellLast ){
shane0af3f892008-11-12 04:55:34 +00001418 return SQLITE_CORRUPT_BKPT;
1419 }
drh17146622009-07-07 17:38:38 +00001420 assert( pc>=iCellFirst && pc<=iCellLast );
drh25ada072015-06-19 15:07:14 +00001421 size = pPage->xCellSize(pPage, &src[pc]);
drh281b21d2008-08-22 12:57:08 +00001422 cbrk -= size;
drh17146622009-07-07 17:38:38 +00001423 if( cbrk<iCellFirst || pc+size>usableSize ){
1424 return SQLITE_CORRUPT_BKPT;
1425 }
drh7157e1d2009-07-09 13:25:32 +00001426 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
drh0a45c272009-07-08 01:49:11 +00001427 testcase( cbrk+size==usableSize );
drh0a45c272009-07-08 01:49:11 +00001428 testcase( pc+size==usableSize );
drh281b21d2008-08-22 12:57:08 +00001429 put2byte(pAddr, cbrk);
drh588400b2014-09-27 05:00:25 +00001430 if( temp==0 ){
1431 int x;
1432 if( cbrk==pc ) continue;
1433 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1434 x = get2byte(&data[hdr+5]);
1435 memcpy(&temp[x], &data[x], (cbrk+size) - x);
1436 src = temp;
1437 }
1438 memcpy(&data[cbrk], &src[pc], size);
drh2af926b2001-05-15 00:39:25 +00001439 }
dane6d065a2017-02-24 19:58:22 +00001440 data[hdr+7] = 0;
dane6d065a2017-02-24 19:58:22 +00001441
1442 defragment_out:
dan3b2ede12017-02-25 16:24:02 +00001443 if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
1444 return SQLITE_CORRUPT_BKPT;
1445 }
drh17146622009-07-07 17:38:38 +00001446 assert( cbrk>=iCellFirst );
drh281b21d2008-08-22 12:57:08 +00001447 put2byte(&data[hdr+5], cbrk);
drh43605152004-05-29 21:46:49 +00001448 data[hdr+1] = 0;
1449 data[hdr+2] = 0;
drh17146622009-07-07 17:38:38 +00001450 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
drhc5053fb2008-11-27 02:22:10 +00001451 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
shane0af3f892008-11-12 04:55:34 +00001452 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +00001453}
1454
drha059ad02001-04-17 20:09:11 +00001455/*
dan8e9ba0c2014-10-14 17:27:04 +00001456** Search the free-list on page pPg for space to store a cell nByte bytes in
1457** size. If one can be found, return a pointer to the space and remove it
1458** from the free-list.
1459**
1460** If no suitable space can be found on the free-list, return NULL.
1461**
drhba0f9992014-10-30 20:48:44 +00001462** This function may detect corruption within pPg. If corruption is
1463** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
dan61e94c92014-10-27 08:02:16 +00001464**
drhb7580e82015-06-25 18:36:13 +00001465** Slots on the free list that are between 1 and 3 bytes larger than nByte
1466** will be ignored if adding the extra space to the fragmentation count
1467** causes the fragmentation count to exceed 60.
dan8e9ba0c2014-10-14 17:27:04 +00001468*/
drhb7580e82015-06-25 18:36:13 +00001469static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
dan8e9ba0c2014-10-14 17:27:04 +00001470 const int hdr = pPg->hdrOffset;
1471 u8 * const aData = pPg->aData;
drhb7580e82015-06-25 18:36:13 +00001472 int iAddr = hdr + 1;
1473 int pc = get2byte(&aData[iAddr]);
1474 int x;
dan8e9ba0c2014-10-14 17:27:04 +00001475 int usableSize = pPg->pBt->usableSize;
1476
drhb7580e82015-06-25 18:36:13 +00001477 assert( pc>0 );
1478 do{
dan8e9ba0c2014-10-14 17:27:04 +00001479 int size; /* Size of the free slot */
drh113762a2014-11-19 16:36:25 +00001480 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
1481 ** increasing offset. */
dan8e9ba0c2014-10-14 17:27:04 +00001482 if( pc>usableSize-4 || pc<iAddr+4 ){
drhba0f9992014-10-30 20:48:44 +00001483 *pRc = SQLITE_CORRUPT_BKPT;
dan8e9ba0c2014-10-14 17:27:04 +00001484 return 0;
1485 }
drh113762a2014-11-19 16:36:25 +00001486 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
1487 ** freeblock form a big-endian integer which is the size of the freeblock
1488 ** in bytes, including the 4-byte header. */
dan8e9ba0c2014-10-14 17:27:04 +00001489 size = get2byte(&aData[pc+2]);
drhb7580e82015-06-25 18:36:13 +00001490 if( (x = size - nByte)>=0 ){
dan8e9ba0c2014-10-14 17:27:04 +00001491 testcase( x==4 );
1492 testcase( x==3 );
drh24dee9d2015-06-02 19:36:29 +00001493 if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){
1494 *pRc = SQLITE_CORRUPT_BKPT;
1495 return 0;
1496 }else if( x<4 ){
drhfdab0262014-11-20 15:30:50 +00001497 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
1498 ** number of bytes in fragments may not exceed 60. */
drhb7580e82015-06-25 18:36:13 +00001499 if( aData[hdr+7]>57 ) return 0;
1500
dan8e9ba0c2014-10-14 17:27:04 +00001501 /* Remove the slot from the free-list. Update the number of
1502 ** fragmented bytes within the page. */
1503 memcpy(&aData[iAddr], &aData[pc], 2);
1504 aData[hdr+7] += (u8)x;
dan8e9ba0c2014-10-14 17:27:04 +00001505 }else{
1506 /* The slot remains on the free-list. Reduce its size to account
1507 ** for the portion used by the new allocation. */
1508 put2byte(&aData[pc+2], x);
1509 }
1510 return &aData[pc + x];
1511 }
drhb7580e82015-06-25 18:36:13 +00001512 iAddr = pc;
1513 pc = get2byte(&aData[pc]);
1514 }while( pc );
dan8e9ba0c2014-10-14 17:27:04 +00001515
1516 return 0;
1517}
1518
1519/*
danielk19776011a752009-04-01 16:25:32 +00001520** Allocate nByte bytes of space from within the B-Tree page passed
drh0a45c272009-07-08 01:49:11 +00001521** as the first argument. Write into *pIdx the index into pPage->aData[]
1522** of the first byte of allocated space. Return either SQLITE_OK or
1523** an error code (usually SQLITE_CORRUPT).
drhbd03cae2001-06-02 02:40:57 +00001524**
drh0a45c272009-07-08 01:49:11 +00001525** The caller guarantees that there is sufficient space to make the
1526** allocation. This routine might need to defragment in order to bring
1527** all the space together, however. This routine will avoid using
1528** the first two bytes past the cell pointer area since presumably this
1529** allocation is being made in order to insert a new cell, so we will
1530** also end up needing a new cell pointer.
drh7e3b0a02001-04-28 16:52:40 +00001531*/
drh0a45c272009-07-08 01:49:11 +00001532static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
danielk19776011a752009-04-01 16:25:32 +00001533 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1534 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
drh0a45c272009-07-08 01:49:11 +00001535 int top; /* First byte of cell content area */
drhfefa0942014-11-05 21:21:08 +00001536 int rc = SQLITE_OK; /* Integer return code */
drh0a45c272009-07-08 01:49:11 +00001537 int gap; /* First byte of gap between cell pointers and cell content */
drh43605152004-05-29 21:46:49 +00001538
danielk19773b8a05f2007-03-19 17:44:26 +00001539 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001540 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +00001541 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa67c3c2008-07-11 02:21:40 +00001542 assert( nByte>=0 ); /* Minimum cell size is 4 */
1543 assert( pPage->nFree>=nByte );
1544 assert( pPage->nOverflow==0 );
mistachkina95d8ca2014-10-27 19:42:02 +00001545 assert( nByte < (int)(pPage->pBt->usableSize-8) );
drh43605152004-05-29 21:46:49 +00001546
drh0a45c272009-07-08 01:49:11 +00001547 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1548 gap = pPage->cellOffset + 2*pPage->nCell;
drh75b31dc2014-08-20 00:54:46 +00001549 assert( gap<=65536 );
drhfdab0262014-11-20 15:30:50 +00001550 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
1551 ** and the reserved space is zero (the usual value for reserved space)
1552 ** then the cell content offset of an empty page wants to be 65536.
1553 ** However, that integer is too large to be stored in a 2-byte unsigned
1554 ** integer, so a value of 0 is used in its place. */
drhded340e2015-06-25 15:04:56 +00001555 top = get2byte(&data[hdr+5]);
mistachkin68cdd0e2015-06-26 03:12:27 +00001556 assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
drhded340e2015-06-25 15:04:56 +00001557 if( gap>top ){
1558 if( top==0 && pPage->pBt->usableSize==65536 ){
1559 top = 65536;
1560 }else{
1561 return SQLITE_CORRUPT_BKPT;
drh9e572e62004-04-23 23:43:10 +00001562 }
1563 }
drh43605152004-05-29 21:46:49 +00001564
drh4c04f3c2014-08-20 11:56:14 +00001565 /* If there is enough space between gap and top for one more cell pointer
1566 ** array entry offset, and if the freelist is not empty, then search the
1567 ** freelist looking for a free slot big enough to satisfy the request.
1568 */
drh5e2f8b92001-05-28 00:41:15 +00001569 testcase( gap+2==top );
drh7aa128d2002-06-21 13:09:16 +00001570 testcase( gap+1==top );
drh14acc042001-06-10 19:56:58 +00001571 testcase( gap==top );
drhe674bf12015-06-25 16:01:44 +00001572 if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
drhb7580e82015-06-25 18:36:13 +00001573 u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
dan8e9ba0c2014-10-14 17:27:04 +00001574 if( pSpace ){
drhfefa0942014-11-05 21:21:08 +00001575 assert( pSpace>=data && (pSpace - data)<65536 );
1576 *pIdx = (int)(pSpace - data);
dan8e9ba0c2014-10-14 17:27:04 +00001577 return SQLITE_OK;
drhb7580e82015-06-25 18:36:13 +00001578 }else if( rc ){
1579 return rc;
drh9e572e62004-04-23 23:43:10 +00001580 }
1581 }
drh43605152004-05-29 21:46:49 +00001582
drh4c04f3c2014-08-20 11:56:14 +00001583 /* The request could not be fulfilled using a freelist slot. Check
1584 ** to see if defragmentation is necessary.
drh0a45c272009-07-08 01:49:11 +00001585 */
1586 testcase( gap+2+nByte==top );
1587 if( gap+2+nByte>top ){
drh1fd2d7d2014-12-02 16:16:47 +00001588 assert( pPage->nCell>0 || CORRUPT_DB );
dane6d065a2017-02-24 19:58:22 +00001589 rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
drh0a45c272009-07-08 01:49:11 +00001590 if( rc ) return rc;
drh5d433ce2010-08-14 16:02:52 +00001591 top = get2byteNotZero(&data[hdr+5]);
dan3b2ede12017-02-25 16:24:02 +00001592 assert( gap+2+nByte<=top );
drh0a45c272009-07-08 01:49:11 +00001593 }
1594
1595
drh43605152004-05-29 21:46:49 +00001596 /* Allocate memory from the gap in between the cell pointer array
drhc314dc72009-07-21 11:52:34 +00001597 ** and the cell content area. The btreeInitPage() call has already
1598 ** validated the freelist. Given that the freelist is valid, there
1599 ** is no way that the allocation can extend off the end of the page.
1600 ** The assert() below verifies the previous sentence.
drh43605152004-05-29 21:46:49 +00001601 */
drh0a45c272009-07-08 01:49:11 +00001602 top -= nByte;
drh43605152004-05-29 21:46:49 +00001603 put2byte(&data[hdr+5], top);
drhfcd71b62011-04-05 22:08:24 +00001604 assert( top+nByte <= (int)pPage->pBt->usableSize );
drh0a45c272009-07-08 01:49:11 +00001605 *pIdx = top;
1606 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001607}
1608
1609/*
drh9e572e62004-04-23 23:43:10 +00001610** Return a section of the pPage->aData to the freelist.
drh7fb91642014-08-20 14:37:09 +00001611** The first byte of the new free block is pPage->aData[iStart]
1612** and the size of the block is iSize bytes.
drh306dc212001-05-21 13:45:10 +00001613**
drh5f5c7532014-08-20 17:56:27 +00001614** Adjacent freeblocks are coalesced.
1615**
1616** Note that even though the freeblock list was checked by btreeInitPage(),
1617** that routine will not detect overlap between cells or freeblocks. Nor
1618** does it detect cells or freeblocks that encrouch into the reserved bytes
1619** at the end of the page. So do additional corruption checks inside this
1620** routine and return SQLITE_CORRUPT if any problems are found.
drh7e3b0a02001-04-28 16:52:40 +00001621*/
drh5f5c7532014-08-20 17:56:27 +00001622static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
drh3f387402014-09-24 01:23:00 +00001623 u16 iPtr; /* Address of ptr to next freeblock */
drh5f5c7532014-08-20 17:56:27 +00001624 u16 iFreeBlk; /* Address of the next freeblock */
1625 u8 hdr; /* Page header size. 0 or 100 */
1626 u8 nFrag = 0; /* Reduction in fragmentation */
1627 u16 iOrigSize = iSize; /* Original value of iSize */
1628 u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
1629 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
drh7fb91642014-08-20 14:37:09 +00001630 unsigned char *data = pPage->aData; /* Page content */
drh2af926b2001-05-15 00:39:25 +00001631
drh9e572e62004-04-23 23:43:10 +00001632 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001633 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
dancf3d17c2015-05-25 15:03:49 +00001634 assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
dan23eba452014-10-24 18:43:57 +00001635 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +00001636 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh7fb91642014-08-20 14:37:09 +00001637 assert( iSize>=4 ); /* Minimum cell size is 4 */
drh5f5c7532014-08-20 17:56:27 +00001638 assert( iStart<=iLast );
drh9e572e62004-04-23 23:43:10 +00001639
drh5f5c7532014-08-20 17:56:27 +00001640 /* Overwrite deleted information with zeros when the secure_delete
1641 ** option is enabled */
drhc9166342012-01-05 23:32:06 +00001642 if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
drh7fb91642014-08-20 14:37:09 +00001643 memset(&data[iStart], 0, iSize);
drh5b47efa2010-02-12 18:18:39 +00001644 }
drhfcce93f2006-02-22 03:08:32 +00001645
drh5f5c7532014-08-20 17:56:27 +00001646 /* The list of freeblocks must be in ascending order. Find the
1647 ** spot on the list where iStart should be inserted.
drh0a45c272009-07-08 01:49:11 +00001648 */
drh43605152004-05-29 21:46:49 +00001649 hdr = pPage->hdrOffset;
drh7fb91642014-08-20 14:37:09 +00001650 iPtr = hdr + 1;
drh7bc4c452014-08-20 18:43:44 +00001651 if( data[iPtr+1]==0 && data[iPtr]==0 ){
1652 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
1653 }else{
drh85f071b2016-09-17 19:34:32 +00001654 while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
1655 if( iFreeBlk<iPtr+4 ){
1656 if( iFreeBlk==0 ) break;
1657 return SQLITE_CORRUPT_BKPT;
1658 }
drh7bc4c452014-08-20 18:43:44 +00001659 iPtr = iFreeBlk;
shanedcc50b72008-11-13 18:29:50 +00001660 }
drh7bc4c452014-08-20 18:43:44 +00001661 if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
1662 assert( iFreeBlk>iPtr || iFreeBlk==0 );
1663
1664 /* At this point:
1665 ** iFreeBlk: First freeblock after iStart, or zero if none
drh3e24a342015-06-15 16:09:35 +00001666 ** iPtr: The address of a pointer to iFreeBlk
drh7bc4c452014-08-20 18:43:44 +00001667 **
1668 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
1669 */
1670 if( iFreeBlk && iEnd+3>=iFreeBlk ){
1671 nFrag = iFreeBlk - iEnd;
1672 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
1673 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
drhae6cd722015-06-25 15:21:52 +00001674 if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT;
drh7bc4c452014-08-20 18:43:44 +00001675 iSize = iEnd - iStart;
1676 iFreeBlk = get2byte(&data[iFreeBlk]);
1677 }
1678
drh3f387402014-09-24 01:23:00 +00001679 /* If iPtr is another freeblock (that is, if iPtr is not the freelist
1680 ** pointer in the page header) then check to see if iStart should be
1681 ** coalesced onto the end of iPtr.
drh7bc4c452014-08-20 18:43:44 +00001682 */
1683 if( iPtr>hdr+1 ){
1684 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
1685 if( iPtrEnd+3>=iStart ){
1686 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
1687 nFrag += iStart - iPtrEnd;
1688 iSize = iEnd - iPtr;
1689 iStart = iPtr;
shanedcc50b72008-11-13 18:29:50 +00001690 }
drh9e572e62004-04-23 23:43:10 +00001691 }
drh7bc4c452014-08-20 18:43:44 +00001692 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
1693 data[hdr+7] -= nFrag;
drh9e572e62004-04-23 23:43:10 +00001694 }
drh7bc4c452014-08-20 18:43:44 +00001695 if( iStart==get2byte(&data[hdr+5]) ){
drh5f5c7532014-08-20 17:56:27 +00001696 /* The new freeblock is at the beginning of the cell content area,
1697 ** so just extend the cell content area rather than create another
1698 ** freelist entry */
drh7bc4c452014-08-20 18:43:44 +00001699 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
drh5f5c7532014-08-20 17:56:27 +00001700 put2byte(&data[hdr+1], iFreeBlk);
1701 put2byte(&data[hdr+5], iEnd);
1702 }else{
1703 /* Insert the new freeblock into the freelist */
1704 put2byte(&data[iPtr], iStart);
1705 put2byte(&data[iStart], iFreeBlk);
1706 put2byte(&data[iStart+2], iSize);
drh4b70f112004-05-02 21:12:19 +00001707 }
drh5f5c7532014-08-20 17:56:27 +00001708 pPage->nFree += iOrigSize;
shanedcc50b72008-11-13 18:29:50 +00001709 return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00001710}
1711
1712/*
drh271efa52004-05-30 19:19:05 +00001713** Decode the flags byte (the first byte of the header) for a page
1714** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +00001715**
1716** Only the following combinations are supported. Anything different
1717** indicates a corrupt database files:
1718**
1719** PTF_ZERODATA
1720** PTF_ZERODATA | PTF_LEAF
1721** PTF_LEAFDATA | PTF_INTKEY
1722** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
drh271efa52004-05-30 19:19:05 +00001723*/
drh44845222008-07-17 18:39:57 +00001724static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +00001725 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +00001726
1727 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +00001728 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00001729 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
drh44845222008-07-17 18:39:57 +00001730 flagByte &= ~PTF_LEAF;
1731 pPage->childPtrSize = 4-4*pPage->leaf;
drh25ada072015-06-19 15:07:14 +00001732 pPage->xCellSize = cellSizePtr;
drh271efa52004-05-30 19:19:05 +00001733 pBt = pPage->pBt;
drh44845222008-07-17 18:39:57 +00001734 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
drh3791c9c2016-05-09 23:11:47 +00001735 /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
1736 ** interior table b-tree page. */
drhfdab0262014-11-20 15:30:50 +00001737 assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
drh3791c9c2016-05-09 23:11:47 +00001738 /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
1739 ** leaf table b-tree page. */
drhfdab0262014-11-20 15:30:50 +00001740 assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
drh44845222008-07-17 18:39:57 +00001741 pPage->intKey = 1;
drh25ada072015-06-19 15:07:14 +00001742 if( pPage->leaf ){
1743 pPage->intKeyLeaf = 1;
drh5fa60512015-06-19 17:19:34 +00001744 pPage->xParseCell = btreeParseCellPtr;
drh25ada072015-06-19 15:07:14 +00001745 }else{
1746 pPage->intKeyLeaf = 0;
drh25ada072015-06-19 15:07:14 +00001747 pPage->xCellSize = cellSizePtrNoPayload;
drh5fa60512015-06-19 17:19:34 +00001748 pPage->xParseCell = btreeParseCellPtrNoPayload;
drh25ada072015-06-19 15:07:14 +00001749 }
drh271efa52004-05-30 19:19:05 +00001750 pPage->maxLocal = pBt->maxLeaf;
1751 pPage->minLocal = pBt->minLeaf;
drh44845222008-07-17 18:39:57 +00001752 }else if( flagByte==PTF_ZERODATA ){
drh3791c9c2016-05-09 23:11:47 +00001753 /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
1754 ** interior index b-tree page. */
drhfdab0262014-11-20 15:30:50 +00001755 assert( (PTF_ZERODATA)==2 );
drh3791c9c2016-05-09 23:11:47 +00001756 /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
1757 ** leaf index b-tree page. */
drhfdab0262014-11-20 15:30:50 +00001758 assert( (PTF_ZERODATA|PTF_LEAF)==10 );
drh44845222008-07-17 18:39:57 +00001759 pPage->intKey = 0;
drh3e28ff52014-09-24 00:59:08 +00001760 pPage->intKeyLeaf = 0;
drh5fa60512015-06-19 17:19:34 +00001761 pPage->xParseCell = btreeParseCellPtrIndex;
drh271efa52004-05-30 19:19:05 +00001762 pPage->maxLocal = pBt->maxLocal;
1763 pPage->minLocal = pBt->minLocal;
drh44845222008-07-17 18:39:57 +00001764 }else{
drhfdab0262014-11-20 15:30:50 +00001765 /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
1766 ** an error. */
drh44845222008-07-17 18:39:57 +00001767 return SQLITE_CORRUPT_BKPT;
drh271efa52004-05-30 19:19:05 +00001768 }
drhc9166342012-01-05 23:32:06 +00001769 pPage->max1bytePayload = pBt->max1bytePayload;
drh44845222008-07-17 18:39:57 +00001770 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +00001771}
1772
1773/*
drh7e3b0a02001-04-28 16:52:40 +00001774** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001775**
1776** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001777** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001778** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1779** guarantee that the page is well-formed. It only shows that
1780** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001781*/
danielk197730548662009-07-09 05:07:37 +00001782static int btreeInitPage(MemPage *pPage){
drh2af926b2001-05-15 00:39:25 +00001783
danielk197771d5d2c2008-09-29 11:49:47 +00001784 assert( pPage->pBt!=0 );
drh1421d982015-05-27 03:46:18 +00001785 assert( pPage->pBt->db!=0 );
danielk197771d5d2c2008-09-29 11:49:47 +00001786 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001787 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +00001788 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1789 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00001790
1791 if( !pPage->isInit ){
drh380c08e2016-12-13 20:30:29 +00001792 int pc; /* Address of a freeblock within pPage->aData[] */
drhf49661a2008-12-10 16:45:50 +00001793 u8 hdr; /* Offset to beginning of page header */
danielk197771d5d2c2008-09-29 11:49:47 +00001794 u8 *data; /* Equal to pPage->aData */
1795 BtShared *pBt; /* The main btree structure */
drhb2eced52010-08-12 02:41:12 +00001796 int usableSize; /* Amount of usable space on each page */
shaneh1df2db72010-08-18 02:28:48 +00001797 u16 cellOffset; /* Offset from start of page to first cell pointer */
drhb2eced52010-08-12 02:41:12 +00001798 int nFree; /* Number of unused bytes on the page */
1799 int top; /* First byte of the cell content area */
drh0a45c272009-07-08 01:49:11 +00001800 int iCellFirst; /* First allowable cell or freeblock offset */
1801 int iCellLast; /* Last possible cell or freeblock offset */
danielk197771d5d2c2008-09-29 11:49:47 +00001802
1803 pBt = pPage->pBt;
1804
danielk1977eaa06f62008-09-18 17:34:44 +00001805 hdr = pPage->hdrOffset;
1806 data = pPage->aData;
drhfdab0262014-11-20 15:30:50 +00001807 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
1808 ** the b-tree page type. */
danielk1977eaa06f62008-09-18 17:34:44 +00001809 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
drhb2eced52010-08-12 02:41:12 +00001810 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
1811 pPage->maskPage = (u16)(pBt->pageSize - 1);
danielk1977eaa06f62008-09-18 17:34:44 +00001812 pPage->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00001813 usableSize = pBt->usableSize;
drhfdab0262014-11-20 15:30:50 +00001814 pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
drh3def2352011-11-11 00:27:15 +00001815 pPage->aDataEnd = &data[usableSize];
1816 pPage->aCellIdx = &data[cellOffset];
drhf44890a2015-06-27 03:58:15 +00001817 pPage->aDataOfst = &data[pPage->childPtrSize];
drhfdab0262014-11-20 15:30:50 +00001818 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
1819 ** the start of the cell content area. A zero value for this integer is
1820 ** interpreted as 65536. */
drh5d433ce2010-08-14 16:02:52 +00001821 top = get2byteNotZero(&data[hdr+5]);
drhfdab0262014-11-20 15:30:50 +00001822 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
1823 ** number of cells on the page. */
danielk1977eaa06f62008-09-18 17:34:44 +00001824 pPage->nCell = get2byte(&data[hdr+3]);
1825 if( pPage->nCell>MX_CELL(pBt) ){
1826 /* To many cells for a single page. The page must be corrupt */
1827 return SQLITE_CORRUPT_BKPT;
1828 }
drhb908d762009-07-08 16:54:40 +00001829 testcase( pPage->nCell==MX_CELL(pBt) );
drhfdab0262014-11-20 15:30:50 +00001830 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
1831 ** possible for a root page of a table that contains no rows) then the
1832 ** offset to the cell content area will equal the page size minus the
1833 ** bytes of reserved space. */
1834 assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
drh69e931e2009-06-03 21:04:35 +00001835
shane5eff7cf2009-08-10 03:57:58 +00001836 /* A malformed database page might cause us to read past the end
drh69e931e2009-06-03 21:04:35 +00001837 ** of page when parsing a cell.
1838 **
1839 ** The following block of code checks early to see if a cell extends
1840 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
1841 ** returned if it does.
1842 */
drh0a45c272009-07-08 01:49:11 +00001843 iCellFirst = cellOffset + 2*pPage->nCell;
1844 iCellLast = usableSize - 4;
drh1421d982015-05-27 03:46:18 +00001845 if( pBt->db->flags & SQLITE_CellSizeCk ){
drh69e931e2009-06-03 21:04:35 +00001846 int i; /* Index into the cell pointer array */
1847 int sz; /* Size of a cell */
1848
drh69e931e2009-06-03 21:04:35 +00001849 if( !pPage->leaf ) iCellLast--;
1850 for(i=0; i<pPage->nCell; i++){
drh329428e2015-06-30 13:28:18 +00001851 pc = get2byteAligned(&data[cellOffset+i*2]);
drh0a45c272009-07-08 01:49:11 +00001852 testcase( pc==iCellFirst );
1853 testcase( pc==iCellLast );
drh69e931e2009-06-03 21:04:35 +00001854 if( pc<iCellFirst || pc>iCellLast ){
1855 return SQLITE_CORRUPT_BKPT;
1856 }
drh25ada072015-06-19 15:07:14 +00001857 sz = pPage->xCellSize(pPage, &data[pc]);
drh0a45c272009-07-08 01:49:11 +00001858 testcase( pc+sz==usableSize );
drh69e931e2009-06-03 21:04:35 +00001859 if( pc+sz>usableSize ){
1860 return SQLITE_CORRUPT_BKPT;
1861 }
1862 }
drh0a45c272009-07-08 01:49:11 +00001863 if( !pPage->leaf ) iCellLast++;
drh69e931e2009-06-03 21:04:35 +00001864 }
drh69e931e2009-06-03 21:04:35 +00001865
drhfdab0262014-11-20 15:30:50 +00001866 /* Compute the total free space on the page
1867 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
1868 ** start of the first freeblock on the page, or is zero if there are no
1869 ** freeblocks. */
danielk1977eaa06f62008-09-18 17:34:44 +00001870 pc = get2byte(&data[hdr+1]);
drhfdab0262014-11-20 15:30:50 +00001871 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
drh77dc0ed2016-12-12 01:30:01 +00001872 if( pc>0 ){
1873 u32 next, size;
1874 if( pc<iCellFirst ){
drhfdab0262014-11-20 15:30:50 +00001875 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
1876 ** always be at least one cell before the first freeblock.
drhfdab0262014-11-20 15:30:50 +00001877 */
danielk1977eaa06f62008-09-18 17:34:44 +00001878 return SQLITE_CORRUPT_BKPT;
1879 }
drh77dc0ed2016-12-12 01:30:01 +00001880 while( 1 ){
1881 if( pc>iCellLast ){
1882 return SQLITE_CORRUPT_BKPT; /* Freeblock off the end of the page */
1883 }
1884 next = get2byte(&data[pc]);
1885 size = get2byte(&data[pc+2]);
1886 nFree = nFree + size;
1887 if( next<=pc+size+3 ) break;
1888 pc = next;
danielk1977eaa06f62008-09-18 17:34:44 +00001889 }
drh77dc0ed2016-12-12 01:30:01 +00001890 if( next>0 ){
1891 return SQLITE_CORRUPT_BKPT; /* Freeblock not in ascending order */
1892 }
drh380c08e2016-12-13 20:30:29 +00001893 if( pc+size>(unsigned int)usableSize ){
drh77dc0ed2016-12-12 01:30:01 +00001894 return SQLITE_CORRUPT_BKPT; /* Last freeblock extends past page end */
1895 }
danielk1977eaa06f62008-09-18 17:34:44 +00001896 }
danielk197793c829c2009-06-03 17:26:17 +00001897
1898 /* At this point, nFree contains the sum of the offset to the start
1899 ** of the cell-content area plus the number of free bytes within
1900 ** the cell-content area. If this is greater than the usable-size
1901 ** of the page, then the page must be corrupted. This check also
1902 ** serves to verify that the offset to the start of the cell-content
1903 ** area, according to the page header, lies within the page.
1904 */
1905 if( nFree>usableSize ){
drh49285702005-09-17 15:20:26 +00001906 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001907 }
shane5eff7cf2009-08-10 03:57:58 +00001908 pPage->nFree = (u16)(nFree - iCellFirst);
danielk197771d5d2c2008-09-29 11:49:47 +00001909 pPage->isInit = 1;
1910 }
drh9e572e62004-04-23 23:43:10 +00001911 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001912}
1913
1914/*
drh8b2f49b2001-06-08 00:21:52 +00001915** Set up a raw page so that it looks like a database page holding
1916** no entries.
drhbd03cae2001-06-02 02:40:57 +00001917*/
drh9e572e62004-04-23 23:43:10 +00001918static void zeroPage(MemPage *pPage, int flags){
1919 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001920 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00001921 u8 hdr = pPage->hdrOffset;
1922 u16 first;
drh9e572e62004-04-23 23:43:10 +00001923
danielk19773b8a05f2007-03-19 17:44:26 +00001924 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +00001925 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1926 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00001927 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00001928 assert( sqlite3_mutex_held(pBt->mutex) );
drhc9166342012-01-05 23:32:06 +00001929 if( pBt->btsFlags & BTS_SECURE_DELETE ){
drh5b47efa2010-02-12 18:18:39 +00001930 memset(&data[hdr], 0, pBt->usableSize - hdr);
1931 }
drh1bd10f82008-12-10 21:19:56 +00001932 data[hdr] = (char)flags;
drhfe485992014-02-12 23:52:16 +00001933 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
drh43605152004-05-29 21:46:49 +00001934 memset(&data[hdr+1], 0, 4);
1935 data[hdr+7] = 0;
1936 put2byte(&data[hdr+5], pBt->usableSize);
shaneh1df2db72010-08-18 02:28:48 +00001937 pPage->nFree = (u16)(pBt->usableSize - first);
drh271efa52004-05-30 19:19:05 +00001938 decodeFlags(pPage, flags);
drh43605152004-05-29 21:46:49 +00001939 pPage->cellOffset = first;
drh3def2352011-11-11 00:27:15 +00001940 pPage->aDataEnd = &data[pBt->usableSize];
1941 pPage->aCellIdx = &data[first];
drhf44890a2015-06-27 03:58:15 +00001942 pPage->aDataOfst = &data[pPage->childPtrSize];
drh43605152004-05-29 21:46:49 +00001943 pPage->nOverflow = 0;
drhb2eced52010-08-12 02:41:12 +00001944 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
1945 pPage->maskPage = (u16)(pBt->pageSize - 1);
drh43605152004-05-29 21:46:49 +00001946 pPage->nCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001947 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00001948}
1949
drh897a8202008-09-18 01:08:15 +00001950
1951/*
1952** Convert a DbPage obtained from the pager into a MemPage used by
1953** the btree layer.
1954*/
1955static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
1956 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
drh8dd1c252015-11-04 22:31:02 +00001957 if( pgno!=pPage->pgno ){
1958 pPage->aData = sqlite3PagerGetData(pDbPage);
1959 pPage->pDbPage = pDbPage;
1960 pPage->pBt = pBt;
1961 pPage->pgno = pgno;
1962 pPage->hdrOffset = pgno==1 ? 100 : 0;
1963 }
1964 assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
drh897a8202008-09-18 01:08:15 +00001965 return pPage;
1966}
1967
drhbd03cae2001-06-02 02:40:57 +00001968/*
drh3aac2dd2004-04-26 14:10:20 +00001969** Get a page from the pager. Initialize the MemPage.pBt and
drh7e8c6f12015-05-28 03:28:27 +00001970** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
drh538f5702007-04-13 02:14:30 +00001971**
drh7e8c6f12015-05-28 03:28:27 +00001972** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
1973** about the content of the page at this time. So do not go to the disk
drh538f5702007-04-13 02:14:30 +00001974** to fetch the content. Just fill in the content with zeros for now.
1975** If in the future we call sqlite3PagerWrite() on this page, that
1976** means we have started to be concerned about content and the disk
1977** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00001978*/
danielk197730548662009-07-09 05:07:37 +00001979static int btreeGetPage(
drh16a9b832007-05-05 18:39:25 +00001980 BtShared *pBt, /* The btree */
1981 Pgno pgno, /* Number of the page to fetch */
1982 MemPage **ppPage, /* Return the page in this parameter */
drhb00fc3b2013-08-21 23:42:32 +00001983 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
drh16a9b832007-05-05 18:39:25 +00001984){
drh3aac2dd2004-04-26 14:10:20 +00001985 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001986 DbPage *pDbPage;
1987
drhb00fc3b2013-08-21 23:42:32 +00001988 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
drh1fee73e2007-08-29 04:00:57 +00001989 assert( sqlite3_mutex_held(pBt->mutex) );
drh9584f582015-11-04 20:22:37 +00001990 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
drh3aac2dd2004-04-26 14:10:20 +00001991 if( rc ) return rc;
drh897a8202008-09-18 01:08:15 +00001992 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
drh3aac2dd2004-04-26 14:10:20 +00001993 return SQLITE_OK;
1994}
1995
1996/*
danielk1977bea2a942009-01-20 17:06:27 +00001997** Retrieve a page from the pager cache. If the requested page is not
1998** already in the pager cache return NULL. Initialize the MemPage.pBt and
1999** MemPage.aData elements if needed.
2000*/
2001static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
2002 DbPage *pDbPage;
2003 assert( sqlite3_mutex_held(pBt->mutex) );
2004 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
2005 if( pDbPage ){
2006 return btreePageFromDbPage(pDbPage, pgno, pBt);
2007 }
2008 return 0;
2009}
2010
2011/*
danielk197789d40042008-11-17 14:20:56 +00002012** Return the size of the database file in pages. If there is any kind of
2013** error, return ((unsigned int)-1).
danielk197767fd7a92008-09-10 17:53:35 +00002014*/
drhb1299152010-03-30 22:58:33 +00002015static Pgno btreePagecount(BtShared *pBt){
2016 return pBt->nPage;
2017}
2018u32 sqlite3BtreeLastPage(Btree *p){
2019 assert( sqlite3BtreeHoldsMutex(p) );
2020 assert( ((p->pBt->nPage)&0x8000000)==0 );
drheac5bd72014-07-25 21:35:39 +00002021 return btreePagecount(p->pBt);
danielk197767fd7a92008-09-10 17:53:35 +00002022}
2023
2024/*
drh28f58dd2015-06-27 19:45:03 +00002025** Get a page from the pager and initialize it.
danielk197789bc4bc2009-07-21 19:25:24 +00002026**
drh15a00212015-06-27 20:55:00 +00002027** If pCur!=0 then the page is being fetched as part of a moveToChild()
2028** call. Do additional sanity checking on the page in this case.
2029** And if the fetch fails, this routine must decrement pCur->iPage.
drh28f58dd2015-06-27 19:45:03 +00002030**
2031** The page is fetched as read-write unless pCur is not NULL and is
2032** a read-only cursor.
2033**
2034** If an error occurs, then *ppPage is undefined. It
danielk197789bc4bc2009-07-21 19:25:24 +00002035** may remain unchanged, or it may be set to an invalid value.
drhde647132004-05-07 17:57:49 +00002036*/
2037static int getAndInitPage(
dan11dcd112013-03-15 18:29:18 +00002038 BtShared *pBt, /* The database file */
2039 Pgno pgno, /* Number of the page to get */
2040 MemPage **ppPage, /* Write the page pointer here */
drh28f58dd2015-06-27 19:45:03 +00002041 BtCursor *pCur, /* Cursor to receive the page, or NULL */
2042 int bReadOnly /* True for a read-only page */
drhde647132004-05-07 17:57:49 +00002043){
2044 int rc;
drh28f58dd2015-06-27 19:45:03 +00002045 DbPage *pDbPage;
drh1fee73e2007-08-29 04:00:57 +00002046 assert( sqlite3_mutex_held(pBt->mutex) );
drh28f58dd2015-06-27 19:45:03 +00002047 assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] );
2048 assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
drh15a00212015-06-27 20:55:00 +00002049 assert( pCur==0 || pCur->iPage>0 );
danielk197789bc4bc2009-07-21 19:25:24 +00002050
danba3cbf32010-06-30 04:29:03 +00002051 if( pgno>btreePagecount(pBt) ){
2052 rc = SQLITE_CORRUPT_BKPT;
drh28f58dd2015-06-27 19:45:03 +00002053 goto getAndInitPage_error;
2054 }
drh9584f582015-11-04 20:22:37 +00002055 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
drh28f58dd2015-06-27 19:45:03 +00002056 if( rc ){
2057 goto getAndInitPage_error;
2058 }
drh8dd1c252015-11-04 22:31:02 +00002059 *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
drh28f58dd2015-06-27 19:45:03 +00002060 if( (*ppPage)->isInit==0 ){
drh8dd1c252015-11-04 22:31:02 +00002061 btreePageFromDbPage(pDbPage, pgno, pBt);
drh28f58dd2015-06-27 19:45:03 +00002062 rc = btreeInitPage(*ppPage);
2063 if( rc!=SQLITE_OK ){
2064 releasePage(*ppPage);
2065 goto getAndInitPage_error;
danielk197789bc4bc2009-07-21 19:25:24 +00002066 }
drhee696e22004-08-30 16:52:17 +00002067 }
drh8dd1c252015-11-04 22:31:02 +00002068 assert( (*ppPage)->pgno==pgno );
2069 assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
danba3cbf32010-06-30 04:29:03 +00002070
drh15a00212015-06-27 20:55:00 +00002071 /* If obtaining a child page for a cursor, we must verify that the page is
2072 ** compatible with the root page. */
drh8dd1c252015-11-04 22:31:02 +00002073 if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
drh28f58dd2015-06-27 19:45:03 +00002074 rc = SQLITE_CORRUPT_BKPT;
2075 releasePage(*ppPage);
2076 goto getAndInitPage_error;
2077 }
drh28f58dd2015-06-27 19:45:03 +00002078 return SQLITE_OK;
2079
2080getAndInitPage_error:
2081 if( pCur ) pCur->iPage--;
danba3cbf32010-06-30 04:29:03 +00002082 testcase( pgno==0 );
2083 assert( pgno!=0 || rc==SQLITE_CORRUPT );
drhde647132004-05-07 17:57:49 +00002084 return rc;
2085}
2086
2087/*
drh3aac2dd2004-04-26 14:10:20 +00002088** Release a MemPage. This should be called once for each prior
danielk197730548662009-07-09 05:07:37 +00002089** call to btreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00002090*/
drhbbf0f862015-06-27 14:59:26 +00002091static void releasePageNotNull(MemPage *pPage){
2092 assert( pPage->aData );
2093 assert( pPage->pBt );
2094 assert( pPage->pDbPage!=0 );
2095 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2096 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2097 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2098 sqlite3PagerUnrefNotNull(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00002099}
drh3aac2dd2004-04-26 14:10:20 +00002100static void releasePage(MemPage *pPage){
drhbbf0f862015-06-27 14:59:26 +00002101 if( pPage ) releasePageNotNull(pPage);
drh3aac2dd2004-04-26 14:10:20 +00002102}
2103
2104/*
drh7e8c6f12015-05-28 03:28:27 +00002105** Get an unused page.
2106**
2107** This works just like btreeGetPage() with the addition:
2108**
2109** * If the page is already in use for some other purpose, immediately
2110** release it and return an SQLITE_CURRUPT error.
2111** * Make sure the isInit flag is clear
2112*/
2113static int btreeGetUnusedPage(
2114 BtShared *pBt, /* The btree */
2115 Pgno pgno, /* Number of the page to fetch */
2116 MemPage **ppPage, /* Return the page in this parameter */
2117 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2118){
2119 int rc = btreeGetPage(pBt, pgno, ppPage, flags);
2120 if( rc==SQLITE_OK ){
2121 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
2122 releasePage(*ppPage);
2123 *ppPage = 0;
2124 return SQLITE_CORRUPT_BKPT;
2125 }
2126 (*ppPage)->isInit = 0;
2127 }else{
2128 *ppPage = 0;
2129 }
2130 return rc;
2131}
2132
drha059ad02001-04-17 20:09:11 +00002133
2134/*
drha6abd042004-06-09 17:37:22 +00002135** During a rollback, when the pager reloads information into the cache
2136** so that the cache is restored to its original state at the start of
2137** the transaction, for each page restored this routine is called.
2138**
2139** This routine needs to reset the extra data section at the end of the
2140** page to agree with the restored data.
2141*/
danielk1977eaa06f62008-09-18 17:34:44 +00002142static void pageReinit(DbPage *pData){
drh07d183d2005-05-01 22:52:42 +00002143 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00002144 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
danielk1977d217e6f2009-04-01 17:13:51 +00002145 assert( sqlite3PagerPageRefcount(pData)>0 );
danielk197771d5d2c2008-09-29 11:49:47 +00002146 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00002147 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00002148 pPage->isInit = 0;
danielk1977d217e6f2009-04-01 17:13:51 +00002149 if( sqlite3PagerPageRefcount(pData)>1 ){
drh5e8d8872009-03-30 17:19:48 +00002150 /* pPage might not be a btree page; it might be an overflow page
2151 ** or ptrmap page or a free page. In those cases, the following
danielk197730548662009-07-09 05:07:37 +00002152 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
drh5e8d8872009-03-30 17:19:48 +00002153 ** But no harm is done by this. And it is very important that
danielk197730548662009-07-09 05:07:37 +00002154 ** btreeInitPage() be called on every btree page so we make
drh5e8d8872009-03-30 17:19:48 +00002155 ** the call for every page that comes in for re-initing. */
danielk197730548662009-07-09 05:07:37 +00002156 btreeInitPage(pPage);
danielk197771d5d2c2008-09-29 11:49:47 +00002157 }
drha6abd042004-06-09 17:37:22 +00002158 }
2159}
2160
2161/*
drhe5fe6902007-12-07 18:55:28 +00002162** Invoke the busy handler for a btree.
2163*/
danielk19771ceedd32008-11-19 10:22:33 +00002164static int btreeInvokeBusyHandler(void *pArg){
drhe5fe6902007-12-07 18:55:28 +00002165 BtShared *pBt = (BtShared*)pArg;
2166 assert( pBt->db );
2167 assert( sqlite3_mutex_held(pBt->db->mutex) );
2168 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
2169}
2170
2171/*
drhad3e0102004-09-03 23:32:18 +00002172** Open a database file.
2173**
drh382c0242001-10-06 16:33:02 +00002174** zFilename is the name of the database file. If zFilename is NULL
drh75c014c2010-08-30 15:02:28 +00002175** then an ephemeral database is created. The ephemeral database might
2176** be exclusively in memory, or it might use a disk-based memory cache.
2177** Either way, the ephemeral database will be automatically deleted
2178** when sqlite3BtreeClose() is called.
2179**
drhe53831d2007-08-17 01:14:38 +00002180** If zFilename is ":memory:" then an in-memory database is created
2181** that is automatically destroyed when it is closed.
drhc47fd8e2009-04-30 13:30:32 +00002182**
drh33f111d2012-01-17 15:29:14 +00002183** The "flags" parameter is a bitmask that might contain bits like
2184** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
drh75c014c2010-08-30 15:02:28 +00002185**
drhc47fd8e2009-04-30 13:30:32 +00002186** If the database is already opened in the same database connection
2187** and we are in shared cache mode, then the open will fail with an
2188** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
2189** objects in the same database connection since doing so will lead
2190** to problems with locking.
drha059ad02001-04-17 20:09:11 +00002191*/
drh23e11ca2004-05-04 17:27:28 +00002192int sqlite3BtreeOpen(
dan3a6d8ae2011-04-23 15:54:54 +00002193 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
drh3aac2dd2004-04-26 14:10:20 +00002194 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00002195 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00002196 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00002197 int flags, /* Options */
2198 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00002199){
drh7555d8e2009-03-20 13:15:30 +00002200 BtShared *pBt = 0; /* Shared part of btree structure */
2201 Btree *p; /* Handle to return */
2202 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
2203 int rc = SQLITE_OK; /* Result code from this function */
2204 u8 nReserve; /* Byte of unused space on each page */
2205 unsigned char zDbHeader[100]; /* Database header content */
danielk1977aef0bf62005-12-30 16:28:01 +00002206
drh75c014c2010-08-30 15:02:28 +00002207 /* True if opening an ephemeral, temporary database */
2208 const int isTempDb = zFilename==0 || zFilename[0]==0;
2209
danielk1977aef0bf62005-12-30 16:28:01 +00002210 /* Set the variable isMemdb to true for an in-memory database, or
drhb0a7c9c2010-12-06 21:09:59 +00002211 ** false for a file-based database.
danielk1977aef0bf62005-12-30 16:28:01 +00002212 */
drhb0a7c9c2010-12-06 21:09:59 +00002213#ifdef SQLITE_OMIT_MEMORYDB
2214 const int isMemdb = 0;
2215#else
2216 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
drh9c67b2a2012-05-28 13:58:00 +00002217 || (isTempDb && sqlite3TempInMemory(db))
2218 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
danielk1977aef0bf62005-12-30 16:28:01 +00002219#endif
2220
drhe5fe6902007-12-07 18:55:28 +00002221 assert( db!=0 );
dan3a6d8ae2011-04-23 15:54:54 +00002222 assert( pVfs!=0 );
drhe5fe6902007-12-07 18:55:28 +00002223 assert( sqlite3_mutex_held(db->mutex) );
drhd4187c72010-08-30 22:15:45 +00002224 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
2225
2226 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
2227 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
2228
2229 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
2230 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
drh153c62c2007-08-24 03:51:33 +00002231
drh75c014c2010-08-30 15:02:28 +00002232 if( isMemdb ){
2233 flags |= BTREE_MEMORY;
2234 }
2235 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
2236 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
2237 }
drh17435752007-08-16 04:30:38 +00002238 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00002239 if( !p ){
mistachkinfad30392016-02-13 23:43:46 +00002240 return SQLITE_NOMEM_BKPT;
danielk1977aef0bf62005-12-30 16:28:01 +00002241 }
2242 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00002243 p->db = db;
danielk1977602b4662009-07-02 07:47:33 +00002244#ifndef SQLITE_OMIT_SHARED_CACHE
2245 p->lock.pBtree = p;
2246 p->lock.iTable = 1;
2247#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002248
drh198bf392006-01-06 21:52:49 +00002249#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00002250 /*
2251 ** If this Btree is a candidate for shared cache, try to find an
2252 ** existing BtShared object that we can share with
2253 */
drh4ab9d252012-05-26 20:08:49 +00002254 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
drhf1f12682009-09-09 14:17:52 +00002255 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
drh6b5f0eb2015-03-31 16:33:08 +00002256 int nFilename = sqlite3Strlen30(zFilename)+1;
danielk1977adfb9b02007-09-17 07:02:56 +00002257 int nFullPathname = pVfs->mxPathname+1;
drh6b5f0eb2015-03-31 16:33:08 +00002258 char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
drh30ddce62011-10-15 00:16:30 +00002259 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
drh6b5f0eb2015-03-31 16:33:08 +00002260
drhff0587c2007-08-29 17:43:19 +00002261 p->sharable = 1;
drhff0587c2007-08-29 17:43:19 +00002262 if( !zFullPathname ){
2263 sqlite3_free(p);
mistachkinfad30392016-02-13 23:43:46 +00002264 return SQLITE_NOMEM_BKPT;
drhff0587c2007-08-29 17:43:19 +00002265 }
drhafc8b7f2012-05-26 18:06:38 +00002266 if( isMemdb ){
drh6b5f0eb2015-03-31 16:33:08 +00002267 memcpy(zFullPathname, zFilename, nFilename);
drhafc8b7f2012-05-26 18:06:38 +00002268 }else{
2269 rc = sqlite3OsFullPathname(pVfs, zFilename,
2270 nFullPathname, zFullPathname);
2271 if( rc ){
2272 sqlite3_free(zFullPathname);
2273 sqlite3_free(p);
2274 return rc;
2275 }
drh070ad6b2011-11-17 11:43:19 +00002276 }
drh30ddce62011-10-15 00:16:30 +00002277#if SQLITE_THREADSAFE
drh7555d8e2009-03-20 13:15:30 +00002278 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
2279 sqlite3_mutex_enter(mutexOpen);
danielk197759f8c082008-06-18 17:09:10 +00002280 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhff0587c2007-08-29 17:43:19 +00002281 sqlite3_mutex_enter(mutexShared);
drh30ddce62011-10-15 00:16:30 +00002282#endif
drh78f82d12008-09-02 00:52:52 +00002283 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
drhff0587c2007-08-29 17:43:19 +00002284 assert( pBt->nRef>0 );
drhd4e0bb02012-05-27 01:19:04 +00002285 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
drhff0587c2007-08-29 17:43:19 +00002286 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
drhc47fd8e2009-04-30 13:30:32 +00002287 int iDb;
2288 for(iDb=db->nDb-1; iDb>=0; iDb--){
2289 Btree *pExisting = db->aDb[iDb].pBt;
2290 if( pExisting && pExisting->pBt==pBt ){
2291 sqlite3_mutex_leave(mutexShared);
2292 sqlite3_mutex_leave(mutexOpen);
2293 sqlite3_free(zFullPathname);
2294 sqlite3_free(p);
2295 return SQLITE_CONSTRAINT;
2296 }
2297 }
drhff0587c2007-08-29 17:43:19 +00002298 p->pBt = pBt;
2299 pBt->nRef++;
2300 break;
2301 }
2302 }
2303 sqlite3_mutex_leave(mutexShared);
2304 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00002305 }
drhff0587c2007-08-29 17:43:19 +00002306#ifdef SQLITE_DEBUG
2307 else{
2308 /* In debug mode, we mark all persistent databases as sharable
2309 ** even when they are not. This exercises the locking code and
2310 ** gives more opportunity for asserts(sqlite3_mutex_held())
2311 ** statements to find locking problems.
2312 */
2313 p->sharable = 1;
2314 }
2315#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002316 }
2317#endif
drha059ad02001-04-17 20:09:11 +00002318 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00002319 /*
2320 ** The following asserts make sure that structures used by the btree are
2321 ** the right size. This is to guard against size changes that result
2322 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00002323 */
drh062cf272015-03-23 19:03:51 +00002324 assert( sizeof(i64)==8 );
2325 assert( sizeof(u64)==8 );
drhe53831d2007-08-17 01:14:38 +00002326 assert( sizeof(u32)==4 );
2327 assert( sizeof(u16)==2 );
2328 assert( sizeof(Pgno)==4 );
2329
2330 pBt = sqlite3MallocZero( sizeof(*pBt) );
2331 if( pBt==0 ){
mistachkinfad30392016-02-13 23:43:46 +00002332 rc = SQLITE_NOMEM_BKPT;
drhe53831d2007-08-17 01:14:38 +00002333 goto btree_open_out;
2334 }
danielk197771d5d2c2008-09-29 11:49:47 +00002335 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
drha2ee5892016-12-09 16:02:00 +00002336 sizeof(MemPage), flags, vfsFlags, pageReinit);
drhe53831d2007-08-17 01:14:38 +00002337 if( rc==SQLITE_OK ){
drh9b4c59f2013-04-15 17:03:42 +00002338 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
drhe53831d2007-08-17 01:14:38 +00002339 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
2340 }
2341 if( rc!=SQLITE_OK ){
2342 goto btree_open_out;
2343 }
shanehbd2aaf92010-09-01 02:38:21 +00002344 pBt->openFlags = (u8)flags;
danielk19772a50ff02009-04-10 09:47:06 +00002345 pBt->db = db;
danielk19771ceedd32008-11-19 10:22:33 +00002346 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
drhe53831d2007-08-17 01:14:38 +00002347 p->pBt = pBt;
2348
drhe53831d2007-08-17 01:14:38 +00002349 pBt->pCursor = 0;
2350 pBt->pPage1 = 0;
drhc9166342012-01-05 23:32:06 +00002351 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
drh5b47efa2010-02-12 18:18:39 +00002352#ifdef SQLITE_SECURE_DELETE
drhc9166342012-01-05 23:32:06 +00002353 pBt->btsFlags |= BTS_SECURE_DELETE;
drh5b47efa2010-02-12 18:18:39 +00002354#endif
drh113762a2014-11-19 16:36:25 +00002355 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2356 ** determined by the 2-byte integer located at an offset of 16 bytes from
2357 ** the beginning of the database file. */
drhb2eced52010-08-12 02:41:12 +00002358 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
drhe53831d2007-08-17 01:14:38 +00002359 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2360 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002361 pBt->pageSize = 0;
drhe53831d2007-08-17 01:14:38 +00002362#ifndef SQLITE_OMIT_AUTOVACUUM
2363 /* If the magic name ":memory:" will create an in-memory database, then
2364 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2365 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2366 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2367 ** regular file-name. In this case the auto-vacuum applies as per normal.
2368 */
2369 if( zFilename && !isMemdb ){
2370 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2371 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2372 }
2373#endif
2374 nReserve = 0;
2375 }else{
drh113762a2014-11-19 16:36:25 +00002376 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2377 ** determined by the one-byte unsigned integer found at an offset of 20
2378 ** into the database file header. */
drhe53831d2007-08-17 01:14:38 +00002379 nReserve = zDbHeader[20];
drhc9166342012-01-05 23:32:06 +00002380 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
drhe53831d2007-08-17 01:14:38 +00002381#ifndef SQLITE_OMIT_AUTOVACUUM
2382 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2383 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2384#endif
2385 }
drhfa9601a2009-06-18 17:22:39 +00002386 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhc0b61812009-04-30 01:22:41 +00002387 if( rc ) goto btree_open_out;
drhe53831d2007-08-17 01:14:38 +00002388 pBt->usableSize = pBt->pageSize - nReserve;
2389 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
drhe53831d2007-08-17 01:14:38 +00002390
2391#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2392 /* Add the new BtShared object to the linked list sharable BtShareds.
2393 */
dan272989b2016-07-06 10:12:02 +00002394 pBt->nRef = 1;
drhe53831d2007-08-17 01:14:38 +00002395 if( p->sharable ){
drh30ddce62011-10-15 00:16:30 +00002396 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
drh30ddce62011-10-15 00:16:30 +00002397 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
danielk1977075c23a2008-09-01 18:34:20 +00002398 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
danielk197759f8c082008-06-18 17:09:10 +00002399 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00002400 if( pBt->mutex==0 ){
mistachkinfad30392016-02-13 23:43:46 +00002401 rc = SQLITE_NOMEM_BKPT;
drh3285db22007-09-03 22:00:39 +00002402 goto btree_open_out;
2403 }
drhff0587c2007-08-29 17:43:19 +00002404 }
drhe53831d2007-08-17 01:14:38 +00002405 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00002406 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2407 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
drhe53831d2007-08-17 01:14:38 +00002408 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00002409 }
drheee46cf2004-11-06 00:02:48 +00002410#endif
drh90f5ecb2004-07-22 01:19:35 +00002411 }
danielk1977aef0bf62005-12-30 16:28:01 +00002412
drhcfed7bc2006-03-13 14:28:05 +00002413#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00002414 /* If the new Btree uses a sharable pBtShared, then link the new
2415 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00002416 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00002417 */
drhe53831d2007-08-17 01:14:38 +00002418 if( p->sharable ){
2419 int i;
2420 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00002421 for(i=0; i<db->nDb; i++){
2422 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00002423 while( pSib->pPrev ){ pSib = pSib->pPrev; }
drh3bfa7e82016-03-22 14:37:59 +00002424 if( (uptr)p->pBt<(uptr)pSib->pBt ){
drhe53831d2007-08-17 01:14:38 +00002425 p->pNext = pSib;
2426 p->pPrev = 0;
2427 pSib->pPrev = p;
2428 }else{
drh3bfa7e82016-03-22 14:37:59 +00002429 while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
drhe53831d2007-08-17 01:14:38 +00002430 pSib = pSib->pNext;
2431 }
2432 p->pNext = pSib->pNext;
2433 p->pPrev = pSib;
2434 if( p->pNext ){
2435 p->pNext->pPrev = p;
2436 }
2437 pSib->pNext = p;
2438 }
2439 break;
2440 }
2441 }
danielk1977aef0bf62005-12-30 16:28:01 +00002442 }
danielk1977aef0bf62005-12-30 16:28:01 +00002443#endif
2444 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00002445
2446btree_open_out:
2447 if( rc!=SQLITE_OK ){
2448 if( pBt && pBt->pPager ){
dan7fb89902016-08-12 16:21:15 +00002449 sqlite3PagerClose(pBt->pPager, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002450 }
drh17435752007-08-16 04:30:38 +00002451 sqlite3_free(pBt);
2452 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00002453 *ppBtree = 0;
drh75c014c2010-08-30 15:02:28 +00002454 }else{
dan0f5a1862016-08-13 14:30:23 +00002455 sqlite3_file *pFile;
2456
drh75c014c2010-08-30 15:02:28 +00002457 /* If the B-Tree was successfully opened, set the pager-cache size to the
2458 ** default value. Except, when opening on an existing shared pager-cache,
2459 ** do not change the pager-cache size.
2460 */
2461 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2462 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
2463 }
dan0f5a1862016-08-13 14:30:23 +00002464
2465 pFile = sqlite3PagerFile(pBt->pPager);
2466 if( pFile->pMethods ){
2467 sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
2468 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002469 }
drh7555d8e2009-03-20 13:15:30 +00002470 if( mutexOpen ){
2471 assert( sqlite3_mutex_held(mutexOpen) );
2472 sqlite3_mutex_leave(mutexOpen);
2473 }
dan272989b2016-07-06 10:12:02 +00002474 assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00002475 return rc;
drha059ad02001-04-17 20:09:11 +00002476}
2477
2478/*
drhe53831d2007-08-17 01:14:38 +00002479** Decrement the BtShared.nRef counter. When it reaches zero,
2480** remove the BtShared structure from the sharing list. Return
2481** true if the BtShared.nRef counter reaches zero and return
2482** false if it is still positive.
2483*/
2484static int removeFromSharingList(BtShared *pBt){
2485#ifndef SQLITE_OMIT_SHARED_CACHE
drh30ddce62011-10-15 00:16:30 +00002486 MUTEX_LOGIC( sqlite3_mutex *pMaster; )
drhe53831d2007-08-17 01:14:38 +00002487 BtShared *pList;
2488 int removed = 0;
2489
drhd677b3d2007-08-20 22:48:41 +00002490 assert( sqlite3_mutex_notheld(pBt->mutex) );
drh30ddce62011-10-15 00:16:30 +00002491 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
drhe53831d2007-08-17 01:14:38 +00002492 sqlite3_mutex_enter(pMaster);
2493 pBt->nRef--;
2494 if( pBt->nRef<=0 ){
drh78f82d12008-09-02 00:52:52 +00002495 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2496 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
drhe53831d2007-08-17 01:14:38 +00002497 }else{
drh78f82d12008-09-02 00:52:52 +00002498 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
drh34004ce2008-07-11 16:15:17 +00002499 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00002500 pList=pList->pNext;
2501 }
drh34004ce2008-07-11 16:15:17 +00002502 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00002503 pList->pNext = pBt->pNext;
2504 }
2505 }
drh3285db22007-09-03 22:00:39 +00002506 if( SQLITE_THREADSAFE ){
2507 sqlite3_mutex_free(pBt->mutex);
2508 }
drhe53831d2007-08-17 01:14:38 +00002509 removed = 1;
2510 }
2511 sqlite3_mutex_leave(pMaster);
2512 return removed;
2513#else
2514 return 1;
2515#endif
2516}
2517
2518/*
drhf7141992008-06-19 00:16:08 +00002519** Make sure pBt->pTmpSpace points to an allocation of
drh92787cf2014-10-15 11:55:51 +00002520** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
2521** pointer.
drhf7141992008-06-19 00:16:08 +00002522*/
2523static void allocateTempSpace(BtShared *pBt){
2524 if( !pBt->pTmpSpace ){
2525 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
dan14285b72013-10-16 11:39:07 +00002526
2527 /* One of the uses of pBt->pTmpSpace is to format cells before
2528 ** inserting them into a leaf page (function fillInCell()). If
2529 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2530 ** by the various routines that manipulate binary cells. Which
2531 ** can mean that fillInCell() only initializes the first 2 or 3
2532 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2533 ** it into a database page. This is not actually a problem, but it
2534 ** does cause a valgrind error when the 1 or 2 bytes of unitialized
2535 ** data is passed to system call write(). So to avoid this error,
drh92787cf2014-10-15 11:55:51 +00002536 ** zero the first 4 bytes of temp space here.
2537 **
2538 ** Also: Provide four bytes of initialized space before the
2539 ** beginning of pTmpSpace as an area available to prepend the
2540 ** left-child pointer to the beginning of a cell.
2541 */
2542 if( pBt->pTmpSpace ){
2543 memset(pBt->pTmpSpace, 0, 8);
2544 pBt->pTmpSpace += 4;
2545 }
drhf7141992008-06-19 00:16:08 +00002546 }
2547}
2548
2549/*
2550** Free the pBt->pTmpSpace allocation
2551*/
2552static void freeTempSpace(BtShared *pBt){
drh92787cf2014-10-15 11:55:51 +00002553 if( pBt->pTmpSpace ){
2554 pBt->pTmpSpace -= 4;
2555 sqlite3PageFree(pBt->pTmpSpace);
2556 pBt->pTmpSpace = 0;
2557 }
drhf7141992008-06-19 00:16:08 +00002558}
2559
2560/*
drha059ad02001-04-17 20:09:11 +00002561** Close an open database and invalidate all cursors.
2562*/
danielk1977aef0bf62005-12-30 16:28:01 +00002563int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002564 BtShared *pBt = p->pBt;
2565 BtCursor *pCur;
2566
danielk1977aef0bf62005-12-30 16:28:01 +00002567 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00002568 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00002569 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002570 pCur = pBt->pCursor;
2571 while( pCur ){
2572 BtCursor *pTmp = pCur;
2573 pCur = pCur->pNext;
2574 if( pTmp->pBtree==p ){
2575 sqlite3BtreeCloseCursor(pTmp);
2576 }
drha059ad02001-04-17 20:09:11 +00002577 }
danielk1977aef0bf62005-12-30 16:28:01 +00002578
danielk19778d34dfd2006-01-24 16:37:57 +00002579 /* Rollback any active transaction and free the handle structure.
2580 ** The call to sqlite3BtreeRollback() drops any table-locks held by
2581 ** this handle.
2582 */
drh47b7fc72014-11-11 01:33:57 +00002583 sqlite3BtreeRollback(p, SQLITE_OK, 0);
drhe53831d2007-08-17 01:14:38 +00002584 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002585
danielk1977aef0bf62005-12-30 16:28:01 +00002586 /* If there are still other outstanding references to the shared-btree
2587 ** structure, return now. The remainder of this procedure cleans
2588 ** up the shared-btree.
2589 */
drhe53831d2007-08-17 01:14:38 +00002590 assert( p->wantToLock==0 && p->locked==0 );
2591 if( !p->sharable || removeFromSharingList(pBt) ){
2592 /* The pBt is no longer on the sharing list, so we can access
2593 ** it without having to hold the mutex.
2594 **
2595 ** Clean out and delete the BtShared object.
2596 */
2597 assert( !pBt->pCursor );
dan7fb89902016-08-12 16:21:15 +00002598 sqlite3PagerClose(pBt->pPager, p->db);
drhe53831d2007-08-17 01:14:38 +00002599 if( pBt->xFreeSchema && pBt->pSchema ){
2600 pBt->xFreeSchema(pBt->pSchema);
2601 }
drhb9755982010-07-24 16:34:37 +00002602 sqlite3DbFree(0, pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00002603 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00002604 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002605 }
2606
drhe53831d2007-08-17 01:14:38 +00002607#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00002608 assert( p->wantToLock==0 );
2609 assert( p->locked==0 );
2610 if( p->pPrev ) p->pPrev->pNext = p->pNext;
2611 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00002612#endif
2613
drhe53831d2007-08-17 01:14:38 +00002614 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00002615 return SQLITE_OK;
2616}
2617
2618/*
drh9b0cf342015-11-12 14:57:19 +00002619** Change the "soft" limit on the number of pages in the cache.
2620** Unused and unmodified pages will be recycled when the number of
2621** pages in the cache exceeds this soft limit. But the size of the
2622** cache is allowed to grow larger than this limit if it contains
2623** dirty pages or pages still in active use.
drhf57b14a2001-09-14 18:54:08 +00002624*/
danielk1977aef0bf62005-12-30 16:28:01 +00002625int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2626 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00002627 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002628 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00002629 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00002630 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00002631 return SQLITE_OK;
2632}
2633
drh9b0cf342015-11-12 14:57:19 +00002634/*
2635** Change the "spill" limit on the number of pages in the cache.
2636** If the number of pages exceeds this limit during a write transaction,
2637** the pager might attempt to "spill" pages to the journal early in
2638** order to free up memory.
2639**
2640** The value returned is the current spill size. If zero is passed
2641** as an argument, no changes are made to the spill size setting, so
2642** using mxPage of 0 is a way to query the current spill size.
2643*/
2644int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
2645 BtShared *pBt = p->pBt;
2646 int res;
2647 assert( sqlite3_mutex_held(p->db->mutex) );
2648 sqlite3BtreeEnter(p);
2649 res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
2650 sqlite3BtreeLeave(p);
2651 return res;
2652}
2653
drh18c7e402014-03-14 11:46:10 +00002654#if SQLITE_MAX_MMAP_SIZE>0
drhf57b14a2001-09-14 18:54:08 +00002655/*
dan5d8a1372013-03-19 19:28:06 +00002656** Change the limit on the amount of the database file that may be
2657** memory mapped.
2658*/
drh9b4c59f2013-04-15 17:03:42 +00002659int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
dan5d8a1372013-03-19 19:28:06 +00002660 BtShared *pBt = p->pBt;
2661 assert( sqlite3_mutex_held(p->db->mutex) );
2662 sqlite3BtreeEnter(p);
drh9b4c59f2013-04-15 17:03:42 +00002663 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
dan5d8a1372013-03-19 19:28:06 +00002664 sqlite3BtreeLeave(p);
2665 return SQLITE_OK;
2666}
drh18c7e402014-03-14 11:46:10 +00002667#endif /* SQLITE_MAX_MMAP_SIZE>0 */
dan5d8a1372013-03-19 19:28:06 +00002668
2669/*
drh973b6e32003-02-12 14:09:42 +00002670** Change the way data is synced to disk in order to increase or decrease
2671** how well the database resists damage due to OS crashes and power
2672** failures. Level 1 is the same as asynchronous (no syncs() occur and
2673** there is a high probability of damage) Level 2 is the default. There
2674** is a very low but non-zero probability of damage. Level 3 reduces the
2675** probability of damage to near zero but with a write performance reduction.
2676*/
danielk197793758c82005-01-21 08:13:14 +00002677#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drh40c39412013-08-16 20:42:20 +00002678int sqlite3BtreeSetPagerFlags(
drhc97d8462010-11-19 18:23:35 +00002679 Btree *p, /* The btree to set the safety level on */
drh40c39412013-08-16 20:42:20 +00002680 unsigned pgFlags /* Various PAGER_* flags */
drhc97d8462010-11-19 18:23:35 +00002681){
danielk1977aef0bf62005-12-30 16:28:01 +00002682 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00002683 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002684 sqlite3BtreeEnter(p);
drh40c39412013-08-16 20:42:20 +00002685 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
drhd677b3d2007-08-20 22:48:41 +00002686 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00002687 return SQLITE_OK;
2688}
danielk197793758c82005-01-21 08:13:14 +00002689#endif
drh973b6e32003-02-12 14:09:42 +00002690
drh2c8997b2005-08-27 16:36:48 +00002691/*
drh90f5ecb2004-07-22 01:19:35 +00002692** Change the default pages size and the number of reserved bytes per page.
drhce4869f2009-04-02 20:16:58 +00002693** Or, if the page size has already been fixed, return SQLITE_READONLY
2694** without changing anything.
drh06f50212004-11-02 14:24:33 +00002695**
2696** The page size must be a power of 2 between 512 and 65536. If the page
2697** size supplied does not meet this constraint then the page size is not
2698** changed.
2699**
2700** Page sizes are constrained to be a power of two so that the region
2701** of the database file used for locking (beginning at PENDING_BYTE,
2702** the first byte past the 1GB boundary, 0x40000000) needs to occur
2703** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00002704**
2705** If parameter nReserve is less than zero, then the number of reserved
2706** bytes per page is left unchanged.
drhce4869f2009-04-02 20:16:58 +00002707**
drhc9166342012-01-05 23:32:06 +00002708** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
drhce4869f2009-04-02 20:16:58 +00002709** and autovacuum mode can no longer be changed.
drh90f5ecb2004-07-22 01:19:35 +00002710*/
drhce4869f2009-04-02 20:16:58 +00002711int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
danielk1977a1644fd2007-08-29 12:31:25 +00002712 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002713 BtShared *pBt = p->pBt;
drhf49661a2008-12-10 16:45:50 +00002714 assert( nReserve>=-1 && nReserve<=255 );
drhd677b3d2007-08-20 22:48:41 +00002715 sqlite3BtreeEnter(p);
drhad0961b2015-02-21 00:19:25 +00002716#if SQLITE_HAS_CODEC
2717 if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
2718#endif
drhc9166342012-01-05 23:32:06 +00002719 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
drhd677b3d2007-08-20 22:48:41 +00002720 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00002721 return SQLITE_READONLY;
2722 }
2723 if( nReserve<0 ){
2724 nReserve = pBt->pageSize - pBt->usableSize;
2725 }
drhf49661a2008-12-10 16:45:50 +00002726 assert( nReserve>=0 && nReserve<=255 );
drh06f50212004-11-02 14:24:33 +00002727 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2728 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00002729 assert( (pageSize & 7)==0 );
dandd14ecb2015-05-05 10:03:08 +00002730 assert( !pBt->pCursor );
drhb2eced52010-08-12 02:41:12 +00002731 pBt->pageSize = (u32)pageSize;
drhf7141992008-06-19 00:16:08 +00002732 freeTempSpace(pBt);
drh90f5ecb2004-07-22 01:19:35 +00002733 }
drhfa9601a2009-06-18 17:22:39 +00002734 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhf49661a2008-12-10 16:45:50 +00002735 pBt->usableSize = pBt->pageSize - (u16)nReserve;
drhc9166342012-01-05 23:32:06 +00002736 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
drhd677b3d2007-08-20 22:48:41 +00002737 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00002738 return rc;
drh90f5ecb2004-07-22 01:19:35 +00002739}
2740
2741/*
2742** Return the currently defined page size
2743*/
danielk1977aef0bf62005-12-30 16:28:01 +00002744int sqlite3BtreeGetPageSize(Btree *p){
2745 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00002746}
drh7f751222009-03-17 22:33:00 +00002747
dan0094f372012-09-28 20:23:42 +00002748/*
2749** This function is similar to sqlite3BtreeGetReserve(), except that it
2750** may only be called if it is guaranteed that the b-tree mutex is already
2751** held.
2752**
2753** This is useful in one special case in the backup API code where it is
2754** known that the shared b-tree mutex is held, but the mutex on the
2755** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
2756** were to be called, it might collide with some other operation on the
mistachkin48864df2013-03-21 21:20:32 +00002757** database handle that owns *p, causing undefined behavior.
dan0094f372012-09-28 20:23:42 +00002758*/
2759int sqlite3BtreeGetReserveNoMutex(Btree *p){
drhad0961b2015-02-21 00:19:25 +00002760 int n;
dan0094f372012-09-28 20:23:42 +00002761 assert( sqlite3_mutex_held(p->pBt->mutex) );
drhad0961b2015-02-21 00:19:25 +00002762 n = p->pBt->pageSize - p->pBt->usableSize;
2763 return n;
dan0094f372012-09-28 20:23:42 +00002764}
2765
drh7f751222009-03-17 22:33:00 +00002766/*
2767** Return the number of bytes of space at the end of every page that
2768** are intentually left unused. This is the "reserved" space that is
2769** sometimes used by extensions.
drhad0961b2015-02-21 00:19:25 +00002770**
2771** If SQLITE_HAS_MUTEX is defined then the number returned is the
2772** greater of the current reserved space and the maximum requested
2773** reserve space.
drh7f751222009-03-17 22:33:00 +00002774*/
drhad0961b2015-02-21 00:19:25 +00002775int sqlite3BtreeGetOptimalReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002776 int n;
2777 sqlite3BtreeEnter(p);
drhad0961b2015-02-21 00:19:25 +00002778 n = sqlite3BtreeGetReserveNoMutex(p);
2779#ifdef SQLITE_HAS_CODEC
2780 if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
2781#endif
drhd677b3d2007-08-20 22:48:41 +00002782 sqlite3BtreeLeave(p);
2783 return n;
drh2011d5f2004-07-22 02:40:37 +00002784}
drhf8e632b2007-05-08 14:51:36 +00002785
drhad0961b2015-02-21 00:19:25 +00002786
drhf8e632b2007-05-08 14:51:36 +00002787/*
2788** Set the maximum page count for a database if mxPage is positive.
2789** No changes are made if mxPage is 0 or negative.
2790** Regardless of the value of mxPage, return the maximum page count.
2791*/
2792int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00002793 int n;
2794 sqlite3BtreeEnter(p);
2795 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
2796 sqlite3BtreeLeave(p);
2797 return n;
drhf8e632b2007-05-08 14:51:36 +00002798}
drh5b47efa2010-02-12 18:18:39 +00002799
2800/*
drhc9166342012-01-05 23:32:06 +00002801** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
2802** then make no changes. Always return the value of the BTS_SECURE_DELETE
drh5b47efa2010-02-12 18:18:39 +00002803** setting after the change.
2804*/
2805int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
2806 int b;
drhaf034ed2010-02-12 19:46:26 +00002807 if( p==0 ) return 0;
drh5b47efa2010-02-12 18:18:39 +00002808 sqlite3BtreeEnter(p);
2809 if( newFlag>=0 ){
drhc9166342012-01-05 23:32:06 +00002810 p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
2811 if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
drh5b47efa2010-02-12 18:18:39 +00002812 }
drhc9166342012-01-05 23:32:06 +00002813 b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
drh5b47efa2010-02-12 18:18:39 +00002814 sqlite3BtreeLeave(p);
2815 return b;
2816}
drh90f5ecb2004-07-22 01:19:35 +00002817
2818/*
danielk1977951af802004-11-05 15:45:09 +00002819** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
2820** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
2821** is disabled. The default value for the auto-vacuum property is
2822** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
2823*/
danielk1977aef0bf62005-12-30 16:28:01 +00002824int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00002825#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002826 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00002827#else
danielk1977dddbcdc2007-04-26 14:42:34 +00002828 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002829 int rc = SQLITE_OK;
drh076d4662009-02-18 20:31:18 +00002830 u8 av = (u8)autoVacuum;
drhd677b3d2007-08-20 22:48:41 +00002831
2832 sqlite3BtreeEnter(p);
drhc9166342012-01-05 23:32:06 +00002833 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002834 rc = SQLITE_READONLY;
2835 }else{
drh076d4662009-02-18 20:31:18 +00002836 pBt->autoVacuum = av ?1:0;
2837 pBt->incrVacuum = av==2 ?1:0;
danielk1977951af802004-11-05 15:45:09 +00002838 }
drhd677b3d2007-08-20 22:48:41 +00002839 sqlite3BtreeLeave(p);
2840 return rc;
danielk1977951af802004-11-05 15:45:09 +00002841#endif
2842}
2843
2844/*
2845** Return the value of the 'auto-vacuum' property. If auto-vacuum is
2846** enabled 1 is returned. Otherwise 0.
2847*/
danielk1977aef0bf62005-12-30 16:28:01 +00002848int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00002849#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002850 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00002851#else
drhd677b3d2007-08-20 22:48:41 +00002852 int rc;
2853 sqlite3BtreeEnter(p);
2854 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00002855 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
2856 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
2857 BTREE_AUTOVACUUM_INCR
2858 );
drhd677b3d2007-08-20 22:48:41 +00002859 sqlite3BtreeLeave(p);
2860 return rc;
danielk1977951af802004-11-05 15:45:09 +00002861#endif
2862}
2863
2864
2865/*
drha34b6762004-05-07 13:30:42 +00002866** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00002867** also acquire a readlock on that file.
2868**
2869** SQLITE_OK is returned on success. If the file is not a
2870** well-formed database file, then SQLITE_CORRUPT is returned.
2871** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00002872** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00002873*/
danielk1977aef0bf62005-12-30 16:28:01 +00002874static int lockBtree(BtShared *pBt){
drhc2a4bab2010-04-02 12:46:45 +00002875 int rc; /* Result code from subfunctions */
2876 MemPage *pPage1; /* Page 1 of the database file */
2877 int nPage; /* Number of pages in the database */
2878 int nPageFile = 0; /* Number of pages in the database file */
2879 int nPageHeader; /* Number of pages in the database according to hdr */
drhd677b3d2007-08-20 22:48:41 +00002880
drh1fee73e2007-08-29 04:00:57 +00002881 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977295dc102009-04-01 19:07:03 +00002882 assert( pBt->pPage1==0 );
danielk197789bc4bc2009-07-21 19:25:24 +00002883 rc = sqlite3PagerSharedLock(pBt->pPager);
2884 if( rc!=SQLITE_OK ) return rc;
drhb00fc3b2013-08-21 23:42:32 +00002885 rc = btreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00002886 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00002887
2888 /* Do some checking to help insure the file we opened really is
2889 ** a valid database file.
2890 */
drhc2a4bab2010-04-02 12:46:45 +00002891 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
drh8fb8b532010-08-14 17:12:04 +00002892 sqlite3PagerPagecount(pBt->pPager, &nPageFile);
drhb28e59b2010-06-17 02:13:39 +00002893 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
drhc2a4bab2010-04-02 12:46:45 +00002894 nPage = nPageFile;
drh97b59a52010-03-31 02:31:33 +00002895 }
2896 if( nPage>0 ){
drh43b18e12010-08-17 19:40:08 +00002897 u32 pageSize;
2898 u32 usableSize;
drhb6f41482004-05-14 01:58:11 +00002899 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00002900 rc = SQLITE_NOTADB;
drh113762a2014-11-19 16:36:25 +00002901 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
2902 ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
2903 ** 61 74 20 33 00. */
drhb6f41482004-05-14 01:58:11 +00002904 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00002905 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00002906 }
dan5cf53532010-05-01 16:40:20 +00002907
2908#ifdef SQLITE_OMIT_WAL
2909 if( page1[18]>1 ){
drhc9166342012-01-05 23:32:06 +00002910 pBt->btsFlags |= BTS_READ_ONLY;
dan5cf53532010-05-01 16:40:20 +00002911 }
2912 if( page1[19]>1 ){
2913 goto page1_init_failed;
2914 }
2915#else
dane04dc882010-04-20 18:53:15 +00002916 if( page1[18]>2 ){
drhc9166342012-01-05 23:32:06 +00002917 pBt->btsFlags |= BTS_READ_ONLY;
drh309169a2007-04-24 17:27:51 +00002918 }
dane04dc882010-04-20 18:53:15 +00002919 if( page1[19]>2 ){
drhb6f41482004-05-14 01:58:11 +00002920 goto page1_init_failed;
2921 }
drhe5ae5732008-06-15 02:51:47 +00002922
dana470aeb2010-04-21 11:43:38 +00002923 /* If the write version is set to 2, this database should be accessed
2924 ** in WAL mode. If the log is not already open, open it now. Then
2925 ** return SQLITE_OK and return without populating BtShared.pPage1.
2926 ** The caller detects this and calls this function again. This is
2927 ** required as the version of page 1 currently in the page1 buffer
2928 ** may not be the latest version - there may be a newer one in the log
2929 ** file.
2930 */
drhc9166342012-01-05 23:32:06 +00002931 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
dane04dc882010-04-20 18:53:15 +00002932 int isOpen = 0;
drh7ed91f22010-04-29 22:34:07 +00002933 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
dane04dc882010-04-20 18:53:15 +00002934 if( rc!=SQLITE_OK ){
2935 goto page1_init_failed;
drhe243de52016-03-08 15:14:26 +00002936 }else{
2937#if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS
2938 sqlite3 *db;
2939 Db *pDb;
2940 if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
2941 while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
2942 if( pDb->bSyncSet==0
drhc2ae2072016-03-08 15:30:01 +00002943 && pDb->safety_level==SQLITE_DEFAULT_SYNCHRONOUS+1
drhe243de52016-03-08 15:14:26 +00002944 ){
drhc2ae2072016-03-08 15:30:01 +00002945 pDb->safety_level = SQLITE_DEFAULT_WAL_SYNCHRONOUS+1;
drhe243de52016-03-08 15:14:26 +00002946 sqlite3PagerSetFlags(pBt->pPager,
2947 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
2948 }
2949 }
2950#endif
2951 if( isOpen==0 ){
2952 releasePage(pPage1);
2953 return SQLITE_OK;
2954 }
dane04dc882010-04-20 18:53:15 +00002955 }
dan8b5444b2010-04-27 14:37:47 +00002956 rc = SQLITE_NOTADB;
dane04dc882010-04-20 18:53:15 +00002957 }
dan5cf53532010-05-01 16:40:20 +00002958#endif
dane04dc882010-04-20 18:53:15 +00002959
drh113762a2014-11-19 16:36:25 +00002960 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
2961 ** fractions and the leaf payload fraction values must be 64, 32, and 32.
2962 **
drhe5ae5732008-06-15 02:51:47 +00002963 ** The original design allowed these amounts to vary, but as of
2964 ** version 3.6.0, we require them to be fixed.
2965 */
2966 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
2967 goto page1_init_failed;
2968 }
drh113762a2014-11-19 16:36:25 +00002969 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2970 ** determined by the 2-byte integer located at an offset of 16 bytes from
2971 ** the beginning of the database file. */
drhb2eced52010-08-12 02:41:12 +00002972 pageSize = (page1[16]<<8) | (page1[17]<<16);
drh113762a2014-11-19 16:36:25 +00002973 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
2974 ** between 512 and 65536 inclusive. */
drhb2eced52010-08-12 02:41:12 +00002975 if( ((pageSize-1)&pageSize)!=0
2976 || pageSize>SQLITE_MAX_PAGE_SIZE
2977 || pageSize<=256
drh7dc385e2007-09-06 23:39:36 +00002978 ){
drh07d183d2005-05-01 22:52:42 +00002979 goto page1_init_failed;
2980 }
2981 assert( (pageSize & 7)==0 );
drh113762a2014-11-19 16:36:25 +00002982 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
2983 ** integer at offset 20 is the number of bytes of space at the end of
2984 ** each page to reserve for extensions.
2985 **
2986 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2987 ** determined by the one-byte unsigned integer found at an offset of 20
2988 ** into the database file header. */
danielk1977f653d782008-03-20 11:04:21 +00002989 usableSize = pageSize - page1[20];
shaneh1df2db72010-08-18 02:28:48 +00002990 if( (u32)pageSize!=pBt->pageSize ){
danielk1977f653d782008-03-20 11:04:21 +00002991 /* After reading the first page of the database assuming a page size
2992 ** of BtShared.pageSize, we have discovered that the page-size is
2993 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
2994 ** zero and return SQLITE_OK. The caller will call this function
2995 ** again with the correct page-size.
2996 */
2997 releasePage(pPage1);
drh43b18e12010-08-17 19:40:08 +00002998 pBt->usableSize = usableSize;
2999 pBt->pageSize = pageSize;
drhf7141992008-06-19 00:16:08 +00003000 freeTempSpace(pBt);
drhfa9601a2009-06-18 17:22:39 +00003001 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
3002 pageSize-usableSize);
drh5e483932009-07-10 16:51:30 +00003003 return rc;
danielk1977f653d782008-03-20 11:04:21 +00003004 }
danecac6702011-02-09 18:19:20 +00003005 if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
drhc2a4bab2010-04-02 12:46:45 +00003006 rc = SQLITE_CORRUPT_BKPT;
3007 goto page1_init_failed;
3008 }
drh113762a2014-11-19 16:36:25 +00003009 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
3010 ** be less than 480. In other words, if the page size is 512, then the
3011 ** reserved space size cannot exceed 32. */
drhb33e1b92009-06-18 11:29:20 +00003012 if( usableSize<480 ){
drhb6f41482004-05-14 01:58:11 +00003013 goto page1_init_failed;
3014 }
drh43b18e12010-08-17 19:40:08 +00003015 pBt->pageSize = pageSize;
3016 pBt->usableSize = usableSize;
drh057cd3a2005-02-15 16:23:02 +00003017#ifndef SQLITE_OMIT_AUTOVACUUM
3018 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00003019 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00003020#endif
drh306dc212001-05-21 13:45:10 +00003021 }
drhb6f41482004-05-14 01:58:11 +00003022
3023 /* maxLocal is the maximum amount of payload to store locally for
3024 ** a cell. Make sure it is small enough so that at least minFanout
3025 ** cells can will fit on one page. We assume a 10-byte page header.
3026 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00003027 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00003028 ** 4-byte child pointer
3029 ** 9-byte nKey value
3030 ** 4-byte nData value
3031 ** 4-byte overflow page pointer
drhe22e03e2010-08-18 21:19:03 +00003032 ** So a cell consists of a 2-byte pointer, a header which is as much as
drh43605152004-05-29 21:46:49 +00003033 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
3034 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00003035 */
shaneh1df2db72010-08-18 02:28:48 +00003036 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
3037 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
3038 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
3039 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
drhc9166342012-01-05 23:32:06 +00003040 if( pBt->maxLocal>127 ){
3041 pBt->max1bytePayload = 127;
3042 }else{
mistachkin0547e2f2012-01-08 00:54:02 +00003043 pBt->max1bytePayload = (u8)pBt->maxLocal;
drhc9166342012-01-05 23:32:06 +00003044 }
drh2e38c322004-09-03 18:38:44 +00003045 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00003046 pBt->pPage1 = pPage1;
drhdd3cd972010-03-27 17:12:36 +00003047 pBt->nPage = nPage;
drhb6f41482004-05-14 01:58:11 +00003048 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00003049
drh72f82862001-05-24 21:06:34 +00003050page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00003051 releasePage(pPage1);
3052 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00003053 return rc;
drh306dc212001-05-21 13:45:10 +00003054}
3055
drh85ec3b62013-05-14 23:12:06 +00003056#ifndef NDEBUG
3057/*
3058** Return the number of cursors open on pBt. This is for use
3059** in assert() expressions, so it is only compiled if NDEBUG is not
3060** defined.
3061**
3062** Only write cursors are counted if wrOnly is true. If wrOnly is
3063** false then all cursors are counted.
3064**
3065** For the purposes of this routine, a cursor is any cursor that
peter.d.reid60ec9142014-09-06 16:39:46 +00003066** is capable of reading or writing to the database. Cursors that
drh85ec3b62013-05-14 23:12:06 +00003067** have been tripped into the CURSOR_FAULT state are not counted.
3068*/
3069static int countValidCursors(BtShared *pBt, int wrOnly){
3070 BtCursor *pCur;
3071 int r = 0;
3072 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drh036dbec2014-03-11 23:40:44 +00003073 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
3074 && pCur->eState!=CURSOR_FAULT ) r++;
drh85ec3b62013-05-14 23:12:06 +00003075 }
3076 return r;
3077}
3078#endif
3079
drh306dc212001-05-21 13:45:10 +00003080/*
drhb8ca3072001-12-05 00:21:20 +00003081** If there are no outstanding cursors and we are not in the middle
3082** of a transaction but there is a read lock on the database, then
3083** this routine unrefs the first page of the database file which
3084** has the effect of releasing the read lock.
3085**
drhb8ca3072001-12-05 00:21:20 +00003086** If there is a transaction in progress, this routine is a no-op.
3087*/
danielk1977aef0bf62005-12-30 16:28:01 +00003088static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00003089 assert( sqlite3_mutex_held(pBt->mutex) );
drh85ec3b62013-05-14 23:12:06 +00003090 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
danielk19771bc9ee92009-07-04 15:41:02 +00003091 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
drhb2325b72014-09-24 18:31:07 +00003092 MemPage *pPage1 = pBt->pPage1;
3093 assert( pPage1->aData );
danielk1977c1761e82009-06-25 09:40:03 +00003094 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
drh3aac2dd2004-04-26 14:10:20 +00003095 pBt->pPage1 = 0;
drhbbf0f862015-06-27 14:59:26 +00003096 releasePageNotNull(pPage1);
drhb8ca3072001-12-05 00:21:20 +00003097 }
3098}
3099
3100/*
drhe39f2f92009-07-23 01:43:59 +00003101** If pBt points to an empty file then convert that empty file
3102** into a new empty database by initializing the first page of
3103** the database.
drh8b2f49b2001-06-08 00:21:52 +00003104*/
danielk1977aef0bf62005-12-30 16:28:01 +00003105static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00003106 MemPage *pP1;
3107 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00003108 int rc;
drhd677b3d2007-08-20 22:48:41 +00003109
drh1fee73e2007-08-29 04:00:57 +00003110 assert( sqlite3_mutex_held(pBt->mutex) );
drhdd3cd972010-03-27 17:12:36 +00003111 if( pBt->nPage>0 ){
3112 return SQLITE_OK;
danielk1977ad0132d2008-06-07 08:58:22 +00003113 }
drh3aac2dd2004-04-26 14:10:20 +00003114 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00003115 assert( pP1!=0 );
3116 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00003117 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00003118 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00003119 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
3120 assert( sizeof(zMagicHeader)==16 );
shaneh1df2db72010-08-18 02:28:48 +00003121 data[16] = (u8)((pBt->pageSize>>8)&0xff);
3122 data[17] = (u8)((pBt->pageSize>>16)&0xff);
drh9e572e62004-04-23 23:43:10 +00003123 data[18] = 1;
3124 data[19] = 1;
drhf49661a2008-12-10 16:45:50 +00003125 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
3126 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
drhe5ae5732008-06-15 02:51:47 +00003127 data[21] = 64;
3128 data[22] = 32;
3129 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00003130 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00003131 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhc9166342012-01-05 23:32:06 +00003132 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
danielk1977003ba062004-11-04 02:57:33 +00003133#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00003134 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00003135 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00003136 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00003137 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00003138#endif
drhdd3cd972010-03-27 17:12:36 +00003139 pBt->nPage = 1;
3140 data[31] = 1;
drh8b2f49b2001-06-08 00:21:52 +00003141 return SQLITE_OK;
3142}
3143
3144/*
danb483eba2012-10-13 19:58:11 +00003145** Initialize the first page of the database file (creating a database
3146** consisting of a single page and no schema objects). Return SQLITE_OK
3147** if successful, or an SQLite error code otherwise.
3148*/
3149int sqlite3BtreeNewDb(Btree *p){
3150 int rc;
3151 sqlite3BtreeEnter(p);
3152 p->pBt->nPage = 0;
3153 rc = newDatabase(p->pBt);
3154 sqlite3BtreeLeave(p);
3155 return rc;
3156}
3157
3158/*
danielk1977ee5741e2004-05-31 10:01:34 +00003159** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00003160** is started if the second argument is nonzero, otherwise a read-
3161** transaction. If the second argument is 2 or more and exclusive
3162** transaction is started, meaning that no other process is allowed
3163** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00003164** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00003165** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00003166**
danielk1977ee5741e2004-05-31 10:01:34 +00003167** A write-transaction must be started before attempting any
3168** changes to the database. None of the following routines
3169** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00003170**
drh23e11ca2004-05-04 17:27:28 +00003171** sqlite3BtreeCreateTable()
3172** sqlite3BtreeCreateIndex()
3173** sqlite3BtreeClearTable()
3174** sqlite3BtreeDropTable()
3175** sqlite3BtreeInsert()
3176** sqlite3BtreeDelete()
3177** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00003178**
drhb8ef32c2005-03-14 02:01:49 +00003179** If an initial attempt to acquire the lock fails because of lock contention
3180** and the database was previously unlocked, then invoke the busy handler
3181** if there is one. But if there was previously a read-lock, do not
3182** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
3183** returned when there is already a read-lock in order to avoid a deadlock.
3184**
3185** Suppose there are two processes A and B. A has a read lock and B has
3186** a reserved lock. B tries to promote to exclusive but is blocked because
3187** of A's read lock. A tries to promote to reserved but is blocked by B.
3188** One or the other of the two processes must give way or there can be
3189** no progress. By returning SQLITE_BUSY and not invoking the busy callback
3190** when A already has a read lock, we encourage A to give up and let B
3191** proceed.
drha059ad02001-04-17 20:09:11 +00003192*/
danielk1977aef0bf62005-12-30 16:28:01 +00003193int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
3194 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00003195 int rc = SQLITE_OK;
3196
drhd677b3d2007-08-20 22:48:41 +00003197 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003198 btreeIntegrity(p);
3199
danielk1977ee5741e2004-05-31 10:01:34 +00003200 /* If the btree is already in a write-transaction, or it
3201 ** is already in a read-transaction and a read-transaction
3202 ** is requested, this is a no-op.
3203 */
danielk1977aef0bf62005-12-30 16:28:01 +00003204 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00003205 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00003206 }
dan56c517a2013-09-26 11:04:33 +00003207 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
drhb8ef32c2005-03-14 02:01:49 +00003208
3209 /* Write transactions are not possible on a read-only database */
drhc9166342012-01-05 23:32:06 +00003210 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00003211 rc = SQLITE_READONLY;
3212 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00003213 }
3214
danielk1977404ca072009-03-16 13:19:36 +00003215#ifndef SQLITE_OMIT_SHARED_CACHE
drh5a1fb182016-01-08 19:34:39 +00003216 {
3217 sqlite3 *pBlock = 0;
3218 /* If another database handle has already opened a write transaction
3219 ** on this shared-btree structure and a second write transaction is
3220 ** requested, return SQLITE_LOCKED.
3221 */
3222 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
3223 || (pBt->btsFlags & BTS_PENDING)!=0
3224 ){
3225 pBlock = pBt->pWriter->db;
3226 }else if( wrflag>1 ){
3227 BtLock *pIter;
3228 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
3229 if( pIter->pBtree!=p ){
3230 pBlock = pIter->pBtree->db;
3231 break;
3232 }
danielk1977641b0f42007-12-21 04:47:25 +00003233 }
3234 }
drh5a1fb182016-01-08 19:34:39 +00003235 if( pBlock ){
3236 sqlite3ConnectionBlocked(p->db, pBlock);
3237 rc = SQLITE_LOCKED_SHAREDCACHE;
3238 goto trans_begun;
3239 }
danielk1977404ca072009-03-16 13:19:36 +00003240 }
danielk1977641b0f42007-12-21 04:47:25 +00003241#endif
3242
danielk1977602b4662009-07-02 07:47:33 +00003243 /* Any read-only or read-write transaction implies a read-lock on
3244 ** page 1. So if some other shared-cache client already has a write-lock
3245 ** on page 1, the transaction cannot be opened. */
drh4c301aa2009-07-15 17:25:45 +00003246 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
3247 if( SQLITE_OK!=rc ) goto trans_begun;
danielk1977602b4662009-07-02 07:47:33 +00003248
drhc9166342012-01-05 23:32:06 +00003249 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
3250 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
drhb8ef32c2005-03-14 02:01:49 +00003251 do {
danielk1977295dc102009-04-01 19:07:03 +00003252 /* Call lockBtree() until either pBt->pPage1 is populated or
3253 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
3254 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
3255 ** reading page 1 it discovers that the page-size of the database
3256 ** file is not pBt->pageSize. In this case lockBtree() will update
3257 ** pBt->pageSize to the page-size of the file on disk.
3258 */
3259 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
drh309169a2007-04-24 17:27:51 +00003260
drhb8ef32c2005-03-14 02:01:49 +00003261 if( rc==SQLITE_OK && wrflag ){
drhc9166342012-01-05 23:32:06 +00003262 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
drh309169a2007-04-24 17:27:51 +00003263 rc = SQLITE_READONLY;
3264 }else{
danielk1977d8293352009-04-30 09:10:37 +00003265 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
drh309169a2007-04-24 17:27:51 +00003266 if( rc==SQLITE_OK ){
3267 rc = newDatabase(pBt);
3268 }
drhb8ef32c2005-03-14 02:01:49 +00003269 }
3270 }
3271
danielk1977bd434552009-03-18 10:33:00 +00003272 if( rc!=SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00003273 unlockBtreeIfUnused(pBt);
3274 }
danf9b76712010-06-01 14:12:45 +00003275 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
danielk19771ceedd32008-11-19 10:22:33 +00003276 btreeInvokeBusyHandler(pBt) );
danielk1977aef0bf62005-12-30 16:28:01 +00003277
3278 if( rc==SQLITE_OK ){
3279 if( p->inTrans==TRANS_NONE ){
3280 pBt->nTransaction++;
danielk1977602b4662009-07-02 07:47:33 +00003281#ifndef SQLITE_OMIT_SHARED_CACHE
3282 if( p->sharable ){
drhf2f105d2012-08-20 15:53:54 +00003283 assert( p->lock.pBtree==p && p->lock.iTable==1 );
danielk1977602b4662009-07-02 07:47:33 +00003284 p->lock.eLock = READ_LOCK;
3285 p->lock.pNext = pBt->pLock;
3286 pBt->pLock = &p->lock;
3287 }
3288#endif
danielk1977aef0bf62005-12-30 16:28:01 +00003289 }
3290 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
3291 if( p->inTrans>pBt->inTransaction ){
3292 pBt->inTransaction = p->inTrans;
3293 }
danielk1977404ca072009-03-16 13:19:36 +00003294 if( wrflag ){
dan59257dc2010-08-04 11:34:31 +00003295 MemPage *pPage1 = pBt->pPage1;
3296#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977404ca072009-03-16 13:19:36 +00003297 assert( !pBt->pWriter );
3298 pBt->pWriter = p;
drhc9166342012-01-05 23:32:06 +00003299 pBt->btsFlags &= ~BTS_EXCLUSIVE;
3300 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
danielk1977641b0f42007-12-21 04:47:25 +00003301#endif
dan59257dc2010-08-04 11:34:31 +00003302
3303 /* If the db-size header field is incorrect (as it may be if an old
3304 ** client has been writing the database file), update it now. Doing
3305 ** this sooner rather than later means the database size can safely
3306 ** re-read the database size from page 1 if a savepoint or transaction
3307 ** rollback occurs within the transaction.
3308 */
3309 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
3310 rc = sqlite3PagerWrite(pPage1->pDbPage);
3311 if( rc==SQLITE_OK ){
3312 put4byte(&pPage1->aData[28], pBt->nPage);
3313 }
3314 }
3315 }
danielk1977aef0bf62005-12-30 16:28:01 +00003316 }
3317
drhd677b3d2007-08-20 22:48:41 +00003318
3319trans_begun:
danielk1977fd7f0452008-12-17 17:30:26 +00003320 if( rc==SQLITE_OK && wrflag ){
danielk197712dd5492008-12-18 15:45:07 +00003321 /* This call makes sure that the pager has the correct number of
3322 ** open savepoints. If the second parameter is greater than 0 and
3323 ** the sub-journal is not already open, then it will be opened here.
3324 */
danielk1977fd7f0452008-12-17 17:30:26 +00003325 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
3326 }
danielk197712dd5492008-12-18 15:45:07 +00003327
danielk1977aef0bf62005-12-30 16:28:01 +00003328 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00003329 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00003330 return rc;
drha059ad02001-04-17 20:09:11 +00003331}
3332
danielk1977687566d2004-11-02 12:56:41 +00003333#ifndef SQLITE_OMIT_AUTOVACUUM
3334
3335/*
3336** Set the pointer-map entries for all children of page pPage. Also, if
3337** pPage contains cells that point to overflow pages, set the pointer
3338** map entries for the overflow pages as well.
3339*/
3340static int setChildPtrmaps(MemPage *pPage){
3341 int i; /* Counter variable */
3342 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00003343 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00003344 BtShared *pBt = pPage->pBt;
danielk1977687566d2004-11-02 12:56:41 +00003345 Pgno pgno = pPage->pgno;
3346
drh1fee73e2007-08-29 04:00:57 +00003347 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197730548662009-07-09 05:07:37 +00003348 rc = btreeInitPage(pPage);
drh2a702542016-12-12 18:12:03 +00003349 if( rc!=SQLITE_OK ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00003350 nCell = pPage->nCell;
3351
3352 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00003353 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00003354
drh98add2e2009-07-20 17:11:49 +00003355 ptrmapPutOvflPtr(pPage, pCell, &rc);
danielk197726836652005-01-17 01:33:13 +00003356
danielk1977687566d2004-11-02 12:56:41 +00003357 if( !pPage->leaf ){
3358 Pgno childPgno = get4byte(pCell);
drh98add2e2009-07-20 17:11:49 +00003359 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00003360 }
3361 }
3362
3363 if( !pPage->leaf ){
3364 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh98add2e2009-07-20 17:11:49 +00003365 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00003366 }
3367
danielk1977687566d2004-11-02 12:56:41 +00003368 return rc;
3369}
3370
3371/*
drhf3aed592009-07-08 18:12:49 +00003372** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
3373** that it points to iTo. Parameter eType describes the type of pointer to
3374** be modified, as follows:
danielk1977687566d2004-11-02 12:56:41 +00003375**
3376** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
3377** page of pPage.
3378**
3379** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3380** page pointed to by one of the cells on pPage.
3381**
3382** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3383** overflow page in the list.
3384*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00003385static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00003386 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00003387 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977687566d2004-11-02 12:56:41 +00003388 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00003389 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00003390 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00003391 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00003392 }
danielk1977f78fc082004-11-02 14:40:32 +00003393 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00003394 }else{
danielk1977687566d2004-11-02 12:56:41 +00003395 int i;
3396 int nCell;
drha1f75d92015-05-24 10:18:12 +00003397 int rc;
danielk1977687566d2004-11-02 12:56:41 +00003398
drha1f75d92015-05-24 10:18:12 +00003399 rc = btreeInitPage(pPage);
3400 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00003401 nCell = pPage->nCell;
3402
danielk1977687566d2004-11-02 12:56:41 +00003403 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00003404 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00003405 if( eType==PTRMAP_OVERFLOW1 ){
3406 CellInfo info;
drh5fa60512015-06-19 17:19:34 +00003407 pPage->xParseCell(pPage, pCell, &info);
drhb701c9a2017-01-12 15:11:03 +00003408 if( info.nLocal<info.nPayload ){
3409 if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
3410 return SQLITE_CORRUPT_BKPT;
3411 }
3412 if( iFrom==get4byte(pCell+info.nSize-4) ){
3413 put4byte(pCell+info.nSize-4, iTo);
3414 break;
3415 }
danielk1977687566d2004-11-02 12:56:41 +00003416 }
3417 }else{
3418 if( get4byte(pCell)==iFrom ){
3419 put4byte(pCell, iTo);
3420 break;
3421 }
3422 }
3423 }
3424
3425 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00003426 if( eType!=PTRMAP_BTREE ||
3427 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00003428 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00003429 }
danielk1977687566d2004-11-02 12:56:41 +00003430 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3431 }
danielk1977687566d2004-11-02 12:56:41 +00003432 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00003433 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00003434}
3435
danielk1977003ba062004-11-04 02:57:33 +00003436
danielk19777701e812005-01-10 12:59:51 +00003437/*
3438** Move the open database page pDbPage to location iFreePage in the
3439** database. The pDbPage reference remains valid.
drhe64ca7b2009-07-16 18:21:17 +00003440**
3441** The isCommit flag indicates that there is no need to remember that
3442** the journal needs to be sync()ed before database page pDbPage->pgno
3443** can be written to. The caller has already promised not to write to that
3444** page.
danielk19777701e812005-01-10 12:59:51 +00003445*/
danielk1977003ba062004-11-04 02:57:33 +00003446static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00003447 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00003448 MemPage *pDbPage, /* Open page to move */
3449 u8 eType, /* Pointer map 'type' entry for pDbPage */
3450 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00003451 Pgno iFreePage, /* The location to move pDbPage to */
drhe64ca7b2009-07-16 18:21:17 +00003452 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
danielk1977003ba062004-11-04 02:57:33 +00003453){
3454 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
3455 Pgno iDbPage = pDbPage->pgno;
3456 Pager *pPager = pBt->pPager;
3457 int rc;
3458
danielk1977a0bf2652004-11-04 14:30:04 +00003459 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3460 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00003461 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00003462 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00003463
drh85b623f2007-12-13 21:54:09 +00003464 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00003465 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
3466 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00003467 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00003468 if( rc!=SQLITE_OK ){
3469 return rc;
3470 }
3471 pDbPage->pgno = iFreePage;
3472
3473 /* If pDbPage was a btree-page, then it may have child pages and/or cells
3474 ** that point to overflow pages. The pointer map entries for all these
3475 ** pages need to be changed.
3476 **
3477 ** If pDbPage is an overflow page, then the first 4 bytes may store a
3478 ** pointer to a subsequent overflow page. If this is the case, then
3479 ** the pointer map needs to be updated for the subsequent overflow page.
3480 */
danielk1977a0bf2652004-11-04 14:30:04 +00003481 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00003482 rc = setChildPtrmaps(pDbPage);
3483 if( rc!=SQLITE_OK ){
3484 return rc;
3485 }
3486 }else{
3487 Pgno nextOvfl = get4byte(pDbPage->aData);
3488 if( nextOvfl!=0 ){
drh98add2e2009-07-20 17:11:49 +00003489 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
danielk1977003ba062004-11-04 02:57:33 +00003490 if( rc!=SQLITE_OK ){
3491 return rc;
3492 }
3493 }
3494 }
3495
3496 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3497 ** that it points at iFreePage. Also fix the pointer map entry for
3498 ** iPtrPage.
3499 */
danielk1977a0bf2652004-11-04 14:30:04 +00003500 if( eType!=PTRMAP_ROOTPAGE ){
drhb00fc3b2013-08-21 23:42:32 +00003501 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00003502 if( rc!=SQLITE_OK ){
3503 return rc;
3504 }
danielk19773b8a05f2007-03-19 17:44:26 +00003505 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00003506 if( rc!=SQLITE_OK ){
3507 releasePage(pPtrPage);
3508 return rc;
3509 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00003510 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00003511 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003512 if( rc==SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00003513 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003514 }
danielk1977003ba062004-11-04 02:57:33 +00003515 }
danielk1977003ba062004-11-04 02:57:33 +00003516 return rc;
3517}
3518
danielk1977dddbcdc2007-04-26 14:42:34 +00003519/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00003520static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00003521
3522/*
dan51f0b6d2013-02-22 20:16:34 +00003523** Perform a single step of an incremental-vacuum. If successful, return
3524** SQLITE_OK. If there is no work to do (and therefore no point in
3525** calling this function again), return SQLITE_DONE. Or, if an error
3526** occurs, return some other error code.
danielk1977dddbcdc2007-04-26 14:42:34 +00003527**
peter.d.reid60ec9142014-09-06 16:39:46 +00003528** More specifically, this function attempts to re-organize the database so
dan51f0b6d2013-02-22 20:16:34 +00003529** that the last page of the file currently in use is no longer in use.
danielk1977dddbcdc2007-04-26 14:42:34 +00003530**
dan51f0b6d2013-02-22 20:16:34 +00003531** Parameter nFin is the number of pages that this database would contain
3532** were this function called until it returns SQLITE_DONE.
3533**
3534** If the bCommit parameter is non-zero, this function assumes that the
3535** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
peter.d.reid60ec9142014-09-06 16:39:46 +00003536** or an error. bCommit is passed true for an auto-vacuum-on-commit
dan51f0b6d2013-02-22 20:16:34 +00003537** operation, or false for an incremental vacuum.
danielk1977dddbcdc2007-04-26 14:42:34 +00003538*/
dan51f0b6d2013-02-22 20:16:34 +00003539static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
danielk1977dddbcdc2007-04-26 14:42:34 +00003540 Pgno nFreeList; /* Number of pages still on the free-list */
drhdd3cd972010-03-27 17:12:36 +00003541 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003542
drh1fee73e2007-08-29 04:00:57 +00003543 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977fa542f12009-04-02 18:28:08 +00003544 assert( iLastPg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00003545
3546 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003547 u8 eType;
3548 Pgno iPtrPage;
3549
3550 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977fa542f12009-04-02 18:28:08 +00003551 if( nFreeList==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003552 return SQLITE_DONE;
3553 }
3554
3555 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3556 if( rc!=SQLITE_OK ){
3557 return rc;
3558 }
3559 if( eType==PTRMAP_ROOTPAGE ){
3560 return SQLITE_CORRUPT_BKPT;
3561 }
3562
3563 if( eType==PTRMAP_FREEPAGE ){
dan51f0b6d2013-02-22 20:16:34 +00003564 if( bCommit==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003565 /* Remove the page from the files free-list. This is not required
dan51f0b6d2013-02-22 20:16:34 +00003566 ** if bCommit is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00003567 ** truncated to zero after this function returns, so it doesn't
3568 ** matter if it still contains some garbage entries.
3569 */
3570 Pgno iFreePg;
3571 MemPage *pFreePg;
dan51f0b6d2013-02-22 20:16:34 +00003572 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
danielk1977dddbcdc2007-04-26 14:42:34 +00003573 if( rc!=SQLITE_OK ){
3574 return rc;
3575 }
3576 assert( iFreePg==iLastPg );
3577 releasePage(pFreePg);
3578 }
3579 } else {
3580 Pgno iFreePg; /* Index of free page to move pLastPg to */
3581 MemPage *pLastPg;
dan51f0b6d2013-02-22 20:16:34 +00003582 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
3583 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
danielk1977dddbcdc2007-04-26 14:42:34 +00003584
drhb00fc3b2013-08-21 23:42:32 +00003585 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00003586 if( rc!=SQLITE_OK ){
3587 return rc;
3588 }
3589
dan51f0b6d2013-02-22 20:16:34 +00003590 /* If bCommit is zero, this loop runs exactly once and page pLastPg
danielk1977b4626a32007-04-28 15:47:43 +00003591 ** is swapped with the first free page pulled off the free list.
3592 **
dan51f0b6d2013-02-22 20:16:34 +00003593 ** On the other hand, if bCommit is greater than zero, then keep
danielk1977b4626a32007-04-28 15:47:43 +00003594 ** looping until a free-page located within the first nFin pages
3595 ** of the file is found.
3596 */
dan51f0b6d2013-02-22 20:16:34 +00003597 if( bCommit==0 ){
3598 eMode = BTALLOC_LE;
3599 iNear = nFin;
3600 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003601 do {
3602 MemPage *pFreePg;
dan51f0b6d2013-02-22 20:16:34 +00003603 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
danielk1977dddbcdc2007-04-26 14:42:34 +00003604 if( rc!=SQLITE_OK ){
3605 releasePage(pLastPg);
3606 return rc;
3607 }
3608 releasePage(pFreePg);
dan51f0b6d2013-02-22 20:16:34 +00003609 }while( bCommit && iFreePg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00003610 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00003611
dane1df4e32013-03-05 11:27:04 +00003612 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
danielk1977dddbcdc2007-04-26 14:42:34 +00003613 releasePage(pLastPg);
3614 if( rc!=SQLITE_OK ){
3615 return rc;
danielk1977662278e2007-11-05 15:30:12 +00003616 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003617 }
3618 }
3619
dan51f0b6d2013-02-22 20:16:34 +00003620 if( bCommit==0 ){
danbc1a3c62013-02-23 16:40:46 +00003621 do {
danielk19773460d192008-12-27 15:23:13 +00003622 iLastPg--;
danbc1a3c62013-02-23 16:40:46 +00003623 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
3624 pBt->bDoTruncate = 1;
drhdd3cd972010-03-27 17:12:36 +00003625 pBt->nPage = iLastPg;
danielk1977dddbcdc2007-04-26 14:42:34 +00003626 }
3627 return SQLITE_OK;
3628}
3629
3630/*
dan51f0b6d2013-02-22 20:16:34 +00003631** The database opened by the first argument is an auto-vacuum database
3632** nOrig pages in size containing nFree free pages. Return the expected
3633** size of the database in pages following an auto-vacuum operation.
3634*/
3635static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
3636 int nEntry; /* Number of entries on one ptrmap page */
3637 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
3638 Pgno nFin; /* Return value */
3639
3640 nEntry = pBt->usableSize/5;
3641 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
3642 nFin = nOrig - nFree - nPtrmap;
3643 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
3644 nFin--;
3645 }
3646 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3647 nFin--;
3648 }
dan51f0b6d2013-02-22 20:16:34 +00003649
3650 return nFin;
3651}
3652
3653/*
danielk1977dddbcdc2007-04-26 14:42:34 +00003654** A write-transaction must be opened before calling this function.
3655** It performs a single unit of work towards an incremental vacuum.
3656**
3657** If the incremental vacuum is finished after this function has run,
shanebe217792009-03-05 04:20:31 +00003658** SQLITE_DONE is returned. If it is not finished, but no error occurred,
danielk1977dddbcdc2007-04-26 14:42:34 +00003659** SQLITE_OK is returned. Otherwise an SQLite error code.
3660*/
3661int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00003662 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003663 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003664
3665 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00003666 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
3667 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00003668 rc = SQLITE_DONE;
3669 }else{
dan51f0b6d2013-02-22 20:16:34 +00003670 Pgno nOrig = btreePagecount(pBt);
3671 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
3672 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
3673
dan91384712013-02-24 11:50:43 +00003674 if( nOrig<nFin ){
3675 rc = SQLITE_CORRUPT_BKPT;
3676 }else if( nFree>0 ){
dan11dcd112013-03-15 18:29:18 +00003677 rc = saveAllCursors(pBt, 0, 0);
3678 if( rc==SQLITE_OK ){
3679 invalidateAllOverflowCache(pBt);
3680 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
3681 }
dan51f0b6d2013-02-22 20:16:34 +00003682 if( rc==SQLITE_OK ){
3683 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3684 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
3685 }
3686 }else{
3687 rc = SQLITE_DONE;
drhdd3cd972010-03-27 17:12:36 +00003688 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003689 }
drhd677b3d2007-08-20 22:48:41 +00003690 sqlite3BtreeLeave(p);
3691 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003692}
3693
3694/*
danielk19773b8a05f2007-03-19 17:44:26 +00003695** This routine is called prior to sqlite3PagerCommit when a transaction
drhf7b54962013-05-28 12:11:54 +00003696** is committed for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00003697**
3698** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
3699** the database file should be truncated to during the commit process.
3700** i.e. the database has been reorganized so that only the first *pnTrunc
3701** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00003702*/
danielk19773460d192008-12-27 15:23:13 +00003703static int autoVacuumCommit(BtShared *pBt){
danielk1977dddbcdc2007-04-26 14:42:34 +00003704 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00003705 Pager *pPager = pBt->pPager;
mistachkinc29cbb02015-07-02 16:52:01 +00003706 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
danielk1977687566d2004-11-02 12:56:41 +00003707
drh1fee73e2007-08-29 04:00:57 +00003708 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00003709 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00003710 assert(pBt->autoVacuum);
3711 if( !pBt->incrVacuum ){
drhea8ffdf2009-07-22 00:35:23 +00003712 Pgno nFin; /* Number of pages in database after autovacuuming */
3713 Pgno nFree; /* Number of pages on the freelist initially */
drh41d628c2009-07-11 17:04:08 +00003714 Pgno iFree; /* The next page to be freed */
drh41d628c2009-07-11 17:04:08 +00003715 Pgno nOrig; /* Database size before freeing */
danielk1977687566d2004-11-02 12:56:41 +00003716
drhb1299152010-03-30 22:58:33 +00003717 nOrig = btreePagecount(pBt);
danielk1977ef165ce2009-04-06 17:50:03 +00003718 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
3719 /* It is not possible to create a database for which the final page
3720 ** is either a pointer-map page or the pending-byte page. If one
3721 ** is encountered, this indicates corruption.
3722 */
danielk19773460d192008-12-27 15:23:13 +00003723 return SQLITE_CORRUPT_BKPT;
3724 }
danielk1977ef165ce2009-04-06 17:50:03 +00003725
danielk19773460d192008-12-27 15:23:13 +00003726 nFree = get4byte(&pBt->pPage1->aData[36]);
dan51f0b6d2013-02-22 20:16:34 +00003727 nFin = finalDbSize(pBt, nOrig, nFree);
drhc5e47ac2009-06-04 00:11:56 +00003728 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
dan0aed84d2013-03-26 14:16:20 +00003729 if( nFin<nOrig ){
3730 rc = saveAllCursors(pBt, 0, 0);
3731 }
danielk19773460d192008-12-27 15:23:13 +00003732 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
dan51f0b6d2013-02-22 20:16:34 +00003733 rc = incrVacuumStep(pBt, nFin, iFree, 1);
danielk1977dddbcdc2007-04-26 14:42:34 +00003734 }
danielk19773460d192008-12-27 15:23:13 +00003735 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
danielk19773460d192008-12-27 15:23:13 +00003736 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3737 put4byte(&pBt->pPage1->aData[32], 0);
3738 put4byte(&pBt->pPage1->aData[36], 0);
drhdd3cd972010-03-27 17:12:36 +00003739 put4byte(&pBt->pPage1->aData[28], nFin);
danbc1a3c62013-02-23 16:40:46 +00003740 pBt->bDoTruncate = 1;
drhdd3cd972010-03-27 17:12:36 +00003741 pBt->nPage = nFin;
danielk1977dddbcdc2007-04-26 14:42:34 +00003742 }
3743 if( rc!=SQLITE_OK ){
3744 sqlite3PagerRollback(pPager);
3745 }
danielk1977687566d2004-11-02 12:56:41 +00003746 }
3747
dan0aed84d2013-03-26 14:16:20 +00003748 assert( nRef>=sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00003749 return rc;
3750}
danielk1977dddbcdc2007-04-26 14:42:34 +00003751
danielk1977a50d9aa2009-06-08 14:49:45 +00003752#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
3753# define setChildPtrmaps(x) SQLITE_OK
3754#endif
danielk1977687566d2004-11-02 12:56:41 +00003755
3756/*
drh80e35f42007-03-30 14:06:34 +00003757** This routine does the first phase of a two-phase commit. This routine
3758** causes a rollback journal to be created (if it does not already exist)
3759** and populated with enough information so that if a power loss occurs
3760** the database can be restored to its original state by playing back
3761** the journal. Then the contents of the journal are flushed out to
3762** the disk. After the journal is safely on oxide, the changes to the
3763** database are written into the database file and flushed to oxide.
3764** At the end of this call, the rollback journal still exists on the
3765** disk and we are still holding all locks, so the transaction has not
drh51898cf2009-04-19 20:51:06 +00003766** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
drh80e35f42007-03-30 14:06:34 +00003767** commit process.
3768**
3769** This call is a no-op if no write-transaction is currently active on pBt.
3770**
3771** Otherwise, sync the database file for the btree pBt. zMaster points to
3772** the name of a master journal file that should be written into the
3773** individual journal file, or is NULL, indicating no master journal file
3774** (single database transaction).
3775**
3776** When this is called, the master journal should already have been
3777** created, populated with this journal pointer and synced to disk.
3778**
3779** Once this is routine has returned, the only thing required to commit
3780** the write-transaction for this database file is to delete the journal.
3781*/
3782int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
3783 int rc = SQLITE_OK;
3784 if( p->inTrans==TRANS_WRITE ){
3785 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003786 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00003787#ifndef SQLITE_OMIT_AUTOVACUUM
3788 if( pBt->autoVacuum ){
danielk19773460d192008-12-27 15:23:13 +00003789 rc = autoVacuumCommit(pBt);
drh80e35f42007-03-30 14:06:34 +00003790 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00003791 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003792 return rc;
3793 }
3794 }
danbc1a3c62013-02-23 16:40:46 +00003795 if( pBt->bDoTruncate ){
3796 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
3797 }
drh80e35f42007-03-30 14:06:34 +00003798#endif
drh49b9d332009-01-02 18:10:42 +00003799 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
drhd677b3d2007-08-20 22:48:41 +00003800 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003801 }
3802 return rc;
3803}
3804
3805/*
danielk197794b30732009-07-02 17:21:57 +00003806** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
3807** at the conclusion of a transaction.
3808*/
3809static void btreeEndTransaction(Btree *p){
3810 BtShared *pBt = p->pBt;
drh1713afb2013-06-28 01:24:57 +00003811 sqlite3 *db = p->db;
danielk197794b30732009-07-02 17:21:57 +00003812 assert( sqlite3BtreeHoldsMutex(p) );
3813
danbc1a3c62013-02-23 16:40:46 +00003814#ifndef SQLITE_OMIT_AUTOVACUUM
3815 pBt->bDoTruncate = 0;
3816#endif
danc0537fe2013-06-28 19:41:43 +00003817 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
danfa401de2009-10-16 14:55:03 +00003818 /* If there are other active statements that belong to this database
3819 ** handle, downgrade to a read-only transaction. The other statements
3820 ** may still be reading from the database. */
danielk197794b30732009-07-02 17:21:57 +00003821 downgradeAllSharedCacheTableLocks(p);
3822 p->inTrans = TRANS_READ;
3823 }else{
3824 /* If the handle had any kind of transaction open, decrement the
3825 ** transaction count of the shared btree. If the transaction count
3826 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
3827 ** call below will unlock the pager. */
3828 if( p->inTrans!=TRANS_NONE ){
3829 clearAllSharedCacheTableLocks(p);
3830 pBt->nTransaction--;
3831 if( 0==pBt->nTransaction ){
3832 pBt->inTransaction = TRANS_NONE;
3833 }
3834 }
3835
3836 /* Set the current transaction state to TRANS_NONE and unlock the
3837 ** pager if this call closed the only read or write transaction. */
3838 p->inTrans = TRANS_NONE;
3839 unlockBtreeIfUnused(pBt);
3840 }
3841
3842 btreeIntegrity(p);
3843}
3844
3845/*
drh2aa679f2001-06-25 02:11:07 +00003846** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00003847**
drh6e345992007-03-30 11:12:08 +00003848** This routine implements the second phase of a 2-phase commit. The
drh51898cf2009-04-19 20:51:06 +00003849** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
3850** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
3851** routine did all the work of writing information out to disk and flushing the
drh6e345992007-03-30 11:12:08 +00003852** contents so that they are written onto the disk platter. All this
drh51898cf2009-04-19 20:51:06 +00003853** routine has to do is delete or truncate or zero the header in the
3854** the rollback journal (which causes the transaction to commit) and
3855** drop locks.
drh6e345992007-03-30 11:12:08 +00003856**
dan60939d02011-03-29 15:40:55 +00003857** Normally, if an error occurs while the pager layer is attempting to
3858** finalize the underlying journal file, this function returns an error and
3859** the upper layer will attempt a rollback. However, if the second argument
3860** is non-zero then this b-tree transaction is part of a multi-file
3861** transaction. In this case, the transaction has already been committed
3862** (by deleting a master journal file) and the caller will ignore this
3863** functions return code. So, even if an error occurs in the pager layer,
3864** reset the b-tree objects internal state to indicate that the write
3865** transaction has been closed. This is quite safe, as the pager will have
3866** transitioned to the error state.
3867**
drh5e00f6c2001-09-13 13:46:56 +00003868** This will release the write lock on the database file. If there
3869** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00003870*/
dan60939d02011-03-29 15:40:55 +00003871int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
danielk1977aef0bf62005-12-30 16:28:01 +00003872
drh075ed302010-10-14 01:17:30 +00003873 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003874 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003875 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003876
3877 /* If the handle has a write-transaction open, commit the shared-btrees
3878 ** transaction and set the shared state to TRANS_READ.
3879 */
3880 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00003881 int rc;
drh075ed302010-10-14 01:17:30 +00003882 BtShared *pBt = p->pBt;
danielk1977aef0bf62005-12-30 16:28:01 +00003883 assert( pBt->inTransaction==TRANS_WRITE );
3884 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00003885 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
dan60939d02011-03-29 15:40:55 +00003886 if( rc!=SQLITE_OK && bCleanup==0 ){
drhd677b3d2007-08-20 22:48:41 +00003887 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00003888 return rc;
3889 }
drh3da9c042014-12-22 18:41:21 +00003890 p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
danielk1977aef0bf62005-12-30 16:28:01 +00003891 pBt->inTransaction = TRANS_READ;
danbf0e57a2013-05-14 20:36:31 +00003892 btreeClearHasContent(pBt);
danielk1977ee5741e2004-05-31 10:01:34 +00003893 }
danielk1977aef0bf62005-12-30 16:28:01 +00003894
danielk197794b30732009-07-02 17:21:57 +00003895 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00003896 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00003897 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003898}
3899
drh80e35f42007-03-30 14:06:34 +00003900/*
3901** Do both phases of a commit.
3902*/
3903int sqlite3BtreeCommit(Btree *p){
3904 int rc;
drhd677b3d2007-08-20 22:48:41 +00003905 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00003906 rc = sqlite3BtreeCommitPhaseOne(p, 0);
3907 if( rc==SQLITE_OK ){
dan60939d02011-03-29 15:40:55 +00003908 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
drh80e35f42007-03-30 14:06:34 +00003909 }
drhd677b3d2007-08-20 22:48:41 +00003910 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003911 return rc;
3912}
3913
drhc39e0002004-05-07 23:50:57 +00003914/*
drhfb982642007-08-30 01:19:59 +00003915** This routine sets the state to CURSOR_FAULT and the error
drh47b7fc72014-11-11 01:33:57 +00003916** code to errCode for every cursor on any BtShared that pBtree
3917** references. Or if the writeOnly flag is set to 1, then only
3918** trip write cursors and leave read cursors unchanged.
drhfb982642007-08-30 01:19:59 +00003919**
drh47b7fc72014-11-11 01:33:57 +00003920** Every cursor is a candidate to be tripped, including cursors
3921** that belong to other database connections that happen to be
3922** sharing the cache with pBtree.
drhfb982642007-08-30 01:19:59 +00003923**
dan80231042014-11-12 14:56:02 +00003924** This routine gets called when a rollback occurs. If the writeOnly
3925** flag is true, then only write-cursors need be tripped - read-only
3926** cursors save their current positions so that they may continue
3927** following the rollback. Or, if writeOnly is false, all cursors are
3928** tripped. In general, writeOnly is false if the transaction being
3929** rolled back modified the database schema. In this case b-tree root
3930** pages may be moved or deleted from the database altogether, making
3931** it unsafe for read cursors to continue.
3932**
3933** If the writeOnly flag is true and an error is encountered while
3934** saving the current position of a read-only cursor, all cursors,
3935** including all read-cursors are tripped.
3936**
3937** SQLITE_OK is returned if successful, or if an error occurs while
3938** saving a cursor position, an SQLite error code.
drhfb982642007-08-30 01:19:59 +00003939*/
dan80231042014-11-12 14:56:02 +00003940int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
drhfb982642007-08-30 01:19:59 +00003941 BtCursor *p;
dan80231042014-11-12 14:56:02 +00003942 int rc = SQLITE_OK;
3943
drh47b7fc72014-11-11 01:33:57 +00003944 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
dan80231042014-11-12 14:56:02 +00003945 if( pBtree ){
3946 sqlite3BtreeEnter(pBtree);
3947 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
3948 int i;
3949 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
drhd2f83132015-03-25 17:35:01 +00003950 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
drhbea3b972014-11-18 20:22:05 +00003951 rc = saveCursorPosition(p);
dan80231042014-11-12 14:56:02 +00003952 if( rc!=SQLITE_OK ){
3953 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
3954 break;
3955 }
3956 }
3957 }else{
3958 sqlite3BtreeClearCursor(p);
3959 p->eState = CURSOR_FAULT;
3960 p->skipNext = errCode;
3961 }
3962 for(i=0; i<=p->iPage; i++){
3963 releasePage(p->apPage[i]);
3964 p->apPage[i] = 0;
3965 }
danielk1977bc2ca9e2008-11-13 14:28:28 +00003966 }
dan80231042014-11-12 14:56:02 +00003967 sqlite3BtreeLeave(pBtree);
drhfb982642007-08-30 01:19:59 +00003968 }
dan80231042014-11-12 14:56:02 +00003969 return rc;
drhfb982642007-08-30 01:19:59 +00003970}
3971
3972/*
drh47b7fc72014-11-11 01:33:57 +00003973** Rollback the transaction in progress.
3974**
3975** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
3976** Only write cursors are tripped if writeOnly is true but all cursors are
3977** tripped if writeOnly is false. Any attempt to use
3978** a tripped cursor will result in an error.
drh5e00f6c2001-09-13 13:46:56 +00003979**
3980** This will release the write lock on the database file. If there
3981** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00003982*/
drh47b7fc72014-11-11 01:33:57 +00003983int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
danielk19778d34dfd2006-01-24 16:37:57 +00003984 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003985 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00003986 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00003987
drh47b7fc72014-11-11 01:33:57 +00003988 assert( writeOnly==1 || writeOnly==0 );
3989 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
drhd677b3d2007-08-20 22:48:41 +00003990 sqlite3BtreeEnter(p);
drh0f198a72012-02-13 16:43:16 +00003991 if( tripCode==SQLITE_OK ){
3992 rc = tripCode = saveAllCursors(pBt, 0, 0);
drh47b7fc72014-11-11 01:33:57 +00003993 if( rc ) writeOnly = 0;
drh0f198a72012-02-13 16:43:16 +00003994 }else{
3995 rc = SQLITE_OK;
danielk19772b8c13e2006-01-24 14:21:24 +00003996 }
drh0f198a72012-02-13 16:43:16 +00003997 if( tripCode ){
dan80231042014-11-12 14:56:02 +00003998 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
3999 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4000 if( rc2!=SQLITE_OK ) rc = rc2;
drh0f198a72012-02-13 16:43:16 +00004001 }
danielk1977aef0bf62005-12-30 16:28:01 +00004002 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00004003
4004 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00004005 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00004006
danielk19778d34dfd2006-01-24 16:37:57 +00004007 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00004008 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00004009 if( rc2!=SQLITE_OK ){
4010 rc = rc2;
4011 }
4012
drh24cd67e2004-05-10 16:18:47 +00004013 /* The rollback may have destroyed the pPage1->aData value. So
danielk197730548662009-07-09 05:07:37 +00004014 ** call btreeGetPage() on page 1 again to make
drh16a9b832007-05-05 18:39:25 +00004015 ** sure pPage1->aData is set correctly. */
drhb00fc3b2013-08-21 23:42:32 +00004016 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh1f5b4672010-04-01 02:22:19 +00004017 int nPage = get4byte(28+(u8*)pPage1->aData);
4018 testcase( nPage==0 );
4019 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
4020 testcase( pBt->nPage!=nPage );
4021 pBt->nPage = nPage;
drh24cd67e2004-05-10 16:18:47 +00004022 releasePage(pPage1);
4023 }
drh85ec3b62013-05-14 23:12:06 +00004024 assert( countValidCursors(pBt, 1)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00004025 pBt->inTransaction = TRANS_READ;
danbf0e57a2013-05-14 20:36:31 +00004026 btreeClearHasContent(pBt);
drh24cd67e2004-05-10 16:18:47 +00004027 }
danielk1977aef0bf62005-12-30 16:28:01 +00004028
danielk197794b30732009-07-02 17:21:57 +00004029 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00004030 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00004031 return rc;
4032}
4033
4034/*
peter.d.reid60ec9142014-09-06 16:39:46 +00004035** Start a statement subtransaction. The subtransaction can be rolled
danielk1977bd434552009-03-18 10:33:00 +00004036** back independently of the main transaction. You must start a transaction
4037** before starting a subtransaction. The subtransaction is ended automatically
4038** if the main transaction commits or rolls back.
drhab01f612004-05-22 02:55:23 +00004039**
4040** Statement subtransactions are used around individual SQL statements
4041** that are contained within a BEGIN...COMMIT block. If a constraint
4042** error occurs within the statement, the effect of that one statement
4043** can be rolled back without having to rollback the entire transaction.
danielk1977bd434552009-03-18 10:33:00 +00004044**
4045** A statement sub-transaction is implemented as an anonymous savepoint. The
4046** value passed as the second parameter is the total number of savepoints,
4047** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4048** are no active savepoints and no other statement-transactions open,
4049** iStatement is 1. This anonymous savepoint can be released or rolled back
4050** using the sqlite3BtreeSavepoint() function.
drh663fc632002-02-02 18:49:19 +00004051*/
danielk1977bd434552009-03-18 10:33:00 +00004052int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
drh663fc632002-02-02 18:49:19 +00004053 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00004054 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00004055 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00004056 assert( p->inTrans==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00004057 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk1977bd434552009-03-18 10:33:00 +00004058 assert( iStatement>0 );
4059 assert( iStatement>p->db->nSavepoint );
drh5e0ccc22010-03-29 19:36:52 +00004060 assert( pBt->inTransaction==TRANS_WRITE );
4061 /* At the pager level, a statement transaction is a savepoint with
4062 ** an index greater than all savepoints created explicitly using
4063 ** SQL statements. It is illegal to open, release or rollback any
4064 ** such savepoints while the statement transaction savepoint is active.
4065 */
4066 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
drhd677b3d2007-08-20 22:48:41 +00004067 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00004068 return rc;
4069}
4070
4071/*
danielk1977fd7f0452008-12-17 17:30:26 +00004072** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4073** or SAVEPOINT_RELEASE. This function either releases or rolls back the
danielk197712dd5492008-12-18 15:45:07 +00004074** savepoint identified by parameter iSavepoint, depending on the value
4075** of op.
4076**
4077** Normally, iSavepoint is greater than or equal to zero. However, if op is
4078** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4079** contents of the entire transaction are rolled back. This is different
4080** from a normal transaction rollback, as no locks are released and the
4081** transaction remains open.
danielk1977fd7f0452008-12-17 17:30:26 +00004082*/
4083int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4084 int rc = SQLITE_OK;
4085 if( p && p->inTrans==TRANS_WRITE ){
4086 BtShared *pBt = p->pBt;
danielk1977fd7f0452008-12-17 17:30:26 +00004087 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4088 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4089 sqlite3BtreeEnter(p);
drh2343c7e2017-02-02 00:46:55 +00004090 if( op==SAVEPOINT_ROLLBACK ){
4091 rc = saveAllCursors(pBt, 0, 0);
4092 }
4093 if( rc==SQLITE_OK ){
4094 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4095 }
drh9f0bbf92009-01-02 21:08:09 +00004096 if( rc==SQLITE_OK ){
drhc9166342012-01-05 23:32:06 +00004097 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4098 pBt->nPage = 0;
4099 }
drh9f0bbf92009-01-02 21:08:09 +00004100 rc = newDatabase(pBt);
drhdd3cd972010-03-27 17:12:36 +00004101 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
drhb9b49bf2010-08-05 03:21:39 +00004102
4103 /* The database size was written into the offset 28 of the header
4104 ** when the transaction started, so we know that the value at offset
4105 ** 28 is nonzero. */
4106 assert( pBt->nPage>0 );
drh9f0bbf92009-01-02 21:08:09 +00004107 }
danielk1977fd7f0452008-12-17 17:30:26 +00004108 sqlite3BtreeLeave(p);
4109 }
4110 return rc;
4111}
4112
4113/*
drh8b2f49b2001-06-08 00:21:52 +00004114** Create a new cursor for the BTree whose root is on the page
danielk19773e8add92009-07-04 17:16:00 +00004115** iTable. If a read-only cursor is requested, it is assumed that
4116** the caller already has at least a read-only transaction open
4117** on the database already. If a write-cursor is requested, then
4118** the caller is assumed to have an open write transaction.
drh1bee3d72001-10-15 00:44:35 +00004119**
drhe807bdb2016-01-21 17:06:33 +00004120** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4121** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
4122** can be used for reading or for writing if other conditions for writing
4123** are also met. These are the conditions that must be met in order
4124** for writing to be allowed:
drh6446c4d2001-12-15 14:22:18 +00004125**
drhe807bdb2016-01-21 17:06:33 +00004126** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
drhf74b8d92002-09-01 23:20:45 +00004127**
drhfe5d71d2007-03-19 11:54:10 +00004128** 2: Other database connections that share the same pager cache
4129** but which are not in the READ_UNCOMMITTED state may not have
4130** cursors open with wrFlag==0 on the same table. Otherwise
4131** the changes made by this write cursor would be visible to
4132** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00004133**
4134** 3: The database must be writable (not on read-only media)
4135**
4136** 4: There must be an active transaction.
4137**
drhe807bdb2016-01-21 17:06:33 +00004138** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4139** is set. If FORDELETE is set, that is a hint to the implementation that
4140** this cursor will only be used to seek to and delete entries of an index
4141** as part of a larger DELETE statement. The FORDELETE hint is not used by
4142** this implementation. But in a hypothetical alternative storage engine
4143** in which index entries are automatically deleted when corresponding table
4144** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4145** operations on this cursor can be no-ops and all READ operations can
4146** return a null row (2-bytes: 0x01 0x00).
4147**
drh6446c4d2001-12-15 14:22:18 +00004148** No checking is done to make sure that page iTable really is the
4149** root page of a b-tree. If it is not, then the cursor acquired
4150** will not work correctly.
danielk197771d5d2c2008-09-29 11:49:47 +00004151**
drhf25a5072009-11-18 23:01:25 +00004152** It is assumed that the sqlite3BtreeCursorZero() has been called
4153** on pCur to initialize the memory space prior to invoking this routine.
drha059ad02001-04-17 20:09:11 +00004154*/
drhd677b3d2007-08-20 22:48:41 +00004155static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00004156 Btree *p, /* The btree */
4157 int iTable, /* Root page of table to open */
4158 int wrFlag, /* 1 to write. 0 read-only */
4159 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4160 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00004161){
danielk19773e8add92009-07-04 17:16:00 +00004162 BtShared *pBt = p->pBt; /* Shared b-tree handle */
drh27fb7462015-06-30 02:47:36 +00004163 BtCursor *pX; /* Looping over other all cursors */
drhecdc7532001-09-23 02:35:53 +00004164
drh1fee73e2007-08-29 04:00:57 +00004165 assert( sqlite3BtreeHoldsMutex(p) );
danfd261ec2015-10-22 20:54:33 +00004166 assert( wrFlag==0
4167 || wrFlag==BTREE_WRCSR
4168 || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4169 );
danielk197796d48e92009-06-29 06:00:37 +00004170
danielk1977602b4662009-07-02 07:47:33 +00004171 /* The following assert statements verify that if this is a sharable
4172 ** b-tree database, the connection is holding the required table locks,
4173 ** and that no other connection has any open cursor that conflicts with
4174 ** this lock. */
danfd261ec2015-10-22 20:54:33 +00004175 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
danielk197796d48e92009-06-29 06:00:37 +00004176 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
4177
danielk19773e8add92009-07-04 17:16:00 +00004178 /* Assert that the caller has opened the required transaction. */
4179 assert( p->inTrans>TRANS_NONE );
4180 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
4181 assert( pBt->pPage1 && pBt->pPage1->aData );
drh98ef0f62015-06-30 01:25:52 +00004182 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk19773e8add92009-07-04 17:16:00 +00004183
drh3fbb0222014-09-24 19:47:27 +00004184 if( wrFlag ){
4185 allocateTempSpace(pBt);
mistachkinfad30392016-02-13 23:43:46 +00004186 if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
drha0c9a112004-03-10 13:42:37 +00004187 }
drhb1299152010-03-30 22:58:33 +00004188 if( iTable==1 && btreePagecount(pBt)==0 ){
dana205a482011-08-27 18:48:57 +00004189 assert( wrFlag==0 );
4190 iTable = 0;
danielk19773e8add92009-07-04 17:16:00 +00004191 }
danielk1977aef0bf62005-12-30 16:28:01 +00004192
danielk1977aef0bf62005-12-30 16:28:01 +00004193 /* Now that no other errors can occur, finish filling in the BtCursor
danielk19773e8add92009-07-04 17:16:00 +00004194 ** variables and link the cursor into the BtShared list. */
danielk1977172114a2009-07-07 15:47:12 +00004195 pCur->pgnoRoot = (Pgno)iTable;
4196 pCur->iPage = -1;
drh1e968a02008-03-25 00:22:21 +00004197 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00004198 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00004199 pCur->pBt = pBt;
danfd261ec2015-10-22 20:54:33 +00004200 pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
drh28f58dd2015-06-27 19:45:03 +00004201 pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
drh27fb7462015-06-30 02:47:36 +00004202 /* If there are two or more cursors on the same btree, then all such
4203 ** cursors *must* have the BTCF_Multiple flag set. */
4204 for(pX=pBt->pCursor; pX; pX=pX->pNext){
4205 if( pX->pgnoRoot==(Pgno)iTable ){
4206 pX->curFlags |= BTCF_Multiple;
4207 pCur->curFlags |= BTCF_Multiple;
4208 }
drha059ad02001-04-17 20:09:11 +00004209 }
drh27fb7462015-06-30 02:47:36 +00004210 pCur->pNext = pBt->pCursor;
drha059ad02001-04-17 20:09:11 +00004211 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00004212 pCur->eState = CURSOR_INVALID;
danielk1977aef0bf62005-12-30 16:28:01 +00004213 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00004214}
drhd677b3d2007-08-20 22:48:41 +00004215int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00004216 Btree *p, /* The btree */
4217 int iTable, /* Root page of table to open */
4218 int wrFlag, /* 1 to write. 0 read-only */
4219 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
4220 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00004221){
4222 int rc;
dan08f901b2015-05-25 19:24:36 +00004223 if( iTable<1 ){
4224 rc = SQLITE_CORRUPT_BKPT;
4225 }else{
4226 sqlite3BtreeEnter(p);
4227 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4228 sqlite3BtreeLeave(p);
4229 }
drhd677b3d2007-08-20 22:48:41 +00004230 return rc;
4231}
drh7f751222009-03-17 22:33:00 +00004232
4233/*
4234** Return the size of a BtCursor object in bytes.
4235**
4236** This interfaces is needed so that users of cursors can preallocate
4237** sufficient storage to hold a cursor. The BtCursor object is opaque
4238** to users so they cannot do the sizeof() themselves - they must call
4239** this routine.
4240*/
4241int sqlite3BtreeCursorSize(void){
drhc54055b2009-11-13 17:05:53 +00004242 return ROUND8(sizeof(BtCursor));
danielk1977cd3e8f72008-03-25 09:47:35 +00004243}
4244
drh7f751222009-03-17 22:33:00 +00004245/*
drhf25a5072009-11-18 23:01:25 +00004246** Initialize memory that will be converted into a BtCursor object.
4247**
4248** The simple approach here would be to memset() the entire object
4249** to zero. But it turns out that the apPage[] and aiIdx[] arrays
4250** do not need to be zeroed and they are large, so we can save a lot
4251** of run-time by skipping the initialization of those elements.
4252*/
4253void sqlite3BtreeCursorZero(BtCursor *p){
4254 memset(p, 0, offsetof(BtCursor, iPage));
4255}
4256
4257/*
drh5e00f6c2001-09-13 13:46:56 +00004258** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00004259** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00004260*/
drh3aac2dd2004-04-26 14:10:20 +00004261int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00004262 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00004263 if( pBtree ){
danielk197771d5d2c2008-09-29 11:49:47 +00004264 int i;
danielk1977cd3e8f72008-03-25 09:47:35 +00004265 BtShared *pBt = pCur->pBt;
4266 sqlite3BtreeEnter(pBtree);
danielk1977be51a652008-10-08 17:58:48 +00004267 sqlite3BtreeClearCursor(pCur);
drh27fb7462015-06-30 02:47:36 +00004268 assert( pBt->pCursor!=0 );
4269 if( pBt->pCursor==pCur ){
danielk1977cd3e8f72008-03-25 09:47:35 +00004270 pBt->pCursor = pCur->pNext;
drh27fb7462015-06-30 02:47:36 +00004271 }else{
4272 BtCursor *pPrev = pBt->pCursor;
4273 do{
4274 if( pPrev->pNext==pCur ){
4275 pPrev->pNext = pCur->pNext;
4276 break;
4277 }
4278 pPrev = pPrev->pNext;
4279 }while( ALWAYS(pPrev) );
danielk1977cd3e8f72008-03-25 09:47:35 +00004280 }
danielk197771d5d2c2008-09-29 11:49:47 +00004281 for(i=0; i<=pCur->iPage; i++){
4282 releasePage(pCur->apPage[i]);
4283 }
danielk1977cd3e8f72008-03-25 09:47:35 +00004284 unlockBtreeIfUnused(pBt);
dan85753662014-12-11 16:38:18 +00004285 sqlite3_free(pCur->aOverflow);
danielk1977cd3e8f72008-03-25 09:47:35 +00004286 /* sqlite3_free(pCur); */
4287 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00004288 }
drh8c42ca92001-06-22 19:15:00 +00004289 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00004290}
4291
drh5e2f8b92001-05-28 00:41:15 +00004292/*
drh86057612007-06-26 01:04:48 +00004293** Make sure the BtCursor* given in the argument has a valid
4294** BtCursor.info structure. If it is not already valid, call
danielk197730548662009-07-09 05:07:37 +00004295** btreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00004296**
4297** BtCursor.info is a cache of the information in the current cell.
danielk197730548662009-07-09 05:07:37 +00004298** Using this cache reduces the number of calls to btreeParseCell().
drh9188b382004-05-14 21:12:22 +00004299*/
drh9188b382004-05-14 21:12:22 +00004300#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00004301 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00004302 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00004303 int iPage = pCur->iPage;
drh51c6d962004-06-06 00:42:25 +00004304 memset(&info, 0, sizeof(info));
danielk197730548662009-07-09 05:07:37 +00004305 btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
dan7df42ab2014-01-20 18:25:44 +00004306 assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00004307 }
danielk19771cc5ed82007-05-16 17:28:43 +00004308#else
4309 #define assertCellInfo(x)
4310#endif
drhc5b41ac2015-06-17 02:11:46 +00004311static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
4312 if( pCur->info.nSize==0 ){
4313 int iPage = pCur->iPage;
4314 pCur->curFlags |= BTCF_ValidNKey;
4315 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
4316 }else{
4317 assertCellInfo(pCur);
drh86057612007-06-26 01:04:48 +00004318 }
drhc5b41ac2015-06-17 02:11:46 +00004319}
drh9188b382004-05-14 21:12:22 +00004320
drhea8ffdf2009-07-22 00:35:23 +00004321#ifndef NDEBUG /* The next routine used only within assert() statements */
4322/*
4323** Return true if the given BtCursor is valid. A valid cursor is one
4324** that is currently pointing to a row in a (non-empty) table.
4325** This is a verification routine is used only within assert() statements.
4326*/
4327int sqlite3BtreeCursorIsValid(BtCursor *pCur){
4328 return pCur && pCur->eState==CURSOR_VALID;
4329}
4330#endif /* NDEBUG */
drhd6ef5af2016-11-15 04:00:24 +00004331int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
4332 assert( pCur!=0 );
4333 return pCur->eState==CURSOR_VALID;
4334}
drhea8ffdf2009-07-22 00:35:23 +00004335
drh9188b382004-05-14 21:12:22 +00004336/*
drha7c90c42016-06-04 20:37:10 +00004337** Return the value of the integer key or "rowid" for a table btree.
4338** This routine is only valid for a cursor that is pointing into a
4339** ordinary table btree. If the cursor points to an index btree or
4340** is invalid, the result of this routine is undefined.
drh7e3b0a02001-04-28 16:52:40 +00004341*/
drha7c90c42016-06-04 20:37:10 +00004342i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00004343 assert( cursorHoldsMutex(pCur) );
drhc5352b92014-11-17 20:33:07 +00004344 assert( pCur->eState==CURSOR_VALID );
drha7c90c42016-06-04 20:37:10 +00004345 assert( pCur->curIntKey );
drhc5352b92014-11-17 20:33:07 +00004346 getCellInfo(pCur);
drha7c90c42016-06-04 20:37:10 +00004347 return pCur->info.nKey;
drha059ad02001-04-17 20:09:11 +00004348}
drh2af926b2001-05-15 00:39:25 +00004349
drh72f82862001-05-24 21:06:34 +00004350/*
drha7c90c42016-06-04 20:37:10 +00004351** Return the number of bytes of payload for the entry that pCur is
4352** currently pointing to. For table btrees, this will be the amount
4353** of data. For index btrees, this will be the size of the key.
drhea8ffdf2009-07-22 00:35:23 +00004354**
4355** The caller must guarantee that the cursor is pointing to a non-NULL
4356** valid entry. In other words, the calling procedure must guarantee
4357** that the cursor has Cursor.eState==CURSOR_VALID.
drh0e1c19e2004-05-11 00:58:56 +00004358*/
drha7c90c42016-06-04 20:37:10 +00004359u32 sqlite3BtreePayloadSize(BtCursor *pCur){
4360 assert( cursorHoldsMutex(pCur) );
drhea8ffdf2009-07-22 00:35:23 +00004361 assert( pCur->eState==CURSOR_VALID );
4362 getCellInfo(pCur);
drha7c90c42016-06-04 20:37:10 +00004363 return pCur->info.nPayload;
drh0e1c19e2004-05-11 00:58:56 +00004364}
4365
4366/*
danielk1977d04417962007-05-02 13:16:30 +00004367** Given the page number of an overflow page in the database (parameter
4368** ovfl), this function finds the page number of the next page in the
4369** linked list of overflow pages. If possible, it uses the auto-vacuum
4370** pointer-map data instead of reading the content of page ovfl to do so.
4371**
4372** If an error occurs an SQLite error code is returned. Otherwise:
4373**
danielk1977bea2a942009-01-20 17:06:27 +00004374** The page number of the next overflow page in the linked list is
4375** written to *pPgnoNext. If page ovfl is the last page in its linked
4376** list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00004377**
danielk1977bea2a942009-01-20 17:06:27 +00004378** If ppPage is not NULL, and a reference to the MemPage object corresponding
4379** to page number pOvfl was obtained, then *ppPage is set to point to that
4380** reference. It is the responsibility of the caller to call releasePage()
4381** on *ppPage to free the reference. In no reference was obtained (because
4382** the pointer-map was used to obtain the value for *pPgnoNext), then
4383** *ppPage is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00004384*/
4385static int getOverflowPage(
drhfa3be902009-07-07 02:44:07 +00004386 BtShared *pBt, /* The database file */
4387 Pgno ovfl, /* Current overflow page number */
danielk1977bea2a942009-01-20 17:06:27 +00004388 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
danielk1977d04417962007-05-02 13:16:30 +00004389 Pgno *pPgnoNext /* OUT: Next overflow page number */
4390){
4391 Pgno next = 0;
danielk1977bea2a942009-01-20 17:06:27 +00004392 MemPage *pPage = 0;
drh1bd10f82008-12-10 21:19:56 +00004393 int rc = SQLITE_OK;
danielk1977d04417962007-05-02 13:16:30 +00004394
drh1fee73e2007-08-29 04:00:57 +00004395 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bea2a942009-01-20 17:06:27 +00004396 assert(pPgnoNext);
danielk1977d04417962007-05-02 13:16:30 +00004397
4398#ifndef SQLITE_OMIT_AUTOVACUUM
4399 /* Try to find the next page in the overflow list using the
4400 ** autovacuum pointer-map pages. Guess that the next page in
4401 ** the overflow list is page number (ovfl+1). If that guess turns
4402 ** out to be wrong, fall back to loading the data of page
4403 ** number ovfl to determine the next page number.
4404 */
4405 if( pBt->autoVacuum ){
4406 Pgno pgno;
4407 Pgno iGuess = ovfl+1;
4408 u8 eType;
4409
4410 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4411 iGuess++;
4412 }
4413
drhb1299152010-03-30 22:58:33 +00004414 if( iGuess<=btreePagecount(pBt) ){
danielk1977d04417962007-05-02 13:16:30 +00004415 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
danielk1977bea2a942009-01-20 17:06:27 +00004416 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
danielk1977d04417962007-05-02 13:16:30 +00004417 next = iGuess;
danielk1977bea2a942009-01-20 17:06:27 +00004418 rc = SQLITE_DONE;
danielk1977d04417962007-05-02 13:16:30 +00004419 }
4420 }
4421 }
4422#endif
4423
danielk1977d8a3f3d2009-07-11 11:45:23 +00004424 assert( next==0 || rc==SQLITE_DONE );
danielk1977bea2a942009-01-20 17:06:27 +00004425 if( rc==SQLITE_OK ){
drhb00fc3b2013-08-21 23:42:32 +00004426 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
danielk1977d8a3f3d2009-07-11 11:45:23 +00004427 assert( rc==SQLITE_OK || pPage==0 );
4428 if( rc==SQLITE_OK ){
danielk1977d04417962007-05-02 13:16:30 +00004429 next = get4byte(pPage->aData);
4430 }
danielk1977443c0592009-01-16 15:21:05 +00004431 }
danielk197745d68822009-01-16 16:23:38 +00004432
danielk1977bea2a942009-01-20 17:06:27 +00004433 *pPgnoNext = next;
4434 if( ppPage ){
4435 *ppPage = pPage;
4436 }else{
4437 releasePage(pPage);
4438 }
4439 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
danielk1977d04417962007-05-02 13:16:30 +00004440}
4441
danielk1977da107192007-05-04 08:32:13 +00004442/*
4443** Copy data from a buffer to a page, or from a page to a buffer.
4444**
4445** pPayload is a pointer to data stored on database page pDbPage.
4446** If argument eOp is false, then nByte bytes of data are copied
4447** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4448** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4449** of data are copied from the buffer pBuf to pPayload.
4450**
4451** SQLITE_OK is returned on success, otherwise an error code.
4452*/
4453static int copyPayload(
4454 void *pPayload, /* Pointer to page data */
4455 void *pBuf, /* Pointer to buffer */
4456 int nByte, /* Number of bytes to copy */
4457 int eOp, /* 0 -> copy from page, 1 -> copy to page */
4458 DbPage *pDbPage /* Page containing pPayload */
4459){
4460 if( eOp ){
4461 /* Copy data from buffer to page (a write operation) */
4462 int rc = sqlite3PagerWrite(pDbPage);
4463 if( rc!=SQLITE_OK ){
4464 return rc;
4465 }
4466 memcpy(pPayload, pBuf, nByte);
4467 }else{
4468 /* Copy data from page to buffer (a read operation) */
4469 memcpy(pBuf, pPayload, nByte);
4470 }
4471 return SQLITE_OK;
4472}
danielk1977d04417962007-05-02 13:16:30 +00004473
4474/*
danielk19779f8d6402007-05-02 17:48:45 +00004475** This function is used to read or overwrite payload information
dan5a500af2014-03-11 20:33:04 +00004476** for the entry that the pCur cursor is pointing to. The eOp
4477** argument is interpreted as follows:
4478**
4479** 0: The operation is a read. Populate the overflow cache.
4480** 1: The operation is a write. Populate the overflow cache.
danielk19779f8d6402007-05-02 17:48:45 +00004481**
4482** A total of "amt" bytes are read or written beginning at "offset".
4483** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00004484**
drh3bcdfd22009-07-12 02:32:21 +00004485** The content being read or written might appear on the main page
4486** or be scattered out on multiple overflow pages.
danielk1977da107192007-05-04 08:32:13 +00004487**
drh42e28f12017-01-27 00:31:59 +00004488** If the current cursor entry uses one or more overflow pages
4489** this function may allocate space for and lazily populate
4490** the overflow page-list cache array (BtCursor.aOverflow).
dan5a500af2014-03-11 20:33:04 +00004491** Subsequent calls use this cache to make seeking to the supplied offset
4492** more efficient.
danielk1977da107192007-05-04 08:32:13 +00004493**
drh42e28f12017-01-27 00:31:59 +00004494** Once an overflow page-list cache has been allocated, it must be
danielk1977da107192007-05-04 08:32:13 +00004495** invalidated if some other cursor writes to the same table, or if
4496** the cursor is moved to a different row. Additionally, in auto-vacuum
4497** mode, the following events may invalidate an overflow page-list cache.
4498**
4499** * An incremental vacuum,
4500** * A commit in auto_vacuum="full" mode,
4501** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00004502*/
danielk19779f8d6402007-05-02 17:48:45 +00004503static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00004504 BtCursor *pCur, /* Cursor pointing to entry to read from */
danielk197789d40042008-11-17 14:20:56 +00004505 u32 offset, /* Begin reading this far into payload */
4506 u32 amt, /* Read this many bytes */
drh3aac2dd2004-04-26 14:10:20 +00004507 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00004508 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00004509){
4510 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00004511 int rc = SQLITE_OK;
danielk19772dec9702007-05-02 16:48:37 +00004512 int iIdx = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004513 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
danielk19770d065412008-11-12 18:21:36 +00004514 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh4c417182014-03-31 23:57:41 +00004515#ifdef SQLITE_DIRECT_OVERFLOW_READ
drh8bb9fd32017-01-26 16:27:32 +00004516 unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
drh4c417182014-03-31 23:57:41 +00004517#endif
drh3aac2dd2004-04-26 14:10:20 +00004518
danielk1977da107192007-05-04 08:32:13 +00004519 assert( pPage );
drh42e28f12017-01-27 00:31:59 +00004520 assert( eOp==0 || eOp==1 );
danielk1977da184232006-01-05 11:34:32 +00004521 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004522 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh1fee73e2007-08-29 04:00:57 +00004523 assert( cursorHoldsMutex(pCur) );
danielk1977da107192007-05-04 08:32:13 +00004524
drh86057612007-06-26 01:04:48 +00004525 getCellInfo(pCur);
drhab1cc582014-09-23 21:25:19 +00004526 aPayload = pCur->info.pPayload;
drhab1cc582014-09-23 21:25:19 +00004527 assert( offset+amt <= pCur->info.nPayload );
danielk1977da107192007-05-04 08:32:13 +00004528
drh0b982072016-03-22 14:10:45 +00004529 assert( aPayload > pPage->aData );
drhc5e7f942016-03-22 15:25:16 +00004530 if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
drh0b982072016-03-22 14:10:45 +00004531 /* Trying to read or write past the end of the data is an error. The
4532 ** conditional above is really:
4533 ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
4534 ** but is recast into its current form to avoid integer overflow problems
4535 */
danielk197767fd7a92008-09-10 17:53:35 +00004536 return SQLITE_CORRUPT_BKPT;
drh3aac2dd2004-04-26 14:10:20 +00004537 }
danielk1977da107192007-05-04 08:32:13 +00004538
4539 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00004540 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00004541 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00004542 if( a+offset>pCur->info.nLocal ){
4543 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00004544 }
drh42e28f12017-01-27 00:31:59 +00004545 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00004546 offset = 0;
drha34b6762004-05-07 13:30:42 +00004547 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00004548 amt -= a;
drhdd793422001-06-28 01:54:48 +00004549 }else{
drhfa1a98a2004-05-14 19:08:17 +00004550 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00004551 }
danielk1977da107192007-05-04 08:32:13 +00004552
dan85753662014-12-11 16:38:18 +00004553
danielk1977da107192007-05-04 08:32:13 +00004554 if( rc==SQLITE_OK && amt>0 ){
danielk197789d40042008-11-17 14:20:56 +00004555 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
danielk1977da107192007-05-04 08:32:13 +00004556 Pgno nextPage;
4557
drhfa1a98a2004-05-14 19:08:17 +00004558 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00004559
drha38c9512014-04-01 01:24:34 +00004560 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
drha38c9512014-04-01 01:24:34 +00004561 **
4562 ** The aOverflow[] array is sized at one entry for each overflow page
4563 ** in the overflow chain. The page number of the first overflow page is
4564 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
4565 ** means "not yet known" (the cache is lazily populated).
danielk1977da107192007-05-04 08:32:13 +00004566 */
drh42e28f12017-01-27 00:31:59 +00004567 if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
danielk19772dec9702007-05-02 16:48:37 +00004568 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
dan5a500af2014-03-11 20:33:04 +00004569 if( nOvfl>pCur->nOvflAlloc ){
dan85753662014-12-11 16:38:18 +00004570 Pgno *aNew = (Pgno*)sqlite3Realloc(
4571 pCur->aOverflow, nOvfl*2*sizeof(Pgno)
dan5a500af2014-03-11 20:33:04 +00004572 );
4573 if( aNew==0 ){
drhcd645532017-01-20 20:43:14 +00004574 return SQLITE_NOMEM_BKPT;
dan5a500af2014-03-11 20:33:04 +00004575 }else{
4576 pCur->nOvflAlloc = nOvfl*2;
4577 pCur->aOverflow = aNew;
4578 }
4579 }
drhcd645532017-01-20 20:43:14 +00004580 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
4581 pCur->curFlags |= BTCF_ValidOvfl;
drhcdf360a2017-01-27 01:13:49 +00004582 }else{
4583 /* If the overflow page-list cache has been allocated and the
4584 ** entry for the first required overflow page is valid, skip
4585 ** directly to it.
4586 */
4587 if( pCur->aOverflow[offset/ovflSize] ){
4588 iIdx = (offset/ovflSize);
4589 nextPage = pCur->aOverflow[iIdx];
4590 offset = (offset%ovflSize);
4591 }
danielk19772dec9702007-05-02 16:48:37 +00004592 }
danielk1977da107192007-05-04 08:32:13 +00004593
drhcd645532017-01-20 20:43:14 +00004594 assert( rc==SQLITE_OK && amt>0 );
4595 while( nextPage ){
danielk1977da107192007-05-04 08:32:13 +00004596 /* If required, populate the overflow page-list cache. */
drh42e28f12017-01-27 00:31:59 +00004597 assert( pCur->aOverflow[iIdx]==0
4598 || pCur->aOverflow[iIdx]==nextPage
4599 || CORRUPT_DB );
4600 pCur->aOverflow[iIdx] = nextPage;
danielk1977da107192007-05-04 08:32:13 +00004601
danielk1977d04417962007-05-02 13:16:30 +00004602 if( offset>=ovflSize ){
4603 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00004604 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00004605 ** data is not required. So first try to lookup the overflow
4606 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00004607 ** function.
danielk1977d04417962007-05-02 13:16:30 +00004608 */
drha38c9512014-04-01 01:24:34 +00004609 assert( pCur->curFlags & BTCF_ValidOvfl );
dan85753662014-12-11 16:38:18 +00004610 assert( pCur->pBtree->db==pBt->db );
drha38c9512014-04-01 01:24:34 +00004611 if( pCur->aOverflow[iIdx+1] ){
danielk1977da107192007-05-04 08:32:13 +00004612 nextPage = pCur->aOverflow[iIdx+1];
drha38c9512014-04-01 01:24:34 +00004613 }else{
danielk1977da107192007-05-04 08:32:13 +00004614 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
drha38c9512014-04-01 01:24:34 +00004615 }
danielk1977da107192007-05-04 08:32:13 +00004616 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00004617 }else{
danielk19779f8d6402007-05-02 17:48:45 +00004618 /* Need to read this page properly. It contains some of the
4619 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00004620 */
danf4ba1092011-10-08 14:57:07 +00004621#ifdef SQLITE_DIRECT_OVERFLOW_READ
drh8bb9fd32017-01-26 16:27:32 +00004622 sqlite3_file *fd; /* File from which to do direct overflow read */
danf4ba1092011-10-08 14:57:07 +00004623#endif
danielk1977cfe9a692004-06-16 12:00:29 +00004624 int a = amt;
danf4ba1092011-10-08 14:57:07 +00004625 if( a + offset > ovflSize ){
4626 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00004627 }
danf4ba1092011-10-08 14:57:07 +00004628
4629#ifdef SQLITE_DIRECT_OVERFLOW_READ
4630 /* If all the following are true:
4631 **
4632 ** 1) this is a read operation, and
4633 ** 2) data is required from the start of this overflow page, and
drh8bb9fd32017-01-26 16:27:32 +00004634 ** 3) there is no open write-transaction, and
4635 ** 4) the database is file-backed, and
drhd930b5c2017-01-26 02:26:02 +00004636 ** 5) the page is not in the WAL file
drh8bb9fd32017-01-26 16:27:32 +00004637 ** 6) at least 4 bytes have already been read into the output buffer
danf4ba1092011-10-08 14:57:07 +00004638 **
4639 ** then data can be read directly from the database file into the
4640 ** output buffer, bypassing the page-cache altogether. This speeds
4641 ** up loading large records that span many overflow pages.
4642 */
drh42e28f12017-01-27 00:31:59 +00004643 if( eOp==0 /* (1) */
danf4ba1092011-10-08 14:57:07 +00004644 && offset==0 /* (2) */
drh8bb9fd32017-01-26 16:27:32 +00004645 && pBt->inTransaction==TRANS_READ /* (3) */
4646 && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (4) */
drhd930b5c2017-01-26 02:26:02 +00004647 && 0==sqlite3PagerUseWal(pBt->pPager, nextPage) /* (5) */
drh8bb9fd32017-01-26 16:27:32 +00004648 && &pBuf[-4]>=pBufStart /* (6) */
danf4ba1092011-10-08 14:57:07 +00004649 ){
4650 u8 aSave[4];
4651 u8 *aWrite = &pBuf[-4];
drh8bb9fd32017-01-26 16:27:32 +00004652 assert( aWrite>=pBufStart ); /* due to (6) */
danf4ba1092011-10-08 14:57:07 +00004653 memcpy(aSave, aWrite, 4);
dan27d47fb2011-12-21 17:00:16 +00004654 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
danf4ba1092011-10-08 14:57:07 +00004655 nextPage = get4byte(aWrite);
4656 memcpy(aWrite, aSave, 4);
4657 }else
4658#endif
4659
4660 {
4661 DbPage *pDbPage;
drh9584f582015-11-04 20:22:37 +00004662 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
drh42e28f12017-01-27 00:31:59 +00004663 (eOp==0 ? PAGER_GET_READONLY : 0)
dan11dcd112013-03-15 18:29:18 +00004664 );
danf4ba1092011-10-08 14:57:07 +00004665 if( rc==SQLITE_OK ){
4666 aPayload = sqlite3PagerGetData(pDbPage);
4667 nextPage = get4byte(aPayload);
drh42e28f12017-01-27 00:31:59 +00004668 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
danf4ba1092011-10-08 14:57:07 +00004669 sqlite3PagerUnref(pDbPage);
4670 offset = 0;
4671 }
4672 }
4673 amt -= a;
drh6ee610b2017-01-27 01:25:00 +00004674 if( amt==0 ) return rc;
danf4ba1092011-10-08 14:57:07 +00004675 pBuf += a;
danielk1977cfe9a692004-06-16 12:00:29 +00004676 }
drhcd645532017-01-20 20:43:14 +00004677 if( rc ) break;
4678 iIdx++;
drh2af926b2001-05-15 00:39:25 +00004679 }
drh2af926b2001-05-15 00:39:25 +00004680 }
danielk1977cfe9a692004-06-16 12:00:29 +00004681
danielk1977da107192007-05-04 08:32:13 +00004682 if( rc==SQLITE_OK && amt>0 ){
drh6ee610b2017-01-27 01:25:00 +00004683 return SQLITE_CORRUPT_BKPT; /* Overflow chain ends prematurely */
drha7fcb052001-12-14 15:09:55 +00004684 }
danielk1977da107192007-05-04 08:32:13 +00004685 return rc;
drh2af926b2001-05-15 00:39:25 +00004686}
4687
drh72f82862001-05-24 21:06:34 +00004688/*
drhcb3cabd2016-11-25 19:18:28 +00004689** Read part of the payload for the row at which that cursor pCur is currently
4690** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00004691** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00004692**
drhcb3cabd2016-11-25 19:18:28 +00004693** pCur can be pointing to either a table or an index b-tree.
4694** If pointing to a table btree, then the content section is read. If
4695** pCur is pointing to an index b-tree then the key section is read.
4696**
4697** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
4698** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
4699** cursor might be invalid or might need to be restored before being read.
drh5d1a8722009-07-22 18:07:40 +00004700**
drh3aac2dd2004-04-26 14:10:20 +00004701** Return SQLITE_OK on success or an error code if anything goes
4702** wrong. An error is returned if "offset+amt" is larger than
4703** the available payload.
drh72f82862001-05-24 21:06:34 +00004704*/
drhcb3cabd2016-11-25 19:18:28 +00004705int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drh1fee73e2007-08-29 04:00:57 +00004706 assert( cursorHoldsMutex(pCur) );
drh5d1a8722009-07-22 18:07:40 +00004707 assert( pCur->eState==CURSOR_VALID );
4708 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
4709 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
4710 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
drh3aac2dd2004-04-26 14:10:20 +00004711}
drh83ec2762017-01-26 16:54:47 +00004712
4713/*
4714** This variant of sqlite3BtreePayload() works even if the cursor has not
4715** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
4716** interface.
4717*/
danielk19773588ceb2008-06-10 17:30:26 +00004718#ifndef SQLITE_OMIT_INCRBLOB
drh83ec2762017-01-26 16:54:47 +00004719static SQLITE_NOINLINE int accessPayloadChecked(
4720 BtCursor *pCur,
4721 u32 offset,
4722 u32 amt,
4723 void *pBuf
4724){
drhcb3cabd2016-11-25 19:18:28 +00004725 int rc;
danielk19773588ceb2008-06-10 17:30:26 +00004726 if ( pCur->eState==CURSOR_INVALID ){
4727 return SQLITE_ABORT;
4728 }
dan7a2347e2016-01-07 16:43:54 +00004729 assert( cursorOwnsBtShared(pCur) );
drh945b0942017-01-26 21:30:00 +00004730 rc = btreeRestoreCursorPosition(pCur);
drh83ec2762017-01-26 16:54:47 +00004731 return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
4732}
4733int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
4734 if( pCur->eState==CURSOR_VALID ){
4735 assert( cursorOwnsBtShared(pCur) );
4736 return accessPayload(pCur, offset, amt, pBuf, 0);
4737 }else{
4738 return accessPayloadChecked(pCur, offset, amt, pBuf);
danielk1977da184232006-01-05 11:34:32 +00004739 }
drh2af926b2001-05-15 00:39:25 +00004740}
drhcb3cabd2016-11-25 19:18:28 +00004741#endif /* SQLITE_OMIT_INCRBLOB */
drh2af926b2001-05-15 00:39:25 +00004742
drh72f82862001-05-24 21:06:34 +00004743/*
drh0e1c19e2004-05-11 00:58:56 +00004744** Return a pointer to payload information from the entry that the
4745** pCur cursor is pointing to. The pointer is to the beginning of
drh2a8d2262013-12-09 20:43:22 +00004746** the key if index btrees (pPage->intKey==0) and is the data for
4747** table btrees (pPage->intKey==1). The number of bytes of available
4748** key/data is written into *pAmt. If *pAmt==0, then the value
4749** returned will not be a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00004750**
4751** This routine is an optimization. It is common for the entire key
4752** and data to fit on the local page and for there to be no overflow
4753** pages. When that is so, this routine can be used to access the
4754** key and data without making a copy. If the key and/or data spills
drh7f751222009-03-17 22:33:00 +00004755** onto overflow pages, then accessPayload() must be used to reassemble
drh0e1c19e2004-05-11 00:58:56 +00004756** the key/data and copy it into a preallocated buffer.
4757**
4758** The pointer returned by this routine looks directly into the cached
4759** page of the database. The data might change or move the next time
4760** any btree routine is called.
4761*/
drh2a8d2262013-12-09 20:43:22 +00004762static const void *fetchPayload(
drh0e1c19e2004-05-11 00:58:56 +00004763 BtCursor *pCur, /* Cursor pointing to entry to read from */
drh2a8d2262013-12-09 20:43:22 +00004764 u32 *pAmt /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00004765){
drhf3392e32015-04-15 17:26:55 +00004766 u32 amt;
danielk197771d5d2c2008-09-29 11:49:47 +00004767 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
danielk1977da184232006-01-05 11:34:32 +00004768 assert( pCur->eState==CURSOR_VALID );
drh2a8d2262013-12-09 20:43:22 +00004769 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
dan7a2347e2016-01-07 16:43:54 +00004770 assert( cursorOwnsBtShared(pCur) );
drh2a8d2262013-12-09 20:43:22 +00004771 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh86dd3712014-03-25 11:00:21 +00004772 assert( pCur->info.nSize>0 );
drhf3392e32015-04-15 17:26:55 +00004773 assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
4774 assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
4775 amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
4776 if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
4777 *pAmt = amt;
drhab1cc582014-09-23 21:25:19 +00004778 return (void*)pCur->info.pPayload;
drh0e1c19e2004-05-11 00:58:56 +00004779}
4780
4781
4782/*
drhe51c44f2004-05-30 20:46:09 +00004783** For the entry that cursor pCur is point to, return as
4784** many bytes of the key or data as are available on the local
4785** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00004786**
4787** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00004788** or be destroyed on the next call to any Btree routine,
4789** including calls from other threads against the same cache.
4790** Hence, a mutex on the BtShared should be held prior to calling
4791** this routine.
drh0e1c19e2004-05-11 00:58:56 +00004792**
4793** These routines is used to get quick access to key and data
4794** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00004795*/
drha7c90c42016-06-04 20:37:10 +00004796const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
drh2a8d2262013-12-09 20:43:22 +00004797 return fetchPayload(pCur, pAmt);
drh0e1c19e2004-05-11 00:58:56 +00004798}
4799
4800
4801/*
drh8178a752003-01-05 21:41:40 +00004802** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00004803** page number of the child page to move to.
danielk1977a299d612009-07-13 11:22:10 +00004804**
4805** This function returns SQLITE_CORRUPT if the page-header flags field of
4806** the new child page does not match the flags field of the parent (i.e.
4807** if an intkey page appears to be the parent of a non-intkey page, or
4808** vice-versa).
drh72f82862001-05-24 21:06:34 +00004809*/
drh3aac2dd2004-04-26 14:10:20 +00004810static int moveToChild(BtCursor *pCur, u32 newPgno){
drhd0679ed2007-08-28 22:24:34 +00004811 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00004812
dan7a2347e2016-01-07 16:43:54 +00004813 assert( cursorOwnsBtShared(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004814 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004815 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
dan11dcd112013-03-15 18:29:18 +00004816 assert( pCur->iPage>=0 );
danielk197771d5d2c2008-09-29 11:49:47 +00004817 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
4818 return SQLITE_CORRUPT_BKPT;
4819 }
drh271efa52004-05-30 19:19:05 +00004820 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004821 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drh28f58dd2015-06-27 19:45:03 +00004822 pCur->iPage++;
4823 pCur->aiIdx[pCur->iPage] = 0;
4824 return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
4825 pCur, pCur->curPagerFlags);
drh72f82862001-05-24 21:06:34 +00004826}
4827
drhd879e3e2017-02-13 13:35:55 +00004828#ifdef SQLITE_DEBUG
danielk1977bf93c562008-09-29 15:53:25 +00004829/*
4830** Page pParent is an internal (non-leaf) tree page. This function
4831** asserts that page number iChild is the left-child if the iIdx'th
4832** cell in page pParent. Or, if iIdx is equal to the total number of
4833** cells in pParent, that page number iChild is the right-child of
4834** the page.
4835*/
4836static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
drhcbd33492015-03-25 13:06:54 +00004837 if( CORRUPT_DB ) return; /* The conditions tested below might not be true
4838 ** in a corrupt database */
danielk1977bf93c562008-09-29 15:53:25 +00004839 assert( iIdx<=pParent->nCell );
4840 if( iIdx==pParent->nCell ){
4841 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
4842 }else{
4843 assert( get4byte(findCell(pParent, iIdx))==iChild );
4844 }
4845}
4846#else
4847# define assertParentIndex(x,y,z)
4848#endif
4849
drh72f82862001-05-24 21:06:34 +00004850/*
drh5e2f8b92001-05-28 00:41:15 +00004851** Move the cursor up to the parent page.
4852**
4853** pCur->idx is set to the cell index that contains the pointer
4854** to the page we are coming from. If we are coming from the
4855** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00004856** the largest cell index.
drh72f82862001-05-24 21:06:34 +00004857*/
danielk197730548662009-07-09 05:07:37 +00004858static void moveToParent(BtCursor *pCur){
dan7a2347e2016-01-07 16:43:54 +00004859 assert( cursorOwnsBtShared(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004860 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004861 assert( pCur->iPage>0 );
4862 assert( pCur->apPage[pCur->iPage] );
danielk1977bf93c562008-09-29 15:53:25 +00004863 assertParentIndex(
4864 pCur->apPage[pCur->iPage-1],
4865 pCur->aiIdx[pCur->iPage-1],
4866 pCur->apPage[pCur->iPage]->pgno
4867 );
dan6c2688c2012-01-12 15:05:03 +00004868 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
drh271efa52004-05-30 19:19:05 +00004869 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004870 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drhbbf0f862015-06-27 14:59:26 +00004871 releasePageNotNull(pCur->apPage[pCur->iPage--]);
drh72f82862001-05-24 21:06:34 +00004872}
4873
4874/*
danielk19778f880a82009-07-13 09:41:45 +00004875** Move the cursor to point to the root page of its b-tree structure.
4876**
4877** If the table has a virtual root page, then the cursor is moved to point
4878** to the virtual root page instead of the actual root page. A table has a
4879** virtual root page when the actual root page contains no cells and a
4880** single child page. This can only happen with the table rooted at page 1.
4881**
4882** If the b-tree structure is empty, the cursor state is set to
4883** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
4884** cell located on the root (or virtual root) page and the cursor state
4885** is set to CURSOR_VALID.
4886**
4887** If this function returns successfully, it may be assumed that the
4888** page-header flags indicate that the [virtual] root-page is the expected
4889** kind of b-tree page (i.e. if when opening the cursor the caller did not
4890** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
4891** indicating a table b-tree, or if the caller did specify a KeyInfo
4892** structure the flags byte is set to 0x02 or 0x0A, indicating an index
4893** b-tree).
drh72f82862001-05-24 21:06:34 +00004894*/
drh5e2f8b92001-05-28 00:41:15 +00004895static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00004896 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00004897 int rc = SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00004898
dan7a2347e2016-01-07 16:43:54 +00004899 assert( cursorOwnsBtShared(pCur) );
drhfb982642007-08-30 01:19:59 +00004900 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
4901 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
4902 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
4903 if( pCur->eState>=CURSOR_REQUIRESEEK ){
4904 if( pCur->eState==CURSOR_FAULT ){
drh4c301aa2009-07-15 17:25:45 +00004905 assert( pCur->skipNext!=SQLITE_OK );
4906 return pCur->skipNext;
drhfb982642007-08-30 01:19:59 +00004907 }
danielk1977be51a652008-10-08 17:58:48 +00004908 sqlite3BtreeClearCursor(pCur);
drhbf700f32007-03-31 02:36:44 +00004909 }
danielk197771d5d2c2008-09-29 11:49:47 +00004910
4911 if( pCur->iPage>=0 ){
drh7ad3eb62016-10-24 01:01:09 +00004912 if( pCur->iPage ){
4913 do{
4914 assert( pCur->apPage[pCur->iPage]!=0 );
4915 releasePageNotNull(pCur->apPage[pCur->iPage--]);
4916 }while( pCur->iPage);
4917 goto skip_init;
drhbbf0f862015-06-27 14:59:26 +00004918 }
dana205a482011-08-27 18:48:57 +00004919 }else if( pCur->pgnoRoot==0 ){
4920 pCur->eState = CURSOR_INVALID;
4921 return SQLITE_OK;
drh777e4c42006-01-13 04:31:58 +00004922 }else{
drh28f58dd2015-06-27 19:45:03 +00004923 assert( pCur->iPage==(-1) );
drh4e8fe3f2013-12-06 23:25:27 +00004924 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
drh15a00212015-06-27 20:55:00 +00004925 0, pCur->curPagerFlags);
drh4c301aa2009-07-15 17:25:45 +00004926 if( rc!=SQLITE_OK ){
drh777e4c42006-01-13 04:31:58 +00004927 pCur->eState = CURSOR_INVALID;
drh7ad3eb62016-10-24 01:01:09 +00004928 return rc;
drh777e4c42006-01-13 04:31:58 +00004929 }
danielk1977172114a2009-07-07 15:47:12 +00004930 pCur->iPage = 0;
drh408efc02015-06-27 22:49:10 +00004931 pCur->curIntKey = pCur->apPage[0]->intKey;
drhc39e0002004-05-07 23:50:57 +00004932 }
danielk197771d5d2c2008-09-29 11:49:47 +00004933 pRoot = pCur->apPage[0];
4934 assert( pRoot->pgno==pCur->pgnoRoot );
dan7df42ab2014-01-20 18:25:44 +00004935
4936 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
4937 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
4938 ** NULL, the caller expects a table b-tree. If this is not the case,
4939 ** return an SQLITE_CORRUPT error.
4940 **
4941 ** Earlier versions of SQLite assumed that this test could not fail
4942 ** if the root page was already loaded when this function was called (i.e.
4943 ** if pCur->iPage>=0). But this is not so if the database is corrupted
4944 ** in such a way that page pRoot is linked into a second b-tree table
4945 ** (or the freelist). */
4946 assert( pRoot->intKey==1 || pRoot->intKey==0 );
4947 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
4948 return SQLITE_CORRUPT_BKPT;
4949 }
danielk19778f880a82009-07-13 09:41:45 +00004950
drh7ad3eb62016-10-24 01:01:09 +00004951skip_init:
danielk197771d5d2c2008-09-29 11:49:47 +00004952 pCur->aiIdx[0] = 0;
drh271efa52004-05-30 19:19:05 +00004953 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004954 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
danielk197771d5d2c2008-09-29 11:49:47 +00004955
drh7ad3eb62016-10-24 01:01:09 +00004956 pRoot = pCur->apPage[0];
drh4e8fe3f2013-12-06 23:25:27 +00004957 if( pRoot->nCell>0 ){
4958 pCur->eState = CURSOR_VALID;
4959 }else if( !pRoot->leaf ){
drh8856d6a2004-04-29 14:42:46 +00004960 Pgno subpage;
drhc85240d2009-06-04 16:14:33 +00004961 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
drh43605152004-05-29 21:46:49 +00004962 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
danielk1977da184232006-01-05 11:34:32 +00004963 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00004964 rc = moveToChild(pCur, subpage);
danielk197771d5d2c2008-09-29 11:49:47 +00004965 }else{
drh4e8fe3f2013-12-06 23:25:27 +00004966 pCur->eState = CURSOR_INVALID;
drh8856d6a2004-04-29 14:42:46 +00004967 }
4968 return rc;
drh72f82862001-05-24 21:06:34 +00004969}
drh2af926b2001-05-15 00:39:25 +00004970
drh5e2f8b92001-05-28 00:41:15 +00004971/*
4972** Move the cursor down to the left-most leaf entry beneath the
4973** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00004974**
4975** The left-most leaf is the one with the smallest key - the first
4976** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00004977*/
4978static int moveToLeftmost(BtCursor *pCur){
4979 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00004980 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00004981 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00004982
dan7a2347e2016-01-07 16:43:54 +00004983 assert( cursorOwnsBtShared(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004984 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004985 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
4986 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
4987 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
drh8178a752003-01-05 21:41:40 +00004988 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00004989 }
drhd677b3d2007-08-20 22:48:41 +00004990 return rc;
drh5e2f8b92001-05-28 00:41:15 +00004991}
4992
drh2dcc9aa2002-12-04 13:40:25 +00004993/*
4994** Move the cursor down to the right-most leaf entry beneath the
4995** page to which it is currently pointing. Notice the difference
4996** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
4997** finds the left-most entry beneath the *entry* whereas moveToRightmost()
4998** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00004999**
5000** The right-most entry is the one with the largest key - the last
5001** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00005002*/
5003static int moveToRightmost(BtCursor *pCur){
5004 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00005005 int rc = SQLITE_OK;
drh1bd10f82008-12-10 21:19:56 +00005006 MemPage *pPage = 0;
drh2dcc9aa2002-12-04 13:40:25 +00005007
dan7a2347e2016-01-07 16:43:54 +00005008 assert( cursorOwnsBtShared(pCur) );
danielk1977da184232006-01-05 11:34:32 +00005009 assert( pCur->eState==CURSOR_VALID );
drhee6438d2014-09-01 13:29:32 +00005010 while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
drh43605152004-05-29 21:46:49 +00005011 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
danielk197771d5d2c2008-09-29 11:49:47 +00005012 pCur->aiIdx[pCur->iPage] = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00005013 rc = moveToChild(pCur, pgno);
drhee6438d2014-09-01 13:29:32 +00005014 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00005015 }
drhee6438d2014-09-01 13:29:32 +00005016 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
5017 assert( pCur->info.nSize==0 );
5018 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5019 return SQLITE_OK;
drh2dcc9aa2002-12-04 13:40:25 +00005020}
5021
drh5e00f6c2001-09-13 13:46:56 +00005022/* Move the cursor to the first entry in the table. Return SQLITE_OK
5023** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00005024** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00005025*/
drh3aac2dd2004-04-26 14:10:20 +00005026int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00005027 int rc;
drhd677b3d2007-08-20 22:48:41 +00005028
dan7a2347e2016-01-07 16:43:54 +00005029 assert( cursorOwnsBtShared(pCur) );
drhe5fe6902007-12-07 18:55:28 +00005030 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00005031 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00005032 if( rc==SQLITE_OK ){
5033 if( pCur->eState==CURSOR_INVALID ){
dana205a482011-08-27 18:48:57 +00005034 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00005035 *pRes = 1;
drhd677b3d2007-08-20 22:48:41 +00005036 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00005037 assert( pCur->apPage[pCur->iPage]->nCell>0 );
drhd677b3d2007-08-20 22:48:41 +00005038 *pRes = 0;
5039 rc = moveToLeftmost(pCur);
5040 }
drh5e00f6c2001-09-13 13:46:56 +00005041 }
drh5e00f6c2001-09-13 13:46:56 +00005042 return rc;
5043}
drh5e2f8b92001-05-28 00:41:15 +00005044
drh9562b552002-02-19 15:00:07 +00005045/* Move the cursor to the last entry in the table. Return SQLITE_OK
5046** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00005047** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00005048*/
drh3aac2dd2004-04-26 14:10:20 +00005049int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00005050 int rc;
drhd677b3d2007-08-20 22:48:41 +00005051
dan7a2347e2016-01-07 16:43:54 +00005052 assert( cursorOwnsBtShared(pCur) );
drhe5fe6902007-12-07 18:55:28 +00005053 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19773f632d52009-05-02 10:03:09 +00005054
5055 /* If the cursor already points to the last entry, this is a no-op. */
drh036dbec2014-03-11 23:40:44 +00005056 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
danielk19773f632d52009-05-02 10:03:09 +00005057#ifdef SQLITE_DEBUG
5058 /* This block serves to assert() that the cursor really does point
5059 ** to the last entry in the b-tree. */
5060 int ii;
5061 for(ii=0; ii<pCur->iPage; ii++){
5062 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
5063 }
5064 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
5065 assert( pCur->apPage[pCur->iPage]->leaf );
5066#endif
5067 return SQLITE_OK;
5068 }
5069
drh9562b552002-02-19 15:00:07 +00005070 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00005071 if( rc==SQLITE_OK ){
5072 if( CURSOR_INVALID==pCur->eState ){
dana205a482011-08-27 18:48:57 +00005073 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00005074 *pRes = 1;
5075 }else{
5076 assert( pCur->eState==CURSOR_VALID );
5077 *pRes = 0;
5078 rc = moveToRightmost(pCur);
drh036dbec2014-03-11 23:40:44 +00005079 if( rc==SQLITE_OK ){
5080 pCur->curFlags |= BTCF_AtLast;
5081 }else{
5082 pCur->curFlags &= ~BTCF_AtLast;
5083 }
5084
drhd677b3d2007-08-20 22:48:41 +00005085 }
drh9562b552002-02-19 15:00:07 +00005086 }
drh9562b552002-02-19 15:00:07 +00005087 return rc;
5088}
5089
drhe14006d2008-03-25 17:23:32 +00005090/* Move the cursor so that it points to an entry near the key
drhe63d9992008-08-13 19:11:48 +00005091** specified by pIdxKey or intKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00005092**
drhe63d9992008-08-13 19:11:48 +00005093** For INTKEY tables, the intKey parameter is used. pIdxKey
5094** must be NULL. For index tables, pIdxKey is used and intKey
5095** is ignored.
drh3aac2dd2004-04-26 14:10:20 +00005096**
drh5e2f8b92001-05-28 00:41:15 +00005097** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00005098** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00005099** were present. The cursor might point to an entry that comes
5100** before or after the key.
5101**
drh64022502009-01-09 14:11:04 +00005102** An integer is written into *pRes which is the result of
5103** comparing the key with the entry to which the cursor is
5104** pointing. The meaning of the integer written into
5105** *pRes is as follows:
drhbd03cae2001-06-02 02:40:57 +00005106**
5107** *pRes<0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00005108** is smaller than intKey/pIdxKey or if the table is empty
drh1a844c32002-12-04 22:29:28 +00005109** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00005110**
5111** *pRes==0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00005112** exactly matches intKey/pIdxKey.
drhbd03cae2001-06-02 02:40:57 +00005113**
5114** *pRes>0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00005115** is larger than intKey/pIdxKey.
drhd677b3d2007-08-20 22:48:41 +00005116**
drhb1d607d2015-11-05 22:30:54 +00005117** For index tables, the pIdxKey->eqSeen field is set to 1 if there
5118** exists an entry in the table that exactly matches pIdxKey.
drha059ad02001-04-17 20:09:11 +00005119*/
drhe63d9992008-08-13 19:11:48 +00005120int sqlite3BtreeMovetoUnpacked(
5121 BtCursor *pCur, /* The cursor to be moved */
5122 UnpackedRecord *pIdxKey, /* Unpacked index key */
5123 i64 intKey, /* The table key */
5124 int biasRight, /* If true, bias the search to the high end */
5125 int *pRes /* Write search results here */
drhe4d90812007-03-29 05:51:49 +00005126){
drh72f82862001-05-24 21:06:34 +00005127 int rc;
dan3b9330f2014-02-27 20:44:18 +00005128 RecordCompare xRecordCompare;
drhd677b3d2007-08-20 22:48:41 +00005129
dan7a2347e2016-01-07 16:43:54 +00005130 assert( cursorOwnsBtShared(pCur) );
drhe5fe6902007-12-07 18:55:28 +00005131 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19775cb09632009-07-09 11:36:01 +00005132 assert( pRes );
danielk19773fd7cf52009-07-13 07:30:52 +00005133 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
drhdebaa862016-06-13 12:51:20 +00005134 assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
drha2c20e42008-03-29 16:01:04 +00005135
5136 /* If the cursor is already positioned at the point we are trying
5137 ** to move to, then just return without doing any work */
drh05a36092016-06-06 01:54:20 +00005138 if( pIdxKey==0
5139 && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
danielk197771d5d2c2008-09-29 11:49:47 +00005140 ){
drhe63d9992008-08-13 19:11:48 +00005141 if( pCur->info.nKey==intKey ){
drha2c20e42008-03-29 16:01:04 +00005142 *pRes = 0;
5143 return SQLITE_OK;
5144 }
drh451e76d2017-01-21 16:54:19 +00005145 if( pCur->info.nKey<intKey ){
5146 if( (pCur->curFlags & BTCF_AtLast)!=0 ){
5147 *pRes = -1;
5148 return SQLITE_OK;
5149 }
drh7f11afa2017-01-21 21:47:54 +00005150 /* If the requested key is one more than the previous key, then
5151 ** try to get there using sqlite3BtreeNext() rather than a full
5152 ** binary search. This is an optimization only. The correct answer
5153 ** is still obtained without this ase, only a little more slowely */
5154 if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
5155 *pRes = 0;
5156 rc = sqlite3BtreeNext(pCur, pRes);
5157 if( rc ) return rc;
5158 if( *pRes==0 ){
5159 getCellInfo(pCur);
5160 if( pCur->info.nKey==intKey ){
5161 return SQLITE_OK;
5162 }
drh451e76d2017-01-21 16:54:19 +00005163 }
5164 }
drha2c20e42008-03-29 16:01:04 +00005165 }
5166 }
5167
dan1fed5da2014-02-25 21:01:25 +00005168 if( pIdxKey ){
5169 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
dan38fdead2014-04-01 10:19:02 +00005170 pIdxKey->errCode = 0;
dan3b9330f2014-02-27 20:44:18 +00005171 assert( pIdxKey->default_rc==1
5172 || pIdxKey->default_rc==0
5173 || pIdxKey->default_rc==-1
5174 );
drh13a747e2014-03-03 21:46:55 +00005175 }else{
drhb6e8fd12014-03-06 01:56:33 +00005176 xRecordCompare = 0; /* All keys are integers */
dan1fed5da2014-02-25 21:01:25 +00005177 }
5178
drh5e2f8b92001-05-28 00:41:15 +00005179 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00005180 if( rc ){
5181 return rc;
5182 }
dana205a482011-08-27 18:48:57 +00005183 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
5184 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
5185 assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
danielk1977da184232006-01-05 11:34:32 +00005186 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00005187 *pRes = -1;
dana205a482011-08-27 18:48:57 +00005188 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
drhc39e0002004-05-07 23:50:57 +00005189 return SQLITE_OK;
5190 }
drhc75d8862015-06-27 23:55:20 +00005191 assert( pCur->apPage[0]->intKey==pCur->curIntKey );
5192 assert( pCur->curIntKey || pIdxKey );
drh14684382006-11-30 13:05:29 +00005193 for(;;){
drhec3e6b12013-11-25 02:38:55 +00005194 int lwr, upr, idx, c;
drh72f82862001-05-24 21:06:34 +00005195 Pgno chldPg;
danielk197771d5d2c2008-09-29 11:49:47 +00005196 MemPage *pPage = pCur->apPage[pCur->iPage];
drhec3e6b12013-11-25 02:38:55 +00005197 u8 *pCell; /* Pointer to current cell in pPage */
danielk1977171fff32009-07-11 05:06:51 +00005198
5199 /* pPage->nCell must be greater than zero. If this is the root-page
5200 ** the cursor would have been INVALID above and this for(;;) loop
5201 ** not run. If this is not the root-page, then the moveToChild() routine
danielk19773fd7cf52009-07-13 07:30:52 +00005202 ** would have already detected db corruption. Similarly, pPage must
5203 ** be the right kind (index or table) of b-tree page. Otherwise
5204 ** a moveToChild() or moveToRoot() call would have detected corruption. */
danielk1977171fff32009-07-11 05:06:51 +00005205 assert( pPage->nCell>0 );
danielk19773fd7cf52009-07-13 07:30:52 +00005206 assert( pPage->intKey==(pIdxKey==0) );
drh72f82862001-05-24 21:06:34 +00005207 lwr = 0;
5208 upr = pPage->nCell-1;
drhebf10b12013-11-25 17:38:26 +00005209 assert( biasRight==0 || biasRight==1 );
5210 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
drhd793f442013-11-25 14:10:15 +00005211 pCur->aiIdx[pCur->iPage] = (u16)idx;
dana4660bd2014-03-04 16:05:25 +00005212 if( xRecordCompare==0 ){
drhec3e6b12013-11-25 02:38:55 +00005213 for(;;){
danielk197711c327a2009-05-04 19:01:26 +00005214 i64 nCellKey;
drhf44890a2015-06-27 03:58:15 +00005215 pCell = findCellPastPtr(pPage, idx);
drh3e28ff52014-09-24 00:59:08 +00005216 if( pPage->intKeyLeaf ){
drh9b2fc612013-11-25 20:14:13 +00005217 while( 0x80 <= *(pCell++) ){
5218 if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
5219 }
drhd172f862006-01-12 15:01:15 +00005220 }
drha2c20e42008-03-29 16:01:04 +00005221 getVarint(pCell, (u64*)&nCellKey);
drhbb933ef2013-11-25 15:01:38 +00005222 if( nCellKey<intKey ){
5223 lwr = idx+1;
5224 if( lwr>upr ){ c = -1; break; }
5225 }else if( nCellKey>intKey ){
5226 upr = idx-1;
5227 if( lwr>upr ){ c = +1; break; }
5228 }else{
5229 assert( nCellKey==intKey );
drhd793f442013-11-25 14:10:15 +00005230 pCur->aiIdx[pCur->iPage] = (u16)idx;
drhec3e6b12013-11-25 02:38:55 +00005231 if( !pPage->leaf ){
5232 lwr = idx;
drhebf10b12013-11-25 17:38:26 +00005233 goto moveto_next_layer;
drhec3e6b12013-11-25 02:38:55 +00005234 }else{
drhd95ef5c2016-11-11 18:19:05 +00005235 pCur->curFlags |= BTCF_ValidNKey;
5236 pCur->info.nKey = nCellKey;
5237 pCur->info.nSize = 0;
drhec3e6b12013-11-25 02:38:55 +00005238 *pRes = 0;
drhd95ef5c2016-11-11 18:19:05 +00005239 return SQLITE_OK;
drhec3e6b12013-11-25 02:38:55 +00005240 }
drhd793f442013-11-25 14:10:15 +00005241 }
drhebf10b12013-11-25 17:38:26 +00005242 assert( lwr+upr>=0 );
5243 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
drhec3e6b12013-11-25 02:38:55 +00005244 }
5245 }else{
5246 for(;;){
drhc6827502015-05-28 15:14:32 +00005247 int nCell; /* Size of the pCell cell in bytes */
drhf44890a2015-06-27 03:58:15 +00005248 pCell = findCellPastPtr(pPage, idx);
drhec3e6b12013-11-25 02:38:55 +00005249
drhb2eced52010-08-12 02:41:12 +00005250 /* The maximum supported page-size is 65536 bytes. This means that
danielk197711c327a2009-05-04 19:01:26 +00005251 ** the maximum number of record bytes stored on an index B-Tree
drhb2eced52010-08-12 02:41:12 +00005252 ** page is less than 16384 bytes and may be stored as a 2-byte
danielk197711c327a2009-05-04 19:01:26 +00005253 ** varint. This information is used to attempt to avoid parsing
5254 ** the entire cell by checking for the cases where the record is
5255 ** stored entirely within the b-tree page by inspecting the first
5256 ** 2 bytes of the cell.
5257 */
drhec3e6b12013-11-25 02:38:55 +00005258 nCell = pCell[0];
drh72b8ef62013-12-06 22:44:51 +00005259 if( nCell<=pPage->max1bytePayload ){
danielk197711c327a2009-05-04 19:01:26 +00005260 /* This branch runs if the record-size field of the cell is a
5261 ** single byte varint and the record fits entirely on the main
5262 ** b-tree page. */
drh3def2352011-11-11 00:27:15 +00005263 testcase( pCell+nCell+1==pPage->aDataEnd );
drh75179de2014-09-16 14:37:35 +00005264 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
danielk197711c327a2009-05-04 19:01:26 +00005265 }else if( !(pCell[1] & 0x80)
5266 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5267 ){
5268 /* The record-size field is a 2 byte varint and the record
5269 ** fits entirely on the main b-tree page. */
drh3def2352011-11-11 00:27:15 +00005270 testcase( pCell+nCell+2==pPage->aDataEnd );
drh75179de2014-09-16 14:37:35 +00005271 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
drhe51c44f2004-05-30 20:46:09 +00005272 }else{
danielk197711c327a2009-05-04 19:01:26 +00005273 /* The record flows over onto one or more overflow pages. In
5274 ** this case the whole cell needs to be parsed, a buffer allocated
5275 ** and accessPayload() used to retrieve the record into the
dan3548db72015-05-27 14:21:05 +00005276 ** buffer before VdbeRecordCompare() can be called.
5277 **
5278 ** If the record is corrupt, the xRecordCompare routine may read
5279 ** up to two varints past the end of the buffer. An extra 18
5280 ** bytes of padding is allocated at the end of the buffer in
5281 ** case this happens. */
danielk197711c327a2009-05-04 19:01:26 +00005282 void *pCellKey;
5283 u8 * const pCellBody = pCell - pPage->childPtrSize;
drh5fa60512015-06-19 17:19:34 +00005284 pPage->xParseCell(pPage, pCellBody, &pCur->info);
shane60a4b532009-05-06 18:57:09 +00005285 nCell = (int)pCur->info.nKey;
drhc6827502015-05-28 15:14:32 +00005286 testcase( nCell<0 ); /* True if key size is 2^32 or more */
5287 testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
5288 testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
5289 testcase( nCell==2 ); /* Minimum legal index key size */
dan3548db72015-05-27 14:21:05 +00005290 if( nCell<2 ){
5291 rc = SQLITE_CORRUPT_BKPT;
5292 goto moveto_finish;
5293 }
5294 pCellKey = sqlite3Malloc( nCell+18 );
danielk19776507ecb2008-03-25 09:56:44 +00005295 if( pCellKey==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005296 rc = SQLITE_NOMEM_BKPT;
danielk19776507ecb2008-03-25 09:56:44 +00005297 goto moveto_finish;
5298 }
drhd793f442013-11-25 14:10:15 +00005299 pCur->aiIdx[pCur->iPage] = (u16)idx;
drh42e28f12017-01-27 00:31:59 +00005300 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
5301 pCur->curFlags &= ~BTCF_ValidOvfl;
drhec9b31f2009-08-25 13:53:49 +00005302 if( rc ){
5303 sqlite3_free(pCellKey);
5304 goto moveto_finish;
5305 }
drh75179de2014-09-16 14:37:35 +00005306 c = xRecordCompare(nCell, pCellKey, pIdxKey);
drhfacf0302008-06-17 15:12:00 +00005307 sqlite3_free(pCellKey);
drhe51c44f2004-05-30 20:46:09 +00005308 }
dan38fdead2014-04-01 10:19:02 +00005309 assert(
5310 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
dana7bf23c2014-05-02 17:12:41 +00005311 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
dan38fdead2014-04-01 10:19:02 +00005312 );
drhbb933ef2013-11-25 15:01:38 +00005313 if( c<0 ){
5314 lwr = idx+1;
5315 }else if( c>0 ){
5316 upr = idx-1;
5317 }else{
5318 assert( c==0 );
drh64022502009-01-09 14:11:04 +00005319 *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00005320 rc = SQLITE_OK;
drhd793f442013-11-25 14:10:15 +00005321 pCur->aiIdx[pCur->iPage] = (u16)idx;
dan38fdead2014-04-01 10:19:02 +00005322 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
drh1e968a02008-03-25 00:22:21 +00005323 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00005324 }
drhebf10b12013-11-25 17:38:26 +00005325 if( lwr>upr ) break;
5326 assert( lwr+upr>=0 );
5327 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
drh72f82862001-05-24 21:06:34 +00005328 }
drh72f82862001-05-24 21:06:34 +00005329 }
drhb07028f2011-10-14 21:49:18 +00005330 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
danielk197771d5d2c2008-09-29 11:49:47 +00005331 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00005332 if( pPage->leaf ){
drhec3e6b12013-11-25 02:38:55 +00005333 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drhbb933ef2013-11-25 15:01:38 +00005334 pCur->aiIdx[pCur->iPage] = (u16)idx;
drhec3e6b12013-11-25 02:38:55 +00005335 *pRes = c;
5336 rc = SQLITE_OK;
5337 goto moveto_finish;
drhebf10b12013-11-25 17:38:26 +00005338 }
5339moveto_next_layer:
5340 if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00005341 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00005342 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00005343 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00005344 }
drhf49661a2008-12-10 16:45:50 +00005345 pCur->aiIdx[pCur->iPage] = (u16)lwr;
drh8178a752003-01-05 21:41:40 +00005346 rc = moveToChild(pCur, chldPg);
drhec3e6b12013-11-25 02:38:55 +00005347 if( rc ) break;
drh72f82862001-05-24 21:06:34 +00005348 }
drh1e968a02008-03-25 00:22:21 +00005349moveto_finish:
drhd2022b02013-11-25 16:23:52 +00005350 pCur->info.nSize = 0;
drhd95ef5c2016-11-11 18:19:05 +00005351 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
drhe63d9992008-08-13 19:11:48 +00005352 return rc;
5353}
5354
drhd677b3d2007-08-20 22:48:41 +00005355
drh72f82862001-05-24 21:06:34 +00005356/*
drhc39e0002004-05-07 23:50:57 +00005357** Return TRUE if the cursor is not pointing at an entry of the table.
5358**
5359** TRUE will be returned after a call to sqlite3BtreeNext() moves
5360** past the last entry in the table or sqlite3BtreePrev() moves past
5361** the first entry. TRUE is also returned if the table is empty.
5362*/
5363int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00005364 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
5365 ** have been deleted? This API will need to change to return an error code
5366 ** as well as the boolean result value.
5367 */
5368 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00005369}
5370
5371/*
drh5e98e832017-02-17 19:24:06 +00005372** Return an estimate for the number of rows in the table that pCur is
5373** pointing to. Return a negative number if no estimate is currently
5374** available.
5375*/
5376i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
5377 i64 n;
5378 u8 i;
5379
5380 assert( cursorOwnsBtShared(pCur) );
5381 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh555227b2017-02-23 02:15:33 +00005382
5383 /* Currently this interface is only called by the OP_IfSmaller
5384 ** opcode, and it that case the cursor will always be valid and
5385 ** will always point to a leaf node. */
5386 if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
5387 if( NEVER(pCur->apPage[pCur->iPage]->leaf==0) ) return -1;
5388
drhdfe11ba2017-02-18 02:42:54 +00005389 for(n=1, i=0; i<=pCur->iPage; i++){
drh5e98e832017-02-17 19:24:06 +00005390 n *= pCur->apPage[i]->nCell;
5391 }
5392 return n;
5393}
5394
5395/*
drhbd03cae2001-06-02 02:40:57 +00005396** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00005397** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00005398** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00005399** this routine was called, then set *pRes=1.
drhe39a7322014-02-03 14:04:11 +00005400**
drhee6438d2014-09-01 13:29:32 +00005401** The main entry point is sqlite3BtreeNext(). That routine is optimized
5402** for the common case of merely incrementing the cell counter BtCursor.aiIdx
5403** to the next cell on the current page. The (slower) btreeNext() helper
5404** routine is called when it is necessary to move to a different page or
5405** to restore the cursor.
5406**
drhe39a7322014-02-03 14:04:11 +00005407** The calling function will set *pRes to 0 or 1. The initial *pRes value
5408** will be 1 if the cursor being stepped corresponds to an SQL index and
5409** if this routine could have been skipped if that SQL index had been
5410** a unique index. Otherwise the caller will have set *pRes to zero.
5411** Zero is the common case. The btree implementation is free to use the
5412** initial *pRes value as a hint to improve performance, but the current
5413** SQLite btree implementation does not. (Note that the comdb2 btree
5414** implementation does use this hint, however.)
drh72f82862001-05-24 21:06:34 +00005415*/
drhee6438d2014-09-01 13:29:32 +00005416static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00005417 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00005418 int idx;
danielk197797a227c2006-01-20 16:32:04 +00005419 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00005420
dan7a2347e2016-01-07 16:43:54 +00005421 assert( cursorOwnsBtShared(pCur) );
drh9b47ee32013-08-20 03:13:51 +00005422 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
drhee6438d2014-09-01 13:29:32 +00005423 assert( *pRes==0 );
drhf66f26a2013-08-19 20:04:10 +00005424 if( pCur->eState!=CURSOR_VALID ){
drhee6438d2014-09-01 13:29:32 +00005425 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
drhf66f26a2013-08-19 20:04:10 +00005426 rc = restoreCursorPosition(pCur);
5427 if( rc!=SQLITE_OK ){
5428 return rc;
5429 }
5430 if( CURSOR_INVALID==pCur->eState ){
5431 *pRes = 1;
5432 return SQLITE_OK;
5433 }
drh9b47ee32013-08-20 03:13:51 +00005434 if( pCur->skipNext ){
5435 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5436 pCur->eState = CURSOR_VALID;
5437 if( pCur->skipNext>0 ){
5438 pCur->skipNext = 0;
drh9b47ee32013-08-20 03:13:51 +00005439 return SQLITE_OK;
5440 }
drhf66f26a2013-08-19 20:04:10 +00005441 pCur->skipNext = 0;
drhf66f26a2013-08-19 20:04:10 +00005442 }
danielk1977da184232006-01-05 11:34:32 +00005443 }
danielk1977da184232006-01-05 11:34:32 +00005444
danielk197771d5d2c2008-09-29 11:49:47 +00005445 pPage = pCur->apPage[pCur->iPage];
5446 idx = ++pCur->aiIdx[pCur->iPage];
5447 assert( pPage->isInit );
danbb246c42012-01-12 14:25:55 +00005448
5449 /* If the database file is corrupt, it is possible for the value of idx
5450 ** to be invalid here. This can only occur if a second cursor modifies
5451 ** the page while cursor pCur is holding a reference to it. Which can
5452 ** only happen if the database is corrupt in such a way as to link the
5453 ** page into more than one b-tree structure. */
5454 testcase( idx>pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00005455
danielk197771d5d2c2008-09-29 11:49:47 +00005456 if( idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00005457 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005458 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drhee6438d2014-09-01 13:29:32 +00005459 if( rc ) return rc;
5460 return moveToLeftmost(pCur);
drh72f82862001-05-24 21:06:34 +00005461 }
drh5e2f8b92001-05-28 00:41:15 +00005462 do{
danielk197771d5d2c2008-09-29 11:49:47 +00005463 if( pCur->iPage==0 ){
drh8c1238a2003-01-02 14:43:55 +00005464 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00005465 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00005466 return SQLITE_OK;
5467 }
danielk197730548662009-07-09 05:07:37 +00005468 moveToParent(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00005469 pPage = pCur->apPage[pCur->iPage];
5470 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
drh44845222008-07-17 18:39:57 +00005471 if( pPage->intKey ){
drhee6438d2014-09-01 13:29:32 +00005472 return sqlite3BtreeNext(pCur, pRes);
drh8b18dd42004-05-12 19:18:15 +00005473 }else{
drhee6438d2014-09-01 13:29:32 +00005474 return SQLITE_OK;
drh8b18dd42004-05-12 19:18:15 +00005475 }
drh8178a752003-01-05 21:41:40 +00005476 }
drh3aac2dd2004-04-26 14:10:20 +00005477 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00005478 return SQLITE_OK;
drhee6438d2014-09-01 13:29:32 +00005479 }else{
5480 return moveToLeftmost(pCur);
drh72f82862001-05-24 21:06:34 +00005481 }
drh72f82862001-05-24 21:06:34 +00005482}
drhee6438d2014-09-01 13:29:32 +00005483int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
5484 MemPage *pPage;
dan7a2347e2016-01-07 16:43:54 +00005485 assert( cursorOwnsBtShared(pCur) );
drhee6438d2014-09-01 13:29:32 +00005486 assert( pRes!=0 );
5487 assert( *pRes==0 || *pRes==1 );
5488 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5489 pCur->info.nSize = 0;
5490 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5491 *pRes = 0;
5492 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
5493 pPage = pCur->apPage[pCur->iPage];
5494 if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
5495 pCur->aiIdx[pCur->iPage]--;
5496 return btreeNext(pCur, pRes);
5497 }
5498 if( pPage->leaf ){
5499 return SQLITE_OK;
5500 }else{
5501 return moveToLeftmost(pCur);
5502 }
5503}
drh72f82862001-05-24 21:06:34 +00005504
drh3b7511c2001-05-26 13:15:44 +00005505/*
drh2dcc9aa2002-12-04 13:40:25 +00005506** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00005507** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00005508** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00005509** this routine was called, then set *pRes=1.
drhe39a7322014-02-03 14:04:11 +00005510**
drhee6438d2014-09-01 13:29:32 +00005511** The main entry point is sqlite3BtreePrevious(). That routine is optimized
5512** for the common case of merely decrementing the cell counter BtCursor.aiIdx
drh3f387402014-09-24 01:23:00 +00005513** to the previous cell on the current page. The (slower) btreePrevious()
5514** helper routine is called when it is necessary to move to a different page
5515** or to restore the cursor.
drhee6438d2014-09-01 13:29:32 +00005516**
drhe39a7322014-02-03 14:04:11 +00005517** The calling function will set *pRes to 0 or 1. The initial *pRes value
5518** will be 1 if the cursor being stepped corresponds to an SQL index and
5519** if this routine could have been skipped if that SQL index had been
5520** a unique index. Otherwise the caller will have set *pRes to zero.
5521** Zero is the common case. The btree implementation is free to use the
5522** initial *pRes value as a hint to improve performance, but the current
5523** SQLite btree implementation does not. (Note that the comdb2 btree
5524** implementation does use this hint, however.)
drh2dcc9aa2002-12-04 13:40:25 +00005525*/
drhee6438d2014-09-01 13:29:32 +00005526static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00005527 int rc;
drh8178a752003-01-05 21:41:40 +00005528 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00005529
dan7a2347e2016-01-07 16:43:54 +00005530 assert( cursorOwnsBtShared(pCur) );
drh9b47ee32013-08-20 03:13:51 +00005531 assert( pRes!=0 );
drhee6438d2014-09-01 13:29:32 +00005532 assert( *pRes==0 );
drh9b47ee32013-08-20 03:13:51 +00005533 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
drhee6438d2014-09-01 13:29:32 +00005534 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
5535 assert( pCur->info.nSize==0 );
drhf66f26a2013-08-19 20:04:10 +00005536 if( pCur->eState!=CURSOR_VALID ){
drh7682a472014-09-29 15:00:28 +00005537 rc = restoreCursorPosition(pCur);
drhee6438d2014-09-01 13:29:32 +00005538 if( rc!=SQLITE_OK ){
5539 return rc;
drhf66f26a2013-08-19 20:04:10 +00005540 }
5541 if( CURSOR_INVALID==pCur->eState ){
5542 *pRes = 1;
5543 return SQLITE_OK;
5544 }
drh9b47ee32013-08-20 03:13:51 +00005545 if( pCur->skipNext ){
5546 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5547 pCur->eState = CURSOR_VALID;
5548 if( pCur->skipNext<0 ){
5549 pCur->skipNext = 0;
drh9b47ee32013-08-20 03:13:51 +00005550 return SQLITE_OK;
5551 }
drhf66f26a2013-08-19 20:04:10 +00005552 pCur->skipNext = 0;
drhf66f26a2013-08-19 20:04:10 +00005553 }
danielk1977da184232006-01-05 11:34:32 +00005554 }
danielk1977da184232006-01-05 11:34:32 +00005555
danielk197771d5d2c2008-09-29 11:49:47 +00005556 pPage = pCur->apPage[pCur->iPage];
5557 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00005558 if( !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00005559 int idx = pCur->aiIdx[pCur->iPage];
5560 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
drhee6438d2014-09-01 13:29:32 +00005561 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00005562 rc = moveToRightmost(pCur);
5563 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00005564 while( pCur->aiIdx[pCur->iPage]==0 ){
5565 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00005566 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00005567 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00005568 return SQLITE_OK;
5569 }
danielk197730548662009-07-09 05:07:37 +00005570 moveToParent(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00005571 }
drhee6438d2014-09-01 13:29:32 +00005572 assert( pCur->info.nSize==0 );
drhd95ef5c2016-11-11 18:19:05 +00005573 assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00005574
5575 pCur->aiIdx[pCur->iPage]--;
5576 pPage = pCur->apPage[pCur->iPage];
drh44845222008-07-17 18:39:57 +00005577 if( pPage->intKey && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00005578 rc = sqlite3BtreePrevious(pCur, pRes);
5579 }else{
5580 rc = SQLITE_OK;
5581 }
drh2dcc9aa2002-12-04 13:40:25 +00005582 }
drh2dcc9aa2002-12-04 13:40:25 +00005583 return rc;
5584}
drhee6438d2014-09-01 13:29:32 +00005585int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
dan7a2347e2016-01-07 16:43:54 +00005586 assert( cursorOwnsBtShared(pCur) );
drhee6438d2014-09-01 13:29:32 +00005587 assert( pRes!=0 );
5588 assert( *pRes==0 || *pRes==1 );
5589 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5590 *pRes = 0;
5591 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
5592 pCur->info.nSize = 0;
5593 if( pCur->eState!=CURSOR_VALID
5594 || pCur->aiIdx[pCur->iPage]==0
5595 || pCur->apPage[pCur->iPage]->leaf==0
5596 ){
5597 return btreePrevious(pCur, pRes);
5598 }
5599 pCur->aiIdx[pCur->iPage]--;
5600 return SQLITE_OK;
5601}
drh2dcc9aa2002-12-04 13:40:25 +00005602
5603/*
drh3b7511c2001-05-26 13:15:44 +00005604** Allocate a new page from the database file.
5605**
danielk19773b8a05f2007-03-19 17:44:26 +00005606** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00005607** has already been called on the new page.) The new page has also
5608** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00005609** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00005610**
5611** SQLITE_OK is returned on success. Any other return value indicates
drh1c8bade2015-05-29 18:42:11 +00005612** an error. *ppPage is set to NULL in the event of an error.
drhbea00b92002-07-08 10:59:50 +00005613**
drh82e647d2013-03-02 03:25:55 +00005614** If the "nearby" parameter is not 0, then an effort is made to
drh199e3cf2002-07-18 11:01:47 +00005615** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00005616** attempt to keep related pages close to each other in the database file,
5617** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00005618**
drh82e647d2013-03-02 03:25:55 +00005619** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
5620** anywhere on the free-list, then it is guaranteed to be returned. If
5621** eMode is BTALLOC_LT then the page returned will be less than or equal
5622** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
5623** are no restrictions on which page is returned.
drh3b7511c2001-05-26 13:15:44 +00005624*/
drh4f0c5872007-03-26 22:05:01 +00005625static int allocateBtreePage(
drh82e647d2013-03-02 03:25:55 +00005626 BtShared *pBt, /* The btree */
5627 MemPage **ppPage, /* Store pointer to the allocated page here */
5628 Pgno *pPgno, /* Store the page number here */
5629 Pgno nearby, /* Search for a page near this one */
5630 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005631){
drh3aac2dd2004-04-26 14:10:20 +00005632 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00005633 int rc;
drh35cd6432009-06-05 14:17:21 +00005634 u32 n; /* Number of pages on the freelist */
drh042d6a12009-06-17 13:57:16 +00005635 u32 k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00005636 MemPage *pTrunk = 0;
5637 MemPage *pPrevTrunk = 0;
drh1662b5a2009-06-04 19:06:09 +00005638 Pgno mxPage; /* Total size of the database file */
drh30e58752002-03-02 20:41:57 +00005639
drh1fee73e2007-08-29 04:00:57 +00005640 assert( sqlite3_mutex_held(pBt->mutex) );
dan09ff9e12013-03-11 11:49:03 +00005641 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
drh3aac2dd2004-04-26 14:10:20 +00005642 pPage1 = pBt->pPage1;
drhb1299152010-03-30 22:58:33 +00005643 mxPage = btreePagecount(pBt);
drh113762a2014-11-19 16:36:25 +00005644 /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
5645 ** stores stores the total number of pages on the freelist. */
drh3aac2dd2004-04-26 14:10:20 +00005646 n = get4byte(&pPage1->aData[36]);
drhdf35a082009-07-09 02:24:35 +00005647 testcase( n==mxPage-1 );
5648 if( n>=mxPage ){
drh1662b5a2009-06-04 19:06:09 +00005649 return SQLITE_CORRUPT_BKPT;
5650 }
drh3aac2dd2004-04-26 14:10:20 +00005651 if( n>0 ){
drh91025292004-05-03 19:49:32 +00005652 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005653 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005654 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
drhc6e956f2015-06-24 13:32:10 +00005655 u32 nSearch = 0; /* Count of the number of search attempts */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005656
drh82e647d2013-03-02 03:25:55 +00005657 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00005658 ** shows that the page 'nearby' is somewhere on the free-list, then
5659 ** the entire-list will be searched for that page.
5660 */
5661#ifndef SQLITE_OMIT_AUTOVACUUM
dan51f0b6d2013-02-22 20:16:34 +00005662 if( eMode==BTALLOC_EXACT ){
5663 if( nearby<=mxPage ){
5664 u8 eType;
5665 assert( nearby>0 );
5666 assert( pBt->autoVacuum );
5667 rc = ptrmapGet(pBt, nearby, &eType, 0);
5668 if( rc ) return rc;
5669 if( eType==PTRMAP_FREEPAGE ){
5670 searchList = 1;
5671 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005672 }
dan51f0b6d2013-02-22 20:16:34 +00005673 }else if( eMode==BTALLOC_LE ){
5674 searchList = 1;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005675 }
5676#endif
5677
5678 /* Decrement the free-list count by 1. Set iTrunk to the index of the
5679 ** first free-list trunk page. iPrevTrunk is initially 1.
5680 */
danielk19773b8a05f2007-03-19 17:44:26 +00005681 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00005682 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00005683 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005684
5685 /* The code within this loop is run only once if the 'searchList' variable
5686 ** is not true. Otherwise, it runs once for each trunk-page on the
drh82e647d2013-03-02 03:25:55 +00005687 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
5688 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
danielk1977cb1a7eb2004-11-05 12:27:02 +00005689 */
5690 do {
5691 pPrevTrunk = pTrunk;
5692 if( pPrevTrunk ){
drh113762a2014-11-19 16:36:25 +00005693 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
5694 ** is the page number of the next freelist trunk page in the list or
5695 ** zero if this is the last freelist trunk page. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005696 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00005697 }else{
drh113762a2014-11-19 16:36:25 +00005698 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
5699 ** stores the page number of the first page of the freelist, or zero if
5700 ** the freelist is empty. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005701 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00005702 }
drhdf35a082009-07-09 02:24:35 +00005703 testcase( iTrunk==mxPage );
drh9e7804d2015-06-24 12:24:03 +00005704 if( iTrunk>mxPage || nSearch++ > n ){
drh1662b5a2009-06-04 19:06:09 +00005705 rc = SQLITE_CORRUPT_BKPT;
5706 }else{
drh7e8c6f12015-05-28 03:28:27 +00005707 rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
drh1662b5a2009-06-04 19:06:09 +00005708 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005709 if( rc ){
drhd3627af2006-12-18 18:34:51 +00005710 pTrunk = 0;
5711 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005712 }
drhb07028f2011-10-14 21:49:18 +00005713 assert( pTrunk!=0 );
5714 assert( pTrunk->aData!=0 );
drh113762a2014-11-19 16:36:25 +00005715 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
5716 ** is the number of leaf page pointers to follow. */
5717 k = get4byte(&pTrunk->aData[4]);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005718 if( k==0 && !searchList ){
5719 /* The trunk has no leaves and the list is not being searched.
5720 ** So extract the trunk page itself and use it as the newly
5721 ** allocated page */
5722 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00005723 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00005724 if( rc ){
5725 goto end_allocate_page;
5726 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005727 *pPgno = iTrunk;
5728 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5729 *ppPage = pTrunk;
5730 pTrunk = 0;
5731 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh042d6a12009-06-17 13:57:16 +00005732 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00005733 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00005734 rc = SQLITE_CORRUPT_BKPT;
5735 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005736#ifndef SQLITE_OMIT_AUTOVACUUM
dan51f0b6d2013-02-22 20:16:34 +00005737 }else if( searchList
5738 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
5739 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00005740 /* The list is being searched and this trunk page is the page
5741 ** to allocate, regardless of whether it has leaves.
5742 */
dan51f0b6d2013-02-22 20:16:34 +00005743 *pPgno = iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005744 *ppPage = pTrunk;
5745 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005746 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00005747 if( rc ){
5748 goto end_allocate_page;
5749 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005750 if( k==0 ){
5751 if( !pPrevTrunk ){
5752 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5753 }else{
danf48c3552010-08-23 15:41:24 +00005754 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
5755 if( rc!=SQLITE_OK ){
5756 goto end_allocate_page;
5757 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005758 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
5759 }
5760 }else{
5761 /* The trunk page is required by the caller but it contains
5762 ** pointers to free-list leaves. The first leaf becomes a trunk
5763 ** page in this case.
5764 */
5765 MemPage *pNewTrunk;
5766 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh1662b5a2009-06-04 19:06:09 +00005767 if( iNewTrunk>mxPage ){
5768 rc = SQLITE_CORRUPT_BKPT;
5769 goto end_allocate_page;
5770 }
drhdf35a082009-07-09 02:24:35 +00005771 testcase( iNewTrunk==mxPage );
drh7e8c6f12015-05-28 03:28:27 +00005772 rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005773 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00005774 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005775 }
danielk19773b8a05f2007-03-19 17:44:26 +00005776 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005777 if( rc!=SQLITE_OK ){
5778 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00005779 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005780 }
5781 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
5782 put4byte(&pNewTrunk->aData[4], k-1);
5783 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00005784 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005785 if( !pPrevTrunk ){
drhc5053fb2008-11-27 02:22:10 +00005786 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
danielk1977cb1a7eb2004-11-05 12:27:02 +00005787 put4byte(&pPage1->aData[32], iNewTrunk);
5788 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00005789 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00005790 if( rc ){
5791 goto end_allocate_page;
5792 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005793 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
5794 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005795 }
5796 pTrunk = 0;
5797 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
5798#endif
danielk1977e5765212009-06-17 11:13:28 +00005799 }else if( k>0 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00005800 /* Extract a leaf from the trunk */
drh042d6a12009-06-17 13:57:16 +00005801 u32 closest;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005802 Pgno iPage;
5803 unsigned char *aData = pTrunk->aData;
5804 if( nearby>0 ){
drh042d6a12009-06-17 13:57:16 +00005805 u32 i;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005806 closest = 0;
danf38b65a2013-02-22 20:57:47 +00005807 if( eMode==BTALLOC_LE ){
5808 for(i=0; i<k; i++){
5809 iPage = get4byte(&aData[8+i*4]);
dan87ade192013-02-23 17:49:16 +00005810 if( iPage<=nearby ){
danf38b65a2013-02-22 20:57:47 +00005811 closest = i;
5812 break;
5813 }
5814 }
5815 }else{
5816 int dist;
5817 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
5818 for(i=1; i<k; i++){
5819 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
5820 if( d2<dist ){
5821 closest = i;
5822 dist = d2;
5823 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005824 }
5825 }
5826 }else{
5827 closest = 0;
5828 }
5829
5830 iPage = get4byte(&aData[8+closest*4]);
drhdf35a082009-07-09 02:24:35 +00005831 testcase( iPage==mxPage );
drh1662b5a2009-06-04 19:06:09 +00005832 if( iPage>mxPage ){
5833 rc = SQLITE_CORRUPT_BKPT;
5834 goto end_allocate_page;
5835 }
drhdf35a082009-07-09 02:24:35 +00005836 testcase( iPage==mxPage );
dan51f0b6d2013-02-22 20:16:34 +00005837 if( !searchList
5838 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
5839 ){
danielk1977bea2a942009-01-20 17:06:27 +00005840 int noContent;
shane1f9e6aa2008-06-09 19:27:11 +00005841 *pPgno = iPage;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005842 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
5843 ": %d more free pages\n",
5844 *pPgno, closest+1, k, pTrunk->pgno, n-1));
drh93b4fc72011-04-07 14:47:01 +00005845 rc = sqlite3PagerWrite(pTrunk->pDbPage);
5846 if( rc ) goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005847 if( closest<k-1 ){
5848 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
5849 }
5850 put4byte(&aData[4], k-1);
drh3f387402014-09-24 01:23:00 +00005851 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
drh7e8c6f12015-05-28 03:28:27 +00005852 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005853 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00005854 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00005855 if( rc!=SQLITE_OK ){
5856 releasePage(*ppPage);
drh1c8bade2015-05-29 18:42:11 +00005857 *ppPage = 0;
danielk1977aac0a382005-01-16 11:07:06 +00005858 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005859 }
5860 searchList = 0;
5861 }
drhee696e22004-08-30 16:52:17 +00005862 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005863 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00005864 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005865 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00005866 }else{
danbc1a3c62013-02-23 16:40:46 +00005867 /* There are no pages on the freelist, so append a new page to the
5868 ** database image.
5869 **
5870 ** Normally, new pages allocated by this block can be requested from the
5871 ** pager layer with the 'no-content' flag set. This prevents the pager
5872 ** from trying to read the pages content from disk. However, if the
5873 ** current transaction has already run one or more incremental-vacuum
5874 ** steps, then the page we are about to allocate may contain content
5875 ** that is required in the event of a rollback. In this case, do
5876 ** not set the no-content flag. This causes the pager to load and journal
5877 ** the current page content before overwriting it.
5878 **
5879 ** Note that the pager will not actually attempt to load or journal
5880 ** content for any page that really does lie past the end of the database
5881 ** file on disk. So the effects of disabling the no-content optimization
5882 ** here are confined to those pages that lie between the end of the
5883 ** database image and the end of the database file.
5884 */
drh3f387402014-09-24 01:23:00 +00005885 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
danbc1a3c62013-02-23 16:40:46 +00005886
drhdd3cd972010-03-27 17:12:36 +00005887 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
5888 if( rc ) return rc;
5889 pBt->nPage++;
5890 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
danielk1977bea2a942009-01-20 17:06:27 +00005891
danielk1977afcdd022004-10-31 16:25:42 +00005892#ifndef SQLITE_OMIT_AUTOVACUUM
drhdd3cd972010-03-27 17:12:36 +00005893 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
danielk1977afcdd022004-10-31 16:25:42 +00005894 /* If *pPgno refers to a pointer-map page, allocate two new pages
5895 ** at the end of the file instead of one. The first allocated page
5896 ** becomes a new pointer-map page, the second is used by the caller.
5897 */
danielk1977ac861692009-03-28 10:54:22 +00005898 MemPage *pPg = 0;
drhdd3cd972010-03-27 17:12:36 +00005899 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
5900 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
drh7e8c6f12015-05-28 03:28:27 +00005901 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
danielk1977ac861692009-03-28 10:54:22 +00005902 if( rc==SQLITE_OK ){
5903 rc = sqlite3PagerWrite(pPg->pDbPage);
5904 releasePage(pPg);
5905 }
5906 if( rc ) return rc;
drhdd3cd972010-03-27 17:12:36 +00005907 pBt->nPage++;
5908 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
danielk1977afcdd022004-10-31 16:25:42 +00005909 }
5910#endif
drhdd3cd972010-03-27 17:12:36 +00005911 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
5912 *pPgno = pBt->nPage;
danielk1977afcdd022004-10-31 16:25:42 +00005913
danielk1977599fcba2004-11-08 07:13:13 +00005914 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh7e8c6f12015-05-28 03:28:27 +00005915 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
drh3b7511c2001-05-26 13:15:44 +00005916 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00005917 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00005918 if( rc!=SQLITE_OK ){
5919 releasePage(*ppPage);
drh7e8c6f12015-05-28 03:28:27 +00005920 *ppPage = 0;
danielk1977aac0a382005-01-16 11:07:06 +00005921 }
drh3a4c1412004-05-09 20:40:11 +00005922 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00005923 }
danielk1977599fcba2004-11-08 07:13:13 +00005924
5925 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00005926
5927end_allocate_page:
5928 releasePage(pTrunk);
5929 releasePage(pPrevTrunk);
drh7e8c6f12015-05-28 03:28:27 +00005930 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
5931 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
drh3b7511c2001-05-26 13:15:44 +00005932 return rc;
5933}
5934
5935/*
danielk1977bea2a942009-01-20 17:06:27 +00005936** This function is used to add page iPage to the database file free-list.
5937** It is assumed that the page is not already a part of the free-list.
drh5e2f8b92001-05-28 00:41:15 +00005938**
danielk1977bea2a942009-01-20 17:06:27 +00005939** The value passed as the second argument to this function is optional.
5940** If the caller happens to have a pointer to the MemPage object
5941** corresponding to page iPage handy, it may pass it as the second value.
5942** Otherwise, it may pass NULL.
5943**
5944** If a pointer to a MemPage object is passed as the second argument,
5945** its reference count is not altered by this function.
drh3b7511c2001-05-26 13:15:44 +00005946*/
danielk1977bea2a942009-01-20 17:06:27 +00005947static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
5948 MemPage *pTrunk = 0; /* Free-list trunk page */
5949 Pgno iTrunk = 0; /* Page number of free-list trunk page */
5950 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
5951 MemPage *pPage; /* Page being freed. May be NULL. */
5952 int rc; /* Return Code */
5953 int nFree; /* Initial number of pages on free-list */
drh8b2f49b2001-06-08 00:21:52 +00005954
danielk1977bea2a942009-01-20 17:06:27 +00005955 assert( sqlite3_mutex_held(pBt->mutex) );
danfb0246b2015-05-26 12:18:17 +00005956 assert( CORRUPT_DB || iPage>1 );
danielk1977bea2a942009-01-20 17:06:27 +00005957 assert( !pMemPage || pMemPage->pgno==iPage );
5958
danfb0246b2015-05-26 12:18:17 +00005959 if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
danielk1977bea2a942009-01-20 17:06:27 +00005960 if( pMemPage ){
5961 pPage = pMemPage;
5962 sqlite3PagerRef(pPage->pDbPage);
5963 }else{
5964 pPage = btreePageLookup(pBt, iPage);
5965 }
drh3aac2dd2004-04-26 14:10:20 +00005966
drha34b6762004-05-07 13:30:42 +00005967 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00005968 rc = sqlite3PagerWrite(pPage1->pDbPage);
danielk1977bea2a942009-01-20 17:06:27 +00005969 if( rc ) goto freepage_out;
5970 nFree = get4byte(&pPage1->aData[36]);
5971 put4byte(&pPage1->aData[36], nFree+1);
drh3aac2dd2004-04-26 14:10:20 +00005972
drhc9166342012-01-05 23:32:06 +00005973 if( pBt->btsFlags & BTS_SECURE_DELETE ){
drh5b47efa2010-02-12 18:18:39 +00005974 /* If the secure_delete option is enabled, then
5975 ** always fully overwrite deleted information with zeros.
5976 */
drhb00fc3b2013-08-21 23:42:32 +00005977 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
shaneh84f4b2f2010-02-26 01:46:54 +00005978 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
drh5b47efa2010-02-12 18:18:39 +00005979 ){
5980 goto freepage_out;
5981 }
5982 memset(pPage->aData, 0, pPage->pBt->pageSize);
danielk1977bea2a942009-01-20 17:06:27 +00005983 }
drhfcce93f2006-02-22 03:08:32 +00005984
danielk1977687566d2004-11-02 12:56:41 +00005985 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00005986 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00005987 */
danielk197785d90ca2008-07-19 14:25:15 +00005988 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00005989 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
danielk1977bea2a942009-01-20 17:06:27 +00005990 if( rc ) goto freepage_out;
danielk1977687566d2004-11-02 12:56:41 +00005991 }
danielk1977687566d2004-11-02 12:56:41 +00005992
danielk1977bea2a942009-01-20 17:06:27 +00005993 /* Now manipulate the actual database free-list structure. There are two
5994 ** possibilities. If the free-list is currently empty, or if the first
5995 ** trunk page in the free-list is full, then this page will become a
5996 ** new free-list trunk page. Otherwise, it will become a leaf of the
5997 ** first trunk page in the current free-list. This block tests if it
5998 ** is possible to add the page as a new free-list leaf.
5999 */
6000 if( nFree!=0 ){
drhc046e3e2009-07-15 11:26:44 +00006001 u32 nLeaf; /* Initial number of leaf cells on trunk page */
danielk1977bea2a942009-01-20 17:06:27 +00006002
6003 iTrunk = get4byte(&pPage1->aData[32]);
drhb00fc3b2013-08-21 23:42:32 +00006004 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977bea2a942009-01-20 17:06:27 +00006005 if( rc!=SQLITE_OK ){
6006 goto freepage_out;
6007 }
6008
6009 nLeaf = get4byte(&pTrunk->aData[4]);
drheeb844a2009-08-08 18:01:07 +00006010 assert( pBt->usableSize>32 );
6011 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
danielk1977bea2a942009-01-20 17:06:27 +00006012 rc = SQLITE_CORRUPT_BKPT;
6013 goto freepage_out;
6014 }
drheeb844a2009-08-08 18:01:07 +00006015 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
danielk1977bea2a942009-01-20 17:06:27 +00006016 /* In this case there is room on the trunk page to insert the page
6017 ** being freed as a new leaf.
drh45b1fac2008-07-04 17:52:42 +00006018 **
6019 ** Note that the trunk page is not really full until it contains
6020 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
6021 ** coded. But due to a coding error in versions of SQLite prior to
6022 ** 3.6.0, databases with freelist trunk pages holding more than
6023 ** usableSize/4 - 8 entries will be reported as corrupt. In order
6024 ** to maintain backwards compatibility with older versions of SQLite,
drhc046e3e2009-07-15 11:26:44 +00006025 ** we will continue to restrict the number of entries to usableSize/4 - 8
drh45b1fac2008-07-04 17:52:42 +00006026 ** for now. At some point in the future (once everyone has upgraded
6027 ** to 3.6.0 or later) we should consider fixing the conditional above
6028 ** to read "usableSize/4-2" instead of "usableSize/4-8".
drh113762a2014-11-19 16:36:25 +00006029 **
6030 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
6031 ** avoid using the last six entries in the freelist trunk page array in
6032 ** order that database files created by newer versions of SQLite can be
6033 ** read by older versions of SQLite.
drh45b1fac2008-07-04 17:52:42 +00006034 */
danielk19773b8a05f2007-03-19 17:44:26 +00006035 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00006036 if( rc==SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00006037 put4byte(&pTrunk->aData[4], nLeaf+1);
6038 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
drhc9166342012-01-05 23:32:06 +00006039 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
danielk1977bea2a942009-01-20 17:06:27 +00006040 sqlite3PagerDontWrite(pPage->pDbPage);
6041 }
danielk1977bea2a942009-01-20 17:06:27 +00006042 rc = btreeSetHasContent(pBt, iPage);
drhf5345442007-04-09 12:45:02 +00006043 }
drh3a4c1412004-05-09 20:40:11 +00006044 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
danielk1977bea2a942009-01-20 17:06:27 +00006045 goto freepage_out;
drh3aac2dd2004-04-26 14:10:20 +00006046 }
drh3b7511c2001-05-26 13:15:44 +00006047 }
danielk1977bea2a942009-01-20 17:06:27 +00006048
6049 /* If control flows to this point, then it was not possible to add the
6050 ** the page being freed as a leaf page of the first trunk in the free-list.
6051 ** Possibly because the free-list is empty, or possibly because the
6052 ** first trunk in the free-list is full. Either way, the page being freed
6053 ** will become the new first trunk page in the free-list.
6054 */
drhb00fc3b2013-08-21 23:42:32 +00006055 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
drhc046e3e2009-07-15 11:26:44 +00006056 goto freepage_out;
6057 }
6058 rc = sqlite3PagerWrite(pPage->pDbPage);
6059 if( rc!=SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00006060 goto freepage_out;
6061 }
6062 put4byte(pPage->aData, iTrunk);
6063 put4byte(&pPage->aData[4], 0);
6064 put4byte(&pPage1->aData[32], iPage);
6065 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
6066
6067freepage_out:
6068 if( pPage ){
6069 pPage->isInit = 0;
6070 }
6071 releasePage(pPage);
6072 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00006073 return rc;
6074}
drhc314dc72009-07-21 11:52:34 +00006075static void freePage(MemPage *pPage, int *pRC){
6076 if( (*pRC)==SQLITE_OK ){
6077 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
6078 }
danielk1977bea2a942009-01-20 17:06:27 +00006079}
drh3b7511c2001-05-26 13:15:44 +00006080
6081/*
drh9bfdc252014-09-24 02:05:41 +00006082** Free any overflow pages associated with the given Cell. Write the
6083** local Cell size (the number of bytes on the original page, omitting
6084** overflow) into *pnSize.
drh3b7511c2001-05-26 13:15:44 +00006085*/
drh9bfdc252014-09-24 02:05:41 +00006086static int clearCell(
6087 MemPage *pPage, /* The page that contains the Cell */
6088 unsigned char *pCell, /* First byte of the Cell */
drh80159da2016-12-09 17:32:51 +00006089 CellInfo *pInfo /* Size information about the cell */
drh9bfdc252014-09-24 02:05:41 +00006090){
danielk1977aef0bf62005-12-30 16:28:01 +00006091 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00006092 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00006093 int rc;
drh94440812007-03-06 11:42:19 +00006094 int nOvfl;
shaneh1df2db72010-08-18 02:28:48 +00006095 u32 ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00006096
drh1fee73e2007-08-29 04:00:57 +00006097 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh80159da2016-12-09 17:32:51 +00006098 pPage->xParseCell(pPage, pCell, pInfo);
6099 if( pInfo->nLocal==pInfo->nPayload ){
drha34b6762004-05-07 13:30:42 +00006100 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00006101 }
drh80159da2016-12-09 17:32:51 +00006102 if( pCell+pInfo->nSize-1 > pPage->aData+pPage->maskPage ){
mistachkin70a1b712012-09-28 18:13:35 +00006103 return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
drhe42a9b42011-08-31 13:27:19 +00006104 }
drh80159da2016-12-09 17:32:51 +00006105 ovflPgno = get4byte(pCell + pInfo->nSize - 4);
shane63207ab2009-02-04 01:49:30 +00006106 assert( pBt->usableSize > 4 );
drh94440812007-03-06 11:42:19 +00006107 ovflPageSize = pBt->usableSize - 4;
drh80159da2016-12-09 17:32:51 +00006108 nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
dan0f8076d2015-05-25 18:47:26 +00006109 assert( nOvfl>0 ||
drh80159da2016-12-09 17:32:51 +00006110 (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
dan0f8076d2015-05-25 18:47:26 +00006111 );
drh72365832007-03-06 15:53:44 +00006112 while( nOvfl-- ){
shane63207ab2009-02-04 01:49:30 +00006113 Pgno iNext = 0;
danielk1977bea2a942009-01-20 17:06:27 +00006114 MemPage *pOvfl = 0;
drhb1299152010-03-30 22:58:33 +00006115 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
danielk1977e589a672009-04-11 16:06:15 +00006116 /* 0 is not a legal page number and page 1 cannot be an
6117 ** overflow page. Therefore if ovflPgno<2 or past the end of the
6118 ** file the database must be corrupt. */
drh49285702005-09-17 15:20:26 +00006119 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00006120 }
danielk1977bea2a942009-01-20 17:06:27 +00006121 if( nOvfl ){
6122 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
6123 if( rc ) return rc;
6124 }
dan887d4b22010-02-25 12:09:16 +00006125
shaneh1da207e2010-03-09 14:41:12 +00006126 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
dan887d4b22010-02-25 12:09:16 +00006127 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
6128 ){
6129 /* There is no reason any cursor should have an outstanding reference
6130 ** to an overflow page belonging to a cell that is being deleted/updated.
6131 ** So if there exists more than one reference to this page, then it
6132 ** must not really be an overflow page and the database must be corrupt.
6133 ** It is helpful to detect this before calling freePage2(), as
6134 ** freePage2() may zero the page contents if secure-delete mode is
6135 ** enabled. If this 'overflow' page happens to be a page that the
6136 ** caller is iterating through or using in some other way, this
6137 ** can be problematic.
6138 */
6139 rc = SQLITE_CORRUPT_BKPT;
6140 }else{
6141 rc = freePage2(pBt, pOvfl, ovflPgno);
6142 }
6143
danielk1977bea2a942009-01-20 17:06:27 +00006144 if( pOvfl ){
6145 sqlite3PagerUnref(pOvfl->pDbPage);
6146 }
drh3b7511c2001-05-26 13:15:44 +00006147 if( rc ) return rc;
danielk1977bea2a942009-01-20 17:06:27 +00006148 ovflPgno = iNext;
drh3b7511c2001-05-26 13:15:44 +00006149 }
drh5e2f8b92001-05-28 00:41:15 +00006150 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00006151}
6152
6153/*
drh91025292004-05-03 19:49:32 +00006154** Create the byte sequence used to represent a cell on page pPage
6155** and write that byte sequence into pCell[]. Overflow pages are
6156** allocated and filled in as necessary. The calling procedure
6157** is responsible for making sure sufficient space has been allocated
6158** for pCell[].
6159**
6160** Note that pCell does not necessary need to point to the pPage->aData
6161** area. pCell might point to some temporary storage. The cell will
6162** be constructed in this temporary area then copied into pPage->aData
6163** later.
drh3b7511c2001-05-26 13:15:44 +00006164*/
6165static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00006166 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00006167 unsigned char *pCell, /* Complete text of the cell */
drh8eeb4462016-05-21 20:03:42 +00006168 const BtreePayload *pX, /* Payload with which to construct the cell */
drh4b70f112004-05-02 21:12:19 +00006169 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00006170){
drh3b7511c2001-05-26 13:15:44 +00006171 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00006172 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00006173 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00006174 int spaceLeft;
6175 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00006176 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00006177 unsigned char *pPrior;
6178 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00006179 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00006180 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00006181 int nHeader;
drh3b7511c2001-05-26 13:15:44 +00006182
drh1fee73e2007-08-29 04:00:57 +00006183 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00006184
drhc5053fb2008-11-27 02:22:10 +00006185 /* pPage is not necessarily writeable since pCell might be auxiliary
6186 ** buffer space that is separate from the pPage buffer area */
6187 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
6188 || sqlite3PagerIswriteable(pPage->pDbPage) );
6189
drh91025292004-05-03 19:49:32 +00006190 /* Fill in the header. */
drh6200c882014-09-23 22:36:25 +00006191 nHeader = pPage->childPtrSize;
drhdfc2daa2016-05-21 23:25:29 +00006192 if( pPage->intKey ){
6193 nPayload = pX->nData + pX->nZero;
6194 pSrc = pX->pData;
6195 nSrc = pX->nData;
6196 assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
drh6200c882014-09-23 22:36:25 +00006197 nHeader += putVarint32(&pCell[nHeader], nPayload);
drhdfc2daa2016-05-21 23:25:29 +00006198 nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
drh6f11bef2004-05-13 01:12:56 +00006199 }else{
drh8eeb4462016-05-21 20:03:42 +00006200 assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
6201 nSrc = nPayload = (int)pX->nKey;
6202 pSrc = pX->pKey;
drhdfc2daa2016-05-21 23:25:29 +00006203 nHeader += putVarint32(&pCell[nHeader], nPayload);
drh3aac2dd2004-04-26 14:10:20 +00006204 }
drhdfc2daa2016-05-21 23:25:29 +00006205
6206 /* Fill in the payload */
drh6200c882014-09-23 22:36:25 +00006207 if( nPayload<=pPage->maxLocal ){
6208 n = nHeader + nPayload;
6209 testcase( n==3 );
6210 testcase( n==4 );
6211 if( n<4 ) n = 4;
6212 *pnSize = n;
6213 spaceLeft = nPayload;
6214 pPrior = pCell;
6215 }else{
6216 int mn = pPage->minLocal;
6217 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
6218 testcase( n==pPage->maxLocal );
6219 testcase( n==pPage->maxLocal+1 );
6220 if( n > pPage->maxLocal ) n = mn;
6221 spaceLeft = n;
6222 *pnSize = n + nHeader + 4;
6223 pPrior = &pCell[nHeader+n];
6224 }
drh3aac2dd2004-04-26 14:10:20 +00006225 pPayload = &pCell[nHeader];
drh3b7511c2001-05-26 13:15:44 +00006226
drh6200c882014-09-23 22:36:25 +00006227 /* At this point variables should be set as follows:
6228 **
6229 ** nPayload Total payload size in bytes
6230 ** pPayload Begin writing payload here
6231 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
6232 ** that means content must spill into overflow pages.
6233 ** *pnSize Size of the local cell (not counting overflow pages)
6234 ** pPrior Where to write the pgno of the first overflow page
6235 **
6236 ** Use a call to btreeParseCellPtr() to verify that the values above
6237 ** were computed correctly.
6238 */
drhd879e3e2017-02-13 13:35:55 +00006239#ifdef SQLITE_DEBUG
drh6200c882014-09-23 22:36:25 +00006240 {
6241 CellInfo info;
drh5fa60512015-06-19 17:19:34 +00006242 pPage->xParseCell(pPage, pCell, &info);
drhcc5f8a42016-02-06 22:32:06 +00006243 assert( nHeader==(int)(info.pPayload - pCell) );
drh8eeb4462016-05-21 20:03:42 +00006244 assert( info.nKey==pX->nKey );
drh6200c882014-09-23 22:36:25 +00006245 assert( *pnSize == info.nSize );
6246 assert( spaceLeft == info.nLocal );
drh6200c882014-09-23 22:36:25 +00006247 }
6248#endif
6249
6250 /* Write the payload into the local Cell and any extra into overflow pages */
drh3b7511c2001-05-26 13:15:44 +00006251 while( nPayload>0 ){
6252 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00006253#ifndef SQLITE_OMIT_AUTOVACUUM
6254 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00006255 if( pBt->autoVacuum ){
6256 do{
6257 pgnoOvfl++;
6258 } while(
6259 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
6260 );
danielk1977b39f70b2007-05-17 18:28:11 +00006261 }
danielk1977afcdd022004-10-31 16:25:42 +00006262#endif
drhf49661a2008-12-10 16:45:50 +00006263 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00006264#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00006265 /* If the database supports auto-vacuum, and the second or subsequent
6266 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00006267 ** for that page now.
6268 **
6269 ** If this is the first overflow page, then write a partial entry
6270 ** to the pointer-map. If we write nothing to this pointer-map slot,
6271 ** then the optimistic overflow chain processing in clearCell()
mistachkin48864df2013-03-21 21:20:32 +00006272 ** may misinterpret the uninitialized values and delete the
danielk19774ef24492007-05-23 09:52:41 +00006273 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00006274 */
danielk19774ef24492007-05-23 09:52:41 +00006275 if( pBt->autoVacuum && rc==SQLITE_OK ){
6276 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
drh98add2e2009-07-20 17:11:49 +00006277 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
danielk197789a4be82007-05-23 13:34:32 +00006278 if( rc ){
6279 releasePage(pOvfl);
6280 }
danielk1977afcdd022004-10-31 16:25:42 +00006281 }
6282#endif
drh3b7511c2001-05-26 13:15:44 +00006283 if( rc ){
drh9b171272004-05-08 02:03:22 +00006284 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00006285 return rc;
6286 }
drhc5053fb2008-11-27 02:22:10 +00006287
6288 /* If pToRelease is not zero than pPrior points into the data area
6289 ** of pToRelease. Make sure pToRelease is still writeable. */
6290 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6291
6292 /* If pPrior is part of the data area of pPage, then make sure pPage
6293 ** is still writeable */
6294 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
6295 || sqlite3PagerIswriteable(pPage->pDbPage) );
6296
drh3aac2dd2004-04-26 14:10:20 +00006297 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00006298 releasePage(pToRelease);
6299 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00006300 pPrior = pOvfl->aData;
6301 put4byte(pPrior, 0);
6302 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00006303 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00006304 }
6305 n = nPayload;
6306 if( n>spaceLeft ) n = spaceLeft;
drhc5053fb2008-11-27 02:22:10 +00006307
6308 /* If pToRelease is not zero than pPayload points into the data area
6309 ** of pToRelease. Make sure pToRelease is still writeable. */
6310 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6311
6312 /* If pPayload is part of the data area of pPage, then make sure pPage
6313 ** is still writeable */
6314 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
6315 || sqlite3PagerIswriteable(pPage->pDbPage) );
6316
drhb026e052007-05-02 01:34:31 +00006317 if( nSrc>0 ){
6318 if( n>nSrc ) n = nSrc;
6319 assert( pSrc );
6320 memcpy(pPayload, pSrc, n);
6321 }else{
6322 memset(pPayload, 0, n);
6323 }
drh3b7511c2001-05-26 13:15:44 +00006324 nPayload -= n;
drhde647132004-05-07 17:57:49 +00006325 pPayload += n;
drh9b171272004-05-08 02:03:22 +00006326 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00006327 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00006328 spaceLeft -= n;
drhdd793422001-06-28 01:54:48 +00006329 }
drh9b171272004-05-08 02:03:22 +00006330 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00006331 return SQLITE_OK;
6332}
6333
drh14acc042001-06-10 19:56:58 +00006334/*
6335** Remove the i-th cell from pPage. This routine effects pPage only.
6336** The cell content is not freed or deallocated. It is assumed that
6337** the cell content has been copied someplace else. This routine just
6338** removes the reference to the cell from pPage.
6339**
6340** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00006341*/
drh98add2e2009-07-20 17:11:49 +00006342static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
drh43b18e12010-08-17 19:40:08 +00006343 u32 pc; /* Offset to cell content of cell being deleted */
drh43605152004-05-29 21:46:49 +00006344 u8 *data; /* pPage->aData */
6345 u8 *ptr; /* Used to move bytes around within data[] */
shanedcc50b72008-11-13 18:29:50 +00006346 int rc; /* The return code */
drhc314dc72009-07-21 11:52:34 +00006347 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
drh43605152004-05-29 21:46:49 +00006348
drh98add2e2009-07-20 17:11:49 +00006349 if( *pRC ) return;
drh8c42ca92001-06-22 19:15:00 +00006350 assert( idx>=0 && idx<pPage->nCell );
dan0f8076d2015-05-25 18:47:26 +00006351 assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00006352 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00006353 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00006354 data = pPage->aData;
drh3def2352011-11-11 00:27:15 +00006355 ptr = &pPage->aCellIdx[2*idx];
shane0af3f892008-11-12 04:55:34 +00006356 pc = get2byte(ptr);
drhc314dc72009-07-21 11:52:34 +00006357 hdr = pPage->hdrOffset;
6358 testcase( pc==get2byte(&data[hdr+5]) );
6359 testcase( pc+sz==pPage->pBt->usableSize );
drh43b18e12010-08-17 19:40:08 +00006360 if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
drh98add2e2009-07-20 17:11:49 +00006361 *pRC = SQLITE_CORRUPT_BKPT;
6362 return;
shane0af3f892008-11-12 04:55:34 +00006363 }
shanedcc50b72008-11-13 18:29:50 +00006364 rc = freeSpace(pPage, pc, sz);
drh98add2e2009-07-20 17:11:49 +00006365 if( rc ){
6366 *pRC = rc;
6367 return;
shanedcc50b72008-11-13 18:29:50 +00006368 }
drh14acc042001-06-10 19:56:58 +00006369 pPage->nCell--;
drhfdab0262014-11-20 15:30:50 +00006370 if( pPage->nCell==0 ){
6371 memset(&data[hdr+1], 0, 4);
6372 data[hdr+7] = 0;
6373 put2byte(&data[hdr+5], pPage->pBt->usableSize);
6374 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
6375 - pPage->childPtrSize - 8;
6376 }else{
6377 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
6378 put2byte(&data[hdr+3], pPage->nCell);
6379 pPage->nFree += 2;
6380 }
drh14acc042001-06-10 19:56:58 +00006381}
6382
6383/*
6384** Insert a new cell on pPage at cell index "i". pCell points to the
6385** content of the cell.
6386**
6387** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00006388** will not fit, then make a copy of the cell content into pTemp if
6389** pTemp is not null. Regardless of pTemp, allocate a new entry
drh2cbd78b2012-02-02 19:37:18 +00006390** in pPage->apOvfl[] and make it point to the cell content (either
drh43605152004-05-29 21:46:49 +00006391** in pTemp or the original pCell) and also record its index.
6392** Allocating a new entry in pPage->aCell[] implies that
6393** pPage->nOverflow is incremented.
drhcb89f4a2016-05-21 11:23:26 +00006394**
6395** *pRC must be SQLITE_OK when this routine is called.
drh14acc042001-06-10 19:56:58 +00006396*/
drh98add2e2009-07-20 17:11:49 +00006397static void insertCell(
drh24cd67e2004-05-10 16:18:47 +00006398 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00006399 int i, /* New cell becomes the i-th cell of the page */
6400 u8 *pCell, /* Content of the new cell */
6401 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00006402 u8 *pTemp, /* Temp storage space for pCell, if needed */
drh98add2e2009-07-20 17:11:49 +00006403 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
6404 int *pRC /* Read and write return code from here */
drh24cd67e2004-05-10 16:18:47 +00006405){
drh383d30f2010-02-26 13:07:37 +00006406 int idx = 0; /* Where to write new cell content in data[] */
drh43605152004-05-29 21:46:49 +00006407 int j; /* Loop counter */
drh43605152004-05-29 21:46:49 +00006408 u8 *data; /* The content of the whole page */
drh2c8fb922015-06-25 19:53:48 +00006409 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
danielk19774dbaa892009-06-16 16:50:22 +00006410
drhcb89f4a2016-05-21 11:23:26 +00006411 assert( *pRC==SQLITE_OK );
drh43605152004-05-29 21:46:49 +00006412 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
danf216e322014-08-14 19:53:37 +00006413 assert( MX_CELL(pPage->pBt)<=10921 );
6414 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
drh2cbd78b2012-02-02 19:37:18 +00006415 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
6416 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
drh1fee73e2007-08-29 04:00:57 +00006417 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc9b9b8a2009-12-03 21:26:52 +00006418 /* The cell should normally be sized correctly. However, when moving a
6419 ** malformed cell from a leaf page to an interior page, if the cell size
6420 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
6421 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
6422 ** the term after the || in the following assert(). */
drh25ada072015-06-19 15:07:14 +00006423 assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
drh43605152004-05-29 21:46:49 +00006424 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00006425 if( pTemp ){
drhd6176c42014-10-11 17:22:55 +00006426 memcpy(pTemp, pCell, sz);
drh43605152004-05-29 21:46:49 +00006427 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00006428 }
danielk19774dbaa892009-06-16 16:50:22 +00006429 if( iChild ){
6430 put4byte(pCell, iChild);
6431 }
drh43605152004-05-29 21:46:49 +00006432 j = pPage->nOverflow++;
drha2ee5892016-12-09 16:02:00 +00006433 /* Comparison against ArraySize-1 since we hold back one extra slot
6434 ** as a contingency. In other words, never need more than 3 overflow
6435 ** slots but 4 are allocated, just to be safe. */
6436 assert( j < ArraySize(pPage->apOvfl)-1 );
drh2cbd78b2012-02-02 19:37:18 +00006437 pPage->apOvfl[j] = pCell;
6438 pPage->aiOvfl[j] = (u16)i;
drhfe647dc2015-06-23 18:24:25 +00006439
6440 /* When multiple overflows occur, they are always sequential and in
6441 ** sorted order. This invariants arise because multiple overflows can
6442 ** only occur when inserting divider cells into the parent page during
6443 ** balancing, and the dividers are adjacent and sorted.
6444 */
6445 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
6446 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
drh14acc042001-06-10 19:56:58 +00006447 }else{
danielk19776e465eb2007-08-21 13:11:00 +00006448 int rc = sqlite3PagerWrite(pPage->pDbPage);
6449 if( rc!=SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00006450 *pRC = rc;
6451 return;
danielk19776e465eb2007-08-21 13:11:00 +00006452 }
6453 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00006454 data = pPage->aData;
drh2c8fb922015-06-25 19:53:48 +00006455 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
drh0a45c272009-07-08 01:49:11 +00006456 rc = allocateSpace(pPage, sz, &idx);
drh98add2e2009-07-20 17:11:49 +00006457 if( rc ){ *pRC = rc; return; }
drhcd8fb7c2015-06-02 14:02:18 +00006458 /* The allocateSpace() routine guarantees the following properties
6459 ** if it returns successfully */
drh2c8fb922015-06-25 19:53:48 +00006460 assert( idx >= 0 );
6461 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
drhfcd71b62011-04-05 22:08:24 +00006462 assert( idx+sz <= (int)pPage->pBt->usableSize );
drh0a45c272009-07-08 01:49:11 +00006463 pPage->nFree -= (u16)(2 + sz);
drhd6176c42014-10-11 17:22:55 +00006464 memcpy(&data[idx], pCell, sz);
danielk19774dbaa892009-06-16 16:50:22 +00006465 if( iChild ){
6466 put4byte(&data[idx], iChild);
6467 }
drh2c8fb922015-06-25 19:53:48 +00006468 pIns = pPage->aCellIdx + i*2;
6469 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
6470 put2byte(pIns, idx);
6471 pPage->nCell++;
6472 /* increment the cell count */
6473 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
6474 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
danielk1977a19df672004-11-03 11:37:07 +00006475#ifndef SQLITE_OMIT_AUTOVACUUM
6476 if( pPage->pBt->autoVacuum ){
6477 /* The cell may contain a pointer to an overflow page. If so, write
6478 ** the entry for the overflow page into the pointer map.
6479 */
drh98add2e2009-07-20 17:11:49 +00006480 ptrmapPutOvflPtr(pPage, pCell, pRC);
danielk1977a19df672004-11-03 11:37:07 +00006481 }
6482#endif
drh14acc042001-06-10 19:56:58 +00006483 }
6484}
6485
6486/*
drh1ffd2472015-06-23 02:37:30 +00006487** A CellArray object contains a cache of pointers and sizes for a
drhc0d269e2016-08-03 14:51:16 +00006488** consecutive sequence of cells that might be held on multiple pages.
drhfa1a98a2004-05-14 19:08:17 +00006489*/
drh1ffd2472015-06-23 02:37:30 +00006490typedef struct CellArray CellArray;
6491struct CellArray {
6492 int nCell; /* Number of cells in apCell[] */
6493 MemPage *pRef; /* Reference page */
6494 u8 **apCell; /* All cells begin balanced */
6495 u16 *szCell; /* Local size of all cells in apCell[] */
6496};
drhfa1a98a2004-05-14 19:08:17 +00006497
drh1ffd2472015-06-23 02:37:30 +00006498/*
6499** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
6500** computed.
6501*/
6502static void populateCellCache(CellArray *p, int idx, int N){
6503 assert( idx>=0 && idx+N<=p->nCell );
6504 while( N>0 ){
6505 assert( p->apCell[idx]!=0 );
6506 if( p->szCell[idx]==0 ){
6507 p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
6508 }else{
6509 assert( CORRUPT_DB ||
6510 p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
6511 }
6512 idx++;
6513 N--;
drhfa1a98a2004-05-14 19:08:17 +00006514 }
drh1ffd2472015-06-23 02:37:30 +00006515}
6516
6517/*
6518** Return the size of the Nth element of the cell array
6519*/
6520static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
6521 assert( N>=0 && N<p->nCell );
6522 assert( p->szCell[N]==0 );
6523 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
6524 return p->szCell[N];
6525}
6526static u16 cachedCellSize(CellArray *p, int N){
6527 assert( N>=0 && N<p->nCell );
6528 if( p->szCell[N] ) return p->szCell[N];
6529 return computeCellSize(p, N);
6530}
6531
6532/*
dan8e9ba0c2014-10-14 17:27:04 +00006533** Array apCell[] contains pointers to nCell b-tree page cells. The
6534** szCell[] array contains the size in bytes of each cell. This function
6535** replaces the current contents of page pPg with the contents of the cell
6536** array.
6537**
6538** Some of the cells in apCell[] may currently be stored in pPg. This
6539** function works around problems caused by this by making a copy of any
6540** such cells before overwriting the page data.
6541**
6542** The MemPage.nFree field is invalidated by this function. It is the
6543** responsibility of the caller to set it correctly.
drhfa1a98a2004-05-14 19:08:17 +00006544*/
drh658873b2015-06-22 20:02:04 +00006545static int rebuildPage(
dan33ea4862014-10-09 19:35:37 +00006546 MemPage *pPg, /* Edit this page */
dan33ea4862014-10-09 19:35:37 +00006547 int nCell, /* Final number of cells on page */
dan09c68402014-10-11 20:00:24 +00006548 u8 **apCell, /* Array of cells */
6549 u16 *szCell /* Array of cell sizes */
dan33ea4862014-10-09 19:35:37 +00006550){
6551 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
6552 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
6553 const int usableSize = pPg->pBt->usableSize;
6554 u8 * const pEnd = &aData[usableSize];
6555 int i;
6556 u8 *pCellptr = pPg->aCellIdx;
6557 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6558 u8 *pData;
6559
6560 i = get2byte(&aData[hdr+5]);
6561 memcpy(&pTmp[i], &aData[i], usableSize - i);
dan33ea4862014-10-09 19:35:37 +00006562
dan8e9ba0c2014-10-14 17:27:04 +00006563 pData = pEnd;
dan33ea4862014-10-09 19:35:37 +00006564 for(i=0; i<nCell; i++){
6565 u8 *pCell = apCell[i];
drh8b0ba7b2015-12-16 13:07:35 +00006566 if( SQLITE_WITHIN(pCell,aData,pEnd) ){
dan33ea4862014-10-09 19:35:37 +00006567 pCell = &pTmp[pCell - aData];
6568 }
6569 pData -= szCell[i];
dan33ea4862014-10-09 19:35:37 +00006570 put2byte(pCellptr, (pData - aData));
6571 pCellptr += 2;
drh658873b2015-06-22 20:02:04 +00006572 if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
6573 memcpy(pData, pCell, szCell[i]);
drh25ada072015-06-19 15:07:14 +00006574 assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
drhea82b372015-06-23 21:35:28 +00006575 testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
dan33ea4862014-10-09 19:35:37 +00006576 }
6577
dand7b545b2014-10-13 18:03:27 +00006578 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
dan33ea4862014-10-09 19:35:37 +00006579 pPg->nCell = nCell;
6580 pPg->nOverflow = 0;
6581
6582 put2byte(&aData[hdr+1], 0);
6583 put2byte(&aData[hdr+3], pPg->nCell);
6584 put2byte(&aData[hdr+5], pData - aData);
6585 aData[hdr+7] = 0x00;
drh658873b2015-06-22 20:02:04 +00006586 return SQLITE_OK;
dan33ea4862014-10-09 19:35:37 +00006587}
6588
dan8e9ba0c2014-10-14 17:27:04 +00006589/*
6590** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
6591** contains the size in bytes of each such cell. This function attempts to
6592** add the cells stored in the array to page pPg. If it cannot (because
6593** the page needs to be defragmented before the cells will fit), non-zero
6594** is returned. Otherwise, if the cells are added successfully, zero is
6595** returned.
6596**
6597** Argument pCellptr points to the first entry in the cell-pointer array
6598** (part of page pPg) to populate. After cell apCell[0] is written to the
6599** page body, a 16-bit offset is written to pCellptr. And so on, for each
6600** cell in the array. It is the responsibility of the caller to ensure
6601** that it is safe to overwrite this part of the cell-pointer array.
6602**
6603** When this function is called, *ppData points to the start of the
6604** content area on page pPg. If the size of the content area is extended,
6605** *ppData is updated to point to the new start of the content area
6606** before returning.
6607**
6608** Finally, argument pBegin points to the byte immediately following the
6609** end of the space required by this page for the cell-pointer area (for
6610** all cells - not just those inserted by the current call). If the content
6611** area must be extended to before this point in order to accomodate all
6612** cells in apCell[], then the cells do not fit and non-zero is returned.
6613*/
dand7b545b2014-10-13 18:03:27 +00006614static int pageInsertArray(
dan8e9ba0c2014-10-14 17:27:04 +00006615 MemPage *pPg, /* Page to add cells to */
6616 u8 *pBegin, /* End of cell-pointer array */
6617 u8 **ppData, /* IN/OUT: Page content -area pointer */
6618 u8 *pCellptr, /* Pointer to cell-pointer area */
drhf7838932015-06-23 15:36:34 +00006619 int iFirst, /* Index of first cell to add */
dan8e9ba0c2014-10-14 17:27:04 +00006620 int nCell, /* Number of cells to add to pPg */
drhf7838932015-06-23 15:36:34 +00006621 CellArray *pCArray /* Array of cells */
dand7b545b2014-10-13 18:03:27 +00006622){
6623 int i;
6624 u8 *aData = pPg->aData;
6625 u8 *pData = *ppData;
drhf7838932015-06-23 15:36:34 +00006626 int iEnd = iFirst + nCell;
dan23eba452014-10-24 18:43:57 +00006627 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
drhf7838932015-06-23 15:36:34 +00006628 for(i=iFirst; i<iEnd; i++){
6629 int sz, rc;
dand7b545b2014-10-13 18:03:27 +00006630 u8 *pSlot;
drhf7838932015-06-23 15:36:34 +00006631 sz = cachedCellSize(pCArray, i);
drhb7580e82015-06-25 18:36:13 +00006632 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
drhcca66982016-04-05 13:19:19 +00006633 if( (pData - pBegin)<sz ) return 1;
dand7b545b2014-10-13 18:03:27 +00006634 pData -= sz;
dand7b545b2014-10-13 18:03:27 +00006635 pSlot = pData;
6636 }
drh48310f82015-10-10 16:41:28 +00006637 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
6638 ** database. But they might for a corrupt database. Hence use memmove()
6639 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
6640 assert( (pSlot+sz)<=pCArray->apCell[i]
6641 || pSlot>=(pCArray->apCell[i]+sz)
6642 || CORRUPT_DB );
6643 memmove(pSlot, pCArray->apCell[i], sz);
dand7b545b2014-10-13 18:03:27 +00006644 put2byte(pCellptr, (pSlot - aData));
6645 pCellptr += 2;
6646 }
6647 *ppData = pData;
6648 return 0;
6649}
6650
dan8e9ba0c2014-10-14 17:27:04 +00006651/*
6652** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
6653** contains the size in bytes of each such cell. This function adds the
6654** space associated with each cell in the array that is currently stored
6655** within the body of pPg to the pPg free-list. The cell-pointers and other
6656** fields of the page are not updated.
6657**
6658** This function returns the total number of cells added to the free-list.
6659*/
dand7b545b2014-10-13 18:03:27 +00006660static int pageFreeArray(
6661 MemPage *pPg, /* Page to edit */
drhf7838932015-06-23 15:36:34 +00006662 int iFirst, /* First cell to delete */
dand7b545b2014-10-13 18:03:27 +00006663 int nCell, /* Cells to delete */
drhf7838932015-06-23 15:36:34 +00006664 CellArray *pCArray /* Array of cells */
dand7b545b2014-10-13 18:03:27 +00006665){
6666 u8 * const aData = pPg->aData;
6667 u8 * const pEnd = &aData[pPg->pBt->usableSize];
dan89ca0b32014-10-25 20:36:28 +00006668 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
dand7b545b2014-10-13 18:03:27 +00006669 int nRet = 0;
6670 int i;
drhf7838932015-06-23 15:36:34 +00006671 int iEnd = iFirst + nCell;
dand7b545b2014-10-13 18:03:27 +00006672 u8 *pFree = 0;
6673 int szFree = 0;
6674
drhf7838932015-06-23 15:36:34 +00006675 for(i=iFirst; i<iEnd; i++){
6676 u8 *pCell = pCArray->apCell[i];
drh8b0ba7b2015-12-16 13:07:35 +00006677 if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
drhf7838932015-06-23 15:36:34 +00006678 int sz;
6679 /* No need to use cachedCellSize() here. The sizes of all cells that
6680 ** are to be freed have already been computing while deciding which
6681 ** cells need freeing */
6682 sz = pCArray->szCell[i]; assert( sz>0 );
dand7b545b2014-10-13 18:03:27 +00006683 if( pFree!=(pCell + sz) ){
drhfefa0942014-11-05 21:21:08 +00006684 if( pFree ){
6685 assert( pFree>aData && (pFree - aData)<65536 );
6686 freeSpace(pPg, (u16)(pFree - aData), szFree);
6687 }
dand7b545b2014-10-13 18:03:27 +00006688 pFree = pCell;
6689 szFree = sz;
dan89ca0b32014-10-25 20:36:28 +00006690 if( pFree+sz>pEnd ) return 0;
dand7b545b2014-10-13 18:03:27 +00006691 }else{
6692 pFree = pCell;
6693 szFree += sz;
6694 }
6695 nRet++;
6696 }
6697 }
drhfefa0942014-11-05 21:21:08 +00006698 if( pFree ){
6699 assert( pFree>aData && (pFree - aData)<65536 );
6700 freeSpace(pPg, (u16)(pFree - aData), szFree);
6701 }
dand7b545b2014-10-13 18:03:27 +00006702 return nRet;
6703}
6704
dand7b545b2014-10-13 18:03:27 +00006705/*
drh5ab63772014-11-27 03:46:04 +00006706** apCell[] and szCell[] contains pointers to and sizes of all cells in the
6707** pages being balanced. The current page, pPg, has pPg->nCell cells starting
6708** with apCell[iOld]. After balancing, this page should hold nNew cells
6709** starting at apCell[iNew].
6710**
6711** This routine makes the necessary adjustments to pPg so that it contains
6712** the correct cells after being balanced.
6713**
dand7b545b2014-10-13 18:03:27 +00006714** The pPg->nFree field is invalid when this function returns. It is the
6715** responsibility of the caller to set it correctly.
6716*/
drh658873b2015-06-22 20:02:04 +00006717static int editPage(
dan09c68402014-10-11 20:00:24 +00006718 MemPage *pPg, /* Edit this page */
6719 int iOld, /* Index of first cell currently on page */
6720 int iNew, /* Index of new first cell on page */
6721 int nNew, /* Final number of cells on page */
drh1ffd2472015-06-23 02:37:30 +00006722 CellArray *pCArray /* Array of cells and sizes */
dan09c68402014-10-11 20:00:24 +00006723){
dand7b545b2014-10-13 18:03:27 +00006724 u8 * const aData = pPg->aData;
6725 const int hdr = pPg->hdrOffset;
6726 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
6727 int nCell = pPg->nCell; /* Cells stored on pPg */
6728 u8 *pData;
6729 u8 *pCellptr;
6730 int i;
6731 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
6732 int iNewEnd = iNew + nNew;
dan09c68402014-10-11 20:00:24 +00006733
6734#ifdef SQLITE_DEBUG
dand7b545b2014-10-13 18:03:27 +00006735 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6736 memcpy(pTmp, aData, pPg->pBt->usableSize);
dan09c68402014-10-11 20:00:24 +00006737#endif
6738
dand7b545b2014-10-13 18:03:27 +00006739 /* Remove cells from the start and end of the page */
6740 if( iOld<iNew ){
drhf7838932015-06-23 15:36:34 +00006741 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
dand7b545b2014-10-13 18:03:27 +00006742 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
6743 nCell -= nShift;
6744 }
6745 if( iNewEnd < iOldEnd ){
drhf7838932015-06-23 15:36:34 +00006746 nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
dand7b545b2014-10-13 18:03:27 +00006747 }
dan09c68402014-10-11 20:00:24 +00006748
drh5ab63772014-11-27 03:46:04 +00006749 pData = &aData[get2byteNotZero(&aData[hdr+5])];
dand7b545b2014-10-13 18:03:27 +00006750 if( pData<pBegin ) goto editpage_fail;
6751
6752 /* Add cells to the start of the page */
6753 if( iNew<iOld ){
drh5ab63772014-11-27 03:46:04 +00006754 int nAdd = MIN(nNew,iOld-iNew);
6755 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
dand7b545b2014-10-13 18:03:27 +00006756 pCellptr = pPg->aCellIdx;
6757 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
6758 if( pageInsertArray(
6759 pPg, pBegin, &pData, pCellptr,
drhf7838932015-06-23 15:36:34 +00006760 iNew, nAdd, pCArray
dand7b545b2014-10-13 18:03:27 +00006761 ) ) goto editpage_fail;
6762 nCell += nAdd;
6763 }
6764
6765 /* Add any overflow cells */
6766 for(i=0; i<pPg->nOverflow; i++){
6767 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
6768 if( iCell>=0 && iCell<nNew ){
drhfefa0942014-11-05 21:21:08 +00006769 pCellptr = &pPg->aCellIdx[iCell * 2];
dand7b545b2014-10-13 18:03:27 +00006770 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
6771 nCell++;
6772 if( pageInsertArray(
6773 pPg, pBegin, &pData, pCellptr,
drhf7838932015-06-23 15:36:34 +00006774 iCell+iNew, 1, pCArray
dand7b545b2014-10-13 18:03:27 +00006775 ) ) goto editpage_fail;
dan09c68402014-10-11 20:00:24 +00006776 }
dand7b545b2014-10-13 18:03:27 +00006777 }
dan09c68402014-10-11 20:00:24 +00006778
dand7b545b2014-10-13 18:03:27 +00006779 /* Append cells to the end of the page */
6780 pCellptr = &pPg->aCellIdx[nCell*2];
6781 if( pageInsertArray(
6782 pPg, pBegin, &pData, pCellptr,
drhf7838932015-06-23 15:36:34 +00006783 iNew+nCell, nNew-nCell, pCArray
dand7b545b2014-10-13 18:03:27 +00006784 ) ) goto editpage_fail;
dan09c68402014-10-11 20:00:24 +00006785
dand7b545b2014-10-13 18:03:27 +00006786 pPg->nCell = nNew;
6787 pPg->nOverflow = 0;
dan09c68402014-10-11 20:00:24 +00006788
dand7b545b2014-10-13 18:03:27 +00006789 put2byte(&aData[hdr+3], pPg->nCell);
6790 put2byte(&aData[hdr+5], pData - aData);
dan09c68402014-10-11 20:00:24 +00006791
6792#ifdef SQLITE_DEBUG
dan23eba452014-10-24 18:43:57 +00006793 for(i=0; i<nNew && !CORRUPT_DB; i++){
drh1ffd2472015-06-23 02:37:30 +00006794 u8 *pCell = pCArray->apCell[i+iNew];
drh329428e2015-06-30 13:28:18 +00006795 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
drh1c715f62016-04-05 13:35:43 +00006796 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
dand7b545b2014-10-13 18:03:27 +00006797 pCell = &pTmp[pCell - aData];
dan09c68402014-10-11 20:00:24 +00006798 }
drh1ffd2472015-06-23 02:37:30 +00006799 assert( 0==memcmp(pCell, &aData[iOff],
6800 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
dand7b545b2014-10-13 18:03:27 +00006801 }
dan09c68402014-10-11 20:00:24 +00006802#endif
6803
drh658873b2015-06-22 20:02:04 +00006804 return SQLITE_OK;
dan09c68402014-10-11 20:00:24 +00006805 editpage_fail:
dan09c68402014-10-11 20:00:24 +00006806 /* Unable to edit this page. Rebuild it from scratch instead. */
drh1ffd2472015-06-23 02:37:30 +00006807 populateCellCache(pCArray, iNew, nNew);
6808 return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
drhfa1a98a2004-05-14 19:08:17 +00006809}
6810
drh14acc042001-06-10 19:56:58 +00006811/*
drhc3b70572003-01-04 19:44:07 +00006812** The following parameters determine how many adjacent pages get involved
6813** in a balancing operation. NN is the number of neighbors on either side
6814** of the page that participate in the balancing operation. NB is the
6815** total number of pages that participate, including the target page and
6816** NN neighbors on either side.
6817**
6818** The minimum value of NN is 1 (of course). Increasing NN above 1
6819** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
6820** in exchange for a larger degradation in INSERT and UPDATE performance.
6821** The value of NN appears to give the best results overall.
6822*/
6823#define NN 1 /* Number of neighbors on either side of pPage */
6824#define NB (NN*2+1) /* Total pages involved in the balance */
6825
danielk1977ac245ec2005-01-14 13:50:11 +00006826
drh615ae552005-01-16 23:21:00 +00006827#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00006828/*
6829** This version of balance() handles the common special case where
6830** a new entry is being inserted on the extreme right-end of the
6831** tree, in other words, when the new entry will become the largest
6832** entry in the tree.
6833**
drhc314dc72009-07-21 11:52:34 +00006834** Instead of trying to balance the 3 right-most leaf pages, just add
drhf222e712005-01-14 22:55:49 +00006835** a new page to the right-hand side and put the one new entry in
6836** that page. This leaves the right side of the tree somewhat
6837** unbalanced. But odds are that we will be inserting new entries
6838** at the end soon afterwards so the nearly empty page will quickly
6839** fill up. On average.
6840**
6841** pPage is the leaf page which is the right-most page in the tree.
6842** pParent is its parent. pPage must have a single overflow entry
6843** which is also the right-most entry on the page.
danielk1977a50d9aa2009-06-08 14:49:45 +00006844**
6845** The pSpace buffer is used to store a temporary copy of the divider
6846** cell that will be inserted into pParent. Such a cell consists of a 4
6847** byte page number followed by a variable length integer. In other
6848** words, at most 13 bytes. Hence the pSpace buffer must be at
6849** least 13 bytes in size.
drhf222e712005-01-14 22:55:49 +00006850*/
danielk1977a50d9aa2009-06-08 14:49:45 +00006851static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
6852 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
danielk19774dbaa892009-06-16 16:50:22 +00006853 MemPage *pNew; /* Newly allocated page */
danielk19776f235cc2009-06-04 14:46:08 +00006854 int rc; /* Return Code */
6855 Pgno pgnoNew; /* Page number of pNew */
danielk1977ac245ec2005-01-14 13:50:11 +00006856
drh1fee73e2007-08-29 04:00:57 +00006857 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk1977a50d9aa2009-06-08 14:49:45 +00006858 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00006859 assert( pPage->nOverflow==1 );
6860
drh5d433ce2010-08-14 16:02:52 +00006861 /* This error condition is now caught prior to reaching this function */
drh1fd2d7d2014-12-02 16:16:47 +00006862 if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
drhd677b3d2007-08-20 22:48:41 +00006863
danielk1977a50d9aa2009-06-08 14:49:45 +00006864 /* Allocate a new page. This page will become the right-sibling of
6865 ** pPage. Make the parent page writable, so that the new divider cell
6866 ** may be inserted. If both these operations are successful, proceed.
6867 */
drh4f0c5872007-03-26 22:05:01 +00006868 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk19774dbaa892009-06-16 16:50:22 +00006869
danielk1977eaa06f62008-09-18 17:34:44 +00006870 if( rc==SQLITE_OK ){
danielk1977a50d9aa2009-06-08 14:49:45 +00006871
6872 u8 *pOut = &pSpace[4];
drh2cbd78b2012-02-02 19:37:18 +00006873 u8 *pCell = pPage->apOvfl[0];
drh25ada072015-06-19 15:07:14 +00006874 u16 szCell = pPage->xCellSize(pPage, pCell);
danielk19776f235cc2009-06-04 14:46:08 +00006875 u8 *pStop;
6876
drhc5053fb2008-11-27 02:22:10 +00006877 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00006878 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
6879 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
drh658873b2015-06-22 20:02:04 +00006880 rc = rebuildPage(pNew, 1, &pCell, &szCell);
drhea82b372015-06-23 21:35:28 +00006881 if( NEVER(rc) ) return rc;
dan8e9ba0c2014-10-14 17:27:04 +00006882 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
danielk19774dbaa892009-06-16 16:50:22 +00006883
6884 /* If this is an auto-vacuum database, update the pointer map
6885 ** with entries for the new page, and any pointer from the
6886 ** cell on the page to an overflow page. If either of these
6887 ** operations fails, the return code is set, but the contents
6888 ** of the parent page are still manipulated by thh code below.
6889 ** That is Ok, at this point the parent page is guaranteed to
6890 ** be marked as dirty. Returning an error code will cause a
6891 ** rollback, undoing any changes made to the parent page.
6892 */
6893 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00006894 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
6895 if( szCell>pNew->minLocal ){
6896 ptrmapPutOvflPtr(pNew, pCell, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006897 }
6898 }
danielk1977eaa06f62008-09-18 17:34:44 +00006899
danielk19776f235cc2009-06-04 14:46:08 +00006900 /* Create a divider cell to insert into pParent. The divider cell
6901 ** consists of a 4-byte page number (the page number of pPage) and
6902 ** a variable length key value (which must be the same value as the
6903 ** largest key on pPage).
danielk1977eaa06f62008-09-18 17:34:44 +00006904 **
danielk19776f235cc2009-06-04 14:46:08 +00006905 ** To find the largest key value on pPage, first find the right-most
6906 ** cell on pPage. The first two fields of this cell are the
6907 ** record-length (a variable length integer at most 32-bits in size)
6908 ** and the key value (a variable length integer, may have any value).
6909 ** The first of the while(...) loops below skips over the record-length
6910 ** field. The second while(...) loop copies the key value from the
danielk1977a50d9aa2009-06-08 14:49:45 +00006911 ** cell on pPage into the pSpace buffer.
danielk1977eaa06f62008-09-18 17:34:44 +00006912 */
danielk1977eaa06f62008-09-18 17:34:44 +00006913 pCell = findCell(pPage, pPage->nCell-1);
danielk19776f235cc2009-06-04 14:46:08 +00006914 pStop = &pCell[9];
6915 while( (*(pCell++)&0x80) && pCell<pStop );
6916 pStop = &pCell[9];
6917 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
6918
danielk19774dbaa892009-06-16 16:50:22 +00006919 /* Insert the new divider cell into pParent. */
drhcb89f4a2016-05-21 11:23:26 +00006920 if( rc==SQLITE_OK ){
6921 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
6922 0, pPage->pgno, &rc);
6923 }
danielk19776f235cc2009-06-04 14:46:08 +00006924
6925 /* Set the right-child pointer of pParent to point to the new page. */
danielk1977eaa06f62008-09-18 17:34:44 +00006926 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
6927
danielk1977e08a3c42008-09-18 18:17:03 +00006928 /* Release the reference to the new page. */
6929 releasePage(pNew);
danielk1977ac11ee62005-01-15 12:45:51 +00006930 }
6931
danielk1977eaa06f62008-09-18 17:34:44 +00006932 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00006933}
drh615ae552005-01-16 23:21:00 +00006934#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00006935
danielk19774dbaa892009-06-16 16:50:22 +00006936#if 0
drhc3b70572003-01-04 19:44:07 +00006937/*
danielk19774dbaa892009-06-16 16:50:22 +00006938** This function does not contribute anything to the operation of SQLite.
6939** it is sometimes activated temporarily while debugging code responsible
6940** for setting pointer-map entries.
6941*/
6942static int ptrmapCheckPages(MemPage **apPage, int nPage){
6943 int i, j;
6944 for(i=0; i<nPage; i++){
6945 Pgno n;
6946 u8 e;
6947 MemPage *pPage = apPage[i];
6948 BtShared *pBt = pPage->pBt;
6949 assert( pPage->isInit );
6950
6951 for(j=0; j<pPage->nCell; j++){
6952 CellInfo info;
6953 u8 *z;
6954
6955 z = findCell(pPage, j);
drh5fa60512015-06-19 17:19:34 +00006956 pPage->xParseCell(pPage, z, &info);
drh45ac1c72015-12-18 03:59:16 +00006957 if( info.nLocal<info.nPayload ){
6958 Pgno ovfl = get4byte(&z[info.nSize-4]);
danielk19774dbaa892009-06-16 16:50:22 +00006959 ptrmapGet(pBt, ovfl, &e, &n);
6960 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
6961 }
6962 if( !pPage->leaf ){
6963 Pgno child = get4byte(z);
6964 ptrmapGet(pBt, child, &e, &n);
6965 assert( n==pPage->pgno && e==PTRMAP_BTREE );
6966 }
6967 }
6968 if( !pPage->leaf ){
6969 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
6970 ptrmapGet(pBt, child, &e, &n);
6971 assert( n==pPage->pgno && e==PTRMAP_BTREE );
6972 }
6973 }
6974 return 1;
6975}
6976#endif
6977
danielk1977cd581a72009-06-23 15:43:39 +00006978/*
6979** This function is used to copy the contents of the b-tree node stored
6980** on page pFrom to page pTo. If page pFrom was not a leaf page, then
6981** the pointer-map entries for each child page are updated so that the
6982** parent page stored in the pointer map is page pTo. If pFrom contained
6983** any cells with overflow page pointers, then the corresponding pointer
6984** map entries are also updated so that the parent page is page pTo.
6985**
6986** If pFrom is currently carrying any overflow cells (entries in the
drh2cbd78b2012-02-02 19:37:18 +00006987** MemPage.apOvfl[] array), they are not copied to pTo.
danielk1977cd581a72009-06-23 15:43:39 +00006988**
danielk197730548662009-07-09 05:07:37 +00006989** Before returning, page pTo is reinitialized using btreeInitPage().
danielk1977cd581a72009-06-23 15:43:39 +00006990**
6991** The performance of this function is not critical. It is only used by
6992** the balance_shallower() and balance_deeper() procedures, neither of
6993** which are called often under normal circumstances.
6994*/
drhc314dc72009-07-21 11:52:34 +00006995static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
6996 if( (*pRC)==SQLITE_OK ){
6997 BtShared * const pBt = pFrom->pBt;
6998 u8 * const aFrom = pFrom->aData;
6999 u8 * const aTo = pTo->aData;
7000 int const iFromHdr = pFrom->hdrOffset;
7001 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
drhdc9b5f82009-12-05 18:34:08 +00007002 int rc;
drhc314dc72009-07-21 11:52:34 +00007003 int iData;
7004
7005
7006 assert( pFrom->isInit );
7007 assert( pFrom->nFree>=iToHdr );
drhfcd71b62011-04-05 22:08:24 +00007008 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
drhc314dc72009-07-21 11:52:34 +00007009
7010 /* Copy the b-tree node content from page pFrom to page pTo. */
7011 iData = get2byte(&aFrom[iFromHdr+5]);
7012 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
7013 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
7014
7015 /* Reinitialize page pTo so that the contents of the MemPage structure
dan89e060e2009-12-05 18:03:50 +00007016 ** match the new data. The initialization of pTo can actually fail under
7017 ** fairly obscure circumstances, even though it is a copy of initialized
7018 ** page pFrom.
7019 */
drhc314dc72009-07-21 11:52:34 +00007020 pTo->isInit = 0;
dan89e060e2009-12-05 18:03:50 +00007021 rc = btreeInitPage(pTo);
7022 if( rc!=SQLITE_OK ){
7023 *pRC = rc;
7024 return;
7025 }
drhc314dc72009-07-21 11:52:34 +00007026
7027 /* If this is an auto-vacuum database, update the pointer-map entries
7028 ** for any b-tree or overflow pages that pTo now contains the pointers to.
7029 */
7030 if( ISAUTOVACUUM ){
7031 *pRC = setChildPtrmaps(pTo);
7032 }
danielk1977cd581a72009-06-23 15:43:39 +00007033 }
danielk1977cd581a72009-06-23 15:43:39 +00007034}
7035
7036/*
danielk19774dbaa892009-06-16 16:50:22 +00007037** This routine redistributes cells on the iParentIdx'th child of pParent
7038** (hereafter "the page") and up to 2 siblings so that all pages have about the
7039** same amount of free space. Usually a single sibling on either side of the
7040** page are used in the balancing, though both siblings might come from one
7041** side if the page is the first or last child of its parent. If the page
7042** has fewer than 2 siblings (something which can only happen if the page
7043** is a root page or a child of a root page) then all available siblings
7044** participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00007045**
danielk19774dbaa892009-06-16 16:50:22 +00007046** The number of siblings of the page might be increased or decreased by
7047** one or two in an effort to keep pages nearly full but not over full.
drh14acc042001-06-10 19:56:58 +00007048**
danielk19774dbaa892009-06-16 16:50:22 +00007049** Note that when this routine is called, some of the cells on the page
7050** might not actually be stored in MemPage.aData[]. This can happen
7051** if the page is overfull. This routine ensures that all cells allocated
7052** to the page and its siblings fit into MemPage.aData[] before returning.
drh14acc042001-06-10 19:56:58 +00007053**
danielk19774dbaa892009-06-16 16:50:22 +00007054** In the course of balancing the page and its siblings, cells may be
7055** inserted into or removed from the parent page (pParent). Doing so
7056** may cause the parent page to become overfull or underfull. If this
7057** happens, it is the responsibility of the caller to invoke the correct
7058** balancing routine to fix this problem (see the balance() routine).
drh8c42ca92001-06-22 19:15:00 +00007059**
drh5e00f6c2001-09-13 13:46:56 +00007060** If this routine fails for any reason, it might leave the database
danielk19776067a9b2009-06-09 09:41:00 +00007061** in a corrupted state. So if this routine fails, the database should
drh5e00f6c2001-09-13 13:46:56 +00007062** be rolled back.
danielk19774dbaa892009-06-16 16:50:22 +00007063**
7064** The third argument to this function, aOvflSpace, is a pointer to a
drhcd09c532009-07-20 19:30:00 +00007065** buffer big enough to hold one page. If while inserting cells into the parent
7066** page (pParent) the parent page becomes overfull, this buffer is
7067** used to store the parent's overflow cells. Because this function inserts
danielk19774dbaa892009-06-16 16:50:22 +00007068** a maximum of four divider cells into the parent page, and the maximum
7069** size of a cell stored within an internal node is always less than 1/4
7070** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
7071** enough for all overflow cells.
7072**
7073** If aOvflSpace is set to a null pointer, this function returns
7074** SQLITE_NOMEM.
drh8b2f49b2001-06-08 00:21:52 +00007075*/
danielk19774dbaa892009-06-16 16:50:22 +00007076static int balance_nonroot(
7077 MemPage *pParent, /* Parent page of siblings being balanced */
7078 int iParentIdx, /* Index of "the page" in pParent */
danielk1977cd581a72009-06-23 15:43:39 +00007079 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
dan428c2182012-08-06 18:50:11 +00007080 int isRoot, /* True if pParent is a root-page */
7081 int bBulk /* True if this call is part of a bulk load */
danielk19774dbaa892009-06-16 16:50:22 +00007082){
drh16a9b832007-05-05 18:39:25 +00007083 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00007084 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
danielk1977a4124bd2008-12-23 10:37:47 +00007085 int nNew = 0; /* Number of pages in apNew[] */
danielk19774dbaa892009-06-16 16:50:22 +00007086 int nOld; /* Number of pages in apOld[] */
drh14acc042001-06-10 19:56:58 +00007087 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00007088 int nxDiv; /* Next divider slot in pParent->aCell[] */
shane85095702009-06-15 16:27:08 +00007089 int rc = SQLITE_OK; /* The return code */
shane36840fd2009-06-26 16:32:13 +00007090 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00007091 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00007092 int usableSpace; /* Bytes in pPage beyond the header */
7093 int pageFlags; /* Value of pPage->aData[0] */
drhe5ae5732008-06-15 02:51:47 +00007094 int iSpace1 = 0; /* First unused byte of aSpace1[] */
danielk19776067a9b2009-06-09 09:41:00 +00007095 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
drhfacf0302008-06-17 15:12:00 +00007096 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00007097 MemPage *apOld[NB]; /* pPage and up to two siblings */
drha2fce642004-06-05 00:01:44 +00007098 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
danielk19774dbaa892009-06-16 16:50:22 +00007099 u8 *pRight; /* Location in parent of right-sibling pointer */
7100 u8 *apDiv[NB-1]; /* Divider cells in pParent */
drh1ffd2472015-06-23 02:37:30 +00007101 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
7102 int cntOld[NB+2]; /* Old index in b.apCell[] */
drh2a0df922014-10-30 23:14:56 +00007103 int szNew[NB+2]; /* Combined size of cells placed on i-th page */
danielk19774dbaa892009-06-16 16:50:22 +00007104 u8 *aSpace1; /* Space for copies of dividers cells */
7105 Pgno pgno; /* Temp var to store a page number in */
dane6593d82014-10-24 16:40:49 +00007106 u8 abDone[NB+2]; /* True after i'th new page is populated */
7107 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
drh00fe08a2014-10-31 00:05:23 +00007108 Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
dane6593d82014-10-24 16:40:49 +00007109 u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
drh1ffd2472015-06-23 02:37:30 +00007110 CellArray b; /* Parsed information on cells being balanced */
drh8b2f49b2001-06-08 00:21:52 +00007111
dan33ea4862014-10-09 19:35:37 +00007112 memset(abDone, 0, sizeof(abDone));
drh1ffd2472015-06-23 02:37:30 +00007113 b.nCell = 0;
7114 b.apCell = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00007115 pBt = pParent->pBt;
7116 assert( sqlite3_mutex_held(pBt->mutex) );
7117 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977474b7cc2008-07-09 11:49:46 +00007118
danielk1977e5765212009-06-17 11:13:28 +00007119#if 0
drh43605152004-05-29 21:46:49 +00007120 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
danielk1977e5765212009-06-17 11:13:28 +00007121#endif
drh2e38c322004-09-03 18:38:44 +00007122
danielk19774dbaa892009-06-16 16:50:22 +00007123 /* At this point pParent may have at most one overflow cell. And if
7124 ** this overflow cell is present, it must be the cell with
7125 ** index iParentIdx. This scenario comes about when this function
drhcd09c532009-07-20 19:30:00 +00007126 ** is called (indirectly) from sqlite3BtreeDelete().
7127 */
danielk19774dbaa892009-06-16 16:50:22 +00007128 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
drh2cbd78b2012-02-02 19:37:18 +00007129 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
danielk19774dbaa892009-06-16 16:50:22 +00007130
danielk197711a8a862009-06-17 11:49:52 +00007131 if( !aOvflSpace ){
mistachkinfad30392016-02-13 23:43:46 +00007132 return SQLITE_NOMEM_BKPT;
danielk197711a8a862009-06-17 11:49:52 +00007133 }
7134
danielk1977a50d9aa2009-06-08 14:49:45 +00007135 /* Find the sibling pages to balance. Also locate the cells in pParent
7136 ** that divide the siblings. An attempt is made to find NN siblings on
7137 ** either side of pPage. More siblings are taken from one side, however,
7138 ** if there are fewer than NN siblings on the other side. If pParent
danielk19774dbaa892009-06-16 16:50:22 +00007139 ** has NB or fewer children then all children of pParent are taken.
7140 **
7141 ** This loop also drops the divider cells from the parent page. This
7142 ** way, the remainder of the function does not have to deal with any
drhcd09c532009-07-20 19:30:00 +00007143 ** overflow cells in the parent page, since if any existed they will
7144 ** have already been removed.
7145 */
danielk19774dbaa892009-06-16 16:50:22 +00007146 i = pParent->nOverflow + pParent->nCell;
7147 if( i<2 ){
drhc3b70572003-01-04 19:44:07 +00007148 nxDiv = 0;
danielk19774dbaa892009-06-16 16:50:22 +00007149 }else{
dan7d6885a2012-08-08 14:04:56 +00007150 assert( bBulk==0 || bBulk==1 );
danielk19774dbaa892009-06-16 16:50:22 +00007151 if( iParentIdx==0 ){
7152 nxDiv = 0;
7153 }else if( iParentIdx==i ){
dan7d6885a2012-08-08 14:04:56 +00007154 nxDiv = i-2+bBulk;
drh14acc042001-06-10 19:56:58 +00007155 }else{
danielk19774dbaa892009-06-16 16:50:22 +00007156 nxDiv = iParentIdx-1;
drh8b2f49b2001-06-08 00:21:52 +00007157 }
dan7d6885a2012-08-08 14:04:56 +00007158 i = 2-bBulk;
danielk19774dbaa892009-06-16 16:50:22 +00007159 }
dan7d6885a2012-08-08 14:04:56 +00007160 nOld = i+1;
danielk19774dbaa892009-06-16 16:50:22 +00007161 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
7162 pRight = &pParent->aData[pParent->hdrOffset+8];
7163 }else{
7164 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
7165 }
7166 pgno = get4byte(pRight);
7167 while( 1 ){
drh28f58dd2015-06-27 19:45:03 +00007168 rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
danielk19774dbaa892009-06-16 16:50:22 +00007169 if( rc ){
danielk197789bc4bc2009-07-21 19:25:24 +00007170 memset(apOld, 0, (i+1)*sizeof(MemPage*));
danielk19774dbaa892009-06-16 16:50:22 +00007171 goto balance_cleanup;
7172 }
danielk1977634f2982005-03-28 08:44:07 +00007173 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
danielk19774dbaa892009-06-16 16:50:22 +00007174 if( (i--)==0 ) break;
7175
drh9cc5b4e2016-12-26 01:41:33 +00007176 if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
drh2cbd78b2012-02-02 19:37:18 +00007177 apDiv[i] = pParent->apOvfl[0];
danielk19774dbaa892009-06-16 16:50:22 +00007178 pgno = get4byte(apDiv[i]);
drh25ada072015-06-19 15:07:14 +00007179 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
danielk19774dbaa892009-06-16 16:50:22 +00007180 pParent->nOverflow = 0;
7181 }else{
7182 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
7183 pgno = get4byte(apDiv[i]);
drh25ada072015-06-19 15:07:14 +00007184 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
danielk19774dbaa892009-06-16 16:50:22 +00007185
7186 /* Drop the cell from the parent page. apDiv[i] still points to
7187 ** the cell within the parent, even though it has been dropped.
7188 ** This is safe because dropping a cell only overwrites the first
7189 ** four bytes of it, and this function does not need the first
7190 ** four bytes of the divider cell. So the pointer is safe to use
danielk197711a8a862009-06-17 11:49:52 +00007191 ** later on.
7192 **
drh8a575d92011-10-12 17:00:28 +00007193 ** But not if we are in secure-delete mode. In secure-delete mode,
danielk197711a8a862009-06-17 11:49:52 +00007194 ** the dropCell() routine will overwrite the entire cell with zeroes.
7195 ** In this case, temporarily copy the cell into the aOvflSpace[]
7196 ** buffer. It will be copied out again as soon as the aSpace[] buffer
7197 ** is allocated. */
drhc9166342012-01-05 23:32:06 +00007198 if( pBt->btsFlags & BTS_SECURE_DELETE ){
drh8a575d92011-10-12 17:00:28 +00007199 int iOff;
7200
7201 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
drh43b18e12010-08-17 19:40:08 +00007202 if( (iOff+szNew[i])>(int)pBt->usableSize ){
dan2ed11e72010-02-26 15:09:19 +00007203 rc = SQLITE_CORRUPT_BKPT;
7204 memset(apOld, 0, (i+1)*sizeof(MemPage*));
7205 goto balance_cleanup;
7206 }else{
7207 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
7208 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
7209 }
drh5b47efa2010-02-12 18:18:39 +00007210 }
drh98add2e2009-07-20 17:11:49 +00007211 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
danielk19774dbaa892009-06-16 16:50:22 +00007212 }
drh8b2f49b2001-06-08 00:21:52 +00007213 }
7214
drha9121e42008-02-19 14:59:35 +00007215 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00007216 ** alignment */
drha9121e42008-02-19 14:59:35 +00007217 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00007218
drh8b2f49b2001-06-08 00:21:52 +00007219 /*
danielk1977634f2982005-03-28 08:44:07 +00007220 ** Allocate space for memory structures
7221 */
drhfacf0302008-06-17 15:12:00 +00007222 szScratch =
drh1ffd2472015-06-23 02:37:30 +00007223 nMaxCells*sizeof(u8*) /* b.apCell */
7224 + nMaxCells*sizeof(u16) /* b.szCell */
dan33ea4862014-10-09 19:35:37 +00007225 + pBt->pageSize; /* aSpace1 */
drh5279d342014-11-04 13:41:32 +00007226
drhcbd55b02014-11-04 14:22:27 +00007227 /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
7228 ** that is more than 6 times the database page size. */
mistachkin0fbd7352014-12-09 04:26:56 +00007229 assert( szScratch<=6*(int)pBt->pageSize );
drh1ffd2472015-06-23 02:37:30 +00007230 b.apCell = sqlite3ScratchMalloc( szScratch );
7231 if( b.apCell==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007232 rc = SQLITE_NOMEM_BKPT;
danielk1977634f2982005-03-28 08:44:07 +00007233 goto balance_cleanup;
7234 }
drh1ffd2472015-06-23 02:37:30 +00007235 b.szCell = (u16*)&b.apCell[nMaxCells];
7236 aSpace1 = (u8*)&b.szCell[nMaxCells];
drhea598cb2009-04-05 12:22:08 +00007237 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
drh14acc042001-06-10 19:56:58 +00007238
7239 /*
7240 ** Load pointers to all cells on sibling pages and the divider cells
drh1ffd2472015-06-23 02:37:30 +00007241 ** into the local b.apCell[] array. Make copies of the divider cells
dan33ea4862014-10-09 19:35:37 +00007242 ** into space obtained from aSpace1[]. The divider cells have already
7243 ** been removed from pParent.
drh4b70f112004-05-02 21:12:19 +00007244 **
7245 ** If the siblings are on leaf pages, then the child pointers of the
7246 ** divider cells are stripped from the cells before they are copied
drh1ffd2472015-06-23 02:37:30 +00007247 ** into aSpace1[]. In this way, all cells in b.apCell[] are without
drh4b70f112004-05-02 21:12:19 +00007248 ** child pointers. If siblings are not leaves, then all cell in
drh1ffd2472015-06-23 02:37:30 +00007249 ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
drh4b70f112004-05-02 21:12:19 +00007250 ** are alike.
drh96f5b762004-05-16 16:24:36 +00007251 **
7252 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
7253 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00007254 */
drh1ffd2472015-06-23 02:37:30 +00007255 b.pRef = apOld[0];
7256 leafCorrection = b.pRef->leaf*4;
7257 leafData = b.pRef->intKeyLeaf;
drh8b2f49b2001-06-08 00:21:52 +00007258 for(i=0; i<nOld; i++){
dan33ea4862014-10-09 19:35:37 +00007259 MemPage *pOld = apOld[i];
drh4edfdd32015-06-23 14:49:42 +00007260 int limit = pOld->nCell;
7261 u8 *aData = pOld->aData;
7262 u16 maskPage = pOld->maskPage;
drh4f4bf772015-06-23 17:09:53 +00007263 u8 *piCell = aData + pOld->cellOffset;
drhfe647dc2015-06-23 18:24:25 +00007264 u8 *piEnd;
danielk19774dbaa892009-06-16 16:50:22 +00007265
drh73d340a2015-05-28 11:23:11 +00007266 /* Verify that all sibling pages are of the same "type" (table-leaf,
7267 ** table-interior, index-leaf, or index-interior).
7268 */
7269 if( pOld->aData[0]!=apOld[0]->aData[0] ){
7270 rc = SQLITE_CORRUPT_BKPT;
7271 goto balance_cleanup;
7272 }
7273
drhfe647dc2015-06-23 18:24:25 +00007274 /* Load b.apCell[] with pointers to all cells in pOld. If pOld
7275 ** constains overflow cells, include them in the b.apCell[] array
7276 ** in the correct spot.
7277 **
7278 ** Note that when there are multiple overflow cells, it is always the
7279 ** case that they are sequential and adjacent. This invariant arises
7280 ** because multiple overflows can only occurs when inserting divider
7281 ** cells into a parent on a prior balance, and divider cells are always
7282 ** adjacent and are inserted in order. There is an assert() tagged
7283 ** with "NOTE 1" in the overflow cell insertion loop to prove this
7284 ** invariant.
drh4edfdd32015-06-23 14:49:42 +00007285 **
7286 ** This must be done in advance. Once the balance starts, the cell
7287 ** offset section of the btree page will be overwritten and we will no
7288 ** long be able to find the cells if a pointer to each cell is not saved
7289 ** first.
7290 */
drh36b78ee2016-01-20 01:32:00 +00007291 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
drh68f2a572011-06-03 17:50:49 +00007292 if( pOld->nOverflow>0 ){
drhfe647dc2015-06-23 18:24:25 +00007293 limit = pOld->aiOvfl[0];
drh68f2a572011-06-03 17:50:49 +00007294 for(j=0; j<limit; j++){
drh329428e2015-06-30 13:28:18 +00007295 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
drhfe647dc2015-06-23 18:24:25 +00007296 piCell += 2;
7297 b.nCell++;
drh68f2a572011-06-03 17:50:49 +00007298 }
drhfe647dc2015-06-23 18:24:25 +00007299 for(k=0; k<pOld->nOverflow; k++){
7300 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
drh4edfdd32015-06-23 14:49:42 +00007301 b.apCell[b.nCell] = pOld->apOvfl[k];
drh1ffd2472015-06-23 02:37:30 +00007302 b.nCell++;
drh68f2a572011-06-03 17:50:49 +00007303 }
drh1ffd2472015-06-23 02:37:30 +00007304 }
drhfe647dc2015-06-23 18:24:25 +00007305 piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
7306 while( piCell<piEnd ){
drh4edfdd32015-06-23 14:49:42 +00007307 assert( b.nCell<nMaxCells );
drh329428e2015-06-30 13:28:18 +00007308 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
drh4f4bf772015-06-23 17:09:53 +00007309 piCell += 2;
drh4edfdd32015-06-23 14:49:42 +00007310 b.nCell++;
drh4edfdd32015-06-23 14:49:42 +00007311 }
7312
drh1ffd2472015-06-23 02:37:30 +00007313 cntOld[i] = b.nCell;
danielk19774dbaa892009-06-16 16:50:22 +00007314 if( i<nOld-1 && !leafData){
shane36840fd2009-06-26 16:32:13 +00007315 u16 sz = (u16)szNew[i];
danielk19774dbaa892009-06-16 16:50:22 +00007316 u8 *pTemp;
drh1ffd2472015-06-23 02:37:30 +00007317 assert( b.nCell<nMaxCells );
7318 b.szCell[b.nCell] = sz;
danielk19774dbaa892009-06-16 16:50:22 +00007319 pTemp = &aSpace1[iSpace1];
7320 iSpace1 += sz;
drhe22e03e2010-08-18 21:19:03 +00007321 assert( sz<=pBt->maxLocal+23 );
drhfcd71b62011-04-05 22:08:24 +00007322 assert( iSpace1 <= (int)pBt->pageSize );
danielk19774dbaa892009-06-16 16:50:22 +00007323 memcpy(pTemp, apDiv[i], sz);
drh1ffd2472015-06-23 02:37:30 +00007324 b.apCell[b.nCell] = pTemp+leafCorrection;
danielk19774dbaa892009-06-16 16:50:22 +00007325 assert( leafCorrection==0 || leafCorrection==4 );
drh1ffd2472015-06-23 02:37:30 +00007326 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
danielk19774dbaa892009-06-16 16:50:22 +00007327 if( !pOld->leaf ){
7328 assert( leafCorrection==0 );
7329 assert( pOld->hdrOffset==0 );
7330 /* The right pointer of the child page pOld becomes the left
7331 ** pointer of the divider cell */
drh1ffd2472015-06-23 02:37:30 +00007332 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
danielk19774dbaa892009-06-16 16:50:22 +00007333 }else{
7334 assert( leafCorrection==4 );
drh1ffd2472015-06-23 02:37:30 +00007335 while( b.szCell[b.nCell]<4 ){
dan8f1eb8a2014-12-06 14:56:49 +00007336 /* Do not allow any cells smaller than 4 bytes. If a smaller cell
7337 ** does exist, pad it with 0x00 bytes. */
drh1ffd2472015-06-23 02:37:30 +00007338 assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
7339 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
danee7172f2014-12-24 18:11:50 +00007340 aSpace1[iSpace1++] = 0x00;
drh1ffd2472015-06-23 02:37:30 +00007341 b.szCell[b.nCell]++;
danielk1977ac11ee62005-01-15 12:45:51 +00007342 }
7343 }
drh1ffd2472015-06-23 02:37:30 +00007344 b.nCell++;
drh8b2f49b2001-06-08 00:21:52 +00007345 }
drh8b2f49b2001-06-08 00:21:52 +00007346 }
7347
7348 /*
drh1ffd2472015-06-23 02:37:30 +00007349 ** Figure out the number of pages needed to hold all b.nCell cells.
drh6019e162001-07-02 17:51:45 +00007350 ** Store this number in "k". Also compute szNew[] which is the total
7351 ** size of all cells on the i-th page and cntNew[] which is the index
drh1ffd2472015-06-23 02:37:30 +00007352 ** in b.apCell[] of the cell that divides page i from page i+1.
7353 ** cntNew[k] should equal b.nCell.
drh6019e162001-07-02 17:51:45 +00007354 **
drh96f5b762004-05-16 16:24:36 +00007355 ** Values computed by this block:
7356 **
7357 ** k: The total number of sibling pages
7358 ** szNew[i]: Spaced used on the i-th sibling page.
drh1ffd2472015-06-23 02:37:30 +00007359 ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
drh96f5b762004-05-16 16:24:36 +00007360 ** the right of the i-th sibling page.
7361 ** usableSpace: Number of bytes of space available on each sibling.
7362 **
drh8b2f49b2001-06-08 00:21:52 +00007363 */
drh43605152004-05-29 21:46:49 +00007364 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh658873b2015-06-22 20:02:04 +00007365 for(i=0; i<nOld; i++){
7366 MemPage *p = apOld[i];
7367 szNew[i] = usableSpace - p->nFree;
drh658873b2015-06-22 20:02:04 +00007368 for(j=0; j<p->nOverflow; j++){
7369 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
7370 }
7371 cntNew[i] = cntOld[i];
7372 }
7373 k = nOld;
7374 for(i=0; i<k; i++){
7375 int sz;
7376 while( szNew[i]>usableSpace ){
7377 if( i+1>=k ){
7378 k = i+2;
7379 if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
7380 szNew[k-1] = 0;
drh1ffd2472015-06-23 02:37:30 +00007381 cntNew[k-1] = b.nCell;
drh658873b2015-06-22 20:02:04 +00007382 }
drh1ffd2472015-06-23 02:37:30 +00007383 sz = 2 + cachedCellSize(&b, cntNew[i]-1);
drh658873b2015-06-22 20:02:04 +00007384 szNew[i] -= sz;
7385 if( !leafData ){
drh1ffd2472015-06-23 02:37:30 +00007386 if( cntNew[i]<b.nCell ){
7387 sz = 2 + cachedCellSize(&b, cntNew[i]);
7388 }else{
7389 sz = 0;
7390 }
drh658873b2015-06-22 20:02:04 +00007391 }
7392 szNew[i+1] += sz;
7393 cntNew[i]--;
7394 }
drh1ffd2472015-06-23 02:37:30 +00007395 while( cntNew[i]<b.nCell ){
7396 sz = 2 + cachedCellSize(&b, cntNew[i]);
drh658873b2015-06-22 20:02:04 +00007397 if( szNew[i]+sz>usableSpace ) break;
7398 szNew[i] += sz;
7399 cntNew[i]++;
7400 if( !leafData ){
drh1ffd2472015-06-23 02:37:30 +00007401 if( cntNew[i]<b.nCell ){
7402 sz = 2 + cachedCellSize(&b, cntNew[i]);
7403 }else{
7404 sz = 0;
7405 }
drh658873b2015-06-22 20:02:04 +00007406 }
7407 szNew[i+1] -= sz;
7408 }
drh1ffd2472015-06-23 02:37:30 +00007409 if( cntNew[i]>=b.nCell ){
drh658873b2015-06-22 20:02:04 +00007410 k = i+1;
drh672073a2015-06-24 12:07:40 +00007411 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
drh658873b2015-06-22 20:02:04 +00007412 rc = SQLITE_CORRUPT_BKPT;
7413 goto balance_cleanup;
drh6019e162001-07-02 17:51:45 +00007414 }
7415 }
drh96f5b762004-05-16 16:24:36 +00007416
7417 /*
7418 ** The packing computed by the previous block is biased toward the siblings
drh2a0df922014-10-30 23:14:56 +00007419 ** on the left side (siblings with smaller keys). The left siblings are
7420 ** always nearly full, while the right-most sibling might be nearly empty.
7421 ** The next block of code attempts to adjust the packing of siblings to
7422 ** get a better balance.
drh96f5b762004-05-16 16:24:36 +00007423 **
7424 ** This adjustment is more than an optimization. The packing above might
7425 ** be so out of balance as to be illegal. For example, the right-most
7426 ** sibling might be completely empty. This adjustment is not optional.
7427 */
drh6019e162001-07-02 17:51:45 +00007428 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00007429 int szRight = szNew[i]; /* Size of sibling on the right */
7430 int szLeft = szNew[i-1]; /* Size of sibling on the left */
7431 int r; /* Index of right-most cell in left sibling */
7432 int d; /* Index of first cell to the left of right sibling */
7433
7434 r = cntNew[i-1] - 1;
7435 d = r + 1 - leafData;
drh008d64c2015-06-23 16:00:24 +00007436 (void)cachedCellSize(&b, d);
drh672073a2015-06-24 12:07:40 +00007437 do{
drh1ffd2472015-06-23 02:37:30 +00007438 assert( d<nMaxCells );
7439 assert( r<nMaxCells );
drh1ffd2472015-06-23 02:37:30 +00007440 (void)cachedCellSize(&b, r);
7441 if( szRight!=0
drh0b4c0422016-07-14 19:48:08 +00007442 && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
drh1ffd2472015-06-23 02:37:30 +00007443 break;
7444 }
7445 szRight += b.szCell[d] + 2;
7446 szLeft -= b.szCell[r] + 2;
drh008d64c2015-06-23 16:00:24 +00007447 cntNew[i-1] = r;
drh008d64c2015-06-23 16:00:24 +00007448 r--;
7449 d--;
drh672073a2015-06-24 12:07:40 +00007450 }while( r>=0 );
drh96f5b762004-05-16 16:24:36 +00007451 szNew[i] = szRight;
7452 szNew[i-1] = szLeft;
drh672073a2015-06-24 12:07:40 +00007453 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
7454 rc = SQLITE_CORRUPT_BKPT;
7455 goto balance_cleanup;
7456 }
drh6019e162001-07-02 17:51:45 +00007457 }
drh09d0deb2005-08-02 17:13:09 +00007458
drh2a0df922014-10-30 23:14:56 +00007459 /* Sanity check: For a non-corrupt database file one of the follwing
7460 ** must be true:
7461 ** (1) We found one or more cells (cntNew[0])>0), or
7462 ** (2) pPage is a virtual root page. A virtual root page is when
7463 ** the real root page is page 1 and we are the only child of
7464 ** that page.
drh09d0deb2005-08-02 17:13:09 +00007465 */
drh2a0df922014-10-30 23:14:56 +00007466 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
dan33ea4862014-10-09 19:35:37 +00007467 TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
7468 apOld[0]->pgno, apOld[0]->nCell,
7469 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
7470 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
danielk1977e5765212009-06-17 11:13:28 +00007471 ));
7472
drh8b2f49b2001-06-08 00:21:52 +00007473 /*
drh6b308672002-07-08 02:16:37 +00007474 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00007475 */
danielk1977a50d9aa2009-06-08 14:49:45 +00007476 pageFlags = apOld[0]->aData[0];
drh14acc042001-06-10 19:56:58 +00007477 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00007478 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00007479 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00007480 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00007481 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00007482 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00007483 nNew++;
danielk197728129562005-01-11 10:25:06 +00007484 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00007485 }else{
drh7aa8f852006-03-28 00:24:44 +00007486 assert( i>0 );
dan428c2182012-08-06 18:50:11 +00007487 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
drh6b308672002-07-08 02:16:37 +00007488 if( rc ) goto balance_cleanup;
dan33ea4862014-10-09 19:35:37 +00007489 zeroPage(pNew, pageFlags);
drhda200cc2004-05-09 11:51:38 +00007490 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00007491 nNew++;
drh1ffd2472015-06-23 02:37:30 +00007492 cntOld[i] = b.nCell;
danielk19774dbaa892009-06-16 16:50:22 +00007493
7494 /* Set the pointer-map entry for the new sibling page. */
7495 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00007496 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00007497 if( rc!=SQLITE_OK ){
7498 goto balance_cleanup;
7499 }
7500 }
drh6b308672002-07-08 02:16:37 +00007501 }
drh8b2f49b2001-06-08 00:21:52 +00007502 }
7503
7504 /*
dan33ea4862014-10-09 19:35:37 +00007505 ** Reassign page numbers so that the new pages are in ascending order.
7506 ** This helps to keep entries in the disk file in order so that a scan
7507 ** of the table is closer to a linear scan through the file. That in turn
7508 ** helps the operating system to deliver pages from the disk more rapidly.
drhf9ffac92002-03-02 19:00:31 +00007509 **
dan33ea4862014-10-09 19:35:37 +00007510 ** An O(n^2) insertion sort algorithm is used, but since n is never more
7511 ** than (NB+2) (a small constant), that should not be a problem.
drhf9ffac92002-03-02 19:00:31 +00007512 **
dan33ea4862014-10-09 19:35:37 +00007513 ** When NB==3, this one optimization makes the database about 25% faster
7514 ** for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00007515 */
dan33ea4862014-10-09 19:35:37 +00007516 for(i=0; i<nNew; i++){
drh00fe08a2014-10-31 00:05:23 +00007517 aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
dan33ea4862014-10-09 19:35:37 +00007518 aPgFlags[i] = apNew[i]->pDbPage->flags;
dan89ca0b32014-10-25 20:36:28 +00007519 for(j=0; j<i; j++){
7520 if( aPgno[j]==aPgno[i] ){
7521 /* This branch is taken if the set of sibling pages somehow contains
7522 ** duplicate entries. This can happen if the database is corrupt.
7523 ** It would be simpler to detect this as part of the loop below, but
drhba0f9992014-10-30 20:48:44 +00007524 ** we do the detection here in order to avoid populating the pager
7525 ** cache with two separate objects associated with the same
7526 ** page number. */
dan89ca0b32014-10-25 20:36:28 +00007527 assert( CORRUPT_DB );
7528 rc = SQLITE_CORRUPT_BKPT;
7529 goto balance_cleanup;
drhf9ffac92002-03-02 19:00:31 +00007530 }
7531 }
dan33ea4862014-10-09 19:35:37 +00007532 }
7533 for(i=0; i<nNew; i++){
dan31f4e992014-10-24 20:57:03 +00007534 int iBest = 0; /* aPgno[] index of page number to use */
dan31f4e992014-10-24 20:57:03 +00007535 for(j=1; j<nNew; j++){
drh00fe08a2014-10-31 00:05:23 +00007536 if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
drhf9ffac92002-03-02 19:00:31 +00007537 }
drh00fe08a2014-10-31 00:05:23 +00007538 pgno = aPgOrder[iBest];
7539 aPgOrder[iBest] = 0xffffffff;
dan31f4e992014-10-24 20:57:03 +00007540 if( iBest!=i ){
7541 if( iBest>i ){
7542 sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
7543 }
7544 sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
7545 apNew[i]->pgno = pgno;
drhf9ffac92002-03-02 19:00:31 +00007546 }
7547 }
dan33ea4862014-10-09 19:35:37 +00007548
7549 TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
7550 "%d(%d nc=%d) %d(%d nc=%d)\n",
7551 apNew[0]->pgno, szNew[0], cntNew[0],
danielk19774dbaa892009-06-16 16:50:22 +00007552 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
dan33ea4862014-10-09 19:35:37 +00007553 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
danielk19774dbaa892009-06-16 16:50:22 +00007554 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
dan33ea4862014-10-09 19:35:37 +00007555 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
danielk19774dbaa892009-06-16 16:50:22 +00007556 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
dan33ea4862014-10-09 19:35:37 +00007557 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
7558 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
7559 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
7560 ));
danielk19774dbaa892009-06-16 16:50:22 +00007561
7562 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7563 put4byte(pRight, apNew[nNew-1]->pgno);
drh24cd67e2004-05-10 16:18:47 +00007564
dan33ea4862014-10-09 19:35:37 +00007565 /* If the sibling pages are not leaves, ensure that the right-child pointer
7566 ** of the right-most new sibling page is set to the value that was
7567 ** originally in the same field of the right-most old sibling page. */
7568 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
7569 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
7570 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
7571 }
danielk1977ac11ee62005-01-15 12:45:51 +00007572
dan33ea4862014-10-09 19:35:37 +00007573 /* Make any required updates to pointer map entries associated with
7574 ** cells stored on sibling pages following the balance operation. Pointer
7575 ** map entries associated with divider cells are set by the insertCell()
7576 ** routine. The associated pointer map entries are:
7577 **
7578 ** a) if the cell contains a reference to an overflow chain, the
7579 ** entry associated with the first page in the overflow chain, and
7580 **
7581 ** b) if the sibling pages are not leaves, the child page associated
7582 ** with the cell.
7583 **
7584 ** If the sibling pages are not leaves, then the pointer map entry
7585 ** associated with the right-child of each sibling may also need to be
7586 ** updated. This happens below, after the sibling pages have been
7587 ** populated, not here.
danielk1977ac11ee62005-01-15 12:45:51 +00007588 */
dan33ea4862014-10-09 19:35:37 +00007589 if( ISAUTOVACUUM ){
7590 MemPage *pNew = apNew[0];
7591 u8 *aOld = pNew->aData;
7592 int cntOldNext = pNew->nCell + pNew->nOverflow;
7593 int usableSize = pBt->usableSize;
7594 int iNew = 0;
7595 int iOld = 0;
danielk1977ac11ee62005-01-15 12:45:51 +00007596
drh1ffd2472015-06-23 02:37:30 +00007597 for(i=0; i<b.nCell; i++){
7598 u8 *pCell = b.apCell[i];
dan33ea4862014-10-09 19:35:37 +00007599 if( i==cntOldNext ){
7600 MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
7601 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
7602 aOld = pOld->aData;
drh4b70f112004-05-02 21:12:19 +00007603 }
dan33ea4862014-10-09 19:35:37 +00007604 if( i==cntNew[iNew] ){
7605 pNew = apNew[++iNew];
7606 if( !leafData ) continue;
7607 }
danielk197785d90ca2008-07-19 14:25:15 +00007608
dan33ea4862014-10-09 19:35:37 +00007609 /* Cell pCell is destined for new sibling page pNew. Originally, it
drhba0f9992014-10-30 20:48:44 +00007610 ** was either part of sibling page iOld (possibly an overflow cell),
dan33ea4862014-10-09 19:35:37 +00007611 ** or else the divider cell to the left of sibling page iOld. So,
7612 ** if sibling page iOld had the same page number as pNew, and if
7613 ** pCell really was a part of sibling page iOld (not a divider or
7614 ** overflow cell), we can skip updating the pointer map entries. */
drhd52d52b2014-12-06 02:05:44 +00007615 if( iOld>=nNew
7616 || pNew->pgno!=aPgno[iOld]
drhac536e62015-12-10 15:09:17 +00007617 || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
drhd52d52b2014-12-06 02:05:44 +00007618 ){
dan33ea4862014-10-09 19:35:37 +00007619 if( !leafCorrection ){
7620 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
7621 }
drh1ffd2472015-06-23 02:37:30 +00007622 if( cachedCellSize(&b,i)>pNew->minLocal ){
dan33ea4862014-10-09 19:35:37 +00007623 ptrmapPutOvflPtr(pNew, pCell, &rc);
danielk1977ac11ee62005-01-15 12:45:51 +00007624 }
drhea82b372015-06-23 21:35:28 +00007625 if( rc ) goto balance_cleanup;
drh43605152004-05-29 21:46:49 +00007626 }
drh14acc042001-06-10 19:56:58 +00007627 }
7628 }
dan33ea4862014-10-09 19:35:37 +00007629
7630 /* Insert new divider cells into pParent. */
7631 for(i=0; i<nNew-1; i++){
7632 u8 *pCell;
7633 u8 *pTemp;
7634 int sz;
7635 MemPage *pNew = apNew[i];
7636 j = cntNew[i];
7637
7638 assert( j<nMaxCells );
drh1ffd2472015-06-23 02:37:30 +00007639 assert( b.apCell[j]!=0 );
7640 pCell = b.apCell[j];
7641 sz = b.szCell[j] + leafCorrection;
dan33ea4862014-10-09 19:35:37 +00007642 pTemp = &aOvflSpace[iOvflSpace];
7643 if( !pNew->leaf ){
7644 memcpy(&pNew->aData[8], pCell, 4);
7645 }else if( leafData ){
7646 /* If the tree is a leaf-data tree, and the siblings are leaves,
drh1ffd2472015-06-23 02:37:30 +00007647 ** then there is no divider cell in b.apCell[]. Instead, the divider
dan33ea4862014-10-09 19:35:37 +00007648 ** cell consists of the integer key for the right-most cell of
7649 ** the sibling-page assembled above only.
7650 */
7651 CellInfo info;
7652 j--;
drh1ffd2472015-06-23 02:37:30 +00007653 pNew->xParseCell(pNew, b.apCell[j], &info);
dan33ea4862014-10-09 19:35:37 +00007654 pCell = pTemp;
7655 sz = 4 + putVarint(&pCell[4], info.nKey);
7656 pTemp = 0;
7657 }else{
7658 pCell -= 4;
7659 /* Obscure case for non-leaf-data trees: If the cell at pCell was
7660 ** previously stored on a leaf node, and its reported size was 4
7661 ** bytes, then it may actually be smaller than this
7662 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
7663 ** any cell). But it is important to pass the correct size to
7664 ** insertCell(), so reparse the cell now.
7665 **
drhc1fb2b82016-03-09 03:29:27 +00007666 ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
7667 ** and WITHOUT ROWID tables with exactly one column which is the
7668 ** primary key.
dan33ea4862014-10-09 19:35:37 +00007669 */
drh1ffd2472015-06-23 02:37:30 +00007670 if( b.szCell[j]==4 ){
dan33ea4862014-10-09 19:35:37 +00007671 assert(leafCorrection==4);
drh25ada072015-06-19 15:07:14 +00007672 sz = pParent->xCellSize(pParent, pCell);
dan33ea4862014-10-09 19:35:37 +00007673 }
7674 }
7675 iOvflSpace += sz;
7676 assert( sz<=pBt->maxLocal+23 );
7677 assert( iOvflSpace <= (int)pBt->pageSize );
7678 insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
7679 if( rc!=SQLITE_OK ) goto balance_cleanup;
7680 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7681 }
7682
7683 /* Now update the actual sibling pages. The order in which they are updated
7684 ** is important, as this code needs to avoid disrupting any page from which
7685 ** cells may still to be read. In practice, this means:
7686 **
drhd836d422014-10-31 14:26:36 +00007687 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
7688 ** then it is not safe to update page apNew[iPg] until after
7689 ** the left-hand sibling apNew[iPg-1] has been updated.
dan33ea4862014-10-09 19:35:37 +00007690 **
drhd836d422014-10-31 14:26:36 +00007691 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
7692 ** then it is not safe to update page apNew[iPg] until after
7693 ** the right-hand sibling apNew[iPg+1] has been updated.
dan33ea4862014-10-09 19:35:37 +00007694 **
7695 ** If neither of the above apply, the page is safe to update.
drhd836d422014-10-31 14:26:36 +00007696 **
7697 ** The iPg value in the following loop starts at nNew-1 goes down
7698 ** to 0, then back up to nNew-1 again, thus making two passes over
7699 ** the pages. On the initial downward pass, only condition (1) above
7700 ** needs to be tested because (2) will always be true from the previous
7701 ** step. On the upward pass, both conditions are always true, so the
7702 ** upwards pass simply processes pages that were missed on the downward
7703 ** pass.
dan33ea4862014-10-09 19:35:37 +00007704 */
drhbec021b2014-10-31 12:22:00 +00007705 for(i=1-nNew; i<nNew; i++){
7706 int iPg = i<0 ? -i : i;
drhbec021b2014-10-31 12:22:00 +00007707 assert( iPg>=0 && iPg<nNew );
drhd836d422014-10-31 14:26:36 +00007708 if( abDone[iPg] ) continue; /* Skip pages already processed */
7709 if( i>=0 /* On the upwards pass, or... */
7710 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
dan33ea4862014-10-09 19:35:37 +00007711 ){
dan09c68402014-10-11 20:00:24 +00007712 int iNew;
7713 int iOld;
7714 int nNewCell;
7715
drhd836d422014-10-31 14:26:36 +00007716 /* Verify condition (1): If cells are moving left, update iPg
7717 ** only after iPg-1 has already been updated. */
7718 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
7719
7720 /* Verify condition (2): If cells are moving right, update iPg
7721 ** only after iPg+1 has already been updated. */
7722 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
7723
dan09c68402014-10-11 20:00:24 +00007724 if( iPg==0 ){
7725 iNew = iOld = 0;
7726 nNewCell = cntNew[0];
7727 }else{
drh1ffd2472015-06-23 02:37:30 +00007728 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
dan09c68402014-10-11 20:00:24 +00007729 iNew = cntNew[iPg-1] + !leafData;
7730 nNewCell = cntNew[iPg] - iNew;
7731 }
7732
drh1ffd2472015-06-23 02:37:30 +00007733 rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
drh658873b2015-06-22 20:02:04 +00007734 if( rc ) goto balance_cleanup;
drhd836d422014-10-31 14:26:36 +00007735 abDone[iPg]++;
dand7b545b2014-10-13 18:03:27 +00007736 apNew[iPg]->nFree = usableSpace-szNew[iPg];
dan09c68402014-10-11 20:00:24 +00007737 assert( apNew[iPg]->nOverflow==0 );
7738 assert( apNew[iPg]->nCell==nNewCell );
dan33ea4862014-10-09 19:35:37 +00007739 }
7740 }
drhd836d422014-10-31 14:26:36 +00007741
7742 /* All pages have been processed exactly once */
dan33ea4862014-10-09 19:35:37 +00007743 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
7744
drh7aa8f852006-03-28 00:24:44 +00007745 assert( nOld>0 );
7746 assert( nNew>0 );
drh14acc042001-06-10 19:56:58 +00007747
danielk197713bd99f2009-06-24 05:40:34 +00007748 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
7749 /* The root page of the b-tree now contains no cells. The only sibling
7750 ** page is the right-child of the parent. Copy the contents of the
7751 ** child page into the parent, decreasing the overall height of the
7752 ** b-tree structure by one. This is described as the "balance-shallower"
7753 ** sub-algorithm in some documentation.
7754 **
7755 ** If this is an auto-vacuum database, the call to copyNodeContent()
7756 ** sets all pointer-map entries corresponding to database image pages
7757 ** for which the pointer is stored within the content being copied.
7758 **
drh768f2902014-10-31 02:51:41 +00007759 ** It is critical that the child page be defragmented before being
7760 ** copied into the parent, because if the parent is page 1 then it will
7761 ** by smaller than the child due to the database header, and so all the
7762 ** free space needs to be up front.
7763 */
drh9b5351d2015-09-30 14:19:08 +00007764 assert( nNew==1 || CORRUPT_DB );
dan3b2ede12017-02-25 16:24:02 +00007765 rc = defragmentPage(apNew[0], -1);
drh768f2902014-10-31 02:51:41 +00007766 testcase( rc!=SQLITE_OK );
danielk197713bd99f2009-06-24 05:40:34 +00007767 assert( apNew[0]->nFree ==
drh768f2902014-10-31 02:51:41 +00007768 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
7769 || rc!=SQLITE_OK
danielk197713bd99f2009-06-24 05:40:34 +00007770 );
drhc314dc72009-07-21 11:52:34 +00007771 copyNodeContent(apNew[0], pParent, &rc);
7772 freePage(apNew[0], &rc);
dan33ea4862014-10-09 19:35:37 +00007773 }else if( ISAUTOVACUUM && !leafCorrection ){
7774 /* Fix the pointer map entries associated with the right-child of each
7775 ** sibling page. All other pointer map entries have already been taken
7776 ** care of. */
7777 for(i=0; i<nNew; i++){
7778 u32 key = get4byte(&apNew[i]->aData[8]);
7779 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00007780 }
dan33ea4862014-10-09 19:35:37 +00007781 }
danielk19774dbaa892009-06-16 16:50:22 +00007782
dan33ea4862014-10-09 19:35:37 +00007783 assert( pParent->isInit );
7784 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
drh1ffd2472015-06-23 02:37:30 +00007785 nOld, nNew, b.nCell));
danielk19774dbaa892009-06-16 16:50:22 +00007786
dan33ea4862014-10-09 19:35:37 +00007787 /* Free any old pages that were not reused as new pages.
7788 */
7789 for(i=nNew; i<nOld; i++){
7790 freePage(apOld[i], &rc);
7791 }
danielk19774dbaa892009-06-16 16:50:22 +00007792
7793#if 0
dan33ea4862014-10-09 19:35:37 +00007794 if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
danielk19774dbaa892009-06-16 16:50:22 +00007795 /* The ptrmapCheckPages() contains assert() statements that verify that
7796 ** all pointer map pages are set correctly. This is helpful while
7797 ** debugging. This is usually disabled because a corrupt database may
7798 ** cause an assert() statement to fail. */
7799 ptrmapCheckPages(apNew, nNew);
7800 ptrmapCheckPages(&pParent, 1);
danielk19774dbaa892009-06-16 16:50:22 +00007801 }
dan33ea4862014-10-09 19:35:37 +00007802#endif
danielk1977cd581a72009-06-23 15:43:39 +00007803
drh8b2f49b2001-06-08 00:21:52 +00007804 /*
drh14acc042001-06-10 19:56:58 +00007805 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00007806 */
drh14acc042001-06-10 19:56:58 +00007807balance_cleanup:
drh1ffd2472015-06-23 02:37:30 +00007808 sqlite3ScratchFree(b.apCell);
drh8b2f49b2001-06-08 00:21:52 +00007809 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00007810 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00007811 }
drh14acc042001-06-10 19:56:58 +00007812 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00007813 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00007814 }
danielk1977eaa06f62008-09-18 17:34:44 +00007815
drh8b2f49b2001-06-08 00:21:52 +00007816 return rc;
7817}
7818
drh43605152004-05-29 21:46:49 +00007819
7820/*
danielk1977a50d9aa2009-06-08 14:49:45 +00007821** This function is called when the root page of a b-tree structure is
7822** overfull (has one or more overflow pages).
drh43605152004-05-29 21:46:49 +00007823**
danielk1977a50d9aa2009-06-08 14:49:45 +00007824** A new child page is allocated and the contents of the current root
7825** page, including overflow cells, are copied into the child. The root
7826** page is then overwritten to make it an empty page with the right-child
7827** pointer pointing to the new page.
7828**
7829** Before returning, all pointer-map entries corresponding to pages
7830** that the new child-page now contains pointers to are updated. The
7831** entry corresponding to the new right-child pointer of the root
7832** page is also updated.
7833**
7834** If successful, *ppChild is set to contain a reference to the child
7835** page and SQLITE_OK is returned. In this case the caller is required
7836** to call releasePage() on *ppChild exactly once. If an error occurs,
7837** an error code is returned and *ppChild is set to 0.
drh43605152004-05-29 21:46:49 +00007838*/
danielk1977a50d9aa2009-06-08 14:49:45 +00007839static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
7840 int rc; /* Return value from subprocedures */
7841 MemPage *pChild = 0; /* Pointer to a new child page */
shane5eff7cf2009-08-10 03:57:58 +00007842 Pgno pgnoChild = 0; /* Page number of the new child page */
danielk1977a50d9aa2009-06-08 14:49:45 +00007843 BtShared *pBt = pRoot->pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00007844
danielk1977a50d9aa2009-06-08 14:49:45 +00007845 assert( pRoot->nOverflow>0 );
drh1fee73e2007-08-29 04:00:57 +00007846 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bc2ca9e2008-11-13 14:28:28 +00007847
danielk1977a50d9aa2009-06-08 14:49:45 +00007848 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
7849 ** page that will become the new right-child of pPage. Copy the contents
7850 ** of the node stored on pRoot into the new child page.
7851 */
drh98add2e2009-07-20 17:11:49 +00007852 rc = sqlite3PagerWrite(pRoot->pDbPage);
7853 if( rc==SQLITE_OK ){
7854 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
drhc314dc72009-07-21 11:52:34 +00007855 copyNodeContent(pRoot, pChild, &rc);
7856 if( ISAUTOVACUUM ){
7857 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
drh98add2e2009-07-20 17:11:49 +00007858 }
7859 }
7860 if( rc ){
danielk1977a50d9aa2009-06-08 14:49:45 +00007861 *ppChild = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00007862 releasePage(pChild);
danielk1977a50d9aa2009-06-08 14:49:45 +00007863 return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00007864 }
danielk1977a50d9aa2009-06-08 14:49:45 +00007865 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
7866 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
7867 assert( pChild->nCell==pRoot->nCell );
danielk197771d5d2c2008-09-29 11:49:47 +00007868
danielk1977a50d9aa2009-06-08 14:49:45 +00007869 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
7870
7871 /* Copy the overflow cells from pRoot to pChild */
drh2cbd78b2012-02-02 19:37:18 +00007872 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
7873 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
7874 memcpy(pChild->apOvfl, pRoot->apOvfl,
7875 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
danielk1977a50d9aa2009-06-08 14:49:45 +00007876 pChild->nOverflow = pRoot->nOverflow;
danielk1977a50d9aa2009-06-08 14:49:45 +00007877
7878 /* Zero the contents of pRoot. Then install pChild as the right-child. */
7879 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
7880 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
7881
7882 *ppChild = pChild;
7883 return SQLITE_OK;
drh43605152004-05-29 21:46:49 +00007884}
7885
7886/*
danielk197771d5d2c2008-09-29 11:49:47 +00007887** The page that pCur currently points to has just been modified in
7888** some way. This function figures out if this modification means the
7889** tree needs to be balanced, and if so calls the appropriate balancing
danielk1977a50d9aa2009-06-08 14:49:45 +00007890** routine. Balancing routines are:
7891**
7892** balance_quick()
danielk1977a50d9aa2009-06-08 14:49:45 +00007893** balance_deeper()
7894** balance_nonroot()
drh43605152004-05-29 21:46:49 +00007895*/
danielk1977a50d9aa2009-06-08 14:49:45 +00007896static int balance(BtCursor *pCur){
drh43605152004-05-29 21:46:49 +00007897 int rc = SQLITE_OK;
danielk1977a50d9aa2009-06-08 14:49:45 +00007898 const int nMin = pCur->pBt->usableSize * 2 / 3;
7899 u8 aBalanceQuickSpace[13];
7900 u8 *pFree = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00007901
drhcc5f8a42016-02-06 22:32:06 +00007902 VVA_ONLY( int balance_quick_called = 0 );
7903 VVA_ONLY( int balance_deeper_called = 0 );
danielk1977a50d9aa2009-06-08 14:49:45 +00007904
7905 do {
7906 int iPage = pCur->iPage;
7907 MemPage *pPage = pCur->apPage[iPage];
7908
7909 if( iPage==0 ){
7910 if( pPage->nOverflow ){
7911 /* The root page of the b-tree is overfull. In this case call the
7912 ** balance_deeper() function to create a new child for the root-page
7913 ** and copy the current contents of the root-page to it. The
7914 ** next iteration of the do-loop will balance the child page.
7915 */
drhcc5f8a42016-02-06 22:32:06 +00007916 assert( balance_deeper_called==0 );
7917 VVA_ONLY( balance_deeper_called++ );
danielk1977a50d9aa2009-06-08 14:49:45 +00007918 rc = balance_deeper(pPage, &pCur->apPage[1]);
7919 if( rc==SQLITE_OK ){
7920 pCur->iPage = 1;
7921 pCur->aiIdx[0] = 0;
7922 pCur->aiIdx[1] = 0;
7923 assert( pCur->apPage[1]->nOverflow );
7924 }
danielk1977a50d9aa2009-06-08 14:49:45 +00007925 }else{
danielk1977a50d9aa2009-06-08 14:49:45 +00007926 break;
7927 }
7928 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
7929 break;
7930 }else{
7931 MemPage * const pParent = pCur->apPage[iPage-1];
7932 int const iIdx = pCur->aiIdx[iPage-1];
7933
7934 rc = sqlite3PagerWrite(pParent->pDbPage);
7935 if( rc==SQLITE_OK ){
7936#ifndef SQLITE_OMIT_QUICKBALANCE
drh3e28ff52014-09-24 00:59:08 +00007937 if( pPage->intKeyLeaf
danielk1977a50d9aa2009-06-08 14:49:45 +00007938 && pPage->nOverflow==1
drh2cbd78b2012-02-02 19:37:18 +00007939 && pPage->aiOvfl[0]==pPage->nCell
danielk1977a50d9aa2009-06-08 14:49:45 +00007940 && pParent->pgno!=1
7941 && pParent->nCell==iIdx
7942 ){
7943 /* Call balance_quick() to create a new sibling of pPage on which
7944 ** to store the overflow cell. balance_quick() inserts a new cell
7945 ** into pParent, which may cause pParent overflow. If this
peter.d.reid60ec9142014-09-06 16:39:46 +00007946 ** happens, the next iteration of the do-loop will balance pParent
danielk1977a50d9aa2009-06-08 14:49:45 +00007947 ** use either balance_nonroot() or balance_deeper(). Until this
7948 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
7949 ** buffer.
7950 **
7951 ** The purpose of the following assert() is to check that only a
7952 ** single call to balance_quick() is made for each call to this
7953 ** function. If this were not verified, a subtle bug involving reuse
7954 ** of the aBalanceQuickSpace[] might sneak in.
7955 */
drhcc5f8a42016-02-06 22:32:06 +00007956 assert( balance_quick_called==0 );
7957 VVA_ONLY( balance_quick_called++ );
danielk1977a50d9aa2009-06-08 14:49:45 +00007958 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
7959 }else
7960#endif
7961 {
7962 /* In this case, call balance_nonroot() to redistribute cells
7963 ** between pPage and up to 2 of its sibling pages. This involves
7964 ** modifying the contents of pParent, which may cause pParent to
7965 ** become overfull or underfull. The next iteration of the do-loop
7966 ** will balance the parent page to correct this.
7967 **
7968 ** If the parent page becomes overfull, the overflow cell or cells
7969 ** are stored in the pSpace buffer allocated immediately below.
7970 ** A subsequent iteration of the do-loop will deal with this by
7971 ** calling balance_nonroot() (balance_deeper() may be called first,
7972 ** but it doesn't deal with overflow cells - just moves them to a
7973 ** different page). Once this subsequent call to balance_nonroot()
7974 ** has completed, it is safe to release the pSpace buffer used by
7975 ** the previous call, as the overflow cell data will have been
7976 ** copied either into the body of a database page or into the new
7977 ** pSpace buffer passed to the latter call to balance_nonroot().
7978 */
7979 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
drhe0997b32015-03-20 14:57:50 +00007980 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
7981 pCur->hints&BTREE_BULKLOAD);
danielk1977a50d9aa2009-06-08 14:49:45 +00007982 if( pFree ){
7983 /* If pFree is not NULL, it points to the pSpace buffer used
7984 ** by a previous call to balance_nonroot(). Its contents are
7985 ** now stored either on real database pages or within the
7986 ** new pSpace buffer, so it may be safely freed here. */
7987 sqlite3PageFree(pFree);
7988 }
7989
danielk19774dbaa892009-06-16 16:50:22 +00007990 /* The pSpace buffer will be freed after the next call to
7991 ** balance_nonroot(), or just before this function returns, whichever
7992 ** comes first. */
danielk1977a50d9aa2009-06-08 14:49:45 +00007993 pFree = pSpace;
danielk1977a50d9aa2009-06-08 14:49:45 +00007994 }
7995 }
7996
7997 pPage->nOverflow = 0;
7998
7999 /* The next iteration of the do-loop balances the parent page. */
8000 releasePage(pPage);
8001 pCur->iPage--;
drhcbd33492015-03-25 13:06:54 +00008002 assert( pCur->iPage>=0 );
drh43605152004-05-29 21:46:49 +00008003 }
danielk1977a50d9aa2009-06-08 14:49:45 +00008004 }while( rc==SQLITE_OK );
8005
8006 if( pFree ){
8007 sqlite3PageFree(pFree);
drh43605152004-05-29 21:46:49 +00008008 }
8009 return rc;
8010}
8011
drhf74b8d92002-09-01 23:20:45 +00008012
8013/*
drh8eeb4462016-05-21 20:03:42 +00008014** Insert a new record into the BTree. The content of the new record
8015** is described by the pX object. The pCur cursor is used only to
8016** define what table the record should be inserted into, and is left
8017** pointing at a random location.
drh4b70f112004-05-02 21:12:19 +00008018**
drh8eeb4462016-05-21 20:03:42 +00008019** For a table btree (used for rowid tables), only the pX.nKey value of
8020** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
8021** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
8022** hold the content of the row.
8023**
8024** For an index btree (used for indexes and WITHOUT ROWID tables), the
8025** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
8026** pX.pData,nData,nZero fields must be zero.
danielk1977de630352009-05-04 11:42:29 +00008027**
8028** If the seekResult parameter is non-zero, then a successful call to
drheaf6ae22016-11-09 20:14:34 +00008029** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
8030** been performed. In other words, if seekResult!=0 then the cursor
8031** is currently pointing to a cell that will be adjacent to the cell
8032** to be inserted. If seekResult<0 then pCur points to a cell that is
8033** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
8034** that is larger than (pKey,nKey).
danielk1977de630352009-05-04 11:42:29 +00008035**
drheaf6ae22016-11-09 20:14:34 +00008036** If seekResult==0, that means pCur is pointing at some unknown location.
8037** In that case, this routine must seek the cursor to the correct insertion
8038** point for (pKey,nKey) before doing the insertion. For index btrees,
8039** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
8040** key values and pX->aMem can be used instead of pX->pKey to avoid having
8041** to decode the key.
drh3b7511c2001-05-26 13:15:44 +00008042*/
drh3aac2dd2004-04-26 14:10:20 +00008043int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00008044 BtCursor *pCur, /* Insert data into the table of this cursor */
drh8eeb4462016-05-21 20:03:42 +00008045 const BtreePayload *pX, /* Content of the row to be inserted */
danf91c1312017-01-10 20:04:38 +00008046 int flags, /* True if this is likely an append */
danielk19773509a652009-07-06 18:56:13 +00008047 int seekResult /* Result of prior MovetoUnpacked() call */
drh3b7511c2001-05-26 13:15:44 +00008048){
drh3b7511c2001-05-26 13:15:44 +00008049 int rc;
drh3e9ca092009-09-08 01:14:48 +00008050 int loc = seekResult; /* -1: before desired location +1: after */
drh1d452e12009-11-01 19:26:59 +00008051 int szNew = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00008052 int idx;
drh3b7511c2001-05-26 13:15:44 +00008053 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00008054 Btree *p = pCur->pBtree;
8055 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00008056 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00008057 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00008058
danf91c1312017-01-10 20:04:38 +00008059 assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
8060
drh98add2e2009-07-20 17:11:49 +00008061 if( pCur->eState==CURSOR_FAULT ){
8062 assert( pCur->skipNext!=SQLITE_OK );
8063 return pCur->skipNext;
8064 }
8065
dan7a2347e2016-01-07 16:43:54 +00008066 assert( cursorOwnsBtShared(pCur) );
drh3f387402014-09-24 01:23:00 +00008067 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
8068 && pBt->inTransaction==TRANS_WRITE
drhc9166342012-01-05 23:32:06 +00008069 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk197796d48e92009-06-29 06:00:37 +00008070 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8071
danielk197731d31b82009-07-13 13:18:07 +00008072 /* Assert that the caller has been consistent. If this cursor was opened
8073 ** expecting an index b-tree, then the caller should be inserting blob
8074 ** keys with no associated data. If the cursor was opened expecting an
8075 ** intkey table, the caller should be inserting integer keys with a
8076 ** blob of associated data. */
drh8eeb4462016-05-21 20:03:42 +00008077 assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
danielk197731d31b82009-07-13 13:18:07 +00008078
danielk19779c3acf32009-05-02 07:36:49 +00008079 /* Save the positions of any other cursors open on this table.
8080 **
danielk19773509a652009-07-06 18:56:13 +00008081 ** In some cases, the call to btreeMoveto() below is a no-op. For
danielk19779c3acf32009-05-02 07:36:49 +00008082 ** example, when inserting data into a table with auto-generated integer
8083 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
8084 ** integer key to use. It then calls this function to actually insert the
danielk19773509a652009-07-06 18:56:13 +00008085 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
danielk19779c3acf32009-05-02 07:36:49 +00008086 ** that the cursor is already where it needs to be and returns without
8087 ** doing any work. To avoid thwarting these optimizations, it is important
8088 ** not to clear the cursor here.
8089 */
drh27fb7462015-06-30 02:47:36 +00008090 if( pCur->curFlags & BTCF_Multiple ){
8091 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8092 if( rc ) return rc;
drhd60f4f42012-03-23 14:23:52 +00008093 }
8094
danielk197771d5d2c2008-09-29 11:49:47 +00008095 if( pCur->pKeyInfo==0 ){
drh8eeb4462016-05-21 20:03:42 +00008096 assert( pX->pKey==0 );
drhe0670b62014-02-12 21:31:12 +00008097 /* If this is an insert into a table b-tree, invalidate any incrblob
8098 ** cursors open on the row being replaced */
drh8eeb4462016-05-21 20:03:42 +00008099 invalidateIncrblobCursors(p, pX->nKey, 0);
drhe0670b62014-02-12 21:31:12 +00008100
danf91c1312017-01-10 20:04:38 +00008101 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8102 ** to a row with the same key as the new entry being inserted. */
8103 assert( (flags & BTREE_SAVEPOSITION)==0 ||
8104 ((pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey) );
8105
drhe0670b62014-02-12 21:31:12 +00008106 /* If the cursor is currently on the last row and we are appending a
drh207c8172015-06-29 23:01:32 +00008107 ** new row onto the end, set the "loc" to avoid an unnecessary
8108 ** btreeMoveto() call */
drh7a1c28d2016-11-10 20:42:08 +00008109 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
8110 loc = 0;
8111 }else if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey>0
8112 && pCur->info.nKey==pX->nKey-1 ){
8113 loc = -1;
drh207c8172015-06-29 23:01:32 +00008114 }else if( loc==0 ){
danf91c1312017-01-10 20:04:38 +00008115 rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
drh207c8172015-06-29 23:01:32 +00008116 if( rc ) return rc;
drhe0670b62014-02-12 21:31:12 +00008117 }
danf91c1312017-01-10 20:04:38 +00008118 }else if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
drh9b4eaeb2016-11-09 00:10:33 +00008119 if( pX->nMem ){
8120 UnpackedRecord r;
drh9b4eaeb2016-11-09 00:10:33 +00008121 r.pKeyInfo = pCur->pKeyInfo;
8122 r.aMem = pX->aMem;
8123 r.nField = pX->nMem;
drh8c730bc2016-12-10 13:12:55 +00008124 r.default_rc = 0;
8125 r.errCode = 0;
8126 r.r1 = 0;
8127 r.r2 = 0;
8128 r.eqSeen = 0;
danf91c1312017-01-10 20:04:38 +00008129 rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
drh9b4eaeb2016-11-09 00:10:33 +00008130 }else{
danf91c1312017-01-10 20:04:38 +00008131 rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
drh9b4eaeb2016-11-09 00:10:33 +00008132 }
drh4c301aa2009-07-15 17:25:45 +00008133 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00008134 }
danielk1977b980d2212009-06-22 18:03:51 +00008135 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
danielk1977da184232006-01-05 11:34:32 +00008136
drh14acc042001-06-10 19:56:58 +00008137 pPage = pCur->apPage[pCur->iPage];
drh8eeb4462016-05-21 20:03:42 +00008138 assert( pPage->intKey || pX->nKey>=0 );
drh44845222008-07-17 18:39:57 +00008139 assert( pPage->leaf || !pPage->intKey );
danielk19778f880a82009-07-13 09:41:45 +00008140
drh3a4c1412004-05-09 20:40:11 +00008141 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
drh8eeb4462016-05-21 20:03:42 +00008142 pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
drh3a4c1412004-05-09 20:40:11 +00008143 loc==0 ? "overwrite" : "new entry"));
danielk197771d5d2c2008-09-29 11:49:47 +00008144 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00008145 newCell = pBt->pTmpSpace;
drh3fbb0222014-09-24 19:47:27 +00008146 assert( newCell!=0 );
drh8eeb4462016-05-21 20:03:42 +00008147 rc = fillInCell(pPage, newCell, pX, &szNew);
drh2e38c322004-09-03 18:38:44 +00008148 if( rc ) goto end_insert;
drh25ada072015-06-19 15:07:14 +00008149 assert( szNew==pPage->xCellSize(pPage, newCell) );
drhfcd71b62011-04-05 22:08:24 +00008150 assert( szNew <= MX_CELL_SIZE(pBt) );
danielk197771d5d2c2008-09-29 11:49:47 +00008151 idx = pCur->aiIdx[pCur->iPage];
danielk1977b980d2212009-06-22 18:03:51 +00008152 if( loc==0 ){
drh80159da2016-12-09 17:32:51 +00008153 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00008154 assert( idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00008155 rc = sqlite3PagerWrite(pPage->pDbPage);
8156 if( rc ){
8157 goto end_insert;
8158 }
danielk197771d5d2c2008-09-29 11:49:47 +00008159 oldCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00008160 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00008161 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00008162 }
drh80159da2016-12-09 17:32:51 +00008163 rc = clearCell(pPage, oldCell, &info);
8164 if( info.nSize==szNew && info.nLocal==info.nPayload ){
drhf9238252016-12-09 18:09:42 +00008165 /* Overwrite the old cell with the new if they are the same size.
8166 ** We could also try to do this if the old cell is smaller, then add
8167 ** the leftover space to the free list. But experiments show that
8168 ** doing that is no faster then skipping this optimization and just
8169 ** calling dropCell() and insertCell(). */
8170 assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
drh2d083432016-12-09 19:42:18 +00008171 if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
drh80159da2016-12-09 17:32:51 +00008172 memcpy(oldCell, newCell, szNew);
8173 return SQLITE_OK;
8174 }
8175 dropCell(pPage, idx, info.nSize, &rc);
drh2e38c322004-09-03 18:38:44 +00008176 if( rc ) goto end_insert;
drh7c717f72001-06-24 20:39:41 +00008177 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00008178 assert( pPage->leaf );
danielk197771d5d2c2008-09-29 11:49:47 +00008179 idx = ++pCur->aiIdx[pCur->iPage];
drh14acc042001-06-10 19:56:58 +00008180 }else{
drh4b70f112004-05-02 21:12:19 +00008181 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00008182 }
drh98add2e2009-07-20 17:11:49 +00008183 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
drh09a4e922016-05-21 12:29:04 +00008184 assert( pPage->nOverflow==0 || rc==SQLITE_OK );
danielk19773f632d52009-05-02 10:03:09 +00008185 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
drh9bf9e9c2008-12-05 20:01:43 +00008186
mistachkin48864df2013-03-21 21:20:32 +00008187 /* If no error has occurred and pPage has an overflow cell, call balance()
danielk1977a50d9aa2009-06-08 14:49:45 +00008188 ** to redistribute the cells within the tree. Since balance() may move
drh036dbec2014-03-11 23:40:44 +00008189 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
danielk1977a50d9aa2009-06-08 14:49:45 +00008190 ** variables.
danielk19773f632d52009-05-02 10:03:09 +00008191 **
danielk1977a50d9aa2009-06-08 14:49:45 +00008192 ** Previous versions of SQLite called moveToRoot() to move the cursor
8193 ** back to the root page as balance() used to invalidate the contents
danielk197754109bb2009-06-23 11:22:29 +00008194 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
8195 ** set the cursor state to "invalid". This makes common insert operations
8196 ** slightly faster.
danielk19773f632d52009-05-02 10:03:09 +00008197 **
danielk1977a50d9aa2009-06-08 14:49:45 +00008198 ** There is a subtle but important optimization here too. When inserting
8199 ** multiple records into an intkey b-tree using a single cursor (as can
8200 ** happen while processing an "INSERT INTO ... SELECT" statement), it
8201 ** is advantageous to leave the cursor pointing to the last entry in
8202 ** the b-tree if possible. If the cursor is left pointing to the last
8203 ** entry in the table, and the next row inserted has an integer key
8204 ** larger than the largest existing key, it is possible to insert the
8205 ** row without seeking the cursor. This can be a big performance boost.
danielk19773f632d52009-05-02 10:03:09 +00008206 */
danielk1977a50d9aa2009-06-08 14:49:45 +00008207 pCur->info.nSize = 0;
drh09a4e922016-05-21 12:29:04 +00008208 if( pPage->nOverflow ){
8209 assert( rc==SQLITE_OK );
drh036dbec2014-03-11 23:40:44 +00008210 pCur->curFlags &= ~(BTCF_ValidNKey);
danielk1977a50d9aa2009-06-08 14:49:45 +00008211 rc = balance(pCur);
8212
8213 /* Must make sure nOverflow is reset to zero even if the balance()
danielk197754109bb2009-06-23 11:22:29 +00008214 ** fails. Internal data structure corruption will result otherwise.
8215 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
8216 ** from trying to save the current position of the cursor. */
danielk1977a50d9aa2009-06-08 14:49:45 +00008217 pCur->apPage[pCur->iPage]->nOverflow = 0;
danielk197754109bb2009-06-23 11:22:29 +00008218 pCur->eState = CURSOR_INVALID;
danf91c1312017-01-10 20:04:38 +00008219 if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
8220 rc = moveToRoot(pCur);
drh7b20a152017-01-12 19:10:55 +00008221 if( pCur->pKeyInfo ){
danf91c1312017-01-10 20:04:38 +00008222 assert( pCur->pKey==0 );
8223 pCur->pKey = sqlite3Malloc( pX->nKey );
8224 if( pCur->pKey==0 ){
8225 rc = SQLITE_NOMEM;
8226 }else{
8227 memcpy(pCur->pKey, pX->pKey, pX->nKey);
8228 }
8229 }
8230 pCur->eState = CURSOR_REQUIRESEEK;
8231 pCur->nKey = pX->nKey;
8232 }
danielk19773f632d52009-05-02 10:03:09 +00008233 }
danielk1977a50d9aa2009-06-08 14:49:45 +00008234 assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
drh9bf9e9c2008-12-05 20:01:43 +00008235
drh2e38c322004-09-03 18:38:44 +00008236end_insert:
drh5e2f8b92001-05-28 00:41:15 +00008237 return rc;
8238}
8239
8240/*
danf0ee1d32015-09-12 19:26:11 +00008241** Delete the entry that the cursor is pointing to.
8242**
drhe807bdb2016-01-21 17:06:33 +00008243** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
8244** the cursor is left pointing at an arbitrary location after the delete.
8245** But if that bit is set, then the cursor is left in a state such that
8246** the next call to BtreeNext() or BtreePrev() moves it to the same row
8247** as it would have been on if the call to BtreeDelete() had been omitted.
8248**
drhdef19e32016-01-27 16:26:25 +00008249** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
8250** associated with a single table entry and its indexes. Only one of those
8251** deletes is considered the "primary" delete. The primary delete occurs
8252** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
8253** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
8254** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
drhe807bdb2016-01-21 17:06:33 +00008255** but which might be used by alternative storage engines.
drh3b7511c2001-05-26 13:15:44 +00008256*/
drhe807bdb2016-01-21 17:06:33 +00008257int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
drhd677b3d2007-08-20 22:48:41 +00008258 Btree *p = pCur->pBtree;
danielk19774dbaa892009-06-16 16:50:22 +00008259 BtShared *pBt = p->pBt;
8260 int rc; /* Return code */
8261 MemPage *pPage; /* Page to delete cell from */
8262 unsigned char *pCell; /* Pointer to cell to delete */
8263 int iCellIdx; /* Index of cell to delete */
8264 int iCellDepth; /* Depth of node containing pCell */
drh80159da2016-12-09 17:32:51 +00008265 CellInfo info; /* Size of the cell being deleted */
danf0ee1d32015-09-12 19:26:11 +00008266 int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
drhe807bdb2016-01-21 17:06:33 +00008267 u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
drh8b2f49b2001-06-08 00:21:52 +00008268
dan7a2347e2016-01-07 16:43:54 +00008269 assert( cursorOwnsBtShared(pCur) );
drh64022502009-01-09 14:11:04 +00008270 assert( pBt->inTransaction==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00008271 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
drh036dbec2014-03-11 23:40:44 +00008272 assert( pCur->curFlags & BTCF_WriteFlag );
danielk197796d48e92009-06-29 06:00:37 +00008273 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8274 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
drh98ef0f62015-06-30 01:25:52 +00008275 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
8276 assert( pCur->eState==CURSOR_VALID );
drhdef19e32016-01-27 16:26:25 +00008277 assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
danielk1977da184232006-01-05 11:34:32 +00008278
danielk19774dbaa892009-06-16 16:50:22 +00008279 iCellDepth = pCur->iPage;
8280 iCellIdx = pCur->aiIdx[iCellDepth];
8281 pPage = pCur->apPage[iCellDepth];
8282 pCell = findCell(pPage, iCellIdx);
8283
drhbfc7a8b2016-04-09 17:04:05 +00008284 /* If the bPreserve flag is set to true, then the cursor position must
8285 ** be preserved following this delete operation. If the current delete
8286 ** will cause a b-tree rebalance, then this is done by saving the cursor
8287 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
8288 ** returning.
8289 **
8290 ** Or, if the current delete will not cause a rebalance, then the cursor
8291 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
8292 ** before or after the deleted entry. In this case set bSkipnext to true. */
8293 if( bPreserve ){
8294 if( !pPage->leaf
8295 || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
8296 ){
8297 /* A b-tree rebalance will be required after deleting this entry.
8298 ** Save the cursor key. */
8299 rc = saveCursorKey(pCur);
8300 if( rc ) return rc;
8301 }else{
8302 bSkipnext = 1;
8303 }
8304 }
8305
danielk19774dbaa892009-06-16 16:50:22 +00008306 /* If the page containing the entry to delete is not a leaf page, move
8307 ** the cursor to the largest entry in the tree that is smaller than
8308 ** the entry being deleted. This cell will replace the cell being deleted
8309 ** from the internal node. The 'previous' entry is used for this instead
8310 ** of the 'next' entry, as the previous entry is always a part of the
8311 ** sub-tree headed by the child page of the cell being deleted. This makes
8312 ** balancing the tree following the delete operation easier. */
8313 if( !pPage->leaf ){
drhe39a7322014-02-03 14:04:11 +00008314 int notUsed = 0;
drh4c301aa2009-07-15 17:25:45 +00008315 rc = sqlite3BtreePrevious(pCur, &notUsed);
8316 if( rc ) return rc;
danielk19774dbaa892009-06-16 16:50:22 +00008317 }
8318
8319 /* Save the positions of any other cursors open on this table before
danf0ee1d32015-09-12 19:26:11 +00008320 ** making any modifications. */
drh27fb7462015-06-30 02:47:36 +00008321 if( pCur->curFlags & BTCF_Multiple ){
8322 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8323 if( rc ) return rc;
8324 }
drhd60f4f42012-03-23 14:23:52 +00008325
8326 /* If this is a delete operation to remove a row from a table b-tree,
8327 ** invalidate any incrblob cursors open on the row being deleted. */
8328 if( pCur->pKeyInfo==0 ){
8329 invalidateIncrblobCursors(p, pCur->info.nKey, 0);
8330 }
8331
danf0ee1d32015-09-12 19:26:11 +00008332 /* Make the page containing the entry to be deleted writable. Then free any
8333 ** overflow pages associated with the entry and finally remove the cell
8334 ** itself from within the page. */
drha4ec1d42009-07-11 13:13:11 +00008335 rc = sqlite3PagerWrite(pPage->pDbPage);
8336 if( rc ) return rc;
drh80159da2016-12-09 17:32:51 +00008337 rc = clearCell(pPage, pCell, &info);
8338 dropCell(pPage, iCellIdx, info.nSize, &rc);
drha4ec1d42009-07-11 13:13:11 +00008339 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00008340
danielk19774dbaa892009-06-16 16:50:22 +00008341 /* If the cell deleted was not located on a leaf page, then the cursor
8342 ** is currently pointing to the largest entry in the sub-tree headed
8343 ** by the child-page of the cell that was just deleted from an internal
8344 ** node. The cell from the leaf node needs to be moved to the internal
8345 ** node to replace the deleted cell. */
drh4b70f112004-05-02 21:12:19 +00008346 if( !pPage->leaf ){
danielk19774dbaa892009-06-16 16:50:22 +00008347 MemPage *pLeaf = pCur->apPage[pCur->iPage];
8348 int nCell;
8349 Pgno n = pCur->apPage[iCellDepth+1]->pgno;
8350 unsigned char *pTmp;
danielk1977e6efa742004-11-10 11:55:10 +00008351
danielk19774dbaa892009-06-16 16:50:22 +00008352 pCell = findCell(pLeaf, pLeaf->nCell-1);
drhb468ce12015-06-24 01:07:30 +00008353 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
drh25ada072015-06-19 15:07:14 +00008354 nCell = pLeaf->xCellSize(pLeaf, pCell);
drhfcd71b62011-04-05 22:08:24 +00008355 assert( MX_CELL_SIZE(pBt) >= nCell );
danielk19774dbaa892009-06-16 16:50:22 +00008356 pTmp = pBt->pTmpSpace;
drh3fbb0222014-09-24 19:47:27 +00008357 assert( pTmp!=0 );
drha4ec1d42009-07-11 13:13:11 +00008358 rc = sqlite3PagerWrite(pLeaf->pDbPage);
drhcb89f4a2016-05-21 11:23:26 +00008359 if( rc==SQLITE_OK ){
8360 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
8361 }
drh98add2e2009-07-20 17:11:49 +00008362 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
drha4ec1d42009-07-11 13:13:11 +00008363 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00008364 }
danielk19774dbaa892009-06-16 16:50:22 +00008365
8366 /* Balance the tree. If the entry deleted was located on a leaf page,
8367 ** then the cursor still points to that page. In this case the first
8368 ** call to balance() repairs the tree, and the if(...) condition is
8369 ** never true.
8370 **
8371 ** Otherwise, if the entry deleted was on an internal node page, then
8372 ** pCur is pointing to the leaf page from which a cell was removed to
8373 ** replace the cell deleted from the internal node. This is slightly
8374 ** tricky as the leaf node may be underfull, and the internal node may
8375 ** be either under or overfull. In this case run the balancing algorithm
8376 ** on the leaf node first. If the balance proceeds far enough up the
8377 ** tree that we can be sure that any problem in the internal node has
8378 ** been corrected, so be it. Otherwise, after balancing the leaf node,
8379 ** walk the cursor up the tree to the internal node and balance it as
8380 ** well. */
8381 rc = balance(pCur);
8382 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
8383 while( pCur->iPage>iCellDepth ){
8384 releasePage(pCur->apPage[pCur->iPage--]);
8385 }
8386 rc = balance(pCur);
8387 }
8388
danielk19776b456a22005-03-21 04:04:02 +00008389 if( rc==SQLITE_OK ){
danf0ee1d32015-09-12 19:26:11 +00008390 if( bSkipnext ){
drha660caf2016-01-01 03:37:44 +00008391 assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
drh38bace82016-02-01 00:21:08 +00008392 assert( pPage==pCur->apPage[pCur->iPage] || CORRUPT_DB );
drh78ac1092015-09-20 22:57:47 +00008393 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
danf0ee1d32015-09-12 19:26:11 +00008394 pCur->eState = CURSOR_SKIPNEXT;
8395 if( iCellIdx>=pPage->nCell ){
8396 pCur->skipNext = -1;
8397 pCur->aiIdx[iCellDepth] = pPage->nCell-1;
8398 }else{
8399 pCur->skipNext = 1;
8400 }
8401 }else{
8402 rc = moveToRoot(pCur);
8403 if( bPreserve ){
8404 pCur->eState = CURSOR_REQUIRESEEK;
8405 }
8406 }
danielk19776b456a22005-03-21 04:04:02 +00008407 }
drh5e2f8b92001-05-28 00:41:15 +00008408 return rc;
drh3b7511c2001-05-26 13:15:44 +00008409}
drh8b2f49b2001-06-08 00:21:52 +00008410
8411/*
drhc6b52df2002-01-04 03:09:29 +00008412** Create a new BTree table. Write into *piTable the page
8413** number for the root page of the new table.
8414**
drhab01f612004-05-22 02:55:23 +00008415** The type of type is determined by the flags parameter. Only the
8416** following values of flags are currently in use. Other values for
8417** flags might not work:
8418**
8419** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
8420** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00008421*/
drhd4187c72010-08-30 22:15:45 +00008422static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
danielk1977aef0bf62005-12-30 16:28:01 +00008423 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00008424 MemPage *pRoot;
8425 Pgno pgnoRoot;
8426 int rc;
drhd4187c72010-08-30 22:15:45 +00008427 int ptfFlags; /* Page-type flage for the root page of new table */
drhd677b3d2007-08-20 22:48:41 +00008428
drh1fee73e2007-08-29 04:00:57 +00008429 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00008430 assert( pBt->inTransaction==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00008431 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk1977e6efa742004-11-10 11:55:10 +00008432
danielk1977003ba062004-11-04 02:57:33 +00008433#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00008434 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00008435 if( rc ){
8436 return rc;
8437 }
danielk1977003ba062004-11-04 02:57:33 +00008438#else
danielk1977687566d2004-11-02 12:56:41 +00008439 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00008440 Pgno pgnoMove; /* Move a page here to make room for the root-page */
8441 MemPage *pPageMove; /* The page to move to. */
8442
danielk197720713f32007-05-03 11:43:33 +00008443 /* Creating a new table may probably require moving an existing database
8444 ** to make room for the new tables root page. In case this page turns
8445 ** out to be an overflow page, delete all overflow page-map caches
8446 ** held by open cursors.
8447 */
danielk197792d4d7a2007-05-04 12:05:56 +00008448 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00008449
danielk1977003ba062004-11-04 02:57:33 +00008450 /* Read the value of meta[3] from the database to determine where the
8451 ** root page of the new table should go. meta[3] is the largest root-page
8452 ** created so far, so the new root-page is (meta[3]+1).
8453 */
danielk1977602b4662009-07-02 07:47:33 +00008454 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00008455 pgnoRoot++;
8456
danielk1977599fcba2004-11-08 07:13:13 +00008457 /* The new root-page may not be allocated on a pointer-map page, or the
8458 ** PENDING_BYTE page.
8459 */
drh72190432008-01-31 14:54:43 +00008460 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00008461 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00008462 pgnoRoot++;
8463 }
drh499e15b2015-05-22 12:37:37 +00008464 assert( pgnoRoot>=3 || CORRUPT_DB );
8465 testcase( pgnoRoot<3 );
danielk1977003ba062004-11-04 02:57:33 +00008466
8467 /* Allocate a page. The page that currently resides at pgnoRoot will
8468 ** be moved to the allocated page (unless the allocated page happens
8469 ** to reside at pgnoRoot).
8470 */
dan51f0b6d2013-02-22 20:16:34 +00008471 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
danielk1977003ba062004-11-04 02:57:33 +00008472 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00008473 return rc;
8474 }
danielk1977003ba062004-11-04 02:57:33 +00008475
8476 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00008477 /* pgnoRoot is the page that will be used for the root-page of
8478 ** the new table (assuming an error did not occur). But we were
8479 ** allocated pgnoMove. If required (i.e. if it was not allocated
8480 ** by extending the file), the current page at position pgnoMove
8481 ** is already journaled.
8482 */
drheeb844a2009-08-08 18:01:07 +00008483 u8 eType = 0;
8484 Pgno iPtrPage = 0;
danielk1977003ba062004-11-04 02:57:33 +00008485
danf7679ad2013-04-03 11:38:36 +00008486 /* Save the positions of any open cursors. This is required in
8487 ** case they are holding a reference to an xFetch reference
8488 ** corresponding to page pgnoRoot. */
8489 rc = saveAllCursors(pBt, 0, 0);
danielk1977003ba062004-11-04 02:57:33 +00008490 releasePage(pPageMove);
danf7679ad2013-04-03 11:38:36 +00008491 if( rc!=SQLITE_OK ){
8492 return rc;
8493 }
danielk1977f35843b2007-04-07 15:03:17 +00008494
8495 /* Move the page currently at pgnoRoot to pgnoMove. */
drhb00fc3b2013-08-21 23:42:32 +00008496 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00008497 if( rc!=SQLITE_OK ){
8498 return rc;
8499 }
8500 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drh27731d72009-06-22 12:05:10 +00008501 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
8502 rc = SQLITE_CORRUPT_BKPT;
8503 }
8504 if( rc!=SQLITE_OK ){
danielk1977003ba062004-11-04 02:57:33 +00008505 releasePage(pRoot);
8506 return rc;
8507 }
drhccae6022005-02-26 17:31:26 +00008508 assert( eType!=PTRMAP_ROOTPAGE );
8509 assert( eType!=PTRMAP_FREEPAGE );
danielk19774c999992008-07-16 18:17:55 +00008510 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +00008511 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00008512
8513 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00008514 if( rc!=SQLITE_OK ){
8515 return rc;
8516 }
drhb00fc3b2013-08-21 23:42:32 +00008517 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00008518 if( rc!=SQLITE_OK ){
8519 return rc;
8520 }
danielk19773b8a05f2007-03-19 17:44:26 +00008521 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00008522 if( rc!=SQLITE_OK ){
8523 releasePage(pRoot);
8524 return rc;
8525 }
8526 }else{
8527 pRoot = pPageMove;
8528 }
8529
danielk197742741be2005-01-08 12:42:39 +00008530 /* Update the pointer-map and meta-data with the new root-page number. */
drh98add2e2009-07-20 17:11:49 +00008531 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
danielk1977003ba062004-11-04 02:57:33 +00008532 if( rc ){
8533 releasePage(pRoot);
8534 return rc;
8535 }
drhbf592832010-03-30 15:51:12 +00008536
8537 /* When the new root page was allocated, page 1 was made writable in
8538 ** order either to increase the database filesize, or to decrement the
8539 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
8540 */
8541 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
danielk1977aef0bf62005-12-30 16:28:01 +00008542 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
drhbf592832010-03-30 15:51:12 +00008543 if( NEVER(rc) ){
danielk1977003ba062004-11-04 02:57:33 +00008544 releasePage(pRoot);
8545 return rc;
8546 }
danielk197742741be2005-01-08 12:42:39 +00008547
danielk1977003ba062004-11-04 02:57:33 +00008548 }else{
drh4f0c5872007-03-26 22:05:01 +00008549 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00008550 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00008551 }
8552#endif
danielk19773b8a05f2007-03-19 17:44:26 +00008553 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhd4187c72010-08-30 22:15:45 +00008554 if( createTabFlags & BTREE_INTKEY ){
8555 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
8556 }else{
8557 ptfFlags = PTF_ZERODATA | PTF_LEAF;
8558 }
8559 zeroPage(pRoot, ptfFlags);
danielk19773b8a05f2007-03-19 17:44:26 +00008560 sqlite3PagerUnref(pRoot->pDbPage);
drhd4187c72010-08-30 22:15:45 +00008561 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
drh8b2f49b2001-06-08 00:21:52 +00008562 *piTable = (int)pgnoRoot;
8563 return SQLITE_OK;
8564}
drhd677b3d2007-08-20 22:48:41 +00008565int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
8566 int rc;
8567 sqlite3BtreeEnter(p);
8568 rc = btreeCreateTable(p, piTable, flags);
8569 sqlite3BtreeLeave(p);
8570 return rc;
8571}
drh8b2f49b2001-06-08 00:21:52 +00008572
8573/*
8574** Erase the given database page and all its children. Return
8575** the page to the freelist.
8576*/
drh4b70f112004-05-02 21:12:19 +00008577static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00008578 BtShared *pBt, /* The BTree that contains the table */
drh7ab641f2009-11-24 02:37:02 +00008579 Pgno pgno, /* Page number to clear */
8580 int freePageFlag, /* Deallocate page if true */
8581 int *pnChange /* Add number of Cells freed to this counter */
drh4b70f112004-05-02 21:12:19 +00008582){
danielk1977146ba992009-07-22 14:08:13 +00008583 MemPage *pPage;
drh8b2f49b2001-06-08 00:21:52 +00008584 int rc;
drh4b70f112004-05-02 21:12:19 +00008585 unsigned char *pCell;
8586 int i;
dan8ce71842014-01-14 20:14:09 +00008587 int hdr;
drh80159da2016-12-09 17:32:51 +00008588 CellInfo info;
drh8b2f49b2001-06-08 00:21:52 +00008589
drh1fee73e2007-08-29 04:00:57 +00008590 assert( sqlite3_mutex_held(pBt->mutex) );
drhb1299152010-03-30 22:58:33 +00008591 if( pgno>btreePagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00008592 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00008593 }
drh28f58dd2015-06-27 19:45:03 +00008594 rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
danielk1977146ba992009-07-22 14:08:13 +00008595 if( rc ) return rc;
drhccf46d02015-04-01 13:21:33 +00008596 if( pPage->bBusy ){
8597 rc = SQLITE_CORRUPT_BKPT;
8598 goto cleardatabasepage_out;
8599 }
8600 pPage->bBusy = 1;
dan8ce71842014-01-14 20:14:09 +00008601 hdr = pPage->hdrOffset;
drh4b70f112004-05-02 21:12:19 +00008602 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00008603 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00008604 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00008605 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00008606 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00008607 }
drh80159da2016-12-09 17:32:51 +00008608 rc = clearCell(pPage, pCell, &info);
danielk19776b456a22005-03-21 04:04:02 +00008609 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00008610 }
drha34b6762004-05-07 13:30:42 +00008611 if( !pPage->leaf ){
dan8ce71842014-01-14 20:14:09 +00008612 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00008613 if( rc ) goto cleardatabasepage_out;
danielk1977c7af4842008-10-27 13:59:33 +00008614 }else if( pnChange ){
drhafe028a2015-05-22 13:09:50 +00008615 assert( pPage->intKey || CORRUPT_DB );
8616 testcase( !pPage->intKey );
danielk1977c7af4842008-10-27 13:59:33 +00008617 *pnChange += pPage->nCell;
drh2aa679f2001-06-25 02:11:07 +00008618 }
8619 if( freePageFlag ){
drhc314dc72009-07-21 11:52:34 +00008620 freePage(pPage, &rc);
danielk19773b8a05f2007-03-19 17:44:26 +00008621 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
dan8ce71842014-01-14 20:14:09 +00008622 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00008623 }
danielk19776b456a22005-03-21 04:04:02 +00008624
8625cleardatabasepage_out:
drhccf46d02015-04-01 13:21:33 +00008626 pPage->bBusy = 0;
drh4b70f112004-05-02 21:12:19 +00008627 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00008628 return rc;
drh8b2f49b2001-06-08 00:21:52 +00008629}
8630
8631/*
drhab01f612004-05-22 02:55:23 +00008632** Delete all information from a single table in the database. iTable is
8633** the page number of the root of the table. After this routine returns,
8634** the root page is empty, but still exists.
8635**
8636** This routine will fail with SQLITE_LOCKED if there are any open
8637** read cursors on the table. Open write cursors are moved to the
8638** root of the table.
danielk1977c7af4842008-10-27 13:59:33 +00008639**
8640** If pnChange is not NULL, then table iTable must be an intkey table. The
8641** integer value pointed to by pnChange is incremented by the number of
8642** entries in the table.
drh8b2f49b2001-06-08 00:21:52 +00008643*/
danielk1977c7af4842008-10-27 13:59:33 +00008644int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
drh8b2f49b2001-06-08 00:21:52 +00008645 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00008646 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00008647 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00008648 assert( p->inTrans==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +00008649
drhc046e3e2009-07-15 11:26:44 +00008650 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
drhd60f4f42012-03-23 14:23:52 +00008651
drhc046e3e2009-07-15 11:26:44 +00008652 if( SQLITE_OK==rc ){
drhd60f4f42012-03-23 14:23:52 +00008653 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
8654 ** is the root of a table b-tree - if it is not, the following call is
8655 ** a no-op). */
8656 invalidateIncrblobCursors(p, 0, 1);
danielk197762c14b32008-11-19 09:05:26 +00008657 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
drh8b2f49b2001-06-08 00:21:52 +00008658 }
drhd677b3d2007-08-20 22:48:41 +00008659 sqlite3BtreeLeave(p);
8660 return rc;
drh8b2f49b2001-06-08 00:21:52 +00008661}
8662
8663/*
drh079a3072014-03-19 14:10:55 +00008664** Delete all information from the single table that pCur is open on.
8665**
8666** This routine only work for pCur on an ephemeral table.
8667*/
8668int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
8669 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
8670}
8671
8672/*
drh8b2f49b2001-06-08 00:21:52 +00008673** Erase all information in a table and add the root of the table to
8674** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00008675** page 1) is never added to the freelist.
8676**
8677** This routine will fail with SQLITE_LOCKED if there are any open
8678** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00008679**
8680** If AUTOVACUUM is enabled and the page at iTable is not the last
8681** root page in the database file, then the last root page
8682** in the database file is moved into the slot formerly occupied by
8683** iTable and that last slot formerly occupied by the last root page
8684** is added to the freelist instead of iTable. In this say, all
8685** root pages are kept at the beginning of the database file, which
8686** is necessary for AUTOVACUUM to work right. *piMoved is set to the
8687** page number that used to be the last root page in the file before
8688** the move. If no page gets moved, *piMoved is set to 0.
8689** The last root page is recorded in meta[3] and the value of
8690** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00008691*/
danielk197789d40042008-11-17 14:20:56 +00008692static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00008693 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00008694 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00008695 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00008696
drh1fee73e2007-08-29 04:00:57 +00008697 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00008698 assert( p->inTrans==TRANS_WRITE );
drh65f38d92016-11-22 01:26:42 +00008699 assert( iTable>=2 );
drh055f2982016-01-15 15:06:41 +00008700
drhb00fc3b2013-08-21 23:42:32 +00008701 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00008702 if( rc ) return rc;
danielk1977c7af4842008-10-27 13:59:33 +00008703 rc = sqlite3BtreeClearTable(p, iTable, 0);
danielk19776b456a22005-03-21 04:04:02 +00008704 if( rc ){
8705 releasePage(pPage);
8706 return rc;
8707 }
danielk1977a0bf2652004-11-04 14:30:04 +00008708
drh205f48e2004-11-05 00:43:11 +00008709 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00008710
danielk1977a0bf2652004-11-04 14:30:04 +00008711#ifdef SQLITE_OMIT_AUTOVACUUM
drh055f2982016-01-15 15:06:41 +00008712 freePage(pPage, &rc);
8713 releasePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00008714#else
drh055f2982016-01-15 15:06:41 +00008715 if( pBt->autoVacuum ){
8716 Pgno maxRootPgno;
8717 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00008718
drh055f2982016-01-15 15:06:41 +00008719 if( iTable==maxRootPgno ){
8720 /* If the table being dropped is the table with the largest root-page
8721 ** number in the database, put the root page on the free list.
danielk1977599fcba2004-11-08 07:13:13 +00008722 */
drhc314dc72009-07-21 11:52:34 +00008723 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00008724 releasePage(pPage);
drh055f2982016-01-15 15:06:41 +00008725 if( rc!=SQLITE_OK ){
8726 return rc;
8727 }
8728 }else{
8729 /* The table being dropped does not have the largest root-page
8730 ** number in the database. So move the page that does into the
8731 ** gap left by the deleted root-page.
8732 */
8733 MemPage *pMove;
8734 releasePage(pPage);
8735 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
8736 if( rc!=SQLITE_OK ){
8737 return rc;
8738 }
8739 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
8740 releasePage(pMove);
8741 if( rc!=SQLITE_OK ){
8742 return rc;
8743 }
8744 pMove = 0;
8745 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
8746 freePage(pMove, &rc);
8747 releasePage(pMove);
8748 if( rc!=SQLITE_OK ){
8749 return rc;
8750 }
8751 *piMoved = maxRootPgno;
danielk1977a0bf2652004-11-04 14:30:04 +00008752 }
drh055f2982016-01-15 15:06:41 +00008753
8754 /* Set the new 'max-root-page' value in the database header. This
8755 ** is the old value less one, less one more if that happens to
8756 ** be a root-page number, less one again if that is the
8757 ** PENDING_BYTE_PAGE.
drhc046e3e2009-07-15 11:26:44 +00008758 */
drh055f2982016-01-15 15:06:41 +00008759 maxRootPgno--;
8760 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
8761 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
8762 maxRootPgno--;
8763 }
8764 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
8765
8766 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
8767 }else{
8768 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00008769 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00008770 }
drh055f2982016-01-15 15:06:41 +00008771#endif
drh8b2f49b2001-06-08 00:21:52 +00008772 return rc;
8773}
drhd677b3d2007-08-20 22:48:41 +00008774int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
8775 int rc;
8776 sqlite3BtreeEnter(p);
dan7733a4d2011-09-02 18:03:16 +00008777 rc = btreeDropTable(p, iTable, piMoved);
drhd677b3d2007-08-20 22:48:41 +00008778 sqlite3BtreeLeave(p);
8779 return rc;
8780}
drh8b2f49b2001-06-08 00:21:52 +00008781
drh001bbcb2003-03-19 03:14:00 +00008782
drh8b2f49b2001-06-08 00:21:52 +00008783/*
danielk1977602b4662009-07-02 07:47:33 +00008784** This function may only be called if the b-tree connection already
8785** has a read or write transaction open on the database.
8786**
drh23e11ca2004-05-04 17:27:28 +00008787** Read the meta-information out of a database file. Meta[0]
8788** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00008789** through meta[15] are available for use by higher layers. Meta[0]
8790** is read-only, the others are read/write.
8791**
8792** The schema layer numbers meta values differently. At the schema
8793** layer (and the SetCookie and ReadCookie opcodes) the number of
8794** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh91618562014-12-19 19:28:02 +00008795**
8796** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
8797** of reading the value out of the header, it instead loads the "DataVersion"
8798** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
8799** database file. It is a number computed by the pager. But its access
8800** pattern is the same as header meta values, and so it is convenient to
8801** read it from this routine.
drh8b2f49b2001-06-08 00:21:52 +00008802*/
danielk1977602b4662009-07-02 07:47:33 +00008803void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
danielk1977aef0bf62005-12-30 16:28:01 +00008804 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00008805
drhd677b3d2007-08-20 22:48:41 +00008806 sqlite3BtreeEnter(p);
danielk1977602b4662009-07-02 07:47:33 +00008807 assert( p->inTrans>TRANS_NONE );
danielk1977e0d9e6f2009-07-03 16:25:06 +00008808 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
danielk1977602b4662009-07-02 07:47:33 +00008809 assert( pBt->pPage1 );
drh23e11ca2004-05-04 17:27:28 +00008810 assert( idx>=0 && idx<=15 );
danielk1977ea897302008-09-19 15:10:58 +00008811
drh91618562014-12-19 19:28:02 +00008812 if( idx==BTREE_DATA_VERSION ){
drh3da9c042014-12-22 18:41:21 +00008813 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
drh91618562014-12-19 19:28:02 +00008814 }else{
8815 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
8816 }
drhae157872004-08-14 19:20:09 +00008817
danielk1977602b4662009-07-02 07:47:33 +00008818 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
8819 ** database, mark the database as read-only. */
danielk1977003ba062004-11-04 02:57:33 +00008820#ifdef SQLITE_OMIT_AUTOVACUUM
drhc9166342012-01-05 23:32:06 +00008821 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
8822 pBt->btsFlags |= BTS_READ_ONLY;
8823 }
danielk1977003ba062004-11-04 02:57:33 +00008824#endif
drhae157872004-08-14 19:20:09 +00008825
drhd677b3d2007-08-20 22:48:41 +00008826 sqlite3BtreeLeave(p);
drh8b2f49b2001-06-08 00:21:52 +00008827}
8828
8829/*
drh23e11ca2004-05-04 17:27:28 +00008830** Write meta-information back into the database. Meta[0] is
8831** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00008832*/
danielk1977aef0bf62005-12-30 16:28:01 +00008833int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
8834 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00008835 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00008836 int rc;
drh23e11ca2004-05-04 17:27:28 +00008837 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00008838 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00008839 assert( p->inTrans==TRANS_WRITE );
8840 assert( pBt->pPage1!=0 );
8841 pP1 = pBt->pPage1->aData;
8842 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
8843 if( rc==SQLITE_OK ){
8844 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00008845#ifndef SQLITE_OMIT_AUTOVACUUM
danielk19770d19f7a2009-06-03 11:25:07 +00008846 if( idx==BTREE_INCR_VACUUM ){
drh64022502009-01-09 14:11:04 +00008847 assert( pBt->autoVacuum || iMeta==0 );
8848 assert( iMeta==0 || iMeta==1 );
8849 pBt->incrVacuum = (u8)iMeta;
drhd677b3d2007-08-20 22:48:41 +00008850 }
drh64022502009-01-09 14:11:04 +00008851#endif
drh5df72a52002-06-06 23:16:05 +00008852 }
drhd677b3d2007-08-20 22:48:41 +00008853 sqlite3BtreeLeave(p);
8854 return rc;
drh8b2f49b2001-06-08 00:21:52 +00008855}
drh8c42ca92001-06-22 19:15:00 +00008856
danielk1977a5533162009-02-24 10:01:51 +00008857#ifndef SQLITE_OMIT_BTREECOUNT
8858/*
8859** The first argument, pCur, is a cursor opened on some b-tree. Count the
8860** number of entries in the b-tree and write the result to *pnEntry.
8861**
8862** SQLITE_OK is returned if the operation is successfully executed.
8863** Otherwise, if an error is encountered (i.e. an IO error or database
8864** corruption) an SQLite error code is returned.
8865*/
8866int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
8867 i64 nEntry = 0; /* Value to return in *pnEntry */
8868 int rc; /* Return code */
dana205a482011-08-27 18:48:57 +00008869
8870 if( pCur->pgnoRoot==0 ){
8871 *pnEntry = 0;
8872 return SQLITE_OK;
8873 }
danielk1977a5533162009-02-24 10:01:51 +00008874 rc = moveToRoot(pCur);
8875
8876 /* Unless an error occurs, the following loop runs one iteration for each
8877 ** page in the B-Tree structure (not including overflow pages).
8878 */
8879 while( rc==SQLITE_OK ){
8880 int iIdx; /* Index of child node in parent */
8881 MemPage *pPage; /* Current page of the b-tree */
8882
8883 /* If this is a leaf page or the tree is not an int-key tree, then
8884 ** this page contains countable entries. Increment the entry counter
8885 ** accordingly.
8886 */
8887 pPage = pCur->apPage[pCur->iPage];
8888 if( pPage->leaf || !pPage->intKey ){
8889 nEntry += pPage->nCell;
8890 }
8891
8892 /* pPage is a leaf node. This loop navigates the cursor so that it
8893 ** points to the first interior cell that it points to the parent of
8894 ** the next page in the tree that has not yet been visited. The
8895 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
8896 ** of the page, or to the number of cells in the page if the next page
8897 ** to visit is the right-child of its parent.
8898 **
8899 ** If all pages in the tree have been visited, return SQLITE_OK to the
8900 ** caller.
8901 */
8902 if( pPage->leaf ){
8903 do {
8904 if( pCur->iPage==0 ){
8905 /* All pages of the b-tree have been visited. Return successfully. */
8906 *pnEntry = nEntry;
drh7efa4262014-12-16 00:08:31 +00008907 return moveToRoot(pCur);
danielk1977a5533162009-02-24 10:01:51 +00008908 }
danielk197730548662009-07-09 05:07:37 +00008909 moveToParent(pCur);
danielk1977a5533162009-02-24 10:01:51 +00008910 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
8911
8912 pCur->aiIdx[pCur->iPage]++;
8913 pPage = pCur->apPage[pCur->iPage];
8914 }
8915
8916 /* Descend to the child node of the cell that the cursor currently
8917 ** points at. This is the right-child if (iIdx==pPage->nCell).
8918 */
8919 iIdx = pCur->aiIdx[pCur->iPage];
8920 if( iIdx==pPage->nCell ){
8921 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
8922 }else{
8923 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
8924 }
8925 }
8926
shanebe217792009-03-05 04:20:31 +00008927 /* An error has occurred. Return an error code. */
danielk1977a5533162009-02-24 10:01:51 +00008928 return rc;
8929}
8930#endif
drhdd793422001-06-28 01:54:48 +00008931
drhdd793422001-06-28 01:54:48 +00008932/*
drh5eddca62001-06-30 21:53:53 +00008933** Return the pager associated with a BTree. This routine is used for
8934** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00008935*/
danielk1977aef0bf62005-12-30 16:28:01 +00008936Pager *sqlite3BtreePager(Btree *p){
8937 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00008938}
drh5eddca62001-06-30 21:53:53 +00008939
drhb7f91642004-10-31 02:22:47 +00008940#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00008941/*
8942** Append a message to the error message string.
8943*/
drh2e38c322004-09-03 18:38:44 +00008944static void checkAppendMsg(
8945 IntegrityCk *pCheck,
drh2e38c322004-09-03 18:38:44 +00008946 const char *zFormat,
8947 ...
8948){
8949 va_list ap;
drh1dcdbc02007-01-27 02:24:54 +00008950 if( !pCheck->mxErr ) return;
8951 pCheck->mxErr--;
8952 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00008953 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +00008954 if( pCheck->errMsg.nChar ){
8955 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +00008956 }
drh867db832014-09-26 02:41:05 +00008957 if( pCheck->zPfx ){
drh5f4a6862016-01-30 12:50:25 +00008958 sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
drhf089aa42008-07-08 19:34:06 +00008959 }
drh5f4a6862016-01-30 12:50:25 +00008960 sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
drhf089aa42008-07-08 19:34:06 +00008961 va_end(ap);
drhb49bc862013-08-21 21:12:10 +00008962 if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
drhc890fec2008-08-01 20:10:08 +00008963 pCheck->mallocFailed = 1;
8964 }
drh5eddca62001-06-30 21:53:53 +00008965}
drhb7f91642004-10-31 02:22:47 +00008966#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00008967
drhb7f91642004-10-31 02:22:47 +00008968#ifndef SQLITE_OMIT_INTEGRITY_CHECK
dan1235bb12012-04-03 17:43:28 +00008969
8970/*
8971** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
8972** corresponds to page iPg is already set.
8973*/
8974static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
8975 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
8976 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
8977}
8978
8979/*
8980** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
8981*/
8982static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
8983 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
8984 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
8985}
8986
8987
drh5eddca62001-06-30 21:53:53 +00008988/*
8989** Add 1 to the reference count for page iPage. If this is the second
8990** reference to the page, add an error message to pCheck->zErrMsg.
peter.d.reid60ec9142014-09-06 16:39:46 +00008991** Return 1 if there are 2 or more references to the page and 0 if
drh5eddca62001-06-30 21:53:53 +00008992** if this is the first reference to the page.
8993**
8994** Also check that the page number is in bounds.
8995*/
drh867db832014-09-26 02:41:05 +00008996static int checkRef(IntegrityCk *pCheck, Pgno iPage){
drh5eddca62001-06-30 21:53:53 +00008997 if( iPage==0 ) return 1;
danielk197789d40042008-11-17 14:20:56 +00008998 if( iPage>pCheck->nPage ){
drh867db832014-09-26 02:41:05 +00008999 checkAppendMsg(pCheck, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00009000 return 1;
9001 }
dan1235bb12012-04-03 17:43:28 +00009002 if( getPageReferenced(pCheck, iPage) ){
drh867db832014-09-26 02:41:05 +00009003 checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00009004 return 1;
9005 }
dan1235bb12012-04-03 17:43:28 +00009006 setPageReferenced(pCheck, iPage);
9007 return 0;
drh5eddca62001-06-30 21:53:53 +00009008}
9009
danielk1977afcdd022004-10-31 16:25:42 +00009010#ifndef SQLITE_OMIT_AUTOVACUUM
9011/*
9012** Check that the entry in the pointer-map for page iChild maps to
9013** page iParent, pointer type ptrType. If not, append an error message
9014** to pCheck.
9015*/
9016static void checkPtrmap(
9017 IntegrityCk *pCheck, /* Integrity check context */
9018 Pgno iChild, /* Child page number */
9019 u8 eType, /* Expected pointer map type */
drh867db832014-09-26 02:41:05 +00009020 Pgno iParent /* Expected pointer map parent page number */
danielk1977afcdd022004-10-31 16:25:42 +00009021){
9022 int rc;
9023 u8 ePtrmapType;
9024 Pgno iPtrmapParent;
9025
9026 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
9027 if( rc!=SQLITE_OK ){
drhb56cd552009-05-01 13:16:54 +00009028 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
drh867db832014-09-26 02:41:05 +00009029 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
danielk1977afcdd022004-10-31 16:25:42 +00009030 return;
9031 }
9032
9033 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
drh867db832014-09-26 02:41:05 +00009034 checkAppendMsg(pCheck,
danielk1977afcdd022004-10-31 16:25:42 +00009035 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
9036 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
9037 }
9038}
9039#endif
9040
drh5eddca62001-06-30 21:53:53 +00009041/*
9042** Check the integrity of the freelist or of an overflow page list.
9043** Verify that the number of pages on the list is N.
9044*/
drh30e58752002-03-02 20:41:57 +00009045static void checkList(
9046 IntegrityCk *pCheck, /* Integrity checking context */
9047 int isFreeList, /* True for a freelist. False for overflow page list */
9048 int iPage, /* Page number for first page in the list */
drh867db832014-09-26 02:41:05 +00009049 int N /* Expected number of pages in the list */
drh30e58752002-03-02 20:41:57 +00009050){
9051 int i;
drh3a4c1412004-05-09 20:40:11 +00009052 int expected = N;
9053 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00009054 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00009055 DbPage *pOvflPage;
9056 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00009057 if( iPage<1 ){
drh867db832014-09-26 02:41:05 +00009058 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00009059 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00009060 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00009061 break;
9062 }
drh867db832014-09-26 02:41:05 +00009063 if( checkRef(pCheck, iPage) ) break;
drh9584f582015-11-04 20:22:37 +00009064 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
drh867db832014-09-26 02:41:05 +00009065 checkAppendMsg(pCheck, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00009066 break;
9067 }
danielk19773b8a05f2007-03-19 17:44:26 +00009068 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00009069 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00009070 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00009071#ifndef SQLITE_OMIT_AUTOVACUUM
9072 if( pCheck->pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00009073 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +00009074 }
9075#endif
drh43b18e12010-08-17 19:40:08 +00009076 if( n>(int)pCheck->pBt->usableSize/4-2 ){
drh867db832014-09-26 02:41:05 +00009077 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00009078 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00009079 N--;
9080 }else{
9081 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00009082 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00009083#ifndef SQLITE_OMIT_AUTOVACUUM
9084 if( pCheck->pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00009085 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +00009086 }
9087#endif
drh867db832014-09-26 02:41:05 +00009088 checkRef(pCheck, iFreePage);
drhee696e22004-08-30 16:52:17 +00009089 }
9090 N -= n;
drh30e58752002-03-02 20:41:57 +00009091 }
drh30e58752002-03-02 20:41:57 +00009092 }
danielk1977afcdd022004-10-31 16:25:42 +00009093#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00009094 else{
9095 /* If this database supports auto-vacuum and iPage is not the last
9096 ** page in this overflow list, check that the pointer-map entry for
9097 ** the following page matches iPage.
9098 */
9099 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00009100 i = get4byte(pOvflData);
drh867db832014-09-26 02:41:05 +00009101 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
danielk1977687566d2004-11-02 12:56:41 +00009102 }
danielk1977afcdd022004-10-31 16:25:42 +00009103 }
9104#endif
danielk19773b8a05f2007-03-19 17:44:26 +00009105 iPage = get4byte(pOvflData);
9106 sqlite3PagerUnref(pOvflPage);
danad41f5e2015-09-18 14:45:01 +00009107
9108 if( isFreeList && N<(iPage!=0) ){
9109 checkAppendMsg(pCheck, "free-page count in header is too small");
9110 }
drh5eddca62001-06-30 21:53:53 +00009111 }
9112}
drhb7f91642004-10-31 02:22:47 +00009113#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00009114
drh67731a92015-04-16 11:56:03 +00009115/*
9116** An implementation of a min-heap.
9117**
9118** aHeap[0] is the number of elements on the heap. aHeap[1] is the
drha33b6832015-04-16 21:57:37 +00009119** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
drh67731a92015-04-16 11:56:03 +00009120** and aHeap[N*2+1].
9121**
9122** The heap property is this: Every node is less than or equal to both
9123** of its daughter nodes. A consequence of the heap property is that the
drh42c0a2b2015-04-28 01:28:36 +00009124** root node aHeap[1] is always the minimum value currently in the heap.
drh67731a92015-04-16 11:56:03 +00009125**
9126** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
9127** the heap, preserving the heap property. The btreeHeapPull() routine
9128** removes the root element from the heap (the minimum value in the heap)
drh42c0a2b2015-04-28 01:28:36 +00009129** and then moves other nodes around as necessary to preserve the heap
drh67731a92015-04-16 11:56:03 +00009130** property.
9131**
9132** This heap is used for cell overlap and coverage testing. Each u32
9133** entry represents the span of a cell or freeblock on a btree page.
9134** The upper 16 bits are the index of the first byte of a range and the
9135** lower 16 bits are the index of the last byte of that range.
9136*/
9137static void btreeHeapInsert(u32 *aHeap, u32 x){
9138 u32 j, i = ++aHeap[0];
9139 aHeap[i] = x;
drha33b6832015-04-16 21:57:37 +00009140 while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
drh67731a92015-04-16 11:56:03 +00009141 x = aHeap[j];
9142 aHeap[j] = aHeap[i];
9143 aHeap[i] = x;
9144 i = j;
9145 }
9146}
9147static int btreeHeapPull(u32 *aHeap, u32 *pOut){
9148 u32 j, i, x;
9149 if( (x = aHeap[0])==0 ) return 0;
9150 *pOut = aHeap[1];
9151 aHeap[1] = aHeap[x];
9152 aHeap[x] = 0xffffffff;
9153 aHeap[0]--;
9154 i = 1;
9155 while( (j = i*2)<=aHeap[0] ){
9156 if( aHeap[j]>aHeap[j+1] ) j++;
9157 if( aHeap[i]<aHeap[j] ) break;
9158 x = aHeap[i];
9159 aHeap[i] = aHeap[j];
9160 aHeap[j] = x;
9161 i = j;
9162 }
9163 return 1;
9164}
9165
drhb7f91642004-10-31 02:22:47 +00009166#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00009167/*
9168** Do various sanity checks on a single page of a tree. Return
9169** the tree depth. Root pages return 0. Parents of root pages
9170** return 1, and so forth.
9171**
9172** These checks are done:
9173**
9174** 1. Make sure that cells and freeblocks do not overlap
9175** but combine to completely cover the page.
drhe05b3f82015-07-01 17:53:49 +00009176** 2. Make sure integer cell keys are in order.
9177** 3. Check the integrity of overflow pages.
9178** 4. Recursively call checkTreePage on all children.
9179** 5. Verify that the depth of all children is the same.
drh5eddca62001-06-30 21:53:53 +00009180*/
9181static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00009182 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00009183 int iPage, /* Page number of the page to check */
drhcbc6b712015-07-02 16:17:30 +00009184 i64 *piMinKey, /* Write minimum integer primary key here */
9185 i64 maxKey /* Error if integer primary key greater than this */
drh5eddca62001-06-30 21:53:53 +00009186){
drhcbc6b712015-07-02 16:17:30 +00009187 MemPage *pPage = 0; /* The page being analyzed */
9188 int i; /* Loop counter */
9189 int rc; /* Result code from subroutine call */
9190 int depth = -1, d2; /* Depth of a subtree */
9191 int pgno; /* Page number */
9192 int nFrag; /* Number of fragmented bytes on the page */
9193 int hdr; /* Offset to the page header */
9194 int cellStart; /* Offset to the start of the cell pointer array */
9195 int nCell; /* Number of cells */
9196 int doCoverageCheck = 1; /* True if cell coverage checking should be done */
9197 int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
9198 ** False if IPK must be strictly less than maxKey */
9199 u8 *data; /* Page content */
9200 u8 *pCell; /* Cell content */
9201 u8 *pCellIdx; /* Next element of the cell pointer array */
9202 BtShared *pBt; /* The BtShared object that owns pPage */
9203 u32 pc; /* Address of a cell */
9204 u32 usableSize; /* Usable size of the page */
9205 u32 contentOffset; /* Offset to the start of the cell content area */
9206 u32 *heap = 0; /* Min-heap used for checking cell coverage */
drhd2dc87f2015-07-02 19:47:08 +00009207 u32 x, prev = 0; /* Next and previous entry on the min-heap */
drh867db832014-09-26 02:41:05 +00009208 const char *saved_zPfx = pCheck->zPfx;
9209 int saved_v1 = pCheck->v1;
9210 int saved_v2 = pCheck->v2;
mistachkin532f1792015-07-14 17:18:05 +00009211 u8 savedIsInit = 0;
danielk1977ef73ee92004-11-06 12:26:07 +00009212
drh5eddca62001-06-30 21:53:53 +00009213 /* Check that the page exists
9214 */
drhd9cb6ac2005-10-20 07:28:17 +00009215 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00009216 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00009217 if( iPage==0 ) return 0;
drh867db832014-09-26 02:41:05 +00009218 if( checkRef(pCheck, iPage) ) return 0;
9219 pCheck->zPfx = "Page %d: ";
9220 pCheck->v1 = iPage;
drhb00fc3b2013-08-21 23:42:32 +00009221 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drh867db832014-09-26 02:41:05 +00009222 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00009223 "unable to get the page. error code=%d", rc);
drh867db832014-09-26 02:41:05 +00009224 goto end_of_check;
drh5eddca62001-06-30 21:53:53 +00009225 }
danielk197793caf5a2009-07-11 06:55:33 +00009226
9227 /* Clear MemPage.isInit to make sure the corruption detection code in
9228 ** btreeInitPage() is executed. */
drh72e191e2015-07-04 11:14:20 +00009229 savedIsInit = pPage->isInit;
danielk197793caf5a2009-07-11 06:55:33 +00009230 pPage->isInit = 0;
danielk197730548662009-07-09 05:07:37 +00009231 if( (rc = btreeInitPage(pPage))!=0 ){
drh64022502009-01-09 14:11:04 +00009232 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
drh867db832014-09-26 02:41:05 +00009233 checkAppendMsg(pCheck,
danielk197730548662009-07-09 05:07:37 +00009234 "btreeInitPage() returns error code %d", rc);
drh867db832014-09-26 02:41:05 +00009235 goto end_of_check;
drh5eddca62001-06-30 21:53:53 +00009236 }
drhcbc6b712015-07-02 16:17:30 +00009237 data = pPage->aData;
9238 hdr = pPage->hdrOffset;
drh5eddca62001-06-30 21:53:53 +00009239
drhcbc6b712015-07-02 16:17:30 +00009240 /* Set up for cell analysis */
drhe05b3f82015-07-01 17:53:49 +00009241 pCheck->zPfx = "On tree page %d cell %d: ";
drhcbc6b712015-07-02 16:17:30 +00009242 contentOffset = get2byteNotZero(&data[hdr+5]);
9243 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
9244
9245 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
9246 ** number of cells on the page. */
9247 nCell = get2byte(&data[hdr+3]);
9248 assert( pPage->nCell==nCell );
9249
9250 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
9251 ** immediately follows the b-tree page header. */
9252 cellStart = hdr + 12 - 4*pPage->leaf;
9253 assert( pPage->aCellIdx==&data[cellStart] );
9254 pCellIdx = &data[cellStart + 2*(nCell-1)];
9255
9256 if( !pPage->leaf ){
9257 /* Analyze the right-child page of internal pages */
9258 pgno = get4byte(&data[hdr+8]);
9259#ifndef SQLITE_OMIT_AUTOVACUUM
9260 if( pBt->autoVacuum ){
9261 pCheck->zPfx = "On page %d at right child: ";
9262 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
9263 }
9264#endif
9265 depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
9266 keyCanBeEqual = 0;
9267 }else{
9268 /* For leaf pages, the coverage check will occur in the same loop
9269 ** as the other cell checks, so initialize the heap. */
9270 heap = pCheck->heap;
9271 heap[0] = 0;
drh5eddca62001-06-30 21:53:53 +00009272 }
9273
drhcbc6b712015-07-02 16:17:30 +00009274 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
9275 ** integer offsets to the cell contents. */
9276 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
drh6f11bef2004-05-13 01:12:56 +00009277 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00009278
drhcbc6b712015-07-02 16:17:30 +00009279 /* Check cell size */
drh867db832014-09-26 02:41:05 +00009280 pCheck->v2 = i;
drhcbc6b712015-07-02 16:17:30 +00009281 assert( pCellIdx==&data[cellStart + i*2] );
9282 pc = get2byteAligned(pCellIdx);
9283 pCellIdx -= 2;
9284 if( pc<contentOffset || pc>usableSize-4 ){
9285 checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
9286 pc, contentOffset, usableSize-4);
9287 doCoverageCheck = 0;
9288 continue;
shaneh195475d2010-02-19 04:28:08 +00009289 }
drhcbc6b712015-07-02 16:17:30 +00009290 pCell = &data[pc];
9291 pPage->xParseCell(pPage, pCell, &info);
9292 if( pc+info.nSize>usableSize ){
9293 checkAppendMsg(pCheck, "Extends off end of page");
9294 doCoverageCheck = 0;
9295 continue;
drh5eddca62001-06-30 21:53:53 +00009296 }
9297
drhcbc6b712015-07-02 16:17:30 +00009298 /* Check for integer primary key out of range */
9299 if( pPage->intKey ){
9300 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
9301 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
9302 }
9303 maxKey = info.nKey;
9304 }
9305
9306 /* Check the content overflow list */
9307 if( info.nPayload>info.nLocal ){
9308 int nPage; /* Number of pages on the overflow chain */
9309 Pgno pgnoOvfl; /* First page of the overflow chain */
drh45ac1c72015-12-18 03:59:16 +00009310 assert( pc + info.nSize - 4 <= usableSize );
drhcbc6b712015-07-02 16:17:30 +00009311 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
drh45ac1c72015-12-18 03:59:16 +00009312 pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
drhda200cc2004-05-09 11:51:38 +00009313#ifndef SQLITE_OMIT_AUTOVACUUM
9314 if( pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00009315 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
drhda200cc2004-05-09 11:51:38 +00009316 }
9317#endif
drh867db832014-09-26 02:41:05 +00009318 checkList(pCheck, 0, pgnoOvfl, nPage);
drh5eddca62001-06-30 21:53:53 +00009319 }
9320
drh5eddca62001-06-30 21:53:53 +00009321 if( !pPage->leaf ){
drhcbc6b712015-07-02 16:17:30 +00009322 /* Check sanity of left child page for internal pages */
drh43605152004-05-29 21:46:49 +00009323 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00009324#ifndef SQLITE_OMIT_AUTOVACUUM
9325 if( pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00009326 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
danielk1977afcdd022004-10-31 16:25:42 +00009327 }
9328#endif
drhcbc6b712015-07-02 16:17:30 +00009329 d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
9330 keyCanBeEqual = 0;
9331 if( d2!=depth ){
drh867db832014-09-26 02:41:05 +00009332 checkAppendMsg(pCheck, "Child page depth differs");
drhcbc6b712015-07-02 16:17:30 +00009333 depth = d2;
drh5eddca62001-06-30 21:53:53 +00009334 }
drhcbc6b712015-07-02 16:17:30 +00009335 }else{
9336 /* Populate the coverage-checking heap for leaf pages */
9337 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
drh5eddca62001-06-30 21:53:53 +00009338 }
9339 }
drhcbc6b712015-07-02 16:17:30 +00009340 *piMinKey = maxKey;
shaneh195475d2010-02-19 04:28:08 +00009341
drh5eddca62001-06-30 21:53:53 +00009342 /* Check for complete coverage of the page
9343 */
drh867db832014-09-26 02:41:05 +00009344 pCheck->zPfx = 0;
drhcbc6b712015-07-02 16:17:30 +00009345 if( doCoverageCheck && pCheck->mxErr>0 ){
9346 /* For leaf pages, the min-heap has already been initialized and the
9347 ** cells have already been inserted. But for internal pages, that has
9348 ** not yet been done, so do it now */
9349 if( !pPage->leaf ){
9350 heap = pCheck->heap;
9351 heap[0] = 0;
drhcbc6b712015-07-02 16:17:30 +00009352 for(i=nCell-1; i>=0; i--){
drh1910def2015-07-02 16:29:56 +00009353 u32 size;
9354 pc = get2byteAligned(&data[cellStart+i*2]);
9355 size = pPage->xCellSize(pPage, &data[pc]);
drh67731a92015-04-16 11:56:03 +00009356 btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
danielk19777701e812005-01-10 12:59:51 +00009357 }
drh2e38c322004-09-03 18:38:44 +00009358 }
drhcbc6b712015-07-02 16:17:30 +00009359 /* Add the freeblocks to the min-heap
9360 **
9361 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
drhfdab0262014-11-20 15:30:50 +00009362 ** is the offset of the first freeblock, or zero if there are no
drhcbc6b712015-07-02 16:17:30 +00009363 ** freeblocks on the page.
9364 */
drh8c2bbb62009-07-10 02:52:20 +00009365 i = get2byte(&data[hdr+1]);
9366 while( i>0 ){
9367 int size, j;
mistachkinc29cbb02015-07-02 16:52:01 +00009368 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
drh8c2bbb62009-07-10 02:52:20 +00009369 size = get2byte(&data[i+2]);
mistachkinc29cbb02015-07-02 16:52:01 +00009370 assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
drhe56d4302015-07-08 01:22:52 +00009371 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
drhfdab0262014-11-20 15:30:50 +00009372 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
9373 ** big-endian integer which is the offset in the b-tree page of the next
9374 ** freeblock in the chain, or zero if the freeblock is the last on the
9375 ** chain. */
drh8c2bbb62009-07-10 02:52:20 +00009376 j = get2byte(&data[i]);
drhfdab0262014-11-20 15:30:50 +00009377 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
9378 ** increasing offset. */
drh8c2bbb62009-07-10 02:52:20 +00009379 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
mistachkinc29cbb02015-07-02 16:52:01 +00009380 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
drh8c2bbb62009-07-10 02:52:20 +00009381 i = j;
drh2e38c322004-09-03 18:38:44 +00009382 }
drhcbc6b712015-07-02 16:17:30 +00009383 /* Analyze the min-heap looking for overlap between cells and/or
9384 ** freeblocks, and counting the number of untracked bytes in nFrag.
drhd2dc87f2015-07-02 19:47:08 +00009385 **
9386 ** Each min-heap entry is of the form: (start_address<<16)|end_address.
9387 ** There is an implied first entry the covers the page header, the cell
9388 ** pointer index, and the gap between the cell pointer index and the start
9389 ** of cell content.
9390 **
9391 ** The loop below pulls entries from the min-heap in order and compares
9392 ** the start_address against the previous end_address. If there is an
9393 ** overlap, that means bytes are used multiple times. If there is a gap,
9394 ** that gap is added to the fragmentation count.
drhcbc6b712015-07-02 16:17:30 +00009395 */
9396 nFrag = 0;
drhd2dc87f2015-07-02 19:47:08 +00009397 prev = contentOffset - 1; /* Implied first min-heap entry */
drh67731a92015-04-16 11:56:03 +00009398 while( btreeHeapPull(heap,&x) ){
drhd2dc87f2015-07-02 19:47:08 +00009399 if( (prev&0xffff)>=(x>>16) ){
drh867db832014-09-26 02:41:05 +00009400 checkAppendMsg(pCheck,
drh67731a92015-04-16 11:56:03 +00009401 "Multiple uses for byte %u of page %d", x>>16, iPage);
drh2e38c322004-09-03 18:38:44 +00009402 break;
drh67731a92015-04-16 11:56:03 +00009403 }else{
drhcbc6b712015-07-02 16:17:30 +00009404 nFrag += (x>>16) - (prev&0xffff) - 1;
drh67731a92015-04-16 11:56:03 +00009405 prev = x;
drh2e38c322004-09-03 18:38:44 +00009406 }
9407 }
drhcbc6b712015-07-02 16:17:30 +00009408 nFrag += usableSize - (prev&0xffff) - 1;
drhfdab0262014-11-20 15:30:50 +00009409 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
9410 ** is stored in the fifth field of the b-tree page header.
9411 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
9412 ** number of fragmented free bytes within the cell content area.
9413 */
drhcbc6b712015-07-02 16:17:30 +00009414 if( heap[0]==0 && nFrag!=data[hdr+7] ){
drh867db832014-09-26 02:41:05 +00009415 checkAppendMsg(pCheck,
drh8c2bbb62009-07-10 02:52:20 +00009416 "Fragmentation of %d bytes reported as %d on page %d",
drhcbc6b712015-07-02 16:17:30 +00009417 nFrag, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00009418 }
9419 }
drh867db832014-09-26 02:41:05 +00009420
9421end_of_check:
drh72e191e2015-07-04 11:14:20 +00009422 if( !doCoverageCheck ) pPage->isInit = savedIsInit;
drh4b70f112004-05-02 21:12:19 +00009423 releasePage(pPage);
drh867db832014-09-26 02:41:05 +00009424 pCheck->zPfx = saved_zPfx;
9425 pCheck->v1 = saved_v1;
9426 pCheck->v2 = saved_v2;
drhda200cc2004-05-09 11:51:38 +00009427 return depth+1;
drh5eddca62001-06-30 21:53:53 +00009428}
drhb7f91642004-10-31 02:22:47 +00009429#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00009430
drhb7f91642004-10-31 02:22:47 +00009431#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00009432/*
9433** This routine does a complete check of the given BTree file. aRoot[] is
9434** an array of pages numbers were each page number is the root page of
9435** a table. nRoot is the number of entries in aRoot.
9436**
danielk19773509a652009-07-06 18:56:13 +00009437** A read-only or read-write transaction must be opened before calling
9438** this function.
9439**
drhc890fec2008-08-01 20:10:08 +00009440** Write the number of error seen in *pnErr. Except for some memory
drhe43ba702008-12-05 22:40:08 +00009441** allocation errors, an error message held in memory obtained from
drhc890fec2008-08-01 20:10:08 +00009442** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
drhe43ba702008-12-05 22:40:08 +00009443** returned. If a memory allocation error occurs, NULL is returned.
drh5eddca62001-06-30 21:53:53 +00009444*/
drh1dcdbc02007-01-27 02:24:54 +00009445char *sqlite3BtreeIntegrityCheck(
9446 Btree *p, /* The btree to be checked */
9447 int *aRoot, /* An array of root pages numbers for individual trees */
9448 int nRoot, /* Number of entries in aRoot[] */
9449 int mxErr, /* Stop reporting errors after this many */
9450 int *pnErr /* Write number of errors seen to this variable */
9451){
danielk197789d40042008-11-17 14:20:56 +00009452 Pgno i;
drhaaab5722002-02-19 13:39:21 +00009453 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00009454 BtShared *pBt = p->pBt;
drhcbc6b712015-07-02 16:17:30 +00009455 int savedDbFlags = pBt->db->flags;
drhf089aa42008-07-08 19:34:06 +00009456 char zErr[100];
drhcbc6b712015-07-02 16:17:30 +00009457 VVA_ONLY( int nRef );
drh5eddca62001-06-30 21:53:53 +00009458
drhd677b3d2007-08-20 22:48:41 +00009459 sqlite3BtreeEnter(p);
danielk19773509a652009-07-06 18:56:13 +00009460 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
drhcc5f8a42016-02-06 22:32:06 +00009461 VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
9462 assert( nRef>=0 );
drh5eddca62001-06-30 21:53:53 +00009463 sCheck.pBt = pBt;
9464 sCheck.pPager = pBt->pPager;
drhb1299152010-03-30 22:58:33 +00009465 sCheck.nPage = btreePagecount(sCheck.pBt);
drh1dcdbc02007-01-27 02:24:54 +00009466 sCheck.mxErr = mxErr;
9467 sCheck.nErr = 0;
drhc890fec2008-08-01 20:10:08 +00009468 sCheck.mallocFailed = 0;
drh867db832014-09-26 02:41:05 +00009469 sCheck.zPfx = 0;
9470 sCheck.v1 = 0;
9471 sCheck.v2 = 0;
drhe05b3f82015-07-01 17:53:49 +00009472 sCheck.aPgRef = 0;
9473 sCheck.heap = 0;
9474 sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
drh5f4a6862016-01-30 12:50:25 +00009475 sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
drh0de8c112002-07-06 16:32:14 +00009476 if( sCheck.nPage==0 ){
drhe05b3f82015-07-01 17:53:49 +00009477 goto integrity_ck_cleanup;
drh0de8c112002-07-06 16:32:14 +00009478 }
dan1235bb12012-04-03 17:43:28 +00009479
9480 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
9481 if( !sCheck.aPgRef ){
drhe05b3f82015-07-01 17:53:49 +00009482 sCheck.mallocFailed = 1;
9483 goto integrity_ck_cleanup;
danielk1977ac245ec2005-01-14 13:50:11 +00009484 }
drhe05b3f82015-07-01 17:53:49 +00009485 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
9486 if( sCheck.heap==0 ){
9487 sCheck.mallocFailed = 1;
9488 goto integrity_ck_cleanup;
9489 }
9490
drh42cac6d2004-11-20 20:31:11 +00009491 i = PENDING_BYTE_PAGE(pBt);
dan1235bb12012-04-03 17:43:28 +00009492 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
drh5eddca62001-06-30 21:53:53 +00009493
9494 /* Check the integrity of the freelist
9495 */
drh867db832014-09-26 02:41:05 +00009496 sCheck.zPfx = "Main freelist: ";
drha34b6762004-05-07 13:30:42 +00009497 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
drh867db832014-09-26 02:41:05 +00009498 get4byte(&pBt->pPage1->aData[36]));
9499 sCheck.zPfx = 0;
drh5eddca62001-06-30 21:53:53 +00009500
9501 /* Check all the tables.
9502 */
drhcbc6b712015-07-02 16:17:30 +00009503 testcase( pBt->db->flags & SQLITE_CellSizeCk );
9504 pBt->db->flags &= ~SQLITE_CellSizeCk;
danielk197789d40042008-11-17 14:20:56 +00009505 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
drhcbc6b712015-07-02 16:17:30 +00009506 i64 notUsed;
drh4ff6dfa2002-03-03 23:06:00 +00009507 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00009508#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00009509 if( pBt->autoVacuum && aRoot[i]>1 ){
drh867db832014-09-26 02:41:05 +00009510 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +00009511 }
9512#endif
drhcbc6b712015-07-02 16:17:30 +00009513 checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
drh5eddca62001-06-30 21:53:53 +00009514 }
drhcbc6b712015-07-02 16:17:30 +00009515 pBt->db->flags = savedDbFlags;
drh5eddca62001-06-30 21:53:53 +00009516
9517 /* Make sure every page in the file is referenced
9518 */
drh1dcdbc02007-01-27 02:24:54 +00009519 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00009520#ifdef SQLITE_OMIT_AUTOVACUUM
dan1235bb12012-04-03 17:43:28 +00009521 if( getPageReferenced(&sCheck, i)==0 ){
drh867db832014-09-26 02:41:05 +00009522 checkAppendMsg(&sCheck, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00009523 }
danielk1977afcdd022004-10-31 16:25:42 +00009524#else
9525 /* If the database supports auto-vacuum, make sure no tables contain
9526 ** references to pointer-map pages.
9527 */
dan1235bb12012-04-03 17:43:28 +00009528 if( getPageReferenced(&sCheck, i)==0 &&
danielk1977266664d2006-02-10 08:24:21 +00009529 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
drh867db832014-09-26 02:41:05 +00009530 checkAppendMsg(&sCheck, "Page %d is never used", i);
danielk1977afcdd022004-10-31 16:25:42 +00009531 }
dan1235bb12012-04-03 17:43:28 +00009532 if( getPageReferenced(&sCheck, i)!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00009533 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
drh867db832014-09-26 02:41:05 +00009534 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
danielk1977afcdd022004-10-31 16:25:42 +00009535 }
9536#endif
drh5eddca62001-06-30 21:53:53 +00009537 }
9538
drh5eddca62001-06-30 21:53:53 +00009539 /* Clean up and report errors.
9540 */
drhe05b3f82015-07-01 17:53:49 +00009541integrity_ck_cleanup:
9542 sqlite3PageFree(sCheck.heap);
dan1235bb12012-04-03 17:43:28 +00009543 sqlite3_free(sCheck.aPgRef);
drhc890fec2008-08-01 20:10:08 +00009544 if( sCheck.mallocFailed ){
9545 sqlite3StrAccumReset(&sCheck.errMsg);
drhe05b3f82015-07-01 17:53:49 +00009546 sCheck.nErr++;
drhc890fec2008-08-01 20:10:08 +00009547 }
drh1dcdbc02007-01-27 02:24:54 +00009548 *pnErr = sCheck.nErr;
drhf089aa42008-07-08 19:34:06 +00009549 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
drhe05b3f82015-07-01 17:53:49 +00009550 /* Make sure this analysis did not leave any unref() pages. */
9551 assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
9552 sqlite3BtreeLeave(p);
drhf089aa42008-07-08 19:34:06 +00009553 return sqlite3StrAccumFinish(&sCheck.errMsg);
drh5eddca62001-06-30 21:53:53 +00009554}
drhb7f91642004-10-31 02:22:47 +00009555#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00009556
drh73509ee2003-04-06 20:44:45 +00009557/*
drhd4e0bb02012-05-27 01:19:04 +00009558** Return the full pathname of the underlying database file. Return
9559** an empty string if the database is in-memory or a TEMP database.
drhd0679ed2007-08-28 22:24:34 +00009560**
9561** The pager filename is invariant as long as the pager is
9562** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00009563*/
danielk1977aef0bf62005-12-30 16:28:01 +00009564const char *sqlite3BtreeGetFilename(Btree *p){
9565 assert( p->pBt->pPager!=0 );
drhd4e0bb02012-05-27 01:19:04 +00009566 return sqlite3PagerFilename(p->pBt->pPager, 1);
drh73509ee2003-04-06 20:44:45 +00009567}
9568
9569/*
danielk19775865e3d2004-06-14 06:03:57 +00009570** Return the pathname of the journal file for this database. The return
9571** value of this routine is the same regardless of whether the journal file
9572** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00009573**
9574** The pager journal filename is invariant as long as the pager is
9575** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00009576*/
danielk1977aef0bf62005-12-30 16:28:01 +00009577const char *sqlite3BtreeGetJournalname(Btree *p){
9578 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00009579 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00009580}
9581
danielk19771d850a72004-05-31 08:26:49 +00009582/*
9583** Return non-zero if a transaction is active.
9584*/
danielk1977aef0bf62005-12-30 16:28:01 +00009585int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00009586 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00009587 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00009588}
9589
dana550f2d2010-08-02 10:47:05 +00009590#ifndef SQLITE_OMIT_WAL
9591/*
9592** Run a checkpoint on the Btree passed as the first argument.
9593**
9594** Return SQLITE_LOCKED if this or any other connection has an open
9595** transaction on the shared-cache the argument Btree is connected to.
dana58f26f2010-11-16 18:56:51 +00009596**
dancdc1f042010-11-18 12:11:05 +00009597** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
dana550f2d2010-08-02 10:47:05 +00009598*/
dancdc1f042010-11-18 12:11:05 +00009599int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
dana550f2d2010-08-02 10:47:05 +00009600 int rc = SQLITE_OK;
9601 if( p ){
9602 BtShared *pBt = p->pBt;
9603 sqlite3BtreeEnter(p);
9604 if( pBt->inTransaction!=TRANS_NONE ){
9605 rc = SQLITE_LOCKED;
9606 }else{
dan7fb89902016-08-12 16:21:15 +00009607 rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
dana550f2d2010-08-02 10:47:05 +00009608 }
9609 sqlite3BtreeLeave(p);
9610 }
9611 return rc;
9612}
9613#endif
9614
danielk19771d850a72004-05-31 08:26:49 +00009615/*
danielk19772372c2b2006-06-27 16:34:56 +00009616** Return non-zero if a read (or write) transaction is active.
9617*/
9618int sqlite3BtreeIsInReadTrans(Btree *p){
drh64022502009-01-09 14:11:04 +00009619 assert( p );
drhe5fe6902007-12-07 18:55:28 +00009620 assert( sqlite3_mutex_held(p->db->mutex) );
drh64022502009-01-09 14:11:04 +00009621 return p->inTrans!=TRANS_NONE;
danielk19772372c2b2006-06-27 16:34:56 +00009622}
9623
danielk197704103022009-02-03 16:51:24 +00009624int sqlite3BtreeIsInBackup(Btree *p){
9625 assert( p );
9626 assert( sqlite3_mutex_held(p->db->mutex) );
9627 return p->nBackup!=0;
9628}
9629
danielk19772372c2b2006-06-27 16:34:56 +00009630/*
danielk1977da184232006-01-05 11:34:32 +00009631** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +00009632** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +00009633** purposes (for example, to store a high-level schema associated with
9634** the shared-btree). The btree layer manages reference counting issues.
9635**
9636** The first time this is called on a shared-btree, nBytes bytes of memory
9637** are allocated, zeroed, and returned to the caller. For each subsequent
9638** call the nBytes parameter is ignored and a pointer to the same blob
9639** of memory returned.
9640**
danielk1977171bfed2008-06-23 09:50:50 +00009641** If the nBytes parameter is 0 and the blob of memory has not yet been
9642** allocated, a null pointer is returned. If the blob has already been
9643** allocated, it is returned as normal.
9644**
danielk1977da184232006-01-05 11:34:32 +00009645** Just before the shared-btree is closed, the function passed as the
9646** xFree argument when the memory allocation was made is invoked on the
drh4fa7d7c2011-04-03 02:41:00 +00009647** blob of allocated memory. The xFree function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00009648** on the memory, the btree layer does that.
9649*/
9650void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
9651 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00009652 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +00009653 if( !pBt->pSchema && nBytes ){
drhb9755982010-07-24 16:34:37 +00009654 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
danielk1977da184232006-01-05 11:34:32 +00009655 pBt->xFreeSchema = xFree;
9656 }
drh27641702007-08-22 02:56:42 +00009657 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00009658 return pBt->pSchema;
9659}
9660
danielk1977c87d34d2006-01-06 13:00:28 +00009661/*
danielk1977404ca072009-03-16 13:19:36 +00009662** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
9663** btree as the argument handle holds an exclusive lock on the
9664** sqlite_master table. Otherwise SQLITE_OK.
danielk1977c87d34d2006-01-06 13:00:28 +00009665*/
9666int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00009667 int rc;
drhe5fe6902007-12-07 18:55:28 +00009668 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +00009669 sqlite3BtreeEnter(p);
danielk1977404ca072009-03-16 13:19:36 +00009670 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
9671 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
drh27641702007-08-22 02:56:42 +00009672 sqlite3BtreeLeave(p);
9673 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00009674}
9675
drha154dcd2006-03-22 22:10:07 +00009676
9677#ifndef SQLITE_OMIT_SHARED_CACHE
9678/*
9679** Obtain a lock on the table whose root page is iTab. The
9680** lock is a write lock if isWritelock is true or a read lock
9681** if it is false.
9682*/
danielk1977c00da102006-01-07 13:21:04 +00009683int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00009684 int rc = SQLITE_OK;
danielk1977602b4662009-07-02 07:47:33 +00009685 assert( p->inTrans!=TRANS_NONE );
drh6a9ad3d2008-04-02 16:29:30 +00009686 if( p->sharable ){
9687 u8 lockType = READ_LOCK + isWriteLock;
9688 assert( READ_LOCK+1==WRITE_LOCK );
9689 assert( isWriteLock==0 || isWriteLock==1 );
danielk1977602b4662009-07-02 07:47:33 +00009690
drh6a9ad3d2008-04-02 16:29:30 +00009691 sqlite3BtreeEnter(p);
drhc25eabe2009-02-24 18:57:31 +00009692 rc = querySharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00009693 if( rc==SQLITE_OK ){
drhc25eabe2009-02-24 18:57:31 +00009694 rc = setSharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00009695 }
9696 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00009697 }
9698 return rc;
9699}
drha154dcd2006-03-22 22:10:07 +00009700#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00009701
danielk1977b4e9af92007-05-01 17:49:49 +00009702#ifndef SQLITE_OMIT_INCRBLOB
9703/*
9704** Argument pCsr must be a cursor opened for writing on an
9705** INTKEY table currently pointing at a valid table entry.
9706** This function modifies the data stored as part of that entry.
danielk1977ecaecf92009-07-08 08:05:35 +00009707**
9708** Only the data content may only be modified, it is not possible to
9709** change the length of the data stored. If this function is called with
9710** parameters that attempt to write past the end of the existing data,
9711** no modifications are made and SQLITE_CORRUPT is returned.
danielk1977b4e9af92007-05-01 17:49:49 +00009712*/
danielk1977dcbb5d32007-05-04 18:36:44 +00009713int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
danielk1977c9000e62009-07-08 13:55:28 +00009714 int rc;
dan7a2347e2016-01-07 16:43:54 +00009715 assert( cursorOwnsBtShared(pCsr) );
drhe5fe6902007-12-07 18:55:28 +00009716 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
drh036dbec2014-03-11 23:40:44 +00009717 assert( pCsr->curFlags & BTCF_Incrblob );
danielk19773588ceb2008-06-10 17:30:26 +00009718
danielk1977c9000e62009-07-08 13:55:28 +00009719 rc = restoreCursorPosition(pCsr);
9720 if( rc!=SQLITE_OK ){
9721 return rc;
9722 }
danielk19773588ceb2008-06-10 17:30:26 +00009723 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
9724 if( pCsr->eState!=CURSOR_VALID ){
9725 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +00009726 }
9727
dan227a1c42013-04-03 11:17:39 +00009728 /* Save the positions of all other cursors open on this table. This is
9729 ** required in case any of them are holding references to an xFetch
9730 ** version of the b-tree page modified by the accessPayload call below.
drh370c9f42013-04-03 20:04:04 +00009731 **
drh3f387402014-09-24 01:23:00 +00009732 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
drh370c9f42013-04-03 20:04:04 +00009733 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
9734 ** saveAllCursors can only return SQLITE_OK.
dan227a1c42013-04-03 11:17:39 +00009735 */
drh370c9f42013-04-03 20:04:04 +00009736 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
9737 assert( rc==SQLITE_OK );
dan227a1c42013-04-03 11:17:39 +00009738
danielk1977c9000e62009-07-08 13:55:28 +00009739 /* Check some assumptions:
danielk1977dcbb5d32007-05-04 18:36:44 +00009740 ** (a) the cursor is open for writing,
danielk1977c9000e62009-07-08 13:55:28 +00009741 ** (b) there is a read/write transaction open,
9742 ** (c) the connection holds a write-lock on the table (if required),
9743 ** (d) there are no conflicting read-locks, and
9744 ** (e) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00009745 */
drh036dbec2014-03-11 23:40:44 +00009746 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
danielk19774f029602009-07-08 18:45:37 +00009747 return SQLITE_READONLY;
9748 }
drhc9166342012-01-05 23:32:06 +00009749 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
9750 && pCsr->pBt->inTransaction==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +00009751 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
9752 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
danielk1977c9000e62009-07-08 13:55:28 +00009753 assert( pCsr->apPage[pCsr->iPage]->intKey );
danielk1977b4e9af92007-05-01 17:49:49 +00009754
drhfb192682009-07-11 18:26:28 +00009755 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00009756}
danielk19772dec9702007-05-02 16:48:37 +00009757
9758/*
dan5a500af2014-03-11 20:33:04 +00009759** Mark this cursor as an incremental blob cursor.
danielk19772dec9702007-05-02 16:48:37 +00009760*/
dan5a500af2014-03-11 20:33:04 +00009761void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
drh036dbec2014-03-11 23:40:44 +00009762 pCur->curFlags |= BTCF_Incrblob;
drh69180952015-06-25 13:03:10 +00009763 pCur->pBtree->hasIncrblobCur = 1;
danielk19772dec9702007-05-02 16:48:37 +00009764}
danielk1977b4e9af92007-05-01 17:49:49 +00009765#endif
dane04dc882010-04-20 18:53:15 +00009766
9767/*
9768** Set both the "read version" (single byte at byte offset 18) and
9769** "write version" (single byte at byte offset 19) fields in the database
9770** header to iVersion.
9771*/
9772int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
9773 BtShared *pBt = pBtree->pBt;
9774 int rc; /* Return code */
9775
dane04dc882010-04-20 18:53:15 +00009776 assert( iVersion==1 || iVersion==2 );
9777
danb9780022010-04-21 18:37:57 +00009778 /* If setting the version fields to 1, do not automatically open the
9779 ** WAL connection, even if the version fields are currently set to 2.
9780 */
drhc9166342012-01-05 23:32:06 +00009781 pBt->btsFlags &= ~BTS_NO_WAL;
9782 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
danb9780022010-04-21 18:37:57 +00009783
9784 rc = sqlite3BtreeBeginTrans(pBtree, 0);
dane04dc882010-04-20 18:53:15 +00009785 if( rc==SQLITE_OK ){
9786 u8 *aData = pBt->pPage1->aData;
danb9780022010-04-21 18:37:57 +00009787 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
danede6eb82010-04-22 06:27:04 +00009788 rc = sqlite3BtreeBeginTrans(pBtree, 2);
danb9780022010-04-21 18:37:57 +00009789 if( rc==SQLITE_OK ){
9790 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
9791 if( rc==SQLITE_OK ){
9792 aData[18] = (u8)iVersion;
9793 aData[19] = (u8)iVersion;
9794 }
9795 }
9796 }
dane04dc882010-04-20 18:53:15 +00009797 }
9798
drhc9166342012-01-05 23:32:06 +00009799 pBt->btsFlags &= ~BTS_NO_WAL;
dane04dc882010-04-20 18:53:15 +00009800 return rc;
9801}
dan428c2182012-08-06 18:50:11 +00009802
drhe0997b32015-03-20 14:57:50 +00009803/*
9804** Return true if the cursor has a hint specified. This routine is
9805** only used from within assert() statements
9806*/
9807int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
9808 return (pCsr->hints & mask)!=0;
9809}
drhe0997b32015-03-20 14:57:50 +00009810
drh781597f2014-05-21 08:21:07 +00009811/*
9812** Return true if the given Btree is read-only.
9813*/
9814int sqlite3BtreeIsReadonly(Btree *p){
9815 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
9816}
drhdef68892014-11-04 12:11:23 +00009817
9818/*
9819** Return the size of the header added to each page by this module.
9820*/
drh37c057b2014-12-30 00:57:29 +00009821int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
dan20d876f2016-01-07 16:06:22 +00009822
drh5a1fb182016-01-08 19:34:39 +00009823#if !defined(SQLITE_OMIT_SHARED_CACHE)
dan20d876f2016-01-07 16:06:22 +00009824/*
9825** Return true if the Btree passed as the only argument is sharable.
9826*/
9827int sqlite3BtreeSharable(Btree *p){
9828 return p->sharable;
9829}
dan272989b2016-07-06 10:12:02 +00009830
9831/*
9832** Return the number of connections to the BtShared object accessed by
9833** the Btree handle passed as the only argument. For private caches
9834** this is always 1. For shared caches it may be 1 or greater.
9835*/
9836int sqlite3BtreeConnectionCount(Btree *p){
9837 testcase( p->sharable );
9838 return p->pBt->nRef;
9839}
drh5a1fb182016-01-08 19:34:39 +00009840#endif