blob: 711e20fddaa65564da9055bb90caf541f33fc194 [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)
drh169dd922017-06-26 13:57:49 +0000155 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
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
drh169dd922017-06-26 13:57:49 +0000232 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
danielk197796d48e92009-06-29 06:00:37 +0000233 ){
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 );
drh169dd922017-06-26 13:57:49 +0000254 assert( !(p->db->flags&SQLITE_ReadUncommit)||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(). */
drh169dd922017-06-26 13:57:49 +0000332 assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
danielk1977e0d9e6f2009-07-03 16:25:06 +0000333
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
dan7b3d71e2015-08-19 20:27:05 +0000442
drh01be4632015-09-03 15:17:12 +0000443#ifndef SQLITE_OMIT_CONCURRENT
danf5cebf72015-08-22 17:28:55 +0000444/*
445** The following structure - BtreePtrmap - stores the in-memory pointer map
danbf3cf572015-08-24 19:56:04 +0000446** used for newly allocated pages in CONCURRENT transactions. Such pages are
danf5cebf72015-08-22 17:28:55 +0000447** always allocated in a contiguous block (from the end of the file) starting
448** with page BtreePtrmap.iFirst.
449*/
dan7b3d71e2015-08-19 20:27:05 +0000450typedef struct RollbackEntry RollbackEntry;
451typedef struct PtrmapEntry PtrmapEntry;
452struct PtrmapEntry {
453 Pgno parent;
454 u8 eType;
455};
456struct RollbackEntry {
457 Pgno pgno;
458 Pgno parent;
459 u8 eType;
460};
dan7b3d71e2015-08-19 20:27:05 +0000461struct BtreePtrmap {
462 Pgno iFirst; /* First new page number aPtr[0] */
463
464 int nPtrAlloc; /* Allocated size of aPtr[] array */
465 PtrmapEntry *aPtr; /* Array of parent page numbers */
466
467 int nSvpt; /* Used size of aSvpt[] array */
468 int nSvptAlloc; /* Allocated size of aSvpt[] */
469 int *aSvpt; /* First aRollback[] entry for savepoint i */
470
471 int nRollback; /* Used size of aRollback[] array */
472 int nRollbackAlloc; /* Allocated size of aRollback[] array */
473 RollbackEntry *aRollback; /* Array of rollback entries */
474};
475
drh01be4632015-09-03 15:17:12 +0000476/* !defined(SQLITE_OMIT_CONCURRENT)
477**
danf5cebf72015-08-22 17:28:55 +0000478** If page number pgno is greater than or equal to BtreePtrmap.iFirst,
479** store an entry for it in the pointer-map structure.
480*/
dan7b3d71e2015-08-19 20:27:05 +0000481static int btreePtrmapStore(
danf5cebf72015-08-22 17:28:55 +0000482 BtShared *pBt,
483 Pgno pgno,
dan7b3d71e2015-08-19 20:27:05 +0000484 u8 eType,
485 Pgno parent
486){
danf5cebf72015-08-22 17:28:55 +0000487 BtreePtrmap *pMap = pBt->pMap;
dan7b3d71e2015-08-19 20:27:05 +0000488 if( pgno>=pMap->iFirst ){
489 int iEntry = pgno - pMap->iFirst;
490
danf5cebf72015-08-22 17:28:55 +0000491 /* Grow the aPtr[] array as required */
492 while( iEntry>=pMap->nPtrAlloc ){
dan7b3d71e2015-08-19 20:27:05 +0000493 int nNew = pMap->nPtrAlloc ? pMap->nPtrAlloc*2 : 16;
494 PtrmapEntry *aNew = (PtrmapEntry*)sqlite3_realloc(
495 pMap->aPtr, nNew*sizeof(PtrmapEntry)
496 );
497 if( aNew==0 ){
498 return SQLITE_NOMEM;
499 }else{
500 int nByte = (nNew-pMap->nPtrAlloc)*sizeof(PtrmapEntry);
501 memset(&aNew[pMap->nPtrAlloc], 0, nByte);
502 pMap->aPtr = aNew;
503 pMap->nPtrAlloc = nNew;
504 }
505 }
506
507 /* Add an entry to the rollback log if required */
508 if( pMap->nSvpt>0 && pMap->aPtr[iEntry].parent ){
509 if( pMap->nRollback>=pMap->nRollbackAlloc ){
510 int nNew = pMap->nRollback ? pMap->nRollback*2 : 16;
511 RollbackEntry *aNew = (RollbackEntry*)sqlite3_realloc(
512 pMap->aRollback, nNew*sizeof(RollbackEntry)
513 );
514 if( aNew==0 ){
515 return SQLITE_NOMEM;
516 }else{
517 pMap->aRollback = aNew;
518 pMap->nRollbackAlloc = nNew;
519 }
520 }
521
522 pMap->aRollback[pMap->nRollback].pgno = pgno;
523 pMap->aRollback[pMap->nRollback].parent = pMap->aPtr[iEntry].parent;
524 pMap->aRollback[pMap->nRollback].eType = pMap->aPtr[iEntry].eType;
dan606f7182017-05-26 16:15:05 +0000525 pMap->nRollback++;
dan7b3d71e2015-08-19 20:27:05 +0000526 }
527
528 /* Update the aPtr[] array */
529 pMap->aPtr[iEntry].parent = parent;
530 pMap->aPtr[iEntry].eType = eType;
531 }
532
533 return SQLITE_OK;
534}
535
drh01be4632015-09-03 15:17:12 +0000536/* !defined(SQLITE_OMIT_CONCURRENT)
537**
dan7b3d71e2015-08-19 20:27:05 +0000538** Open savepoint iSavepoint, if it is not already open.
539*/
danf5cebf72015-08-22 17:28:55 +0000540static int btreePtrmapBegin(BtShared *pBt, int nSvpt){
541 BtreePtrmap *pMap = pBt->pMap;
dan606f7182017-05-26 16:15:05 +0000542 if( pMap && nSvpt>pMap->nSvpt ){
dan7b3d71e2015-08-19 20:27:05 +0000543 int i;
544 if( nSvpt>=pMap->nSvptAlloc ){
545 int nNew = pMap->nSvptAlloc ? pMap->nSvptAlloc*2 : 16;
546 int *aNew = sqlite3_realloc(pMap->aSvpt, sizeof(int) * nNew);
547 if( aNew==0 ){
548 return SQLITE_NOMEM;
549 }else{
550 pMap->aSvpt = aNew;
551 pMap->nSvptAlloc = nNew;
552 }
553 }
554
555 for(i=pMap->nSvpt; i<nSvpt; i++){
556 pMap->aSvpt[i] = pMap->nRollback;
557 }
558 pMap->nSvpt = nSvpt;
559 }
560
561 return SQLITE_OK;
562}
563
drh01be4632015-09-03 15:17:12 +0000564/* !defined(SQLITE_OMIT_CONCURRENT)
565**
dan7b3d71e2015-08-19 20:27:05 +0000566** Rollback (if op==SAVEPOINT_ROLLBACK) or release (if op==SAVEPOINT_RELEASE)
567** savepoint iSvpt.
568*/
danf5cebf72015-08-22 17:28:55 +0000569static void btreePtrmapEnd(BtShared *pBt, int op, int iSvpt){
570 BtreePtrmap *pMap = pBt->pMap;
571 if( pMap ){
572 assert( op==SAVEPOINT_ROLLBACK || op==SAVEPOINT_RELEASE );
573 assert( iSvpt>=0 || (iSvpt==-1 && op==SAVEPOINT_ROLLBACK) );
574 if( iSvpt<0 ){
575 pMap->nSvpt = 0;
576 pMap->nRollback = 0;
577 memset(pMap->aPtr, 0, sizeof(Pgno) * pMap->nPtrAlloc);
578 }else if( iSvpt<pMap->nSvpt ){
579 if( op==SAVEPOINT_ROLLBACK ){
580 int ii;
581 for(ii=pMap->nRollback-1; ii>=pMap->aSvpt[iSvpt]; ii--){
582 RollbackEntry *p = &pMap->aRollback[ii];
583 PtrmapEntry *pEntry = &pMap->aPtr[p->pgno - pMap->iFirst];
584 pEntry->parent = p->parent;
585 pEntry->eType = p->eType;
586 }
dan7b3d71e2015-08-19 20:27:05 +0000587 }
danf5cebf72015-08-22 17:28:55 +0000588 pMap->nSvpt = iSvpt + (op==SAVEPOINT_ROLLBACK);
589 pMap->nRollback = pMap->aSvpt[iSvpt];
dan7b3d71e2015-08-19 20:27:05 +0000590 }
dan7b3d71e2015-08-19 20:27:05 +0000591 }
592}
593
drh01be4632015-09-03 15:17:12 +0000594/* !defined(SQLITE_OMIT_CONCURRENT)
595**
danbf3cf572015-08-24 19:56:04 +0000596** This function is called after an CONCURRENT transaction is opened on the
danf5cebf72015-08-22 17:28:55 +0000597** database. It allocates the BtreePtrmap structure used to track pointers
598** to allocated pages and zeroes the nFree/iTrunk fields in the database
599** header on page 1.
600*/
601static int btreePtrmapAllocate(BtShared *pBt){
602 int rc = SQLITE_OK;
dan987f8212015-08-27 17:42:38 +0000603 if( pBt->pMap==0 ){
604 BtreePtrmap *pMap = sqlite3_malloc(sizeof(BtreePtrmap));
605 if( pMap==0 ){
606 rc = SQLITE_NOMEM;
607 }else{
608 memset(&pBt->pPage1->aData[32], 0, sizeof(u32)*2);
609 memset(pMap, 0, sizeof(BtreePtrmap));
610 pMap->iFirst = pBt->nPage + 1;
611 pBt->pMap = pMap;
612 }
danf5cebf72015-08-22 17:28:55 +0000613 }
614 return rc;
615}
616
drh01be4632015-09-03 15:17:12 +0000617/* !defined(SQLITE_OMIT_CONCURRENT)
618**
danf5cebf72015-08-22 17:28:55 +0000619** Free any BtreePtrmap structure allocated by an earlier call to
620** btreePtrmapAllocate().
621*/
622static void btreePtrmapDelete(BtShared *pBt){
623 BtreePtrmap *pMap = pBt->pMap;
624 if( pMap ){
625 sqlite3_free(pMap->aRollback);
626 sqlite3_free(pMap->aPtr);
627 sqlite3_free(pMap->aSvpt);
628 sqlite3_free(pMap);
629 pBt->pMap = 0;
630 }
631}
drh01be4632015-09-03 15:17:12 +0000632#else /* SQLITE_OMIT_CONCURRENT */
danf5cebf72015-08-22 17:28:55 +0000633# define btreePtrmapAllocate(x) SQLITE_OK
634# define btreePtrmapDelete(x)
635# define btreePtrmapBegin(x,y) SQLITE_OK
636# define btreePtrmapEnd(x,y,z)
drh01be4632015-09-03 15:17:12 +0000637#endif /* SQLITE_OMIT_CONCURRENT */
dan7b3d71e2015-08-19 20:27:05 +0000638
drh980b1a72006-08-16 16:42:48 +0000639static void releasePage(MemPage *pPage); /* Forward reference */
640
drh1fee73e2007-08-29 04:00:57 +0000641/*
drh0ee3dbe2009-10-16 15:05:18 +0000642***** This routine is used inside of assert() only ****
643**
644** Verify that the cursor holds the mutex on its BtShared
drh1fee73e2007-08-29 04:00:57 +0000645*/
drh0ee3dbe2009-10-16 15:05:18 +0000646#ifdef SQLITE_DEBUG
drh1fee73e2007-08-29 04:00:57 +0000647static int cursorHoldsMutex(BtCursor *p){
drhff0587c2007-08-29 17:43:19 +0000648 return sqlite3_mutex_held(p->pBt->mutex);
drh1fee73e2007-08-29 04:00:57 +0000649}
drh5e08d0f2016-06-04 21:05:54 +0000650
651/* Verify that the cursor and the BtShared agree about what is the current
652** database connetion. This is important in shared-cache mode. If the database
653** connection pointers get out-of-sync, it is possible for routines like
654** btreeInitPage() to reference an stale connection pointer that references a
655** a connection that has already closed. This routine is used inside assert()
656** statements only and for the purpose of double-checking that the btree code
657** does keep the database connection pointers up-to-date.
658*/
dan7a2347e2016-01-07 16:43:54 +0000659static int cursorOwnsBtShared(BtCursor *p){
660 assert( cursorHoldsMutex(p) );
661 return (p->pBtree->db==p->pBt->db);
662}
drh1fee73e2007-08-29 04:00:57 +0000663#endif
664
danielk197792d4d7a2007-05-04 12:05:56 +0000665/*
dan5a500af2014-03-11 20:33:04 +0000666** Invalidate the overflow cache of the cursor passed as the first argument.
667** on the shared btree structure pBt.
danielk197792d4d7a2007-05-04 12:05:56 +0000668*/
drh036dbec2014-03-11 23:40:44 +0000669#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
danielk197792d4d7a2007-05-04 12:05:56 +0000670
671/*
672** Invalidate the overflow page-list cache for all cursors opened
673** on the shared btree structure pBt.
674*/
675static void invalidateAllOverflowCache(BtShared *pBt){
676 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000677 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +0000678 for(p=pBt->pCursor; p; p=p->pNext){
679 invalidateOverflowCache(p);
680 }
681}
danielk197796d48e92009-06-29 06:00:37 +0000682
dan5a500af2014-03-11 20:33:04 +0000683#ifndef SQLITE_OMIT_INCRBLOB
danielk197796d48e92009-06-29 06:00:37 +0000684/*
685** This function is called before modifying the contents of a table
drh0ee3dbe2009-10-16 15:05:18 +0000686** to invalidate any incrblob cursors that are open on the
drheeb844a2009-08-08 18:01:07 +0000687** row or one of the rows being modified.
danielk197796d48e92009-06-29 06:00:37 +0000688**
689** If argument isClearTable is true, then the entire contents of the
690** table is about to be deleted. In this case invalidate all incrblob
691** cursors open on any row within the table with root-page pgnoRoot.
692**
693** Otherwise, if argument isClearTable is false, then the row with
694** rowid iRow is being replaced or deleted. In this case invalidate
drh0ee3dbe2009-10-16 15:05:18 +0000695** only those incrblob cursors open on that specific row.
danielk197796d48e92009-06-29 06:00:37 +0000696*/
697static void invalidateIncrblobCursors(
698 Btree *pBtree, /* The database file to check */
drh9ca431a2017-03-29 18:03:50 +0000699 Pgno pgnoRoot, /* The table that might be changing */
danielk197796d48e92009-06-29 06:00:37 +0000700 i64 iRow, /* The rowid that might be changing */
701 int isClearTable /* True if all rows are being deleted */
702){
703 BtCursor *p;
drh69180952015-06-25 13:03:10 +0000704 if( pBtree->hasIncrblobCur==0 ) return;
danielk197796d48e92009-06-29 06:00:37 +0000705 assert( sqlite3BtreeHoldsMutex(pBtree) );
drh69180952015-06-25 13:03:10 +0000706 pBtree->hasIncrblobCur = 0;
707 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
708 if( (p->curFlags & BTCF_Incrblob)!=0 ){
709 pBtree->hasIncrblobCur = 1;
drh9ca431a2017-03-29 18:03:50 +0000710 if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
drh69180952015-06-25 13:03:10 +0000711 p->eState = CURSOR_INVALID;
712 }
danielk197796d48e92009-06-29 06:00:37 +0000713 }
714 }
715}
716
danielk197792d4d7a2007-05-04 12:05:56 +0000717#else
dan5a500af2014-03-11 20:33:04 +0000718 /* Stub function when INCRBLOB is omitted */
drh9ca431a2017-03-29 18:03:50 +0000719 #define invalidateIncrblobCursors(w,x,y,z)
drh0ee3dbe2009-10-16 15:05:18 +0000720#endif /* SQLITE_OMIT_INCRBLOB */
danielk197792d4d7a2007-05-04 12:05:56 +0000721
drh980b1a72006-08-16 16:42:48 +0000722/*
danielk1977bea2a942009-01-20 17:06:27 +0000723** Set bit pgno of the BtShared.pHasContent bitvec. This is called
724** when a page that previously contained data becomes a free-list leaf
725** page.
726**
727** The BtShared.pHasContent bitvec exists to work around an obscure
728** bug caused by the interaction of two useful IO optimizations surrounding
729** free-list leaf pages:
730**
731** 1) When all data is deleted from a page and the page becomes
732** a free-list leaf page, the page is not written to the database
733** (as free-list leaf pages contain no meaningful data). Sometimes
734** such a page is not even journalled (as it will not be modified,
735** why bother journalling it?).
736**
737** 2) When a free-list leaf page is reused, its content is not read
738** from the database or written to the journal file (why should it
739** be, if it is not at all meaningful?).
740**
741** By themselves, these optimizations work fine and provide a handy
742** performance boost to bulk delete or insert operations. However, if
743** a page is moved to the free-list and then reused within the same
744** transaction, a problem comes up. If the page is not journalled when
745** it is moved to the free-list and it is also not journalled when it
746** is extracted from the free-list and reused, then the original data
747** may be lost. In the event of a rollback, it may not be possible
748** to restore the database to its original configuration.
749**
750** The solution is the BtShared.pHasContent bitvec. Whenever a page is
751** moved to become a free-list leaf page, the corresponding bit is
752** set in the bitvec. Whenever a leaf page is extracted from the free-list,
drh0ee3dbe2009-10-16 15:05:18 +0000753** optimization 2 above is omitted if the corresponding bit is already
danielk1977bea2a942009-01-20 17:06:27 +0000754** set in BtShared.pHasContent. The contents of the bitvec are cleared
755** at the end of every transaction.
756*/
757static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
758 int rc = SQLITE_OK;
759 if( !pBt->pHasContent ){
drhdd3cd972010-03-27 17:12:36 +0000760 assert( pgno<=pBt->nPage );
761 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
drh4c301aa2009-07-15 17:25:45 +0000762 if( !pBt->pHasContent ){
mistachkinfad30392016-02-13 23:43:46 +0000763 rc = SQLITE_NOMEM_BKPT;
danielk1977bea2a942009-01-20 17:06:27 +0000764 }
765 }
766 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
767 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
768 }
769 return rc;
770}
771
772/*
773** Query the BtShared.pHasContent vector.
774**
775** This function is called when a free-list leaf page is removed from the
776** free-list for reuse. It returns false if it is safe to retrieve the
777** page from the pager layer with the 'no-content' flag set. True otherwise.
778*/
779static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
780 Bitvec *p = pBt->pHasContent;
781 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
782}
783
784/*
785** Clear (destroy) the BtShared.pHasContent bitvec. This should be
786** invoked at the conclusion of each write-transaction.
787*/
788static void btreeClearHasContent(BtShared *pBt){
789 sqlite3BitvecDestroy(pBt->pHasContent);
790 pBt->pHasContent = 0;
791}
792
793/*
drh138eeeb2013-03-27 03:15:23 +0000794** Release all of the apPage[] pages for a cursor.
795*/
796static void btreeReleaseAllCursorPages(BtCursor *pCur){
797 int i;
798 for(i=0; i<=pCur->iPage; i++){
799 releasePage(pCur->apPage[i]);
800 pCur->apPage[i] = 0;
801 }
802 pCur->iPage = -1;
803}
804
danf0ee1d32015-09-12 19:26:11 +0000805/*
806** The cursor passed as the only argument must point to a valid entry
807** when this function is called (i.e. have eState==CURSOR_VALID). This
808** function saves the current cursor key in variables pCur->nKey and
809** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
810** code otherwise.
811**
812** If the cursor is open on an intkey table, then the integer key
813** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
814** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
815** set to point to a malloced buffer pCur->nKey bytes in size containing
816** the key.
817*/
818static int saveCursorKey(BtCursor *pCur){
drha7c90c42016-06-04 20:37:10 +0000819 int rc = SQLITE_OK;
danf0ee1d32015-09-12 19:26:11 +0000820 assert( CURSOR_VALID==pCur->eState );
821 assert( 0==pCur->pKey );
822 assert( cursorHoldsMutex(pCur) );
823
drha7c90c42016-06-04 20:37:10 +0000824 if( pCur->curIntKey ){
825 /* Only the rowid is required for a table btree */
826 pCur->nKey = sqlite3BtreeIntegerKey(pCur);
827 }else{
828 /* For an index btree, save the complete key content */
drhd66c4f82016-06-04 20:58:35 +0000829 void *pKey;
drha7c90c42016-06-04 20:37:10 +0000830 pCur->nKey = sqlite3BtreePayloadSize(pCur);
drhd66c4f82016-06-04 20:58:35 +0000831 pKey = sqlite3Malloc( pCur->nKey );
danf0ee1d32015-09-12 19:26:11 +0000832 if( pKey ){
drhcb3cabd2016-11-25 19:18:28 +0000833 rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
danf0ee1d32015-09-12 19:26:11 +0000834 if( rc==SQLITE_OK ){
835 pCur->pKey = pKey;
836 }else{
837 sqlite3_free(pKey);
838 }
839 }else{
mistachkinfad30392016-02-13 23:43:46 +0000840 rc = SQLITE_NOMEM_BKPT;
danf0ee1d32015-09-12 19:26:11 +0000841 }
842 }
843 assert( !pCur->curIntKey || !pCur->pKey );
844 return rc;
845}
drh138eeeb2013-03-27 03:15:23 +0000846
847/*
drh980b1a72006-08-16 16:42:48 +0000848** Save the current cursor position in the variables BtCursor.nKey
849** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
drhea8ffdf2009-07-22 00:35:23 +0000850**
851** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
852** prior to calling this routine.
drh980b1a72006-08-16 16:42:48 +0000853*/
854static int saveCursorPosition(BtCursor *pCur){
855 int rc;
856
drhd2f83132015-03-25 17:35:01 +0000857 assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
drh980b1a72006-08-16 16:42:48 +0000858 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000859 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000860
drhd2f83132015-03-25 17:35:01 +0000861 if( pCur->eState==CURSOR_SKIPNEXT ){
862 pCur->eState = CURSOR_VALID;
863 }else{
864 pCur->skipNext = 0;
865 }
drh980b1a72006-08-16 16:42:48 +0000866
danf0ee1d32015-09-12 19:26:11 +0000867 rc = saveCursorKey(pCur);
drh980b1a72006-08-16 16:42:48 +0000868 if( rc==SQLITE_OK ){
drh138eeeb2013-03-27 03:15:23 +0000869 btreeReleaseAllCursorPages(pCur);
drh980b1a72006-08-16 16:42:48 +0000870 pCur->eState = CURSOR_REQUIRESEEK;
871 }
872
dane755e102015-09-30 12:59:12 +0000873 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
drh980b1a72006-08-16 16:42:48 +0000874 return rc;
875}
876
drh637f3d82014-08-22 22:26:07 +0000877/* Forward reference */
878static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
879
drh980b1a72006-08-16 16:42:48 +0000880/*
drh0ee3dbe2009-10-16 15:05:18 +0000881** Save the positions of all cursors (except pExcept) that are open on
drh637f3d82014-08-22 22:26:07 +0000882** the table with root-page iRoot. "Saving the cursor position" means that
883** the location in the btree is remembered in such a way that it can be
884** moved back to the same spot after the btree has been modified. This
885** routine is called just before cursor pExcept is used to modify the
886** table, for example in BtreeDelete() or BtreeInsert().
887**
drh27fb7462015-06-30 02:47:36 +0000888** If there are two or more cursors on the same btree, then all such
889** cursors should have their BTCF_Multiple flag set. The btreeCursor()
890** routine enforces that rule. This routine only needs to be called in
891** the uncommon case when pExpect has the BTCF_Multiple flag set.
892**
893** If pExpect!=NULL and if no other cursors are found on the same root-page,
894** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
895** pointless call to this routine.
896**
drh637f3d82014-08-22 22:26:07 +0000897** Implementation note: This routine merely checks to see if any cursors
898** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
899** event that cursors are in need to being saved.
drh980b1a72006-08-16 16:42:48 +0000900*/
901static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
drh3bdffdd2014-08-23 19:08:09 +0000902 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000903 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000904 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000905 for(p=pBt->pCursor; p; p=p->pNext){
drh637f3d82014-08-22 22:26:07 +0000906 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
907 }
drh27fb7462015-06-30 02:47:36 +0000908 if( p ) return saveCursorsOnList(p, iRoot, pExcept);
909 if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
910 return SQLITE_OK;
drh637f3d82014-08-22 22:26:07 +0000911}
912
913/* This helper routine to saveAllCursors does the actual work of saving
914** the cursors if and when a cursor is found that actually requires saving.
915** The common case is that no cursors need to be saved, so this routine is
916** broken out from its caller to avoid unnecessary stack pointer movement.
917*/
918static int SQLITE_NOINLINE saveCursorsOnList(
drh3f387402014-09-24 01:23:00 +0000919 BtCursor *p, /* The first cursor that needs saving */
920 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
921 BtCursor *pExcept /* Do not save this cursor */
drh637f3d82014-08-22 22:26:07 +0000922){
923 do{
drh138eeeb2013-03-27 03:15:23 +0000924 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
drhd2f83132015-03-25 17:35:01 +0000925 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
drh138eeeb2013-03-27 03:15:23 +0000926 int rc = saveCursorPosition(p);
927 if( SQLITE_OK!=rc ){
928 return rc;
929 }
930 }else{
931 testcase( p->iPage>0 );
932 btreeReleaseAllCursorPages(p);
drh980b1a72006-08-16 16:42:48 +0000933 }
934 }
drh637f3d82014-08-22 22:26:07 +0000935 p = p->pNext;
936 }while( p );
drh980b1a72006-08-16 16:42:48 +0000937 return SQLITE_OK;
938}
939
940/*
drhbf700f32007-03-31 02:36:44 +0000941** Clear the current cursor position.
942*/
danielk1977be51a652008-10-08 17:58:48 +0000943void sqlite3BtreeClearCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000944 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000945 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +0000946 pCur->pKey = 0;
947 pCur->eState = CURSOR_INVALID;
948}
949
950/*
danielk19773509a652009-07-06 18:56:13 +0000951** In this version of BtreeMoveto, pKey is a packed index record
952** such as is generated by the OP_MakeRecord opcode. Unpack the
953** record and then call BtreeMovetoUnpacked() to do the work.
954*/
955static int btreeMoveto(
956 BtCursor *pCur, /* Cursor open on the btree to be searched */
957 const void *pKey, /* Packed key if the btree is an index */
958 i64 nKey, /* Integer key for tables. Size of pKey for indices */
959 int bias, /* Bias search to the high end */
960 int *pRes /* Write search results here */
961){
962 int rc; /* Status code */
963 UnpackedRecord *pIdxKey; /* Unpacked index key */
danielk19773509a652009-07-06 18:56:13 +0000964
965 if( pKey ){
966 assert( nKey==(i64)(int)nKey );
drha582b012016-12-21 19:45:54 +0000967 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pCur->pKeyInfo);
mistachkinfad30392016-02-13 23:43:46 +0000968 if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
mistachkin0fe5f952011-09-14 18:19:08 +0000969 sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
drh094b7582013-11-30 12:49:28 +0000970 if( pIdxKey->nField==0 ){
drhcc97ca42017-06-07 22:32:59 +0000971 rc = SQLITE_CORRUPT_PGNO(pCur->apPage[pCur->iPage]->pgno);
drha582b012016-12-21 19:45:54 +0000972 goto moveto_done;
drh094b7582013-11-30 12:49:28 +0000973 }
danielk19773509a652009-07-06 18:56:13 +0000974 }else{
975 pIdxKey = 0;
976 }
977 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
drha582b012016-12-21 19:45:54 +0000978moveto_done:
979 if( pIdxKey ){
980 sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
danielk19773509a652009-07-06 18:56:13 +0000981 }
982 return rc;
983}
984
985/*
drh980b1a72006-08-16 16:42:48 +0000986** Restore the cursor to the position it was in (or as close to as possible)
987** when saveCursorPosition() was called. Note that this call deletes the
988** saved position info stored by saveCursorPosition(), so there can be
drha3460582008-07-11 21:02:53 +0000989** at most one effective restoreCursorPosition() call after each
drh980b1a72006-08-16 16:42:48 +0000990** saveCursorPosition().
drh980b1a72006-08-16 16:42:48 +0000991*/
danielk197730548662009-07-09 05:07:37 +0000992static int btreeRestoreCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000993 int rc;
drhd2f83132015-03-25 17:35:01 +0000994 int skipNext;
dan7a2347e2016-01-07 16:43:54 +0000995 assert( cursorOwnsBtShared(pCur) );
drhfb982642007-08-30 01:19:59 +0000996 assert( pCur->eState>=CURSOR_REQUIRESEEK );
997 if( pCur->eState==CURSOR_FAULT ){
drh4c301aa2009-07-15 17:25:45 +0000998 return pCur->skipNext;
drhfb982642007-08-30 01:19:59 +0000999 }
drh980b1a72006-08-16 16:42:48 +00001000 pCur->eState = CURSOR_INVALID;
drhd2f83132015-03-25 17:35:01 +00001001 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
drh980b1a72006-08-16 16:42:48 +00001002 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +00001003 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +00001004 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +00001005 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drhd2f83132015-03-25 17:35:01 +00001006 pCur->skipNext |= skipNext;
drh9b47ee32013-08-20 03:13:51 +00001007 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
1008 pCur->eState = CURSOR_SKIPNEXT;
1009 }
drh980b1a72006-08-16 16:42:48 +00001010 }
1011 return rc;
1012}
1013
drha3460582008-07-11 21:02:53 +00001014#define restoreCursorPosition(p) \
drhfb982642007-08-30 01:19:59 +00001015 (p->eState>=CURSOR_REQUIRESEEK ? \
danielk197730548662009-07-09 05:07:37 +00001016 btreeRestoreCursorPosition(p) : \
drh16a9b832007-05-05 18:39:25 +00001017 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +00001018
drha3460582008-07-11 21:02:53 +00001019/*
drh6848dad2014-08-22 23:33:03 +00001020** Determine whether or not a cursor has moved from the position where
1021** it was last placed, or has been invalidated for any other reason.
1022** Cursors can move when the row they are pointing at is deleted out
1023** from under them, for example. Cursor might also move if a btree
1024** is rebalanced.
drha3460582008-07-11 21:02:53 +00001025**
drh6848dad2014-08-22 23:33:03 +00001026** Calling this routine with a NULL cursor pointer returns false.
drh86dd3712014-03-25 11:00:21 +00001027**
drh6848dad2014-08-22 23:33:03 +00001028** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
1029** back to where it ought to be if this routine returns true.
drha3460582008-07-11 21:02:53 +00001030*/
drh6848dad2014-08-22 23:33:03 +00001031int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
drhc22284f2014-10-13 16:02:20 +00001032 return pCur->eState!=CURSOR_VALID;
drh6848dad2014-08-22 23:33:03 +00001033}
1034
1035/*
1036** This routine restores a cursor back to its original position after it
1037** has been moved by some outside activity (such as a btree rebalance or
1038** a row having been deleted out from under the cursor).
1039**
1040** On success, the *pDifferentRow parameter is false if the cursor is left
1041** pointing at exactly the same row. *pDifferntRow is the row the cursor
1042** was pointing to has been deleted, forcing the cursor to point to some
1043** nearby row.
1044**
1045** This routine should only be called for a cursor that just returned
1046** TRUE from sqlite3BtreeCursorHasMoved().
1047*/
1048int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
drha3460582008-07-11 21:02:53 +00001049 int rc;
1050
drh6848dad2014-08-22 23:33:03 +00001051 assert( pCur!=0 );
1052 assert( pCur->eState!=CURSOR_VALID );
drha3460582008-07-11 21:02:53 +00001053 rc = restoreCursorPosition(pCur);
1054 if( rc ){
drh6848dad2014-08-22 23:33:03 +00001055 *pDifferentRow = 1;
drha3460582008-07-11 21:02:53 +00001056 return rc;
1057 }
drh606a3572015-03-25 18:29:10 +00001058 if( pCur->eState!=CURSOR_VALID ){
drh6848dad2014-08-22 23:33:03 +00001059 *pDifferentRow = 1;
drha3460582008-07-11 21:02:53 +00001060 }else{
drh606a3572015-03-25 18:29:10 +00001061 assert( pCur->skipNext==0 );
drh6848dad2014-08-22 23:33:03 +00001062 *pDifferentRow = 0;
drha3460582008-07-11 21:02:53 +00001063 }
1064 return SQLITE_OK;
1065}
1066
drhf7854c72015-10-27 13:24:37 +00001067#ifdef SQLITE_ENABLE_CURSOR_HINTS
drh28935362013-12-07 20:39:19 +00001068/*
drh0df57012015-08-14 15:05:55 +00001069** Provide hints to the cursor. The particular hint given (and the type
1070** and number of the varargs parameters) is determined by the eHintType
1071** parameter. See the definitions of the BTREE_HINT_* macros for details.
drh28935362013-12-07 20:39:19 +00001072*/
drh0df57012015-08-14 15:05:55 +00001073void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
drhf7854c72015-10-27 13:24:37 +00001074 /* Used only by system that substitute their own storage engine */
drh28935362013-12-07 20:39:19 +00001075}
drhf7854c72015-10-27 13:24:37 +00001076#endif
1077
1078/*
1079** Provide flag hints to the cursor.
1080*/
1081void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
1082 assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
1083 pCur->hints = x;
1084}
1085
drh28935362013-12-07 20:39:19 +00001086
danielk1977599fcba2004-11-08 07:13:13 +00001087#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +00001088/*
drha3152892007-05-05 11:48:52 +00001089** Given a page number of a regular database page, return the page
1090** number for the pointer-map page that contains the entry for the
1091** input page number.
drh5f77b2e2010-08-21 15:09:37 +00001092**
1093** Return 0 (not a valid page) for pgno==1 since there is
1094** no pointer map associated with page 1. The integrity_check logic
1095** requires that ptrmapPageno(*,1)!=1.
danielk1977afcdd022004-10-31 16:25:42 +00001096*/
danielk1977266664d2006-02-10 08:24:21 +00001097static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
danielk197789d40042008-11-17 14:20:56 +00001098 int nPagesPerMapPage;
1099 Pgno iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +00001100 assert( sqlite3_mutex_held(pBt->mutex) );
drh5f77b2e2010-08-21 15:09:37 +00001101 if( pgno<2 ) return 0;
drhd677b3d2007-08-20 22:48:41 +00001102 nPagesPerMapPage = (pBt->usableSize/5)+1;
1103 iPtrMap = (pgno-2)/nPagesPerMapPage;
1104 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +00001105 if( ret==PENDING_BYTE_PAGE(pBt) ){
1106 ret++;
1107 }
1108 return ret;
1109}
danielk1977a19df672004-11-03 11:37:07 +00001110
danielk1977afcdd022004-10-31 16:25:42 +00001111/*
danielk1977afcdd022004-10-31 16:25:42 +00001112** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +00001113**
1114** This routine updates the pointer map entry for page number 'key'
1115** so that it maps to type 'eType' and parent page number 'pgno'.
drh98add2e2009-07-20 17:11:49 +00001116**
1117** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
1118** a no-op. If an error occurs, the appropriate error code is written
1119** into *pRC.
danielk1977afcdd022004-10-31 16:25:42 +00001120*/
drh98add2e2009-07-20 17:11:49 +00001121static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
danielk19773b8a05f2007-03-19 17:44:26 +00001122 DbPage *pDbPage; /* The pointer map page */
1123 u8 *pPtrmap; /* The pointer map data */
1124 Pgno iPtrmap; /* The pointer map page number */
1125 int offset; /* Offset in pointer map page */
drh98add2e2009-07-20 17:11:49 +00001126 int rc; /* Return code from subfunctions */
1127
1128 if( *pRC ) return;
danielk1977afcdd022004-10-31 16:25:42 +00001129
danf5cebf72015-08-22 17:28:55 +00001130 assert( sqlite3_mutex_held(pBt->mutex) );
1131 /* The master-journal page number is never added to a pointer-map page */
1132 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
1133
drh01be4632015-09-03 15:17:12 +00001134#ifndef SQLITE_OMIT_CONCURRENT
dan7b3d71e2015-08-19 20:27:05 +00001135 if( pBt->pMap ){
danf5cebf72015-08-22 17:28:55 +00001136 *pRC = btreePtrmapStore(pBt, key, eType, parent);
1137 return;
dan7b3d71e2015-08-19 20:27:05 +00001138 }
danf5cebf72015-08-22 17:28:55 +00001139#endif
1140
1141 assert( pBt->autoVacuum );
1142 if( key==0 ){
1143 *pRC = SQLITE_CORRUPT_BKPT;
1144 return;
1145 }
1146 iPtrmap = PTRMAP_PAGENO(pBt, key);
drh9584f582015-11-04 20:22:37 +00001147 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
danf5cebf72015-08-22 17:28:55 +00001148 if( rc!=SQLITE_OK ){
1149 *pRC = rc;
1150 return;
1151 }
1152 offset = PTRMAP_PTROFFSET(iPtrmap, key);
1153 if( offset<0 ){
1154 *pRC = SQLITE_CORRUPT_BKPT;
1155 goto ptrmap_exit;
1156 }
1157 assert( offset <= (int)pBt->usableSize-5 );
1158 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1159
1160 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
1161 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
1162 *pRC= rc = sqlite3PagerWrite(pDbPage);
1163 if( rc==SQLITE_OK ){
1164 pPtrmap[offset] = eType;
1165 put4byte(&pPtrmap[offset+1], parent);
1166 }
1167 }
1168
1169ptrmap_exit:
1170 sqlite3PagerUnref(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +00001171}
1172
1173/*
1174** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +00001175**
1176** This routine retrieves the pointer map entry for page 'key', writing
1177** the type and parent page number to *pEType and *pPgno respectively.
1178** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +00001179*/
danielk1977aef0bf62005-12-30 16:28:01 +00001180static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +00001181 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +00001182 int iPtrmap; /* Pointer map page index */
1183 u8 *pPtrmap; /* Pointer map page data */
1184 int offset; /* Offset of entry in pointer map */
1185 int rc;
1186
drh1fee73e2007-08-29 04:00:57 +00001187 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001188
danielk1977266664d2006-02-10 08:24:21 +00001189 iPtrmap = PTRMAP_PAGENO(pBt, key);
drh9584f582015-11-04 20:22:37 +00001190 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00001191 if( rc!=0 ){
1192 return rc;
1193 }
danielk19773b8a05f2007-03-19 17:44:26 +00001194 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +00001195
danielk19778c666b12008-07-18 09:34:57 +00001196 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drhfc243732011-05-17 15:21:56 +00001197 if( offset<0 ){
1198 sqlite3PagerUnref(pDbPage);
1199 return SQLITE_CORRUPT_BKPT;
1200 }
1201 assert( offset <= (int)pBt->usableSize-5 );
drh43617e92006-03-06 20:55:46 +00001202 assert( pEType!=0 );
1203 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +00001204 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +00001205
danielk19773b8a05f2007-03-19 17:44:26 +00001206 sqlite3PagerUnref(pDbPage);
drhcc97ca42017-06-07 22:32:59 +00001207 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
danielk1977afcdd022004-10-31 16:25:42 +00001208 return SQLITE_OK;
1209}
1210
danielk197785d90ca2008-07-19 14:25:15 +00001211#else /* if defined SQLITE_OMIT_AUTOVACUUM */
drh98add2e2009-07-20 17:11:49 +00001212 #define ptrmapPut(w,x,y,z,rc)
danielk197785d90ca2008-07-19 14:25:15 +00001213 #define ptrmapGet(w,x,y,z) SQLITE_OK
drh98add2e2009-07-20 17:11:49 +00001214 #define ptrmapPutOvflPtr(x, y, rc)
danielk197785d90ca2008-07-19 14:25:15 +00001215#endif
danielk1977afcdd022004-10-31 16:25:42 +00001216
drh0d316a42002-08-11 20:10:47 +00001217/*
drh271efa52004-05-30 19:19:05 +00001218** Given a btree page and a cell index (0 means the first cell on
1219** the page, 1 means the second cell, and so forth) return a pointer
1220** to the cell content.
1221**
drhf44890a2015-06-27 03:58:15 +00001222** findCellPastPtr() does the same except it skips past the initial
1223** 4-byte child pointer found on interior pages, if there is one.
1224**
drh271efa52004-05-30 19:19:05 +00001225** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +00001226*/
drh1688c862008-07-18 02:44:17 +00001227#define findCell(P,I) \
drh329428e2015-06-30 13:28:18 +00001228 ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
drhf44890a2015-06-27 03:58:15 +00001229#define findCellPastPtr(P,I) \
drh329428e2015-06-30 13:28:18 +00001230 ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
drhf44890a2015-06-27 03:58:15 +00001231
drh68f2a572011-06-03 17:50:49 +00001232
drh43605152004-05-29 21:46:49 +00001233/*
drh5fa60512015-06-19 17:19:34 +00001234** This is common tail processing for btreeParseCellPtr() and
1235** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
1236** on a single B-tree page. Make necessary adjustments to the CellInfo
1237** structure.
drh43605152004-05-29 21:46:49 +00001238*/
drh5fa60512015-06-19 17:19:34 +00001239static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
1240 MemPage *pPage, /* Page containing the cell */
1241 u8 *pCell, /* Pointer to the cell text. */
1242 CellInfo *pInfo /* Fill in this structure */
1243){
1244 /* If the payload will not fit completely on the local page, we have
1245 ** to decide how much to store locally and how much to spill onto
1246 ** overflow pages. The strategy is to minimize the amount of unused
1247 ** space on overflow pages while keeping the amount of local storage
1248 ** in between minLocal and maxLocal.
1249 **
1250 ** Warning: changing the way overflow payload is distributed in any
1251 ** way will result in an incompatible file format.
1252 */
1253 int minLocal; /* Minimum amount of payload held locally */
1254 int maxLocal; /* Maximum amount of payload held locally */
1255 int surplus; /* Overflow payload available for local storage */
1256
1257 minLocal = pPage->minLocal;
1258 maxLocal = pPage->maxLocal;
1259 surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
1260 testcase( surplus==maxLocal );
1261 testcase( surplus==maxLocal+1 );
1262 if( surplus <= maxLocal ){
1263 pInfo->nLocal = (u16)surplus;
1264 }else{
1265 pInfo->nLocal = (u16)minLocal;
1266 }
drh45ac1c72015-12-18 03:59:16 +00001267 pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
drh5fa60512015-06-19 17:19:34 +00001268}
1269
1270/*
1271** The following routines are implementations of the MemPage.xParseCell()
1272** method.
1273**
1274** Parse a cell content block and fill in the CellInfo structure.
1275**
1276** btreeParseCellPtr() => table btree leaf nodes
1277** btreeParseCellNoPayload() => table btree internal nodes
1278** btreeParseCellPtrIndex() => index btree nodes
1279**
1280** There is also a wrapper function btreeParseCell() that works for
1281** all MemPage types and that references the cell by index rather than
1282** by pointer.
1283*/
1284static void btreeParseCellPtrNoPayload(
1285 MemPage *pPage, /* Page containing the cell */
1286 u8 *pCell, /* Pointer to the cell text. */
1287 CellInfo *pInfo /* Fill in this structure */
1288){
1289 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1290 assert( pPage->leaf==0 );
drh5fa60512015-06-19 17:19:34 +00001291 assert( pPage->childPtrSize==4 );
drh94a31152015-07-01 04:08:40 +00001292#ifndef SQLITE_DEBUG
1293 UNUSED_PARAMETER(pPage);
1294#endif
drh5fa60512015-06-19 17:19:34 +00001295 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
1296 pInfo->nPayload = 0;
1297 pInfo->nLocal = 0;
drh5fa60512015-06-19 17:19:34 +00001298 pInfo->pPayload = 0;
1299 return;
1300}
danielk197730548662009-07-09 05:07:37 +00001301static void btreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +00001302 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +00001303 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +00001304 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +00001305){
drh3e28ff52014-09-24 00:59:08 +00001306 u8 *pIter; /* For scanning through pCell */
drh271efa52004-05-30 19:19:05 +00001307 u32 nPayload; /* Number of bytes of cell payload */
drh56cb04e2015-06-19 18:24:37 +00001308 u64 iKey; /* Extracted Key value */
drh43605152004-05-29 21:46:49 +00001309
drh1fee73e2007-08-29 04:00:57 +00001310 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhab01f612004-05-22 02:55:23 +00001311 assert( pPage->leaf==0 || pPage->leaf==1 );
drh5fa60512015-06-19 17:19:34 +00001312 assert( pPage->intKeyLeaf );
1313 assert( pPage->childPtrSize==0 );
drh56cb04e2015-06-19 18:24:37 +00001314 pIter = pCell;
1315
1316 /* The next block of code is equivalent to:
1317 **
1318 ** pIter += getVarint32(pIter, nPayload);
1319 **
1320 ** The code is inlined to avoid a function call.
1321 */
1322 nPayload = *pIter;
1323 if( nPayload>=0x80 ){
drheeab2c62015-06-19 20:08:39 +00001324 u8 *pEnd = &pIter[8];
drh56cb04e2015-06-19 18:24:37 +00001325 nPayload &= 0x7f;
1326 do{
1327 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1328 }while( (*pIter)>=0x80 && pIter<pEnd );
1329 }
1330 pIter++;
1331
1332 /* The next block of code is equivalent to:
1333 **
1334 ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
1335 **
1336 ** The code is inlined to avoid a function call.
1337 */
1338 iKey = *pIter;
1339 if( iKey>=0x80 ){
1340 u8 *pEnd = &pIter[7];
1341 iKey &= 0x7f;
1342 while(1){
1343 iKey = (iKey<<7) | (*++pIter & 0x7f);
1344 if( (*pIter)<0x80 ) break;
1345 if( pIter>=pEnd ){
1346 iKey = (iKey<<8) | *++pIter;
1347 break;
1348 }
1349 }
1350 }
1351 pIter++;
1352
1353 pInfo->nKey = *(i64*)&iKey;
drh72365832007-03-06 15:53:44 +00001354 pInfo->nPayload = nPayload;
drhab1cc582014-09-23 21:25:19 +00001355 pInfo->pPayload = pIter;
drh0a45c272009-07-08 01:49:11 +00001356 testcase( nPayload==pPage->maxLocal );
1357 testcase( nPayload==pPage->maxLocal+1 );
drhab1cc582014-09-23 21:25:19 +00001358 if( nPayload<=pPage->maxLocal ){
drh271efa52004-05-30 19:19:05 +00001359 /* This is the (easy) common case where the entire payload fits
1360 ** on the local page. No overflow is required.
1361 */
drhab1cc582014-09-23 21:25:19 +00001362 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1363 if( pInfo->nSize<4 ) pInfo->nSize = 4;
drhf49661a2008-12-10 16:45:50 +00001364 pInfo->nLocal = (u16)nPayload;
drh6f11bef2004-05-13 01:12:56 +00001365 }else{
drh5fa60512015-06-19 17:19:34 +00001366 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1367 }
1368}
1369static void btreeParseCellPtrIndex(
1370 MemPage *pPage, /* Page containing the cell */
1371 u8 *pCell, /* Pointer to the cell text. */
1372 CellInfo *pInfo /* Fill in this structure */
1373){
1374 u8 *pIter; /* For scanning through pCell */
1375 u32 nPayload; /* Number of bytes of cell payload */
drh271efa52004-05-30 19:19:05 +00001376
drh5fa60512015-06-19 17:19:34 +00001377 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1378 assert( pPage->leaf==0 || pPage->leaf==1 );
1379 assert( pPage->intKeyLeaf==0 );
drh5fa60512015-06-19 17:19:34 +00001380 pIter = pCell + pPage->childPtrSize;
1381 nPayload = *pIter;
1382 if( nPayload>=0x80 ){
drheeab2c62015-06-19 20:08:39 +00001383 u8 *pEnd = &pIter[8];
drh5fa60512015-06-19 17:19:34 +00001384 nPayload &= 0x7f;
1385 do{
1386 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1387 }while( *(pIter)>=0x80 && pIter<pEnd );
1388 }
1389 pIter++;
1390 pInfo->nKey = nPayload;
1391 pInfo->nPayload = nPayload;
1392 pInfo->pPayload = pIter;
1393 testcase( nPayload==pPage->maxLocal );
1394 testcase( nPayload==pPage->maxLocal+1 );
1395 if( nPayload<=pPage->maxLocal ){
1396 /* This is the (easy) common case where the entire payload fits
1397 ** on the local page. No overflow is required.
1398 */
1399 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1400 if( pInfo->nSize<4 ) pInfo->nSize = 4;
1401 pInfo->nLocal = (u16)nPayload;
drh5fa60512015-06-19 17:19:34 +00001402 }else{
1403 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
drh6f11bef2004-05-13 01:12:56 +00001404 }
drh3aac2dd2004-04-26 14:10:20 +00001405}
danielk197730548662009-07-09 05:07:37 +00001406static void btreeParseCell(
drh43605152004-05-29 21:46:49 +00001407 MemPage *pPage, /* Page containing the cell */
1408 int iCell, /* The cell index. First cell is 0 */
1409 CellInfo *pInfo /* Fill in this structure */
1410){
drh5fa60512015-06-19 17:19:34 +00001411 pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
drh43605152004-05-29 21:46:49 +00001412}
drh3aac2dd2004-04-26 14:10:20 +00001413
1414/*
drh5fa60512015-06-19 17:19:34 +00001415** The following routines are implementations of the MemPage.xCellSize
1416** method.
1417**
drh43605152004-05-29 21:46:49 +00001418** Compute the total number of bytes that a Cell needs in the cell
1419** data area of the btree-page. The return number includes the cell
1420** data header and the local payload, but not any overflow page or
1421** the space used by the cell pointer.
drh25ada072015-06-19 15:07:14 +00001422**
drh5fa60512015-06-19 17:19:34 +00001423** cellSizePtrNoPayload() => table internal nodes
1424** cellSizePtr() => all index nodes & table leaf nodes
drh3b7511c2001-05-26 13:15:44 +00001425*/
danielk1977ae5558b2009-04-29 11:31:47 +00001426static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
drh3f387402014-09-24 01:23:00 +00001427 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
1428 u8 *pEnd; /* End mark for a varint */
1429 u32 nSize; /* Size value to return */
danielk1977ae5558b2009-04-29 11:31:47 +00001430
1431#ifdef SQLITE_DEBUG
1432 /* The value returned by this function should always be the same as
1433 ** the (CellInfo.nSize) value found by doing a full parse of the
1434 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1435 ** this function verifies that this invariant is not violated. */
1436 CellInfo debuginfo;
drh5fa60512015-06-19 17:19:34 +00001437 pPage->xParseCell(pPage, pCell, &debuginfo);
danielk1977ae5558b2009-04-29 11:31:47 +00001438#endif
1439
drh3e28ff52014-09-24 00:59:08 +00001440 nSize = *pIter;
1441 if( nSize>=0x80 ){
drheeab2c62015-06-19 20:08:39 +00001442 pEnd = &pIter[8];
drh3e28ff52014-09-24 00:59:08 +00001443 nSize &= 0x7f;
1444 do{
1445 nSize = (nSize<<7) | (*++pIter & 0x7f);
1446 }while( *(pIter)>=0x80 && pIter<pEnd );
1447 }
1448 pIter++;
drhdc41d602014-09-22 19:51:35 +00001449 if( pPage->intKey ){
danielk1977ae5558b2009-04-29 11:31:47 +00001450 /* pIter now points at the 64-bit integer key value, a variable length
1451 ** integer. The following block moves pIter to point at the first byte
1452 ** past the end of the key value. */
1453 pEnd = &pIter[9];
1454 while( (*pIter++)&0x80 && pIter<pEnd );
danielk1977ae5558b2009-04-29 11:31:47 +00001455 }
drh0a45c272009-07-08 01:49:11 +00001456 testcase( nSize==pPage->maxLocal );
1457 testcase( nSize==pPage->maxLocal+1 );
drh3e28ff52014-09-24 00:59:08 +00001458 if( nSize<=pPage->maxLocal ){
1459 nSize += (u32)(pIter - pCell);
1460 if( nSize<4 ) nSize = 4;
1461 }else{
danielk1977ae5558b2009-04-29 11:31:47 +00001462 int minLocal = pPage->minLocal;
1463 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
drh0a45c272009-07-08 01:49:11 +00001464 testcase( nSize==pPage->maxLocal );
1465 testcase( nSize==pPage->maxLocal+1 );
danielk1977ae5558b2009-04-29 11:31:47 +00001466 if( nSize>pPage->maxLocal ){
1467 nSize = minLocal;
1468 }
drh3e28ff52014-09-24 00:59:08 +00001469 nSize += 4 + (u16)(pIter - pCell);
danielk1977ae5558b2009-04-29 11:31:47 +00001470 }
drhdc41d602014-09-22 19:51:35 +00001471 assert( nSize==debuginfo.nSize || CORRUPT_DB );
shane60a4b532009-05-06 18:57:09 +00001472 return (u16)nSize;
danielk1977ae5558b2009-04-29 11:31:47 +00001473}
drh25ada072015-06-19 15:07:14 +00001474static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
1475 u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
1476 u8 *pEnd; /* End mark for a varint */
1477
1478#ifdef SQLITE_DEBUG
1479 /* The value returned by this function should always be the same as
1480 ** the (CellInfo.nSize) value found by doing a full parse of the
1481 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1482 ** this function verifies that this invariant is not violated. */
1483 CellInfo debuginfo;
drh5fa60512015-06-19 17:19:34 +00001484 pPage->xParseCell(pPage, pCell, &debuginfo);
drh94a31152015-07-01 04:08:40 +00001485#else
1486 UNUSED_PARAMETER(pPage);
drh25ada072015-06-19 15:07:14 +00001487#endif
1488
1489 assert( pPage->childPtrSize==4 );
1490 pEnd = pIter + 9;
1491 while( (*pIter++)&0x80 && pIter<pEnd );
1492 assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
1493 return (u16)(pIter - pCell);
1494}
1495
drh0ee3dbe2009-10-16 15:05:18 +00001496
1497#ifdef SQLITE_DEBUG
1498/* This variation on cellSizePtr() is used inside of assert() statements
1499** only. */
drha9121e42008-02-19 14:59:35 +00001500static u16 cellSize(MemPage *pPage, int iCell){
drh25ada072015-06-19 15:07:14 +00001501 return pPage->xCellSize(pPage, findCell(pPage, iCell));
drh43605152004-05-29 21:46:49 +00001502}
danielk1977bc6ada42004-06-30 08:20:16 +00001503#endif
drh3b7511c2001-05-26 13:15:44 +00001504
danielk197779a40da2005-01-16 08:00:01 +00001505#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +00001506/*
danielk197726836652005-01-17 01:33:13 +00001507** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +00001508** to an overflow page, insert an entry into the pointer-map
1509** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +00001510*/
drh98add2e2009-07-20 17:11:49 +00001511static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
drhfa67c3c2008-07-11 02:21:40 +00001512 CellInfo info;
drh98add2e2009-07-20 17:11:49 +00001513 if( *pRC ) return;
drhfa67c3c2008-07-11 02:21:40 +00001514 assert( pCell!=0 );
drh5fa60512015-06-19 17:19:34 +00001515 pPage->xParseCell(pPage, pCell, &info);
drh45ac1c72015-12-18 03:59:16 +00001516 if( info.nLocal<info.nPayload ){
1517 Pgno ovfl = get4byte(&pCell[info.nSize-4]);
drh98add2e2009-07-20 17:11:49 +00001518 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
danielk1977ac11ee62005-01-15 12:45:51 +00001519 }
danielk1977ac11ee62005-01-15 12:45:51 +00001520}
danielk197779a40da2005-01-16 08:00:01 +00001521#endif
1522
danielk1977ac11ee62005-01-15 12:45:51 +00001523
drhda200cc2004-05-09 11:51:38 +00001524/*
dane6d065a2017-02-24 19:58:22 +00001525** Defragment the page given. This routine reorganizes cells within the
1526** page so that there are no free-blocks on the free-block list.
1527**
1528** Parameter nMaxFrag is the maximum amount of fragmented space that may be
1529** present in the page after this routine returns.
drhfdab0262014-11-20 15:30:50 +00001530**
1531** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
1532** b-tree page so that there are no freeblocks or fragment bytes, all
1533** unused bytes are contained in the unallocated space region, and all
1534** cells are packed tightly at the end of the page.
drh365d68f2001-05-11 11:02:46 +00001535*/
dane6d065a2017-02-24 19:58:22 +00001536static int defragmentPage(MemPage *pPage, int nMaxFrag){
drh43605152004-05-29 21:46:49 +00001537 int i; /* Loop counter */
peter.d.reid60ec9142014-09-06 16:39:46 +00001538 int pc; /* Address of the i-th cell */
drh43605152004-05-29 21:46:49 +00001539 int hdr; /* Offset to the page header */
1540 int size; /* Size of a cell */
1541 int usableSize; /* Number of usable bytes on a page */
1542 int cellOffset; /* Offset to the cell pointer array */
drh281b21d2008-08-22 12:57:08 +00001543 int cbrk; /* Offset to the cell content area */
drh43605152004-05-29 21:46:49 +00001544 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +00001545 unsigned char *data; /* The page data */
1546 unsigned char *temp; /* Temp area for cell content */
drh588400b2014-09-27 05:00:25 +00001547 unsigned char *src; /* Source of content */
drh17146622009-07-07 17:38:38 +00001548 int iCellFirst; /* First allowable cell index */
1549 int iCellLast; /* Last possible cell index */
1550
danielk19773b8a05f2007-03-19 17:44:26 +00001551 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001552 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +00001553 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +00001554 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00001555 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh588400b2014-09-27 05:00:25 +00001556 temp = 0;
1557 src = data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +00001558 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001559 cellOffset = pPage->cellOffset;
1560 nCell = pPage->nCell;
1561 assert( nCell==get2byte(&data[hdr+3]) );
drh17146622009-07-07 17:38:38 +00001562 iCellFirst = cellOffset + 2*nCell;
dan30741eb2017-03-03 20:02:53 +00001563 usableSize = pPage->pBt->usableSize;
dane6d065a2017-02-24 19:58:22 +00001564
1565 /* This block handles pages with two or fewer free blocks and nMaxFrag
1566 ** or fewer fragmented bytes. In this case it is faster to move the
1567 ** two (or one) blocks of cells using memmove() and add the required
1568 ** offsets to each pointer in the cell-pointer array than it is to
1569 ** reconstruct the entire page. */
1570 if( (int)data[hdr+7]<=nMaxFrag ){
1571 int iFree = get2byte(&data[hdr+1]);
1572 if( iFree ){
1573 int iFree2 = get2byte(&data[iFree]);
dan30741eb2017-03-03 20:02:53 +00001574
1575 /* pageFindSlot() has already verified that free blocks are sorted
1576 ** in order of offset within the page, and that no block extends
1577 ** past the end of the page. Provided the two free slots do not
1578 ** overlap, this guarantees that the memmove() calls below will not
1579 ** overwrite the usableSize byte buffer, even if the database page
1580 ** is corrupt. */
1581 assert( iFree2==0 || iFree2>iFree );
1582 assert( iFree+get2byte(&data[iFree+2]) <= usableSize );
1583 assert( iFree2==0 || iFree2+get2byte(&data[iFree2+2]) <= usableSize );
1584
dane6d065a2017-02-24 19:58:22 +00001585 if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
1586 u8 *pEnd = &data[cellOffset + nCell*2];
1587 u8 *pAddr;
1588 int sz2 = 0;
1589 int sz = get2byte(&data[iFree+2]);
1590 int top = get2byte(&data[hdr+5]);
1591 if( iFree2 ){
drhcc97ca42017-06-07 22:32:59 +00001592 if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
dane6d065a2017-02-24 19:58:22 +00001593 sz2 = get2byte(&data[iFree2+2]);
dan30741eb2017-03-03 20:02:53 +00001594 assert( iFree+sz+sz2+iFree2-(iFree+sz) <= usableSize );
dane6d065a2017-02-24 19:58:22 +00001595 memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
1596 sz += sz2;
1597 }
1598 cbrk = top+sz;
dan30741eb2017-03-03 20:02:53 +00001599 assert( cbrk+(iFree-top) <= usableSize );
dane6d065a2017-02-24 19:58:22 +00001600 memmove(&data[cbrk], &data[top], iFree-top);
1601 for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
1602 pc = get2byte(pAddr);
1603 if( pc<iFree ){ put2byte(pAddr, pc+sz); }
1604 else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
1605 }
1606 goto defragment_out;
1607 }
1608 }
1609 }
1610
drh281b21d2008-08-22 12:57:08 +00001611 cbrk = usableSize;
drh17146622009-07-07 17:38:38 +00001612 iCellLast = usableSize - 4;
drh43605152004-05-29 21:46:49 +00001613 for(i=0; i<nCell; i++){
1614 u8 *pAddr; /* The i-th cell pointer */
1615 pAddr = &data[cellOffset + i*2];
1616 pc = get2byte(pAddr);
drh0a45c272009-07-08 01:49:11 +00001617 testcase( pc==iCellFirst );
1618 testcase( pc==iCellLast );
danielk197730548662009-07-09 05:07:37 +00001619 /* These conditions have already been verified in btreeInitPage()
drh1421d982015-05-27 03:46:18 +00001620 ** if PRAGMA cell_size_check=ON.
drh17146622009-07-07 17:38:38 +00001621 */
1622 if( pc<iCellFirst || pc>iCellLast ){
drhcc97ca42017-06-07 22:32:59 +00001623 return SQLITE_CORRUPT_PGNO(pPage->pgno);
shane0af3f892008-11-12 04:55:34 +00001624 }
drh17146622009-07-07 17:38:38 +00001625 assert( pc>=iCellFirst && pc<=iCellLast );
drh25ada072015-06-19 15:07:14 +00001626 size = pPage->xCellSize(pPage, &src[pc]);
drh281b21d2008-08-22 12:57:08 +00001627 cbrk -= size;
drh17146622009-07-07 17:38:38 +00001628 if( cbrk<iCellFirst || pc+size>usableSize ){
drhcc97ca42017-06-07 22:32:59 +00001629 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh17146622009-07-07 17:38:38 +00001630 }
drh7157e1d2009-07-09 13:25:32 +00001631 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
drh0a45c272009-07-08 01:49:11 +00001632 testcase( cbrk+size==usableSize );
drh0a45c272009-07-08 01:49:11 +00001633 testcase( pc+size==usableSize );
drh281b21d2008-08-22 12:57:08 +00001634 put2byte(pAddr, cbrk);
drh588400b2014-09-27 05:00:25 +00001635 if( temp==0 ){
1636 int x;
1637 if( cbrk==pc ) continue;
1638 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1639 x = get2byte(&data[hdr+5]);
1640 memcpy(&temp[x], &data[x], (cbrk+size) - x);
1641 src = temp;
1642 }
1643 memcpy(&data[cbrk], &src[pc], size);
drh2af926b2001-05-15 00:39:25 +00001644 }
dane6d065a2017-02-24 19:58:22 +00001645 data[hdr+7] = 0;
dane6d065a2017-02-24 19:58:22 +00001646
1647 defragment_out:
dan3b2ede12017-02-25 16:24:02 +00001648 if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
drhcc97ca42017-06-07 22:32:59 +00001649 return SQLITE_CORRUPT_PGNO(pPage->pgno);
dan3b2ede12017-02-25 16:24:02 +00001650 }
drh17146622009-07-07 17:38:38 +00001651 assert( cbrk>=iCellFirst );
drh281b21d2008-08-22 12:57:08 +00001652 put2byte(&data[hdr+5], cbrk);
drh43605152004-05-29 21:46:49 +00001653 data[hdr+1] = 0;
1654 data[hdr+2] = 0;
drh17146622009-07-07 17:38:38 +00001655 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
drhc5053fb2008-11-27 02:22:10 +00001656 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
shane0af3f892008-11-12 04:55:34 +00001657 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +00001658}
1659
drha059ad02001-04-17 20:09:11 +00001660/*
dan8e9ba0c2014-10-14 17:27:04 +00001661** Search the free-list on page pPg for space to store a cell nByte bytes in
1662** size. If one can be found, return a pointer to the space and remove it
1663** from the free-list.
1664**
1665** If no suitable space can be found on the free-list, return NULL.
1666**
drhba0f9992014-10-30 20:48:44 +00001667** This function may detect corruption within pPg. If corruption is
1668** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
dan61e94c92014-10-27 08:02:16 +00001669**
drhb7580e82015-06-25 18:36:13 +00001670** Slots on the free list that are between 1 and 3 bytes larger than nByte
1671** will be ignored if adding the extra space to the fragmentation count
1672** causes the fragmentation count to exceed 60.
dan8e9ba0c2014-10-14 17:27:04 +00001673*/
drhb7580e82015-06-25 18:36:13 +00001674static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
dan8e9ba0c2014-10-14 17:27:04 +00001675 const int hdr = pPg->hdrOffset;
1676 u8 * const aData = pPg->aData;
drhb7580e82015-06-25 18:36:13 +00001677 int iAddr = hdr + 1;
1678 int pc = get2byte(&aData[iAddr]);
1679 int x;
dan8e9ba0c2014-10-14 17:27:04 +00001680 int usableSize = pPg->pBt->usableSize;
1681
drhb7580e82015-06-25 18:36:13 +00001682 assert( pc>0 );
1683 do{
dan8e9ba0c2014-10-14 17:27:04 +00001684 int size; /* Size of the free slot */
drh113762a2014-11-19 16:36:25 +00001685 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
1686 ** increasing offset. */
dan8e9ba0c2014-10-14 17:27:04 +00001687 if( pc>usableSize-4 || pc<iAddr+4 ){
drhcc97ca42017-06-07 22:32:59 +00001688 *pRc = SQLITE_CORRUPT_PGNO(pPg->pgno);
dan8e9ba0c2014-10-14 17:27:04 +00001689 return 0;
1690 }
drh113762a2014-11-19 16:36:25 +00001691 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
1692 ** freeblock form a big-endian integer which is the size of the freeblock
1693 ** in bytes, including the 4-byte header. */
dan8e9ba0c2014-10-14 17:27:04 +00001694 size = get2byte(&aData[pc+2]);
drhb7580e82015-06-25 18:36:13 +00001695 if( (x = size - nByte)>=0 ){
dan8e9ba0c2014-10-14 17:27:04 +00001696 testcase( x==4 );
1697 testcase( x==3 );
drh24dee9d2015-06-02 19:36:29 +00001698 if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){
drhcc97ca42017-06-07 22:32:59 +00001699 *pRc = SQLITE_CORRUPT_PGNO(pPg->pgno);
drh24dee9d2015-06-02 19:36:29 +00001700 return 0;
1701 }else if( x<4 ){
drhfdab0262014-11-20 15:30:50 +00001702 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
1703 ** number of bytes in fragments may not exceed 60. */
drhb7580e82015-06-25 18:36:13 +00001704 if( aData[hdr+7]>57 ) return 0;
1705
dan8e9ba0c2014-10-14 17:27:04 +00001706 /* Remove the slot from the free-list. Update the number of
1707 ** fragmented bytes within the page. */
1708 memcpy(&aData[iAddr], &aData[pc], 2);
1709 aData[hdr+7] += (u8)x;
dan8e9ba0c2014-10-14 17:27:04 +00001710 }else{
1711 /* The slot remains on the free-list. Reduce its size to account
1712 ** for the portion used by the new allocation. */
1713 put2byte(&aData[pc+2], x);
1714 }
1715 return &aData[pc + x];
1716 }
drhb7580e82015-06-25 18:36:13 +00001717 iAddr = pc;
1718 pc = get2byte(&aData[pc]);
1719 }while( pc );
dan8e9ba0c2014-10-14 17:27:04 +00001720
1721 return 0;
1722}
1723
1724/*
danielk19776011a752009-04-01 16:25:32 +00001725** Allocate nByte bytes of space from within the B-Tree page passed
drh0a45c272009-07-08 01:49:11 +00001726** as the first argument. Write into *pIdx the index into pPage->aData[]
1727** of the first byte of allocated space. Return either SQLITE_OK or
1728** an error code (usually SQLITE_CORRUPT).
drhbd03cae2001-06-02 02:40:57 +00001729**
drh0a45c272009-07-08 01:49:11 +00001730** The caller guarantees that there is sufficient space to make the
1731** allocation. This routine might need to defragment in order to bring
1732** all the space together, however. This routine will avoid using
1733** the first two bytes past the cell pointer area since presumably this
1734** allocation is being made in order to insert a new cell, so we will
1735** also end up needing a new cell pointer.
drh7e3b0a02001-04-28 16:52:40 +00001736*/
drh0a45c272009-07-08 01:49:11 +00001737static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
danielk19776011a752009-04-01 16:25:32 +00001738 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1739 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
drh0a45c272009-07-08 01:49:11 +00001740 int top; /* First byte of cell content area */
drhfefa0942014-11-05 21:21:08 +00001741 int rc = SQLITE_OK; /* Integer return code */
drh0a45c272009-07-08 01:49:11 +00001742 int gap; /* First byte of gap between cell pointers and cell content */
drh43605152004-05-29 21:46:49 +00001743
danielk19773b8a05f2007-03-19 17:44:26 +00001744 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001745 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +00001746 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa67c3c2008-07-11 02:21:40 +00001747 assert( nByte>=0 ); /* Minimum cell size is 4 */
1748 assert( pPage->nFree>=nByte );
1749 assert( pPage->nOverflow==0 );
mistachkina95d8ca2014-10-27 19:42:02 +00001750 assert( nByte < (int)(pPage->pBt->usableSize-8) );
drh43605152004-05-29 21:46:49 +00001751
drh0a45c272009-07-08 01:49:11 +00001752 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1753 gap = pPage->cellOffset + 2*pPage->nCell;
drh75b31dc2014-08-20 00:54:46 +00001754 assert( gap<=65536 );
drhfdab0262014-11-20 15:30:50 +00001755 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
1756 ** and the reserved space is zero (the usual value for reserved space)
1757 ** then the cell content offset of an empty page wants to be 65536.
1758 ** However, that integer is too large to be stored in a 2-byte unsigned
1759 ** integer, so a value of 0 is used in its place. */
drhded340e2015-06-25 15:04:56 +00001760 top = get2byte(&data[hdr+5]);
mistachkin68cdd0e2015-06-26 03:12:27 +00001761 assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
drhded340e2015-06-25 15:04:56 +00001762 if( gap>top ){
1763 if( top==0 && pPage->pBt->usableSize==65536 ){
1764 top = 65536;
1765 }else{
drhcc97ca42017-06-07 22:32:59 +00001766 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drhded340e2015-06-25 15:04:56 +00001767 }
drhe7266222015-05-29 17:51:16 +00001768 }
drh4c04f3c2014-08-20 11:56:14 +00001769
1770 /* If there is enough space between gap and top for one more cell pointer
1771 ** array entry offset, and if the freelist is not empty, then search the
1772 ** freelist looking for a free slot big enough to satisfy the request.
1773 */
drh0a45c272009-07-08 01:49:11 +00001774 testcase( gap+2==top );
1775 testcase( gap+1==top );
1776 testcase( gap==top );
drhe674bf12015-06-25 16:01:44 +00001777 if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
drhb7580e82015-06-25 18:36:13 +00001778 u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
dan8e9ba0c2014-10-14 17:27:04 +00001779 if( pSpace ){
drhfefa0942014-11-05 21:21:08 +00001780 assert( pSpace>=data && (pSpace - data)<65536 );
1781 *pIdx = (int)(pSpace - data);
dan8e9ba0c2014-10-14 17:27:04 +00001782 return SQLITE_OK;
drhb7580e82015-06-25 18:36:13 +00001783 }else if( rc ){
1784 return rc;
drh9e572e62004-04-23 23:43:10 +00001785 }
1786 }
drh43605152004-05-29 21:46:49 +00001787
drh4c04f3c2014-08-20 11:56:14 +00001788 /* The request could not be fulfilled using a freelist slot. Check
1789 ** to see if defragmentation is necessary.
drh0a45c272009-07-08 01:49:11 +00001790 */
1791 testcase( gap+2+nByte==top );
1792 if( gap+2+nByte>top ){
drh1fd2d7d2014-12-02 16:16:47 +00001793 assert( pPage->nCell>0 || CORRUPT_DB );
dane6d065a2017-02-24 19:58:22 +00001794 rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
drh0a45c272009-07-08 01:49:11 +00001795 if( rc ) return rc;
drh5d433ce2010-08-14 16:02:52 +00001796 top = get2byteNotZero(&data[hdr+5]);
dan3b2ede12017-02-25 16:24:02 +00001797 assert( gap+2+nByte<=top );
drh0a45c272009-07-08 01:49:11 +00001798 }
1799
1800
drh43605152004-05-29 21:46:49 +00001801 /* Allocate memory from the gap in between the cell pointer array
drhc314dc72009-07-21 11:52:34 +00001802 ** and the cell content area. The btreeInitPage() call has already
1803 ** validated the freelist. Given that the freelist is valid, there
1804 ** is no way that the allocation can extend off the end of the page.
1805 ** The assert() below verifies the previous sentence.
drh43605152004-05-29 21:46:49 +00001806 */
drh0a45c272009-07-08 01:49:11 +00001807 top -= nByte;
drh43605152004-05-29 21:46:49 +00001808 put2byte(&data[hdr+5], top);
drhfcd71b62011-04-05 22:08:24 +00001809 assert( top+nByte <= (int)pPage->pBt->usableSize );
drh0a45c272009-07-08 01:49:11 +00001810 *pIdx = top;
1811 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001812}
1813
1814/*
drh9e572e62004-04-23 23:43:10 +00001815** Return a section of the pPage->aData to the freelist.
drh7fb91642014-08-20 14:37:09 +00001816** The first byte of the new free block is pPage->aData[iStart]
1817** and the size of the block is iSize bytes.
drh306dc212001-05-21 13:45:10 +00001818**
drh5f5c7532014-08-20 17:56:27 +00001819** Adjacent freeblocks are coalesced.
1820**
1821** Note that even though the freeblock list was checked by btreeInitPage(),
1822** that routine will not detect overlap between cells or freeblocks. Nor
1823** does it detect cells or freeblocks that encrouch into the reserved bytes
1824** at the end of the page. So do additional corruption checks inside this
1825** routine and return SQLITE_CORRUPT if any problems are found.
drh7e3b0a02001-04-28 16:52:40 +00001826*/
drh5f5c7532014-08-20 17:56:27 +00001827static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
drh3f387402014-09-24 01:23:00 +00001828 u16 iPtr; /* Address of ptr to next freeblock */
drh5f5c7532014-08-20 17:56:27 +00001829 u16 iFreeBlk; /* Address of the next freeblock */
1830 u8 hdr; /* Page header size. 0 or 100 */
1831 u8 nFrag = 0; /* Reduction in fragmentation */
1832 u16 iOrigSize = iSize; /* Original value of iSize */
1833 u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
1834 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
drh7fb91642014-08-20 14:37:09 +00001835 unsigned char *data = pPage->aData; /* Page content */
drh2af926b2001-05-15 00:39:25 +00001836
drh9e572e62004-04-23 23:43:10 +00001837 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001838 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
dancf3d17c2015-05-25 15:03:49 +00001839 assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
dan23eba452014-10-24 18:43:57 +00001840 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +00001841 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh7fb91642014-08-20 14:37:09 +00001842 assert( iSize>=4 ); /* Minimum cell size is 4 */
drh5f5c7532014-08-20 17:56:27 +00001843 assert( iStart<=iLast );
drh9e572e62004-04-23 23:43:10 +00001844
drh5f5c7532014-08-20 17:56:27 +00001845 /* Overwrite deleted information with zeros when the secure_delete
1846 ** option is enabled */
drha5907a82017-06-19 11:44:22 +00001847 if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
drh7fb91642014-08-20 14:37:09 +00001848 memset(&data[iStart], 0, iSize);
drh5b47efa2010-02-12 18:18:39 +00001849 }
drhfcce93f2006-02-22 03:08:32 +00001850
drh5f5c7532014-08-20 17:56:27 +00001851 /* The list of freeblocks must be in ascending order. Find the
1852 ** spot on the list where iStart should be inserted.
drh0a45c272009-07-08 01:49:11 +00001853 */
drh43605152004-05-29 21:46:49 +00001854 hdr = pPage->hdrOffset;
drh7fb91642014-08-20 14:37:09 +00001855 iPtr = hdr + 1;
drh7bc4c452014-08-20 18:43:44 +00001856 if( data[iPtr+1]==0 && data[iPtr]==0 ){
1857 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
1858 }else{
drh85f071b2016-09-17 19:34:32 +00001859 while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
1860 if( iFreeBlk<iPtr+4 ){
1861 if( iFreeBlk==0 ) break;
drhcc97ca42017-06-07 22:32:59 +00001862 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh85f071b2016-09-17 19:34:32 +00001863 }
drh7bc4c452014-08-20 18:43:44 +00001864 iPtr = iFreeBlk;
drh9e572e62004-04-23 23:43:10 +00001865 }
drhcc97ca42017-06-07 22:32:59 +00001866 if( iFreeBlk>iLast ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh7bc4c452014-08-20 18:43:44 +00001867 assert( iFreeBlk>iPtr || iFreeBlk==0 );
1868
1869 /* At this point:
1870 ** iFreeBlk: First freeblock after iStart, or zero if none
drh3e24a342015-06-15 16:09:35 +00001871 ** iPtr: The address of a pointer to iFreeBlk
drh7bc4c452014-08-20 18:43:44 +00001872 **
1873 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
1874 */
1875 if( iFreeBlk && iEnd+3>=iFreeBlk ){
1876 nFrag = iFreeBlk - iEnd;
drhcc97ca42017-06-07 22:32:59 +00001877 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh7bc4c452014-08-20 18:43:44 +00001878 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
drhcc97ca42017-06-07 22:32:59 +00001879 if( iEnd > pPage->pBt->usableSize ){
1880 return SQLITE_CORRUPT_PGNO(pPage->pgno);
1881 }
drh7bc4c452014-08-20 18:43:44 +00001882 iSize = iEnd - iStart;
1883 iFreeBlk = get2byte(&data[iFreeBlk]);
1884 }
1885
drh3f387402014-09-24 01:23:00 +00001886 /* If iPtr is another freeblock (that is, if iPtr is not the freelist
1887 ** pointer in the page header) then check to see if iStart should be
1888 ** coalesced onto the end of iPtr.
drh7bc4c452014-08-20 18:43:44 +00001889 */
1890 if( iPtr>hdr+1 ){
1891 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
1892 if( iPtrEnd+3>=iStart ){
drhcc97ca42017-06-07 22:32:59 +00001893 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh7bc4c452014-08-20 18:43:44 +00001894 nFrag += iStart - iPtrEnd;
1895 iSize = iEnd - iPtr;
1896 iStart = iPtr;
1897 }
1898 }
drhcc97ca42017-06-07 22:32:59 +00001899 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh7bc4c452014-08-20 18:43:44 +00001900 data[hdr+7] -= nFrag;
drh9e572e62004-04-23 23:43:10 +00001901 }
drh7bc4c452014-08-20 18:43:44 +00001902 if( iStart==get2byte(&data[hdr+5]) ){
drh5f5c7532014-08-20 17:56:27 +00001903 /* The new freeblock is at the beginning of the cell content area,
1904 ** so just extend the cell content area rather than create another
1905 ** freelist entry */
drhcc97ca42017-06-07 22:32:59 +00001906 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh5f5c7532014-08-20 17:56:27 +00001907 put2byte(&data[hdr+1], iFreeBlk);
1908 put2byte(&data[hdr+5], iEnd);
1909 }else{
1910 /* Insert the new freeblock into the freelist */
1911 put2byte(&data[iPtr], iStart);
1912 put2byte(&data[iStart], iFreeBlk);
1913 put2byte(&data[iStart+2], iSize);
drh4b70f112004-05-02 21:12:19 +00001914 }
drh5f5c7532014-08-20 17:56:27 +00001915 pPage->nFree += iOrigSize;
shanedcc50b72008-11-13 18:29:50 +00001916 return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00001917}
1918
1919/*
drh271efa52004-05-30 19:19:05 +00001920** Decode the flags byte (the first byte of the header) for a page
1921** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +00001922**
1923** Only the following combinations are supported. Anything different
1924** indicates a corrupt database files:
1925**
1926** PTF_ZERODATA
1927** PTF_ZERODATA | PTF_LEAF
1928** PTF_LEAFDATA | PTF_INTKEY
1929** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
drh271efa52004-05-30 19:19:05 +00001930*/
drh44845222008-07-17 18:39:57 +00001931static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +00001932 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +00001933
1934 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +00001935 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00001936 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
drh44845222008-07-17 18:39:57 +00001937 flagByte &= ~PTF_LEAF;
1938 pPage->childPtrSize = 4-4*pPage->leaf;
drh25ada072015-06-19 15:07:14 +00001939 pPage->xCellSize = cellSizePtr;
drh271efa52004-05-30 19:19:05 +00001940 pBt = pPage->pBt;
drh44845222008-07-17 18:39:57 +00001941 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
drh3791c9c2016-05-09 23:11:47 +00001942 /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
1943 ** interior table b-tree page. */
drhfdab0262014-11-20 15:30:50 +00001944 assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
drh3791c9c2016-05-09 23:11:47 +00001945 /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
1946 ** leaf table b-tree page. */
drhfdab0262014-11-20 15:30:50 +00001947 assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
drh44845222008-07-17 18:39:57 +00001948 pPage->intKey = 1;
drh25ada072015-06-19 15:07:14 +00001949 if( pPage->leaf ){
1950 pPage->intKeyLeaf = 1;
drh5fa60512015-06-19 17:19:34 +00001951 pPage->xParseCell = btreeParseCellPtr;
drh25ada072015-06-19 15:07:14 +00001952 }else{
1953 pPage->intKeyLeaf = 0;
drh25ada072015-06-19 15:07:14 +00001954 pPage->xCellSize = cellSizePtrNoPayload;
drh5fa60512015-06-19 17:19:34 +00001955 pPage->xParseCell = btreeParseCellPtrNoPayload;
drh25ada072015-06-19 15:07:14 +00001956 }
drh271efa52004-05-30 19:19:05 +00001957 pPage->maxLocal = pBt->maxLeaf;
1958 pPage->minLocal = pBt->minLeaf;
drh44845222008-07-17 18:39:57 +00001959 }else if( flagByte==PTF_ZERODATA ){
drh3791c9c2016-05-09 23:11:47 +00001960 /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
1961 ** interior index b-tree page. */
drhfdab0262014-11-20 15:30:50 +00001962 assert( (PTF_ZERODATA)==2 );
drh3791c9c2016-05-09 23:11:47 +00001963 /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
1964 ** leaf index b-tree page. */
drhfdab0262014-11-20 15:30:50 +00001965 assert( (PTF_ZERODATA|PTF_LEAF)==10 );
drh44845222008-07-17 18:39:57 +00001966 pPage->intKey = 0;
drh3e28ff52014-09-24 00:59:08 +00001967 pPage->intKeyLeaf = 0;
drh5fa60512015-06-19 17:19:34 +00001968 pPage->xParseCell = btreeParseCellPtrIndex;
drh271efa52004-05-30 19:19:05 +00001969 pPage->maxLocal = pBt->maxLocal;
1970 pPage->minLocal = pBt->minLocal;
drh44845222008-07-17 18:39:57 +00001971 }else{
drhfdab0262014-11-20 15:30:50 +00001972 /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
1973 ** an error. */
drhcc97ca42017-06-07 22:32:59 +00001974 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh271efa52004-05-30 19:19:05 +00001975 }
drhc9166342012-01-05 23:32:06 +00001976 pPage->max1bytePayload = pBt->max1bytePayload;
drh44845222008-07-17 18:39:57 +00001977 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +00001978}
1979
1980/*
drh7e3b0a02001-04-28 16:52:40 +00001981** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001982**
1983** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001984** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001985** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1986** guarantee that the page is well-formed. It only shows that
1987** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001988*/
danielk197730548662009-07-09 05:07:37 +00001989static int btreeInitPage(MemPage *pPage){
drh14e845a2017-05-25 21:35:56 +00001990 int pc; /* Address of a freeblock within pPage->aData[] */
1991 u8 hdr; /* Offset to beginning of page header */
1992 u8 *data; /* Equal to pPage->aData */
1993 BtShared *pBt; /* The main btree structure */
1994 int usableSize; /* Amount of usable space on each page */
1995 u16 cellOffset; /* Offset from start of page to first cell pointer */
1996 int nFree; /* Number of unused bytes on the page */
1997 int top; /* First byte of the cell content area */
1998 int iCellFirst; /* First allowable cell or freeblock offset */
1999 int iCellLast; /* Last possible cell or freeblock offset */
drh2af926b2001-05-15 00:39:25 +00002000
danielk197771d5d2c2008-09-29 11:49:47 +00002001 assert( pPage->pBt!=0 );
drh1421d982015-05-27 03:46:18 +00002002 assert( pPage->pBt->db!=0 );
danielk197771d5d2c2008-09-29 11:49:47 +00002003 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00002004 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +00002005 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
2006 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
drh14e845a2017-05-25 21:35:56 +00002007 assert( pPage->isInit==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00002008
drh14e845a2017-05-25 21:35:56 +00002009 pBt = pPage->pBt;
2010 hdr = pPage->hdrOffset;
2011 data = pPage->aData;
2012 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
2013 ** the b-tree page type. */
drhcc97ca42017-06-07 22:32:59 +00002014 if( decodeFlags(pPage, data[hdr]) ){
2015 return SQLITE_CORRUPT_PGNO(pPage->pgno);
danielk197771d5d2c2008-09-29 11:49:47 +00002016 }
drh14e845a2017-05-25 21:35:56 +00002017 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2018 pPage->maskPage = (u16)(pBt->pageSize - 1);
2019 pPage->nOverflow = 0;
2020 usableSize = pBt->usableSize;
2021 pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
2022 pPage->aDataEnd = &data[usableSize];
2023 pPage->aCellIdx = &data[cellOffset];
2024 pPage->aDataOfst = &data[pPage->childPtrSize];
2025 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
2026 ** the start of the cell content area. A zero value for this integer is
2027 ** interpreted as 65536. */
2028 top = get2byteNotZero(&data[hdr+5]);
2029 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
2030 ** number of cells on the page. */
2031 pPage->nCell = get2byte(&data[hdr+3]);
2032 if( pPage->nCell>MX_CELL(pBt) ){
2033 /* To many cells for a single page. The page must be corrupt */
drhcc97ca42017-06-07 22:32:59 +00002034 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh14e845a2017-05-25 21:35:56 +00002035 }
2036 testcase( pPage->nCell==MX_CELL(pBt) );
2037 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
2038 ** possible for a root page of a table that contains no rows) then the
2039 ** offset to the cell content area will equal the page size minus the
2040 ** bytes of reserved space. */
2041 assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
danielk1977eaa06f62008-09-18 17:34:44 +00002042
drh14e845a2017-05-25 21:35:56 +00002043 /* A malformed database page might cause us to read past the end
2044 ** of page when parsing a cell.
2045 **
2046 ** The following block of code checks early to see if a cell extends
2047 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
2048 ** returned if it does.
2049 */
2050 iCellFirst = cellOffset + 2*pPage->nCell;
2051 iCellLast = usableSize - 4;
2052 if( pBt->db->flags & SQLITE_CellSizeCk ){
2053 int i; /* Index into the cell pointer array */
2054 int sz; /* Size of a cell */
danielk1977eaa06f62008-09-18 17:34:44 +00002055
drh14e845a2017-05-25 21:35:56 +00002056 if( !pPage->leaf ) iCellLast--;
2057 for(i=0; i<pPage->nCell; i++){
2058 pc = get2byteAligned(&data[cellOffset+i*2]);
2059 testcase( pc==iCellFirst );
2060 testcase( pc==iCellLast );
2061 if( pc<iCellFirst || pc>iCellLast ){
drhcc97ca42017-06-07 22:32:59 +00002062 return SQLITE_CORRUPT_PGNO(pPage->pgno);
danielk1977eaa06f62008-09-18 17:34:44 +00002063 }
drh14e845a2017-05-25 21:35:56 +00002064 sz = pPage->xCellSize(pPage, &data[pc]);
2065 testcase( pc+sz==usableSize );
2066 if( pc+sz>usableSize ){
drhcc97ca42017-06-07 22:32:59 +00002067 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh77dc0ed2016-12-12 01:30:01 +00002068 }
drh1688c862008-07-18 02:44:17 +00002069 }
drh14e845a2017-05-25 21:35:56 +00002070 if( !pPage->leaf ) iCellLast++;
2071 }
drh1688c862008-07-18 02:44:17 +00002072
drh14e845a2017-05-25 21:35:56 +00002073 /* Compute the total free space on the page
2074 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
2075 ** start of the first freeblock on the page, or is zero if there are no
2076 ** freeblocks. */
2077 pc = get2byte(&data[hdr+1]);
2078 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
2079 if( pc>0 ){
2080 u32 next, size;
2081 if( pc<iCellFirst ){
2082 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
2083 ** always be at least one cell before the first freeblock.
2084 */
drhcc97ca42017-06-07 22:32:59 +00002085 return SQLITE_CORRUPT_PGNO(pPage->pgno);
danielk1977e16535f2008-06-11 18:15:29 +00002086 }
drh14e845a2017-05-25 21:35:56 +00002087 while( 1 ){
2088 if( pc>iCellLast ){
drhcc97ca42017-06-07 22:32:59 +00002089 /* Freeblock off the end of the page */
2090 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh14e845a2017-05-25 21:35:56 +00002091 }
2092 next = get2byte(&data[pc]);
2093 size = get2byte(&data[pc+2]);
2094 nFree = nFree + size;
2095 if( next<=pc+size+3 ) break;
2096 pc = next;
2097 }
2098 if( next>0 ){
drhcc97ca42017-06-07 22:32:59 +00002099 /* Freeblock not in ascending order */
2100 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh14e845a2017-05-25 21:35:56 +00002101 }
2102 if( pc+size>(unsigned int)usableSize ){
drhcc97ca42017-06-07 22:32:59 +00002103 /* Last freeblock extends past page end */
2104 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh14e845a2017-05-25 21:35:56 +00002105 }
danielk1977eaa06f62008-09-18 17:34:44 +00002106 }
drh14e845a2017-05-25 21:35:56 +00002107
2108 /* At this point, nFree contains the sum of the offset to the start
2109 ** of the cell-content area plus the number of free bytes within
2110 ** the cell-content area. If this is greater than the usable-size
2111 ** of the page, then the page must be corrupted. This check also
2112 ** serves to verify that the offset to the start of the cell-content
2113 ** area, according to the page header, lies within the page.
2114 */
2115 if( nFree>usableSize ){
drhcc97ca42017-06-07 22:32:59 +00002116 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh14e845a2017-05-25 21:35:56 +00002117 }
2118 pPage->nFree = (u16)(nFree - iCellFirst);
2119 pPage->isInit = 1;
drh9e572e62004-04-23 23:43:10 +00002120 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00002121}
2122
2123/*
drh8b2f49b2001-06-08 00:21:52 +00002124** Set up a raw page so that it looks like a database page holding
2125** no entries.
drhbd03cae2001-06-02 02:40:57 +00002126*/
drh9e572e62004-04-23 23:43:10 +00002127static void zeroPage(MemPage *pPage, int flags){
2128 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00002129 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00002130 u8 hdr = pPage->hdrOffset;
2131 u16 first;
drh9e572e62004-04-23 23:43:10 +00002132
danielk19773b8a05f2007-03-19 17:44:26 +00002133 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +00002134 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2135 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00002136 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00002137 assert( sqlite3_mutex_held(pBt->mutex) );
drha5907a82017-06-19 11:44:22 +00002138 if( pBt->btsFlags & BTS_FAST_SECURE ){
drh5b47efa2010-02-12 18:18:39 +00002139 memset(&data[hdr], 0, pBt->usableSize - hdr);
2140 }
drh1bd10f82008-12-10 21:19:56 +00002141 data[hdr] = (char)flags;
drhfe485992014-02-12 23:52:16 +00002142 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
drh43605152004-05-29 21:46:49 +00002143 memset(&data[hdr+1], 0, 4);
2144 data[hdr+7] = 0;
2145 put2byte(&data[hdr+5], pBt->usableSize);
shaneh1df2db72010-08-18 02:28:48 +00002146 pPage->nFree = (u16)(pBt->usableSize - first);
drh271efa52004-05-30 19:19:05 +00002147 decodeFlags(pPage, flags);
drh43605152004-05-29 21:46:49 +00002148 pPage->cellOffset = first;
drh3def2352011-11-11 00:27:15 +00002149 pPage->aDataEnd = &data[pBt->usableSize];
2150 pPage->aCellIdx = &data[first];
drhf44890a2015-06-27 03:58:15 +00002151 pPage->aDataOfst = &data[pPage->childPtrSize];
drh43605152004-05-29 21:46:49 +00002152 pPage->nOverflow = 0;
drhb2eced52010-08-12 02:41:12 +00002153 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2154 pPage->maskPage = (u16)(pBt->pageSize - 1);
drh43605152004-05-29 21:46:49 +00002155 pPage->nCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00002156 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00002157}
2158
drh897a8202008-09-18 01:08:15 +00002159
2160/*
2161** Convert a DbPage obtained from the pager into a MemPage used by
2162** the btree layer.
2163*/
2164static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
2165 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
drh8dd1c252015-11-04 22:31:02 +00002166 if( pgno!=pPage->pgno ){
2167 pPage->aData = sqlite3PagerGetData(pDbPage);
2168 pPage->pDbPage = pDbPage;
2169 pPage->pBt = pBt;
2170 pPage->pgno = pgno;
2171 pPage->hdrOffset = pgno==1 ? 100 : 0;
2172 }
2173 assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
drh897a8202008-09-18 01:08:15 +00002174 return pPage;
2175}
2176
drhbd03cae2001-06-02 02:40:57 +00002177/*
drh3aac2dd2004-04-26 14:10:20 +00002178** Get a page from the pager. Initialize the MemPage.pBt and
drh7e8c6f12015-05-28 03:28:27 +00002179** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
drh538f5702007-04-13 02:14:30 +00002180**
drh7e8c6f12015-05-28 03:28:27 +00002181** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
2182** about the content of the page at this time. So do not go to the disk
drh538f5702007-04-13 02:14:30 +00002183** to fetch the content. Just fill in the content with zeros for now.
2184** If in the future we call sqlite3PagerWrite() on this page, that
2185** means we have started to be concerned about content and the disk
2186** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00002187*/
danielk197730548662009-07-09 05:07:37 +00002188static int btreeGetPage(
drh16a9b832007-05-05 18:39:25 +00002189 BtShared *pBt, /* The btree */
2190 Pgno pgno, /* Number of the page to fetch */
2191 MemPage **ppPage, /* Return the page in this parameter */
drhb00fc3b2013-08-21 23:42:32 +00002192 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
drh16a9b832007-05-05 18:39:25 +00002193){
drh3aac2dd2004-04-26 14:10:20 +00002194 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00002195 DbPage *pDbPage;
2196
drhb00fc3b2013-08-21 23:42:32 +00002197 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
drh1fee73e2007-08-29 04:00:57 +00002198 assert( sqlite3_mutex_held(pBt->mutex) );
drh9584f582015-11-04 20:22:37 +00002199 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
drh3aac2dd2004-04-26 14:10:20 +00002200 if( rc ) return rc;
drh897a8202008-09-18 01:08:15 +00002201 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
drh3aac2dd2004-04-26 14:10:20 +00002202 return SQLITE_OK;
2203}
2204
2205/*
danielk1977bea2a942009-01-20 17:06:27 +00002206** Retrieve a page from the pager cache. If the requested page is not
2207** already in the pager cache return NULL. Initialize the MemPage.pBt and
2208** MemPage.aData elements if needed.
2209*/
2210static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
2211 DbPage *pDbPage;
2212 assert( sqlite3_mutex_held(pBt->mutex) );
2213 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
2214 if( pDbPage ){
2215 return btreePageFromDbPage(pDbPage, pgno, pBt);
2216 }
2217 return 0;
2218}
2219
2220/*
danielk197789d40042008-11-17 14:20:56 +00002221** Return the size of the database file in pages. If there is any kind of
2222** error, return ((unsigned int)-1).
danielk197767fd7a92008-09-10 17:53:35 +00002223*/
drhb1299152010-03-30 22:58:33 +00002224static Pgno btreePagecount(BtShared *pBt){
2225 return pBt->nPage;
2226}
2227u32 sqlite3BtreeLastPage(Btree *p){
2228 assert( sqlite3BtreeHoldsMutex(p) );
2229 assert( ((p->pBt->nPage)&0x8000000)==0 );
drheac5bd72014-07-25 21:35:39 +00002230 return btreePagecount(p->pBt);
danielk197767fd7a92008-09-10 17:53:35 +00002231}
2232
2233/*
drh28f58dd2015-06-27 19:45:03 +00002234** Get a page from the pager and initialize it.
danielk197789bc4bc2009-07-21 19:25:24 +00002235**
drh15a00212015-06-27 20:55:00 +00002236** If pCur!=0 then the page is being fetched as part of a moveToChild()
2237** call. Do additional sanity checking on the page in this case.
2238** And if the fetch fails, this routine must decrement pCur->iPage.
drh28f58dd2015-06-27 19:45:03 +00002239**
2240** The page is fetched as read-write unless pCur is not NULL and is
2241** a read-only cursor.
2242**
2243** If an error occurs, then *ppPage is undefined. It
danielk197789bc4bc2009-07-21 19:25:24 +00002244** may remain unchanged, or it may be set to an invalid value.
drhde647132004-05-07 17:57:49 +00002245*/
2246static int getAndInitPage(
dan11dcd112013-03-15 18:29:18 +00002247 BtShared *pBt, /* The database file */
2248 Pgno pgno, /* Number of the page to get */
2249 MemPage **ppPage, /* Write the page pointer here */
drh28f58dd2015-06-27 19:45:03 +00002250 BtCursor *pCur, /* Cursor to receive the page, or NULL */
2251 int bReadOnly /* True for a read-only page */
drhde647132004-05-07 17:57:49 +00002252){
2253 int rc;
drh28f58dd2015-06-27 19:45:03 +00002254 DbPage *pDbPage;
drh1fee73e2007-08-29 04:00:57 +00002255 assert( sqlite3_mutex_held(pBt->mutex) );
drh28f58dd2015-06-27 19:45:03 +00002256 assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] );
2257 assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
drh15a00212015-06-27 20:55:00 +00002258 assert( pCur==0 || pCur->iPage>0 );
danielk197789bc4bc2009-07-21 19:25:24 +00002259
danba3cbf32010-06-30 04:29:03 +00002260 if( pgno>btreePagecount(pBt) ){
2261 rc = SQLITE_CORRUPT_BKPT;
drh28f58dd2015-06-27 19:45:03 +00002262 goto getAndInitPage_error;
2263 }
drh9584f582015-11-04 20:22:37 +00002264 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
drh28f58dd2015-06-27 19:45:03 +00002265 if( rc ){
2266 goto getAndInitPage_error;
2267 }
drh8dd1c252015-11-04 22:31:02 +00002268 *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
drh28f58dd2015-06-27 19:45:03 +00002269 if( (*ppPage)->isInit==0 ){
drh8dd1c252015-11-04 22:31:02 +00002270 btreePageFromDbPage(pDbPage, pgno, pBt);
drh28f58dd2015-06-27 19:45:03 +00002271 rc = btreeInitPage(*ppPage);
2272 if( rc!=SQLITE_OK ){
2273 releasePage(*ppPage);
2274 goto getAndInitPage_error;
danielk197789bc4bc2009-07-21 19:25:24 +00002275 }
drhee696e22004-08-30 16:52:17 +00002276 }
drh8dd1c252015-11-04 22:31:02 +00002277 assert( (*ppPage)->pgno==pgno );
2278 assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
danba3cbf32010-06-30 04:29:03 +00002279
drh15a00212015-06-27 20:55:00 +00002280 /* If obtaining a child page for a cursor, we must verify that the page is
2281 ** compatible with the root page. */
drh8dd1c252015-11-04 22:31:02 +00002282 if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
drhcc97ca42017-06-07 22:32:59 +00002283 rc = SQLITE_CORRUPT_PGNO(pgno);
drh28f58dd2015-06-27 19:45:03 +00002284 releasePage(*ppPage);
2285 goto getAndInitPage_error;
2286 }
drh28f58dd2015-06-27 19:45:03 +00002287 return SQLITE_OK;
2288
2289getAndInitPage_error:
2290 if( pCur ) pCur->iPage--;
drh325d0872015-06-29 00:52:33 +00002291 testcase( pgno==0 );
2292 assert( pgno!=0 || rc==SQLITE_CORRUPT );
drhde647132004-05-07 17:57:49 +00002293 return rc;
2294}
2295
dan7fff2e12017-05-29 14:27:37 +00002296#ifndef SQLITE_OMIT_CONCURRENT
2297/*
2298** Set the value of the MemPage.pgnoRoot variable, if it exists.
2299*/
2300static void setMempageRoot(MemPage *pPg, u32 pgnoRoot){
2301 pPg->pgnoRoot = pgnoRoot;
2302}
2303#else
2304# define setMempageRoot(x,y)
2305#endif
2306
drhde647132004-05-07 17:57:49 +00002307/*
drh3aac2dd2004-04-26 14:10:20 +00002308** Release a MemPage. This should be called once for each prior
danielk197730548662009-07-09 05:07:37 +00002309** call to btreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00002310*/
drhbbf0f862015-06-27 14:59:26 +00002311static void releasePageNotNull(MemPage *pPage){
2312 assert( pPage->aData );
2313 assert( pPage->pBt );
2314 assert( pPage->pDbPage!=0 );
2315 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2316 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2317 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2318 sqlite3PagerUnrefNotNull(pPage->pDbPage);
2319}
drh4b70f112004-05-02 21:12:19 +00002320static void releasePage(MemPage *pPage){
drhbbf0f862015-06-27 14:59:26 +00002321 if( pPage ) releasePageNotNull(pPage);
drh3aac2dd2004-04-26 14:10:20 +00002322}
2323
2324/*
drh7e8c6f12015-05-28 03:28:27 +00002325** Get an unused page.
2326**
2327** This works just like btreeGetPage() with the addition:
2328**
2329** * If the page is already in use for some other purpose, immediately
2330** release it and return an SQLITE_CURRUPT error.
2331** * Make sure the isInit flag is clear
2332*/
2333static int btreeGetUnusedPage(
2334 BtShared *pBt, /* The btree */
2335 Pgno pgno, /* Number of the page to fetch */
2336 MemPage **ppPage, /* Return the page in this parameter */
2337 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2338){
2339 int rc = btreeGetPage(pBt, pgno, ppPage, flags);
2340 if( rc==SQLITE_OK ){
2341 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
2342 releasePage(*ppPage);
2343 *ppPage = 0;
2344 return SQLITE_CORRUPT_BKPT;
2345 }
2346 (*ppPage)->isInit = 0;
2347 }else{
2348 *ppPage = 0;
2349 }
2350 return rc;
2351}
2352
2353
2354/*
drha6abd042004-06-09 17:37:22 +00002355** During a rollback, when the pager reloads information into the cache
2356** so that the cache is restored to its original state at the start of
2357** the transaction, for each page restored this routine is called.
2358**
2359** This routine needs to reset the extra data section at the end of the
2360** page to agree with the restored data.
2361*/
danielk1977eaa06f62008-09-18 17:34:44 +00002362static void pageReinit(DbPage *pData){
drh07d183d2005-05-01 22:52:42 +00002363 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00002364 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
danielk1977d217e6f2009-04-01 17:13:51 +00002365 assert( sqlite3PagerPageRefcount(pData)>0 );
danielk197771d5d2c2008-09-29 11:49:47 +00002366 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00002367 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00002368 pPage->isInit = 0;
danielk1977d217e6f2009-04-01 17:13:51 +00002369 if( sqlite3PagerPageRefcount(pData)>1 ){
drh5e8d8872009-03-30 17:19:48 +00002370 /* pPage might not be a btree page; it might be an overflow page
2371 ** or ptrmap page or a free page. In those cases, the following
danielk197730548662009-07-09 05:07:37 +00002372 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
drh5e8d8872009-03-30 17:19:48 +00002373 ** But no harm is done by this. And it is very important that
danielk197730548662009-07-09 05:07:37 +00002374 ** btreeInitPage() be called on every btree page so we make
drh5e8d8872009-03-30 17:19:48 +00002375 ** the call for every page that comes in for re-initing. */
danielk197730548662009-07-09 05:07:37 +00002376 btreeInitPage(pPage);
danielk197771d5d2c2008-09-29 11:49:47 +00002377 }
drha6abd042004-06-09 17:37:22 +00002378 }
2379}
2380
2381/*
drhe5fe6902007-12-07 18:55:28 +00002382** Invoke the busy handler for a btree.
2383*/
danielk19771ceedd32008-11-19 10:22:33 +00002384static int btreeInvokeBusyHandler(void *pArg){
drhe5fe6902007-12-07 18:55:28 +00002385 BtShared *pBt = (BtShared*)pArg;
2386 assert( pBt->db );
2387 assert( sqlite3_mutex_held(pBt->db->mutex) );
2388 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
2389}
2390
2391/*
drhad3e0102004-09-03 23:32:18 +00002392** Open a database file.
2393**
drh382c0242001-10-06 16:33:02 +00002394** zFilename is the name of the database file. If zFilename is NULL
drh75c014c2010-08-30 15:02:28 +00002395** then an ephemeral database is created. The ephemeral database might
2396** be exclusively in memory, or it might use a disk-based memory cache.
2397** Either way, the ephemeral database will be automatically deleted
2398** when sqlite3BtreeClose() is called.
2399**
drhe53831d2007-08-17 01:14:38 +00002400** If zFilename is ":memory:" then an in-memory database is created
2401** that is automatically destroyed when it is closed.
drhc47fd8e2009-04-30 13:30:32 +00002402**
drh33f111d2012-01-17 15:29:14 +00002403** The "flags" parameter is a bitmask that might contain bits like
2404** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
drh75c014c2010-08-30 15:02:28 +00002405**
drhc47fd8e2009-04-30 13:30:32 +00002406** If the database is already opened in the same database connection
2407** and we are in shared cache mode, then the open will fail with an
2408** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
2409** objects in the same database connection since doing so will lead
2410** to problems with locking.
drha059ad02001-04-17 20:09:11 +00002411*/
drh23e11ca2004-05-04 17:27:28 +00002412int sqlite3BtreeOpen(
dan3a6d8ae2011-04-23 15:54:54 +00002413 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
drh3aac2dd2004-04-26 14:10:20 +00002414 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00002415 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00002416 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00002417 int flags, /* Options */
2418 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00002419){
drh7555d8e2009-03-20 13:15:30 +00002420 BtShared *pBt = 0; /* Shared part of btree structure */
2421 Btree *p; /* Handle to return */
2422 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
2423 int rc = SQLITE_OK; /* Result code from this function */
2424 u8 nReserve; /* Byte of unused space on each page */
2425 unsigned char zDbHeader[100]; /* Database header content */
danielk1977aef0bf62005-12-30 16:28:01 +00002426
drh75c014c2010-08-30 15:02:28 +00002427 /* True if opening an ephemeral, temporary database */
2428 const int isTempDb = zFilename==0 || zFilename[0]==0;
2429
danielk1977aef0bf62005-12-30 16:28:01 +00002430 /* Set the variable isMemdb to true for an in-memory database, or
drhb0a7c9c2010-12-06 21:09:59 +00002431 ** false for a file-based database.
danielk1977aef0bf62005-12-30 16:28:01 +00002432 */
drhb0a7c9c2010-12-06 21:09:59 +00002433#ifdef SQLITE_OMIT_MEMORYDB
2434 const int isMemdb = 0;
2435#else
2436 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
drh9c67b2a2012-05-28 13:58:00 +00002437 || (isTempDb && sqlite3TempInMemory(db))
2438 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
danielk1977aef0bf62005-12-30 16:28:01 +00002439#endif
2440
drhe5fe6902007-12-07 18:55:28 +00002441 assert( db!=0 );
dan3a6d8ae2011-04-23 15:54:54 +00002442 assert( pVfs!=0 );
drhe5fe6902007-12-07 18:55:28 +00002443 assert( sqlite3_mutex_held(db->mutex) );
drhd4187c72010-08-30 22:15:45 +00002444 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
2445
2446 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
2447 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
2448
2449 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
2450 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
drh153c62c2007-08-24 03:51:33 +00002451
drh75c014c2010-08-30 15:02:28 +00002452 if( isMemdb ){
2453 flags |= BTREE_MEMORY;
2454 }
2455 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
2456 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
2457 }
drh17435752007-08-16 04:30:38 +00002458 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00002459 if( !p ){
mistachkinfad30392016-02-13 23:43:46 +00002460 return SQLITE_NOMEM_BKPT;
danielk1977aef0bf62005-12-30 16:28:01 +00002461 }
2462 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00002463 p->db = db;
danielk1977602b4662009-07-02 07:47:33 +00002464#ifndef SQLITE_OMIT_SHARED_CACHE
2465 p->lock.pBtree = p;
2466 p->lock.iTable = 1;
2467#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002468
drh198bf392006-01-06 21:52:49 +00002469#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00002470 /*
2471 ** If this Btree is a candidate for shared cache, try to find an
2472 ** existing BtShared object that we can share with
2473 */
drh4ab9d252012-05-26 20:08:49 +00002474 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
drhf1f12682009-09-09 14:17:52 +00002475 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
drh6b5f0eb2015-03-31 16:33:08 +00002476 int nFilename = sqlite3Strlen30(zFilename)+1;
danielk1977adfb9b02007-09-17 07:02:56 +00002477 int nFullPathname = pVfs->mxPathname+1;
drh6b5f0eb2015-03-31 16:33:08 +00002478 char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
drh30ddce62011-10-15 00:16:30 +00002479 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
drh6b5f0eb2015-03-31 16:33:08 +00002480
drhff0587c2007-08-29 17:43:19 +00002481 p->sharable = 1;
drhff0587c2007-08-29 17:43:19 +00002482 if( !zFullPathname ){
2483 sqlite3_free(p);
mistachkinfad30392016-02-13 23:43:46 +00002484 return SQLITE_NOMEM_BKPT;
drhff0587c2007-08-29 17:43:19 +00002485 }
drhafc8b7f2012-05-26 18:06:38 +00002486 if( isMemdb ){
drh6b5f0eb2015-03-31 16:33:08 +00002487 memcpy(zFullPathname, zFilename, nFilename);
drhafc8b7f2012-05-26 18:06:38 +00002488 }else{
2489 rc = sqlite3OsFullPathname(pVfs, zFilename,
2490 nFullPathname, zFullPathname);
2491 if( rc ){
2492 sqlite3_free(zFullPathname);
2493 sqlite3_free(p);
2494 return rc;
2495 }
drh070ad6b2011-11-17 11:43:19 +00002496 }
drh30ddce62011-10-15 00:16:30 +00002497#if SQLITE_THREADSAFE
drh7555d8e2009-03-20 13:15:30 +00002498 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
2499 sqlite3_mutex_enter(mutexOpen);
danielk197759f8c082008-06-18 17:09:10 +00002500 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhff0587c2007-08-29 17:43:19 +00002501 sqlite3_mutex_enter(mutexShared);
drh30ddce62011-10-15 00:16:30 +00002502#endif
drh78f82d12008-09-02 00:52:52 +00002503 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
drhff0587c2007-08-29 17:43:19 +00002504 assert( pBt->nRef>0 );
drhd4e0bb02012-05-27 01:19:04 +00002505 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
drhff0587c2007-08-29 17:43:19 +00002506 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
drhc47fd8e2009-04-30 13:30:32 +00002507 int iDb;
2508 for(iDb=db->nDb-1; iDb>=0; iDb--){
2509 Btree *pExisting = db->aDb[iDb].pBt;
2510 if( pExisting && pExisting->pBt==pBt ){
2511 sqlite3_mutex_leave(mutexShared);
2512 sqlite3_mutex_leave(mutexOpen);
2513 sqlite3_free(zFullPathname);
2514 sqlite3_free(p);
2515 return SQLITE_CONSTRAINT;
2516 }
2517 }
drhff0587c2007-08-29 17:43:19 +00002518 p->pBt = pBt;
2519 pBt->nRef++;
2520 break;
2521 }
2522 }
2523 sqlite3_mutex_leave(mutexShared);
2524 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00002525 }
drhff0587c2007-08-29 17:43:19 +00002526#ifdef SQLITE_DEBUG
2527 else{
2528 /* In debug mode, we mark all persistent databases as sharable
2529 ** even when they are not. This exercises the locking code and
2530 ** gives more opportunity for asserts(sqlite3_mutex_held())
2531 ** statements to find locking problems.
2532 */
2533 p->sharable = 1;
2534 }
2535#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002536 }
2537#endif
drha059ad02001-04-17 20:09:11 +00002538 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00002539 /*
2540 ** The following asserts make sure that structures used by the btree are
2541 ** the right size. This is to guard against size changes that result
2542 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00002543 */
drh062cf272015-03-23 19:03:51 +00002544 assert( sizeof(i64)==8 );
2545 assert( sizeof(u64)==8 );
drhe53831d2007-08-17 01:14:38 +00002546 assert( sizeof(u32)==4 );
2547 assert( sizeof(u16)==2 );
2548 assert( sizeof(Pgno)==4 );
2549
2550 pBt = sqlite3MallocZero( sizeof(*pBt) );
2551 if( pBt==0 ){
mistachkinfad30392016-02-13 23:43:46 +00002552 rc = SQLITE_NOMEM_BKPT;
drhe53831d2007-08-17 01:14:38 +00002553 goto btree_open_out;
2554 }
danielk197771d5d2c2008-09-29 11:49:47 +00002555 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
drha2ee5892016-12-09 16:02:00 +00002556 sizeof(MemPage), flags, vfsFlags, pageReinit);
drhe53831d2007-08-17 01:14:38 +00002557 if( rc==SQLITE_OK ){
drh9b4c59f2013-04-15 17:03:42 +00002558 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
drhe53831d2007-08-17 01:14:38 +00002559 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
2560 }
2561 if( rc!=SQLITE_OK ){
2562 goto btree_open_out;
2563 }
shanehbd2aaf92010-09-01 02:38:21 +00002564 pBt->openFlags = (u8)flags;
danielk19772a50ff02009-04-10 09:47:06 +00002565 pBt->db = db;
danielk19771ceedd32008-11-19 10:22:33 +00002566 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
drhe53831d2007-08-17 01:14:38 +00002567 p->pBt = pBt;
2568
drhe53831d2007-08-17 01:14:38 +00002569 pBt->pCursor = 0;
2570 pBt->pPage1 = 0;
drhc9166342012-01-05 23:32:06 +00002571 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
drha5907a82017-06-19 11:44:22 +00002572#if defined(SQLITE_SECURE_DELETE)
drhc9166342012-01-05 23:32:06 +00002573 pBt->btsFlags |= BTS_SECURE_DELETE;
drha5907a82017-06-19 11:44:22 +00002574#elif defined(SQLITE_FAST_SECURE_DELETE)
2575 pBt->btsFlags |= BTS_OVERWRITE;
drh5b47efa2010-02-12 18:18:39 +00002576#endif
drh113762a2014-11-19 16:36:25 +00002577 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2578 ** determined by the 2-byte integer located at an offset of 16 bytes from
2579 ** the beginning of the database file. */
drhb2eced52010-08-12 02:41:12 +00002580 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
drhe53831d2007-08-17 01:14:38 +00002581 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2582 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002583 pBt->pageSize = 0;
drhe53831d2007-08-17 01:14:38 +00002584#ifndef SQLITE_OMIT_AUTOVACUUM
2585 /* If the magic name ":memory:" will create an in-memory database, then
2586 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2587 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2588 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2589 ** regular file-name. In this case the auto-vacuum applies as per normal.
2590 */
2591 if( zFilename && !isMemdb ){
2592 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2593 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2594 }
2595#endif
2596 nReserve = 0;
2597 }else{
drh113762a2014-11-19 16:36:25 +00002598 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2599 ** determined by the one-byte unsigned integer found at an offset of 20
2600 ** into the database file header. */
drhe53831d2007-08-17 01:14:38 +00002601 nReserve = zDbHeader[20];
drhc9166342012-01-05 23:32:06 +00002602 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
drhe53831d2007-08-17 01:14:38 +00002603#ifndef SQLITE_OMIT_AUTOVACUUM
2604 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2605 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2606#endif
2607 }
drhfa9601a2009-06-18 17:22:39 +00002608 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhc0b61812009-04-30 01:22:41 +00002609 if( rc ) goto btree_open_out;
drhe53831d2007-08-17 01:14:38 +00002610 pBt->usableSize = pBt->pageSize - nReserve;
2611 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
drhe53831d2007-08-17 01:14:38 +00002612
2613#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2614 /* Add the new BtShared object to the linked list sharable BtShareds.
2615 */
dan272989b2016-07-06 10:12:02 +00002616 pBt->nRef = 1;
drhe53831d2007-08-17 01:14:38 +00002617 if( p->sharable ){
drh30ddce62011-10-15 00:16:30 +00002618 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
drh30ddce62011-10-15 00:16:30 +00002619 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
danielk1977075c23a2008-09-01 18:34:20 +00002620 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
danielk197759f8c082008-06-18 17:09:10 +00002621 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00002622 if( pBt->mutex==0 ){
mistachkinfad30392016-02-13 23:43:46 +00002623 rc = SQLITE_NOMEM_BKPT;
drh3285db22007-09-03 22:00:39 +00002624 goto btree_open_out;
2625 }
drhff0587c2007-08-29 17:43:19 +00002626 }
drhe53831d2007-08-17 01:14:38 +00002627 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00002628 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2629 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
drhe53831d2007-08-17 01:14:38 +00002630 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00002631 }
drheee46cf2004-11-06 00:02:48 +00002632#endif
drh90f5ecb2004-07-22 01:19:35 +00002633 }
danielk1977aef0bf62005-12-30 16:28:01 +00002634
drhcfed7bc2006-03-13 14:28:05 +00002635#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00002636 /* If the new Btree uses a sharable pBtShared, then link the new
2637 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00002638 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00002639 */
drhe53831d2007-08-17 01:14:38 +00002640 if( p->sharable ){
2641 int i;
2642 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00002643 for(i=0; i<db->nDb; i++){
2644 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00002645 while( pSib->pPrev ){ pSib = pSib->pPrev; }
drh3bfa7e82016-03-22 14:37:59 +00002646 if( (uptr)p->pBt<(uptr)pSib->pBt ){
drhe53831d2007-08-17 01:14:38 +00002647 p->pNext = pSib;
2648 p->pPrev = 0;
2649 pSib->pPrev = p;
2650 }else{
drh3bfa7e82016-03-22 14:37:59 +00002651 while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
drhe53831d2007-08-17 01:14:38 +00002652 pSib = pSib->pNext;
2653 }
2654 p->pNext = pSib->pNext;
2655 p->pPrev = pSib;
2656 if( p->pNext ){
2657 p->pNext->pPrev = p;
2658 }
2659 pSib->pNext = p;
2660 }
2661 break;
2662 }
2663 }
danielk1977aef0bf62005-12-30 16:28:01 +00002664 }
danielk1977aef0bf62005-12-30 16:28:01 +00002665#endif
2666 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00002667
2668btree_open_out:
2669 if( rc!=SQLITE_OK ){
2670 if( pBt && pBt->pPager ){
dan7fb89902016-08-12 16:21:15 +00002671 sqlite3PagerClose(pBt->pPager, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002672 }
drh17435752007-08-16 04:30:38 +00002673 sqlite3_free(pBt);
2674 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00002675 *ppBtree = 0;
drh75c014c2010-08-30 15:02:28 +00002676 }else{
dan0f5a1862016-08-13 14:30:23 +00002677 sqlite3_file *pFile;
2678
drh75c014c2010-08-30 15:02:28 +00002679 /* If the B-Tree was successfully opened, set the pager-cache size to the
2680 ** default value. Except, when opening on an existing shared pager-cache,
2681 ** do not change the pager-cache size.
2682 */
2683 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2684 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
2685 }
dan0f5a1862016-08-13 14:30:23 +00002686
2687 pFile = sqlite3PagerFile(pBt->pPager);
2688 if( pFile->pMethods ){
2689 sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
2690 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002691 }
drh7555d8e2009-03-20 13:15:30 +00002692 if( mutexOpen ){
2693 assert( sqlite3_mutex_held(mutexOpen) );
2694 sqlite3_mutex_leave(mutexOpen);
2695 }
dan272989b2016-07-06 10:12:02 +00002696 assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00002697 return rc;
drha059ad02001-04-17 20:09:11 +00002698}
2699
2700/*
drhe53831d2007-08-17 01:14:38 +00002701** Decrement the BtShared.nRef counter. When it reaches zero,
2702** remove the BtShared structure from the sharing list. Return
2703** true if the BtShared.nRef counter reaches zero and return
2704** false if it is still positive.
2705*/
2706static int removeFromSharingList(BtShared *pBt){
2707#ifndef SQLITE_OMIT_SHARED_CACHE
drh30ddce62011-10-15 00:16:30 +00002708 MUTEX_LOGIC( sqlite3_mutex *pMaster; )
drhe53831d2007-08-17 01:14:38 +00002709 BtShared *pList;
2710 int removed = 0;
2711
drhd677b3d2007-08-20 22:48:41 +00002712 assert( sqlite3_mutex_notheld(pBt->mutex) );
drh30ddce62011-10-15 00:16:30 +00002713 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
drhe53831d2007-08-17 01:14:38 +00002714 sqlite3_mutex_enter(pMaster);
2715 pBt->nRef--;
2716 if( pBt->nRef<=0 ){
drh78f82d12008-09-02 00:52:52 +00002717 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2718 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
drhe53831d2007-08-17 01:14:38 +00002719 }else{
drh78f82d12008-09-02 00:52:52 +00002720 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
drh34004ce2008-07-11 16:15:17 +00002721 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00002722 pList=pList->pNext;
2723 }
drh34004ce2008-07-11 16:15:17 +00002724 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00002725 pList->pNext = pBt->pNext;
2726 }
2727 }
drh3285db22007-09-03 22:00:39 +00002728 if( SQLITE_THREADSAFE ){
2729 sqlite3_mutex_free(pBt->mutex);
2730 }
drhe53831d2007-08-17 01:14:38 +00002731 removed = 1;
2732 }
2733 sqlite3_mutex_leave(pMaster);
2734 return removed;
2735#else
2736 return 1;
2737#endif
2738}
2739
2740/*
drhf7141992008-06-19 00:16:08 +00002741** Make sure pBt->pTmpSpace points to an allocation of
drh92787cf2014-10-15 11:55:51 +00002742** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
2743** pointer.
drhf7141992008-06-19 00:16:08 +00002744*/
2745static void allocateTempSpace(BtShared *pBt){
2746 if( !pBt->pTmpSpace ){
2747 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
dan14285b72013-10-16 11:39:07 +00002748
2749 /* One of the uses of pBt->pTmpSpace is to format cells before
2750 ** inserting them into a leaf page (function fillInCell()). If
2751 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2752 ** by the various routines that manipulate binary cells. Which
2753 ** can mean that fillInCell() only initializes the first 2 or 3
2754 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2755 ** it into a database page. This is not actually a problem, but it
2756 ** does cause a valgrind error when the 1 or 2 bytes of unitialized
2757 ** data is passed to system call write(). So to avoid this error,
drh92787cf2014-10-15 11:55:51 +00002758 ** zero the first 4 bytes of temp space here.
2759 **
2760 ** Also: Provide four bytes of initialized space before the
2761 ** beginning of pTmpSpace as an area available to prepend the
2762 ** left-child pointer to the beginning of a cell.
2763 */
2764 if( pBt->pTmpSpace ){
2765 memset(pBt->pTmpSpace, 0, 8);
2766 pBt->pTmpSpace += 4;
2767 }
drhf7141992008-06-19 00:16:08 +00002768 }
2769}
2770
2771/*
2772** Free the pBt->pTmpSpace allocation
2773*/
2774static void freeTempSpace(BtShared *pBt){
drh92787cf2014-10-15 11:55:51 +00002775 if( pBt->pTmpSpace ){
2776 pBt->pTmpSpace -= 4;
2777 sqlite3PageFree(pBt->pTmpSpace);
2778 pBt->pTmpSpace = 0;
2779 }
drhf7141992008-06-19 00:16:08 +00002780}
2781
2782/*
drha059ad02001-04-17 20:09:11 +00002783** Close an open database and invalidate all cursors.
2784*/
danielk1977aef0bf62005-12-30 16:28:01 +00002785int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002786 BtShared *pBt = p->pBt;
2787 BtCursor *pCur;
2788
danielk1977aef0bf62005-12-30 16:28:01 +00002789 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00002790 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00002791 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002792 pCur = pBt->pCursor;
2793 while( pCur ){
2794 BtCursor *pTmp = pCur;
2795 pCur = pCur->pNext;
2796 if( pTmp->pBtree==p ){
2797 sqlite3BtreeCloseCursor(pTmp);
2798 }
drha059ad02001-04-17 20:09:11 +00002799 }
danielk1977aef0bf62005-12-30 16:28:01 +00002800
danielk19778d34dfd2006-01-24 16:37:57 +00002801 /* Rollback any active transaction and free the handle structure.
2802 ** The call to sqlite3BtreeRollback() drops any table-locks held by
2803 ** this handle.
2804 */
drh47b7fc72014-11-11 01:33:57 +00002805 sqlite3BtreeRollback(p, SQLITE_OK, 0);
drhe53831d2007-08-17 01:14:38 +00002806 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002807
danielk1977aef0bf62005-12-30 16:28:01 +00002808 /* If there are still other outstanding references to the shared-btree
2809 ** structure, return now. The remainder of this procedure cleans
2810 ** up the shared-btree.
2811 */
drhe53831d2007-08-17 01:14:38 +00002812 assert( p->wantToLock==0 && p->locked==0 );
2813 if( !p->sharable || removeFromSharingList(pBt) ){
2814 /* The pBt is no longer on the sharing list, so we can access
2815 ** it without having to hold the mutex.
2816 **
2817 ** Clean out and delete the BtShared object.
2818 */
2819 assert( !pBt->pCursor );
dan7fb89902016-08-12 16:21:15 +00002820 sqlite3PagerClose(pBt->pPager, p->db);
drhe53831d2007-08-17 01:14:38 +00002821 if( pBt->xFreeSchema && pBt->pSchema ){
2822 pBt->xFreeSchema(pBt->pSchema);
2823 }
drhb9755982010-07-24 16:34:37 +00002824 sqlite3DbFree(0, pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00002825 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00002826 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002827 }
2828
drhe53831d2007-08-17 01:14:38 +00002829#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00002830 assert( p->wantToLock==0 );
2831 assert( p->locked==0 );
2832 if( p->pPrev ) p->pPrev->pNext = p->pNext;
2833 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00002834#endif
2835
drhe53831d2007-08-17 01:14:38 +00002836 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00002837 return SQLITE_OK;
2838}
2839
2840/*
drh9b0cf342015-11-12 14:57:19 +00002841** Change the "soft" limit on the number of pages in the cache.
2842** Unused and unmodified pages will be recycled when the number of
2843** pages in the cache exceeds this soft limit. But the size of the
2844** cache is allowed to grow larger than this limit if it contains
2845** dirty pages or pages still in active use.
drhf57b14a2001-09-14 18:54:08 +00002846*/
danielk1977aef0bf62005-12-30 16:28:01 +00002847int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2848 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00002849 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002850 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00002851 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00002852 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00002853 return SQLITE_OK;
2854}
2855
drh9b0cf342015-11-12 14:57:19 +00002856/*
2857** Change the "spill" limit on the number of pages in the cache.
2858** If the number of pages exceeds this limit during a write transaction,
2859** the pager might attempt to "spill" pages to the journal early in
2860** order to free up memory.
2861**
2862** The value returned is the current spill size. If zero is passed
2863** as an argument, no changes are made to the spill size setting, so
2864** using mxPage of 0 is a way to query the current spill size.
2865*/
2866int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
2867 BtShared *pBt = p->pBt;
2868 int res;
2869 assert( sqlite3_mutex_held(p->db->mutex) );
2870 sqlite3BtreeEnter(p);
2871 res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
2872 sqlite3BtreeLeave(p);
2873 return res;
2874}
2875
drh18c7e402014-03-14 11:46:10 +00002876#if SQLITE_MAX_MMAP_SIZE>0
drhf57b14a2001-09-14 18:54:08 +00002877/*
dan5d8a1372013-03-19 19:28:06 +00002878** Change the limit on the amount of the database file that may be
2879** memory mapped.
2880*/
drh9b4c59f2013-04-15 17:03:42 +00002881int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
dan5d8a1372013-03-19 19:28:06 +00002882 BtShared *pBt = p->pBt;
2883 assert( sqlite3_mutex_held(p->db->mutex) );
2884 sqlite3BtreeEnter(p);
drh9b4c59f2013-04-15 17:03:42 +00002885 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
dan5d8a1372013-03-19 19:28:06 +00002886 sqlite3BtreeLeave(p);
2887 return SQLITE_OK;
2888}
drh18c7e402014-03-14 11:46:10 +00002889#endif /* SQLITE_MAX_MMAP_SIZE>0 */
dan5d8a1372013-03-19 19:28:06 +00002890
2891/*
drh973b6e32003-02-12 14:09:42 +00002892** Change the way data is synced to disk in order to increase or decrease
2893** how well the database resists damage due to OS crashes and power
2894** failures. Level 1 is the same as asynchronous (no syncs() occur and
2895** there is a high probability of damage) Level 2 is the default. There
2896** is a very low but non-zero probability of damage. Level 3 reduces the
2897** probability of damage to near zero but with a write performance reduction.
2898*/
danielk197793758c82005-01-21 08:13:14 +00002899#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drh40c39412013-08-16 20:42:20 +00002900int sqlite3BtreeSetPagerFlags(
drhc97d8462010-11-19 18:23:35 +00002901 Btree *p, /* The btree to set the safety level on */
drh40c39412013-08-16 20:42:20 +00002902 unsigned pgFlags /* Various PAGER_* flags */
drhc97d8462010-11-19 18:23:35 +00002903){
danielk1977aef0bf62005-12-30 16:28:01 +00002904 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00002905 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002906 sqlite3BtreeEnter(p);
drh40c39412013-08-16 20:42:20 +00002907 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
drhd677b3d2007-08-20 22:48:41 +00002908 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00002909 return SQLITE_OK;
2910}
danielk197793758c82005-01-21 08:13:14 +00002911#endif
drh973b6e32003-02-12 14:09:42 +00002912
drh2c8997b2005-08-27 16:36:48 +00002913/*
drh90f5ecb2004-07-22 01:19:35 +00002914** Change the default pages size and the number of reserved bytes per page.
drhce4869f2009-04-02 20:16:58 +00002915** Or, if the page size has already been fixed, return SQLITE_READONLY
2916** without changing anything.
drh06f50212004-11-02 14:24:33 +00002917**
2918** The page size must be a power of 2 between 512 and 65536. If the page
2919** size supplied does not meet this constraint then the page size is not
2920** changed.
2921**
2922** Page sizes are constrained to be a power of two so that the region
2923** of the database file used for locking (beginning at PENDING_BYTE,
2924** the first byte past the 1GB boundary, 0x40000000) needs to occur
2925** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00002926**
2927** If parameter nReserve is less than zero, then the number of reserved
2928** bytes per page is left unchanged.
drhce4869f2009-04-02 20:16:58 +00002929**
drhc9166342012-01-05 23:32:06 +00002930** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
drhce4869f2009-04-02 20:16:58 +00002931** and autovacuum mode can no longer be changed.
drh90f5ecb2004-07-22 01:19:35 +00002932*/
drhce4869f2009-04-02 20:16:58 +00002933int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
danielk1977a1644fd2007-08-29 12:31:25 +00002934 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002935 BtShared *pBt = p->pBt;
drhf49661a2008-12-10 16:45:50 +00002936 assert( nReserve>=-1 && nReserve<=255 );
drhd677b3d2007-08-20 22:48:41 +00002937 sqlite3BtreeEnter(p);
drhad0961b2015-02-21 00:19:25 +00002938#if SQLITE_HAS_CODEC
2939 if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
2940#endif
drhc9166342012-01-05 23:32:06 +00002941 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
drhd677b3d2007-08-20 22:48:41 +00002942 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00002943 return SQLITE_READONLY;
2944 }
2945 if( nReserve<0 ){
2946 nReserve = pBt->pageSize - pBt->usableSize;
2947 }
drhf49661a2008-12-10 16:45:50 +00002948 assert( nReserve>=0 && nReserve<=255 );
drh06f50212004-11-02 14:24:33 +00002949 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2950 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00002951 assert( (pageSize & 7)==0 );
dandd14ecb2015-05-05 10:03:08 +00002952 assert( !pBt->pCursor );
drhb2eced52010-08-12 02:41:12 +00002953 pBt->pageSize = (u32)pageSize;
drhf7141992008-06-19 00:16:08 +00002954 freeTempSpace(pBt);
drh90f5ecb2004-07-22 01:19:35 +00002955 }
drhfa9601a2009-06-18 17:22:39 +00002956 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhf49661a2008-12-10 16:45:50 +00002957 pBt->usableSize = pBt->pageSize - (u16)nReserve;
drhc9166342012-01-05 23:32:06 +00002958 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
drhd677b3d2007-08-20 22:48:41 +00002959 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00002960 return rc;
drh90f5ecb2004-07-22 01:19:35 +00002961}
2962
2963/*
2964** Return the currently defined page size
2965*/
danielk1977aef0bf62005-12-30 16:28:01 +00002966int sqlite3BtreeGetPageSize(Btree *p){
2967 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00002968}
drh7f751222009-03-17 22:33:00 +00002969
dan0094f372012-09-28 20:23:42 +00002970/*
2971** This function is similar to sqlite3BtreeGetReserve(), except that it
2972** may only be called if it is guaranteed that the b-tree mutex is already
2973** held.
2974**
2975** This is useful in one special case in the backup API code where it is
2976** known that the shared b-tree mutex is held, but the mutex on the
2977** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
2978** were to be called, it might collide with some other operation on the
mistachkin48864df2013-03-21 21:20:32 +00002979** database handle that owns *p, causing undefined behavior.
dan0094f372012-09-28 20:23:42 +00002980*/
2981int sqlite3BtreeGetReserveNoMutex(Btree *p){
drhad0961b2015-02-21 00:19:25 +00002982 int n;
dan0094f372012-09-28 20:23:42 +00002983 assert( sqlite3_mutex_held(p->pBt->mutex) );
drhad0961b2015-02-21 00:19:25 +00002984 n = p->pBt->pageSize - p->pBt->usableSize;
2985 return n;
dan0094f372012-09-28 20:23:42 +00002986}
2987
drh7f751222009-03-17 22:33:00 +00002988/*
2989** Return the number of bytes of space at the end of every page that
2990** are intentually left unused. This is the "reserved" space that is
2991** sometimes used by extensions.
drhad0961b2015-02-21 00:19:25 +00002992**
2993** If SQLITE_HAS_MUTEX is defined then the number returned is the
2994** greater of the current reserved space and the maximum requested
2995** reserve space.
drh7f751222009-03-17 22:33:00 +00002996*/
drhad0961b2015-02-21 00:19:25 +00002997int sqlite3BtreeGetOptimalReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002998 int n;
2999 sqlite3BtreeEnter(p);
drhad0961b2015-02-21 00:19:25 +00003000 n = sqlite3BtreeGetReserveNoMutex(p);
3001#ifdef SQLITE_HAS_CODEC
3002 if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
3003#endif
drhd677b3d2007-08-20 22:48:41 +00003004 sqlite3BtreeLeave(p);
3005 return n;
drh2011d5f2004-07-22 02:40:37 +00003006}
drhf8e632b2007-05-08 14:51:36 +00003007
drhad0961b2015-02-21 00:19:25 +00003008
drhf8e632b2007-05-08 14:51:36 +00003009/*
3010** Set the maximum page count for a database if mxPage is positive.
3011** No changes are made if mxPage is 0 or negative.
3012** Regardless of the value of mxPage, return the maximum page count.
3013*/
3014int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00003015 int n;
3016 sqlite3BtreeEnter(p);
3017 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
3018 sqlite3BtreeLeave(p);
3019 return n;
drhf8e632b2007-05-08 14:51:36 +00003020}
drh5b47efa2010-02-12 18:18:39 +00003021
3022/*
drha5907a82017-06-19 11:44:22 +00003023** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
3024**
3025** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
3026** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
3027** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
3028** newFlag==(-1) No changes
3029**
3030** This routine acts as a query if newFlag is less than zero
3031**
3032** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
3033** freelist leaf pages are not written back to the database. Thus in-page
3034** deleted content is cleared, but freelist deleted content is not.
3035**
3036** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
3037** that freelist leaf pages are written back into the database, increasing
3038** the amount of disk I/O.
drh5b47efa2010-02-12 18:18:39 +00003039*/
3040int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
3041 int b;
drhaf034ed2010-02-12 19:46:26 +00003042 if( p==0 ) return 0;
drh5b47efa2010-02-12 18:18:39 +00003043 sqlite3BtreeEnter(p);
drha5907a82017-06-19 11:44:22 +00003044 assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
3045 assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
drh5b47efa2010-02-12 18:18:39 +00003046 if( newFlag>=0 ){
drha5907a82017-06-19 11:44:22 +00003047 p->pBt->btsFlags &= ~BTS_FAST_SECURE;
3048 p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
3049 }
3050 b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
drh5b47efa2010-02-12 18:18:39 +00003051 sqlite3BtreeLeave(p);
3052 return b;
3053}
drh90f5ecb2004-07-22 01:19:35 +00003054
3055/*
danielk1977951af802004-11-05 15:45:09 +00003056** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
3057** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
3058** is disabled. The default value for the auto-vacuum property is
3059** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
3060*/
danielk1977aef0bf62005-12-30 16:28:01 +00003061int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00003062#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00003063 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00003064#else
danielk1977dddbcdc2007-04-26 14:42:34 +00003065 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003066 int rc = SQLITE_OK;
drh076d4662009-02-18 20:31:18 +00003067 u8 av = (u8)autoVacuum;
drhd677b3d2007-08-20 22:48:41 +00003068
3069 sqlite3BtreeEnter(p);
drhc9166342012-01-05 23:32:06 +00003070 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00003071 rc = SQLITE_READONLY;
3072 }else{
drh076d4662009-02-18 20:31:18 +00003073 pBt->autoVacuum = av ?1:0;
3074 pBt->incrVacuum = av==2 ?1:0;
danielk1977951af802004-11-05 15:45:09 +00003075 }
drhd677b3d2007-08-20 22:48:41 +00003076 sqlite3BtreeLeave(p);
3077 return rc;
danielk1977951af802004-11-05 15:45:09 +00003078#endif
3079}
3080
3081/*
3082** Return the value of the 'auto-vacuum' property. If auto-vacuum is
3083** enabled 1 is returned. Otherwise 0.
3084*/
danielk1977aef0bf62005-12-30 16:28:01 +00003085int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00003086#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00003087 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00003088#else
drhd677b3d2007-08-20 22:48:41 +00003089 int rc;
3090 sqlite3BtreeEnter(p);
3091 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00003092 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
3093 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
3094 BTREE_AUTOVACUUM_INCR
3095 );
drhd677b3d2007-08-20 22:48:41 +00003096 sqlite3BtreeLeave(p);
3097 return rc;
danielk1977951af802004-11-05 15:45:09 +00003098#endif
3099}
3100
danf5da7db2017-03-16 18:14:39 +00003101/*
3102** If the user has not set the safety-level for this database connection
3103** using "PRAGMA synchronous", and if the safety-level is not already
3104** set to the value passed to this function as the second parameter,
3105** set it so.
3106*/
3107#if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS
3108static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
3109 sqlite3 *db;
3110 Db *pDb;
3111 if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
3112 while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
3113 if( pDb->bSyncSet==0
3114 && pDb->safety_level!=safety_level
3115 && pDb!=&db->aDb[1]
3116 ){
3117 pDb->safety_level = safety_level;
3118 sqlite3PagerSetFlags(pBt->pPager,
3119 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
3120 }
3121 }
3122}
3123#else
danfc8f4b62017-03-16 18:54:42 +00003124# define setDefaultSyncFlag(pBt,safety_level)
danf5da7db2017-03-16 18:14:39 +00003125#endif
danielk1977951af802004-11-05 15:45:09 +00003126
3127/*
drha34b6762004-05-07 13:30:42 +00003128** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00003129** also acquire a readlock on that file.
3130**
3131** SQLITE_OK is returned on success. If the file is not a
3132** well-formed database file, then SQLITE_CORRUPT is returned.
3133** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00003134** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00003135*/
danielk1977aef0bf62005-12-30 16:28:01 +00003136static int lockBtree(BtShared *pBt){
drhc2a4bab2010-04-02 12:46:45 +00003137 int rc; /* Result code from subfunctions */
3138 MemPage *pPage1; /* Page 1 of the database file */
3139 int nPage; /* Number of pages in the database */
3140 int nPageFile = 0; /* Number of pages in the database file */
3141 int nPageHeader; /* Number of pages in the database according to hdr */
drhd677b3d2007-08-20 22:48:41 +00003142
drh1fee73e2007-08-29 04:00:57 +00003143 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977295dc102009-04-01 19:07:03 +00003144 assert( pBt->pPage1==0 );
danielk197789bc4bc2009-07-21 19:25:24 +00003145 rc = sqlite3PagerSharedLock(pBt->pPager);
3146 if( rc!=SQLITE_OK ) return rc;
drhb00fc3b2013-08-21 23:42:32 +00003147 rc = btreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00003148 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00003149
3150 /* Do some checking to help insure the file we opened really is
3151 ** a valid database file.
3152 */
drhc2a4bab2010-04-02 12:46:45 +00003153 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
drh8fb8b532010-08-14 17:12:04 +00003154 sqlite3PagerPagecount(pBt->pPager, &nPageFile);
drhb28e59b2010-06-17 02:13:39 +00003155 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
drhc2a4bab2010-04-02 12:46:45 +00003156 nPage = nPageFile;
drh97b59a52010-03-31 02:31:33 +00003157 }
3158 if( nPage>0 ){
drh43b18e12010-08-17 19:40:08 +00003159 u32 pageSize;
3160 u32 usableSize;
drhb6f41482004-05-14 01:58:11 +00003161 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00003162 rc = SQLITE_NOTADB;
drh113762a2014-11-19 16:36:25 +00003163 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
3164 ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
3165 ** 61 74 20 33 00. */
drhb6f41482004-05-14 01:58:11 +00003166 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00003167 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00003168 }
dan5cf53532010-05-01 16:40:20 +00003169
3170#ifdef SQLITE_OMIT_WAL
3171 if( page1[18]>1 ){
drhc9166342012-01-05 23:32:06 +00003172 pBt->btsFlags |= BTS_READ_ONLY;
dan5cf53532010-05-01 16:40:20 +00003173 }
3174 if( page1[19]>1 ){
3175 goto page1_init_failed;
3176 }
3177#else
dane04dc882010-04-20 18:53:15 +00003178 if( page1[18]>2 ){
drhc9166342012-01-05 23:32:06 +00003179 pBt->btsFlags |= BTS_READ_ONLY;
drh309169a2007-04-24 17:27:51 +00003180 }
dane04dc882010-04-20 18:53:15 +00003181 if( page1[19]>2 ){
drhb6f41482004-05-14 01:58:11 +00003182 goto page1_init_failed;
3183 }
drhe5ae5732008-06-15 02:51:47 +00003184
dana470aeb2010-04-21 11:43:38 +00003185 /* If the write version is set to 2, this database should be accessed
3186 ** in WAL mode. If the log is not already open, open it now. Then
3187 ** return SQLITE_OK and return without populating BtShared.pPage1.
3188 ** The caller detects this and calls this function again. This is
3189 ** required as the version of page 1 currently in the page1 buffer
3190 ** may not be the latest version - there may be a newer one in the log
3191 ** file.
3192 */
drhc9166342012-01-05 23:32:06 +00003193 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
dane04dc882010-04-20 18:53:15 +00003194 int isOpen = 0;
drh7ed91f22010-04-29 22:34:07 +00003195 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
dane04dc882010-04-20 18:53:15 +00003196 if( rc!=SQLITE_OK ){
3197 goto page1_init_failed;
drhe243de52016-03-08 15:14:26 +00003198 }else{
danf5da7db2017-03-16 18:14:39 +00003199 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
drhe243de52016-03-08 15:14:26 +00003200 if( isOpen==0 ){
3201 releasePage(pPage1);
3202 return SQLITE_OK;
3203 }
dane04dc882010-04-20 18:53:15 +00003204 }
dan8b5444b2010-04-27 14:37:47 +00003205 rc = SQLITE_NOTADB;
danf5da7db2017-03-16 18:14:39 +00003206 }else{
3207 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
dane04dc882010-04-20 18:53:15 +00003208 }
dan5cf53532010-05-01 16:40:20 +00003209#endif
dane04dc882010-04-20 18:53:15 +00003210
drh113762a2014-11-19 16:36:25 +00003211 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
3212 ** fractions and the leaf payload fraction values must be 64, 32, and 32.
3213 **
drhe5ae5732008-06-15 02:51:47 +00003214 ** The original design allowed these amounts to vary, but as of
3215 ** version 3.6.0, we require them to be fixed.
3216 */
3217 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
3218 goto page1_init_failed;
3219 }
drh113762a2014-11-19 16:36:25 +00003220 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
3221 ** determined by the 2-byte integer located at an offset of 16 bytes from
3222 ** the beginning of the database file. */
drhb2eced52010-08-12 02:41:12 +00003223 pageSize = (page1[16]<<8) | (page1[17]<<16);
drh113762a2014-11-19 16:36:25 +00003224 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
3225 ** between 512 and 65536 inclusive. */
drhb2eced52010-08-12 02:41:12 +00003226 if( ((pageSize-1)&pageSize)!=0
3227 || pageSize>SQLITE_MAX_PAGE_SIZE
3228 || pageSize<=256
drh7dc385e2007-09-06 23:39:36 +00003229 ){
drh07d183d2005-05-01 22:52:42 +00003230 goto page1_init_failed;
3231 }
3232 assert( (pageSize & 7)==0 );
drh113762a2014-11-19 16:36:25 +00003233 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
3234 ** integer at offset 20 is the number of bytes of space at the end of
3235 ** each page to reserve for extensions.
3236 **
3237 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
3238 ** determined by the one-byte unsigned integer found at an offset of 20
3239 ** into the database file header. */
danielk1977f653d782008-03-20 11:04:21 +00003240 usableSize = pageSize - page1[20];
shaneh1df2db72010-08-18 02:28:48 +00003241 if( (u32)pageSize!=pBt->pageSize ){
danielk1977f653d782008-03-20 11:04:21 +00003242 /* After reading the first page of the database assuming a page size
3243 ** of BtShared.pageSize, we have discovered that the page-size is
3244 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
3245 ** zero and return SQLITE_OK. The caller will call this function
3246 ** again with the correct page-size.
3247 */
3248 releasePage(pPage1);
drh43b18e12010-08-17 19:40:08 +00003249 pBt->usableSize = usableSize;
3250 pBt->pageSize = pageSize;
drhf7141992008-06-19 00:16:08 +00003251 freeTempSpace(pBt);
drhfa9601a2009-06-18 17:22:39 +00003252 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
3253 pageSize-usableSize);
drh5e483932009-07-10 16:51:30 +00003254 return rc;
danielk1977f653d782008-03-20 11:04:21 +00003255 }
drh169dd922017-06-26 13:57:49 +00003256 if( (pBt->db->flags & SQLITE_WriteSchema)==0 && nPage>nPageFile ){
drhc2a4bab2010-04-02 12:46:45 +00003257 rc = SQLITE_CORRUPT_BKPT;
3258 goto page1_init_failed;
3259 }
drh113762a2014-11-19 16:36:25 +00003260 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
3261 ** be less than 480. In other words, if the page size is 512, then the
3262 ** reserved space size cannot exceed 32. */
drhb33e1b92009-06-18 11:29:20 +00003263 if( usableSize<480 ){
drhb6f41482004-05-14 01:58:11 +00003264 goto page1_init_failed;
3265 }
drh43b18e12010-08-17 19:40:08 +00003266 pBt->pageSize = pageSize;
3267 pBt->usableSize = usableSize;
drh057cd3a2005-02-15 16:23:02 +00003268#ifndef SQLITE_OMIT_AUTOVACUUM
3269 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00003270 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00003271#endif
drh306dc212001-05-21 13:45:10 +00003272 }
drhb6f41482004-05-14 01:58:11 +00003273
3274 /* maxLocal is the maximum amount of payload to store locally for
3275 ** a cell. Make sure it is small enough so that at least minFanout
3276 ** cells can will fit on one page. We assume a 10-byte page header.
3277 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00003278 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00003279 ** 4-byte child pointer
3280 ** 9-byte nKey value
3281 ** 4-byte nData value
3282 ** 4-byte overflow page pointer
drhe22e03e2010-08-18 21:19:03 +00003283 ** So a cell consists of a 2-byte pointer, a header which is as much as
drh43605152004-05-29 21:46:49 +00003284 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
3285 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00003286 */
shaneh1df2db72010-08-18 02:28:48 +00003287 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
3288 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
3289 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
3290 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
drhc9166342012-01-05 23:32:06 +00003291 if( pBt->maxLocal>127 ){
3292 pBt->max1bytePayload = 127;
3293 }else{
mistachkin0547e2f2012-01-08 00:54:02 +00003294 pBt->max1bytePayload = (u8)pBt->maxLocal;
drhc9166342012-01-05 23:32:06 +00003295 }
drh2e38c322004-09-03 18:38:44 +00003296 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00003297 pBt->pPage1 = pPage1;
drhdd3cd972010-03-27 17:12:36 +00003298 pBt->nPage = nPage;
drhb6f41482004-05-14 01:58:11 +00003299 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00003300
drh72f82862001-05-24 21:06:34 +00003301page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00003302 releasePage(pPage1);
3303 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00003304 return rc;
drh306dc212001-05-21 13:45:10 +00003305}
3306
drh85ec3b62013-05-14 23:12:06 +00003307#ifndef NDEBUG
3308/*
3309** Return the number of cursors open on pBt. This is for use
3310** in assert() expressions, so it is only compiled if NDEBUG is not
3311** defined.
3312**
3313** Only write cursors are counted if wrOnly is true. If wrOnly is
3314** false then all cursors are counted.
3315**
3316** For the purposes of this routine, a cursor is any cursor that
peter.d.reid60ec9142014-09-06 16:39:46 +00003317** is capable of reading or writing to the database. Cursors that
drh85ec3b62013-05-14 23:12:06 +00003318** have been tripped into the CURSOR_FAULT state are not counted.
3319*/
3320static int countValidCursors(BtShared *pBt, int wrOnly){
3321 BtCursor *pCur;
3322 int r = 0;
3323 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drh036dbec2014-03-11 23:40:44 +00003324 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
3325 && pCur->eState!=CURSOR_FAULT ) r++;
drh85ec3b62013-05-14 23:12:06 +00003326 }
3327 return r;
3328}
3329#endif
3330
drh306dc212001-05-21 13:45:10 +00003331/*
drhb8ca3072001-12-05 00:21:20 +00003332** If there are no outstanding cursors and we are not in the middle
3333** of a transaction but there is a read lock on the database, then
3334** this routine unrefs the first page of the database file which
3335** has the effect of releasing the read lock.
3336**
drhb8ca3072001-12-05 00:21:20 +00003337** If there is a transaction in progress, this routine is a no-op.
3338*/
danielk1977aef0bf62005-12-30 16:28:01 +00003339static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00003340 assert( sqlite3_mutex_held(pBt->mutex) );
drh85ec3b62013-05-14 23:12:06 +00003341 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
danielk19771bc9ee92009-07-04 15:41:02 +00003342 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
drhb2325b72014-09-24 18:31:07 +00003343 MemPage *pPage1 = pBt->pPage1;
3344 assert( pPage1->aData );
danielk1977c1761e82009-06-25 09:40:03 +00003345 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
drh3aac2dd2004-04-26 14:10:20 +00003346 pBt->pPage1 = 0;
drhbbf0f862015-06-27 14:59:26 +00003347 releasePageNotNull(pPage1);
drhb8ca3072001-12-05 00:21:20 +00003348 }
3349}
3350
3351/*
drhe39f2f92009-07-23 01:43:59 +00003352** If pBt points to an empty file then convert that empty file
3353** into a new empty database by initializing the first page of
3354** the database.
drh8b2f49b2001-06-08 00:21:52 +00003355*/
danielk1977aef0bf62005-12-30 16:28:01 +00003356static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00003357 MemPage *pP1;
3358 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00003359 int rc;
drhd677b3d2007-08-20 22:48:41 +00003360
drh1fee73e2007-08-29 04:00:57 +00003361 assert( sqlite3_mutex_held(pBt->mutex) );
drhdd3cd972010-03-27 17:12:36 +00003362 if( pBt->nPage>0 ){
3363 return SQLITE_OK;
danielk1977ad0132d2008-06-07 08:58:22 +00003364 }
drh3aac2dd2004-04-26 14:10:20 +00003365 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00003366 assert( pP1!=0 );
3367 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00003368 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00003369 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00003370 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
3371 assert( sizeof(zMagicHeader)==16 );
shaneh1df2db72010-08-18 02:28:48 +00003372 data[16] = (u8)((pBt->pageSize>>8)&0xff);
3373 data[17] = (u8)((pBt->pageSize>>16)&0xff);
drh9e572e62004-04-23 23:43:10 +00003374 data[18] = 1;
3375 data[19] = 1;
drhf49661a2008-12-10 16:45:50 +00003376 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
3377 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
drhe5ae5732008-06-15 02:51:47 +00003378 data[21] = 64;
3379 data[22] = 32;
3380 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00003381 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00003382 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhc9166342012-01-05 23:32:06 +00003383 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
danielk1977003ba062004-11-04 02:57:33 +00003384#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00003385 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00003386 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00003387 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00003388 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00003389#endif
drhdd3cd972010-03-27 17:12:36 +00003390 pBt->nPage = 1;
3391 data[31] = 1;
drh8b2f49b2001-06-08 00:21:52 +00003392 return SQLITE_OK;
3393}
3394
3395/*
danb483eba2012-10-13 19:58:11 +00003396** Initialize the first page of the database file (creating a database
3397** consisting of a single page and no schema objects). Return SQLITE_OK
3398** if successful, or an SQLite error code otherwise.
3399*/
3400int sqlite3BtreeNewDb(Btree *p){
3401 int rc;
3402 sqlite3BtreeEnter(p);
3403 p->pBt->nPage = 0;
3404 rc = newDatabase(p->pBt);
3405 sqlite3BtreeLeave(p);
3406 return rc;
3407}
3408
3409/*
danielk1977ee5741e2004-05-31 10:01:34 +00003410** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00003411** is started if the second argument is nonzero, otherwise a read-
3412** transaction. If the second argument is 2 or more and exclusive
3413** transaction is started, meaning that no other process is allowed
3414** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00003415** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00003416** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00003417**
danielk1977ee5741e2004-05-31 10:01:34 +00003418** A write-transaction must be started before attempting any
3419** changes to the database. None of the following routines
3420** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00003421**
drh23e11ca2004-05-04 17:27:28 +00003422** sqlite3BtreeCreateTable()
3423** sqlite3BtreeCreateIndex()
3424** sqlite3BtreeClearTable()
3425** sqlite3BtreeDropTable()
3426** sqlite3BtreeInsert()
3427** sqlite3BtreeDelete()
3428** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00003429**
drhb8ef32c2005-03-14 02:01:49 +00003430** If an initial attempt to acquire the lock fails because of lock contention
3431** and the database was previously unlocked, then invoke the busy handler
3432** if there is one. But if there was previously a read-lock, do not
3433** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
3434** returned when there is already a read-lock in order to avoid a deadlock.
3435**
3436** Suppose there are two processes A and B. A has a read lock and B has
3437** a reserved lock. B tries to promote to exclusive but is blocked because
3438** of A's read lock. A tries to promote to reserved but is blocked by B.
3439** One or the other of the two processes must give way or there can be
3440** no progress. By returning SQLITE_BUSY and not invoking the busy callback
3441** when A already has a read lock, we encourage A to give up and let B
3442** proceed.
drha059ad02001-04-17 20:09:11 +00003443*/
danielk1977aef0bf62005-12-30 16:28:01 +00003444int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
3445 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00003446 int rc = SQLITE_OK;
dan987f8212015-08-27 17:42:38 +00003447 int bConcurrent = (p->db->bConcurrent && !ISAUTOVACUUM);
danielk1977ee5741e2004-05-31 10:01:34 +00003448
drhd677b3d2007-08-20 22:48:41 +00003449 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003450 btreeIntegrity(p);
3451
danielk1977ee5741e2004-05-31 10:01:34 +00003452 /* If the btree is already in a write-transaction, or it
3453 ** is already in a read-transaction and a read-transaction
3454 ** is requested, this is a no-op.
3455 */
danielk1977aef0bf62005-12-30 16:28:01 +00003456 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00003457 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00003458 }
dan56c517a2013-09-26 11:04:33 +00003459 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
drhb8ef32c2005-03-14 02:01:49 +00003460
3461 /* Write transactions are not possible on a read-only database */
drhc9166342012-01-05 23:32:06 +00003462 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00003463 rc = SQLITE_READONLY;
3464 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00003465 }
3466
danielk1977404ca072009-03-16 13:19:36 +00003467#ifndef SQLITE_OMIT_SHARED_CACHE
drh5a1fb182016-01-08 19:34:39 +00003468 {
3469 sqlite3 *pBlock = 0;
3470 /* If another database handle has already opened a write transaction
3471 ** on this shared-btree structure and a second write transaction is
3472 ** requested, return SQLITE_LOCKED.
3473 */
3474 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
3475 || (pBt->btsFlags & BTS_PENDING)!=0
3476 ){
3477 pBlock = pBt->pWriter->db;
3478 }else if( wrflag>1 ){
3479 BtLock *pIter;
3480 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
3481 if( pIter->pBtree!=p ){
3482 pBlock = pIter->pBtree->db;
3483 break;
3484 }
danielk1977641b0f42007-12-21 04:47:25 +00003485 }
3486 }
drh5a1fb182016-01-08 19:34:39 +00003487 if( pBlock ){
3488 sqlite3ConnectionBlocked(p->db, pBlock);
3489 rc = SQLITE_LOCKED_SHAREDCACHE;
3490 goto trans_begun;
3491 }
danielk1977404ca072009-03-16 13:19:36 +00003492 }
danielk1977641b0f42007-12-21 04:47:25 +00003493#endif
3494
danielk1977602b4662009-07-02 07:47:33 +00003495 /* Any read-only or read-write transaction implies a read-lock on
3496 ** page 1. So if some other shared-cache client already has a write-lock
3497 ** on page 1, the transaction cannot be opened. */
drh4c301aa2009-07-15 17:25:45 +00003498 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
3499 if( SQLITE_OK!=rc ) goto trans_begun;
danielk1977602b4662009-07-02 07:47:33 +00003500
drhc9166342012-01-05 23:32:06 +00003501 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
3502 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
drhb8ef32c2005-03-14 02:01:49 +00003503 do {
danielk1977295dc102009-04-01 19:07:03 +00003504 /* Call lockBtree() until either pBt->pPage1 is populated or
3505 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
3506 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
3507 ** reading page 1 it discovers that the page-size of the database
3508 ** file is not pBt->pageSize. In this case lockBtree() will update
3509 ** pBt->pageSize to the page-size of the file on disk.
3510 */
3511 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
drh309169a2007-04-24 17:27:51 +00003512
drhb8ef32c2005-03-14 02:01:49 +00003513 if( rc==SQLITE_OK && wrflag ){
drhc9166342012-01-05 23:32:06 +00003514 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
drh309169a2007-04-24 17:27:51 +00003515 rc = SQLITE_READONLY;
3516 }else{
dan987f8212015-08-27 17:42:38 +00003517 int exFlag = bConcurrent ? -1 : (wrflag>1);
3518 rc = sqlite3PagerBegin(pBt->pPager, exFlag, sqlite3TempInMemory(p->db));
drh309169a2007-04-24 17:27:51 +00003519 if( rc==SQLITE_OK ){
3520 rc = newDatabase(pBt);
3521 }
drhb8ef32c2005-03-14 02:01:49 +00003522 }
3523 }
3524
danielk1977bd434552009-03-18 10:33:00 +00003525 if( rc!=SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00003526 unlockBtreeIfUnused(pBt);
3527 }
danf9b76712010-06-01 14:12:45 +00003528 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
danielk19771ceedd32008-11-19 10:22:33 +00003529 btreeInvokeBusyHandler(pBt) );
danielk1977aef0bf62005-12-30 16:28:01 +00003530
3531 if( rc==SQLITE_OK ){
3532 if( p->inTrans==TRANS_NONE ){
3533 pBt->nTransaction++;
danielk1977602b4662009-07-02 07:47:33 +00003534#ifndef SQLITE_OMIT_SHARED_CACHE
3535 if( p->sharable ){
drhf2f105d2012-08-20 15:53:54 +00003536 assert( p->lock.pBtree==p && p->lock.iTable==1 );
danielk1977602b4662009-07-02 07:47:33 +00003537 p->lock.eLock = READ_LOCK;
3538 p->lock.pNext = pBt->pLock;
3539 pBt->pLock = &p->lock;
3540 }
3541#endif
danielk1977aef0bf62005-12-30 16:28:01 +00003542 }
3543 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
3544 if( p->inTrans>pBt->inTransaction ){
3545 pBt->inTransaction = p->inTrans;
3546 }
danielk1977404ca072009-03-16 13:19:36 +00003547 if( wrflag ){
dan59257dc2010-08-04 11:34:31 +00003548 MemPage *pPage1 = pBt->pPage1;
3549#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977404ca072009-03-16 13:19:36 +00003550 assert( !pBt->pWriter );
3551 pBt->pWriter = p;
drhc9166342012-01-05 23:32:06 +00003552 pBt->btsFlags &= ~BTS_EXCLUSIVE;
3553 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
danielk1977641b0f42007-12-21 04:47:25 +00003554#endif
dan59257dc2010-08-04 11:34:31 +00003555
3556 /* If the db-size header field is incorrect (as it may be if an old
3557 ** client has been writing the database file), update it now. Doing
3558 ** this sooner rather than later means the database size can safely
3559 ** re-read the database size from page 1 if a savepoint or transaction
3560 ** rollback occurs within the transaction.
3561 */
3562 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
3563 rc = sqlite3PagerWrite(pPage1->pDbPage);
3564 if( rc==SQLITE_OK ){
3565 put4byte(&pPage1->aData[28], pBt->nPage);
3566 }
3567 }
3568 }
danielk1977aef0bf62005-12-30 16:28:01 +00003569 }
3570
drhd677b3d2007-08-20 22:48:41 +00003571
3572trans_begun:
drh01be4632015-09-03 15:17:12 +00003573#ifndef SQLITE_OMIT_CONCURRENT
dan987f8212015-08-27 17:42:38 +00003574 if( bConcurrent && rc==SQLITE_OK && sqlite3PagerIsWal(pBt->pPager) ){
3575 rc = sqlite3PagerBeginConcurrent(pBt->pPager);
3576 if( rc==SQLITE_OK && wrflag ){
3577 rc = btreePtrmapAllocate(pBt);
3578 }
3579 }
3580#endif
3581
danielk1977fd7f0452008-12-17 17:30:26 +00003582 if( rc==SQLITE_OK && wrflag ){
danielk197712dd5492008-12-18 15:45:07 +00003583 /* This call makes sure that the pager has the correct number of
3584 ** open savepoints. If the second parameter is greater than 0 and
3585 ** the sub-journal is not already open, then it will be opened here.
3586 */
dan7b3d71e2015-08-19 20:27:05 +00003587 int nSavepoint = p->db->nSavepoint;
3588 rc = sqlite3PagerOpenSavepoint(pBt->pPager, nSavepoint);
danf5cebf72015-08-22 17:28:55 +00003589 if( rc==SQLITE_OK && nSavepoint ){
3590 rc = btreePtrmapBegin(pBt, nSavepoint);
dan7b3d71e2015-08-19 20:27:05 +00003591 }
danielk1977fd7f0452008-12-17 17:30:26 +00003592 }
danielk197712dd5492008-12-18 15:45:07 +00003593
danielk1977aef0bf62005-12-30 16:28:01 +00003594 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00003595 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00003596 return rc;
drha059ad02001-04-17 20:09:11 +00003597}
3598
danielk1977687566d2004-11-02 12:56:41 +00003599#ifndef SQLITE_OMIT_AUTOVACUUM
3600
3601/*
3602** Set the pointer-map entries for all children of page pPage. Also, if
3603** pPage contains cells that point to overflow pages, set the pointer
3604** map entries for the overflow pages as well.
3605*/
3606static int setChildPtrmaps(MemPage *pPage){
3607 int i; /* Counter variable */
3608 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00003609 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00003610 BtShared *pBt = pPage->pBt;
danielk1977687566d2004-11-02 12:56:41 +00003611 Pgno pgno = pPage->pgno;
3612
drh1fee73e2007-08-29 04:00:57 +00003613 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh14e845a2017-05-25 21:35:56 +00003614 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
drh2a702542016-12-12 18:12:03 +00003615 if( rc!=SQLITE_OK ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00003616 nCell = pPage->nCell;
3617
3618 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00003619 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00003620
drh98add2e2009-07-20 17:11:49 +00003621 ptrmapPutOvflPtr(pPage, pCell, &rc);
danielk197726836652005-01-17 01:33:13 +00003622
danielk1977687566d2004-11-02 12:56:41 +00003623 if( !pPage->leaf ){
3624 Pgno childPgno = get4byte(pCell);
drh98add2e2009-07-20 17:11:49 +00003625 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00003626 }
3627 }
3628
3629 if( !pPage->leaf ){
3630 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh98add2e2009-07-20 17:11:49 +00003631 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00003632 }
3633
danielk1977687566d2004-11-02 12:56:41 +00003634 return rc;
3635}
3636
3637/*
drhf3aed592009-07-08 18:12:49 +00003638** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
3639** that it points to iTo. Parameter eType describes the type of pointer to
3640** be modified, as follows:
danielk1977687566d2004-11-02 12:56:41 +00003641**
3642** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
3643** page of pPage.
3644**
3645** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3646** page pointed to by one of the cells on pPage.
3647**
3648** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3649** overflow page in the list.
3650*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00003651static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00003652 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00003653 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977687566d2004-11-02 12:56:41 +00003654 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00003655 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00003656 if( get4byte(pPage->aData)!=iFrom ){
drhcc97ca42017-06-07 22:32:59 +00003657 return SQLITE_CORRUPT_PGNO(pPage->pgno);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003658 }
danielk1977f78fc082004-11-02 14:40:32 +00003659 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00003660 }else{
danielk1977687566d2004-11-02 12:56:41 +00003661 int i;
3662 int nCell;
drha1f75d92015-05-24 10:18:12 +00003663 int rc;
danielk1977687566d2004-11-02 12:56:41 +00003664
drh14e845a2017-05-25 21:35:56 +00003665 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
drha1f75d92015-05-24 10:18:12 +00003666 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00003667 nCell = pPage->nCell;
3668
danielk1977687566d2004-11-02 12:56:41 +00003669 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00003670 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00003671 if( eType==PTRMAP_OVERFLOW1 ){
3672 CellInfo info;
drh5fa60512015-06-19 17:19:34 +00003673 pPage->xParseCell(pPage, pCell, &info);
drhb701c9a2017-01-12 15:11:03 +00003674 if( info.nLocal<info.nPayload ){
3675 if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
drhcc97ca42017-06-07 22:32:59 +00003676 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drhb701c9a2017-01-12 15:11:03 +00003677 }
3678 if( iFrom==get4byte(pCell+info.nSize-4) ){
3679 put4byte(pCell+info.nSize-4, iTo);
3680 break;
3681 }
danielk1977687566d2004-11-02 12:56:41 +00003682 }
3683 }else{
3684 if( get4byte(pCell)==iFrom ){
3685 put4byte(pCell, iTo);
3686 break;
3687 }
3688 }
3689 }
3690
3691 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00003692 if( eType!=PTRMAP_BTREE ||
3693 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drhcc97ca42017-06-07 22:32:59 +00003694 return SQLITE_CORRUPT_PGNO(pPage->pgno);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003695 }
danielk1977687566d2004-11-02 12:56:41 +00003696 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3697 }
danielk1977687566d2004-11-02 12:56:41 +00003698 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00003699 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00003700}
3701
danielk1977003ba062004-11-04 02:57:33 +00003702
danielk19777701e812005-01-10 12:59:51 +00003703/*
3704** Move the open database page pDbPage to location iFreePage in the
3705** database. The pDbPage reference remains valid.
drhe64ca7b2009-07-16 18:21:17 +00003706**
3707** The isCommit flag indicates that there is no need to remember that
3708** the journal needs to be sync()ed before database page pDbPage->pgno
3709** can be written to. The caller has already promised not to write to that
3710** page.
danielk19777701e812005-01-10 12:59:51 +00003711*/
danielk1977003ba062004-11-04 02:57:33 +00003712static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00003713 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00003714 MemPage *pDbPage, /* Open page to move */
3715 u8 eType, /* Pointer map 'type' entry for pDbPage */
3716 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00003717 Pgno iFreePage, /* The location to move pDbPage to */
drhe64ca7b2009-07-16 18:21:17 +00003718 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
danielk1977003ba062004-11-04 02:57:33 +00003719){
3720 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
3721 Pgno iDbPage = pDbPage->pgno;
3722 Pager *pPager = pBt->pPager;
3723 int rc;
3724
danielk1977a0bf2652004-11-04 14:30:04 +00003725 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3726 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00003727 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00003728 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00003729
drh85b623f2007-12-13 21:54:09 +00003730 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00003731 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
3732 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00003733 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00003734 if( rc!=SQLITE_OK ){
3735 return rc;
3736 }
3737 pDbPage->pgno = iFreePage;
3738
3739 /* If pDbPage was a btree-page, then it may have child pages and/or cells
3740 ** that point to overflow pages. The pointer map entries for all these
3741 ** pages need to be changed.
3742 **
3743 ** If pDbPage is an overflow page, then the first 4 bytes may store a
3744 ** pointer to a subsequent overflow page. If this is the case, then
3745 ** the pointer map needs to be updated for the subsequent overflow page.
3746 */
danielk1977a0bf2652004-11-04 14:30:04 +00003747 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00003748 rc = setChildPtrmaps(pDbPage);
3749 if( rc!=SQLITE_OK ){
3750 return rc;
3751 }
3752 }else{
3753 Pgno nextOvfl = get4byte(pDbPage->aData);
3754 if( nextOvfl!=0 ){
drh98add2e2009-07-20 17:11:49 +00003755 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
danielk1977003ba062004-11-04 02:57:33 +00003756 if( rc!=SQLITE_OK ){
3757 return rc;
3758 }
3759 }
3760 }
3761
3762 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3763 ** that it points at iFreePage. Also fix the pointer map entry for
3764 ** iPtrPage.
3765 */
danielk1977a0bf2652004-11-04 14:30:04 +00003766 if( eType!=PTRMAP_ROOTPAGE ){
drhb00fc3b2013-08-21 23:42:32 +00003767 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00003768 if( rc!=SQLITE_OK ){
3769 return rc;
3770 }
danielk19773b8a05f2007-03-19 17:44:26 +00003771 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00003772 if( rc!=SQLITE_OK ){
3773 releasePage(pPtrPage);
3774 return rc;
3775 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00003776 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00003777 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003778 if( rc==SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00003779 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003780 }
danielk1977003ba062004-11-04 02:57:33 +00003781 }
danielk1977003ba062004-11-04 02:57:33 +00003782 return rc;
3783}
3784
danielk1977dddbcdc2007-04-26 14:42:34 +00003785/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00003786static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00003787
3788/*
dan51f0b6d2013-02-22 20:16:34 +00003789** Perform a single step of an incremental-vacuum. If successful, return
3790** SQLITE_OK. If there is no work to do (and therefore no point in
3791** calling this function again), return SQLITE_DONE. Or, if an error
3792** occurs, return some other error code.
danielk1977dddbcdc2007-04-26 14:42:34 +00003793**
peter.d.reid60ec9142014-09-06 16:39:46 +00003794** More specifically, this function attempts to re-organize the database so
dan51f0b6d2013-02-22 20:16:34 +00003795** that the last page of the file currently in use is no longer in use.
danielk1977dddbcdc2007-04-26 14:42:34 +00003796**
dan51f0b6d2013-02-22 20:16:34 +00003797** Parameter nFin is the number of pages that this database would contain
3798** were this function called until it returns SQLITE_DONE.
3799**
3800** If the bCommit parameter is non-zero, this function assumes that the
3801** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
peter.d.reid60ec9142014-09-06 16:39:46 +00003802** or an error. bCommit is passed true for an auto-vacuum-on-commit
dan51f0b6d2013-02-22 20:16:34 +00003803** operation, or false for an incremental vacuum.
danielk1977dddbcdc2007-04-26 14:42:34 +00003804*/
dan51f0b6d2013-02-22 20:16:34 +00003805static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
danielk1977dddbcdc2007-04-26 14:42:34 +00003806 Pgno nFreeList; /* Number of pages still on the free-list */
drhdd3cd972010-03-27 17:12:36 +00003807 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003808
drh1fee73e2007-08-29 04:00:57 +00003809 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977fa542f12009-04-02 18:28:08 +00003810 assert( iLastPg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00003811
3812 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003813 u8 eType;
3814 Pgno iPtrPage;
3815
3816 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977fa542f12009-04-02 18:28:08 +00003817 if( nFreeList==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003818 return SQLITE_DONE;
3819 }
3820
3821 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3822 if( rc!=SQLITE_OK ){
3823 return rc;
3824 }
3825 if( eType==PTRMAP_ROOTPAGE ){
3826 return SQLITE_CORRUPT_BKPT;
3827 }
3828
3829 if( eType==PTRMAP_FREEPAGE ){
dan51f0b6d2013-02-22 20:16:34 +00003830 if( bCommit==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003831 /* Remove the page from the files free-list. This is not required
dan51f0b6d2013-02-22 20:16:34 +00003832 ** if bCommit is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00003833 ** truncated to zero after this function returns, so it doesn't
3834 ** matter if it still contains some garbage entries.
3835 */
3836 Pgno iFreePg;
3837 MemPage *pFreePg;
dan51f0b6d2013-02-22 20:16:34 +00003838 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
danielk1977dddbcdc2007-04-26 14:42:34 +00003839 if( rc!=SQLITE_OK ){
3840 return rc;
3841 }
3842 assert( iFreePg==iLastPg );
3843 releasePage(pFreePg);
3844 }
3845 } else {
3846 Pgno iFreePg; /* Index of free page to move pLastPg to */
3847 MemPage *pLastPg;
dan51f0b6d2013-02-22 20:16:34 +00003848 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
3849 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
danielk1977dddbcdc2007-04-26 14:42:34 +00003850
drhb00fc3b2013-08-21 23:42:32 +00003851 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00003852 if( rc!=SQLITE_OK ){
3853 return rc;
3854 }
3855
dan51f0b6d2013-02-22 20:16:34 +00003856 /* If bCommit is zero, this loop runs exactly once and page pLastPg
danielk1977b4626a32007-04-28 15:47:43 +00003857 ** is swapped with the first free page pulled off the free list.
3858 **
dan51f0b6d2013-02-22 20:16:34 +00003859 ** On the other hand, if bCommit is greater than zero, then keep
danielk1977b4626a32007-04-28 15:47:43 +00003860 ** looping until a free-page located within the first nFin pages
3861 ** of the file is found.
3862 */
dan51f0b6d2013-02-22 20:16:34 +00003863 if( bCommit==0 ){
3864 eMode = BTALLOC_LE;
3865 iNear = nFin;
3866 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003867 do {
3868 MemPage *pFreePg;
dan51f0b6d2013-02-22 20:16:34 +00003869 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
danielk1977dddbcdc2007-04-26 14:42:34 +00003870 if( rc!=SQLITE_OK ){
3871 releasePage(pLastPg);
3872 return rc;
3873 }
3874 releasePage(pFreePg);
dan51f0b6d2013-02-22 20:16:34 +00003875 }while( bCommit && iFreePg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00003876 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00003877
dane1df4e32013-03-05 11:27:04 +00003878 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
danielk1977dddbcdc2007-04-26 14:42:34 +00003879 releasePage(pLastPg);
3880 if( rc!=SQLITE_OK ){
3881 return rc;
danielk1977662278e2007-11-05 15:30:12 +00003882 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003883 }
3884 }
3885
dan51f0b6d2013-02-22 20:16:34 +00003886 if( bCommit==0 ){
danbc1a3c62013-02-23 16:40:46 +00003887 do {
danielk19773460d192008-12-27 15:23:13 +00003888 iLastPg--;
danbc1a3c62013-02-23 16:40:46 +00003889 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
3890 pBt->bDoTruncate = 1;
drhdd3cd972010-03-27 17:12:36 +00003891 pBt->nPage = iLastPg;
danielk1977dddbcdc2007-04-26 14:42:34 +00003892 }
3893 return SQLITE_OK;
3894}
3895
3896/*
dan51f0b6d2013-02-22 20:16:34 +00003897** The database opened by the first argument is an auto-vacuum database
3898** nOrig pages in size containing nFree free pages. Return the expected
3899** size of the database in pages following an auto-vacuum operation.
3900*/
3901static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
3902 int nEntry; /* Number of entries on one ptrmap page */
3903 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
3904 Pgno nFin; /* Return value */
3905
3906 nEntry = pBt->usableSize/5;
3907 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
3908 nFin = nOrig - nFree - nPtrmap;
3909 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
3910 nFin--;
3911 }
3912 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3913 nFin--;
3914 }
dan51f0b6d2013-02-22 20:16:34 +00003915
3916 return nFin;
3917}
3918
3919/*
danielk1977dddbcdc2007-04-26 14:42:34 +00003920** A write-transaction must be opened before calling this function.
3921** It performs a single unit of work towards an incremental vacuum.
3922**
3923** If the incremental vacuum is finished after this function has run,
shanebe217792009-03-05 04:20:31 +00003924** SQLITE_DONE is returned. If it is not finished, but no error occurred,
danielk1977dddbcdc2007-04-26 14:42:34 +00003925** SQLITE_OK is returned. Otherwise an SQLite error code.
3926*/
3927int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00003928 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003929 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003930
3931 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00003932 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
3933 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00003934 rc = SQLITE_DONE;
3935 }else{
dan51f0b6d2013-02-22 20:16:34 +00003936 Pgno nOrig = btreePagecount(pBt);
3937 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
3938 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
3939
dan91384712013-02-24 11:50:43 +00003940 if( nOrig<nFin ){
3941 rc = SQLITE_CORRUPT_BKPT;
3942 }else if( nFree>0 ){
dan11dcd112013-03-15 18:29:18 +00003943 rc = saveAllCursors(pBt, 0, 0);
3944 if( rc==SQLITE_OK ){
3945 invalidateAllOverflowCache(pBt);
3946 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
3947 }
dan51f0b6d2013-02-22 20:16:34 +00003948 if( rc==SQLITE_OK ){
3949 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3950 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
3951 }
3952 }else{
3953 rc = SQLITE_DONE;
drhdd3cd972010-03-27 17:12:36 +00003954 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003955 }
drhd677b3d2007-08-20 22:48:41 +00003956 sqlite3BtreeLeave(p);
3957 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003958}
3959
3960/*
danielk19773b8a05f2007-03-19 17:44:26 +00003961** This routine is called prior to sqlite3PagerCommit when a transaction
drhf7b54962013-05-28 12:11:54 +00003962** is committed for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00003963**
3964** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
3965** the database file should be truncated to during the commit process.
3966** i.e. the database has been reorganized so that only the first *pnTrunc
3967** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00003968*/
danielk19773460d192008-12-27 15:23:13 +00003969static int autoVacuumCommit(BtShared *pBt){
danielk1977dddbcdc2007-04-26 14:42:34 +00003970 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00003971 Pager *pPager = pBt->pPager;
mistachkinc29cbb02015-07-02 16:52:01 +00003972 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
danielk1977687566d2004-11-02 12:56:41 +00003973
drh1fee73e2007-08-29 04:00:57 +00003974 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00003975 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00003976 assert(pBt->autoVacuum);
3977 if( !pBt->incrVacuum ){
drhea8ffdf2009-07-22 00:35:23 +00003978 Pgno nFin; /* Number of pages in database after autovacuuming */
3979 Pgno nFree; /* Number of pages on the freelist initially */
drh41d628c2009-07-11 17:04:08 +00003980 Pgno iFree; /* The next page to be freed */
drh41d628c2009-07-11 17:04:08 +00003981 Pgno nOrig; /* Database size before freeing */
danielk1977687566d2004-11-02 12:56:41 +00003982
drhb1299152010-03-30 22:58:33 +00003983 nOrig = btreePagecount(pBt);
danielk1977ef165ce2009-04-06 17:50:03 +00003984 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
3985 /* It is not possible to create a database for which the final page
3986 ** is either a pointer-map page or the pending-byte page. If one
3987 ** is encountered, this indicates corruption.
3988 */
danielk19773460d192008-12-27 15:23:13 +00003989 return SQLITE_CORRUPT_BKPT;
3990 }
danielk1977ef165ce2009-04-06 17:50:03 +00003991
danielk19773460d192008-12-27 15:23:13 +00003992 nFree = get4byte(&pBt->pPage1->aData[36]);
dan51f0b6d2013-02-22 20:16:34 +00003993 nFin = finalDbSize(pBt, nOrig, nFree);
drhc5e47ac2009-06-04 00:11:56 +00003994 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
dan0aed84d2013-03-26 14:16:20 +00003995 if( nFin<nOrig ){
3996 rc = saveAllCursors(pBt, 0, 0);
3997 }
danielk19773460d192008-12-27 15:23:13 +00003998 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
dan51f0b6d2013-02-22 20:16:34 +00003999 rc = incrVacuumStep(pBt, nFin, iFree, 1);
danielk1977dddbcdc2007-04-26 14:42:34 +00004000 }
danielk19773460d192008-12-27 15:23:13 +00004001 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
danielk19773460d192008-12-27 15:23:13 +00004002 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
4003 put4byte(&pBt->pPage1->aData[32], 0);
4004 put4byte(&pBt->pPage1->aData[36], 0);
drhdd3cd972010-03-27 17:12:36 +00004005 put4byte(&pBt->pPage1->aData[28], nFin);
danbc1a3c62013-02-23 16:40:46 +00004006 pBt->bDoTruncate = 1;
drhdd3cd972010-03-27 17:12:36 +00004007 pBt->nPage = nFin;
danielk1977dddbcdc2007-04-26 14:42:34 +00004008 }
4009 if( rc!=SQLITE_OK ){
4010 sqlite3PagerRollback(pPager);
4011 }
danielk1977687566d2004-11-02 12:56:41 +00004012 }
4013
dan0aed84d2013-03-26 14:16:20 +00004014 assert( nRef>=sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00004015 return rc;
4016}
danielk1977dddbcdc2007-04-26 14:42:34 +00004017
danielk1977a50d9aa2009-06-08 14:49:45 +00004018#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
4019# define setChildPtrmaps(x) SQLITE_OK
4020#endif
danielk1977687566d2004-11-02 12:56:41 +00004021
drh01be4632015-09-03 15:17:12 +00004022#ifndef SQLITE_OMIT_CONCURRENT
danielk1977687566d2004-11-02 12:56:41 +00004023/*
danbf3cf572015-08-24 19:56:04 +00004024** This function is called as part of merging an CONCURRENT transaction with
dan5cf03722015-08-24 10:05:03 +00004025** the snapshot at the head of the wal file. It relocates all pages in the
4026** range iFirst..iLast, inclusive. It is assumed that the BtreePtrmap
4027** structure at BtShared.pMap contains the location of the pointers to each
4028** page in the range.
4029**
4030** If pnCurrent is NULL, then all pages in the range are moved to currently
4031** free locations (i.e. free-list entries) within the database file before page
4032** iFirst.
4033**
4034** Or, if pnCurrent is not NULL, then it points to a value containing the
4035** current size of the database file in pages. In this case, all pages are
4036** relocated to the end of the database file - page iFirst is relocated to
4037** page (*pnCurrent+1), page iFirst+1 to page (*pnCurrent+2), and so on.
4038** Value *pnCurrent is set to the new size of the database before this
4039** function returns.
4040**
4041** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error code.
4042*/
4043static int btreeRelocateRange(
4044 BtShared *pBt, /* B-tree handle */
4045 Pgno iFirst, /* First page to relocate */
4046 Pgno iLast, /* Last page to relocate */
4047 Pgno *pnCurrent /* If not NULL, IN/OUT: Database size */
4048){
4049 int rc = SQLITE_OK;
4050 BtreePtrmap *pMap = pBt->pMap;
4051 Pgno iPg;
4052
4053 for(iPg=iFirst; iPg<=iLast && rc==SQLITE_OK; iPg++){
4054 MemPage *pFree = 0; /* Page allocated from free-list */
4055 MemPage *pPg = 0;
4056 Pgno iNew; /* New page number for pPg */
4057 PtrmapEntry *pEntry; /* Pointer map entry for page iPg */
4058
4059 if( iPg==PENDING_BYTE_PAGE(pBt) ) continue;
4060 pEntry = &pMap->aPtr[iPg - pMap->iFirst];
4061
4062 if( pEntry->eType==PTRMAP_FREEPAGE ){
4063 Pgno dummy;
4064 rc = allocateBtreePage(pBt, &pFree, &dummy, iPg, BTALLOC_EXACT);
4065 releasePage(pFree);
4066 assert( rc!=SQLITE_OK || dummy==iPg );
4067 }else if( pnCurrent ){
4068 btreeGetPage(pBt, iPg, &pPg, 0);
4069 assert( sqlite3PagerIswriteable(pPg->pDbPage) );
4070 assert( sqlite3PagerPageRefcount(pPg->pDbPage)==1 );
4071 iNew = ++(*pnCurrent);
4072 if( iNew==PENDING_BYTE_PAGE(pBt) ) iNew = ++(*pnCurrent);
4073 rc = relocatePage(pBt, pPg, pEntry->eType, pEntry->parent, iNew, 1);
4074 releasePageNotNull(pPg);
4075 }else{
4076 rc = allocateBtreePage(pBt, &pFree, &iNew, iFirst-1, BTALLOC_LE);
4077 assert( rc!=SQLITE_OK || iNew<iFirst );
dan5cf03722015-08-24 10:05:03 +00004078 if( rc==SQLITE_OK ){
4079 MemPage *pPg = 0;
danac0a4222015-08-25 14:37:39 +00004080 releasePage(pFree);
dan5cf03722015-08-24 10:05:03 +00004081 btreeGetPage(pBt, iPg, &pPg, 0);
4082 rc = relocatePage(pBt, pPg, pEntry->eType, pEntry->parent,iNew,1);
4083 releasePage(pPg);
4084 }
4085 }
4086 }
4087 return rc;
4088}
4089
drh01be4632015-09-03 15:17:12 +00004090/* !defined(SQLITE_OMIT_CONCURRENT)
4091**
dan7b3d71e2015-08-19 20:27:05 +00004092** The b-tree handle passed as the only argument is about to commit an
danbf3cf572015-08-24 19:56:04 +00004093** CONCURRENT transaction. At this point it is guaranteed that this is
dan7b3d71e2015-08-19 20:27:05 +00004094** possible - the wal WRITER lock is held and it is known that there are
4095** no conflicts with committed transactions.
4096*/
4097static int btreeFixUnlocked(Btree *p){
4098 BtShared *pBt = p->pBt;
4099 MemPage *pPage1 = pBt->pPage1;
4100 u8 *p1 = pPage1->aData;
4101 Pager *pPager = pBt->pPager;
4102 int rc = SQLITE_OK;
4103
4104 /* If page 1 of the database is not writable, then no pages were allocated
4105 ** or freed by this transaction. In this case no special handling is
4106 ** required. Otherwise, if page 1 is dirty, proceed. */
4107 BtreePtrmap *pMap = pBt->pMap;
4108 Pgno iTrunk = get4byte(&p1[32]);
4109 Pgno nPage = btreePagecount(pBt);
dan7b3d71e2015-08-19 20:27:05 +00004110 u32 nFree = get4byte(&p1[36]);
4111
dan7b3d71e2015-08-19 20:27:05 +00004112 assert( pBt->pMap );
4113 rc = sqlite3PagerUpgradeSnapshot(pPager, pPage1->pDbPage);
4114 assert( p1==pPage1->aData );
4115
4116 if( rc==SQLITE_OK ){
4117 Pgno nHPage = get4byte(&p1[28]);
dan5cf03722015-08-24 10:05:03 +00004118 Pgno nFin = nHPage; /* Size of db after transaction merge */
dan7b3d71e2015-08-19 20:27:05 +00004119
4120 if( sqlite3PagerIswriteable(pPage1->pDbPage) ){
4121 Pgno iHTrunk = get4byte(&p1[32]);
4122 u32 nHFree = get4byte(&p1[36]);
4123
4124 /* Attach the head database free list to the end of the current
4125 ** transactions free-list (if any). */
4126 if( iTrunk!=0 ){
4127 put4byte(&p1[36], nHFree + nFree);
4128 put4byte(&p1[32], iTrunk);
4129 while( iTrunk ){
4130 DbPage *pTrunk = sqlite3PagerLookup(pPager, iTrunk);
4131 iTrunk = get4byte((u8*)pTrunk->pData);
4132 if( iTrunk==0 ){
4133 put4byte((u8*)pTrunk->pData, iHTrunk);
4134 }
4135 sqlite3PagerUnref(pTrunk);
4136 };
4137 }
4138
dan572a21c2015-08-21 18:55:22 +00004139 if( nHPage<(pMap->iFirst-1) ){
4140 /* The database consisted of (pMap->iFirst-1) pages when the current
danbf3cf572015-08-24 19:56:04 +00004141 ** concurrent transaction was opened. And an concurrent transaction may
dan572a21c2015-08-21 18:55:22 +00004142 ** not be executed on an auto-vacuum database - so the db should
4143 ** not have shrunk since the transaction was opened. Therefore nHPage
4144 ** should be set to (pMap->iFirst-1) or greater. */
dan7b3d71e2015-08-19 20:27:05 +00004145 rc = SQLITE_CORRUPT_BKPT;
4146 }else{
4147 /* The current transaction allocated pages pMap->iFirst through
4148 ** nPage (inclusive) at the end of the database file. Meanwhile,
4149 ** other transactions have allocated (iFirst..nHPage). So move
dan5cf03722015-08-24 10:05:03 +00004150 ** pages (iFirst..MIN(nPage,nHPage)) to (MAX(nPage,nHPage)+1). */
dan7b3d71e2015-08-19 20:27:05 +00004151 Pgno iLast = MIN(nPage, nHPage); /* Last page to move */
dan572a21c2015-08-21 18:55:22 +00004152 Pgno nCurrent; /* Current size of db */
dan572a21c2015-08-21 18:55:22 +00004153 nCurrent = MAX(nPage, nHPage);
dan5cf03722015-08-24 10:05:03 +00004154 rc = btreeRelocateRange(pBt, pMap->iFirst, iLast, &nCurrent);
danb87b25f2015-08-21 20:11:23 +00004155
dan5cf03722015-08-24 10:05:03 +00004156 /* There are now no collisions with the snapshot at the head of the
4157 ** database file. So at this point it would be possible to write
4158 ** the transaction out to disk. Before doing so though, attempt to
4159 ** relocate some of the new pages to free locations within the body
4160 ** of the database file (i.e. free-list entries). */
4161 if( rc==SQLITE_OK ){
4162 assert( nCurrent!=PENDING_BYTE_PAGE(pBt) );
4163 sqlite3PagerSetDbsize(pBt->pPager, nCurrent);
4164 nFree = get4byte(&p1[36]);
dane3c3be82017-05-25 21:02:00 +00004165 nFin = nCurrent-nFree;
dan5cf03722015-08-24 10:05:03 +00004166 if( nCurrent>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
4167 nFin--;
dan70af25d2015-08-21 17:57:16 +00004168 }
dane3c3be82017-05-25 21:02:00 +00004169 nFin = MAX(nFin, nHPage);
dan5cf03722015-08-24 10:05:03 +00004170 rc = btreeRelocateRange(pBt, nFin+1, nCurrent, 0);
danf5cebf72015-08-22 17:28:55 +00004171 }
dan572a21c2015-08-21 18:55:22 +00004172
dan5cf03722015-08-24 10:05:03 +00004173 put4byte(&p1[28], nFin);
dan7b3d71e2015-08-19 20:27:05 +00004174 }
4175 }
dan5cf03722015-08-24 10:05:03 +00004176 sqlite3PagerSetDbsize(pPager, nFin);
dan7b3d71e2015-08-19 20:27:05 +00004177 }
4178
4179 return rc;
4180}
drh3f531da2015-09-01 17:48:54 +00004181#else
4182# define btreeFixUnlocked(X) SQLITE_OK
drh01be4632015-09-03 15:17:12 +00004183#endif /* SQLITE_OMIT_CONCURRENT */
dan7b3d71e2015-08-19 20:27:05 +00004184
4185/*
drh80e35f42007-03-30 14:06:34 +00004186** This routine does the first phase of a two-phase commit. This routine
4187** causes a rollback journal to be created (if it does not already exist)
4188** and populated with enough information so that if a power loss occurs
4189** the database can be restored to its original state by playing back
4190** the journal. Then the contents of the journal are flushed out to
4191** the disk. After the journal is safely on oxide, the changes to the
4192** database are written into the database file and flushed to oxide.
4193** At the end of this call, the rollback journal still exists on the
4194** disk and we are still holding all locks, so the transaction has not
drh51898cf2009-04-19 20:51:06 +00004195** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
drh80e35f42007-03-30 14:06:34 +00004196** commit process.
4197**
4198** This call is a no-op if no write-transaction is currently active on pBt.
4199**
4200** Otherwise, sync the database file for the btree pBt. zMaster points to
4201** the name of a master journal file that should be written into the
4202** individual journal file, or is NULL, indicating no master journal file
4203** (single database transaction).
4204**
4205** When this is called, the master journal should already have been
4206** created, populated with this journal pointer and synced to disk.
4207**
4208** Once this is routine has returned, the only thing required to commit
4209** the write-transaction for this database file is to delete the journal.
4210*/
4211int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
4212 int rc = SQLITE_OK;
4213 if( p->inTrans==TRANS_WRITE ){
4214 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00004215 sqlite3BtreeEnter(p);
dan3d394342015-07-27 19:31:45 +00004216
drh80e35f42007-03-30 14:06:34 +00004217#ifndef SQLITE_OMIT_AUTOVACUUM
dan7b3d71e2015-08-19 20:27:05 +00004218 if( pBt->autoVacuum ){
danbf3cf572015-08-24 19:56:04 +00004219 assert( ISCONCURRENT==0 );
danielk19773460d192008-12-27 15:23:13 +00004220 rc = autoVacuumCommit(pBt);
drh80e35f42007-03-30 14:06:34 +00004221 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00004222 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00004223 return rc;
4224 }
4225 }
danbc1a3c62013-02-23 16:40:46 +00004226 if( pBt->bDoTruncate ){
4227 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
4228 }
drh80e35f42007-03-30 14:06:34 +00004229#endif
danbf3cf572015-08-24 19:56:04 +00004230 if( rc==SQLITE_OK && ISCONCURRENT ){
dan7b3d71e2015-08-19 20:27:05 +00004231 rc = btreeFixUnlocked(p);
4232 }
dan3d394342015-07-27 19:31:45 +00004233 if( rc==SQLITE_OK ){
4234 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
4235 }
drhd677b3d2007-08-20 22:48:41 +00004236 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00004237 }
4238 return rc;
4239}
4240
4241/*
danielk197794b30732009-07-02 17:21:57 +00004242** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
4243** at the conclusion of a transaction.
4244*/
4245static void btreeEndTransaction(Btree *p){
4246 BtShared *pBt = p->pBt;
drh1713afb2013-06-28 01:24:57 +00004247 sqlite3 *db = p->db;
danielk197794b30732009-07-02 17:21:57 +00004248 assert( sqlite3BtreeHoldsMutex(p) );
4249
danbc1a3c62013-02-23 16:40:46 +00004250#ifndef SQLITE_OMIT_AUTOVACUUM
4251 pBt->bDoTruncate = 0;
4252#endif
danc0537fe2013-06-28 19:41:43 +00004253 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
danfa401de2009-10-16 14:55:03 +00004254 /* If there are other active statements that belong to this database
4255 ** handle, downgrade to a read-only transaction. The other statements
4256 ** may still be reading from the database. */
danielk197794b30732009-07-02 17:21:57 +00004257 downgradeAllSharedCacheTableLocks(p);
4258 p->inTrans = TRANS_READ;
4259 }else{
4260 /* If the handle had any kind of transaction open, decrement the
4261 ** transaction count of the shared btree. If the transaction count
4262 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
4263 ** call below will unlock the pager. */
4264 if( p->inTrans!=TRANS_NONE ){
4265 clearAllSharedCacheTableLocks(p);
4266 pBt->nTransaction--;
4267 if( 0==pBt->nTransaction ){
4268 pBt->inTransaction = TRANS_NONE;
4269 }
4270 }
4271
4272 /* Set the current transaction state to TRANS_NONE and unlock the
4273 ** pager if this call closed the only read or write transaction. */
4274 p->inTrans = TRANS_NONE;
4275 unlockBtreeIfUnused(pBt);
4276 }
4277
dan987f8212015-08-27 17:42:38 +00004278 /* If this was an CONCURRENT transaction, delete the pBt->pMap object.
4279 ** Also call PagerEndConcurrent() to ensure that the pager has discarded
4280 ** the record of all pages read within the transaction. */
danf5cebf72015-08-22 17:28:55 +00004281 btreePtrmapDelete(pBt);
dan987f8212015-08-27 17:42:38 +00004282 sqlite3PagerEndConcurrent(pBt->pPager);
danielk197794b30732009-07-02 17:21:57 +00004283 btreeIntegrity(p);
4284}
4285
4286/*
drh2aa679f2001-06-25 02:11:07 +00004287** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00004288**
drh6e345992007-03-30 11:12:08 +00004289** This routine implements the second phase of a 2-phase commit. The
drh51898cf2009-04-19 20:51:06 +00004290** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
4291** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
4292** routine did all the work of writing information out to disk and flushing the
drh6e345992007-03-30 11:12:08 +00004293** contents so that they are written onto the disk platter. All this
drh51898cf2009-04-19 20:51:06 +00004294** routine has to do is delete or truncate or zero the header in the
4295** the rollback journal (which causes the transaction to commit) and
4296** drop locks.
drh6e345992007-03-30 11:12:08 +00004297**
dan60939d02011-03-29 15:40:55 +00004298** Normally, if an error occurs while the pager layer is attempting to
4299** finalize the underlying journal file, this function returns an error and
4300** the upper layer will attempt a rollback. However, if the second argument
4301** is non-zero then this b-tree transaction is part of a multi-file
4302** transaction. In this case, the transaction has already been committed
4303** (by deleting a master journal file) and the caller will ignore this
4304** functions return code. So, even if an error occurs in the pager layer,
4305** reset the b-tree objects internal state to indicate that the write
4306** transaction has been closed. This is quite safe, as the pager will have
4307** transitioned to the error state.
4308**
drh5e00f6c2001-09-13 13:46:56 +00004309** This will release the write lock on the database file. If there
4310** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00004311*/
dan60939d02011-03-29 15:40:55 +00004312int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
danielk1977aef0bf62005-12-30 16:28:01 +00004313
drh075ed302010-10-14 01:17:30 +00004314 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00004315 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00004316 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00004317
4318 /* If the handle has a write-transaction open, commit the shared-btrees
4319 ** transaction and set the shared state to TRANS_READ.
4320 */
4321 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00004322 int rc;
drh075ed302010-10-14 01:17:30 +00004323 BtShared *pBt = p->pBt;
danielk1977aef0bf62005-12-30 16:28:01 +00004324 assert( pBt->inTransaction==TRANS_WRITE );
4325 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00004326 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
dan60939d02011-03-29 15:40:55 +00004327 if( rc!=SQLITE_OK && bCleanup==0 ){
drhd677b3d2007-08-20 22:48:41 +00004328 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00004329 return rc;
4330 }
drh3da9c042014-12-22 18:41:21 +00004331 p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
danielk1977aef0bf62005-12-30 16:28:01 +00004332 pBt->inTransaction = TRANS_READ;
danbf0e57a2013-05-14 20:36:31 +00004333 btreeClearHasContent(pBt);
danielk1977ee5741e2004-05-31 10:01:34 +00004334 }
danielk1977aef0bf62005-12-30 16:28:01 +00004335
danielk197794b30732009-07-02 17:21:57 +00004336 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00004337 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00004338 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00004339}
4340
drh80e35f42007-03-30 14:06:34 +00004341/*
4342** Do both phases of a commit.
4343*/
4344int sqlite3BtreeCommit(Btree *p){
4345 int rc;
drhd677b3d2007-08-20 22:48:41 +00004346 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00004347 rc = sqlite3BtreeCommitPhaseOne(p, 0);
4348 if( rc==SQLITE_OK ){
dan60939d02011-03-29 15:40:55 +00004349 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
drh80e35f42007-03-30 14:06:34 +00004350 }
drhd677b3d2007-08-20 22:48:41 +00004351 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00004352 return rc;
4353}
4354
drhc39e0002004-05-07 23:50:57 +00004355/*
drhfb982642007-08-30 01:19:59 +00004356** This routine sets the state to CURSOR_FAULT and the error
drh47b7fc72014-11-11 01:33:57 +00004357** code to errCode for every cursor on any BtShared that pBtree
4358** references. Or if the writeOnly flag is set to 1, then only
4359** trip write cursors and leave read cursors unchanged.
drhfb982642007-08-30 01:19:59 +00004360**
drh47b7fc72014-11-11 01:33:57 +00004361** Every cursor is a candidate to be tripped, including cursors
4362** that belong to other database connections that happen to be
4363** sharing the cache with pBtree.
drhfb982642007-08-30 01:19:59 +00004364**
dan80231042014-11-12 14:56:02 +00004365** This routine gets called when a rollback occurs. If the writeOnly
4366** flag is true, then only write-cursors need be tripped - read-only
4367** cursors save their current positions so that they may continue
4368** following the rollback. Or, if writeOnly is false, all cursors are
4369** tripped. In general, writeOnly is false if the transaction being
4370** rolled back modified the database schema. In this case b-tree root
4371** pages may be moved or deleted from the database altogether, making
4372** it unsafe for read cursors to continue.
4373**
4374** If the writeOnly flag is true and an error is encountered while
4375** saving the current position of a read-only cursor, all cursors,
4376** including all read-cursors are tripped.
4377**
4378** SQLITE_OK is returned if successful, or if an error occurs while
4379** saving a cursor position, an SQLite error code.
drhfb982642007-08-30 01:19:59 +00004380*/
dan80231042014-11-12 14:56:02 +00004381int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
drhfb982642007-08-30 01:19:59 +00004382 BtCursor *p;
dan80231042014-11-12 14:56:02 +00004383 int rc = SQLITE_OK;
4384
drh47b7fc72014-11-11 01:33:57 +00004385 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
dan80231042014-11-12 14:56:02 +00004386 if( pBtree ){
4387 sqlite3BtreeEnter(pBtree);
4388 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
4389 int i;
4390 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
drhd2f83132015-03-25 17:35:01 +00004391 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
drhbea3b972014-11-18 20:22:05 +00004392 rc = saveCursorPosition(p);
dan80231042014-11-12 14:56:02 +00004393 if( rc!=SQLITE_OK ){
4394 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
4395 break;
4396 }
4397 }
4398 }else{
4399 sqlite3BtreeClearCursor(p);
4400 p->eState = CURSOR_FAULT;
4401 p->skipNext = errCode;
4402 }
4403 for(i=0; i<=p->iPage; i++){
4404 releasePage(p->apPage[i]);
4405 p->apPage[i] = 0;
4406 }
danielk1977bc2ca9e2008-11-13 14:28:28 +00004407 }
dan80231042014-11-12 14:56:02 +00004408 sqlite3BtreeLeave(pBtree);
drhfb982642007-08-30 01:19:59 +00004409 }
dan80231042014-11-12 14:56:02 +00004410 return rc;
drhfb982642007-08-30 01:19:59 +00004411}
4412
4413/*
drh47b7fc72014-11-11 01:33:57 +00004414** Rollback the transaction in progress.
4415**
4416** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
4417** Only write cursors are tripped if writeOnly is true but all cursors are
4418** tripped if writeOnly is false. Any attempt to use
4419** a tripped cursor will result in an error.
drh5e00f6c2001-09-13 13:46:56 +00004420**
4421** This will release the write lock on the database file. If there
4422** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00004423*/
drh47b7fc72014-11-11 01:33:57 +00004424int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
danielk19778d34dfd2006-01-24 16:37:57 +00004425 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00004426 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00004427 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00004428
drh47b7fc72014-11-11 01:33:57 +00004429 assert( writeOnly==1 || writeOnly==0 );
4430 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
drhd677b3d2007-08-20 22:48:41 +00004431 sqlite3BtreeEnter(p);
drh0f198a72012-02-13 16:43:16 +00004432 if( tripCode==SQLITE_OK ){
4433 rc = tripCode = saveAllCursors(pBt, 0, 0);
drh47b7fc72014-11-11 01:33:57 +00004434 if( rc ) writeOnly = 0;
drh0f198a72012-02-13 16:43:16 +00004435 }else{
4436 rc = SQLITE_OK;
danielk19772b8c13e2006-01-24 14:21:24 +00004437 }
drh0f198a72012-02-13 16:43:16 +00004438 if( tripCode ){
dan80231042014-11-12 14:56:02 +00004439 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
4440 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4441 if( rc2!=SQLITE_OK ) rc = rc2;
drh0f198a72012-02-13 16:43:16 +00004442 }
danielk1977aef0bf62005-12-30 16:28:01 +00004443 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00004444
4445 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00004446 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00004447
danielk19778d34dfd2006-01-24 16:37:57 +00004448 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00004449 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00004450 if( rc2!=SQLITE_OK ){
4451 rc = rc2;
4452 }
4453
drh24cd67e2004-05-10 16:18:47 +00004454 /* The rollback may have destroyed the pPage1->aData value. So
danielk197730548662009-07-09 05:07:37 +00004455 ** call btreeGetPage() on page 1 again to make
drh16a9b832007-05-05 18:39:25 +00004456 ** sure pPage1->aData is set correctly. */
drhb00fc3b2013-08-21 23:42:32 +00004457 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh1f5b4672010-04-01 02:22:19 +00004458 int nPage = get4byte(28+(u8*)pPage1->aData);
4459 testcase( nPage==0 );
4460 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
4461 testcase( pBt->nPage!=nPage );
4462 pBt->nPage = nPage;
drh24cd67e2004-05-10 16:18:47 +00004463 releasePage(pPage1);
4464 }
drh85ec3b62013-05-14 23:12:06 +00004465 assert( countValidCursors(pBt, 1)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00004466 pBt->inTransaction = TRANS_READ;
danbf0e57a2013-05-14 20:36:31 +00004467 btreeClearHasContent(pBt);
drh24cd67e2004-05-10 16:18:47 +00004468 }
danielk1977aef0bf62005-12-30 16:28:01 +00004469
danielk197794b30732009-07-02 17:21:57 +00004470 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00004471 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00004472 return rc;
4473}
4474
4475/*
peter.d.reid60ec9142014-09-06 16:39:46 +00004476** Start a statement subtransaction. The subtransaction can be rolled
danielk1977bd434552009-03-18 10:33:00 +00004477** back independently of the main transaction. You must start a transaction
4478** before starting a subtransaction. The subtransaction is ended automatically
4479** if the main transaction commits or rolls back.
drhab01f612004-05-22 02:55:23 +00004480**
4481** Statement subtransactions are used around individual SQL statements
4482** that are contained within a BEGIN...COMMIT block. If a constraint
4483** error occurs within the statement, the effect of that one statement
4484** can be rolled back without having to rollback the entire transaction.
danielk1977bd434552009-03-18 10:33:00 +00004485**
4486** A statement sub-transaction is implemented as an anonymous savepoint. The
4487** value passed as the second parameter is the total number of savepoints,
4488** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4489** are no active savepoints and no other statement-transactions open,
4490** iStatement is 1. This anonymous savepoint can be released or rolled back
4491** using the sqlite3BtreeSavepoint() function.
drh663fc632002-02-02 18:49:19 +00004492*/
danielk1977bd434552009-03-18 10:33:00 +00004493int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
drh663fc632002-02-02 18:49:19 +00004494 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00004495 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00004496 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00004497 assert( p->inTrans==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00004498 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk1977bd434552009-03-18 10:33:00 +00004499 assert( iStatement>0 );
4500 assert( iStatement>p->db->nSavepoint );
drh5e0ccc22010-03-29 19:36:52 +00004501 assert( pBt->inTransaction==TRANS_WRITE );
4502 /* At the pager level, a statement transaction is a savepoint with
4503 ** an index greater than all savepoints created explicitly using
4504 ** SQL statements. It is illegal to open, release or rollback any
4505 ** such savepoints while the statement transaction savepoint is active.
4506 */
4507 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
danf5cebf72015-08-22 17:28:55 +00004508 if( rc==SQLITE_OK ){
4509 rc = btreePtrmapBegin(pBt, iStatement);
dan7b3d71e2015-08-19 20:27:05 +00004510 }
drhd677b3d2007-08-20 22:48:41 +00004511 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00004512 return rc;
4513}
4514
4515/*
danielk1977fd7f0452008-12-17 17:30:26 +00004516** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4517** or SAVEPOINT_RELEASE. This function either releases or rolls back the
danielk197712dd5492008-12-18 15:45:07 +00004518** savepoint identified by parameter iSavepoint, depending on the value
4519** of op.
4520**
4521** Normally, iSavepoint is greater than or equal to zero. However, if op is
4522** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4523** contents of the entire transaction are rolled back. This is different
4524** from a normal transaction rollback, as no locks are released and the
4525** transaction remains open.
danielk1977fd7f0452008-12-17 17:30:26 +00004526*/
4527int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4528 int rc = SQLITE_OK;
4529 if( p && p->inTrans==TRANS_WRITE ){
4530 BtShared *pBt = p->pBt;
danielk1977fd7f0452008-12-17 17:30:26 +00004531 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4532 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4533 sqlite3BtreeEnter(p);
danf5cebf72015-08-22 17:28:55 +00004534 btreePtrmapEnd(pBt, op, iSavepoint);
drh2343c7e2017-02-02 00:46:55 +00004535 if( op==SAVEPOINT_ROLLBACK ){
4536 rc = saveAllCursors(pBt, 0, 0);
4537 }
4538 if( rc==SQLITE_OK ){
4539 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4540 }
drh9f0bbf92009-01-02 21:08:09 +00004541 if( rc==SQLITE_OK ){
drhc9166342012-01-05 23:32:06 +00004542 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4543 pBt->nPage = 0;
4544 }
drh9f0bbf92009-01-02 21:08:09 +00004545 rc = newDatabase(pBt);
drhdd3cd972010-03-27 17:12:36 +00004546 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
drhb9b49bf2010-08-05 03:21:39 +00004547
4548 /* The database size was written into the offset 28 of the header
4549 ** when the transaction started, so we know that the value at offset
4550 ** 28 is nonzero. */
4551 assert( pBt->nPage>0 );
drh9f0bbf92009-01-02 21:08:09 +00004552 }
danielk1977fd7f0452008-12-17 17:30:26 +00004553 sqlite3BtreeLeave(p);
4554 }
4555 return rc;
4556}
4557
4558/*
drh8b2f49b2001-06-08 00:21:52 +00004559** Create a new cursor for the BTree whose root is on the page
danielk19773e8add92009-07-04 17:16:00 +00004560** iTable. If a read-only cursor is requested, it is assumed that
4561** the caller already has at least a read-only transaction open
4562** on the database already. If a write-cursor is requested, then
4563** the caller is assumed to have an open write transaction.
drh1bee3d72001-10-15 00:44:35 +00004564**
drhe807bdb2016-01-21 17:06:33 +00004565** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4566** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
4567** can be used for reading or for writing if other conditions for writing
4568** are also met. These are the conditions that must be met in order
4569** for writing to be allowed:
drh6446c4d2001-12-15 14:22:18 +00004570**
drhe807bdb2016-01-21 17:06:33 +00004571** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
drhf74b8d92002-09-01 23:20:45 +00004572**
drhfe5d71d2007-03-19 11:54:10 +00004573** 2: Other database connections that share the same pager cache
4574** but which are not in the READ_UNCOMMITTED state may not have
4575** cursors open with wrFlag==0 on the same table. Otherwise
4576** the changes made by this write cursor would be visible to
4577** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00004578**
4579** 3: The database must be writable (not on read-only media)
4580**
4581** 4: There must be an active transaction.
4582**
drhe807bdb2016-01-21 17:06:33 +00004583** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4584** is set. If FORDELETE is set, that is a hint to the implementation that
4585** this cursor will only be used to seek to and delete entries of an index
4586** as part of a larger DELETE statement. The FORDELETE hint is not used by
4587** this implementation. But in a hypothetical alternative storage engine
4588** in which index entries are automatically deleted when corresponding table
4589** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4590** operations on this cursor can be no-ops and all READ operations can
4591** return a null row (2-bytes: 0x01 0x00).
4592**
drh6446c4d2001-12-15 14:22:18 +00004593** No checking is done to make sure that page iTable really is the
4594** root page of a b-tree. If it is not, then the cursor acquired
4595** will not work correctly.
danielk197771d5d2c2008-09-29 11:49:47 +00004596**
drhf25a5072009-11-18 23:01:25 +00004597** It is assumed that the sqlite3BtreeCursorZero() has been called
4598** on pCur to initialize the memory space prior to invoking this routine.
drha059ad02001-04-17 20:09:11 +00004599*/
drhd677b3d2007-08-20 22:48:41 +00004600static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00004601 Btree *p, /* The btree */
4602 int iTable, /* Root page of table to open */
4603 int wrFlag, /* 1 to write. 0 read-only */
4604 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4605 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00004606){
danielk19773e8add92009-07-04 17:16:00 +00004607 BtShared *pBt = p->pBt; /* Shared b-tree handle */
drh27fb7462015-06-30 02:47:36 +00004608 BtCursor *pX; /* Looping over other all cursors */
drhecdc7532001-09-23 02:35:53 +00004609
drh1fee73e2007-08-29 04:00:57 +00004610 assert( sqlite3BtreeHoldsMutex(p) );
danfd261ec2015-10-22 20:54:33 +00004611 assert( wrFlag==0
4612 || wrFlag==BTREE_WRCSR
4613 || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4614 );
danielk197796d48e92009-06-29 06:00:37 +00004615
danielk1977602b4662009-07-02 07:47:33 +00004616 /* The following assert statements verify that if this is a sharable
4617 ** b-tree database, the connection is holding the required table locks,
4618 ** and that no other connection has any open cursor that conflicts with
4619 ** this lock. */
danfd261ec2015-10-22 20:54:33 +00004620 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
danielk197796d48e92009-06-29 06:00:37 +00004621 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
4622
danielk19773e8add92009-07-04 17:16:00 +00004623 /* Assert that the caller has opened the required transaction. */
4624 assert( p->inTrans>TRANS_NONE );
4625 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
4626 assert( pBt->pPage1 && pBt->pPage1->aData );
drh98ef0f62015-06-30 01:25:52 +00004627 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk19773e8add92009-07-04 17:16:00 +00004628
drh3fbb0222014-09-24 19:47:27 +00004629 if( wrFlag ){
4630 allocateTempSpace(pBt);
mistachkinfad30392016-02-13 23:43:46 +00004631 if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
drh3fbb0222014-09-24 19:47:27 +00004632 }
drhb1299152010-03-30 22:58:33 +00004633 if( iTable==1 && btreePagecount(pBt)==0 ){
dana205a482011-08-27 18:48:57 +00004634 assert( wrFlag==0 );
4635 iTable = 0;
danielk19773e8add92009-07-04 17:16:00 +00004636 }
danielk1977aef0bf62005-12-30 16:28:01 +00004637
danielk1977aef0bf62005-12-30 16:28:01 +00004638 /* Now that no other errors can occur, finish filling in the BtCursor
danielk19773e8add92009-07-04 17:16:00 +00004639 ** variables and link the cursor into the BtShared list. */
danielk1977172114a2009-07-07 15:47:12 +00004640 pCur->pgnoRoot = (Pgno)iTable;
4641 pCur->iPage = -1;
drh1e968a02008-03-25 00:22:21 +00004642 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00004643 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00004644 pCur->pBt = pBt;
danfd261ec2015-10-22 20:54:33 +00004645 pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
drh28f58dd2015-06-27 19:45:03 +00004646 pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
drh27fb7462015-06-30 02:47:36 +00004647 /* If there are two or more cursors on the same btree, then all such
4648 ** cursors *must* have the BTCF_Multiple flag set. */
4649 for(pX=pBt->pCursor; pX; pX=pX->pNext){
4650 if( pX->pgnoRoot==(Pgno)iTable ){
4651 pX->curFlags |= BTCF_Multiple;
4652 pCur->curFlags |= BTCF_Multiple;
4653 }
drha059ad02001-04-17 20:09:11 +00004654 }
drh27fb7462015-06-30 02:47:36 +00004655 pCur->pNext = pBt->pCursor;
drha059ad02001-04-17 20:09:11 +00004656 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00004657 pCur->eState = CURSOR_INVALID;
danielk1977aef0bf62005-12-30 16:28:01 +00004658 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00004659}
drhd677b3d2007-08-20 22:48:41 +00004660int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00004661 Btree *p, /* The btree */
4662 int iTable, /* Root page of table to open */
4663 int wrFlag, /* 1 to write. 0 read-only */
4664 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
4665 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00004666){
4667 int rc;
dan08f901b2015-05-25 19:24:36 +00004668 if( iTable<1 ){
4669 rc = SQLITE_CORRUPT_BKPT;
4670 }else{
4671 sqlite3BtreeEnter(p);
4672 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4673 sqlite3BtreeLeave(p);
4674 }
drhd677b3d2007-08-20 22:48:41 +00004675 return rc;
4676}
drh7f751222009-03-17 22:33:00 +00004677
4678/*
4679** Return the size of a BtCursor object in bytes.
4680**
4681** This interfaces is needed so that users of cursors can preallocate
4682** sufficient storage to hold a cursor. The BtCursor object is opaque
4683** to users so they cannot do the sizeof() themselves - they must call
4684** this routine.
4685*/
4686int sqlite3BtreeCursorSize(void){
drhc54055b2009-11-13 17:05:53 +00004687 return ROUND8(sizeof(BtCursor));
danielk1977cd3e8f72008-03-25 09:47:35 +00004688}
4689
drh7f751222009-03-17 22:33:00 +00004690/*
drhf25a5072009-11-18 23:01:25 +00004691** Initialize memory that will be converted into a BtCursor object.
4692**
4693** The simple approach here would be to memset() the entire object
4694** to zero. But it turns out that the apPage[] and aiIdx[] arrays
4695** do not need to be zeroed and they are large, so we can save a lot
4696** of run-time by skipping the initialization of those elements.
4697*/
4698void sqlite3BtreeCursorZero(BtCursor *p){
4699 memset(p, 0, offsetof(BtCursor, iPage));
4700}
4701
4702/*
drh5e00f6c2001-09-13 13:46:56 +00004703** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00004704** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00004705*/
drh3aac2dd2004-04-26 14:10:20 +00004706int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00004707 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00004708 if( pBtree ){
danielk197771d5d2c2008-09-29 11:49:47 +00004709 int i;
danielk1977cd3e8f72008-03-25 09:47:35 +00004710 BtShared *pBt = pCur->pBt;
4711 sqlite3BtreeEnter(pBtree);
danielk1977be51a652008-10-08 17:58:48 +00004712 sqlite3BtreeClearCursor(pCur);
drh27fb7462015-06-30 02:47:36 +00004713 assert( pBt->pCursor!=0 );
4714 if( pBt->pCursor==pCur ){
danielk1977cd3e8f72008-03-25 09:47:35 +00004715 pBt->pCursor = pCur->pNext;
drh27fb7462015-06-30 02:47:36 +00004716 }else{
4717 BtCursor *pPrev = pBt->pCursor;
4718 do{
4719 if( pPrev->pNext==pCur ){
4720 pPrev->pNext = pCur->pNext;
4721 break;
4722 }
4723 pPrev = pPrev->pNext;
4724 }while( ALWAYS(pPrev) );
danielk1977cd3e8f72008-03-25 09:47:35 +00004725 }
danielk197771d5d2c2008-09-29 11:49:47 +00004726 for(i=0; i<=pCur->iPage; i++){
4727 releasePage(pCur->apPage[i]);
4728 }
danielk1977cd3e8f72008-03-25 09:47:35 +00004729 unlockBtreeIfUnused(pBt);
dan85753662014-12-11 16:38:18 +00004730 sqlite3_free(pCur->aOverflow);
danielk1977cd3e8f72008-03-25 09:47:35 +00004731 /* sqlite3_free(pCur); */
4732 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00004733 }
drh8c42ca92001-06-22 19:15:00 +00004734 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00004735}
4736
drh5e2f8b92001-05-28 00:41:15 +00004737/*
drh86057612007-06-26 01:04:48 +00004738** Make sure the BtCursor* given in the argument has a valid
4739** BtCursor.info structure. If it is not already valid, call
danielk197730548662009-07-09 05:07:37 +00004740** btreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00004741**
4742** BtCursor.info is a cache of the information in the current cell.
danielk197730548662009-07-09 05:07:37 +00004743** Using this cache reduces the number of calls to btreeParseCell().
drh9188b382004-05-14 21:12:22 +00004744*/
drh9188b382004-05-14 21:12:22 +00004745#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00004746 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00004747 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00004748 int iPage = pCur->iPage;
drh51c6d962004-06-06 00:42:25 +00004749 memset(&info, 0, sizeof(info));
drh75e96b32017-04-01 00:20:06 +00004750 btreeParseCell(pCur->apPage[iPage], pCur->ix, &info);
dan7df42ab2014-01-20 18:25:44 +00004751 assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00004752 }
danielk19771cc5ed82007-05-16 17:28:43 +00004753#else
4754 #define assertCellInfo(x)
4755#endif
drhc5b41ac2015-06-17 02:11:46 +00004756static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
4757 if( pCur->info.nSize==0 ){
4758 int iPage = pCur->iPage;
4759 pCur->curFlags |= BTCF_ValidNKey;
drh75e96b32017-04-01 00:20:06 +00004760 btreeParseCell(pCur->apPage[iPage],pCur->ix,&pCur->info);
drhc5b41ac2015-06-17 02:11:46 +00004761 }else{
4762 assertCellInfo(pCur);
drh86057612007-06-26 01:04:48 +00004763 }
drhc5b41ac2015-06-17 02:11:46 +00004764}
drh9188b382004-05-14 21:12:22 +00004765
drhea8ffdf2009-07-22 00:35:23 +00004766#ifndef NDEBUG /* The next routine used only within assert() statements */
4767/*
4768** Return true if the given BtCursor is valid. A valid cursor is one
4769** that is currently pointing to a row in a (non-empty) table.
4770** This is a verification routine is used only within assert() statements.
4771*/
4772int sqlite3BtreeCursorIsValid(BtCursor *pCur){
4773 return pCur && pCur->eState==CURSOR_VALID;
4774}
4775#endif /* NDEBUG */
drhd6ef5af2016-11-15 04:00:24 +00004776int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
4777 assert( pCur!=0 );
4778 return pCur->eState==CURSOR_VALID;
4779}
drhea8ffdf2009-07-22 00:35:23 +00004780
drh9188b382004-05-14 21:12:22 +00004781/*
drha7c90c42016-06-04 20:37:10 +00004782** Return the value of the integer key or "rowid" for a table btree.
4783** This routine is only valid for a cursor that is pointing into a
4784** ordinary table btree. If the cursor points to an index btree or
4785** is invalid, the result of this routine is undefined.
drh7e3b0a02001-04-28 16:52:40 +00004786*/
drha7c90c42016-06-04 20:37:10 +00004787i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00004788 assert( cursorHoldsMutex(pCur) );
drhc5352b92014-11-17 20:33:07 +00004789 assert( pCur->eState==CURSOR_VALID );
drha7c90c42016-06-04 20:37:10 +00004790 assert( pCur->curIntKey );
drhc5352b92014-11-17 20:33:07 +00004791 getCellInfo(pCur);
drha7c90c42016-06-04 20:37:10 +00004792 return pCur->info.nKey;
drha059ad02001-04-17 20:09:11 +00004793}
drh2af926b2001-05-15 00:39:25 +00004794
drh72f82862001-05-24 21:06:34 +00004795/*
drha7c90c42016-06-04 20:37:10 +00004796** Return the number of bytes of payload for the entry that pCur is
4797** currently pointing to. For table btrees, this will be the amount
4798** of data. For index btrees, this will be the size of the key.
drhea8ffdf2009-07-22 00:35:23 +00004799**
4800** The caller must guarantee that the cursor is pointing to a non-NULL
4801** valid entry. In other words, the calling procedure must guarantee
4802** that the cursor has Cursor.eState==CURSOR_VALID.
drh0e1c19e2004-05-11 00:58:56 +00004803*/
drha7c90c42016-06-04 20:37:10 +00004804u32 sqlite3BtreePayloadSize(BtCursor *pCur){
4805 assert( cursorHoldsMutex(pCur) );
drhea8ffdf2009-07-22 00:35:23 +00004806 assert( pCur->eState==CURSOR_VALID );
4807 getCellInfo(pCur);
drha7c90c42016-06-04 20:37:10 +00004808 return pCur->info.nPayload;
drh0e1c19e2004-05-11 00:58:56 +00004809}
4810
4811/*
danielk1977d04417962007-05-02 13:16:30 +00004812** Given the page number of an overflow page in the database (parameter
4813** ovfl), this function finds the page number of the next page in the
4814** linked list of overflow pages. If possible, it uses the auto-vacuum
4815** pointer-map data instead of reading the content of page ovfl to do so.
4816**
4817** If an error occurs an SQLite error code is returned. Otherwise:
4818**
danielk1977bea2a942009-01-20 17:06:27 +00004819** The page number of the next overflow page in the linked list is
4820** written to *pPgnoNext. If page ovfl is the last page in its linked
4821** list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00004822**
danielk1977bea2a942009-01-20 17:06:27 +00004823** If ppPage is not NULL, and a reference to the MemPage object corresponding
4824** to page number pOvfl was obtained, then *ppPage is set to point to that
4825** reference. It is the responsibility of the caller to call releasePage()
4826** on *ppPage to free the reference. In no reference was obtained (because
4827** the pointer-map was used to obtain the value for *pPgnoNext), then
4828** *ppPage is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00004829*/
4830static int getOverflowPage(
drhfa3be902009-07-07 02:44:07 +00004831 BtShared *pBt, /* The database file */
4832 Pgno ovfl, /* Current overflow page number */
danielk1977bea2a942009-01-20 17:06:27 +00004833 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
danielk1977d04417962007-05-02 13:16:30 +00004834 Pgno *pPgnoNext /* OUT: Next overflow page number */
4835){
4836 Pgno next = 0;
danielk1977bea2a942009-01-20 17:06:27 +00004837 MemPage *pPage = 0;
drh1bd10f82008-12-10 21:19:56 +00004838 int rc = SQLITE_OK;
danielk1977d04417962007-05-02 13:16:30 +00004839
drh1fee73e2007-08-29 04:00:57 +00004840 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bea2a942009-01-20 17:06:27 +00004841 assert(pPgnoNext);
danielk1977d04417962007-05-02 13:16:30 +00004842
4843#ifndef SQLITE_OMIT_AUTOVACUUM
4844 /* Try to find the next page in the overflow list using the
4845 ** autovacuum pointer-map pages. Guess that the next page in
4846 ** the overflow list is page number (ovfl+1). If that guess turns
4847 ** out to be wrong, fall back to loading the data of page
4848 ** number ovfl to determine the next page number.
4849 */
4850 if( pBt->autoVacuum ){
4851 Pgno pgno;
4852 Pgno iGuess = ovfl+1;
4853 u8 eType;
4854
4855 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4856 iGuess++;
4857 }
4858
drhb1299152010-03-30 22:58:33 +00004859 if( iGuess<=btreePagecount(pBt) ){
danielk1977d04417962007-05-02 13:16:30 +00004860 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
danielk1977bea2a942009-01-20 17:06:27 +00004861 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
danielk1977d04417962007-05-02 13:16:30 +00004862 next = iGuess;
danielk1977bea2a942009-01-20 17:06:27 +00004863 rc = SQLITE_DONE;
danielk1977d04417962007-05-02 13:16:30 +00004864 }
4865 }
4866 }
4867#endif
4868
danielk1977d8a3f3d2009-07-11 11:45:23 +00004869 assert( next==0 || rc==SQLITE_DONE );
danielk1977bea2a942009-01-20 17:06:27 +00004870 if( rc==SQLITE_OK ){
drhb00fc3b2013-08-21 23:42:32 +00004871 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
danielk1977d8a3f3d2009-07-11 11:45:23 +00004872 assert( rc==SQLITE_OK || pPage==0 );
4873 if( rc==SQLITE_OK ){
danielk1977d04417962007-05-02 13:16:30 +00004874 next = get4byte(pPage->aData);
4875 }
danielk1977443c0592009-01-16 15:21:05 +00004876 }
danielk197745d68822009-01-16 16:23:38 +00004877
danielk1977bea2a942009-01-20 17:06:27 +00004878 *pPgnoNext = next;
4879 if( ppPage ){
4880 *ppPage = pPage;
4881 }else{
4882 releasePage(pPage);
4883 }
4884 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
danielk1977d04417962007-05-02 13:16:30 +00004885}
4886
danielk1977da107192007-05-04 08:32:13 +00004887/*
4888** Copy data from a buffer to a page, or from a page to a buffer.
4889**
4890** pPayload is a pointer to data stored on database page pDbPage.
4891** If argument eOp is false, then nByte bytes of data are copied
4892** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4893** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4894** of data are copied from the buffer pBuf to pPayload.
4895**
4896** SQLITE_OK is returned on success, otherwise an error code.
4897*/
4898static int copyPayload(
4899 void *pPayload, /* Pointer to page data */
4900 void *pBuf, /* Pointer to buffer */
4901 int nByte, /* Number of bytes to copy */
4902 int eOp, /* 0 -> copy from page, 1 -> copy to page */
4903 DbPage *pDbPage /* Page containing pPayload */
4904){
4905 if( eOp ){
4906 /* Copy data from buffer to page (a write operation) */
4907 int rc = sqlite3PagerWrite(pDbPage);
4908 if( rc!=SQLITE_OK ){
4909 return rc;
4910 }
4911 memcpy(pPayload, pBuf, nByte);
4912 }else{
4913 /* Copy data from page to buffer (a read operation) */
4914 memcpy(pBuf, pPayload, nByte);
4915 }
4916 return SQLITE_OK;
4917}
danielk1977d04417962007-05-02 13:16:30 +00004918
4919/*
danielk19779f8d6402007-05-02 17:48:45 +00004920** This function is used to read or overwrite payload information
dan5a500af2014-03-11 20:33:04 +00004921** for the entry that the pCur cursor is pointing to. The eOp
4922** argument is interpreted as follows:
4923**
4924** 0: The operation is a read. Populate the overflow cache.
4925** 1: The operation is a write. Populate the overflow cache.
danielk19779f8d6402007-05-02 17:48:45 +00004926**
4927** A total of "amt" bytes are read or written beginning at "offset".
4928** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00004929**
drh3bcdfd22009-07-12 02:32:21 +00004930** The content being read or written might appear on the main page
4931** or be scattered out on multiple overflow pages.
danielk1977da107192007-05-04 08:32:13 +00004932**
drh42e28f12017-01-27 00:31:59 +00004933** If the current cursor entry uses one or more overflow pages
4934** this function may allocate space for and lazily populate
4935** the overflow page-list cache array (BtCursor.aOverflow).
dan5a500af2014-03-11 20:33:04 +00004936** Subsequent calls use this cache to make seeking to the supplied offset
4937** more efficient.
danielk1977da107192007-05-04 08:32:13 +00004938**
drh42e28f12017-01-27 00:31:59 +00004939** Once an overflow page-list cache has been allocated, it must be
danielk1977da107192007-05-04 08:32:13 +00004940** invalidated if some other cursor writes to the same table, or if
4941** the cursor is moved to a different row. Additionally, in auto-vacuum
4942** mode, the following events may invalidate an overflow page-list cache.
4943**
4944** * An incremental vacuum,
4945** * A commit in auto_vacuum="full" mode,
4946** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00004947*/
danielk19779f8d6402007-05-02 17:48:45 +00004948static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00004949 BtCursor *pCur, /* Cursor pointing to entry to read from */
danielk197789d40042008-11-17 14:20:56 +00004950 u32 offset, /* Begin reading this far into payload */
4951 u32 amt, /* Read this many bytes */
drh3aac2dd2004-04-26 14:10:20 +00004952 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00004953 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00004954){
4955 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00004956 int rc = SQLITE_OK;
danielk19772dec9702007-05-02 16:48:37 +00004957 int iIdx = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004958 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
danielk19770d065412008-11-12 18:21:36 +00004959 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh4c417182014-03-31 23:57:41 +00004960#ifdef SQLITE_DIRECT_OVERFLOW_READ
drh8bb9fd32017-01-26 16:27:32 +00004961 unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
drh4c417182014-03-31 23:57:41 +00004962#endif
drh3aac2dd2004-04-26 14:10:20 +00004963
danielk1977da107192007-05-04 08:32:13 +00004964 assert( pPage );
drh42e28f12017-01-27 00:31:59 +00004965 assert( eOp==0 || eOp==1 );
danielk1977da184232006-01-05 11:34:32 +00004966 assert( pCur->eState==CURSOR_VALID );
drh75e96b32017-04-01 00:20:06 +00004967 assert( pCur->ix<pPage->nCell );
drh1fee73e2007-08-29 04:00:57 +00004968 assert( cursorHoldsMutex(pCur) );
danielk1977da107192007-05-04 08:32:13 +00004969
drh86057612007-06-26 01:04:48 +00004970 getCellInfo(pCur);
drhab1cc582014-09-23 21:25:19 +00004971 aPayload = pCur->info.pPayload;
drhab1cc582014-09-23 21:25:19 +00004972 assert( offset+amt <= pCur->info.nPayload );
danielk1977da107192007-05-04 08:32:13 +00004973
drh0b982072016-03-22 14:10:45 +00004974 assert( aPayload > pPage->aData );
drhc5e7f942016-03-22 15:25:16 +00004975 if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
drh0b982072016-03-22 14:10:45 +00004976 /* Trying to read or write past the end of the data is an error. The
4977 ** conditional above is really:
4978 ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
4979 ** but is recast into its current form to avoid integer overflow problems
4980 */
drhcc97ca42017-06-07 22:32:59 +00004981 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh3aac2dd2004-04-26 14:10:20 +00004982 }
danielk1977da107192007-05-04 08:32:13 +00004983
4984 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00004985 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00004986 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00004987 if( a+offset>pCur->info.nLocal ){
4988 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00004989 }
drh42e28f12017-01-27 00:31:59 +00004990 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00004991 offset = 0;
drha34b6762004-05-07 13:30:42 +00004992 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00004993 amt -= a;
drhdd793422001-06-28 01:54:48 +00004994 }else{
drhfa1a98a2004-05-14 19:08:17 +00004995 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00004996 }
danielk1977da107192007-05-04 08:32:13 +00004997
dan85753662014-12-11 16:38:18 +00004998
danielk1977da107192007-05-04 08:32:13 +00004999 if( rc==SQLITE_OK && amt>0 ){
danielk197789d40042008-11-17 14:20:56 +00005000 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
danielk1977da107192007-05-04 08:32:13 +00005001 Pgno nextPage;
5002
drhfa1a98a2004-05-14 19:08:17 +00005003 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00005004
drha38c9512014-04-01 01:24:34 +00005005 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
drha38c9512014-04-01 01:24:34 +00005006 **
5007 ** The aOverflow[] array is sized at one entry for each overflow page
5008 ** in the overflow chain. The page number of the first overflow page is
5009 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
5010 ** means "not yet known" (the cache is lazily populated).
danielk1977da107192007-05-04 08:32:13 +00005011 */
drh42e28f12017-01-27 00:31:59 +00005012 if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
danielk19772dec9702007-05-02 16:48:37 +00005013 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
dan5a500af2014-03-11 20:33:04 +00005014 if( nOvfl>pCur->nOvflAlloc ){
dan85753662014-12-11 16:38:18 +00005015 Pgno *aNew = (Pgno*)sqlite3Realloc(
5016 pCur->aOverflow, nOvfl*2*sizeof(Pgno)
dan5a500af2014-03-11 20:33:04 +00005017 );
5018 if( aNew==0 ){
drhcd645532017-01-20 20:43:14 +00005019 return SQLITE_NOMEM_BKPT;
dan5a500af2014-03-11 20:33:04 +00005020 }else{
5021 pCur->nOvflAlloc = nOvfl*2;
5022 pCur->aOverflow = aNew;
5023 }
5024 }
drhcd645532017-01-20 20:43:14 +00005025 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
5026 pCur->curFlags |= BTCF_ValidOvfl;
drhcdf360a2017-01-27 01:13:49 +00005027 }else{
5028 /* If the overflow page-list cache has been allocated and the
5029 ** entry for the first required overflow page is valid, skip
5030 ** directly to it.
5031 */
5032 if( pCur->aOverflow[offset/ovflSize] ){
5033 iIdx = (offset/ovflSize);
5034 nextPage = pCur->aOverflow[iIdx];
5035 offset = (offset%ovflSize);
danielk19772dec9702007-05-02 16:48:37 +00005036 }
5037 }
danielk1977da107192007-05-04 08:32:13 +00005038
drhcd645532017-01-20 20:43:14 +00005039 assert( rc==SQLITE_OK && amt>0 );
5040 while( nextPage ){
danielk1977da107192007-05-04 08:32:13 +00005041 /* If required, populate the overflow page-list cache. */
drh42e28f12017-01-27 00:31:59 +00005042 assert( pCur->aOverflow[iIdx]==0
5043 || pCur->aOverflow[iIdx]==nextPage
5044 || CORRUPT_DB );
5045 pCur->aOverflow[iIdx] = nextPage;
danielk1977da107192007-05-04 08:32:13 +00005046
danielk1977d04417962007-05-02 13:16:30 +00005047 if( offset>=ovflSize ){
5048 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00005049 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00005050 ** data is not required. So first try to lookup the overflow
5051 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00005052 ** function.
danielk1977d04417962007-05-02 13:16:30 +00005053 */
drha38c9512014-04-01 01:24:34 +00005054 assert( pCur->curFlags & BTCF_ValidOvfl );
dan85753662014-12-11 16:38:18 +00005055 assert( pCur->pBtree->db==pBt->db );
drha38c9512014-04-01 01:24:34 +00005056 if( pCur->aOverflow[iIdx+1] ){
danielk1977da107192007-05-04 08:32:13 +00005057 nextPage = pCur->aOverflow[iIdx+1];
drha38c9512014-04-01 01:24:34 +00005058 }else{
danielk1977da107192007-05-04 08:32:13 +00005059 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
drha38c9512014-04-01 01:24:34 +00005060 }
danielk1977da107192007-05-04 08:32:13 +00005061 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00005062 }else{
danielk19779f8d6402007-05-02 17:48:45 +00005063 /* Need to read this page properly. It contains some of the
5064 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00005065 */
danf4ba1092011-10-08 14:57:07 +00005066#ifdef SQLITE_DIRECT_OVERFLOW_READ
drh8bb9fd32017-01-26 16:27:32 +00005067 sqlite3_file *fd; /* File from which to do direct overflow read */
danf4ba1092011-10-08 14:57:07 +00005068#endif
danielk1977cfe9a692004-06-16 12:00:29 +00005069 int a = amt;
danf4ba1092011-10-08 14:57:07 +00005070 if( a + offset > ovflSize ){
5071 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00005072 }
danf4ba1092011-10-08 14:57:07 +00005073
5074#ifdef SQLITE_DIRECT_OVERFLOW_READ
5075 /* If all the following are true:
5076 **
5077 ** 1) this is a read operation, and
5078 ** 2) data is required from the start of this overflow page, and
drh8bb9fd32017-01-26 16:27:32 +00005079 ** 3) there is no open write-transaction, and
5080 ** 4) the database is file-backed, and
drhd930b5c2017-01-26 02:26:02 +00005081 ** 5) the page is not in the WAL file
drh8bb9fd32017-01-26 16:27:32 +00005082 ** 6) at least 4 bytes have already been read into the output buffer
danf4ba1092011-10-08 14:57:07 +00005083 **
5084 ** then data can be read directly from the database file into the
5085 ** output buffer, bypassing the page-cache altogether. This speeds
5086 ** up loading large records that span many overflow pages.
5087 */
drh42e28f12017-01-27 00:31:59 +00005088 if( eOp==0 /* (1) */
danf4ba1092011-10-08 14:57:07 +00005089 && offset==0 /* (2) */
drh8bb9fd32017-01-26 16:27:32 +00005090 && pBt->inTransaction==TRANS_READ /* (3) */
5091 && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (4) */
drhd930b5c2017-01-26 02:26:02 +00005092 && 0==sqlite3PagerUseWal(pBt->pPager, nextPage) /* (5) */
drh8bb9fd32017-01-26 16:27:32 +00005093 && &pBuf[-4]>=pBufStart /* (6) */
danf4ba1092011-10-08 14:57:07 +00005094 ){
5095 u8 aSave[4];
5096 u8 *aWrite = &pBuf[-4];
drh8bb9fd32017-01-26 16:27:32 +00005097 assert( aWrite>=pBufStart ); /* due to (6) */
danf4ba1092011-10-08 14:57:07 +00005098 memcpy(aSave, aWrite, 4);
dan27d47fb2011-12-21 17:00:16 +00005099 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
danf4ba1092011-10-08 14:57:07 +00005100 nextPage = get4byte(aWrite);
5101 memcpy(aWrite, aSave, 4);
5102 }else
5103#endif
5104
5105 {
5106 DbPage *pDbPage;
drh9584f582015-11-04 20:22:37 +00005107 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
drh42e28f12017-01-27 00:31:59 +00005108 (eOp==0 ? PAGER_GET_READONLY : 0)
dan11dcd112013-03-15 18:29:18 +00005109 );
danf4ba1092011-10-08 14:57:07 +00005110 if( rc==SQLITE_OK ){
5111 aPayload = sqlite3PagerGetData(pDbPage);
5112 nextPage = get4byte(aPayload);
drh42e28f12017-01-27 00:31:59 +00005113 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
danf4ba1092011-10-08 14:57:07 +00005114 sqlite3PagerUnref(pDbPage);
5115 offset = 0;
5116 }
5117 }
5118 amt -= a;
drh6ee610b2017-01-27 01:25:00 +00005119 if( amt==0 ) return rc;
danf4ba1092011-10-08 14:57:07 +00005120 pBuf += a;
danielk1977cfe9a692004-06-16 12:00:29 +00005121 }
drhcd645532017-01-20 20:43:14 +00005122 if( rc ) break;
5123 iIdx++;
drh2af926b2001-05-15 00:39:25 +00005124 }
drh2af926b2001-05-15 00:39:25 +00005125 }
danielk1977cfe9a692004-06-16 12:00:29 +00005126
danielk1977da107192007-05-04 08:32:13 +00005127 if( rc==SQLITE_OK && amt>0 ){
drhcc97ca42017-06-07 22:32:59 +00005128 /* Overflow chain ends prematurely */
5129 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drha7fcb052001-12-14 15:09:55 +00005130 }
danielk1977da107192007-05-04 08:32:13 +00005131 return rc;
drh2af926b2001-05-15 00:39:25 +00005132}
5133
drh72f82862001-05-24 21:06:34 +00005134/*
drhcb3cabd2016-11-25 19:18:28 +00005135** Read part of the payload for the row at which that cursor pCur is currently
5136** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00005137** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00005138**
drhcb3cabd2016-11-25 19:18:28 +00005139** pCur can be pointing to either a table or an index b-tree.
5140** If pointing to a table btree, then the content section is read. If
5141** pCur is pointing to an index b-tree then the key section is read.
5142**
5143** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
5144** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
5145** cursor might be invalid or might need to be restored before being read.
drh5d1a8722009-07-22 18:07:40 +00005146**
drh3aac2dd2004-04-26 14:10:20 +00005147** Return SQLITE_OK on success or an error code if anything goes
5148** wrong. An error is returned if "offset+amt" is larger than
5149** the available payload.
drh72f82862001-05-24 21:06:34 +00005150*/
drhcb3cabd2016-11-25 19:18:28 +00005151int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drh1fee73e2007-08-29 04:00:57 +00005152 assert( cursorHoldsMutex(pCur) );
drh5d1a8722009-07-22 18:07:40 +00005153 assert( pCur->eState==CURSOR_VALID );
5154 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
drh75e96b32017-04-01 00:20:06 +00005155 assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
drh5d1a8722009-07-22 18:07:40 +00005156 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
drh3aac2dd2004-04-26 14:10:20 +00005157}
drh83ec2762017-01-26 16:54:47 +00005158
5159/*
5160** This variant of sqlite3BtreePayload() works even if the cursor has not
5161** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
5162** interface.
5163*/
danielk19773588ceb2008-06-10 17:30:26 +00005164#ifndef SQLITE_OMIT_INCRBLOB
drh83ec2762017-01-26 16:54:47 +00005165static SQLITE_NOINLINE int accessPayloadChecked(
5166 BtCursor *pCur,
5167 u32 offset,
5168 u32 amt,
5169 void *pBuf
5170){
drhcb3cabd2016-11-25 19:18:28 +00005171 int rc;
danielk19773588ceb2008-06-10 17:30:26 +00005172 if ( pCur->eState==CURSOR_INVALID ){
5173 return SQLITE_ABORT;
5174 }
dan7a2347e2016-01-07 16:43:54 +00005175 assert( cursorOwnsBtShared(pCur) );
drh945b0942017-01-26 21:30:00 +00005176 rc = btreeRestoreCursorPosition(pCur);
drh83ec2762017-01-26 16:54:47 +00005177 return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
5178}
5179int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5180 if( pCur->eState==CURSOR_VALID ){
5181 assert( cursorOwnsBtShared(pCur) );
5182 return accessPayload(pCur, offset, amt, pBuf, 0);
5183 }else{
5184 return accessPayloadChecked(pCur, offset, amt, pBuf);
danielk1977da184232006-01-05 11:34:32 +00005185 }
drh2af926b2001-05-15 00:39:25 +00005186}
drhcb3cabd2016-11-25 19:18:28 +00005187#endif /* SQLITE_OMIT_INCRBLOB */
drh2af926b2001-05-15 00:39:25 +00005188
drh72f82862001-05-24 21:06:34 +00005189/*
drh0e1c19e2004-05-11 00:58:56 +00005190** Return a pointer to payload information from the entry that the
5191** pCur cursor is pointing to. The pointer is to the beginning of
drh2a8d2262013-12-09 20:43:22 +00005192** the key if index btrees (pPage->intKey==0) and is the data for
5193** table btrees (pPage->intKey==1). The number of bytes of available
5194** key/data is written into *pAmt. If *pAmt==0, then the value
5195** returned will not be a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00005196**
5197** This routine is an optimization. It is common for the entire key
5198** and data to fit on the local page and for there to be no overflow
5199** pages. When that is so, this routine can be used to access the
5200** key and data without making a copy. If the key and/or data spills
drh7f751222009-03-17 22:33:00 +00005201** onto overflow pages, then accessPayload() must be used to reassemble
drh0e1c19e2004-05-11 00:58:56 +00005202** the key/data and copy it into a preallocated buffer.
5203**
5204** The pointer returned by this routine looks directly into the cached
5205** page of the database. The data might change or move the next time
5206** any btree routine is called.
5207*/
drh2a8d2262013-12-09 20:43:22 +00005208static const void *fetchPayload(
drh0e1c19e2004-05-11 00:58:56 +00005209 BtCursor *pCur, /* Cursor pointing to entry to read from */
drh2a8d2262013-12-09 20:43:22 +00005210 u32 *pAmt /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00005211){
drhf3392e32015-04-15 17:26:55 +00005212 u32 amt;
danielk197771d5d2c2008-09-29 11:49:47 +00005213 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
danielk1977da184232006-01-05 11:34:32 +00005214 assert( pCur->eState==CURSOR_VALID );
drh2a8d2262013-12-09 20:43:22 +00005215 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
dan7a2347e2016-01-07 16:43:54 +00005216 assert( cursorOwnsBtShared(pCur) );
drh75e96b32017-04-01 00:20:06 +00005217 assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
drh86dd3712014-03-25 11:00:21 +00005218 assert( pCur->info.nSize>0 );
drhf3392e32015-04-15 17:26:55 +00005219 assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
5220 assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
5221 amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
5222 if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
5223 *pAmt = amt;
drhab1cc582014-09-23 21:25:19 +00005224 return (void*)pCur->info.pPayload;
drh0e1c19e2004-05-11 00:58:56 +00005225}
5226
5227
5228/*
drhe51c44f2004-05-30 20:46:09 +00005229** For the entry that cursor pCur is point to, return as
5230** many bytes of the key or data as are available on the local
5231** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00005232**
5233** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00005234** or be destroyed on the next call to any Btree routine,
5235** including calls from other threads against the same cache.
5236** Hence, a mutex on the BtShared should be held prior to calling
5237** this routine.
drh0e1c19e2004-05-11 00:58:56 +00005238**
5239** These routines is used to get quick access to key and data
5240** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00005241*/
drha7c90c42016-06-04 20:37:10 +00005242const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
drh2a8d2262013-12-09 20:43:22 +00005243 return fetchPayload(pCur, pAmt);
drh0e1c19e2004-05-11 00:58:56 +00005244}
5245
5246
5247/*
drh8178a752003-01-05 21:41:40 +00005248** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00005249** page number of the child page to move to.
danielk1977a299d612009-07-13 11:22:10 +00005250**
5251** This function returns SQLITE_CORRUPT if the page-header flags field of
5252** the new child page does not match the flags field of the parent (i.e.
5253** if an intkey page appears to be the parent of a non-intkey page, or
5254** vice-versa).
drh72f82862001-05-24 21:06:34 +00005255*/
drh3aac2dd2004-04-26 14:10:20 +00005256static int moveToChild(BtCursor *pCur, u32 newPgno){
drhd0679ed2007-08-28 22:24:34 +00005257 BtShared *pBt = pCur->pBt;
dan7fff2e12017-05-29 14:27:37 +00005258 int rc;
drh72f82862001-05-24 21:06:34 +00005259
dan7a2347e2016-01-07 16:43:54 +00005260 assert( cursorOwnsBtShared(pCur) );
danielk1977da184232006-01-05 11:34:32 +00005261 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00005262 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
dan11dcd112013-03-15 18:29:18 +00005263 assert( pCur->iPage>=0 );
danielk197771d5d2c2008-09-29 11:49:47 +00005264 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
5265 return SQLITE_CORRUPT_BKPT;
5266 }
drh271efa52004-05-30 19:19:05 +00005267 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00005268 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drh75e96b32017-04-01 00:20:06 +00005269 pCur->aiIdx[pCur->iPage++] = pCur->ix;
5270 pCur->ix = 0;
dan7fff2e12017-05-29 14:27:37 +00005271 rc = getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
drh28f58dd2015-06-27 19:45:03 +00005272 pCur, pCur->curPagerFlags);
dan7fff2e12017-05-29 14:27:37 +00005273 if( rc==SQLITE_OK ){
5274 setMempageRoot(pCur->apPage[pCur->iPage], pCur->pgnoRoot);
5275 }
5276 return rc;
drh72f82862001-05-24 21:06:34 +00005277}
5278
drhd879e3e2017-02-13 13:35:55 +00005279#ifdef SQLITE_DEBUG
danielk1977bf93c562008-09-29 15:53:25 +00005280/*
5281** Page pParent is an internal (non-leaf) tree page. This function
5282** asserts that page number iChild is the left-child if the iIdx'th
5283** cell in page pParent. Or, if iIdx is equal to the total number of
5284** cells in pParent, that page number iChild is the right-child of
5285** the page.
5286*/
5287static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
drhcbd33492015-03-25 13:06:54 +00005288 if( CORRUPT_DB ) return; /* The conditions tested below might not be true
5289 ** in a corrupt database */
danielk1977bf93c562008-09-29 15:53:25 +00005290 assert( iIdx<=pParent->nCell );
5291 if( iIdx==pParent->nCell ){
5292 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
5293 }else{
5294 assert( get4byte(findCell(pParent, iIdx))==iChild );
5295 }
5296}
5297#else
5298# define assertParentIndex(x,y,z)
5299#endif
5300
drh72f82862001-05-24 21:06:34 +00005301/*
drh5e2f8b92001-05-28 00:41:15 +00005302** Move the cursor up to the parent page.
5303**
5304** pCur->idx is set to the cell index that contains the pointer
5305** to the page we are coming from. If we are coming from the
5306** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00005307** the largest cell index.
drh72f82862001-05-24 21:06:34 +00005308*/
danielk197730548662009-07-09 05:07:37 +00005309static void moveToParent(BtCursor *pCur){
dan7a2347e2016-01-07 16:43:54 +00005310 assert( cursorOwnsBtShared(pCur) );
danielk1977da184232006-01-05 11:34:32 +00005311 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00005312 assert( pCur->iPage>0 );
5313 assert( pCur->apPage[pCur->iPage] );
danielk1977bf93c562008-09-29 15:53:25 +00005314 assertParentIndex(
5315 pCur->apPage[pCur->iPage-1],
5316 pCur->aiIdx[pCur->iPage-1],
5317 pCur->apPage[pCur->iPage]->pgno
5318 );
dan6c2688c2012-01-12 15:05:03 +00005319 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
drh271efa52004-05-30 19:19:05 +00005320 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00005321 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drh75e96b32017-04-01 00:20:06 +00005322 pCur->ix = pCur->aiIdx[pCur->iPage-1];
drhbbf0f862015-06-27 14:59:26 +00005323 releasePageNotNull(pCur->apPage[pCur->iPage--]);
drh72f82862001-05-24 21:06:34 +00005324}
5325
5326/*
danielk19778f880a82009-07-13 09:41:45 +00005327** Move the cursor to point to the root page of its b-tree structure.
5328**
5329** If the table has a virtual root page, then the cursor is moved to point
5330** to the virtual root page instead of the actual root page. A table has a
5331** virtual root page when the actual root page contains no cells and a
5332** single child page. This can only happen with the table rooted at page 1.
5333**
5334** If the b-tree structure is empty, the cursor state is set to
5335** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
5336** cell located on the root (or virtual root) page and the cursor state
5337** is set to CURSOR_VALID.
5338**
5339** If this function returns successfully, it may be assumed that the
5340** page-header flags indicate that the [virtual] root-page is the expected
5341** kind of b-tree page (i.e. if when opening the cursor the caller did not
5342** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
5343** indicating a table b-tree, or if the caller did specify a KeyInfo
5344** structure the flags byte is set to 0x02 or 0x0A, indicating an index
5345** b-tree).
drh72f82862001-05-24 21:06:34 +00005346*/
drh5e2f8b92001-05-28 00:41:15 +00005347static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00005348 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00005349 int rc = SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00005350
dan7a2347e2016-01-07 16:43:54 +00005351 assert( cursorOwnsBtShared(pCur) );
drhfb982642007-08-30 01:19:59 +00005352 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
5353 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
5354 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
5355 if( pCur->eState>=CURSOR_REQUIRESEEK ){
5356 if( pCur->eState==CURSOR_FAULT ){
drh4c301aa2009-07-15 17:25:45 +00005357 assert( pCur->skipNext!=SQLITE_OK );
5358 return pCur->skipNext;
drhfb982642007-08-30 01:19:59 +00005359 }
danielk1977be51a652008-10-08 17:58:48 +00005360 sqlite3BtreeClearCursor(pCur);
drhbf700f32007-03-31 02:36:44 +00005361 }
danielk197771d5d2c2008-09-29 11:49:47 +00005362
5363 if( pCur->iPage>=0 ){
drh7ad3eb62016-10-24 01:01:09 +00005364 if( pCur->iPage ){
5365 do{
5366 assert( pCur->apPage[pCur->iPage]!=0 );
5367 releasePageNotNull(pCur->apPage[pCur->iPage--]);
5368 }while( pCur->iPage);
5369 goto skip_init;
drhbbf0f862015-06-27 14:59:26 +00005370 }
dana205a482011-08-27 18:48:57 +00005371 }else if( pCur->pgnoRoot==0 ){
5372 pCur->eState = CURSOR_INVALID;
5373 return SQLITE_OK;
drh777e4c42006-01-13 04:31:58 +00005374 }else{
drh28f58dd2015-06-27 19:45:03 +00005375 assert( pCur->iPage==(-1) );
drh4e8fe3f2013-12-06 23:25:27 +00005376 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
drh15a00212015-06-27 20:55:00 +00005377 0, pCur->curPagerFlags);
drh4c301aa2009-07-15 17:25:45 +00005378 if( rc!=SQLITE_OK ){
drh777e4c42006-01-13 04:31:58 +00005379 pCur->eState = CURSOR_INVALID;
drh7ad3eb62016-10-24 01:01:09 +00005380 return rc;
drh777e4c42006-01-13 04:31:58 +00005381 }
dan7fff2e12017-05-29 14:27:37 +00005382 setMempageRoot(pCur->apPage[0], pCur->pgnoRoot);
danielk1977172114a2009-07-07 15:47:12 +00005383 pCur->iPage = 0;
drh408efc02015-06-27 22:49:10 +00005384 pCur->curIntKey = pCur->apPage[0]->intKey;
drhc39e0002004-05-07 23:50:57 +00005385 }
danielk197771d5d2c2008-09-29 11:49:47 +00005386 pRoot = pCur->apPage[0];
5387 assert( pRoot->pgno==pCur->pgnoRoot );
dan7df42ab2014-01-20 18:25:44 +00005388
5389 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
5390 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
5391 ** NULL, the caller expects a table b-tree. If this is not the case,
5392 ** return an SQLITE_CORRUPT error.
5393 **
5394 ** Earlier versions of SQLite assumed that this test could not fail
5395 ** if the root page was already loaded when this function was called (i.e.
5396 ** if pCur->iPage>=0). But this is not so if the database is corrupted
5397 ** in such a way that page pRoot is linked into a second b-tree table
5398 ** (or the freelist). */
5399 assert( pRoot->intKey==1 || pRoot->intKey==0 );
5400 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
drhcc97ca42017-06-07 22:32:59 +00005401 return SQLITE_CORRUPT_PGNO(pCur->apPage[pCur->iPage]->pgno);
dan7df42ab2014-01-20 18:25:44 +00005402 }
danielk19778f880a82009-07-13 09:41:45 +00005403
drh7ad3eb62016-10-24 01:01:09 +00005404skip_init:
drh75e96b32017-04-01 00:20:06 +00005405 pCur->ix = 0;
drh271efa52004-05-30 19:19:05 +00005406 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00005407 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
danielk197771d5d2c2008-09-29 11:49:47 +00005408
drh7ad3eb62016-10-24 01:01:09 +00005409 pRoot = pCur->apPage[0];
drh4e8fe3f2013-12-06 23:25:27 +00005410 if( pRoot->nCell>0 ){
5411 pCur->eState = CURSOR_VALID;
5412 }else if( !pRoot->leaf ){
drh8856d6a2004-04-29 14:42:46 +00005413 Pgno subpage;
drhc85240d2009-06-04 16:14:33 +00005414 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
drh43605152004-05-29 21:46:49 +00005415 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
danielk1977da184232006-01-05 11:34:32 +00005416 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00005417 rc = moveToChild(pCur, subpage);
danielk197771d5d2c2008-09-29 11:49:47 +00005418 }else{
drh4e8fe3f2013-12-06 23:25:27 +00005419 pCur->eState = CURSOR_INVALID;
drh8856d6a2004-04-29 14:42:46 +00005420 }
5421 return rc;
drh72f82862001-05-24 21:06:34 +00005422}
drh2af926b2001-05-15 00:39:25 +00005423
drh5e2f8b92001-05-28 00:41:15 +00005424/*
5425** Move the cursor down to the left-most leaf entry beneath the
5426** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00005427**
5428** The left-most leaf is the one with the smallest key - the first
5429** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00005430*/
5431static int moveToLeftmost(BtCursor *pCur){
5432 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00005433 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00005434 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00005435
dan7a2347e2016-01-07 16:43:54 +00005436 assert( cursorOwnsBtShared(pCur) );
danielk1977da184232006-01-05 11:34:32 +00005437 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00005438 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
drh75e96b32017-04-01 00:20:06 +00005439 assert( pCur->ix<pPage->nCell );
5440 pgno = get4byte(findCell(pPage, pCur->ix));
drh8178a752003-01-05 21:41:40 +00005441 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00005442 }
drhd677b3d2007-08-20 22:48:41 +00005443 return rc;
drh5e2f8b92001-05-28 00:41:15 +00005444}
5445
drh2dcc9aa2002-12-04 13:40:25 +00005446/*
5447** Move the cursor down to the right-most leaf entry beneath the
5448** page to which it is currently pointing. Notice the difference
5449** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
5450** finds the left-most entry beneath the *entry* whereas moveToRightmost()
5451** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00005452**
5453** The right-most entry is the one with the largest key - the last
5454** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00005455*/
5456static int moveToRightmost(BtCursor *pCur){
5457 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00005458 int rc = SQLITE_OK;
drh1bd10f82008-12-10 21:19:56 +00005459 MemPage *pPage = 0;
drh2dcc9aa2002-12-04 13:40:25 +00005460
dan7a2347e2016-01-07 16:43:54 +00005461 assert( cursorOwnsBtShared(pCur) );
danielk1977da184232006-01-05 11:34:32 +00005462 assert( pCur->eState==CURSOR_VALID );
drhee6438d2014-09-01 13:29:32 +00005463 while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
drh43605152004-05-29 21:46:49 +00005464 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh75e96b32017-04-01 00:20:06 +00005465 pCur->ix = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00005466 rc = moveToChild(pCur, pgno);
drhee6438d2014-09-01 13:29:32 +00005467 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00005468 }
drh75e96b32017-04-01 00:20:06 +00005469 pCur->ix = pPage->nCell-1;
drhee6438d2014-09-01 13:29:32 +00005470 assert( pCur->info.nSize==0 );
5471 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5472 return SQLITE_OK;
drh2dcc9aa2002-12-04 13:40:25 +00005473}
5474
drh5e00f6c2001-09-13 13:46:56 +00005475/* Move the cursor to the first entry in the table. Return SQLITE_OK
5476** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00005477** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00005478*/
drh3aac2dd2004-04-26 14:10:20 +00005479int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00005480 int rc;
drhd677b3d2007-08-20 22:48:41 +00005481
dan7a2347e2016-01-07 16:43:54 +00005482 assert( cursorOwnsBtShared(pCur) );
drhe5fe6902007-12-07 18:55:28 +00005483 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00005484 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00005485 if( rc==SQLITE_OK ){
5486 if( pCur->eState==CURSOR_INVALID ){
dana205a482011-08-27 18:48:57 +00005487 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00005488 *pRes = 1;
drhd677b3d2007-08-20 22:48:41 +00005489 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00005490 assert( pCur->apPage[pCur->iPage]->nCell>0 );
drhd677b3d2007-08-20 22:48:41 +00005491 *pRes = 0;
5492 rc = moveToLeftmost(pCur);
5493 }
drh5e00f6c2001-09-13 13:46:56 +00005494 }
drh5e00f6c2001-09-13 13:46:56 +00005495 return rc;
5496}
drh5e2f8b92001-05-28 00:41:15 +00005497
drh9562b552002-02-19 15:00:07 +00005498/* Move the cursor to the last entry in the table. Return SQLITE_OK
5499** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00005500** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00005501*/
drh3aac2dd2004-04-26 14:10:20 +00005502int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00005503 int rc;
drhd677b3d2007-08-20 22:48:41 +00005504
dan7a2347e2016-01-07 16:43:54 +00005505 assert( cursorOwnsBtShared(pCur) );
drhe5fe6902007-12-07 18:55:28 +00005506 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19773f632d52009-05-02 10:03:09 +00005507
5508 /* If the cursor already points to the last entry, this is a no-op. */
drh036dbec2014-03-11 23:40:44 +00005509 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
danielk19773f632d52009-05-02 10:03:09 +00005510#ifdef SQLITE_DEBUG
5511 /* This block serves to assert() that the cursor really does point
5512 ** to the last entry in the b-tree. */
5513 int ii;
5514 for(ii=0; ii<pCur->iPage; ii++){
5515 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
5516 }
drh75e96b32017-04-01 00:20:06 +00005517 assert( pCur->ix==pCur->apPage[pCur->iPage]->nCell-1 );
danielk19773f632d52009-05-02 10:03:09 +00005518 assert( pCur->apPage[pCur->iPage]->leaf );
5519#endif
5520 return SQLITE_OK;
5521 }
5522
drh9562b552002-02-19 15:00:07 +00005523 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00005524 if( rc==SQLITE_OK ){
5525 if( CURSOR_INVALID==pCur->eState ){
dana205a482011-08-27 18:48:57 +00005526 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00005527 *pRes = 1;
5528 }else{
5529 assert( pCur->eState==CURSOR_VALID );
5530 *pRes = 0;
5531 rc = moveToRightmost(pCur);
drh036dbec2014-03-11 23:40:44 +00005532 if( rc==SQLITE_OK ){
5533 pCur->curFlags |= BTCF_AtLast;
5534 }else{
5535 pCur->curFlags &= ~BTCF_AtLast;
5536 }
5537
drhd677b3d2007-08-20 22:48:41 +00005538 }
drh9562b552002-02-19 15:00:07 +00005539 }
drh9562b552002-02-19 15:00:07 +00005540 return rc;
5541}
5542
drhe14006d2008-03-25 17:23:32 +00005543/* Move the cursor so that it points to an entry near the key
drhe63d9992008-08-13 19:11:48 +00005544** specified by pIdxKey or intKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00005545**
drhe63d9992008-08-13 19:11:48 +00005546** For INTKEY tables, the intKey parameter is used. pIdxKey
5547** must be NULL. For index tables, pIdxKey is used and intKey
5548** is ignored.
drh3aac2dd2004-04-26 14:10:20 +00005549**
drh5e2f8b92001-05-28 00:41:15 +00005550** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00005551** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00005552** were present. The cursor might point to an entry that comes
5553** before or after the key.
5554**
drh64022502009-01-09 14:11:04 +00005555** An integer is written into *pRes which is the result of
5556** comparing the key with the entry to which the cursor is
5557** pointing. The meaning of the integer written into
5558** *pRes is as follows:
drhbd03cae2001-06-02 02:40:57 +00005559**
5560** *pRes<0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00005561** is smaller than intKey/pIdxKey or if the table is empty
drh1a844c32002-12-04 22:29:28 +00005562** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00005563**
5564** *pRes==0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00005565** exactly matches intKey/pIdxKey.
drhbd03cae2001-06-02 02:40:57 +00005566**
5567** *pRes>0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00005568** is larger than intKey/pIdxKey.
drhd677b3d2007-08-20 22:48:41 +00005569**
drhb1d607d2015-11-05 22:30:54 +00005570** For index tables, the pIdxKey->eqSeen field is set to 1 if there
5571** exists an entry in the table that exactly matches pIdxKey.
drha059ad02001-04-17 20:09:11 +00005572*/
drhe63d9992008-08-13 19:11:48 +00005573int sqlite3BtreeMovetoUnpacked(
5574 BtCursor *pCur, /* The cursor to be moved */
5575 UnpackedRecord *pIdxKey, /* Unpacked index key */
5576 i64 intKey, /* The table key */
5577 int biasRight, /* If true, bias the search to the high end */
5578 int *pRes /* Write search results here */
drhe4d90812007-03-29 05:51:49 +00005579){
drh72f82862001-05-24 21:06:34 +00005580 int rc;
dan3b9330f2014-02-27 20:44:18 +00005581 RecordCompare xRecordCompare;
drhd677b3d2007-08-20 22:48:41 +00005582
dan7a2347e2016-01-07 16:43:54 +00005583 assert( cursorOwnsBtShared(pCur) );
drhe5fe6902007-12-07 18:55:28 +00005584 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19775cb09632009-07-09 11:36:01 +00005585 assert( pRes );
danielk19773fd7cf52009-07-13 07:30:52 +00005586 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
drhdebaa862016-06-13 12:51:20 +00005587 assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
drha2c20e42008-03-29 16:01:04 +00005588
5589 /* If the cursor is already positioned at the point we are trying
5590 ** to move to, then just return without doing any work */
drh05a36092016-06-06 01:54:20 +00005591 if( pIdxKey==0
5592 && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
danielk197771d5d2c2008-09-29 11:49:47 +00005593 ){
drhe63d9992008-08-13 19:11:48 +00005594 if( pCur->info.nKey==intKey ){
drha2c20e42008-03-29 16:01:04 +00005595 *pRes = 0;
5596 return SQLITE_OK;
5597 }
drh451e76d2017-01-21 16:54:19 +00005598 if( pCur->info.nKey<intKey ){
5599 if( (pCur->curFlags & BTCF_AtLast)!=0 ){
5600 *pRes = -1;
5601 return SQLITE_OK;
5602 }
drh7f11afa2017-01-21 21:47:54 +00005603 /* If the requested key is one more than the previous key, then
5604 ** try to get there using sqlite3BtreeNext() rather than a full
5605 ** binary search. This is an optimization only. The correct answer
drh2ab792e2017-05-30 18:34:07 +00005606 ** is still obtained without this case, only a little more slowely */
drh7f11afa2017-01-21 21:47:54 +00005607 if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
5608 *pRes = 0;
drh2ab792e2017-05-30 18:34:07 +00005609 rc = sqlite3BtreeNext(pCur, 0);
5610 if( rc==SQLITE_OK ){
drh7f11afa2017-01-21 21:47:54 +00005611 getCellInfo(pCur);
5612 if( pCur->info.nKey==intKey ){
5613 return SQLITE_OK;
5614 }
drh2ab792e2017-05-30 18:34:07 +00005615 }else if( rc==SQLITE_DONE ){
5616 rc = SQLITE_OK;
5617 }else{
5618 return rc;
drh451e76d2017-01-21 16:54:19 +00005619 }
5620 }
drha2c20e42008-03-29 16:01:04 +00005621 }
5622 }
5623
dan1fed5da2014-02-25 21:01:25 +00005624 if( pIdxKey ){
5625 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
dan38fdead2014-04-01 10:19:02 +00005626 pIdxKey->errCode = 0;
dan3b9330f2014-02-27 20:44:18 +00005627 assert( pIdxKey->default_rc==1
5628 || pIdxKey->default_rc==0
5629 || pIdxKey->default_rc==-1
5630 );
drh13a747e2014-03-03 21:46:55 +00005631 }else{
drhb6e8fd12014-03-06 01:56:33 +00005632 xRecordCompare = 0; /* All keys are integers */
dan1fed5da2014-02-25 21:01:25 +00005633 }
5634
drh5e2f8b92001-05-28 00:41:15 +00005635 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00005636 if( rc ){
5637 return rc;
5638 }
dana205a482011-08-27 18:48:57 +00005639 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
5640 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
5641 assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
danielk1977da184232006-01-05 11:34:32 +00005642 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00005643 *pRes = -1;
dana205a482011-08-27 18:48:57 +00005644 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
drhc39e0002004-05-07 23:50:57 +00005645 return SQLITE_OK;
5646 }
drhc75d8862015-06-27 23:55:20 +00005647 assert( pCur->apPage[0]->intKey==pCur->curIntKey );
5648 assert( pCur->curIntKey || pIdxKey );
drh14684382006-11-30 13:05:29 +00005649 for(;;){
drhec3e6b12013-11-25 02:38:55 +00005650 int lwr, upr, idx, c;
drh72f82862001-05-24 21:06:34 +00005651 Pgno chldPg;
danielk197771d5d2c2008-09-29 11:49:47 +00005652 MemPage *pPage = pCur->apPage[pCur->iPage];
drhec3e6b12013-11-25 02:38:55 +00005653 u8 *pCell; /* Pointer to current cell in pPage */
danielk1977171fff32009-07-11 05:06:51 +00005654
5655 /* pPage->nCell must be greater than zero. If this is the root-page
5656 ** the cursor would have been INVALID above and this for(;;) loop
5657 ** not run. If this is not the root-page, then the moveToChild() routine
danielk19773fd7cf52009-07-13 07:30:52 +00005658 ** would have already detected db corruption. Similarly, pPage must
5659 ** be the right kind (index or table) of b-tree page. Otherwise
5660 ** a moveToChild() or moveToRoot() call would have detected corruption. */
danielk1977171fff32009-07-11 05:06:51 +00005661 assert( pPage->nCell>0 );
danielk19773fd7cf52009-07-13 07:30:52 +00005662 assert( pPage->intKey==(pIdxKey==0) );
drh72f82862001-05-24 21:06:34 +00005663 lwr = 0;
5664 upr = pPage->nCell-1;
drhebf10b12013-11-25 17:38:26 +00005665 assert( biasRight==0 || biasRight==1 );
5666 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
drh75e96b32017-04-01 00:20:06 +00005667 pCur->ix = (u16)idx;
dana4660bd2014-03-04 16:05:25 +00005668 if( xRecordCompare==0 ){
drhec3e6b12013-11-25 02:38:55 +00005669 for(;;){
danielk197711c327a2009-05-04 19:01:26 +00005670 i64 nCellKey;
drhf44890a2015-06-27 03:58:15 +00005671 pCell = findCellPastPtr(pPage, idx);
drh3e28ff52014-09-24 00:59:08 +00005672 if( pPage->intKeyLeaf ){
drh9b2fc612013-11-25 20:14:13 +00005673 while( 0x80 <= *(pCell++) ){
drhcc97ca42017-06-07 22:32:59 +00005674 if( pCell>=pPage->aDataEnd ){
5675 return SQLITE_CORRUPT_PGNO(pPage->pgno);
5676 }
drh9b2fc612013-11-25 20:14:13 +00005677 }
drhd172f862006-01-12 15:01:15 +00005678 }
drha2c20e42008-03-29 16:01:04 +00005679 getVarint(pCell, (u64*)&nCellKey);
drhbb933ef2013-11-25 15:01:38 +00005680 if( nCellKey<intKey ){
5681 lwr = idx+1;
5682 if( lwr>upr ){ c = -1; break; }
5683 }else if( nCellKey>intKey ){
5684 upr = idx-1;
5685 if( lwr>upr ){ c = +1; break; }
5686 }else{
5687 assert( nCellKey==intKey );
drh75e96b32017-04-01 00:20:06 +00005688 pCur->ix = (u16)idx;
drhec3e6b12013-11-25 02:38:55 +00005689 if( !pPage->leaf ){
5690 lwr = idx;
drhebf10b12013-11-25 17:38:26 +00005691 goto moveto_next_layer;
drhec3e6b12013-11-25 02:38:55 +00005692 }else{
drhd95ef5c2016-11-11 18:19:05 +00005693 pCur->curFlags |= BTCF_ValidNKey;
5694 pCur->info.nKey = nCellKey;
5695 pCur->info.nSize = 0;
drhec3e6b12013-11-25 02:38:55 +00005696 *pRes = 0;
drhd95ef5c2016-11-11 18:19:05 +00005697 return SQLITE_OK;
drhec3e6b12013-11-25 02:38:55 +00005698 }
drhd793f442013-11-25 14:10:15 +00005699 }
drhebf10b12013-11-25 17:38:26 +00005700 assert( lwr+upr>=0 );
5701 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
drhec3e6b12013-11-25 02:38:55 +00005702 }
5703 }else{
5704 for(;;){
drhc6827502015-05-28 15:14:32 +00005705 int nCell; /* Size of the pCell cell in bytes */
drhf44890a2015-06-27 03:58:15 +00005706 pCell = findCellPastPtr(pPage, idx);
drhec3e6b12013-11-25 02:38:55 +00005707
drhb2eced52010-08-12 02:41:12 +00005708 /* The maximum supported page-size is 65536 bytes. This means that
danielk197711c327a2009-05-04 19:01:26 +00005709 ** the maximum number of record bytes stored on an index B-Tree
drhb2eced52010-08-12 02:41:12 +00005710 ** page is less than 16384 bytes and may be stored as a 2-byte
danielk197711c327a2009-05-04 19:01:26 +00005711 ** varint. This information is used to attempt to avoid parsing
5712 ** the entire cell by checking for the cases where the record is
5713 ** stored entirely within the b-tree page by inspecting the first
5714 ** 2 bytes of the cell.
5715 */
drhec3e6b12013-11-25 02:38:55 +00005716 nCell = pCell[0];
drh72b8ef62013-12-06 22:44:51 +00005717 if( nCell<=pPage->max1bytePayload ){
danielk197711c327a2009-05-04 19:01:26 +00005718 /* This branch runs if the record-size field of the cell is a
5719 ** single byte varint and the record fits entirely on the main
5720 ** b-tree page. */
drh3def2352011-11-11 00:27:15 +00005721 testcase( pCell+nCell+1==pPage->aDataEnd );
drh75179de2014-09-16 14:37:35 +00005722 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
danielk197711c327a2009-05-04 19:01:26 +00005723 }else if( !(pCell[1] & 0x80)
5724 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5725 ){
5726 /* The record-size field is a 2 byte varint and the record
5727 ** fits entirely on the main b-tree page. */
drh3def2352011-11-11 00:27:15 +00005728 testcase( pCell+nCell+2==pPage->aDataEnd );
drh75179de2014-09-16 14:37:35 +00005729 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
drhe51c44f2004-05-30 20:46:09 +00005730 }else{
danielk197711c327a2009-05-04 19:01:26 +00005731 /* The record flows over onto one or more overflow pages. In
5732 ** this case the whole cell needs to be parsed, a buffer allocated
5733 ** and accessPayload() used to retrieve the record into the
dan3548db72015-05-27 14:21:05 +00005734 ** buffer before VdbeRecordCompare() can be called.
5735 **
5736 ** If the record is corrupt, the xRecordCompare routine may read
5737 ** up to two varints past the end of the buffer. An extra 18
5738 ** bytes of padding is allocated at the end of the buffer in
5739 ** case this happens. */
danielk197711c327a2009-05-04 19:01:26 +00005740 void *pCellKey;
5741 u8 * const pCellBody = pCell - pPage->childPtrSize;
drh5fa60512015-06-19 17:19:34 +00005742 pPage->xParseCell(pPage, pCellBody, &pCur->info);
shane60a4b532009-05-06 18:57:09 +00005743 nCell = (int)pCur->info.nKey;
drhc6827502015-05-28 15:14:32 +00005744 testcase( nCell<0 ); /* True if key size is 2^32 or more */
5745 testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
5746 testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
5747 testcase( nCell==2 ); /* Minimum legal index key size */
dan3548db72015-05-27 14:21:05 +00005748 if( nCell<2 ){
drhcc97ca42017-06-07 22:32:59 +00005749 rc = SQLITE_CORRUPT_PGNO(pPage->pgno);
dan3548db72015-05-27 14:21:05 +00005750 goto moveto_finish;
5751 }
5752 pCellKey = sqlite3Malloc( nCell+18 );
danielk19776507ecb2008-03-25 09:56:44 +00005753 if( pCellKey==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005754 rc = SQLITE_NOMEM_BKPT;
danielk19776507ecb2008-03-25 09:56:44 +00005755 goto moveto_finish;
5756 }
drh75e96b32017-04-01 00:20:06 +00005757 pCur->ix = (u16)idx;
drh42e28f12017-01-27 00:31:59 +00005758 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
5759 pCur->curFlags &= ~BTCF_ValidOvfl;
drhec9b31f2009-08-25 13:53:49 +00005760 if( rc ){
5761 sqlite3_free(pCellKey);
5762 goto moveto_finish;
5763 }
drh75179de2014-09-16 14:37:35 +00005764 c = xRecordCompare(nCell, pCellKey, pIdxKey);
drhfacf0302008-06-17 15:12:00 +00005765 sqlite3_free(pCellKey);
drhe51c44f2004-05-30 20:46:09 +00005766 }
dan38fdead2014-04-01 10:19:02 +00005767 assert(
5768 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
dana7bf23c2014-05-02 17:12:41 +00005769 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
dan38fdead2014-04-01 10:19:02 +00005770 );
drhbb933ef2013-11-25 15:01:38 +00005771 if( c<0 ){
5772 lwr = idx+1;
5773 }else if( c>0 ){
5774 upr = idx-1;
5775 }else{
5776 assert( c==0 );
drh64022502009-01-09 14:11:04 +00005777 *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00005778 rc = SQLITE_OK;
drh75e96b32017-04-01 00:20:06 +00005779 pCur->ix = (u16)idx;
dan38fdead2014-04-01 10:19:02 +00005780 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
drh1e968a02008-03-25 00:22:21 +00005781 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00005782 }
drhebf10b12013-11-25 17:38:26 +00005783 if( lwr>upr ) break;
5784 assert( lwr+upr>=0 );
5785 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
drh72f82862001-05-24 21:06:34 +00005786 }
drh72f82862001-05-24 21:06:34 +00005787 }
drhb07028f2011-10-14 21:49:18 +00005788 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
danielk197771d5d2c2008-09-29 11:49:47 +00005789 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00005790 if( pPage->leaf ){
drh75e96b32017-04-01 00:20:06 +00005791 assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
5792 pCur->ix = (u16)idx;
drhec3e6b12013-11-25 02:38:55 +00005793 *pRes = c;
5794 rc = SQLITE_OK;
5795 goto moveto_finish;
drhebf10b12013-11-25 17:38:26 +00005796 }
5797moveto_next_layer:
5798 if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00005799 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00005800 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00005801 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00005802 }
drh75e96b32017-04-01 00:20:06 +00005803 pCur->ix = (u16)lwr;
drh8178a752003-01-05 21:41:40 +00005804 rc = moveToChild(pCur, chldPg);
drhec3e6b12013-11-25 02:38:55 +00005805 if( rc ) break;
drh72f82862001-05-24 21:06:34 +00005806 }
drh1e968a02008-03-25 00:22:21 +00005807moveto_finish:
drhd2022b02013-11-25 16:23:52 +00005808 pCur->info.nSize = 0;
drhd95ef5c2016-11-11 18:19:05 +00005809 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
drhe63d9992008-08-13 19:11:48 +00005810 return rc;
5811}
5812
drhd677b3d2007-08-20 22:48:41 +00005813
drh72f82862001-05-24 21:06:34 +00005814/*
drhc39e0002004-05-07 23:50:57 +00005815** Return TRUE if the cursor is not pointing at an entry of the table.
5816**
5817** TRUE will be returned after a call to sqlite3BtreeNext() moves
5818** past the last entry in the table or sqlite3BtreePrev() moves past
5819** the first entry. TRUE is also returned if the table is empty.
5820*/
5821int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00005822 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
5823 ** have been deleted? This API will need to change to return an error code
5824 ** as well as the boolean result value.
5825 */
5826 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00005827}
5828
5829/*
drh5e98e832017-02-17 19:24:06 +00005830** Return an estimate for the number of rows in the table that pCur is
5831** pointing to. Return a negative number if no estimate is currently
5832** available.
5833*/
5834i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
5835 i64 n;
5836 u8 i;
5837
5838 assert( cursorOwnsBtShared(pCur) );
5839 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh555227b2017-02-23 02:15:33 +00005840
5841 /* Currently this interface is only called by the OP_IfSmaller
5842 ** opcode, and it that case the cursor will always be valid and
5843 ** will always point to a leaf node. */
5844 if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
5845 if( NEVER(pCur->apPage[pCur->iPage]->leaf==0) ) return -1;
5846
drhdfe11ba2017-02-18 02:42:54 +00005847 for(n=1, i=0; i<=pCur->iPage; i++){
drh5e98e832017-02-17 19:24:06 +00005848 n *= pCur->apPage[i]->nCell;
5849 }
5850 return n;
5851}
5852
5853/*
drh2ab792e2017-05-30 18:34:07 +00005854** Advance the cursor to the next entry in the database.
5855** Return value:
5856**
5857** SQLITE_OK success
5858** SQLITE_DONE cursor is already pointing at the last element
5859** otherwise some kind of error occurred
drhe39a7322014-02-03 14:04:11 +00005860**
drhee6438d2014-09-01 13:29:32 +00005861** The main entry point is sqlite3BtreeNext(). That routine is optimized
5862** for the common case of merely incrementing the cell counter BtCursor.aiIdx
5863** to the next cell on the current page. The (slower) btreeNext() helper
5864** routine is called when it is necessary to move to a different page or
5865** to restore the cursor.
5866**
drh89997982017-07-11 18:11:33 +00005867** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
5868** cursor corresponds to an SQL index and this routine could have been
5869** skipped if the SQL index had been a unique index. The F argument
5870** is a hint to the implement. SQLite btree implementation does not use
5871** this hint, but COMDB2 does.
drh72f82862001-05-24 21:06:34 +00005872*/
drh89997982017-07-11 18:11:33 +00005873static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00005874 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00005875 int idx;
danielk197797a227c2006-01-20 16:32:04 +00005876 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00005877
dan7a2347e2016-01-07 16:43:54 +00005878 assert( cursorOwnsBtShared(pCur) );
drh9b47ee32013-08-20 03:13:51 +00005879 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
drhf66f26a2013-08-19 20:04:10 +00005880 if( pCur->eState!=CURSOR_VALID ){
drhee6438d2014-09-01 13:29:32 +00005881 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
drhf66f26a2013-08-19 20:04:10 +00005882 rc = restoreCursorPosition(pCur);
5883 if( rc!=SQLITE_OK ){
5884 return rc;
5885 }
5886 if( CURSOR_INVALID==pCur->eState ){
drh2ab792e2017-05-30 18:34:07 +00005887 return SQLITE_DONE;
drhf66f26a2013-08-19 20:04:10 +00005888 }
drh9b47ee32013-08-20 03:13:51 +00005889 if( pCur->skipNext ){
5890 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5891 pCur->eState = CURSOR_VALID;
5892 if( pCur->skipNext>0 ){
5893 pCur->skipNext = 0;
drh9b47ee32013-08-20 03:13:51 +00005894 return SQLITE_OK;
5895 }
drhf66f26a2013-08-19 20:04:10 +00005896 pCur->skipNext = 0;
drhf66f26a2013-08-19 20:04:10 +00005897 }
danielk1977da184232006-01-05 11:34:32 +00005898 }
danielk1977da184232006-01-05 11:34:32 +00005899
danielk197771d5d2c2008-09-29 11:49:47 +00005900 pPage = pCur->apPage[pCur->iPage];
drh75e96b32017-04-01 00:20:06 +00005901 idx = ++pCur->ix;
danielk197771d5d2c2008-09-29 11:49:47 +00005902 assert( pPage->isInit );
danbb246c42012-01-12 14:25:55 +00005903
5904 /* If the database file is corrupt, it is possible for the value of idx
5905 ** to be invalid here. This can only occur if a second cursor modifies
5906 ** the page while cursor pCur is holding a reference to it. Which can
5907 ** only happen if the database is corrupt in such a way as to link the
5908 ** page into more than one b-tree structure. */
5909 testcase( idx>pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00005910
danielk197771d5d2c2008-09-29 11:49:47 +00005911 if( idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00005912 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005913 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drhee6438d2014-09-01 13:29:32 +00005914 if( rc ) return rc;
5915 return moveToLeftmost(pCur);
drh72f82862001-05-24 21:06:34 +00005916 }
drh5e2f8b92001-05-28 00:41:15 +00005917 do{
danielk197771d5d2c2008-09-29 11:49:47 +00005918 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00005919 pCur->eState = CURSOR_INVALID;
drh2ab792e2017-05-30 18:34:07 +00005920 return SQLITE_DONE;
drh5e2f8b92001-05-28 00:41:15 +00005921 }
danielk197730548662009-07-09 05:07:37 +00005922 moveToParent(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00005923 pPage = pCur->apPage[pCur->iPage];
drh75e96b32017-04-01 00:20:06 +00005924 }while( pCur->ix>=pPage->nCell );
drh44845222008-07-17 18:39:57 +00005925 if( pPage->intKey ){
drh89997982017-07-11 18:11:33 +00005926 return sqlite3BtreeNext(pCur, 0);
drh8b18dd42004-05-12 19:18:15 +00005927 }else{
drhee6438d2014-09-01 13:29:32 +00005928 return SQLITE_OK;
drh8b18dd42004-05-12 19:18:15 +00005929 }
drh8178a752003-01-05 21:41:40 +00005930 }
drh3aac2dd2004-04-26 14:10:20 +00005931 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00005932 return SQLITE_OK;
drhee6438d2014-09-01 13:29:32 +00005933 }else{
5934 return moveToLeftmost(pCur);
drh72f82862001-05-24 21:06:34 +00005935 }
drh72f82862001-05-24 21:06:34 +00005936}
drh2ab792e2017-05-30 18:34:07 +00005937int sqlite3BtreeNext(BtCursor *pCur, int flags){
drhee6438d2014-09-01 13:29:32 +00005938 MemPage *pPage;
drh89997982017-07-11 18:11:33 +00005939 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
dan7a2347e2016-01-07 16:43:54 +00005940 assert( cursorOwnsBtShared(pCur) );
drh2ab792e2017-05-30 18:34:07 +00005941 assert( flags==0 || flags==1 );
drhee6438d2014-09-01 13:29:32 +00005942 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5943 pCur->info.nSize = 0;
5944 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drh89997982017-07-11 18:11:33 +00005945 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
drhee6438d2014-09-01 13:29:32 +00005946 pPage = pCur->apPage[pCur->iPage];
drh75e96b32017-04-01 00:20:06 +00005947 if( (++pCur->ix)>=pPage->nCell ){
5948 pCur->ix--;
drh89997982017-07-11 18:11:33 +00005949 return btreeNext(pCur);
drhee6438d2014-09-01 13:29:32 +00005950 }
5951 if( pPage->leaf ){
5952 return SQLITE_OK;
5953 }else{
5954 return moveToLeftmost(pCur);
5955 }
5956}
drh72f82862001-05-24 21:06:34 +00005957
drh3b7511c2001-05-26 13:15:44 +00005958/*
drh2ab792e2017-05-30 18:34:07 +00005959** Step the cursor to the back to the previous entry in the database.
5960** Return values:
5961**
5962** SQLITE_OK success
5963** SQLITE_DONE the cursor is already on the first element of the table
5964** otherwise some kind of error occurred
drhe39a7322014-02-03 14:04:11 +00005965**
drhee6438d2014-09-01 13:29:32 +00005966** The main entry point is sqlite3BtreePrevious(). That routine is optimized
5967** for the common case of merely decrementing the cell counter BtCursor.aiIdx
drh3f387402014-09-24 01:23:00 +00005968** to the previous cell on the current page. The (slower) btreePrevious()
5969** helper routine is called when it is necessary to move to a different page
5970** or to restore the cursor.
drhee6438d2014-09-01 13:29:32 +00005971**
drh89997982017-07-11 18:11:33 +00005972** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
5973** the cursor corresponds to an SQL index and this routine could have been
5974** skipped if the SQL index had been a unique index. The F argument is a
5975** hint to the implement. The native SQLite btree implementation does not
5976** use this hint, but COMDB2 does.
drh2dcc9aa2002-12-04 13:40:25 +00005977*/
drh89997982017-07-11 18:11:33 +00005978static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
drh2dcc9aa2002-12-04 13:40:25 +00005979 int rc;
drh8178a752003-01-05 21:41:40 +00005980 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00005981
dan7a2347e2016-01-07 16:43:54 +00005982 assert( cursorOwnsBtShared(pCur) );
drh9b47ee32013-08-20 03:13:51 +00005983 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
drhee6438d2014-09-01 13:29:32 +00005984 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
5985 assert( pCur->info.nSize==0 );
drhf66f26a2013-08-19 20:04:10 +00005986 if( pCur->eState!=CURSOR_VALID ){
drh7682a472014-09-29 15:00:28 +00005987 rc = restoreCursorPosition(pCur);
drhee6438d2014-09-01 13:29:32 +00005988 if( rc!=SQLITE_OK ){
5989 return rc;
drhf66f26a2013-08-19 20:04:10 +00005990 }
5991 if( CURSOR_INVALID==pCur->eState ){
drh2ab792e2017-05-30 18:34:07 +00005992 return SQLITE_DONE;
drhf66f26a2013-08-19 20:04:10 +00005993 }
drh9b47ee32013-08-20 03:13:51 +00005994 if( pCur->skipNext ){
5995 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5996 pCur->eState = CURSOR_VALID;
5997 if( pCur->skipNext<0 ){
5998 pCur->skipNext = 0;
drh9b47ee32013-08-20 03:13:51 +00005999 return SQLITE_OK;
6000 }
drhf66f26a2013-08-19 20:04:10 +00006001 pCur->skipNext = 0;
drhf66f26a2013-08-19 20:04:10 +00006002 }
danielk1977da184232006-01-05 11:34:32 +00006003 }
danielk1977da184232006-01-05 11:34:32 +00006004
danielk197771d5d2c2008-09-29 11:49:47 +00006005 pPage = pCur->apPage[pCur->iPage];
6006 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00006007 if( !pPage->leaf ){
drh75e96b32017-04-01 00:20:06 +00006008 int idx = pCur->ix;
danielk197771d5d2c2008-09-29 11:49:47 +00006009 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
drhee6438d2014-09-01 13:29:32 +00006010 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00006011 rc = moveToRightmost(pCur);
6012 }else{
drh75e96b32017-04-01 00:20:06 +00006013 while( pCur->ix==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00006014 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00006015 pCur->eState = CURSOR_INVALID;
drh2ab792e2017-05-30 18:34:07 +00006016 return SQLITE_DONE;
drh2dcc9aa2002-12-04 13:40:25 +00006017 }
danielk197730548662009-07-09 05:07:37 +00006018 moveToParent(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00006019 }
drhee6438d2014-09-01 13:29:32 +00006020 assert( pCur->info.nSize==0 );
drhd95ef5c2016-11-11 18:19:05 +00006021 assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006022
drh75e96b32017-04-01 00:20:06 +00006023 pCur->ix--;
danielk197771d5d2c2008-09-29 11:49:47 +00006024 pPage = pCur->apPage[pCur->iPage];
drh44845222008-07-17 18:39:57 +00006025 if( pPage->intKey && !pPage->leaf ){
drh89997982017-07-11 18:11:33 +00006026 rc = sqlite3BtreePrevious(pCur, 0);
drh8b18dd42004-05-12 19:18:15 +00006027 }else{
6028 rc = SQLITE_OK;
6029 }
drh2dcc9aa2002-12-04 13:40:25 +00006030 }
drh2dcc9aa2002-12-04 13:40:25 +00006031 return rc;
6032}
drh2ab792e2017-05-30 18:34:07 +00006033int sqlite3BtreePrevious(BtCursor *pCur, int flags){
dan7a2347e2016-01-07 16:43:54 +00006034 assert( cursorOwnsBtShared(pCur) );
drh2ab792e2017-05-30 18:34:07 +00006035 assert( flags==0 || flags==1 );
drhee6438d2014-09-01 13:29:32 +00006036 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
drh89997982017-07-11 18:11:33 +00006037 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
drhee6438d2014-09-01 13:29:32 +00006038 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
6039 pCur->info.nSize = 0;
6040 if( pCur->eState!=CURSOR_VALID
drh75e96b32017-04-01 00:20:06 +00006041 || pCur->ix==0
drhee6438d2014-09-01 13:29:32 +00006042 || pCur->apPage[pCur->iPage]->leaf==0
6043 ){
drh89997982017-07-11 18:11:33 +00006044 return btreePrevious(pCur);
drhee6438d2014-09-01 13:29:32 +00006045 }
drh75e96b32017-04-01 00:20:06 +00006046 pCur->ix--;
drhee6438d2014-09-01 13:29:32 +00006047 return SQLITE_OK;
6048}
drh2dcc9aa2002-12-04 13:40:25 +00006049
6050/*
drh3b7511c2001-05-26 13:15:44 +00006051** Allocate a new page from the database file.
6052**
danielk19773b8a05f2007-03-19 17:44:26 +00006053** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00006054** has already been called on the new page.) The new page has also
6055** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00006056** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00006057**
6058** SQLITE_OK is returned on success. Any other return value indicates
drh1c8bade2015-05-29 18:42:11 +00006059** an error. *ppPage is set to NULL in the event of an error.
drhbea00b92002-07-08 10:59:50 +00006060**
drh82e647d2013-03-02 03:25:55 +00006061** If the "nearby" parameter is not 0, then an effort is made to
drh199e3cf2002-07-18 11:01:47 +00006062** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00006063** attempt to keep related pages close to each other in the database file,
6064** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00006065**
drh82e647d2013-03-02 03:25:55 +00006066** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
6067** anywhere on the free-list, then it is guaranteed to be returned. If
6068** eMode is BTALLOC_LT then the page returned will be less than or equal
6069** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
6070** are no restrictions on which page is returned.
drh3b7511c2001-05-26 13:15:44 +00006071*/
drh4f0c5872007-03-26 22:05:01 +00006072static int allocateBtreePage(
drh82e647d2013-03-02 03:25:55 +00006073 BtShared *pBt, /* The btree */
6074 MemPage **ppPage, /* Store pointer to the allocated page here */
6075 Pgno *pPgno, /* Store the page number here */
6076 Pgno nearby, /* Search for a page near this one */
6077 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
danielk1977cb1a7eb2004-11-05 12:27:02 +00006078){
drh3aac2dd2004-04-26 14:10:20 +00006079 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00006080 int rc;
drh35cd6432009-06-05 14:17:21 +00006081 u32 n; /* Number of pages on the freelist */
drh042d6a12009-06-17 13:57:16 +00006082 u32 k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00006083 MemPage *pTrunk = 0;
6084 MemPage *pPrevTrunk = 0;
drh1662b5a2009-06-04 19:06:09 +00006085 Pgno mxPage; /* Total size of the database file */
drh30e58752002-03-02 20:41:57 +00006086
drh1fee73e2007-08-29 04:00:57 +00006087 assert( sqlite3_mutex_held(pBt->mutex) );
dan572a21c2015-08-21 18:55:22 +00006088 assert( eMode==BTALLOC_ANY || (nearby>0 && REQUIRE_PTRMAP ) );
drh3aac2dd2004-04-26 14:10:20 +00006089 pPage1 = pBt->pPage1;
drhb1299152010-03-30 22:58:33 +00006090 mxPage = btreePagecount(pBt);
drh113762a2014-11-19 16:36:25 +00006091 /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
6092 ** stores stores the total number of pages on the freelist. */
drh3aac2dd2004-04-26 14:10:20 +00006093 n = get4byte(&pPage1->aData[36]);
drhdf35a082009-07-09 02:24:35 +00006094 testcase( n==mxPage-1 );
danbf3cf572015-08-24 19:56:04 +00006095 if( ISCONCURRENT==0 && n>=mxPage ){
drh1662b5a2009-06-04 19:06:09 +00006096 return SQLITE_CORRUPT_BKPT;
6097 }
dan7b3d71e2015-08-19 20:27:05 +00006098
6099 /* Ensure page 1 is writable. This function will either change the number
6100 ** of pages in the free-list or the size of the database file. Since both
6101 ** of these operations involve modifying page 1 header fields, page 1
danbf3cf572015-08-24 19:56:04 +00006102 ** will definitely be written by this transaction. If this is an CONCURRENT
dan7b3d71e2015-08-19 20:27:05 +00006103 ** transaction, ensure the BtreePtrmap structure has been allocated. */
dan7b3d71e2015-08-19 20:27:05 +00006104 rc = sqlite3PagerWrite(pPage1->pDbPage);
6105 if( rc ) return rc;
6106
drh3aac2dd2004-04-26 14:10:20 +00006107 if( n>0 ){
drh91025292004-05-03 19:49:32 +00006108 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00006109 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006110 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
drhc6e956f2015-06-24 13:32:10 +00006111 u32 nSearch = 0; /* Count of the number of search attempts */
danielk1977cb1a7eb2004-11-05 12:27:02 +00006112
drh82e647d2013-03-02 03:25:55 +00006113 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00006114 ** shows that the page 'nearby' is somewhere on the free-list, then
6115 ** the entire-list will be searched for that page.
6116 */
dan51f0b6d2013-02-22 20:16:34 +00006117 if( eMode==BTALLOC_EXACT ){
danbf3cf572015-08-24 19:56:04 +00006118 assert( ISAUTOVACUUM!=ISCONCURRENT );
dan70af25d2015-08-21 17:57:16 +00006119 if( ISAUTOVACUUM ){
6120 if( nearby<=mxPage ){
6121 u8 eType;
6122 assert( nearby>0 );
6123 assert( pBt->autoVacuum );
6124 rc = ptrmapGet(pBt, nearby, &eType, 0);
6125 if( rc ) return rc;
6126 if( eType==PTRMAP_FREEPAGE ){
6127 searchList = 1;
6128 }
dan51f0b6d2013-02-22 20:16:34 +00006129 }
dan70af25d2015-08-21 17:57:16 +00006130 }else{
6131 searchList = 1;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006132 }
dan572a21c2015-08-21 18:55:22 +00006133 }else if( eMode==BTALLOC_LE ){
dan51f0b6d2013-02-22 20:16:34 +00006134 searchList = 1;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006135 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006136
6137 /* Decrement the free-list count by 1. Set iTrunk to the index of the
6138 ** first free-list trunk page. iPrevTrunk is initially 1.
6139 */
drh3aac2dd2004-04-26 14:10:20 +00006140 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00006141
6142 /* The code within this loop is run only once if the 'searchList' variable
6143 ** is not true. Otherwise, it runs once for each trunk-page on the
drh82e647d2013-03-02 03:25:55 +00006144 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
6145 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
danielk1977cb1a7eb2004-11-05 12:27:02 +00006146 */
6147 do {
6148 pPrevTrunk = pTrunk;
6149 if( pPrevTrunk ){
drh113762a2014-11-19 16:36:25 +00006150 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
6151 ** is the page number of the next freelist trunk page in the list or
6152 ** zero if this is the last freelist trunk page. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00006153 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00006154 }else{
drh113762a2014-11-19 16:36:25 +00006155 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
6156 ** stores the page number of the first page of the freelist, or zero if
6157 ** the freelist is empty. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00006158 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00006159 }
drhdf35a082009-07-09 02:24:35 +00006160 testcase( iTrunk==mxPage );
drh9e7804d2015-06-24 12:24:03 +00006161 if( iTrunk>mxPage || nSearch++ > n ){
drhc62aab52017-06-11 18:26:15 +00006162 rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
drh1662b5a2009-06-04 19:06:09 +00006163 }else{
drh7e8c6f12015-05-28 03:28:27 +00006164 rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
drh1662b5a2009-06-04 19:06:09 +00006165 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006166 if( rc ){
drhd3627af2006-12-18 18:34:51 +00006167 pTrunk = 0;
6168 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006169 }
drhb07028f2011-10-14 21:49:18 +00006170 assert( pTrunk!=0 );
6171 assert( pTrunk->aData!=0 );
drh113762a2014-11-19 16:36:25 +00006172 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
6173 ** is the number of leaf page pointers to follow. */
6174 k = get4byte(&pTrunk->aData[4]);
danielk1977cb1a7eb2004-11-05 12:27:02 +00006175 if( k==0 && !searchList ){
6176 /* The trunk has no leaves and the list is not being searched.
6177 ** So extract the trunk page itself and use it as the newly
6178 ** allocated page */
6179 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00006180 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00006181 if( rc ){
6182 goto end_allocate_page;
6183 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006184 *pPgno = iTrunk;
6185 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6186 *ppPage = pTrunk;
6187 pTrunk = 0;
6188 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh042d6a12009-06-17 13:57:16 +00006189 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00006190 /* Value of k is out of range. Database corruption */
drhcc97ca42017-06-07 22:32:59 +00006191 rc = SQLITE_CORRUPT_PGNO(iTrunk);
drhd3627af2006-12-18 18:34:51 +00006192 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006193#ifndef SQLITE_OMIT_AUTOVACUUM
dan51f0b6d2013-02-22 20:16:34 +00006194 }else if( searchList
6195 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
6196 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00006197 /* The list is being searched and this trunk page is the page
6198 ** to allocate, regardless of whether it has leaves.
6199 */
dan51f0b6d2013-02-22 20:16:34 +00006200 *pPgno = iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006201 *ppPage = pTrunk;
6202 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00006203 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00006204 if( rc ){
6205 goto end_allocate_page;
6206 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006207 if( k==0 ){
6208 if( !pPrevTrunk ){
6209 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6210 }else{
danf48c3552010-08-23 15:41:24 +00006211 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6212 if( rc!=SQLITE_OK ){
6213 goto end_allocate_page;
6214 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006215 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
6216 }
6217 }else{
6218 /* The trunk page is required by the caller but it contains
6219 ** pointers to free-list leaves. The first leaf becomes a trunk
6220 ** page in this case.
6221 */
6222 MemPage *pNewTrunk;
6223 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh1662b5a2009-06-04 19:06:09 +00006224 if( iNewTrunk>mxPage ){
drhcc97ca42017-06-07 22:32:59 +00006225 rc = SQLITE_CORRUPT_PGNO(iTrunk);
drh1662b5a2009-06-04 19:06:09 +00006226 goto end_allocate_page;
6227 }
drhdf35a082009-07-09 02:24:35 +00006228 testcase( iNewTrunk==mxPage );
drh7e8c6f12015-05-28 03:28:27 +00006229 rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00006230 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00006231 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006232 }
danielk19773b8a05f2007-03-19 17:44:26 +00006233 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00006234 if( rc!=SQLITE_OK ){
6235 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00006236 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006237 }
6238 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
6239 put4byte(&pNewTrunk->aData[4], k-1);
6240 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00006241 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00006242 if( !pPrevTrunk ){
drhc5053fb2008-11-27 02:22:10 +00006243 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
danielk1977cb1a7eb2004-11-05 12:27:02 +00006244 put4byte(&pPage1->aData[32], iNewTrunk);
6245 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00006246 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00006247 if( rc ){
6248 goto end_allocate_page;
6249 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006250 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
6251 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006252 }
6253 pTrunk = 0;
6254 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
6255#endif
danielk1977e5765212009-06-17 11:13:28 +00006256 }else if( k>0 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00006257 /* Extract a leaf from the trunk */
drh042d6a12009-06-17 13:57:16 +00006258 u32 closest;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006259 Pgno iPage;
6260 unsigned char *aData = pTrunk->aData;
6261 if( nearby>0 ){
drh042d6a12009-06-17 13:57:16 +00006262 u32 i;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006263 closest = 0;
danf38b65a2013-02-22 20:57:47 +00006264 if( eMode==BTALLOC_LE ){
6265 for(i=0; i<k; i++){
6266 iPage = get4byte(&aData[8+i*4]);
dan87ade192013-02-23 17:49:16 +00006267 if( iPage<=nearby ){
danf38b65a2013-02-22 20:57:47 +00006268 closest = i;
6269 break;
6270 }
6271 }
6272 }else{
6273 int dist;
6274 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
6275 for(i=1; i<k; i++){
6276 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
6277 if( d2<dist ){
6278 closest = i;
6279 dist = d2;
6280 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006281 }
6282 }
6283 }else{
6284 closest = 0;
6285 }
6286
6287 iPage = get4byte(&aData[8+closest*4]);
drhdf35a082009-07-09 02:24:35 +00006288 testcase( iPage==mxPage );
drh1662b5a2009-06-04 19:06:09 +00006289 if( iPage>mxPage ){
drhcc97ca42017-06-07 22:32:59 +00006290 rc = SQLITE_CORRUPT_PGNO(iTrunk);
drh1662b5a2009-06-04 19:06:09 +00006291 goto end_allocate_page;
6292 }
drhdf35a082009-07-09 02:24:35 +00006293 testcase( iPage==mxPage );
dan51f0b6d2013-02-22 20:16:34 +00006294 if( !searchList
6295 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
6296 ){
danielk1977bea2a942009-01-20 17:06:27 +00006297 int noContent;
shane1f9e6aa2008-06-09 19:27:11 +00006298 *pPgno = iPage;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006299 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
6300 ": %d more free pages\n",
6301 *pPgno, closest+1, k, pTrunk->pgno, n-1));
drh93b4fc72011-04-07 14:47:01 +00006302 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6303 if( rc ) goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006304 if( closest<k-1 ){
6305 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
6306 }
6307 put4byte(&aData[4], k-1);
drh3f387402014-09-24 01:23:00 +00006308 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
drh7e8c6f12015-05-28 03:28:27 +00006309 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
danielk1977cb1a7eb2004-11-05 12:27:02 +00006310 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00006311 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00006312 if( rc!=SQLITE_OK ){
6313 releasePage(*ppPage);
drh1c8bade2015-05-29 18:42:11 +00006314 *ppPage = 0;
danielk1977aac0a382005-01-16 11:07:06 +00006315 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006316 }
6317 searchList = 0;
6318 }
drhee696e22004-08-30 16:52:17 +00006319 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006320 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00006321 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006322 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00006323 }else{
danbc1a3c62013-02-23 16:40:46 +00006324 /* There are no pages on the freelist, so append a new page to the
6325 ** database image.
6326 **
6327 ** Normally, new pages allocated by this block can be requested from the
6328 ** pager layer with the 'no-content' flag set. This prevents the pager
6329 ** from trying to read the pages content from disk. However, if the
6330 ** current transaction has already run one or more incremental-vacuum
6331 ** steps, then the page we are about to allocate may contain content
6332 ** that is required in the event of a rollback. In this case, do
6333 ** not set the no-content flag. This causes the pager to load and journal
6334 ** the current page content before overwriting it.
6335 **
6336 ** Note that the pager will not actually attempt to load or journal
6337 ** content for any page that really does lie past the end of the database
6338 ** file on disk. So the effects of disabling the no-content optimization
6339 ** here are confined to those pages that lie between the end of the
6340 ** database image and the end of the database file.
6341 */
drh3f387402014-09-24 01:23:00 +00006342 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
danbc1a3c62013-02-23 16:40:46 +00006343
drhdd3cd972010-03-27 17:12:36 +00006344 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6345 if( rc ) return rc;
6346 pBt->nPage++;
6347 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
danielk1977bea2a942009-01-20 17:06:27 +00006348
danielk1977afcdd022004-10-31 16:25:42 +00006349#ifndef SQLITE_OMIT_AUTOVACUUM
drhdd3cd972010-03-27 17:12:36 +00006350 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
danielk1977afcdd022004-10-31 16:25:42 +00006351 /* If *pPgno refers to a pointer-map page, allocate two new pages
6352 ** at the end of the file instead of one. The first allocated page
6353 ** becomes a new pointer-map page, the second is used by the caller.
6354 */
danielk1977ac861692009-03-28 10:54:22 +00006355 MemPage *pPg = 0;
drhdd3cd972010-03-27 17:12:36 +00006356 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
6357 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
drh7e8c6f12015-05-28 03:28:27 +00006358 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
danielk1977ac861692009-03-28 10:54:22 +00006359 if( rc==SQLITE_OK ){
6360 rc = sqlite3PagerWrite(pPg->pDbPage);
6361 releasePage(pPg);
6362 }
6363 if( rc ) return rc;
drhdd3cd972010-03-27 17:12:36 +00006364 pBt->nPage++;
6365 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
danielk1977afcdd022004-10-31 16:25:42 +00006366 }
6367#endif
drhdd3cd972010-03-27 17:12:36 +00006368 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
6369 *pPgno = pBt->nPage;
danielk1977afcdd022004-10-31 16:25:42 +00006370
danielk1977599fcba2004-11-08 07:13:13 +00006371 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh7e8c6f12015-05-28 03:28:27 +00006372 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
drh3b7511c2001-05-26 13:15:44 +00006373 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00006374 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00006375 if( rc!=SQLITE_OK ){
6376 releasePage(*ppPage);
drh7e8c6f12015-05-28 03:28:27 +00006377 *ppPage = 0;
danielk1977aac0a382005-01-16 11:07:06 +00006378 }
drh3a4c1412004-05-09 20:40:11 +00006379 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00006380 }
danielk1977599fcba2004-11-08 07:13:13 +00006381
6382 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00006383
6384end_allocate_page:
6385 releasePage(pTrunk);
6386 releasePage(pPrevTrunk);
drh7e8c6f12015-05-28 03:28:27 +00006387 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
6388 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
drh3b7511c2001-05-26 13:15:44 +00006389 return rc;
6390}
6391
6392/*
danielk1977bea2a942009-01-20 17:06:27 +00006393** This function is used to add page iPage to the database file free-list.
6394** It is assumed that the page is not already a part of the free-list.
drh5e2f8b92001-05-28 00:41:15 +00006395**
danielk1977bea2a942009-01-20 17:06:27 +00006396** The value passed as the second argument to this function is optional.
6397** If the caller happens to have a pointer to the MemPage object
6398** corresponding to page iPage handy, it may pass it as the second value.
6399** Otherwise, it may pass NULL.
6400**
6401** If a pointer to a MemPage object is passed as the second argument,
6402** its reference count is not altered by this function.
drh3b7511c2001-05-26 13:15:44 +00006403*/
danielk1977bea2a942009-01-20 17:06:27 +00006404static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
6405 MemPage *pTrunk = 0; /* Free-list trunk page */
6406 Pgno iTrunk = 0; /* Page number of free-list trunk page */
6407 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
6408 MemPage *pPage; /* Page being freed. May be NULL. */
6409 int rc; /* Return Code */
6410 int nFree; /* Initial number of pages on free-list */
drh8b2f49b2001-06-08 00:21:52 +00006411
danielk1977bea2a942009-01-20 17:06:27 +00006412 assert( sqlite3_mutex_held(pBt->mutex) );
danfb0246b2015-05-26 12:18:17 +00006413 assert( CORRUPT_DB || iPage>1 );
danielk1977bea2a942009-01-20 17:06:27 +00006414 assert( !pMemPage || pMemPage->pgno==iPage );
6415
danfb0246b2015-05-26 12:18:17 +00006416 if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
danielk1977bea2a942009-01-20 17:06:27 +00006417 if( pMemPage ){
6418 pPage = pMemPage;
6419 sqlite3PagerRef(pPage->pDbPage);
6420 }else{
6421 pPage = btreePageLookup(pBt, iPage);
6422 }
drh3aac2dd2004-04-26 14:10:20 +00006423
drha34b6762004-05-07 13:30:42 +00006424 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00006425 rc = sqlite3PagerWrite(pPage1->pDbPage);
danielk1977bea2a942009-01-20 17:06:27 +00006426 if( rc ) goto freepage_out;
6427 nFree = get4byte(&pPage1->aData[36]);
6428 put4byte(&pPage1->aData[36], nFree+1);
drh3aac2dd2004-04-26 14:10:20 +00006429
drhc9166342012-01-05 23:32:06 +00006430 if( pBt->btsFlags & BTS_SECURE_DELETE ){
drh5b47efa2010-02-12 18:18:39 +00006431 /* If the secure_delete option is enabled, then
6432 ** always fully overwrite deleted information with zeros.
6433 */
drhb00fc3b2013-08-21 23:42:32 +00006434 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
shaneh84f4b2f2010-02-26 01:46:54 +00006435 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
drh5b47efa2010-02-12 18:18:39 +00006436 ){
6437 goto freepage_out;
6438 }
6439 memset(pPage->aData, 0, pPage->pBt->pageSize);
danielk1977bea2a942009-01-20 17:06:27 +00006440 }
drhfcce93f2006-02-22 03:08:32 +00006441
danielk1977687566d2004-11-02 12:56:41 +00006442 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00006443 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00006444 */
dan7b3d71e2015-08-19 20:27:05 +00006445 if( REQUIRE_PTRMAP ){
drh98add2e2009-07-20 17:11:49 +00006446 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
danielk1977bea2a942009-01-20 17:06:27 +00006447 if( rc ) goto freepage_out;
danielk1977687566d2004-11-02 12:56:41 +00006448 }
danielk1977687566d2004-11-02 12:56:41 +00006449
danielk1977bea2a942009-01-20 17:06:27 +00006450 /* Now manipulate the actual database free-list structure. There are two
6451 ** possibilities. If the free-list is currently empty, or if the first
6452 ** trunk page in the free-list is full, then this page will become a
6453 ** new free-list trunk page. Otherwise, it will become a leaf of the
6454 ** first trunk page in the current free-list. This block tests if it
6455 ** is possible to add the page as a new free-list leaf.
6456 */
6457 if( nFree!=0 ){
drhc046e3e2009-07-15 11:26:44 +00006458 u32 nLeaf; /* Initial number of leaf cells on trunk page */
danielk1977bea2a942009-01-20 17:06:27 +00006459
6460 iTrunk = get4byte(&pPage1->aData[32]);
drhb00fc3b2013-08-21 23:42:32 +00006461 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977bea2a942009-01-20 17:06:27 +00006462 if( rc!=SQLITE_OK ){
6463 goto freepage_out;
6464 }
6465
6466 nLeaf = get4byte(&pTrunk->aData[4]);
drheeb844a2009-08-08 18:01:07 +00006467 assert( pBt->usableSize>32 );
6468 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
danielk1977bea2a942009-01-20 17:06:27 +00006469 rc = SQLITE_CORRUPT_BKPT;
6470 goto freepage_out;
6471 }
drheeb844a2009-08-08 18:01:07 +00006472 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
danielk1977bea2a942009-01-20 17:06:27 +00006473 /* In this case there is room on the trunk page to insert the page
6474 ** being freed as a new leaf.
drh45b1fac2008-07-04 17:52:42 +00006475 **
6476 ** Note that the trunk page is not really full until it contains
6477 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
6478 ** coded. But due to a coding error in versions of SQLite prior to
6479 ** 3.6.0, databases with freelist trunk pages holding more than
6480 ** usableSize/4 - 8 entries will be reported as corrupt. In order
6481 ** to maintain backwards compatibility with older versions of SQLite,
drhc046e3e2009-07-15 11:26:44 +00006482 ** we will continue to restrict the number of entries to usableSize/4 - 8
drh45b1fac2008-07-04 17:52:42 +00006483 ** for now. At some point in the future (once everyone has upgraded
6484 ** to 3.6.0 or later) we should consider fixing the conditional above
6485 ** to read "usableSize/4-2" instead of "usableSize/4-8".
drh113762a2014-11-19 16:36:25 +00006486 **
6487 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
6488 ** avoid using the last six entries in the freelist trunk page array in
6489 ** order that database files created by newer versions of SQLite can be
6490 ** read by older versions of SQLite.
drh45b1fac2008-07-04 17:52:42 +00006491 */
danielk19773b8a05f2007-03-19 17:44:26 +00006492 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00006493 if( rc==SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00006494 put4byte(&pTrunk->aData[4], nLeaf+1);
6495 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
drhc9166342012-01-05 23:32:06 +00006496 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
danielk1977bea2a942009-01-20 17:06:27 +00006497 sqlite3PagerDontWrite(pPage->pDbPage);
6498 }
danielk1977bea2a942009-01-20 17:06:27 +00006499 rc = btreeSetHasContent(pBt, iPage);
drhf5345442007-04-09 12:45:02 +00006500 }
drh3a4c1412004-05-09 20:40:11 +00006501 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
danielk1977bea2a942009-01-20 17:06:27 +00006502 goto freepage_out;
drh3aac2dd2004-04-26 14:10:20 +00006503 }
drh3b7511c2001-05-26 13:15:44 +00006504 }
danielk1977bea2a942009-01-20 17:06:27 +00006505
6506 /* If control flows to this point, then it was not possible to add the
6507 ** the page being freed as a leaf page of the first trunk in the free-list.
6508 ** Possibly because the free-list is empty, or possibly because the
6509 ** first trunk in the free-list is full. Either way, the page being freed
6510 ** will become the new first trunk page in the free-list.
6511 */
drhb00fc3b2013-08-21 23:42:32 +00006512 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
drhc046e3e2009-07-15 11:26:44 +00006513 goto freepage_out;
6514 }
6515 rc = sqlite3PagerWrite(pPage->pDbPage);
6516 if( rc!=SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00006517 goto freepage_out;
6518 }
6519 put4byte(pPage->aData, iTrunk);
6520 put4byte(&pPage->aData[4], 0);
6521 put4byte(&pPage1->aData[32], iPage);
6522 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
6523
6524freepage_out:
6525 if( pPage ){
6526 pPage->isInit = 0;
6527 }
6528 releasePage(pPage);
6529 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00006530 return rc;
6531}
drhc314dc72009-07-21 11:52:34 +00006532static void freePage(MemPage *pPage, int *pRC){
6533 if( (*pRC)==SQLITE_OK ){
6534 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
6535 }
danielk1977bea2a942009-01-20 17:06:27 +00006536}
drh3b7511c2001-05-26 13:15:44 +00006537
6538/*
drh9bfdc252014-09-24 02:05:41 +00006539** Free any overflow pages associated with the given Cell. Write the
6540** local Cell size (the number of bytes on the original page, omitting
6541** overflow) into *pnSize.
drh3b7511c2001-05-26 13:15:44 +00006542*/
drh9bfdc252014-09-24 02:05:41 +00006543static int clearCell(
6544 MemPage *pPage, /* The page that contains the Cell */
6545 unsigned char *pCell, /* First byte of the Cell */
drh80159da2016-12-09 17:32:51 +00006546 CellInfo *pInfo /* Size information about the cell */
drh9bfdc252014-09-24 02:05:41 +00006547){
danielk1977aef0bf62005-12-30 16:28:01 +00006548 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00006549 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00006550 int rc;
drh94440812007-03-06 11:42:19 +00006551 int nOvfl;
shaneh1df2db72010-08-18 02:28:48 +00006552 u32 ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00006553
drh1fee73e2007-08-29 04:00:57 +00006554 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh80159da2016-12-09 17:32:51 +00006555 pPage->xParseCell(pPage, pCell, pInfo);
6556 if( pInfo->nLocal==pInfo->nPayload ){
drha34b6762004-05-07 13:30:42 +00006557 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00006558 }
drh80159da2016-12-09 17:32:51 +00006559 if( pCell+pInfo->nSize-1 > pPage->aData+pPage->maskPage ){
drhcc97ca42017-06-07 22:32:59 +00006560 /* Cell extends past end of page */
6561 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drhe42a9b42011-08-31 13:27:19 +00006562 }
drh80159da2016-12-09 17:32:51 +00006563 ovflPgno = get4byte(pCell + pInfo->nSize - 4);
shane63207ab2009-02-04 01:49:30 +00006564 assert( pBt->usableSize > 4 );
drh94440812007-03-06 11:42:19 +00006565 ovflPageSize = pBt->usableSize - 4;
drh80159da2016-12-09 17:32:51 +00006566 nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
dan0f8076d2015-05-25 18:47:26 +00006567 assert( nOvfl>0 ||
drh80159da2016-12-09 17:32:51 +00006568 (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
dan0f8076d2015-05-25 18:47:26 +00006569 );
drh72365832007-03-06 15:53:44 +00006570 while( nOvfl-- ){
shane63207ab2009-02-04 01:49:30 +00006571 Pgno iNext = 0;
danielk1977bea2a942009-01-20 17:06:27 +00006572 MemPage *pOvfl = 0;
drhb1299152010-03-30 22:58:33 +00006573 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
danielk1977e589a672009-04-11 16:06:15 +00006574 /* 0 is not a legal page number and page 1 cannot be an
6575 ** overflow page. Therefore if ovflPgno<2 or past the end of the
6576 ** file the database must be corrupt. */
drh49285702005-09-17 15:20:26 +00006577 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00006578 }
danielk1977bea2a942009-01-20 17:06:27 +00006579 if( nOvfl ){
6580 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
6581 if( rc ) return rc;
6582 }
dan887d4b22010-02-25 12:09:16 +00006583
shaneh1da207e2010-03-09 14:41:12 +00006584 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
dan887d4b22010-02-25 12:09:16 +00006585 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
6586 ){
6587 /* There is no reason any cursor should have an outstanding reference
6588 ** to an overflow page belonging to a cell that is being deleted/updated.
6589 ** So if there exists more than one reference to this page, then it
6590 ** must not really be an overflow page and the database must be corrupt.
6591 ** It is helpful to detect this before calling freePage2(), as
6592 ** freePage2() may zero the page contents if secure-delete mode is
6593 ** enabled. If this 'overflow' page happens to be a page that the
6594 ** caller is iterating through or using in some other way, this
6595 ** can be problematic.
6596 */
6597 rc = SQLITE_CORRUPT_BKPT;
6598 }else{
6599 rc = freePage2(pBt, pOvfl, ovflPgno);
6600 }
6601
danielk1977bea2a942009-01-20 17:06:27 +00006602 if( pOvfl ){
6603 sqlite3PagerUnref(pOvfl->pDbPage);
6604 }
drh3b7511c2001-05-26 13:15:44 +00006605 if( rc ) return rc;
danielk1977bea2a942009-01-20 17:06:27 +00006606 ovflPgno = iNext;
drh3b7511c2001-05-26 13:15:44 +00006607 }
drh5e2f8b92001-05-28 00:41:15 +00006608 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00006609}
6610
6611/*
drh91025292004-05-03 19:49:32 +00006612** Create the byte sequence used to represent a cell on page pPage
6613** and write that byte sequence into pCell[]. Overflow pages are
6614** allocated and filled in as necessary. The calling procedure
6615** is responsible for making sure sufficient space has been allocated
6616** for pCell[].
6617**
6618** Note that pCell does not necessary need to point to the pPage->aData
6619** area. pCell might point to some temporary storage. The cell will
6620** be constructed in this temporary area then copied into pPage->aData
6621** later.
drh3b7511c2001-05-26 13:15:44 +00006622*/
6623static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00006624 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00006625 unsigned char *pCell, /* Complete text of the cell */
drh8eeb4462016-05-21 20:03:42 +00006626 const BtreePayload *pX, /* Payload with which to construct the cell */
drh4b70f112004-05-02 21:12:19 +00006627 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00006628){
drh3b7511c2001-05-26 13:15:44 +00006629 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00006630 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00006631 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00006632 int spaceLeft;
6633 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00006634 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00006635 unsigned char *pPrior;
6636 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00006637 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00006638 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00006639 int nHeader;
drh3b7511c2001-05-26 13:15:44 +00006640
drh1fee73e2007-08-29 04:00:57 +00006641 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00006642
drhc5053fb2008-11-27 02:22:10 +00006643 /* pPage is not necessarily writeable since pCell might be auxiliary
6644 ** buffer space that is separate from the pPage buffer area */
6645 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
6646 || sqlite3PagerIswriteable(pPage->pDbPage) );
6647
drh91025292004-05-03 19:49:32 +00006648 /* Fill in the header. */
drh6200c882014-09-23 22:36:25 +00006649 nHeader = pPage->childPtrSize;
drh3aac2dd2004-04-26 14:10:20 +00006650 if( pPage->intKey ){
drhdfc2daa2016-05-21 23:25:29 +00006651 nPayload = pX->nData + pX->nZero;
6652 pSrc = pX->pData;
6653 nSrc = pX->nData;
6654 assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
drh3b7511c2001-05-26 13:15:44 +00006655 nHeader += putVarint32(&pCell[nHeader], nPayload);
drhdfc2daa2016-05-21 23:25:29 +00006656 nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
drh3b7511c2001-05-26 13:15:44 +00006657 }else{
drh8eeb4462016-05-21 20:03:42 +00006658 assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
6659 nSrc = nPayload = (int)pX->nKey;
6660 pSrc = pX->pKey;
drhdfc2daa2016-05-21 23:25:29 +00006661 nHeader += putVarint32(&pCell[nHeader], nPayload);
drh3aac2dd2004-04-26 14:10:20 +00006662 }
drhdfc2daa2016-05-21 23:25:29 +00006663
6664 /* Fill in the payload */
drh6200c882014-09-23 22:36:25 +00006665 if( nPayload<=pPage->maxLocal ){
6666 n = nHeader + nPayload;
6667 testcase( n==3 );
6668 testcase( n==4 );
6669 if( n<4 ) n = 4;
6670 *pnSize = n;
6671 spaceLeft = nPayload;
6672 pPrior = pCell;
6673 }else{
6674 int mn = pPage->minLocal;
6675 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
6676 testcase( n==pPage->maxLocal );
6677 testcase( n==pPage->maxLocal+1 );
6678 if( n > pPage->maxLocal ) n = mn;
6679 spaceLeft = n;
6680 *pnSize = n + nHeader + 4;
6681 pPrior = &pCell[nHeader+n];
6682 }
drh3aac2dd2004-04-26 14:10:20 +00006683 pPayload = &pCell[nHeader];
drh3b7511c2001-05-26 13:15:44 +00006684
drh6200c882014-09-23 22:36:25 +00006685 /* At this point variables should be set as follows:
6686 **
6687 ** nPayload Total payload size in bytes
6688 ** pPayload Begin writing payload here
6689 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
6690 ** that means content must spill into overflow pages.
6691 ** *pnSize Size of the local cell (not counting overflow pages)
6692 ** pPrior Where to write the pgno of the first overflow page
6693 **
6694 ** Use a call to btreeParseCellPtr() to verify that the values above
6695 ** were computed correctly.
6696 */
drhd879e3e2017-02-13 13:35:55 +00006697#ifdef SQLITE_DEBUG
drh6200c882014-09-23 22:36:25 +00006698 {
6699 CellInfo info;
drh5fa60512015-06-19 17:19:34 +00006700 pPage->xParseCell(pPage, pCell, &info);
drhcc5f8a42016-02-06 22:32:06 +00006701 assert( nHeader==(int)(info.pPayload - pCell) );
drh8eeb4462016-05-21 20:03:42 +00006702 assert( info.nKey==pX->nKey );
drh6200c882014-09-23 22:36:25 +00006703 assert( *pnSize == info.nSize );
6704 assert( spaceLeft == info.nLocal );
drh6200c882014-09-23 22:36:25 +00006705 }
6706#endif
6707
6708 /* Write the payload into the local Cell and any extra into overflow pages */
drh3b7511c2001-05-26 13:15:44 +00006709 while( nPayload>0 ){
6710 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00006711#ifndef SQLITE_OMIT_AUTOVACUUM
6712 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00006713 if( pBt->autoVacuum ){
6714 do{
6715 pgnoOvfl++;
6716 } while(
6717 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
6718 );
danielk1977b39f70b2007-05-17 18:28:11 +00006719 }
danielk1977afcdd022004-10-31 16:25:42 +00006720#endif
drhf49661a2008-12-10 16:45:50 +00006721 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
dan7b3d71e2015-08-19 20:27:05 +00006722
danielk1977a19df672004-11-03 11:37:07 +00006723 /* If the database supports auto-vacuum, and the second or subsequent
6724 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00006725 ** for that page now.
6726 **
6727 ** If this is the first overflow page, then write a partial entry
6728 ** to the pointer-map. If we write nothing to this pointer-map slot,
6729 ** then the optimistic overflow chain processing in clearCell()
mistachkin48864df2013-03-21 21:20:32 +00006730 ** may misinterpret the uninitialized values and delete the
danielk19774ef24492007-05-23 09:52:41 +00006731 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00006732 */
dan7b3d71e2015-08-19 20:27:05 +00006733 if( REQUIRE_PTRMAP && rc==SQLITE_OK ){
danielk19774ef24492007-05-23 09:52:41 +00006734 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
drh98add2e2009-07-20 17:11:49 +00006735 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
danielk197789a4be82007-05-23 13:34:32 +00006736 if( rc ){
6737 releasePage(pOvfl);
6738 }
danielk1977afcdd022004-10-31 16:25:42 +00006739 }
drh3b7511c2001-05-26 13:15:44 +00006740 if( rc ){
drh9b171272004-05-08 02:03:22 +00006741 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00006742 return rc;
6743 }
drhc5053fb2008-11-27 02:22:10 +00006744
6745 /* If pToRelease is not zero than pPrior points into the data area
6746 ** of pToRelease. Make sure pToRelease is still writeable. */
6747 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6748
6749 /* If pPrior is part of the data area of pPage, then make sure pPage
6750 ** is still writeable */
6751 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
6752 || sqlite3PagerIswriteable(pPage->pDbPage) );
6753
drh3aac2dd2004-04-26 14:10:20 +00006754 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00006755 releasePage(pToRelease);
6756 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00006757 pPrior = pOvfl->aData;
6758 put4byte(pPrior, 0);
6759 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00006760 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00006761 }
6762 n = nPayload;
6763 if( n>spaceLeft ) n = spaceLeft;
drhc5053fb2008-11-27 02:22:10 +00006764
6765 /* If pToRelease is not zero than pPayload points into the data area
6766 ** of pToRelease. Make sure pToRelease is still writeable. */
6767 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6768
6769 /* If pPayload is part of the data area of pPage, then make sure pPage
6770 ** is still writeable */
6771 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
6772 || sqlite3PagerIswriteable(pPage->pDbPage) );
6773
drhb026e052007-05-02 01:34:31 +00006774 if( nSrc>0 ){
6775 if( n>nSrc ) n = nSrc;
6776 assert( pSrc );
6777 memcpy(pPayload, pSrc, n);
6778 }else{
6779 memset(pPayload, 0, n);
6780 }
drh3b7511c2001-05-26 13:15:44 +00006781 nPayload -= n;
drhde647132004-05-07 17:57:49 +00006782 pPayload += n;
drh9b171272004-05-08 02:03:22 +00006783 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00006784 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00006785 spaceLeft -= n;
drhdd793422001-06-28 01:54:48 +00006786 }
drh9b171272004-05-08 02:03:22 +00006787 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00006788 return SQLITE_OK;
6789}
6790
drh14acc042001-06-10 19:56:58 +00006791/*
6792** Remove the i-th cell from pPage. This routine effects pPage only.
6793** The cell content is not freed or deallocated. It is assumed that
6794** the cell content has been copied someplace else. This routine just
6795** removes the reference to the cell from pPage.
6796**
6797** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00006798*/
drh98add2e2009-07-20 17:11:49 +00006799static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
drh43b18e12010-08-17 19:40:08 +00006800 u32 pc; /* Offset to cell content of cell being deleted */
drh43605152004-05-29 21:46:49 +00006801 u8 *data; /* pPage->aData */
6802 u8 *ptr; /* Used to move bytes around within data[] */
shanedcc50b72008-11-13 18:29:50 +00006803 int rc; /* The return code */
drhc314dc72009-07-21 11:52:34 +00006804 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
drh43605152004-05-29 21:46:49 +00006805
drh98add2e2009-07-20 17:11:49 +00006806 if( *pRC ) return;
drh8c42ca92001-06-22 19:15:00 +00006807 assert( idx>=0 && idx<pPage->nCell );
dan0f8076d2015-05-25 18:47:26 +00006808 assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00006809 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00006810 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00006811 data = pPage->aData;
drh3def2352011-11-11 00:27:15 +00006812 ptr = &pPage->aCellIdx[2*idx];
shane0af3f892008-11-12 04:55:34 +00006813 pc = get2byte(ptr);
drhc314dc72009-07-21 11:52:34 +00006814 hdr = pPage->hdrOffset;
6815 testcase( pc==get2byte(&data[hdr+5]) );
6816 testcase( pc+sz==pPage->pBt->usableSize );
drh43b18e12010-08-17 19:40:08 +00006817 if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
drh98add2e2009-07-20 17:11:49 +00006818 *pRC = SQLITE_CORRUPT_BKPT;
6819 return;
shane0af3f892008-11-12 04:55:34 +00006820 }
shanedcc50b72008-11-13 18:29:50 +00006821 rc = freeSpace(pPage, pc, sz);
drh98add2e2009-07-20 17:11:49 +00006822 if( rc ){
6823 *pRC = rc;
6824 return;
shanedcc50b72008-11-13 18:29:50 +00006825 }
drh14acc042001-06-10 19:56:58 +00006826 pPage->nCell--;
drhfdab0262014-11-20 15:30:50 +00006827 if( pPage->nCell==0 ){
6828 memset(&data[hdr+1], 0, 4);
6829 data[hdr+7] = 0;
6830 put2byte(&data[hdr+5], pPage->pBt->usableSize);
6831 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
6832 - pPage->childPtrSize - 8;
6833 }else{
6834 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
6835 put2byte(&data[hdr+3], pPage->nCell);
6836 pPage->nFree += 2;
6837 }
drh14acc042001-06-10 19:56:58 +00006838}
6839
6840/*
6841** Insert a new cell on pPage at cell index "i". pCell points to the
6842** content of the cell.
6843**
6844** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00006845** will not fit, then make a copy of the cell content into pTemp if
6846** pTemp is not null. Regardless of pTemp, allocate a new entry
drh2cbd78b2012-02-02 19:37:18 +00006847** in pPage->apOvfl[] and make it point to the cell content (either
drh43605152004-05-29 21:46:49 +00006848** in pTemp or the original pCell) and also record its index.
6849** Allocating a new entry in pPage->aCell[] implies that
6850** pPage->nOverflow is incremented.
drhcb89f4a2016-05-21 11:23:26 +00006851**
6852** *pRC must be SQLITE_OK when this routine is called.
drh14acc042001-06-10 19:56:58 +00006853*/
drh98add2e2009-07-20 17:11:49 +00006854static void insertCell(
drh24cd67e2004-05-10 16:18:47 +00006855 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00006856 int i, /* New cell becomes the i-th cell of the page */
6857 u8 *pCell, /* Content of the new cell */
6858 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00006859 u8 *pTemp, /* Temp storage space for pCell, if needed */
drh98add2e2009-07-20 17:11:49 +00006860 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
6861 int *pRC /* Read and write return code from here */
drh24cd67e2004-05-10 16:18:47 +00006862){
drh383d30f2010-02-26 13:07:37 +00006863 int idx = 0; /* Where to write new cell content in data[] */
drh43605152004-05-29 21:46:49 +00006864 int j; /* Loop counter */
drh43605152004-05-29 21:46:49 +00006865 u8 *data; /* The content of the whole page */
drh2c8fb922015-06-25 19:53:48 +00006866 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
danielk19774dbaa892009-06-16 16:50:22 +00006867
drhcb89f4a2016-05-21 11:23:26 +00006868 assert( *pRC==SQLITE_OK );
drh43605152004-05-29 21:46:49 +00006869 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
danf216e322014-08-14 19:53:37 +00006870 assert( MX_CELL(pPage->pBt)<=10921 );
6871 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
drh2cbd78b2012-02-02 19:37:18 +00006872 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
6873 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
drh1fee73e2007-08-29 04:00:57 +00006874 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc9b9b8a2009-12-03 21:26:52 +00006875 /* The cell should normally be sized correctly. However, when moving a
6876 ** malformed cell from a leaf page to an interior page, if the cell size
6877 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
6878 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
6879 ** the term after the || in the following assert(). */
drh25ada072015-06-19 15:07:14 +00006880 assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
drh43605152004-05-29 21:46:49 +00006881 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00006882 if( pTemp ){
drhd6176c42014-10-11 17:22:55 +00006883 memcpy(pTemp, pCell, sz);
drh43605152004-05-29 21:46:49 +00006884 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00006885 }
danielk19774dbaa892009-06-16 16:50:22 +00006886 if( iChild ){
6887 put4byte(pCell, iChild);
6888 }
drh43605152004-05-29 21:46:49 +00006889 j = pPage->nOverflow++;
drha2ee5892016-12-09 16:02:00 +00006890 /* Comparison against ArraySize-1 since we hold back one extra slot
6891 ** as a contingency. In other words, never need more than 3 overflow
6892 ** slots but 4 are allocated, just to be safe. */
6893 assert( j < ArraySize(pPage->apOvfl)-1 );
drh2cbd78b2012-02-02 19:37:18 +00006894 pPage->apOvfl[j] = pCell;
6895 pPage->aiOvfl[j] = (u16)i;
drhfe647dc2015-06-23 18:24:25 +00006896
6897 /* When multiple overflows occur, they are always sequential and in
6898 ** sorted order. This invariants arise because multiple overflows can
6899 ** only occur when inserting divider cells into the parent page during
6900 ** balancing, and the dividers are adjacent and sorted.
6901 */
6902 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
6903 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
drh14acc042001-06-10 19:56:58 +00006904 }else{
dan7b3d71e2015-08-19 20:27:05 +00006905 BtShared *pBt = pPage->pBt;
danielk19776e465eb2007-08-21 13:11:00 +00006906 int rc = sqlite3PagerWrite(pPage->pDbPage);
6907 if( rc!=SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00006908 *pRC = rc;
6909 return;
danielk19776e465eb2007-08-21 13:11:00 +00006910 }
6911 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00006912 data = pPage->aData;
drh2c8fb922015-06-25 19:53:48 +00006913 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
drh0a45c272009-07-08 01:49:11 +00006914 rc = allocateSpace(pPage, sz, &idx);
drh98add2e2009-07-20 17:11:49 +00006915 if( rc ){ *pRC = rc; return; }
drhcd8fb7c2015-06-02 14:02:18 +00006916 /* The allocateSpace() routine guarantees the following properties
6917 ** if it returns successfully */
drh2c8fb922015-06-25 19:53:48 +00006918 assert( idx >= 0 );
6919 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
dan7b3d71e2015-08-19 20:27:05 +00006920 assert( idx+sz <= (int)pBt->usableSize );
drh0a45c272009-07-08 01:49:11 +00006921 pPage->nFree -= (u16)(2 + sz);
drhd6176c42014-10-11 17:22:55 +00006922 memcpy(&data[idx], pCell, sz);
danielk19774dbaa892009-06-16 16:50:22 +00006923 if( iChild ){
6924 put4byte(&data[idx], iChild);
6925 }
drh2c8fb922015-06-25 19:53:48 +00006926 pIns = pPage->aCellIdx + i*2;
6927 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
6928 put2byte(pIns, idx);
6929 pPage->nCell++;
6930 /* increment the cell count */
6931 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
6932 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
dan7b3d71e2015-08-19 20:27:05 +00006933 if( REQUIRE_PTRMAP ){
danielk1977a19df672004-11-03 11:37:07 +00006934 /* The cell may contain a pointer to an overflow page. If so, write
6935 ** the entry for the overflow page into the pointer map.
6936 */
drh98add2e2009-07-20 17:11:49 +00006937 ptrmapPutOvflPtr(pPage, pCell, pRC);
danielk1977a19df672004-11-03 11:37:07 +00006938 }
drh14acc042001-06-10 19:56:58 +00006939 }
6940}
6941
6942/*
drh1ffd2472015-06-23 02:37:30 +00006943** A CellArray object contains a cache of pointers and sizes for a
drhc0d269e2016-08-03 14:51:16 +00006944** consecutive sequence of cells that might be held on multiple pages.
drh1ffd2472015-06-23 02:37:30 +00006945*/
6946typedef struct CellArray CellArray;
6947struct CellArray {
6948 int nCell; /* Number of cells in apCell[] */
6949 MemPage *pRef; /* Reference page */
6950 u8 **apCell; /* All cells begin balanced */
6951 u16 *szCell; /* Local size of all cells in apCell[] */
6952};
6953
6954/*
6955** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
6956** computed.
6957*/
6958static void populateCellCache(CellArray *p, int idx, int N){
6959 assert( idx>=0 && idx+N<=p->nCell );
6960 while( N>0 ){
6961 assert( p->apCell[idx]!=0 );
6962 if( p->szCell[idx]==0 ){
6963 p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
6964 }else{
6965 assert( CORRUPT_DB ||
6966 p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
6967 }
6968 idx++;
6969 N--;
6970 }
6971}
6972
6973/*
6974** Return the size of the Nth element of the cell array
6975*/
6976static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
6977 assert( N>=0 && N<p->nCell );
6978 assert( p->szCell[N]==0 );
6979 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
6980 return p->szCell[N];
6981}
6982static u16 cachedCellSize(CellArray *p, int N){
6983 assert( N>=0 && N<p->nCell );
6984 if( p->szCell[N] ) return p->szCell[N];
6985 return computeCellSize(p, N);
6986}
6987
6988/*
dan8e9ba0c2014-10-14 17:27:04 +00006989** Array apCell[] contains pointers to nCell b-tree page cells. The
6990** szCell[] array contains the size in bytes of each cell. This function
6991** replaces the current contents of page pPg with the contents of the cell
6992** array.
6993**
6994** Some of the cells in apCell[] may currently be stored in pPg. This
6995** function works around problems caused by this by making a copy of any
6996** such cells before overwriting the page data.
6997**
6998** The MemPage.nFree field is invalidated by this function. It is the
6999** responsibility of the caller to set it correctly.
drhfa1a98a2004-05-14 19:08:17 +00007000*/
drh658873b2015-06-22 20:02:04 +00007001static int rebuildPage(
dan33ea4862014-10-09 19:35:37 +00007002 MemPage *pPg, /* Edit this page */
dan33ea4862014-10-09 19:35:37 +00007003 int nCell, /* Final number of cells on page */
dan09c68402014-10-11 20:00:24 +00007004 u8 **apCell, /* Array of cells */
7005 u16 *szCell /* Array of cell sizes */
dan33ea4862014-10-09 19:35:37 +00007006){
7007 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
7008 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
7009 const int usableSize = pPg->pBt->usableSize;
7010 u8 * const pEnd = &aData[usableSize];
7011 int i;
7012 u8 *pCellptr = pPg->aCellIdx;
7013 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7014 u8 *pData;
7015
7016 i = get2byte(&aData[hdr+5]);
7017 memcpy(&pTmp[i], &aData[i], usableSize - i);
dan33ea4862014-10-09 19:35:37 +00007018
dan8e9ba0c2014-10-14 17:27:04 +00007019 pData = pEnd;
dan33ea4862014-10-09 19:35:37 +00007020 for(i=0; i<nCell; i++){
7021 u8 *pCell = apCell[i];
drh8b0ba7b2015-12-16 13:07:35 +00007022 if( SQLITE_WITHIN(pCell,aData,pEnd) ){
dan33ea4862014-10-09 19:35:37 +00007023 pCell = &pTmp[pCell - aData];
7024 }
7025 pData -= szCell[i];
dan33ea4862014-10-09 19:35:37 +00007026 put2byte(pCellptr, (pData - aData));
7027 pCellptr += 2;
drh658873b2015-06-22 20:02:04 +00007028 if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
7029 memcpy(pData, pCell, szCell[i]);
drh25ada072015-06-19 15:07:14 +00007030 assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
drhea82b372015-06-23 21:35:28 +00007031 testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
dan33ea4862014-10-09 19:35:37 +00007032 }
7033
dand7b545b2014-10-13 18:03:27 +00007034 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
dan33ea4862014-10-09 19:35:37 +00007035 pPg->nCell = nCell;
7036 pPg->nOverflow = 0;
7037
7038 put2byte(&aData[hdr+1], 0);
7039 put2byte(&aData[hdr+3], pPg->nCell);
7040 put2byte(&aData[hdr+5], pData - aData);
7041 aData[hdr+7] = 0x00;
drh658873b2015-06-22 20:02:04 +00007042 return SQLITE_OK;
dan33ea4862014-10-09 19:35:37 +00007043}
7044
dan8e9ba0c2014-10-14 17:27:04 +00007045/*
7046** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
7047** contains the size in bytes of each such cell. This function attempts to
7048** add the cells stored in the array to page pPg. If it cannot (because
7049** the page needs to be defragmented before the cells will fit), non-zero
7050** is returned. Otherwise, if the cells are added successfully, zero is
7051** returned.
7052**
7053** Argument pCellptr points to the first entry in the cell-pointer array
7054** (part of page pPg) to populate. After cell apCell[0] is written to the
7055** page body, a 16-bit offset is written to pCellptr. And so on, for each
7056** cell in the array. It is the responsibility of the caller to ensure
7057** that it is safe to overwrite this part of the cell-pointer array.
7058**
7059** When this function is called, *ppData points to the start of the
7060** content area on page pPg. If the size of the content area is extended,
7061** *ppData is updated to point to the new start of the content area
7062** before returning.
7063**
7064** Finally, argument pBegin points to the byte immediately following the
7065** end of the space required by this page for the cell-pointer area (for
7066** all cells - not just those inserted by the current call). If the content
7067** area must be extended to before this point in order to accomodate all
7068** cells in apCell[], then the cells do not fit and non-zero is returned.
7069*/
dand7b545b2014-10-13 18:03:27 +00007070static int pageInsertArray(
dan8e9ba0c2014-10-14 17:27:04 +00007071 MemPage *pPg, /* Page to add cells to */
7072 u8 *pBegin, /* End of cell-pointer array */
7073 u8 **ppData, /* IN/OUT: Page content -area pointer */
7074 u8 *pCellptr, /* Pointer to cell-pointer area */
drhf7838932015-06-23 15:36:34 +00007075 int iFirst, /* Index of first cell to add */
dan8e9ba0c2014-10-14 17:27:04 +00007076 int nCell, /* Number of cells to add to pPg */
drhf7838932015-06-23 15:36:34 +00007077 CellArray *pCArray /* Array of cells */
dand7b545b2014-10-13 18:03:27 +00007078){
7079 int i;
7080 u8 *aData = pPg->aData;
7081 u8 *pData = *ppData;
drhf7838932015-06-23 15:36:34 +00007082 int iEnd = iFirst + nCell;
dan23eba452014-10-24 18:43:57 +00007083 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
drhf7838932015-06-23 15:36:34 +00007084 for(i=iFirst; i<iEnd; i++){
7085 int sz, rc;
dand7b545b2014-10-13 18:03:27 +00007086 u8 *pSlot;
drhf7838932015-06-23 15:36:34 +00007087 sz = cachedCellSize(pCArray, i);
drhb7580e82015-06-25 18:36:13 +00007088 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
drhcca66982016-04-05 13:19:19 +00007089 if( (pData - pBegin)<sz ) return 1;
dand7b545b2014-10-13 18:03:27 +00007090 pData -= sz;
dand7b545b2014-10-13 18:03:27 +00007091 pSlot = pData;
7092 }
drh48310f82015-10-10 16:41:28 +00007093 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
7094 ** database. But they might for a corrupt database. Hence use memmove()
7095 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
7096 assert( (pSlot+sz)<=pCArray->apCell[i]
7097 || pSlot>=(pCArray->apCell[i]+sz)
7098 || CORRUPT_DB );
7099 memmove(pSlot, pCArray->apCell[i], sz);
dand7b545b2014-10-13 18:03:27 +00007100 put2byte(pCellptr, (pSlot - aData));
7101 pCellptr += 2;
7102 }
7103 *ppData = pData;
7104 return 0;
7105}
7106
dan8e9ba0c2014-10-14 17:27:04 +00007107/*
7108** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
7109** contains the size in bytes of each such cell. This function adds the
7110** space associated with each cell in the array that is currently stored
7111** within the body of pPg to the pPg free-list. The cell-pointers and other
7112** fields of the page are not updated.
7113**
7114** This function returns the total number of cells added to the free-list.
7115*/
dand7b545b2014-10-13 18:03:27 +00007116static int pageFreeArray(
7117 MemPage *pPg, /* Page to edit */
drhf7838932015-06-23 15:36:34 +00007118 int iFirst, /* First cell to delete */
dand7b545b2014-10-13 18:03:27 +00007119 int nCell, /* Cells to delete */
drhf7838932015-06-23 15:36:34 +00007120 CellArray *pCArray /* Array of cells */
dand7b545b2014-10-13 18:03:27 +00007121){
7122 u8 * const aData = pPg->aData;
7123 u8 * const pEnd = &aData[pPg->pBt->usableSize];
dan89ca0b32014-10-25 20:36:28 +00007124 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
dand7b545b2014-10-13 18:03:27 +00007125 int nRet = 0;
7126 int i;
drhf7838932015-06-23 15:36:34 +00007127 int iEnd = iFirst + nCell;
dand7b545b2014-10-13 18:03:27 +00007128 u8 *pFree = 0;
7129 int szFree = 0;
7130
drhf7838932015-06-23 15:36:34 +00007131 for(i=iFirst; i<iEnd; i++){
7132 u8 *pCell = pCArray->apCell[i];
drh8b0ba7b2015-12-16 13:07:35 +00007133 if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
drhf7838932015-06-23 15:36:34 +00007134 int sz;
7135 /* No need to use cachedCellSize() here. The sizes of all cells that
7136 ** are to be freed have already been computing while deciding which
7137 ** cells need freeing */
7138 sz = pCArray->szCell[i]; assert( sz>0 );
dand7b545b2014-10-13 18:03:27 +00007139 if( pFree!=(pCell + sz) ){
drhfefa0942014-11-05 21:21:08 +00007140 if( pFree ){
7141 assert( pFree>aData && (pFree - aData)<65536 );
7142 freeSpace(pPg, (u16)(pFree - aData), szFree);
7143 }
dand7b545b2014-10-13 18:03:27 +00007144 pFree = pCell;
7145 szFree = sz;
dan89ca0b32014-10-25 20:36:28 +00007146 if( pFree+sz>pEnd ) return 0;
dand7b545b2014-10-13 18:03:27 +00007147 }else{
7148 pFree = pCell;
7149 szFree += sz;
7150 }
7151 nRet++;
7152 }
7153 }
drhfefa0942014-11-05 21:21:08 +00007154 if( pFree ){
7155 assert( pFree>aData && (pFree - aData)<65536 );
7156 freeSpace(pPg, (u16)(pFree - aData), szFree);
7157 }
dand7b545b2014-10-13 18:03:27 +00007158 return nRet;
7159}
7160
dand7b545b2014-10-13 18:03:27 +00007161/*
drh5ab63772014-11-27 03:46:04 +00007162** apCell[] and szCell[] contains pointers to and sizes of all cells in the
7163** pages being balanced. The current page, pPg, has pPg->nCell cells starting
7164** with apCell[iOld]. After balancing, this page should hold nNew cells
7165** starting at apCell[iNew].
7166**
7167** This routine makes the necessary adjustments to pPg so that it contains
7168** the correct cells after being balanced.
7169**
dand7b545b2014-10-13 18:03:27 +00007170** The pPg->nFree field is invalid when this function returns. It is the
7171** responsibility of the caller to set it correctly.
7172*/
drh658873b2015-06-22 20:02:04 +00007173static int editPage(
dan09c68402014-10-11 20:00:24 +00007174 MemPage *pPg, /* Edit this page */
7175 int iOld, /* Index of first cell currently on page */
7176 int iNew, /* Index of new first cell on page */
7177 int nNew, /* Final number of cells on page */
drh1ffd2472015-06-23 02:37:30 +00007178 CellArray *pCArray /* Array of cells and sizes */
dan09c68402014-10-11 20:00:24 +00007179){
dand7b545b2014-10-13 18:03:27 +00007180 u8 * const aData = pPg->aData;
7181 const int hdr = pPg->hdrOffset;
7182 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
7183 int nCell = pPg->nCell; /* Cells stored on pPg */
7184 u8 *pData;
7185 u8 *pCellptr;
7186 int i;
7187 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
7188 int iNewEnd = iNew + nNew;
dan09c68402014-10-11 20:00:24 +00007189
7190#ifdef SQLITE_DEBUG
dand7b545b2014-10-13 18:03:27 +00007191 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7192 memcpy(pTmp, aData, pPg->pBt->usableSize);
dan09c68402014-10-11 20:00:24 +00007193#endif
7194
dand7b545b2014-10-13 18:03:27 +00007195 /* Remove cells from the start and end of the page */
7196 if( iOld<iNew ){
drhf7838932015-06-23 15:36:34 +00007197 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
dand7b545b2014-10-13 18:03:27 +00007198 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
7199 nCell -= nShift;
7200 }
7201 if( iNewEnd < iOldEnd ){
drhf7838932015-06-23 15:36:34 +00007202 nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
dand7b545b2014-10-13 18:03:27 +00007203 }
dan09c68402014-10-11 20:00:24 +00007204
drh5ab63772014-11-27 03:46:04 +00007205 pData = &aData[get2byteNotZero(&aData[hdr+5])];
dand7b545b2014-10-13 18:03:27 +00007206 if( pData<pBegin ) goto editpage_fail;
7207
7208 /* Add cells to the start of the page */
7209 if( iNew<iOld ){
drh5ab63772014-11-27 03:46:04 +00007210 int nAdd = MIN(nNew,iOld-iNew);
7211 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
dand7b545b2014-10-13 18:03:27 +00007212 pCellptr = pPg->aCellIdx;
7213 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
7214 if( pageInsertArray(
7215 pPg, pBegin, &pData, pCellptr,
drhf7838932015-06-23 15:36:34 +00007216 iNew, nAdd, pCArray
dand7b545b2014-10-13 18:03:27 +00007217 ) ) goto editpage_fail;
7218 nCell += nAdd;
7219 }
7220
7221 /* Add any overflow cells */
7222 for(i=0; i<pPg->nOverflow; i++){
7223 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
7224 if( iCell>=0 && iCell<nNew ){
drhfefa0942014-11-05 21:21:08 +00007225 pCellptr = &pPg->aCellIdx[iCell * 2];
dand7b545b2014-10-13 18:03:27 +00007226 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
7227 nCell++;
7228 if( pageInsertArray(
7229 pPg, pBegin, &pData, pCellptr,
drhf7838932015-06-23 15:36:34 +00007230 iCell+iNew, 1, pCArray
dand7b545b2014-10-13 18:03:27 +00007231 ) ) goto editpage_fail;
dan09c68402014-10-11 20:00:24 +00007232 }
dand7b545b2014-10-13 18:03:27 +00007233 }
dan09c68402014-10-11 20:00:24 +00007234
dand7b545b2014-10-13 18:03:27 +00007235 /* Append cells to the end of the page */
7236 pCellptr = &pPg->aCellIdx[nCell*2];
7237 if( pageInsertArray(
7238 pPg, pBegin, &pData, pCellptr,
drhf7838932015-06-23 15:36:34 +00007239 iNew+nCell, nNew-nCell, pCArray
dand7b545b2014-10-13 18:03:27 +00007240 ) ) goto editpage_fail;
dan09c68402014-10-11 20:00:24 +00007241
dand7b545b2014-10-13 18:03:27 +00007242 pPg->nCell = nNew;
7243 pPg->nOverflow = 0;
dan09c68402014-10-11 20:00:24 +00007244
dand7b545b2014-10-13 18:03:27 +00007245 put2byte(&aData[hdr+3], pPg->nCell);
7246 put2byte(&aData[hdr+5], pData - aData);
dan09c68402014-10-11 20:00:24 +00007247
7248#ifdef SQLITE_DEBUG
dan23eba452014-10-24 18:43:57 +00007249 for(i=0; i<nNew && !CORRUPT_DB; i++){
drh1ffd2472015-06-23 02:37:30 +00007250 u8 *pCell = pCArray->apCell[i+iNew];
drh329428e2015-06-30 13:28:18 +00007251 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
drh1c715f62016-04-05 13:35:43 +00007252 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
dand7b545b2014-10-13 18:03:27 +00007253 pCell = &pTmp[pCell - aData];
dan09c68402014-10-11 20:00:24 +00007254 }
drh1ffd2472015-06-23 02:37:30 +00007255 assert( 0==memcmp(pCell, &aData[iOff],
7256 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
dand7b545b2014-10-13 18:03:27 +00007257 }
dan09c68402014-10-11 20:00:24 +00007258#endif
7259
drh658873b2015-06-22 20:02:04 +00007260 return SQLITE_OK;
dan09c68402014-10-11 20:00:24 +00007261 editpage_fail:
dan09c68402014-10-11 20:00:24 +00007262 /* Unable to edit this page. Rebuild it from scratch instead. */
drh1ffd2472015-06-23 02:37:30 +00007263 populateCellCache(pCArray, iNew, nNew);
7264 return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
dan09c68402014-10-11 20:00:24 +00007265}
7266
drh14acc042001-06-10 19:56:58 +00007267/*
drhc3b70572003-01-04 19:44:07 +00007268** The following parameters determine how many adjacent pages get involved
7269** in a balancing operation. NN is the number of neighbors on either side
7270** of the page that participate in the balancing operation. NB is the
7271** total number of pages that participate, including the target page and
7272** NN neighbors on either side.
7273**
7274** The minimum value of NN is 1 (of course). Increasing NN above 1
7275** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
7276** in exchange for a larger degradation in INSERT and UPDATE performance.
7277** The value of NN appears to give the best results overall.
7278*/
7279#define NN 1 /* Number of neighbors on either side of pPage */
7280#define NB (NN*2+1) /* Total pages involved in the balance */
7281
danielk1977ac245ec2005-01-14 13:50:11 +00007282
drh615ae552005-01-16 23:21:00 +00007283#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00007284/*
7285** This version of balance() handles the common special case where
7286** a new entry is being inserted on the extreme right-end of the
7287** tree, in other words, when the new entry will become the largest
7288** entry in the tree.
7289**
drhc314dc72009-07-21 11:52:34 +00007290** Instead of trying to balance the 3 right-most leaf pages, just add
drhf222e712005-01-14 22:55:49 +00007291** a new page to the right-hand side and put the one new entry in
7292** that page. This leaves the right side of the tree somewhat
7293** unbalanced. But odds are that we will be inserting new entries
7294** at the end soon afterwards so the nearly empty page will quickly
7295** fill up. On average.
7296**
7297** pPage is the leaf page which is the right-most page in the tree.
7298** pParent is its parent. pPage must have a single overflow entry
7299** which is also the right-most entry on the page.
danielk1977a50d9aa2009-06-08 14:49:45 +00007300**
7301** The pSpace buffer is used to store a temporary copy of the divider
7302** cell that will be inserted into pParent. Such a cell consists of a 4
7303** byte page number followed by a variable length integer. In other
7304** words, at most 13 bytes. Hence the pSpace buffer must be at
7305** least 13 bytes in size.
drhf222e712005-01-14 22:55:49 +00007306*/
danielk1977a50d9aa2009-06-08 14:49:45 +00007307static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
7308 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
danielk19774dbaa892009-06-16 16:50:22 +00007309 MemPage *pNew; /* Newly allocated page */
danielk19776f235cc2009-06-04 14:46:08 +00007310 int rc; /* Return Code */
7311 Pgno pgnoNew; /* Page number of pNew */
danielk1977ac245ec2005-01-14 13:50:11 +00007312
drh1fee73e2007-08-29 04:00:57 +00007313 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk1977a50d9aa2009-06-08 14:49:45 +00007314 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00007315 assert( pPage->nOverflow==1 );
7316
drh5d433ce2010-08-14 16:02:52 +00007317 /* This error condition is now caught prior to reaching this function */
drh1fd2d7d2014-12-02 16:16:47 +00007318 if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
drhd677b3d2007-08-20 22:48:41 +00007319
danielk1977a50d9aa2009-06-08 14:49:45 +00007320 /* Allocate a new page. This page will become the right-sibling of
7321 ** pPage. Make the parent page writable, so that the new divider cell
7322 ** may be inserted. If both these operations are successful, proceed.
7323 */
drh4f0c5872007-03-26 22:05:01 +00007324 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk19774dbaa892009-06-16 16:50:22 +00007325
danielk1977eaa06f62008-09-18 17:34:44 +00007326 if( rc==SQLITE_OK ){
danielk1977a50d9aa2009-06-08 14:49:45 +00007327
7328 u8 *pOut = &pSpace[4];
drh2cbd78b2012-02-02 19:37:18 +00007329 u8 *pCell = pPage->apOvfl[0];
drh25ada072015-06-19 15:07:14 +00007330 u16 szCell = pPage->xCellSize(pPage, pCell);
danielk19776f235cc2009-06-04 14:46:08 +00007331 u8 *pStop;
7332
drhc5053fb2008-11-27 02:22:10 +00007333 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00007334 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
7335 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
drh658873b2015-06-22 20:02:04 +00007336 rc = rebuildPage(pNew, 1, &pCell, &szCell);
drhea82b372015-06-23 21:35:28 +00007337 if( NEVER(rc) ) return rc;
dan8e9ba0c2014-10-14 17:27:04 +00007338 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
danielk19774dbaa892009-06-16 16:50:22 +00007339
7340 /* If this is an auto-vacuum database, update the pointer map
7341 ** with entries for the new page, and any pointer from the
7342 ** cell on the page to an overflow page. If either of these
7343 ** operations fails, the return code is set, but the contents
7344 ** of the parent page are still manipulated by thh code below.
7345 ** That is Ok, at this point the parent page is guaranteed to
7346 ** be marked as dirty. Returning an error code will cause a
7347 ** rollback, undoing any changes made to the parent page.
7348 */
dan7b3d71e2015-08-19 20:27:05 +00007349 if( REQUIRE_PTRMAP ){
drh98add2e2009-07-20 17:11:49 +00007350 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
7351 if( szCell>pNew->minLocal ){
7352 ptrmapPutOvflPtr(pNew, pCell, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00007353 }
7354 }
danielk1977eaa06f62008-09-18 17:34:44 +00007355
danielk19776f235cc2009-06-04 14:46:08 +00007356 /* Create a divider cell to insert into pParent. The divider cell
7357 ** consists of a 4-byte page number (the page number of pPage) and
7358 ** a variable length key value (which must be the same value as the
7359 ** largest key on pPage).
danielk1977eaa06f62008-09-18 17:34:44 +00007360 **
danielk19776f235cc2009-06-04 14:46:08 +00007361 ** To find the largest key value on pPage, first find the right-most
7362 ** cell on pPage. The first two fields of this cell are the
7363 ** record-length (a variable length integer at most 32-bits in size)
7364 ** and the key value (a variable length integer, may have any value).
7365 ** The first of the while(...) loops below skips over the record-length
7366 ** field. The second while(...) loop copies the key value from the
danielk1977a50d9aa2009-06-08 14:49:45 +00007367 ** cell on pPage into the pSpace buffer.
danielk1977eaa06f62008-09-18 17:34:44 +00007368 */
danielk1977eaa06f62008-09-18 17:34:44 +00007369 pCell = findCell(pPage, pPage->nCell-1);
danielk19776f235cc2009-06-04 14:46:08 +00007370 pStop = &pCell[9];
7371 while( (*(pCell++)&0x80) && pCell<pStop );
7372 pStop = &pCell[9];
7373 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
7374
danielk19774dbaa892009-06-16 16:50:22 +00007375 /* Insert the new divider cell into pParent. */
drhcb89f4a2016-05-21 11:23:26 +00007376 if( rc==SQLITE_OK ){
7377 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
7378 0, pPage->pgno, &rc);
7379 }
danielk19776f235cc2009-06-04 14:46:08 +00007380
7381 /* Set the right-child pointer of pParent to point to the new page. */
danielk1977eaa06f62008-09-18 17:34:44 +00007382 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
7383
danielk1977e08a3c42008-09-18 18:17:03 +00007384 /* Release the reference to the new page. */
7385 releasePage(pNew);
danielk1977ac11ee62005-01-15 12:45:51 +00007386 }
7387
danielk1977eaa06f62008-09-18 17:34:44 +00007388 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00007389}
drh615ae552005-01-16 23:21:00 +00007390#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00007391
dane6593d82014-10-24 16:40:49 +00007392#if 0
drhc3b70572003-01-04 19:44:07 +00007393/*
danielk19774dbaa892009-06-16 16:50:22 +00007394** This function does not contribute anything to the operation of SQLite.
7395** it is sometimes activated temporarily while debugging code responsible
7396** for setting pointer-map entries.
7397*/
7398static int ptrmapCheckPages(MemPage **apPage, int nPage){
7399 int i, j;
7400 for(i=0; i<nPage; i++){
7401 Pgno n;
7402 u8 e;
7403 MemPage *pPage = apPage[i];
7404 BtShared *pBt = pPage->pBt;
7405 assert( pPage->isInit );
7406
7407 for(j=0; j<pPage->nCell; j++){
7408 CellInfo info;
7409 u8 *z;
7410
7411 z = findCell(pPage, j);
drh5fa60512015-06-19 17:19:34 +00007412 pPage->xParseCell(pPage, z, &info);
drh45ac1c72015-12-18 03:59:16 +00007413 if( info.nLocal<info.nPayload ){
7414 Pgno ovfl = get4byte(&z[info.nSize-4]);
danielk19774dbaa892009-06-16 16:50:22 +00007415 ptrmapGet(pBt, ovfl, &e, &n);
7416 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
7417 }
7418 if( !pPage->leaf ){
7419 Pgno child = get4byte(z);
7420 ptrmapGet(pBt, child, &e, &n);
7421 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7422 }
7423 }
7424 if( !pPage->leaf ){
7425 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7426 ptrmapGet(pBt, child, &e, &n);
7427 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7428 }
7429 }
7430 return 1;
7431}
7432#endif
7433
danielk1977cd581a72009-06-23 15:43:39 +00007434/*
7435** This function is used to copy the contents of the b-tree node stored
7436** on page pFrom to page pTo. If page pFrom was not a leaf page, then
7437** the pointer-map entries for each child page are updated so that the
7438** parent page stored in the pointer map is page pTo. If pFrom contained
7439** any cells with overflow page pointers, then the corresponding pointer
7440** map entries are also updated so that the parent page is page pTo.
7441**
7442** If pFrom is currently carrying any overflow cells (entries in the
drh2cbd78b2012-02-02 19:37:18 +00007443** MemPage.apOvfl[] array), they are not copied to pTo.
danielk1977cd581a72009-06-23 15:43:39 +00007444**
danielk197730548662009-07-09 05:07:37 +00007445** Before returning, page pTo is reinitialized using btreeInitPage().
danielk1977cd581a72009-06-23 15:43:39 +00007446**
7447** The performance of this function is not critical. It is only used by
7448** the balance_shallower() and balance_deeper() procedures, neither of
7449** which are called often under normal circumstances.
7450*/
drhc314dc72009-07-21 11:52:34 +00007451static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
7452 if( (*pRC)==SQLITE_OK ){
7453 BtShared * const pBt = pFrom->pBt;
7454 u8 * const aFrom = pFrom->aData;
7455 u8 * const aTo = pTo->aData;
7456 int const iFromHdr = pFrom->hdrOffset;
7457 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
drhdc9b5f82009-12-05 18:34:08 +00007458 int rc;
drhc314dc72009-07-21 11:52:34 +00007459 int iData;
7460
7461
7462 assert( pFrom->isInit );
7463 assert( pFrom->nFree>=iToHdr );
drhfcd71b62011-04-05 22:08:24 +00007464 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
drhc314dc72009-07-21 11:52:34 +00007465
7466 /* Copy the b-tree node content from page pFrom to page pTo. */
7467 iData = get2byte(&aFrom[iFromHdr+5]);
7468 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
7469 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
7470
7471 /* Reinitialize page pTo so that the contents of the MemPage structure
dan89e060e2009-12-05 18:03:50 +00007472 ** match the new data. The initialization of pTo can actually fail under
7473 ** fairly obscure circumstances, even though it is a copy of initialized
7474 ** page pFrom.
7475 */
drhc314dc72009-07-21 11:52:34 +00007476 pTo->isInit = 0;
dan89e060e2009-12-05 18:03:50 +00007477 rc = btreeInitPage(pTo);
7478 if( rc!=SQLITE_OK ){
7479 *pRC = rc;
7480 return;
7481 }
drhc314dc72009-07-21 11:52:34 +00007482
7483 /* If this is an auto-vacuum database, update the pointer-map entries
7484 ** for any b-tree or overflow pages that pTo now contains the pointers to.
7485 */
dan7b3d71e2015-08-19 20:27:05 +00007486 if( REQUIRE_PTRMAP ){
drhc314dc72009-07-21 11:52:34 +00007487 *pRC = setChildPtrmaps(pTo);
7488 }
danielk1977cd581a72009-06-23 15:43:39 +00007489 }
danielk1977cd581a72009-06-23 15:43:39 +00007490}
7491
7492/*
danielk19774dbaa892009-06-16 16:50:22 +00007493** This routine redistributes cells on the iParentIdx'th child of pParent
7494** (hereafter "the page") and up to 2 siblings so that all pages have about the
7495** same amount of free space. Usually a single sibling on either side of the
7496** page are used in the balancing, though both siblings might come from one
7497** side if the page is the first or last child of its parent. If the page
7498** has fewer than 2 siblings (something which can only happen if the page
7499** is a root page or a child of a root page) then all available siblings
7500** participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00007501**
danielk19774dbaa892009-06-16 16:50:22 +00007502** The number of siblings of the page might be increased or decreased by
7503** one or two in an effort to keep pages nearly full but not over full.
drh14acc042001-06-10 19:56:58 +00007504**
danielk19774dbaa892009-06-16 16:50:22 +00007505** Note that when this routine is called, some of the cells on the page
7506** might not actually be stored in MemPage.aData[]. This can happen
7507** if the page is overfull. This routine ensures that all cells allocated
7508** to the page and its siblings fit into MemPage.aData[] before returning.
drh14acc042001-06-10 19:56:58 +00007509**
danielk19774dbaa892009-06-16 16:50:22 +00007510** In the course of balancing the page and its siblings, cells may be
7511** inserted into or removed from the parent page (pParent). Doing so
7512** may cause the parent page to become overfull or underfull. If this
7513** happens, it is the responsibility of the caller to invoke the correct
7514** balancing routine to fix this problem (see the balance() routine).
drh8c42ca92001-06-22 19:15:00 +00007515**
drh5e00f6c2001-09-13 13:46:56 +00007516** If this routine fails for any reason, it might leave the database
danielk19776067a9b2009-06-09 09:41:00 +00007517** in a corrupted state. So if this routine fails, the database should
drh5e00f6c2001-09-13 13:46:56 +00007518** be rolled back.
danielk19774dbaa892009-06-16 16:50:22 +00007519**
7520** The third argument to this function, aOvflSpace, is a pointer to a
drhcd09c532009-07-20 19:30:00 +00007521** buffer big enough to hold one page. If while inserting cells into the parent
7522** page (pParent) the parent page becomes overfull, this buffer is
7523** used to store the parent's overflow cells. Because this function inserts
danielk19774dbaa892009-06-16 16:50:22 +00007524** a maximum of four divider cells into the parent page, and the maximum
7525** size of a cell stored within an internal node is always less than 1/4
7526** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
7527** enough for all overflow cells.
7528**
7529** If aOvflSpace is set to a null pointer, this function returns
7530** SQLITE_NOMEM.
drh8b2f49b2001-06-08 00:21:52 +00007531*/
danielk19774dbaa892009-06-16 16:50:22 +00007532static int balance_nonroot(
7533 MemPage *pParent, /* Parent page of siblings being balanced */
7534 int iParentIdx, /* Index of "the page" in pParent */
danielk1977cd581a72009-06-23 15:43:39 +00007535 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
dan428c2182012-08-06 18:50:11 +00007536 int isRoot, /* True if pParent is a root-page */
dan7fff2e12017-05-29 14:27:37 +00007537 int bBulk, /* True if this call is part of a bulk load */
7538 Pgno pgnoRoot /* Root page of b-tree being balanced */
danielk19774dbaa892009-06-16 16:50:22 +00007539){
drh16a9b832007-05-05 18:39:25 +00007540 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00007541 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
danielk1977a4124bd2008-12-23 10:37:47 +00007542 int nNew = 0; /* Number of pages in apNew[] */
danielk19774dbaa892009-06-16 16:50:22 +00007543 int nOld; /* Number of pages in apOld[] */
drh14acc042001-06-10 19:56:58 +00007544 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00007545 int nxDiv; /* Next divider slot in pParent->aCell[] */
shane85095702009-06-15 16:27:08 +00007546 int rc = SQLITE_OK; /* The return code */
shane36840fd2009-06-26 16:32:13 +00007547 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00007548 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00007549 int usableSpace; /* Bytes in pPage beyond the header */
7550 int pageFlags; /* Value of pPage->aData[0] */
drhe5ae5732008-06-15 02:51:47 +00007551 int iSpace1 = 0; /* First unused byte of aSpace1[] */
danielk19776067a9b2009-06-09 09:41:00 +00007552 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
drhfacf0302008-06-17 15:12:00 +00007553 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00007554 MemPage *apOld[NB]; /* pPage and up to two siblings */
drha2fce642004-06-05 00:01:44 +00007555 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
danielk19774dbaa892009-06-16 16:50:22 +00007556 u8 *pRight; /* Location in parent of right-sibling pointer */
7557 u8 *apDiv[NB-1]; /* Divider cells in pParent */
drh1ffd2472015-06-23 02:37:30 +00007558 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
7559 int cntOld[NB+2]; /* Old index in b.apCell[] */
drh2a0df922014-10-30 23:14:56 +00007560 int szNew[NB+2]; /* Combined size of cells placed on i-th page */
danielk19774dbaa892009-06-16 16:50:22 +00007561 u8 *aSpace1; /* Space for copies of dividers cells */
7562 Pgno pgno; /* Temp var to store a page number in */
dane6593d82014-10-24 16:40:49 +00007563 u8 abDone[NB+2]; /* True after i'th new page is populated */
7564 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
drh00fe08a2014-10-31 00:05:23 +00007565 Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
dane6593d82014-10-24 16:40:49 +00007566 u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
drh1ffd2472015-06-23 02:37:30 +00007567 CellArray b; /* Parsed information on cells being balanced */
dan33ea4862014-10-09 19:35:37 +00007568
7569 memset(abDone, 0, sizeof(abDone));
drh1ffd2472015-06-23 02:37:30 +00007570 b.nCell = 0;
7571 b.apCell = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00007572 pBt = pParent->pBt;
7573 assert( sqlite3_mutex_held(pBt->mutex) );
7574 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977474b7cc2008-07-09 11:49:46 +00007575
danielk1977e5765212009-06-17 11:13:28 +00007576#if 0
drh43605152004-05-29 21:46:49 +00007577 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
danielk1977e5765212009-06-17 11:13:28 +00007578#endif
drh2e38c322004-09-03 18:38:44 +00007579
danielk19774dbaa892009-06-16 16:50:22 +00007580 /* At this point pParent may have at most one overflow cell. And if
7581 ** this overflow cell is present, it must be the cell with
7582 ** index iParentIdx. This scenario comes about when this function
drhcd09c532009-07-20 19:30:00 +00007583 ** is called (indirectly) from sqlite3BtreeDelete().
7584 */
danielk19774dbaa892009-06-16 16:50:22 +00007585 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
drh2cbd78b2012-02-02 19:37:18 +00007586 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
danielk19774dbaa892009-06-16 16:50:22 +00007587
danielk197711a8a862009-06-17 11:49:52 +00007588 if( !aOvflSpace ){
mistachkinfad30392016-02-13 23:43:46 +00007589 return SQLITE_NOMEM_BKPT;
danielk197711a8a862009-06-17 11:49:52 +00007590 }
7591
danielk1977a50d9aa2009-06-08 14:49:45 +00007592 /* Find the sibling pages to balance. Also locate the cells in pParent
7593 ** that divide the siblings. An attempt is made to find NN siblings on
7594 ** either side of pPage. More siblings are taken from one side, however,
7595 ** if there are fewer than NN siblings on the other side. If pParent
danielk19774dbaa892009-06-16 16:50:22 +00007596 ** has NB or fewer children then all children of pParent are taken.
7597 **
7598 ** This loop also drops the divider cells from the parent page. This
7599 ** way, the remainder of the function does not have to deal with any
drhcd09c532009-07-20 19:30:00 +00007600 ** overflow cells in the parent page, since if any existed they will
7601 ** have already been removed.
7602 */
danielk19774dbaa892009-06-16 16:50:22 +00007603 i = pParent->nOverflow + pParent->nCell;
7604 if( i<2 ){
drhc3b70572003-01-04 19:44:07 +00007605 nxDiv = 0;
danielk19774dbaa892009-06-16 16:50:22 +00007606 }else{
dan7d6885a2012-08-08 14:04:56 +00007607 assert( bBulk==0 || bBulk==1 );
danielk19774dbaa892009-06-16 16:50:22 +00007608 if( iParentIdx==0 ){
7609 nxDiv = 0;
7610 }else if( iParentIdx==i ){
dan7d6885a2012-08-08 14:04:56 +00007611 nxDiv = i-2+bBulk;
drh14acc042001-06-10 19:56:58 +00007612 }else{
danielk19774dbaa892009-06-16 16:50:22 +00007613 nxDiv = iParentIdx-1;
drh8b2f49b2001-06-08 00:21:52 +00007614 }
dan7d6885a2012-08-08 14:04:56 +00007615 i = 2-bBulk;
danielk19774dbaa892009-06-16 16:50:22 +00007616 }
dan7d6885a2012-08-08 14:04:56 +00007617 nOld = i+1;
danielk19774dbaa892009-06-16 16:50:22 +00007618 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
7619 pRight = &pParent->aData[pParent->hdrOffset+8];
7620 }else{
7621 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
7622 }
7623 pgno = get4byte(pRight);
7624 while( 1 ){
drh28f58dd2015-06-27 19:45:03 +00007625 rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
danielk19774dbaa892009-06-16 16:50:22 +00007626 if( rc ){
danielk197789bc4bc2009-07-21 19:25:24 +00007627 memset(apOld, 0, (i+1)*sizeof(MemPage*));
danielk19774dbaa892009-06-16 16:50:22 +00007628 goto balance_cleanup;
7629 }
dan7fff2e12017-05-29 14:27:37 +00007630 setMempageRoot(apOld[i], pgnoRoot);
7631
danielk1977634f2982005-03-28 08:44:07 +00007632 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
danielk19774dbaa892009-06-16 16:50:22 +00007633 if( (i--)==0 ) break;
7634
drh9cc5b4e2016-12-26 01:41:33 +00007635 if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
drh2cbd78b2012-02-02 19:37:18 +00007636 apDiv[i] = pParent->apOvfl[0];
danielk19774dbaa892009-06-16 16:50:22 +00007637 pgno = get4byte(apDiv[i]);
drh25ada072015-06-19 15:07:14 +00007638 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
danielk19774dbaa892009-06-16 16:50:22 +00007639 pParent->nOverflow = 0;
7640 }else{
7641 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
7642 pgno = get4byte(apDiv[i]);
drh25ada072015-06-19 15:07:14 +00007643 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
danielk19774dbaa892009-06-16 16:50:22 +00007644
7645 /* Drop the cell from the parent page. apDiv[i] still points to
7646 ** the cell within the parent, even though it has been dropped.
7647 ** This is safe because dropping a cell only overwrites the first
7648 ** four bytes of it, and this function does not need the first
7649 ** four bytes of the divider cell. So the pointer is safe to use
danielk197711a8a862009-06-17 11:49:52 +00007650 ** later on.
7651 **
drh8a575d92011-10-12 17:00:28 +00007652 ** But not if we are in secure-delete mode. In secure-delete mode,
danielk197711a8a862009-06-17 11:49:52 +00007653 ** the dropCell() routine will overwrite the entire cell with zeroes.
7654 ** In this case, temporarily copy the cell into the aOvflSpace[]
7655 ** buffer. It will be copied out again as soon as the aSpace[] buffer
7656 ** is allocated. */
drha5907a82017-06-19 11:44:22 +00007657 if( pBt->btsFlags & BTS_FAST_SECURE ){
drh8a575d92011-10-12 17:00:28 +00007658 int iOff;
7659
7660 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
drh43b18e12010-08-17 19:40:08 +00007661 if( (iOff+szNew[i])>(int)pBt->usableSize ){
dan2ed11e72010-02-26 15:09:19 +00007662 rc = SQLITE_CORRUPT_BKPT;
7663 memset(apOld, 0, (i+1)*sizeof(MemPage*));
7664 goto balance_cleanup;
7665 }else{
7666 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
7667 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
7668 }
drh5b47efa2010-02-12 18:18:39 +00007669 }
drh98add2e2009-07-20 17:11:49 +00007670 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
danielk19774dbaa892009-06-16 16:50:22 +00007671 }
drh8b2f49b2001-06-08 00:21:52 +00007672 }
7673
drha9121e42008-02-19 14:59:35 +00007674 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00007675 ** alignment */
drha9121e42008-02-19 14:59:35 +00007676 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00007677
drh8b2f49b2001-06-08 00:21:52 +00007678 /*
danielk1977634f2982005-03-28 08:44:07 +00007679 ** Allocate space for memory structures
7680 */
drhfacf0302008-06-17 15:12:00 +00007681 szScratch =
drh1ffd2472015-06-23 02:37:30 +00007682 nMaxCells*sizeof(u8*) /* b.apCell */
7683 + nMaxCells*sizeof(u16) /* b.szCell */
dan33ea4862014-10-09 19:35:37 +00007684 + pBt->pageSize; /* aSpace1 */
drh5279d342014-11-04 13:41:32 +00007685
drhcbd55b02014-11-04 14:22:27 +00007686 /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
7687 ** that is more than 6 times the database page size. */
mistachkin0fbd7352014-12-09 04:26:56 +00007688 assert( szScratch<=6*(int)pBt->pageSize );
drh1ffd2472015-06-23 02:37:30 +00007689 b.apCell = sqlite3ScratchMalloc( szScratch );
7690 if( b.apCell==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007691 rc = SQLITE_NOMEM_BKPT;
danielk1977634f2982005-03-28 08:44:07 +00007692 goto balance_cleanup;
7693 }
drh1ffd2472015-06-23 02:37:30 +00007694 b.szCell = (u16*)&b.apCell[nMaxCells];
7695 aSpace1 = (u8*)&b.szCell[nMaxCells];
drhea598cb2009-04-05 12:22:08 +00007696 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
drh14acc042001-06-10 19:56:58 +00007697
7698 /*
7699 ** Load pointers to all cells on sibling pages and the divider cells
drh1ffd2472015-06-23 02:37:30 +00007700 ** into the local b.apCell[] array. Make copies of the divider cells
dan33ea4862014-10-09 19:35:37 +00007701 ** into space obtained from aSpace1[]. The divider cells have already
7702 ** been removed from pParent.
drh4b70f112004-05-02 21:12:19 +00007703 **
7704 ** If the siblings are on leaf pages, then the child pointers of the
7705 ** divider cells are stripped from the cells before they are copied
drh1ffd2472015-06-23 02:37:30 +00007706 ** into aSpace1[]. In this way, all cells in b.apCell[] are without
drh4b70f112004-05-02 21:12:19 +00007707 ** child pointers. If siblings are not leaves, then all cell in
drh1ffd2472015-06-23 02:37:30 +00007708 ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
drh4b70f112004-05-02 21:12:19 +00007709 ** are alike.
drh96f5b762004-05-16 16:24:36 +00007710 **
7711 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
7712 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00007713 */
drh1ffd2472015-06-23 02:37:30 +00007714 b.pRef = apOld[0];
7715 leafCorrection = b.pRef->leaf*4;
7716 leafData = b.pRef->intKeyLeaf;
drh8b2f49b2001-06-08 00:21:52 +00007717 for(i=0; i<nOld; i++){
dan33ea4862014-10-09 19:35:37 +00007718 MemPage *pOld = apOld[i];
drh4edfdd32015-06-23 14:49:42 +00007719 int limit = pOld->nCell;
7720 u8 *aData = pOld->aData;
7721 u16 maskPage = pOld->maskPage;
drh4f4bf772015-06-23 17:09:53 +00007722 u8 *piCell = aData + pOld->cellOffset;
drhfe647dc2015-06-23 18:24:25 +00007723 u8 *piEnd;
danielk19774dbaa892009-06-16 16:50:22 +00007724
drh73d340a2015-05-28 11:23:11 +00007725 /* Verify that all sibling pages are of the same "type" (table-leaf,
7726 ** table-interior, index-leaf, or index-interior).
7727 */
7728 if( pOld->aData[0]!=apOld[0]->aData[0] ){
7729 rc = SQLITE_CORRUPT_BKPT;
7730 goto balance_cleanup;
7731 }
7732
drhfe647dc2015-06-23 18:24:25 +00007733 /* Load b.apCell[] with pointers to all cells in pOld. If pOld
7734 ** constains overflow cells, include them in the b.apCell[] array
7735 ** in the correct spot.
7736 **
7737 ** Note that when there are multiple overflow cells, it is always the
7738 ** case that they are sequential and adjacent. This invariant arises
7739 ** because multiple overflows can only occurs when inserting divider
7740 ** cells into a parent on a prior balance, and divider cells are always
7741 ** adjacent and are inserted in order. There is an assert() tagged
7742 ** with "NOTE 1" in the overflow cell insertion loop to prove this
7743 ** invariant.
drh4edfdd32015-06-23 14:49:42 +00007744 **
7745 ** This must be done in advance. Once the balance starts, the cell
7746 ** offset section of the btree page will be overwritten and we will no
7747 ** long be able to find the cells if a pointer to each cell is not saved
7748 ** first.
7749 */
drh36b78ee2016-01-20 01:32:00 +00007750 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
drh68f2a572011-06-03 17:50:49 +00007751 if( pOld->nOverflow>0 ){
drhfe647dc2015-06-23 18:24:25 +00007752 limit = pOld->aiOvfl[0];
7753 for(j=0; j<limit; j++){
drh329428e2015-06-30 13:28:18 +00007754 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
drhfe647dc2015-06-23 18:24:25 +00007755 piCell += 2;
7756 b.nCell++;
7757 }
7758 for(k=0; k<pOld->nOverflow; k++){
7759 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
drh4edfdd32015-06-23 14:49:42 +00007760 b.apCell[b.nCell] = pOld->apOvfl[k];
drh1ffd2472015-06-23 02:37:30 +00007761 b.nCell++;
drh68f2a572011-06-03 17:50:49 +00007762 }
drh1ffd2472015-06-23 02:37:30 +00007763 }
drhfe647dc2015-06-23 18:24:25 +00007764 piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
7765 while( piCell<piEnd ){
drh4edfdd32015-06-23 14:49:42 +00007766 assert( b.nCell<nMaxCells );
drh329428e2015-06-30 13:28:18 +00007767 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
drh4f4bf772015-06-23 17:09:53 +00007768 piCell += 2;
drh4edfdd32015-06-23 14:49:42 +00007769 b.nCell++;
drh4edfdd32015-06-23 14:49:42 +00007770 }
7771
drh1ffd2472015-06-23 02:37:30 +00007772 cntOld[i] = b.nCell;
danielk19774dbaa892009-06-16 16:50:22 +00007773 if( i<nOld-1 && !leafData){
shane36840fd2009-06-26 16:32:13 +00007774 u16 sz = (u16)szNew[i];
danielk19774dbaa892009-06-16 16:50:22 +00007775 u8 *pTemp;
drh1ffd2472015-06-23 02:37:30 +00007776 assert( b.nCell<nMaxCells );
7777 b.szCell[b.nCell] = sz;
danielk19774dbaa892009-06-16 16:50:22 +00007778 pTemp = &aSpace1[iSpace1];
7779 iSpace1 += sz;
drhe22e03e2010-08-18 21:19:03 +00007780 assert( sz<=pBt->maxLocal+23 );
drhfcd71b62011-04-05 22:08:24 +00007781 assert( iSpace1 <= (int)pBt->pageSize );
danielk19774dbaa892009-06-16 16:50:22 +00007782 memcpy(pTemp, apDiv[i], sz);
drh1ffd2472015-06-23 02:37:30 +00007783 b.apCell[b.nCell] = pTemp+leafCorrection;
danielk19774dbaa892009-06-16 16:50:22 +00007784 assert( leafCorrection==0 || leafCorrection==4 );
drh1ffd2472015-06-23 02:37:30 +00007785 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
danielk19774dbaa892009-06-16 16:50:22 +00007786 if( !pOld->leaf ){
7787 assert( leafCorrection==0 );
7788 assert( pOld->hdrOffset==0 );
7789 /* The right pointer of the child page pOld becomes the left
7790 ** pointer of the divider cell */
drh1ffd2472015-06-23 02:37:30 +00007791 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
danielk19774dbaa892009-06-16 16:50:22 +00007792 }else{
7793 assert( leafCorrection==4 );
drh1ffd2472015-06-23 02:37:30 +00007794 while( b.szCell[b.nCell]<4 ){
dan8f1eb8a2014-12-06 14:56:49 +00007795 /* Do not allow any cells smaller than 4 bytes. If a smaller cell
7796 ** does exist, pad it with 0x00 bytes. */
drh1ffd2472015-06-23 02:37:30 +00007797 assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
7798 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
danee7172f2014-12-24 18:11:50 +00007799 aSpace1[iSpace1++] = 0x00;
drh1ffd2472015-06-23 02:37:30 +00007800 b.szCell[b.nCell]++;
danielk1977ac11ee62005-01-15 12:45:51 +00007801 }
7802 }
drh1ffd2472015-06-23 02:37:30 +00007803 b.nCell++;
drh8b2f49b2001-06-08 00:21:52 +00007804 }
drh8b2f49b2001-06-08 00:21:52 +00007805 }
7806
7807 /*
drh1ffd2472015-06-23 02:37:30 +00007808 ** Figure out the number of pages needed to hold all b.nCell cells.
drh6019e162001-07-02 17:51:45 +00007809 ** Store this number in "k". Also compute szNew[] which is the total
7810 ** size of all cells on the i-th page and cntNew[] which is the index
drh1ffd2472015-06-23 02:37:30 +00007811 ** in b.apCell[] of the cell that divides page i from page i+1.
7812 ** cntNew[k] should equal b.nCell.
drh6019e162001-07-02 17:51:45 +00007813 **
drh96f5b762004-05-16 16:24:36 +00007814 ** Values computed by this block:
7815 **
7816 ** k: The total number of sibling pages
7817 ** szNew[i]: Spaced used on the i-th sibling page.
drh1ffd2472015-06-23 02:37:30 +00007818 ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
drh96f5b762004-05-16 16:24:36 +00007819 ** the right of the i-th sibling page.
7820 ** usableSpace: Number of bytes of space available on each sibling.
7821 **
drh8b2f49b2001-06-08 00:21:52 +00007822 */
drh43605152004-05-29 21:46:49 +00007823 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh658873b2015-06-22 20:02:04 +00007824 for(i=0; i<nOld; i++){
7825 MemPage *p = apOld[i];
7826 szNew[i] = usableSpace - p->nFree;
drh658873b2015-06-22 20:02:04 +00007827 for(j=0; j<p->nOverflow; j++){
7828 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
7829 }
7830 cntNew[i] = cntOld[i];
7831 }
7832 k = nOld;
7833 for(i=0; i<k; i++){
7834 int sz;
7835 while( szNew[i]>usableSpace ){
7836 if( i+1>=k ){
7837 k = i+2;
7838 if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
7839 szNew[k-1] = 0;
drh1ffd2472015-06-23 02:37:30 +00007840 cntNew[k-1] = b.nCell;
drh658873b2015-06-22 20:02:04 +00007841 }
drh1ffd2472015-06-23 02:37:30 +00007842 sz = 2 + cachedCellSize(&b, cntNew[i]-1);
drh658873b2015-06-22 20:02:04 +00007843 szNew[i] -= sz;
7844 if( !leafData ){
drh1ffd2472015-06-23 02:37:30 +00007845 if( cntNew[i]<b.nCell ){
7846 sz = 2 + cachedCellSize(&b, cntNew[i]);
7847 }else{
7848 sz = 0;
7849 }
drh658873b2015-06-22 20:02:04 +00007850 }
7851 szNew[i+1] += sz;
7852 cntNew[i]--;
7853 }
drh1ffd2472015-06-23 02:37:30 +00007854 while( cntNew[i]<b.nCell ){
7855 sz = 2 + cachedCellSize(&b, cntNew[i]);
drh658873b2015-06-22 20:02:04 +00007856 if( szNew[i]+sz>usableSpace ) break;
7857 szNew[i] += sz;
7858 cntNew[i]++;
7859 if( !leafData ){
drh1ffd2472015-06-23 02:37:30 +00007860 if( cntNew[i]<b.nCell ){
7861 sz = 2 + cachedCellSize(&b, cntNew[i]);
7862 }else{
7863 sz = 0;
7864 }
drh658873b2015-06-22 20:02:04 +00007865 }
7866 szNew[i+1] -= sz;
7867 }
drh1ffd2472015-06-23 02:37:30 +00007868 if( cntNew[i]>=b.nCell ){
drh658873b2015-06-22 20:02:04 +00007869 k = i+1;
drh672073a2015-06-24 12:07:40 +00007870 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
drh658873b2015-06-22 20:02:04 +00007871 rc = SQLITE_CORRUPT_BKPT;
7872 goto balance_cleanup;
drh6019e162001-07-02 17:51:45 +00007873 }
7874 }
drh96f5b762004-05-16 16:24:36 +00007875
7876 /*
7877 ** The packing computed by the previous block is biased toward the siblings
drh2a0df922014-10-30 23:14:56 +00007878 ** on the left side (siblings with smaller keys). The left siblings are
7879 ** always nearly full, while the right-most sibling might be nearly empty.
7880 ** The next block of code attempts to adjust the packing of siblings to
7881 ** get a better balance.
drh96f5b762004-05-16 16:24:36 +00007882 **
7883 ** This adjustment is more than an optimization. The packing above might
7884 ** be so out of balance as to be illegal. For example, the right-most
7885 ** sibling might be completely empty. This adjustment is not optional.
7886 */
drh6019e162001-07-02 17:51:45 +00007887 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00007888 int szRight = szNew[i]; /* Size of sibling on the right */
7889 int szLeft = szNew[i-1]; /* Size of sibling on the left */
7890 int r; /* Index of right-most cell in left sibling */
7891 int d; /* Index of first cell to the left of right sibling */
7892
drh008d64c2015-06-23 16:00:24 +00007893 r = cntNew[i-1] - 1;
7894 d = r + 1 - leafData;
7895 (void)cachedCellSize(&b, d);
drh672073a2015-06-24 12:07:40 +00007896 do{
drh1ffd2472015-06-23 02:37:30 +00007897 assert( d<nMaxCells );
7898 assert( r<nMaxCells );
drh1ffd2472015-06-23 02:37:30 +00007899 (void)cachedCellSize(&b, r);
7900 if( szRight!=0
drh0b4c0422016-07-14 19:48:08 +00007901 && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
drh1ffd2472015-06-23 02:37:30 +00007902 break;
7903 }
7904 szRight += b.szCell[d] + 2;
7905 szLeft -= b.szCell[r] + 2;
drh008d64c2015-06-23 16:00:24 +00007906 cntNew[i-1] = r;
drh008d64c2015-06-23 16:00:24 +00007907 r--;
7908 d--;
drh672073a2015-06-24 12:07:40 +00007909 }while( r>=0 );
drh96f5b762004-05-16 16:24:36 +00007910 szNew[i] = szRight;
7911 szNew[i-1] = szLeft;
drh672073a2015-06-24 12:07:40 +00007912 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
7913 rc = SQLITE_CORRUPT_BKPT;
7914 goto balance_cleanup;
7915 }
drh6019e162001-07-02 17:51:45 +00007916 }
drh09d0deb2005-08-02 17:13:09 +00007917
drh2a0df922014-10-30 23:14:56 +00007918 /* Sanity check: For a non-corrupt database file one of the follwing
7919 ** must be true:
7920 ** (1) We found one or more cells (cntNew[0])>0), or
7921 ** (2) pPage is a virtual root page. A virtual root page is when
7922 ** the real root page is page 1 and we are the only child of
7923 ** that page.
drh09d0deb2005-08-02 17:13:09 +00007924 */
drh2a0df922014-10-30 23:14:56 +00007925 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
dan33ea4862014-10-09 19:35:37 +00007926 TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
7927 apOld[0]->pgno, apOld[0]->nCell,
7928 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
7929 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
danielk1977e5765212009-06-17 11:13:28 +00007930 ));
7931
drh8b2f49b2001-06-08 00:21:52 +00007932 /*
drh6b308672002-07-08 02:16:37 +00007933 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00007934 */
danielk1977a50d9aa2009-06-08 14:49:45 +00007935 pageFlags = apOld[0]->aData[0];
drh14acc042001-06-10 19:56:58 +00007936 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00007937 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00007938 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00007939 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00007940 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00007941 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00007942 nNew++;
danielk197728129562005-01-11 10:25:06 +00007943 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00007944 }else{
drh7aa8f852006-03-28 00:24:44 +00007945 assert( i>0 );
dan428c2182012-08-06 18:50:11 +00007946 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
drh6b308672002-07-08 02:16:37 +00007947 if( rc ) goto balance_cleanup;
dan33ea4862014-10-09 19:35:37 +00007948 zeroPage(pNew, pageFlags);
drhda200cc2004-05-09 11:51:38 +00007949 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00007950 nNew++;
drh1ffd2472015-06-23 02:37:30 +00007951 cntOld[i] = b.nCell;
danielk19774dbaa892009-06-16 16:50:22 +00007952
7953 /* Set the pointer-map entry for the new sibling page. */
dan7b3d71e2015-08-19 20:27:05 +00007954 if( REQUIRE_PTRMAP ){
drh98add2e2009-07-20 17:11:49 +00007955 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00007956 if( rc!=SQLITE_OK ){
7957 goto balance_cleanup;
7958 }
7959 }
drh6b308672002-07-08 02:16:37 +00007960 }
drh8b2f49b2001-06-08 00:21:52 +00007961 }
7962
7963 /*
dan33ea4862014-10-09 19:35:37 +00007964 ** Reassign page numbers so that the new pages are in ascending order.
7965 ** This helps to keep entries in the disk file in order so that a scan
7966 ** of the table is closer to a linear scan through the file. That in turn
7967 ** helps the operating system to deliver pages from the disk more rapidly.
drhf9ffac92002-03-02 19:00:31 +00007968 **
dan33ea4862014-10-09 19:35:37 +00007969 ** An O(n^2) insertion sort algorithm is used, but since n is never more
7970 ** than (NB+2) (a small constant), that should not be a problem.
drhf9ffac92002-03-02 19:00:31 +00007971 **
dan33ea4862014-10-09 19:35:37 +00007972 ** When NB==3, this one optimization makes the database about 25% faster
7973 ** for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00007974 */
dan33ea4862014-10-09 19:35:37 +00007975 for(i=0; i<nNew; i++){
drh00fe08a2014-10-31 00:05:23 +00007976 aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
dan33ea4862014-10-09 19:35:37 +00007977 aPgFlags[i] = apNew[i]->pDbPage->flags;
dan89ca0b32014-10-25 20:36:28 +00007978 for(j=0; j<i; j++){
7979 if( aPgno[j]==aPgno[i] ){
7980 /* This branch is taken if the set of sibling pages somehow contains
7981 ** duplicate entries. This can happen if the database is corrupt.
7982 ** It would be simpler to detect this as part of the loop below, but
drhba0f9992014-10-30 20:48:44 +00007983 ** we do the detection here in order to avoid populating the pager
7984 ** cache with two separate objects associated with the same
7985 ** page number. */
dan89ca0b32014-10-25 20:36:28 +00007986 assert( CORRUPT_DB );
7987 rc = SQLITE_CORRUPT_BKPT;
7988 goto balance_cleanup;
7989 }
7990 }
dan33ea4862014-10-09 19:35:37 +00007991 }
7992 for(i=0; i<nNew; i++){
dan31f4e992014-10-24 20:57:03 +00007993 int iBest = 0; /* aPgno[] index of page number to use */
dan31f4e992014-10-24 20:57:03 +00007994 for(j=1; j<nNew; j++){
drh00fe08a2014-10-31 00:05:23 +00007995 if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
drhf9ffac92002-03-02 19:00:31 +00007996 }
drh00fe08a2014-10-31 00:05:23 +00007997 pgno = aPgOrder[iBest];
7998 aPgOrder[iBest] = 0xffffffff;
dan31f4e992014-10-24 20:57:03 +00007999 if( iBest!=i ){
8000 if( iBest>i ){
8001 sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
8002 }
8003 sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
8004 apNew[i]->pgno = pgno;
drhf9ffac92002-03-02 19:00:31 +00008005 }
8006 }
dan33ea4862014-10-09 19:35:37 +00008007
8008 TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
8009 "%d(%d nc=%d) %d(%d nc=%d)\n",
8010 apNew[0]->pgno, szNew[0], cntNew[0],
danielk19774dbaa892009-06-16 16:50:22 +00008011 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
dan33ea4862014-10-09 19:35:37 +00008012 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
danielk19774dbaa892009-06-16 16:50:22 +00008013 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
dan33ea4862014-10-09 19:35:37 +00008014 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
danielk19774dbaa892009-06-16 16:50:22 +00008015 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
dan33ea4862014-10-09 19:35:37 +00008016 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
8017 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
8018 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
8019 ));
danielk19774dbaa892009-06-16 16:50:22 +00008020
8021 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8022 put4byte(pRight, apNew[nNew-1]->pgno);
drh24cd67e2004-05-10 16:18:47 +00008023
dan33ea4862014-10-09 19:35:37 +00008024 /* If the sibling pages are not leaves, ensure that the right-child pointer
8025 ** of the right-most new sibling page is set to the value that was
8026 ** originally in the same field of the right-most old sibling page. */
8027 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
8028 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
8029 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
8030 }
danielk1977ac11ee62005-01-15 12:45:51 +00008031
dan33ea4862014-10-09 19:35:37 +00008032 /* Make any required updates to pointer map entries associated with
8033 ** cells stored on sibling pages following the balance operation. Pointer
8034 ** map entries associated with divider cells are set by the insertCell()
8035 ** routine. The associated pointer map entries are:
8036 **
8037 ** a) if the cell contains a reference to an overflow chain, the
8038 ** entry associated with the first page in the overflow chain, and
8039 **
8040 ** b) if the sibling pages are not leaves, the child page associated
8041 ** with the cell.
8042 **
8043 ** If the sibling pages are not leaves, then the pointer map entry
8044 ** associated with the right-child of each sibling may also need to be
8045 ** updated. This happens below, after the sibling pages have been
8046 ** populated, not here.
8047 */
dan7b3d71e2015-08-19 20:27:05 +00008048 if( REQUIRE_PTRMAP ){
dan33ea4862014-10-09 19:35:37 +00008049 MemPage *pNew = apNew[0];
8050 u8 *aOld = pNew->aData;
8051 int cntOldNext = pNew->nCell + pNew->nOverflow;
8052 int usableSize = pBt->usableSize;
8053 int iNew = 0;
8054 int iOld = 0;
danielk1977634f2982005-03-28 08:44:07 +00008055
drh1ffd2472015-06-23 02:37:30 +00008056 for(i=0; i<b.nCell; i++){
8057 u8 *pCell = b.apCell[i];
dan33ea4862014-10-09 19:35:37 +00008058 if( i==cntOldNext ){
8059 MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
8060 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
8061 aOld = pOld->aData;
8062 }
8063 if( i==cntNew[iNew] ){
8064 pNew = apNew[++iNew];
8065 if( !leafData ) continue;
8066 }
8067
8068 /* Cell pCell is destined for new sibling page pNew. Originally, it
drhba0f9992014-10-30 20:48:44 +00008069 ** was either part of sibling page iOld (possibly an overflow cell),
dan33ea4862014-10-09 19:35:37 +00008070 ** or else the divider cell to the left of sibling page iOld. So,
8071 ** if sibling page iOld had the same page number as pNew, and if
8072 ** pCell really was a part of sibling page iOld (not a divider or
8073 ** overflow cell), we can skip updating the pointer map entries. */
drhd52d52b2014-12-06 02:05:44 +00008074 if( iOld>=nNew
8075 || pNew->pgno!=aPgno[iOld]
drhac536e62015-12-10 15:09:17 +00008076 || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
drhd52d52b2014-12-06 02:05:44 +00008077 ){
dan33ea4862014-10-09 19:35:37 +00008078 if( !leafCorrection ){
8079 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
8080 }
drh1ffd2472015-06-23 02:37:30 +00008081 if( cachedCellSize(&b,i)>pNew->minLocal ){
dan33ea4862014-10-09 19:35:37 +00008082 ptrmapPutOvflPtr(pNew, pCell, &rc);
danielk19774aeff622007-05-12 09:30:47 +00008083 }
drhea82b372015-06-23 21:35:28 +00008084 if( rc ) goto balance_cleanup;
drh4b70f112004-05-02 21:12:19 +00008085 }
drh14acc042001-06-10 19:56:58 +00008086 }
8087 }
dan33ea4862014-10-09 19:35:37 +00008088
8089 /* Insert new divider cells into pParent. */
8090 for(i=0; i<nNew-1; i++){
8091 u8 *pCell;
8092 u8 *pTemp;
8093 int sz;
8094 MemPage *pNew = apNew[i];
8095 j = cntNew[i];
8096
8097 assert( j<nMaxCells );
drh1ffd2472015-06-23 02:37:30 +00008098 assert( b.apCell[j]!=0 );
8099 pCell = b.apCell[j];
8100 sz = b.szCell[j] + leafCorrection;
dan33ea4862014-10-09 19:35:37 +00008101 pTemp = &aOvflSpace[iOvflSpace];
8102 if( !pNew->leaf ){
8103 memcpy(&pNew->aData[8], pCell, 4);
8104 }else if( leafData ){
8105 /* If the tree is a leaf-data tree, and the siblings are leaves,
drh1ffd2472015-06-23 02:37:30 +00008106 ** then there is no divider cell in b.apCell[]. Instead, the divider
dan33ea4862014-10-09 19:35:37 +00008107 ** cell consists of the integer key for the right-most cell of
8108 ** the sibling-page assembled above only.
8109 */
8110 CellInfo info;
8111 j--;
drh1ffd2472015-06-23 02:37:30 +00008112 pNew->xParseCell(pNew, b.apCell[j], &info);
dan33ea4862014-10-09 19:35:37 +00008113 pCell = pTemp;
8114 sz = 4 + putVarint(&pCell[4], info.nKey);
8115 pTemp = 0;
8116 }else{
8117 pCell -= 4;
8118 /* Obscure case for non-leaf-data trees: If the cell at pCell was
8119 ** previously stored on a leaf node, and its reported size was 4
8120 ** bytes, then it may actually be smaller than this
8121 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
8122 ** any cell). But it is important to pass the correct size to
8123 ** insertCell(), so reparse the cell now.
8124 **
drhc1fb2b82016-03-09 03:29:27 +00008125 ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
8126 ** and WITHOUT ROWID tables with exactly one column which is the
8127 ** primary key.
dan33ea4862014-10-09 19:35:37 +00008128 */
drh1ffd2472015-06-23 02:37:30 +00008129 if( b.szCell[j]==4 ){
dan33ea4862014-10-09 19:35:37 +00008130 assert(leafCorrection==4);
drh25ada072015-06-19 15:07:14 +00008131 sz = pParent->xCellSize(pParent, pCell);
dan33ea4862014-10-09 19:35:37 +00008132 }
8133 }
8134 iOvflSpace += sz;
8135 assert( sz<=pBt->maxLocal+23 );
8136 assert( iOvflSpace <= (int)pBt->pageSize );
8137 insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
8138 if( rc!=SQLITE_OK ) goto balance_cleanup;
8139 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8140 }
8141
8142 /* Now update the actual sibling pages. The order in which they are updated
8143 ** is important, as this code needs to avoid disrupting any page from which
8144 ** cells may still to be read. In practice, this means:
8145 **
drhd836d422014-10-31 14:26:36 +00008146 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
8147 ** then it is not safe to update page apNew[iPg] until after
8148 ** the left-hand sibling apNew[iPg-1] has been updated.
dan33ea4862014-10-09 19:35:37 +00008149 **
drhd836d422014-10-31 14:26:36 +00008150 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
8151 ** then it is not safe to update page apNew[iPg] until after
8152 ** the right-hand sibling apNew[iPg+1] has been updated.
dan33ea4862014-10-09 19:35:37 +00008153 **
8154 ** If neither of the above apply, the page is safe to update.
drhd836d422014-10-31 14:26:36 +00008155 **
8156 ** The iPg value in the following loop starts at nNew-1 goes down
8157 ** to 0, then back up to nNew-1 again, thus making two passes over
8158 ** the pages. On the initial downward pass, only condition (1) above
8159 ** needs to be tested because (2) will always be true from the previous
8160 ** step. On the upward pass, both conditions are always true, so the
8161 ** upwards pass simply processes pages that were missed on the downward
8162 ** pass.
dan33ea4862014-10-09 19:35:37 +00008163 */
drhbec021b2014-10-31 12:22:00 +00008164 for(i=1-nNew; i<nNew; i++){
8165 int iPg = i<0 ? -i : i;
drhbec021b2014-10-31 12:22:00 +00008166 assert( iPg>=0 && iPg<nNew );
drhd836d422014-10-31 14:26:36 +00008167 if( abDone[iPg] ) continue; /* Skip pages already processed */
8168 if( i>=0 /* On the upwards pass, or... */
8169 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
dan33ea4862014-10-09 19:35:37 +00008170 ){
dan09c68402014-10-11 20:00:24 +00008171 int iNew;
8172 int iOld;
8173 int nNewCell;
8174
drhd836d422014-10-31 14:26:36 +00008175 /* Verify condition (1): If cells are moving left, update iPg
8176 ** only after iPg-1 has already been updated. */
8177 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
8178
8179 /* Verify condition (2): If cells are moving right, update iPg
8180 ** only after iPg+1 has already been updated. */
8181 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
8182
dan09c68402014-10-11 20:00:24 +00008183 if( iPg==0 ){
8184 iNew = iOld = 0;
8185 nNewCell = cntNew[0];
8186 }else{
drh1ffd2472015-06-23 02:37:30 +00008187 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
dan09c68402014-10-11 20:00:24 +00008188 iNew = cntNew[iPg-1] + !leafData;
8189 nNewCell = cntNew[iPg] - iNew;
8190 }
8191
drh1ffd2472015-06-23 02:37:30 +00008192 rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
drh658873b2015-06-22 20:02:04 +00008193 if( rc ) goto balance_cleanup;
drhd836d422014-10-31 14:26:36 +00008194 abDone[iPg]++;
dand7b545b2014-10-13 18:03:27 +00008195 apNew[iPg]->nFree = usableSpace-szNew[iPg];
dan09c68402014-10-11 20:00:24 +00008196 assert( apNew[iPg]->nOverflow==0 );
8197 assert( apNew[iPg]->nCell==nNewCell );
dan33ea4862014-10-09 19:35:37 +00008198 }
8199 }
drhd836d422014-10-31 14:26:36 +00008200
8201 /* All pages have been processed exactly once */
dan33ea4862014-10-09 19:35:37 +00008202 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
8203
drh7aa8f852006-03-28 00:24:44 +00008204 assert( nOld>0 );
8205 assert( nNew>0 );
drh14acc042001-06-10 19:56:58 +00008206
danielk197713bd99f2009-06-24 05:40:34 +00008207 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
8208 /* The root page of the b-tree now contains no cells. The only sibling
8209 ** page is the right-child of the parent. Copy the contents of the
8210 ** child page into the parent, decreasing the overall height of the
8211 ** b-tree structure by one. This is described as the "balance-shallower"
8212 ** sub-algorithm in some documentation.
8213 **
8214 ** If this is an auto-vacuum database, the call to copyNodeContent()
8215 ** sets all pointer-map entries corresponding to database image pages
8216 ** for which the pointer is stored within the content being copied.
8217 **
drh768f2902014-10-31 02:51:41 +00008218 ** It is critical that the child page be defragmented before being
8219 ** copied into the parent, because if the parent is page 1 then it will
8220 ** by smaller than the child due to the database header, and so all the
8221 ** free space needs to be up front.
8222 */
drh9b5351d2015-09-30 14:19:08 +00008223 assert( nNew==1 || CORRUPT_DB );
dan3b2ede12017-02-25 16:24:02 +00008224 rc = defragmentPage(apNew[0], -1);
drh768f2902014-10-31 02:51:41 +00008225 testcase( rc!=SQLITE_OK );
8226 assert( apNew[0]->nFree ==
8227 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
8228 || rc!=SQLITE_OK
8229 );
8230 copyNodeContent(apNew[0], pParent, &rc);
8231 freePage(apNew[0], &rc);
dan7b3d71e2015-08-19 20:27:05 +00008232 }else if( REQUIRE_PTRMAP && !leafCorrection ){
dan33ea4862014-10-09 19:35:37 +00008233 /* Fix the pointer map entries associated with the right-child of each
8234 ** sibling page. All other pointer map entries have already been taken
8235 ** care of. */
8236 for(i=0; i<nNew; i++){
8237 u32 key = get4byte(&apNew[i]->aData[8]);
8238 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00008239 }
dan33ea4862014-10-09 19:35:37 +00008240 }
danielk19774dbaa892009-06-16 16:50:22 +00008241
dan33ea4862014-10-09 19:35:37 +00008242 assert( pParent->isInit );
8243 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
drh1ffd2472015-06-23 02:37:30 +00008244 nOld, nNew, b.nCell));
danielk19774dbaa892009-06-16 16:50:22 +00008245
dan33ea4862014-10-09 19:35:37 +00008246 /* Free any old pages that were not reused as new pages.
8247 */
8248 for(i=nNew; i<nOld; i++){
8249 freePage(apOld[i], &rc);
8250 }
8251
dane6593d82014-10-24 16:40:49 +00008252#if 0
dan33ea4862014-10-09 19:35:37 +00008253 if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
danielk19774dbaa892009-06-16 16:50:22 +00008254 /* The ptrmapCheckPages() contains assert() statements that verify that
8255 ** all pointer map pages are set correctly. This is helpful while
8256 ** debugging. This is usually disabled because a corrupt database may
8257 ** cause an assert() statement to fail. */
8258 ptrmapCheckPages(apNew, nNew);
8259 ptrmapCheckPages(&pParent, 1);
danielk19774dbaa892009-06-16 16:50:22 +00008260 }
dan33ea4862014-10-09 19:35:37 +00008261#endif
danielk1977cd581a72009-06-23 15:43:39 +00008262
drh8b2f49b2001-06-08 00:21:52 +00008263 /*
drh14acc042001-06-10 19:56:58 +00008264 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00008265 */
drh14acc042001-06-10 19:56:58 +00008266balance_cleanup:
drh1ffd2472015-06-23 02:37:30 +00008267 sqlite3ScratchFree(b.apCell);
drh8b2f49b2001-06-08 00:21:52 +00008268 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00008269 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00008270 }
drh14acc042001-06-10 19:56:58 +00008271 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00008272 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00008273 }
danielk1977eaa06f62008-09-18 17:34:44 +00008274
drh8b2f49b2001-06-08 00:21:52 +00008275 return rc;
8276}
8277
drh43605152004-05-29 21:46:49 +00008278
8279/*
danielk1977a50d9aa2009-06-08 14:49:45 +00008280** This function is called when the root page of a b-tree structure is
8281** overfull (has one or more overflow pages).
drh43605152004-05-29 21:46:49 +00008282**
danielk1977a50d9aa2009-06-08 14:49:45 +00008283** A new child page is allocated and the contents of the current root
8284** page, including overflow cells, are copied into the child. The root
8285** page is then overwritten to make it an empty page with the right-child
8286** pointer pointing to the new page.
8287**
8288** Before returning, all pointer-map entries corresponding to pages
8289** that the new child-page now contains pointers to are updated. The
8290** entry corresponding to the new right-child pointer of the root
8291** page is also updated.
8292**
8293** If successful, *ppChild is set to contain a reference to the child
8294** page and SQLITE_OK is returned. In this case the caller is required
8295** to call releasePage() on *ppChild exactly once. If an error occurs,
8296** an error code is returned and *ppChild is set to 0.
drh43605152004-05-29 21:46:49 +00008297*/
danielk1977a50d9aa2009-06-08 14:49:45 +00008298static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
8299 int rc; /* Return value from subprocedures */
8300 MemPage *pChild = 0; /* Pointer to a new child page */
shane5eff7cf2009-08-10 03:57:58 +00008301 Pgno pgnoChild = 0; /* Page number of the new child page */
danielk1977a50d9aa2009-06-08 14:49:45 +00008302 BtShared *pBt = pRoot->pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00008303
danielk1977a50d9aa2009-06-08 14:49:45 +00008304 assert( pRoot->nOverflow>0 );
drh1fee73e2007-08-29 04:00:57 +00008305 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bc2ca9e2008-11-13 14:28:28 +00008306
danielk1977a50d9aa2009-06-08 14:49:45 +00008307 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
8308 ** page that will become the new right-child of pPage. Copy the contents
8309 ** of the node stored on pRoot into the new child page.
8310 */
drh98add2e2009-07-20 17:11:49 +00008311 rc = sqlite3PagerWrite(pRoot->pDbPage);
8312 if( rc==SQLITE_OK ){
8313 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
drhc314dc72009-07-21 11:52:34 +00008314 copyNodeContent(pRoot, pChild, &rc);
dan7b3d71e2015-08-19 20:27:05 +00008315 if( REQUIRE_PTRMAP ){
drhc314dc72009-07-21 11:52:34 +00008316 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
drh98add2e2009-07-20 17:11:49 +00008317 }
8318 }
8319 if( rc ){
danielk1977a50d9aa2009-06-08 14:49:45 +00008320 *ppChild = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00008321 releasePage(pChild);
danielk1977a50d9aa2009-06-08 14:49:45 +00008322 return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00008323 }
danielk1977a50d9aa2009-06-08 14:49:45 +00008324 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
8325 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8326 assert( pChild->nCell==pRoot->nCell );
danielk197771d5d2c2008-09-29 11:49:47 +00008327
danielk1977a50d9aa2009-06-08 14:49:45 +00008328 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
8329
8330 /* Copy the overflow cells from pRoot to pChild */
drh2cbd78b2012-02-02 19:37:18 +00008331 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
8332 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
8333 memcpy(pChild->apOvfl, pRoot->apOvfl,
8334 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
danielk1977a50d9aa2009-06-08 14:49:45 +00008335 pChild->nOverflow = pRoot->nOverflow;
danielk1977a50d9aa2009-06-08 14:49:45 +00008336
8337 /* Zero the contents of pRoot. Then install pChild as the right-child. */
8338 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
8339 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
8340
8341 *ppChild = pChild;
8342 return SQLITE_OK;
drh43605152004-05-29 21:46:49 +00008343}
8344
8345/*
danielk197771d5d2c2008-09-29 11:49:47 +00008346** The page that pCur currently points to has just been modified in
8347** some way. This function figures out if this modification means the
8348** tree needs to be balanced, and if so calls the appropriate balancing
danielk1977a50d9aa2009-06-08 14:49:45 +00008349** routine. Balancing routines are:
8350**
8351** balance_quick()
danielk1977a50d9aa2009-06-08 14:49:45 +00008352** balance_deeper()
8353** balance_nonroot()
drh43605152004-05-29 21:46:49 +00008354*/
danielk1977a50d9aa2009-06-08 14:49:45 +00008355static int balance(BtCursor *pCur){
drh43605152004-05-29 21:46:49 +00008356 int rc = SQLITE_OK;
danielk1977a50d9aa2009-06-08 14:49:45 +00008357 const int nMin = pCur->pBt->usableSize * 2 / 3;
8358 u8 aBalanceQuickSpace[13];
8359 u8 *pFree = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00008360
drhcc5f8a42016-02-06 22:32:06 +00008361 VVA_ONLY( int balance_quick_called = 0 );
8362 VVA_ONLY( int balance_deeper_called = 0 );
danielk1977a50d9aa2009-06-08 14:49:45 +00008363
8364 do {
8365 int iPage = pCur->iPage;
8366 MemPage *pPage = pCur->apPage[iPage];
8367
8368 if( iPage==0 ){
8369 if( pPage->nOverflow ){
8370 /* The root page of the b-tree is overfull. In this case call the
8371 ** balance_deeper() function to create a new child for the root-page
8372 ** and copy the current contents of the root-page to it. The
8373 ** next iteration of the do-loop will balance the child page.
8374 */
drhcc5f8a42016-02-06 22:32:06 +00008375 assert( balance_deeper_called==0 );
8376 VVA_ONLY( balance_deeper_called++ );
danielk1977a50d9aa2009-06-08 14:49:45 +00008377 rc = balance_deeper(pPage, &pCur->apPage[1]);
8378 if( rc==SQLITE_OK ){
8379 pCur->iPage = 1;
drh75e96b32017-04-01 00:20:06 +00008380 pCur->ix = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00008381 pCur->aiIdx[0] = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00008382 assert( pCur->apPage[1]->nOverflow );
8383 }
danielk1977a50d9aa2009-06-08 14:49:45 +00008384 }else{
danielk1977a50d9aa2009-06-08 14:49:45 +00008385 break;
8386 }
8387 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
8388 break;
8389 }else{
8390 MemPage * const pParent = pCur->apPage[iPage-1];
8391 int const iIdx = pCur->aiIdx[iPage-1];
8392
8393 rc = sqlite3PagerWrite(pParent->pDbPage);
8394 if( rc==SQLITE_OK ){
8395#ifndef SQLITE_OMIT_QUICKBALANCE
drh3e28ff52014-09-24 00:59:08 +00008396 if( pPage->intKeyLeaf
danielk1977a50d9aa2009-06-08 14:49:45 +00008397 && pPage->nOverflow==1
drh2cbd78b2012-02-02 19:37:18 +00008398 && pPage->aiOvfl[0]==pPage->nCell
danielk1977a50d9aa2009-06-08 14:49:45 +00008399 && pParent->pgno!=1
8400 && pParent->nCell==iIdx
8401 ){
8402 /* Call balance_quick() to create a new sibling of pPage on which
8403 ** to store the overflow cell. balance_quick() inserts a new cell
8404 ** into pParent, which may cause pParent overflow. If this
peter.d.reid60ec9142014-09-06 16:39:46 +00008405 ** happens, the next iteration of the do-loop will balance pParent
danielk1977a50d9aa2009-06-08 14:49:45 +00008406 ** use either balance_nonroot() or balance_deeper(). Until this
8407 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
8408 ** buffer.
8409 **
8410 ** The purpose of the following assert() is to check that only a
8411 ** single call to balance_quick() is made for each call to this
8412 ** function. If this were not verified, a subtle bug involving reuse
8413 ** of the aBalanceQuickSpace[] might sneak in.
8414 */
drhcc5f8a42016-02-06 22:32:06 +00008415 assert( balance_quick_called==0 );
8416 VVA_ONLY( balance_quick_called++ );
danielk1977a50d9aa2009-06-08 14:49:45 +00008417 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
8418 }else
8419#endif
8420 {
8421 /* In this case, call balance_nonroot() to redistribute cells
8422 ** between pPage and up to 2 of its sibling pages. This involves
8423 ** modifying the contents of pParent, which may cause pParent to
8424 ** become overfull or underfull. The next iteration of the do-loop
8425 ** will balance the parent page to correct this.
8426 **
8427 ** If the parent page becomes overfull, the overflow cell or cells
8428 ** are stored in the pSpace buffer allocated immediately below.
8429 ** A subsequent iteration of the do-loop will deal with this by
8430 ** calling balance_nonroot() (balance_deeper() may be called first,
8431 ** but it doesn't deal with overflow cells - just moves them to a
8432 ** different page). Once this subsequent call to balance_nonroot()
8433 ** has completed, it is safe to release the pSpace buffer used by
8434 ** the previous call, as the overflow cell data will have been
8435 ** copied either into the body of a database page or into the new
8436 ** pSpace buffer passed to the latter call to balance_nonroot().
8437 */
8438 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
drhe0997b32015-03-20 14:57:50 +00008439 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
dan7fff2e12017-05-29 14:27:37 +00008440 pCur->hints&BTREE_BULKLOAD, pCur->pgnoRoot);
danielk1977a50d9aa2009-06-08 14:49:45 +00008441 if( pFree ){
8442 /* If pFree is not NULL, it points to the pSpace buffer used
8443 ** by a previous call to balance_nonroot(). Its contents are
8444 ** now stored either on real database pages or within the
8445 ** new pSpace buffer, so it may be safely freed here. */
8446 sqlite3PageFree(pFree);
8447 }
8448
danielk19774dbaa892009-06-16 16:50:22 +00008449 /* The pSpace buffer will be freed after the next call to
8450 ** balance_nonroot(), or just before this function returns, whichever
8451 ** comes first. */
danielk1977a50d9aa2009-06-08 14:49:45 +00008452 pFree = pSpace;
danielk1977a50d9aa2009-06-08 14:49:45 +00008453 }
8454 }
8455
8456 pPage->nOverflow = 0;
8457
8458 /* The next iteration of the do-loop balances the parent page. */
8459 releasePage(pPage);
8460 pCur->iPage--;
drhcbd33492015-03-25 13:06:54 +00008461 assert( pCur->iPage>=0 );
drh43605152004-05-29 21:46:49 +00008462 }
danielk1977a50d9aa2009-06-08 14:49:45 +00008463 }while( rc==SQLITE_OK );
8464
8465 if( pFree ){
8466 sqlite3PageFree(pFree);
drh43605152004-05-29 21:46:49 +00008467 }
8468 return rc;
8469}
8470
drhf74b8d92002-09-01 23:20:45 +00008471
8472/*
drh8eeb4462016-05-21 20:03:42 +00008473** Insert a new record into the BTree. The content of the new record
8474** is described by the pX object. The pCur cursor is used only to
8475** define what table the record should be inserted into, and is left
8476** pointing at a random location.
drh4b70f112004-05-02 21:12:19 +00008477**
drh8eeb4462016-05-21 20:03:42 +00008478** For a table btree (used for rowid tables), only the pX.nKey value of
8479** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
8480** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
8481** hold the content of the row.
8482**
8483** For an index btree (used for indexes and WITHOUT ROWID tables), the
8484** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
8485** pX.pData,nData,nZero fields must be zero.
danielk1977de630352009-05-04 11:42:29 +00008486**
8487** If the seekResult parameter is non-zero, then a successful call to
drheaf6ae22016-11-09 20:14:34 +00008488** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
8489** been performed. In other words, if seekResult!=0 then the cursor
8490** is currently pointing to a cell that will be adjacent to the cell
8491** to be inserted. If seekResult<0 then pCur points to a cell that is
8492** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
8493** that is larger than (pKey,nKey).
danielk1977de630352009-05-04 11:42:29 +00008494**
drheaf6ae22016-11-09 20:14:34 +00008495** If seekResult==0, that means pCur is pointing at some unknown location.
8496** In that case, this routine must seek the cursor to the correct insertion
8497** point for (pKey,nKey) before doing the insertion. For index btrees,
8498** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
8499** key values and pX->aMem can be used instead of pX->pKey to avoid having
8500** to decode the key.
drh3b7511c2001-05-26 13:15:44 +00008501*/
drh3aac2dd2004-04-26 14:10:20 +00008502int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00008503 BtCursor *pCur, /* Insert data into the table of this cursor */
drh8eeb4462016-05-21 20:03:42 +00008504 const BtreePayload *pX, /* Content of the row to be inserted */
danf91c1312017-01-10 20:04:38 +00008505 int flags, /* True if this is likely an append */
danielk19773509a652009-07-06 18:56:13 +00008506 int seekResult /* Result of prior MovetoUnpacked() call */
drh3b7511c2001-05-26 13:15:44 +00008507){
drh3b7511c2001-05-26 13:15:44 +00008508 int rc;
drh3e9ca092009-09-08 01:14:48 +00008509 int loc = seekResult; /* -1: before desired location +1: after */
drh1d452e12009-11-01 19:26:59 +00008510 int szNew = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00008511 int idx;
drh3b7511c2001-05-26 13:15:44 +00008512 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00008513 Btree *p = pCur->pBtree;
8514 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00008515 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00008516 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00008517
danf91c1312017-01-10 20:04:38 +00008518 assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
8519
drh98add2e2009-07-20 17:11:49 +00008520 if( pCur->eState==CURSOR_FAULT ){
8521 assert( pCur->skipNext!=SQLITE_OK );
8522 return pCur->skipNext;
8523 }
8524
dan7a2347e2016-01-07 16:43:54 +00008525 assert( cursorOwnsBtShared(pCur) );
drh3f387402014-09-24 01:23:00 +00008526 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
8527 && pBt->inTransaction==TRANS_WRITE
drhc9166342012-01-05 23:32:06 +00008528 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk197796d48e92009-06-29 06:00:37 +00008529 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8530
danielk197731d31b82009-07-13 13:18:07 +00008531 /* Assert that the caller has been consistent. If this cursor was opened
8532 ** expecting an index b-tree, then the caller should be inserting blob
8533 ** keys with no associated data. If the cursor was opened expecting an
8534 ** intkey table, the caller should be inserting integer keys with a
8535 ** blob of associated data. */
drh8eeb4462016-05-21 20:03:42 +00008536 assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
danielk197731d31b82009-07-13 13:18:07 +00008537
danielk19779c3acf32009-05-02 07:36:49 +00008538 /* Save the positions of any other cursors open on this table.
8539 **
danielk19773509a652009-07-06 18:56:13 +00008540 ** In some cases, the call to btreeMoveto() below is a no-op. For
danielk19779c3acf32009-05-02 07:36:49 +00008541 ** example, when inserting data into a table with auto-generated integer
8542 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
8543 ** integer key to use. It then calls this function to actually insert the
danielk19773509a652009-07-06 18:56:13 +00008544 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
danielk19779c3acf32009-05-02 07:36:49 +00008545 ** that the cursor is already where it needs to be and returns without
8546 ** doing any work. To avoid thwarting these optimizations, it is important
8547 ** not to clear the cursor here.
8548 */
drh27fb7462015-06-30 02:47:36 +00008549 if( pCur->curFlags & BTCF_Multiple ){
8550 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8551 if( rc ) return rc;
8552 }
drhd60f4f42012-03-23 14:23:52 +00008553
drhd60f4f42012-03-23 14:23:52 +00008554 if( pCur->pKeyInfo==0 ){
drh8eeb4462016-05-21 20:03:42 +00008555 assert( pX->pKey==0 );
drhe0670b62014-02-12 21:31:12 +00008556 /* If this is an insert into a table b-tree, invalidate any incrblob
8557 ** cursors open on the row being replaced */
drh9ca431a2017-03-29 18:03:50 +00008558 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
drhe0670b62014-02-12 21:31:12 +00008559
danf91c1312017-01-10 20:04:38 +00008560 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8561 ** to a row with the same key as the new entry being inserted. */
8562 assert( (flags & BTREE_SAVEPOSITION)==0 ||
8563 ((pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey) );
8564
drhe0670b62014-02-12 21:31:12 +00008565 /* If the cursor is currently on the last row and we are appending a
drh207c8172015-06-29 23:01:32 +00008566 ** new row onto the end, set the "loc" to avoid an unnecessary
8567 ** btreeMoveto() call */
drh7a1c28d2016-11-10 20:42:08 +00008568 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
8569 loc = 0;
drh207c8172015-06-29 23:01:32 +00008570 }else if( loc==0 ){
danf91c1312017-01-10 20:04:38 +00008571 rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
drh207c8172015-06-29 23:01:32 +00008572 if( rc ) return rc;
drhe0670b62014-02-12 21:31:12 +00008573 }
danf91c1312017-01-10 20:04:38 +00008574 }else if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
drh9b4eaeb2016-11-09 00:10:33 +00008575 if( pX->nMem ){
8576 UnpackedRecord r;
drh9b4eaeb2016-11-09 00:10:33 +00008577 r.pKeyInfo = pCur->pKeyInfo;
8578 r.aMem = pX->aMem;
8579 r.nField = pX->nMem;
drh8c730bc2016-12-10 13:12:55 +00008580 r.default_rc = 0;
8581 r.errCode = 0;
8582 r.r1 = 0;
8583 r.r2 = 0;
8584 r.eqSeen = 0;
danf91c1312017-01-10 20:04:38 +00008585 rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
drh9b4eaeb2016-11-09 00:10:33 +00008586 }else{
danf91c1312017-01-10 20:04:38 +00008587 rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
drh9b4eaeb2016-11-09 00:10:33 +00008588 }
drh4c301aa2009-07-15 17:25:45 +00008589 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00008590 }
danielk1977b980d2212009-06-22 18:03:51 +00008591 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
danielk1977da184232006-01-05 11:34:32 +00008592
danielk197771d5d2c2008-09-29 11:49:47 +00008593 pPage = pCur->apPage[pCur->iPage];
drh8eeb4462016-05-21 20:03:42 +00008594 assert( pPage->intKey || pX->nKey>=0 );
drh44845222008-07-17 18:39:57 +00008595 assert( pPage->leaf || !pPage->intKey );
danielk19778f880a82009-07-13 09:41:45 +00008596
drh3a4c1412004-05-09 20:40:11 +00008597 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
drh8eeb4462016-05-21 20:03:42 +00008598 pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
drh3a4c1412004-05-09 20:40:11 +00008599 loc==0 ? "overwrite" : "new entry"));
danielk197771d5d2c2008-09-29 11:49:47 +00008600 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00008601 newCell = pBt->pTmpSpace;
drh3fbb0222014-09-24 19:47:27 +00008602 assert( newCell!=0 );
drh8eeb4462016-05-21 20:03:42 +00008603 rc = fillInCell(pPage, newCell, pX, &szNew);
drh2e38c322004-09-03 18:38:44 +00008604 if( rc ) goto end_insert;
drh25ada072015-06-19 15:07:14 +00008605 assert( szNew==pPage->xCellSize(pPage, newCell) );
drhfcd71b62011-04-05 22:08:24 +00008606 assert( szNew <= MX_CELL_SIZE(pBt) );
drh75e96b32017-04-01 00:20:06 +00008607 idx = pCur->ix;
danielk1977b980d2212009-06-22 18:03:51 +00008608 if( loc==0 ){
drh80159da2016-12-09 17:32:51 +00008609 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00008610 assert( idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00008611 rc = sqlite3PagerWrite(pPage->pDbPage);
8612 if( rc ){
8613 goto end_insert;
8614 }
danielk197771d5d2c2008-09-29 11:49:47 +00008615 oldCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00008616 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00008617 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00008618 }
drh80159da2016-12-09 17:32:51 +00008619 rc = clearCell(pPage, oldCell, &info);
drh50179f92017-06-08 11:26:13 +00008620 if( info.nSize==szNew && info.nLocal==info.nPayload
dan4956bd52017-06-08 16:23:55 +00008621 && (!REQUIRE_PTRMAP || szNew<pPage->minLocal)
drh50179f92017-06-08 11:26:13 +00008622 ){
drhf9238252016-12-09 18:09:42 +00008623 /* Overwrite the old cell with the new if they are the same size.
8624 ** We could also try to do this if the old cell is smaller, then add
8625 ** the leftover space to the free list. But experiments show that
8626 ** doing that is no faster then skipping this optimization and just
drh50179f92017-06-08 11:26:13 +00008627 ** calling dropCell() and insertCell().
8628 **
8629 ** This optimization cannot be used on an autovacuum database if the
8630 ** new entry uses overflow pages, as the insertCell() call below is
8631 ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
drhf9238252016-12-09 18:09:42 +00008632 assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
drh2d083432016-12-09 19:42:18 +00008633 if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
drh80159da2016-12-09 17:32:51 +00008634 memcpy(oldCell, newCell, szNew);
8635 return SQLITE_OK;
8636 }
8637 dropCell(pPage, idx, info.nSize, &rc);
drh2e38c322004-09-03 18:38:44 +00008638 if( rc ) goto end_insert;
drh7c717f72001-06-24 20:39:41 +00008639 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00008640 assert( pPage->leaf );
drh75e96b32017-04-01 00:20:06 +00008641 idx = ++pCur->ix;
dan874080b2017-05-01 18:12:56 +00008642 pCur->curFlags &= ~BTCF_ValidNKey;
drh14acc042001-06-10 19:56:58 +00008643 }else{
drh4b70f112004-05-02 21:12:19 +00008644 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00008645 }
drh98add2e2009-07-20 17:11:49 +00008646 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
drh09a4e922016-05-21 12:29:04 +00008647 assert( pPage->nOverflow==0 || rc==SQLITE_OK );
danielk19773f632d52009-05-02 10:03:09 +00008648 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
drh9bf9e9c2008-12-05 20:01:43 +00008649
mistachkin48864df2013-03-21 21:20:32 +00008650 /* If no error has occurred and pPage has an overflow cell, call balance()
danielk1977a50d9aa2009-06-08 14:49:45 +00008651 ** to redistribute the cells within the tree. Since balance() may move
drh036dbec2014-03-11 23:40:44 +00008652 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
danielk1977a50d9aa2009-06-08 14:49:45 +00008653 ** variables.
danielk19773f632d52009-05-02 10:03:09 +00008654 **
danielk1977a50d9aa2009-06-08 14:49:45 +00008655 ** Previous versions of SQLite called moveToRoot() to move the cursor
8656 ** back to the root page as balance() used to invalidate the contents
danielk197754109bb2009-06-23 11:22:29 +00008657 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
8658 ** set the cursor state to "invalid". This makes common insert operations
8659 ** slightly faster.
danielk19773f632d52009-05-02 10:03:09 +00008660 **
danielk1977a50d9aa2009-06-08 14:49:45 +00008661 ** There is a subtle but important optimization here too. When inserting
8662 ** multiple records into an intkey b-tree using a single cursor (as can
8663 ** happen while processing an "INSERT INTO ... SELECT" statement), it
8664 ** is advantageous to leave the cursor pointing to the last entry in
8665 ** the b-tree if possible. If the cursor is left pointing to the last
8666 ** entry in the table, and the next row inserted has an integer key
8667 ** larger than the largest existing key, it is possible to insert the
8668 ** row without seeking the cursor. This can be a big performance boost.
danielk19773f632d52009-05-02 10:03:09 +00008669 */
danielk1977a50d9aa2009-06-08 14:49:45 +00008670 pCur->info.nSize = 0;
drh09a4e922016-05-21 12:29:04 +00008671 if( pPage->nOverflow ){
8672 assert( rc==SQLITE_OK );
drh036dbec2014-03-11 23:40:44 +00008673 pCur->curFlags &= ~(BTCF_ValidNKey);
danielk1977a50d9aa2009-06-08 14:49:45 +00008674 rc = balance(pCur);
8675
8676 /* Must make sure nOverflow is reset to zero even if the balance()
danielk197754109bb2009-06-23 11:22:29 +00008677 ** fails. Internal data structure corruption will result otherwise.
8678 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
8679 ** from trying to save the current position of the cursor. */
danielk1977a50d9aa2009-06-08 14:49:45 +00008680 pCur->apPage[pCur->iPage]->nOverflow = 0;
danielk197754109bb2009-06-23 11:22:29 +00008681 pCur->eState = CURSOR_INVALID;
danf91c1312017-01-10 20:04:38 +00008682 if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
8683 rc = moveToRoot(pCur);
drh7b20a152017-01-12 19:10:55 +00008684 if( pCur->pKeyInfo ){
danf91c1312017-01-10 20:04:38 +00008685 assert( pCur->pKey==0 );
8686 pCur->pKey = sqlite3Malloc( pX->nKey );
8687 if( pCur->pKey==0 ){
8688 rc = SQLITE_NOMEM;
8689 }else{
8690 memcpy(pCur->pKey, pX->pKey, pX->nKey);
8691 }
8692 }
8693 pCur->eState = CURSOR_REQUIRESEEK;
8694 pCur->nKey = pX->nKey;
8695 }
danielk19773f632d52009-05-02 10:03:09 +00008696 }
danielk1977a50d9aa2009-06-08 14:49:45 +00008697 assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
drh9bf9e9c2008-12-05 20:01:43 +00008698
drh2e38c322004-09-03 18:38:44 +00008699end_insert:
drh5e2f8b92001-05-28 00:41:15 +00008700 return rc;
8701}
8702
8703/*
danf0ee1d32015-09-12 19:26:11 +00008704** Delete the entry that the cursor is pointing to.
8705**
drhe807bdb2016-01-21 17:06:33 +00008706** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
8707** the cursor is left pointing at an arbitrary location after the delete.
8708** But if that bit is set, then the cursor is left in a state such that
8709** the next call to BtreeNext() or BtreePrev() moves it to the same row
8710** as it would have been on if the call to BtreeDelete() had been omitted.
8711**
drhdef19e32016-01-27 16:26:25 +00008712** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
8713** associated with a single table entry and its indexes. Only one of those
8714** deletes is considered the "primary" delete. The primary delete occurs
8715** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
8716** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
8717** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
drhe807bdb2016-01-21 17:06:33 +00008718** but which might be used by alternative storage engines.
drh3b7511c2001-05-26 13:15:44 +00008719*/
drhe807bdb2016-01-21 17:06:33 +00008720int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
drhd677b3d2007-08-20 22:48:41 +00008721 Btree *p = pCur->pBtree;
danielk19774dbaa892009-06-16 16:50:22 +00008722 BtShared *pBt = p->pBt;
8723 int rc; /* Return code */
8724 MemPage *pPage; /* Page to delete cell from */
8725 unsigned char *pCell; /* Pointer to cell to delete */
8726 int iCellIdx; /* Index of cell to delete */
8727 int iCellDepth; /* Depth of node containing pCell */
drh80159da2016-12-09 17:32:51 +00008728 CellInfo info; /* Size of the cell being deleted */
danf0ee1d32015-09-12 19:26:11 +00008729 int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
drhe807bdb2016-01-21 17:06:33 +00008730 u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
drh8b2f49b2001-06-08 00:21:52 +00008731
dan7a2347e2016-01-07 16:43:54 +00008732 assert( cursorOwnsBtShared(pCur) );
drh64022502009-01-09 14:11:04 +00008733 assert( pBt->inTransaction==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00008734 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
drh036dbec2014-03-11 23:40:44 +00008735 assert( pCur->curFlags & BTCF_WriteFlag );
danielk197796d48e92009-06-29 06:00:37 +00008736 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8737 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
drh75e96b32017-04-01 00:20:06 +00008738 assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
drh98ef0f62015-06-30 01:25:52 +00008739 assert( pCur->eState==CURSOR_VALID );
drhdef19e32016-01-27 16:26:25 +00008740 assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
danielk1977da184232006-01-05 11:34:32 +00008741
danielk19774dbaa892009-06-16 16:50:22 +00008742 iCellDepth = pCur->iPage;
drh75e96b32017-04-01 00:20:06 +00008743 iCellIdx = pCur->ix;
danielk19774dbaa892009-06-16 16:50:22 +00008744 pPage = pCur->apPage[iCellDepth];
8745 pCell = findCell(pPage, iCellIdx);
8746
drhbfc7a8b2016-04-09 17:04:05 +00008747 /* If the bPreserve flag is set to true, then the cursor position must
8748 ** be preserved following this delete operation. If the current delete
8749 ** will cause a b-tree rebalance, then this is done by saving the cursor
8750 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
8751 ** returning.
8752 **
8753 ** Or, if the current delete will not cause a rebalance, then the cursor
8754 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
8755 ** before or after the deleted entry. In this case set bSkipnext to true. */
8756 if( bPreserve ){
8757 if( !pPage->leaf
8758 || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
8759 ){
8760 /* A b-tree rebalance will be required after deleting this entry.
8761 ** Save the cursor key. */
8762 rc = saveCursorKey(pCur);
8763 if( rc ) return rc;
8764 }else{
8765 bSkipnext = 1;
8766 }
8767 }
8768
danielk19774dbaa892009-06-16 16:50:22 +00008769 /* If the page containing the entry to delete is not a leaf page, move
8770 ** the cursor to the largest entry in the tree that is smaller than
8771 ** the entry being deleted. This cell will replace the cell being deleted
8772 ** from the internal node. The 'previous' entry is used for this instead
8773 ** of the 'next' entry, as the previous entry is always a part of the
8774 ** sub-tree headed by the child page of the cell being deleted. This makes
8775 ** balancing the tree following the delete operation easier. */
8776 if( !pPage->leaf ){
drh2ab792e2017-05-30 18:34:07 +00008777 rc = sqlite3BtreePrevious(pCur, 0);
8778 assert( rc!=SQLITE_DONE );
drh4c301aa2009-07-15 17:25:45 +00008779 if( rc ) return rc;
danielk19774dbaa892009-06-16 16:50:22 +00008780 }
8781
8782 /* Save the positions of any other cursors open on this table before
danf0ee1d32015-09-12 19:26:11 +00008783 ** making any modifications. */
drh27fb7462015-06-30 02:47:36 +00008784 if( pCur->curFlags & BTCF_Multiple ){
8785 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8786 if( rc ) return rc;
8787 }
drhd60f4f42012-03-23 14:23:52 +00008788
8789 /* If this is a delete operation to remove a row from a table b-tree,
8790 ** invalidate any incrblob cursors open on the row being deleted. */
8791 if( pCur->pKeyInfo==0 ){
drh9ca431a2017-03-29 18:03:50 +00008792 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
drhd60f4f42012-03-23 14:23:52 +00008793 }
8794
danf0ee1d32015-09-12 19:26:11 +00008795 /* Make the page containing the entry to be deleted writable. Then free any
8796 ** overflow pages associated with the entry and finally remove the cell
8797 ** itself from within the page. */
drha4ec1d42009-07-11 13:13:11 +00008798 rc = sqlite3PagerWrite(pPage->pDbPage);
8799 if( rc ) return rc;
drh80159da2016-12-09 17:32:51 +00008800 rc = clearCell(pPage, pCell, &info);
8801 dropCell(pPage, iCellIdx, info.nSize, &rc);
drha4ec1d42009-07-11 13:13:11 +00008802 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00008803
danielk19774dbaa892009-06-16 16:50:22 +00008804 /* If the cell deleted was not located on a leaf page, then the cursor
8805 ** is currently pointing to the largest entry in the sub-tree headed
8806 ** by the child-page of the cell that was just deleted from an internal
8807 ** node. The cell from the leaf node needs to be moved to the internal
8808 ** node to replace the deleted cell. */
drh4b70f112004-05-02 21:12:19 +00008809 if( !pPage->leaf ){
danielk19774dbaa892009-06-16 16:50:22 +00008810 MemPage *pLeaf = pCur->apPage[pCur->iPage];
8811 int nCell;
8812 Pgno n = pCur->apPage[iCellDepth+1]->pgno;
8813 unsigned char *pTmp;
danielk1977e6efa742004-11-10 11:55:10 +00008814
danielk19774dbaa892009-06-16 16:50:22 +00008815 pCell = findCell(pLeaf, pLeaf->nCell-1);
drhb468ce12015-06-24 01:07:30 +00008816 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
drh25ada072015-06-19 15:07:14 +00008817 nCell = pLeaf->xCellSize(pLeaf, pCell);
drhfcd71b62011-04-05 22:08:24 +00008818 assert( MX_CELL_SIZE(pBt) >= nCell );
danielk19774dbaa892009-06-16 16:50:22 +00008819 pTmp = pBt->pTmpSpace;
drh3fbb0222014-09-24 19:47:27 +00008820 assert( pTmp!=0 );
drha4ec1d42009-07-11 13:13:11 +00008821 rc = sqlite3PagerWrite(pLeaf->pDbPage);
drhcb89f4a2016-05-21 11:23:26 +00008822 if( rc==SQLITE_OK ){
8823 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
8824 }
drh98add2e2009-07-20 17:11:49 +00008825 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
drha4ec1d42009-07-11 13:13:11 +00008826 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00008827 }
danielk19774dbaa892009-06-16 16:50:22 +00008828
8829 /* Balance the tree. If the entry deleted was located on a leaf page,
8830 ** then the cursor still points to that page. In this case the first
8831 ** call to balance() repairs the tree, and the if(...) condition is
8832 ** never true.
8833 **
8834 ** Otherwise, if the entry deleted was on an internal node page, then
8835 ** pCur is pointing to the leaf page from which a cell was removed to
8836 ** replace the cell deleted from the internal node. This is slightly
8837 ** tricky as the leaf node may be underfull, and the internal node may
8838 ** be either under or overfull. In this case run the balancing algorithm
8839 ** on the leaf node first. If the balance proceeds far enough up the
8840 ** tree that we can be sure that any problem in the internal node has
8841 ** been corrected, so be it. Otherwise, after balancing the leaf node,
8842 ** walk the cursor up the tree to the internal node and balance it as
8843 ** well. */
8844 rc = balance(pCur);
8845 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
8846 while( pCur->iPage>iCellDepth ){
8847 releasePage(pCur->apPage[pCur->iPage--]);
8848 }
8849 rc = balance(pCur);
8850 }
8851
danielk19776b456a22005-03-21 04:04:02 +00008852 if( rc==SQLITE_OK ){
danf0ee1d32015-09-12 19:26:11 +00008853 if( bSkipnext ){
drha660caf2016-01-01 03:37:44 +00008854 assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
drh38bace82016-02-01 00:21:08 +00008855 assert( pPage==pCur->apPage[pCur->iPage] || CORRUPT_DB );
drh78ac1092015-09-20 22:57:47 +00008856 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
danf0ee1d32015-09-12 19:26:11 +00008857 pCur->eState = CURSOR_SKIPNEXT;
8858 if( iCellIdx>=pPage->nCell ){
8859 pCur->skipNext = -1;
drh75e96b32017-04-01 00:20:06 +00008860 pCur->ix = pPage->nCell-1;
danf0ee1d32015-09-12 19:26:11 +00008861 }else{
8862 pCur->skipNext = 1;
8863 }
8864 }else{
8865 rc = moveToRoot(pCur);
8866 if( bPreserve ){
8867 pCur->eState = CURSOR_REQUIRESEEK;
8868 }
8869 }
danielk19776b456a22005-03-21 04:04:02 +00008870 }
drh5e2f8b92001-05-28 00:41:15 +00008871 return rc;
drh3b7511c2001-05-26 13:15:44 +00008872}
drh8b2f49b2001-06-08 00:21:52 +00008873
8874/*
drhc6b52df2002-01-04 03:09:29 +00008875** Create a new BTree table. Write into *piTable the page
8876** number for the root page of the new table.
8877**
drhab01f612004-05-22 02:55:23 +00008878** The type of type is determined by the flags parameter. Only the
8879** following values of flags are currently in use. Other values for
8880** flags might not work:
8881**
8882** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
8883** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00008884*/
drhd4187c72010-08-30 22:15:45 +00008885static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
danielk1977aef0bf62005-12-30 16:28:01 +00008886 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00008887 MemPage *pRoot;
8888 Pgno pgnoRoot;
8889 int rc;
drhd4187c72010-08-30 22:15:45 +00008890 int ptfFlags; /* Page-type flage for the root page of new table */
drhd677b3d2007-08-20 22:48:41 +00008891
drh1fee73e2007-08-29 04:00:57 +00008892 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00008893 assert( pBt->inTransaction==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00008894 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk1977e6efa742004-11-10 11:55:10 +00008895
danielk1977003ba062004-11-04 02:57:33 +00008896#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00008897 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00008898 if( rc ){
8899 return rc;
8900 }
danielk1977003ba062004-11-04 02:57:33 +00008901#else
danielk1977687566d2004-11-02 12:56:41 +00008902 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00008903 Pgno pgnoMove; /* Move a page here to make room for the root-page */
8904 MemPage *pPageMove; /* The page to move to. */
8905
danielk197720713f32007-05-03 11:43:33 +00008906 /* Creating a new table may probably require moving an existing database
8907 ** to make room for the new tables root page. In case this page turns
8908 ** out to be an overflow page, delete all overflow page-map caches
8909 ** held by open cursors.
8910 */
danielk197792d4d7a2007-05-04 12:05:56 +00008911 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00008912
danielk1977003ba062004-11-04 02:57:33 +00008913 /* Read the value of meta[3] from the database to determine where the
8914 ** root page of the new table should go. meta[3] is the largest root-page
8915 ** created so far, so the new root-page is (meta[3]+1).
8916 */
danielk1977602b4662009-07-02 07:47:33 +00008917 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00008918 pgnoRoot++;
8919
danielk1977599fcba2004-11-08 07:13:13 +00008920 /* The new root-page may not be allocated on a pointer-map page, or the
8921 ** PENDING_BYTE page.
8922 */
drh72190432008-01-31 14:54:43 +00008923 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00008924 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00008925 pgnoRoot++;
8926 }
drh499e15b2015-05-22 12:37:37 +00008927 assert( pgnoRoot>=3 || CORRUPT_DB );
8928 testcase( pgnoRoot<3 );
danielk1977003ba062004-11-04 02:57:33 +00008929
8930 /* Allocate a page. The page that currently resides at pgnoRoot will
8931 ** be moved to the allocated page (unless the allocated page happens
8932 ** to reside at pgnoRoot).
8933 */
dan51f0b6d2013-02-22 20:16:34 +00008934 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
danielk1977003ba062004-11-04 02:57:33 +00008935 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00008936 return rc;
8937 }
danielk1977003ba062004-11-04 02:57:33 +00008938
8939 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00008940 /* pgnoRoot is the page that will be used for the root-page of
8941 ** the new table (assuming an error did not occur). But we were
8942 ** allocated pgnoMove. If required (i.e. if it was not allocated
8943 ** by extending the file), the current page at position pgnoMove
8944 ** is already journaled.
8945 */
drheeb844a2009-08-08 18:01:07 +00008946 u8 eType = 0;
8947 Pgno iPtrPage = 0;
danielk1977003ba062004-11-04 02:57:33 +00008948
danf7679ad2013-04-03 11:38:36 +00008949 /* Save the positions of any open cursors. This is required in
8950 ** case they are holding a reference to an xFetch reference
8951 ** corresponding to page pgnoRoot. */
8952 rc = saveAllCursors(pBt, 0, 0);
danielk1977003ba062004-11-04 02:57:33 +00008953 releasePage(pPageMove);
danf7679ad2013-04-03 11:38:36 +00008954 if( rc!=SQLITE_OK ){
8955 return rc;
8956 }
danielk1977f35843b2007-04-07 15:03:17 +00008957
8958 /* Move the page currently at pgnoRoot to pgnoMove. */
drhb00fc3b2013-08-21 23:42:32 +00008959 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00008960 if( rc!=SQLITE_OK ){
8961 return rc;
8962 }
8963 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drh27731d72009-06-22 12:05:10 +00008964 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
8965 rc = SQLITE_CORRUPT_BKPT;
8966 }
8967 if( rc!=SQLITE_OK ){
danielk1977003ba062004-11-04 02:57:33 +00008968 releasePage(pRoot);
8969 return rc;
8970 }
drhccae6022005-02-26 17:31:26 +00008971 assert( eType!=PTRMAP_ROOTPAGE );
8972 assert( eType!=PTRMAP_FREEPAGE );
danielk19774c999992008-07-16 18:17:55 +00008973 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +00008974 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00008975
8976 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00008977 if( rc!=SQLITE_OK ){
8978 return rc;
8979 }
drhb00fc3b2013-08-21 23:42:32 +00008980 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00008981 if( rc!=SQLITE_OK ){
8982 return rc;
8983 }
danielk19773b8a05f2007-03-19 17:44:26 +00008984 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00008985 if( rc!=SQLITE_OK ){
8986 releasePage(pRoot);
8987 return rc;
8988 }
8989 }else{
8990 pRoot = pPageMove;
8991 }
8992
danielk197742741be2005-01-08 12:42:39 +00008993 /* Update the pointer-map and meta-data with the new root-page number. */
drh98add2e2009-07-20 17:11:49 +00008994 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
danielk1977003ba062004-11-04 02:57:33 +00008995 if( rc ){
8996 releasePage(pRoot);
8997 return rc;
8998 }
drhbf592832010-03-30 15:51:12 +00008999
9000 /* When the new root page was allocated, page 1 was made writable in
9001 ** order either to increase the database filesize, or to decrement the
9002 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
9003 */
9004 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
danielk1977aef0bf62005-12-30 16:28:01 +00009005 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
drhbf592832010-03-30 15:51:12 +00009006 if( NEVER(rc) ){
danielk1977003ba062004-11-04 02:57:33 +00009007 releasePage(pRoot);
9008 return rc;
9009 }
danielk197742741be2005-01-08 12:42:39 +00009010
danielk1977003ba062004-11-04 02:57:33 +00009011 }else{
drh4f0c5872007-03-26 22:05:01 +00009012 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00009013 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00009014 }
9015#endif
danielk19773b8a05f2007-03-19 17:44:26 +00009016 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhd4187c72010-08-30 22:15:45 +00009017 if( createTabFlags & BTREE_INTKEY ){
9018 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
9019 }else{
9020 ptfFlags = PTF_ZERODATA | PTF_LEAF;
9021 }
9022 zeroPage(pRoot, ptfFlags);
danielk19773b8a05f2007-03-19 17:44:26 +00009023 sqlite3PagerUnref(pRoot->pDbPage);
drhd4187c72010-08-30 22:15:45 +00009024 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
drh8b2f49b2001-06-08 00:21:52 +00009025 *piTable = (int)pgnoRoot;
9026 return SQLITE_OK;
9027}
drhd677b3d2007-08-20 22:48:41 +00009028int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
9029 int rc;
9030 sqlite3BtreeEnter(p);
9031 rc = btreeCreateTable(p, piTable, flags);
9032 sqlite3BtreeLeave(p);
9033 return rc;
9034}
drh8b2f49b2001-06-08 00:21:52 +00009035
9036/*
9037** Erase the given database page and all its children. Return
9038** the page to the freelist.
9039*/
drh4b70f112004-05-02 21:12:19 +00009040static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00009041 BtShared *pBt, /* The BTree that contains the table */
drh7ab641f2009-11-24 02:37:02 +00009042 Pgno pgno, /* Page number to clear */
9043 int freePageFlag, /* Deallocate page if true */
dan7fff2e12017-05-29 14:27:37 +00009044 int *pnChange, /* Add number of Cells freed to this counter */
9045 Pgno pgnoRoot
drh4b70f112004-05-02 21:12:19 +00009046){
danielk1977146ba992009-07-22 14:08:13 +00009047 MemPage *pPage;
drh8b2f49b2001-06-08 00:21:52 +00009048 int rc;
drh4b70f112004-05-02 21:12:19 +00009049 unsigned char *pCell;
9050 int i;
dan8ce71842014-01-14 20:14:09 +00009051 int hdr;
drh80159da2016-12-09 17:32:51 +00009052 CellInfo info;
drh8b2f49b2001-06-08 00:21:52 +00009053
drh1fee73e2007-08-29 04:00:57 +00009054 assert( sqlite3_mutex_held(pBt->mutex) );
drhb1299152010-03-30 22:58:33 +00009055 if( pgno>btreePagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00009056 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00009057 }
drh28f58dd2015-06-27 19:45:03 +00009058 rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
danielk1977146ba992009-07-22 14:08:13 +00009059 if( rc ) return rc;
dan7fff2e12017-05-29 14:27:37 +00009060 setMempageRoot(pPage, pgnoRoot);
drhccf46d02015-04-01 13:21:33 +00009061 if( pPage->bBusy ){
9062 rc = SQLITE_CORRUPT_BKPT;
9063 goto cleardatabasepage_out;
9064 }
9065 pPage->bBusy = 1;
dan8ce71842014-01-14 20:14:09 +00009066 hdr = pPage->hdrOffset;
drh4b70f112004-05-02 21:12:19 +00009067 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00009068 pCell = findCell(pPage, i);
drhccf46d02015-04-01 13:21:33 +00009069 if( !pPage->leaf ){
dan7fff2e12017-05-29 14:27:37 +00009070 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange, pgnoRoot);
danielk19776b456a22005-03-21 04:04:02 +00009071 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00009072 }
drh80159da2016-12-09 17:32:51 +00009073 rc = clearCell(pPage, pCell, &info);
danielk19776b456a22005-03-21 04:04:02 +00009074 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00009075 }
drhccf46d02015-04-01 13:21:33 +00009076 if( !pPage->leaf ){
dan7fff2e12017-05-29 14:27:37 +00009077 rc = clearDatabasePage(
9078 pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange, pgnoRoot
9079 );
danielk19776b456a22005-03-21 04:04:02 +00009080 if( rc ) goto cleardatabasepage_out;
danielk1977c7af4842008-10-27 13:59:33 +00009081 }else if( pnChange ){
drhafe028a2015-05-22 13:09:50 +00009082 assert( pPage->intKey || CORRUPT_DB );
9083 testcase( !pPage->intKey );
danielk1977c7af4842008-10-27 13:59:33 +00009084 *pnChange += pPage->nCell;
drh2aa679f2001-06-25 02:11:07 +00009085 }
9086 if( freePageFlag ){
drhc314dc72009-07-21 11:52:34 +00009087 freePage(pPage, &rc);
danielk19773b8a05f2007-03-19 17:44:26 +00009088 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
dan8ce71842014-01-14 20:14:09 +00009089 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00009090 }
danielk19776b456a22005-03-21 04:04:02 +00009091
9092cleardatabasepage_out:
drhccf46d02015-04-01 13:21:33 +00009093 pPage->bBusy = 0;
drh4b70f112004-05-02 21:12:19 +00009094 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00009095 return rc;
drh8b2f49b2001-06-08 00:21:52 +00009096}
9097
9098/*
drhab01f612004-05-22 02:55:23 +00009099** Delete all information from a single table in the database. iTable is
9100** the page number of the root of the table. After this routine returns,
9101** the root page is empty, but still exists.
9102**
9103** This routine will fail with SQLITE_LOCKED if there are any open
9104** read cursors on the table. Open write cursors are moved to the
9105** root of the table.
danielk1977c7af4842008-10-27 13:59:33 +00009106**
9107** If pnChange is not NULL, then table iTable must be an intkey table. The
9108** integer value pointed to by pnChange is incremented by the number of
9109** entries in the table.
drh8b2f49b2001-06-08 00:21:52 +00009110*/
danielk1977c7af4842008-10-27 13:59:33 +00009111int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
drh8b2f49b2001-06-08 00:21:52 +00009112 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00009113 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00009114 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00009115 assert( p->inTrans==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +00009116
drhc046e3e2009-07-15 11:26:44 +00009117 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
drhd60f4f42012-03-23 14:23:52 +00009118
drhc046e3e2009-07-15 11:26:44 +00009119 if( SQLITE_OK==rc ){
drhd60f4f42012-03-23 14:23:52 +00009120 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
9121 ** is the root of a table b-tree - if it is not, the following call is
9122 ** a no-op). */
drh9ca431a2017-03-29 18:03:50 +00009123 invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
dan7fff2e12017-05-29 14:27:37 +00009124 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange, (Pgno)iTable);
drh8b2f49b2001-06-08 00:21:52 +00009125 }
drhd677b3d2007-08-20 22:48:41 +00009126 sqlite3BtreeLeave(p);
9127 return rc;
drh8b2f49b2001-06-08 00:21:52 +00009128}
9129
9130/*
drh079a3072014-03-19 14:10:55 +00009131** Delete all information from the single table that pCur is open on.
9132**
9133** This routine only work for pCur on an ephemeral table.
9134*/
9135int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
9136 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
9137}
9138
9139/*
drh8b2f49b2001-06-08 00:21:52 +00009140** Erase all information in a table and add the root of the table to
9141** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00009142** page 1) is never added to the freelist.
9143**
9144** This routine will fail with SQLITE_LOCKED if there are any open
9145** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00009146**
9147** If AUTOVACUUM is enabled and the page at iTable is not the last
9148** root page in the database file, then the last root page
9149** in the database file is moved into the slot formerly occupied by
9150** iTable and that last slot formerly occupied by the last root page
9151** is added to the freelist instead of iTable. In this say, all
9152** root pages are kept at the beginning of the database file, which
9153** is necessary for AUTOVACUUM to work right. *piMoved is set to the
9154** page number that used to be the last root page in the file before
9155** the move. If no page gets moved, *piMoved is set to 0.
9156** The last root page is recorded in meta[3] and the value of
9157** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00009158*/
danielk197789d40042008-11-17 14:20:56 +00009159static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00009160 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00009161 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00009162 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00009163
drh1fee73e2007-08-29 04:00:57 +00009164 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00009165 assert( p->inTrans==TRANS_WRITE );
drh65f38d92016-11-22 01:26:42 +00009166 assert( iTable>=2 );
drh055f2982016-01-15 15:06:41 +00009167
drhb00fc3b2013-08-21 23:42:32 +00009168 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00009169 if( rc ) return rc;
danielk1977c7af4842008-10-27 13:59:33 +00009170 rc = sqlite3BtreeClearTable(p, iTable, 0);
danielk19776b456a22005-03-21 04:04:02 +00009171 if( rc ){
9172 releasePage(pPage);
9173 return rc;
9174 }
danielk1977a0bf2652004-11-04 14:30:04 +00009175
drh205f48e2004-11-05 00:43:11 +00009176 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00009177
danielk1977a0bf2652004-11-04 14:30:04 +00009178#ifdef SQLITE_OMIT_AUTOVACUUM
drh055f2982016-01-15 15:06:41 +00009179 freePage(pPage, &rc);
9180 releasePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00009181#else
drh055f2982016-01-15 15:06:41 +00009182 if( pBt->autoVacuum ){
9183 Pgno maxRootPgno;
9184 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00009185
drh055f2982016-01-15 15:06:41 +00009186 if( iTable==maxRootPgno ){
9187 /* If the table being dropped is the table with the largest root-page
9188 ** number in the database, put the root page on the free list.
danielk1977599fcba2004-11-08 07:13:13 +00009189 */
drhc314dc72009-07-21 11:52:34 +00009190 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00009191 releasePage(pPage);
drh055f2982016-01-15 15:06:41 +00009192 if( rc!=SQLITE_OK ){
9193 return rc;
9194 }
9195 }else{
9196 /* The table being dropped does not have the largest root-page
9197 ** number in the database. So move the page that does into the
9198 ** gap left by the deleted root-page.
9199 */
9200 MemPage *pMove;
9201 releasePage(pPage);
9202 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9203 if( rc!=SQLITE_OK ){
9204 return rc;
9205 }
9206 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
9207 releasePage(pMove);
9208 if( rc!=SQLITE_OK ){
9209 return rc;
9210 }
9211 pMove = 0;
9212 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9213 freePage(pMove, &rc);
9214 releasePage(pMove);
9215 if( rc!=SQLITE_OK ){
9216 return rc;
9217 }
9218 *piMoved = maxRootPgno;
danielk1977a0bf2652004-11-04 14:30:04 +00009219 }
drh055f2982016-01-15 15:06:41 +00009220
9221 /* Set the new 'max-root-page' value in the database header. This
9222 ** is the old value less one, less one more if that happens to
9223 ** be a root-page number, less one again if that is the
9224 ** PENDING_BYTE_PAGE.
drhc046e3e2009-07-15 11:26:44 +00009225 */
drh055f2982016-01-15 15:06:41 +00009226 maxRootPgno--;
9227 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
9228 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
9229 maxRootPgno--;
9230 }
9231 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
9232
9233 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
9234 }else{
9235 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00009236 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00009237 }
drh055f2982016-01-15 15:06:41 +00009238#endif
drh8b2f49b2001-06-08 00:21:52 +00009239 return rc;
9240}
drhd677b3d2007-08-20 22:48:41 +00009241int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
9242 int rc;
9243 sqlite3BtreeEnter(p);
dan7733a4d2011-09-02 18:03:16 +00009244 rc = btreeDropTable(p, iTable, piMoved);
drhd677b3d2007-08-20 22:48:41 +00009245 sqlite3BtreeLeave(p);
9246 return rc;
9247}
drh8b2f49b2001-06-08 00:21:52 +00009248
drh001bbcb2003-03-19 03:14:00 +00009249
drh8b2f49b2001-06-08 00:21:52 +00009250/*
danielk1977602b4662009-07-02 07:47:33 +00009251** This function may only be called if the b-tree connection already
9252** has a read or write transaction open on the database.
9253**
drh23e11ca2004-05-04 17:27:28 +00009254** Read the meta-information out of a database file. Meta[0]
9255** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00009256** through meta[15] are available for use by higher layers. Meta[0]
9257** is read-only, the others are read/write.
9258**
9259** The schema layer numbers meta values differently. At the schema
9260** layer (and the SetCookie and ReadCookie opcodes) the number of
9261** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh91618562014-12-19 19:28:02 +00009262**
9263** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
9264** of reading the value out of the header, it instead loads the "DataVersion"
9265** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
9266** database file. It is a number computed by the pager. But its access
9267** pattern is the same as header meta values, and so it is convenient to
9268** read it from this routine.
drh8b2f49b2001-06-08 00:21:52 +00009269*/
danielk1977602b4662009-07-02 07:47:33 +00009270void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
danielk1977aef0bf62005-12-30 16:28:01 +00009271 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00009272
drhd677b3d2007-08-20 22:48:41 +00009273 sqlite3BtreeEnter(p);
danielk1977602b4662009-07-02 07:47:33 +00009274 assert( p->inTrans>TRANS_NONE );
danielk1977e0d9e6f2009-07-03 16:25:06 +00009275 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
danielk1977602b4662009-07-02 07:47:33 +00009276 assert( pBt->pPage1 );
drh23e11ca2004-05-04 17:27:28 +00009277 assert( idx>=0 && idx<=15 );
danielk1977ea897302008-09-19 15:10:58 +00009278
drh91618562014-12-19 19:28:02 +00009279 if( idx==BTREE_DATA_VERSION ){
drh3da9c042014-12-22 18:41:21 +00009280 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
drh91618562014-12-19 19:28:02 +00009281 }else{
9282 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
9283 }
drhae157872004-08-14 19:20:09 +00009284
danielk1977602b4662009-07-02 07:47:33 +00009285 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
9286 ** database, mark the database as read-only. */
danielk1977003ba062004-11-04 02:57:33 +00009287#ifdef SQLITE_OMIT_AUTOVACUUM
drhc9166342012-01-05 23:32:06 +00009288 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
9289 pBt->btsFlags |= BTS_READ_ONLY;
9290 }
danielk1977003ba062004-11-04 02:57:33 +00009291#endif
drhae157872004-08-14 19:20:09 +00009292
drhd677b3d2007-08-20 22:48:41 +00009293 sqlite3BtreeLeave(p);
drh8b2f49b2001-06-08 00:21:52 +00009294}
9295
9296/*
drh23e11ca2004-05-04 17:27:28 +00009297** Write meta-information back into the database. Meta[0] is
9298** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00009299*/
danielk1977aef0bf62005-12-30 16:28:01 +00009300int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
9301 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00009302 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00009303 int rc;
drh23e11ca2004-05-04 17:27:28 +00009304 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00009305 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00009306 assert( p->inTrans==TRANS_WRITE );
9307 assert( pBt->pPage1!=0 );
9308 pP1 = pBt->pPage1->aData;
9309 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
9310 if( rc==SQLITE_OK ){
9311 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00009312#ifndef SQLITE_OMIT_AUTOVACUUM
danielk19770d19f7a2009-06-03 11:25:07 +00009313 if( idx==BTREE_INCR_VACUUM ){
drh64022502009-01-09 14:11:04 +00009314 assert( pBt->autoVacuum || iMeta==0 );
9315 assert( iMeta==0 || iMeta==1 );
9316 pBt->incrVacuum = (u8)iMeta;
drhd677b3d2007-08-20 22:48:41 +00009317 }
drh64022502009-01-09 14:11:04 +00009318#endif
drh5df72a52002-06-06 23:16:05 +00009319 }
drhd677b3d2007-08-20 22:48:41 +00009320 sqlite3BtreeLeave(p);
9321 return rc;
drh8b2f49b2001-06-08 00:21:52 +00009322}
drh8c42ca92001-06-22 19:15:00 +00009323
danielk1977a5533162009-02-24 10:01:51 +00009324#ifndef SQLITE_OMIT_BTREECOUNT
9325/*
9326** The first argument, pCur, is a cursor opened on some b-tree. Count the
9327** number of entries in the b-tree and write the result to *pnEntry.
9328**
9329** SQLITE_OK is returned if the operation is successfully executed.
9330** Otherwise, if an error is encountered (i.e. an IO error or database
9331** corruption) an SQLite error code is returned.
9332*/
9333int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
9334 i64 nEntry = 0; /* Value to return in *pnEntry */
9335 int rc; /* Return code */
dana205a482011-08-27 18:48:57 +00009336
9337 if( pCur->pgnoRoot==0 ){
9338 *pnEntry = 0;
9339 return SQLITE_OK;
9340 }
danielk1977a5533162009-02-24 10:01:51 +00009341 rc = moveToRoot(pCur);
9342
9343 /* Unless an error occurs, the following loop runs one iteration for each
9344 ** page in the B-Tree structure (not including overflow pages).
9345 */
9346 while( rc==SQLITE_OK ){
9347 int iIdx; /* Index of child node in parent */
9348 MemPage *pPage; /* Current page of the b-tree */
9349
9350 /* If this is a leaf page or the tree is not an int-key tree, then
9351 ** this page contains countable entries. Increment the entry counter
9352 ** accordingly.
9353 */
9354 pPage = pCur->apPage[pCur->iPage];
9355 if( pPage->leaf || !pPage->intKey ){
9356 nEntry += pPage->nCell;
9357 }
9358
9359 /* pPage is a leaf node. This loop navigates the cursor so that it
9360 ** points to the first interior cell that it points to the parent of
9361 ** the next page in the tree that has not yet been visited. The
9362 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
9363 ** of the page, or to the number of cells in the page if the next page
9364 ** to visit is the right-child of its parent.
9365 **
9366 ** If all pages in the tree have been visited, return SQLITE_OK to the
9367 ** caller.
9368 */
9369 if( pPage->leaf ){
9370 do {
9371 if( pCur->iPage==0 ){
9372 /* All pages of the b-tree have been visited. Return successfully. */
9373 *pnEntry = nEntry;
drh7efa4262014-12-16 00:08:31 +00009374 return moveToRoot(pCur);
danielk1977a5533162009-02-24 10:01:51 +00009375 }
danielk197730548662009-07-09 05:07:37 +00009376 moveToParent(pCur);
drh75e96b32017-04-01 00:20:06 +00009377 }while ( pCur->ix>=pCur->apPage[pCur->iPage]->nCell );
danielk1977a5533162009-02-24 10:01:51 +00009378
drh75e96b32017-04-01 00:20:06 +00009379 pCur->ix++;
danielk1977a5533162009-02-24 10:01:51 +00009380 pPage = pCur->apPage[pCur->iPage];
9381 }
9382
9383 /* Descend to the child node of the cell that the cursor currently
9384 ** points at. This is the right-child if (iIdx==pPage->nCell).
9385 */
drh75e96b32017-04-01 00:20:06 +00009386 iIdx = pCur->ix;
danielk1977a5533162009-02-24 10:01:51 +00009387 if( iIdx==pPage->nCell ){
9388 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
9389 }else{
9390 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
9391 }
9392 }
9393
shanebe217792009-03-05 04:20:31 +00009394 /* An error has occurred. Return an error code. */
danielk1977a5533162009-02-24 10:01:51 +00009395 return rc;
9396}
9397#endif
drhdd793422001-06-28 01:54:48 +00009398
drhdd793422001-06-28 01:54:48 +00009399/*
drh5eddca62001-06-30 21:53:53 +00009400** Return the pager associated with a BTree. This routine is used for
9401** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00009402*/
danielk1977aef0bf62005-12-30 16:28:01 +00009403Pager *sqlite3BtreePager(Btree *p){
9404 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00009405}
drh5eddca62001-06-30 21:53:53 +00009406
drhb7f91642004-10-31 02:22:47 +00009407#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00009408/*
9409** Append a message to the error message string.
9410*/
drh2e38c322004-09-03 18:38:44 +00009411static void checkAppendMsg(
9412 IntegrityCk *pCheck,
drh2e38c322004-09-03 18:38:44 +00009413 const char *zFormat,
9414 ...
9415){
9416 va_list ap;
drh1dcdbc02007-01-27 02:24:54 +00009417 if( !pCheck->mxErr ) return;
9418 pCheck->mxErr--;
9419 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00009420 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +00009421 if( pCheck->errMsg.nChar ){
9422 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +00009423 }
drh867db832014-09-26 02:41:05 +00009424 if( pCheck->zPfx ){
drh5f4a6862016-01-30 12:50:25 +00009425 sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
drhf089aa42008-07-08 19:34:06 +00009426 }
drh5f4a6862016-01-30 12:50:25 +00009427 sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
drhf089aa42008-07-08 19:34:06 +00009428 va_end(ap);
drhb49bc862013-08-21 21:12:10 +00009429 if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
drhc890fec2008-08-01 20:10:08 +00009430 pCheck->mallocFailed = 1;
9431 }
drh5eddca62001-06-30 21:53:53 +00009432}
drhb7f91642004-10-31 02:22:47 +00009433#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00009434
drhb7f91642004-10-31 02:22:47 +00009435#ifndef SQLITE_OMIT_INTEGRITY_CHECK
dan1235bb12012-04-03 17:43:28 +00009436
9437/*
9438** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
9439** corresponds to page iPg is already set.
9440*/
9441static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9442 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9443 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
9444}
9445
9446/*
9447** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
9448*/
9449static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9450 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9451 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
9452}
9453
9454
drh5eddca62001-06-30 21:53:53 +00009455/*
9456** Add 1 to the reference count for page iPage. If this is the second
9457** reference to the page, add an error message to pCheck->zErrMsg.
peter.d.reid60ec9142014-09-06 16:39:46 +00009458** Return 1 if there are 2 or more references to the page and 0 if
drh5eddca62001-06-30 21:53:53 +00009459** if this is the first reference to the page.
9460**
9461** Also check that the page number is in bounds.
9462*/
drh867db832014-09-26 02:41:05 +00009463static int checkRef(IntegrityCk *pCheck, Pgno iPage){
drh5eddca62001-06-30 21:53:53 +00009464 if( iPage==0 ) return 1;
danielk197789d40042008-11-17 14:20:56 +00009465 if( iPage>pCheck->nPage ){
drh867db832014-09-26 02:41:05 +00009466 checkAppendMsg(pCheck, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00009467 return 1;
9468 }
dan1235bb12012-04-03 17:43:28 +00009469 if( getPageReferenced(pCheck, iPage) ){
drh867db832014-09-26 02:41:05 +00009470 checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00009471 return 1;
9472 }
dan1235bb12012-04-03 17:43:28 +00009473 setPageReferenced(pCheck, iPage);
9474 return 0;
drh5eddca62001-06-30 21:53:53 +00009475}
9476
danielk1977afcdd022004-10-31 16:25:42 +00009477#ifndef SQLITE_OMIT_AUTOVACUUM
9478/*
9479** Check that the entry in the pointer-map for page iChild maps to
9480** page iParent, pointer type ptrType. If not, append an error message
9481** to pCheck.
9482*/
9483static void checkPtrmap(
9484 IntegrityCk *pCheck, /* Integrity check context */
9485 Pgno iChild, /* Child page number */
9486 u8 eType, /* Expected pointer map type */
drh867db832014-09-26 02:41:05 +00009487 Pgno iParent /* Expected pointer map parent page number */
danielk1977afcdd022004-10-31 16:25:42 +00009488){
9489 int rc;
9490 u8 ePtrmapType;
9491 Pgno iPtrmapParent;
9492
9493 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
9494 if( rc!=SQLITE_OK ){
drhb56cd552009-05-01 13:16:54 +00009495 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
drh867db832014-09-26 02:41:05 +00009496 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
danielk1977afcdd022004-10-31 16:25:42 +00009497 return;
9498 }
9499
9500 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
drh867db832014-09-26 02:41:05 +00009501 checkAppendMsg(pCheck,
danielk1977afcdd022004-10-31 16:25:42 +00009502 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
9503 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
9504 }
9505}
9506#endif
9507
drh5eddca62001-06-30 21:53:53 +00009508/*
9509** Check the integrity of the freelist or of an overflow page list.
9510** Verify that the number of pages on the list is N.
9511*/
drh30e58752002-03-02 20:41:57 +00009512static void checkList(
9513 IntegrityCk *pCheck, /* Integrity checking context */
9514 int isFreeList, /* True for a freelist. False for overflow page list */
9515 int iPage, /* Page number for first page in the list */
drh867db832014-09-26 02:41:05 +00009516 int N /* Expected number of pages in the list */
drh30e58752002-03-02 20:41:57 +00009517){
9518 int i;
drh3a4c1412004-05-09 20:40:11 +00009519 int expected = N;
9520 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00009521 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00009522 DbPage *pOvflPage;
9523 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00009524 if( iPage<1 ){
drh867db832014-09-26 02:41:05 +00009525 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00009526 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00009527 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00009528 break;
9529 }
drh867db832014-09-26 02:41:05 +00009530 if( checkRef(pCheck, iPage) ) break;
drh9584f582015-11-04 20:22:37 +00009531 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
drh867db832014-09-26 02:41:05 +00009532 checkAppendMsg(pCheck, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00009533 break;
9534 }
danielk19773b8a05f2007-03-19 17:44:26 +00009535 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00009536 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00009537 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00009538#ifndef SQLITE_OMIT_AUTOVACUUM
9539 if( pCheck->pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00009540 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +00009541 }
9542#endif
drh43b18e12010-08-17 19:40:08 +00009543 if( n>(int)pCheck->pBt->usableSize/4-2 ){
drh867db832014-09-26 02:41:05 +00009544 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00009545 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00009546 N--;
9547 }else{
9548 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00009549 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00009550#ifndef SQLITE_OMIT_AUTOVACUUM
9551 if( pCheck->pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00009552 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +00009553 }
9554#endif
drh867db832014-09-26 02:41:05 +00009555 checkRef(pCheck, iFreePage);
drhee696e22004-08-30 16:52:17 +00009556 }
9557 N -= n;
drh30e58752002-03-02 20:41:57 +00009558 }
drh30e58752002-03-02 20:41:57 +00009559 }
danielk1977afcdd022004-10-31 16:25:42 +00009560#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00009561 else{
9562 /* If this database supports auto-vacuum and iPage is not the last
9563 ** page in this overflow list, check that the pointer-map entry for
9564 ** the following page matches iPage.
9565 */
9566 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00009567 i = get4byte(pOvflData);
drh867db832014-09-26 02:41:05 +00009568 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
danielk1977687566d2004-11-02 12:56:41 +00009569 }
danielk1977afcdd022004-10-31 16:25:42 +00009570 }
9571#endif
danielk19773b8a05f2007-03-19 17:44:26 +00009572 iPage = get4byte(pOvflData);
9573 sqlite3PagerUnref(pOvflPage);
danad41f5e2015-09-18 14:45:01 +00009574
9575 if( isFreeList && N<(iPage!=0) ){
9576 checkAppendMsg(pCheck, "free-page count in header is too small");
9577 }
drh5eddca62001-06-30 21:53:53 +00009578 }
9579}
drhb7f91642004-10-31 02:22:47 +00009580#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00009581
drh67731a92015-04-16 11:56:03 +00009582/*
9583** An implementation of a min-heap.
9584**
9585** aHeap[0] is the number of elements on the heap. aHeap[1] is the
drha33b6832015-04-16 21:57:37 +00009586** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
drh67731a92015-04-16 11:56:03 +00009587** and aHeap[N*2+1].
9588**
9589** The heap property is this: Every node is less than or equal to both
9590** of its daughter nodes. A consequence of the heap property is that the
drh42c0a2b2015-04-28 01:28:36 +00009591** root node aHeap[1] is always the minimum value currently in the heap.
drh67731a92015-04-16 11:56:03 +00009592**
9593** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
9594** the heap, preserving the heap property. The btreeHeapPull() routine
9595** removes the root element from the heap (the minimum value in the heap)
drh42c0a2b2015-04-28 01:28:36 +00009596** and then moves other nodes around as necessary to preserve the heap
drh67731a92015-04-16 11:56:03 +00009597** property.
9598**
9599** This heap is used for cell overlap and coverage testing. Each u32
9600** entry represents the span of a cell or freeblock on a btree page.
9601** The upper 16 bits are the index of the first byte of a range and the
9602** lower 16 bits are the index of the last byte of that range.
9603*/
9604static void btreeHeapInsert(u32 *aHeap, u32 x){
9605 u32 j, i = ++aHeap[0];
9606 aHeap[i] = x;
drha33b6832015-04-16 21:57:37 +00009607 while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
drh67731a92015-04-16 11:56:03 +00009608 x = aHeap[j];
9609 aHeap[j] = aHeap[i];
9610 aHeap[i] = x;
9611 i = j;
9612 }
9613}
9614static int btreeHeapPull(u32 *aHeap, u32 *pOut){
9615 u32 j, i, x;
9616 if( (x = aHeap[0])==0 ) return 0;
9617 *pOut = aHeap[1];
9618 aHeap[1] = aHeap[x];
9619 aHeap[x] = 0xffffffff;
9620 aHeap[0]--;
9621 i = 1;
9622 while( (j = i*2)<=aHeap[0] ){
9623 if( aHeap[j]>aHeap[j+1] ) j++;
9624 if( aHeap[i]<aHeap[j] ) break;
9625 x = aHeap[i];
9626 aHeap[i] = aHeap[j];
9627 aHeap[j] = x;
9628 i = j;
9629 }
9630 return 1;
9631}
9632
drhb7f91642004-10-31 02:22:47 +00009633#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00009634/*
9635** Do various sanity checks on a single page of a tree. Return
9636** the tree depth. Root pages return 0. Parents of root pages
9637** return 1, and so forth.
9638**
9639** These checks are done:
9640**
9641** 1. Make sure that cells and freeblocks do not overlap
9642** but combine to completely cover the page.
drhe05b3f82015-07-01 17:53:49 +00009643** 2. Make sure integer cell keys are in order.
9644** 3. Check the integrity of overflow pages.
9645** 4. Recursively call checkTreePage on all children.
9646** 5. Verify that the depth of all children is the same.
drh5eddca62001-06-30 21:53:53 +00009647*/
9648static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00009649 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00009650 int iPage, /* Page number of the page to check */
drhcbc6b712015-07-02 16:17:30 +00009651 i64 *piMinKey, /* Write minimum integer primary key here */
9652 i64 maxKey /* Error if integer primary key greater than this */
drh5eddca62001-06-30 21:53:53 +00009653){
drhcbc6b712015-07-02 16:17:30 +00009654 MemPage *pPage = 0; /* The page being analyzed */
9655 int i; /* Loop counter */
9656 int rc; /* Result code from subroutine call */
9657 int depth = -1, d2; /* Depth of a subtree */
9658 int pgno; /* Page number */
9659 int nFrag; /* Number of fragmented bytes on the page */
9660 int hdr; /* Offset to the page header */
9661 int cellStart; /* Offset to the start of the cell pointer array */
9662 int nCell; /* Number of cells */
9663 int doCoverageCheck = 1; /* True if cell coverage checking should be done */
9664 int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
9665 ** False if IPK must be strictly less than maxKey */
9666 u8 *data; /* Page content */
9667 u8 *pCell; /* Cell content */
9668 u8 *pCellIdx; /* Next element of the cell pointer array */
9669 BtShared *pBt; /* The BtShared object that owns pPage */
9670 u32 pc; /* Address of a cell */
9671 u32 usableSize; /* Usable size of the page */
9672 u32 contentOffset; /* Offset to the start of the cell content area */
9673 u32 *heap = 0; /* Min-heap used for checking cell coverage */
drhd2dc87f2015-07-02 19:47:08 +00009674 u32 x, prev = 0; /* Next and previous entry on the min-heap */
drh867db832014-09-26 02:41:05 +00009675 const char *saved_zPfx = pCheck->zPfx;
9676 int saved_v1 = pCheck->v1;
9677 int saved_v2 = pCheck->v2;
mistachkin532f1792015-07-14 17:18:05 +00009678 u8 savedIsInit = 0;
danielk1977ef73ee92004-11-06 12:26:07 +00009679
drh5eddca62001-06-30 21:53:53 +00009680 /* Check that the page exists
9681 */
drhd9cb6ac2005-10-20 07:28:17 +00009682 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00009683 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00009684 if( iPage==0 ) return 0;
drh867db832014-09-26 02:41:05 +00009685 if( checkRef(pCheck, iPage) ) return 0;
9686 pCheck->zPfx = "Page %d: ";
9687 pCheck->v1 = iPage;
drhb00fc3b2013-08-21 23:42:32 +00009688 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drh867db832014-09-26 02:41:05 +00009689 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00009690 "unable to get the page. error code=%d", rc);
drh867db832014-09-26 02:41:05 +00009691 goto end_of_check;
drh5eddca62001-06-30 21:53:53 +00009692 }
danielk197793caf5a2009-07-11 06:55:33 +00009693
9694 /* Clear MemPage.isInit to make sure the corruption detection code in
9695 ** btreeInitPage() is executed. */
drh72e191e2015-07-04 11:14:20 +00009696 savedIsInit = pPage->isInit;
danielk197793caf5a2009-07-11 06:55:33 +00009697 pPage->isInit = 0;
danielk197730548662009-07-09 05:07:37 +00009698 if( (rc = btreeInitPage(pPage))!=0 ){
drh64022502009-01-09 14:11:04 +00009699 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
drh867db832014-09-26 02:41:05 +00009700 checkAppendMsg(pCheck,
danielk197730548662009-07-09 05:07:37 +00009701 "btreeInitPage() returns error code %d", rc);
drh867db832014-09-26 02:41:05 +00009702 goto end_of_check;
drh5eddca62001-06-30 21:53:53 +00009703 }
drhcbc6b712015-07-02 16:17:30 +00009704 data = pPage->aData;
9705 hdr = pPage->hdrOffset;
drh5eddca62001-06-30 21:53:53 +00009706
drhcbc6b712015-07-02 16:17:30 +00009707 /* Set up for cell analysis */
drhe05b3f82015-07-01 17:53:49 +00009708 pCheck->zPfx = "On tree page %d cell %d: ";
drhcbc6b712015-07-02 16:17:30 +00009709 contentOffset = get2byteNotZero(&data[hdr+5]);
9710 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
9711
9712 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
9713 ** number of cells on the page. */
9714 nCell = get2byte(&data[hdr+3]);
9715 assert( pPage->nCell==nCell );
9716
9717 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
9718 ** immediately follows the b-tree page header. */
9719 cellStart = hdr + 12 - 4*pPage->leaf;
9720 assert( pPage->aCellIdx==&data[cellStart] );
9721 pCellIdx = &data[cellStart + 2*(nCell-1)];
9722
9723 if( !pPage->leaf ){
9724 /* Analyze the right-child page of internal pages */
9725 pgno = get4byte(&data[hdr+8]);
9726#ifndef SQLITE_OMIT_AUTOVACUUM
9727 if( pBt->autoVacuum ){
9728 pCheck->zPfx = "On page %d at right child: ";
9729 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
9730 }
9731#endif
9732 depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
9733 keyCanBeEqual = 0;
9734 }else{
9735 /* For leaf pages, the coverage check will occur in the same loop
9736 ** as the other cell checks, so initialize the heap. */
9737 heap = pCheck->heap;
9738 heap[0] = 0;
drhcbc6b712015-07-02 16:17:30 +00009739 }
9740
9741 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
9742 ** integer offsets to the cell contents. */
9743 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
drh6f11bef2004-05-13 01:12:56 +00009744 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00009745
drhcbc6b712015-07-02 16:17:30 +00009746 /* Check cell size */
drh867db832014-09-26 02:41:05 +00009747 pCheck->v2 = i;
drhcbc6b712015-07-02 16:17:30 +00009748 assert( pCellIdx==&data[cellStart + i*2] );
9749 pc = get2byteAligned(pCellIdx);
9750 pCellIdx -= 2;
9751 if( pc<contentOffset || pc>usableSize-4 ){
9752 checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
9753 pc, contentOffset, usableSize-4);
9754 doCoverageCheck = 0;
9755 continue;
shaneh195475d2010-02-19 04:28:08 +00009756 }
drhcbc6b712015-07-02 16:17:30 +00009757 pCell = &data[pc];
9758 pPage->xParseCell(pPage, pCell, &info);
9759 if( pc+info.nSize>usableSize ){
9760 checkAppendMsg(pCheck, "Extends off end of page");
9761 doCoverageCheck = 0;
9762 continue;
9763 }
9764
9765 /* Check for integer primary key out of range */
9766 if( pPage->intKey ){
9767 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
9768 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
9769 }
9770 maxKey = info.nKey;
dan4b2667c2017-05-01 18:24:01 +00009771 keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
drhcbc6b712015-07-02 16:17:30 +00009772 }
9773
9774 /* Check the content overflow list */
9775 if( info.nPayload>info.nLocal ){
9776 int nPage; /* Number of pages on the overflow chain */
9777 Pgno pgnoOvfl; /* First page of the overflow chain */
drh45ac1c72015-12-18 03:59:16 +00009778 assert( pc + info.nSize - 4 <= usableSize );
drhcbc6b712015-07-02 16:17:30 +00009779 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
drh45ac1c72015-12-18 03:59:16 +00009780 pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
danielk1977afcdd022004-10-31 16:25:42 +00009781#ifndef SQLITE_OMIT_AUTOVACUUM
9782 if( pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00009783 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
danielk1977afcdd022004-10-31 16:25:42 +00009784 }
9785#endif
drh867db832014-09-26 02:41:05 +00009786 checkList(pCheck, 0, pgnoOvfl, nPage);
drh5eddca62001-06-30 21:53:53 +00009787 }
9788
drhda200cc2004-05-09 11:51:38 +00009789 if( !pPage->leaf ){
drhcbc6b712015-07-02 16:17:30 +00009790 /* Check sanity of left child page for internal pages */
drh43605152004-05-29 21:46:49 +00009791 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00009792#ifndef SQLITE_OMIT_AUTOVACUUM
9793 if( pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00009794 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
danielk1977afcdd022004-10-31 16:25:42 +00009795 }
9796#endif
drhcbc6b712015-07-02 16:17:30 +00009797 d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
9798 keyCanBeEqual = 0;
9799 if( d2!=depth ){
drh867db832014-09-26 02:41:05 +00009800 checkAppendMsg(pCheck, "Child page depth differs");
drhcbc6b712015-07-02 16:17:30 +00009801 depth = d2;
drhda200cc2004-05-09 11:51:38 +00009802 }
drhcbc6b712015-07-02 16:17:30 +00009803 }else{
9804 /* Populate the coverage-checking heap for leaf pages */
9805 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
drh5eddca62001-06-30 21:53:53 +00009806 }
drh5eddca62001-06-30 21:53:53 +00009807 }
drhcbc6b712015-07-02 16:17:30 +00009808 *piMinKey = maxKey;
shaneh195475d2010-02-19 04:28:08 +00009809
drh5eddca62001-06-30 21:53:53 +00009810 /* Check for complete coverage of the page
9811 */
drh867db832014-09-26 02:41:05 +00009812 pCheck->zPfx = 0;
drhcbc6b712015-07-02 16:17:30 +00009813 if( doCoverageCheck && pCheck->mxErr>0 ){
9814 /* For leaf pages, the min-heap has already been initialized and the
9815 ** cells have already been inserted. But for internal pages, that has
9816 ** not yet been done, so do it now */
9817 if( !pPage->leaf ){
9818 heap = pCheck->heap;
9819 heap[0] = 0;
drhcbc6b712015-07-02 16:17:30 +00009820 for(i=nCell-1; i>=0; i--){
drh1910def2015-07-02 16:29:56 +00009821 u32 size;
9822 pc = get2byteAligned(&data[cellStart+i*2]);
9823 size = pPage->xCellSize(pPage, &data[pc]);
drh67731a92015-04-16 11:56:03 +00009824 btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
danielk19777701e812005-01-10 12:59:51 +00009825 }
drh2e38c322004-09-03 18:38:44 +00009826 }
drhcbc6b712015-07-02 16:17:30 +00009827 /* Add the freeblocks to the min-heap
9828 **
9829 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
drhfdab0262014-11-20 15:30:50 +00009830 ** is the offset of the first freeblock, or zero if there are no
drhcbc6b712015-07-02 16:17:30 +00009831 ** freeblocks on the page.
9832 */
drh8c2bbb62009-07-10 02:52:20 +00009833 i = get2byte(&data[hdr+1]);
9834 while( i>0 ){
9835 int size, j;
mistachkinc29cbb02015-07-02 16:52:01 +00009836 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
drh8c2bbb62009-07-10 02:52:20 +00009837 size = get2byte(&data[i+2]);
mistachkinc29cbb02015-07-02 16:52:01 +00009838 assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
drhe56d4302015-07-08 01:22:52 +00009839 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
drhfdab0262014-11-20 15:30:50 +00009840 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
9841 ** big-endian integer which is the offset in the b-tree page of the next
9842 ** freeblock in the chain, or zero if the freeblock is the last on the
9843 ** chain. */
drh8c2bbb62009-07-10 02:52:20 +00009844 j = get2byte(&data[i]);
drhfdab0262014-11-20 15:30:50 +00009845 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
9846 ** increasing offset. */
drh8c2bbb62009-07-10 02:52:20 +00009847 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
mistachkinc29cbb02015-07-02 16:52:01 +00009848 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
drh8c2bbb62009-07-10 02:52:20 +00009849 i = j;
drh2e38c322004-09-03 18:38:44 +00009850 }
drhcbc6b712015-07-02 16:17:30 +00009851 /* Analyze the min-heap looking for overlap between cells and/or
9852 ** freeblocks, and counting the number of untracked bytes in nFrag.
drhd2dc87f2015-07-02 19:47:08 +00009853 **
9854 ** Each min-heap entry is of the form: (start_address<<16)|end_address.
9855 ** There is an implied first entry the covers the page header, the cell
9856 ** pointer index, and the gap between the cell pointer index and the start
9857 ** of cell content.
9858 **
9859 ** The loop below pulls entries from the min-heap in order and compares
9860 ** the start_address against the previous end_address. If there is an
9861 ** overlap, that means bytes are used multiple times. If there is a gap,
9862 ** that gap is added to the fragmentation count.
drhcbc6b712015-07-02 16:17:30 +00009863 */
9864 nFrag = 0;
drhd2dc87f2015-07-02 19:47:08 +00009865 prev = contentOffset - 1; /* Implied first min-heap entry */
drh67731a92015-04-16 11:56:03 +00009866 while( btreeHeapPull(heap,&x) ){
drhd2dc87f2015-07-02 19:47:08 +00009867 if( (prev&0xffff)>=(x>>16) ){
drh867db832014-09-26 02:41:05 +00009868 checkAppendMsg(pCheck,
drh67731a92015-04-16 11:56:03 +00009869 "Multiple uses for byte %u of page %d", x>>16, iPage);
drh2e38c322004-09-03 18:38:44 +00009870 break;
drh67731a92015-04-16 11:56:03 +00009871 }else{
drhcbc6b712015-07-02 16:17:30 +00009872 nFrag += (x>>16) - (prev&0xffff) - 1;
drh67731a92015-04-16 11:56:03 +00009873 prev = x;
drh2e38c322004-09-03 18:38:44 +00009874 }
9875 }
drhcbc6b712015-07-02 16:17:30 +00009876 nFrag += usableSize - (prev&0xffff) - 1;
drhfdab0262014-11-20 15:30:50 +00009877 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
9878 ** is stored in the fifth field of the b-tree page header.
9879 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
9880 ** number of fragmented free bytes within the cell content area.
9881 */
drhcbc6b712015-07-02 16:17:30 +00009882 if( heap[0]==0 && nFrag!=data[hdr+7] ){
drh867db832014-09-26 02:41:05 +00009883 checkAppendMsg(pCheck,
drh8c2bbb62009-07-10 02:52:20 +00009884 "Fragmentation of %d bytes reported as %d on page %d",
drhcbc6b712015-07-02 16:17:30 +00009885 nFrag, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00009886 }
9887 }
drh867db832014-09-26 02:41:05 +00009888
9889end_of_check:
drh72e191e2015-07-04 11:14:20 +00009890 if( !doCoverageCheck ) pPage->isInit = savedIsInit;
drhe05b3f82015-07-01 17:53:49 +00009891 releasePage(pPage);
drh867db832014-09-26 02:41:05 +00009892 pCheck->zPfx = saved_zPfx;
9893 pCheck->v1 = saved_v1;
9894 pCheck->v2 = saved_v2;
drhda200cc2004-05-09 11:51:38 +00009895 return depth+1;
drh5eddca62001-06-30 21:53:53 +00009896}
drhb7f91642004-10-31 02:22:47 +00009897#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00009898
drhb7f91642004-10-31 02:22:47 +00009899#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00009900/*
9901** This routine does a complete check of the given BTree file. aRoot[] is
9902** an array of pages numbers were each page number is the root page of
9903** a table. nRoot is the number of entries in aRoot.
9904**
danielk19773509a652009-07-06 18:56:13 +00009905** A read-only or read-write transaction must be opened before calling
9906** this function.
9907**
drhc890fec2008-08-01 20:10:08 +00009908** Write the number of error seen in *pnErr. Except for some memory
drhe43ba702008-12-05 22:40:08 +00009909** allocation errors, an error message held in memory obtained from
drhc890fec2008-08-01 20:10:08 +00009910** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
drhe43ba702008-12-05 22:40:08 +00009911** returned. If a memory allocation error occurs, NULL is returned.
drh5eddca62001-06-30 21:53:53 +00009912*/
drh1dcdbc02007-01-27 02:24:54 +00009913char *sqlite3BtreeIntegrityCheck(
9914 Btree *p, /* The btree to be checked */
9915 int *aRoot, /* An array of root pages numbers for individual trees */
9916 int nRoot, /* Number of entries in aRoot[] */
9917 int mxErr, /* Stop reporting errors after this many */
9918 int *pnErr /* Write number of errors seen to this variable */
9919){
danielk197789d40042008-11-17 14:20:56 +00009920 Pgno i;
drhaaab5722002-02-19 13:39:21 +00009921 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00009922 BtShared *pBt = p->pBt;
drhcbc6b712015-07-02 16:17:30 +00009923 int savedDbFlags = pBt->db->flags;
drhf089aa42008-07-08 19:34:06 +00009924 char zErr[100];
drhcbc6b712015-07-02 16:17:30 +00009925 VVA_ONLY( int nRef );
drh5eddca62001-06-30 21:53:53 +00009926
drhd677b3d2007-08-20 22:48:41 +00009927 sqlite3BtreeEnter(p);
danielk19773509a652009-07-06 18:56:13 +00009928 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
drhcc5f8a42016-02-06 22:32:06 +00009929 VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
9930 assert( nRef>=0 );
drh5eddca62001-06-30 21:53:53 +00009931 sCheck.pBt = pBt;
9932 sCheck.pPager = pBt->pPager;
drhb1299152010-03-30 22:58:33 +00009933 sCheck.nPage = btreePagecount(sCheck.pBt);
drh1dcdbc02007-01-27 02:24:54 +00009934 sCheck.mxErr = mxErr;
9935 sCheck.nErr = 0;
drhc890fec2008-08-01 20:10:08 +00009936 sCheck.mallocFailed = 0;
drh867db832014-09-26 02:41:05 +00009937 sCheck.zPfx = 0;
9938 sCheck.v1 = 0;
9939 sCheck.v2 = 0;
drhe05b3f82015-07-01 17:53:49 +00009940 sCheck.aPgRef = 0;
9941 sCheck.heap = 0;
9942 sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
drh5f4a6862016-01-30 12:50:25 +00009943 sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
drh0de8c112002-07-06 16:32:14 +00009944 if( sCheck.nPage==0 ){
drhe05b3f82015-07-01 17:53:49 +00009945 goto integrity_ck_cleanup;
drh0de8c112002-07-06 16:32:14 +00009946 }
dan1235bb12012-04-03 17:43:28 +00009947
9948 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
9949 if( !sCheck.aPgRef ){
drhe05b3f82015-07-01 17:53:49 +00009950 sCheck.mallocFailed = 1;
9951 goto integrity_ck_cleanup;
danielk1977ac245ec2005-01-14 13:50:11 +00009952 }
drhe05b3f82015-07-01 17:53:49 +00009953 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
9954 if( sCheck.heap==0 ){
9955 sCheck.mallocFailed = 1;
9956 goto integrity_ck_cleanup;
9957 }
9958
drh42cac6d2004-11-20 20:31:11 +00009959 i = PENDING_BYTE_PAGE(pBt);
dan1235bb12012-04-03 17:43:28 +00009960 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
drh5eddca62001-06-30 21:53:53 +00009961
9962 /* Check the integrity of the freelist
9963 */
drh867db832014-09-26 02:41:05 +00009964 sCheck.zPfx = "Main freelist: ";
drha34b6762004-05-07 13:30:42 +00009965 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
drh867db832014-09-26 02:41:05 +00009966 get4byte(&pBt->pPage1->aData[36]));
9967 sCheck.zPfx = 0;
drh5eddca62001-06-30 21:53:53 +00009968
9969 /* Check all the tables.
9970 */
drhcbc6b712015-07-02 16:17:30 +00009971 testcase( pBt->db->flags & SQLITE_CellSizeCk );
9972 pBt->db->flags &= ~SQLITE_CellSizeCk;
danielk197789d40042008-11-17 14:20:56 +00009973 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
drhcbc6b712015-07-02 16:17:30 +00009974 i64 notUsed;
drh4ff6dfa2002-03-03 23:06:00 +00009975 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00009976#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00009977 if( pBt->autoVacuum && aRoot[i]>1 ){
drh867db832014-09-26 02:41:05 +00009978 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +00009979 }
9980#endif
drhcbc6b712015-07-02 16:17:30 +00009981 checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
drh5eddca62001-06-30 21:53:53 +00009982 }
drhcbc6b712015-07-02 16:17:30 +00009983 pBt->db->flags = savedDbFlags;
drh5eddca62001-06-30 21:53:53 +00009984
dan57888f72015-08-25 17:16:33 +00009985 /* Make sure every page in the file is referenced. Skip this if the
9986 ** database is currently being written by a CONCURRENT transaction (it
9987 ** may fail as pages that were part of the free-list when the transaction
9988 ** was opened cannot be counted). */
9989 for(i=1; ISCONCURRENT==0 && i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00009990#ifdef SQLITE_OMIT_AUTOVACUUM
dan1235bb12012-04-03 17:43:28 +00009991 if( getPageReferenced(&sCheck, i)==0 ){
drh867db832014-09-26 02:41:05 +00009992 checkAppendMsg(&sCheck, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00009993 }
danielk1977afcdd022004-10-31 16:25:42 +00009994#else
9995 /* If the database supports auto-vacuum, make sure no tables contain
9996 ** references to pointer-map pages.
9997 */
dan1235bb12012-04-03 17:43:28 +00009998 if( getPageReferenced(&sCheck, i)==0 &&
danielk1977266664d2006-02-10 08:24:21 +00009999 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
drh867db832014-09-26 02:41:05 +000010000 checkAppendMsg(&sCheck, "Page %d is never used", i);
danielk1977afcdd022004-10-31 16:25:42 +000010001 }
dan1235bb12012-04-03 17:43:28 +000010002 if( getPageReferenced(&sCheck, i)!=0 &&
danielk1977266664d2006-02-10 08:24:21 +000010003 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
drh867db832014-09-26 02:41:05 +000010004 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
danielk1977afcdd022004-10-31 16:25:42 +000010005 }
10006#endif
drh5eddca62001-06-30 21:53:53 +000010007 }
10008
drh5eddca62001-06-30 21:53:53 +000010009 /* Clean up and report errors.
10010 */
drhe05b3f82015-07-01 17:53:49 +000010011integrity_ck_cleanup:
10012 sqlite3PageFree(sCheck.heap);
dan1235bb12012-04-03 17:43:28 +000010013 sqlite3_free(sCheck.aPgRef);
drhc890fec2008-08-01 20:10:08 +000010014 if( sCheck.mallocFailed ){
10015 sqlite3StrAccumReset(&sCheck.errMsg);
drhe05b3f82015-07-01 17:53:49 +000010016 sCheck.nErr++;
drhc890fec2008-08-01 20:10:08 +000010017 }
drh1dcdbc02007-01-27 02:24:54 +000010018 *pnErr = sCheck.nErr;
drhf089aa42008-07-08 19:34:06 +000010019 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
drhe05b3f82015-07-01 17:53:49 +000010020 /* Make sure this analysis did not leave any unref() pages. */
10021 assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
10022 sqlite3BtreeLeave(p);
drhf089aa42008-07-08 19:34:06 +000010023 return sqlite3StrAccumFinish(&sCheck.errMsg);
drh5eddca62001-06-30 21:53:53 +000010024}
drhb7f91642004-10-31 02:22:47 +000010025#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +000010026
drh73509ee2003-04-06 20:44:45 +000010027/*
drhd4e0bb02012-05-27 01:19:04 +000010028** Return the full pathname of the underlying database file. Return
10029** an empty string if the database is in-memory or a TEMP database.
drhd0679ed2007-08-28 22:24:34 +000010030**
10031** The pager filename is invariant as long as the pager is
10032** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +000010033*/
danielk1977aef0bf62005-12-30 16:28:01 +000010034const char *sqlite3BtreeGetFilename(Btree *p){
10035 assert( p->pBt->pPager!=0 );
drhd4e0bb02012-05-27 01:19:04 +000010036 return sqlite3PagerFilename(p->pBt->pPager, 1);
drh73509ee2003-04-06 20:44:45 +000010037}
10038
10039/*
danielk19775865e3d2004-06-14 06:03:57 +000010040** Return the pathname of the journal file for this database. The return
10041** value of this routine is the same regardless of whether the journal file
10042** has been created or not.
drhd0679ed2007-08-28 22:24:34 +000010043**
10044** The pager journal filename is invariant as long as the pager is
10045** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +000010046*/
danielk1977aef0bf62005-12-30 16:28:01 +000010047const char *sqlite3BtreeGetJournalname(Btree *p){
10048 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +000010049 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +000010050}
10051
danielk19771d850a72004-05-31 08:26:49 +000010052/*
10053** Return non-zero if a transaction is active.
10054*/
danielk1977aef0bf62005-12-30 16:28:01 +000010055int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +000010056 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +000010057 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +000010058}
10059
dana550f2d2010-08-02 10:47:05 +000010060#ifndef SQLITE_OMIT_WAL
10061/*
10062** Run a checkpoint on the Btree passed as the first argument.
10063**
10064** Return SQLITE_LOCKED if this or any other connection has an open
10065** transaction on the shared-cache the argument Btree is connected to.
dana58f26f2010-11-16 18:56:51 +000010066**
dancdc1f042010-11-18 12:11:05 +000010067** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
dana550f2d2010-08-02 10:47:05 +000010068*/
dancdc1f042010-11-18 12:11:05 +000010069int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
dana550f2d2010-08-02 10:47:05 +000010070 int rc = SQLITE_OK;
10071 if( p ){
10072 BtShared *pBt = p->pBt;
10073 sqlite3BtreeEnter(p);
10074 if( pBt->inTransaction!=TRANS_NONE ){
10075 rc = SQLITE_LOCKED;
10076 }else{
dan7fb89902016-08-12 16:21:15 +000010077 rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
dana550f2d2010-08-02 10:47:05 +000010078 }
10079 sqlite3BtreeLeave(p);
10080 }
10081 return rc;
10082}
10083#endif
10084
danielk19771d850a72004-05-31 08:26:49 +000010085/*
danielk19772372c2b2006-06-27 16:34:56 +000010086** Return non-zero if a read (or write) transaction is active.
10087*/
10088int sqlite3BtreeIsInReadTrans(Btree *p){
drh64022502009-01-09 14:11:04 +000010089 assert( p );
drhe5fe6902007-12-07 18:55:28 +000010090 assert( sqlite3_mutex_held(p->db->mutex) );
drh64022502009-01-09 14:11:04 +000010091 return p->inTrans!=TRANS_NONE;
danielk19772372c2b2006-06-27 16:34:56 +000010092}
10093
danielk197704103022009-02-03 16:51:24 +000010094int sqlite3BtreeIsInBackup(Btree *p){
10095 assert( p );
10096 assert( sqlite3_mutex_held(p->db->mutex) );
10097 return p->nBackup!=0;
10098}
10099
danielk19772372c2b2006-06-27 16:34:56 +000010100/*
danielk1977da184232006-01-05 11:34:32 +000010101** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +000010102** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +000010103** purposes (for example, to store a high-level schema associated with
10104** the shared-btree). The btree layer manages reference counting issues.
10105**
10106** The first time this is called on a shared-btree, nBytes bytes of memory
10107** are allocated, zeroed, and returned to the caller. For each subsequent
10108** call the nBytes parameter is ignored and a pointer to the same blob
10109** of memory returned.
10110**
danielk1977171bfed2008-06-23 09:50:50 +000010111** If the nBytes parameter is 0 and the blob of memory has not yet been
10112** allocated, a null pointer is returned. If the blob has already been
10113** allocated, it is returned as normal.
10114**
danielk1977da184232006-01-05 11:34:32 +000010115** Just before the shared-btree is closed, the function passed as the
10116** xFree argument when the memory allocation was made is invoked on the
drh4fa7d7c2011-04-03 02:41:00 +000010117** blob of allocated memory. The xFree function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +000010118** on the memory, the btree layer does that.
10119*/
10120void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
10121 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +000010122 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +000010123 if( !pBt->pSchema && nBytes ){
drhb9755982010-07-24 16:34:37 +000010124 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
danielk1977da184232006-01-05 11:34:32 +000010125 pBt->xFreeSchema = xFree;
10126 }
drh27641702007-08-22 02:56:42 +000010127 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +000010128 return pBt->pSchema;
10129}
10130
danielk1977c87d34d2006-01-06 13:00:28 +000010131/*
danielk1977404ca072009-03-16 13:19:36 +000010132** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
10133** btree as the argument handle holds an exclusive lock on the
10134** sqlite_master table. Otherwise SQLITE_OK.
danielk1977c87d34d2006-01-06 13:00:28 +000010135*/
10136int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +000010137 int rc;
drhe5fe6902007-12-07 18:55:28 +000010138 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +000010139 sqlite3BtreeEnter(p);
danielk1977404ca072009-03-16 13:19:36 +000010140 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
10141 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
drh27641702007-08-22 02:56:42 +000010142 sqlite3BtreeLeave(p);
10143 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +000010144}
10145
drha154dcd2006-03-22 22:10:07 +000010146
10147#ifndef SQLITE_OMIT_SHARED_CACHE
10148/*
10149** Obtain a lock on the table whose root page is iTab. The
10150** lock is a write lock if isWritelock is true or a read lock
10151** if it is false.
10152*/
danielk1977c00da102006-01-07 13:21:04 +000010153int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +000010154 int rc = SQLITE_OK;
danielk1977602b4662009-07-02 07:47:33 +000010155 assert( p->inTrans!=TRANS_NONE );
drh6a9ad3d2008-04-02 16:29:30 +000010156 if( p->sharable ){
10157 u8 lockType = READ_LOCK + isWriteLock;
10158 assert( READ_LOCK+1==WRITE_LOCK );
10159 assert( isWriteLock==0 || isWriteLock==1 );
danielk1977602b4662009-07-02 07:47:33 +000010160
drh6a9ad3d2008-04-02 16:29:30 +000010161 sqlite3BtreeEnter(p);
drhc25eabe2009-02-24 18:57:31 +000010162 rc = querySharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +000010163 if( rc==SQLITE_OK ){
drhc25eabe2009-02-24 18:57:31 +000010164 rc = setSharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +000010165 }
10166 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +000010167 }
10168 return rc;
10169}
drha154dcd2006-03-22 22:10:07 +000010170#endif
danielk1977b82e7ed2006-01-11 14:09:31 +000010171
danielk1977b4e9af92007-05-01 17:49:49 +000010172#ifndef SQLITE_OMIT_INCRBLOB
10173/*
10174** Argument pCsr must be a cursor opened for writing on an
10175** INTKEY table currently pointing at a valid table entry.
10176** This function modifies the data stored as part of that entry.
danielk1977ecaecf92009-07-08 08:05:35 +000010177**
10178** Only the data content may only be modified, it is not possible to
10179** change the length of the data stored. If this function is called with
10180** parameters that attempt to write past the end of the existing data,
10181** no modifications are made and SQLITE_CORRUPT is returned.
danielk1977b4e9af92007-05-01 17:49:49 +000010182*/
danielk1977dcbb5d32007-05-04 18:36:44 +000010183int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
danielk1977c9000e62009-07-08 13:55:28 +000010184 int rc;
dan7a2347e2016-01-07 16:43:54 +000010185 assert( cursorOwnsBtShared(pCsr) );
drhe5fe6902007-12-07 18:55:28 +000010186 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
drh036dbec2014-03-11 23:40:44 +000010187 assert( pCsr->curFlags & BTCF_Incrblob );
danielk19773588ceb2008-06-10 17:30:26 +000010188
danielk1977c9000e62009-07-08 13:55:28 +000010189 rc = restoreCursorPosition(pCsr);
10190 if( rc!=SQLITE_OK ){
10191 return rc;
10192 }
danielk19773588ceb2008-06-10 17:30:26 +000010193 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
10194 if( pCsr->eState!=CURSOR_VALID ){
10195 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +000010196 }
10197
dan227a1c42013-04-03 11:17:39 +000010198 /* Save the positions of all other cursors open on this table. This is
10199 ** required in case any of them are holding references to an xFetch
10200 ** version of the b-tree page modified by the accessPayload call below.
drh370c9f42013-04-03 20:04:04 +000010201 **
drh3f387402014-09-24 01:23:00 +000010202 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
drh370c9f42013-04-03 20:04:04 +000010203 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
10204 ** saveAllCursors can only return SQLITE_OK.
dan227a1c42013-04-03 11:17:39 +000010205 */
drh370c9f42013-04-03 20:04:04 +000010206 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
10207 assert( rc==SQLITE_OK );
dan227a1c42013-04-03 11:17:39 +000010208
danielk1977c9000e62009-07-08 13:55:28 +000010209 /* Check some assumptions:
danielk1977dcbb5d32007-05-04 18:36:44 +000010210 ** (a) the cursor is open for writing,
danielk1977c9000e62009-07-08 13:55:28 +000010211 ** (b) there is a read/write transaction open,
10212 ** (c) the connection holds a write-lock on the table (if required),
10213 ** (d) there are no conflicting read-locks, and
10214 ** (e) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +000010215 */
drh036dbec2014-03-11 23:40:44 +000010216 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
danielk19774f029602009-07-08 18:45:37 +000010217 return SQLITE_READONLY;
10218 }
drhc9166342012-01-05 23:32:06 +000010219 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
10220 && pCsr->pBt->inTransaction==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +000010221 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
10222 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
danielk1977c9000e62009-07-08 13:55:28 +000010223 assert( pCsr->apPage[pCsr->iPage]->intKey );
danielk1977b4e9af92007-05-01 17:49:49 +000010224
drhfb192682009-07-11 18:26:28 +000010225 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
danielk1977b4e9af92007-05-01 17:49:49 +000010226}
danielk19772dec9702007-05-02 16:48:37 +000010227
10228/*
dan5a500af2014-03-11 20:33:04 +000010229** Mark this cursor as an incremental blob cursor.
danielk19772dec9702007-05-02 16:48:37 +000010230*/
dan5a500af2014-03-11 20:33:04 +000010231void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
drh036dbec2014-03-11 23:40:44 +000010232 pCur->curFlags |= BTCF_Incrblob;
drh69180952015-06-25 13:03:10 +000010233 pCur->pBtree->hasIncrblobCur = 1;
danielk19772dec9702007-05-02 16:48:37 +000010234}
danielk1977b4e9af92007-05-01 17:49:49 +000010235#endif
dane04dc882010-04-20 18:53:15 +000010236
10237/*
10238** Set both the "read version" (single byte at byte offset 18) and
10239** "write version" (single byte at byte offset 19) fields in the database
10240** header to iVersion.
10241*/
10242int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
10243 BtShared *pBt = pBtree->pBt;
10244 int rc; /* Return code */
10245
dane04dc882010-04-20 18:53:15 +000010246 assert( iVersion==1 || iVersion==2 );
10247
danb9780022010-04-21 18:37:57 +000010248 /* If setting the version fields to 1, do not automatically open the
10249 ** WAL connection, even if the version fields are currently set to 2.
10250 */
drhc9166342012-01-05 23:32:06 +000010251 pBt->btsFlags &= ~BTS_NO_WAL;
10252 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
danb9780022010-04-21 18:37:57 +000010253
10254 rc = sqlite3BtreeBeginTrans(pBtree, 0);
dane04dc882010-04-20 18:53:15 +000010255 if( rc==SQLITE_OK ){
10256 u8 *aData = pBt->pPage1->aData;
danb9780022010-04-21 18:37:57 +000010257 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
danede6eb82010-04-22 06:27:04 +000010258 rc = sqlite3BtreeBeginTrans(pBtree, 2);
danb9780022010-04-21 18:37:57 +000010259 if( rc==SQLITE_OK ){
10260 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
10261 if( rc==SQLITE_OK ){
10262 aData[18] = (u8)iVersion;
10263 aData[19] = (u8)iVersion;
10264 }
10265 }
10266 }
dane04dc882010-04-20 18:53:15 +000010267 }
10268
drhc9166342012-01-05 23:32:06 +000010269 pBt->btsFlags &= ~BTS_NO_WAL;
dane04dc882010-04-20 18:53:15 +000010270 return rc;
10271}
dan428c2182012-08-06 18:50:11 +000010272
drhe0997b32015-03-20 14:57:50 +000010273/*
10274** Return true if the cursor has a hint specified. This routine is
10275** only used from within assert() statements
10276*/
10277int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
10278 return (pCsr->hints & mask)!=0;
10279}
drhe0997b32015-03-20 14:57:50 +000010280
drh781597f2014-05-21 08:21:07 +000010281/*
10282** Return true if the given Btree is read-only.
10283*/
10284int sqlite3BtreeIsReadonly(Btree *p){
10285 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
10286}
drhdef68892014-11-04 12:11:23 +000010287
10288/*
10289** Return the size of the header added to each page by this module.
10290*/
drh37c057b2014-12-30 00:57:29 +000010291int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
dan7b3d71e2015-08-19 20:27:05 +000010292
danf5cebf72015-08-22 17:28:55 +000010293/*
10294** This function is called to ensure that all locks required to commit the
10295** current write-transaction to the database file are held. If the db is
10296** in rollback mode, this means the EXCLUSIVE lock on the database file.
10297**
danbf3cf572015-08-24 19:56:04 +000010298** Or, if this is an CONCURRENT transaction on a wal-mode database, the WRITER
danf5cebf72015-08-22 17:28:55 +000010299** lock on the wal file. In this case this function also checks that the
danbf3cf572015-08-24 19:56:04 +000010300** CONCURRENT transaction can be safely committed (does not commit with any
danf5cebf72015-08-22 17:28:55 +000010301** other transaction committed since it was opened).
10302**
10303** SQLITE_OK is returned if successful. SQLITE_BUSY if the required locks
10304** cannot be obtained due to a conflicting lock. If the locks cannot be
danbf3cf572015-08-24 19:56:04 +000010305** obtained for an CONCURRENT transaction due to a conflict with an already
danf5cebf72015-08-22 17:28:55 +000010306** committed transaction, SQLITE_BUSY_SNAPSHOT is returned. Otherwise, if
10307** some other error (OOM, IO, etc.) occurs, the relevant SQLite error code
10308** is returned.
10309*/
dan7b3d71e2015-08-19 20:27:05 +000010310int sqlite3BtreeExclusiveLock(Btree *p){
10311 int rc;
dan995b2452017-05-29 19:23:56 +000010312 Pgno pgno = 0;
dan7b3d71e2015-08-19 20:27:05 +000010313 BtShared *pBt = p->pBt;
10314 assert( p->inTrans==TRANS_WRITE && pBt->pPage1 );
10315 sqlite3BtreeEnter(p);
dan995b2452017-05-29 19:23:56 +000010316 rc = sqlite3PagerExclusiveLock(pBt->pPager, pBt->pPage1->pDbPage, &pgno);
drh7365bcd2017-07-20 18:28:33 +000010317#ifdef SQLITE_OMIT_CONCURRENT
10318 assert( pgno==0 );
10319#else
dan995b2452017-05-29 19:23:56 +000010320 if( rc==SQLITE_BUSY_SNAPSHOT && pgno ){
10321 PgHdr *pPg = 0;
10322 int rc2 = sqlite3PagerGet(pBt->pPager, pgno, &pPg, 0);
10323 if( rc2==SQLITE_OK ){
10324 int bWrite = -1;
10325 const char *zObj = 0;
10326 const char *zTab = 0;
10327
10328 if( pPg ){
10329 Pgno pgnoRoot = 0;
10330 HashElem *pE;
10331 Schema *pSchema;
10332
10333 pgnoRoot = ((MemPage*)sqlite3PagerGetExtra(pPg))->pgnoRoot;
10334 bWrite = sqlite3PagerIswriteable(pPg);
10335 sqlite3PagerUnref(pPg);
10336
10337 pSchema = sqlite3SchemaGet(p->db, p);
10338 if( pSchema ){
10339 for(pE=sqliteHashFirst(&pSchema->tblHash); pE; pE=sqliteHashNext(pE)){
10340 Table *pTab = (Table *)sqliteHashData(pE);
10341 if( pTab->tnum==(int)pgnoRoot ){
10342 zObj = pTab->zName;
10343 zTab = 0;
10344 }else{
10345 Index *pIdx;
10346 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
10347 if( pIdx->tnum==(int)pgnoRoot ){
10348 zObj = pIdx->zName;
10349 zTab = pTab->zName;
10350 }
10351 }
10352 }
10353 }
10354 }
10355 }
10356
10357 sqlite3_log(SQLITE_OK,
10358 "cannot commit CONCURRENT transaction "
10359 "- conflict at page %d "
10360 "(%s page; part of db %s %s%s%s)",
10361 (int)pgno,
10362 (bWrite==0?"read-only":(bWrite>0?"read/write":"unknown")),
10363 (zTab ? "index" : "table"),
10364 (zTab ? zTab : ""), (zTab ? "." : ""), (zObj ? zObj : "UNKNOWN")
10365 );
10366 }
10367 }
drh7365bcd2017-07-20 18:28:33 +000010368#endif
dan7b3d71e2015-08-19 20:27:05 +000010369 sqlite3BtreeLeave(p);
10370 return rc;
10371}
danf687ba52016-01-14 15:46:31 +000010372
drh5a1fb182016-01-08 19:34:39 +000010373#if !defined(SQLITE_OMIT_SHARED_CACHE)
dan20d876f2016-01-07 16:06:22 +000010374/*
10375** Return true if the Btree passed as the only argument is sharable.
10376*/
10377int sqlite3BtreeSharable(Btree *p){
10378 return p->sharable;
10379}
dan272989b2016-07-06 10:12:02 +000010380
10381/*
10382** Return the number of connections to the BtShared object accessed by
10383** the Btree handle passed as the only argument. For private caches
10384** this is always 1. For shared caches it may be 1 or greater.
10385*/
10386int sqlite3BtreeConnectionCount(Btree *p){
10387 testcase( p->sharable );
10388 return p->pBt->nRef;
10389}
drh5a1fb182016-01-08 19:34:39 +000010390#endif