blob: 7e5314b581e193d1fe41cd65174a649e57489cf0 [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*************************************************************************
danielk19775118b912005-12-30 16:31:53 +000012** $Id: btree.c,v 1.278 2005/12/30 16:31:54 danielk1977 Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
15** For a detailed discussion of BTrees, refer to
16**
17** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
18** "Sorting And Searching", pages 473-480. Addison-Wesley
19** Publishing Company, Reading, Massachusetts.
20**
21** The basic idea is that each page of the file contains N database
22** entries and N+1 pointers to subpages.
23**
24** ----------------------------------------------------------------
25** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N) | Ptr(N+1) |
26** ----------------------------------------------------------------
27**
28** All of the keys on the page that Ptr(0) points to have values less
29** than Key(0). All of the keys on page Ptr(1) and its subpages have
30** values greater than Key(0) and less than Key(1). All of the keys
31** on Ptr(N+1) and its subpages have values greater than Key(N). And
32** so forth.
33**
drh5e00f6c2001-09-13 13:46:56 +000034** Finding a particular key requires reading O(log(M)) pages from the
35** disk where M is the number of entries in the tree.
drh8b2f49b2001-06-08 00:21:52 +000036**
37** In this implementation, a single file can hold one or more separate
38** BTrees. Each BTree is identified by the index of its root page. The
drh9e572e62004-04-23 23:43:10 +000039** key and data for any entry are combined to form the "payload". A
40** fixed amount of payload can be carried directly on the database
41** page. If the payload is larger than the preset amount then surplus
42** bytes are stored on overflow pages. The payload for an entry
43** and the preceding pointer are combined to form a "Cell". Each
44** page has a small header which contains the Ptr(N+1) pointer and other
45** information such as the size of key and data.
drh8b2f49b2001-06-08 00:21:52 +000046**
drh9e572e62004-04-23 23:43:10 +000047** FORMAT DETAILS
48**
49** The file is divided into pages. The first page is called page 1,
50** the second is page 2, and so forth. A page number of zero indicates
51** "no such page". The page size can be anything between 512 and 65536.
52** Each page can be either a btree page, a freelist page or an overflow
53** page.
54**
55** The first page is always a btree page. The first 100 bytes of the first
drh271efa52004-05-30 19:19:05 +000056** page contain a special header (the "file header") that describes the file.
57** The format of the file header is as follows:
drh9e572e62004-04-23 23:43:10 +000058**
59** OFFSET SIZE DESCRIPTION
drhde647132004-05-07 17:57:49 +000060** 0 16 Header string: "SQLite format 3\000"
drh9e572e62004-04-23 23:43:10 +000061** 16 2 Page size in bytes.
62** 18 1 File format write version
63** 19 1 File format read version
drh6f11bef2004-05-13 01:12:56 +000064** 20 1 Bytes of unused space at the end of each page
65** 21 1 Max embedded payload fraction
66** 22 1 Min embedded payload fraction
67** 23 1 Min leaf payload fraction
68** 24 4 File change counter
69** 28 4 Reserved for future use
drh9e572e62004-04-23 23:43:10 +000070** 32 4 First freelist page
71** 36 4 Number of freelist pages in the file
72** 40 60 15 4-byte meta values passed to higher layers
73**
74** All of the integer values are big-endian (most significant byte first).
drh6f11bef2004-05-13 01:12:56 +000075**
drhab01f612004-05-22 02:55:23 +000076** The file change counter is incremented when the database is changed more
drh6f11bef2004-05-13 01:12:56 +000077** than once within the same second. This counter, together with the
78** modification time of the file, allows other processes to know
79** when the file has changed and thus when they need to flush their
80** cache.
81**
82** The max embedded payload fraction is the amount of the total usable
83** space in a page that can be consumed by a single cell for standard
84** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
85** is to limit the maximum cell size so that at least 4 cells will fit
drhab01f612004-05-22 02:55:23 +000086** on one page. Thus the default max embedded payload fraction is 64.
drh6f11bef2004-05-13 01:12:56 +000087**
88** If the payload for a cell is larger than the max payload, then extra
89** payload is spilled to overflow pages. Once an overflow page is allocated,
90** as many bytes as possible are moved into the overflow pages without letting
91** the cell size drop below the min embedded payload fraction.
92**
93** The min leaf payload fraction is like the min embedded payload fraction
94** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
95** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
96** not specified in the header.
drh9e572e62004-04-23 23:43:10 +000097**
drh43605152004-05-29 21:46:49 +000098** Each btree pages is divided into three sections: The header, the
99** cell pointer array, and the cell area area. Page 1 also has a 100-byte
drh271efa52004-05-30 19:19:05 +0000100** file header that occurs before the page header.
101**
102** |----------------|
103** | file header | 100 bytes. Page 1 only.
104** |----------------|
105** | page header | 8 bytes for leaves. 12 bytes for interior nodes
106** |----------------|
107** | cell pointer | | 2 bytes per cell. Sorted order.
108** | array | | Grows downward
109** | | v
110** |----------------|
111** | unallocated |
112** | space |
113** |----------------| ^ Grows upwards
114** | cell content | | Arbitrary order interspersed with freeblocks.
115** | area | | and free space fragments.
116** |----------------|
drh43605152004-05-29 21:46:49 +0000117**
118** The page headers looks like this:
drh9e572e62004-04-23 23:43:10 +0000119**
120** OFFSET SIZE DESCRIPTION
drh6f11bef2004-05-13 01:12:56 +0000121** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
drh9e572e62004-04-23 23:43:10 +0000122** 1 2 byte offset to the first freeblock
drh43605152004-05-29 21:46:49 +0000123** 3 2 number of cells on this page
drh271efa52004-05-30 19:19:05 +0000124** 5 2 first byte of the cell content area
drh43605152004-05-29 21:46:49 +0000125** 7 1 number of fragmented free bytes
drh271efa52004-05-30 19:19:05 +0000126** 8 4 Right child (the Ptr(N+1) value). Omitted on leaves.
drh9e572e62004-04-23 23:43:10 +0000127**
128** The flags define the format of this btree page. The leaf flag means that
129** this page has no children. The zerodata flag means that this page carries
drh44f87bd2004-09-27 13:19:51 +0000130** only keys and no data. The intkey flag means that the key is a integer
131** which is stored in the key size entry of the cell header rather than in
132** the payload area.
drh9e572e62004-04-23 23:43:10 +0000133**
drh43605152004-05-29 21:46:49 +0000134** The cell pointer array begins on the first byte after the page header.
135** The cell pointer array contains zero or more 2-byte numbers which are
136** offsets from the beginning of the page to the cell content in the cell
137** content area. The cell pointers occur in sorted order. The system strives
138** to keep free space after the last cell pointer so that new cells can
drh44f87bd2004-09-27 13:19:51 +0000139** be easily added without having to defragment the page.
drh43605152004-05-29 21:46:49 +0000140**
141** Cell content is stored at the very end of the page and grows toward the
142** beginning of the page.
143**
144** Unused space within the cell content area is collected into a linked list of
145** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
146** to the first freeblock is given in the header. Freeblocks occur in
147** increasing order. Because a freeblock must be at least 4 bytes in size,
148** any group of 3 or fewer unused bytes in the cell content area cannot
149** exist on the freeblock chain. A group of 3 or fewer free bytes is called
150** a fragment. The total number of bytes in all fragments is recorded.
151** in the page header at offset 7.
152**
153** SIZE DESCRIPTION
154** 2 Byte offset of the next freeblock
155** 2 Bytes in this freeblock
156**
157** Cells are of variable length. Cells are stored in the cell content area at
158** the end of the page. Pointers to the cells are in the cell pointer array
159** that immediately follows the page header. Cells is not necessarily
160** contiguous or in order, but cell pointers are contiguous and in order.
161**
162** Cell content makes use of variable length integers. A variable
163** length integer is 1 to 9 bytes where the lower 7 bits of each
drh9e572e62004-04-23 23:43:10 +0000164** byte are used. The integer consists of all bytes that have bit 8 set and
drh6f11bef2004-05-13 01:12:56 +0000165** the first byte with bit 8 clear. The most significant byte of the integer
drhab01f612004-05-22 02:55:23 +0000166** appears first. A variable-length integer may not be more than 9 bytes long.
167** As a special case, all 8 bytes of the 9th byte are used as data. This
168** allows a 64-bit integer to be encoded in 9 bytes.
drh9e572e62004-04-23 23:43:10 +0000169**
170** 0x00 becomes 0x00000000
drh6f11bef2004-05-13 01:12:56 +0000171** 0x7f becomes 0x0000007f
172** 0x81 0x00 becomes 0x00000080
173** 0x82 0x00 becomes 0x00000100
174** 0x80 0x7f becomes 0x0000007f
175** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
drh9e572e62004-04-23 23:43:10 +0000176** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
177**
178** Variable length integers are used for rowids and to hold the number of
179** bytes of key and data in a btree cell.
180**
drh43605152004-05-29 21:46:49 +0000181** The content of a cell looks like this:
drh9e572e62004-04-23 23:43:10 +0000182**
183** SIZE DESCRIPTION
drh3aac2dd2004-04-26 14:10:20 +0000184** 4 Page number of the left child. Omitted if leaf flag is set.
185** var Number of bytes of data. Omitted if the zerodata flag is set.
186** var Number of bytes of key. Or the key itself if intkey flag is set.
drh9e572e62004-04-23 23:43:10 +0000187** * Payload
188** 4 First page of the overflow chain. Omitted if no overflow
189**
190** Overflow pages form a linked list. Each page except the last is completely
191** filled with data (pagesize - 4 bytes). The last page can have as little
192** as 1 byte of data.
193**
194** SIZE DESCRIPTION
195** 4 Page number of next overflow page
196** * Data
197**
198** Freelist pages come in two subtypes: trunk pages and leaf pages. The
199** file header points to first in a linked list of trunk page. Each trunk
200** page points to multiple leaf pages. The content of a leaf page is
201** unspecified. A trunk page looks like this:
202**
203** SIZE DESCRIPTION
204** 4 Page number of next trunk page
205** 4 Number of leaf pointers on this page
206** * zero or more pages numbers of leaves
drha059ad02001-04-17 20:09:11 +0000207*/
208#include "sqliteInt.h"
209#include "pager.h"
210#include "btree.h"
drh1f595712004-06-15 01:40:29 +0000211#include "os.h"
drha059ad02001-04-17 20:09:11 +0000212#include <assert.h>
213
drhc96d8532005-05-03 12:30:33 +0000214/* Round up a number to the next larger multiple of 8. This is used
215** to force 8-byte alignment on 64-bit architectures.
216*/
217#define ROUND8(x) ((x+7)&~7)
218
219
drh4b70f112004-05-02 21:12:19 +0000220/* The following value is the maximum cell size assuming a maximum page
221** size give above.
222*/
drh2e38c322004-09-03 18:38:44 +0000223#define MX_CELL_SIZE(pBt) (pBt->pageSize-8)
drh4b70f112004-05-02 21:12:19 +0000224
225/* The maximum number of cells on a single page of the database. This
226** assumes a minimum cell size of 3 bytes. Such small cells will be
227** exceedingly rare, but they are possible.
228*/
drh2e38c322004-09-03 18:38:44 +0000229#define MX_CELL(pBt) ((pBt->pageSize-8)/3)
drh4b70f112004-05-02 21:12:19 +0000230
paulb95a8862003-04-01 21:16:41 +0000231/* Forward declarations */
drh3aac2dd2004-04-26 14:10:20 +0000232typedef struct MemPage MemPage;
danielk1977aef0bf62005-12-30 16:28:01 +0000233typedef struct BtLock BtLock;
paulb95a8862003-04-01 21:16:41 +0000234
drh8c42ca92001-06-22 19:15:00 +0000235/*
drhbd03cae2001-06-02 02:40:57 +0000236** This is a magic string that appears at the beginning of every
drh8c42ca92001-06-22 19:15:00 +0000237** SQLite database in order to identify the file as a real database.
drh556b2a22005-06-14 16:04:05 +0000238**
239** You can change this value at compile-time by specifying a
240** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
241** header must be exactly 16 bytes including the zero-terminator so
242** the string itself should be 15 characters long. If you change
243** the header, then your custom library will not be able to read
244** databases generated by the standard tools and the standard tools
245** will not be able to read databases created by your custom library.
246*/
247#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
248# define SQLITE_FILE_HEADER "SQLite format 3"
249#endif
250static const char zMagicHeader[] = SQLITE_FILE_HEADER;
drh08ed44e2001-04-29 23:32:55 +0000251
252/*
drh4b70f112004-05-02 21:12:19 +0000253** Page type flags. An ORed combination of these flags appear as the
254** first byte of every BTree page.
drh8c42ca92001-06-22 19:15:00 +0000255*/
drhde647132004-05-07 17:57:49 +0000256#define PTF_INTKEY 0x01
drh9e572e62004-04-23 23:43:10 +0000257#define PTF_ZERODATA 0x02
drh8b18dd42004-05-12 19:18:15 +0000258#define PTF_LEAFDATA 0x04
259#define PTF_LEAF 0x08
drh8c42ca92001-06-22 19:15:00 +0000260
261/*
drh9e572e62004-04-23 23:43:10 +0000262** As each page of the file is loaded into memory, an instance of the following
263** structure is appended and initialized to zero. This structure stores
264** information about the page that is decoded from the raw file page.
drh14acc042001-06-10 19:56:58 +0000265**
drh72f82862001-05-24 21:06:34 +0000266** The pParent field points back to the parent page. This allows us to
267** walk up the BTree from any leaf to the root. Care must be taken to
268** unref() the parent page pointer when this page is no longer referenced.
drhbd03cae2001-06-02 02:40:57 +0000269** The pageDestructor() routine handles that chore.
drh7e3b0a02001-04-28 16:52:40 +0000270*/
271struct MemPage {
drha6abd042004-06-09 17:37:22 +0000272 u8 isInit; /* True if previously initialized. MUST BE FIRST! */
drh43605152004-05-29 21:46:49 +0000273 u8 idxShift; /* True if Cell indices have changed */
274 u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
275 u8 intKey; /* True if intkey flag is set */
276 u8 leaf; /* True if leaf flag is set */
277 u8 zeroData; /* True if table stores keys only */
278 u8 leafData; /* True if tables stores data on leaves only */
279 u8 hasData; /* True if this page stores data */
280 u8 hdrOffset; /* 100 for page 1. 0 otherwise */
drh271efa52004-05-30 19:19:05 +0000281 u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
drha2fce642004-06-05 00:01:44 +0000282 u16 maxLocal; /* Copy of Btree.maxLocal or Btree.maxLeaf */
283 u16 minLocal; /* Copy of Btree.minLocal or Btree.minLeaf */
drh43605152004-05-29 21:46:49 +0000284 u16 cellOffset; /* Index in aData of first cell pointer */
285 u16 idxParent; /* Index in parent of this node */
286 u16 nFree; /* Number of free bytes on the page */
287 u16 nCell; /* Number of cells on this page, local and ovfl */
288 struct _OvflCell { /* Cells that will not fit on aData[] */
danielk1977aef0bf62005-12-30 16:28:01 +0000289 u8 *pCell; /* Pointers to the body of the overflow cell */
290 u16 idx; /* Insert this cell before idx-th non-overflow cell */
drha2fce642004-06-05 00:01:44 +0000291 } aOvfl[5];
danielk1977aef0bf62005-12-30 16:28:01 +0000292 BtShared *pBt; /* Pointer back to BTree structure */
293 u8 *aData; /* Pointer back to the start of the page */
294 Pgno pgno; /* Page number for this page */
295 MemPage *pParent; /* The parent of this page. NULL for root */
drh8c42ca92001-06-22 19:15:00 +0000296};
drh7e3b0a02001-04-28 16:52:40 +0000297
298/*
drh3b7511c2001-05-26 13:15:44 +0000299** The in-memory image of a disk page has the auxiliary information appended
300** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
301** that extra information.
302*/
drh3aac2dd2004-04-26 14:10:20 +0000303#define EXTRA_SIZE sizeof(MemPage)
drh3b7511c2001-05-26 13:15:44 +0000304
danielk1977aef0bf62005-12-30 16:28:01 +0000305/* Btree handle */
306struct Btree {
307 sqlite3 *pSqlite;
308 BtShared *pBt;
309 u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
310};
311
312/*
313** Btree.inTrans may take one of the following values.
314**
315** If the shared-data extension is enabled, there may be multiple users
316** of the Btree structure. At most one of these may open a write transaction,
317** but any number may have active read transactions. Variable Btree.pDb
318** points to the handle that owns any current write-transaction.
319*/
320#define TRANS_NONE 0
321#define TRANS_READ 1
322#define TRANS_WRITE 2
323
drh3b7511c2001-05-26 13:15:44 +0000324/*
drha059ad02001-04-17 20:09:11 +0000325** Everything we need to know about an open database
326*/
danielk1977aef0bf62005-12-30 16:28:01 +0000327struct BtShared {
drha059ad02001-04-17 20:09:11 +0000328 Pager *pPager; /* The page cache */
drh306dc212001-05-21 13:45:10 +0000329 BtCursor *pCursor; /* A list of all open cursors */
drh3aac2dd2004-04-26 14:10:20 +0000330 MemPage *pPage1; /* First page of the database */
drhab01f612004-05-22 02:55:23 +0000331 u8 inStmt; /* True if we are in a statement subtransaction */
drh5df72a52002-06-06 23:16:05 +0000332 u8 readOnly; /* True if the underlying file is readonly */
drhab01f612004-05-22 02:55:23 +0000333 u8 maxEmbedFrac; /* Maximum payload as % of total page size */
334 u8 minEmbedFrac; /* Minimum payload as % of total page size */
335 u8 minLeafFrac; /* Minimum leaf payload as % of total page size */
drh90f5ecb2004-07-22 01:19:35 +0000336 u8 pageSizeFixed; /* True if the page size can no longer be changed */
drh057cd3a2005-02-15 16:23:02 +0000337#ifndef SQLITE_OMIT_AUTOVACUUM
338 u8 autoVacuum; /* True if database supports auto-vacuum */
339#endif
drha2fce642004-06-05 00:01:44 +0000340 u16 pageSize; /* Total number of bytes on a page */
341 u16 usableSize; /* Number of usable bytes on each page */
drh6f11bef2004-05-13 01:12:56 +0000342 int maxLocal; /* Maximum local payload in non-LEAFDATA tables */
343 int minLocal; /* Minimum local payload in non-LEAFDATA tables */
344 int maxLeaf; /* Maximum local payload in a LEAFDATA table */
345 int minLeaf; /* Minimum local payload in a LEAFDATA table */
drhb8ef32c2005-03-14 02:01:49 +0000346 BusyHandler *pBusyHandler; /* Callback for when there is lock contention */
danielk1977aef0bf62005-12-30 16:28:01 +0000347 u8 inTransaction; /* Transaction state */
348 BtShared *pNext; /* Next in SqliteTsd.pBtree linked list */
349 int nRef; /* Number of references to this structure */
350 int nTransaction; /* Number of open transactions (read + write) */
351 BtLock *pLock; /* List of locks held on this shared-btree struct */
drha059ad02001-04-17 20:09:11 +0000352};
danielk1977ee5741e2004-05-31 10:01:34 +0000353
354/*
drhfa1a98a2004-05-14 19:08:17 +0000355** An instance of the following structure is used to hold information
drh271efa52004-05-30 19:19:05 +0000356** about a cell. The parseCellPtr() function fills in this structure
drhab01f612004-05-22 02:55:23 +0000357** based on information extract from the raw disk page.
drhfa1a98a2004-05-14 19:08:17 +0000358*/
359typedef struct CellInfo CellInfo;
360struct CellInfo {
drh43605152004-05-29 21:46:49 +0000361 u8 *pCell; /* Pointer to the start of cell content */
drhfa1a98a2004-05-14 19:08:17 +0000362 i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
363 u32 nData; /* Number of bytes of data */
drh271efa52004-05-30 19:19:05 +0000364 u16 nHeader; /* Size of the cell content header in bytes */
drhfa1a98a2004-05-14 19:08:17 +0000365 u16 nLocal; /* Amount of payload held locally */
drhab01f612004-05-22 02:55:23 +0000366 u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
drh271efa52004-05-30 19:19:05 +0000367 u16 nSize; /* Size of the cell content on the main b-tree page */
drhfa1a98a2004-05-14 19:08:17 +0000368};
369
370/*
drh365d68f2001-05-11 11:02:46 +0000371** A cursor is a pointer to a particular entry in the BTree.
372** The entry is identified by its MemPage and the index in
drha34b6762004-05-07 13:30:42 +0000373** MemPage.aCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000374*/
drh72f82862001-05-24 21:06:34 +0000375struct BtCursor {
danielk1977aef0bf62005-12-30 16:28:01 +0000376 Btree *pBtree; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000377 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drh3aac2dd2004-04-26 14:10:20 +0000378 int (*xCompare)(void*,int,const void*,int,const void*); /* Key comp func */
379 void *pArg; /* First arg to xCompare() */
drh8b2f49b2001-06-08 00:21:52 +0000380 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000381 MemPage *pPage; /* Page that contains the entry */
drh3aac2dd2004-04-26 14:10:20 +0000382 int idx; /* Index of the entry in pPage->aCell[] */
drhfa1a98a2004-05-14 19:08:17 +0000383 CellInfo info; /* A parse of the cell we are pointing at */
drhecdc7532001-09-23 02:35:53 +0000384 u8 wrFlag; /* True if writable */
drhc39e0002004-05-07 23:50:57 +0000385 u8 isValid; /* TRUE if points to a valid entry */
drh365d68f2001-05-11 11:02:46 +0000386};
drh7e3b0a02001-04-28 16:52:40 +0000387
drha059ad02001-04-17 20:09:11 +0000388/*
drh615ae552005-01-16 23:21:00 +0000389** The TRACE macro will print high-level status information about the
390** btree operation when the global variable sqlite3_btree_trace is
391** enabled.
392*/
393#if SQLITE_TEST
394# define TRACE(X) if( sqlite3_btree_trace )\
395 { sqlite3DebugPrintf X; fflush(stdout); }
396#else
397# define TRACE(X)
398#endif
399int sqlite3_btree_trace=0; /* True to enable tracing */
400
401/*
drh66cbd152004-09-01 16:12:25 +0000402** Forward declaration
403*/
danielk1977aef0bf62005-12-30 16:28:01 +0000404static int checkReadLocks(BtShared*,Pgno,BtCursor*);
drh66cbd152004-09-01 16:12:25 +0000405
drh66cbd152004-09-01 16:12:25 +0000406/*
drhab01f612004-05-22 02:55:23 +0000407** Read or write a two- and four-byte big-endian integer values.
drh0d316a42002-08-11 20:10:47 +0000408*/
drh9e572e62004-04-23 23:43:10 +0000409static u32 get2byte(unsigned char *p){
410 return (p[0]<<8) | p[1];
drh0d316a42002-08-11 20:10:47 +0000411}
drh9e572e62004-04-23 23:43:10 +0000412static u32 get4byte(unsigned char *p){
413 return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
414}
drh9e572e62004-04-23 23:43:10 +0000415static void put2byte(unsigned char *p, u32 v){
416 p[0] = v>>8;
417 p[1] = v;
418}
419static void put4byte(unsigned char *p, u32 v){
420 p[0] = v>>24;
421 p[1] = v>>16;
422 p[2] = v>>8;
423 p[3] = v;
424}
drh6f11bef2004-05-13 01:12:56 +0000425
drh9e572e62004-04-23 23:43:10 +0000426/*
drhab01f612004-05-22 02:55:23 +0000427** Routines to read and write variable-length integers. These used to
428** be defined locally, but now we use the varint routines in the util.c
429** file.
drh9e572e62004-04-23 23:43:10 +0000430*/
drh6d2fb152004-05-14 16:50:06 +0000431#define getVarint sqlite3GetVarint
432#define getVarint32 sqlite3GetVarint32
433#define putVarint sqlite3PutVarint
drh0d316a42002-08-11 20:10:47 +0000434
danielk1977599fcba2004-11-08 07:13:13 +0000435/* The database page the PENDING_BYTE occupies. This page is never used.
436** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
437** should possibly be consolidated (presumably in pager.h).
438*/
439#define PENDING_BYTE_PAGE(pBt) ((PENDING_BYTE/(pBt)->pageSize)+1)
danielk1977afcdd022004-10-31 16:25:42 +0000440
danielk1977aef0bf62005-12-30 16:28:01 +0000441/*
442** A linked list of the following structures is stored at BtShared.pLock.
443** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
444** is opened on the table with root page BtShared.iTable. Locks are removed
445** from this list when a transaction is committed or rolled back, or when
446** a btree handle is closed.
447*/
448struct BtLock {
449 Btree *pBtree; /* Btree handle holding this lock */
450 Pgno iTable; /* Root page of table */
451 u8 eLock; /* READ_LOCK or WRITE_LOCK */
452 BtLock *pNext; /* Next in BtShared.pLock list */
453};
454
455/* Candidate values for BtLock.eLock */
456#define READ_LOCK 1
457#define WRITE_LOCK 2
458
459#ifdef SQLITE_OMIT_SHARED_CACHE
460 /*
461 ** The functions queryTableLock(), lockTable() and unlockAllTables()
462 ** manipulate entries in the BtShared.pLock linked list used to store
463 ** shared-cache table level locks. If the library is compiled with the
464 ** shared-cache feature disabled, then there is only ever one user
465 ** of each BtShared structure and so this locking is not required.
466 ** So define the three interface functions as no-ops.
467 */
468 #define queryTableLock(a,b,c) SQLITE_OK
469 #define lockTable(a,b,c) SQLITE_OK
470 #define unlockAllTables(a,b,c)
471#else
472
473/*
474** Query to see if btree handle p may obtain a lock of type eLock
475** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
476** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
477** SQLITE_BUSY if not.
478*/
479static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
480 BtShared *pBt = p->pBt;
481 BtLock *pIter;
482
483 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
484 if( pIter->pBtree!=p && pIter->iTable==iTab &&
485 (pIter->eLock!=READ_LOCK || eLock!=READ_LOCK) ){
486 return SQLITE_BUSY;
487 }
488 }
489 return SQLITE_OK;
490}
491
492/*
493** Add a lock on the table with root-page iTable to the shared-btree used
494** by Btree handle p. Parameter eLock must be either READ_LOCK or
495** WRITE_LOCK.
496**
497** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
498** SQLITE_NOMEM may also be returned.
499*/
500static int lockTable(Btree *p, Pgno iTable, u8 eLock){
501 BtShared *pBt = p->pBt;
502 BtLock *pLock = 0;
503 BtLock *pIter;
504
505 assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
506
507 /* First search the list for an existing lock on this table. */
508 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
509 if( pIter->iTable==iTable && pIter->pBtree==p ){
510 pLock = pIter;
511 break;
512 }
513 }
514
515 /* If the above search did not find a BtLock struct associating Btree p
516 ** with table iTable, allocate one and link it into the list.
517 */
518 if( !pLock ){
519 pLock = (BtLock *)sqliteMalloc(sizeof(BtLock));
520 if( !pLock ){
521 return SQLITE_NOMEM;
522 }
523 pLock->iTable = iTable;
524 pLock->pBtree = p;
525 pLock->pNext = pBt->pLock;
526 pBt->pLock = pLock;
527 }
528
529 /* Set the BtLock.eLock variable to the maximum of the current lock
530 ** and the requested lock. This means if a write-lock was already held
531 ** and a read-lock requested, we don't incorrectly downgrade the lock.
532 */
533 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000534 if( eLock>pLock->eLock ){
535 pLock->eLock = eLock;
536 }
danielk1977aef0bf62005-12-30 16:28:01 +0000537
538 return SQLITE_OK;
539}
540
541/*
542** Release all the table locks (locks obtained via calls to the lockTable()
543** procedure) held by Btree handle p.
544*/
545static void unlockAllTables(Btree *p){
546 BtLock **ppIter = &p->pBt->pLock;
547 while( *ppIter ){
548 BtLock *pLock = *ppIter;
549 if( pLock->pBtree==p ){
550 *ppIter = pLock->pNext;
551 sqliteFree(pLock);
552 }else{
553 ppIter = &pLock->pNext;
554 }
555 }
556}
557#endif /* SQLITE_OMIT_SHARED_CACHE */
558
danielk1977599fcba2004-11-08 07:13:13 +0000559#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000560/*
drh42cac6d2004-11-20 20:31:11 +0000561** These macros define the location of the pointer-map entry for a
562** database page. The first argument to each is the number of usable
563** bytes on each page of the database (often 1024). The second is the
564** page number to look up in the pointer map.
danielk1977afcdd022004-10-31 16:25:42 +0000565**
566** PTRMAP_PAGENO returns the database page number of the pointer-map
567** page that stores the required pointer. PTRMAP_PTROFFSET returns
568** the offset of the requested map entry.
569**
570** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
571** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
danielk1977599fcba2004-11-08 07:13:13 +0000572** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
573** this test.
danielk1977afcdd022004-10-31 16:25:42 +0000574*/
575#define PTRMAP_PAGENO(pgsz, pgno) (((pgno-2)/(pgsz/5+1))*(pgsz/5+1)+2)
576#define PTRMAP_PTROFFSET(pgsz, pgno) (((pgno-2)%(pgsz/5+1)-1)*5)
danielk1977a19df672004-11-03 11:37:07 +0000577#define PTRMAP_ISPAGE(pgsz, pgno) (PTRMAP_PAGENO(pgsz,pgno)==pgno)
578
danielk1977afcdd022004-10-31 16:25:42 +0000579/*
drh615ae552005-01-16 23:21:00 +0000580** The pointer map is a lookup table that identifies the parent page for
581** each child page in the database file. The parent page is the page that
582** contains a pointer to the child. Every page in the database contains
583** 0 or 1 parent pages. (In this context 'database page' refers
584** to any page that is not part of the pointer map itself.) Each pointer map
585** entry consists of a single byte 'type' and a 4 byte parent page number.
586** The PTRMAP_XXX identifiers below are the valid types.
587**
588** The purpose of the pointer map is to facility moving pages from one
589** position in the file to another as part of autovacuum. When a page
590** is moved, the pointer in its parent must be updated to point to the
591** new location. The pointer map is used to locate the parent page quickly.
danielk1977afcdd022004-10-31 16:25:42 +0000592**
danielk1977687566d2004-11-02 12:56:41 +0000593** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
594** used in this case.
danielk1977afcdd022004-10-31 16:25:42 +0000595**
danielk1977687566d2004-11-02 12:56:41 +0000596** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
597** is not used in this case.
598**
599** PTRMAP_OVERFLOW1: The database page is the first page in a list of
600** overflow pages. The page number identifies the page that
601** contains the cell with a pointer to this overflow page.
602**
603** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
604** overflow pages. The page-number identifies the previous
605** page in the overflow page list.
606**
607** PTRMAP_BTREE: The database page is a non-root btree page. The page number
608** identifies the parent page in the btree.
danielk1977afcdd022004-10-31 16:25:42 +0000609*/
danielk1977687566d2004-11-02 12:56:41 +0000610#define PTRMAP_ROOTPAGE 1
611#define PTRMAP_FREEPAGE 2
612#define PTRMAP_OVERFLOW1 3
613#define PTRMAP_OVERFLOW2 4
614#define PTRMAP_BTREE 5
danielk1977afcdd022004-10-31 16:25:42 +0000615
616/*
617** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000618**
619** This routine updates the pointer map entry for page number 'key'
620** so that it maps to type 'eType' and parent page number 'pgno'.
621** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000622*/
danielk1977aef0bf62005-12-30 16:28:01 +0000623static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
danielk1977afcdd022004-10-31 16:25:42 +0000624 u8 *pPtrmap; /* The pointer map page */
625 Pgno iPtrmap; /* The pointer map page number */
626 int offset; /* Offset in pointer map page */
627 int rc;
628
danielk1977ac11ee62005-01-15 12:45:51 +0000629 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000630 if( key==0 ){
drh49285702005-09-17 15:20:26 +0000631 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000632 }
drh42cac6d2004-11-20 20:31:11 +0000633 iPtrmap = PTRMAP_PAGENO(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000634 rc = sqlite3pager_get(pBt->pPager, iPtrmap, (void **)&pPtrmap);
danielk1977687566d2004-11-02 12:56:41 +0000635 if( rc!=SQLITE_OK ){
danielk1977afcdd022004-10-31 16:25:42 +0000636 return rc;
637 }
drh42cac6d2004-11-20 20:31:11 +0000638 offset = PTRMAP_PTROFFSET(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000639
drh615ae552005-01-16 23:21:00 +0000640 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
641 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
danielk1977afcdd022004-10-31 16:25:42 +0000642 rc = sqlite3pager_write(pPtrmap);
danielk19775558a8a2005-01-17 07:53:44 +0000643 if( rc==SQLITE_OK ){
644 pPtrmap[offset] = eType;
645 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000646 }
danielk1977afcdd022004-10-31 16:25:42 +0000647 }
648
649 sqlite3pager_unref(pPtrmap);
danielk19775558a8a2005-01-17 07:53:44 +0000650 return rc;
danielk1977afcdd022004-10-31 16:25:42 +0000651}
652
653/*
654** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000655**
656** This routine retrieves the pointer map entry for page 'key', writing
657** the type and parent page number to *pEType and *pPgno respectively.
658** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000659*/
danielk1977aef0bf62005-12-30 16:28:01 +0000660static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk1977afcdd022004-10-31 16:25:42 +0000661 int iPtrmap; /* Pointer map page index */
662 u8 *pPtrmap; /* Pointer map page data */
663 int offset; /* Offset of entry in pointer map */
664 int rc;
665
drh42cac6d2004-11-20 20:31:11 +0000666 iPtrmap = PTRMAP_PAGENO(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000667 rc = sqlite3pager_get(pBt->pPager, iPtrmap, (void **)&pPtrmap);
668 if( rc!=0 ){
669 return rc;
670 }
671
drh42cac6d2004-11-20 20:31:11 +0000672 offset = PTRMAP_PTROFFSET(pBt->usableSize, key);
danielk1977687566d2004-11-02 12:56:41 +0000673 if( pEType ) *pEType = pPtrmap[offset];
674 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000675
676 sqlite3pager_unref(pPtrmap);
drh49285702005-09-17 15:20:26 +0000677 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000678 return SQLITE_OK;
679}
680
681#endif /* SQLITE_OMIT_AUTOVACUUM */
682
drh0d316a42002-08-11 20:10:47 +0000683/*
danielk1977aef0bf62005-12-30 16:28:01 +0000684** Return a pointer to the Btree structure associated with btree pBt
685** and connection handle pSqlite.
686*/
687#if 0
688static Btree *btree_findref(BtShared *pBt, sqlite3 *pSqlite){
689#ifndef SQLITE_OMIT_SHARED_DATA
690 if( pBt->aRef ){
691 int i;
692 for(i=0; i<pBt->nRef; i++){
693 if( pBt->aRef[i].pSqlite==pSqlite ){
694 return &pBt->aRef[i];
695 }
696 }
697 assert(0);
698 }
699#endif
700 return &pBt->ref;
701}
702#endif
703
704/*
drh271efa52004-05-30 19:19:05 +0000705** Given a btree page and a cell index (0 means the first cell on
706** the page, 1 means the second cell, and so forth) return a pointer
707** to the cell content.
708**
709** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000710*/
drh43605152004-05-29 21:46:49 +0000711static u8 *findCell(MemPage *pPage, int iCell){
712 u8 *data = pPage->aData;
713 assert( iCell>=0 );
714 assert( iCell<get2byte(&data[pPage->hdrOffset+3]) );
715 return data + get2byte(&data[pPage->cellOffset+2*iCell]);
716}
717
718/*
719** This a more complex version of findCell() that works for
720** pages that do contain overflow cells. See insert
721*/
722static u8 *findOverflowCell(MemPage *pPage, int iCell){
723 int i;
724 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000725 int k;
726 struct _OvflCell *pOvfl;
727 pOvfl = &pPage->aOvfl[i];
728 k = pOvfl->idx;
729 if( k<=iCell ){
730 if( k==iCell ){
731 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000732 }
733 iCell--;
734 }
735 }
736 return findCell(pPage, iCell);
737}
738
739/*
740** Parse a cell content block and fill in the CellInfo structure. There
741** are two versions of this function. parseCell() takes a cell index
742** as the second argument and parseCellPtr() takes a pointer to the
743** body of the cell as its second argument.
744*/
745static void parseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000746 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000747 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000748 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000749){
drh271efa52004-05-30 19:19:05 +0000750 int n; /* Number bytes in cell content header */
751 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000752
753 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000754 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000755 n = pPage->childPtrSize;
756 assert( n==4-4*pPage->leaf );
drh8b18dd42004-05-12 19:18:15 +0000757 if( pPage->hasData ){
drh271efa52004-05-30 19:19:05 +0000758 n += getVarint32(&pCell[n], &nPayload);
drh8b18dd42004-05-12 19:18:15 +0000759 }else{
drh271efa52004-05-30 19:19:05 +0000760 nPayload = 0;
drh3aac2dd2004-04-26 14:10:20 +0000761 }
danielk1977e0d4b062004-06-28 01:11:46 +0000762 n += getVarint(&pCell[n], (u64 *)&pInfo->nKey);
drh6f11bef2004-05-13 01:12:56 +0000763 pInfo->nHeader = n;
drh271efa52004-05-30 19:19:05 +0000764 pInfo->nData = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000765 if( !pPage->intKey ){
766 nPayload += pInfo->nKey;
767 }
drh271efa52004-05-30 19:19:05 +0000768 if( nPayload<=pPage->maxLocal ){
769 /* This is the (easy) common case where the entire payload fits
770 ** on the local page. No overflow is required.
771 */
772 int nSize; /* Total size of cell content in bytes */
drh6f11bef2004-05-13 01:12:56 +0000773 pInfo->nLocal = nPayload;
774 pInfo->iOverflow = 0;
drh271efa52004-05-30 19:19:05 +0000775 nSize = nPayload + n;
776 if( nSize<4 ){
777 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000778 }
drh271efa52004-05-30 19:19:05 +0000779 pInfo->nSize = nSize;
drh6f11bef2004-05-13 01:12:56 +0000780 }else{
drh271efa52004-05-30 19:19:05 +0000781 /* If the payload will not fit completely on the local page, we have
782 ** to decide how much to store locally and how much to spill onto
783 ** overflow pages. The strategy is to minimize the amount of unused
784 ** space on overflow pages while keeping the amount of local storage
785 ** in between minLocal and maxLocal.
786 **
787 ** Warning: changing the way overflow payload is distributed in any
788 ** way will result in an incompatible file format.
789 */
790 int minLocal; /* Minimum amount of payload held locally */
791 int maxLocal; /* Maximum amount of payload held locally */
792 int surplus; /* Overflow payload available for local storage */
793
794 minLocal = pPage->minLocal;
795 maxLocal = pPage->maxLocal;
796 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000797 if( surplus <= maxLocal ){
798 pInfo->nLocal = surplus;
799 }else{
800 pInfo->nLocal = minLocal;
801 }
802 pInfo->iOverflow = pInfo->nLocal + n;
803 pInfo->nSize = pInfo->iOverflow + 4;
804 }
drh3aac2dd2004-04-26 14:10:20 +0000805}
drh43605152004-05-29 21:46:49 +0000806static void parseCell(
807 MemPage *pPage, /* Page containing the cell */
808 int iCell, /* The cell index. First cell is 0 */
809 CellInfo *pInfo /* Fill in this structure */
810){
811 parseCellPtr(pPage, findCell(pPage, iCell), pInfo);
812}
drh3aac2dd2004-04-26 14:10:20 +0000813
814/*
drh43605152004-05-29 21:46:49 +0000815** Compute the total number of bytes that a Cell needs in the cell
816** data area of the btree-page. The return number includes the cell
817** data header and the local payload, but not any overflow page or
818** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000819*/
danielk1977bc6ada42004-06-30 08:20:16 +0000820#ifndef NDEBUG
drh43605152004-05-29 21:46:49 +0000821static int cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000822 CellInfo info;
drh43605152004-05-29 21:46:49 +0000823 parseCell(pPage, iCell, &info);
824 return info.nSize;
825}
danielk1977bc6ada42004-06-30 08:20:16 +0000826#endif
drh43605152004-05-29 21:46:49 +0000827static int cellSizePtr(MemPage *pPage, u8 *pCell){
828 CellInfo info;
829 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000830 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000831}
832
danielk197779a40da2005-01-16 08:00:01 +0000833#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +0000834/*
danielk197726836652005-01-17 01:33:13 +0000835** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +0000836** to an overflow page, insert an entry into the pointer-map
837** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +0000838*/
danielk197726836652005-01-17 01:33:13 +0000839static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
danielk197779a40da2005-01-16 08:00:01 +0000840 if( pCell ){
841 CellInfo info;
842 parseCellPtr(pPage, pCell, &info);
843 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
844 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
845 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
846 }
danielk1977ac11ee62005-01-15 12:45:51 +0000847 }
danielk197779a40da2005-01-16 08:00:01 +0000848 return SQLITE_OK;
danielk1977ac11ee62005-01-15 12:45:51 +0000849}
danielk197726836652005-01-17 01:33:13 +0000850/*
851** If the cell with index iCell on page pPage contains a pointer
852** to an overflow page, insert an entry into the pointer-map
853** for the overflow page.
854*/
855static int ptrmapPutOvfl(MemPage *pPage, int iCell){
856 u8 *pCell;
857 pCell = findOverflowCell(pPage, iCell);
858 return ptrmapPutOvflPtr(pPage, pCell);
859}
danielk197779a40da2005-01-16 08:00:01 +0000860#endif
861
danielk1977ac11ee62005-01-15 12:45:51 +0000862
863/*
drhda200cc2004-05-09 11:51:38 +0000864** Do sanity checking on a page. Throw an exception if anything is
865** not right.
866**
867** This routine is used for internal error checking only. It is omitted
868** from most builds.
869*/
870#if defined(BTREE_DEBUG) && !defined(NDEBUG) && 0
871static void _pageIntegrity(MemPage *pPage){
drhb6f41482004-05-14 01:58:11 +0000872 int usableSize;
drhda200cc2004-05-09 11:51:38 +0000873 u8 *data;
drh43605152004-05-29 21:46:49 +0000874 int i, j, idx, c, pc, hdr, nFree;
875 int cellOffset;
876 int nCell, cellLimit;
drh2e38c322004-09-03 18:38:44 +0000877 u8 *used;
drhda200cc2004-05-09 11:51:38 +0000878
drh2e38c322004-09-03 18:38:44 +0000879 used = sqliteMallocRaw( pPage->pBt->pageSize );
880 if( used==0 ) return;
drhb6f41482004-05-14 01:58:11 +0000881 usableSize = pPage->pBt->usableSize;
drh07d183d2005-05-01 22:52:42 +0000882 assert( pPage->aData==&((unsigned char*)pPage)[-pPage->pBt->pageSize] );
drhda200cc2004-05-09 11:51:38 +0000883 hdr = pPage->hdrOffset;
884 assert( hdr==(pPage->pgno==1 ? 100 : 0) );
885 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
886 c = pPage->aData[hdr];
887 if( pPage->isInit ){
888 assert( pPage->leaf == ((c & PTF_LEAF)!=0) );
889 assert( pPage->zeroData == ((c & PTF_ZERODATA)!=0) );
drh8b18dd42004-05-12 19:18:15 +0000890 assert( pPage->leafData == ((c & PTF_LEAFDATA)!=0) );
891 assert( pPage->intKey == ((c & (PTF_INTKEY|PTF_LEAFDATA))!=0) );
892 assert( pPage->hasData ==
893 !(pPage->zeroData || (!pPage->leaf && pPage->leafData)) );
drh43605152004-05-29 21:46:49 +0000894 assert( pPage->cellOffset==pPage->hdrOffset+12-4*pPage->leaf );
895 assert( pPage->nCell = get2byte(&pPage->aData[hdr+3]) );
drhda200cc2004-05-09 11:51:38 +0000896 }
897 data = pPage->aData;
drhb6f41482004-05-14 01:58:11 +0000898 memset(used, 0, usableSize);
drhda200cc2004-05-09 11:51:38 +0000899 for(i=0; i<hdr+10-pPage->leaf*4; i++) used[i] = 1;
900 nFree = 0;
901 pc = get2byte(&data[hdr+1]);
902 while( pc ){
903 int size;
drhb6f41482004-05-14 01:58:11 +0000904 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +0000905 size = get2byte(&data[pc+2]);
drhb6f41482004-05-14 01:58:11 +0000906 assert( pc+size<=usableSize );
drhda200cc2004-05-09 11:51:38 +0000907 nFree += size;
908 for(i=pc; i<pc+size; i++){
909 assert( used[i]==0 );
910 used[i] = 1;
911 }
912 pc = get2byte(&data[pc]);
913 }
drhda200cc2004-05-09 11:51:38 +0000914 idx = 0;
drh43605152004-05-29 21:46:49 +0000915 nCell = get2byte(&data[hdr+3]);
916 cellLimit = get2byte(&data[hdr+5]);
917 assert( pPage->isInit==0
918 || pPage->nFree==nFree+data[hdr+7]+cellLimit-(cellOffset+2*nCell) );
919 cellOffset = pPage->cellOffset;
920 for(i=0; i<nCell; i++){
drhda200cc2004-05-09 11:51:38 +0000921 int size;
drh43605152004-05-29 21:46:49 +0000922 pc = get2byte(&data[cellOffset+2*i]);
drhb6f41482004-05-14 01:58:11 +0000923 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +0000924 size = cellSize(pPage, &data[pc]);
drhb6f41482004-05-14 01:58:11 +0000925 assert( pc+size<=usableSize );
drh43605152004-05-29 21:46:49 +0000926 for(j=pc; j<pc+size; j++){
927 assert( used[j]==0 );
928 used[j] = 1;
drhda200cc2004-05-09 11:51:38 +0000929 }
drhda200cc2004-05-09 11:51:38 +0000930 }
drh43605152004-05-29 21:46:49 +0000931 for(i=cellOffset+2*nCell; i<cellimit; i++){
932 assert( used[i]==0 );
933 used[i] = 1;
934 }
drhda200cc2004-05-09 11:51:38 +0000935 nFree = 0;
drhb6f41482004-05-14 01:58:11 +0000936 for(i=0; i<usableSize; i++){
drhda200cc2004-05-09 11:51:38 +0000937 assert( used[i]<=1 );
938 if( used[i]==0 ) nFree++;
939 }
drh43605152004-05-29 21:46:49 +0000940 assert( nFree==data[hdr+7] );
drh2e38c322004-09-03 18:38:44 +0000941 sqliteFree(used);
drhda200cc2004-05-09 11:51:38 +0000942}
943#define pageIntegrity(X) _pageIntegrity(X)
944#else
945# define pageIntegrity(X)
946#endif
947
danielk1977aef0bf62005-12-30 16:28:01 +0000948/* A bunch of assert() statements to check the transaction state variables
949** of handle p (type Btree*) are internally consistent.
950*/
951#define btreeIntegrity(p) \
952 assert( p->inTrans!=TRANS_NONE || p->pBt->nTransaction<p->pBt->nRef ); \
953 assert( p->pBt->nTransaction<=p->pBt->nRef ); \
954 assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
955 assert( p->pBt->inTransaction>=p->inTrans );
956
drhda200cc2004-05-09 11:51:38 +0000957/*
drh72f82862001-05-24 21:06:34 +0000958** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +0000959** end of the page and all free space is collected into one
960** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +0000961** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +0000962*/
drh2e38c322004-09-03 18:38:44 +0000963static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000964 int i; /* Loop counter */
965 int pc; /* Address of a i-th cell */
966 int addr; /* Offset of first byte after cell pointer array */
967 int hdr; /* Offset to the page header */
968 int size; /* Size of a cell */
969 int usableSize; /* Number of usable bytes on a page */
970 int cellOffset; /* Offset to the cell pointer array */
971 int brk; /* Offset to the cell content area */
972 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +0000973 unsigned char *data; /* The page data */
974 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +0000975
drha34b6762004-05-07 13:30:42 +0000976 assert( sqlite3pager_iswriteable(pPage->aData) );
drh9e572e62004-04-23 23:43:10 +0000977 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +0000978 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000979 assert( pPage->nOverflow==0 );
drh2e38c322004-09-03 18:38:44 +0000980 temp = sqliteMalloc( pPage->pBt->pageSize );
981 if( temp==0 ) return SQLITE_NOMEM;
drh43605152004-05-29 21:46:49 +0000982 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000983 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000984 cellOffset = pPage->cellOffset;
985 nCell = pPage->nCell;
986 assert( nCell==get2byte(&data[hdr+3]) );
987 usableSize = pPage->pBt->usableSize;
988 brk = get2byte(&data[hdr+5]);
989 memcpy(&temp[brk], &data[brk], usableSize - brk);
990 brk = usableSize;
991 for(i=0; i<nCell; i++){
992 u8 *pAddr; /* The i-th cell pointer */
993 pAddr = &data[cellOffset + i*2];
994 pc = get2byte(pAddr);
995 assert( pc<pPage->pBt->usableSize );
996 size = cellSizePtr(pPage, &temp[pc]);
997 brk -= size;
998 memcpy(&data[brk], &temp[pc], size);
999 put2byte(pAddr, brk);
drh2af926b2001-05-15 00:39:25 +00001000 }
drh43605152004-05-29 21:46:49 +00001001 assert( brk>=cellOffset+2*nCell );
1002 put2byte(&data[hdr+5], brk);
1003 data[hdr+1] = 0;
1004 data[hdr+2] = 0;
1005 data[hdr+7] = 0;
1006 addr = cellOffset+2*nCell;
1007 memset(&data[addr], 0, brk-addr);
drh2e38c322004-09-03 18:38:44 +00001008 sqliteFree(temp);
1009 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +00001010}
1011
drha059ad02001-04-17 20:09:11 +00001012/*
drh43605152004-05-29 21:46:49 +00001013** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +00001014**
drh9e572e62004-04-23 23:43:10 +00001015** Return the index into pPage->aData[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +00001016** the new allocation. Or return 0 if there is not enough free
1017** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +00001018**
drh72f82862001-05-24 21:06:34 +00001019** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +00001020** nBytes of contiguous free space, then this routine automatically
1021** calls defragementPage() to consolidate all free space before
1022** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +00001023*/
drh9e572e62004-04-23 23:43:10 +00001024static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +00001025 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +00001026 int size;
drh24cd67e2004-05-10 16:18:47 +00001027 int nFrag;
drh43605152004-05-29 21:46:49 +00001028 int top;
1029 int nCell;
1030 int cellOffset;
drh9e572e62004-04-23 23:43:10 +00001031 unsigned char *data;
drh43605152004-05-29 21:46:49 +00001032
drh9e572e62004-04-23 23:43:10 +00001033 data = pPage->aData;
drha34b6762004-05-07 13:30:42 +00001034 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +00001035 assert( pPage->pBt );
1036 if( nByte<4 ) nByte = 4;
drh43605152004-05-29 21:46:49 +00001037 if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
1038 pPage->nFree -= nByte;
drh9e572e62004-04-23 23:43:10 +00001039 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001040
1041 nFrag = data[hdr+7];
1042 if( nFrag<60 ){
1043 /* Search the freelist looking for a slot big enough to satisfy the
1044 ** space request. */
1045 addr = hdr+1;
1046 while( (pc = get2byte(&data[addr]))>0 ){
1047 size = get2byte(&data[pc+2]);
1048 if( size>=nByte ){
1049 if( size<nByte+4 ){
1050 memcpy(&data[addr], &data[pc], 2);
1051 data[hdr+7] = nFrag + size - nByte;
1052 return pc;
1053 }else{
1054 put2byte(&data[pc+2], size-nByte);
1055 return pc + size - nByte;
1056 }
1057 }
1058 addr = pc;
drh9e572e62004-04-23 23:43:10 +00001059 }
1060 }
drh43605152004-05-29 21:46:49 +00001061
1062 /* Allocate memory from the gap in between the cell pointer array
1063 ** and the cell content area.
1064 */
1065 top = get2byte(&data[hdr+5]);
1066 nCell = get2byte(&data[hdr+3]);
1067 cellOffset = pPage->cellOffset;
1068 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
drh2e38c322004-09-03 18:38:44 +00001069 if( defragmentPage(pPage) ) return 0;
drh43605152004-05-29 21:46:49 +00001070 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +00001071 }
drh43605152004-05-29 21:46:49 +00001072 top -= nByte;
1073 assert( cellOffset + 2*nCell <= top );
1074 put2byte(&data[hdr+5], top);
1075 return top;
drh7e3b0a02001-04-28 16:52:40 +00001076}
1077
1078/*
drh9e572e62004-04-23 23:43:10 +00001079** Return a section of the pPage->aData to the freelist.
1080** The first byte of the new free block is pPage->aDisk[start]
1081** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +00001082**
1083** Most of the effort here is involved in coalesing adjacent
1084** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +00001085*/
drh9e572e62004-04-23 23:43:10 +00001086static void freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +00001087 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +00001088 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +00001089
drh9e572e62004-04-23 23:43:10 +00001090 assert( pPage->pBt!=0 );
drha34b6762004-05-07 13:30:42 +00001091 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +00001092 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +00001093 assert( (start + size)<=pPage->pBt->usableSize );
drh9e572e62004-04-23 23:43:10 +00001094 if( size<4 ) size = 4;
1095
1096 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +00001097 hdr = pPage->hdrOffset;
1098 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +00001099 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +00001100 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +00001101 assert( pbegin>addr );
1102 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +00001103 }
drhb6f41482004-05-14 01:58:11 +00001104 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +00001105 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +00001106 put2byte(&data[addr], start);
1107 put2byte(&data[start], pbegin);
1108 put2byte(&data[start+2], size);
drh2af926b2001-05-15 00:39:25 +00001109 pPage->nFree += size;
drh9e572e62004-04-23 23:43:10 +00001110
1111 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +00001112 addr = pPage->hdrOffset + 1;
1113 while( (pbegin = get2byte(&data[addr]))>0 ){
drh9e572e62004-04-23 23:43:10 +00001114 int pnext, psize;
drh3aac2dd2004-04-26 14:10:20 +00001115 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +00001116 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +00001117 pnext = get2byte(&data[pbegin]);
1118 psize = get2byte(&data[pbegin+2]);
1119 if( pbegin + psize + 3 >= pnext && pnext>0 ){
1120 int frag = pnext - (pbegin+psize);
drh43605152004-05-29 21:46:49 +00001121 assert( frag<=data[pPage->hdrOffset+7] );
1122 data[pPage->hdrOffset+7] -= frag;
drh9e572e62004-04-23 23:43:10 +00001123 put2byte(&data[pbegin], get2byte(&data[pnext]));
1124 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
1125 }else{
drh3aac2dd2004-04-26 14:10:20 +00001126 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +00001127 }
1128 }
drh7e3b0a02001-04-28 16:52:40 +00001129
drh43605152004-05-29 21:46:49 +00001130 /* If the cell content area begins with a freeblock, remove it. */
1131 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
1132 int top;
1133 pbegin = get2byte(&data[hdr+1]);
1134 memcpy(&data[hdr+1], &data[pbegin], 2);
1135 top = get2byte(&data[hdr+5]);
1136 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
drh4b70f112004-05-02 21:12:19 +00001137 }
drh4b70f112004-05-02 21:12:19 +00001138}
1139
1140/*
drh271efa52004-05-30 19:19:05 +00001141** Decode the flags byte (the first byte of the header) for a page
1142** and initialize fields of the MemPage structure accordingly.
1143*/
1144static void decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +00001145 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +00001146
1147 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
1148 pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
1149 pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
1150 pPage->leaf = (flagByte & PTF_LEAF)!=0;
1151 pPage->childPtrSize = 4*(pPage->leaf==0);
1152 pBt = pPage->pBt;
1153 if( flagByte & PTF_LEAFDATA ){
1154 pPage->leafData = 1;
1155 pPage->maxLocal = pBt->maxLeaf;
1156 pPage->minLocal = pBt->minLeaf;
1157 }else{
1158 pPage->leafData = 0;
1159 pPage->maxLocal = pBt->maxLocal;
1160 pPage->minLocal = pBt->minLocal;
1161 }
1162 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
1163}
1164
1165/*
drh7e3b0a02001-04-28 16:52:40 +00001166** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001167**
drhbd03cae2001-06-02 02:40:57 +00001168** The pParent parameter must be a pointer to the MemPage which
drh9e572e62004-04-23 23:43:10 +00001169** is the parent of the page being initialized. The root of a
1170** BTree has no parent and so for that page, pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +00001171**
drh72f82862001-05-24 21:06:34 +00001172** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001173** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001174** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1175** guarantee that the page is well-formed. It only shows that
1176** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001177*/
drh9e572e62004-04-23 23:43:10 +00001178static int initPage(
drh3aac2dd2004-04-26 14:10:20 +00001179 MemPage *pPage, /* The page to be initialized */
drh9e572e62004-04-23 23:43:10 +00001180 MemPage *pParent /* The parent. Might be NULL */
1181){
drh271efa52004-05-30 19:19:05 +00001182 int pc; /* Address of a freeblock within pPage->aData[] */
drh271efa52004-05-30 19:19:05 +00001183 int hdr; /* Offset to beginning of page header */
1184 u8 *data; /* Equal to pPage->aData */
danielk1977aef0bf62005-12-30 16:28:01 +00001185 BtShared *pBt; /* The main btree structure */
drh271efa52004-05-30 19:19:05 +00001186 int usableSize; /* Amount of usable space on each page */
1187 int cellOffset; /* Offset from start of page to first cell pointer */
1188 int nFree; /* Number of unused bytes on the page */
1189 int top; /* First byte of the cell content area */
drh2af926b2001-05-15 00:39:25 +00001190
drh2e38c322004-09-03 18:38:44 +00001191 pBt = pPage->pBt;
1192 assert( pBt!=0 );
1193 assert( pParent==0 || pParent->pBt==pBt );
drha34b6762004-05-07 13:30:42 +00001194 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
drh07d183d2005-05-01 22:52:42 +00001195 assert( pPage->aData == &((unsigned char*)pPage)[-pBt->pageSize] );
drhee696e22004-08-30 16:52:17 +00001196 if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
1197 /* The parent page should never change unless the file is corrupt */
drh49285702005-09-17 15:20:26 +00001198 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001199 }
drh10617cd2004-05-14 15:27:27 +00001200 if( pPage->isInit ) return SQLITE_OK;
drhda200cc2004-05-09 11:51:38 +00001201 if( pPage->pParent==0 && pParent!=0 ){
1202 pPage->pParent = pParent;
drha34b6762004-05-07 13:30:42 +00001203 sqlite3pager_ref(pParent->aData);
drh5e2f8b92001-05-28 00:41:15 +00001204 }
drhde647132004-05-07 17:57:49 +00001205 hdr = pPage->hdrOffset;
drha34b6762004-05-07 13:30:42 +00001206 data = pPage->aData;
drh271efa52004-05-30 19:19:05 +00001207 decodeFlags(pPage, data[hdr]);
drh43605152004-05-29 21:46:49 +00001208 pPage->nOverflow = 0;
drhc8629a12004-05-08 20:07:40 +00001209 pPage->idxShift = 0;
drh2e38c322004-09-03 18:38:44 +00001210 usableSize = pBt->usableSize;
drh43605152004-05-29 21:46:49 +00001211 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
1212 top = get2byte(&data[hdr+5]);
1213 pPage->nCell = get2byte(&data[hdr+3]);
drh2e38c322004-09-03 18:38:44 +00001214 if( pPage->nCell>MX_CELL(pBt) ){
drhee696e22004-08-30 16:52:17 +00001215 /* To many cells for a single page. The page must be corrupt */
drh49285702005-09-17 15:20:26 +00001216 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001217 }
1218 if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
1219 /* All pages must have at least one cell, except for root pages */
drh49285702005-09-17 15:20:26 +00001220 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001221 }
drh9e572e62004-04-23 23:43:10 +00001222
1223 /* Compute the total free space on the page */
drh9e572e62004-04-23 23:43:10 +00001224 pc = get2byte(&data[hdr+1]);
drh43605152004-05-29 21:46:49 +00001225 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
drh9e572e62004-04-23 23:43:10 +00001226 while( pc>0 ){
1227 int next, size;
drhee696e22004-08-30 16:52:17 +00001228 if( pc>usableSize-4 ){
1229 /* Free block is off the page */
drh49285702005-09-17 15:20:26 +00001230 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001231 }
drh9e572e62004-04-23 23:43:10 +00001232 next = get2byte(&data[pc]);
1233 size = get2byte(&data[pc+2]);
drhee696e22004-08-30 16:52:17 +00001234 if( next>0 && next<=pc+size+3 ){
1235 /* Free blocks must be in accending order */
drh49285702005-09-17 15:20:26 +00001236 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001237 }
drh3add3672004-05-15 00:29:24 +00001238 nFree += size;
drh9e572e62004-04-23 23:43:10 +00001239 pc = next;
1240 }
drh3add3672004-05-15 00:29:24 +00001241 pPage->nFree = nFree;
drhee696e22004-08-30 16:52:17 +00001242 if( nFree>=usableSize ){
1243 /* Free space cannot exceed total page size */
drh49285702005-09-17 15:20:26 +00001244 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001245 }
drh9e572e62004-04-23 23:43:10 +00001246
drhde647132004-05-07 17:57:49 +00001247 pPage->isInit = 1;
drhda200cc2004-05-09 11:51:38 +00001248 pageIntegrity(pPage);
drh9e572e62004-04-23 23:43:10 +00001249 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001250}
1251
1252/*
drh8b2f49b2001-06-08 00:21:52 +00001253** Set up a raw page so that it looks like a database page holding
1254** no entries.
drhbd03cae2001-06-02 02:40:57 +00001255*/
drh9e572e62004-04-23 23:43:10 +00001256static void zeroPage(MemPage *pPage, int flags){
1257 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001258 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00001259 int hdr = pPage->hdrOffset;
drh9e572e62004-04-23 23:43:10 +00001260 int first;
1261
drhda200cc2004-05-09 11:51:38 +00001262 assert( sqlite3pager_pagenumber(data)==pPage->pgno );
drh07d183d2005-05-01 22:52:42 +00001263 assert( &data[pBt->pageSize] == (unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +00001264 assert( sqlite3pager_iswriteable(data) );
drhb6f41482004-05-14 01:58:11 +00001265 memset(&data[hdr], 0, pBt->usableSize - hdr);
drh9e572e62004-04-23 23:43:10 +00001266 data[hdr] = flags;
drh43605152004-05-29 21:46:49 +00001267 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
1268 memset(&data[hdr+1], 0, 4);
1269 data[hdr+7] = 0;
1270 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +00001271 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +00001272 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +00001273 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +00001274 pPage->cellOffset = first;
1275 pPage->nOverflow = 0;
drhda200cc2004-05-09 11:51:38 +00001276 pPage->idxShift = 0;
drh43605152004-05-29 21:46:49 +00001277 pPage->nCell = 0;
drhda200cc2004-05-09 11:51:38 +00001278 pPage->isInit = 1;
1279 pageIntegrity(pPage);
drhbd03cae2001-06-02 02:40:57 +00001280}
1281
1282/*
drh3aac2dd2004-04-26 14:10:20 +00001283** Get a page from the pager. Initialize the MemPage.pBt and
1284** MemPage.aData elements if needed.
1285*/
danielk1977aef0bf62005-12-30 16:28:01 +00001286static int getPage(BtShared *pBt, Pgno pgno, MemPage **ppPage){
drh3aac2dd2004-04-26 14:10:20 +00001287 int rc;
1288 unsigned char *aData;
1289 MemPage *pPage;
drha34b6762004-05-07 13:30:42 +00001290 rc = sqlite3pager_get(pBt->pPager, pgno, (void**)&aData);
drh3aac2dd2004-04-26 14:10:20 +00001291 if( rc ) return rc;
drh07d183d2005-05-01 22:52:42 +00001292 pPage = (MemPage*)&aData[pBt->pageSize];
drh3aac2dd2004-04-26 14:10:20 +00001293 pPage->aData = aData;
1294 pPage->pBt = pBt;
1295 pPage->pgno = pgno;
drhde647132004-05-07 17:57:49 +00001296 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
drh3aac2dd2004-04-26 14:10:20 +00001297 *ppPage = pPage;
1298 return SQLITE_OK;
1299}
1300
1301/*
drhde647132004-05-07 17:57:49 +00001302** Get a page from the pager and initialize it. This routine
1303** is just a convenience wrapper around separate calls to
1304** getPage() and initPage().
1305*/
1306static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +00001307 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +00001308 Pgno pgno, /* Number of the page to get */
1309 MemPage **ppPage, /* Write the page pointer here */
1310 MemPage *pParent /* Parent of the page */
1311){
1312 int rc;
drhee696e22004-08-30 16:52:17 +00001313 if( pgno==0 ){
drh49285702005-09-17 15:20:26 +00001314 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001315 }
drhde647132004-05-07 17:57:49 +00001316 rc = getPage(pBt, pgno, ppPage);
drh10617cd2004-05-14 15:27:27 +00001317 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
drhde647132004-05-07 17:57:49 +00001318 rc = initPage(*ppPage, pParent);
1319 }
1320 return rc;
1321}
1322
1323/*
drh3aac2dd2004-04-26 14:10:20 +00001324** Release a MemPage. This should be called once for each prior
1325** call to getPage.
1326*/
drh4b70f112004-05-02 21:12:19 +00001327static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001328 if( pPage ){
1329 assert( pPage->aData );
1330 assert( pPage->pBt );
drh07d183d2005-05-01 22:52:42 +00001331 assert( &pPage->aData[pPage->pBt->pageSize]==(unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +00001332 sqlite3pager_unref(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00001333 }
1334}
1335
1336/*
drh72f82862001-05-24 21:06:34 +00001337** This routine is called when the reference count for a page
1338** reaches zero. We need to unref the pParent pointer when that
1339** happens.
1340*/
drhb6f41482004-05-14 01:58:11 +00001341static void pageDestructor(void *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +00001342 MemPage *pPage;
1343 assert( (pageSize & 7)==0 );
1344 pPage = (MemPage*)&((char*)pData)[pageSize];
drh72f82862001-05-24 21:06:34 +00001345 if( pPage->pParent ){
1346 MemPage *pParent = pPage->pParent;
1347 pPage->pParent = 0;
drha34b6762004-05-07 13:30:42 +00001348 releasePage(pParent);
drh72f82862001-05-24 21:06:34 +00001349 }
drh3aac2dd2004-04-26 14:10:20 +00001350 pPage->isInit = 0;
drh72f82862001-05-24 21:06:34 +00001351}
1352
1353/*
drha6abd042004-06-09 17:37:22 +00001354** During a rollback, when the pager reloads information into the cache
1355** so that the cache is restored to its original state at the start of
1356** the transaction, for each page restored this routine is called.
1357**
1358** This routine needs to reset the extra data section at the end of the
1359** page to agree with the restored data.
1360*/
1361static void pageReinit(void *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +00001362 MemPage *pPage;
1363 assert( (pageSize & 7)==0 );
1364 pPage = (MemPage*)&((char*)pData)[pageSize];
drha6abd042004-06-09 17:37:22 +00001365 if( pPage->isInit ){
1366 pPage->isInit = 0;
1367 initPage(pPage, pPage->pParent);
1368 }
1369}
1370
1371/*
drhad3e0102004-09-03 23:32:18 +00001372** Open a database file.
1373**
drh382c0242001-10-06 16:33:02 +00001374** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001375** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001376** database file will be deleted when sqlite3BtreeClose() is called.
drha059ad02001-04-17 20:09:11 +00001377*/
drh23e11ca2004-05-04 17:27:28 +00001378int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001379 const char *zFilename, /* Name of the file containing the BTree database */
danielk1977aef0bf62005-12-30 16:28:01 +00001380 sqlite3 *pSqlite, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001381 Btree **ppBtree, /* Pointer to new Btree object written here */
drh90f5ecb2004-07-22 01:19:35 +00001382 int flags /* Options */
drh6019e162001-07-02 17:51:45 +00001383){
danielk1977aef0bf62005-12-30 16:28:01 +00001384 BtShared *pBt; /* Shared part of btree structure */
1385 Btree *p; /* Handle to return */
drha34b6762004-05-07 13:30:42 +00001386 int rc;
drh90f5ecb2004-07-22 01:19:35 +00001387 int nReserve;
1388 unsigned char zDbHeader[100];
danielk1977aef0bf62005-12-30 16:28:01 +00001389 SqliteTsd *pTsd = sqlite3Tsd();
1390
1391 /* Set the variable isMemdb to true for an in-memory database, or
1392 ** false for a file-based database. This symbol is only required if
1393 ** either of the shared-data or autovacuum features are compiled
1394 ** into the library.
1395 */
1396#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1397 #ifdef SQLITE_OMIT_MEMORYDB
1398 const int isMemdb = !zFilename;
1399 #else
1400 const int isMemdb = !zFilename || (strcmp(zFilename, ":memory:")?0:1);
1401 #endif
1402#endif
1403
1404 p = sqliteMalloc(sizeof(Btree));
1405 if( !p ){
1406 return SQLITE_NOMEM;
1407 }
1408 p->inTrans = TRANS_NONE;
1409 p->pSqlite = pSqlite;
1410
1411 /* Try to find an existing Btree structure opened on zFilename. */
1412#ifndef SQLITE_OMIT_SHARED_CACHE
1413 if( pTsd->useSharedData && zFilename && !isMemdb ){
1414 char *zFullPathname = sqlite3Os.xFullPathname(zFilename);
1415 if( !zFullPathname ){
1416 sqliteFree(p);
1417 return SQLITE_NOMEM;
1418 }
1419 for(pBt=pTsd->pBtree; pBt; pBt=pBt->pNext){
1420 if( 0==strcmp(zFullPathname, sqlite3pager_filename(pBt->pPager)) ){
1421 p->pBt = pBt;
1422 *ppBtree = p;
1423 pBt->nRef++;
1424 sqliteFree(zFullPathname);
1425 return SQLITE_OK;
1426 }
1427 }
1428 sqliteFree(zFullPathname);
1429 }
1430#endif
drha059ad02001-04-17 20:09:11 +00001431
drhd62d3d02003-01-24 12:14:20 +00001432 /*
1433 ** The following asserts make sure that structures used by the btree are
1434 ** the right size. This is to guard against size changes that result
1435 ** when compiling on a different architecture.
1436 */
drh4a1c3802004-05-12 15:15:47 +00001437 assert( sizeof(i64)==8 );
drh9e572e62004-04-23 23:43:10 +00001438 assert( sizeof(u64)==8 );
drhd62d3d02003-01-24 12:14:20 +00001439 assert( sizeof(u32)==4 );
1440 assert( sizeof(u16)==2 );
1441 assert( sizeof(Pgno)==4 );
drhd62d3d02003-01-24 12:14:20 +00001442
drha059ad02001-04-17 20:09:11 +00001443 pBt = sqliteMalloc( sizeof(*pBt) );
1444 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +00001445 *ppBtree = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00001446 sqliteFree(p);
drha059ad02001-04-17 20:09:11 +00001447 return SQLITE_NOMEM;
1448 }
drh7bec5052005-02-06 02:45:41 +00001449 rc = sqlite3pager_open(&pBt->pPager, zFilename, EXTRA_SIZE, flags);
drha059ad02001-04-17 20:09:11 +00001450 if( rc!=SQLITE_OK ){
drha34b6762004-05-07 13:30:42 +00001451 if( pBt->pPager ) sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001452 sqliteFree(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00001453 sqliteFree(p);
drha059ad02001-04-17 20:09:11 +00001454 *ppBtree = 0;
1455 return rc;
1456 }
danielk1977aef0bf62005-12-30 16:28:01 +00001457 p->pBt = pBt;
1458
drha34b6762004-05-07 13:30:42 +00001459 sqlite3pager_set_destructor(pBt->pPager, pageDestructor);
drha6abd042004-06-09 17:37:22 +00001460 sqlite3pager_set_reiniter(pBt->pPager, pageReinit);
drha059ad02001-04-17 20:09:11 +00001461 pBt->pCursor = 0;
drha34b6762004-05-07 13:30:42 +00001462 pBt->pPage1 = 0;
1463 pBt->readOnly = sqlite3pager_isreadonly(pBt->pPager);
drh90f5ecb2004-07-22 01:19:35 +00001464 sqlite3pager_read_fileheader(pBt->pPager, sizeof(zDbHeader), zDbHeader);
1465 pBt->pageSize = get2byte(&zDbHeader[16]);
drh07d183d2005-05-01 22:52:42 +00001466 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1467 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
drh90f5ecb2004-07-22 01:19:35 +00001468 pBt->pageSize = SQLITE_DEFAULT_PAGE_SIZE;
1469 pBt->maxEmbedFrac = 64; /* 25% */
1470 pBt->minEmbedFrac = 32; /* 12.5% */
1471 pBt->minLeafFrac = 32; /* 12.5% */
drheee46cf2004-11-06 00:02:48 +00001472#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197703aded42004-11-22 05:26:27 +00001473 /* If the magic name ":memory:" will create an in-memory database, then
1474 ** do not set the auto-vacuum flag, even if SQLITE_DEFAULT_AUTOVACUUM
1475 ** is true. On the other hand, if SQLITE_OMIT_MEMORYDB has been defined,
1476 ** then ":memory:" is just a regular file-name. Respect the auto-vacuum
1477 ** default in this case.
1478 */
danielk1977aef0bf62005-12-30 16:28:01 +00001479 if( zFilename && !isMemdb ){
danielk1977951af802004-11-05 15:45:09 +00001480 pBt->autoVacuum = SQLITE_DEFAULT_AUTOVACUUM;
1481 }
drheee46cf2004-11-06 00:02:48 +00001482#endif
drh90f5ecb2004-07-22 01:19:35 +00001483 nReserve = 0;
1484 }else{
1485 nReserve = zDbHeader[20];
1486 pBt->maxEmbedFrac = zDbHeader[21];
1487 pBt->minEmbedFrac = zDbHeader[22];
1488 pBt->minLeafFrac = zDbHeader[23];
1489 pBt->pageSizeFixed = 1;
danielk1977951af802004-11-05 15:45:09 +00001490#ifndef SQLITE_OMIT_AUTOVACUUM
1491 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1492#endif
drh90f5ecb2004-07-22 01:19:35 +00001493 }
1494 pBt->usableSize = pBt->pageSize - nReserve;
drh07d183d2005-05-01 22:52:42 +00001495 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
drh90f5ecb2004-07-22 01:19:35 +00001496 sqlite3pager_set_pagesize(pBt->pPager, pBt->pageSize);
danielk1977aef0bf62005-12-30 16:28:01 +00001497
1498#ifndef SQLITE_OMIT_SHARED_CACHE
1499 /* Add the new btree to the linked list starting at SqliteTsd.pBtree */
1500 if( pTsd->useSharedData && zFilename && !isMemdb ){
1501 pBt->pNext = pTsd->pBtree;
1502 pTsd->pBtree = pBt;
1503 }
1504 pBt->nRef = 1;
1505#endif
1506 *ppBtree = p;
drha059ad02001-04-17 20:09:11 +00001507 return SQLITE_OK;
1508}
1509
1510/*
1511** Close an open database and invalidate all cursors.
1512*/
danielk1977aef0bf62005-12-30 16:28:01 +00001513int sqlite3BtreeClose(Btree *p){
1514 SqliteTsd *pTsd = sqlite3Tsd();
1515 BtShared *pBt = p->pBt;
1516 BtCursor *pCur;
1517
1518 /* Drop any table-locks */
1519 unlockAllTables(p);
1520
1521 /* Close all cursors opened via this handle. */
1522 pCur = pBt->pCursor;
1523 while( pCur ){
1524 BtCursor *pTmp = pCur;
1525 pCur = pCur->pNext;
1526 if( pTmp->pBtree==p ){
1527 sqlite3BtreeCloseCursor(pTmp);
1528 }
drha059ad02001-04-17 20:09:11 +00001529 }
danielk1977aef0bf62005-12-30 16:28:01 +00001530
1531 sqliteFree(p);
1532
1533#ifndef SQLITE_OMIT_SHARED_CACHE
1534 /* If there are still other outstanding references to the shared-btree
1535 ** structure, return now. The remainder of this procedure cleans
1536 ** up the shared-btree.
1537 */
1538 assert( pBt->nRef>0 );
1539 pBt->nRef--;
1540 if( pBt->nRef ){
1541 return SQLITE_OK;
1542 }
1543
1544 /* Remove the shared-btree from the thread wide list */
1545 if( pTsd->pBtree==pBt ){
1546 pTsd->pBtree = pBt->pNext;
1547 }else{
1548 BtShared *pPrev;
1549 for(pPrev=pTsd->pBtree; pPrev && pPrev->pNext!=pBt; pPrev=pPrev->pNext);
1550 if( pPrev ){
1551 pPrev->pNext = pBt->pNext;
1552 }
1553 }
1554#endif
1555
1556 /* Close the pager and free the shared-btree structure */
1557 assert( !pBt->pCursor );
drha34b6762004-05-07 13:30:42 +00001558 sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001559 sqliteFree(pBt);
1560 return SQLITE_OK;
1561}
1562
1563/*
drh90f5ecb2004-07-22 01:19:35 +00001564** Change the busy handler callback function.
1565*/
danielk1977aef0bf62005-12-30 16:28:01 +00001566int sqlite3BtreeSetBusyHandler(Btree *p, BusyHandler *pHandler){
1567 BtShared *pBt = p->pBt;
drhb8ef32c2005-03-14 02:01:49 +00001568 pBt->pBusyHandler = pHandler;
drh90f5ecb2004-07-22 01:19:35 +00001569 sqlite3pager_set_busyhandler(pBt->pPager, pHandler);
1570 return SQLITE_OK;
1571}
1572
1573/*
drhda47d772002-12-02 04:25:19 +00001574** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001575**
1576** The maximum number of cache pages is set to the absolute
1577** value of mxPage. If mxPage is negative, the pager will
1578** operate asynchronously - it will not stop to do fsync()s
1579** to insure data is written to the disk surface before
1580** continuing. Transactions still work if synchronous is off,
1581** and the database cannot be corrupted if this program
1582** crashes. But if the operating system crashes or there is
1583** an abrupt power failure when synchronous is off, the database
1584** could be left in an inconsistent and unrecoverable state.
1585** Synchronous is on by default so database corruption is not
1586** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001587*/
danielk1977aef0bf62005-12-30 16:28:01 +00001588int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
1589 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00001590 sqlite3pager_set_cachesize(pBt->pPager, mxPage);
drhf57b14a2001-09-14 18:54:08 +00001591 return SQLITE_OK;
1592}
1593
1594/*
drh973b6e32003-02-12 14:09:42 +00001595** Change the way data is synced to disk in order to increase or decrease
1596** how well the database resists damage due to OS crashes and power
1597** failures. Level 1 is the same as asynchronous (no syncs() occur and
1598** there is a high probability of damage) Level 2 is the default. There
1599** is a very low but non-zero probability of damage. Level 3 reduces the
1600** probability of damage to near zero but with a write performance reduction.
1601*/
danielk197793758c82005-01-21 08:13:14 +00001602#ifndef SQLITE_OMIT_PAGER_PRAGMAS
danielk1977aef0bf62005-12-30 16:28:01 +00001603int sqlite3BtreeSetSafetyLevel(Btree *p, int level){
1604 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00001605 sqlite3pager_set_safety_level(pBt->pPager, level);
drh973b6e32003-02-12 14:09:42 +00001606 return SQLITE_OK;
1607}
danielk197793758c82005-01-21 08:13:14 +00001608#endif
drh973b6e32003-02-12 14:09:42 +00001609
drh2c8997b2005-08-27 16:36:48 +00001610/*
1611** Return TRUE if the given btree is set to safety level 1. In other
1612** words, return TRUE if no sync() occurs on the disk files.
1613*/
danielk1977aef0bf62005-12-30 16:28:01 +00001614int sqlite3BtreeSyncDisabled(Btree *p){
1615 BtShared *pBt = p->pBt;
drh2c8997b2005-08-27 16:36:48 +00001616 assert( pBt && pBt->pPager );
1617 return sqlite3pager_nosync(pBt->pPager);
1618}
1619
danielk1977576ec6b2005-01-21 11:55:25 +00001620#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001621/*
drh90f5ecb2004-07-22 01:19:35 +00001622** Change the default pages size and the number of reserved bytes per page.
drh06f50212004-11-02 14:24:33 +00001623**
1624** The page size must be a power of 2 between 512 and 65536. If the page
1625** size supplied does not meet this constraint then the page size is not
1626** changed.
1627**
1628** Page sizes are constrained to be a power of two so that the region
1629** of the database file used for locking (beginning at PENDING_BYTE,
1630** the first byte past the 1GB boundary, 0x40000000) needs to occur
1631** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001632**
1633** If parameter nReserve is less than zero, then the number of reserved
1634** bytes per page is left unchanged.
drh90f5ecb2004-07-22 01:19:35 +00001635*/
danielk1977aef0bf62005-12-30 16:28:01 +00001636int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
1637 BtShared *pBt = p->pBt;
drh90f5ecb2004-07-22 01:19:35 +00001638 if( pBt->pageSizeFixed ){
1639 return SQLITE_READONLY;
1640 }
1641 if( nReserve<0 ){
1642 nReserve = pBt->pageSize - pBt->usableSize;
1643 }
drh06f50212004-11-02 14:24:33 +00001644 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
1645 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00001646 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00001647 assert( !pBt->pPage1 && !pBt->pCursor );
drh1c7880e2005-05-20 20:01:55 +00001648 pBt->pageSize = sqlite3pager_set_pagesize(pBt->pPager, pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001649 }
1650 pBt->usableSize = pBt->pageSize - nReserve;
1651 return SQLITE_OK;
1652}
1653
1654/*
1655** Return the currently defined page size
1656*/
danielk1977aef0bf62005-12-30 16:28:01 +00001657int sqlite3BtreeGetPageSize(Btree *p){
1658 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00001659}
danielk1977aef0bf62005-12-30 16:28:01 +00001660int sqlite3BtreeGetReserve(Btree *p){
1661 return p->pBt->pageSize - p->pBt->usableSize;
drh2011d5f2004-07-22 02:40:37 +00001662}
danielk1977576ec6b2005-01-21 11:55:25 +00001663#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00001664
1665/*
danielk1977951af802004-11-05 15:45:09 +00001666** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
1667** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
1668** is disabled. The default value for the auto-vacuum property is
1669** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
1670*/
danielk1977aef0bf62005-12-30 16:28:01 +00001671int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
1672 BtShared *pBt = p->pBt;;
danielk1977951af802004-11-05 15:45:09 +00001673#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001674 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00001675#else
1676 if( pBt->pageSizeFixed ){
1677 return SQLITE_READONLY;
1678 }
1679 pBt->autoVacuum = (autoVacuum?1:0);
1680 return SQLITE_OK;
1681#endif
1682}
1683
1684/*
1685** Return the value of the 'auto-vacuum' property. If auto-vacuum is
1686** enabled 1 is returned. Otherwise 0.
1687*/
danielk1977aef0bf62005-12-30 16:28:01 +00001688int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00001689#ifdef SQLITE_OMIT_AUTOVACUUM
1690 return 0;
1691#else
danielk1977aef0bf62005-12-30 16:28:01 +00001692 return p->pBt->autoVacuum;
danielk1977951af802004-11-05 15:45:09 +00001693#endif
1694}
1695
1696
1697/*
drha34b6762004-05-07 13:30:42 +00001698** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001699** also acquire a readlock on that file.
1700**
1701** SQLITE_OK is returned on success. If the file is not a
1702** well-formed database file, then SQLITE_CORRUPT is returned.
1703** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
1704** is returned if we run out of memory. SQLITE_PROTOCOL is returned
1705** if there is a locking protocol violation.
1706*/
danielk1977aef0bf62005-12-30 16:28:01 +00001707static int lockBtree(BtShared *pBt){
drh07d183d2005-05-01 22:52:42 +00001708 int rc, pageSize;
drh3aac2dd2004-04-26 14:10:20 +00001709 MemPage *pPage1;
drha34b6762004-05-07 13:30:42 +00001710 if( pBt->pPage1 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001711 rc = getPage(pBt, 1, &pPage1);
drh306dc212001-05-21 13:45:10 +00001712 if( rc!=SQLITE_OK ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00001713
drh306dc212001-05-21 13:45:10 +00001714
1715 /* Do some checking to help insure the file we opened really is
1716 ** a valid database file.
1717 */
drhb6f41482004-05-14 01:58:11 +00001718 rc = SQLITE_NOTADB;
drha34b6762004-05-07 13:30:42 +00001719 if( sqlite3pager_pagecount(pBt->pPager)>0 ){
drhb6f41482004-05-14 01:58:11 +00001720 u8 *page1 = pPage1->aData;
1721 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001722 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001723 }
drhb6f41482004-05-14 01:58:11 +00001724 if( page1[18]>1 || page1[19]>1 ){
1725 goto page1_init_failed;
1726 }
drh07d183d2005-05-01 22:52:42 +00001727 pageSize = get2byte(&page1[16]);
1728 if( ((pageSize-1)&pageSize)!=0 ){
1729 goto page1_init_failed;
1730 }
1731 assert( (pageSize & 7)==0 );
1732 pBt->pageSize = pageSize;
1733 pBt->usableSize = pageSize - page1[20];
drhb6f41482004-05-14 01:58:11 +00001734 if( pBt->usableSize<500 ){
1735 goto page1_init_failed;
1736 }
1737 pBt->maxEmbedFrac = page1[21];
1738 pBt->minEmbedFrac = page1[22];
1739 pBt->minLeafFrac = page1[23];
drh057cd3a2005-02-15 16:23:02 +00001740#ifndef SQLITE_OMIT_AUTOVACUUM
1741 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
1742#endif
drh306dc212001-05-21 13:45:10 +00001743 }
drhb6f41482004-05-14 01:58:11 +00001744
1745 /* maxLocal is the maximum amount of payload to store locally for
1746 ** a cell. Make sure it is small enough so that at least minFanout
1747 ** cells can will fit on one page. We assume a 10-byte page header.
1748 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001749 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001750 ** 4-byte child pointer
1751 ** 9-byte nKey value
1752 ** 4-byte nData value
1753 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001754 ** So a cell consists of a 2-byte poiner, a header which is as much as
1755 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1756 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001757 */
drh43605152004-05-29 21:46:49 +00001758 pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
1759 pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
1760 pBt->maxLeaf = pBt->usableSize - 35;
1761 pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
drhb6f41482004-05-14 01:58:11 +00001762 if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
1763 goto page1_init_failed;
1764 }
drh2e38c322004-09-03 18:38:44 +00001765 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001766 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001767 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001768
drh72f82862001-05-24 21:06:34 +00001769page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001770 releasePage(pPage1);
1771 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001772 return rc;
drh306dc212001-05-21 13:45:10 +00001773}
1774
1775/*
drhb8ef32c2005-03-14 02:01:49 +00001776** This routine works like lockBtree() except that it also invokes the
1777** busy callback if there is lock contention.
1778*/
danielk1977aef0bf62005-12-30 16:28:01 +00001779static int lockBtreeWithRetry(Btree *pRef){
drhb8ef32c2005-03-14 02:01:49 +00001780 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00001781 if( pRef->inTrans==TRANS_NONE ){
1782 u8 inTransaction = pRef->pBt->inTransaction;
1783 btreeIntegrity(pRef);
1784 rc = sqlite3BtreeBeginTrans(pRef, 0);
1785 pRef->pBt->inTransaction = inTransaction;
1786 pRef->inTrans = TRANS_NONE;
1787 if( rc==SQLITE_OK ){
1788 pRef->pBt->nTransaction--;
1789 }
1790 btreeIntegrity(pRef);
drhb8ef32c2005-03-14 02:01:49 +00001791 }
1792 return rc;
1793}
1794
1795
1796/*
drhb8ca3072001-12-05 00:21:20 +00001797** If there are no outstanding cursors and we are not in the middle
1798** of a transaction but there is a read lock on the database, then
1799** this routine unrefs the first page of the database file which
1800** has the effect of releasing the read lock.
1801**
1802** If there are any outstanding cursors, this routine is a no-op.
1803**
1804** If there is a transaction in progress, this routine is a no-op.
1805*/
danielk1977aef0bf62005-12-30 16:28:01 +00001806static void unlockBtreeIfUnused(BtShared *pBt){
1807 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
drh51c6d962004-06-06 00:42:25 +00001808 if( pBt->pPage1->aData==0 ){
1809 MemPage *pPage = pBt->pPage1;
drh2646da72005-12-09 20:02:05 +00001810 pPage->aData = &((u8*)pPage)[-pBt->pageSize];
drh51c6d962004-06-06 00:42:25 +00001811 pPage->pBt = pBt;
1812 pPage->pgno = 1;
1813 }
drh3aac2dd2004-04-26 14:10:20 +00001814 releasePage(pBt->pPage1);
1815 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00001816 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001817 }
1818}
1819
1820/*
drh9e572e62004-04-23 23:43:10 +00001821** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001822** file.
drh8b2f49b2001-06-08 00:21:52 +00001823*/
danielk1977aef0bf62005-12-30 16:28:01 +00001824static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00001825 MemPage *pP1;
1826 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001827 int rc;
drhde647132004-05-07 17:57:49 +00001828 if( sqlite3pager_pagecount(pBt->pPager)>0 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001829 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00001830 assert( pP1!=0 );
1831 data = pP1->aData;
drha34b6762004-05-07 13:30:42 +00001832 rc = sqlite3pager_write(data);
drh8b2f49b2001-06-08 00:21:52 +00001833 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00001834 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
1835 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00001836 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00001837 data[18] = 1;
1838 data[19] = 1;
drhb6f41482004-05-14 01:58:11 +00001839 data[20] = pBt->pageSize - pBt->usableSize;
1840 data[21] = pBt->maxEmbedFrac;
1841 data[22] = pBt->minEmbedFrac;
1842 data[23] = pBt->minLeafFrac;
1843 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00001844 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00001845 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00001846#ifndef SQLITE_OMIT_AUTOVACUUM
1847 if( pBt->autoVacuum ){
1848 put4byte(&data[36 + 4*4], 1);
1849 }
1850#endif
drh8b2f49b2001-06-08 00:21:52 +00001851 return SQLITE_OK;
1852}
1853
1854/*
danielk1977ee5741e2004-05-31 10:01:34 +00001855** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00001856** is started if the second argument is nonzero, otherwise a read-
1857** transaction. If the second argument is 2 or more and exclusive
1858** transaction is started, meaning that no other process is allowed
1859** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00001860** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00001861** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00001862**
danielk1977ee5741e2004-05-31 10:01:34 +00001863** A write-transaction must be started before attempting any
1864** changes to the database. None of the following routines
1865** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00001866**
drh23e11ca2004-05-04 17:27:28 +00001867** sqlite3BtreeCreateTable()
1868** sqlite3BtreeCreateIndex()
1869** sqlite3BtreeClearTable()
1870** sqlite3BtreeDropTable()
1871** sqlite3BtreeInsert()
1872** sqlite3BtreeDelete()
1873** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00001874**
drhb8ef32c2005-03-14 02:01:49 +00001875** If an initial attempt to acquire the lock fails because of lock contention
1876** and the database was previously unlocked, then invoke the busy handler
1877** if there is one. But if there was previously a read-lock, do not
1878** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
1879** returned when there is already a read-lock in order to avoid a deadlock.
1880**
1881** Suppose there are two processes A and B. A has a read lock and B has
1882** a reserved lock. B tries to promote to exclusive but is blocked because
1883** of A's read lock. A tries to promote to reserved but is blocked by B.
1884** One or the other of the two processes must give way or there can be
1885** no progress. By returning SQLITE_BUSY and not invoking the busy callback
1886** when A already has a read lock, we encourage A to give up and let B
1887** proceed.
drha059ad02001-04-17 20:09:11 +00001888*/
danielk1977aef0bf62005-12-30 16:28:01 +00001889int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
1890 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00001891 int rc = SQLITE_OK;
1892
danielk1977aef0bf62005-12-30 16:28:01 +00001893 btreeIntegrity(p);
1894
danielk1977ee5741e2004-05-31 10:01:34 +00001895 /* If the btree is already in a write-transaction, or it
1896 ** is already in a read-transaction and a read-transaction
1897 ** is requested, this is a no-op.
1898 */
danielk1977aef0bf62005-12-30 16:28:01 +00001899 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
danielk1977ee5741e2004-05-31 10:01:34 +00001900 return SQLITE_OK;
1901 }
drhb8ef32c2005-03-14 02:01:49 +00001902
1903 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00001904 if( pBt->readOnly && wrflag ){
1905 return SQLITE_READONLY;
1906 }
1907
danielk1977aef0bf62005-12-30 16:28:01 +00001908 /* If another database handle has already opened a write transaction
1909 ** on this shared-btree structure and a second write transaction is
1910 ** requested, return SQLITE_BUSY.
1911 */
1912 if( pBt->inTransaction==TRANS_WRITE && wrflag ){
1913 return SQLITE_BUSY;
1914 }
1915
drhb8ef32c2005-03-14 02:01:49 +00001916 do {
1917 if( pBt->pPage1==0 ){
1918 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +00001919 }
drhb8ef32c2005-03-14 02:01:49 +00001920
1921 if( rc==SQLITE_OK && wrflag ){
1922 rc = sqlite3pager_begin(pBt->pPage1->aData, wrflag>1);
1923 if( rc==SQLITE_OK ){
1924 rc = newDatabase(pBt);
1925 }
1926 }
1927
1928 if( rc==SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00001929 if( wrflag ) pBt->inStmt = 0;
1930 }else{
1931 unlockBtreeIfUnused(pBt);
1932 }
danielk1977aef0bf62005-12-30 16:28:01 +00001933 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
drha4afb652005-07-09 02:16:02 +00001934 sqlite3InvokeBusyHandler(pBt->pBusyHandler) );
danielk1977aef0bf62005-12-30 16:28:01 +00001935
1936 if( rc==SQLITE_OK ){
1937 if( p->inTrans==TRANS_NONE ){
1938 pBt->nTransaction++;
1939 }
1940 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
1941 if( p->inTrans>pBt->inTransaction ){
1942 pBt->inTransaction = p->inTrans;
1943 }
1944 }
1945
1946 btreeIntegrity(p);
drhb8ca3072001-12-05 00:21:20 +00001947 return rc;
drha059ad02001-04-17 20:09:11 +00001948}
1949
danielk1977687566d2004-11-02 12:56:41 +00001950#ifndef SQLITE_OMIT_AUTOVACUUM
1951
1952/*
1953** Set the pointer-map entries for all children of page pPage. Also, if
1954** pPage contains cells that point to overflow pages, set the pointer
1955** map entries for the overflow pages as well.
1956*/
1957static int setChildPtrmaps(MemPage *pPage){
1958 int i; /* Counter variable */
1959 int nCell; /* Number of cells in page pPage */
1960 int rc = SQLITE_OK; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00001961 BtShared *pBt = pPage->pBt;
danielk1977687566d2004-11-02 12:56:41 +00001962 int isInitOrig = pPage->isInit;
1963 Pgno pgno = pPage->pgno;
1964
1965 initPage(pPage, 0);
1966 nCell = pPage->nCell;
1967
1968 for(i=0; i<nCell; i++){
danielk1977687566d2004-11-02 12:56:41 +00001969 u8 *pCell = findCell(pPage, i);
1970
danielk197726836652005-01-17 01:33:13 +00001971 rc = ptrmapPutOvflPtr(pPage, pCell);
1972 if( rc!=SQLITE_OK ){
1973 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00001974 }
danielk197726836652005-01-17 01:33:13 +00001975
danielk1977687566d2004-11-02 12:56:41 +00001976 if( !pPage->leaf ){
1977 Pgno childPgno = get4byte(pCell);
1978 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
1979 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
1980 }
1981 }
1982
1983 if( !pPage->leaf ){
1984 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
1985 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
1986 }
1987
1988set_child_ptrmaps_out:
1989 pPage->isInit = isInitOrig;
1990 return rc;
1991}
1992
1993/*
1994** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
1995** page, is a pointer to page iFrom. Modify this pointer so that it points to
1996** iTo. Parameter eType describes the type of pointer to be modified, as
1997** follows:
1998**
1999** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2000** page of pPage.
2001**
2002** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2003** page pointed to by one of the cells on pPage.
2004**
2005** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2006** overflow page in the list.
2007*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00002008static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
danielk1977687566d2004-11-02 12:56:41 +00002009 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00002010 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00002011 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00002012 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002013 }
danielk1977f78fc082004-11-02 14:40:32 +00002014 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00002015 }else{
2016 int isInitOrig = pPage->isInit;
2017 int i;
2018 int nCell;
2019
2020 initPage(pPage, 0);
2021 nCell = pPage->nCell;
2022
danielk1977687566d2004-11-02 12:56:41 +00002023 for(i=0; i<nCell; i++){
2024 u8 *pCell = findCell(pPage, i);
2025 if( eType==PTRMAP_OVERFLOW1 ){
2026 CellInfo info;
2027 parseCellPtr(pPage, pCell, &info);
2028 if( info.iOverflow ){
2029 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
2030 put4byte(&pCell[info.iOverflow], iTo);
2031 break;
2032 }
2033 }
2034 }else{
2035 if( get4byte(pCell)==iFrom ){
2036 put4byte(pCell, iTo);
2037 break;
2038 }
2039 }
2040 }
2041
2042 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00002043 if( eType!=PTRMAP_BTREE ||
2044 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00002045 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002046 }
danielk1977687566d2004-11-02 12:56:41 +00002047 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
2048 }
2049
2050 pPage->isInit = isInitOrig;
2051 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002052 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002053}
2054
danielk1977003ba062004-11-04 02:57:33 +00002055
danielk19777701e812005-01-10 12:59:51 +00002056/*
2057** Move the open database page pDbPage to location iFreePage in the
2058** database. The pDbPage reference remains valid.
2059*/
danielk1977003ba062004-11-04 02:57:33 +00002060static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00002061 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00002062 MemPage *pDbPage, /* Open page to move */
2063 u8 eType, /* Pointer map 'type' entry for pDbPage */
2064 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
2065 Pgno iFreePage /* The location to move pDbPage to */
danielk1977003ba062004-11-04 02:57:33 +00002066){
2067 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
2068 Pgno iDbPage = pDbPage->pgno;
2069 Pager *pPager = pBt->pPager;
2070 int rc;
2071
danielk1977a0bf2652004-11-04 14:30:04 +00002072 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
2073 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
danielk1977003ba062004-11-04 02:57:33 +00002074
2075 /* Move page iDbPage from it's current location to page number iFreePage */
2076 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
2077 iDbPage, iFreePage, iPtrPage, eType));
2078 rc = sqlite3pager_movepage(pPager, pDbPage->aData, iFreePage);
2079 if( rc!=SQLITE_OK ){
2080 return rc;
2081 }
2082 pDbPage->pgno = iFreePage;
2083
2084 /* If pDbPage was a btree-page, then it may have child pages and/or cells
2085 ** that point to overflow pages. The pointer map entries for all these
2086 ** pages need to be changed.
2087 **
2088 ** If pDbPage is an overflow page, then the first 4 bytes may store a
2089 ** pointer to a subsequent overflow page. If this is the case, then
2090 ** the pointer map needs to be updated for the subsequent overflow page.
2091 */
danielk1977a0bf2652004-11-04 14:30:04 +00002092 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00002093 rc = setChildPtrmaps(pDbPage);
2094 if( rc!=SQLITE_OK ){
2095 return rc;
2096 }
2097 }else{
2098 Pgno nextOvfl = get4byte(pDbPage->aData);
2099 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00002100 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
2101 if( rc!=SQLITE_OK ){
2102 return rc;
2103 }
2104 }
2105 }
2106
2107 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
2108 ** that it points at iFreePage. Also fix the pointer map entry for
2109 ** iPtrPage.
2110 */
danielk1977a0bf2652004-11-04 14:30:04 +00002111 if( eType!=PTRMAP_ROOTPAGE ){
2112 rc = getPage(pBt, iPtrPage, &pPtrPage);
2113 if( rc!=SQLITE_OK ){
2114 return rc;
2115 }
2116 rc = sqlite3pager_write(pPtrPage->aData);
2117 if( rc!=SQLITE_OK ){
2118 releasePage(pPtrPage);
2119 return rc;
2120 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002121 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00002122 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002123 if( rc==SQLITE_OK ){
2124 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
2125 }
danielk1977003ba062004-11-04 02:57:33 +00002126 }
danielk1977003ba062004-11-04 02:57:33 +00002127 return rc;
2128}
2129
danielk1977687566d2004-11-02 12:56:41 +00002130/* Forward declaration required by autoVacuumCommit(). */
danielk1977aef0bf62005-12-30 16:28:01 +00002131static int allocatePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00002132
2133/*
2134** This routine is called prior to sqlite3pager_commit when a transaction
2135** is commited for an auto-vacuum database.
2136*/
danielk1977aef0bf62005-12-30 16:28:01 +00002137static int autoVacuumCommit(BtShared *pBt, Pgno *nTrunc){
danielk1977687566d2004-11-02 12:56:41 +00002138 Pager *pPager = pBt->pPager;
2139 Pgno nFreeList; /* Number of pages remaining on the free-list. */
danielk1977a19df672004-11-03 11:37:07 +00002140 int nPtrMap; /* Number of pointer-map pages deallocated */
2141 Pgno origSize; /* Pages in the database file */
2142 Pgno finSize; /* Pages in the database file after truncation */
danielk1977687566d2004-11-02 12:56:41 +00002143 int rc; /* Return code */
2144 u8 eType;
danielk1977a19df672004-11-03 11:37:07 +00002145 int pgsz = pBt->pageSize; /* Page size for this database */
danielk1977687566d2004-11-02 12:56:41 +00002146 Pgno iDbPage; /* The database page to move */
danielk1977687566d2004-11-02 12:56:41 +00002147 MemPage *pDbMemPage = 0; /* "" */
2148 Pgno iPtrPage; /* The page that contains a pointer to iDbPage */
danielk1977687566d2004-11-02 12:56:41 +00002149 Pgno iFreePage; /* The free-list page to move iDbPage to */
2150 MemPage *pFreeMemPage = 0; /* "" */
2151
2152#ifndef NDEBUG
2153 int nRef = *sqlite3pager_stats(pPager);
2154#endif
2155
2156 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +00002157 if( PTRMAP_ISPAGE(pgsz, sqlite3pager_pagecount(pPager)) ){
drh49285702005-09-17 15:20:26 +00002158 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002159 }
danielk1977687566d2004-11-02 12:56:41 +00002160
2161 /* Figure out how many free-pages are in the database. If there are no
2162 ** free pages, then auto-vacuum is a no-op.
2163 */
2164 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977a19df672004-11-03 11:37:07 +00002165 if( nFreeList==0 ){
danielk1977d761c0c2004-11-05 16:37:02 +00002166 *nTrunc = 0;
danielk1977a19df672004-11-03 11:37:07 +00002167 return SQLITE_OK;
2168 }
danielk1977687566d2004-11-02 12:56:41 +00002169
danielk1977a19df672004-11-03 11:37:07 +00002170 origSize = sqlite3pager_pagecount(pPager);
2171 nPtrMap = (nFreeList-origSize+PTRMAP_PAGENO(pgsz, origSize)+pgsz/5)/(pgsz/5);
2172 finSize = origSize - nFreeList - nPtrMap;
danielk1977fd5f5b62005-09-16 09:52:29 +00002173 if( origSize>=PENDING_BYTE_PAGE(pBt) && finSize<=PENDING_BYTE_PAGE(pBt) ){
danielk1977599fcba2004-11-08 07:13:13 +00002174 finSize--;
drh42cac6d2004-11-20 20:31:11 +00002175 if( PTRMAP_ISPAGE(pBt->usableSize, finSize) ){
danielk1977599fcba2004-11-08 07:13:13 +00002176 finSize--;
2177 }
2178 }
danielk1977a19df672004-11-03 11:37:07 +00002179 TRACE(("AUTOVACUUM: Begin (db size %d->%d)\n", origSize, finSize));
danielk1977687566d2004-11-02 12:56:41 +00002180
danielk1977a19df672004-11-03 11:37:07 +00002181 /* Variable 'finSize' will be the size of the file in pages after
danielk1977687566d2004-11-02 12:56:41 +00002182 ** the auto-vacuum has completed (the current file size minus the number
2183 ** of pages on the free list). Loop through the pages that lie beyond
2184 ** this mark, and if they are not already on the free list, move them
danielk1977a19df672004-11-03 11:37:07 +00002185 ** to a free page earlier in the file (somewhere before finSize).
danielk1977687566d2004-11-02 12:56:41 +00002186 */
danielk1977a19df672004-11-03 11:37:07 +00002187 for( iDbPage=finSize+1; iDbPage<=origSize; iDbPage++ ){
danielk1977599fcba2004-11-08 07:13:13 +00002188 /* If iDbPage is a pointer map page, or the pending-byte page, skip it. */
2189 if( PTRMAP_ISPAGE(pgsz, iDbPage) || iDbPage==PENDING_BYTE_PAGE(pBt) ){
2190 continue;
2191 }
2192
danielk1977687566d2004-11-02 12:56:41 +00002193 rc = ptrmapGet(pBt, iDbPage, &eType, &iPtrPage);
2194 if( rc!=SQLITE_OK ) goto autovacuum_out;
drhccae6022005-02-26 17:31:26 +00002195 if( eType==PTRMAP_ROOTPAGE ){
drh49285702005-09-17 15:20:26 +00002196 rc = SQLITE_CORRUPT_BKPT;
drhccae6022005-02-26 17:31:26 +00002197 goto autovacuum_out;
2198 }
danielk1977687566d2004-11-02 12:56:41 +00002199
danielk1977599fcba2004-11-08 07:13:13 +00002200 /* If iDbPage is free, do not swap it. */
2201 if( eType==PTRMAP_FREEPAGE ){
danielk1977687566d2004-11-02 12:56:41 +00002202 continue;
2203 }
2204 rc = getPage(pBt, iDbPage, &pDbMemPage);
2205 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977687566d2004-11-02 12:56:41 +00002206
2207 /* Find the next page in the free-list that is not already at the end
2208 ** of the file. A page can be pulled off the free list using the
2209 ** allocatePage() routine.
2210 */
2211 do{
2212 if( pFreeMemPage ){
2213 releasePage(pFreeMemPage);
2214 pFreeMemPage = 0;
2215 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00002216 rc = allocatePage(pBt, &pFreeMemPage, &iFreePage, 0, 0);
danielk1977ac11ee62005-01-15 12:45:51 +00002217 if( rc!=SQLITE_OK ){
2218 releasePage(pDbMemPage);
2219 goto autovacuum_out;
2220 }
danielk1977a19df672004-11-03 11:37:07 +00002221 assert( iFreePage<=origSize );
2222 }while( iFreePage>finSize );
danielk1977687566d2004-11-02 12:56:41 +00002223 releasePage(pFreeMemPage);
2224 pFreeMemPage = 0;
danielk1977687566d2004-11-02 12:56:41 +00002225
danielk1977003ba062004-11-04 02:57:33 +00002226 rc = relocatePage(pBt, pDbMemPage, eType, iPtrPage, iFreePage);
danielk1977687566d2004-11-02 12:56:41 +00002227 releasePage(pDbMemPage);
danielk1977687566d2004-11-02 12:56:41 +00002228 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977687566d2004-11-02 12:56:41 +00002229 }
2230
2231 /* The entire free-list has been swapped to the end of the file. So
danielk1977a19df672004-11-03 11:37:07 +00002232 ** truncate the database file to finSize pages and consider the
danielk1977687566d2004-11-02 12:56:41 +00002233 ** free-list empty.
2234 */
2235 rc = sqlite3pager_write(pBt->pPage1->aData);
2236 if( rc!=SQLITE_OK ) goto autovacuum_out;
2237 put4byte(&pBt->pPage1->aData[32], 0);
2238 put4byte(&pBt->pPage1->aData[36], 0);
danielk1977687566d2004-11-02 12:56:41 +00002239 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977d761c0c2004-11-05 16:37:02 +00002240 *nTrunc = finSize;
danielk1977687566d2004-11-02 12:56:41 +00002241
2242autovacuum_out:
danielk1977687566d2004-11-02 12:56:41 +00002243 assert( nRef==*sqlite3pager_stats(pPager) );
2244 if( rc!=SQLITE_OK ){
2245 sqlite3pager_rollback(pPager);
2246 }
2247 return rc;
2248}
2249#endif
2250
2251/*
drh2aa679f2001-06-25 02:11:07 +00002252** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00002253**
2254** This will release the write lock on the database file. If there
2255** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002256*/
danielk1977aef0bf62005-12-30 16:28:01 +00002257int sqlite3BtreeCommit(Btree *p){
danielk1977ee5741e2004-05-31 10:01:34 +00002258 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002259 BtShared *pBt = p->pBt;
2260
2261 btreeIntegrity(p);
2262 unlockAllTables(p);
2263
2264 /* If the handle has a write-transaction open, commit the shared-btrees
2265 ** transaction and set the shared state to TRANS_READ.
2266 */
2267 if( p->inTrans==TRANS_WRITE ){
2268 assert( pBt->inTransaction==TRANS_WRITE );
2269 assert( pBt->nTransaction>0 );
danielk1977ee5741e2004-05-31 10:01:34 +00002270 rc = sqlite3pager_commit(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00002271 pBt->inTransaction = TRANS_READ;
2272 pBt->inStmt = 0;
danielk1977ee5741e2004-05-31 10:01:34 +00002273 }
danielk1977aef0bf62005-12-30 16:28:01 +00002274
2275 /* If the handle has any kind of transaction open, decrement the transaction
2276 ** count of the shared btree. If the transaction count reaches 0, set
2277 ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
2278 ** will unlock the pager.
2279 */
2280 if( p->inTrans!=TRANS_NONE ){
2281 pBt->nTransaction--;
2282 if( 0==pBt->nTransaction ){
2283 pBt->inTransaction = TRANS_NONE;
2284 }
2285 }
2286
2287 /* Set the handles current transaction state to TRANS_NONE and unlock
2288 ** the pager if this call closed the only read or write transaction.
2289 */
2290 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002291 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002292
2293 btreeIntegrity(p);
drha059ad02001-04-17 20:09:11 +00002294 return rc;
2295}
2296
danielk1977fbcd5852004-06-15 02:44:18 +00002297#ifndef NDEBUG
2298/*
2299** Return the number of write-cursors open on this handle. This is for use
2300** in assert() expressions, so it is only compiled if NDEBUG is not
2301** defined.
2302*/
danielk1977aef0bf62005-12-30 16:28:01 +00002303static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00002304 BtCursor *pCur;
2305 int r = 0;
2306 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
danielk1977aef0bf62005-12-30 16:28:01 +00002307 if( pCur->wrFlag ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00002308 }
2309 return r;
2310}
2311#endif
2312
drhda200cc2004-05-09 11:51:38 +00002313#ifdef SQLITE_TEST
2314/*
2315** Print debugging information about all cursors to standard output.
2316*/
danielk1977aef0bf62005-12-30 16:28:01 +00002317void sqlite3BtreeCursorList(Btree *p){
drhda200cc2004-05-09 11:51:38 +00002318 BtCursor *pCur;
danielk1977aef0bf62005-12-30 16:28:01 +00002319 BtShared *pBt = p->pBt;
drhda200cc2004-05-09 11:51:38 +00002320 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
2321 MemPage *pPage = pCur->pPage;
2322 char *zMode = pCur->wrFlag ? "rw" : "ro";
drhfe63d1c2004-09-08 20:13:04 +00002323 sqlite3DebugPrintf("CURSOR %p rooted at %4d(%s) currently at %d.%d%s\n",
2324 pCur, pCur->pgnoRoot, zMode,
drhda200cc2004-05-09 11:51:38 +00002325 pPage ? pPage->pgno : 0, pCur->idx,
2326 pCur->isValid ? "" : " eof"
2327 );
2328 }
2329}
2330#endif
2331
drhc39e0002004-05-07 23:50:57 +00002332/*
drhecdc7532001-09-23 02:35:53 +00002333** Rollback the transaction in progress. All cursors will be
2334** invalided by this operation. Any attempt to use a cursor
2335** that was open at the beginning of this operation will result
2336** in an error.
drh5e00f6c2001-09-13 13:46:56 +00002337**
2338** This will release the write lock on the database file. If there
2339** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002340*/
danielk1977aef0bf62005-12-30 16:28:01 +00002341int sqlite3BtreeRollback(Btree *p){
danielk1977cfe9a692004-06-16 12:00:29 +00002342 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002343 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00002344 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00002345
2346 btreeIntegrity(p);
2347 unlockAllTables(p);
2348
2349 if( p->inTrans==TRANS_WRITE ){
2350 assert( TRANS_WRITE==pBt->inTransaction );
2351
drh24cd67e2004-05-10 16:18:47 +00002352 rc = sqlite3pager_rollback(pBt->pPager);
2353 /* The rollback may have destroyed the pPage1->aData value. So
2354 ** call getPage() on page 1 again to make sure pPage1->aData is
2355 ** set correctly. */
2356 if( getPage(pBt, 1, &pPage1)==SQLITE_OK ){
2357 releasePage(pPage1);
2358 }
danielk1977fbcd5852004-06-15 02:44:18 +00002359 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002360 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00002361 }
danielk1977aef0bf62005-12-30 16:28:01 +00002362
2363 if( p->inTrans!=TRANS_NONE ){
2364 assert( pBt->nTransaction>0 );
2365 pBt->nTransaction--;
2366 if( 0==pBt->nTransaction ){
2367 pBt->inTransaction = TRANS_NONE;
2368 }
2369 }
2370
2371 p->inTrans = TRANS_NONE;
danielk1977ee5741e2004-05-31 10:01:34 +00002372 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00002373 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002374
2375 btreeIntegrity(p);
drha059ad02001-04-17 20:09:11 +00002376 return rc;
2377}
2378
2379/*
drhab01f612004-05-22 02:55:23 +00002380** Start a statement subtransaction. The subtransaction can
2381** can be rolled back independently of the main transaction.
2382** You must start a transaction before starting a subtransaction.
2383** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00002384** commits or rolls back.
2385**
drhab01f612004-05-22 02:55:23 +00002386** Only one subtransaction may be active at a time. It is an error to try
2387** to start a new subtransaction if another subtransaction is already active.
2388**
2389** Statement subtransactions are used around individual SQL statements
2390** that are contained within a BEGIN...COMMIT block. If a constraint
2391** error occurs within the statement, the effect of that one statement
2392** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00002393*/
danielk1977aef0bf62005-12-30 16:28:01 +00002394int sqlite3BtreeBeginStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002395 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002396 BtShared *pBt = p->pBt;
2397 if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
drhf74b8d92002-09-01 23:20:45 +00002398 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh0d65dc02002-02-03 00:56:09 +00002399 }
danielk1977aef0bf62005-12-30 16:28:01 +00002400 assert( pBt->inTransaction==TRANS_WRITE );
drha34b6762004-05-07 13:30:42 +00002401 rc = pBt->readOnly ? SQLITE_OK : sqlite3pager_stmt_begin(pBt->pPager);
drh3aac2dd2004-04-26 14:10:20 +00002402 pBt->inStmt = 1;
drh663fc632002-02-02 18:49:19 +00002403 return rc;
2404}
2405
2406
2407/*
drhab01f612004-05-22 02:55:23 +00002408** Commit the statment subtransaction currently in progress. If no
2409** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00002410*/
danielk1977aef0bf62005-12-30 16:28:01 +00002411int sqlite3BtreeCommitStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002412 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002413 BtShared *pBt = p->pBt;
drh3aac2dd2004-04-26 14:10:20 +00002414 if( pBt->inStmt && !pBt->readOnly ){
drha34b6762004-05-07 13:30:42 +00002415 rc = sqlite3pager_stmt_commit(pBt->pPager);
drh663fc632002-02-02 18:49:19 +00002416 }else{
2417 rc = SQLITE_OK;
2418 }
drh3aac2dd2004-04-26 14:10:20 +00002419 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00002420 return rc;
2421}
2422
2423/*
drhab01f612004-05-22 02:55:23 +00002424** Rollback the active statement subtransaction. If no subtransaction
2425** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00002426**
drhab01f612004-05-22 02:55:23 +00002427** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00002428** to use a cursor that was open at the beginning of this operation
2429** will result in an error.
2430*/
danielk1977aef0bf62005-12-30 16:28:01 +00002431int sqlite3BtreeRollbackStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002432 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002433 BtShared *pBt = p->pBt;
drh3aac2dd2004-04-26 14:10:20 +00002434 if( pBt->inStmt==0 || pBt->readOnly ) return SQLITE_OK;
drha34b6762004-05-07 13:30:42 +00002435 rc = sqlite3pager_stmt_rollback(pBt->pPager);
danielk1977fbcd5852004-06-15 02:44:18 +00002436 assert( countWriteCursors(pBt)==0 );
drh3aac2dd2004-04-26 14:10:20 +00002437 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00002438 return rc;
2439}
2440
2441/*
drh3aac2dd2004-04-26 14:10:20 +00002442** Default key comparison function to be used if no comparison function
2443** is specified on the sqlite3BtreeCursor() call.
2444*/
2445static int dfltCompare(
2446 void *NotUsed, /* User data is not used */
2447 int n1, const void *p1, /* First key to compare */
2448 int n2, const void *p2 /* Second key to compare */
2449){
2450 int c;
2451 c = memcmp(p1, p2, n1<n2 ? n1 : n2);
2452 if( c==0 ){
2453 c = n1 - n2;
2454 }
2455 return c;
2456}
2457
2458/*
drh8b2f49b2001-06-08 00:21:52 +00002459** Create a new cursor for the BTree whose root is on the page
2460** iTable. The act of acquiring a cursor gets a read lock on
2461** the database file.
drh1bee3d72001-10-15 00:44:35 +00002462**
2463** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00002464** If wrFlag==1, then the cursor can be used for reading or for
2465** writing if other conditions for writing are also met. These
2466** are the conditions that must be met in order for writing to
2467** be allowed:
drh6446c4d2001-12-15 14:22:18 +00002468**
drhf74b8d92002-09-01 23:20:45 +00002469** 1: The cursor must have been opened with wrFlag==1
2470**
2471** 2: No other cursors may be open with wrFlag==0 on the same table
2472**
2473** 3: The database must be writable (not on read-only media)
2474**
2475** 4: There must be an active transaction.
2476**
2477** Condition 2 warrants further discussion. If any cursor is opened
2478** on a table with wrFlag==0, that prevents all other cursors from
2479** writing to that table. This is a kind of "read-lock". When a cursor
2480** is opened with wrFlag==0 it is guaranteed that the table will not
2481** change as long as the cursor is open. This allows the cursor to
2482** do a sequential scan of the table without having to worry about
2483** entries being inserted or deleted during the scan. Cursors should
2484** be opened with wrFlag==0 only if this read-lock property is needed.
2485** That is to say, cursors should be opened with wrFlag==0 only if they
drh23e11ca2004-05-04 17:27:28 +00002486** intend to use the sqlite3BtreeNext() system call. All other cursors
drhf74b8d92002-09-01 23:20:45 +00002487** should be opened with wrFlag==1 even if they never really intend
2488** to write.
2489**
drh6446c4d2001-12-15 14:22:18 +00002490** No checking is done to make sure that page iTable really is the
2491** root page of a b-tree. If it is not, then the cursor acquired
2492** will not work correctly.
drh3aac2dd2004-04-26 14:10:20 +00002493**
2494** The comparison function must be logically the same for every cursor
2495** on a particular table. Changing the comparison function will result
2496** in incorrect operations. If the comparison function is NULL, a
2497** default comparison function is used. The comparison function is
2498** always ignored for INTKEY tables.
drha059ad02001-04-17 20:09:11 +00002499*/
drh3aac2dd2004-04-26 14:10:20 +00002500int sqlite3BtreeCursor(
danielk1977aef0bf62005-12-30 16:28:01 +00002501 Btree *p, /* The btree */
drh3aac2dd2004-04-26 14:10:20 +00002502 int iTable, /* Root page of table to open */
2503 int wrFlag, /* 1 to write. 0 read-only */
2504 int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
2505 void *pArg, /* First arg to xCompare() */
2506 BtCursor **ppCur /* Write new cursor here */
2507){
drha059ad02001-04-17 20:09:11 +00002508 int rc;
drh8dcd7ca2004-08-08 19:43:29 +00002509 BtCursor *pCur;
danielk1977aef0bf62005-12-30 16:28:01 +00002510 BtShared *pBt = p->pBt;
drhecdc7532001-09-23 02:35:53 +00002511
drh8dcd7ca2004-08-08 19:43:29 +00002512 *ppCur = 0;
2513 if( wrFlag ){
drh8dcd7ca2004-08-08 19:43:29 +00002514 if( pBt->readOnly ){
2515 return SQLITE_READONLY;
2516 }
2517 if( checkReadLocks(pBt, iTable, 0) ){
2518 return SQLITE_LOCKED;
2519 }
drha0c9a112004-03-10 13:42:37 +00002520 }
danielk1977aef0bf62005-12-30 16:28:01 +00002521
2522#ifndef SQLITE_OMIT_SHARED_CACHE
2523 rc = queryTableLock(p, iTable, wrFlag?WRITE_LOCK:READ_LOCK);
2524 if( rc!=SQLITE_OK ){
2525 return rc;
2526 }
2527#endif
2528
drh4b70f112004-05-02 21:12:19 +00002529 if( pBt->pPage1==0 ){
danielk1977aef0bf62005-12-30 16:28:01 +00002530 rc = lockBtreeWithRetry(p);
drha059ad02001-04-17 20:09:11 +00002531 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002532 return rc;
2533 }
2534 }
drheafe05b2004-06-13 00:54:01 +00002535 pCur = sqliteMallocRaw( sizeof(*pCur) );
drha059ad02001-04-17 20:09:11 +00002536 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +00002537 rc = SQLITE_NOMEM;
2538 goto create_cursor_exception;
2539 }
drh8b2f49b2001-06-08 00:21:52 +00002540 pCur->pgnoRoot = (Pgno)iTable;
danielk19776b456a22005-03-21 04:04:02 +00002541 pCur->pPage = 0; /* For exit-handler, in case getAndInitPage() fails. */
drh24cd67e2004-05-10 16:18:47 +00002542 if( iTable==1 && sqlite3pager_pagecount(pBt->pPager)==0 ){
2543 rc = SQLITE_EMPTY;
2544 goto create_cursor_exception;
2545 }
drhde647132004-05-07 17:57:49 +00002546 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
drhbd03cae2001-06-02 02:40:57 +00002547 if( rc!=SQLITE_OK ){
2548 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002549 }
danielk1977aef0bf62005-12-30 16:28:01 +00002550
2551 /* Obtain the table-lock on the shared-btree. */
2552 rc = lockTable(p, iTable, wrFlag?WRITE_LOCK:READ_LOCK);
2553 if( rc!=SQLITE_OK ){
2554 assert( rc==SQLITE_NOMEM );
2555 goto create_cursor_exception;
2556 }
2557
2558 /* Now that no other errors can occur, finish filling in the BtCursor
2559 ** variables, link the cursor into the BtShared list and set *ppCur (the
2560 ** output argument to this function).
2561 */
drh3aac2dd2004-04-26 14:10:20 +00002562 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2563 pCur->pArg = pArg;
danielk1977aef0bf62005-12-30 16:28:01 +00002564 pCur->pBtree = p;
drhecdc7532001-09-23 02:35:53 +00002565 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +00002566 pCur->idx = 0;
drh59eb6762004-06-13 23:07:04 +00002567 memset(&pCur->info, 0, sizeof(pCur->info));
drha059ad02001-04-17 20:09:11 +00002568 pCur->pNext = pBt->pCursor;
2569 if( pCur->pNext ){
2570 pCur->pNext->pPrev = pCur;
2571 }
drh14acc042001-06-10 19:56:58 +00002572 pCur->pPrev = 0;
drha059ad02001-04-17 20:09:11 +00002573 pBt->pCursor = pCur;
drhc39e0002004-05-07 23:50:57 +00002574 pCur->isValid = 0;
drh2af926b2001-05-15 00:39:25 +00002575 *ppCur = pCur;
drhbd03cae2001-06-02 02:40:57 +00002576
danielk1977aef0bf62005-12-30 16:28:01 +00002577 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00002578create_cursor_exception:
drhbd03cae2001-06-02 02:40:57 +00002579 if( pCur ){
drh3aac2dd2004-04-26 14:10:20 +00002580 releasePage(pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +00002581 sqliteFree(pCur);
2582 }
drh5e00f6c2001-09-13 13:46:56 +00002583 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00002584 return rc;
drha059ad02001-04-17 20:09:11 +00002585}
2586
drh7a224de2004-06-02 01:22:02 +00002587#if 0 /* Not Used */
drhd3d39e92004-05-20 22:16:29 +00002588/*
2589** Change the value of the comparison function used by a cursor.
2590*/
danielk1977bf3b7212004-05-18 10:06:24 +00002591void sqlite3BtreeSetCompare(
drhd3d39e92004-05-20 22:16:29 +00002592 BtCursor *pCur, /* The cursor to whose comparison function is changed */
2593 int(*xCmp)(void*,int,const void*,int,const void*), /* New comparison func */
2594 void *pArg /* First argument to xCmp() */
danielk1977bf3b7212004-05-18 10:06:24 +00002595){
2596 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2597 pCur->pArg = pArg;
2598}
drh7a224de2004-06-02 01:22:02 +00002599#endif
danielk1977bf3b7212004-05-18 10:06:24 +00002600
drha059ad02001-04-17 20:09:11 +00002601/*
drh5e00f6c2001-09-13 13:46:56 +00002602** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00002603** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00002604*/
drh3aac2dd2004-04-26 14:10:20 +00002605int sqlite3BtreeCloseCursor(BtCursor *pCur){
danielk1977aef0bf62005-12-30 16:28:01 +00002606 BtShared *pBt = pCur->pBtree->pBt;
drha059ad02001-04-17 20:09:11 +00002607 if( pCur->pPrev ){
2608 pCur->pPrev->pNext = pCur->pNext;
2609 }else{
2610 pBt->pCursor = pCur->pNext;
2611 }
2612 if( pCur->pNext ){
2613 pCur->pNext->pPrev = pCur->pPrev;
2614 }
drh3aac2dd2004-04-26 14:10:20 +00002615 releasePage(pCur->pPage);
drh5e00f6c2001-09-13 13:46:56 +00002616 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00002617 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +00002618 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002619}
2620
drh7e3b0a02001-04-28 16:52:40 +00002621/*
drh5e2f8b92001-05-28 00:41:15 +00002622** Make a temporary cursor by filling in the fields of pTempCur.
2623** The temporary cursor is not on the cursor list for the Btree.
2624*/
drh14acc042001-06-10 19:56:58 +00002625static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00002626 memcpy(pTempCur, pCur, sizeof(*pCur));
2627 pTempCur->pNext = 0;
2628 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00002629 if( pTempCur->pPage ){
drha34b6762004-05-07 13:30:42 +00002630 sqlite3pager_ref(pTempCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00002631 }
drh5e2f8b92001-05-28 00:41:15 +00002632}
2633
2634/*
drhbd03cae2001-06-02 02:40:57 +00002635** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00002636** function above.
2637*/
drh14acc042001-06-10 19:56:58 +00002638static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00002639 if( pCur->pPage ){
drha34b6762004-05-07 13:30:42 +00002640 sqlite3pager_unref(pCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00002641 }
drh5e2f8b92001-05-28 00:41:15 +00002642}
2643
2644/*
drh9188b382004-05-14 21:12:22 +00002645** Make sure the BtCursor.info field of the given cursor is valid.
drhab01f612004-05-22 02:55:23 +00002646** If it is not already valid, call parseCell() to fill it in.
2647**
2648** BtCursor.info is a cache of the information in the current cell.
2649** Using this cache reduces the number of calls to parseCell().
drh9188b382004-05-14 21:12:22 +00002650*/
2651static void getCellInfo(BtCursor *pCur){
drh271efa52004-05-30 19:19:05 +00002652 if( pCur->info.nSize==0 ){
drh3a41a3f2004-05-30 02:14:17 +00002653 parseCell(pCur->pPage, pCur->idx, &pCur->info);
drh9188b382004-05-14 21:12:22 +00002654 }else{
2655#ifndef NDEBUG
2656 CellInfo info;
drh51c6d962004-06-06 00:42:25 +00002657 memset(&info, 0, sizeof(info));
drh3a41a3f2004-05-30 02:14:17 +00002658 parseCell(pCur->pPage, pCur->idx, &info);
drh9188b382004-05-14 21:12:22 +00002659 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
2660#endif
2661 }
2662}
2663
2664/*
drh3aac2dd2004-04-26 14:10:20 +00002665** Set *pSize to the size of the buffer needed to hold the value of
2666** the key for the current entry. If the cursor is not pointing
2667** to a valid entry, *pSize is set to 0.
2668**
drh4b70f112004-05-02 21:12:19 +00002669** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00002670** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00002671*/
drh4a1c3802004-05-12 15:15:47 +00002672int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
danielk1977299b1872004-11-22 10:02:10 +00002673 if( !pCur->isValid ){
drh72f82862001-05-24 21:06:34 +00002674 *pSize = 0;
2675 }else{
drh9188b382004-05-14 21:12:22 +00002676 getCellInfo(pCur);
2677 *pSize = pCur->info.nKey;
drh72f82862001-05-24 21:06:34 +00002678 }
2679 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002680}
drh2af926b2001-05-15 00:39:25 +00002681
drh72f82862001-05-24 21:06:34 +00002682/*
drh0e1c19e2004-05-11 00:58:56 +00002683** Set *pSize to the number of bytes of data in the entry the
2684** cursor currently points to. Always return SQLITE_OK.
2685** Failure is not possible. If the cursor is not currently
2686** pointing to an entry (which can happen, for example, if
2687** the database is empty) then *pSize is set to 0.
2688*/
2689int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
danielk1977299b1872004-11-22 10:02:10 +00002690 if( !pCur->isValid ){
danielk197796fc5fe2004-05-13 11:34:16 +00002691 /* Not pointing at a valid entry - set *pSize to 0. */
drh0e1c19e2004-05-11 00:58:56 +00002692 *pSize = 0;
2693 }else{
drh9188b382004-05-14 21:12:22 +00002694 getCellInfo(pCur);
2695 *pSize = pCur->info.nData;
drh0e1c19e2004-05-11 00:58:56 +00002696 }
2697 return SQLITE_OK;
2698}
2699
2700/*
drh72f82862001-05-24 21:06:34 +00002701** Read payload information from the entry that the pCur cursor is
2702** pointing to. Begin reading the payload at "offset" and read
2703** a total of "amt" bytes. Put the result in zBuf.
2704**
2705** This routine does not make a distinction between key and data.
drhab01f612004-05-22 02:55:23 +00002706** It just reads bytes from the payload area. Data might appear
2707** on the main page or be scattered out on multiple overflow pages.
drh72f82862001-05-24 21:06:34 +00002708*/
drh3aac2dd2004-04-26 14:10:20 +00002709static int getPayload(
2710 BtCursor *pCur, /* Cursor pointing to entry to read from */
2711 int offset, /* Begin reading this far into payload */
2712 int amt, /* Read this many bytes */
2713 unsigned char *pBuf, /* Write the bytes into this buffer */
2714 int skipKey /* offset begins at data if this is true */
2715){
2716 unsigned char *aPayload;
drh2af926b2001-05-15 00:39:25 +00002717 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +00002718 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002719 MemPage *pPage;
danielk1977aef0bf62005-12-30 16:28:01 +00002720 BtShared *pBt;
drh6f11bef2004-05-13 01:12:56 +00002721 int ovflSize;
drhfa1a98a2004-05-14 19:08:17 +00002722 u32 nKey;
drh3aac2dd2004-04-26 14:10:20 +00002723
drh72f82862001-05-24 21:06:34 +00002724 assert( pCur!=0 && pCur->pPage!=0 );
drhc39e0002004-05-07 23:50:57 +00002725 assert( pCur->isValid );
danielk1977aef0bf62005-12-30 16:28:01 +00002726 pBt = pCur->pBtree->pBt;
drh3aac2dd2004-04-26 14:10:20 +00002727 pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00002728 pageIntegrity(pPage);
drh3aac2dd2004-04-26 14:10:20 +00002729 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00002730 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00002731 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00002732 aPayload += pCur->info.nHeader;
drh3aac2dd2004-04-26 14:10:20 +00002733 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00002734 nKey = 0;
2735 }else{
2736 nKey = pCur->info.nKey;
drh3aac2dd2004-04-26 14:10:20 +00002737 }
2738 assert( offset>=0 );
2739 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00002740 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00002741 }
drhfa1a98a2004-05-14 19:08:17 +00002742 if( offset+amt > nKey+pCur->info.nData ){
drha34b6762004-05-07 13:30:42 +00002743 return SQLITE_ERROR;
drh3aac2dd2004-04-26 14:10:20 +00002744 }
drhfa1a98a2004-05-14 19:08:17 +00002745 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00002746 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00002747 if( a+offset>pCur->info.nLocal ){
2748 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00002749 }
drha34b6762004-05-07 13:30:42 +00002750 memcpy(pBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +00002751 if( a==amt ){
2752 return SQLITE_OK;
2753 }
drh2aa679f2001-06-25 02:11:07 +00002754 offset = 0;
drha34b6762004-05-07 13:30:42 +00002755 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00002756 amt -= a;
drhdd793422001-06-28 01:54:48 +00002757 }else{
drhfa1a98a2004-05-14 19:08:17 +00002758 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00002759 }
danielk1977cfe9a692004-06-16 12:00:29 +00002760 ovflSize = pBt->usableSize - 4;
drhbd03cae2001-06-02 02:40:57 +00002761 if( amt>0 ){
drhfa1a98a2004-05-14 19:08:17 +00002762 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977cfe9a692004-06-16 12:00:29 +00002763 while( amt>0 && nextPage ){
2764 rc = sqlite3pager_get(pBt->pPager, nextPage, (void**)&aPayload);
2765 if( rc!=0 ){
2766 return rc;
drh2af926b2001-05-15 00:39:25 +00002767 }
danielk1977cfe9a692004-06-16 12:00:29 +00002768 nextPage = get4byte(aPayload);
2769 if( offset<ovflSize ){
2770 int a = amt;
2771 if( a + offset > ovflSize ){
2772 a = ovflSize - offset;
2773 }
2774 memcpy(pBuf, &aPayload[offset+4], a);
2775 offset = 0;
2776 amt -= a;
2777 pBuf += a;
2778 }else{
2779 offset -= ovflSize;
2780 }
2781 sqlite3pager_unref(aPayload);
drh2af926b2001-05-15 00:39:25 +00002782 }
drh2af926b2001-05-15 00:39:25 +00002783 }
danielk1977cfe9a692004-06-16 12:00:29 +00002784
drha7fcb052001-12-14 15:09:55 +00002785 if( amt>0 ){
drh49285702005-09-17 15:20:26 +00002786 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00002787 }
2788 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00002789}
2790
drh72f82862001-05-24 21:06:34 +00002791/*
drh3aac2dd2004-04-26 14:10:20 +00002792** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002793** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002794** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00002795**
drh3aac2dd2004-04-26 14:10:20 +00002796** Return SQLITE_OK on success or an error code if anything goes
2797** wrong. An error is returned if "offset+amt" is larger than
2798** the available payload.
drh72f82862001-05-24 21:06:34 +00002799*/
drha34b6762004-05-07 13:30:42 +00002800int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
danielk197728129562005-01-11 10:25:06 +00002801 assert( pCur->isValid );
drhc39e0002004-05-07 23:50:57 +00002802 assert( pCur->pPage!=0 );
drh6575a222005-03-10 17:06:34 +00002803 if( pCur->pPage->intKey ){
drh49285702005-09-17 15:20:26 +00002804 return SQLITE_CORRUPT_BKPT;
drh6575a222005-03-10 17:06:34 +00002805 }
drhc39e0002004-05-07 23:50:57 +00002806 assert( pCur->pPage->intKey==0 );
2807 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh3aac2dd2004-04-26 14:10:20 +00002808 return getPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
2809}
2810
2811/*
drh3aac2dd2004-04-26 14:10:20 +00002812** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002813** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002814** begins at "offset".
2815**
2816** Return SQLITE_OK on success or an error code if anything goes
2817** wrong. An error is returned if "offset+amt" is larger than
2818** the available payload.
drh72f82862001-05-24 21:06:34 +00002819*/
drh3aac2dd2004-04-26 14:10:20 +00002820int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
danielk197728129562005-01-11 10:25:06 +00002821 assert( pCur->isValid );
drh8c1238a2003-01-02 14:43:55 +00002822 assert( pCur->pPage!=0 );
drhc39e0002004-05-07 23:50:57 +00002823 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh3aac2dd2004-04-26 14:10:20 +00002824 return getPayload(pCur, offset, amt, pBuf, 1);
drh2af926b2001-05-15 00:39:25 +00002825}
2826
drh72f82862001-05-24 21:06:34 +00002827/*
drh0e1c19e2004-05-11 00:58:56 +00002828** Return a pointer to payload information from the entry that the
2829** pCur cursor is pointing to. The pointer is to the beginning of
2830** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00002831** skipKey==1. The number of bytes of available key/data is written
2832** into *pAmt. If *pAmt==0, then the value returned will not be
2833** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00002834**
2835** This routine is an optimization. It is common for the entire key
2836** and data to fit on the local page and for there to be no overflow
2837** pages. When that is so, this routine can be used to access the
2838** key and data without making a copy. If the key and/or data spills
2839** onto overflow pages, then getPayload() must be used to reassembly
2840** the key/data and copy it into a preallocated buffer.
2841**
2842** The pointer returned by this routine looks directly into the cached
2843** page of the database. The data might change or move the next time
2844** any btree routine is called.
2845*/
2846static const unsigned char *fetchPayload(
2847 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00002848 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00002849 int skipKey /* read beginning at data if this is true */
2850){
2851 unsigned char *aPayload;
2852 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00002853 u32 nKey;
2854 int nLocal;
drh0e1c19e2004-05-11 00:58:56 +00002855
2856 assert( pCur!=0 && pCur->pPage!=0 );
2857 assert( pCur->isValid );
drh0e1c19e2004-05-11 00:58:56 +00002858 pPage = pCur->pPage;
2859 pageIntegrity(pPage);
2860 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00002861 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00002862 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00002863 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00002864 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00002865 nKey = 0;
2866 }else{
2867 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00002868 }
drh0e1c19e2004-05-11 00:58:56 +00002869 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00002870 aPayload += nKey;
2871 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00002872 }else{
drhfa1a98a2004-05-14 19:08:17 +00002873 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00002874 if( nLocal>nKey ){
2875 nLocal = nKey;
2876 }
drh0e1c19e2004-05-11 00:58:56 +00002877 }
drhe51c44f2004-05-30 20:46:09 +00002878 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00002879 return aPayload;
2880}
2881
2882
2883/*
drhe51c44f2004-05-30 20:46:09 +00002884** For the entry that cursor pCur is point to, return as
2885** many bytes of the key or data as are available on the local
2886** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00002887**
2888** The pointer returned is ephemeral. The key/data may move
2889** or be destroyed on the next call to any Btree routine.
2890**
2891** These routines is used to get quick access to key and data
2892** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00002893*/
drhe51c44f2004-05-30 20:46:09 +00002894const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
2895 return (const void*)fetchPayload(pCur, pAmt, 0);
drh0e1c19e2004-05-11 00:58:56 +00002896}
drhe51c44f2004-05-30 20:46:09 +00002897const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
2898 return (const void*)fetchPayload(pCur, pAmt, 1);
drh0e1c19e2004-05-11 00:58:56 +00002899}
2900
2901
2902/*
drh8178a752003-01-05 21:41:40 +00002903** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00002904** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00002905*/
drh3aac2dd2004-04-26 14:10:20 +00002906static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00002907 int rc;
2908 MemPage *pNewPage;
drh3aac2dd2004-04-26 14:10:20 +00002909 MemPage *pOldPage;
danielk1977aef0bf62005-12-30 16:28:01 +00002910 BtShared *pBt = pCur->pBtree->pBt;
drh72f82862001-05-24 21:06:34 +00002911
drhc39e0002004-05-07 23:50:57 +00002912 assert( pCur->isValid );
drhde647132004-05-07 17:57:49 +00002913 rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00002914 if( rc ) return rc;
drhda200cc2004-05-09 11:51:38 +00002915 pageIntegrity(pNewPage);
drh428ae8c2003-01-04 16:48:09 +00002916 pNewPage->idxParent = pCur->idx;
drh3aac2dd2004-04-26 14:10:20 +00002917 pOldPage = pCur->pPage;
2918 pOldPage->idxShift = 0;
2919 releasePage(pOldPage);
drh72f82862001-05-24 21:06:34 +00002920 pCur->pPage = pNewPage;
2921 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00002922 pCur->info.nSize = 0;
drh4be295b2003-12-16 03:44:47 +00002923 if( pNewPage->nCell<1 ){
drh49285702005-09-17 15:20:26 +00002924 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00002925 }
drh72f82862001-05-24 21:06:34 +00002926 return SQLITE_OK;
2927}
2928
2929/*
drh8856d6a2004-04-29 14:42:46 +00002930** Return true if the page is the virtual root of its table.
2931**
2932** The virtual root page is the root page for most tables. But
2933** for the table rooted on page 1, sometime the real root page
2934** is empty except for the right-pointer. In such cases the
2935** virtual root page is the page that the right-pointer of page
2936** 1 is pointing to.
2937*/
2938static int isRootPage(MemPage *pPage){
2939 MemPage *pParent = pPage->pParent;
drhda200cc2004-05-09 11:51:38 +00002940 if( pParent==0 ) return 1;
2941 if( pParent->pgno>1 ) return 0;
2942 if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
drh8856d6a2004-04-29 14:42:46 +00002943 return 0;
2944}
2945
2946/*
drh5e2f8b92001-05-28 00:41:15 +00002947** Move the cursor up to the parent page.
2948**
2949** pCur->idx is set to the cell index that contains the pointer
2950** to the page we are coming from. If we are coming from the
2951** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00002952** the largest cell index.
drh72f82862001-05-24 21:06:34 +00002953*/
drh8178a752003-01-05 21:41:40 +00002954static void moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00002955 MemPage *pParent;
drh8178a752003-01-05 21:41:40 +00002956 MemPage *pPage;
drh428ae8c2003-01-04 16:48:09 +00002957 int idxParent;
drh3aac2dd2004-04-26 14:10:20 +00002958
drhc39e0002004-05-07 23:50:57 +00002959 assert( pCur->isValid );
drh8178a752003-01-05 21:41:40 +00002960 pPage = pCur->pPage;
2961 assert( pPage!=0 );
drh8856d6a2004-04-29 14:42:46 +00002962 assert( !isRootPage(pPage) );
drhda200cc2004-05-09 11:51:38 +00002963 pageIntegrity(pPage);
drh8178a752003-01-05 21:41:40 +00002964 pParent = pPage->pParent;
2965 assert( pParent!=0 );
drhda200cc2004-05-09 11:51:38 +00002966 pageIntegrity(pParent);
drh8178a752003-01-05 21:41:40 +00002967 idxParent = pPage->idxParent;
drha34b6762004-05-07 13:30:42 +00002968 sqlite3pager_ref(pParent->aData);
drh3aac2dd2004-04-26 14:10:20 +00002969 releasePage(pPage);
drh72f82862001-05-24 21:06:34 +00002970 pCur->pPage = pParent;
drh271efa52004-05-30 19:19:05 +00002971 pCur->info.nSize = 0;
drh428ae8c2003-01-04 16:48:09 +00002972 assert( pParent->idxShift==0 );
drh43605152004-05-29 21:46:49 +00002973 pCur->idx = idxParent;
drh72f82862001-05-24 21:06:34 +00002974}
2975
2976/*
2977** Move the cursor to the root page
2978*/
drh5e2f8b92001-05-28 00:41:15 +00002979static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00002980 MemPage *pRoot;
drhbd03cae2001-06-02 02:40:57 +00002981 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002982 BtShared *pBt = pCur->pBtree->pBt;
drhbd03cae2001-06-02 02:40:57 +00002983
drhde647132004-05-07 17:57:49 +00002984 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0);
drhc39e0002004-05-07 23:50:57 +00002985 if( rc ){
2986 pCur->isValid = 0;
2987 return rc;
2988 }
drh3aac2dd2004-04-26 14:10:20 +00002989 releasePage(pCur->pPage);
drhda200cc2004-05-09 11:51:38 +00002990 pageIntegrity(pRoot);
drh3aac2dd2004-04-26 14:10:20 +00002991 pCur->pPage = pRoot;
drh72f82862001-05-24 21:06:34 +00002992 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00002993 pCur->info.nSize = 0;
drh8856d6a2004-04-29 14:42:46 +00002994 if( pRoot->nCell==0 && !pRoot->leaf ){
2995 Pgno subpage;
2996 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00002997 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00002998 assert( subpage>0 );
drh3644f082004-05-10 18:45:09 +00002999 pCur->isValid = 1;
drh4b70f112004-05-02 21:12:19 +00003000 rc = moveToChild(pCur, subpage);
drh8856d6a2004-04-29 14:42:46 +00003001 }
drhc39e0002004-05-07 23:50:57 +00003002 pCur->isValid = pCur->pPage->nCell>0;
drh8856d6a2004-04-29 14:42:46 +00003003 return rc;
drh72f82862001-05-24 21:06:34 +00003004}
drh2af926b2001-05-15 00:39:25 +00003005
drh5e2f8b92001-05-28 00:41:15 +00003006/*
3007** Move the cursor down to the left-most leaf entry beneath the
3008** entry to which it is currently pointing.
3009*/
3010static int moveToLeftmost(BtCursor *pCur){
3011 Pgno pgno;
3012 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003013 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00003014
drhc39e0002004-05-07 23:50:57 +00003015 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00003016 while( !(pPage = pCur->pPage)->leaf ){
drha34b6762004-05-07 13:30:42 +00003017 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00003018 pgno = get4byte(findCell(pPage, pCur->idx));
drh8178a752003-01-05 21:41:40 +00003019 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00003020 if( rc ) return rc;
3021 }
3022 return SQLITE_OK;
3023}
3024
drh2dcc9aa2002-12-04 13:40:25 +00003025/*
3026** Move the cursor down to the right-most leaf entry beneath the
3027** page to which it is currently pointing. Notice the difference
3028** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
3029** finds the left-most entry beneath the *entry* whereas moveToRightmost()
3030** finds the right-most entry beneath the *page*.
3031*/
3032static int moveToRightmost(BtCursor *pCur){
3033 Pgno pgno;
3034 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003035 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003036
drhc39e0002004-05-07 23:50:57 +00003037 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00003038 while( !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00003039 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh3aac2dd2004-04-26 14:10:20 +00003040 pCur->idx = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00003041 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003042 if( rc ) return rc;
3043 }
drh3aac2dd2004-04-26 14:10:20 +00003044 pCur->idx = pPage->nCell - 1;
drh271efa52004-05-30 19:19:05 +00003045 pCur->info.nSize = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003046 return SQLITE_OK;
3047}
3048
drh5e00f6c2001-09-13 13:46:56 +00003049/* Move the cursor to the first entry in the table. Return SQLITE_OK
3050** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003051** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00003052*/
drh3aac2dd2004-04-26 14:10:20 +00003053int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00003054 int rc;
3055 rc = moveToRoot(pCur);
3056 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00003057 if( pCur->isValid==0 ){
3058 assert( pCur->pPage->nCell==0 );
drh5e00f6c2001-09-13 13:46:56 +00003059 *pRes = 1;
3060 return SQLITE_OK;
3061 }
drhc39e0002004-05-07 23:50:57 +00003062 assert( pCur->pPage->nCell>0 );
drh5e00f6c2001-09-13 13:46:56 +00003063 *pRes = 0;
3064 rc = moveToLeftmost(pCur);
3065 return rc;
3066}
drh5e2f8b92001-05-28 00:41:15 +00003067
drh9562b552002-02-19 15:00:07 +00003068/* Move the cursor to the last entry in the table. Return SQLITE_OK
3069** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003070** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00003071*/
drh3aac2dd2004-04-26 14:10:20 +00003072int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00003073 int rc;
drh9562b552002-02-19 15:00:07 +00003074 rc = moveToRoot(pCur);
3075 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00003076 if( pCur->isValid==0 ){
3077 assert( pCur->pPage->nCell==0 );
drh9562b552002-02-19 15:00:07 +00003078 *pRes = 1;
3079 return SQLITE_OK;
3080 }
drhc39e0002004-05-07 23:50:57 +00003081 assert( pCur->isValid );
drh9562b552002-02-19 15:00:07 +00003082 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003083 rc = moveToRightmost(pCur);
drh9562b552002-02-19 15:00:07 +00003084 return rc;
3085}
3086
drh3aac2dd2004-04-26 14:10:20 +00003087/* Move the cursor so that it points to an entry near pKey/nKey.
drh72f82862001-05-24 21:06:34 +00003088** Return a success code.
3089**
drh3aac2dd2004-04-26 14:10:20 +00003090** For INTKEY tables, only the nKey parameter is used. pKey is
3091** ignored. For other tables, nKey is the number of bytes of data
drh0b2f3162005-12-21 18:36:45 +00003092** in pKey. The comparison function specified when the cursor was
drh3aac2dd2004-04-26 14:10:20 +00003093** created is used to compare keys.
3094**
drh5e2f8b92001-05-28 00:41:15 +00003095** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00003096** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00003097** were present. The cursor might point to an entry that comes
3098** before or after the key.
3099**
drhbd03cae2001-06-02 02:40:57 +00003100** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00003101** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00003102** this value is as follows:
3103**
3104** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00003105** is smaller than pKey or if the table is empty
3106** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00003107**
3108** *pRes==0 The cursor is left pointing at an entry that
3109** exactly matches pKey.
3110**
3111** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00003112** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00003113*/
drh4a1c3802004-05-12 15:15:47 +00003114int sqlite3BtreeMoveto(BtCursor *pCur, const void *pKey, i64 nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00003115 int rc;
drh5e2f8b92001-05-28 00:41:15 +00003116 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00003117 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00003118 assert( pCur->pPage );
3119 assert( pCur->pPage->isInit );
3120 if( pCur->isValid==0 ){
drhf328bc82004-05-10 23:29:49 +00003121 *pRes = -1;
drhc39e0002004-05-07 23:50:57 +00003122 assert( pCur->pPage->nCell==0 );
3123 return SQLITE_OK;
3124 }
drh4eec4c12005-01-21 00:22:37 +00003125 for(;;){
drh72f82862001-05-24 21:06:34 +00003126 int lwr, upr;
3127 Pgno chldPg;
3128 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00003129 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00003130 lwr = 0;
3131 upr = pPage->nCell-1;
drh4eec4c12005-01-21 00:22:37 +00003132 if( !pPage->intKey && pKey==0 ){
drh49285702005-09-17 15:20:26 +00003133 return SQLITE_CORRUPT_BKPT;
drh4eec4c12005-01-21 00:22:37 +00003134 }
drhda200cc2004-05-09 11:51:38 +00003135 pageIntegrity(pPage);
drh72f82862001-05-24 21:06:34 +00003136 while( lwr<=upr ){
danielk197713adf8a2004-06-03 16:08:41 +00003137 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00003138 i64 nCellKey;
drh72f82862001-05-24 21:06:34 +00003139 pCur->idx = (lwr+upr)/2;
drh271efa52004-05-30 19:19:05 +00003140 pCur->info.nSize = 0;
drhde647132004-05-07 17:57:49 +00003141 sqlite3BtreeKeySize(pCur, &nCellKey);
drh3aac2dd2004-04-26 14:10:20 +00003142 if( pPage->intKey ){
3143 if( nCellKey<nKey ){
3144 c = -1;
3145 }else if( nCellKey>nKey ){
3146 c = +1;
3147 }else{
3148 c = 0;
3149 }
drh3aac2dd2004-04-26 14:10:20 +00003150 }else{
drhe51c44f2004-05-30 20:46:09 +00003151 int available;
danielk197713adf8a2004-06-03 16:08:41 +00003152 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drhe51c44f2004-05-30 20:46:09 +00003153 if( available>=nCellKey ){
3154 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
3155 }else{
3156 pCellKey = sqliteMallocRaw( nCellKey );
3157 if( pCellKey==0 ) return SQLITE_NOMEM;
danielk197713adf8a2004-06-03 16:08:41 +00003158 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
drhe51c44f2004-05-30 20:46:09 +00003159 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
3160 sqliteFree(pCellKey);
3161 if( rc ) return rc;
3162 }
drh3aac2dd2004-04-26 14:10:20 +00003163 }
drh72f82862001-05-24 21:06:34 +00003164 if( c==0 ){
drh8b18dd42004-05-12 19:18:15 +00003165 if( pPage->leafData && !pPage->leaf ){
drhfc70e6f2004-05-12 21:11:27 +00003166 lwr = pCur->idx;
3167 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00003168 break;
3169 }else{
drh8b18dd42004-05-12 19:18:15 +00003170 if( pRes ) *pRes = 0;
3171 return SQLITE_OK;
3172 }
drh72f82862001-05-24 21:06:34 +00003173 }
3174 if( c<0 ){
3175 lwr = pCur->idx+1;
3176 }else{
3177 upr = pCur->idx-1;
3178 }
3179 }
3180 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00003181 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00003182 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00003183 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00003184 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00003185 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00003186 }else{
drh43605152004-05-29 21:46:49 +00003187 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00003188 }
3189 if( chldPg==0 ){
drhc39e0002004-05-07 23:50:57 +00003190 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00003191 if( pRes ) *pRes = c;
3192 return SQLITE_OK;
3193 }
drh428ae8c2003-01-04 16:48:09 +00003194 pCur->idx = lwr;
drh271efa52004-05-30 19:19:05 +00003195 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00003196 rc = moveToChild(pCur, chldPg);
drhc39e0002004-05-07 23:50:57 +00003197 if( rc ){
3198 return rc;
3199 }
drh72f82862001-05-24 21:06:34 +00003200 }
drhbd03cae2001-06-02 02:40:57 +00003201 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00003202}
3203
3204/*
drhc39e0002004-05-07 23:50:57 +00003205** Return TRUE if the cursor is not pointing at an entry of the table.
3206**
3207** TRUE will be returned after a call to sqlite3BtreeNext() moves
3208** past the last entry in the table or sqlite3BtreePrev() moves past
3209** the first entry. TRUE is also returned if the table is empty.
3210*/
3211int sqlite3BtreeEof(BtCursor *pCur){
3212 return pCur->isValid==0;
3213}
3214
3215/*
drhbd03cae2001-06-02 02:40:57 +00003216** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00003217** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00003218** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00003219** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00003220*/
drh3aac2dd2004-04-26 14:10:20 +00003221int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00003222 int rc;
drh8178a752003-01-05 21:41:40 +00003223 MemPage *pPage = pCur->pPage;
drh8b18dd42004-05-12 19:18:15 +00003224
drh8c1238a2003-01-02 14:43:55 +00003225 assert( pRes!=0 );
drhc39e0002004-05-07 23:50:57 +00003226 if( pCur->isValid==0 ){
drh8c1238a2003-01-02 14:43:55 +00003227 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00003228 return SQLITE_OK;
drhecdc7532001-09-23 02:35:53 +00003229 }
drh8178a752003-01-05 21:41:40 +00003230 assert( pPage->isInit );
drh8178a752003-01-05 21:41:40 +00003231 assert( pCur->idx<pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00003232
drh72f82862001-05-24 21:06:34 +00003233 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00003234 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00003235 if( pCur->idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00003236 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003237 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00003238 if( rc ) return rc;
3239 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003240 *pRes = 0;
3241 return rc;
drh72f82862001-05-24 21:06:34 +00003242 }
drh5e2f8b92001-05-28 00:41:15 +00003243 do{
drh8856d6a2004-04-29 14:42:46 +00003244 if( isRootPage(pPage) ){
drh8c1238a2003-01-02 14:43:55 +00003245 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00003246 pCur->isValid = 0;
drh5e2f8b92001-05-28 00:41:15 +00003247 return SQLITE_OK;
3248 }
drh8178a752003-01-05 21:41:40 +00003249 moveToParent(pCur);
3250 pPage = pCur->pPage;
3251 }while( pCur->idx>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00003252 *pRes = 0;
drh8b18dd42004-05-12 19:18:15 +00003253 if( pPage->leafData ){
3254 rc = sqlite3BtreeNext(pCur, pRes);
3255 }else{
3256 rc = SQLITE_OK;
3257 }
3258 return rc;
drh8178a752003-01-05 21:41:40 +00003259 }
3260 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00003261 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00003262 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00003263 }
drh5e2f8b92001-05-28 00:41:15 +00003264 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003265 return rc;
drh72f82862001-05-24 21:06:34 +00003266}
3267
drh3b7511c2001-05-26 13:15:44 +00003268/*
drh2dcc9aa2002-12-04 13:40:25 +00003269** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00003270** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00003271** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00003272** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00003273*/
drh3aac2dd2004-04-26 14:10:20 +00003274int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00003275 int rc;
3276 Pgno pgno;
drh8178a752003-01-05 21:41:40 +00003277 MemPage *pPage;
drhc39e0002004-05-07 23:50:57 +00003278 if( pCur->isValid==0 ){
3279 *pRes = 1;
3280 return SQLITE_OK;
3281 }
danielk19776a43f9b2004-11-16 04:57:24 +00003282
drh8178a752003-01-05 21:41:40 +00003283 pPage = pCur->pPage;
drh8178a752003-01-05 21:41:40 +00003284 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00003285 assert( pCur->idx>=0 );
drha34b6762004-05-07 13:30:42 +00003286 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003287 pgno = get4byte( findCell(pPage, pCur->idx) );
drh8178a752003-01-05 21:41:40 +00003288 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003289 if( rc ) return rc;
3290 rc = moveToRightmost(pCur);
3291 }else{
3292 while( pCur->idx==0 ){
drh8856d6a2004-04-29 14:42:46 +00003293 if( isRootPage(pPage) ){
drhc39e0002004-05-07 23:50:57 +00003294 pCur->isValid = 0;
3295 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00003296 return SQLITE_OK;
3297 }
drh8178a752003-01-05 21:41:40 +00003298 moveToParent(pCur);
3299 pPage = pCur->pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003300 }
3301 pCur->idx--;
drh271efa52004-05-30 19:19:05 +00003302 pCur->info.nSize = 0;
drh8237d452004-11-22 19:07:09 +00003303 if( pPage->leafData && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00003304 rc = sqlite3BtreePrevious(pCur, pRes);
3305 }else{
3306 rc = SQLITE_OK;
3307 }
drh2dcc9aa2002-12-04 13:40:25 +00003308 }
drh8178a752003-01-05 21:41:40 +00003309 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003310 return rc;
3311}
3312
3313/*
drh3b7511c2001-05-26 13:15:44 +00003314** Allocate a new page from the database file.
3315**
drha34b6762004-05-07 13:30:42 +00003316** The new page is marked as dirty. (In other words, sqlite3pager_write()
drh3b7511c2001-05-26 13:15:44 +00003317** has already been called on the new page.) The new page has also
3318** been referenced and the calling routine is responsible for calling
drha34b6762004-05-07 13:30:42 +00003319** sqlite3pager_unref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00003320**
3321** SQLITE_OK is returned on success. Any other return value indicates
3322** an error. *ppPage and *pPgno are undefined in the event of an error.
drha34b6762004-05-07 13:30:42 +00003323** Do not invoke sqlite3pager_unref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00003324**
drh199e3cf2002-07-18 11:01:47 +00003325** If the "nearby" parameter is not 0, then a (feeble) effort is made to
3326** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00003327** attempt to keep related pages close to each other in the database file,
3328** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00003329**
3330** If the "exact" parameter is not 0, and the page-number nearby exists
3331** anywhere on the free-list, then it is guarenteed to be returned. This
3332** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00003333*/
danielk1977cb1a7eb2004-11-05 12:27:02 +00003334static int allocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00003335 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00003336 MemPage **ppPage,
3337 Pgno *pPgno,
3338 Pgno nearby,
3339 u8 exact
3340){
drh3aac2dd2004-04-26 14:10:20 +00003341 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00003342 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003343 int n; /* Number of pages on the freelist */
3344 int k; /* Number of leaves on the trunk of the freelist */
drh30e58752002-03-02 20:41:57 +00003345
drh3aac2dd2004-04-26 14:10:20 +00003346 pPage1 = pBt->pPage1;
3347 n = get4byte(&pPage1->aData[36]);
3348 if( n>0 ){
drh91025292004-05-03 19:49:32 +00003349 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00003350 MemPage *pTrunk = 0;
3351 Pgno iTrunk;
3352 MemPage *pPrevTrunk = 0;
3353 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
3354
3355 /* If the 'exact' parameter was true and a query of the pointer-map
3356 ** shows that the page 'nearby' is somewhere on the free-list, then
3357 ** the entire-list will be searched for that page.
3358 */
3359#ifndef SQLITE_OMIT_AUTOVACUUM
3360 if( exact ){
3361 u8 eType;
3362 assert( nearby>0 );
3363 assert( pBt->autoVacuum );
3364 rc = ptrmapGet(pBt, nearby, &eType, 0);
3365 if( rc ) return rc;
3366 if( eType==PTRMAP_FREEPAGE ){
3367 searchList = 1;
3368 }
3369 *pPgno = nearby;
3370 }
3371#endif
3372
3373 /* Decrement the free-list count by 1. Set iTrunk to the index of the
3374 ** first free-list trunk page. iPrevTrunk is initially 1.
3375 */
drha34b6762004-05-07 13:30:42 +00003376 rc = sqlite3pager_write(pPage1->aData);
drh3b7511c2001-05-26 13:15:44 +00003377 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003378 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003379
3380 /* The code within this loop is run only once if the 'searchList' variable
3381 ** is not true. Otherwise, it runs once for each trunk-page on the
3382 ** free-list until the page 'nearby' is located.
3383 */
3384 do {
3385 pPrevTrunk = pTrunk;
3386 if( pPrevTrunk ){
3387 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00003388 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00003389 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00003390 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003391 rc = getPage(pBt, iTrunk, &pTrunk);
3392 if( rc ){
3393 releasePage(pPrevTrunk);
3394 return rc;
3395 }
3396
3397 /* TODO: This should move to after the loop? */
3398 rc = sqlite3pager_write(pTrunk->aData);
3399 if( rc ){
3400 releasePage(pTrunk);
3401 releasePage(pPrevTrunk);
3402 return rc;
3403 }
3404
3405 k = get4byte(&pTrunk->aData[4]);
3406 if( k==0 && !searchList ){
3407 /* The trunk has no leaves and the list is not being searched.
3408 ** So extract the trunk page itself and use it as the newly
3409 ** allocated page */
3410 assert( pPrevTrunk==0 );
3411 *pPgno = iTrunk;
3412 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3413 *ppPage = pTrunk;
3414 pTrunk = 0;
3415 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3416 }else if( k>pBt->usableSize/4 - 8 ){
3417 /* Value of k is out of range. Database corruption */
drh49285702005-09-17 15:20:26 +00003418 return SQLITE_CORRUPT_BKPT;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003419#ifndef SQLITE_OMIT_AUTOVACUUM
3420 }else if( searchList && nearby==iTrunk ){
3421 /* The list is being searched and this trunk page is the page
3422 ** to allocate, regardless of whether it has leaves.
3423 */
3424 assert( *pPgno==iTrunk );
3425 *ppPage = pTrunk;
3426 searchList = 0;
3427 if( k==0 ){
3428 if( !pPrevTrunk ){
3429 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3430 }else{
3431 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
3432 }
3433 }else{
3434 /* The trunk page is required by the caller but it contains
3435 ** pointers to free-list leaves. The first leaf becomes a trunk
3436 ** page in this case.
3437 */
3438 MemPage *pNewTrunk;
3439 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
3440 rc = getPage(pBt, iNewTrunk, &pNewTrunk);
3441 if( rc!=SQLITE_OK ){
3442 releasePage(pTrunk);
3443 releasePage(pPrevTrunk);
3444 return rc;
3445 }
3446 rc = sqlite3pager_write(pNewTrunk->aData);
3447 if( rc!=SQLITE_OK ){
3448 releasePage(pNewTrunk);
3449 releasePage(pTrunk);
3450 releasePage(pPrevTrunk);
3451 return rc;
3452 }
3453 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
3454 put4byte(&pNewTrunk->aData[4], k-1);
3455 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
3456 if( !pPrevTrunk ){
3457 put4byte(&pPage1->aData[32], iNewTrunk);
3458 }else{
3459 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
3460 }
3461 releasePage(pNewTrunk);
3462 }
3463 pTrunk = 0;
3464 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3465#endif
3466 }else{
3467 /* Extract a leaf from the trunk */
3468 int closest;
3469 Pgno iPage;
3470 unsigned char *aData = pTrunk->aData;
3471 if( nearby>0 ){
3472 int i, dist;
3473 closest = 0;
3474 dist = get4byte(&aData[8]) - nearby;
3475 if( dist<0 ) dist = -dist;
3476 for(i=1; i<k; i++){
3477 int d2 = get4byte(&aData[8+i*4]) - nearby;
3478 if( d2<0 ) d2 = -d2;
3479 if( d2<dist ){
3480 closest = i;
3481 dist = d2;
3482 }
3483 }
3484 }else{
3485 closest = 0;
3486 }
3487
3488 iPage = get4byte(&aData[8+closest*4]);
3489 if( !searchList || iPage==nearby ){
3490 *pPgno = iPage;
3491 if( *pPgno>sqlite3pager_pagecount(pBt->pPager) ){
3492 /* Free page off the end of the file */
drh49285702005-09-17 15:20:26 +00003493 return SQLITE_CORRUPT_BKPT;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003494 }
3495 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
3496 ": %d more free pages\n",
3497 *pPgno, closest+1, k, pTrunk->pgno, n-1));
3498 if( closest<k-1 ){
3499 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
3500 }
3501 put4byte(&aData[4], k-1);
3502 rc = getPage(pBt, *pPgno, ppPage);
3503 if( rc==SQLITE_OK ){
3504 sqlite3pager_dont_rollback((*ppPage)->aData);
3505 rc = sqlite3pager_write((*ppPage)->aData);
danielk1977aac0a382005-01-16 11:07:06 +00003506 if( rc!=SQLITE_OK ){
3507 releasePage(*ppPage);
3508 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003509 }
3510 searchList = 0;
3511 }
drhee696e22004-08-30 16:52:17 +00003512 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003513 releasePage(pPrevTrunk);
3514 }while( searchList );
3515 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003516 }else{
drh3aac2dd2004-04-26 14:10:20 +00003517 /* There are no pages on the freelist, so create a new page at the
3518 ** end of the file */
drha34b6762004-05-07 13:30:42 +00003519 *pPgno = sqlite3pager_pagecount(pBt->pPager) + 1;
danielk1977afcdd022004-10-31 16:25:42 +00003520
3521#ifndef SQLITE_OMIT_AUTOVACUUM
drh42cac6d2004-11-20 20:31:11 +00003522 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt->usableSize, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00003523 /* If *pPgno refers to a pointer-map page, allocate two new pages
3524 ** at the end of the file instead of one. The first allocated page
3525 ** becomes a new pointer-map page, the second is used by the caller.
3526 */
3527 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00003528 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977afcdd022004-10-31 16:25:42 +00003529 (*pPgno)++;
3530 }
3531#endif
3532
danielk1977599fcba2004-11-08 07:13:13 +00003533 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00003534 rc = getPage(pBt, *pPgno, ppPage);
drh3b7511c2001-05-26 13:15:44 +00003535 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003536 rc = sqlite3pager_write((*ppPage)->aData);
danielk1977aac0a382005-01-16 11:07:06 +00003537 if( rc!=SQLITE_OK ){
3538 releasePage(*ppPage);
3539 }
drh3a4c1412004-05-09 20:40:11 +00003540 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00003541 }
danielk1977599fcba2004-11-08 07:13:13 +00003542
3543 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh3b7511c2001-05-26 13:15:44 +00003544 return rc;
3545}
3546
3547/*
drh3aac2dd2004-04-26 14:10:20 +00003548** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00003549**
drha34b6762004-05-07 13:30:42 +00003550** sqlite3pager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00003551*/
drh3aac2dd2004-04-26 14:10:20 +00003552static int freePage(MemPage *pPage){
danielk1977aef0bf62005-12-30 16:28:01 +00003553 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00003554 MemPage *pPage1 = pBt->pPage1;
3555 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00003556
drh3aac2dd2004-04-26 14:10:20 +00003557 /* Prepare the page for freeing */
3558 assert( pPage->pgno>1 );
3559 pPage->isInit = 0;
3560 releasePage(pPage->pParent);
3561 pPage->pParent = 0;
3562
drha34b6762004-05-07 13:30:42 +00003563 /* Increment the free page count on pPage1 */
3564 rc = sqlite3pager_write(pPage1->aData);
drh3aac2dd2004-04-26 14:10:20 +00003565 if( rc ) return rc;
3566 n = get4byte(&pPage1->aData[36]);
3567 put4byte(&pPage1->aData[36], n+1);
3568
danielk1977687566d2004-11-02 12:56:41 +00003569#ifndef SQLITE_OMIT_AUTOVACUUM
3570 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00003571 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00003572 */
3573 if( pBt->autoVacuum ){
3574 rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
danielk1977a64a0352004-11-05 01:45:13 +00003575 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00003576 }
3577#endif
3578
drh3aac2dd2004-04-26 14:10:20 +00003579 if( n==0 ){
3580 /* This is the first free page */
drhda200cc2004-05-09 11:51:38 +00003581 rc = sqlite3pager_write(pPage->aData);
3582 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003583 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00003584 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003585 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003586 }else{
3587 /* Other free pages already exist. Retrive the first trunk page
3588 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00003589 MemPage *pTrunk;
3590 rc = getPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003591 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003592 k = get4byte(&pTrunk->aData[4]);
drhee696e22004-08-30 16:52:17 +00003593 if( k>=pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00003594 /* The trunk is full. Turn the page being freed into a new
3595 ** trunk page with no leaves. */
drha34b6762004-05-07 13:30:42 +00003596 rc = sqlite3pager_write(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00003597 if( rc ) return rc;
3598 put4byte(pPage->aData, pTrunk->pgno);
3599 put4byte(&pPage->aData[4], 0);
3600 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003601 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
3602 pPage->pgno, pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003603 }else{
3604 /* Add the newly freed page as a leaf on the current trunk */
drha34b6762004-05-07 13:30:42 +00003605 rc = sqlite3pager_write(pTrunk->aData);
drh3aac2dd2004-04-26 14:10:20 +00003606 if( rc ) return rc;
3607 put4byte(&pTrunk->aData[4], k+1);
3608 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drha34b6762004-05-07 13:30:42 +00003609 sqlite3pager_dont_write(pBt->pPager, pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003610 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003611 }
3612 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003613 }
drh3b7511c2001-05-26 13:15:44 +00003614 return rc;
3615}
3616
3617/*
drh3aac2dd2004-04-26 14:10:20 +00003618** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00003619*/
drh3aac2dd2004-04-26 14:10:20 +00003620static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00003621 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00003622 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00003623 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00003624 int rc;
drh3b7511c2001-05-26 13:15:44 +00003625
drh43605152004-05-29 21:46:49 +00003626 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003627 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00003628 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00003629 }
drh6f11bef2004-05-13 01:12:56 +00003630 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh3aac2dd2004-04-26 14:10:20 +00003631 while( ovflPgno!=0 ){
3632 MemPage *pOvfl;
danielk1977a1cb1832005-02-12 08:59:55 +00003633 if( ovflPgno>sqlite3pager_pagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00003634 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00003635 }
drh3aac2dd2004-04-26 14:10:20 +00003636 rc = getPage(pBt, ovflPgno, &pOvfl);
drh3b7511c2001-05-26 13:15:44 +00003637 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003638 ovflPgno = get4byte(pOvfl->aData);
drha34b6762004-05-07 13:30:42 +00003639 rc = freePage(pOvfl);
drha34b6762004-05-07 13:30:42 +00003640 sqlite3pager_unref(pOvfl->aData);
danielk19776b456a22005-03-21 04:04:02 +00003641 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00003642 }
drh5e2f8b92001-05-28 00:41:15 +00003643 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00003644}
3645
3646/*
drh91025292004-05-03 19:49:32 +00003647** Create the byte sequence used to represent a cell on page pPage
3648** and write that byte sequence into pCell[]. Overflow pages are
3649** allocated and filled in as necessary. The calling procedure
3650** is responsible for making sure sufficient space has been allocated
3651** for pCell[].
3652**
3653** Note that pCell does not necessary need to point to the pPage->aData
3654** area. pCell might point to some temporary storage. The cell will
3655** be constructed in this temporary area then copied into pPage->aData
3656** later.
drh3b7511c2001-05-26 13:15:44 +00003657*/
3658static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00003659 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00003660 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00003661 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00003662 const void *pData,int nData, /* The data */
3663 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00003664){
drh3b7511c2001-05-26 13:15:44 +00003665 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00003666 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00003667 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00003668 int spaceLeft;
3669 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00003670 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00003671 unsigned char *pPrior;
3672 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00003673 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00003674 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00003675 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00003676 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00003677
drh91025292004-05-03 19:49:32 +00003678 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00003679 nHeader = 0;
drh91025292004-05-03 19:49:32 +00003680 if( !pPage->leaf ){
3681 nHeader += 4;
3682 }
drh8b18dd42004-05-12 19:18:15 +00003683 if( pPage->hasData ){
drh91025292004-05-03 19:49:32 +00003684 nHeader += putVarint(&pCell[nHeader], nData);
drh6f11bef2004-05-13 01:12:56 +00003685 }else{
drh91025292004-05-03 19:49:32 +00003686 nData = 0;
3687 }
drh6f11bef2004-05-13 01:12:56 +00003688 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh43605152004-05-29 21:46:49 +00003689 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003690 assert( info.nHeader==nHeader );
3691 assert( info.nKey==nKey );
3692 assert( info.nData==nData );
3693
3694 /* Fill in the payload */
drh3aac2dd2004-04-26 14:10:20 +00003695 nPayload = nData;
3696 if( pPage->intKey ){
3697 pSrc = pData;
3698 nSrc = nData;
drh91025292004-05-03 19:49:32 +00003699 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00003700 }else{
3701 nPayload += nKey;
3702 pSrc = pKey;
3703 nSrc = nKey;
3704 }
drh6f11bef2004-05-13 01:12:56 +00003705 *pnSize = info.nSize;
3706 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00003707 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00003708 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00003709
drh3b7511c2001-05-26 13:15:44 +00003710 while( nPayload>0 ){
3711 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00003712#ifndef SQLITE_OMIT_AUTOVACUUM
3713 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
3714#endif
danielk1977cb1a7eb2004-11-05 12:27:02 +00003715 rc = allocatePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00003716#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00003717 /* If the database supports auto-vacuum, and the second or subsequent
3718 ** overflow page is being allocated, add an entry to the pointer-map
3719 ** for that page now. The entry for the first overflow page will be
3720 ** added later, by the insertCell() routine.
danielk1977afcdd022004-10-31 16:25:42 +00003721 */
danielk1977a19df672004-11-03 11:37:07 +00003722 if( pBt->autoVacuum && pgnoPtrmap!=0 && rc==SQLITE_OK ){
3723 rc = ptrmapPut(pBt, pgnoOvfl, PTRMAP_OVERFLOW2, pgnoPtrmap);
danielk1977afcdd022004-10-31 16:25:42 +00003724 }
3725#endif
drh3b7511c2001-05-26 13:15:44 +00003726 if( rc ){
drh9b171272004-05-08 02:03:22 +00003727 releasePage(pToRelease);
danielk197728129562005-01-11 10:25:06 +00003728 /* clearCell(pPage, pCell); */
drh3b7511c2001-05-26 13:15:44 +00003729 return rc;
3730 }
drh3aac2dd2004-04-26 14:10:20 +00003731 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00003732 releasePage(pToRelease);
3733 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00003734 pPrior = pOvfl->aData;
3735 put4byte(pPrior, 0);
3736 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00003737 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00003738 }
3739 n = nPayload;
3740 if( n>spaceLeft ) n = spaceLeft;
drh3aac2dd2004-04-26 14:10:20 +00003741 if( n>nSrc ) n = nSrc;
3742 memcpy(pPayload, pSrc, n);
drh3b7511c2001-05-26 13:15:44 +00003743 nPayload -= n;
drhde647132004-05-07 17:57:49 +00003744 pPayload += n;
drh9b171272004-05-08 02:03:22 +00003745 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00003746 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00003747 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00003748 if( nSrc==0 ){
3749 nSrc = nData;
3750 pSrc = pData;
3751 }
drhdd793422001-06-28 01:54:48 +00003752 }
drh9b171272004-05-08 02:03:22 +00003753 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00003754 return SQLITE_OK;
3755}
3756
3757/*
drhbd03cae2001-06-02 02:40:57 +00003758** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00003759** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00003760** pointer in the third argument.
3761*/
danielk1977aef0bf62005-12-30 16:28:01 +00003762static int reparentPage(BtShared *pBt, Pgno pgno, MemPage *pNewParent, int idx){
drhbd03cae2001-06-02 02:40:57 +00003763 MemPage *pThis;
drh4b70f112004-05-02 21:12:19 +00003764 unsigned char *aData;
drhbd03cae2001-06-02 02:40:57 +00003765
danielk1977afcdd022004-10-31 16:25:42 +00003766 if( pgno==0 ) return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00003767 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00003768 aData = sqlite3pager_lookup(pBt->pPager, pgno);
drhda200cc2004-05-09 11:51:38 +00003769 if( aData ){
drh07d183d2005-05-01 22:52:42 +00003770 pThis = (MemPage*)&aData[pBt->pageSize];
drh31276532004-09-27 12:20:52 +00003771 assert( pThis->aData==aData );
drhda200cc2004-05-09 11:51:38 +00003772 if( pThis->isInit ){
3773 if( pThis->pParent!=pNewParent ){
3774 if( pThis->pParent ) sqlite3pager_unref(pThis->pParent->aData);
3775 pThis->pParent = pNewParent;
3776 if( pNewParent ) sqlite3pager_ref(pNewParent->aData);
3777 }
3778 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00003779 }
drha34b6762004-05-07 13:30:42 +00003780 sqlite3pager_unref(aData);
drhbd03cae2001-06-02 02:40:57 +00003781 }
danielk1977afcdd022004-10-31 16:25:42 +00003782
3783#ifndef SQLITE_OMIT_AUTOVACUUM
3784 if( pBt->autoVacuum ){
3785 return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
3786 }
3787#endif
3788 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00003789}
3790
danielk1977ac11ee62005-01-15 12:45:51 +00003791
3792
drhbd03cae2001-06-02 02:40:57 +00003793/*
drh4b70f112004-05-02 21:12:19 +00003794** Change the pParent pointer of all children of pPage to point back
3795** to pPage.
3796**
drhbd03cae2001-06-02 02:40:57 +00003797** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00003798** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00003799**
3800** This routine gets called after you memcpy() one page into
3801** another.
3802*/
danielk1977afcdd022004-10-31 16:25:42 +00003803static int reparentChildPages(MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00003804 int i;
danielk1977aef0bf62005-12-30 16:28:01 +00003805 BtShared *pBt = pPage->pBt;
danielk1977afcdd022004-10-31 16:25:42 +00003806 int rc = SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00003807
danielk1977afcdd022004-10-31 16:25:42 +00003808 if( pPage->leaf ) return SQLITE_OK;
danielk1977afcdd022004-10-31 16:25:42 +00003809
drhbd03cae2001-06-02 02:40:57 +00003810 for(i=0; i<pPage->nCell; i++){
danielk1977afcdd022004-10-31 16:25:42 +00003811 u8 *pCell = findCell(pPage, i);
3812 if( !pPage->leaf ){
3813 rc = reparentPage(pBt, get4byte(pCell), pPage, i);
3814 if( rc!=SQLITE_OK ) return rc;
3815 }
drhbd03cae2001-06-02 02:40:57 +00003816 }
danielk1977afcdd022004-10-31 16:25:42 +00003817 if( !pPage->leaf ){
3818 rc = reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]),
3819 pPage, i);
3820 pPage->idxShift = 0;
3821 }
3822 return rc;
drh14acc042001-06-10 19:56:58 +00003823}
3824
3825/*
3826** Remove the i-th cell from pPage. This routine effects pPage only.
3827** The cell content is not freed or deallocated. It is assumed that
3828** the cell content has been copied someplace else. This routine just
3829** removes the reference to the cell from pPage.
3830**
3831** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00003832*/
drh4b70f112004-05-02 21:12:19 +00003833static void dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00003834 int i; /* Loop counter */
3835 int pc; /* Offset to cell content of cell being deleted */
3836 u8 *data; /* pPage->aData */
3837 u8 *ptr; /* Used to move bytes around within data[] */
3838
drh8c42ca92001-06-22 19:15:00 +00003839 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00003840 assert( sz==cellSize(pPage, idx) );
drha34b6762004-05-07 13:30:42 +00003841 assert( sqlite3pager_iswriteable(pPage->aData) );
drhda200cc2004-05-09 11:51:38 +00003842 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00003843 ptr = &data[pPage->cellOffset + 2*idx];
3844 pc = get2byte(ptr);
3845 assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
drhde647132004-05-07 17:57:49 +00003846 freeSpace(pPage, pc, sz);
drh43605152004-05-29 21:46:49 +00003847 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
3848 ptr[0] = ptr[2];
3849 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00003850 }
3851 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00003852 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
3853 pPage->nFree += 2;
drh428ae8c2003-01-04 16:48:09 +00003854 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00003855}
3856
3857/*
3858** Insert a new cell on pPage at cell index "i". pCell points to the
3859** content of the cell.
3860**
3861** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00003862** will not fit, then make a copy of the cell content into pTemp if
3863** pTemp is not null. Regardless of pTemp, allocate a new entry
3864** in pPage->aOvfl[] and make it point to the cell content (either
3865** in pTemp or the original pCell) and also record its index.
3866** Allocating a new entry in pPage->aCell[] implies that
3867** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00003868**
3869** If nSkip is non-zero, then do not copy the first nSkip bytes of the
3870** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00003871** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00003872** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00003873*/
danielk1977e80463b2004-11-03 03:01:16 +00003874static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00003875 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00003876 int i, /* New cell becomes the i-th cell of the page */
3877 u8 *pCell, /* Content of the new cell */
3878 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00003879 u8 *pTemp, /* Temp storage space for pCell, if needed */
3880 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00003881){
drh43605152004-05-29 21:46:49 +00003882 int idx; /* Where to write new cell content in data[] */
3883 int j; /* Loop counter */
3884 int top; /* First byte of content for any cell in data[] */
3885 int end; /* First byte past the last cell pointer in data[] */
3886 int ins; /* Index in data[] where new cell pointer is inserted */
3887 int hdr; /* Offset into data[] of the page header */
3888 int cellOffset; /* Address of first cell pointer in data[] */
3889 u8 *data; /* The content of the whole page */
3890 u8 *ptr; /* Used for moving information around in data[] */
3891
3892 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
3893 assert( sz==cellSizePtr(pPage, pCell) );
drha34b6762004-05-07 13:30:42 +00003894 assert( sqlite3pager_iswriteable(pPage->aData) );
drh43605152004-05-29 21:46:49 +00003895 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00003896 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00003897 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00003898 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00003899 }
drh43605152004-05-29 21:46:49 +00003900 j = pPage->nOverflow++;
3901 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
3902 pPage->aOvfl[j].pCell = pCell;
3903 pPage->aOvfl[j].idx = i;
3904 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00003905 }else{
drh43605152004-05-29 21:46:49 +00003906 data = pPage->aData;
3907 hdr = pPage->hdrOffset;
3908 top = get2byte(&data[hdr+5]);
3909 cellOffset = pPage->cellOffset;
3910 end = cellOffset + 2*pPage->nCell + 2;
3911 ins = cellOffset + 2*i;
3912 if( end > top - sz ){
danielk19776b456a22005-03-21 04:04:02 +00003913 int rc = defragmentPage(pPage);
3914 if( rc!=SQLITE_OK ) return rc;
drh43605152004-05-29 21:46:49 +00003915 top = get2byte(&data[hdr+5]);
3916 assert( end + sz <= top );
3917 }
3918 idx = allocateSpace(pPage, sz);
3919 assert( idx>0 );
3920 assert( end <= get2byte(&data[hdr+5]) );
3921 pPage->nCell++;
3922 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00003923 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00003924 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
3925 ptr[0] = ptr[-2];
3926 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00003927 }
drh43605152004-05-29 21:46:49 +00003928 put2byte(&data[ins], idx);
3929 put2byte(&data[hdr+3], pPage->nCell);
3930 pPage->idxShift = 1;
drhda200cc2004-05-09 11:51:38 +00003931 pageIntegrity(pPage);
danielk1977a19df672004-11-03 11:37:07 +00003932#ifndef SQLITE_OMIT_AUTOVACUUM
3933 if( pPage->pBt->autoVacuum ){
3934 /* The cell may contain a pointer to an overflow page. If so, write
3935 ** the entry for the overflow page into the pointer map.
3936 */
3937 CellInfo info;
3938 parseCellPtr(pPage, pCell, &info);
3939 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
3940 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
3941 int rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
3942 if( rc!=SQLITE_OK ) return rc;
3943 }
3944 }
3945#endif
drh14acc042001-06-10 19:56:58 +00003946 }
danielk1977e80463b2004-11-03 03:01:16 +00003947
danielk1977e80463b2004-11-03 03:01:16 +00003948 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00003949}
3950
3951/*
drhfa1a98a2004-05-14 19:08:17 +00003952** Add a list of cells to a page. The page should be initially empty.
3953** The cells are guaranteed to fit on the page.
3954*/
3955static void assemblePage(
3956 MemPage *pPage, /* The page to be assemblied */
3957 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00003958 u8 **apCell, /* Pointers to cell bodies */
drhfa1a98a2004-05-14 19:08:17 +00003959 int *aSize /* Sizes of the cells */
3960){
3961 int i; /* Loop counter */
3962 int totalSize; /* Total size of all cells */
3963 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00003964 int cellptr; /* Address of next cell pointer */
3965 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00003966 u8 *data; /* Data for the page */
3967
drh43605152004-05-29 21:46:49 +00003968 assert( pPage->nOverflow==0 );
drhfa1a98a2004-05-14 19:08:17 +00003969 totalSize = 0;
3970 for(i=0; i<nCell; i++){
3971 totalSize += aSize[i];
3972 }
drh43605152004-05-29 21:46:49 +00003973 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00003974 assert( pPage->nCell==0 );
drh43605152004-05-29 21:46:49 +00003975 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00003976 data = pPage->aData;
3977 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00003978 put2byte(&data[hdr+3], nCell);
drh09d0deb2005-08-02 17:13:09 +00003979 if( nCell ){
3980 cellbody = allocateSpace(pPage, totalSize);
3981 assert( cellbody>0 );
3982 assert( pPage->nFree >= 2*nCell );
3983 pPage->nFree -= 2*nCell;
3984 for(i=0; i<nCell; i++){
3985 put2byte(&data[cellptr], cellbody);
3986 memcpy(&data[cellbody], apCell[i], aSize[i]);
3987 cellptr += 2;
3988 cellbody += aSize[i];
3989 }
3990 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00003991 }
3992 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00003993}
3994
drh14acc042001-06-10 19:56:58 +00003995/*
drhc3b70572003-01-04 19:44:07 +00003996** The following parameters determine how many adjacent pages get involved
3997** in a balancing operation. NN is the number of neighbors on either side
3998** of the page that participate in the balancing operation. NB is the
3999** total number of pages that participate, including the target page and
4000** NN neighbors on either side.
4001**
4002** The minimum value of NN is 1 (of course). Increasing NN above 1
4003** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
4004** in exchange for a larger degradation in INSERT and UPDATE performance.
4005** The value of NN appears to give the best results overall.
4006*/
4007#define NN 1 /* Number of neighbors on either side of pPage */
4008#define NB (NN*2+1) /* Total pages involved in the balance */
4009
drh43605152004-05-29 21:46:49 +00004010/* Forward reference */
danielk1977ac245ec2005-01-14 13:50:11 +00004011static int balance(MemPage*, int);
4012
drh615ae552005-01-16 23:21:00 +00004013#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004014/*
4015** This version of balance() handles the common special case where
4016** a new entry is being inserted on the extreme right-end of the
4017** tree, in other words, when the new entry will become the largest
4018** entry in the tree.
4019**
4020** Instead of trying balance the 3 right-most leaf pages, just add
4021** a new page to the right-hand side and put the one new entry in
4022** that page. This leaves the right side of the tree somewhat
4023** unbalanced. But odds are that we will be inserting new entries
4024** at the end soon afterwards so the nearly empty page will quickly
4025** fill up. On average.
4026**
4027** pPage is the leaf page which is the right-most page in the tree.
4028** pParent is its parent. pPage must have a single overflow entry
4029** which is also the right-most entry on the page.
4030*/
danielk1977ac245ec2005-01-14 13:50:11 +00004031static int balance_quick(MemPage *pPage, MemPage *pParent){
4032 int rc;
4033 MemPage *pNew;
4034 Pgno pgnoNew;
4035 u8 *pCell;
4036 int szCell;
4037 CellInfo info;
danielk1977aef0bf62005-12-30 16:28:01 +00004038 BtShared *pBt = pPage->pBt;
danielk197779a40da2005-01-16 08:00:01 +00004039 int parentIdx = pParent->nCell; /* pParent new divider cell index */
4040 int parentSize; /* Size of new divider cell */
4041 u8 parentCell[64]; /* Space for the new divider cell */
danielk1977ac245ec2005-01-14 13:50:11 +00004042
4043 /* Allocate a new page. Insert the overflow cell from pPage
4044 ** into it. Then remove the overflow cell from pPage.
4045 */
danielk1977ac11ee62005-01-15 12:45:51 +00004046 rc = allocatePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977ac245ec2005-01-14 13:50:11 +00004047 if( rc!=SQLITE_OK ){
4048 return rc;
4049 }
4050 pCell = pPage->aOvfl[0].pCell;
4051 szCell = cellSizePtr(pPage, pCell);
4052 zeroPage(pNew, pPage->aData[0]);
4053 assemblePage(pNew, 1, &pCell, &szCell);
4054 pPage->nOverflow = 0;
4055
danielk197779a40da2005-01-16 08:00:01 +00004056 /* Set the parent of the newly allocated page to pParent. */
4057 pNew->pParent = pParent;
4058 sqlite3pager_ref(pParent->aData);
4059
danielk1977ac245ec2005-01-14 13:50:11 +00004060 /* pPage is currently the right-child of pParent. Change this
4061 ** so that the right-child is the new page allocated above and
danielk197779a40da2005-01-16 08:00:01 +00004062 ** pPage is the next-to-right child.
danielk1977ac245ec2005-01-14 13:50:11 +00004063 */
danielk1977ac11ee62005-01-15 12:45:51 +00004064 assert( pPage->nCell>0 );
danielk1977ac245ec2005-01-14 13:50:11 +00004065 parseCellPtr(pPage, findCell(pPage, pPage->nCell-1), &info);
4066 rc = fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, &parentSize);
4067 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00004068 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004069 }
4070 assert( parentSize<64 );
4071 rc = insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
4072 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00004073 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004074 }
4075 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
4076 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
4077
danielk197779a40da2005-01-16 08:00:01 +00004078#ifndef SQLITE_OMIT_AUTOVACUUM
4079 /* If this is an auto-vacuum database, update the pointer map
4080 ** with entries for the new page, and any pointer from the
4081 ** cell on the page to an overflow page.
4082 */
danielk1977ac11ee62005-01-15 12:45:51 +00004083 if( pBt->autoVacuum ){
4084 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
4085 if( rc!=SQLITE_OK ){
4086 return rc;
4087 }
danielk197779a40da2005-01-16 08:00:01 +00004088 rc = ptrmapPutOvfl(pNew, 0);
4089 if( rc!=SQLITE_OK ){
4090 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00004091 }
4092 }
danielk197779a40da2005-01-16 08:00:01 +00004093#endif
danielk1977ac11ee62005-01-15 12:45:51 +00004094
danielk197779a40da2005-01-16 08:00:01 +00004095 /* Release the reference to the new page and balance the parent page,
4096 ** in case the divider cell inserted caused it to become overfull.
4097 */
danielk1977ac245ec2005-01-14 13:50:11 +00004098 releasePage(pNew);
4099 return balance(pParent, 0);
4100}
drh615ae552005-01-16 23:21:00 +00004101#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00004102
drhc3b70572003-01-04 19:44:07 +00004103/*
danielk1977ac11ee62005-01-15 12:45:51 +00004104** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
4105** if the database supports auto-vacuum or not. Because it is used
4106** within an expression that is an argument to another macro
4107** (sqliteMallocRaw), it is not possible to use conditional compilation.
4108** So, this macro is defined instead.
4109*/
4110#ifndef SQLITE_OMIT_AUTOVACUUM
4111#define ISAUTOVACUUM (pBt->autoVacuum)
4112#else
4113#define ISAUTOVACUUM 0
4114#endif
4115
4116/*
drhab01f612004-05-22 02:55:23 +00004117** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00004118** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00004119** Usually NN siblings on either side of pPage is used in the balancing,
4120** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00004121** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00004122** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00004123** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00004124**
drh0c6cc4e2004-06-15 02:13:26 +00004125** The number of siblings of pPage might be increased or decreased by one or
4126** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00004127** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00004128** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00004129** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00004130** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00004131**
drh8b2f49b2001-06-08 00:21:52 +00004132** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00004133** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00004134** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00004135** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00004136**
drh8c42ca92001-06-22 19:15:00 +00004137** In the course of balancing the siblings of pPage, the parent of pPage
4138** might become overfull or underfull. If that happens, then this routine
4139** is called recursively on the parent.
4140**
drh5e00f6c2001-09-13 13:46:56 +00004141** If this routine fails for any reason, it might leave the database
4142** in a corrupted state. So if this routine fails, the database should
4143** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00004144*/
drh43605152004-05-29 21:46:49 +00004145static int balance_nonroot(MemPage *pPage){
drh8b2f49b2001-06-08 00:21:52 +00004146 MemPage *pParent; /* The parent of pPage */
danielk1977aef0bf62005-12-30 16:28:01 +00004147 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00004148 int nCell = 0; /* Number of cells in apCell[] */
4149 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
drh8b2f49b2001-06-08 00:21:52 +00004150 int nOld; /* Number of pages in apOld[] */
4151 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00004152 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00004153 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00004154 int idx; /* Index of pPage in pParent->aCell[] */
4155 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00004156 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00004157 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00004158 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00004159 int usableSpace; /* Bytes in pPage beyond the header */
4160 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00004161 int subtotal; /* Subtotal of bytes in cells on one page */
drhb6f41482004-05-14 01:58:11 +00004162 int iSpace = 0; /* First unused byte of aSpace[] */
drhc3b70572003-01-04 19:44:07 +00004163 MemPage *apOld[NB]; /* pPage and up to two siblings */
4164 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00004165 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00004166 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
4167 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drh4b70f112004-05-02 21:12:19 +00004168 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00004169 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
4170 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00004171 u8 **apCell = 0; /* All cells begin balanced */
drh2e38c322004-09-03 18:38:44 +00004172 int *szCell; /* Local size of all cells in apCell[] */
4173 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
4174 u8 *aSpace; /* Space to hold copies of dividers cells */
danielk19774e17d142005-01-16 09:06:33 +00004175#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00004176 u8 *aFrom = 0;
4177#endif
drh8b2f49b2001-06-08 00:21:52 +00004178
drh14acc042001-06-10 19:56:58 +00004179 /*
drh43605152004-05-29 21:46:49 +00004180 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00004181 */
drh3a4c1412004-05-09 20:40:11 +00004182 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004183 assert( sqlite3pager_iswriteable(pPage->aData) );
drh4b70f112004-05-02 21:12:19 +00004184 pBt = pPage->pBt;
drh14acc042001-06-10 19:56:58 +00004185 pParent = pPage->pParent;
drh43605152004-05-29 21:46:49 +00004186 sqlite3pager_write(pParent->aData);
4187 assert( pParent );
4188 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00004189
drh615ae552005-01-16 23:21:00 +00004190#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004191 /*
4192 ** A special case: If a new entry has just been inserted into a
4193 ** table (that is, a btree with integer keys and all data at the leaves)
drh09d0deb2005-08-02 17:13:09 +00004194 ** and the new entry is the right-most entry in the tree (it has the
drhf222e712005-01-14 22:55:49 +00004195 ** largest key) then use the special balance_quick() routine for
4196 ** balancing. balance_quick() is much faster and results in a tighter
4197 ** packing of data in the common case.
4198 */
danielk1977ac245ec2005-01-14 13:50:11 +00004199 if( pPage->leaf &&
4200 pPage->intKey &&
4201 pPage->leafData &&
4202 pPage->nOverflow==1 &&
4203 pPage->aOvfl[0].idx==pPage->nCell &&
danielk1977ac11ee62005-01-15 12:45:51 +00004204 pPage->pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00004205 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
4206 ){
danielk1977ac11ee62005-01-15 12:45:51 +00004207 /*
4208 ** TODO: Check the siblings to the left of pPage. It may be that
4209 ** they are not full and no new page is required.
4210 */
danielk1977ac245ec2005-01-14 13:50:11 +00004211 return balance_quick(pPage, pParent);
4212 }
4213#endif
4214
drh2e38c322004-09-03 18:38:44 +00004215 /*
drh4b70f112004-05-02 21:12:19 +00004216 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00004217 ** to pPage. The "idx" variable is the index of that cell. If pPage
4218 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00004219 */
drhbb49aba2003-01-04 18:53:27 +00004220 if( pParent->idxShift ){
drha34b6762004-05-07 13:30:42 +00004221 Pgno pgno;
drh4b70f112004-05-02 21:12:19 +00004222 pgno = pPage->pgno;
drha34b6762004-05-07 13:30:42 +00004223 assert( pgno==sqlite3pager_pagenumber(pPage->aData) );
drhbb49aba2003-01-04 18:53:27 +00004224 for(idx=0; idx<pParent->nCell; idx++){
drh43605152004-05-29 21:46:49 +00004225 if( get4byte(findCell(pParent, idx))==pgno ){
drhbb49aba2003-01-04 18:53:27 +00004226 break;
4227 }
drh8b2f49b2001-06-08 00:21:52 +00004228 }
drh4b70f112004-05-02 21:12:19 +00004229 assert( idx<pParent->nCell
drh43605152004-05-29 21:46:49 +00004230 || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
drhbb49aba2003-01-04 18:53:27 +00004231 }else{
4232 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00004233 }
drh8b2f49b2001-06-08 00:21:52 +00004234
4235 /*
drh14acc042001-06-10 19:56:58 +00004236 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00004237 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00004238 */
drh14acc042001-06-10 19:56:58 +00004239 nOld = nNew = 0;
drha34b6762004-05-07 13:30:42 +00004240 sqlite3pager_ref(pParent->aData);
drh14acc042001-06-10 19:56:58 +00004241
4242 /*
drh4b70f112004-05-02 21:12:19 +00004243 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00004244 ** the siblings. An attempt is made to find NN siblings on either
4245 ** side of pPage. More siblings are taken from one side, however, if
4246 ** pPage there are fewer than NN siblings on the other side. If pParent
4247 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00004248 */
drhc3b70572003-01-04 19:44:07 +00004249 nxDiv = idx - NN;
4250 if( nxDiv + NB > pParent->nCell ){
4251 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00004252 }
drhc3b70572003-01-04 19:44:07 +00004253 if( nxDiv<0 ){
4254 nxDiv = 0;
4255 }
drh8b2f49b2001-06-08 00:21:52 +00004256 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00004257 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00004258 if( k<pParent->nCell ){
drh43605152004-05-29 21:46:49 +00004259 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00004260 nDiv++;
drha34b6762004-05-07 13:30:42 +00004261 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00004262 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00004263 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00004264 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00004265 }else{
4266 break;
drh8b2f49b2001-06-08 00:21:52 +00004267 }
drhde647132004-05-07 17:57:49 +00004268 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00004269 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00004270 apOld[i]->idxParent = k;
drh91025292004-05-03 19:49:32 +00004271 apCopy[i] = 0;
4272 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00004273 nOld++;
danielk1977634f2982005-03-28 08:44:07 +00004274 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
drh8b2f49b2001-06-08 00:21:52 +00004275 }
4276
drh8d97f1f2005-05-05 18:14:13 +00004277 /* Make nMaxCells a multiple of 2 in order to preserve 8-byte
4278 ** alignment */
4279 nMaxCells = (nMaxCells + 1)&~1;
4280
drh8b2f49b2001-06-08 00:21:52 +00004281 /*
danielk1977634f2982005-03-28 08:44:07 +00004282 ** Allocate space for memory structures
4283 */
4284 apCell = sqliteMallocRaw(
4285 nMaxCells*sizeof(u8*) /* apCell */
4286 + nMaxCells*sizeof(int) /* szCell */
drhc96d8532005-05-03 12:30:33 +00004287 + ROUND8(sizeof(MemPage))*NB /* aCopy */
drh07d183d2005-05-01 22:52:42 +00004288 + pBt->pageSize*(5+NB) /* aSpace */
drhc96d8532005-05-03 12:30:33 +00004289 + (ISAUTOVACUUM ? nMaxCells : 0) /* aFrom */
danielk1977634f2982005-03-28 08:44:07 +00004290 );
4291 if( apCell==0 ){
4292 rc = SQLITE_NOMEM;
4293 goto balance_cleanup;
4294 }
4295 szCell = (int*)&apCell[nMaxCells];
4296 aCopy[0] = (u8*)&szCell[nMaxCells];
drhc96d8532005-05-03 12:30:33 +00004297 assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004298 for(i=1; i<NB; i++){
drhc96d8532005-05-03 12:30:33 +00004299 aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
4300 assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004301 }
drhc96d8532005-05-03 12:30:33 +00004302 aSpace = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
4303 assert( ((aSpace - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004304#ifndef SQLITE_OMIT_AUTOVACUUM
4305 if( pBt->autoVacuum ){
drh07d183d2005-05-01 22:52:42 +00004306 aFrom = &aSpace[5*pBt->pageSize];
danielk1977634f2982005-03-28 08:44:07 +00004307 }
4308#endif
4309
4310 /*
drh14acc042001-06-10 19:56:58 +00004311 ** Make copies of the content of pPage and its siblings into aOld[].
4312 ** The rest of this function will use data from the copies rather
4313 ** that the original pages since the original pages will be in the
4314 ** process of being overwritten.
4315 */
4316 for(i=0; i<nOld; i++){
drh07d183d2005-05-01 22:52:42 +00004317 MemPage *p = apCopy[i] = (MemPage*)&aCopy[i][pBt->pageSize];
drh07d183d2005-05-01 22:52:42 +00004318 p->aData = &((u8*)p)[-pBt->pageSize];
4319 memcpy(p->aData, apOld[i]->aData, pBt->pageSize + sizeof(MemPage));
4320 /* The memcpy() above changes the value of p->aData so we have to
4321 ** set it again. */
drh07d183d2005-05-01 22:52:42 +00004322 p->aData = &((u8*)p)[-pBt->pageSize];
drh14acc042001-06-10 19:56:58 +00004323 }
4324
4325 /*
4326 ** Load pointers to all cells on sibling pages and the divider cells
4327 ** into the local apCell[] array. Make copies of the divider cells
drhb6f41482004-05-14 01:58:11 +00004328 ** into space obtained form aSpace[] and remove the the divider Cells
4329 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00004330 **
4331 ** If the siblings are on leaf pages, then the child pointers of the
4332 ** divider cells are stripped from the cells before they are copied
drh96f5b762004-05-16 16:24:36 +00004333 ** into aSpace[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00004334 ** child pointers. If siblings are not leaves, then all cell in
4335 ** apCell[] include child pointers. Either way, all cells in apCell[]
4336 ** are alike.
drh96f5b762004-05-16 16:24:36 +00004337 **
4338 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
4339 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00004340 */
4341 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00004342 leafCorrection = pPage->leaf*4;
drh8b18dd42004-05-12 19:18:15 +00004343 leafData = pPage->leafData && pPage->leaf;
drh8b2f49b2001-06-08 00:21:52 +00004344 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00004345 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00004346 int limit = pOld->nCell+pOld->nOverflow;
4347 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00004348 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00004349 apCell[nCell] = findOverflowCell(pOld, j);
4350 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk1977ac11ee62005-01-15 12:45:51 +00004351#ifndef SQLITE_OMIT_AUTOVACUUM
4352 if( pBt->autoVacuum ){
4353 int a;
4354 aFrom[nCell] = i;
4355 for(a=0; a<pOld->nOverflow; a++){
4356 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
4357 aFrom[nCell] = 0xFF;
4358 break;
4359 }
4360 }
4361 }
4362#endif
drh14acc042001-06-10 19:56:58 +00004363 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00004364 }
4365 if( i<nOld-1 ){
drh43605152004-05-29 21:46:49 +00004366 int sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00004367 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00004368 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
4369 ** are duplicates of keys on the child pages. We need to remove
4370 ** the divider cells from pParent, but the dividers cells are not
4371 ** added to apCell[] because they are duplicates of child cells.
4372 */
drh8b18dd42004-05-12 19:18:15 +00004373 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00004374 }else{
drhb6f41482004-05-14 01:58:11 +00004375 u8 *pTemp;
danielk1977634f2982005-03-28 08:44:07 +00004376 assert( nCell<nMaxCells );
drhb6f41482004-05-14 01:58:11 +00004377 szCell[nCell] = sz;
4378 pTemp = &aSpace[iSpace];
4379 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004380 assert( iSpace<=pBt->pageSize*5 );
drhb6f41482004-05-14 01:58:11 +00004381 memcpy(pTemp, apDiv[i], sz);
4382 apCell[nCell] = pTemp+leafCorrection;
danielk1977ac11ee62005-01-15 12:45:51 +00004383#ifndef SQLITE_OMIT_AUTOVACUUM
4384 if( pBt->autoVacuum ){
4385 aFrom[nCell] = 0xFF;
4386 }
4387#endif
drhb6f41482004-05-14 01:58:11 +00004388 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00004389 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00004390 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00004391 if( !pOld->leaf ){
4392 assert( leafCorrection==0 );
4393 /* The right pointer of the child page pOld becomes the left
4394 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00004395 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00004396 }else{
4397 assert( leafCorrection==4 );
4398 }
4399 nCell++;
drh4b70f112004-05-02 21:12:19 +00004400 }
drh8b2f49b2001-06-08 00:21:52 +00004401 }
4402 }
4403
4404 /*
drh6019e162001-07-02 17:51:45 +00004405 ** Figure out the number of pages needed to hold all nCell cells.
4406 ** Store this number in "k". Also compute szNew[] which is the total
4407 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00004408 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00004409 ** cntNew[k] should equal nCell.
4410 **
drh96f5b762004-05-16 16:24:36 +00004411 ** Values computed by this block:
4412 **
4413 ** k: The total number of sibling pages
4414 ** szNew[i]: Spaced used on the i-th sibling page.
4415 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
4416 ** the right of the i-th sibling page.
4417 ** usableSpace: Number of bytes of space available on each sibling.
4418 **
drh8b2f49b2001-06-08 00:21:52 +00004419 */
drh43605152004-05-29 21:46:49 +00004420 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00004421 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00004422 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00004423 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00004424 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00004425 szNew[k] = subtotal - szCell[i];
4426 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00004427 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00004428 subtotal = 0;
4429 k++;
4430 }
4431 }
4432 szNew[k] = subtotal;
4433 cntNew[k] = nCell;
4434 k++;
drh96f5b762004-05-16 16:24:36 +00004435
4436 /*
4437 ** The packing computed by the previous block is biased toward the siblings
4438 ** on the left side. The left siblings are always nearly full, while the
4439 ** right-most sibling might be nearly empty. This block of code attempts
4440 ** to adjust the packing of siblings to get a better balance.
4441 **
4442 ** This adjustment is more than an optimization. The packing above might
4443 ** be so out of balance as to be illegal. For example, the right-most
4444 ** sibling might be completely empty. This adjustment is not optional.
4445 */
drh6019e162001-07-02 17:51:45 +00004446 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00004447 int szRight = szNew[i]; /* Size of sibling on the right */
4448 int szLeft = szNew[i-1]; /* Size of sibling on the left */
4449 int r; /* Index of right-most cell in left sibling */
4450 int d; /* Index of first cell to the left of right sibling */
4451
4452 r = cntNew[i-1] - 1;
4453 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00004454 assert( d<nMaxCells );
4455 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00004456 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
4457 szRight += szCell[d] + 2;
4458 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00004459 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00004460 r = cntNew[i-1] - 1;
4461 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00004462 }
drh96f5b762004-05-16 16:24:36 +00004463 szNew[i] = szRight;
4464 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00004465 }
drh09d0deb2005-08-02 17:13:09 +00004466
4467 /* Either we found one or more cells (cntnew[0])>0) or we are the
4468 ** a virtual root page. A virtual root page is when the real root
4469 ** page is page 1 and we are the only child of that page.
4470 */
4471 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00004472
4473 /*
drh6b308672002-07-08 02:16:37 +00004474 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00004475 */
drh4b70f112004-05-02 21:12:19 +00004476 assert( pPage->pgno>1 );
4477 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00004478 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00004479 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00004480 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00004481 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00004482 pgnoNew[i] = pgnoOld[i];
4483 apOld[i] = 0;
danielk197728129562005-01-11 10:25:06 +00004484 rc = sqlite3pager_write(pNew->aData);
4485 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00004486 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004487 rc = allocatePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00004488 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00004489 apNew[i] = pNew;
drh6b308672002-07-08 02:16:37 +00004490 }
drh14acc042001-06-10 19:56:58 +00004491 nNew++;
drhda200cc2004-05-09 11:51:38 +00004492 zeroPage(pNew, pageFlags);
drh8b2f49b2001-06-08 00:21:52 +00004493 }
4494
danielk1977299b1872004-11-22 10:02:10 +00004495 /* Free any old pages that were not reused as new pages.
4496 */
4497 while( i<nOld ){
4498 rc = freePage(apOld[i]);
4499 if( rc ) goto balance_cleanup;
4500 releasePage(apOld[i]);
4501 apOld[i] = 0;
4502 i++;
4503 }
4504
drh8b2f49b2001-06-08 00:21:52 +00004505 /*
drhf9ffac92002-03-02 19:00:31 +00004506 ** Put the new pages in accending order. This helps to
4507 ** keep entries in the disk file in order so that a scan
4508 ** of the table is a linear scan through the file. That
4509 ** in turn helps the operating system to deliver pages
4510 ** from the disk more rapidly.
4511 **
4512 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00004513 ** n is never more than NB (a small constant), that should
4514 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00004515 **
drhc3b70572003-01-04 19:44:07 +00004516 ** When NB==3, this one optimization makes the database
4517 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00004518 */
4519 for(i=0; i<k-1; i++){
4520 int minV = pgnoNew[i];
4521 int minI = i;
4522 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00004523 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00004524 minI = j;
4525 minV = pgnoNew[j];
4526 }
4527 }
4528 if( minI>i ){
4529 int t;
4530 MemPage *pT;
4531 t = pgnoNew[i];
4532 pT = apNew[i];
4533 pgnoNew[i] = pgnoNew[minI];
4534 apNew[i] = apNew[minI];
4535 pgnoNew[minI] = t;
4536 apNew[minI] = pT;
4537 }
4538 }
drha2fce642004-06-05 00:01:44 +00004539 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00004540 pgnoOld[0],
4541 nOld>=2 ? pgnoOld[1] : 0,
4542 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00004543 pgnoNew[0], szNew[0],
4544 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
4545 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00004546 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
4547 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00004548
drhf9ffac92002-03-02 19:00:31 +00004549 /*
drh14acc042001-06-10 19:56:58 +00004550 ** Evenly distribute the data in apCell[] across the new pages.
4551 ** Insert divider cells into pParent as necessary.
4552 */
4553 j = 0;
4554 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00004555 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00004556 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00004557 assert( j<nMaxCells );
drh4b70f112004-05-02 21:12:19 +00004558 assert( pNew->pgno==pgnoNew[i] );
drhfa1a98a2004-05-14 19:08:17 +00004559 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00004560 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00004561 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00004562
4563#ifndef SQLITE_OMIT_AUTOVACUUM
4564 /* If this is an auto-vacuum database, update the pointer map entries
4565 ** that point to the siblings that were rearranged. These can be: left
4566 ** children of cells, the right-child of the page, or overflow pages
4567 ** pointed to by cells.
4568 */
4569 if( pBt->autoVacuum ){
4570 for(k=j; k<cntNew[i]; k++){
danielk1977634f2982005-03-28 08:44:07 +00004571 assert( k<nMaxCells );
danielk1977ac11ee62005-01-15 12:45:51 +00004572 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
danielk197779a40da2005-01-16 08:00:01 +00004573 rc = ptrmapPutOvfl(pNew, k-j);
4574 if( rc!=SQLITE_OK ){
4575 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00004576 }
4577 }
4578 }
4579 }
4580#endif
4581
4582 j = cntNew[i];
4583
4584 /* If the sibling page assembled above was not the right-most sibling,
4585 ** insert a divider cell into the parent page.
4586 */
drh14acc042001-06-10 19:56:58 +00004587 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00004588 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00004589 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00004590 int sz;
danielk1977634f2982005-03-28 08:44:07 +00004591
4592 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00004593 pCell = apCell[j];
4594 sz = szCell[j] + leafCorrection;
drh4b70f112004-05-02 21:12:19 +00004595 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00004596 memcpy(&pNew->aData[8], pCell, 4);
drh24cd67e2004-05-10 16:18:47 +00004597 pTemp = 0;
drh8b18dd42004-05-12 19:18:15 +00004598 }else if( leafData ){
danielk1977ac11ee62005-01-15 12:45:51 +00004599 /* If the tree is a leaf-data tree, and the siblings are leaves,
4600 ** then there is no divider cell in apCell[]. Instead, the divider
4601 ** cell consists of the integer key for the right-most cell of
4602 ** the sibling-page assembled above only.
4603 */
drh6f11bef2004-05-13 01:12:56 +00004604 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00004605 j--;
drh43605152004-05-29 21:46:49 +00004606 parseCellPtr(pNew, apCell[j], &info);
drhb6f41482004-05-14 01:58:11 +00004607 pCell = &aSpace[iSpace];
drh6f11bef2004-05-13 01:12:56 +00004608 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, &sz);
drhb6f41482004-05-14 01:58:11 +00004609 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004610 assert( iSpace<=pBt->pageSize*5 );
drh8b18dd42004-05-12 19:18:15 +00004611 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00004612 }else{
4613 pCell -= 4;
drhb6f41482004-05-14 01:58:11 +00004614 pTemp = &aSpace[iSpace];
4615 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004616 assert( iSpace<=pBt->pageSize*5 );
drh4b70f112004-05-02 21:12:19 +00004617 }
danielk1977a3ad5e72005-01-07 08:56:44 +00004618 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00004619 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh43605152004-05-29 21:46:49 +00004620 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +00004621#ifndef SQLITE_OMIT_AUTOVACUUM
4622 /* If this is an auto-vacuum database, and not a leaf-data tree,
4623 ** then update the pointer map with an entry for the overflow page
4624 ** that the cell just inserted points to (if any).
4625 */
4626 if( pBt->autoVacuum && !leafData ){
danielk197779a40da2005-01-16 08:00:01 +00004627 rc = ptrmapPutOvfl(pParent, nxDiv);
4628 if( rc!=SQLITE_OK ){
4629 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00004630 }
4631 }
4632#endif
drh14acc042001-06-10 19:56:58 +00004633 j++;
4634 nxDiv++;
4635 }
4636 }
drh6019e162001-07-02 17:51:45 +00004637 assert( j==nCell );
drh4b70f112004-05-02 21:12:19 +00004638 if( (pageFlags & PTF_LEAF)==0 ){
drh43605152004-05-29 21:46:49 +00004639 memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
drh14acc042001-06-10 19:56:58 +00004640 }
drh43605152004-05-29 21:46:49 +00004641 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00004642 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00004643 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00004644 }else{
4645 /* Right-most sibling is the left child of the first entry in pParent
4646 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00004647 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00004648 }
4649
4650 /*
4651 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00004652 */
4653 for(i=0; i<nNew; i++){
danielk1977afcdd022004-10-31 16:25:42 +00004654 rc = reparentChildPages(apNew[i]);
4655 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004656 }
danielk1977afcdd022004-10-31 16:25:42 +00004657 rc = reparentChildPages(pParent);
4658 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004659
4660 /*
drh3a4c1412004-05-09 20:40:11 +00004661 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00004662 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00004663 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00004664 */
drhda200cc2004-05-09 11:51:38 +00004665 assert( pParent->isInit );
drh3a4c1412004-05-09 20:40:11 +00004666 /* assert( pPage->isInit ); // No! pPage might have been added to freelist */
4667 /* pageIntegrity(pPage); // No! pPage might have been added to freelist */
danielk1977ac245ec2005-01-14 13:50:11 +00004668 rc = balance(pParent, 0);
drhda200cc2004-05-09 11:51:38 +00004669
drh8b2f49b2001-06-08 00:21:52 +00004670 /*
drh14acc042001-06-10 19:56:58 +00004671 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00004672 */
drh14acc042001-06-10 19:56:58 +00004673balance_cleanup:
drh2e38c322004-09-03 18:38:44 +00004674 sqliteFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00004675 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00004676 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00004677 }
drh14acc042001-06-10 19:56:58 +00004678 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00004679 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00004680 }
drh91025292004-05-03 19:49:32 +00004681 releasePage(pParent);
drh3a4c1412004-05-09 20:40:11 +00004682 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
4683 pPage->pgno, nOld, nNew, nCell));
drh8b2f49b2001-06-08 00:21:52 +00004684 return rc;
4685}
4686
4687/*
drh43605152004-05-29 21:46:49 +00004688** This routine is called for the root page of a btree when the root
4689** page contains no cells. This is an opportunity to make the tree
4690** shallower by one level.
4691*/
4692static int balance_shallower(MemPage *pPage){
4693 MemPage *pChild; /* The only child page of pPage */
4694 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00004695 int rc = SQLITE_OK; /* Return code from subprocedures */
danielk1977aef0bf62005-12-30 16:28:01 +00004696 BtShared *pBt; /* The main BTree structure */
drh2e38c322004-09-03 18:38:44 +00004697 int mxCellPerPage; /* Maximum number of cells per page */
4698 u8 **apCell; /* All cells from pages being balanced */
4699 int *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00004700
4701 assert( pPage->pParent==0 );
4702 assert( pPage->nCell==0 );
drh2e38c322004-09-03 18:38:44 +00004703 pBt = pPage->pBt;
4704 mxCellPerPage = MX_CELL(pBt);
4705 apCell = sqliteMallocRaw( mxCellPerPage*(sizeof(u8*)+sizeof(int)) );
4706 if( apCell==0 ) return SQLITE_NOMEM;
4707 szCell = (int*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00004708 if( pPage->leaf ){
4709 /* The table is completely empty */
4710 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
4711 }else{
4712 /* The root page is empty but has one child. Transfer the
4713 ** information from that one child into the root page if it
4714 ** will fit. This reduces the depth of the tree by one.
4715 **
4716 ** If the root page is page 1, it has less space available than
4717 ** its child (due to the 100 byte header that occurs at the beginning
4718 ** of the database fle), so it might not be able to hold all of the
4719 ** information currently contained in the child. If this is the
4720 ** case, then do not do the transfer. Leave page 1 empty except
4721 ** for the right-pointer to the child page. The child page becomes
4722 ** the virtual root of the tree.
4723 */
4724 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
4725 assert( pgnoChild>0 );
4726 assert( pgnoChild<=sqlite3pager_pagecount(pPage->pBt->pPager) );
4727 rc = getPage(pPage->pBt, pgnoChild, &pChild);
drh2e38c322004-09-03 18:38:44 +00004728 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004729 if( pPage->pgno==1 ){
4730 rc = initPage(pChild, pPage);
drh2e38c322004-09-03 18:38:44 +00004731 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004732 assert( pChild->nOverflow==0 );
4733 if( pChild->nFree>=100 ){
4734 /* The child information will fit on the root page, so do the
4735 ** copy */
4736 int i;
4737 zeroPage(pPage, pChild->aData[0]);
4738 for(i=0; i<pChild->nCell; i++){
4739 apCell[i] = findCell(pChild,i);
4740 szCell[i] = cellSizePtr(pChild, apCell[i]);
4741 }
4742 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00004743 /* Copy the right-pointer of the child to the parent. */
4744 put4byte(&pPage->aData[pPage->hdrOffset+8],
4745 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh43605152004-05-29 21:46:49 +00004746 freePage(pChild);
4747 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
4748 }else{
4749 /* The child has more information that will fit on the root.
4750 ** The tree is already balanced. Do nothing. */
4751 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
4752 }
4753 }else{
4754 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
4755 pPage->isInit = 0;
4756 pPage->pParent = 0;
4757 rc = initPage(pPage, 0);
4758 assert( rc==SQLITE_OK );
4759 freePage(pChild);
4760 TRACE(("BALANCE: transfer child %d into root %d\n",
4761 pChild->pgno, pPage->pgno));
4762 }
danielk1977afcdd022004-10-31 16:25:42 +00004763 rc = reparentChildPages(pPage);
danielk1977ac11ee62005-01-15 12:45:51 +00004764 assert( pPage->nOverflow==0 );
4765#ifndef SQLITE_OMIT_AUTOVACUUM
4766 if( pBt->autoVacuum ){
danielk1977aac0a382005-01-16 11:07:06 +00004767 int i;
danielk1977ac11ee62005-01-15 12:45:51 +00004768 for(i=0; i<pPage->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00004769 rc = ptrmapPutOvfl(pPage, i);
4770 if( rc!=SQLITE_OK ){
4771 goto end_shallow_balance;
danielk1977ac11ee62005-01-15 12:45:51 +00004772 }
4773 }
4774 }
4775#endif
danielk1977afcdd022004-10-31 16:25:42 +00004776 if( rc!=SQLITE_OK ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004777 releasePage(pChild);
4778 }
drh2e38c322004-09-03 18:38:44 +00004779end_shallow_balance:
4780 sqliteFree(apCell);
4781 return rc;
drh43605152004-05-29 21:46:49 +00004782}
4783
4784
4785/*
4786** The root page is overfull
4787**
4788** When this happens, Create a new child page and copy the
4789** contents of the root into the child. Then make the root
4790** page an empty page with rightChild pointing to the new
4791** child. Finally, call balance_internal() on the new child
4792** to cause it to split.
4793*/
4794static int balance_deeper(MemPage *pPage){
4795 int rc; /* Return value from subprocedures */
4796 MemPage *pChild; /* Pointer to a new child page */
4797 Pgno pgnoChild; /* Page number of the new child page */
danielk1977aef0bf62005-12-30 16:28:01 +00004798 BtShared *pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00004799 int usableSize; /* Total usable size of a page */
4800 u8 *data; /* Content of the parent page */
4801 u8 *cdata; /* Content of the child page */
4802 int hdr; /* Offset to page header in parent */
4803 int brk; /* Offset to content of first cell in parent */
4804
4805 assert( pPage->pParent==0 );
4806 assert( pPage->nOverflow>0 );
4807 pBt = pPage->pBt;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004808 rc = allocatePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00004809 if( rc ) return rc;
4810 assert( sqlite3pager_iswriteable(pChild->aData) );
4811 usableSize = pBt->usableSize;
4812 data = pPage->aData;
4813 hdr = pPage->hdrOffset;
4814 brk = get2byte(&data[hdr+5]);
4815 cdata = pChild->aData;
4816 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
4817 memcpy(&cdata[brk], &data[brk], usableSize-brk);
danielk1977c7dc7532004-11-17 10:22:03 +00004818 assert( pChild->isInit==0 );
drh43605152004-05-29 21:46:49 +00004819 rc = initPage(pChild, pPage);
danielk19776b456a22005-03-21 04:04:02 +00004820 if( rc ) goto balancedeeper_out;
drh43605152004-05-29 21:46:49 +00004821 memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
4822 pChild->nOverflow = pPage->nOverflow;
4823 if( pChild->nOverflow ){
4824 pChild->nFree = 0;
4825 }
4826 assert( pChild->nCell==pPage->nCell );
4827 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
4828 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
4829 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
danielk19774e17d142005-01-16 09:06:33 +00004830#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00004831 if( pBt->autoVacuum ){
4832 int i;
4833 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
danielk19776b456a22005-03-21 04:04:02 +00004834 if( rc ) goto balancedeeper_out;
danielk1977ac11ee62005-01-15 12:45:51 +00004835 for(i=0; i<pChild->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00004836 rc = ptrmapPutOvfl(pChild, i);
4837 if( rc!=SQLITE_OK ){
4838 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00004839 }
4840 }
4841 }
danielk19774e17d142005-01-16 09:06:33 +00004842#endif
drh43605152004-05-29 21:46:49 +00004843 rc = balance_nonroot(pChild);
danielk19776b456a22005-03-21 04:04:02 +00004844
4845balancedeeper_out:
drh43605152004-05-29 21:46:49 +00004846 releasePage(pChild);
4847 return rc;
4848}
4849
4850/*
4851** Decide if the page pPage needs to be balanced. If balancing is
4852** required, call the appropriate balancing routine.
4853*/
danielk1977ac245ec2005-01-14 13:50:11 +00004854static int balance(MemPage *pPage, int insert){
drh43605152004-05-29 21:46:49 +00004855 int rc = SQLITE_OK;
4856 if( pPage->pParent==0 ){
4857 if( pPage->nOverflow>0 ){
4858 rc = balance_deeper(pPage);
4859 }
danielk1977687566d2004-11-02 12:56:41 +00004860 if( rc==SQLITE_OK && pPage->nCell==0 ){
drh43605152004-05-29 21:46:49 +00004861 rc = balance_shallower(pPage);
4862 }
4863 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00004864 if( pPage->nOverflow>0 ||
4865 (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
drh43605152004-05-29 21:46:49 +00004866 rc = balance_nonroot(pPage);
4867 }
4868 }
4869 return rc;
4870}
4871
4872/*
drh8dcd7ca2004-08-08 19:43:29 +00004873** This routine checks all cursors that point to table pgnoRoot.
4874** If any of those cursors other than pExclude were opened with
drhf74b8d92002-09-01 23:20:45 +00004875** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
drh8dcd7ca2004-08-08 19:43:29 +00004876** cursors that point to pgnoRoot were opened with wrFlag==1
drhf74b8d92002-09-01 23:20:45 +00004877** then this routine returns SQLITE_OK.
danielk1977299b1872004-11-22 10:02:10 +00004878**
4879** In addition to checking for read-locks (where a read-lock
4880** means a cursor opened with wrFlag==0) this routine also moves
4881** all cursors other than pExclude so that they are pointing to the
4882** first Cell on root page. This is necessary because an insert
4883** or delete might change the number of cells on a page or delete
4884** a page entirely and we do not want to leave any cursors
4885** pointing to non-existant pages or cells.
drhf74b8d92002-09-01 23:20:45 +00004886*/
danielk1977aef0bf62005-12-30 16:28:01 +00004887static int checkReadLocks(BtShared *pBt, Pgno pgnoRoot, BtCursor *pExclude){
danielk1977299b1872004-11-22 10:02:10 +00004888 BtCursor *p;
4889 for(p=pBt->pCursor; p; p=p->pNext){
4890 if( p->pgnoRoot!=pgnoRoot || p==pExclude ) continue;
4891 if( p->wrFlag==0 ) return SQLITE_LOCKED;
4892 if( p->pPage->pgno!=p->pgnoRoot ){
4893 moveToRoot(p);
4894 }
4895 }
drhf74b8d92002-09-01 23:20:45 +00004896 return SQLITE_OK;
4897}
4898
4899/*
drh3b7511c2001-05-26 13:15:44 +00004900** Insert a new record into the BTree. The key is given by (pKey,nKey)
4901** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00004902** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00004903** is left pointing at a random location.
4904**
4905** For an INTKEY table, only the nKey value of the key is used. pKey is
4906** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00004907*/
drh3aac2dd2004-04-26 14:10:20 +00004908int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00004909 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00004910 const void *pKey, i64 nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00004911 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00004912){
drh3b7511c2001-05-26 13:15:44 +00004913 int rc;
4914 int loc;
drh14acc042001-06-10 19:56:58 +00004915 int szNew;
drh3b7511c2001-05-26 13:15:44 +00004916 MemPage *pPage;
danielk1977aef0bf62005-12-30 16:28:01 +00004917 BtShared *pBt = pCur->pBtree->pBt;
drha34b6762004-05-07 13:30:42 +00004918 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00004919 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00004920
danielk1977aef0bf62005-12-30 16:28:01 +00004921 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00004922 /* Must start a transaction before doing an insert */
4923 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00004924 }
drhf74b8d92002-09-01 23:20:45 +00004925 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00004926 if( !pCur->wrFlag ){
4927 return SQLITE_PERM; /* Cursor not open for writing */
4928 }
drh8dcd7ca2004-08-08 19:43:29 +00004929 if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00004930 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
4931 }
drh3aac2dd2004-04-26 14:10:20 +00004932 rc = sqlite3BtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00004933 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00004934 pPage = pCur->pPage;
drh4a1c3802004-05-12 15:15:47 +00004935 assert( pPage->intKey || nKey>=0 );
drh8b18dd42004-05-12 19:18:15 +00004936 assert( pPage->leaf || !pPage->leafData );
drh3a4c1412004-05-09 20:40:11 +00004937 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
4938 pCur->pgnoRoot, nKey, nData, pPage->pgno,
4939 loc==0 ? "overwrite" : "new entry"));
drh7aa128d2002-06-21 13:09:16 +00004940 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004941 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00004942 if( rc ) return rc;
drh2e38c322004-09-03 18:38:44 +00004943 newCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
4944 if( newCell==0 ) return SQLITE_NOMEM;
drha34b6762004-05-07 13:30:42 +00004945 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, &szNew);
drh2e38c322004-09-03 18:38:44 +00004946 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00004947 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00004948 assert( szNew<=MX_CELL_SIZE(pBt) );
drhf328bc82004-05-10 23:29:49 +00004949 if( loc==0 && pCur->isValid ){
drha34b6762004-05-07 13:30:42 +00004950 int szOld;
4951 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00004952 oldCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00004953 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004954 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00004955 }
drh43605152004-05-29 21:46:49 +00004956 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00004957 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00004958 if( rc ) goto end_insert;
drh4b70f112004-05-02 21:12:19 +00004959 dropCell(pPage, pCur->idx, szOld);
drh7c717f72001-06-24 20:39:41 +00004960 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00004961 assert( pPage->leaf );
drh14acc042001-06-10 19:56:58 +00004962 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00004963 pCur->info.nSize = 0;
drh14acc042001-06-10 19:56:58 +00004964 }else{
drh4b70f112004-05-02 21:12:19 +00004965 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00004966 }
danielk1977a3ad5e72005-01-07 08:56:44 +00004967 rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
danielk1977e80463b2004-11-03 03:01:16 +00004968 if( rc!=SQLITE_OK ) goto end_insert;
danielk1977ac245ec2005-01-14 13:50:11 +00004969 rc = balance(pPage, 1);
drh23e11ca2004-05-04 17:27:28 +00004970 /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
drh3fc190c2001-09-14 03:24:23 +00004971 /* fflush(stdout); */
danielk1977299b1872004-11-22 10:02:10 +00004972 if( rc==SQLITE_OK ){
4973 moveToRoot(pCur);
4974 }
drh2e38c322004-09-03 18:38:44 +00004975end_insert:
4976 sqliteFree(newCell);
drh5e2f8b92001-05-28 00:41:15 +00004977 return rc;
4978}
4979
4980/*
drh4b70f112004-05-02 21:12:19 +00004981** Delete the entry that the cursor is pointing to. The cursor
4982** is left pointing at a random location.
drh3b7511c2001-05-26 13:15:44 +00004983*/
drh3aac2dd2004-04-26 14:10:20 +00004984int sqlite3BtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00004985 MemPage *pPage = pCur->pPage;
drh4b70f112004-05-02 21:12:19 +00004986 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00004987 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00004988 Pgno pgnoChild = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00004989 BtShared *pBt = pCur->pBtree->pBt;
drh8b2f49b2001-06-08 00:21:52 +00004990
drh7aa128d2002-06-21 13:09:16 +00004991 assert( pPage->isInit );
danielk1977aef0bf62005-12-30 16:28:01 +00004992 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00004993 /* Must start a transaction before doing a delete */
4994 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00004995 }
drhf74b8d92002-09-01 23:20:45 +00004996 assert( !pBt->readOnly );
drhbd03cae2001-06-02 02:40:57 +00004997 if( pCur->idx >= pPage->nCell ){
4998 return SQLITE_ERROR; /* The cursor is not pointing to anything */
4999 }
drhecdc7532001-09-23 02:35:53 +00005000 if( !pCur->wrFlag ){
5001 return SQLITE_PERM; /* Did not open this cursor for writing */
5002 }
drh8dcd7ca2004-08-08 19:43:29 +00005003 if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00005004 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5005 }
drha34b6762004-05-07 13:30:42 +00005006 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00005007 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00005008
5009 /* Locate the cell within it's page and leave pCell pointing to the
5010 ** data. The clearCell() call frees any overflow pages associated with the
5011 ** cell. The cell itself is still intact.
5012 */
danielk1977299b1872004-11-22 10:02:10 +00005013 pCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005014 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005015 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005016 }
danielk197728129562005-01-11 10:25:06 +00005017 rc = clearCell(pPage, pCell);
5018 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00005019
drh4b70f112004-05-02 21:12:19 +00005020 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00005021 /*
drh5e00f6c2001-09-13 13:46:56 +00005022 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00005023 ** do something we will leave a hole on an internal page.
5024 ** We have to fill the hole by moving in a cell from a leaf. The
5025 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00005026 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00005027 */
drh14acc042001-06-10 19:56:58 +00005028 BtCursor leafCur;
drh4b70f112004-05-02 21:12:19 +00005029 unsigned char *pNext;
drh14acc042001-06-10 19:56:58 +00005030 int szNext;
danielk1977299b1872004-11-22 10:02:10 +00005031 int notUsed;
danielk19776b456a22005-03-21 04:04:02 +00005032 unsigned char *tempCell = 0;
drh8b18dd42004-05-12 19:18:15 +00005033 assert( !pPage->leafData );
drh14acc042001-06-10 19:56:58 +00005034 getTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00005035 rc = sqlite3BtreeNext(&leafCur, &notUsed);
drh14acc042001-06-10 19:56:58 +00005036 if( rc!=SQLITE_OK ){
drhee696e22004-08-30 16:52:17 +00005037 if( rc!=SQLITE_NOMEM ){
drh49285702005-09-17 15:20:26 +00005038 rc = SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00005039 }
drh5e2f8b92001-05-28 00:41:15 +00005040 }
danielk19776b456a22005-03-21 04:04:02 +00005041 if( rc==SQLITE_OK ){
5042 rc = sqlite3pager_write(leafCur.pPage->aData);
5043 }
5044 if( rc==SQLITE_OK ){
5045 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
5046 pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
5047 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
5048 pNext = findCell(leafCur.pPage, leafCur.idx);
5049 szNext = cellSizePtr(leafCur.pPage, pNext);
5050 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
5051 tempCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
5052 if( tempCell==0 ){
5053 rc = SQLITE_NOMEM;
5054 }
5055 }
5056 if( rc==SQLITE_OK ){
5057 rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
5058 }
5059 if( rc==SQLITE_OK ){
5060 put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
5061 rc = balance(pPage, 0);
5062 }
5063 if( rc==SQLITE_OK ){
5064 dropCell(leafCur.pPage, leafCur.idx, szNext);
5065 rc = balance(leafCur.pPage, 0);
5066 }
drh2e38c322004-09-03 18:38:44 +00005067 sqliteFree(tempCell);
drh8c42ca92001-06-22 19:15:00 +00005068 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00005069 }else{
danielk1977299b1872004-11-22 10:02:10 +00005070 TRACE(("DELETE: table=%d delete from leaf %d\n",
5071 pCur->pgnoRoot, pPage->pgno));
5072 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
danielk1977ac245ec2005-01-14 13:50:11 +00005073 rc = balance(pPage, 0);
drh5e2f8b92001-05-28 00:41:15 +00005074 }
danielk19776b456a22005-03-21 04:04:02 +00005075 if( rc==SQLITE_OK ){
5076 moveToRoot(pCur);
5077 }
drh5e2f8b92001-05-28 00:41:15 +00005078 return rc;
drh3b7511c2001-05-26 13:15:44 +00005079}
drh8b2f49b2001-06-08 00:21:52 +00005080
5081/*
drhc6b52df2002-01-04 03:09:29 +00005082** Create a new BTree table. Write into *piTable the page
5083** number for the root page of the new table.
5084**
drhab01f612004-05-22 02:55:23 +00005085** The type of type is determined by the flags parameter. Only the
5086** following values of flags are currently in use. Other values for
5087** flags might not work:
5088**
5089** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
5090** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00005091*/
danielk1977aef0bf62005-12-30 16:28:01 +00005092int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
5093 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005094 MemPage *pRoot;
5095 Pgno pgnoRoot;
5096 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00005097 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005098 /* Must start a transaction first */
5099 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005100 }
danielk197728129562005-01-11 10:25:06 +00005101 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00005102
5103 /* It is illegal to create a table if any cursors are open on the
5104 ** database. This is because in auto-vacuum mode the backend may
5105 ** need to move a database page to make room for the new root-page.
5106 ** If an open cursor was using the page a problem would occur.
5107 */
5108 if( pBt->pCursor ){
5109 return SQLITE_LOCKED;
5110 }
5111
danielk1977003ba062004-11-04 02:57:33 +00005112#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977cb1a7eb2004-11-05 12:27:02 +00005113 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drh8b2f49b2001-06-08 00:21:52 +00005114 if( rc ) return rc;
danielk1977003ba062004-11-04 02:57:33 +00005115#else
danielk1977687566d2004-11-02 12:56:41 +00005116 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00005117 Pgno pgnoMove; /* Move a page here to make room for the root-page */
5118 MemPage *pPageMove; /* The page to move to. */
5119
danielk1977003ba062004-11-04 02:57:33 +00005120 /* Read the value of meta[3] from the database to determine where the
5121 ** root page of the new table should go. meta[3] is the largest root-page
5122 ** created so far, so the new root-page is (meta[3]+1).
5123 */
danielk1977aef0bf62005-12-30 16:28:01 +00005124 rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00005125 if( rc!=SQLITE_OK ) return rc;
5126 pgnoRoot++;
5127
danielk1977599fcba2004-11-08 07:13:13 +00005128 /* The new root-page may not be allocated on a pointer-map page, or the
5129 ** PENDING_BYTE page.
5130 */
drh42cac6d2004-11-20 20:31:11 +00005131 if( pgnoRoot==PTRMAP_PAGENO(pBt->usableSize, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00005132 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00005133 pgnoRoot++;
5134 }
5135 assert( pgnoRoot>=3 );
5136
5137 /* Allocate a page. The page that currently resides at pgnoRoot will
5138 ** be moved to the allocated page (unless the allocated page happens
5139 ** to reside at pgnoRoot).
5140 */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005141 rc = allocatePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00005142 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00005143 return rc;
5144 }
danielk1977003ba062004-11-04 02:57:33 +00005145
5146 if( pgnoMove!=pgnoRoot ){
5147 u8 eType;
5148 Pgno iPtrPage;
5149
5150 releasePage(pPageMove);
5151 rc = getPage(pBt, pgnoRoot, &pRoot);
5152 if( rc!=SQLITE_OK ){
5153 return rc;
5154 }
5155 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drhccae6022005-02-26 17:31:26 +00005156 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00005157 releasePage(pRoot);
5158 return rc;
5159 }
drhccae6022005-02-26 17:31:26 +00005160 assert( eType!=PTRMAP_ROOTPAGE );
5161 assert( eType!=PTRMAP_FREEPAGE );
danielk19775fd057a2005-03-09 13:09:43 +00005162 rc = sqlite3pager_write(pRoot->aData);
5163 if( rc!=SQLITE_OK ){
5164 releasePage(pRoot);
5165 return rc;
5166 }
danielk1977003ba062004-11-04 02:57:33 +00005167 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove);
5168 releasePage(pRoot);
5169 if( rc!=SQLITE_OK ){
5170 return rc;
5171 }
5172 rc = getPage(pBt, pgnoRoot, &pRoot);
5173 if( rc!=SQLITE_OK ){
5174 return rc;
5175 }
5176 rc = sqlite3pager_write(pRoot->aData);
5177 if( rc!=SQLITE_OK ){
5178 releasePage(pRoot);
5179 return rc;
5180 }
5181 }else{
5182 pRoot = pPageMove;
5183 }
5184
danielk197742741be2005-01-08 12:42:39 +00005185 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00005186 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
5187 if( rc ){
5188 releasePage(pRoot);
5189 return rc;
5190 }
danielk1977aef0bf62005-12-30 16:28:01 +00005191 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00005192 if( rc ){
5193 releasePage(pRoot);
5194 return rc;
5195 }
danielk197742741be2005-01-08 12:42:39 +00005196
danielk1977003ba062004-11-04 02:57:33 +00005197 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00005198 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00005199 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00005200 }
5201#endif
drha34b6762004-05-07 13:30:42 +00005202 assert( sqlite3pager_iswriteable(pRoot->aData) );
drhde647132004-05-07 17:57:49 +00005203 zeroPage(pRoot, flags | PTF_LEAF);
drha34b6762004-05-07 13:30:42 +00005204 sqlite3pager_unref(pRoot->aData);
drh8b2f49b2001-06-08 00:21:52 +00005205 *piTable = (int)pgnoRoot;
5206 return SQLITE_OK;
5207}
5208
5209/*
5210** Erase the given database page and all its children. Return
5211** the page to the freelist.
5212*/
drh4b70f112004-05-02 21:12:19 +00005213static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00005214 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00005215 Pgno pgno, /* Page number to clear */
5216 MemPage *pParent, /* Parent page. NULL for the root */
5217 int freePageFlag /* Deallocate page if true */
5218){
danielk19776b456a22005-03-21 04:04:02 +00005219 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00005220 int rc;
drh4b70f112004-05-02 21:12:19 +00005221 unsigned char *pCell;
5222 int i;
drh8b2f49b2001-06-08 00:21:52 +00005223
danielk1977a1cb1832005-02-12 08:59:55 +00005224 if( pgno>sqlite3pager_pagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00005225 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00005226 }
5227
drhde647132004-05-07 17:57:49 +00005228 rc = getAndInitPage(pBt, pgno, &pPage, pParent);
danielk19776b456a22005-03-21 04:04:02 +00005229 if( rc ) goto cleardatabasepage_out;
drha34b6762004-05-07 13:30:42 +00005230 rc = sqlite3pager_write(pPage->aData);
danielk19776b456a22005-03-21 04:04:02 +00005231 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00005232 for(i=0; i<pPage->nCell; i++){
drh43605152004-05-29 21:46:49 +00005233 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00005234 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005235 rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00005236 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00005237 }
drh4b70f112004-05-02 21:12:19 +00005238 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00005239 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00005240 }
drha34b6762004-05-07 13:30:42 +00005241 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005242 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00005243 if( rc ) goto cleardatabasepage_out;
drh2aa679f2001-06-25 02:11:07 +00005244 }
5245 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00005246 rc = freePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00005247 }else{
drh3a4c1412004-05-09 20:40:11 +00005248 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00005249 }
danielk19776b456a22005-03-21 04:04:02 +00005250
5251cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00005252 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00005253 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005254}
5255
5256/*
drhab01f612004-05-22 02:55:23 +00005257** Delete all information from a single table in the database. iTable is
5258** the page number of the root of the table. After this routine returns,
5259** the root page is empty, but still exists.
5260**
5261** This routine will fail with SQLITE_LOCKED if there are any open
5262** read cursors on the table. Open write cursors are moved to the
5263** root of the table.
drh8b2f49b2001-06-08 00:21:52 +00005264*/
danielk1977aef0bf62005-12-30 16:28:01 +00005265int sqlite3BtreeClearTable(Btree *p, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00005266 int rc;
drhf74b8d92002-09-01 23:20:45 +00005267 BtCursor *pCur;
danielk1977aef0bf62005-12-30 16:28:01 +00005268 BtShared *pBt = p->pBt;
5269 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005270 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005271 }
drhf74b8d92002-09-01 23:20:45 +00005272 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
5273 if( pCur->pgnoRoot==(Pgno)iTable ){
5274 if( pCur->wrFlag==0 ) return SQLITE_LOCKED;
5275 moveToRoot(pCur);
5276 }
drhecdc7532001-09-23 02:35:53 +00005277 }
drha34b6762004-05-07 13:30:42 +00005278 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
danielk197771fd80b2005-12-16 06:54:01 +00005279#if 0
drh8b2f49b2001-06-08 00:21:52 +00005280 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00005281 sqlite3BtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00005282 }
danielk197771fd80b2005-12-16 06:54:01 +00005283#endif
drh8c42ca92001-06-22 19:15:00 +00005284 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005285}
5286
5287/*
5288** Erase all information in a table and add the root of the table to
5289** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00005290** page 1) is never added to the freelist.
5291**
5292** This routine will fail with SQLITE_LOCKED if there are any open
5293** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00005294**
5295** If AUTOVACUUM is enabled and the page at iTable is not the last
5296** root page in the database file, then the last root page
5297** in the database file is moved into the slot formerly occupied by
5298** iTable and that last slot formerly occupied by the last root page
5299** is added to the freelist instead of iTable. In this say, all
5300** root pages are kept at the beginning of the database file, which
5301** is necessary for AUTOVACUUM to work right. *piMoved is set to the
5302** page number that used to be the last root page in the file before
5303** the move. If no page gets moved, *piMoved is set to 0.
5304** The last root page is recorded in meta[3] and the value of
5305** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00005306*/
danielk1977aef0bf62005-12-30 16:28:01 +00005307int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00005308 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00005309 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00005310 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00005311
danielk1977aef0bf62005-12-30 16:28:01 +00005312 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005313 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005314 }
danielk1977a0bf2652004-11-04 14:30:04 +00005315
danielk1977e6efa742004-11-10 11:55:10 +00005316 /* It is illegal to drop a table if any cursors are open on the
5317 ** database. This is because in auto-vacuum mode the backend may
5318 ** need to move another root-page to fill a gap left by the deleted
5319 ** root page. If an open cursor was using this page a problem would
5320 ** occur.
5321 */
5322 if( pBt->pCursor ){
5323 return SQLITE_LOCKED;
drh5df72a52002-06-06 23:16:05 +00005324 }
danielk1977a0bf2652004-11-04 14:30:04 +00005325
drha34b6762004-05-07 13:30:42 +00005326 rc = getPage(pBt, (Pgno)iTable, &pPage);
drh2aa679f2001-06-25 02:11:07 +00005327 if( rc ) return rc;
danielk1977aef0bf62005-12-30 16:28:01 +00005328 rc = sqlite3BtreeClearTable(p, iTable);
danielk19776b456a22005-03-21 04:04:02 +00005329 if( rc ){
5330 releasePage(pPage);
5331 return rc;
5332 }
danielk1977a0bf2652004-11-04 14:30:04 +00005333
drh205f48e2004-11-05 00:43:11 +00005334 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00005335
drh4b70f112004-05-02 21:12:19 +00005336 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00005337#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00005338 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00005339 releasePage(pPage);
5340#else
5341 if( pBt->autoVacuum ){
5342 Pgno maxRootPgno;
danielk1977aef0bf62005-12-30 16:28:01 +00005343 rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00005344 if( rc!=SQLITE_OK ){
5345 releasePage(pPage);
5346 return rc;
5347 }
5348
5349 if( iTable==maxRootPgno ){
5350 /* If the table being dropped is the table with the largest root-page
5351 ** number in the database, put the root page on the free list.
5352 */
5353 rc = freePage(pPage);
5354 releasePage(pPage);
5355 if( rc!=SQLITE_OK ){
5356 return rc;
5357 }
5358 }else{
5359 /* The table being dropped does not have the largest root-page
5360 ** number in the database. So move the page that does into the
5361 ** gap left by the deleted root-page.
5362 */
5363 MemPage *pMove;
5364 releasePage(pPage);
5365 rc = getPage(pBt, maxRootPgno, &pMove);
5366 if( rc!=SQLITE_OK ){
5367 return rc;
5368 }
5369 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable);
5370 releasePage(pMove);
5371 if( rc!=SQLITE_OK ){
5372 return rc;
5373 }
5374 rc = getPage(pBt, maxRootPgno, &pMove);
5375 if( rc!=SQLITE_OK ){
5376 return rc;
5377 }
5378 rc = freePage(pMove);
5379 releasePage(pMove);
5380 if( rc!=SQLITE_OK ){
5381 return rc;
5382 }
5383 *piMoved = maxRootPgno;
5384 }
5385
danielk1977599fcba2004-11-08 07:13:13 +00005386 /* Set the new 'max-root-page' value in the database header. This
5387 ** is the old value less one, less one more if that happens to
5388 ** be a root-page number, less one again if that is the
5389 ** PENDING_BYTE_PAGE.
5390 */
danielk197787a6e732004-11-05 12:58:25 +00005391 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00005392 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
5393 maxRootPgno--;
5394 }
drh42cac6d2004-11-20 20:31:11 +00005395 if( maxRootPgno==PTRMAP_PAGENO(pBt->usableSize, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00005396 maxRootPgno--;
5397 }
danielk1977599fcba2004-11-08 07:13:13 +00005398 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
5399
danielk1977aef0bf62005-12-30 16:28:01 +00005400 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00005401 }else{
5402 rc = freePage(pPage);
5403 releasePage(pPage);
5404 }
5405#endif
drh2aa679f2001-06-25 02:11:07 +00005406 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00005407 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00005408 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00005409 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00005410 }
drh8b2f49b2001-06-08 00:21:52 +00005411 return rc;
5412}
5413
drh001bbcb2003-03-19 03:14:00 +00005414
drh8b2f49b2001-06-08 00:21:52 +00005415/*
drh23e11ca2004-05-04 17:27:28 +00005416** Read the meta-information out of a database file. Meta[0]
5417** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00005418** through meta[15] are available for use by higher layers. Meta[0]
5419** is read-only, the others are read/write.
5420**
5421** The schema layer numbers meta values differently. At the schema
5422** layer (and the SetCookie and ReadCookie opcodes) the number of
5423** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00005424*/
danielk1977aef0bf62005-12-30 16:28:01 +00005425int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
drh8b2f49b2001-06-08 00:21:52 +00005426 int rc;
drh4b70f112004-05-02 21:12:19 +00005427 unsigned char *pP1;
danielk1977aef0bf62005-12-30 16:28:01 +00005428 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005429
drh23e11ca2004-05-04 17:27:28 +00005430 assert( idx>=0 && idx<=15 );
drha34b6762004-05-07 13:30:42 +00005431 rc = sqlite3pager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00005432 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00005433 *pMeta = get4byte(&pP1[36 + idx*4]);
drha34b6762004-05-07 13:30:42 +00005434 sqlite3pager_unref(pP1);
drhae157872004-08-14 19:20:09 +00005435
danielk1977599fcba2004-11-08 07:13:13 +00005436 /* If autovacuumed is disabled in this build but we are trying to
5437 ** access an autovacuumed database, then make the database readonly.
5438 */
danielk1977003ba062004-11-04 02:57:33 +00005439#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00005440 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00005441#endif
drhae157872004-08-14 19:20:09 +00005442
drh8b2f49b2001-06-08 00:21:52 +00005443 return SQLITE_OK;
5444}
5445
5446/*
drh23e11ca2004-05-04 17:27:28 +00005447** Write meta-information back into the database. Meta[0] is
5448** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00005449*/
danielk1977aef0bf62005-12-30 16:28:01 +00005450int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
5451 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00005452 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00005453 int rc;
drh23e11ca2004-05-04 17:27:28 +00005454 assert( idx>=1 && idx<=15 );
danielk1977aef0bf62005-12-30 16:28:01 +00005455 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005456 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +00005457 }
drhde647132004-05-07 17:57:49 +00005458 assert( pBt->pPage1!=0 );
5459 pP1 = pBt->pPage1->aData;
drha34b6762004-05-07 13:30:42 +00005460 rc = sqlite3pager_write(pP1);
drh4b70f112004-05-02 21:12:19 +00005461 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00005462 put4byte(&pP1[36 + idx*4], iMeta);
drh8b2f49b2001-06-08 00:21:52 +00005463 return SQLITE_OK;
5464}
drh8c42ca92001-06-22 19:15:00 +00005465
drhf328bc82004-05-10 23:29:49 +00005466/*
5467** Return the flag byte at the beginning of the page that the cursor
5468** is currently pointing to.
5469*/
5470int sqlite3BtreeFlags(BtCursor *pCur){
5471 MemPage *pPage = pCur->pPage;
5472 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
5473}
5474
danielk1977b5402fb2005-01-12 07:15:04 +00005475#ifdef SQLITE_DEBUG
drh8c42ca92001-06-22 19:15:00 +00005476/*
5477** Print a disassembly of the given page on standard output. This routine
5478** is used for debugging and testing only.
5479*/
danielk1977aef0bf62005-12-30 16:28:01 +00005480static int btreePageDump(BtShared *pBt, int pgno, int recursive, MemPage *pParent){
drh8c42ca92001-06-22 19:15:00 +00005481 int rc;
5482 MemPage *pPage;
drhc8629a12004-05-08 20:07:40 +00005483 int i, j, c;
drh8c42ca92001-06-22 19:15:00 +00005484 int nFree;
5485 u16 idx;
drhab9f7f12004-05-08 10:56:11 +00005486 int hdr;
drh43605152004-05-29 21:46:49 +00005487 int nCell;
drha2fce642004-06-05 00:01:44 +00005488 int isInit;
drhab9f7f12004-05-08 10:56:11 +00005489 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00005490 char range[20];
5491 unsigned char payload[20];
drhab9f7f12004-05-08 10:56:11 +00005492
drh4b70f112004-05-02 21:12:19 +00005493 rc = getPage(pBt, (Pgno)pgno, &pPage);
drha2fce642004-06-05 00:01:44 +00005494 isInit = pPage->isInit;
5495 if( pPage->isInit==0 ){
danielk1977c7dc7532004-11-17 10:22:03 +00005496 initPage(pPage, pParent);
drha2fce642004-06-05 00:01:44 +00005497 }
drh8c42ca92001-06-22 19:15:00 +00005498 if( rc ){
5499 return rc;
5500 }
drhab9f7f12004-05-08 10:56:11 +00005501 hdr = pPage->hdrOffset;
5502 data = pPage->aData;
drhc8629a12004-05-08 20:07:40 +00005503 c = data[hdr];
drh8b18dd42004-05-12 19:18:15 +00005504 pPage->intKey = (c & (PTF_INTKEY|PTF_LEAFDATA))!=0;
drhc8629a12004-05-08 20:07:40 +00005505 pPage->zeroData = (c & PTF_ZERODATA)!=0;
drh8b18dd42004-05-12 19:18:15 +00005506 pPage->leafData = (c & PTF_LEAFDATA)!=0;
drhc8629a12004-05-08 20:07:40 +00005507 pPage->leaf = (c & PTF_LEAF)!=0;
drh8b18dd42004-05-12 19:18:15 +00005508 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
drh43605152004-05-29 21:46:49 +00005509 nCell = get2byte(&data[hdr+3]);
drhfe63d1c2004-09-08 20:13:04 +00005510 sqlite3DebugPrintf("PAGE %d: flags=0x%02x frag=%d parent=%d\n", pgno,
drh43605152004-05-29 21:46:49 +00005511 data[hdr], data[hdr+7],
drhda200cc2004-05-09 11:51:38 +00005512 (pPage->isInit && pPage->pParent) ? pPage->pParent->pgno : 0);
drhab9f7f12004-05-08 10:56:11 +00005513 assert( hdr == (pgno==1 ? 100 : 0) );
drh43605152004-05-29 21:46:49 +00005514 idx = hdr + 12 - pPage->leaf*4;
5515 for(i=0; i<nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00005516 CellInfo info;
drh4b70f112004-05-02 21:12:19 +00005517 Pgno child;
drh43605152004-05-29 21:46:49 +00005518 unsigned char *pCell;
drh6f11bef2004-05-13 01:12:56 +00005519 int sz;
drh43605152004-05-29 21:46:49 +00005520 int addr;
drh6f11bef2004-05-13 01:12:56 +00005521
drh43605152004-05-29 21:46:49 +00005522 addr = get2byte(&data[idx + 2*i]);
5523 pCell = &data[addr];
5524 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005525 sz = info.nSize;
drh43605152004-05-29 21:46:49 +00005526 sprintf(range,"%d..%d", addr, addr+sz-1);
drh4b70f112004-05-02 21:12:19 +00005527 if( pPage->leaf ){
5528 child = 0;
5529 }else{
drh43605152004-05-29 21:46:49 +00005530 child = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005531 }
drh6f11bef2004-05-13 01:12:56 +00005532 sz = info.nData;
5533 if( !pPage->intKey ) sz += info.nKey;
drh8c42ca92001-06-22 19:15:00 +00005534 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
drh6f11bef2004-05-13 01:12:56 +00005535 memcpy(payload, &pCell[info.nHeader], sz);
drh8c42ca92001-06-22 19:15:00 +00005536 for(j=0; j<sz; j++){
5537 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
5538 }
5539 payload[sz] = 0;
drhfe63d1c2004-09-08 20:13:04 +00005540 sqlite3DebugPrintf(
drh6f11bef2004-05-13 01:12:56 +00005541 "cell %2d: i=%-10s chld=%-4d nk=%-4lld nd=%-4d payload=%s\n",
5542 i, range, child, info.nKey, info.nData, payload
drh8c42ca92001-06-22 19:15:00 +00005543 );
drh8c42ca92001-06-22 19:15:00 +00005544 }
drh4b70f112004-05-02 21:12:19 +00005545 if( !pPage->leaf ){
drhfe63d1c2004-09-08 20:13:04 +00005546 sqlite3DebugPrintf("right_child: %d\n", get4byte(&data[hdr+8]));
drh4b70f112004-05-02 21:12:19 +00005547 }
drh8c42ca92001-06-22 19:15:00 +00005548 nFree = 0;
5549 i = 0;
drhab9f7f12004-05-08 10:56:11 +00005550 idx = get2byte(&data[hdr+1]);
drhb6f41482004-05-14 01:58:11 +00005551 while( idx>0 && idx<pPage->pBt->usableSize ){
drhab9f7f12004-05-08 10:56:11 +00005552 int sz = get2byte(&data[idx+2]);
drh4b70f112004-05-02 21:12:19 +00005553 sprintf(range,"%d..%d", idx, idx+sz-1);
5554 nFree += sz;
drhfe63d1c2004-09-08 20:13:04 +00005555 sqlite3DebugPrintf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
drh4b70f112004-05-02 21:12:19 +00005556 i, range, sz, nFree);
drhab9f7f12004-05-08 10:56:11 +00005557 idx = get2byte(&data[idx]);
drh2aa679f2001-06-25 02:11:07 +00005558 i++;
drh8c42ca92001-06-22 19:15:00 +00005559 }
5560 if( idx!=0 ){
drhfe63d1c2004-09-08 20:13:04 +00005561 sqlite3DebugPrintf("ERROR: next freeblock index out of range: %d\n", idx);
drh8c42ca92001-06-22 19:15:00 +00005562 }
drha34b6762004-05-07 13:30:42 +00005563 if( recursive && !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005564 for(i=0; i<nCell; i++){
5565 unsigned char *pCell = findCell(pPage, i);
danielk1977c7dc7532004-11-17 10:22:03 +00005566 btreePageDump(pBt, get4byte(pCell), 1, pPage);
drha34b6762004-05-07 13:30:42 +00005567 idx = get2byte(pCell);
drh6019e162001-07-02 17:51:45 +00005568 }
danielk1977c7dc7532004-11-17 10:22:03 +00005569 btreePageDump(pBt, get4byte(&data[hdr+8]), 1, pPage);
drh6019e162001-07-02 17:51:45 +00005570 }
drha2fce642004-06-05 00:01:44 +00005571 pPage->isInit = isInit;
drhab9f7f12004-05-08 10:56:11 +00005572 sqlite3pager_unref(data);
drh3644f082004-05-10 18:45:09 +00005573 fflush(stdout);
drh8c42ca92001-06-22 19:15:00 +00005574 return SQLITE_OK;
5575}
danielk1977aef0bf62005-12-30 16:28:01 +00005576int sqlite3BtreePageDump(Btree *p, int pgno, int recursive){
5577 return btreePageDump(p->pBt, pgno, recursive, 0);
danielk1977c7dc7532004-11-17 10:22:03 +00005578}
drhaaab5722002-02-19 13:39:21 +00005579#endif
drh8c42ca92001-06-22 19:15:00 +00005580
drhaaab5722002-02-19 13:39:21 +00005581#ifdef SQLITE_TEST
drh8c42ca92001-06-22 19:15:00 +00005582/*
drh2aa679f2001-06-25 02:11:07 +00005583** Fill aResult[] with information about the entry and page that the
5584** cursor is pointing to.
5585**
5586** aResult[0] = The page number
5587** aResult[1] = The entry number
5588** aResult[2] = Total number of entries on this page
drh3e27c022004-07-23 00:01:38 +00005589** aResult[3] = Cell size (local payload + header)
drh2aa679f2001-06-25 02:11:07 +00005590** aResult[4] = Number of free bytes on this page
5591** aResult[5] = Number of free blocks on the page
drh3e27c022004-07-23 00:01:38 +00005592** aResult[6] = Total payload size (local + overflow)
5593** aResult[7] = Header size in bytes
5594** aResult[8] = Local payload size
5595** aResult[9] = Parent page number
drh5eddca62001-06-30 21:53:53 +00005596**
5597** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00005598*/
drh3e27c022004-07-23 00:01:38 +00005599int sqlite3BtreeCursorInfo(BtCursor *pCur, int *aResult, int upCnt){
drh2aa679f2001-06-25 02:11:07 +00005600 int cnt, idx;
5601 MemPage *pPage = pCur->pPage;
drh3e27c022004-07-23 00:01:38 +00005602 BtCursor tmpCur;
drhda200cc2004-05-09 11:51:38 +00005603
5604 pageIntegrity(pPage);
drh4b70f112004-05-02 21:12:19 +00005605 assert( pPage->isInit );
drh3e27c022004-07-23 00:01:38 +00005606 getTempCursor(pCur, &tmpCur);
5607 while( upCnt-- ){
5608 moveToParent(&tmpCur);
5609 }
5610 pPage = tmpCur.pPage;
5611 pageIntegrity(pPage);
drha34b6762004-05-07 13:30:42 +00005612 aResult[0] = sqlite3pager_pagenumber(pPage->aData);
drh91025292004-05-03 19:49:32 +00005613 assert( aResult[0]==pPage->pgno );
drh3e27c022004-07-23 00:01:38 +00005614 aResult[1] = tmpCur.idx;
drh2aa679f2001-06-25 02:11:07 +00005615 aResult[2] = pPage->nCell;
drh3e27c022004-07-23 00:01:38 +00005616 if( tmpCur.idx>=0 && tmpCur.idx<pPage->nCell ){
5617 getCellInfo(&tmpCur);
5618 aResult[3] = tmpCur.info.nSize;
5619 aResult[6] = tmpCur.info.nData;
5620 aResult[7] = tmpCur.info.nHeader;
5621 aResult[8] = tmpCur.info.nLocal;
drh2aa679f2001-06-25 02:11:07 +00005622 }else{
5623 aResult[3] = 0;
5624 aResult[6] = 0;
drh3e27c022004-07-23 00:01:38 +00005625 aResult[7] = 0;
5626 aResult[8] = 0;
drh2aa679f2001-06-25 02:11:07 +00005627 }
5628 aResult[4] = pPage->nFree;
5629 cnt = 0;
drh4b70f112004-05-02 21:12:19 +00005630 idx = get2byte(&pPage->aData[pPage->hdrOffset+1]);
drhb6f41482004-05-14 01:58:11 +00005631 while( idx>0 && idx<pPage->pBt->usableSize ){
drh2aa679f2001-06-25 02:11:07 +00005632 cnt++;
drh4b70f112004-05-02 21:12:19 +00005633 idx = get2byte(&pPage->aData[idx]);
drh2aa679f2001-06-25 02:11:07 +00005634 }
5635 aResult[5] = cnt;
drh3e27c022004-07-23 00:01:38 +00005636 if( pPage->pParent==0 || isRootPage(pPage) ){
5637 aResult[9] = 0;
5638 }else{
5639 aResult[9] = pPage->pParent->pgno;
5640 }
5641 releaseTempCursor(&tmpCur);
drh8c42ca92001-06-22 19:15:00 +00005642 return SQLITE_OK;
5643}
drhaaab5722002-02-19 13:39:21 +00005644#endif
drhdd793422001-06-28 01:54:48 +00005645
drhdd793422001-06-28 01:54:48 +00005646/*
drh5eddca62001-06-30 21:53:53 +00005647** Return the pager associated with a BTree. This routine is used for
5648** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00005649*/
danielk1977aef0bf62005-12-30 16:28:01 +00005650Pager *sqlite3BtreePager(Btree *p){
5651 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00005652}
drh5eddca62001-06-30 21:53:53 +00005653
5654/*
5655** This structure is passed around through all the sanity checking routines
5656** in order to keep track of some global state information.
5657*/
drhaaab5722002-02-19 13:39:21 +00005658typedef struct IntegrityCk IntegrityCk;
5659struct IntegrityCk {
danielk1977aef0bf62005-12-30 16:28:01 +00005660 BtShared *pBt; /* The tree being checked out */
drh100569d2001-10-02 13:01:48 +00005661 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
5662 int nPage; /* Number of pages in the database */
5663 int *anRef; /* Number of times each page is referenced */
drh100569d2001-10-02 13:01:48 +00005664 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00005665};
5666
drhb7f91642004-10-31 02:22:47 +00005667#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005668/*
5669** Append a message to the error message string.
5670*/
drh2e38c322004-09-03 18:38:44 +00005671static void checkAppendMsg(
5672 IntegrityCk *pCheck,
5673 char *zMsg1,
5674 const char *zFormat,
5675 ...
5676){
5677 va_list ap;
5678 char *zMsg2;
5679 va_start(ap, zFormat);
5680 zMsg2 = sqlite3VMPrintf(zFormat, ap);
5681 va_end(ap);
5682 if( zMsg1==0 ) zMsg1 = "";
drh5eddca62001-06-30 21:53:53 +00005683 if( pCheck->zErrMsg ){
5684 char *zOld = pCheck->zErrMsg;
5685 pCheck->zErrMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00005686 sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00005687 sqliteFree(zOld);
5688 }else{
danielk19774adee202004-05-08 08:23:19 +00005689 sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00005690 }
drh2e38c322004-09-03 18:38:44 +00005691 sqliteFree(zMsg2);
drh5eddca62001-06-30 21:53:53 +00005692}
drhb7f91642004-10-31 02:22:47 +00005693#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005694
drhb7f91642004-10-31 02:22:47 +00005695#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005696/*
5697** Add 1 to the reference count for page iPage. If this is the second
5698** reference to the page, add an error message to pCheck->zErrMsg.
5699** Return 1 if there are 2 ore more references to the page and 0 if
5700** if this is the first reference to the page.
5701**
5702** Also check that the page number is in bounds.
5703*/
drhaaab5722002-02-19 13:39:21 +00005704static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00005705 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00005706 if( iPage>pCheck->nPage || iPage<0 ){
drh2e38c322004-09-03 18:38:44 +00005707 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005708 return 1;
5709 }
5710 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00005711 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005712 return 1;
5713 }
5714 return (pCheck->anRef[iPage]++)>1;
5715}
5716
danielk1977afcdd022004-10-31 16:25:42 +00005717#ifndef SQLITE_OMIT_AUTOVACUUM
5718/*
5719** Check that the entry in the pointer-map for page iChild maps to
5720** page iParent, pointer type ptrType. If not, append an error message
5721** to pCheck.
5722*/
5723static void checkPtrmap(
5724 IntegrityCk *pCheck, /* Integrity check context */
5725 Pgno iChild, /* Child page number */
5726 u8 eType, /* Expected pointer map type */
5727 Pgno iParent, /* Expected pointer map parent page number */
5728 char *zContext /* Context description (used for error msg) */
5729){
5730 int rc;
5731 u8 ePtrmapType;
5732 Pgno iPtrmapParent;
5733
5734 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
5735 if( rc!=SQLITE_OK ){
5736 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
5737 return;
5738 }
5739
5740 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
5741 checkAppendMsg(pCheck, zContext,
5742 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
5743 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
5744 }
5745}
5746#endif
5747
drh5eddca62001-06-30 21:53:53 +00005748/*
5749** Check the integrity of the freelist or of an overflow page list.
5750** Verify that the number of pages on the list is N.
5751*/
drh30e58752002-03-02 20:41:57 +00005752static void checkList(
5753 IntegrityCk *pCheck, /* Integrity checking context */
5754 int isFreeList, /* True for a freelist. False for overflow page list */
5755 int iPage, /* Page number for first page in the list */
5756 int N, /* Expected number of pages in the list */
5757 char *zContext /* Context for error messages */
5758){
5759 int i;
drh3a4c1412004-05-09 20:40:11 +00005760 int expected = N;
5761 int iFirst = iPage;
drh30e58752002-03-02 20:41:57 +00005762 while( N-- > 0 ){
drh4b70f112004-05-02 21:12:19 +00005763 unsigned char *pOvfl;
drh5eddca62001-06-30 21:53:53 +00005764 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00005765 checkAppendMsg(pCheck, zContext,
5766 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00005767 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00005768 break;
5769 }
5770 if( checkRef(pCheck, iPage, zContext) ) break;
drha34b6762004-05-07 13:30:42 +00005771 if( sqlite3pager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
drh2e38c322004-09-03 18:38:44 +00005772 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005773 break;
5774 }
drh30e58752002-03-02 20:41:57 +00005775 if( isFreeList ){
drh4b70f112004-05-02 21:12:19 +00005776 int n = get4byte(&pOvfl[4]);
danielk1977687566d2004-11-02 12:56:41 +00005777#ifndef SQLITE_OMIT_AUTOVACUUM
5778 if( pCheck->pBt->autoVacuum ){
5779 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
5780 }
5781#endif
drh855eb1c2004-08-31 13:45:11 +00005782 if( n>pCheck->pBt->usableSize/4-8 ){
drh2e38c322004-09-03 18:38:44 +00005783 checkAppendMsg(pCheck, zContext,
5784 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00005785 N--;
5786 }else{
5787 for(i=0; i<n; i++){
danielk1977687566d2004-11-02 12:56:41 +00005788 Pgno iFreePage = get4byte(&pOvfl[8+i*4]);
5789#ifndef SQLITE_OMIT_AUTOVACUUM
5790 if( pCheck->pBt->autoVacuum ){
5791 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
5792 }
5793#endif
5794 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00005795 }
5796 N -= n;
drh30e58752002-03-02 20:41:57 +00005797 }
drh30e58752002-03-02 20:41:57 +00005798 }
danielk1977afcdd022004-10-31 16:25:42 +00005799#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00005800 else{
5801 /* If this database supports auto-vacuum and iPage is not the last
5802 ** page in this overflow list, check that the pointer-map entry for
5803 ** the following page matches iPage.
5804 */
5805 if( pCheck->pBt->autoVacuum && N>0 ){
5806 i = get4byte(pOvfl);
5807 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
5808 }
danielk1977afcdd022004-10-31 16:25:42 +00005809 }
5810#endif
drh4b70f112004-05-02 21:12:19 +00005811 iPage = get4byte(pOvfl);
drha34b6762004-05-07 13:30:42 +00005812 sqlite3pager_unref(pOvfl);
drh5eddca62001-06-30 21:53:53 +00005813 }
5814}
drhb7f91642004-10-31 02:22:47 +00005815#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005816
drhb7f91642004-10-31 02:22:47 +00005817#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005818/*
5819** Do various sanity checks on a single page of a tree. Return
5820** the tree depth. Root pages return 0. Parents of root pages
5821** return 1, and so forth.
5822**
5823** These checks are done:
5824**
5825** 1. Make sure that cells and freeblocks do not overlap
5826** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00005827** NO 2. Make sure cell keys are in order.
5828** NO 3. Make sure no key is less than or equal to zLowerBound.
5829** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00005830** 5. Check the integrity of overflow pages.
5831** 6. Recursively call checkTreePage on all children.
5832** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00005833** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00005834** the root of the tree.
5835*/
5836static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00005837 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00005838 int iPage, /* Page number of the page to check */
5839 MemPage *pParent, /* Parent page */
5840 char *zParentContext, /* Parent context */
5841 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00005842 int nLower, /* Number of characters in zLowerBound */
5843 char *zUpperBound, /* All keys should be less than this, if not NULL */
5844 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00005845){
5846 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00005847 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00005848 int hdr, cellStart;
5849 int nCell;
drhda200cc2004-05-09 11:51:38 +00005850 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00005851 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00005852 int usableSize;
drh5eddca62001-06-30 21:53:53 +00005853 char zContext[100];
drh2e38c322004-09-03 18:38:44 +00005854 char *hit;
drh5eddca62001-06-30 21:53:53 +00005855
danielk1977ef73ee92004-11-06 12:26:07 +00005856 sprintf(zContext, "Page %d: ", iPage);
5857
drh5eddca62001-06-30 21:53:53 +00005858 /* Check that the page exists
5859 */
drhd9cb6ac2005-10-20 07:28:17 +00005860 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00005861 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00005862 if( iPage==0 ) return 0;
5863 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh4b70f112004-05-02 21:12:19 +00005864 if( (rc = getPage(pBt, (Pgno)iPage, &pPage))!=0 ){
drh2e38c322004-09-03 18:38:44 +00005865 checkAppendMsg(pCheck, zContext,
5866 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00005867 return 0;
5868 }
drh4b70f112004-05-02 21:12:19 +00005869 if( (rc = initPage(pPage, pParent))!=0 ){
drh2e38c322004-09-03 18:38:44 +00005870 checkAppendMsg(pCheck, zContext, "initPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00005871 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00005872 return 0;
5873 }
5874
5875 /* Check out all the cells.
5876 */
5877 depth = 0;
drh5eddca62001-06-30 21:53:53 +00005878 for(i=0; i<pPage->nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00005879 u8 *pCell;
5880 int sz;
5881 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00005882
5883 /* Check payload overflow pages
5884 */
drh3a4c1412004-05-09 20:40:11 +00005885 sprintf(zContext, "On tree page %d cell %d: ", iPage, i);
drh43605152004-05-29 21:46:49 +00005886 pCell = findCell(pPage,i);
5887 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005888 sz = info.nData;
5889 if( !pPage->intKey ) sz += info.nKey;
5890 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00005891 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00005892 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
5893#ifndef SQLITE_OMIT_AUTOVACUUM
5894 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00005895 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00005896 }
5897#endif
5898 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00005899 }
5900
5901 /* Check sanity of left child page.
5902 */
drhda200cc2004-05-09 11:51:38 +00005903 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005904 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00005905#ifndef SQLITE_OMIT_AUTOVACUUM
5906 if( pBt->autoVacuum ){
5907 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
5908 }
5909#endif
drhda200cc2004-05-09 11:51:38 +00005910 d2 = checkTreePage(pCheck,pgno,pPage,zContext,0,0,0,0);
5911 if( i>0 && d2!=depth ){
5912 checkAppendMsg(pCheck, zContext, "Child page depth differs");
5913 }
5914 depth = d2;
drh5eddca62001-06-30 21:53:53 +00005915 }
drh5eddca62001-06-30 21:53:53 +00005916 }
drhda200cc2004-05-09 11:51:38 +00005917 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005918 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drhda200cc2004-05-09 11:51:38 +00005919 sprintf(zContext, "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00005920#ifndef SQLITE_OMIT_AUTOVACUUM
5921 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00005922 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00005923 }
5924#endif
drhda200cc2004-05-09 11:51:38 +00005925 checkTreePage(pCheck, pgno, pPage, zContext,0,0,0,0);
5926 }
drh5eddca62001-06-30 21:53:53 +00005927
5928 /* Check for complete coverage of the page
5929 */
drhda200cc2004-05-09 11:51:38 +00005930 data = pPage->aData;
5931 hdr = pPage->hdrOffset;
drh2e38c322004-09-03 18:38:44 +00005932 hit = sqliteMalloc( usableSize );
5933 if( hit ){
5934 memset(hit, 1, get2byte(&data[hdr+5]));
5935 nCell = get2byte(&data[hdr+3]);
5936 cellStart = hdr + 12 - 4*pPage->leaf;
5937 for(i=0; i<nCell; i++){
5938 int pc = get2byte(&data[cellStart+i*2]);
5939 int size = cellSizePtr(pPage, &data[pc]);
5940 int j;
danielk19777701e812005-01-10 12:59:51 +00005941 if( (pc+size-1)>=usableSize || pc<0 ){
5942 checkAppendMsg(pCheck, 0,
5943 "Corruption detected in cell %d on page %d",i,iPage,0);
5944 }else{
5945 for(j=pc+size-1; j>=pc; j--) hit[j]++;
5946 }
drh2e38c322004-09-03 18:38:44 +00005947 }
5948 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
5949 cnt++){
5950 int size = get2byte(&data[i+2]);
5951 int j;
danielk19777701e812005-01-10 12:59:51 +00005952 if( (i+size-1)>=usableSize || i<0 ){
5953 checkAppendMsg(pCheck, 0,
5954 "Corruption detected in cell %d on page %d",i,iPage,0);
5955 }else{
5956 for(j=i+size-1; j>=i; j--) hit[j]++;
5957 }
drh2e38c322004-09-03 18:38:44 +00005958 i = get2byte(&data[i]);
5959 }
5960 for(i=cnt=0; i<usableSize; i++){
5961 if( hit[i]==0 ){
5962 cnt++;
5963 }else if( hit[i]>1 ){
5964 checkAppendMsg(pCheck, 0,
5965 "Multiple uses for byte %d of page %d", i, iPage);
5966 break;
5967 }
5968 }
5969 if( cnt!=data[hdr+7] ){
5970 checkAppendMsg(pCheck, 0,
5971 "Fragmented space is %d byte reported as %d on page %d",
5972 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00005973 }
5974 }
drh2e38c322004-09-03 18:38:44 +00005975 sqliteFree(hit);
drh6019e162001-07-02 17:51:45 +00005976
drh4b70f112004-05-02 21:12:19 +00005977 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00005978 return depth+1;
drh5eddca62001-06-30 21:53:53 +00005979}
drhb7f91642004-10-31 02:22:47 +00005980#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005981
drhb7f91642004-10-31 02:22:47 +00005982#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005983/*
5984** This routine does a complete check of the given BTree file. aRoot[] is
5985** an array of pages numbers were each page number is the root page of
5986** a table. nRoot is the number of entries in aRoot.
5987**
5988** If everything checks out, this routine returns NULL. If something is
5989** amiss, an error message is written into memory obtained from malloc()
5990** and a pointer to that error message is returned. The calling function
5991** is responsible for freeing the error message when it is done.
5992*/
danielk1977aef0bf62005-12-30 16:28:01 +00005993char *sqlite3BtreeIntegrityCheck(Btree *p, int *aRoot, int nRoot){
drh5eddca62001-06-30 21:53:53 +00005994 int i;
5995 int nRef;
drhaaab5722002-02-19 13:39:21 +00005996 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00005997 BtShared *pBt = p->pBt;
drh5eddca62001-06-30 21:53:53 +00005998
drha34b6762004-05-07 13:30:42 +00005999 nRef = *sqlite3pager_stats(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00006000 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
drhefc251d2001-07-01 22:12:01 +00006001 return sqliteStrDup("Unable to acquire a read lock on the database");
6002 }
drh5eddca62001-06-30 21:53:53 +00006003 sCheck.pBt = pBt;
6004 sCheck.pPager = pBt->pPager;
drha34b6762004-05-07 13:30:42 +00006005 sCheck.nPage = sqlite3pager_pagecount(sCheck.pPager);
drh0de8c112002-07-06 16:32:14 +00006006 if( sCheck.nPage==0 ){
6007 unlockBtreeIfUnused(pBt);
6008 return 0;
6009 }
drh8c1238a2003-01-02 14:43:55 +00006010 sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00006011 if( !sCheck.anRef ){
6012 unlockBtreeIfUnused(pBt);
6013 return sqlite3MPrintf("Unable to malloc %d bytes",
6014 (sCheck.nPage+1)*sizeof(sCheck.anRef[0]));
6015 }
drhda200cc2004-05-09 11:51:38 +00006016 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00006017 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00006018 if( i<=sCheck.nPage ){
6019 sCheck.anRef[i] = 1;
6020 }
drh5eddca62001-06-30 21:53:53 +00006021 sCheck.zErrMsg = 0;
6022
6023 /* Check the integrity of the freelist
6024 */
drha34b6762004-05-07 13:30:42 +00006025 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
6026 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00006027
6028 /* Check all the tables.
6029 */
6030 for(i=0; i<nRoot; i++){
drh4ff6dfa2002-03-03 23:06:00 +00006031 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00006032#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006033 if( pBt->autoVacuum && aRoot[i]>1 ){
6034 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
6035 }
6036#endif
drh1bffb9c2002-02-03 17:37:36 +00006037 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00006038 }
6039
6040 /* Make sure every page in the file is referenced
6041 */
6042 for(i=1; i<=sCheck.nPage; i++){
danielk1977afcdd022004-10-31 16:25:42 +00006043#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00006044 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00006045 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00006046 }
danielk1977afcdd022004-10-31 16:25:42 +00006047#else
6048 /* If the database supports auto-vacuum, make sure no tables contain
6049 ** references to pointer-map pages.
6050 */
6051 if( sCheck.anRef[i]==0 &&
drh42cac6d2004-11-20 20:31:11 +00006052 (PTRMAP_PAGENO(pBt->usableSize, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006053 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
6054 }
6055 if( sCheck.anRef[i]!=0 &&
drh42cac6d2004-11-20 20:31:11 +00006056 (PTRMAP_PAGENO(pBt->usableSize, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006057 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
6058 }
6059#endif
drh5eddca62001-06-30 21:53:53 +00006060 }
6061
6062 /* Make sure this analysis did not leave any unref() pages
6063 */
drh5e00f6c2001-09-13 13:46:56 +00006064 unlockBtreeIfUnused(pBt);
drha34b6762004-05-07 13:30:42 +00006065 if( nRef != *sqlite3pager_stats(pBt->pPager) ){
drh2e38c322004-09-03 18:38:44 +00006066 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00006067 "Outstanding page count goes from %d to %d during this analysis",
drha34b6762004-05-07 13:30:42 +00006068 nRef, *sqlite3pager_stats(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00006069 );
drh5eddca62001-06-30 21:53:53 +00006070 }
6071
6072 /* Clean up and report errors.
6073 */
6074 sqliteFree(sCheck.anRef);
6075 return sCheck.zErrMsg;
6076}
drhb7f91642004-10-31 02:22:47 +00006077#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00006078
drh73509ee2003-04-06 20:44:45 +00006079/*
6080** Return the full pathname of the underlying database file.
6081*/
danielk1977aef0bf62005-12-30 16:28:01 +00006082const char *sqlite3BtreeGetFilename(Btree *p){
6083 assert( p->pBt->pPager!=0 );
6084 return sqlite3pager_filename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00006085}
6086
6087/*
danielk19775865e3d2004-06-14 06:03:57 +00006088** Return the pathname of the directory that contains the database file.
6089*/
danielk1977aef0bf62005-12-30 16:28:01 +00006090const char *sqlite3BtreeGetDirname(Btree *p){
6091 assert( p->pBt->pPager!=0 );
6092 return sqlite3pager_dirname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006093}
6094
6095/*
6096** Return the pathname of the journal file for this database. The return
6097** value of this routine is the same regardless of whether the journal file
6098** has been created or not.
6099*/
danielk1977aef0bf62005-12-30 16:28:01 +00006100const char *sqlite3BtreeGetJournalname(Btree *p){
6101 assert( p->pBt->pPager!=0 );
6102 return sqlite3pager_journalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006103}
6104
drhb7f91642004-10-31 02:22:47 +00006105#ifndef SQLITE_OMIT_VACUUM
danielk19775865e3d2004-06-14 06:03:57 +00006106/*
drhf7c57532003-04-25 13:22:51 +00006107** Copy the complete content of pBtFrom into pBtTo. A transaction
6108** must be active for both files.
6109**
6110** The size of file pBtFrom may be reduced by this operation.
drh43605152004-05-29 21:46:49 +00006111** If anything goes wrong, the transaction on pBtFrom is rolled back.
drh73509ee2003-04-06 20:44:45 +00006112*/
danielk1977aef0bf62005-12-30 16:28:01 +00006113int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
drhf7c57532003-04-25 13:22:51 +00006114 int rc = SQLITE_OK;
drh50f2f432005-09-16 11:32:18 +00006115 Pgno i, nPage, nToPage, iSkip;
drhf7c57532003-04-25 13:22:51 +00006116
danielk1977aef0bf62005-12-30 16:28:01 +00006117 BtShared *pBtTo = pTo->pBt;
6118 BtShared *pBtFrom = pFrom->pBt;
6119
6120 if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
danielk1977ee5741e2004-05-31 10:01:34 +00006121 return SQLITE_ERROR;
6122 }
drhf7c57532003-04-25 13:22:51 +00006123 if( pBtTo->pCursor ) return SQLITE_BUSY;
drha34b6762004-05-07 13:30:42 +00006124 nToPage = sqlite3pager_pagecount(pBtTo->pPager);
6125 nPage = sqlite3pager_pagecount(pBtFrom->pPager);
drh50f2f432005-09-16 11:32:18 +00006126 iSkip = PENDING_BYTE_PAGE(pBtTo);
danielk1977369f27e2004-06-15 11:40:04 +00006127 for(i=1; rc==SQLITE_OK && i<=nPage; i++){
drhf7c57532003-04-25 13:22:51 +00006128 void *pPage;
drh50f2f432005-09-16 11:32:18 +00006129 if( i==iSkip ) continue;
drha34b6762004-05-07 13:30:42 +00006130 rc = sqlite3pager_get(pBtFrom->pPager, i, &pPage);
drhf7c57532003-04-25 13:22:51 +00006131 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00006132 rc = sqlite3pager_overwrite(pBtTo->pPager, i, pPage);
drh2e6d11b2003-04-25 15:37:57 +00006133 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00006134 sqlite3pager_unref(pPage);
drhf7c57532003-04-25 13:22:51 +00006135 }
drh2e6d11b2003-04-25 15:37:57 +00006136 for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
6137 void *pPage;
drh49285702005-09-17 15:20:26 +00006138 if( i==iSkip ) continue;
drha34b6762004-05-07 13:30:42 +00006139 rc = sqlite3pager_get(pBtTo->pPager, i, &pPage);
drh2e6d11b2003-04-25 15:37:57 +00006140 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00006141 rc = sqlite3pager_write(pPage);
6142 sqlite3pager_unref(pPage);
6143 sqlite3pager_dont_write(pBtTo->pPager, i);
drh2e6d11b2003-04-25 15:37:57 +00006144 }
6145 if( !rc && nPage<nToPage ){
drha34b6762004-05-07 13:30:42 +00006146 rc = sqlite3pager_truncate(pBtTo->pPager, nPage);
drh2e6d11b2003-04-25 15:37:57 +00006147 }
drhf7c57532003-04-25 13:22:51 +00006148 if( rc ){
danielk1977aef0bf62005-12-30 16:28:01 +00006149 sqlite3BtreeRollback(pTo);
drhf7c57532003-04-25 13:22:51 +00006150 }
6151 return rc;
drh73509ee2003-04-06 20:44:45 +00006152}
drhb7f91642004-10-31 02:22:47 +00006153#endif /* SQLITE_OMIT_VACUUM */
danielk19771d850a72004-05-31 08:26:49 +00006154
6155/*
6156** Return non-zero if a transaction is active.
6157*/
danielk1977aef0bf62005-12-30 16:28:01 +00006158int sqlite3BtreeIsInTrans(Btree *p){
6159 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00006160}
6161
6162/*
6163** Return non-zero if a statement transaction is active.
6164*/
danielk1977aef0bf62005-12-30 16:28:01 +00006165int sqlite3BtreeIsInStmt(Btree *p){
6166 return (p->pBt && p->pBt->inStmt);
danielk19771d850a72004-05-31 08:26:49 +00006167}
danielk197713adf8a2004-06-03 16:08:41 +00006168
6169/*
6170** This call is a no-op if no write-transaction is currently active on pBt.
6171**
6172** Otherwise, sync the database file for the btree pBt. zMaster points to
6173** the name of a master journal file that should be written into the
6174** individual journal file, or is NULL, indicating no master journal file
6175** (single database transaction).
6176**
6177** When this is called, the master journal should already have been
6178** created, populated with this journal pointer and synced to disk.
6179**
6180** Once this is routine has returned, the only thing required to commit
6181** the write-transaction for this database file is to delete the journal.
6182*/
danielk1977aef0bf62005-12-30 16:28:01 +00006183int sqlite3BtreeSync(Btree *p, const char *zMaster){
6184 if( p->inTrans==TRANS_WRITE ){
6185 BtShared *pBt = p->pBt;
danielk1977687566d2004-11-02 12:56:41 +00006186#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977d761c0c2004-11-05 16:37:02 +00006187 Pgno nTrunc = 0;
danielk1977687566d2004-11-02 12:56:41 +00006188 if( pBt->autoVacuum ){
danielk1977d761c0c2004-11-05 16:37:02 +00006189 int rc = autoVacuumCommit(pBt, &nTrunc);
danielk1977687566d2004-11-02 12:56:41 +00006190 if( rc!=SQLITE_OK ) return rc;
6191 }
danielk1977d761c0c2004-11-05 16:37:02 +00006192 return sqlite3pager_sync(pBt->pPager, zMaster, nTrunc);
danielk1977687566d2004-11-02 12:56:41 +00006193#endif
danielk1977d761c0c2004-11-05 16:37:02 +00006194 return sqlite3pager_sync(pBt->pPager, zMaster, 0);
danielk197713adf8a2004-06-03 16:08:41 +00006195 }
6196 return SQLITE_OK;
6197}
danielk1977aef0bf62005-12-30 16:28:01 +00006198
6199#ifndef SQLITE_OMIT_SHARED_CACHE
6200/*
6201** Enable the shared pager and schema features.
6202*/
6203int sqlite3_enable_shared_cache(int enable){
6204 SqliteTsd *pTsd = sqlite3Tsd();
6205 if( pTsd->pPager ){
6206 return SQLITE_MISUSE;
6207 }
6208 pTsd->useSharedData = enable;
6209 return SQLITE_OK;
6210}
6211#endif
6212