blob: 548c7577a92155b96581b309d6abd0af57a7ea39 [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*************************************************************************
drhfe63d1c2004-09-08 20:13:04 +000012** $Id: btree.c,v 1.189 2004/09/08 20:13:05 drh 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
130** only keys and no data. The intkey flag means that the key is a single
131** variable length integer at the beginning of the payload.
132**
drh43605152004-05-29 21:46:49 +0000133** The cell pointer array begins on the first byte after the page header.
134** The cell pointer array contains zero or more 2-byte numbers which are
135** offsets from the beginning of the page to the cell content in the cell
136** content area. The cell pointers occur in sorted order. The system strives
137** to keep free space after the last cell pointer so that new cells can
138** be easily added without have to defragment the page.
139**
140** Cell content is stored at the very end of the page and grows toward the
141** beginning of the page.
142**
143** Unused space within the cell content area is collected into a linked list of
144** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
145** to the first freeblock is given in the header. Freeblocks occur in
146** increasing order. Because a freeblock must be at least 4 bytes in size,
147** any group of 3 or fewer unused bytes in the cell content area cannot
148** exist on the freeblock chain. A group of 3 or fewer free bytes is called
149** a fragment. The total number of bytes in all fragments is recorded.
150** in the page header at offset 7.
151**
152** SIZE DESCRIPTION
153** 2 Byte offset of the next freeblock
154** 2 Bytes in this freeblock
155**
156** Cells are of variable length. Cells are stored in the cell content area at
157** the end of the page. Pointers to the cells are in the cell pointer array
158** that immediately follows the page header. Cells is not necessarily
159** contiguous or in order, but cell pointers are contiguous and in order.
160**
161** Cell content makes use of variable length integers. A variable
162** length integer is 1 to 9 bytes where the lower 7 bits of each
drh9e572e62004-04-23 23:43:10 +0000163** byte are used. The integer consists of all bytes that have bit 8 set and
drh6f11bef2004-05-13 01:12:56 +0000164** the first byte with bit 8 clear. The most significant byte of the integer
drhab01f612004-05-22 02:55:23 +0000165** appears first. A variable-length integer may not be more than 9 bytes long.
166** As a special case, all 8 bytes of the 9th byte are used as data. This
167** allows a 64-bit integer to be encoded in 9 bytes.
drh9e572e62004-04-23 23:43:10 +0000168**
169** 0x00 becomes 0x00000000
drh6f11bef2004-05-13 01:12:56 +0000170** 0x7f becomes 0x0000007f
171** 0x81 0x00 becomes 0x00000080
172** 0x82 0x00 becomes 0x00000100
173** 0x80 0x7f becomes 0x0000007f
174** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
drh9e572e62004-04-23 23:43:10 +0000175** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
176**
177** Variable length integers are used for rowids and to hold the number of
178** bytes of key and data in a btree cell.
179**
drh43605152004-05-29 21:46:49 +0000180** The content of a cell looks like this:
drh9e572e62004-04-23 23:43:10 +0000181**
182** SIZE DESCRIPTION
drh3aac2dd2004-04-26 14:10:20 +0000183** 4 Page number of the left child. Omitted if leaf flag is set.
184** var Number of bytes of data. Omitted if the zerodata flag is set.
185** var Number of bytes of key. Or the key itself if intkey flag is set.
drh9e572e62004-04-23 23:43:10 +0000186** * Payload
187** 4 First page of the overflow chain. Omitted if no overflow
188**
189** Overflow pages form a linked list. Each page except the last is completely
190** filled with data (pagesize - 4 bytes). The last page can have as little
191** as 1 byte of data.
192**
193** SIZE DESCRIPTION
194** 4 Page number of next overflow page
195** * Data
196**
197** Freelist pages come in two subtypes: trunk pages and leaf pages. The
198** file header points to first in a linked list of trunk page. Each trunk
199** page points to multiple leaf pages. The content of a leaf page is
200** unspecified. A trunk page looks like this:
201**
202** SIZE DESCRIPTION
203** 4 Page number of next trunk page
204** 4 Number of leaf pointers on this page
205** * zero or more pages numbers of leaves
drha059ad02001-04-17 20:09:11 +0000206*/
207#include "sqliteInt.h"
208#include "pager.h"
209#include "btree.h"
drh1f595712004-06-15 01:40:29 +0000210#include "os.h"
drha059ad02001-04-17 20:09:11 +0000211#include <assert.h>
212
drh4b70f112004-05-02 21:12:19 +0000213
drh4b70f112004-05-02 21:12:19 +0000214/* The following value is the maximum cell size assuming a maximum page
215** size give above.
216*/
drh2e38c322004-09-03 18:38:44 +0000217#define MX_CELL_SIZE(pBt) (pBt->pageSize-8)
drh4b70f112004-05-02 21:12:19 +0000218
219/* The maximum number of cells on a single page of the database. This
220** assumes a minimum cell size of 3 bytes. Such small cells will be
221** exceedingly rare, but they are possible.
222*/
drh2e38c322004-09-03 18:38:44 +0000223#define MX_CELL(pBt) ((pBt->pageSize-8)/3)
drh4b70f112004-05-02 21:12:19 +0000224
paulb95a8862003-04-01 21:16:41 +0000225/* Forward declarations */
drh3aac2dd2004-04-26 14:10:20 +0000226typedef struct MemPage MemPage;
paulb95a8862003-04-01 21:16:41 +0000227
drh8c42ca92001-06-22 19:15:00 +0000228/*
drhbd03cae2001-06-02 02:40:57 +0000229** This is a magic string that appears at the beginning of every
drh8c42ca92001-06-22 19:15:00 +0000230** SQLite database in order to identify the file as a real database.
drhde647132004-05-07 17:57:49 +0000231** 123456789 123456 */
232static const char zMagicHeader[] = "SQLite format 3";
drh08ed44e2001-04-29 23:32:55 +0000233
234/*
drh4b70f112004-05-02 21:12:19 +0000235** Page type flags. An ORed combination of these flags appear as the
236** first byte of every BTree page.
drh8c42ca92001-06-22 19:15:00 +0000237*/
drhde647132004-05-07 17:57:49 +0000238#define PTF_INTKEY 0x01
drh9e572e62004-04-23 23:43:10 +0000239#define PTF_ZERODATA 0x02
drh8b18dd42004-05-12 19:18:15 +0000240#define PTF_LEAFDATA 0x04
241#define PTF_LEAF 0x08
drh8c42ca92001-06-22 19:15:00 +0000242
243/*
drh9e572e62004-04-23 23:43:10 +0000244** As each page of the file is loaded into memory, an instance of the following
245** structure is appended and initialized to zero. This structure stores
246** information about the page that is decoded from the raw file page.
drh14acc042001-06-10 19:56:58 +0000247**
drh72f82862001-05-24 21:06:34 +0000248** The pParent field points back to the parent page. This allows us to
249** walk up the BTree from any leaf to the root. Care must be taken to
250** unref() the parent page pointer when this page is no longer referenced.
drhbd03cae2001-06-02 02:40:57 +0000251** The pageDestructor() routine handles that chore.
drh7e3b0a02001-04-28 16:52:40 +0000252*/
253struct MemPage {
drha6abd042004-06-09 17:37:22 +0000254 u8 isInit; /* True if previously initialized. MUST BE FIRST! */
drh43605152004-05-29 21:46:49 +0000255 u8 idxShift; /* True if Cell indices have changed */
256 u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
257 u8 intKey; /* True if intkey flag is set */
258 u8 leaf; /* True if leaf flag is set */
259 u8 zeroData; /* True if table stores keys only */
260 u8 leafData; /* True if tables stores data on leaves only */
261 u8 hasData; /* True if this page stores data */
262 u8 hdrOffset; /* 100 for page 1. 0 otherwise */
drh271efa52004-05-30 19:19:05 +0000263 u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
drha2fce642004-06-05 00:01:44 +0000264 u16 maxLocal; /* Copy of Btree.maxLocal or Btree.maxLeaf */
265 u16 minLocal; /* Copy of Btree.minLocal or Btree.minLeaf */
drh43605152004-05-29 21:46:49 +0000266 u16 cellOffset; /* Index in aData of first cell pointer */
267 u16 idxParent; /* Index in parent of this node */
268 u16 nFree; /* Number of free bytes on the page */
269 u16 nCell; /* Number of cells on this page, local and ovfl */
270 struct _OvflCell { /* Cells that will not fit on aData[] */
271 u8 *pCell; /* Pointers to the body of the overflow cell */
272 u16 idx; /* Insert this cell before idx-th non-overflow cell */
drha2fce642004-06-05 00:01:44 +0000273 } aOvfl[5];
drh43605152004-05-29 21:46:49 +0000274 struct Btree *pBt; /* Pointer back to BTree structure */
275 u8 *aData; /* Pointer back to the start of the page */
276 Pgno pgno; /* Page number for this page */
277 MemPage *pParent; /* The parent of this page. NULL for root */
drh8c42ca92001-06-22 19:15:00 +0000278};
drh7e3b0a02001-04-28 16:52:40 +0000279
280/*
drh3b7511c2001-05-26 13:15:44 +0000281** The in-memory image of a disk page has the auxiliary information appended
282** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
283** that extra information.
284*/
drh3aac2dd2004-04-26 14:10:20 +0000285#define EXTRA_SIZE sizeof(MemPage)
drh3b7511c2001-05-26 13:15:44 +0000286
287/*
drha059ad02001-04-17 20:09:11 +0000288** Everything we need to know about an open database
289*/
290struct Btree {
291 Pager *pPager; /* The page cache */
drh306dc212001-05-21 13:45:10 +0000292 BtCursor *pCursor; /* A list of all open cursors */
drh3aac2dd2004-04-26 14:10:20 +0000293 MemPage *pPage1; /* First page of the database */
drh663fc632002-02-02 18:49:19 +0000294 u8 inTrans; /* True if a transaction is in progress */
drhab01f612004-05-22 02:55:23 +0000295 u8 inStmt; /* True if we are in a statement subtransaction */
drh5df72a52002-06-06 23:16:05 +0000296 u8 readOnly; /* True if the underlying file is readonly */
drhab01f612004-05-22 02:55:23 +0000297 u8 maxEmbedFrac; /* Maximum payload as % of total page size */
298 u8 minEmbedFrac; /* Minimum payload as % of total page size */
299 u8 minLeafFrac; /* Minimum leaf payload as % of total page size */
drh90f5ecb2004-07-22 01:19:35 +0000300 u8 pageSizeFixed; /* True if the page size can no longer be changed */
drha2fce642004-06-05 00:01:44 +0000301 u16 pageSize; /* Total number of bytes on a page */
302 u16 usableSize; /* Number of usable bytes on each page */
drh6f11bef2004-05-13 01:12:56 +0000303 int maxLocal; /* Maximum local payload in non-LEAFDATA tables */
304 int minLocal; /* Minimum local payload in non-LEAFDATA tables */
305 int maxLeaf; /* Maximum local payload in a LEAFDATA table */
306 int minLeaf; /* Minimum local payload in a LEAFDATA table */
drha059ad02001-04-17 20:09:11 +0000307};
308typedef Btree Bt;
309
drh365d68f2001-05-11 11:02:46 +0000310/*
danielk1977ee5741e2004-05-31 10:01:34 +0000311** Btree.inTrans may take one of the following values.
312*/
313#define TRANS_NONE 0
314#define TRANS_READ 1
315#define TRANS_WRITE 2
316
317/*
drhfa1a98a2004-05-14 19:08:17 +0000318** An instance of the following structure is used to hold information
drh271efa52004-05-30 19:19:05 +0000319** about a cell. The parseCellPtr() function fills in this structure
drhab01f612004-05-22 02:55:23 +0000320** based on information extract from the raw disk page.
drhfa1a98a2004-05-14 19:08:17 +0000321*/
322typedef struct CellInfo CellInfo;
323struct CellInfo {
drh43605152004-05-29 21:46:49 +0000324 u8 *pCell; /* Pointer to the start of cell content */
drhfa1a98a2004-05-14 19:08:17 +0000325 i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
326 u32 nData; /* Number of bytes of data */
drh271efa52004-05-30 19:19:05 +0000327 u16 nHeader; /* Size of the cell content header in bytes */
drhfa1a98a2004-05-14 19:08:17 +0000328 u16 nLocal; /* Amount of payload held locally */
drhab01f612004-05-22 02:55:23 +0000329 u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
drh271efa52004-05-30 19:19:05 +0000330 u16 nSize; /* Size of the cell content on the main b-tree page */
drhfa1a98a2004-05-14 19:08:17 +0000331};
332
333/*
drh365d68f2001-05-11 11:02:46 +0000334** A cursor is a pointer to a particular entry in the BTree.
335** The entry is identified by its MemPage and the index in
drha34b6762004-05-07 13:30:42 +0000336** MemPage.aCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000337*/
drh72f82862001-05-24 21:06:34 +0000338struct BtCursor {
drh5e2f8b92001-05-28 00:41:15 +0000339 Btree *pBt; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000340 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drh3aac2dd2004-04-26 14:10:20 +0000341 int (*xCompare)(void*,int,const void*,int,const void*); /* Key comp func */
342 void *pArg; /* First arg to xCompare() */
drh8b2f49b2001-06-08 00:21:52 +0000343 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000344 MemPage *pPage; /* Page that contains the entry */
drh3aac2dd2004-04-26 14:10:20 +0000345 int idx; /* Index of the entry in pPage->aCell[] */
drhfa1a98a2004-05-14 19:08:17 +0000346 CellInfo info; /* A parse of the cell we are pointing at */
drhecdc7532001-09-23 02:35:53 +0000347 u8 wrFlag; /* True if writable */
drhc39e0002004-05-07 23:50:57 +0000348 u8 isValid; /* TRUE if points to a valid entry */
349 u8 status; /* Set to SQLITE_ABORT if cursors is invalidated */
drh365d68f2001-05-11 11:02:46 +0000350};
drh7e3b0a02001-04-28 16:52:40 +0000351
drha059ad02001-04-17 20:09:11 +0000352/*
drh66cbd152004-09-01 16:12:25 +0000353** Forward declaration
354*/
355static int checkReadLocks(Btree*,Pgno,BtCursor*);
356
357
358/*
drhab01f612004-05-22 02:55:23 +0000359** Read or write a two- and four-byte big-endian integer values.
drh0d316a42002-08-11 20:10:47 +0000360*/
drh9e572e62004-04-23 23:43:10 +0000361static u32 get2byte(unsigned char *p){
362 return (p[0]<<8) | p[1];
drh0d316a42002-08-11 20:10:47 +0000363}
drh9e572e62004-04-23 23:43:10 +0000364static u32 get4byte(unsigned char *p){
365 return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
366}
drh9e572e62004-04-23 23:43:10 +0000367static void put2byte(unsigned char *p, u32 v){
368 p[0] = v>>8;
369 p[1] = v;
370}
371static void put4byte(unsigned char *p, u32 v){
372 p[0] = v>>24;
373 p[1] = v>>16;
374 p[2] = v>>8;
375 p[3] = v;
376}
drh6f11bef2004-05-13 01:12:56 +0000377
drh9e572e62004-04-23 23:43:10 +0000378/*
drhab01f612004-05-22 02:55:23 +0000379** Routines to read and write variable-length integers. These used to
380** be defined locally, but now we use the varint routines in the util.c
381** file.
drh9e572e62004-04-23 23:43:10 +0000382*/
drh6d2fb152004-05-14 16:50:06 +0000383#define getVarint sqlite3GetVarint
384#define getVarint32 sqlite3GetVarint32
385#define putVarint sqlite3PutVarint
drh0d316a42002-08-11 20:10:47 +0000386
387/*
drh271efa52004-05-30 19:19:05 +0000388** Given a btree page and a cell index (0 means the first cell on
389** the page, 1 means the second cell, and so forth) return a pointer
390** to the cell content.
391**
392** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000393*/
drh43605152004-05-29 21:46:49 +0000394static u8 *findCell(MemPage *pPage, int iCell){
395 u8 *data = pPage->aData;
396 assert( iCell>=0 );
397 assert( iCell<get2byte(&data[pPage->hdrOffset+3]) );
398 return data + get2byte(&data[pPage->cellOffset+2*iCell]);
399}
400
401/*
402** This a more complex version of findCell() that works for
403** pages that do contain overflow cells. See insert
404*/
405static u8 *findOverflowCell(MemPage *pPage, int iCell){
406 int i;
407 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000408 int k;
409 struct _OvflCell *pOvfl;
410 pOvfl = &pPage->aOvfl[i];
411 k = pOvfl->idx;
412 if( k<=iCell ){
413 if( k==iCell ){
414 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000415 }
416 iCell--;
417 }
418 }
419 return findCell(pPage, iCell);
420}
421
422/*
423** Parse a cell content block and fill in the CellInfo structure. There
424** are two versions of this function. parseCell() takes a cell index
425** as the second argument and parseCellPtr() takes a pointer to the
426** body of the cell as its second argument.
427*/
428static void parseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000429 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000430 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000431 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000432){
drh271efa52004-05-30 19:19:05 +0000433 int n; /* Number bytes in cell content header */
434 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000435
436 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000437 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000438 n = pPage->childPtrSize;
439 assert( n==4-4*pPage->leaf );
drh8b18dd42004-05-12 19:18:15 +0000440 if( pPage->hasData ){
drh271efa52004-05-30 19:19:05 +0000441 n += getVarint32(&pCell[n], &nPayload);
drh8b18dd42004-05-12 19:18:15 +0000442 }else{
drh271efa52004-05-30 19:19:05 +0000443 nPayload = 0;
drh3aac2dd2004-04-26 14:10:20 +0000444 }
danielk1977e0d4b062004-06-28 01:11:46 +0000445 n += getVarint(&pCell[n], (u64 *)&pInfo->nKey);
drh6f11bef2004-05-13 01:12:56 +0000446 pInfo->nHeader = n;
drh271efa52004-05-30 19:19:05 +0000447 pInfo->nData = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000448 if( !pPage->intKey ){
449 nPayload += pInfo->nKey;
450 }
drh271efa52004-05-30 19:19:05 +0000451 if( nPayload<=pPage->maxLocal ){
452 /* This is the (easy) common case where the entire payload fits
453 ** on the local page. No overflow is required.
454 */
455 int nSize; /* Total size of cell content in bytes */
drh6f11bef2004-05-13 01:12:56 +0000456 pInfo->nLocal = nPayload;
457 pInfo->iOverflow = 0;
drh271efa52004-05-30 19:19:05 +0000458 nSize = nPayload + n;
459 if( nSize<4 ){
460 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000461 }
drh271efa52004-05-30 19:19:05 +0000462 pInfo->nSize = nSize;
drh6f11bef2004-05-13 01:12:56 +0000463 }else{
drh271efa52004-05-30 19:19:05 +0000464 /* If the payload will not fit completely on the local page, we have
465 ** to decide how much to store locally and how much to spill onto
466 ** overflow pages. The strategy is to minimize the amount of unused
467 ** space on overflow pages while keeping the amount of local storage
468 ** in between minLocal and maxLocal.
469 **
470 ** Warning: changing the way overflow payload is distributed in any
471 ** way will result in an incompatible file format.
472 */
473 int minLocal; /* Minimum amount of payload held locally */
474 int maxLocal; /* Maximum amount of payload held locally */
475 int surplus; /* Overflow payload available for local storage */
476
477 minLocal = pPage->minLocal;
478 maxLocal = pPage->maxLocal;
479 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000480 if( surplus <= maxLocal ){
481 pInfo->nLocal = surplus;
482 }else{
483 pInfo->nLocal = minLocal;
484 }
485 pInfo->iOverflow = pInfo->nLocal + n;
486 pInfo->nSize = pInfo->iOverflow + 4;
487 }
drh3aac2dd2004-04-26 14:10:20 +0000488}
drh43605152004-05-29 21:46:49 +0000489static void parseCell(
490 MemPage *pPage, /* Page containing the cell */
491 int iCell, /* The cell index. First cell is 0 */
492 CellInfo *pInfo /* Fill in this structure */
493){
494 parseCellPtr(pPage, findCell(pPage, iCell), pInfo);
495}
drh3aac2dd2004-04-26 14:10:20 +0000496
497/*
drh43605152004-05-29 21:46:49 +0000498** Compute the total number of bytes that a Cell needs in the cell
499** data area of the btree-page. The return number includes the cell
500** data header and the local payload, but not any overflow page or
501** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000502*/
danielk1977bc6ada42004-06-30 08:20:16 +0000503#ifndef NDEBUG
drh43605152004-05-29 21:46:49 +0000504static int cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000505 CellInfo info;
drh43605152004-05-29 21:46:49 +0000506 parseCell(pPage, iCell, &info);
507 return info.nSize;
508}
danielk1977bc6ada42004-06-30 08:20:16 +0000509#endif
drh43605152004-05-29 21:46:49 +0000510static int cellSizePtr(MemPage *pPage, u8 *pCell){
511 CellInfo info;
512 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000513 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000514}
515
516/*
drhda200cc2004-05-09 11:51:38 +0000517** Do sanity checking on a page. Throw an exception if anything is
518** not right.
519**
520** This routine is used for internal error checking only. It is omitted
521** from most builds.
522*/
523#if defined(BTREE_DEBUG) && !defined(NDEBUG) && 0
524static void _pageIntegrity(MemPage *pPage){
drhb6f41482004-05-14 01:58:11 +0000525 int usableSize;
drhda200cc2004-05-09 11:51:38 +0000526 u8 *data;
drh43605152004-05-29 21:46:49 +0000527 int i, j, idx, c, pc, hdr, nFree;
528 int cellOffset;
529 int nCell, cellLimit;
drh2e38c322004-09-03 18:38:44 +0000530 u8 *used;
drhda200cc2004-05-09 11:51:38 +0000531
drh2e38c322004-09-03 18:38:44 +0000532 used = sqliteMallocRaw( pPage->pBt->pageSize );
533 if( used==0 ) return;
drhb6f41482004-05-14 01:58:11 +0000534 usableSize = pPage->pBt->usableSize;
535 assert( pPage->aData==&((unsigned char*)pPage)[-pPage->pBt->pageSize] );
drhda200cc2004-05-09 11:51:38 +0000536 hdr = pPage->hdrOffset;
537 assert( hdr==(pPage->pgno==1 ? 100 : 0) );
538 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
539 c = pPage->aData[hdr];
540 if( pPage->isInit ){
541 assert( pPage->leaf == ((c & PTF_LEAF)!=0) );
542 assert( pPage->zeroData == ((c & PTF_ZERODATA)!=0) );
drh8b18dd42004-05-12 19:18:15 +0000543 assert( pPage->leafData == ((c & PTF_LEAFDATA)!=0) );
544 assert( pPage->intKey == ((c & (PTF_INTKEY|PTF_LEAFDATA))!=0) );
545 assert( pPage->hasData ==
546 !(pPage->zeroData || (!pPage->leaf && pPage->leafData)) );
drh43605152004-05-29 21:46:49 +0000547 assert( pPage->cellOffset==pPage->hdrOffset+12-4*pPage->leaf );
548 assert( pPage->nCell = get2byte(&pPage->aData[hdr+3]) );
drhda200cc2004-05-09 11:51:38 +0000549 }
550 data = pPage->aData;
drhb6f41482004-05-14 01:58:11 +0000551 memset(used, 0, usableSize);
drhda200cc2004-05-09 11:51:38 +0000552 for(i=0; i<hdr+10-pPage->leaf*4; i++) used[i] = 1;
553 nFree = 0;
554 pc = get2byte(&data[hdr+1]);
555 while( pc ){
556 int size;
drhb6f41482004-05-14 01:58:11 +0000557 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +0000558 size = get2byte(&data[pc+2]);
drhb6f41482004-05-14 01:58:11 +0000559 assert( pc+size<=usableSize );
drhda200cc2004-05-09 11:51:38 +0000560 nFree += size;
561 for(i=pc; i<pc+size; i++){
562 assert( used[i]==0 );
563 used[i] = 1;
564 }
565 pc = get2byte(&data[pc]);
566 }
drhda200cc2004-05-09 11:51:38 +0000567 idx = 0;
drh43605152004-05-29 21:46:49 +0000568 nCell = get2byte(&data[hdr+3]);
569 cellLimit = get2byte(&data[hdr+5]);
570 assert( pPage->isInit==0
571 || pPage->nFree==nFree+data[hdr+7]+cellLimit-(cellOffset+2*nCell) );
572 cellOffset = pPage->cellOffset;
573 for(i=0; i<nCell; i++){
drhda200cc2004-05-09 11:51:38 +0000574 int size;
drh43605152004-05-29 21:46:49 +0000575 pc = get2byte(&data[cellOffset+2*i]);
drhb6f41482004-05-14 01:58:11 +0000576 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +0000577 size = cellSize(pPage, &data[pc]);
drhb6f41482004-05-14 01:58:11 +0000578 assert( pc+size<=usableSize );
drh43605152004-05-29 21:46:49 +0000579 for(j=pc; j<pc+size; j++){
580 assert( used[j]==0 );
581 used[j] = 1;
drhda200cc2004-05-09 11:51:38 +0000582 }
drhda200cc2004-05-09 11:51:38 +0000583 }
drh43605152004-05-29 21:46:49 +0000584 for(i=cellOffset+2*nCell; i<cellimit; i++){
585 assert( used[i]==0 );
586 used[i] = 1;
587 }
drhda200cc2004-05-09 11:51:38 +0000588 nFree = 0;
drhb6f41482004-05-14 01:58:11 +0000589 for(i=0; i<usableSize; i++){
drhda200cc2004-05-09 11:51:38 +0000590 assert( used[i]<=1 );
591 if( used[i]==0 ) nFree++;
592 }
drh43605152004-05-29 21:46:49 +0000593 assert( nFree==data[hdr+7] );
drh2e38c322004-09-03 18:38:44 +0000594 sqliteFree(used);
drhda200cc2004-05-09 11:51:38 +0000595}
596#define pageIntegrity(X) _pageIntegrity(X)
597#else
598# define pageIntegrity(X)
599#endif
600
601/*
drh72f82862001-05-24 21:06:34 +0000602** Defragment the page given. All Cells are moved to the
603** beginning of the page and all free space is collected
604** into one big FreeBlk at the end of the page.
drh365d68f2001-05-11 11:02:46 +0000605*/
drh2e38c322004-09-03 18:38:44 +0000606static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000607 int i; /* Loop counter */
608 int pc; /* Address of a i-th cell */
609 int addr; /* Offset of first byte after cell pointer array */
610 int hdr; /* Offset to the page header */
611 int size; /* Size of a cell */
612 int usableSize; /* Number of usable bytes on a page */
613 int cellOffset; /* Offset to the cell pointer array */
614 int brk; /* Offset to the cell content area */
615 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +0000616 unsigned char *data; /* The page data */
617 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +0000618
drha34b6762004-05-07 13:30:42 +0000619 assert( sqlite3pager_iswriteable(pPage->aData) );
drh9e572e62004-04-23 23:43:10 +0000620 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +0000621 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000622 assert( pPage->nOverflow==0 );
drh2e38c322004-09-03 18:38:44 +0000623 temp = sqliteMalloc( pPage->pBt->pageSize );
624 if( temp==0 ) return SQLITE_NOMEM;
drh43605152004-05-29 21:46:49 +0000625 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000626 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000627 cellOffset = pPage->cellOffset;
628 nCell = pPage->nCell;
629 assert( nCell==get2byte(&data[hdr+3]) );
630 usableSize = pPage->pBt->usableSize;
631 brk = get2byte(&data[hdr+5]);
632 memcpy(&temp[brk], &data[brk], usableSize - brk);
633 brk = usableSize;
634 for(i=0; i<nCell; i++){
635 u8 *pAddr; /* The i-th cell pointer */
636 pAddr = &data[cellOffset + i*2];
637 pc = get2byte(pAddr);
638 assert( pc<pPage->pBt->usableSize );
639 size = cellSizePtr(pPage, &temp[pc]);
640 brk -= size;
641 memcpy(&data[brk], &temp[pc], size);
642 put2byte(pAddr, brk);
drh2af926b2001-05-15 00:39:25 +0000643 }
drh43605152004-05-29 21:46:49 +0000644 assert( brk>=cellOffset+2*nCell );
645 put2byte(&data[hdr+5], brk);
646 data[hdr+1] = 0;
647 data[hdr+2] = 0;
648 data[hdr+7] = 0;
649 addr = cellOffset+2*nCell;
650 memset(&data[addr], 0, brk-addr);
drh2e38c322004-09-03 18:38:44 +0000651 sqliteFree(temp);
652 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +0000653}
654
drha059ad02001-04-17 20:09:11 +0000655/*
drh43605152004-05-29 21:46:49 +0000656** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +0000657**
drh9e572e62004-04-23 23:43:10 +0000658** Return the index into pPage->aData[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000659** the new allocation. Or return 0 if there is not enough free
660** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000661**
drh72f82862001-05-24 21:06:34 +0000662** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000663** nBytes of contiguous free space, then this routine automatically
664** calls defragementPage() to consolidate all free space before
665** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000666*/
drh9e572e62004-04-23 23:43:10 +0000667static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +0000668 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +0000669 int size;
drh24cd67e2004-05-10 16:18:47 +0000670 int nFrag;
drh43605152004-05-29 21:46:49 +0000671 int top;
672 int nCell;
673 int cellOffset;
drh9e572e62004-04-23 23:43:10 +0000674 unsigned char *data;
drh43605152004-05-29 21:46:49 +0000675
drh9e572e62004-04-23 23:43:10 +0000676 data = pPage->aData;
drha34b6762004-05-07 13:30:42 +0000677 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +0000678 assert( pPage->pBt );
679 if( nByte<4 ) nByte = 4;
drh43605152004-05-29 21:46:49 +0000680 if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
681 pPage->nFree -= nByte;
drh9e572e62004-04-23 23:43:10 +0000682 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000683
684 nFrag = data[hdr+7];
685 if( nFrag<60 ){
686 /* Search the freelist looking for a slot big enough to satisfy the
687 ** space request. */
688 addr = hdr+1;
689 while( (pc = get2byte(&data[addr]))>0 ){
690 size = get2byte(&data[pc+2]);
691 if( size>=nByte ){
692 if( size<nByte+4 ){
693 memcpy(&data[addr], &data[pc], 2);
694 data[hdr+7] = nFrag + size - nByte;
695 return pc;
696 }else{
697 put2byte(&data[pc+2], size-nByte);
698 return pc + size - nByte;
699 }
700 }
701 addr = pc;
drh9e572e62004-04-23 23:43:10 +0000702 }
703 }
drh43605152004-05-29 21:46:49 +0000704
705 /* Allocate memory from the gap in between the cell pointer array
706 ** and the cell content area.
707 */
708 top = get2byte(&data[hdr+5]);
709 nCell = get2byte(&data[hdr+3]);
710 cellOffset = pPage->cellOffset;
711 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
drh2e38c322004-09-03 18:38:44 +0000712 if( defragmentPage(pPage) ) return 0;
drh43605152004-05-29 21:46:49 +0000713 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +0000714 }
drh43605152004-05-29 21:46:49 +0000715 top -= nByte;
716 assert( cellOffset + 2*nCell <= top );
717 put2byte(&data[hdr+5], top);
718 return top;
drh7e3b0a02001-04-28 16:52:40 +0000719}
720
721/*
drh9e572e62004-04-23 23:43:10 +0000722** Return a section of the pPage->aData to the freelist.
723** The first byte of the new free block is pPage->aDisk[start]
724** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +0000725**
726** Most of the effort here is involved in coalesing adjacent
727** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000728*/
drh9e572e62004-04-23 23:43:10 +0000729static void freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +0000730 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +0000731 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +0000732
drh9e572e62004-04-23 23:43:10 +0000733 assert( pPage->pBt!=0 );
drha34b6762004-05-07 13:30:42 +0000734 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +0000735 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +0000736 assert( (start + size)<=pPage->pBt->usableSize );
drh9e572e62004-04-23 23:43:10 +0000737 if( size<4 ) size = 4;
738
739 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +0000740 hdr = pPage->hdrOffset;
741 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +0000742 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +0000743 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000744 assert( pbegin>addr );
745 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +0000746 }
drhb6f41482004-05-14 01:58:11 +0000747 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000748 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +0000749 put2byte(&data[addr], start);
750 put2byte(&data[start], pbegin);
751 put2byte(&data[start+2], size);
drh2af926b2001-05-15 00:39:25 +0000752 pPage->nFree += size;
drh9e572e62004-04-23 23:43:10 +0000753
754 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +0000755 addr = pPage->hdrOffset + 1;
756 while( (pbegin = get2byte(&data[addr]))>0 ){
drh9e572e62004-04-23 23:43:10 +0000757 int pnext, psize;
drh3aac2dd2004-04-26 14:10:20 +0000758 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +0000759 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +0000760 pnext = get2byte(&data[pbegin]);
761 psize = get2byte(&data[pbegin+2]);
762 if( pbegin + psize + 3 >= pnext && pnext>0 ){
763 int frag = pnext - (pbegin+psize);
drh43605152004-05-29 21:46:49 +0000764 assert( frag<=data[pPage->hdrOffset+7] );
765 data[pPage->hdrOffset+7] -= frag;
drh9e572e62004-04-23 23:43:10 +0000766 put2byte(&data[pbegin], get2byte(&data[pnext]));
767 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
768 }else{
drh3aac2dd2004-04-26 14:10:20 +0000769 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +0000770 }
771 }
drh7e3b0a02001-04-28 16:52:40 +0000772
drh43605152004-05-29 21:46:49 +0000773 /* If the cell content area begins with a freeblock, remove it. */
774 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
775 int top;
776 pbegin = get2byte(&data[hdr+1]);
777 memcpy(&data[hdr+1], &data[pbegin], 2);
778 top = get2byte(&data[hdr+5]);
779 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
drh4b70f112004-05-02 21:12:19 +0000780 }
drh4b70f112004-05-02 21:12:19 +0000781}
782
783/*
drh271efa52004-05-30 19:19:05 +0000784** Decode the flags byte (the first byte of the header) for a page
785** and initialize fields of the MemPage structure accordingly.
786*/
787static void decodeFlags(MemPage *pPage, int flagByte){
788 Btree *pBt; /* A copy of pPage->pBt */
789
790 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
791 pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
792 pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
793 pPage->leaf = (flagByte & PTF_LEAF)!=0;
794 pPage->childPtrSize = 4*(pPage->leaf==0);
795 pBt = pPage->pBt;
796 if( flagByte & PTF_LEAFDATA ){
797 pPage->leafData = 1;
798 pPage->maxLocal = pBt->maxLeaf;
799 pPage->minLocal = pBt->minLeaf;
800 }else{
801 pPage->leafData = 0;
802 pPage->maxLocal = pBt->maxLocal;
803 pPage->minLocal = pBt->minLocal;
804 }
805 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
806}
807
808/*
drh7e3b0a02001-04-28 16:52:40 +0000809** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000810**
drhbd03cae2001-06-02 02:40:57 +0000811** The pParent parameter must be a pointer to the MemPage which
drh9e572e62004-04-23 23:43:10 +0000812** is the parent of the page being initialized. The root of a
813** BTree has no parent and so for that page, pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000814**
drh72f82862001-05-24 21:06:34 +0000815** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +0000816** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +0000817** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
818** guarantee that the page is well-formed. It only shows that
819** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000820*/
drh9e572e62004-04-23 23:43:10 +0000821static int initPage(
drh3aac2dd2004-04-26 14:10:20 +0000822 MemPage *pPage, /* The page to be initialized */
drh9e572e62004-04-23 23:43:10 +0000823 MemPage *pParent /* The parent. Might be NULL */
824){
drh271efa52004-05-30 19:19:05 +0000825 int pc; /* Address of a freeblock within pPage->aData[] */
826 int i; /* Loop counter */
827 int hdr; /* Offset to beginning of page header */
828 u8 *data; /* Equal to pPage->aData */
drh2e38c322004-09-03 18:38:44 +0000829 Btree *pBt; /* The main btree structure */
drh271efa52004-05-30 19:19:05 +0000830 int usableSize; /* Amount of usable space on each page */
831 int cellOffset; /* Offset from start of page to first cell pointer */
832 int nFree; /* Number of unused bytes on the page */
833 int top; /* First byte of the cell content area */
drh2af926b2001-05-15 00:39:25 +0000834
drh2e38c322004-09-03 18:38:44 +0000835 pBt = pPage->pBt;
836 assert( pBt!=0 );
837 assert( pParent==0 || pParent->pBt==pBt );
drha34b6762004-05-07 13:30:42 +0000838 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
drh2e38c322004-09-03 18:38:44 +0000839 assert( pPage->aData == &((unsigned char*)pPage)[-pBt->pageSize] );
drhee696e22004-08-30 16:52:17 +0000840 if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
841 /* The parent page should never change unless the file is corrupt */
842 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
843 }
drh10617cd2004-05-14 15:27:27 +0000844 if( pPage->isInit ) return SQLITE_OK;
drhda200cc2004-05-09 11:51:38 +0000845 if( pPage->pParent==0 && pParent!=0 ){
846 pPage->pParent = pParent;
drha34b6762004-05-07 13:30:42 +0000847 sqlite3pager_ref(pParent->aData);
drh5e2f8b92001-05-28 00:41:15 +0000848 }
drhde647132004-05-07 17:57:49 +0000849 hdr = pPage->hdrOffset;
drha34b6762004-05-07 13:30:42 +0000850 data = pPage->aData;
drh271efa52004-05-30 19:19:05 +0000851 decodeFlags(pPage, data[hdr]);
drh43605152004-05-29 21:46:49 +0000852 pPage->nOverflow = 0;
drhc8629a12004-05-08 20:07:40 +0000853 pPage->idxShift = 0;
drh2e38c322004-09-03 18:38:44 +0000854 usableSize = pBt->usableSize;
drh43605152004-05-29 21:46:49 +0000855 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
856 top = get2byte(&data[hdr+5]);
857 pPage->nCell = get2byte(&data[hdr+3]);
drh2e38c322004-09-03 18:38:44 +0000858 if( pPage->nCell>MX_CELL(pBt) ){
drhee696e22004-08-30 16:52:17 +0000859 /* To many cells for a single page. The page must be corrupt */
860 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
861 }
862 if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
863 /* All pages must have at least one cell, except for root pages */
864 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
865 }
drh9e572e62004-04-23 23:43:10 +0000866
867 /* Compute the total free space on the page */
drh9e572e62004-04-23 23:43:10 +0000868 pc = get2byte(&data[hdr+1]);
drh43605152004-05-29 21:46:49 +0000869 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
drh3add3672004-05-15 00:29:24 +0000870 i = 0;
drh9e572e62004-04-23 23:43:10 +0000871 while( pc>0 ){
872 int next, size;
drhee696e22004-08-30 16:52:17 +0000873 if( pc>usableSize-4 ){
874 /* Free block is off the page */
875 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
876 }
877 if( i++>SQLITE_MAX_PAGE_SIZE/4 ){
878 /* The free block list forms an infinite loop */
879 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
880 }
drh9e572e62004-04-23 23:43:10 +0000881 next = get2byte(&data[pc]);
882 size = get2byte(&data[pc+2]);
drhee696e22004-08-30 16:52:17 +0000883 if( next>0 && next<=pc+size+3 ){
884 /* Free blocks must be in accending order */
885 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
886 }
drh3add3672004-05-15 00:29:24 +0000887 nFree += size;
drh9e572e62004-04-23 23:43:10 +0000888 pc = next;
889 }
drh3add3672004-05-15 00:29:24 +0000890 pPage->nFree = nFree;
drhee696e22004-08-30 16:52:17 +0000891 if( nFree>=usableSize ){
892 /* Free space cannot exceed total page size */
893 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
894 }
drh9e572e62004-04-23 23:43:10 +0000895
drhde647132004-05-07 17:57:49 +0000896 pPage->isInit = 1;
drhda200cc2004-05-09 11:51:38 +0000897 pageIntegrity(pPage);
drh9e572e62004-04-23 23:43:10 +0000898 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +0000899}
900
901/*
drh8b2f49b2001-06-08 00:21:52 +0000902** Set up a raw page so that it looks like a database page holding
903** no entries.
drhbd03cae2001-06-02 02:40:57 +0000904*/
drh9e572e62004-04-23 23:43:10 +0000905static void zeroPage(MemPage *pPage, int flags){
906 unsigned char *data = pPage->aData;
907 Btree *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +0000908 int hdr = pPage->hdrOffset;
drh9e572e62004-04-23 23:43:10 +0000909 int first;
910
drhda200cc2004-05-09 11:51:38 +0000911 assert( sqlite3pager_pagenumber(data)==pPage->pgno );
912 assert( &data[pBt->pageSize] == (unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +0000913 assert( sqlite3pager_iswriteable(data) );
drhb6f41482004-05-14 01:58:11 +0000914 memset(&data[hdr], 0, pBt->usableSize - hdr);
drh9e572e62004-04-23 23:43:10 +0000915 data[hdr] = flags;
drh43605152004-05-29 21:46:49 +0000916 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
917 memset(&data[hdr+1], 0, 4);
918 data[hdr+7] = 0;
919 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +0000920 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +0000921 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +0000922 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +0000923 pPage->cellOffset = first;
924 pPage->nOverflow = 0;
drhda200cc2004-05-09 11:51:38 +0000925 pPage->idxShift = 0;
drh43605152004-05-29 21:46:49 +0000926 pPage->nCell = 0;
drhda200cc2004-05-09 11:51:38 +0000927 pPage->isInit = 1;
928 pageIntegrity(pPage);
drhbd03cae2001-06-02 02:40:57 +0000929}
930
931/*
drh3aac2dd2004-04-26 14:10:20 +0000932** Get a page from the pager. Initialize the MemPage.pBt and
933** MemPage.aData elements if needed.
934*/
935static int getPage(Btree *pBt, Pgno pgno, MemPage **ppPage){
936 int rc;
937 unsigned char *aData;
938 MemPage *pPage;
drha34b6762004-05-07 13:30:42 +0000939 rc = sqlite3pager_get(pBt->pPager, pgno, (void**)&aData);
drh3aac2dd2004-04-26 14:10:20 +0000940 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +0000941 pPage = (MemPage*)&aData[pBt->pageSize];
drh3aac2dd2004-04-26 14:10:20 +0000942 pPage->aData = aData;
943 pPage->pBt = pBt;
944 pPage->pgno = pgno;
drhde647132004-05-07 17:57:49 +0000945 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
drh3aac2dd2004-04-26 14:10:20 +0000946 *ppPage = pPage;
947 return SQLITE_OK;
948}
949
950/*
drhde647132004-05-07 17:57:49 +0000951** Get a page from the pager and initialize it. This routine
952** is just a convenience wrapper around separate calls to
953** getPage() and initPage().
954*/
955static int getAndInitPage(
956 Btree *pBt, /* The database file */
957 Pgno pgno, /* Number of the page to get */
958 MemPage **ppPage, /* Write the page pointer here */
959 MemPage *pParent /* Parent of the page */
960){
961 int rc;
drhee696e22004-08-30 16:52:17 +0000962 if( pgno==0 ){
963 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
964 }
drhde647132004-05-07 17:57:49 +0000965 rc = getPage(pBt, pgno, ppPage);
drh10617cd2004-05-14 15:27:27 +0000966 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
drhde647132004-05-07 17:57:49 +0000967 rc = initPage(*ppPage, pParent);
968 }
969 return rc;
970}
971
972/*
drh3aac2dd2004-04-26 14:10:20 +0000973** Release a MemPage. This should be called once for each prior
974** call to getPage.
975*/
drh4b70f112004-05-02 21:12:19 +0000976static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +0000977 if( pPage ){
978 assert( pPage->aData );
979 assert( pPage->pBt );
980 assert( &pPage->aData[pPage->pBt->pageSize]==(unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +0000981 sqlite3pager_unref(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +0000982 }
983}
984
985/*
drh72f82862001-05-24 21:06:34 +0000986** This routine is called when the reference count for a page
987** reaches zero. We need to unref the pParent pointer when that
988** happens.
989*/
drhb6f41482004-05-14 01:58:11 +0000990static void pageDestructor(void *pData, int pageSize){
991 MemPage *pPage = (MemPage*)&((char*)pData)[pageSize];
drh72f82862001-05-24 21:06:34 +0000992 if( pPage->pParent ){
993 MemPage *pParent = pPage->pParent;
994 pPage->pParent = 0;
drha34b6762004-05-07 13:30:42 +0000995 releasePage(pParent);
drh72f82862001-05-24 21:06:34 +0000996 }
drh3aac2dd2004-04-26 14:10:20 +0000997 pPage->isInit = 0;
drh72f82862001-05-24 21:06:34 +0000998}
999
1000/*
drha6abd042004-06-09 17:37:22 +00001001** During a rollback, when the pager reloads information into the cache
1002** so that the cache is restored to its original state at the start of
1003** the transaction, for each page restored this routine is called.
1004**
1005** This routine needs to reset the extra data section at the end of the
1006** page to agree with the restored data.
1007*/
1008static void pageReinit(void *pData, int pageSize){
1009 MemPage *pPage = (MemPage*)&((char*)pData)[pageSize];
1010 if( pPage->isInit ){
1011 pPage->isInit = 0;
1012 initPage(pPage, pPage->pParent);
1013 }
1014}
1015
1016/*
drhad3e0102004-09-03 23:32:18 +00001017** Open a database file.
1018**
drh382c0242001-10-06 16:33:02 +00001019** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001020** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001021** database file will be deleted when sqlite3BtreeClose() is called.
drha059ad02001-04-17 20:09:11 +00001022*/
drh23e11ca2004-05-04 17:27:28 +00001023int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001024 const char *zFilename, /* Name of the file containing the BTree database */
1025 Btree **ppBtree, /* Pointer to new Btree object written here */
drh90f5ecb2004-07-22 01:19:35 +00001026 int flags /* Options */
drh6019e162001-07-02 17:51:45 +00001027){
drha059ad02001-04-17 20:09:11 +00001028 Btree *pBt;
drha34b6762004-05-07 13:30:42 +00001029 int rc;
drh90f5ecb2004-07-22 01:19:35 +00001030 int nReserve;
1031 unsigned char zDbHeader[100];
drha059ad02001-04-17 20:09:11 +00001032
drhd62d3d02003-01-24 12:14:20 +00001033 /*
1034 ** The following asserts make sure that structures used by the btree are
1035 ** the right size. This is to guard against size changes that result
1036 ** when compiling on a different architecture.
1037 */
drh4a1c3802004-05-12 15:15:47 +00001038 assert( sizeof(i64)==8 );
drh9e572e62004-04-23 23:43:10 +00001039 assert( sizeof(u64)==8 );
drhd62d3d02003-01-24 12:14:20 +00001040 assert( sizeof(u32)==4 );
1041 assert( sizeof(u16)==2 );
1042 assert( sizeof(Pgno)==4 );
drhd62d3d02003-01-24 12:14:20 +00001043 assert( sizeof(ptr)==sizeof(char*) );
1044 assert( sizeof(uptr)==sizeof(ptr) );
1045
drha059ad02001-04-17 20:09:11 +00001046 pBt = sqliteMalloc( sizeof(*pBt) );
1047 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +00001048 *ppBtree = 0;
drha059ad02001-04-17 20:09:11 +00001049 return SQLITE_NOMEM;
1050 }
drh90f5ecb2004-07-22 01:19:35 +00001051 rc = sqlite3pager_open(&pBt->pPager, zFilename, EXTRA_SIZE,
1052 (flags & BTREE_OMIT_JOURNAL)==0);
drha059ad02001-04-17 20:09:11 +00001053 if( rc!=SQLITE_OK ){
drha34b6762004-05-07 13:30:42 +00001054 if( pBt->pPager ) sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001055 sqliteFree(pBt);
1056 *ppBtree = 0;
1057 return rc;
1058 }
drha34b6762004-05-07 13:30:42 +00001059 sqlite3pager_set_destructor(pBt->pPager, pageDestructor);
drha6abd042004-06-09 17:37:22 +00001060 sqlite3pager_set_reiniter(pBt->pPager, pageReinit);
drha059ad02001-04-17 20:09:11 +00001061 pBt->pCursor = 0;
drha34b6762004-05-07 13:30:42 +00001062 pBt->pPage1 = 0;
1063 pBt->readOnly = sqlite3pager_isreadonly(pBt->pPager);
drh90f5ecb2004-07-22 01:19:35 +00001064 sqlite3pager_read_fileheader(pBt->pPager, sizeof(zDbHeader), zDbHeader);
1065 pBt->pageSize = get2byte(&zDbHeader[16]);
1066 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE ){
1067 pBt->pageSize = SQLITE_DEFAULT_PAGE_SIZE;
1068 pBt->maxEmbedFrac = 64; /* 25% */
1069 pBt->minEmbedFrac = 32; /* 12.5% */
1070 pBt->minLeafFrac = 32; /* 12.5% */
1071 nReserve = 0;
1072 }else{
1073 nReserve = zDbHeader[20];
1074 pBt->maxEmbedFrac = zDbHeader[21];
1075 pBt->minEmbedFrac = zDbHeader[22];
1076 pBt->minLeafFrac = zDbHeader[23];
1077 pBt->pageSizeFixed = 1;
1078 }
1079 pBt->usableSize = pBt->pageSize - nReserve;
1080 sqlite3pager_set_pagesize(pBt->pPager, pBt->pageSize);
drha059ad02001-04-17 20:09:11 +00001081 *ppBtree = pBt;
1082 return SQLITE_OK;
1083}
1084
1085/*
1086** Close an open database and invalidate all cursors.
1087*/
drh3aac2dd2004-04-26 14:10:20 +00001088int sqlite3BtreeClose(Btree *pBt){
drha059ad02001-04-17 20:09:11 +00001089 while( pBt->pCursor ){
drh3aac2dd2004-04-26 14:10:20 +00001090 sqlite3BtreeCloseCursor(pBt->pCursor);
drha059ad02001-04-17 20:09:11 +00001091 }
drha34b6762004-05-07 13:30:42 +00001092 sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001093 sqliteFree(pBt);
1094 return SQLITE_OK;
1095}
1096
1097/*
drh90f5ecb2004-07-22 01:19:35 +00001098** Change the busy handler callback function.
1099*/
1100int sqlite3BtreeSetBusyHandler(Btree *pBt, BusyHandler *pHandler){
1101 sqlite3pager_set_busyhandler(pBt->pPager, pHandler);
1102 return SQLITE_OK;
1103}
1104
1105/*
drhda47d772002-12-02 04:25:19 +00001106** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001107**
1108** The maximum number of cache pages is set to the absolute
1109** value of mxPage. If mxPage is negative, the pager will
1110** operate asynchronously - it will not stop to do fsync()s
1111** to insure data is written to the disk surface before
1112** continuing. Transactions still work if synchronous is off,
1113** and the database cannot be corrupted if this program
1114** crashes. But if the operating system crashes or there is
1115** an abrupt power failure when synchronous is off, the database
1116** could be left in an inconsistent and unrecoverable state.
1117** Synchronous is on by default so database corruption is not
1118** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001119*/
drh23e11ca2004-05-04 17:27:28 +00001120int sqlite3BtreeSetCacheSize(Btree *pBt, int mxPage){
drha34b6762004-05-07 13:30:42 +00001121 sqlite3pager_set_cachesize(pBt->pPager, mxPage);
drhf57b14a2001-09-14 18:54:08 +00001122 return SQLITE_OK;
1123}
1124
1125/*
drh973b6e32003-02-12 14:09:42 +00001126** Change the way data is synced to disk in order to increase or decrease
1127** how well the database resists damage due to OS crashes and power
1128** failures. Level 1 is the same as asynchronous (no syncs() occur and
1129** there is a high probability of damage) Level 2 is the default. There
1130** is a very low but non-zero probability of damage. Level 3 reduces the
1131** probability of damage to near zero but with a write performance reduction.
1132*/
drh3aac2dd2004-04-26 14:10:20 +00001133int sqlite3BtreeSetSafetyLevel(Btree *pBt, int level){
drha34b6762004-05-07 13:30:42 +00001134 sqlite3pager_set_safety_level(pBt->pPager, level);
drh973b6e32003-02-12 14:09:42 +00001135 return SQLITE_OK;
1136}
1137
1138/*
drh90f5ecb2004-07-22 01:19:35 +00001139** Change the default pages size and the number of reserved bytes per page.
1140*/
1141int sqlite3BtreeSetPageSize(Btree *pBt, int pageSize, int nReserve){
1142 if( pBt->pageSizeFixed ){
1143 return SQLITE_READONLY;
1144 }
1145 if( nReserve<0 ){
1146 nReserve = pBt->pageSize - pBt->usableSize;
1147 }
drhf2a611c2004-09-05 00:33:43 +00001148 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE ){
drh90f5ecb2004-07-22 01:19:35 +00001149 pBt->pageSize = pageSize;
1150 sqlite3pager_set_pagesize(pBt->pPager, pageSize);
1151 }
1152 pBt->usableSize = pBt->pageSize - nReserve;
1153 return SQLITE_OK;
1154}
1155
1156/*
1157** Return the currently defined page size
1158*/
1159int sqlite3BtreeGetPageSize(Btree *pBt){
1160 return pBt->pageSize;
1161}
drh2011d5f2004-07-22 02:40:37 +00001162int sqlite3BtreeGetReserve(Btree *pBt){
1163 return pBt->pageSize - pBt->usableSize;
1164}
drh90f5ecb2004-07-22 01:19:35 +00001165
1166/*
drha34b6762004-05-07 13:30:42 +00001167** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001168** also acquire a readlock on that file.
1169**
1170** SQLITE_OK is returned on success. If the file is not a
1171** well-formed database file, then SQLITE_CORRUPT is returned.
1172** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
1173** is returned if we run out of memory. SQLITE_PROTOCOL is returned
1174** if there is a locking protocol violation.
1175*/
1176static int lockBtree(Btree *pBt){
1177 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001178 MemPage *pPage1;
drha34b6762004-05-07 13:30:42 +00001179 if( pBt->pPage1 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001180 rc = getPage(pBt, 1, &pPage1);
drh306dc212001-05-21 13:45:10 +00001181 if( rc!=SQLITE_OK ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00001182
drh306dc212001-05-21 13:45:10 +00001183
1184 /* Do some checking to help insure the file we opened really is
1185 ** a valid database file.
1186 */
drhb6f41482004-05-14 01:58:11 +00001187 rc = SQLITE_NOTADB;
drha34b6762004-05-07 13:30:42 +00001188 if( sqlite3pager_pagecount(pBt->pPager)>0 ){
drhb6f41482004-05-14 01:58:11 +00001189 u8 *page1 = pPage1->aData;
1190 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001191 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001192 }
drhb6f41482004-05-14 01:58:11 +00001193 if( page1[18]>1 || page1[19]>1 ){
1194 goto page1_init_failed;
1195 }
1196 pBt->pageSize = get2byte(&page1[16]);
1197 pBt->usableSize = pBt->pageSize - page1[20];
1198 if( pBt->usableSize<500 ){
1199 goto page1_init_failed;
1200 }
1201 pBt->maxEmbedFrac = page1[21];
1202 pBt->minEmbedFrac = page1[22];
1203 pBt->minLeafFrac = page1[23];
drh306dc212001-05-21 13:45:10 +00001204 }
drhb6f41482004-05-14 01:58:11 +00001205
1206 /* maxLocal is the maximum amount of payload to store locally for
1207 ** a cell. Make sure it is small enough so that at least minFanout
1208 ** cells can will fit on one page. We assume a 10-byte page header.
1209 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001210 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001211 ** 4-byte child pointer
1212 ** 9-byte nKey value
1213 ** 4-byte nData value
1214 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001215 ** So a cell consists of a 2-byte poiner, a header which is as much as
1216 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1217 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001218 */
drh43605152004-05-29 21:46:49 +00001219 pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
1220 pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
1221 pBt->maxLeaf = pBt->usableSize - 35;
1222 pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
drhb6f41482004-05-14 01:58:11 +00001223 if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
1224 goto page1_init_failed;
1225 }
drh2e38c322004-09-03 18:38:44 +00001226 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001227 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001228 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001229
drh72f82862001-05-24 21:06:34 +00001230page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001231 releasePage(pPage1);
1232 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001233 return rc;
drh306dc212001-05-21 13:45:10 +00001234}
1235
1236/*
drhb8ca3072001-12-05 00:21:20 +00001237** If there are no outstanding cursors and we are not in the middle
1238** of a transaction but there is a read lock on the database, then
1239** this routine unrefs the first page of the database file which
1240** has the effect of releasing the read lock.
1241**
1242** If there are any outstanding cursors, this routine is a no-op.
1243**
1244** If there is a transaction in progress, this routine is a no-op.
1245*/
1246static void unlockBtreeIfUnused(Btree *pBt){
danielk1977ee5741e2004-05-31 10:01:34 +00001247 if( pBt->inTrans==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
drh51c6d962004-06-06 00:42:25 +00001248 if( pBt->pPage1->aData==0 ){
1249 MemPage *pPage = pBt->pPage1;
1250 pPage->aData = &((char*)pPage)[-pBt->pageSize];
1251 pPage->pBt = pBt;
1252 pPage->pgno = 1;
1253 }
drh3aac2dd2004-04-26 14:10:20 +00001254 releasePage(pBt->pPage1);
1255 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00001256 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001257 }
1258}
1259
1260/*
drh9e572e62004-04-23 23:43:10 +00001261** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001262** file.
drh8b2f49b2001-06-08 00:21:52 +00001263*/
1264static int newDatabase(Btree *pBt){
drh9e572e62004-04-23 23:43:10 +00001265 MemPage *pP1;
1266 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001267 int rc;
drhde647132004-05-07 17:57:49 +00001268 if( sqlite3pager_pagecount(pBt->pPager)>0 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001269 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00001270 assert( pP1!=0 );
1271 data = pP1->aData;
drha34b6762004-05-07 13:30:42 +00001272 rc = sqlite3pager_write(data);
drh8b2f49b2001-06-08 00:21:52 +00001273 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00001274 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
1275 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00001276 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00001277 data[18] = 1;
1278 data[19] = 1;
drhb6f41482004-05-14 01:58:11 +00001279 data[20] = pBt->pageSize - pBt->usableSize;
1280 data[21] = pBt->maxEmbedFrac;
1281 data[22] = pBt->minEmbedFrac;
1282 data[23] = pBt->minLeafFrac;
1283 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00001284 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00001285 pBt->pageSizeFixed = 1;
drh8b2f49b2001-06-08 00:21:52 +00001286 return SQLITE_OK;
1287}
1288
1289/*
danielk1977ee5741e2004-05-31 10:01:34 +00001290** Attempt to start a new transaction. A write-transaction
1291** is started if the second argument is true, otherwise a read-
1292** transaction.
drh8b2f49b2001-06-08 00:21:52 +00001293**
danielk1977ee5741e2004-05-31 10:01:34 +00001294** A write-transaction must be started before attempting any
1295** changes to the database. None of the following routines
1296** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00001297**
drh23e11ca2004-05-04 17:27:28 +00001298** sqlite3BtreeCreateTable()
1299** sqlite3BtreeCreateIndex()
1300** sqlite3BtreeClearTable()
1301** sqlite3BtreeDropTable()
1302** sqlite3BtreeInsert()
1303** sqlite3BtreeDelete()
1304** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00001305**
1306** If wrflag is true, then nMaster specifies the maximum length of
1307** a master journal file name supplied later via sqlite3BtreeSync().
1308** This is so that appropriate space can be allocated in the journal file
1309** when it is created..
drha059ad02001-04-17 20:09:11 +00001310*/
danielk197740b38dc2004-06-26 08:38:24 +00001311int sqlite3BtreeBeginTrans(Btree *pBt, int wrflag){
danielk1977ee5741e2004-05-31 10:01:34 +00001312 int rc = SQLITE_OK;
1313
1314 /* If the btree is already in a write-transaction, or it
1315 ** is already in a read-transaction and a read-transaction
1316 ** is requested, this is a no-op.
1317 */
1318 if( pBt->inTrans==TRANS_WRITE ||
1319 (pBt->inTrans==TRANS_READ && !wrflag) ){
1320 return SQLITE_OK;
1321 }
1322 if( pBt->readOnly && wrflag ){
1323 return SQLITE_READONLY;
1324 }
1325
drh3aac2dd2004-04-26 14:10:20 +00001326 if( pBt->pPage1==0 ){
drh7e3b0a02001-04-28 16:52:40 +00001327 rc = lockBtree(pBt);
danielk1977ee5741e2004-05-31 10:01:34 +00001328 }
1329
1330 if( rc==SQLITE_OK && wrflag ){
danielk197740b38dc2004-06-26 08:38:24 +00001331 rc = sqlite3pager_begin(pBt->pPage1->aData);
danielk1977ee5741e2004-05-31 10:01:34 +00001332 if( rc==SQLITE_OK ){
1333 rc = newDatabase(pBt);
drh8c42ca92001-06-22 19:15:00 +00001334 }
drha059ad02001-04-17 20:09:11 +00001335 }
danielk1977ee5741e2004-05-31 10:01:34 +00001336
drhf74b8d92002-09-01 23:20:45 +00001337 if( rc==SQLITE_OK ){
danielk1977ee5741e2004-05-31 10:01:34 +00001338 pBt->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
1339 if( wrflag ) pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001340 }else{
1341 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001342 }
drhb8ca3072001-12-05 00:21:20 +00001343 return rc;
drha059ad02001-04-17 20:09:11 +00001344}
1345
1346/*
drh2aa679f2001-06-25 02:11:07 +00001347** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00001348**
1349** This will release the write lock on the database file. If there
1350** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00001351*/
drh3aac2dd2004-04-26 14:10:20 +00001352int sqlite3BtreeCommit(Btree *pBt){
danielk1977ee5741e2004-05-31 10:01:34 +00001353 int rc = SQLITE_OK;
1354 if( pBt->inTrans==TRANS_WRITE ){
1355 rc = sqlite3pager_commit(pBt->pPager);
1356 }
1357 pBt->inTrans = TRANS_NONE;
drh3aac2dd2004-04-26 14:10:20 +00001358 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00001359 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001360 return rc;
1361}
1362
danielk1977fbcd5852004-06-15 02:44:18 +00001363#ifndef NDEBUG
1364/*
1365** Return the number of write-cursors open on this handle. This is for use
1366** in assert() expressions, so it is only compiled if NDEBUG is not
1367** defined.
1368*/
1369static int countWriteCursors(Btree *pBt){
1370 BtCursor *pCur;
1371 int r = 0;
1372 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1373 if( pCur->wrFlag ) r++;
1374 }
1375 return r;
1376}
1377#endif
1378
1379#if 0
drha059ad02001-04-17 20:09:11 +00001380/*
drhc39e0002004-05-07 23:50:57 +00001381** Invalidate all cursors
1382*/
1383static void invalidateCursors(Btree *pBt){
1384 BtCursor *pCur;
1385 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1386 MemPage *pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00001387 if( pPage /* && !pPage->isInit */ ){
1388 pageIntegrity(pPage);
drhc39e0002004-05-07 23:50:57 +00001389 releasePage(pPage);
1390 pCur->pPage = 0;
1391 pCur->isValid = 0;
1392 pCur->status = SQLITE_ABORT;
1393 }
1394 }
1395}
danielk1977fbcd5852004-06-15 02:44:18 +00001396#endif
drhc39e0002004-05-07 23:50:57 +00001397
drhda200cc2004-05-09 11:51:38 +00001398#ifdef SQLITE_TEST
1399/*
1400** Print debugging information about all cursors to standard output.
1401*/
1402void sqlite3BtreeCursorList(Btree *pBt){
1403 BtCursor *pCur;
1404 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1405 MemPage *pPage = pCur->pPage;
1406 char *zMode = pCur->wrFlag ? "rw" : "ro";
drhfe63d1c2004-09-08 20:13:04 +00001407 sqlite3DebugPrintf("CURSOR %p rooted at %4d(%s) currently at %d.%d%s\n",
1408 pCur, pCur->pgnoRoot, zMode,
drhda200cc2004-05-09 11:51:38 +00001409 pPage ? pPage->pgno : 0, pCur->idx,
1410 pCur->isValid ? "" : " eof"
1411 );
1412 }
1413}
1414#endif
1415
drhc39e0002004-05-07 23:50:57 +00001416/*
drhecdc7532001-09-23 02:35:53 +00001417** Rollback the transaction in progress. All cursors will be
1418** invalided by this operation. Any attempt to use a cursor
1419** that was open at the beginning of this operation will result
1420** in an error.
drh5e00f6c2001-09-13 13:46:56 +00001421**
1422** This will release the write lock on the database file. If there
1423** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00001424*/
drh3aac2dd2004-04-26 14:10:20 +00001425int sqlite3BtreeRollback(Btree *pBt){
danielk1977cfe9a692004-06-16 12:00:29 +00001426 int rc = SQLITE_OK;
drh24cd67e2004-05-10 16:18:47 +00001427 MemPage *pPage1;
danielk1977ee5741e2004-05-31 10:01:34 +00001428 if( pBt->inTrans==TRANS_WRITE ){
drh24cd67e2004-05-10 16:18:47 +00001429 rc = sqlite3pager_rollback(pBt->pPager);
1430 /* The rollback may have destroyed the pPage1->aData value. So
1431 ** call getPage() on page 1 again to make sure pPage1->aData is
1432 ** set correctly. */
1433 if( getPage(pBt, 1, &pPage1)==SQLITE_OK ){
1434 releasePage(pPage1);
1435 }
danielk1977fbcd5852004-06-15 02:44:18 +00001436 assert( countWriteCursors(pBt)==0 );
drh24cd67e2004-05-10 16:18:47 +00001437 }
danielk1977ee5741e2004-05-31 10:01:34 +00001438 pBt->inTrans = TRANS_NONE;
1439 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00001440 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001441 return rc;
1442}
1443
1444/*
drhab01f612004-05-22 02:55:23 +00001445** Start a statement subtransaction. The subtransaction can
1446** can be rolled back independently of the main transaction.
1447** You must start a transaction before starting a subtransaction.
1448** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00001449** commits or rolls back.
1450**
drhab01f612004-05-22 02:55:23 +00001451** Only one subtransaction may be active at a time. It is an error to try
1452** to start a new subtransaction if another subtransaction is already active.
1453**
1454** Statement subtransactions are used around individual SQL statements
1455** that are contained within a BEGIN...COMMIT block. If a constraint
1456** error occurs within the statement, the effect of that one statement
1457** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00001458*/
drh3aac2dd2004-04-26 14:10:20 +00001459int sqlite3BtreeBeginStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00001460 int rc;
danielk1977ee5741e2004-05-31 10:01:34 +00001461 if( (pBt->inTrans!=TRANS_WRITE) || pBt->inStmt ){
drhf74b8d92002-09-01 23:20:45 +00001462 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh0d65dc02002-02-03 00:56:09 +00001463 }
drha34b6762004-05-07 13:30:42 +00001464 rc = pBt->readOnly ? SQLITE_OK : sqlite3pager_stmt_begin(pBt->pPager);
drh3aac2dd2004-04-26 14:10:20 +00001465 pBt->inStmt = 1;
drh663fc632002-02-02 18:49:19 +00001466 return rc;
1467}
1468
1469
1470/*
drhab01f612004-05-22 02:55:23 +00001471** Commit the statment subtransaction currently in progress. If no
1472** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00001473*/
drh3aac2dd2004-04-26 14:10:20 +00001474int sqlite3BtreeCommitStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00001475 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001476 if( pBt->inStmt && !pBt->readOnly ){
drha34b6762004-05-07 13:30:42 +00001477 rc = sqlite3pager_stmt_commit(pBt->pPager);
drh663fc632002-02-02 18:49:19 +00001478 }else{
1479 rc = SQLITE_OK;
1480 }
drh3aac2dd2004-04-26 14:10:20 +00001481 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00001482 return rc;
1483}
1484
1485/*
drhab01f612004-05-22 02:55:23 +00001486** Rollback the active statement subtransaction. If no subtransaction
1487** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00001488**
drhab01f612004-05-22 02:55:23 +00001489** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00001490** to use a cursor that was open at the beginning of this operation
1491** will result in an error.
1492*/
drh3aac2dd2004-04-26 14:10:20 +00001493int sqlite3BtreeRollbackStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00001494 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001495 if( pBt->inStmt==0 || pBt->readOnly ) return SQLITE_OK;
drha34b6762004-05-07 13:30:42 +00001496 rc = sqlite3pager_stmt_rollback(pBt->pPager);
danielk1977fbcd5852004-06-15 02:44:18 +00001497 assert( countWriteCursors(pBt)==0 );
drh3aac2dd2004-04-26 14:10:20 +00001498 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00001499 return rc;
1500}
1501
1502/*
drh3aac2dd2004-04-26 14:10:20 +00001503** Default key comparison function to be used if no comparison function
1504** is specified on the sqlite3BtreeCursor() call.
1505*/
1506static int dfltCompare(
1507 void *NotUsed, /* User data is not used */
1508 int n1, const void *p1, /* First key to compare */
1509 int n2, const void *p2 /* Second key to compare */
1510){
1511 int c;
1512 c = memcmp(p1, p2, n1<n2 ? n1 : n2);
1513 if( c==0 ){
1514 c = n1 - n2;
1515 }
1516 return c;
1517}
1518
1519/*
drh8b2f49b2001-06-08 00:21:52 +00001520** Create a new cursor for the BTree whose root is on the page
1521** iTable. The act of acquiring a cursor gets a read lock on
1522** the database file.
drh1bee3d72001-10-15 00:44:35 +00001523**
1524** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00001525** If wrFlag==1, then the cursor can be used for reading or for
1526** writing if other conditions for writing are also met. These
1527** are the conditions that must be met in order for writing to
1528** be allowed:
drh6446c4d2001-12-15 14:22:18 +00001529**
drhf74b8d92002-09-01 23:20:45 +00001530** 1: The cursor must have been opened with wrFlag==1
1531**
1532** 2: No other cursors may be open with wrFlag==0 on the same table
1533**
1534** 3: The database must be writable (not on read-only media)
1535**
1536** 4: There must be an active transaction.
1537**
1538** Condition 2 warrants further discussion. If any cursor is opened
1539** on a table with wrFlag==0, that prevents all other cursors from
1540** writing to that table. This is a kind of "read-lock". When a cursor
1541** is opened with wrFlag==0 it is guaranteed that the table will not
1542** change as long as the cursor is open. This allows the cursor to
1543** do a sequential scan of the table without having to worry about
1544** entries being inserted or deleted during the scan. Cursors should
1545** be opened with wrFlag==0 only if this read-lock property is needed.
1546** That is to say, cursors should be opened with wrFlag==0 only if they
drh23e11ca2004-05-04 17:27:28 +00001547** intend to use the sqlite3BtreeNext() system call. All other cursors
drhf74b8d92002-09-01 23:20:45 +00001548** should be opened with wrFlag==1 even if they never really intend
1549** to write.
1550**
drh6446c4d2001-12-15 14:22:18 +00001551** No checking is done to make sure that page iTable really is the
1552** root page of a b-tree. If it is not, then the cursor acquired
1553** will not work correctly.
drh3aac2dd2004-04-26 14:10:20 +00001554**
1555** The comparison function must be logically the same for every cursor
1556** on a particular table. Changing the comparison function will result
1557** in incorrect operations. If the comparison function is NULL, a
1558** default comparison function is used. The comparison function is
1559** always ignored for INTKEY tables.
drha059ad02001-04-17 20:09:11 +00001560*/
drh3aac2dd2004-04-26 14:10:20 +00001561int sqlite3BtreeCursor(
1562 Btree *pBt, /* The btree */
1563 int iTable, /* Root page of table to open */
1564 int wrFlag, /* 1 to write. 0 read-only */
1565 int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
1566 void *pArg, /* First arg to xCompare() */
1567 BtCursor **ppCur /* Write new cursor here */
1568){
drha059ad02001-04-17 20:09:11 +00001569 int rc;
drh8dcd7ca2004-08-08 19:43:29 +00001570 BtCursor *pCur;
drhecdc7532001-09-23 02:35:53 +00001571
drh8dcd7ca2004-08-08 19:43:29 +00001572 *ppCur = 0;
1573 if( wrFlag ){
drh8dcd7ca2004-08-08 19:43:29 +00001574 if( pBt->readOnly ){
1575 return SQLITE_READONLY;
1576 }
1577 if( checkReadLocks(pBt, iTable, 0) ){
1578 return SQLITE_LOCKED;
1579 }
drha0c9a112004-03-10 13:42:37 +00001580 }
drh4b70f112004-05-02 21:12:19 +00001581 if( pBt->pPage1==0 ){
drha059ad02001-04-17 20:09:11 +00001582 rc = lockBtree(pBt);
1583 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00001584 return rc;
1585 }
1586 }
drheafe05b2004-06-13 00:54:01 +00001587 pCur = sqliteMallocRaw( sizeof(*pCur) );
drha059ad02001-04-17 20:09:11 +00001588 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +00001589 rc = SQLITE_NOMEM;
1590 goto create_cursor_exception;
1591 }
drh8b2f49b2001-06-08 00:21:52 +00001592 pCur->pgnoRoot = (Pgno)iTable;
drh24cd67e2004-05-10 16:18:47 +00001593 if( iTable==1 && sqlite3pager_pagecount(pBt->pPager)==0 ){
1594 rc = SQLITE_EMPTY;
drheafe05b2004-06-13 00:54:01 +00001595 pCur->pPage = 0;
drh24cd67e2004-05-10 16:18:47 +00001596 goto create_cursor_exception;
1597 }
danielk1977369f27e2004-06-15 11:40:04 +00001598 pCur->pPage = 0; /* For exit-handler, in case getAndInitPage() fails. */
drhde647132004-05-07 17:57:49 +00001599 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
drhbd03cae2001-06-02 02:40:57 +00001600 if( rc!=SQLITE_OK ){
1601 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00001602 }
drh3aac2dd2004-04-26 14:10:20 +00001603 pCur->xCompare = xCmp ? xCmp : dfltCompare;
1604 pCur->pArg = pArg;
drh14acc042001-06-10 19:56:58 +00001605 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +00001606 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +00001607 pCur->idx = 0;
drh59eb6762004-06-13 23:07:04 +00001608 memset(&pCur->info, 0, sizeof(pCur->info));
drha059ad02001-04-17 20:09:11 +00001609 pCur->pNext = pBt->pCursor;
1610 if( pCur->pNext ){
1611 pCur->pNext->pPrev = pCur;
1612 }
drh14acc042001-06-10 19:56:58 +00001613 pCur->pPrev = 0;
drha059ad02001-04-17 20:09:11 +00001614 pBt->pCursor = pCur;
drhc39e0002004-05-07 23:50:57 +00001615 pCur->isValid = 0;
1616 pCur->status = SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00001617 *ppCur = pCur;
1618 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00001619
1620create_cursor_exception:
drhbd03cae2001-06-02 02:40:57 +00001621 if( pCur ){
drh3aac2dd2004-04-26 14:10:20 +00001622 releasePage(pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +00001623 sqliteFree(pCur);
1624 }
drh5e00f6c2001-09-13 13:46:56 +00001625 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00001626 return rc;
drha059ad02001-04-17 20:09:11 +00001627}
1628
drh7a224de2004-06-02 01:22:02 +00001629#if 0 /* Not Used */
drhd3d39e92004-05-20 22:16:29 +00001630/*
1631** Change the value of the comparison function used by a cursor.
1632*/
danielk1977bf3b7212004-05-18 10:06:24 +00001633void sqlite3BtreeSetCompare(
drhd3d39e92004-05-20 22:16:29 +00001634 BtCursor *pCur, /* The cursor to whose comparison function is changed */
1635 int(*xCmp)(void*,int,const void*,int,const void*), /* New comparison func */
1636 void *pArg /* First argument to xCmp() */
danielk1977bf3b7212004-05-18 10:06:24 +00001637){
1638 pCur->xCompare = xCmp ? xCmp : dfltCompare;
1639 pCur->pArg = pArg;
1640}
drh7a224de2004-06-02 01:22:02 +00001641#endif
danielk1977bf3b7212004-05-18 10:06:24 +00001642
drha059ad02001-04-17 20:09:11 +00001643/*
drh5e00f6c2001-09-13 13:46:56 +00001644** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00001645** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00001646*/
drh3aac2dd2004-04-26 14:10:20 +00001647int sqlite3BtreeCloseCursor(BtCursor *pCur){
drha059ad02001-04-17 20:09:11 +00001648 Btree *pBt = pCur->pBt;
drha059ad02001-04-17 20:09:11 +00001649 if( pCur->pPrev ){
1650 pCur->pPrev->pNext = pCur->pNext;
1651 }else{
1652 pBt->pCursor = pCur->pNext;
1653 }
1654 if( pCur->pNext ){
1655 pCur->pNext->pPrev = pCur->pPrev;
1656 }
drh3aac2dd2004-04-26 14:10:20 +00001657 releasePage(pCur->pPage);
drh5e00f6c2001-09-13 13:46:56 +00001658 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001659 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +00001660 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00001661}
1662
drh7e3b0a02001-04-28 16:52:40 +00001663/*
drh5e2f8b92001-05-28 00:41:15 +00001664** Make a temporary cursor by filling in the fields of pTempCur.
1665** The temporary cursor is not on the cursor list for the Btree.
1666*/
drh14acc042001-06-10 19:56:58 +00001667static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00001668 memcpy(pTempCur, pCur, sizeof(*pCur));
1669 pTempCur->pNext = 0;
1670 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00001671 if( pTempCur->pPage ){
drha34b6762004-05-07 13:30:42 +00001672 sqlite3pager_ref(pTempCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00001673 }
drh5e2f8b92001-05-28 00:41:15 +00001674}
1675
1676/*
drhbd03cae2001-06-02 02:40:57 +00001677** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00001678** function above.
1679*/
drh14acc042001-06-10 19:56:58 +00001680static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00001681 if( pCur->pPage ){
drha34b6762004-05-07 13:30:42 +00001682 sqlite3pager_unref(pCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00001683 }
drh5e2f8b92001-05-28 00:41:15 +00001684}
1685
1686/*
drh9188b382004-05-14 21:12:22 +00001687** Make sure the BtCursor.info field of the given cursor is valid.
drhab01f612004-05-22 02:55:23 +00001688** If it is not already valid, call parseCell() to fill it in.
1689**
1690** BtCursor.info is a cache of the information in the current cell.
1691** Using this cache reduces the number of calls to parseCell().
drh9188b382004-05-14 21:12:22 +00001692*/
1693static void getCellInfo(BtCursor *pCur){
drh271efa52004-05-30 19:19:05 +00001694 if( pCur->info.nSize==0 ){
drh3a41a3f2004-05-30 02:14:17 +00001695 parseCell(pCur->pPage, pCur->idx, &pCur->info);
drh9188b382004-05-14 21:12:22 +00001696 }else{
1697#ifndef NDEBUG
1698 CellInfo info;
drh51c6d962004-06-06 00:42:25 +00001699 memset(&info, 0, sizeof(info));
drh3a41a3f2004-05-30 02:14:17 +00001700 parseCell(pCur->pPage, pCur->idx, &info);
drh9188b382004-05-14 21:12:22 +00001701 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
1702#endif
1703 }
1704}
1705
1706/*
drh3aac2dd2004-04-26 14:10:20 +00001707** Set *pSize to the size of the buffer needed to hold the value of
1708** the key for the current entry. If the cursor is not pointing
1709** to a valid entry, *pSize is set to 0.
1710**
drh4b70f112004-05-02 21:12:19 +00001711** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00001712** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00001713*/
drh4a1c3802004-05-12 15:15:47 +00001714int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drhc39e0002004-05-07 23:50:57 +00001715 if( !pCur->isValid ){
drh72f82862001-05-24 21:06:34 +00001716 *pSize = 0;
1717 }else{
drh9188b382004-05-14 21:12:22 +00001718 getCellInfo(pCur);
1719 *pSize = pCur->info.nKey;
drh72f82862001-05-24 21:06:34 +00001720 }
1721 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00001722}
drh2af926b2001-05-15 00:39:25 +00001723
drh72f82862001-05-24 21:06:34 +00001724/*
drh0e1c19e2004-05-11 00:58:56 +00001725** Set *pSize to the number of bytes of data in the entry the
1726** cursor currently points to. Always return SQLITE_OK.
1727** Failure is not possible. If the cursor is not currently
1728** pointing to an entry (which can happen, for example, if
1729** the database is empty) then *pSize is set to 0.
1730*/
1731int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drh0e1c19e2004-05-11 00:58:56 +00001732 if( !pCur->isValid ){
danielk197796fc5fe2004-05-13 11:34:16 +00001733 /* Not pointing at a valid entry - set *pSize to 0. */
drh0e1c19e2004-05-11 00:58:56 +00001734 *pSize = 0;
1735 }else{
drh9188b382004-05-14 21:12:22 +00001736 getCellInfo(pCur);
1737 *pSize = pCur->info.nData;
drh0e1c19e2004-05-11 00:58:56 +00001738 }
1739 return SQLITE_OK;
1740}
1741
1742/*
drh72f82862001-05-24 21:06:34 +00001743** Read payload information from the entry that the pCur cursor is
1744** pointing to. Begin reading the payload at "offset" and read
1745** a total of "amt" bytes. Put the result in zBuf.
1746**
1747** This routine does not make a distinction between key and data.
drhab01f612004-05-22 02:55:23 +00001748** It just reads bytes from the payload area. Data might appear
1749** on the main page or be scattered out on multiple overflow pages.
drh72f82862001-05-24 21:06:34 +00001750*/
drh3aac2dd2004-04-26 14:10:20 +00001751static int getPayload(
1752 BtCursor *pCur, /* Cursor pointing to entry to read from */
1753 int offset, /* Begin reading this far into payload */
1754 int amt, /* Read this many bytes */
1755 unsigned char *pBuf, /* Write the bytes into this buffer */
1756 int skipKey /* offset begins at data if this is true */
1757){
1758 unsigned char *aPayload;
drh2af926b2001-05-15 00:39:25 +00001759 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +00001760 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001761 MemPage *pPage;
1762 Btree *pBt;
drh6f11bef2004-05-13 01:12:56 +00001763 int ovflSize;
drhfa1a98a2004-05-14 19:08:17 +00001764 u32 nKey;
drh3aac2dd2004-04-26 14:10:20 +00001765
drh72f82862001-05-24 21:06:34 +00001766 assert( pCur!=0 && pCur->pPage!=0 );
drhc39e0002004-05-07 23:50:57 +00001767 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00001768 pBt = pCur->pBt;
1769 pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00001770 pageIntegrity(pPage);
drh3aac2dd2004-04-26 14:10:20 +00001771 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00001772 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00001773 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00001774 aPayload += pCur->info.nHeader;
drh3aac2dd2004-04-26 14:10:20 +00001775 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00001776 nKey = 0;
1777 }else{
1778 nKey = pCur->info.nKey;
drh3aac2dd2004-04-26 14:10:20 +00001779 }
1780 assert( offset>=0 );
1781 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00001782 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00001783 }
drhfa1a98a2004-05-14 19:08:17 +00001784 if( offset+amt > nKey+pCur->info.nData ){
drha34b6762004-05-07 13:30:42 +00001785 return SQLITE_ERROR;
drh3aac2dd2004-04-26 14:10:20 +00001786 }
drhfa1a98a2004-05-14 19:08:17 +00001787 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00001788 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00001789 if( a+offset>pCur->info.nLocal ){
1790 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00001791 }
drha34b6762004-05-07 13:30:42 +00001792 memcpy(pBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +00001793 if( a==amt ){
1794 return SQLITE_OK;
1795 }
drh2aa679f2001-06-25 02:11:07 +00001796 offset = 0;
drha34b6762004-05-07 13:30:42 +00001797 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00001798 amt -= a;
drhdd793422001-06-28 01:54:48 +00001799 }else{
drhfa1a98a2004-05-14 19:08:17 +00001800 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00001801 }
danielk1977cfe9a692004-06-16 12:00:29 +00001802 ovflSize = pBt->usableSize - 4;
drhbd03cae2001-06-02 02:40:57 +00001803 if( amt>0 ){
drhfa1a98a2004-05-14 19:08:17 +00001804 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977cfe9a692004-06-16 12:00:29 +00001805 while( amt>0 && nextPage ){
1806 rc = sqlite3pager_get(pBt->pPager, nextPage, (void**)&aPayload);
1807 if( rc!=0 ){
1808 return rc;
drh2af926b2001-05-15 00:39:25 +00001809 }
danielk1977cfe9a692004-06-16 12:00:29 +00001810 nextPage = get4byte(aPayload);
1811 if( offset<ovflSize ){
1812 int a = amt;
1813 if( a + offset > ovflSize ){
1814 a = ovflSize - offset;
1815 }
1816 memcpy(pBuf, &aPayload[offset+4], a);
1817 offset = 0;
1818 amt -= a;
1819 pBuf += a;
1820 }else{
1821 offset -= ovflSize;
1822 }
1823 sqlite3pager_unref(aPayload);
drh2af926b2001-05-15 00:39:25 +00001824 }
drh2af926b2001-05-15 00:39:25 +00001825 }
danielk1977cfe9a692004-06-16 12:00:29 +00001826
drha7fcb052001-12-14 15:09:55 +00001827 if( amt>0 ){
drhee696e22004-08-30 16:52:17 +00001828 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
drha7fcb052001-12-14 15:09:55 +00001829 }
1830 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00001831}
1832
drh72f82862001-05-24 21:06:34 +00001833/*
drh3aac2dd2004-04-26 14:10:20 +00001834** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00001835** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00001836** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00001837**
drh3aac2dd2004-04-26 14:10:20 +00001838** Return SQLITE_OK on success or an error code if anything goes
1839** wrong. An error is returned if "offset+amt" is larger than
1840** the available payload.
drh72f82862001-05-24 21:06:34 +00001841*/
drha34b6762004-05-07 13:30:42 +00001842int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhc39e0002004-05-07 23:50:57 +00001843 if( pCur->isValid==0 ){
1844 return pCur->status;
drh3aac2dd2004-04-26 14:10:20 +00001845 }
drhc39e0002004-05-07 23:50:57 +00001846 assert( pCur->pPage!=0 );
1847 assert( pCur->pPage->intKey==0 );
1848 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh3aac2dd2004-04-26 14:10:20 +00001849 return getPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
1850}
1851
1852/*
drh3aac2dd2004-04-26 14:10:20 +00001853** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00001854** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00001855** begins at "offset".
1856**
1857** Return SQLITE_OK on success or an error code if anything goes
1858** wrong. An error is returned if "offset+amt" is larger than
1859** the available payload.
drh72f82862001-05-24 21:06:34 +00001860*/
drh3aac2dd2004-04-26 14:10:20 +00001861int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhc39e0002004-05-07 23:50:57 +00001862 if( !pCur->isValid ){
1863 return pCur->status ? pCur->status : SQLITE_INTERNAL;
1864 }
drh8c1238a2003-01-02 14:43:55 +00001865 assert( pCur->pPage!=0 );
drhc39e0002004-05-07 23:50:57 +00001866 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh3aac2dd2004-04-26 14:10:20 +00001867 return getPayload(pCur, offset, amt, pBuf, 1);
drh2af926b2001-05-15 00:39:25 +00001868}
1869
drh72f82862001-05-24 21:06:34 +00001870/*
drh0e1c19e2004-05-11 00:58:56 +00001871** Return a pointer to payload information from the entry that the
1872** pCur cursor is pointing to. The pointer is to the beginning of
1873** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00001874** skipKey==1. The number of bytes of available key/data is written
1875** into *pAmt. If *pAmt==0, then the value returned will not be
1876** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00001877**
1878** This routine is an optimization. It is common for the entire key
1879** and data to fit on the local page and for there to be no overflow
1880** pages. When that is so, this routine can be used to access the
1881** key and data without making a copy. If the key and/or data spills
1882** onto overflow pages, then getPayload() must be used to reassembly
1883** the key/data and copy it into a preallocated buffer.
1884**
1885** The pointer returned by this routine looks directly into the cached
1886** page of the database. The data might change or move the next time
1887** any btree routine is called.
1888*/
1889static const unsigned char *fetchPayload(
1890 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00001891 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00001892 int skipKey /* read beginning at data if this is true */
1893){
1894 unsigned char *aPayload;
1895 MemPage *pPage;
1896 Btree *pBt;
drhfa1a98a2004-05-14 19:08:17 +00001897 u32 nKey;
1898 int nLocal;
drh0e1c19e2004-05-11 00:58:56 +00001899
1900 assert( pCur!=0 && pCur->pPage!=0 );
1901 assert( pCur->isValid );
1902 pBt = pCur->pBt;
1903 pPage = pCur->pPage;
1904 pageIntegrity(pPage);
1905 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00001906 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00001907 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00001908 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00001909 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00001910 nKey = 0;
1911 }else{
1912 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00001913 }
drh0e1c19e2004-05-11 00:58:56 +00001914 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00001915 aPayload += nKey;
1916 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00001917 }else{
drhfa1a98a2004-05-14 19:08:17 +00001918 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00001919 if( nLocal>nKey ){
1920 nLocal = nKey;
1921 }
drh0e1c19e2004-05-11 00:58:56 +00001922 }
drhe51c44f2004-05-30 20:46:09 +00001923 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00001924 return aPayload;
1925}
1926
1927
1928/*
drhe51c44f2004-05-30 20:46:09 +00001929** For the entry that cursor pCur is point to, return as
1930** many bytes of the key or data as are available on the local
1931** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00001932**
1933** The pointer returned is ephemeral. The key/data may move
1934** or be destroyed on the next call to any Btree routine.
1935**
1936** These routines is used to get quick access to key and data
1937** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00001938*/
drhe51c44f2004-05-30 20:46:09 +00001939const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
1940 return (const void*)fetchPayload(pCur, pAmt, 0);
drh0e1c19e2004-05-11 00:58:56 +00001941}
drhe51c44f2004-05-30 20:46:09 +00001942const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
1943 return (const void*)fetchPayload(pCur, pAmt, 1);
drh0e1c19e2004-05-11 00:58:56 +00001944}
1945
1946
1947/*
drh8178a752003-01-05 21:41:40 +00001948** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00001949** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00001950*/
drh3aac2dd2004-04-26 14:10:20 +00001951static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00001952 int rc;
1953 MemPage *pNewPage;
drh3aac2dd2004-04-26 14:10:20 +00001954 MemPage *pOldPage;
drh0d316a42002-08-11 20:10:47 +00001955 Btree *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00001956
drhc39e0002004-05-07 23:50:57 +00001957 assert( pCur->isValid );
drhde647132004-05-07 17:57:49 +00001958 rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00001959 if( rc ) return rc;
drhda200cc2004-05-09 11:51:38 +00001960 pageIntegrity(pNewPage);
drh428ae8c2003-01-04 16:48:09 +00001961 pNewPage->idxParent = pCur->idx;
drh3aac2dd2004-04-26 14:10:20 +00001962 pOldPage = pCur->pPage;
1963 pOldPage->idxShift = 0;
1964 releasePage(pOldPage);
drh72f82862001-05-24 21:06:34 +00001965 pCur->pPage = pNewPage;
1966 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00001967 pCur->info.nSize = 0;
drh4be295b2003-12-16 03:44:47 +00001968 if( pNewPage->nCell<1 ){
drhee696e22004-08-30 16:52:17 +00001969 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
drh4be295b2003-12-16 03:44:47 +00001970 }
drh72f82862001-05-24 21:06:34 +00001971 return SQLITE_OK;
1972}
1973
1974/*
drh8856d6a2004-04-29 14:42:46 +00001975** Return true if the page is the virtual root of its table.
1976**
1977** The virtual root page is the root page for most tables. But
1978** for the table rooted on page 1, sometime the real root page
1979** is empty except for the right-pointer. In such cases the
1980** virtual root page is the page that the right-pointer of page
1981** 1 is pointing to.
1982*/
1983static int isRootPage(MemPage *pPage){
1984 MemPage *pParent = pPage->pParent;
drhda200cc2004-05-09 11:51:38 +00001985 if( pParent==0 ) return 1;
1986 if( pParent->pgno>1 ) return 0;
1987 if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
drh8856d6a2004-04-29 14:42:46 +00001988 return 0;
1989}
1990
1991/*
drh5e2f8b92001-05-28 00:41:15 +00001992** Move the cursor up to the parent page.
1993**
1994** pCur->idx is set to the cell index that contains the pointer
1995** to the page we are coming from. If we are coming from the
1996** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00001997** the largest cell index.
drh72f82862001-05-24 21:06:34 +00001998*/
drh8178a752003-01-05 21:41:40 +00001999static void moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00002000 Pgno oldPgno;
2001 MemPage *pParent;
drh8178a752003-01-05 21:41:40 +00002002 MemPage *pPage;
drh428ae8c2003-01-04 16:48:09 +00002003 int idxParent;
drh3aac2dd2004-04-26 14:10:20 +00002004
drhc39e0002004-05-07 23:50:57 +00002005 assert( pCur->isValid );
drh8178a752003-01-05 21:41:40 +00002006 pPage = pCur->pPage;
2007 assert( pPage!=0 );
drh8856d6a2004-04-29 14:42:46 +00002008 assert( !isRootPage(pPage) );
drhda200cc2004-05-09 11:51:38 +00002009 pageIntegrity(pPage);
drh8178a752003-01-05 21:41:40 +00002010 pParent = pPage->pParent;
2011 assert( pParent!=0 );
drhda200cc2004-05-09 11:51:38 +00002012 pageIntegrity(pParent);
drh8178a752003-01-05 21:41:40 +00002013 idxParent = pPage->idxParent;
drha34b6762004-05-07 13:30:42 +00002014 sqlite3pager_ref(pParent->aData);
drh3aac2dd2004-04-26 14:10:20 +00002015 oldPgno = pPage->pgno;
2016 releasePage(pPage);
drh72f82862001-05-24 21:06:34 +00002017 pCur->pPage = pParent;
drh271efa52004-05-30 19:19:05 +00002018 pCur->info.nSize = 0;
drh428ae8c2003-01-04 16:48:09 +00002019 assert( pParent->idxShift==0 );
drh43605152004-05-29 21:46:49 +00002020 pCur->idx = idxParent;
drh72f82862001-05-24 21:06:34 +00002021}
2022
2023/*
2024** Move the cursor to the root page
2025*/
drh5e2f8b92001-05-28 00:41:15 +00002026static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00002027 MemPage *pRoot;
drhbd03cae2001-06-02 02:40:57 +00002028 int rc;
drh0d316a42002-08-11 20:10:47 +00002029 Btree *pBt = pCur->pBt;
drhbd03cae2001-06-02 02:40:57 +00002030
drhde647132004-05-07 17:57:49 +00002031 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0);
drhc39e0002004-05-07 23:50:57 +00002032 if( rc ){
2033 pCur->isValid = 0;
2034 return rc;
2035 }
drh3aac2dd2004-04-26 14:10:20 +00002036 releasePage(pCur->pPage);
drhda200cc2004-05-09 11:51:38 +00002037 pageIntegrity(pRoot);
drh3aac2dd2004-04-26 14:10:20 +00002038 pCur->pPage = pRoot;
drh72f82862001-05-24 21:06:34 +00002039 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00002040 pCur->info.nSize = 0;
drh8856d6a2004-04-29 14:42:46 +00002041 if( pRoot->nCell==0 && !pRoot->leaf ){
2042 Pgno subpage;
2043 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00002044 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00002045 assert( subpage>0 );
drh3644f082004-05-10 18:45:09 +00002046 pCur->isValid = 1;
drh4b70f112004-05-02 21:12:19 +00002047 rc = moveToChild(pCur, subpage);
drh8856d6a2004-04-29 14:42:46 +00002048 }
drhc39e0002004-05-07 23:50:57 +00002049 pCur->isValid = pCur->pPage->nCell>0;
drh8856d6a2004-04-29 14:42:46 +00002050 return rc;
drh72f82862001-05-24 21:06:34 +00002051}
drh2af926b2001-05-15 00:39:25 +00002052
drh5e2f8b92001-05-28 00:41:15 +00002053/*
2054** Move the cursor down to the left-most leaf entry beneath the
2055** entry to which it is currently pointing.
2056*/
2057static int moveToLeftmost(BtCursor *pCur){
2058 Pgno pgno;
2059 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002060 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00002061
drhc39e0002004-05-07 23:50:57 +00002062 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00002063 while( !(pPage = pCur->pPage)->leaf ){
drha34b6762004-05-07 13:30:42 +00002064 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00002065 pgno = get4byte(findCell(pPage, pCur->idx));
drh8178a752003-01-05 21:41:40 +00002066 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00002067 if( rc ) return rc;
2068 }
2069 return SQLITE_OK;
2070}
2071
drh2dcc9aa2002-12-04 13:40:25 +00002072/*
2073** Move the cursor down to the right-most leaf entry beneath the
2074** page to which it is currently pointing. Notice the difference
2075** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
2076** finds the left-most entry beneath the *entry* whereas moveToRightmost()
2077** finds the right-most entry beneath the *page*.
2078*/
2079static int moveToRightmost(BtCursor *pCur){
2080 Pgno pgno;
2081 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002082 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00002083
drhc39e0002004-05-07 23:50:57 +00002084 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00002085 while( !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00002086 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh3aac2dd2004-04-26 14:10:20 +00002087 pCur->idx = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00002088 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00002089 if( rc ) return rc;
2090 }
drh3aac2dd2004-04-26 14:10:20 +00002091 pCur->idx = pPage->nCell - 1;
drh271efa52004-05-30 19:19:05 +00002092 pCur->info.nSize = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002093 return SQLITE_OK;
2094}
2095
drh5e00f6c2001-09-13 13:46:56 +00002096/* Move the cursor to the first entry in the table. Return SQLITE_OK
2097** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00002098** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00002099*/
drh3aac2dd2004-04-26 14:10:20 +00002100int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00002101 int rc;
drhc39e0002004-05-07 23:50:57 +00002102 if( pCur->status ){
2103 return pCur->status;
2104 }
drh5e00f6c2001-09-13 13:46:56 +00002105 rc = moveToRoot(pCur);
2106 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00002107 if( pCur->isValid==0 ){
2108 assert( pCur->pPage->nCell==0 );
drh5e00f6c2001-09-13 13:46:56 +00002109 *pRes = 1;
2110 return SQLITE_OK;
2111 }
drhc39e0002004-05-07 23:50:57 +00002112 assert( pCur->pPage->nCell>0 );
drh5e00f6c2001-09-13 13:46:56 +00002113 *pRes = 0;
2114 rc = moveToLeftmost(pCur);
2115 return rc;
2116}
drh5e2f8b92001-05-28 00:41:15 +00002117
drh9562b552002-02-19 15:00:07 +00002118/* Move the cursor to the last entry in the table. Return SQLITE_OK
2119** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00002120** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00002121*/
drh3aac2dd2004-04-26 14:10:20 +00002122int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00002123 int rc;
drhc39e0002004-05-07 23:50:57 +00002124 if( pCur->status ){
2125 return pCur->status;
2126 }
drh9562b552002-02-19 15:00:07 +00002127 rc = moveToRoot(pCur);
2128 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00002129 if( pCur->isValid==0 ){
2130 assert( pCur->pPage->nCell==0 );
drh9562b552002-02-19 15:00:07 +00002131 *pRes = 1;
2132 return SQLITE_OK;
2133 }
drhc39e0002004-05-07 23:50:57 +00002134 assert( pCur->isValid );
drh9562b552002-02-19 15:00:07 +00002135 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002136 rc = moveToRightmost(pCur);
drh9562b552002-02-19 15:00:07 +00002137 return rc;
2138}
2139
drh3aac2dd2004-04-26 14:10:20 +00002140/* Move the cursor so that it points to an entry near pKey/nKey.
drh72f82862001-05-24 21:06:34 +00002141** Return a success code.
2142**
drh3aac2dd2004-04-26 14:10:20 +00002143** For INTKEY tables, only the nKey parameter is used. pKey is
2144** ignored. For other tables, nKey is the number of bytes of data
2145** in nKey. The comparison function specified when the cursor was
2146** created is used to compare keys.
2147**
drh5e2f8b92001-05-28 00:41:15 +00002148** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00002149** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00002150** were present. The cursor might point to an entry that comes
2151** before or after the key.
2152**
drhbd03cae2001-06-02 02:40:57 +00002153** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00002154** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00002155** this value is as follows:
2156**
2157** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00002158** is smaller than pKey or if the table is empty
2159** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00002160**
2161** *pRes==0 The cursor is left pointing at an entry that
2162** exactly matches pKey.
2163**
2164** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00002165** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00002166*/
drh4a1c3802004-05-12 15:15:47 +00002167int sqlite3BtreeMoveto(BtCursor *pCur, const void *pKey, i64 nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00002168 int rc;
drhc39e0002004-05-07 23:50:57 +00002169
2170 if( pCur->status ){
2171 return pCur->status;
2172 }
drh5e2f8b92001-05-28 00:41:15 +00002173 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00002174 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00002175 assert( pCur->pPage );
2176 assert( pCur->pPage->isInit );
2177 if( pCur->isValid==0 ){
drhf328bc82004-05-10 23:29:49 +00002178 *pRes = -1;
drhc39e0002004-05-07 23:50:57 +00002179 assert( pCur->pPage->nCell==0 );
2180 return SQLITE_OK;
2181 }
drh72f82862001-05-24 21:06:34 +00002182 for(;;){
2183 int lwr, upr;
2184 Pgno chldPg;
2185 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00002186 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00002187 lwr = 0;
2188 upr = pPage->nCell-1;
drhda200cc2004-05-09 11:51:38 +00002189 pageIntegrity(pPage);
drh72f82862001-05-24 21:06:34 +00002190 while( lwr<=upr ){
danielk197713adf8a2004-06-03 16:08:41 +00002191 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00002192 i64 nCellKey;
drh72f82862001-05-24 21:06:34 +00002193 pCur->idx = (lwr+upr)/2;
drh271efa52004-05-30 19:19:05 +00002194 pCur->info.nSize = 0;
drhde647132004-05-07 17:57:49 +00002195 sqlite3BtreeKeySize(pCur, &nCellKey);
drh3aac2dd2004-04-26 14:10:20 +00002196 if( pPage->intKey ){
2197 if( nCellKey<nKey ){
2198 c = -1;
2199 }else if( nCellKey>nKey ){
2200 c = +1;
2201 }else{
2202 c = 0;
2203 }
drh3aac2dd2004-04-26 14:10:20 +00002204 }else{
drhe51c44f2004-05-30 20:46:09 +00002205 int available;
danielk197713adf8a2004-06-03 16:08:41 +00002206 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drhe51c44f2004-05-30 20:46:09 +00002207 if( available>=nCellKey ){
2208 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
2209 }else{
2210 pCellKey = sqliteMallocRaw( nCellKey );
2211 if( pCellKey==0 ) return SQLITE_NOMEM;
danielk197713adf8a2004-06-03 16:08:41 +00002212 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
drhe51c44f2004-05-30 20:46:09 +00002213 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
2214 sqliteFree(pCellKey);
2215 if( rc ) return rc;
2216 }
drh3aac2dd2004-04-26 14:10:20 +00002217 }
drh72f82862001-05-24 21:06:34 +00002218 if( c==0 ){
drh8b18dd42004-05-12 19:18:15 +00002219 if( pPage->leafData && !pPage->leaf ){
drhfc70e6f2004-05-12 21:11:27 +00002220 lwr = pCur->idx;
2221 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00002222 break;
2223 }else{
drh8b18dd42004-05-12 19:18:15 +00002224 if( pRes ) *pRes = 0;
2225 return SQLITE_OK;
2226 }
drh72f82862001-05-24 21:06:34 +00002227 }
2228 if( c<0 ){
2229 lwr = pCur->idx+1;
2230 }else{
2231 upr = pCur->idx-1;
2232 }
2233 }
2234 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00002235 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00002236 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00002237 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00002238 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00002239 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00002240 }else{
drh43605152004-05-29 21:46:49 +00002241 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00002242 }
2243 if( chldPg==0 ){
drhc39e0002004-05-07 23:50:57 +00002244 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00002245 if( pRes ) *pRes = c;
2246 return SQLITE_OK;
2247 }
drh428ae8c2003-01-04 16:48:09 +00002248 pCur->idx = lwr;
drh271efa52004-05-30 19:19:05 +00002249 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00002250 rc = moveToChild(pCur, chldPg);
drhc39e0002004-05-07 23:50:57 +00002251 if( rc ){
2252 return rc;
2253 }
drh72f82862001-05-24 21:06:34 +00002254 }
drhbd03cae2001-06-02 02:40:57 +00002255 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00002256}
2257
2258/*
drhc39e0002004-05-07 23:50:57 +00002259** Return TRUE if the cursor is not pointing at an entry of the table.
2260**
2261** TRUE will be returned after a call to sqlite3BtreeNext() moves
2262** past the last entry in the table or sqlite3BtreePrev() moves past
2263** the first entry. TRUE is also returned if the table is empty.
2264*/
2265int sqlite3BtreeEof(BtCursor *pCur){
2266 return pCur->isValid==0;
2267}
2268
2269/*
drhbd03cae2001-06-02 02:40:57 +00002270** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00002271** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00002272** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00002273** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00002274*/
drh3aac2dd2004-04-26 14:10:20 +00002275int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00002276 int rc;
drh8178a752003-01-05 21:41:40 +00002277 MemPage *pPage = pCur->pPage;
drh8b18dd42004-05-12 19:18:15 +00002278
drh8c1238a2003-01-02 14:43:55 +00002279 assert( pRes!=0 );
drhc39e0002004-05-07 23:50:57 +00002280 if( pCur->isValid==0 ){
drh8c1238a2003-01-02 14:43:55 +00002281 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00002282 return SQLITE_OK;
drhecdc7532001-09-23 02:35:53 +00002283 }
drh8178a752003-01-05 21:41:40 +00002284 assert( pPage->isInit );
drh8178a752003-01-05 21:41:40 +00002285 assert( pCur->idx<pPage->nCell );
drh72f82862001-05-24 21:06:34 +00002286 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00002287 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00002288 if( pCur->idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00002289 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00002290 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00002291 if( rc ) return rc;
2292 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00002293 *pRes = 0;
2294 return rc;
drh72f82862001-05-24 21:06:34 +00002295 }
drh5e2f8b92001-05-28 00:41:15 +00002296 do{
drh8856d6a2004-04-29 14:42:46 +00002297 if( isRootPage(pPage) ){
drh8c1238a2003-01-02 14:43:55 +00002298 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00002299 pCur->isValid = 0;
drh5e2f8b92001-05-28 00:41:15 +00002300 return SQLITE_OK;
2301 }
drh8178a752003-01-05 21:41:40 +00002302 moveToParent(pCur);
2303 pPage = pCur->pPage;
2304 }while( pCur->idx>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00002305 *pRes = 0;
drh8b18dd42004-05-12 19:18:15 +00002306 if( pPage->leafData ){
2307 rc = sqlite3BtreeNext(pCur, pRes);
2308 }else{
2309 rc = SQLITE_OK;
2310 }
2311 return rc;
drh8178a752003-01-05 21:41:40 +00002312 }
2313 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00002314 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00002315 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00002316 }
drh5e2f8b92001-05-28 00:41:15 +00002317 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00002318 return rc;
drh72f82862001-05-24 21:06:34 +00002319}
2320
drh3b7511c2001-05-26 13:15:44 +00002321/*
drh2dcc9aa2002-12-04 13:40:25 +00002322** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00002323** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00002324** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00002325** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00002326*/
drh3aac2dd2004-04-26 14:10:20 +00002327int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00002328 int rc;
2329 Pgno pgno;
drh8178a752003-01-05 21:41:40 +00002330 MemPage *pPage;
drhc39e0002004-05-07 23:50:57 +00002331 if( pCur->isValid==0 ){
2332 *pRes = 1;
2333 return SQLITE_OK;
2334 }
drh8178a752003-01-05 21:41:40 +00002335 pPage = pCur->pPage;
drh8178a752003-01-05 21:41:40 +00002336 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00002337 assert( pCur->idx>=0 );
drha34b6762004-05-07 13:30:42 +00002338 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00002339 pgno = get4byte( findCell(pPage, pCur->idx) );
drh8178a752003-01-05 21:41:40 +00002340 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00002341 if( rc ) return rc;
2342 rc = moveToRightmost(pCur);
2343 }else{
2344 while( pCur->idx==0 ){
drh8856d6a2004-04-29 14:42:46 +00002345 if( isRootPage(pPage) ){
drhc39e0002004-05-07 23:50:57 +00002346 pCur->isValid = 0;
2347 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00002348 return SQLITE_OK;
2349 }
drh8178a752003-01-05 21:41:40 +00002350 moveToParent(pCur);
2351 pPage = pCur->pPage;
drh2dcc9aa2002-12-04 13:40:25 +00002352 }
2353 pCur->idx--;
drh271efa52004-05-30 19:19:05 +00002354 pCur->info.nSize = 0;
drh8b18dd42004-05-12 19:18:15 +00002355 if( pPage->leafData ){
2356 rc = sqlite3BtreePrevious(pCur, pRes);
2357 }else{
2358 rc = SQLITE_OK;
2359 }
drh2dcc9aa2002-12-04 13:40:25 +00002360 }
drh8178a752003-01-05 21:41:40 +00002361 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002362 return rc;
2363}
2364
2365/*
drh3a4c1412004-05-09 20:40:11 +00002366** The TRACE macro will print high-level status information about the
2367** btree operation when the global variable sqlite3_btree_trace is
2368** enabled.
2369*/
2370#if SQLITE_TEST
drhe54ca3f2004-06-07 01:52:14 +00002371# define TRACE(X) if( sqlite3_btree_trace )\
2372 { sqlite3DebugPrintf X; fflush(stdout); }
drh3a4c1412004-05-09 20:40:11 +00002373#else
2374# define TRACE(X)
2375#endif
2376int sqlite3_btree_trace=0; /* True to enable tracing */
2377
2378/*
drh3b7511c2001-05-26 13:15:44 +00002379** Allocate a new page from the database file.
2380**
drha34b6762004-05-07 13:30:42 +00002381** The new page is marked as dirty. (In other words, sqlite3pager_write()
drh3b7511c2001-05-26 13:15:44 +00002382** has already been called on the new page.) The new page has also
2383** been referenced and the calling routine is responsible for calling
drha34b6762004-05-07 13:30:42 +00002384** sqlite3pager_unref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00002385**
2386** SQLITE_OK is returned on success. Any other return value indicates
2387** an error. *ppPage and *pPgno are undefined in the event of an error.
drha34b6762004-05-07 13:30:42 +00002388** Do not invoke sqlite3pager_unref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00002389**
drh199e3cf2002-07-18 11:01:47 +00002390** If the "nearby" parameter is not 0, then a (feeble) effort is made to
2391** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00002392** attempt to keep related pages close to each other in the database file,
2393** which in turn can make database access faster.
drh3b7511c2001-05-26 13:15:44 +00002394*/
drh199e3cf2002-07-18 11:01:47 +00002395static int allocatePage(Btree *pBt, MemPage **ppPage, Pgno *pPgno, Pgno nearby){
drh3aac2dd2004-04-26 14:10:20 +00002396 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00002397 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002398 int n; /* Number of pages on the freelist */
2399 int k; /* Number of leaves on the trunk of the freelist */
drh30e58752002-03-02 20:41:57 +00002400
drh3aac2dd2004-04-26 14:10:20 +00002401 pPage1 = pBt->pPage1;
2402 n = get4byte(&pPage1->aData[36]);
2403 if( n>0 ){
drh91025292004-05-03 19:49:32 +00002404 /* There are pages on the freelist. Reuse one of those pages. */
drh3aac2dd2004-04-26 14:10:20 +00002405 MemPage *pTrunk;
drha34b6762004-05-07 13:30:42 +00002406 rc = sqlite3pager_write(pPage1->aData);
drh3b7511c2001-05-26 13:15:44 +00002407 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00002408 put4byte(&pPage1->aData[36], n-1);
2409 rc = getPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk);
drh3b7511c2001-05-26 13:15:44 +00002410 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00002411 rc = sqlite3pager_write(pTrunk->aData);
drh3b7511c2001-05-26 13:15:44 +00002412 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00002413 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00002414 return rc;
2415 }
drh3aac2dd2004-04-26 14:10:20 +00002416 k = get4byte(&pTrunk->aData[4]);
2417 if( k==0 ){
2418 /* The trunk has no leaves. So extract the trunk page itself and
2419 ** use it as the newly allocated page */
drha34b6762004-05-07 13:30:42 +00002420 *pPgno = get4byte(&pPage1->aData[32]);
drh3aac2dd2004-04-26 14:10:20 +00002421 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
2422 *ppPage = pTrunk;
drh3a4c1412004-05-09 20:40:11 +00002423 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drhee696e22004-08-30 16:52:17 +00002424 }else if( k>pBt->usableSize/4 - 8 ){
2425 /* Value of k is out of range. Database corruption */
2426 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
drh30e58752002-03-02 20:41:57 +00002427 }else{
drh3aac2dd2004-04-26 14:10:20 +00002428 /* Extract a leaf from the trunk */
2429 int closest;
2430 unsigned char *aData = pTrunk->aData;
2431 if( nearby>0 ){
drhbea00b92002-07-08 10:59:50 +00002432 int i, dist;
2433 closest = 0;
drh3aac2dd2004-04-26 14:10:20 +00002434 dist = get4byte(&aData[8]) - nearby;
drhbea00b92002-07-08 10:59:50 +00002435 if( dist<0 ) dist = -dist;
drh3a4c1412004-05-09 20:40:11 +00002436 for(i=1; i<k; i++){
drh3aac2dd2004-04-26 14:10:20 +00002437 int d2 = get4byte(&aData[8+i*4]) - nearby;
drhbea00b92002-07-08 10:59:50 +00002438 if( d2<0 ) d2 = -d2;
2439 if( d2<dist ) closest = i;
2440 }
2441 }else{
2442 closest = 0;
2443 }
drha34b6762004-05-07 13:30:42 +00002444 *pPgno = get4byte(&aData[8+closest*4]);
drhee696e22004-08-30 16:52:17 +00002445 if( *pPgno>sqlite3pager_pagecount(pBt->pPager) ){
2446 /* Free page off the end of the file */
2447 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
2448 }
drh3a4c1412004-05-09 20:40:11 +00002449 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d: %d more free pages\n",
2450 *pPgno, closest+1, k, pTrunk->pgno, n-1));
drh9b171272004-05-08 02:03:22 +00002451 if( closest<k-1 ){
2452 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
2453 }
drh3a4c1412004-05-09 20:40:11 +00002454 put4byte(&aData[4], k-1);
drh3aac2dd2004-04-26 14:10:20 +00002455 rc = getPage(pBt, *pPgno, ppPage);
2456 releasePage(pTrunk);
drh30e58752002-03-02 20:41:57 +00002457 if( rc==SQLITE_OK ){
drh9b171272004-05-08 02:03:22 +00002458 sqlite3pager_dont_rollback((*ppPage)->aData);
drha34b6762004-05-07 13:30:42 +00002459 rc = sqlite3pager_write((*ppPage)->aData);
drh30e58752002-03-02 20:41:57 +00002460 }
2461 }
drh3b7511c2001-05-26 13:15:44 +00002462 }else{
drh3aac2dd2004-04-26 14:10:20 +00002463 /* There are no pages on the freelist, so create a new page at the
2464 ** end of the file */
drha34b6762004-05-07 13:30:42 +00002465 *pPgno = sqlite3pager_pagecount(pBt->pPager) + 1;
drh3aac2dd2004-04-26 14:10:20 +00002466 rc = getPage(pBt, *pPgno, ppPage);
drh3b7511c2001-05-26 13:15:44 +00002467 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00002468 rc = sqlite3pager_write((*ppPage)->aData);
drh3a4c1412004-05-09 20:40:11 +00002469 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00002470 }
2471 return rc;
2472}
2473
2474/*
drh3aac2dd2004-04-26 14:10:20 +00002475** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00002476**
drha34b6762004-05-07 13:30:42 +00002477** sqlite3pager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00002478*/
drh3aac2dd2004-04-26 14:10:20 +00002479static int freePage(MemPage *pPage){
2480 Btree *pBt = pPage->pBt;
2481 MemPage *pPage1 = pBt->pPage1;
2482 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00002483
drh3aac2dd2004-04-26 14:10:20 +00002484 /* Prepare the page for freeing */
2485 assert( pPage->pgno>1 );
2486 pPage->isInit = 0;
2487 releasePage(pPage->pParent);
2488 pPage->pParent = 0;
2489
drha34b6762004-05-07 13:30:42 +00002490 /* Increment the free page count on pPage1 */
2491 rc = sqlite3pager_write(pPage1->aData);
drh3aac2dd2004-04-26 14:10:20 +00002492 if( rc ) return rc;
2493 n = get4byte(&pPage1->aData[36]);
2494 put4byte(&pPage1->aData[36], n+1);
2495
2496 if( n==0 ){
2497 /* This is the first free page */
drhda200cc2004-05-09 11:51:38 +00002498 rc = sqlite3pager_write(pPage->aData);
2499 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00002500 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00002501 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00002502 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00002503 }else{
2504 /* Other free pages already exist. Retrive the first trunk page
2505 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00002506 MemPage *pTrunk;
2507 rc = getPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk);
drh3b7511c2001-05-26 13:15:44 +00002508 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00002509 k = get4byte(&pTrunk->aData[4]);
drhee696e22004-08-30 16:52:17 +00002510 if( k>=pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00002511 /* The trunk is full. Turn the page being freed into a new
2512 ** trunk page with no leaves. */
drha34b6762004-05-07 13:30:42 +00002513 rc = sqlite3pager_write(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00002514 if( rc ) return rc;
2515 put4byte(pPage->aData, pTrunk->pgno);
2516 put4byte(&pPage->aData[4], 0);
2517 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00002518 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
2519 pPage->pgno, pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00002520 }else{
2521 /* Add the newly freed page as a leaf on the current trunk */
drha34b6762004-05-07 13:30:42 +00002522 rc = sqlite3pager_write(pTrunk->aData);
drh3aac2dd2004-04-26 14:10:20 +00002523 if( rc ) return rc;
2524 put4byte(&pTrunk->aData[4], k+1);
2525 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drha34b6762004-05-07 13:30:42 +00002526 sqlite3pager_dont_write(pBt->pPager, pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00002527 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00002528 }
2529 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00002530 }
drh3b7511c2001-05-26 13:15:44 +00002531 return rc;
2532}
2533
2534/*
drh3aac2dd2004-04-26 14:10:20 +00002535** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00002536*/
drh3aac2dd2004-04-26 14:10:20 +00002537static int clearCell(MemPage *pPage, unsigned char *pCell){
2538 Btree *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00002539 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00002540 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00002541 int rc;
drh3b7511c2001-05-26 13:15:44 +00002542
drh43605152004-05-29 21:46:49 +00002543 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00002544 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00002545 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00002546 }
drh6f11bef2004-05-13 01:12:56 +00002547 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh3aac2dd2004-04-26 14:10:20 +00002548 while( ovflPgno!=0 ){
2549 MemPage *pOvfl;
2550 rc = getPage(pBt, ovflPgno, &pOvfl);
drh3b7511c2001-05-26 13:15:44 +00002551 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00002552 ovflPgno = get4byte(pOvfl->aData);
drha34b6762004-05-07 13:30:42 +00002553 rc = freePage(pOvfl);
drhbd03cae2001-06-02 02:40:57 +00002554 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00002555 sqlite3pager_unref(pOvfl->aData);
drh3b7511c2001-05-26 13:15:44 +00002556 }
drh5e2f8b92001-05-28 00:41:15 +00002557 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00002558}
2559
2560/*
drh91025292004-05-03 19:49:32 +00002561** Create the byte sequence used to represent a cell on page pPage
2562** and write that byte sequence into pCell[]. Overflow pages are
2563** allocated and filled in as necessary. The calling procedure
2564** is responsible for making sure sufficient space has been allocated
2565** for pCell[].
2566**
2567** Note that pCell does not necessary need to point to the pPage->aData
2568** area. pCell might point to some temporary storage. The cell will
2569** be constructed in this temporary area then copied into pPage->aData
2570** later.
drh3b7511c2001-05-26 13:15:44 +00002571*/
2572static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00002573 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00002574 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00002575 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00002576 const void *pData,int nData, /* The data */
2577 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00002578){
drh3b7511c2001-05-26 13:15:44 +00002579 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00002580 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00002581 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00002582 int spaceLeft;
2583 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00002584 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00002585 unsigned char *pPrior;
2586 unsigned char *pPayload;
2587 Btree *pBt = pPage->pBt;
2588 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00002589 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00002590 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00002591
drh91025292004-05-03 19:49:32 +00002592 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00002593 nHeader = 0;
drh91025292004-05-03 19:49:32 +00002594 if( !pPage->leaf ){
2595 nHeader += 4;
2596 }
drh8b18dd42004-05-12 19:18:15 +00002597 if( pPage->hasData ){
drh91025292004-05-03 19:49:32 +00002598 nHeader += putVarint(&pCell[nHeader], nData);
drh6f11bef2004-05-13 01:12:56 +00002599 }else{
drh91025292004-05-03 19:49:32 +00002600 nData = 0;
2601 }
drh6f11bef2004-05-13 01:12:56 +00002602 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh43605152004-05-29 21:46:49 +00002603 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00002604 assert( info.nHeader==nHeader );
2605 assert( info.nKey==nKey );
2606 assert( info.nData==nData );
2607
2608 /* Fill in the payload */
drh3aac2dd2004-04-26 14:10:20 +00002609 nPayload = nData;
2610 if( pPage->intKey ){
2611 pSrc = pData;
2612 nSrc = nData;
drh91025292004-05-03 19:49:32 +00002613 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00002614 }else{
2615 nPayload += nKey;
2616 pSrc = pKey;
2617 nSrc = nKey;
2618 }
drh6f11bef2004-05-13 01:12:56 +00002619 *pnSize = info.nSize;
2620 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00002621 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00002622 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00002623
drh3b7511c2001-05-26 13:15:44 +00002624 while( nPayload>0 ){
2625 if( spaceLeft==0 ){
drh3aac2dd2004-04-26 14:10:20 +00002626 rc = allocatePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl);
drh3b7511c2001-05-26 13:15:44 +00002627 if( rc ){
drh9b171272004-05-08 02:03:22 +00002628 releasePage(pToRelease);
drh3aac2dd2004-04-26 14:10:20 +00002629 clearCell(pPage, pCell);
drh3b7511c2001-05-26 13:15:44 +00002630 return rc;
2631 }
drh3aac2dd2004-04-26 14:10:20 +00002632 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00002633 releasePage(pToRelease);
2634 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00002635 pPrior = pOvfl->aData;
2636 put4byte(pPrior, 0);
2637 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00002638 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00002639 }
2640 n = nPayload;
2641 if( n>spaceLeft ) n = spaceLeft;
drh3aac2dd2004-04-26 14:10:20 +00002642 if( n>nSrc ) n = nSrc;
2643 memcpy(pPayload, pSrc, n);
drh3b7511c2001-05-26 13:15:44 +00002644 nPayload -= n;
drhde647132004-05-07 17:57:49 +00002645 pPayload += n;
drh9b171272004-05-08 02:03:22 +00002646 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00002647 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00002648 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00002649 if( nSrc==0 ){
2650 nSrc = nData;
2651 pSrc = pData;
2652 }
drhdd793422001-06-28 01:54:48 +00002653 }
drh9b171272004-05-08 02:03:22 +00002654 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00002655 return SQLITE_OK;
2656}
2657
2658/*
drhbd03cae2001-06-02 02:40:57 +00002659** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00002660** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00002661** pointer in the third argument.
2662*/
drh4b70f112004-05-02 21:12:19 +00002663static void reparentPage(Btree *pBt, Pgno pgno, MemPage *pNewParent, int idx){
drhbd03cae2001-06-02 02:40:57 +00002664 MemPage *pThis;
drh4b70f112004-05-02 21:12:19 +00002665 unsigned char *aData;
drhbd03cae2001-06-02 02:40:57 +00002666
drhdd793422001-06-28 01:54:48 +00002667 if( pgno==0 ) return;
drh4b70f112004-05-02 21:12:19 +00002668 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00002669 aData = sqlite3pager_lookup(pBt->pPager, pgno);
drhda200cc2004-05-09 11:51:38 +00002670 if( aData ){
drhb6f41482004-05-14 01:58:11 +00002671 pThis = (MemPage*)&aData[pBt->usableSize];
drhda200cc2004-05-09 11:51:38 +00002672 if( pThis->isInit ){
2673 if( pThis->pParent!=pNewParent ){
2674 if( pThis->pParent ) sqlite3pager_unref(pThis->pParent->aData);
2675 pThis->pParent = pNewParent;
2676 if( pNewParent ) sqlite3pager_ref(pNewParent->aData);
2677 }
2678 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00002679 }
drha34b6762004-05-07 13:30:42 +00002680 sqlite3pager_unref(aData);
drhbd03cae2001-06-02 02:40:57 +00002681 }
2682}
2683
2684/*
drh4b70f112004-05-02 21:12:19 +00002685** Change the pParent pointer of all children of pPage to point back
2686** to pPage.
2687**
drhbd03cae2001-06-02 02:40:57 +00002688** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00002689** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00002690**
2691** This routine gets called after you memcpy() one page into
2692** another.
2693*/
drh4b70f112004-05-02 21:12:19 +00002694static void reparentChildPages(MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00002695 int i;
drh4b70f112004-05-02 21:12:19 +00002696 Btree *pBt;
2697
drha34b6762004-05-07 13:30:42 +00002698 if( pPage->leaf ) return;
drh4b70f112004-05-02 21:12:19 +00002699 pBt = pPage->pBt;
drhbd03cae2001-06-02 02:40:57 +00002700 for(i=0; i<pPage->nCell; i++){
drh43605152004-05-29 21:46:49 +00002701 reparentPage(pBt, get4byte(findCell(pPage,i)), pPage, i);
drhbd03cae2001-06-02 02:40:57 +00002702 }
drh43605152004-05-29 21:46:49 +00002703 reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]), pPage, i);
drh428ae8c2003-01-04 16:48:09 +00002704 pPage->idxShift = 0;
drh14acc042001-06-10 19:56:58 +00002705}
2706
2707/*
2708** Remove the i-th cell from pPage. This routine effects pPage only.
2709** The cell content is not freed or deallocated. It is assumed that
2710** the cell content has been copied someplace else. This routine just
2711** removes the reference to the cell from pPage.
2712**
2713** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00002714*/
drh4b70f112004-05-02 21:12:19 +00002715static void dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00002716 int i; /* Loop counter */
2717 int pc; /* Offset to cell content of cell being deleted */
2718 u8 *data; /* pPage->aData */
2719 u8 *ptr; /* Used to move bytes around within data[] */
2720
drh8c42ca92001-06-22 19:15:00 +00002721 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00002722 assert( sz==cellSize(pPage, idx) );
drha34b6762004-05-07 13:30:42 +00002723 assert( sqlite3pager_iswriteable(pPage->aData) );
drhda200cc2004-05-09 11:51:38 +00002724 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00002725 ptr = &data[pPage->cellOffset + 2*idx];
2726 pc = get2byte(ptr);
2727 assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
drhde647132004-05-07 17:57:49 +00002728 freeSpace(pPage, pc, sz);
drh43605152004-05-29 21:46:49 +00002729 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
2730 ptr[0] = ptr[2];
2731 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00002732 }
2733 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00002734 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
2735 pPage->nFree += 2;
drh428ae8c2003-01-04 16:48:09 +00002736 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00002737}
2738
2739/*
2740** Insert a new cell on pPage at cell index "i". pCell points to the
2741** content of the cell.
2742**
2743** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00002744** will not fit, then make a copy of the cell content into pTemp if
2745** pTemp is not null. Regardless of pTemp, allocate a new entry
2746** in pPage->aOvfl[] and make it point to the cell content (either
2747** in pTemp or the original pCell) and also record its index.
2748** Allocating a new entry in pPage->aCell[] implies that
2749** pPage->nOverflow is incremented.
drh14acc042001-06-10 19:56:58 +00002750*/
drh24cd67e2004-05-10 16:18:47 +00002751static void insertCell(
2752 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00002753 int i, /* New cell becomes the i-th cell of the page */
2754 u8 *pCell, /* Content of the new cell */
2755 int sz, /* Bytes of content in pCell */
drh24cd67e2004-05-10 16:18:47 +00002756 u8 *pTemp /* Temp storage space for pCell, if needed */
2757){
drh43605152004-05-29 21:46:49 +00002758 int idx; /* Where to write new cell content in data[] */
2759 int j; /* Loop counter */
2760 int top; /* First byte of content for any cell in data[] */
2761 int end; /* First byte past the last cell pointer in data[] */
2762 int ins; /* Index in data[] where new cell pointer is inserted */
2763 int hdr; /* Offset into data[] of the page header */
2764 int cellOffset; /* Address of first cell pointer in data[] */
2765 u8 *data; /* The content of the whole page */
2766 u8 *ptr; /* Used for moving information around in data[] */
2767
2768 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
2769 assert( sz==cellSizePtr(pPage, pCell) );
drha34b6762004-05-07 13:30:42 +00002770 assert( sqlite3pager_iswriteable(pPage->aData) );
drh43605152004-05-29 21:46:49 +00002771 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00002772 if( pTemp ){
2773 memcpy(pTemp, pCell, sz);
drh43605152004-05-29 21:46:49 +00002774 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00002775 }
drh43605152004-05-29 21:46:49 +00002776 j = pPage->nOverflow++;
2777 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
2778 pPage->aOvfl[j].pCell = pCell;
2779 pPage->aOvfl[j].idx = i;
2780 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00002781 }else{
drh43605152004-05-29 21:46:49 +00002782 data = pPage->aData;
2783 hdr = pPage->hdrOffset;
2784 top = get2byte(&data[hdr+5]);
2785 cellOffset = pPage->cellOffset;
2786 end = cellOffset + 2*pPage->nCell + 2;
2787 ins = cellOffset + 2*i;
2788 if( end > top - sz ){
2789 defragmentPage(pPage);
2790 top = get2byte(&data[hdr+5]);
2791 assert( end + sz <= top );
2792 }
2793 idx = allocateSpace(pPage, sz);
2794 assert( idx>0 );
2795 assert( end <= get2byte(&data[hdr+5]) );
2796 pPage->nCell++;
2797 pPage->nFree -= 2;
drhda200cc2004-05-09 11:51:38 +00002798 memcpy(&data[idx], pCell, sz);
drh43605152004-05-29 21:46:49 +00002799 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
2800 ptr[0] = ptr[-2];
2801 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00002802 }
drh43605152004-05-29 21:46:49 +00002803 put2byte(&data[ins], idx);
2804 put2byte(&data[hdr+3], pPage->nCell);
2805 pPage->idxShift = 1;
drhda200cc2004-05-09 11:51:38 +00002806 pageIntegrity(pPage);
drh14acc042001-06-10 19:56:58 +00002807 }
2808}
2809
2810/*
drhfa1a98a2004-05-14 19:08:17 +00002811** Add a list of cells to a page. The page should be initially empty.
2812** The cells are guaranteed to fit on the page.
2813*/
2814static void assemblePage(
2815 MemPage *pPage, /* The page to be assemblied */
2816 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00002817 u8 **apCell, /* Pointers to cell bodies */
drhfa1a98a2004-05-14 19:08:17 +00002818 int *aSize /* Sizes of the cells */
2819){
2820 int i; /* Loop counter */
2821 int totalSize; /* Total size of all cells */
2822 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00002823 int cellptr; /* Address of next cell pointer */
2824 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00002825 u8 *data; /* Data for the page */
2826
drh43605152004-05-29 21:46:49 +00002827 assert( pPage->nOverflow==0 );
drhfa1a98a2004-05-14 19:08:17 +00002828 totalSize = 0;
2829 for(i=0; i<nCell; i++){
2830 totalSize += aSize[i];
2831 }
drh43605152004-05-29 21:46:49 +00002832 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00002833 assert( pPage->nCell==0 );
drh43605152004-05-29 21:46:49 +00002834 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00002835 data = pPage->aData;
2836 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00002837 put2byte(&data[hdr+3], nCell);
2838 cellbody = allocateSpace(pPage, totalSize);
2839 assert( cellbody>0 );
2840 assert( pPage->nFree >= 2*nCell );
2841 pPage->nFree -= 2*nCell;
drhfa1a98a2004-05-14 19:08:17 +00002842 for(i=0; i<nCell; i++){
drh43605152004-05-29 21:46:49 +00002843 put2byte(&data[cellptr], cellbody);
2844 memcpy(&data[cellbody], apCell[i], aSize[i]);
2845 cellptr += 2;
2846 cellbody += aSize[i];
drhfa1a98a2004-05-14 19:08:17 +00002847 }
drh43605152004-05-29 21:46:49 +00002848 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00002849 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00002850}
2851
drh14acc042001-06-10 19:56:58 +00002852/*
drhc8629a12004-05-08 20:07:40 +00002853** GCC does not define the offsetof() macro so we'll have to do it
2854** ourselves.
2855*/
2856#ifndef offsetof
2857#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
2858#endif
2859
2860/*
drhc3b70572003-01-04 19:44:07 +00002861** The following parameters determine how many adjacent pages get involved
2862** in a balancing operation. NN is the number of neighbors on either side
2863** of the page that participate in the balancing operation. NB is the
2864** total number of pages that participate, including the target page and
2865** NN neighbors on either side.
2866**
2867** The minimum value of NN is 1 (of course). Increasing NN above 1
2868** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
2869** in exchange for a larger degradation in INSERT and UPDATE performance.
2870** The value of NN appears to give the best results overall.
2871*/
2872#define NN 1 /* Number of neighbors on either side of pPage */
2873#define NB (NN*2+1) /* Total pages involved in the balance */
2874
drh43605152004-05-29 21:46:49 +00002875/* Forward reference */
2876static int balance(MemPage*);
2877
drhc3b70572003-01-04 19:44:07 +00002878/*
drhab01f612004-05-22 02:55:23 +00002879** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00002880** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00002881** Usually NN siblings on either side of pPage is used in the balancing,
2882** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00002883** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00002884** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00002885** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00002886**
drh0c6cc4e2004-06-15 02:13:26 +00002887** The number of siblings of pPage might be increased or decreased by one or
2888** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00002889** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00002890** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00002891** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00002892** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00002893**
drh8b2f49b2001-06-08 00:21:52 +00002894** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00002895** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00002896** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00002897** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00002898**
drh8c42ca92001-06-22 19:15:00 +00002899** In the course of balancing the siblings of pPage, the parent of pPage
2900** might become overfull or underfull. If that happens, then this routine
2901** is called recursively on the parent.
2902**
drh5e00f6c2001-09-13 13:46:56 +00002903** If this routine fails for any reason, it might leave the database
2904** in a corrupted state. So if this routine fails, the database should
2905** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00002906*/
drh43605152004-05-29 21:46:49 +00002907static int balance_nonroot(MemPage *pPage){
drh8b2f49b2001-06-08 00:21:52 +00002908 MemPage *pParent; /* The parent of pPage */
drh4b70f112004-05-02 21:12:19 +00002909 Btree *pBt; /* The whole database */
danielk1977cfe9a692004-06-16 12:00:29 +00002910 int nCell = 0; /* Number of cells in aCell[] */
drh8b2f49b2001-06-08 00:21:52 +00002911 int nOld; /* Number of pages in apOld[] */
2912 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00002913 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00002914 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00002915 int idx; /* Index of pPage in pParent->aCell[] */
2916 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00002917 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00002918 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00002919 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00002920 int usableSpace; /* Bytes in pPage beyond the header */
2921 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00002922 int subtotal; /* Subtotal of bytes in cells on one page */
drhb6f41482004-05-14 01:58:11 +00002923 int iSpace = 0; /* First unused byte of aSpace[] */
drh2e38c322004-09-03 18:38:44 +00002924 int mxCellPerPage; /* Maximum number of cells in one page */
drhc3b70572003-01-04 19:44:07 +00002925 MemPage *apOld[NB]; /* pPage and up to two siblings */
2926 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00002927 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00002928 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
2929 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drhc3b70572003-01-04 19:44:07 +00002930 int idxDiv[NB]; /* Indices of divider cells in pParent */
drh4b70f112004-05-02 21:12:19 +00002931 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00002932 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
2933 int szNew[NB+2]; /* Combined size of cells place on i-th page */
drh2e38c322004-09-03 18:38:44 +00002934 u8 **apCell; /* All cells begin balanced */
2935 int *szCell; /* Local size of all cells in apCell[] */
2936 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
2937 u8 *aSpace; /* Space to hold copies of dividers cells */
drh8b2f49b2001-06-08 00:21:52 +00002938
drh14acc042001-06-10 19:56:58 +00002939 /*
drh43605152004-05-29 21:46:49 +00002940 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00002941 */
drh3a4c1412004-05-09 20:40:11 +00002942 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00002943 assert( sqlite3pager_iswriteable(pPage->aData) );
drh4b70f112004-05-02 21:12:19 +00002944 pBt = pPage->pBt;
drh14acc042001-06-10 19:56:58 +00002945 pParent = pPage->pParent;
drh43605152004-05-29 21:46:49 +00002946 sqlite3pager_write(pParent->aData);
2947 assert( pParent );
2948 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00002949
2950 /*
2951 ** Allocate space for memory structures
2952 */
2953 mxCellPerPage = MX_CELL(pBt);
2954 apCell = sqliteMallocRaw(
2955 (mxCellPerPage+2)*NB*(sizeof(u8*)+sizeof(int))
2956 + sizeof(MemPage)*NB
2957 + pBt->pageSize*(5+NB)
2958 );
2959 if( apCell==0 ){
2960 return SQLITE_NOMEM;
2961 }
2962 szCell = (int*)&apCell[(mxCellPerPage+2)*NB];
2963 aCopy[0] = (u8*)&szCell[(mxCellPerPage+2)*NB];
2964 for(i=1; i<NB; i++){
2965 aCopy[i] = &aCopy[i-1][pBt->pageSize+sizeof(MemPage)];
2966 }
2967 aSpace = &aCopy[NB-1][pBt->pageSize+sizeof(MemPage)];
drh14acc042001-06-10 19:56:58 +00002968
drh8b2f49b2001-06-08 00:21:52 +00002969 /*
drh4b70f112004-05-02 21:12:19 +00002970 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00002971 ** to pPage. The "idx" variable is the index of that cell. If pPage
2972 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00002973 */
drhbb49aba2003-01-04 18:53:27 +00002974 if( pParent->idxShift ){
drha34b6762004-05-07 13:30:42 +00002975 Pgno pgno;
drh4b70f112004-05-02 21:12:19 +00002976 pgno = pPage->pgno;
drha34b6762004-05-07 13:30:42 +00002977 assert( pgno==sqlite3pager_pagenumber(pPage->aData) );
drhbb49aba2003-01-04 18:53:27 +00002978 for(idx=0; idx<pParent->nCell; idx++){
drh43605152004-05-29 21:46:49 +00002979 if( get4byte(findCell(pParent, idx))==pgno ){
drhbb49aba2003-01-04 18:53:27 +00002980 break;
2981 }
drh8b2f49b2001-06-08 00:21:52 +00002982 }
drh4b70f112004-05-02 21:12:19 +00002983 assert( idx<pParent->nCell
drh43605152004-05-29 21:46:49 +00002984 || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
drhbb49aba2003-01-04 18:53:27 +00002985 }else{
2986 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00002987 }
drh8b2f49b2001-06-08 00:21:52 +00002988
2989 /*
drh14acc042001-06-10 19:56:58 +00002990 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00002991 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00002992 */
drh14acc042001-06-10 19:56:58 +00002993 nOld = nNew = 0;
drha34b6762004-05-07 13:30:42 +00002994 sqlite3pager_ref(pParent->aData);
drh14acc042001-06-10 19:56:58 +00002995
2996 /*
drh4b70f112004-05-02 21:12:19 +00002997 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00002998 ** the siblings. An attempt is made to find NN siblings on either
2999 ** side of pPage. More siblings are taken from one side, however, if
3000 ** pPage there are fewer than NN siblings on the other side. If pParent
3001 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00003002 */
drhc3b70572003-01-04 19:44:07 +00003003 nxDiv = idx - NN;
3004 if( nxDiv + NB > pParent->nCell ){
3005 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00003006 }
drhc3b70572003-01-04 19:44:07 +00003007 if( nxDiv<0 ){
3008 nxDiv = 0;
3009 }
drh8b2f49b2001-06-08 00:21:52 +00003010 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00003011 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00003012 if( k<pParent->nCell ){
3013 idxDiv[i] = k;
drh43605152004-05-29 21:46:49 +00003014 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00003015 nDiv++;
drha34b6762004-05-07 13:30:42 +00003016 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00003017 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00003018 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00003019 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00003020 }else{
3021 break;
drh8b2f49b2001-06-08 00:21:52 +00003022 }
drhde647132004-05-07 17:57:49 +00003023 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00003024 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00003025 apOld[i]->idxParent = k;
drh91025292004-05-03 19:49:32 +00003026 apCopy[i] = 0;
3027 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00003028 nOld++;
drh8b2f49b2001-06-08 00:21:52 +00003029 }
3030
3031 /*
drh14acc042001-06-10 19:56:58 +00003032 ** Make copies of the content of pPage and its siblings into aOld[].
3033 ** The rest of this function will use data from the copies rather
3034 ** that the original pages since the original pages will be in the
3035 ** process of being overwritten.
3036 */
3037 for(i=0; i<nOld; i++){
drh2e38c322004-09-03 18:38:44 +00003038 MemPage *p = apCopy[i] = (MemPage*)&aCopy[i][pBt->pageSize];
drh43605152004-05-29 21:46:49 +00003039 p->aData = &((u8*)p)[-pBt->pageSize];
3040 memcpy(p->aData, apOld[i]->aData, pBt->pageSize + sizeof(MemPage));
3041 p->aData = &((u8*)p)[-pBt->pageSize];
drh14acc042001-06-10 19:56:58 +00003042 }
3043
3044 /*
3045 ** Load pointers to all cells on sibling pages and the divider cells
3046 ** into the local apCell[] array. Make copies of the divider cells
drhb6f41482004-05-14 01:58:11 +00003047 ** into space obtained form aSpace[] and remove the the divider Cells
3048 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00003049 **
3050 ** If the siblings are on leaf pages, then the child pointers of the
3051 ** divider cells are stripped from the cells before they are copied
drh96f5b762004-05-16 16:24:36 +00003052 ** into aSpace[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00003053 ** child pointers. If siblings are not leaves, then all cell in
3054 ** apCell[] include child pointers. Either way, all cells in apCell[]
3055 ** are alike.
drh96f5b762004-05-16 16:24:36 +00003056 **
3057 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
3058 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00003059 */
3060 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00003061 leafCorrection = pPage->leaf*4;
drh8b18dd42004-05-12 19:18:15 +00003062 leafData = pPage->leafData && pPage->leaf;
drh8b2f49b2001-06-08 00:21:52 +00003063 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00003064 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00003065 int limit = pOld->nCell+pOld->nOverflow;
3066 for(j=0; j<limit; j++){
3067 apCell[nCell] = findOverflowCell(pOld, j);
3068 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
drh14acc042001-06-10 19:56:58 +00003069 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00003070 }
3071 if( i<nOld-1 ){
drh43605152004-05-29 21:46:49 +00003072 int sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00003073 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00003074 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
3075 ** are duplicates of keys on the child pages. We need to remove
3076 ** the divider cells from pParent, but the dividers cells are not
3077 ** added to apCell[] because they are duplicates of child cells.
3078 */
drh8b18dd42004-05-12 19:18:15 +00003079 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00003080 }else{
drhb6f41482004-05-14 01:58:11 +00003081 u8 *pTemp;
3082 szCell[nCell] = sz;
3083 pTemp = &aSpace[iSpace];
3084 iSpace += sz;
drh2e38c322004-09-03 18:38:44 +00003085 assert( iSpace<=pBt->pageSize*5 );
drhb6f41482004-05-14 01:58:11 +00003086 memcpy(pTemp, apDiv[i], sz);
3087 apCell[nCell] = pTemp+leafCorrection;
3088 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00003089 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00003090 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00003091 if( !pOld->leaf ){
3092 assert( leafCorrection==0 );
3093 /* The right pointer of the child page pOld becomes the left
3094 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00003095 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00003096 }else{
3097 assert( leafCorrection==4 );
3098 }
3099 nCell++;
drh4b70f112004-05-02 21:12:19 +00003100 }
drh8b2f49b2001-06-08 00:21:52 +00003101 }
3102 }
3103
3104 /*
drh6019e162001-07-02 17:51:45 +00003105 ** Figure out the number of pages needed to hold all nCell cells.
3106 ** Store this number in "k". Also compute szNew[] which is the total
3107 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00003108 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00003109 ** cntNew[k] should equal nCell.
3110 **
drh96f5b762004-05-16 16:24:36 +00003111 ** Values computed by this block:
3112 **
3113 ** k: The total number of sibling pages
3114 ** szNew[i]: Spaced used on the i-th sibling page.
3115 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
3116 ** the right of the i-th sibling page.
3117 ** usableSpace: Number of bytes of space available on each sibling.
3118 **
drh8b2f49b2001-06-08 00:21:52 +00003119 */
drh43605152004-05-29 21:46:49 +00003120 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00003121 for(subtotal=k=i=0; i<nCell; i++){
drh43605152004-05-29 21:46:49 +00003122 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00003123 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00003124 szNew[k] = subtotal - szCell[i];
3125 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00003126 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00003127 subtotal = 0;
3128 k++;
3129 }
3130 }
3131 szNew[k] = subtotal;
3132 cntNew[k] = nCell;
3133 k++;
drh96f5b762004-05-16 16:24:36 +00003134
3135 /*
3136 ** The packing computed by the previous block is biased toward the siblings
3137 ** on the left side. The left siblings are always nearly full, while the
3138 ** right-most sibling might be nearly empty. This block of code attempts
3139 ** to adjust the packing of siblings to get a better balance.
3140 **
3141 ** This adjustment is more than an optimization. The packing above might
3142 ** be so out of balance as to be illegal. For example, the right-most
3143 ** sibling might be completely empty. This adjustment is not optional.
3144 */
drh6019e162001-07-02 17:51:45 +00003145 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00003146 int szRight = szNew[i]; /* Size of sibling on the right */
3147 int szLeft = szNew[i-1]; /* Size of sibling on the left */
3148 int r; /* Index of right-most cell in left sibling */
3149 int d; /* Index of first cell to the left of right sibling */
3150
3151 r = cntNew[i-1] - 1;
3152 d = r + 1 - leafData;
drh43605152004-05-29 21:46:49 +00003153 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
3154 szRight += szCell[d] + 2;
3155 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00003156 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00003157 r = cntNew[i-1] - 1;
3158 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00003159 }
drh96f5b762004-05-16 16:24:36 +00003160 szNew[i] = szRight;
3161 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00003162 }
3163 assert( cntNew[0]>0 );
drh8b2f49b2001-06-08 00:21:52 +00003164
3165 /*
drh6b308672002-07-08 02:16:37 +00003166 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00003167 */
drh4b70f112004-05-02 21:12:19 +00003168 assert( pPage->pgno>1 );
3169 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00003170 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00003171 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00003172 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00003173 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00003174 pgnoNew[i] = pgnoOld[i];
3175 apOld[i] = 0;
drhda200cc2004-05-09 11:51:38 +00003176 sqlite3pager_write(pNew->aData);
drh6b308672002-07-08 02:16:37 +00003177 }else{
drhda200cc2004-05-09 11:51:38 +00003178 rc = allocatePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1]);
drh6b308672002-07-08 02:16:37 +00003179 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00003180 apNew[i] = pNew;
drh6b308672002-07-08 02:16:37 +00003181 }
drh14acc042001-06-10 19:56:58 +00003182 nNew++;
drhda200cc2004-05-09 11:51:38 +00003183 zeroPage(pNew, pageFlags);
drh8b2f49b2001-06-08 00:21:52 +00003184 }
3185
drh6b308672002-07-08 02:16:37 +00003186 /* Free any old pages that were not reused as new pages.
3187 */
3188 while( i<nOld ){
drh4b70f112004-05-02 21:12:19 +00003189 rc = freePage(apOld[i]);
drh6b308672002-07-08 02:16:37 +00003190 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00003191 releasePage(apOld[i]);
drh6b308672002-07-08 02:16:37 +00003192 apOld[i] = 0;
3193 i++;
3194 }
3195
drh8b2f49b2001-06-08 00:21:52 +00003196 /*
drhf9ffac92002-03-02 19:00:31 +00003197 ** Put the new pages in accending order. This helps to
3198 ** keep entries in the disk file in order so that a scan
3199 ** of the table is a linear scan through the file. That
3200 ** in turn helps the operating system to deliver pages
3201 ** from the disk more rapidly.
3202 **
3203 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00003204 ** n is never more than NB (a small constant), that should
3205 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00003206 **
drhc3b70572003-01-04 19:44:07 +00003207 ** When NB==3, this one optimization makes the database
3208 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00003209 */
3210 for(i=0; i<k-1; i++){
3211 int minV = pgnoNew[i];
3212 int minI = i;
3213 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00003214 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00003215 minI = j;
3216 minV = pgnoNew[j];
3217 }
3218 }
3219 if( minI>i ){
3220 int t;
3221 MemPage *pT;
3222 t = pgnoNew[i];
3223 pT = apNew[i];
3224 pgnoNew[i] = pgnoNew[minI];
3225 apNew[i] = apNew[minI];
3226 pgnoNew[minI] = t;
3227 apNew[minI] = pT;
3228 }
3229 }
drha2fce642004-06-05 00:01:44 +00003230 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00003231 pgnoOld[0],
3232 nOld>=2 ? pgnoOld[1] : 0,
3233 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00003234 pgnoNew[0], szNew[0],
3235 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
3236 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00003237 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
3238 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00003239
drhf9ffac92002-03-02 19:00:31 +00003240
3241 /*
drh14acc042001-06-10 19:56:58 +00003242 ** Evenly distribute the data in apCell[] across the new pages.
3243 ** Insert divider cells into pParent as necessary.
3244 */
3245 j = 0;
3246 for(i=0; i<nNew; i++){
3247 MemPage *pNew = apNew[i];
drh4b70f112004-05-02 21:12:19 +00003248 assert( pNew->pgno==pgnoNew[i] );
drhfa1a98a2004-05-14 19:08:17 +00003249 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
3250 j = cntNew[i];
drh6019e162001-07-02 17:51:45 +00003251 assert( pNew->nCell>0 );
drh43605152004-05-29 21:46:49 +00003252 assert( pNew->nOverflow==0 );
drh14acc042001-06-10 19:56:58 +00003253 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00003254 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00003255 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00003256 int sz;
3257 pCell = apCell[j];
3258 sz = szCell[j] + leafCorrection;
drh4b70f112004-05-02 21:12:19 +00003259 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00003260 memcpy(&pNew->aData[8], pCell, 4);
drh24cd67e2004-05-10 16:18:47 +00003261 pTemp = 0;
drh8b18dd42004-05-12 19:18:15 +00003262 }else if( leafData ){
drh6f11bef2004-05-13 01:12:56 +00003263 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00003264 j--;
drh43605152004-05-29 21:46:49 +00003265 parseCellPtr(pNew, apCell[j], &info);
drhb6f41482004-05-14 01:58:11 +00003266 pCell = &aSpace[iSpace];
drh6f11bef2004-05-13 01:12:56 +00003267 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, &sz);
drhb6f41482004-05-14 01:58:11 +00003268 iSpace += sz;
drh2e38c322004-09-03 18:38:44 +00003269 assert( iSpace<=pBt->pageSize*5 );
drh8b18dd42004-05-12 19:18:15 +00003270 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00003271 }else{
3272 pCell -= 4;
drhb6f41482004-05-14 01:58:11 +00003273 pTemp = &aSpace[iSpace];
3274 iSpace += sz;
drh2e38c322004-09-03 18:38:44 +00003275 assert( iSpace<=pBt->pageSize*5 );
drh4b70f112004-05-02 21:12:19 +00003276 }
drh8b18dd42004-05-12 19:18:15 +00003277 insertCell(pParent, nxDiv, pCell, sz, pTemp);
drh43605152004-05-29 21:46:49 +00003278 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
drh14acc042001-06-10 19:56:58 +00003279 j++;
3280 nxDiv++;
3281 }
3282 }
drh6019e162001-07-02 17:51:45 +00003283 assert( j==nCell );
drh4b70f112004-05-02 21:12:19 +00003284 if( (pageFlags & PTF_LEAF)==0 ){
drh43605152004-05-29 21:46:49 +00003285 memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
drh14acc042001-06-10 19:56:58 +00003286 }
drh43605152004-05-29 21:46:49 +00003287 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00003288 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00003289 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00003290 }else{
3291 /* Right-most sibling is the left child of the first entry in pParent
3292 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00003293 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00003294 }
3295
3296 /*
3297 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00003298 */
3299 for(i=0; i<nNew; i++){
drh4b70f112004-05-02 21:12:19 +00003300 reparentChildPages(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00003301 }
drh4b70f112004-05-02 21:12:19 +00003302 reparentChildPages(pParent);
drh8b2f49b2001-06-08 00:21:52 +00003303
3304 /*
drh3a4c1412004-05-09 20:40:11 +00003305 ** Balance the parent page. Note that the current page (pPage) might
3306 ** have been added to the freelist is it might no longer be initialized.
3307 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00003308 */
drhda200cc2004-05-09 11:51:38 +00003309 assert( pParent->isInit );
drh3a4c1412004-05-09 20:40:11 +00003310 /* assert( pPage->isInit ); // No! pPage might have been added to freelist */
3311 /* pageIntegrity(pPage); // No! pPage might have been added to freelist */
drh4b70f112004-05-02 21:12:19 +00003312 rc = balance(pParent);
drhda200cc2004-05-09 11:51:38 +00003313
drh8b2f49b2001-06-08 00:21:52 +00003314 /*
drh14acc042001-06-10 19:56:58 +00003315 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00003316 */
drh14acc042001-06-10 19:56:58 +00003317balance_cleanup:
drh2e38c322004-09-03 18:38:44 +00003318 sqliteFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00003319 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00003320 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00003321 }
drh14acc042001-06-10 19:56:58 +00003322 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00003323 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00003324 }
drh91025292004-05-03 19:49:32 +00003325 releasePage(pParent);
drh3a4c1412004-05-09 20:40:11 +00003326 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
3327 pPage->pgno, nOld, nNew, nCell));
drh8b2f49b2001-06-08 00:21:52 +00003328 return rc;
3329}
3330
3331/*
drh43605152004-05-29 21:46:49 +00003332** This routine is called for the root page of a btree when the root
3333** page contains no cells. This is an opportunity to make the tree
3334** shallower by one level.
3335*/
3336static int balance_shallower(MemPage *pPage){
3337 MemPage *pChild; /* The only child page of pPage */
3338 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00003339 int rc = SQLITE_OK; /* Return code from subprocedures */
3340 Btree *pBt; /* The main BTree structure */
3341 int mxCellPerPage; /* Maximum number of cells per page */
3342 u8 **apCell; /* All cells from pages being balanced */
3343 int *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00003344
3345 assert( pPage->pParent==0 );
3346 assert( pPage->nCell==0 );
drh2e38c322004-09-03 18:38:44 +00003347 pBt = pPage->pBt;
3348 mxCellPerPage = MX_CELL(pBt);
3349 apCell = sqliteMallocRaw( mxCellPerPage*(sizeof(u8*)+sizeof(int)) );
3350 if( apCell==0 ) return SQLITE_NOMEM;
3351 szCell = (int*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00003352 if( pPage->leaf ){
3353 /* The table is completely empty */
3354 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
3355 }else{
3356 /* The root page is empty but has one child. Transfer the
3357 ** information from that one child into the root page if it
3358 ** will fit. This reduces the depth of the tree by one.
3359 **
3360 ** If the root page is page 1, it has less space available than
3361 ** its child (due to the 100 byte header that occurs at the beginning
3362 ** of the database fle), so it might not be able to hold all of the
3363 ** information currently contained in the child. If this is the
3364 ** case, then do not do the transfer. Leave page 1 empty except
3365 ** for the right-pointer to the child page. The child page becomes
3366 ** the virtual root of the tree.
3367 */
3368 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
3369 assert( pgnoChild>0 );
3370 assert( pgnoChild<=sqlite3pager_pagecount(pPage->pBt->pPager) );
3371 rc = getPage(pPage->pBt, pgnoChild, &pChild);
drh2e38c322004-09-03 18:38:44 +00003372 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00003373 if( pPage->pgno==1 ){
3374 rc = initPage(pChild, pPage);
drh2e38c322004-09-03 18:38:44 +00003375 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00003376 assert( pChild->nOverflow==0 );
3377 if( pChild->nFree>=100 ){
3378 /* The child information will fit on the root page, so do the
3379 ** copy */
3380 int i;
3381 zeroPage(pPage, pChild->aData[0]);
3382 for(i=0; i<pChild->nCell; i++){
3383 apCell[i] = findCell(pChild,i);
3384 szCell[i] = cellSizePtr(pChild, apCell[i]);
3385 }
3386 assemblePage(pPage, pChild->nCell, apCell, szCell);
3387 freePage(pChild);
3388 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
3389 }else{
3390 /* The child has more information that will fit on the root.
3391 ** The tree is already balanced. Do nothing. */
3392 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
3393 }
3394 }else{
3395 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
3396 pPage->isInit = 0;
3397 pPage->pParent = 0;
3398 rc = initPage(pPage, 0);
3399 assert( rc==SQLITE_OK );
3400 freePage(pChild);
3401 TRACE(("BALANCE: transfer child %d into root %d\n",
3402 pChild->pgno, pPage->pgno));
3403 }
3404 reparentChildPages(pPage);
3405 releasePage(pChild);
3406 }
drh2e38c322004-09-03 18:38:44 +00003407end_shallow_balance:
3408 sqliteFree(apCell);
3409 return rc;
drh43605152004-05-29 21:46:49 +00003410}
3411
3412
3413/*
3414** The root page is overfull
3415**
3416** When this happens, Create a new child page and copy the
3417** contents of the root into the child. Then make the root
3418** page an empty page with rightChild pointing to the new
3419** child. Finally, call balance_internal() on the new child
3420** to cause it to split.
3421*/
3422static int balance_deeper(MemPage *pPage){
3423 int rc; /* Return value from subprocedures */
3424 MemPage *pChild; /* Pointer to a new child page */
3425 Pgno pgnoChild; /* Page number of the new child page */
3426 Btree *pBt; /* The BTree */
3427 int usableSize; /* Total usable size of a page */
3428 u8 *data; /* Content of the parent page */
3429 u8 *cdata; /* Content of the child page */
3430 int hdr; /* Offset to page header in parent */
3431 int brk; /* Offset to content of first cell in parent */
3432
3433 assert( pPage->pParent==0 );
3434 assert( pPage->nOverflow>0 );
3435 pBt = pPage->pBt;
3436 rc = allocatePage(pBt, &pChild, &pgnoChild, pPage->pgno);
3437 if( rc ) return rc;
3438 assert( sqlite3pager_iswriteable(pChild->aData) );
3439 usableSize = pBt->usableSize;
3440 data = pPage->aData;
3441 hdr = pPage->hdrOffset;
3442 brk = get2byte(&data[hdr+5]);
3443 cdata = pChild->aData;
3444 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
3445 memcpy(&cdata[brk], &data[brk], usableSize-brk);
3446 rc = initPage(pChild, pPage);
3447 if( rc ) return rc;
3448 memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
3449 pChild->nOverflow = pPage->nOverflow;
3450 if( pChild->nOverflow ){
3451 pChild->nFree = 0;
3452 }
3453 assert( pChild->nCell==pPage->nCell );
3454 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
3455 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
3456 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
3457 rc = balance_nonroot(pChild);
3458 releasePage(pChild);
3459 return rc;
3460}
3461
3462/*
3463** Decide if the page pPage needs to be balanced. If balancing is
3464** required, call the appropriate balancing routine.
3465*/
3466static int balance(MemPage *pPage){
3467 int rc = SQLITE_OK;
3468 if( pPage->pParent==0 ){
3469 if( pPage->nOverflow>0 ){
3470 rc = balance_deeper(pPage);
3471 }
3472 if( pPage->nCell==0 ){
3473 rc = balance_shallower(pPage);
3474 }
3475 }else{
3476 if( pPage->nOverflow>0 || pPage->nFree>pPage->pBt->usableSize*2/3 ){
3477 rc = balance_nonroot(pPage);
3478 }
3479 }
3480 return rc;
3481}
3482
3483/*
drh8dcd7ca2004-08-08 19:43:29 +00003484** This routine checks all cursors that point to table pgnoRoot.
3485** If any of those cursors other than pExclude were opened with
drhf74b8d92002-09-01 23:20:45 +00003486** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
drh8dcd7ca2004-08-08 19:43:29 +00003487** cursors that point to pgnoRoot were opened with wrFlag==1
drhf74b8d92002-09-01 23:20:45 +00003488** then this routine returns SQLITE_OK.
3489**
3490** In addition to checking for read-locks (where a read-lock
3491** means a cursor opened with wrFlag==0) this routine also moves
drh8dcd7ca2004-08-08 19:43:29 +00003492** all cursors other than pExclude so that they are pointing to the
drhf74b8d92002-09-01 23:20:45 +00003493** first Cell on root page. This is necessary because an insert
3494** or delete might change the number of cells on a page or delete
3495** a page entirely and we do not want to leave any cursors
3496** pointing to non-existant pages or cells.
3497*/
drh8dcd7ca2004-08-08 19:43:29 +00003498static int checkReadLocks(Btree *pBt, Pgno pgnoRoot, BtCursor *pExclude){
drhf74b8d92002-09-01 23:20:45 +00003499 BtCursor *p;
drh8dcd7ca2004-08-08 19:43:29 +00003500 for(p=pBt->pCursor; p; p=p->pNext){
3501 if( p->pgnoRoot!=pgnoRoot || p==pExclude ) continue;
drhf74b8d92002-09-01 23:20:45 +00003502 if( p->wrFlag==0 ) return SQLITE_LOCKED;
drh91025292004-05-03 19:49:32 +00003503 if( p->pPage->pgno!=p->pgnoRoot ){
drhf74b8d92002-09-01 23:20:45 +00003504 moveToRoot(p);
3505 }
3506 }
3507 return SQLITE_OK;
3508}
3509
3510/*
drh3b7511c2001-05-26 13:15:44 +00003511** Insert a new record into the BTree. The key is given by (pKey,nKey)
3512** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00003513** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00003514** is left pointing at a random location.
3515**
3516** For an INTKEY table, only the nKey value of the key is used. pKey is
3517** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00003518*/
drh3aac2dd2004-04-26 14:10:20 +00003519int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00003520 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00003521 const void *pKey, i64 nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00003522 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00003523){
drh3b7511c2001-05-26 13:15:44 +00003524 int rc;
3525 int loc;
drh14acc042001-06-10 19:56:58 +00003526 int szNew;
drh3b7511c2001-05-26 13:15:44 +00003527 MemPage *pPage;
3528 Btree *pBt = pCur->pBt;
drha34b6762004-05-07 13:30:42 +00003529 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00003530 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00003531
drhc39e0002004-05-07 23:50:57 +00003532 if( pCur->status ){
3533 return pCur->status; /* A rollback destroyed this cursor */
drhecdc7532001-09-23 02:35:53 +00003534 }
danielk1977ee5741e2004-05-31 10:01:34 +00003535 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00003536 /* Must start a transaction before doing an insert */
3537 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003538 }
drhf74b8d92002-09-01 23:20:45 +00003539 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00003540 if( !pCur->wrFlag ){
3541 return SQLITE_PERM; /* Cursor not open for writing */
3542 }
drh8dcd7ca2004-08-08 19:43:29 +00003543 if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00003544 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
3545 }
drh3aac2dd2004-04-26 14:10:20 +00003546 rc = sqlite3BtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00003547 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00003548 pPage = pCur->pPage;
drh4a1c3802004-05-12 15:15:47 +00003549 assert( pPage->intKey || nKey>=0 );
drh8b18dd42004-05-12 19:18:15 +00003550 assert( pPage->leaf || !pPage->leafData );
drh3a4c1412004-05-09 20:40:11 +00003551 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
3552 pCur->pgnoRoot, nKey, nData, pPage->pgno,
3553 loc==0 ? "overwrite" : "new entry"));
drh7aa128d2002-06-21 13:09:16 +00003554 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00003555 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00003556 if( rc ) return rc;
drh2e38c322004-09-03 18:38:44 +00003557 newCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
3558 if( newCell==0 ) return SQLITE_NOMEM;
drha34b6762004-05-07 13:30:42 +00003559 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, &szNew);
drh2e38c322004-09-03 18:38:44 +00003560 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00003561 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00003562 assert( szNew<=MX_CELL_SIZE(pBt) );
drhf328bc82004-05-10 23:29:49 +00003563 if( loc==0 && pCur->isValid ){
drha34b6762004-05-07 13:30:42 +00003564 int szOld;
3565 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00003566 oldCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00003567 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003568 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00003569 }
drh43605152004-05-29 21:46:49 +00003570 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00003571 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00003572 if( rc ) goto end_insert;
drh4b70f112004-05-02 21:12:19 +00003573 dropCell(pPage, pCur->idx, szOld);
drh7c717f72001-06-24 20:39:41 +00003574 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00003575 assert( pPage->leaf );
drh14acc042001-06-10 19:56:58 +00003576 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00003577 pCur->info.nSize = 0;
drh14acc042001-06-10 19:56:58 +00003578 }else{
drh4b70f112004-05-02 21:12:19 +00003579 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00003580 }
drh24cd67e2004-05-10 16:18:47 +00003581 insertCell(pPage, pCur->idx, newCell, szNew, 0);
drh4b70f112004-05-02 21:12:19 +00003582 rc = balance(pPage);
drh23e11ca2004-05-04 17:27:28 +00003583 /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
drh3fc190c2001-09-14 03:24:23 +00003584 /* fflush(stdout); */
drh4b70f112004-05-02 21:12:19 +00003585 moveToRoot(pCur);
drh2e38c322004-09-03 18:38:44 +00003586end_insert:
3587 sqliteFree(newCell);
drh5e2f8b92001-05-28 00:41:15 +00003588 return rc;
3589}
3590
3591/*
drh4b70f112004-05-02 21:12:19 +00003592** Delete the entry that the cursor is pointing to. The cursor
3593** is left pointing at a random location.
drh3b7511c2001-05-26 13:15:44 +00003594*/
drh3aac2dd2004-04-26 14:10:20 +00003595int sqlite3BtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00003596 MemPage *pPage = pCur->pPage;
drh4b70f112004-05-02 21:12:19 +00003597 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00003598 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00003599 Pgno pgnoChild = 0;
drh0d316a42002-08-11 20:10:47 +00003600 Btree *pBt = pCur->pBt;
drh8b2f49b2001-06-08 00:21:52 +00003601
drh7aa128d2002-06-21 13:09:16 +00003602 assert( pPage->isInit );
drhc39e0002004-05-07 23:50:57 +00003603 if( pCur->status ){
3604 return pCur->status; /* A rollback destroyed this cursor */
drhecdc7532001-09-23 02:35:53 +00003605 }
danielk1977ee5741e2004-05-31 10:01:34 +00003606 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00003607 /* Must start a transaction before doing a delete */
3608 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003609 }
drhf74b8d92002-09-01 23:20:45 +00003610 assert( !pBt->readOnly );
drhbd03cae2001-06-02 02:40:57 +00003611 if( pCur->idx >= pPage->nCell ){
3612 return SQLITE_ERROR; /* The cursor is not pointing to anything */
3613 }
drhecdc7532001-09-23 02:35:53 +00003614 if( !pCur->wrFlag ){
3615 return SQLITE_PERM; /* Did not open this cursor for writing */
3616 }
drh8dcd7ca2004-08-08 19:43:29 +00003617 if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00003618 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
3619 }
drha34b6762004-05-07 13:30:42 +00003620 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00003621 if( rc ) return rc;
drh43605152004-05-29 21:46:49 +00003622 pCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00003623 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003624 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00003625 }
3626 clearCell(pPage, pCell);
3627 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00003628 /*
drh5e00f6c2001-09-13 13:46:56 +00003629 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00003630 ** do something we will leave a hole on an internal page.
3631 ** We have to fill the hole by moving in a cell from a leaf. The
3632 ** next Cell after the one to be deleted is guaranteed to exist and
3633 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00003634 */
drh14acc042001-06-10 19:56:58 +00003635 BtCursor leafCur;
drh4b70f112004-05-02 21:12:19 +00003636 unsigned char *pNext;
drh14acc042001-06-10 19:56:58 +00003637 int szNext;
drh8c1238a2003-01-02 14:43:55 +00003638 int notUsed;
drh2e38c322004-09-03 18:38:44 +00003639 unsigned char *tempCell;
drh8b18dd42004-05-12 19:18:15 +00003640 assert( !pPage->leafData );
drh14acc042001-06-10 19:56:58 +00003641 getTempCursor(pCur, &leafCur);
drh3aac2dd2004-04-26 14:10:20 +00003642 rc = sqlite3BtreeNext(&leafCur, &notUsed);
drh14acc042001-06-10 19:56:58 +00003643 if( rc!=SQLITE_OK ){
drhee696e22004-08-30 16:52:17 +00003644 if( rc!=SQLITE_NOMEM ){
3645 rc = SQLITE_CORRUPT; /* bkpt-CORRUPT */
3646 }
drh8a6ac0a2004-02-14 17:35:07 +00003647 return rc;
drh5e2f8b92001-05-28 00:41:15 +00003648 }
drha34b6762004-05-07 13:30:42 +00003649 rc = sqlite3pager_write(leafCur.pPage->aData);
drh6019e162001-07-02 17:51:45 +00003650 if( rc ) return rc;
drh3a4c1412004-05-09 20:40:11 +00003651 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
3652 pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
drh43605152004-05-29 21:46:49 +00003653 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
3654 pNext = findCell(leafCur.pPage, leafCur.idx);
3655 szNext = cellSizePtr(leafCur.pPage, pNext);
drh2e38c322004-09-03 18:38:44 +00003656 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
3657 tempCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
3658 if( tempCell==0 ) return SQLITE_NOMEM;
drh24cd67e2004-05-10 16:18:47 +00003659 insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell);
drh43605152004-05-29 21:46:49 +00003660 put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
drh4b70f112004-05-02 21:12:19 +00003661 rc = balance(pPage);
drh2e38c322004-09-03 18:38:44 +00003662 sqliteFree(tempCell);
drh5e2f8b92001-05-28 00:41:15 +00003663 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00003664 dropCell(leafCur.pPage, leafCur.idx, szNext);
3665 rc = balance(leafCur.pPage);
drh8c42ca92001-06-22 19:15:00 +00003666 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00003667 }else{
drh3a4c1412004-05-09 20:40:11 +00003668 TRACE(("DELETE: table=%d delete from leaf %d\n",
3669 pCur->pgnoRoot, pPage->pgno));
drh43605152004-05-29 21:46:49 +00003670 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
drh4b70f112004-05-02 21:12:19 +00003671 rc = balance(pPage);
drh5e2f8b92001-05-28 00:41:15 +00003672 }
drh4b70f112004-05-02 21:12:19 +00003673 moveToRoot(pCur);
drh5e2f8b92001-05-28 00:41:15 +00003674 return rc;
drh3b7511c2001-05-26 13:15:44 +00003675}
drh8b2f49b2001-06-08 00:21:52 +00003676
3677/*
drhc6b52df2002-01-04 03:09:29 +00003678** Create a new BTree table. Write into *piTable the page
3679** number for the root page of the new table.
3680**
drhab01f612004-05-22 02:55:23 +00003681** The type of type is determined by the flags parameter. Only the
3682** following values of flags are currently in use. Other values for
3683** flags might not work:
3684**
3685** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
3686** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00003687*/
drh3aac2dd2004-04-26 14:10:20 +00003688int sqlite3BtreeCreateTable(Btree *pBt, int *piTable, int flags){
drh8b2f49b2001-06-08 00:21:52 +00003689 MemPage *pRoot;
3690 Pgno pgnoRoot;
3691 int rc;
danielk1977ee5741e2004-05-31 10:01:34 +00003692 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00003693 /* Must start a transaction first */
3694 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003695 }
drh5df72a52002-06-06 23:16:05 +00003696 if( pBt->readOnly ){
3697 return SQLITE_READONLY;
3698 }
drhda200cc2004-05-09 11:51:38 +00003699 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1);
drh8b2f49b2001-06-08 00:21:52 +00003700 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003701 assert( sqlite3pager_iswriteable(pRoot->aData) );
drhde647132004-05-07 17:57:49 +00003702 zeroPage(pRoot, flags | PTF_LEAF);
drha34b6762004-05-07 13:30:42 +00003703 sqlite3pager_unref(pRoot->aData);
drh8b2f49b2001-06-08 00:21:52 +00003704 *piTable = (int)pgnoRoot;
3705 return SQLITE_OK;
3706}
3707
3708/*
3709** Erase the given database page and all its children. Return
3710** the page to the freelist.
3711*/
drh4b70f112004-05-02 21:12:19 +00003712static int clearDatabasePage(
3713 Btree *pBt, /* The BTree that contains the table */
3714 Pgno pgno, /* Page number to clear */
3715 MemPage *pParent, /* Parent page. NULL for the root */
3716 int freePageFlag /* Deallocate page if true */
3717){
drh8b2f49b2001-06-08 00:21:52 +00003718 MemPage *pPage;
3719 int rc;
drh4b70f112004-05-02 21:12:19 +00003720 unsigned char *pCell;
3721 int i;
drh8b2f49b2001-06-08 00:21:52 +00003722
drhde647132004-05-07 17:57:49 +00003723 rc = getAndInitPage(pBt, pgno, &pPage, pParent);
drh8b2f49b2001-06-08 00:21:52 +00003724 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003725 rc = sqlite3pager_write(pPage->aData);
drh6019e162001-07-02 17:51:45 +00003726 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00003727 for(i=0; i<pPage->nCell; i++){
drh43605152004-05-29 21:46:49 +00003728 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00003729 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003730 rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
drh8b2f49b2001-06-08 00:21:52 +00003731 if( rc ) return rc;
3732 }
drh4b70f112004-05-02 21:12:19 +00003733 rc = clearCell(pPage, pCell);
drh8b2f49b2001-06-08 00:21:52 +00003734 if( rc ) return rc;
3735 }
drha34b6762004-05-07 13:30:42 +00003736 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003737 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
drh2aa679f2001-06-25 02:11:07 +00003738 if( rc ) return rc;
3739 }
3740 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00003741 rc = freePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00003742 }else{
drh3a4c1412004-05-09 20:40:11 +00003743 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00003744 }
drh4b70f112004-05-02 21:12:19 +00003745 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00003746 return rc;
drh8b2f49b2001-06-08 00:21:52 +00003747}
3748
3749/*
drhab01f612004-05-22 02:55:23 +00003750** Delete all information from a single table in the database. iTable is
3751** the page number of the root of the table. After this routine returns,
3752** the root page is empty, but still exists.
3753**
3754** This routine will fail with SQLITE_LOCKED if there are any open
3755** read cursors on the table. Open write cursors are moved to the
3756** root of the table.
drh8b2f49b2001-06-08 00:21:52 +00003757*/
drh3aac2dd2004-04-26 14:10:20 +00003758int sqlite3BtreeClearTable(Btree *pBt, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00003759 int rc;
drhf74b8d92002-09-01 23:20:45 +00003760 BtCursor *pCur;
danielk1977ee5741e2004-05-31 10:01:34 +00003761 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00003762 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003763 }
drhf74b8d92002-09-01 23:20:45 +00003764 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3765 if( pCur->pgnoRoot==(Pgno)iTable ){
3766 if( pCur->wrFlag==0 ) return SQLITE_LOCKED;
3767 moveToRoot(pCur);
3768 }
drhecdc7532001-09-23 02:35:53 +00003769 }
drha34b6762004-05-07 13:30:42 +00003770 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
drh8b2f49b2001-06-08 00:21:52 +00003771 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00003772 sqlite3BtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00003773 }
drh8c42ca92001-06-22 19:15:00 +00003774 return rc;
drh8b2f49b2001-06-08 00:21:52 +00003775}
3776
3777/*
3778** Erase all information in a table and add the root of the table to
3779** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00003780** page 1) is never added to the freelist.
3781**
3782** This routine will fail with SQLITE_LOCKED if there are any open
3783** cursors on the table.
drh8b2f49b2001-06-08 00:21:52 +00003784*/
drh3aac2dd2004-04-26 14:10:20 +00003785int sqlite3BtreeDropTable(Btree *pBt, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00003786 int rc;
3787 MemPage *pPage;
drhf74b8d92002-09-01 23:20:45 +00003788 BtCursor *pCur;
danielk1977ee5741e2004-05-31 10:01:34 +00003789 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00003790 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003791 }
drhf74b8d92002-09-01 23:20:45 +00003792 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3793 if( pCur->pgnoRoot==(Pgno)iTable ){
3794 return SQLITE_LOCKED; /* Cannot drop a table that has a cursor */
3795 }
drh5df72a52002-06-06 23:16:05 +00003796 }
drha34b6762004-05-07 13:30:42 +00003797 rc = getPage(pBt, (Pgno)iTable, &pPage);
drh2aa679f2001-06-25 02:11:07 +00003798 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003799 rc = sqlite3BtreeClearTable(pBt, iTable);
drh2aa679f2001-06-25 02:11:07 +00003800 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00003801 if( iTable>1 ){
drha34b6762004-05-07 13:30:42 +00003802 rc = freePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00003803 }else{
drha34b6762004-05-07 13:30:42 +00003804 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
drh8b2f49b2001-06-08 00:21:52 +00003805 }
drh4b70f112004-05-02 21:12:19 +00003806 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00003807 return rc;
3808}
3809
drh001bbcb2003-03-19 03:14:00 +00003810
drh8b2f49b2001-06-08 00:21:52 +00003811/*
drh23e11ca2004-05-04 17:27:28 +00003812** Read the meta-information out of a database file. Meta[0]
3813** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00003814** through meta[15] are available for use by higher layers. Meta[0]
3815** is read-only, the others are read/write.
3816**
3817** The schema layer numbers meta values differently. At the schema
3818** layer (and the SetCookie and ReadCookie opcodes) the number of
3819** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00003820*/
drh3aac2dd2004-04-26 14:10:20 +00003821int sqlite3BtreeGetMeta(Btree *pBt, int idx, u32 *pMeta){
drh8b2f49b2001-06-08 00:21:52 +00003822 int rc;
drh4b70f112004-05-02 21:12:19 +00003823 unsigned char *pP1;
drh8b2f49b2001-06-08 00:21:52 +00003824
drh23e11ca2004-05-04 17:27:28 +00003825 assert( idx>=0 && idx<=15 );
drha34b6762004-05-07 13:30:42 +00003826 rc = sqlite3pager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00003827 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00003828 *pMeta = get4byte(&pP1[36 + idx*4]);
drha34b6762004-05-07 13:30:42 +00003829 sqlite3pager_unref(pP1);
drhae157872004-08-14 19:20:09 +00003830
3831 /* The current implementation is unable to handle writes to an autovacuumed
3832 ** database. So make such a database readonly. */
3833 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
3834
drh8b2f49b2001-06-08 00:21:52 +00003835 return SQLITE_OK;
3836}
3837
3838/*
drh23e11ca2004-05-04 17:27:28 +00003839** Write meta-information back into the database. Meta[0] is
3840** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00003841*/
drh3aac2dd2004-04-26 14:10:20 +00003842int sqlite3BtreeUpdateMeta(Btree *pBt, int idx, u32 iMeta){
drh4b70f112004-05-02 21:12:19 +00003843 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00003844 int rc;
drh23e11ca2004-05-04 17:27:28 +00003845 assert( idx>=1 && idx<=15 );
danielk1977ee5741e2004-05-31 10:01:34 +00003846 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00003847 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +00003848 }
drhde647132004-05-07 17:57:49 +00003849 assert( pBt->pPage1!=0 );
3850 pP1 = pBt->pPage1->aData;
drha34b6762004-05-07 13:30:42 +00003851 rc = sqlite3pager_write(pP1);
drh4b70f112004-05-02 21:12:19 +00003852 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00003853 put4byte(&pP1[36 + idx*4], iMeta);
drh8b2f49b2001-06-08 00:21:52 +00003854 return SQLITE_OK;
3855}
drh8c42ca92001-06-22 19:15:00 +00003856
drhf328bc82004-05-10 23:29:49 +00003857/*
3858** Return the flag byte at the beginning of the page that the cursor
3859** is currently pointing to.
3860*/
3861int sqlite3BtreeFlags(BtCursor *pCur){
3862 MemPage *pPage = pCur->pPage;
3863 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
3864}
3865
drh8c42ca92001-06-22 19:15:00 +00003866/*
3867** Print a disassembly of the given page on standard output. This routine
3868** is used for debugging and testing only.
3869*/
drhaaab5722002-02-19 13:39:21 +00003870#ifdef SQLITE_TEST
drh23e11ca2004-05-04 17:27:28 +00003871int sqlite3BtreePageDump(Btree *pBt, int pgno, int recursive){
drh8c42ca92001-06-22 19:15:00 +00003872 int rc;
3873 MemPage *pPage;
drhc8629a12004-05-08 20:07:40 +00003874 int i, j, c;
drh8c42ca92001-06-22 19:15:00 +00003875 int nFree;
3876 u16 idx;
drhab9f7f12004-05-08 10:56:11 +00003877 int hdr;
drh43605152004-05-29 21:46:49 +00003878 int nCell;
drha2fce642004-06-05 00:01:44 +00003879 int isInit;
drhab9f7f12004-05-08 10:56:11 +00003880 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00003881 char range[20];
3882 unsigned char payload[20];
drhab9f7f12004-05-08 10:56:11 +00003883
drh4b70f112004-05-02 21:12:19 +00003884 rc = getPage(pBt, (Pgno)pgno, &pPage);
drha2fce642004-06-05 00:01:44 +00003885 isInit = pPage->isInit;
3886 if( pPage->isInit==0 ){
3887 initPage(pPage, 0);
3888 }
drh8c42ca92001-06-22 19:15:00 +00003889 if( rc ){
3890 return rc;
3891 }
drhab9f7f12004-05-08 10:56:11 +00003892 hdr = pPage->hdrOffset;
3893 data = pPage->aData;
drhc8629a12004-05-08 20:07:40 +00003894 c = data[hdr];
drh8b18dd42004-05-12 19:18:15 +00003895 pPage->intKey = (c & (PTF_INTKEY|PTF_LEAFDATA))!=0;
drhc8629a12004-05-08 20:07:40 +00003896 pPage->zeroData = (c & PTF_ZERODATA)!=0;
drh8b18dd42004-05-12 19:18:15 +00003897 pPage->leafData = (c & PTF_LEAFDATA)!=0;
drhc8629a12004-05-08 20:07:40 +00003898 pPage->leaf = (c & PTF_LEAF)!=0;
drh8b18dd42004-05-12 19:18:15 +00003899 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
drh43605152004-05-29 21:46:49 +00003900 nCell = get2byte(&data[hdr+3]);
drhfe63d1c2004-09-08 20:13:04 +00003901 sqlite3DebugPrintf("PAGE %d: flags=0x%02x frag=%d parent=%d\n", pgno,
drh43605152004-05-29 21:46:49 +00003902 data[hdr], data[hdr+7],
drhda200cc2004-05-09 11:51:38 +00003903 (pPage->isInit && pPage->pParent) ? pPage->pParent->pgno : 0);
drhab9f7f12004-05-08 10:56:11 +00003904 assert( hdr == (pgno==1 ? 100 : 0) );
drh43605152004-05-29 21:46:49 +00003905 idx = hdr + 12 - pPage->leaf*4;
3906 for(i=0; i<nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00003907 CellInfo info;
drh4b70f112004-05-02 21:12:19 +00003908 Pgno child;
drh43605152004-05-29 21:46:49 +00003909 unsigned char *pCell;
drh6f11bef2004-05-13 01:12:56 +00003910 int sz;
drh43605152004-05-29 21:46:49 +00003911 int addr;
drh6f11bef2004-05-13 01:12:56 +00003912
drh43605152004-05-29 21:46:49 +00003913 addr = get2byte(&data[idx + 2*i]);
3914 pCell = &data[addr];
3915 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003916 sz = info.nSize;
drh43605152004-05-29 21:46:49 +00003917 sprintf(range,"%d..%d", addr, addr+sz-1);
drh4b70f112004-05-02 21:12:19 +00003918 if( pPage->leaf ){
3919 child = 0;
3920 }else{
drh43605152004-05-29 21:46:49 +00003921 child = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00003922 }
drh6f11bef2004-05-13 01:12:56 +00003923 sz = info.nData;
3924 if( !pPage->intKey ) sz += info.nKey;
drh8c42ca92001-06-22 19:15:00 +00003925 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
drh6f11bef2004-05-13 01:12:56 +00003926 memcpy(payload, &pCell[info.nHeader], sz);
drh8c42ca92001-06-22 19:15:00 +00003927 for(j=0; j<sz; j++){
3928 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
3929 }
3930 payload[sz] = 0;
drhfe63d1c2004-09-08 20:13:04 +00003931 sqlite3DebugPrintf(
drh6f11bef2004-05-13 01:12:56 +00003932 "cell %2d: i=%-10s chld=%-4d nk=%-4lld nd=%-4d payload=%s\n",
3933 i, range, child, info.nKey, info.nData, payload
drh8c42ca92001-06-22 19:15:00 +00003934 );
drh8c42ca92001-06-22 19:15:00 +00003935 }
drh4b70f112004-05-02 21:12:19 +00003936 if( !pPage->leaf ){
drhfe63d1c2004-09-08 20:13:04 +00003937 sqlite3DebugPrintf("right_child: %d\n", get4byte(&data[hdr+8]));
drh4b70f112004-05-02 21:12:19 +00003938 }
drh8c42ca92001-06-22 19:15:00 +00003939 nFree = 0;
3940 i = 0;
drhab9f7f12004-05-08 10:56:11 +00003941 idx = get2byte(&data[hdr+1]);
drhb6f41482004-05-14 01:58:11 +00003942 while( idx>0 && idx<pPage->pBt->usableSize ){
drhab9f7f12004-05-08 10:56:11 +00003943 int sz = get2byte(&data[idx+2]);
drh4b70f112004-05-02 21:12:19 +00003944 sprintf(range,"%d..%d", idx, idx+sz-1);
3945 nFree += sz;
drhfe63d1c2004-09-08 20:13:04 +00003946 sqlite3DebugPrintf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
drh4b70f112004-05-02 21:12:19 +00003947 i, range, sz, nFree);
drhab9f7f12004-05-08 10:56:11 +00003948 idx = get2byte(&data[idx]);
drh2aa679f2001-06-25 02:11:07 +00003949 i++;
drh8c42ca92001-06-22 19:15:00 +00003950 }
3951 if( idx!=0 ){
drhfe63d1c2004-09-08 20:13:04 +00003952 sqlite3DebugPrintf("ERROR: next freeblock index out of range: %d\n", idx);
drh8c42ca92001-06-22 19:15:00 +00003953 }
drha34b6762004-05-07 13:30:42 +00003954 if( recursive && !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003955 for(i=0; i<nCell; i++){
3956 unsigned char *pCell = findCell(pPage, i);
3957 sqlite3BtreePageDump(pBt, get4byte(pCell), 1);
drha34b6762004-05-07 13:30:42 +00003958 idx = get2byte(pCell);
drh6019e162001-07-02 17:51:45 +00003959 }
drh43605152004-05-29 21:46:49 +00003960 sqlite3BtreePageDump(pBt, get4byte(&data[hdr+8]), 1);
drh6019e162001-07-02 17:51:45 +00003961 }
drha2fce642004-06-05 00:01:44 +00003962 pPage->isInit = isInit;
drhab9f7f12004-05-08 10:56:11 +00003963 sqlite3pager_unref(data);
drh3644f082004-05-10 18:45:09 +00003964 fflush(stdout);
drh8c42ca92001-06-22 19:15:00 +00003965 return SQLITE_OK;
3966}
drhaaab5722002-02-19 13:39:21 +00003967#endif
drh8c42ca92001-06-22 19:15:00 +00003968
drhaaab5722002-02-19 13:39:21 +00003969#ifdef SQLITE_TEST
drh8c42ca92001-06-22 19:15:00 +00003970/*
drh2aa679f2001-06-25 02:11:07 +00003971** Fill aResult[] with information about the entry and page that the
3972** cursor is pointing to.
3973**
3974** aResult[0] = The page number
3975** aResult[1] = The entry number
3976** aResult[2] = Total number of entries on this page
drh3e27c022004-07-23 00:01:38 +00003977** aResult[3] = Cell size (local payload + header)
drh2aa679f2001-06-25 02:11:07 +00003978** aResult[4] = Number of free bytes on this page
3979** aResult[5] = Number of free blocks on the page
drh3e27c022004-07-23 00:01:38 +00003980** aResult[6] = Total payload size (local + overflow)
3981** aResult[7] = Header size in bytes
3982** aResult[8] = Local payload size
3983** aResult[9] = Parent page number
drh5eddca62001-06-30 21:53:53 +00003984**
3985** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00003986*/
drh3e27c022004-07-23 00:01:38 +00003987int sqlite3BtreeCursorInfo(BtCursor *pCur, int *aResult, int upCnt){
drh2aa679f2001-06-25 02:11:07 +00003988 int cnt, idx;
3989 MemPage *pPage = pCur->pPage;
drh3e27c022004-07-23 00:01:38 +00003990 BtCursor tmpCur;
drhda200cc2004-05-09 11:51:38 +00003991
3992 pageIntegrity(pPage);
drh4b70f112004-05-02 21:12:19 +00003993 assert( pPage->isInit );
drh3e27c022004-07-23 00:01:38 +00003994 getTempCursor(pCur, &tmpCur);
3995 while( upCnt-- ){
3996 moveToParent(&tmpCur);
3997 }
3998 pPage = tmpCur.pPage;
3999 pageIntegrity(pPage);
drha34b6762004-05-07 13:30:42 +00004000 aResult[0] = sqlite3pager_pagenumber(pPage->aData);
drh91025292004-05-03 19:49:32 +00004001 assert( aResult[0]==pPage->pgno );
drh3e27c022004-07-23 00:01:38 +00004002 aResult[1] = tmpCur.idx;
drh2aa679f2001-06-25 02:11:07 +00004003 aResult[2] = pPage->nCell;
drh3e27c022004-07-23 00:01:38 +00004004 if( tmpCur.idx>=0 && tmpCur.idx<pPage->nCell ){
4005 getCellInfo(&tmpCur);
4006 aResult[3] = tmpCur.info.nSize;
4007 aResult[6] = tmpCur.info.nData;
4008 aResult[7] = tmpCur.info.nHeader;
4009 aResult[8] = tmpCur.info.nLocal;
drh2aa679f2001-06-25 02:11:07 +00004010 }else{
4011 aResult[3] = 0;
4012 aResult[6] = 0;
drh3e27c022004-07-23 00:01:38 +00004013 aResult[7] = 0;
4014 aResult[8] = 0;
drh2aa679f2001-06-25 02:11:07 +00004015 }
4016 aResult[4] = pPage->nFree;
4017 cnt = 0;
drh4b70f112004-05-02 21:12:19 +00004018 idx = get2byte(&pPage->aData[pPage->hdrOffset+1]);
drhb6f41482004-05-14 01:58:11 +00004019 while( idx>0 && idx<pPage->pBt->usableSize ){
drh2aa679f2001-06-25 02:11:07 +00004020 cnt++;
drh4b70f112004-05-02 21:12:19 +00004021 idx = get2byte(&pPage->aData[idx]);
drh2aa679f2001-06-25 02:11:07 +00004022 }
4023 aResult[5] = cnt;
drh3e27c022004-07-23 00:01:38 +00004024 if( pPage->pParent==0 || isRootPage(pPage) ){
4025 aResult[9] = 0;
4026 }else{
4027 aResult[9] = pPage->pParent->pgno;
4028 }
4029 releaseTempCursor(&tmpCur);
drh8c42ca92001-06-22 19:15:00 +00004030 return SQLITE_OK;
4031}
drhaaab5722002-02-19 13:39:21 +00004032#endif
drhdd793422001-06-28 01:54:48 +00004033
drhdd793422001-06-28 01:54:48 +00004034/*
drh5eddca62001-06-30 21:53:53 +00004035** Return the pager associated with a BTree. This routine is used for
4036** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00004037*/
drh3aac2dd2004-04-26 14:10:20 +00004038Pager *sqlite3BtreePager(Btree *pBt){
drhdd793422001-06-28 01:54:48 +00004039 return pBt->pPager;
4040}
drh5eddca62001-06-30 21:53:53 +00004041
4042/*
4043** This structure is passed around through all the sanity checking routines
4044** in order to keep track of some global state information.
4045*/
drhaaab5722002-02-19 13:39:21 +00004046typedef struct IntegrityCk IntegrityCk;
4047struct IntegrityCk {
drh100569d2001-10-02 13:01:48 +00004048 Btree *pBt; /* The tree being checked out */
4049 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
4050 int nPage; /* Number of pages in the database */
4051 int *anRef; /* Number of times each page is referenced */
drh100569d2001-10-02 13:01:48 +00004052 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00004053};
4054
4055/*
4056** Append a message to the error message string.
4057*/
drh2e38c322004-09-03 18:38:44 +00004058static void checkAppendMsg(
4059 IntegrityCk *pCheck,
4060 char *zMsg1,
4061 const char *zFormat,
4062 ...
4063){
4064 va_list ap;
4065 char *zMsg2;
4066 va_start(ap, zFormat);
4067 zMsg2 = sqlite3VMPrintf(zFormat, ap);
4068 va_end(ap);
4069 if( zMsg1==0 ) zMsg1 = "";
drh5eddca62001-06-30 21:53:53 +00004070 if( pCheck->zErrMsg ){
4071 char *zOld = pCheck->zErrMsg;
4072 pCheck->zErrMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00004073 sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00004074 sqliteFree(zOld);
4075 }else{
danielk19774adee202004-05-08 08:23:19 +00004076 sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00004077 }
drh2e38c322004-09-03 18:38:44 +00004078 sqliteFree(zMsg2);
drh5eddca62001-06-30 21:53:53 +00004079}
4080
4081/*
4082** Add 1 to the reference count for page iPage. If this is the second
4083** reference to the page, add an error message to pCheck->zErrMsg.
4084** Return 1 if there are 2 ore more references to the page and 0 if
4085** if this is the first reference to the page.
4086**
4087** Also check that the page number is in bounds.
4088*/
drhaaab5722002-02-19 13:39:21 +00004089static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00004090 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00004091 if( iPage>pCheck->nPage || iPage<0 ){
drh2e38c322004-09-03 18:38:44 +00004092 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00004093 return 1;
4094 }
4095 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00004096 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00004097 return 1;
4098 }
4099 return (pCheck->anRef[iPage]++)>1;
4100}
4101
4102/*
4103** Check the integrity of the freelist or of an overflow page list.
4104** Verify that the number of pages on the list is N.
4105*/
drh30e58752002-03-02 20:41:57 +00004106static void checkList(
4107 IntegrityCk *pCheck, /* Integrity checking context */
4108 int isFreeList, /* True for a freelist. False for overflow page list */
4109 int iPage, /* Page number for first page in the list */
4110 int N, /* Expected number of pages in the list */
4111 char *zContext /* Context for error messages */
4112){
4113 int i;
drh3a4c1412004-05-09 20:40:11 +00004114 int expected = N;
4115 int iFirst = iPage;
drh30e58752002-03-02 20:41:57 +00004116 while( N-- > 0 ){
drh4b70f112004-05-02 21:12:19 +00004117 unsigned char *pOvfl;
drh5eddca62001-06-30 21:53:53 +00004118 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00004119 checkAppendMsg(pCheck, zContext,
4120 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00004121 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00004122 break;
4123 }
4124 if( checkRef(pCheck, iPage, zContext) ) break;
drha34b6762004-05-07 13:30:42 +00004125 if( sqlite3pager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
drh2e38c322004-09-03 18:38:44 +00004126 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00004127 break;
4128 }
drh30e58752002-03-02 20:41:57 +00004129 if( isFreeList ){
drh4b70f112004-05-02 21:12:19 +00004130 int n = get4byte(&pOvfl[4]);
drh855eb1c2004-08-31 13:45:11 +00004131 if( n>pCheck->pBt->usableSize/4-8 ){
drh2e38c322004-09-03 18:38:44 +00004132 checkAppendMsg(pCheck, zContext,
4133 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00004134 N--;
4135 }else{
4136 for(i=0; i<n; i++){
4137 checkRef(pCheck, get4byte(&pOvfl[8+i*4]), zContext);
4138 }
4139 N -= n;
drh30e58752002-03-02 20:41:57 +00004140 }
drh30e58752002-03-02 20:41:57 +00004141 }
drh4b70f112004-05-02 21:12:19 +00004142 iPage = get4byte(pOvfl);
drha34b6762004-05-07 13:30:42 +00004143 sqlite3pager_unref(pOvfl);
drh5eddca62001-06-30 21:53:53 +00004144 }
4145}
4146
4147/*
4148** Do various sanity checks on a single page of a tree. Return
4149** the tree depth. Root pages return 0. Parents of root pages
4150** return 1, and so forth.
4151**
4152** These checks are done:
4153**
4154** 1. Make sure that cells and freeblocks do not overlap
4155** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00004156** NO 2. Make sure cell keys are in order.
4157** NO 3. Make sure no key is less than or equal to zLowerBound.
4158** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00004159** 5. Check the integrity of overflow pages.
4160** 6. Recursively call checkTreePage on all children.
4161** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00004162** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00004163** the root of the tree.
4164*/
4165static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00004166 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00004167 int iPage, /* Page number of the page to check */
4168 MemPage *pParent, /* Parent page */
4169 char *zParentContext, /* Parent context */
4170 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00004171 int nLower, /* Number of characters in zLowerBound */
4172 char *zUpperBound, /* All keys should be less than this, if not NULL */
4173 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00004174){
4175 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00004176 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00004177 int hdr, cellStart;
4178 int nCell;
drhda200cc2004-05-09 11:51:38 +00004179 u8 *data;
drh5eddca62001-06-30 21:53:53 +00004180 BtCursor cur;
drh0d316a42002-08-11 20:10:47 +00004181 Btree *pBt;
drhb6f41482004-05-14 01:58:11 +00004182 int maxLocal, usableSize;
drh5eddca62001-06-30 21:53:53 +00004183 char zContext[100];
drh2e38c322004-09-03 18:38:44 +00004184 char *hit;
drh5eddca62001-06-30 21:53:53 +00004185
4186 /* Check that the page exists
4187 */
drh0d316a42002-08-11 20:10:47 +00004188 cur.pBt = pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00004189 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00004190 if( iPage==0 ) return 0;
4191 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh4b70f112004-05-02 21:12:19 +00004192 if( (rc = getPage(pBt, (Pgno)iPage, &pPage))!=0 ){
drh2e38c322004-09-03 18:38:44 +00004193 checkAppendMsg(pCheck, zContext,
4194 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00004195 return 0;
4196 }
drh6f11bef2004-05-13 01:12:56 +00004197 maxLocal = pPage->leafData ? pBt->maxLeaf : pBt->maxLocal;
drh4b70f112004-05-02 21:12:19 +00004198 if( (rc = initPage(pPage, pParent))!=0 ){
drh2e38c322004-09-03 18:38:44 +00004199 checkAppendMsg(pCheck, zContext, "initPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00004200 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00004201 return 0;
4202 }
4203
4204 /* Check out all the cells.
4205 */
4206 depth = 0;
drh5eddca62001-06-30 21:53:53 +00004207 cur.pPage = pPage;
drh5eddca62001-06-30 21:53:53 +00004208 for(i=0; i<pPage->nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00004209 u8 *pCell;
4210 int sz;
4211 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00004212
4213 /* Check payload overflow pages
4214 */
drh3a4c1412004-05-09 20:40:11 +00004215 sprintf(zContext, "On tree page %d cell %d: ", iPage, i);
drh43605152004-05-29 21:46:49 +00004216 pCell = findCell(pPage,i);
4217 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004218 sz = info.nData;
4219 if( !pPage->intKey ) sz += info.nKey;
4220 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00004221 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +00004222 checkList(pCheck, 0, get4byte(&pCell[info.iOverflow]),nPage,zContext);
drh5eddca62001-06-30 21:53:53 +00004223 }
4224
4225 /* Check sanity of left child page.
4226 */
drhda200cc2004-05-09 11:51:38 +00004227 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004228 pgno = get4byte(pCell);
drhda200cc2004-05-09 11:51:38 +00004229 d2 = checkTreePage(pCheck,pgno,pPage,zContext,0,0,0,0);
4230 if( i>0 && d2!=depth ){
4231 checkAppendMsg(pCheck, zContext, "Child page depth differs");
4232 }
4233 depth = d2;
drh5eddca62001-06-30 21:53:53 +00004234 }
drh5eddca62001-06-30 21:53:53 +00004235 }
drhda200cc2004-05-09 11:51:38 +00004236 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004237 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drhda200cc2004-05-09 11:51:38 +00004238 sprintf(zContext, "On page %d at right child: ", iPage);
4239 checkTreePage(pCheck, pgno, pPage, zContext,0,0,0,0);
4240 }
drh5eddca62001-06-30 21:53:53 +00004241
4242 /* Check for complete coverage of the page
4243 */
drhda200cc2004-05-09 11:51:38 +00004244 data = pPage->aData;
4245 hdr = pPage->hdrOffset;
drh2e38c322004-09-03 18:38:44 +00004246 hit = sqliteMalloc( usableSize );
4247 if( hit ){
4248 memset(hit, 1, get2byte(&data[hdr+5]));
4249 nCell = get2byte(&data[hdr+3]);
4250 cellStart = hdr + 12 - 4*pPage->leaf;
4251 for(i=0; i<nCell; i++){
4252 int pc = get2byte(&data[cellStart+i*2]);
4253 int size = cellSizePtr(pPage, &data[pc]);
4254 int j;
4255 for(j=pc+size-1; j>=pc; j--) hit[j]++;
4256 }
4257 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
4258 cnt++){
4259 int size = get2byte(&data[i+2]);
4260 int j;
4261 for(j=i+size-1; j>=i; j--) hit[j]++;
4262 i = get2byte(&data[i]);
4263 }
4264 for(i=cnt=0; i<usableSize; i++){
4265 if( hit[i]==0 ){
4266 cnt++;
4267 }else if( hit[i]>1 ){
4268 checkAppendMsg(pCheck, 0,
4269 "Multiple uses for byte %d of page %d", i, iPage);
4270 break;
4271 }
4272 }
4273 if( cnt!=data[hdr+7] ){
4274 checkAppendMsg(pCheck, 0,
4275 "Fragmented space is %d byte reported as %d on page %d",
4276 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00004277 }
4278 }
drh2e38c322004-09-03 18:38:44 +00004279 sqliteFree(hit);
drh6019e162001-07-02 17:51:45 +00004280
drh4b70f112004-05-02 21:12:19 +00004281 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00004282 return depth+1;
drh5eddca62001-06-30 21:53:53 +00004283}
4284
4285/*
4286** This routine does a complete check of the given BTree file. aRoot[] is
4287** an array of pages numbers were each page number is the root page of
4288** a table. nRoot is the number of entries in aRoot.
4289**
4290** If everything checks out, this routine returns NULL. If something is
4291** amiss, an error message is written into memory obtained from malloc()
4292** and a pointer to that error message is returned. The calling function
4293** is responsible for freeing the error message when it is done.
4294*/
drh3aac2dd2004-04-26 14:10:20 +00004295char *sqlite3BtreeIntegrityCheck(Btree *pBt, int *aRoot, int nRoot){
drh5eddca62001-06-30 21:53:53 +00004296 int i;
4297 int nRef;
drhaaab5722002-02-19 13:39:21 +00004298 IntegrityCk sCheck;
drh5eddca62001-06-30 21:53:53 +00004299
drha34b6762004-05-07 13:30:42 +00004300 nRef = *sqlite3pager_stats(pBt->pPager);
drhefc251d2001-07-01 22:12:01 +00004301 if( lockBtree(pBt)!=SQLITE_OK ){
4302 return sqliteStrDup("Unable to acquire a read lock on the database");
4303 }
drh5eddca62001-06-30 21:53:53 +00004304 sCheck.pBt = pBt;
4305 sCheck.pPager = pBt->pPager;
drha34b6762004-05-07 13:30:42 +00004306 sCheck.nPage = sqlite3pager_pagecount(sCheck.pPager);
drh0de8c112002-07-06 16:32:14 +00004307 if( sCheck.nPage==0 ){
4308 unlockBtreeIfUnused(pBt);
4309 return 0;
4310 }
drh8c1238a2003-01-02 14:43:55 +00004311 sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
drhda200cc2004-05-09 11:51:38 +00004312 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh1f595712004-06-15 01:40:29 +00004313 i = PENDING_BYTE/pBt->pageSize + 1;
4314 if( i<=sCheck.nPage ){
4315 sCheck.anRef[i] = 1;
4316 }
drh5eddca62001-06-30 21:53:53 +00004317 sCheck.zErrMsg = 0;
4318
4319 /* Check the integrity of the freelist
4320 */
drha34b6762004-05-07 13:30:42 +00004321 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
4322 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00004323
4324 /* Check all the tables.
4325 */
4326 for(i=0; i<nRoot; i++){
drh4ff6dfa2002-03-03 23:06:00 +00004327 if( aRoot[i]==0 ) continue;
drh1bffb9c2002-02-03 17:37:36 +00004328 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00004329 }
4330
4331 /* Make sure every page in the file is referenced
4332 */
4333 for(i=1; i<=sCheck.nPage; i++){
4334 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00004335 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00004336 }
4337 }
4338
4339 /* Make sure this analysis did not leave any unref() pages
4340 */
drh5e00f6c2001-09-13 13:46:56 +00004341 unlockBtreeIfUnused(pBt);
drha34b6762004-05-07 13:30:42 +00004342 if( nRef != *sqlite3pager_stats(pBt->pPager) ){
drh2e38c322004-09-03 18:38:44 +00004343 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00004344 "Outstanding page count goes from %d to %d during this analysis",
drha34b6762004-05-07 13:30:42 +00004345 nRef, *sqlite3pager_stats(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00004346 );
drh5eddca62001-06-30 21:53:53 +00004347 }
4348
4349 /* Clean up and report errors.
4350 */
4351 sqliteFree(sCheck.anRef);
4352 return sCheck.zErrMsg;
4353}
paulb95a8862003-04-01 21:16:41 +00004354
drh73509ee2003-04-06 20:44:45 +00004355/*
4356** Return the full pathname of the underlying database file.
4357*/
drh3aac2dd2004-04-26 14:10:20 +00004358const char *sqlite3BtreeGetFilename(Btree *pBt){
drh73509ee2003-04-06 20:44:45 +00004359 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00004360 return sqlite3pager_filename(pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00004361}
4362
4363/*
danielk19775865e3d2004-06-14 06:03:57 +00004364** Return the pathname of the directory that contains the database file.
4365*/
4366const char *sqlite3BtreeGetDirname(Btree *pBt){
4367 assert( pBt->pPager!=0 );
4368 return sqlite3pager_dirname(pBt->pPager);
4369}
4370
4371/*
4372** Return the pathname of the journal file for this database. The return
4373** value of this routine is the same regardless of whether the journal file
4374** has been created or not.
4375*/
4376const char *sqlite3BtreeGetJournalname(Btree *pBt){
4377 assert( pBt->pPager!=0 );
4378 return sqlite3pager_journalname(pBt->pPager);
4379}
4380
4381/*
drhf7c57532003-04-25 13:22:51 +00004382** Copy the complete content of pBtFrom into pBtTo. A transaction
4383** must be active for both files.
4384**
4385** The size of file pBtFrom may be reduced by this operation.
drh43605152004-05-29 21:46:49 +00004386** If anything goes wrong, the transaction on pBtFrom is rolled back.
drh73509ee2003-04-06 20:44:45 +00004387*/
drh3aac2dd2004-04-26 14:10:20 +00004388int sqlite3BtreeCopyFile(Btree *pBtTo, Btree *pBtFrom){
drhf7c57532003-04-25 13:22:51 +00004389 int rc = SQLITE_OK;
drh2e6d11b2003-04-25 15:37:57 +00004390 Pgno i, nPage, nToPage;
drhf7c57532003-04-25 13:22:51 +00004391
danielk1977ee5741e2004-05-31 10:01:34 +00004392 if( pBtTo->inTrans!=TRANS_WRITE || pBtFrom->inTrans!=TRANS_WRITE ){
4393 return SQLITE_ERROR;
4394 }
drhf7c57532003-04-25 13:22:51 +00004395 if( pBtTo->pCursor ) return SQLITE_BUSY;
drha34b6762004-05-07 13:30:42 +00004396 nToPage = sqlite3pager_pagecount(pBtTo->pPager);
4397 nPage = sqlite3pager_pagecount(pBtFrom->pPager);
danielk1977369f27e2004-06-15 11:40:04 +00004398 for(i=1; rc==SQLITE_OK && i<=nPage; i++){
drhf7c57532003-04-25 13:22:51 +00004399 void *pPage;
drha34b6762004-05-07 13:30:42 +00004400 rc = sqlite3pager_get(pBtFrom->pPager, i, &pPage);
drhf7c57532003-04-25 13:22:51 +00004401 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00004402 rc = sqlite3pager_overwrite(pBtTo->pPager, i, pPage);
drh2e6d11b2003-04-25 15:37:57 +00004403 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00004404 sqlite3pager_unref(pPage);
drhf7c57532003-04-25 13:22:51 +00004405 }
drh2e6d11b2003-04-25 15:37:57 +00004406 for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
4407 void *pPage;
drha34b6762004-05-07 13:30:42 +00004408 rc = sqlite3pager_get(pBtTo->pPager, i, &pPage);
drh2e6d11b2003-04-25 15:37:57 +00004409 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00004410 rc = sqlite3pager_write(pPage);
4411 sqlite3pager_unref(pPage);
4412 sqlite3pager_dont_write(pBtTo->pPager, i);
drh2e6d11b2003-04-25 15:37:57 +00004413 }
4414 if( !rc && nPage<nToPage ){
drha34b6762004-05-07 13:30:42 +00004415 rc = sqlite3pager_truncate(pBtTo->pPager, nPage);
drh2e6d11b2003-04-25 15:37:57 +00004416 }
drhf7c57532003-04-25 13:22:51 +00004417 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00004418 sqlite3BtreeRollback(pBtTo);
drhf7c57532003-04-25 13:22:51 +00004419 }
4420 return rc;
drh73509ee2003-04-06 20:44:45 +00004421}
danielk19771d850a72004-05-31 08:26:49 +00004422
4423/*
4424** Return non-zero if a transaction is active.
4425*/
4426int sqlite3BtreeIsInTrans(Btree *pBt){
danielk1977ee5741e2004-05-31 10:01:34 +00004427 return (pBt && (pBt->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00004428}
4429
4430/*
4431** Return non-zero if a statement transaction is active.
4432*/
4433int sqlite3BtreeIsInStmt(Btree *pBt){
4434 return (pBt && pBt->inStmt);
4435}
danielk197713adf8a2004-06-03 16:08:41 +00004436
4437/*
4438** This call is a no-op if no write-transaction is currently active on pBt.
4439**
4440** Otherwise, sync the database file for the btree pBt. zMaster points to
4441** the name of a master journal file that should be written into the
4442** individual journal file, or is NULL, indicating no master journal file
4443** (single database transaction).
4444**
4445** When this is called, the master journal should already have been
4446** created, populated with this journal pointer and synced to disk.
4447**
4448** Once this is routine has returned, the only thing required to commit
4449** the write-transaction for this database file is to delete the journal.
4450*/
4451int sqlite3BtreeSync(Btree *pBt, const char *zMaster){
4452 if( pBt->inTrans==TRANS_WRITE ){
4453 return sqlite3pager_sync(pBt->pPager, zMaster);
4454 }
4455 return SQLITE_OK;
4456}