blob: 4077b8dd9831a94567296ffe1c0f727779f1c771 [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**
drhccb21132020-06-19 11:34:57 +000072** Access to this variable is protected by SQLITE_MUTEX_STATIC_MAIN.
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
drh37ccfcf2020-08-31 18:49:04 +0000115#ifdef SQLITE_DEBUG
116/*
drha7fc1682020-11-24 19:55:49 +0000117** Return and reset the seek counter for a Btree object.
drh37ccfcf2020-08-31 18:49:04 +0000118*/
119sqlite3_uint64 sqlite3BtreeSeekCount(Btree *pBt){
120 u64 n = pBt->nSeek;
121 pBt->nSeek = 0;
122 return n;
123}
124#endif
125
daneebf2f52017-11-18 17:30:08 +0000126/*
127** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
128** (MemPage*) as an argument. The (MemPage*) must not be NULL.
129**
130** If SQLITE_DEBUG is not defined, then this macro is equivalent to
131** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
132** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
133** with the page number and filename associated with the (MemPage*).
134*/
135#ifdef SQLITE_DEBUG
136int corruptPageError(int lineno, MemPage *p){
drh8bfe66a2018-01-22 15:45:12 +0000137 char *zMsg;
138 sqlite3BeginBenignMalloc();
139 zMsg = sqlite3_mprintf("database corruption page %d of %s",
daneebf2f52017-11-18 17:30:08 +0000140 (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
141 );
drh8bfe66a2018-01-22 15:45:12 +0000142 sqlite3EndBenignMalloc();
daneebf2f52017-11-18 17:30:08 +0000143 if( zMsg ){
144 sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
145 }
146 sqlite3_free(zMsg);
147 return SQLITE_CORRUPT_BKPT;
148}
149# define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
150#else
151# define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
152#endif
153
drhe53831d2007-08-17 01:14:38 +0000154#ifndef SQLITE_OMIT_SHARED_CACHE
danielk197796d48e92009-06-29 06:00:37 +0000155
156#ifdef SQLITE_DEBUG
157/*
drh0ee3dbe2009-10-16 15:05:18 +0000158**** This function is only used as part of an assert() statement. ***
159**
160** Check to see if pBtree holds the required locks to read or write to the
161** table with root page iRoot. Return 1 if it does and 0 if not.
162**
163** For example, when writing to a table with root-page iRoot via
danielk197796d48e92009-06-29 06:00:37 +0000164** Btree connection pBtree:
165**
166** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
167**
drh0ee3dbe2009-10-16 15:05:18 +0000168** When writing to an index that resides in a sharable database, the
danielk197796d48e92009-06-29 06:00:37 +0000169** caller should have first obtained a lock specifying the root page of
drh0ee3dbe2009-10-16 15:05:18 +0000170** the corresponding table. This makes things a bit more complicated,
171** as this module treats each table as a separate structure. To determine
172** the table corresponding to the index being written, this
danielk197796d48e92009-06-29 06:00:37 +0000173** function has to search through the database schema.
174**
drh0ee3dbe2009-10-16 15:05:18 +0000175** Instead of a lock on the table/index rooted at page iRoot, the caller may
danielk197796d48e92009-06-29 06:00:37 +0000176** hold a write-lock on the schema table (root page 1). This is also
177** acceptable.
178*/
179static int hasSharedCacheTableLock(
180 Btree *pBtree, /* Handle that must hold lock */
181 Pgno iRoot, /* Root page of b-tree */
182 int isIndex, /* True if iRoot is the root of an index b-tree */
183 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
184){
185 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
186 Pgno iTab = 0;
187 BtLock *pLock;
188
drh0ee3dbe2009-10-16 15:05:18 +0000189 /* If this database is not shareable, or if the client is reading
danielk197796d48e92009-06-29 06:00:37 +0000190 ** and has the read-uncommitted flag set, then no lock is required.
drh0ee3dbe2009-10-16 15:05:18 +0000191 ** Return true immediately.
192 */
danielk197796d48e92009-06-29 06:00:37 +0000193 if( (pBtree->sharable==0)
drh169dd922017-06-26 13:57:49 +0000194 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
danielk197796d48e92009-06-29 06:00:37 +0000195 ){
196 return 1;
197 }
198
drh0ee3dbe2009-10-16 15:05:18 +0000199 /* If the client is reading or writing an index and the schema is
200 ** not loaded, then it is too difficult to actually check to see if
201 ** the correct locks are held. So do not bother - just return true.
202 ** This case does not come up very often anyhow.
203 */
drh2c5e35f2014-08-05 11:04:21 +0000204 if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
drh0ee3dbe2009-10-16 15:05:18 +0000205 return 1;
206 }
207
danielk197796d48e92009-06-29 06:00:37 +0000208 /* Figure out the root-page that the lock should be held on. For table
209 ** b-trees, this is just the root page of the b-tree being read or
210 ** written. For index b-trees, it is the root page of the associated
211 ** table. */
212 if( isIndex ){
213 HashElem *p;
dan877859f2020-06-17 20:29:56 +0000214 int bSeen = 0;
danielk197796d48e92009-06-29 06:00:37 +0000215 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
216 Index *pIdx = (Index *)sqliteHashData(p);
drhe684ac62022-03-08 13:59:46 +0000217 if( pIdx->tnum==iRoot ){
dan877859f2020-06-17 20:29:56 +0000218 if( bSeen ){
drh1ffede82015-01-30 20:59:27 +0000219 /* Two or more indexes share the same root page. There must
220 ** be imposter tables. So just return true. The assert is not
221 ** useful in that case. */
222 return 1;
223 }
shane5eff7cf2009-08-10 03:57:58 +0000224 iTab = pIdx->pTable->tnum;
dan877859f2020-06-17 20:29:56 +0000225 bSeen = 1;
danielk197796d48e92009-06-29 06:00:37 +0000226 }
227 }
228 }else{
229 iTab = iRoot;
230 }
231
232 /* Search for the required lock. Either a write-lock on root-page iTab, a
233 ** write-lock on the schema table, or (if the client is reading) a
234 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
235 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
236 if( pLock->pBtree==pBtree
237 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
238 && pLock->eLock>=eLockType
239 ){
240 return 1;
241 }
242 }
243
244 /* Failed to find the required lock. */
245 return 0;
246}
drh0ee3dbe2009-10-16 15:05:18 +0000247#endif /* SQLITE_DEBUG */
danielk197796d48e92009-06-29 06:00:37 +0000248
drh0ee3dbe2009-10-16 15:05:18 +0000249#ifdef SQLITE_DEBUG
danielk197796d48e92009-06-29 06:00:37 +0000250/*
drh0ee3dbe2009-10-16 15:05:18 +0000251**** This function may be used as part of assert() statements only. ****
danielk197796d48e92009-06-29 06:00:37 +0000252**
drh0ee3dbe2009-10-16 15:05:18 +0000253** Return true if it would be illegal for pBtree to write into the
254** table or index rooted at iRoot because other shared connections are
255** simultaneously reading that same table or index.
256**
257** It is illegal for pBtree to write if some other Btree object that
258** shares the same BtShared object is currently reading or writing
259** the iRoot table. Except, if the other Btree object has the
260** read-uncommitted flag set, then it is OK for the other object to
261** have a read cursor.
262**
263** For example, before writing to any part of the table or index
264** rooted at page iRoot, one should call:
danielk197796d48e92009-06-29 06:00:37 +0000265**
266** assert( !hasReadConflicts(pBtree, iRoot) );
267*/
268static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
269 BtCursor *p;
270 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
271 if( p->pgnoRoot==iRoot
272 && p->pBtree!=pBtree
drh169dd922017-06-26 13:57:49 +0000273 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
danielk197796d48e92009-06-29 06:00:37 +0000274 ){
275 return 1;
276 }
277 }
278 return 0;
279}
280#endif /* #ifdef SQLITE_DEBUG */
281
danielk1977da184232006-01-05 11:34:32 +0000282/*
drh0ee3dbe2009-10-16 15:05:18 +0000283** Query to see if Btree handle p may obtain a lock of type eLock
danielk1977aef0bf62005-12-30 16:28:01 +0000284** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
drhc25eabe2009-02-24 18:57:31 +0000285** SQLITE_OK if the lock may be obtained (by calling
286** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
danielk1977aef0bf62005-12-30 16:28:01 +0000287*/
drhc25eabe2009-02-24 18:57:31 +0000288static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +0000289 BtShared *pBt = p->pBt;
290 BtLock *pIter;
291
drh1fee73e2007-08-29 04:00:57 +0000292 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000293 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
294 assert( p->db!=0 );
drh169dd922017-06-26 13:57:49 +0000295 assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
drhd677b3d2007-08-20 22:48:41 +0000296
danielk19775b413d72009-04-01 09:41:54 +0000297 /* If requesting a write-lock, then the Btree must have an open write
298 ** transaction on this file. And, obviously, for this to be so there
299 ** must be an open write transaction on the file itself.
300 */
301 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
302 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
303
drh0ee3dbe2009-10-16 15:05:18 +0000304 /* This routine is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000305 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000306 return SQLITE_OK;
307 }
308
danielk1977641b0f42007-12-21 04:47:25 +0000309 /* If some other connection is holding an exclusive lock, the
310 ** requested lock may not be obtained.
311 */
drhc9166342012-01-05 23:32:06 +0000312 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
danielk1977404ca072009-03-16 13:19:36 +0000313 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
314 return SQLITE_LOCKED_SHAREDCACHE;
danielk1977641b0f42007-12-21 04:47:25 +0000315 }
316
danielk1977e0d9e6f2009-07-03 16:25:06 +0000317 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
318 /* The condition (pIter->eLock!=eLock) in the following if(...)
319 ** statement is a simplification of:
320 **
321 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
322 **
323 ** since we know that if eLock==WRITE_LOCK, then no other connection
324 ** may hold a WRITE_LOCK on any table in this file (since there can
325 ** only be a single writer).
326 */
327 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
328 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
329 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
330 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
331 if( eLock==WRITE_LOCK ){
332 assert( p==pBt->pWriter );
drhc9166342012-01-05 23:32:06 +0000333 pBt->btsFlags |= BTS_PENDING;
danielk1977da184232006-01-05 11:34:32 +0000334 }
danielk1977e0d9e6f2009-07-03 16:25:06 +0000335 return SQLITE_LOCKED_SHAREDCACHE;
danielk1977aef0bf62005-12-30 16:28:01 +0000336 }
337 }
338 return SQLITE_OK;
339}
drhe53831d2007-08-17 01:14:38 +0000340#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000341
drhe53831d2007-08-17 01:14:38 +0000342#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000343/*
344** Add a lock on the table with root-page iTable to the shared-btree used
345** by Btree handle p. Parameter eLock must be either READ_LOCK or
346** WRITE_LOCK.
347**
danielk19779d104862009-07-09 08:27:14 +0000348** This function assumes the following:
349**
drh0ee3dbe2009-10-16 15:05:18 +0000350** (a) The specified Btree object p is connected to a sharable
351** database (one with the BtShared.sharable flag set), and
danielk19779d104862009-07-09 08:27:14 +0000352**
drh0ee3dbe2009-10-16 15:05:18 +0000353** (b) No other Btree objects hold a lock that conflicts
danielk19779d104862009-07-09 08:27:14 +0000354** with the requested lock (i.e. querySharedCacheTableLock() has
355** already been called and returned SQLITE_OK).
356**
357** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
358** is returned if a malloc attempt fails.
danielk1977aef0bf62005-12-30 16:28:01 +0000359*/
drhc25eabe2009-02-24 18:57:31 +0000360static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +0000361 BtShared *pBt = p->pBt;
362 BtLock *pLock = 0;
363 BtLock *pIter;
364
drh1fee73e2007-08-29 04:00:57 +0000365 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000366 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
367 assert( p->db!=0 );
drhd677b3d2007-08-20 22:48:41 +0000368
danielk1977e0d9e6f2009-07-03 16:25:06 +0000369 /* A connection with the read-uncommitted flag set will never try to
370 ** obtain a read-lock using this function. The only read-lock obtained
drh1e32bed2020-06-19 13:33:53 +0000371 ** by a connection in read-uncommitted mode is on the sqlite_schema
danielk1977e0d9e6f2009-07-03 16:25:06 +0000372 ** table, and that lock is obtained in BtreeBeginTrans(). */
drh169dd922017-06-26 13:57:49 +0000373 assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
danielk1977e0d9e6f2009-07-03 16:25:06 +0000374
danielk19779d104862009-07-09 08:27:14 +0000375 /* This function should only be called on a sharable b-tree after it
376 ** has been determined that no other b-tree holds a conflicting lock. */
377 assert( p->sharable );
drhc25eabe2009-02-24 18:57:31 +0000378 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
danielk1977aef0bf62005-12-30 16:28:01 +0000379
380 /* First search the list for an existing lock on this table. */
381 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
382 if( pIter->iTable==iTable && pIter->pBtree==p ){
383 pLock = pIter;
384 break;
385 }
386 }
387
388 /* If the above search did not find a BtLock struct associating Btree p
389 ** with table iTable, allocate one and link it into the list.
390 */
391 if( !pLock ){
drh17435752007-08-16 04:30:38 +0000392 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
danielk1977aef0bf62005-12-30 16:28:01 +0000393 if( !pLock ){
mistachkinfad30392016-02-13 23:43:46 +0000394 return SQLITE_NOMEM_BKPT;
danielk1977aef0bf62005-12-30 16:28:01 +0000395 }
396 pLock->iTable = iTable;
397 pLock->pBtree = p;
398 pLock->pNext = pBt->pLock;
399 pBt->pLock = pLock;
400 }
401
402 /* Set the BtLock.eLock variable to the maximum of the current lock
403 ** and the requested lock. This means if a write-lock was already held
404 ** and a read-lock requested, we don't incorrectly downgrade the lock.
405 */
406 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000407 if( eLock>pLock->eLock ){
408 pLock->eLock = eLock;
409 }
danielk1977aef0bf62005-12-30 16:28:01 +0000410
411 return SQLITE_OK;
412}
drhe53831d2007-08-17 01:14:38 +0000413#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000414
drhe53831d2007-08-17 01:14:38 +0000415#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000416/*
drhc25eabe2009-02-24 18:57:31 +0000417** Release all the table locks (locks obtained via calls to
drh0ee3dbe2009-10-16 15:05:18 +0000418** the setSharedCacheTableLock() procedure) held by Btree object p.
danielk1977fa542f12009-04-02 18:28:08 +0000419**
drh0ee3dbe2009-10-16 15:05:18 +0000420** This function assumes that Btree p has an open read or write
drhc9166342012-01-05 23:32:06 +0000421** transaction. If it does not, then the BTS_PENDING flag
danielk1977fa542f12009-04-02 18:28:08 +0000422** may be incorrectly cleared.
danielk1977aef0bf62005-12-30 16:28:01 +0000423*/
drhc25eabe2009-02-24 18:57:31 +0000424static void clearAllSharedCacheTableLocks(Btree *p){
danielk1977641b0f42007-12-21 04:47:25 +0000425 BtShared *pBt = p->pBt;
426 BtLock **ppIter = &pBt->pLock;
danielk1977da184232006-01-05 11:34:32 +0000427
drh1fee73e2007-08-29 04:00:57 +0000428 assert( sqlite3BtreeHoldsMutex(p) );
drhe53831d2007-08-17 01:14:38 +0000429 assert( p->sharable || 0==*ppIter );
danielk1977fa542f12009-04-02 18:28:08 +0000430 assert( p->inTrans>0 );
danielk1977da184232006-01-05 11:34:32 +0000431
danielk1977aef0bf62005-12-30 16:28:01 +0000432 while( *ppIter ){
433 BtLock *pLock = *ppIter;
drhc9166342012-01-05 23:32:06 +0000434 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
danielk1977fa542f12009-04-02 18:28:08 +0000435 assert( pLock->pBtree->inTrans>=pLock->eLock );
danielk1977aef0bf62005-12-30 16:28:01 +0000436 if( pLock->pBtree==p ){
437 *ppIter = pLock->pNext;
danielk1977602b4662009-07-02 07:47:33 +0000438 assert( pLock->iTable!=1 || pLock==&p->lock );
439 if( pLock->iTable!=1 ){
440 sqlite3_free(pLock);
441 }
danielk1977aef0bf62005-12-30 16:28:01 +0000442 }else{
443 ppIter = &pLock->pNext;
444 }
445 }
danielk1977641b0f42007-12-21 04:47:25 +0000446
drhc9166342012-01-05 23:32:06 +0000447 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
danielk1977404ca072009-03-16 13:19:36 +0000448 if( pBt->pWriter==p ){
449 pBt->pWriter = 0;
drhc9166342012-01-05 23:32:06 +0000450 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
danielk1977404ca072009-03-16 13:19:36 +0000451 }else if( pBt->nTransaction==2 ){
drh0ee3dbe2009-10-16 15:05:18 +0000452 /* This function is called when Btree p is concluding its
danielk1977404ca072009-03-16 13:19:36 +0000453 ** transaction. If there currently exists a writer, and p is not
454 ** that writer, then the number of locks held by connections other
455 ** than the writer must be about to drop to zero. In this case
drhc9166342012-01-05 23:32:06 +0000456 ** set the BTS_PENDING flag to 0.
danielk1977404ca072009-03-16 13:19:36 +0000457 **
drhc9166342012-01-05 23:32:06 +0000458 ** If there is not currently a writer, then BTS_PENDING must
danielk1977404ca072009-03-16 13:19:36 +0000459 ** be zero already. So this next line is harmless in that case.
460 */
drhc9166342012-01-05 23:32:06 +0000461 pBt->btsFlags &= ~BTS_PENDING;
danielk1977641b0f42007-12-21 04:47:25 +0000462 }
danielk1977aef0bf62005-12-30 16:28:01 +0000463}
danielk197794b30732009-07-02 17:21:57 +0000464
danielk1977e0d9e6f2009-07-03 16:25:06 +0000465/*
drh0ee3dbe2009-10-16 15:05:18 +0000466** This function changes all write-locks held by Btree p into read-locks.
danielk1977e0d9e6f2009-07-03 16:25:06 +0000467*/
danielk197794b30732009-07-02 17:21:57 +0000468static void downgradeAllSharedCacheTableLocks(Btree *p){
469 BtShared *pBt = p->pBt;
470 if( pBt->pWriter==p ){
471 BtLock *pLock;
472 pBt->pWriter = 0;
drhc9166342012-01-05 23:32:06 +0000473 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
danielk197794b30732009-07-02 17:21:57 +0000474 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
475 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
476 pLock->eLock = READ_LOCK;
477 }
478 }
479}
480
danielk1977aef0bf62005-12-30 16:28:01 +0000481#endif /* SQLITE_OMIT_SHARED_CACHE */
482
drh01be4632015-09-03 15:17:12 +0000483#ifndef SQLITE_OMIT_CONCURRENT
danf5cebf72015-08-22 17:28:55 +0000484/*
485** The following structure - BtreePtrmap - stores the in-memory pointer map
danbf3cf572015-08-24 19:56:04 +0000486** used for newly allocated pages in CONCURRENT transactions. Such pages are
danf5cebf72015-08-22 17:28:55 +0000487** always allocated in a contiguous block (from the end of the file) starting
488** with page BtreePtrmap.iFirst.
489*/
dan7b3d71e2015-08-19 20:27:05 +0000490typedef struct RollbackEntry RollbackEntry;
491typedef struct PtrmapEntry PtrmapEntry;
492struct PtrmapEntry {
493 Pgno parent;
494 u8 eType;
495};
496struct RollbackEntry {
497 Pgno pgno;
498 Pgno parent;
499 u8 eType;
500};
dan7b3d71e2015-08-19 20:27:05 +0000501struct BtreePtrmap {
502 Pgno iFirst; /* First new page number aPtr[0] */
503
504 int nPtrAlloc; /* Allocated size of aPtr[] array */
505 PtrmapEntry *aPtr; /* Array of parent page numbers */
506
507 int nSvpt; /* Used size of aSvpt[] array */
508 int nSvptAlloc; /* Allocated size of aSvpt[] */
509 int *aSvpt; /* First aRollback[] entry for savepoint i */
510
511 int nRollback; /* Used size of aRollback[] array */
512 int nRollbackAlloc; /* Allocated size of aRollback[] array */
513 RollbackEntry *aRollback; /* Array of rollback entries */
514};
515
drh01be4632015-09-03 15:17:12 +0000516/* !defined(SQLITE_OMIT_CONCURRENT)
517**
danf5cebf72015-08-22 17:28:55 +0000518** If page number pgno is greater than or equal to BtreePtrmap.iFirst,
519** store an entry for it in the pointer-map structure.
520*/
dan7b3d71e2015-08-19 20:27:05 +0000521static int btreePtrmapStore(
danf5cebf72015-08-22 17:28:55 +0000522 BtShared *pBt,
523 Pgno pgno,
dan7b3d71e2015-08-19 20:27:05 +0000524 u8 eType,
525 Pgno parent
526){
danf5cebf72015-08-22 17:28:55 +0000527 BtreePtrmap *pMap = pBt->pMap;
dan7b3d71e2015-08-19 20:27:05 +0000528 if( pgno>=pMap->iFirst ){
529 int iEntry = pgno - pMap->iFirst;
530
danf5cebf72015-08-22 17:28:55 +0000531 /* Grow the aPtr[] array as required */
532 while( iEntry>=pMap->nPtrAlloc ){
dan7b3d71e2015-08-19 20:27:05 +0000533 int nNew = pMap->nPtrAlloc ? pMap->nPtrAlloc*2 : 16;
534 PtrmapEntry *aNew = (PtrmapEntry*)sqlite3_realloc(
535 pMap->aPtr, nNew*sizeof(PtrmapEntry)
536 );
537 if( aNew==0 ){
538 return SQLITE_NOMEM;
539 }else{
540 int nByte = (nNew-pMap->nPtrAlloc)*sizeof(PtrmapEntry);
541 memset(&aNew[pMap->nPtrAlloc], 0, nByte);
542 pMap->aPtr = aNew;
543 pMap->nPtrAlloc = nNew;
544 }
545 }
546
547 /* Add an entry to the rollback log if required */
548 if( pMap->nSvpt>0 && pMap->aPtr[iEntry].parent ){
549 if( pMap->nRollback>=pMap->nRollbackAlloc ){
550 int nNew = pMap->nRollback ? pMap->nRollback*2 : 16;
551 RollbackEntry *aNew = (RollbackEntry*)sqlite3_realloc(
552 pMap->aRollback, nNew*sizeof(RollbackEntry)
553 );
554 if( aNew==0 ){
555 return SQLITE_NOMEM;
556 }else{
557 pMap->aRollback = aNew;
558 pMap->nRollbackAlloc = nNew;
559 }
560 }
561
562 pMap->aRollback[pMap->nRollback].pgno = pgno;
563 pMap->aRollback[pMap->nRollback].parent = pMap->aPtr[iEntry].parent;
564 pMap->aRollback[pMap->nRollback].eType = pMap->aPtr[iEntry].eType;
dan606f7182017-05-26 16:15:05 +0000565 pMap->nRollback++;
dan7b3d71e2015-08-19 20:27:05 +0000566 }
567
568 /* Update the aPtr[] array */
569 pMap->aPtr[iEntry].parent = parent;
570 pMap->aPtr[iEntry].eType = eType;
571 }
572
573 return SQLITE_OK;
574}
575
drh01be4632015-09-03 15:17:12 +0000576/* !defined(SQLITE_OMIT_CONCURRENT)
577**
dan7b3d71e2015-08-19 20:27:05 +0000578** Open savepoint iSavepoint, if it is not already open.
579*/
danf5cebf72015-08-22 17:28:55 +0000580static int btreePtrmapBegin(BtShared *pBt, int nSvpt){
581 BtreePtrmap *pMap = pBt->pMap;
dan606f7182017-05-26 16:15:05 +0000582 if( pMap && nSvpt>pMap->nSvpt ){
dan7b3d71e2015-08-19 20:27:05 +0000583 int i;
584 if( nSvpt>=pMap->nSvptAlloc ){
585 int nNew = pMap->nSvptAlloc ? pMap->nSvptAlloc*2 : 16;
586 int *aNew = sqlite3_realloc(pMap->aSvpt, sizeof(int) * nNew);
587 if( aNew==0 ){
588 return SQLITE_NOMEM;
589 }else{
590 pMap->aSvpt = aNew;
591 pMap->nSvptAlloc = nNew;
592 }
593 }
594
595 for(i=pMap->nSvpt; i<nSvpt; i++){
596 pMap->aSvpt[i] = pMap->nRollback;
597 }
598 pMap->nSvpt = nSvpt;
599 }
600
601 return SQLITE_OK;
602}
603
drh01be4632015-09-03 15:17:12 +0000604/* !defined(SQLITE_OMIT_CONCURRENT)
605**
dan7b3d71e2015-08-19 20:27:05 +0000606** Rollback (if op==SAVEPOINT_ROLLBACK) or release (if op==SAVEPOINT_RELEASE)
607** savepoint iSvpt.
608*/
danf5cebf72015-08-22 17:28:55 +0000609static void btreePtrmapEnd(BtShared *pBt, int op, int iSvpt){
610 BtreePtrmap *pMap = pBt->pMap;
611 if( pMap ){
612 assert( op==SAVEPOINT_ROLLBACK || op==SAVEPOINT_RELEASE );
613 assert( iSvpt>=0 || (iSvpt==-1 && op==SAVEPOINT_ROLLBACK) );
614 if( iSvpt<0 ){
615 pMap->nSvpt = 0;
616 pMap->nRollback = 0;
617 memset(pMap->aPtr, 0, sizeof(Pgno) * pMap->nPtrAlloc);
618 }else if( iSvpt<pMap->nSvpt ){
619 if( op==SAVEPOINT_ROLLBACK ){
620 int ii;
621 for(ii=pMap->nRollback-1; ii>=pMap->aSvpt[iSvpt]; ii--){
622 RollbackEntry *p = &pMap->aRollback[ii];
623 PtrmapEntry *pEntry = &pMap->aPtr[p->pgno - pMap->iFirst];
624 pEntry->parent = p->parent;
625 pEntry->eType = p->eType;
626 }
dan7b3d71e2015-08-19 20:27:05 +0000627 }
danf5cebf72015-08-22 17:28:55 +0000628 pMap->nSvpt = iSvpt + (op==SAVEPOINT_ROLLBACK);
629 pMap->nRollback = pMap->aSvpt[iSvpt];
dan7b3d71e2015-08-19 20:27:05 +0000630 }
dan7b3d71e2015-08-19 20:27:05 +0000631 }
632}
633
drh01be4632015-09-03 15:17:12 +0000634/* !defined(SQLITE_OMIT_CONCURRENT)
635**
danbf3cf572015-08-24 19:56:04 +0000636** This function is called after an CONCURRENT transaction is opened on the
danf5cebf72015-08-22 17:28:55 +0000637** database. It allocates the BtreePtrmap structure used to track pointers
638** to allocated pages and zeroes the nFree/iTrunk fields in the database
639** header on page 1.
640*/
641static int btreePtrmapAllocate(BtShared *pBt){
642 int rc = SQLITE_OK;
dan987f8212015-08-27 17:42:38 +0000643 if( pBt->pMap==0 ){
644 BtreePtrmap *pMap = sqlite3_malloc(sizeof(BtreePtrmap));
645 if( pMap==0 ){
646 rc = SQLITE_NOMEM;
647 }else{
648 memset(&pBt->pPage1->aData[32], 0, sizeof(u32)*2);
649 memset(pMap, 0, sizeof(BtreePtrmap));
650 pMap->iFirst = pBt->nPage + 1;
651 pBt->pMap = pMap;
652 }
danf5cebf72015-08-22 17:28:55 +0000653 }
654 return rc;
655}
656
drh01be4632015-09-03 15:17:12 +0000657/* !defined(SQLITE_OMIT_CONCURRENT)
658**
danf5cebf72015-08-22 17:28:55 +0000659** Free any BtreePtrmap structure allocated by an earlier call to
660** btreePtrmapAllocate().
661*/
662static void btreePtrmapDelete(BtShared *pBt){
663 BtreePtrmap *pMap = pBt->pMap;
664 if( pMap ){
665 sqlite3_free(pMap->aRollback);
666 sqlite3_free(pMap->aPtr);
667 sqlite3_free(pMap->aSvpt);
668 sqlite3_free(pMap);
669 pBt->pMap = 0;
670 }
671}
dan51883df2018-12-03 19:29:37 +0000672
673/*
674** Check that the pointer-map does not contain any entries with a parent
675** page of 0. Call sqlite3_log() multiple times to output the entire
676** data structure if it does.
677*/
678static void btreePtrmapCheck(BtShared *pBt, Pgno nPage){
679 Pgno i;
680 int bProblem = 0;
681 BtreePtrmap *p = pBt->pMap;
682
683 for(i=p->iFirst; i<=nPage; i++){
684 PtrmapEntry *pEntry = &p->aPtr[i-p->iFirst];
685 if( pEntry->eType==PTRMAP_OVERFLOW1
686 || pEntry->eType==PTRMAP_OVERFLOW2
687 || pEntry->eType==PTRMAP_BTREE
688 ){
689 if( pEntry->parent==0 ){
690 bProblem = 1;
691 break;
692 }
693 }
694 }
695
696 if( bProblem ){
697 for(i=p->iFirst; i<=nPage; i++){
698 PtrmapEntry *pEntry = &p->aPtr[i-p->iFirst];
699 sqlite3_log(SQLITE_CORRUPT,
700 "btreePtrmapCheck: pgno=%d eType=%d parent=%d",
701 (int)i, (int)pEntry->eType, (int)pEntry->parent
702 );
703 }
704 abort();
705 }
706}
707
drh01be4632015-09-03 15:17:12 +0000708#else /* SQLITE_OMIT_CONCURRENT */
danf5cebf72015-08-22 17:28:55 +0000709# define btreePtrmapAllocate(x) SQLITE_OK
710# define btreePtrmapDelete(x)
711# define btreePtrmapBegin(x,y) SQLITE_OK
712# define btreePtrmapEnd(x,y,z)
dan51883df2018-12-03 19:29:37 +0000713# define btreePtrmapCheck(y,z)
drh01be4632015-09-03 15:17:12 +0000714#endif /* SQLITE_OMIT_CONCURRENT */
dan7b3d71e2015-08-19 20:27:05 +0000715
drh980b1a72006-08-16 16:42:48 +0000716static void releasePage(MemPage *pPage); /* Forward reference */
drh3908fe92017-09-01 14:50:19 +0000717static void releasePageOne(MemPage *pPage); /* Forward reference */
drh352a35a2017-08-15 03:46:47 +0000718static void releasePageNotNull(MemPage *pPage); /* Forward reference */
drh980b1a72006-08-16 16:42:48 +0000719
drh1fee73e2007-08-29 04:00:57 +0000720/*
drh0ee3dbe2009-10-16 15:05:18 +0000721***** This routine is used inside of assert() only ****
722**
723** Verify that the cursor holds the mutex on its BtShared
drh1fee73e2007-08-29 04:00:57 +0000724*/
drh0ee3dbe2009-10-16 15:05:18 +0000725#ifdef SQLITE_DEBUG
drh1fee73e2007-08-29 04:00:57 +0000726static int cursorHoldsMutex(BtCursor *p){
drhff0587c2007-08-29 17:43:19 +0000727 return sqlite3_mutex_held(p->pBt->mutex);
drh1fee73e2007-08-29 04:00:57 +0000728}
drh5e08d0f2016-06-04 21:05:54 +0000729
730/* Verify that the cursor and the BtShared agree about what is the current
731** database connetion. This is important in shared-cache mode. If the database
732** connection pointers get out-of-sync, it is possible for routines like
733** btreeInitPage() to reference an stale connection pointer that references a
734** a connection that has already closed. This routine is used inside assert()
735** statements only and for the purpose of double-checking that the btree code
736** does keep the database connection pointers up-to-date.
737*/
dan7a2347e2016-01-07 16:43:54 +0000738static int cursorOwnsBtShared(BtCursor *p){
739 assert( cursorHoldsMutex(p) );
740 return (p->pBtree->db==p->pBt->db);
741}
drh1fee73e2007-08-29 04:00:57 +0000742#endif
743
danielk197792d4d7a2007-05-04 12:05:56 +0000744/*
dan5a500af2014-03-11 20:33:04 +0000745** Invalidate the overflow cache of the cursor passed as the first argument.
746** on the shared btree structure pBt.
danielk197792d4d7a2007-05-04 12:05:56 +0000747*/
drh036dbec2014-03-11 23:40:44 +0000748#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
danielk197792d4d7a2007-05-04 12:05:56 +0000749
750/*
751** Invalidate the overflow page-list cache for all cursors opened
752** on the shared btree structure pBt.
753*/
754static void invalidateAllOverflowCache(BtShared *pBt){
755 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000756 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +0000757 for(p=pBt->pCursor; p; p=p->pNext){
758 invalidateOverflowCache(p);
759 }
760}
danielk197796d48e92009-06-29 06:00:37 +0000761
dan5a500af2014-03-11 20:33:04 +0000762#ifndef SQLITE_OMIT_INCRBLOB
danielk197796d48e92009-06-29 06:00:37 +0000763/*
764** This function is called before modifying the contents of a table
drh0ee3dbe2009-10-16 15:05:18 +0000765** to invalidate any incrblob cursors that are open on the
drheeb844a2009-08-08 18:01:07 +0000766** row or one of the rows being modified.
danielk197796d48e92009-06-29 06:00:37 +0000767**
768** If argument isClearTable is true, then the entire contents of the
769** table is about to be deleted. In this case invalidate all incrblob
770** cursors open on any row within the table with root-page pgnoRoot.
771**
772** Otherwise, if argument isClearTable is false, then the row with
773** rowid iRow is being replaced or deleted. In this case invalidate
drh0ee3dbe2009-10-16 15:05:18 +0000774** only those incrblob cursors open on that specific row.
danielk197796d48e92009-06-29 06:00:37 +0000775*/
776static void invalidateIncrblobCursors(
777 Btree *pBtree, /* The database file to check */
drh9ca431a2017-03-29 18:03:50 +0000778 Pgno pgnoRoot, /* The table that might be changing */
danielk197796d48e92009-06-29 06:00:37 +0000779 i64 iRow, /* The rowid that might be changing */
780 int isClearTable /* True if all rows are being deleted */
781){
782 BtCursor *p;
drh49bb56e2021-05-14 20:01:36 +0000783 assert( pBtree->hasIncrblobCur );
danielk197796d48e92009-06-29 06:00:37 +0000784 assert( sqlite3BtreeHoldsMutex(pBtree) );
drh69180952015-06-25 13:03:10 +0000785 pBtree->hasIncrblobCur = 0;
786 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
787 if( (p->curFlags & BTCF_Incrblob)!=0 ){
788 pBtree->hasIncrblobCur = 1;
drh9ca431a2017-03-29 18:03:50 +0000789 if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
drh69180952015-06-25 13:03:10 +0000790 p->eState = CURSOR_INVALID;
791 }
danielk197796d48e92009-06-29 06:00:37 +0000792 }
793 }
794}
795
danielk197792d4d7a2007-05-04 12:05:56 +0000796#else
dan5a500af2014-03-11 20:33:04 +0000797 /* Stub function when INCRBLOB is omitted */
drh9ca431a2017-03-29 18:03:50 +0000798 #define invalidateIncrblobCursors(w,x,y,z)
drh0ee3dbe2009-10-16 15:05:18 +0000799#endif /* SQLITE_OMIT_INCRBLOB */
danielk197792d4d7a2007-05-04 12:05:56 +0000800
drh980b1a72006-08-16 16:42:48 +0000801/*
danielk1977bea2a942009-01-20 17:06:27 +0000802** Set bit pgno of the BtShared.pHasContent bitvec. This is called
803** when a page that previously contained data becomes a free-list leaf
804** page.
805**
806** The BtShared.pHasContent bitvec exists to work around an obscure
807** bug caused by the interaction of two useful IO optimizations surrounding
808** free-list leaf pages:
809**
810** 1) When all data is deleted from a page and the page becomes
811** a free-list leaf page, the page is not written to the database
812** (as free-list leaf pages contain no meaningful data). Sometimes
813** such a page is not even journalled (as it will not be modified,
814** why bother journalling it?).
815**
816** 2) When a free-list leaf page is reused, its content is not read
817** from the database or written to the journal file (why should it
818** be, if it is not at all meaningful?).
819**
820** By themselves, these optimizations work fine and provide a handy
821** performance boost to bulk delete or insert operations. However, if
822** a page is moved to the free-list and then reused within the same
823** transaction, a problem comes up. If the page is not journalled when
824** it is moved to the free-list and it is also not journalled when it
825** is extracted from the free-list and reused, then the original data
826** may be lost. In the event of a rollback, it may not be possible
827** to restore the database to its original configuration.
828**
829** The solution is the BtShared.pHasContent bitvec. Whenever a page is
830** moved to become a free-list leaf page, the corresponding bit is
831** set in the bitvec. Whenever a leaf page is extracted from the free-list,
drh0ee3dbe2009-10-16 15:05:18 +0000832** optimization 2 above is omitted if the corresponding bit is already
danielk1977bea2a942009-01-20 17:06:27 +0000833** set in BtShared.pHasContent. The contents of the bitvec are cleared
834** at the end of every transaction.
835*/
836static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
837 int rc = SQLITE_OK;
838 if( !pBt->pHasContent ){
drhdd3cd972010-03-27 17:12:36 +0000839 assert( pgno<=pBt->nPage );
840 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
drh4c301aa2009-07-15 17:25:45 +0000841 if( !pBt->pHasContent ){
mistachkinfad30392016-02-13 23:43:46 +0000842 rc = SQLITE_NOMEM_BKPT;
danielk1977bea2a942009-01-20 17:06:27 +0000843 }
844 }
845 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
846 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
847 }
848 return rc;
849}
850
851/*
852** Query the BtShared.pHasContent vector.
853**
854** This function is called when a free-list leaf page is removed from the
855** free-list for reuse. It returns false if it is safe to retrieve the
856** page from the pager layer with the 'no-content' flag set. True otherwise.
857*/
858static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
859 Bitvec *p = pBt->pHasContent;
pdrdb9cb172020-03-08 13:33:58 +0000860 return p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTestNotNull(p, pgno));
danielk1977bea2a942009-01-20 17:06:27 +0000861}
862
863/*
864** Clear (destroy) the BtShared.pHasContent bitvec. This should be
865** invoked at the conclusion of each write-transaction.
866*/
867static void btreeClearHasContent(BtShared *pBt){
868 sqlite3BitvecDestroy(pBt->pHasContent);
869 pBt->pHasContent = 0;
870}
871
872/*
drh138eeeb2013-03-27 03:15:23 +0000873** Release all of the apPage[] pages for a cursor.
874*/
875static void btreeReleaseAllCursorPages(BtCursor *pCur){
876 int i;
drh352a35a2017-08-15 03:46:47 +0000877 if( pCur->iPage>=0 ){
878 for(i=0; i<pCur->iPage; i++){
879 releasePageNotNull(pCur->apPage[i]);
880 }
881 releasePageNotNull(pCur->pPage);
882 pCur->iPage = -1;
drh138eeeb2013-03-27 03:15:23 +0000883 }
drh138eeeb2013-03-27 03:15:23 +0000884}
885
danf0ee1d32015-09-12 19:26:11 +0000886/*
887** The cursor passed as the only argument must point to a valid entry
888** when this function is called (i.e. have eState==CURSOR_VALID). This
889** function saves the current cursor key in variables pCur->nKey and
890** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
891** code otherwise.
892**
893** If the cursor is open on an intkey table, then the integer key
894** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
895** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
896** set to point to a malloced buffer pCur->nKey bytes in size containing
897** the key.
898*/
899static int saveCursorKey(BtCursor *pCur){
drha7c90c42016-06-04 20:37:10 +0000900 int rc = SQLITE_OK;
danf0ee1d32015-09-12 19:26:11 +0000901 assert( CURSOR_VALID==pCur->eState );
902 assert( 0==pCur->pKey );
903 assert( cursorHoldsMutex(pCur) );
904
drha7c90c42016-06-04 20:37:10 +0000905 if( pCur->curIntKey ){
906 /* Only the rowid is required for a table btree */
907 pCur->nKey = sqlite3BtreeIntegerKey(pCur);
908 }else{
danfffaf232018-12-14 13:18:35 +0000909 /* For an index btree, save the complete key content. It is possible
910 ** that the current key is corrupt. In that case, it is possible that
911 ** the sqlite3VdbeRecordUnpack() function may overread the buffer by
912 ** up to the size of 1 varint plus 1 8-byte value when the cursor
913 ** position is restored. Hence the 17 bytes of padding allocated
914 ** below. */
drhd66c4f82016-06-04 20:58:35 +0000915 void *pKey;
drha7c90c42016-06-04 20:37:10 +0000916 pCur->nKey = sqlite3BtreePayloadSize(pCur);
danfffaf232018-12-14 13:18:35 +0000917 pKey = sqlite3Malloc( pCur->nKey + 9 + 8 );
danf0ee1d32015-09-12 19:26:11 +0000918 if( pKey ){
drhcb3cabd2016-11-25 19:18:28 +0000919 rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
danf0ee1d32015-09-12 19:26:11 +0000920 if( rc==SQLITE_OK ){
drhe6c628e2019-01-21 16:01:17 +0000921 memset(((u8*)pKey)+pCur->nKey, 0, 9+8);
danf0ee1d32015-09-12 19:26:11 +0000922 pCur->pKey = pKey;
923 }else{
924 sqlite3_free(pKey);
925 }
926 }else{
mistachkinfad30392016-02-13 23:43:46 +0000927 rc = SQLITE_NOMEM_BKPT;
danf0ee1d32015-09-12 19:26:11 +0000928 }
929 }
930 assert( !pCur->curIntKey || !pCur->pKey );
931 return rc;
932}
drh138eeeb2013-03-27 03:15:23 +0000933
934/*
drh980b1a72006-08-16 16:42:48 +0000935** Save the current cursor position in the variables BtCursor.nKey
936** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
drhea8ffdf2009-07-22 00:35:23 +0000937**
938** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
939** prior to calling this routine.
drh980b1a72006-08-16 16:42:48 +0000940*/
941static int saveCursorPosition(BtCursor *pCur){
942 int rc;
943
drhd2f83132015-03-25 17:35:01 +0000944 assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
drh980b1a72006-08-16 16:42:48 +0000945 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000946 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000947
drh7b14b652019-12-29 22:08:20 +0000948 if( pCur->curFlags & BTCF_Pinned ){
949 return SQLITE_CONSTRAINT_PINNED;
950 }
drhd2f83132015-03-25 17:35:01 +0000951 if( pCur->eState==CURSOR_SKIPNEXT ){
952 pCur->eState = CURSOR_VALID;
953 }else{
954 pCur->skipNext = 0;
955 }
drh980b1a72006-08-16 16:42:48 +0000956
danf0ee1d32015-09-12 19:26:11 +0000957 rc = saveCursorKey(pCur);
drh980b1a72006-08-16 16:42:48 +0000958 if( rc==SQLITE_OK ){
drh138eeeb2013-03-27 03:15:23 +0000959 btreeReleaseAllCursorPages(pCur);
drh980b1a72006-08-16 16:42:48 +0000960 pCur->eState = CURSOR_REQUIRESEEK;
961 }
962
dane755e102015-09-30 12:59:12 +0000963 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
drh980b1a72006-08-16 16:42:48 +0000964 return rc;
965}
966
drh637f3d82014-08-22 22:26:07 +0000967/* Forward reference */
968static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
969
drh980b1a72006-08-16 16:42:48 +0000970/*
drh0ee3dbe2009-10-16 15:05:18 +0000971** Save the positions of all cursors (except pExcept) that are open on
drh637f3d82014-08-22 22:26:07 +0000972** the table with root-page iRoot. "Saving the cursor position" means that
973** the location in the btree is remembered in such a way that it can be
974** moved back to the same spot after the btree has been modified. This
975** routine is called just before cursor pExcept is used to modify the
976** table, for example in BtreeDelete() or BtreeInsert().
977**
drh27fb7462015-06-30 02:47:36 +0000978** If there are two or more cursors on the same btree, then all such
979** cursors should have their BTCF_Multiple flag set. The btreeCursor()
980** routine enforces that rule. This routine only needs to be called in
981** the uncommon case when pExpect has the BTCF_Multiple flag set.
982**
983** If pExpect!=NULL and if no other cursors are found on the same root-page,
984** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
985** pointless call to this routine.
986**
drh637f3d82014-08-22 22:26:07 +0000987** Implementation note: This routine merely checks to see if any cursors
988** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
989** event that cursors are in need to being saved.
drh980b1a72006-08-16 16:42:48 +0000990*/
991static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
drh3bdffdd2014-08-23 19:08:09 +0000992 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000993 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000994 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000995 for(p=pBt->pCursor; p; p=p->pNext){
drh637f3d82014-08-22 22:26:07 +0000996 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
997 }
drh27fb7462015-06-30 02:47:36 +0000998 if( p ) return saveCursorsOnList(p, iRoot, pExcept);
999 if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
1000 return SQLITE_OK;
drh637f3d82014-08-22 22:26:07 +00001001}
1002
1003/* This helper routine to saveAllCursors does the actual work of saving
1004** the cursors if and when a cursor is found that actually requires saving.
1005** The common case is that no cursors need to be saved, so this routine is
1006** broken out from its caller to avoid unnecessary stack pointer movement.
1007*/
1008static int SQLITE_NOINLINE saveCursorsOnList(
drh3f387402014-09-24 01:23:00 +00001009 BtCursor *p, /* The first cursor that needs saving */
1010 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
1011 BtCursor *pExcept /* Do not save this cursor */
drh637f3d82014-08-22 22:26:07 +00001012){
1013 do{
drh138eeeb2013-03-27 03:15:23 +00001014 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
drhd2f83132015-03-25 17:35:01 +00001015 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
drh138eeeb2013-03-27 03:15:23 +00001016 int rc = saveCursorPosition(p);
1017 if( SQLITE_OK!=rc ){
1018 return rc;
1019 }
1020 }else{
drh85ef6302017-08-02 15:50:09 +00001021 testcase( p->iPage>=0 );
drh138eeeb2013-03-27 03:15:23 +00001022 btreeReleaseAllCursorPages(p);
drh980b1a72006-08-16 16:42:48 +00001023 }
1024 }
drh637f3d82014-08-22 22:26:07 +00001025 p = p->pNext;
1026 }while( p );
drh980b1a72006-08-16 16:42:48 +00001027 return SQLITE_OK;
1028}
1029
1030/*
drhbf700f32007-03-31 02:36:44 +00001031** Clear the current cursor position.
1032*/
danielk1977be51a652008-10-08 17:58:48 +00001033void sqlite3BtreeClearCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00001034 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +00001035 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +00001036 pCur->pKey = 0;
1037 pCur->eState = CURSOR_INVALID;
1038}
1039
1040/*
danielk19773509a652009-07-06 18:56:13 +00001041** In this version of BtreeMoveto, pKey is a packed index record
1042** such as is generated by the OP_MakeRecord opcode. Unpack the
drheab10642022-03-06 20:22:24 +00001043** record and then call sqlite3BtreeIndexMoveto() to do the work.
danielk19773509a652009-07-06 18:56:13 +00001044*/
1045static int btreeMoveto(
1046 BtCursor *pCur, /* Cursor open on the btree to be searched */
1047 const void *pKey, /* Packed key if the btree is an index */
1048 i64 nKey, /* Integer key for tables. Size of pKey for indices */
1049 int bias, /* Bias search to the high end */
1050 int *pRes /* Write search results here */
1051){
1052 int rc; /* Status code */
1053 UnpackedRecord *pIdxKey; /* Unpacked index key */
danielk19773509a652009-07-06 18:56:13 +00001054
1055 if( pKey ){
danb0c4c942019-01-24 15:16:17 +00001056 KeyInfo *pKeyInfo = pCur->pKeyInfo;
danielk19773509a652009-07-06 18:56:13 +00001057 assert( nKey==(i64)(int)nKey );
danb0c4c942019-01-24 15:16:17 +00001058 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
mistachkinfad30392016-02-13 23:43:46 +00001059 if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
danb0c4c942019-01-24 15:16:17 +00001060 sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey);
1061 if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
mistachkin88a79732017-09-04 19:31:54 +00001062 rc = SQLITE_CORRUPT_BKPT;
drh42a410d2021-06-19 18:32:20 +00001063 }else{
1064 rc = sqlite3BtreeIndexMoveto(pCur, pIdxKey, pRes);
drh094b7582013-11-30 12:49:28 +00001065 }
drh42a410d2021-06-19 18:32:20 +00001066 sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
danielk19773509a652009-07-06 18:56:13 +00001067 }else{
1068 pIdxKey = 0;
drh42a410d2021-06-19 18:32:20 +00001069 rc = sqlite3BtreeTableMoveto(pCur, nKey, bias, pRes);
danielk19773509a652009-07-06 18:56:13 +00001070 }
1071 return rc;
1072}
1073
1074/*
drh980b1a72006-08-16 16:42:48 +00001075** Restore the cursor to the position it was in (or as close to as possible)
1076** when saveCursorPosition() was called. Note that this call deletes the
1077** saved position info stored by saveCursorPosition(), so there can be
drha3460582008-07-11 21:02:53 +00001078** at most one effective restoreCursorPosition() call after each
drh980b1a72006-08-16 16:42:48 +00001079** saveCursorPosition().
drh980b1a72006-08-16 16:42:48 +00001080*/
danielk197730548662009-07-09 05:07:37 +00001081static int btreeRestoreCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +00001082 int rc;
mistachkin4e2d3d42019-04-01 03:07:21 +00001083 int skipNext = 0;
dan7a2347e2016-01-07 16:43:54 +00001084 assert( cursorOwnsBtShared(pCur) );
drhfb982642007-08-30 01:19:59 +00001085 assert( pCur->eState>=CURSOR_REQUIRESEEK );
1086 if( pCur->eState==CURSOR_FAULT ){
drh4c301aa2009-07-15 17:25:45 +00001087 return pCur->skipNext;
drhfb982642007-08-30 01:19:59 +00001088 }
drh980b1a72006-08-16 16:42:48 +00001089 pCur->eState = CURSOR_INVALID;
drhb336d1a2019-03-30 19:17:35 +00001090 if( sqlite3FaultSim(410) ){
1091 rc = SQLITE_IOERR;
1092 }else{
1093 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
1094 }
drh980b1a72006-08-16 16:42:48 +00001095 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +00001096 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +00001097 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +00001098 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drh0c873bf2019-01-28 00:42:06 +00001099 if( skipNext ) pCur->skipNext = skipNext;
drh9b47ee32013-08-20 03:13:51 +00001100 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
1101 pCur->eState = CURSOR_SKIPNEXT;
1102 }
drh980b1a72006-08-16 16:42:48 +00001103 }
1104 return rc;
1105}
1106
drha3460582008-07-11 21:02:53 +00001107#define restoreCursorPosition(p) \
drhfb982642007-08-30 01:19:59 +00001108 (p->eState>=CURSOR_REQUIRESEEK ? \
danielk197730548662009-07-09 05:07:37 +00001109 btreeRestoreCursorPosition(p) : \
drh16a9b832007-05-05 18:39:25 +00001110 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +00001111
drha3460582008-07-11 21:02:53 +00001112/*
drh6848dad2014-08-22 23:33:03 +00001113** Determine whether or not a cursor has moved from the position where
1114** it was last placed, or has been invalidated for any other reason.
1115** Cursors can move when the row they are pointing at is deleted out
1116** from under them, for example. Cursor might also move if a btree
1117** is rebalanced.
drha3460582008-07-11 21:02:53 +00001118**
drh6848dad2014-08-22 23:33:03 +00001119** Calling this routine with a NULL cursor pointer returns false.
drh86dd3712014-03-25 11:00:21 +00001120**
drh6848dad2014-08-22 23:33:03 +00001121** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
1122** back to where it ought to be if this routine returns true.
drha3460582008-07-11 21:02:53 +00001123*/
drh6848dad2014-08-22 23:33:03 +00001124int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
drh5ba5f5b2018-06-02 16:32:04 +00001125 assert( EIGHT_BYTE_ALIGNMENT(pCur)
1126 || pCur==sqlite3BtreeFakeValidCursor() );
1127 assert( offsetof(BtCursor, eState)==0 );
1128 assert( sizeof(pCur->eState)==1 );
1129 return CURSOR_VALID != *(u8*)pCur;
drh6848dad2014-08-22 23:33:03 +00001130}
1131
1132/*
drhfe0cf7a2017-08-16 19:20:20 +00001133** Return a pointer to a fake BtCursor object that will always answer
1134** false to the sqlite3BtreeCursorHasMoved() routine above. The fake
1135** cursor returned must not be used with any other Btree interface.
1136*/
1137BtCursor *sqlite3BtreeFakeValidCursor(void){
1138 static u8 fakeCursor = CURSOR_VALID;
1139 assert( offsetof(BtCursor, eState)==0 );
1140 return (BtCursor*)&fakeCursor;
1141}
1142
1143/*
drh6848dad2014-08-22 23:33:03 +00001144** This routine restores a cursor back to its original position after it
1145** has been moved by some outside activity (such as a btree rebalance or
1146** a row having been deleted out from under the cursor).
1147**
1148** On success, the *pDifferentRow parameter is false if the cursor is left
1149** pointing at exactly the same row. *pDifferntRow is the row the cursor
1150** was pointing to has been deleted, forcing the cursor to point to some
1151** nearby row.
1152**
1153** This routine should only be called for a cursor that just returned
1154** TRUE from sqlite3BtreeCursorHasMoved().
1155*/
1156int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
drha3460582008-07-11 21:02:53 +00001157 int rc;
1158
drh6848dad2014-08-22 23:33:03 +00001159 assert( pCur!=0 );
1160 assert( pCur->eState!=CURSOR_VALID );
drha3460582008-07-11 21:02:53 +00001161 rc = restoreCursorPosition(pCur);
1162 if( rc ){
drh6848dad2014-08-22 23:33:03 +00001163 *pDifferentRow = 1;
drha3460582008-07-11 21:02:53 +00001164 return rc;
1165 }
drh606a3572015-03-25 18:29:10 +00001166 if( pCur->eState!=CURSOR_VALID ){
drh6848dad2014-08-22 23:33:03 +00001167 *pDifferentRow = 1;
drha3460582008-07-11 21:02:53 +00001168 }else{
drh6848dad2014-08-22 23:33:03 +00001169 *pDifferentRow = 0;
drha3460582008-07-11 21:02:53 +00001170 }
1171 return SQLITE_OK;
1172}
1173
drhf7854c72015-10-27 13:24:37 +00001174#ifdef SQLITE_ENABLE_CURSOR_HINTS
drh28935362013-12-07 20:39:19 +00001175/*
drh0df57012015-08-14 15:05:55 +00001176** Provide hints to the cursor. The particular hint given (and the type
1177** and number of the varargs parameters) is determined by the eHintType
1178** parameter. See the definitions of the BTREE_HINT_* macros for details.
drh28935362013-12-07 20:39:19 +00001179*/
drh0df57012015-08-14 15:05:55 +00001180void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
drhf7854c72015-10-27 13:24:37 +00001181 /* Used only by system that substitute their own storage engine */
drh28935362013-12-07 20:39:19 +00001182}
drhf7854c72015-10-27 13:24:37 +00001183#endif
1184
1185/*
1186** Provide flag hints to the cursor.
1187*/
1188void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
1189 assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
1190 pCur->hints = x;
1191}
1192
drh28935362013-12-07 20:39:19 +00001193
danielk1977599fcba2004-11-08 07:13:13 +00001194#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +00001195/*
drha3152892007-05-05 11:48:52 +00001196** Given a page number of a regular database page, return the page
1197** number for the pointer-map page that contains the entry for the
1198** input page number.
drh5f77b2e2010-08-21 15:09:37 +00001199**
1200** Return 0 (not a valid page) for pgno==1 since there is
1201** no pointer map associated with page 1. The integrity_check logic
1202** requires that ptrmapPageno(*,1)!=1.
danielk1977afcdd022004-10-31 16:25:42 +00001203*/
danielk1977266664d2006-02-10 08:24:21 +00001204static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
danielk197789d40042008-11-17 14:20:56 +00001205 int nPagesPerMapPage;
1206 Pgno iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +00001207 assert( sqlite3_mutex_held(pBt->mutex) );
drh5f77b2e2010-08-21 15:09:37 +00001208 if( pgno<2 ) return 0;
drhd677b3d2007-08-20 22:48:41 +00001209 nPagesPerMapPage = (pBt->usableSize/5)+1;
1210 iPtrMap = (pgno-2)/nPagesPerMapPage;
1211 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +00001212 if( ret==PENDING_BYTE_PAGE(pBt) ){
1213 ret++;
1214 }
1215 return ret;
1216}
danielk1977a19df672004-11-03 11:37:07 +00001217
danielk1977afcdd022004-10-31 16:25:42 +00001218/*
danielk1977afcdd022004-10-31 16:25:42 +00001219** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +00001220**
1221** This routine updates the pointer map entry for page number 'key'
1222** so that it maps to type 'eType' and parent page number 'pgno'.
drh98add2e2009-07-20 17:11:49 +00001223**
1224** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
1225** a no-op. If an error occurs, the appropriate error code is written
1226** into *pRC.
danielk1977afcdd022004-10-31 16:25:42 +00001227*/
drh98add2e2009-07-20 17:11:49 +00001228static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
danielk19773b8a05f2007-03-19 17:44:26 +00001229 DbPage *pDbPage; /* The pointer map page */
1230 u8 *pPtrmap; /* The pointer map data */
1231 Pgno iPtrmap; /* The pointer map page number */
1232 int offset; /* Offset in pointer map page */
drh98add2e2009-07-20 17:11:49 +00001233 int rc; /* Return code from subfunctions */
1234
1235 if( *pRC ) return;
danielk1977afcdd022004-10-31 16:25:42 +00001236
danf5cebf72015-08-22 17:28:55 +00001237 assert( sqlite3_mutex_held(pBt->mutex) );
drh067b92b2020-06-19 15:24:12 +00001238 /* The super-journal page number must never be used as a pointer map page */
danf5cebf72015-08-22 17:28:55 +00001239 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
1240
drh01be4632015-09-03 15:17:12 +00001241#ifndef SQLITE_OMIT_CONCURRENT
dan7b3d71e2015-08-19 20:27:05 +00001242 if( pBt->pMap ){
danf5cebf72015-08-22 17:28:55 +00001243 *pRC = btreePtrmapStore(pBt, key, eType, parent);
1244 return;
dan7b3d71e2015-08-19 20:27:05 +00001245 }
danf5cebf72015-08-22 17:28:55 +00001246#endif
1247
1248 assert( pBt->autoVacuum );
1249 if( key==0 ){
1250 *pRC = SQLITE_CORRUPT_BKPT;
1251 return;
1252 }
1253 iPtrmap = PTRMAP_PAGENO(pBt, key);
drh9584f582015-11-04 20:22:37 +00001254 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
danf5cebf72015-08-22 17:28:55 +00001255 if( rc!=SQLITE_OK ){
1256 *pRC = rc;
1257 return;
1258 }
drh203b1ea2018-12-14 03:14:18 +00001259 if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){
1260 /* The first byte of the extra data is the MemPage.isInit byte.
1261 ** If that byte is set, it means this page is also being used
1262 ** as a btree page. */
1263 *pRC = SQLITE_CORRUPT_BKPT;
1264 goto ptrmap_exit;
1265 }
danf5cebf72015-08-22 17:28:55 +00001266 offset = PTRMAP_PTROFFSET(iPtrmap, key);
1267 if( offset<0 ){
1268 *pRC = SQLITE_CORRUPT_BKPT;
1269 goto ptrmap_exit;
1270 }
1271 assert( offset <= (int)pBt->usableSize-5 );
1272 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1273
1274 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
1275 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
1276 *pRC= rc = sqlite3PagerWrite(pDbPage);
1277 if( rc==SQLITE_OK ){
1278 pPtrmap[offset] = eType;
1279 put4byte(&pPtrmap[offset+1], parent);
1280 }
1281 }
1282
1283ptrmap_exit:
1284 sqlite3PagerUnref(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +00001285}
1286
1287/*
1288** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +00001289**
1290** This routine retrieves the pointer map entry for page 'key', writing
1291** the type and parent page number to *pEType and *pPgno respectively.
1292** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +00001293*/
danielk1977aef0bf62005-12-30 16:28:01 +00001294static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +00001295 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +00001296 int iPtrmap; /* Pointer map page index */
1297 u8 *pPtrmap; /* Pointer map page data */
1298 int offset; /* Offset of entry in pointer map */
1299 int rc;
1300
drh1fee73e2007-08-29 04:00:57 +00001301 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001302
danielk1977266664d2006-02-10 08:24:21 +00001303 iPtrmap = PTRMAP_PAGENO(pBt, key);
drh9584f582015-11-04 20:22:37 +00001304 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00001305 if( rc!=0 ){
1306 return rc;
1307 }
danielk19773b8a05f2007-03-19 17:44:26 +00001308 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +00001309
danielk19778c666b12008-07-18 09:34:57 +00001310 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drhfc243732011-05-17 15:21:56 +00001311 if( offset<0 ){
1312 sqlite3PagerUnref(pDbPage);
1313 return SQLITE_CORRUPT_BKPT;
1314 }
1315 assert( offset <= (int)pBt->usableSize-5 );
drh43617e92006-03-06 20:55:46 +00001316 assert( pEType!=0 );
1317 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +00001318 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +00001319
danielk19773b8a05f2007-03-19 17:44:26 +00001320 sqlite3PagerUnref(pDbPage);
drhcc97ca42017-06-07 22:32:59 +00001321 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
danielk1977afcdd022004-10-31 16:25:42 +00001322 return SQLITE_OK;
1323}
1324
danielk197785d90ca2008-07-19 14:25:15 +00001325#else /* if defined SQLITE_OMIT_AUTOVACUUM */
drh98add2e2009-07-20 17:11:49 +00001326 #define ptrmapPut(w,x,y,z,rc)
danielk197785d90ca2008-07-19 14:25:15 +00001327 #define ptrmapGet(w,x,y,z) SQLITE_OK
drh0f1bf4c2019-01-13 20:17:21 +00001328 #define ptrmapPutOvflPtr(x, y, z, rc)
danielk197785d90ca2008-07-19 14:25:15 +00001329#endif
danielk1977afcdd022004-10-31 16:25:42 +00001330
drh0d316a42002-08-11 20:10:47 +00001331/*
drh271efa52004-05-30 19:19:05 +00001332** Given a btree page and a cell index (0 means the first cell on
1333** the page, 1 means the second cell, and so forth) return a pointer
1334** to the cell content.
1335**
drhf44890a2015-06-27 03:58:15 +00001336** findCellPastPtr() does the same except it skips past the initial
1337** 4-byte child pointer found on interior pages, if there is one.
1338**
drh271efa52004-05-30 19:19:05 +00001339** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +00001340*/
drh1688c862008-07-18 02:44:17 +00001341#define findCell(P,I) \
drh329428e2015-06-30 13:28:18 +00001342 ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
drhf44890a2015-06-27 03:58:15 +00001343#define findCellPastPtr(P,I) \
drh329428e2015-06-30 13:28:18 +00001344 ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
drhf44890a2015-06-27 03:58:15 +00001345
drh68f2a572011-06-03 17:50:49 +00001346
drh43605152004-05-29 21:46:49 +00001347/*
drh5fa60512015-06-19 17:19:34 +00001348** This is common tail processing for btreeParseCellPtr() and
1349** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
1350** on a single B-tree page. Make necessary adjustments to the CellInfo
1351** structure.
drh43605152004-05-29 21:46:49 +00001352*/
drh5fa60512015-06-19 17:19:34 +00001353static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
1354 MemPage *pPage, /* Page containing the cell */
1355 u8 *pCell, /* Pointer to the cell text. */
1356 CellInfo *pInfo /* Fill in this structure */
1357){
1358 /* If the payload will not fit completely on the local page, we have
1359 ** to decide how much to store locally and how much to spill onto
1360 ** overflow pages. The strategy is to minimize the amount of unused
1361 ** space on overflow pages while keeping the amount of local storage
1362 ** in between minLocal and maxLocal.
1363 **
1364 ** Warning: changing the way overflow payload is distributed in any
1365 ** way will result in an incompatible file format.
1366 */
1367 int minLocal; /* Minimum amount of payload held locally */
1368 int maxLocal; /* Maximum amount of payload held locally */
1369 int surplus; /* Overflow payload available for local storage */
1370
1371 minLocal = pPage->minLocal;
1372 maxLocal = pPage->maxLocal;
1373 surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
1374 testcase( surplus==maxLocal );
1375 testcase( surplus==maxLocal+1 );
1376 if( surplus <= maxLocal ){
1377 pInfo->nLocal = (u16)surplus;
1378 }else{
1379 pInfo->nLocal = (u16)minLocal;
1380 }
drh45ac1c72015-12-18 03:59:16 +00001381 pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
drh5fa60512015-06-19 17:19:34 +00001382}
1383
1384/*
danebbf3682020-12-09 16:32:11 +00001385** Given a record with nPayload bytes of payload stored within btree
1386** page pPage, return the number of bytes of payload stored locally.
1387*/
dan59964b42020-12-14 15:25:14 +00001388static int btreePayloadToLocal(MemPage *pPage, i64 nPayload){
danebbf3682020-12-09 16:32:11 +00001389 int maxLocal; /* Maximum amount of payload held locally */
1390 maxLocal = pPage->maxLocal;
1391 if( nPayload<=maxLocal ){
1392 return nPayload;
1393 }else{
1394 int minLocal; /* Minimum amount of payload held locally */
1395 int surplus; /* Overflow payload available for local storage */
1396 minLocal = pPage->minLocal;
1397 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize-4);
1398 return ( surplus <= maxLocal ) ? surplus : minLocal;
1399 }
1400}
1401
1402/*
drh5fa60512015-06-19 17:19:34 +00001403** The following routines are implementations of the MemPage.xParseCell()
1404** method.
1405**
1406** Parse a cell content block and fill in the CellInfo structure.
1407**
1408** btreeParseCellPtr() => table btree leaf nodes
1409** btreeParseCellNoPayload() => table btree internal nodes
1410** btreeParseCellPtrIndex() => index btree nodes
1411**
1412** There is also a wrapper function btreeParseCell() that works for
1413** all MemPage types and that references the cell by index rather than
1414** by pointer.
1415*/
1416static void btreeParseCellPtrNoPayload(
1417 MemPage *pPage, /* Page containing the cell */
1418 u8 *pCell, /* Pointer to the cell text. */
1419 CellInfo *pInfo /* Fill in this structure */
1420){
1421 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1422 assert( pPage->leaf==0 );
drh5fa60512015-06-19 17:19:34 +00001423 assert( pPage->childPtrSize==4 );
drh94a31152015-07-01 04:08:40 +00001424#ifndef SQLITE_DEBUG
1425 UNUSED_PARAMETER(pPage);
1426#endif
drh5fa60512015-06-19 17:19:34 +00001427 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
1428 pInfo->nPayload = 0;
1429 pInfo->nLocal = 0;
drh5fa60512015-06-19 17:19:34 +00001430 pInfo->pPayload = 0;
1431 return;
1432}
danielk197730548662009-07-09 05:07:37 +00001433static void btreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +00001434 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +00001435 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +00001436 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +00001437){
drh3e28ff52014-09-24 00:59:08 +00001438 u8 *pIter; /* For scanning through pCell */
drh271efa52004-05-30 19:19:05 +00001439 u32 nPayload; /* Number of bytes of cell payload */
drh56cb04e2015-06-19 18:24:37 +00001440 u64 iKey; /* Extracted Key value */
drh43605152004-05-29 21:46:49 +00001441
drh1fee73e2007-08-29 04:00:57 +00001442 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhab01f612004-05-22 02:55:23 +00001443 assert( pPage->leaf==0 || pPage->leaf==1 );
drh5fa60512015-06-19 17:19:34 +00001444 assert( pPage->intKeyLeaf );
1445 assert( pPage->childPtrSize==0 );
drh56cb04e2015-06-19 18:24:37 +00001446 pIter = pCell;
1447
1448 /* The next block of code is equivalent to:
1449 **
1450 ** pIter += getVarint32(pIter, nPayload);
1451 **
1452 ** The code is inlined to avoid a function call.
1453 */
1454 nPayload = *pIter;
1455 if( nPayload>=0x80 ){
drheeab2c62015-06-19 20:08:39 +00001456 u8 *pEnd = &pIter[8];
drh56cb04e2015-06-19 18:24:37 +00001457 nPayload &= 0x7f;
1458 do{
1459 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1460 }while( (*pIter)>=0x80 && pIter<pEnd );
1461 }
1462 pIter++;
1463
1464 /* The next block of code is equivalent to:
1465 **
1466 ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
1467 **
drh29bbc2b2022-01-02 16:48:00 +00001468 ** The code is inlined and the loop is unrolled for performance.
1469 ** This routine is a high-runner.
drh56cb04e2015-06-19 18:24:37 +00001470 */
1471 iKey = *pIter;
1472 if( iKey>=0x80 ){
drh29bbc2b2022-01-02 16:48:00 +00001473 u8 x;
1474 iKey = ((iKey&0x7f)<<7) | ((x = *++pIter) & 0x7f);
1475 if( x>=0x80 ){
1476 iKey = (iKey<<7) | ((x =*++pIter) & 0x7f);
1477 if( x>=0x80 ){
1478 iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
1479 if( x>=0x80 ){
1480 iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
1481 if( x>=0x80 ){
1482 iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
1483 if( x>=0x80 ){
1484 iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
1485 if( x>=0x80 ){
1486 iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
1487 if( x>=0x80 ){
1488 iKey = (iKey<<8) | (*++pIter);
1489 }
1490 }
1491 }
1492 }
1493 }
drh56cb04e2015-06-19 18:24:37 +00001494 }
1495 }
1496 }
1497 pIter++;
1498
1499 pInfo->nKey = *(i64*)&iKey;
drh72365832007-03-06 15:53:44 +00001500 pInfo->nPayload = nPayload;
drhab1cc582014-09-23 21:25:19 +00001501 pInfo->pPayload = pIter;
drh0a45c272009-07-08 01:49:11 +00001502 testcase( nPayload==pPage->maxLocal );
mistachkin2b5fbb22021-12-31 18:26:50 +00001503 testcase( nPayload==(u32)pPage->maxLocal+1 );
drhab1cc582014-09-23 21:25:19 +00001504 if( nPayload<=pPage->maxLocal ){
drh271efa52004-05-30 19:19:05 +00001505 /* This is the (easy) common case where the entire payload fits
1506 ** on the local page. No overflow is required.
1507 */
drhab1cc582014-09-23 21:25:19 +00001508 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1509 if( pInfo->nSize<4 ) pInfo->nSize = 4;
drhf49661a2008-12-10 16:45:50 +00001510 pInfo->nLocal = (u16)nPayload;
drh6f11bef2004-05-13 01:12:56 +00001511 }else{
drh5fa60512015-06-19 17:19:34 +00001512 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1513 }
1514}
1515static void btreeParseCellPtrIndex(
1516 MemPage *pPage, /* Page containing the cell */
1517 u8 *pCell, /* Pointer to the cell text. */
1518 CellInfo *pInfo /* Fill in this structure */
1519){
1520 u8 *pIter; /* For scanning through pCell */
1521 u32 nPayload; /* Number of bytes of cell payload */
drh271efa52004-05-30 19:19:05 +00001522
drh5fa60512015-06-19 17:19:34 +00001523 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1524 assert( pPage->leaf==0 || pPage->leaf==1 );
1525 assert( pPage->intKeyLeaf==0 );
drh5fa60512015-06-19 17:19:34 +00001526 pIter = pCell + pPage->childPtrSize;
1527 nPayload = *pIter;
1528 if( nPayload>=0x80 ){
drheeab2c62015-06-19 20:08:39 +00001529 u8 *pEnd = &pIter[8];
drh5fa60512015-06-19 17:19:34 +00001530 nPayload &= 0x7f;
1531 do{
1532 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1533 }while( *(pIter)>=0x80 && pIter<pEnd );
1534 }
1535 pIter++;
1536 pInfo->nKey = nPayload;
1537 pInfo->nPayload = nPayload;
1538 pInfo->pPayload = pIter;
1539 testcase( nPayload==pPage->maxLocal );
mistachkin2b5fbb22021-12-31 18:26:50 +00001540 testcase( nPayload==(u32)pPage->maxLocal+1 );
drh5fa60512015-06-19 17:19:34 +00001541 if( nPayload<=pPage->maxLocal ){
1542 /* This is the (easy) common case where the entire payload fits
1543 ** on the local page. No overflow is required.
1544 */
1545 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1546 if( pInfo->nSize<4 ) pInfo->nSize = 4;
1547 pInfo->nLocal = (u16)nPayload;
drh5fa60512015-06-19 17:19:34 +00001548 }else{
1549 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
drh6f11bef2004-05-13 01:12:56 +00001550 }
drh3aac2dd2004-04-26 14:10:20 +00001551}
danielk197730548662009-07-09 05:07:37 +00001552static void btreeParseCell(
drh43605152004-05-29 21:46:49 +00001553 MemPage *pPage, /* Page containing the cell */
1554 int iCell, /* The cell index. First cell is 0 */
1555 CellInfo *pInfo /* Fill in this structure */
1556){
drh5fa60512015-06-19 17:19:34 +00001557 pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
drh43605152004-05-29 21:46:49 +00001558}
drh3aac2dd2004-04-26 14:10:20 +00001559
1560/*
drh5fa60512015-06-19 17:19:34 +00001561** The following routines are implementations of the MemPage.xCellSize
1562** method.
1563**
drh43605152004-05-29 21:46:49 +00001564** Compute the total number of bytes that a Cell needs in the cell
1565** data area of the btree-page. The return number includes the cell
1566** data header and the local payload, but not any overflow page or
1567** the space used by the cell pointer.
drh25ada072015-06-19 15:07:14 +00001568**
drh5fa60512015-06-19 17:19:34 +00001569** cellSizePtrNoPayload() => table internal nodes
drh19ae01b2022-02-23 22:56:10 +00001570** cellSizePtrTableLeaf() => table leaf nodes
drh5fa60512015-06-19 17:19:34 +00001571** cellSizePtr() => all index nodes & table leaf nodes
drh3b7511c2001-05-26 13:15:44 +00001572*/
danielk1977ae5558b2009-04-29 11:31:47 +00001573static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
drh3f387402014-09-24 01:23:00 +00001574 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
1575 u8 *pEnd; /* End mark for a varint */
1576 u32 nSize; /* Size value to return */
danielk1977ae5558b2009-04-29 11:31:47 +00001577
1578#ifdef SQLITE_DEBUG
1579 /* The value returned by this function should always be the same as
1580 ** the (CellInfo.nSize) value found by doing a full parse of the
1581 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1582 ** this function verifies that this invariant is not violated. */
1583 CellInfo debuginfo;
drh5fa60512015-06-19 17:19:34 +00001584 pPage->xParseCell(pPage, pCell, &debuginfo);
danielk1977ae5558b2009-04-29 11:31:47 +00001585#endif
1586
drh3e28ff52014-09-24 00:59:08 +00001587 nSize = *pIter;
1588 if( nSize>=0x80 ){
drheeab2c62015-06-19 20:08:39 +00001589 pEnd = &pIter[8];
drh3e28ff52014-09-24 00:59:08 +00001590 nSize &= 0x7f;
1591 do{
1592 nSize = (nSize<<7) | (*++pIter & 0x7f);
1593 }while( *(pIter)>=0x80 && pIter<pEnd );
1594 }
1595 pIter++;
drh0a45c272009-07-08 01:49:11 +00001596 testcase( nSize==pPage->maxLocal );
mistachkin2b5fbb22021-12-31 18:26:50 +00001597 testcase( nSize==(u32)pPage->maxLocal+1 );
drh3e28ff52014-09-24 00:59:08 +00001598 if( nSize<=pPage->maxLocal ){
1599 nSize += (u32)(pIter - pCell);
1600 if( nSize<4 ) nSize = 4;
1601 }else{
danielk1977ae5558b2009-04-29 11:31:47 +00001602 int minLocal = pPage->minLocal;
1603 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
drh0a45c272009-07-08 01:49:11 +00001604 testcase( nSize==pPage->maxLocal );
mistachkin2b5fbb22021-12-31 18:26:50 +00001605 testcase( nSize==(u32)pPage->maxLocal+1 );
danielk1977ae5558b2009-04-29 11:31:47 +00001606 if( nSize>pPage->maxLocal ){
1607 nSize = minLocal;
1608 }
drh3e28ff52014-09-24 00:59:08 +00001609 nSize += 4 + (u16)(pIter - pCell);
danielk1977ae5558b2009-04-29 11:31:47 +00001610 }
drhdc41d602014-09-22 19:51:35 +00001611 assert( nSize==debuginfo.nSize || CORRUPT_DB );
shane60a4b532009-05-06 18:57:09 +00001612 return (u16)nSize;
danielk1977ae5558b2009-04-29 11:31:47 +00001613}
drh25ada072015-06-19 15:07:14 +00001614static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
1615 u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
1616 u8 *pEnd; /* End mark for a varint */
1617
1618#ifdef SQLITE_DEBUG
1619 /* The value returned by this function should always be the same as
1620 ** the (CellInfo.nSize) value found by doing a full parse of the
1621 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1622 ** this function verifies that this invariant is not violated. */
1623 CellInfo debuginfo;
drh5fa60512015-06-19 17:19:34 +00001624 pPage->xParseCell(pPage, pCell, &debuginfo);
drh94a31152015-07-01 04:08:40 +00001625#else
1626 UNUSED_PARAMETER(pPage);
drh25ada072015-06-19 15:07:14 +00001627#endif
1628
1629 assert( pPage->childPtrSize==4 );
1630 pEnd = pIter + 9;
1631 while( (*pIter++)&0x80 && pIter<pEnd );
1632 assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
1633 return (u16)(pIter - pCell);
1634}
drh19ae01b2022-02-23 22:56:10 +00001635static u16 cellSizePtrTableLeaf(MemPage *pPage, u8 *pCell){
1636 u8 *pIter = pCell; /* For looping over bytes of pCell */
1637 u8 *pEnd; /* End mark for a varint */
1638 u32 nSize; /* Size value to return */
1639
1640#ifdef SQLITE_DEBUG
1641 /* The value returned by this function should always be the same as
1642 ** the (CellInfo.nSize) value found by doing a full parse of the
1643 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1644 ** this function verifies that this invariant is not violated. */
1645 CellInfo debuginfo;
1646 pPage->xParseCell(pPage, pCell, &debuginfo);
1647#endif
1648
1649 nSize = *pIter;
1650 if( nSize>=0x80 ){
1651 pEnd = &pIter[8];
1652 nSize &= 0x7f;
1653 do{
1654 nSize = (nSize<<7) | (*++pIter & 0x7f);
1655 }while( *(pIter)>=0x80 && pIter<pEnd );
1656 }
1657 pIter++;
1658 /* pIter now points at the 64-bit integer key value, a variable length
1659 ** integer. The following block moves pIter to point at the first byte
1660 ** past the end of the key value. */
1661 if( (*pIter++)&0x80
1662 && (*pIter++)&0x80
1663 && (*pIter++)&0x80
1664 && (*pIter++)&0x80
1665 && (*pIter++)&0x80
1666 && (*pIter++)&0x80
1667 && (*pIter++)&0x80
1668 && (*pIter++)&0x80 ){ pIter++; }
1669 testcase( nSize==pPage->maxLocal );
1670 testcase( nSize==(u32)pPage->maxLocal+1 );
1671 if( nSize<=pPage->maxLocal ){
1672 nSize += (u32)(pIter - pCell);
1673 if( nSize<4 ) nSize = 4;
1674 }else{
1675 int minLocal = pPage->minLocal;
1676 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1677 testcase( nSize==pPage->maxLocal );
1678 testcase( nSize==(u32)pPage->maxLocal+1 );
1679 if( nSize>pPage->maxLocal ){
1680 nSize = minLocal;
1681 }
1682 nSize += 4 + (u16)(pIter - pCell);
1683 }
1684 assert( nSize==debuginfo.nSize || CORRUPT_DB );
1685 return (u16)nSize;
1686}
drh25ada072015-06-19 15:07:14 +00001687
drh0ee3dbe2009-10-16 15:05:18 +00001688
1689#ifdef SQLITE_DEBUG
1690/* This variation on cellSizePtr() is used inside of assert() statements
1691** only. */
drha9121e42008-02-19 14:59:35 +00001692static u16 cellSize(MemPage *pPage, int iCell){
drh25ada072015-06-19 15:07:14 +00001693 return pPage->xCellSize(pPage, findCell(pPage, iCell));
drh43605152004-05-29 21:46:49 +00001694}
danielk1977bc6ada42004-06-30 08:20:16 +00001695#endif
drh3b7511c2001-05-26 13:15:44 +00001696
danielk197779a40da2005-01-16 08:00:01 +00001697#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +00001698/*
drh0f1bf4c2019-01-13 20:17:21 +00001699** The cell pCell is currently part of page pSrc but will ultimately be part
drh3b4cb712022-03-01 19:19:20 +00001700** of pPage. (pSrc and pPage are often the same.) If pCell contains a
drh0f1bf4c2019-01-13 20:17:21 +00001701** pointer to an overflow page, insert an entry into the pointer-map for
1702** the overflow page that will be valid after pCell has been moved to pPage.
danielk1977ac11ee62005-01-15 12:45:51 +00001703*/
drh0f1bf4c2019-01-13 20:17:21 +00001704static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){
drhfa67c3c2008-07-11 02:21:40 +00001705 CellInfo info;
drh98add2e2009-07-20 17:11:49 +00001706 if( *pRC ) return;
drhfa67c3c2008-07-11 02:21:40 +00001707 assert( pCell!=0 );
drh5fa60512015-06-19 17:19:34 +00001708 pPage->xParseCell(pPage, pCell, &info);
drh45ac1c72015-12-18 03:59:16 +00001709 if( info.nLocal<info.nPayload ){
drhe7acce62018-12-14 16:00:38 +00001710 Pgno ovfl;
drh0f1bf4c2019-01-13 20:17:21 +00001711 if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
1712 testcase( pSrc!=pPage );
drhe7acce62018-12-14 16:00:38 +00001713 *pRC = SQLITE_CORRUPT_BKPT;
1714 return;
1715 }
1716 ovfl = get4byte(&pCell[info.nSize-4]);
drh98add2e2009-07-20 17:11:49 +00001717 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
danielk1977ac11ee62005-01-15 12:45:51 +00001718 }
danielk1977ac11ee62005-01-15 12:45:51 +00001719}
danielk197779a40da2005-01-16 08:00:01 +00001720#endif
1721
danielk1977ac11ee62005-01-15 12:45:51 +00001722
drhda200cc2004-05-09 11:51:38 +00001723/*
dane6d065a2017-02-24 19:58:22 +00001724** Defragment the page given. This routine reorganizes cells within the
1725** page so that there are no free-blocks on the free-block list.
1726**
1727** Parameter nMaxFrag is the maximum amount of fragmented space that may be
1728** present in the page after this routine returns.
drhfdab0262014-11-20 15:30:50 +00001729**
1730** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
1731** b-tree page so that there are no freeblocks or fragment bytes, all
1732** unused bytes are contained in the unallocated space region, and all
1733** cells are packed tightly at the end of the page.
drh365d68f2001-05-11 11:02:46 +00001734*/
dane6d065a2017-02-24 19:58:22 +00001735static int defragmentPage(MemPage *pPage, int nMaxFrag){
drh43605152004-05-29 21:46:49 +00001736 int i; /* Loop counter */
peter.d.reid60ec9142014-09-06 16:39:46 +00001737 int pc; /* Address of the i-th cell */
drh43605152004-05-29 21:46:49 +00001738 int hdr; /* Offset to the page header */
1739 int size; /* Size of a cell */
1740 int usableSize; /* Number of usable bytes on a page */
1741 int cellOffset; /* Offset to the cell pointer array */
drh281b21d2008-08-22 12:57:08 +00001742 int cbrk; /* Offset to the cell content area */
drh43605152004-05-29 21:46:49 +00001743 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +00001744 unsigned char *data; /* The page data */
1745 unsigned char *temp; /* Temp area for cell content */
drh588400b2014-09-27 05:00:25 +00001746 unsigned char *src; /* Source of content */
drh17146622009-07-07 17:38:38 +00001747 int iCellFirst; /* First allowable cell index */
1748 int iCellLast; /* Last possible cell index */
dan7f65b7a2021-04-10 20:27:06 +00001749 int iCellStart; /* First cell offset in input */
drh17146622009-07-07 17:38:38 +00001750
danielk19773b8a05f2007-03-19 17:44:26 +00001751 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001752 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +00001753 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +00001754 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00001755 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh1dd13032022-07-26 15:41:34 +00001756 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +00001757 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001758 cellOffset = pPage->cellOffset;
1759 nCell = pPage->nCell;
drh45616c72019-02-28 13:21:36 +00001760 assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB );
drh17146622009-07-07 17:38:38 +00001761 iCellFirst = cellOffset + 2*nCell;
dan30741eb2017-03-03 20:02:53 +00001762 usableSize = pPage->pBt->usableSize;
dane6d065a2017-02-24 19:58:22 +00001763
1764 /* This block handles pages with two or fewer free blocks and nMaxFrag
1765 ** or fewer fragmented bytes. In this case it is faster to move the
1766 ** two (or one) blocks of cells using memmove() and add the required
1767 ** offsets to each pointer in the cell-pointer array than it is to
1768 ** reconstruct the entire page. */
1769 if( (int)data[hdr+7]<=nMaxFrag ){
1770 int iFree = get2byte(&data[hdr+1]);
drh119e1ff2019-03-30 18:39:13 +00001771 if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
dane6d065a2017-02-24 19:58:22 +00001772 if( iFree ){
1773 int iFree2 = get2byte(&data[iFree]);
drh5881dfe2018-12-13 03:36:13 +00001774 if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
dane6d065a2017-02-24 19:58:22 +00001775 if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
1776 u8 *pEnd = &data[cellOffset + nCell*2];
1777 u8 *pAddr;
1778 int sz2 = 0;
1779 int sz = get2byte(&data[iFree+2]);
1780 int top = get2byte(&data[hdr+5]);
drh4b9e7362020-02-18 23:58:58 +00001781 if( top>=iFree ){
daneebf2f52017-11-18 17:30:08 +00001782 return SQLITE_CORRUPT_PAGE(pPage);
drh4e6cec12017-09-28 13:47:35 +00001783 }
dane6d065a2017-02-24 19:58:22 +00001784 if( iFree2 ){
drh5881dfe2018-12-13 03:36:13 +00001785 if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage);
dane6d065a2017-02-24 19:58:22 +00001786 sz2 = get2byte(&data[iFree2+2]);
drh5881dfe2018-12-13 03:36:13 +00001787 if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);
dane6d065a2017-02-24 19:58:22 +00001788 memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
1789 sz += sz2;
drhbcdb4cc2022-09-18 17:59:28 +00001790 }else if( iFree+sz>usableSize ){
dandcc427c2019-03-21 21:18:36 +00001791 return SQLITE_CORRUPT_PAGE(pPage);
dane6d065a2017-02-24 19:58:22 +00001792 }
dandcc427c2019-03-21 21:18:36 +00001793
dane6d065a2017-02-24 19:58:22 +00001794 cbrk = top+sz;
dan30741eb2017-03-03 20:02:53 +00001795 assert( cbrk+(iFree-top) <= usableSize );
dane6d065a2017-02-24 19:58:22 +00001796 memmove(&data[cbrk], &data[top], iFree-top);
1797 for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
1798 pc = get2byte(pAddr);
1799 if( pc<iFree ){ put2byte(pAddr, pc+sz); }
1800 else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
1801 }
1802 goto defragment_out;
1803 }
1804 }
1805 }
1806
drh281b21d2008-08-22 12:57:08 +00001807 cbrk = usableSize;
drh17146622009-07-07 17:38:38 +00001808 iCellLast = usableSize - 4;
dan7f65b7a2021-04-10 20:27:06 +00001809 iCellStart = get2byte(&data[hdr+5]);
drhf15b77b2022-07-07 21:04:03 +00001810 if( nCell>0 ){
1811 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1812 memcpy(&temp[iCellStart], &data[iCellStart], usableSize - iCellStart);
1813 src = temp;
1814 for(i=0; i<nCell; i++){
1815 u8 *pAddr; /* The i-th cell pointer */
1816 pAddr = &data[cellOffset + i*2];
1817 pc = get2byte(pAddr);
1818 testcase( pc==iCellFirst );
1819 testcase( pc==iCellLast );
1820 /* These conditions have already been verified in btreeInitPage()
1821 ** if PRAGMA cell_size_check=ON.
1822 */
1823 if( pc<iCellStart || pc>iCellLast ){
1824 return SQLITE_CORRUPT_PAGE(pPage);
1825 }
1826 assert( pc>=iCellStart && pc<=iCellLast );
1827 size = pPage->xCellSize(pPage, &src[pc]);
1828 cbrk -= size;
1829 if( cbrk<iCellStart || pc+size>usableSize ){
1830 return SQLITE_CORRUPT_PAGE(pPage);
1831 }
1832 assert( cbrk+size<=usableSize && cbrk>=iCellStart );
1833 testcase( cbrk+size==usableSize );
1834 testcase( pc+size==usableSize );
1835 put2byte(pAddr, cbrk);
1836 memcpy(&data[cbrk], &src[pc], size);
shane0af3f892008-11-12 04:55:34 +00001837 }
drh2af926b2001-05-15 00:39:25 +00001838 }
dane6d065a2017-02-24 19:58:22 +00001839 data[hdr+7] = 0;
dane6d065a2017-02-24 19:58:22 +00001840
drhf15b77b2022-07-07 21:04:03 +00001841defragment_out:
drhb0ea9432019-02-09 21:06:40 +00001842 assert( pPage->nFree>=0 );
dan3b2ede12017-02-25 16:24:02 +00001843 if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
daneebf2f52017-11-18 17:30:08 +00001844 return SQLITE_CORRUPT_PAGE(pPage);
dan3b2ede12017-02-25 16:24:02 +00001845 }
drh17146622009-07-07 17:38:38 +00001846 assert( cbrk>=iCellFirst );
drh281b21d2008-08-22 12:57:08 +00001847 put2byte(&data[hdr+5], cbrk);
drh43605152004-05-29 21:46:49 +00001848 data[hdr+1] = 0;
1849 data[hdr+2] = 0;
drh17146622009-07-07 17:38:38 +00001850 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
drhc5053fb2008-11-27 02:22:10 +00001851 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
shane0af3f892008-11-12 04:55:34 +00001852 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +00001853}
1854
drha059ad02001-04-17 20:09:11 +00001855/*
dan8e9ba0c2014-10-14 17:27:04 +00001856** Search the free-list on page pPg for space to store a cell nByte bytes in
1857** size. If one can be found, return a pointer to the space and remove it
1858** from the free-list.
1859**
1860** If no suitable space can be found on the free-list, return NULL.
1861**
drhba0f9992014-10-30 20:48:44 +00001862** This function may detect corruption within pPg. If corruption is
1863** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
dan61e94c92014-10-27 08:02:16 +00001864**
drhb7580e82015-06-25 18:36:13 +00001865** Slots on the free list that are between 1 and 3 bytes larger than nByte
1866** will be ignored if adding the extra space to the fragmentation count
1867** causes the fragmentation count to exceed 60.
dan8e9ba0c2014-10-14 17:27:04 +00001868*/
drhb7580e82015-06-25 18:36:13 +00001869static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
drh298f45c2019-02-08 22:34:59 +00001870 const int hdr = pPg->hdrOffset; /* Offset to page header */
1871 u8 * const aData = pPg->aData; /* Page data */
1872 int iAddr = hdr + 1; /* Address of ptr to pc */
drh009a48e2022-02-23 18:23:15 +00001873 u8 *pTmp = &aData[iAddr]; /* Temporary ptr into aData[] */
1874 int pc = get2byte(pTmp); /* Address of a free slot */
drh298f45c2019-02-08 22:34:59 +00001875 int x; /* Excess size of the slot */
1876 int maxPC = pPg->pBt->usableSize - nByte; /* Max address for a usable slot */
1877 int size; /* Size of the free slot */
dan8e9ba0c2014-10-14 17:27:04 +00001878
drhb7580e82015-06-25 18:36:13 +00001879 assert( pc>0 );
drh298f45c2019-02-08 22:34:59 +00001880 while( pc<=maxPC ){
drh113762a2014-11-19 16:36:25 +00001881 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
1882 ** freeblock form a big-endian integer which is the size of the freeblock
1883 ** in bytes, including the 4-byte header. */
drh009a48e2022-02-23 18:23:15 +00001884 pTmp = &aData[pc+2];
1885 size = get2byte(pTmp);
drhb7580e82015-06-25 18:36:13 +00001886 if( (x = size - nByte)>=0 ){
dan8e9ba0c2014-10-14 17:27:04 +00001887 testcase( x==4 );
1888 testcase( x==3 );
drh298f45c2019-02-08 22:34:59 +00001889 if( x<4 ){
drhfdab0262014-11-20 15:30:50 +00001890 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
1891 ** number of bytes in fragments may not exceed 60. */
drhb7580e82015-06-25 18:36:13 +00001892 if( aData[hdr+7]>57 ) return 0;
1893
dan8e9ba0c2014-10-14 17:27:04 +00001894 /* Remove the slot from the free-list. Update the number of
1895 ** fragmented bytes within the page. */
1896 memcpy(&aData[iAddr], &aData[pc], 2);
1897 aData[hdr+7] += (u8)x;
dan1942d1f2022-04-18 15:56:58 +00001898 return &aData[pc];
drh298f45c2019-02-08 22:34:59 +00001899 }else if( x+pc > maxPC ){
1900 /* This slot extends off the end of the usable part of the page */
1901 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1902 return 0;
dan8e9ba0c2014-10-14 17:27:04 +00001903 }else{
1904 /* The slot remains on the free-list. Reduce its size to account
drh298f45c2019-02-08 22:34:59 +00001905 ** for the portion used by the new allocation. */
dan8e9ba0c2014-10-14 17:27:04 +00001906 put2byte(&aData[pc+2], x);
1907 }
1908 return &aData[pc + x];
1909 }
drhb7580e82015-06-25 18:36:13 +00001910 iAddr = pc;
drh009a48e2022-02-23 18:23:15 +00001911 pTmp = &aData[pc];
1912 pc = get2byte(pTmp);
drhebaa9472022-07-07 20:29:49 +00001913 if( pc<=iAddr ){
drh298f45c2019-02-08 22:34:59 +00001914 if( pc ){
drhebaa9472022-07-07 20:29:49 +00001915 /* The next slot in the chain comes before the current slot */
drh298f45c2019-02-08 22:34:59 +00001916 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1917 }
1918 return 0;
1919 }
drh87d63c92017-08-23 23:09:03 +00001920 }
drh298f45c2019-02-08 22:34:59 +00001921 if( pc>maxPC+nByte-4 ){
1922 /* The free slot chain extends off the end of the page */
daneebf2f52017-11-18 17:30:08 +00001923 *pRc = SQLITE_CORRUPT_PAGE(pPg);
drh87d63c92017-08-23 23:09:03 +00001924 }
dan8e9ba0c2014-10-14 17:27:04 +00001925 return 0;
1926}
1927
1928/*
danielk19776011a752009-04-01 16:25:32 +00001929** Allocate nByte bytes of space from within the B-Tree page passed
drh0a45c272009-07-08 01:49:11 +00001930** as the first argument. Write into *pIdx the index into pPage->aData[]
1931** of the first byte of allocated space. Return either SQLITE_OK or
1932** an error code (usually SQLITE_CORRUPT).
drhbd03cae2001-06-02 02:40:57 +00001933**
drh0a45c272009-07-08 01:49:11 +00001934** The caller guarantees that there is sufficient space to make the
1935** allocation. This routine might need to defragment in order to bring
1936** all the space together, however. This routine will avoid using
1937** the first two bytes past the cell pointer area since presumably this
1938** allocation is being made in order to insert a new cell, so we will
1939** also end up needing a new cell pointer.
drh7e3b0a02001-04-28 16:52:40 +00001940*/
drh0a45c272009-07-08 01:49:11 +00001941static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
danielk19776011a752009-04-01 16:25:32 +00001942 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1943 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
drh0a45c272009-07-08 01:49:11 +00001944 int top; /* First byte of cell content area */
drhfefa0942014-11-05 21:21:08 +00001945 int rc = SQLITE_OK; /* Integer return code */
drh009a48e2022-02-23 18:23:15 +00001946 u8 *pTmp; /* Temp ptr into data[] */
drh0a45c272009-07-08 01:49:11 +00001947 int gap; /* First byte of gap between cell pointers and cell content */
drh43605152004-05-29 21:46:49 +00001948
danielk19773b8a05f2007-03-19 17:44:26 +00001949 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001950 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +00001951 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa67c3c2008-07-11 02:21:40 +00001952 assert( nByte>=0 ); /* Minimum cell size is 4 */
1953 assert( pPage->nFree>=nByte );
1954 assert( pPage->nOverflow==0 );
mistachkina95d8ca2014-10-27 19:42:02 +00001955 assert( nByte < (int)(pPage->pBt->usableSize-8) );
drh43605152004-05-29 21:46:49 +00001956
drh0a45c272009-07-08 01:49:11 +00001957 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1958 gap = pPage->cellOffset + 2*pPage->nCell;
drh75b31dc2014-08-20 00:54:46 +00001959 assert( gap<=65536 );
drhfdab0262014-11-20 15:30:50 +00001960 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
1961 ** and the reserved space is zero (the usual value for reserved space)
1962 ** then the cell content offset of an empty page wants to be 65536.
1963 ** However, that integer is too large to be stored in a 2-byte unsigned
1964 ** integer, so a value of 0 is used in its place. */
drh009a48e2022-02-23 18:23:15 +00001965 pTmp = &data[hdr+5];
1966 top = get2byte(pTmp);
drhdfcecdf2019-05-08 00:17:45 +00001967 assert( top<=(int)pPage->pBt->usableSize ); /* by btreeComputeFreeSpace() */
drhded340e2015-06-25 15:04:56 +00001968 if( gap>top ){
1969 if( top==0 && pPage->pBt->usableSize==65536 ){
1970 top = 65536;
1971 }else{
daneebf2f52017-11-18 17:30:08 +00001972 return SQLITE_CORRUPT_PAGE(pPage);
drhded340e2015-06-25 15:04:56 +00001973 }
drhe7266222015-05-29 17:51:16 +00001974 }
drh4c04f3c2014-08-20 11:56:14 +00001975
drhd4a67442019-02-11 19:27:36 +00001976 /* If there is enough space between gap and top for one more cell pointer,
1977 ** and if the freelist is not empty, then search the
1978 ** freelist looking for a slot big enough to satisfy the request.
drh4c04f3c2014-08-20 11:56:14 +00001979 */
drh0a45c272009-07-08 01:49:11 +00001980 testcase( gap+2==top );
1981 testcase( gap+1==top );
1982 testcase( gap==top );
drhe674bf12015-06-25 16:01:44 +00001983 if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
drhb7580e82015-06-25 18:36:13 +00001984 u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
dan8e9ba0c2014-10-14 17:27:04 +00001985 if( pSpace ){
drh3b76c452020-01-03 17:40:30 +00001986 int g2;
drh2b96b692019-08-05 16:22:20 +00001987 assert( pSpace+nByte<=data+pPage->pBt->usableSize );
drh3b76c452020-01-03 17:40:30 +00001988 *pIdx = g2 = (int)(pSpace-data);
drhb9154182021-06-20 22:49:26 +00001989 if( g2<=gap ){
drh2b96b692019-08-05 16:22:20 +00001990 return SQLITE_CORRUPT_PAGE(pPage);
1991 }else{
1992 return SQLITE_OK;
1993 }
drhb7580e82015-06-25 18:36:13 +00001994 }else if( rc ){
1995 return rc;
drh9e572e62004-04-23 23:43:10 +00001996 }
1997 }
drh43605152004-05-29 21:46:49 +00001998
drh4c04f3c2014-08-20 11:56:14 +00001999 /* The request could not be fulfilled using a freelist slot. Check
2000 ** to see if defragmentation is necessary.
drh0a45c272009-07-08 01:49:11 +00002001 */
2002 testcase( gap+2+nByte==top );
2003 if( gap+2+nByte>top ){
drh1fd2d7d2014-12-02 16:16:47 +00002004 assert( pPage->nCell>0 || CORRUPT_DB );
drhb0ea9432019-02-09 21:06:40 +00002005 assert( pPage->nFree>=0 );
dane6d065a2017-02-24 19:58:22 +00002006 rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
drh0a45c272009-07-08 01:49:11 +00002007 if( rc ) return rc;
drh5d433ce2010-08-14 16:02:52 +00002008 top = get2byteNotZero(&data[hdr+5]);
dan3b2ede12017-02-25 16:24:02 +00002009 assert( gap+2+nByte<=top );
drh0a45c272009-07-08 01:49:11 +00002010 }
2011
2012
drh43605152004-05-29 21:46:49 +00002013 /* Allocate memory from the gap in between the cell pointer array
drh5860a612019-02-12 16:58:26 +00002014 ** and the cell content area. The btreeComputeFreeSpace() call has already
drhc314dc72009-07-21 11:52:34 +00002015 ** validated the freelist. Given that the freelist is valid, there
2016 ** is no way that the allocation can extend off the end of the page.
2017 ** The assert() below verifies the previous sentence.
drh43605152004-05-29 21:46:49 +00002018 */
drh0a45c272009-07-08 01:49:11 +00002019 top -= nByte;
drh43605152004-05-29 21:46:49 +00002020 put2byte(&data[hdr+5], top);
drhfcd71b62011-04-05 22:08:24 +00002021 assert( top+nByte <= (int)pPage->pBt->usableSize );
drh0a45c272009-07-08 01:49:11 +00002022 *pIdx = top;
2023 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00002024}
2025
2026/*
drh9e572e62004-04-23 23:43:10 +00002027** Return a section of the pPage->aData to the freelist.
drh7fb91642014-08-20 14:37:09 +00002028** The first byte of the new free block is pPage->aData[iStart]
2029** and the size of the block is iSize bytes.
drh306dc212001-05-21 13:45:10 +00002030**
drh5f5c7532014-08-20 17:56:27 +00002031** Adjacent freeblocks are coalesced.
2032**
drh5860a612019-02-12 16:58:26 +00002033** Even though the freeblock list was checked by btreeComputeFreeSpace(),
drh5f5c7532014-08-20 17:56:27 +00002034** that routine will not detect overlap between cells or freeblocks. Nor
2035** does it detect cells or freeblocks that encrouch into the reserved bytes
2036** at the end of the page. So do additional corruption checks inside this
2037** routine and return SQLITE_CORRUPT if any problems are found.
drh7e3b0a02001-04-28 16:52:40 +00002038*/
drh5f5c7532014-08-20 17:56:27 +00002039static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
drh3f387402014-09-24 01:23:00 +00002040 u16 iPtr; /* Address of ptr to next freeblock */
drh5f5c7532014-08-20 17:56:27 +00002041 u16 iFreeBlk; /* Address of the next freeblock */
2042 u8 hdr; /* Page header size. 0 or 100 */
2043 u8 nFrag = 0; /* Reduction in fragmentation */
2044 u16 iOrigSize = iSize; /* Original value of iSize */
drh5e398e42017-08-23 20:36:06 +00002045 u16 x; /* Offset to cell content area */
drh5f5c7532014-08-20 17:56:27 +00002046 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
drh7fb91642014-08-20 14:37:09 +00002047 unsigned char *data = pPage->aData; /* Page content */
drh009a48e2022-02-23 18:23:15 +00002048 u8 *pTmp; /* Temporary ptr into data[] */
drh2af926b2001-05-15 00:39:25 +00002049
drh9e572e62004-04-23 23:43:10 +00002050 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00002051 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
dancf3d17c2015-05-25 15:03:49 +00002052 assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
dan23eba452014-10-24 18:43:57 +00002053 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +00002054 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh7fb91642014-08-20 14:37:09 +00002055 assert( iSize>=4 ); /* Minimum cell size is 4 */
drh5e398e42017-08-23 20:36:06 +00002056 assert( iStart<=pPage->pBt->usableSize-4 );
drhfcce93f2006-02-22 03:08:32 +00002057
drh5f5c7532014-08-20 17:56:27 +00002058 /* The list of freeblocks must be in ascending order. Find the
2059 ** spot on the list where iStart should be inserted.
drh0a45c272009-07-08 01:49:11 +00002060 */
drh43605152004-05-29 21:46:49 +00002061 hdr = pPage->hdrOffset;
drh7fb91642014-08-20 14:37:09 +00002062 iPtr = hdr + 1;
drh7bc4c452014-08-20 18:43:44 +00002063 if( data[iPtr+1]==0 && data[iPtr]==0 ){
2064 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
2065 }else{
drh85f071b2016-09-17 19:34:32 +00002066 while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
drhdce232a2022-07-07 20:11:35 +00002067 if( iFreeBlk<=iPtr ){
drh05e8c542020-01-14 16:39:54 +00002068 if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */
daneebf2f52017-11-18 17:30:08 +00002069 return SQLITE_CORRUPT_PAGE(pPage);
drh85f071b2016-09-17 19:34:32 +00002070 }
drh7bc4c452014-08-20 18:43:44 +00002071 iPtr = iFreeBlk;
drh9e572e62004-04-23 23:43:10 +00002072 }
drh628b1a32020-01-05 21:53:15 +00002073 if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */
daneebf2f52017-11-18 17:30:08 +00002074 return SQLITE_CORRUPT_PAGE(pPage);
drh5e398e42017-08-23 20:36:06 +00002075 }
drh0aa09452022-02-14 13:53:49 +00002076 assert( iFreeBlk>iPtr || iFreeBlk==0 || CORRUPT_DB );
drh7bc4c452014-08-20 18:43:44 +00002077
2078 /* At this point:
2079 ** iFreeBlk: First freeblock after iStart, or zero if none
drh3e24a342015-06-15 16:09:35 +00002080 ** iPtr: The address of a pointer to iFreeBlk
drh7bc4c452014-08-20 18:43:44 +00002081 **
2082 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
2083 */
2084 if( iFreeBlk && iEnd+3>=iFreeBlk ){
2085 nFrag = iFreeBlk - iEnd;
daneebf2f52017-11-18 17:30:08 +00002086 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
drh7bc4c452014-08-20 18:43:44 +00002087 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
drh6aa75152020-06-12 00:31:52 +00002088 if( iEnd > pPage->pBt->usableSize ){
daneebf2f52017-11-18 17:30:08 +00002089 return SQLITE_CORRUPT_PAGE(pPage);
drhcc97ca42017-06-07 22:32:59 +00002090 }
drh7bc4c452014-08-20 18:43:44 +00002091 iSize = iEnd - iStart;
2092 iFreeBlk = get2byte(&data[iFreeBlk]);
2093 }
2094
drh3f387402014-09-24 01:23:00 +00002095 /* If iPtr is another freeblock (that is, if iPtr is not the freelist
2096 ** pointer in the page header) then check to see if iStart should be
2097 ** coalesced onto the end of iPtr.
drh7bc4c452014-08-20 18:43:44 +00002098 */
2099 if( iPtr>hdr+1 ){
2100 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
2101 if( iPtrEnd+3>=iStart ){
daneebf2f52017-11-18 17:30:08 +00002102 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
drh7bc4c452014-08-20 18:43:44 +00002103 nFrag += iStart - iPtrEnd;
2104 iSize = iEnd - iPtr;
2105 iStart = iPtr;
2106 }
2107 }
daneebf2f52017-11-18 17:30:08 +00002108 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
drh7bc4c452014-08-20 18:43:44 +00002109 data[hdr+7] -= nFrag;
drh9e572e62004-04-23 23:43:10 +00002110 }
drh009a48e2022-02-23 18:23:15 +00002111 pTmp = &data[hdr+5];
2112 x = get2byte(pTmp);
drh5e398e42017-08-23 20:36:06 +00002113 if( iStart<=x ){
drh5f5c7532014-08-20 17:56:27 +00002114 /* The new freeblock is at the beginning of the cell content area,
2115 ** so just extend the cell content area rather than create another
2116 ** freelist entry */
drh3b76c452020-01-03 17:40:30 +00002117 if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage);
drh48118e42020-01-29 13:50:11 +00002118 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
drh5f5c7532014-08-20 17:56:27 +00002119 put2byte(&data[hdr+1], iFreeBlk);
2120 put2byte(&data[hdr+5], iEnd);
2121 }else{
2122 /* Insert the new freeblock into the freelist */
2123 put2byte(&data[iPtr], iStart);
drh4b70f112004-05-02 21:12:19 +00002124 }
drh5e398e42017-08-23 20:36:06 +00002125 if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
2126 /* Overwrite deleted information with zeros when the secure_delete
2127 ** option is enabled */
2128 memset(&data[iStart], 0, iSize);
2129 }
2130 put2byte(&data[iStart], iFreeBlk);
2131 put2byte(&data[iStart+2], iSize);
drh5f5c7532014-08-20 17:56:27 +00002132 pPage->nFree += iOrigSize;
shanedcc50b72008-11-13 18:29:50 +00002133 return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00002134}
2135
2136/*
drh271efa52004-05-30 19:19:05 +00002137** Decode the flags byte (the first byte of the header) for a page
2138** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +00002139**
2140** Only the following combinations are supported. Anything different
2141** indicates a corrupt database files:
2142**
drhbf9b9942022-11-19 13:09:03 +00002143** PTF_ZERODATA (0x02, 2)
2144** PTF_LEAFDATA | PTF_INTKEY (0x05, 5)
2145** PTF_ZERODATA | PTF_LEAF (0x0a, 10)
2146** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF (0x0d, 13)
drh271efa52004-05-30 19:19:05 +00002147*/
drh44845222008-07-17 18:39:57 +00002148static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +00002149 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +00002150
2151 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +00002152 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh271efa52004-05-30 19:19:05 +00002153 pBt = pPage->pBt;
drhbf9b9942022-11-19 13:09:03 +00002154 pPage->max1bytePayload = pBt->max1bytePayload;
2155 if( flagByte>=(PTF_ZERODATA | PTF_LEAF) ){
2156 pPage->childPtrSize = 0;
2157 pPage->leaf = 1;
2158 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF) ){
drh25ada072015-06-19 15:07:14 +00002159 pPage->intKeyLeaf = 1;
drh19ae01b2022-02-23 22:56:10 +00002160 pPage->xCellSize = cellSizePtrTableLeaf;
drh5fa60512015-06-19 17:19:34 +00002161 pPage->xParseCell = btreeParseCellPtr;
drhbf9b9942022-11-19 13:09:03 +00002162 pPage->intKey = 1;
2163 pPage->maxLocal = pBt->maxLeaf;
2164 pPage->minLocal = pBt->minLeaf;
2165 }else if( flagByte==(PTF_ZERODATA | PTF_LEAF) ){
2166 pPage->intKey = 0;
2167 pPage->intKeyLeaf = 0;
2168 pPage->xCellSize = cellSizePtr;
2169 pPage->xParseCell = btreeParseCellPtrIndex;
2170 pPage->maxLocal = pBt->maxLocal;
2171 pPage->minLocal = pBt->minLocal;
drh25ada072015-06-19 15:07:14 +00002172 }else{
drhbf9b9942022-11-19 13:09:03 +00002173 pPage->intKey = 0;
2174 pPage->intKeyLeaf = 0;
2175 pPage->xCellSize = cellSizePtr;
2176 pPage->xParseCell = btreeParseCellPtrIndex;
2177 return SQLITE_CORRUPT_PAGE(pPage);
2178 }
2179 }else{
2180 pPage->childPtrSize = 4;
2181 pPage->leaf = 0;
2182 if( flagByte==(PTF_ZERODATA) ){
2183 pPage->intKey = 0;
2184 pPage->intKeyLeaf = 0;
2185 pPage->xCellSize = cellSizePtr;
2186 pPage->xParseCell = btreeParseCellPtrIndex;
2187 pPage->maxLocal = pBt->maxLocal;
2188 pPage->minLocal = pBt->minLocal;
2189 }else if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
drh25ada072015-06-19 15:07:14 +00002190 pPage->intKeyLeaf = 0;
drh25ada072015-06-19 15:07:14 +00002191 pPage->xCellSize = cellSizePtrNoPayload;
drh5fa60512015-06-19 17:19:34 +00002192 pPage->xParseCell = btreeParseCellPtrNoPayload;
drhbf9b9942022-11-19 13:09:03 +00002193 pPage->intKey = 1;
2194 pPage->maxLocal = pBt->maxLeaf;
2195 pPage->minLocal = pBt->minLeaf;
2196 }else{
2197 pPage->intKey = 0;
2198 pPage->intKeyLeaf = 0;
2199 pPage->xCellSize = cellSizePtr;
2200 pPage->xParseCell = btreeParseCellPtrIndex;
2201 return SQLITE_CORRUPT_PAGE(pPage);
drh25ada072015-06-19 15:07:14 +00002202 }
drh271efa52004-05-30 19:19:05 +00002203 }
drh44845222008-07-17 18:39:57 +00002204 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +00002205}
2206
2207/*
drhb0ea9432019-02-09 21:06:40 +00002208** Compute the amount of freespace on the page. In other words, fill
2209** in the pPage->nFree field.
drh7e3b0a02001-04-28 16:52:40 +00002210*/
drhb0ea9432019-02-09 21:06:40 +00002211static int btreeComputeFreeSpace(MemPage *pPage){
drh14e845a2017-05-25 21:35:56 +00002212 int pc; /* Address of a freeblock within pPage->aData[] */
2213 u8 hdr; /* Offset to beginning of page header */
2214 u8 *data; /* Equal to pPage->aData */
drh14e845a2017-05-25 21:35:56 +00002215 int usableSize; /* Amount of usable space on each page */
drh14e845a2017-05-25 21:35:56 +00002216 int nFree; /* Number of unused bytes on the page */
2217 int top; /* First byte of the cell content area */
2218 int iCellFirst; /* First allowable cell or freeblock offset */
2219 int iCellLast; /* Last possible cell or freeblock offset */
drh2af926b2001-05-15 00:39:25 +00002220
danielk197771d5d2c2008-09-29 11:49:47 +00002221 assert( pPage->pBt!=0 );
drh1421d982015-05-27 03:46:18 +00002222 assert( pPage->pBt->db!=0 );
danielk197771d5d2c2008-09-29 11:49:47 +00002223 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00002224 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +00002225 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
2226 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
drhb0ea9432019-02-09 21:06:40 +00002227 assert( pPage->isInit==1 );
2228 assert( pPage->nFree<0 );
danielk197771d5d2c2008-09-29 11:49:47 +00002229
drhb0ea9432019-02-09 21:06:40 +00002230 usableSize = pPage->pBt->usableSize;
drh14e845a2017-05-25 21:35:56 +00002231 hdr = pPage->hdrOffset;
2232 data = pPage->aData;
drh14e845a2017-05-25 21:35:56 +00002233 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
2234 ** the start of the cell content area. A zero value for this integer is
2235 ** interpreted as 65536. */
2236 top = get2byteNotZero(&data[hdr+5]);
drhb0ea9432019-02-09 21:06:40 +00002237 iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;
drh14e845a2017-05-25 21:35:56 +00002238 iCellLast = usableSize - 4;
danielk197793c829c2009-06-03 17:26:17 +00002239
drh14e845a2017-05-25 21:35:56 +00002240 /* Compute the total free space on the page
2241 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
2242 ** start of the first freeblock on the page, or is zero if there are no
2243 ** freeblocks. */
2244 pc = get2byte(&data[hdr+1]);
2245 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
2246 if( pc>0 ){
2247 u32 next, size;
dan9a20ea92020-01-03 15:51:23 +00002248 if( pc<top ){
drh14e845a2017-05-25 21:35:56 +00002249 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
2250 ** always be at least one cell before the first freeblock.
2251 */
daneebf2f52017-11-18 17:30:08 +00002252 return SQLITE_CORRUPT_PAGE(pPage);
drhee696e22004-08-30 16:52:17 +00002253 }
drh14e845a2017-05-25 21:35:56 +00002254 while( 1 ){
2255 if( pc>iCellLast ){
drhcc97ca42017-06-07 22:32:59 +00002256 /* Freeblock off the end of the page */
daneebf2f52017-11-18 17:30:08 +00002257 return SQLITE_CORRUPT_PAGE(pPage);
drh14e845a2017-05-25 21:35:56 +00002258 }
2259 next = get2byte(&data[pc]);
2260 size = get2byte(&data[pc+2]);
2261 nFree = nFree + size;
2262 if( next<=pc+size+3 ) break;
2263 pc = next;
2264 }
2265 if( next>0 ){
drhcc97ca42017-06-07 22:32:59 +00002266 /* Freeblock not in ascending order */
daneebf2f52017-11-18 17:30:08 +00002267 return SQLITE_CORRUPT_PAGE(pPage);
drh14e845a2017-05-25 21:35:56 +00002268 }
2269 if( pc+size>(unsigned int)usableSize ){
drhcc97ca42017-06-07 22:32:59 +00002270 /* Last freeblock extends past page end */
daneebf2f52017-11-18 17:30:08 +00002271 return SQLITE_CORRUPT_PAGE(pPage);
drh14e845a2017-05-25 21:35:56 +00002272 }
danielk197771d5d2c2008-09-29 11:49:47 +00002273 }
drh14e845a2017-05-25 21:35:56 +00002274
2275 /* At this point, nFree contains the sum of the offset to the start
2276 ** of the cell-content area plus the number of free bytes within
2277 ** the cell-content area. If this is greater than the usable-size
2278 ** of the page, then the page must be corrupted. This check also
2279 ** serves to verify that the offset to the start of the cell-content
2280 ** area, according to the page header, lies within the page.
2281 */
drhdfcecdf2019-05-08 00:17:45 +00002282 if( nFree>usableSize || nFree<iCellFirst ){
daneebf2f52017-11-18 17:30:08 +00002283 return SQLITE_CORRUPT_PAGE(pPage);
drh14e845a2017-05-25 21:35:56 +00002284 }
2285 pPage->nFree = (u16)(nFree - iCellFirst);
drhb0ea9432019-02-09 21:06:40 +00002286 return SQLITE_OK;
2287}
2288
2289/*
drh5860a612019-02-12 16:58:26 +00002290** Do additional sanity check after btreeInitPage() if
2291** PRAGMA cell_size_check=ON
2292*/
2293static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){
2294 int iCellFirst; /* First allowable cell or freeblock offset */
2295 int iCellLast; /* Last possible cell or freeblock offset */
2296 int i; /* Index into the cell pointer array */
2297 int sz; /* Size of a cell */
2298 int pc; /* Address of a freeblock within pPage->aData[] */
2299 u8 *data; /* Equal to pPage->aData */
2300 int usableSize; /* Maximum usable space on the page */
2301 int cellOffset; /* Start of cell content area */
2302
2303 iCellFirst = pPage->cellOffset + 2*pPage->nCell;
2304 usableSize = pPage->pBt->usableSize;
2305 iCellLast = usableSize - 4;
2306 data = pPage->aData;
2307 cellOffset = pPage->cellOffset;
2308 if( !pPage->leaf ) iCellLast--;
2309 for(i=0; i<pPage->nCell; i++){
2310 pc = get2byteAligned(&data[cellOffset+i*2]);
2311 testcase( pc==iCellFirst );
2312 testcase( pc==iCellLast );
2313 if( pc<iCellFirst || pc>iCellLast ){
2314 return SQLITE_CORRUPT_PAGE(pPage);
2315 }
2316 sz = pPage->xCellSize(pPage, &data[pc]);
2317 testcase( pc+sz==usableSize );
2318 if( pc+sz>usableSize ){
2319 return SQLITE_CORRUPT_PAGE(pPage);
2320 }
2321 }
2322 return SQLITE_OK;
2323}
2324
2325/*
drhb0ea9432019-02-09 21:06:40 +00002326** Initialize the auxiliary information for a disk block.
2327**
2328** Return SQLITE_OK on success. If we see that the page does
2329** not contain a well-formed database page, then return
2330** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
2331** guarantee that the page is well-formed. It only shows that
2332** we failed to detect any corruption.
2333*/
2334static int btreeInitPage(MemPage *pPage){
drhb0ea9432019-02-09 21:06:40 +00002335 u8 *data; /* Equal to pPage->aData */
2336 BtShared *pBt; /* The main btree structure */
drhb0ea9432019-02-09 21:06:40 +00002337
2338 assert( pPage->pBt!=0 );
2339 assert( pPage->pBt->db!=0 );
2340 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2341 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
2342 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
2343 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
2344 assert( pPage->isInit==0 );
2345
2346 pBt = pPage->pBt;
drh5860a612019-02-12 16:58:26 +00002347 data = pPage->aData + pPage->hdrOffset;
drhb0ea9432019-02-09 21:06:40 +00002348 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
2349 ** the b-tree page type. */
drh5860a612019-02-12 16:58:26 +00002350 if( decodeFlags(pPage, data[0]) ){
drhb0ea9432019-02-09 21:06:40 +00002351 return SQLITE_CORRUPT_PAGE(pPage);
2352 }
2353 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2354 pPage->maskPage = (u16)(pBt->pageSize - 1);
2355 pPage->nOverflow = 0;
drh5860a612019-02-12 16:58:26 +00002356 pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;
2357 pPage->aCellIdx = data + pPage->childPtrSize + 8;
drha055abb2022-03-01 20:15:04 +00002358 pPage->aDataEnd = pPage->aData + pBt->pageSize;
drh5860a612019-02-12 16:58:26 +00002359 pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
drhb0ea9432019-02-09 21:06:40 +00002360 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
2361 ** number of cells on the page. */
drh5860a612019-02-12 16:58:26 +00002362 pPage->nCell = get2byte(&data[3]);
drhb0ea9432019-02-09 21:06:40 +00002363 if( pPage->nCell>MX_CELL(pBt) ){
2364 /* To many cells for a single page. The page must be corrupt */
2365 return SQLITE_CORRUPT_PAGE(pPage);
2366 }
2367 testcase( pPage->nCell==MX_CELL(pBt) );
2368 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
2369 ** possible for a root page of a table that contains no rows) then the
2370 ** offset to the cell content area will equal the page size minus the
2371 ** bytes of reserved space. */
2372 assert( pPage->nCell>0
mistachkin065f3bf2019-03-20 05:45:03 +00002373 || get2byteNotZero(&data[5])==(int)pBt->usableSize
drhb0ea9432019-02-09 21:06:40 +00002374 || CORRUPT_DB );
drhb0ea9432019-02-09 21:06:40 +00002375 pPage->nFree = -1; /* Indicate that this value is yet uncomputed */
drh14e845a2017-05-25 21:35:56 +00002376 pPage->isInit = 1;
drh5860a612019-02-12 16:58:26 +00002377 if( pBt->db->flags & SQLITE_CellSizeCk ){
2378 return btreeCellSizeCheck(pPage);
2379 }
drh9e572e62004-04-23 23:43:10 +00002380 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00002381}
2382
2383/*
drh8b2f49b2001-06-08 00:21:52 +00002384** Set up a raw page so that it looks like a database page holding
2385** no entries.
drhbd03cae2001-06-02 02:40:57 +00002386*/
drh9e572e62004-04-23 23:43:10 +00002387static void zeroPage(MemPage *pPage, int flags){
2388 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00002389 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00002390 u8 hdr = pPage->hdrOffset;
2391 u16 first;
drh9e572e62004-04-23 23:43:10 +00002392
drh37034292022-03-01 16:22:54 +00002393 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno || CORRUPT_DB );
drhbf4bca52007-09-06 22:19:14 +00002394 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2395 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00002396 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00002397 assert( sqlite3_mutex_held(pBt->mutex) );
drha5907a82017-06-19 11:44:22 +00002398 if( pBt->btsFlags & BTS_FAST_SECURE ){
drh5b47efa2010-02-12 18:18:39 +00002399 memset(&data[hdr], 0, pBt->usableSize - hdr);
2400 }
drh1bd10f82008-12-10 21:19:56 +00002401 data[hdr] = (char)flags;
drhfe485992014-02-12 23:52:16 +00002402 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
drh43605152004-05-29 21:46:49 +00002403 memset(&data[hdr+1], 0, 4);
2404 data[hdr+7] = 0;
2405 put2byte(&data[hdr+5], pBt->usableSize);
shaneh1df2db72010-08-18 02:28:48 +00002406 pPage->nFree = (u16)(pBt->usableSize - first);
drh271efa52004-05-30 19:19:05 +00002407 decodeFlags(pPage, flags);
drh43605152004-05-29 21:46:49 +00002408 pPage->cellOffset = first;
drha055abb2022-03-01 20:15:04 +00002409 pPage->aDataEnd = &data[pBt->pageSize];
drh3def2352011-11-11 00:27:15 +00002410 pPage->aCellIdx = &data[first];
drhf44890a2015-06-27 03:58:15 +00002411 pPage->aDataOfst = &data[pPage->childPtrSize];
drh43605152004-05-29 21:46:49 +00002412 pPage->nOverflow = 0;
drhb2eced52010-08-12 02:41:12 +00002413 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2414 pPage->maskPage = (u16)(pBt->pageSize - 1);
drh43605152004-05-29 21:46:49 +00002415 pPage->nCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00002416 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00002417}
2418
drh897a8202008-09-18 01:08:15 +00002419
2420/*
2421** Convert a DbPage obtained from the pager into a MemPage used by
2422** the btree layer.
2423*/
2424static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
2425 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
drh8dd1c252015-11-04 22:31:02 +00002426 if( pgno!=pPage->pgno ){
2427 pPage->aData = sqlite3PagerGetData(pDbPage);
2428 pPage->pDbPage = pDbPage;
2429 pPage->pBt = pBt;
2430 pPage->pgno = pgno;
2431 pPage->hdrOffset = pgno==1 ? 100 : 0;
2432 }
2433 assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
drh897a8202008-09-18 01:08:15 +00002434 return pPage;
2435}
2436
drhbd03cae2001-06-02 02:40:57 +00002437/*
drh3aac2dd2004-04-26 14:10:20 +00002438** Get a page from the pager. Initialize the MemPage.pBt and
drh7e8c6f12015-05-28 03:28:27 +00002439** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
drh538f5702007-04-13 02:14:30 +00002440**
drh7e8c6f12015-05-28 03:28:27 +00002441** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
2442** about the content of the page at this time. So do not go to the disk
drh538f5702007-04-13 02:14:30 +00002443** to fetch the content. Just fill in the content with zeros for now.
2444** If in the future we call sqlite3PagerWrite() on this page, that
2445** means we have started to be concerned about content and the disk
2446** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00002447*/
danielk197730548662009-07-09 05:07:37 +00002448static int btreeGetPage(
drh16a9b832007-05-05 18:39:25 +00002449 BtShared *pBt, /* The btree */
2450 Pgno pgno, /* Number of the page to fetch */
2451 MemPage **ppPage, /* Return the page in this parameter */
drhb00fc3b2013-08-21 23:42:32 +00002452 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
drh16a9b832007-05-05 18:39:25 +00002453){
drh3aac2dd2004-04-26 14:10:20 +00002454 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00002455 DbPage *pDbPage;
2456
drhb00fc3b2013-08-21 23:42:32 +00002457 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
drh1fee73e2007-08-29 04:00:57 +00002458 assert( sqlite3_mutex_held(pBt->mutex) );
drh9584f582015-11-04 20:22:37 +00002459 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
drh3aac2dd2004-04-26 14:10:20 +00002460 if( rc ) return rc;
drh897a8202008-09-18 01:08:15 +00002461 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
drh3aac2dd2004-04-26 14:10:20 +00002462 return SQLITE_OK;
2463}
2464
2465/*
danielk1977bea2a942009-01-20 17:06:27 +00002466** Retrieve a page from the pager cache. If the requested page is not
2467** already in the pager cache return NULL. Initialize the MemPage.pBt and
2468** MemPage.aData elements if needed.
2469*/
2470static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
2471 DbPage *pDbPage;
2472 assert( sqlite3_mutex_held(pBt->mutex) );
2473 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
2474 if( pDbPage ){
2475 return btreePageFromDbPage(pDbPage, pgno, pBt);
2476 }
2477 return 0;
2478}
2479
2480/*
danielk197789d40042008-11-17 14:20:56 +00002481** Return the size of the database file in pages. If there is any kind of
2482** error, return ((unsigned int)-1).
danielk197767fd7a92008-09-10 17:53:35 +00002483*/
drhb1299152010-03-30 22:58:33 +00002484static Pgno btreePagecount(BtShared *pBt){
2485 return pBt->nPage;
2486}
drh584e8b72020-07-22 17:12:59 +00002487Pgno sqlite3BtreeLastPage(Btree *p){
drhb1299152010-03-30 22:58:33 +00002488 assert( sqlite3BtreeHoldsMutex(p) );
drh584e8b72020-07-22 17:12:59 +00002489 return btreePagecount(p->pBt);
danielk197767fd7a92008-09-10 17:53:35 +00002490}
2491
2492/*
drh28f58dd2015-06-27 19:45:03 +00002493** Get a page from the pager and initialize it.
danielk197789bc4bc2009-07-21 19:25:24 +00002494**
drh15a00212015-06-27 20:55:00 +00002495** If pCur!=0 then the page is being fetched as part of a moveToChild()
2496** call. Do additional sanity checking on the page in this case.
2497** And if the fetch fails, this routine must decrement pCur->iPage.
drh28f58dd2015-06-27 19:45:03 +00002498**
2499** The page is fetched as read-write unless pCur is not NULL and is
2500** a read-only cursor.
2501**
2502** If an error occurs, then *ppPage is undefined. It
danielk197789bc4bc2009-07-21 19:25:24 +00002503** may remain unchanged, or it may be set to an invalid value.
drhde647132004-05-07 17:57:49 +00002504*/
2505static int getAndInitPage(
dan11dcd112013-03-15 18:29:18 +00002506 BtShared *pBt, /* The database file */
2507 Pgno pgno, /* Number of the page to get */
2508 MemPage **ppPage, /* Write the page pointer here */
drh28f58dd2015-06-27 19:45:03 +00002509 BtCursor *pCur, /* Cursor to receive the page, or NULL */
2510 int bReadOnly /* True for a read-only page */
drhde647132004-05-07 17:57:49 +00002511){
2512 int rc;
drh28f58dd2015-06-27 19:45:03 +00002513 DbPage *pDbPage;
drh1fee73e2007-08-29 04:00:57 +00002514 assert( sqlite3_mutex_held(pBt->mutex) );
drh352a35a2017-08-15 03:46:47 +00002515 assert( pCur==0 || ppPage==&pCur->pPage );
drh28f58dd2015-06-27 19:45:03 +00002516 assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
drh15a00212015-06-27 20:55:00 +00002517 assert( pCur==0 || pCur->iPage>0 );
danielk197789bc4bc2009-07-21 19:25:24 +00002518
danba3cbf32010-06-30 04:29:03 +00002519 if( pgno>btreePagecount(pBt) ){
2520 rc = SQLITE_CORRUPT_BKPT;
drhb0ea9432019-02-09 21:06:40 +00002521 goto getAndInitPage_error1;
drh28f58dd2015-06-27 19:45:03 +00002522 }
drh9584f582015-11-04 20:22:37 +00002523 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
drh28f58dd2015-06-27 19:45:03 +00002524 if( rc ){
drhb0ea9432019-02-09 21:06:40 +00002525 goto getAndInitPage_error1;
drh28f58dd2015-06-27 19:45:03 +00002526 }
drh8dd1c252015-11-04 22:31:02 +00002527 *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
drh28f58dd2015-06-27 19:45:03 +00002528 if( (*ppPage)->isInit==0 ){
drh8dd1c252015-11-04 22:31:02 +00002529 btreePageFromDbPage(pDbPage, pgno, pBt);
drh28f58dd2015-06-27 19:45:03 +00002530 rc = btreeInitPage(*ppPage);
2531 if( rc!=SQLITE_OK ){
drhb0ea9432019-02-09 21:06:40 +00002532 goto getAndInitPage_error2;
danielk197789bc4bc2009-07-21 19:25:24 +00002533 }
drhee696e22004-08-30 16:52:17 +00002534 }
drh37034292022-03-01 16:22:54 +00002535 assert( (*ppPage)->pgno==pgno || CORRUPT_DB );
drh8dd1c252015-11-04 22:31:02 +00002536 assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
danba3cbf32010-06-30 04:29:03 +00002537
drh15a00212015-06-27 20:55:00 +00002538 /* If obtaining a child page for a cursor, we must verify that the page is
2539 ** compatible with the root page. */
drh8dd1c252015-11-04 22:31:02 +00002540 if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
drhcc97ca42017-06-07 22:32:59 +00002541 rc = SQLITE_CORRUPT_PGNO(pgno);
drhb0ea9432019-02-09 21:06:40 +00002542 goto getAndInitPage_error2;
drh28f58dd2015-06-27 19:45:03 +00002543 }
drh28f58dd2015-06-27 19:45:03 +00002544 return SQLITE_OK;
2545
drhb0ea9432019-02-09 21:06:40 +00002546getAndInitPage_error2:
2547 releasePage(*ppPage);
2548getAndInitPage_error1:
drh352a35a2017-08-15 03:46:47 +00002549 if( pCur ){
2550 pCur->iPage--;
2551 pCur->pPage = pCur->apPage[pCur->iPage];
2552 }
drh325d0872015-06-29 00:52:33 +00002553 testcase( pgno==0 );
drh48cae132022-07-05 10:40:30 +00002554 assert( pgno!=0 || rc!=SQLITE_OK );
drhde647132004-05-07 17:57:49 +00002555 return rc;
2556}
2557
dan7fff2e12017-05-29 14:27:37 +00002558#ifndef SQLITE_OMIT_CONCURRENT
2559/*
2560** Set the value of the MemPage.pgnoRoot variable, if it exists.
2561*/
2562static void setMempageRoot(MemPage *pPg, u32 pgnoRoot){
2563 pPg->pgnoRoot = pgnoRoot;
2564}
2565#else
2566# define setMempageRoot(x,y)
2567#endif
2568
drhde647132004-05-07 17:57:49 +00002569/*
drh3aac2dd2004-04-26 14:10:20 +00002570** Release a MemPage. This should be called once for each prior
danielk197730548662009-07-09 05:07:37 +00002571** call to btreeGetPage.
drh3908fe92017-09-01 14:50:19 +00002572**
2573** Page1 is a special case and must be released using releasePageOne().
drh3aac2dd2004-04-26 14:10:20 +00002574*/
drhbbf0f862015-06-27 14:59:26 +00002575static void releasePageNotNull(MemPage *pPage){
2576 assert( pPage->aData );
2577 assert( pPage->pBt );
2578 assert( pPage->pDbPage!=0 );
2579 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2580 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2581 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2582 sqlite3PagerUnrefNotNull(pPage->pDbPage);
2583}
drh4b70f112004-05-02 21:12:19 +00002584static void releasePage(MemPage *pPage){
drhbbf0f862015-06-27 14:59:26 +00002585 if( pPage ) releasePageNotNull(pPage);
drh3aac2dd2004-04-26 14:10:20 +00002586}
drh3908fe92017-09-01 14:50:19 +00002587static void releasePageOne(MemPage *pPage){
2588 assert( pPage!=0 );
2589 assert( pPage->aData );
2590 assert( pPage->pBt );
2591 assert( pPage->pDbPage!=0 );
2592 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2593 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2594 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2595 sqlite3PagerUnrefPageOne(pPage->pDbPage);
2596}
drh3aac2dd2004-04-26 14:10:20 +00002597
2598/*
drh7e8c6f12015-05-28 03:28:27 +00002599** Get an unused page.
2600**
2601** This works just like btreeGetPage() with the addition:
2602**
2603** * If the page is already in use for some other purpose, immediately
2604** release it and return an SQLITE_CURRUPT error.
2605** * Make sure the isInit flag is clear
2606*/
2607static int btreeGetUnusedPage(
2608 BtShared *pBt, /* The btree */
2609 Pgno pgno, /* Number of the page to fetch */
2610 MemPage **ppPage, /* Return the page in this parameter */
2611 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2612){
2613 int rc = btreeGetPage(pBt, pgno, ppPage, flags);
2614 if( rc==SQLITE_OK ){
2615 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
2616 releasePage(*ppPage);
2617 *ppPage = 0;
2618 return SQLITE_CORRUPT_BKPT;
2619 }
2620 (*ppPage)->isInit = 0;
2621 }else{
2622 *ppPage = 0;
2623 }
2624 return rc;
2625}
2626
2627
2628/*
drha6abd042004-06-09 17:37:22 +00002629** During a rollback, when the pager reloads information into the cache
2630** so that the cache is restored to its original state at the start of
2631** the transaction, for each page restored this routine is called.
2632**
2633** This routine needs to reset the extra data section at the end of the
2634** page to agree with the restored data.
2635*/
danielk1977eaa06f62008-09-18 17:34:44 +00002636static void pageReinit(DbPage *pData){
drh07d183d2005-05-01 22:52:42 +00002637 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00002638 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
danielk1977d217e6f2009-04-01 17:13:51 +00002639 assert( sqlite3PagerPageRefcount(pData)>0 );
danielk197771d5d2c2008-09-29 11:49:47 +00002640 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00002641 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00002642 pPage->isInit = 0;
danielk1977d217e6f2009-04-01 17:13:51 +00002643 if( sqlite3PagerPageRefcount(pData)>1 ){
drh5e8d8872009-03-30 17:19:48 +00002644 /* pPage might not be a btree page; it might be an overflow page
2645 ** or ptrmap page or a free page. In those cases, the following
danielk197730548662009-07-09 05:07:37 +00002646 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
drh5e8d8872009-03-30 17:19:48 +00002647 ** But no harm is done by this. And it is very important that
danielk197730548662009-07-09 05:07:37 +00002648 ** btreeInitPage() be called on every btree page so we make
drh5e8d8872009-03-30 17:19:48 +00002649 ** the call for every page that comes in for re-initing. */
danielk197730548662009-07-09 05:07:37 +00002650 btreeInitPage(pPage);
danielk197771d5d2c2008-09-29 11:49:47 +00002651 }
drha6abd042004-06-09 17:37:22 +00002652 }
2653}
2654
2655/*
drhe5fe6902007-12-07 18:55:28 +00002656** Invoke the busy handler for a btree.
2657*/
danielk19771ceedd32008-11-19 10:22:33 +00002658static int btreeInvokeBusyHandler(void *pArg){
drhe5fe6902007-12-07 18:55:28 +00002659 BtShared *pBt = (BtShared*)pArg;
2660 assert( pBt->db );
2661 assert( sqlite3_mutex_held(pBt->db->mutex) );
drh783e1592020-05-06 20:55:38 +00002662 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
drhe5fe6902007-12-07 18:55:28 +00002663}
2664
2665/*
drhad3e0102004-09-03 23:32:18 +00002666** Open a database file.
2667**
drh382c0242001-10-06 16:33:02 +00002668** zFilename is the name of the database file. If zFilename is NULL
drh75c014c2010-08-30 15:02:28 +00002669** then an ephemeral database is created. The ephemeral database might
2670** be exclusively in memory, or it might use a disk-based memory cache.
2671** Either way, the ephemeral database will be automatically deleted
2672** when sqlite3BtreeClose() is called.
2673**
drhe53831d2007-08-17 01:14:38 +00002674** If zFilename is ":memory:" then an in-memory database is created
2675** that is automatically destroyed when it is closed.
drhc47fd8e2009-04-30 13:30:32 +00002676**
drh33f111d2012-01-17 15:29:14 +00002677** The "flags" parameter is a bitmask that might contain bits like
2678** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
drh75c014c2010-08-30 15:02:28 +00002679**
drhc47fd8e2009-04-30 13:30:32 +00002680** If the database is already opened in the same database connection
2681** and we are in shared cache mode, then the open will fail with an
2682** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
2683** objects in the same database connection since doing so will lead
2684** to problems with locking.
drha059ad02001-04-17 20:09:11 +00002685*/
drh23e11ca2004-05-04 17:27:28 +00002686int sqlite3BtreeOpen(
dan3a6d8ae2011-04-23 15:54:54 +00002687 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
drh3aac2dd2004-04-26 14:10:20 +00002688 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00002689 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00002690 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00002691 int flags, /* Options */
2692 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00002693){
drh7555d8e2009-03-20 13:15:30 +00002694 BtShared *pBt = 0; /* Shared part of btree structure */
2695 Btree *p; /* Handle to return */
2696 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
2697 int rc = SQLITE_OK; /* Result code from this function */
2698 u8 nReserve; /* Byte of unused space on each page */
2699 unsigned char zDbHeader[100]; /* Database header content */
danielk1977aef0bf62005-12-30 16:28:01 +00002700
drh75c014c2010-08-30 15:02:28 +00002701 /* True if opening an ephemeral, temporary database */
2702 const int isTempDb = zFilename==0 || zFilename[0]==0;
2703
danielk1977aef0bf62005-12-30 16:28:01 +00002704 /* Set the variable isMemdb to true for an in-memory database, or
drhb0a7c9c2010-12-06 21:09:59 +00002705 ** false for a file-based database.
danielk1977aef0bf62005-12-30 16:28:01 +00002706 */
drhb0a7c9c2010-12-06 21:09:59 +00002707#ifdef SQLITE_OMIT_MEMORYDB
2708 const int isMemdb = 0;
2709#else
2710 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
drh9c67b2a2012-05-28 13:58:00 +00002711 || (isTempDb && sqlite3TempInMemory(db))
2712 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
danielk1977aef0bf62005-12-30 16:28:01 +00002713#endif
2714
drhe5fe6902007-12-07 18:55:28 +00002715 assert( db!=0 );
dan3a6d8ae2011-04-23 15:54:54 +00002716 assert( pVfs!=0 );
drhe5fe6902007-12-07 18:55:28 +00002717 assert( sqlite3_mutex_held(db->mutex) );
drhd4187c72010-08-30 22:15:45 +00002718 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
2719
2720 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
2721 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
2722
2723 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
2724 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
drh153c62c2007-08-24 03:51:33 +00002725
drh75c014c2010-08-30 15:02:28 +00002726 if( isMemdb ){
2727 flags |= BTREE_MEMORY;
2728 }
2729 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
2730 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
2731 }
drh17435752007-08-16 04:30:38 +00002732 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00002733 if( !p ){
mistachkinfad30392016-02-13 23:43:46 +00002734 return SQLITE_NOMEM_BKPT;
danielk1977aef0bf62005-12-30 16:28:01 +00002735 }
2736 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00002737 p->db = db;
danielk1977602b4662009-07-02 07:47:33 +00002738#ifndef SQLITE_OMIT_SHARED_CACHE
2739 p->lock.pBtree = p;
2740 p->lock.iTable = 1;
2741#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002742
drh198bf392006-01-06 21:52:49 +00002743#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00002744 /*
2745 ** If this Btree is a candidate for shared cache, try to find an
2746 ** existing BtShared object that we can share with
2747 */
drh4ab9d252012-05-26 20:08:49 +00002748 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
drhf1f12682009-09-09 14:17:52 +00002749 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
drh6b5f0eb2015-03-31 16:33:08 +00002750 int nFilename = sqlite3Strlen30(zFilename)+1;
danielk1977adfb9b02007-09-17 07:02:56 +00002751 int nFullPathname = pVfs->mxPathname+1;
drh6b5f0eb2015-03-31 16:33:08 +00002752 char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
drh30ddce62011-10-15 00:16:30 +00002753 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
drh6b5f0eb2015-03-31 16:33:08 +00002754
drhff0587c2007-08-29 17:43:19 +00002755 p->sharable = 1;
drhff0587c2007-08-29 17:43:19 +00002756 if( !zFullPathname ){
2757 sqlite3_free(p);
mistachkinfad30392016-02-13 23:43:46 +00002758 return SQLITE_NOMEM_BKPT;
drhff0587c2007-08-29 17:43:19 +00002759 }
drhafc8b7f2012-05-26 18:06:38 +00002760 if( isMemdb ){
drh6b5f0eb2015-03-31 16:33:08 +00002761 memcpy(zFullPathname, zFilename, nFilename);
drhafc8b7f2012-05-26 18:06:38 +00002762 }else{
2763 rc = sqlite3OsFullPathname(pVfs, zFilename,
2764 nFullPathname, zFullPathname);
2765 if( rc ){
drhc398c652019-11-22 00:42:01 +00002766 if( rc==SQLITE_OK_SYMLINK ){
2767 rc = SQLITE_OK;
2768 }else{
2769 sqlite3_free(zFullPathname);
2770 sqlite3_free(p);
2771 return rc;
2772 }
drhafc8b7f2012-05-26 18:06:38 +00002773 }
drh070ad6b2011-11-17 11:43:19 +00002774 }
drh30ddce62011-10-15 00:16:30 +00002775#if SQLITE_THREADSAFE
drh7555d8e2009-03-20 13:15:30 +00002776 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
2777 sqlite3_mutex_enter(mutexOpen);
drhccb21132020-06-19 11:34:57 +00002778 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
drhff0587c2007-08-29 17:43:19 +00002779 sqlite3_mutex_enter(mutexShared);
drh30ddce62011-10-15 00:16:30 +00002780#endif
drh78f82d12008-09-02 00:52:52 +00002781 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
drhff0587c2007-08-29 17:43:19 +00002782 assert( pBt->nRef>0 );
drhd4e0bb02012-05-27 01:19:04 +00002783 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
drhff0587c2007-08-29 17:43:19 +00002784 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
drhc47fd8e2009-04-30 13:30:32 +00002785 int iDb;
2786 for(iDb=db->nDb-1; iDb>=0; iDb--){
2787 Btree *pExisting = db->aDb[iDb].pBt;
2788 if( pExisting && pExisting->pBt==pBt ){
2789 sqlite3_mutex_leave(mutexShared);
2790 sqlite3_mutex_leave(mutexOpen);
2791 sqlite3_free(zFullPathname);
2792 sqlite3_free(p);
2793 return SQLITE_CONSTRAINT;
2794 }
2795 }
drhff0587c2007-08-29 17:43:19 +00002796 p->pBt = pBt;
2797 pBt->nRef++;
2798 break;
2799 }
2800 }
2801 sqlite3_mutex_leave(mutexShared);
2802 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00002803 }
drhff0587c2007-08-29 17:43:19 +00002804#ifdef SQLITE_DEBUG
2805 else{
2806 /* In debug mode, we mark all persistent databases as sharable
2807 ** even when they are not. This exercises the locking code and
2808 ** gives more opportunity for asserts(sqlite3_mutex_held())
2809 ** statements to find locking problems.
2810 */
2811 p->sharable = 1;
2812 }
2813#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002814 }
2815#endif
drha059ad02001-04-17 20:09:11 +00002816 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00002817 /*
2818 ** The following asserts make sure that structures used by the btree are
2819 ** the right size. This is to guard against size changes that result
2820 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00002821 */
drh062cf272015-03-23 19:03:51 +00002822 assert( sizeof(i64)==8 );
2823 assert( sizeof(u64)==8 );
drhe53831d2007-08-17 01:14:38 +00002824 assert( sizeof(u32)==4 );
2825 assert( sizeof(u16)==2 );
2826 assert( sizeof(Pgno)==4 );
2827
2828 pBt = sqlite3MallocZero( sizeof(*pBt) );
2829 if( pBt==0 ){
mistachkinfad30392016-02-13 23:43:46 +00002830 rc = SQLITE_NOMEM_BKPT;
drhe53831d2007-08-17 01:14:38 +00002831 goto btree_open_out;
2832 }
danielk197771d5d2c2008-09-29 11:49:47 +00002833 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
drha2ee5892016-12-09 16:02:00 +00002834 sizeof(MemPage), flags, vfsFlags, pageReinit);
drhe53831d2007-08-17 01:14:38 +00002835 if( rc==SQLITE_OK ){
drh9b4c59f2013-04-15 17:03:42 +00002836 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
drhe53831d2007-08-17 01:14:38 +00002837 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
2838 }
2839 if( rc!=SQLITE_OK ){
2840 goto btree_open_out;
2841 }
shanehbd2aaf92010-09-01 02:38:21 +00002842 pBt->openFlags = (u8)flags;
danielk19772a50ff02009-04-10 09:47:06 +00002843 pBt->db = db;
drh80262892018-03-26 16:37:53 +00002844 sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
drhe53831d2007-08-17 01:14:38 +00002845 p->pBt = pBt;
2846
drhe53831d2007-08-17 01:14:38 +00002847 pBt->pCursor = 0;
2848 pBt->pPage1 = 0;
drhc9166342012-01-05 23:32:06 +00002849 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
drha5907a82017-06-19 11:44:22 +00002850#if defined(SQLITE_SECURE_DELETE)
drhc9166342012-01-05 23:32:06 +00002851 pBt->btsFlags |= BTS_SECURE_DELETE;
drha5907a82017-06-19 11:44:22 +00002852#elif defined(SQLITE_FAST_SECURE_DELETE)
2853 pBt->btsFlags |= BTS_OVERWRITE;
drh5b47efa2010-02-12 18:18:39 +00002854#endif
drh113762a2014-11-19 16:36:25 +00002855 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2856 ** determined by the 2-byte integer located at an offset of 16 bytes from
2857 ** the beginning of the database file. */
drhb2eced52010-08-12 02:41:12 +00002858 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
drhe53831d2007-08-17 01:14:38 +00002859 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2860 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002861 pBt->pageSize = 0;
drhe53831d2007-08-17 01:14:38 +00002862#ifndef SQLITE_OMIT_AUTOVACUUM
2863 /* If the magic name ":memory:" will create an in-memory database, then
2864 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2865 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2866 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2867 ** regular file-name. In this case the auto-vacuum applies as per normal.
2868 */
2869 if( zFilename && !isMemdb ){
2870 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2871 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2872 }
2873#endif
2874 nReserve = 0;
2875 }else{
drh113762a2014-11-19 16:36:25 +00002876 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2877 ** determined by the one-byte unsigned integer found at an offset of 20
2878 ** into the database file header. */
drhe53831d2007-08-17 01:14:38 +00002879 nReserve = zDbHeader[20];
drhc9166342012-01-05 23:32:06 +00002880 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
drhe53831d2007-08-17 01:14:38 +00002881#ifndef SQLITE_OMIT_AUTOVACUUM
2882 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2883 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2884#endif
2885 }
drhfa9601a2009-06-18 17:22:39 +00002886 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhc0b61812009-04-30 01:22:41 +00002887 if( rc ) goto btree_open_out;
drhe53831d2007-08-17 01:14:38 +00002888 pBt->usableSize = pBt->pageSize - nReserve;
2889 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
drhe53831d2007-08-17 01:14:38 +00002890
2891#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2892 /* Add the new BtShared object to the linked list sharable BtShareds.
2893 */
dan272989b2016-07-06 10:12:02 +00002894 pBt->nRef = 1;
drhe53831d2007-08-17 01:14:38 +00002895 if( p->sharable ){
drh30ddce62011-10-15 00:16:30 +00002896 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
drhccb21132020-06-19 11:34:57 +00002897 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);)
danielk1977075c23a2008-09-01 18:34:20 +00002898 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
danielk197759f8c082008-06-18 17:09:10 +00002899 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00002900 if( pBt->mutex==0 ){
mistachkinfad30392016-02-13 23:43:46 +00002901 rc = SQLITE_NOMEM_BKPT;
drh3285db22007-09-03 22:00:39 +00002902 goto btree_open_out;
2903 }
drhff0587c2007-08-29 17:43:19 +00002904 }
drhe53831d2007-08-17 01:14:38 +00002905 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00002906 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2907 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
drhe53831d2007-08-17 01:14:38 +00002908 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00002909 }
drheee46cf2004-11-06 00:02:48 +00002910#endif
drh90f5ecb2004-07-22 01:19:35 +00002911 }
danielk1977aef0bf62005-12-30 16:28:01 +00002912
drhcfed7bc2006-03-13 14:28:05 +00002913#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00002914 /* If the new Btree uses a sharable pBtShared, then link the new
2915 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00002916 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00002917 */
drhe53831d2007-08-17 01:14:38 +00002918 if( p->sharable ){
2919 int i;
2920 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00002921 for(i=0; i<db->nDb; i++){
2922 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00002923 while( pSib->pPrev ){ pSib = pSib->pPrev; }
drh3bfa7e82016-03-22 14:37:59 +00002924 if( (uptr)p->pBt<(uptr)pSib->pBt ){
drhe53831d2007-08-17 01:14:38 +00002925 p->pNext = pSib;
2926 p->pPrev = 0;
2927 pSib->pPrev = p;
2928 }else{
drh3bfa7e82016-03-22 14:37:59 +00002929 while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
drhe53831d2007-08-17 01:14:38 +00002930 pSib = pSib->pNext;
2931 }
2932 p->pNext = pSib->pNext;
2933 p->pPrev = pSib;
2934 if( p->pNext ){
2935 p->pNext->pPrev = p;
2936 }
2937 pSib->pNext = p;
2938 }
2939 break;
2940 }
2941 }
danielk1977aef0bf62005-12-30 16:28:01 +00002942 }
danielk1977aef0bf62005-12-30 16:28:01 +00002943#endif
2944 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00002945
2946btree_open_out:
2947 if( rc!=SQLITE_OK ){
2948 if( pBt && pBt->pPager ){
dan7fb89902016-08-12 16:21:15 +00002949 sqlite3PagerClose(pBt->pPager, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002950 }
drh17435752007-08-16 04:30:38 +00002951 sqlite3_free(pBt);
2952 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00002953 *ppBtree = 0;
drh75c014c2010-08-30 15:02:28 +00002954 }else{
dan0f5a1862016-08-13 14:30:23 +00002955 sqlite3_file *pFile;
2956
drh75c014c2010-08-30 15:02:28 +00002957 /* If the B-Tree was successfully opened, set the pager-cache size to the
2958 ** default value. Except, when opening on an existing shared pager-cache,
2959 ** do not change the pager-cache size.
2960 */
2961 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
dan78f04752020-09-04 19:10:43 +00002962 sqlite3BtreeSetCacheSize(p, SQLITE_DEFAULT_CACHE_SIZE);
drh75c014c2010-08-30 15:02:28 +00002963 }
dan0f5a1862016-08-13 14:30:23 +00002964
2965 pFile = sqlite3PagerFile(pBt->pPager);
2966 if( pFile->pMethods ){
2967 sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
2968 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002969 }
drh7555d8e2009-03-20 13:15:30 +00002970 if( mutexOpen ){
2971 assert( sqlite3_mutex_held(mutexOpen) );
2972 sqlite3_mutex_leave(mutexOpen);
2973 }
dan272989b2016-07-06 10:12:02 +00002974 assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00002975 return rc;
drha059ad02001-04-17 20:09:11 +00002976}
2977
2978/*
drhe53831d2007-08-17 01:14:38 +00002979** Decrement the BtShared.nRef counter. When it reaches zero,
2980** remove the BtShared structure from the sharing list. Return
2981** true if the BtShared.nRef counter reaches zero and return
2982** false if it is still positive.
2983*/
2984static int removeFromSharingList(BtShared *pBt){
2985#ifndef SQLITE_OMIT_SHARED_CACHE
drh067b92b2020-06-19 15:24:12 +00002986 MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )
drhe53831d2007-08-17 01:14:38 +00002987 BtShared *pList;
2988 int removed = 0;
2989
drhd677b3d2007-08-20 22:48:41 +00002990 assert( sqlite3_mutex_notheld(pBt->mutex) );
drh067b92b2020-06-19 15:24:12 +00002991 MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
2992 sqlite3_mutex_enter(pMainMtx);
drhe53831d2007-08-17 01:14:38 +00002993 pBt->nRef--;
2994 if( pBt->nRef<=0 ){
drh78f82d12008-09-02 00:52:52 +00002995 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2996 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
drhe53831d2007-08-17 01:14:38 +00002997 }else{
drh78f82d12008-09-02 00:52:52 +00002998 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
drh34004ce2008-07-11 16:15:17 +00002999 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00003000 pList=pList->pNext;
3001 }
drh34004ce2008-07-11 16:15:17 +00003002 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00003003 pList->pNext = pBt->pNext;
3004 }
3005 }
drh3285db22007-09-03 22:00:39 +00003006 if( SQLITE_THREADSAFE ){
3007 sqlite3_mutex_free(pBt->mutex);
3008 }
drhe53831d2007-08-17 01:14:38 +00003009 removed = 1;
3010 }
drh067b92b2020-06-19 15:24:12 +00003011 sqlite3_mutex_leave(pMainMtx);
drhe53831d2007-08-17 01:14:38 +00003012 return removed;
3013#else
3014 return 1;
3015#endif
3016}
3017
3018/*
drhf7141992008-06-19 00:16:08 +00003019** Make sure pBt->pTmpSpace points to an allocation of
drh92787cf2014-10-15 11:55:51 +00003020** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
3021** pointer.
drhf7141992008-06-19 00:16:08 +00003022*/
drh2f0bc1d2021-12-03 13:42:41 +00003023static SQLITE_NOINLINE int allocateTempSpace(BtShared *pBt){
3024 assert( pBt!=0 );
3025 assert( pBt->pTmpSpace==0 );
3026 /* This routine is called only by btreeCursor() when allocating the
3027 ** first write cursor for the BtShared object */
3028 assert( pBt->pCursor!=0 && (pBt->pCursor->curFlags & BTCF_WriteFlag)!=0 );
3029 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
3030 if( pBt->pTmpSpace==0 ){
3031 BtCursor *pCur = pBt->pCursor;
3032 pBt->pCursor = pCur->pNext; /* Unlink the cursor */
3033 memset(pCur, 0, sizeof(*pCur));
3034 return SQLITE_NOMEM_BKPT;
drhf7141992008-06-19 00:16:08 +00003035 }
drh2f0bc1d2021-12-03 13:42:41 +00003036
3037 /* One of the uses of pBt->pTmpSpace is to format cells before
3038 ** inserting them into a leaf page (function fillInCell()). If
3039 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
3040 ** by the various routines that manipulate binary cells. Which
3041 ** can mean that fillInCell() only initializes the first 2 or 3
3042 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
3043 ** it into a database page. This is not actually a problem, but it
3044 ** does cause a valgrind error when the 1 or 2 bytes of unitialized
3045 ** data is passed to system call write(). So to avoid this error,
3046 ** zero the first 4 bytes of temp space here.
3047 **
3048 ** Also: Provide four bytes of initialized space before the
3049 ** beginning of pTmpSpace as an area available to prepend the
3050 ** left-child pointer to the beginning of a cell.
3051 */
drh11e4fdb2021-12-03 14:57:05 +00003052 memset(pBt->pTmpSpace, 0, 8);
3053 pBt->pTmpSpace += 4;
drh2f0bc1d2021-12-03 13:42:41 +00003054 return SQLITE_OK;
drhf7141992008-06-19 00:16:08 +00003055}
3056
3057/*
3058** Free the pBt->pTmpSpace allocation
3059*/
3060static void freeTempSpace(BtShared *pBt){
drh92787cf2014-10-15 11:55:51 +00003061 if( pBt->pTmpSpace ){
3062 pBt->pTmpSpace -= 4;
3063 sqlite3PageFree(pBt->pTmpSpace);
3064 pBt->pTmpSpace = 0;
3065 }
drhf7141992008-06-19 00:16:08 +00003066}
3067
3068/*
drha059ad02001-04-17 20:09:11 +00003069** Close an open database and invalidate all cursors.
3070*/
danielk1977aef0bf62005-12-30 16:28:01 +00003071int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00003072 BtShared *pBt = p->pBt;
danielk1977aef0bf62005-12-30 16:28:01 +00003073
danielk1977aef0bf62005-12-30 16:28:01 +00003074 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00003075 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00003076 sqlite3BtreeEnter(p);
drh5a4a15f2021-03-18 15:42:59 +00003077
3078 /* Verify that no other cursors have this Btree open */
3079#ifdef SQLITE_DEBUG
3080 {
3081 BtCursor *pCur = pBt->pCursor;
3082 while( pCur ){
3083 BtCursor *pTmp = pCur;
3084 pCur = pCur->pNext;
3085 assert( pTmp->pBtree!=p );
3086
danielk1977aef0bf62005-12-30 16:28:01 +00003087 }
drha059ad02001-04-17 20:09:11 +00003088 }
drh5a4a15f2021-03-18 15:42:59 +00003089#endif
danielk1977aef0bf62005-12-30 16:28:01 +00003090
danielk19778d34dfd2006-01-24 16:37:57 +00003091 /* Rollback any active transaction and free the handle structure.
3092 ** The call to sqlite3BtreeRollback() drops any table-locks held by
3093 ** this handle.
3094 */
drh47b7fc72014-11-11 01:33:57 +00003095 sqlite3BtreeRollback(p, SQLITE_OK, 0);
drhe53831d2007-08-17 01:14:38 +00003096 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003097
danielk1977aef0bf62005-12-30 16:28:01 +00003098 /* If there are still other outstanding references to the shared-btree
3099 ** structure, return now. The remainder of this procedure cleans
3100 ** up the shared-btree.
3101 */
drhe53831d2007-08-17 01:14:38 +00003102 assert( p->wantToLock==0 && p->locked==0 );
3103 if( !p->sharable || removeFromSharingList(pBt) ){
3104 /* The pBt is no longer on the sharing list, so we can access
3105 ** it without having to hold the mutex.
3106 **
3107 ** Clean out and delete the BtShared object.
3108 */
3109 assert( !pBt->pCursor );
dan7fb89902016-08-12 16:21:15 +00003110 sqlite3PagerClose(pBt->pPager, p->db);
drhe53831d2007-08-17 01:14:38 +00003111 if( pBt->xFreeSchema && pBt->pSchema ){
3112 pBt->xFreeSchema(pBt->pSchema);
3113 }
drhb9755982010-07-24 16:34:37 +00003114 sqlite3DbFree(0, pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00003115 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00003116 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00003117 }
3118
drhe53831d2007-08-17 01:14:38 +00003119#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00003120 assert( p->wantToLock==0 );
3121 assert( p->locked==0 );
3122 if( p->pPrev ) p->pPrev->pNext = p->pNext;
3123 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00003124#endif
3125
drhe53831d2007-08-17 01:14:38 +00003126 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00003127 return SQLITE_OK;
3128}
3129
3130/*
drh9b0cf342015-11-12 14:57:19 +00003131** Change the "soft" limit on the number of pages in the cache.
3132** Unused and unmodified pages will be recycled when the number of
3133** pages in the cache exceeds this soft limit. But the size of the
3134** cache is allowed to grow larger than this limit if it contains
3135** dirty pages or pages still in active use.
drhf57b14a2001-09-14 18:54:08 +00003136*/
danielk1977aef0bf62005-12-30 16:28:01 +00003137int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
3138 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00003139 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00003140 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00003141 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00003142 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00003143 return SQLITE_OK;
3144}
3145
drh9b0cf342015-11-12 14:57:19 +00003146/*
3147** Change the "spill" limit on the number of pages in the cache.
3148** If the number of pages exceeds this limit during a write transaction,
3149** the pager might attempt to "spill" pages to the journal early in
3150** order to free up memory.
3151**
3152** The value returned is the current spill size. If zero is passed
3153** as an argument, no changes are made to the spill size setting, so
3154** using mxPage of 0 is a way to query the current spill size.
3155*/
3156int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
3157 BtShared *pBt = p->pBt;
3158 int res;
3159 assert( sqlite3_mutex_held(p->db->mutex) );
3160 sqlite3BtreeEnter(p);
3161 res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
3162 sqlite3BtreeLeave(p);
3163 return res;
3164}
3165
drh18c7e402014-03-14 11:46:10 +00003166#if SQLITE_MAX_MMAP_SIZE>0
drhf57b14a2001-09-14 18:54:08 +00003167/*
dan5d8a1372013-03-19 19:28:06 +00003168** Change the limit on the amount of the database file that may be
3169** memory mapped.
3170*/
drh9b4c59f2013-04-15 17:03:42 +00003171int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
dan5d8a1372013-03-19 19:28:06 +00003172 BtShared *pBt = p->pBt;
3173 assert( sqlite3_mutex_held(p->db->mutex) );
3174 sqlite3BtreeEnter(p);
drh9b4c59f2013-04-15 17:03:42 +00003175 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
dan5d8a1372013-03-19 19:28:06 +00003176 sqlite3BtreeLeave(p);
3177 return SQLITE_OK;
3178}
drh18c7e402014-03-14 11:46:10 +00003179#endif /* SQLITE_MAX_MMAP_SIZE>0 */
dan5d8a1372013-03-19 19:28:06 +00003180
3181/*
drh973b6e32003-02-12 14:09:42 +00003182** Change the way data is synced to disk in order to increase or decrease
3183** how well the database resists damage due to OS crashes and power
3184** failures. Level 1 is the same as asynchronous (no syncs() occur and
3185** there is a high probability of damage) Level 2 is the default. There
3186** is a very low but non-zero probability of damage. Level 3 reduces the
3187** probability of damage to near zero but with a write performance reduction.
3188*/
danielk197793758c82005-01-21 08:13:14 +00003189#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drh40c39412013-08-16 20:42:20 +00003190int sqlite3BtreeSetPagerFlags(
drhc97d8462010-11-19 18:23:35 +00003191 Btree *p, /* The btree to set the safety level on */
drh40c39412013-08-16 20:42:20 +00003192 unsigned pgFlags /* Various PAGER_* flags */
drhc97d8462010-11-19 18:23:35 +00003193){
danielk1977aef0bf62005-12-30 16:28:01 +00003194 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00003195 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00003196 sqlite3BtreeEnter(p);
drh40c39412013-08-16 20:42:20 +00003197 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
drhd677b3d2007-08-20 22:48:41 +00003198 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00003199 return SQLITE_OK;
3200}
danielk197793758c82005-01-21 08:13:14 +00003201#endif
drh973b6e32003-02-12 14:09:42 +00003202
drh2c8997b2005-08-27 16:36:48 +00003203/*
drh90f5ecb2004-07-22 01:19:35 +00003204** Change the default pages size and the number of reserved bytes per page.
drhce4869f2009-04-02 20:16:58 +00003205** Or, if the page size has already been fixed, return SQLITE_READONLY
3206** without changing anything.
drh06f50212004-11-02 14:24:33 +00003207**
3208** The page size must be a power of 2 between 512 and 65536. If the page
3209** size supplied does not meet this constraint then the page size is not
3210** changed.
3211**
3212** Page sizes are constrained to be a power of two so that the region
3213** of the database file used for locking (beginning at PENDING_BYTE,
3214** the first byte past the 1GB boundary, 0x40000000) needs to occur
3215** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00003216**
3217** If parameter nReserve is less than zero, then the number of reserved
3218** bytes per page is left unchanged.
drhce4869f2009-04-02 20:16:58 +00003219**
drhc9166342012-01-05 23:32:06 +00003220** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
drhce4869f2009-04-02 20:16:58 +00003221** and autovacuum mode can no longer be changed.
drh90f5ecb2004-07-22 01:19:35 +00003222*/
drhce4869f2009-04-02 20:16:58 +00003223int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
danielk1977a1644fd2007-08-29 12:31:25 +00003224 int rc = SQLITE_OK;
drhe937df82020-05-07 01:56:57 +00003225 int x;
danielk1977aef0bf62005-12-30 16:28:01 +00003226 BtShared *pBt = p->pBt;
drhe937df82020-05-07 01:56:57 +00003227 assert( nReserve>=0 && nReserve<=255 );
drhd677b3d2007-08-20 22:48:41 +00003228 sqlite3BtreeEnter(p);
drhe937df82020-05-07 01:56:57 +00003229 pBt->nReserveWanted = nReserve;
3230 x = pBt->pageSize - pBt->usableSize;
3231 if( nReserve<x ) nReserve = x;
drhc9166342012-01-05 23:32:06 +00003232 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
drhd677b3d2007-08-20 22:48:41 +00003233 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00003234 return SQLITE_READONLY;
3235 }
drhf49661a2008-12-10 16:45:50 +00003236 assert( nReserve>=0 && nReserve<=255 );
drh06f50212004-11-02 14:24:33 +00003237 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
3238 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00003239 assert( (pageSize & 7)==0 );
dandd14ecb2015-05-05 10:03:08 +00003240 assert( !pBt->pCursor );
drh906602a2021-01-21 21:36:25 +00003241 if( nReserve>32 && pageSize==512 ) pageSize = 1024;
drhb2eced52010-08-12 02:41:12 +00003242 pBt->pageSize = (u32)pageSize;
drhf7141992008-06-19 00:16:08 +00003243 freeTempSpace(pBt);
drh90f5ecb2004-07-22 01:19:35 +00003244 }
drhfa9601a2009-06-18 17:22:39 +00003245 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhf49661a2008-12-10 16:45:50 +00003246 pBt->usableSize = pBt->pageSize - (u16)nReserve;
drhc9166342012-01-05 23:32:06 +00003247 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
drhd677b3d2007-08-20 22:48:41 +00003248 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00003249 return rc;
drh90f5ecb2004-07-22 01:19:35 +00003250}
3251
3252/*
3253** Return the currently defined page size
3254*/
danielk1977aef0bf62005-12-30 16:28:01 +00003255int sqlite3BtreeGetPageSize(Btree *p){
3256 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00003257}
drh7f751222009-03-17 22:33:00 +00003258
dan0094f372012-09-28 20:23:42 +00003259/*
3260** This function is similar to sqlite3BtreeGetReserve(), except that it
3261** may only be called if it is guaranteed that the b-tree mutex is already
3262** held.
3263**
3264** This is useful in one special case in the backup API code where it is
3265** known that the shared b-tree mutex is held, but the mutex on the
3266** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
3267** were to be called, it might collide with some other operation on the
mistachkin48864df2013-03-21 21:20:32 +00003268** database handle that owns *p, causing undefined behavior.
dan0094f372012-09-28 20:23:42 +00003269*/
3270int sqlite3BtreeGetReserveNoMutex(Btree *p){
drhad0961b2015-02-21 00:19:25 +00003271 int n;
dan0094f372012-09-28 20:23:42 +00003272 assert( sqlite3_mutex_held(p->pBt->mutex) );
drhad0961b2015-02-21 00:19:25 +00003273 n = p->pBt->pageSize - p->pBt->usableSize;
3274 return n;
dan0094f372012-09-28 20:23:42 +00003275}
3276
drh7f751222009-03-17 22:33:00 +00003277/*
3278** Return the number of bytes of space at the end of every page that
3279** are intentually left unused. This is the "reserved" space that is
3280** sometimes used by extensions.
drhad0961b2015-02-21 00:19:25 +00003281**
drh4d347662020-04-22 00:50:21 +00003282** The value returned is the larger of the current reserve size and
3283** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES.
3284** The amount of reserve can only grow - never shrink.
drh7f751222009-03-17 22:33:00 +00003285*/
drh45248de2020-04-20 15:18:43 +00003286int sqlite3BtreeGetRequestedReserve(Btree *p){
drhe937df82020-05-07 01:56:57 +00003287 int n1, n2;
drhd677b3d2007-08-20 22:48:41 +00003288 sqlite3BtreeEnter(p);
drhe937df82020-05-07 01:56:57 +00003289 n1 = (int)p->pBt->nReserveWanted;
3290 n2 = sqlite3BtreeGetReserveNoMutex(p);
drhd677b3d2007-08-20 22:48:41 +00003291 sqlite3BtreeLeave(p);
drhe937df82020-05-07 01:56:57 +00003292 return n1>n2 ? n1 : n2;
drh2011d5f2004-07-22 02:40:37 +00003293}
drhf8e632b2007-05-08 14:51:36 +00003294
drhad0961b2015-02-21 00:19:25 +00003295
drhf8e632b2007-05-08 14:51:36 +00003296/*
3297** Set the maximum page count for a database if mxPage is positive.
3298** No changes are made if mxPage is 0 or negative.
3299** Regardless of the value of mxPage, return the maximum page count.
3300*/
drhe9261db2020-07-20 12:47:32 +00003301Pgno sqlite3BtreeMaxPageCount(Btree *p, Pgno mxPage){
3302 Pgno n;
drhd677b3d2007-08-20 22:48:41 +00003303 sqlite3BtreeEnter(p);
3304 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
3305 sqlite3BtreeLeave(p);
3306 return n;
drhf8e632b2007-05-08 14:51:36 +00003307}
drh5b47efa2010-02-12 18:18:39 +00003308
3309/*
drha5907a82017-06-19 11:44:22 +00003310** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
3311**
3312** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
3313** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
3314** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
3315** newFlag==(-1) No changes
3316**
3317** This routine acts as a query if newFlag is less than zero
3318**
3319** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
3320** freelist leaf pages are not written back to the database. Thus in-page
3321** deleted content is cleared, but freelist deleted content is not.
3322**
3323** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
3324** that freelist leaf pages are written back into the database, increasing
3325** the amount of disk I/O.
drh5b47efa2010-02-12 18:18:39 +00003326*/
3327int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
3328 int b;
drhaf034ed2010-02-12 19:46:26 +00003329 if( p==0 ) return 0;
drh5b47efa2010-02-12 18:18:39 +00003330 sqlite3BtreeEnter(p);
drha5907a82017-06-19 11:44:22 +00003331 assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
3332 assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
drh5b47efa2010-02-12 18:18:39 +00003333 if( newFlag>=0 ){
drha5907a82017-06-19 11:44:22 +00003334 p->pBt->btsFlags &= ~BTS_FAST_SECURE;
3335 p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
3336 }
3337 b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
drh5b47efa2010-02-12 18:18:39 +00003338 sqlite3BtreeLeave(p);
3339 return b;
3340}
drh90f5ecb2004-07-22 01:19:35 +00003341
3342/*
danielk1977951af802004-11-05 15:45:09 +00003343** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
3344** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
3345** is disabled. The default value for the auto-vacuum property is
3346** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
3347*/
danielk1977aef0bf62005-12-30 16:28:01 +00003348int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00003349#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00003350 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00003351#else
danielk1977dddbcdc2007-04-26 14:42:34 +00003352 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003353 int rc = SQLITE_OK;
drh076d4662009-02-18 20:31:18 +00003354 u8 av = (u8)autoVacuum;
drhd677b3d2007-08-20 22:48:41 +00003355
3356 sqlite3BtreeEnter(p);
drhc9166342012-01-05 23:32:06 +00003357 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00003358 rc = SQLITE_READONLY;
3359 }else{
drh076d4662009-02-18 20:31:18 +00003360 pBt->autoVacuum = av ?1:0;
3361 pBt->incrVacuum = av==2 ?1:0;
danielk1977951af802004-11-05 15:45:09 +00003362 }
drhd677b3d2007-08-20 22:48:41 +00003363 sqlite3BtreeLeave(p);
3364 return rc;
danielk1977951af802004-11-05 15:45:09 +00003365#endif
3366}
3367
3368/*
3369** Return the value of the 'auto-vacuum' property. If auto-vacuum is
3370** enabled 1 is returned. Otherwise 0.
3371*/
danielk1977aef0bf62005-12-30 16:28:01 +00003372int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00003373#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00003374 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00003375#else
drhd677b3d2007-08-20 22:48:41 +00003376 int rc;
3377 sqlite3BtreeEnter(p);
3378 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00003379 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
3380 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
3381 BTREE_AUTOVACUUM_INCR
3382 );
drhd677b3d2007-08-20 22:48:41 +00003383 sqlite3BtreeLeave(p);
3384 return rc;
danielk1977951af802004-11-05 15:45:09 +00003385#endif
3386}
3387
danf5da7db2017-03-16 18:14:39 +00003388/*
3389** If the user has not set the safety-level for this database connection
3390** using "PRAGMA synchronous", and if the safety-level is not already
3391** set to the value passed to this function as the second parameter,
3392** set it so.
3393*/
drh2ed57372017-10-05 20:57:38 +00003394#if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
3395 && !defined(SQLITE_OMIT_WAL)
danf5da7db2017-03-16 18:14:39 +00003396static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
3397 sqlite3 *db;
3398 Db *pDb;
3399 if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
3400 while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
3401 if( pDb->bSyncSet==0
3402 && pDb->safety_level!=safety_level
3403 && pDb!=&db->aDb[1]
3404 ){
3405 pDb->safety_level = safety_level;
3406 sqlite3PagerSetFlags(pBt->pPager,
3407 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
3408 }
3409 }
3410}
3411#else
danfc8f4b62017-03-16 18:54:42 +00003412# define setDefaultSyncFlag(pBt,safety_level)
danf5da7db2017-03-16 18:14:39 +00003413#endif
danielk1977951af802004-11-05 15:45:09 +00003414
drh0314cf32018-04-28 01:27:09 +00003415/* Forward declaration */
3416static int newDatabase(BtShared*);
3417
3418
danielk1977951af802004-11-05 15:45:09 +00003419/*
drha34b6762004-05-07 13:30:42 +00003420** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00003421** also acquire a readlock on that file.
3422**
3423** SQLITE_OK is returned on success. If the file is not a
3424** well-formed database file, then SQLITE_CORRUPT is returned.
3425** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00003426** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00003427*/
danielk1977aef0bf62005-12-30 16:28:01 +00003428static int lockBtree(BtShared *pBt){
drhc2a4bab2010-04-02 12:46:45 +00003429 int rc; /* Result code from subfunctions */
3430 MemPage *pPage1; /* Page 1 of the database file */
dane6370e92019-01-11 17:41:23 +00003431 u32 nPage; /* Number of pages in the database */
3432 u32 nPageFile = 0; /* Number of pages in the database file */
drhd677b3d2007-08-20 22:48:41 +00003433
drh1fee73e2007-08-29 04:00:57 +00003434 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977295dc102009-04-01 19:07:03 +00003435 assert( pBt->pPage1==0 );
danielk197789bc4bc2009-07-21 19:25:24 +00003436 rc = sqlite3PagerSharedLock(pBt->pPager);
3437 if( rc!=SQLITE_OK ) return rc;
drhb00fc3b2013-08-21 23:42:32 +00003438 rc = btreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00003439 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00003440
3441 /* Do some checking to help insure the file we opened really is
3442 ** a valid database file.
3443 */
drh7d4c94b2021-10-04 22:34:38 +00003444 nPage = get4byte(28+(u8*)pPage1->aData);
dane6370e92019-01-11 17:41:23 +00003445 sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
drhb28e59b2010-06-17 02:13:39 +00003446 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
drhc2a4bab2010-04-02 12:46:45 +00003447 nPage = nPageFile;
drh97b59a52010-03-31 02:31:33 +00003448 }
drh0314cf32018-04-28 01:27:09 +00003449 if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
3450 nPage = 0;
3451 }
drh97b59a52010-03-31 02:31:33 +00003452 if( nPage>0 ){
drh43b18e12010-08-17 19:40:08 +00003453 u32 pageSize;
3454 u32 usableSize;
drhb6f41482004-05-14 01:58:11 +00003455 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00003456 rc = SQLITE_NOTADB;
drh113762a2014-11-19 16:36:25 +00003457 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
3458 ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
3459 ** 61 74 20 33 00. */
drhb6f41482004-05-14 01:58:11 +00003460 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00003461 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00003462 }
dan5cf53532010-05-01 16:40:20 +00003463
3464#ifdef SQLITE_OMIT_WAL
3465 if( page1[18]>1 ){
drhc9166342012-01-05 23:32:06 +00003466 pBt->btsFlags |= BTS_READ_ONLY;
dan5cf53532010-05-01 16:40:20 +00003467 }
3468 if( page1[19]>1 ){
3469 goto page1_init_failed;
3470 }
3471#else
dane04dc882010-04-20 18:53:15 +00003472 if( page1[18]>2 ){
drhc9166342012-01-05 23:32:06 +00003473 pBt->btsFlags |= BTS_READ_ONLY;
drh309169a2007-04-24 17:27:51 +00003474 }
dane04dc882010-04-20 18:53:15 +00003475 if( page1[19]>2 ){
drhb6f41482004-05-14 01:58:11 +00003476 goto page1_init_failed;
3477 }
drhe5ae5732008-06-15 02:51:47 +00003478
drh0ccda522021-08-23 15:56:01 +00003479 /* If the read version is set to 2, this database should be accessed
dana470aeb2010-04-21 11:43:38 +00003480 ** in WAL mode. If the log is not already open, open it now. Then
3481 ** return SQLITE_OK and return without populating BtShared.pPage1.
3482 ** The caller detects this and calls this function again. This is
3483 ** required as the version of page 1 currently in the page1 buffer
3484 ** may not be the latest version - there may be a newer one in the log
3485 ** file.
3486 */
drhc9166342012-01-05 23:32:06 +00003487 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
dane04dc882010-04-20 18:53:15 +00003488 int isOpen = 0;
drh7ed91f22010-04-29 22:34:07 +00003489 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
dane04dc882010-04-20 18:53:15 +00003490 if( rc!=SQLITE_OK ){
3491 goto page1_init_failed;
drhe243de52016-03-08 15:14:26 +00003492 }else{
danf5da7db2017-03-16 18:14:39 +00003493 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
drhe243de52016-03-08 15:14:26 +00003494 if( isOpen==0 ){
drh3908fe92017-09-01 14:50:19 +00003495 releasePageOne(pPage1);
drhe243de52016-03-08 15:14:26 +00003496 return SQLITE_OK;
3497 }
dane04dc882010-04-20 18:53:15 +00003498 }
dan8b5444b2010-04-27 14:37:47 +00003499 rc = SQLITE_NOTADB;
danf5da7db2017-03-16 18:14:39 +00003500 }else{
3501 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
dane04dc882010-04-20 18:53:15 +00003502 }
dan5cf53532010-05-01 16:40:20 +00003503#endif
dane04dc882010-04-20 18:53:15 +00003504
drh113762a2014-11-19 16:36:25 +00003505 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
3506 ** fractions and the leaf payload fraction values must be 64, 32, and 32.
3507 **
drhe5ae5732008-06-15 02:51:47 +00003508 ** The original design allowed these amounts to vary, but as of
3509 ** version 3.6.0, we require them to be fixed.
3510 */
3511 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
3512 goto page1_init_failed;
3513 }
drh113762a2014-11-19 16:36:25 +00003514 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
3515 ** determined by the 2-byte integer located at an offset of 16 bytes from
3516 ** the beginning of the database file. */
drhb2eced52010-08-12 02:41:12 +00003517 pageSize = (page1[16]<<8) | (page1[17]<<16);
drh113762a2014-11-19 16:36:25 +00003518 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
3519 ** between 512 and 65536 inclusive. */
drhb2eced52010-08-12 02:41:12 +00003520 if( ((pageSize-1)&pageSize)!=0
3521 || pageSize>SQLITE_MAX_PAGE_SIZE
3522 || pageSize<=256
drh7dc385e2007-09-06 23:39:36 +00003523 ){
drh07d183d2005-05-01 22:52:42 +00003524 goto page1_init_failed;
3525 }
drhdcc27002019-01-06 02:06:31 +00003526 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
drh07d183d2005-05-01 22:52:42 +00003527 assert( (pageSize & 7)==0 );
drh113762a2014-11-19 16:36:25 +00003528 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
3529 ** integer at offset 20 is the number of bytes of space at the end of
3530 ** each page to reserve for extensions.
3531 **
3532 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
3533 ** determined by the one-byte unsigned integer found at an offset of 20
3534 ** into the database file header. */
danielk1977f653d782008-03-20 11:04:21 +00003535 usableSize = pageSize - page1[20];
shaneh1df2db72010-08-18 02:28:48 +00003536 if( (u32)pageSize!=pBt->pageSize ){
danielk1977f653d782008-03-20 11:04:21 +00003537 /* After reading the first page of the database assuming a page size
3538 ** of BtShared.pageSize, we have discovered that the page-size is
3539 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
3540 ** zero and return SQLITE_OK. The caller will call this function
3541 ** again with the correct page-size.
3542 */
drh3908fe92017-09-01 14:50:19 +00003543 releasePageOne(pPage1);
drh43b18e12010-08-17 19:40:08 +00003544 pBt->usableSize = usableSize;
3545 pBt->pageSize = pageSize;
drhf7141992008-06-19 00:16:08 +00003546 freeTempSpace(pBt);
drhfa9601a2009-06-18 17:22:39 +00003547 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
3548 pageSize-usableSize);
drh5e483932009-07-10 16:51:30 +00003549 return rc;
danielk1977f653d782008-03-20 11:04:21 +00003550 }
drh5a6f8182022-01-17 14:42:38 +00003551 if( nPage>nPageFile ){
3552 if( sqlite3WritableSchema(pBt->db)==0 ){
3553 rc = SQLITE_CORRUPT_BKPT;
3554 goto page1_init_failed;
3555 }else{
3556 nPage = nPageFile;
3557 }
drhc2a4bab2010-04-02 12:46:45 +00003558 }
drh113762a2014-11-19 16:36:25 +00003559 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
3560 ** be less than 480. In other words, if the page size is 512, then the
3561 ** reserved space size cannot exceed 32. */
drhb33e1b92009-06-18 11:29:20 +00003562 if( usableSize<480 ){
drhb6f41482004-05-14 01:58:11 +00003563 goto page1_init_failed;
3564 }
drh43b18e12010-08-17 19:40:08 +00003565 pBt->pageSize = pageSize;
3566 pBt->usableSize = usableSize;
drh057cd3a2005-02-15 16:23:02 +00003567#ifndef SQLITE_OMIT_AUTOVACUUM
3568 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00003569 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00003570#endif
drh306dc212001-05-21 13:45:10 +00003571 }
drhb6f41482004-05-14 01:58:11 +00003572
3573 /* maxLocal is the maximum amount of payload to store locally for
3574 ** a cell. Make sure it is small enough so that at least minFanout
3575 ** cells can will fit on one page. We assume a 10-byte page header.
3576 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00003577 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00003578 ** 4-byte child pointer
3579 ** 9-byte nKey value
3580 ** 4-byte nData value
3581 ** 4-byte overflow page pointer
drhe22e03e2010-08-18 21:19:03 +00003582 ** So a cell consists of a 2-byte pointer, a header which is as much as
drh43605152004-05-29 21:46:49 +00003583 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
3584 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00003585 */
shaneh1df2db72010-08-18 02:28:48 +00003586 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
3587 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
3588 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
3589 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
drhc9166342012-01-05 23:32:06 +00003590 if( pBt->maxLocal>127 ){
3591 pBt->max1bytePayload = 127;
3592 }else{
mistachkin0547e2f2012-01-08 00:54:02 +00003593 pBt->max1bytePayload = (u8)pBt->maxLocal;
drhc9166342012-01-05 23:32:06 +00003594 }
drh2e38c322004-09-03 18:38:44 +00003595 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00003596 pBt->pPage1 = pPage1;
drhdd3cd972010-03-27 17:12:36 +00003597 pBt->nPage = nPage;
drhb6f41482004-05-14 01:58:11 +00003598 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00003599
drh72f82862001-05-24 21:06:34 +00003600page1_init_failed:
drh3908fe92017-09-01 14:50:19 +00003601 releasePageOne(pPage1);
drh3aac2dd2004-04-26 14:10:20 +00003602 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00003603 return rc;
drh306dc212001-05-21 13:45:10 +00003604}
3605
drh85ec3b62013-05-14 23:12:06 +00003606#ifndef NDEBUG
3607/*
3608** Return the number of cursors open on pBt. This is for use
3609** in assert() expressions, so it is only compiled if NDEBUG is not
3610** defined.
3611**
3612** Only write cursors are counted if wrOnly is true. If wrOnly is
3613** false then all cursors are counted.
3614**
3615** For the purposes of this routine, a cursor is any cursor that
peter.d.reid60ec9142014-09-06 16:39:46 +00003616** is capable of reading or writing to the database. Cursors that
drh85ec3b62013-05-14 23:12:06 +00003617** have been tripped into the CURSOR_FAULT state are not counted.
3618*/
3619static int countValidCursors(BtShared *pBt, int wrOnly){
3620 BtCursor *pCur;
3621 int r = 0;
3622 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drh036dbec2014-03-11 23:40:44 +00003623 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
3624 && pCur->eState!=CURSOR_FAULT ) r++;
drh85ec3b62013-05-14 23:12:06 +00003625 }
3626 return r;
3627}
3628#endif
3629
drh306dc212001-05-21 13:45:10 +00003630/*
drhb8ca3072001-12-05 00:21:20 +00003631** If there are no outstanding cursors and we are not in the middle
3632** of a transaction but there is a read lock on the database, then
3633** this routine unrefs the first page of the database file which
3634** has the effect of releasing the read lock.
3635**
drhb8ca3072001-12-05 00:21:20 +00003636** If there is a transaction in progress, this routine is a no-op.
3637*/
danielk1977aef0bf62005-12-30 16:28:01 +00003638static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00003639 assert( sqlite3_mutex_held(pBt->mutex) );
drh85ec3b62013-05-14 23:12:06 +00003640 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
danielk19771bc9ee92009-07-04 15:41:02 +00003641 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
drhb2325b72014-09-24 18:31:07 +00003642 MemPage *pPage1 = pBt->pPage1;
3643 assert( pPage1->aData );
danielk1977c1761e82009-06-25 09:40:03 +00003644 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
drh3aac2dd2004-04-26 14:10:20 +00003645 pBt->pPage1 = 0;
drh3908fe92017-09-01 14:50:19 +00003646 releasePageOne(pPage1);
drhb8ca3072001-12-05 00:21:20 +00003647 }
3648}
3649
3650/*
drhe39f2f92009-07-23 01:43:59 +00003651** If pBt points to an empty file then convert that empty file
3652** into a new empty database by initializing the first page of
3653** the database.
drh8b2f49b2001-06-08 00:21:52 +00003654*/
danielk1977aef0bf62005-12-30 16:28:01 +00003655static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00003656 MemPage *pP1;
3657 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00003658 int rc;
drhd677b3d2007-08-20 22:48:41 +00003659
drh1fee73e2007-08-29 04:00:57 +00003660 assert( sqlite3_mutex_held(pBt->mutex) );
drhdd3cd972010-03-27 17:12:36 +00003661 if( pBt->nPage>0 ){
3662 return SQLITE_OK;
danielk1977ad0132d2008-06-07 08:58:22 +00003663 }
drh3aac2dd2004-04-26 14:10:20 +00003664 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00003665 assert( pP1!=0 );
3666 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00003667 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00003668 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00003669 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
3670 assert( sizeof(zMagicHeader)==16 );
shaneh1df2db72010-08-18 02:28:48 +00003671 data[16] = (u8)((pBt->pageSize>>8)&0xff);
3672 data[17] = (u8)((pBt->pageSize>>16)&0xff);
drh9e572e62004-04-23 23:43:10 +00003673 data[18] = 1;
3674 data[19] = 1;
drhf49661a2008-12-10 16:45:50 +00003675 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
3676 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
drhe5ae5732008-06-15 02:51:47 +00003677 data[21] = 64;
3678 data[22] = 32;
3679 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00003680 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00003681 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhc9166342012-01-05 23:32:06 +00003682 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
danielk1977003ba062004-11-04 02:57:33 +00003683#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00003684 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00003685 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00003686 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00003687 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00003688#endif
drhdd3cd972010-03-27 17:12:36 +00003689 pBt->nPage = 1;
3690 data[31] = 1;
drh8b2f49b2001-06-08 00:21:52 +00003691 return SQLITE_OK;
3692}
3693
3694/*
danb483eba2012-10-13 19:58:11 +00003695** Initialize the first page of the database file (creating a database
3696** consisting of a single page and no schema objects). Return SQLITE_OK
3697** if successful, or an SQLite error code otherwise.
3698*/
3699int sqlite3BtreeNewDb(Btree *p){
3700 int rc;
3701 sqlite3BtreeEnter(p);
3702 p->pBt->nPage = 0;
3703 rc = newDatabase(p->pBt);
3704 sqlite3BtreeLeave(p);
3705 return rc;
3706}
3707
3708/*
danielk1977ee5741e2004-05-31 10:01:34 +00003709** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00003710** is started if the second argument is nonzero, otherwise a read-
3711** transaction. If the second argument is 2 or more and exclusive
3712** transaction is started, meaning that no other process is allowed
3713** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00003714** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00003715** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00003716**
danielk1977ee5741e2004-05-31 10:01:34 +00003717** A write-transaction must be started before attempting any
3718** changes to the database. None of the following routines
3719** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00003720**
drh23e11ca2004-05-04 17:27:28 +00003721** sqlite3BtreeCreateTable()
3722** sqlite3BtreeCreateIndex()
3723** sqlite3BtreeClearTable()
3724** sqlite3BtreeDropTable()
3725** sqlite3BtreeInsert()
3726** sqlite3BtreeDelete()
3727** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00003728**
drhb8ef32c2005-03-14 02:01:49 +00003729** If an initial attempt to acquire the lock fails because of lock contention
3730** and the database was previously unlocked, then invoke the busy handler
3731** if there is one. But if there was previously a read-lock, do not
3732** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
3733** returned when there is already a read-lock in order to avoid a deadlock.
3734**
3735** Suppose there are two processes A and B. A has a read lock and B has
3736** a reserved lock. B tries to promote to exclusive but is blocked because
3737** of A's read lock. A tries to promote to reserved but is blocked by B.
3738** One or the other of the two processes must give way or there can be
3739** no progress. By returning SQLITE_BUSY and not invoking the busy callback
3740** when A already has a read lock, we encourage A to give up and let B
3741** proceed.
drha059ad02001-04-17 20:09:11 +00003742*/
drhbb2d9b12018-06-06 16:28:40 +00003743int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
danielk1977aef0bf62005-12-30 16:28:01 +00003744 BtShared *pBt = p->pBt;
dan7bb8b8a2020-05-06 20:27:18 +00003745 Pager *pPager = pBt->pPager;
danielk1977ee5741e2004-05-31 10:01:34 +00003746 int rc = SQLITE_OK;
drh43fa1a52022-12-21 20:07:58 +00003747 int bConcurrent = (p->db->eConcurrent && !ISAUTOVACUUM(pBt));
danielk1977ee5741e2004-05-31 10:01:34 +00003748
drhd677b3d2007-08-20 22:48:41 +00003749 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003750 btreeIntegrity(p);
3751
danielk1977ee5741e2004-05-31 10:01:34 +00003752 /* If the btree is already in a write-transaction, or it
3753 ** is already in a read-transaction and a read-transaction
3754 ** is requested, this is a no-op.
3755 */
danielk1977aef0bf62005-12-30 16:28:01 +00003756 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00003757 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00003758 }
dan56c517a2013-09-26 11:04:33 +00003759 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
drhb8ef32c2005-03-14 02:01:49 +00003760
danea933f02018-07-19 11:44:02 +00003761 if( (p->db->flags & SQLITE_ResetDatabase)
dan7bb8b8a2020-05-06 20:27:18 +00003762 && sqlite3PagerIsreadonly(pPager)==0
danea933f02018-07-19 11:44:02 +00003763 ){
3764 pBt->btsFlags &= ~BTS_READ_ONLY;
3765 }
3766
drhb8ef32c2005-03-14 02:01:49 +00003767 /* Write transactions are not possible on a read-only database */
drhc9166342012-01-05 23:32:06 +00003768 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00003769 rc = SQLITE_READONLY;
3770 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00003771 }
3772
danielk1977404ca072009-03-16 13:19:36 +00003773#ifndef SQLITE_OMIT_SHARED_CACHE
drh5a1fb182016-01-08 19:34:39 +00003774 {
3775 sqlite3 *pBlock = 0;
3776 /* If another database handle has already opened a write transaction
3777 ** on this shared-btree structure and a second write transaction is
3778 ** requested, return SQLITE_LOCKED.
3779 */
3780 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
3781 || (pBt->btsFlags & BTS_PENDING)!=0
3782 ){
3783 pBlock = pBt->pWriter->db;
3784 }else if( wrflag>1 ){
3785 BtLock *pIter;
3786 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
3787 if( pIter->pBtree!=p ){
3788 pBlock = pIter->pBtree->db;
3789 break;
3790 }
danielk1977641b0f42007-12-21 04:47:25 +00003791 }
3792 }
drh5a1fb182016-01-08 19:34:39 +00003793 if( pBlock ){
3794 sqlite3ConnectionBlocked(p->db, pBlock);
3795 rc = SQLITE_LOCKED_SHAREDCACHE;
3796 goto trans_begun;
3797 }
danielk1977404ca072009-03-16 13:19:36 +00003798 }
danielk1977641b0f42007-12-21 04:47:25 +00003799#endif
3800
danielk1977602b4662009-07-02 07:47:33 +00003801 /* Any read-only or read-write transaction implies a read-lock on
3802 ** page 1. So if some other shared-cache client already has a write-lock
3803 ** on page 1, the transaction cannot be opened. */
drh346a70c2020-06-15 20:27:35 +00003804 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
drh4c301aa2009-07-15 17:25:45 +00003805 if( SQLITE_OK!=rc ) goto trans_begun;
danielk1977602b4662009-07-02 07:47:33 +00003806
drhc9166342012-01-05 23:32:06 +00003807 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
3808 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
drhb8ef32c2005-03-14 02:01:49 +00003809 do {
dan11a81822020-05-07 14:26:40 +00003810 sqlite3PagerWalDb(pPager, p->db);
dan58021b22020-05-05 20:30:07 +00003811
3812#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3813 /* If transitioning from no transaction directly to a write transaction,
3814 ** block for the WRITER lock first if possible. */
3815 if( pBt->pPage1==0 && wrflag ){
3816 assert( pBt->inTransaction==TRANS_NONE );
dan861fb1e2020-05-06 19:14:41 +00003817 rc = sqlite3PagerWalWriteLock(pPager, 1);
dan7bb8b8a2020-05-06 20:27:18 +00003818 if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break;
dan58021b22020-05-05 20:30:07 +00003819 }
3820#endif
3821
danielk1977295dc102009-04-01 19:07:03 +00003822 /* Call lockBtree() until either pBt->pPage1 is populated or
3823 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
3824 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
3825 ** reading page 1 it discovers that the page-size of the database
3826 ** file is not pBt->pageSize. In this case lockBtree() will update
3827 ** pBt->pageSize to the page-size of the file on disk.
3828 */
3829 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
drh309169a2007-04-24 17:27:51 +00003830
drhb8ef32c2005-03-14 02:01:49 +00003831 if( rc==SQLITE_OK && wrflag ){
drhc9166342012-01-05 23:32:06 +00003832 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
drh309169a2007-04-24 17:27:51 +00003833 rc = SQLITE_READONLY;
3834 }else{
dan987f8212015-08-27 17:42:38 +00003835 int exFlag = bConcurrent ? -1 : (wrflag>1);
dancf7c1bf2020-05-18 15:41:31 +00003836 rc = sqlite3PagerBegin(pPager, exFlag, sqlite3TempInMemory(p->db));
drh309169a2007-04-24 17:27:51 +00003837 if( rc==SQLITE_OK ){
3838 rc = newDatabase(pBt);
dan8bf6d702018-07-05 17:16:55 +00003839 }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
3840 /* if there was no transaction opened when this function was
3841 ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
3842 ** code to SQLITE_BUSY. */
3843 rc = SQLITE_BUSY;
drh309169a2007-04-24 17:27:51 +00003844 }
drhb8ef32c2005-03-14 02:01:49 +00003845 }
3846 }
3847
danielk1977bd434552009-03-18 10:33:00 +00003848 if( rc!=SQLITE_OK ){
danfc87ab82020-05-06 19:22:59 +00003849 (void)sqlite3PagerWalWriteLock(pPager, 0);
drhb8ef32c2005-03-14 02:01:49 +00003850 unlockBtreeIfUnused(pBt);
3851 }
danf9b76712010-06-01 14:12:45 +00003852 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
danielk19771ceedd32008-11-19 10:22:33 +00003853 btreeInvokeBusyHandler(pBt) );
dan7bb8b8a2020-05-06 20:27:18 +00003854 sqlite3PagerWalDb(pPager, 0);
3855#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3856 if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
3857#endif
danielk1977aef0bf62005-12-30 16:28:01 +00003858
3859 if( rc==SQLITE_OK ){
3860 if( p->inTrans==TRANS_NONE ){
3861 pBt->nTransaction++;
danielk1977602b4662009-07-02 07:47:33 +00003862#ifndef SQLITE_OMIT_SHARED_CACHE
3863 if( p->sharable ){
drhf2f105d2012-08-20 15:53:54 +00003864 assert( p->lock.pBtree==p && p->lock.iTable==1 );
danielk1977602b4662009-07-02 07:47:33 +00003865 p->lock.eLock = READ_LOCK;
3866 p->lock.pNext = pBt->pLock;
3867 pBt->pLock = &p->lock;
3868 }
3869#endif
danielk1977aef0bf62005-12-30 16:28:01 +00003870 }
3871 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
3872 if( p->inTrans>pBt->inTransaction ){
3873 pBt->inTransaction = p->inTrans;
3874 }
danielk1977404ca072009-03-16 13:19:36 +00003875 if( wrflag ){
dan59257dc2010-08-04 11:34:31 +00003876 MemPage *pPage1 = pBt->pPage1;
3877#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977404ca072009-03-16 13:19:36 +00003878 assert( !pBt->pWriter );
3879 pBt->pWriter = p;
drhc9166342012-01-05 23:32:06 +00003880 pBt->btsFlags &= ~BTS_EXCLUSIVE;
3881 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
danielk1977641b0f42007-12-21 04:47:25 +00003882#endif
dan59257dc2010-08-04 11:34:31 +00003883
3884 /* If the db-size header field is incorrect (as it may be if an old
3885 ** client has been writing the database file), update it now. Doing
3886 ** this sooner rather than later means the database size can safely
3887 ** re-read the database size from page 1 if a savepoint or transaction
3888 ** rollback occurs within the transaction.
3889 */
3890 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
3891 rc = sqlite3PagerWrite(pPage1->pDbPage);
3892 if( rc==SQLITE_OK ){
3893 put4byte(&pPage1->aData[28], pBt->nPage);
3894 }
3895 }
3896 }
danielk1977aef0bf62005-12-30 16:28:01 +00003897 }
3898
drhd677b3d2007-08-20 22:48:41 +00003899trans_begun:
drh01be4632015-09-03 15:17:12 +00003900#ifndef SQLITE_OMIT_CONCURRENT
dan987f8212015-08-27 17:42:38 +00003901 if( bConcurrent && rc==SQLITE_OK && sqlite3PagerIsWal(pBt->pPager) ){
3902 rc = sqlite3PagerBeginConcurrent(pBt->pPager);
3903 if( rc==SQLITE_OK && wrflag ){
3904 rc = btreePtrmapAllocate(pBt);
3905 }
3906 }
3907#endif
3908
drhbb2d9b12018-06-06 16:28:40 +00003909 if( rc==SQLITE_OK ){
3910 if( pSchemaVersion ){
3911 *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
3912 }
3913 if( wrflag ){
3914 /* This call makes sure that the pager has the correct number of
3915 ** open savepoints. If the second parameter is greater than 0 and
3916 ** the sub-journal is not already open, then it will be opened here.
3917 */
drh0c1fa5c2018-06-06 17:03:53 +00003918 int nSavepoint = p->db->nSavepoint;
dancf7c1bf2020-05-18 15:41:31 +00003919 rc = sqlite3PagerOpenSavepoint(pPager, nSavepoint);
drh0c1fa5c2018-06-06 17:03:53 +00003920 if( rc==SQLITE_OK && nSavepoint ){
3921 rc = btreePtrmapBegin(pBt, nSavepoint);
3922 }
dan7b3d71e2015-08-19 20:27:05 +00003923 }
danielk1977fd7f0452008-12-17 17:30:26 +00003924 }
danielk197712dd5492008-12-18 15:45:07 +00003925
danielk1977aef0bf62005-12-30 16:28:01 +00003926 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00003927 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00003928 return rc;
drha059ad02001-04-17 20:09:11 +00003929}
3930
danielk1977687566d2004-11-02 12:56:41 +00003931#ifndef SQLITE_OMIT_AUTOVACUUM
3932
3933/*
3934** Set the pointer-map entries for all children of page pPage. Also, if
3935** pPage contains cells that point to overflow pages, set the pointer
3936** map entries for the overflow pages as well.
3937*/
3938static int setChildPtrmaps(MemPage *pPage){
3939 int i; /* Counter variable */
3940 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00003941 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00003942 BtShared *pBt = pPage->pBt;
danielk1977687566d2004-11-02 12:56:41 +00003943 Pgno pgno = pPage->pgno;
3944
drh1fee73e2007-08-29 04:00:57 +00003945 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh14e845a2017-05-25 21:35:56 +00003946 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
drh2a702542016-12-12 18:12:03 +00003947 if( rc!=SQLITE_OK ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00003948 nCell = pPage->nCell;
3949
3950 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00003951 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00003952
drh0f1bf4c2019-01-13 20:17:21 +00003953 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);
danielk197726836652005-01-17 01:33:13 +00003954
danielk1977687566d2004-11-02 12:56:41 +00003955 if( !pPage->leaf ){
3956 Pgno childPgno = get4byte(pCell);
drh98add2e2009-07-20 17:11:49 +00003957 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00003958 }
3959 }
3960
3961 if( !pPage->leaf ){
3962 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh98add2e2009-07-20 17:11:49 +00003963 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00003964 }
3965
danielk1977687566d2004-11-02 12:56:41 +00003966 return rc;
3967}
3968
3969/*
drhf3aed592009-07-08 18:12:49 +00003970** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
3971** that it points to iTo. Parameter eType describes the type of pointer to
3972** be modified, as follows:
danielk1977687566d2004-11-02 12:56:41 +00003973**
3974** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
3975** page of pPage.
3976**
3977** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3978** page pointed to by one of the cells on pPage.
3979**
3980** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3981** overflow page in the list.
3982*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00003983static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00003984 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00003985 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977687566d2004-11-02 12:56:41 +00003986 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00003987 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00003988 if( get4byte(pPage->aData)!=iFrom ){
daneebf2f52017-11-18 17:30:08 +00003989 return SQLITE_CORRUPT_PAGE(pPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003990 }
danielk1977f78fc082004-11-02 14:40:32 +00003991 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00003992 }else{
danielk1977687566d2004-11-02 12:56:41 +00003993 int i;
3994 int nCell;
drha1f75d92015-05-24 10:18:12 +00003995 int rc;
danielk1977687566d2004-11-02 12:56:41 +00003996
drh14e845a2017-05-25 21:35:56 +00003997 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
drha1f75d92015-05-24 10:18:12 +00003998 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00003999 nCell = pPage->nCell;
4000
danielk1977687566d2004-11-02 12:56:41 +00004001 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00004002 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00004003 if( eType==PTRMAP_OVERFLOW1 ){
4004 CellInfo info;
drh5fa60512015-06-19 17:19:34 +00004005 pPage->xParseCell(pPage, pCell, &info);
drhb701c9a2017-01-12 15:11:03 +00004006 if( info.nLocal<info.nPayload ){
4007 if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
daneebf2f52017-11-18 17:30:08 +00004008 return SQLITE_CORRUPT_PAGE(pPage);
drhb701c9a2017-01-12 15:11:03 +00004009 }
4010 if( iFrom==get4byte(pCell+info.nSize-4) ){
4011 put4byte(pCell+info.nSize-4, iTo);
4012 break;
4013 }
danielk1977687566d2004-11-02 12:56:41 +00004014 }
4015 }else{
drh005c9d82022-10-10 12:02:53 +00004016 if( pCell+4 > pPage->aData+pPage->pBt->usableSize ){
4017 return SQLITE_CORRUPT_PAGE(pPage);
4018 }
danielk1977687566d2004-11-02 12:56:41 +00004019 if( get4byte(pCell)==iFrom ){
4020 put4byte(pCell, iTo);
4021 break;
4022 }
4023 }
4024 }
4025
4026 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00004027 if( eType!=PTRMAP_BTREE ||
4028 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
daneebf2f52017-11-18 17:30:08 +00004029 return SQLITE_CORRUPT_PAGE(pPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00004030 }
danielk1977687566d2004-11-02 12:56:41 +00004031 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
4032 }
danielk1977687566d2004-11-02 12:56:41 +00004033 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00004034 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00004035}
4036
danielk1977003ba062004-11-04 02:57:33 +00004037
danielk19777701e812005-01-10 12:59:51 +00004038/*
4039** Move the open database page pDbPage to location iFreePage in the
4040** database. The pDbPage reference remains valid.
drhe64ca7b2009-07-16 18:21:17 +00004041**
4042** The isCommit flag indicates that there is no need to remember that
4043** the journal needs to be sync()ed before database page pDbPage->pgno
4044** can be written to. The caller has already promised not to write to that
4045** page.
danielk19777701e812005-01-10 12:59:51 +00004046*/
danielk1977003ba062004-11-04 02:57:33 +00004047static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00004048 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00004049 MemPage *pDbPage, /* Open page to move */
4050 u8 eType, /* Pointer map 'type' entry for pDbPage */
4051 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00004052 Pgno iFreePage, /* The location to move pDbPage to */
drhe64ca7b2009-07-16 18:21:17 +00004053 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
danielk1977003ba062004-11-04 02:57:33 +00004054){
4055 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
4056 Pgno iDbPage = pDbPage->pgno;
4057 Pager *pPager = pBt->pPager;
4058 int rc;
4059
danielk1977a0bf2652004-11-04 14:30:04 +00004060 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
4061 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00004062 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00004063 assert( pDbPage->pBt==pBt );
drh49272bc2018-10-31 01:04:18 +00004064 if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
danielk1977003ba062004-11-04 02:57:33 +00004065
drh85b623f2007-12-13 21:54:09 +00004066 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00004067 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
4068 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00004069 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00004070 if( rc!=SQLITE_OK ){
4071 return rc;
4072 }
4073 pDbPage->pgno = iFreePage;
4074
4075 /* If pDbPage was a btree-page, then it may have child pages and/or cells
4076 ** that point to overflow pages. The pointer map entries for all these
4077 ** pages need to be changed.
4078 **
4079 ** If pDbPage is an overflow page, then the first 4 bytes may store a
4080 ** pointer to a subsequent overflow page. If this is the case, then
4081 ** the pointer map needs to be updated for the subsequent overflow page.
4082 */
danielk1977a0bf2652004-11-04 14:30:04 +00004083 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00004084 rc = setChildPtrmaps(pDbPage);
4085 if( rc!=SQLITE_OK ){
4086 return rc;
4087 }
4088 }else{
4089 Pgno nextOvfl = get4byte(pDbPage->aData);
4090 if( nextOvfl!=0 ){
drh98add2e2009-07-20 17:11:49 +00004091 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
danielk1977003ba062004-11-04 02:57:33 +00004092 if( rc!=SQLITE_OK ){
4093 return rc;
4094 }
4095 }
4096 }
4097
4098 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
4099 ** that it points at iFreePage. Also fix the pointer map entry for
4100 ** iPtrPage.
4101 */
danielk1977a0bf2652004-11-04 14:30:04 +00004102 if( eType!=PTRMAP_ROOTPAGE ){
drhb00fc3b2013-08-21 23:42:32 +00004103 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00004104 if( rc!=SQLITE_OK ){
4105 return rc;
4106 }
danielk19773b8a05f2007-03-19 17:44:26 +00004107 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00004108 if( rc!=SQLITE_OK ){
4109 releasePage(pPtrPage);
4110 return rc;
4111 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00004112 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00004113 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00004114 if( rc==SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00004115 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
danielk1977fdb7cdb2005-01-17 02:12:18 +00004116 }
danielk1977003ba062004-11-04 02:57:33 +00004117 }
danielk1977003ba062004-11-04 02:57:33 +00004118 return rc;
4119}
4120
danielk1977dddbcdc2007-04-26 14:42:34 +00004121/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00004122static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00004123
4124/*
dan51f0b6d2013-02-22 20:16:34 +00004125** Perform a single step of an incremental-vacuum. If successful, return
4126** SQLITE_OK. If there is no work to do (and therefore no point in
4127** calling this function again), return SQLITE_DONE. Or, if an error
4128** occurs, return some other error code.
danielk1977dddbcdc2007-04-26 14:42:34 +00004129**
peter.d.reid60ec9142014-09-06 16:39:46 +00004130** More specifically, this function attempts to re-organize the database so
dan51f0b6d2013-02-22 20:16:34 +00004131** that the last page of the file currently in use is no longer in use.
danielk1977dddbcdc2007-04-26 14:42:34 +00004132**
dan51f0b6d2013-02-22 20:16:34 +00004133** Parameter nFin is the number of pages that this database would contain
4134** were this function called until it returns SQLITE_DONE.
4135**
4136** If the bCommit parameter is non-zero, this function assumes that the
4137** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
peter.d.reid60ec9142014-09-06 16:39:46 +00004138** or an error. bCommit is passed true for an auto-vacuum-on-commit
dan51f0b6d2013-02-22 20:16:34 +00004139** operation, or false for an incremental vacuum.
danielk1977dddbcdc2007-04-26 14:42:34 +00004140*/
dan51f0b6d2013-02-22 20:16:34 +00004141static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
danielk1977dddbcdc2007-04-26 14:42:34 +00004142 Pgno nFreeList; /* Number of pages still on the free-list */
drhdd3cd972010-03-27 17:12:36 +00004143 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00004144
drh1fee73e2007-08-29 04:00:57 +00004145 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977fa542f12009-04-02 18:28:08 +00004146 assert( iLastPg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00004147
4148 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
danielk1977dddbcdc2007-04-26 14:42:34 +00004149 u8 eType;
4150 Pgno iPtrPage;
4151
4152 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977fa542f12009-04-02 18:28:08 +00004153 if( nFreeList==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00004154 return SQLITE_DONE;
4155 }
4156
4157 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
4158 if( rc!=SQLITE_OK ){
4159 return rc;
4160 }
4161 if( eType==PTRMAP_ROOTPAGE ){
4162 return SQLITE_CORRUPT_BKPT;
4163 }
4164
4165 if( eType==PTRMAP_FREEPAGE ){
dan51f0b6d2013-02-22 20:16:34 +00004166 if( bCommit==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00004167 /* Remove the page from the files free-list. This is not required
dan51f0b6d2013-02-22 20:16:34 +00004168 ** if bCommit is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00004169 ** truncated to zero after this function returns, so it doesn't
4170 ** matter if it still contains some garbage entries.
4171 */
4172 Pgno iFreePg;
4173 MemPage *pFreePg;
dan51f0b6d2013-02-22 20:16:34 +00004174 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
danielk1977dddbcdc2007-04-26 14:42:34 +00004175 if( rc!=SQLITE_OK ){
4176 return rc;
4177 }
4178 assert( iFreePg==iLastPg );
4179 releasePage(pFreePg);
4180 }
4181 } else {
4182 Pgno iFreePg; /* Index of free page to move pLastPg to */
4183 MemPage *pLastPg;
dan51f0b6d2013-02-22 20:16:34 +00004184 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
4185 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
danielk1977dddbcdc2007-04-26 14:42:34 +00004186
drhb00fc3b2013-08-21 23:42:32 +00004187 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00004188 if( rc!=SQLITE_OK ){
4189 return rc;
4190 }
4191
dan51f0b6d2013-02-22 20:16:34 +00004192 /* If bCommit is zero, this loop runs exactly once and page pLastPg
danielk1977b4626a32007-04-28 15:47:43 +00004193 ** is swapped with the first free page pulled off the free list.
4194 **
dan51f0b6d2013-02-22 20:16:34 +00004195 ** On the other hand, if bCommit is greater than zero, then keep
danielk1977b4626a32007-04-28 15:47:43 +00004196 ** looping until a free-page located within the first nFin pages
4197 ** of the file is found.
4198 */
dan51f0b6d2013-02-22 20:16:34 +00004199 if( bCommit==0 ){
4200 eMode = BTALLOC_LE;
4201 iNear = nFin;
4202 }
danielk1977dddbcdc2007-04-26 14:42:34 +00004203 do {
4204 MemPage *pFreePg;
drhdba3a5a2022-06-15 14:57:04 +00004205 Pgno dbSize = btreePagecount(pBt);
dan51f0b6d2013-02-22 20:16:34 +00004206 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
danielk1977dddbcdc2007-04-26 14:42:34 +00004207 if( rc!=SQLITE_OK ){
4208 releasePage(pLastPg);
4209 return rc;
4210 }
4211 releasePage(pFreePg);
drhdba3a5a2022-06-15 14:57:04 +00004212 if( iFreePg>dbSize ){
4213 releasePage(pLastPg);
4214 return SQLITE_CORRUPT_BKPT;
4215 }
dan51f0b6d2013-02-22 20:16:34 +00004216 }while( bCommit && iFreePg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00004217 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00004218
dane1df4e32013-03-05 11:27:04 +00004219 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
danielk1977dddbcdc2007-04-26 14:42:34 +00004220 releasePage(pLastPg);
4221 if( rc!=SQLITE_OK ){
4222 return rc;
danielk1977662278e2007-11-05 15:30:12 +00004223 }
danielk1977dddbcdc2007-04-26 14:42:34 +00004224 }
4225 }
4226
dan51f0b6d2013-02-22 20:16:34 +00004227 if( bCommit==0 ){
danbc1a3c62013-02-23 16:40:46 +00004228 do {
danielk19773460d192008-12-27 15:23:13 +00004229 iLastPg--;
danbc1a3c62013-02-23 16:40:46 +00004230 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
4231 pBt->bDoTruncate = 1;
drhdd3cd972010-03-27 17:12:36 +00004232 pBt->nPage = iLastPg;
danielk1977dddbcdc2007-04-26 14:42:34 +00004233 }
4234 return SQLITE_OK;
4235}
4236
4237/*
dan51f0b6d2013-02-22 20:16:34 +00004238** The database opened by the first argument is an auto-vacuum database
4239** nOrig pages in size containing nFree free pages. Return the expected
4240** size of the database in pages following an auto-vacuum operation.
4241*/
4242static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
4243 int nEntry; /* Number of entries on one ptrmap page */
4244 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
4245 Pgno nFin; /* Return value */
4246
4247 nEntry = pBt->usableSize/5;
4248 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
4249 nFin = nOrig - nFree - nPtrmap;
4250 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
4251 nFin--;
4252 }
4253 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
4254 nFin--;
4255 }
dan51f0b6d2013-02-22 20:16:34 +00004256
4257 return nFin;
4258}
4259
4260/*
danielk1977dddbcdc2007-04-26 14:42:34 +00004261** A write-transaction must be opened before calling this function.
4262** It performs a single unit of work towards an incremental vacuum.
4263**
4264** If the incremental vacuum is finished after this function has run,
shanebe217792009-03-05 04:20:31 +00004265** SQLITE_DONE is returned. If it is not finished, but no error occurred,
danielk1977dddbcdc2007-04-26 14:42:34 +00004266** SQLITE_OK is returned. Otherwise an SQLite error code.
4267*/
4268int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00004269 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00004270 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00004271
4272 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00004273 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
4274 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00004275 rc = SQLITE_DONE;
4276 }else{
dan51f0b6d2013-02-22 20:16:34 +00004277 Pgno nOrig = btreePagecount(pBt);
4278 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
4279 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
4280
drhbc2cf3b2020-07-14 12:40:53 +00004281 if( nOrig<nFin || nFree>=nOrig ){
dan91384712013-02-24 11:50:43 +00004282 rc = SQLITE_CORRUPT_BKPT;
4283 }else if( nFree>0 ){
dan11dcd112013-03-15 18:29:18 +00004284 rc = saveAllCursors(pBt, 0, 0);
4285 if( rc==SQLITE_OK ){
4286 invalidateAllOverflowCache(pBt);
4287 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
4288 }
dan51f0b6d2013-02-22 20:16:34 +00004289 if( rc==SQLITE_OK ){
4290 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
4291 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
4292 }
4293 }else{
4294 rc = SQLITE_DONE;
drhdd3cd972010-03-27 17:12:36 +00004295 }
danielk1977dddbcdc2007-04-26 14:42:34 +00004296 }
drhd677b3d2007-08-20 22:48:41 +00004297 sqlite3BtreeLeave(p);
4298 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00004299}
4300
4301/*
danielk19773b8a05f2007-03-19 17:44:26 +00004302** This routine is called prior to sqlite3PagerCommit when a transaction
drhf7b54962013-05-28 12:11:54 +00004303** is committed for an auto-vacuum database.
danielk1977687566d2004-11-02 12:56:41 +00004304*/
drh1bbfc672021-10-15 23:02:27 +00004305static int autoVacuumCommit(Btree *p){
danielk1977dddbcdc2007-04-26 14:42:34 +00004306 int rc = SQLITE_OK;
drh1bbfc672021-10-15 23:02:27 +00004307 Pager *pPager;
4308 BtShared *pBt;
4309 sqlite3 *db;
4310 VVA_ONLY( int nRef );
4311
4312 assert( p!=0 );
4313 pBt = p->pBt;
4314 pPager = pBt->pPager;
4315 VVA_ONLY( nRef = sqlite3PagerRefcount(pPager); )
danielk1977687566d2004-11-02 12:56:41 +00004316
drh1fee73e2007-08-29 04:00:57 +00004317 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00004318 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00004319 assert(pBt->autoVacuum);
4320 if( !pBt->incrVacuum ){
drhea8ffdf2009-07-22 00:35:23 +00004321 Pgno nFin; /* Number of pages in database after autovacuuming */
4322 Pgno nFree; /* Number of pages on the freelist initially */
drh1bbfc672021-10-15 23:02:27 +00004323 Pgno nVac; /* Number of pages to vacuum */
drh41d628c2009-07-11 17:04:08 +00004324 Pgno iFree; /* The next page to be freed */
drh41d628c2009-07-11 17:04:08 +00004325 Pgno nOrig; /* Database size before freeing */
danielk1977687566d2004-11-02 12:56:41 +00004326
drhb1299152010-03-30 22:58:33 +00004327 nOrig = btreePagecount(pBt);
danielk1977ef165ce2009-04-06 17:50:03 +00004328 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
4329 /* It is not possible to create a database for which the final page
4330 ** is either a pointer-map page or the pending-byte page. If one
4331 ** is encountered, this indicates corruption.
4332 */
danielk19773460d192008-12-27 15:23:13 +00004333 return SQLITE_CORRUPT_BKPT;
4334 }
danielk1977ef165ce2009-04-06 17:50:03 +00004335
danielk19773460d192008-12-27 15:23:13 +00004336 nFree = get4byte(&pBt->pPage1->aData[36]);
drh1bbfc672021-10-15 23:02:27 +00004337 db = p->db;
4338 if( db->xAutovacPages ){
4339 int iDb;
4340 for(iDb=0; ALWAYS(iDb<db->nDb); iDb++){
4341 if( db->aDb[iDb].pBt==p ) break;
4342 }
4343 nVac = db->xAutovacPages(
4344 db->pAutovacPagesArg,
4345 db->aDb[iDb].zDbSName,
4346 nOrig,
4347 nFree,
4348 pBt->pageSize
4349 );
4350 if( nVac>nFree ){
4351 nVac = nFree;
4352 }
4353 if( nVac==0 ){
4354 return SQLITE_OK;
4355 }
4356 }else{
4357 nVac = nFree;
4358 }
4359 nFin = finalDbSize(pBt, nOrig, nVac);
drhc5e47ac2009-06-04 00:11:56 +00004360 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
dan0aed84d2013-03-26 14:16:20 +00004361 if( nFin<nOrig ){
4362 rc = saveAllCursors(pBt, 0, 0);
4363 }
danielk19773460d192008-12-27 15:23:13 +00004364 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
drh1bbfc672021-10-15 23:02:27 +00004365 rc = incrVacuumStep(pBt, nFin, iFree, nVac==nFree);
danielk1977dddbcdc2007-04-26 14:42:34 +00004366 }
danielk19773460d192008-12-27 15:23:13 +00004367 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
danielk19773460d192008-12-27 15:23:13 +00004368 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
drh1bbfc672021-10-15 23:02:27 +00004369 if( nVac==nFree ){
4370 put4byte(&pBt->pPage1->aData[32], 0);
4371 put4byte(&pBt->pPage1->aData[36], 0);
4372 }
drhdd3cd972010-03-27 17:12:36 +00004373 put4byte(&pBt->pPage1->aData[28], nFin);
danbc1a3c62013-02-23 16:40:46 +00004374 pBt->bDoTruncate = 1;
drhdd3cd972010-03-27 17:12:36 +00004375 pBt->nPage = nFin;
danielk1977dddbcdc2007-04-26 14:42:34 +00004376 }
4377 if( rc!=SQLITE_OK ){
4378 sqlite3PagerRollback(pPager);
4379 }
danielk1977687566d2004-11-02 12:56:41 +00004380 }
4381
dan0aed84d2013-03-26 14:16:20 +00004382 assert( nRef>=sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00004383 return rc;
4384}
danielk1977dddbcdc2007-04-26 14:42:34 +00004385
danielk1977a50d9aa2009-06-08 14:49:45 +00004386#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
4387# define setChildPtrmaps(x) SQLITE_OK
4388#endif
danielk1977687566d2004-11-02 12:56:41 +00004389
drh01be4632015-09-03 15:17:12 +00004390#ifndef SQLITE_OMIT_CONCURRENT
danielk1977687566d2004-11-02 12:56:41 +00004391/*
danbf3cf572015-08-24 19:56:04 +00004392** This function is called as part of merging an CONCURRENT transaction with
dan5cf03722015-08-24 10:05:03 +00004393** the snapshot at the head of the wal file. It relocates all pages in the
4394** range iFirst..iLast, inclusive. It is assumed that the BtreePtrmap
4395** structure at BtShared.pMap contains the location of the pointers to each
4396** page in the range.
4397**
4398** If pnCurrent is NULL, then all pages in the range are moved to currently
4399** free locations (i.e. free-list entries) within the database file before page
4400** iFirst.
4401**
4402** Or, if pnCurrent is not NULL, then it points to a value containing the
4403** current size of the database file in pages. In this case, all pages are
4404** relocated to the end of the database file - page iFirst is relocated to
4405** page (*pnCurrent+1), page iFirst+1 to page (*pnCurrent+2), and so on.
4406** Value *pnCurrent is set to the new size of the database before this
4407** function returns.
4408**
4409** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error code.
4410*/
4411static int btreeRelocateRange(
4412 BtShared *pBt, /* B-tree handle */
4413 Pgno iFirst, /* First page to relocate */
4414 Pgno iLast, /* Last page to relocate */
4415 Pgno *pnCurrent /* If not NULL, IN/OUT: Database size */
4416){
4417 int rc = SQLITE_OK;
4418 BtreePtrmap *pMap = pBt->pMap;
4419 Pgno iPg;
4420
4421 for(iPg=iFirst; iPg<=iLast && rc==SQLITE_OK; iPg++){
4422 MemPage *pFree = 0; /* Page allocated from free-list */
4423 MemPage *pPg = 0;
4424 Pgno iNew; /* New page number for pPg */
4425 PtrmapEntry *pEntry; /* Pointer map entry for page iPg */
4426
4427 if( iPg==PENDING_BYTE_PAGE(pBt) ) continue;
4428 pEntry = &pMap->aPtr[iPg - pMap->iFirst];
4429
4430 if( pEntry->eType==PTRMAP_FREEPAGE ){
4431 Pgno dummy;
4432 rc = allocateBtreePage(pBt, &pFree, &dummy, iPg, BTALLOC_EXACT);
dan51883df2018-12-03 19:29:37 +00004433 if( pFree ){
4434 assert( sqlite3PagerPageRefcount(pFree->pDbPage)==1 );
4435 sqlite3PcacheDrop(pFree->pDbPage);
4436 }
dan5cf03722015-08-24 10:05:03 +00004437 assert( rc!=SQLITE_OK || dummy==iPg );
4438 }else if( pnCurrent ){
4439 btreeGetPage(pBt, iPg, &pPg, 0);
4440 assert( sqlite3PagerIswriteable(pPg->pDbPage) );
4441 assert( sqlite3PagerPageRefcount(pPg->pDbPage)==1 );
4442 iNew = ++(*pnCurrent);
4443 if( iNew==PENDING_BYTE_PAGE(pBt) ) iNew = ++(*pnCurrent);
4444 rc = relocatePage(pBt, pPg, pEntry->eType, pEntry->parent, iNew, 1);
4445 releasePageNotNull(pPg);
4446 }else{
4447 rc = allocateBtreePage(pBt, &pFree, &iNew, iFirst-1, BTALLOC_LE);
4448 assert( rc!=SQLITE_OK || iNew<iFirst );
dan5cf03722015-08-24 10:05:03 +00004449 if( rc==SQLITE_OK ){
danac0a4222015-08-25 14:37:39 +00004450 releasePage(pFree);
dan5cf03722015-08-24 10:05:03 +00004451 btreeGetPage(pBt, iPg, &pPg, 0);
4452 rc = relocatePage(pBt, pPg, pEntry->eType, pEntry->parent,iNew,1);
4453 releasePage(pPg);
4454 }
4455 }
4456 }
4457 return rc;
4458}
4459
drh01be4632015-09-03 15:17:12 +00004460/* !defined(SQLITE_OMIT_CONCURRENT)
4461**
dan7b3d71e2015-08-19 20:27:05 +00004462** The b-tree handle passed as the only argument is about to commit an
danbf3cf572015-08-24 19:56:04 +00004463** CONCURRENT transaction. At this point it is guaranteed that this is
dan7b3d71e2015-08-19 20:27:05 +00004464** possible - the wal WRITER lock is held and it is known that there are
4465** no conflicts with committed transactions.
4466*/
4467static int btreeFixUnlocked(Btree *p){
4468 BtShared *pBt = p->pBt;
4469 MemPage *pPage1 = pBt->pPage1;
4470 u8 *p1 = pPage1->aData;
4471 Pager *pPager = pBt->pPager;
4472 int rc = SQLITE_OK;
4473
4474 /* If page 1 of the database is not writable, then no pages were allocated
4475 ** or freed by this transaction. In this case no special handling is
4476 ** required. Otherwise, if page 1 is dirty, proceed. */
4477 BtreePtrmap *pMap = pBt->pMap;
4478 Pgno iTrunk = get4byte(&p1[32]);
4479 Pgno nPage = btreePagecount(pBt);
dan7b3d71e2015-08-19 20:27:05 +00004480 u32 nFree = get4byte(&p1[36]);
4481
dan7b3d71e2015-08-19 20:27:05 +00004482 assert( pBt->pMap );
4483 rc = sqlite3PagerUpgradeSnapshot(pPager, pPage1->pDbPage);
4484 assert( p1==pPage1->aData );
4485
4486 if( rc==SQLITE_OK ){
4487 Pgno nHPage = get4byte(&p1[28]);
dan5cf03722015-08-24 10:05:03 +00004488 Pgno nFin = nHPage; /* Size of db after transaction merge */
dan7b3d71e2015-08-19 20:27:05 +00004489
4490 if( sqlite3PagerIswriteable(pPage1->pDbPage) ){
4491 Pgno iHTrunk = get4byte(&p1[32]);
4492 u32 nHFree = get4byte(&p1[36]);
4493
dan51883df2018-12-03 19:29:37 +00004494 btreePtrmapCheck(pBt, nPage);
4495
dan7b3d71e2015-08-19 20:27:05 +00004496 /* Attach the head database free list to the end of the current
4497 ** transactions free-list (if any). */
4498 if( iTrunk!=0 ){
4499 put4byte(&p1[36], nHFree + nFree);
4500 put4byte(&p1[32], iTrunk);
4501 while( iTrunk ){
4502 DbPage *pTrunk = sqlite3PagerLookup(pPager, iTrunk);
4503 iTrunk = get4byte((u8*)pTrunk->pData);
4504 if( iTrunk==0 ){
4505 put4byte((u8*)pTrunk->pData, iHTrunk);
4506 }
4507 sqlite3PagerUnref(pTrunk);
4508 };
4509 }
4510
dan572a21c2015-08-21 18:55:22 +00004511 if( nHPage<(pMap->iFirst-1) ){
4512 /* The database consisted of (pMap->iFirst-1) pages when the current
danbf3cf572015-08-24 19:56:04 +00004513 ** concurrent transaction was opened. And an concurrent transaction may
dan572a21c2015-08-21 18:55:22 +00004514 ** not be executed on an auto-vacuum database - so the db should
4515 ** not have shrunk since the transaction was opened. Therefore nHPage
4516 ** should be set to (pMap->iFirst-1) or greater. */
dan7b3d71e2015-08-19 20:27:05 +00004517 rc = SQLITE_CORRUPT_BKPT;
4518 }else{
4519 /* The current transaction allocated pages pMap->iFirst through
4520 ** nPage (inclusive) at the end of the database file. Meanwhile,
4521 ** other transactions have allocated (iFirst..nHPage). So move
dan51883df2018-12-03 19:29:37 +00004522 ** pages (iFirst..MIN(nPage,nHPage)) to (MAX(nPage,nHPage)+1). */
dan7b3d71e2015-08-19 20:27:05 +00004523 Pgno iLast = MIN(nPage, nHPage); /* Last page to move */
dan572a21c2015-08-21 18:55:22 +00004524 Pgno nCurrent; /* Current size of db */
dan51883df2018-12-03 19:29:37 +00004525
dan572a21c2015-08-21 18:55:22 +00004526 nCurrent = MAX(nPage, nHPage);
dan51883df2018-12-03 19:29:37 +00004527 pBt->nPage = nCurrent;
dan5cf03722015-08-24 10:05:03 +00004528 rc = btreeRelocateRange(pBt, pMap->iFirst, iLast, &nCurrent);
danb87b25f2015-08-21 20:11:23 +00004529
dan5cf03722015-08-24 10:05:03 +00004530 /* There are now no collisions with the snapshot at the head of the
4531 ** database file. So at this point it would be possible to write
4532 ** the transaction out to disk. Before doing so though, attempt to
4533 ** relocate some of the new pages to free locations within the body
4534 ** of the database file (i.e. free-list entries). */
4535 if( rc==SQLITE_OK ){
4536 assert( nCurrent!=PENDING_BYTE_PAGE(pBt) );
4537 sqlite3PagerSetDbsize(pBt->pPager, nCurrent);
4538 nFree = get4byte(&p1[36]);
dane3c3be82017-05-25 21:02:00 +00004539 nFin = nCurrent-nFree;
dan5cf03722015-08-24 10:05:03 +00004540 if( nCurrent>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
4541 nFin--;
dan70af25d2015-08-21 17:57:16 +00004542 }
dane3c3be82017-05-25 21:02:00 +00004543 nFin = MAX(nFin, nHPage);
dan5cf03722015-08-24 10:05:03 +00004544 rc = btreeRelocateRange(pBt, nFin+1, nCurrent, 0);
danf5cebf72015-08-22 17:28:55 +00004545 }
dan572a21c2015-08-21 18:55:22 +00004546
dan5cf03722015-08-24 10:05:03 +00004547 put4byte(&p1[28], nFin);
dan7b3d71e2015-08-19 20:27:05 +00004548 }
4549 }
dan5cf03722015-08-24 10:05:03 +00004550 sqlite3PagerSetDbsize(pPager, nFin);
dan7b3d71e2015-08-19 20:27:05 +00004551 }
4552
4553 return rc;
4554}
drh3f531da2015-09-01 17:48:54 +00004555#else
4556# define btreeFixUnlocked(X) SQLITE_OK
drh01be4632015-09-03 15:17:12 +00004557#endif /* SQLITE_OMIT_CONCURRENT */
dan7b3d71e2015-08-19 20:27:05 +00004558
4559/*
drh80e35f42007-03-30 14:06:34 +00004560** This routine does the first phase of a two-phase commit. This routine
4561** causes a rollback journal to be created (if it does not already exist)
4562** and populated with enough information so that if a power loss occurs
4563** the database can be restored to its original state by playing back
4564** the journal. Then the contents of the journal are flushed out to
4565** the disk. After the journal is safely on oxide, the changes to the
4566** database are written into the database file and flushed to oxide.
4567** At the end of this call, the rollback journal still exists on the
4568** disk and we are still holding all locks, so the transaction has not
drh51898cf2009-04-19 20:51:06 +00004569** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
drh80e35f42007-03-30 14:06:34 +00004570** commit process.
4571**
4572** This call is a no-op if no write-transaction is currently active on pBt.
4573**
drh067b92b2020-06-19 15:24:12 +00004574** Otherwise, sync the database file for the btree pBt. zSuperJrnl points to
4575** the name of a super-journal file that should be written into the
4576** individual journal file, or is NULL, indicating no super-journal file
drh80e35f42007-03-30 14:06:34 +00004577** (single database transaction).
4578**
drh067b92b2020-06-19 15:24:12 +00004579** When this is called, the super-journal should already have been
drh80e35f42007-03-30 14:06:34 +00004580** created, populated with this journal pointer and synced to disk.
4581**
4582** Once this is routine has returned, the only thing required to commit
4583** the write-transaction for this database file is to delete the journal.
4584*/
drh067b92b2020-06-19 15:24:12 +00004585int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){
drh80e35f42007-03-30 14:06:34 +00004586 int rc = SQLITE_OK;
4587 if( p->inTrans==TRANS_WRITE ){
4588 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00004589 sqlite3BtreeEnter(p);
dan3d394342015-07-27 19:31:45 +00004590
drh80e35f42007-03-30 14:06:34 +00004591#ifndef SQLITE_OMIT_AUTOVACUUM
dan7b3d71e2015-08-19 20:27:05 +00004592 if( pBt->autoVacuum ){
danbf3cf572015-08-24 19:56:04 +00004593 assert( ISCONCURRENT==0 );
drh1bbfc672021-10-15 23:02:27 +00004594 rc = autoVacuumCommit(p);
drh80e35f42007-03-30 14:06:34 +00004595 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00004596 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00004597 return rc;
4598 }
4599 }
danbc1a3c62013-02-23 16:40:46 +00004600 if( pBt->bDoTruncate ){
4601 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
4602 }
drh80e35f42007-03-30 14:06:34 +00004603#endif
dan9a477712020-07-16 20:24:11 +00004604 if( rc==SQLITE_OK && ISCONCURRENT && p->db->eConcurrent==CONCURRENT_OPEN ){
dan7b3d71e2015-08-19 20:27:05 +00004605 rc = btreeFixUnlocked(p);
4606 }
dan3d394342015-07-27 19:31:45 +00004607 if( rc==SQLITE_OK ){
dan1098bdb2020-07-30 19:19:12 +00004608 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0);
dan3d394342015-07-27 19:31:45 +00004609 }
drhd677b3d2007-08-20 22:48:41 +00004610 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00004611 }
4612 return rc;
4613}
4614
4615/*
danielk197794b30732009-07-02 17:21:57 +00004616** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
4617** at the conclusion of a transaction.
4618*/
4619static void btreeEndTransaction(Btree *p){
4620 BtShared *pBt = p->pBt;
drh1713afb2013-06-28 01:24:57 +00004621 sqlite3 *db = p->db;
danielk197794b30732009-07-02 17:21:57 +00004622 assert( sqlite3BtreeHoldsMutex(p) );
4623
danbc1a3c62013-02-23 16:40:46 +00004624#ifndef SQLITE_OMIT_AUTOVACUUM
4625 pBt->bDoTruncate = 0;
4626#endif
danc0537fe2013-06-28 19:41:43 +00004627 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
danfa401de2009-10-16 14:55:03 +00004628 /* If there are other active statements that belong to this database
4629 ** handle, downgrade to a read-only transaction. The other statements
4630 ** may still be reading from the database. */
danielk197794b30732009-07-02 17:21:57 +00004631 downgradeAllSharedCacheTableLocks(p);
4632 p->inTrans = TRANS_READ;
4633 }else{
4634 /* If the handle had any kind of transaction open, decrement the
4635 ** transaction count of the shared btree. If the transaction count
4636 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
4637 ** call below will unlock the pager. */
4638 if( p->inTrans!=TRANS_NONE ){
4639 clearAllSharedCacheTableLocks(p);
4640 pBt->nTransaction--;
4641 if( 0==pBt->nTransaction ){
4642 pBt->inTransaction = TRANS_NONE;
4643 }
4644 }
4645
4646 /* Set the current transaction state to TRANS_NONE and unlock the
4647 ** pager if this call closed the only read or write transaction. */
4648 p->inTrans = TRANS_NONE;
4649 unlockBtreeIfUnused(pBt);
4650 }
4651
dan987f8212015-08-27 17:42:38 +00004652 /* If this was an CONCURRENT transaction, delete the pBt->pMap object.
4653 ** Also call PagerEndConcurrent() to ensure that the pager has discarded
4654 ** the record of all pages read within the transaction. */
danf5cebf72015-08-22 17:28:55 +00004655 btreePtrmapDelete(pBt);
dan987f8212015-08-27 17:42:38 +00004656 sqlite3PagerEndConcurrent(pBt->pPager);
danielk197794b30732009-07-02 17:21:57 +00004657 btreeIntegrity(p);
4658}
4659
4660/*
drh2aa679f2001-06-25 02:11:07 +00004661** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00004662**
drh6e345992007-03-30 11:12:08 +00004663** This routine implements the second phase of a 2-phase commit. The
drh51898cf2009-04-19 20:51:06 +00004664** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
4665** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
4666** routine did all the work of writing information out to disk and flushing the
drh6e345992007-03-30 11:12:08 +00004667** contents so that they are written onto the disk platter. All this
drh51898cf2009-04-19 20:51:06 +00004668** routine has to do is delete or truncate or zero the header in the
4669** the rollback journal (which causes the transaction to commit) and
4670** drop locks.
drh6e345992007-03-30 11:12:08 +00004671**
dan60939d02011-03-29 15:40:55 +00004672** Normally, if an error occurs while the pager layer is attempting to
4673** finalize the underlying journal file, this function returns an error and
4674** the upper layer will attempt a rollback. However, if the second argument
4675** is non-zero then this b-tree transaction is part of a multi-file
4676** transaction. In this case, the transaction has already been committed
drh067b92b2020-06-19 15:24:12 +00004677** (by deleting a super-journal file) and the caller will ignore this
dan60939d02011-03-29 15:40:55 +00004678** functions return code. So, even if an error occurs in the pager layer,
4679** reset the b-tree objects internal state to indicate that the write
4680** transaction has been closed. This is quite safe, as the pager will have
4681** transitioned to the error state.
4682**
drh5e00f6c2001-09-13 13:46:56 +00004683** This will release the write lock on the database file. If there
4684** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00004685*/
dan60939d02011-03-29 15:40:55 +00004686int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
danielk1977aef0bf62005-12-30 16:28:01 +00004687
drh075ed302010-10-14 01:17:30 +00004688 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00004689 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00004690 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00004691
4692 /* If the handle has a write-transaction open, commit the shared-btrees
4693 ** transaction and set the shared state to TRANS_READ.
4694 */
4695 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00004696 int rc;
drh075ed302010-10-14 01:17:30 +00004697 BtShared *pBt = p->pBt;
danielk1977aef0bf62005-12-30 16:28:01 +00004698 assert( pBt->inTransaction==TRANS_WRITE );
4699 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00004700 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
dan60939d02011-03-29 15:40:55 +00004701 if( rc!=SQLITE_OK && bCleanup==0 ){
drhd677b3d2007-08-20 22:48:41 +00004702 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00004703 return rc;
4704 }
drh2b994ce2021-03-18 12:36:09 +00004705 p->iBDataVersion--; /* Compensate for pPager->iDataVersion++; */
danielk1977aef0bf62005-12-30 16:28:01 +00004706 pBt->inTransaction = TRANS_READ;
danbf0e57a2013-05-14 20:36:31 +00004707 btreeClearHasContent(pBt);
danielk1977ee5741e2004-05-31 10:01:34 +00004708 }
danielk1977aef0bf62005-12-30 16:28:01 +00004709
danielk197794b30732009-07-02 17:21:57 +00004710 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00004711 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00004712 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00004713}
4714
drh80e35f42007-03-30 14:06:34 +00004715/*
4716** Do both phases of a commit.
4717*/
4718int sqlite3BtreeCommit(Btree *p){
4719 int rc;
drhd677b3d2007-08-20 22:48:41 +00004720 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00004721 rc = sqlite3BtreeCommitPhaseOne(p, 0);
4722 if( rc==SQLITE_OK ){
dan60939d02011-03-29 15:40:55 +00004723 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
drh80e35f42007-03-30 14:06:34 +00004724 }
drhd677b3d2007-08-20 22:48:41 +00004725 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00004726 return rc;
4727}
4728
drhc39e0002004-05-07 23:50:57 +00004729/*
drhfb982642007-08-30 01:19:59 +00004730** This routine sets the state to CURSOR_FAULT and the error
drh47b7fc72014-11-11 01:33:57 +00004731** code to errCode for every cursor on any BtShared that pBtree
4732** references. Or if the writeOnly flag is set to 1, then only
4733** trip write cursors and leave read cursors unchanged.
drhfb982642007-08-30 01:19:59 +00004734**
drh47b7fc72014-11-11 01:33:57 +00004735** Every cursor is a candidate to be tripped, including cursors
4736** that belong to other database connections that happen to be
4737** sharing the cache with pBtree.
drhfb982642007-08-30 01:19:59 +00004738**
dan80231042014-11-12 14:56:02 +00004739** This routine gets called when a rollback occurs. If the writeOnly
4740** flag is true, then only write-cursors need be tripped - read-only
4741** cursors save their current positions so that they may continue
4742** following the rollback. Or, if writeOnly is false, all cursors are
4743** tripped. In general, writeOnly is false if the transaction being
4744** rolled back modified the database schema. In this case b-tree root
4745** pages may be moved or deleted from the database altogether, making
4746** it unsafe for read cursors to continue.
4747**
4748** If the writeOnly flag is true and an error is encountered while
4749** saving the current position of a read-only cursor, all cursors,
4750** including all read-cursors are tripped.
4751**
4752** SQLITE_OK is returned if successful, or if an error occurs while
4753** saving a cursor position, an SQLite error code.
drhfb982642007-08-30 01:19:59 +00004754*/
dan80231042014-11-12 14:56:02 +00004755int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
drhfb982642007-08-30 01:19:59 +00004756 BtCursor *p;
dan80231042014-11-12 14:56:02 +00004757 int rc = SQLITE_OK;
4758
drh47b7fc72014-11-11 01:33:57 +00004759 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
dan80231042014-11-12 14:56:02 +00004760 if( pBtree ){
4761 sqlite3BtreeEnter(pBtree);
4762 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
dan80231042014-11-12 14:56:02 +00004763 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
drhd2f83132015-03-25 17:35:01 +00004764 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
drhbea3b972014-11-18 20:22:05 +00004765 rc = saveCursorPosition(p);
dan80231042014-11-12 14:56:02 +00004766 if( rc!=SQLITE_OK ){
4767 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
4768 break;
4769 }
4770 }
4771 }else{
4772 sqlite3BtreeClearCursor(p);
4773 p->eState = CURSOR_FAULT;
4774 p->skipNext = errCode;
4775 }
drh85ef6302017-08-02 15:50:09 +00004776 btreeReleaseAllCursorPages(p);
danielk1977bc2ca9e2008-11-13 14:28:28 +00004777 }
dan80231042014-11-12 14:56:02 +00004778 sqlite3BtreeLeave(pBtree);
drhfb982642007-08-30 01:19:59 +00004779 }
dan80231042014-11-12 14:56:02 +00004780 return rc;
drhfb982642007-08-30 01:19:59 +00004781}
4782
4783/*
drh41422652019-05-10 14:34:18 +00004784** Set the pBt->nPage field correctly, according to the current
4785** state of the database. Assume pBt->pPage1 is valid.
4786*/
4787static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){
4788 int nPage = get4byte(&pPage1->aData[28]);
4789 testcase( nPage==0 );
4790 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
mistachkin2b5fbb22021-12-31 18:26:50 +00004791 testcase( pBt->nPage!=(u32)nPage );
drh41422652019-05-10 14:34:18 +00004792 pBt->nPage = nPage;
4793}
4794
4795/*
drh47b7fc72014-11-11 01:33:57 +00004796** Rollback the transaction in progress.
4797**
4798** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
4799** Only write cursors are tripped if writeOnly is true but all cursors are
4800** tripped if writeOnly is false. Any attempt to use
4801** a tripped cursor will result in an error.
drh5e00f6c2001-09-13 13:46:56 +00004802**
4803** This will release the write lock on the database file. If there
4804** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00004805*/
drh47b7fc72014-11-11 01:33:57 +00004806int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
danielk19778d34dfd2006-01-24 16:37:57 +00004807 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00004808 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00004809 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00004810
drh47b7fc72014-11-11 01:33:57 +00004811 assert( writeOnly==1 || writeOnly==0 );
4812 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
drhd677b3d2007-08-20 22:48:41 +00004813 sqlite3BtreeEnter(p);
drh0f198a72012-02-13 16:43:16 +00004814 if( tripCode==SQLITE_OK ){
4815 rc = tripCode = saveAllCursors(pBt, 0, 0);
drh47b7fc72014-11-11 01:33:57 +00004816 if( rc ) writeOnly = 0;
drh0f198a72012-02-13 16:43:16 +00004817 }else{
4818 rc = SQLITE_OK;
danielk19772b8c13e2006-01-24 14:21:24 +00004819 }
drh0f198a72012-02-13 16:43:16 +00004820 if( tripCode ){
dan80231042014-11-12 14:56:02 +00004821 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
4822 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4823 if( rc2!=SQLITE_OK ) rc = rc2;
drh0f198a72012-02-13 16:43:16 +00004824 }
danielk1977aef0bf62005-12-30 16:28:01 +00004825 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00004826
4827 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00004828 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00004829
danielk19778d34dfd2006-01-24 16:37:57 +00004830 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00004831 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00004832 if( rc2!=SQLITE_OK ){
4833 rc = rc2;
4834 }
4835
drh24cd67e2004-05-10 16:18:47 +00004836 /* The rollback may have destroyed the pPage1->aData value. So
danielk197730548662009-07-09 05:07:37 +00004837 ** call btreeGetPage() on page 1 again to make
drh16a9b832007-05-05 18:39:25 +00004838 ** sure pPage1->aData is set correctly. */
drhb00fc3b2013-08-21 23:42:32 +00004839 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh41422652019-05-10 14:34:18 +00004840 btreeSetNPage(pBt, pPage1);
drh3908fe92017-09-01 14:50:19 +00004841 releasePageOne(pPage1);
drh24cd67e2004-05-10 16:18:47 +00004842 }
drh85ec3b62013-05-14 23:12:06 +00004843 assert( countValidCursors(pBt, 1)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00004844 pBt->inTransaction = TRANS_READ;
danbf0e57a2013-05-14 20:36:31 +00004845 btreeClearHasContent(pBt);
drh24cd67e2004-05-10 16:18:47 +00004846 }
danielk1977aef0bf62005-12-30 16:28:01 +00004847
danielk197794b30732009-07-02 17:21:57 +00004848 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00004849 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00004850 return rc;
4851}
4852
4853/*
peter.d.reid60ec9142014-09-06 16:39:46 +00004854** Start a statement subtransaction. The subtransaction can be rolled
danielk1977bd434552009-03-18 10:33:00 +00004855** back independently of the main transaction. You must start a transaction
4856** before starting a subtransaction. The subtransaction is ended automatically
4857** if the main transaction commits or rolls back.
drhab01f612004-05-22 02:55:23 +00004858**
4859** Statement subtransactions are used around individual SQL statements
4860** that are contained within a BEGIN...COMMIT block. If a constraint
4861** error occurs within the statement, the effect of that one statement
4862** can be rolled back without having to rollback the entire transaction.
danielk1977bd434552009-03-18 10:33:00 +00004863**
4864** A statement sub-transaction is implemented as an anonymous savepoint. The
4865** value passed as the second parameter is the total number of savepoints,
4866** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4867** are no active savepoints and no other statement-transactions open,
4868** iStatement is 1. This anonymous savepoint can be released or rolled back
4869** using the sqlite3BtreeSavepoint() function.
drh663fc632002-02-02 18:49:19 +00004870*/
danielk1977bd434552009-03-18 10:33:00 +00004871int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
drh663fc632002-02-02 18:49:19 +00004872 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00004873 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00004874 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00004875 assert( p->inTrans==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00004876 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk1977bd434552009-03-18 10:33:00 +00004877 assert( iStatement>0 );
4878 assert( iStatement>p->db->nSavepoint );
drh5e0ccc22010-03-29 19:36:52 +00004879 assert( pBt->inTransaction==TRANS_WRITE );
4880 /* At the pager level, a statement transaction is a savepoint with
4881 ** an index greater than all savepoints created explicitly using
4882 ** SQL statements. It is illegal to open, release or rollback any
4883 ** such savepoints while the statement transaction savepoint is active.
4884 */
4885 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
danf5cebf72015-08-22 17:28:55 +00004886 if( rc==SQLITE_OK ){
4887 rc = btreePtrmapBegin(pBt, iStatement);
dan7b3d71e2015-08-19 20:27:05 +00004888 }
drhd677b3d2007-08-20 22:48:41 +00004889 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00004890 return rc;
4891}
4892
4893/*
danielk1977fd7f0452008-12-17 17:30:26 +00004894** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4895** or SAVEPOINT_RELEASE. This function either releases or rolls back the
danielk197712dd5492008-12-18 15:45:07 +00004896** savepoint identified by parameter iSavepoint, depending on the value
4897** of op.
4898**
4899** Normally, iSavepoint is greater than or equal to zero. However, if op is
4900** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4901** contents of the entire transaction are rolled back. This is different
4902** from a normal transaction rollback, as no locks are released and the
4903** transaction remains open.
danielk1977fd7f0452008-12-17 17:30:26 +00004904*/
4905int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4906 int rc = SQLITE_OK;
4907 if( p && p->inTrans==TRANS_WRITE ){
4908 BtShared *pBt = p->pBt;
danielk1977fd7f0452008-12-17 17:30:26 +00004909 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4910 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4911 sqlite3BtreeEnter(p);
danf5cebf72015-08-22 17:28:55 +00004912 btreePtrmapEnd(pBt, op, iSavepoint);
drh2343c7e2017-02-02 00:46:55 +00004913 if( op==SAVEPOINT_ROLLBACK ){
4914 rc = saveAllCursors(pBt, 0, 0);
4915 }
4916 if( rc==SQLITE_OK ){
4917 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4918 }
drh9f0bbf92009-01-02 21:08:09 +00004919 if( rc==SQLITE_OK ){
drhc9166342012-01-05 23:32:06 +00004920 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4921 pBt->nPage = 0;
4922 }
drh9f0bbf92009-01-02 21:08:09 +00004923 rc = newDatabase(pBt);
drh41422652019-05-10 14:34:18 +00004924 btreeSetNPage(pBt, pBt->pPage1);
drhb9b49bf2010-08-05 03:21:39 +00004925
dana9a54652019-04-22 11:47:40 +00004926 /* pBt->nPage might be zero if the database was corrupt when
4927 ** the transaction was started. Otherwise, it must be at least 1. */
4928 assert( CORRUPT_DB || pBt->nPage>0 );
drh9f0bbf92009-01-02 21:08:09 +00004929 }
danielk1977fd7f0452008-12-17 17:30:26 +00004930 sqlite3BtreeLeave(p);
4931 }
4932 return rc;
4933}
4934
4935/*
drh8b2f49b2001-06-08 00:21:52 +00004936** Create a new cursor for the BTree whose root is on the page
danielk19773e8add92009-07-04 17:16:00 +00004937** iTable. If a read-only cursor is requested, it is assumed that
4938** the caller already has at least a read-only transaction open
4939** on the database already. If a write-cursor is requested, then
4940** the caller is assumed to have an open write transaction.
drh1bee3d72001-10-15 00:44:35 +00004941**
drhe807bdb2016-01-21 17:06:33 +00004942** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4943** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
4944** can be used for reading or for writing if other conditions for writing
4945** are also met. These are the conditions that must be met in order
4946** for writing to be allowed:
drh6446c4d2001-12-15 14:22:18 +00004947**
drhe807bdb2016-01-21 17:06:33 +00004948** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
drhf74b8d92002-09-01 23:20:45 +00004949**
drhfe5d71d2007-03-19 11:54:10 +00004950** 2: Other database connections that share the same pager cache
4951** but which are not in the READ_UNCOMMITTED state may not have
4952** cursors open with wrFlag==0 on the same table. Otherwise
4953** the changes made by this write cursor would be visible to
4954** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00004955**
4956** 3: The database must be writable (not on read-only media)
4957**
4958** 4: There must be an active transaction.
4959**
drhe807bdb2016-01-21 17:06:33 +00004960** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4961** is set. If FORDELETE is set, that is a hint to the implementation that
4962** this cursor will only be used to seek to and delete entries of an index
4963** as part of a larger DELETE statement. The FORDELETE hint is not used by
4964** this implementation. But in a hypothetical alternative storage engine
4965** in which index entries are automatically deleted when corresponding table
4966** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4967** operations on this cursor can be no-ops and all READ operations can
4968** return a null row (2-bytes: 0x01 0x00).
4969**
drh6446c4d2001-12-15 14:22:18 +00004970** No checking is done to make sure that page iTable really is the
4971** root page of a b-tree. If it is not, then the cursor acquired
4972** will not work correctly.
danielk197771d5d2c2008-09-29 11:49:47 +00004973**
drhf25a5072009-11-18 23:01:25 +00004974** It is assumed that the sqlite3BtreeCursorZero() has been called
4975** on pCur to initialize the memory space prior to invoking this routine.
drha059ad02001-04-17 20:09:11 +00004976*/
drhd677b3d2007-08-20 22:48:41 +00004977static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00004978 Btree *p, /* The btree */
drhabc38152020-07-22 13:38:04 +00004979 Pgno iTable, /* Root page of table to open */
danielk1977cd3e8f72008-03-25 09:47:35 +00004980 int wrFlag, /* 1 to write. 0 read-only */
4981 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4982 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00004983){
danielk19773e8add92009-07-04 17:16:00 +00004984 BtShared *pBt = p->pBt; /* Shared b-tree handle */
drh27fb7462015-06-30 02:47:36 +00004985 BtCursor *pX; /* Looping over other all cursors */
drhecdc7532001-09-23 02:35:53 +00004986
drh1fee73e2007-08-29 04:00:57 +00004987 assert( sqlite3BtreeHoldsMutex(p) );
danfd261ec2015-10-22 20:54:33 +00004988 assert( wrFlag==0
4989 || wrFlag==BTREE_WRCSR
4990 || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4991 );
danielk197796d48e92009-06-29 06:00:37 +00004992
danielk1977602b4662009-07-02 07:47:33 +00004993 /* The following assert statements verify that if this is a sharable
4994 ** b-tree database, the connection is holding the required table locks,
4995 ** and that no other connection has any open cursor that conflicts with
drhac801802019-11-17 11:47:50 +00004996 ** this lock. The iTable<1 term disables the check for corrupt schemas. */
4997 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1))
4998 || iTable<1 );
danielk197796d48e92009-06-29 06:00:37 +00004999 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
5000
danielk19773e8add92009-07-04 17:16:00 +00005001 /* Assert that the caller has opened the required transaction. */
5002 assert( p->inTrans>TRANS_NONE );
5003 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
5004 assert( pBt->pPage1 && pBt->pPage1->aData );
drh98ef0f62015-06-30 01:25:52 +00005005 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk19773e8add92009-07-04 17:16:00 +00005006
drhdb561bc2019-10-25 14:46:05 +00005007 if( iTable<=1 ){
5008 if( iTable<1 ){
5009 return SQLITE_CORRUPT_BKPT;
5010 }else if( btreePagecount(pBt)==0 ){
5011 assert( wrFlag==0 );
5012 iTable = 0;
5013 }
danielk19773e8add92009-07-04 17:16:00 +00005014 }
danielk1977aef0bf62005-12-30 16:28:01 +00005015
danielk1977aef0bf62005-12-30 16:28:01 +00005016 /* Now that no other errors can occur, finish filling in the BtCursor
danielk19773e8add92009-07-04 17:16:00 +00005017 ** variables and link the cursor into the BtShared list. */
drhabc38152020-07-22 13:38:04 +00005018 pCur->pgnoRoot = iTable;
danielk1977172114a2009-07-07 15:47:12 +00005019 pCur->iPage = -1;
drh1e968a02008-03-25 00:22:21 +00005020 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00005021 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00005022 pCur->pBt = pBt;
drh2f0bc1d2021-12-03 13:42:41 +00005023 pCur->curFlags = 0;
drh27fb7462015-06-30 02:47:36 +00005024 /* If there are two or more cursors on the same btree, then all such
5025 ** cursors *must* have the BTCF_Multiple flag set. */
5026 for(pX=pBt->pCursor; pX; pX=pX->pNext){
drhabc38152020-07-22 13:38:04 +00005027 if( pX->pgnoRoot==iTable ){
drh27fb7462015-06-30 02:47:36 +00005028 pX->curFlags |= BTCF_Multiple;
drh2f0bc1d2021-12-03 13:42:41 +00005029 pCur->curFlags = BTCF_Multiple;
drh27fb7462015-06-30 02:47:36 +00005030 }
drha059ad02001-04-17 20:09:11 +00005031 }
drh2f0bc1d2021-12-03 13:42:41 +00005032 pCur->eState = CURSOR_INVALID;
drh27fb7462015-06-30 02:47:36 +00005033 pCur->pNext = pBt->pCursor;
drha059ad02001-04-17 20:09:11 +00005034 pBt->pCursor = pCur;
drh2f0bc1d2021-12-03 13:42:41 +00005035 if( wrFlag ){
5036 pCur->curFlags |= BTCF_WriteFlag;
5037 pCur->curPagerFlags = 0;
5038 if( pBt->pTmpSpace==0 ) return allocateTempSpace(pBt);
5039 }else{
5040 pCur->curPagerFlags = PAGER_GET_READONLY;
5041 }
danielk1977aef0bf62005-12-30 16:28:01 +00005042 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00005043}
drhdb561bc2019-10-25 14:46:05 +00005044static int btreeCursorWithLock(
5045 Btree *p, /* The btree */
drhabc38152020-07-22 13:38:04 +00005046 Pgno iTable, /* Root page of table to open */
drhdb561bc2019-10-25 14:46:05 +00005047 int wrFlag, /* 1 to write. 0 read-only */
5048 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
5049 BtCursor *pCur /* Space for new cursor */
5050){
5051 int rc;
5052 sqlite3BtreeEnter(p);
5053 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
5054 sqlite3BtreeLeave(p);
5055 return rc;
5056}
drhd677b3d2007-08-20 22:48:41 +00005057int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00005058 Btree *p, /* The btree */
drhabc38152020-07-22 13:38:04 +00005059 Pgno iTable, /* Root page of table to open */
danielk1977cd3e8f72008-03-25 09:47:35 +00005060 int wrFlag, /* 1 to write. 0 read-only */
5061 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
5062 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00005063){
drhdb561bc2019-10-25 14:46:05 +00005064 if( p->sharable ){
5065 return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur);
dan08f901b2015-05-25 19:24:36 +00005066 }else{
drhdb561bc2019-10-25 14:46:05 +00005067 return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
dan08f901b2015-05-25 19:24:36 +00005068 }
drhd677b3d2007-08-20 22:48:41 +00005069}
drh7f751222009-03-17 22:33:00 +00005070
5071/*
5072** Return the size of a BtCursor object in bytes.
5073**
5074** This interfaces is needed so that users of cursors can preallocate
5075** sufficient storage to hold a cursor. The BtCursor object is opaque
5076** to users so they cannot do the sizeof() themselves - they must call
5077** this routine.
5078*/
5079int sqlite3BtreeCursorSize(void){
drhc54055b2009-11-13 17:05:53 +00005080 return ROUND8(sizeof(BtCursor));
danielk1977cd3e8f72008-03-25 09:47:35 +00005081}
5082
drh7f751222009-03-17 22:33:00 +00005083/*
drhf25a5072009-11-18 23:01:25 +00005084** Initialize memory that will be converted into a BtCursor object.
5085**
5086** The simple approach here would be to memset() the entire object
5087** to zero. But it turns out that the apPage[] and aiIdx[] arrays
5088** do not need to be zeroed and they are large, so we can save a lot
5089** of run-time by skipping the initialization of those elements.
5090*/
5091void sqlite3BtreeCursorZero(BtCursor *p){
drhda6bc672018-01-24 16:04:21 +00005092 memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
drhf25a5072009-11-18 23:01:25 +00005093}
5094
5095/*
drh5e00f6c2001-09-13 13:46:56 +00005096** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00005097** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00005098*/
drh3aac2dd2004-04-26 14:10:20 +00005099int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00005100 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00005101 if( pBtree ){
5102 BtShared *pBt = pCur->pBt;
5103 sqlite3BtreeEnter(pBtree);
drh27fb7462015-06-30 02:47:36 +00005104 assert( pBt->pCursor!=0 );
5105 if( pBt->pCursor==pCur ){
danielk1977cd3e8f72008-03-25 09:47:35 +00005106 pBt->pCursor = pCur->pNext;
drh27fb7462015-06-30 02:47:36 +00005107 }else{
5108 BtCursor *pPrev = pBt->pCursor;
5109 do{
5110 if( pPrev->pNext==pCur ){
5111 pPrev->pNext = pCur->pNext;
5112 break;
5113 }
5114 pPrev = pPrev->pNext;
5115 }while( ALWAYS(pPrev) );
danielk1977cd3e8f72008-03-25 09:47:35 +00005116 }
drh352a35a2017-08-15 03:46:47 +00005117 btreeReleaseAllCursorPages(pCur);
danielk1977cd3e8f72008-03-25 09:47:35 +00005118 unlockBtreeIfUnused(pBt);
dan85753662014-12-11 16:38:18 +00005119 sqlite3_free(pCur->aOverflow);
drhf38dd3b2017-08-14 23:53:02 +00005120 sqlite3_free(pCur->pKey);
daneeee8a52021-03-18 14:31:37 +00005121 if( (pBt->openFlags & BTREE_SINGLE) && pBt->pCursor==0 ){
5122 /* Since the BtShared is not sharable, there is no need to
5123 ** worry about the missing sqlite3BtreeLeave() call here. */
5124 assert( pBtree->sharable==0 );
5125 sqlite3BtreeClose(pBtree);
5126 }else{
5127 sqlite3BtreeLeave(pBtree);
5128 }
dan97c8cb32019-01-01 18:00:17 +00005129 pCur->pBtree = 0;
drha059ad02001-04-17 20:09:11 +00005130 }
drh8c42ca92001-06-22 19:15:00 +00005131 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00005132}
5133
drh5e2f8b92001-05-28 00:41:15 +00005134/*
drh86057612007-06-26 01:04:48 +00005135** Make sure the BtCursor* given in the argument has a valid
5136** BtCursor.info structure. If it is not already valid, call
danielk197730548662009-07-09 05:07:37 +00005137** btreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00005138**
5139** BtCursor.info is a cache of the information in the current cell.
danielk197730548662009-07-09 05:07:37 +00005140** Using this cache reduces the number of calls to btreeParseCell().
drh9188b382004-05-14 21:12:22 +00005141*/
drh9188b382004-05-14 21:12:22 +00005142#ifndef NDEBUG
drha224ee22018-02-19 13:53:56 +00005143 static int cellInfoEqual(CellInfo *a, CellInfo *b){
5144 if( a->nKey!=b->nKey ) return 0;
5145 if( a->pPayload!=b->pPayload ) return 0;
5146 if( a->nPayload!=b->nPayload ) return 0;
5147 if( a->nLocal!=b->nLocal ) return 0;
5148 if( a->nSize!=b->nSize ) return 0;
5149 return 1;
5150 }
danielk19771cc5ed82007-05-16 17:28:43 +00005151 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00005152 CellInfo info;
drh51c6d962004-06-06 00:42:25 +00005153 memset(&info, 0, sizeof(info));
drh352a35a2017-08-15 03:46:47 +00005154 btreeParseCell(pCur->pPage, pCur->ix, &info);
drha224ee22018-02-19 13:53:56 +00005155 assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
drh9188b382004-05-14 21:12:22 +00005156 }
danielk19771cc5ed82007-05-16 17:28:43 +00005157#else
5158 #define assertCellInfo(x)
5159#endif
drhc5b41ac2015-06-17 02:11:46 +00005160static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
5161 if( pCur->info.nSize==0 ){
drhc5b41ac2015-06-17 02:11:46 +00005162 pCur->curFlags |= BTCF_ValidNKey;
drh352a35a2017-08-15 03:46:47 +00005163 btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
drhc5b41ac2015-06-17 02:11:46 +00005164 }else{
5165 assertCellInfo(pCur);
drh86057612007-06-26 01:04:48 +00005166 }
drhc5b41ac2015-06-17 02:11:46 +00005167}
drh9188b382004-05-14 21:12:22 +00005168
drhea8ffdf2009-07-22 00:35:23 +00005169#ifndef NDEBUG /* The next routine used only within assert() statements */
5170/*
5171** Return true if the given BtCursor is valid. A valid cursor is one
5172** that is currently pointing to a row in a (non-empty) table.
5173** This is a verification routine is used only within assert() statements.
5174*/
5175int sqlite3BtreeCursorIsValid(BtCursor *pCur){
5176 return pCur && pCur->eState==CURSOR_VALID;
5177}
5178#endif /* NDEBUG */
drhd6ef5af2016-11-15 04:00:24 +00005179int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
5180 assert( pCur!=0 );
5181 return pCur->eState==CURSOR_VALID;
5182}
drhea8ffdf2009-07-22 00:35:23 +00005183
drh9188b382004-05-14 21:12:22 +00005184/*
drha7c90c42016-06-04 20:37:10 +00005185** Return the value of the integer key or "rowid" for a table btree.
5186** This routine is only valid for a cursor that is pointing into a
5187** ordinary table btree. If the cursor points to an index btree or
5188** is invalid, the result of this routine is undefined.
drh7e3b0a02001-04-28 16:52:40 +00005189*/
drha7c90c42016-06-04 20:37:10 +00005190i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00005191 assert( cursorHoldsMutex(pCur) );
drhc5352b92014-11-17 20:33:07 +00005192 assert( pCur->eState==CURSOR_VALID );
drha7c90c42016-06-04 20:37:10 +00005193 assert( pCur->curIntKey );
drhc5352b92014-11-17 20:33:07 +00005194 getCellInfo(pCur);
drha7c90c42016-06-04 20:37:10 +00005195 return pCur->info.nKey;
drha059ad02001-04-17 20:09:11 +00005196}
drh2af926b2001-05-15 00:39:25 +00005197
drh7b14b652019-12-29 22:08:20 +00005198/*
5199** Pin or unpin a cursor.
5200*/
5201void sqlite3BtreeCursorPin(BtCursor *pCur){
5202 assert( (pCur->curFlags & BTCF_Pinned)==0 );
5203 pCur->curFlags |= BTCF_Pinned;
5204}
5205void sqlite3BtreeCursorUnpin(BtCursor *pCur){
5206 assert( (pCur->curFlags & BTCF_Pinned)!=0 );
5207 pCur->curFlags &= ~BTCF_Pinned;
5208}
5209
drh092457b2017-12-29 15:04:49 +00005210#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
drh72f82862001-05-24 21:06:34 +00005211/*
drh2fc865c2017-12-16 20:20:37 +00005212** Return the offset into the database file for the start of the
5213** payload to which the cursor is pointing.
5214*/
drh092457b2017-12-29 15:04:49 +00005215i64 sqlite3BtreeOffset(BtCursor *pCur){
drh2fc865c2017-12-16 20:20:37 +00005216 assert( cursorHoldsMutex(pCur) );
5217 assert( pCur->eState==CURSOR_VALID );
drh2fc865c2017-12-16 20:20:37 +00005218 getCellInfo(pCur);
drhfe6d20e2017-12-29 14:33:54 +00005219 return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
drh2fc865c2017-12-16 20:20:37 +00005220 (i64)(pCur->info.pPayload - pCur->pPage->aData);
5221}
drh092457b2017-12-29 15:04:49 +00005222#endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
drh2fc865c2017-12-16 20:20:37 +00005223
drh72f82862001-05-24 21:06:34 +00005224/*
drha7c90c42016-06-04 20:37:10 +00005225** Return the number of bytes of payload for the entry that pCur is
5226** currently pointing to. For table btrees, this will be the amount
5227** of data. For index btrees, this will be the size of the key.
drhea8ffdf2009-07-22 00:35:23 +00005228**
5229** The caller must guarantee that the cursor is pointing to a non-NULL
5230** valid entry. In other words, the calling procedure must guarantee
5231** that the cursor has Cursor.eState==CURSOR_VALID.
drh0e1c19e2004-05-11 00:58:56 +00005232*/
drha7c90c42016-06-04 20:37:10 +00005233u32 sqlite3BtreePayloadSize(BtCursor *pCur){
5234 assert( cursorHoldsMutex(pCur) );
drhea8ffdf2009-07-22 00:35:23 +00005235 assert( pCur->eState==CURSOR_VALID );
5236 getCellInfo(pCur);
drha7c90c42016-06-04 20:37:10 +00005237 return pCur->info.nPayload;
drh0e1c19e2004-05-11 00:58:56 +00005238}
5239
5240/*
drh53d30dd2019-02-04 21:10:24 +00005241** Return an upper bound on the size of any record for the table
5242** that the cursor is pointing into.
5243**
5244** This is an optimization. Everything will still work if this
5245** routine always returns 2147483647 (which is the largest record
5246** that SQLite can handle) or more. But returning a smaller value might
5247** prevent large memory allocations when trying to interpret a
5248** corrupt datrabase.
5249**
5250** The current implementation merely returns the size of the underlying
5251** database file.
5252*/
5253sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
5254 assert( cursorHoldsMutex(pCur) );
5255 assert( pCur->eState==CURSOR_VALID );
5256 return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
5257}
5258
5259/*
danielk1977d04417962007-05-02 13:16:30 +00005260** Given the page number of an overflow page in the database (parameter
5261** ovfl), this function finds the page number of the next page in the
5262** linked list of overflow pages. If possible, it uses the auto-vacuum
5263** pointer-map data instead of reading the content of page ovfl to do so.
5264**
5265** If an error occurs an SQLite error code is returned. Otherwise:
5266**
danielk1977bea2a942009-01-20 17:06:27 +00005267** The page number of the next overflow page in the linked list is
5268** written to *pPgnoNext. If page ovfl is the last page in its linked
5269** list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00005270**
danielk1977bea2a942009-01-20 17:06:27 +00005271** If ppPage is not NULL, and a reference to the MemPage object corresponding
5272** to page number pOvfl was obtained, then *ppPage is set to point to that
5273** reference. It is the responsibility of the caller to call releasePage()
5274** on *ppPage to free the reference. In no reference was obtained (because
5275** the pointer-map was used to obtain the value for *pPgnoNext), then
5276** *ppPage is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00005277*/
5278static int getOverflowPage(
drhfa3be902009-07-07 02:44:07 +00005279 BtShared *pBt, /* The database file */
5280 Pgno ovfl, /* Current overflow page number */
danielk1977bea2a942009-01-20 17:06:27 +00005281 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
danielk1977d04417962007-05-02 13:16:30 +00005282 Pgno *pPgnoNext /* OUT: Next overflow page number */
5283){
5284 Pgno next = 0;
danielk1977bea2a942009-01-20 17:06:27 +00005285 MemPage *pPage = 0;
drh1bd10f82008-12-10 21:19:56 +00005286 int rc = SQLITE_OK;
danielk1977d04417962007-05-02 13:16:30 +00005287
drh1fee73e2007-08-29 04:00:57 +00005288 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bea2a942009-01-20 17:06:27 +00005289 assert(pPgnoNext);
danielk1977d04417962007-05-02 13:16:30 +00005290
5291#ifndef SQLITE_OMIT_AUTOVACUUM
5292 /* Try to find the next page in the overflow list using the
5293 ** autovacuum pointer-map pages. Guess that the next page in
5294 ** the overflow list is page number (ovfl+1). If that guess turns
5295 ** out to be wrong, fall back to loading the data of page
5296 ** number ovfl to determine the next page number.
5297 */
5298 if( pBt->autoVacuum ){
5299 Pgno pgno;
5300 Pgno iGuess = ovfl+1;
5301 u8 eType;
5302
5303 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
5304 iGuess++;
5305 }
5306
drhb1299152010-03-30 22:58:33 +00005307 if( iGuess<=btreePagecount(pBt) ){
danielk1977d04417962007-05-02 13:16:30 +00005308 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
danielk1977bea2a942009-01-20 17:06:27 +00005309 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
danielk1977d04417962007-05-02 13:16:30 +00005310 next = iGuess;
danielk1977bea2a942009-01-20 17:06:27 +00005311 rc = SQLITE_DONE;
danielk1977d04417962007-05-02 13:16:30 +00005312 }
5313 }
5314 }
5315#endif
5316
danielk1977d8a3f3d2009-07-11 11:45:23 +00005317 assert( next==0 || rc==SQLITE_DONE );
danielk1977bea2a942009-01-20 17:06:27 +00005318 if( rc==SQLITE_OK ){
drhb00fc3b2013-08-21 23:42:32 +00005319 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
danielk1977d8a3f3d2009-07-11 11:45:23 +00005320 assert( rc==SQLITE_OK || pPage==0 );
5321 if( rc==SQLITE_OK ){
danielk1977d04417962007-05-02 13:16:30 +00005322 next = get4byte(pPage->aData);
5323 }
danielk1977443c0592009-01-16 15:21:05 +00005324 }
danielk197745d68822009-01-16 16:23:38 +00005325
danielk1977bea2a942009-01-20 17:06:27 +00005326 *pPgnoNext = next;
5327 if( ppPage ){
5328 *ppPage = pPage;
5329 }else{
5330 releasePage(pPage);
5331 }
5332 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
danielk1977d04417962007-05-02 13:16:30 +00005333}
5334
danielk1977da107192007-05-04 08:32:13 +00005335/*
5336** Copy data from a buffer to a page, or from a page to a buffer.
5337**
5338** pPayload is a pointer to data stored on database page pDbPage.
5339** If argument eOp is false, then nByte bytes of data are copied
5340** from pPayload to the buffer pointed at by pBuf. If eOp is true,
5341** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
5342** of data are copied from the buffer pBuf to pPayload.
5343**
5344** SQLITE_OK is returned on success, otherwise an error code.
5345*/
5346static int copyPayload(
5347 void *pPayload, /* Pointer to page data */
5348 void *pBuf, /* Pointer to buffer */
5349 int nByte, /* Number of bytes to copy */
5350 int eOp, /* 0 -> copy from page, 1 -> copy to page */
5351 DbPage *pDbPage /* Page containing pPayload */
5352){
5353 if( eOp ){
5354 /* Copy data from buffer to page (a write operation) */
5355 int rc = sqlite3PagerWrite(pDbPage);
5356 if( rc!=SQLITE_OK ){
5357 return rc;
5358 }
5359 memcpy(pPayload, pBuf, nByte);
5360 }else{
5361 /* Copy data from page to buffer (a read operation) */
5362 memcpy(pBuf, pPayload, nByte);
5363 }
5364 return SQLITE_OK;
5365}
danielk1977d04417962007-05-02 13:16:30 +00005366
5367/*
danielk19779f8d6402007-05-02 17:48:45 +00005368** This function is used to read or overwrite payload information
dan5a500af2014-03-11 20:33:04 +00005369** for the entry that the pCur cursor is pointing to. The eOp
5370** argument is interpreted as follows:
5371**
5372** 0: The operation is a read. Populate the overflow cache.
5373** 1: The operation is a write. Populate the overflow cache.
danielk19779f8d6402007-05-02 17:48:45 +00005374**
5375** A total of "amt" bytes are read or written beginning at "offset".
5376** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00005377**
drh3bcdfd22009-07-12 02:32:21 +00005378** The content being read or written might appear on the main page
5379** or be scattered out on multiple overflow pages.
danielk1977da107192007-05-04 08:32:13 +00005380**
drh42e28f12017-01-27 00:31:59 +00005381** If the current cursor entry uses one or more overflow pages
5382** this function may allocate space for and lazily populate
5383** the overflow page-list cache array (BtCursor.aOverflow).
dan5a500af2014-03-11 20:33:04 +00005384** Subsequent calls use this cache to make seeking to the supplied offset
5385** more efficient.
danielk1977da107192007-05-04 08:32:13 +00005386**
drh42e28f12017-01-27 00:31:59 +00005387** Once an overflow page-list cache has been allocated, it must be
danielk1977da107192007-05-04 08:32:13 +00005388** invalidated if some other cursor writes to the same table, or if
5389** the cursor is moved to a different row. Additionally, in auto-vacuum
5390** mode, the following events may invalidate an overflow page-list cache.
5391**
5392** * An incremental vacuum,
5393** * A commit in auto_vacuum="full" mode,
5394** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00005395*/
danielk19779f8d6402007-05-02 17:48:45 +00005396static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00005397 BtCursor *pCur, /* Cursor pointing to entry to read from */
danielk197789d40042008-11-17 14:20:56 +00005398 u32 offset, /* Begin reading this far into payload */
5399 u32 amt, /* Read this many bytes */
drh3aac2dd2004-04-26 14:10:20 +00005400 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00005401 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00005402){
5403 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00005404 int rc = SQLITE_OK;
danielk19772dec9702007-05-02 16:48:37 +00005405 int iIdx = 0;
drh352a35a2017-08-15 03:46:47 +00005406 MemPage *pPage = pCur->pPage; /* Btree page of current entry */
danielk19770d065412008-11-12 18:21:36 +00005407 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh4c417182014-03-31 23:57:41 +00005408#ifdef SQLITE_DIRECT_OVERFLOW_READ
drh8bb9fd32017-01-26 16:27:32 +00005409 unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
drh4c417182014-03-31 23:57:41 +00005410#endif
drh3aac2dd2004-04-26 14:10:20 +00005411
danielk1977da107192007-05-04 08:32:13 +00005412 assert( pPage );
drh42e28f12017-01-27 00:31:59 +00005413 assert( eOp==0 || eOp==1 );
danielk1977da184232006-01-05 11:34:32 +00005414 assert( pCur->eState==CURSOR_VALID );
drha7149082021-10-13 20:11:30 +00005415 if( pCur->ix>=pPage->nCell ){
5416 return SQLITE_CORRUPT_PAGE(pPage);
5417 }
drh1fee73e2007-08-29 04:00:57 +00005418 assert( cursorHoldsMutex(pCur) );
danielk1977da107192007-05-04 08:32:13 +00005419
drh86057612007-06-26 01:04:48 +00005420 getCellInfo(pCur);
drhab1cc582014-09-23 21:25:19 +00005421 aPayload = pCur->info.pPayload;
drhab1cc582014-09-23 21:25:19 +00005422 assert( offset+amt <= pCur->info.nPayload );
danielk1977da107192007-05-04 08:32:13 +00005423
drh0b982072016-03-22 14:10:45 +00005424 assert( aPayload > pPage->aData );
drhc5e7f942016-03-22 15:25:16 +00005425 if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
drh0b982072016-03-22 14:10:45 +00005426 /* Trying to read or write past the end of the data is an error. The
5427 ** conditional above is really:
5428 ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
5429 ** but is recast into its current form to avoid integer overflow problems
5430 */
daneebf2f52017-11-18 17:30:08 +00005431 return SQLITE_CORRUPT_PAGE(pPage);
drh3aac2dd2004-04-26 14:10:20 +00005432 }
danielk1977da107192007-05-04 08:32:13 +00005433
5434 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00005435 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00005436 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00005437 if( a+offset>pCur->info.nLocal ){
5438 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00005439 }
drh42e28f12017-01-27 00:31:59 +00005440 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00005441 offset = 0;
drha34b6762004-05-07 13:30:42 +00005442 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00005443 amt -= a;
drhdd793422001-06-28 01:54:48 +00005444 }else{
drhfa1a98a2004-05-14 19:08:17 +00005445 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00005446 }
danielk1977da107192007-05-04 08:32:13 +00005447
dan85753662014-12-11 16:38:18 +00005448
danielk1977da107192007-05-04 08:32:13 +00005449 if( rc==SQLITE_OK && amt>0 ){
danielk197789d40042008-11-17 14:20:56 +00005450 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
danielk1977da107192007-05-04 08:32:13 +00005451 Pgno nextPage;
5452
drhfa1a98a2004-05-14 19:08:17 +00005453 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
drh584e8b72020-07-22 17:12:59 +00005454
drha38c9512014-04-01 01:24:34 +00005455 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
drha38c9512014-04-01 01:24:34 +00005456 **
5457 ** The aOverflow[] array is sized at one entry for each overflow page
5458 ** in the overflow chain. The page number of the first overflow page is
5459 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
5460 ** means "not yet known" (the cache is lazily populated).
danielk1977da107192007-05-04 08:32:13 +00005461 */
drh42e28f12017-01-27 00:31:59 +00005462 if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
danielk19772dec9702007-05-02 16:48:37 +00005463 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
drhda6bc672018-01-24 16:04:21 +00005464 if( pCur->aOverflow==0
mistachkin97f90592018-02-04 01:30:54 +00005465 || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
drhda6bc672018-01-24 16:04:21 +00005466 ){
dan85753662014-12-11 16:38:18 +00005467 Pgno *aNew = (Pgno*)sqlite3Realloc(
5468 pCur->aOverflow, nOvfl*2*sizeof(Pgno)
dan5a500af2014-03-11 20:33:04 +00005469 );
5470 if( aNew==0 ){
drhcd645532017-01-20 20:43:14 +00005471 return SQLITE_NOMEM_BKPT;
dan5a500af2014-03-11 20:33:04 +00005472 }else{
dan5a500af2014-03-11 20:33:04 +00005473 pCur->aOverflow = aNew;
5474 }
5475 }
drhcd645532017-01-20 20:43:14 +00005476 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
5477 pCur->curFlags |= BTCF_ValidOvfl;
drhcdf360a2017-01-27 01:13:49 +00005478 }else{
5479 /* If the overflow page-list cache has been allocated and the
5480 ** entry for the first required overflow page is valid, skip
5481 ** directly to it.
5482 */
5483 if( pCur->aOverflow[offset/ovflSize] ){
5484 iIdx = (offset/ovflSize);
5485 nextPage = pCur->aOverflow[iIdx];
5486 offset = (offset%ovflSize);
danielk19772dec9702007-05-02 16:48:37 +00005487 }
5488 }
danielk1977da107192007-05-04 08:32:13 +00005489
drhcd645532017-01-20 20:43:14 +00005490 assert( rc==SQLITE_OK && amt>0 );
5491 while( nextPage ){
danielk1977da107192007-05-04 08:32:13 +00005492 /* If required, populate the overflow page-list cache. */
drh584e8b72020-07-22 17:12:59 +00005493 if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT;
drh42e28f12017-01-27 00:31:59 +00005494 assert( pCur->aOverflow[iIdx]==0
5495 || pCur->aOverflow[iIdx]==nextPage
5496 || CORRUPT_DB );
5497 pCur->aOverflow[iIdx] = nextPage;
danielk1977da107192007-05-04 08:32:13 +00005498
danielk1977d04417962007-05-02 13:16:30 +00005499 if( offset>=ovflSize ){
5500 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00005501 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00005502 ** data is not required. So first try to lookup the overflow
5503 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00005504 ** function.
danielk1977d04417962007-05-02 13:16:30 +00005505 */
drha38c9512014-04-01 01:24:34 +00005506 assert( pCur->curFlags & BTCF_ValidOvfl );
dan85753662014-12-11 16:38:18 +00005507 assert( pCur->pBtree->db==pBt->db );
drha38c9512014-04-01 01:24:34 +00005508 if( pCur->aOverflow[iIdx+1] ){
danielk1977da107192007-05-04 08:32:13 +00005509 nextPage = pCur->aOverflow[iIdx+1];
drha38c9512014-04-01 01:24:34 +00005510 }else{
danielk1977da107192007-05-04 08:32:13 +00005511 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
drha38c9512014-04-01 01:24:34 +00005512 }
danielk1977da107192007-05-04 08:32:13 +00005513 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00005514 }else{
danielk19779f8d6402007-05-02 17:48:45 +00005515 /* Need to read this page properly. It contains some of the
5516 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00005517 */
danielk1977cfe9a692004-06-16 12:00:29 +00005518 int a = amt;
danf4ba1092011-10-08 14:57:07 +00005519 if( a + offset > ovflSize ){
5520 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00005521 }
danf4ba1092011-10-08 14:57:07 +00005522
5523#ifdef SQLITE_DIRECT_OVERFLOW_READ
5524 /* If all the following are true:
5525 **
5526 ** 1) this is a read operation, and
5527 ** 2) data is required from the start of this overflow page, and
dan09236752018-11-22 19:10:14 +00005528 ** 3) there are no dirty pages in the page-cache
drh8bb9fd32017-01-26 16:27:32 +00005529 ** 4) the database is file-backed, and
drhd930b5c2017-01-26 02:26:02 +00005530 ** 5) the page is not in the WAL file
drh8bb9fd32017-01-26 16:27:32 +00005531 ** 6) at least 4 bytes have already been read into the output buffer
danf4ba1092011-10-08 14:57:07 +00005532 **
5533 ** then data can be read directly from the database file into the
5534 ** output buffer, bypassing the page-cache altogether. This speeds
5535 ** up loading large records that span many overflow pages.
5536 */
drh42e28f12017-01-27 00:31:59 +00005537 if( eOp==0 /* (1) */
danf4ba1092011-10-08 14:57:07 +00005538 && offset==0 /* (2) */
dan09236752018-11-22 19:10:14 +00005539 && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */
drh8bb9fd32017-01-26 16:27:32 +00005540 && &pBuf[-4]>=pBufStart /* (6) */
danf4ba1092011-10-08 14:57:07 +00005541 ){
dan09236752018-11-22 19:10:14 +00005542 sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
danf4ba1092011-10-08 14:57:07 +00005543 u8 aSave[4];
5544 u8 *aWrite = &pBuf[-4];
drh8bb9fd32017-01-26 16:27:32 +00005545 assert( aWrite>=pBufStart ); /* due to (6) */
danf4ba1092011-10-08 14:57:07 +00005546 memcpy(aSave, aWrite, 4);
dan27d47fb2011-12-21 17:00:16 +00005547 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
drhb9fc4552019-08-15 00:04:44 +00005548 if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT;
danf4ba1092011-10-08 14:57:07 +00005549 nextPage = get4byte(aWrite);
5550 memcpy(aWrite, aSave, 4);
5551 }else
5552#endif
5553
5554 {
5555 DbPage *pDbPage;
drh9584f582015-11-04 20:22:37 +00005556 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
drh42e28f12017-01-27 00:31:59 +00005557 (eOp==0 ? PAGER_GET_READONLY : 0)
dan11dcd112013-03-15 18:29:18 +00005558 );
danf4ba1092011-10-08 14:57:07 +00005559 if( rc==SQLITE_OK ){
5560 aPayload = sqlite3PagerGetData(pDbPage);
5561 nextPage = get4byte(aPayload);
drh42e28f12017-01-27 00:31:59 +00005562 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
danf4ba1092011-10-08 14:57:07 +00005563 sqlite3PagerUnref(pDbPage);
5564 offset = 0;
5565 }
5566 }
5567 amt -= a;
drh6ee610b2017-01-27 01:25:00 +00005568 if( amt==0 ) return rc;
danf4ba1092011-10-08 14:57:07 +00005569 pBuf += a;
danielk1977cfe9a692004-06-16 12:00:29 +00005570 }
drhcd645532017-01-20 20:43:14 +00005571 if( rc ) break;
5572 iIdx++;
drh2af926b2001-05-15 00:39:25 +00005573 }
drh2af926b2001-05-15 00:39:25 +00005574 }
danielk1977cfe9a692004-06-16 12:00:29 +00005575
danielk1977da107192007-05-04 08:32:13 +00005576 if( rc==SQLITE_OK && amt>0 ){
drhcc97ca42017-06-07 22:32:59 +00005577 /* Overflow chain ends prematurely */
daneebf2f52017-11-18 17:30:08 +00005578 return SQLITE_CORRUPT_PAGE(pPage);
drha7fcb052001-12-14 15:09:55 +00005579 }
danielk1977da107192007-05-04 08:32:13 +00005580 return rc;
drh2af926b2001-05-15 00:39:25 +00005581}
5582
drh72f82862001-05-24 21:06:34 +00005583/*
drhcb3cabd2016-11-25 19:18:28 +00005584** Read part of the payload for the row at which that cursor pCur is currently
5585** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00005586** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00005587**
drhcb3cabd2016-11-25 19:18:28 +00005588** pCur can be pointing to either a table or an index b-tree.
5589** If pointing to a table btree, then the content section is read. If
5590** pCur is pointing to an index b-tree then the key section is read.
5591**
5592** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
5593** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
5594** cursor might be invalid or might need to be restored before being read.
drh5d1a8722009-07-22 18:07:40 +00005595**
drh3aac2dd2004-04-26 14:10:20 +00005596** Return SQLITE_OK on success or an error code if anything goes
5597** wrong. An error is returned if "offset+amt" is larger than
5598** the available payload.
drh72f82862001-05-24 21:06:34 +00005599*/
drhcb3cabd2016-11-25 19:18:28 +00005600int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drh1fee73e2007-08-29 04:00:57 +00005601 assert( cursorHoldsMutex(pCur) );
drh5d1a8722009-07-22 18:07:40 +00005602 assert( pCur->eState==CURSOR_VALID );
drh352a35a2017-08-15 03:46:47 +00005603 assert( pCur->iPage>=0 && pCur->pPage );
drh5d1a8722009-07-22 18:07:40 +00005604 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
drh3aac2dd2004-04-26 14:10:20 +00005605}
drh83ec2762017-01-26 16:54:47 +00005606
5607/*
5608** This variant of sqlite3BtreePayload() works even if the cursor has not
5609** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
5610** interface.
5611*/
danielk19773588ceb2008-06-10 17:30:26 +00005612#ifndef SQLITE_OMIT_INCRBLOB
drh83ec2762017-01-26 16:54:47 +00005613static SQLITE_NOINLINE int accessPayloadChecked(
5614 BtCursor *pCur,
5615 u32 offset,
5616 u32 amt,
5617 void *pBuf
5618){
drhcb3cabd2016-11-25 19:18:28 +00005619 int rc;
danielk19773588ceb2008-06-10 17:30:26 +00005620 if ( pCur->eState==CURSOR_INVALID ){
5621 return SQLITE_ABORT;
5622 }
dan7a2347e2016-01-07 16:43:54 +00005623 assert( cursorOwnsBtShared(pCur) );
drh945b0942017-01-26 21:30:00 +00005624 rc = btreeRestoreCursorPosition(pCur);
drh83ec2762017-01-26 16:54:47 +00005625 return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
5626}
5627int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5628 if( pCur->eState==CURSOR_VALID ){
5629 assert( cursorOwnsBtShared(pCur) );
5630 return accessPayload(pCur, offset, amt, pBuf, 0);
5631 }else{
5632 return accessPayloadChecked(pCur, offset, amt, pBuf);
danielk1977da184232006-01-05 11:34:32 +00005633 }
drh2af926b2001-05-15 00:39:25 +00005634}
drhcb3cabd2016-11-25 19:18:28 +00005635#endif /* SQLITE_OMIT_INCRBLOB */
drh2af926b2001-05-15 00:39:25 +00005636
drh72f82862001-05-24 21:06:34 +00005637/*
drh0e1c19e2004-05-11 00:58:56 +00005638** Return a pointer to payload information from the entry that the
5639** pCur cursor is pointing to. The pointer is to the beginning of
drh2a8d2262013-12-09 20:43:22 +00005640** the key if index btrees (pPage->intKey==0) and is the data for
5641** table btrees (pPage->intKey==1). The number of bytes of available
5642** key/data is written into *pAmt. If *pAmt==0, then the value
5643** returned will not be a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00005644**
5645** This routine is an optimization. It is common for the entire key
5646** and data to fit on the local page and for there to be no overflow
5647** pages. When that is so, this routine can be used to access the
5648** key and data without making a copy. If the key and/or data spills
drh7f751222009-03-17 22:33:00 +00005649** onto overflow pages, then accessPayload() must be used to reassemble
drh0e1c19e2004-05-11 00:58:56 +00005650** the key/data and copy it into a preallocated buffer.
5651**
5652** The pointer returned by this routine looks directly into the cached
5653** page of the database. The data might change or move the next time
5654** any btree routine is called.
5655*/
drh2a8d2262013-12-09 20:43:22 +00005656static const void *fetchPayload(
drh0e1c19e2004-05-11 00:58:56 +00005657 BtCursor *pCur, /* Cursor pointing to entry to read from */
drh2a8d2262013-12-09 20:43:22 +00005658 u32 *pAmt /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00005659){
danf2f72a02017-10-19 15:17:38 +00005660 int amt;
drh352a35a2017-08-15 03:46:47 +00005661 assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
danielk1977da184232006-01-05 11:34:32 +00005662 assert( pCur->eState==CURSOR_VALID );
drh2a8d2262013-12-09 20:43:22 +00005663 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
dan7a2347e2016-01-07 16:43:54 +00005664 assert( cursorOwnsBtShared(pCur) );
drhcd789f92021-10-11 09:39:42 +00005665 assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
drh86dd3712014-03-25 11:00:21 +00005666 assert( pCur->info.nSize>0 );
drh352a35a2017-08-15 03:46:47 +00005667 assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
5668 assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
danf2f72a02017-10-19 15:17:38 +00005669 amt = pCur->info.nLocal;
5670 if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
5671 /* There is too little space on the page for the expected amount
5672 ** of local content. Database must be corrupt. */
5673 assert( CORRUPT_DB );
5674 amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
5675 }
5676 *pAmt = (u32)amt;
drhab1cc582014-09-23 21:25:19 +00005677 return (void*)pCur->info.pPayload;
drh0e1c19e2004-05-11 00:58:56 +00005678}
5679
5680
5681/*
drhe51c44f2004-05-30 20:46:09 +00005682** For the entry that cursor pCur is point to, return as
5683** many bytes of the key or data as are available on the local
5684** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00005685**
5686** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00005687** or be destroyed on the next call to any Btree routine,
5688** including calls from other threads against the same cache.
5689** Hence, a mutex on the BtShared should be held prior to calling
5690** this routine.
drh0e1c19e2004-05-11 00:58:56 +00005691**
5692** These routines is used to get quick access to key and data
5693** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00005694*/
drha7c90c42016-06-04 20:37:10 +00005695const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
drh2a8d2262013-12-09 20:43:22 +00005696 return fetchPayload(pCur, pAmt);
drh0e1c19e2004-05-11 00:58:56 +00005697}
5698
5699
5700/*
drh8178a752003-01-05 21:41:40 +00005701** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00005702** page number of the child page to move to.
danielk1977a299d612009-07-13 11:22:10 +00005703**
5704** This function returns SQLITE_CORRUPT if the page-header flags field of
5705** the new child page does not match the flags field of the parent (i.e.
5706** if an intkey page appears to be the parent of a non-intkey page, or
5707** vice-versa).
drh72f82862001-05-24 21:06:34 +00005708*/
drh3aac2dd2004-04-26 14:10:20 +00005709static int moveToChild(BtCursor *pCur, u32 newPgno){
drhd0679ed2007-08-28 22:24:34 +00005710 BtShared *pBt = pCur->pBt;
dan7fff2e12017-05-29 14:27:37 +00005711 int rc;
drh72f82862001-05-24 21:06:34 +00005712
dan7a2347e2016-01-07 16:43:54 +00005713 assert( cursorOwnsBtShared(pCur) );
danielk1977da184232006-01-05 11:34:32 +00005714 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00005715 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
dan11dcd112013-03-15 18:29:18 +00005716 assert( pCur->iPage>=0 );
danielk197771d5d2c2008-09-29 11:49:47 +00005717 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
5718 return SQLITE_CORRUPT_BKPT;
5719 }
drh271efa52004-05-30 19:19:05 +00005720 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00005721 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drh352a35a2017-08-15 03:46:47 +00005722 pCur->aiIdx[pCur->iPage] = pCur->ix;
5723 pCur->apPage[pCur->iPage] = pCur->pPage;
drh75e96b32017-04-01 00:20:06 +00005724 pCur->ix = 0;
drh352a35a2017-08-15 03:46:47 +00005725 pCur->iPage++;
drhb25057c2017-08-28 17:19:35 +00005726 rc = getAndInitPage(pBt, newPgno, &pCur->pPage,
drh28f58dd2015-06-27 19:45:03 +00005727 pCur, pCur->curPagerFlags);
dan7fff2e12017-05-29 14:27:37 +00005728 if( rc==SQLITE_OK ){
drhb25057c2017-08-28 17:19:35 +00005729 setMempageRoot(pCur->pPage, pCur->pgnoRoot);
dan7fff2e12017-05-29 14:27:37 +00005730 }
5731 return rc;
drh72f82862001-05-24 21:06:34 +00005732}
5733
drhd879e3e2017-02-13 13:35:55 +00005734#ifdef SQLITE_DEBUG
danielk1977bf93c562008-09-29 15:53:25 +00005735/*
5736** Page pParent is an internal (non-leaf) tree page. This function
5737** asserts that page number iChild is the left-child if the iIdx'th
5738** cell in page pParent. Or, if iIdx is equal to the total number of
5739** cells in pParent, that page number iChild is the right-child of
5740** the page.
5741*/
5742static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
drhcbd33492015-03-25 13:06:54 +00005743 if( CORRUPT_DB ) return; /* The conditions tested below might not be true
5744 ** in a corrupt database */
danielk1977bf93c562008-09-29 15:53:25 +00005745 assert( iIdx<=pParent->nCell );
5746 if( iIdx==pParent->nCell ){
5747 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
5748 }else{
5749 assert( get4byte(findCell(pParent, iIdx))==iChild );
5750 }
5751}
5752#else
5753# define assertParentIndex(x,y,z)
5754#endif
5755
drh72f82862001-05-24 21:06:34 +00005756/*
drh5e2f8b92001-05-28 00:41:15 +00005757** Move the cursor up to the parent page.
5758**
5759** pCur->idx is set to the cell index that contains the pointer
5760** to the page we are coming from. If we are coming from the
5761** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00005762** the largest cell index.
drh72f82862001-05-24 21:06:34 +00005763*/
danielk197730548662009-07-09 05:07:37 +00005764static void moveToParent(BtCursor *pCur){
drh352a35a2017-08-15 03:46:47 +00005765 MemPage *pLeaf;
dan7a2347e2016-01-07 16:43:54 +00005766 assert( cursorOwnsBtShared(pCur) );
danielk1977da184232006-01-05 11:34:32 +00005767 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00005768 assert( pCur->iPage>0 );
drh352a35a2017-08-15 03:46:47 +00005769 assert( pCur->pPage );
danielk1977bf93c562008-09-29 15:53:25 +00005770 assertParentIndex(
5771 pCur->apPage[pCur->iPage-1],
5772 pCur->aiIdx[pCur->iPage-1],
drh352a35a2017-08-15 03:46:47 +00005773 pCur->pPage->pgno
danielk1977bf93c562008-09-29 15:53:25 +00005774 );
dan6c2688c2012-01-12 15:05:03 +00005775 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
drh271efa52004-05-30 19:19:05 +00005776 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00005777 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drh75e96b32017-04-01 00:20:06 +00005778 pCur->ix = pCur->aiIdx[pCur->iPage-1];
drh352a35a2017-08-15 03:46:47 +00005779 pLeaf = pCur->pPage;
5780 pCur->pPage = pCur->apPage[--pCur->iPage];
5781 releasePageNotNull(pLeaf);
drh72f82862001-05-24 21:06:34 +00005782}
5783
5784/*
danielk19778f880a82009-07-13 09:41:45 +00005785** Move the cursor to point to the root page of its b-tree structure.
5786**
5787** If the table has a virtual root page, then the cursor is moved to point
5788** to the virtual root page instead of the actual root page. A table has a
5789** virtual root page when the actual root page contains no cells and a
5790** single child page. This can only happen with the table rooted at page 1.
5791**
5792** If the b-tree structure is empty, the cursor state is set to
drh44548e72017-08-14 18:13:52 +00005793** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
5794** the cursor is set to point to the first cell located on the root
5795** (or virtual root) page and the cursor state is set to CURSOR_VALID.
danielk19778f880a82009-07-13 09:41:45 +00005796**
5797** If this function returns successfully, it may be assumed that the
5798** page-header flags indicate that the [virtual] root-page is the expected
5799** kind of b-tree page (i.e. if when opening the cursor the caller did not
5800** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
5801** indicating a table b-tree, or if the caller did specify a KeyInfo
5802** structure the flags byte is set to 0x02 or 0x0A, indicating an index
5803** b-tree).
drh72f82862001-05-24 21:06:34 +00005804*/
drh5e2f8b92001-05-28 00:41:15 +00005805static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00005806 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00005807 int rc = SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00005808
dan7a2347e2016-01-07 16:43:54 +00005809 assert( cursorOwnsBtShared(pCur) );
drhfb982642007-08-30 01:19:59 +00005810 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
5811 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
5812 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
drh85ef6302017-08-02 15:50:09 +00005813 assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
drh44548e72017-08-14 18:13:52 +00005814 assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
danielk197771d5d2c2008-09-29 11:49:47 +00005815
5816 if( pCur->iPage>=0 ){
drh7ad3eb62016-10-24 01:01:09 +00005817 if( pCur->iPage ){
drh352a35a2017-08-15 03:46:47 +00005818 releasePageNotNull(pCur->pPage);
5819 while( --pCur->iPage ){
5820 releasePageNotNull(pCur->apPage[pCur->iPage]);
5821 }
drh7f8f6592021-12-13 19:59:55 +00005822 pRoot = pCur->pPage = pCur->apPage[0];
drh7ad3eb62016-10-24 01:01:09 +00005823 goto skip_init;
drhbbf0f862015-06-27 14:59:26 +00005824 }
dana205a482011-08-27 18:48:57 +00005825 }else if( pCur->pgnoRoot==0 ){
5826 pCur->eState = CURSOR_INVALID;
drh44548e72017-08-14 18:13:52 +00005827 return SQLITE_EMPTY;
drh777e4c42006-01-13 04:31:58 +00005828 }else{
drh28f58dd2015-06-27 19:45:03 +00005829 assert( pCur->iPage==(-1) );
drh85ef6302017-08-02 15:50:09 +00005830 if( pCur->eState>=CURSOR_REQUIRESEEK ){
5831 if( pCur->eState==CURSOR_FAULT ){
5832 assert( pCur->skipNext!=SQLITE_OK );
5833 return pCur->skipNext;
5834 }
5835 sqlite3BtreeClearCursor(pCur);
5836 }
drhe6aec722022-07-07 22:59:35 +00005837 rc = getAndInitPage(pCur->pBt, pCur->pgnoRoot, &pCur->pPage,
drh15a00212015-06-27 20:55:00 +00005838 0, pCur->curPagerFlags);
drh4c301aa2009-07-15 17:25:45 +00005839 if( rc!=SQLITE_OK ){
drh777e4c42006-01-13 04:31:58 +00005840 pCur->eState = CURSOR_INVALID;
drhf0357d82017-08-14 17:03:58 +00005841 return rc;
drh777e4c42006-01-13 04:31:58 +00005842 }
drhb25057c2017-08-28 17:19:35 +00005843 setMempageRoot(pCur->pPage, pCur->pgnoRoot);
danielk1977172114a2009-07-07 15:47:12 +00005844 pCur->iPage = 0;
drh352a35a2017-08-15 03:46:47 +00005845 pCur->curIntKey = pCur->pPage->intKey;
drhc39e0002004-05-07 23:50:57 +00005846 }
drh352a35a2017-08-15 03:46:47 +00005847 pRoot = pCur->pPage;
drhec9b6222022-03-07 18:32:08 +00005848 assert( pRoot->pgno==pCur->pgnoRoot || CORRUPT_DB );
dan7df42ab2014-01-20 18:25:44 +00005849
5850 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
5851 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
5852 ** NULL, the caller expects a table b-tree. If this is not the case,
5853 ** return an SQLITE_CORRUPT error.
5854 **
5855 ** Earlier versions of SQLite assumed that this test could not fail
5856 ** if the root page was already loaded when this function was called (i.e.
5857 ** if pCur->iPage>=0). But this is not so if the database is corrupted
5858 ** in such a way that page pRoot is linked into a second b-tree table
5859 ** (or the freelist). */
5860 assert( pRoot->intKey==1 || pRoot->intKey==0 );
5861 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
daneebf2f52017-11-18 17:30:08 +00005862 return SQLITE_CORRUPT_PAGE(pCur->pPage);
dan7df42ab2014-01-20 18:25:44 +00005863 }
danielk19778f880a82009-07-13 09:41:45 +00005864
drh7ad3eb62016-10-24 01:01:09 +00005865skip_init:
drh75e96b32017-04-01 00:20:06 +00005866 pCur->ix = 0;
drh271efa52004-05-30 19:19:05 +00005867 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00005868 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
danielk197771d5d2c2008-09-29 11:49:47 +00005869
drh4e8fe3f2013-12-06 23:25:27 +00005870 if( pRoot->nCell>0 ){
5871 pCur->eState = CURSOR_VALID;
5872 }else if( !pRoot->leaf ){
drh8856d6a2004-04-29 14:42:46 +00005873 Pgno subpage;
drhc85240d2009-06-04 16:14:33 +00005874 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
drh43605152004-05-29 21:46:49 +00005875 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
danielk1977da184232006-01-05 11:34:32 +00005876 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00005877 rc = moveToChild(pCur, subpage);
danielk197771d5d2c2008-09-29 11:49:47 +00005878 }else{
drh4e8fe3f2013-12-06 23:25:27 +00005879 pCur->eState = CURSOR_INVALID;
drh44548e72017-08-14 18:13:52 +00005880 rc = SQLITE_EMPTY;
drh8856d6a2004-04-29 14:42:46 +00005881 }
5882 return rc;
drh72f82862001-05-24 21:06:34 +00005883}
drh2af926b2001-05-15 00:39:25 +00005884
drh5e2f8b92001-05-28 00:41:15 +00005885/*
5886** Move the cursor down to the left-most leaf entry beneath the
5887** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00005888**
5889** The left-most leaf is the one with the smallest key - the first
5890** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00005891*/
5892static int moveToLeftmost(BtCursor *pCur){
5893 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00005894 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00005895 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00005896
dan7a2347e2016-01-07 16:43:54 +00005897 assert( cursorOwnsBtShared(pCur) );
danielk1977da184232006-01-05 11:34:32 +00005898 assert( pCur->eState==CURSOR_VALID );
drh352a35a2017-08-15 03:46:47 +00005899 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
drh75e96b32017-04-01 00:20:06 +00005900 assert( pCur->ix<pPage->nCell );
5901 pgno = get4byte(findCell(pPage, pCur->ix));
drh8178a752003-01-05 21:41:40 +00005902 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00005903 }
drhd677b3d2007-08-20 22:48:41 +00005904 return rc;
drh5e2f8b92001-05-28 00:41:15 +00005905}
5906
drh2dcc9aa2002-12-04 13:40:25 +00005907/*
5908** Move the cursor down to the right-most leaf entry beneath the
5909** page to which it is currently pointing. Notice the difference
5910** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
5911** finds the left-most entry beneath the *entry* whereas moveToRightmost()
5912** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00005913**
5914** The right-most entry is the one with the largest key - the last
5915** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00005916*/
5917static int moveToRightmost(BtCursor *pCur){
5918 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00005919 int rc = SQLITE_OK;
drh1bd10f82008-12-10 21:19:56 +00005920 MemPage *pPage = 0;
drh2dcc9aa2002-12-04 13:40:25 +00005921
dan7a2347e2016-01-07 16:43:54 +00005922 assert( cursorOwnsBtShared(pCur) );
danielk1977da184232006-01-05 11:34:32 +00005923 assert( pCur->eState==CURSOR_VALID );
drh352a35a2017-08-15 03:46:47 +00005924 while( !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00005925 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh75e96b32017-04-01 00:20:06 +00005926 pCur->ix = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00005927 rc = moveToChild(pCur, pgno);
drhee6438d2014-09-01 13:29:32 +00005928 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00005929 }
drh75e96b32017-04-01 00:20:06 +00005930 pCur->ix = pPage->nCell-1;
drhee6438d2014-09-01 13:29:32 +00005931 assert( pCur->info.nSize==0 );
5932 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5933 return SQLITE_OK;
drh2dcc9aa2002-12-04 13:40:25 +00005934}
5935
drh5e00f6c2001-09-13 13:46:56 +00005936/* Move the cursor to the first entry in the table. Return SQLITE_OK
5937** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00005938** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00005939*/
drh3aac2dd2004-04-26 14:10:20 +00005940int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00005941 int rc;
drhd677b3d2007-08-20 22:48:41 +00005942
dan7a2347e2016-01-07 16:43:54 +00005943 assert( cursorOwnsBtShared(pCur) );
drhe5fe6902007-12-07 18:55:28 +00005944 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00005945 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00005946 if( rc==SQLITE_OK ){
drh352a35a2017-08-15 03:46:47 +00005947 assert( pCur->pPage->nCell>0 );
drh44548e72017-08-14 18:13:52 +00005948 *pRes = 0;
5949 rc = moveToLeftmost(pCur);
5950 }else if( rc==SQLITE_EMPTY ){
drh352a35a2017-08-15 03:46:47 +00005951 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
drh44548e72017-08-14 18:13:52 +00005952 *pRes = 1;
5953 rc = SQLITE_OK;
drh5e00f6c2001-09-13 13:46:56 +00005954 }
drh5e00f6c2001-09-13 13:46:56 +00005955 return rc;
5956}
drh5e2f8b92001-05-28 00:41:15 +00005957
drh9562b552002-02-19 15:00:07 +00005958/* Move the cursor to the last entry in the table. Return SQLITE_OK
5959** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00005960** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00005961*/
drh85728a22022-11-19 00:22:12 +00005962static SQLITE_NOINLINE int btreeLast(BtCursor *pCur, int *pRes){
5963 int rc = moveToRoot(pCur);
5964 if( rc==SQLITE_OK ){
5965 assert( pCur->eState==CURSOR_VALID );
5966 *pRes = 0;
5967 rc = moveToRightmost(pCur);
5968 if( rc==SQLITE_OK ){
5969 pCur->curFlags |= BTCF_AtLast;
5970 }else{
5971 pCur->curFlags &= ~BTCF_AtLast;
5972 }
5973 }else if( rc==SQLITE_EMPTY ){
5974 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5975 *pRes = 1;
5976 rc = SQLITE_OK;
5977 }
5978 return rc;
5979}
drh3aac2dd2004-04-26 14:10:20 +00005980int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
dan7a2347e2016-01-07 16:43:54 +00005981 assert( cursorOwnsBtShared(pCur) );
drhe5fe6902007-12-07 18:55:28 +00005982 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19773f632d52009-05-02 10:03:09 +00005983
5984 /* If the cursor already points to the last entry, this is a no-op. */
drh036dbec2014-03-11 23:40:44 +00005985 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
danielk19773f632d52009-05-02 10:03:09 +00005986#ifdef SQLITE_DEBUG
5987 /* This block serves to assert() that the cursor really does point
5988 ** to the last entry in the b-tree. */
5989 int ii;
5990 for(ii=0; ii<pCur->iPage; ii++){
5991 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
5992 }
drh319deef2021-04-04 23:56:15 +00005993 assert( pCur->ix==pCur->pPage->nCell-1 || CORRUPT_DB );
5994 testcase( pCur->ix!=pCur->pPage->nCell-1 );
5995 /* ^-- dbsqlfuzz b92b72e4de80b5140c30ab71372ca719b8feb618 */
drh352a35a2017-08-15 03:46:47 +00005996 assert( pCur->pPage->leaf );
danielk19773f632d52009-05-02 10:03:09 +00005997#endif
drheb265342019-05-08 23:55:04 +00005998 *pRes = 0;
danielk19773f632d52009-05-02 10:03:09 +00005999 return SQLITE_OK;
6000 }
drh85728a22022-11-19 00:22:12 +00006001 return btreeLast(pCur, pRes);
drh9562b552002-02-19 15:00:07 +00006002}
6003
drh42a410d2021-06-19 18:32:20 +00006004/* Move the cursor so that it points to an entry in a table (a.k.a INTKEY)
6005** table near the key intKey. Return a success code.
drh3aac2dd2004-04-26 14:10:20 +00006006**
drh5e2f8b92001-05-28 00:41:15 +00006007** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00006008** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00006009** were present. The cursor might point to an entry that comes
6010** before or after the key.
6011**
drh64022502009-01-09 14:11:04 +00006012** An integer is written into *pRes which is the result of
6013** comparing the key with the entry to which the cursor is
6014** pointing. The meaning of the integer written into
6015** *pRes is as follows:
drhbd03cae2001-06-02 02:40:57 +00006016**
6017** *pRes<0 The cursor is left pointing at an entry that
drh42a410d2021-06-19 18:32:20 +00006018** is smaller than intKey or if the table is empty
drh1a844c32002-12-04 22:29:28 +00006019** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00006020**
6021** *pRes==0 The cursor is left pointing at an entry that
drh42a410d2021-06-19 18:32:20 +00006022** exactly matches intKey.
drhbd03cae2001-06-02 02:40:57 +00006023**
6024** *pRes>0 The cursor is left pointing at an entry that
drh42a410d2021-06-19 18:32:20 +00006025** is larger than intKey.
drha059ad02001-04-17 20:09:11 +00006026*/
drh42a410d2021-06-19 18:32:20 +00006027int sqlite3BtreeTableMoveto(
drhe63d9992008-08-13 19:11:48 +00006028 BtCursor *pCur, /* The cursor to be moved */
drhe63d9992008-08-13 19:11:48 +00006029 i64 intKey, /* The table key */
6030 int biasRight, /* If true, bias the search to the high end */
6031 int *pRes /* Write search results here */
drhe4d90812007-03-29 05:51:49 +00006032){
drh72f82862001-05-24 21:06:34 +00006033 int rc;
drhd677b3d2007-08-20 22:48:41 +00006034
dan7a2347e2016-01-07 16:43:54 +00006035 assert( cursorOwnsBtShared(pCur) );
drhe5fe6902007-12-07 18:55:28 +00006036 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19775cb09632009-07-09 11:36:01 +00006037 assert( pRes );
drh42a410d2021-06-19 18:32:20 +00006038 assert( pCur->pKeyInfo==0 );
6039 assert( pCur->eState!=CURSOR_VALID || pCur->curIntKey!=0 );
drha2c20e42008-03-29 16:01:04 +00006040
6041 /* If the cursor is already positioned at the point we are trying
6042 ** to move to, then just return without doing any work */
drh42a410d2021-06-19 18:32:20 +00006043 if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 ){
drhe63d9992008-08-13 19:11:48 +00006044 if( pCur->info.nKey==intKey ){
drha2c20e42008-03-29 16:01:04 +00006045 *pRes = 0;
6046 return SQLITE_OK;
6047 }
drh451e76d2017-01-21 16:54:19 +00006048 if( pCur->info.nKey<intKey ){
6049 if( (pCur->curFlags & BTCF_AtLast)!=0 ){
6050 *pRes = -1;
6051 return SQLITE_OK;
6052 }
drh7f11afa2017-01-21 21:47:54 +00006053 /* If the requested key is one more than the previous key, then
6054 ** try to get there using sqlite3BtreeNext() rather than a full
6055 ** binary search. This is an optimization only. The correct answer
drh2ab792e2017-05-30 18:34:07 +00006056 ** is still obtained without this case, only a little more slowely */
drh0c873bf2019-01-28 00:42:06 +00006057 if( pCur->info.nKey+1==intKey ){
drh7f11afa2017-01-21 21:47:54 +00006058 *pRes = 0;
drh2ab792e2017-05-30 18:34:07 +00006059 rc = sqlite3BtreeNext(pCur, 0);
6060 if( rc==SQLITE_OK ){
drh7f11afa2017-01-21 21:47:54 +00006061 getCellInfo(pCur);
6062 if( pCur->info.nKey==intKey ){
6063 return SQLITE_OK;
6064 }
drhe85e1da2021-10-01 21:01:07 +00006065 }else if( rc!=SQLITE_DONE ){
drh2ab792e2017-05-30 18:34:07 +00006066 return rc;
drh451e76d2017-01-21 16:54:19 +00006067 }
6068 }
drha2c20e42008-03-29 16:01:04 +00006069 }
6070 }
6071
drh37ccfcf2020-08-31 18:49:04 +00006072#ifdef SQLITE_DEBUG
6073 pCur->pBtree->nSeek++; /* Performance measurement during testing */
6074#endif
6075
drh42a410d2021-06-19 18:32:20 +00006076 rc = moveToRoot(pCur);
6077 if( rc ){
6078 if( rc==SQLITE_EMPTY ){
6079 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
6080 *pRes = -1;
6081 return SQLITE_OK;
6082 }
6083 return rc;
dan1fed5da2014-02-25 21:01:25 +00006084 }
drh42a410d2021-06-19 18:32:20 +00006085 assert( pCur->pPage );
6086 assert( pCur->pPage->isInit );
6087 assert( pCur->eState==CURSOR_VALID );
6088 assert( pCur->pPage->nCell > 0 );
6089 assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
6090 assert( pCur->curIntKey );
6091
6092 for(;;){
6093 int lwr, upr, idx, c;
6094 Pgno chldPg;
6095 MemPage *pPage = pCur->pPage;
6096 u8 *pCell; /* Pointer to current cell in pPage */
6097
6098 /* pPage->nCell must be greater than zero. If this is the root-page
6099 ** the cursor would have been INVALID above and this for(;;) loop
6100 ** not run. If this is not the root-page, then the moveToChild() routine
6101 ** would have already detected db corruption. Similarly, pPage must
6102 ** be the right kind (index or table) of b-tree page. Otherwise
6103 ** a moveToChild() or moveToRoot() call would have detected corruption. */
6104 assert( pPage->nCell>0 );
6105 assert( pPage->intKey );
6106 lwr = 0;
6107 upr = pPage->nCell-1;
6108 assert( biasRight==0 || biasRight==1 );
6109 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
drh42a410d2021-06-19 18:32:20 +00006110 for(;;){
6111 i64 nCellKey;
6112 pCell = findCellPastPtr(pPage, idx);
6113 if( pPage->intKeyLeaf ){
6114 while( 0x80 <= *(pCell++) ){
6115 if( pCell>=pPage->aDataEnd ){
6116 return SQLITE_CORRUPT_PAGE(pPage);
6117 }
6118 }
6119 }
6120 getVarint(pCell, (u64*)&nCellKey);
6121 if( nCellKey<intKey ){
6122 lwr = idx+1;
6123 if( lwr>upr ){ c = -1; break; }
6124 }else if( nCellKey>intKey ){
6125 upr = idx-1;
6126 if( lwr>upr ){ c = +1; break; }
6127 }else{
6128 assert( nCellKey==intKey );
6129 pCur->ix = (u16)idx;
6130 if( !pPage->leaf ){
6131 lwr = idx;
6132 goto moveto_table_next_layer;
6133 }else{
6134 pCur->curFlags |= BTCF_ValidNKey;
6135 pCur->info.nKey = nCellKey;
6136 pCur->info.nSize = 0;
6137 *pRes = 0;
6138 return SQLITE_OK;
6139 }
6140 }
6141 assert( lwr+upr>=0 );
6142 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
6143 }
6144 assert( lwr==upr+1 || !pPage->leaf );
6145 assert( pPage->isInit );
6146 if( pPage->leaf ){
6147 assert( pCur->ix<pCur->pPage->nCell );
6148 pCur->ix = (u16)idx;
6149 *pRes = c;
6150 rc = SQLITE_OK;
6151 goto moveto_table_finish;
6152 }
6153moveto_table_next_layer:
6154 if( lwr>=pPage->nCell ){
6155 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
6156 }else{
6157 chldPg = get4byte(findCell(pPage, lwr));
6158 }
6159 pCur->ix = (u16)lwr;
6160 rc = moveToChild(pCur, chldPg);
6161 if( rc ) break;
6162 }
6163moveto_table_finish:
6164 pCur->info.nSize = 0;
6165 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
6166 return rc;
6167}
6168
drhc5a55db2022-03-07 01:29:36 +00006169/*
6170** Compare the "idx"-th cell on the page the cursor pCur is currently
6171** pointing to to pIdxKey using xRecordCompare. Return negative or
6172** zero if the cell is less than or equal pIdxKey. Return positive
6173** if unknown.
6174**
6175** Return value negative: Cell at pCur[idx] less than pIdxKey
6176**
6177** Return value is zero: Cell at pCur[idx] equals pIdxKey
6178**
6179** Return value positive: Nothing is known about the relationship
6180** of the cell at pCur[idx] and pIdxKey.
6181**
6182** This routine is part of an optimization. It is always safe to return
6183** a positive value as that will cause the optimization to be skipped.
6184*/
6185static int indexCellCompare(
6186 BtCursor *pCur,
6187 int idx,
6188 UnpackedRecord *pIdxKey,
6189 RecordCompare xRecordCompare
6190){
6191 MemPage *pPage = pCur->pPage;
6192 int c;
6193 int nCell; /* Size of the pCell cell in bytes */
6194 u8 *pCell = findCellPastPtr(pPage, idx);
6195
6196 nCell = pCell[0];
6197 if( nCell<=pPage->max1bytePayload ){
6198 /* This branch runs if the record-size field of the cell is a
6199 ** single byte varint and the record fits entirely on the main
6200 ** b-tree page. */
6201 testcase( pCell+nCell+1==pPage->aDataEnd );
6202 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
6203 }else if( !(pCell[1] & 0x80)
6204 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
6205 ){
6206 /* The record-size field is a 2 byte varint and the record
6207 ** fits entirely on the main b-tree page. */
6208 testcase( pCell+nCell+2==pPage->aDataEnd );
6209 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
6210 }else{
6211 /* If the record extends into overflow pages, do not attempt
6212 ** the optimization. */
6213 c = 99;
6214 }
6215 return c;
6216}
6217
6218/*
6219** Return true (non-zero) if pCur is current pointing to the last
6220** page of a table.
6221*/
6222static int cursorOnLastPage(BtCursor *pCur){
6223 int i;
6224 assert( pCur->eState==CURSOR_VALID );
6225 for(i=0; i<pCur->iPage; i++){
6226 MemPage *pPage = pCur->apPage[i];
6227 if( pCur->aiIdx[i]<pPage->nCell ) return 0;
6228 }
6229 return 1;
6230}
6231
drh42a410d2021-06-19 18:32:20 +00006232/* Move the cursor so that it points to an entry in an index table
6233** near the key pIdxKey. Return a success code.
6234**
6235** If an exact match is not found, then the cursor is always
6236** left pointing at a leaf page which would hold the entry if it
6237** were present. The cursor might point to an entry that comes
6238** before or after the key.
6239**
6240** An integer is written into *pRes which is the result of
6241** comparing the key with the entry to which the cursor is
6242** pointing. The meaning of the integer written into
6243** *pRes is as follows:
6244**
6245** *pRes<0 The cursor is left pointing at an entry that
6246** is smaller than pIdxKey or if the table is empty
6247** and the cursor is therefore left point to nothing.
6248**
6249** *pRes==0 The cursor is left pointing at an entry that
6250** exactly matches pIdxKey.
6251**
6252** *pRes>0 The cursor is left pointing at an entry that
6253** is larger than pIdxKey.
6254**
6255** The pIdxKey->eqSeen field is set to 1 if there
6256** exists an entry in the table that exactly matches pIdxKey.
6257*/
6258int sqlite3BtreeIndexMoveto(
6259 BtCursor *pCur, /* The cursor to be moved */
6260 UnpackedRecord *pIdxKey, /* Unpacked index key */
6261 int *pRes /* Write search results here */
6262){
6263 int rc;
6264 RecordCompare xRecordCompare;
6265
6266 assert( cursorOwnsBtShared(pCur) );
6267 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
6268 assert( pRes );
6269 assert( pCur->pKeyInfo!=0 );
6270
6271#ifdef SQLITE_DEBUG
6272 pCur->pBtree->nSeek++; /* Performance measurement during testing */
6273#endif
6274
6275 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
6276 pIdxKey->errCode = 0;
6277 assert( pIdxKey->default_rc==1
6278 || pIdxKey->default_rc==0
6279 || pIdxKey->default_rc==-1
6280 );
dan1fed5da2014-02-25 21:01:25 +00006281
drhc5a55db2022-03-07 01:29:36 +00006282
6283 /* Check to see if we can skip a lot of work. Two cases:
6284 **
6285 ** (1) If the cursor is already pointing to the very last cell
6286 ** in the table and the pIdxKey search key is greater than or
6287 ** equal to that last cell, then no movement is required.
6288 **
6289 ** (2) If the cursor is on the last page of the table and the first
6290 ** cell on that last page is less than or equal to the pIdxKey
6291 ** search key, then we can start the search on the current page
6292 ** without needing to go back to root.
6293 */
6294 if( pCur->eState==CURSOR_VALID
6295 && pCur->pPage->leaf
6296 && cursorOnLastPage(pCur)
6297 ){
6298 int c;
6299 if( pCur->ix==pCur->pPage->nCell-1
6300 && (c = indexCellCompare(pCur, pCur->ix, pIdxKey, xRecordCompare))<=0
drh605137a2022-03-11 14:20:06 +00006301 && pIdxKey->errCode==SQLITE_OK
drhc5a55db2022-03-07 01:29:36 +00006302 ){
6303 *pRes = c;
6304 return SQLITE_OK; /* Cursor already pointing at the correct spot */
6305 }
6306 if( pCur->iPage>0
drh605137a2022-03-11 14:20:06 +00006307 && indexCellCompare(pCur, 0, pIdxKey, xRecordCompare)<=0
6308 && pIdxKey->errCode==SQLITE_OK
drhc5a55db2022-03-07 01:29:36 +00006309 ){
drh42bb09c2022-03-07 17:19:40 +00006310 pCur->curFlags &= ~BTCF_ValidOvfl;
drh1d497682022-06-19 16:55:07 +00006311 if( !pCur->pPage->isInit ){
6312 return SQLITE_CORRUPT_BKPT;
6313 }
drhc5a55db2022-03-07 01:29:36 +00006314 goto bypass_moveto_root; /* Start search on the current page */
6315 }
drh605137a2022-03-11 14:20:06 +00006316 pIdxKey->errCode = SQLITE_OK;
drhc5a55db2022-03-07 01:29:36 +00006317 }
6318
drh5e2f8b92001-05-28 00:41:15 +00006319 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00006320 if( rc ){
drh44548e72017-08-14 18:13:52 +00006321 if( rc==SQLITE_EMPTY ){
drh352a35a2017-08-15 03:46:47 +00006322 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
drh44548e72017-08-14 18:13:52 +00006323 *pRes = -1;
6324 return SQLITE_OK;
6325 }
drhd677b3d2007-08-20 22:48:41 +00006326 return rc;
6327 }
drhc5a55db2022-03-07 01:29:36 +00006328
6329bypass_moveto_root:
drh352a35a2017-08-15 03:46:47 +00006330 assert( pCur->pPage );
6331 assert( pCur->pPage->isInit );
drh44548e72017-08-14 18:13:52 +00006332 assert( pCur->eState==CURSOR_VALID );
drh352a35a2017-08-15 03:46:47 +00006333 assert( pCur->pPage->nCell > 0 );
drhc5a55db2022-03-07 01:29:36 +00006334 assert( pCur->curIntKey==0 );
6335 assert( pIdxKey!=0 );
drh14684382006-11-30 13:05:29 +00006336 for(;;){
drhec3e6b12013-11-25 02:38:55 +00006337 int lwr, upr, idx, c;
drh72f82862001-05-24 21:06:34 +00006338 Pgno chldPg;
drh352a35a2017-08-15 03:46:47 +00006339 MemPage *pPage = pCur->pPage;
drhec3e6b12013-11-25 02:38:55 +00006340 u8 *pCell; /* Pointer to current cell in pPage */
danielk1977171fff32009-07-11 05:06:51 +00006341
6342 /* pPage->nCell must be greater than zero. If this is the root-page
6343 ** the cursor would have been INVALID above and this for(;;) loop
6344 ** not run. If this is not the root-page, then the moveToChild() routine
danielk19773fd7cf52009-07-13 07:30:52 +00006345 ** would have already detected db corruption. Similarly, pPage must
6346 ** be the right kind (index or table) of b-tree page. Otherwise
6347 ** a moveToChild() or moveToRoot() call would have detected corruption. */
danielk1977171fff32009-07-11 05:06:51 +00006348 assert( pPage->nCell>0 );
drhc5a55db2022-03-07 01:29:36 +00006349 assert( pPage->intKey==0 );
drh72f82862001-05-24 21:06:34 +00006350 lwr = 0;
6351 upr = pPage->nCell-1;
drh42a410d2021-06-19 18:32:20 +00006352 idx = upr>>1; /* idx = (lwr+upr)/2; */
drh42a410d2021-06-19 18:32:20 +00006353 for(;;){
6354 int nCell; /* Size of the pCell cell in bytes */
6355 pCell = findCellPastPtr(pPage, idx);
drhec3e6b12013-11-25 02:38:55 +00006356
drh42a410d2021-06-19 18:32:20 +00006357 /* The maximum supported page-size is 65536 bytes. This means that
6358 ** the maximum number of record bytes stored on an index B-Tree
6359 ** page is less than 16384 bytes and may be stored as a 2-byte
6360 ** varint. This information is used to attempt to avoid parsing
6361 ** the entire cell by checking for the cases where the record is
6362 ** stored entirely within the b-tree page by inspecting the first
6363 ** 2 bytes of the cell.
6364 */
6365 nCell = pCell[0];
6366 if( nCell<=pPage->max1bytePayload ){
6367 /* This branch runs if the record-size field of the cell is a
6368 ** single byte varint and the record fits entirely on the main
6369 ** b-tree page. */
6370 testcase( pCell+nCell+1==pPage->aDataEnd );
6371 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
6372 }else if( !(pCell[1] & 0x80)
6373 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
6374 ){
6375 /* The record-size field is a 2 byte varint and the record
6376 ** fits entirely on the main b-tree page. */
6377 testcase( pCell+nCell+2==pPage->aDataEnd );
6378 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
6379 }else{
6380 /* The record flows over onto one or more overflow pages. In
6381 ** this case the whole cell needs to be parsed, a buffer allocated
6382 ** and accessPayload() used to retrieve the record into the
6383 ** buffer before VdbeRecordCompare() can be called.
6384 **
6385 ** If the record is corrupt, the xRecordCompare routine may read
6386 ** up to two varints past the end of the buffer. An extra 18
6387 ** bytes of padding is allocated at the end of the buffer in
6388 ** case this happens. */
6389 void *pCellKey;
6390 u8 * const pCellBody = pCell - pPage->childPtrSize;
6391 const int nOverrun = 18; /* Size of the overrun padding */
6392 pPage->xParseCell(pPage, pCellBody, &pCur->info);
6393 nCell = (int)pCur->info.nKey;
6394 testcase( nCell<0 ); /* True if key size is 2^32 or more */
6395 testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
6396 testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
6397 testcase( nCell==2 ); /* Minimum legal index key size */
6398 if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
6399 rc = SQLITE_CORRUPT_PAGE(pPage);
6400 goto moveto_index_finish;
6401 }
6402 pCellKey = sqlite3Malloc( nCell+nOverrun );
6403 if( pCellKey==0 ){
6404 rc = SQLITE_NOMEM_BKPT;
6405 goto moveto_index_finish;
6406 }
6407 pCur->ix = (u16)idx;
6408 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
6409 memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */
6410 pCur->curFlags &= ~BTCF_ValidOvfl;
6411 if( rc ){
drhfacf0302008-06-17 15:12:00 +00006412 sqlite3_free(pCellKey);
drh42a410d2021-06-19 18:32:20 +00006413 goto moveto_index_finish;
drhe51c44f2004-05-30 20:46:09 +00006414 }
drh42a410d2021-06-19 18:32:20 +00006415 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
6416 sqlite3_free(pCellKey);
drh72f82862001-05-24 21:06:34 +00006417 }
drh42a410d2021-06-19 18:32:20 +00006418 assert(
6419 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
6420 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
6421 );
6422 if( c<0 ){
6423 lwr = idx+1;
6424 }else if( c>0 ){
6425 upr = idx-1;
6426 }else{
6427 assert( c==0 );
6428 *pRes = 0;
6429 rc = SQLITE_OK;
6430 pCur->ix = (u16)idx;
6431 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
6432 goto moveto_index_finish;
6433 }
6434 if( lwr>upr ) break;
6435 assert( lwr+upr>=0 );
6436 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
drh72f82862001-05-24 21:06:34 +00006437 }
drhb07028f2011-10-14 21:49:18 +00006438 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
danielk197771d5d2c2008-09-29 11:49:47 +00006439 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00006440 if( pPage->leaf ){
drh3b79f752022-04-13 10:49:50 +00006441 assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
drh75e96b32017-04-01 00:20:06 +00006442 pCur->ix = (u16)idx;
drhec3e6b12013-11-25 02:38:55 +00006443 *pRes = c;
6444 rc = SQLITE_OK;
drh42a410d2021-06-19 18:32:20 +00006445 goto moveto_index_finish;
drhebf10b12013-11-25 17:38:26 +00006446 }
drhebf10b12013-11-25 17:38:26 +00006447 if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00006448 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00006449 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00006450 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00006451 }
drh75e96b32017-04-01 00:20:06 +00006452 pCur->ix = (u16)lwr;
drh8178a752003-01-05 21:41:40 +00006453 rc = moveToChild(pCur, chldPg);
drhec3e6b12013-11-25 02:38:55 +00006454 if( rc ) break;
drh72f82862001-05-24 21:06:34 +00006455 }
drh42a410d2021-06-19 18:32:20 +00006456moveto_index_finish:
drhd2022b02013-11-25 16:23:52 +00006457 pCur->info.nSize = 0;
drhd95ef5c2016-11-11 18:19:05 +00006458 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
drhe63d9992008-08-13 19:11:48 +00006459 return rc;
6460}
6461
drhd677b3d2007-08-20 22:48:41 +00006462
drh72f82862001-05-24 21:06:34 +00006463/*
drhc39e0002004-05-07 23:50:57 +00006464** Return TRUE if the cursor is not pointing at an entry of the table.
6465**
6466** TRUE will be returned after a call to sqlite3BtreeNext() moves
6467** past the last entry in the table or sqlite3BtreePrev() moves past
6468** the first entry. TRUE is also returned if the table is empty.
6469*/
6470int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00006471 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
6472 ** have been deleted? This API will need to change to return an error code
6473 ** as well as the boolean result value.
6474 */
6475 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00006476}
6477
6478/*
drh5e98e832017-02-17 19:24:06 +00006479** Return an estimate for the number of rows in the table that pCur is
6480** pointing to. Return a negative number if no estimate is currently
6481** available.
6482*/
6483i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
6484 i64 n;
6485 u8 i;
6486
6487 assert( cursorOwnsBtShared(pCur) );
6488 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh555227b2017-02-23 02:15:33 +00006489
6490 /* Currently this interface is only called by the OP_IfSmaller
6491 ** opcode, and it that case the cursor will always be valid and
6492 ** will always point to a leaf node. */
6493 if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
drh352a35a2017-08-15 03:46:47 +00006494 if( NEVER(pCur->pPage->leaf==0) ) return -1;
drh555227b2017-02-23 02:15:33 +00006495
drh352a35a2017-08-15 03:46:47 +00006496 n = pCur->pPage->nCell;
6497 for(i=0; i<pCur->iPage; i++){
drh5e98e832017-02-17 19:24:06 +00006498 n *= pCur->apPage[i]->nCell;
6499 }
6500 return n;
6501}
6502
6503/*
drh2ab792e2017-05-30 18:34:07 +00006504** Advance the cursor to the next entry in the database.
6505** Return value:
6506**
6507** SQLITE_OK success
6508** SQLITE_DONE cursor is already pointing at the last element
6509** otherwise some kind of error occurred
drhe39a7322014-02-03 14:04:11 +00006510**
drhee6438d2014-09-01 13:29:32 +00006511** The main entry point is sqlite3BtreeNext(). That routine is optimized
6512** for the common case of merely incrementing the cell counter BtCursor.aiIdx
6513** to the next cell on the current page. The (slower) btreeNext() helper
6514** routine is called when it is necessary to move to a different page or
6515** to restore the cursor.
6516**
drh89997982017-07-11 18:11:33 +00006517** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
6518** cursor corresponds to an SQL index and this routine could have been
6519** skipped if the SQL index had been a unique index. The F argument
6520** is a hint to the implement. SQLite btree implementation does not use
6521** this hint, but COMDB2 does.
drh72f82862001-05-24 21:06:34 +00006522*/
drh89997982017-07-11 18:11:33 +00006523static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00006524 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00006525 int idx;
danielk197797a227c2006-01-20 16:32:04 +00006526 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00006527
dan7a2347e2016-01-07 16:43:54 +00006528 assert( cursorOwnsBtShared(pCur) );
drhf66f26a2013-08-19 20:04:10 +00006529 if( pCur->eState!=CURSOR_VALID ){
drhee6438d2014-09-01 13:29:32 +00006530 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
drhf66f26a2013-08-19 20:04:10 +00006531 rc = restoreCursorPosition(pCur);
6532 if( rc!=SQLITE_OK ){
6533 return rc;
6534 }
6535 if( CURSOR_INVALID==pCur->eState ){
drh2ab792e2017-05-30 18:34:07 +00006536 return SQLITE_DONE;
drhf66f26a2013-08-19 20:04:10 +00006537 }
drh0c873bf2019-01-28 00:42:06 +00006538 if( pCur->eState==CURSOR_SKIPNEXT ){
drh9b47ee32013-08-20 03:13:51 +00006539 pCur->eState = CURSOR_VALID;
drh0c873bf2019-01-28 00:42:06 +00006540 if( pCur->skipNext>0 ) return SQLITE_OK;
drhf66f26a2013-08-19 20:04:10 +00006541 }
danielk1977da184232006-01-05 11:34:32 +00006542 }
danielk1977da184232006-01-05 11:34:32 +00006543
drh352a35a2017-08-15 03:46:47 +00006544 pPage = pCur->pPage;
drh75e96b32017-04-01 00:20:06 +00006545 idx = ++pCur->ix;
drh0a803bd2022-09-30 20:48:22 +00006546 if( NEVER(!pPage->isInit) || sqlite3FaultSim(412) ){
drhf3cd0c82018-06-08 19:13:57 +00006547 return SQLITE_CORRUPT_BKPT;
6548 }
danbb246c42012-01-12 14:25:55 +00006549
danielk197771d5d2c2008-09-29 11:49:47 +00006550 if( idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00006551 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006552 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drhee6438d2014-09-01 13:29:32 +00006553 if( rc ) return rc;
6554 return moveToLeftmost(pCur);
drh72f82862001-05-24 21:06:34 +00006555 }
drh5e2f8b92001-05-28 00:41:15 +00006556 do{
danielk197771d5d2c2008-09-29 11:49:47 +00006557 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00006558 pCur->eState = CURSOR_INVALID;
drh2ab792e2017-05-30 18:34:07 +00006559 return SQLITE_DONE;
drh5e2f8b92001-05-28 00:41:15 +00006560 }
danielk197730548662009-07-09 05:07:37 +00006561 moveToParent(pCur);
drh352a35a2017-08-15 03:46:47 +00006562 pPage = pCur->pPage;
drh75e96b32017-04-01 00:20:06 +00006563 }while( pCur->ix>=pPage->nCell );
drh44845222008-07-17 18:39:57 +00006564 if( pPage->intKey ){
drh89997982017-07-11 18:11:33 +00006565 return sqlite3BtreeNext(pCur, 0);
drh8b18dd42004-05-12 19:18:15 +00006566 }else{
drhee6438d2014-09-01 13:29:32 +00006567 return SQLITE_OK;
drh8b18dd42004-05-12 19:18:15 +00006568 }
drh8178a752003-01-05 21:41:40 +00006569 }
drh3aac2dd2004-04-26 14:10:20 +00006570 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00006571 return SQLITE_OK;
drhee6438d2014-09-01 13:29:32 +00006572 }else{
6573 return moveToLeftmost(pCur);
drh72f82862001-05-24 21:06:34 +00006574 }
drh72f82862001-05-24 21:06:34 +00006575}
drh2ab792e2017-05-30 18:34:07 +00006576int sqlite3BtreeNext(BtCursor *pCur, int flags){
drhee6438d2014-09-01 13:29:32 +00006577 MemPage *pPage;
drh89997982017-07-11 18:11:33 +00006578 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
dan7a2347e2016-01-07 16:43:54 +00006579 assert( cursorOwnsBtShared(pCur) );
drh2ab792e2017-05-30 18:34:07 +00006580 assert( flags==0 || flags==1 );
drhee6438d2014-09-01 13:29:32 +00006581 pCur->info.nSize = 0;
6582 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drh89997982017-07-11 18:11:33 +00006583 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
drh352a35a2017-08-15 03:46:47 +00006584 pPage = pCur->pPage;
drh75e96b32017-04-01 00:20:06 +00006585 if( (++pCur->ix)>=pPage->nCell ){
6586 pCur->ix--;
drh89997982017-07-11 18:11:33 +00006587 return btreeNext(pCur);
drhee6438d2014-09-01 13:29:32 +00006588 }
6589 if( pPage->leaf ){
6590 return SQLITE_OK;
6591 }else{
6592 return moveToLeftmost(pCur);
6593 }
6594}
drh72f82862001-05-24 21:06:34 +00006595
drh3b7511c2001-05-26 13:15:44 +00006596/*
drh2ab792e2017-05-30 18:34:07 +00006597** Step the cursor to the back to the previous entry in the database.
6598** Return values:
6599**
6600** SQLITE_OK success
6601** SQLITE_DONE the cursor is already on the first element of the table
6602** otherwise some kind of error occurred
drhe39a7322014-02-03 14:04:11 +00006603**
drhee6438d2014-09-01 13:29:32 +00006604** The main entry point is sqlite3BtreePrevious(). That routine is optimized
6605** for the common case of merely decrementing the cell counter BtCursor.aiIdx
drh3f387402014-09-24 01:23:00 +00006606** to the previous cell on the current page. The (slower) btreePrevious()
6607** helper routine is called when it is necessary to move to a different page
6608** or to restore the cursor.
drhee6438d2014-09-01 13:29:32 +00006609**
drh89997982017-07-11 18:11:33 +00006610** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
6611** the cursor corresponds to an SQL index and this routine could have been
6612** skipped if the SQL index had been a unique index. The F argument is a
6613** hint to the implement. The native SQLite btree implementation does not
6614** use this hint, but COMDB2 does.
drh2dcc9aa2002-12-04 13:40:25 +00006615*/
drh89997982017-07-11 18:11:33 +00006616static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
drh2dcc9aa2002-12-04 13:40:25 +00006617 int rc;
drh8178a752003-01-05 21:41:40 +00006618 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00006619
dan7a2347e2016-01-07 16:43:54 +00006620 assert( cursorOwnsBtShared(pCur) );
drhee6438d2014-09-01 13:29:32 +00006621 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
6622 assert( pCur->info.nSize==0 );
drhf66f26a2013-08-19 20:04:10 +00006623 if( pCur->eState!=CURSOR_VALID ){
drh7682a472014-09-29 15:00:28 +00006624 rc = restoreCursorPosition(pCur);
drhee6438d2014-09-01 13:29:32 +00006625 if( rc!=SQLITE_OK ){
6626 return rc;
drhf66f26a2013-08-19 20:04:10 +00006627 }
6628 if( CURSOR_INVALID==pCur->eState ){
drh2ab792e2017-05-30 18:34:07 +00006629 return SQLITE_DONE;
drhf66f26a2013-08-19 20:04:10 +00006630 }
drh0c873bf2019-01-28 00:42:06 +00006631 if( CURSOR_SKIPNEXT==pCur->eState ){
drh9b47ee32013-08-20 03:13:51 +00006632 pCur->eState = CURSOR_VALID;
drh0c873bf2019-01-28 00:42:06 +00006633 if( pCur->skipNext<0 ) return SQLITE_OK;
drhf66f26a2013-08-19 20:04:10 +00006634 }
danielk1977da184232006-01-05 11:34:32 +00006635 }
danielk1977da184232006-01-05 11:34:32 +00006636
drh352a35a2017-08-15 03:46:47 +00006637 pPage = pCur->pPage;
danielk197771d5d2c2008-09-29 11:49:47 +00006638 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00006639 if( !pPage->leaf ){
drh75e96b32017-04-01 00:20:06 +00006640 int idx = pCur->ix;
danielk197771d5d2c2008-09-29 11:49:47 +00006641 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
drhee6438d2014-09-01 13:29:32 +00006642 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00006643 rc = moveToRightmost(pCur);
6644 }else{
drh75e96b32017-04-01 00:20:06 +00006645 while( pCur->ix==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00006646 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00006647 pCur->eState = CURSOR_INVALID;
drh2ab792e2017-05-30 18:34:07 +00006648 return SQLITE_DONE;
drh2dcc9aa2002-12-04 13:40:25 +00006649 }
danielk197730548662009-07-09 05:07:37 +00006650 moveToParent(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00006651 }
drhee6438d2014-09-01 13:29:32 +00006652 assert( pCur->info.nSize==0 );
drhd95ef5c2016-11-11 18:19:05 +00006653 assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006654
drh75e96b32017-04-01 00:20:06 +00006655 pCur->ix--;
drh352a35a2017-08-15 03:46:47 +00006656 pPage = pCur->pPage;
drh44845222008-07-17 18:39:57 +00006657 if( pPage->intKey && !pPage->leaf ){
drh89997982017-07-11 18:11:33 +00006658 rc = sqlite3BtreePrevious(pCur, 0);
drh8b18dd42004-05-12 19:18:15 +00006659 }else{
6660 rc = SQLITE_OK;
6661 }
drh2dcc9aa2002-12-04 13:40:25 +00006662 }
drh2dcc9aa2002-12-04 13:40:25 +00006663 return rc;
6664}
drh2ab792e2017-05-30 18:34:07 +00006665int sqlite3BtreePrevious(BtCursor *pCur, int flags){
dan7a2347e2016-01-07 16:43:54 +00006666 assert( cursorOwnsBtShared(pCur) );
drh2ab792e2017-05-30 18:34:07 +00006667 assert( flags==0 || flags==1 );
drh89997982017-07-11 18:11:33 +00006668 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
drhee6438d2014-09-01 13:29:32 +00006669 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
6670 pCur->info.nSize = 0;
6671 if( pCur->eState!=CURSOR_VALID
drh75e96b32017-04-01 00:20:06 +00006672 || pCur->ix==0
drh352a35a2017-08-15 03:46:47 +00006673 || pCur->pPage->leaf==0
drhee6438d2014-09-01 13:29:32 +00006674 ){
drh89997982017-07-11 18:11:33 +00006675 return btreePrevious(pCur);
drhee6438d2014-09-01 13:29:32 +00006676 }
drh75e96b32017-04-01 00:20:06 +00006677 pCur->ix--;
drhee6438d2014-09-01 13:29:32 +00006678 return SQLITE_OK;
6679}
drh2dcc9aa2002-12-04 13:40:25 +00006680
6681/*
drh3b7511c2001-05-26 13:15:44 +00006682** Allocate a new page from the database file.
6683**
danielk19773b8a05f2007-03-19 17:44:26 +00006684** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00006685** has already been called on the new page.) The new page has also
6686** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00006687** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00006688**
6689** SQLITE_OK is returned on success. Any other return value indicates
drh1c8bade2015-05-29 18:42:11 +00006690** an error. *ppPage is set to NULL in the event of an error.
drhbea00b92002-07-08 10:59:50 +00006691**
drh82e647d2013-03-02 03:25:55 +00006692** If the "nearby" parameter is not 0, then an effort is made to
drh199e3cf2002-07-18 11:01:47 +00006693** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00006694** attempt to keep related pages close to each other in the database file,
6695** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00006696**
drh82e647d2013-03-02 03:25:55 +00006697** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
6698** anywhere on the free-list, then it is guaranteed to be returned. If
6699** eMode is BTALLOC_LT then the page returned will be less than or equal
6700** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
6701** are no restrictions on which page is returned.
drh3b7511c2001-05-26 13:15:44 +00006702*/
drh4f0c5872007-03-26 22:05:01 +00006703static int allocateBtreePage(
drh82e647d2013-03-02 03:25:55 +00006704 BtShared *pBt, /* The btree */
6705 MemPage **ppPage, /* Store pointer to the allocated page here */
6706 Pgno *pPgno, /* Store the page number here */
6707 Pgno nearby, /* Search for a page near this one */
6708 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
danielk1977cb1a7eb2004-11-05 12:27:02 +00006709){
drh3aac2dd2004-04-26 14:10:20 +00006710 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00006711 int rc;
drh35cd6432009-06-05 14:17:21 +00006712 u32 n; /* Number of pages on the freelist */
drh042d6a12009-06-17 13:57:16 +00006713 u32 k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00006714 MemPage *pTrunk = 0;
6715 MemPage *pPrevTrunk = 0;
drh1662b5a2009-06-04 19:06:09 +00006716 Pgno mxPage; /* Total size of the database file */
drh30e58752002-03-02 20:41:57 +00006717
drh1fee73e2007-08-29 04:00:57 +00006718 assert( sqlite3_mutex_held(pBt->mutex) );
dan572a21c2015-08-21 18:55:22 +00006719 assert( eMode==BTALLOC_ANY || (nearby>0 && REQUIRE_PTRMAP ) );
drh3aac2dd2004-04-26 14:10:20 +00006720 pPage1 = pBt->pPage1;
drhb1299152010-03-30 22:58:33 +00006721 mxPage = btreePagecount(pBt);
drhda017572022-11-07 12:21:06 +00006722 /* EVIDENCE-OF: R-21003-45125 The 4-byte big-endian integer at offset 36
6723 ** stores the total number of pages on the freelist. */
drh3aac2dd2004-04-26 14:10:20 +00006724 n = get4byte(&pPage1->aData[36]);
drhdf35a082009-07-09 02:24:35 +00006725 testcase( n==mxPage-1 );
dan51883df2018-12-03 19:29:37 +00006726 if( n>=mxPage ){
drh1662b5a2009-06-04 19:06:09 +00006727 return SQLITE_CORRUPT_BKPT;
6728 }
dan7b3d71e2015-08-19 20:27:05 +00006729
6730 /* Ensure page 1 is writable. This function will either change the number
6731 ** of pages in the free-list or the size of the database file. Since both
6732 ** of these operations involve modifying page 1 header fields, page 1
danbf3cf572015-08-24 19:56:04 +00006733 ** will definitely be written by this transaction. If this is an CONCURRENT
dan7b3d71e2015-08-19 20:27:05 +00006734 ** transaction, ensure the BtreePtrmap structure has been allocated. */
dan7b3d71e2015-08-19 20:27:05 +00006735 rc = sqlite3PagerWrite(pPage1->pDbPage);
6736 if( rc ) return rc;
6737
drh3aac2dd2004-04-26 14:10:20 +00006738 if( n>0 ){
drh91025292004-05-03 19:49:32 +00006739 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00006740 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006741 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
drhc6e956f2015-06-24 13:32:10 +00006742 u32 nSearch = 0; /* Count of the number of search attempts */
danielk1977cb1a7eb2004-11-05 12:27:02 +00006743
drh82e647d2013-03-02 03:25:55 +00006744 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00006745 ** shows that the page 'nearby' is somewhere on the free-list, then
6746 ** the entire-list will be searched for that page.
6747 */
dan51f0b6d2013-02-22 20:16:34 +00006748 if( eMode==BTALLOC_EXACT ){
drh43fa1a52022-12-21 20:07:58 +00006749 assert( ISAUTOVACUUM(pBt)!=ISCONCURRENT );
6750 if( ISAUTOVACUUM(pBt) ){
drh7e4f8362020-08-10 21:16:29 +00006751 if( nearby<=mxPage ){
dan70af25d2015-08-21 17:57:16 +00006752 u8 eType;
6753 assert( nearby>0 );
6754 assert( pBt->autoVacuum );
6755 rc = ptrmapGet(pBt, nearby, &eType, 0);
6756 if( rc ) return rc;
6757 if( eType==PTRMAP_FREEPAGE ){
6758 searchList = 1;
6759 }
dan51f0b6d2013-02-22 20:16:34 +00006760 }
dan70af25d2015-08-21 17:57:16 +00006761 }else{
6762 searchList = 1;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006763 }
dan572a21c2015-08-21 18:55:22 +00006764 }else if( eMode==BTALLOC_LE ){
dan51f0b6d2013-02-22 20:16:34 +00006765 searchList = 1;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006766 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006767
6768 /* Decrement the free-list count by 1. Set iTrunk to the index of the
6769 ** first free-list trunk page. iPrevTrunk is initially 1.
6770 */
drh3aac2dd2004-04-26 14:10:20 +00006771 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00006772
6773 /* The code within this loop is run only once if the 'searchList' variable
6774 ** is not true. Otherwise, it runs once for each trunk-page on the
drh82e647d2013-03-02 03:25:55 +00006775 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
6776 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
danielk1977cb1a7eb2004-11-05 12:27:02 +00006777 */
6778 do {
6779 pPrevTrunk = pTrunk;
6780 if( pPrevTrunk ){
drh113762a2014-11-19 16:36:25 +00006781 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
6782 ** is the page number of the next freelist trunk page in the list or
6783 ** zero if this is the last freelist trunk page. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00006784 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00006785 }else{
drh113762a2014-11-19 16:36:25 +00006786 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
6787 ** stores the page number of the first page of the freelist, or zero if
6788 ** the freelist is empty. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00006789 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00006790 }
drhdf35a082009-07-09 02:24:35 +00006791 testcase( iTrunk==mxPage );
drh9e7804d2015-06-24 12:24:03 +00006792 if( iTrunk>mxPage || nSearch++ > n ){
drhc62aab52017-06-11 18:26:15 +00006793 rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
drh1662b5a2009-06-04 19:06:09 +00006794 }else{
drh7e8c6f12015-05-28 03:28:27 +00006795 rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
drh1662b5a2009-06-04 19:06:09 +00006796 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006797 if( rc ){
drhd3627af2006-12-18 18:34:51 +00006798 pTrunk = 0;
6799 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006800 }
drhb07028f2011-10-14 21:49:18 +00006801 assert( pTrunk!=0 );
6802 assert( pTrunk->aData!=0 );
drh113762a2014-11-19 16:36:25 +00006803 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
6804 ** is the number of leaf page pointers to follow. */
6805 k = get4byte(&pTrunk->aData[4]);
danielk1977cb1a7eb2004-11-05 12:27:02 +00006806 if( k==0 && !searchList ){
6807 /* The trunk has no leaves and the list is not being searched.
6808 ** So extract the trunk page itself and use it as the newly
6809 ** allocated page */
6810 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00006811 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00006812 if( rc ){
6813 goto end_allocate_page;
6814 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006815 *pPgno = iTrunk;
6816 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6817 *ppPage = pTrunk;
6818 pTrunk = 0;
6819 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh042d6a12009-06-17 13:57:16 +00006820 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00006821 /* Value of k is out of range. Database corruption */
drhcc97ca42017-06-07 22:32:59 +00006822 rc = SQLITE_CORRUPT_PGNO(iTrunk);
drhd3627af2006-12-18 18:34:51 +00006823 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006824#ifndef SQLITE_OMIT_AUTOVACUUM
dan51f0b6d2013-02-22 20:16:34 +00006825 }else if( searchList
6826 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
6827 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00006828 /* The list is being searched and this trunk page is the page
6829 ** to allocate, regardless of whether it has leaves.
6830 */
dan51f0b6d2013-02-22 20:16:34 +00006831 *pPgno = iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006832 *ppPage = pTrunk;
6833 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00006834 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00006835 if( rc ){
6836 goto end_allocate_page;
6837 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006838 if( k==0 ){
6839 if( !pPrevTrunk ){
6840 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6841 }else{
danf48c3552010-08-23 15:41:24 +00006842 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6843 if( rc!=SQLITE_OK ){
6844 goto end_allocate_page;
6845 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006846 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
6847 }
6848 }else{
6849 /* The trunk page is required by the caller but it contains
6850 ** pointers to free-list leaves. The first leaf becomes a trunk
6851 ** page in this case.
6852 */
6853 MemPage *pNewTrunk;
6854 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh1662b5a2009-06-04 19:06:09 +00006855 if( iNewTrunk>mxPage ){
drhcc97ca42017-06-07 22:32:59 +00006856 rc = SQLITE_CORRUPT_PGNO(iTrunk);
drh1662b5a2009-06-04 19:06:09 +00006857 goto end_allocate_page;
6858 }
drhdf35a082009-07-09 02:24:35 +00006859 testcase( iNewTrunk==mxPage );
drh7e8c6f12015-05-28 03:28:27 +00006860 rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00006861 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00006862 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006863 }
danielk19773b8a05f2007-03-19 17:44:26 +00006864 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00006865 if( rc!=SQLITE_OK ){
6866 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00006867 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006868 }
6869 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
6870 put4byte(&pNewTrunk->aData[4], k-1);
6871 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00006872 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00006873 if( !pPrevTrunk ){
drhc5053fb2008-11-27 02:22:10 +00006874 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
danielk1977cb1a7eb2004-11-05 12:27:02 +00006875 put4byte(&pPage1->aData[32], iNewTrunk);
6876 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00006877 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00006878 if( rc ){
6879 goto end_allocate_page;
6880 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006881 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
6882 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006883 }
6884 pTrunk = 0;
6885 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
6886#endif
danielk1977e5765212009-06-17 11:13:28 +00006887 }else if( k>0 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00006888 /* Extract a leaf from the trunk */
drh042d6a12009-06-17 13:57:16 +00006889 u32 closest;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006890 Pgno iPage;
6891 unsigned char *aData = pTrunk->aData;
6892 if( nearby>0 ){
drh042d6a12009-06-17 13:57:16 +00006893 u32 i;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006894 closest = 0;
danf38b65a2013-02-22 20:57:47 +00006895 if( eMode==BTALLOC_LE ){
6896 for(i=0; i<k; i++){
6897 iPage = get4byte(&aData[8+i*4]);
dan87ade192013-02-23 17:49:16 +00006898 if( iPage<=nearby ){
danf38b65a2013-02-22 20:57:47 +00006899 closest = i;
6900 break;
6901 }
6902 }
6903 }else{
6904 int dist;
6905 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
6906 for(i=1; i<k; i++){
6907 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
6908 if( d2<dist ){
6909 closest = i;
6910 dist = d2;
6911 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006912 }
6913 }
6914 }else{
6915 closest = 0;
6916 }
6917
6918 iPage = get4byte(&aData[8+closest*4]);
drhdf35a082009-07-09 02:24:35 +00006919 testcase( iPage==mxPage );
drh07812192021-04-07 12:21:35 +00006920 if( iPage>mxPage || iPage<2 ){
drhcc97ca42017-06-07 22:32:59 +00006921 rc = SQLITE_CORRUPT_PGNO(iTrunk);
drh1662b5a2009-06-04 19:06:09 +00006922 goto end_allocate_page;
6923 }
drhdf35a082009-07-09 02:24:35 +00006924 testcase( iPage==mxPage );
dan51f0b6d2013-02-22 20:16:34 +00006925 if( !searchList
6926 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
6927 ){
danielk1977bea2a942009-01-20 17:06:27 +00006928 int noContent;
shane1f9e6aa2008-06-09 19:27:11 +00006929 *pPgno = iPage;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006930 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
6931 ": %d more free pages\n",
6932 *pPgno, closest+1, k, pTrunk->pgno, n-1));
drh93b4fc72011-04-07 14:47:01 +00006933 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6934 if( rc ) goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006935 if( closest<k-1 ){
6936 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
6937 }
6938 put4byte(&aData[4], k-1);
drh3f387402014-09-24 01:23:00 +00006939 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
drh7e8c6f12015-05-28 03:28:27 +00006940 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
danielk1977cb1a7eb2004-11-05 12:27:02 +00006941 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00006942 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00006943 if( rc!=SQLITE_OK ){
6944 releasePage(*ppPage);
drh1c8bade2015-05-29 18:42:11 +00006945 *ppPage = 0;
danielk1977aac0a382005-01-16 11:07:06 +00006946 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006947 }
6948 searchList = 0;
6949 }
drhee696e22004-08-30 16:52:17 +00006950 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00006951 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00006952 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00006953 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00006954 }else{
danbc1a3c62013-02-23 16:40:46 +00006955 /* There are no pages on the freelist, so append a new page to the
6956 ** database image.
6957 **
6958 ** Normally, new pages allocated by this block can be requested from the
6959 ** pager layer with the 'no-content' flag set. This prevents the pager
6960 ** from trying to read the pages content from disk. However, if the
6961 ** current transaction has already run one or more incremental-vacuum
6962 ** steps, then the page we are about to allocate may contain content
6963 ** that is required in the event of a rollback. In this case, do
6964 ** not set the no-content flag. This causes the pager to load and journal
6965 ** the current page content before overwriting it.
6966 **
6967 ** Note that the pager will not actually attempt to load or journal
6968 ** content for any page that really does lie past the end of the database
6969 ** file on disk. So the effects of disabling the no-content optimization
6970 ** here are confined to those pages that lie between the end of the
6971 ** database image and the end of the database file.
6972 */
drh3f387402014-09-24 01:23:00 +00006973 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
danbc1a3c62013-02-23 16:40:46 +00006974
drhdd3cd972010-03-27 17:12:36 +00006975 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6976 if( rc ) return rc;
6977 pBt->nPage++;
6978 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
danielk1977bea2a942009-01-20 17:06:27 +00006979
danielk1977afcdd022004-10-31 16:25:42 +00006980#ifndef SQLITE_OMIT_AUTOVACUUM
drhdd3cd972010-03-27 17:12:36 +00006981 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
danielk1977afcdd022004-10-31 16:25:42 +00006982 /* If *pPgno refers to a pointer-map page, allocate two new pages
6983 ** at the end of the file instead of one. The first allocated page
6984 ** becomes a new pointer-map page, the second is used by the caller.
6985 */
danielk1977ac861692009-03-28 10:54:22 +00006986 MemPage *pPg = 0;
drhdd3cd972010-03-27 17:12:36 +00006987 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
6988 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
drh7e8c6f12015-05-28 03:28:27 +00006989 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
danielk1977ac861692009-03-28 10:54:22 +00006990 if( rc==SQLITE_OK ){
6991 rc = sqlite3PagerWrite(pPg->pDbPage);
6992 releasePage(pPg);
6993 }
6994 if( rc ) return rc;
drhdd3cd972010-03-27 17:12:36 +00006995 pBt->nPage++;
6996 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
danielk1977afcdd022004-10-31 16:25:42 +00006997 }
6998#endif
drhdd3cd972010-03-27 17:12:36 +00006999 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
7000 *pPgno = pBt->nPage;
danielk1977afcdd022004-10-31 16:25:42 +00007001
danielk1977599fcba2004-11-08 07:13:13 +00007002 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh7e8c6f12015-05-28 03:28:27 +00007003 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
drh3b7511c2001-05-26 13:15:44 +00007004 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00007005 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00007006 if( rc!=SQLITE_OK ){
7007 releasePage(*ppPage);
drh7e8c6f12015-05-28 03:28:27 +00007008 *ppPage = 0;
danielk1977aac0a382005-01-16 11:07:06 +00007009 }
drh3a4c1412004-05-09 20:40:11 +00007010 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00007011 }
danielk1977599fcba2004-11-08 07:13:13 +00007012
danba14c692019-01-25 13:42:12 +00007013 assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00007014
7015end_allocate_page:
7016 releasePage(pTrunk);
7017 releasePage(pPrevTrunk);
drh7e8c6f12015-05-28 03:28:27 +00007018 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
7019 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
drh3b7511c2001-05-26 13:15:44 +00007020 return rc;
7021}
7022
7023/*
danielk1977bea2a942009-01-20 17:06:27 +00007024** This function is used to add page iPage to the database file free-list.
7025** It is assumed that the page is not already a part of the free-list.
drh5e2f8b92001-05-28 00:41:15 +00007026**
danielk1977bea2a942009-01-20 17:06:27 +00007027** The value passed as the second argument to this function is optional.
7028** If the caller happens to have a pointer to the MemPage object
7029** corresponding to page iPage handy, it may pass it as the second value.
7030** Otherwise, it may pass NULL.
7031**
7032** If a pointer to a MemPage object is passed as the second argument,
7033** its reference count is not altered by this function.
drh3b7511c2001-05-26 13:15:44 +00007034*/
danielk1977bea2a942009-01-20 17:06:27 +00007035static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
7036 MemPage *pTrunk = 0; /* Free-list trunk page */
7037 Pgno iTrunk = 0; /* Page number of free-list trunk page */
7038 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
7039 MemPage *pPage; /* Page being freed. May be NULL. */
7040 int rc; /* Return Code */
drh25050f22019-04-09 01:26:31 +00007041 u32 nFree; /* Initial number of pages on free-list */
drh8b2f49b2001-06-08 00:21:52 +00007042
danielk1977bea2a942009-01-20 17:06:27 +00007043 assert( sqlite3_mutex_held(pBt->mutex) );
danfb0246b2015-05-26 12:18:17 +00007044 assert( CORRUPT_DB || iPage>1 );
danielk1977bea2a942009-01-20 17:06:27 +00007045 assert( !pMemPage || pMemPage->pgno==iPage );
7046
drh9a4e8862022-02-14 18:18:56 +00007047 if( iPage<2 || iPage>pBt->nPage ){
drh58b42ad2019-03-25 19:50:19 +00007048 return SQLITE_CORRUPT_BKPT;
7049 }
danielk1977bea2a942009-01-20 17:06:27 +00007050 if( pMemPage ){
7051 pPage = pMemPage;
7052 sqlite3PagerRef(pPage->pDbPage);
7053 }else{
7054 pPage = btreePageLookup(pBt, iPage);
7055 }
drh3aac2dd2004-04-26 14:10:20 +00007056
drha34b6762004-05-07 13:30:42 +00007057 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00007058 rc = sqlite3PagerWrite(pPage1->pDbPage);
danielk1977bea2a942009-01-20 17:06:27 +00007059 if( rc ) goto freepage_out;
7060 nFree = get4byte(&pPage1->aData[36]);
7061 put4byte(&pPage1->aData[36], nFree+1);
drh3aac2dd2004-04-26 14:10:20 +00007062
drhc9166342012-01-05 23:32:06 +00007063 if( pBt->btsFlags & BTS_SECURE_DELETE ){
drh5b47efa2010-02-12 18:18:39 +00007064 /* If the secure_delete option is enabled, then
7065 ** always fully overwrite deleted information with zeros.
7066 */
drhb00fc3b2013-08-21 23:42:32 +00007067 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
shaneh84f4b2f2010-02-26 01:46:54 +00007068 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
drh5b47efa2010-02-12 18:18:39 +00007069 ){
7070 goto freepage_out;
7071 }
7072 memset(pPage->aData, 0, pPage->pBt->pageSize);
danielk1977bea2a942009-01-20 17:06:27 +00007073 }
drhfcce93f2006-02-22 03:08:32 +00007074
danielk1977687566d2004-11-02 12:56:41 +00007075 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00007076 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00007077 */
dan7b3d71e2015-08-19 20:27:05 +00007078 if( REQUIRE_PTRMAP ){
drh98add2e2009-07-20 17:11:49 +00007079 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
danielk1977bea2a942009-01-20 17:06:27 +00007080 if( rc ) goto freepage_out;
danielk1977687566d2004-11-02 12:56:41 +00007081 }
danielk1977687566d2004-11-02 12:56:41 +00007082
danielk1977bea2a942009-01-20 17:06:27 +00007083 /* Now manipulate the actual database free-list structure. There are two
7084 ** possibilities. If the free-list is currently empty, or if the first
7085 ** trunk page in the free-list is full, then this page will become a
7086 ** new free-list trunk page. Otherwise, it will become a leaf of the
7087 ** first trunk page in the current free-list. This block tests if it
7088 ** is possible to add the page as a new free-list leaf.
7089 */
7090 if( nFree!=0 ){
drhc046e3e2009-07-15 11:26:44 +00007091 u32 nLeaf; /* Initial number of leaf cells on trunk page */
danielk1977bea2a942009-01-20 17:06:27 +00007092
7093 iTrunk = get4byte(&pPage1->aData[32]);
drh10248222020-07-28 20:32:12 +00007094 if( iTrunk>btreePagecount(pBt) ){
7095 rc = SQLITE_CORRUPT_BKPT;
7096 goto freepage_out;
7097 }
drhb00fc3b2013-08-21 23:42:32 +00007098 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977bea2a942009-01-20 17:06:27 +00007099 if( rc!=SQLITE_OK ){
7100 goto freepage_out;
7101 }
7102
7103 nLeaf = get4byte(&pTrunk->aData[4]);
drheeb844a2009-08-08 18:01:07 +00007104 assert( pBt->usableSize>32 );
7105 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
danielk1977bea2a942009-01-20 17:06:27 +00007106 rc = SQLITE_CORRUPT_BKPT;
7107 goto freepage_out;
7108 }
drheeb844a2009-08-08 18:01:07 +00007109 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
danielk1977bea2a942009-01-20 17:06:27 +00007110 /* In this case there is room on the trunk page to insert the page
7111 ** being freed as a new leaf.
drh45b1fac2008-07-04 17:52:42 +00007112 **
7113 ** Note that the trunk page is not really full until it contains
7114 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
7115 ** coded. But due to a coding error in versions of SQLite prior to
7116 ** 3.6.0, databases with freelist trunk pages holding more than
7117 ** usableSize/4 - 8 entries will be reported as corrupt. In order
7118 ** to maintain backwards compatibility with older versions of SQLite,
drhc046e3e2009-07-15 11:26:44 +00007119 ** we will continue to restrict the number of entries to usableSize/4 - 8
drh45b1fac2008-07-04 17:52:42 +00007120 ** for now. At some point in the future (once everyone has upgraded
7121 ** to 3.6.0 or later) we should consider fixing the conditional above
7122 ** to read "usableSize/4-2" instead of "usableSize/4-8".
drh113762a2014-11-19 16:36:25 +00007123 **
7124 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
7125 ** avoid using the last six entries in the freelist trunk page array in
7126 ** order that database files created by newer versions of SQLite can be
7127 ** read by older versions of SQLite.
drh45b1fac2008-07-04 17:52:42 +00007128 */
danielk19773b8a05f2007-03-19 17:44:26 +00007129 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00007130 if( rc==SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00007131 put4byte(&pTrunk->aData[4], nLeaf+1);
7132 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
drhc9166342012-01-05 23:32:06 +00007133 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
danielk1977bea2a942009-01-20 17:06:27 +00007134 sqlite3PagerDontWrite(pPage->pDbPage);
7135 }
danielk1977bea2a942009-01-20 17:06:27 +00007136 rc = btreeSetHasContent(pBt, iPage);
drhf5345442007-04-09 12:45:02 +00007137 }
drh3a4c1412004-05-09 20:40:11 +00007138 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
danielk1977bea2a942009-01-20 17:06:27 +00007139 goto freepage_out;
drh3aac2dd2004-04-26 14:10:20 +00007140 }
drh3b7511c2001-05-26 13:15:44 +00007141 }
danielk1977bea2a942009-01-20 17:06:27 +00007142
7143 /* If control flows to this point, then it was not possible to add the
7144 ** the page being freed as a leaf page of the first trunk in the free-list.
7145 ** Possibly because the free-list is empty, or possibly because the
7146 ** first trunk in the free-list is full. Either way, the page being freed
7147 ** will become the new first trunk page in the free-list.
7148 */
drhb00fc3b2013-08-21 23:42:32 +00007149 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
drhc046e3e2009-07-15 11:26:44 +00007150 goto freepage_out;
7151 }
7152 rc = sqlite3PagerWrite(pPage->pDbPage);
7153 if( rc!=SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00007154 goto freepage_out;
7155 }
7156 put4byte(pPage->aData, iTrunk);
7157 put4byte(&pPage->aData[4], 0);
7158 put4byte(&pPage1->aData[32], iPage);
7159 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
7160
7161freepage_out:
7162 if( pPage ){
7163 pPage->isInit = 0;
7164 }
7165 releasePage(pPage);
7166 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00007167 return rc;
7168}
drhc314dc72009-07-21 11:52:34 +00007169static void freePage(MemPage *pPage, int *pRC){
7170 if( (*pRC)==SQLITE_OK ){
7171 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
7172 }
danielk1977bea2a942009-01-20 17:06:27 +00007173}
drh3b7511c2001-05-26 13:15:44 +00007174
7175/*
drh86c779f2021-05-15 13:08:44 +00007176** Free the overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00007177*/
drh86c779f2021-05-15 13:08:44 +00007178static SQLITE_NOINLINE int clearCellOverflow(
drh9bfdc252014-09-24 02:05:41 +00007179 MemPage *pPage, /* The page that contains the Cell */
7180 unsigned char *pCell, /* First byte of the Cell */
drh80159da2016-12-09 17:32:51 +00007181 CellInfo *pInfo /* Size information about the cell */
drh9bfdc252014-09-24 02:05:41 +00007182){
drh60172a52017-08-02 18:27:50 +00007183 BtShared *pBt;
drh3aac2dd2004-04-26 14:10:20 +00007184 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00007185 int rc;
drh94440812007-03-06 11:42:19 +00007186 int nOvfl;
shaneh1df2db72010-08-18 02:28:48 +00007187 u32 ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00007188
drh1fee73e2007-08-29 04:00:57 +00007189 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh86c779f2021-05-15 13:08:44 +00007190 assert( pInfo->nLocal!=pInfo->nPayload );
drh6fcf83a2018-05-05 01:23:28 +00007191 testcase( pCell + pInfo->nSize == pPage->aDataEnd );
7192 testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
7193 if( pCell + pInfo->nSize > pPage->aDataEnd ){
drhcc97ca42017-06-07 22:32:59 +00007194 /* Cell extends past end of page */
daneebf2f52017-11-18 17:30:08 +00007195 return SQLITE_CORRUPT_PAGE(pPage);
drhe42a9b42011-08-31 13:27:19 +00007196 }
drh80159da2016-12-09 17:32:51 +00007197 ovflPgno = get4byte(pCell + pInfo->nSize - 4);
drh60172a52017-08-02 18:27:50 +00007198 pBt = pPage->pBt;
shane63207ab2009-02-04 01:49:30 +00007199 assert( pBt->usableSize > 4 );
drh94440812007-03-06 11:42:19 +00007200 ovflPageSize = pBt->usableSize - 4;
drh80159da2016-12-09 17:32:51 +00007201 nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
dan0f8076d2015-05-25 18:47:26 +00007202 assert( nOvfl>0 ||
drh80159da2016-12-09 17:32:51 +00007203 (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
dan0f8076d2015-05-25 18:47:26 +00007204 );
drh72365832007-03-06 15:53:44 +00007205 while( nOvfl-- ){
shane63207ab2009-02-04 01:49:30 +00007206 Pgno iNext = 0;
danielk1977bea2a942009-01-20 17:06:27 +00007207 MemPage *pOvfl = 0;
drhb1299152010-03-30 22:58:33 +00007208 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
danielk1977e589a672009-04-11 16:06:15 +00007209 /* 0 is not a legal page number and page 1 cannot be an
7210 ** overflow page. Therefore if ovflPgno<2 or past the end of the
7211 ** file the database must be corrupt. */
drh49285702005-09-17 15:20:26 +00007212 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00007213 }
danielk1977bea2a942009-01-20 17:06:27 +00007214 if( nOvfl ){
7215 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
7216 if( rc ) return rc;
7217 }
dan887d4b22010-02-25 12:09:16 +00007218
shaneh1da207e2010-03-09 14:41:12 +00007219 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
dan887d4b22010-02-25 12:09:16 +00007220 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
7221 ){
7222 /* There is no reason any cursor should have an outstanding reference
7223 ** to an overflow page belonging to a cell that is being deleted/updated.
7224 ** So if there exists more than one reference to this page, then it
7225 ** must not really be an overflow page and the database must be corrupt.
7226 ** It is helpful to detect this before calling freePage2(), as
7227 ** freePage2() may zero the page contents if secure-delete mode is
7228 ** enabled. If this 'overflow' page happens to be a page that the
7229 ** caller is iterating through or using in some other way, this
7230 ** can be problematic.
7231 */
7232 rc = SQLITE_CORRUPT_BKPT;
7233 }else{
7234 rc = freePage2(pBt, pOvfl, ovflPgno);
7235 }
7236
danielk1977bea2a942009-01-20 17:06:27 +00007237 if( pOvfl ){
7238 sqlite3PagerUnref(pOvfl->pDbPage);
7239 }
drh3b7511c2001-05-26 13:15:44 +00007240 if( rc ) return rc;
danielk1977bea2a942009-01-20 17:06:27 +00007241 ovflPgno = iNext;
drh3b7511c2001-05-26 13:15:44 +00007242 }
drh5e2f8b92001-05-28 00:41:15 +00007243 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00007244}
7245
drh86c779f2021-05-15 13:08:44 +00007246/* Call xParseCell to compute the size of a cell. If the cell contains
7247** overflow, then invoke cellClearOverflow to clear out that overflow.
7248** STore the result code (SQLITE_OK or some error code) in rc.
7249**
7250** Implemented as macro to force inlining for performance.
7251*/
7252#define BTREE_CLEAR_CELL(rc, pPage, pCell, sInfo) \
7253 pPage->xParseCell(pPage, pCell, &sInfo); \
7254 if( sInfo.nLocal!=sInfo.nPayload ){ \
7255 rc = clearCellOverflow(pPage, pCell, &sInfo); \
7256 }else{ \
7257 rc = SQLITE_OK; \
7258 }
7259
7260
drh3b7511c2001-05-26 13:15:44 +00007261/*
drh91025292004-05-03 19:49:32 +00007262** Create the byte sequence used to represent a cell on page pPage
7263** and write that byte sequence into pCell[]. Overflow pages are
7264** allocated and filled in as necessary. The calling procedure
7265** is responsible for making sure sufficient space has been allocated
7266** for pCell[].
7267**
7268** Note that pCell does not necessary need to point to the pPage->aData
7269** area. pCell might point to some temporary storage. The cell will
7270** be constructed in this temporary area then copied into pPage->aData
7271** later.
drh3b7511c2001-05-26 13:15:44 +00007272*/
7273static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00007274 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00007275 unsigned char *pCell, /* Complete text of the cell */
drh8eeb4462016-05-21 20:03:42 +00007276 const BtreePayload *pX, /* Payload with which to construct the cell */
drh4b70f112004-05-02 21:12:19 +00007277 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00007278){
drh3b7511c2001-05-26 13:15:44 +00007279 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00007280 const u8 *pSrc;
drh5e27e1d2017-08-23 14:45:59 +00007281 int nSrc, n, rc, mn;
drh3aac2dd2004-04-26 14:10:20 +00007282 int spaceLeft;
drh5e27e1d2017-08-23 14:45:59 +00007283 MemPage *pToRelease;
drh3aac2dd2004-04-26 14:10:20 +00007284 unsigned char *pPrior;
7285 unsigned char *pPayload;
drh5e27e1d2017-08-23 14:45:59 +00007286 BtShared *pBt;
7287 Pgno pgnoOvfl;
drh4b70f112004-05-02 21:12:19 +00007288 int nHeader;
drh3b7511c2001-05-26 13:15:44 +00007289
drh1fee73e2007-08-29 04:00:57 +00007290 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00007291
drhc5053fb2008-11-27 02:22:10 +00007292 /* pPage is not necessarily writeable since pCell might be auxiliary
7293 ** buffer space that is separate from the pPage buffer area */
drh5e27e1d2017-08-23 14:45:59 +00007294 assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
drhc5053fb2008-11-27 02:22:10 +00007295 || sqlite3PagerIswriteable(pPage->pDbPage) );
7296
drh91025292004-05-03 19:49:32 +00007297 /* Fill in the header. */
drh6200c882014-09-23 22:36:25 +00007298 nHeader = pPage->childPtrSize;
drh3aac2dd2004-04-26 14:10:20 +00007299 if( pPage->intKey ){
drhdfc2daa2016-05-21 23:25:29 +00007300 nPayload = pX->nData + pX->nZero;
7301 pSrc = pX->pData;
7302 nSrc = pX->nData;
7303 assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
drh3b7511c2001-05-26 13:15:44 +00007304 nHeader += putVarint32(&pCell[nHeader], nPayload);
drhdfc2daa2016-05-21 23:25:29 +00007305 nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
drh3b7511c2001-05-26 13:15:44 +00007306 }else{
drh8eeb4462016-05-21 20:03:42 +00007307 assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
7308 nSrc = nPayload = (int)pX->nKey;
7309 pSrc = pX->pKey;
drhdfc2daa2016-05-21 23:25:29 +00007310 nHeader += putVarint32(&pCell[nHeader], nPayload);
drh3aac2dd2004-04-26 14:10:20 +00007311 }
drhdfc2daa2016-05-21 23:25:29 +00007312
7313 /* Fill in the payload */
drh5e27e1d2017-08-23 14:45:59 +00007314 pPayload = &pCell[nHeader];
drh6200c882014-09-23 22:36:25 +00007315 if( nPayload<=pPage->maxLocal ){
drh5e27e1d2017-08-23 14:45:59 +00007316 /* This is the common case where everything fits on the btree page
7317 ** and no overflow pages are required. */
drh6200c882014-09-23 22:36:25 +00007318 n = nHeader + nPayload;
7319 testcase( n==3 );
7320 testcase( n==4 );
7321 if( n<4 ) n = 4;
7322 *pnSize = n;
drh5e27e1d2017-08-23 14:45:59 +00007323 assert( nSrc<=nPayload );
7324 testcase( nSrc<nPayload );
7325 memcpy(pPayload, pSrc, nSrc);
7326 memset(pPayload+nSrc, 0, nPayload-nSrc);
7327 return SQLITE_OK;
drh6200c882014-09-23 22:36:25 +00007328 }
drh5e27e1d2017-08-23 14:45:59 +00007329
7330 /* If we reach this point, it means that some of the content will need
7331 ** to spill onto overflow pages.
7332 */
7333 mn = pPage->minLocal;
7334 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
7335 testcase( n==pPage->maxLocal );
7336 testcase( n==pPage->maxLocal+1 );
7337 if( n > pPage->maxLocal ) n = mn;
7338 spaceLeft = n;
7339 *pnSize = n + nHeader + 4;
7340 pPrior = &pCell[nHeader+n];
7341 pToRelease = 0;
7342 pgnoOvfl = 0;
7343 pBt = pPage->pBt;
drh3b7511c2001-05-26 13:15:44 +00007344
drh6200c882014-09-23 22:36:25 +00007345 /* At this point variables should be set as follows:
7346 **
7347 ** nPayload Total payload size in bytes
7348 ** pPayload Begin writing payload here
7349 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
7350 ** that means content must spill into overflow pages.
7351 ** *pnSize Size of the local cell (not counting overflow pages)
7352 ** pPrior Where to write the pgno of the first overflow page
7353 **
7354 ** Use a call to btreeParseCellPtr() to verify that the values above
7355 ** were computed correctly.
7356 */
drhd879e3e2017-02-13 13:35:55 +00007357#ifdef SQLITE_DEBUG
drh6200c882014-09-23 22:36:25 +00007358 {
7359 CellInfo info;
drh5fa60512015-06-19 17:19:34 +00007360 pPage->xParseCell(pPage, pCell, &info);
drhcc5f8a42016-02-06 22:32:06 +00007361 assert( nHeader==(int)(info.pPayload - pCell) );
drh8eeb4462016-05-21 20:03:42 +00007362 assert( info.nKey==pX->nKey );
drh6200c882014-09-23 22:36:25 +00007363 assert( *pnSize == info.nSize );
7364 assert( spaceLeft == info.nLocal );
drh6200c882014-09-23 22:36:25 +00007365 }
7366#endif
7367
7368 /* Write the payload into the local Cell and any extra into overflow pages */
drh5e27e1d2017-08-23 14:45:59 +00007369 while( 1 ){
7370 n = nPayload;
7371 if( n>spaceLeft ) n = spaceLeft;
7372
7373 /* If pToRelease is not zero than pPayload points into the data area
7374 ** of pToRelease. Make sure pToRelease is still writeable. */
7375 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
7376
7377 /* If pPayload is part of the data area of pPage, then make sure pPage
7378 ** is still writeable */
7379 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
7380 || sqlite3PagerIswriteable(pPage->pDbPage) );
7381
7382 if( nSrc>=n ){
7383 memcpy(pPayload, pSrc, n);
7384 }else if( nSrc>0 ){
7385 n = nSrc;
7386 memcpy(pPayload, pSrc, n);
7387 }else{
7388 memset(pPayload, 0, n);
7389 }
7390 nPayload -= n;
7391 if( nPayload<=0 ) break;
7392 pPayload += n;
7393 pSrc += n;
7394 nSrc -= n;
7395 spaceLeft -= n;
drh3b7511c2001-05-26 13:15:44 +00007396 if( spaceLeft==0 ){
drh5e27e1d2017-08-23 14:45:59 +00007397 MemPage *pOvfl = 0;
danielk1977afcdd022004-10-31 16:25:42 +00007398#ifndef SQLITE_OMIT_AUTOVACUUM
7399 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00007400 if( pBt->autoVacuum ){
7401 do{
7402 pgnoOvfl++;
7403 } while(
7404 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
7405 );
danielk1977b39f70b2007-05-17 18:28:11 +00007406 }
danielk1977afcdd022004-10-31 16:25:42 +00007407#endif
drhf49661a2008-12-10 16:45:50 +00007408 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
dan7b3d71e2015-08-19 20:27:05 +00007409
danielk1977a19df672004-11-03 11:37:07 +00007410 /* If the database supports auto-vacuum, and the second or subsequent
7411 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00007412 ** for that page now.
7413 **
7414 ** If this is the first overflow page, then write a partial entry
7415 ** to the pointer-map. If we write nothing to this pointer-map slot,
7416 ** then the optimistic overflow chain processing in clearCell()
mistachkin48864df2013-03-21 21:20:32 +00007417 ** may misinterpret the uninitialized values and delete the
danielk19774ef24492007-05-23 09:52:41 +00007418 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00007419 */
dan7b3d71e2015-08-19 20:27:05 +00007420 if( REQUIRE_PTRMAP && rc==SQLITE_OK ){
danielk19774ef24492007-05-23 09:52:41 +00007421 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
drh98add2e2009-07-20 17:11:49 +00007422 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
danielk197789a4be82007-05-23 13:34:32 +00007423 if( rc ){
7424 releasePage(pOvfl);
7425 }
danielk1977afcdd022004-10-31 16:25:42 +00007426 }
drh3b7511c2001-05-26 13:15:44 +00007427 if( rc ){
drh9b171272004-05-08 02:03:22 +00007428 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00007429 return rc;
7430 }
drhc5053fb2008-11-27 02:22:10 +00007431
7432 /* If pToRelease is not zero than pPrior points into the data area
7433 ** of pToRelease. Make sure pToRelease is still writeable. */
7434 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
7435
7436 /* If pPrior is part of the data area of pPage, then make sure pPage
7437 ** is still writeable */
7438 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
7439 || sqlite3PagerIswriteable(pPage->pDbPage) );
7440
drh3aac2dd2004-04-26 14:10:20 +00007441 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00007442 releasePage(pToRelease);
7443 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00007444 pPrior = pOvfl->aData;
7445 put4byte(pPrior, 0);
7446 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00007447 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00007448 }
drhdd793422001-06-28 01:54:48 +00007449 }
drh9b171272004-05-08 02:03:22 +00007450 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00007451 return SQLITE_OK;
7452}
7453
drh14acc042001-06-10 19:56:58 +00007454/*
7455** Remove the i-th cell from pPage. This routine effects pPage only.
7456** The cell content is not freed or deallocated. It is assumed that
7457** the cell content has been copied someplace else. This routine just
7458** removes the reference to the cell from pPage.
7459**
7460** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00007461*/
drh98add2e2009-07-20 17:11:49 +00007462static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
drh43b18e12010-08-17 19:40:08 +00007463 u32 pc; /* Offset to cell content of cell being deleted */
drh43605152004-05-29 21:46:49 +00007464 u8 *data; /* pPage->aData */
7465 u8 *ptr; /* Used to move bytes around within data[] */
shanedcc50b72008-11-13 18:29:50 +00007466 int rc; /* The return code */
drhc314dc72009-07-21 11:52:34 +00007467 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
drh43605152004-05-29 21:46:49 +00007468
drh98add2e2009-07-20 17:11:49 +00007469 if( *pRC ) return;
drh2dfe9662022-01-02 11:25:51 +00007470 assert( idx>=0 );
7471 assert( idx<pPage->nCell );
dan0f8076d2015-05-25 18:47:26 +00007472 assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00007473 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00007474 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhb0ea9432019-02-09 21:06:40 +00007475 assert( pPage->nFree>=0 );
drhda200cc2004-05-09 11:51:38 +00007476 data = pPage->aData;
drh3def2352011-11-11 00:27:15 +00007477 ptr = &pPage->aCellIdx[2*idx];
mistachkinbeacaac2022-01-12 00:28:12 +00007478 assert( pPage->pBt->usableSize > (u32)(ptr-data) );
shane0af3f892008-11-12 04:55:34 +00007479 pc = get2byte(ptr);
drhc314dc72009-07-21 11:52:34 +00007480 hdr = pPage->hdrOffset;
mistachkin2b5fbb22021-12-31 18:26:50 +00007481 testcase( pc==(u32)get2byte(&data[hdr+5]) );
drhc314dc72009-07-21 11:52:34 +00007482 testcase( pc+sz==pPage->pBt->usableSize );
drh5e398e42017-08-23 20:36:06 +00007483 if( pc+sz > pPage->pBt->usableSize ){
drh98add2e2009-07-20 17:11:49 +00007484 *pRC = SQLITE_CORRUPT_BKPT;
7485 return;
shane0af3f892008-11-12 04:55:34 +00007486 }
shanedcc50b72008-11-13 18:29:50 +00007487 rc = freeSpace(pPage, pc, sz);
drh98add2e2009-07-20 17:11:49 +00007488 if( rc ){
7489 *pRC = rc;
7490 return;
shanedcc50b72008-11-13 18:29:50 +00007491 }
drh14acc042001-06-10 19:56:58 +00007492 pPage->nCell--;
drhfdab0262014-11-20 15:30:50 +00007493 if( pPage->nCell==0 ){
7494 memset(&data[hdr+1], 0, 4);
7495 data[hdr+7] = 0;
7496 put2byte(&data[hdr+5], pPage->pBt->usableSize);
7497 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
7498 - pPage->childPtrSize - 8;
7499 }else{
7500 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
7501 put2byte(&data[hdr+3], pPage->nCell);
7502 pPage->nFree += 2;
7503 }
drh14acc042001-06-10 19:56:58 +00007504}
7505
7506/*
7507** Insert a new cell on pPage at cell index "i". pCell points to the
7508** content of the cell.
7509**
7510** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00007511** will not fit, then make a copy of the cell content into pTemp if
7512** pTemp is not null. Regardless of pTemp, allocate a new entry
drh2cbd78b2012-02-02 19:37:18 +00007513** in pPage->apOvfl[] and make it point to the cell content (either
drh43605152004-05-29 21:46:49 +00007514** in pTemp or the original pCell) and also record its index.
7515** Allocating a new entry in pPage->aCell[] implies that
7516** pPage->nOverflow is incremented.
drh14acc042001-06-10 19:56:58 +00007517*/
drhb53d8fa2022-11-21 15:55:57 +00007518static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00007519 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00007520 int i, /* New cell becomes the i-th cell of the page */
7521 u8 *pCell, /* Content of the new cell */
7522 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00007523 u8 *pTemp, /* Temp storage space for pCell, if needed */
drhb53d8fa2022-11-21 15:55:57 +00007524 Pgno iChild /* If non-zero, replace first 4 bytes with this value */
drh24cd67e2004-05-10 16:18:47 +00007525){
drh383d30f2010-02-26 13:07:37 +00007526 int idx = 0; /* Where to write new cell content in data[] */
drh43605152004-05-29 21:46:49 +00007527 int j; /* Loop counter */
drh43605152004-05-29 21:46:49 +00007528 u8 *data; /* The content of the whole page */
drh2c8fb922015-06-25 19:53:48 +00007529 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
danielk19774dbaa892009-06-16 16:50:22 +00007530
drh43605152004-05-29 21:46:49 +00007531 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
danf216e322014-08-14 19:53:37 +00007532 assert( MX_CELL(pPage->pBt)<=10921 );
7533 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
drh2cbd78b2012-02-02 19:37:18 +00007534 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
7535 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
drh1fee73e2007-08-29 04:00:57 +00007536 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh996f5cc2019-07-17 16:18:01 +00007537 assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
drhb0ea9432019-02-09 21:06:40 +00007538 assert( pPage->nFree>=0 );
drh43605152004-05-29 21:46:49 +00007539 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00007540 if( pTemp ){
drhd6176c42014-10-11 17:22:55 +00007541 memcpy(pTemp, pCell, sz);
drh43605152004-05-29 21:46:49 +00007542 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00007543 }
danielk19774dbaa892009-06-16 16:50:22 +00007544 if( iChild ){
7545 put4byte(pCell, iChild);
7546 }
drh43605152004-05-29 21:46:49 +00007547 j = pPage->nOverflow++;
drha2ee5892016-12-09 16:02:00 +00007548 /* Comparison against ArraySize-1 since we hold back one extra slot
7549 ** as a contingency. In other words, never need more than 3 overflow
7550 ** slots but 4 are allocated, just to be safe. */
7551 assert( j < ArraySize(pPage->apOvfl)-1 );
drh2cbd78b2012-02-02 19:37:18 +00007552 pPage->apOvfl[j] = pCell;
7553 pPage->aiOvfl[j] = (u16)i;
drhfe647dc2015-06-23 18:24:25 +00007554
7555 /* When multiple overflows occur, they are always sequential and in
7556 ** sorted order. This invariants arise because multiple overflows can
7557 ** only occur when inserting divider cells into the parent page during
7558 ** balancing, and the dividers are adjacent and sorted.
7559 */
7560 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
7561 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
drh14acc042001-06-10 19:56:58 +00007562 }else{
dan7b3d71e2015-08-19 20:27:05 +00007563 BtShared *pBt = pPage->pBt;
danielk19776e465eb2007-08-21 13:11:00 +00007564 int rc = sqlite3PagerWrite(pPage->pDbPage);
7565 if( rc!=SQLITE_OK ){
drhb53d8fa2022-11-21 15:55:57 +00007566 return rc;
danielk19776e465eb2007-08-21 13:11:00 +00007567 }
7568 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00007569 data = pPage->aData;
drh2c8fb922015-06-25 19:53:48 +00007570 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
drh0a45c272009-07-08 01:49:11 +00007571 rc = allocateSpace(pPage, sz, &idx);
drhb53d8fa2022-11-21 15:55:57 +00007572 if( rc ){ return rc; }
drhcd8fb7c2015-06-02 14:02:18 +00007573 /* The allocateSpace() routine guarantees the following properties
7574 ** if it returns successfully */
drh2c8fb922015-06-25 19:53:48 +00007575 assert( idx >= 0 );
7576 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
dan7b3d71e2015-08-19 20:27:05 +00007577 assert( idx+sz <= (int)pBt->usableSize );
drh0a45c272009-07-08 01:49:11 +00007578 pPage->nFree -= (u16)(2 + sz);
danielk19774dbaa892009-06-16 16:50:22 +00007579 if( iChild ){
drhd12db3d2019-01-14 05:48:10 +00007580 /* In a corrupt database where an entry in the cell index section of
7581 ** a btree page has a value of 3 or less, the pCell value might point
7582 ** as many as 4 bytes in front of the start of the aData buffer for
7583 ** the source page. Make sure this does not cause problems by not
7584 ** reading the first 4 bytes */
7585 memcpy(&data[idx+4], pCell+4, sz-4);
danielk19774dbaa892009-06-16 16:50:22 +00007586 put4byte(&data[idx], iChild);
drhd12db3d2019-01-14 05:48:10 +00007587 }else{
7588 memcpy(&data[idx], pCell, sz);
danielk19774dbaa892009-06-16 16:50:22 +00007589 }
drh2c8fb922015-06-25 19:53:48 +00007590 pIns = pPage->aCellIdx + i*2;
7591 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
7592 put2byte(pIns, idx);
7593 pPage->nCell++;
7594 /* increment the cell count */
7595 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
drh56785a02019-02-16 22:45:55 +00007596 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
dan7b3d71e2015-08-19 20:27:05 +00007597 if( REQUIRE_PTRMAP ){
drh5b046da2022-11-28 20:08:15 +00007598 int rc2 = SQLITE_OK;
danielk1977a19df672004-11-03 11:37:07 +00007599 /* The cell may contain a pointer to an overflow page. If so, write
7600 ** the entry for the overflow page into the pointer map.
7601 */
drh5b046da2022-11-28 20:08:15 +00007602 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc2);
drhd3fc2e62022-11-28 21:17:30 +00007603 if( rc2 ) return rc2;
danielk1977a19df672004-11-03 11:37:07 +00007604 }
drh14acc042001-06-10 19:56:58 +00007605 }
drhb53d8fa2022-11-21 15:55:57 +00007606 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00007607}
7608
7609/*
drhe3dadac2019-01-23 19:25:59 +00007610** The following parameters determine how many adjacent pages get involved
7611** in a balancing operation. NN is the number of neighbors on either side
7612** of the page that participate in the balancing operation. NB is the
7613** total number of pages that participate, including the target page and
7614** NN neighbors on either side.
7615**
7616** The minimum value of NN is 1 (of course). Increasing NN above 1
7617** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
7618** in exchange for a larger degradation in INSERT and UPDATE performance.
7619** The value of NN appears to give the best results overall.
7620**
7621** (Later:) The description above makes it seem as if these values are
7622** tunable - as if you could change them and recompile and it would all work.
7623** But that is unlikely. NB has been 3 since the inception of SQLite and
7624** we have never tested any other value.
7625*/
7626#define NN 1 /* Number of neighbors on either side of pPage */
7627#define NB 3 /* (NN*2+1): Total pages involved in the balance */
7628
7629/*
drh1ffd2472015-06-23 02:37:30 +00007630** A CellArray object contains a cache of pointers and sizes for a
drhc0d269e2016-08-03 14:51:16 +00007631** consecutive sequence of cells that might be held on multiple pages.
drhe3dadac2019-01-23 19:25:59 +00007632**
7633** The cells in this array are the divider cell or cells from the pParent
7634** page plus up to three child pages. There are a total of nCell cells.
7635**
7636** pRef is a pointer to one of the pages that contributes cells. This is
7637** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
7638** which should be common to all pages that contribute cells to this array.
7639**
7640** apCell[] and szCell[] hold, respectively, pointers to the start of each
7641** cell and the size of each cell. Some of the apCell[] pointers might refer
7642** to overflow cells. In other words, some apCel[] pointers might not point
7643** to content area of the pages.
7644**
7645** A szCell[] of zero means the size of that cell has not yet been computed.
7646**
7647** The cells come from as many as four different pages:
7648**
7649** -----------
7650** | Parent |
7651** -----------
7652** / | \
7653** / | \
7654** --------- --------- ---------
7655** |Child-1| |Child-2| |Child-3|
7656** --------- --------- ---------
7657**
drh26b7ec82019-02-01 14:50:43 +00007658** The order of cells is in the array is for an index btree is:
drhe3dadac2019-01-23 19:25:59 +00007659**
7660** 1. All cells from Child-1 in order
7661** 2. The first divider cell from Parent
7662** 3. All cells from Child-2 in order
7663** 4. The second divider cell from Parent
7664** 5. All cells from Child-3 in order
7665**
drh26b7ec82019-02-01 14:50:43 +00007666** For a table-btree (with rowids) the items 2 and 4 are empty because
7667** content exists only in leaves and there are no divider cells.
7668**
7669** For an index btree, the apEnd[] array holds pointer to the end of page
7670** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
7671** respectively. The ixNx[] array holds the number of cells contained in
7672** each of these 5 stages, and all stages to the left. Hence:
7673**
drhe3dadac2019-01-23 19:25:59 +00007674** ixNx[0] = Number of cells in Child-1.
7675** ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
7676** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
7677** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
7678** ixNx[4] = Total number of cells.
drh26b7ec82019-02-01 14:50:43 +00007679**
7680** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
7681** are used and they point to the leaf pages only, and the ixNx value are:
7682**
7683** ixNx[0] = Number of cells in Child-1.
drh9c7e44c2019-02-14 15:27:12 +00007684** ixNx[1] = Number of cells in Child-1 and Child-2.
7685** ixNx[2] = Total number of cells.
7686**
7687** Sometimes when deleting, a child page can have zero cells. In those
7688** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]
7689** entries, shift down. The end result is that each ixNx[] entry should
7690** be larger than the previous
drh1ffd2472015-06-23 02:37:30 +00007691*/
7692typedef struct CellArray CellArray;
7693struct CellArray {
7694 int nCell; /* Number of cells in apCell[] */
7695 MemPage *pRef; /* Reference page */
7696 u8 **apCell; /* All cells begin balanced */
7697 u16 *szCell; /* Local size of all cells in apCell[] */
drhe3dadac2019-01-23 19:25:59 +00007698 u8 *apEnd[NB*2]; /* MemPage.aDataEnd values */
7699 int ixNx[NB*2]; /* Index of at which we move to the next apEnd[] */
drh1ffd2472015-06-23 02:37:30 +00007700};
7701
7702/*
7703** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
7704** computed.
7705*/
7706static void populateCellCache(CellArray *p, int idx, int N){
drh47de1f92022-11-19 18:17:40 +00007707 MemPage *pRef = p->pRef;
7708 u16 *szCell = p->szCell;
drh1ffd2472015-06-23 02:37:30 +00007709 assert( idx>=0 && idx+N<=p->nCell );
7710 while( N>0 ){
7711 assert( p->apCell[idx]!=0 );
drh47de1f92022-11-19 18:17:40 +00007712 if( szCell[idx]==0 ){
7713 szCell[idx] = pRef->xCellSize(pRef, p->apCell[idx]);
drh1ffd2472015-06-23 02:37:30 +00007714 }else{
7715 assert( CORRUPT_DB ||
drh47de1f92022-11-19 18:17:40 +00007716 szCell[idx]==pRef->xCellSize(pRef, p->apCell[idx]) );
drh1ffd2472015-06-23 02:37:30 +00007717 }
7718 idx++;
7719 N--;
7720 }
7721}
7722
7723/*
7724** Return the size of the Nth element of the cell array
7725*/
7726static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
7727 assert( N>=0 && N<p->nCell );
7728 assert( p->szCell[N]==0 );
7729 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
7730 return p->szCell[N];
7731}
7732static u16 cachedCellSize(CellArray *p, int N){
7733 assert( N>=0 && N<p->nCell );
7734 if( p->szCell[N] ) return p->szCell[N];
7735 return computeCellSize(p, N);
7736}
7737
7738/*
dan8e9ba0c2014-10-14 17:27:04 +00007739** Array apCell[] contains pointers to nCell b-tree page cells. The
7740** szCell[] array contains the size in bytes of each cell. This function
7741** replaces the current contents of page pPg with the contents of the cell
7742** array.
7743**
7744** Some of the cells in apCell[] may currently be stored in pPg. This
7745** function works around problems caused by this by making a copy of any
7746** such cells before overwriting the page data.
7747**
7748** The MemPage.nFree field is invalidated by this function. It is the
7749** responsibility of the caller to set it correctly.
drhfa1a98a2004-05-14 19:08:17 +00007750*/
drh658873b2015-06-22 20:02:04 +00007751static int rebuildPage(
drhe3dadac2019-01-23 19:25:59 +00007752 CellArray *pCArray, /* Content to be added to page pPg */
7753 int iFirst, /* First cell in pCArray to use */
dan33ea4862014-10-09 19:35:37 +00007754 int nCell, /* Final number of cells on page */
drhe3dadac2019-01-23 19:25:59 +00007755 MemPage *pPg /* The page to be reconstructed */
dan33ea4862014-10-09 19:35:37 +00007756){
7757 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
7758 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
7759 const int usableSize = pPg->pBt->usableSize;
7760 u8 * const pEnd = &aData[usableSize];
drhe3dadac2019-01-23 19:25:59 +00007761 int i = iFirst; /* Which cell to copy from pCArray*/
drha0466432019-01-29 16:41:13 +00007762 u32 j; /* Start of cell content area */
drhe3dadac2019-01-23 19:25:59 +00007763 int iEnd = i+nCell; /* Loop terminator */
dan33ea4862014-10-09 19:35:37 +00007764 u8 *pCellptr = pPg->aCellIdx;
7765 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7766 u8 *pData;
drhe3dadac2019-01-23 19:25:59 +00007767 int k; /* Current slot in pCArray->apEnd[] */
7768 u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */
dan33ea4862014-10-09 19:35:37 +00007769
drhe3dadac2019-01-23 19:25:59 +00007770 assert( i<iEnd );
7771 j = get2byte(&aData[hdr+5]);
drh10f73652022-01-05 21:01:26 +00007772 if( j>(u32)usableSize ){ j = 0; }
drhe3dadac2019-01-23 19:25:59 +00007773 memcpy(&pTmp[j], &aData[j], usableSize - j);
7774
7775 for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
7776 pSrcEnd = pCArray->apEnd[k];
dan33ea4862014-10-09 19:35:37 +00007777
dan8e9ba0c2014-10-14 17:27:04 +00007778 pData = pEnd;
drhe3dadac2019-01-23 19:25:59 +00007779 while( 1/*exit by break*/ ){
7780 u8 *pCell = pCArray->apCell[i];
7781 u16 sz = pCArray->szCell[i];
7782 assert( sz>0 );
drh8cae5a42021-04-20 20:48:15 +00007783 if( SQLITE_WITHIN(pCell,aData+j,pEnd) ){
drhe3dadac2019-01-23 19:25:59 +00007784 if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
dan33ea4862014-10-09 19:35:37 +00007785 pCell = &pTmp[pCell - aData];
drhe3dadac2019-01-23 19:25:59 +00007786 }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
7787 && (uptr)(pCell)<(uptr)pSrcEnd
7788 ){
7789 return SQLITE_CORRUPT_BKPT;
dan33ea4862014-10-09 19:35:37 +00007790 }
drhe3dadac2019-01-23 19:25:59 +00007791
7792 pData -= sz;
dan33ea4862014-10-09 19:35:37 +00007793 put2byte(pCellptr, (pData - aData));
7794 pCellptr += 2;
drh658873b2015-06-22 20:02:04 +00007795 if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
drheca3c672021-04-22 20:01:02 +00007796 memmove(pData, pCell, sz);
drhe3dadac2019-01-23 19:25:59 +00007797 assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
drhe3dadac2019-01-23 19:25:59 +00007798 i++;
7799 if( i>=iEnd ) break;
7800 if( pCArray->ixNx[k]<=i ){
7801 k++;
7802 pSrcEnd = pCArray->apEnd[k];
7803 }
dan33ea4862014-10-09 19:35:37 +00007804 }
7805
dand7b545b2014-10-13 18:03:27 +00007806 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
dan33ea4862014-10-09 19:35:37 +00007807 pPg->nCell = nCell;
7808 pPg->nOverflow = 0;
7809
7810 put2byte(&aData[hdr+1], 0);
7811 put2byte(&aData[hdr+3], pPg->nCell);
7812 put2byte(&aData[hdr+5], pData - aData);
7813 aData[hdr+7] = 0x00;
drh658873b2015-06-22 20:02:04 +00007814 return SQLITE_OK;
dan33ea4862014-10-09 19:35:37 +00007815}
7816
dan8e9ba0c2014-10-14 17:27:04 +00007817/*
drhe3dadac2019-01-23 19:25:59 +00007818** The pCArray objects contains pointers to b-tree cells and the cell sizes.
7819** This function attempts to add the cells stored in the array to page pPg.
7820** If it cannot (because the page needs to be defragmented before the cells
7821** will fit), non-zero is returned. Otherwise, if the cells are added
7822** successfully, zero is returned.
dan8e9ba0c2014-10-14 17:27:04 +00007823**
7824** Argument pCellptr points to the first entry in the cell-pointer array
7825** (part of page pPg) to populate. After cell apCell[0] is written to the
7826** page body, a 16-bit offset is written to pCellptr. And so on, for each
7827** cell in the array. It is the responsibility of the caller to ensure
7828** that it is safe to overwrite this part of the cell-pointer array.
7829**
7830** When this function is called, *ppData points to the start of the
7831** content area on page pPg. If the size of the content area is extended,
7832** *ppData is updated to point to the new start of the content area
7833** before returning.
7834**
7835** Finally, argument pBegin points to the byte immediately following the
7836** end of the space required by this page for the cell-pointer area (for
7837** all cells - not just those inserted by the current call). If the content
7838** area must be extended to before this point in order to accomodate all
7839** cells in apCell[], then the cells do not fit and non-zero is returned.
7840*/
dand7b545b2014-10-13 18:03:27 +00007841static int pageInsertArray(
dan8e9ba0c2014-10-14 17:27:04 +00007842 MemPage *pPg, /* Page to add cells to */
7843 u8 *pBegin, /* End of cell-pointer array */
drhe3dadac2019-01-23 19:25:59 +00007844 u8 **ppData, /* IN/OUT: Page content-area pointer */
dan8e9ba0c2014-10-14 17:27:04 +00007845 u8 *pCellptr, /* Pointer to cell-pointer area */
drhf7838932015-06-23 15:36:34 +00007846 int iFirst, /* Index of first cell to add */
dan8e9ba0c2014-10-14 17:27:04 +00007847 int nCell, /* Number of cells to add to pPg */
drhf7838932015-06-23 15:36:34 +00007848 CellArray *pCArray /* Array of cells */
dand7b545b2014-10-13 18:03:27 +00007849){
drhe3dadac2019-01-23 19:25:59 +00007850 int i = iFirst; /* Loop counter - cell index to insert */
7851 u8 *aData = pPg->aData; /* Complete page */
7852 u8 *pData = *ppData; /* Content area. A subset of aData[] */
7853 int iEnd = iFirst + nCell; /* End of loop. One past last cell to ins */
7854 int k; /* Current slot in pCArray->apEnd[] */
7855 u8 *pEnd; /* Maximum extent of cell data */
dan23eba452014-10-24 18:43:57 +00007856 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
drhe3dadac2019-01-23 19:25:59 +00007857 if( iEnd<=iFirst ) return 0;
7858 for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
7859 pEnd = pCArray->apEnd[k];
7860 while( 1 /*Exit by break*/ ){
drhf7838932015-06-23 15:36:34 +00007861 int sz, rc;
dand7b545b2014-10-13 18:03:27 +00007862 u8 *pSlot;
dan666a42f2019-08-24 21:02:47 +00007863 assert( pCArray->szCell[i]!=0 );
7864 sz = pCArray->szCell[i];
drhb7580e82015-06-25 18:36:13 +00007865 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
drhcca66982016-04-05 13:19:19 +00007866 if( (pData - pBegin)<sz ) return 1;
dand7b545b2014-10-13 18:03:27 +00007867 pData -= sz;
dand7b545b2014-10-13 18:03:27 +00007868 pSlot = pData;
7869 }
drh48310f82015-10-10 16:41:28 +00007870 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
7871 ** database. But they might for a corrupt database. Hence use memmove()
7872 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
7873 assert( (pSlot+sz)<=pCArray->apCell[i]
7874 || pSlot>=(pCArray->apCell[i]+sz)
7875 || CORRUPT_DB );
drhe3dadac2019-01-23 19:25:59 +00007876 if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
7877 && (uptr)(pCArray->apCell[i])<(uptr)pEnd
7878 ){
7879 assert( CORRUPT_DB );
7880 (void)SQLITE_CORRUPT_BKPT;
7881 return 1;
7882 }
drh48310f82015-10-10 16:41:28 +00007883 memmove(pSlot, pCArray->apCell[i], sz);
dand7b545b2014-10-13 18:03:27 +00007884 put2byte(pCellptr, (pSlot - aData));
7885 pCellptr += 2;
drhe3dadac2019-01-23 19:25:59 +00007886 i++;
7887 if( i>=iEnd ) break;
7888 if( pCArray->ixNx[k]<=i ){
7889 k++;
7890 pEnd = pCArray->apEnd[k];
7891 }
dand7b545b2014-10-13 18:03:27 +00007892 }
7893 *ppData = pData;
7894 return 0;
7895}
7896
dan8e9ba0c2014-10-14 17:27:04 +00007897/*
drhe3dadac2019-01-23 19:25:59 +00007898** The pCArray object contains pointers to b-tree cells and their sizes.
7899**
7900** This function adds the space associated with each cell in the array
7901** that is currently stored within the body of pPg to the pPg free-list.
7902** The cell-pointers and other fields of the page are not updated.
dan8e9ba0c2014-10-14 17:27:04 +00007903**
7904** This function returns the total number of cells added to the free-list.
7905*/
dand7b545b2014-10-13 18:03:27 +00007906static int pageFreeArray(
7907 MemPage *pPg, /* Page to edit */
drhf7838932015-06-23 15:36:34 +00007908 int iFirst, /* First cell to delete */
dand7b545b2014-10-13 18:03:27 +00007909 int nCell, /* Cells to delete */
drhf7838932015-06-23 15:36:34 +00007910 CellArray *pCArray /* Array of cells */
dand7b545b2014-10-13 18:03:27 +00007911){
7912 u8 * const aData = pPg->aData;
7913 u8 * const pEnd = &aData[pPg->pBt->usableSize];
dan89ca0b32014-10-25 20:36:28 +00007914 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
dand7b545b2014-10-13 18:03:27 +00007915 int nRet = 0;
7916 int i;
drhf7838932015-06-23 15:36:34 +00007917 int iEnd = iFirst + nCell;
drh1e620572022-11-19 14:18:48 +00007918 u8 *pFree = 0; /* \__ Parameters for pending call to */
7919 int szFree = 0; /* / freeSpace() */
dand7b545b2014-10-13 18:03:27 +00007920
drhf7838932015-06-23 15:36:34 +00007921 for(i=iFirst; i<iEnd; i++){
7922 u8 *pCell = pCArray->apCell[i];
drh8b0ba7b2015-12-16 13:07:35 +00007923 if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
drhf7838932015-06-23 15:36:34 +00007924 int sz;
7925 /* No need to use cachedCellSize() here. The sizes of all cells that
7926 ** are to be freed have already been computing while deciding which
7927 ** cells need freeing */
7928 sz = pCArray->szCell[i]; assert( sz>0 );
dand7b545b2014-10-13 18:03:27 +00007929 if( pFree!=(pCell + sz) ){
drhfefa0942014-11-05 21:21:08 +00007930 if( pFree ){
7931 assert( pFree>aData && (pFree - aData)<65536 );
7932 freeSpace(pPg, (u16)(pFree - aData), szFree);
7933 }
dand7b545b2014-10-13 18:03:27 +00007934 pFree = pCell;
7935 szFree = sz;
drhccb897c2021-05-11 10:47:41 +00007936 if( pFree+sz>pEnd ){
7937 return 0;
drhc3c23f32021-05-06 11:02:55 +00007938 }
dand7b545b2014-10-13 18:03:27 +00007939 }else{
drh1e620572022-11-19 14:18:48 +00007940 /* The current cell is adjacent to and before the pFree cell.
7941 ** Combine the two regions into one to reduce the number of calls
7942 ** to freeSpace(). */
dand7b545b2014-10-13 18:03:27 +00007943 pFree = pCell;
7944 szFree += sz;
7945 }
7946 nRet++;
7947 }
7948 }
drhfefa0942014-11-05 21:21:08 +00007949 if( pFree ){
7950 assert( pFree>aData && (pFree - aData)<65536 );
7951 freeSpace(pPg, (u16)(pFree - aData), szFree);
7952 }
dand7b545b2014-10-13 18:03:27 +00007953 return nRet;
7954}
7955
dand7b545b2014-10-13 18:03:27 +00007956/*
drha0466432019-01-29 16:41:13 +00007957** pCArray contains pointers to and sizes of all cells in the page being
drhe3dadac2019-01-23 19:25:59 +00007958** balanced. The current page, pPg, has pPg->nCell cells starting with
7959** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells
drh5ab63772014-11-27 03:46:04 +00007960** starting at apCell[iNew].
7961**
7962** This routine makes the necessary adjustments to pPg so that it contains
7963** the correct cells after being balanced.
7964**
dand7b545b2014-10-13 18:03:27 +00007965** The pPg->nFree field is invalid when this function returns. It is the
7966** responsibility of the caller to set it correctly.
7967*/
drh658873b2015-06-22 20:02:04 +00007968static int editPage(
dan09c68402014-10-11 20:00:24 +00007969 MemPage *pPg, /* Edit this page */
7970 int iOld, /* Index of first cell currently on page */
7971 int iNew, /* Index of new first cell on page */
7972 int nNew, /* Final number of cells on page */
drh1ffd2472015-06-23 02:37:30 +00007973 CellArray *pCArray /* Array of cells and sizes */
dan09c68402014-10-11 20:00:24 +00007974){
dand7b545b2014-10-13 18:03:27 +00007975 u8 * const aData = pPg->aData;
7976 const int hdr = pPg->hdrOffset;
7977 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
7978 int nCell = pPg->nCell; /* Cells stored on pPg */
7979 u8 *pData;
7980 u8 *pCellptr;
7981 int i;
7982 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
7983 int iNewEnd = iNew + nNew;
dan09c68402014-10-11 20:00:24 +00007984
7985#ifdef SQLITE_DEBUG
dand7b545b2014-10-13 18:03:27 +00007986 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7987 memcpy(pTmp, aData, pPg->pBt->usableSize);
dan09c68402014-10-11 20:00:24 +00007988#endif
7989
dand7b545b2014-10-13 18:03:27 +00007990 /* Remove cells from the start and end of the page */
drha0466432019-01-29 16:41:13 +00007991 assert( nCell>=0 );
dand7b545b2014-10-13 18:03:27 +00007992 if( iOld<iNew ){
drhf7838932015-06-23 15:36:34 +00007993 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
drhfde25922020-05-05 19:54:02 +00007994 if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT;
dand7b545b2014-10-13 18:03:27 +00007995 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
7996 nCell -= nShift;
7997 }
7998 if( iNewEnd < iOldEnd ){
drha0466432019-01-29 16:41:13 +00007999 int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
8000 assert( nCell>=nTail );
8001 nCell -= nTail;
dand7b545b2014-10-13 18:03:27 +00008002 }
dan09c68402014-10-11 20:00:24 +00008003
drh5ab63772014-11-27 03:46:04 +00008004 pData = &aData[get2byteNotZero(&aData[hdr+5])];
dand7b545b2014-10-13 18:03:27 +00008005 if( pData<pBegin ) goto editpage_fail;
drh10f73652022-01-05 21:01:26 +00008006 if( pData>pPg->aDataEnd ) goto editpage_fail;
dand7b545b2014-10-13 18:03:27 +00008007
8008 /* Add cells to the start of the page */
8009 if( iNew<iOld ){
drh5ab63772014-11-27 03:46:04 +00008010 int nAdd = MIN(nNew,iOld-iNew);
8011 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
drha0466432019-01-29 16:41:13 +00008012 assert( nAdd>=0 );
dand7b545b2014-10-13 18:03:27 +00008013 pCellptr = pPg->aCellIdx;
8014 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
8015 if( pageInsertArray(
8016 pPg, pBegin, &pData, pCellptr,
drhf7838932015-06-23 15:36:34 +00008017 iNew, nAdd, pCArray
dand7b545b2014-10-13 18:03:27 +00008018 ) ) goto editpage_fail;
8019 nCell += nAdd;
8020 }
8021
8022 /* Add any overflow cells */
8023 for(i=0; i<pPg->nOverflow; i++){
8024 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
8025 if( iCell>=0 && iCell<nNew ){
drhfefa0942014-11-05 21:21:08 +00008026 pCellptr = &pPg->aCellIdx[iCell * 2];
drh4b986b22019-03-08 14:02:11 +00008027 if( nCell>iCell ){
8028 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
8029 }
dand7b545b2014-10-13 18:03:27 +00008030 nCell++;
dan666a42f2019-08-24 21:02:47 +00008031 cachedCellSize(pCArray, iCell+iNew);
dand7b545b2014-10-13 18:03:27 +00008032 if( pageInsertArray(
8033 pPg, pBegin, &pData, pCellptr,
drhf7838932015-06-23 15:36:34 +00008034 iCell+iNew, 1, pCArray
dand7b545b2014-10-13 18:03:27 +00008035 ) ) goto editpage_fail;
dan09c68402014-10-11 20:00:24 +00008036 }
dand7b545b2014-10-13 18:03:27 +00008037 }
dan09c68402014-10-11 20:00:24 +00008038
dand7b545b2014-10-13 18:03:27 +00008039 /* Append cells to the end of the page */
drha0466432019-01-29 16:41:13 +00008040 assert( nCell>=0 );
dand7b545b2014-10-13 18:03:27 +00008041 pCellptr = &pPg->aCellIdx[nCell*2];
8042 if( pageInsertArray(
8043 pPg, pBegin, &pData, pCellptr,
drhf7838932015-06-23 15:36:34 +00008044 iNew+nCell, nNew-nCell, pCArray
dand7b545b2014-10-13 18:03:27 +00008045 ) ) goto editpage_fail;
dan09c68402014-10-11 20:00:24 +00008046
dand7b545b2014-10-13 18:03:27 +00008047 pPg->nCell = nNew;
8048 pPg->nOverflow = 0;
dan09c68402014-10-11 20:00:24 +00008049
dand7b545b2014-10-13 18:03:27 +00008050 put2byte(&aData[hdr+3], pPg->nCell);
8051 put2byte(&aData[hdr+5], pData - aData);
dan09c68402014-10-11 20:00:24 +00008052
8053#ifdef SQLITE_DEBUG
dan23eba452014-10-24 18:43:57 +00008054 for(i=0; i<nNew && !CORRUPT_DB; i++){
drh1ffd2472015-06-23 02:37:30 +00008055 u8 *pCell = pCArray->apCell[i+iNew];
drh329428e2015-06-30 13:28:18 +00008056 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
drh1c715f62016-04-05 13:35:43 +00008057 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
dand7b545b2014-10-13 18:03:27 +00008058 pCell = &pTmp[pCell - aData];
dan09c68402014-10-11 20:00:24 +00008059 }
drh1ffd2472015-06-23 02:37:30 +00008060 assert( 0==memcmp(pCell, &aData[iOff],
8061 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
dand7b545b2014-10-13 18:03:27 +00008062 }
dan09c68402014-10-11 20:00:24 +00008063#endif
8064
drh658873b2015-06-22 20:02:04 +00008065 return SQLITE_OK;
dan09c68402014-10-11 20:00:24 +00008066 editpage_fail:
dan09c68402014-10-11 20:00:24 +00008067 /* Unable to edit this page. Rebuild it from scratch instead. */
drh1ffd2472015-06-23 02:37:30 +00008068 populateCellCache(pCArray, iNew, nNew);
drhe3dadac2019-01-23 19:25:59 +00008069 return rebuildPage(pCArray, iNew, nNew, pPg);
dan09c68402014-10-11 20:00:24 +00008070}
8071
danielk1977ac245ec2005-01-14 13:50:11 +00008072
drh615ae552005-01-16 23:21:00 +00008073#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00008074/*
8075** This version of balance() handles the common special case where
8076** a new entry is being inserted on the extreme right-end of the
8077** tree, in other words, when the new entry will become the largest
8078** entry in the tree.
8079**
drhc314dc72009-07-21 11:52:34 +00008080** Instead of trying to balance the 3 right-most leaf pages, just add
drhf222e712005-01-14 22:55:49 +00008081** a new page to the right-hand side and put the one new entry in
8082** that page. This leaves the right side of the tree somewhat
8083** unbalanced. But odds are that we will be inserting new entries
8084** at the end soon afterwards so the nearly empty page will quickly
8085** fill up. On average.
8086**
8087** pPage is the leaf page which is the right-most page in the tree.
8088** pParent is its parent. pPage must have a single overflow entry
8089** which is also the right-most entry on the page.
danielk1977a50d9aa2009-06-08 14:49:45 +00008090**
8091** The pSpace buffer is used to store a temporary copy of the divider
8092** cell that will be inserted into pParent. Such a cell consists of a 4
8093** byte page number followed by a variable length integer. In other
8094** words, at most 13 bytes. Hence the pSpace buffer must be at
8095** least 13 bytes in size.
drhf222e712005-01-14 22:55:49 +00008096*/
danielk1977a50d9aa2009-06-08 14:49:45 +00008097static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
8098 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
danielk19774dbaa892009-06-16 16:50:22 +00008099 MemPage *pNew; /* Newly allocated page */
danielk19776f235cc2009-06-04 14:46:08 +00008100 int rc; /* Return Code */
8101 Pgno pgnoNew; /* Page number of pNew */
danielk1977ac245ec2005-01-14 13:50:11 +00008102
drh1fee73e2007-08-29 04:00:57 +00008103 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk1977a50d9aa2009-06-08 14:49:45 +00008104 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00008105 assert( pPage->nOverflow==1 );
drhb0ea9432019-02-09 21:06:40 +00008106
drh6301c432018-12-13 21:52:18 +00008107 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; /* dbfuzz001.test */
drh68133502019-02-11 17:22:30 +00008108 assert( pPage->nFree>=0 );
8109 assert( pParent->nFree>=0 );
drhd677b3d2007-08-20 22:48:41 +00008110
danielk1977a50d9aa2009-06-08 14:49:45 +00008111 /* Allocate a new page. This page will become the right-sibling of
8112 ** pPage. Make the parent page writable, so that the new divider cell
8113 ** may be inserted. If both these operations are successful, proceed.
8114 */
drh4f0c5872007-03-26 22:05:01 +00008115 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk19774dbaa892009-06-16 16:50:22 +00008116
danielk1977eaa06f62008-09-18 17:34:44 +00008117 if( rc==SQLITE_OK ){
danielk1977a50d9aa2009-06-08 14:49:45 +00008118
8119 u8 *pOut = &pSpace[4];
drh2cbd78b2012-02-02 19:37:18 +00008120 u8 *pCell = pPage->apOvfl[0];
drh25ada072015-06-19 15:07:14 +00008121 u16 szCell = pPage->xCellSize(pPage, pCell);
danielk19776f235cc2009-06-04 14:46:08 +00008122 u8 *pStop;
drhe3dadac2019-01-23 19:25:59 +00008123 CellArray b;
danielk19776f235cc2009-06-04 14:46:08 +00008124
drhc5053fb2008-11-27 02:22:10 +00008125 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
danba14c692019-01-25 13:42:12 +00008126 assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
danielk1977e56b60e2009-06-10 09:11:06 +00008127 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
drhe3dadac2019-01-23 19:25:59 +00008128 b.nCell = 1;
8129 b.pRef = pPage;
8130 b.apCell = &pCell;
8131 b.szCell = &szCell;
8132 b.apEnd[0] = pPage->aDataEnd;
8133 b.ixNx[0] = 2;
8134 rc = rebuildPage(&b, 0, 1, pNew);
8135 if( NEVER(rc) ){
8136 releasePage(pNew);
8137 return rc;
8138 }
dan8e9ba0c2014-10-14 17:27:04 +00008139 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
danielk19774dbaa892009-06-16 16:50:22 +00008140
8141 /* If this is an auto-vacuum database, update the pointer map
8142 ** with entries for the new page, and any pointer from the
8143 ** cell on the page to an overflow page. If either of these
8144 ** operations fails, the return code is set, but the contents
8145 ** of the parent page are still manipulated by thh code below.
8146 ** That is Ok, at this point the parent page is guaranteed to
8147 ** be marked as dirty. Returning an error code will cause a
8148 ** rollback, undoing any changes made to the parent page.
8149 */
dan7b3d71e2015-08-19 20:27:05 +00008150 if( REQUIRE_PTRMAP ){
drh98add2e2009-07-20 17:11:49 +00008151 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
8152 if( szCell>pNew->minLocal ){
drh0f1bf4c2019-01-13 20:17:21 +00008153 ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00008154 }
8155 }
danielk1977eaa06f62008-09-18 17:34:44 +00008156
danielk19776f235cc2009-06-04 14:46:08 +00008157 /* Create a divider cell to insert into pParent. The divider cell
8158 ** consists of a 4-byte page number (the page number of pPage) and
8159 ** a variable length key value (which must be the same value as the
8160 ** largest key on pPage).
danielk1977eaa06f62008-09-18 17:34:44 +00008161 **
danielk19776f235cc2009-06-04 14:46:08 +00008162 ** To find the largest key value on pPage, first find the right-most
8163 ** cell on pPage. The first two fields of this cell are the
8164 ** record-length (a variable length integer at most 32-bits in size)
8165 ** and the key value (a variable length integer, may have any value).
8166 ** The first of the while(...) loops below skips over the record-length
8167 ** field. The second while(...) loop copies the key value from the
danielk1977a50d9aa2009-06-08 14:49:45 +00008168 ** cell on pPage into the pSpace buffer.
danielk1977eaa06f62008-09-18 17:34:44 +00008169 */
danielk1977eaa06f62008-09-18 17:34:44 +00008170 pCell = findCell(pPage, pPage->nCell-1);
danielk19776f235cc2009-06-04 14:46:08 +00008171 pStop = &pCell[9];
8172 while( (*(pCell++)&0x80) && pCell<pStop );
8173 pStop = &pCell[9];
8174 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
8175
danielk19774dbaa892009-06-16 16:50:22 +00008176 /* Insert the new divider cell into pParent. */
drhcb89f4a2016-05-21 11:23:26 +00008177 if( rc==SQLITE_OK ){
drhb53d8fa2022-11-21 15:55:57 +00008178 rc = insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
8179 0, pPage->pgno);
drhcb89f4a2016-05-21 11:23:26 +00008180 }
danielk19776f235cc2009-06-04 14:46:08 +00008181
8182 /* Set the right-child pointer of pParent to point to the new page. */
danielk1977eaa06f62008-09-18 17:34:44 +00008183 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
8184
danielk1977e08a3c42008-09-18 18:17:03 +00008185 /* Release the reference to the new page. */
8186 releasePage(pNew);
danielk1977ac11ee62005-01-15 12:45:51 +00008187 }
8188
danielk1977eaa06f62008-09-18 17:34:44 +00008189 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00008190}
drh615ae552005-01-16 23:21:00 +00008191#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00008192
dane6593d82014-10-24 16:40:49 +00008193#if 0
drhc3b70572003-01-04 19:44:07 +00008194/*
danielk19774dbaa892009-06-16 16:50:22 +00008195** This function does not contribute anything to the operation of SQLite.
8196** it is sometimes activated temporarily while debugging code responsible
8197** for setting pointer-map entries.
8198*/
8199static int ptrmapCheckPages(MemPage **apPage, int nPage){
8200 int i, j;
8201 for(i=0; i<nPage; i++){
8202 Pgno n;
8203 u8 e;
8204 MemPage *pPage = apPage[i];
8205 BtShared *pBt = pPage->pBt;
8206 assert( pPage->isInit );
8207
8208 for(j=0; j<pPage->nCell; j++){
8209 CellInfo info;
8210 u8 *z;
8211
8212 z = findCell(pPage, j);
drh5fa60512015-06-19 17:19:34 +00008213 pPage->xParseCell(pPage, z, &info);
drh45ac1c72015-12-18 03:59:16 +00008214 if( info.nLocal<info.nPayload ){
8215 Pgno ovfl = get4byte(&z[info.nSize-4]);
danielk19774dbaa892009-06-16 16:50:22 +00008216 ptrmapGet(pBt, ovfl, &e, &n);
8217 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
8218 }
8219 if( !pPage->leaf ){
8220 Pgno child = get4byte(z);
8221 ptrmapGet(pBt, child, &e, &n);
8222 assert( n==pPage->pgno && e==PTRMAP_BTREE );
8223 }
8224 }
8225 if( !pPage->leaf ){
8226 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
8227 ptrmapGet(pBt, child, &e, &n);
8228 assert( n==pPage->pgno && e==PTRMAP_BTREE );
8229 }
8230 }
8231 return 1;
8232}
8233#endif
8234
danielk1977cd581a72009-06-23 15:43:39 +00008235/*
8236** This function is used to copy the contents of the b-tree node stored
8237** on page pFrom to page pTo. If page pFrom was not a leaf page, then
8238** the pointer-map entries for each child page are updated so that the
8239** parent page stored in the pointer map is page pTo. If pFrom contained
8240** any cells with overflow page pointers, then the corresponding pointer
8241** map entries are also updated so that the parent page is page pTo.
8242**
8243** If pFrom is currently carrying any overflow cells (entries in the
drh2cbd78b2012-02-02 19:37:18 +00008244** MemPage.apOvfl[] array), they are not copied to pTo.
danielk1977cd581a72009-06-23 15:43:39 +00008245**
danielk197730548662009-07-09 05:07:37 +00008246** Before returning, page pTo is reinitialized using btreeInitPage().
danielk1977cd581a72009-06-23 15:43:39 +00008247**
8248** The performance of this function is not critical. It is only used by
8249** the balance_shallower() and balance_deeper() procedures, neither of
8250** which are called often under normal circumstances.
8251*/
drhc314dc72009-07-21 11:52:34 +00008252static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
8253 if( (*pRC)==SQLITE_OK ){
8254 BtShared * const pBt = pFrom->pBt;
8255 u8 * const aFrom = pFrom->aData;
8256 u8 * const aTo = pTo->aData;
8257 int const iFromHdr = pFrom->hdrOffset;
8258 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
drhdc9b5f82009-12-05 18:34:08 +00008259 int rc;
drhc314dc72009-07-21 11:52:34 +00008260 int iData;
8261
8262
8263 assert( pFrom->isInit );
8264 assert( pFrom->nFree>=iToHdr );
drhfcd71b62011-04-05 22:08:24 +00008265 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
drhc314dc72009-07-21 11:52:34 +00008266
8267 /* Copy the b-tree node content from page pFrom to page pTo. */
8268 iData = get2byte(&aFrom[iFromHdr+5]);
8269 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
8270 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
8271
8272 /* Reinitialize page pTo so that the contents of the MemPage structure
dan89e060e2009-12-05 18:03:50 +00008273 ** match the new data. The initialization of pTo can actually fail under
8274 ** fairly obscure circumstances, even though it is a copy of initialized
8275 ** page pFrom.
8276 */
drhc314dc72009-07-21 11:52:34 +00008277 pTo->isInit = 0;
dan89e060e2009-12-05 18:03:50 +00008278 rc = btreeInitPage(pTo);
drh8357c662019-02-11 22:50:01 +00008279 if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);
dan89e060e2009-12-05 18:03:50 +00008280 if( rc!=SQLITE_OK ){
8281 *pRC = rc;
8282 return;
8283 }
drhc314dc72009-07-21 11:52:34 +00008284
8285 /* If this is an auto-vacuum database, update the pointer-map entries
8286 ** for any b-tree or overflow pages that pTo now contains the pointers to.
8287 */
dan7b3d71e2015-08-19 20:27:05 +00008288 if( REQUIRE_PTRMAP ){
drhc314dc72009-07-21 11:52:34 +00008289 *pRC = setChildPtrmaps(pTo);
8290 }
danielk1977cd581a72009-06-23 15:43:39 +00008291 }
danielk1977cd581a72009-06-23 15:43:39 +00008292}
8293
8294/*
danielk19774dbaa892009-06-16 16:50:22 +00008295** This routine redistributes cells on the iParentIdx'th child of pParent
8296** (hereafter "the page") and up to 2 siblings so that all pages have about the
8297** same amount of free space. Usually a single sibling on either side of the
8298** page are used in the balancing, though both siblings might come from one
8299** side if the page is the first or last child of its parent. If the page
8300** has fewer than 2 siblings (something which can only happen if the page
8301** is a root page or a child of a root page) then all available siblings
8302** participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00008303**
danielk19774dbaa892009-06-16 16:50:22 +00008304** The number of siblings of the page might be increased or decreased by
8305** one or two in an effort to keep pages nearly full but not over full.
drh14acc042001-06-10 19:56:58 +00008306**
danielk19774dbaa892009-06-16 16:50:22 +00008307** Note that when this routine is called, some of the cells on the page
8308** might not actually be stored in MemPage.aData[]. This can happen
8309** if the page is overfull. This routine ensures that all cells allocated
8310** to the page and its siblings fit into MemPage.aData[] before returning.
drh14acc042001-06-10 19:56:58 +00008311**
danielk19774dbaa892009-06-16 16:50:22 +00008312** In the course of balancing the page and its siblings, cells may be
8313** inserted into or removed from the parent page (pParent). Doing so
8314** may cause the parent page to become overfull or underfull. If this
8315** happens, it is the responsibility of the caller to invoke the correct
8316** balancing routine to fix this problem (see the balance() routine).
drh8c42ca92001-06-22 19:15:00 +00008317**
drh5e00f6c2001-09-13 13:46:56 +00008318** If this routine fails for any reason, it might leave the database
danielk19776067a9b2009-06-09 09:41:00 +00008319** in a corrupted state. So if this routine fails, the database should
drh5e00f6c2001-09-13 13:46:56 +00008320** be rolled back.
danielk19774dbaa892009-06-16 16:50:22 +00008321**
8322** The third argument to this function, aOvflSpace, is a pointer to a
drhcd09c532009-07-20 19:30:00 +00008323** buffer big enough to hold one page. If while inserting cells into the parent
8324** page (pParent) the parent page becomes overfull, this buffer is
8325** used to store the parent's overflow cells. Because this function inserts
danielk19774dbaa892009-06-16 16:50:22 +00008326** a maximum of four divider cells into the parent page, and the maximum
8327** size of a cell stored within an internal node is always less than 1/4
8328** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
8329** enough for all overflow cells.
8330**
8331** If aOvflSpace is set to a null pointer, this function returns
8332** SQLITE_NOMEM.
drh8b2f49b2001-06-08 00:21:52 +00008333*/
danielk19774dbaa892009-06-16 16:50:22 +00008334static int balance_nonroot(
8335 MemPage *pParent, /* Parent page of siblings being balanced */
8336 int iParentIdx, /* Index of "the page" in pParent */
danielk1977cd581a72009-06-23 15:43:39 +00008337 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
dan428c2182012-08-06 18:50:11 +00008338 int isRoot, /* True if pParent is a root-page */
dan7fff2e12017-05-29 14:27:37 +00008339 int bBulk, /* True if this call is part of a bulk load */
8340 Pgno pgnoRoot /* Root page of b-tree being balanced */
danielk19774dbaa892009-06-16 16:50:22 +00008341){
drh16a9b832007-05-05 18:39:25 +00008342 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00008343 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
danielk1977a4124bd2008-12-23 10:37:47 +00008344 int nNew = 0; /* Number of pages in apNew[] */
danielk19774dbaa892009-06-16 16:50:22 +00008345 int nOld; /* Number of pages in apOld[] */
drh14acc042001-06-10 19:56:58 +00008346 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00008347 int nxDiv; /* Next divider slot in pParent->aCell[] */
shane85095702009-06-15 16:27:08 +00008348 int rc = SQLITE_OK; /* The return code */
shane36840fd2009-06-26 16:32:13 +00008349 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00008350 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00008351 int usableSpace; /* Bytes in pPage beyond the header */
8352 int pageFlags; /* Value of pPage->aData[0] */
drhe5ae5732008-06-15 02:51:47 +00008353 int iSpace1 = 0; /* First unused byte of aSpace1[] */
danielk19776067a9b2009-06-09 09:41:00 +00008354 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
drhfacf0302008-06-17 15:12:00 +00008355 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00008356 MemPage *apOld[NB]; /* pPage and up to two siblings */
drha2fce642004-06-05 00:01:44 +00008357 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
danielk19774dbaa892009-06-16 16:50:22 +00008358 u8 *pRight; /* Location in parent of right-sibling pointer */
8359 u8 *apDiv[NB-1]; /* Divider cells in pParent */
drh1ffd2472015-06-23 02:37:30 +00008360 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
8361 int cntOld[NB+2]; /* Old index in b.apCell[] */
drh2a0df922014-10-30 23:14:56 +00008362 int szNew[NB+2]; /* Combined size of cells placed on i-th page */
danielk19774dbaa892009-06-16 16:50:22 +00008363 u8 *aSpace1; /* Space for copies of dividers cells */
8364 Pgno pgno; /* Temp var to store a page number in */
dane6593d82014-10-24 16:40:49 +00008365 u8 abDone[NB+2]; /* True after i'th new page is populated */
8366 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
drh7d4c94b2021-10-04 22:34:38 +00008367 CellArray b; /* Parsed information on cells being balanced */
dan33ea4862014-10-09 19:35:37 +00008368
8369 memset(abDone, 0, sizeof(abDone));
drh7d4c94b2021-10-04 22:34:38 +00008370 memset(&b, 0, sizeof(b));
danielk1977a50d9aa2009-06-08 14:49:45 +00008371 pBt = pParent->pBt;
8372 assert( sqlite3_mutex_held(pBt->mutex) );
8373 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977474b7cc2008-07-09 11:49:46 +00008374
danielk19774dbaa892009-06-16 16:50:22 +00008375 /* At this point pParent may have at most one overflow cell. And if
8376 ** this overflow cell is present, it must be the cell with
8377 ** index iParentIdx. This scenario comes about when this function
drhcd09c532009-07-20 19:30:00 +00008378 ** is called (indirectly) from sqlite3BtreeDelete().
8379 */
danielk19774dbaa892009-06-16 16:50:22 +00008380 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
drh2cbd78b2012-02-02 19:37:18 +00008381 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
danielk19774dbaa892009-06-16 16:50:22 +00008382
danielk197711a8a862009-06-17 11:49:52 +00008383 if( !aOvflSpace ){
mistachkinfad30392016-02-13 23:43:46 +00008384 return SQLITE_NOMEM_BKPT;
danielk197711a8a862009-06-17 11:49:52 +00008385 }
drh68133502019-02-11 17:22:30 +00008386 assert( pParent->nFree>=0 );
danielk197711a8a862009-06-17 11:49:52 +00008387
danielk1977a50d9aa2009-06-08 14:49:45 +00008388 /* Find the sibling pages to balance. Also locate the cells in pParent
8389 ** that divide the siblings. An attempt is made to find NN siblings on
8390 ** either side of pPage. More siblings are taken from one side, however,
8391 ** if there are fewer than NN siblings on the other side. If pParent
danielk19774dbaa892009-06-16 16:50:22 +00008392 ** has NB or fewer children then all children of pParent are taken.
8393 **
8394 ** This loop also drops the divider cells from the parent page. This
8395 ** way, the remainder of the function does not have to deal with any
drhcd09c532009-07-20 19:30:00 +00008396 ** overflow cells in the parent page, since if any existed they will
8397 ** have already been removed.
8398 */
danielk19774dbaa892009-06-16 16:50:22 +00008399 i = pParent->nOverflow + pParent->nCell;
8400 if( i<2 ){
drhc3b70572003-01-04 19:44:07 +00008401 nxDiv = 0;
danielk19774dbaa892009-06-16 16:50:22 +00008402 }else{
dan7d6885a2012-08-08 14:04:56 +00008403 assert( bBulk==0 || bBulk==1 );
danielk19774dbaa892009-06-16 16:50:22 +00008404 if( iParentIdx==0 ){
8405 nxDiv = 0;
8406 }else if( iParentIdx==i ){
dan7d6885a2012-08-08 14:04:56 +00008407 nxDiv = i-2+bBulk;
drh14acc042001-06-10 19:56:58 +00008408 }else{
danielk19774dbaa892009-06-16 16:50:22 +00008409 nxDiv = iParentIdx-1;
drh8b2f49b2001-06-08 00:21:52 +00008410 }
dan7d6885a2012-08-08 14:04:56 +00008411 i = 2-bBulk;
danielk19774dbaa892009-06-16 16:50:22 +00008412 }
dan7d6885a2012-08-08 14:04:56 +00008413 nOld = i+1;
danielk19774dbaa892009-06-16 16:50:22 +00008414 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
8415 pRight = &pParent->aData[pParent->hdrOffset+8];
8416 }else{
8417 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
8418 }
8419 pgno = get4byte(pRight);
8420 while( 1 ){
dan1f9f5762021-03-01 16:15:41 +00008421 if( rc==SQLITE_OK ){
8422 rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
8423 }
danielk19774dbaa892009-06-16 16:50:22 +00008424 if( rc ){
danielk197789bc4bc2009-07-21 19:25:24 +00008425 memset(apOld, 0, (i+1)*sizeof(MemPage*));
danielk19774dbaa892009-06-16 16:50:22 +00008426 goto balance_cleanup;
8427 }
dan7fff2e12017-05-29 14:27:37 +00008428 setMempageRoot(apOld[i], pgnoRoot);
drh85a379b2019-02-09 22:33:44 +00008429 if( apOld[i]->nFree<0 ){
8430 rc = btreeComputeFreeSpace(apOld[i]);
8431 if( rc ){
8432 memset(apOld, 0, (i)*sizeof(MemPage*));
8433 goto balance_cleanup;
8434 }
8435 }
danb9f8a182021-06-22 14:59:34 +00008436 nMaxCells += apOld[i]->nCell + ArraySize(pParent->apOvfl);
danielk19774dbaa892009-06-16 16:50:22 +00008437 if( (i--)==0 ) break;
8438
drh9cc5b4e2016-12-26 01:41:33 +00008439 if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
drh2cbd78b2012-02-02 19:37:18 +00008440 apDiv[i] = pParent->apOvfl[0];
danielk19774dbaa892009-06-16 16:50:22 +00008441 pgno = get4byte(apDiv[i]);
drh25ada072015-06-19 15:07:14 +00008442 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
danielk19774dbaa892009-06-16 16:50:22 +00008443 pParent->nOverflow = 0;
8444 }else{
8445 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
8446 pgno = get4byte(apDiv[i]);
drh25ada072015-06-19 15:07:14 +00008447 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
danielk19774dbaa892009-06-16 16:50:22 +00008448
8449 /* Drop the cell from the parent page. apDiv[i] still points to
8450 ** the cell within the parent, even though it has been dropped.
8451 ** This is safe because dropping a cell only overwrites the first
8452 ** four bytes of it, and this function does not need the first
8453 ** four bytes of the divider cell. So the pointer is safe to use
danielk197711a8a862009-06-17 11:49:52 +00008454 ** later on.
8455 **
drh8a575d92011-10-12 17:00:28 +00008456 ** But not if we are in secure-delete mode. In secure-delete mode,
danielk197711a8a862009-06-17 11:49:52 +00008457 ** the dropCell() routine will overwrite the entire cell with zeroes.
8458 ** In this case, temporarily copy the cell into the aOvflSpace[]
8459 ** buffer. It will be copied out again as soon as the aSpace[] buffer
8460 ** is allocated. */
drha5907a82017-06-19 11:44:22 +00008461 if( pBt->btsFlags & BTS_FAST_SECURE ){
drh8a575d92011-10-12 17:00:28 +00008462 int iOff;
8463
dan1f9f5762021-03-01 16:15:41 +00008464 /* If the following if() condition is not true, the db is corrupted.
8465 ** The call to dropCell() below will detect this. */
drh8a575d92011-10-12 17:00:28 +00008466 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
dan1f9f5762021-03-01 16:15:41 +00008467 if( (iOff+szNew[i])<=(int)pBt->usableSize ){
dan2ed11e72010-02-26 15:09:19 +00008468 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
8469 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
8470 }
drh5b47efa2010-02-12 18:18:39 +00008471 }
drh98add2e2009-07-20 17:11:49 +00008472 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
danielk19774dbaa892009-06-16 16:50:22 +00008473 }
drh8b2f49b2001-06-08 00:21:52 +00008474 }
8475
drha9121e42008-02-19 14:59:35 +00008476 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00008477 ** alignment */
drha9121e42008-02-19 14:59:35 +00008478 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00008479
drh8b2f49b2001-06-08 00:21:52 +00008480 /*
danielk1977634f2982005-03-28 08:44:07 +00008481 ** Allocate space for memory structures
8482 */
drhfacf0302008-06-17 15:12:00 +00008483 szScratch =
drh1ffd2472015-06-23 02:37:30 +00008484 nMaxCells*sizeof(u8*) /* b.apCell */
8485 + nMaxCells*sizeof(u16) /* b.szCell */
dan33ea4862014-10-09 19:35:37 +00008486 + pBt->pageSize; /* aSpace1 */
drh5279d342014-11-04 13:41:32 +00008487
drhf012dc42019-03-19 15:36:46 +00008488 assert( szScratch<=7*(int)pBt->pageSize );
drhb2a0f752017-08-28 15:51:35 +00008489 b.apCell = sqlite3StackAllocRaw(0, szScratch );
drh1ffd2472015-06-23 02:37:30 +00008490 if( b.apCell==0 ){
mistachkinfad30392016-02-13 23:43:46 +00008491 rc = SQLITE_NOMEM_BKPT;
danielk1977634f2982005-03-28 08:44:07 +00008492 goto balance_cleanup;
8493 }
drh1ffd2472015-06-23 02:37:30 +00008494 b.szCell = (u16*)&b.apCell[nMaxCells];
8495 aSpace1 = (u8*)&b.szCell[nMaxCells];
drhea598cb2009-04-05 12:22:08 +00008496 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
drh14acc042001-06-10 19:56:58 +00008497
8498 /*
8499 ** Load pointers to all cells on sibling pages and the divider cells
drh1ffd2472015-06-23 02:37:30 +00008500 ** into the local b.apCell[] array. Make copies of the divider cells
dan33ea4862014-10-09 19:35:37 +00008501 ** into space obtained from aSpace1[]. The divider cells have already
8502 ** been removed from pParent.
drh4b70f112004-05-02 21:12:19 +00008503 **
8504 ** If the siblings are on leaf pages, then the child pointers of the
8505 ** divider cells are stripped from the cells before they are copied
drh1ffd2472015-06-23 02:37:30 +00008506 ** into aSpace1[]. In this way, all cells in b.apCell[] are without
drh4b70f112004-05-02 21:12:19 +00008507 ** child pointers. If siblings are not leaves, then all cell in
drh1ffd2472015-06-23 02:37:30 +00008508 ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
drh4b70f112004-05-02 21:12:19 +00008509 ** are alike.
drh96f5b762004-05-16 16:24:36 +00008510 **
8511 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
8512 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00008513 */
drh1ffd2472015-06-23 02:37:30 +00008514 b.pRef = apOld[0];
8515 leafCorrection = b.pRef->leaf*4;
8516 leafData = b.pRef->intKeyLeaf;
drh8b2f49b2001-06-08 00:21:52 +00008517 for(i=0; i<nOld; i++){
dan33ea4862014-10-09 19:35:37 +00008518 MemPage *pOld = apOld[i];
drh4edfdd32015-06-23 14:49:42 +00008519 int limit = pOld->nCell;
8520 u8 *aData = pOld->aData;
8521 u16 maskPage = pOld->maskPage;
drh4f4bf772015-06-23 17:09:53 +00008522 u8 *piCell = aData + pOld->cellOffset;
drhfe647dc2015-06-23 18:24:25 +00008523 u8 *piEnd;
drhe12ca5a2019-05-02 15:56:39 +00008524 VVA_ONLY( int nCellAtStart = b.nCell; )
danielk19774dbaa892009-06-16 16:50:22 +00008525
drh73d340a2015-05-28 11:23:11 +00008526 /* Verify that all sibling pages are of the same "type" (table-leaf,
8527 ** table-interior, index-leaf, or index-interior).
8528 */
8529 if( pOld->aData[0]!=apOld[0]->aData[0] ){
8530 rc = SQLITE_CORRUPT_BKPT;
8531 goto balance_cleanup;
8532 }
8533
drhfe647dc2015-06-23 18:24:25 +00008534 /* Load b.apCell[] with pointers to all cells in pOld. If pOld
drh8d7f1632018-01-23 13:30:38 +00008535 ** contains overflow cells, include them in the b.apCell[] array
drhfe647dc2015-06-23 18:24:25 +00008536 ** in the correct spot.
8537 **
8538 ** Note that when there are multiple overflow cells, it is always the
8539 ** case that they are sequential and adjacent. This invariant arises
8540 ** because multiple overflows can only occurs when inserting divider
8541 ** cells into a parent on a prior balance, and divider cells are always
8542 ** adjacent and are inserted in order. There is an assert() tagged
8543 ** with "NOTE 1" in the overflow cell insertion loop to prove this
8544 ** invariant.
drh4edfdd32015-06-23 14:49:42 +00008545 **
8546 ** This must be done in advance. Once the balance starts, the cell
8547 ** offset section of the btree page will be overwritten and we will no
8548 ** long be able to find the cells if a pointer to each cell is not saved
8549 ** first.
8550 */
drh36b78ee2016-01-20 01:32:00 +00008551 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
drh68f2a572011-06-03 17:50:49 +00008552 if( pOld->nOverflow>0 ){
drh27e80a32019-08-15 13:17:49 +00008553 if( NEVER(limit<pOld->aiOvfl[0]) ){
drhe12ca5a2019-05-02 15:56:39 +00008554 rc = SQLITE_CORRUPT_BKPT;
8555 goto balance_cleanup;
8556 }
drhfe647dc2015-06-23 18:24:25 +00008557 limit = pOld->aiOvfl[0];
8558 for(j=0; j<limit; j++){
drh329428e2015-06-30 13:28:18 +00008559 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
drhfe647dc2015-06-23 18:24:25 +00008560 piCell += 2;
8561 b.nCell++;
8562 }
8563 for(k=0; k<pOld->nOverflow; k++){
8564 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
drh4edfdd32015-06-23 14:49:42 +00008565 b.apCell[b.nCell] = pOld->apOvfl[k];
drh1ffd2472015-06-23 02:37:30 +00008566 b.nCell++;
drh68f2a572011-06-03 17:50:49 +00008567 }
drh1ffd2472015-06-23 02:37:30 +00008568 }
drhfe647dc2015-06-23 18:24:25 +00008569 piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
8570 while( piCell<piEnd ){
drh4edfdd32015-06-23 14:49:42 +00008571 assert( b.nCell<nMaxCells );
drh329428e2015-06-30 13:28:18 +00008572 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
drh4f4bf772015-06-23 17:09:53 +00008573 piCell += 2;
drh4edfdd32015-06-23 14:49:42 +00008574 b.nCell++;
drh4edfdd32015-06-23 14:49:42 +00008575 }
drhe12ca5a2019-05-02 15:56:39 +00008576 assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
drh4edfdd32015-06-23 14:49:42 +00008577
drh1ffd2472015-06-23 02:37:30 +00008578 cntOld[i] = b.nCell;
danielk19774dbaa892009-06-16 16:50:22 +00008579 if( i<nOld-1 && !leafData){
shane36840fd2009-06-26 16:32:13 +00008580 u16 sz = (u16)szNew[i];
danielk19774dbaa892009-06-16 16:50:22 +00008581 u8 *pTemp;
drh1ffd2472015-06-23 02:37:30 +00008582 assert( b.nCell<nMaxCells );
8583 b.szCell[b.nCell] = sz;
danielk19774dbaa892009-06-16 16:50:22 +00008584 pTemp = &aSpace1[iSpace1];
8585 iSpace1 += sz;
drhe22e03e2010-08-18 21:19:03 +00008586 assert( sz<=pBt->maxLocal+23 );
drhfcd71b62011-04-05 22:08:24 +00008587 assert( iSpace1 <= (int)pBt->pageSize );
danielk19774dbaa892009-06-16 16:50:22 +00008588 memcpy(pTemp, apDiv[i], sz);
drh1ffd2472015-06-23 02:37:30 +00008589 b.apCell[b.nCell] = pTemp+leafCorrection;
danielk19774dbaa892009-06-16 16:50:22 +00008590 assert( leafCorrection==0 || leafCorrection==4 );
drh1ffd2472015-06-23 02:37:30 +00008591 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
danielk19774dbaa892009-06-16 16:50:22 +00008592 if( !pOld->leaf ){
8593 assert( leafCorrection==0 );
dan5b482a92021-04-20 13:31:51 +00008594 assert( pOld->hdrOffset==0 || CORRUPT_DB );
danielk19774dbaa892009-06-16 16:50:22 +00008595 /* The right pointer of the child page pOld becomes the left
8596 ** pointer of the divider cell */
drh1ffd2472015-06-23 02:37:30 +00008597 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
danielk19774dbaa892009-06-16 16:50:22 +00008598 }else{
8599 assert( leafCorrection==4 );
drh1ffd2472015-06-23 02:37:30 +00008600 while( b.szCell[b.nCell]<4 ){
dan8f1eb8a2014-12-06 14:56:49 +00008601 /* Do not allow any cells smaller than 4 bytes. If a smaller cell
8602 ** does exist, pad it with 0x00 bytes. */
drh1ffd2472015-06-23 02:37:30 +00008603 assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
8604 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
danee7172f2014-12-24 18:11:50 +00008605 aSpace1[iSpace1++] = 0x00;
drh1ffd2472015-06-23 02:37:30 +00008606 b.szCell[b.nCell]++;
danielk1977ac11ee62005-01-15 12:45:51 +00008607 }
8608 }
drh1ffd2472015-06-23 02:37:30 +00008609 b.nCell++;
drh8b2f49b2001-06-08 00:21:52 +00008610 }
drh8b2f49b2001-06-08 00:21:52 +00008611 }
8612
8613 /*
drh1ffd2472015-06-23 02:37:30 +00008614 ** Figure out the number of pages needed to hold all b.nCell cells.
drh6019e162001-07-02 17:51:45 +00008615 ** Store this number in "k". Also compute szNew[] which is the total
8616 ** size of all cells on the i-th page and cntNew[] which is the index
drh1ffd2472015-06-23 02:37:30 +00008617 ** in b.apCell[] of the cell that divides page i from page i+1.
8618 ** cntNew[k] should equal b.nCell.
drh6019e162001-07-02 17:51:45 +00008619 **
drh96f5b762004-05-16 16:24:36 +00008620 ** Values computed by this block:
8621 **
8622 ** k: The total number of sibling pages
8623 ** szNew[i]: Spaced used on the i-th sibling page.
drh1ffd2472015-06-23 02:37:30 +00008624 ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
drh96f5b762004-05-16 16:24:36 +00008625 ** the right of the i-th sibling page.
8626 ** usableSpace: Number of bytes of space available on each sibling.
8627 **
drh8b2f49b2001-06-08 00:21:52 +00008628 */
drh43605152004-05-29 21:46:49 +00008629 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh26b7ec82019-02-01 14:50:43 +00008630 for(i=k=0; i<nOld; i++, k++){
drh658873b2015-06-22 20:02:04 +00008631 MemPage *p = apOld[i];
drh26b7ec82019-02-01 14:50:43 +00008632 b.apEnd[k] = p->aDataEnd;
8633 b.ixNx[k] = cntOld[i];
drh9c7e44c2019-02-14 15:27:12 +00008634 if( k && b.ixNx[k]==b.ixNx[k-1] ){
8635 k--; /* Omit b.ixNx[] entry for child pages with no cells */
8636 }
drh26b7ec82019-02-01 14:50:43 +00008637 if( !leafData ){
8638 k++;
8639 b.apEnd[k] = pParent->aDataEnd;
8640 b.ixNx[k] = cntOld[i]+1;
8641 }
drhb0ea9432019-02-09 21:06:40 +00008642 assert( p->nFree>=0 );
drh658873b2015-06-22 20:02:04 +00008643 szNew[i] = usableSpace - p->nFree;
drh658873b2015-06-22 20:02:04 +00008644 for(j=0; j<p->nOverflow; j++){
8645 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
8646 }
8647 cntNew[i] = cntOld[i];
8648 }
8649 k = nOld;
8650 for(i=0; i<k; i++){
8651 int sz;
8652 while( szNew[i]>usableSpace ){
8653 if( i+1>=k ){
8654 k = i+2;
8655 if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
8656 szNew[k-1] = 0;
drh1ffd2472015-06-23 02:37:30 +00008657 cntNew[k-1] = b.nCell;
drh658873b2015-06-22 20:02:04 +00008658 }
drh1ffd2472015-06-23 02:37:30 +00008659 sz = 2 + cachedCellSize(&b, cntNew[i]-1);
drh658873b2015-06-22 20:02:04 +00008660 szNew[i] -= sz;
8661 if( !leafData ){
drh1ffd2472015-06-23 02:37:30 +00008662 if( cntNew[i]<b.nCell ){
8663 sz = 2 + cachedCellSize(&b, cntNew[i]);
8664 }else{
8665 sz = 0;
8666 }
drh658873b2015-06-22 20:02:04 +00008667 }
8668 szNew[i+1] += sz;
8669 cntNew[i]--;
8670 }
drh1ffd2472015-06-23 02:37:30 +00008671 while( cntNew[i]<b.nCell ){
8672 sz = 2 + cachedCellSize(&b, cntNew[i]);
drh658873b2015-06-22 20:02:04 +00008673 if( szNew[i]+sz>usableSpace ) break;
8674 szNew[i] += sz;
8675 cntNew[i]++;
8676 if( !leafData ){
drh1ffd2472015-06-23 02:37:30 +00008677 if( cntNew[i]<b.nCell ){
8678 sz = 2 + cachedCellSize(&b, cntNew[i]);
8679 }else{
8680 sz = 0;
8681 }
drh658873b2015-06-22 20:02:04 +00008682 }
8683 szNew[i+1] -= sz;
8684 }
drh1ffd2472015-06-23 02:37:30 +00008685 if( cntNew[i]>=b.nCell ){
drh658873b2015-06-22 20:02:04 +00008686 k = i+1;
drh672073a2015-06-24 12:07:40 +00008687 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
drh658873b2015-06-22 20:02:04 +00008688 rc = SQLITE_CORRUPT_BKPT;
8689 goto balance_cleanup;
drh6019e162001-07-02 17:51:45 +00008690 }
8691 }
drh96f5b762004-05-16 16:24:36 +00008692
8693 /*
8694 ** The packing computed by the previous block is biased toward the siblings
drh2a0df922014-10-30 23:14:56 +00008695 ** on the left side (siblings with smaller keys). The left siblings are
8696 ** always nearly full, while the right-most sibling might be nearly empty.
8697 ** The next block of code attempts to adjust the packing of siblings to
8698 ** get a better balance.
drh96f5b762004-05-16 16:24:36 +00008699 **
8700 ** This adjustment is more than an optimization. The packing above might
8701 ** be so out of balance as to be illegal. For example, the right-most
8702 ** sibling might be completely empty. This adjustment is not optional.
8703 */
drh6019e162001-07-02 17:51:45 +00008704 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00008705 int szRight = szNew[i]; /* Size of sibling on the right */
8706 int szLeft = szNew[i-1]; /* Size of sibling on the left */
8707 int r; /* Index of right-most cell in left sibling */
8708 int d; /* Index of first cell to the left of right sibling */
8709
drh008d64c2015-06-23 16:00:24 +00008710 r = cntNew[i-1] - 1;
8711 d = r + 1 - leafData;
8712 (void)cachedCellSize(&b, d);
drh672073a2015-06-24 12:07:40 +00008713 do{
drh16635fa2022-11-19 18:43:32 +00008714 int szR, szD;
drh1ffd2472015-06-23 02:37:30 +00008715 assert( d<nMaxCells );
8716 assert( r<nMaxCells );
drh16635fa2022-11-19 18:43:32 +00008717 szR = cachedCellSize(&b, r);
8718 szD = b.szCell[d];
drh1ffd2472015-06-23 02:37:30 +00008719 if( szRight!=0
drh16635fa2022-11-19 18:43:32 +00008720 && (bBulk || szRight+szD+2 > szLeft-(szR+(i==k-1?0:2)))){
drh1ffd2472015-06-23 02:37:30 +00008721 break;
8722 }
drh16635fa2022-11-19 18:43:32 +00008723 szRight += szD + 2;
8724 szLeft -= szR + 2;
drh008d64c2015-06-23 16:00:24 +00008725 cntNew[i-1] = r;
drh008d64c2015-06-23 16:00:24 +00008726 r--;
8727 d--;
drh672073a2015-06-24 12:07:40 +00008728 }while( r>=0 );
drh96f5b762004-05-16 16:24:36 +00008729 szNew[i] = szRight;
8730 szNew[i-1] = szLeft;
drh672073a2015-06-24 12:07:40 +00008731 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
8732 rc = SQLITE_CORRUPT_BKPT;
8733 goto balance_cleanup;
8734 }
drh6019e162001-07-02 17:51:45 +00008735 }
drh09d0deb2005-08-02 17:13:09 +00008736
drh2a0df922014-10-30 23:14:56 +00008737 /* Sanity check: For a non-corrupt database file one of the follwing
8738 ** must be true:
8739 ** (1) We found one or more cells (cntNew[0])>0), or
8740 ** (2) pPage is a virtual root page. A virtual root page is when
8741 ** the real root page is page 1 and we are the only child of
8742 ** that page.
drh09d0deb2005-08-02 17:13:09 +00008743 */
drh2a0df922014-10-30 23:14:56 +00008744 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
dan33ea4862014-10-09 19:35:37 +00008745 TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
8746 apOld[0]->pgno, apOld[0]->nCell,
8747 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
8748 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
danielk1977e5765212009-06-17 11:13:28 +00008749 ));
8750
drh8b2f49b2001-06-08 00:21:52 +00008751 /*
drh6b308672002-07-08 02:16:37 +00008752 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00008753 */
danielk1977a50d9aa2009-06-08 14:49:45 +00008754 pageFlags = apOld[0]->aData[0];
drh14acc042001-06-10 19:56:58 +00008755 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00008756 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00008757 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00008758 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00008759 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00008760 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00008761 nNew++;
drh41d26392021-06-20 22:17:49 +00008762 if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv))
8763 && rc==SQLITE_OK
8764 ){
drh9e673ac2021-02-01 12:39:50 +00008765 rc = SQLITE_CORRUPT_BKPT;
8766 }
danielk197728129562005-01-11 10:25:06 +00008767 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00008768 }else{
drh7aa8f852006-03-28 00:24:44 +00008769 assert( i>0 );
dan428c2182012-08-06 18:50:11 +00008770 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
drh6b308672002-07-08 02:16:37 +00008771 if( rc ) goto balance_cleanup;
dan33ea4862014-10-09 19:35:37 +00008772 zeroPage(pNew, pageFlags);
drhda200cc2004-05-09 11:51:38 +00008773 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00008774 nNew++;
drh1ffd2472015-06-23 02:37:30 +00008775 cntOld[i] = b.nCell;
danielk19774dbaa892009-06-16 16:50:22 +00008776
8777 /* Set the pointer-map entry for the new sibling page. */
dan7b3d71e2015-08-19 20:27:05 +00008778 if( REQUIRE_PTRMAP ){
drh98add2e2009-07-20 17:11:49 +00008779 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00008780 if( rc!=SQLITE_OK ){
8781 goto balance_cleanup;
8782 }
8783 }
drh6b308672002-07-08 02:16:37 +00008784 }
drh8b2f49b2001-06-08 00:21:52 +00008785 }
8786
8787 /*
dan33ea4862014-10-09 19:35:37 +00008788 ** Reassign page numbers so that the new pages are in ascending order.
8789 ** This helps to keep entries in the disk file in order so that a scan
8790 ** of the table is closer to a linear scan through the file. That in turn
8791 ** helps the operating system to deliver pages from the disk more rapidly.
drhf9ffac92002-03-02 19:00:31 +00008792 **
drh9c3a1142022-08-31 15:04:42 +00008793 ** An O(N*N) sort algorithm is used, but since N is never more than NB+2
8794 ** (5), that is not a performance concern.
drhf9ffac92002-03-02 19:00:31 +00008795 **
dan33ea4862014-10-09 19:35:37 +00008796 ** When NB==3, this one optimization makes the database about 25% faster
8797 ** for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00008798 */
dan33ea4862014-10-09 19:35:37 +00008799 for(i=0; i<nNew; i++){
drh9c3a1142022-08-31 15:04:42 +00008800 aPgno[i] = apNew[i]->pgno;
8801 assert( apNew[i]->pDbPage->flags & PGHDR_WRITEABLE );
8802 assert( apNew[i]->pDbPage->flags & PGHDR_DIRTY );
dan33ea4862014-10-09 19:35:37 +00008803 }
drh9c3a1142022-08-31 15:04:42 +00008804 for(i=0; i<nNew-1; i++){
8805 int iB = i;
8806 for(j=i+1; j<nNew; j++){
8807 if( apNew[j]->pgno < apNew[iB]->pgno ) iB = j;
drhf9ffac92002-03-02 19:00:31 +00008808 }
drh9c3a1142022-08-31 15:04:42 +00008809
8810 /* If apNew[i] has a page number that is bigger than any of the
8811 ** subsequence apNew[i] entries, then swap apNew[i] with the subsequent
8812 ** entry that has the smallest page number (which we know to be
8813 ** entry apNew[iB]).
8814 */
8815 if( iB!=i ){
8816 Pgno pgnoA = apNew[i]->pgno;
8817 Pgno pgnoB = apNew[iB]->pgno;
8818 Pgno pgnoTemp = (PENDING_BYTE/pBt->pageSize)+1;
8819 u16 fgA = apNew[i]->pDbPage->flags;
8820 u16 fgB = apNew[iB]->pDbPage->flags;
8821 sqlite3PagerRekey(apNew[i]->pDbPage, pgnoTemp, fgB);
8822 sqlite3PagerRekey(apNew[iB]->pDbPage, pgnoA, fgA);
8823 sqlite3PagerRekey(apNew[i]->pDbPage, pgnoB, fgB);
8824 apNew[i]->pgno = pgnoB;
8825 apNew[iB]->pgno = pgnoA;
drhf9ffac92002-03-02 19:00:31 +00008826 }
8827 }
dan33ea4862014-10-09 19:35:37 +00008828
8829 TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
8830 "%d(%d nc=%d) %d(%d nc=%d)\n",
8831 apNew[0]->pgno, szNew[0], cntNew[0],
danielk19774dbaa892009-06-16 16:50:22 +00008832 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
dan33ea4862014-10-09 19:35:37 +00008833 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
danielk19774dbaa892009-06-16 16:50:22 +00008834 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
dan33ea4862014-10-09 19:35:37 +00008835 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
danielk19774dbaa892009-06-16 16:50:22 +00008836 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
dan33ea4862014-10-09 19:35:37 +00008837 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
8838 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
8839 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
8840 ));
danielk19774dbaa892009-06-16 16:50:22 +00008841
8842 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
drh55f66b32019-07-16 19:44:32 +00008843 assert( nNew>=1 && nNew<=ArraySize(apNew) );
8844 assert( apNew[nNew-1]!=0 );
danielk19774dbaa892009-06-16 16:50:22 +00008845 put4byte(pRight, apNew[nNew-1]->pgno);
drh24cd67e2004-05-10 16:18:47 +00008846
dan33ea4862014-10-09 19:35:37 +00008847 /* If the sibling pages are not leaves, ensure that the right-child pointer
8848 ** of the right-most new sibling page is set to the value that was
8849 ** originally in the same field of the right-most old sibling page. */
8850 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
8851 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
8852 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
8853 }
danielk1977ac11ee62005-01-15 12:45:51 +00008854
dan33ea4862014-10-09 19:35:37 +00008855 /* Make any required updates to pointer map entries associated with
8856 ** cells stored on sibling pages following the balance operation. Pointer
8857 ** map entries associated with divider cells are set by the insertCell()
8858 ** routine. The associated pointer map entries are:
8859 **
8860 ** a) if the cell contains a reference to an overflow chain, the
8861 ** entry associated with the first page in the overflow chain, and
8862 **
8863 ** b) if the sibling pages are not leaves, the child page associated
8864 ** with the cell.
8865 **
8866 ** If the sibling pages are not leaves, then the pointer map entry
8867 ** associated with the right-child of each sibling may also need to be
8868 ** updated. This happens below, after the sibling pages have been
8869 ** populated, not here.
8870 */
dan7b3d71e2015-08-19 20:27:05 +00008871 if( REQUIRE_PTRMAP ){
drh0f1bf4c2019-01-13 20:17:21 +00008872 MemPage *pOld;
8873 MemPage *pNew = pOld = apNew[0];
dan33ea4862014-10-09 19:35:37 +00008874 int cntOldNext = pNew->nCell + pNew->nOverflow;
dan33ea4862014-10-09 19:35:37 +00008875 int iNew = 0;
8876 int iOld = 0;
danielk1977634f2982005-03-28 08:44:07 +00008877
drh1ffd2472015-06-23 02:37:30 +00008878 for(i=0; i<b.nCell; i++){
8879 u8 *pCell = b.apCell[i];
drh9c7e44c2019-02-14 15:27:12 +00008880 while( i==cntOldNext ){
8881 iOld++;
8882 assert( iOld<nNew || iOld<nOld );
drhdd2d9a32019-05-07 17:47:43 +00008883 assert( iOld>=0 && iOld<NB );
drh9c7e44c2019-02-14 15:27:12 +00008884 pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];
dan33ea4862014-10-09 19:35:37 +00008885 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
dan33ea4862014-10-09 19:35:37 +00008886 }
8887 if( i==cntNew[iNew] ){
8888 pNew = apNew[++iNew];
8889 if( !leafData ) continue;
8890 }
8891
8892 /* Cell pCell is destined for new sibling page pNew. Originally, it
drhba0f9992014-10-30 20:48:44 +00008893 ** was either part of sibling page iOld (possibly an overflow cell),
dan33ea4862014-10-09 19:35:37 +00008894 ** or else the divider cell to the left of sibling page iOld. So,
8895 ** if sibling page iOld had the same page number as pNew, and if
8896 ** pCell really was a part of sibling page iOld (not a divider or
8897 ** overflow cell), we can skip updating the pointer map entries. */
drhd52d52b2014-12-06 02:05:44 +00008898 if( iOld>=nNew
8899 || pNew->pgno!=aPgno[iOld]
drh9c7e44c2019-02-14 15:27:12 +00008900 || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
drhd52d52b2014-12-06 02:05:44 +00008901 ){
dan33ea4862014-10-09 19:35:37 +00008902 if( !leafCorrection ){
8903 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
8904 }
drh1ffd2472015-06-23 02:37:30 +00008905 if( cachedCellSize(&b,i)>pNew->minLocal ){
drh0f1bf4c2019-01-13 20:17:21 +00008906 ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
danielk19774aeff622007-05-12 09:30:47 +00008907 }
drhea82b372015-06-23 21:35:28 +00008908 if( rc ) goto balance_cleanup;
drh4b70f112004-05-02 21:12:19 +00008909 }
drh14acc042001-06-10 19:56:58 +00008910 }
8911 }
dan33ea4862014-10-09 19:35:37 +00008912
8913 /* Insert new divider cells into pParent. */
8914 for(i=0; i<nNew-1; i++){
8915 u8 *pCell;
8916 u8 *pTemp;
8917 int sz;
drhc3c23f32021-05-06 11:02:55 +00008918 u8 *pSrcEnd;
dan33ea4862014-10-09 19:35:37 +00008919 MemPage *pNew = apNew[i];
8920 j = cntNew[i];
8921
8922 assert( j<nMaxCells );
drh1ffd2472015-06-23 02:37:30 +00008923 assert( b.apCell[j]!=0 );
8924 pCell = b.apCell[j];
8925 sz = b.szCell[j] + leafCorrection;
dan33ea4862014-10-09 19:35:37 +00008926 pTemp = &aOvflSpace[iOvflSpace];
8927 if( !pNew->leaf ){
8928 memcpy(&pNew->aData[8], pCell, 4);
8929 }else if( leafData ){
8930 /* If the tree is a leaf-data tree, and the siblings are leaves,
drh1ffd2472015-06-23 02:37:30 +00008931 ** then there is no divider cell in b.apCell[]. Instead, the divider
dan33ea4862014-10-09 19:35:37 +00008932 ** cell consists of the integer key for the right-most cell of
8933 ** the sibling-page assembled above only.
8934 */
8935 CellInfo info;
8936 j--;
drh1ffd2472015-06-23 02:37:30 +00008937 pNew->xParseCell(pNew, b.apCell[j], &info);
dan33ea4862014-10-09 19:35:37 +00008938 pCell = pTemp;
8939 sz = 4 + putVarint(&pCell[4], info.nKey);
8940 pTemp = 0;
8941 }else{
8942 pCell -= 4;
8943 /* Obscure case for non-leaf-data trees: If the cell at pCell was
8944 ** previously stored on a leaf node, and its reported size was 4
8945 ** bytes, then it may actually be smaller than this
8946 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
8947 ** any cell). But it is important to pass the correct size to
8948 ** insertCell(), so reparse the cell now.
8949 **
drhc1fb2b82016-03-09 03:29:27 +00008950 ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
8951 ** and WITHOUT ROWID tables with exactly one column which is the
8952 ** primary key.
dan33ea4862014-10-09 19:35:37 +00008953 */
drh1ffd2472015-06-23 02:37:30 +00008954 if( b.szCell[j]==4 ){
dan33ea4862014-10-09 19:35:37 +00008955 assert(leafCorrection==4);
drh25ada072015-06-19 15:07:14 +00008956 sz = pParent->xCellSize(pParent, pCell);
dan33ea4862014-10-09 19:35:37 +00008957 }
8958 }
8959 iOvflSpace += sz;
8960 assert( sz<=pBt->maxLocal+23 );
8961 assert( iOvflSpace <= (int)pBt->pageSize );
dan6625d6d2022-04-12 17:02:27 +00008962 for(k=0; b.ixNx[k]<=j && ALWAYS(k<NB*2); k++){}
drhc3c23f32021-05-06 11:02:55 +00008963 pSrcEnd = b.apEnd[k];
8964 if( SQLITE_WITHIN(pSrcEnd, pCell, pCell+sz) ){
8965 rc = SQLITE_CORRUPT_BKPT;
8966 goto balance_cleanup;
8967 }
drhb53d8fa2022-11-21 15:55:57 +00008968 rc = insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno);
dan33ea4862014-10-09 19:35:37 +00008969 if( rc!=SQLITE_OK ) goto balance_cleanup;
8970 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8971 }
8972
8973 /* Now update the actual sibling pages. The order in which they are updated
8974 ** is important, as this code needs to avoid disrupting any page from which
8975 ** cells may still to be read. In practice, this means:
8976 **
drhd836d422014-10-31 14:26:36 +00008977 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
8978 ** then it is not safe to update page apNew[iPg] until after
8979 ** the left-hand sibling apNew[iPg-1] has been updated.
dan33ea4862014-10-09 19:35:37 +00008980 **
drhd836d422014-10-31 14:26:36 +00008981 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
8982 ** then it is not safe to update page apNew[iPg] until after
8983 ** the right-hand sibling apNew[iPg+1] has been updated.
dan33ea4862014-10-09 19:35:37 +00008984 **
8985 ** If neither of the above apply, the page is safe to update.
drhd836d422014-10-31 14:26:36 +00008986 **
8987 ** The iPg value in the following loop starts at nNew-1 goes down
8988 ** to 0, then back up to nNew-1 again, thus making two passes over
8989 ** the pages. On the initial downward pass, only condition (1) above
8990 ** needs to be tested because (2) will always be true from the previous
8991 ** step. On the upward pass, both conditions are always true, so the
8992 ** upwards pass simply processes pages that were missed on the downward
8993 ** pass.
dan33ea4862014-10-09 19:35:37 +00008994 */
drhbec021b2014-10-31 12:22:00 +00008995 for(i=1-nNew; i<nNew; i++){
8996 int iPg = i<0 ? -i : i;
drhbec021b2014-10-31 12:22:00 +00008997 assert( iPg>=0 && iPg<nNew );
drhd836d422014-10-31 14:26:36 +00008998 if( abDone[iPg] ) continue; /* Skip pages already processed */
8999 if( i>=0 /* On the upwards pass, or... */
9000 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
dan33ea4862014-10-09 19:35:37 +00009001 ){
dan09c68402014-10-11 20:00:24 +00009002 int iNew;
9003 int iOld;
9004 int nNewCell;
9005
drhd836d422014-10-31 14:26:36 +00009006 /* Verify condition (1): If cells are moving left, update iPg
9007 ** only after iPg-1 has already been updated. */
9008 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
9009
9010 /* Verify condition (2): If cells are moving right, update iPg
9011 ** only after iPg+1 has already been updated. */
9012 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
9013
dan09c68402014-10-11 20:00:24 +00009014 if( iPg==0 ){
9015 iNew = iOld = 0;
9016 nNewCell = cntNew[0];
9017 }else{
drh1ffd2472015-06-23 02:37:30 +00009018 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
dan09c68402014-10-11 20:00:24 +00009019 iNew = cntNew[iPg-1] + !leafData;
9020 nNewCell = cntNew[iPg] - iNew;
9021 }
9022
drh1ffd2472015-06-23 02:37:30 +00009023 rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
drh658873b2015-06-22 20:02:04 +00009024 if( rc ) goto balance_cleanup;
drhd836d422014-10-31 14:26:36 +00009025 abDone[iPg]++;
dand7b545b2014-10-13 18:03:27 +00009026 apNew[iPg]->nFree = usableSpace-szNew[iPg];
dan09c68402014-10-11 20:00:24 +00009027 assert( apNew[iPg]->nOverflow==0 );
9028 assert( apNew[iPg]->nCell==nNewCell );
dan33ea4862014-10-09 19:35:37 +00009029 }
9030 }
drhd836d422014-10-31 14:26:36 +00009031
9032 /* All pages have been processed exactly once */
dan33ea4862014-10-09 19:35:37 +00009033 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
9034
drh7aa8f852006-03-28 00:24:44 +00009035 assert( nOld>0 );
9036 assert( nNew>0 );
drh14acc042001-06-10 19:56:58 +00009037
danielk197713bd99f2009-06-24 05:40:34 +00009038 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
9039 /* The root page of the b-tree now contains no cells. The only sibling
9040 ** page is the right-child of the parent. Copy the contents of the
9041 ** child page into the parent, decreasing the overall height of the
9042 ** b-tree structure by one. This is described as the "balance-shallower"
9043 ** sub-algorithm in some documentation.
9044 **
9045 ** If this is an auto-vacuum database, the call to copyNodeContent()
9046 ** sets all pointer-map entries corresponding to database image pages
9047 ** for which the pointer is stored within the content being copied.
9048 **
drh768f2902014-10-31 02:51:41 +00009049 ** It is critical that the child page be defragmented before being
9050 ** copied into the parent, because if the parent is page 1 then it will
9051 ** by smaller than the child due to the database header, and so all the
9052 ** free space needs to be up front.
9053 */
drh9b5351d2015-09-30 14:19:08 +00009054 assert( nNew==1 || CORRUPT_DB );
dan3b2ede12017-02-25 16:24:02 +00009055 rc = defragmentPage(apNew[0], -1);
drh768f2902014-10-31 02:51:41 +00009056 testcase( rc!=SQLITE_OK );
9057 assert( apNew[0]->nFree ==
drh1c960262019-03-25 18:44:08 +00009058 (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
9059 - apNew[0]->nCell*2)
drh768f2902014-10-31 02:51:41 +00009060 || rc!=SQLITE_OK
9061 );
9062 copyNodeContent(apNew[0], pParent, &rc);
9063 freePage(apNew[0], &rc);
dan7b3d71e2015-08-19 20:27:05 +00009064 }else if( REQUIRE_PTRMAP && !leafCorrection ){
dan33ea4862014-10-09 19:35:37 +00009065 /* Fix the pointer map entries associated with the right-child of each
9066 ** sibling page. All other pointer map entries have already been taken
9067 ** care of. */
9068 for(i=0; i<nNew; i++){
9069 u32 key = get4byte(&apNew[i]->aData[8]);
9070 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00009071 }
dan33ea4862014-10-09 19:35:37 +00009072 }
danielk19774dbaa892009-06-16 16:50:22 +00009073
dan33ea4862014-10-09 19:35:37 +00009074 assert( pParent->isInit );
9075 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
drh1ffd2472015-06-23 02:37:30 +00009076 nOld, nNew, b.nCell));
danielk19774dbaa892009-06-16 16:50:22 +00009077
dan33ea4862014-10-09 19:35:37 +00009078 /* Free any old pages that were not reused as new pages.
9079 */
9080 for(i=nNew; i<nOld; i++){
9081 freePage(apOld[i], &rc);
9082 }
9083
dane6593d82014-10-24 16:40:49 +00009084#if 0
drhe7d53842022-11-21 14:13:10 +00009085 if( ISAUTOVACUUM(pBt) && rc==SQLITE_OK && apNew[0]->isInit ){
danielk19774dbaa892009-06-16 16:50:22 +00009086 /* The ptrmapCheckPages() contains assert() statements that verify that
9087 ** all pointer map pages are set correctly. This is helpful while
9088 ** debugging. This is usually disabled because a corrupt database may
9089 ** cause an assert() statement to fail. */
9090 ptrmapCheckPages(apNew, nNew);
9091 ptrmapCheckPages(&pParent, 1);
danielk19774dbaa892009-06-16 16:50:22 +00009092 }
dan33ea4862014-10-09 19:35:37 +00009093#endif
danielk1977cd581a72009-06-23 15:43:39 +00009094
drh8b2f49b2001-06-08 00:21:52 +00009095 /*
drh14acc042001-06-10 19:56:58 +00009096 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00009097 */
drh14acc042001-06-10 19:56:58 +00009098balance_cleanup:
drhb2a0f752017-08-28 15:51:35 +00009099 sqlite3StackFree(0, b.apCell);
drh8b2f49b2001-06-08 00:21:52 +00009100 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00009101 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00009102 }
drh14acc042001-06-10 19:56:58 +00009103 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00009104 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00009105 }
danielk1977eaa06f62008-09-18 17:34:44 +00009106
drh8b2f49b2001-06-08 00:21:52 +00009107 return rc;
9108}
9109
drh43605152004-05-29 21:46:49 +00009110
9111/*
danielk1977a50d9aa2009-06-08 14:49:45 +00009112** This function is called when the root page of a b-tree structure is
9113** overfull (has one or more overflow pages).
drh43605152004-05-29 21:46:49 +00009114**
danielk1977a50d9aa2009-06-08 14:49:45 +00009115** A new child page is allocated and the contents of the current root
9116** page, including overflow cells, are copied into the child. The root
9117** page is then overwritten to make it an empty page with the right-child
9118** pointer pointing to the new page.
9119**
9120** Before returning, all pointer-map entries corresponding to pages
9121** that the new child-page now contains pointers to are updated. The
9122** entry corresponding to the new right-child pointer of the root
9123** page is also updated.
9124**
9125** If successful, *ppChild is set to contain a reference to the child
9126** page and SQLITE_OK is returned. In this case the caller is required
9127** to call releasePage() on *ppChild exactly once. If an error occurs,
9128** an error code is returned and *ppChild is set to 0.
drh43605152004-05-29 21:46:49 +00009129*/
danielk1977a50d9aa2009-06-08 14:49:45 +00009130static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
9131 int rc; /* Return value from subprocedures */
9132 MemPage *pChild = 0; /* Pointer to a new child page */
shane5eff7cf2009-08-10 03:57:58 +00009133 Pgno pgnoChild = 0; /* Page number of the new child page */
danielk1977a50d9aa2009-06-08 14:49:45 +00009134 BtShared *pBt = pRoot->pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00009135
danielk1977a50d9aa2009-06-08 14:49:45 +00009136 assert( pRoot->nOverflow>0 );
drh1fee73e2007-08-29 04:00:57 +00009137 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bc2ca9e2008-11-13 14:28:28 +00009138
danielk1977a50d9aa2009-06-08 14:49:45 +00009139 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
9140 ** page that will become the new right-child of pPage. Copy the contents
9141 ** of the node stored on pRoot into the new child page.
9142 */
drh98add2e2009-07-20 17:11:49 +00009143 rc = sqlite3PagerWrite(pRoot->pDbPage);
9144 if( rc==SQLITE_OK ){
9145 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
drhc314dc72009-07-21 11:52:34 +00009146 copyNodeContent(pRoot, pChild, &rc);
dan7b3d71e2015-08-19 20:27:05 +00009147 if( REQUIRE_PTRMAP ){
drhc314dc72009-07-21 11:52:34 +00009148 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
drh98add2e2009-07-20 17:11:49 +00009149 }
9150 }
9151 if( rc ){
danielk1977a50d9aa2009-06-08 14:49:45 +00009152 *ppChild = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00009153 releasePage(pChild);
danielk1977a50d9aa2009-06-08 14:49:45 +00009154 return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00009155 }
danielk1977a50d9aa2009-06-08 14:49:45 +00009156 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
9157 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drh12fe9a02019-02-19 16:42:54 +00009158 assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
danielk197771d5d2c2008-09-29 11:49:47 +00009159
danielk1977a50d9aa2009-06-08 14:49:45 +00009160 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
9161
9162 /* Copy the overflow cells from pRoot to pChild */
drh2cbd78b2012-02-02 19:37:18 +00009163 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
9164 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
9165 memcpy(pChild->apOvfl, pRoot->apOvfl,
9166 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
danielk1977a50d9aa2009-06-08 14:49:45 +00009167 pChild->nOverflow = pRoot->nOverflow;
danielk1977a50d9aa2009-06-08 14:49:45 +00009168
9169 /* Zero the contents of pRoot. Then install pChild as the right-child. */
9170 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
9171 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
9172
9173 *ppChild = pChild;
9174 return SQLITE_OK;
drh43605152004-05-29 21:46:49 +00009175}
9176
9177/*
drha2d50282019-12-23 18:02:15 +00009178** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid
9179** on the same B-tree as pCur.
9180**
drh87463962021-10-05 22:51:26 +00009181** This can occur if a database is corrupt with two or more SQL tables
drha2d50282019-12-23 18:02:15 +00009182** pointing to the same b-tree. If an insert occurs on one SQL table
9183** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL
9184** table linked to the same b-tree. If the secondary insert causes a
9185** rebalance, that can change content out from under the cursor on the
9186** first SQL table, violating invariants on the first insert.
9187*/
9188static int anotherValidCursor(BtCursor *pCur){
9189 BtCursor *pOther;
9190 for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
9191 if( pOther!=pCur
9192 && pOther->eState==CURSOR_VALID
9193 && pOther->pPage==pCur->pPage
9194 ){
9195 return SQLITE_CORRUPT_BKPT;
9196 }
9197 }
9198 return SQLITE_OK;
9199}
9200
9201/*
danielk197771d5d2c2008-09-29 11:49:47 +00009202** The page that pCur currently points to has just been modified in
9203** some way. This function figures out if this modification means the
9204** tree needs to be balanced, and if so calls the appropriate balancing
danielk1977a50d9aa2009-06-08 14:49:45 +00009205** routine. Balancing routines are:
9206**
9207** balance_quick()
danielk1977a50d9aa2009-06-08 14:49:45 +00009208** balance_deeper()
9209** balance_nonroot()
drh43605152004-05-29 21:46:49 +00009210*/
danielk1977a50d9aa2009-06-08 14:49:45 +00009211static int balance(BtCursor *pCur){
drh43605152004-05-29 21:46:49 +00009212 int rc = SQLITE_OK;
danielk1977a50d9aa2009-06-08 14:49:45 +00009213 u8 aBalanceQuickSpace[13];
9214 u8 *pFree = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00009215
drhcc5f8a42016-02-06 22:32:06 +00009216 VVA_ONLY( int balance_quick_called = 0 );
9217 VVA_ONLY( int balance_deeper_called = 0 );
danielk1977a50d9aa2009-06-08 14:49:45 +00009218
9219 do {
dan01fd42b2019-07-13 09:55:33 +00009220 int iPage;
drh352a35a2017-08-15 03:46:47 +00009221 MemPage *pPage = pCur->pPage;
danielk1977a50d9aa2009-06-08 14:49:45 +00009222
drha941ff72019-02-12 00:58:10 +00009223 if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
drhc4c0ff82022-03-31 16:09:13 +00009224 if( pPage->nOverflow==0 && pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){
drhde948482022-03-29 13:16:32 +00009225 /* No rebalance required as long as:
9226 ** (1) There are no overflow cells
9227 ** (2) The amount of free space on the page is less than 2/3rds of
9228 ** the total usable space on the page. */
dan01fd42b2019-07-13 09:55:33 +00009229 break;
9230 }else if( (iPage = pCur->iPage)==0 ){
drha2d50282019-12-23 18:02:15 +00009231 if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
danielk1977a50d9aa2009-06-08 14:49:45 +00009232 /* The root page of the b-tree is overfull. In this case call the
9233 ** balance_deeper() function to create a new child for the root-page
9234 ** and copy the current contents of the root-page to it. The
9235 ** next iteration of the do-loop will balance the child page.
9236 */
drhcc5f8a42016-02-06 22:32:06 +00009237 assert( balance_deeper_called==0 );
9238 VVA_ONLY( balance_deeper_called++ );
danielk1977a50d9aa2009-06-08 14:49:45 +00009239 rc = balance_deeper(pPage, &pCur->apPage[1]);
9240 if( rc==SQLITE_OK ){
9241 pCur->iPage = 1;
drh75e96b32017-04-01 00:20:06 +00009242 pCur->ix = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00009243 pCur->aiIdx[0] = 0;
drh352a35a2017-08-15 03:46:47 +00009244 pCur->apPage[0] = pPage;
9245 pCur->pPage = pCur->apPage[1];
9246 assert( pCur->pPage->nOverflow );
danielk1977a50d9aa2009-06-08 14:49:45 +00009247 }
danielk1977a50d9aa2009-06-08 14:49:45 +00009248 }else{
danielk1977a50d9aa2009-06-08 14:49:45 +00009249 break;
9250 }
danad658b22022-09-30 20:15:21 +00009251 }else if( sqlite3PagerPageRefcount(pPage->pDbPage)>1 ){
9252 /* The page being written is not a root page, and there is currently
9253 ** more than one reference to it. This only happens if the page is one
9254 ** of its own ancestor pages. Corruption. */
9255 rc = SQLITE_CORRUPT_BKPT;
danielk1977a50d9aa2009-06-08 14:49:45 +00009256 }else{
9257 MemPage * const pParent = pCur->apPage[iPage-1];
9258 int const iIdx = pCur->aiIdx[iPage-1];
9259
9260 rc = sqlite3PagerWrite(pParent->pDbPage);
drh68133502019-02-11 17:22:30 +00009261 if( rc==SQLITE_OK && pParent->nFree<0 ){
9262 rc = btreeComputeFreeSpace(pParent);
9263 }
danielk1977a50d9aa2009-06-08 14:49:45 +00009264 if( rc==SQLITE_OK ){
9265#ifndef SQLITE_OMIT_QUICKBALANCE
drh3e28ff52014-09-24 00:59:08 +00009266 if( pPage->intKeyLeaf
danielk1977a50d9aa2009-06-08 14:49:45 +00009267 && pPage->nOverflow==1
drh2cbd78b2012-02-02 19:37:18 +00009268 && pPage->aiOvfl[0]==pPage->nCell
danielk1977a50d9aa2009-06-08 14:49:45 +00009269 && pParent->pgno!=1
9270 && pParent->nCell==iIdx
9271 ){
9272 /* Call balance_quick() to create a new sibling of pPage on which
9273 ** to store the overflow cell. balance_quick() inserts a new cell
9274 ** into pParent, which may cause pParent overflow. If this
peter.d.reid60ec9142014-09-06 16:39:46 +00009275 ** happens, the next iteration of the do-loop will balance pParent
danielk1977a50d9aa2009-06-08 14:49:45 +00009276 ** use either balance_nonroot() or balance_deeper(). Until this
9277 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
9278 ** buffer.
9279 **
9280 ** The purpose of the following assert() is to check that only a
9281 ** single call to balance_quick() is made for each call to this
9282 ** function. If this were not verified, a subtle bug involving reuse
9283 ** of the aBalanceQuickSpace[] might sneak in.
9284 */
drhcc5f8a42016-02-06 22:32:06 +00009285 assert( balance_quick_called==0 );
9286 VVA_ONLY( balance_quick_called++ );
danielk1977a50d9aa2009-06-08 14:49:45 +00009287 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
9288 }else
9289#endif
9290 {
9291 /* In this case, call balance_nonroot() to redistribute cells
9292 ** between pPage and up to 2 of its sibling pages. This involves
9293 ** modifying the contents of pParent, which may cause pParent to
9294 ** become overfull or underfull. The next iteration of the do-loop
9295 ** will balance the parent page to correct this.
9296 **
9297 ** If the parent page becomes overfull, the overflow cell or cells
9298 ** are stored in the pSpace buffer allocated immediately below.
9299 ** A subsequent iteration of the do-loop will deal with this by
9300 ** calling balance_nonroot() (balance_deeper() may be called first,
9301 ** but it doesn't deal with overflow cells - just moves them to a
9302 ** different page). Once this subsequent call to balance_nonroot()
9303 ** has completed, it is safe to release the pSpace buffer used by
9304 ** the previous call, as the overflow cell data will have been
9305 ** copied either into the body of a database page or into the new
9306 ** pSpace buffer passed to the latter call to balance_nonroot().
9307 */
9308 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
drhe0997b32015-03-20 14:57:50 +00009309 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
dan7fff2e12017-05-29 14:27:37 +00009310 pCur->hints&BTREE_BULKLOAD, pCur->pgnoRoot);
danielk1977a50d9aa2009-06-08 14:49:45 +00009311 if( pFree ){
9312 /* If pFree is not NULL, it points to the pSpace buffer used
9313 ** by a previous call to balance_nonroot(). Its contents are
9314 ** now stored either on real database pages or within the
9315 ** new pSpace buffer, so it may be safely freed here. */
9316 sqlite3PageFree(pFree);
9317 }
9318
danielk19774dbaa892009-06-16 16:50:22 +00009319 /* The pSpace buffer will be freed after the next call to
9320 ** balance_nonroot(), or just before this function returns, whichever
9321 ** comes first. */
danielk1977a50d9aa2009-06-08 14:49:45 +00009322 pFree = pSpace;
danielk1977a50d9aa2009-06-08 14:49:45 +00009323 }
9324 }
9325
9326 pPage->nOverflow = 0;
9327
9328 /* The next iteration of the do-loop balances the parent page. */
9329 releasePage(pPage);
9330 pCur->iPage--;
drhcbd33492015-03-25 13:06:54 +00009331 assert( pCur->iPage>=0 );
drh352a35a2017-08-15 03:46:47 +00009332 pCur->pPage = pCur->apPage[pCur->iPage];
drh43605152004-05-29 21:46:49 +00009333 }
danielk1977a50d9aa2009-06-08 14:49:45 +00009334 }while( rc==SQLITE_OK );
9335
9336 if( pFree ){
9337 sqlite3PageFree(pFree);
drh43605152004-05-29 21:46:49 +00009338 }
9339 return rc;
9340}
9341
drh3de5d162018-05-03 03:59:02 +00009342/* Overwrite content from pX into pDest. Only do the write if the
9343** content is different from what is already there.
9344*/
9345static int btreeOverwriteContent(
9346 MemPage *pPage, /* MemPage on which writing will occur */
9347 u8 *pDest, /* Pointer to the place to start writing */
9348 const BtreePayload *pX, /* Source of data to write */
9349 int iOffset, /* Offset of first byte to write */
9350 int iAmt /* Number of bytes to be written */
9351){
9352 int nData = pX->nData - iOffset;
9353 if( nData<=0 ){
9354 /* Overwritting with zeros */
9355 int i;
9356 for(i=0; i<iAmt && pDest[i]==0; i++){}
9357 if( i<iAmt ){
9358 int rc = sqlite3PagerWrite(pPage->pDbPage);
9359 if( rc ) return rc;
9360 memset(pDest + i, 0, iAmt - i);
9361 }
9362 }else{
9363 if( nData<iAmt ){
9364 /* Mixed read data and zeros at the end. Make a recursive call
9365 ** to write the zeros then fall through to write the real data */
drhd5aa9262018-05-03 16:56:06 +00009366 int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
9367 iAmt-nData);
9368 if( rc ) return rc;
drh3de5d162018-05-03 03:59:02 +00009369 iAmt = nData;
9370 }
9371 if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
9372 int rc = sqlite3PagerWrite(pPage->pDbPage);
9373 if( rc ) return rc;
drh55469bb2019-01-24 13:36:47 +00009374 /* In a corrupt database, it is possible for the source and destination
9375 ** buffers to overlap. This is harmless since the database is already
9376 ** corrupt but it does cause valgrind and ASAN warnings. So use
9377 ** memmove(). */
9378 memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
drh3de5d162018-05-03 03:59:02 +00009379 }
9380 }
9381 return SQLITE_OK;
9382}
9383
9384/*
9385** Overwrite the cell that cursor pCur is pointing to with fresh content
drh1eb88d62023-01-03 15:11:01 +00009386** contained in pX. In this variant, pCur is pointing to an overflow
9387** cell.
drh3de5d162018-05-03 03:59:02 +00009388*/
drh1eb88d62023-01-03 15:11:01 +00009389static SQLITE_NOINLINE int btreeOverwriteOverflowCell(
9390 BtCursor *pCur, /* Cursor pointing to cell to ovewrite */
9391 const BtreePayload *pX /* Content to write into the cell */
9392){
drh3de5d162018-05-03 03:59:02 +00009393 int iOffset; /* Next byte of pX->pData to write */
9394 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
9395 int rc; /* Return code */
9396 MemPage *pPage = pCur->pPage; /* Page being written */
9397 BtShared *pBt; /* Btree */
9398 Pgno ovflPgno; /* Next overflow page to write */
9399 u32 ovflPageSize; /* Size to write on overflow page */
9400
drh1eb88d62023-01-03 15:11:01 +00009401 assert( pCur->info.nLocal<nTotal ); /* pCur is an overflow cell */
9402
drh3de5d162018-05-03 03:59:02 +00009403 /* Overwrite the local portion first */
9404 rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
9405 0, pCur->info.nLocal);
9406 if( rc ) return rc;
drh3de5d162018-05-03 03:59:02 +00009407
9408 /* Now overwrite the overflow pages */
9409 iOffset = pCur->info.nLocal;
drh30f7a252018-05-07 11:29:59 +00009410 assert( nTotal>=0 );
9411 assert( iOffset>=0 );
drh3de5d162018-05-03 03:59:02 +00009412 ovflPgno = get4byte(pCur->info.pPayload + iOffset);
9413 pBt = pPage->pBt;
9414 ovflPageSize = pBt->usableSize - 4;
9415 do{
9416 rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
9417 if( rc ) return rc;
drh7f581172021-09-10 01:02:42 +00009418 if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 || pPage->isInit ){
drhd5aa9262018-05-03 16:56:06 +00009419 rc = SQLITE_CORRUPT_BKPT;
drh3de5d162018-05-03 03:59:02 +00009420 }else{
drh30f7a252018-05-07 11:29:59 +00009421 if( iOffset+ovflPageSize<(u32)nTotal ){
drhd5aa9262018-05-03 16:56:06 +00009422 ovflPgno = get4byte(pPage->aData);
9423 }else{
9424 ovflPageSize = nTotal - iOffset;
9425 }
9426 rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
9427 iOffset, ovflPageSize);
drh3de5d162018-05-03 03:59:02 +00009428 }
drhd5aa9262018-05-03 16:56:06 +00009429 sqlite3PagerUnref(pPage->pDbPage);
drh3de5d162018-05-03 03:59:02 +00009430 if( rc ) return rc;
9431 iOffset += ovflPageSize;
drh3de5d162018-05-03 03:59:02 +00009432 }while( iOffset<nTotal );
9433 return SQLITE_OK;
9434}
9435
drh1eb88d62023-01-03 15:11:01 +00009436/*
9437** Overwrite the cell that cursor pCur is pointing to with fresh content
9438** contained in pX.
9439*/
9440static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
9441 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
9442 MemPage *pPage = pCur->pPage; /* Page being written */
9443
9444 if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd
9445 || pCur->info.pPayload < pPage->aData + pPage->cellOffset
9446 ){
9447 return SQLITE_CORRUPT_BKPT;
9448 }
9449 if( pCur->info.nLocal==nTotal ){
9450 /* The entire cell is local */
9451 return btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
9452 0, pCur->info.nLocal);
9453 }else{
9454 /* The cell contains overflow content */
9455 return btreeOverwriteOverflowCell(pCur, pX);
9456 }
9457}
9458
drhf74b8d92002-09-01 23:20:45 +00009459
9460/*
drh8eeb4462016-05-21 20:03:42 +00009461** Insert a new record into the BTree. The content of the new record
9462** is described by the pX object. The pCur cursor is used only to
9463** define what table the record should be inserted into, and is left
9464** pointing at a random location.
drh4b70f112004-05-02 21:12:19 +00009465**
drh8eeb4462016-05-21 20:03:42 +00009466** For a table btree (used for rowid tables), only the pX.nKey value of
9467** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
9468** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
9469** hold the content of the row.
9470**
9471** For an index btree (used for indexes and WITHOUT ROWID tables), the
9472** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
9473** pX.pData,nData,nZero fields must be zero.
danielk1977de630352009-05-04 11:42:29 +00009474**
9475** If the seekResult parameter is non-zero, then a successful call to
drheab10642022-03-06 20:22:24 +00009476** sqlite3BtreeIndexMoveto() to seek cursor pCur to (pKey,nKey) has already
drheaf6ae22016-11-09 20:14:34 +00009477** been performed. In other words, if seekResult!=0 then the cursor
9478** is currently pointing to a cell that will be adjacent to the cell
9479** to be inserted. If seekResult<0 then pCur points to a cell that is
9480** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
9481** that is larger than (pKey,nKey).
danielk1977de630352009-05-04 11:42:29 +00009482**
drheaf6ae22016-11-09 20:14:34 +00009483** If seekResult==0, that means pCur is pointing at some unknown location.
9484** In that case, this routine must seek the cursor to the correct insertion
9485** point for (pKey,nKey) before doing the insertion. For index btrees,
9486** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
9487** key values and pX->aMem can be used instead of pX->pKey to avoid having
9488** to decode the key.
drh3b7511c2001-05-26 13:15:44 +00009489*/
drh3aac2dd2004-04-26 14:10:20 +00009490int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00009491 BtCursor *pCur, /* Insert data into the table of this cursor */
drh8eeb4462016-05-21 20:03:42 +00009492 const BtreePayload *pX, /* Content of the row to be inserted */
danf91c1312017-01-10 20:04:38 +00009493 int flags, /* True if this is likely an append */
drheab10642022-03-06 20:22:24 +00009494 int seekResult /* Result of prior IndexMoveto() call */
drh3b7511c2001-05-26 13:15:44 +00009495){
drh3b7511c2001-05-26 13:15:44 +00009496 int rc;
drh3e9ca092009-09-08 01:14:48 +00009497 int loc = seekResult; /* -1: before desired location +1: after */
drh1d452e12009-11-01 19:26:59 +00009498 int szNew = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00009499 int idx;
drh3b7511c2001-05-26 13:15:44 +00009500 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00009501 Btree *p = pCur->pBtree;
drha34b6762004-05-07 13:30:42 +00009502 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00009503 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00009504
dancd1b2d02020-12-09 20:33:51 +00009505 assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND|BTREE_PREFORMAT))==flags );
dan7aae7352020-12-10 18:06:24 +00009506 assert( (flags & BTREE_PREFORMAT)==0 || seekResult || pCur->pKeyInfo==0 );
danf91c1312017-01-10 20:04:38 +00009507
danielk19779c3acf32009-05-02 07:36:49 +00009508 /* Save the positions of any other cursors open on this table.
9509 **
danielk19773509a652009-07-06 18:56:13 +00009510 ** In some cases, the call to btreeMoveto() below is a no-op. For
danielk19779c3acf32009-05-02 07:36:49 +00009511 ** example, when inserting data into a table with auto-generated integer
9512 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
9513 ** integer key to use. It then calls this function to actually insert the
danielk19773509a652009-07-06 18:56:13 +00009514 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
danielk19779c3acf32009-05-02 07:36:49 +00009515 ** that the cursor is already where it needs to be and returns without
9516 ** doing any work. To avoid thwarting these optimizations, it is important
9517 ** not to clear the cursor here.
9518 */
drh27fb7462015-06-30 02:47:36 +00009519 if( pCur->curFlags & BTCF_Multiple ){
drhe7d53842022-11-21 14:13:10 +00009520 rc = saveAllCursors(p->pBt, pCur->pgnoRoot, pCur);
drh27fb7462015-06-30 02:47:36 +00009521 if( rc ) return rc;
danf5ea93b2021-04-08 19:39:00 +00009522 if( loc && pCur->iPage<0 ){
9523 /* This can only happen if the schema is corrupt such that there is more
9524 ** than one table or index with the same root page as used by the cursor.
9525 ** Which can only happen if the SQLITE_NoSchemaError flag was set when
9526 ** the schema was loaded. This cannot be asserted though, as a user might
9527 ** set the flag, load the schema, and then unset the flag. */
9528 return SQLITE_CORRUPT_BKPT;
9529 }
drh27fb7462015-06-30 02:47:36 +00009530 }
drhd60f4f42012-03-23 14:23:52 +00009531
drhc63e4092022-03-21 18:48:31 +00009532 /* Ensure that the cursor is not in the CURSOR_FAULT state and that it
9533 ** points to a valid cell.
9534 */
drhbd5fb3a2022-03-21 18:17:09 +00009535 if( pCur->eState>=CURSOR_REQUIRESEEK ){
drhc63e4092022-03-21 18:48:31 +00009536 testcase( pCur->eState==CURSOR_REQUIRESEEK );
9537 testcase( pCur->eState==CURSOR_FAULT );
drhbd5fb3a2022-03-21 18:17:09 +00009538 rc = moveToRoot(pCur);
9539 if( rc && rc!=SQLITE_EMPTY ) return rc;
9540 }
9541
9542 assert( cursorOwnsBtShared(pCur) );
9543 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
drhe7d53842022-11-21 14:13:10 +00009544 && p->pBt->inTransaction==TRANS_WRITE
9545 && (p->pBt->btsFlags & BTS_READ_ONLY)==0 );
drhbd5fb3a2022-03-21 18:17:09 +00009546 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
9547
9548 /* Assert that the caller has been consistent. If this cursor was opened
9549 ** expecting an index b-tree, then the caller should be inserting blob
9550 ** keys with no associated data. If the cursor was opened expecting an
9551 ** intkey table, the caller should be inserting integer keys with a
9552 ** blob of associated data. */
9553 assert( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) );
9554
drhd60f4f42012-03-23 14:23:52 +00009555 if( pCur->pKeyInfo==0 ){
drh8eeb4462016-05-21 20:03:42 +00009556 assert( pX->pKey==0 );
drhe0670b62014-02-12 21:31:12 +00009557 /* If this is an insert into a table b-tree, invalidate any incrblob
9558 ** cursors open on the row being replaced */
drh49bb56e2021-05-14 20:01:36 +00009559 if( p->hasIncrblobCur ){
9560 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
9561 }
drhe0670b62014-02-12 21:31:12 +00009562
danf91c1312017-01-10 20:04:38 +00009563 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
drhd720d392018-05-07 17:27:04 +00009564 ** to a row with the same key as the new entry being inserted.
9565 */
9566#ifdef SQLITE_DEBUG
9567 if( flags & BTREE_SAVEPOSITION ){
9568 assert( pCur->curFlags & BTCF_ValidNKey );
9569 assert( pX->nKey==pCur->info.nKey );
drhd720d392018-05-07 17:27:04 +00009570 assert( loc==0 );
9571 }
9572#endif
danf91c1312017-01-10 20:04:38 +00009573
drhd720d392018-05-07 17:27:04 +00009574 /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
9575 ** that the cursor is not pointing to a row to be overwritten.
9576 ** So do a complete check.
9577 */
drh7a1c28d2016-11-10 20:42:08 +00009578 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
drhd720d392018-05-07 17:27:04 +00009579 /* The cursor is pointing to the entry that is to be
drh3de5d162018-05-03 03:59:02 +00009580 ** overwritten */
drh30f7a252018-05-07 11:29:59 +00009581 assert( pX->nData>=0 && pX->nZero>=0 );
9582 if( pCur->info.nSize!=0
9583 && pCur->info.nPayload==(u32)pX->nData+pX->nZero
9584 ){
drhd720d392018-05-07 17:27:04 +00009585 /* New entry is the same size as the old. Do an overwrite */
drh3de5d162018-05-03 03:59:02 +00009586 return btreeOverwriteCell(pCur, pX);
9587 }
drhd720d392018-05-07 17:27:04 +00009588 assert( loc==0 );
drh207c8172015-06-29 23:01:32 +00009589 }else if( loc==0 ){
drhd720d392018-05-07 17:27:04 +00009590 /* The cursor is *not* pointing to the cell to be overwritten, nor
9591 ** to an adjacent cell. Move the cursor so that it is pointing either
9592 ** to the cell to be overwritten or an adjacent cell.
9593 */
drh42a410d2021-06-19 18:32:20 +00009594 rc = sqlite3BtreeTableMoveto(pCur, pX->nKey,
9595 (flags & BTREE_APPEND)!=0, &loc);
drh207c8172015-06-29 23:01:32 +00009596 if( rc ) return rc;
drhe0670b62014-02-12 21:31:12 +00009597 }
drhd720d392018-05-07 17:27:04 +00009598 }else{
9599 /* This is an index or a WITHOUT ROWID table */
9600
9601 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
9602 ** to a row with the same key as the new entry being inserted.
9603 */
9604 assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
9605
9606 /* If the cursor is not already pointing either to the cell to be
9607 ** overwritten, or if a new cell is being inserted, if the cursor is
9608 ** not pointing to an immediately adjacent cell, then move the cursor
9609 ** so that it does.
9610 */
9611 if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
9612 if( pX->nMem ){
9613 UnpackedRecord r;
9614 r.pKeyInfo = pCur->pKeyInfo;
9615 r.aMem = pX->aMem;
9616 r.nField = pX->nMem;
9617 r.default_rc = 0;
drhd720d392018-05-07 17:27:04 +00009618 r.eqSeen = 0;
drh42a410d2021-06-19 18:32:20 +00009619 rc = sqlite3BtreeIndexMoveto(pCur, &r, &loc);
drhd720d392018-05-07 17:27:04 +00009620 }else{
drh42a410d2021-06-19 18:32:20 +00009621 rc = btreeMoveto(pCur, pX->pKey, pX->nKey,
9622 (flags & BTREE_APPEND)!=0, &loc);
drhd720d392018-05-07 17:27:04 +00009623 }
9624 if( rc ) return rc;
drh9b4eaeb2016-11-09 00:10:33 +00009625 }
drh89ee2292018-05-07 18:41:19 +00009626
9627 /* If the cursor is currently pointing to an entry to be overwritten
9628 ** and the new content is the same as as the old, then use the
9629 ** overwrite optimization.
9630 */
9631 if( loc==0 ){
9632 getCellInfo(pCur);
9633 if( pCur->info.nKey==pX->nKey ){
9634 BtreePayload x2;
9635 x2.pData = pX->pKey;
9636 x2.nData = pX->nKey;
9637 x2.nZero = 0;
9638 return btreeOverwriteCell(pCur, &x2);
9639 }
9640 }
danielk1977da184232006-01-05 11:34:32 +00009641 }
drh0e5ce802019-12-20 12:33:17 +00009642 assert( pCur->eState==CURSOR_VALID
drhbd5fb3a2022-03-21 18:17:09 +00009643 || (pCur->eState==CURSOR_INVALID && loc) );
danielk1977da184232006-01-05 11:34:32 +00009644
drh352a35a2017-08-15 03:46:47 +00009645 pPage = pCur->pPage;
dancd1b2d02020-12-09 20:33:51 +00009646 assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
drh44845222008-07-17 18:39:57 +00009647 assert( pPage->leaf || !pPage->intKey );
drhb0ea9432019-02-09 21:06:40 +00009648 if( pPage->nFree<0 ){
drhc63e4092022-03-21 18:48:31 +00009649 if( NEVER(pCur->eState>CURSOR_INVALID) ){
9650 /* ^^^^^--- due to the moveToRoot() call above */
drha1085f02020-07-11 16:42:28 +00009651 rc = SQLITE_CORRUPT_BKPT;
9652 }else{
9653 rc = btreeComputeFreeSpace(pPage);
9654 }
drhb0ea9432019-02-09 21:06:40 +00009655 if( rc ) return rc;
9656 }
danielk19778f880a82009-07-13 09:41:45 +00009657
drh3a4c1412004-05-09 20:40:11 +00009658 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
drh8eeb4462016-05-21 20:03:42 +00009659 pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
drh3a4c1412004-05-09 20:40:11 +00009660 loc==0 ? "overwrite" : "new entry"));
drhf51672a2022-05-31 15:18:55 +00009661 assert( pPage->isInit || CORRUPT_DB );
drhe7d53842022-11-21 14:13:10 +00009662 newCell = p->pBt->pTmpSpace;
drh3fbb0222014-09-24 19:47:27 +00009663 assert( newCell!=0 );
drhecba1072022-11-19 20:10:55 +00009664 assert( BTREE_PREFORMAT==OPFLAG_PREFORMAT );
dancd1b2d02020-12-09 20:33:51 +00009665 if( flags & BTREE_PREFORMAT ){
dancd1b2d02020-12-09 20:33:51 +00009666 rc = SQLITE_OK;
drhe7d53842022-11-21 14:13:10 +00009667 szNew = p->pBt->nPreformatSize;
dan7aae7352020-12-10 18:06:24 +00009668 if( szNew<4 ) szNew = 4;
drhe7d53842022-11-21 14:13:10 +00009669 if( ISAUTOVACUUM(p->pBt) && szNew>pPage->maxLocal ){
dan7aae7352020-12-10 18:06:24 +00009670 CellInfo info;
9671 pPage->xParseCell(pPage, newCell, &info);
dan9257ddb2020-12-10 19:54:13 +00009672 if( info.nPayload!=info.nLocal ){
dan7aae7352020-12-10 18:06:24 +00009673 Pgno ovfl = get4byte(&newCell[szNew-4]);
drhe7d53842022-11-21 14:13:10 +00009674 ptrmapPut(p->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, &rc);
drh5a1d6592022-11-19 19:37:26 +00009675 if( NEVER(rc) ) goto end_insert;
dan7aae7352020-12-10 18:06:24 +00009676 }
9677 }
dancd1b2d02020-12-09 20:33:51 +00009678 }else{
9679 rc = fillInCell(pPage, newCell, pX, &szNew);
drh5a1d6592022-11-19 19:37:26 +00009680 if( rc ) goto end_insert;
dancd1b2d02020-12-09 20:33:51 +00009681 }
drh25ada072015-06-19 15:07:14 +00009682 assert( szNew==pPage->xCellSize(pPage, newCell) );
drhe7d53842022-11-21 14:13:10 +00009683 assert( szNew <= MX_CELL_SIZE(p->pBt) );
drh75e96b32017-04-01 00:20:06 +00009684 idx = pCur->ix;
danielk1977b980d2212009-06-22 18:03:51 +00009685 if( loc==0 ){
drh80159da2016-12-09 17:32:51 +00009686 CellInfo info;
drh43fa1a52022-12-21 20:07:58 +00009687 BtShared *pBt = p->pBt;
drh635480e2021-10-08 16:15:17 +00009688 assert( idx>=0 );
9689 if( idx>=pPage->nCell ){
9690 return SQLITE_CORRUPT_BKPT;
9691 }
danielk19776e465eb2007-08-21 13:11:00 +00009692 rc = sqlite3PagerWrite(pPage->pDbPage);
9693 if( rc ){
9694 goto end_insert;
9695 }
danielk197771d5d2c2008-09-29 11:49:47 +00009696 oldCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00009697 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00009698 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00009699 }
drh86c779f2021-05-15 13:08:44 +00009700 BTREE_CLEAR_CELL(rc, pPage, oldCell, info);
drh554a19d2019-08-12 18:26:46 +00009701 testcase( pCur->curFlags & BTCF_ValidOvfl );
9702 invalidateOverflowCache(pCur);
drh50179f92017-06-08 11:26:13 +00009703 if( info.nSize==szNew && info.nLocal==info.nPayload
dan4956bd52017-06-08 16:23:55 +00009704 && (!REQUIRE_PTRMAP || szNew<pPage->minLocal)
drh50179f92017-06-08 11:26:13 +00009705 ){
drhf9238252016-12-09 18:09:42 +00009706 /* Overwrite the old cell with the new if they are the same size.
9707 ** We could also try to do this if the old cell is smaller, then add
9708 ** the leftover space to the free list. But experiments show that
9709 ** doing that is no faster then skipping this optimization and just
drh50179f92017-06-08 11:26:13 +00009710 ** calling dropCell() and insertCell().
9711 **
9712 ** This optimization cannot be used on an autovacuum database if the
9713 ** new entry uses overflow pages, as the insertCell() call below is
9714 ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
drhf9238252016-12-09 18:09:42 +00009715 assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
drh93788182019-07-22 23:24:01 +00009716 if( oldCell < pPage->aData+pPage->hdrOffset+10 ){
9717 return SQLITE_CORRUPT_BKPT;
9718 }
9719 if( oldCell+szNew > pPage->aDataEnd ){
9720 return SQLITE_CORRUPT_BKPT;
9721 }
drh80159da2016-12-09 17:32:51 +00009722 memcpy(oldCell, newCell, szNew);
9723 return SQLITE_OK;
9724 }
9725 dropCell(pPage, idx, info.nSize, &rc);
drh2e38c322004-09-03 18:38:44 +00009726 if( rc ) goto end_insert;
drh7c717f72001-06-24 20:39:41 +00009727 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00009728 assert( pPage->leaf );
drh75e96b32017-04-01 00:20:06 +00009729 idx = ++pCur->ix;
dan874080b2017-05-01 18:12:56 +00009730 pCur->curFlags &= ~BTCF_ValidNKey;
drh14acc042001-06-10 19:56:58 +00009731 }else{
drh4b70f112004-05-02 21:12:19 +00009732 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00009733 }
drhb53d8fa2022-11-21 15:55:57 +00009734 rc = insertCell(pPage, idx, newCell, szNew, 0, 0);
drh09a4e922016-05-21 12:29:04 +00009735 assert( pPage->nOverflow==0 || rc==SQLITE_OK );
danielk19773f632d52009-05-02 10:03:09 +00009736 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
drh9bf9e9c2008-12-05 20:01:43 +00009737
mistachkin48864df2013-03-21 21:20:32 +00009738 /* If no error has occurred and pPage has an overflow cell, call balance()
danielk1977a50d9aa2009-06-08 14:49:45 +00009739 ** to redistribute the cells within the tree. Since balance() may move
drh036dbec2014-03-11 23:40:44 +00009740 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
danielk1977a50d9aa2009-06-08 14:49:45 +00009741 ** variables.
danielk19773f632d52009-05-02 10:03:09 +00009742 **
danielk1977a50d9aa2009-06-08 14:49:45 +00009743 ** Previous versions of SQLite called moveToRoot() to move the cursor
9744 ** back to the root page as balance() used to invalidate the contents
danielk197754109bb2009-06-23 11:22:29 +00009745 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
9746 ** set the cursor state to "invalid". This makes common insert operations
9747 ** slightly faster.
danielk19773f632d52009-05-02 10:03:09 +00009748 **
danielk1977a50d9aa2009-06-08 14:49:45 +00009749 ** There is a subtle but important optimization here too. When inserting
9750 ** multiple records into an intkey b-tree using a single cursor (as can
9751 ** happen while processing an "INSERT INTO ... SELECT" statement), it
9752 ** is advantageous to leave the cursor pointing to the last entry in
9753 ** the b-tree if possible. If the cursor is left pointing to the last
9754 ** entry in the table, and the next row inserted has an integer key
9755 ** larger than the largest existing key, it is possible to insert the
9756 ** row without seeking the cursor. This can be a big performance boost.
danielk19773f632d52009-05-02 10:03:09 +00009757 */
danielk1977a50d9aa2009-06-08 14:49:45 +00009758 pCur->info.nSize = 0;
drh09a4e922016-05-21 12:29:04 +00009759 if( pPage->nOverflow ){
9760 assert( rc==SQLITE_OK );
drh036dbec2014-03-11 23:40:44 +00009761 pCur->curFlags &= ~(BTCF_ValidNKey);
danielk1977a50d9aa2009-06-08 14:49:45 +00009762 rc = balance(pCur);
9763
9764 /* Must make sure nOverflow is reset to zero even if the balance()
danielk197754109bb2009-06-23 11:22:29 +00009765 ** fails. Internal data structure corruption will result otherwise.
9766 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
9767 ** from trying to save the current position of the cursor. */
drh352a35a2017-08-15 03:46:47 +00009768 pCur->pPage->nOverflow = 0;
danielk197754109bb2009-06-23 11:22:29 +00009769 pCur->eState = CURSOR_INVALID;
danf91c1312017-01-10 20:04:38 +00009770 if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
drh85ef6302017-08-02 15:50:09 +00009771 btreeReleaseAllCursorPages(pCur);
drh7b20a152017-01-12 19:10:55 +00009772 if( pCur->pKeyInfo ){
danf91c1312017-01-10 20:04:38 +00009773 assert( pCur->pKey==0 );
9774 pCur->pKey = sqlite3Malloc( pX->nKey );
9775 if( pCur->pKey==0 ){
9776 rc = SQLITE_NOMEM;
9777 }else{
9778 memcpy(pCur->pKey, pX->pKey, pX->nKey);
9779 }
9780 }
9781 pCur->eState = CURSOR_REQUIRESEEK;
9782 pCur->nKey = pX->nKey;
9783 }
danielk19773f632d52009-05-02 10:03:09 +00009784 }
drh352a35a2017-08-15 03:46:47 +00009785 assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
drh9bf9e9c2008-12-05 20:01:43 +00009786
drh2e38c322004-09-03 18:38:44 +00009787end_insert:
drh5e2f8b92001-05-28 00:41:15 +00009788 return rc;
9789}
9790
9791/*
dand2ffc972020-12-10 19:20:15 +00009792** This function is used as part of copying the current row from cursor
9793** pSrc into cursor pDest. If the cursors are open on intkey tables, then
9794** parameter iKey is used as the rowid value when the record is copied
9795** into pDest. Otherwise, the record is copied verbatim.
9796**
9797** This function does not actually write the new value to cursor pDest.
9798** Instead, it creates and populates any required overflow pages and
9799** writes the data for the new cell into the BtShared.pTmpSpace buffer
9800** for the destination database. The size of the cell, in bytes, is left
9801** in BtShared.nPreformatSize. The caller completes the insertion by
9802** calling sqlite3BtreeInsert() with the BTREE_PREFORMAT flag specified.
9803**
9804** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
9805*/
dan7aae7352020-12-10 18:06:24 +00009806int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 iKey){
dan7aae7352020-12-10 18:06:24 +00009807 BtShared *pBt = pDest->pBt;
9808 u8 *aOut = pBt->pTmpSpace; /* Pointer to next output buffer */
danebbf3682020-12-09 16:32:11 +00009809 const u8 *aIn; /* Pointer to next input buffer */
drhe5baf5c2020-12-16 14:20:45 +00009810 u32 nIn; /* Size of input buffer aIn[] */
dan7f607062020-12-15 19:27:20 +00009811 u32 nRem; /* Bytes of data still to copy */
dan036e0672020-12-08 20:19:07 +00009812
dan036e0672020-12-08 20:19:07 +00009813 getCellInfo(pSrc);
drhb47b1f62022-04-01 21:01:37 +00009814 if( pSrc->info.nPayload<0x80 ){
9815 *(aOut++) = pSrc->info.nPayload;
9816 }else{
9817 aOut += sqlite3PutVarint(aOut, pSrc->info.nPayload);
9818 }
dan7aae7352020-12-10 18:06:24 +00009819 if( pDest->pKeyInfo==0 ) aOut += putVarint(aOut, iKey);
danebbf3682020-12-09 16:32:11 +00009820 nIn = pSrc->info.nLocal;
9821 aIn = pSrc->info.pPayload;
drh0a8b6a92020-12-16 21:09:45 +00009822 if( aIn+nIn>pSrc->pPage->aDataEnd ){
9823 return SQLITE_CORRUPT_BKPT;
9824 }
danebbf3682020-12-09 16:32:11 +00009825 nRem = pSrc->info.nPayload;
dan7aae7352020-12-10 18:06:24 +00009826 if( nIn==nRem && nIn<pDest->pPage->maxLocal ){
9827 memcpy(aOut, aIn, nIn);
9828 pBt->nPreformatSize = nIn + (aOut - pBt->pTmpSpace);
drhd01dee52022-11-21 13:35:00 +00009829 return SQLITE_OK;
dan7aae7352020-12-10 18:06:24 +00009830 }else{
drhd01dee52022-11-21 13:35:00 +00009831 int rc = SQLITE_OK;
dan7aae7352020-12-10 18:06:24 +00009832 Pager *pSrcPager = pSrc->pBt->pPager;
9833 u8 *pPgnoOut = 0;
9834 Pgno ovflIn = 0;
9835 DbPage *pPageIn = 0;
9836 MemPage *pPageOut = 0;
drhe5baf5c2020-12-16 14:20:45 +00009837 u32 nOut; /* Size of output buffer aOut[] */
danebbf3682020-12-09 16:32:11 +00009838
dan7aae7352020-12-10 18:06:24 +00009839 nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload);
9840 pBt->nPreformatSize = nOut + (aOut - pBt->pTmpSpace);
9841 if( nOut<pSrc->info.nPayload ){
9842 pPgnoOut = &aOut[nOut];
9843 pBt->nPreformatSize += 4;
9844 }
9845
9846 if( nRem>nIn ){
drh0a8b6a92020-12-16 21:09:45 +00009847 if( aIn+nIn+4>pSrc->pPage->aDataEnd ){
9848 return SQLITE_CORRUPT_BKPT;
9849 }
dan7aae7352020-12-10 18:06:24 +00009850 ovflIn = get4byte(&pSrc->info.pPayload[nIn]);
9851 }
9852
9853 do {
9854 nRem -= nOut;
9855 do{
9856 assert( nOut>0 );
9857 if( nIn>0 ){
9858 int nCopy = MIN(nOut, nIn);
9859 memcpy(aOut, aIn, nCopy);
9860 nOut -= nCopy;
9861 nIn -= nCopy;
9862 aOut += nCopy;
9863 aIn += nCopy;
9864 }
9865 if( nOut>0 ){
9866 sqlite3PagerUnref(pPageIn);
9867 pPageIn = 0;
9868 rc = sqlite3PagerGet(pSrcPager, ovflIn, &pPageIn, PAGER_GET_READONLY);
9869 if( rc==SQLITE_OK ){
9870 aIn = (const u8*)sqlite3PagerGetData(pPageIn);
9871 ovflIn = get4byte(aIn);
9872 aIn += 4;
9873 nIn = pSrc->pBt->usableSize - 4;
9874 }
9875 }
9876 }while( rc==SQLITE_OK && nOut>0 );
9877
drhad1188b2021-10-02 18:22:24 +00009878 if( rc==SQLITE_OK && nRem>0 && ALWAYS(pPgnoOut) ){
dan7aae7352020-12-10 18:06:24 +00009879 Pgno pgnoNew;
9880 MemPage *pNew = 0;
9881 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
9882 put4byte(pPgnoOut, pgnoNew);
drhe7d53842022-11-21 14:13:10 +00009883 if( ISAUTOVACUUM(pBt) && pPageOut ){
dan7aae7352020-12-10 18:06:24 +00009884 ptrmapPut(pBt, pgnoNew, PTRMAP_OVERFLOW2, pPageOut->pgno, &rc);
9885 }
9886 releasePage(pPageOut);
9887 pPageOut = pNew;
9888 if( pPageOut ){
9889 pPgnoOut = pPageOut->aData;
9890 put4byte(pPgnoOut, 0);
9891 aOut = &pPgnoOut[4];
9892 nOut = MIN(pBt->usableSize - 4, nRem);
danebbf3682020-12-09 16:32:11 +00009893 }
9894 }
dan7aae7352020-12-10 18:06:24 +00009895 }while( nRem>0 && rc==SQLITE_OK );
9896
9897 releasePage(pPageOut);
9898 sqlite3PagerUnref(pPageIn);
drhd01dee52022-11-21 13:35:00 +00009899 return rc;
dan036e0672020-12-08 20:19:07 +00009900 }
dan036e0672020-12-08 20:19:07 +00009901}
9902
drh5e2f8b92001-05-28 00:41:15 +00009903/*
danf0ee1d32015-09-12 19:26:11 +00009904** Delete the entry that the cursor is pointing to.
9905**
drhe807bdb2016-01-21 17:06:33 +00009906** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
9907** the cursor is left pointing at an arbitrary location after the delete.
9908** But if that bit is set, then the cursor is left in a state such that
9909** the next call to BtreeNext() or BtreePrev() moves it to the same row
9910** as it would have been on if the call to BtreeDelete() had been omitted.
9911**
drhdef19e32016-01-27 16:26:25 +00009912** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
9913** associated with a single table entry and its indexes. Only one of those
9914** deletes is considered the "primary" delete. The primary delete occurs
9915** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
9916** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
9917** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
drhe807bdb2016-01-21 17:06:33 +00009918** but which might be used by alternative storage engines.
drh3b7511c2001-05-26 13:15:44 +00009919*/
drhe807bdb2016-01-21 17:06:33 +00009920int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
drhd677b3d2007-08-20 22:48:41 +00009921 Btree *p = pCur->pBtree;
danielk19774dbaa892009-06-16 16:50:22 +00009922 BtShared *pBt = p->pBt;
drh7e17a3a2022-01-02 14:55:43 +00009923 int rc; /* Return code */
9924 MemPage *pPage; /* Page to delete cell from */
9925 unsigned char *pCell; /* Pointer to cell to delete */
9926 int iCellIdx; /* Index of cell to delete */
9927 int iCellDepth; /* Depth of node containing pCell */
9928 CellInfo info; /* Size of the cell being deleted */
9929 u8 bPreserve; /* Keep cursor valid. 2 for CURSOR_SKIPNEXT */
drh8b2f49b2001-06-08 00:21:52 +00009930
dan7a2347e2016-01-07 16:43:54 +00009931 assert( cursorOwnsBtShared(pCur) );
drh64022502009-01-09 14:11:04 +00009932 assert( pBt->inTransaction==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00009933 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
drh036dbec2014-03-11 23:40:44 +00009934 assert( pCur->curFlags & BTCF_WriteFlag );
danielk197796d48e92009-06-29 06:00:37 +00009935 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
9936 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
drhdef19e32016-01-27 16:26:25 +00009937 assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
drh500d7e52022-03-22 23:33:20 +00009938 if( pCur->eState!=CURSOR_VALID ){
9939 if( pCur->eState>=CURSOR_REQUIRESEEK ){
9940 rc = btreeRestoreCursorPosition(pCur);
9941 assert( rc!=SQLITE_OK || CORRUPT_DB || pCur->eState==CURSOR_VALID );
9942 if( rc || pCur->eState!=CURSOR_VALID ) return rc;
9943 }else{
9944 return SQLITE_CORRUPT_BKPT;
9945 }
danb560a712019-03-13 15:29:14 +00009946 }
drh500d7e52022-03-22 23:33:20 +00009947 assert( pCur->eState==CURSOR_VALID );
danielk1977da184232006-01-05 11:34:32 +00009948
danielk19774dbaa892009-06-16 16:50:22 +00009949 iCellDepth = pCur->iPage;
drh75e96b32017-04-01 00:20:06 +00009950 iCellIdx = pCur->ix;
drh352a35a2017-08-15 03:46:47 +00009951 pPage = pCur->pPage;
drh7e17a3a2022-01-02 14:55:43 +00009952 if( pPage->nCell<=iCellIdx ){
9953 return SQLITE_CORRUPT_BKPT;
9954 }
danielk19774dbaa892009-06-16 16:50:22 +00009955 pCell = findCell(pPage, iCellIdx);
drh2dfe9662022-01-02 11:25:51 +00009956 if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ){
9957 return SQLITE_CORRUPT_BKPT;
9958 }
danielk19774dbaa892009-06-16 16:50:22 +00009959
drh7e17a3a2022-01-02 14:55:43 +00009960 /* If the BTREE_SAVEPOSITION bit is on, then the cursor position must
drhbfc7a8b2016-04-09 17:04:05 +00009961 ** be preserved following this delete operation. If the current delete
9962 ** will cause a b-tree rebalance, then this is done by saving the cursor
9963 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
9964 ** returning.
9965 **
drh7e17a3a2022-01-02 14:55:43 +00009966 ** If the current delete will not cause a rebalance, then the cursor
drhbfc7a8b2016-04-09 17:04:05 +00009967 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
drh7e17a3a2022-01-02 14:55:43 +00009968 ** before or after the deleted entry.
9969 **
9970 ** The bPreserve value records which path is required:
9971 **
9972 ** bPreserve==0 Not necessary to save the cursor position
9973 ** bPreserve==1 Use CURSOR_REQUIRESEEK to save the cursor position
9974 ** bPreserve==2 Cursor won't move. Set CURSOR_SKIPNEXT.
9975 */
9976 bPreserve = (flags & BTREE_SAVEPOSITION)!=0;
drhbfc7a8b2016-04-09 17:04:05 +00009977 if( bPreserve ){
9978 if( !pPage->leaf
drh500d7e52022-03-22 23:33:20 +00009979 || (pPage->nFree+pPage->xCellSize(pPage,pCell)+2) >
9980 (int)(pBt->usableSize*2/3)
drh1641f112018-12-13 21:05:45 +00009981 || pPage->nCell==1 /* See dbfuzz001.test for a test case */
drhbfc7a8b2016-04-09 17:04:05 +00009982 ){
9983 /* A b-tree rebalance will be required after deleting this entry.
9984 ** Save the cursor key. */
9985 rc = saveCursorKey(pCur);
9986 if( rc ) return rc;
9987 }else{
drh7e17a3a2022-01-02 14:55:43 +00009988 bPreserve = 2;
drhbfc7a8b2016-04-09 17:04:05 +00009989 }
9990 }
9991
danielk19774dbaa892009-06-16 16:50:22 +00009992 /* If the page containing the entry to delete is not a leaf page, move
9993 ** the cursor to the largest entry in the tree that is smaller than
9994 ** the entry being deleted. This cell will replace the cell being deleted
9995 ** from the internal node. The 'previous' entry is used for this instead
9996 ** of the 'next' entry, as the previous entry is always a part of the
9997 ** sub-tree headed by the child page of the cell being deleted. This makes
9998 ** balancing the tree following the delete operation easier. */
9999 if( !pPage->leaf ){
drh2ab792e2017-05-30 18:34:07 +000010000 rc = sqlite3BtreePrevious(pCur, 0);
10001 assert( rc!=SQLITE_DONE );
drh4c301aa2009-07-15 17:25:45 +000010002 if( rc ) return rc;
danielk19774dbaa892009-06-16 16:50:22 +000010003 }
10004
10005 /* Save the positions of any other cursors open on this table before
danf0ee1d32015-09-12 19:26:11 +000010006 ** making any modifications. */
drh27fb7462015-06-30 02:47:36 +000010007 if( pCur->curFlags & BTCF_Multiple ){
10008 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
10009 if( rc ) return rc;
10010 }
drhd60f4f42012-03-23 14:23:52 +000010011
10012 /* If this is a delete operation to remove a row from a table b-tree,
10013 ** invalidate any incrblob cursors open on the row being deleted. */
drh49bb56e2021-05-14 20:01:36 +000010014 if( pCur->pKeyInfo==0 && p->hasIncrblobCur ){
drh9ca431a2017-03-29 18:03:50 +000010015 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
drhd60f4f42012-03-23 14:23:52 +000010016 }
10017
danf0ee1d32015-09-12 19:26:11 +000010018 /* Make the page containing the entry to be deleted writable. Then free any
10019 ** overflow pages associated with the entry and finally remove the cell
10020 ** itself from within the page. */
drha4ec1d42009-07-11 13:13:11 +000010021 rc = sqlite3PagerWrite(pPage->pDbPage);
10022 if( rc ) return rc;
drh86c779f2021-05-15 13:08:44 +000010023 BTREE_CLEAR_CELL(rc, pPage, pCell, info);
drh80159da2016-12-09 17:32:51 +000010024 dropCell(pPage, iCellIdx, info.nSize, &rc);
drha4ec1d42009-07-11 13:13:11 +000010025 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +000010026
danielk19774dbaa892009-06-16 16:50:22 +000010027 /* If the cell deleted was not located on a leaf page, then the cursor
10028 ** is currently pointing to the largest entry in the sub-tree headed
10029 ** by the child-page of the cell that was just deleted from an internal
10030 ** node. The cell from the leaf node needs to be moved to the internal
10031 ** node to replace the deleted cell. */
drh4b70f112004-05-02 21:12:19 +000010032 if( !pPage->leaf ){
drh352a35a2017-08-15 03:46:47 +000010033 MemPage *pLeaf = pCur->pPage;
danielk19774dbaa892009-06-16 16:50:22 +000010034 int nCell;
drh352a35a2017-08-15 03:46:47 +000010035 Pgno n;
danielk19774dbaa892009-06-16 16:50:22 +000010036 unsigned char *pTmp;
danielk1977e6efa742004-11-10 11:55:10 +000010037
drhb0ea9432019-02-09 21:06:40 +000010038 if( pLeaf->nFree<0 ){
10039 rc = btreeComputeFreeSpace(pLeaf);
10040 if( rc ) return rc;
10041 }
drh352a35a2017-08-15 03:46:47 +000010042 if( iCellDepth<pCur->iPage-1 ){
10043 n = pCur->apPage[iCellDepth+1]->pgno;
10044 }else{
10045 n = pCur->pPage->pgno;
10046 }
danielk19774dbaa892009-06-16 16:50:22 +000010047 pCell = findCell(pLeaf, pLeaf->nCell-1);
drhb468ce12015-06-24 01:07:30 +000010048 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
drh25ada072015-06-19 15:07:14 +000010049 nCell = pLeaf->xCellSize(pLeaf, pCell);
drhfcd71b62011-04-05 22:08:24 +000010050 assert( MX_CELL_SIZE(pBt) >= nCell );
danielk19774dbaa892009-06-16 16:50:22 +000010051 pTmp = pBt->pTmpSpace;
drh3fbb0222014-09-24 19:47:27 +000010052 assert( pTmp!=0 );
drha4ec1d42009-07-11 13:13:11 +000010053 rc = sqlite3PagerWrite(pLeaf->pDbPage);
drhcb89f4a2016-05-21 11:23:26 +000010054 if( rc==SQLITE_OK ){
drhb53d8fa2022-11-21 15:55:57 +000010055 rc = insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n);
drhcb89f4a2016-05-21 11:23:26 +000010056 }
drh98add2e2009-07-20 17:11:49 +000010057 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
drha4ec1d42009-07-11 13:13:11 +000010058 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +000010059 }
danielk19774dbaa892009-06-16 16:50:22 +000010060
10061 /* Balance the tree. If the entry deleted was located on a leaf page,
10062 ** then the cursor still points to that page. In this case the first
10063 ** call to balance() repairs the tree, and the if(...) condition is
10064 ** never true.
10065 **
10066 ** Otherwise, if the entry deleted was on an internal node page, then
10067 ** pCur is pointing to the leaf page from which a cell was removed to
10068 ** replace the cell deleted from the internal node. This is slightly
10069 ** tricky as the leaf node may be underfull, and the internal node may
10070 ** be either under or overfull. In this case run the balancing algorithm
10071 ** on the leaf node first. If the balance proceeds far enough up the
10072 ** tree that we can be sure that any problem in the internal node has
10073 ** been corrected, so be it. Otherwise, after balancing the leaf node,
10074 ** walk the cursor up the tree to the internal node and balance it as
10075 ** well. */
drhde948482022-03-29 13:16:32 +000010076 assert( pCur->pPage->nOverflow==0 );
10077 assert( pCur->pPage->nFree>=0 );
drhc4c0ff82022-03-31 16:09:13 +000010078 if( pCur->pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){
drhde948482022-03-29 13:16:32 +000010079 /* Optimization: If the free space is less than 2/3rds of the page,
10080 ** then balance() will always be a no-op. No need to invoke it. */
10081 rc = SQLITE_OK;
10082 }else{
10083 rc = balance(pCur);
10084 }
danielk19774dbaa892009-06-16 16:50:22 +000010085 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
drh352a35a2017-08-15 03:46:47 +000010086 releasePageNotNull(pCur->pPage);
10087 pCur->iPage--;
danielk19774dbaa892009-06-16 16:50:22 +000010088 while( pCur->iPage>iCellDepth ){
10089 releasePage(pCur->apPage[pCur->iPage--]);
10090 }
drh352a35a2017-08-15 03:46:47 +000010091 pCur->pPage = pCur->apPage[pCur->iPage];
danielk19774dbaa892009-06-16 16:50:22 +000010092 rc = balance(pCur);
10093 }
10094
danielk19776b456a22005-03-21 04:04:02 +000010095 if( rc==SQLITE_OK ){
drh7e17a3a2022-01-02 14:55:43 +000010096 if( bPreserve>1 ){
10097 assert( (pCur->iPage==iCellDepth || CORRUPT_DB) );
drh352a35a2017-08-15 03:46:47 +000010098 assert( pPage==pCur->pPage || CORRUPT_DB );
drh78ac1092015-09-20 22:57:47 +000010099 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
danf0ee1d32015-09-12 19:26:11 +000010100 pCur->eState = CURSOR_SKIPNEXT;
10101 if( iCellIdx>=pPage->nCell ){
10102 pCur->skipNext = -1;
drh75e96b32017-04-01 00:20:06 +000010103 pCur->ix = pPage->nCell-1;
danf0ee1d32015-09-12 19:26:11 +000010104 }else{
10105 pCur->skipNext = 1;
10106 }
10107 }else{
10108 rc = moveToRoot(pCur);
10109 if( bPreserve ){
drh85ef6302017-08-02 15:50:09 +000010110 btreeReleaseAllCursorPages(pCur);
danf0ee1d32015-09-12 19:26:11 +000010111 pCur->eState = CURSOR_REQUIRESEEK;
10112 }
drh44548e72017-08-14 18:13:52 +000010113 if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
danf0ee1d32015-09-12 19:26:11 +000010114 }
danielk19776b456a22005-03-21 04:04:02 +000010115 }
drh5e2f8b92001-05-28 00:41:15 +000010116 return rc;
drh3b7511c2001-05-26 13:15:44 +000010117}
drh8b2f49b2001-06-08 00:21:52 +000010118
10119/*
drhc6b52df2002-01-04 03:09:29 +000010120** Create a new BTree table. Write into *piTable the page
10121** number for the root page of the new table.
10122**
drhab01f612004-05-22 02:55:23 +000010123** The type of type is determined by the flags parameter. Only the
10124** following values of flags are currently in use. Other values for
10125** flags might not work:
10126**
10127** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
10128** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +000010129*/
drhabc38152020-07-22 13:38:04 +000010130static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){
danielk1977aef0bf62005-12-30 16:28:01 +000010131 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +000010132 MemPage *pRoot;
10133 Pgno pgnoRoot;
10134 int rc;
drhd4187c72010-08-30 22:15:45 +000010135 int ptfFlags; /* Page-type flage for the root page of new table */
drhd677b3d2007-08-20 22:48:41 +000010136
drh1fee73e2007-08-29 04:00:57 +000010137 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +000010138 assert( pBt->inTransaction==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +000010139 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk1977e6efa742004-11-10 11:55:10 +000010140
danielk1977003ba062004-11-04 02:57:33 +000010141#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +000010142 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +000010143 if( rc ){
10144 return rc;
10145 }
danielk1977003ba062004-11-04 02:57:33 +000010146#else
danielk1977687566d2004-11-02 12:56:41 +000010147 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +000010148 Pgno pgnoMove; /* Move a page here to make room for the root-page */
10149 MemPage *pPageMove; /* The page to move to. */
10150
danielk197720713f32007-05-03 11:43:33 +000010151 /* Creating a new table may probably require moving an existing database
10152 ** to make room for the new tables root page. In case this page turns
10153 ** out to be an overflow page, delete all overflow page-map caches
10154 ** held by open cursors.
10155 */
danielk197792d4d7a2007-05-04 12:05:56 +000010156 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +000010157
danielk1977003ba062004-11-04 02:57:33 +000010158 /* Read the value of meta[3] from the database to determine where the
10159 ** root page of the new table should go. meta[3] is the largest root-page
10160 ** created so far, so the new root-page is (meta[3]+1).
10161 */
danielk1977602b4662009-07-02 07:47:33 +000010162 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
drh10248222020-07-28 20:32:12 +000010163 if( pgnoRoot>btreePagecount(pBt) ){
10164 return SQLITE_CORRUPT_BKPT;
10165 }
danielk1977003ba062004-11-04 02:57:33 +000010166 pgnoRoot++;
10167
danielk1977599fcba2004-11-08 07:13:13 +000010168 /* The new root-page may not be allocated on a pointer-map page, or the
10169 ** PENDING_BYTE page.
10170 */
drh72190432008-01-31 14:54:43 +000010171 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +000010172 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +000010173 pgnoRoot++;
10174 }
drh48bf2d72020-07-30 17:14:55 +000010175 assert( pgnoRoot>=3 );
danielk1977003ba062004-11-04 02:57:33 +000010176
10177 /* Allocate a page. The page that currently resides at pgnoRoot will
10178 ** be moved to the allocated page (unless the allocated page happens
10179 ** to reside at pgnoRoot).
10180 */
dan51f0b6d2013-02-22 20:16:34 +000010181 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
danielk1977003ba062004-11-04 02:57:33 +000010182 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +000010183 return rc;
10184 }
danielk1977003ba062004-11-04 02:57:33 +000010185
10186 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +000010187 /* pgnoRoot is the page that will be used for the root-page of
10188 ** the new table (assuming an error did not occur). But we were
10189 ** allocated pgnoMove. If required (i.e. if it was not allocated
10190 ** by extending the file), the current page at position pgnoMove
10191 ** is already journaled.
10192 */
drheeb844a2009-08-08 18:01:07 +000010193 u8 eType = 0;
10194 Pgno iPtrPage = 0;
danielk1977003ba062004-11-04 02:57:33 +000010195
danf7679ad2013-04-03 11:38:36 +000010196 /* Save the positions of any open cursors. This is required in
10197 ** case they are holding a reference to an xFetch reference
10198 ** corresponding to page pgnoRoot. */
10199 rc = saveAllCursors(pBt, 0, 0);
danielk1977003ba062004-11-04 02:57:33 +000010200 releasePage(pPageMove);
danf7679ad2013-04-03 11:38:36 +000010201 if( rc!=SQLITE_OK ){
10202 return rc;
10203 }
danielk1977f35843b2007-04-07 15:03:17 +000010204
10205 /* Move the page currently at pgnoRoot to pgnoMove. */
drhb00fc3b2013-08-21 23:42:32 +000010206 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +000010207 if( rc!=SQLITE_OK ){
10208 return rc;
10209 }
10210 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drh27731d72009-06-22 12:05:10 +000010211 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
10212 rc = SQLITE_CORRUPT_BKPT;
10213 }
10214 if( rc!=SQLITE_OK ){
danielk1977003ba062004-11-04 02:57:33 +000010215 releasePage(pRoot);
10216 return rc;
10217 }
drhccae6022005-02-26 17:31:26 +000010218 assert( eType!=PTRMAP_ROOTPAGE );
10219 assert( eType!=PTRMAP_FREEPAGE );
danielk19774c999992008-07-16 18:17:55 +000010220 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +000010221 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +000010222
10223 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +000010224 if( rc!=SQLITE_OK ){
10225 return rc;
10226 }
drhb00fc3b2013-08-21 23:42:32 +000010227 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +000010228 if( rc!=SQLITE_OK ){
10229 return rc;
10230 }
danielk19773b8a05f2007-03-19 17:44:26 +000010231 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +000010232 if( rc!=SQLITE_OK ){
10233 releasePage(pRoot);
10234 return rc;
10235 }
10236 }else{
10237 pRoot = pPageMove;
10238 }
10239
danielk197742741be2005-01-08 12:42:39 +000010240 /* Update the pointer-map and meta-data with the new root-page number. */
drh98add2e2009-07-20 17:11:49 +000010241 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
danielk1977003ba062004-11-04 02:57:33 +000010242 if( rc ){
10243 releasePage(pRoot);
10244 return rc;
10245 }
drhbf592832010-03-30 15:51:12 +000010246
10247 /* When the new root page was allocated, page 1 was made writable in
10248 ** order either to increase the database filesize, or to decrement the
10249 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
10250 */
10251 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
danielk1977aef0bf62005-12-30 16:28:01 +000010252 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
drhbf592832010-03-30 15:51:12 +000010253 if( NEVER(rc) ){
danielk1977003ba062004-11-04 02:57:33 +000010254 releasePage(pRoot);
10255 return rc;
10256 }
danielk197742741be2005-01-08 12:42:39 +000010257
danielk1977003ba062004-11-04 02:57:33 +000010258 }else{
drh4f0c5872007-03-26 22:05:01 +000010259 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +000010260 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +000010261 }
10262#endif
danielk19773b8a05f2007-03-19 17:44:26 +000010263 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhd4187c72010-08-30 22:15:45 +000010264 if( createTabFlags & BTREE_INTKEY ){
10265 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
10266 }else{
10267 ptfFlags = PTF_ZERODATA | PTF_LEAF;
10268 }
10269 zeroPage(pRoot, ptfFlags);
danielk19773b8a05f2007-03-19 17:44:26 +000010270 sqlite3PagerUnref(pRoot->pDbPage);
drhd4187c72010-08-30 22:15:45 +000010271 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
drhabc38152020-07-22 13:38:04 +000010272 *piTable = pgnoRoot;
drh8b2f49b2001-06-08 00:21:52 +000010273 return SQLITE_OK;
10274}
drhabc38152020-07-22 13:38:04 +000010275int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){
drhd677b3d2007-08-20 22:48:41 +000010276 int rc;
10277 sqlite3BtreeEnter(p);
10278 rc = btreeCreateTable(p, piTable, flags);
10279 sqlite3BtreeLeave(p);
10280 return rc;
10281}
drh8b2f49b2001-06-08 00:21:52 +000010282
10283/*
10284** Erase the given database page and all its children. Return
10285** the page to the freelist.
10286*/
drh4b70f112004-05-02 21:12:19 +000010287static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +000010288 BtShared *pBt, /* The BTree that contains the table */
drh7ab641f2009-11-24 02:37:02 +000010289 Pgno pgno, /* Page number to clear */
10290 int freePageFlag, /* Deallocate page if true */
drhdb7959d2021-08-03 16:31:54 +000010291 i64 *pnChange, /* Add number of Cells freed to this counter */
dan7fff2e12017-05-29 14:27:37 +000010292 Pgno pgnoRoot
drh4b70f112004-05-02 21:12:19 +000010293){
danielk1977146ba992009-07-22 14:08:13 +000010294 MemPage *pPage;
drh8b2f49b2001-06-08 00:21:52 +000010295 int rc;
drh4b70f112004-05-02 21:12:19 +000010296 unsigned char *pCell;
10297 int i;
dan8ce71842014-01-14 20:14:09 +000010298 int hdr;
drh80159da2016-12-09 17:32:51 +000010299 CellInfo info;
drh8b2f49b2001-06-08 00:21:52 +000010300
drh1fee73e2007-08-29 04:00:57 +000010301 assert( sqlite3_mutex_held(pBt->mutex) );
drhb1299152010-03-30 22:58:33 +000010302 if( pgno>btreePagecount(pBt) ){
drh49285702005-09-17 15:20:26 +000010303 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +000010304 }
drh28f58dd2015-06-27 19:45:03 +000010305 rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
danielk1977146ba992009-07-22 14:08:13 +000010306 if( rc ) return rc;
dan7fff2e12017-05-29 14:27:37 +000010307 setMempageRoot(pPage, pgnoRoot);
dan1273d692021-10-16 17:09:36 +000010308 if( (pBt->openFlags & BTREE_SINGLE)==0
drh9a4e8862022-02-14 18:18:56 +000010309 && sqlite3PagerPageRefcount(pPage->pDbPage) != (1 + (pgno==1))
dan1273d692021-10-16 17:09:36 +000010310 ){
drhccf46d02015-04-01 13:21:33 +000010311 rc = SQLITE_CORRUPT_BKPT;
10312 goto cleardatabasepage_out;
10313 }
dan8ce71842014-01-14 20:14:09 +000010314 hdr = pPage->hdrOffset;
drh4b70f112004-05-02 21:12:19 +000010315 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +000010316 pCell = findCell(pPage, i);
drhccf46d02015-04-01 13:21:33 +000010317 if( !pPage->leaf ){
dan7fff2e12017-05-29 14:27:37 +000010318 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange, pgnoRoot);
danielk19776b456a22005-03-21 04:04:02 +000010319 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +000010320 }
drh86c779f2021-05-15 13:08:44 +000010321 BTREE_CLEAR_CELL(rc, pPage, pCell, info);
danielk19776b456a22005-03-21 04:04:02 +000010322 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +000010323 }
drhccf46d02015-04-01 13:21:33 +000010324 if( !pPage->leaf ){
dan7fff2e12017-05-29 14:27:37 +000010325 rc = clearDatabasePage(
10326 pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange, pgnoRoot
10327 );
danielk19776b456a22005-03-21 04:04:02 +000010328 if( rc ) goto cleardatabasepage_out;
dan020c4f32021-06-22 18:06:23 +000010329 if( pPage->intKey ) pnChange = 0;
drha6df0e62021-06-03 18:51:51 +000010330 }
10331 if( pnChange ){
drhafe028a2015-05-22 13:09:50 +000010332 testcase( !pPage->intKey );
danielk1977c7af4842008-10-27 13:59:33 +000010333 *pnChange += pPage->nCell;
drh2aa679f2001-06-25 02:11:07 +000010334 }
10335 if( freePageFlag ){
drhc314dc72009-07-21 11:52:34 +000010336 freePage(pPage, &rc);
danielk19773b8a05f2007-03-19 17:44:26 +000010337 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
dan8ce71842014-01-14 20:14:09 +000010338 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +000010339 }
danielk19776b456a22005-03-21 04:04:02 +000010340
10341cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +000010342 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +000010343 return rc;
drh8b2f49b2001-06-08 00:21:52 +000010344}
10345
10346/*
drhab01f612004-05-22 02:55:23 +000010347** Delete all information from a single table in the database. iTable is
10348** the page number of the root of the table. After this routine returns,
10349** the root page is empty, but still exists.
10350**
10351** This routine will fail with SQLITE_LOCKED if there are any open
10352** read cursors on the table. Open write cursors are moved to the
10353** root of the table.
danielk1977c7af4842008-10-27 13:59:33 +000010354**
drha6df0e62021-06-03 18:51:51 +000010355** If pnChange is not NULL, then the integer value pointed to by pnChange
10356** is incremented by the number of entries in the table.
drh8b2f49b2001-06-08 00:21:52 +000010357*/
dan2c718872021-06-22 18:32:05 +000010358int sqlite3BtreeClearTable(Btree *p, int iTable, i64 *pnChange){
drh8b2f49b2001-06-08 00:21:52 +000010359 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +000010360 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +000010361 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +000010362 assert( p->inTrans==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +000010363
drhc046e3e2009-07-15 11:26:44 +000010364 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
drhd60f4f42012-03-23 14:23:52 +000010365
drhc046e3e2009-07-15 11:26:44 +000010366 if( SQLITE_OK==rc ){
drhd60f4f42012-03-23 14:23:52 +000010367 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
10368 ** is the root of a table b-tree - if it is not, the following call is
10369 ** a no-op). */
drh49bb56e2021-05-14 20:01:36 +000010370 if( p->hasIncrblobCur ){
10371 invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
10372 }
dan7fff2e12017-05-29 14:27:37 +000010373 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange, (Pgno)iTable);
drh8b2f49b2001-06-08 00:21:52 +000010374 }
drhd677b3d2007-08-20 22:48:41 +000010375 sqlite3BtreeLeave(p);
10376 return rc;
drh8b2f49b2001-06-08 00:21:52 +000010377}
10378
10379/*
drh079a3072014-03-19 14:10:55 +000010380** Delete all information from the single table that pCur is open on.
10381**
10382** This routine only work for pCur on an ephemeral table.
10383*/
10384int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
10385 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
10386}
10387
10388/*
drh8b2f49b2001-06-08 00:21:52 +000010389** Erase all information in a table and add the root of the table to
10390** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +000010391** page 1) is never added to the freelist.
10392**
10393** This routine will fail with SQLITE_LOCKED if there are any open
10394** cursors on the table.
drh205f48e2004-11-05 00:43:11 +000010395**
10396** If AUTOVACUUM is enabled and the page at iTable is not the last
10397** root page in the database file, then the last root page
10398** in the database file is moved into the slot formerly occupied by
10399** iTable and that last slot formerly occupied by the last root page
10400** is added to the freelist instead of iTable. In this say, all
10401** root pages are kept at the beginning of the database file, which
10402** is necessary for AUTOVACUUM to work right. *piMoved is set to the
10403** page number that used to be the last root page in the file before
10404** the move. If no page gets moved, *piMoved is set to 0.
10405** The last root page is recorded in meta[3] and the value of
10406** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +000010407*/
danielk197789d40042008-11-17 14:20:56 +000010408static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +000010409 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +000010410 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +000010411 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +000010412
drh1fee73e2007-08-29 04:00:57 +000010413 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +000010414 assert( p->inTrans==TRANS_WRITE );
drh65f38d92016-11-22 01:26:42 +000010415 assert( iTable>=2 );
drh9a518842019-03-08 01:52:30 +000010416 if( iTable>btreePagecount(pBt) ){
10417 return SQLITE_CORRUPT_BKPT;
10418 }
drh055f2982016-01-15 15:06:41 +000010419
danielk1977c7af4842008-10-27 13:59:33 +000010420 rc = sqlite3BtreeClearTable(p, iTable, 0);
dan1273d692021-10-16 17:09:36 +000010421 if( rc ) return rc;
10422 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drhda125362021-10-16 18:53:36 +000010423 if( NEVER(rc) ){
danielk19776b456a22005-03-21 04:04:02 +000010424 releasePage(pPage);
10425 return rc;
10426 }
danielk1977a0bf2652004-11-04 14:30:04 +000010427
drh205f48e2004-11-05 00:43:11 +000010428 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +000010429
danielk1977a0bf2652004-11-04 14:30:04 +000010430#ifdef SQLITE_OMIT_AUTOVACUUM
drh055f2982016-01-15 15:06:41 +000010431 freePage(pPage, &rc);
10432 releasePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +000010433#else
drh055f2982016-01-15 15:06:41 +000010434 if( pBt->autoVacuum ){
10435 Pgno maxRootPgno;
10436 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +000010437
drh055f2982016-01-15 15:06:41 +000010438 if( iTable==maxRootPgno ){
10439 /* If the table being dropped is the table with the largest root-page
10440 ** number in the database, put the root page on the free list.
danielk1977599fcba2004-11-08 07:13:13 +000010441 */
drhc314dc72009-07-21 11:52:34 +000010442 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +000010443 releasePage(pPage);
drh055f2982016-01-15 15:06:41 +000010444 if( rc!=SQLITE_OK ){
10445 return rc;
10446 }
10447 }else{
10448 /* The table being dropped does not have the largest root-page
10449 ** number in the database. So move the page that does into the
10450 ** gap left by the deleted root-page.
10451 */
10452 MemPage *pMove;
10453 releasePage(pPage);
10454 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
10455 if( rc!=SQLITE_OK ){
10456 return rc;
10457 }
10458 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
10459 releasePage(pMove);
10460 if( rc!=SQLITE_OK ){
10461 return rc;
10462 }
10463 pMove = 0;
10464 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
10465 freePage(pMove, &rc);
10466 releasePage(pMove);
10467 if( rc!=SQLITE_OK ){
10468 return rc;
10469 }
10470 *piMoved = maxRootPgno;
danielk1977a0bf2652004-11-04 14:30:04 +000010471 }
drh055f2982016-01-15 15:06:41 +000010472
10473 /* Set the new 'max-root-page' value in the database header. This
10474 ** is the old value less one, less one more if that happens to
10475 ** be a root-page number, less one again if that is the
10476 ** PENDING_BYTE_PAGE.
drhc046e3e2009-07-15 11:26:44 +000010477 */
drh055f2982016-01-15 15:06:41 +000010478 maxRootPgno--;
10479 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
10480 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
10481 maxRootPgno--;
10482 }
10483 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
10484
10485 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
10486 }else{
10487 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +000010488 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +000010489 }
drh055f2982016-01-15 15:06:41 +000010490#endif
drh8b2f49b2001-06-08 00:21:52 +000010491 return rc;
10492}
drhd677b3d2007-08-20 22:48:41 +000010493int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
10494 int rc;
10495 sqlite3BtreeEnter(p);
dan7733a4d2011-09-02 18:03:16 +000010496 rc = btreeDropTable(p, iTable, piMoved);
drhd677b3d2007-08-20 22:48:41 +000010497 sqlite3BtreeLeave(p);
10498 return rc;
10499}
drh8b2f49b2001-06-08 00:21:52 +000010500
drh001bbcb2003-03-19 03:14:00 +000010501
drh8b2f49b2001-06-08 00:21:52 +000010502/*
danielk1977602b4662009-07-02 07:47:33 +000010503** This function may only be called if the b-tree connection already
10504** has a read or write transaction open on the database.
10505**
drh23e11ca2004-05-04 17:27:28 +000010506** Read the meta-information out of a database file. Meta[0]
10507** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +000010508** through meta[15] are available for use by higher layers. Meta[0]
10509** is read-only, the others are read/write.
10510**
10511** The schema layer numbers meta values differently. At the schema
10512** layer (and the SetCookie and ReadCookie opcodes) the number of
10513** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh91618562014-12-19 19:28:02 +000010514**
10515** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
10516** of reading the value out of the header, it instead loads the "DataVersion"
10517** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
10518** database file. It is a number computed by the pager. But its access
10519** pattern is the same as header meta values, and so it is convenient to
10520** read it from this routine.
drh8b2f49b2001-06-08 00:21:52 +000010521*/
danielk1977602b4662009-07-02 07:47:33 +000010522void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
danielk1977aef0bf62005-12-30 16:28:01 +000010523 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +000010524
drhd677b3d2007-08-20 22:48:41 +000010525 sqlite3BtreeEnter(p);
danielk1977602b4662009-07-02 07:47:33 +000010526 assert( p->inTrans>TRANS_NONE );
drh346a70c2020-06-15 20:27:35 +000010527 assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) );
danielk1977602b4662009-07-02 07:47:33 +000010528 assert( pBt->pPage1 );
drh23e11ca2004-05-04 17:27:28 +000010529 assert( idx>=0 && idx<=15 );
danielk1977ea897302008-09-19 15:10:58 +000010530
drh91618562014-12-19 19:28:02 +000010531 if( idx==BTREE_DATA_VERSION ){
drh2b994ce2021-03-18 12:36:09 +000010532 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iBDataVersion;
drh91618562014-12-19 19:28:02 +000010533 }else{
10534 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
10535 }
drhae157872004-08-14 19:20:09 +000010536
danielk1977602b4662009-07-02 07:47:33 +000010537 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
10538 ** database, mark the database as read-only. */
danielk1977003ba062004-11-04 02:57:33 +000010539#ifdef SQLITE_OMIT_AUTOVACUUM
drhc9166342012-01-05 23:32:06 +000010540 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
10541 pBt->btsFlags |= BTS_READ_ONLY;
10542 }
danielk1977003ba062004-11-04 02:57:33 +000010543#endif
drhae157872004-08-14 19:20:09 +000010544
drhd677b3d2007-08-20 22:48:41 +000010545 sqlite3BtreeLeave(p);
drh8b2f49b2001-06-08 00:21:52 +000010546}
10547
10548/*
drh23e11ca2004-05-04 17:27:28 +000010549** Write meta-information back into the database. Meta[0] is
10550** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +000010551*/
danielk1977aef0bf62005-12-30 16:28:01 +000010552int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
10553 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +000010554 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +000010555 int rc;
drh23e11ca2004-05-04 17:27:28 +000010556 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +000010557 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +000010558 assert( p->inTrans==TRANS_WRITE );
10559 assert( pBt->pPage1!=0 );
10560 pP1 = pBt->pPage1->aData;
10561 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
10562 if( rc==SQLITE_OK ){
10563 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +000010564#ifndef SQLITE_OMIT_AUTOVACUUM
danielk19770d19f7a2009-06-03 11:25:07 +000010565 if( idx==BTREE_INCR_VACUUM ){
drh64022502009-01-09 14:11:04 +000010566 assert( pBt->autoVacuum || iMeta==0 );
10567 assert( iMeta==0 || iMeta==1 );
10568 pBt->incrVacuum = (u8)iMeta;
drhd677b3d2007-08-20 22:48:41 +000010569 }
drh64022502009-01-09 14:11:04 +000010570#endif
drh5df72a52002-06-06 23:16:05 +000010571 }
drhd677b3d2007-08-20 22:48:41 +000010572 sqlite3BtreeLeave(p);
10573 return rc;
drh8b2f49b2001-06-08 00:21:52 +000010574}
drh8c42ca92001-06-22 19:15:00 +000010575
danielk1977a5533162009-02-24 10:01:51 +000010576/*
10577** The first argument, pCur, is a cursor opened on some b-tree. Count the
10578** number of entries in the b-tree and write the result to *pnEntry.
10579**
10580** SQLITE_OK is returned if the operation is successfully executed.
10581** Otherwise, if an error is encountered (i.e. an IO error or database
10582** corruption) an SQLite error code is returned.
10583*/
drh21f6daa2019-10-11 14:21:48 +000010584int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){
danielk1977a5533162009-02-24 10:01:51 +000010585 i64 nEntry = 0; /* Value to return in *pnEntry */
10586 int rc; /* Return code */
dana205a482011-08-27 18:48:57 +000010587
drh44548e72017-08-14 18:13:52 +000010588 rc = moveToRoot(pCur);
10589 if( rc==SQLITE_EMPTY ){
dana205a482011-08-27 18:48:57 +000010590 *pnEntry = 0;
10591 return SQLITE_OK;
10592 }
danielk1977a5533162009-02-24 10:01:51 +000010593
10594 /* Unless an error occurs, the following loop runs one iteration for each
10595 ** page in the B-Tree structure (not including overflow pages).
10596 */
dan892edb62020-03-30 13:35:05 +000010597 while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
danielk1977a5533162009-02-24 10:01:51 +000010598 int iIdx; /* Index of child node in parent */
10599 MemPage *pPage; /* Current page of the b-tree */
10600
10601 /* If this is a leaf page or the tree is not an int-key tree, then
10602 ** this page contains countable entries. Increment the entry counter
10603 ** accordingly.
10604 */
drh352a35a2017-08-15 03:46:47 +000010605 pPage = pCur->pPage;
danielk1977a5533162009-02-24 10:01:51 +000010606 if( pPage->leaf || !pPage->intKey ){
10607 nEntry += pPage->nCell;
10608 }
10609
10610 /* pPage is a leaf node. This loop navigates the cursor so that it
10611 ** points to the first interior cell that it points to the parent of
10612 ** the next page in the tree that has not yet been visited. The
10613 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
10614 ** of the page, or to the number of cells in the page if the next page
10615 ** to visit is the right-child of its parent.
10616 **
10617 ** If all pages in the tree have been visited, return SQLITE_OK to the
10618 ** caller.
10619 */
10620 if( pPage->leaf ){
10621 do {
10622 if( pCur->iPage==0 ){
10623 /* All pages of the b-tree have been visited. Return successfully. */
10624 *pnEntry = nEntry;
drh7efa4262014-12-16 00:08:31 +000010625 return moveToRoot(pCur);
danielk1977a5533162009-02-24 10:01:51 +000010626 }
danielk197730548662009-07-09 05:07:37 +000010627 moveToParent(pCur);
drh352a35a2017-08-15 03:46:47 +000010628 }while ( pCur->ix>=pCur->pPage->nCell );
danielk1977a5533162009-02-24 10:01:51 +000010629
drh75e96b32017-04-01 00:20:06 +000010630 pCur->ix++;
drh352a35a2017-08-15 03:46:47 +000010631 pPage = pCur->pPage;
danielk1977a5533162009-02-24 10:01:51 +000010632 }
10633
10634 /* Descend to the child node of the cell that the cursor currently
10635 ** points at. This is the right-child if (iIdx==pPage->nCell).
10636 */
drh75e96b32017-04-01 00:20:06 +000010637 iIdx = pCur->ix;
danielk1977a5533162009-02-24 10:01:51 +000010638 if( iIdx==pPage->nCell ){
10639 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
10640 }else{
10641 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
10642 }
10643 }
10644
shanebe217792009-03-05 04:20:31 +000010645 /* An error has occurred. Return an error code. */
danielk1977a5533162009-02-24 10:01:51 +000010646 return rc;
10647}
drhdd793422001-06-28 01:54:48 +000010648
drhdd793422001-06-28 01:54:48 +000010649/*
drh5eddca62001-06-30 21:53:53 +000010650** Return the pager associated with a BTree. This routine is used for
10651** testing and debugging only.
drhdd793422001-06-28 01:54:48 +000010652*/
danielk1977aef0bf62005-12-30 16:28:01 +000010653Pager *sqlite3BtreePager(Btree *p){
10654 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +000010655}
drh5eddca62001-06-30 21:53:53 +000010656
drhb7f91642004-10-31 02:22:47 +000010657#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +000010658/*
drh5dd74bf2023-01-11 16:17:31 +000010659** Record an OOM error during integrity_check
10660*/
10661static void checkOom(IntegrityCk *pCheck){
10662 pCheck->rc = SQLITE_NOMEM;
10663 pCheck->mxErr = 0; /* Causes integrity_check processing to stop */
10664 if( pCheck->nErr==0 ) pCheck->nErr++;
10665}
10666
10667/*
10668** Invoke the progress handler, if appropriate. Also check for an
10669** interrupt.
10670*/
10671static void checkProgress(IntegrityCk *pCheck){
10672 sqlite3 *db = pCheck->db;
10673 if( AtomicLoad(&db->u1.isInterrupted) ){
10674 pCheck->rc = SQLITE_INTERRUPT;
10675 pCheck->nErr++;
10676 pCheck->mxErr = 0;
10677 }
10678#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
10679 if( db->xProgress ){
10680 assert( db->nProgressOps>0 );
10681 pCheck->nStep++;
10682 if( (pCheck->nStep % db->nProgressOps)==0
10683 && db->xProgress(db->pProgressArg)
10684 ){
10685 pCheck->rc = SQLITE_INTERRUPT;
10686 pCheck->nErr++;
10687 pCheck->mxErr = 0;
10688 }
10689 }
10690#endif
10691}
10692
10693/*
drh5eddca62001-06-30 21:53:53 +000010694** Append a message to the error message string.
10695*/
drh2e38c322004-09-03 18:38:44 +000010696static void checkAppendMsg(
10697 IntegrityCk *pCheck,
drh2e38c322004-09-03 18:38:44 +000010698 const char *zFormat,
10699 ...
10700){
10701 va_list ap;
drh5dd74bf2023-01-11 16:17:31 +000010702 checkProgress(pCheck);
drh1dcdbc02007-01-27 02:24:54 +000010703 if( !pCheck->mxErr ) return;
10704 pCheck->mxErr--;
10705 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +000010706 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +000010707 if( pCheck->errMsg.nChar ){
drh0cdbe1a2018-05-09 13:46:26 +000010708 sqlite3_str_append(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +000010709 }
drh867db832014-09-26 02:41:05 +000010710 if( pCheck->zPfx ){
drh0cdbe1a2018-05-09 13:46:26 +000010711 sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
drhf089aa42008-07-08 19:34:06 +000010712 }
drh0cdbe1a2018-05-09 13:46:26 +000010713 sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
drhf089aa42008-07-08 19:34:06 +000010714 va_end(ap);
drh0cdbe1a2018-05-09 13:46:26 +000010715 if( pCheck->errMsg.accError==SQLITE_NOMEM ){
drh5dd74bf2023-01-11 16:17:31 +000010716 checkOom(pCheck);
drhc890fec2008-08-01 20:10:08 +000010717 }
drh5eddca62001-06-30 21:53:53 +000010718}
drhb7f91642004-10-31 02:22:47 +000010719#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +000010720
drhb7f91642004-10-31 02:22:47 +000010721#ifndef SQLITE_OMIT_INTEGRITY_CHECK
dan1235bb12012-04-03 17:43:28 +000010722
10723/*
10724** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
10725** corresponds to page iPg is already set.
10726*/
10727static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
10728 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
10729 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
10730}
10731
10732/*
10733** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
10734*/
10735static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
10736 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
10737 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
10738}
10739
10740
drh5eddca62001-06-30 21:53:53 +000010741/*
10742** Add 1 to the reference count for page iPage. If this is the second
10743** reference to the page, add an error message to pCheck->zErrMsg.
peter.d.reid60ec9142014-09-06 16:39:46 +000010744** Return 1 if there are 2 or more references to the page and 0 if
drh5eddca62001-06-30 21:53:53 +000010745** if this is the first reference to the page.
10746**
10747** Also check that the page number is in bounds.
10748*/
drh867db832014-09-26 02:41:05 +000010749static int checkRef(IntegrityCk *pCheck, Pgno iPage){
drh91d58662018-07-20 13:39:28 +000010750 if( iPage>pCheck->nPage || iPage==0 ){
drh867db832014-09-26 02:41:05 +000010751 checkAppendMsg(pCheck, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +000010752 return 1;
10753 }
dan1235bb12012-04-03 17:43:28 +000010754 if( getPageReferenced(pCheck, iPage) ){
drh867db832014-09-26 02:41:05 +000010755 checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +000010756 return 1;
10757 }
dan1235bb12012-04-03 17:43:28 +000010758 setPageReferenced(pCheck, iPage);
10759 return 0;
drh5eddca62001-06-30 21:53:53 +000010760}
10761
danielk1977afcdd022004-10-31 16:25:42 +000010762#ifndef SQLITE_OMIT_AUTOVACUUM
10763/*
10764** Check that the entry in the pointer-map for page iChild maps to
10765** page iParent, pointer type ptrType. If not, append an error message
10766** to pCheck.
10767*/
10768static void checkPtrmap(
10769 IntegrityCk *pCheck, /* Integrity check context */
10770 Pgno iChild, /* Child page number */
10771 u8 eType, /* Expected pointer map type */
drh867db832014-09-26 02:41:05 +000010772 Pgno iParent /* Expected pointer map parent page number */
danielk1977afcdd022004-10-31 16:25:42 +000010773){
10774 int rc;
10775 u8 ePtrmapType;
10776 Pgno iPtrmapParent;
10777
10778 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
10779 if( rc!=SQLITE_OK ){
drh5dd74bf2023-01-11 16:17:31 +000010780 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) checkOom(pCheck);
drh867db832014-09-26 02:41:05 +000010781 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
danielk1977afcdd022004-10-31 16:25:42 +000010782 return;
10783 }
10784
10785 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
drh867db832014-09-26 02:41:05 +000010786 checkAppendMsg(pCheck,
danielk1977afcdd022004-10-31 16:25:42 +000010787 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
10788 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
10789 }
10790}
10791#endif
10792
drh5eddca62001-06-30 21:53:53 +000010793/*
10794** Check the integrity of the freelist or of an overflow page list.
10795** Verify that the number of pages on the list is N.
10796*/
drh30e58752002-03-02 20:41:57 +000010797static void checkList(
10798 IntegrityCk *pCheck, /* Integrity checking context */
10799 int isFreeList, /* True for a freelist. False for overflow page list */
drhabc38152020-07-22 13:38:04 +000010800 Pgno iPage, /* Page number for first page in the list */
drheaac9992019-02-26 16:17:06 +000010801 u32 N /* Expected number of pages in the list */
drh30e58752002-03-02 20:41:57 +000010802){
10803 int i;
drheaac9992019-02-26 16:17:06 +000010804 u32 expected = N;
drh91d58662018-07-20 13:39:28 +000010805 int nErrAtStart = pCheck->nErr;
10806 while( iPage!=0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +000010807 DbPage *pOvflPage;
10808 unsigned char *pOvflData;
drh867db832014-09-26 02:41:05 +000010809 if( checkRef(pCheck, iPage) ) break;
drh91d58662018-07-20 13:39:28 +000010810 N--;
drh9584f582015-11-04 20:22:37 +000010811 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
drh867db832014-09-26 02:41:05 +000010812 checkAppendMsg(pCheck, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +000010813 break;
10814 }
danielk19773b8a05f2007-03-19 17:44:26 +000010815 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +000010816 if( isFreeList ){
drhae104742018-12-14 17:57:01 +000010817 u32 n = (u32)get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +000010818#ifndef SQLITE_OMIT_AUTOVACUUM
10819 if( pCheck->pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +000010820 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +000010821 }
10822#endif
drhae104742018-12-14 17:57:01 +000010823 if( n>pCheck->pBt->usableSize/4-2 ){
drh867db832014-09-26 02:41:05 +000010824 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +000010825 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +000010826 N--;
10827 }else{
drhae104742018-12-14 17:57:01 +000010828 for(i=0; i<(int)n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +000010829 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +000010830#ifndef SQLITE_OMIT_AUTOVACUUM
10831 if( pCheck->pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +000010832 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +000010833 }
10834#endif
drh867db832014-09-26 02:41:05 +000010835 checkRef(pCheck, iFreePage);
drhee696e22004-08-30 16:52:17 +000010836 }
10837 N -= n;
drh30e58752002-03-02 20:41:57 +000010838 }
drh30e58752002-03-02 20:41:57 +000010839 }
danielk1977afcdd022004-10-31 16:25:42 +000010840#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +000010841 else{
10842 /* If this database supports auto-vacuum and iPage is not the last
10843 ** page in this overflow list, check that the pointer-map entry for
10844 ** the following page matches iPage.
10845 */
10846 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +000010847 i = get4byte(pOvflData);
drh867db832014-09-26 02:41:05 +000010848 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
danielk1977687566d2004-11-02 12:56:41 +000010849 }
danielk1977afcdd022004-10-31 16:25:42 +000010850 }
10851#endif
danielk19773b8a05f2007-03-19 17:44:26 +000010852 iPage = get4byte(pOvflData);
10853 sqlite3PagerUnref(pOvflPage);
drh91d58662018-07-20 13:39:28 +000010854 }
10855 if( N && nErrAtStart==pCheck->nErr ){
10856 checkAppendMsg(pCheck,
10857 "%s is %d but should be %d",
10858 isFreeList ? "size" : "overflow list length",
10859 expected-N, expected);
drh5eddca62001-06-30 21:53:53 +000010860 }
10861}
drhb7f91642004-10-31 02:22:47 +000010862#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +000010863
drh67731a92015-04-16 11:56:03 +000010864/*
10865** An implementation of a min-heap.
10866**
10867** aHeap[0] is the number of elements on the heap. aHeap[1] is the
drha33b6832015-04-16 21:57:37 +000010868** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
drh67731a92015-04-16 11:56:03 +000010869** and aHeap[N*2+1].
10870**
10871** The heap property is this: Every node is less than or equal to both
10872** of its daughter nodes. A consequence of the heap property is that the
drh42c0a2b2015-04-28 01:28:36 +000010873** root node aHeap[1] is always the minimum value currently in the heap.
drh67731a92015-04-16 11:56:03 +000010874**
10875** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
10876** the heap, preserving the heap property. The btreeHeapPull() routine
10877** removes the root element from the heap (the minimum value in the heap)
drh42c0a2b2015-04-28 01:28:36 +000010878** and then moves other nodes around as necessary to preserve the heap
drh67731a92015-04-16 11:56:03 +000010879** property.
10880**
10881** This heap is used for cell overlap and coverage testing. Each u32
10882** entry represents the span of a cell or freeblock on a btree page.
10883** The upper 16 bits are the index of the first byte of a range and the
10884** lower 16 bits are the index of the last byte of that range.
10885*/
10886static void btreeHeapInsert(u32 *aHeap, u32 x){
drhf92b0062023-01-27 20:15:48 +000010887 u32 j, i;
10888 assert( aHeap!=0 );
10889 i = ++aHeap[0];
drh67731a92015-04-16 11:56:03 +000010890 aHeap[i] = x;
drha33b6832015-04-16 21:57:37 +000010891 while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
drh67731a92015-04-16 11:56:03 +000010892 x = aHeap[j];
10893 aHeap[j] = aHeap[i];
10894 aHeap[i] = x;
10895 i = j;
10896 }
10897}
10898static int btreeHeapPull(u32 *aHeap, u32 *pOut){
10899 u32 j, i, x;
10900 if( (x = aHeap[0])==0 ) return 0;
10901 *pOut = aHeap[1];
10902 aHeap[1] = aHeap[x];
10903 aHeap[x] = 0xffffffff;
10904 aHeap[0]--;
10905 i = 1;
10906 while( (j = i*2)<=aHeap[0] ){
10907 if( aHeap[j]>aHeap[j+1] ) j++;
10908 if( aHeap[i]<aHeap[j] ) break;
10909 x = aHeap[i];
10910 aHeap[i] = aHeap[j];
10911 aHeap[j] = x;
10912 i = j;
10913 }
10914 return 1;
10915}
10916
drhb7f91642004-10-31 02:22:47 +000010917#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +000010918/*
10919** Do various sanity checks on a single page of a tree. Return
10920** the tree depth. Root pages return 0. Parents of root pages
10921** return 1, and so forth.
10922**
10923** These checks are done:
10924**
10925** 1. Make sure that cells and freeblocks do not overlap
10926** but combine to completely cover the page.
drhe05b3f82015-07-01 17:53:49 +000010927** 2. Make sure integer cell keys are in order.
10928** 3. Check the integrity of overflow pages.
10929** 4. Recursively call checkTreePage on all children.
10930** 5. Verify that the depth of all children is the same.
drh5eddca62001-06-30 21:53:53 +000010931*/
10932static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +000010933 IntegrityCk *pCheck, /* Context for the sanity check */
drhabc38152020-07-22 13:38:04 +000010934 Pgno iPage, /* Page number of the page to check */
drhcbc6b712015-07-02 16:17:30 +000010935 i64 *piMinKey, /* Write minimum integer primary key here */
10936 i64 maxKey /* Error if integer primary key greater than this */
drh5eddca62001-06-30 21:53:53 +000010937){
drhcbc6b712015-07-02 16:17:30 +000010938 MemPage *pPage = 0; /* The page being analyzed */
10939 int i; /* Loop counter */
10940 int rc; /* Result code from subroutine call */
10941 int depth = -1, d2; /* Depth of a subtree */
10942 int pgno; /* Page number */
10943 int nFrag; /* Number of fragmented bytes on the page */
10944 int hdr; /* Offset to the page header */
10945 int cellStart; /* Offset to the start of the cell pointer array */
10946 int nCell; /* Number of cells */
10947 int doCoverageCheck = 1; /* True if cell coverage checking should be done */
10948 int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
10949 ** False if IPK must be strictly less than maxKey */
10950 u8 *data; /* Page content */
10951 u8 *pCell; /* Cell content */
10952 u8 *pCellIdx; /* Next element of the cell pointer array */
10953 BtShared *pBt; /* The BtShared object that owns pPage */
10954 u32 pc; /* Address of a cell */
10955 u32 usableSize; /* Usable size of the page */
10956 u32 contentOffset; /* Offset to the start of the cell content area */
10957 u32 *heap = 0; /* Min-heap used for checking cell coverage */
drhd2dc87f2015-07-02 19:47:08 +000010958 u32 x, prev = 0; /* Next and previous entry on the min-heap */
drh867db832014-09-26 02:41:05 +000010959 const char *saved_zPfx = pCheck->zPfx;
10960 int saved_v1 = pCheck->v1;
10961 int saved_v2 = pCheck->v2;
mistachkin532f1792015-07-14 17:18:05 +000010962 u8 savedIsInit = 0;
danielk1977ef73ee92004-11-06 12:26:07 +000010963
drh5eddca62001-06-30 21:53:53 +000010964 /* Check that the page exists
10965 */
drh5dd74bf2023-01-11 16:17:31 +000010966 checkProgress(pCheck);
10967 if( pCheck->mxErr==0 ) goto end_of_check;
drhd9cb6ac2005-10-20 07:28:17 +000010968 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +000010969 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +000010970 if( iPage==0 ) return 0;
drh867db832014-09-26 02:41:05 +000010971 if( checkRef(pCheck, iPage) ) return 0;
drhabc38152020-07-22 13:38:04 +000010972 pCheck->zPfx = "Page %u: ";
drh867db832014-09-26 02:41:05 +000010973 pCheck->v1 = iPage;
drhabc38152020-07-22 13:38:04 +000010974 if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
drh867db832014-09-26 02:41:05 +000010975 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +000010976 "unable to get the page. error code=%d", rc);
drh867db832014-09-26 02:41:05 +000010977 goto end_of_check;
drh5eddca62001-06-30 21:53:53 +000010978 }
danielk197793caf5a2009-07-11 06:55:33 +000010979
10980 /* Clear MemPage.isInit to make sure the corruption detection code in
10981 ** btreeInitPage() is executed. */
drh72e191e2015-07-04 11:14:20 +000010982 savedIsInit = pPage->isInit;
danielk197793caf5a2009-07-11 06:55:33 +000010983 pPage->isInit = 0;
danielk197730548662009-07-09 05:07:37 +000010984 if( (rc = btreeInitPage(pPage))!=0 ){
drh64022502009-01-09 14:11:04 +000010985 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
drh867db832014-09-26 02:41:05 +000010986 checkAppendMsg(pCheck,
danielk197730548662009-07-09 05:07:37 +000010987 "btreeInitPage() returns error code %d", rc);
drh867db832014-09-26 02:41:05 +000010988 goto end_of_check;
drh5eddca62001-06-30 21:53:53 +000010989 }
drhb0ea9432019-02-09 21:06:40 +000010990 if( (rc = btreeComputeFreeSpace(pPage))!=0 ){
10991 assert( rc==SQLITE_CORRUPT );
10992 checkAppendMsg(pCheck, "free space corruption", rc);
10993 goto end_of_check;
10994 }
drhcbc6b712015-07-02 16:17:30 +000010995 data = pPage->aData;
10996 hdr = pPage->hdrOffset;
drh5eddca62001-06-30 21:53:53 +000010997
drhcbc6b712015-07-02 16:17:30 +000010998 /* Set up for cell analysis */
drhabc38152020-07-22 13:38:04 +000010999 pCheck->zPfx = "On tree page %u cell %d: ";
drhcbc6b712015-07-02 16:17:30 +000011000 contentOffset = get2byteNotZero(&data[hdr+5]);
11001 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
11002
11003 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
11004 ** number of cells on the page. */
11005 nCell = get2byte(&data[hdr+3]);
11006 assert( pPage->nCell==nCell );
11007
11008 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
11009 ** immediately follows the b-tree page header. */
11010 cellStart = hdr + 12 - 4*pPage->leaf;
11011 assert( pPage->aCellIdx==&data[cellStart] );
11012 pCellIdx = &data[cellStart + 2*(nCell-1)];
11013
11014 if( !pPage->leaf ){
11015 /* Analyze the right-child page of internal pages */
11016 pgno = get4byte(&data[hdr+8]);
11017#ifndef SQLITE_OMIT_AUTOVACUUM
11018 if( pBt->autoVacuum ){
drhabc38152020-07-22 13:38:04 +000011019 pCheck->zPfx = "On page %u at right child: ";
drhcbc6b712015-07-02 16:17:30 +000011020 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
11021 }
11022#endif
11023 depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
11024 keyCanBeEqual = 0;
11025 }else{
11026 /* For leaf pages, the coverage check will occur in the same loop
11027 ** as the other cell checks, so initialize the heap. */
11028 heap = pCheck->heap;
11029 heap[0] = 0;
drhcbc6b712015-07-02 16:17:30 +000011030 }
11031
11032 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
11033 ** integer offsets to the cell contents. */
11034 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
drh6f11bef2004-05-13 01:12:56 +000011035 CellInfo info;
drh5eddca62001-06-30 21:53:53 +000011036
drhcbc6b712015-07-02 16:17:30 +000011037 /* Check cell size */
drh867db832014-09-26 02:41:05 +000011038 pCheck->v2 = i;
drhcbc6b712015-07-02 16:17:30 +000011039 assert( pCellIdx==&data[cellStart + i*2] );
11040 pc = get2byteAligned(pCellIdx);
11041 pCellIdx -= 2;
11042 if( pc<contentOffset || pc>usableSize-4 ){
11043 checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
11044 pc, contentOffset, usableSize-4);
11045 doCoverageCheck = 0;
11046 continue;
shaneh195475d2010-02-19 04:28:08 +000011047 }
drhcbc6b712015-07-02 16:17:30 +000011048 pCell = &data[pc];
11049 pPage->xParseCell(pPage, pCell, &info);
11050 if( pc+info.nSize>usableSize ){
11051 checkAppendMsg(pCheck, "Extends off end of page");
11052 doCoverageCheck = 0;
11053 continue;
11054 }
11055
11056 /* Check for integer primary key out of range */
11057 if( pPage->intKey ){
11058 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
11059 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
11060 }
11061 maxKey = info.nKey;
dan4b2667c2017-05-01 18:24:01 +000011062 keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
drhcbc6b712015-07-02 16:17:30 +000011063 }
11064
11065 /* Check the content overflow list */
11066 if( info.nPayload>info.nLocal ){
drheaac9992019-02-26 16:17:06 +000011067 u32 nPage; /* Number of pages on the overflow chain */
drhcbc6b712015-07-02 16:17:30 +000011068 Pgno pgnoOvfl; /* First page of the overflow chain */
drh45ac1c72015-12-18 03:59:16 +000011069 assert( pc + info.nSize - 4 <= usableSize );
drhcbc6b712015-07-02 16:17:30 +000011070 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
drh45ac1c72015-12-18 03:59:16 +000011071 pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
danielk1977afcdd022004-10-31 16:25:42 +000011072#ifndef SQLITE_OMIT_AUTOVACUUM
11073 if( pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +000011074 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
danielk1977afcdd022004-10-31 16:25:42 +000011075 }
11076#endif
drh867db832014-09-26 02:41:05 +000011077 checkList(pCheck, 0, pgnoOvfl, nPage);
drh5eddca62001-06-30 21:53:53 +000011078 }
11079
drhda200cc2004-05-09 11:51:38 +000011080 if( !pPage->leaf ){
drhcbc6b712015-07-02 16:17:30 +000011081 /* Check sanity of left child page for internal pages */
drh43605152004-05-29 21:46:49 +000011082 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +000011083#ifndef SQLITE_OMIT_AUTOVACUUM
11084 if( pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +000011085 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
danielk1977afcdd022004-10-31 16:25:42 +000011086 }
11087#endif
drhcbc6b712015-07-02 16:17:30 +000011088 d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
11089 keyCanBeEqual = 0;
11090 if( d2!=depth ){
drh867db832014-09-26 02:41:05 +000011091 checkAppendMsg(pCheck, "Child page depth differs");
drhcbc6b712015-07-02 16:17:30 +000011092 depth = d2;
drhda200cc2004-05-09 11:51:38 +000011093 }
drhcbc6b712015-07-02 16:17:30 +000011094 }else{
11095 /* Populate the coverage-checking heap for leaf pages */
11096 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
drh5eddca62001-06-30 21:53:53 +000011097 }
drh5eddca62001-06-30 21:53:53 +000011098 }
drhcbc6b712015-07-02 16:17:30 +000011099 *piMinKey = maxKey;
shaneh195475d2010-02-19 04:28:08 +000011100
drh5eddca62001-06-30 21:53:53 +000011101 /* Check for complete coverage of the page
11102 */
drh867db832014-09-26 02:41:05 +000011103 pCheck->zPfx = 0;
drhcbc6b712015-07-02 16:17:30 +000011104 if( doCoverageCheck && pCheck->mxErr>0 ){
11105 /* For leaf pages, the min-heap has already been initialized and the
11106 ** cells have already been inserted. But for internal pages, that has
11107 ** not yet been done, so do it now */
11108 if( !pPage->leaf ){
11109 heap = pCheck->heap;
11110 heap[0] = 0;
drhcbc6b712015-07-02 16:17:30 +000011111 for(i=nCell-1; i>=0; i--){
drh1910def2015-07-02 16:29:56 +000011112 u32 size;
11113 pc = get2byteAligned(&data[cellStart+i*2]);
11114 size = pPage->xCellSize(pPage, &data[pc]);
drh67731a92015-04-16 11:56:03 +000011115 btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
danielk19777701e812005-01-10 12:59:51 +000011116 }
drh2e38c322004-09-03 18:38:44 +000011117 }
drhcbc6b712015-07-02 16:17:30 +000011118 /* Add the freeblocks to the min-heap
11119 **
11120 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
drhfdab0262014-11-20 15:30:50 +000011121 ** is the offset of the first freeblock, or zero if there are no
drhcbc6b712015-07-02 16:17:30 +000011122 ** freeblocks on the page.
11123 */
drh8c2bbb62009-07-10 02:52:20 +000011124 i = get2byte(&data[hdr+1]);
11125 while( i>0 ){
11126 int size, j;
drh5860a612019-02-12 16:58:26 +000011127 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
drh8c2bbb62009-07-10 02:52:20 +000011128 size = get2byte(&data[i+2]);
drh5860a612019-02-12 16:58:26 +000011129 assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
drhe56d4302015-07-08 01:22:52 +000011130 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
drhfdab0262014-11-20 15:30:50 +000011131 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
11132 ** big-endian integer which is the offset in the b-tree page of the next
11133 ** freeblock in the chain, or zero if the freeblock is the last on the
11134 ** chain. */
drh8c2bbb62009-07-10 02:52:20 +000011135 j = get2byte(&data[i]);
drhfdab0262014-11-20 15:30:50 +000011136 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
11137 ** increasing offset. */
drh5860a612019-02-12 16:58:26 +000011138 assert( j==0 || j>i+size ); /* Enforced by btreeComputeFreeSpace() */
11139 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
drh8c2bbb62009-07-10 02:52:20 +000011140 i = j;
drh2e38c322004-09-03 18:38:44 +000011141 }
drhcbc6b712015-07-02 16:17:30 +000011142 /* Analyze the min-heap looking for overlap between cells and/or
11143 ** freeblocks, and counting the number of untracked bytes in nFrag.
drhd2dc87f2015-07-02 19:47:08 +000011144 **
11145 ** Each min-heap entry is of the form: (start_address<<16)|end_address.
11146 ** There is an implied first entry the covers the page header, the cell
11147 ** pointer index, and the gap between the cell pointer index and the start
11148 ** of cell content.
11149 **
11150 ** The loop below pulls entries from the min-heap in order and compares
11151 ** the start_address against the previous end_address. If there is an
11152 ** overlap, that means bytes are used multiple times. If there is a gap,
11153 ** that gap is added to the fragmentation count.
drhcbc6b712015-07-02 16:17:30 +000011154 */
11155 nFrag = 0;
drhd2dc87f2015-07-02 19:47:08 +000011156 prev = contentOffset - 1; /* Implied first min-heap entry */
drh67731a92015-04-16 11:56:03 +000011157 while( btreeHeapPull(heap,&x) ){
drhd2dc87f2015-07-02 19:47:08 +000011158 if( (prev&0xffff)>=(x>>16) ){
drh867db832014-09-26 02:41:05 +000011159 checkAppendMsg(pCheck,
drhabc38152020-07-22 13:38:04 +000011160 "Multiple uses for byte %u of page %u", x>>16, iPage);
drh2e38c322004-09-03 18:38:44 +000011161 break;
drh67731a92015-04-16 11:56:03 +000011162 }else{
drhcbc6b712015-07-02 16:17:30 +000011163 nFrag += (x>>16) - (prev&0xffff) - 1;
drh67731a92015-04-16 11:56:03 +000011164 prev = x;
drh2e38c322004-09-03 18:38:44 +000011165 }
11166 }
drhcbc6b712015-07-02 16:17:30 +000011167 nFrag += usableSize - (prev&0xffff) - 1;
drhfdab0262014-11-20 15:30:50 +000011168 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
11169 ** is stored in the fifth field of the b-tree page header.
11170 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
11171 ** number of fragmented free bytes within the cell content area.
11172 */
drhcbc6b712015-07-02 16:17:30 +000011173 if( heap[0]==0 && nFrag!=data[hdr+7] ){
drh867db832014-09-26 02:41:05 +000011174 checkAppendMsg(pCheck,
drhabc38152020-07-22 13:38:04 +000011175 "Fragmentation of %d bytes reported as %d on page %u",
drhcbc6b712015-07-02 16:17:30 +000011176 nFrag, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +000011177 }
11178 }
drh867db832014-09-26 02:41:05 +000011179
11180end_of_check:
drh72e191e2015-07-04 11:14:20 +000011181 if( !doCoverageCheck ) pPage->isInit = savedIsInit;
drhe05b3f82015-07-01 17:53:49 +000011182 releasePage(pPage);
drh867db832014-09-26 02:41:05 +000011183 pCheck->zPfx = saved_zPfx;
11184 pCheck->v1 = saved_v1;
11185 pCheck->v2 = saved_v2;
drhda200cc2004-05-09 11:51:38 +000011186 return depth+1;
drh5eddca62001-06-30 21:53:53 +000011187}
drhb7f91642004-10-31 02:22:47 +000011188#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +000011189
drhb7f91642004-10-31 02:22:47 +000011190#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +000011191/*
11192** This routine does a complete check of the given BTree file. aRoot[] is
11193** an array of pages numbers were each page number is the root page of
11194** a table. nRoot is the number of entries in aRoot.
11195**
danielk19773509a652009-07-06 18:56:13 +000011196** A read-only or read-write transaction must be opened before calling
11197** this function.
11198**
drhc890fec2008-08-01 20:10:08 +000011199** Write the number of error seen in *pnErr. Except for some memory
drhe43ba702008-12-05 22:40:08 +000011200** allocation errors, an error message held in memory obtained from
drhc890fec2008-08-01 20:10:08 +000011201** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
drhe43ba702008-12-05 22:40:08 +000011202** returned. If a memory allocation error occurs, NULL is returned.
drh17d2d592020-07-23 00:45:06 +000011203**
11204** If the first entry in aRoot[] is 0, that indicates that the list of
11205** root pages is incomplete. This is a "partial integrity-check". This
11206** happens when performing an integrity check on a single table. The
11207** zero is skipped, of course. But in addition, the freelist checks
11208** and the checks to make sure every page is referenced are also skipped,
11209** since obviously it is not possible to know which pages are covered by
11210** the unverified btrees. Except, if aRoot[1] is 1, then the freelist
11211** checks are still performed.
drh5eddca62001-06-30 21:53:53 +000011212*/
drh5dd74bf2023-01-11 16:17:31 +000011213int sqlite3BtreeIntegrityCheck(
drh21f6daa2019-10-11 14:21:48 +000011214 sqlite3 *db, /* Database connection that is running the check */
drh1dcdbc02007-01-27 02:24:54 +000011215 Btree *p, /* The btree to be checked */
drhabc38152020-07-22 13:38:04 +000011216 Pgno *aRoot, /* An array of root pages numbers for individual trees */
drh1dcdbc02007-01-27 02:24:54 +000011217 int nRoot, /* Number of entries in aRoot[] */
11218 int mxErr, /* Stop reporting errors after this many */
drh5dd74bf2023-01-11 16:17:31 +000011219 int *pnErr, /* OUT: Write number of errors seen to this variable */
11220 char **pzOut /* OUT: Write the error message string here */
drh1dcdbc02007-01-27 02:24:54 +000011221){
danielk197789d40042008-11-17 14:20:56 +000011222 Pgno i;
drhaaab5722002-02-19 13:39:21 +000011223 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +000011224 BtShared *pBt = p->pBt;
drhf10ce632019-01-11 14:46:44 +000011225 u64 savedDbFlags = pBt->db->flags;
drhf089aa42008-07-08 19:34:06 +000011226 char zErr[100];
drh17d2d592020-07-23 00:45:06 +000011227 int bPartial = 0; /* True if not checking all btrees */
11228 int bCkFreelist = 1; /* True to scan the freelist */
drhcbc6b712015-07-02 16:17:30 +000011229 VVA_ONLY( int nRef );
drh17d2d592020-07-23 00:45:06 +000011230 assert( nRoot>0 );
11231
11232 /* aRoot[0]==0 means this is a partial check */
11233 if( aRoot[0]==0 ){
11234 assert( nRoot>1 );
11235 bPartial = 1;
11236 if( aRoot[1]!=1 ) bCkFreelist = 0;
11237 }
drh5eddca62001-06-30 21:53:53 +000011238
drhd677b3d2007-08-20 22:48:41 +000011239 sqlite3BtreeEnter(p);
danielk19773509a652009-07-06 18:56:13 +000011240 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
drhcc5f8a42016-02-06 22:32:06 +000011241 VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
11242 assert( nRef>=0 );
drh5dd74bf2023-01-11 16:17:31 +000011243 memset(&sCheck, 0, sizeof(sCheck));
drh21f6daa2019-10-11 14:21:48 +000011244 sCheck.db = db;
drh5eddca62001-06-30 21:53:53 +000011245 sCheck.pBt = pBt;
11246 sCheck.pPager = pBt->pPager;
drhb1299152010-03-30 22:58:33 +000011247 sCheck.nPage = btreePagecount(sCheck.pBt);
drh1dcdbc02007-01-27 02:24:54 +000011248 sCheck.mxErr = mxErr;
drhe05b3f82015-07-01 17:53:49 +000011249 sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
drh5f4a6862016-01-30 12:50:25 +000011250 sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
drh0de8c112002-07-06 16:32:14 +000011251 if( sCheck.nPage==0 ){
drhe05b3f82015-07-01 17:53:49 +000011252 goto integrity_ck_cleanup;
drh0de8c112002-07-06 16:32:14 +000011253 }
dan1235bb12012-04-03 17:43:28 +000011254
11255 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
11256 if( !sCheck.aPgRef ){
drh5dd74bf2023-01-11 16:17:31 +000011257 checkOom(&sCheck);
drhe05b3f82015-07-01 17:53:49 +000011258 goto integrity_ck_cleanup;
danielk1977ac245ec2005-01-14 13:50:11 +000011259 }
drhe05b3f82015-07-01 17:53:49 +000011260 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
11261 if( sCheck.heap==0 ){
drh5dd74bf2023-01-11 16:17:31 +000011262 checkOom(&sCheck);
drhe05b3f82015-07-01 17:53:49 +000011263 goto integrity_ck_cleanup;
11264 }
11265
drh42cac6d2004-11-20 20:31:11 +000011266 i = PENDING_BYTE_PAGE(pBt);
dan1235bb12012-04-03 17:43:28 +000011267 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
drh5eddca62001-06-30 21:53:53 +000011268
11269 /* Check the integrity of the freelist
11270 */
drh17d2d592020-07-23 00:45:06 +000011271 if( bCkFreelist ){
11272 sCheck.zPfx = "Main freelist: ";
11273 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
11274 get4byte(&pBt->pPage1->aData[36]));
11275 sCheck.zPfx = 0;
11276 }
drh5eddca62001-06-30 21:53:53 +000011277
11278 /* Check all the tables.
11279 */
drh040d77a2018-07-20 15:44:09 +000011280#ifndef SQLITE_OMIT_AUTOVACUUM
drh17d2d592020-07-23 00:45:06 +000011281 if( !bPartial ){
11282 if( pBt->autoVacuum ){
drhed109c02020-07-23 09:14:25 +000011283 Pgno mx = 0;
11284 Pgno mxInHdr;
drh17d2d592020-07-23 00:45:06 +000011285 for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
11286 mxInHdr = get4byte(&pBt->pPage1->aData[52]);
11287 if( mx!=mxInHdr ){
11288 checkAppendMsg(&sCheck,
11289 "max rootpage (%d) disagrees with header (%d)",
11290 mx, mxInHdr
11291 );
11292 }
11293 }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
drh040d77a2018-07-20 15:44:09 +000011294 checkAppendMsg(&sCheck,
drh17d2d592020-07-23 00:45:06 +000011295 "incremental_vacuum enabled with a max rootpage of zero"
drh040d77a2018-07-20 15:44:09 +000011296 );
11297 }
drh040d77a2018-07-20 15:44:09 +000011298 }
11299#endif
drhcbc6b712015-07-02 16:17:30 +000011300 testcase( pBt->db->flags & SQLITE_CellSizeCk );
drhd5b44d62018-12-06 17:06:02 +000011301 pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
danielk197789d40042008-11-17 14:20:56 +000011302 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
drhcbc6b712015-07-02 16:17:30 +000011303 i64 notUsed;
drh4ff6dfa2002-03-03 23:06:00 +000011304 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +000011305#ifndef SQLITE_OMIT_AUTOVACUUM
drh17d2d592020-07-23 00:45:06 +000011306 if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){
drh867db832014-09-26 02:41:05 +000011307 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +000011308 }
11309#endif
drhcbc6b712015-07-02 16:17:30 +000011310 checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
drh5eddca62001-06-30 21:53:53 +000011311 }
drhcbc6b712015-07-02 16:17:30 +000011312 pBt->db->flags = savedDbFlags;
drh5eddca62001-06-30 21:53:53 +000011313
drh17d2d592020-07-23 00:45:06 +000011314 if( !bPartial ){
dan1098bdb2020-07-30 19:19:12 +000011315 /* Make sure every page in the file is referenced. Skip this if the
11316 ** database is currently being written by a CONCURRENT transaction (it
11317 ** may fail as pages that were part of the free-list when the transaction
11318 ** was opened cannot be counted). */
11319 for(i=1; ISCONCURRENT==0 && i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +000011320#ifdef SQLITE_OMIT_AUTOVACUUM
drh17d2d592020-07-23 00:45:06 +000011321 if( getPageReferenced(&sCheck, i)==0 ){
11322 checkAppendMsg(&sCheck, "Page %d is never used", i);
11323 }
danielk1977afcdd022004-10-31 16:25:42 +000011324#else
drh17d2d592020-07-23 00:45:06 +000011325 /* If the database supports auto-vacuum, make sure no tables contain
11326 ** references to pointer-map pages.
11327 */
11328 if( getPageReferenced(&sCheck, i)==0 &&
11329 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
11330 checkAppendMsg(&sCheck, "Page %d is never used", i);
11331 }
11332 if( getPageReferenced(&sCheck, i)!=0 &&
11333 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
11334 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
11335 }
danielk1977afcdd022004-10-31 16:25:42 +000011336#endif
drh47eb5612020-08-10 21:01:32 +000011337 }
drh5eddca62001-06-30 21:53:53 +000011338 }
11339
drh5eddca62001-06-30 21:53:53 +000011340 /* Clean up and report errors.
11341 */
drhe05b3f82015-07-01 17:53:49 +000011342integrity_ck_cleanup:
11343 sqlite3PageFree(sCheck.heap);
dan1235bb12012-04-03 17:43:28 +000011344 sqlite3_free(sCheck.aPgRef);
drh1dcdbc02007-01-27 02:24:54 +000011345 *pnErr = sCheck.nErr;
drh5dd74bf2023-01-11 16:17:31 +000011346 if( sCheck.nErr==0 ){
11347 sqlite3_str_reset(&sCheck.errMsg);
11348 *pzOut = 0;
11349 }else{
11350 *pzOut = sqlite3StrAccumFinish(&sCheck.errMsg);
11351 }
drhe05b3f82015-07-01 17:53:49 +000011352 /* Make sure this analysis did not leave any unref() pages. */
11353 assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
11354 sqlite3BtreeLeave(p);
drh5dd74bf2023-01-11 16:17:31 +000011355 return sCheck.rc;
drh5eddca62001-06-30 21:53:53 +000011356}
drhb7f91642004-10-31 02:22:47 +000011357#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +000011358
drh73509ee2003-04-06 20:44:45 +000011359/*
drhd4e0bb02012-05-27 01:19:04 +000011360** Return the full pathname of the underlying database file. Return
11361** an empty string if the database is in-memory or a TEMP database.
drhd0679ed2007-08-28 22:24:34 +000011362**
11363** The pager filename is invariant as long as the pager is
11364** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +000011365*/
danielk1977aef0bf62005-12-30 16:28:01 +000011366const char *sqlite3BtreeGetFilename(Btree *p){
11367 assert( p->pBt->pPager!=0 );
drhd4e0bb02012-05-27 01:19:04 +000011368 return sqlite3PagerFilename(p->pBt->pPager, 1);
drh73509ee2003-04-06 20:44:45 +000011369}
11370
11371/*
danielk19775865e3d2004-06-14 06:03:57 +000011372** Return the pathname of the journal file for this database. The return
11373** value of this routine is the same regardless of whether the journal file
11374** has been created or not.
drhd0679ed2007-08-28 22:24:34 +000011375**
11376** The pager journal filename is invariant as long as the pager is
11377** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +000011378*/
danielk1977aef0bf62005-12-30 16:28:01 +000011379const char *sqlite3BtreeGetJournalname(Btree *p){
11380 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +000011381 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +000011382}
11383
danielk19771d850a72004-05-31 08:26:49 +000011384/*
drh99744fa2020-08-25 19:09:07 +000011385** Return one of SQLITE_TXN_NONE, SQLITE_TXN_READ, or SQLITE_TXN_WRITE
11386** to describe the current transaction state of Btree p.
danielk19771d850a72004-05-31 08:26:49 +000011387*/
drh99744fa2020-08-25 19:09:07 +000011388int sqlite3BtreeTxnState(Btree *p){
drhe5fe6902007-12-07 18:55:28 +000011389 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
drh99744fa2020-08-25 19:09:07 +000011390 return p ? p->inTrans : 0;
danielk19771d850a72004-05-31 08:26:49 +000011391}
11392
dana550f2d2010-08-02 10:47:05 +000011393#ifndef SQLITE_OMIT_WAL
11394/*
11395** Run a checkpoint on the Btree passed as the first argument.
11396**
11397** Return SQLITE_LOCKED if this or any other connection has an open
11398** transaction on the shared-cache the argument Btree is connected to.
dana58f26f2010-11-16 18:56:51 +000011399**
dancdc1f042010-11-18 12:11:05 +000011400** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
dana550f2d2010-08-02 10:47:05 +000011401*/
dancdc1f042010-11-18 12:11:05 +000011402int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
dana550f2d2010-08-02 10:47:05 +000011403 int rc = SQLITE_OK;
11404 if( p ){
11405 BtShared *pBt = p->pBt;
11406 sqlite3BtreeEnter(p);
11407 if( pBt->inTransaction!=TRANS_NONE ){
11408 rc = SQLITE_LOCKED;
11409 }else{
dan7fb89902016-08-12 16:21:15 +000011410 rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
dana550f2d2010-08-02 10:47:05 +000011411 }
11412 sqlite3BtreeLeave(p);
11413 }
11414 return rc;
11415}
11416#endif
11417
danielk19771d850a72004-05-31 08:26:49 +000011418/*
drh99744fa2020-08-25 19:09:07 +000011419** Return true if there is currently a backup running on Btree p.
danielk19772372c2b2006-06-27 16:34:56 +000011420*/
danielk197704103022009-02-03 16:51:24 +000011421int sqlite3BtreeIsInBackup(Btree *p){
11422 assert( p );
11423 assert( sqlite3_mutex_held(p->db->mutex) );
11424 return p->nBackup!=0;
11425}
11426
danielk19772372c2b2006-06-27 16:34:56 +000011427/*
danielk1977da184232006-01-05 11:34:32 +000011428** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +000011429** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +000011430** purposes (for example, to store a high-level schema associated with
11431** the shared-btree). The btree layer manages reference counting issues.
11432**
11433** The first time this is called on a shared-btree, nBytes bytes of memory
11434** are allocated, zeroed, and returned to the caller. For each subsequent
11435** call the nBytes parameter is ignored and a pointer to the same blob
11436** of memory returned.
11437**
danielk1977171bfed2008-06-23 09:50:50 +000011438** If the nBytes parameter is 0 and the blob of memory has not yet been
11439** allocated, a null pointer is returned. If the blob has already been
11440** allocated, it is returned as normal.
11441**
danielk1977da184232006-01-05 11:34:32 +000011442** Just before the shared-btree is closed, the function passed as the
11443** xFree argument when the memory allocation was made is invoked on the
drh4fa7d7c2011-04-03 02:41:00 +000011444** blob of allocated memory. The xFree function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +000011445** on the memory, the btree layer does that.
11446*/
11447void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
11448 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +000011449 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +000011450 if( !pBt->pSchema && nBytes ){
drhb9755982010-07-24 16:34:37 +000011451 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
danielk1977da184232006-01-05 11:34:32 +000011452 pBt->xFreeSchema = xFree;
11453 }
drh27641702007-08-22 02:56:42 +000011454 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +000011455 return pBt->pSchema;
11456}
11457
danielk1977c87d34d2006-01-06 13:00:28 +000011458/*
danielk1977404ca072009-03-16 13:19:36 +000011459** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
11460** btree as the argument handle holds an exclusive lock on the
drh1e32bed2020-06-19 13:33:53 +000011461** sqlite_schema table. Otherwise SQLITE_OK.
danielk1977c87d34d2006-01-06 13:00:28 +000011462*/
11463int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +000011464 int rc;
drhe5fe6902007-12-07 18:55:28 +000011465 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +000011466 sqlite3BtreeEnter(p);
drh346a70c2020-06-15 20:27:35 +000011467 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
danielk1977404ca072009-03-16 13:19:36 +000011468 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
drh27641702007-08-22 02:56:42 +000011469 sqlite3BtreeLeave(p);
11470 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +000011471}
11472
drha154dcd2006-03-22 22:10:07 +000011473
11474#ifndef SQLITE_OMIT_SHARED_CACHE
11475/*
11476** Obtain a lock on the table whose root page is iTab. The
11477** lock is a write lock if isWritelock is true or a read lock
11478** if it is false.
11479*/
danielk1977c00da102006-01-07 13:21:04 +000011480int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +000011481 int rc = SQLITE_OK;
danielk1977602b4662009-07-02 07:47:33 +000011482 assert( p->inTrans!=TRANS_NONE );
drh6a9ad3d2008-04-02 16:29:30 +000011483 if( p->sharable ){
11484 u8 lockType = READ_LOCK + isWriteLock;
11485 assert( READ_LOCK+1==WRITE_LOCK );
11486 assert( isWriteLock==0 || isWriteLock==1 );
danielk1977602b4662009-07-02 07:47:33 +000011487
drh6a9ad3d2008-04-02 16:29:30 +000011488 sqlite3BtreeEnter(p);
drhc25eabe2009-02-24 18:57:31 +000011489 rc = querySharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +000011490 if( rc==SQLITE_OK ){
drhc25eabe2009-02-24 18:57:31 +000011491 rc = setSharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +000011492 }
11493 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +000011494 }
11495 return rc;
11496}
drha154dcd2006-03-22 22:10:07 +000011497#endif
danielk1977b82e7ed2006-01-11 14:09:31 +000011498
danielk1977b4e9af92007-05-01 17:49:49 +000011499#ifndef SQLITE_OMIT_INCRBLOB
11500/*
11501** Argument pCsr must be a cursor opened for writing on an
11502** INTKEY table currently pointing at a valid table entry.
11503** This function modifies the data stored as part of that entry.
danielk1977ecaecf92009-07-08 08:05:35 +000011504**
11505** Only the data content may only be modified, it is not possible to
11506** change the length of the data stored. If this function is called with
11507** parameters that attempt to write past the end of the existing data,
11508** no modifications are made and SQLITE_CORRUPT is returned.
danielk1977b4e9af92007-05-01 17:49:49 +000011509*/
danielk1977dcbb5d32007-05-04 18:36:44 +000011510int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
danielk1977c9000e62009-07-08 13:55:28 +000011511 int rc;
dan7a2347e2016-01-07 16:43:54 +000011512 assert( cursorOwnsBtShared(pCsr) );
drhe5fe6902007-12-07 18:55:28 +000011513 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
drh036dbec2014-03-11 23:40:44 +000011514 assert( pCsr->curFlags & BTCF_Incrblob );
danielk19773588ceb2008-06-10 17:30:26 +000011515
danielk1977c9000e62009-07-08 13:55:28 +000011516 rc = restoreCursorPosition(pCsr);
11517 if( rc!=SQLITE_OK ){
11518 return rc;
11519 }
danielk19773588ceb2008-06-10 17:30:26 +000011520 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
11521 if( pCsr->eState!=CURSOR_VALID ){
11522 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +000011523 }
11524
dan227a1c42013-04-03 11:17:39 +000011525 /* Save the positions of all other cursors open on this table. This is
11526 ** required in case any of them are holding references to an xFetch
11527 ** version of the b-tree page modified by the accessPayload call below.
drh370c9f42013-04-03 20:04:04 +000011528 **
drh3f387402014-09-24 01:23:00 +000011529 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
drh370c9f42013-04-03 20:04:04 +000011530 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
11531 ** saveAllCursors can only return SQLITE_OK.
dan227a1c42013-04-03 11:17:39 +000011532 */
drh370c9f42013-04-03 20:04:04 +000011533 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
11534 assert( rc==SQLITE_OK );
dan227a1c42013-04-03 11:17:39 +000011535
danielk1977c9000e62009-07-08 13:55:28 +000011536 /* Check some assumptions:
danielk1977dcbb5d32007-05-04 18:36:44 +000011537 ** (a) the cursor is open for writing,
danielk1977c9000e62009-07-08 13:55:28 +000011538 ** (b) there is a read/write transaction open,
11539 ** (c) the connection holds a write-lock on the table (if required),
11540 ** (d) there are no conflicting read-locks, and
11541 ** (e) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +000011542 */
drh036dbec2014-03-11 23:40:44 +000011543 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
danielk19774f029602009-07-08 18:45:37 +000011544 return SQLITE_READONLY;
11545 }
drhc9166342012-01-05 23:32:06 +000011546 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
11547 && pCsr->pBt->inTransaction==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +000011548 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
11549 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
drh352a35a2017-08-15 03:46:47 +000011550 assert( pCsr->pPage->intKey );
danielk1977b4e9af92007-05-01 17:49:49 +000011551
drhfb192682009-07-11 18:26:28 +000011552 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
danielk1977b4e9af92007-05-01 17:49:49 +000011553}
danielk19772dec9702007-05-02 16:48:37 +000011554
11555/*
dan5a500af2014-03-11 20:33:04 +000011556** Mark this cursor as an incremental blob cursor.
danielk19772dec9702007-05-02 16:48:37 +000011557*/
dan5a500af2014-03-11 20:33:04 +000011558void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
drh036dbec2014-03-11 23:40:44 +000011559 pCur->curFlags |= BTCF_Incrblob;
drh69180952015-06-25 13:03:10 +000011560 pCur->pBtree->hasIncrblobCur = 1;
danielk19772dec9702007-05-02 16:48:37 +000011561}
danielk1977b4e9af92007-05-01 17:49:49 +000011562#endif
dane04dc882010-04-20 18:53:15 +000011563
11564/*
11565** Set both the "read version" (single byte at byte offset 18) and
11566** "write version" (single byte at byte offset 19) fields in the database
11567** header to iVersion.
11568*/
11569int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
11570 BtShared *pBt = pBtree->pBt;
11571 int rc; /* Return code */
11572
dane04dc882010-04-20 18:53:15 +000011573 assert( iVersion==1 || iVersion==2 );
11574
danb9780022010-04-21 18:37:57 +000011575 /* If setting the version fields to 1, do not automatically open the
11576 ** WAL connection, even if the version fields are currently set to 2.
11577 */
drhc9166342012-01-05 23:32:06 +000011578 pBt->btsFlags &= ~BTS_NO_WAL;
11579 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
danb9780022010-04-21 18:37:57 +000011580
drhbb2d9b12018-06-06 16:28:40 +000011581 rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
dane04dc882010-04-20 18:53:15 +000011582 if( rc==SQLITE_OK ){
11583 u8 *aData = pBt->pPage1->aData;
danb9780022010-04-21 18:37:57 +000011584 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
drhbb2d9b12018-06-06 16:28:40 +000011585 rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
danb9780022010-04-21 18:37:57 +000011586 if( rc==SQLITE_OK ){
11587 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
11588 if( rc==SQLITE_OK ){
11589 aData[18] = (u8)iVersion;
11590 aData[19] = (u8)iVersion;
11591 }
11592 }
11593 }
dane04dc882010-04-20 18:53:15 +000011594 }
11595
drhc9166342012-01-05 23:32:06 +000011596 pBt->btsFlags &= ~BTS_NO_WAL;
dane04dc882010-04-20 18:53:15 +000011597 return rc;
11598}
dan428c2182012-08-06 18:50:11 +000011599
drhe0997b32015-03-20 14:57:50 +000011600/*
11601** Return true if the cursor has a hint specified. This routine is
11602** only used from within assert() statements
11603*/
11604int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
11605 return (pCsr->hints & mask)!=0;
11606}
drhe0997b32015-03-20 14:57:50 +000011607
drh781597f2014-05-21 08:21:07 +000011608/*
11609** Return true if the given Btree is read-only.
11610*/
11611int sqlite3BtreeIsReadonly(Btree *p){
11612 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
11613}
drhdef68892014-11-04 12:11:23 +000011614
11615/*
11616** Return the size of the header added to each page by this module.
11617*/
drh37c057b2014-12-30 00:57:29 +000011618int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
dan7b3d71e2015-08-19 20:27:05 +000011619
danf5cebf72015-08-22 17:28:55 +000011620/*
11621** This function is called to ensure that all locks required to commit the
11622** current write-transaction to the database file are held. If the db is
11623** in rollback mode, this means the EXCLUSIVE lock on the database file.
11624**
danbf3cf572015-08-24 19:56:04 +000011625** Or, if this is an CONCURRENT transaction on a wal-mode database, the WRITER
danf5cebf72015-08-22 17:28:55 +000011626** lock on the wal file. In this case this function also checks that the
danbf3cf572015-08-24 19:56:04 +000011627** CONCURRENT transaction can be safely committed (does not commit with any
danf5cebf72015-08-22 17:28:55 +000011628** other transaction committed since it was opened).
11629**
11630** SQLITE_OK is returned if successful. SQLITE_BUSY if the required locks
11631** cannot be obtained due to a conflicting lock. If the locks cannot be
danbf3cf572015-08-24 19:56:04 +000011632** obtained for an CONCURRENT transaction due to a conflict with an already
danf5cebf72015-08-22 17:28:55 +000011633** committed transaction, SQLITE_BUSY_SNAPSHOT is returned. Otherwise, if
11634** some other error (OOM, IO, etc.) occurs, the relevant SQLite error code
11635** is returned.
11636*/
dan7b3d71e2015-08-19 20:27:05 +000011637int sqlite3BtreeExclusiveLock(Btree *p){
11638 int rc;
dan995b2452017-05-29 19:23:56 +000011639 Pgno pgno = 0;
dan7b3d71e2015-08-19 20:27:05 +000011640 BtShared *pBt = p->pBt;
11641 assert( p->inTrans==TRANS_WRITE && pBt->pPage1 );
11642 sqlite3BtreeEnter(p);
dan9a477712020-07-16 20:24:11 +000011643 rc = sqlite3PagerExclusiveLock(pBt->pPager,
11644 (p->db->eConcurrent==CONCURRENT_SCHEMA) ? 0 : pBt->pPage1->pDbPage,
11645 &pgno
11646 );
drh7365bcd2017-07-20 18:28:33 +000011647#ifdef SQLITE_OMIT_CONCURRENT
11648 assert( pgno==0 );
11649#else
dan995b2452017-05-29 19:23:56 +000011650 if( rc==SQLITE_BUSY_SNAPSHOT && pgno ){
11651 PgHdr *pPg = 0;
11652 int rc2 = sqlite3PagerGet(pBt->pPager, pgno, &pPg, 0);
11653 if( rc2==SQLITE_OK ){
11654 int bWrite = -1;
11655 const char *zObj = 0;
11656 const char *zTab = 0;
danb7ee5662018-05-15 11:28:36 +000011657 char zContent[17];
dan995b2452017-05-29 19:23:56 +000011658
11659 if( pPg ){
11660 Pgno pgnoRoot = 0;
11661 HashElem *pE;
11662 Schema *pSchema;
danb7ee5662018-05-15 11:28:36 +000011663 u8 *aData = (u8*)sqlite3PagerGetData(pPg);
11664 int i;
11665 for(i=0; i<8; i++){
11666 static const char hexdigits[] = {
11667 '0', '1', '2', '3', '4', '5', '6', '7',
11668 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
11669 };
11670 zContent[i*2] = hexdigits[(aData[i] >> 4)];
11671 zContent[i*2+1] = hexdigits[(aData[i] & 0xF)];
11672 }
11673 zContent[16] = '\0';
dan995b2452017-05-29 19:23:56 +000011674
11675 pgnoRoot = ((MemPage*)sqlite3PagerGetExtra(pPg))->pgnoRoot;
11676 bWrite = sqlite3PagerIswriteable(pPg);
11677 sqlite3PagerUnref(pPg);
11678
11679 pSchema = sqlite3SchemaGet(p->db, p);
11680 if( pSchema ){
11681 for(pE=sqliteHashFirst(&pSchema->tblHash); pE; pE=sqliteHashNext(pE)){
11682 Table *pTab = (Table *)sqliteHashData(pE);
11683 if( pTab->tnum==(int)pgnoRoot ){
11684 zObj = pTab->zName;
11685 zTab = 0;
11686 }else{
11687 Index *pIdx;
11688 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
11689 if( pIdx->tnum==(int)pgnoRoot ){
11690 zObj = pIdx->zName;
11691 zTab = pTab->zName;
11692 }
11693 }
11694 }
11695 }
11696 }
11697 }
11698
11699 sqlite3_log(SQLITE_OK,
11700 "cannot commit CONCURRENT transaction "
11701 "- conflict at page %d "
danb7ee5662018-05-15 11:28:36 +000011702 "(%s page; part of db %s %s%s%s; content=%s...)",
dan995b2452017-05-29 19:23:56 +000011703 (int)pgno,
11704 (bWrite==0?"read-only":(bWrite>0?"read/write":"unknown")),
11705 (zTab ? "index" : "table"),
danbfbe2b82018-05-15 08:51:05 +000011706 (zTab ? zTab : ""), (zTab ? "." : ""), (zObj ? zObj : "UNKNOWN"),
danb7ee5662018-05-15 11:28:36 +000011707 zContent
dan995b2452017-05-29 19:23:56 +000011708 );
11709 }
11710 }
drh7365bcd2017-07-20 18:28:33 +000011711#endif
dan7b3d71e2015-08-19 20:27:05 +000011712 sqlite3BtreeLeave(p);
11713 return rc;
11714}
danf687ba52016-01-14 15:46:31 +000011715
drh43fa1a52022-12-21 20:07:58 +000011716/*
dan1b3d13e2022-11-28 18:41:41 +000011717** If no transaction is active and the database is not a temp-db, clear
11718** the in-memory pager cache.
11719*/
11720void sqlite3BtreeClearCache(Btree *p){
11721 BtShared *pBt = p->pBt;
11722 if( pBt->inTransaction==TRANS_NONE ){
11723 sqlite3PagerClearCache(pBt->pPager);
11724 }
11725}
11726
drh5a1fb182016-01-08 19:34:39 +000011727#if !defined(SQLITE_OMIT_SHARED_CACHE)
dan20d876f2016-01-07 16:06:22 +000011728/*
11729** Return true if the Btree passed as the only argument is sharable.
11730*/
11731int sqlite3BtreeSharable(Btree *p){
11732 return p->sharable;
11733}
dan272989b2016-07-06 10:12:02 +000011734
11735/*
11736** Return the number of connections to the BtShared object accessed by
11737** the Btree handle passed as the only argument. For private caches
11738** this is always 1. For shared caches it may be 1 or greater.
11739*/
11740int sqlite3BtreeConnectionCount(Btree *p){
11741 testcase( p->sharable );
11742 return p->pBt->nRef;
11743}
drh5a1fb182016-01-08 19:34:39 +000011744#endif