blob: b507102da05039da6fdebd95ecbdb98fb89c8d09 [file] [log] [blame]
drha3152892007-05-05 11:48:52 +00001/*
2** 2004 April 6
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** 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.
10**
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** For a detailed discussion of BTrees, refer to
14**
15** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
16** "Sorting And Searching", pages 473-480. Addison-Wesley
17** Publishing Company, Reading, Massachusetts.
18**
19** The basic idea is that each page of the file contains N database
20** entries and N+1 pointers to subpages.
21**
22** ----------------------------------------------------------------
23** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
24** ----------------------------------------------------------------
25**
26** All of the keys on the page that Ptr(0) points to have values less
27** than Key(0). All of the keys on page Ptr(1) and its subpages have
28** values greater than Key(0) and less than Key(1). All of the keys
29** on Ptr(N) and its subpages have values greater than Key(N-1). And
30** so forth.
31**
32** Finding a particular key requires reading O(log(M)) pages from the
33** disk where M is the number of entries in the tree.
34**
35** In this implementation, a single file can hold one or more separate
36** BTrees. Each BTree is identified by the index of its root page. The
37** key and data for any entry are combined to form the "payload". A
38** fixed amount of payload can be carried directly on the database
39** page. If the payload is larger than the preset amount then surplus
40** bytes are stored on overflow pages. The payload for an entry
41** and the preceding pointer are combined to form a "Cell". Each
42** page has a small header which contains the Ptr(N) pointer and other
43** information such as the size of key and data.
44**
45** FORMAT DETAILS
46**
47** The file is divided into pages. The first page is called page 1,
48** the second is page 2, and so forth. A page number of zero indicates
drhb2eced52010-08-12 02:41:12 +000049** "no such page". The page size can be any power of 2 between 512 and 65536.
drh5bbe5482009-10-27 18:06:10 +000050** Each page can be either a btree page, a freelist page, an overflow
51** page, or a pointer-map page.
drha3152892007-05-05 11:48:52 +000052**
53** The first page is always a btree page. The first 100 bytes of the first
54** page contain a special header (the "file header") that describes the file.
55** The format of the file header is as follows:
56**
57** OFFSET SIZE DESCRIPTION
58** 0 16 Header string: "SQLite format 3\000"
drhe75fb062013-10-01 20:29:30 +000059** 16 2 Page size in bytes. (1 means 65536)
drha3152892007-05-05 11:48:52 +000060** 18 1 File format write version
61** 19 1 File format read version
62** 20 1 Bytes of unused space at the end of each page
drhe75fb062013-10-01 20:29:30 +000063** 21 1 Max embedded payload fraction (must be 64)
64** 22 1 Min embedded payload fraction (must be 32)
65** 23 1 Min leaf payload fraction (must be 32)
drha3152892007-05-05 11:48:52 +000066** 24 4 File change counter
67** 28 4 Reserved for future use
68** 32 4 First freelist page
69** 36 4 Number of freelist pages in the file
70** 40 60 15 4-byte meta values passed to higher layers
71**
drh27731d72009-06-22 12:05:10 +000072** 40 4 Schema cookie
73** 44 4 File format of schema layer
74** 48 4 Size of page cache
75** 52 4 Largest root-page (auto/incr_vacuum)
76** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
77** 60 4 User version
78** 64 4 Incremental vacuum mode
drhe75fb062013-10-01 20:29:30 +000079** 68 4 Application-ID
80** 72 20 unused
81** 92 4 The version-valid-for number
82** 96 4 SQLITE_VERSION_NUMBER
drh27731d72009-06-22 12:05:10 +000083**
drha3152892007-05-05 11:48:52 +000084** All of the integer values are big-endian (most significant byte first).
85**
drh80308692007-06-15 12:06:58 +000086** The file change counter is incremented when the database is changed
87** This counter allows other processes to know when the file has changed
88** and thus when they need to flush their cache.
drha3152892007-05-05 11:48:52 +000089**
90** The max embedded payload fraction is the amount of the total usable
91** space in a page that can be consumed by a single cell for standard
92** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
93** is to limit the maximum cell size so that at least 4 cells will fit
94** on one page. Thus the default max embedded payload fraction is 64.
95**
96** If the payload for a cell is larger than the max payload, then extra
97** payload is spilled to overflow pages. Once an overflow page is allocated,
98** as many bytes as possible are moved into the overflow pages without letting
99** the cell size drop below the min embedded payload fraction.
100**
101** The min leaf payload fraction is like the min embedded payload fraction
102** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
103** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
104** not specified in the header.
105**
106** Each btree pages is divided into three sections: The header, the
drh80308692007-06-15 12:06:58 +0000107** cell pointer array, and the cell content area. Page 1 also has a 100-byte
drha3152892007-05-05 11:48:52 +0000108** file header that occurs before the page header.
109**
110** |----------------|
111** | file header | 100 bytes. Page 1 only.
112** |----------------|
113** | page header | 8 bytes for leaves. 12 bytes for interior nodes
114** |----------------|
115** | cell pointer | | 2 bytes per cell. Sorted order.
116** | array | | Grows downward
117** | | v
118** |----------------|
119** | unallocated |
120** | space |
121** |----------------| ^ Grows upwards
122** | cell content | | Arbitrary order interspersed with freeblocks.
123** | area | | and free space fragments.
124** |----------------|
125**
126** The page headers looks like this:
127**
128** OFFSET SIZE DESCRIPTION
129** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
130** 1 2 byte offset to the first freeblock
131** 3 2 number of cells on this page
132** 5 2 first byte of the cell content area
133** 7 1 number of fragmented free bytes
134** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
135**
136** The flags define the format of this btree page. The leaf flag means that
137** this page has no children. The zerodata flag means that this page carries
peter.d.reid60ec9142014-09-06 16:39:46 +0000138** only keys and no data. The intkey flag means that the key is an integer
drha3152892007-05-05 11:48:52 +0000139** which is stored in the key size entry of the cell header rather than in
140** the payload area.
141**
142** The cell pointer array begins on the first byte after the page header.
143** The cell pointer array contains zero or more 2-byte numbers which are
144** offsets from the beginning of the page to the cell content in the cell
145** content area. The cell pointers occur in sorted order. The system strives
146** to keep free space after the last cell pointer so that new cells can
147** be easily added without having to defragment the page.
148**
149** Cell content is stored at the very end of the page and grows toward the
150** beginning of the page.
151**
152** Unused space within the cell content area is collected into a linked list of
153** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
154** to the first freeblock is given in the header. Freeblocks occur in
155** increasing order. Because a freeblock must be at least 4 bytes in size,
156** any group of 3 or fewer unused bytes in the cell content area cannot
157** exist on the freeblock chain. A group of 3 or fewer free bytes is called
158** a fragment. The total number of bytes in all fragments is recorded.
159** in the page header at offset 7.
160**
161** SIZE DESCRIPTION
162** 2 Byte offset of the next freeblock
163** 2 Bytes in this freeblock
164**
165** Cells are of variable length. Cells are stored in the cell content area at
166** the end of the page. Pointers to the cells are in the cell pointer array
167** that immediately follows the page header. Cells is not necessarily
168** contiguous or in order, but cell pointers are contiguous and in order.
169**
170** Cell content makes use of variable length integers. A variable
171** length integer is 1 to 9 bytes where the lower 7 bits of each
172** byte are used. The integer consists of all bytes that have bit 8 set and
173** the first byte with bit 8 clear. The most significant byte of the integer
174** appears first. A variable-length integer may not be more than 9 bytes long.
175** As a special case, all 8 bytes of the 9th byte are used as data. This
176** allows a 64-bit integer to be encoded in 9 bytes.
177**
178** 0x00 becomes 0x00000000
179** 0x7f becomes 0x0000007f
180** 0x81 0x00 becomes 0x00000080
181** 0x82 0x00 becomes 0x00000100
182** 0x80 0x7f becomes 0x0000007f
183** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
184** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
185**
186** Variable length integers are used for rowids and to hold the number of
187** bytes of key and data in a btree cell.
188**
189** The content of a cell looks like this:
190**
191** SIZE DESCRIPTION
192** 4 Page number of the left child. Omitted if leaf flag is set.
193** var Number of bytes of data. Omitted if the zerodata flag is set.
194** var Number of bytes of key. Or the key itself if intkey flag is set.
195** * Payload
196** 4 First page of the overflow chain. Omitted if no overflow
197**
198** Overflow pages form a linked list. Each page except the last is completely
199** filled with data (pagesize - 4 bytes). The last page can have as little
200** as 1 byte of data.
201**
202** SIZE DESCRIPTION
203** 4 Page number of next overflow page
204** * Data
205**
206** Freelist pages come in two subtypes: trunk pages and leaf pages. The
drh80308692007-06-15 12:06:58 +0000207** file header points to the first in a linked list of trunk page. Each trunk
drha3152892007-05-05 11:48:52 +0000208** page points to multiple leaf pages. The content of a leaf page is
209** unspecified. A trunk page looks like this:
210**
211** SIZE DESCRIPTION
212** 4 Page number of next trunk page
213** 4 Number of leaf pointers on this page
214** * zero or more pages numbers of leaves
215*/
216#include "sqliteInt.h"
drha3152892007-05-05 11:48:52 +0000217
drha3152892007-05-05 11:48:52 +0000218
219/* The following value is the maximum cell size assuming a maximum page
220** size give above.
221*/
drhfcd71b62011-04-05 22:08:24 +0000222#define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
drha3152892007-05-05 11:48:52 +0000223
224/* The maximum number of cells on a single page of the database. This
drha9121e42008-02-19 14:59:35 +0000225** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
226** plus 2 bytes for the index to the cell in the page header). Such
227** small cells will be rare, but they are possible.
drha3152892007-05-05 11:48:52 +0000228*/
drha9121e42008-02-19 14:59:35 +0000229#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
drha3152892007-05-05 11:48:52 +0000230
231/* Forward declarations */
232typedef struct MemPage MemPage;
233typedef struct BtLock BtLock;
drh5fa60512015-06-19 17:19:34 +0000234typedef struct CellInfo CellInfo;
dan7b3d71e2015-08-19 20:27:05 +0000235typedef struct BtreePtrmap BtreePtrmap;
drha3152892007-05-05 11:48:52 +0000236
237/*
238** This is a magic string that appears at the beginning of every
239** SQLite database in order to identify the file as a real database.
240**
241** You can change this value at compile-time by specifying a
242** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
243** header must be exactly 16 bytes including the zero-terminator so
244** the string itself should be 15 characters long. If you change
245** the header, then your custom library will not be able to read
246** databases generated by the standard tools and the standard tools
247** will not be able to read databases created by your custom library.
248*/
249#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
250# define SQLITE_FILE_HEADER "SQLite format 3"
251#endif
252
253/*
254** Page type flags. An ORed combination of these flags appear as the
drhe53831d2007-08-17 01:14:38 +0000255** first byte of on-disk image of every BTree page.
drha3152892007-05-05 11:48:52 +0000256*/
257#define PTF_INTKEY 0x01
258#define PTF_ZERODATA 0x02
259#define PTF_LEAFDATA 0x04
260#define PTF_LEAF 0x08
261
262/*
drha2ee5892016-12-09 16:02:00 +0000263** An instance of this object stores information about each a single database
264** page that has been loaded into memory. The information in this object
265** is derived from the raw on-disk page content.
drha3152892007-05-05 11:48:52 +0000266**
drha2ee5892016-12-09 16:02:00 +0000267** As each database page is loaded into memory, the pager allocats an
268** instance of this object and zeros the first 8 bytes. (This is the
269** "extra" information associated with each page of the pager.)
drhd677b3d2007-08-20 22:48:41 +0000270**
271** Access to all fields of this structure is controlled by the mutex
272** stored in MemPage.pBt->mutex.
drha3152892007-05-05 11:48:52 +0000273*/
274struct MemPage {
275 u8 isInit; /* True if previously initialized. MUST BE FIRST! */
drh3e28ff52014-09-24 00:59:08 +0000276 u8 intKey; /* True if table b-trees. False for index b-trees */
277 u8 intKeyLeaf; /* True if the leaf of an intKey table */
drha2ee5892016-12-09 16:02:00 +0000278 Pgno pgno; /* Page number for this page */
drh7365bcd2017-07-20 18:28:33 +0000279#ifndef SQLITE_OMIT_CONCURRENT
280 Pgno pgnoRoot; /* Root page of b-tree that this page belongs to */
281#endif
drha2ee5892016-12-09 16:02:00 +0000282 /* Only the first 8 bytes (above) are zeroed by pager.c when a new page
283 ** is allocated. All fields that follow must be initialized before use */
drh3e28ff52014-09-24 00:59:08 +0000284 u8 leaf; /* True if a leaf page */
drha3152892007-05-05 11:48:52 +0000285 u8 hdrOffset; /* 100 for page 1. 0 otherwise */
286 u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
drhc9166342012-01-05 23:32:06 +0000287 u8 max1bytePayload; /* min(maxLocal,127) */
drha2ee5892016-12-09 16:02:00 +0000288 u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
drhe53831d2007-08-17 01:14:38 +0000289 u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
290 u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
drha3152892007-05-05 11:48:52 +0000291 u16 cellOffset; /* Index in aData of first cell pointer */
drha941ff72019-02-12 00:58:10 +0000292 int nFree; /* Number of free bytes on the page. -1 for unknown */
drha3152892007-05-05 11:48:52 +0000293 u16 nCell; /* Number of cells on this page, local and ovfl */
drh1688c862008-07-18 02:44:17 +0000294 u16 maskPage; /* Mask for page offset */
drha2ee5892016-12-09 16:02:00 +0000295 u16 aiOvfl[4]; /* Insert the i-th overflow cell before the aiOvfl-th
drh2cbd78b2012-02-02 19:37:18 +0000296 ** non-overflow cell */
drha2ee5892016-12-09 16:02:00 +0000297 u8 *apOvfl[4]; /* Pointers to the body of overflow cells */
drhe53831d2007-08-17 01:14:38 +0000298 BtShared *pBt; /* Pointer to BtShared that this page is part of */
299 u8 *aData; /* Pointer to disk image of the page data */
drha055abb2022-03-01 20:15:04 +0000300 u8 *aDataEnd; /* One byte past the end of the entire page - not just
301 ** the usable space, the entire page. Used to prevent
drh32135d72022-03-08 15:49:17 +0000302 ** corruption-induced buffer overflow. */
drh3def2352011-11-11 00:27:15 +0000303 u8 *aCellIdx; /* The cell index area */
drhf44890a2015-06-27 03:58:15 +0000304 u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
drha3152892007-05-05 11:48:52 +0000305 DbPage *pDbPage; /* Pager page handle */
drh5fa60512015-06-19 17:19:34 +0000306 u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
307 void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
drha3152892007-05-05 11:48:52 +0000308};
309
310/*
danielk1977602b4662009-07-02 07:47:33 +0000311** A linked list of the following structures is stored at BtShared.pLock.
312** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
313** is opened on the table with root page BtShared.iTable. Locks are removed
314** from this list when a transaction is committed or rolled back, or when
315** a btree handle is closed.
316*/
317struct BtLock {
318 Btree *pBtree; /* Btree handle holding this lock */
319 Pgno iTable; /* Root page of table */
320 u8 eLock; /* READ_LOCK or WRITE_LOCK */
321 BtLock *pNext; /* Next in BtShared.pLock list */
322};
323
324/* Candidate values for BtLock.eLock */
325#define READ_LOCK 1
326#define WRITE_LOCK 2
327
drhe53831d2007-08-17 01:14:38 +0000328/* A Btree handle
329**
330** A database connection contains a pointer to an instance of
331** this object for every database file that it has open. This structure
332** is opaque to the database connection. The database connection cannot
333** see the internals of this structure and only deals with pointers to
334** this structure.
335**
336** For some database files, the same underlying database cache might be
drhed1f8782009-10-16 13:23:33 +0000337** shared between multiple connections. In that case, each connection
338** has it own instance of this object. But each instance of this object
drhe53831d2007-08-17 01:14:38 +0000339** points to the same BtShared object. The database cache and the
340** schema associated with the database file are all contained within
341** the BtShared object.
drhabddb0c2007-08-20 13:14:28 +0000342**
drhd0679ed2007-08-28 22:24:34 +0000343** All fields in this structure are accessed under sqlite3.mutex.
344** The pBt pointer itself may not be changed while there exists cursors
345** in the referenced BtShared that point back to this Btree since those
drh4fa7d7c2011-04-03 02:41:00 +0000346** cursors have to go through this Btree to find their BtShared and
drhd0679ed2007-08-28 22:24:34 +0000347** they often do so without holding sqlite3.mutex.
drhe53831d2007-08-17 01:14:38 +0000348*/
drha3152892007-05-05 11:48:52 +0000349struct Btree {
drhe5fe6902007-12-07 18:55:28 +0000350 sqlite3 *db; /* The database connection holding this btree */
drhe53831d2007-08-17 01:14:38 +0000351 BtShared *pBt; /* Sharable content of this btree */
352 u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
drhe5fe6902007-12-07 18:55:28 +0000353 u8 sharable; /* True if we can share pBt with another db */
354 u8 locked; /* True if db currently has pBt locked */
drh69180952015-06-25 13:03:10 +0000355 u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
drhe53831d2007-08-17 01:14:38 +0000356 int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
danielk197704103022009-02-03 16:51:24 +0000357 int nBackup; /* Number of backup operations reading this btree */
drh2b994ce2021-03-18 12:36:09 +0000358 u32 iBDataVersion; /* Combines with pBt->pPager->iDataVersion */
drhe5fe6902007-12-07 18:55:28 +0000359 Btree *pNext; /* List of other sharable Btrees from the same db */
drhe53831d2007-08-17 01:14:38 +0000360 Btree *pPrev; /* Back pointer of the same list */
drh37ccfcf2020-08-31 18:49:04 +0000361#ifdef SQLITE_DEBUG
362 u64 nSeek; /* Calls to sqlite3BtreeMovetoUnpacked() */
363#endif
danielk1977602b4662009-07-02 07:47:33 +0000364#ifndef SQLITE_OMIT_SHARED_CACHE
365 BtLock lock; /* Object used to lock page 1 */
366#endif
drha3152892007-05-05 11:48:52 +0000367};
368
369/*
370** Btree.inTrans may take one of the following values.
371**
372** If the shared-data extension is enabled, there may be multiple users
373** of the Btree structure. At most one of these may open a write transaction,
drhe53831d2007-08-17 01:14:38 +0000374** but any number may have active read transactions.
drh99744fa2020-08-25 19:09:07 +0000375**
376** These values must match SQLITE_TXN_NONE, SQLITE_TXN_READ, and
377** SQLITE_TXN_WRITE
drha3152892007-05-05 11:48:52 +0000378*/
379#define TRANS_NONE 0
380#define TRANS_READ 1
381#define TRANS_WRITE 2
382
drh99744fa2020-08-25 19:09:07 +0000383#if TRANS_NONE!=SQLITE_TXN_NONE
384# error wrong numeric code for no-transaction
385#endif
386#if TRANS_READ!=SQLITE_TXN_READ
387# error wrong numeric code for read-transaction
388#endif
389#if TRANS_WRITE!=SQLITE_TXN_WRITE
390# error wrong numeric code for write-transaction
391#endif
392
393
drha3152892007-05-05 11:48:52 +0000394/*
drhe53831d2007-08-17 01:14:38 +0000395** An instance of this object represents a single database file.
396**
drhb8a45bb2011-12-31 21:51:55 +0000397** A single database file can be in use at the same time by two
drhe53831d2007-08-17 01:14:38 +0000398** or more database connections. When two or more connections are
399** sharing the same database file, each connection has it own
400** private Btree object for the file and each of those Btrees points
401** to this one BtShared object. BtShared.nRef is the number of
402** connections currently sharing this database file.
drhabddb0c2007-08-20 13:14:28 +0000403**
404** Fields in this structure are accessed under the BtShared.mutex
405** mutex, except for nRef and pNext which are accessed under the
drhccb21132020-06-19 11:34:57 +0000406** global SQLITE_MUTEX_STATIC_MAIN mutex. The pPager field
drhb1ab8ea2007-08-29 00:33:07 +0000407** may not be modified once it is initially set as long as nRef>0.
408** The pSchema field may be set once under BtShared.mutex and
409** thereafter is unchanged as long as nRef>0.
danielk1977404ca072009-03-16 13:19:36 +0000410**
411** isPending:
412**
413** If a BtShared client fails to obtain a write-lock on a database
414** table (because there exists one or more read-locks on the table),
415** the shared-cache enters 'pending-lock' state and isPending is
416** set to true.
417**
418** The shared-cache leaves the 'pending lock' state when either of
419** the following occur:
420**
421** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
422** 2) The number of locks held by other connections drops to zero.
423**
424** while in the 'pending-lock' state, no connection may start a new
425** transaction.
426**
427** This feature is included to help prevent writer-starvation.
drha3152892007-05-05 11:48:52 +0000428*/
429struct BtShared {
430 Pager *pPager; /* The page cache */
drhe5fe6902007-12-07 18:55:28 +0000431 sqlite3 *db; /* Database connection currently using this Btree */
drha3152892007-05-05 11:48:52 +0000432 BtCursor *pCursor; /* A list of all open cursors */
433 MemPage *pPage1; /* First page of the database */
drhd4187c72010-08-30 22:15:45 +0000434 u8 openFlags; /* Flags to sqlite3BtreeOpen() */
drha3152892007-05-05 11:48:52 +0000435#ifndef SQLITE_OMIT_AUTOVACUUM
436 u8 autoVacuum; /* True if auto-vacuum is enabled */
437 u8 incrVacuum; /* True if incr-vacuum is enabled */
danbc1a3c62013-02-23 16:40:46 +0000438 u8 bDoTruncate; /* True to truncate db on commit */
drha3152892007-05-05 11:48:52 +0000439#endif
drh2e5de2f2011-01-07 02:50:40 +0000440 u8 inTransaction; /* Transaction state */
drhc9166342012-01-05 23:32:06 +0000441 u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
drhe937df82020-05-07 01:56:57 +0000442 u8 nReserveWanted; /* Desired number of extra bytes per page */
drhc9166342012-01-05 23:32:06 +0000443 u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
drhf49661a2008-12-10 16:45:50 +0000444 u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
445 u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
446 u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
447 u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
drhb2eced52010-08-12 02:41:12 +0000448 u32 pageSize; /* Total number of bytes on a page */
449 u32 usableSize; /* Number of usable bytes on each page */
drha3152892007-05-05 11:48:52 +0000450 int nTransaction; /* Number of open transactions (read + write) */
drhdd3cd972010-03-27 17:12:36 +0000451 u32 nPage; /* Number of pages in the database */
drha3152892007-05-05 11:48:52 +0000452 void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
453 void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
drhbdaec522011-04-04 00:14:43 +0000454 sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
danielk1977bea2a942009-01-20 17:06:27 +0000455 Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
drha3152892007-05-05 11:48:52 +0000456#ifndef SQLITE_OMIT_SHARED_CACHE
drhabddb0c2007-08-20 13:14:28 +0000457 int nRef; /* Number of references to this structure */
458 BtShared *pNext; /* Next on a list of sharable BtShared structs */
drha3152892007-05-05 11:48:52 +0000459 BtLock *pLock; /* List of locks held on this shared-btree struct */
danielk1977404ca072009-03-16 13:19:36 +0000460 Btree *pWriter; /* Btree with currently open write transaction */
drha3152892007-05-05 11:48:52 +0000461#endif
drh92787cf2014-10-15 11:55:51 +0000462 u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
drh01be4632015-09-03 15:17:12 +0000463#ifndef SQLITE_OMIT_CONCURRENT
dan7b3d71e2015-08-19 20:27:05 +0000464 BtreePtrmap *pMap;
465#endif
dan7aae7352020-12-10 18:06:24 +0000466 int nPreformatSize; /* Size of last cell written by TransferRow() */
drha3152892007-05-05 11:48:52 +0000467};
468
469/*
drhc9166342012-01-05 23:32:06 +0000470** Allowed values for BtShared.btsFlags
471*/
472#define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
473#define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
474#define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
drha5907a82017-06-19 11:44:22 +0000475#define BTS_OVERWRITE 0x0008 /* Overwrite deleted content with zeros */
476#define BTS_FAST_SECURE 0x000c /* Combination of the previous two */
477#define BTS_INITIALLY_EMPTY 0x0010 /* Database was empty at trans start */
478#define BTS_NO_WAL 0x0020 /* Do not open write-ahead-log files */
479#define BTS_EXCLUSIVE 0x0040 /* pWriter has an exclusive lock */
480#define BTS_PENDING 0x0080 /* Waiting for read-locks to clear */
drhc9166342012-01-05 23:32:06 +0000481
482/*
drha3152892007-05-05 11:48:52 +0000483** An instance of the following structure is used to hold information
484** about a cell. The parseCellPtr() function fills in this structure
485** based on information extract from the raw disk page.
486*/
drha3152892007-05-05 11:48:52 +0000487struct CellInfo {
drhab1cc582014-09-23 21:25:19 +0000488 i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
489 u8 *pPayload; /* Pointer to the start of payload */
490 u32 nPayload; /* Bytes of payload */
491 u16 nLocal; /* Amount of payload held locally, not on overflow */
drha3152892007-05-05 11:48:52 +0000492 u16 nSize; /* Size of the cell content on the main b-tree page */
493};
494
495/*
danielk197771d5d2c2008-09-29 11:49:47 +0000496** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
497** this will be declared corrupt. This value is calculated based on a
498** maximum database size of 2^31 pages a minimum fanout of 2 for a
499** root-node and 3 for all other internal nodes.
500**
501** If a tree that appears to be taller than this is encountered, it is
502** assumed that the database is corrupt.
503*/
504#define BTCURSOR_MAX_DEPTH 20
505
506/*
drhe53831d2007-08-17 01:14:38 +0000507** A cursor is a pointer to a particular entry within a particular
508** b-tree within a database file.
509**
drha3152892007-05-05 11:48:52 +0000510** The entry is identified by its MemPage and the index in
511** MemPage.aCell[] of the entry.
drhe53831d2007-08-17 01:14:38 +0000512**
drhb8a45bb2011-12-31 21:51:55 +0000513** A single database file can be shared by two more database connections,
drhe53831d2007-08-17 01:14:38 +0000514** but cursors cannot be shared. Each cursor is associated with a
drhe5fe6902007-12-07 18:55:28 +0000515** particular database connection identified BtCursor.pBtree.db.
drhabddb0c2007-08-20 13:14:28 +0000516**
drhd677b3d2007-08-20 22:48:41 +0000517** Fields in this structure are accessed under the BtShared.mutex
drhd0679ed2007-08-28 22:24:34 +0000518** found at self->pBt->mutex.
drhd816e002014-11-17 19:25:15 +0000519**
520** skipNext meaning:
drh0c873bf2019-01-28 00:42:06 +0000521** The meaning of skipNext depends on the value of eState:
522**
523** eState Meaning of skipNext
524** VALID skipNext is meaningless and is ignored
525** INVALID skipNext is meaningless and is ignored
526** SKIPNEXT sqlite3BtreeNext() is a no-op if skipNext>0 and
527** sqlite3BtreePrevious() is no-op if skipNext<0.
528** REQUIRESEEK restoreCursorPosition() restores the cursor to
529** eState=SKIPNEXT if skipNext!=0
530** FAULT skipNext holds the cursor fault error code.
drha3152892007-05-05 11:48:52 +0000531*/
532struct BtCursor {
drhfe0cf7a2017-08-16 19:20:20 +0000533 u8 eState; /* One of the CURSOR_XXX constants (see below) */
534 u8 curFlags; /* zero or more BTCF_* flags defined below */
535 u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */
536 u8 hints; /* As configured by CursorSetHints() */
drhd816e002014-11-17 19:25:15 +0000537 int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
538 ** Error code if eState==CURSOR_FAULT */
drhda6bc672018-01-24 16:04:21 +0000539 Btree *pBtree; /* The Btree to which this cursor belongs */
540 Pgno *aOverflow; /* Cache of overflow page locations */
541 void *pKey; /* Saved key that was cursor last known position */
drh408efc02015-06-27 22:49:10 +0000542 /* All fields above are zeroed when the cursor is allocated. See
543 ** sqlite3BtreeCursorZero(). Fields that follow must be manually
544 ** initialized. */
drhda6bc672018-01-24 16:04:21 +0000545#define BTCURSOR_FIRST_UNINIT pBt /* Name of first uninitialized field */
546 BtShared *pBt; /* The BtShared this cursor points to */
547 BtCursor *pNext; /* Forms a linked list of all cursors */
548 CellInfo info; /* A parse of the cell we are pointing at */
549 i64 nKey; /* Size of pKey, or last integer key */
550 Pgno pgnoRoot; /* The root page of this tree */
drh408efc02015-06-27 22:49:10 +0000551 i8 iPage; /* Index of current page in apPage */
552 u8 curIntKey; /* Value of apPage[0]->intKey */
drh75e96b32017-04-01 00:20:06 +0000553 u16 ix; /* Current index for apPage[iPage] */
drhb6017a42017-04-01 11:40:05 +0000554 u16 aiIdx[BTCURSOR_MAX_DEPTH-1]; /* Current index in apPage[i] */
555 struct KeyInfo *pKeyInfo; /* Arg passed to comparison function */
drh352a35a2017-08-15 03:46:47 +0000556 MemPage *pPage; /* Current page */
557 MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */
drha3152892007-05-05 11:48:52 +0000558};
559
560/*
drh036dbec2014-03-11 23:40:44 +0000561** Legal values for BtCursor.curFlags
562*/
drh4c417182014-03-31 23:57:41 +0000563#define BTCF_WriteFlag 0x01 /* True if a write cursor */
564#define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
565#define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
566#define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
drh036dbec2014-03-11 23:40:44 +0000567#define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
drh27fb7462015-06-30 02:47:36 +0000568#define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
drh7b14b652019-12-29 22:08:20 +0000569#define BTCF_Pinned 0x40 /* Cursor is busy and cannot be moved */
drh036dbec2014-03-11 23:40:44 +0000570
571/*
drha3152892007-05-05 11:48:52 +0000572** Potential values for BtCursor.eState.
573**
drha3152892007-05-05 11:48:52 +0000574** CURSOR_INVALID:
575** Cursor does not point to a valid entry. This can happen (for example)
576** because the table is empty or because BtreeCursorFirst() has not been
577** called.
578**
drh9b47ee32013-08-20 03:13:51 +0000579** CURSOR_VALID:
580** Cursor points to a valid entry. getPayload() etc. may be called.
581**
582** CURSOR_SKIPNEXT:
583** Cursor is valid except that the Cursor.skipNext field is non-zero
584** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
585** operation should be a no-op.
586**
drha3152892007-05-05 11:48:52 +0000587** CURSOR_REQUIRESEEK:
588** The table that this cursor was opened on still exists, but has been
589** modified since the cursor was last used. The cursor position is saved
590** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
drha3460582008-07-11 21:02:53 +0000591** this state, restoreCursorPosition() can be called to attempt to
drha3152892007-05-05 11:48:52 +0000592** seek the cursor to the saved position.
drhfb982642007-08-30 01:19:59 +0000593**
594** CURSOR_FAULT:
peter.d.reid60ec9142014-09-06 16:39:46 +0000595** An unrecoverable error (an I/O error or a malloc failure) has occurred
drhfb982642007-08-30 01:19:59 +0000596** on a different connection that shares the BtShared cache with this
597** cursor. The error has left the cache in an inconsistent state.
598** Do nothing else with this cursor. Any attempt to use the cursor
drhd816e002014-11-17 19:25:15 +0000599** should return the error code stored in BtCursor.skipNext
drha3152892007-05-05 11:48:52 +0000600*/
drha8519d72018-01-24 14:40:01 +0000601#define CURSOR_VALID 0
602#define CURSOR_INVALID 1
drh9b47ee32013-08-20 03:13:51 +0000603#define CURSOR_SKIPNEXT 2
604#define CURSOR_REQUIRESEEK 3
605#define CURSOR_FAULT 4
drha3152892007-05-05 11:48:52 +0000606
danielk1977bea2a942009-01-20 17:06:27 +0000607/*
608** The database page the PENDING_BYTE occupies. This page is never used.
drha3152892007-05-05 11:48:52 +0000609*/
drh584bfca2022-02-23 17:00:44 +0000610#define PENDING_BYTE_PAGE(pBt) ((Pgno)((PENDING_BYTE/((pBt)->pageSize))+1))
drha3152892007-05-05 11:48:52 +0000611
612/*
drha3152892007-05-05 11:48:52 +0000613** These macros define the location of the pointer-map entry for a
614** database page. The first argument to each is the number of usable
615** bytes on each page of the database (often 1024). The second is the
616** page number to look up in the pointer map.
617**
618** PTRMAP_PAGENO returns the database page number of the pointer-map
619** page that stores the required pointer. PTRMAP_PTROFFSET returns
620** the offset of the requested map entry.
621**
622** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
623** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
624** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
625** this test.
626*/
627#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
danielk19778c666b12008-07-18 09:34:57 +0000628#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
drha3152892007-05-05 11:48:52 +0000629#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
630
631/*
632** The pointer map is a lookup table that identifies the parent page for
633** each child page in the database file. The parent page is the page that
634** contains a pointer to the child. Every page in the database contains
635** 0 or 1 parent pages. (In this context 'database page' refers
636** to any page that is not part of the pointer map itself.) Each pointer map
637** entry consists of a single byte 'type' and a 4 byte parent page number.
638** The PTRMAP_XXX identifiers below are the valid types.
639**
640** The purpose of the pointer map is to facility moving pages from one
641** position in the file to another as part of autovacuum. When a page
642** is moved, the pointer in its parent must be updated to point to the
643** new location. The pointer map is used to locate the parent page quickly.
644**
645** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
646** used in this case.
647**
648** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
649** is not used in this case.
650**
651** PTRMAP_OVERFLOW1: The database page is the first page in a list of
652** overflow pages. The page number identifies the page that
653** contains the cell with a pointer to this overflow page.
654**
655** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
656** overflow pages. The page-number identifies the previous
657** page in the overflow page list.
658**
659** PTRMAP_BTREE: The database page is a non-root btree page. The page number
660** identifies the parent page in the btree.
661*/
662#define PTRMAP_ROOTPAGE 1
663#define PTRMAP_FREEPAGE 2
664#define PTRMAP_OVERFLOW1 3
665#define PTRMAP_OVERFLOW2 4
666#define PTRMAP_BTREE 5
667
668/* A bunch of assert() statements to check the transaction state variables
669** of handle p (type Btree*) are internally consistent.
670*/
671#define btreeIntegrity(p) \
drha3152892007-05-05 11:48:52 +0000672 assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
673 assert( p->pBt->inTransaction>=p->inTrans );
674
675
676/*
677** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
678** if the database supports auto-vacuum or not. Because it is used
679** within an expression that is an argument to another macro
680** (sqliteMallocRaw), it is not possible to use conditional compilation.
681** So, this macro is defined instead.
682*/
drh01be4632015-09-03 15:17:12 +0000683#ifdef SQLITE_OMIT_AUTOVACUUM
drhe7d53842022-11-21 14:13:10 +0000684#define ISAUTOVACUUM(pBt) 0
drh01be4632015-09-03 15:17:12 +0000685#else
drh43fa1a52022-12-21 20:07:58 +0000686#define ISAUTOVACUUM(pBt) (pBt->autoVacuum)
drha3152892007-05-05 11:48:52 +0000687#endif
688
drh01be4632015-09-03 15:17:12 +0000689#ifdef SQLITE_OMIT_CONCURRENT
danbf3cf572015-08-24 19:56:04 +0000690# define ISCONCURRENT 0
drh01be4632015-09-03 15:17:12 +0000691#else
692# define ISCONCURRENT (pBt->pMap!=0)
dan7b3d71e2015-08-19 20:27:05 +0000693#endif
694
drh43fa1a52022-12-21 20:07:58 +0000695#define REQUIRE_PTRMAP (ISAUTOVACUUM(pBt) || ISCONCURRENT)
drha3152892007-05-05 11:48:52 +0000696
697/*
drh5dd74bf2023-01-11 16:17:31 +0000698** This structure is passed around through all the PRAGMA integrity_check
699** checking routines in order to keep track of some global state information.
dan1235bb12012-04-03 17:43:28 +0000700**
701** The aRef[] array is allocated so that there is 1 bit for each page in
702** the database. As the integrity-check proceeds, for each page used in
703** the database the corresponding bit is set. This allows integrity-check to
704** detect pages that are used twice and orphaned pages (both of which
705** indicate corruption).
drha3152892007-05-05 11:48:52 +0000706*/
707typedef struct IntegrityCk IntegrityCk;
708struct IntegrityCk {
709 BtShared *pBt; /* The tree being checked out */
710 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
dan1235bb12012-04-03 17:43:28 +0000711 u8 *aPgRef; /* 1 bit per page in the db (see above) */
drh2cbd78b2012-02-02 19:37:18 +0000712 Pgno nPage; /* Number of pages in the database */
drha3152892007-05-05 11:48:52 +0000713 int mxErr; /* Stop accumulating errors when this reaches zero */
drha3152892007-05-05 11:48:52 +0000714 int nErr; /* Number of messages written to zErrMsg so far */
drh8518eac2023-01-11 20:52:15 +0000715 int rc; /* SQLITE_OK, SQLITE_NOMEM, or SQLITE_INTERRUPT */
drh5dd74bf2023-01-11 16:17:31 +0000716 u32 nStep; /* Number of steps into the integrity_check process */
drh867db832014-09-26 02:41:05 +0000717 const char *zPfx; /* Error message prefix */
drhabc38152020-07-22 13:38:04 +0000718 Pgno v1; /* Value for first %u substitution in zPfx */
719 int v2; /* Value for second %d substitution in zPfx */
drhf089aa42008-07-08 19:34:06 +0000720 StrAccum errMsg; /* Accumulate the error message text here */
drhe05b3f82015-07-01 17:53:49 +0000721 u32 *heap; /* Min-heap used for analyzing cell coverage */
drh21f6daa2019-10-11 14:21:48 +0000722 sqlite3 *db; /* Database connection running the check */
drha3152892007-05-05 11:48:52 +0000723};
724
725/*
drhb8a45bb2011-12-31 21:51:55 +0000726** Routines to read or write a two- and four-byte big-endian integer values.
drha3152892007-05-05 11:48:52 +0000727*/
danielk19771cc5ed82007-05-16 17:28:43 +0000728#define get2byte(x) ((x)[0]<<8 | (x)[1])
drhf49661a2008-12-10 16:45:50 +0000729#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
drha3152892007-05-05 11:48:52 +0000730#define get4byte sqlite3Get4byte
drha3152892007-05-05 11:48:52 +0000731#define put4byte sqlite3Put4byte
drh329428e2015-06-30 13:28:18 +0000732
733/*
734** get2byteAligned(), unlike get2byte(), requires that its argument point to a
735** two-byte aligned address. get2bytea() is only used for accessing the
736** cell addresses in a btree header.
737*/
738#if SQLITE_BYTEORDER==4321
739# define get2byteAligned(x) (*(u16*)(x))
drha39284b2017-02-09 17:12:22 +0000740#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
drh329428e2015-06-30 13:28:18 +0000741# define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
drh30a58312017-02-13 13:26:33 +0000742#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
mistachkin647ca462015-06-30 17:28:40 +0000743# define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
drh329428e2015-06-30 13:28:18 +0000744#else
745# define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
746#endif