blob: a1b125dda89593f39568caf421ac871ae2e0fbdd [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
drh3908fe92017-09-01 14:50:19 +0000442static void releasePage(MemPage *pPage); /* Forward reference */
443static void releasePageOne(MemPage *pPage); /* Forward reference */
drh352a35a2017-08-15 03:46:47 +0000444static void releasePageNotNull(MemPage *pPage); /* Forward reference */
drh980b1a72006-08-16 16:42:48 +0000445
drh1fee73e2007-08-29 04:00:57 +0000446/*
drh0ee3dbe2009-10-16 15:05:18 +0000447***** This routine is used inside of assert() only ****
448**
449** Verify that the cursor holds the mutex on its BtShared
drh1fee73e2007-08-29 04:00:57 +0000450*/
drh0ee3dbe2009-10-16 15:05:18 +0000451#ifdef SQLITE_DEBUG
drh1fee73e2007-08-29 04:00:57 +0000452static int cursorHoldsMutex(BtCursor *p){
drhff0587c2007-08-29 17:43:19 +0000453 return sqlite3_mutex_held(p->pBt->mutex);
drh1fee73e2007-08-29 04:00:57 +0000454}
drh5e08d0f2016-06-04 21:05:54 +0000455
456/* Verify that the cursor and the BtShared agree about what is the current
457** database connetion. This is important in shared-cache mode. If the database
458** connection pointers get out-of-sync, it is possible for routines like
459** btreeInitPage() to reference an stale connection pointer that references a
460** a connection that has already closed. This routine is used inside assert()
461** statements only and for the purpose of double-checking that the btree code
462** does keep the database connection pointers up-to-date.
463*/
dan7a2347e2016-01-07 16:43:54 +0000464static int cursorOwnsBtShared(BtCursor *p){
465 assert( cursorHoldsMutex(p) );
466 return (p->pBtree->db==p->pBt->db);
467}
drh1fee73e2007-08-29 04:00:57 +0000468#endif
469
danielk197792d4d7a2007-05-04 12:05:56 +0000470/*
dan5a500af2014-03-11 20:33:04 +0000471** Invalidate the overflow cache of the cursor passed as the first argument.
472** on the shared btree structure pBt.
danielk197792d4d7a2007-05-04 12:05:56 +0000473*/
drh036dbec2014-03-11 23:40:44 +0000474#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
danielk197792d4d7a2007-05-04 12:05:56 +0000475
476/*
477** Invalidate the overflow page-list cache for all cursors opened
478** on the shared btree structure pBt.
479*/
480static void invalidateAllOverflowCache(BtShared *pBt){
481 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000482 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +0000483 for(p=pBt->pCursor; p; p=p->pNext){
484 invalidateOverflowCache(p);
485 }
486}
danielk197796d48e92009-06-29 06:00:37 +0000487
dan5a500af2014-03-11 20:33:04 +0000488#ifndef SQLITE_OMIT_INCRBLOB
danielk197796d48e92009-06-29 06:00:37 +0000489/*
490** This function is called before modifying the contents of a table
drh0ee3dbe2009-10-16 15:05:18 +0000491** to invalidate any incrblob cursors that are open on the
drheeb844a2009-08-08 18:01:07 +0000492** row or one of the rows being modified.
danielk197796d48e92009-06-29 06:00:37 +0000493**
494** If argument isClearTable is true, then the entire contents of the
495** table is about to be deleted. In this case invalidate all incrblob
496** cursors open on any row within the table with root-page pgnoRoot.
497**
498** Otherwise, if argument isClearTable is false, then the row with
499** rowid iRow is being replaced or deleted. In this case invalidate
drh0ee3dbe2009-10-16 15:05:18 +0000500** only those incrblob cursors open on that specific row.
danielk197796d48e92009-06-29 06:00:37 +0000501*/
502static void invalidateIncrblobCursors(
503 Btree *pBtree, /* The database file to check */
drh9ca431a2017-03-29 18:03:50 +0000504 Pgno pgnoRoot, /* The table that might be changing */
danielk197796d48e92009-06-29 06:00:37 +0000505 i64 iRow, /* The rowid that might be changing */
506 int isClearTable /* True if all rows are being deleted */
507){
508 BtCursor *p;
drh69180952015-06-25 13:03:10 +0000509 if( pBtree->hasIncrblobCur==0 ) return;
danielk197796d48e92009-06-29 06:00:37 +0000510 assert( sqlite3BtreeHoldsMutex(pBtree) );
drh69180952015-06-25 13:03:10 +0000511 pBtree->hasIncrblobCur = 0;
512 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
513 if( (p->curFlags & BTCF_Incrblob)!=0 ){
514 pBtree->hasIncrblobCur = 1;
drh9ca431a2017-03-29 18:03:50 +0000515 if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
drh69180952015-06-25 13:03:10 +0000516 p->eState = CURSOR_INVALID;
517 }
danielk197796d48e92009-06-29 06:00:37 +0000518 }
519 }
520}
521
danielk197792d4d7a2007-05-04 12:05:56 +0000522#else
dan5a500af2014-03-11 20:33:04 +0000523 /* Stub function when INCRBLOB is omitted */
drh9ca431a2017-03-29 18:03:50 +0000524 #define invalidateIncrblobCursors(w,x,y,z)
drh0ee3dbe2009-10-16 15:05:18 +0000525#endif /* SQLITE_OMIT_INCRBLOB */
danielk197792d4d7a2007-05-04 12:05:56 +0000526
drh980b1a72006-08-16 16:42:48 +0000527/*
danielk1977bea2a942009-01-20 17:06:27 +0000528** Set bit pgno of the BtShared.pHasContent bitvec. This is called
529** when a page that previously contained data becomes a free-list leaf
530** page.
531**
532** The BtShared.pHasContent bitvec exists to work around an obscure
533** bug caused by the interaction of two useful IO optimizations surrounding
534** free-list leaf pages:
535**
536** 1) When all data is deleted from a page and the page becomes
537** a free-list leaf page, the page is not written to the database
538** (as free-list leaf pages contain no meaningful data). Sometimes
539** such a page is not even journalled (as it will not be modified,
540** why bother journalling it?).
541**
542** 2) When a free-list leaf page is reused, its content is not read
543** from the database or written to the journal file (why should it
544** be, if it is not at all meaningful?).
545**
546** By themselves, these optimizations work fine and provide a handy
547** performance boost to bulk delete or insert operations. However, if
548** a page is moved to the free-list and then reused within the same
549** transaction, a problem comes up. If the page is not journalled when
550** it is moved to the free-list and it is also not journalled when it
551** is extracted from the free-list and reused, then the original data
552** may be lost. In the event of a rollback, it may not be possible
553** to restore the database to its original configuration.
554**
555** The solution is the BtShared.pHasContent bitvec. Whenever a page is
556** moved to become a free-list leaf page, the corresponding bit is
557** set in the bitvec. Whenever a leaf page is extracted from the free-list,
drh0ee3dbe2009-10-16 15:05:18 +0000558** optimization 2 above is omitted if the corresponding bit is already
danielk1977bea2a942009-01-20 17:06:27 +0000559** set in BtShared.pHasContent. The contents of the bitvec are cleared
560** at the end of every transaction.
561*/
562static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
563 int rc = SQLITE_OK;
564 if( !pBt->pHasContent ){
drhdd3cd972010-03-27 17:12:36 +0000565 assert( pgno<=pBt->nPage );
566 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
drh4c301aa2009-07-15 17:25:45 +0000567 if( !pBt->pHasContent ){
mistachkinfad30392016-02-13 23:43:46 +0000568 rc = SQLITE_NOMEM_BKPT;
danielk1977bea2a942009-01-20 17:06:27 +0000569 }
570 }
571 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
572 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
573 }
574 return rc;
575}
576
577/*
578** Query the BtShared.pHasContent vector.
579**
580** This function is called when a free-list leaf page is removed from the
581** free-list for reuse. It returns false if it is safe to retrieve the
582** page from the pager layer with the 'no-content' flag set. True otherwise.
583*/
584static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
585 Bitvec *p = pBt->pHasContent;
586 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
587}
588
589/*
590** Clear (destroy) the BtShared.pHasContent bitvec. This should be
591** invoked at the conclusion of each write-transaction.
592*/
593static void btreeClearHasContent(BtShared *pBt){
594 sqlite3BitvecDestroy(pBt->pHasContent);
595 pBt->pHasContent = 0;
596}
597
598/*
drh138eeeb2013-03-27 03:15:23 +0000599** Release all of the apPage[] pages for a cursor.
600*/
601static void btreeReleaseAllCursorPages(BtCursor *pCur){
602 int i;
drh352a35a2017-08-15 03:46:47 +0000603 if( pCur->iPage>=0 ){
604 for(i=0; i<pCur->iPage; i++){
605 releasePageNotNull(pCur->apPage[i]);
606 }
607 releasePageNotNull(pCur->pPage);
608 pCur->iPage = -1;
drh138eeeb2013-03-27 03:15:23 +0000609 }
drh138eeeb2013-03-27 03:15:23 +0000610}
611
danf0ee1d32015-09-12 19:26:11 +0000612/*
613** The cursor passed as the only argument must point to a valid entry
614** when this function is called (i.e. have eState==CURSOR_VALID). This
615** function saves the current cursor key in variables pCur->nKey and
616** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
617** code otherwise.
618**
619** If the cursor is open on an intkey table, then the integer key
620** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
621** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
622** set to point to a malloced buffer pCur->nKey bytes in size containing
623** the key.
624*/
625static int saveCursorKey(BtCursor *pCur){
drha7c90c42016-06-04 20:37:10 +0000626 int rc = SQLITE_OK;
danf0ee1d32015-09-12 19:26:11 +0000627 assert( CURSOR_VALID==pCur->eState );
628 assert( 0==pCur->pKey );
629 assert( cursorHoldsMutex(pCur) );
630
drha7c90c42016-06-04 20:37:10 +0000631 if( pCur->curIntKey ){
632 /* Only the rowid is required for a table btree */
633 pCur->nKey = sqlite3BtreeIntegerKey(pCur);
634 }else{
635 /* For an index btree, save the complete key content */
drhd66c4f82016-06-04 20:58:35 +0000636 void *pKey;
drha7c90c42016-06-04 20:37:10 +0000637 pCur->nKey = sqlite3BtreePayloadSize(pCur);
drhd66c4f82016-06-04 20:58:35 +0000638 pKey = sqlite3Malloc( pCur->nKey );
danf0ee1d32015-09-12 19:26:11 +0000639 if( pKey ){
drhcb3cabd2016-11-25 19:18:28 +0000640 rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
danf0ee1d32015-09-12 19:26:11 +0000641 if( rc==SQLITE_OK ){
642 pCur->pKey = pKey;
643 }else{
644 sqlite3_free(pKey);
645 }
646 }else{
mistachkinfad30392016-02-13 23:43:46 +0000647 rc = SQLITE_NOMEM_BKPT;
danf0ee1d32015-09-12 19:26:11 +0000648 }
649 }
650 assert( !pCur->curIntKey || !pCur->pKey );
651 return rc;
652}
drh138eeeb2013-03-27 03:15:23 +0000653
654/*
drh980b1a72006-08-16 16:42:48 +0000655** Save the current cursor position in the variables BtCursor.nKey
656** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
drhea8ffdf2009-07-22 00:35:23 +0000657**
658** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
659** prior to calling this routine.
drh980b1a72006-08-16 16:42:48 +0000660*/
661static int saveCursorPosition(BtCursor *pCur){
662 int rc;
663
drhd2f83132015-03-25 17:35:01 +0000664 assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
drh980b1a72006-08-16 16:42:48 +0000665 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000666 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000667
drhd2f83132015-03-25 17:35:01 +0000668 if( pCur->eState==CURSOR_SKIPNEXT ){
669 pCur->eState = CURSOR_VALID;
670 }else{
671 pCur->skipNext = 0;
672 }
drh980b1a72006-08-16 16:42:48 +0000673
danf0ee1d32015-09-12 19:26:11 +0000674 rc = saveCursorKey(pCur);
drh980b1a72006-08-16 16:42:48 +0000675 if( rc==SQLITE_OK ){
drh138eeeb2013-03-27 03:15:23 +0000676 btreeReleaseAllCursorPages(pCur);
drh980b1a72006-08-16 16:42:48 +0000677 pCur->eState = CURSOR_REQUIRESEEK;
678 }
679
dane755e102015-09-30 12:59:12 +0000680 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
drh980b1a72006-08-16 16:42:48 +0000681 return rc;
682}
683
drh637f3d82014-08-22 22:26:07 +0000684/* Forward reference */
685static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
686
drh980b1a72006-08-16 16:42:48 +0000687/*
drh0ee3dbe2009-10-16 15:05:18 +0000688** Save the positions of all cursors (except pExcept) that are open on
drh637f3d82014-08-22 22:26:07 +0000689** the table with root-page iRoot. "Saving the cursor position" means that
690** the location in the btree is remembered in such a way that it can be
691** moved back to the same spot after the btree has been modified. This
692** routine is called just before cursor pExcept is used to modify the
693** table, for example in BtreeDelete() or BtreeInsert().
694**
drh27fb7462015-06-30 02:47:36 +0000695** If there are two or more cursors on the same btree, then all such
696** cursors should have their BTCF_Multiple flag set. The btreeCursor()
697** routine enforces that rule. This routine only needs to be called in
698** the uncommon case when pExpect has the BTCF_Multiple flag set.
699**
700** If pExpect!=NULL and if no other cursors are found on the same root-page,
701** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
702** pointless call to this routine.
703**
drh637f3d82014-08-22 22:26:07 +0000704** Implementation note: This routine merely checks to see if any cursors
705** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
706** event that cursors are in need to being saved.
drh980b1a72006-08-16 16:42:48 +0000707*/
708static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
709 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000710 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000711 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000712 for(p=pBt->pCursor; p; p=p->pNext){
drh637f3d82014-08-22 22:26:07 +0000713 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
714 }
drh27fb7462015-06-30 02:47:36 +0000715 if( p ) return saveCursorsOnList(p, iRoot, pExcept);
716 if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
717 return SQLITE_OK;
drh637f3d82014-08-22 22:26:07 +0000718}
719
720/* This helper routine to saveAllCursors does the actual work of saving
721** the cursors if and when a cursor is found that actually requires saving.
722** The common case is that no cursors need to be saved, so this routine is
723** broken out from its caller to avoid unnecessary stack pointer movement.
724*/
725static int SQLITE_NOINLINE saveCursorsOnList(
drh3f387402014-09-24 01:23:00 +0000726 BtCursor *p, /* The first cursor that needs saving */
727 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
728 BtCursor *pExcept /* Do not save this cursor */
drh637f3d82014-08-22 22:26:07 +0000729){
730 do{
drh138eeeb2013-03-27 03:15:23 +0000731 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
drhd2f83132015-03-25 17:35:01 +0000732 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
drh138eeeb2013-03-27 03:15:23 +0000733 int rc = saveCursorPosition(p);
734 if( SQLITE_OK!=rc ){
735 return rc;
736 }
737 }else{
drh85ef6302017-08-02 15:50:09 +0000738 testcase( p->iPage>=0 );
drh138eeeb2013-03-27 03:15:23 +0000739 btreeReleaseAllCursorPages(p);
drh980b1a72006-08-16 16:42:48 +0000740 }
741 }
drh637f3d82014-08-22 22:26:07 +0000742 p = p->pNext;
743 }while( p );
drh980b1a72006-08-16 16:42:48 +0000744 return SQLITE_OK;
745}
746
747/*
drhbf700f32007-03-31 02:36:44 +0000748** Clear the current cursor position.
749*/
danielk1977be51a652008-10-08 17:58:48 +0000750void sqlite3BtreeClearCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000751 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000752 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +0000753 pCur->pKey = 0;
754 pCur->eState = CURSOR_INVALID;
755}
756
757/*
danielk19773509a652009-07-06 18:56:13 +0000758** In this version of BtreeMoveto, pKey is a packed index record
759** such as is generated by the OP_MakeRecord opcode. Unpack the
760** record and then call BtreeMovetoUnpacked() to do the work.
761*/
762static int btreeMoveto(
763 BtCursor *pCur, /* Cursor open on the btree to be searched */
764 const void *pKey, /* Packed key if the btree is an index */
765 i64 nKey, /* Integer key for tables. Size of pKey for indices */
766 int bias, /* Bias search to the high end */
767 int *pRes /* Write search results here */
768){
769 int rc; /* Status code */
770 UnpackedRecord *pIdxKey; /* Unpacked index key */
danielk19773509a652009-07-06 18:56:13 +0000771
772 if( pKey ){
773 assert( nKey==(i64)(int)nKey );
drha582b012016-12-21 19:45:54 +0000774 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pCur->pKeyInfo);
mistachkinfad30392016-02-13 23:43:46 +0000775 if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
mistachkin0fe5f952011-09-14 18:19:08 +0000776 sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
drh094b7582013-11-30 12:49:28 +0000777 if( pIdxKey->nField==0 ){
mistachkin88a79732017-09-04 19:31:54 +0000778 rc = SQLITE_CORRUPT_BKPT;
drha582b012016-12-21 19:45:54 +0000779 goto moveto_done;
drh094b7582013-11-30 12:49:28 +0000780 }
danielk19773509a652009-07-06 18:56:13 +0000781 }else{
782 pIdxKey = 0;
783 }
784 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
drha582b012016-12-21 19:45:54 +0000785moveto_done:
786 if( pIdxKey ){
787 sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
danielk19773509a652009-07-06 18:56:13 +0000788 }
789 return rc;
790}
791
792/*
drh980b1a72006-08-16 16:42:48 +0000793** Restore the cursor to the position it was in (or as close to as possible)
794** when saveCursorPosition() was called. Note that this call deletes the
795** saved position info stored by saveCursorPosition(), so there can be
drha3460582008-07-11 21:02:53 +0000796** at most one effective restoreCursorPosition() call after each
drh980b1a72006-08-16 16:42:48 +0000797** saveCursorPosition().
drh980b1a72006-08-16 16:42:48 +0000798*/
danielk197730548662009-07-09 05:07:37 +0000799static int btreeRestoreCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000800 int rc;
drhd2f83132015-03-25 17:35:01 +0000801 int skipNext;
dan7a2347e2016-01-07 16:43:54 +0000802 assert( cursorOwnsBtShared(pCur) );
drhfb982642007-08-30 01:19:59 +0000803 assert( pCur->eState>=CURSOR_REQUIRESEEK );
804 if( pCur->eState==CURSOR_FAULT ){
drh4c301aa2009-07-15 17:25:45 +0000805 return pCur->skipNext;
drhfb982642007-08-30 01:19:59 +0000806 }
drh980b1a72006-08-16 16:42:48 +0000807 pCur->eState = CURSOR_INVALID;
drhd2f83132015-03-25 17:35:01 +0000808 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
drh980b1a72006-08-16 16:42:48 +0000809 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +0000810 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +0000811 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +0000812 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drhd2f83132015-03-25 17:35:01 +0000813 pCur->skipNext |= skipNext;
drh9b47ee32013-08-20 03:13:51 +0000814 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
815 pCur->eState = CURSOR_SKIPNEXT;
816 }
drh980b1a72006-08-16 16:42:48 +0000817 }
818 return rc;
819}
820
drha3460582008-07-11 21:02:53 +0000821#define restoreCursorPosition(p) \
drhfb982642007-08-30 01:19:59 +0000822 (p->eState>=CURSOR_REQUIRESEEK ? \
danielk197730548662009-07-09 05:07:37 +0000823 btreeRestoreCursorPosition(p) : \
drh16a9b832007-05-05 18:39:25 +0000824 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +0000825
drha3460582008-07-11 21:02:53 +0000826/*
drh6848dad2014-08-22 23:33:03 +0000827** Determine whether or not a cursor has moved from the position where
828** it was last placed, or has been invalidated for any other reason.
829** Cursors can move when the row they are pointing at is deleted out
830** from under them, for example. Cursor might also move if a btree
831** is rebalanced.
drha3460582008-07-11 21:02:53 +0000832**
drh6848dad2014-08-22 23:33:03 +0000833** Calling this routine with a NULL cursor pointer returns false.
drh86dd3712014-03-25 11:00:21 +0000834**
drh6848dad2014-08-22 23:33:03 +0000835** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
836** back to where it ought to be if this routine returns true.
drha3460582008-07-11 21:02:53 +0000837*/
drh6848dad2014-08-22 23:33:03 +0000838int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
drhc22284f2014-10-13 16:02:20 +0000839 return pCur->eState!=CURSOR_VALID;
drh6848dad2014-08-22 23:33:03 +0000840}
841
842/*
drhfe0cf7a2017-08-16 19:20:20 +0000843** Return a pointer to a fake BtCursor object that will always answer
844** false to the sqlite3BtreeCursorHasMoved() routine above. The fake
845** cursor returned must not be used with any other Btree interface.
846*/
847BtCursor *sqlite3BtreeFakeValidCursor(void){
848 static u8 fakeCursor = CURSOR_VALID;
849 assert( offsetof(BtCursor, eState)==0 );
850 return (BtCursor*)&fakeCursor;
851}
852
853/*
drh6848dad2014-08-22 23:33:03 +0000854** This routine restores a cursor back to its original position after it
855** has been moved by some outside activity (such as a btree rebalance or
856** a row having been deleted out from under the cursor).
857**
858** On success, the *pDifferentRow parameter is false if the cursor is left
859** pointing at exactly the same row. *pDifferntRow is the row the cursor
860** was pointing to has been deleted, forcing the cursor to point to some
861** nearby row.
862**
863** This routine should only be called for a cursor that just returned
864** TRUE from sqlite3BtreeCursorHasMoved().
865*/
866int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
drha3460582008-07-11 21:02:53 +0000867 int rc;
868
drh6848dad2014-08-22 23:33:03 +0000869 assert( pCur!=0 );
870 assert( pCur->eState!=CURSOR_VALID );
drha3460582008-07-11 21:02:53 +0000871 rc = restoreCursorPosition(pCur);
872 if( rc ){
drh6848dad2014-08-22 23:33:03 +0000873 *pDifferentRow = 1;
drha3460582008-07-11 21:02:53 +0000874 return rc;
875 }
drh606a3572015-03-25 18:29:10 +0000876 if( pCur->eState!=CURSOR_VALID ){
drh6848dad2014-08-22 23:33:03 +0000877 *pDifferentRow = 1;
drha3460582008-07-11 21:02:53 +0000878 }else{
drh606a3572015-03-25 18:29:10 +0000879 assert( pCur->skipNext==0 );
drh6848dad2014-08-22 23:33:03 +0000880 *pDifferentRow = 0;
drha3460582008-07-11 21:02:53 +0000881 }
882 return SQLITE_OK;
883}
884
drhf7854c72015-10-27 13:24:37 +0000885#ifdef SQLITE_ENABLE_CURSOR_HINTS
drh28935362013-12-07 20:39:19 +0000886/*
drh0df57012015-08-14 15:05:55 +0000887** Provide hints to the cursor. The particular hint given (and the type
888** and number of the varargs parameters) is determined by the eHintType
889** parameter. See the definitions of the BTREE_HINT_* macros for details.
drh28935362013-12-07 20:39:19 +0000890*/
drh0df57012015-08-14 15:05:55 +0000891void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
drhf7854c72015-10-27 13:24:37 +0000892 /* Used only by system that substitute their own storage engine */
drh28935362013-12-07 20:39:19 +0000893}
drhf7854c72015-10-27 13:24:37 +0000894#endif
895
896/*
897** Provide flag hints to the cursor.
898*/
899void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
900 assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
901 pCur->hints = x;
902}
903
drh28935362013-12-07 20:39:19 +0000904
danielk1977599fcba2004-11-08 07:13:13 +0000905#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000906/*
drha3152892007-05-05 11:48:52 +0000907** Given a page number of a regular database page, return the page
908** number for the pointer-map page that contains the entry for the
909** input page number.
drh5f77b2e2010-08-21 15:09:37 +0000910**
911** Return 0 (not a valid page) for pgno==1 since there is
912** no pointer map associated with page 1. The integrity_check logic
913** requires that ptrmapPageno(*,1)!=1.
danielk1977afcdd022004-10-31 16:25:42 +0000914*/
danielk1977266664d2006-02-10 08:24:21 +0000915static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
danielk197789d40042008-11-17 14:20:56 +0000916 int nPagesPerMapPage;
917 Pgno iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +0000918 assert( sqlite3_mutex_held(pBt->mutex) );
drh5f77b2e2010-08-21 15:09:37 +0000919 if( pgno<2 ) return 0;
drhd677b3d2007-08-20 22:48:41 +0000920 nPagesPerMapPage = (pBt->usableSize/5)+1;
921 iPtrMap = (pgno-2)/nPagesPerMapPage;
922 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +0000923 if( ret==PENDING_BYTE_PAGE(pBt) ){
924 ret++;
925 }
926 return ret;
927}
danielk1977a19df672004-11-03 11:37:07 +0000928
danielk1977afcdd022004-10-31 16:25:42 +0000929/*
danielk1977afcdd022004-10-31 16:25:42 +0000930** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000931**
932** This routine updates the pointer map entry for page number 'key'
933** so that it maps to type 'eType' and parent page number 'pgno'.
drh98add2e2009-07-20 17:11:49 +0000934**
935** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
936** a no-op. If an error occurs, the appropriate error code is written
937** into *pRC.
danielk1977afcdd022004-10-31 16:25:42 +0000938*/
drh98add2e2009-07-20 17:11:49 +0000939static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
danielk19773b8a05f2007-03-19 17:44:26 +0000940 DbPage *pDbPage; /* The pointer map page */
941 u8 *pPtrmap; /* The pointer map data */
942 Pgno iPtrmap; /* The pointer map page number */
943 int offset; /* Offset in pointer map page */
drh98add2e2009-07-20 17:11:49 +0000944 int rc; /* Return code from subfunctions */
945
946 if( *pRC ) return;
danielk1977afcdd022004-10-31 16:25:42 +0000947
drh1fee73e2007-08-29 04:00:57 +0000948 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977266664d2006-02-10 08:24:21 +0000949 /* The master-journal page number must never be used as a pointer map page */
950 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
951
danielk1977ac11ee62005-01-15 12:45:51 +0000952 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000953 if( key==0 ){
drh98add2e2009-07-20 17:11:49 +0000954 *pRC = SQLITE_CORRUPT_BKPT;
955 return;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000956 }
danielk1977266664d2006-02-10 08:24:21 +0000957 iPtrmap = PTRMAP_PAGENO(pBt, key);
drh9584f582015-11-04 20:22:37 +0000958 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
danielk1977687566d2004-11-02 12:56:41 +0000959 if( rc!=SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +0000960 *pRC = rc;
961 return;
danielk1977afcdd022004-10-31 16:25:42 +0000962 }
danielk19778c666b12008-07-18 09:34:57 +0000963 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drhacfc72b2009-06-05 18:44:15 +0000964 if( offset<0 ){
drh98add2e2009-07-20 17:11:49 +0000965 *pRC = SQLITE_CORRUPT_BKPT;
drh4925a552009-07-07 11:39:58 +0000966 goto ptrmap_exit;
drhacfc72b2009-06-05 18:44:15 +0000967 }
drhfc243732011-05-17 15:21:56 +0000968 assert( offset <= (int)pBt->usableSize-5 );
danielk19773b8a05f2007-03-19 17:44:26 +0000969 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000970
drh615ae552005-01-16 23:21:00 +0000971 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
972 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
drh98add2e2009-07-20 17:11:49 +0000973 *pRC= rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000974 if( rc==SQLITE_OK ){
975 pPtrmap[offset] = eType;
976 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000977 }
danielk1977afcdd022004-10-31 16:25:42 +0000978 }
979
drh4925a552009-07-07 11:39:58 +0000980ptrmap_exit:
danielk19773b8a05f2007-03-19 17:44:26 +0000981 sqlite3PagerUnref(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000982}
983
984/*
985** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000986**
987** This routine retrieves the pointer map entry for page 'key', writing
988** the type and parent page number to *pEType and *pPgno respectively.
989** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000990*/
danielk1977aef0bf62005-12-30 16:28:01 +0000991static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000992 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000993 int iPtrmap; /* Pointer map page index */
994 u8 *pPtrmap; /* Pointer map page data */
995 int offset; /* Offset of entry in pointer map */
996 int rc;
997
drh1fee73e2007-08-29 04:00:57 +0000998 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000999
danielk1977266664d2006-02-10 08:24:21 +00001000 iPtrmap = PTRMAP_PAGENO(pBt, key);
drh9584f582015-11-04 20:22:37 +00001001 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00001002 if( rc!=0 ){
1003 return rc;
1004 }
danielk19773b8a05f2007-03-19 17:44:26 +00001005 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +00001006
danielk19778c666b12008-07-18 09:34:57 +00001007 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drhfc243732011-05-17 15:21:56 +00001008 if( offset<0 ){
1009 sqlite3PagerUnref(pDbPage);
1010 return SQLITE_CORRUPT_BKPT;
1011 }
1012 assert( offset <= (int)pBt->usableSize-5 );
drh43617e92006-03-06 20:55:46 +00001013 assert( pEType!=0 );
1014 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +00001015 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +00001016
danielk19773b8a05f2007-03-19 17:44:26 +00001017 sqlite3PagerUnref(pDbPage);
drhcc97ca42017-06-07 22:32:59 +00001018 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
danielk1977afcdd022004-10-31 16:25:42 +00001019 return SQLITE_OK;
1020}
1021
danielk197785d90ca2008-07-19 14:25:15 +00001022#else /* if defined SQLITE_OMIT_AUTOVACUUM */
drh98add2e2009-07-20 17:11:49 +00001023 #define ptrmapPut(w,x,y,z,rc)
danielk197785d90ca2008-07-19 14:25:15 +00001024 #define ptrmapGet(w,x,y,z) SQLITE_OK
drh98add2e2009-07-20 17:11:49 +00001025 #define ptrmapPutOvflPtr(x, y, rc)
danielk197785d90ca2008-07-19 14:25:15 +00001026#endif
danielk1977afcdd022004-10-31 16:25:42 +00001027
drh0d316a42002-08-11 20:10:47 +00001028/*
drh271efa52004-05-30 19:19:05 +00001029** Given a btree page and a cell index (0 means the first cell on
1030** the page, 1 means the second cell, and so forth) return a pointer
1031** to the cell content.
1032**
drhf44890a2015-06-27 03:58:15 +00001033** findCellPastPtr() does the same except it skips past the initial
1034** 4-byte child pointer found on interior pages, if there is one.
1035**
drh271efa52004-05-30 19:19:05 +00001036** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +00001037*/
drh1688c862008-07-18 02:44:17 +00001038#define findCell(P,I) \
drh329428e2015-06-30 13:28:18 +00001039 ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
drhf44890a2015-06-27 03:58:15 +00001040#define findCellPastPtr(P,I) \
drh329428e2015-06-30 13:28:18 +00001041 ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
drh68f2a572011-06-03 17:50:49 +00001042
drh43605152004-05-29 21:46:49 +00001043
1044/*
drh5fa60512015-06-19 17:19:34 +00001045** This is common tail processing for btreeParseCellPtr() and
1046** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
1047** on a single B-tree page. Make necessary adjustments to the CellInfo
1048** structure.
drh43605152004-05-29 21:46:49 +00001049*/
drh5fa60512015-06-19 17:19:34 +00001050static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
1051 MemPage *pPage, /* Page containing the cell */
1052 u8 *pCell, /* Pointer to the cell text. */
1053 CellInfo *pInfo /* Fill in this structure */
1054){
1055 /* If the payload will not fit completely on the local page, we have
1056 ** to decide how much to store locally and how much to spill onto
1057 ** overflow pages. The strategy is to minimize the amount of unused
1058 ** space on overflow pages while keeping the amount of local storage
1059 ** in between minLocal and maxLocal.
1060 **
1061 ** Warning: changing the way overflow payload is distributed in any
1062 ** way will result in an incompatible file format.
1063 */
1064 int minLocal; /* Minimum amount of payload held locally */
1065 int maxLocal; /* Maximum amount of payload held locally */
1066 int surplus; /* Overflow payload available for local storage */
1067
1068 minLocal = pPage->minLocal;
1069 maxLocal = pPage->maxLocal;
1070 surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
1071 testcase( surplus==maxLocal );
1072 testcase( surplus==maxLocal+1 );
1073 if( surplus <= maxLocal ){
1074 pInfo->nLocal = (u16)surplus;
1075 }else{
1076 pInfo->nLocal = (u16)minLocal;
drh43605152004-05-29 21:46:49 +00001077 }
drh45ac1c72015-12-18 03:59:16 +00001078 pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
drh43605152004-05-29 21:46:49 +00001079}
1080
1081/*
drh5fa60512015-06-19 17:19:34 +00001082** The following routines are implementations of the MemPage.xParseCell()
1083** method.
danielk19771cc5ed82007-05-16 17:28:43 +00001084**
drh5fa60512015-06-19 17:19:34 +00001085** Parse a cell content block and fill in the CellInfo structure.
1086**
1087** btreeParseCellPtr() => table btree leaf nodes
1088** btreeParseCellNoPayload() => table btree internal nodes
1089** btreeParseCellPtrIndex() => index btree nodes
1090**
1091** There is also a wrapper function btreeParseCell() that works for
1092** all MemPage types and that references the cell by index rather than
1093** by pointer.
drh43605152004-05-29 21:46:49 +00001094*/
drh5fa60512015-06-19 17:19:34 +00001095static void btreeParseCellPtrNoPayload(
1096 MemPage *pPage, /* Page containing the cell */
1097 u8 *pCell, /* Pointer to the cell text. */
1098 CellInfo *pInfo /* Fill in this structure */
1099){
1100 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1101 assert( pPage->leaf==0 );
drh5fa60512015-06-19 17:19:34 +00001102 assert( pPage->childPtrSize==4 );
drh94a31152015-07-01 04:08:40 +00001103#ifndef SQLITE_DEBUG
1104 UNUSED_PARAMETER(pPage);
1105#endif
drh5fa60512015-06-19 17:19:34 +00001106 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
1107 pInfo->nPayload = 0;
1108 pInfo->nLocal = 0;
drh5fa60512015-06-19 17:19:34 +00001109 pInfo->pPayload = 0;
1110 return;
1111}
danielk197730548662009-07-09 05:07:37 +00001112static void btreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +00001113 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +00001114 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +00001115 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +00001116){
drh3e28ff52014-09-24 00:59:08 +00001117 u8 *pIter; /* For scanning through pCell */
drh271efa52004-05-30 19:19:05 +00001118 u32 nPayload; /* Number of bytes of cell payload */
drh56cb04e2015-06-19 18:24:37 +00001119 u64 iKey; /* Extracted Key value */
drh43605152004-05-29 21:46:49 +00001120
drh1fee73e2007-08-29 04:00:57 +00001121 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhab01f612004-05-22 02:55:23 +00001122 assert( pPage->leaf==0 || pPage->leaf==1 );
drh5fa60512015-06-19 17:19:34 +00001123 assert( pPage->intKeyLeaf );
1124 assert( pPage->childPtrSize==0 );
drh56cb04e2015-06-19 18:24:37 +00001125 pIter = pCell;
1126
1127 /* The next block of code is equivalent to:
1128 **
1129 ** pIter += getVarint32(pIter, nPayload);
1130 **
1131 ** The code is inlined to avoid a function call.
1132 */
1133 nPayload = *pIter;
1134 if( nPayload>=0x80 ){
drheeab2c62015-06-19 20:08:39 +00001135 u8 *pEnd = &pIter[8];
drh56cb04e2015-06-19 18:24:37 +00001136 nPayload &= 0x7f;
1137 do{
1138 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1139 }while( (*pIter)>=0x80 && pIter<pEnd );
drh6f11bef2004-05-13 01:12:56 +00001140 }
drh56cb04e2015-06-19 18:24:37 +00001141 pIter++;
1142
1143 /* The next block of code is equivalent to:
1144 **
1145 ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
1146 **
1147 ** The code is inlined to avoid a function call.
1148 */
1149 iKey = *pIter;
1150 if( iKey>=0x80 ){
1151 u8 *pEnd = &pIter[7];
1152 iKey &= 0x7f;
1153 while(1){
1154 iKey = (iKey<<7) | (*++pIter & 0x7f);
1155 if( (*pIter)<0x80 ) break;
1156 if( pIter>=pEnd ){
1157 iKey = (iKey<<8) | *++pIter;
1158 break;
1159 }
1160 }
1161 }
1162 pIter++;
1163
1164 pInfo->nKey = *(i64*)&iKey;
drh72365832007-03-06 15:53:44 +00001165 pInfo->nPayload = nPayload;
drhab1cc582014-09-23 21:25:19 +00001166 pInfo->pPayload = pIter;
drh0a45c272009-07-08 01:49:11 +00001167 testcase( nPayload==pPage->maxLocal );
1168 testcase( nPayload==pPage->maxLocal+1 );
drhab1cc582014-09-23 21:25:19 +00001169 if( nPayload<=pPage->maxLocal ){
drh271efa52004-05-30 19:19:05 +00001170 /* This is the (easy) common case where the entire payload fits
1171 ** on the local page. No overflow is required.
1172 */
drhab1cc582014-09-23 21:25:19 +00001173 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1174 if( pInfo->nSize<4 ) pInfo->nSize = 4;
drhf49661a2008-12-10 16:45:50 +00001175 pInfo->nLocal = (u16)nPayload;
drh6f11bef2004-05-13 01:12:56 +00001176 }else{
drh5fa60512015-06-19 17:19:34 +00001177 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
drh6f11bef2004-05-13 01:12:56 +00001178 }
drh3aac2dd2004-04-26 14:10:20 +00001179}
drh5fa60512015-06-19 17:19:34 +00001180static void btreeParseCellPtrIndex(
1181 MemPage *pPage, /* Page containing the cell */
1182 u8 *pCell, /* Pointer to the cell text. */
1183 CellInfo *pInfo /* Fill in this structure */
1184){
1185 u8 *pIter; /* For scanning through pCell */
1186 u32 nPayload; /* Number of bytes of cell payload */
drh3aac2dd2004-04-26 14:10:20 +00001187
drh5fa60512015-06-19 17:19:34 +00001188 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1189 assert( pPage->leaf==0 || pPage->leaf==1 );
1190 assert( pPage->intKeyLeaf==0 );
drh5fa60512015-06-19 17:19:34 +00001191 pIter = pCell + pPage->childPtrSize;
1192 nPayload = *pIter;
1193 if( nPayload>=0x80 ){
drheeab2c62015-06-19 20:08:39 +00001194 u8 *pEnd = &pIter[8];
drh5fa60512015-06-19 17:19:34 +00001195 nPayload &= 0x7f;
1196 do{
1197 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1198 }while( *(pIter)>=0x80 && pIter<pEnd );
1199 }
1200 pIter++;
1201 pInfo->nKey = nPayload;
1202 pInfo->nPayload = nPayload;
1203 pInfo->pPayload = pIter;
1204 testcase( nPayload==pPage->maxLocal );
1205 testcase( nPayload==pPage->maxLocal+1 );
1206 if( nPayload<=pPage->maxLocal ){
1207 /* This is the (easy) common case where the entire payload fits
1208 ** on the local page. No overflow is required.
1209 */
1210 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1211 if( pInfo->nSize<4 ) pInfo->nSize = 4;
1212 pInfo->nLocal = (u16)nPayload;
drh5fa60512015-06-19 17:19:34 +00001213 }else{
1214 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
drh3aac2dd2004-04-26 14:10:20 +00001215 }
1216}
danielk197730548662009-07-09 05:07:37 +00001217static void btreeParseCell(
drh43605152004-05-29 21:46:49 +00001218 MemPage *pPage, /* Page containing the cell */
1219 int iCell, /* The cell index. First cell is 0 */
1220 CellInfo *pInfo /* Fill in this structure */
1221){
drh5fa60512015-06-19 17:19:34 +00001222 pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
drh43605152004-05-29 21:46:49 +00001223}
drh3aac2dd2004-04-26 14:10:20 +00001224
1225/*
drh5fa60512015-06-19 17:19:34 +00001226** The following routines are implementations of the MemPage.xCellSize
1227** method.
1228**
drh43605152004-05-29 21:46:49 +00001229** Compute the total number of bytes that a Cell needs in the cell
1230** data area of the btree-page. The return number includes the cell
1231** data header and the local payload, but not any overflow page or
1232** the space used by the cell pointer.
drh25ada072015-06-19 15:07:14 +00001233**
drh5fa60512015-06-19 17:19:34 +00001234** cellSizePtrNoPayload() => table internal nodes
1235** cellSizePtr() => all index nodes & table leaf nodes
drh3b7511c2001-05-26 13:15:44 +00001236*/
danielk1977ae5558b2009-04-29 11:31:47 +00001237static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
drh3f387402014-09-24 01:23:00 +00001238 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
1239 u8 *pEnd; /* End mark for a varint */
1240 u32 nSize; /* Size value to return */
danielk1977ae5558b2009-04-29 11:31:47 +00001241
1242#ifdef SQLITE_DEBUG
1243 /* The value returned by this function should always be the same as
1244 ** the (CellInfo.nSize) value found by doing a full parse of the
1245 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1246 ** this function verifies that this invariant is not violated. */
1247 CellInfo debuginfo;
drh5fa60512015-06-19 17:19:34 +00001248 pPage->xParseCell(pPage, pCell, &debuginfo);
danielk1977ae5558b2009-04-29 11:31:47 +00001249#endif
1250
drh3e28ff52014-09-24 00:59:08 +00001251 nSize = *pIter;
1252 if( nSize>=0x80 ){
drheeab2c62015-06-19 20:08:39 +00001253 pEnd = &pIter[8];
drh3e28ff52014-09-24 00:59:08 +00001254 nSize &= 0x7f;
1255 do{
1256 nSize = (nSize<<7) | (*++pIter & 0x7f);
1257 }while( *(pIter)>=0x80 && pIter<pEnd );
1258 }
1259 pIter++;
danielk1977ae5558b2009-04-29 11:31:47 +00001260 if( pPage->intKey ){
danielk1977ae5558b2009-04-29 11:31:47 +00001261 /* pIter now points at the 64-bit integer key value, a variable length
1262 ** integer. The following block moves pIter to point at the first byte
1263 ** past the end of the key value. */
1264 pEnd = &pIter[9];
1265 while( (*pIter++)&0x80 && pIter<pEnd );
danielk1977ae5558b2009-04-29 11:31:47 +00001266 }
drh0a45c272009-07-08 01:49:11 +00001267 testcase( nSize==pPage->maxLocal );
1268 testcase( nSize==pPage->maxLocal+1 );
drh3e28ff52014-09-24 00:59:08 +00001269 if( nSize<=pPage->maxLocal ){
1270 nSize += (u32)(pIter - pCell);
1271 if( nSize<4 ) nSize = 4;
1272 }else{
danielk1977ae5558b2009-04-29 11:31:47 +00001273 int minLocal = pPage->minLocal;
1274 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
drh0a45c272009-07-08 01:49:11 +00001275 testcase( nSize==pPage->maxLocal );
1276 testcase( nSize==pPage->maxLocal+1 );
danielk1977ae5558b2009-04-29 11:31:47 +00001277 if( nSize>pPage->maxLocal ){
1278 nSize = minLocal;
1279 }
drh3e28ff52014-09-24 00:59:08 +00001280 nSize += 4 + (u16)(pIter - pCell);
danielk1977ae5558b2009-04-29 11:31:47 +00001281 }
drhdc41d602014-09-22 19:51:35 +00001282 assert( nSize==debuginfo.nSize || CORRUPT_DB );
shane60a4b532009-05-06 18:57:09 +00001283 return (u16)nSize;
danielk1977ae5558b2009-04-29 11:31:47 +00001284}
drh25ada072015-06-19 15:07:14 +00001285static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
1286 u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
1287 u8 *pEnd; /* End mark for a varint */
1288
1289#ifdef SQLITE_DEBUG
1290 /* The value returned by this function should always be the same as
1291 ** the (CellInfo.nSize) value found by doing a full parse of the
1292 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1293 ** this function verifies that this invariant is not violated. */
1294 CellInfo debuginfo;
drh5fa60512015-06-19 17:19:34 +00001295 pPage->xParseCell(pPage, pCell, &debuginfo);
drh94a31152015-07-01 04:08:40 +00001296#else
1297 UNUSED_PARAMETER(pPage);
drh25ada072015-06-19 15:07:14 +00001298#endif
1299
1300 assert( pPage->childPtrSize==4 );
1301 pEnd = pIter + 9;
1302 while( (*pIter++)&0x80 && pIter<pEnd );
1303 assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
1304 return (u16)(pIter - pCell);
1305}
1306
drh0ee3dbe2009-10-16 15:05:18 +00001307
1308#ifdef SQLITE_DEBUG
1309/* This variation on cellSizePtr() is used inside of assert() statements
1310** only. */
drha9121e42008-02-19 14:59:35 +00001311static u16 cellSize(MemPage *pPage, int iCell){
drh25ada072015-06-19 15:07:14 +00001312 return pPage->xCellSize(pPage, findCell(pPage, iCell));
drh43605152004-05-29 21:46:49 +00001313}
danielk1977bc6ada42004-06-30 08:20:16 +00001314#endif
drh3b7511c2001-05-26 13:15:44 +00001315
danielk197779a40da2005-01-16 08:00:01 +00001316#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +00001317/*
danielk197726836652005-01-17 01:33:13 +00001318** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +00001319** to an overflow page, insert an entry into the pointer-map
1320** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +00001321*/
drh98add2e2009-07-20 17:11:49 +00001322static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
drhfa67c3c2008-07-11 02:21:40 +00001323 CellInfo info;
drh98add2e2009-07-20 17:11:49 +00001324 if( *pRC ) return;
drhfa67c3c2008-07-11 02:21:40 +00001325 assert( pCell!=0 );
drh5fa60512015-06-19 17:19:34 +00001326 pPage->xParseCell(pPage, pCell, &info);
drh45ac1c72015-12-18 03:59:16 +00001327 if( info.nLocal<info.nPayload ){
1328 Pgno ovfl = get4byte(&pCell[info.nSize-4]);
drh98add2e2009-07-20 17:11:49 +00001329 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
danielk1977ac11ee62005-01-15 12:45:51 +00001330 }
danielk1977ac11ee62005-01-15 12:45:51 +00001331}
danielk197779a40da2005-01-16 08:00:01 +00001332#endif
1333
danielk1977ac11ee62005-01-15 12:45:51 +00001334
drhda200cc2004-05-09 11:51:38 +00001335/*
dane6d065a2017-02-24 19:58:22 +00001336** Defragment the page given. This routine reorganizes cells within the
1337** page so that there are no free-blocks on the free-block list.
1338**
1339** Parameter nMaxFrag is the maximum amount of fragmented space that may be
1340** present in the page after this routine returns.
drhfdab0262014-11-20 15:30:50 +00001341**
1342** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
1343** b-tree page so that there are no freeblocks or fragment bytes, all
1344** unused bytes are contained in the unallocated space region, and all
1345** cells are packed tightly at the end of the page.
drh365d68f2001-05-11 11:02:46 +00001346*/
dane6d065a2017-02-24 19:58:22 +00001347static int defragmentPage(MemPage *pPage, int nMaxFrag){
drh43605152004-05-29 21:46:49 +00001348 int i; /* Loop counter */
peter.d.reid60ec9142014-09-06 16:39:46 +00001349 int pc; /* Address of the i-th cell */
drh43605152004-05-29 21:46:49 +00001350 int hdr; /* Offset to the page header */
1351 int size; /* Size of a cell */
1352 int usableSize; /* Number of usable bytes on a page */
1353 int cellOffset; /* Offset to the cell pointer array */
drh281b21d2008-08-22 12:57:08 +00001354 int cbrk; /* Offset to the cell content area */
drh43605152004-05-29 21:46:49 +00001355 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +00001356 unsigned char *data; /* The page data */
1357 unsigned char *temp; /* Temp area for cell content */
drh588400b2014-09-27 05:00:25 +00001358 unsigned char *src; /* Source of content */
drh17146622009-07-07 17:38:38 +00001359 int iCellFirst; /* First allowable cell index */
1360 int iCellLast; /* Last possible cell index */
1361
danielk19773b8a05f2007-03-19 17:44:26 +00001362 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001363 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +00001364 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +00001365 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00001366 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh588400b2014-09-27 05:00:25 +00001367 temp = 0;
1368 src = data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +00001369 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001370 cellOffset = pPage->cellOffset;
1371 nCell = pPage->nCell;
1372 assert( nCell==get2byte(&data[hdr+3]) );
dane6d065a2017-02-24 19:58:22 +00001373 iCellFirst = cellOffset + 2*nCell;
dan30741eb2017-03-03 20:02:53 +00001374 usableSize = pPage->pBt->usableSize;
dane6d065a2017-02-24 19:58:22 +00001375
1376 /* This block handles pages with two or fewer free blocks and nMaxFrag
1377 ** or fewer fragmented bytes. In this case it is faster to move the
1378 ** two (or one) blocks of cells using memmove() and add the required
1379 ** offsets to each pointer in the cell-pointer array than it is to
1380 ** reconstruct the entire page. */
1381 if( (int)data[hdr+7]<=nMaxFrag ){
1382 int iFree = get2byte(&data[hdr+1]);
1383 if( iFree ){
1384 int iFree2 = get2byte(&data[iFree]);
dan30741eb2017-03-03 20:02:53 +00001385
1386 /* pageFindSlot() has already verified that free blocks are sorted
1387 ** in order of offset within the page, and that no block extends
1388 ** past the end of the page. Provided the two free slots do not
1389 ** overlap, this guarantees that the memmove() calls below will not
1390 ** overwrite the usableSize byte buffer, even if the database page
1391 ** is corrupt. */
1392 assert( iFree2==0 || iFree2>iFree );
1393 assert( iFree+get2byte(&data[iFree+2]) <= usableSize );
1394 assert( iFree2==0 || iFree2+get2byte(&data[iFree2+2]) <= usableSize );
1395
dane6d065a2017-02-24 19:58:22 +00001396 if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
1397 u8 *pEnd = &data[cellOffset + nCell*2];
1398 u8 *pAddr;
1399 int sz2 = 0;
1400 int sz = get2byte(&data[iFree+2]);
1401 int top = get2byte(&data[hdr+5]);
1402 if( iFree2 ){
drh60348462017-08-25 13:02:48 +00001403 assert( iFree+sz<=iFree2 ); /* Verified by pageFindSlot() */
dane6d065a2017-02-24 19:58:22 +00001404 sz2 = get2byte(&data[iFree2+2]);
dan30741eb2017-03-03 20:02:53 +00001405 assert( iFree+sz+sz2+iFree2-(iFree+sz) <= usableSize );
dane6d065a2017-02-24 19:58:22 +00001406 memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
1407 sz += sz2;
1408 }
1409 cbrk = top+sz;
dan30741eb2017-03-03 20:02:53 +00001410 assert( cbrk+(iFree-top) <= usableSize );
dane6d065a2017-02-24 19:58:22 +00001411 memmove(&data[cbrk], &data[top], iFree-top);
1412 for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
1413 pc = get2byte(pAddr);
1414 if( pc<iFree ){ put2byte(pAddr, pc+sz); }
1415 else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
1416 }
1417 goto defragment_out;
1418 }
1419 }
1420 }
1421
drh281b21d2008-08-22 12:57:08 +00001422 cbrk = usableSize;
drh17146622009-07-07 17:38:38 +00001423 iCellLast = usableSize - 4;
drh43605152004-05-29 21:46:49 +00001424 for(i=0; i<nCell; i++){
1425 u8 *pAddr; /* The i-th cell pointer */
1426 pAddr = &data[cellOffset + i*2];
1427 pc = get2byte(pAddr);
drh0a45c272009-07-08 01:49:11 +00001428 testcase( pc==iCellFirst );
1429 testcase( pc==iCellLast );
danielk197730548662009-07-09 05:07:37 +00001430 /* These conditions have already been verified in btreeInitPage()
drh1421d982015-05-27 03:46:18 +00001431 ** if PRAGMA cell_size_check=ON.
drh17146622009-07-07 17:38:38 +00001432 */
1433 if( pc<iCellFirst || pc>iCellLast ){
drhcc97ca42017-06-07 22:32:59 +00001434 return SQLITE_CORRUPT_PGNO(pPage->pgno);
shane0af3f892008-11-12 04:55:34 +00001435 }
drh17146622009-07-07 17:38:38 +00001436 assert( pc>=iCellFirst && pc<=iCellLast );
drh25ada072015-06-19 15:07:14 +00001437 size = pPage->xCellSize(pPage, &src[pc]);
drh281b21d2008-08-22 12:57:08 +00001438 cbrk -= size;
drh17146622009-07-07 17:38:38 +00001439 if( cbrk<iCellFirst || pc+size>usableSize ){
drhcc97ca42017-06-07 22:32:59 +00001440 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh17146622009-07-07 17:38:38 +00001441 }
drh7157e1d2009-07-09 13:25:32 +00001442 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
drh0a45c272009-07-08 01:49:11 +00001443 testcase( cbrk+size==usableSize );
drh0a45c272009-07-08 01:49:11 +00001444 testcase( pc+size==usableSize );
drh281b21d2008-08-22 12:57:08 +00001445 put2byte(pAddr, cbrk);
drh588400b2014-09-27 05:00:25 +00001446 if( temp==0 ){
1447 int x;
1448 if( cbrk==pc ) continue;
1449 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1450 x = get2byte(&data[hdr+5]);
1451 memcpy(&temp[x], &data[x], (cbrk+size) - x);
1452 src = temp;
1453 }
1454 memcpy(&data[cbrk], &src[pc], size);
drh2af926b2001-05-15 00:39:25 +00001455 }
dane6d065a2017-02-24 19:58:22 +00001456 data[hdr+7] = 0;
dane6d065a2017-02-24 19:58:22 +00001457
1458 defragment_out:
dan3b2ede12017-02-25 16:24:02 +00001459 if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
drhcc97ca42017-06-07 22:32:59 +00001460 return SQLITE_CORRUPT_PGNO(pPage->pgno);
dan3b2ede12017-02-25 16:24:02 +00001461 }
drh17146622009-07-07 17:38:38 +00001462 assert( cbrk>=iCellFirst );
drh281b21d2008-08-22 12:57:08 +00001463 put2byte(&data[hdr+5], cbrk);
drh43605152004-05-29 21:46:49 +00001464 data[hdr+1] = 0;
1465 data[hdr+2] = 0;
drh17146622009-07-07 17:38:38 +00001466 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
drhc5053fb2008-11-27 02:22:10 +00001467 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
shane0af3f892008-11-12 04:55:34 +00001468 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +00001469}
1470
drha059ad02001-04-17 20:09:11 +00001471/*
dan8e9ba0c2014-10-14 17:27:04 +00001472** Search the free-list on page pPg for space to store a cell nByte bytes in
1473** size. If one can be found, return a pointer to the space and remove it
1474** from the free-list.
1475**
1476** If no suitable space can be found on the free-list, return NULL.
1477**
drhba0f9992014-10-30 20:48:44 +00001478** This function may detect corruption within pPg. If corruption is
1479** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
dan61e94c92014-10-27 08:02:16 +00001480**
drhb7580e82015-06-25 18:36:13 +00001481** Slots on the free list that are between 1 and 3 bytes larger than nByte
1482** will be ignored if adding the extra space to the fragmentation count
1483** causes the fragmentation count to exceed 60.
dan8e9ba0c2014-10-14 17:27:04 +00001484*/
drhb7580e82015-06-25 18:36:13 +00001485static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
dan8e9ba0c2014-10-14 17:27:04 +00001486 const int hdr = pPg->hdrOffset;
1487 u8 * const aData = pPg->aData;
drhb7580e82015-06-25 18:36:13 +00001488 int iAddr = hdr + 1;
1489 int pc = get2byte(&aData[iAddr]);
1490 int x;
dan8e9ba0c2014-10-14 17:27:04 +00001491 int usableSize = pPg->pBt->usableSize;
drh87d63c92017-08-23 23:09:03 +00001492 int size; /* Size of the free slot */
dan8e9ba0c2014-10-14 17:27:04 +00001493
drhb7580e82015-06-25 18:36:13 +00001494 assert( pc>0 );
drh87d63c92017-08-23 23:09:03 +00001495 while( pc<=usableSize-4 ){
drh113762a2014-11-19 16:36:25 +00001496 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
1497 ** freeblock form a big-endian integer which is the size of the freeblock
1498 ** in bytes, including the 4-byte header. */
dan8e9ba0c2014-10-14 17:27:04 +00001499 size = get2byte(&aData[pc+2]);
drhb7580e82015-06-25 18:36:13 +00001500 if( (x = size - nByte)>=0 ){
dan8e9ba0c2014-10-14 17:27:04 +00001501 testcase( x==4 );
1502 testcase( x==3 );
drh5e398e42017-08-23 20:36:06 +00001503 if( size+pc > usableSize ){
drhcc97ca42017-06-07 22:32:59 +00001504 *pRc = SQLITE_CORRUPT_PGNO(pPg->pgno);
drh24dee9d2015-06-02 19:36:29 +00001505 return 0;
1506 }else if( x<4 ){
drhfdab0262014-11-20 15:30:50 +00001507 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
1508 ** number of bytes in fragments may not exceed 60. */
drhb7580e82015-06-25 18:36:13 +00001509 if( aData[hdr+7]>57 ) return 0;
1510
dan8e9ba0c2014-10-14 17:27:04 +00001511 /* Remove the slot from the free-list. Update the number of
1512 ** fragmented bytes within the page. */
1513 memcpy(&aData[iAddr], &aData[pc], 2);
1514 aData[hdr+7] += (u8)x;
dan8e9ba0c2014-10-14 17:27:04 +00001515 }else{
1516 /* The slot remains on the free-list. Reduce its size to account
1517 ** for the portion used by the new allocation. */
1518 put2byte(&aData[pc+2], x);
1519 }
1520 return &aData[pc + x];
1521 }
drhb7580e82015-06-25 18:36:13 +00001522 iAddr = pc;
1523 pc = get2byte(&aData[pc]);
drh87d63c92017-08-23 23:09:03 +00001524 if( pc<iAddr+size ) break;
1525 }
1526 if( pc ){
1527 *pRc = SQLITE_CORRUPT_PGNO(pPg->pgno);
1528 }
dan8e9ba0c2014-10-14 17:27:04 +00001529
1530 return 0;
1531}
1532
1533/*
danielk19776011a752009-04-01 16:25:32 +00001534** Allocate nByte bytes of space from within the B-Tree page passed
drh0a45c272009-07-08 01:49:11 +00001535** as the first argument. Write into *pIdx the index into pPage->aData[]
1536** of the first byte of allocated space. Return either SQLITE_OK or
1537** an error code (usually SQLITE_CORRUPT).
drhbd03cae2001-06-02 02:40:57 +00001538**
drh0a45c272009-07-08 01:49:11 +00001539** The caller guarantees that there is sufficient space to make the
1540** allocation. This routine might need to defragment in order to bring
1541** all the space together, however. This routine will avoid using
1542** the first two bytes past the cell pointer area since presumably this
1543** allocation is being made in order to insert a new cell, so we will
1544** also end up needing a new cell pointer.
drh7e3b0a02001-04-28 16:52:40 +00001545*/
drh0a45c272009-07-08 01:49:11 +00001546static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
danielk19776011a752009-04-01 16:25:32 +00001547 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1548 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
drh0a45c272009-07-08 01:49:11 +00001549 int top; /* First byte of cell content area */
drhfefa0942014-11-05 21:21:08 +00001550 int rc = SQLITE_OK; /* Integer return code */
drh0a45c272009-07-08 01:49:11 +00001551 int gap; /* First byte of gap between cell pointers and cell content */
drh43605152004-05-29 21:46:49 +00001552
danielk19773b8a05f2007-03-19 17:44:26 +00001553 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001554 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +00001555 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa67c3c2008-07-11 02:21:40 +00001556 assert( nByte>=0 ); /* Minimum cell size is 4 */
1557 assert( pPage->nFree>=nByte );
1558 assert( pPage->nOverflow==0 );
mistachkina95d8ca2014-10-27 19:42:02 +00001559 assert( nByte < (int)(pPage->pBt->usableSize-8) );
drh43605152004-05-29 21:46:49 +00001560
drh0a45c272009-07-08 01:49:11 +00001561 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1562 gap = pPage->cellOffset + 2*pPage->nCell;
drh75b31dc2014-08-20 00:54:46 +00001563 assert( gap<=65536 );
drhfdab0262014-11-20 15:30:50 +00001564 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
1565 ** and the reserved space is zero (the usual value for reserved space)
1566 ** then the cell content offset of an empty page wants to be 65536.
1567 ** However, that integer is too large to be stored in a 2-byte unsigned
1568 ** integer, so a value of 0 is used in its place. */
drhded340e2015-06-25 15:04:56 +00001569 top = get2byte(&data[hdr+5]);
mistachkin68cdd0e2015-06-26 03:12:27 +00001570 assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
drhded340e2015-06-25 15:04:56 +00001571 if( gap>top ){
1572 if( top==0 && pPage->pBt->usableSize==65536 ){
1573 top = 65536;
1574 }else{
drhcc97ca42017-06-07 22:32:59 +00001575 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh9e572e62004-04-23 23:43:10 +00001576 }
1577 }
drh43605152004-05-29 21:46:49 +00001578
drh4c04f3c2014-08-20 11:56:14 +00001579 /* If there is enough space between gap and top for one more cell pointer
1580 ** array entry offset, and if the freelist is not empty, then search the
1581 ** freelist looking for a free slot big enough to satisfy the request.
1582 */
drh5e2f8b92001-05-28 00:41:15 +00001583 testcase( gap+2==top );
drh7aa128d2002-06-21 13:09:16 +00001584 testcase( gap+1==top );
drh14acc042001-06-10 19:56:58 +00001585 testcase( gap==top );
drhe674bf12015-06-25 16:01:44 +00001586 if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
drhb7580e82015-06-25 18:36:13 +00001587 u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
dan8e9ba0c2014-10-14 17:27:04 +00001588 if( pSpace ){
drhfefa0942014-11-05 21:21:08 +00001589 assert( pSpace>=data && (pSpace - data)<65536 );
1590 *pIdx = (int)(pSpace - data);
dan8e9ba0c2014-10-14 17:27:04 +00001591 return SQLITE_OK;
drhb7580e82015-06-25 18:36:13 +00001592 }else if( rc ){
1593 return rc;
drh9e572e62004-04-23 23:43:10 +00001594 }
1595 }
drh43605152004-05-29 21:46:49 +00001596
drh4c04f3c2014-08-20 11:56:14 +00001597 /* The request could not be fulfilled using a freelist slot. Check
1598 ** to see if defragmentation is necessary.
drh0a45c272009-07-08 01:49:11 +00001599 */
1600 testcase( gap+2+nByte==top );
1601 if( gap+2+nByte>top ){
drh1fd2d7d2014-12-02 16:16:47 +00001602 assert( pPage->nCell>0 || CORRUPT_DB );
dane6d065a2017-02-24 19:58:22 +00001603 rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
drh0a45c272009-07-08 01:49:11 +00001604 if( rc ) return rc;
drh5d433ce2010-08-14 16:02:52 +00001605 top = get2byteNotZero(&data[hdr+5]);
dan3b2ede12017-02-25 16:24:02 +00001606 assert( gap+2+nByte<=top );
drh0a45c272009-07-08 01:49:11 +00001607 }
1608
1609
drh43605152004-05-29 21:46:49 +00001610 /* Allocate memory from the gap in between the cell pointer array
drhc314dc72009-07-21 11:52:34 +00001611 ** and the cell content area. The btreeInitPage() call has already
1612 ** validated the freelist. Given that the freelist is valid, there
1613 ** is no way that the allocation can extend off the end of the page.
1614 ** The assert() below verifies the previous sentence.
drh43605152004-05-29 21:46:49 +00001615 */
drh0a45c272009-07-08 01:49:11 +00001616 top -= nByte;
drh43605152004-05-29 21:46:49 +00001617 put2byte(&data[hdr+5], top);
drhfcd71b62011-04-05 22:08:24 +00001618 assert( top+nByte <= (int)pPage->pBt->usableSize );
drh0a45c272009-07-08 01:49:11 +00001619 *pIdx = top;
1620 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001621}
1622
1623/*
drh9e572e62004-04-23 23:43:10 +00001624** Return a section of the pPage->aData to the freelist.
drh7fb91642014-08-20 14:37:09 +00001625** The first byte of the new free block is pPage->aData[iStart]
1626** and the size of the block is iSize bytes.
drh306dc212001-05-21 13:45:10 +00001627**
drh5f5c7532014-08-20 17:56:27 +00001628** Adjacent freeblocks are coalesced.
1629**
1630** Note that even though the freeblock list was checked by btreeInitPage(),
1631** that routine will not detect overlap between cells or freeblocks. Nor
1632** does it detect cells or freeblocks that encrouch into the reserved bytes
1633** at the end of the page. So do additional corruption checks inside this
1634** routine and return SQLITE_CORRUPT if any problems are found.
drh7e3b0a02001-04-28 16:52:40 +00001635*/
drh5f5c7532014-08-20 17:56:27 +00001636static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
drh3f387402014-09-24 01:23:00 +00001637 u16 iPtr; /* Address of ptr to next freeblock */
drh5f5c7532014-08-20 17:56:27 +00001638 u16 iFreeBlk; /* Address of the next freeblock */
1639 u8 hdr; /* Page header size. 0 or 100 */
1640 u8 nFrag = 0; /* Reduction in fragmentation */
1641 u16 iOrigSize = iSize; /* Original value of iSize */
drh5e398e42017-08-23 20:36:06 +00001642 u16 x; /* Offset to cell content area */
drh5f5c7532014-08-20 17:56:27 +00001643 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
drh7fb91642014-08-20 14:37:09 +00001644 unsigned char *data = pPage->aData; /* Page content */
drh2af926b2001-05-15 00:39:25 +00001645
drh9e572e62004-04-23 23:43:10 +00001646 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001647 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
dancf3d17c2015-05-25 15:03:49 +00001648 assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
dan23eba452014-10-24 18:43:57 +00001649 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +00001650 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh7fb91642014-08-20 14:37:09 +00001651 assert( iSize>=4 ); /* Minimum cell size is 4 */
drh5e398e42017-08-23 20:36:06 +00001652 assert( iStart<=pPage->pBt->usableSize-4 );
drhfcce93f2006-02-22 03:08:32 +00001653
drh5f5c7532014-08-20 17:56:27 +00001654 /* The list of freeblocks must be in ascending order. Find the
1655 ** spot on the list where iStart should be inserted.
drh0a45c272009-07-08 01:49:11 +00001656 */
drh43605152004-05-29 21:46:49 +00001657 hdr = pPage->hdrOffset;
drh7fb91642014-08-20 14:37:09 +00001658 iPtr = hdr + 1;
drh7bc4c452014-08-20 18:43:44 +00001659 if( data[iPtr+1]==0 && data[iPtr]==0 ){
1660 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
1661 }else{
drh85f071b2016-09-17 19:34:32 +00001662 while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
1663 if( iFreeBlk<iPtr+4 ){
1664 if( iFreeBlk==0 ) break;
drhcc97ca42017-06-07 22:32:59 +00001665 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh85f071b2016-09-17 19:34:32 +00001666 }
drh7bc4c452014-08-20 18:43:44 +00001667 iPtr = iFreeBlk;
shanedcc50b72008-11-13 18:29:50 +00001668 }
drh5e398e42017-08-23 20:36:06 +00001669 if( iFreeBlk>pPage->pBt->usableSize-4 ){
1670 return SQLITE_CORRUPT_PGNO(pPage->pgno);
1671 }
drh7bc4c452014-08-20 18:43:44 +00001672 assert( iFreeBlk>iPtr || iFreeBlk==0 );
1673
1674 /* At this point:
1675 ** iFreeBlk: First freeblock after iStart, or zero if none
drh3e24a342015-06-15 16:09:35 +00001676 ** iPtr: The address of a pointer to iFreeBlk
drh7bc4c452014-08-20 18:43:44 +00001677 **
1678 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
1679 */
1680 if( iFreeBlk && iEnd+3>=iFreeBlk ){
1681 nFrag = iFreeBlk - iEnd;
drhcc97ca42017-06-07 22:32:59 +00001682 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh7bc4c452014-08-20 18:43:44 +00001683 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
drhcc97ca42017-06-07 22:32:59 +00001684 if( iEnd > pPage->pBt->usableSize ){
1685 return SQLITE_CORRUPT_PGNO(pPage->pgno);
1686 }
drh7bc4c452014-08-20 18:43:44 +00001687 iSize = iEnd - iStart;
1688 iFreeBlk = get2byte(&data[iFreeBlk]);
1689 }
1690
drh3f387402014-09-24 01:23:00 +00001691 /* If iPtr is another freeblock (that is, if iPtr is not the freelist
1692 ** pointer in the page header) then check to see if iStart should be
1693 ** coalesced onto the end of iPtr.
drh7bc4c452014-08-20 18:43:44 +00001694 */
1695 if( iPtr>hdr+1 ){
1696 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
1697 if( iPtrEnd+3>=iStart ){
drhcc97ca42017-06-07 22:32:59 +00001698 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh7bc4c452014-08-20 18:43:44 +00001699 nFrag += iStart - iPtrEnd;
1700 iSize = iEnd - iPtr;
1701 iStart = iPtr;
shanedcc50b72008-11-13 18:29:50 +00001702 }
drh9e572e62004-04-23 23:43:10 +00001703 }
drhcc97ca42017-06-07 22:32:59 +00001704 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh7bc4c452014-08-20 18:43:44 +00001705 data[hdr+7] -= nFrag;
drh9e572e62004-04-23 23:43:10 +00001706 }
drh5e398e42017-08-23 20:36:06 +00001707 x = get2byte(&data[hdr+5]);
1708 if( iStart<=x ){
drh5f5c7532014-08-20 17:56:27 +00001709 /* The new freeblock is at the beginning of the cell content area,
1710 ** so just extend the cell content area rather than create another
1711 ** freelist entry */
drh5e398e42017-08-23 20:36:06 +00001712 if( iStart<x || iPtr!=hdr+1 ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh5f5c7532014-08-20 17:56:27 +00001713 put2byte(&data[hdr+1], iFreeBlk);
1714 put2byte(&data[hdr+5], iEnd);
1715 }else{
1716 /* Insert the new freeblock into the freelist */
1717 put2byte(&data[iPtr], iStart);
drh4b70f112004-05-02 21:12:19 +00001718 }
drh5e398e42017-08-23 20:36:06 +00001719 if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
1720 /* Overwrite deleted information with zeros when the secure_delete
1721 ** option is enabled */
1722 memset(&data[iStart], 0, iSize);
1723 }
1724 put2byte(&data[iStart], iFreeBlk);
1725 put2byte(&data[iStart+2], iSize);
drh5f5c7532014-08-20 17:56:27 +00001726 pPage->nFree += iOrigSize;
shanedcc50b72008-11-13 18:29:50 +00001727 return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00001728}
1729
1730/*
drh271efa52004-05-30 19:19:05 +00001731** Decode the flags byte (the first byte of the header) for a page
1732** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +00001733**
1734** Only the following combinations are supported. Anything different
1735** indicates a corrupt database files:
1736**
1737** PTF_ZERODATA
1738** PTF_ZERODATA | PTF_LEAF
1739** PTF_LEAFDATA | PTF_INTKEY
1740** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
drh271efa52004-05-30 19:19:05 +00001741*/
drh44845222008-07-17 18:39:57 +00001742static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +00001743 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +00001744
1745 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +00001746 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00001747 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
drh44845222008-07-17 18:39:57 +00001748 flagByte &= ~PTF_LEAF;
1749 pPage->childPtrSize = 4-4*pPage->leaf;
drh25ada072015-06-19 15:07:14 +00001750 pPage->xCellSize = cellSizePtr;
drh271efa52004-05-30 19:19:05 +00001751 pBt = pPage->pBt;
drh44845222008-07-17 18:39:57 +00001752 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
drh3791c9c2016-05-09 23:11:47 +00001753 /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
1754 ** interior table b-tree page. */
drhfdab0262014-11-20 15:30:50 +00001755 assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
drh3791c9c2016-05-09 23:11:47 +00001756 /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
1757 ** leaf table b-tree page. */
drhfdab0262014-11-20 15:30:50 +00001758 assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
drh44845222008-07-17 18:39:57 +00001759 pPage->intKey = 1;
drh25ada072015-06-19 15:07:14 +00001760 if( pPage->leaf ){
1761 pPage->intKeyLeaf = 1;
drh5fa60512015-06-19 17:19:34 +00001762 pPage->xParseCell = btreeParseCellPtr;
drh25ada072015-06-19 15:07:14 +00001763 }else{
1764 pPage->intKeyLeaf = 0;
drh25ada072015-06-19 15:07:14 +00001765 pPage->xCellSize = cellSizePtrNoPayload;
drh5fa60512015-06-19 17:19:34 +00001766 pPage->xParseCell = btreeParseCellPtrNoPayload;
drh25ada072015-06-19 15:07:14 +00001767 }
drh271efa52004-05-30 19:19:05 +00001768 pPage->maxLocal = pBt->maxLeaf;
1769 pPage->minLocal = pBt->minLeaf;
drh44845222008-07-17 18:39:57 +00001770 }else if( flagByte==PTF_ZERODATA ){
drh3791c9c2016-05-09 23:11:47 +00001771 /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
1772 ** interior index b-tree page. */
drhfdab0262014-11-20 15:30:50 +00001773 assert( (PTF_ZERODATA)==2 );
drh3791c9c2016-05-09 23:11:47 +00001774 /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
1775 ** leaf index b-tree page. */
drhfdab0262014-11-20 15:30:50 +00001776 assert( (PTF_ZERODATA|PTF_LEAF)==10 );
drh44845222008-07-17 18:39:57 +00001777 pPage->intKey = 0;
drh3e28ff52014-09-24 00:59:08 +00001778 pPage->intKeyLeaf = 0;
drh5fa60512015-06-19 17:19:34 +00001779 pPage->xParseCell = btreeParseCellPtrIndex;
drh271efa52004-05-30 19:19:05 +00001780 pPage->maxLocal = pBt->maxLocal;
1781 pPage->minLocal = pBt->minLocal;
drh44845222008-07-17 18:39:57 +00001782 }else{
drhfdab0262014-11-20 15:30:50 +00001783 /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
1784 ** an error. */
drhcc97ca42017-06-07 22:32:59 +00001785 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh271efa52004-05-30 19:19:05 +00001786 }
drhc9166342012-01-05 23:32:06 +00001787 pPage->max1bytePayload = pBt->max1bytePayload;
drh44845222008-07-17 18:39:57 +00001788 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +00001789}
1790
1791/*
drh7e3b0a02001-04-28 16:52:40 +00001792** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001793**
1794** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001795** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001796** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1797** guarantee that the page is well-formed. It only shows that
1798** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001799*/
danielk197730548662009-07-09 05:07:37 +00001800static int btreeInitPage(MemPage *pPage){
drh14e845a2017-05-25 21:35:56 +00001801 int pc; /* Address of a freeblock within pPage->aData[] */
1802 u8 hdr; /* Offset to beginning of page header */
1803 u8 *data; /* Equal to pPage->aData */
1804 BtShared *pBt; /* The main btree structure */
1805 int usableSize; /* Amount of usable space on each page */
1806 u16 cellOffset; /* Offset from start of page to first cell pointer */
1807 int nFree; /* Number of unused bytes on the page */
1808 int top; /* First byte of the cell content area */
1809 int iCellFirst; /* First allowable cell or freeblock offset */
1810 int iCellLast; /* Last possible cell or freeblock offset */
drh2af926b2001-05-15 00:39:25 +00001811
danielk197771d5d2c2008-09-29 11:49:47 +00001812 assert( pPage->pBt!=0 );
drh1421d982015-05-27 03:46:18 +00001813 assert( pPage->pBt->db!=0 );
danielk197771d5d2c2008-09-29 11:49:47 +00001814 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001815 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +00001816 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1817 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
drh14e845a2017-05-25 21:35:56 +00001818 assert( pPage->isInit==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00001819
drh14e845a2017-05-25 21:35:56 +00001820 pBt = pPage->pBt;
1821 hdr = pPage->hdrOffset;
1822 data = pPage->aData;
1823 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
1824 ** the b-tree page type. */
drhcc97ca42017-06-07 22:32:59 +00001825 if( decodeFlags(pPage, data[hdr]) ){
1826 return SQLITE_CORRUPT_PGNO(pPage->pgno);
1827 }
drh14e845a2017-05-25 21:35:56 +00001828 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
1829 pPage->maskPage = (u16)(pBt->pageSize - 1);
1830 pPage->nOverflow = 0;
1831 usableSize = pBt->usableSize;
1832 pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
1833 pPage->aDataEnd = &data[usableSize];
1834 pPage->aCellIdx = &data[cellOffset];
1835 pPage->aDataOfst = &data[pPage->childPtrSize];
1836 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
1837 ** the start of the cell content area. A zero value for this integer is
1838 ** interpreted as 65536. */
1839 top = get2byteNotZero(&data[hdr+5]);
1840 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
1841 ** number of cells on the page. */
1842 pPage->nCell = get2byte(&data[hdr+3]);
1843 if( pPage->nCell>MX_CELL(pBt) ){
1844 /* To many cells for a single page. The page must be corrupt */
drhcc97ca42017-06-07 22:32:59 +00001845 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh14e845a2017-05-25 21:35:56 +00001846 }
1847 testcase( pPage->nCell==MX_CELL(pBt) );
1848 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
1849 ** possible for a root page of a table that contains no rows) then the
1850 ** offset to the cell content area will equal the page size minus the
1851 ** bytes of reserved space. */
1852 assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
danielk197771d5d2c2008-09-29 11:49:47 +00001853
drh14e845a2017-05-25 21:35:56 +00001854 /* A malformed database page might cause us to read past the end
1855 ** of page when parsing a cell.
1856 **
1857 ** The following block of code checks early to see if a cell extends
1858 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
1859 ** returned if it does.
1860 */
1861 iCellFirst = cellOffset + 2*pPage->nCell;
1862 iCellLast = usableSize - 4;
1863 if( pBt->db->flags & SQLITE_CellSizeCk ){
1864 int i; /* Index into the cell pointer array */
1865 int sz; /* Size of a cell */
danielk197771d5d2c2008-09-29 11:49:47 +00001866
drh14e845a2017-05-25 21:35:56 +00001867 if( !pPage->leaf ) iCellLast--;
1868 for(i=0; i<pPage->nCell; i++){
1869 pc = get2byteAligned(&data[cellOffset+i*2]);
1870 testcase( pc==iCellFirst );
1871 testcase( pc==iCellLast );
1872 if( pc<iCellFirst || pc>iCellLast ){
drhcc97ca42017-06-07 22:32:59 +00001873 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh69e931e2009-06-03 21:04:35 +00001874 }
drh14e845a2017-05-25 21:35:56 +00001875 sz = pPage->xCellSize(pPage, &data[pc]);
1876 testcase( pc+sz==usableSize );
1877 if( pc+sz>usableSize ){
drhcc97ca42017-06-07 22:32:59 +00001878 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh77dc0ed2016-12-12 01:30:01 +00001879 }
danielk1977eaa06f62008-09-18 17:34:44 +00001880 }
drh14e845a2017-05-25 21:35:56 +00001881 if( !pPage->leaf ) iCellLast++;
1882 }
danielk197793c829c2009-06-03 17:26:17 +00001883
drh14e845a2017-05-25 21:35:56 +00001884 /* Compute the total free space on the page
1885 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
1886 ** start of the first freeblock on the page, or is zero if there are no
1887 ** freeblocks. */
1888 pc = get2byte(&data[hdr+1]);
1889 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
1890 if( pc>0 ){
1891 u32 next, size;
1892 if( pc<iCellFirst ){
1893 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
1894 ** always be at least one cell before the first freeblock.
1895 */
drhcc97ca42017-06-07 22:32:59 +00001896 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drhee696e22004-08-30 16:52:17 +00001897 }
drh14e845a2017-05-25 21:35:56 +00001898 while( 1 ){
1899 if( pc>iCellLast ){
drhcc97ca42017-06-07 22:32:59 +00001900 /* Freeblock off the end of the page */
1901 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh14e845a2017-05-25 21:35:56 +00001902 }
1903 next = get2byte(&data[pc]);
1904 size = get2byte(&data[pc+2]);
1905 nFree = nFree + size;
1906 if( next<=pc+size+3 ) break;
1907 pc = next;
1908 }
1909 if( next>0 ){
drhcc97ca42017-06-07 22:32:59 +00001910 /* Freeblock not in ascending order */
1911 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh14e845a2017-05-25 21:35:56 +00001912 }
1913 if( pc+size>(unsigned int)usableSize ){
drhcc97ca42017-06-07 22:32:59 +00001914 /* Last freeblock extends past page end */
1915 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh14e845a2017-05-25 21:35:56 +00001916 }
danielk197771d5d2c2008-09-29 11:49:47 +00001917 }
drh14e845a2017-05-25 21:35:56 +00001918
1919 /* At this point, nFree contains the sum of the offset to the start
1920 ** of the cell-content area plus the number of free bytes within
1921 ** the cell-content area. If this is greater than the usable-size
1922 ** of the page, then the page must be corrupted. This check also
1923 ** serves to verify that the offset to the start of the cell-content
1924 ** area, according to the page header, lies within the page.
1925 */
1926 if( nFree>usableSize ){
drhcc97ca42017-06-07 22:32:59 +00001927 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh14e845a2017-05-25 21:35:56 +00001928 }
1929 pPage->nFree = (u16)(nFree - iCellFirst);
1930 pPage->isInit = 1;
drh9e572e62004-04-23 23:43:10 +00001931 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001932}
1933
1934/*
drh8b2f49b2001-06-08 00:21:52 +00001935** Set up a raw page so that it looks like a database page holding
1936** no entries.
drhbd03cae2001-06-02 02:40:57 +00001937*/
drh9e572e62004-04-23 23:43:10 +00001938static void zeroPage(MemPage *pPage, int flags){
1939 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001940 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00001941 u8 hdr = pPage->hdrOffset;
1942 u16 first;
drh9e572e62004-04-23 23:43:10 +00001943
danielk19773b8a05f2007-03-19 17:44:26 +00001944 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +00001945 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1946 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00001947 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00001948 assert( sqlite3_mutex_held(pBt->mutex) );
drha5907a82017-06-19 11:44:22 +00001949 if( pBt->btsFlags & BTS_FAST_SECURE ){
drh5b47efa2010-02-12 18:18:39 +00001950 memset(&data[hdr], 0, pBt->usableSize - hdr);
1951 }
drh1bd10f82008-12-10 21:19:56 +00001952 data[hdr] = (char)flags;
drhfe485992014-02-12 23:52:16 +00001953 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
drh43605152004-05-29 21:46:49 +00001954 memset(&data[hdr+1], 0, 4);
1955 data[hdr+7] = 0;
1956 put2byte(&data[hdr+5], pBt->usableSize);
shaneh1df2db72010-08-18 02:28:48 +00001957 pPage->nFree = (u16)(pBt->usableSize - first);
drh271efa52004-05-30 19:19:05 +00001958 decodeFlags(pPage, flags);
drh43605152004-05-29 21:46:49 +00001959 pPage->cellOffset = first;
drh3def2352011-11-11 00:27:15 +00001960 pPage->aDataEnd = &data[pBt->usableSize];
1961 pPage->aCellIdx = &data[first];
drhf44890a2015-06-27 03:58:15 +00001962 pPage->aDataOfst = &data[pPage->childPtrSize];
drh43605152004-05-29 21:46:49 +00001963 pPage->nOverflow = 0;
drhb2eced52010-08-12 02:41:12 +00001964 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
1965 pPage->maskPage = (u16)(pBt->pageSize - 1);
drh43605152004-05-29 21:46:49 +00001966 pPage->nCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001967 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00001968}
1969
drh897a8202008-09-18 01:08:15 +00001970
1971/*
1972** Convert a DbPage obtained from the pager into a MemPage used by
1973** the btree layer.
1974*/
1975static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
1976 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
drh8dd1c252015-11-04 22:31:02 +00001977 if( pgno!=pPage->pgno ){
1978 pPage->aData = sqlite3PagerGetData(pDbPage);
1979 pPage->pDbPage = pDbPage;
1980 pPage->pBt = pBt;
1981 pPage->pgno = pgno;
1982 pPage->hdrOffset = pgno==1 ? 100 : 0;
1983 }
1984 assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
drh897a8202008-09-18 01:08:15 +00001985 return pPage;
1986}
1987
drhbd03cae2001-06-02 02:40:57 +00001988/*
drh3aac2dd2004-04-26 14:10:20 +00001989** Get a page from the pager. Initialize the MemPage.pBt and
drh7e8c6f12015-05-28 03:28:27 +00001990** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
drh538f5702007-04-13 02:14:30 +00001991**
drh7e8c6f12015-05-28 03:28:27 +00001992** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
1993** about the content of the page at this time. So do not go to the disk
drh538f5702007-04-13 02:14:30 +00001994** to fetch the content. Just fill in the content with zeros for now.
1995** If in the future we call sqlite3PagerWrite() on this page, that
1996** means we have started to be concerned about content and the disk
1997** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00001998*/
danielk197730548662009-07-09 05:07:37 +00001999static int btreeGetPage(
drh16a9b832007-05-05 18:39:25 +00002000 BtShared *pBt, /* The btree */
2001 Pgno pgno, /* Number of the page to fetch */
2002 MemPage **ppPage, /* Return the page in this parameter */
drhb00fc3b2013-08-21 23:42:32 +00002003 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
drh16a9b832007-05-05 18:39:25 +00002004){
drh3aac2dd2004-04-26 14:10:20 +00002005 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00002006 DbPage *pDbPage;
2007
drhb00fc3b2013-08-21 23:42:32 +00002008 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
drh1fee73e2007-08-29 04:00:57 +00002009 assert( sqlite3_mutex_held(pBt->mutex) );
drh9584f582015-11-04 20:22:37 +00002010 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
drh3aac2dd2004-04-26 14:10:20 +00002011 if( rc ) return rc;
drh897a8202008-09-18 01:08:15 +00002012 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
drh3aac2dd2004-04-26 14:10:20 +00002013 return SQLITE_OK;
2014}
2015
2016/*
danielk1977bea2a942009-01-20 17:06:27 +00002017** Retrieve a page from the pager cache. If the requested page is not
2018** already in the pager cache return NULL. Initialize the MemPage.pBt and
2019** MemPage.aData elements if needed.
2020*/
2021static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
2022 DbPage *pDbPage;
2023 assert( sqlite3_mutex_held(pBt->mutex) );
2024 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
2025 if( pDbPage ){
2026 return btreePageFromDbPage(pDbPage, pgno, pBt);
2027 }
2028 return 0;
2029}
2030
2031/*
danielk197789d40042008-11-17 14:20:56 +00002032** Return the size of the database file in pages. If there is any kind of
2033** error, return ((unsigned int)-1).
danielk197767fd7a92008-09-10 17:53:35 +00002034*/
drhb1299152010-03-30 22:58:33 +00002035static Pgno btreePagecount(BtShared *pBt){
2036 return pBt->nPage;
2037}
2038u32 sqlite3BtreeLastPage(Btree *p){
2039 assert( sqlite3BtreeHoldsMutex(p) );
2040 assert( ((p->pBt->nPage)&0x8000000)==0 );
drheac5bd72014-07-25 21:35:39 +00002041 return btreePagecount(p->pBt);
danielk197767fd7a92008-09-10 17:53:35 +00002042}
2043
2044/*
drh28f58dd2015-06-27 19:45:03 +00002045** Get a page from the pager and initialize it.
danielk197789bc4bc2009-07-21 19:25:24 +00002046**
drh15a00212015-06-27 20:55:00 +00002047** If pCur!=0 then the page is being fetched as part of a moveToChild()
2048** call. Do additional sanity checking on the page in this case.
2049** And if the fetch fails, this routine must decrement pCur->iPage.
drh28f58dd2015-06-27 19:45:03 +00002050**
2051** The page is fetched as read-write unless pCur is not NULL and is
2052** a read-only cursor.
2053**
2054** If an error occurs, then *ppPage is undefined. It
danielk197789bc4bc2009-07-21 19:25:24 +00002055** may remain unchanged, or it may be set to an invalid value.
drhde647132004-05-07 17:57:49 +00002056*/
2057static int getAndInitPage(
dan11dcd112013-03-15 18:29:18 +00002058 BtShared *pBt, /* The database file */
2059 Pgno pgno, /* Number of the page to get */
2060 MemPage **ppPage, /* Write the page pointer here */
drh28f58dd2015-06-27 19:45:03 +00002061 BtCursor *pCur, /* Cursor to receive the page, or NULL */
2062 int bReadOnly /* True for a read-only page */
drhde647132004-05-07 17:57:49 +00002063){
2064 int rc;
drh28f58dd2015-06-27 19:45:03 +00002065 DbPage *pDbPage;
drh1fee73e2007-08-29 04:00:57 +00002066 assert( sqlite3_mutex_held(pBt->mutex) );
drh352a35a2017-08-15 03:46:47 +00002067 assert( pCur==0 || ppPage==&pCur->pPage );
drh28f58dd2015-06-27 19:45:03 +00002068 assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
drh15a00212015-06-27 20:55:00 +00002069 assert( pCur==0 || pCur->iPage>0 );
danielk197789bc4bc2009-07-21 19:25:24 +00002070
danba3cbf32010-06-30 04:29:03 +00002071 if( pgno>btreePagecount(pBt) ){
2072 rc = SQLITE_CORRUPT_BKPT;
drh28f58dd2015-06-27 19:45:03 +00002073 goto getAndInitPage_error;
2074 }
drh9584f582015-11-04 20:22:37 +00002075 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
drh28f58dd2015-06-27 19:45:03 +00002076 if( rc ){
2077 goto getAndInitPage_error;
2078 }
drh8dd1c252015-11-04 22:31:02 +00002079 *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
drh28f58dd2015-06-27 19:45:03 +00002080 if( (*ppPage)->isInit==0 ){
drh8dd1c252015-11-04 22:31:02 +00002081 btreePageFromDbPage(pDbPage, pgno, pBt);
drh28f58dd2015-06-27 19:45:03 +00002082 rc = btreeInitPage(*ppPage);
2083 if( rc!=SQLITE_OK ){
2084 releasePage(*ppPage);
2085 goto getAndInitPage_error;
danielk197789bc4bc2009-07-21 19:25:24 +00002086 }
drhee696e22004-08-30 16:52:17 +00002087 }
drh8dd1c252015-11-04 22:31:02 +00002088 assert( (*ppPage)->pgno==pgno );
2089 assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
danba3cbf32010-06-30 04:29:03 +00002090
drh15a00212015-06-27 20:55:00 +00002091 /* If obtaining a child page for a cursor, we must verify that the page is
2092 ** compatible with the root page. */
drh8dd1c252015-11-04 22:31:02 +00002093 if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
drhcc97ca42017-06-07 22:32:59 +00002094 rc = SQLITE_CORRUPT_PGNO(pgno);
drh28f58dd2015-06-27 19:45:03 +00002095 releasePage(*ppPage);
2096 goto getAndInitPage_error;
2097 }
drh28f58dd2015-06-27 19:45:03 +00002098 return SQLITE_OK;
2099
2100getAndInitPage_error:
drh352a35a2017-08-15 03:46:47 +00002101 if( pCur ){
2102 pCur->iPage--;
2103 pCur->pPage = pCur->apPage[pCur->iPage];
2104 }
danba3cbf32010-06-30 04:29:03 +00002105 testcase( pgno==0 );
2106 assert( pgno!=0 || rc==SQLITE_CORRUPT );
drhde647132004-05-07 17:57:49 +00002107 return rc;
2108}
2109
2110/*
drh3aac2dd2004-04-26 14:10:20 +00002111** Release a MemPage. This should be called once for each prior
danielk197730548662009-07-09 05:07:37 +00002112** call to btreeGetPage.
drh3908fe92017-09-01 14:50:19 +00002113**
2114** Page1 is a special case and must be released using releasePageOne().
drh3aac2dd2004-04-26 14:10:20 +00002115*/
drhbbf0f862015-06-27 14:59:26 +00002116static void releasePageNotNull(MemPage *pPage){
2117 assert( pPage->aData );
2118 assert( pPage->pBt );
2119 assert( pPage->pDbPage!=0 );
2120 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2121 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2122 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2123 sqlite3PagerUnrefNotNull(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00002124}
drh3aac2dd2004-04-26 14:10:20 +00002125static void releasePage(MemPage *pPage){
drhbbf0f862015-06-27 14:59:26 +00002126 if( pPage ) releasePageNotNull(pPage);
drh3aac2dd2004-04-26 14:10:20 +00002127}
drh3908fe92017-09-01 14:50:19 +00002128static void releasePageOne(MemPage *pPage){
2129 assert( pPage!=0 );
2130 assert( pPage->aData );
2131 assert( pPage->pBt );
2132 assert( pPage->pDbPage!=0 );
2133 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2134 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2135 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2136 sqlite3PagerUnrefPageOne(pPage->pDbPage);
2137}
drh3aac2dd2004-04-26 14:10:20 +00002138
2139/*
drh7e8c6f12015-05-28 03:28:27 +00002140** Get an unused page.
2141**
2142** This works just like btreeGetPage() with the addition:
2143**
2144** * If the page is already in use for some other purpose, immediately
2145** release it and return an SQLITE_CURRUPT error.
2146** * Make sure the isInit flag is clear
2147*/
2148static int btreeGetUnusedPage(
2149 BtShared *pBt, /* The btree */
2150 Pgno pgno, /* Number of the page to fetch */
2151 MemPage **ppPage, /* Return the page in this parameter */
2152 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2153){
2154 int rc = btreeGetPage(pBt, pgno, ppPage, flags);
2155 if( rc==SQLITE_OK ){
2156 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
2157 releasePage(*ppPage);
2158 *ppPage = 0;
2159 return SQLITE_CORRUPT_BKPT;
2160 }
2161 (*ppPage)->isInit = 0;
2162 }else{
2163 *ppPage = 0;
2164 }
2165 return rc;
2166}
2167
drha059ad02001-04-17 20:09:11 +00002168
2169/*
drha6abd042004-06-09 17:37:22 +00002170** During a rollback, when the pager reloads information into the cache
2171** so that the cache is restored to its original state at the start of
2172** the transaction, for each page restored this routine is called.
2173**
2174** This routine needs to reset the extra data section at the end of the
2175** page to agree with the restored data.
2176*/
danielk1977eaa06f62008-09-18 17:34:44 +00002177static void pageReinit(DbPage *pData){
drh07d183d2005-05-01 22:52:42 +00002178 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00002179 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
danielk1977d217e6f2009-04-01 17:13:51 +00002180 assert( sqlite3PagerPageRefcount(pData)>0 );
danielk197771d5d2c2008-09-29 11:49:47 +00002181 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00002182 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00002183 pPage->isInit = 0;
danielk1977d217e6f2009-04-01 17:13:51 +00002184 if( sqlite3PagerPageRefcount(pData)>1 ){
drh5e8d8872009-03-30 17:19:48 +00002185 /* pPage might not be a btree page; it might be an overflow page
2186 ** or ptrmap page or a free page. In those cases, the following
danielk197730548662009-07-09 05:07:37 +00002187 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
drh5e8d8872009-03-30 17:19:48 +00002188 ** But no harm is done by this. And it is very important that
danielk197730548662009-07-09 05:07:37 +00002189 ** btreeInitPage() be called on every btree page so we make
drh5e8d8872009-03-30 17:19:48 +00002190 ** the call for every page that comes in for re-initing. */
danielk197730548662009-07-09 05:07:37 +00002191 btreeInitPage(pPage);
danielk197771d5d2c2008-09-29 11:49:47 +00002192 }
drha6abd042004-06-09 17:37:22 +00002193 }
2194}
2195
2196/*
drhe5fe6902007-12-07 18:55:28 +00002197** Invoke the busy handler for a btree.
2198*/
danielk19771ceedd32008-11-19 10:22:33 +00002199static int btreeInvokeBusyHandler(void *pArg){
drhe5fe6902007-12-07 18:55:28 +00002200 BtShared *pBt = (BtShared*)pArg;
2201 assert( pBt->db );
2202 assert( sqlite3_mutex_held(pBt->db->mutex) );
2203 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
2204}
2205
2206/*
drhad3e0102004-09-03 23:32:18 +00002207** Open a database file.
2208**
drh382c0242001-10-06 16:33:02 +00002209** zFilename is the name of the database file. If zFilename is NULL
drh75c014c2010-08-30 15:02:28 +00002210** then an ephemeral database is created. The ephemeral database might
2211** be exclusively in memory, or it might use a disk-based memory cache.
2212** Either way, the ephemeral database will be automatically deleted
2213** when sqlite3BtreeClose() is called.
2214**
drhe53831d2007-08-17 01:14:38 +00002215** If zFilename is ":memory:" then an in-memory database is created
2216** that is automatically destroyed when it is closed.
drhc47fd8e2009-04-30 13:30:32 +00002217**
drh33f111d2012-01-17 15:29:14 +00002218** The "flags" parameter is a bitmask that might contain bits like
2219** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
drh75c014c2010-08-30 15:02:28 +00002220**
drhc47fd8e2009-04-30 13:30:32 +00002221** If the database is already opened in the same database connection
2222** and we are in shared cache mode, then the open will fail with an
2223** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
2224** objects in the same database connection since doing so will lead
2225** to problems with locking.
drha059ad02001-04-17 20:09:11 +00002226*/
drh23e11ca2004-05-04 17:27:28 +00002227int sqlite3BtreeOpen(
dan3a6d8ae2011-04-23 15:54:54 +00002228 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
drh3aac2dd2004-04-26 14:10:20 +00002229 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00002230 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00002231 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00002232 int flags, /* Options */
2233 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00002234){
drh7555d8e2009-03-20 13:15:30 +00002235 BtShared *pBt = 0; /* Shared part of btree structure */
2236 Btree *p; /* Handle to return */
2237 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
2238 int rc = SQLITE_OK; /* Result code from this function */
2239 u8 nReserve; /* Byte of unused space on each page */
2240 unsigned char zDbHeader[100]; /* Database header content */
danielk1977aef0bf62005-12-30 16:28:01 +00002241
drh75c014c2010-08-30 15:02:28 +00002242 /* True if opening an ephemeral, temporary database */
2243 const int isTempDb = zFilename==0 || zFilename[0]==0;
2244
danielk1977aef0bf62005-12-30 16:28:01 +00002245 /* Set the variable isMemdb to true for an in-memory database, or
drhb0a7c9c2010-12-06 21:09:59 +00002246 ** false for a file-based database.
danielk1977aef0bf62005-12-30 16:28:01 +00002247 */
drhb0a7c9c2010-12-06 21:09:59 +00002248#ifdef SQLITE_OMIT_MEMORYDB
2249 const int isMemdb = 0;
2250#else
2251 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
drh9c67b2a2012-05-28 13:58:00 +00002252 || (isTempDb && sqlite3TempInMemory(db))
2253 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
danielk1977aef0bf62005-12-30 16:28:01 +00002254#endif
2255
drhe5fe6902007-12-07 18:55:28 +00002256 assert( db!=0 );
dan3a6d8ae2011-04-23 15:54:54 +00002257 assert( pVfs!=0 );
drhe5fe6902007-12-07 18:55:28 +00002258 assert( sqlite3_mutex_held(db->mutex) );
drhd4187c72010-08-30 22:15:45 +00002259 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
2260
2261 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
2262 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
2263
2264 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
2265 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
drh153c62c2007-08-24 03:51:33 +00002266
drh75c014c2010-08-30 15:02:28 +00002267 if( isMemdb ){
2268 flags |= BTREE_MEMORY;
2269 }
2270 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
2271 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
2272 }
drh17435752007-08-16 04:30:38 +00002273 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00002274 if( !p ){
mistachkinfad30392016-02-13 23:43:46 +00002275 return SQLITE_NOMEM_BKPT;
danielk1977aef0bf62005-12-30 16:28:01 +00002276 }
2277 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00002278 p->db = db;
danielk1977602b4662009-07-02 07:47:33 +00002279#ifndef SQLITE_OMIT_SHARED_CACHE
2280 p->lock.pBtree = p;
2281 p->lock.iTable = 1;
2282#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002283
drh198bf392006-01-06 21:52:49 +00002284#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00002285 /*
2286 ** If this Btree is a candidate for shared cache, try to find an
2287 ** existing BtShared object that we can share with
2288 */
drh4ab9d252012-05-26 20:08:49 +00002289 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
drhf1f12682009-09-09 14:17:52 +00002290 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
drh6b5f0eb2015-03-31 16:33:08 +00002291 int nFilename = sqlite3Strlen30(zFilename)+1;
danielk1977adfb9b02007-09-17 07:02:56 +00002292 int nFullPathname = pVfs->mxPathname+1;
drh6b5f0eb2015-03-31 16:33:08 +00002293 char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
drh30ddce62011-10-15 00:16:30 +00002294 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
drh6b5f0eb2015-03-31 16:33:08 +00002295
drhff0587c2007-08-29 17:43:19 +00002296 p->sharable = 1;
drhff0587c2007-08-29 17:43:19 +00002297 if( !zFullPathname ){
2298 sqlite3_free(p);
mistachkinfad30392016-02-13 23:43:46 +00002299 return SQLITE_NOMEM_BKPT;
drhff0587c2007-08-29 17:43:19 +00002300 }
drhafc8b7f2012-05-26 18:06:38 +00002301 if( isMemdb ){
drh6b5f0eb2015-03-31 16:33:08 +00002302 memcpy(zFullPathname, zFilename, nFilename);
drhafc8b7f2012-05-26 18:06:38 +00002303 }else{
2304 rc = sqlite3OsFullPathname(pVfs, zFilename,
2305 nFullPathname, zFullPathname);
2306 if( rc ){
2307 sqlite3_free(zFullPathname);
2308 sqlite3_free(p);
2309 return rc;
2310 }
drh070ad6b2011-11-17 11:43:19 +00002311 }
drh30ddce62011-10-15 00:16:30 +00002312#if SQLITE_THREADSAFE
drh7555d8e2009-03-20 13:15:30 +00002313 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
2314 sqlite3_mutex_enter(mutexOpen);
danielk197759f8c082008-06-18 17:09:10 +00002315 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhff0587c2007-08-29 17:43:19 +00002316 sqlite3_mutex_enter(mutexShared);
drh30ddce62011-10-15 00:16:30 +00002317#endif
drh78f82d12008-09-02 00:52:52 +00002318 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
drhff0587c2007-08-29 17:43:19 +00002319 assert( pBt->nRef>0 );
drhd4e0bb02012-05-27 01:19:04 +00002320 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
drhff0587c2007-08-29 17:43:19 +00002321 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
drhc47fd8e2009-04-30 13:30:32 +00002322 int iDb;
2323 for(iDb=db->nDb-1; iDb>=0; iDb--){
2324 Btree *pExisting = db->aDb[iDb].pBt;
2325 if( pExisting && pExisting->pBt==pBt ){
2326 sqlite3_mutex_leave(mutexShared);
2327 sqlite3_mutex_leave(mutexOpen);
2328 sqlite3_free(zFullPathname);
2329 sqlite3_free(p);
2330 return SQLITE_CONSTRAINT;
2331 }
2332 }
drhff0587c2007-08-29 17:43:19 +00002333 p->pBt = pBt;
2334 pBt->nRef++;
2335 break;
2336 }
2337 }
2338 sqlite3_mutex_leave(mutexShared);
2339 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00002340 }
drhff0587c2007-08-29 17:43:19 +00002341#ifdef SQLITE_DEBUG
2342 else{
2343 /* In debug mode, we mark all persistent databases as sharable
2344 ** even when they are not. This exercises the locking code and
2345 ** gives more opportunity for asserts(sqlite3_mutex_held())
2346 ** statements to find locking problems.
2347 */
2348 p->sharable = 1;
2349 }
2350#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002351 }
2352#endif
drha059ad02001-04-17 20:09:11 +00002353 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00002354 /*
2355 ** The following asserts make sure that structures used by the btree are
2356 ** the right size. This is to guard against size changes that result
2357 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00002358 */
drh062cf272015-03-23 19:03:51 +00002359 assert( sizeof(i64)==8 );
2360 assert( sizeof(u64)==8 );
drhe53831d2007-08-17 01:14:38 +00002361 assert( sizeof(u32)==4 );
2362 assert( sizeof(u16)==2 );
2363 assert( sizeof(Pgno)==4 );
2364
2365 pBt = sqlite3MallocZero( sizeof(*pBt) );
2366 if( pBt==0 ){
mistachkinfad30392016-02-13 23:43:46 +00002367 rc = SQLITE_NOMEM_BKPT;
drhe53831d2007-08-17 01:14:38 +00002368 goto btree_open_out;
2369 }
danielk197771d5d2c2008-09-29 11:49:47 +00002370 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
drha2ee5892016-12-09 16:02:00 +00002371 sizeof(MemPage), flags, vfsFlags, pageReinit);
drhe53831d2007-08-17 01:14:38 +00002372 if( rc==SQLITE_OK ){
drh9b4c59f2013-04-15 17:03:42 +00002373 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
drhe53831d2007-08-17 01:14:38 +00002374 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
2375 }
2376 if( rc!=SQLITE_OK ){
2377 goto btree_open_out;
2378 }
shanehbd2aaf92010-09-01 02:38:21 +00002379 pBt->openFlags = (u8)flags;
danielk19772a50ff02009-04-10 09:47:06 +00002380 pBt->db = db;
danielk19771ceedd32008-11-19 10:22:33 +00002381 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
drhe53831d2007-08-17 01:14:38 +00002382 p->pBt = pBt;
2383
drhe53831d2007-08-17 01:14:38 +00002384 pBt->pCursor = 0;
2385 pBt->pPage1 = 0;
drhc9166342012-01-05 23:32:06 +00002386 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
drha5907a82017-06-19 11:44:22 +00002387#if defined(SQLITE_SECURE_DELETE)
drhc9166342012-01-05 23:32:06 +00002388 pBt->btsFlags |= BTS_SECURE_DELETE;
drha5907a82017-06-19 11:44:22 +00002389#elif defined(SQLITE_FAST_SECURE_DELETE)
2390 pBt->btsFlags |= BTS_OVERWRITE;
drh5b47efa2010-02-12 18:18:39 +00002391#endif
drh113762a2014-11-19 16:36:25 +00002392 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2393 ** determined by the 2-byte integer located at an offset of 16 bytes from
2394 ** the beginning of the database file. */
drhb2eced52010-08-12 02:41:12 +00002395 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
drhe53831d2007-08-17 01:14:38 +00002396 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2397 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002398 pBt->pageSize = 0;
drhe53831d2007-08-17 01:14:38 +00002399#ifndef SQLITE_OMIT_AUTOVACUUM
2400 /* If the magic name ":memory:" will create an in-memory database, then
2401 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2402 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2403 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2404 ** regular file-name. In this case the auto-vacuum applies as per normal.
2405 */
2406 if( zFilename && !isMemdb ){
2407 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2408 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2409 }
2410#endif
2411 nReserve = 0;
2412 }else{
drh113762a2014-11-19 16:36:25 +00002413 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2414 ** determined by the one-byte unsigned integer found at an offset of 20
2415 ** into the database file header. */
drhe53831d2007-08-17 01:14:38 +00002416 nReserve = zDbHeader[20];
drhc9166342012-01-05 23:32:06 +00002417 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
drhe53831d2007-08-17 01:14:38 +00002418#ifndef SQLITE_OMIT_AUTOVACUUM
2419 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2420 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2421#endif
2422 }
drhfa9601a2009-06-18 17:22:39 +00002423 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhc0b61812009-04-30 01:22:41 +00002424 if( rc ) goto btree_open_out;
drhe53831d2007-08-17 01:14:38 +00002425 pBt->usableSize = pBt->pageSize - nReserve;
2426 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
drhe53831d2007-08-17 01:14:38 +00002427
2428#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2429 /* Add the new BtShared object to the linked list sharable BtShareds.
2430 */
dan272989b2016-07-06 10:12:02 +00002431 pBt->nRef = 1;
drhe53831d2007-08-17 01:14:38 +00002432 if( p->sharable ){
drh30ddce62011-10-15 00:16:30 +00002433 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
drh30ddce62011-10-15 00:16:30 +00002434 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
danielk1977075c23a2008-09-01 18:34:20 +00002435 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
danielk197759f8c082008-06-18 17:09:10 +00002436 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00002437 if( pBt->mutex==0 ){
mistachkinfad30392016-02-13 23:43:46 +00002438 rc = SQLITE_NOMEM_BKPT;
drh3285db22007-09-03 22:00:39 +00002439 goto btree_open_out;
2440 }
drhff0587c2007-08-29 17:43:19 +00002441 }
drhe53831d2007-08-17 01:14:38 +00002442 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00002443 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2444 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
drhe53831d2007-08-17 01:14:38 +00002445 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00002446 }
drheee46cf2004-11-06 00:02:48 +00002447#endif
drh90f5ecb2004-07-22 01:19:35 +00002448 }
danielk1977aef0bf62005-12-30 16:28:01 +00002449
drhcfed7bc2006-03-13 14:28:05 +00002450#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00002451 /* If the new Btree uses a sharable pBtShared, then link the new
2452 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00002453 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00002454 */
drhe53831d2007-08-17 01:14:38 +00002455 if( p->sharable ){
2456 int i;
2457 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00002458 for(i=0; i<db->nDb; i++){
2459 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00002460 while( pSib->pPrev ){ pSib = pSib->pPrev; }
drh3bfa7e82016-03-22 14:37:59 +00002461 if( (uptr)p->pBt<(uptr)pSib->pBt ){
drhe53831d2007-08-17 01:14:38 +00002462 p->pNext = pSib;
2463 p->pPrev = 0;
2464 pSib->pPrev = p;
2465 }else{
drh3bfa7e82016-03-22 14:37:59 +00002466 while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
drhe53831d2007-08-17 01:14:38 +00002467 pSib = pSib->pNext;
2468 }
2469 p->pNext = pSib->pNext;
2470 p->pPrev = pSib;
2471 if( p->pNext ){
2472 p->pNext->pPrev = p;
2473 }
2474 pSib->pNext = p;
2475 }
2476 break;
2477 }
2478 }
danielk1977aef0bf62005-12-30 16:28:01 +00002479 }
danielk1977aef0bf62005-12-30 16:28:01 +00002480#endif
2481 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00002482
2483btree_open_out:
2484 if( rc!=SQLITE_OK ){
2485 if( pBt && pBt->pPager ){
dan7fb89902016-08-12 16:21:15 +00002486 sqlite3PagerClose(pBt->pPager, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002487 }
drh17435752007-08-16 04:30:38 +00002488 sqlite3_free(pBt);
2489 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00002490 *ppBtree = 0;
drh75c014c2010-08-30 15:02:28 +00002491 }else{
dan0f5a1862016-08-13 14:30:23 +00002492 sqlite3_file *pFile;
2493
drh75c014c2010-08-30 15:02:28 +00002494 /* If the B-Tree was successfully opened, set the pager-cache size to the
2495 ** default value. Except, when opening on an existing shared pager-cache,
2496 ** do not change the pager-cache size.
2497 */
2498 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2499 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
2500 }
dan0f5a1862016-08-13 14:30:23 +00002501
2502 pFile = sqlite3PagerFile(pBt->pPager);
2503 if( pFile->pMethods ){
2504 sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
2505 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002506 }
drh7555d8e2009-03-20 13:15:30 +00002507 if( mutexOpen ){
2508 assert( sqlite3_mutex_held(mutexOpen) );
2509 sqlite3_mutex_leave(mutexOpen);
2510 }
dan272989b2016-07-06 10:12:02 +00002511 assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00002512 return rc;
drha059ad02001-04-17 20:09:11 +00002513}
2514
2515/*
drhe53831d2007-08-17 01:14:38 +00002516** Decrement the BtShared.nRef counter. When it reaches zero,
2517** remove the BtShared structure from the sharing list. Return
2518** true if the BtShared.nRef counter reaches zero and return
2519** false if it is still positive.
2520*/
2521static int removeFromSharingList(BtShared *pBt){
2522#ifndef SQLITE_OMIT_SHARED_CACHE
drh30ddce62011-10-15 00:16:30 +00002523 MUTEX_LOGIC( sqlite3_mutex *pMaster; )
drhe53831d2007-08-17 01:14:38 +00002524 BtShared *pList;
2525 int removed = 0;
2526
drhd677b3d2007-08-20 22:48:41 +00002527 assert( sqlite3_mutex_notheld(pBt->mutex) );
drh30ddce62011-10-15 00:16:30 +00002528 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
drhe53831d2007-08-17 01:14:38 +00002529 sqlite3_mutex_enter(pMaster);
2530 pBt->nRef--;
2531 if( pBt->nRef<=0 ){
drh78f82d12008-09-02 00:52:52 +00002532 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2533 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
drhe53831d2007-08-17 01:14:38 +00002534 }else{
drh78f82d12008-09-02 00:52:52 +00002535 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
drh34004ce2008-07-11 16:15:17 +00002536 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00002537 pList=pList->pNext;
2538 }
drh34004ce2008-07-11 16:15:17 +00002539 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00002540 pList->pNext = pBt->pNext;
2541 }
2542 }
drh3285db22007-09-03 22:00:39 +00002543 if( SQLITE_THREADSAFE ){
2544 sqlite3_mutex_free(pBt->mutex);
2545 }
drhe53831d2007-08-17 01:14:38 +00002546 removed = 1;
2547 }
2548 sqlite3_mutex_leave(pMaster);
2549 return removed;
2550#else
2551 return 1;
2552#endif
2553}
2554
2555/*
drhf7141992008-06-19 00:16:08 +00002556** Make sure pBt->pTmpSpace points to an allocation of
drh92787cf2014-10-15 11:55:51 +00002557** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
2558** pointer.
drhf7141992008-06-19 00:16:08 +00002559*/
2560static void allocateTempSpace(BtShared *pBt){
2561 if( !pBt->pTmpSpace ){
2562 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
dan14285b72013-10-16 11:39:07 +00002563
2564 /* One of the uses of pBt->pTmpSpace is to format cells before
2565 ** inserting them into a leaf page (function fillInCell()). If
2566 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2567 ** by the various routines that manipulate binary cells. Which
2568 ** can mean that fillInCell() only initializes the first 2 or 3
2569 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2570 ** it into a database page. This is not actually a problem, but it
2571 ** does cause a valgrind error when the 1 or 2 bytes of unitialized
2572 ** data is passed to system call write(). So to avoid this error,
drh92787cf2014-10-15 11:55:51 +00002573 ** zero the first 4 bytes of temp space here.
2574 **
2575 ** Also: Provide four bytes of initialized space before the
2576 ** beginning of pTmpSpace as an area available to prepend the
2577 ** left-child pointer to the beginning of a cell.
2578 */
2579 if( pBt->pTmpSpace ){
2580 memset(pBt->pTmpSpace, 0, 8);
2581 pBt->pTmpSpace += 4;
2582 }
drhf7141992008-06-19 00:16:08 +00002583 }
2584}
2585
2586/*
2587** Free the pBt->pTmpSpace allocation
2588*/
2589static void freeTempSpace(BtShared *pBt){
drh92787cf2014-10-15 11:55:51 +00002590 if( pBt->pTmpSpace ){
2591 pBt->pTmpSpace -= 4;
2592 sqlite3PageFree(pBt->pTmpSpace);
2593 pBt->pTmpSpace = 0;
2594 }
drhf7141992008-06-19 00:16:08 +00002595}
2596
2597/*
drha059ad02001-04-17 20:09:11 +00002598** Close an open database and invalidate all cursors.
2599*/
danielk1977aef0bf62005-12-30 16:28:01 +00002600int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002601 BtShared *pBt = p->pBt;
2602 BtCursor *pCur;
2603
danielk1977aef0bf62005-12-30 16:28:01 +00002604 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00002605 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00002606 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002607 pCur = pBt->pCursor;
2608 while( pCur ){
2609 BtCursor *pTmp = pCur;
2610 pCur = pCur->pNext;
2611 if( pTmp->pBtree==p ){
2612 sqlite3BtreeCloseCursor(pTmp);
2613 }
drha059ad02001-04-17 20:09:11 +00002614 }
danielk1977aef0bf62005-12-30 16:28:01 +00002615
danielk19778d34dfd2006-01-24 16:37:57 +00002616 /* Rollback any active transaction and free the handle structure.
2617 ** The call to sqlite3BtreeRollback() drops any table-locks held by
2618 ** this handle.
2619 */
drh47b7fc72014-11-11 01:33:57 +00002620 sqlite3BtreeRollback(p, SQLITE_OK, 0);
drhe53831d2007-08-17 01:14:38 +00002621 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002622
danielk1977aef0bf62005-12-30 16:28:01 +00002623 /* If there are still other outstanding references to the shared-btree
2624 ** structure, return now. The remainder of this procedure cleans
2625 ** up the shared-btree.
2626 */
drhe53831d2007-08-17 01:14:38 +00002627 assert( p->wantToLock==0 && p->locked==0 );
2628 if( !p->sharable || removeFromSharingList(pBt) ){
2629 /* The pBt is no longer on the sharing list, so we can access
2630 ** it without having to hold the mutex.
2631 **
2632 ** Clean out and delete the BtShared object.
2633 */
2634 assert( !pBt->pCursor );
dan7fb89902016-08-12 16:21:15 +00002635 sqlite3PagerClose(pBt->pPager, p->db);
drhe53831d2007-08-17 01:14:38 +00002636 if( pBt->xFreeSchema && pBt->pSchema ){
2637 pBt->xFreeSchema(pBt->pSchema);
2638 }
drhb9755982010-07-24 16:34:37 +00002639 sqlite3DbFree(0, pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00002640 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00002641 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002642 }
2643
drhe53831d2007-08-17 01:14:38 +00002644#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00002645 assert( p->wantToLock==0 );
2646 assert( p->locked==0 );
2647 if( p->pPrev ) p->pPrev->pNext = p->pNext;
2648 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00002649#endif
2650
drhe53831d2007-08-17 01:14:38 +00002651 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00002652 return SQLITE_OK;
2653}
2654
2655/*
drh9b0cf342015-11-12 14:57:19 +00002656** Change the "soft" limit on the number of pages in the cache.
2657** Unused and unmodified pages will be recycled when the number of
2658** pages in the cache exceeds this soft limit. But the size of the
2659** cache is allowed to grow larger than this limit if it contains
2660** dirty pages or pages still in active use.
drhf57b14a2001-09-14 18:54:08 +00002661*/
danielk1977aef0bf62005-12-30 16:28:01 +00002662int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2663 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00002664 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002665 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00002666 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00002667 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00002668 return SQLITE_OK;
2669}
2670
drh9b0cf342015-11-12 14:57:19 +00002671/*
2672** Change the "spill" limit on the number of pages in the cache.
2673** If the number of pages exceeds this limit during a write transaction,
2674** the pager might attempt to "spill" pages to the journal early in
2675** order to free up memory.
2676**
2677** The value returned is the current spill size. If zero is passed
2678** as an argument, no changes are made to the spill size setting, so
2679** using mxPage of 0 is a way to query the current spill size.
2680*/
2681int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
2682 BtShared *pBt = p->pBt;
2683 int res;
2684 assert( sqlite3_mutex_held(p->db->mutex) );
2685 sqlite3BtreeEnter(p);
2686 res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
2687 sqlite3BtreeLeave(p);
2688 return res;
2689}
2690
drh18c7e402014-03-14 11:46:10 +00002691#if SQLITE_MAX_MMAP_SIZE>0
drhf57b14a2001-09-14 18:54:08 +00002692/*
dan5d8a1372013-03-19 19:28:06 +00002693** Change the limit on the amount of the database file that may be
2694** memory mapped.
2695*/
drh9b4c59f2013-04-15 17:03:42 +00002696int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
dan5d8a1372013-03-19 19:28:06 +00002697 BtShared *pBt = p->pBt;
2698 assert( sqlite3_mutex_held(p->db->mutex) );
2699 sqlite3BtreeEnter(p);
drh9b4c59f2013-04-15 17:03:42 +00002700 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
dan5d8a1372013-03-19 19:28:06 +00002701 sqlite3BtreeLeave(p);
2702 return SQLITE_OK;
2703}
drh18c7e402014-03-14 11:46:10 +00002704#endif /* SQLITE_MAX_MMAP_SIZE>0 */
dan5d8a1372013-03-19 19:28:06 +00002705
2706/*
drh973b6e32003-02-12 14:09:42 +00002707** Change the way data is synced to disk in order to increase or decrease
2708** how well the database resists damage due to OS crashes and power
2709** failures. Level 1 is the same as asynchronous (no syncs() occur and
2710** there is a high probability of damage) Level 2 is the default. There
2711** is a very low but non-zero probability of damage. Level 3 reduces the
2712** probability of damage to near zero but with a write performance reduction.
2713*/
danielk197793758c82005-01-21 08:13:14 +00002714#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drh40c39412013-08-16 20:42:20 +00002715int sqlite3BtreeSetPagerFlags(
drhc97d8462010-11-19 18:23:35 +00002716 Btree *p, /* The btree to set the safety level on */
drh40c39412013-08-16 20:42:20 +00002717 unsigned pgFlags /* Various PAGER_* flags */
drhc97d8462010-11-19 18:23:35 +00002718){
danielk1977aef0bf62005-12-30 16:28:01 +00002719 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00002720 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002721 sqlite3BtreeEnter(p);
drh40c39412013-08-16 20:42:20 +00002722 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
drhd677b3d2007-08-20 22:48:41 +00002723 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00002724 return SQLITE_OK;
2725}
danielk197793758c82005-01-21 08:13:14 +00002726#endif
drh973b6e32003-02-12 14:09:42 +00002727
drh2c8997b2005-08-27 16:36:48 +00002728/*
drh90f5ecb2004-07-22 01:19:35 +00002729** Change the default pages size and the number of reserved bytes per page.
drhce4869f2009-04-02 20:16:58 +00002730** Or, if the page size has already been fixed, return SQLITE_READONLY
2731** without changing anything.
drh06f50212004-11-02 14:24:33 +00002732**
2733** The page size must be a power of 2 between 512 and 65536. If the page
2734** size supplied does not meet this constraint then the page size is not
2735** changed.
2736**
2737** Page sizes are constrained to be a power of two so that the region
2738** of the database file used for locking (beginning at PENDING_BYTE,
2739** the first byte past the 1GB boundary, 0x40000000) needs to occur
2740** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00002741**
2742** If parameter nReserve is less than zero, then the number of reserved
2743** bytes per page is left unchanged.
drhce4869f2009-04-02 20:16:58 +00002744**
drhc9166342012-01-05 23:32:06 +00002745** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
drhce4869f2009-04-02 20:16:58 +00002746** and autovacuum mode can no longer be changed.
drh90f5ecb2004-07-22 01:19:35 +00002747*/
drhce4869f2009-04-02 20:16:58 +00002748int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
danielk1977a1644fd2007-08-29 12:31:25 +00002749 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002750 BtShared *pBt = p->pBt;
drhf49661a2008-12-10 16:45:50 +00002751 assert( nReserve>=-1 && nReserve<=255 );
drhd677b3d2007-08-20 22:48:41 +00002752 sqlite3BtreeEnter(p);
drhad0961b2015-02-21 00:19:25 +00002753#if SQLITE_HAS_CODEC
2754 if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
2755#endif
drhc9166342012-01-05 23:32:06 +00002756 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
drhd677b3d2007-08-20 22:48:41 +00002757 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00002758 return SQLITE_READONLY;
2759 }
2760 if( nReserve<0 ){
2761 nReserve = pBt->pageSize - pBt->usableSize;
2762 }
drhf49661a2008-12-10 16:45:50 +00002763 assert( nReserve>=0 && nReserve<=255 );
drh06f50212004-11-02 14:24:33 +00002764 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2765 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00002766 assert( (pageSize & 7)==0 );
dandd14ecb2015-05-05 10:03:08 +00002767 assert( !pBt->pCursor );
drhb2eced52010-08-12 02:41:12 +00002768 pBt->pageSize = (u32)pageSize;
drhf7141992008-06-19 00:16:08 +00002769 freeTempSpace(pBt);
drh90f5ecb2004-07-22 01:19:35 +00002770 }
drhfa9601a2009-06-18 17:22:39 +00002771 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhf49661a2008-12-10 16:45:50 +00002772 pBt->usableSize = pBt->pageSize - (u16)nReserve;
drhc9166342012-01-05 23:32:06 +00002773 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
drhd677b3d2007-08-20 22:48:41 +00002774 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00002775 return rc;
drh90f5ecb2004-07-22 01:19:35 +00002776}
2777
2778/*
2779** Return the currently defined page size
2780*/
danielk1977aef0bf62005-12-30 16:28:01 +00002781int sqlite3BtreeGetPageSize(Btree *p){
2782 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00002783}
drh7f751222009-03-17 22:33:00 +00002784
dan0094f372012-09-28 20:23:42 +00002785/*
2786** This function is similar to sqlite3BtreeGetReserve(), except that it
2787** may only be called if it is guaranteed that the b-tree mutex is already
2788** held.
2789**
2790** This is useful in one special case in the backup API code where it is
2791** known that the shared b-tree mutex is held, but the mutex on the
2792** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
2793** were to be called, it might collide with some other operation on the
mistachkin48864df2013-03-21 21:20:32 +00002794** database handle that owns *p, causing undefined behavior.
dan0094f372012-09-28 20:23:42 +00002795*/
2796int sqlite3BtreeGetReserveNoMutex(Btree *p){
drhad0961b2015-02-21 00:19:25 +00002797 int n;
dan0094f372012-09-28 20:23:42 +00002798 assert( sqlite3_mutex_held(p->pBt->mutex) );
drhad0961b2015-02-21 00:19:25 +00002799 n = p->pBt->pageSize - p->pBt->usableSize;
2800 return n;
dan0094f372012-09-28 20:23:42 +00002801}
2802
drh7f751222009-03-17 22:33:00 +00002803/*
2804** Return the number of bytes of space at the end of every page that
2805** are intentually left unused. This is the "reserved" space that is
2806** sometimes used by extensions.
drhad0961b2015-02-21 00:19:25 +00002807**
2808** If SQLITE_HAS_MUTEX is defined then the number returned is the
2809** greater of the current reserved space and the maximum requested
2810** reserve space.
drh7f751222009-03-17 22:33:00 +00002811*/
drhad0961b2015-02-21 00:19:25 +00002812int sqlite3BtreeGetOptimalReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002813 int n;
2814 sqlite3BtreeEnter(p);
drhad0961b2015-02-21 00:19:25 +00002815 n = sqlite3BtreeGetReserveNoMutex(p);
2816#ifdef SQLITE_HAS_CODEC
2817 if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
2818#endif
drhd677b3d2007-08-20 22:48:41 +00002819 sqlite3BtreeLeave(p);
2820 return n;
drh2011d5f2004-07-22 02:40:37 +00002821}
drhf8e632b2007-05-08 14:51:36 +00002822
drhad0961b2015-02-21 00:19:25 +00002823
drhf8e632b2007-05-08 14:51:36 +00002824/*
2825** Set the maximum page count for a database if mxPage is positive.
2826** No changes are made if mxPage is 0 or negative.
2827** Regardless of the value of mxPage, return the maximum page count.
2828*/
2829int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00002830 int n;
2831 sqlite3BtreeEnter(p);
2832 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
2833 sqlite3BtreeLeave(p);
2834 return n;
drhf8e632b2007-05-08 14:51:36 +00002835}
drh5b47efa2010-02-12 18:18:39 +00002836
2837/*
drha5907a82017-06-19 11:44:22 +00002838** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
2839**
2840** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
2841** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
2842** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
2843** newFlag==(-1) No changes
2844**
2845** This routine acts as a query if newFlag is less than zero
2846**
2847** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
2848** freelist leaf pages are not written back to the database. Thus in-page
2849** deleted content is cleared, but freelist deleted content is not.
2850**
2851** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
2852** that freelist leaf pages are written back into the database, increasing
2853** the amount of disk I/O.
drh5b47efa2010-02-12 18:18:39 +00002854*/
2855int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
2856 int b;
drhaf034ed2010-02-12 19:46:26 +00002857 if( p==0 ) return 0;
drh5b47efa2010-02-12 18:18:39 +00002858 sqlite3BtreeEnter(p);
drha5907a82017-06-19 11:44:22 +00002859 assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
2860 assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
drh5b47efa2010-02-12 18:18:39 +00002861 if( newFlag>=0 ){
drha5907a82017-06-19 11:44:22 +00002862 p->pBt->btsFlags &= ~BTS_FAST_SECURE;
2863 p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
2864 }
2865 b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
drh5b47efa2010-02-12 18:18:39 +00002866 sqlite3BtreeLeave(p);
2867 return b;
2868}
drh90f5ecb2004-07-22 01:19:35 +00002869
2870/*
danielk1977951af802004-11-05 15:45:09 +00002871** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
2872** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
2873** is disabled. The default value for the auto-vacuum property is
2874** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
2875*/
danielk1977aef0bf62005-12-30 16:28:01 +00002876int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00002877#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002878 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00002879#else
danielk1977dddbcdc2007-04-26 14:42:34 +00002880 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002881 int rc = SQLITE_OK;
drh076d4662009-02-18 20:31:18 +00002882 u8 av = (u8)autoVacuum;
drhd677b3d2007-08-20 22:48:41 +00002883
2884 sqlite3BtreeEnter(p);
drhc9166342012-01-05 23:32:06 +00002885 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002886 rc = SQLITE_READONLY;
2887 }else{
drh076d4662009-02-18 20:31:18 +00002888 pBt->autoVacuum = av ?1:0;
2889 pBt->incrVacuum = av==2 ?1:0;
danielk1977951af802004-11-05 15:45:09 +00002890 }
drhd677b3d2007-08-20 22:48:41 +00002891 sqlite3BtreeLeave(p);
2892 return rc;
danielk1977951af802004-11-05 15:45:09 +00002893#endif
2894}
2895
2896/*
2897** Return the value of the 'auto-vacuum' property. If auto-vacuum is
2898** enabled 1 is returned. Otherwise 0.
2899*/
danielk1977aef0bf62005-12-30 16:28:01 +00002900int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00002901#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002902 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00002903#else
drhd677b3d2007-08-20 22:48:41 +00002904 int rc;
2905 sqlite3BtreeEnter(p);
2906 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00002907 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
2908 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
2909 BTREE_AUTOVACUUM_INCR
2910 );
drhd677b3d2007-08-20 22:48:41 +00002911 sqlite3BtreeLeave(p);
2912 return rc;
danielk1977951af802004-11-05 15:45:09 +00002913#endif
2914}
2915
danf5da7db2017-03-16 18:14:39 +00002916/*
2917** If the user has not set the safety-level for this database connection
2918** using "PRAGMA synchronous", and if the safety-level is not already
2919** set to the value passed to this function as the second parameter,
2920** set it so.
2921*/
2922#if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS
2923static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
2924 sqlite3 *db;
2925 Db *pDb;
2926 if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
2927 while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
2928 if( pDb->bSyncSet==0
2929 && pDb->safety_level!=safety_level
2930 && pDb!=&db->aDb[1]
2931 ){
2932 pDb->safety_level = safety_level;
2933 sqlite3PagerSetFlags(pBt->pPager,
2934 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
2935 }
2936 }
2937}
2938#else
danfc8f4b62017-03-16 18:54:42 +00002939# define setDefaultSyncFlag(pBt,safety_level)
danf5da7db2017-03-16 18:14:39 +00002940#endif
danielk1977951af802004-11-05 15:45:09 +00002941
2942/*
drha34b6762004-05-07 13:30:42 +00002943** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00002944** also acquire a readlock on that file.
2945**
2946** SQLITE_OK is returned on success. If the file is not a
2947** well-formed database file, then SQLITE_CORRUPT is returned.
2948** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00002949** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00002950*/
danielk1977aef0bf62005-12-30 16:28:01 +00002951static int lockBtree(BtShared *pBt){
drhc2a4bab2010-04-02 12:46:45 +00002952 int rc; /* Result code from subfunctions */
2953 MemPage *pPage1; /* Page 1 of the database file */
2954 int nPage; /* Number of pages in the database */
2955 int nPageFile = 0; /* Number of pages in the database file */
2956 int nPageHeader; /* Number of pages in the database according to hdr */
drhd677b3d2007-08-20 22:48:41 +00002957
drh1fee73e2007-08-29 04:00:57 +00002958 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977295dc102009-04-01 19:07:03 +00002959 assert( pBt->pPage1==0 );
danielk197789bc4bc2009-07-21 19:25:24 +00002960 rc = sqlite3PagerSharedLock(pBt->pPager);
2961 if( rc!=SQLITE_OK ) return rc;
drhb00fc3b2013-08-21 23:42:32 +00002962 rc = btreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00002963 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00002964
2965 /* Do some checking to help insure the file we opened really is
2966 ** a valid database file.
2967 */
drhc2a4bab2010-04-02 12:46:45 +00002968 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
drh8fb8b532010-08-14 17:12:04 +00002969 sqlite3PagerPagecount(pBt->pPager, &nPageFile);
drhb28e59b2010-06-17 02:13:39 +00002970 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
drhc2a4bab2010-04-02 12:46:45 +00002971 nPage = nPageFile;
drh97b59a52010-03-31 02:31:33 +00002972 }
2973 if( nPage>0 ){
drh43b18e12010-08-17 19:40:08 +00002974 u32 pageSize;
2975 u32 usableSize;
drhb6f41482004-05-14 01:58:11 +00002976 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00002977 rc = SQLITE_NOTADB;
drh113762a2014-11-19 16:36:25 +00002978 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
2979 ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
2980 ** 61 74 20 33 00. */
drhb6f41482004-05-14 01:58:11 +00002981 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00002982 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00002983 }
dan5cf53532010-05-01 16:40:20 +00002984
2985#ifdef SQLITE_OMIT_WAL
2986 if( page1[18]>1 ){
drhc9166342012-01-05 23:32:06 +00002987 pBt->btsFlags |= BTS_READ_ONLY;
dan5cf53532010-05-01 16:40:20 +00002988 }
2989 if( page1[19]>1 ){
2990 goto page1_init_failed;
2991 }
2992#else
dane04dc882010-04-20 18:53:15 +00002993 if( page1[18]>2 ){
drhc9166342012-01-05 23:32:06 +00002994 pBt->btsFlags |= BTS_READ_ONLY;
drh309169a2007-04-24 17:27:51 +00002995 }
dane04dc882010-04-20 18:53:15 +00002996 if( page1[19]>2 ){
drhb6f41482004-05-14 01:58:11 +00002997 goto page1_init_failed;
2998 }
drhe5ae5732008-06-15 02:51:47 +00002999
dana470aeb2010-04-21 11:43:38 +00003000 /* If the write version is set to 2, this database should be accessed
3001 ** in WAL mode. If the log is not already open, open it now. Then
3002 ** return SQLITE_OK and return without populating BtShared.pPage1.
3003 ** The caller detects this and calls this function again. This is
3004 ** required as the version of page 1 currently in the page1 buffer
3005 ** may not be the latest version - there may be a newer one in the log
3006 ** file.
3007 */
drhc9166342012-01-05 23:32:06 +00003008 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
dane04dc882010-04-20 18:53:15 +00003009 int isOpen = 0;
drh7ed91f22010-04-29 22:34:07 +00003010 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
dane04dc882010-04-20 18:53:15 +00003011 if( rc!=SQLITE_OK ){
3012 goto page1_init_failed;
drhe243de52016-03-08 15:14:26 +00003013 }else{
danf5da7db2017-03-16 18:14:39 +00003014 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
drhe243de52016-03-08 15:14:26 +00003015 if( isOpen==0 ){
drh3908fe92017-09-01 14:50:19 +00003016 releasePageOne(pPage1);
drhe243de52016-03-08 15:14:26 +00003017 return SQLITE_OK;
3018 }
dane04dc882010-04-20 18:53:15 +00003019 }
dan8b5444b2010-04-27 14:37:47 +00003020 rc = SQLITE_NOTADB;
danf5da7db2017-03-16 18:14:39 +00003021 }else{
3022 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
dane04dc882010-04-20 18:53:15 +00003023 }
dan5cf53532010-05-01 16:40:20 +00003024#endif
dane04dc882010-04-20 18:53:15 +00003025
drh113762a2014-11-19 16:36:25 +00003026 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
3027 ** fractions and the leaf payload fraction values must be 64, 32, and 32.
3028 **
drhe5ae5732008-06-15 02:51:47 +00003029 ** The original design allowed these amounts to vary, but as of
3030 ** version 3.6.0, we require them to be fixed.
3031 */
3032 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
3033 goto page1_init_failed;
3034 }
drh113762a2014-11-19 16:36:25 +00003035 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
3036 ** determined by the 2-byte integer located at an offset of 16 bytes from
3037 ** the beginning of the database file. */
drhb2eced52010-08-12 02:41:12 +00003038 pageSize = (page1[16]<<8) | (page1[17]<<16);
drh113762a2014-11-19 16:36:25 +00003039 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
3040 ** between 512 and 65536 inclusive. */
drhb2eced52010-08-12 02:41:12 +00003041 if( ((pageSize-1)&pageSize)!=0
3042 || pageSize>SQLITE_MAX_PAGE_SIZE
3043 || pageSize<=256
drh7dc385e2007-09-06 23:39:36 +00003044 ){
drh07d183d2005-05-01 22:52:42 +00003045 goto page1_init_failed;
3046 }
3047 assert( (pageSize & 7)==0 );
drh113762a2014-11-19 16:36:25 +00003048 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
3049 ** integer at offset 20 is the number of bytes of space at the end of
3050 ** each page to reserve for extensions.
3051 **
3052 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
3053 ** determined by the one-byte unsigned integer found at an offset of 20
3054 ** into the database file header. */
danielk1977f653d782008-03-20 11:04:21 +00003055 usableSize = pageSize - page1[20];
shaneh1df2db72010-08-18 02:28:48 +00003056 if( (u32)pageSize!=pBt->pageSize ){
danielk1977f653d782008-03-20 11:04:21 +00003057 /* After reading the first page of the database assuming a page size
3058 ** of BtShared.pageSize, we have discovered that the page-size is
3059 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
3060 ** zero and return SQLITE_OK. The caller will call this function
3061 ** again with the correct page-size.
3062 */
drh3908fe92017-09-01 14:50:19 +00003063 releasePageOne(pPage1);
drh43b18e12010-08-17 19:40:08 +00003064 pBt->usableSize = usableSize;
3065 pBt->pageSize = pageSize;
drhf7141992008-06-19 00:16:08 +00003066 freeTempSpace(pBt);
drhfa9601a2009-06-18 17:22:39 +00003067 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
3068 pageSize-usableSize);
drh5e483932009-07-10 16:51:30 +00003069 return rc;
danielk1977f653d782008-03-20 11:04:21 +00003070 }
drh169dd922017-06-26 13:57:49 +00003071 if( (pBt->db->flags & SQLITE_WriteSchema)==0 && nPage>nPageFile ){
drhc2a4bab2010-04-02 12:46:45 +00003072 rc = SQLITE_CORRUPT_BKPT;
3073 goto page1_init_failed;
3074 }
drh113762a2014-11-19 16:36:25 +00003075 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
3076 ** be less than 480. In other words, if the page size is 512, then the
3077 ** reserved space size cannot exceed 32. */
drhb33e1b92009-06-18 11:29:20 +00003078 if( usableSize<480 ){
drhb6f41482004-05-14 01:58:11 +00003079 goto page1_init_failed;
3080 }
drh43b18e12010-08-17 19:40:08 +00003081 pBt->pageSize = pageSize;
3082 pBt->usableSize = usableSize;
drh057cd3a2005-02-15 16:23:02 +00003083#ifndef SQLITE_OMIT_AUTOVACUUM
3084 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00003085 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00003086#endif
drh306dc212001-05-21 13:45:10 +00003087 }
drhb6f41482004-05-14 01:58:11 +00003088
3089 /* maxLocal is the maximum amount of payload to store locally for
3090 ** a cell. Make sure it is small enough so that at least minFanout
3091 ** cells can will fit on one page. We assume a 10-byte page header.
3092 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00003093 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00003094 ** 4-byte child pointer
3095 ** 9-byte nKey value
3096 ** 4-byte nData value
3097 ** 4-byte overflow page pointer
drhe22e03e2010-08-18 21:19:03 +00003098 ** So a cell consists of a 2-byte pointer, a header which is as much as
drh43605152004-05-29 21:46:49 +00003099 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
3100 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00003101 */
shaneh1df2db72010-08-18 02:28:48 +00003102 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
3103 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
3104 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
3105 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
drhc9166342012-01-05 23:32:06 +00003106 if( pBt->maxLocal>127 ){
3107 pBt->max1bytePayload = 127;
3108 }else{
mistachkin0547e2f2012-01-08 00:54:02 +00003109 pBt->max1bytePayload = (u8)pBt->maxLocal;
drhc9166342012-01-05 23:32:06 +00003110 }
drh2e38c322004-09-03 18:38:44 +00003111 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00003112 pBt->pPage1 = pPage1;
drhdd3cd972010-03-27 17:12:36 +00003113 pBt->nPage = nPage;
drhb6f41482004-05-14 01:58:11 +00003114 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00003115
drh72f82862001-05-24 21:06:34 +00003116page1_init_failed:
drh3908fe92017-09-01 14:50:19 +00003117 releasePageOne(pPage1);
drh3aac2dd2004-04-26 14:10:20 +00003118 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00003119 return rc;
drh306dc212001-05-21 13:45:10 +00003120}
3121
drh85ec3b62013-05-14 23:12:06 +00003122#ifndef NDEBUG
3123/*
3124** Return the number of cursors open on pBt. This is for use
3125** in assert() expressions, so it is only compiled if NDEBUG is not
3126** defined.
3127**
3128** Only write cursors are counted if wrOnly is true. If wrOnly is
3129** false then all cursors are counted.
3130**
3131** For the purposes of this routine, a cursor is any cursor that
peter.d.reid60ec9142014-09-06 16:39:46 +00003132** is capable of reading or writing to the database. Cursors that
drh85ec3b62013-05-14 23:12:06 +00003133** have been tripped into the CURSOR_FAULT state are not counted.
3134*/
3135static int countValidCursors(BtShared *pBt, int wrOnly){
3136 BtCursor *pCur;
3137 int r = 0;
3138 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drh036dbec2014-03-11 23:40:44 +00003139 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
3140 && pCur->eState!=CURSOR_FAULT ) r++;
drh85ec3b62013-05-14 23:12:06 +00003141 }
3142 return r;
3143}
3144#endif
3145
drh306dc212001-05-21 13:45:10 +00003146/*
drhb8ca3072001-12-05 00:21:20 +00003147** If there are no outstanding cursors and we are not in the middle
3148** of a transaction but there is a read lock on the database, then
3149** this routine unrefs the first page of the database file which
3150** has the effect of releasing the read lock.
3151**
drhb8ca3072001-12-05 00:21:20 +00003152** If there is a transaction in progress, this routine is a no-op.
3153*/
danielk1977aef0bf62005-12-30 16:28:01 +00003154static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00003155 assert( sqlite3_mutex_held(pBt->mutex) );
drh85ec3b62013-05-14 23:12:06 +00003156 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
danielk19771bc9ee92009-07-04 15:41:02 +00003157 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
drhb2325b72014-09-24 18:31:07 +00003158 MemPage *pPage1 = pBt->pPage1;
3159 assert( pPage1->aData );
danielk1977c1761e82009-06-25 09:40:03 +00003160 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
drh3aac2dd2004-04-26 14:10:20 +00003161 pBt->pPage1 = 0;
drh3908fe92017-09-01 14:50:19 +00003162 releasePageOne(pPage1);
drhb8ca3072001-12-05 00:21:20 +00003163 }
3164}
3165
3166/*
drhe39f2f92009-07-23 01:43:59 +00003167** If pBt points to an empty file then convert that empty file
3168** into a new empty database by initializing the first page of
3169** the database.
drh8b2f49b2001-06-08 00:21:52 +00003170*/
danielk1977aef0bf62005-12-30 16:28:01 +00003171static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00003172 MemPage *pP1;
3173 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00003174 int rc;
drhd677b3d2007-08-20 22:48:41 +00003175
drh1fee73e2007-08-29 04:00:57 +00003176 assert( sqlite3_mutex_held(pBt->mutex) );
drhdd3cd972010-03-27 17:12:36 +00003177 if( pBt->nPage>0 ){
3178 return SQLITE_OK;
danielk1977ad0132d2008-06-07 08:58:22 +00003179 }
drh3aac2dd2004-04-26 14:10:20 +00003180 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00003181 assert( pP1!=0 );
3182 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00003183 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00003184 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00003185 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
3186 assert( sizeof(zMagicHeader)==16 );
shaneh1df2db72010-08-18 02:28:48 +00003187 data[16] = (u8)((pBt->pageSize>>8)&0xff);
3188 data[17] = (u8)((pBt->pageSize>>16)&0xff);
drh9e572e62004-04-23 23:43:10 +00003189 data[18] = 1;
3190 data[19] = 1;
drhf49661a2008-12-10 16:45:50 +00003191 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
3192 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
drhe5ae5732008-06-15 02:51:47 +00003193 data[21] = 64;
3194 data[22] = 32;
3195 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00003196 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00003197 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhc9166342012-01-05 23:32:06 +00003198 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
danielk1977003ba062004-11-04 02:57:33 +00003199#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00003200 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00003201 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00003202 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00003203 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00003204#endif
drhdd3cd972010-03-27 17:12:36 +00003205 pBt->nPage = 1;
3206 data[31] = 1;
drh8b2f49b2001-06-08 00:21:52 +00003207 return SQLITE_OK;
3208}
3209
3210/*
danb483eba2012-10-13 19:58:11 +00003211** Initialize the first page of the database file (creating a database
3212** consisting of a single page and no schema objects). Return SQLITE_OK
3213** if successful, or an SQLite error code otherwise.
3214*/
3215int sqlite3BtreeNewDb(Btree *p){
3216 int rc;
3217 sqlite3BtreeEnter(p);
3218 p->pBt->nPage = 0;
3219 rc = newDatabase(p->pBt);
3220 sqlite3BtreeLeave(p);
3221 return rc;
3222}
3223
3224/*
danielk1977ee5741e2004-05-31 10:01:34 +00003225** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00003226** is started if the second argument is nonzero, otherwise a read-
3227** transaction. If the second argument is 2 or more and exclusive
3228** transaction is started, meaning that no other process is allowed
3229** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00003230** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00003231** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00003232**
danielk1977ee5741e2004-05-31 10:01:34 +00003233** A write-transaction must be started before attempting any
3234** changes to the database. None of the following routines
3235** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00003236**
drh23e11ca2004-05-04 17:27:28 +00003237** sqlite3BtreeCreateTable()
3238** sqlite3BtreeCreateIndex()
3239** sqlite3BtreeClearTable()
3240** sqlite3BtreeDropTable()
3241** sqlite3BtreeInsert()
3242** sqlite3BtreeDelete()
3243** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00003244**
drhb8ef32c2005-03-14 02:01:49 +00003245** If an initial attempt to acquire the lock fails because of lock contention
3246** and the database was previously unlocked, then invoke the busy handler
3247** if there is one. But if there was previously a read-lock, do not
3248** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
3249** returned when there is already a read-lock in order to avoid a deadlock.
3250**
3251** Suppose there are two processes A and B. A has a read lock and B has
3252** a reserved lock. B tries to promote to exclusive but is blocked because
3253** of A's read lock. A tries to promote to reserved but is blocked by B.
3254** One or the other of the two processes must give way or there can be
3255** no progress. By returning SQLITE_BUSY and not invoking the busy callback
3256** when A already has a read lock, we encourage A to give up and let B
3257** proceed.
drha059ad02001-04-17 20:09:11 +00003258*/
danielk1977aef0bf62005-12-30 16:28:01 +00003259int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
3260 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00003261 int rc = SQLITE_OK;
3262
drhd677b3d2007-08-20 22:48:41 +00003263 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003264 btreeIntegrity(p);
3265
danielk1977ee5741e2004-05-31 10:01:34 +00003266 /* If the btree is already in a write-transaction, or it
3267 ** is already in a read-transaction and a read-transaction
3268 ** is requested, this is a no-op.
3269 */
danielk1977aef0bf62005-12-30 16:28:01 +00003270 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00003271 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00003272 }
dan56c517a2013-09-26 11:04:33 +00003273 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
drhb8ef32c2005-03-14 02:01:49 +00003274
3275 /* Write transactions are not possible on a read-only database */
drhc9166342012-01-05 23:32:06 +00003276 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00003277 rc = SQLITE_READONLY;
3278 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00003279 }
3280
danielk1977404ca072009-03-16 13:19:36 +00003281#ifndef SQLITE_OMIT_SHARED_CACHE
drh5a1fb182016-01-08 19:34:39 +00003282 {
3283 sqlite3 *pBlock = 0;
3284 /* If another database handle has already opened a write transaction
3285 ** on this shared-btree structure and a second write transaction is
3286 ** requested, return SQLITE_LOCKED.
3287 */
3288 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
3289 || (pBt->btsFlags & BTS_PENDING)!=0
3290 ){
3291 pBlock = pBt->pWriter->db;
3292 }else if( wrflag>1 ){
3293 BtLock *pIter;
3294 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
3295 if( pIter->pBtree!=p ){
3296 pBlock = pIter->pBtree->db;
3297 break;
3298 }
danielk1977641b0f42007-12-21 04:47:25 +00003299 }
3300 }
drh5a1fb182016-01-08 19:34:39 +00003301 if( pBlock ){
3302 sqlite3ConnectionBlocked(p->db, pBlock);
3303 rc = SQLITE_LOCKED_SHAREDCACHE;
3304 goto trans_begun;
3305 }
danielk1977404ca072009-03-16 13:19:36 +00003306 }
danielk1977641b0f42007-12-21 04:47:25 +00003307#endif
3308
danielk1977602b4662009-07-02 07:47:33 +00003309 /* Any read-only or read-write transaction implies a read-lock on
3310 ** page 1. So if some other shared-cache client already has a write-lock
3311 ** on page 1, the transaction cannot be opened. */
drh4c301aa2009-07-15 17:25:45 +00003312 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
3313 if( SQLITE_OK!=rc ) goto trans_begun;
danielk1977602b4662009-07-02 07:47:33 +00003314
drhc9166342012-01-05 23:32:06 +00003315 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
3316 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
drhb8ef32c2005-03-14 02:01:49 +00003317 do {
danielk1977295dc102009-04-01 19:07:03 +00003318 /* Call lockBtree() until either pBt->pPage1 is populated or
3319 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
3320 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
3321 ** reading page 1 it discovers that the page-size of the database
3322 ** file is not pBt->pageSize. In this case lockBtree() will update
3323 ** pBt->pageSize to the page-size of the file on disk.
3324 */
3325 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
drh309169a2007-04-24 17:27:51 +00003326
drhb8ef32c2005-03-14 02:01:49 +00003327 if( rc==SQLITE_OK && wrflag ){
drhc9166342012-01-05 23:32:06 +00003328 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
drh309169a2007-04-24 17:27:51 +00003329 rc = SQLITE_READONLY;
3330 }else{
danielk1977d8293352009-04-30 09:10:37 +00003331 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
drh309169a2007-04-24 17:27:51 +00003332 if( rc==SQLITE_OK ){
3333 rc = newDatabase(pBt);
3334 }
drhb8ef32c2005-03-14 02:01:49 +00003335 }
3336 }
3337
danielk1977bd434552009-03-18 10:33:00 +00003338 if( rc!=SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00003339 unlockBtreeIfUnused(pBt);
3340 }
danf9b76712010-06-01 14:12:45 +00003341 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
danielk19771ceedd32008-11-19 10:22:33 +00003342 btreeInvokeBusyHandler(pBt) );
danielk1977aef0bf62005-12-30 16:28:01 +00003343
3344 if( rc==SQLITE_OK ){
3345 if( p->inTrans==TRANS_NONE ){
3346 pBt->nTransaction++;
danielk1977602b4662009-07-02 07:47:33 +00003347#ifndef SQLITE_OMIT_SHARED_CACHE
3348 if( p->sharable ){
drhf2f105d2012-08-20 15:53:54 +00003349 assert( p->lock.pBtree==p && p->lock.iTable==1 );
danielk1977602b4662009-07-02 07:47:33 +00003350 p->lock.eLock = READ_LOCK;
3351 p->lock.pNext = pBt->pLock;
3352 pBt->pLock = &p->lock;
3353 }
3354#endif
danielk1977aef0bf62005-12-30 16:28:01 +00003355 }
3356 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
3357 if( p->inTrans>pBt->inTransaction ){
3358 pBt->inTransaction = p->inTrans;
3359 }
danielk1977404ca072009-03-16 13:19:36 +00003360 if( wrflag ){
dan59257dc2010-08-04 11:34:31 +00003361 MemPage *pPage1 = pBt->pPage1;
3362#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977404ca072009-03-16 13:19:36 +00003363 assert( !pBt->pWriter );
3364 pBt->pWriter = p;
drhc9166342012-01-05 23:32:06 +00003365 pBt->btsFlags &= ~BTS_EXCLUSIVE;
3366 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
danielk1977641b0f42007-12-21 04:47:25 +00003367#endif
dan59257dc2010-08-04 11:34:31 +00003368
3369 /* If the db-size header field is incorrect (as it may be if an old
3370 ** client has been writing the database file), update it now. Doing
3371 ** this sooner rather than later means the database size can safely
3372 ** re-read the database size from page 1 if a savepoint or transaction
3373 ** rollback occurs within the transaction.
3374 */
3375 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
3376 rc = sqlite3PagerWrite(pPage1->pDbPage);
3377 if( rc==SQLITE_OK ){
3378 put4byte(&pPage1->aData[28], pBt->nPage);
3379 }
3380 }
3381 }
danielk1977aef0bf62005-12-30 16:28:01 +00003382 }
3383
drhd677b3d2007-08-20 22:48:41 +00003384
3385trans_begun:
danielk1977fd7f0452008-12-17 17:30:26 +00003386 if( rc==SQLITE_OK && wrflag ){
danielk197712dd5492008-12-18 15:45:07 +00003387 /* This call makes sure that the pager has the correct number of
3388 ** open savepoints. If the second parameter is greater than 0 and
3389 ** the sub-journal is not already open, then it will be opened here.
3390 */
danielk1977fd7f0452008-12-17 17:30:26 +00003391 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
3392 }
danielk197712dd5492008-12-18 15:45:07 +00003393
danielk1977aef0bf62005-12-30 16:28:01 +00003394 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00003395 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00003396 return rc;
drha059ad02001-04-17 20:09:11 +00003397}
3398
danielk1977687566d2004-11-02 12:56:41 +00003399#ifndef SQLITE_OMIT_AUTOVACUUM
3400
3401/*
3402** Set the pointer-map entries for all children of page pPage. Also, if
3403** pPage contains cells that point to overflow pages, set the pointer
3404** map entries for the overflow pages as well.
3405*/
3406static int setChildPtrmaps(MemPage *pPage){
3407 int i; /* Counter variable */
3408 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00003409 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00003410 BtShared *pBt = pPage->pBt;
danielk1977687566d2004-11-02 12:56:41 +00003411 Pgno pgno = pPage->pgno;
3412
drh1fee73e2007-08-29 04:00:57 +00003413 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh14e845a2017-05-25 21:35:56 +00003414 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
drh2a702542016-12-12 18:12:03 +00003415 if( rc!=SQLITE_OK ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00003416 nCell = pPage->nCell;
3417
3418 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00003419 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00003420
drh98add2e2009-07-20 17:11:49 +00003421 ptrmapPutOvflPtr(pPage, pCell, &rc);
danielk197726836652005-01-17 01:33:13 +00003422
danielk1977687566d2004-11-02 12:56:41 +00003423 if( !pPage->leaf ){
3424 Pgno childPgno = get4byte(pCell);
drh98add2e2009-07-20 17:11:49 +00003425 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00003426 }
3427 }
3428
3429 if( !pPage->leaf ){
3430 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh98add2e2009-07-20 17:11:49 +00003431 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00003432 }
3433
danielk1977687566d2004-11-02 12:56:41 +00003434 return rc;
3435}
3436
3437/*
drhf3aed592009-07-08 18:12:49 +00003438** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
3439** that it points to iTo. Parameter eType describes the type of pointer to
3440** be modified, as follows:
danielk1977687566d2004-11-02 12:56:41 +00003441**
3442** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
3443** page of pPage.
3444**
3445** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3446** page pointed to by one of the cells on pPage.
3447**
3448** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3449** overflow page in the list.
3450*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00003451static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00003452 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00003453 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977687566d2004-11-02 12:56:41 +00003454 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00003455 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00003456 if( get4byte(pPage->aData)!=iFrom ){
drhcc97ca42017-06-07 22:32:59 +00003457 return SQLITE_CORRUPT_PGNO(pPage->pgno);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003458 }
danielk1977f78fc082004-11-02 14:40:32 +00003459 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00003460 }else{
danielk1977687566d2004-11-02 12:56:41 +00003461 int i;
3462 int nCell;
drha1f75d92015-05-24 10:18:12 +00003463 int rc;
danielk1977687566d2004-11-02 12:56:41 +00003464
drh14e845a2017-05-25 21:35:56 +00003465 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
drha1f75d92015-05-24 10:18:12 +00003466 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00003467 nCell = pPage->nCell;
3468
danielk1977687566d2004-11-02 12:56:41 +00003469 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00003470 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00003471 if( eType==PTRMAP_OVERFLOW1 ){
3472 CellInfo info;
drh5fa60512015-06-19 17:19:34 +00003473 pPage->xParseCell(pPage, pCell, &info);
drhb701c9a2017-01-12 15:11:03 +00003474 if( info.nLocal<info.nPayload ){
3475 if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
drhcc97ca42017-06-07 22:32:59 +00003476 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drhb701c9a2017-01-12 15:11:03 +00003477 }
3478 if( iFrom==get4byte(pCell+info.nSize-4) ){
3479 put4byte(pCell+info.nSize-4, iTo);
3480 break;
3481 }
danielk1977687566d2004-11-02 12:56:41 +00003482 }
3483 }else{
3484 if( get4byte(pCell)==iFrom ){
3485 put4byte(pCell, iTo);
3486 break;
3487 }
3488 }
3489 }
3490
3491 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00003492 if( eType!=PTRMAP_BTREE ||
3493 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drhcc97ca42017-06-07 22:32:59 +00003494 return SQLITE_CORRUPT_PGNO(pPage->pgno);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003495 }
danielk1977687566d2004-11-02 12:56:41 +00003496 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3497 }
danielk1977687566d2004-11-02 12:56:41 +00003498 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00003499 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00003500}
3501
danielk1977003ba062004-11-04 02:57:33 +00003502
danielk19777701e812005-01-10 12:59:51 +00003503/*
3504** Move the open database page pDbPage to location iFreePage in the
3505** database. The pDbPage reference remains valid.
drhe64ca7b2009-07-16 18:21:17 +00003506**
3507** The isCommit flag indicates that there is no need to remember that
3508** the journal needs to be sync()ed before database page pDbPage->pgno
3509** can be written to. The caller has already promised not to write to that
3510** page.
danielk19777701e812005-01-10 12:59:51 +00003511*/
danielk1977003ba062004-11-04 02:57:33 +00003512static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00003513 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00003514 MemPage *pDbPage, /* Open page to move */
3515 u8 eType, /* Pointer map 'type' entry for pDbPage */
3516 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00003517 Pgno iFreePage, /* The location to move pDbPage to */
drhe64ca7b2009-07-16 18:21:17 +00003518 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
danielk1977003ba062004-11-04 02:57:33 +00003519){
3520 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
3521 Pgno iDbPage = pDbPage->pgno;
3522 Pager *pPager = pBt->pPager;
3523 int rc;
3524
danielk1977a0bf2652004-11-04 14:30:04 +00003525 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3526 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00003527 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00003528 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00003529
drh85b623f2007-12-13 21:54:09 +00003530 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00003531 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
3532 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00003533 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00003534 if( rc!=SQLITE_OK ){
3535 return rc;
3536 }
3537 pDbPage->pgno = iFreePage;
3538
3539 /* If pDbPage was a btree-page, then it may have child pages and/or cells
3540 ** that point to overflow pages. The pointer map entries for all these
3541 ** pages need to be changed.
3542 **
3543 ** If pDbPage is an overflow page, then the first 4 bytes may store a
3544 ** pointer to a subsequent overflow page. If this is the case, then
3545 ** the pointer map needs to be updated for the subsequent overflow page.
3546 */
danielk1977a0bf2652004-11-04 14:30:04 +00003547 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00003548 rc = setChildPtrmaps(pDbPage);
3549 if( rc!=SQLITE_OK ){
3550 return rc;
3551 }
3552 }else{
3553 Pgno nextOvfl = get4byte(pDbPage->aData);
3554 if( nextOvfl!=0 ){
drh98add2e2009-07-20 17:11:49 +00003555 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
danielk1977003ba062004-11-04 02:57:33 +00003556 if( rc!=SQLITE_OK ){
3557 return rc;
3558 }
3559 }
3560 }
3561
3562 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3563 ** that it points at iFreePage. Also fix the pointer map entry for
3564 ** iPtrPage.
3565 */
danielk1977a0bf2652004-11-04 14:30:04 +00003566 if( eType!=PTRMAP_ROOTPAGE ){
drhb00fc3b2013-08-21 23:42:32 +00003567 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00003568 if( rc!=SQLITE_OK ){
3569 return rc;
3570 }
danielk19773b8a05f2007-03-19 17:44:26 +00003571 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00003572 if( rc!=SQLITE_OK ){
3573 releasePage(pPtrPage);
3574 return rc;
3575 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00003576 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00003577 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003578 if( rc==SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00003579 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003580 }
danielk1977003ba062004-11-04 02:57:33 +00003581 }
danielk1977003ba062004-11-04 02:57:33 +00003582 return rc;
3583}
3584
danielk1977dddbcdc2007-04-26 14:42:34 +00003585/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00003586static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00003587
3588/*
dan51f0b6d2013-02-22 20:16:34 +00003589** Perform a single step of an incremental-vacuum. If successful, return
3590** SQLITE_OK. If there is no work to do (and therefore no point in
3591** calling this function again), return SQLITE_DONE. Or, if an error
3592** occurs, return some other error code.
danielk1977dddbcdc2007-04-26 14:42:34 +00003593**
peter.d.reid60ec9142014-09-06 16:39:46 +00003594** More specifically, this function attempts to re-organize the database so
dan51f0b6d2013-02-22 20:16:34 +00003595** that the last page of the file currently in use is no longer in use.
danielk1977dddbcdc2007-04-26 14:42:34 +00003596**
dan51f0b6d2013-02-22 20:16:34 +00003597** Parameter nFin is the number of pages that this database would contain
3598** were this function called until it returns SQLITE_DONE.
3599**
3600** If the bCommit parameter is non-zero, this function assumes that the
3601** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
peter.d.reid60ec9142014-09-06 16:39:46 +00003602** or an error. bCommit is passed true for an auto-vacuum-on-commit
dan51f0b6d2013-02-22 20:16:34 +00003603** operation, or false for an incremental vacuum.
danielk1977dddbcdc2007-04-26 14:42:34 +00003604*/
dan51f0b6d2013-02-22 20:16:34 +00003605static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
danielk1977dddbcdc2007-04-26 14:42:34 +00003606 Pgno nFreeList; /* Number of pages still on the free-list */
drhdd3cd972010-03-27 17:12:36 +00003607 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003608
drh1fee73e2007-08-29 04:00:57 +00003609 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977fa542f12009-04-02 18:28:08 +00003610 assert( iLastPg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00003611
3612 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003613 u8 eType;
3614 Pgno iPtrPage;
3615
3616 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977fa542f12009-04-02 18:28:08 +00003617 if( nFreeList==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003618 return SQLITE_DONE;
3619 }
3620
3621 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3622 if( rc!=SQLITE_OK ){
3623 return rc;
3624 }
3625 if( eType==PTRMAP_ROOTPAGE ){
3626 return SQLITE_CORRUPT_BKPT;
3627 }
3628
3629 if( eType==PTRMAP_FREEPAGE ){
dan51f0b6d2013-02-22 20:16:34 +00003630 if( bCommit==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003631 /* Remove the page from the files free-list. This is not required
dan51f0b6d2013-02-22 20:16:34 +00003632 ** if bCommit is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00003633 ** truncated to zero after this function returns, so it doesn't
3634 ** matter if it still contains some garbage entries.
3635 */
3636 Pgno iFreePg;
3637 MemPage *pFreePg;
dan51f0b6d2013-02-22 20:16:34 +00003638 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
danielk1977dddbcdc2007-04-26 14:42:34 +00003639 if( rc!=SQLITE_OK ){
3640 return rc;
3641 }
3642 assert( iFreePg==iLastPg );
3643 releasePage(pFreePg);
3644 }
3645 } else {
3646 Pgno iFreePg; /* Index of free page to move pLastPg to */
3647 MemPage *pLastPg;
dan51f0b6d2013-02-22 20:16:34 +00003648 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
3649 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
danielk1977dddbcdc2007-04-26 14:42:34 +00003650
drhb00fc3b2013-08-21 23:42:32 +00003651 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00003652 if( rc!=SQLITE_OK ){
3653 return rc;
3654 }
3655
dan51f0b6d2013-02-22 20:16:34 +00003656 /* If bCommit is zero, this loop runs exactly once and page pLastPg
danielk1977b4626a32007-04-28 15:47:43 +00003657 ** is swapped with the first free page pulled off the free list.
3658 **
dan51f0b6d2013-02-22 20:16:34 +00003659 ** On the other hand, if bCommit is greater than zero, then keep
danielk1977b4626a32007-04-28 15:47:43 +00003660 ** looping until a free-page located within the first nFin pages
3661 ** of the file is found.
3662 */
dan51f0b6d2013-02-22 20:16:34 +00003663 if( bCommit==0 ){
3664 eMode = BTALLOC_LE;
3665 iNear = nFin;
3666 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003667 do {
3668 MemPage *pFreePg;
dan51f0b6d2013-02-22 20:16:34 +00003669 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
danielk1977dddbcdc2007-04-26 14:42:34 +00003670 if( rc!=SQLITE_OK ){
3671 releasePage(pLastPg);
3672 return rc;
3673 }
3674 releasePage(pFreePg);
dan51f0b6d2013-02-22 20:16:34 +00003675 }while( bCommit && iFreePg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00003676 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00003677
dane1df4e32013-03-05 11:27:04 +00003678 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
danielk1977dddbcdc2007-04-26 14:42:34 +00003679 releasePage(pLastPg);
3680 if( rc!=SQLITE_OK ){
3681 return rc;
danielk1977662278e2007-11-05 15:30:12 +00003682 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003683 }
3684 }
3685
dan51f0b6d2013-02-22 20:16:34 +00003686 if( bCommit==0 ){
danbc1a3c62013-02-23 16:40:46 +00003687 do {
danielk19773460d192008-12-27 15:23:13 +00003688 iLastPg--;
danbc1a3c62013-02-23 16:40:46 +00003689 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
3690 pBt->bDoTruncate = 1;
drhdd3cd972010-03-27 17:12:36 +00003691 pBt->nPage = iLastPg;
danielk1977dddbcdc2007-04-26 14:42:34 +00003692 }
3693 return SQLITE_OK;
3694}
3695
3696/*
dan51f0b6d2013-02-22 20:16:34 +00003697** The database opened by the first argument is an auto-vacuum database
3698** nOrig pages in size containing nFree free pages. Return the expected
3699** size of the database in pages following an auto-vacuum operation.
3700*/
3701static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
3702 int nEntry; /* Number of entries on one ptrmap page */
3703 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
3704 Pgno nFin; /* Return value */
3705
3706 nEntry = pBt->usableSize/5;
3707 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
3708 nFin = nOrig - nFree - nPtrmap;
3709 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
3710 nFin--;
3711 }
3712 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3713 nFin--;
3714 }
dan51f0b6d2013-02-22 20:16:34 +00003715
3716 return nFin;
3717}
3718
3719/*
danielk1977dddbcdc2007-04-26 14:42:34 +00003720** A write-transaction must be opened before calling this function.
3721** It performs a single unit of work towards an incremental vacuum.
3722**
3723** If the incremental vacuum is finished after this function has run,
shanebe217792009-03-05 04:20:31 +00003724** SQLITE_DONE is returned. If it is not finished, but no error occurred,
danielk1977dddbcdc2007-04-26 14:42:34 +00003725** SQLITE_OK is returned. Otherwise an SQLite error code.
3726*/
3727int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00003728 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003729 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003730
3731 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00003732 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
3733 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00003734 rc = SQLITE_DONE;
3735 }else{
dan51f0b6d2013-02-22 20:16:34 +00003736 Pgno nOrig = btreePagecount(pBt);
3737 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
3738 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
3739
dan91384712013-02-24 11:50:43 +00003740 if( nOrig<nFin ){
3741 rc = SQLITE_CORRUPT_BKPT;
3742 }else if( nFree>0 ){
dan11dcd112013-03-15 18:29:18 +00003743 rc = saveAllCursors(pBt, 0, 0);
3744 if( rc==SQLITE_OK ){
3745 invalidateAllOverflowCache(pBt);
3746 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
3747 }
dan51f0b6d2013-02-22 20:16:34 +00003748 if( rc==SQLITE_OK ){
3749 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3750 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
3751 }
3752 }else{
3753 rc = SQLITE_DONE;
drhdd3cd972010-03-27 17:12:36 +00003754 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003755 }
drhd677b3d2007-08-20 22:48:41 +00003756 sqlite3BtreeLeave(p);
3757 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003758}
3759
3760/*
danielk19773b8a05f2007-03-19 17:44:26 +00003761** This routine is called prior to sqlite3PagerCommit when a transaction
drhf7b54962013-05-28 12:11:54 +00003762** is committed for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00003763**
3764** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
3765** the database file should be truncated to during the commit process.
3766** i.e. the database has been reorganized so that only the first *pnTrunc
3767** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00003768*/
danielk19773460d192008-12-27 15:23:13 +00003769static int autoVacuumCommit(BtShared *pBt){
danielk1977dddbcdc2007-04-26 14:42:34 +00003770 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00003771 Pager *pPager = pBt->pPager;
mistachkinc29cbb02015-07-02 16:52:01 +00003772 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
danielk1977687566d2004-11-02 12:56:41 +00003773
drh1fee73e2007-08-29 04:00:57 +00003774 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00003775 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00003776 assert(pBt->autoVacuum);
3777 if( !pBt->incrVacuum ){
drhea8ffdf2009-07-22 00:35:23 +00003778 Pgno nFin; /* Number of pages in database after autovacuuming */
3779 Pgno nFree; /* Number of pages on the freelist initially */
drh41d628c2009-07-11 17:04:08 +00003780 Pgno iFree; /* The next page to be freed */
drh41d628c2009-07-11 17:04:08 +00003781 Pgno nOrig; /* Database size before freeing */
danielk1977687566d2004-11-02 12:56:41 +00003782
drhb1299152010-03-30 22:58:33 +00003783 nOrig = btreePagecount(pBt);
danielk1977ef165ce2009-04-06 17:50:03 +00003784 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
3785 /* It is not possible to create a database for which the final page
3786 ** is either a pointer-map page or the pending-byte page. If one
3787 ** is encountered, this indicates corruption.
3788 */
danielk19773460d192008-12-27 15:23:13 +00003789 return SQLITE_CORRUPT_BKPT;
3790 }
danielk1977ef165ce2009-04-06 17:50:03 +00003791
danielk19773460d192008-12-27 15:23:13 +00003792 nFree = get4byte(&pBt->pPage1->aData[36]);
dan51f0b6d2013-02-22 20:16:34 +00003793 nFin = finalDbSize(pBt, nOrig, nFree);
drhc5e47ac2009-06-04 00:11:56 +00003794 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
dan0aed84d2013-03-26 14:16:20 +00003795 if( nFin<nOrig ){
3796 rc = saveAllCursors(pBt, 0, 0);
3797 }
danielk19773460d192008-12-27 15:23:13 +00003798 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
dan51f0b6d2013-02-22 20:16:34 +00003799 rc = incrVacuumStep(pBt, nFin, iFree, 1);
danielk1977dddbcdc2007-04-26 14:42:34 +00003800 }
danielk19773460d192008-12-27 15:23:13 +00003801 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
danielk19773460d192008-12-27 15:23:13 +00003802 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3803 put4byte(&pBt->pPage1->aData[32], 0);
3804 put4byte(&pBt->pPage1->aData[36], 0);
drhdd3cd972010-03-27 17:12:36 +00003805 put4byte(&pBt->pPage1->aData[28], nFin);
danbc1a3c62013-02-23 16:40:46 +00003806 pBt->bDoTruncate = 1;
drhdd3cd972010-03-27 17:12:36 +00003807 pBt->nPage = nFin;
danielk1977dddbcdc2007-04-26 14:42:34 +00003808 }
3809 if( rc!=SQLITE_OK ){
3810 sqlite3PagerRollback(pPager);
3811 }
danielk1977687566d2004-11-02 12:56:41 +00003812 }
3813
dan0aed84d2013-03-26 14:16:20 +00003814 assert( nRef>=sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00003815 return rc;
3816}
danielk1977dddbcdc2007-04-26 14:42:34 +00003817
danielk1977a50d9aa2009-06-08 14:49:45 +00003818#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
3819# define setChildPtrmaps(x) SQLITE_OK
3820#endif
danielk1977687566d2004-11-02 12:56:41 +00003821
3822/*
drh80e35f42007-03-30 14:06:34 +00003823** This routine does the first phase of a two-phase commit. This routine
3824** causes a rollback journal to be created (if it does not already exist)
3825** and populated with enough information so that if a power loss occurs
3826** the database can be restored to its original state by playing back
3827** the journal. Then the contents of the journal are flushed out to
3828** the disk. After the journal is safely on oxide, the changes to the
3829** database are written into the database file and flushed to oxide.
3830** At the end of this call, the rollback journal still exists on the
3831** disk and we are still holding all locks, so the transaction has not
drh51898cf2009-04-19 20:51:06 +00003832** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
drh80e35f42007-03-30 14:06:34 +00003833** commit process.
3834**
3835** This call is a no-op if no write-transaction is currently active on pBt.
3836**
3837** Otherwise, sync the database file for the btree pBt. zMaster points to
3838** the name of a master journal file that should be written into the
3839** individual journal file, or is NULL, indicating no master journal file
3840** (single database transaction).
3841**
3842** When this is called, the master journal should already have been
3843** created, populated with this journal pointer and synced to disk.
3844**
3845** Once this is routine has returned, the only thing required to commit
3846** the write-transaction for this database file is to delete the journal.
3847*/
3848int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
3849 int rc = SQLITE_OK;
3850 if( p->inTrans==TRANS_WRITE ){
3851 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003852 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00003853#ifndef SQLITE_OMIT_AUTOVACUUM
3854 if( pBt->autoVacuum ){
danielk19773460d192008-12-27 15:23:13 +00003855 rc = autoVacuumCommit(pBt);
drh80e35f42007-03-30 14:06:34 +00003856 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00003857 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003858 return rc;
3859 }
3860 }
danbc1a3c62013-02-23 16:40:46 +00003861 if( pBt->bDoTruncate ){
3862 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
3863 }
drh80e35f42007-03-30 14:06:34 +00003864#endif
drh49b9d332009-01-02 18:10:42 +00003865 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
drhd677b3d2007-08-20 22:48:41 +00003866 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003867 }
3868 return rc;
3869}
3870
3871/*
danielk197794b30732009-07-02 17:21:57 +00003872** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
3873** at the conclusion of a transaction.
3874*/
3875static void btreeEndTransaction(Btree *p){
3876 BtShared *pBt = p->pBt;
drh1713afb2013-06-28 01:24:57 +00003877 sqlite3 *db = p->db;
danielk197794b30732009-07-02 17:21:57 +00003878 assert( sqlite3BtreeHoldsMutex(p) );
3879
danbc1a3c62013-02-23 16:40:46 +00003880#ifndef SQLITE_OMIT_AUTOVACUUM
3881 pBt->bDoTruncate = 0;
3882#endif
danc0537fe2013-06-28 19:41:43 +00003883 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
danfa401de2009-10-16 14:55:03 +00003884 /* If there are other active statements that belong to this database
3885 ** handle, downgrade to a read-only transaction. The other statements
3886 ** may still be reading from the database. */
danielk197794b30732009-07-02 17:21:57 +00003887 downgradeAllSharedCacheTableLocks(p);
3888 p->inTrans = TRANS_READ;
3889 }else{
3890 /* If the handle had any kind of transaction open, decrement the
3891 ** transaction count of the shared btree. If the transaction count
3892 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
3893 ** call below will unlock the pager. */
3894 if( p->inTrans!=TRANS_NONE ){
3895 clearAllSharedCacheTableLocks(p);
3896 pBt->nTransaction--;
3897 if( 0==pBt->nTransaction ){
3898 pBt->inTransaction = TRANS_NONE;
3899 }
3900 }
3901
3902 /* Set the current transaction state to TRANS_NONE and unlock the
3903 ** pager if this call closed the only read or write transaction. */
3904 p->inTrans = TRANS_NONE;
3905 unlockBtreeIfUnused(pBt);
3906 }
3907
3908 btreeIntegrity(p);
3909}
3910
3911/*
drh2aa679f2001-06-25 02:11:07 +00003912** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00003913**
drh6e345992007-03-30 11:12:08 +00003914** This routine implements the second phase of a 2-phase commit. The
drh51898cf2009-04-19 20:51:06 +00003915** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
3916** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
3917** routine did all the work of writing information out to disk and flushing the
drh6e345992007-03-30 11:12:08 +00003918** contents so that they are written onto the disk platter. All this
drh51898cf2009-04-19 20:51:06 +00003919** routine has to do is delete or truncate or zero the header in the
3920** the rollback journal (which causes the transaction to commit) and
3921** drop locks.
drh6e345992007-03-30 11:12:08 +00003922**
dan60939d02011-03-29 15:40:55 +00003923** Normally, if an error occurs while the pager layer is attempting to
3924** finalize the underlying journal file, this function returns an error and
3925** the upper layer will attempt a rollback. However, if the second argument
3926** is non-zero then this b-tree transaction is part of a multi-file
3927** transaction. In this case, the transaction has already been committed
3928** (by deleting a master journal file) and the caller will ignore this
3929** functions return code. So, even if an error occurs in the pager layer,
3930** reset the b-tree objects internal state to indicate that the write
3931** transaction has been closed. This is quite safe, as the pager will have
3932** transitioned to the error state.
3933**
drh5e00f6c2001-09-13 13:46:56 +00003934** This will release the write lock on the database file. If there
3935** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00003936*/
dan60939d02011-03-29 15:40:55 +00003937int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
danielk1977aef0bf62005-12-30 16:28:01 +00003938
drh075ed302010-10-14 01:17:30 +00003939 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003940 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003941 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003942
3943 /* If the handle has a write-transaction open, commit the shared-btrees
3944 ** transaction and set the shared state to TRANS_READ.
3945 */
3946 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00003947 int rc;
drh075ed302010-10-14 01:17:30 +00003948 BtShared *pBt = p->pBt;
danielk1977aef0bf62005-12-30 16:28:01 +00003949 assert( pBt->inTransaction==TRANS_WRITE );
3950 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00003951 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
dan60939d02011-03-29 15:40:55 +00003952 if( rc!=SQLITE_OK && bCleanup==0 ){
drhd677b3d2007-08-20 22:48:41 +00003953 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00003954 return rc;
3955 }
drh3da9c042014-12-22 18:41:21 +00003956 p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
danielk1977aef0bf62005-12-30 16:28:01 +00003957 pBt->inTransaction = TRANS_READ;
danbf0e57a2013-05-14 20:36:31 +00003958 btreeClearHasContent(pBt);
danielk1977ee5741e2004-05-31 10:01:34 +00003959 }
danielk1977aef0bf62005-12-30 16:28:01 +00003960
danielk197794b30732009-07-02 17:21:57 +00003961 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00003962 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00003963 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003964}
3965
drh80e35f42007-03-30 14:06:34 +00003966/*
3967** Do both phases of a commit.
3968*/
3969int sqlite3BtreeCommit(Btree *p){
3970 int rc;
drhd677b3d2007-08-20 22:48:41 +00003971 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00003972 rc = sqlite3BtreeCommitPhaseOne(p, 0);
3973 if( rc==SQLITE_OK ){
dan60939d02011-03-29 15:40:55 +00003974 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
drh80e35f42007-03-30 14:06:34 +00003975 }
drhd677b3d2007-08-20 22:48:41 +00003976 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003977 return rc;
3978}
3979
drhc39e0002004-05-07 23:50:57 +00003980/*
drhfb982642007-08-30 01:19:59 +00003981** This routine sets the state to CURSOR_FAULT and the error
drh47b7fc72014-11-11 01:33:57 +00003982** code to errCode for every cursor on any BtShared that pBtree
3983** references. Or if the writeOnly flag is set to 1, then only
3984** trip write cursors and leave read cursors unchanged.
drhfb982642007-08-30 01:19:59 +00003985**
drh47b7fc72014-11-11 01:33:57 +00003986** Every cursor is a candidate to be tripped, including cursors
3987** that belong to other database connections that happen to be
3988** sharing the cache with pBtree.
drhfb982642007-08-30 01:19:59 +00003989**
dan80231042014-11-12 14:56:02 +00003990** This routine gets called when a rollback occurs. If the writeOnly
3991** flag is true, then only write-cursors need be tripped - read-only
3992** cursors save their current positions so that they may continue
3993** following the rollback. Or, if writeOnly is false, all cursors are
3994** tripped. In general, writeOnly is false if the transaction being
3995** rolled back modified the database schema. In this case b-tree root
3996** pages may be moved or deleted from the database altogether, making
3997** it unsafe for read cursors to continue.
3998**
3999** If the writeOnly flag is true and an error is encountered while
4000** saving the current position of a read-only cursor, all cursors,
4001** including all read-cursors are tripped.
4002**
4003** SQLITE_OK is returned if successful, or if an error occurs while
4004** saving a cursor position, an SQLite error code.
drhfb982642007-08-30 01:19:59 +00004005*/
dan80231042014-11-12 14:56:02 +00004006int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
drhfb982642007-08-30 01:19:59 +00004007 BtCursor *p;
dan80231042014-11-12 14:56:02 +00004008 int rc = SQLITE_OK;
4009
drh47b7fc72014-11-11 01:33:57 +00004010 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
dan80231042014-11-12 14:56:02 +00004011 if( pBtree ){
4012 sqlite3BtreeEnter(pBtree);
4013 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
dan80231042014-11-12 14:56:02 +00004014 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
drhd2f83132015-03-25 17:35:01 +00004015 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
drhbea3b972014-11-18 20:22:05 +00004016 rc = saveCursorPosition(p);
dan80231042014-11-12 14:56:02 +00004017 if( rc!=SQLITE_OK ){
4018 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
4019 break;
4020 }
4021 }
4022 }else{
4023 sqlite3BtreeClearCursor(p);
4024 p->eState = CURSOR_FAULT;
4025 p->skipNext = errCode;
4026 }
drh85ef6302017-08-02 15:50:09 +00004027 btreeReleaseAllCursorPages(p);
danielk1977bc2ca9e2008-11-13 14:28:28 +00004028 }
dan80231042014-11-12 14:56:02 +00004029 sqlite3BtreeLeave(pBtree);
drhfb982642007-08-30 01:19:59 +00004030 }
dan80231042014-11-12 14:56:02 +00004031 return rc;
drhfb982642007-08-30 01:19:59 +00004032}
4033
4034/*
drh47b7fc72014-11-11 01:33:57 +00004035** Rollback the transaction in progress.
4036**
4037** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
4038** Only write cursors are tripped if writeOnly is true but all cursors are
4039** tripped if writeOnly is false. Any attempt to use
4040** a tripped cursor will result in an error.
drh5e00f6c2001-09-13 13:46:56 +00004041**
4042** This will release the write lock on the database file. If there
4043** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00004044*/
drh47b7fc72014-11-11 01:33:57 +00004045int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
danielk19778d34dfd2006-01-24 16:37:57 +00004046 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00004047 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00004048 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00004049
drh47b7fc72014-11-11 01:33:57 +00004050 assert( writeOnly==1 || writeOnly==0 );
4051 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
drhd677b3d2007-08-20 22:48:41 +00004052 sqlite3BtreeEnter(p);
drh0f198a72012-02-13 16:43:16 +00004053 if( tripCode==SQLITE_OK ){
4054 rc = tripCode = saveAllCursors(pBt, 0, 0);
drh47b7fc72014-11-11 01:33:57 +00004055 if( rc ) writeOnly = 0;
drh0f198a72012-02-13 16:43:16 +00004056 }else{
4057 rc = SQLITE_OK;
danielk19772b8c13e2006-01-24 14:21:24 +00004058 }
drh0f198a72012-02-13 16:43:16 +00004059 if( tripCode ){
dan80231042014-11-12 14:56:02 +00004060 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
4061 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4062 if( rc2!=SQLITE_OK ) rc = rc2;
drh0f198a72012-02-13 16:43:16 +00004063 }
danielk1977aef0bf62005-12-30 16:28:01 +00004064 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00004065
4066 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00004067 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00004068
danielk19778d34dfd2006-01-24 16:37:57 +00004069 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00004070 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00004071 if( rc2!=SQLITE_OK ){
4072 rc = rc2;
4073 }
4074
drh24cd67e2004-05-10 16:18:47 +00004075 /* The rollback may have destroyed the pPage1->aData value. So
danielk197730548662009-07-09 05:07:37 +00004076 ** call btreeGetPage() on page 1 again to make
drh16a9b832007-05-05 18:39:25 +00004077 ** sure pPage1->aData is set correctly. */
drhb00fc3b2013-08-21 23:42:32 +00004078 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh1f5b4672010-04-01 02:22:19 +00004079 int nPage = get4byte(28+(u8*)pPage1->aData);
4080 testcase( nPage==0 );
4081 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
4082 testcase( pBt->nPage!=nPage );
4083 pBt->nPage = nPage;
drh3908fe92017-09-01 14:50:19 +00004084 releasePageOne(pPage1);
drh24cd67e2004-05-10 16:18:47 +00004085 }
drh85ec3b62013-05-14 23:12:06 +00004086 assert( countValidCursors(pBt, 1)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00004087 pBt->inTransaction = TRANS_READ;
danbf0e57a2013-05-14 20:36:31 +00004088 btreeClearHasContent(pBt);
drh24cd67e2004-05-10 16:18:47 +00004089 }
danielk1977aef0bf62005-12-30 16:28:01 +00004090
danielk197794b30732009-07-02 17:21:57 +00004091 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00004092 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00004093 return rc;
4094}
4095
4096/*
peter.d.reid60ec9142014-09-06 16:39:46 +00004097** Start a statement subtransaction. The subtransaction can be rolled
danielk1977bd434552009-03-18 10:33:00 +00004098** back independently of the main transaction. You must start a transaction
4099** before starting a subtransaction. The subtransaction is ended automatically
4100** if the main transaction commits or rolls back.
drhab01f612004-05-22 02:55:23 +00004101**
4102** Statement subtransactions are used around individual SQL statements
4103** that are contained within a BEGIN...COMMIT block. If a constraint
4104** error occurs within the statement, the effect of that one statement
4105** can be rolled back without having to rollback the entire transaction.
danielk1977bd434552009-03-18 10:33:00 +00004106**
4107** A statement sub-transaction is implemented as an anonymous savepoint. The
4108** value passed as the second parameter is the total number of savepoints,
4109** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4110** are no active savepoints and no other statement-transactions open,
4111** iStatement is 1. This anonymous savepoint can be released or rolled back
4112** using the sqlite3BtreeSavepoint() function.
drh663fc632002-02-02 18:49:19 +00004113*/
danielk1977bd434552009-03-18 10:33:00 +00004114int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
drh663fc632002-02-02 18:49:19 +00004115 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00004116 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00004117 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00004118 assert( p->inTrans==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00004119 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk1977bd434552009-03-18 10:33:00 +00004120 assert( iStatement>0 );
4121 assert( iStatement>p->db->nSavepoint );
drh5e0ccc22010-03-29 19:36:52 +00004122 assert( pBt->inTransaction==TRANS_WRITE );
4123 /* At the pager level, a statement transaction is a savepoint with
4124 ** an index greater than all savepoints created explicitly using
4125 ** SQL statements. It is illegal to open, release or rollback any
4126 ** such savepoints while the statement transaction savepoint is active.
4127 */
4128 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
drhd677b3d2007-08-20 22:48:41 +00004129 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00004130 return rc;
4131}
4132
4133/*
danielk1977fd7f0452008-12-17 17:30:26 +00004134** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4135** or SAVEPOINT_RELEASE. This function either releases or rolls back the
danielk197712dd5492008-12-18 15:45:07 +00004136** savepoint identified by parameter iSavepoint, depending on the value
4137** of op.
4138**
4139** Normally, iSavepoint is greater than or equal to zero. However, if op is
4140** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4141** contents of the entire transaction are rolled back. This is different
4142** from a normal transaction rollback, as no locks are released and the
4143** transaction remains open.
danielk1977fd7f0452008-12-17 17:30:26 +00004144*/
4145int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4146 int rc = SQLITE_OK;
4147 if( p && p->inTrans==TRANS_WRITE ){
4148 BtShared *pBt = p->pBt;
danielk1977fd7f0452008-12-17 17:30:26 +00004149 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4150 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4151 sqlite3BtreeEnter(p);
drh2343c7e2017-02-02 00:46:55 +00004152 if( op==SAVEPOINT_ROLLBACK ){
4153 rc = saveAllCursors(pBt, 0, 0);
4154 }
4155 if( rc==SQLITE_OK ){
4156 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4157 }
drh9f0bbf92009-01-02 21:08:09 +00004158 if( rc==SQLITE_OK ){
drhc9166342012-01-05 23:32:06 +00004159 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4160 pBt->nPage = 0;
4161 }
drh9f0bbf92009-01-02 21:08:09 +00004162 rc = newDatabase(pBt);
drhdd3cd972010-03-27 17:12:36 +00004163 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
drhb9b49bf2010-08-05 03:21:39 +00004164
4165 /* The database size was written into the offset 28 of the header
4166 ** when the transaction started, so we know that the value at offset
4167 ** 28 is nonzero. */
4168 assert( pBt->nPage>0 );
drh9f0bbf92009-01-02 21:08:09 +00004169 }
danielk1977fd7f0452008-12-17 17:30:26 +00004170 sqlite3BtreeLeave(p);
4171 }
4172 return rc;
4173}
4174
4175/*
drh8b2f49b2001-06-08 00:21:52 +00004176** Create a new cursor for the BTree whose root is on the page
danielk19773e8add92009-07-04 17:16:00 +00004177** iTable. If a read-only cursor is requested, it is assumed that
4178** the caller already has at least a read-only transaction open
4179** on the database already. If a write-cursor is requested, then
4180** the caller is assumed to have an open write transaction.
drh1bee3d72001-10-15 00:44:35 +00004181**
drhe807bdb2016-01-21 17:06:33 +00004182** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4183** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
4184** can be used for reading or for writing if other conditions for writing
4185** are also met. These are the conditions that must be met in order
4186** for writing to be allowed:
drh6446c4d2001-12-15 14:22:18 +00004187**
drhe807bdb2016-01-21 17:06:33 +00004188** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
drhf74b8d92002-09-01 23:20:45 +00004189**
drhfe5d71d2007-03-19 11:54:10 +00004190** 2: Other database connections that share the same pager cache
4191** but which are not in the READ_UNCOMMITTED state may not have
4192** cursors open with wrFlag==0 on the same table. Otherwise
4193** the changes made by this write cursor would be visible to
4194** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00004195**
4196** 3: The database must be writable (not on read-only media)
4197**
4198** 4: There must be an active transaction.
4199**
drhe807bdb2016-01-21 17:06:33 +00004200** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4201** is set. If FORDELETE is set, that is a hint to the implementation that
4202** this cursor will only be used to seek to and delete entries of an index
4203** as part of a larger DELETE statement. The FORDELETE hint is not used by
4204** this implementation. But in a hypothetical alternative storage engine
4205** in which index entries are automatically deleted when corresponding table
4206** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4207** operations on this cursor can be no-ops and all READ operations can
4208** return a null row (2-bytes: 0x01 0x00).
4209**
drh6446c4d2001-12-15 14:22:18 +00004210** No checking is done to make sure that page iTable really is the
4211** root page of a b-tree. If it is not, then the cursor acquired
4212** will not work correctly.
danielk197771d5d2c2008-09-29 11:49:47 +00004213**
drhf25a5072009-11-18 23:01:25 +00004214** It is assumed that the sqlite3BtreeCursorZero() has been called
4215** on pCur to initialize the memory space prior to invoking this routine.
drha059ad02001-04-17 20:09:11 +00004216*/
drhd677b3d2007-08-20 22:48:41 +00004217static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00004218 Btree *p, /* The btree */
4219 int iTable, /* Root page of table to open */
4220 int wrFlag, /* 1 to write. 0 read-only */
4221 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4222 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00004223){
danielk19773e8add92009-07-04 17:16:00 +00004224 BtShared *pBt = p->pBt; /* Shared b-tree handle */
drh27fb7462015-06-30 02:47:36 +00004225 BtCursor *pX; /* Looping over other all cursors */
drhecdc7532001-09-23 02:35:53 +00004226
drh1fee73e2007-08-29 04:00:57 +00004227 assert( sqlite3BtreeHoldsMutex(p) );
danfd261ec2015-10-22 20:54:33 +00004228 assert( wrFlag==0
4229 || wrFlag==BTREE_WRCSR
4230 || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4231 );
danielk197796d48e92009-06-29 06:00:37 +00004232
danielk1977602b4662009-07-02 07:47:33 +00004233 /* The following assert statements verify that if this is a sharable
4234 ** b-tree database, the connection is holding the required table locks,
4235 ** and that no other connection has any open cursor that conflicts with
4236 ** this lock. */
danfd261ec2015-10-22 20:54:33 +00004237 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
danielk197796d48e92009-06-29 06:00:37 +00004238 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
4239
danielk19773e8add92009-07-04 17:16:00 +00004240 /* Assert that the caller has opened the required transaction. */
4241 assert( p->inTrans>TRANS_NONE );
4242 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
4243 assert( pBt->pPage1 && pBt->pPage1->aData );
drh98ef0f62015-06-30 01:25:52 +00004244 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk19773e8add92009-07-04 17:16:00 +00004245
drh3fbb0222014-09-24 19:47:27 +00004246 if( wrFlag ){
4247 allocateTempSpace(pBt);
mistachkinfad30392016-02-13 23:43:46 +00004248 if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
drha0c9a112004-03-10 13:42:37 +00004249 }
drhb1299152010-03-30 22:58:33 +00004250 if( iTable==1 && btreePagecount(pBt)==0 ){
dana205a482011-08-27 18:48:57 +00004251 assert( wrFlag==0 );
4252 iTable = 0;
danielk19773e8add92009-07-04 17:16:00 +00004253 }
danielk1977aef0bf62005-12-30 16:28:01 +00004254
danielk1977aef0bf62005-12-30 16:28:01 +00004255 /* Now that no other errors can occur, finish filling in the BtCursor
danielk19773e8add92009-07-04 17:16:00 +00004256 ** variables and link the cursor into the BtShared list. */
danielk1977172114a2009-07-07 15:47:12 +00004257 pCur->pgnoRoot = (Pgno)iTable;
4258 pCur->iPage = -1;
drh1e968a02008-03-25 00:22:21 +00004259 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00004260 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00004261 pCur->pBt = pBt;
danfd261ec2015-10-22 20:54:33 +00004262 pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
drh28f58dd2015-06-27 19:45:03 +00004263 pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
drh27fb7462015-06-30 02:47:36 +00004264 /* If there are two or more cursors on the same btree, then all such
4265 ** cursors *must* have the BTCF_Multiple flag set. */
4266 for(pX=pBt->pCursor; pX; pX=pX->pNext){
4267 if( pX->pgnoRoot==(Pgno)iTable ){
4268 pX->curFlags |= BTCF_Multiple;
4269 pCur->curFlags |= BTCF_Multiple;
4270 }
drha059ad02001-04-17 20:09:11 +00004271 }
drh27fb7462015-06-30 02:47:36 +00004272 pCur->pNext = pBt->pCursor;
drha059ad02001-04-17 20:09:11 +00004273 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00004274 pCur->eState = CURSOR_INVALID;
danielk1977aef0bf62005-12-30 16:28:01 +00004275 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00004276}
drhd677b3d2007-08-20 22:48:41 +00004277int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00004278 Btree *p, /* The btree */
4279 int iTable, /* Root page of table to open */
4280 int wrFlag, /* 1 to write. 0 read-only */
4281 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
4282 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00004283){
4284 int rc;
dan08f901b2015-05-25 19:24:36 +00004285 if( iTable<1 ){
4286 rc = SQLITE_CORRUPT_BKPT;
4287 }else{
4288 sqlite3BtreeEnter(p);
4289 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4290 sqlite3BtreeLeave(p);
4291 }
drhd677b3d2007-08-20 22:48:41 +00004292 return rc;
4293}
drh7f751222009-03-17 22:33:00 +00004294
4295/*
4296** Return the size of a BtCursor object in bytes.
4297**
4298** This interfaces is needed so that users of cursors can preallocate
4299** sufficient storage to hold a cursor. The BtCursor object is opaque
4300** to users so they cannot do the sizeof() themselves - they must call
4301** this routine.
4302*/
4303int sqlite3BtreeCursorSize(void){
drhc54055b2009-11-13 17:05:53 +00004304 return ROUND8(sizeof(BtCursor));
danielk1977cd3e8f72008-03-25 09:47:35 +00004305}
4306
drh7f751222009-03-17 22:33:00 +00004307/*
drhf25a5072009-11-18 23:01:25 +00004308** Initialize memory that will be converted into a BtCursor object.
4309**
4310** The simple approach here would be to memset() the entire object
4311** to zero. But it turns out that the apPage[] and aiIdx[] arrays
4312** do not need to be zeroed and they are large, so we can save a lot
4313** of run-time by skipping the initialization of those elements.
4314*/
4315void sqlite3BtreeCursorZero(BtCursor *p){
4316 memset(p, 0, offsetof(BtCursor, iPage));
4317}
4318
4319/*
drh5e00f6c2001-09-13 13:46:56 +00004320** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00004321** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00004322*/
drh3aac2dd2004-04-26 14:10:20 +00004323int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00004324 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00004325 if( pBtree ){
4326 BtShared *pBt = pCur->pBt;
4327 sqlite3BtreeEnter(pBtree);
drh27fb7462015-06-30 02:47:36 +00004328 assert( pBt->pCursor!=0 );
4329 if( pBt->pCursor==pCur ){
danielk1977cd3e8f72008-03-25 09:47:35 +00004330 pBt->pCursor = pCur->pNext;
drh27fb7462015-06-30 02:47:36 +00004331 }else{
4332 BtCursor *pPrev = pBt->pCursor;
4333 do{
4334 if( pPrev->pNext==pCur ){
4335 pPrev->pNext = pCur->pNext;
4336 break;
4337 }
4338 pPrev = pPrev->pNext;
4339 }while( ALWAYS(pPrev) );
danielk1977cd3e8f72008-03-25 09:47:35 +00004340 }
drh352a35a2017-08-15 03:46:47 +00004341 btreeReleaseAllCursorPages(pCur);
danielk1977cd3e8f72008-03-25 09:47:35 +00004342 unlockBtreeIfUnused(pBt);
dan85753662014-12-11 16:38:18 +00004343 sqlite3_free(pCur->aOverflow);
drhf38dd3b2017-08-14 23:53:02 +00004344 sqlite3_free(pCur->pKey);
danielk1977cd3e8f72008-03-25 09:47:35 +00004345 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00004346 }
drh8c42ca92001-06-22 19:15:00 +00004347 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00004348}
4349
drh5e2f8b92001-05-28 00:41:15 +00004350/*
drh86057612007-06-26 01:04:48 +00004351** Make sure the BtCursor* given in the argument has a valid
4352** BtCursor.info structure. If it is not already valid, call
danielk197730548662009-07-09 05:07:37 +00004353** btreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00004354**
4355** BtCursor.info is a cache of the information in the current cell.
danielk197730548662009-07-09 05:07:37 +00004356** Using this cache reduces the number of calls to btreeParseCell().
drh9188b382004-05-14 21:12:22 +00004357*/
drh9188b382004-05-14 21:12:22 +00004358#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00004359 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00004360 CellInfo info;
drh51c6d962004-06-06 00:42:25 +00004361 memset(&info, 0, sizeof(info));
drh352a35a2017-08-15 03:46:47 +00004362 btreeParseCell(pCur->pPage, pCur->ix, &info);
dan7df42ab2014-01-20 18:25:44 +00004363 assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00004364 }
danielk19771cc5ed82007-05-16 17:28:43 +00004365#else
4366 #define assertCellInfo(x)
4367#endif
drhc5b41ac2015-06-17 02:11:46 +00004368static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
4369 if( pCur->info.nSize==0 ){
drhc5b41ac2015-06-17 02:11:46 +00004370 pCur->curFlags |= BTCF_ValidNKey;
drh352a35a2017-08-15 03:46:47 +00004371 btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
drhc5b41ac2015-06-17 02:11:46 +00004372 }else{
4373 assertCellInfo(pCur);
drh86057612007-06-26 01:04:48 +00004374 }
drhc5b41ac2015-06-17 02:11:46 +00004375}
drh9188b382004-05-14 21:12:22 +00004376
drhea8ffdf2009-07-22 00:35:23 +00004377#ifndef NDEBUG /* The next routine used only within assert() statements */
4378/*
4379** Return true if the given BtCursor is valid. A valid cursor is one
4380** that is currently pointing to a row in a (non-empty) table.
4381** This is a verification routine is used only within assert() statements.
4382*/
4383int sqlite3BtreeCursorIsValid(BtCursor *pCur){
4384 return pCur && pCur->eState==CURSOR_VALID;
4385}
4386#endif /* NDEBUG */
drhd6ef5af2016-11-15 04:00:24 +00004387int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
4388 assert( pCur!=0 );
4389 return pCur->eState==CURSOR_VALID;
4390}
drhea8ffdf2009-07-22 00:35:23 +00004391
drh9188b382004-05-14 21:12:22 +00004392/*
drha7c90c42016-06-04 20:37:10 +00004393** Return the value of the integer key or "rowid" for a table btree.
4394** This routine is only valid for a cursor that is pointing into a
4395** ordinary table btree. If the cursor points to an index btree or
4396** is invalid, the result of this routine is undefined.
drh7e3b0a02001-04-28 16:52:40 +00004397*/
drha7c90c42016-06-04 20:37:10 +00004398i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00004399 assert( cursorHoldsMutex(pCur) );
drhc5352b92014-11-17 20:33:07 +00004400 assert( pCur->eState==CURSOR_VALID );
drha7c90c42016-06-04 20:37:10 +00004401 assert( pCur->curIntKey );
drhc5352b92014-11-17 20:33:07 +00004402 getCellInfo(pCur);
drha7c90c42016-06-04 20:37:10 +00004403 return pCur->info.nKey;
drha059ad02001-04-17 20:09:11 +00004404}
drh2af926b2001-05-15 00:39:25 +00004405
drh72f82862001-05-24 21:06:34 +00004406/*
drha7c90c42016-06-04 20:37:10 +00004407** Return the number of bytes of payload for the entry that pCur is
4408** currently pointing to. For table btrees, this will be the amount
4409** of data. For index btrees, this will be the size of the key.
drhea8ffdf2009-07-22 00:35:23 +00004410**
4411** The caller must guarantee that the cursor is pointing to a non-NULL
4412** valid entry. In other words, the calling procedure must guarantee
4413** that the cursor has Cursor.eState==CURSOR_VALID.
drh0e1c19e2004-05-11 00:58:56 +00004414*/
drha7c90c42016-06-04 20:37:10 +00004415u32 sqlite3BtreePayloadSize(BtCursor *pCur){
4416 assert( cursorHoldsMutex(pCur) );
drhea8ffdf2009-07-22 00:35:23 +00004417 assert( pCur->eState==CURSOR_VALID );
4418 getCellInfo(pCur);
drha7c90c42016-06-04 20:37:10 +00004419 return pCur->info.nPayload;
drh0e1c19e2004-05-11 00:58:56 +00004420}
4421
4422/*
danielk1977d04417962007-05-02 13:16:30 +00004423** Given the page number of an overflow page in the database (parameter
4424** ovfl), this function finds the page number of the next page in the
4425** linked list of overflow pages. If possible, it uses the auto-vacuum
4426** pointer-map data instead of reading the content of page ovfl to do so.
4427**
4428** If an error occurs an SQLite error code is returned. Otherwise:
4429**
danielk1977bea2a942009-01-20 17:06:27 +00004430** The page number of the next overflow page in the linked list is
4431** written to *pPgnoNext. If page ovfl is the last page in its linked
4432** list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00004433**
danielk1977bea2a942009-01-20 17:06:27 +00004434** If ppPage is not NULL, and a reference to the MemPage object corresponding
4435** to page number pOvfl was obtained, then *ppPage is set to point to that
4436** reference. It is the responsibility of the caller to call releasePage()
4437** on *ppPage to free the reference. In no reference was obtained (because
4438** the pointer-map was used to obtain the value for *pPgnoNext), then
4439** *ppPage is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00004440*/
4441static int getOverflowPage(
drhfa3be902009-07-07 02:44:07 +00004442 BtShared *pBt, /* The database file */
4443 Pgno ovfl, /* Current overflow page number */
danielk1977bea2a942009-01-20 17:06:27 +00004444 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
danielk1977d04417962007-05-02 13:16:30 +00004445 Pgno *pPgnoNext /* OUT: Next overflow page number */
4446){
4447 Pgno next = 0;
danielk1977bea2a942009-01-20 17:06:27 +00004448 MemPage *pPage = 0;
drh1bd10f82008-12-10 21:19:56 +00004449 int rc = SQLITE_OK;
danielk1977d04417962007-05-02 13:16:30 +00004450
drh1fee73e2007-08-29 04:00:57 +00004451 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bea2a942009-01-20 17:06:27 +00004452 assert(pPgnoNext);
danielk1977d04417962007-05-02 13:16:30 +00004453
4454#ifndef SQLITE_OMIT_AUTOVACUUM
4455 /* Try to find the next page in the overflow list using the
4456 ** autovacuum pointer-map pages. Guess that the next page in
4457 ** the overflow list is page number (ovfl+1). If that guess turns
4458 ** out to be wrong, fall back to loading the data of page
4459 ** number ovfl to determine the next page number.
4460 */
4461 if( pBt->autoVacuum ){
4462 Pgno pgno;
4463 Pgno iGuess = ovfl+1;
4464 u8 eType;
4465
4466 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4467 iGuess++;
4468 }
4469
drhb1299152010-03-30 22:58:33 +00004470 if( iGuess<=btreePagecount(pBt) ){
danielk1977d04417962007-05-02 13:16:30 +00004471 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
danielk1977bea2a942009-01-20 17:06:27 +00004472 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
danielk1977d04417962007-05-02 13:16:30 +00004473 next = iGuess;
danielk1977bea2a942009-01-20 17:06:27 +00004474 rc = SQLITE_DONE;
danielk1977d04417962007-05-02 13:16:30 +00004475 }
4476 }
4477 }
4478#endif
4479
danielk1977d8a3f3d2009-07-11 11:45:23 +00004480 assert( next==0 || rc==SQLITE_DONE );
danielk1977bea2a942009-01-20 17:06:27 +00004481 if( rc==SQLITE_OK ){
drhb00fc3b2013-08-21 23:42:32 +00004482 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
danielk1977d8a3f3d2009-07-11 11:45:23 +00004483 assert( rc==SQLITE_OK || pPage==0 );
4484 if( rc==SQLITE_OK ){
danielk1977d04417962007-05-02 13:16:30 +00004485 next = get4byte(pPage->aData);
4486 }
danielk1977443c0592009-01-16 15:21:05 +00004487 }
danielk197745d68822009-01-16 16:23:38 +00004488
danielk1977bea2a942009-01-20 17:06:27 +00004489 *pPgnoNext = next;
4490 if( ppPage ){
4491 *ppPage = pPage;
4492 }else{
4493 releasePage(pPage);
4494 }
4495 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
danielk1977d04417962007-05-02 13:16:30 +00004496}
4497
danielk1977da107192007-05-04 08:32:13 +00004498/*
4499** Copy data from a buffer to a page, or from a page to a buffer.
4500**
4501** pPayload is a pointer to data stored on database page pDbPage.
4502** If argument eOp is false, then nByte bytes of data are copied
4503** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4504** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4505** of data are copied from the buffer pBuf to pPayload.
4506**
4507** SQLITE_OK is returned on success, otherwise an error code.
4508*/
4509static int copyPayload(
4510 void *pPayload, /* Pointer to page data */
4511 void *pBuf, /* Pointer to buffer */
4512 int nByte, /* Number of bytes to copy */
4513 int eOp, /* 0 -> copy from page, 1 -> copy to page */
4514 DbPage *pDbPage /* Page containing pPayload */
4515){
4516 if( eOp ){
4517 /* Copy data from buffer to page (a write operation) */
4518 int rc = sqlite3PagerWrite(pDbPage);
4519 if( rc!=SQLITE_OK ){
4520 return rc;
4521 }
4522 memcpy(pPayload, pBuf, nByte);
4523 }else{
4524 /* Copy data from page to buffer (a read operation) */
4525 memcpy(pBuf, pPayload, nByte);
4526 }
4527 return SQLITE_OK;
4528}
danielk1977d04417962007-05-02 13:16:30 +00004529
4530/*
danielk19779f8d6402007-05-02 17:48:45 +00004531** This function is used to read or overwrite payload information
dan5a500af2014-03-11 20:33:04 +00004532** for the entry that the pCur cursor is pointing to. The eOp
4533** argument is interpreted as follows:
4534**
4535** 0: The operation is a read. Populate the overflow cache.
4536** 1: The operation is a write. Populate the overflow cache.
danielk19779f8d6402007-05-02 17:48:45 +00004537**
4538** A total of "amt" bytes are read or written beginning at "offset".
4539** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00004540**
drh3bcdfd22009-07-12 02:32:21 +00004541** The content being read or written might appear on the main page
4542** or be scattered out on multiple overflow pages.
danielk1977da107192007-05-04 08:32:13 +00004543**
drh42e28f12017-01-27 00:31:59 +00004544** If the current cursor entry uses one or more overflow pages
4545** this function may allocate space for and lazily populate
4546** the overflow page-list cache array (BtCursor.aOverflow).
dan5a500af2014-03-11 20:33:04 +00004547** Subsequent calls use this cache to make seeking to the supplied offset
4548** more efficient.
danielk1977da107192007-05-04 08:32:13 +00004549**
drh42e28f12017-01-27 00:31:59 +00004550** Once an overflow page-list cache has been allocated, it must be
danielk1977da107192007-05-04 08:32:13 +00004551** invalidated if some other cursor writes to the same table, or if
4552** the cursor is moved to a different row. Additionally, in auto-vacuum
4553** mode, the following events may invalidate an overflow page-list cache.
4554**
4555** * An incremental vacuum,
4556** * A commit in auto_vacuum="full" mode,
4557** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00004558*/
danielk19779f8d6402007-05-02 17:48:45 +00004559static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00004560 BtCursor *pCur, /* Cursor pointing to entry to read from */
danielk197789d40042008-11-17 14:20:56 +00004561 u32 offset, /* Begin reading this far into payload */
4562 u32 amt, /* Read this many bytes */
drh3aac2dd2004-04-26 14:10:20 +00004563 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00004564 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00004565){
4566 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00004567 int rc = SQLITE_OK;
danielk19772dec9702007-05-02 16:48:37 +00004568 int iIdx = 0;
drh352a35a2017-08-15 03:46:47 +00004569 MemPage *pPage = pCur->pPage; /* Btree page of current entry */
danielk19770d065412008-11-12 18:21:36 +00004570 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh4c417182014-03-31 23:57:41 +00004571#ifdef SQLITE_DIRECT_OVERFLOW_READ
drh8bb9fd32017-01-26 16:27:32 +00004572 unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
drh4c417182014-03-31 23:57:41 +00004573#endif
drh3aac2dd2004-04-26 14:10:20 +00004574
danielk1977da107192007-05-04 08:32:13 +00004575 assert( pPage );
drh42e28f12017-01-27 00:31:59 +00004576 assert( eOp==0 || eOp==1 );
danielk1977da184232006-01-05 11:34:32 +00004577 assert( pCur->eState==CURSOR_VALID );
drh75e96b32017-04-01 00:20:06 +00004578 assert( pCur->ix<pPage->nCell );
drh1fee73e2007-08-29 04:00:57 +00004579 assert( cursorHoldsMutex(pCur) );
danielk1977da107192007-05-04 08:32:13 +00004580
drh86057612007-06-26 01:04:48 +00004581 getCellInfo(pCur);
drhab1cc582014-09-23 21:25:19 +00004582 aPayload = pCur->info.pPayload;
drhab1cc582014-09-23 21:25:19 +00004583 assert( offset+amt <= pCur->info.nPayload );
danielk1977da107192007-05-04 08:32:13 +00004584
drh0b982072016-03-22 14:10:45 +00004585 assert( aPayload > pPage->aData );
drhc5e7f942016-03-22 15:25:16 +00004586 if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
drh0b982072016-03-22 14:10:45 +00004587 /* Trying to read or write past the end of the data is an error. The
4588 ** conditional above is really:
4589 ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
4590 ** but is recast into its current form to avoid integer overflow problems
4591 */
drhcc97ca42017-06-07 22:32:59 +00004592 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drh3aac2dd2004-04-26 14:10:20 +00004593 }
danielk1977da107192007-05-04 08:32:13 +00004594
4595 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00004596 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00004597 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00004598 if( a+offset>pCur->info.nLocal ){
4599 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00004600 }
drh42e28f12017-01-27 00:31:59 +00004601 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00004602 offset = 0;
drha34b6762004-05-07 13:30:42 +00004603 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00004604 amt -= a;
drhdd793422001-06-28 01:54:48 +00004605 }else{
drhfa1a98a2004-05-14 19:08:17 +00004606 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00004607 }
danielk1977da107192007-05-04 08:32:13 +00004608
dan85753662014-12-11 16:38:18 +00004609
danielk1977da107192007-05-04 08:32:13 +00004610 if( rc==SQLITE_OK && amt>0 ){
danielk197789d40042008-11-17 14:20:56 +00004611 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
danielk1977da107192007-05-04 08:32:13 +00004612 Pgno nextPage;
4613
drhfa1a98a2004-05-14 19:08:17 +00004614 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00004615
drha38c9512014-04-01 01:24:34 +00004616 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
drha38c9512014-04-01 01:24:34 +00004617 **
4618 ** The aOverflow[] array is sized at one entry for each overflow page
4619 ** in the overflow chain. The page number of the first overflow page is
4620 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
4621 ** means "not yet known" (the cache is lazily populated).
danielk1977da107192007-05-04 08:32:13 +00004622 */
drh42e28f12017-01-27 00:31:59 +00004623 if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
danielk19772dec9702007-05-02 16:48:37 +00004624 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
dan5a500af2014-03-11 20:33:04 +00004625 if( nOvfl>pCur->nOvflAlloc ){
dan85753662014-12-11 16:38:18 +00004626 Pgno *aNew = (Pgno*)sqlite3Realloc(
4627 pCur->aOverflow, nOvfl*2*sizeof(Pgno)
dan5a500af2014-03-11 20:33:04 +00004628 );
4629 if( aNew==0 ){
drhcd645532017-01-20 20:43:14 +00004630 return SQLITE_NOMEM_BKPT;
dan5a500af2014-03-11 20:33:04 +00004631 }else{
4632 pCur->nOvflAlloc = nOvfl*2;
4633 pCur->aOverflow = aNew;
4634 }
4635 }
drhcd645532017-01-20 20:43:14 +00004636 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
4637 pCur->curFlags |= BTCF_ValidOvfl;
drhcdf360a2017-01-27 01:13:49 +00004638 }else{
4639 /* If the overflow page-list cache has been allocated and the
4640 ** entry for the first required overflow page is valid, skip
4641 ** directly to it.
4642 */
4643 if( pCur->aOverflow[offset/ovflSize] ){
4644 iIdx = (offset/ovflSize);
4645 nextPage = pCur->aOverflow[iIdx];
4646 offset = (offset%ovflSize);
4647 }
danielk19772dec9702007-05-02 16:48:37 +00004648 }
danielk1977da107192007-05-04 08:32:13 +00004649
drhcd645532017-01-20 20:43:14 +00004650 assert( rc==SQLITE_OK && amt>0 );
4651 while( nextPage ){
danielk1977da107192007-05-04 08:32:13 +00004652 /* If required, populate the overflow page-list cache. */
drh42e28f12017-01-27 00:31:59 +00004653 assert( pCur->aOverflow[iIdx]==0
4654 || pCur->aOverflow[iIdx]==nextPage
4655 || CORRUPT_DB );
4656 pCur->aOverflow[iIdx] = nextPage;
danielk1977da107192007-05-04 08:32:13 +00004657
danielk1977d04417962007-05-02 13:16:30 +00004658 if( offset>=ovflSize ){
4659 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00004660 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00004661 ** data is not required. So first try to lookup the overflow
4662 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00004663 ** function.
danielk1977d04417962007-05-02 13:16:30 +00004664 */
drha38c9512014-04-01 01:24:34 +00004665 assert( pCur->curFlags & BTCF_ValidOvfl );
dan85753662014-12-11 16:38:18 +00004666 assert( pCur->pBtree->db==pBt->db );
drha38c9512014-04-01 01:24:34 +00004667 if( pCur->aOverflow[iIdx+1] ){
danielk1977da107192007-05-04 08:32:13 +00004668 nextPage = pCur->aOverflow[iIdx+1];
drha38c9512014-04-01 01:24:34 +00004669 }else{
danielk1977da107192007-05-04 08:32:13 +00004670 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
drha38c9512014-04-01 01:24:34 +00004671 }
danielk1977da107192007-05-04 08:32:13 +00004672 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00004673 }else{
danielk19779f8d6402007-05-02 17:48:45 +00004674 /* Need to read this page properly. It contains some of the
4675 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00004676 */
danf4ba1092011-10-08 14:57:07 +00004677#ifdef SQLITE_DIRECT_OVERFLOW_READ
drh8bb9fd32017-01-26 16:27:32 +00004678 sqlite3_file *fd; /* File from which to do direct overflow read */
danf4ba1092011-10-08 14:57:07 +00004679#endif
danielk1977cfe9a692004-06-16 12:00:29 +00004680 int a = amt;
danf4ba1092011-10-08 14:57:07 +00004681 if( a + offset > ovflSize ){
4682 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00004683 }
danf4ba1092011-10-08 14:57:07 +00004684
4685#ifdef SQLITE_DIRECT_OVERFLOW_READ
4686 /* If all the following are true:
4687 **
4688 ** 1) this is a read operation, and
4689 ** 2) data is required from the start of this overflow page, and
drh8bb9fd32017-01-26 16:27:32 +00004690 ** 3) there is no open write-transaction, and
4691 ** 4) the database is file-backed, and
drhd930b5c2017-01-26 02:26:02 +00004692 ** 5) the page is not in the WAL file
drh8bb9fd32017-01-26 16:27:32 +00004693 ** 6) at least 4 bytes have already been read into the output buffer
danf4ba1092011-10-08 14:57:07 +00004694 **
4695 ** then data can be read directly from the database file into the
4696 ** output buffer, bypassing the page-cache altogether. This speeds
4697 ** up loading large records that span many overflow pages.
4698 */
drh42e28f12017-01-27 00:31:59 +00004699 if( eOp==0 /* (1) */
danf4ba1092011-10-08 14:57:07 +00004700 && offset==0 /* (2) */
drh8bb9fd32017-01-26 16:27:32 +00004701 && pBt->inTransaction==TRANS_READ /* (3) */
4702 && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (4) */
drhd930b5c2017-01-26 02:26:02 +00004703 && 0==sqlite3PagerUseWal(pBt->pPager, nextPage) /* (5) */
drh8bb9fd32017-01-26 16:27:32 +00004704 && &pBuf[-4]>=pBufStart /* (6) */
danf4ba1092011-10-08 14:57:07 +00004705 ){
4706 u8 aSave[4];
4707 u8 *aWrite = &pBuf[-4];
drh8bb9fd32017-01-26 16:27:32 +00004708 assert( aWrite>=pBufStart ); /* due to (6) */
danf4ba1092011-10-08 14:57:07 +00004709 memcpy(aSave, aWrite, 4);
dan27d47fb2011-12-21 17:00:16 +00004710 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
danf4ba1092011-10-08 14:57:07 +00004711 nextPage = get4byte(aWrite);
4712 memcpy(aWrite, aSave, 4);
4713 }else
4714#endif
4715
4716 {
4717 DbPage *pDbPage;
drh9584f582015-11-04 20:22:37 +00004718 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
drh42e28f12017-01-27 00:31:59 +00004719 (eOp==0 ? PAGER_GET_READONLY : 0)
dan11dcd112013-03-15 18:29:18 +00004720 );
danf4ba1092011-10-08 14:57:07 +00004721 if( rc==SQLITE_OK ){
4722 aPayload = sqlite3PagerGetData(pDbPage);
4723 nextPage = get4byte(aPayload);
drh42e28f12017-01-27 00:31:59 +00004724 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
danf4ba1092011-10-08 14:57:07 +00004725 sqlite3PagerUnref(pDbPage);
4726 offset = 0;
4727 }
4728 }
4729 amt -= a;
drh6ee610b2017-01-27 01:25:00 +00004730 if( amt==0 ) return rc;
danf4ba1092011-10-08 14:57:07 +00004731 pBuf += a;
danielk1977cfe9a692004-06-16 12:00:29 +00004732 }
drhcd645532017-01-20 20:43:14 +00004733 if( rc ) break;
4734 iIdx++;
drh2af926b2001-05-15 00:39:25 +00004735 }
drh2af926b2001-05-15 00:39:25 +00004736 }
danielk1977cfe9a692004-06-16 12:00:29 +00004737
danielk1977da107192007-05-04 08:32:13 +00004738 if( rc==SQLITE_OK && amt>0 ){
drhcc97ca42017-06-07 22:32:59 +00004739 /* Overflow chain ends prematurely */
4740 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drha7fcb052001-12-14 15:09:55 +00004741 }
danielk1977da107192007-05-04 08:32:13 +00004742 return rc;
drh2af926b2001-05-15 00:39:25 +00004743}
4744
drh72f82862001-05-24 21:06:34 +00004745/*
drhcb3cabd2016-11-25 19:18:28 +00004746** Read part of the payload for the row at which that cursor pCur is currently
4747** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00004748** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00004749**
drhcb3cabd2016-11-25 19:18:28 +00004750** pCur can be pointing to either a table or an index b-tree.
4751** If pointing to a table btree, then the content section is read. If
4752** pCur is pointing to an index b-tree then the key section is read.
4753**
4754** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
4755** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
4756** cursor might be invalid or might need to be restored before being read.
drh5d1a8722009-07-22 18:07:40 +00004757**
drh3aac2dd2004-04-26 14:10:20 +00004758** Return SQLITE_OK on success or an error code if anything goes
4759** wrong. An error is returned if "offset+amt" is larger than
4760** the available payload.
drh72f82862001-05-24 21:06:34 +00004761*/
drhcb3cabd2016-11-25 19:18:28 +00004762int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drh1fee73e2007-08-29 04:00:57 +00004763 assert( cursorHoldsMutex(pCur) );
drh5d1a8722009-07-22 18:07:40 +00004764 assert( pCur->eState==CURSOR_VALID );
drh352a35a2017-08-15 03:46:47 +00004765 assert( pCur->iPage>=0 && pCur->pPage );
4766 assert( pCur->ix<pCur->pPage->nCell );
drh5d1a8722009-07-22 18:07:40 +00004767 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
drh3aac2dd2004-04-26 14:10:20 +00004768}
drh83ec2762017-01-26 16:54:47 +00004769
4770/*
4771** This variant of sqlite3BtreePayload() works even if the cursor has not
4772** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
4773** interface.
4774*/
danielk19773588ceb2008-06-10 17:30:26 +00004775#ifndef SQLITE_OMIT_INCRBLOB
drh83ec2762017-01-26 16:54:47 +00004776static SQLITE_NOINLINE int accessPayloadChecked(
4777 BtCursor *pCur,
4778 u32 offset,
4779 u32 amt,
4780 void *pBuf
4781){
drhcb3cabd2016-11-25 19:18:28 +00004782 int rc;
danielk19773588ceb2008-06-10 17:30:26 +00004783 if ( pCur->eState==CURSOR_INVALID ){
4784 return SQLITE_ABORT;
4785 }
dan7a2347e2016-01-07 16:43:54 +00004786 assert( cursorOwnsBtShared(pCur) );
drh945b0942017-01-26 21:30:00 +00004787 rc = btreeRestoreCursorPosition(pCur);
drh83ec2762017-01-26 16:54:47 +00004788 return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
4789}
4790int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
4791 if( pCur->eState==CURSOR_VALID ){
4792 assert( cursorOwnsBtShared(pCur) );
4793 return accessPayload(pCur, offset, amt, pBuf, 0);
4794 }else{
4795 return accessPayloadChecked(pCur, offset, amt, pBuf);
danielk1977da184232006-01-05 11:34:32 +00004796 }
drh2af926b2001-05-15 00:39:25 +00004797}
drhcb3cabd2016-11-25 19:18:28 +00004798#endif /* SQLITE_OMIT_INCRBLOB */
drh2af926b2001-05-15 00:39:25 +00004799
drh72f82862001-05-24 21:06:34 +00004800/*
drh0e1c19e2004-05-11 00:58:56 +00004801** Return a pointer to payload information from the entry that the
4802** pCur cursor is pointing to. The pointer is to the beginning of
drh2a8d2262013-12-09 20:43:22 +00004803** the key if index btrees (pPage->intKey==0) and is the data for
4804** table btrees (pPage->intKey==1). The number of bytes of available
4805** key/data is written into *pAmt. If *pAmt==0, then the value
4806** returned will not be a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00004807**
4808** This routine is an optimization. It is common for the entire key
4809** and data to fit on the local page and for there to be no overflow
4810** pages. When that is so, this routine can be used to access the
4811** key and data without making a copy. If the key and/or data spills
drh7f751222009-03-17 22:33:00 +00004812** onto overflow pages, then accessPayload() must be used to reassemble
drh0e1c19e2004-05-11 00:58:56 +00004813** the key/data and copy it into a preallocated buffer.
4814**
4815** The pointer returned by this routine looks directly into the cached
4816** page of the database. The data might change or move the next time
4817** any btree routine is called.
4818*/
drh2a8d2262013-12-09 20:43:22 +00004819static const void *fetchPayload(
drh0e1c19e2004-05-11 00:58:56 +00004820 BtCursor *pCur, /* Cursor pointing to entry to read from */
drh2a8d2262013-12-09 20:43:22 +00004821 u32 *pAmt /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00004822){
drhf3392e32015-04-15 17:26:55 +00004823 u32 amt;
drh352a35a2017-08-15 03:46:47 +00004824 assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
danielk1977da184232006-01-05 11:34:32 +00004825 assert( pCur->eState==CURSOR_VALID );
drh2a8d2262013-12-09 20:43:22 +00004826 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
dan7a2347e2016-01-07 16:43:54 +00004827 assert( cursorOwnsBtShared(pCur) );
drh352a35a2017-08-15 03:46:47 +00004828 assert( pCur->ix<pCur->pPage->nCell );
drh86dd3712014-03-25 11:00:21 +00004829 assert( pCur->info.nSize>0 );
drh352a35a2017-08-15 03:46:47 +00004830 assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
4831 assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
4832 amt = (int)(pCur->pPage->aDataEnd - pCur->info.pPayload);
drhf3392e32015-04-15 17:26:55 +00004833 if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
4834 *pAmt = amt;
drhab1cc582014-09-23 21:25:19 +00004835 return (void*)pCur->info.pPayload;
drh0e1c19e2004-05-11 00:58:56 +00004836}
4837
4838
4839/*
drhe51c44f2004-05-30 20:46:09 +00004840** For the entry that cursor pCur is point to, return as
4841** many bytes of the key or data as are available on the local
4842** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00004843**
4844** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00004845** or be destroyed on the next call to any Btree routine,
4846** including calls from other threads against the same cache.
4847** Hence, a mutex on the BtShared should be held prior to calling
4848** this routine.
drh0e1c19e2004-05-11 00:58:56 +00004849**
4850** These routines is used to get quick access to key and data
4851** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00004852*/
drha7c90c42016-06-04 20:37:10 +00004853const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
drh2a8d2262013-12-09 20:43:22 +00004854 return fetchPayload(pCur, pAmt);
drh0e1c19e2004-05-11 00:58:56 +00004855}
4856
4857
4858/*
drh8178a752003-01-05 21:41:40 +00004859** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00004860** page number of the child page to move to.
danielk1977a299d612009-07-13 11:22:10 +00004861**
4862** This function returns SQLITE_CORRUPT if the page-header flags field of
4863** the new child page does not match the flags field of the parent (i.e.
4864** if an intkey page appears to be the parent of a non-intkey page, or
4865** vice-versa).
drh72f82862001-05-24 21:06:34 +00004866*/
drh3aac2dd2004-04-26 14:10:20 +00004867static int moveToChild(BtCursor *pCur, u32 newPgno){
drhd0679ed2007-08-28 22:24:34 +00004868 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00004869
dan7a2347e2016-01-07 16:43:54 +00004870 assert( cursorOwnsBtShared(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004871 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004872 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
dan11dcd112013-03-15 18:29:18 +00004873 assert( pCur->iPage>=0 );
danielk197771d5d2c2008-09-29 11:49:47 +00004874 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
4875 return SQLITE_CORRUPT_BKPT;
4876 }
drh271efa52004-05-30 19:19:05 +00004877 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004878 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drh352a35a2017-08-15 03:46:47 +00004879 pCur->aiIdx[pCur->iPage] = pCur->ix;
4880 pCur->apPage[pCur->iPage] = pCur->pPage;
drh75e96b32017-04-01 00:20:06 +00004881 pCur->ix = 0;
drh352a35a2017-08-15 03:46:47 +00004882 pCur->iPage++;
4883 return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
drh72f82862001-05-24 21:06:34 +00004884}
4885
drhd879e3e2017-02-13 13:35:55 +00004886#ifdef SQLITE_DEBUG
danielk1977bf93c562008-09-29 15:53:25 +00004887/*
4888** Page pParent is an internal (non-leaf) tree page. This function
4889** asserts that page number iChild is the left-child if the iIdx'th
4890** cell in page pParent. Or, if iIdx is equal to the total number of
4891** cells in pParent, that page number iChild is the right-child of
4892** the page.
4893*/
4894static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
drhcbd33492015-03-25 13:06:54 +00004895 if( CORRUPT_DB ) return; /* The conditions tested below might not be true
4896 ** in a corrupt database */
danielk1977bf93c562008-09-29 15:53:25 +00004897 assert( iIdx<=pParent->nCell );
4898 if( iIdx==pParent->nCell ){
4899 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
4900 }else{
4901 assert( get4byte(findCell(pParent, iIdx))==iChild );
4902 }
4903}
4904#else
4905# define assertParentIndex(x,y,z)
4906#endif
4907
drh72f82862001-05-24 21:06:34 +00004908/*
drh5e2f8b92001-05-28 00:41:15 +00004909** Move the cursor up to the parent page.
4910**
4911** pCur->idx is set to the cell index that contains the pointer
4912** to the page we are coming from. If we are coming from the
4913** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00004914** the largest cell index.
drh72f82862001-05-24 21:06:34 +00004915*/
danielk197730548662009-07-09 05:07:37 +00004916static void moveToParent(BtCursor *pCur){
drh352a35a2017-08-15 03:46:47 +00004917 MemPage *pLeaf;
dan7a2347e2016-01-07 16:43:54 +00004918 assert( cursorOwnsBtShared(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004919 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004920 assert( pCur->iPage>0 );
drh352a35a2017-08-15 03:46:47 +00004921 assert( pCur->pPage );
danielk1977bf93c562008-09-29 15:53:25 +00004922 assertParentIndex(
4923 pCur->apPage[pCur->iPage-1],
4924 pCur->aiIdx[pCur->iPage-1],
drh352a35a2017-08-15 03:46:47 +00004925 pCur->pPage->pgno
danielk1977bf93c562008-09-29 15:53:25 +00004926 );
dan6c2688c2012-01-12 15:05:03 +00004927 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
drh271efa52004-05-30 19:19:05 +00004928 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004929 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drh75e96b32017-04-01 00:20:06 +00004930 pCur->ix = pCur->aiIdx[pCur->iPage-1];
drh352a35a2017-08-15 03:46:47 +00004931 pLeaf = pCur->pPage;
4932 pCur->pPage = pCur->apPage[--pCur->iPage];
4933 releasePageNotNull(pLeaf);
drh72f82862001-05-24 21:06:34 +00004934}
4935
4936/*
danielk19778f880a82009-07-13 09:41:45 +00004937** Move the cursor to point to the root page of its b-tree structure.
4938**
4939** If the table has a virtual root page, then the cursor is moved to point
4940** to the virtual root page instead of the actual root page. A table has a
4941** virtual root page when the actual root page contains no cells and a
4942** single child page. This can only happen with the table rooted at page 1.
4943**
4944** If the b-tree structure is empty, the cursor state is set to
drh44548e72017-08-14 18:13:52 +00004945** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
4946** the cursor is set to point to the first cell located on the root
4947** (or virtual root) page and the cursor state is set to CURSOR_VALID.
danielk19778f880a82009-07-13 09:41:45 +00004948**
4949** If this function returns successfully, it may be assumed that the
4950** page-header flags indicate that the [virtual] root-page is the expected
4951** kind of b-tree page (i.e. if when opening the cursor the caller did not
4952** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
4953** indicating a table b-tree, or if the caller did specify a KeyInfo
4954** structure the flags byte is set to 0x02 or 0x0A, indicating an index
4955** b-tree).
drh72f82862001-05-24 21:06:34 +00004956*/
drh5e2f8b92001-05-28 00:41:15 +00004957static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00004958 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00004959 int rc = SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00004960
dan7a2347e2016-01-07 16:43:54 +00004961 assert( cursorOwnsBtShared(pCur) );
drhfb982642007-08-30 01:19:59 +00004962 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
4963 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
4964 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
drh85ef6302017-08-02 15:50:09 +00004965 assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
drh44548e72017-08-14 18:13:52 +00004966 assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
danielk197771d5d2c2008-09-29 11:49:47 +00004967
4968 if( pCur->iPage>=0 ){
drh7ad3eb62016-10-24 01:01:09 +00004969 if( pCur->iPage ){
drh352a35a2017-08-15 03:46:47 +00004970 releasePageNotNull(pCur->pPage);
4971 while( --pCur->iPage ){
4972 releasePageNotNull(pCur->apPage[pCur->iPage]);
4973 }
4974 pCur->pPage = pCur->apPage[0];
drh7ad3eb62016-10-24 01:01:09 +00004975 goto skip_init;
drhbbf0f862015-06-27 14:59:26 +00004976 }
dana205a482011-08-27 18:48:57 +00004977 }else if( pCur->pgnoRoot==0 ){
4978 pCur->eState = CURSOR_INVALID;
drh44548e72017-08-14 18:13:52 +00004979 return SQLITE_EMPTY;
drh777e4c42006-01-13 04:31:58 +00004980 }else{
drh28f58dd2015-06-27 19:45:03 +00004981 assert( pCur->iPage==(-1) );
drh85ef6302017-08-02 15:50:09 +00004982 if( pCur->eState>=CURSOR_REQUIRESEEK ){
4983 if( pCur->eState==CURSOR_FAULT ){
4984 assert( pCur->skipNext!=SQLITE_OK );
4985 return pCur->skipNext;
4986 }
4987 sqlite3BtreeClearCursor(pCur);
4988 }
drh352a35a2017-08-15 03:46:47 +00004989 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
drh15a00212015-06-27 20:55:00 +00004990 0, pCur->curPagerFlags);
drh4c301aa2009-07-15 17:25:45 +00004991 if( rc!=SQLITE_OK ){
drh777e4c42006-01-13 04:31:58 +00004992 pCur->eState = CURSOR_INVALID;
drhf0357d82017-08-14 17:03:58 +00004993 return rc;
drh777e4c42006-01-13 04:31:58 +00004994 }
danielk1977172114a2009-07-07 15:47:12 +00004995 pCur->iPage = 0;
drh352a35a2017-08-15 03:46:47 +00004996 pCur->curIntKey = pCur->pPage->intKey;
drhc39e0002004-05-07 23:50:57 +00004997 }
drh352a35a2017-08-15 03:46:47 +00004998 pRoot = pCur->pPage;
danielk197771d5d2c2008-09-29 11:49:47 +00004999 assert( pRoot->pgno==pCur->pgnoRoot );
dan7df42ab2014-01-20 18:25:44 +00005000
5001 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
5002 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
5003 ** NULL, the caller expects a table b-tree. If this is not the case,
5004 ** return an SQLITE_CORRUPT error.
5005 **
5006 ** Earlier versions of SQLite assumed that this test could not fail
5007 ** if the root page was already loaded when this function was called (i.e.
5008 ** if pCur->iPage>=0). But this is not so if the database is corrupted
5009 ** in such a way that page pRoot is linked into a second b-tree table
5010 ** (or the freelist). */
5011 assert( pRoot->intKey==1 || pRoot->intKey==0 );
5012 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
drh352a35a2017-08-15 03:46:47 +00005013 return SQLITE_CORRUPT_PGNO(pCur->pPage->pgno);
dan7df42ab2014-01-20 18:25:44 +00005014 }
danielk19778f880a82009-07-13 09:41:45 +00005015
drh7ad3eb62016-10-24 01:01:09 +00005016skip_init:
drh75e96b32017-04-01 00:20:06 +00005017 pCur->ix = 0;
drh271efa52004-05-30 19:19:05 +00005018 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00005019 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
danielk197771d5d2c2008-09-29 11:49:47 +00005020
drh352a35a2017-08-15 03:46:47 +00005021 pRoot = pCur->pPage;
drh4e8fe3f2013-12-06 23:25:27 +00005022 if( pRoot->nCell>0 ){
5023 pCur->eState = CURSOR_VALID;
5024 }else if( !pRoot->leaf ){
drh8856d6a2004-04-29 14:42:46 +00005025 Pgno subpage;
drhc85240d2009-06-04 16:14:33 +00005026 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
drh43605152004-05-29 21:46:49 +00005027 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
danielk1977da184232006-01-05 11:34:32 +00005028 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00005029 rc = moveToChild(pCur, subpage);
danielk197771d5d2c2008-09-29 11:49:47 +00005030 }else{
drh4e8fe3f2013-12-06 23:25:27 +00005031 pCur->eState = CURSOR_INVALID;
drh44548e72017-08-14 18:13:52 +00005032 rc = SQLITE_EMPTY;
drh8856d6a2004-04-29 14:42:46 +00005033 }
5034 return rc;
drh72f82862001-05-24 21:06:34 +00005035}
drh2af926b2001-05-15 00:39:25 +00005036
drh5e2f8b92001-05-28 00:41:15 +00005037/*
5038** Move the cursor down to the left-most leaf entry beneath the
5039** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00005040**
5041** The left-most leaf is the one with the smallest key - the first
5042** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00005043*/
5044static int moveToLeftmost(BtCursor *pCur){
5045 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00005046 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00005047 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00005048
dan7a2347e2016-01-07 16:43:54 +00005049 assert( cursorOwnsBtShared(pCur) );
danielk1977da184232006-01-05 11:34:32 +00005050 assert( pCur->eState==CURSOR_VALID );
drh352a35a2017-08-15 03:46:47 +00005051 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
drh75e96b32017-04-01 00:20:06 +00005052 assert( pCur->ix<pPage->nCell );
5053 pgno = get4byte(findCell(pPage, pCur->ix));
drh8178a752003-01-05 21:41:40 +00005054 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00005055 }
drhd677b3d2007-08-20 22:48:41 +00005056 return rc;
drh5e2f8b92001-05-28 00:41:15 +00005057}
5058
drh2dcc9aa2002-12-04 13:40:25 +00005059/*
5060** Move the cursor down to the right-most leaf entry beneath the
5061** page to which it is currently pointing. Notice the difference
5062** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
5063** finds the left-most entry beneath the *entry* whereas moveToRightmost()
5064** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00005065**
5066** The right-most entry is the one with the largest key - the last
5067** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00005068*/
5069static int moveToRightmost(BtCursor *pCur){
5070 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00005071 int rc = SQLITE_OK;
drh1bd10f82008-12-10 21:19:56 +00005072 MemPage *pPage = 0;
drh2dcc9aa2002-12-04 13:40:25 +00005073
dan7a2347e2016-01-07 16:43:54 +00005074 assert( cursorOwnsBtShared(pCur) );
danielk1977da184232006-01-05 11:34:32 +00005075 assert( pCur->eState==CURSOR_VALID );
drh352a35a2017-08-15 03:46:47 +00005076 while( !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00005077 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh75e96b32017-04-01 00:20:06 +00005078 pCur->ix = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00005079 rc = moveToChild(pCur, pgno);
drhee6438d2014-09-01 13:29:32 +00005080 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00005081 }
drh75e96b32017-04-01 00:20:06 +00005082 pCur->ix = pPage->nCell-1;
drhee6438d2014-09-01 13:29:32 +00005083 assert( pCur->info.nSize==0 );
5084 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5085 return SQLITE_OK;
drh2dcc9aa2002-12-04 13:40:25 +00005086}
5087
drh5e00f6c2001-09-13 13:46:56 +00005088/* Move the cursor to the first entry in the table. Return SQLITE_OK
5089** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00005090** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00005091*/
drh3aac2dd2004-04-26 14:10:20 +00005092int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00005093 int rc;
drhd677b3d2007-08-20 22:48:41 +00005094
dan7a2347e2016-01-07 16:43:54 +00005095 assert( cursorOwnsBtShared(pCur) );
drhe5fe6902007-12-07 18:55:28 +00005096 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00005097 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00005098 if( rc==SQLITE_OK ){
drh352a35a2017-08-15 03:46:47 +00005099 assert( pCur->pPage->nCell>0 );
drh44548e72017-08-14 18:13:52 +00005100 *pRes = 0;
5101 rc = moveToLeftmost(pCur);
5102 }else if( rc==SQLITE_EMPTY ){
drh352a35a2017-08-15 03:46:47 +00005103 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
drh44548e72017-08-14 18:13:52 +00005104 *pRes = 1;
5105 rc = SQLITE_OK;
drh5e00f6c2001-09-13 13:46:56 +00005106 }
drh5e00f6c2001-09-13 13:46:56 +00005107 return rc;
5108}
drh5e2f8b92001-05-28 00:41:15 +00005109
drh9562b552002-02-19 15:00:07 +00005110/* Move the cursor to the last entry in the table. Return SQLITE_OK
5111** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00005112** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00005113*/
drh3aac2dd2004-04-26 14:10:20 +00005114int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00005115 int rc;
drhd677b3d2007-08-20 22:48:41 +00005116
dan7a2347e2016-01-07 16:43:54 +00005117 assert( cursorOwnsBtShared(pCur) );
drhe5fe6902007-12-07 18:55:28 +00005118 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19773f632d52009-05-02 10:03:09 +00005119
5120 /* If the cursor already points to the last entry, this is a no-op. */
drh036dbec2014-03-11 23:40:44 +00005121 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
danielk19773f632d52009-05-02 10:03:09 +00005122#ifdef SQLITE_DEBUG
5123 /* This block serves to assert() that the cursor really does point
5124 ** to the last entry in the b-tree. */
5125 int ii;
5126 for(ii=0; ii<pCur->iPage; ii++){
5127 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
5128 }
drh352a35a2017-08-15 03:46:47 +00005129 assert( pCur->ix==pCur->pPage->nCell-1 );
5130 assert( pCur->pPage->leaf );
danielk19773f632d52009-05-02 10:03:09 +00005131#endif
5132 return SQLITE_OK;
5133 }
5134
drh9562b552002-02-19 15:00:07 +00005135 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00005136 if( rc==SQLITE_OK ){
drh44548e72017-08-14 18:13:52 +00005137 assert( pCur->eState==CURSOR_VALID );
5138 *pRes = 0;
5139 rc = moveToRightmost(pCur);
5140 if( rc==SQLITE_OK ){
5141 pCur->curFlags |= BTCF_AtLast;
drhd677b3d2007-08-20 22:48:41 +00005142 }else{
drh44548e72017-08-14 18:13:52 +00005143 pCur->curFlags &= ~BTCF_AtLast;
drhd677b3d2007-08-20 22:48:41 +00005144 }
drh44548e72017-08-14 18:13:52 +00005145 }else if( rc==SQLITE_EMPTY ){
drh352a35a2017-08-15 03:46:47 +00005146 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
drh44548e72017-08-14 18:13:52 +00005147 *pRes = 1;
5148 rc = SQLITE_OK;
drh9562b552002-02-19 15:00:07 +00005149 }
drh9562b552002-02-19 15:00:07 +00005150 return rc;
5151}
5152
drhe14006d2008-03-25 17:23:32 +00005153/* Move the cursor so that it points to an entry near the key
drhe63d9992008-08-13 19:11:48 +00005154** specified by pIdxKey or intKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00005155**
drhe63d9992008-08-13 19:11:48 +00005156** For INTKEY tables, the intKey parameter is used. pIdxKey
5157** must be NULL. For index tables, pIdxKey is used and intKey
5158** is ignored.
drh3aac2dd2004-04-26 14:10:20 +00005159**
drh5e2f8b92001-05-28 00:41:15 +00005160** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00005161** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00005162** were present. The cursor might point to an entry that comes
5163** before or after the key.
5164**
drh64022502009-01-09 14:11:04 +00005165** An integer is written into *pRes which is the result of
5166** comparing the key with the entry to which the cursor is
5167** pointing. The meaning of the integer written into
5168** *pRes is as follows:
drhbd03cae2001-06-02 02:40:57 +00005169**
5170** *pRes<0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00005171** is smaller than intKey/pIdxKey or if the table is empty
drh1a844c32002-12-04 22:29:28 +00005172** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00005173**
5174** *pRes==0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00005175** exactly matches intKey/pIdxKey.
drhbd03cae2001-06-02 02:40:57 +00005176**
5177** *pRes>0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00005178** is larger than intKey/pIdxKey.
drhd677b3d2007-08-20 22:48:41 +00005179**
drhb1d607d2015-11-05 22:30:54 +00005180** For index tables, the pIdxKey->eqSeen field is set to 1 if there
5181** exists an entry in the table that exactly matches pIdxKey.
drha059ad02001-04-17 20:09:11 +00005182*/
drhe63d9992008-08-13 19:11:48 +00005183int sqlite3BtreeMovetoUnpacked(
5184 BtCursor *pCur, /* The cursor to be moved */
5185 UnpackedRecord *pIdxKey, /* Unpacked index key */
5186 i64 intKey, /* The table key */
5187 int biasRight, /* If true, bias the search to the high end */
5188 int *pRes /* Write search results here */
drhe4d90812007-03-29 05:51:49 +00005189){
drh72f82862001-05-24 21:06:34 +00005190 int rc;
dan3b9330f2014-02-27 20:44:18 +00005191 RecordCompare xRecordCompare;
drhd677b3d2007-08-20 22:48:41 +00005192
dan7a2347e2016-01-07 16:43:54 +00005193 assert( cursorOwnsBtShared(pCur) );
drhe5fe6902007-12-07 18:55:28 +00005194 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19775cb09632009-07-09 11:36:01 +00005195 assert( pRes );
danielk19773fd7cf52009-07-13 07:30:52 +00005196 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
drhdebaa862016-06-13 12:51:20 +00005197 assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
drha2c20e42008-03-29 16:01:04 +00005198
5199 /* If the cursor is already positioned at the point we are trying
5200 ** to move to, then just return without doing any work */
drh05a36092016-06-06 01:54:20 +00005201 if( pIdxKey==0
5202 && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
danielk197771d5d2c2008-09-29 11:49:47 +00005203 ){
drhe63d9992008-08-13 19:11:48 +00005204 if( pCur->info.nKey==intKey ){
drha2c20e42008-03-29 16:01:04 +00005205 *pRes = 0;
5206 return SQLITE_OK;
5207 }
drh451e76d2017-01-21 16:54:19 +00005208 if( pCur->info.nKey<intKey ){
5209 if( (pCur->curFlags & BTCF_AtLast)!=0 ){
5210 *pRes = -1;
5211 return SQLITE_OK;
5212 }
drh7f11afa2017-01-21 21:47:54 +00005213 /* If the requested key is one more than the previous key, then
5214 ** try to get there using sqlite3BtreeNext() rather than a full
5215 ** binary search. This is an optimization only. The correct answer
drh2ab792e2017-05-30 18:34:07 +00005216 ** is still obtained without this case, only a little more slowely */
drh7f11afa2017-01-21 21:47:54 +00005217 if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
5218 *pRes = 0;
drh2ab792e2017-05-30 18:34:07 +00005219 rc = sqlite3BtreeNext(pCur, 0);
5220 if( rc==SQLITE_OK ){
drh7f11afa2017-01-21 21:47:54 +00005221 getCellInfo(pCur);
5222 if( pCur->info.nKey==intKey ){
5223 return SQLITE_OK;
5224 }
drh2ab792e2017-05-30 18:34:07 +00005225 }else if( rc==SQLITE_DONE ){
5226 rc = SQLITE_OK;
5227 }else{
5228 return rc;
drh451e76d2017-01-21 16:54:19 +00005229 }
5230 }
drha2c20e42008-03-29 16:01:04 +00005231 }
5232 }
5233
dan1fed5da2014-02-25 21:01:25 +00005234 if( pIdxKey ){
5235 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
dan38fdead2014-04-01 10:19:02 +00005236 pIdxKey->errCode = 0;
dan3b9330f2014-02-27 20:44:18 +00005237 assert( pIdxKey->default_rc==1
5238 || pIdxKey->default_rc==0
5239 || pIdxKey->default_rc==-1
5240 );
drh13a747e2014-03-03 21:46:55 +00005241 }else{
drhb6e8fd12014-03-06 01:56:33 +00005242 xRecordCompare = 0; /* All keys are integers */
dan1fed5da2014-02-25 21:01:25 +00005243 }
5244
drh5e2f8b92001-05-28 00:41:15 +00005245 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00005246 if( rc ){
drh44548e72017-08-14 18:13:52 +00005247 if( rc==SQLITE_EMPTY ){
drh352a35a2017-08-15 03:46:47 +00005248 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
drh44548e72017-08-14 18:13:52 +00005249 *pRes = -1;
5250 return SQLITE_OK;
5251 }
drhd677b3d2007-08-20 22:48:41 +00005252 return rc;
5253 }
drh352a35a2017-08-15 03:46:47 +00005254 assert( pCur->pPage );
5255 assert( pCur->pPage->isInit );
drh44548e72017-08-14 18:13:52 +00005256 assert( pCur->eState==CURSOR_VALID );
drh352a35a2017-08-15 03:46:47 +00005257 assert( pCur->pPage->nCell > 0 );
5258 assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
drhc75d8862015-06-27 23:55:20 +00005259 assert( pCur->curIntKey || pIdxKey );
drh14684382006-11-30 13:05:29 +00005260 for(;;){
drhec3e6b12013-11-25 02:38:55 +00005261 int lwr, upr, idx, c;
drh72f82862001-05-24 21:06:34 +00005262 Pgno chldPg;
drh352a35a2017-08-15 03:46:47 +00005263 MemPage *pPage = pCur->pPage;
drhec3e6b12013-11-25 02:38:55 +00005264 u8 *pCell; /* Pointer to current cell in pPage */
danielk1977171fff32009-07-11 05:06:51 +00005265
5266 /* pPage->nCell must be greater than zero. If this is the root-page
5267 ** the cursor would have been INVALID above and this for(;;) loop
5268 ** not run. If this is not the root-page, then the moveToChild() routine
danielk19773fd7cf52009-07-13 07:30:52 +00005269 ** would have already detected db corruption. Similarly, pPage must
5270 ** be the right kind (index or table) of b-tree page. Otherwise
5271 ** a moveToChild() or moveToRoot() call would have detected corruption. */
danielk1977171fff32009-07-11 05:06:51 +00005272 assert( pPage->nCell>0 );
danielk19773fd7cf52009-07-13 07:30:52 +00005273 assert( pPage->intKey==(pIdxKey==0) );
drh72f82862001-05-24 21:06:34 +00005274 lwr = 0;
5275 upr = pPage->nCell-1;
drhebf10b12013-11-25 17:38:26 +00005276 assert( biasRight==0 || biasRight==1 );
5277 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
drh75e96b32017-04-01 00:20:06 +00005278 pCur->ix = (u16)idx;
dana4660bd2014-03-04 16:05:25 +00005279 if( xRecordCompare==0 ){
drhec3e6b12013-11-25 02:38:55 +00005280 for(;;){
danielk197711c327a2009-05-04 19:01:26 +00005281 i64 nCellKey;
drhf44890a2015-06-27 03:58:15 +00005282 pCell = findCellPastPtr(pPage, idx);
drh3e28ff52014-09-24 00:59:08 +00005283 if( pPage->intKeyLeaf ){
drh9b2fc612013-11-25 20:14:13 +00005284 while( 0x80 <= *(pCell++) ){
drhcc97ca42017-06-07 22:32:59 +00005285 if( pCell>=pPage->aDataEnd ){
5286 return SQLITE_CORRUPT_PGNO(pPage->pgno);
5287 }
drh9b2fc612013-11-25 20:14:13 +00005288 }
drhd172f862006-01-12 15:01:15 +00005289 }
drha2c20e42008-03-29 16:01:04 +00005290 getVarint(pCell, (u64*)&nCellKey);
drhbb933ef2013-11-25 15:01:38 +00005291 if( nCellKey<intKey ){
5292 lwr = idx+1;
5293 if( lwr>upr ){ c = -1; break; }
5294 }else if( nCellKey>intKey ){
5295 upr = idx-1;
5296 if( lwr>upr ){ c = +1; break; }
5297 }else{
5298 assert( nCellKey==intKey );
drh75e96b32017-04-01 00:20:06 +00005299 pCur->ix = (u16)idx;
drhec3e6b12013-11-25 02:38:55 +00005300 if( !pPage->leaf ){
5301 lwr = idx;
drhebf10b12013-11-25 17:38:26 +00005302 goto moveto_next_layer;
drhec3e6b12013-11-25 02:38:55 +00005303 }else{
drhd95ef5c2016-11-11 18:19:05 +00005304 pCur->curFlags |= BTCF_ValidNKey;
5305 pCur->info.nKey = nCellKey;
5306 pCur->info.nSize = 0;
drhec3e6b12013-11-25 02:38:55 +00005307 *pRes = 0;
drhd95ef5c2016-11-11 18:19:05 +00005308 return SQLITE_OK;
drhec3e6b12013-11-25 02:38:55 +00005309 }
drhd793f442013-11-25 14:10:15 +00005310 }
drhebf10b12013-11-25 17:38:26 +00005311 assert( lwr+upr>=0 );
5312 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
drhec3e6b12013-11-25 02:38:55 +00005313 }
5314 }else{
5315 for(;;){
drhc6827502015-05-28 15:14:32 +00005316 int nCell; /* Size of the pCell cell in bytes */
drhf44890a2015-06-27 03:58:15 +00005317 pCell = findCellPastPtr(pPage, idx);
drhec3e6b12013-11-25 02:38:55 +00005318
drhb2eced52010-08-12 02:41:12 +00005319 /* The maximum supported page-size is 65536 bytes. This means that
danielk197711c327a2009-05-04 19:01:26 +00005320 ** the maximum number of record bytes stored on an index B-Tree
drhb2eced52010-08-12 02:41:12 +00005321 ** page is less than 16384 bytes and may be stored as a 2-byte
danielk197711c327a2009-05-04 19:01:26 +00005322 ** varint. This information is used to attempt to avoid parsing
5323 ** the entire cell by checking for the cases where the record is
5324 ** stored entirely within the b-tree page by inspecting the first
5325 ** 2 bytes of the cell.
5326 */
drhec3e6b12013-11-25 02:38:55 +00005327 nCell = pCell[0];
drh72b8ef62013-12-06 22:44:51 +00005328 if( nCell<=pPage->max1bytePayload ){
danielk197711c327a2009-05-04 19:01:26 +00005329 /* This branch runs if the record-size field of the cell is a
5330 ** single byte varint and the record fits entirely on the main
5331 ** b-tree page. */
drh3def2352011-11-11 00:27:15 +00005332 testcase( pCell+nCell+1==pPage->aDataEnd );
drh75179de2014-09-16 14:37:35 +00005333 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
danielk197711c327a2009-05-04 19:01:26 +00005334 }else if( !(pCell[1] & 0x80)
5335 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5336 ){
5337 /* The record-size field is a 2 byte varint and the record
5338 ** fits entirely on the main b-tree page. */
drh3def2352011-11-11 00:27:15 +00005339 testcase( pCell+nCell+2==pPage->aDataEnd );
drh75179de2014-09-16 14:37:35 +00005340 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
drhe51c44f2004-05-30 20:46:09 +00005341 }else{
danielk197711c327a2009-05-04 19:01:26 +00005342 /* The record flows over onto one or more overflow pages. In
5343 ** this case the whole cell needs to be parsed, a buffer allocated
5344 ** and accessPayload() used to retrieve the record into the
dan3548db72015-05-27 14:21:05 +00005345 ** buffer before VdbeRecordCompare() can be called.
5346 **
5347 ** If the record is corrupt, the xRecordCompare routine may read
5348 ** up to two varints past the end of the buffer. An extra 18
5349 ** bytes of padding is allocated at the end of the buffer in
5350 ** case this happens. */
danielk197711c327a2009-05-04 19:01:26 +00005351 void *pCellKey;
5352 u8 * const pCellBody = pCell - pPage->childPtrSize;
drh5fa60512015-06-19 17:19:34 +00005353 pPage->xParseCell(pPage, pCellBody, &pCur->info);
shane60a4b532009-05-06 18:57:09 +00005354 nCell = (int)pCur->info.nKey;
drhc6827502015-05-28 15:14:32 +00005355 testcase( nCell<0 ); /* True if key size is 2^32 or more */
5356 testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
5357 testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
5358 testcase( nCell==2 ); /* Minimum legal index key size */
dan3548db72015-05-27 14:21:05 +00005359 if( nCell<2 ){
drhcc97ca42017-06-07 22:32:59 +00005360 rc = SQLITE_CORRUPT_PGNO(pPage->pgno);
dan3548db72015-05-27 14:21:05 +00005361 goto moveto_finish;
5362 }
5363 pCellKey = sqlite3Malloc( nCell+18 );
danielk19776507ecb2008-03-25 09:56:44 +00005364 if( pCellKey==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005365 rc = SQLITE_NOMEM_BKPT;
danielk19776507ecb2008-03-25 09:56:44 +00005366 goto moveto_finish;
5367 }
drh75e96b32017-04-01 00:20:06 +00005368 pCur->ix = (u16)idx;
drh42e28f12017-01-27 00:31:59 +00005369 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
5370 pCur->curFlags &= ~BTCF_ValidOvfl;
drhec9b31f2009-08-25 13:53:49 +00005371 if( rc ){
5372 sqlite3_free(pCellKey);
5373 goto moveto_finish;
5374 }
drh75179de2014-09-16 14:37:35 +00005375 c = xRecordCompare(nCell, pCellKey, pIdxKey);
drhfacf0302008-06-17 15:12:00 +00005376 sqlite3_free(pCellKey);
drhe51c44f2004-05-30 20:46:09 +00005377 }
dan38fdead2014-04-01 10:19:02 +00005378 assert(
5379 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
dana7bf23c2014-05-02 17:12:41 +00005380 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
dan38fdead2014-04-01 10:19:02 +00005381 );
drhbb933ef2013-11-25 15:01:38 +00005382 if( c<0 ){
5383 lwr = idx+1;
5384 }else if( c>0 ){
5385 upr = idx-1;
5386 }else{
5387 assert( c==0 );
drh64022502009-01-09 14:11:04 +00005388 *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00005389 rc = SQLITE_OK;
drh75e96b32017-04-01 00:20:06 +00005390 pCur->ix = (u16)idx;
mistachkin88a79732017-09-04 19:31:54 +00005391 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
drh1e968a02008-03-25 00:22:21 +00005392 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00005393 }
drhebf10b12013-11-25 17:38:26 +00005394 if( lwr>upr ) break;
5395 assert( lwr+upr>=0 );
5396 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
drh72f82862001-05-24 21:06:34 +00005397 }
drh72f82862001-05-24 21:06:34 +00005398 }
drhb07028f2011-10-14 21:49:18 +00005399 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
danielk197771d5d2c2008-09-29 11:49:47 +00005400 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00005401 if( pPage->leaf ){
drh352a35a2017-08-15 03:46:47 +00005402 assert( pCur->ix<pCur->pPage->nCell );
drh75e96b32017-04-01 00:20:06 +00005403 pCur->ix = (u16)idx;
drhec3e6b12013-11-25 02:38:55 +00005404 *pRes = c;
5405 rc = SQLITE_OK;
5406 goto moveto_finish;
drhebf10b12013-11-25 17:38:26 +00005407 }
5408moveto_next_layer:
5409 if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00005410 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00005411 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00005412 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00005413 }
drh75e96b32017-04-01 00:20:06 +00005414 pCur->ix = (u16)lwr;
drh8178a752003-01-05 21:41:40 +00005415 rc = moveToChild(pCur, chldPg);
drhec3e6b12013-11-25 02:38:55 +00005416 if( rc ) break;
drh72f82862001-05-24 21:06:34 +00005417 }
drh1e968a02008-03-25 00:22:21 +00005418moveto_finish:
drhd2022b02013-11-25 16:23:52 +00005419 pCur->info.nSize = 0;
drhd95ef5c2016-11-11 18:19:05 +00005420 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
drhe63d9992008-08-13 19:11:48 +00005421 return rc;
5422}
5423
drhd677b3d2007-08-20 22:48:41 +00005424
drh72f82862001-05-24 21:06:34 +00005425/*
drhc39e0002004-05-07 23:50:57 +00005426** Return TRUE if the cursor is not pointing at an entry of the table.
5427**
5428** TRUE will be returned after a call to sqlite3BtreeNext() moves
5429** past the last entry in the table or sqlite3BtreePrev() moves past
5430** the first entry. TRUE is also returned if the table is empty.
5431*/
5432int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00005433 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
5434 ** have been deleted? This API will need to change to return an error code
5435 ** as well as the boolean result value.
5436 */
5437 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00005438}
5439
5440/*
drh5e98e832017-02-17 19:24:06 +00005441** Return an estimate for the number of rows in the table that pCur is
5442** pointing to. Return a negative number if no estimate is currently
5443** available.
5444*/
5445i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
5446 i64 n;
5447 u8 i;
5448
5449 assert( cursorOwnsBtShared(pCur) );
5450 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh555227b2017-02-23 02:15:33 +00005451
5452 /* Currently this interface is only called by the OP_IfSmaller
5453 ** opcode, and it that case the cursor will always be valid and
5454 ** will always point to a leaf node. */
5455 if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
drh352a35a2017-08-15 03:46:47 +00005456 if( NEVER(pCur->pPage->leaf==0) ) return -1;
drh555227b2017-02-23 02:15:33 +00005457
drh352a35a2017-08-15 03:46:47 +00005458 n = pCur->pPage->nCell;
5459 for(i=0; i<pCur->iPage; i++){
drh5e98e832017-02-17 19:24:06 +00005460 n *= pCur->apPage[i]->nCell;
5461 }
5462 return n;
5463}
5464
5465/*
drh2ab792e2017-05-30 18:34:07 +00005466** Advance the cursor to the next entry in the database.
5467** Return value:
5468**
5469** SQLITE_OK success
5470** SQLITE_DONE cursor is already pointing at the last element
5471** otherwise some kind of error occurred
drhe39a7322014-02-03 14:04:11 +00005472**
drhee6438d2014-09-01 13:29:32 +00005473** The main entry point is sqlite3BtreeNext(). That routine is optimized
5474** for the common case of merely incrementing the cell counter BtCursor.aiIdx
5475** to the next cell on the current page. The (slower) btreeNext() helper
5476** routine is called when it is necessary to move to a different page or
5477** to restore the cursor.
5478**
drh89997982017-07-11 18:11:33 +00005479** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
5480** cursor corresponds to an SQL index and this routine could have been
5481** skipped if the SQL index had been a unique index. The F argument
5482** is a hint to the implement. SQLite btree implementation does not use
5483** this hint, but COMDB2 does.
drh72f82862001-05-24 21:06:34 +00005484*/
drh89997982017-07-11 18:11:33 +00005485static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00005486 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00005487 int idx;
danielk197797a227c2006-01-20 16:32:04 +00005488 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00005489
dan7a2347e2016-01-07 16:43:54 +00005490 assert( cursorOwnsBtShared(pCur) );
drh9b47ee32013-08-20 03:13:51 +00005491 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
drhf66f26a2013-08-19 20:04:10 +00005492 if( pCur->eState!=CURSOR_VALID ){
drhee6438d2014-09-01 13:29:32 +00005493 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
drhf66f26a2013-08-19 20:04:10 +00005494 rc = restoreCursorPosition(pCur);
5495 if( rc!=SQLITE_OK ){
5496 return rc;
5497 }
5498 if( CURSOR_INVALID==pCur->eState ){
drh2ab792e2017-05-30 18:34:07 +00005499 return SQLITE_DONE;
drhf66f26a2013-08-19 20:04:10 +00005500 }
drh9b47ee32013-08-20 03:13:51 +00005501 if( pCur->skipNext ){
5502 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5503 pCur->eState = CURSOR_VALID;
5504 if( pCur->skipNext>0 ){
5505 pCur->skipNext = 0;
drh9b47ee32013-08-20 03:13:51 +00005506 return SQLITE_OK;
5507 }
drhf66f26a2013-08-19 20:04:10 +00005508 pCur->skipNext = 0;
drhf66f26a2013-08-19 20:04:10 +00005509 }
danielk1977da184232006-01-05 11:34:32 +00005510 }
danielk1977da184232006-01-05 11:34:32 +00005511
drh352a35a2017-08-15 03:46:47 +00005512 pPage = pCur->pPage;
drh75e96b32017-04-01 00:20:06 +00005513 idx = ++pCur->ix;
danielk197771d5d2c2008-09-29 11:49:47 +00005514 assert( pPage->isInit );
danbb246c42012-01-12 14:25:55 +00005515
5516 /* If the database file is corrupt, it is possible for the value of idx
5517 ** to be invalid here. This can only occur if a second cursor modifies
5518 ** the page while cursor pCur is holding a reference to it. Which can
5519 ** only happen if the database is corrupt in such a way as to link the
5520 ** page into more than one b-tree structure. */
5521 testcase( idx>pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00005522
danielk197771d5d2c2008-09-29 11:49:47 +00005523 if( idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00005524 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005525 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drhee6438d2014-09-01 13:29:32 +00005526 if( rc ) return rc;
5527 return moveToLeftmost(pCur);
drh72f82862001-05-24 21:06:34 +00005528 }
drh5e2f8b92001-05-28 00:41:15 +00005529 do{
danielk197771d5d2c2008-09-29 11:49:47 +00005530 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00005531 pCur->eState = CURSOR_INVALID;
drh2ab792e2017-05-30 18:34:07 +00005532 return SQLITE_DONE;
drh5e2f8b92001-05-28 00:41:15 +00005533 }
danielk197730548662009-07-09 05:07:37 +00005534 moveToParent(pCur);
drh352a35a2017-08-15 03:46:47 +00005535 pPage = pCur->pPage;
drh75e96b32017-04-01 00:20:06 +00005536 }while( pCur->ix>=pPage->nCell );
drh44845222008-07-17 18:39:57 +00005537 if( pPage->intKey ){
drh89997982017-07-11 18:11:33 +00005538 return sqlite3BtreeNext(pCur, 0);
drh8b18dd42004-05-12 19:18:15 +00005539 }else{
drhee6438d2014-09-01 13:29:32 +00005540 return SQLITE_OK;
drh8b18dd42004-05-12 19:18:15 +00005541 }
drh8178a752003-01-05 21:41:40 +00005542 }
drh3aac2dd2004-04-26 14:10:20 +00005543 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00005544 return SQLITE_OK;
drhee6438d2014-09-01 13:29:32 +00005545 }else{
5546 return moveToLeftmost(pCur);
drh72f82862001-05-24 21:06:34 +00005547 }
drh72f82862001-05-24 21:06:34 +00005548}
drh2ab792e2017-05-30 18:34:07 +00005549int sqlite3BtreeNext(BtCursor *pCur, int flags){
drhee6438d2014-09-01 13:29:32 +00005550 MemPage *pPage;
drh89997982017-07-11 18:11:33 +00005551 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
dan7a2347e2016-01-07 16:43:54 +00005552 assert( cursorOwnsBtShared(pCur) );
drh2ab792e2017-05-30 18:34:07 +00005553 assert( flags==0 || flags==1 );
drhee6438d2014-09-01 13:29:32 +00005554 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5555 pCur->info.nSize = 0;
5556 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drh89997982017-07-11 18:11:33 +00005557 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
drh352a35a2017-08-15 03:46:47 +00005558 pPage = pCur->pPage;
drh75e96b32017-04-01 00:20:06 +00005559 if( (++pCur->ix)>=pPage->nCell ){
5560 pCur->ix--;
drh89997982017-07-11 18:11:33 +00005561 return btreeNext(pCur);
drhee6438d2014-09-01 13:29:32 +00005562 }
5563 if( pPage->leaf ){
5564 return SQLITE_OK;
5565 }else{
5566 return moveToLeftmost(pCur);
5567 }
5568}
drh72f82862001-05-24 21:06:34 +00005569
drh3b7511c2001-05-26 13:15:44 +00005570/*
drh2ab792e2017-05-30 18:34:07 +00005571** Step the cursor to the back to the previous entry in the database.
5572** Return values:
5573**
5574** SQLITE_OK success
5575** SQLITE_DONE the cursor is already on the first element of the table
5576** otherwise some kind of error occurred
drhe39a7322014-02-03 14:04:11 +00005577**
drhee6438d2014-09-01 13:29:32 +00005578** The main entry point is sqlite3BtreePrevious(). That routine is optimized
5579** for the common case of merely decrementing the cell counter BtCursor.aiIdx
drh3f387402014-09-24 01:23:00 +00005580** to the previous cell on the current page. The (slower) btreePrevious()
5581** helper routine is called when it is necessary to move to a different page
5582** or to restore the cursor.
drhee6438d2014-09-01 13:29:32 +00005583**
drh89997982017-07-11 18:11:33 +00005584** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
5585** the cursor corresponds to an SQL index and this routine could have been
5586** skipped if the SQL index had been a unique index. The F argument is a
5587** hint to the implement. The native SQLite btree implementation does not
5588** use this hint, but COMDB2 does.
drh2dcc9aa2002-12-04 13:40:25 +00005589*/
drh89997982017-07-11 18:11:33 +00005590static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
drh2dcc9aa2002-12-04 13:40:25 +00005591 int rc;
drh8178a752003-01-05 21:41:40 +00005592 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00005593
dan7a2347e2016-01-07 16:43:54 +00005594 assert( cursorOwnsBtShared(pCur) );
drh9b47ee32013-08-20 03:13:51 +00005595 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
drhee6438d2014-09-01 13:29:32 +00005596 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
5597 assert( pCur->info.nSize==0 );
drhf66f26a2013-08-19 20:04:10 +00005598 if( pCur->eState!=CURSOR_VALID ){
drh7682a472014-09-29 15:00:28 +00005599 rc = restoreCursorPosition(pCur);
drhee6438d2014-09-01 13:29:32 +00005600 if( rc!=SQLITE_OK ){
5601 return rc;
drhf66f26a2013-08-19 20:04:10 +00005602 }
5603 if( CURSOR_INVALID==pCur->eState ){
drh2ab792e2017-05-30 18:34:07 +00005604 return SQLITE_DONE;
drhf66f26a2013-08-19 20:04:10 +00005605 }
drh9b47ee32013-08-20 03:13:51 +00005606 if( pCur->skipNext ){
5607 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5608 pCur->eState = CURSOR_VALID;
5609 if( pCur->skipNext<0 ){
5610 pCur->skipNext = 0;
drh9b47ee32013-08-20 03:13:51 +00005611 return SQLITE_OK;
5612 }
drhf66f26a2013-08-19 20:04:10 +00005613 pCur->skipNext = 0;
drhf66f26a2013-08-19 20:04:10 +00005614 }
danielk1977da184232006-01-05 11:34:32 +00005615 }
danielk1977da184232006-01-05 11:34:32 +00005616
drh352a35a2017-08-15 03:46:47 +00005617 pPage = pCur->pPage;
danielk197771d5d2c2008-09-29 11:49:47 +00005618 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00005619 if( !pPage->leaf ){
drh75e96b32017-04-01 00:20:06 +00005620 int idx = pCur->ix;
danielk197771d5d2c2008-09-29 11:49:47 +00005621 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
drhee6438d2014-09-01 13:29:32 +00005622 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00005623 rc = moveToRightmost(pCur);
5624 }else{
drh75e96b32017-04-01 00:20:06 +00005625 while( pCur->ix==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005626 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00005627 pCur->eState = CURSOR_INVALID;
drh2ab792e2017-05-30 18:34:07 +00005628 return SQLITE_DONE;
drh2dcc9aa2002-12-04 13:40:25 +00005629 }
danielk197730548662009-07-09 05:07:37 +00005630 moveToParent(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00005631 }
drhee6438d2014-09-01 13:29:32 +00005632 assert( pCur->info.nSize==0 );
drhd95ef5c2016-11-11 18:19:05 +00005633 assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00005634
drh75e96b32017-04-01 00:20:06 +00005635 pCur->ix--;
drh352a35a2017-08-15 03:46:47 +00005636 pPage = pCur->pPage;
drh44845222008-07-17 18:39:57 +00005637 if( pPage->intKey && !pPage->leaf ){
drh89997982017-07-11 18:11:33 +00005638 rc = sqlite3BtreePrevious(pCur, 0);
drh8b18dd42004-05-12 19:18:15 +00005639 }else{
5640 rc = SQLITE_OK;
5641 }
drh2dcc9aa2002-12-04 13:40:25 +00005642 }
drh2dcc9aa2002-12-04 13:40:25 +00005643 return rc;
5644}
drh2ab792e2017-05-30 18:34:07 +00005645int sqlite3BtreePrevious(BtCursor *pCur, int flags){
dan7a2347e2016-01-07 16:43:54 +00005646 assert( cursorOwnsBtShared(pCur) );
drh2ab792e2017-05-30 18:34:07 +00005647 assert( flags==0 || flags==1 );
drhee6438d2014-09-01 13:29:32 +00005648 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
drh89997982017-07-11 18:11:33 +00005649 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
drhee6438d2014-09-01 13:29:32 +00005650 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
5651 pCur->info.nSize = 0;
5652 if( pCur->eState!=CURSOR_VALID
drh75e96b32017-04-01 00:20:06 +00005653 || pCur->ix==0
drh352a35a2017-08-15 03:46:47 +00005654 || pCur->pPage->leaf==0
drhee6438d2014-09-01 13:29:32 +00005655 ){
drh89997982017-07-11 18:11:33 +00005656 return btreePrevious(pCur);
drhee6438d2014-09-01 13:29:32 +00005657 }
drh75e96b32017-04-01 00:20:06 +00005658 pCur->ix--;
drhee6438d2014-09-01 13:29:32 +00005659 return SQLITE_OK;
5660}
drh2dcc9aa2002-12-04 13:40:25 +00005661
5662/*
drh3b7511c2001-05-26 13:15:44 +00005663** Allocate a new page from the database file.
5664**
danielk19773b8a05f2007-03-19 17:44:26 +00005665** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00005666** has already been called on the new page.) The new page has also
5667** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00005668** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00005669**
5670** SQLITE_OK is returned on success. Any other return value indicates
drh1c8bade2015-05-29 18:42:11 +00005671** an error. *ppPage is set to NULL in the event of an error.
drhbea00b92002-07-08 10:59:50 +00005672**
drh82e647d2013-03-02 03:25:55 +00005673** If the "nearby" parameter is not 0, then an effort is made to
drh199e3cf2002-07-18 11:01:47 +00005674** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00005675** attempt to keep related pages close to each other in the database file,
5676** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00005677**
drh82e647d2013-03-02 03:25:55 +00005678** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
5679** anywhere on the free-list, then it is guaranteed to be returned. If
5680** eMode is BTALLOC_LT then the page returned will be less than or equal
5681** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
5682** are no restrictions on which page is returned.
drh3b7511c2001-05-26 13:15:44 +00005683*/
drh4f0c5872007-03-26 22:05:01 +00005684static int allocateBtreePage(
drh82e647d2013-03-02 03:25:55 +00005685 BtShared *pBt, /* The btree */
5686 MemPage **ppPage, /* Store pointer to the allocated page here */
5687 Pgno *pPgno, /* Store the page number here */
5688 Pgno nearby, /* Search for a page near this one */
5689 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005690){
drh3aac2dd2004-04-26 14:10:20 +00005691 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00005692 int rc;
drh35cd6432009-06-05 14:17:21 +00005693 u32 n; /* Number of pages on the freelist */
drh042d6a12009-06-17 13:57:16 +00005694 u32 k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00005695 MemPage *pTrunk = 0;
5696 MemPage *pPrevTrunk = 0;
drh1662b5a2009-06-04 19:06:09 +00005697 Pgno mxPage; /* Total size of the database file */
drh30e58752002-03-02 20:41:57 +00005698
drh1fee73e2007-08-29 04:00:57 +00005699 assert( sqlite3_mutex_held(pBt->mutex) );
dan09ff9e12013-03-11 11:49:03 +00005700 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
drh3aac2dd2004-04-26 14:10:20 +00005701 pPage1 = pBt->pPage1;
drhb1299152010-03-30 22:58:33 +00005702 mxPage = btreePagecount(pBt);
drh113762a2014-11-19 16:36:25 +00005703 /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
5704 ** stores stores the total number of pages on the freelist. */
drh3aac2dd2004-04-26 14:10:20 +00005705 n = get4byte(&pPage1->aData[36]);
drhdf35a082009-07-09 02:24:35 +00005706 testcase( n==mxPage-1 );
5707 if( n>=mxPage ){
drh1662b5a2009-06-04 19:06:09 +00005708 return SQLITE_CORRUPT_BKPT;
5709 }
drh3aac2dd2004-04-26 14:10:20 +00005710 if( n>0 ){
drh91025292004-05-03 19:49:32 +00005711 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005712 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005713 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
drhc6e956f2015-06-24 13:32:10 +00005714 u32 nSearch = 0; /* Count of the number of search attempts */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005715
drh82e647d2013-03-02 03:25:55 +00005716 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00005717 ** shows that the page 'nearby' is somewhere on the free-list, then
5718 ** the entire-list will be searched for that page.
5719 */
5720#ifndef SQLITE_OMIT_AUTOVACUUM
dan51f0b6d2013-02-22 20:16:34 +00005721 if( eMode==BTALLOC_EXACT ){
5722 if( nearby<=mxPage ){
5723 u8 eType;
5724 assert( nearby>0 );
5725 assert( pBt->autoVacuum );
5726 rc = ptrmapGet(pBt, nearby, &eType, 0);
5727 if( rc ) return rc;
5728 if( eType==PTRMAP_FREEPAGE ){
5729 searchList = 1;
5730 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005731 }
dan51f0b6d2013-02-22 20:16:34 +00005732 }else if( eMode==BTALLOC_LE ){
5733 searchList = 1;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005734 }
5735#endif
5736
5737 /* Decrement the free-list count by 1. Set iTrunk to the index of the
5738 ** first free-list trunk page. iPrevTrunk is initially 1.
5739 */
danielk19773b8a05f2007-03-19 17:44:26 +00005740 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00005741 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00005742 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005743
5744 /* The code within this loop is run only once if the 'searchList' variable
5745 ** is not true. Otherwise, it runs once for each trunk-page on the
drh82e647d2013-03-02 03:25:55 +00005746 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
5747 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
danielk1977cb1a7eb2004-11-05 12:27:02 +00005748 */
5749 do {
5750 pPrevTrunk = pTrunk;
5751 if( pPrevTrunk ){
drh113762a2014-11-19 16:36:25 +00005752 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
5753 ** is the page number of the next freelist trunk page in the list or
5754 ** zero if this is the last freelist trunk page. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005755 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00005756 }else{
drh113762a2014-11-19 16:36:25 +00005757 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
5758 ** stores the page number of the first page of the freelist, or zero if
5759 ** the freelist is empty. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005760 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00005761 }
drhdf35a082009-07-09 02:24:35 +00005762 testcase( iTrunk==mxPage );
drh9e7804d2015-06-24 12:24:03 +00005763 if( iTrunk>mxPage || nSearch++ > n ){
drhc62aab52017-06-11 18:26:15 +00005764 rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
drh1662b5a2009-06-04 19:06:09 +00005765 }else{
drh7e8c6f12015-05-28 03:28:27 +00005766 rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
drh1662b5a2009-06-04 19:06:09 +00005767 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005768 if( rc ){
drhd3627af2006-12-18 18:34:51 +00005769 pTrunk = 0;
5770 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005771 }
drhb07028f2011-10-14 21:49:18 +00005772 assert( pTrunk!=0 );
5773 assert( pTrunk->aData!=0 );
drh113762a2014-11-19 16:36:25 +00005774 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
5775 ** is the number of leaf page pointers to follow. */
5776 k = get4byte(&pTrunk->aData[4]);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005777 if( k==0 && !searchList ){
5778 /* The trunk has no leaves and the list is not being searched.
5779 ** So extract the trunk page itself and use it as the newly
5780 ** allocated page */
5781 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00005782 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00005783 if( rc ){
5784 goto end_allocate_page;
5785 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005786 *pPgno = iTrunk;
5787 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5788 *ppPage = pTrunk;
5789 pTrunk = 0;
5790 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh042d6a12009-06-17 13:57:16 +00005791 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00005792 /* Value of k is out of range. Database corruption */
drhcc97ca42017-06-07 22:32:59 +00005793 rc = SQLITE_CORRUPT_PGNO(iTrunk);
drhd3627af2006-12-18 18:34:51 +00005794 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005795#ifndef SQLITE_OMIT_AUTOVACUUM
dan51f0b6d2013-02-22 20:16:34 +00005796 }else if( searchList
5797 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
5798 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00005799 /* The list is being searched and this trunk page is the page
5800 ** to allocate, regardless of whether it has leaves.
5801 */
dan51f0b6d2013-02-22 20:16:34 +00005802 *pPgno = iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005803 *ppPage = pTrunk;
5804 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005805 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00005806 if( rc ){
5807 goto end_allocate_page;
5808 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005809 if( k==0 ){
5810 if( !pPrevTrunk ){
5811 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5812 }else{
danf48c3552010-08-23 15:41:24 +00005813 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
5814 if( rc!=SQLITE_OK ){
5815 goto end_allocate_page;
5816 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005817 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
5818 }
5819 }else{
5820 /* The trunk page is required by the caller but it contains
5821 ** pointers to free-list leaves. The first leaf becomes a trunk
5822 ** page in this case.
5823 */
5824 MemPage *pNewTrunk;
5825 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh1662b5a2009-06-04 19:06:09 +00005826 if( iNewTrunk>mxPage ){
drhcc97ca42017-06-07 22:32:59 +00005827 rc = SQLITE_CORRUPT_PGNO(iTrunk);
drh1662b5a2009-06-04 19:06:09 +00005828 goto end_allocate_page;
5829 }
drhdf35a082009-07-09 02:24:35 +00005830 testcase( iNewTrunk==mxPage );
drh7e8c6f12015-05-28 03:28:27 +00005831 rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005832 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00005833 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005834 }
danielk19773b8a05f2007-03-19 17:44:26 +00005835 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005836 if( rc!=SQLITE_OK ){
5837 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00005838 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005839 }
5840 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
5841 put4byte(&pNewTrunk->aData[4], k-1);
5842 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00005843 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005844 if( !pPrevTrunk ){
drhc5053fb2008-11-27 02:22:10 +00005845 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
danielk1977cb1a7eb2004-11-05 12:27:02 +00005846 put4byte(&pPage1->aData[32], iNewTrunk);
5847 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00005848 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00005849 if( rc ){
5850 goto end_allocate_page;
5851 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005852 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
5853 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005854 }
5855 pTrunk = 0;
5856 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
5857#endif
danielk1977e5765212009-06-17 11:13:28 +00005858 }else if( k>0 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00005859 /* Extract a leaf from the trunk */
drh042d6a12009-06-17 13:57:16 +00005860 u32 closest;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005861 Pgno iPage;
5862 unsigned char *aData = pTrunk->aData;
5863 if( nearby>0 ){
drh042d6a12009-06-17 13:57:16 +00005864 u32 i;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005865 closest = 0;
danf38b65a2013-02-22 20:57:47 +00005866 if( eMode==BTALLOC_LE ){
5867 for(i=0; i<k; i++){
5868 iPage = get4byte(&aData[8+i*4]);
dan87ade192013-02-23 17:49:16 +00005869 if( iPage<=nearby ){
danf38b65a2013-02-22 20:57:47 +00005870 closest = i;
5871 break;
5872 }
5873 }
5874 }else{
5875 int dist;
5876 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
5877 for(i=1; i<k; i++){
5878 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
5879 if( d2<dist ){
5880 closest = i;
5881 dist = d2;
5882 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005883 }
5884 }
5885 }else{
5886 closest = 0;
5887 }
5888
5889 iPage = get4byte(&aData[8+closest*4]);
drhdf35a082009-07-09 02:24:35 +00005890 testcase( iPage==mxPage );
drh1662b5a2009-06-04 19:06:09 +00005891 if( iPage>mxPage ){
drhcc97ca42017-06-07 22:32:59 +00005892 rc = SQLITE_CORRUPT_PGNO(iTrunk);
drh1662b5a2009-06-04 19:06:09 +00005893 goto end_allocate_page;
5894 }
drhdf35a082009-07-09 02:24:35 +00005895 testcase( iPage==mxPage );
dan51f0b6d2013-02-22 20:16:34 +00005896 if( !searchList
5897 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
5898 ){
danielk1977bea2a942009-01-20 17:06:27 +00005899 int noContent;
shane1f9e6aa2008-06-09 19:27:11 +00005900 *pPgno = iPage;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005901 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
5902 ": %d more free pages\n",
5903 *pPgno, closest+1, k, pTrunk->pgno, n-1));
drh93b4fc72011-04-07 14:47:01 +00005904 rc = sqlite3PagerWrite(pTrunk->pDbPage);
5905 if( rc ) goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005906 if( closest<k-1 ){
5907 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
5908 }
5909 put4byte(&aData[4], k-1);
drh3f387402014-09-24 01:23:00 +00005910 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
drh7e8c6f12015-05-28 03:28:27 +00005911 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005912 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00005913 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00005914 if( rc!=SQLITE_OK ){
5915 releasePage(*ppPage);
drh1c8bade2015-05-29 18:42:11 +00005916 *ppPage = 0;
danielk1977aac0a382005-01-16 11:07:06 +00005917 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005918 }
5919 searchList = 0;
5920 }
drhee696e22004-08-30 16:52:17 +00005921 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005922 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00005923 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005924 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00005925 }else{
danbc1a3c62013-02-23 16:40:46 +00005926 /* There are no pages on the freelist, so append a new page to the
5927 ** database image.
5928 **
5929 ** Normally, new pages allocated by this block can be requested from the
5930 ** pager layer with the 'no-content' flag set. This prevents the pager
5931 ** from trying to read the pages content from disk. However, if the
5932 ** current transaction has already run one or more incremental-vacuum
5933 ** steps, then the page we are about to allocate may contain content
5934 ** that is required in the event of a rollback. In this case, do
5935 ** not set the no-content flag. This causes the pager to load and journal
5936 ** the current page content before overwriting it.
5937 **
5938 ** Note that the pager will not actually attempt to load or journal
5939 ** content for any page that really does lie past the end of the database
5940 ** file on disk. So the effects of disabling the no-content optimization
5941 ** here are confined to those pages that lie between the end of the
5942 ** database image and the end of the database file.
5943 */
drh3f387402014-09-24 01:23:00 +00005944 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
danbc1a3c62013-02-23 16:40:46 +00005945
drhdd3cd972010-03-27 17:12:36 +00005946 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
5947 if( rc ) return rc;
5948 pBt->nPage++;
5949 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
danielk1977bea2a942009-01-20 17:06:27 +00005950
danielk1977afcdd022004-10-31 16:25:42 +00005951#ifndef SQLITE_OMIT_AUTOVACUUM
drhdd3cd972010-03-27 17:12:36 +00005952 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
danielk1977afcdd022004-10-31 16:25:42 +00005953 /* If *pPgno refers to a pointer-map page, allocate two new pages
5954 ** at the end of the file instead of one. The first allocated page
5955 ** becomes a new pointer-map page, the second is used by the caller.
5956 */
danielk1977ac861692009-03-28 10:54:22 +00005957 MemPage *pPg = 0;
drhdd3cd972010-03-27 17:12:36 +00005958 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
5959 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
drh7e8c6f12015-05-28 03:28:27 +00005960 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
danielk1977ac861692009-03-28 10:54:22 +00005961 if( rc==SQLITE_OK ){
5962 rc = sqlite3PagerWrite(pPg->pDbPage);
5963 releasePage(pPg);
5964 }
5965 if( rc ) return rc;
drhdd3cd972010-03-27 17:12:36 +00005966 pBt->nPage++;
5967 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
danielk1977afcdd022004-10-31 16:25:42 +00005968 }
5969#endif
drhdd3cd972010-03-27 17:12:36 +00005970 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
5971 *pPgno = pBt->nPage;
danielk1977afcdd022004-10-31 16:25:42 +00005972
danielk1977599fcba2004-11-08 07:13:13 +00005973 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh7e8c6f12015-05-28 03:28:27 +00005974 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
drh3b7511c2001-05-26 13:15:44 +00005975 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00005976 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00005977 if( rc!=SQLITE_OK ){
5978 releasePage(*ppPage);
drh7e8c6f12015-05-28 03:28:27 +00005979 *ppPage = 0;
danielk1977aac0a382005-01-16 11:07:06 +00005980 }
drh3a4c1412004-05-09 20:40:11 +00005981 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00005982 }
danielk1977599fcba2004-11-08 07:13:13 +00005983
5984 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00005985
5986end_allocate_page:
5987 releasePage(pTrunk);
5988 releasePage(pPrevTrunk);
drh7e8c6f12015-05-28 03:28:27 +00005989 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
5990 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
drh3b7511c2001-05-26 13:15:44 +00005991 return rc;
5992}
5993
5994/*
danielk1977bea2a942009-01-20 17:06:27 +00005995** This function is used to add page iPage to the database file free-list.
5996** It is assumed that the page is not already a part of the free-list.
drh5e2f8b92001-05-28 00:41:15 +00005997**
danielk1977bea2a942009-01-20 17:06:27 +00005998** The value passed as the second argument to this function is optional.
5999** If the caller happens to have a pointer to the MemPage object
6000** corresponding to page iPage handy, it may pass it as the second value.
6001** Otherwise, it may pass NULL.
6002**
6003** If a pointer to a MemPage object is passed as the second argument,
6004** its reference count is not altered by this function.
drh3b7511c2001-05-26 13:15:44 +00006005*/
danielk1977bea2a942009-01-20 17:06:27 +00006006static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
6007 MemPage *pTrunk = 0; /* Free-list trunk page */
6008 Pgno iTrunk = 0; /* Page number of free-list trunk page */
6009 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
6010 MemPage *pPage; /* Page being freed. May be NULL. */
6011 int rc; /* Return Code */
6012 int nFree; /* Initial number of pages on free-list */
drh8b2f49b2001-06-08 00:21:52 +00006013
danielk1977bea2a942009-01-20 17:06:27 +00006014 assert( sqlite3_mutex_held(pBt->mutex) );
danfb0246b2015-05-26 12:18:17 +00006015 assert( CORRUPT_DB || iPage>1 );
danielk1977bea2a942009-01-20 17:06:27 +00006016 assert( !pMemPage || pMemPage->pgno==iPage );
6017
danfb0246b2015-05-26 12:18:17 +00006018 if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
danielk1977bea2a942009-01-20 17:06:27 +00006019 if( pMemPage ){
6020 pPage = pMemPage;
6021 sqlite3PagerRef(pPage->pDbPage);
6022 }else{
6023 pPage = btreePageLookup(pBt, iPage);
6024 }
drh3aac2dd2004-04-26 14:10:20 +00006025
drha34b6762004-05-07 13:30:42 +00006026 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00006027 rc = sqlite3PagerWrite(pPage1->pDbPage);
danielk1977bea2a942009-01-20 17:06:27 +00006028 if( rc ) goto freepage_out;
6029 nFree = get4byte(&pPage1->aData[36]);
6030 put4byte(&pPage1->aData[36], nFree+1);
drh3aac2dd2004-04-26 14:10:20 +00006031
drhc9166342012-01-05 23:32:06 +00006032 if( pBt->btsFlags & BTS_SECURE_DELETE ){
drh5b47efa2010-02-12 18:18:39 +00006033 /* If the secure_delete option is enabled, then
6034 ** always fully overwrite deleted information with zeros.
6035 */
drhb00fc3b2013-08-21 23:42:32 +00006036 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
shaneh84f4b2f2010-02-26 01:46:54 +00006037 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
drh5b47efa2010-02-12 18:18:39 +00006038 ){
6039 goto freepage_out;
6040 }
6041 memset(pPage->aData, 0, pPage->pBt->pageSize);
danielk1977bea2a942009-01-20 17:06:27 +00006042 }
drhfcce93f2006-02-22 03:08:32 +00006043
danielk1977687566d2004-11-02 12:56:41 +00006044 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00006045 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00006046 */
danielk197785d90ca2008-07-19 14:25:15 +00006047 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00006048 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
danielk1977bea2a942009-01-20 17:06:27 +00006049 if( rc ) goto freepage_out;
danielk1977687566d2004-11-02 12:56:41 +00006050 }
danielk1977687566d2004-11-02 12:56:41 +00006051
danielk1977bea2a942009-01-20 17:06:27 +00006052 /* Now manipulate the actual database free-list structure. There are two
6053 ** possibilities. If the free-list is currently empty, or if the first
6054 ** trunk page in the free-list is full, then this page will become a
6055 ** new free-list trunk page. Otherwise, it will become a leaf of the
6056 ** first trunk page in the current free-list. This block tests if it
6057 ** is possible to add the page as a new free-list leaf.
6058 */
6059 if( nFree!=0 ){
drhc046e3e2009-07-15 11:26:44 +00006060 u32 nLeaf; /* Initial number of leaf cells on trunk page */
danielk1977bea2a942009-01-20 17:06:27 +00006061
6062 iTrunk = get4byte(&pPage1->aData[32]);
drhb00fc3b2013-08-21 23:42:32 +00006063 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977bea2a942009-01-20 17:06:27 +00006064 if( rc!=SQLITE_OK ){
6065 goto freepage_out;
6066 }
6067
6068 nLeaf = get4byte(&pTrunk->aData[4]);
drheeb844a2009-08-08 18:01:07 +00006069 assert( pBt->usableSize>32 );
6070 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
danielk1977bea2a942009-01-20 17:06:27 +00006071 rc = SQLITE_CORRUPT_BKPT;
6072 goto freepage_out;
6073 }
drheeb844a2009-08-08 18:01:07 +00006074 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
danielk1977bea2a942009-01-20 17:06:27 +00006075 /* In this case there is room on the trunk page to insert the page
6076 ** being freed as a new leaf.
drh45b1fac2008-07-04 17:52:42 +00006077 **
6078 ** Note that the trunk page is not really full until it contains
6079 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
6080 ** coded. But due to a coding error in versions of SQLite prior to
6081 ** 3.6.0, databases with freelist trunk pages holding more than
6082 ** usableSize/4 - 8 entries will be reported as corrupt. In order
6083 ** to maintain backwards compatibility with older versions of SQLite,
drhc046e3e2009-07-15 11:26:44 +00006084 ** we will continue to restrict the number of entries to usableSize/4 - 8
drh45b1fac2008-07-04 17:52:42 +00006085 ** for now. At some point in the future (once everyone has upgraded
6086 ** to 3.6.0 or later) we should consider fixing the conditional above
6087 ** to read "usableSize/4-2" instead of "usableSize/4-8".
drh113762a2014-11-19 16:36:25 +00006088 **
6089 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
6090 ** avoid using the last six entries in the freelist trunk page array in
6091 ** order that database files created by newer versions of SQLite can be
6092 ** read by older versions of SQLite.
drh45b1fac2008-07-04 17:52:42 +00006093 */
danielk19773b8a05f2007-03-19 17:44:26 +00006094 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00006095 if( rc==SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00006096 put4byte(&pTrunk->aData[4], nLeaf+1);
6097 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
drhc9166342012-01-05 23:32:06 +00006098 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
danielk1977bea2a942009-01-20 17:06:27 +00006099 sqlite3PagerDontWrite(pPage->pDbPage);
6100 }
danielk1977bea2a942009-01-20 17:06:27 +00006101 rc = btreeSetHasContent(pBt, iPage);
drhf5345442007-04-09 12:45:02 +00006102 }
drh3a4c1412004-05-09 20:40:11 +00006103 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
danielk1977bea2a942009-01-20 17:06:27 +00006104 goto freepage_out;
drh3aac2dd2004-04-26 14:10:20 +00006105 }
drh3b7511c2001-05-26 13:15:44 +00006106 }
danielk1977bea2a942009-01-20 17:06:27 +00006107
6108 /* If control flows to this point, then it was not possible to add the
6109 ** the page being freed as a leaf page of the first trunk in the free-list.
6110 ** Possibly because the free-list is empty, or possibly because the
6111 ** first trunk in the free-list is full. Either way, the page being freed
6112 ** will become the new first trunk page in the free-list.
6113 */
drhb00fc3b2013-08-21 23:42:32 +00006114 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
drhc046e3e2009-07-15 11:26:44 +00006115 goto freepage_out;
6116 }
6117 rc = sqlite3PagerWrite(pPage->pDbPage);
6118 if( rc!=SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00006119 goto freepage_out;
6120 }
6121 put4byte(pPage->aData, iTrunk);
6122 put4byte(&pPage->aData[4], 0);
6123 put4byte(&pPage1->aData[32], iPage);
6124 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
6125
6126freepage_out:
6127 if( pPage ){
6128 pPage->isInit = 0;
6129 }
6130 releasePage(pPage);
6131 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00006132 return rc;
6133}
drhc314dc72009-07-21 11:52:34 +00006134static void freePage(MemPage *pPage, int *pRC){
6135 if( (*pRC)==SQLITE_OK ){
6136 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
6137 }
danielk1977bea2a942009-01-20 17:06:27 +00006138}
drh3b7511c2001-05-26 13:15:44 +00006139
6140/*
drh9bfdc252014-09-24 02:05:41 +00006141** Free any overflow pages associated with the given Cell. Write the
6142** local Cell size (the number of bytes on the original page, omitting
6143** overflow) into *pnSize.
drh3b7511c2001-05-26 13:15:44 +00006144*/
drh9bfdc252014-09-24 02:05:41 +00006145static int clearCell(
6146 MemPage *pPage, /* The page that contains the Cell */
6147 unsigned char *pCell, /* First byte of the Cell */
drh80159da2016-12-09 17:32:51 +00006148 CellInfo *pInfo /* Size information about the cell */
drh9bfdc252014-09-24 02:05:41 +00006149){
drh60172a52017-08-02 18:27:50 +00006150 BtShared *pBt;
drh3aac2dd2004-04-26 14:10:20 +00006151 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00006152 int rc;
drh94440812007-03-06 11:42:19 +00006153 int nOvfl;
shaneh1df2db72010-08-18 02:28:48 +00006154 u32 ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00006155
drh1fee73e2007-08-29 04:00:57 +00006156 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh80159da2016-12-09 17:32:51 +00006157 pPage->xParseCell(pPage, pCell, pInfo);
6158 if( pInfo->nLocal==pInfo->nPayload ){
drha34b6762004-05-07 13:30:42 +00006159 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00006160 }
drh80159da2016-12-09 17:32:51 +00006161 if( pCell+pInfo->nSize-1 > pPage->aData+pPage->maskPage ){
drhcc97ca42017-06-07 22:32:59 +00006162 /* Cell extends past end of page */
6163 return SQLITE_CORRUPT_PGNO(pPage->pgno);
drhe42a9b42011-08-31 13:27:19 +00006164 }
drh80159da2016-12-09 17:32:51 +00006165 ovflPgno = get4byte(pCell + pInfo->nSize - 4);
drh60172a52017-08-02 18:27:50 +00006166 pBt = pPage->pBt;
shane63207ab2009-02-04 01:49:30 +00006167 assert( pBt->usableSize > 4 );
drh94440812007-03-06 11:42:19 +00006168 ovflPageSize = pBt->usableSize - 4;
drh80159da2016-12-09 17:32:51 +00006169 nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
dan0f8076d2015-05-25 18:47:26 +00006170 assert( nOvfl>0 ||
drh80159da2016-12-09 17:32:51 +00006171 (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
dan0f8076d2015-05-25 18:47:26 +00006172 );
drh72365832007-03-06 15:53:44 +00006173 while( nOvfl-- ){
shane63207ab2009-02-04 01:49:30 +00006174 Pgno iNext = 0;
danielk1977bea2a942009-01-20 17:06:27 +00006175 MemPage *pOvfl = 0;
drhb1299152010-03-30 22:58:33 +00006176 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
danielk1977e589a672009-04-11 16:06:15 +00006177 /* 0 is not a legal page number and page 1 cannot be an
6178 ** overflow page. Therefore if ovflPgno<2 or past the end of the
6179 ** file the database must be corrupt. */
drh49285702005-09-17 15:20:26 +00006180 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00006181 }
danielk1977bea2a942009-01-20 17:06:27 +00006182 if( nOvfl ){
6183 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
6184 if( rc ) return rc;
6185 }
dan887d4b22010-02-25 12:09:16 +00006186
shaneh1da207e2010-03-09 14:41:12 +00006187 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
dan887d4b22010-02-25 12:09:16 +00006188 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
6189 ){
6190 /* There is no reason any cursor should have an outstanding reference
6191 ** to an overflow page belonging to a cell that is being deleted/updated.
6192 ** So if there exists more than one reference to this page, then it
6193 ** must not really be an overflow page and the database must be corrupt.
6194 ** It is helpful to detect this before calling freePage2(), as
6195 ** freePage2() may zero the page contents if secure-delete mode is
6196 ** enabled. If this 'overflow' page happens to be a page that the
6197 ** caller is iterating through or using in some other way, this
6198 ** can be problematic.
6199 */
6200 rc = SQLITE_CORRUPT_BKPT;
6201 }else{
6202 rc = freePage2(pBt, pOvfl, ovflPgno);
6203 }
6204
danielk1977bea2a942009-01-20 17:06:27 +00006205 if( pOvfl ){
6206 sqlite3PagerUnref(pOvfl->pDbPage);
6207 }
drh3b7511c2001-05-26 13:15:44 +00006208 if( rc ) return rc;
danielk1977bea2a942009-01-20 17:06:27 +00006209 ovflPgno = iNext;
drh3b7511c2001-05-26 13:15:44 +00006210 }
drh5e2f8b92001-05-28 00:41:15 +00006211 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00006212}
6213
6214/*
drh91025292004-05-03 19:49:32 +00006215** Create the byte sequence used to represent a cell on page pPage
6216** and write that byte sequence into pCell[]. Overflow pages are
6217** allocated and filled in as necessary. The calling procedure
6218** is responsible for making sure sufficient space has been allocated
6219** for pCell[].
6220**
6221** Note that pCell does not necessary need to point to the pPage->aData
6222** area. pCell might point to some temporary storage. The cell will
6223** be constructed in this temporary area then copied into pPage->aData
6224** later.
drh3b7511c2001-05-26 13:15:44 +00006225*/
6226static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00006227 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00006228 unsigned char *pCell, /* Complete text of the cell */
drh8eeb4462016-05-21 20:03:42 +00006229 const BtreePayload *pX, /* Payload with which to construct the cell */
drh4b70f112004-05-02 21:12:19 +00006230 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00006231){
drh3b7511c2001-05-26 13:15:44 +00006232 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00006233 const u8 *pSrc;
drh5e27e1d2017-08-23 14:45:59 +00006234 int nSrc, n, rc, mn;
drh3aac2dd2004-04-26 14:10:20 +00006235 int spaceLeft;
drh5e27e1d2017-08-23 14:45:59 +00006236 MemPage *pToRelease;
drh3aac2dd2004-04-26 14:10:20 +00006237 unsigned char *pPrior;
6238 unsigned char *pPayload;
drh5e27e1d2017-08-23 14:45:59 +00006239 BtShared *pBt;
6240 Pgno pgnoOvfl;
drh4b70f112004-05-02 21:12:19 +00006241 int nHeader;
drh3b7511c2001-05-26 13:15:44 +00006242
drh1fee73e2007-08-29 04:00:57 +00006243 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00006244
drhc5053fb2008-11-27 02:22:10 +00006245 /* pPage is not necessarily writeable since pCell might be auxiliary
6246 ** buffer space that is separate from the pPage buffer area */
drh5e27e1d2017-08-23 14:45:59 +00006247 assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
drhc5053fb2008-11-27 02:22:10 +00006248 || sqlite3PagerIswriteable(pPage->pDbPage) );
6249
drh91025292004-05-03 19:49:32 +00006250 /* Fill in the header. */
drh6200c882014-09-23 22:36:25 +00006251 nHeader = pPage->childPtrSize;
drhdfc2daa2016-05-21 23:25:29 +00006252 if( pPage->intKey ){
6253 nPayload = pX->nData + pX->nZero;
6254 pSrc = pX->pData;
6255 nSrc = pX->nData;
6256 assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
drh6200c882014-09-23 22:36:25 +00006257 nHeader += putVarint32(&pCell[nHeader], nPayload);
drhdfc2daa2016-05-21 23:25:29 +00006258 nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
drh6f11bef2004-05-13 01:12:56 +00006259 }else{
drh8eeb4462016-05-21 20:03:42 +00006260 assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
6261 nSrc = nPayload = (int)pX->nKey;
6262 pSrc = pX->pKey;
drhdfc2daa2016-05-21 23:25:29 +00006263 nHeader += putVarint32(&pCell[nHeader], nPayload);
drh3aac2dd2004-04-26 14:10:20 +00006264 }
drhdfc2daa2016-05-21 23:25:29 +00006265
6266 /* Fill in the payload */
drh5e27e1d2017-08-23 14:45:59 +00006267 pPayload = &pCell[nHeader];
drh6200c882014-09-23 22:36:25 +00006268 if( nPayload<=pPage->maxLocal ){
drh5e27e1d2017-08-23 14:45:59 +00006269 /* This is the common case where everything fits on the btree page
6270 ** and no overflow pages are required. */
drh6200c882014-09-23 22:36:25 +00006271 n = nHeader + nPayload;
6272 testcase( n==3 );
6273 testcase( n==4 );
6274 if( n<4 ) n = 4;
6275 *pnSize = n;
drh5e27e1d2017-08-23 14:45:59 +00006276 assert( nSrc<=nPayload );
6277 testcase( nSrc<nPayload );
6278 memcpy(pPayload, pSrc, nSrc);
6279 memset(pPayload+nSrc, 0, nPayload-nSrc);
6280 return SQLITE_OK;
drh6200c882014-09-23 22:36:25 +00006281 }
drh5e27e1d2017-08-23 14:45:59 +00006282
6283 /* If we reach this point, it means that some of the content will need
6284 ** to spill onto overflow pages.
6285 */
6286 mn = pPage->minLocal;
6287 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
6288 testcase( n==pPage->maxLocal );
6289 testcase( n==pPage->maxLocal+1 );
6290 if( n > pPage->maxLocal ) n = mn;
6291 spaceLeft = n;
6292 *pnSize = n + nHeader + 4;
6293 pPrior = &pCell[nHeader+n];
6294 pToRelease = 0;
6295 pgnoOvfl = 0;
6296 pBt = pPage->pBt;
drh3b7511c2001-05-26 13:15:44 +00006297
drh6200c882014-09-23 22:36:25 +00006298 /* At this point variables should be set as follows:
6299 **
6300 ** nPayload Total payload size in bytes
6301 ** pPayload Begin writing payload here
6302 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
6303 ** that means content must spill into overflow pages.
6304 ** *pnSize Size of the local cell (not counting overflow pages)
6305 ** pPrior Where to write the pgno of the first overflow page
6306 **
6307 ** Use a call to btreeParseCellPtr() to verify that the values above
6308 ** were computed correctly.
6309 */
drhd879e3e2017-02-13 13:35:55 +00006310#ifdef SQLITE_DEBUG
drh6200c882014-09-23 22:36:25 +00006311 {
6312 CellInfo info;
drh5fa60512015-06-19 17:19:34 +00006313 pPage->xParseCell(pPage, pCell, &info);
drhcc5f8a42016-02-06 22:32:06 +00006314 assert( nHeader==(int)(info.pPayload - pCell) );
drh8eeb4462016-05-21 20:03:42 +00006315 assert( info.nKey==pX->nKey );
drh6200c882014-09-23 22:36:25 +00006316 assert( *pnSize == info.nSize );
6317 assert( spaceLeft == info.nLocal );
drh6200c882014-09-23 22:36:25 +00006318 }
6319#endif
6320
6321 /* Write the payload into the local Cell and any extra into overflow pages */
drh5e27e1d2017-08-23 14:45:59 +00006322 while( 1 ){
6323 n = nPayload;
6324 if( n>spaceLeft ) n = spaceLeft;
6325
6326 /* If pToRelease is not zero than pPayload points into the data area
6327 ** of pToRelease. Make sure pToRelease is still writeable. */
6328 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6329
6330 /* If pPayload is part of the data area of pPage, then make sure pPage
6331 ** is still writeable */
6332 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
6333 || sqlite3PagerIswriteable(pPage->pDbPage) );
6334
6335 if( nSrc>=n ){
6336 memcpy(pPayload, pSrc, n);
6337 }else if( nSrc>0 ){
6338 n = nSrc;
6339 memcpy(pPayload, pSrc, n);
6340 }else{
6341 memset(pPayload, 0, n);
6342 }
6343 nPayload -= n;
6344 if( nPayload<=0 ) break;
6345 pPayload += n;
6346 pSrc += n;
6347 nSrc -= n;
6348 spaceLeft -= n;
drh3b7511c2001-05-26 13:15:44 +00006349 if( spaceLeft==0 ){
drh5e27e1d2017-08-23 14:45:59 +00006350 MemPage *pOvfl = 0;
danielk1977afcdd022004-10-31 16:25:42 +00006351#ifndef SQLITE_OMIT_AUTOVACUUM
6352 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00006353 if( pBt->autoVacuum ){
6354 do{
6355 pgnoOvfl++;
6356 } while(
6357 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
6358 );
danielk1977b39f70b2007-05-17 18:28:11 +00006359 }
danielk1977afcdd022004-10-31 16:25:42 +00006360#endif
drhf49661a2008-12-10 16:45:50 +00006361 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00006362#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00006363 /* If the database supports auto-vacuum, and the second or subsequent
6364 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00006365 ** for that page now.
6366 **
6367 ** If this is the first overflow page, then write a partial entry
6368 ** to the pointer-map. If we write nothing to this pointer-map slot,
6369 ** then the optimistic overflow chain processing in clearCell()
mistachkin48864df2013-03-21 21:20:32 +00006370 ** may misinterpret the uninitialized values and delete the
danielk19774ef24492007-05-23 09:52:41 +00006371 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00006372 */
danielk19774ef24492007-05-23 09:52:41 +00006373 if( pBt->autoVacuum && rc==SQLITE_OK ){
6374 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
drh98add2e2009-07-20 17:11:49 +00006375 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
danielk197789a4be82007-05-23 13:34:32 +00006376 if( rc ){
6377 releasePage(pOvfl);
6378 }
danielk1977afcdd022004-10-31 16:25:42 +00006379 }
6380#endif
drh3b7511c2001-05-26 13:15:44 +00006381 if( rc ){
drh9b171272004-05-08 02:03:22 +00006382 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00006383 return rc;
6384 }
drhc5053fb2008-11-27 02:22:10 +00006385
6386 /* If pToRelease is not zero than pPrior points into the data area
6387 ** of pToRelease. Make sure pToRelease is still writeable. */
6388 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6389
6390 /* If pPrior is part of the data area of pPage, then make sure pPage
6391 ** is still writeable */
6392 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
6393 || sqlite3PagerIswriteable(pPage->pDbPage) );
6394
drh3aac2dd2004-04-26 14:10:20 +00006395 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00006396 releasePage(pToRelease);
6397 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00006398 pPrior = pOvfl->aData;
6399 put4byte(pPrior, 0);
6400 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00006401 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00006402 }
drhdd793422001-06-28 01:54:48 +00006403 }
drh9b171272004-05-08 02:03:22 +00006404 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00006405 return SQLITE_OK;
6406}
6407
drh14acc042001-06-10 19:56:58 +00006408/*
6409** Remove the i-th cell from pPage. This routine effects pPage only.
6410** The cell content is not freed or deallocated. It is assumed that
6411** the cell content has been copied someplace else. This routine just
6412** removes the reference to the cell from pPage.
6413**
6414** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00006415*/
drh98add2e2009-07-20 17:11:49 +00006416static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
drh43b18e12010-08-17 19:40:08 +00006417 u32 pc; /* Offset to cell content of cell being deleted */
drh43605152004-05-29 21:46:49 +00006418 u8 *data; /* pPage->aData */
6419 u8 *ptr; /* Used to move bytes around within data[] */
shanedcc50b72008-11-13 18:29:50 +00006420 int rc; /* The return code */
drhc314dc72009-07-21 11:52:34 +00006421 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
drh43605152004-05-29 21:46:49 +00006422
drh98add2e2009-07-20 17:11:49 +00006423 if( *pRC ) return;
drh8c42ca92001-06-22 19:15:00 +00006424 assert( idx>=0 && idx<pPage->nCell );
dan0f8076d2015-05-25 18:47:26 +00006425 assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00006426 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00006427 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00006428 data = pPage->aData;
drh3def2352011-11-11 00:27:15 +00006429 ptr = &pPage->aCellIdx[2*idx];
shane0af3f892008-11-12 04:55:34 +00006430 pc = get2byte(ptr);
drhc314dc72009-07-21 11:52:34 +00006431 hdr = pPage->hdrOffset;
6432 testcase( pc==get2byte(&data[hdr+5]) );
6433 testcase( pc+sz==pPage->pBt->usableSize );
drh5e398e42017-08-23 20:36:06 +00006434 if( pc+sz > pPage->pBt->usableSize ){
drh98add2e2009-07-20 17:11:49 +00006435 *pRC = SQLITE_CORRUPT_BKPT;
6436 return;
shane0af3f892008-11-12 04:55:34 +00006437 }
shanedcc50b72008-11-13 18:29:50 +00006438 rc = freeSpace(pPage, pc, sz);
drh98add2e2009-07-20 17:11:49 +00006439 if( rc ){
6440 *pRC = rc;
6441 return;
shanedcc50b72008-11-13 18:29:50 +00006442 }
drh14acc042001-06-10 19:56:58 +00006443 pPage->nCell--;
drhfdab0262014-11-20 15:30:50 +00006444 if( pPage->nCell==0 ){
6445 memset(&data[hdr+1], 0, 4);
6446 data[hdr+7] = 0;
6447 put2byte(&data[hdr+5], pPage->pBt->usableSize);
6448 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
6449 - pPage->childPtrSize - 8;
6450 }else{
6451 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
6452 put2byte(&data[hdr+3], pPage->nCell);
6453 pPage->nFree += 2;
6454 }
drh14acc042001-06-10 19:56:58 +00006455}
6456
6457/*
6458** Insert a new cell on pPage at cell index "i". pCell points to the
6459** content of the cell.
6460**
6461** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00006462** will not fit, then make a copy of the cell content into pTemp if
6463** pTemp is not null. Regardless of pTemp, allocate a new entry
drh2cbd78b2012-02-02 19:37:18 +00006464** in pPage->apOvfl[] and make it point to the cell content (either
drh43605152004-05-29 21:46:49 +00006465** in pTemp or the original pCell) and also record its index.
6466** Allocating a new entry in pPage->aCell[] implies that
6467** pPage->nOverflow is incremented.
drhcb89f4a2016-05-21 11:23:26 +00006468**
6469** *pRC must be SQLITE_OK when this routine is called.
drh14acc042001-06-10 19:56:58 +00006470*/
drh98add2e2009-07-20 17:11:49 +00006471static void insertCell(
drh24cd67e2004-05-10 16:18:47 +00006472 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00006473 int i, /* New cell becomes the i-th cell of the page */
6474 u8 *pCell, /* Content of the new cell */
6475 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00006476 u8 *pTemp, /* Temp storage space for pCell, if needed */
drh98add2e2009-07-20 17:11:49 +00006477 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
6478 int *pRC /* Read and write return code from here */
drh24cd67e2004-05-10 16:18:47 +00006479){
drh383d30f2010-02-26 13:07:37 +00006480 int idx = 0; /* Where to write new cell content in data[] */
drh43605152004-05-29 21:46:49 +00006481 int j; /* Loop counter */
drh43605152004-05-29 21:46:49 +00006482 u8 *data; /* The content of the whole page */
drh2c8fb922015-06-25 19:53:48 +00006483 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
danielk19774dbaa892009-06-16 16:50:22 +00006484
drhcb89f4a2016-05-21 11:23:26 +00006485 assert( *pRC==SQLITE_OK );
drh43605152004-05-29 21:46:49 +00006486 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
danf216e322014-08-14 19:53:37 +00006487 assert( MX_CELL(pPage->pBt)<=10921 );
6488 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
drh2cbd78b2012-02-02 19:37:18 +00006489 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
6490 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
drh1fee73e2007-08-29 04:00:57 +00006491 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc9b9b8a2009-12-03 21:26:52 +00006492 /* The cell should normally be sized correctly. However, when moving a
6493 ** malformed cell from a leaf page to an interior page, if the cell size
6494 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
6495 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
6496 ** the term after the || in the following assert(). */
drh25ada072015-06-19 15:07:14 +00006497 assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
drh43605152004-05-29 21:46:49 +00006498 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00006499 if( pTemp ){
drhd6176c42014-10-11 17:22:55 +00006500 memcpy(pTemp, pCell, sz);
drh43605152004-05-29 21:46:49 +00006501 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00006502 }
danielk19774dbaa892009-06-16 16:50:22 +00006503 if( iChild ){
6504 put4byte(pCell, iChild);
6505 }
drh43605152004-05-29 21:46:49 +00006506 j = pPage->nOverflow++;
drha2ee5892016-12-09 16:02:00 +00006507 /* Comparison against ArraySize-1 since we hold back one extra slot
6508 ** as a contingency. In other words, never need more than 3 overflow
6509 ** slots but 4 are allocated, just to be safe. */
6510 assert( j < ArraySize(pPage->apOvfl)-1 );
drh2cbd78b2012-02-02 19:37:18 +00006511 pPage->apOvfl[j] = pCell;
6512 pPage->aiOvfl[j] = (u16)i;
drhfe647dc2015-06-23 18:24:25 +00006513
6514 /* When multiple overflows occur, they are always sequential and in
6515 ** sorted order. This invariants arise because multiple overflows can
6516 ** only occur when inserting divider cells into the parent page during
6517 ** balancing, and the dividers are adjacent and sorted.
6518 */
6519 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
6520 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
drh14acc042001-06-10 19:56:58 +00006521 }else{
danielk19776e465eb2007-08-21 13:11:00 +00006522 int rc = sqlite3PagerWrite(pPage->pDbPage);
6523 if( rc!=SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00006524 *pRC = rc;
6525 return;
danielk19776e465eb2007-08-21 13:11:00 +00006526 }
6527 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00006528 data = pPage->aData;
drh2c8fb922015-06-25 19:53:48 +00006529 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
drh0a45c272009-07-08 01:49:11 +00006530 rc = allocateSpace(pPage, sz, &idx);
drh98add2e2009-07-20 17:11:49 +00006531 if( rc ){ *pRC = rc; return; }
drhcd8fb7c2015-06-02 14:02:18 +00006532 /* The allocateSpace() routine guarantees the following properties
6533 ** if it returns successfully */
drh2c8fb922015-06-25 19:53:48 +00006534 assert( idx >= 0 );
6535 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
drhfcd71b62011-04-05 22:08:24 +00006536 assert( idx+sz <= (int)pPage->pBt->usableSize );
drh0a45c272009-07-08 01:49:11 +00006537 pPage->nFree -= (u16)(2 + sz);
drhd6176c42014-10-11 17:22:55 +00006538 memcpy(&data[idx], pCell, sz);
danielk19774dbaa892009-06-16 16:50:22 +00006539 if( iChild ){
6540 put4byte(&data[idx], iChild);
6541 }
drh2c8fb922015-06-25 19:53:48 +00006542 pIns = pPage->aCellIdx + i*2;
6543 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
6544 put2byte(pIns, idx);
6545 pPage->nCell++;
6546 /* increment the cell count */
6547 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
6548 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
danielk1977a19df672004-11-03 11:37:07 +00006549#ifndef SQLITE_OMIT_AUTOVACUUM
6550 if( pPage->pBt->autoVacuum ){
6551 /* The cell may contain a pointer to an overflow page. If so, write
6552 ** the entry for the overflow page into the pointer map.
6553 */
drh98add2e2009-07-20 17:11:49 +00006554 ptrmapPutOvflPtr(pPage, pCell, pRC);
danielk1977a19df672004-11-03 11:37:07 +00006555 }
6556#endif
drh14acc042001-06-10 19:56:58 +00006557 }
6558}
6559
6560/*
drh1ffd2472015-06-23 02:37:30 +00006561** A CellArray object contains a cache of pointers and sizes for a
drhc0d269e2016-08-03 14:51:16 +00006562** consecutive sequence of cells that might be held on multiple pages.
drhfa1a98a2004-05-14 19:08:17 +00006563*/
drh1ffd2472015-06-23 02:37:30 +00006564typedef struct CellArray CellArray;
6565struct CellArray {
6566 int nCell; /* Number of cells in apCell[] */
6567 MemPage *pRef; /* Reference page */
6568 u8 **apCell; /* All cells begin balanced */
6569 u16 *szCell; /* Local size of all cells in apCell[] */
6570};
drhfa1a98a2004-05-14 19:08:17 +00006571
drh1ffd2472015-06-23 02:37:30 +00006572/*
6573** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
6574** computed.
6575*/
6576static void populateCellCache(CellArray *p, int idx, int N){
6577 assert( idx>=0 && idx+N<=p->nCell );
6578 while( N>0 ){
6579 assert( p->apCell[idx]!=0 );
6580 if( p->szCell[idx]==0 ){
6581 p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
6582 }else{
6583 assert( CORRUPT_DB ||
6584 p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
6585 }
6586 idx++;
6587 N--;
drhfa1a98a2004-05-14 19:08:17 +00006588 }
drh1ffd2472015-06-23 02:37:30 +00006589}
6590
6591/*
6592** Return the size of the Nth element of the cell array
6593*/
6594static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
6595 assert( N>=0 && N<p->nCell );
6596 assert( p->szCell[N]==0 );
6597 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
6598 return p->szCell[N];
6599}
6600static u16 cachedCellSize(CellArray *p, int N){
6601 assert( N>=0 && N<p->nCell );
6602 if( p->szCell[N] ) return p->szCell[N];
6603 return computeCellSize(p, N);
6604}
6605
6606/*
dan8e9ba0c2014-10-14 17:27:04 +00006607** Array apCell[] contains pointers to nCell b-tree page cells. The
6608** szCell[] array contains the size in bytes of each cell. This function
6609** replaces the current contents of page pPg with the contents of the cell
6610** array.
6611**
6612** Some of the cells in apCell[] may currently be stored in pPg. This
6613** function works around problems caused by this by making a copy of any
6614** such cells before overwriting the page data.
6615**
6616** The MemPage.nFree field is invalidated by this function. It is the
6617** responsibility of the caller to set it correctly.
drhfa1a98a2004-05-14 19:08:17 +00006618*/
drh658873b2015-06-22 20:02:04 +00006619static int rebuildPage(
dan33ea4862014-10-09 19:35:37 +00006620 MemPage *pPg, /* Edit this page */
dan33ea4862014-10-09 19:35:37 +00006621 int nCell, /* Final number of cells on page */
dan09c68402014-10-11 20:00:24 +00006622 u8 **apCell, /* Array of cells */
6623 u16 *szCell /* Array of cell sizes */
dan33ea4862014-10-09 19:35:37 +00006624){
6625 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
6626 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
6627 const int usableSize = pPg->pBt->usableSize;
6628 u8 * const pEnd = &aData[usableSize];
6629 int i;
6630 u8 *pCellptr = pPg->aCellIdx;
6631 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6632 u8 *pData;
6633
6634 i = get2byte(&aData[hdr+5]);
6635 memcpy(&pTmp[i], &aData[i], usableSize - i);
dan33ea4862014-10-09 19:35:37 +00006636
dan8e9ba0c2014-10-14 17:27:04 +00006637 pData = pEnd;
dan33ea4862014-10-09 19:35:37 +00006638 for(i=0; i<nCell; i++){
6639 u8 *pCell = apCell[i];
drh8b0ba7b2015-12-16 13:07:35 +00006640 if( SQLITE_WITHIN(pCell,aData,pEnd) ){
dan33ea4862014-10-09 19:35:37 +00006641 pCell = &pTmp[pCell - aData];
6642 }
6643 pData -= szCell[i];
dan33ea4862014-10-09 19:35:37 +00006644 put2byte(pCellptr, (pData - aData));
6645 pCellptr += 2;
drh658873b2015-06-22 20:02:04 +00006646 if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
6647 memcpy(pData, pCell, szCell[i]);
drh25ada072015-06-19 15:07:14 +00006648 assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
drhea82b372015-06-23 21:35:28 +00006649 testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
dan33ea4862014-10-09 19:35:37 +00006650 }
6651
dand7b545b2014-10-13 18:03:27 +00006652 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
dan33ea4862014-10-09 19:35:37 +00006653 pPg->nCell = nCell;
6654 pPg->nOverflow = 0;
6655
6656 put2byte(&aData[hdr+1], 0);
6657 put2byte(&aData[hdr+3], pPg->nCell);
6658 put2byte(&aData[hdr+5], pData - aData);
6659 aData[hdr+7] = 0x00;
drh658873b2015-06-22 20:02:04 +00006660 return SQLITE_OK;
dan33ea4862014-10-09 19:35:37 +00006661}
6662
dan8e9ba0c2014-10-14 17:27:04 +00006663/*
6664** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
6665** contains the size in bytes of each such cell. This function attempts to
6666** add the cells stored in the array to page pPg. If it cannot (because
6667** the page needs to be defragmented before the cells will fit), non-zero
6668** is returned. Otherwise, if the cells are added successfully, zero is
6669** returned.
6670**
6671** Argument pCellptr points to the first entry in the cell-pointer array
6672** (part of page pPg) to populate. After cell apCell[0] is written to the
6673** page body, a 16-bit offset is written to pCellptr. And so on, for each
6674** cell in the array. It is the responsibility of the caller to ensure
6675** that it is safe to overwrite this part of the cell-pointer array.
6676**
6677** When this function is called, *ppData points to the start of the
6678** content area on page pPg. If the size of the content area is extended,
6679** *ppData is updated to point to the new start of the content area
6680** before returning.
6681**
6682** Finally, argument pBegin points to the byte immediately following the
6683** end of the space required by this page for the cell-pointer area (for
6684** all cells - not just those inserted by the current call). If the content
6685** area must be extended to before this point in order to accomodate all
6686** cells in apCell[], then the cells do not fit and non-zero is returned.
6687*/
dand7b545b2014-10-13 18:03:27 +00006688static int pageInsertArray(
dan8e9ba0c2014-10-14 17:27:04 +00006689 MemPage *pPg, /* Page to add cells to */
6690 u8 *pBegin, /* End of cell-pointer array */
6691 u8 **ppData, /* IN/OUT: Page content -area pointer */
6692 u8 *pCellptr, /* Pointer to cell-pointer area */
drhf7838932015-06-23 15:36:34 +00006693 int iFirst, /* Index of first cell to add */
dan8e9ba0c2014-10-14 17:27:04 +00006694 int nCell, /* Number of cells to add to pPg */
drhf7838932015-06-23 15:36:34 +00006695 CellArray *pCArray /* Array of cells */
dand7b545b2014-10-13 18:03:27 +00006696){
6697 int i;
6698 u8 *aData = pPg->aData;
6699 u8 *pData = *ppData;
drhf7838932015-06-23 15:36:34 +00006700 int iEnd = iFirst + nCell;
dan23eba452014-10-24 18:43:57 +00006701 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
drhf7838932015-06-23 15:36:34 +00006702 for(i=iFirst; i<iEnd; i++){
6703 int sz, rc;
dand7b545b2014-10-13 18:03:27 +00006704 u8 *pSlot;
drhf7838932015-06-23 15:36:34 +00006705 sz = cachedCellSize(pCArray, i);
drhb7580e82015-06-25 18:36:13 +00006706 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
drhcca66982016-04-05 13:19:19 +00006707 if( (pData - pBegin)<sz ) return 1;
dand7b545b2014-10-13 18:03:27 +00006708 pData -= sz;
dand7b545b2014-10-13 18:03:27 +00006709 pSlot = pData;
6710 }
drh48310f82015-10-10 16:41:28 +00006711 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
6712 ** database. But they might for a corrupt database. Hence use memmove()
6713 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
6714 assert( (pSlot+sz)<=pCArray->apCell[i]
6715 || pSlot>=(pCArray->apCell[i]+sz)
6716 || CORRUPT_DB );
6717 memmove(pSlot, pCArray->apCell[i], sz);
dand7b545b2014-10-13 18:03:27 +00006718 put2byte(pCellptr, (pSlot - aData));
6719 pCellptr += 2;
6720 }
6721 *ppData = pData;
6722 return 0;
6723}
6724
dan8e9ba0c2014-10-14 17:27:04 +00006725/*
6726** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
6727** contains the size in bytes of each such cell. This function adds the
6728** space associated with each cell in the array that is currently stored
6729** within the body of pPg to the pPg free-list. The cell-pointers and other
6730** fields of the page are not updated.
6731**
6732** This function returns the total number of cells added to the free-list.
6733*/
dand7b545b2014-10-13 18:03:27 +00006734static int pageFreeArray(
6735 MemPage *pPg, /* Page to edit */
drhf7838932015-06-23 15:36:34 +00006736 int iFirst, /* First cell to delete */
dand7b545b2014-10-13 18:03:27 +00006737 int nCell, /* Cells to delete */
drhf7838932015-06-23 15:36:34 +00006738 CellArray *pCArray /* Array of cells */
dand7b545b2014-10-13 18:03:27 +00006739){
6740 u8 * const aData = pPg->aData;
6741 u8 * const pEnd = &aData[pPg->pBt->usableSize];
dan89ca0b32014-10-25 20:36:28 +00006742 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
dand7b545b2014-10-13 18:03:27 +00006743 int nRet = 0;
6744 int i;
drhf7838932015-06-23 15:36:34 +00006745 int iEnd = iFirst + nCell;
dand7b545b2014-10-13 18:03:27 +00006746 u8 *pFree = 0;
6747 int szFree = 0;
6748
drhf7838932015-06-23 15:36:34 +00006749 for(i=iFirst; i<iEnd; i++){
6750 u8 *pCell = pCArray->apCell[i];
drh8b0ba7b2015-12-16 13:07:35 +00006751 if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
drhf7838932015-06-23 15:36:34 +00006752 int sz;
6753 /* No need to use cachedCellSize() here. The sizes of all cells that
6754 ** are to be freed have already been computing while deciding which
6755 ** cells need freeing */
6756 sz = pCArray->szCell[i]; assert( sz>0 );
dand7b545b2014-10-13 18:03:27 +00006757 if( pFree!=(pCell + sz) ){
drhfefa0942014-11-05 21:21:08 +00006758 if( pFree ){
6759 assert( pFree>aData && (pFree - aData)<65536 );
6760 freeSpace(pPg, (u16)(pFree - aData), szFree);
6761 }
dand7b545b2014-10-13 18:03:27 +00006762 pFree = pCell;
6763 szFree = sz;
dan89ca0b32014-10-25 20:36:28 +00006764 if( pFree+sz>pEnd ) return 0;
dand7b545b2014-10-13 18:03:27 +00006765 }else{
6766 pFree = pCell;
6767 szFree += sz;
6768 }
6769 nRet++;
6770 }
6771 }
drhfefa0942014-11-05 21:21:08 +00006772 if( pFree ){
6773 assert( pFree>aData && (pFree - aData)<65536 );
6774 freeSpace(pPg, (u16)(pFree - aData), szFree);
6775 }
dand7b545b2014-10-13 18:03:27 +00006776 return nRet;
6777}
6778
dand7b545b2014-10-13 18:03:27 +00006779/*
drh5ab63772014-11-27 03:46:04 +00006780** apCell[] and szCell[] contains pointers to and sizes of all cells in the
6781** pages being balanced. The current page, pPg, has pPg->nCell cells starting
6782** with apCell[iOld]. After balancing, this page should hold nNew cells
6783** starting at apCell[iNew].
6784**
6785** This routine makes the necessary adjustments to pPg so that it contains
6786** the correct cells after being balanced.
6787**
dand7b545b2014-10-13 18:03:27 +00006788** The pPg->nFree field is invalid when this function returns. It is the
6789** responsibility of the caller to set it correctly.
6790*/
drh658873b2015-06-22 20:02:04 +00006791static int editPage(
dan09c68402014-10-11 20:00:24 +00006792 MemPage *pPg, /* Edit this page */
6793 int iOld, /* Index of first cell currently on page */
6794 int iNew, /* Index of new first cell on page */
6795 int nNew, /* Final number of cells on page */
drh1ffd2472015-06-23 02:37:30 +00006796 CellArray *pCArray /* Array of cells and sizes */
dan09c68402014-10-11 20:00:24 +00006797){
dand7b545b2014-10-13 18:03:27 +00006798 u8 * const aData = pPg->aData;
6799 const int hdr = pPg->hdrOffset;
6800 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
6801 int nCell = pPg->nCell; /* Cells stored on pPg */
6802 u8 *pData;
6803 u8 *pCellptr;
6804 int i;
6805 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
6806 int iNewEnd = iNew + nNew;
dan09c68402014-10-11 20:00:24 +00006807
6808#ifdef SQLITE_DEBUG
dand7b545b2014-10-13 18:03:27 +00006809 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6810 memcpy(pTmp, aData, pPg->pBt->usableSize);
dan09c68402014-10-11 20:00:24 +00006811#endif
6812
dand7b545b2014-10-13 18:03:27 +00006813 /* Remove cells from the start and end of the page */
6814 if( iOld<iNew ){
drhf7838932015-06-23 15:36:34 +00006815 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
dand7b545b2014-10-13 18:03:27 +00006816 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
6817 nCell -= nShift;
6818 }
6819 if( iNewEnd < iOldEnd ){
drhf7838932015-06-23 15:36:34 +00006820 nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
dand7b545b2014-10-13 18:03:27 +00006821 }
dan09c68402014-10-11 20:00:24 +00006822
drh5ab63772014-11-27 03:46:04 +00006823 pData = &aData[get2byteNotZero(&aData[hdr+5])];
dand7b545b2014-10-13 18:03:27 +00006824 if( pData<pBegin ) goto editpage_fail;
6825
6826 /* Add cells to the start of the page */
6827 if( iNew<iOld ){
drh5ab63772014-11-27 03:46:04 +00006828 int nAdd = MIN(nNew,iOld-iNew);
6829 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
dand7b545b2014-10-13 18:03:27 +00006830 pCellptr = pPg->aCellIdx;
6831 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
6832 if( pageInsertArray(
6833 pPg, pBegin, &pData, pCellptr,
drhf7838932015-06-23 15:36:34 +00006834 iNew, nAdd, pCArray
dand7b545b2014-10-13 18:03:27 +00006835 ) ) goto editpage_fail;
6836 nCell += nAdd;
6837 }
6838
6839 /* Add any overflow cells */
6840 for(i=0; i<pPg->nOverflow; i++){
6841 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
6842 if( iCell>=0 && iCell<nNew ){
drhfefa0942014-11-05 21:21:08 +00006843 pCellptr = &pPg->aCellIdx[iCell * 2];
dand7b545b2014-10-13 18:03:27 +00006844 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
6845 nCell++;
6846 if( pageInsertArray(
6847 pPg, pBegin, &pData, pCellptr,
drhf7838932015-06-23 15:36:34 +00006848 iCell+iNew, 1, pCArray
dand7b545b2014-10-13 18:03:27 +00006849 ) ) goto editpage_fail;
dan09c68402014-10-11 20:00:24 +00006850 }
dand7b545b2014-10-13 18:03:27 +00006851 }
dan09c68402014-10-11 20:00:24 +00006852
dand7b545b2014-10-13 18:03:27 +00006853 /* Append cells to the end of the page */
6854 pCellptr = &pPg->aCellIdx[nCell*2];
6855 if( pageInsertArray(
6856 pPg, pBegin, &pData, pCellptr,
drhf7838932015-06-23 15:36:34 +00006857 iNew+nCell, nNew-nCell, pCArray
dand7b545b2014-10-13 18:03:27 +00006858 ) ) goto editpage_fail;
dan09c68402014-10-11 20:00:24 +00006859
dand7b545b2014-10-13 18:03:27 +00006860 pPg->nCell = nNew;
6861 pPg->nOverflow = 0;
dan09c68402014-10-11 20:00:24 +00006862
dand7b545b2014-10-13 18:03:27 +00006863 put2byte(&aData[hdr+3], pPg->nCell);
6864 put2byte(&aData[hdr+5], pData - aData);
dan09c68402014-10-11 20:00:24 +00006865
6866#ifdef SQLITE_DEBUG
dan23eba452014-10-24 18:43:57 +00006867 for(i=0; i<nNew && !CORRUPT_DB; i++){
drh1ffd2472015-06-23 02:37:30 +00006868 u8 *pCell = pCArray->apCell[i+iNew];
drh329428e2015-06-30 13:28:18 +00006869 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
drh1c715f62016-04-05 13:35:43 +00006870 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
dand7b545b2014-10-13 18:03:27 +00006871 pCell = &pTmp[pCell - aData];
dan09c68402014-10-11 20:00:24 +00006872 }
drh1ffd2472015-06-23 02:37:30 +00006873 assert( 0==memcmp(pCell, &aData[iOff],
6874 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
dand7b545b2014-10-13 18:03:27 +00006875 }
dan09c68402014-10-11 20:00:24 +00006876#endif
6877
drh658873b2015-06-22 20:02:04 +00006878 return SQLITE_OK;
dan09c68402014-10-11 20:00:24 +00006879 editpage_fail:
dan09c68402014-10-11 20:00:24 +00006880 /* Unable to edit this page. Rebuild it from scratch instead. */
drh1ffd2472015-06-23 02:37:30 +00006881 populateCellCache(pCArray, iNew, nNew);
6882 return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
drhfa1a98a2004-05-14 19:08:17 +00006883}
6884
drh14acc042001-06-10 19:56:58 +00006885/*
drhc3b70572003-01-04 19:44:07 +00006886** The following parameters determine how many adjacent pages get involved
6887** in a balancing operation. NN is the number of neighbors on either side
6888** of the page that participate in the balancing operation. NB is the
6889** total number of pages that participate, including the target page and
6890** NN neighbors on either side.
6891**
6892** The minimum value of NN is 1 (of course). Increasing NN above 1
6893** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
6894** in exchange for a larger degradation in INSERT and UPDATE performance.
6895** The value of NN appears to give the best results overall.
6896*/
6897#define NN 1 /* Number of neighbors on either side of pPage */
6898#define NB (NN*2+1) /* Total pages involved in the balance */
6899
danielk1977ac245ec2005-01-14 13:50:11 +00006900
drh615ae552005-01-16 23:21:00 +00006901#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00006902/*
6903** This version of balance() handles the common special case where
6904** a new entry is being inserted on the extreme right-end of the
6905** tree, in other words, when the new entry will become the largest
6906** entry in the tree.
6907**
drhc314dc72009-07-21 11:52:34 +00006908** Instead of trying to balance the 3 right-most leaf pages, just add
drhf222e712005-01-14 22:55:49 +00006909** a new page to the right-hand side and put the one new entry in
6910** that page. This leaves the right side of the tree somewhat
6911** unbalanced. But odds are that we will be inserting new entries
6912** at the end soon afterwards so the nearly empty page will quickly
6913** fill up. On average.
6914**
6915** pPage is the leaf page which is the right-most page in the tree.
6916** pParent is its parent. pPage must have a single overflow entry
6917** which is also the right-most entry on the page.
danielk1977a50d9aa2009-06-08 14:49:45 +00006918**
6919** The pSpace buffer is used to store a temporary copy of the divider
6920** cell that will be inserted into pParent. Such a cell consists of a 4
6921** byte page number followed by a variable length integer. In other
6922** words, at most 13 bytes. Hence the pSpace buffer must be at
6923** least 13 bytes in size.
drhf222e712005-01-14 22:55:49 +00006924*/
danielk1977a50d9aa2009-06-08 14:49:45 +00006925static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
6926 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
danielk19774dbaa892009-06-16 16:50:22 +00006927 MemPage *pNew; /* Newly allocated page */
danielk19776f235cc2009-06-04 14:46:08 +00006928 int rc; /* Return Code */
6929 Pgno pgnoNew; /* Page number of pNew */
danielk1977ac245ec2005-01-14 13:50:11 +00006930
drh1fee73e2007-08-29 04:00:57 +00006931 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk1977a50d9aa2009-06-08 14:49:45 +00006932 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00006933 assert( pPage->nOverflow==1 );
6934
drh5d433ce2010-08-14 16:02:52 +00006935 /* This error condition is now caught prior to reaching this function */
drh1fd2d7d2014-12-02 16:16:47 +00006936 if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
drhd677b3d2007-08-20 22:48:41 +00006937
danielk1977a50d9aa2009-06-08 14:49:45 +00006938 /* Allocate a new page. This page will become the right-sibling of
6939 ** pPage. Make the parent page writable, so that the new divider cell
6940 ** may be inserted. If both these operations are successful, proceed.
6941 */
drh4f0c5872007-03-26 22:05:01 +00006942 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk19774dbaa892009-06-16 16:50:22 +00006943
danielk1977eaa06f62008-09-18 17:34:44 +00006944 if( rc==SQLITE_OK ){
danielk1977a50d9aa2009-06-08 14:49:45 +00006945
6946 u8 *pOut = &pSpace[4];
drh2cbd78b2012-02-02 19:37:18 +00006947 u8 *pCell = pPage->apOvfl[0];
drh25ada072015-06-19 15:07:14 +00006948 u16 szCell = pPage->xCellSize(pPage, pCell);
danielk19776f235cc2009-06-04 14:46:08 +00006949 u8 *pStop;
6950
drhc5053fb2008-11-27 02:22:10 +00006951 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00006952 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
6953 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
drh658873b2015-06-22 20:02:04 +00006954 rc = rebuildPage(pNew, 1, &pCell, &szCell);
drhea82b372015-06-23 21:35:28 +00006955 if( NEVER(rc) ) return rc;
dan8e9ba0c2014-10-14 17:27:04 +00006956 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
danielk19774dbaa892009-06-16 16:50:22 +00006957
6958 /* If this is an auto-vacuum database, update the pointer map
6959 ** with entries for the new page, and any pointer from the
6960 ** cell on the page to an overflow page. If either of these
6961 ** operations fails, the return code is set, but the contents
6962 ** of the parent page are still manipulated by thh code below.
6963 ** That is Ok, at this point the parent page is guaranteed to
6964 ** be marked as dirty. Returning an error code will cause a
6965 ** rollback, undoing any changes made to the parent page.
6966 */
6967 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00006968 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
6969 if( szCell>pNew->minLocal ){
6970 ptrmapPutOvflPtr(pNew, pCell, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006971 }
6972 }
danielk1977eaa06f62008-09-18 17:34:44 +00006973
danielk19776f235cc2009-06-04 14:46:08 +00006974 /* Create a divider cell to insert into pParent. The divider cell
6975 ** consists of a 4-byte page number (the page number of pPage) and
6976 ** a variable length key value (which must be the same value as the
6977 ** largest key on pPage).
danielk1977eaa06f62008-09-18 17:34:44 +00006978 **
danielk19776f235cc2009-06-04 14:46:08 +00006979 ** To find the largest key value on pPage, first find the right-most
6980 ** cell on pPage. The first two fields of this cell are the
6981 ** record-length (a variable length integer at most 32-bits in size)
6982 ** and the key value (a variable length integer, may have any value).
6983 ** The first of the while(...) loops below skips over the record-length
6984 ** field. The second while(...) loop copies the key value from the
danielk1977a50d9aa2009-06-08 14:49:45 +00006985 ** cell on pPage into the pSpace buffer.
danielk1977eaa06f62008-09-18 17:34:44 +00006986 */
danielk1977eaa06f62008-09-18 17:34:44 +00006987 pCell = findCell(pPage, pPage->nCell-1);
danielk19776f235cc2009-06-04 14:46:08 +00006988 pStop = &pCell[9];
6989 while( (*(pCell++)&0x80) && pCell<pStop );
6990 pStop = &pCell[9];
6991 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
6992
danielk19774dbaa892009-06-16 16:50:22 +00006993 /* Insert the new divider cell into pParent. */
drhcb89f4a2016-05-21 11:23:26 +00006994 if( rc==SQLITE_OK ){
6995 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
6996 0, pPage->pgno, &rc);
6997 }
danielk19776f235cc2009-06-04 14:46:08 +00006998
6999 /* Set the right-child pointer of pParent to point to the new page. */
danielk1977eaa06f62008-09-18 17:34:44 +00007000 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
7001
danielk1977e08a3c42008-09-18 18:17:03 +00007002 /* Release the reference to the new page. */
7003 releasePage(pNew);
danielk1977ac11ee62005-01-15 12:45:51 +00007004 }
7005
danielk1977eaa06f62008-09-18 17:34:44 +00007006 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00007007}
drh615ae552005-01-16 23:21:00 +00007008#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00007009
danielk19774dbaa892009-06-16 16:50:22 +00007010#if 0
drhc3b70572003-01-04 19:44:07 +00007011/*
danielk19774dbaa892009-06-16 16:50:22 +00007012** This function does not contribute anything to the operation of SQLite.
7013** it is sometimes activated temporarily while debugging code responsible
7014** for setting pointer-map entries.
7015*/
7016static int ptrmapCheckPages(MemPage **apPage, int nPage){
7017 int i, j;
7018 for(i=0; i<nPage; i++){
7019 Pgno n;
7020 u8 e;
7021 MemPage *pPage = apPage[i];
7022 BtShared *pBt = pPage->pBt;
7023 assert( pPage->isInit );
7024
7025 for(j=0; j<pPage->nCell; j++){
7026 CellInfo info;
7027 u8 *z;
7028
7029 z = findCell(pPage, j);
drh5fa60512015-06-19 17:19:34 +00007030 pPage->xParseCell(pPage, z, &info);
drh45ac1c72015-12-18 03:59:16 +00007031 if( info.nLocal<info.nPayload ){
7032 Pgno ovfl = get4byte(&z[info.nSize-4]);
danielk19774dbaa892009-06-16 16:50:22 +00007033 ptrmapGet(pBt, ovfl, &e, &n);
7034 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
7035 }
7036 if( !pPage->leaf ){
7037 Pgno child = get4byte(z);
7038 ptrmapGet(pBt, child, &e, &n);
7039 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7040 }
7041 }
7042 if( !pPage->leaf ){
7043 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7044 ptrmapGet(pBt, child, &e, &n);
7045 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7046 }
7047 }
7048 return 1;
7049}
7050#endif
7051
danielk1977cd581a72009-06-23 15:43:39 +00007052/*
7053** This function is used to copy the contents of the b-tree node stored
7054** on page pFrom to page pTo. If page pFrom was not a leaf page, then
7055** the pointer-map entries for each child page are updated so that the
7056** parent page stored in the pointer map is page pTo. If pFrom contained
7057** any cells with overflow page pointers, then the corresponding pointer
7058** map entries are also updated so that the parent page is page pTo.
7059**
7060** If pFrom is currently carrying any overflow cells (entries in the
drh2cbd78b2012-02-02 19:37:18 +00007061** MemPage.apOvfl[] array), they are not copied to pTo.
danielk1977cd581a72009-06-23 15:43:39 +00007062**
danielk197730548662009-07-09 05:07:37 +00007063** Before returning, page pTo is reinitialized using btreeInitPage().
danielk1977cd581a72009-06-23 15:43:39 +00007064**
7065** The performance of this function is not critical. It is only used by
7066** the balance_shallower() and balance_deeper() procedures, neither of
7067** which are called often under normal circumstances.
7068*/
drhc314dc72009-07-21 11:52:34 +00007069static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
7070 if( (*pRC)==SQLITE_OK ){
7071 BtShared * const pBt = pFrom->pBt;
7072 u8 * const aFrom = pFrom->aData;
7073 u8 * const aTo = pTo->aData;
7074 int const iFromHdr = pFrom->hdrOffset;
7075 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
drhdc9b5f82009-12-05 18:34:08 +00007076 int rc;
drhc314dc72009-07-21 11:52:34 +00007077 int iData;
7078
7079
7080 assert( pFrom->isInit );
7081 assert( pFrom->nFree>=iToHdr );
drhfcd71b62011-04-05 22:08:24 +00007082 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
drhc314dc72009-07-21 11:52:34 +00007083
7084 /* Copy the b-tree node content from page pFrom to page pTo. */
7085 iData = get2byte(&aFrom[iFromHdr+5]);
7086 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
7087 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
7088
7089 /* Reinitialize page pTo so that the contents of the MemPage structure
dan89e060e2009-12-05 18:03:50 +00007090 ** match the new data. The initialization of pTo can actually fail under
7091 ** fairly obscure circumstances, even though it is a copy of initialized
7092 ** page pFrom.
7093 */
drhc314dc72009-07-21 11:52:34 +00007094 pTo->isInit = 0;
dan89e060e2009-12-05 18:03:50 +00007095 rc = btreeInitPage(pTo);
7096 if( rc!=SQLITE_OK ){
7097 *pRC = rc;
7098 return;
7099 }
drhc314dc72009-07-21 11:52:34 +00007100
7101 /* If this is an auto-vacuum database, update the pointer-map entries
7102 ** for any b-tree or overflow pages that pTo now contains the pointers to.
7103 */
7104 if( ISAUTOVACUUM ){
7105 *pRC = setChildPtrmaps(pTo);
7106 }
danielk1977cd581a72009-06-23 15:43:39 +00007107 }
danielk1977cd581a72009-06-23 15:43:39 +00007108}
7109
7110/*
danielk19774dbaa892009-06-16 16:50:22 +00007111** This routine redistributes cells on the iParentIdx'th child of pParent
7112** (hereafter "the page") and up to 2 siblings so that all pages have about the
7113** same amount of free space. Usually a single sibling on either side of the
7114** page are used in the balancing, though both siblings might come from one
7115** side if the page is the first or last child of its parent. If the page
7116** has fewer than 2 siblings (something which can only happen if the page
7117** is a root page or a child of a root page) then all available siblings
7118** participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00007119**
danielk19774dbaa892009-06-16 16:50:22 +00007120** The number of siblings of the page might be increased or decreased by
7121** one or two in an effort to keep pages nearly full but not over full.
drh14acc042001-06-10 19:56:58 +00007122**
danielk19774dbaa892009-06-16 16:50:22 +00007123** Note that when this routine is called, some of the cells on the page
7124** might not actually be stored in MemPage.aData[]. This can happen
7125** if the page is overfull. This routine ensures that all cells allocated
7126** to the page and its siblings fit into MemPage.aData[] before returning.
drh14acc042001-06-10 19:56:58 +00007127**
danielk19774dbaa892009-06-16 16:50:22 +00007128** In the course of balancing the page and its siblings, cells may be
7129** inserted into or removed from the parent page (pParent). Doing so
7130** may cause the parent page to become overfull or underfull. If this
7131** happens, it is the responsibility of the caller to invoke the correct
7132** balancing routine to fix this problem (see the balance() routine).
drh8c42ca92001-06-22 19:15:00 +00007133**
drh5e00f6c2001-09-13 13:46:56 +00007134** If this routine fails for any reason, it might leave the database
danielk19776067a9b2009-06-09 09:41:00 +00007135** in a corrupted state. So if this routine fails, the database should
drh5e00f6c2001-09-13 13:46:56 +00007136** be rolled back.
danielk19774dbaa892009-06-16 16:50:22 +00007137**
7138** The third argument to this function, aOvflSpace, is a pointer to a
drhcd09c532009-07-20 19:30:00 +00007139** buffer big enough to hold one page. If while inserting cells into the parent
7140** page (pParent) the parent page becomes overfull, this buffer is
7141** used to store the parent's overflow cells. Because this function inserts
danielk19774dbaa892009-06-16 16:50:22 +00007142** a maximum of four divider cells into the parent page, and the maximum
7143** size of a cell stored within an internal node is always less than 1/4
7144** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
7145** enough for all overflow cells.
7146**
7147** If aOvflSpace is set to a null pointer, this function returns
7148** SQLITE_NOMEM.
drh8b2f49b2001-06-08 00:21:52 +00007149*/
danielk19774dbaa892009-06-16 16:50:22 +00007150static int balance_nonroot(
7151 MemPage *pParent, /* Parent page of siblings being balanced */
7152 int iParentIdx, /* Index of "the page" in pParent */
danielk1977cd581a72009-06-23 15:43:39 +00007153 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
dan428c2182012-08-06 18:50:11 +00007154 int isRoot, /* True if pParent is a root-page */
7155 int bBulk /* True if this call is part of a bulk load */
danielk19774dbaa892009-06-16 16:50:22 +00007156){
drh16a9b832007-05-05 18:39:25 +00007157 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00007158 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
danielk1977a4124bd2008-12-23 10:37:47 +00007159 int nNew = 0; /* Number of pages in apNew[] */
danielk19774dbaa892009-06-16 16:50:22 +00007160 int nOld; /* Number of pages in apOld[] */
drh14acc042001-06-10 19:56:58 +00007161 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00007162 int nxDiv; /* Next divider slot in pParent->aCell[] */
shane85095702009-06-15 16:27:08 +00007163 int rc = SQLITE_OK; /* The return code */
shane36840fd2009-06-26 16:32:13 +00007164 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00007165 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00007166 int usableSpace; /* Bytes in pPage beyond the header */
7167 int pageFlags; /* Value of pPage->aData[0] */
drhe5ae5732008-06-15 02:51:47 +00007168 int iSpace1 = 0; /* First unused byte of aSpace1[] */
danielk19776067a9b2009-06-09 09:41:00 +00007169 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
drhfacf0302008-06-17 15:12:00 +00007170 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00007171 MemPage *apOld[NB]; /* pPage and up to two siblings */
drha2fce642004-06-05 00:01:44 +00007172 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
danielk19774dbaa892009-06-16 16:50:22 +00007173 u8 *pRight; /* Location in parent of right-sibling pointer */
7174 u8 *apDiv[NB-1]; /* Divider cells in pParent */
drh1ffd2472015-06-23 02:37:30 +00007175 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
7176 int cntOld[NB+2]; /* Old index in b.apCell[] */
drh2a0df922014-10-30 23:14:56 +00007177 int szNew[NB+2]; /* Combined size of cells placed on i-th page */
danielk19774dbaa892009-06-16 16:50:22 +00007178 u8 *aSpace1; /* Space for copies of dividers cells */
7179 Pgno pgno; /* Temp var to store a page number in */
dane6593d82014-10-24 16:40:49 +00007180 u8 abDone[NB+2]; /* True after i'th new page is populated */
7181 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
drh00fe08a2014-10-31 00:05:23 +00007182 Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
dane6593d82014-10-24 16:40:49 +00007183 u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
drh1ffd2472015-06-23 02:37:30 +00007184 CellArray b; /* Parsed information on cells being balanced */
drh8b2f49b2001-06-08 00:21:52 +00007185
dan33ea4862014-10-09 19:35:37 +00007186 memset(abDone, 0, sizeof(abDone));
drh1ffd2472015-06-23 02:37:30 +00007187 b.nCell = 0;
7188 b.apCell = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00007189 pBt = pParent->pBt;
7190 assert( sqlite3_mutex_held(pBt->mutex) );
7191 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977474b7cc2008-07-09 11:49:46 +00007192
danielk1977e5765212009-06-17 11:13:28 +00007193#if 0
drh43605152004-05-29 21:46:49 +00007194 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
danielk1977e5765212009-06-17 11:13:28 +00007195#endif
drh2e38c322004-09-03 18:38:44 +00007196
danielk19774dbaa892009-06-16 16:50:22 +00007197 /* At this point pParent may have at most one overflow cell. And if
7198 ** this overflow cell is present, it must be the cell with
7199 ** index iParentIdx. This scenario comes about when this function
drhcd09c532009-07-20 19:30:00 +00007200 ** is called (indirectly) from sqlite3BtreeDelete().
7201 */
danielk19774dbaa892009-06-16 16:50:22 +00007202 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
drh2cbd78b2012-02-02 19:37:18 +00007203 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
danielk19774dbaa892009-06-16 16:50:22 +00007204
danielk197711a8a862009-06-17 11:49:52 +00007205 if( !aOvflSpace ){
mistachkinfad30392016-02-13 23:43:46 +00007206 return SQLITE_NOMEM_BKPT;
danielk197711a8a862009-06-17 11:49:52 +00007207 }
7208
danielk1977a50d9aa2009-06-08 14:49:45 +00007209 /* Find the sibling pages to balance. Also locate the cells in pParent
7210 ** that divide the siblings. An attempt is made to find NN siblings on
7211 ** either side of pPage. More siblings are taken from one side, however,
7212 ** if there are fewer than NN siblings on the other side. If pParent
danielk19774dbaa892009-06-16 16:50:22 +00007213 ** has NB or fewer children then all children of pParent are taken.
7214 **
7215 ** This loop also drops the divider cells from the parent page. This
7216 ** way, the remainder of the function does not have to deal with any
drhcd09c532009-07-20 19:30:00 +00007217 ** overflow cells in the parent page, since if any existed they will
7218 ** have already been removed.
7219 */
danielk19774dbaa892009-06-16 16:50:22 +00007220 i = pParent->nOverflow + pParent->nCell;
7221 if( i<2 ){
drhc3b70572003-01-04 19:44:07 +00007222 nxDiv = 0;
danielk19774dbaa892009-06-16 16:50:22 +00007223 }else{
dan7d6885a2012-08-08 14:04:56 +00007224 assert( bBulk==0 || bBulk==1 );
danielk19774dbaa892009-06-16 16:50:22 +00007225 if( iParentIdx==0 ){
7226 nxDiv = 0;
7227 }else if( iParentIdx==i ){
dan7d6885a2012-08-08 14:04:56 +00007228 nxDiv = i-2+bBulk;
drh14acc042001-06-10 19:56:58 +00007229 }else{
danielk19774dbaa892009-06-16 16:50:22 +00007230 nxDiv = iParentIdx-1;
drh8b2f49b2001-06-08 00:21:52 +00007231 }
dan7d6885a2012-08-08 14:04:56 +00007232 i = 2-bBulk;
danielk19774dbaa892009-06-16 16:50:22 +00007233 }
dan7d6885a2012-08-08 14:04:56 +00007234 nOld = i+1;
danielk19774dbaa892009-06-16 16:50:22 +00007235 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
7236 pRight = &pParent->aData[pParent->hdrOffset+8];
7237 }else{
7238 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
7239 }
7240 pgno = get4byte(pRight);
7241 while( 1 ){
drh28f58dd2015-06-27 19:45:03 +00007242 rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
danielk19774dbaa892009-06-16 16:50:22 +00007243 if( rc ){
danielk197789bc4bc2009-07-21 19:25:24 +00007244 memset(apOld, 0, (i+1)*sizeof(MemPage*));
danielk19774dbaa892009-06-16 16:50:22 +00007245 goto balance_cleanup;
7246 }
danielk1977634f2982005-03-28 08:44:07 +00007247 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
danielk19774dbaa892009-06-16 16:50:22 +00007248 if( (i--)==0 ) break;
7249
drh9cc5b4e2016-12-26 01:41:33 +00007250 if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
drh2cbd78b2012-02-02 19:37:18 +00007251 apDiv[i] = pParent->apOvfl[0];
danielk19774dbaa892009-06-16 16:50:22 +00007252 pgno = get4byte(apDiv[i]);
drh25ada072015-06-19 15:07:14 +00007253 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
danielk19774dbaa892009-06-16 16:50:22 +00007254 pParent->nOverflow = 0;
7255 }else{
7256 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
7257 pgno = get4byte(apDiv[i]);
drh25ada072015-06-19 15:07:14 +00007258 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
danielk19774dbaa892009-06-16 16:50:22 +00007259
7260 /* Drop the cell from the parent page. apDiv[i] still points to
7261 ** the cell within the parent, even though it has been dropped.
7262 ** This is safe because dropping a cell only overwrites the first
7263 ** four bytes of it, and this function does not need the first
7264 ** four bytes of the divider cell. So the pointer is safe to use
danielk197711a8a862009-06-17 11:49:52 +00007265 ** later on.
7266 **
drh8a575d92011-10-12 17:00:28 +00007267 ** But not if we are in secure-delete mode. In secure-delete mode,
danielk197711a8a862009-06-17 11:49:52 +00007268 ** the dropCell() routine will overwrite the entire cell with zeroes.
7269 ** In this case, temporarily copy the cell into the aOvflSpace[]
7270 ** buffer. It will be copied out again as soon as the aSpace[] buffer
7271 ** is allocated. */
drha5907a82017-06-19 11:44:22 +00007272 if( pBt->btsFlags & BTS_FAST_SECURE ){
drh8a575d92011-10-12 17:00:28 +00007273 int iOff;
7274
7275 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
drh43b18e12010-08-17 19:40:08 +00007276 if( (iOff+szNew[i])>(int)pBt->usableSize ){
dan2ed11e72010-02-26 15:09:19 +00007277 rc = SQLITE_CORRUPT_BKPT;
7278 memset(apOld, 0, (i+1)*sizeof(MemPage*));
7279 goto balance_cleanup;
7280 }else{
7281 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
7282 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
7283 }
drh5b47efa2010-02-12 18:18:39 +00007284 }
drh98add2e2009-07-20 17:11:49 +00007285 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
danielk19774dbaa892009-06-16 16:50:22 +00007286 }
drh8b2f49b2001-06-08 00:21:52 +00007287 }
7288
drha9121e42008-02-19 14:59:35 +00007289 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00007290 ** alignment */
drha9121e42008-02-19 14:59:35 +00007291 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00007292
drh8b2f49b2001-06-08 00:21:52 +00007293 /*
danielk1977634f2982005-03-28 08:44:07 +00007294 ** Allocate space for memory structures
7295 */
drhfacf0302008-06-17 15:12:00 +00007296 szScratch =
drh1ffd2472015-06-23 02:37:30 +00007297 nMaxCells*sizeof(u8*) /* b.apCell */
7298 + nMaxCells*sizeof(u16) /* b.szCell */
dan33ea4862014-10-09 19:35:37 +00007299 + pBt->pageSize; /* aSpace1 */
drh5279d342014-11-04 13:41:32 +00007300
drhcbd55b02014-11-04 14:22:27 +00007301 /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
7302 ** that is more than 6 times the database page size. */
mistachkin0fbd7352014-12-09 04:26:56 +00007303 assert( szScratch<=6*(int)pBt->pageSize );
drhb2a0f752017-08-28 15:51:35 +00007304 b.apCell = sqlite3StackAllocRaw(0, szScratch );
drh1ffd2472015-06-23 02:37:30 +00007305 if( b.apCell==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007306 rc = SQLITE_NOMEM_BKPT;
danielk1977634f2982005-03-28 08:44:07 +00007307 goto balance_cleanup;
7308 }
drh1ffd2472015-06-23 02:37:30 +00007309 b.szCell = (u16*)&b.apCell[nMaxCells];
7310 aSpace1 = (u8*)&b.szCell[nMaxCells];
drhea598cb2009-04-05 12:22:08 +00007311 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
drh14acc042001-06-10 19:56:58 +00007312
7313 /*
7314 ** Load pointers to all cells on sibling pages and the divider cells
drh1ffd2472015-06-23 02:37:30 +00007315 ** into the local b.apCell[] array. Make copies of the divider cells
dan33ea4862014-10-09 19:35:37 +00007316 ** into space obtained from aSpace1[]. The divider cells have already
7317 ** been removed from pParent.
drh4b70f112004-05-02 21:12:19 +00007318 **
7319 ** If the siblings are on leaf pages, then the child pointers of the
7320 ** divider cells are stripped from the cells before they are copied
drh1ffd2472015-06-23 02:37:30 +00007321 ** into aSpace1[]. In this way, all cells in b.apCell[] are without
drh4b70f112004-05-02 21:12:19 +00007322 ** child pointers. If siblings are not leaves, then all cell in
drh1ffd2472015-06-23 02:37:30 +00007323 ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
drh4b70f112004-05-02 21:12:19 +00007324 ** are alike.
drh96f5b762004-05-16 16:24:36 +00007325 **
7326 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
7327 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00007328 */
drh1ffd2472015-06-23 02:37:30 +00007329 b.pRef = apOld[0];
7330 leafCorrection = b.pRef->leaf*4;
7331 leafData = b.pRef->intKeyLeaf;
drh8b2f49b2001-06-08 00:21:52 +00007332 for(i=0; i<nOld; i++){
dan33ea4862014-10-09 19:35:37 +00007333 MemPage *pOld = apOld[i];
drh4edfdd32015-06-23 14:49:42 +00007334 int limit = pOld->nCell;
7335 u8 *aData = pOld->aData;
7336 u16 maskPage = pOld->maskPage;
drh4f4bf772015-06-23 17:09:53 +00007337 u8 *piCell = aData + pOld->cellOffset;
drhfe647dc2015-06-23 18:24:25 +00007338 u8 *piEnd;
danielk19774dbaa892009-06-16 16:50:22 +00007339
drh73d340a2015-05-28 11:23:11 +00007340 /* Verify that all sibling pages are of the same "type" (table-leaf,
7341 ** table-interior, index-leaf, or index-interior).
7342 */
7343 if( pOld->aData[0]!=apOld[0]->aData[0] ){
7344 rc = SQLITE_CORRUPT_BKPT;
7345 goto balance_cleanup;
7346 }
7347
drhfe647dc2015-06-23 18:24:25 +00007348 /* Load b.apCell[] with pointers to all cells in pOld. If pOld
7349 ** constains overflow cells, include them in the b.apCell[] array
7350 ** in the correct spot.
7351 **
7352 ** Note that when there are multiple overflow cells, it is always the
7353 ** case that they are sequential and adjacent. This invariant arises
7354 ** because multiple overflows can only occurs when inserting divider
7355 ** cells into a parent on a prior balance, and divider cells are always
7356 ** adjacent and are inserted in order. There is an assert() tagged
7357 ** with "NOTE 1" in the overflow cell insertion loop to prove this
7358 ** invariant.
drh4edfdd32015-06-23 14:49:42 +00007359 **
7360 ** This must be done in advance. Once the balance starts, the cell
7361 ** offset section of the btree page will be overwritten and we will no
7362 ** long be able to find the cells if a pointer to each cell is not saved
7363 ** first.
7364 */
drh36b78ee2016-01-20 01:32:00 +00007365 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
drh68f2a572011-06-03 17:50:49 +00007366 if( pOld->nOverflow>0 ){
drhfe647dc2015-06-23 18:24:25 +00007367 limit = pOld->aiOvfl[0];
drh68f2a572011-06-03 17:50:49 +00007368 for(j=0; j<limit; j++){
drh329428e2015-06-30 13:28:18 +00007369 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
drhfe647dc2015-06-23 18:24:25 +00007370 piCell += 2;
7371 b.nCell++;
drh68f2a572011-06-03 17:50:49 +00007372 }
drhfe647dc2015-06-23 18:24:25 +00007373 for(k=0; k<pOld->nOverflow; k++){
7374 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
drh4edfdd32015-06-23 14:49:42 +00007375 b.apCell[b.nCell] = pOld->apOvfl[k];
drh1ffd2472015-06-23 02:37:30 +00007376 b.nCell++;
drh68f2a572011-06-03 17:50:49 +00007377 }
drh1ffd2472015-06-23 02:37:30 +00007378 }
drhfe647dc2015-06-23 18:24:25 +00007379 piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
7380 while( piCell<piEnd ){
drh4edfdd32015-06-23 14:49:42 +00007381 assert( b.nCell<nMaxCells );
drh329428e2015-06-30 13:28:18 +00007382 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
drh4f4bf772015-06-23 17:09:53 +00007383 piCell += 2;
drh4edfdd32015-06-23 14:49:42 +00007384 b.nCell++;
drh4edfdd32015-06-23 14:49:42 +00007385 }
7386
drh1ffd2472015-06-23 02:37:30 +00007387 cntOld[i] = b.nCell;
danielk19774dbaa892009-06-16 16:50:22 +00007388 if( i<nOld-1 && !leafData){
shane36840fd2009-06-26 16:32:13 +00007389 u16 sz = (u16)szNew[i];
danielk19774dbaa892009-06-16 16:50:22 +00007390 u8 *pTemp;
drh1ffd2472015-06-23 02:37:30 +00007391 assert( b.nCell<nMaxCells );
7392 b.szCell[b.nCell] = sz;
danielk19774dbaa892009-06-16 16:50:22 +00007393 pTemp = &aSpace1[iSpace1];
7394 iSpace1 += sz;
drhe22e03e2010-08-18 21:19:03 +00007395 assert( sz<=pBt->maxLocal+23 );
drhfcd71b62011-04-05 22:08:24 +00007396 assert( iSpace1 <= (int)pBt->pageSize );
danielk19774dbaa892009-06-16 16:50:22 +00007397 memcpy(pTemp, apDiv[i], sz);
drh1ffd2472015-06-23 02:37:30 +00007398 b.apCell[b.nCell] = pTemp+leafCorrection;
danielk19774dbaa892009-06-16 16:50:22 +00007399 assert( leafCorrection==0 || leafCorrection==4 );
drh1ffd2472015-06-23 02:37:30 +00007400 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
danielk19774dbaa892009-06-16 16:50:22 +00007401 if( !pOld->leaf ){
7402 assert( leafCorrection==0 );
7403 assert( pOld->hdrOffset==0 );
7404 /* The right pointer of the child page pOld becomes the left
7405 ** pointer of the divider cell */
drh1ffd2472015-06-23 02:37:30 +00007406 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
danielk19774dbaa892009-06-16 16:50:22 +00007407 }else{
7408 assert( leafCorrection==4 );
drh1ffd2472015-06-23 02:37:30 +00007409 while( b.szCell[b.nCell]<4 ){
dan8f1eb8a2014-12-06 14:56:49 +00007410 /* Do not allow any cells smaller than 4 bytes. If a smaller cell
7411 ** does exist, pad it with 0x00 bytes. */
drh1ffd2472015-06-23 02:37:30 +00007412 assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
7413 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
danee7172f2014-12-24 18:11:50 +00007414 aSpace1[iSpace1++] = 0x00;
drh1ffd2472015-06-23 02:37:30 +00007415 b.szCell[b.nCell]++;
danielk1977ac11ee62005-01-15 12:45:51 +00007416 }
7417 }
drh1ffd2472015-06-23 02:37:30 +00007418 b.nCell++;
drh8b2f49b2001-06-08 00:21:52 +00007419 }
drh8b2f49b2001-06-08 00:21:52 +00007420 }
7421
7422 /*
drh1ffd2472015-06-23 02:37:30 +00007423 ** Figure out the number of pages needed to hold all b.nCell cells.
drh6019e162001-07-02 17:51:45 +00007424 ** Store this number in "k". Also compute szNew[] which is the total
7425 ** size of all cells on the i-th page and cntNew[] which is the index
drh1ffd2472015-06-23 02:37:30 +00007426 ** in b.apCell[] of the cell that divides page i from page i+1.
7427 ** cntNew[k] should equal b.nCell.
drh6019e162001-07-02 17:51:45 +00007428 **
drh96f5b762004-05-16 16:24:36 +00007429 ** Values computed by this block:
7430 **
7431 ** k: The total number of sibling pages
7432 ** szNew[i]: Spaced used on the i-th sibling page.
drh1ffd2472015-06-23 02:37:30 +00007433 ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
drh96f5b762004-05-16 16:24:36 +00007434 ** the right of the i-th sibling page.
7435 ** usableSpace: Number of bytes of space available on each sibling.
7436 **
drh8b2f49b2001-06-08 00:21:52 +00007437 */
drh43605152004-05-29 21:46:49 +00007438 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh658873b2015-06-22 20:02:04 +00007439 for(i=0; i<nOld; i++){
7440 MemPage *p = apOld[i];
7441 szNew[i] = usableSpace - p->nFree;
drh658873b2015-06-22 20:02:04 +00007442 for(j=0; j<p->nOverflow; j++){
7443 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
7444 }
7445 cntNew[i] = cntOld[i];
7446 }
7447 k = nOld;
7448 for(i=0; i<k; i++){
7449 int sz;
7450 while( szNew[i]>usableSpace ){
7451 if( i+1>=k ){
7452 k = i+2;
7453 if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
7454 szNew[k-1] = 0;
drh1ffd2472015-06-23 02:37:30 +00007455 cntNew[k-1] = b.nCell;
drh658873b2015-06-22 20:02:04 +00007456 }
drh1ffd2472015-06-23 02:37:30 +00007457 sz = 2 + cachedCellSize(&b, cntNew[i]-1);
drh658873b2015-06-22 20:02:04 +00007458 szNew[i] -= sz;
7459 if( !leafData ){
drh1ffd2472015-06-23 02:37:30 +00007460 if( cntNew[i]<b.nCell ){
7461 sz = 2 + cachedCellSize(&b, cntNew[i]);
7462 }else{
7463 sz = 0;
7464 }
drh658873b2015-06-22 20:02:04 +00007465 }
7466 szNew[i+1] += sz;
7467 cntNew[i]--;
7468 }
drh1ffd2472015-06-23 02:37:30 +00007469 while( cntNew[i]<b.nCell ){
7470 sz = 2 + cachedCellSize(&b, cntNew[i]);
drh658873b2015-06-22 20:02:04 +00007471 if( szNew[i]+sz>usableSpace ) break;
7472 szNew[i] += sz;
7473 cntNew[i]++;
7474 if( !leafData ){
drh1ffd2472015-06-23 02:37:30 +00007475 if( cntNew[i]<b.nCell ){
7476 sz = 2 + cachedCellSize(&b, cntNew[i]);
7477 }else{
7478 sz = 0;
7479 }
drh658873b2015-06-22 20:02:04 +00007480 }
7481 szNew[i+1] -= sz;
7482 }
drh1ffd2472015-06-23 02:37:30 +00007483 if( cntNew[i]>=b.nCell ){
drh658873b2015-06-22 20:02:04 +00007484 k = i+1;
drh672073a2015-06-24 12:07:40 +00007485 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
drh658873b2015-06-22 20:02:04 +00007486 rc = SQLITE_CORRUPT_BKPT;
7487 goto balance_cleanup;
drh6019e162001-07-02 17:51:45 +00007488 }
7489 }
drh96f5b762004-05-16 16:24:36 +00007490
7491 /*
7492 ** The packing computed by the previous block is biased toward the siblings
drh2a0df922014-10-30 23:14:56 +00007493 ** on the left side (siblings with smaller keys). The left siblings are
7494 ** always nearly full, while the right-most sibling might be nearly empty.
7495 ** The next block of code attempts to adjust the packing of siblings to
7496 ** get a better balance.
drh96f5b762004-05-16 16:24:36 +00007497 **
7498 ** This adjustment is more than an optimization. The packing above might
7499 ** be so out of balance as to be illegal. For example, the right-most
7500 ** sibling might be completely empty. This adjustment is not optional.
7501 */
drh6019e162001-07-02 17:51:45 +00007502 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00007503 int szRight = szNew[i]; /* Size of sibling on the right */
7504 int szLeft = szNew[i-1]; /* Size of sibling on the left */
7505 int r; /* Index of right-most cell in left sibling */
7506 int d; /* Index of first cell to the left of right sibling */
7507
7508 r = cntNew[i-1] - 1;
7509 d = r + 1 - leafData;
drh008d64c2015-06-23 16:00:24 +00007510 (void)cachedCellSize(&b, d);
drh672073a2015-06-24 12:07:40 +00007511 do{
drh1ffd2472015-06-23 02:37:30 +00007512 assert( d<nMaxCells );
7513 assert( r<nMaxCells );
drh1ffd2472015-06-23 02:37:30 +00007514 (void)cachedCellSize(&b, r);
7515 if( szRight!=0
drh0b4c0422016-07-14 19:48:08 +00007516 && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
drh1ffd2472015-06-23 02:37:30 +00007517 break;
7518 }
7519 szRight += b.szCell[d] + 2;
7520 szLeft -= b.szCell[r] + 2;
drh008d64c2015-06-23 16:00:24 +00007521 cntNew[i-1] = r;
drh008d64c2015-06-23 16:00:24 +00007522 r--;
7523 d--;
drh672073a2015-06-24 12:07:40 +00007524 }while( r>=0 );
drh96f5b762004-05-16 16:24:36 +00007525 szNew[i] = szRight;
7526 szNew[i-1] = szLeft;
drh672073a2015-06-24 12:07:40 +00007527 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
7528 rc = SQLITE_CORRUPT_BKPT;
7529 goto balance_cleanup;
7530 }
drh6019e162001-07-02 17:51:45 +00007531 }
drh09d0deb2005-08-02 17:13:09 +00007532
drh2a0df922014-10-30 23:14:56 +00007533 /* Sanity check: For a non-corrupt database file one of the follwing
7534 ** must be true:
7535 ** (1) We found one or more cells (cntNew[0])>0), or
7536 ** (2) pPage is a virtual root page. A virtual root page is when
7537 ** the real root page is page 1 and we are the only child of
7538 ** that page.
drh09d0deb2005-08-02 17:13:09 +00007539 */
drh2a0df922014-10-30 23:14:56 +00007540 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
dan33ea4862014-10-09 19:35:37 +00007541 TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
7542 apOld[0]->pgno, apOld[0]->nCell,
7543 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
7544 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
danielk1977e5765212009-06-17 11:13:28 +00007545 ));
7546
drh8b2f49b2001-06-08 00:21:52 +00007547 /*
drh6b308672002-07-08 02:16:37 +00007548 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00007549 */
danielk1977a50d9aa2009-06-08 14:49:45 +00007550 pageFlags = apOld[0]->aData[0];
drh14acc042001-06-10 19:56:58 +00007551 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00007552 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00007553 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00007554 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00007555 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00007556 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00007557 nNew++;
danielk197728129562005-01-11 10:25:06 +00007558 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00007559 }else{
drh7aa8f852006-03-28 00:24:44 +00007560 assert( i>0 );
dan428c2182012-08-06 18:50:11 +00007561 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
drh6b308672002-07-08 02:16:37 +00007562 if( rc ) goto balance_cleanup;
dan33ea4862014-10-09 19:35:37 +00007563 zeroPage(pNew, pageFlags);
drhda200cc2004-05-09 11:51:38 +00007564 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00007565 nNew++;
drh1ffd2472015-06-23 02:37:30 +00007566 cntOld[i] = b.nCell;
danielk19774dbaa892009-06-16 16:50:22 +00007567
7568 /* Set the pointer-map entry for the new sibling page. */
7569 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00007570 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00007571 if( rc!=SQLITE_OK ){
7572 goto balance_cleanup;
7573 }
7574 }
drh6b308672002-07-08 02:16:37 +00007575 }
drh8b2f49b2001-06-08 00:21:52 +00007576 }
7577
7578 /*
dan33ea4862014-10-09 19:35:37 +00007579 ** Reassign page numbers so that the new pages are in ascending order.
7580 ** This helps to keep entries in the disk file in order so that a scan
7581 ** of the table is closer to a linear scan through the file. That in turn
7582 ** helps the operating system to deliver pages from the disk more rapidly.
drhf9ffac92002-03-02 19:00:31 +00007583 **
dan33ea4862014-10-09 19:35:37 +00007584 ** An O(n^2) insertion sort algorithm is used, but since n is never more
7585 ** than (NB+2) (a small constant), that should not be a problem.
drhf9ffac92002-03-02 19:00:31 +00007586 **
dan33ea4862014-10-09 19:35:37 +00007587 ** When NB==3, this one optimization makes the database about 25% faster
7588 ** for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00007589 */
dan33ea4862014-10-09 19:35:37 +00007590 for(i=0; i<nNew; i++){
drh00fe08a2014-10-31 00:05:23 +00007591 aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
dan33ea4862014-10-09 19:35:37 +00007592 aPgFlags[i] = apNew[i]->pDbPage->flags;
dan89ca0b32014-10-25 20:36:28 +00007593 for(j=0; j<i; j++){
7594 if( aPgno[j]==aPgno[i] ){
7595 /* This branch is taken if the set of sibling pages somehow contains
7596 ** duplicate entries. This can happen if the database is corrupt.
7597 ** It would be simpler to detect this as part of the loop below, but
drhba0f9992014-10-30 20:48:44 +00007598 ** we do the detection here in order to avoid populating the pager
7599 ** cache with two separate objects associated with the same
7600 ** page number. */
dan89ca0b32014-10-25 20:36:28 +00007601 assert( CORRUPT_DB );
7602 rc = SQLITE_CORRUPT_BKPT;
7603 goto balance_cleanup;
drhf9ffac92002-03-02 19:00:31 +00007604 }
7605 }
dan33ea4862014-10-09 19:35:37 +00007606 }
7607 for(i=0; i<nNew; i++){
dan31f4e992014-10-24 20:57:03 +00007608 int iBest = 0; /* aPgno[] index of page number to use */
dan31f4e992014-10-24 20:57:03 +00007609 for(j=1; j<nNew; j++){
drh00fe08a2014-10-31 00:05:23 +00007610 if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
drhf9ffac92002-03-02 19:00:31 +00007611 }
drh00fe08a2014-10-31 00:05:23 +00007612 pgno = aPgOrder[iBest];
7613 aPgOrder[iBest] = 0xffffffff;
dan31f4e992014-10-24 20:57:03 +00007614 if( iBest!=i ){
7615 if( iBest>i ){
7616 sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
7617 }
7618 sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
7619 apNew[i]->pgno = pgno;
drhf9ffac92002-03-02 19:00:31 +00007620 }
7621 }
dan33ea4862014-10-09 19:35:37 +00007622
7623 TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
7624 "%d(%d nc=%d) %d(%d nc=%d)\n",
7625 apNew[0]->pgno, szNew[0], cntNew[0],
danielk19774dbaa892009-06-16 16:50:22 +00007626 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
dan33ea4862014-10-09 19:35:37 +00007627 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
danielk19774dbaa892009-06-16 16:50:22 +00007628 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
dan33ea4862014-10-09 19:35:37 +00007629 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
danielk19774dbaa892009-06-16 16:50:22 +00007630 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
dan33ea4862014-10-09 19:35:37 +00007631 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
7632 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
7633 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
7634 ));
danielk19774dbaa892009-06-16 16:50:22 +00007635
7636 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7637 put4byte(pRight, apNew[nNew-1]->pgno);
drh24cd67e2004-05-10 16:18:47 +00007638
dan33ea4862014-10-09 19:35:37 +00007639 /* If the sibling pages are not leaves, ensure that the right-child pointer
7640 ** of the right-most new sibling page is set to the value that was
7641 ** originally in the same field of the right-most old sibling page. */
7642 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
7643 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
7644 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
7645 }
danielk1977ac11ee62005-01-15 12:45:51 +00007646
dan33ea4862014-10-09 19:35:37 +00007647 /* Make any required updates to pointer map entries associated with
7648 ** cells stored on sibling pages following the balance operation. Pointer
7649 ** map entries associated with divider cells are set by the insertCell()
7650 ** routine. The associated pointer map entries are:
7651 **
7652 ** a) if the cell contains a reference to an overflow chain, the
7653 ** entry associated with the first page in the overflow chain, and
7654 **
7655 ** b) if the sibling pages are not leaves, the child page associated
7656 ** with the cell.
7657 **
7658 ** If the sibling pages are not leaves, then the pointer map entry
7659 ** associated with the right-child of each sibling may also need to be
7660 ** updated. This happens below, after the sibling pages have been
7661 ** populated, not here.
danielk1977ac11ee62005-01-15 12:45:51 +00007662 */
dan33ea4862014-10-09 19:35:37 +00007663 if( ISAUTOVACUUM ){
7664 MemPage *pNew = apNew[0];
7665 u8 *aOld = pNew->aData;
7666 int cntOldNext = pNew->nCell + pNew->nOverflow;
7667 int usableSize = pBt->usableSize;
7668 int iNew = 0;
7669 int iOld = 0;
danielk1977ac11ee62005-01-15 12:45:51 +00007670
drh1ffd2472015-06-23 02:37:30 +00007671 for(i=0; i<b.nCell; i++){
7672 u8 *pCell = b.apCell[i];
dan33ea4862014-10-09 19:35:37 +00007673 if( i==cntOldNext ){
7674 MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
7675 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
7676 aOld = pOld->aData;
drh4b70f112004-05-02 21:12:19 +00007677 }
dan33ea4862014-10-09 19:35:37 +00007678 if( i==cntNew[iNew] ){
7679 pNew = apNew[++iNew];
7680 if( !leafData ) continue;
7681 }
danielk197785d90ca2008-07-19 14:25:15 +00007682
dan33ea4862014-10-09 19:35:37 +00007683 /* Cell pCell is destined for new sibling page pNew. Originally, it
drhba0f9992014-10-30 20:48:44 +00007684 ** was either part of sibling page iOld (possibly an overflow cell),
dan33ea4862014-10-09 19:35:37 +00007685 ** or else the divider cell to the left of sibling page iOld. So,
7686 ** if sibling page iOld had the same page number as pNew, and if
7687 ** pCell really was a part of sibling page iOld (not a divider or
7688 ** overflow cell), we can skip updating the pointer map entries. */
drhd52d52b2014-12-06 02:05:44 +00007689 if( iOld>=nNew
7690 || pNew->pgno!=aPgno[iOld]
drhac536e62015-12-10 15:09:17 +00007691 || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
drhd52d52b2014-12-06 02:05:44 +00007692 ){
dan33ea4862014-10-09 19:35:37 +00007693 if( !leafCorrection ){
7694 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
7695 }
drh1ffd2472015-06-23 02:37:30 +00007696 if( cachedCellSize(&b,i)>pNew->minLocal ){
dan33ea4862014-10-09 19:35:37 +00007697 ptrmapPutOvflPtr(pNew, pCell, &rc);
danielk1977ac11ee62005-01-15 12:45:51 +00007698 }
drhea82b372015-06-23 21:35:28 +00007699 if( rc ) goto balance_cleanup;
drh43605152004-05-29 21:46:49 +00007700 }
drh14acc042001-06-10 19:56:58 +00007701 }
7702 }
dan33ea4862014-10-09 19:35:37 +00007703
7704 /* Insert new divider cells into pParent. */
7705 for(i=0; i<nNew-1; i++){
7706 u8 *pCell;
7707 u8 *pTemp;
7708 int sz;
7709 MemPage *pNew = apNew[i];
7710 j = cntNew[i];
7711
7712 assert( j<nMaxCells );
drh1ffd2472015-06-23 02:37:30 +00007713 assert( b.apCell[j]!=0 );
7714 pCell = b.apCell[j];
7715 sz = b.szCell[j] + leafCorrection;
dan33ea4862014-10-09 19:35:37 +00007716 pTemp = &aOvflSpace[iOvflSpace];
7717 if( !pNew->leaf ){
7718 memcpy(&pNew->aData[8], pCell, 4);
7719 }else if( leafData ){
7720 /* If the tree is a leaf-data tree, and the siblings are leaves,
drh1ffd2472015-06-23 02:37:30 +00007721 ** then there is no divider cell in b.apCell[]. Instead, the divider
dan33ea4862014-10-09 19:35:37 +00007722 ** cell consists of the integer key for the right-most cell of
7723 ** the sibling-page assembled above only.
7724 */
7725 CellInfo info;
7726 j--;
drh1ffd2472015-06-23 02:37:30 +00007727 pNew->xParseCell(pNew, b.apCell[j], &info);
dan33ea4862014-10-09 19:35:37 +00007728 pCell = pTemp;
7729 sz = 4 + putVarint(&pCell[4], info.nKey);
7730 pTemp = 0;
7731 }else{
7732 pCell -= 4;
7733 /* Obscure case for non-leaf-data trees: If the cell at pCell was
7734 ** previously stored on a leaf node, and its reported size was 4
7735 ** bytes, then it may actually be smaller than this
7736 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
7737 ** any cell). But it is important to pass the correct size to
7738 ** insertCell(), so reparse the cell now.
7739 **
drhc1fb2b82016-03-09 03:29:27 +00007740 ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
7741 ** and WITHOUT ROWID tables with exactly one column which is the
7742 ** primary key.
dan33ea4862014-10-09 19:35:37 +00007743 */
drh1ffd2472015-06-23 02:37:30 +00007744 if( b.szCell[j]==4 ){
dan33ea4862014-10-09 19:35:37 +00007745 assert(leafCorrection==4);
drh25ada072015-06-19 15:07:14 +00007746 sz = pParent->xCellSize(pParent, pCell);
dan33ea4862014-10-09 19:35:37 +00007747 }
7748 }
7749 iOvflSpace += sz;
7750 assert( sz<=pBt->maxLocal+23 );
7751 assert( iOvflSpace <= (int)pBt->pageSize );
7752 insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
7753 if( rc!=SQLITE_OK ) goto balance_cleanup;
7754 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7755 }
7756
7757 /* Now update the actual sibling pages. The order in which they are updated
7758 ** is important, as this code needs to avoid disrupting any page from which
7759 ** cells may still to be read. In practice, this means:
7760 **
drhd836d422014-10-31 14:26:36 +00007761 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
7762 ** then it is not safe to update page apNew[iPg] until after
7763 ** the left-hand sibling apNew[iPg-1] has been updated.
dan33ea4862014-10-09 19:35:37 +00007764 **
drhd836d422014-10-31 14:26:36 +00007765 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
7766 ** then it is not safe to update page apNew[iPg] until after
7767 ** the right-hand sibling apNew[iPg+1] has been updated.
dan33ea4862014-10-09 19:35:37 +00007768 **
7769 ** If neither of the above apply, the page is safe to update.
drhd836d422014-10-31 14:26:36 +00007770 **
7771 ** The iPg value in the following loop starts at nNew-1 goes down
7772 ** to 0, then back up to nNew-1 again, thus making two passes over
7773 ** the pages. On the initial downward pass, only condition (1) above
7774 ** needs to be tested because (2) will always be true from the previous
7775 ** step. On the upward pass, both conditions are always true, so the
7776 ** upwards pass simply processes pages that were missed on the downward
7777 ** pass.
dan33ea4862014-10-09 19:35:37 +00007778 */
drhbec021b2014-10-31 12:22:00 +00007779 for(i=1-nNew; i<nNew; i++){
7780 int iPg = i<0 ? -i : i;
drhbec021b2014-10-31 12:22:00 +00007781 assert( iPg>=0 && iPg<nNew );
drhd836d422014-10-31 14:26:36 +00007782 if( abDone[iPg] ) continue; /* Skip pages already processed */
7783 if( i>=0 /* On the upwards pass, or... */
7784 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
dan33ea4862014-10-09 19:35:37 +00007785 ){
dan09c68402014-10-11 20:00:24 +00007786 int iNew;
7787 int iOld;
7788 int nNewCell;
7789
drhd836d422014-10-31 14:26:36 +00007790 /* Verify condition (1): If cells are moving left, update iPg
7791 ** only after iPg-1 has already been updated. */
7792 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
7793
7794 /* Verify condition (2): If cells are moving right, update iPg
7795 ** only after iPg+1 has already been updated. */
7796 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
7797
dan09c68402014-10-11 20:00:24 +00007798 if( iPg==0 ){
7799 iNew = iOld = 0;
7800 nNewCell = cntNew[0];
7801 }else{
drh1ffd2472015-06-23 02:37:30 +00007802 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
dan09c68402014-10-11 20:00:24 +00007803 iNew = cntNew[iPg-1] + !leafData;
7804 nNewCell = cntNew[iPg] - iNew;
7805 }
7806
drh1ffd2472015-06-23 02:37:30 +00007807 rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
drh658873b2015-06-22 20:02:04 +00007808 if( rc ) goto balance_cleanup;
drhd836d422014-10-31 14:26:36 +00007809 abDone[iPg]++;
dand7b545b2014-10-13 18:03:27 +00007810 apNew[iPg]->nFree = usableSpace-szNew[iPg];
dan09c68402014-10-11 20:00:24 +00007811 assert( apNew[iPg]->nOverflow==0 );
7812 assert( apNew[iPg]->nCell==nNewCell );
dan33ea4862014-10-09 19:35:37 +00007813 }
7814 }
drhd836d422014-10-31 14:26:36 +00007815
7816 /* All pages have been processed exactly once */
dan33ea4862014-10-09 19:35:37 +00007817 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
7818
drh7aa8f852006-03-28 00:24:44 +00007819 assert( nOld>0 );
7820 assert( nNew>0 );
drh14acc042001-06-10 19:56:58 +00007821
danielk197713bd99f2009-06-24 05:40:34 +00007822 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
7823 /* The root page of the b-tree now contains no cells. The only sibling
7824 ** page is the right-child of the parent. Copy the contents of the
7825 ** child page into the parent, decreasing the overall height of the
7826 ** b-tree structure by one. This is described as the "balance-shallower"
7827 ** sub-algorithm in some documentation.
7828 **
7829 ** If this is an auto-vacuum database, the call to copyNodeContent()
7830 ** sets all pointer-map entries corresponding to database image pages
7831 ** for which the pointer is stored within the content being copied.
7832 **
drh768f2902014-10-31 02:51:41 +00007833 ** It is critical that the child page be defragmented before being
7834 ** copied into the parent, because if the parent is page 1 then it will
7835 ** by smaller than the child due to the database header, and so all the
7836 ** free space needs to be up front.
7837 */
drh9b5351d2015-09-30 14:19:08 +00007838 assert( nNew==1 || CORRUPT_DB );
dan3b2ede12017-02-25 16:24:02 +00007839 rc = defragmentPage(apNew[0], -1);
drh768f2902014-10-31 02:51:41 +00007840 testcase( rc!=SQLITE_OK );
danielk197713bd99f2009-06-24 05:40:34 +00007841 assert( apNew[0]->nFree ==
drh768f2902014-10-31 02:51:41 +00007842 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
7843 || rc!=SQLITE_OK
danielk197713bd99f2009-06-24 05:40:34 +00007844 );
drhc314dc72009-07-21 11:52:34 +00007845 copyNodeContent(apNew[0], pParent, &rc);
7846 freePage(apNew[0], &rc);
dan33ea4862014-10-09 19:35:37 +00007847 }else if( ISAUTOVACUUM && !leafCorrection ){
7848 /* Fix the pointer map entries associated with the right-child of each
7849 ** sibling page. All other pointer map entries have already been taken
7850 ** care of. */
7851 for(i=0; i<nNew; i++){
7852 u32 key = get4byte(&apNew[i]->aData[8]);
7853 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00007854 }
dan33ea4862014-10-09 19:35:37 +00007855 }
danielk19774dbaa892009-06-16 16:50:22 +00007856
dan33ea4862014-10-09 19:35:37 +00007857 assert( pParent->isInit );
7858 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
drh1ffd2472015-06-23 02:37:30 +00007859 nOld, nNew, b.nCell));
danielk19774dbaa892009-06-16 16:50:22 +00007860
dan33ea4862014-10-09 19:35:37 +00007861 /* Free any old pages that were not reused as new pages.
7862 */
7863 for(i=nNew; i<nOld; i++){
7864 freePage(apOld[i], &rc);
7865 }
danielk19774dbaa892009-06-16 16:50:22 +00007866
7867#if 0
dan33ea4862014-10-09 19:35:37 +00007868 if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
danielk19774dbaa892009-06-16 16:50:22 +00007869 /* The ptrmapCheckPages() contains assert() statements that verify that
7870 ** all pointer map pages are set correctly. This is helpful while
7871 ** debugging. This is usually disabled because a corrupt database may
7872 ** cause an assert() statement to fail. */
7873 ptrmapCheckPages(apNew, nNew);
7874 ptrmapCheckPages(&pParent, 1);
danielk19774dbaa892009-06-16 16:50:22 +00007875 }
dan33ea4862014-10-09 19:35:37 +00007876#endif
danielk1977cd581a72009-06-23 15:43:39 +00007877
drh8b2f49b2001-06-08 00:21:52 +00007878 /*
drh14acc042001-06-10 19:56:58 +00007879 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00007880 */
drh14acc042001-06-10 19:56:58 +00007881balance_cleanup:
drhb2a0f752017-08-28 15:51:35 +00007882 sqlite3StackFree(0, b.apCell);
drh8b2f49b2001-06-08 00:21:52 +00007883 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00007884 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00007885 }
drh14acc042001-06-10 19:56:58 +00007886 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00007887 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00007888 }
danielk1977eaa06f62008-09-18 17:34:44 +00007889
drh8b2f49b2001-06-08 00:21:52 +00007890 return rc;
7891}
7892
drh43605152004-05-29 21:46:49 +00007893
7894/*
danielk1977a50d9aa2009-06-08 14:49:45 +00007895** This function is called when the root page of a b-tree structure is
7896** overfull (has one or more overflow pages).
drh43605152004-05-29 21:46:49 +00007897**
danielk1977a50d9aa2009-06-08 14:49:45 +00007898** A new child page is allocated and the contents of the current root
7899** page, including overflow cells, are copied into the child. The root
7900** page is then overwritten to make it an empty page with the right-child
7901** pointer pointing to the new page.
7902**
7903** Before returning, all pointer-map entries corresponding to pages
7904** that the new child-page now contains pointers to are updated. The
7905** entry corresponding to the new right-child pointer of the root
7906** page is also updated.
7907**
7908** If successful, *ppChild is set to contain a reference to the child
7909** page and SQLITE_OK is returned. In this case the caller is required
7910** to call releasePage() on *ppChild exactly once. If an error occurs,
7911** an error code is returned and *ppChild is set to 0.
drh43605152004-05-29 21:46:49 +00007912*/
danielk1977a50d9aa2009-06-08 14:49:45 +00007913static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
7914 int rc; /* Return value from subprocedures */
7915 MemPage *pChild = 0; /* Pointer to a new child page */
shane5eff7cf2009-08-10 03:57:58 +00007916 Pgno pgnoChild = 0; /* Page number of the new child page */
danielk1977a50d9aa2009-06-08 14:49:45 +00007917 BtShared *pBt = pRoot->pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00007918
danielk1977a50d9aa2009-06-08 14:49:45 +00007919 assert( pRoot->nOverflow>0 );
drh1fee73e2007-08-29 04:00:57 +00007920 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bc2ca9e2008-11-13 14:28:28 +00007921
danielk1977a50d9aa2009-06-08 14:49:45 +00007922 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
7923 ** page that will become the new right-child of pPage. Copy the contents
7924 ** of the node stored on pRoot into the new child page.
7925 */
drh98add2e2009-07-20 17:11:49 +00007926 rc = sqlite3PagerWrite(pRoot->pDbPage);
7927 if( rc==SQLITE_OK ){
7928 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
drhc314dc72009-07-21 11:52:34 +00007929 copyNodeContent(pRoot, pChild, &rc);
7930 if( ISAUTOVACUUM ){
7931 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
drh98add2e2009-07-20 17:11:49 +00007932 }
7933 }
7934 if( rc ){
danielk1977a50d9aa2009-06-08 14:49:45 +00007935 *ppChild = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00007936 releasePage(pChild);
danielk1977a50d9aa2009-06-08 14:49:45 +00007937 return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00007938 }
danielk1977a50d9aa2009-06-08 14:49:45 +00007939 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
7940 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
7941 assert( pChild->nCell==pRoot->nCell );
danielk197771d5d2c2008-09-29 11:49:47 +00007942
danielk1977a50d9aa2009-06-08 14:49:45 +00007943 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
7944
7945 /* Copy the overflow cells from pRoot to pChild */
drh2cbd78b2012-02-02 19:37:18 +00007946 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
7947 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
7948 memcpy(pChild->apOvfl, pRoot->apOvfl,
7949 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
danielk1977a50d9aa2009-06-08 14:49:45 +00007950 pChild->nOverflow = pRoot->nOverflow;
danielk1977a50d9aa2009-06-08 14:49:45 +00007951
7952 /* Zero the contents of pRoot. Then install pChild as the right-child. */
7953 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
7954 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
7955
7956 *ppChild = pChild;
7957 return SQLITE_OK;
drh43605152004-05-29 21:46:49 +00007958}
7959
7960/*
danielk197771d5d2c2008-09-29 11:49:47 +00007961** The page that pCur currently points to has just been modified in
7962** some way. This function figures out if this modification means the
7963** tree needs to be balanced, and if so calls the appropriate balancing
danielk1977a50d9aa2009-06-08 14:49:45 +00007964** routine. Balancing routines are:
7965**
7966** balance_quick()
danielk1977a50d9aa2009-06-08 14:49:45 +00007967** balance_deeper()
7968** balance_nonroot()
drh43605152004-05-29 21:46:49 +00007969*/
danielk1977a50d9aa2009-06-08 14:49:45 +00007970static int balance(BtCursor *pCur){
drh43605152004-05-29 21:46:49 +00007971 int rc = SQLITE_OK;
danielk1977a50d9aa2009-06-08 14:49:45 +00007972 const int nMin = pCur->pBt->usableSize * 2 / 3;
7973 u8 aBalanceQuickSpace[13];
7974 u8 *pFree = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00007975
drhcc5f8a42016-02-06 22:32:06 +00007976 VVA_ONLY( int balance_quick_called = 0 );
7977 VVA_ONLY( int balance_deeper_called = 0 );
danielk1977a50d9aa2009-06-08 14:49:45 +00007978
7979 do {
7980 int iPage = pCur->iPage;
drh352a35a2017-08-15 03:46:47 +00007981 MemPage *pPage = pCur->pPage;
danielk1977a50d9aa2009-06-08 14:49:45 +00007982
7983 if( iPage==0 ){
7984 if( pPage->nOverflow ){
7985 /* The root page of the b-tree is overfull. In this case call the
7986 ** balance_deeper() function to create a new child for the root-page
7987 ** and copy the current contents of the root-page to it. The
7988 ** next iteration of the do-loop will balance the child page.
7989 */
drhcc5f8a42016-02-06 22:32:06 +00007990 assert( balance_deeper_called==0 );
7991 VVA_ONLY( balance_deeper_called++ );
danielk1977a50d9aa2009-06-08 14:49:45 +00007992 rc = balance_deeper(pPage, &pCur->apPage[1]);
7993 if( rc==SQLITE_OK ){
7994 pCur->iPage = 1;
drh75e96b32017-04-01 00:20:06 +00007995 pCur->ix = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00007996 pCur->aiIdx[0] = 0;
drh352a35a2017-08-15 03:46:47 +00007997 pCur->apPage[0] = pPage;
7998 pCur->pPage = pCur->apPage[1];
7999 assert( pCur->pPage->nOverflow );
danielk1977a50d9aa2009-06-08 14:49:45 +00008000 }
danielk1977a50d9aa2009-06-08 14:49:45 +00008001 }else{
danielk1977a50d9aa2009-06-08 14:49:45 +00008002 break;
8003 }
8004 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
8005 break;
8006 }else{
8007 MemPage * const pParent = pCur->apPage[iPage-1];
8008 int const iIdx = pCur->aiIdx[iPage-1];
8009
8010 rc = sqlite3PagerWrite(pParent->pDbPage);
8011 if( rc==SQLITE_OK ){
8012#ifndef SQLITE_OMIT_QUICKBALANCE
drh3e28ff52014-09-24 00:59:08 +00008013 if( pPage->intKeyLeaf
danielk1977a50d9aa2009-06-08 14:49:45 +00008014 && pPage->nOverflow==1
drh2cbd78b2012-02-02 19:37:18 +00008015 && pPage->aiOvfl[0]==pPage->nCell
danielk1977a50d9aa2009-06-08 14:49:45 +00008016 && pParent->pgno!=1
8017 && pParent->nCell==iIdx
8018 ){
8019 /* Call balance_quick() to create a new sibling of pPage on which
8020 ** to store the overflow cell. balance_quick() inserts a new cell
8021 ** into pParent, which may cause pParent overflow. If this
peter.d.reid60ec9142014-09-06 16:39:46 +00008022 ** happens, the next iteration of the do-loop will balance pParent
danielk1977a50d9aa2009-06-08 14:49:45 +00008023 ** use either balance_nonroot() or balance_deeper(). Until this
8024 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
8025 ** buffer.
8026 **
8027 ** The purpose of the following assert() is to check that only a
8028 ** single call to balance_quick() is made for each call to this
8029 ** function. If this were not verified, a subtle bug involving reuse
8030 ** of the aBalanceQuickSpace[] might sneak in.
8031 */
drhcc5f8a42016-02-06 22:32:06 +00008032 assert( balance_quick_called==0 );
8033 VVA_ONLY( balance_quick_called++ );
danielk1977a50d9aa2009-06-08 14:49:45 +00008034 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
8035 }else
8036#endif
8037 {
8038 /* In this case, call balance_nonroot() to redistribute cells
8039 ** between pPage and up to 2 of its sibling pages. This involves
8040 ** modifying the contents of pParent, which may cause pParent to
8041 ** become overfull or underfull. The next iteration of the do-loop
8042 ** will balance the parent page to correct this.
8043 **
8044 ** If the parent page becomes overfull, the overflow cell or cells
8045 ** are stored in the pSpace buffer allocated immediately below.
8046 ** A subsequent iteration of the do-loop will deal with this by
8047 ** calling balance_nonroot() (balance_deeper() may be called first,
8048 ** but it doesn't deal with overflow cells - just moves them to a
8049 ** different page). Once this subsequent call to balance_nonroot()
8050 ** has completed, it is safe to release the pSpace buffer used by
8051 ** the previous call, as the overflow cell data will have been
8052 ** copied either into the body of a database page or into the new
8053 ** pSpace buffer passed to the latter call to balance_nonroot().
8054 */
8055 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
drhe0997b32015-03-20 14:57:50 +00008056 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
8057 pCur->hints&BTREE_BULKLOAD);
danielk1977a50d9aa2009-06-08 14:49:45 +00008058 if( pFree ){
8059 /* If pFree is not NULL, it points to the pSpace buffer used
8060 ** by a previous call to balance_nonroot(). Its contents are
8061 ** now stored either on real database pages or within the
8062 ** new pSpace buffer, so it may be safely freed here. */
8063 sqlite3PageFree(pFree);
8064 }
8065
danielk19774dbaa892009-06-16 16:50:22 +00008066 /* The pSpace buffer will be freed after the next call to
8067 ** balance_nonroot(), or just before this function returns, whichever
8068 ** comes first. */
danielk1977a50d9aa2009-06-08 14:49:45 +00008069 pFree = pSpace;
danielk1977a50d9aa2009-06-08 14:49:45 +00008070 }
8071 }
8072
8073 pPage->nOverflow = 0;
8074
8075 /* The next iteration of the do-loop balances the parent page. */
8076 releasePage(pPage);
8077 pCur->iPage--;
drhcbd33492015-03-25 13:06:54 +00008078 assert( pCur->iPage>=0 );
drh352a35a2017-08-15 03:46:47 +00008079 pCur->pPage = pCur->apPage[pCur->iPage];
drh43605152004-05-29 21:46:49 +00008080 }
danielk1977a50d9aa2009-06-08 14:49:45 +00008081 }while( rc==SQLITE_OK );
8082
8083 if( pFree ){
8084 sqlite3PageFree(pFree);
drh43605152004-05-29 21:46:49 +00008085 }
8086 return rc;
8087}
8088
drhf74b8d92002-09-01 23:20:45 +00008089
8090/*
drh8eeb4462016-05-21 20:03:42 +00008091** Insert a new record into the BTree. The content of the new record
8092** is described by the pX object. The pCur cursor is used only to
8093** define what table the record should be inserted into, and is left
8094** pointing at a random location.
drh4b70f112004-05-02 21:12:19 +00008095**
drh8eeb4462016-05-21 20:03:42 +00008096** For a table btree (used for rowid tables), only the pX.nKey value of
8097** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
8098** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
8099** hold the content of the row.
8100**
8101** For an index btree (used for indexes and WITHOUT ROWID tables), the
8102** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
8103** pX.pData,nData,nZero fields must be zero.
danielk1977de630352009-05-04 11:42:29 +00008104**
8105** If the seekResult parameter is non-zero, then a successful call to
drheaf6ae22016-11-09 20:14:34 +00008106** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
8107** been performed. In other words, if seekResult!=0 then the cursor
8108** is currently pointing to a cell that will be adjacent to the cell
8109** to be inserted. If seekResult<0 then pCur points to a cell that is
8110** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
8111** that is larger than (pKey,nKey).
danielk1977de630352009-05-04 11:42:29 +00008112**
drheaf6ae22016-11-09 20:14:34 +00008113** If seekResult==0, that means pCur is pointing at some unknown location.
8114** In that case, this routine must seek the cursor to the correct insertion
8115** point for (pKey,nKey) before doing the insertion. For index btrees,
8116** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
8117** key values and pX->aMem can be used instead of pX->pKey to avoid having
8118** to decode the key.
drh3b7511c2001-05-26 13:15:44 +00008119*/
drh3aac2dd2004-04-26 14:10:20 +00008120int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00008121 BtCursor *pCur, /* Insert data into the table of this cursor */
drh8eeb4462016-05-21 20:03:42 +00008122 const BtreePayload *pX, /* Content of the row to be inserted */
danf91c1312017-01-10 20:04:38 +00008123 int flags, /* True if this is likely an append */
danielk19773509a652009-07-06 18:56:13 +00008124 int seekResult /* Result of prior MovetoUnpacked() call */
drh3b7511c2001-05-26 13:15:44 +00008125){
drh3b7511c2001-05-26 13:15:44 +00008126 int rc;
drh3e9ca092009-09-08 01:14:48 +00008127 int loc = seekResult; /* -1: before desired location +1: after */
drh1d452e12009-11-01 19:26:59 +00008128 int szNew = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00008129 int idx;
drh3b7511c2001-05-26 13:15:44 +00008130 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00008131 Btree *p = pCur->pBtree;
8132 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00008133 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00008134 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00008135
danf91c1312017-01-10 20:04:38 +00008136 assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
8137
drh98add2e2009-07-20 17:11:49 +00008138 if( pCur->eState==CURSOR_FAULT ){
8139 assert( pCur->skipNext!=SQLITE_OK );
8140 return pCur->skipNext;
8141 }
8142
dan7a2347e2016-01-07 16:43:54 +00008143 assert( cursorOwnsBtShared(pCur) );
drh3f387402014-09-24 01:23:00 +00008144 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
8145 && pBt->inTransaction==TRANS_WRITE
drhc9166342012-01-05 23:32:06 +00008146 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk197796d48e92009-06-29 06:00:37 +00008147 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8148
danielk197731d31b82009-07-13 13:18:07 +00008149 /* Assert that the caller has been consistent. If this cursor was opened
8150 ** expecting an index b-tree, then the caller should be inserting blob
8151 ** keys with no associated data. If the cursor was opened expecting an
8152 ** intkey table, the caller should be inserting integer keys with a
8153 ** blob of associated data. */
drh8eeb4462016-05-21 20:03:42 +00008154 assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
danielk197731d31b82009-07-13 13:18:07 +00008155
danielk19779c3acf32009-05-02 07:36:49 +00008156 /* Save the positions of any other cursors open on this table.
8157 **
danielk19773509a652009-07-06 18:56:13 +00008158 ** In some cases, the call to btreeMoveto() below is a no-op. For
danielk19779c3acf32009-05-02 07:36:49 +00008159 ** example, when inserting data into a table with auto-generated integer
8160 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
8161 ** integer key to use. It then calls this function to actually insert the
danielk19773509a652009-07-06 18:56:13 +00008162 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
danielk19779c3acf32009-05-02 07:36:49 +00008163 ** that the cursor is already where it needs to be and returns without
8164 ** doing any work. To avoid thwarting these optimizations, it is important
8165 ** not to clear the cursor here.
8166 */
drh27fb7462015-06-30 02:47:36 +00008167 if( pCur->curFlags & BTCF_Multiple ){
8168 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8169 if( rc ) return rc;
drhd60f4f42012-03-23 14:23:52 +00008170 }
8171
danielk197771d5d2c2008-09-29 11:49:47 +00008172 if( pCur->pKeyInfo==0 ){
drh8eeb4462016-05-21 20:03:42 +00008173 assert( pX->pKey==0 );
drhe0670b62014-02-12 21:31:12 +00008174 /* If this is an insert into a table b-tree, invalidate any incrblob
8175 ** cursors open on the row being replaced */
drh9ca431a2017-03-29 18:03:50 +00008176 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
drhe0670b62014-02-12 21:31:12 +00008177
danf91c1312017-01-10 20:04:38 +00008178 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8179 ** to a row with the same key as the new entry being inserted. */
8180 assert( (flags & BTREE_SAVEPOSITION)==0 ||
8181 ((pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey) );
8182
drhe0670b62014-02-12 21:31:12 +00008183 /* If the cursor is currently on the last row and we are appending a
drh207c8172015-06-29 23:01:32 +00008184 ** new row onto the end, set the "loc" to avoid an unnecessary
8185 ** btreeMoveto() call */
drh7a1c28d2016-11-10 20:42:08 +00008186 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
8187 loc = 0;
drh207c8172015-06-29 23:01:32 +00008188 }else if( loc==0 ){
danf91c1312017-01-10 20:04:38 +00008189 rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
drh207c8172015-06-29 23:01:32 +00008190 if( rc ) return rc;
drhe0670b62014-02-12 21:31:12 +00008191 }
danf91c1312017-01-10 20:04:38 +00008192 }else if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
drh9b4eaeb2016-11-09 00:10:33 +00008193 if( pX->nMem ){
8194 UnpackedRecord r;
drh9b4eaeb2016-11-09 00:10:33 +00008195 r.pKeyInfo = pCur->pKeyInfo;
8196 r.aMem = pX->aMem;
8197 r.nField = pX->nMem;
drh8c730bc2016-12-10 13:12:55 +00008198 r.default_rc = 0;
8199 r.errCode = 0;
8200 r.r1 = 0;
8201 r.r2 = 0;
8202 r.eqSeen = 0;
danf91c1312017-01-10 20:04:38 +00008203 rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
drh9b4eaeb2016-11-09 00:10:33 +00008204 }else{
danf91c1312017-01-10 20:04:38 +00008205 rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
drh9b4eaeb2016-11-09 00:10:33 +00008206 }
drh4c301aa2009-07-15 17:25:45 +00008207 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00008208 }
danielk1977b980d2212009-06-22 18:03:51 +00008209 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
danielk1977da184232006-01-05 11:34:32 +00008210
drh352a35a2017-08-15 03:46:47 +00008211 pPage = pCur->pPage;
drh8eeb4462016-05-21 20:03:42 +00008212 assert( pPage->intKey || pX->nKey>=0 );
drh44845222008-07-17 18:39:57 +00008213 assert( pPage->leaf || !pPage->intKey );
danielk19778f880a82009-07-13 09:41:45 +00008214
drh3a4c1412004-05-09 20:40:11 +00008215 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
drh8eeb4462016-05-21 20:03:42 +00008216 pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
drh3a4c1412004-05-09 20:40:11 +00008217 loc==0 ? "overwrite" : "new entry"));
danielk197771d5d2c2008-09-29 11:49:47 +00008218 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00008219 newCell = pBt->pTmpSpace;
drh3fbb0222014-09-24 19:47:27 +00008220 assert( newCell!=0 );
drh8eeb4462016-05-21 20:03:42 +00008221 rc = fillInCell(pPage, newCell, pX, &szNew);
drh2e38c322004-09-03 18:38:44 +00008222 if( rc ) goto end_insert;
drh25ada072015-06-19 15:07:14 +00008223 assert( szNew==pPage->xCellSize(pPage, newCell) );
drhfcd71b62011-04-05 22:08:24 +00008224 assert( szNew <= MX_CELL_SIZE(pBt) );
drh75e96b32017-04-01 00:20:06 +00008225 idx = pCur->ix;
danielk1977b980d2212009-06-22 18:03:51 +00008226 if( loc==0 ){
drh80159da2016-12-09 17:32:51 +00008227 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00008228 assert( idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00008229 rc = sqlite3PagerWrite(pPage->pDbPage);
8230 if( rc ){
8231 goto end_insert;
8232 }
danielk197771d5d2c2008-09-29 11:49:47 +00008233 oldCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00008234 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00008235 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00008236 }
drh80159da2016-12-09 17:32:51 +00008237 rc = clearCell(pPage, oldCell, &info);
danca66f6c2017-06-08 11:14:08 +00008238 if( info.nSize==szNew && info.nLocal==info.nPayload
8239 && (!ISAUTOVACUUM || szNew<pPage->minLocal)
8240 ){
drhf9238252016-12-09 18:09:42 +00008241 /* Overwrite the old cell with the new if they are the same size.
8242 ** We could also try to do this if the old cell is smaller, then add
8243 ** the leftover space to the free list. But experiments show that
8244 ** doing that is no faster then skipping this optimization and just
danca66f6c2017-06-08 11:14:08 +00008245 ** calling dropCell() and insertCell().
8246 **
8247 ** This optimization cannot be used on an autovacuum database if the
8248 ** new entry uses overflow pages, as the insertCell() call below is
8249 ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
drhf9238252016-12-09 18:09:42 +00008250 assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
drh2d083432016-12-09 19:42:18 +00008251 if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
drh80159da2016-12-09 17:32:51 +00008252 memcpy(oldCell, newCell, szNew);
8253 return SQLITE_OK;
8254 }
8255 dropCell(pPage, idx, info.nSize, &rc);
drh2e38c322004-09-03 18:38:44 +00008256 if( rc ) goto end_insert;
drh7c717f72001-06-24 20:39:41 +00008257 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00008258 assert( pPage->leaf );
drh75e96b32017-04-01 00:20:06 +00008259 idx = ++pCur->ix;
dan874080b2017-05-01 18:12:56 +00008260 pCur->curFlags &= ~BTCF_ValidNKey;
drh14acc042001-06-10 19:56:58 +00008261 }else{
drh4b70f112004-05-02 21:12:19 +00008262 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00008263 }
drh98add2e2009-07-20 17:11:49 +00008264 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
drh09a4e922016-05-21 12:29:04 +00008265 assert( pPage->nOverflow==0 || rc==SQLITE_OK );
danielk19773f632d52009-05-02 10:03:09 +00008266 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
drh9bf9e9c2008-12-05 20:01:43 +00008267
mistachkin48864df2013-03-21 21:20:32 +00008268 /* If no error has occurred and pPage has an overflow cell, call balance()
danielk1977a50d9aa2009-06-08 14:49:45 +00008269 ** to redistribute the cells within the tree. Since balance() may move
drh036dbec2014-03-11 23:40:44 +00008270 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
danielk1977a50d9aa2009-06-08 14:49:45 +00008271 ** variables.
danielk19773f632d52009-05-02 10:03:09 +00008272 **
danielk1977a50d9aa2009-06-08 14:49:45 +00008273 ** Previous versions of SQLite called moveToRoot() to move the cursor
8274 ** back to the root page as balance() used to invalidate the contents
danielk197754109bb2009-06-23 11:22:29 +00008275 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
8276 ** set the cursor state to "invalid". This makes common insert operations
8277 ** slightly faster.
danielk19773f632d52009-05-02 10:03:09 +00008278 **
danielk1977a50d9aa2009-06-08 14:49:45 +00008279 ** There is a subtle but important optimization here too. When inserting
8280 ** multiple records into an intkey b-tree using a single cursor (as can
8281 ** happen while processing an "INSERT INTO ... SELECT" statement), it
8282 ** is advantageous to leave the cursor pointing to the last entry in
8283 ** the b-tree if possible. If the cursor is left pointing to the last
8284 ** entry in the table, and the next row inserted has an integer key
8285 ** larger than the largest existing key, it is possible to insert the
8286 ** row without seeking the cursor. This can be a big performance boost.
danielk19773f632d52009-05-02 10:03:09 +00008287 */
danielk1977a50d9aa2009-06-08 14:49:45 +00008288 pCur->info.nSize = 0;
drh09a4e922016-05-21 12:29:04 +00008289 if( pPage->nOverflow ){
8290 assert( rc==SQLITE_OK );
drh036dbec2014-03-11 23:40:44 +00008291 pCur->curFlags &= ~(BTCF_ValidNKey);
danielk1977a50d9aa2009-06-08 14:49:45 +00008292 rc = balance(pCur);
8293
8294 /* Must make sure nOverflow is reset to zero even if the balance()
danielk197754109bb2009-06-23 11:22:29 +00008295 ** fails. Internal data structure corruption will result otherwise.
8296 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
8297 ** from trying to save the current position of the cursor. */
drh352a35a2017-08-15 03:46:47 +00008298 pCur->pPage->nOverflow = 0;
danielk197754109bb2009-06-23 11:22:29 +00008299 pCur->eState = CURSOR_INVALID;
danf91c1312017-01-10 20:04:38 +00008300 if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
drh85ef6302017-08-02 15:50:09 +00008301 btreeReleaseAllCursorPages(pCur);
drh7b20a152017-01-12 19:10:55 +00008302 if( pCur->pKeyInfo ){
danf91c1312017-01-10 20:04:38 +00008303 assert( pCur->pKey==0 );
8304 pCur->pKey = sqlite3Malloc( pX->nKey );
8305 if( pCur->pKey==0 ){
8306 rc = SQLITE_NOMEM;
8307 }else{
8308 memcpy(pCur->pKey, pX->pKey, pX->nKey);
8309 }
8310 }
8311 pCur->eState = CURSOR_REQUIRESEEK;
8312 pCur->nKey = pX->nKey;
8313 }
danielk19773f632d52009-05-02 10:03:09 +00008314 }
drh352a35a2017-08-15 03:46:47 +00008315 assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
drh9bf9e9c2008-12-05 20:01:43 +00008316
drh2e38c322004-09-03 18:38:44 +00008317end_insert:
drh5e2f8b92001-05-28 00:41:15 +00008318 return rc;
8319}
8320
8321/*
danf0ee1d32015-09-12 19:26:11 +00008322** Delete the entry that the cursor is pointing to.
8323**
drhe807bdb2016-01-21 17:06:33 +00008324** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
8325** the cursor is left pointing at an arbitrary location after the delete.
8326** But if that bit is set, then the cursor is left in a state such that
8327** the next call to BtreeNext() or BtreePrev() moves it to the same row
8328** as it would have been on if the call to BtreeDelete() had been omitted.
8329**
drhdef19e32016-01-27 16:26:25 +00008330** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
8331** associated with a single table entry and its indexes. Only one of those
8332** deletes is considered the "primary" delete. The primary delete occurs
8333** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
8334** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
8335** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
drhe807bdb2016-01-21 17:06:33 +00008336** but which might be used by alternative storage engines.
drh3b7511c2001-05-26 13:15:44 +00008337*/
drhe807bdb2016-01-21 17:06:33 +00008338int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
drhd677b3d2007-08-20 22:48:41 +00008339 Btree *p = pCur->pBtree;
danielk19774dbaa892009-06-16 16:50:22 +00008340 BtShared *pBt = p->pBt;
8341 int rc; /* Return code */
8342 MemPage *pPage; /* Page to delete cell from */
8343 unsigned char *pCell; /* Pointer to cell to delete */
8344 int iCellIdx; /* Index of cell to delete */
8345 int iCellDepth; /* Depth of node containing pCell */
drh80159da2016-12-09 17:32:51 +00008346 CellInfo info; /* Size of the cell being deleted */
danf0ee1d32015-09-12 19:26:11 +00008347 int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
drhe807bdb2016-01-21 17:06:33 +00008348 u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
drh8b2f49b2001-06-08 00:21:52 +00008349
dan7a2347e2016-01-07 16:43:54 +00008350 assert( cursorOwnsBtShared(pCur) );
drh64022502009-01-09 14:11:04 +00008351 assert( pBt->inTransaction==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00008352 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
drh036dbec2014-03-11 23:40:44 +00008353 assert( pCur->curFlags & BTCF_WriteFlag );
danielk197796d48e92009-06-29 06:00:37 +00008354 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8355 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
drh352a35a2017-08-15 03:46:47 +00008356 assert( pCur->ix<pCur->pPage->nCell );
drh98ef0f62015-06-30 01:25:52 +00008357 assert( pCur->eState==CURSOR_VALID );
drhdef19e32016-01-27 16:26:25 +00008358 assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
danielk1977da184232006-01-05 11:34:32 +00008359
danielk19774dbaa892009-06-16 16:50:22 +00008360 iCellDepth = pCur->iPage;
drh75e96b32017-04-01 00:20:06 +00008361 iCellIdx = pCur->ix;
drh352a35a2017-08-15 03:46:47 +00008362 pPage = pCur->pPage;
danielk19774dbaa892009-06-16 16:50:22 +00008363 pCell = findCell(pPage, iCellIdx);
8364
drhbfc7a8b2016-04-09 17:04:05 +00008365 /* If the bPreserve flag is set to true, then the cursor position must
8366 ** be preserved following this delete operation. If the current delete
8367 ** will cause a b-tree rebalance, then this is done by saving the cursor
8368 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
8369 ** returning.
8370 **
8371 ** Or, if the current delete will not cause a rebalance, then the cursor
8372 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
8373 ** before or after the deleted entry. In this case set bSkipnext to true. */
8374 if( bPreserve ){
8375 if( !pPage->leaf
8376 || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
8377 ){
8378 /* A b-tree rebalance will be required after deleting this entry.
8379 ** Save the cursor key. */
8380 rc = saveCursorKey(pCur);
8381 if( rc ) return rc;
8382 }else{
8383 bSkipnext = 1;
8384 }
8385 }
8386
danielk19774dbaa892009-06-16 16:50:22 +00008387 /* If the page containing the entry to delete is not a leaf page, move
8388 ** the cursor to the largest entry in the tree that is smaller than
8389 ** the entry being deleted. This cell will replace the cell being deleted
8390 ** from the internal node. The 'previous' entry is used for this instead
8391 ** of the 'next' entry, as the previous entry is always a part of the
8392 ** sub-tree headed by the child page of the cell being deleted. This makes
8393 ** balancing the tree following the delete operation easier. */
8394 if( !pPage->leaf ){
drh2ab792e2017-05-30 18:34:07 +00008395 rc = sqlite3BtreePrevious(pCur, 0);
8396 assert( rc!=SQLITE_DONE );
drh4c301aa2009-07-15 17:25:45 +00008397 if( rc ) return rc;
danielk19774dbaa892009-06-16 16:50:22 +00008398 }
8399
8400 /* Save the positions of any other cursors open on this table before
danf0ee1d32015-09-12 19:26:11 +00008401 ** making any modifications. */
drh27fb7462015-06-30 02:47:36 +00008402 if( pCur->curFlags & BTCF_Multiple ){
8403 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8404 if( rc ) return rc;
8405 }
drhd60f4f42012-03-23 14:23:52 +00008406
8407 /* If this is a delete operation to remove a row from a table b-tree,
8408 ** invalidate any incrblob cursors open on the row being deleted. */
8409 if( pCur->pKeyInfo==0 ){
drh9ca431a2017-03-29 18:03:50 +00008410 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
drhd60f4f42012-03-23 14:23:52 +00008411 }
8412
danf0ee1d32015-09-12 19:26:11 +00008413 /* Make the page containing the entry to be deleted writable. Then free any
8414 ** overflow pages associated with the entry and finally remove the cell
8415 ** itself from within the page. */
drha4ec1d42009-07-11 13:13:11 +00008416 rc = sqlite3PagerWrite(pPage->pDbPage);
8417 if( rc ) return rc;
drh80159da2016-12-09 17:32:51 +00008418 rc = clearCell(pPage, pCell, &info);
8419 dropCell(pPage, iCellIdx, info.nSize, &rc);
drha4ec1d42009-07-11 13:13:11 +00008420 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00008421
danielk19774dbaa892009-06-16 16:50:22 +00008422 /* If the cell deleted was not located on a leaf page, then the cursor
8423 ** is currently pointing to the largest entry in the sub-tree headed
8424 ** by the child-page of the cell that was just deleted from an internal
8425 ** node. The cell from the leaf node needs to be moved to the internal
8426 ** node to replace the deleted cell. */
drh4b70f112004-05-02 21:12:19 +00008427 if( !pPage->leaf ){
drh352a35a2017-08-15 03:46:47 +00008428 MemPage *pLeaf = pCur->pPage;
danielk19774dbaa892009-06-16 16:50:22 +00008429 int nCell;
drh352a35a2017-08-15 03:46:47 +00008430 Pgno n;
danielk19774dbaa892009-06-16 16:50:22 +00008431 unsigned char *pTmp;
danielk1977e6efa742004-11-10 11:55:10 +00008432
drh352a35a2017-08-15 03:46:47 +00008433 if( iCellDepth<pCur->iPage-1 ){
8434 n = pCur->apPage[iCellDepth+1]->pgno;
8435 }else{
8436 n = pCur->pPage->pgno;
8437 }
danielk19774dbaa892009-06-16 16:50:22 +00008438 pCell = findCell(pLeaf, pLeaf->nCell-1);
drhb468ce12015-06-24 01:07:30 +00008439 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
drh25ada072015-06-19 15:07:14 +00008440 nCell = pLeaf->xCellSize(pLeaf, pCell);
drhfcd71b62011-04-05 22:08:24 +00008441 assert( MX_CELL_SIZE(pBt) >= nCell );
danielk19774dbaa892009-06-16 16:50:22 +00008442 pTmp = pBt->pTmpSpace;
drh3fbb0222014-09-24 19:47:27 +00008443 assert( pTmp!=0 );
drha4ec1d42009-07-11 13:13:11 +00008444 rc = sqlite3PagerWrite(pLeaf->pDbPage);
drhcb89f4a2016-05-21 11:23:26 +00008445 if( rc==SQLITE_OK ){
8446 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
8447 }
drh98add2e2009-07-20 17:11:49 +00008448 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
drha4ec1d42009-07-11 13:13:11 +00008449 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00008450 }
danielk19774dbaa892009-06-16 16:50:22 +00008451
8452 /* Balance the tree. If the entry deleted was located on a leaf page,
8453 ** then the cursor still points to that page. In this case the first
8454 ** call to balance() repairs the tree, and the if(...) condition is
8455 ** never true.
8456 **
8457 ** Otherwise, if the entry deleted was on an internal node page, then
8458 ** pCur is pointing to the leaf page from which a cell was removed to
8459 ** replace the cell deleted from the internal node. This is slightly
8460 ** tricky as the leaf node may be underfull, and the internal node may
8461 ** be either under or overfull. In this case run the balancing algorithm
8462 ** on the leaf node first. If the balance proceeds far enough up the
8463 ** tree that we can be sure that any problem in the internal node has
8464 ** been corrected, so be it. Otherwise, after balancing the leaf node,
8465 ** walk the cursor up the tree to the internal node and balance it as
8466 ** well. */
8467 rc = balance(pCur);
8468 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
drh352a35a2017-08-15 03:46:47 +00008469 releasePageNotNull(pCur->pPage);
8470 pCur->iPage--;
danielk19774dbaa892009-06-16 16:50:22 +00008471 while( pCur->iPage>iCellDepth ){
8472 releasePage(pCur->apPage[pCur->iPage--]);
8473 }
drh352a35a2017-08-15 03:46:47 +00008474 pCur->pPage = pCur->apPage[pCur->iPage];
danielk19774dbaa892009-06-16 16:50:22 +00008475 rc = balance(pCur);
8476 }
8477
danielk19776b456a22005-03-21 04:04:02 +00008478 if( rc==SQLITE_OK ){
danf0ee1d32015-09-12 19:26:11 +00008479 if( bSkipnext ){
drha660caf2016-01-01 03:37:44 +00008480 assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
drh352a35a2017-08-15 03:46:47 +00008481 assert( pPage==pCur->pPage || CORRUPT_DB );
drh78ac1092015-09-20 22:57:47 +00008482 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
danf0ee1d32015-09-12 19:26:11 +00008483 pCur->eState = CURSOR_SKIPNEXT;
8484 if( iCellIdx>=pPage->nCell ){
8485 pCur->skipNext = -1;
drh75e96b32017-04-01 00:20:06 +00008486 pCur->ix = pPage->nCell-1;
danf0ee1d32015-09-12 19:26:11 +00008487 }else{
8488 pCur->skipNext = 1;
8489 }
8490 }else{
8491 rc = moveToRoot(pCur);
8492 if( bPreserve ){
drh85ef6302017-08-02 15:50:09 +00008493 btreeReleaseAllCursorPages(pCur);
danf0ee1d32015-09-12 19:26:11 +00008494 pCur->eState = CURSOR_REQUIRESEEK;
8495 }
drh44548e72017-08-14 18:13:52 +00008496 if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
danf0ee1d32015-09-12 19:26:11 +00008497 }
danielk19776b456a22005-03-21 04:04:02 +00008498 }
drh5e2f8b92001-05-28 00:41:15 +00008499 return rc;
drh3b7511c2001-05-26 13:15:44 +00008500}
drh8b2f49b2001-06-08 00:21:52 +00008501
8502/*
drhc6b52df2002-01-04 03:09:29 +00008503** Create a new BTree table. Write into *piTable the page
8504** number for the root page of the new table.
8505**
drhab01f612004-05-22 02:55:23 +00008506** The type of type is determined by the flags parameter. Only the
8507** following values of flags are currently in use. Other values for
8508** flags might not work:
8509**
8510** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
8511** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00008512*/
drhd4187c72010-08-30 22:15:45 +00008513static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
danielk1977aef0bf62005-12-30 16:28:01 +00008514 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00008515 MemPage *pRoot;
8516 Pgno pgnoRoot;
8517 int rc;
drhd4187c72010-08-30 22:15:45 +00008518 int ptfFlags; /* Page-type flage for the root page of new table */
drhd677b3d2007-08-20 22:48:41 +00008519
drh1fee73e2007-08-29 04:00:57 +00008520 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00008521 assert( pBt->inTransaction==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00008522 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk1977e6efa742004-11-10 11:55:10 +00008523
danielk1977003ba062004-11-04 02:57:33 +00008524#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00008525 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00008526 if( rc ){
8527 return rc;
8528 }
danielk1977003ba062004-11-04 02:57:33 +00008529#else
danielk1977687566d2004-11-02 12:56:41 +00008530 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00008531 Pgno pgnoMove; /* Move a page here to make room for the root-page */
8532 MemPage *pPageMove; /* The page to move to. */
8533
danielk197720713f32007-05-03 11:43:33 +00008534 /* Creating a new table may probably require moving an existing database
8535 ** to make room for the new tables root page. In case this page turns
8536 ** out to be an overflow page, delete all overflow page-map caches
8537 ** held by open cursors.
8538 */
danielk197792d4d7a2007-05-04 12:05:56 +00008539 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00008540
danielk1977003ba062004-11-04 02:57:33 +00008541 /* Read the value of meta[3] from the database to determine where the
8542 ** root page of the new table should go. meta[3] is the largest root-page
8543 ** created so far, so the new root-page is (meta[3]+1).
8544 */
danielk1977602b4662009-07-02 07:47:33 +00008545 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00008546 pgnoRoot++;
8547
danielk1977599fcba2004-11-08 07:13:13 +00008548 /* The new root-page may not be allocated on a pointer-map page, or the
8549 ** PENDING_BYTE page.
8550 */
drh72190432008-01-31 14:54:43 +00008551 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00008552 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00008553 pgnoRoot++;
8554 }
drh499e15b2015-05-22 12:37:37 +00008555 assert( pgnoRoot>=3 || CORRUPT_DB );
8556 testcase( pgnoRoot<3 );
danielk1977003ba062004-11-04 02:57:33 +00008557
8558 /* Allocate a page. The page that currently resides at pgnoRoot will
8559 ** be moved to the allocated page (unless the allocated page happens
8560 ** to reside at pgnoRoot).
8561 */
dan51f0b6d2013-02-22 20:16:34 +00008562 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
danielk1977003ba062004-11-04 02:57:33 +00008563 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00008564 return rc;
8565 }
danielk1977003ba062004-11-04 02:57:33 +00008566
8567 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00008568 /* pgnoRoot is the page that will be used for the root-page of
8569 ** the new table (assuming an error did not occur). But we were
8570 ** allocated pgnoMove. If required (i.e. if it was not allocated
8571 ** by extending the file), the current page at position pgnoMove
8572 ** is already journaled.
8573 */
drheeb844a2009-08-08 18:01:07 +00008574 u8 eType = 0;
8575 Pgno iPtrPage = 0;
danielk1977003ba062004-11-04 02:57:33 +00008576
danf7679ad2013-04-03 11:38:36 +00008577 /* Save the positions of any open cursors. This is required in
8578 ** case they are holding a reference to an xFetch reference
8579 ** corresponding to page pgnoRoot. */
8580 rc = saveAllCursors(pBt, 0, 0);
danielk1977003ba062004-11-04 02:57:33 +00008581 releasePage(pPageMove);
danf7679ad2013-04-03 11:38:36 +00008582 if( rc!=SQLITE_OK ){
8583 return rc;
8584 }
danielk1977f35843b2007-04-07 15:03:17 +00008585
8586 /* Move the page currently at pgnoRoot to pgnoMove. */
drhb00fc3b2013-08-21 23:42:32 +00008587 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00008588 if( rc!=SQLITE_OK ){
8589 return rc;
8590 }
8591 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drh27731d72009-06-22 12:05:10 +00008592 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
8593 rc = SQLITE_CORRUPT_BKPT;
8594 }
8595 if( rc!=SQLITE_OK ){
danielk1977003ba062004-11-04 02:57:33 +00008596 releasePage(pRoot);
8597 return rc;
8598 }
drhccae6022005-02-26 17:31:26 +00008599 assert( eType!=PTRMAP_ROOTPAGE );
8600 assert( eType!=PTRMAP_FREEPAGE );
danielk19774c999992008-07-16 18:17:55 +00008601 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +00008602 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00008603
8604 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00008605 if( rc!=SQLITE_OK ){
8606 return rc;
8607 }
drhb00fc3b2013-08-21 23:42:32 +00008608 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00008609 if( rc!=SQLITE_OK ){
8610 return rc;
8611 }
danielk19773b8a05f2007-03-19 17:44:26 +00008612 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00008613 if( rc!=SQLITE_OK ){
8614 releasePage(pRoot);
8615 return rc;
8616 }
8617 }else{
8618 pRoot = pPageMove;
8619 }
8620
danielk197742741be2005-01-08 12:42:39 +00008621 /* Update the pointer-map and meta-data with the new root-page number. */
drh98add2e2009-07-20 17:11:49 +00008622 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
danielk1977003ba062004-11-04 02:57:33 +00008623 if( rc ){
8624 releasePage(pRoot);
8625 return rc;
8626 }
drhbf592832010-03-30 15:51:12 +00008627
8628 /* When the new root page was allocated, page 1 was made writable in
8629 ** order either to increase the database filesize, or to decrement the
8630 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
8631 */
8632 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
danielk1977aef0bf62005-12-30 16:28:01 +00008633 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
drhbf592832010-03-30 15:51:12 +00008634 if( NEVER(rc) ){
danielk1977003ba062004-11-04 02:57:33 +00008635 releasePage(pRoot);
8636 return rc;
8637 }
danielk197742741be2005-01-08 12:42:39 +00008638
danielk1977003ba062004-11-04 02:57:33 +00008639 }else{
drh4f0c5872007-03-26 22:05:01 +00008640 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00008641 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00008642 }
8643#endif
danielk19773b8a05f2007-03-19 17:44:26 +00008644 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhd4187c72010-08-30 22:15:45 +00008645 if( createTabFlags & BTREE_INTKEY ){
8646 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
8647 }else{
8648 ptfFlags = PTF_ZERODATA | PTF_LEAF;
8649 }
8650 zeroPage(pRoot, ptfFlags);
danielk19773b8a05f2007-03-19 17:44:26 +00008651 sqlite3PagerUnref(pRoot->pDbPage);
drhd4187c72010-08-30 22:15:45 +00008652 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
drh8b2f49b2001-06-08 00:21:52 +00008653 *piTable = (int)pgnoRoot;
8654 return SQLITE_OK;
8655}
drhd677b3d2007-08-20 22:48:41 +00008656int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
8657 int rc;
8658 sqlite3BtreeEnter(p);
8659 rc = btreeCreateTable(p, piTable, flags);
8660 sqlite3BtreeLeave(p);
8661 return rc;
8662}
drh8b2f49b2001-06-08 00:21:52 +00008663
8664/*
8665** Erase the given database page and all its children. Return
8666** the page to the freelist.
8667*/
drh4b70f112004-05-02 21:12:19 +00008668static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00008669 BtShared *pBt, /* The BTree that contains the table */
drh7ab641f2009-11-24 02:37:02 +00008670 Pgno pgno, /* Page number to clear */
8671 int freePageFlag, /* Deallocate page if true */
8672 int *pnChange /* Add number of Cells freed to this counter */
drh4b70f112004-05-02 21:12:19 +00008673){
danielk1977146ba992009-07-22 14:08:13 +00008674 MemPage *pPage;
drh8b2f49b2001-06-08 00:21:52 +00008675 int rc;
drh4b70f112004-05-02 21:12:19 +00008676 unsigned char *pCell;
8677 int i;
dan8ce71842014-01-14 20:14:09 +00008678 int hdr;
drh80159da2016-12-09 17:32:51 +00008679 CellInfo info;
drh8b2f49b2001-06-08 00:21:52 +00008680
drh1fee73e2007-08-29 04:00:57 +00008681 assert( sqlite3_mutex_held(pBt->mutex) );
drhb1299152010-03-30 22:58:33 +00008682 if( pgno>btreePagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00008683 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00008684 }
drh28f58dd2015-06-27 19:45:03 +00008685 rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
danielk1977146ba992009-07-22 14:08:13 +00008686 if( rc ) return rc;
drhccf46d02015-04-01 13:21:33 +00008687 if( pPage->bBusy ){
8688 rc = SQLITE_CORRUPT_BKPT;
8689 goto cleardatabasepage_out;
8690 }
8691 pPage->bBusy = 1;
dan8ce71842014-01-14 20:14:09 +00008692 hdr = pPage->hdrOffset;
drh4b70f112004-05-02 21:12:19 +00008693 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00008694 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00008695 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00008696 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00008697 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00008698 }
drh80159da2016-12-09 17:32:51 +00008699 rc = clearCell(pPage, pCell, &info);
danielk19776b456a22005-03-21 04:04:02 +00008700 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00008701 }
drha34b6762004-05-07 13:30:42 +00008702 if( !pPage->leaf ){
dan8ce71842014-01-14 20:14:09 +00008703 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00008704 if( rc ) goto cleardatabasepage_out;
danielk1977c7af4842008-10-27 13:59:33 +00008705 }else if( pnChange ){
drhafe028a2015-05-22 13:09:50 +00008706 assert( pPage->intKey || CORRUPT_DB );
8707 testcase( !pPage->intKey );
danielk1977c7af4842008-10-27 13:59:33 +00008708 *pnChange += pPage->nCell;
drh2aa679f2001-06-25 02:11:07 +00008709 }
8710 if( freePageFlag ){
drhc314dc72009-07-21 11:52:34 +00008711 freePage(pPage, &rc);
danielk19773b8a05f2007-03-19 17:44:26 +00008712 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
dan8ce71842014-01-14 20:14:09 +00008713 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00008714 }
danielk19776b456a22005-03-21 04:04:02 +00008715
8716cleardatabasepage_out:
drhccf46d02015-04-01 13:21:33 +00008717 pPage->bBusy = 0;
drh4b70f112004-05-02 21:12:19 +00008718 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00008719 return rc;
drh8b2f49b2001-06-08 00:21:52 +00008720}
8721
8722/*
drhab01f612004-05-22 02:55:23 +00008723** Delete all information from a single table in the database. iTable is
8724** the page number of the root of the table. After this routine returns,
8725** the root page is empty, but still exists.
8726**
8727** This routine will fail with SQLITE_LOCKED if there are any open
8728** read cursors on the table. Open write cursors are moved to the
8729** root of the table.
danielk1977c7af4842008-10-27 13:59:33 +00008730**
8731** If pnChange is not NULL, then table iTable must be an intkey table. The
8732** integer value pointed to by pnChange is incremented by the number of
8733** entries in the table.
drh8b2f49b2001-06-08 00:21:52 +00008734*/
danielk1977c7af4842008-10-27 13:59:33 +00008735int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
drh8b2f49b2001-06-08 00:21:52 +00008736 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00008737 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00008738 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00008739 assert( p->inTrans==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +00008740
drhc046e3e2009-07-15 11:26:44 +00008741 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
drhd60f4f42012-03-23 14:23:52 +00008742
drhc046e3e2009-07-15 11:26:44 +00008743 if( SQLITE_OK==rc ){
drhd60f4f42012-03-23 14:23:52 +00008744 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
8745 ** is the root of a table b-tree - if it is not, the following call is
8746 ** a no-op). */
drh9ca431a2017-03-29 18:03:50 +00008747 invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
danielk197762c14b32008-11-19 09:05:26 +00008748 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
drh8b2f49b2001-06-08 00:21:52 +00008749 }
drhd677b3d2007-08-20 22:48:41 +00008750 sqlite3BtreeLeave(p);
8751 return rc;
drh8b2f49b2001-06-08 00:21:52 +00008752}
8753
8754/*
drh079a3072014-03-19 14:10:55 +00008755** Delete all information from the single table that pCur is open on.
8756**
8757** This routine only work for pCur on an ephemeral table.
8758*/
8759int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
8760 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
8761}
8762
8763/*
drh8b2f49b2001-06-08 00:21:52 +00008764** Erase all information in a table and add the root of the table to
8765** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00008766** page 1) is never added to the freelist.
8767**
8768** This routine will fail with SQLITE_LOCKED if there are any open
8769** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00008770**
8771** If AUTOVACUUM is enabled and the page at iTable is not the last
8772** root page in the database file, then the last root page
8773** in the database file is moved into the slot formerly occupied by
8774** iTable and that last slot formerly occupied by the last root page
8775** is added to the freelist instead of iTable. In this say, all
8776** root pages are kept at the beginning of the database file, which
8777** is necessary for AUTOVACUUM to work right. *piMoved is set to the
8778** page number that used to be the last root page in the file before
8779** the move. If no page gets moved, *piMoved is set to 0.
8780** The last root page is recorded in meta[3] and the value of
8781** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00008782*/
danielk197789d40042008-11-17 14:20:56 +00008783static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00008784 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00008785 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00008786 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00008787
drh1fee73e2007-08-29 04:00:57 +00008788 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00008789 assert( p->inTrans==TRANS_WRITE );
drh65f38d92016-11-22 01:26:42 +00008790 assert( iTable>=2 );
drh055f2982016-01-15 15:06:41 +00008791
drhb00fc3b2013-08-21 23:42:32 +00008792 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00008793 if( rc ) return rc;
danielk1977c7af4842008-10-27 13:59:33 +00008794 rc = sqlite3BtreeClearTable(p, iTable, 0);
danielk19776b456a22005-03-21 04:04:02 +00008795 if( rc ){
8796 releasePage(pPage);
8797 return rc;
8798 }
danielk1977a0bf2652004-11-04 14:30:04 +00008799
drh205f48e2004-11-05 00:43:11 +00008800 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00008801
danielk1977a0bf2652004-11-04 14:30:04 +00008802#ifdef SQLITE_OMIT_AUTOVACUUM
drh055f2982016-01-15 15:06:41 +00008803 freePage(pPage, &rc);
8804 releasePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00008805#else
drh055f2982016-01-15 15:06:41 +00008806 if( pBt->autoVacuum ){
8807 Pgno maxRootPgno;
8808 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00008809
drh055f2982016-01-15 15:06:41 +00008810 if( iTable==maxRootPgno ){
8811 /* If the table being dropped is the table with the largest root-page
8812 ** number in the database, put the root page on the free list.
danielk1977599fcba2004-11-08 07:13:13 +00008813 */
drhc314dc72009-07-21 11:52:34 +00008814 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00008815 releasePage(pPage);
drh055f2982016-01-15 15:06:41 +00008816 if( rc!=SQLITE_OK ){
8817 return rc;
8818 }
8819 }else{
8820 /* The table being dropped does not have the largest root-page
8821 ** number in the database. So move the page that does into the
8822 ** gap left by the deleted root-page.
8823 */
8824 MemPage *pMove;
8825 releasePage(pPage);
8826 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
8827 if( rc!=SQLITE_OK ){
8828 return rc;
8829 }
8830 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
8831 releasePage(pMove);
8832 if( rc!=SQLITE_OK ){
8833 return rc;
8834 }
8835 pMove = 0;
8836 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
8837 freePage(pMove, &rc);
8838 releasePage(pMove);
8839 if( rc!=SQLITE_OK ){
8840 return rc;
8841 }
8842 *piMoved = maxRootPgno;
danielk1977a0bf2652004-11-04 14:30:04 +00008843 }
drh055f2982016-01-15 15:06:41 +00008844
8845 /* Set the new 'max-root-page' value in the database header. This
8846 ** is the old value less one, less one more if that happens to
8847 ** be a root-page number, less one again if that is the
8848 ** PENDING_BYTE_PAGE.
drhc046e3e2009-07-15 11:26:44 +00008849 */
drh055f2982016-01-15 15:06:41 +00008850 maxRootPgno--;
8851 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
8852 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
8853 maxRootPgno--;
8854 }
8855 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
8856
8857 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
8858 }else{
8859 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00008860 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00008861 }
drh055f2982016-01-15 15:06:41 +00008862#endif
drh8b2f49b2001-06-08 00:21:52 +00008863 return rc;
8864}
drhd677b3d2007-08-20 22:48:41 +00008865int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
8866 int rc;
8867 sqlite3BtreeEnter(p);
dan7733a4d2011-09-02 18:03:16 +00008868 rc = btreeDropTable(p, iTable, piMoved);
drhd677b3d2007-08-20 22:48:41 +00008869 sqlite3BtreeLeave(p);
8870 return rc;
8871}
drh8b2f49b2001-06-08 00:21:52 +00008872
drh001bbcb2003-03-19 03:14:00 +00008873
drh8b2f49b2001-06-08 00:21:52 +00008874/*
danielk1977602b4662009-07-02 07:47:33 +00008875** This function may only be called if the b-tree connection already
8876** has a read or write transaction open on the database.
8877**
drh23e11ca2004-05-04 17:27:28 +00008878** Read the meta-information out of a database file. Meta[0]
8879** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00008880** through meta[15] are available for use by higher layers. Meta[0]
8881** is read-only, the others are read/write.
8882**
8883** The schema layer numbers meta values differently. At the schema
8884** layer (and the SetCookie and ReadCookie opcodes) the number of
8885** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh91618562014-12-19 19:28:02 +00008886**
8887** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
8888** of reading the value out of the header, it instead loads the "DataVersion"
8889** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
8890** database file. It is a number computed by the pager. But its access
8891** pattern is the same as header meta values, and so it is convenient to
8892** read it from this routine.
drh8b2f49b2001-06-08 00:21:52 +00008893*/
danielk1977602b4662009-07-02 07:47:33 +00008894void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
danielk1977aef0bf62005-12-30 16:28:01 +00008895 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00008896
drhd677b3d2007-08-20 22:48:41 +00008897 sqlite3BtreeEnter(p);
danielk1977602b4662009-07-02 07:47:33 +00008898 assert( p->inTrans>TRANS_NONE );
danielk1977e0d9e6f2009-07-03 16:25:06 +00008899 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
danielk1977602b4662009-07-02 07:47:33 +00008900 assert( pBt->pPage1 );
drh23e11ca2004-05-04 17:27:28 +00008901 assert( idx>=0 && idx<=15 );
danielk1977ea897302008-09-19 15:10:58 +00008902
drh91618562014-12-19 19:28:02 +00008903 if( idx==BTREE_DATA_VERSION ){
drh3da9c042014-12-22 18:41:21 +00008904 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
drh91618562014-12-19 19:28:02 +00008905 }else{
8906 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
8907 }
drhae157872004-08-14 19:20:09 +00008908
danielk1977602b4662009-07-02 07:47:33 +00008909 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
8910 ** database, mark the database as read-only. */
danielk1977003ba062004-11-04 02:57:33 +00008911#ifdef SQLITE_OMIT_AUTOVACUUM
drhc9166342012-01-05 23:32:06 +00008912 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
8913 pBt->btsFlags |= BTS_READ_ONLY;
8914 }
danielk1977003ba062004-11-04 02:57:33 +00008915#endif
drhae157872004-08-14 19:20:09 +00008916
drhd677b3d2007-08-20 22:48:41 +00008917 sqlite3BtreeLeave(p);
drh8b2f49b2001-06-08 00:21:52 +00008918}
8919
8920/*
drh23e11ca2004-05-04 17:27:28 +00008921** Write meta-information back into the database. Meta[0] is
8922** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00008923*/
danielk1977aef0bf62005-12-30 16:28:01 +00008924int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
8925 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00008926 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00008927 int rc;
drh23e11ca2004-05-04 17:27:28 +00008928 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00008929 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00008930 assert( p->inTrans==TRANS_WRITE );
8931 assert( pBt->pPage1!=0 );
8932 pP1 = pBt->pPage1->aData;
8933 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
8934 if( rc==SQLITE_OK ){
8935 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00008936#ifndef SQLITE_OMIT_AUTOVACUUM
danielk19770d19f7a2009-06-03 11:25:07 +00008937 if( idx==BTREE_INCR_VACUUM ){
drh64022502009-01-09 14:11:04 +00008938 assert( pBt->autoVacuum || iMeta==0 );
8939 assert( iMeta==0 || iMeta==1 );
8940 pBt->incrVacuum = (u8)iMeta;
drhd677b3d2007-08-20 22:48:41 +00008941 }
drh64022502009-01-09 14:11:04 +00008942#endif
drh5df72a52002-06-06 23:16:05 +00008943 }
drhd677b3d2007-08-20 22:48:41 +00008944 sqlite3BtreeLeave(p);
8945 return rc;
drh8b2f49b2001-06-08 00:21:52 +00008946}
drh8c42ca92001-06-22 19:15:00 +00008947
danielk1977a5533162009-02-24 10:01:51 +00008948#ifndef SQLITE_OMIT_BTREECOUNT
8949/*
8950** The first argument, pCur, is a cursor opened on some b-tree. Count the
8951** number of entries in the b-tree and write the result to *pnEntry.
8952**
8953** SQLITE_OK is returned if the operation is successfully executed.
8954** Otherwise, if an error is encountered (i.e. an IO error or database
8955** corruption) an SQLite error code is returned.
8956*/
8957int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
8958 i64 nEntry = 0; /* Value to return in *pnEntry */
8959 int rc; /* Return code */
dana205a482011-08-27 18:48:57 +00008960
drh44548e72017-08-14 18:13:52 +00008961 rc = moveToRoot(pCur);
8962 if( rc==SQLITE_EMPTY ){
dana205a482011-08-27 18:48:57 +00008963 *pnEntry = 0;
8964 return SQLITE_OK;
8965 }
danielk1977a5533162009-02-24 10:01:51 +00008966
8967 /* Unless an error occurs, the following loop runs one iteration for each
8968 ** page in the B-Tree structure (not including overflow pages).
8969 */
8970 while( rc==SQLITE_OK ){
8971 int iIdx; /* Index of child node in parent */
8972 MemPage *pPage; /* Current page of the b-tree */
8973
8974 /* If this is a leaf page or the tree is not an int-key tree, then
8975 ** this page contains countable entries. Increment the entry counter
8976 ** accordingly.
8977 */
drh352a35a2017-08-15 03:46:47 +00008978 pPage = pCur->pPage;
danielk1977a5533162009-02-24 10:01:51 +00008979 if( pPage->leaf || !pPage->intKey ){
8980 nEntry += pPage->nCell;
8981 }
8982
8983 /* pPage is a leaf node. This loop navigates the cursor so that it
8984 ** points to the first interior cell that it points to the parent of
8985 ** the next page in the tree that has not yet been visited. The
8986 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
8987 ** of the page, or to the number of cells in the page if the next page
8988 ** to visit is the right-child of its parent.
8989 **
8990 ** If all pages in the tree have been visited, return SQLITE_OK to the
8991 ** caller.
8992 */
8993 if( pPage->leaf ){
8994 do {
8995 if( pCur->iPage==0 ){
8996 /* All pages of the b-tree have been visited. Return successfully. */
8997 *pnEntry = nEntry;
drh7efa4262014-12-16 00:08:31 +00008998 return moveToRoot(pCur);
danielk1977a5533162009-02-24 10:01:51 +00008999 }
danielk197730548662009-07-09 05:07:37 +00009000 moveToParent(pCur);
drh352a35a2017-08-15 03:46:47 +00009001 }while ( pCur->ix>=pCur->pPage->nCell );
danielk1977a5533162009-02-24 10:01:51 +00009002
drh75e96b32017-04-01 00:20:06 +00009003 pCur->ix++;
drh352a35a2017-08-15 03:46:47 +00009004 pPage = pCur->pPage;
danielk1977a5533162009-02-24 10:01:51 +00009005 }
9006
9007 /* Descend to the child node of the cell that the cursor currently
9008 ** points at. This is the right-child if (iIdx==pPage->nCell).
9009 */
drh75e96b32017-04-01 00:20:06 +00009010 iIdx = pCur->ix;
danielk1977a5533162009-02-24 10:01:51 +00009011 if( iIdx==pPage->nCell ){
9012 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
9013 }else{
9014 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
9015 }
9016 }
9017
shanebe217792009-03-05 04:20:31 +00009018 /* An error has occurred. Return an error code. */
danielk1977a5533162009-02-24 10:01:51 +00009019 return rc;
9020}
9021#endif
drhdd793422001-06-28 01:54:48 +00009022
drhdd793422001-06-28 01:54:48 +00009023/*
drh5eddca62001-06-30 21:53:53 +00009024** Return the pager associated with a BTree. This routine is used for
9025** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00009026*/
danielk1977aef0bf62005-12-30 16:28:01 +00009027Pager *sqlite3BtreePager(Btree *p){
9028 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00009029}
drh5eddca62001-06-30 21:53:53 +00009030
drhb7f91642004-10-31 02:22:47 +00009031#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00009032/*
9033** Append a message to the error message string.
9034*/
drh2e38c322004-09-03 18:38:44 +00009035static void checkAppendMsg(
9036 IntegrityCk *pCheck,
drh2e38c322004-09-03 18:38:44 +00009037 const char *zFormat,
9038 ...
9039){
9040 va_list ap;
drh1dcdbc02007-01-27 02:24:54 +00009041 if( !pCheck->mxErr ) return;
9042 pCheck->mxErr--;
9043 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00009044 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +00009045 if( pCheck->errMsg.nChar ){
9046 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +00009047 }
drh867db832014-09-26 02:41:05 +00009048 if( pCheck->zPfx ){
drh5f4a6862016-01-30 12:50:25 +00009049 sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
drhf089aa42008-07-08 19:34:06 +00009050 }
drh5f4a6862016-01-30 12:50:25 +00009051 sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
drhf089aa42008-07-08 19:34:06 +00009052 va_end(ap);
drhb49bc862013-08-21 21:12:10 +00009053 if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
drhc890fec2008-08-01 20:10:08 +00009054 pCheck->mallocFailed = 1;
9055 }
drh5eddca62001-06-30 21:53:53 +00009056}
drhb7f91642004-10-31 02:22:47 +00009057#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00009058
drhb7f91642004-10-31 02:22:47 +00009059#ifndef SQLITE_OMIT_INTEGRITY_CHECK
dan1235bb12012-04-03 17:43:28 +00009060
9061/*
9062** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
9063** corresponds to page iPg is already set.
9064*/
9065static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9066 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9067 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
9068}
9069
9070/*
9071** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
9072*/
9073static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9074 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9075 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
9076}
9077
9078
drh5eddca62001-06-30 21:53:53 +00009079/*
9080** Add 1 to the reference count for page iPage. If this is the second
9081** reference to the page, add an error message to pCheck->zErrMsg.
peter.d.reid60ec9142014-09-06 16:39:46 +00009082** Return 1 if there are 2 or more references to the page and 0 if
drh5eddca62001-06-30 21:53:53 +00009083** if this is the first reference to the page.
9084**
9085** Also check that the page number is in bounds.
9086*/
drh867db832014-09-26 02:41:05 +00009087static int checkRef(IntegrityCk *pCheck, Pgno iPage){
drh5eddca62001-06-30 21:53:53 +00009088 if( iPage==0 ) return 1;
danielk197789d40042008-11-17 14:20:56 +00009089 if( iPage>pCheck->nPage ){
drh867db832014-09-26 02:41:05 +00009090 checkAppendMsg(pCheck, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00009091 return 1;
9092 }
dan1235bb12012-04-03 17:43:28 +00009093 if( getPageReferenced(pCheck, iPage) ){
drh867db832014-09-26 02:41:05 +00009094 checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00009095 return 1;
9096 }
dan1235bb12012-04-03 17:43:28 +00009097 setPageReferenced(pCheck, iPage);
9098 return 0;
drh5eddca62001-06-30 21:53:53 +00009099}
9100
danielk1977afcdd022004-10-31 16:25:42 +00009101#ifndef SQLITE_OMIT_AUTOVACUUM
9102/*
9103** Check that the entry in the pointer-map for page iChild maps to
9104** page iParent, pointer type ptrType. If not, append an error message
9105** to pCheck.
9106*/
9107static void checkPtrmap(
9108 IntegrityCk *pCheck, /* Integrity check context */
9109 Pgno iChild, /* Child page number */
9110 u8 eType, /* Expected pointer map type */
drh867db832014-09-26 02:41:05 +00009111 Pgno iParent /* Expected pointer map parent page number */
danielk1977afcdd022004-10-31 16:25:42 +00009112){
9113 int rc;
9114 u8 ePtrmapType;
9115 Pgno iPtrmapParent;
9116
9117 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
9118 if( rc!=SQLITE_OK ){
drhb56cd552009-05-01 13:16:54 +00009119 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
drh867db832014-09-26 02:41:05 +00009120 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
danielk1977afcdd022004-10-31 16:25:42 +00009121 return;
9122 }
9123
9124 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
drh867db832014-09-26 02:41:05 +00009125 checkAppendMsg(pCheck,
danielk1977afcdd022004-10-31 16:25:42 +00009126 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
9127 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
9128 }
9129}
9130#endif
9131
drh5eddca62001-06-30 21:53:53 +00009132/*
9133** Check the integrity of the freelist or of an overflow page list.
9134** Verify that the number of pages on the list is N.
9135*/
drh30e58752002-03-02 20:41:57 +00009136static void checkList(
9137 IntegrityCk *pCheck, /* Integrity checking context */
9138 int isFreeList, /* True for a freelist. False for overflow page list */
9139 int iPage, /* Page number for first page in the list */
drh867db832014-09-26 02:41:05 +00009140 int N /* Expected number of pages in the list */
drh30e58752002-03-02 20:41:57 +00009141){
9142 int i;
drh3a4c1412004-05-09 20:40:11 +00009143 int expected = N;
9144 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00009145 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00009146 DbPage *pOvflPage;
9147 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00009148 if( iPage<1 ){
drh867db832014-09-26 02:41:05 +00009149 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00009150 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00009151 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00009152 break;
9153 }
drh867db832014-09-26 02:41:05 +00009154 if( checkRef(pCheck, iPage) ) break;
drh9584f582015-11-04 20:22:37 +00009155 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
drh867db832014-09-26 02:41:05 +00009156 checkAppendMsg(pCheck, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00009157 break;
9158 }
danielk19773b8a05f2007-03-19 17:44:26 +00009159 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00009160 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00009161 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00009162#ifndef SQLITE_OMIT_AUTOVACUUM
9163 if( pCheck->pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00009164 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +00009165 }
9166#endif
drh43b18e12010-08-17 19:40:08 +00009167 if( n>(int)pCheck->pBt->usableSize/4-2 ){
drh867db832014-09-26 02:41:05 +00009168 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00009169 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00009170 N--;
9171 }else{
9172 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00009173 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00009174#ifndef SQLITE_OMIT_AUTOVACUUM
9175 if( pCheck->pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00009176 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +00009177 }
9178#endif
drh867db832014-09-26 02:41:05 +00009179 checkRef(pCheck, iFreePage);
drhee696e22004-08-30 16:52:17 +00009180 }
9181 N -= n;
drh30e58752002-03-02 20:41:57 +00009182 }
drh30e58752002-03-02 20:41:57 +00009183 }
danielk1977afcdd022004-10-31 16:25:42 +00009184#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00009185 else{
9186 /* If this database supports auto-vacuum and iPage is not the last
9187 ** page in this overflow list, check that the pointer-map entry for
9188 ** the following page matches iPage.
9189 */
9190 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00009191 i = get4byte(pOvflData);
drh867db832014-09-26 02:41:05 +00009192 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
danielk1977687566d2004-11-02 12:56:41 +00009193 }
danielk1977afcdd022004-10-31 16:25:42 +00009194 }
9195#endif
danielk19773b8a05f2007-03-19 17:44:26 +00009196 iPage = get4byte(pOvflData);
9197 sqlite3PagerUnref(pOvflPage);
danad41f5e2015-09-18 14:45:01 +00009198
9199 if( isFreeList && N<(iPage!=0) ){
9200 checkAppendMsg(pCheck, "free-page count in header is too small");
9201 }
drh5eddca62001-06-30 21:53:53 +00009202 }
9203}
drhb7f91642004-10-31 02:22:47 +00009204#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00009205
drh67731a92015-04-16 11:56:03 +00009206/*
9207** An implementation of a min-heap.
9208**
9209** aHeap[0] is the number of elements on the heap. aHeap[1] is the
drha33b6832015-04-16 21:57:37 +00009210** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
drh67731a92015-04-16 11:56:03 +00009211** and aHeap[N*2+1].
9212**
9213** The heap property is this: Every node is less than or equal to both
9214** of its daughter nodes. A consequence of the heap property is that the
drh42c0a2b2015-04-28 01:28:36 +00009215** root node aHeap[1] is always the minimum value currently in the heap.
drh67731a92015-04-16 11:56:03 +00009216**
9217** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
9218** the heap, preserving the heap property. The btreeHeapPull() routine
9219** removes the root element from the heap (the minimum value in the heap)
drh42c0a2b2015-04-28 01:28:36 +00009220** and then moves other nodes around as necessary to preserve the heap
drh67731a92015-04-16 11:56:03 +00009221** property.
9222**
9223** This heap is used for cell overlap and coverage testing. Each u32
9224** entry represents the span of a cell or freeblock on a btree page.
9225** The upper 16 bits are the index of the first byte of a range and the
9226** lower 16 bits are the index of the last byte of that range.
9227*/
9228static void btreeHeapInsert(u32 *aHeap, u32 x){
9229 u32 j, i = ++aHeap[0];
9230 aHeap[i] = x;
drha33b6832015-04-16 21:57:37 +00009231 while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
drh67731a92015-04-16 11:56:03 +00009232 x = aHeap[j];
9233 aHeap[j] = aHeap[i];
9234 aHeap[i] = x;
9235 i = j;
9236 }
9237}
9238static int btreeHeapPull(u32 *aHeap, u32 *pOut){
9239 u32 j, i, x;
9240 if( (x = aHeap[0])==0 ) return 0;
9241 *pOut = aHeap[1];
9242 aHeap[1] = aHeap[x];
9243 aHeap[x] = 0xffffffff;
9244 aHeap[0]--;
9245 i = 1;
9246 while( (j = i*2)<=aHeap[0] ){
9247 if( aHeap[j]>aHeap[j+1] ) j++;
9248 if( aHeap[i]<aHeap[j] ) break;
9249 x = aHeap[i];
9250 aHeap[i] = aHeap[j];
9251 aHeap[j] = x;
9252 i = j;
9253 }
9254 return 1;
9255}
9256
drhb7f91642004-10-31 02:22:47 +00009257#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00009258/*
9259** Do various sanity checks on a single page of a tree. Return
9260** the tree depth. Root pages return 0. Parents of root pages
9261** return 1, and so forth.
9262**
9263** These checks are done:
9264**
9265** 1. Make sure that cells and freeblocks do not overlap
9266** but combine to completely cover the page.
drhe05b3f82015-07-01 17:53:49 +00009267** 2. Make sure integer cell keys are in order.
9268** 3. Check the integrity of overflow pages.
9269** 4. Recursively call checkTreePage on all children.
9270** 5. Verify that the depth of all children is the same.
drh5eddca62001-06-30 21:53:53 +00009271*/
9272static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00009273 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00009274 int iPage, /* Page number of the page to check */
drhcbc6b712015-07-02 16:17:30 +00009275 i64 *piMinKey, /* Write minimum integer primary key here */
9276 i64 maxKey /* Error if integer primary key greater than this */
drh5eddca62001-06-30 21:53:53 +00009277){
drhcbc6b712015-07-02 16:17:30 +00009278 MemPage *pPage = 0; /* The page being analyzed */
9279 int i; /* Loop counter */
9280 int rc; /* Result code from subroutine call */
9281 int depth = -1, d2; /* Depth of a subtree */
9282 int pgno; /* Page number */
9283 int nFrag; /* Number of fragmented bytes on the page */
9284 int hdr; /* Offset to the page header */
9285 int cellStart; /* Offset to the start of the cell pointer array */
9286 int nCell; /* Number of cells */
9287 int doCoverageCheck = 1; /* True if cell coverage checking should be done */
9288 int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
9289 ** False if IPK must be strictly less than maxKey */
9290 u8 *data; /* Page content */
9291 u8 *pCell; /* Cell content */
9292 u8 *pCellIdx; /* Next element of the cell pointer array */
9293 BtShared *pBt; /* The BtShared object that owns pPage */
9294 u32 pc; /* Address of a cell */
9295 u32 usableSize; /* Usable size of the page */
9296 u32 contentOffset; /* Offset to the start of the cell content area */
9297 u32 *heap = 0; /* Min-heap used for checking cell coverage */
drhd2dc87f2015-07-02 19:47:08 +00009298 u32 x, prev = 0; /* Next and previous entry on the min-heap */
drh867db832014-09-26 02:41:05 +00009299 const char *saved_zPfx = pCheck->zPfx;
9300 int saved_v1 = pCheck->v1;
9301 int saved_v2 = pCheck->v2;
mistachkin532f1792015-07-14 17:18:05 +00009302 u8 savedIsInit = 0;
danielk1977ef73ee92004-11-06 12:26:07 +00009303
drh5eddca62001-06-30 21:53:53 +00009304 /* Check that the page exists
9305 */
drhd9cb6ac2005-10-20 07:28:17 +00009306 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00009307 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00009308 if( iPage==0 ) return 0;
drh867db832014-09-26 02:41:05 +00009309 if( checkRef(pCheck, iPage) ) return 0;
9310 pCheck->zPfx = "Page %d: ";
9311 pCheck->v1 = iPage;
drhb00fc3b2013-08-21 23:42:32 +00009312 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drh867db832014-09-26 02:41:05 +00009313 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00009314 "unable to get the page. error code=%d", rc);
drh867db832014-09-26 02:41:05 +00009315 goto end_of_check;
drh5eddca62001-06-30 21:53:53 +00009316 }
danielk197793caf5a2009-07-11 06:55:33 +00009317
9318 /* Clear MemPage.isInit to make sure the corruption detection code in
9319 ** btreeInitPage() is executed. */
drh72e191e2015-07-04 11:14:20 +00009320 savedIsInit = pPage->isInit;
danielk197793caf5a2009-07-11 06:55:33 +00009321 pPage->isInit = 0;
danielk197730548662009-07-09 05:07:37 +00009322 if( (rc = btreeInitPage(pPage))!=0 ){
drh64022502009-01-09 14:11:04 +00009323 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
drh867db832014-09-26 02:41:05 +00009324 checkAppendMsg(pCheck,
danielk197730548662009-07-09 05:07:37 +00009325 "btreeInitPage() returns error code %d", rc);
drh867db832014-09-26 02:41:05 +00009326 goto end_of_check;
drh5eddca62001-06-30 21:53:53 +00009327 }
drhcbc6b712015-07-02 16:17:30 +00009328 data = pPage->aData;
9329 hdr = pPage->hdrOffset;
drh5eddca62001-06-30 21:53:53 +00009330
drhcbc6b712015-07-02 16:17:30 +00009331 /* Set up for cell analysis */
drhe05b3f82015-07-01 17:53:49 +00009332 pCheck->zPfx = "On tree page %d cell %d: ";
drhcbc6b712015-07-02 16:17:30 +00009333 contentOffset = get2byteNotZero(&data[hdr+5]);
9334 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
9335
9336 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
9337 ** number of cells on the page. */
9338 nCell = get2byte(&data[hdr+3]);
9339 assert( pPage->nCell==nCell );
9340
9341 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
9342 ** immediately follows the b-tree page header. */
9343 cellStart = hdr + 12 - 4*pPage->leaf;
9344 assert( pPage->aCellIdx==&data[cellStart] );
9345 pCellIdx = &data[cellStart + 2*(nCell-1)];
9346
9347 if( !pPage->leaf ){
9348 /* Analyze the right-child page of internal pages */
9349 pgno = get4byte(&data[hdr+8]);
9350#ifndef SQLITE_OMIT_AUTOVACUUM
9351 if( pBt->autoVacuum ){
9352 pCheck->zPfx = "On page %d at right child: ";
9353 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
9354 }
9355#endif
9356 depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
9357 keyCanBeEqual = 0;
9358 }else{
9359 /* For leaf pages, the coverage check will occur in the same loop
9360 ** as the other cell checks, so initialize the heap. */
9361 heap = pCheck->heap;
9362 heap[0] = 0;
drh5eddca62001-06-30 21:53:53 +00009363 }
9364
drhcbc6b712015-07-02 16:17:30 +00009365 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
9366 ** integer offsets to the cell contents. */
9367 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
drh6f11bef2004-05-13 01:12:56 +00009368 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00009369
drhcbc6b712015-07-02 16:17:30 +00009370 /* Check cell size */
drh867db832014-09-26 02:41:05 +00009371 pCheck->v2 = i;
drhcbc6b712015-07-02 16:17:30 +00009372 assert( pCellIdx==&data[cellStart + i*2] );
9373 pc = get2byteAligned(pCellIdx);
9374 pCellIdx -= 2;
9375 if( pc<contentOffset || pc>usableSize-4 ){
9376 checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
9377 pc, contentOffset, usableSize-4);
9378 doCoverageCheck = 0;
9379 continue;
shaneh195475d2010-02-19 04:28:08 +00009380 }
drhcbc6b712015-07-02 16:17:30 +00009381 pCell = &data[pc];
9382 pPage->xParseCell(pPage, pCell, &info);
9383 if( pc+info.nSize>usableSize ){
9384 checkAppendMsg(pCheck, "Extends off end of page");
9385 doCoverageCheck = 0;
9386 continue;
drh5eddca62001-06-30 21:53:53 +00009387 }
9388
drhcbc6b712015-07-02 16:17:30 +00009389 /* Check for integer primary key out of range */
9390 if( pPage->intKey ){
9391 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
9392 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
9393 }
9394 maxKey = info.nKey;
dan4b2667c2017-05-01 18:24:01 +00009395 keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
drhcbc6b712015-07-02 16:17:30 +00009396 }
9397
9398 /* Check the content overflow list */
9399 if( info.nPayload>info.nLocal ){
9400 int nPage; /* Number of pages on the overflow chain */
9401 Pgno pgnoOvfl; /* First page of the overflow chain */
drh45ac1c72015-12-18 03:59:16 +00009402 assert( pc + info.nSize - 4 <= usableSize );
drhcbc6b712015-07-02 16:17:30 +00009403 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
drh45ac1c72015-12-18 03:59:16 +00009404 pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
drhda200cc2004-05-09 11:51:38 +00009405#ifndef SQLITE_OMIT_AUTOVACUUM
9406 if( pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00009407 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
drhda200cc2004-05-09 11:51:38 +00009408 }
9409#endif
drh867db832014-09-26 02:41:05 +00009410 checkList(pCheck, 0, pgnoOvfl, nPage);
drh5eddca62001-06-30 21:53:53 +00009411 }
9412
drh5eddca62001-06-30 21:53:53 +00009413 if( !pPage->leaf ){
drhcbc6b712015-07-02 16:17:30 +00009414 /* Check sanity of left child page for internal pages */
drh43605152004-05-29 21:46:49 +00009415 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00009416#ifndef SQLITE_OMIT_AUTOVACUUM
9417 if( pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00009418 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
danielk1977afcdd022004-10-31 16:25:42 +00009419 }
9420#endif
drhcbc6b712015-07-02 16:17:30 +00009421 d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
9422 keyCanBeEqual = 0;
9423 if( d2!=depth ){
drh867db832014-09-26 02:41:05 +00009424 checkAppendMsg(pCheck, "Child page depth differs");
drhcbc6b712015-07-02 16:17:30 +00009425 depth = d2;
drh5eddca62001-06-30 21:53:53 +00009426 }
drhcbc6b712015-07-02 16:17:30 +00009427 }else{
9428 /* Populate the coverage-checking heap for leaf pages */
9429 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
drh5eddca62001-06-30 21:53:53 +00009430 }
9431 }
drhcbc6b712015-07-02 16:17:30 +00009432 *piMinKey = maxKey;
shaneh195475d2010-02-19 04:28:08 +00009433
drh5eddca62001-06-30 21:53:53 +00009434 /* Check for complete coverage of the page
9435 */
drh867db832014-09-26 02:41:05 +00009436 pCheck->zPfx = 0;
drhcbc6b712015-07-02 16:17:30 +00009437 if( doCoverageCheck && pCheck->mxErr>0 ){
9438 /* For leaf pages, the min-heap has already been initialized and the
9439 ** cells have already been inserted. But for internal pages, that has
9440 ** not yet been done, so do it now */
9441 if( !pPage->leaf ){
9442 heap = pCheck->heap;
9443 heap[0] = 0;
drhcbc6b712015-07-02 16:17:30 +00009444 for(i=nCell-1; i>=0; i--){
drh1910def2015-07-02 16:29:56 +00009445 u32 size;
9446 pc = get2byteAligned(&data[cellStart+i*2]);
9447 size = pPage->xCellSize(pPage, &data[pc]);
drh67731a92015-04-16 11:56:03 +00009448 btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
danielk19777701e812005-01-10 12:59:51 +00009449 }
drh2e38c322004-09-03 18:38:44 +00009450 }
drhcbc6b712015-07-02 16:17:30 +00009451 /* Add the freeblocks to the min-heap
9452 **
9453 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
drhfdab0262014-11-20 15:30:50 +00009454 ** is the offset of the first freeblock, or zero if there are no
drhcbc6b712015-07-02 16:17:30 +00009455 ** freeblocks on the page.
9456 */
drh8c2bbb62009-07-10 02:52:20 +00009457 i = get2byte(&data[hdr+1]);
9458 while( i>0 ){
9459 int size, j;
mistachkinc29cbb02015-07-02 16:52:01 +00009460 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
drh8c2bbb62009-07-10 02:52:20 +00009461 size = get2byte(&data[i+2]);
mistachkinc29cbb02015-07-02 16:52:01 +00009462 assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
drhe56d4302015-07-08 01:22:52 +00009463 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
drhfdab0262014-11-20 15:30:50 +00009464 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
9465 ** big-endian integer which is the offset in the b-tree page of the next
9466 ** freeblock in the chain, or zero if the freeblock is the last on the
9467 ** chain. */
drh8c2bbb62009-07-10 02:52:20 +00009468 j = get2byte(&data[i]);
drhfdab0262014-11-20 15:30:50 +00009469 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
9470 ** increasing offset. */
drh8c2bbb62009-07-10 02:52:20 +00009471 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
mistachkinc29cbb02015-07-02 16:52:01 +00009472 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
drh8c2bbb62009-07-10 02:52:20 +00009473 i = j;
drh2e38c322004-09-03 18:38:44 +00009474 }
drhcbc6b712015-07-02 16:17:30 +00009475 /* Analyze the min-heap looking for overlap between cells and/or
9476 ** freeblocks, and counting the number of untracked bytes in nFrag.
drhd2dc87f2015-07-02 19:47:08 +00009477 **
9478 ** Each min-heap entry is of the form: (start_address<<16)|end_address.
9479 ** There is an implied first entry the covers the page header, the cell
9480 ** pointer index, and the gap between the cell pointer index and the start
9481 ** of cell content.
9482 **
9483 ** The loop below pulls entries from the min-heap in order and compares
9484 ** the start_address against the previous end_address. If there is an
9485 ** overlap, that means bytes are used multiple times. If there is a gap,
9486 ** that gap is added to the fragmentation count.
drhcbc6b712015-07-02 16:17:30 +00009487 */
9488 nFrag = 0;
drhd2dc87f2015-07-02 19:47:08 +00009489 prev = contentOffset - 1; /* Implied first min-heap entry */
drh67731a92015-04-16 11:56:03 +00009490 while( btreeHeapPull(heap,&x) ){
drhd2dc87f2015-07-02 19:47:08 +00009491 if( (prev&0xffff)>=(x>>16) ){
drh867db832014-09-26 02:41:05 +00009492 checkAppendMsg(pCheck,
drh67731a92015-04-16 11:56:03 +00009493 "Multiple uses for byte %u of page %d", x>>16, iPage);
drh2e38c322004-09-03 18:38:44 +00009494 break;
drh67731a92015-04-16 11:56:03 +00009495 }else{
drhcbc6b712015-07-02 16:17:30 +00009496 nFrag += (x>>16) - (prev&0xffff) - 1;
drh67731a92015-04-16 11:56:03 +00009497 prev = x;
drh2e38c322004-09-03 18:38:44 +00009498 }
9499 }
drhcbc6b712015-07-02 16:17:30 +00009500 nFrag += usableSize - (prev&0xffff) - 1;
drhfdab0262014-11-20 15:30:50 +00009501 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
9502 ** is stored in the fifth field of the b-tree page header.
9503 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
9504 ** number of fragmented free bytes within the cell content area.
9505 */
drhcbc6b712015-07-02 16:17:30 +00009506 if( heap[0]==0 && nFrag!=data[hdr+7] ){
drh867db832014-09-26 02:41:05 +00009507 checkAppendMsg(pCheck,
drh8c2bbb62009-07-10 02:52:20 +00009508 "Fragmentation of %d bytes reported as %d on page %d",
drhcbc6b712015-07-02 16:17:30 +00009509 nFrag, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00009510 }
9511 }
drh867db832014-09-26 02:41:05 +00009512
9513end_of_check:
drh72e191e2015-07-04 11:14:20 +00009514 if( !doCoverageCheck ) pPage->isInit = savedIsInit;
drh4b70f112004-05-02 21:12:19 +00009515 releasePage(pPage);
drh867db832014-09-26 02:41:05 +00009516 pCheck->zPfx = saved_zPfx;
9517 pCheck->v1 = saved_v1;
9518 pCheck->v2 = saved_v2;
drhda200cc2004-05-09 11:51:38 +00009519 return depth+1;
drh5eddca62001-06-30 21:53:53 +00009520}
drhb7f91642004-10-31 02:22:47 +00009521#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00009522
drhb7f91642004-10-31 02:22:47 +00009523#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00009524/*
9525** This routine does a complete check of the given BTree file. aRoot[] is
9526** an array of pages numbers were each page number is the root page of
9527** a table. nRoot is the number of entries in aRoot.
9528**
danielk19773509a652009-07-06 18:56:13 +00009529** A read-only or read-write transaction must be opened before calling
9530** this function.
9531**
drhc890fec2008-08-01 20:10:08 +00009532** Write the number of error seen in *pnErr. Except for some memory
drhe43ba702008-12-05 22:40:08 +00009533** allocation errors, an error message held in memory obtained from
drhc890fec2008-08-01 20:10:08 +00009534** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
drhe43ba702008-12-05 22:40:08 +00009535** returned. If a memory allocation error occurs, NULL is returned.
drh5eddca62001-06-30 21:53:53 +00009536*/
drh1dcdbc02007-01-27 02:24:54 +00009537char *sqlite3BtreeIntegrityCheck(
9538 Btree *p, /* The btree to be checked */
9539 int *aRoot, /* An array of root pages numbers for individual trees */
9540 int nRoot, /* Number of entries in aRoot[] */
9541 int mxErr, /* Stop reporting errors after this many */
9542 int *pnErr /* Write number of errors seen to this variable */
9543){
danielk197789d40042008-11-17 14:20:56 +00009544 Pgno i;
drhaaab5722002-02-19 13:39:21 +00009545 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00009546 BtShared *pBt = p->pBt;
drhcbc6b712015-07-02 16:17:30 +00009547 int savedDbFlags = pBt->db->flags;
drhf089aa42008-07-08 19:34:06 +00009548 char zErr[100];
drhcbc6b712015-07-02 16:17:30 +00009549 VVA_ONLY( int nRef );
drh5eddca62001-06-30 21:53:53 +00009550
drhd677b3d2007-08-20 22:48:41 +00009551 sqlite3BtreeEnter(p);
danielk19773509a652009-07-06 18:56:13 +00009552 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
drhcc5f8a42016-02-06 22:32:06 +00009553 VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
9554 assert( nRef>=0 );
drh5eddca62001-06-30 21:53:53 +00009555 sCheck.pBt = pBt;
9556 sCheck.pPager = pBt->pPager;
drhb1299152010-03-30 22:58:33 +00009557 sCheck.nPage = btreePagecount(sCheck.pBt);
drh1dcdbc02007-01-27 02:24:54 +00009558 sCheck.mxErr = mxErr;
9559 sCheck.nErr = 0;
drhc890fec2008-08-01 20:10:08 +00009560 sCheck.mallocFailed = 0;
drh867db832014-09-26 02:41:05 +00009561 sCheck.zPfx = 0;
9562 sCheck.v1 = 0;
9563 sCheck.v2 = 0;
drhe05b3f82015-07-01 17:53:49 +00009564 sCheck.aPgRef = 0;
9565 sCheck.heap = 0;
9566 sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
drh5f4a6862016-01-30 12:50:25 +00009567 sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
drh0de8c112002-07-06 16:32:14 +00009568 if( sCheck.nPage==0 ){
drhe05b3f82015-07-01 17:53:49 +00009569 goto integrity_ck_cleanup;
drh0de8c112002-07-06 16:32:14 +00009570 }
dan1235bb12012-04-03 17:43:28 +00009571
9572 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
9573 if( !sCheck.aPgRef ){
drhe05b3f82015-07-01 17:53:49 +00009574 sCheck.mallocFailed = 1;
9575 goto integrity_ck_cleanup;
danielk1977ac245ec2005-01-14 13:50:11 +00009576 }
drhe05b3f82015-07-01 17:53:49 +00009577 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
9578 if( sCheck.heap==0 ){
9579 sCheck.mallocFailed = 1;
9580 goto integrity_ck_cleanup;
9581 }
9582
drh42cac6d2004-11-20 20:31:11 +00009583 i = PENDING_BYTE_PAGE(pBt);
dan1235bb12012-04-03 17:43:28 +00009584 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
drh5eddca62001-06-30 21:53:53 +00009585
9586 /* Check the integrity of the freelist
9587 */
drh867db832014-09-26 02:41:05 +00009588 sCheck.zPfx = "Main freelist: ";
drha34b6762004-05-07 13:30:42 +00009589 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
drh867db832014-09-26 02:41:05 +00009590 get4byte(&pBt->pPage1->aData[36]));
9591 sCheck.zPfx = 0;
drh5eddca62001-06-30 21:53:53 +00009592
9593 /* Check all the tables.
9594 */
drhcbc6b712015-07-02 16:17:30 +00009595 testcase( pBt->db->flags & SQLITE_CellSizeCk );
9596 pBt->db->flags &= ~SQLITE_CellSizeCk;
danielk197789d40042008-11-17 14:20:56 +00009597 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
drhcbc6b712015-07-02 16:17:30 +00009598 i64 notUsed;
drh4ff6dfa2002-03-03 23:06:00 +00009599 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00009600#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00009601 if( pBt->autoVacuum && aRoot[i]>1 ){
drh867db832014-09-26 02:41:05 +00009602 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +00009603 }
9604#endif
drhcbc6b712015-07-02 16:17:30 +00009605 checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
drh5eddca62001-06-30 21:53:53 +00009606 }
drhcbc6b712015-07-02 16:17:30 +00009607 pBt->db->flags = savedDbFlags;
drh5eddca62001-06-30 21:53:53 +00009608
9609 /* Make sure every page in the file is referenced
9610 */
drh1dcdbc02007-01-27 02:24:54 +00009611 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00009612#ifdef SQLITE_OMIT_AUTOVACUUM
dan1235bb12012-04-03 17:43:28 +00009613 if( getPageReferenced(&sCheck, i)==0 ){
drh867db832014-09-26 02:41:05 +00009614 checkAppendMsg(&sCheck, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00009615 }
danielk1977afcdd022004-10-31 16:25:42 +00009616#else
9617 /* If the database supports auto-vacuum, make sure no tables contain
9618 ** references to pointer-map pages.
9619 */
dan1235bb12012-04-03 17:43:28 +00009620 if( getPageReferenced(&sCheck, i)==0 &&
danielk1977266664d2006-02-10 08:24:21 +00009621 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
drh867db832014-09-26 02:41:05 +00009622 checkAppendMsg(&sCheck, "Page %d is never used", i);
danielk1977afcdd022004-10-31 16:25:42 +00009623 }
dan1235bb12012-04-03 17:43:28 +00009624 if( getPageReferenced(&sCheck, i)!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00009625 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
drh867db832014-09-26 02:41:05 +00009626 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
danielk1977afcdd022004-10-31 16:25:42 +00009627 }
9628#endif
drh5eddca62001-06-30 21:53:53 +00009629 }
9630
drh5eddca62001-06-30 21:53:53 +00009631 /* Clean up and report errors.
9632 */
drhe05b3f82015-07-01 17:53:49 +00009633integrity_ck_cleanup:
9634 sqlite3PageFree(sCheck.heap);
dan1235bb12012-04-03 17:43:28 +00009635 sqlite3_free(sCheck.aPgRef);
drhc890fec2008-08-01 20:10:08 +00009636 if( sCheck.mallocFailed ){
9637 sqlite3StrAccumReset(&sCheck.errMsg);
drhe05b3f82015-07-01 17:53:49 +00009638 sCheck.nErr++;
drhc890fec2008-08-01 20:10:08 +00009639 }
drh1dcdbc02007-01-27 02:24:54 +00009640 *pnErr = sCheck.nErr;
drhf089aa42008-07-08 19:34:06 +00009641 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
drhe05b3f82015-07-01 17:53:49 +00009642 /* Make sure this analysis did not leave any unref() pages. */
9643 assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
9644 sqlite3BtreeLeave(p);
drhf089aa42008-07-08 19:34:06 +00009645 return sqlite3StrAccumFinish(&sCheck.errMsg);
drh5eddca62001-06-30 21:53:53 +00009646}
drhb7f91642004-10-31 02:22:47 +00009647#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00009648
drh73509ee2003-04-06 20:44:45 +00009649/*
drhd4e0bb02012-05-27 01:19:04 +00009650** Return the full pathname of the underlying database file. Return
9651** an empty string if the database is in-memory or a TEMP database.
drhd0679ed2007-08-28 22:24:34 +00009652**
9653** The pager filename is invariant as long as the pager is
9654** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00009655*/
danielk1977aef0bf62005-12-30 16:28:01 +00009656const char *sqlite3BtreeGetFilename(Btree *p){
9657 assert( p->pBt->pPager!=0 );
drhd4e0bb02012-05-27 01:19:04 +00009658 return sqlite3PagerFilename(p->pBt->pPager, 1);
drh73509ee2003-04-06 20:44:45 +00009659}
9660
9661/*
danielk19775865e3d2004-06-14 06:03:57 +00009662** Return the pathname of the journal file for this database. The return
9663** value of this routine is the same regardless of whether the journal file
9664** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00009665**
9666** The pager journal filename is invariant as long as the pager is
9667** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00009668*/
danielk1977aef0bf62005-12-30 16:28:01 +00009669const char *sqlite3BtreeGetJournalname(Btree *p){
9670 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00009671 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00009672}
9673
danielk19771d850a72004-05-31 08:26:49 +00009674/*
9675** Return non-zero if a transaction is active.
9676*/
danielk1977aef0bf62005-12-30 16:28:01 +00009677int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00009678 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00009679 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00009680}
9681
dana550f2d2010-08-02 10:47:05 +00009682#ifndef SQLITE_OMIT_WAL
9683/*
9684** Run a checkpoint on the Btree passed as the first argument.
9685**
9686** Return SQLITE_LOCKED if this or any other connection has an open
9687** transaction on the shared-cache the argument Btree is connected to.
dana58f26f2010-11-16 18:56:51 +00009688**
dancdc1f042010-11-18 12:11:05 +00009689** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
dana550f2d2010-08-02 10:47:05 +00009690*/
dancdc1f042010-11-18 12:11:05 +00009691int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
dana550f2d2010-08-02 10:47:05 +00009692 int rc = SQLITE_OK;
9693 if( p ){
9694 BtShared *pBt = p->pBt;
9695 sqlite3BtreeEnter(p);
9696 if( pBt->inTransaction!=TRANS_NONE ){
9697 rc = SQLITE_LOCKED;
9698 }else{
dan7fb89902016-08-12 16:21:15 +00009699 rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
dana550f2d2010-08-02 10:47:05 +00009700 }
9701 sqlite3BtreeLeave(p);
9702 }
9703 return rc;
9704}
9705#endif
9706
danielk19771d850a72004-05-31 08:26:49 +00009707/*
danielk19772372c2b2006-06-27 16:34:56 +00009708** Return non-zero if a read (or write) transaction is active.
9709*/
9710int sqlite3BtreeIsInReadTrans(Btree *p){
drh64022502009-01-09 14:11:04 +00009711 assert( p );
drhe5fe6902007-12-07 18:55:28 +00009712 assert( sqlite3_mutex_held(p->db->mutex) );
drh64022502009-01-09 14:11:04 +00009713 return p->inTrans!=TRANS_NONE;
danielk19772372c2b2006-06-27 16:34:56 +00009714}
9715
danielk197704103022009-02-03 16:51:24 +00009716int sqlite3BtreeIsInBackup(Btree *p){
9717 assert( p );
9718 assert( sqlite3_mutex_held(p->db->mutex) );
9719 return p->nBackup!=0;
9720}
9721
danielk19772372c2b2006-06-27 16:34:56 +00009722/*
danielk1977da184232006-01-05 11:34:32 +00009723** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +00009724** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +00009725** purposes (for example, to store a high-level schema associated with
9726** the shared-btree). The btree layer manages reference counting issues.
9727**
9728** The first time this is called on a shared-btree, nBytes bytes of memory
9729** are allocated, zeroed, and returned to the caller. For each subsequent
9730** call the nBytes parameter is ignored and a pointer to the same blob
9731** of memory returned.
9732**
danielk1977171bfed2008-06-23 09:50:50 +00009733** If the nBytes parameter is 0 and the blob of memory has not yet been
9734** allocated, a null pointer is returned. If the blob has already been
9735** allocated, it is returned as normal.
9736**
danielk1977da184232006-01-05 11:34:32 +00009737** Just before the shared-btree is closed, the function passed as the
9738** xFree argument when the memory allocation was made is invoked on the
drh4fa7d7c2011-04-03 02:41:00 +00009739** blob of allocated memory. The xFree function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00009740** on the memory, the btree layer does that.
9741*/
9742void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
9743 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00009744 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +00009745 if( !pBt->pSchema && nBytes ){
drhb9755982010-07-24 16:34:37 +00009746 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
danielk1977da184232006-01-05 11:34:32 +00009747 pBt->xFreeSchema = xFree;
9748 }
drh27641702007-08-22 02:56:42 +00009749 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00009750 return pBt->pSchema;
9751}
9752
danielk1977c87d34d2006-01-06 13:00:28 +00009753/*
danielk1977404ca072009-03-16 13:19:36 +00009754** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
9755** btree as the argument handle holds an exclusive lock on the
9756** sqlite_master table. Otherwise SQLITE_OK.
danielk1977c87d34d2006-01-06 13:00:28 +00009757*/
9758int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00009759 int rc;
drhe5fe6902007-12-07 18:55:28 +00009760 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +00009761 sqlite3BtreeEnter(p);
danielk1977404ca072009-03-16 13:19:36 +00009762 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
9763 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
drh27641702007-08-22 02:56:42 +00009764 sqlite3BtreeLeave(p);
9765 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00009766}
9767
drha154dcd2006-03-22 22:10:07 +00009768
9769#ifndef SQLITE_OMIT_SHARED_CACHE
9770/*
9771** Obtain a lock on the table whose root page is iTab. The
9772** lock is a write lock if isWritelock is true or a read lock
9773** if it is false.
9774*/
danielk1977c00da102006-01-07 13:21:04 +00009775int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00009776 int rc = SQLITE_OK;
danielk1977602b4662009-07-02 07:47:33 +00009777 assert( p->inTrans!=TRANS_NONE );
drh6a9ad3d2008-04-02 16:29:30 +00009778 if( p->sharable ){
9779 u8 lockType = READ_LOCK + isWriteLock;
9780 assert( READ_LOCK+1==WRITE_LOCK );
9781 assert( isWriteLock==0 || isWriteLock==1 );
danielk1977602b4662009-07-02 07:47:33 +00009782
drh6a9ad3d2008-04-02 16:29:30 +00009783 sqlite3BtreeEnter(p);
drhc25eabe2009-02-24 18:57:31 +00009784 rc = querySharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00009785 if( rc==SQLITE_OK ){
drhc25eabe2009-02-24 18:57:31 +00009786 rc = setSharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00009787 }
9788 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00009789 }
9790 return rc;
9791}
drha154dcd2006-03-22 22:10:07 +00009792#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00009793
danielk1977b4e9af92007-05-01 17:49:49 +00009794#ifndef SQLITE_OMIT_INCRBLOB
9795/*
9796** Argument pCsr must be a cursor opened for writing on an
9797** INTKEY table currently pointing at a valid table entry.
9798** This function modifies the data stored as part of that entry.
danielk1977ecaecf92009-07-08 08:05:35 +00009799**
9800** Only the data content may only be modified, it is not possible to
9801** change the length of the data stored. If this function is called with
9802** parameters that attempt to write past the end of the existing data,
9803** no modifications are made and SQLITE_CORRUPT is returned.
danielk1977b4e9af92007-05-01 17:49:49 +00009804*/
danielk1977dcbb5d32007-05-04 18:36:44 +00009805int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
danielk1977c9000e62009-07-08 13:55:28 +00009806 int rc;
dan7a2347e2016-01-07 16:43:54 +00009807 assert( cursorOwnsBtShared(pCsr) );
drhe5fe6902007-12-07 18:55:28 +00009808 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
drh036dbec2014-03-11 23:40:44 +00009809 assert( pCsr->curFlags & BTCF_Incrblob );
danielk19773588ceb2008-06-10 17:30:26 +00009810
danielk1977c9000e62009-07-08 13:55:28 +00009811 rc = restoreCursorPosition(pCsr);
9812 if( rc!=SQLITE_OK ){
9813 return rc;
9814 }
danielk19773588ceb2008-06-10 17:30:26 +00009815 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
9816 if( pCsr->eState!=CURSOR_VALID ){
9817 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +00009818 }
9819
dan227a1c42013-04-03 11:17:39 +00009820 /* Save the positions of all other cursors open on this table. This is
9821 ** required in case any of them are holding references to an xFetch
9822 ** version of the b-tree page modified by the accessPayload call below.
drh370c9f42013-04-03 20:04:04 +00009823 **
drh3f387402014-09-24 01:23:00 +00009824 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
drh370c9f42013-04-03 20:04:04 +00009825 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
9826 ** saveAllCursors can only return SQLITE_OK.
dan227a1c42013-04-03 11:17:39 +00009827 */
drh370c9f42013-04-03 20:04:04 +00009828 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
9829 assert( rc==SQLITE_OK );
dan227a1c42013-04-03 11:17:39 +00009830
danielk1977c9000e62009-07-08 13:55:28 +00009831 /* Check some assumptions:
danielk1977dcbb5d32007-05-04 18:36:44 +00009832 ** (a) the cursor is open for writing,
danielk1977c9000e62009-07-08 13:55:28 +00009833 ** (b) there is a read/write transaction open,
9834 ** (c) the connection holds a write-lock on the table (if required),
9835 ** (d) there are no conflicting read-locks, and
9836 ** (e) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00009837 */
drh036dbec2014-03-11 23:40:44 +00009838 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
danielk19774f029602009-07-08 18:45:37 +00009839 return SQLITE_READONLY;
9840 }
drhc9166342012-01-05 23:32:06 +00009841 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
9842 && pCsr->pBt->inTransaction==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +00009843 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
9844 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
drh352a35a2017-08-15 03:46:47 +00009845 assert( pCsr->pPage->intKey );
danielk1977b4e9af92007-05-01 17:49:49 +00009846
drhfb192682009-07-11 18:26:28 +00009847 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00009848}
danielk19772dec9702007-05-02 16:48:37 +00009849
9850/*
dan5a500af2014-03-11 20:33:04 +00009851** Mark this cursor as an incremental blob cursor.
danielk19772dec9702007-05-02 16:48:37 +00009852*/
dan5a500af2014-03-11 20:33:04 +00009853void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
drh036dbec2014-03-11 23:40:44 +00009854 pCur->curFlags |= BTCF_Incrblob;
drh69180952015-06-25 13:03:10 +00009855 pCur->pBtree->hasIncrblobCur = 1;
danielk19772dec9702007-05-02 16:48:37 +00009856}
danielk1977b4e9af92007-05-01 17:49:49 +00009857#endif
dane04dc882010-04-20 18:53:15 +00009858
9859/*
9860** Set both the "read version" (single byte at byte offset 18) and
9861** "write version" (single byte at byte offset 19) fields in the database
9862** header to iVersion.
9863*/
9864int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
9865 BtShared *pBt = pBtree->pBt;
9866 int rc; /* Return code */
9867
dane04dc882010-04-20 18:53:15 +00009868 assert( iVersion==1 || iVersion==2 );
9869
danb9780022010-04-21 18:37:57 +00009870 /* If setting the version fields to 1, do not automatically open the
9871 ** WAL connection, even if the version fields are currently set to 2.
9872 */
drhc9166342012-01-05 23:32:06 +00009873 pBt->btsFlags &= ~BTS_NO_WAL;
9874 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
danb9780022010-04-21 18:37:57 +00009875
9876 rc = sqlite3BtreeBeginTrans(pBtree, 0);
dane04dc882010-04-20 18:53:15 +00009877 if( rc==SQLITE_OK ){
9878 u8 *aData = pBt->pPage1->aData;
danb9780022010-04-21 18:37:57 +00009879 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
danede6eb82010-04-22 06:27:04 +00009880 rc = sqlite3BtreeBeginTrans(pBtree, 2);
danb9780022010-04-21 18:37:57 +00009881 if( rc==SQLITE_OK ){
9882 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
9883 if( rc==SQLITE_OK ){
9884 aData[18] = (u8)iVersion;
9885 aData[19] = (u8)iVersion;
9886 }
9887 }
9888 }
dane04dc882010-04-20 18:53:15 +00009889 }
9890
drhc9166342012-01-05 23:32:06 +00009891 pBt->btsFlags &= ~BTS_NO_WAL;
dane04dc882010-04-20 18:53:15 +00009892 return rc;
9893}
dan428c2182012-08-06 18:50:11 +00009894
drhe0997b32015-03-20 14:57:50 +00009895/*
9896** Return true if the cursor has a hint specified. This routine is
9897** only used from within assert() statements
9898*/
9899int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
9900 return (pCsr->hints & mask)!=0;
9901}
drhe0997b32015-03-20 14:57:50 +00009902
drh781597f2014-05-21 08:21:07 +00009903/*
9904** Return true if the given Btree is read-only.
9905*/
9906int sqlite3BtreeIsReadonly(Btree *p){
9907 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
9908}
drhdef68892014-11-04 12:11:23 +00009909
9910/*
9911** Return the size of the header added to each page by this module.
9912*/
drh37c057b2014-12-30 00:57:29 +00009913int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
dan20d876f2016-01-07 16:06:22 +00009914
drh5a1fb182016-01-08 19:34:39 +00009915#if !defined(SQLITE_OMIT_SHARED_CACHE)
dan20d876f2016-01-07 16:06:22 +00009916/*
9917** Return true if the Btree passed as the only argument is sharable.
9918*/
9919int sqlite3BtreeSharable(Btree *p){
9920 return p->sharable;
9921}
dan272989b2016-07-06 10:12:02 +00009922
9923/*
9924** Return the number of connections to the BtShared object accessed by
9925** the Btree handle passed as the only argument. For private caches
9926** this is always 1. For shared caches it may be 1 or greater.
9927*/
9928int sqlite3BtreeConnectionCount(Btree *p){
9929 testcase( p->sharable );
9930 return p->pBt->nRef;
9931}
drh5a1fb182016-01-08 19:34:39 +00009932#endif