blob: 86b98d6718744202ee18d030b3632012200a6cd3 [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*************************************************************************
danielk19771d850a72004-05-31 08:26:49 +000012** $Id: btree.c,v 1.153 2004/05/31 08:26:49 danielk1977 Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
15** For a detailed discussion of BTrees, refer to
16**
17** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
18** "Sorting And Searching", pages 473-480. Addison-Wesley
19** Publishing Company, Reading, Massachusetts.
20**
21** The basic idea is that each page of the file contains N database
22** entries and N+1 pointers to subpages.
23**
24** ----------------------------------------------------------------
25** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N) | Ptr(N+1) |
26** ----------------------------------------------------------------
27**
28** All of the keys on the page that Ptr(0) points to have values less
29** than Key(0). All of the keys on page Ptr(1) and its subpages have
30** values greater than Key(0) and less than Key(1). All of the keys
31** on Ptr(N+1) and its subpages have values greater than Key(N). And
32** so forth.
33**
drh5e00f6c2001-09-13 13:46:56 +000034** Finding a particular key requires reading O(log(M)) pages from the
35** disk where M is the number of entries in the tree.
drh8b2f49b2001-06-08 00:21:52 +000036**
37** In this implementation, a single file can hold one or more separate
38** BTrees. Each BTree is identified by the index of its root page. The
drh9e572e62004-04-23 23:43:10 +000039** key and data for any entry are combined to form the "payload". A
40** fixed amount of payload can be carried directly on the database
41** page. If the payload is larger than the preset amount then surplus
42** bytes are stored on overflow pages. The payload for an entry
43** and the preceding pointer are combined to form a "Cell". Each
44** page has a small header which contains the Ptr(N+1) pointer and other
45** information such as the size of key and data.
drh8b2f49b2001-06-08 00:21:52 +000046**
drh9e572e62004-04-23 23:43:10 +000047** FORMAT DETAILS
48**
49** The file is divided into pages. The first page is called page 1,
50** the second is page 2, and so forth. A page number of zero indicates
51** "no such page". The page size can be anything between 512 and 65536.
52** Each page can be either a btree page, a freelist page or an overflow
53** page.
54**
55** The first page is always a btree page. The first 100 bytes of the first
drh271efa52004-05-30 19:19:05 +000056** page contain a special header (the "file header") that describes the file.
57** The format of the file header is as follows:
drh9e572e62004-04-23 23:43:10 +000058**
59** OFFSET SIZE DESCRIPTION
drhde647132004-05-07 17:57:49 +000060** 0 16 Header string: "SQLite format 3\000"
drh9e572e62004-04-23 23:43:10 +000061** 16 2 Page size in bytes.
62** 18 1 File format write version
63** 19 1 File format read version
drh6f11bef2004-05-13 01:12:56 +000064** 20 1 Bytes of unused space at the end of each page
65** 21 1 Max embedded payload fraction
66** 22 1 Min embedded payload fraction
67** 23 1 Min leaf payload fraction
68** 24 4 File change counter
69** 28 4 Reserved for future use
drh9e572e62004-04-23 23:43:10 +000070** 32 4 First freelist page
71** 36 4 Number of freelist pages in the file
72** 40 60 15 4-byte meta values passed to higher layers
73**
74** All of the integer values are big-endian (most significant byte first).
drh6f11bef2004-05-13 01:12:56 +000075**
drhab01f612004-05-22 02:55:23 +000076** The file change counter is incremented when the database is changed more
drh6f11bef2004-05-13 01:12:56 +000077** than once within the same second. This counter, together with the
78** modification time of the file, allows other processes to know
79** when the file has changed and thus when they need to flush their
80** cache.
81**
82** The max embedded payload fraction is the amount of the total usable
83** space in a page that can be consumed by a single cell for standard
84** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
85** is to limit the maximum cell size so that at least 4 cells will fit
drhab01f612004-05-22 02:55:23 +000086** on one page. Thus the default max embedded payload fraction is 64.
drh6f11bef2004-05-13 01:12:56 +000087**
88** If the payload for a cell is larger than the max payload, then extra
89** payload is spilled to overflow pages. Once an overflow page is allocated,
90** as many bytes as possible are moved into the overflow pages without letting
91** the cell size drop below the min embedded payload fraction.
92**
93** The min leaf payload fraction is like the min embedded payload fraction
94** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
95** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
96** not specified in the header.
drh9e572e62004-04-23 23:43:10 +000097**
drh43605152004-05-29 21:46:49 +000098** Each btree pages is divided into three sections: The header, the
99** cell pointer array, and the cell area area. Page 1 also has a 100-byte
drh271efa52004-05-30 19:19:05 +0000100** file header that occurs before the page header.
101**
102** |----------------|
103** | file header | 100 bytes. Page 1 only.
104** |----------------|
105** | page header | 8 bytes for leaves. 12 bytes for interior nodes
106** |----------------|
107** | cell pointer | | 2 bytes per cell. Sorted order.
108** | array | | Grows downward
109** | | v
110** |----------------|
111** | unallocated |
112** | space |
113** |----------------| ^ Grows upwards
114** | cell content | | Arbitrary order interspersed with freeblocks.
115** | area | | and free space fragments.
116** |----------------|
drh43605152004-05-29 21:46:49 +0000117**
118** The page headers looks like this:
drh9e572e62004-04-23 23:43:10 +0000119**
120** OFFSET SIZE DESCRIPTION
drh6f11bef2004-05-13 01:12:56 +0000121** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
drh9e572e62004-04-23 23:43:10 +0000122** 1 2 byte offset to the first freeblock
drh43605152004-05-29 21:46:49 +0000123** 3 2 number of cells on this page
drh271efa52004-05-30 19:19:05 +0000124** 5 2 first byte of the cell content area
drh43605152004-05-29 21:46:49 +0000125** 7 1 number of fragmented free bytes
drh271efa52004-05-30 19:19:05 +0000126** 8 4 Right child (the Ptr(N+1) value). Omitted on leaves.
drh9e572e62004-04-23 23:43:10 +0000127**
128** The flags define the format of this btree page. The leaf flag means that
129** this page has no children. The zerodata flag means that this page carries
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"
210#include <assert.h>
211
drh4b70f112004-05-02 21:12:19 +0000212
213/* Maximum page size. The upper bound on this value is 65536 (a limit
drh43605152004-05-29 21:46:49 +0000214** imposed by the 2-byte size of cell array pointers.) The
drh4b70f112004-05-02 21:12:19 +0000215** maximum page size determines the amount of stack space allocated
216** by many of the routines in this module. On embedded architectures
217** or any machine where memory and especially stack memory is limited,
218** one may wish to chose a smaller value for the maximum page size.
219*/
220#ifndef MX_PAGE_SIZE
221# define MX_PAGE_SIZE 1024
222#endif
223
drh4b70f112004-05-02 21:12:19 +0000224/* The following value is the maximum cell size assuming a maximum page
225** size give above.
226*/
drh43605152004-05-29 21:46:49 +0000227#define MX_CELL_SIZE (MX_PAGE_SIZE-8)
drh4b70f112004-05-02 21:12:19 +0000228
229/* The maximum number of cells on a single page of the database. This
230** assumes a minimum cell size of 3 bytes. Such small cells will be
231** exceedingly rare, but they are possible.
232*/
drh43605152004-05-29 21:46:49 +0000233#define MX_CELL ((MX_PAGE_SIZE-8)/3)
drh4b70f112004-05-02 21:12:19 +0000234
paulb95a8862003-04-01 21:16:41 +0000235/* Forward declarations */
drh3aac2dd2004-04-26 14:10:20 +0000236typedef struct MemPage MemPage;
paulb95a8862003-04-01 21:16:41 +0000237
drh8c42ca92001-06-22 19:15:00 +0000238/*
drhbd03cae2001-06-02 02:40:57 +0000239** This is a magic string that appears at the beginning of every
drh8c42ca92001-06-22 19:15:00 +0000240** SQLite database in order to identify the file as a real database.
drhde647132004-05-07 17:57:49 +0000241** 123456789 123456 */
242static const char zMagicHeader[] = "SQLite format 3";
drh08ed44e2001-04-29 23:32:55 +0000243
244/*
drh4b70f112004-05-02 21:12:19 +0000245** Page type flags. An ORed combination of these flags appear as the
246** first byte of every BTree page.
drh8c42ca92001-06-22 19:15:00 +0000247*/
drhde647132004-05-07 17:57:49 +0000248#define PTF_INTKEY 0x01
drh9e572e62004-04-23 23:43:10 +0000249#define PTF_ZERODATA 0x02
drh8b18dd42004-05-12 19:18:15 +0000250#define PTF_LEAFDATA 0x04
251#define PTF_LEAF 0x08
drh8c42ca92001-06-22 19:15:00 +0000252
253/*
drh9e572e62004-04-23 23:43:10 +0000254** As each page of the file is loaded into memory, an instance of the following
255** structure is appended and initialized to zero. This structure stores
256** information about the page that is decoded from the raw file page.
drh14acc042001-06-10 19:56:58 +0000257**
drh72f82862001-05-24 21:06:34 +0000258** The pParent field points back to the parent page. This allows us to
259** walk up the BTree from any leaf to the root. Care must be taken to
260** unref() the parent page pointer when this page is no longer referenced.
drhbd03cae2001-06-02 02:40:57 +0000261** The pageDestructor() routine handles that chore.
drh7e3b0a02001-04-28 16:52:40 +0000262*/
263struct MemPage {
drh43605152004-05-29 21:46:49 +0000264 u8 isInit; /* True if previously initialized */
265 u8 idxShift; /* True if Cell indices have changed */
266 u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
267 u8 intKey; /* True if intkey flag is set */
268 u8 leaf; /* True if leaf flag is set */
269 u8 zeroData; /* True if table stores keys only */
270 u8 leafData; /* True if tables stores data on leaves only */
271 u8 hasData; /* True if this page stores data */
272 u8 hdrOffset; /* 100 for page 1. 0 otherwise */
drh271efa52004-05-30 19:19:05 +0000273 u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
274 u8 maxLocal; /* Copy of Btree.maxLocal or Btree.maxLeaf */
275 u8 minLocal; /* Copy of Btree.minLocal or Btree.minLeaf */
drh43605152004-05-29 21:46:49 +0000276 u16 cellOffset; /* Index in aData of first cell pointer */
277 u16 idxParent; /* Index in parent of this node */
278 u16 nFree; /* Number of free bytes on the page */
279 u16 nCell; /* Number of cells on this page, local and ovfl */
280 struct _OvflCell { /* Cells that will not fit on aData[] */
281 u8 *pCell; /* Pointers to the body of the overflow cell */
282 u16 idx; /* Insert this cell before idx-th non-overflow cell */
283 } aOvfl[3];
284 struct Btree *pBt; /* Pointer back to BTree structure */
285 u8 *aData; /* Pointer back to the start of the page */
286 Pgno pgno; /* Page number for this page */
287 MemPage *pParent; /* The parent of this page. NULL for root */
drh8c42ca92001-06-22 19:15:00 +0000288};
drh7e3b0a02001-04-28 16:52:40 +0000289
290/*
drh3b7511c2001-05-26 13:15:44 +0000291** The in-memory image of a disk page has the auxiliary information appended
292** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
293** that extra information.
294*/
drh3aac2dd2004-04-26 14:10:20 +0000295#define EXTRA_SIZE sizeof(MemPage)
drh3b7511c2001-05-26 13:15:44 +0000296
297/*
drha059ad02001-04-17 20:09:11 +0000298** Everything we need to know about an open database
299*/
300struct Btree {
301 Pager *pPager; /* The page cache */
drh306dc212001-05-21 13:45:10 +0000302 BtCursor *pCursor; /* A list of all open cursors */
drh3aac2dd2004-04-26 14:10:20 +0000303 MemPage *pPage1; /* First page of the database */
drh663fc632002-02-02 18:49:19 +0000304 u8 inTrans; /* True if a transaction is in progress */
drhab01f612004-05-22 02:55:23 +0000305 u8 inStmt; /* True if we are in a statement subtransaction */
drh5df72a52002-06-06 23:16:05 +0000306 u8 readOnly; /* True if the underlying file is readonly */
drhab01f612004-05-22 02:55:23 +0000307 u8 maxEmbedFrac; /* Maximum payload as % of total page size */
308 u8 minEmbedFrac; /* Minimum payload as % of total page size */
309 u8 minLeafFrac; /* Minimum leaf payload as % of total page size */
drhb6f41482004-05-14 01:58:11 +0000310 int pageSize; /* Total number of bytes on a page */
311 int usableSize; /* Number of usable bytes on each page */
drh6f11bef2004-05-13 01:12:56 +0000312 int maxLocal; /* Maximum local payload in non-LEAFDATA tables */
313 int minLocal; /* Minimum local payload in non-LEAFDATA tables */
314 int maxLeaf; /* Maximum local payload in a LEAFDATA table */
315 int minLeaf; /* Minimum local payload in a LEAFDATA table */
drha059ad02001-04-17 20:09:11 +0000316};
317typedef Btree Bt;
318
drh365d68f2001-05-11 11:02:46 +0000319/*
drhfa1a98a2004-05-14 19:08:17 +0000320** An instance of the following structure is used to hold information
drh271efa52004-05-30 19:19:05 +0000321** about a cell. The parseCellPtr() function fills in this structure
drhab01f612004-05-22 02:55:23 +0000322** based on information extract from the raw disk page.
drhfa1a98a2004-05-14 19:08:17 +0000323*/
324typedef struct CellInfo CellInfo;
325struct CellInfo {
drh43605152004-05-29 21:46:49 +0000326 u8 *pCell; /* Pointer to the start of cell content */
drhfa1a98a2004-05-14 19:08:17 +0000327 i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
328 u32 nData; /* Number of bytes of data */
drh271efa52004-05-30 19:19:05 +0000329 u16 nHeader; /* Size of the cell content header in bytes */
drhfa1a98a2004-05-14 19:08:17 +0000330 u16 nLocal; /* Amount of payload held locally */
drhab01f612004-05-22 02:55:23 +0000331 u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
drh271efa52004-05-30 19:19:05 +0000332 u16 nSize; /* Size of the cell content on the main b-tree page */
drhfa1a98a2004-05-14 19:08:17 +0000333};
334
335/*
drh365d68f2001-05-11 11:02:46 +0000336** A cursor is a pointer to a particular entry in the BTree.
337** The entry is identified by its MemPage and the index in
drha34b6762004-05-07 13:30:42 +0000338** MemPage.aCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000339*/
drh72f82862001-05-24 21:06:34 +0000340struct BtCursor {
drh5e2f8b92001-05-28 00:41:15 +0000341 Btree *pBt; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000342 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drhf74b8d92002-09-01 23:20:45 +0000343 BtCursor *pShared; /* Loop of cursors with the same root page */
drh3aac2dd2004-04-26 14:10:20 +0000344 int (*xCompare)(void*,int,const void*,int,const void*); /* Key comp func */
345 void *pArg; /* First arg to xCompare() */
drh8b2f49b2001-06-08 00:21:52 +0000346 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000347 MemPage *pPage; /* Page that contains the entry */
drh3aac2dd2004-04-26 14:10:20 +0000348 int idx; /* Index of the entry in pPage->aCell[] */
drhfa1a98a2004-05-14 19:08:17 +0000349 CellInfo info; /* A parse of the cell we are pointing at */
drhecdc7532001-09-23 02:35:53 +0000350 u8 wrFlag; /* True if writable */
drhc39e0002004-05-07 23:50:57 +0000351 u8 isValid; /* TRUE if points to a valid entry */
352 u8 status; /* Set to SQLITE_ABORT if cursors is invalidated */
drh365d68f2001-05-11 11:02:46 +0000353};
drh7e3b0a02001-04-28 16:52:40 +0000354
drha059ad02001-04-17 20:09:11 +0000355/*
drhab01f612004-05-22 02:55:23 +0000356** Read or write a two- and four-byte big-endian integer values.
drh0d316a42002-08-11 20:10:47 +0000357*/
drh9e572e62004-04-23 23:43:10 +0000358static u32 get2byte(unsigned char *p){
359 return (p[0]<<8) | p[1];
drh0d316a42002-08-11 20:10:47 +0000360}
drh9e572e62004-04-23 23:43:10 +0000361static u32 get4byte(unsigned char *p){
362 return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
363}
drh9e572e62004-04-23 23:43:10 +0000364static void put2byte(unsigned char *p, u32 v){
365 p[0] = v>>8;
366 p[1] = v;
367}
368static void put4byte(unsigned char *p, u32 v){
369 p[0] = v>>24;
370 p[1] = v>>16;
371 p[2] = v>>8;
372 p[3] = v;
373}
drh6f11bef2004-05-13 01:12:56 +0000374
drh9e572e62004-04-23 23:43:10 +0000375/*
drhab01f612004-05-22 02:55:23 +0000376** Routines to read and write variable-length integers. These used to
377** be defined locally, but now we use the varint routines in the util.c
378** file.
drh9e572e62004-04-23 23:43:10 +0000379*/
drh6d2fb152004-05-14 16:50:06 +0000380#define getVarint sqlite3GetVarint
381#define getVarint32 sqlite3GetVarint32
382#define putVarint sqlite3PutVarint
drh0d316a42002-08-11 20:10:47 +0000383
384/*
drh271efa52004-05-30 19:19:05 +0000385** Given a btree page and a cell index (0 means the first cell on
386** the page, 1 means the second cell, and so forth) return a pointer
387** to the cell content.
388**
389** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000390*/
drh43605152004-05-29 21:46:49 +0000391static u8 *findCell(MemPage *pPage, int iCell){
392 u8 *data = pPage->aData;
393 assert( iCell>=0 );
394 assert( iCell<get2byte(&data[pPage->hdrOffset+3]) );
395 return data + get2byte(&data[pPage->cellOffset+2*iCell]);
396}
397
398/*
399** This a more complex version of findCell() that works for
400** pages that do contain overflow cells. See insert
401*/
402static u8 *findOverflowCell(MemPage *pPage, int iCell){
403 int i;
404 for(i=pPage->nOverflow-1; i>=0; i--){
405 if( pPage->aOvfl[i].idx<=iCell ){
406 if( pPage->aOvfl[i].idx==iCell ){
407 return pPage->aOvfl[i].pCell;
408 }
409 iCell--;
410 }
411 }
412 return findCell(pPage, iCell);
413}
414
415/*
416** Parse a cell content block and fill in the CellInfo structure. There
417** are two versions of this function. parseCell() takes a cell index
418** as the second argument and parseCellPtr() takes a pointer to the
419** body of the cell as its second argument.
420*/
421static void parseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000422 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000423 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000424 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000425){
drh271efa52004-05-30 19:19:05 +0000426 int n; /* Number bytes in cell content header */
427 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000428
429 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000430 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000431 n = pPage->childPtrSize;
432 assert( n==4-4*pPage->leaf );
drh8b18dd42004-05-12 19:18:15 +0000433 if( pPage->hasData ){
drh271efa52004-05-30 19:19:05 +0000434 n += getVarint32(&pCell[n], &nPayload);
drh8b18dd42004-05-12 19:18:15 +0000435 }else{
drh271efa52004-05-30 19:19:05 +0000436 nPayload = 0;
drh3aac2dd2004-04-26 14:10:20 +0000437 }
drh6f11bef2004-05-13 01:12:56 +0000438 n += getVarint(&pCell[n], &pInfo->nKey);
439 pInfo->nHeader = n;
drh271efa52004-05-30 19:19:05 +0000440 pInfo->nData = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000441 if( !pPage->intKey ){
442 nPayload += pInfo->nKey;
443 }
drh271efa52004-05-30 19:19:05 +0000444 if( nPayload<=pPage->maxLocal ){
445 /* This is the (easy) common case where the entire payload fits
446 ** on the local page. No overflow is required.
447 */
448 int nSize; /* Total size of cell content in bytes */
drh6f11bef2004-05-13 01:12:56 +0000449 pInfo->nLocal = nPayload;
450 pInfo->iOverflow = 0;
drh271efa52004-05-30 19:19:05 +0000451 nSize = nPayload + n;
452 if( nSize<4 ){
453 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000454 }
drh271efa52004-05-30 19:19:05 +0000455 pInfo->nSize = nSize;
drh6f11bef2004-05-13 01:12:56 +0000456 }else{
drh271efa52004-05-30 19:19:05 +0000457 /* If the payload will not fit completely on the local page, we have
458 ** to decide how much to store locally and how much to spill onto
459 ** overflow pages. The strategy is to minimize the amount of unused
460 ** space on overflow pages while keeping the amount of local storage
461 ** in between minLocal and maxLocal.
462 **
463 ** Warning: changing the way overflow payload is distributed in any
464 ** way will result in an incompatible file format.
465 */
466 int minLocal; /* Minimum amount of payload held locally */
467 int maxLocal; /* Maximum amount of payload held locally */
468 int surplus; /* Overflow payload available for local storage */
469
470 minLocal = pPage->minLocal;
471 maxLocal = pPage->maxLocal;
472 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000473 if( surplus <= maxLocal ){
474 pInfo->nLocal = surplus;
475 }else{
476 pInfo->nLocal = minLocal;
477 }
478 pInfo->iOverflow = pInfo->nLocal + n;
479 pInfo->nSize = pInfo->iOverflow + 4;
480 }
drh3aac2dd2004-04-26 14:10:20 +0000481}
drh43605152004-05-29 21:46:49 +0000482static void parseCell(
483 MemPage *pPage, /* Page containing the cell */
484 int iCell, /* The cell index. First cell is 0 */
485 CellInfo *pInfo /* Fill in this structure */
486){
487 parseCellPtr(pPage, findCell(pPage, iCell), pInfo);
488}
drh3aac2dd2004-04-26 14:10:20 +0000489
490/*
drh43605152004-05-29 21:46:49 +0000491** Compute the total number of bytes that a Cell needs in the cell
492** data area of the btree-page. The return number includes the cell
493** data header and the local payload, but not any overflow page or
494** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000495*/
drh43605152004-05-29 21:46:49 +0000496static int cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000497 CellInfo info;
drh43605152004-05-29 21:46:49 +0000498 parseCell(pPage, iCell, &info);
499 return info.nSize;
500}
501static int cellSizePtr(MemPage *pPage, u8 *pCell){
502 CellInfo info;
503 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000504 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000505}
506
507/*
drhda200cc2004-05-09 11:51:38 +0000508** Do sanity checking on a page. Throw an exception if anything is
509** not right.
510**
511** This routine is used for internal error checking only. It is omitted
512** from most builds.
513*/
514#if defined(BTREE_DEBUG) && !defined(NDEBUG) && 0
515static void _pageIntegrity(MemPage *pPage){
drhb6f41482004-05-14 01:58:11 +0000516 int usableSize;
drhda200cc2004-05-09 11:51:38 +0000517 u8 *data;
drh43605152004-05-29 21:46:49 +0000518 int i, j, idx, c, pc, hdr, nFree;
519 int cellOffset;
520 int nCell, cellLimit;
drhda200cc2004-05-09 11:51:38 +0000521 u8 used[MX_PAGE_SIZE];
522
drhb6f41482004-05-14 01:58:11 +0000523 usableSize = pPage->pBt->usableSize;
524 assert( pPage->aData==&((unsigned char*)pPage)[-pPage->pBt->pageSize] );
drhda200cc2004-05-09 11:51:38 +0000525 hdr = pPage->hdrOffset;
526 assert( hdr==(pPage->pgno==1 ? 100 : 0) );
527 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
528 c = pPage->aData[hdr];
529 if( pPage->isInit ){
530 assert( pPage->leaf == ((c & PTF_LEAF)!=0) );
531 assert( pPage->zeroData == ((c & PTF_ZERODATA)!=0) );
drh8b18dd42004-05-12 19:18:15 +0000532 assert( pPage->leafData == ((c & PTF_LEAFDATA)!=0) );
533 assert( pPage->intKey == ((c & (PTF_INTKEY|PTF_LEAFDATA))!=0) );
534 assert( pPage->hasData ==
535 !(pPage->zeroData || (!pPage->leaf && pPage->leafData)) );
drh43605152004-05-29 21:46:49 +0000536 assert( pPage->cellOffset==pPage->hdrOffset+12-4*pPage->leaf );
537 assert( pPage->nCell = get2byte(&pPage->aData[hdr+3]) );
drhda200cc2004-05-09 11:51:38 +0000538 }
539 data = pPage->aData;
drhb6f41482004-05-14 01:58:11 +0000540 memset(used, 0, usableSize);
drhda200cc2004-05-09 11:51:38 +0000541 for(i=0; i<hdr+10-pPage->leaf*4; i++) used[i] = 1;
542 nFree = 0;
543 pc = get2byte(&data[hdr+1]);
544 while( pc ){
545 int size;
drhb6f41482004-05-14 01:58:11 +0000546 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +0000547 size = get2byte(&data[pc+2]);
drhb6f41482004-05-14 01:58:11 +0000548 assert( pc+size<=usableSize );
drhda200cc2004-05-09 11:51:38 +0000549 nFree += size;
550 for(i=pc; i<pc+size; i++){
551 assert( used[i]==0 );
552 used[i] = 1;
553 }
554 pc = get2byte(&data[pc]);
555 }
drhda200cc2004-05-09 11:51:38 +0000556 idx = 0;
drh43605152004-05-29 21:46:49 +0000557 nCell = get2byte(&data[hdr+3]);
558 cellLimit = get2byte(&data[hdr+5]);
559 assert( pPage->isInit==0
560 || pPage->nFree==nFree+data[hdr+7]+cellLimit-(cellOffset+2*nCell) );
561 cellOffset = pPage->cellOffset;
562 for(i=0; i<nCell; i++){
drhda200cc2004-05-09 11:51:38 +0000563 int size;
drh43605152004-05-29 21:46:49 +0000564 pc = get2byte(&data[cellOffset+2*i]);
drhb6f41482004-05-14 01:58:11 +0000565 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +0000566 size = cellSize(pPage, &data[pc]);
drhb6f41482004-05-14 01:58:11 +0000567 assert( pc+size<=usableSize );
drh43605152004-05-29 21:46:49 +0000568 for(j=pc; j<pc+size; j++){
569 assert( used[j]==0 );
570 used[j] = 1;
drhda200cc2004-05-09 11:51:38 +0000571 }
drhda200cc2004-05-09 11:51:38 +0000572 }
drh43605152004-05-29 21:46:49 +0000573 for(i=cellOffset+2*nCell; i<cellimit; i++){
574 assert( used[i]==0 );
575 used[i] = 1;
576 }
drhda200cc2004-05-09 11:51:38 +0000577 nFree = 0;
drhb6f41482004-05-14 01:58:11 +0000578 for(i=0; i<usableSize; i++){
drhda200cc2004-05-09 11:51:38 +0000579 assert( used[i]<=1 );
580 if( used[i]==0 ) nFree++;
581 }
drh43605152004-05-29 21:46:49 +0000582 assert( nFree==data[hdr+7] );
drhda200cc2004-05-09 11:51:38 +0000583}
584#define pageIntegrity(X) _pageIntegrity(X)
585#else
586# define pageIntegrity(X)
587#endif
588
589/*
drh72f82862001-05-24 21:06:34 +0000590** Defragment the page given. All Cells are moved to the
591** beginning of the page and all free space is collected
592** into one big FreeBlk at the end of the page.
drh365d68f2001-05-11 11:02:46 +0000593*/
drh9e572e62004-04-23 23:43:10 +0000594static void defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000595 int i; /* Loop counter */
596 int pc; /* Address of a i-th cell */
597 int addr; /* Offset of first byte after cell pointer array */
598 int hdr; /* Offset to the page header */
599 int size; /* Size of a cell */
600 int usableSize; /* Number of usable bytes on a page */
601 int cellOffset; /* Offset to the cell pointer array */
602 int brk; /* Offset to the cell content area */
603 int nCell; /* Number of cells on the page */
604 unsigned char *data; /* The page data */
605 unsigned char temp[MX_PAGE_SIZE]; /* Temp holding area for cell content */
drh2af926b2001-05-15 00:39:25 +0000606
drha34b6762004-05-07 13:30:42 +0000607 assert( sqlite3pager_iswriteable(pPage->aData) );
drh9e572e62004-04-23 23:43:10 +0000608 assert( pPage->pBt!=0 );
drhb6f41482004-05-14 01:58:11 +0000609 assert( pPage->pBt->usableSize <= MX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000610 assert( pPage->nOverflow==0 );
611 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000612 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000613 cellOffset = pPage->cellOffset;
614 nCell = pPage->nCell;
615 assert( nCell==get2byte(&data[hdr+3]) );
616 usableSize = pPage->pBt->usableSize;
617 brk = get2byte(&data[hdr+5]);
618 memcpy(&temp[brk], &data[brk], usableSize - brk);
619 brk = usableSize;
620 for(i=0; i<nCell; i++){
621 u8 *pAddr; /* The i-th cell pointer */
622 pAddr = &data[cellOffset + i*2];
623 pc = get2byte(pAddr);
624 assert( pc<pPage->pBt->usableSize );
625 size = cellSizePtr(pPage, &temp[pc]);
626 brk -= size;
627 memcpy(&data[brk], &temp[pc], size);
628 put2byte(pAddr, brk);
drh2af926b2001-05-15 00:39:25 +0000629 }
drh43605152004-05-29 21:46:49 +0000630 assert( brk>=cellOffset+2*nCell );
631 put2byte(&data[hdr+5], brk);
632 data[hdr+1] = 0;
633 data[hdr+2] = 0;
634 data[hdr+7] = 0;
635 addr = cellOffset+2*nCell;
636 memset(&data[addr], 0, brk-addr);
drh365d68f2001-05-11 11:02:46 +0000637}
638
drha059ad02001-04-17 20:09:11 +0000639/*
drh43605152004-05-29 21:46:49 +0000640** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +0000641**
drh9e572e62004-04-23 23:43:10 +0000642** Return the index into pPage->aData[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000643** the new allocation. Or return 0 if there is not enough free
644** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000645**
drh72f82862001-05-24 21:06:34 +0000646** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000647** nBytes of contiguous free space, then this routine automatically
648** calls defragementPage() to consolidate all free space before
649** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000650*/
drh9e572e62004-04-23 23:43:10 +0000651static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +0000652 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +0000653 int size;
drh24cd67e2004-05-10 16:18:47 +0000654 int nFrag;
drh43605152004-05-29 21:46:49 +0000655 int top;
656 int nCell;
657 int cellOffset;
drh9e572e62004-04-23 23:43:10 +0000658 unsigned char *data;
drh43605152004-05-29 21:46:49 +0000659
drh9e572e62004-04-23 23:43:10 +0000660 data = pPage->aData;
drha34b6762004-05-07 13:30:42 +0000661 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +0000662 assert( pPage->pBt );
663 if( nByte<4 ) nByte = 4;
drh43605152004-05-29 21:46:49 +0000664 if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
665 pPage->nFree -= nByte;
drh9e572e62004-04-23 23:43:10 +0000666 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000667
668 nFrag = data[hdr+7];
669 if( nFrag<60 ){
670 /* Search the freelist looking for a slot big enough to satisfy the
671 ** space request. */
672 addr = hdr+1;
673 while( (pc = get2byte(&data[addr]))>0 ){
674 size = get2byte(&data[pc+2]);
675 if( size>=nByte ){
676 if( size<nByte+4 ){
677 memcpy(&data[addr], &data[pc], 2);
678 data[hdr+7] = nFrag + size - nByte;
679 return pc;
680 }else{
681 put2byte(&data[pc+2], size-nByte);
682 return pc + size - nByte;
683 }
684 }
685 addr = pc;
drh9e572e62004-04-23 23:43:10 +0000686 }
687 }
drh43605152004-05-29 21:46:49 +0000688
689 /* Allocate memory from the gap in between the cell pointer array
690 ** and the cell content area.
691 */
692 top = get2byte(&data[hdr+5]);
693 nCell = get2byte(&data[hdr+3]);
694 cellOffset = pPage->cellOffset;
695 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
696 defragmentPage(pPage);
697 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +0000698 }
drh43605152004-05-29 21:46:49 +0000699 top -= nByte;
700 assert( cellOffset + 2*nCell <= top );
701 put2byte(&data[hdr+5], top);
702 return top;
drh7e3b0a02001-04-28 16:52:40 +0000703}
704
705/*
drh9e572e62004-04-23 23:43:10 +0000706** Return a section of the pPage->aData to the freelist.
707** The first byte of the new free block is pPage->aDisk[start]
708** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +0000709**
710** Most of the effort here is involved in coalesing adjacent
711** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000712*/
drh9e572e62004-04-23 23:43:10 +0000713static void freeSpace(MemPage *pPage, int start, int size){
714 int end = start + size; /* End of the segment being freed */
drh43605152004-05-29 21:46:49 +0000715 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +0000716 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +0000717
drh9e572e62004-04-23 23:43:10 +0000718 assert( pPage->pBt!=0 );
drha34b6762004-05-07 13:30:42 +0000719 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +0000720 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
drhb6f41482004-05-14 01:58:11 +0000721 assert( end<=pPage->pBt->usableSize );
drh9e572e62004-04-23 23:43:10 +0000722 if( size<4 ) size = 4;
723
724 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +0000725 hdr = pPage->hdrOffset;
726 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +0000727 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +0000728 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000729 assert( pbegin>addr );
730 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +0000731 }
drhb6f41482004-05-14 01:58:11 +0000732 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000733 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +0000734 put2byte(&data[addr], start);
735 put2byte(&data[start], pbegin);
736 put2byte(&data[start+2], size);
drh2af926b2001-05-15 00:39:25 +0000737 pPage->nFree += size;
drh9e572e62004-04-23 23:43:10 +0000738
739 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +0000740 addr = pPage->hdrOffset + 1;
741 while( (pbegin = get2byte(&data[addr]))>0 ){
drh9e572e62004-04-23 23:43:10 +0000742 int pnext, psize;
drh3aac2dd2004-04-26 14:10:20 +0000743 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +0000744 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +0000745 pnext = get2byte(&data[pbegin]);
746 psize = get2byte(&data[pbegin+2]);
747 if( pbegin + psize + 3 >= pnext && pnext>0 ){
748 int frag = pnext - (pbegin+psize);
drh43605152004-05-29 21:46:49 +0000749 assert( frag<=data[pPage->hdrOffset+7] );
750 data[pPage->hdrOffset+7] -= frag;
drh9e572e62004-04-23 23:43:10 +0000751 put2byte(&data[pbegin], get2byte(&data[pnext]));
752 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
753 }else{
drh3aac2dd2004-04-26 14:10:20 +0000754 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +0000755 }
756 }
drh7e3b0a02001-04-28 16:52:40 +0000757
drh43605152004-05-29 21:46:49 +0000758 /* If the cell content area begins with a freeblock, remove it. */
759 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
760 int top;
761 pbegin = get2byte(&data[hdr+1]);
762 memcpy(&data[hdr+1], &data[pbegin], 2);
763 top = get2byte(&data[hdr+5]);
764 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
drh4b70f112004-05-02 21:12:19 +0000765 }
drh4b70f112004-05-02 21:12:19 +0000766}
767
768/*
drh271efa52004-05-30 19:19:05 +0000769** Decode the flags byte (the first byte of the header) for a page
770** and initialize fields of the MemPage structure accordingly.
771*/
772static void decodeFlags(MemPage *pPage, int flagByte){
773 Btree *pBt; /* A copy of pPage->pBt */
774
775 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
776 pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
777 pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
778 pPage->leaf = (flagByte & PTF_LEAF)!=0;
779 pPage->childPtrSize = 4*(pPage->leaf==0);
780 pBt = pPage->pBt;
781 if( flagByte & PTF_LEAFDATA ){
782 pPage->leafData = 1;
783 pPage->maxLocal = pBt->maxLeaf;
784 pPage->minLocal = pBt->minLeaf;
785 }else{
786 pPage->leafData = 0;
787 pPage->maxLocal = pBt->maxLocal;
788 pPage->minLocal = pBt->minLocal;
789 }
790 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
791}
792
793/*
drh7e3b0a02001-04-28 16:52:40 +0000794** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000795**
drhbd03cae2001-06-02 02:40:57 +0000796** The pParent parameter must be a pointer to the MemPage which
drh9e572e62004-04-23 23:43:10 +0000797** is the parent of the page being initialized. The root of a
798** BTree has no parent and so for that page, pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000799**
drh72f82862001-05-24 21:06:34 +0000800** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +0000801** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +0000802** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
803** guarantee that the page is well-formed. It only shows that
804** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000805*/
drh9e572e62004-04-23 23:43:10 +0000806static int initPage(
drh3aac2dd2004-04-26 14:10:20 +0000807 MemPage *pPage, /* The page to be initialized */
drh9e572e62004-04-23 23:43:10 +0000808 MemPage *pParent /* The parent. Might be NULL */
809){
drh271efa52004-05-30 19:19:05 +0000810 int pc; /* Address of a freeblock within pPage->aData[] */
811 int i; /* Loop counter */
812 int hdr; /* Offset to beginning of page header */
813 u8 *data; /* Equal to pPage->aData */
814 int usableSize; /* Amount of usable space on each page */
815 int cellOffset; /* Offset from start of page to first cell pointer */
816 int nFree; /* Number of unused bytes on the page */
817 int top; /* First byte of the cell content area */
drh2af926b2001-05-15 00:39:25 +0000818
drh3aac2dd2004-04-26 14:10:20 +0000819 assert( pPage->pBt!=0 );
drh4b70f112004-05-02 21:12:19 +0000820 assert( pParent==0 || pParent->pBt==pPage->pBt );
drha34b6762004-05-07 13:30:42 +0000821 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
drhde647132004-05-07 17:57:49 +0000822 assert( pPage->aData == &((unsigned char*)pPage)[-pPage->pBt->pageSize] );
drhda200cc2004-05-09 11:51:38 +0000823 assert( pPage->pParent==0 || pPage->pParent==pParent );
drh10617cd2004-05-14 15:27:27 +0000824 assert( pPage->pParent==pParent || !pPage->isInit );
825 if( pPage->isInit ) return SQLITE_OK;
drhda200cc2004-05-09 11:51:38 +0000826 if( pPage->pParent==0 && pParent!=0 ){
827 pPage->pParent = pParent;
drha34b6762004-05-07 13:30:42 +0000828 sqlite3pager_ref(pParent->aData);
drh5e2f8b92001-05-28 00:41:15 +0000829 }
drhde647132004-05-07 17:57:49 +0000830 hdr = pPage->hdrOffset;
drha34b6762004-05-07 13:30:42 +0000831 data = pPage->aData;
drh271efa52004-05-30 19:19:05 +0000832 decodeFlags(pPage, data[hdr]);
drh43605152004-05-29 21:46:49 +0000833 pPage->nOverflow = 0;
drhc8629a12004-05-08 20:07:40 +0000834 pPage->idxShift = 0;
drhb6f41482004-05-14 01:58:11 +0000835 usableSize = pPage->pBt->usableSize;
drh43605152004-05-29 21:46:49 +0000836 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
837 top = get2byte(&data[hdr+5]);
838 pPage->nCell = get2byte(&data[hdr+3]);
drh9e572e62004-04-23 23:43:10 +0000839
840 /* Compute the total free space on the page */
drh9e572e62004-04-23 23:43:10 +0000841 pc = get2byte(&data[hdr+1]);
drh43605152004-05-29 21:46:49 +0000842 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
drh3add3672004-05-15 00:29:24 +0000843 i = 0;
drh9e572e62004-04-23 23:43:10 +0000844 while( pc>0 ){
845 int next, size;
drhb6f41482004-05-14 01:58:11 +0000846 if( pc>=usableSize ) return SQLITE_CORRUPT;
drh3add3672004-05-15 00:29:24 +0000847 if( i++>MX_PAGE_SIZE ) return SQLITE_CORRUPT;
drh9e572e62004-04-23 23:43:10 +0000848 next = get2byte(&data[pc]);
849 size = get2byte(&data[pc+2]);
drh3aac2dd2004-04-26 14:10:20 +0000850 if( next>0 && next<=pc+size+3 ) return SQLITE_CORRUPT;
drh3add3672004-05-15 00:29:24 +0000851 nFree += size;
drh9e572e62004-04-23 23:43:10 +0000852 pc = next;
853 }
drh3add3672004-05-15 00:29:24 +0000854 pPage->nFree = nFree;
855 if( nFree>=usableSize ) return SQLITE_CORRUPT;
drh9e572e62004-04-23 23:43:10 +0000856
drhde647132004-05-07 17:57:49 +0000857 pPage->isInit = 1;
drhda200cc2004-05-09 11:51:38 +0000858 pageIntegrity(pPage);
drh9e572e62004-04-23 23:43:10 +0000859 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +0000860}
861
862/*
drh8b2f49b2001-06-08 00:21:52 +0000863** Set up a raw page so that it looks like a database page holding
864** no entries.
drhbd03cae2001-06-02 02:40:57 +0000865*/
drh9e572e62004-04-23 23:43:10 +0000866static void zeroPage(MemPage *pPage, int flags){
867 unsigned char *data = pPage->aData;
868 Btree *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +0000869 int hdr = pPage->hdrOffset;
drh9e572e62004-04-23 23:43:10 +0000870 int first;
871
drhda200cc2004-05-09 11:51:38 +0000872 assert( sqlite3pager_pagenumber(data)==pPage->pgno );
873 assert( &data[pBt->pageSize] == (unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +0000874 assert( sqlite3pager_iswriteable(data) );
drhb6f41482004-05-14 01:58:11 +0000875 memset(&data[hdr], 0, pBt->usableSize - hdr);
drh9e572e62004-04-23 23:43:10 +0000876 data[hdr] = flags;
drh43605152004-05-29 21:46:49 +0000877 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
878 memset(&data[hdr+1], 0, 4);
879 data[hdr+7] = 0;
880 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +0000881 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +0000882 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +0000883 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +0000884 pPage->cellOffset = first;
885 pPage->nOverflow = 0;
drhda200cc2004-05-09 11:51:38 +0000886 pPage->idxShift = 0;
drh43605152004-05-29 21:46:49 +0000887 pPage->nCell = 0;
drhda200cc2004-05-09 11:51:38 +0000888 pPage->isInit = 1;
889 pageIntegrity(pPage);
drhbd03cae2001-06-02 02:40:57 +0000890}
891
892/*
drh3aac2dd2004-04-26 14:10:20 +0000893** Get a page from the pager. Initialize the MemPage.pBt and
894** MemPage.aData elements if needed.
895*/
896static int getPage(Btree *pBt, Pgno pgno, MemPage **ppPage){
897 int rc;
898 unsigned char *aData;
899 MemPage *pPage;
drha34b6762004-05-07 13:30:42 +0000900 rc = sqlite3pager_get(pBt->pPager, pgno, (void**)&aData);
drh3aac2dd2004-04-26 14:10:20 +0000901 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +0000902 pPage = (MemPage*)&aData[pBt->pageSize];
drh3aac2dd2004-04-26 14:10:20 +0000903 pPage->aData = aData;
904 pPage->pBt = pBt;
905 pPage->pgno = pgno;
drhde647132004-05-07 17:57:49 +0000906 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
drh3aac2dd2004-04-26 14:10:20 +0000907 *ppPage = pPage;
908 return SQLITE_OK;
909}
910
911/*
drhde647132004-05-07 17:57:49 +0000912** Get a page from the pager and initialize it. This routine
913** is just a convenience wrapper around separate calls to
914** getPage() and initPage().
915*/
916static int getAndInitPage(
917 Btree *pBt, /* The database file */
918 Pgno pgno, /* Number of the page to get */
919 MemPage **ppPage, /* Write the page pointer here */
920 MemPage *pParent /* Parent of the page */
921){
922 int rc;
923 rc = getPage(pBt, pgno, ppPage);
drh10617cd2004-05-14 15:27:27 +0000924 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
drhde647132004-05-07 17:57:49 +0000925 rc = initPage(*ppPage, pParent);
926 }
927 return rc;
928}
929
930/*
drh3aac2dd2004-04-26 14:10:20 +0000931** Release a MemPage. This should be called once for each prior
932** call to getPage.
933*/
drh4b70f112004-05-02 21:12:19 +0000934static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +0000935 if( pPage ){
936 assert( pPage->aData );
937 assert( pPage->pBt );
938 assert( &pPage->aData[pPage->pBt->pageSize]==(unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +0000939 sqlite3pager_unref(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +0000940 }
941}
942
943/*
drh72f82862001-05-24 21:06:34 +0000944** This routine is called when the reference count for a page
945** reaches zero. We need to unref the pParent pointer when that
946** happens.
947*/
drhb6f41482004-05-14 01:58:11 +0000948static void pageDestructor(void *pData, int pageSize){
949 MemPage *pPage = (MemPage*)&((char*)pData)[pageSize];
drh72f82862001-05-24 21:06:34 +0000950 if( pPage->pParent ){
951 MemPage *pParent = pPage->pParent;
952 pPage->pParent = 0;
drha34b6762004-05-07 13:30:42 +0000953 releasePage(pParent);
drh72f82862001-05-24 21:06:34 +0000954 }
drh3aac2dd2004-04-26 14:10:20 +0000955 pPage->isInit = 0;
drh72f82862001-05-24 21:06:34 +0000956}
957
958/*
drh306dc212001-05-21 13:45:10 +0000959** Open a new database.
960**
961** Actually, this routine just sets up the internal data structures
drh72f82862001-05-24 21:06:34 +0000962** for accessing the database. We do not open the database file
963** until the first page is loaded.
drh382c0242001-10-06 16:33:02 +0000964**
965** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +0000966** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +0000967** database file will be deleted when sqlite3BtreeClose() is called.
drha059ad02001-04-17 20:09:11 +0000968*/
drh23e11ca2004-05-04 17:27:28 +0000969int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +0000970 const char *zFilename, /* Name of the file containing the BTree database */
971 Btree **ppBtree, /* Pointer to new Btree object written here */
972 int nCache, /* Number of cache pages */
973 int flags /* Options */
drh6019e162001-07-02 17:51:45 +0000974){
drha059ad02001-04-17 20:09:11 +0000975 Btree *pBt;
drha34b6762004-05-07 13:30:42 +0000976 int rc;
drha059ad02001-04-17 20:09:11 +0000977
drhd62d3d02003-01-24 12:14:20 +0000978 /*
979 ** The following asserts make sure that structures used by the btree are
980 ** the right size. This is to guard against size changes that result
981 ** when compiling on a different architecture.
982 */
drh4a1c3802004-05-12 15:15:47 +0000983 assert( sizeof(i64)==8 );
drh9e572e62004-04-23 23:43:10 +0000984 assert( sizeof(u64)==8 );
drhd62d3d02003-01-24 12:14:20 +0000985 assert( sizeof(u32)==4 );
986 assert( sizeof(u16)==2 );
987 assert( sizeof(Pgno)==4 );
drhd62d3d02003-01-24 12:14:20 +0000988 assert( sizeof(ptr)==sizeof(char*) );
989 assert( sizeof(uptr)==sizeof(ptr) );
990
drha059ad02001-04-17 20:09:11 +0000991 pBt = sqliteMalloc( sizeof(*pBt) );
992 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +0000993 *ppBtree = 0;
drha059ad02001-04-17 20:09:11 +0000994 return SQLITE_NOMEM;
995 }
drh6019e162001-07-02 17:51:45 +0000996 if( nCache<10 ) nCache = 10;
drha34b6762004-05-07 13:30:42 +0000997 rc = sqlite3pager_open(&pBt->pPager, zFilename, nCache, EXTRA_SIZE,
drh3aac2dd2004-04-26 14:10:20 +0000998 (flags & BTREE_OMIT_JOURNAL)==0);
drha059ad02001-04-17 20:09:11 +0000999 if( rc!=SQLITE_OK ){
drha34b6762004-05-07 13:30:42 +00001000 if( pBt->pPager ) sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001001 sqliteFree(pBt);
1002 *ppBtree = 0;
1003 return rc;
1004 }
drha34b6762004-05-07 13:30:42 +00001005 sqlite3pager_set_destructor(pBt->pPager, pageDestructor);
drha059ad02001-04-17 20:09:11 +00001006 pBt->pCursor = 0;
drha34b6762004-05-07 13:30:42 +00001007 pBt->pPage1 = 0;
1008 pBt->readOnly = sqlite3pager_isreadonly(pBt->pPager);
drh4b70f112004-05-02 21:12:19 +00001009 pBt->pageSize = SQLITE_PAGE_SIZE; /* FIX ME - read from header */
drhb6f41482004-05-14 01:58:11 +00001010 pBt->usableSize = pBt->pageSize;
drh6f11bef2004-05-13 01:12:56 +00001011 pBt->maxEmbedFrac = 64; /* FIX ME - read from header */
1012 pBt->minEmbedFrac = 32; /* FIX ME - read from header */
1013 pBt->minLeafFrac = 32; /* FIX ME - read from header */
drh3a4c1412004-05-09 20:40:11 +00001014
drha059ad02001-04-17 20:09:11 +00001015 *ppBtree = pBt;
1016 return SQLITE_OK;
1017}
1018
1019/*
1020** Close an open database and invalidate all cursors.
1021*/
drh3aac2dd2004-04-26 14:10:20 +00001022int sqlite3BtreeClose(Btree *pBt){
drha059ad02001-04-17 20:09:11 +00001023 while( pBt->pCursor ){
drh3aac2dd2004-04-26 14:10:20 +00001024 sqlite3BtreeCloseCursor(pBt->pCursor);
drha059ad02001-04-17 20:09:11 +00001025 }
drha34b6762004-05-07 13:30:42 +00001026 sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001027 sqliteFree(pBt);
1028 return SQLITE_OK;
1029}
1030
1031/*
drhda47d772002-12-02 04:25:19 +00001032** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001033**
1034** The maximum number of cache pages is set to the absolute
1035** value of mxPage. If mxPage is negative, the pager will
1036** operate asynchronously - it will not stop to do fsync()s
1037** to insure data is written to the disk surface before
1038** continuing. Transactions still work if synchronous is off,
1039** and the database cannot be corrupted if this program
1040** crashes. But if the operating system crashes or there is
1041** an abrupt power failure when synchronous is off, the database
1042** could be left in an inconsistent and unrecoverable state.
1043** Synchronous is on by default so database corruption is not
1044** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001045*/
drh23e11ca2004-05-04 17:27:28 +00001046int sqlite3BtreeSetCacheSize(Btree *pBt, int mxPage){
drha34b6762004-05-07 13:30:42 +00001047 sqlite3pager_set_cachesize(pBt->pPager, mxPage);
drhf57b14a2001-09-14 18:54:08 +00001048 return SQLITE_OK;
1049}
1050
1051/*
drh973b6e32003-02-12 14:09:42 +00001052** Change the way data is synced to disk in order to increase or decrease
1053** how well the database resists damage due to OS crashes and power
1054** failures. Level 1 is the same as asynchronous (no syncs() occur and
1055** there is a high probability of damage) Level 2 is the default. There
1056** is a very low but non-zero probability of damage. Level 3 reduces the
1057** probability of damage to near zero but with a write performance reduction.
1058*/
drh3aac2dd2004-04-26 14:10:20 +00001059int sqlite3BtreeSetSafetyLevel(Btree *pBt, int level){
drha34b6762004-05-07 13:30:42 +00001060 sqlite3pager_set_safety_level(pBt->pPager, level);
drh973b6e32003-02-12 14:09:42 +00001061 return SQLITE_OK;
1062}
1063
1064/*
drha34b6762004-05-07 13:30:42 +00001065** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001066** also acquire a readlock on that file.
1067**
1068** SQLITE_OK is returned on success. If the file is not a
1069** well-formed database file, then SQLITE_CORRUPT is returned.
1070** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
1071** is returned if we run out of memory. SQLITE_PROTOCOL is returned
1072** if there is a locking protocol violation.
1073*/
1074static int lockBtree(Btree *pBt){
1075 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001076 MemPage *pPage1;
drha34b6762004-05-07 13:30:42 +00001077 if( pBt->pPage1 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001078 rc = getPage(pBt, 1, &pPage1);
drh306dc212001-05-21 13:45:10 +00001079 if( rc!=SQLITE_OK ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00001080
drh306dc212001-05-21 13:45:10 +00001081
1082 /* Do some checking to help insure the file we opened really is
1083 ** a valid database file.
1084 */
drhb6f41482004-05-14 01:58:11 +00001085 rc = SQLITE_NOTADB;
drha34b6762004-05-07 13:30:42 +00001086 if( sqlite3pager_pagecount(pBt->pPager)>0 ){
drhb6f41482004-05-14 01:58:11 +00001087 u8 *page1 = pPage1->aData;
1088 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001089 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001090 }
drhb6f41482004-05-14 01:58:11 +00001091 if( page1[18]>1 || page1[19]>1 ){
1092 goto page1_init_failed;
1093 }
1094 pBt->pageSize = get2byte(&page1[16]);
1095 pBt->usableSize = pBt->pageSize - page1[20];
1096 if( pBt->usableSize<500 ){
1097 goto page1_init_failed;
1098 }
1099 pBt->maxEmbedFrac = page1[21];
1100 pBt->minEmbedFrac = page1[22];
1101 pBt->minLeafFrac = page1[23];
drh306dc212001-05-21 13:45:10 +00001102 }
drhb6f41482004-05-14 01:58:11 +00001103
1104 /* maxLocal is the maximum amount of payload to store locally for
1105 ** a cell. Make sure it is small enough so that at least minFanout
1106 ** cells can will fit on one page. We assume a 10-byte page header.
1107 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001108 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001109 ** 4-byte child pointer
1110 ** 9-byte nKey value
1111 ** 4-byte nData value
1112 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001113 ** So a cell consists of a 2-byte poiner, a header which is as much as
1114 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1115 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001116 */
drh43605152004-05-29 21:46:49 +00001117 pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
1118 pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
1119 pBt->maxLeaf = pBt->usableSize - 35;
1120 pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
drhb6f41482004-05-14 01:58:11 +00001121 if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
1122 goto page1_init_failed;
1123 }
1124 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE );
drh3aac2dd2004-04-26 14:10:20 +00001125 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001126 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001127
drh72f82862001-05-24 21:06:34 +00001128page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001129 releasePage(pPage1);
1130 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001131 return rc;
drh306dc212001-05-21 13:45:10 +00001132}
1133
1134/*
drhb8ca3072001-12-05 00:21:20 +00001135** If there are no outstanding cursors and we are not in the middle
1136** of a transaction but there is a read lock on the database, then
1137** this routine unrefs the first page of the database file which
1138** has the effect of releasing the read lock.
1139**
1140** If there are any outstanding cursors, this routine is a no-op.
1141**
1142** If there is a transaction in progress, this routine is a no-op.
1143*/
1144static void unlockBtreeIfUnused(Btree *pBt){
drh3aac2dd2004-04-26 14:10:20 +00001145 if( pBt->inTrans==0 && pBt->pCursor==0 && pBt->pPage1!=0 ){
1146 releasePage(pBt->pPage1);
1147 pBt->pPage1 = 0;
drhb8ca3072001-12-05 00:21:20 +00001148 pBt->inTrans = 0;
drh3aac2dd2004-04-26 14:10:20 +00001149 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001150 }
1151}
1152
1153/*
drh9e572e62004-04-23 23:43:10 +00001154** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001155** file.
drh8b2f49b2001-06-08 00:21:52 +00001156*/
1157static int newDatabase(Btree *pBt){
drh9e572e62004-04-23 23:43:10 +00001158 MemPage *pP1;
1159 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001160 int rc;
drhde647132004-05-07 17:57:49 +00001161 if( sqlite3pager_pagecount(pBt->pPager)>0 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001162 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00001163 assert( pP1!=0 );
1164 data = pP1->aData;
drha34b6762004-05-07 13:30:42 +00001165 rc = sqlite3pager_write(data);
drh8b2f49b2001-06-08 00:21:52 +00001166 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00001167 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
1168 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00001169 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00001170 data[18] = 1;
1171 data[19] = 1;
drhb6f41482004-05-14 01:58:11 +00001172 data[20] = pBt->pageSize - pBt->usableSize;
1173 data[21] = pBt->maxEmbedFrac;
1174 data[22] = pBt->minEmbedFrac;
1175 data[23] = pBt->minLeafFrac;
1176 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00001177 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drh8b2f49b2001-06-08 00:21:52 +00001178 return SQLITE_OK;
1179}
1180
1181/*
drh72f82862001-05-24 21:06:34 +00001182** Attempt to start a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00001183**
1184** A transaction must be started before attempting any changes
1185** to the database. None of the following routines will work
1186** unless a transaction is started first:
1187**
drh23e11ca2004-05-04 17:27:28 +00001188** sqlite3BtreeCreateTable()
1189** sqlite3BtreeCreateIndex()
1190** sqlite3BtreeClearTable()
1191** sqlite3BtreeDropTable()
1192** sqlite3BtreeInsert()
1193** sqlite3BtreeDelete()
1194** sqlite3BtreeUpdateMeta()
drha059ad02001-04-17 20:09:11 +00001195*/
drh3aac2dd2004-04-26 14:10:20 +00001196int sqlite3BtreeBeginTrans(Btree *pBt){
drha059ad02001-04-17 20:09:11 +00001197 int rc;
1198 if( pBt->inTrans ) return SQLITE_ERROR;
drhf74b8d92002-09-01 23:20:45 +00001199 if( pBt->readOnly ) return SQLITE_READONLY;
drh3aac2dd2004-04-26 14:10:20 +00001200 if( pBt->pPage1==0 ){
drh7e3b0a02001-04-28 16:52:40 +00001201 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +00001202 if( rc!=SQLITE_OK ){
1203 return rc;
1204 }
drha059ad02001-04-17 20:09:11 +00001205 }
drha34b6762004-05-07 13:30:42 +00001206 rc = sqlite3pager_begin(pBt->pPage1->aData);
drhf74b8d92002-09-01 23:20:45 +00001207 if( rc==SQLITE_OK ){
1208 rc = newDatabase(pBt);
drha059ad02001-04-17 20:09:11 +00001209 }
drhb8ca3072001-12-05 00:21:20 +00001210 if( rc==SQLITE_OK ){
1211 pBt->inTrans = 1;
drh3aac2dd2004-04-26 14:10:20 +00001212 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001213 }else{
1214 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001215 }
drhb8ca3072001-12-05 00:21:20 +00001216 return rc;
drha059ad02001-04-17 20:09:11 +00001217}
1218
1219/*
drh2aa679f2001-06-25 02:11:07 +00001220** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00001221**
1222** This will release the write lock on the database file. If there
1223** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00001224*/
drh3aac2dd2004-04-26 14:10:20 +00001225int sqlite3BtreeCommit(Btree *pBt){
drha059ad02001-04-17 20:09:11 +00001226 int rc;
drha34b6762004-05-07 13:30:42 +00001227 rc = pBt->readOnly ? SQLITE_OK : sqlite3pager_commit(pBt->pPager);
drh7c717f72001-06-24 20:39:41 +00001228 pBt->inTrans = 0;
drh3aac2dd2004-04-26 14:10:20 +00001229 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00001230 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001231 return rc;
1232}
1233
1234/*
drhc39e0002004-05-07 23:50:57 +00001235** Invalidate all cursors
1236*/
1237static void invalidateCursors(Btree *pBt){
1238 BtCursor *pCur;
1239 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1240 MemPage *pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00001241 if( pPage /* && !pPage->isInit */ ){
1242 pageIntegrity(pPage);
drhc39e0002004-05-07 23:50:57 +00001243 releasePage(pPage);
1244 pCur->pPage = 0;
1245 pCur->isValid = 0;
1246 pCur->status = SQLITE_ABORT;
1247 }
1248 }
1249}
1250
drhda200cc2004-05-09 11:51:38 +00001251#ifdef SQLITE_TEST
1252/*
1253** Print debugging information about all cursors to standard output.
1254*/
1255void sqlite3BtreeCursorList(Btree *pBt){
1256 BtCursor *pCur;
1257 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1258 MemPage *pPage = pCur->pPage;
1259 char *zMode = pCur->wrFlag ? "rw" : "ro";
1260 printf("CURSOR %08x rooted at %4d(%s) currently at %d.%d%s\n",
1261 (int)pCur, pCur->pgnoRoot, zMode,
1262 pPage ? pPage->pgno : 0, pCur->idx,
1263 pCur->isValid ? "" : " eof"
1264 );
1265 }
1266}
1267#endif
1268
drhc39e0002004-05-07 23:50:57 +00001269/*
drhecdc7532001-09-23 02:35:53 +00001270** Rollback the transaction in progress. All cursors will be
1271** invalided by this operation. Any attempt to use a cursor
1272** that was open at the beginning of this operation will result
1273** in an error.
drh5e00f6c2001-09-13 13:46:56 +00001274**
1275** This will release the write lock on the database file. If there
1276** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00001277*/
drh3aac2dd2004-04-26 14:10:20 +00001278int sqlite3BtreeRollback(Btree *pBt){
drha059ad02001-04-17 20:09:11 +00001279 int rc;
drh24cd67e2004-05-10 16:18:47 +00001280 MemPage *pPage1;
drh7c717f72001-06-24 20:39:41 +00001281 if( pBt->inTrans==0 ) return SQLITE_OK;
1282 pBt->inTrans = 0;
drh3aac2dd2004-04-26 14:10:20 +00001283 pBt->inStmt = 0;
drh24cd67e2004-05-10 16:18:47 +00001284 if( pBt->readOnly ){
1285 rc = SQLITE_OK;
1286 }else{
1287 rc = sqlite3pager_rollback(pBt->pPager);
1288 /* The rollback may have destroyed the pPage1->aData value. So
1289 ** call getPage() on page 1 again to make sure pPage1->aData is
1290 ** set correctly. */
1291 if( getPage(pBt, 1, &pPage1)==SQLITE_OK ){
1292 releasePage(pPage1);
1293 }
1294 }
drhc39e0002004-05-07 23:50:57 +00001295 invalidateCursors(pBt);
drh5e00f6c2001-09-13 13:46:56 +00001296 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001297 return rc;
1298}
1299
1300/*
drhab01f612004-05-22 02:55:23 +00001301** Start a statement subtransaction. The subtransaction can
1302** can be rolled back independently of the main transaction.
1303** You must start a transaction before starting a subtransaction.
1304** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00001305** commits or rolls back.
1306**
drhab01f612004-05-22 02:55:23 +00001307** Only one subtransaction may be active at a time. It is an error to try
1308** to start a new subtransaction if another subtransaction is already active.
1309**
1310** Statement subtransactions are used around individual SQL statements
1311** that are contained within a BEGIN...COMMIT block. If a constraint
1312** error occurs within the statement, the effect of that one statement
1313** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00001314*/
drh3aac2dd2004-04-26 14:10:20 +00001315int sqlite3BtreeBeginStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00001316 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001317 if( !pBt->inTrans || pBt->inStmt ){
drhf74b8d92002-09-01 23:20:45 +00001318 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh0d65dc02002-02-03 00:56:09 +00001319 }
drha34b6762004-05-07 13:30:42 +00001320 rc = pBt->readOnly ? SQLITE_OK : sqlite3pager_stmt_begin(pBt->pPager);
drh3aac2dd2004-04-26 14:10:20 +00001321 pBt->inStmt = 1;
drh663fc632002-02-02 18:49:19 +00001322 return rc;
1323}
1324
1325
1326/*
drhab01f612004-05-22 02:55:23 +00001327** Commit the statment subtransaction currently in progress. If no
1328** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00001329*/
drh3aac2dd2004-04-26 14:10:20 +00001330int sqlite3BtreeCommitStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00001331 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001332 if( pBt->inStmt && !pBt->readOnly ){
drha34b6762004-05-07 13:30:42 +00001333 rc = sqlite3pager_stmt_commit(pBt->pPager);
drh663fc632002-02-02 18:49:19 +00001334 }else{
1335 rc = SQLITE_OK;
1336 }
drh3aac2dd2004-04-26 14:10:20 +00001337 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00001338 return rc;
1339}
1340
1341/*
drhab01f612004-05-22 02:55:23 +00001342** Rollback the active statement subtransaction. If no subtransaction
1343** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00001344**
drhab01f612004-05-22 02:55:23 +00001345** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00001346** to use a cursor that was open at the beginning of this operation
1347** will result in an error.
1348*/
drh3aac2dd2004-04-26 14:10:20 +00001349int sqlite3BtreeRollbackStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00001350 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001351 if( pBt->inStmt==0 || pBt->readOnly ) return SQLITE_OK;
drha34b6762004-05-07 13:30:42 +00001352 rc = sqlite3pager_stmt_rollback(pBt->pPager);
drhc39e0002004-05-07 23:50:57 +00001353 invalidateCursors(pBt);
drh3aac2dd2004-04-26 14:10:20 +00001354 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00001355 return rc;
1356}
1357
1358/*
drh3aac2dd2004-04-26 14:10:20 +00001359** Default key comparison function to be used if no comparison function
1360** is specified on the sqlite3BtreeCursor() call.
1361*/
1362static int dfltCompare(
1363 void *NotUsed, /* User data is not used */
1364 int n1, const void *p1, /* First key to compare */
1365 int n2, const void *p2 /* Second key to compare */
1366){
1367 int c;
1368 c = memcmp(p1, p2, n1<n2 ? n1 : n2);
1369 if( c==0 ){
1370 c = n1 - n2;
1371 }
1372 return c;
1373}
1374
1375/*
drh8b2f49b2001-06-08 00:21:52 +00001376** Create a new cursor for the BTree whose root is on the page
1377** iTable. The act of acquiring a cursor gets a read lock on
1378** the database file.
drh1bee3d72001-10-15 00:44:35 +00001379**
1380** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00001381** If wrFlag==1, then the cursor can be used for reading or for
1382** writing if other conditions for writing are also met. These
1383** are the conditions that must be met in order for writing to
1384** be allowed:
drh6446c4d2001-12-15 14:22:18 +00001385**
drhf74b8d92002-09-01 23:20:45 +00001386** 1: The cursor must have been opened with wrFlag==1
1387**
1388** 2: No other cursors may be open with wrFlag==0 on the same table
1389**
1390** 3: The database must be writable (not on read-only media)
1391**
1392** 4: There must be an active transaction.
1393**
1394** Condition 2 warrants further discussion. If any cursor is opened
1395** on a table with wrFlag==0, that prevents all other cursors from
1396** writing to that table. This is a kind of "read-lock". When a cursor
1397** is opened with wrFlag==0 it is guaranteed that the table will not
1398** change as long as the cursor is open. This allows the cursor to
1399** do a sequential scan of the table without having to worry about
1400** entries being inserted or deleted during the scan. Cursors should
1401** be opened with wrFlag==0 only if this read-lock property is needed.
1402** That is to say, cursors should be opened with wrFlag==0 only if they
drh23e11ca2004-05-04 17:27:28 +00001403** intend to use the sqlite3BtreeNext() system call. All other cursors
drhf74b8d92002-09-01 23:20:45 +00001404** should be opened with wrFlag==1 even if they never really intend
1405** to write.
1406**
drh6446c4d2001-12-15 14:22:18 +00001407** No checking is done to make sure that page iTable really is the
1408** root page of a b-tree. If it is not, then the cursor acquired
1409** will not work correctly.
drh3aac2dd2004-04-26 14:10:20 +00001410**
1411** The comparison function must be logically the same for every cursor
1412** on a particular table. Changing the comparison function will result
1413** in incorrect operations. If the comparison function is NULL, a
1414** default comparison function is used. The comparison function is
1415** always ignored for INTKEY tables.
drha059ad02001-04-17 20:09:11 +00001416*/
drh3aac2dd2004-04-26 14:10:20 +00001417int sqlite3BtreeCursor(
1418 Btree *pBt, /* The btree */
1419 int iTable, /* Root page of table to open */
1420 int wrFlag, /* 1 to write. 0 read-only */
1421 int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
1422 void *pArg, /* First arg to xCompare() */
1423 BtCursor **ppCur /* Write new cursor here */
1424){
drha059ad02001-04-17 20:09:11 +00001425 int rc;
drhf74b8d92002-09-01 23:20:45 +00001426 BtCursor *pCur, *pRing;
drhecdc7532001-09-23 02:35:53 +00001427
drha0c9a112004-03-10 13:42:37 +00001428 if( pBt->readOnly && wrFlag ){
1429 *ppCur = 0;
1430 return SQLITE_READONLY;
1431 }
drh4b70f112004-05-02 21:12:19 +00001432 if( pBt->pPage1==0 ){
drha059ad02001-04-17 20:09:11 +00001433 rc = lockBtree(pBt);
1434 if( rc!=SQLITE_OK ){
1435 *ppCur = 0;
1436 return rc;
1437 }
1438 }
1439 pCur = sqliteMalloc( sizeof(*pCur) );
1440 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +00001441 rc = SQLITE_NOMEM;
1442 goto create_cursor_exception;
1443 }
drh8b2f49b2001-06-08 00:21:52 +00001444 pCur->pgnoRoot = (Pgno)iTable;
drh24cd67e2004-05-10 16:18:47 +00001445 if( iTable==1 && sqlite3pager_pagecount(pBt->pPager)==0 ){
1446 rc = SQLITE_EMPTY;
1447 goto create_cursor_exception;
1448 }
drhde647132004-05-07 17:57:49 +00001449 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
drhbd03cae2001-06-02 02:40:57 +00001450 if( rc!=SQLITE_OK ){
1451 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00001452 }
drh3aac2dd2004-04-26 14:10:20 +00001453 pCur->xCompare = xCmp ? xCmp : dfltCompare;
1454 pCur->pArg = pArg;
drh14acc042001-06-10 19:56:58 +00001455 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +00001456 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +00001457 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00001458 pCur->info.nSize = 0;
drha059ad02001-04-17 20:09:11 +00001459 pCur->pNext = pBt->pCursor;
1460 if( pCur->pNext ){
1461 pCur->pNext->pPrev = pCur;
1462 }
drh14acc042001-06-10 19:56:58 +00001463 pCur->pPrev = 0;
drhf74b8d92002-09-01 23:20:45 +00001464 pRing = pBt->pCursor;
1465 while( pRing && pRing->pgnoRoot!=pCur->pgnoRoot ){ pRing = pRing->pNext; }
1466 if( pRing ){
1467 pCur->pShared = pRing->pShared;
1468 pRing->pShared = pCur;
1469 }else{
1470 pCur->pShared = pCur;
1471 }
drha059ad02001-04-17 20:09:11 +00001472 pBt->pCursor = pCur;
drhc39e0002004-05-07 23:50:57 +00001473 pCur->isValid = 0;
1474 pCur->status = SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00001475 *ppCur = pCur;
1476 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00001477
1478create_cursor_exception:
1479 *ppCur = 0;
1480 if( pCur ){
drh3aac2dd2004-04-26 14:10:20 +00001481 releasePage(pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +00001482 sqliteFree(pCur);
1483 }
drh5e00f6c2001-09-13 13:46:56 +00001484 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00001485 return rc;
drha059ad02001-04-17 20:09:11 +00001486}
1487
drhd3d39e92004-05-20 22:16:29 +00001488/*
1489** Change the value of the comparison function used by a cursor.
1490*/
danielk1977bf3b7212004-05-18 10:06:24 +00001491void sqlite3BtreeSetCompare(
drhd3d39e92004-05-20 22:16:29 +00001492 BtCursor *pCur, /* The cursor to whose comparison function is changed */
1493 int(*xCmp)(void*,int,const void*,int,const void*), /* New comparison func */
1494 void *pArg /* First argument to xCmp() */
danielk1977bf3b7212004-05-18 10:06:24 +00001495){
1496 pCur->xCompare = xCmp ? xCmp : dfltCompare;
1497 pCur->pArg = pArg;
1498}
1499
drha059ad02001-04-17 20:09:11 +00001500/*
drh5e00f6c2001-09-13 13:46:56 +00001501** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00001502** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00001503*/
drh3aac2dd2004-04-26 14:10:20 +00001504int sqlite3BtreeCloseCursor(BtCursor *pCur){
drha059ad02001-04-17 20:09:11 +00001505 Btree *pBt = pCur->pBt;
drha059ad02001-04-17 20:09:11 +00001506 if( pCur->pPrev ){
1507 pCur->pPrev->pNext = pCur->pNext;
1508 }else{
1509 pBt->pCursor = pCur->pNext;
1510 }
1511 if( pCur->pNext ){
1512 pCur->pNext->pPrev = pCur->pPrev;
1513 }
drh3aac2dd2004-04-26 14:10:20 +00001514 releasePage(pCur->pPage);
drhf74b8d92002-09-01 23:20:45 +00001515 if( pCur->pShared!=pCur ){
1516 BtCursor *pRing = pCur->pShared;
1517 while( pRing->pShared!=pCur ){ pRing = pRing->pShared; }
1518 pRing->pShared = pCur->pShared;
1519 }
drh5e00f6c2001-09-13 13:46:56 +00001520 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001521 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +00001522 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00001523}
1524
drh7e3b0a02001-04-28 16:52:40 +00001525/*
drh5e2f8b92001-05-28 00:41:15 +00001526** Make a temporary cursor by filling in the fields of pTempCur.
1527** The temporary cursor is not on the cursor list for the Btree.
1528*/
drh14acc042001-06-10 19:56:58 +00001529static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00001530 memcpy(pTempCur, pCur, sizeof(*pCur));
1531 pTempCur->pNext = 0;
1532 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00001533 if( pTempCur->pPage ){
drha34b6762004-05-07 13:30:42 +00001534 sqlite3pager_ref(pTempCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00001535 }
drh5e2f8b92001-05-28 00:41:15 +00001536}
1537
1538/*
drhbd03cae2001-06-02 02:40:57 +00001539** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00001540** function above.
1541*/
drh14acc042001-06-10 19:56:58 +00001542static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00001543 if( pCur->pPage ){
drha34b6762004-05-07 13:30:42 +00001544 sqlite3pager_unref(pCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00001545 }
drh5e2f8b92001-05-28 00:41:15 +00001546}
1547
1548/*
drh9188b382004-05-14 21:12:22 +00001549** Make sure the BtCursor.info field of the given cursor is valid.
drhab01f612004-05-22 02:55:23 +00001550** If it is not already valid, call parseCell() to fill it in.
1551**
1552** BtCursor.info is a cache of the information in the current cell.
1553** Using this cache reduces the number of calls to parseCell().
drh9188b382004-05-14 21:12:22 +00001554*/
1555static void getCellInfo(BtCursor *pCur){
drh271efa52004-05-30 19:19:05 +00001556 if( pCur->info.nSize==0 ){
drh3a41a3f2004-05-30 02:14:17 +00001557 parseCell(pCur->pPage, pCur->idx, &pCur->info);
drh9188b382004-05-14 21:12:22 +00001558 }else{
1559#ifndef NDEBUG
1560 CellInfo info;
drh3a41a3f2004-05-30 02:14:17 +00001561 parseCell(pCur->pPage, pCur->idx, &info);
drh9188b382004-05-14 21:12:22 +00001562 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
1563#endif
1564 }
1565}
1566
1567/*
drh3aac2dd2004-04-26 14:10:20 +00001568** Set *pSize to the size of the buffer needed to hold the value of
1569** the key for the current entry. If the cursor is not pointing
1570** to a valid entry, *pSize is set to 0.
1571**
drh4b70f112004-05-02 21:12:19 +00001572** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00001573** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00001574*/
drh4a1c3802004-05-12 15:15:47 +00001575int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drhc39e0002004-05-07 23:50:57 +00001576 if( !pCur->isValid ){
drh72f82862001-05-24 21:06:34 +00001577 *pSize = 0;
1578 }else{
drh9188b382004-05-14 21:12:22 +00001579 getCellInfo(pCur);
1580 *pSize = pCur->info.nKey;
drh72f82862001-05-24 21:06:34 +00001581 }
1582 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00001583}
drh2af926b2001-05-15 00:39:25 +00001584
drh72f82862001-05-24 21:06:34 +00001585/*
drh0e1c19e2004-05-11 00:58:56 +00001586** Set *pSize to the number of bytes of data in the entry the
1587** cursor currently points to. Always return SQLITE_OK.
1588** Failure is not possible. If the cursor is not currently
1589** pointing to an entry (which can happen, for example, if
1590** the database is empty) then *pSize is set to 0.
1591*/
1592int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drh0e1c19e2004-05-11 00:58:56 +00001593 if( !pCur->isValid ){
danielk197796fc5fe2004-05-13 11:34:16 +00001594 /* Not pointing at a valid entry - set *pSize to 0. */
drh0e1c19e2004-05-11 00:58:56 +00001595 *pSize = 0;
1596 }else{
drh9188b382004-05-14 21:12:22 +00001597 getCellInfo(pCur);
1598 *pSize = pCur->info.nData;
drh0e1c19e2004-05-11 00:58:56 +00001599 }
1600 return SQLITE_OK;
1601}
1602
1603/*
drh72f82862001-05-24 21:06:34 +00001604** Read payload information from the entry that the pCur cursor is
1605** pointing to. Begin reading the payload at "offset" and read
1606** a total of "amt" bytes. Put the result in zBuf.
1607**
1608** This routine does not make a distinction between key and data.
drhab01f612004-05-22 02:55:23 +00001609** It just reads bytes from the payload area. Data might appear
1610** on the main page or be scattered out on multiple overflow pages.
drh72f82862001-05-24 21:06:34 +00001611*/
drh3aac2dd2004-04-26 14:10:20 +00001612static int getPayload(
1613 BtCursor *pCur, /* Cursor pointing to entry to read from */
1614 int offset, /* Begin reading this far into payload */
1615 int amt, /* Read this many bytes */
1616 unsigned char *pBuf, /* Write the bytes into this buffer */
1617 int skipKey /* offset begins at data if this is true */
1618){
1619 unsigned char *aPayload;
drh2af926b2001-05-15 00:39:25 +00001620 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +00001621 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001622 MemPage *pPage;
1623 Btree *pBt;
drh6f11bef2004-05-13 01:12:56 +00001624 int ovflSize;
drhfa1a98a2004-05-14 19:08:17 +00001625 u32 nKey;
drh3aac2dd2004-04-26 14:10:20 +00001626
drh72f82862001-05-24 21:06:34 +00001627 assert( pCur!=0 && pCur->pPage!=0 );
drhc39e0002004-05-07 23:50:57 +00001628 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00001629 pBt = pCur->pBt;
1630 pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00001631 pageIntegrity(pPage);
drh3aac2dd2004-04-26 14:10:20 +00001632 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00001633 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00001634 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00001635 aPayload += pCur->info.nHeader;
drh3aac2dd2004-04-26 14:10:20 +00001636 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00001637 nKey = 0;
1638 }else{
1639 nKey = pCur->info.nKey;
drh3aac2dd2004-04-26 14:10:20 +00001640 }
1641 assert( offset>=0 );
1642 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00001643 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00001644 }
drhfa1a98a2004-05-14 19:08:17 +00001645 if( offset+amt > nKey+pCur->info.nData ){
drha34b6762004-05-07 13:30:42 +00001646 return SQLITE_ERROR;
drh3aac2dd2004-04-26 14:10:20 +00001647 }
drhfa1a98a2004-05-14 19:08:17 +00001648 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00001649 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00001650 if( a+offset>pCur->info.nLocal ){
1651 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00001652 }
drha34b6762004-05-07 13:30:42 +00001653 memcpy(pBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +00001654 if( a==amt ){
1655 return SQLITE_OK;
1656 }
drh2aa679f2001-06-25 02:11:07 +00001657 offset = 0;
drha34b6762004-05-07 13:30:42 +00001658 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00001659 amt -= a;
drhdd793422001-06-28 01:54:48 +00001660 }else{
drhfa1a98a2004-05-14 19:08:17 +00001661 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00001662 }
1663 if( amt>0 ){
drhfa1a98a2004-05-14 19:08:17 +00001664 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
drh2af926b2001-05-15 00:39:25 +00001665 }
drhb6f41482004-05-14 01:58:11 +00001666 ovflSize = pBt->usableSize - 4;
drh2af926b2001-05-15 00:39:25 +00001667 while( amt>0 && nextPage ){
drha34b6762004-05-07 13:30:42 +00001668 rc = sqlite3pager_get(pBt->pPager, nextPage, (void**)&aPayload);
drh2af926b2001-05-15 00:39:25 +00001669 if( rc!=0 ){
1670 return rc;
1671 }
drha34b6762004-05-07 13:30:42 +00001672 nextPage = get4byte(aPayload);
drh3aac2dd2004-04-26 14:10:20 +00001673 if( offset<ovflSize ){
drh2af926b2001-05-15 00:39:25 +00001674 int a = amt;
drh3aac2dd2004-04-26 14:10:20 +00001675 if( a + offset > ovflSize ){
1676 a = ovflSize - offset;
drh2af926b2001-05-15 00:39:25 +00001677 }
drh9b171272004-05-08 02:03:22 +00001678 memcpy(pBuf, &aPayload[offset+4], a);
drh2aa679f2001-06-25 02:11:07 +00001679 offset = 0;
drh2af926b2001-05-15 00:39:25 +00001680 amt -= a;
drha34b6762004-05-07 13:30:42 +00001681 pBuf += a;
drh2aa679f2001-06-25 02:11:07 +00001682 }else{
drh3aac2dd2004-04-26 14:10:20 +00001683 offset -= ovflSize;
drh2af926b2001-05-15 00:39:25 +00001684 }
drha34b6762004-05-07 13:30:42 +00001685 sqlite3pager_unref(aPayload);
drh2af926b2001-05-15 00:39:25 +00001686 }
drha7fcb052001-12-14 15:09:55 +00001687 if( amt>0 ){
1688 return SQLITE_CORRUPT;
1689 }
1690 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00001691}
1692
drh72f82862001-05-24 21:06:34 +00001693/*
drh3aac2dd2004-04-26 14:10:20 +00001694** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00001695** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00001696** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00001697**
drh3aac2dd2004-04-26 14:10:20 +00001698** Return SQLITE_OK on success or an error code if anything goes
1699** wrong. An error is returned if "offset+amt" is larger than
1700** the available payload.
drh72f82862001-05-24 21:06:34 +00001701*/
drha34b6762004-05-07 13:30:42 +00001702int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drh8c1238a2003-01-02 14:43:55 +00001703 assert( amt>=0 );
1704 assert( offset>=0 );
drhc39e0002004-05-07 23:50:57 +00001705 if( pCur->isValid==0 ){
1706 return pCur->status;
drh3aac2dd2004-04-26 14:10:20 +00001707 }
drhc39e0002004-05-07 23:50:57 +00001708 assert( pCur->pPage!=0 );
1709 assert( pCur->pPage->intKey==0 );
1710 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh3aac2dd2004-04-26 14:10:20 +00001711 return getPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
1712}
1713
1714/*
drh3aac2dd2004-04-26 14:10:20 +00001715** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00001716** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00001717** begins at "offset".
1718**
1719** Return SQLITE_OK on success or an error code if anything goes
1720** wrong. An error is returned if "offset+amt" is larger than
1721** the available payload.
drh72f82862001-05-24 21:06:34 +00001722*/
drh3aac2dd2004-04-26 14:10:20 +00001723int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhc39e0002004-05-07 23:50:57 +00001724 if( !pCur->isValid ){
1725 return pCur->status ? pCur->status : SQLITE_INTERNAL;
1726 }
drh8c1238a2003-01-02 14:43:55 +00001727 assert( amt>=0 );
1728 assert( offset>=0 );
1729 assert( pCur->pPage!=0 );
drhc39e0002004-05-07 23:50:57 +00001730 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh3aac2dd2004-04-26 14:10:20 +00001731 return getPayload(pCur, offset, amt, pBuf, 1);
drh2af926b2001-05-15 00:39:25 +00001732}
1733
drh72f82862001-05-24 21:06:34 +00001734/*
drh0e1c19e2004-05-11 00:58:56 +00001735** Return a pointer to payload information from the entry that the
1736** pCur cursor is pointing to. The pointer is to the beginning of
1737** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00001738** skipKey==1. The number of bytes of available key/data is written
1739** into *pAmt. If *pAmt==0, then the value returned will not be
1740** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00001741**
1742** This routine is an optimization. It is common for the entire key
1743** and data to fit on the local page and for there to be no overflow
1744** pages. When that is so, this routine can be used to access the
1745** key and data without making a copy. If the key and/or data spills
1746** onto overflow pages, then getPayload() must be used to reassembly
1747** the key/data and copy it into a preallocated buffer.
1748**
1749** The pointer returned by this routine looks directly into the cached
1750** page of the database. The data might change or move the next time
1751** any btree routine is called.
1752*/
1753static const unsigned char *fetchPayload(
1754 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00001755 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00001756 int skipKey /* read beginning at data if this is true */
1757){
1758 unsigned char *aPayload;
1759 MemPage *pPage;
1760 Btree *pBt;
drhfa1a98a2004-05-14 19:08:17 +00001761 u32 nKey;
1762 int nLocal;
drh0e1c19e2004-05-11 00:58:56 +00001763
1764 assert( pCur!=0 && pCur->pPage!=0 );
1765 assert( pCur->isValid );
1766 pBt = pCur->pBt;
1767 pPage = pCur->pPage;
1768 pageIntegrity(pPage);
1769 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00001770 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00001771 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00001772 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00001773 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00001774 nKey = 0;
1775 }else{
1776 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00001777 }
drh0e1c19e2004-05-11 00:58:56 +00001778 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00001779 aPayload += nKey;
1780 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00001781 }else{
drhfa1a98a2004-05-14 19:08:17 +00001782 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00001783 if( nLocal>nKey ){
1784 nLocal = nKey;
1785 }
drh0e1c19e2004-05-11 00:58:56 +00001786 }
drhe51c44f2004-05-30 20:46:09 +00001787 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00001788 return aPayload;
1789}
1790
1791
1792/*
drhe51c44f2004-05-30 20:46:09 +00001793** For the entry that cursor pCur is point to, return as
1794** many bytes of the key or data as are available on the local
1795** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00001796**
1797** The pointer returned is ephemeral. The key/data may move
1798** or be destroyed on the next call to any Btree routine.
1799**
1800** These routines is used to get quick access to key and data
1801** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00001802*/
drhe51c44f2004-05-30 20:46:09 +00001803const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
1804 return (const void*)fetchPayload(pCur, pAmt, 0);
drh0e1c19e2004-05-11 00:58:56 +00001805}
drhe51c44f2004-05-30 20:46:09 +00001806const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
1807 return (const void*)fetchPayload(pCur, pAmt, 1);
drh0e1c19e2004-05-11 00:58:56 +00001808}
1809
1810
1811/*
drh8178a752003-01-05 21:41:40 +00001812** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00001813** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00001814*/
drh3aac2dd2004-04-26 14:10:20 +00001815static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00001816 int rc;
1817 MemPage *pNewPage;
drh3aac2dd2004-04-26 14:10:20 +00001818 MemPage *pOldPage;
drh0d316a42002-08-11 20:10:47 +00001819 Btree *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00001820
drhc39e0002004-05-07 23:50:57 +00001821 assert( pCur->isValid );
drhde647132004-05-07 17:57:49 +00001822 rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00001823 if( rc ) return rc;
drhda200cc2004-05-09 11:51:38 +00001824 pageIntegrity(pNewPage);
drh428ae8c2003-01-04 16:48:09 +00001825 pNewPage->idxParent = pCur->idx;
drh3aac2dd2004-04-26 14:10:20 +00001826 pOldPage = pCur->pPage;
1827 pOldPage->idxShift = 0;
1828 releasePage(pOldPage);
drh72f82862001-05-24 21:06:34 +00001829 pCur->pPage = pNewPage;
1830 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00001831 pCur->info.nSize = 0;
drh4be295b2003-12-16 03:44:47 +00001832 if( pNewPage->nCell<1 ){
1833 return SQLITE_CORRUPT;
1834 }
drh72f82862001-05-24 21:06:34 +00001835 return SQLITE_OK;
1836}
1837
1838/*
drh8856d6a2004-04-29 14:42:46 +00001839** Return true if the page is the virtual root of its table.
1840**
1841** The virtual root page is the root page for most tables. But
1842** for the table rooted on page 1, sometime the real root page
1843** is empty except for the right-pointer. In such cases the
1844** virtual root page is the page that the right-pointer of page
1845** 1 is pointing to.
1846*/
1847static int isRootPage(MemPage *pPage){
1848 MemPage *pParent = pPage->pParent;
drhda200cc2004-05-09 11:51:38 +00001849 if( pParent==0 ) return 1;
1850 if( pParent->pgno>1 ) return 0;
1851 if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
drh8856d6a2004-04-29 14:42:46 +00001852 return 0;
1853}
1854
1855/*
drh5e2f8b92001-05-28 00:41:15 +00001856** Move the cursor up to the parent page.
1857**
1858** pCur->idx is set to the cell index that contains the pointer
1859** to the page we are coming from. If we are coming from the
1860** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00001861** the largest cell index.
drh72f82862001-05-24 21:06:34 +00001862*/
drh8178a752003-01-05 21:41:40 +00001863static void moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001864 Pgno oldPgno;
1865 MemPage *pParent;
drh8178a752003-01-05 21:41:40 +00001866 MemPage *pPage;
drh428ae8c2003-01-04 16:48:09 +00001867 int idxParent;
drh3aac2dd2004-04-26 14:10:20 +00001868
drhc39e0002004-05-07 23:50:57 +00001869 assert( pCur->isValid );
drh8178a752003-01-05 21:41:40 +00001870 pPage = pCur->pPage;
1871 assert( pPage!=0 );
drh8856d6a2004-04-29 14:42:46 +00001872 assert( !isRootPage(pPage) );
drhda200cc2004-05-09 11:51:38 +00001873 pageIntegrity(pPage);
drh8178a752003-01-05 21:41:40 +00001874 pParent = pPage->pParent;
1875 assert( pParent!=0 );
drhda200cc2004-05-09 11:51:38 +00001876 pageIntegrity(pParent);
drh8178a752003-01-05 21:41:40 +00001877 idxParent = pPage->idxParent;
drha34b6762004-05-07 13:30:42 +00001878 sqlite3pager_ref(pParent->aData);
drh3aac2dd2004-04-26 14:10:20 +00001879 oldPgno = pPage->pgno;
1880 releasePage(pPage);
drh72f82862001-05-24 21:06:34 +00001881 pCur->pPage = pParent;
drh271efa52004-05-30 19:19:05 +00001882 pCur->info.nSize = 0;
drh428ae8c2003-01-04 16:48:09 +00001883 assert( pParent->idxShift==0 );
drh43605152004-05-29 21:46:49 +00001884 pCur->idx = idxParent;
drh72f82862001-05-24 21:06:34 +00001885}
1886
1887/*
1888** Move the cursor to the root page
1889*/
drh5e2f8b92001-05-28 00:41:15 +00001890static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00001891 MemPage *pRoot;
drhbd03cae2001-06-02 02:40:57 +00001892 int rc;
drh0d316a42002-08-11 20:10:47 +00001893 Btree *pBt = pCur->pBt;
drhbd03cae2001-06-02 02:40:57 +00001894
drhde647132004-05-07 17:57:49 +00001895 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0);
drhc39e0002004-05-07 23:50:57 +00001896 if( rc ){
1897 pCur->isValid = 0;
1898 return rc;
1899 }
drh3aac2dd2004-04-26 14:10:20 +00001900 releasePage(pCur->pPage);
drhda200cc2004-05-09 11:51:38 +00001901 pageIntegrity(pRoot);
drh3aac2dd2004-04-26 14:10:20 +00001902 pCur->pPage = pRoot;
drh72f82862001-05-24 21:06:34 +00001903 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00001904 pCur->info.nSize = 0;
drh8856d6a2004-04-29 14:42:46 +00001905 if( pRoot->nCell==0 && !pRoot->leaf ){
1906 Pgno subpage;
1907 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00001908 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00001909 assert( subpage>0 );
drh3644f082004-05-10 18:45:09 +00001910 pCur->isValid = 1;
drh4b70f112004-05-02 21:12:19 +00001911 rc = moveToChild(pCur, subpage);
drh8856d6a2004-04-29 14:42:46 +00001912 }
drhc39e0002004-05-07 23:50:57 +00001913 pCur->isValid = pCur->pPage->nCell>0;
drh8856d6a2004-04-29 14:42:46 +00001914 return rc;
drh72f82862001-05-24 21:06:34 +00001915}
drh2af926b2001-05-15 00:39:25 +00001916
drh5e2f8b92001-05-28 00:41:15 +00001917/*
1918** Move the cursor down to the left-most leaf entry beneath the
1919** entry to which it is currently pointing.
1920*/
1921static int moveToLeftmost(BtCursor *pCur){
1922 Pgno pgno;
1923 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001924 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00001925
drhc39e0002004-05-07 23:50:57 +00001926 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00001927 while( !(pPage = pCur->pPage)->leaf ){
drha34b6762004-05-07 13:30:42 +00001928 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00001929 pgno = get4byte(findCell(pPage, pCur->idx));
drh8178a752003-01-05 21:41:40 +00001930 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00001931 if( rc ) return rc;
1932 }
1933 return SQLITE_OK;
1934}
1935
drh2dcc9aa2002-12-04 13:40:25 +00001936/*
1937** Move the cursor down to the right-most leaf entry beneath the
1938** page to which it is currently pointing. Notice the difference
1939** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
1940** finds the left-most entry beneath the *entry* whereas moveToRightmost()
1941** finds the right-most entry beneath the *page*.
1942*/
1943static int moveToRightmost(BtCursor *pCur){
1944 Pgno pgno;
1945 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001946 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00001947
drhc39e0002004-05-07 23:50:57 +00001948 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00001949 while( !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00001950 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh3aac2dd2004-04-26 14:10:20 +00001951 pCur->idx = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00001952 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00001953 if( rc ) return rc;
1954 }
drh3aac2dd2004-04-26 14:10:20 +00001955 pCur->idx = pPage->nCell - 1;
drh271efa52004-05-30 19:19:05 +00001956 pCur->info.nSize = 0;
drh2dcc9aa2002-12-04 13:40:25 +00001957 return SQLITE_OK;
1958}
1959
drh5e00f6c2001-09-13 13:46:56 +00001960/* Move the cursor to the first entry in the table. Return SQLITE_OK
1961** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00001962** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00001963*/
drh3aac2dd2004-04-26 14:10:20 +00001964int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00001965 int rc;
drhc39e0002004-05-07 23:50:57 +00001966 if( pCur->status ){
1967 return pCur->status;
1968 }
drh5e00f6c2001-09-13 13:46:56 +00001969 rc = moveToRoot(pCur);
1970 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00001971 if( pCur->isValid==0 ){
1972 assert( pCur->pPage->nCell==0 );
drh5e00f6c2001-09-13 13:46:56 +00001973 *pRes = 1;
1974 return SQLITE_OK;
1975 }
drhc39e0002004-05-07 23:50:57 +00001976 assert( pCur->pPage->nCell>0 );
drh5e00f6c2001-09-13 13:46:56 +00001977 *pRes = 0;
1978 rc = moveToLeftmost(pCur);
1979 return rc;
1980}
drh5e2f8b92001-05-28 00:41:15 +00001981
drh9562b552002-02-19 15:00:07 +00001982/* Move the cursor to the last entry in the table. Return SQLITE_OK
1983** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00001984** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00001985*/
drh3aac2dd2004-04-26 14:10:20 +00001986int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00001987 int rc;
drhc39e0002004-05-07 23:50:57 +00001988 if( pCur->status ){
1989 return pCur->status;
1990 }
drh9562b552002-02-19 15:00:07 +00001991 rc = moveToRoot(pCur);
1992 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00001993 if( pCur->isValid==0 ){
1994 assert( pCur->pPage->nCell==0 );
drh9562b552002-02-19 15:00:07 +00001995 *pRes = 1;
1996 return SQLITE_OK;
1997 }
drhc39e0002004-05-07 23:50:57 +00001998 assert( pCur->isValid );
drh9562b552002-02-19 15:00:07 +00001999 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002000 rc = moveToRightmost(pCur);
drh9562b552002-02-19 15:00:07 +00002001 return rc;
2002}
2003
drh3aac2dd2004-04-26 14:10:20 +00002004/* Move the cursor so that it points to an entry near pKey/nKey.
drh72f82862001-05-24 21:06:34 +00002005** Return a success code.
2006**
drh3aac2dd2004-04-26 14:10:20 +00002007** For INTKEY tables, only the nKey parameter is used. pKey is
2008** ignored. For other tables, nKey is the number of bytes of data
2009** in nKey. The comparison function specified when the cursor was
2010** created is used to compare keys.
2011**
drh5e2f8b92001-05-28 00:41:15 +00002012** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00002013** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00002014** were present. The cursor might point to an entry that comes
2015** before or after the key.
2016**
drhbd03cae2001-06-02 02:40:57 +00002017** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00002018** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00002019** this value is as follows:
2020**
2021** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00002022** is smaller than pKey or if the table is empty
2023** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00002024**
2025** *pRes==0 The cursor is left pointing at an entry that
2026** exactly matches pKey.
2027**
2028** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00002029** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00002030*/
drh4a1c3802004-05-12 15:15:47 +00002031int sqlite3BtreeMoveto(BtCursor *pCur, const void *pKey, i64 nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00002032 int rc;
drhc39e0002004-05-07 23:50:57 +00002033
2034 if( pCur->status ){
2035 return pCur->status;
2036 }
drh5e2f8b92001-05-28 00:41:15 +00002037 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00002038 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00002039 assert( pCur->pPage );
2040 assert( pCur->pPage->isInit );
2041 if( pCur->isValid==0 ){
drhf328bc82004-05-10 23:29:49 +00002042 *pRes = -1;
drhc39e0002004-05-07 23:50:57 +00002043 assert( pCur->pPage->nCell==0 );
2044 return SQLITE_OK;
2045 }
drh72f82862001-05-24 21:06:34 +00002046 for(;;){
2047 int lwr, upr;
2048 Pgno chldPg;
2049 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00002050 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00002051 lwr = 0;
2052 upr = pPage->nCell-1;
drhda200cc2004-05-09 11:51:38 +00002053 pageIntegrity(pPage);
drh72f82862001-05-24 21:06:34 +00002054 while( lwr<=upr ){
drh0e1c19e2004-05-11 00:58:56 +00002055 const void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00002056 i64 nCellKey;
drh72f82862001-05-24 21:06:34 +00002057 pCur->idx = (lwr+upr)/2;
drh271efa52004-05-30 19:19:05 +00002058 pCur->info.nSize = 0;
drhde647132004-05-07 17:57:49 +00002059 sqlite3BtreeKeySize(pCur, &nCellKey);
drh3aac2dd2004-04-26 14:10:20 +00002060 if( pPage->intKey ){
2061 if( nCellKey<nKey ){
2062 c = -1;
2063 }else if( nCellKey>nKey ){
2064 c = +1;
2065 }else{
2066 c = 0;
2067 }
drh3aac2dd2004-04-26 14:10:20 +00002068 }else{
drhe51c44f2004-05-30 20:46:09 +00002069 int available;
2070 pCellKey = fetchPayload(pCur, &available, 0);
2071 if( available>=nCellKey ){
2072 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
2073 }else{
2074 pCellKey = sqliteMallocRaw( nCellKey );
2075 if( pCellKey==0 ) return SQLITE_NOMEM;
2076 rc = sqlite3BtreeKey(pCur, 0, nCellKey, pCellKey);
2077 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
2078 sqliteFree(pCellKey);
2079 if( rc ) return rc;
2080 }
drh3aac2dd2004-04-26 14:10:20 +00002081 }
drh72f82862001-05-24 21:06:34 +00002082 if( c==0 ){
drh8b18dd42004-05-12 19:18:15 +00002083 if( pPage->leafData && !pPage->leaf ){
drhfc70e6f2004-05-12 21:11:27 +00002084 lwr = pCur->idx;
2085 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00002086 break;
2087 }else{
drh8b18dd42004-05-12 19:18:15 +00002088 if( pRes ) *pRes = 0;
2089 return SQLITE_OK;
2090 }
drh72f82862001-05-24 21:06:34 +00002091 }
2092 if( c<0 ){
2093 lwr = pCur->idx+1;
2094 }else{
2095 upr = pCur->idx-1;
2096 }
2097 }
2098 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00002099 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00002100 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00002101 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00002102 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00002103 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00002104 }else{
drh43605152004-05-29 21:46:49 +00002105 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00002106 }
2107 if( chldPg==0 ){
drhc39e0002004-05-07 23:50:57 +00002108 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00002109 if( pRes ) *pRes = c;
2110 return SQLITE_OK;
2111 }
drh428ae8c2003-01-04 16:48:09 +00002112 pCur->idx = lwr;
drh271efa52004-05-30 19:19:05 +00002113 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00002114 rc = moveToChild(pCur, chldPg);
drhc39e0002004-05-07 23:50:57 +00002115 if( rc ){
2116 return rc;
2117 }
drh72f82862001-05-24 21:06:34 +00002118 }
drhbd03cae2001-06-02 02:40:57 +00002119 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00002120}
2121
2122/*
drhc39e0002004-05-07 23:50:57 +00002123** Return TRUE if the cursor is not pointing at an entry of the table.
2124**
2125** TRUE will be returned after a call to sqlite3BtreeNext() moves
2126** past the last entry in the table or sqlite3BtreePrev() moves past
2127** the first entry. TRUE is also returned if the table is empty.
2128*/
2129int sqlite3BtreeEof(BtCursor *pCur){
2130 return pCur->isValid==0;
2131}
2132
2133/*
drhbd03cae2001-06-02 02:40:57 +00002134** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00002135** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00002136** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00002137** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00002138*/
drh3aac2dd2004-04-26 14:10:20 +00002139int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00002140 int rc;
drh8178a752003-01-05 21:41:40 +00002141 MemPage *pPage = pCur->pPage;
drh8b18dd42004-05-12 19:18:15 +00002142
drh8c1238a2003-01-02 14:43:55 +00002143 assert( pRes!=0 );
drhc39e0002004-05-07 23:50:57 +00002144 if( pCur->isValid==0 ){
drh8c1238a2003-01-02 14:43:55 +00002145 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00002146 return SQLITE_OK;
drhecdc7532001-09-23 02:35:53 +00002147 }
drh8178a752003-01-05 21:41:40 +00002148 assert( pPage->isInit );
drh8178a752003-01-05 21:41:40 +00002149 assert( pCur->idx<pPage->nCell );
drh72f82862001-05-24 21:06:34 +00002150 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00002151 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00002152 if( pCur->idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00002153 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00002154 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00002155 if( rc ) return rc;
2156 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00002157 *pRes = 0;
2158 return rc;
drh72f82862001-05-24 21:06:34 +00002159 }
drh5e2f8b92001-05-28 00:41:15 +00002160 do{
drh8856d6a2004-04-29 14:42:46 +00002161 if( isRootPage(pPage) ){
drh8c1238a2003-01-02 14:43:55 +00002162 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00002163 pCur->isValid = 0;
drh5e2f8b92001-05-28 00:41:15 +00002164 return SQLITE_OK;
2165 }
drh8178a752003-01-05 21:41:40 +00002166 moveToParent(pCur);
2167 pPage = pCur->pPage;
2168 }while( pCur->idx>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00002169 *pRes = 0;
drh8b18dd42004-05-12 19:18:15 +00002170 if( pPage->leafData ){
2171 rc = sqlite3BtreeNext(pCur, pRes);
2172 }else{
2173 rc = SQLITE_OK;
2174 }
2175 return rc;
drh8178a752003-01-05 21:41:40 +00002176 }
2177 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00002178 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00002179 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00002180 }
drh5e2f8b92001-05-28 00:41:15 +00002181 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00002182 return rc;
drh72f82862001-05-24 21:06:34 +00002183}
2184
drh3b7511c2001-05-26 13:15:44 +00002185/*
drh2dcc9aa2002-12-04 13:40:25 +00002186** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00002187** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00002188** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00002189** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00002190*/
drh3aac2dd2004-04-26 14:10:20 +00002191int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00002192 int rc;
2193 Pgno pgno;
drh8178a752003-01-05 21:41:40 +00002194 MemPage *pPage;
drhc39e0002004-05-07 23:50:57 +00002195 if( pCur->isValid==0 ){
2196 *pRes = 1;
2197 return SQLITE_OK;
2198 }
drh8178a752003-01-05 21:41:40 +00002199 pPage = pCur->pPage;
drh8178a752003-01-05 21:41:40 +00002200 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00002201 assert( pCur->idx>=0 );
drha34b6762004-05-07 13:30:42 +00002202 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00002203 pgno = get4byte( findCell(pPage, pCur->idx) );
drh8178a752003-01-05 21:41:40 +00002204 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00002205 if( rc ) return rc;
2206 rc = moveToRightmost(pCur);
2207 }else{
2208 while( pCur->idx==0 ){
drh8856d6a2004-04-29 14:42:46 +00002209 if( isRootPage(pPage) ){
drhc39e0002004-05-07 23:50:57 +00002210 pCur->isValid = 0;
2211 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00002212 return SQLITE_OK;
2213 }
drh8178a752003-01-05 21:41:40 +00002214 moveToParent(pCur);
2215 pPage = pCur->pPage;
drh2dcc9aa2002-12-04 13:40:25 +00002216 }
2217 pCur->idx--;
drh271efa52004-05-30 19:19:05 +00002218 pCur->info.nSize = 0;
drh8b18dd42004-05-12 19:18:15 +00002219 if( pPage->leafData ){
2220 rc = sqlite3BtreePrevious(pCur, pRes);
2221 }else{
2222 rc = SQLITE_OK;
2223 }
drh2dcc9aa2002-12-04 13:40:25 +00002224 }
drh8178a752003-01-05 21:41:40 +00002225 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002226 return rc;
2227}
2228
2229/*
drh3a4c1412004-05-09 20:40:11 +00002230** The TRACE macro will print high-level status information about the
2231** btree operation when the global variable sqlite3_btree_trace is
2232** enabled.
2233*/
2234#if SQLITE_TEST
2235# define TRACE(X) if( sqlite3_btree_trace ){ printf X; fflush(stdout); }
2236#else
2237# define TRACE(X)
2238#endif
2239int sqlite3_btree_trace=0; /* True to enable tracing */
2240
2241/*
drh3b7511c2001-05-26 13:15:44 +00002242** Allocate a new page from the database file.
2243**
drha34b6762004-05-07 13:30:42 +00002244** The new page is marked as dirty. (In other words, sqlite3pager_write()
drh3b7511c2001-05-26 13:15:44 +00002245** has already been called on the new page.) The new page has also
2246** been referenced and the calling routine is responsible for calling
drha34b6762004-05-07 13:30:42 +00002247** sqlite3pager_unref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00002248**
2249** SQLITE_OK is returned on success. Any other return value indicates
2250** an error. *ppPage and *pPgno are undefined in the event of an error.
drha34b6762004-05-07 13:30:42 +00002251** Do not invoke sqlite3pager_unref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00002252**
drh199e3cf2002-07-18 11:01:47 +00002253** If the "nearby" parameter is not 0, then a (feeble) effort is made to
2254** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00002255** attempt to keep related pages close to each other in the database file,
2256** which in turn can make database access faster.
drh3b7511c2001-05-26 13:15:44 +00002257*/
drh199e3cf2002-07-18 11:01:47 +00002258static int allocatePage(Btree *pBt, MemPage **ppPage, Pgno *pPgno, Pgno nearby){
drh3aac2dd2004-04-26 14:10:20 +00002259 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00002260 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002261 int n; /* Number of pages on the freelist */
2262 int k; /* Number of leaves on the trunk of the freelist */
drh30e58752002-03-02 20:41:57 +00002263
drh3aac2dd2004-04-26 14:10:20 +00002264 pPage1 = pBt->pPage1;
2265 n = get4byte(&pPage1->aData[36]);
2266 if( n>0 ){
drh91025292004-05-03 19:49:32 +00002267 /* There are pages on the freelist. Reuse one of those pages. */
drh3aac2dd2004-04-26 14:10:20 +00002268 MemPage *pTrunk;
drha34b6762004-05-07 13:30:42 +00002269 rc = sqlite3pager_write(pPage1->aData);
drh3b7511c2001-05-26 13:15:44 +00002270 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00002271 put4byte(&pPage1->aData[36], n-1);
2272 rc = getPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk);
drh3b7511c2001-05-26 13:15:44 +00002273 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00002274 rc = sqlite3pager_write(pTrunk->aData);
drh3b7511c2001-05-26 13:15:44 +00002275 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00002276 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00002277 return rc;
2278 }
drh3aac2dd2004-04-26 14:10:20 +00002279 k = get4byte(&pTrunk->aData[4]);
2280 if( k==0 ){
2281 /* The trunk has no leaves. So extract the trunk page itself and
2282 ** use it as the newly allocated page */
drha34b6762004-05-07 13:30:42 +00002283 *pPgno = get4byte(&pPage1->aData[32]);
drh3aac2dd2004-04-26 14:10:20 +00002284 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
2285 *ppPage = pTrunk;
drh3a4c1412004-05-09 20:40:11 +00002286 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh30e58752002-03-02 20:41:57 +00002287 }else{
drh3aac2dd2004-04-26 14:10:20 +00002288 /* Extract a leaf from the trunk */
2289 int closest;
2290 unsigned char *aData = pTrunk->aData;
2291 if( nearby>0 ){
drhbea00b92002-07-08 10:59:50 +00002292 int i, dist;
2293 closest = 0;
drh3aac2dd2004-04-26 14:10:20 +00002294 dist = get4byte(&aData[8]) - nearby;
drhbea00b92002-07-08 10:59:50 +00002295 if( dist<0 ) dist = -dist;
drh3a4c1412004-05-09 20:40:11 +00002296 for(i=1; i<k; i++){
drh3aac2dd2004-04-26 14:10:20 +00002297 int d2 = get4byte(&aData[8+i*4]) - nearby;
drhbea00b92002-07-08 10:59:50 +00002298 if( d2<0 ) d2 = -d2;
2299 if( d2<dist ) closest = i;
2300 }
2301 }else{
2302 closest = 0;
2303 }
drha34b6762004-05-07 13:30:42 +00002304 *pPgno = get4byte(&aData[8+closest*4]);
drh3a4c1412004-05-09 20:40:11 +00002305 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d: %d more free pages\n",
2306 *pPgno, closest+1, k, pTrunk->pgno, n-1));
drh9b171272004-05-08 02:03:22 +00002307 if( closest<k-1 ){
2308 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
2309 }
drh3a4c1412004-05-09 20:40:11 +00002310 put4byte(&aData[4], k-1);
drh3aac2dd2004-04-26 14:10:20 +00002311 rc = getPage(pBt, *pPgno, ppPage);
2312 releasePage(pTrunk);
drh30e58752002-03-02 20:41:57 +00002313 if( rc==SQLITE_OK ){
drh9b171272004-05-08 02:03:22 +00002314 sqlite3pager_dont_rollback((*ppPage)->aData);
drha34b6762004-05-07 13:30:42 +00002315 rc = sqlite3pager_write((*ppPage)->aData);
drh30e58752002-03-02 20:41:57 +00002316 }
2317 }
drh3b7511c2001-05-26 13:15:44 +00002318 }else{
drh3aac2dd2004-04-26 14:10:20 +00002319 /* There are no pages on the freelist, so create a new page at the
2320 ** end of the file */
drha34b6762004-05-07 13:30:42 +00002321 *pPgno = sqlite3pager_pagecount(pBt->pPager) + 1;
drh3aac2dd2004-04-26 14:10:20 +00002322 rc = getPage(pBt, *pPgno, ppPage);
drh3b7511c2001-05-26 13:15:44 +00002323 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00002324 rc = sqlite3pager_write((*ppPage)->aData);
drh3a4c1412004-05-09 20:40:11 +00002325 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00002326 }
2327 return rc;
2328}
2329
2330/*
drh3aac2dd2004-04-26 14:10:20 +00002331** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00002332**
drha34b6762004-05-07 13:30:42 +00002333** sqlite3pager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00002334*/
drh3aac2dd2004-04-26 14:10:20 +00002335static int freePage(MemPage *pPage){
2336 Btree *pBt = pPage->pBt;
2337 MemPage *pPage1 = pBt->pPage1;
2338 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00002339
drh3aac2dd2004-04-26 14:10:20 +00002340 /* Prepare the page for freeing */
2341 assert( pPage->pgno>1 );
2342 pPage->isInit = 0;
2343 releasePage(pPage->pParent);
2344 pPage->pParent = 0;
2345
drha34b6762004-05-07 13:30:42 +00002346 /* Increment the free page count on pPage1 */
2347 rc = sqlite3pager_write(pPage1->aData);
drh3aac2dd2004-04-26 14:10:20 +00002348 if( rc ) return rc;
2349 n = get4byte(&pPage1->aData[36]);
2350 put4byte(&pPage1->aData[36], n+1);
2351
2352 if( n==0 ){
2353 /* This is the first free page */
drhda200cc2004-05-09 11:51:38 +00002354 rc = sqlite3pager_write(pPage->aData);
2355 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00002356 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00002357 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00002358 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00002359 }else{
2360 /* Other free pages already exist. Retrive the first trunk page
2361 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00002362 MemPage *pTrunk;
2363 rc = getPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk);
drh3b7511c2001-05-26 13:15:44 +00002364 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00002365 k = get4byte(&pTrunk->aData[4]);
drhb6f41482004-05-14 01:58:11 +00002366 if( k==pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00002367 /* The trunk is full. Turn the page being freed into a new
2368 ** trunk page with no leaves. */
drha34b6762004-05-07 13:30:42 +00002369 rc = sqlite3pager_write(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00002370 if( rc ) return rc;
2371 put4byte(pPage->aData, pTrunk->pgno);
2372 put4byte(&pPage->aData[4], 0);
2373 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00002374 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
2375 pPage->pgno, pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00002376 }else{
2377 /* Add the newly freed page as a leaf on the current trunk */
drha34b6762004-05-07 13:30:42 +00002378 rc = sqlite3pager_write(pTrunk->aData);
drh3aac2dd2004-04-26 14:10:20 +00002379 if( rc ) return rc;
2380 put4byte(&pTrunk->aData[4], k+1);
2381 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drha34b6762004-05-07 13:30:42 +00002382 sqlite3pager_dont_write(pBt->pPager, pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00002383 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00002384 }
2385 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00002386 }
drh3b7511c2001-05-26 13:15:44 +00002387 return rc;
2388}
2389
2390/*
drh3aac2dd2004-04-26 14:10:20 +00002391** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00002392*/
drh3aac2dd2004-04-26 14:10:20 +00002393static int clearCell(MemPage *pPage, unsigned char *pCell){
2394 Btree *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00002395 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00002396 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00002397 int rc;
drh3b7511c2001-05-26 13:15:44 +00002398
drh43605152004-05-29 21:46:49 +00002399 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00002400 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00002401 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00002402 }
drh6f11bef2004-05-13 01:12:56 +00002403 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh3aac2dd2004-04-26 14:10:20 +00002404 while( ovflPgno!=0 ){
2405 MemPage *pOvfl;
2406 rc = getPage(pBt, ovflPgno, &pOvfl);
drh3b7511c2001-05-26 13:15:44 +00002407 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00002408 ovflPgno = get4byte(pOvfl->aData);
drha34b6762004-05-07 13:30:42 +00002409 rc = freePage(pOvfl);
drhbd03cae2001-06-02 02:40:57 +00002410 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00002411 sqlite3pager_unref(pOvfl->aData);
drh3b7511c2001-05-26 13:15:44 +00002412 }
drh5e2f8b92001-05-28 00:41:15 +00002413 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00002414}
2415
2416/*
drh91025292004-05-03 19:49:32 +00002417** Create the byte sequence used to represent a cell on page pPage
2418** and write that byte sequence into pCell[]. Overflow pages are
2419** allocated and filled in as necessary. The calling procedure
2420** is responsible for making sure sufficient space has been allocated
2421** for pCell[].
2422**
2423** Note that pCell does not necessary need to point to the pPage->aData
2424** area. pCell might point to some temporary storage. The cell will
2425** be constructed in this temporary area then copied into pPage->aData
2426** later.
drh3b7511c2001-05-26 13:15:44 +00002427*/
2428static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00002429 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00002430 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00002431 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00002432 const void *pData,int nData, /* The data */
2433 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00002434){
drh3b7511c2001-05-26 13:15:44 +00002435 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00002436 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00002437 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00002438 int spaceLeft;
2439 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00002440 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00002441 unsigned char *pPrior;
2442 unsigned char *pPayload;
2443 Btree *pBt = pPage->pBt;
2444 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00002445 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00002446 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00002447
drh91025292004-05-03 19:49:32 +00002448 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00002449 nHeader = 0;
drh91025292004-05-03 19:49:32 +00002450 if( !pPage->leaf ){
2451 nHeader += 4;
2452 }
drh8b18dd42004-05-12 19:18:15 +00002453 if( pPage->hasData ){
drh91025292004-05-03 19:49:32 +00002454 nHeader += putVarint(&pCell[nHeader], nData);
drh6f11bef2004-05-13 01:12:56 +00002455 }else{
drh91025292004-05-03 19:49:32 +00002456 nData = 0;
2457 }
drh6f11bef2004-05-13 01:12:56 +00002458 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh43605152004-05-29 21:46:49 +00002459 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00002460 assert( info.nHeader==nHeader );
2461 assert( info.nKey==nKey );
2462 assert( info.nData==nData );
2463
2464 /* Fill in the payload */
drh3aac2dd2004-04-26 14:10:20 +00002465 nPayload = nData;
2466 if( pPage->intKey ){
2467 pSrc = pData;
2468 nSrc = nData;
drh91025292004-05-03 19:49:32 +00002469 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00002470 }else{
2471 nPayload += nKey;
2472 pSrc = pKey;
2473 nSrc = nKey;
2474 }
drh6f11bef2004-05-13 01:12:56 +00002475 *pnSize = info.nSize;
2476 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00002477 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00002478 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00002479
drh3b7511c2001-05-26 13:15:44 +00002480 while( nPayload>0 ){
2481 if( spaceLeft==0 ){
drh3aac2dd2004-04-26 14:10:20 +00002482 rc = allocatePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl);
drh3b7511c2001-05-26 13:15:44 +00002483 if( rc ){
drh9b171272004-05-08 02:03:22 +00002484 releasePage(pToRelease);
drh3aac2dd2004-04-26 14:10:20 +00002485 clearCell(pPage, pCell);
drh3b7511c2001-05-26 13:15:44 +00002486 return rc;
2487 }
drh3aac2dd2004-04-26 14:10:20 +00002488 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00002489 releasePage(pToRelease);
2490 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00002491 pPrior = pOvfl->aData;
2492 put4byte(pPrior, 0);
2493 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00002494 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00002495 }
2496 n = nPayload;
2497 if( n>spaceLeft ) n = spaceLeft;
drh3aac2dd2004-04-26 14:10:20 +00002498 if( n>nSrc ) n = nSrc;
2499 memcpy(pPayload, pSrc, n);
drh3b7511c2001-05-26 13:15:44 +00002500 nPayload -= n;
drhde647132004-05-07 17:57:49 +00002501 pPayload += n;
drh9b171272004-05-08 02:03:22 +00002502 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00002503 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00002504 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00002505 if( nSrc==0 ){
2506 nSrc = nData;
2507 pSrc = pData;
2508 }
drhdd793422001-06-28 01:54:48 +00002509 }
drh9b171272004-05-08 02:03:22 +00002510 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00002511 return SQLITE_OK;
2512}
2513
2514/*
drhbd03cae2001-06-02 02:40:57 +00002515** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00002516** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00002517** pointer in the third argument.
2518*/
drh4b70f112004-05-02 21:12:19 +00002519static void reparentPage(Btree *pBt, Pgno pgno, MemPage *pNewParent, int idx){
drhbd03cae2001-06-02 02:40:57 +00002520 MemPage *pThis;
drh4b70f112004-05-02 21:12:19 +00002521 unsigned char *aData;
drhbd03cae2001-06-02 02:40:57 +00002522
drhdd793422001-06-28 01:54:48 +00002523 if( pgno==0 ) return;
drh4b70f112004-05-02 21:12:19 +00002524 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00002525 aData = sqlite3pager_lookup(pBt->pPager, pgno);
drhda200cc2004-05-09 11:51:38 +00002526 if( aData ){
drhb6f41482004-05-14 01:58:11 +00002527 pThis = (MemPage*)&aData[pBt->usableSize];
drhda200cc2004-05-09 11:51:38 +00002528 if( pThis->isInit ){
2529 if( pThis->pParent!=pNewParent ){
2530 if( pThis->pParent ) sqlite3pager_unref(pThis->pParent->aData);
2531 pThis->pParent = pNewParent;
2532 if( pNewParent ) sqlite3pager_ref(pNewParent->aData);
2533 }
2534 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00002535 }
drha34b6762004-05-07 13:30:42 +00002536 sqlite3pager_unref(aData);
drhbd03cae2001-06-02 02:40:57 +00002537 }
2538}
2539
2540/*
drh4b70f112004-05-02 21:12:19 +00002541** Change the pParent pointer of all children of pPage to point back
2542** to pPage.
2543**
drhbd03cae2001-06-02 02:40:57 +00002544** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00002545** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00002546**
2547** This routine gets called after you memcpy() one page into
2548** another.
2549*/
drh4b70f112004-05-02 21:12:19 +00002550static void reparentChildPages(MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00002551 int i;
drh4b70f112004-05-02 21:12:19 +00002552 Btree *pBt;
2553
drha34b6762004-05-07 13:30:42 +00002554 if( pPage->leaf ) return;
drh4b70f112004-05-02 21:12:19 +00002555 pBt = pPage->pBt;
drhbd03cae2001-06-02 02:40:57 +00002556 for(i=0; i<pPage->nCell; i++){
drh43605152004-05-29 21:46:49 +00002557 reparentPage(pBt, get4byte(findCell(pPage,i)), pPage, i);
drhbd03cae2001-06-02 02:40:57 +00002558 }
drh43605152004-05-29 21:46:49 +00002559 reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]), pPage, i);
drh428ae8c2003-01-04 16:48:09 +00002560 pPage->idxShift = 0;
drh14acc042001-06-10 19:56:58 +00002561}
2562
2563/*
2564** Remove the i-th cell from pPage. This routine effects pPage only.
2565** The cell content is not freed or deallocated. It is assumed that
2566** the cell content has been copied someplace else. This routine just
2567** removes the reference to the cell from pPage.
2568**
2569** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00002570*/
drh4b70f112004-05-02 21:12:19 +00002571static void dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00002572 int i; /* Loop counter */
2573 int pc; /* Offset to cell content of cell being deleted */
2574 u8 *data; /* pPage->aData */
2575 u8 *ptr; /* Used to move bytes around within data[] */
2576
drh8c42ca92001-06-22 19:15:00 +00002577 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00002578 assert( sz==cellSize(pPage, idx) );
drha34b6762004-05-07 13:30:42 +00002579 assert( sqlite3pager_iswriteable(pPage->aData) );
drhda200cc2004-05-09 11:51:38 +00002580 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00002581 ptr = &data[pPage->cellOffset + 2*idx];
2582 pc = get2byte(ptr);
2583 assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
drhde647132004-05-07 17:57:49 +00002584 freeSpace(pPage, pc, sz);
drh43605152004-05-29 21:46:49 +00002585 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
2586 ptr[0] = ptr[2];
2587 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00002588 }
2589 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00002590 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
2591 pPage->nFree += 2;
drh428ae8c2003-01-04 16:48:09 +00002592 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00002593}
2594
2595/*
2596** Insert a new cell on pPage at cell index "i". pCell points to the
2597** content of the cell.
2598**
2599** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00002600** will not fit, then make a copy of the cell content into pTemp if
2601** pTemp is not null. Regardless of pTemp, allocate a new entry
2602** in pPage->aOvfl[] and make it point to the cell content (either
2603** in pTemp or the original pCell) and also record its index.
2604** Allocating a new entry in pPage->aCell[] implies that
2605** pPage->nOverflow is incremented.
drh14acc042001-06-10 19:56:58 +00002606*/
drh24cd67e2004-05-10 16:18:47 +00002607static void insertCell(
2608 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00002609 int i, /* New cell becomes the i-th cell of the page */
2610 u8 *pCell, /* Content of the new cell */
2611 int sz, /* Bytes of content in pCell */
drh24cd67e2004-05-10 16:18:47 +00002612 u8 *pTemp /* Temp storage space for pCell, if needed */
2613){
drh43605152004-05-29 21:46:49 +00002614 int idx; /* Where to write new cell content in data[] */
2615 int j; /* Loop counter */
2616 int top; /* First byte of content for any cell in data[] */
2617 int end; /* First byte past the last cell pointer in data[] */
2618 int ins; /* Index in data[] where new cell pointer is inserted */
2619 int hdr; /* Offset into data[] of the page header */
2620 int cellOffset; /* Address of first cell pointer in data[] */
2621 u8 *data; /* The content of the whole page */
2622 u8 *ptr; /* Used for moving information around in data[] */
2623
2624 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
2625 assert( sz==cellSizePtr(pPage, pCell) );
drha34b6762004-05-07 13:30:42 +00002626 assert( sqlite3pager_iswriteable(pPage->aData) );
drh43605152004-05-29 21:46:49 +00002627 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00002628 if( pTemp ){
2629 memcpy(pTemp, pCell, sz);
drh43605152004-05-29 21:46:49 +00002630 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00002631 }
drh43605152004-05-29 21:46:49 +00002632 j = pPage->nOverflow++;
2633 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
2634 pPage->aOvfl[j].pCell = pCell;
2635 pPage->aOvfl[j].idx = i;
2636 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00002637 }else{
drh43605152004-05-29 21:46:49 +00002638 data = pPage->aData;
2639 hdr = pPage->hdrOffset;
2640 top = get2byte(&data[hdr+5]);
2641 cellOffset = pPage->cellOffset;
2642 end = cellOffset + 2*pPage->nCell + 2;
2643 ins = cellOffset + 2*i;
2644 if( end > top - sz ){
2645 defragmentPage(pPage);
2646 top = get2byte(&data[hdr+5]);
2647 assert( end + sz <= top );
2648 }
2649 idx = allocateSpace(pPage, sz);
2650 assert( idx>0 );
2651 assert( end <= get2byte(&data[hdr+5]) );
2652 pPage->nCell++;
2653 pPage->nFree -= 2;
drhda200cc2004-05-09 11:51:38 +00002654 memcpy(&data[idx], pCell, sz);
drh43605152004-05-29 21:46:49 +00002655 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
2656 ptr[0] = ptr[-2];
2657 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00002658 }
drh43605152004-05-29 21:46:49 +00002659 put2byte(&data[ins], idx);
2660 put2byte(&data[hdr+3], pPage->nCell);
2661 pPage->idxShift = 1;
drhda200cc2004-05-09 11:51:38 +00002662 pageIntegrity(pPage);
drh14acc042001-06-10 19:56:58 +00002663 }
2664}
2665
2666/*
drhfa1a98a2004-05-14 19:08:17 +00002667** Add a list of cells to a page. The page should be initially empty.
2668** The cells are guaranteed to fit on the page.
2669*/
2670static void assemblePage(
2671 MemPage *pPage, /* The page to be assemblied */
2672 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00002673 u8 **apCell, /* Pointers to cell bodies */
drhfa1a98a2004-05-14 19:08:17 +00002674 int *aSize /* Sizes of the cells */
2675){
2676 int i; /* Loop counter */
2677 int totalSize; /* Total size of all cells */
2678 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00002679 int cellptr; /* Address of next cell pointer */
2680 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00002681 u8 *data; /* Data for the page */
2682
drh43605152004-05-29 21:46:49 +00002683 assert( pPage->nOverflow==0 );
drhfa1a98a2004-05-14 19:08:17 +00002684 totalSize = 0;
2685 for(i=0; i<nCell; i++){
2686 totalSize += aSize[i];
2687 }
drh43605152004-05-29 21:46:49 +00002688 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00002689 assert( pPage->nCell==0 );
drh43605152004-05-29 21:46:49 +00002690 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00002691 data = pPage->aData;
2692 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00002693 put2byte(&data[hdr+3], nCell);
2694 cellbody = allocateSpace(pPage, totalSize);
2695 assert( cellbody>0 );
2696 assert( pPage->nFree >= 2*nCell );
2697 pPage->nFree -= 2*nCell;
drhfa1a98a2004-05-14 19:08:17 +00002698 for(i=0; i<nCell; i++){
drh43605152004-05-29 21:46:49 +00002699 put2byte(&data[cellptr], cellbody);
2700 memcpy(&data[cellbody], apCell[i], aSize[i]);
2701 cellptr += 2;
2702 cellbody += aSize[i];
drhfa1a98a2004-05-14 19:08:17 +00002703 }
drh43605152004-05-29 21:46:49 +00002704 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00002705 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00002706}
2707
drh14acc042001-06-10 19:56:58 +00002708/*
drhc8629a12004-05-08 20:07:40 +00002709** GCC does not define the offsetof() macro so we'll have to do it
2710** ourselves.
2711*/
2712#ifndef offsetof
2713#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
2714#endif
2715
2716/*
drhc3b70572003-01-04 19:44:07 +00002717** The following parameters determine how many adjacent pages get involved
2718** in a balancing operation. NN is the number of neighbors on either side
2719** of the page that participate in the balancing operation. NB is the
2720** total number of pages that participate, including the target page and
2721** NN neighbors on either side.
2722**
2723** The minimum value of NN is 1 (of course). Increasing NN above 1
2724** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
2725** in exchange for a larger degradation in INSERT and UPDATE performance.
2726** The value of NN appears to give the best results overall.
2727*/
2728#define NN 1 /* Number of neighbors on either side of pPage */
2729#define NB (NN*2+1) /* Total pages involved in the balance */
2730
drh43605152004-05-29 21:46:49 +00002731/* Forward reference */
2732static int balance(MemPage*);
2733
drhc3b70572003-01-04 19:44:07 +00002734/*
drhab01f612004-05-22 02:55:23 +00002735** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00002736** of pPage so that all pages have about the same amount of free space.
drh14acc042001-06-10 19:56:58 +00002737** Usually one sibling on either side of pPage is used in the balancing,
drh8b2f49b2001-06-08 00:21:52 +00002738** though both siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00002739** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00002740** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00002741** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00002742**
2743** The number of siblings of pPage might be increased or decreased by
drhab01f612004-05-22 02:55:23 +00002744** one in an effort to keep pages nearly full but not over full. The root page
2745** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00002746** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00002747** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00002748** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00002749**
drh8b2f49b2001-06-08 00:21:52 +00002750** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00002751** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00002752** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00002753** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00002754**
drh8c42ca92001-06-22 19:15:00 +00002755** In the course of balancing the siblings of pPage, the parent of pPage
2756** might become overfull or underfull. If that happens, then this routine
2757** is called recursively on the parent.
2758**
drh5e00f6c2001-09-13 13:46:56 +00002759** If this routine fails for any reason, it might leave the database
2760** in a corrupted state. So if this routine fails, the database should
2761** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00002762*/
drh43605152004-05-29 21:46:49 +00002763static int balance_nonroot(MemPage *pPage){
drh8b2f49b2001-06-08 00:21:52 +00002764 MemPage *pParent; /* The parent of pPage */
drh4b70f112004-05-02 21:12:19 +00002765 Btree *pBt; /* The whole database */
drha34b6762004-05-07 13:30:42 +00002766 int nCell; /* Number of cells in aCell[] */
drh8b2f49b2001-06-08 00:21:52 +00002767 int nOld; /* Number of pages in apOld[] */
2768 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00002769 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00002770 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00002771 int idx; /* Index of pPage in pParent->aCell[] */
2772 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00002773 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00002774 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00002775 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00002776 int usableSpace; /* Bytes in pPage beyond the header */
2777 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00002778 int subtotal; /* Subtotal of bytes in cells on one page */
drhb6f41482004-05-14 01:58:11 +00002779 int iSpace = 0; /* First unused byte of aSpace[] */
drhc3b70572003-01-04 19:44:07 +00002780 MemPage *apOld[NB]; /* pPage and up to two siblings */
2781 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00002782 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drhc3b70572003-01-04 19:44:07 +00002783 MemPage *apNew[NB+1]; /* pPage and up to NB siblings after balancing */
2784 Pgno pgnoNew[NB+1]; /* Page numbers for each page in apNew[] */
2785 int idxDiv[NB]; /* Indices of divider cells in pParent */
drh4b70f112004-05-02 21:12:19 +00002786 u8 *apDiv[NB]; /* Divider cells in pParent */
drha34b6762004-05-07 13:30:42 +00002787 int cntNew[NB+1]; /* Index in aCell[] of cell after i-th page */
drhc3b70572003-01-04 19:44:07 +00002788 int szNew[NB+1]; /* Combined size of cells place on i-th page */
drh4b70f112004-05-02 21:12:19 +00002789 u8 *apCell[(MX_CELL+2)*NB]; /* All cells from pages being balanced */
drhc3b70572003-01-04 19:44:07 +00002790 int szCell[(MX_CELL+2)*NB]; /* Local size of all cells */
drh4b70f112004-05-02 21:12:19 +00002791 u8 aCopy[NB][MX_PAGE_SIZE+sizeof(MemPage)]; /* Space for apCopy[] */
drhb6f41482004-05-14 01:58:11 +00002792 u8 aSpace[MX_PAGE_SIZE*4]; /* Space to copies of divider cells */
drh8b2f49b2001-06-08 00:21:52 +00002793
drh14acc042001-06-10 19:56:58 +00002794 /*
drh43605152004-05-29 21:46:49 +00002795 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00002796 */
drh3a4c1412004-05-09 20:40:11 +00002797 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00002798 assert( sqlite3pager_iswriteable(pPage->aData) );
drh4b70f112004-05-02 21:12:19 +00002799 pBt = pPage->pBt;
drh14acc042001-06-10 19:56:58 +00002800 pParent = pPage->pParent;
drh43605152004-05-29 21:46:49 +00002801 sqlite3pager_write(pParent->aData);
2802 assert( pParent );
2803 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh14acc042001-06-10 19:56:58 +00002804
drh8b2f49b2001-06-08 00:21:52 +00002805 /*
drh4b70f112004-05-02 21:12:19 +00002806 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00002807 ** to pPage. The "idx" variable is the index of that cell. If pPage
2808 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00002809 */
drhbb49aba2003-01-04 18:53:27 +00002810 if( pParent->idxShift ){
drha34b6762004-05-07 13:30:42 +00002811 Pgno pgno;
drh4b70f112004-05-02 21:12:19 +00002812 pgno = pPage->pgno;
drha34b6762004-05-07 13:30:42 +00002813 assert( pgno==sqlite3pager_pagenumber(pPage->aData) );
drhbb49aba2003-01-04 18:53:27 +00002814 for(idx=0; idx<pParent->nCell; idx++){
drh43605152004-05-29 21:46:49 +00002815 if( get4byte(findCell(pParent, idx))==pgno ){
drhbb49aba2003-01-04 18:53:27 +00002816 break;
2817 }
drh8b2f49b2001-06-08 00:21:52 +00002818 }
drh4b70f112004-05-02 21:12:19 +00002819 assert( idx<pParent->nCell
drh43605152004-05-29 21:46:49 +00002820 || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
drhbb49aba2003-01-04 18:53:27 +00002821 }else{
2822 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00002823 }
drh8b2f49b2001-06-08 00:21:52 +00002824
2825 /*
drh14acc042001-06-10 19:56:58 +00002826 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00002827 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00002828 */
drh14acc042001-06-10 19:56:58 +00002829 nOld = nNew = 0;
drha34b6762004-05-07 13:30:42 +00002830 sqlite3pager_ref(pParent->aData);
drh14acc042001-06-10 19:56:58 +00002831
2832 /*
drh4b70f112004-05-02 21:12:19 +00002833 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00002834 ** the siblings. An attempt is made to find NN siblings on either
2835 ** side of pPage. More siblings are taken from one side, however, if
2836 ** pPage there are fewer than NN siblings on the other side. If pParent
2837 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00002838 */
drhc3b70572003-01-04 19:44:07 +00002839 nxDiv = idx - NN;
2840 if( nxDiv + NB > pParent->nCell ){
2841 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00002842 }
drhc3b70572003-01-04 19:44:07 +00002843 if( nxDiv<0 ){
2844 nxDiv = 0;
2845 }
drh8b2f49b2001-06-08 00:21:52 +00002846 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00002847 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00002848 if( k<pParent->nCell ){
2849 idxDiv[i] = k;
drh43605152004-05-29 21:46:49 +00002850 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00002851 nDiv++;
drha34b6762004-05-07 13:30:42 +00002852 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00002853 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00002854 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00002855 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00002856 }else{
2857 break;
drh8b2f49b2001-06-08 00:21:52 +00002858 }
drhde647132004-05-07 17:57:49 +00002859 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00002860 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00002861 apOld[i]->idxParent = k;
drh91025292004-05-03 19:49:32 +00002862 apCopy[i] = 0;
2863 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00002864 nOld++;
drh8b2f49b2001-06-08 00:21:52 +00002865 }
2866
2867 /*
drh14acc042001-06-10 19:56:58 +00002868 ** Make copies of the content of pPage and its siblings into aOld[].
2869 ** The rest of this function will use data from the copies rather
2870 ** that the original pages since the original pages will be in the
2871 ** process of being overwritten.
2872 */
2873 for(i=0; i<nOld; i++){
drhc8629a12004-05-08 20:07:40 +00002874 MemPage *p = apCopy[i] = (MemPage*)&aCopy[i+1][-sizeof(MemPage)];
drh43605152004-05-29 21:46:49 +00002875 p->aData = &((u8*)p)[-pBt->pageSize];
2876 memcpy(p->aData, apOld[i]->aData, pBt->pageSize + sizeof(MemPage));
2877 p->aData = &((u8*)p)[-pBt->pageSize];
drh14acc042001-06-10 19:56:58 +00002878 }
2879
2880 /*
2881 ** Load pointers to all cells on sibling pages and the divider cells
2882 ** into the local apCell[] array. Make copies of the divider cells
drhb6f41482004-05-14 01:58:11 +00002883 ** into space obtained form aSpace[] and remove the the divider Cells
2884 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00002885 **
2886 ** If the siblings are on leaf pages, then the child pointers of the
2887 ** divider cells are stripped from the cells before they are copied
drh96f5b762004-05-16 16:24:36 +00002888 ** into aSpace[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00002889 ** child pointers. If siblings are not leaves, then all cell in
2890 ** apCell[] include child pointers. Either way, all cells in apCell[]
2891 ** are alike.
drh96f5b762004-05-16 16:24:36 +00002892 **
2893 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
2894 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00002895 */
2896 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00002897 leafCorrection = pPage->leaf*4;
drh8b18dd42004-05-12 19:18:15 +00002898 leafData = pPage->leafData && pPage->leaf;
drh8b2f49b2001-06-08 00:21:52 +00002899 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00002900 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00002901 int limit = pOld->nCell+pOld->nOverflow;
2902 for(j=0; j<limit; j++){
2903 apCell[nCell] = findOverflowCell(pOld, j);
2904 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
drh14acc042001-06-10 19:56:58 +00002905 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00002906 }
2907 if( i<nOld-1 ){
drh43605152004-05-29 21:46:49 +00002908 int sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00002909 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00002910 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
2911 ** are duplicates of keys on the child pages. We need to remove
2912 ** the divider cells from pParent, but the dividers cells are not
2913 ** added to apCell[] because they are duplicates of child cells.
2914 */
drh8b18dd42004-05-12 19:18:15 +00002915 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00002916 }else{
drhb6f41482004-05-14 01:58:11 +00002917 u8 *pTemp;
2918 szCell[nCell] = sz;
2919 pTemp = &aSpace[iSpace];
2920 iSpace += sz;
2921 assert( iSpace<=sizeof(aSpace) );
2922 memcpy(pTemp, apDiv[i], sz);
2923 apCell[nCell] = pTemp+leafCorrection;
2924 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00002925 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00002926 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00002927 if( !pOld->leaf ){
2928 assert( leafCorrection==0 );
2929 /* The right pointer of the child page pOld becomes the left
2930 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00002931 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00002932 }else{
2933 assert( leafCorrection==4 );
2934 }
2935 nCell++;
drh4b70f112004-05-02 21:12:19 +00002936 }
drh8b2f49b2001-06-08 00:21:52 +00002937 }
2938 }
2939
2940 /*
drh6019e162001-07-02 17:51:45 +00002941 ** Figure out the number of pages needed to hold all nCell cells.
2942 ** Store this number in "k". Also compute szNew[] which is the total
2943 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00002944 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00002945 ** cntNew[k] should equal nCell.
2946 **
drh96f5b762004-05-16 16:24:36 +00002947 ** Values computed by this block:
2948 **
2949 ** k: The total number of sibling pages
2950 ** szNew[i]: Spaced used on the i-th sibling page.
2951 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
2952 ** the right of the i-th sibling page.
2953 ** usableSpace: Number of bytes of space available on each sibling.
2954 **
drh8b2f49b2001-06-08 00:21:52 +00002955 */
drh43605152004-05-29 21:46:49 +00002956 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00002957 for(subtotal=k=i=0; i<nCell; i++){
drh43605152004-05-29 21:46:49 +00002958 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00002959 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00002960 szNew[k] = subtotal - szCell[i];
2961 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00002962 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00002963 subtotal = 0;
2964 k++;
2965 }
2966 }
2967 szNew[k] = subtotal;
2968 cntNew[k] = nCell;
2969 k++;
drh96f5b762004-05-16 16:24:36 +00002970
2971 /*
2972 ** The packing computed by the previous block is biased toward the siblings
2973 ** on the left side. The left siblings are always nearly full, while the
2974 ** right-most sibling might be nearly empty. This block of code attempts
2975 ** to adjust the packing of siblings to get a better balance.
2976 **
2977 ** This adjustment is more than an optimization. The packing above might
2978 ** be so out of balance as to be illegal. For example, the right-most
2979 ** sibling might be completely empty. This adjustment is not optional.
2980 */
drh6019e162001-07-02 17:51:45 +00002981 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00002982 int szRight = szNew[i]; /* Size of sibling on the right */
2983 int szLeft = szNew[i-1]; /* Size of sibling on the left */
2984 int r; /* Index of right-most cell in left sibling */
2985 int d; /* Index of first cell to the left of right sibling */
2986
2987 r = cntNew[i-1] - 1;
2988 d = r + 1 - leafData;
drh43605152004-05-29 21:46:49 +00002989 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
2990 szRight += szCell[d] + 2;
2991 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00002992 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00002993 r = cntNew[i-1] - 1;
2994 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00002995 }
drh96f5b762004-05-16 16:24:36 +00002996 szNew[i] = szRight;
2997 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00002998 }
2999 assert( cntNew[0]>0 );
drh8b2f49b2001-06-08 00:21:52 +00003000
3001 /*
drh6b308672002-07-08 02:16:37 +00003002 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00003003 */
drh4b70f112004-05-02 21:12:19 +00003004 assert( pPage->pgno>1 );
3005 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00003006 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00003007 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00003008 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00003009 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00003010 pgnoNew[i] = pgnoOld[i];
3011 apOld[i] = 0;
drhda200cc2004-05-09 11:51:38 +00003012 sqlite3pager_write(pNew->aData);
drh6b308672002-07-08 02:16:37 +00003013 }else{
drhda200cc2004-05-09 11:51:38 +00003014 rc = allocatePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1]);
drh6b308672002-07-08 02:16:37 +00003015 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00003016 apNew[i] = pNew;
drh6b308672002-07-08 02:16:37 +00003017 }
drh14acc042001-06-10 19:56:58 +00003018 nNew++;
drhda200cc2004-05-09 11:51:38 +00003019 zeroPage(pNew, pageFlags);
drh8b2f49b2001-06-08 00:21:52 +00003020 }
3021
drh6b308672002-07-08 02:16:37 +00003022 /* Free any old pages that were not reused as new pages.
3023 */
3024 while( i<nOld ){
drh4b70f112004-05-02 21:12:19 +00003025 rc = freePage(apOld[i]);
drh6b308672002-07-08 02:16:37 +00003026 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00003027 releasePage(apOld[i]);
drh6b308672002-07-08 02:16:37 +00003028 apOld[i] = 0;
3029 i++;
3030 }
3031
drh8b2f49b2001-06-08 00:21:52 +00003032 /*
drhf9ffac92002-03-02 19:00:31 +00003033 ** Put the new pages in accending order. This helps to
3034 ** keep entries in the disk file in order so that a scan
3035 ** of the table is a linear scan through the file. That
3036 ** in turn helps the operating system to deliver pages
3037 ** from the disk more rapidly.
3038 **
3039 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00003040 ** n is never more than NB (a small constant), that should
3041 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00003042 **
drhc3b70572003-01-04 19:44:07 +00003043 ** When NB==3, this one optimization makes the database
3044 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00003045 */
3046 for(i=0; i<k-1; i++){
3047 int minV = pgnoNew[i];
3048 int minI = i;
3049 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00003050 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00003051 minI = j;
3052 minV = pgnoNew[j];
3053 }
3054 }
3055 if( minI>i ){
3056 int t;
3057 MemPage *pT;
3058 t = pgnoNew[i];
3059 pT = apNew[i];
3060 pgnoNew[i] = pgnoNew[minI];
3061 apNew[i] = apNew[minI];
3062 pgnoNew[minI] = t;
3063 apNew[minI] = pT;
3064 }
3065 }
drh10c0fa62004-05-18 12:50:17 +00003066 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00003067 pgnoOld[0],
3068 nOld>=2 ? pgnoOld[1] : 0,
3069 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00003070 pgnoNew[0], szNew[0],
3071 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
3072 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
3073 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0));
drh24cd67e2004-05-10 16:18:47 +00003074
drhf9ffac92002-03-02 19:00:31 +00003075
3076 /*
drh14acc042001-06-10 19:56:58 +00003077 ** Evenly distribute the data in apCell[] across the new pages.
3078 ** Insert divider cells into pParent as necessary.
3079 */
3080 j = 0;
3081 for(i=0; i<nNew; i++){
3082 MemPage *pNew = apNew[i];
drh4b70f112004-05-02 21:12:19 +00003083 assert( pNew->pgno==pgnoNew[i] );
drhfa1a98a2004-05-14 19:08:17 +00003084 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
3085 j = cntNew[i];
drh6019e162001-07-02 17:51:45 +00003086 assert( pNew->nCell>0 );
drh43605152004-05-29 21:46:49 +00003087 assert( pNew->nOverflow==0 );
drh14acc042001-06-10 19:56:58 +00003088 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00003089 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00003090 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00003091 int sz;
3092 pCell = apCell[j];
3093 sz = szCell[j] + leafCorrection;
drh4b70f112004-05-02 21:12:19 +00003094 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00003095 memcpy(&pNew->aData[8], pCell, 4);
drh24cd67e2004-05-10 16:18:47 +00003096 pTemp = 0;
drh8b18dd42004-05-12 19:18:15 +00003097 }else if( leafData ){
drh6f11bef2004-05-13 01:12:56 +00003098 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00003099 j--;
drh43605152004-05-29 21:46:49 +00003100 parseCellPtr(pNew, apCell[j], &info);
drhb6f41482004-05-14 01:58:11 +00003101 pCell = &aSpace[iSpace];
drh6f11bef2004-05-13 01:12:56 +00003102 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, &sz);
drhb6f41482004-05-14 01:58:11 +00003103 iSpace += sz;
3104 assert( iSpace<=sizeof(aSpace) );
drh8b18dd42004-05-12 19:18:15 +00003105 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00003106 }else{
3107 pCell -= 4;
drhb6f41482004-05-14 01:58:11 +00003108 pTemp = &aSpace[iSpace];
3109 iSpace += sz;
3110 assert( iSpace<=sizeof(aSpace) );
drh4b70f112004-05-02 21:12:19 +00003111 }
drh8b18dd42004-05-12 19:18:15 +00003112 insertCell(pParent, nxDiv, pCell, sz, pTemp);
drh43605152004-05-29 21:46:49 +00003113 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
drh14acc042001-06-10 19:56:58 +00003114 j++;
3115 nxDiv++;
3116 }
3117 }
drh6019e162001-07-02 17:51:45 +00003118 assert( j==nCell );
drh4b70f112004-05-02 21:12:19 +00003119 if( (pageFlags & PTF_LEAF)==0 ){
drh43605152004-05-29 21:46:49 +00003120 memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
drh14acc042001-06-10 19:56:58 +00003121 }
drh43605152004-05-29 21:46:49 +00003122 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00003123 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00003124 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00003125 }else{
3126 /* Right-most sibling is the left child of the first entry in pParent
3127 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00003128 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00003129 }
3130
3131 /*
3132 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00003133 */
3134 for(i=0; i<nNew; i++){
drh4b70f112004-05-02 21:12:19 +00003135 reparentChildPages(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00003136 }
drh4b70f112004-05-02 21:12:19 +00003137 reparentChildPages(pParent);
drh8b2f49b2001-06-08 00:21:52 +00003138
3139 /*
drh3a4c1412004-05-09 20:40:11 +00003140 ** Balance the parent page. Note that the current page (pPage) might
3141 ** have been added to the freelist is it might no longer be initialized.
3142 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00003143 */
drhda200cc2004-05-09 11:51:38 +00003144 assert( pParent->isInit );
drh3a4c1412004-05-09 20:40:11 +00003145 /* assert( pPage->isInit ); // No! pPage might have been added to freelist */
3146 /* pageIntegrity(pPage); // No! pPage might have been added to freelist */
drh4b70f112004-05-02 21:12:19 +00003147 rc = balance(pParent);
drhda200cc2004-05-09 11:51:38 +00003148
drh8b2f49b2001-06-08 00:21:52 +00003149 /*
drh14acc042001-06-10 19:56:58 +00003150 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00003151 */
drh14acc042001-06-10 19:56:58 +00003152balance_cleanup:
drh8b2f49b2001-06-08 00:21:52 +00003153 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00003154 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00003155 }
drh14acc042001-06-10 19:56:58 +00003156 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00003157 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00003158 }
drh91025292004-05-03 19:49:32 +00003159 releasePage(pParent);
drh3a4c1412004-05-09 20:40:11 +00003160 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
3161 pPage->pgno, nOld, nNew, nCell));
drh8b2f49b2001-06-08 00:21:52 +00003162 return rc;
3163}
3164
3165/*
drh43605152004-05-29 21:46:49 +00003166** This routine is called for the root page of a btree when the root
3167** page contains no cells. This is an opportunity to make the tree
3168** shallower by one level.
3169*/
3170static int balance_shallower(MemPage *pPage){
3171 MemPage *pChild; /* The only child page of pPage */
3172 Pgno pgnoChild; /* Page number for pChild */
3173 int rc; /* Return code from subprocedures */
3174 u8 *apCell[(MX_CELL+2)*NB]; /* All cells from pages being balanced */
3175 int szCell[(MX_CELL+2)*NB]; /* Local size of all cells */
3176
3177 assert( pPage->pParent==0 );
3178 assert( pPage->nCell==0 );
3179 if( pPage->leaf ){
3180 /* The table is completely empty */
3181 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
3182 }else{
3183 /* The root page is empty but has one child. Transfer the
3184 ** information from that one child into the root page if it
3185 ** will fit. This reduces the depth of the tree by one.
3186 **
3187 ** If the root page is page 1, it has less space available than
3188 ** its child (due to the 100 byte header that occurs at the beginning
3189 ** of the database fle), so it might not be able to hold all of the
3190 ** information currently contained in the child. If this is the
3191 ** case, then do not do the transfer. Leave page 1 empty except
3192 ** for the right-pointer to the child page. The child page becomes
3193 ** the virtual root of the tree.
3194 */
3195 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
3196 assert( pgnoChild>0 );
3197 assert( pgnoChild<=sqlite3pager_pagecount(pPage->pBt->pPager) );
3198 rc = getPage(pPage->pBt, pgnoChild, &pChild);
3199 if( rc ) return rc;
3200 if( pPage->pgno==1 ){
3201 rc = initPage(pChild, pPage);
3202 if( rc ) return rc;
3203 assert( pChild->nOverflow==0 );
3204 if( pChild->nFree>=100 ){
3205 /* The child information will fit on the root page, so do the
3206 ** copy */
3207 int i;
3208 zeroPage(pPage, pChild->aData[0]);
3209 for(i=0; i<pChild->nCell; i++){
3210 apCell[i] = findCell(pChild,i);
3211 szCell[i] = cellSizePtr(pChild, apCell[i]);
3212 }
3213 assemblePage(pPage, pChild->nCell, apCell, szCell);
3214 freePage(pChild);
3215 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
3216 }else{
3217 /* The child has more information that will fit on the root.
3218 ** The tree is already balanced. Do nothing. */
3219 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
3220 }
3221 }else{
3222 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
3223 pPage->isInit = 0;
3224 pPage->pParent = 0;
3225 rc = initPage(pPage, 0);
3226 assert( rc==SQLITE_OK );
3227 freePage(pChild);
3228 TRACE(("BALANCE: transfer child %d into root %d\n",
3229 pChild->pgno, pPage->pgno));
3230 }
3231 reparentChildPages(pPage);
3232 releasePage(pChild);
3233 }
3234 return SQLITE_OK;
3235}
3236
3237
3238/*
3239** The root page is overfull
3240**
3241** When this happens, Create a new child page and copy the
3242** contents of the root into the child. Then make the root
3243** page an empty page with rightChild pointing to the new
3244** child. Finally, call balance_internal() on the new child
3245** to cause it to split.
3246*/
3247static int balance_deeper(MemPage *pPage){
3248 int rc; /* Return value from subprocedures */
3249 MemPage *pChild; /* Pointer to a new child page */
3250 Pgno pgnoChild; /* Page number of the new child page */
3251 Btree *pBt; /* The BTree */
3252 int usableSize; /* Total usable size of a page */
3253 u8 *data; /* Content of the parent page */
3254 u8 *cdata; /* Content of the child page */
3255 int hdr; /* Offset to page header in parent */
3256 int brk; /* Offset to content of first cell in parent */
3257
3258 assert( pPage->pParent==0 );
3259 assert( pPage->nOverflow>0 );
3260 pBt = pPage->pBt;
3261 rc = allocatePage(pBt, &pChild, &pgnoChild, pPage->pgno);
3262 if( rc ) return rc;
3263 assert( sqlite3pager_iswriteable(pChild->aData) );
3264 usableSize = pBt->usableSize;
3265 data = pPage->aData;
3266 hdr = pPage->hdrOffset;
3267 brk = get2byte(&data[hdr+5]);
3268 cdata = pChild->aData;
3269 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
3270 memcpy(&cdata[brk], &data[brk], usableSize-brk);
3271 rc = initPage(pChild, pPage);
3272 if( rc ) return rc;
3273 memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
3274 pChild->nOverflow = pPage->nOverflow;
3275 if( pChild->nOverflow ){
3276 pChild->nFree = 0;
3277 }
3278 assert( pChild->nCell==pPage->nCell );
3279 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
3280 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
3281 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
3282 rc = balance_nonroot(pChild);
3283 releasePage(pChild);
3284 return rc;
3285}
3286
3287/*
3288** Decide if the page pPage needs to be balanced. If balancing is
3289** required, call the appropriate balancing routine.
3290*/
3291static int balance(MemPage *pPage){
3292 int rc = SQLITE_OK;
3293 if( pPage->pParent==0 ){
3294 if( pPage->nOverflow>0 ){
3295 rc = balance_deeper(pPage);
3296 }
3297 if( pPage->nCell==0 ){
3298 rc = balance_shallower(pPage);
3299 }
3300 }else{
3301 if( pPage->nOverflow>0 || pPage->nFree>pPage->pBt->usableSize*2/3 ){
3302 rc = balance_nonroot(pPage);
3303 }
3304 }
3305 return rc;
3306}
3307
3308/*
drhf74b8d92002-09-01 23:20:45 +00003309** This routine checks all cursors that point to the same table
3310** as pCur points to. If any of those cursors were opened with
3311** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
3312** cursors point to the same table were opened with wrFlag==1
3313** then this routine returns SQLITE_OK.
3314**
3315** In addition to checking for read-locks (where a read-lock
3316** means a cursor opened with wrFlag==0) this routine also moves
3317** all cursors other than pCur so that they are pointing to the
3318** first Cell on root page. This is necessary because an insert
3319** or delete might change the number of cells on a page or delete
3320** a page entirely and we do not want to leave any cursors
3321** pointing to non-existant pages or cells.
3322*/
3323static int checkReadLocks(BtCursor *pCur){
3324 BtCursor *p;
3325 assert( pCur->wrFlag );
3326 for(p=pCur->pShared; p!=pCur; p=p->pShared){
3327 assert( p );
3328 assert( p->pgnoRoot==pCur->pgnoRoot );
drha34b6762004-05-07 13:30:42 +00003329 assert( p->pPage->pgno==sqlite3pager_pagenumber(p->pPage->aData) );
drhf74b8d92002-09-01 23:20:45 +00003330 if( p->wrFlag==0 ) return SQLITE_LOCKED;
drh91025292004-05-03 19:49:32 +00003331 if( p->pPage->pgno!=p->pgnoRoot ){
drhf74b8d92002-09-01 23:20:45 +00003332 moveToRoot(p);
3333 }
3334 }
3335 return SQLITE_OK;
3336}
3337
3338/*
drh3b7511c2001-05-26 13:15:44 +00003339** Insert a new record into the BTree. The key is given by (pKey,nKey)
3340** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00003341** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00003342** is left pointing at a random location.
3343**
3344** For an INTKEY table, only the nKey value of the key is used. pKey is
3345** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00003346*/
drh3aac2dd2004-04-26 14:10:20 +00003347int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00003348 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00003349 const void *pKey, i64 nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00003350 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00003351){
drh3b7511c2001-05-26 13:15:44 +00003352 int rc;
3353 int loc;
drh14acc042001-06-10 19:56:58 +00003354 int szNew;
drh3b7511c2001-05-26 13:15:44 +00003355 MemPage *pPage;
3356 Btree *pBt = pCur->pBt;
drha34b6762004-05-07 13:30:42 +00003357 unsigned char *oldCell;
3358 unsigned char newCell[MX_CELL_SIZE];
drh3b7511c2001-05-26 13:15:44 +00003359
drhc39e0002004-05-07 23:50:57 +00003360 if( pCur->status ){
3361 return pCur->status; /* A rollback destroyed this cursor */
drhecdc7532001-09-23 02:35:53 +00003362 }
danielk1977e7c8d582004-05-13 13:38:52 +00003363 if( !pBt->inTrans ){
drhf74b8d92002-09-01 23:20:45 +00003364 /* Must start a transaction before doing an insert */
3365 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003366 }
drhf74b8d92002-09-01 23:20:45 +00003367 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00003368 if( !pCur->wrFlag ){
3369 return SQLITE_PERM; /* Cursor not open for writing */
3370 }
drhf74b8d92002-09-01 23:20:45 +00003371 if( checkReadLocks(pCur) ){
3372 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
3373 }
drh3aac2dd2004-04-26 14:10:20 +00003374 rc = sqlite3BtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00003375 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00003376 pPage = pCur->pPage;
drh4a1c3802004-05-12 15:15:47 +00003377 assert( pPage->intKey || nKey>=0 );
drh8b18dd42004-05-12 19:18:15 +00003378 assert( pPage->leaf || !pPage->leafData );
drh3a4c1412004-05-09 20:40:11 +00003379 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
3380 pCur->pgnoRoot, nKey, nData, pPage->pgno,
3381 loc==0 ? "overwrite" : "new entry"));
drh7aa128d2002-06-21 13:09:16 +00003382 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00003383 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00003384 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003385 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, &szNew);
drh3b7511c2001-05-26 13:15:44 +00003386 if( rc ) return rc;
drh43605152004-05-29 21:46:49 +00003387 assert( szNew==cellSizePtr(pPage, newCell) );
drh3a4c1412004-05-09 20:40:11 +00003388 assert( szNew<=sizeof(newCell) );
drhf328bc82004-05-10 23:29:49 +00003389 if( loc==0 && pCur->isValid ){
drha34b6762004-05-07 13:30:42 +00003390 int szOld;
3391 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00003392 oldCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00003393 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003394 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00003395 }
drh43605152004-05-29 21:46:49 +00003396 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00003397 rc = clearCell(pPage, oldCell);
drh5e2f8b92001-05-28 00:41:15 +00003398 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00003399 dropCell(pPage, pCur->idx, szOld);
drh7c717f72001-06-24 20:39:41 +00003400 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00003401 assert( pPage->leaf );
drh14acc042001-06-10 19:56:58 +00003402 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00003403 pCur->info.nSize = 0;
drh14acc042001-06-10 19:56:58 +00003404 }else{
drh4b70f112004-05-02 21:12:19 +00003405 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00003406 }
drh24cd67e2004-05-10 16:18:47 +00003407 insertCell(pPage, pCur->idx, newCell, szNew, 0);
drh4b70f112004-05-02 21:12:19 +00003408 rc = balance(pPage);
drh23e11ca2004-05-04 17:27:28 +00003409 /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
drh3fc190c2001-09-14 03:24:23 +00003410 /* fflush(stdout); */
drh4b70f112004-05-02 21:12:19 +00003411 moveToRoot(pCur);
drh5e2f8b92001-05-28 00:41:15 +00003412 return rc;
3413}
3414
3415/*
drh4b70f112004-05-02 21:12:19 +00003416** Delete the entry that the cursor is pointing to. The cursor
3417** is left pointing at a random location.
drh3b7511c2001-05-26 13:15:44 +00003418*/
drh3aac2dd2004-04-26 14:10:20 +00003419int sqlite3BtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00003420 MemPage *pPage = pCur->pPage;
drh4b70f112004-05-02 21:12:19 +00003421 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00003422 int rc;
drh8c42ca92001-06-22 19:15:00 +00003423 Pgno pgnoChild;
drh0d316a42002-08-11 20:10:47 +00003424 Btree *pBt = pCur->pBt;
drh8b2f49b2001-06-08 00:21:52 +00003425
drh7aa128d2002-06-21 13:09:16 +00003426 assert( pPage->isInit );
drhc39e0002004-05-07 23:50:57 +00003427 if( pCur->status ){
3428 return pCur->status; /* A rollback destroyed this cursor */
drhecdc7532001-09-23 02:35:53 +00003429 }
drhf74b8d92002-09-01 23:20:45 +00003430 if( !pBt->inTrans ){
3431 /* Must start a transaction before doing a delete */
3432 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003433 }
drhf74b8d92002-09-01 23:20:45 +00003434 assert( !pBt->readOnly );
drhbd03cae2001-06-02 02:40:57 +00003435 if( pCur->idx >= pPage->nCell ){
3436 return SQLITE_ERROR; /* The cursor is not pointing to anything */
3437 }
drhecdc7532001-09-23 02:35:53 +00003438 if( !pCur->wrFlag ){
3439 return SQLITE_PERM; /* Did not open this cursor for writing */
3440 }
drhf74b8d92002-09-01 23:20:45 +00003441 if( checkReadLocks(pCur) ){
3442 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
3443 }
drha34b6762004-05-07 13:30:42 +00003444 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00003445 if( rc ) return rc;
drh43605152004-05-29 21:46:49 +00003446 pCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00003447 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003448 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00003449 }
3450 clearCell(pPage, pCell);
3451 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00003452 /*
drh5e00f6c2001-09-13 13:46:56 +00003453 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00003454 ** do something we will leave a hole on an internal page.
3455 ** We have to fill the hole by moving in a cell from a leaf. The
3456 ** next Cell after the one to be deleted is guaranteed to exist and
3457 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00003458 */
drh14acc042001-06-10 19:56:58 +00003459 BtCursor leafCur;
drh4b70f112004-05-02 21:12:19 +00003460 unsigned char *pNext;
drh14acc042001-06-10 19:56:58 +00003461 int szNext;
drh8c1238a2003-01-02 14:43:55 +00003462 int notUsed;
drh24cd67e2004-05-10 16:18:47 +00003463 unsigned char tempCell[MX_CELL_SIZE];
drh8b18dd42004-05-12 19:18:15 +00003464 assert( !pPage->leafData );
drh14acc042001-06-10 19:56:58 +00003465 getTempCursor(pCur, &leafCur);
drh3aac2dd2004-04-26 14:10:20 +00003466 rc = sqlite3BtreeNext(&leafCur, &notUsed);
drh14acc042001-06-10 19:56:58 +00003467 if( rc!=SQLITE_OK ){
drh8a6ac0a2004-02-14 17:35:07 +00003468 if( rc!=SQLITE_NOMEM ) rc = SQLITE_CORRUPT;
3469 return rc;
drh5e2f8b92001-05-28 00:41:15 +00003470 }
drha34b6762004-05-07 13:30:42 +00003471 rc = sqlite3pager_write(leafCur.pPage->aData);
drh6019e162001-07-02 17:51:45 +00003472 if( rc ) return rc;
drh3a4c1412004-05-09 20:40:11 +00003473 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
3474 pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
drh43605152004-05-29 21:46:49 +00003475 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
3476 pNext = findCell(leafCur.pPage, leafCur.idx);
3477 szNext = cellSizePtr(leafCur.pPage, pNext);
drh24cd67e2004-05-10 16:18:47 +00003478 assert( sizeof(tempCell)>=szNext+4 );
3479 insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell);
drh43605152004-05-29 21:46:49 +00003480 put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
drh4b70f112004-05-02 21:12:19 +00003481 rc = balance(pPage);
drh5e2f8b92001-05-28 00:41:15 +00003482 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00003483 dropCell(leafCur.pPage, leafCur.idx, szNext);
3484 rc = balance(leafCur.pPage);
drh8c42ca92001-06-22 19:15:00 +00003485 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00003486 }else{
drh3a4c1412004-05-09 20:40:11 +00003487 TRACE(("DELETE: table=%d delete from leaf %d\n",
3488 pCur->pgnoRoot, pPage->pgno));
drh43605152004-05-29 21:46:49 +00003489 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
drh4b70f112004-05-02 21:12:19 +00003490 rc = balance(pPage);
drh5e2f8b92001-05-28 00:41:15 +00003491 }
drh4b70f112004-05-02 21:12:19 +00003492 moveToRoot(pCur);
drh5e2f8b92001-05-28 00:41:15 +00003493 return rc;
drh3b7511c2001-05-26 13:15:44 +00003494}
drh8b2f49b2001-06-08 00:21:52 +00003495
3496/*
drhc6b52df2002-01-04 03:09:29 +00003497** Create a new BTree table. Write into *piTable the page
3498** number for the root page of the new table.
3499**
drhab01f612004-05-22 02:55:23 +00003500** The type of type is determined by the flags parameter. Only the
3501** following values of flags are currently in use. Other values for
3502** flags might not work:
3503**
3504** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
3505** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00003506*/
drh3aac2dd2004-04-26 14:10:20 +00003507int sqlite3BtreeCreateTable(Btree *pBt, int *piTable, int flags){
drh8b2f49b2001-06-08 00:21:52 +00003508 MemPage *pRoot;
3509 Pgno pgnoRoot;
3510 int rc;
3511 if( !pBt->inTrans ){
drhf74b8d92002-09-01 23:20:45 +00003512 /* Must start a transaction first */
3513 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003514 }
drh5df72a52002-06-06 23:16:05 +00003515 if( pBt->readOnly ){
3516 return SQLITE_READONLY;
3517 }
drhda200cc2004-05-09 11:51:38 +00003518 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1);
drh8b2f49b2001-06-08 00:21:52 +00003519 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003520 assert( sqlite3pager_iswriteable(pRoot->aData) );
drhde647132004-05-07 17:57:49 +00003521 zeroPage(pRoot, flags | PTF_LEAF);
drha34b6762004-05-07 13:30:42 +00003522 sqlite3pager_unref(pRoot->aData);
drh8b2f49b2001-06-08 00:21:52 +00003523 *piTable = (int)pgnoRoot;
3524 return SQLITE_OK;
3525}
3526
3527/*
3528** Erase the given database page and all its children. Return
3529** the page to the freelist.
3530*/
drh4b70f112004-05-02 21:12:19 +00003531static int clearDatabasePage(
3532 Btree *pBt, /* The BTree that contains the table */
3533 Pgno pgno, /* Page number to clear */
3534 MemPage *pParent, /* Parent page. NULL for the root */
3535 int freePageFlag /* Deallocate page if true */
3536){
drh8b2f49b2001-06-08 00:21:52 +00003537 MemPage *pPage;
3538 int rc;
drh4b70f112004-05-02 21:12:19 +00003539 unsigned char *pCell;
3540 int i;
drh8b2f49b2001-06-08 00:21:52 +00003541
drhde647132004-05-07 17:57:49 +00003542 rc = getAndInitPage(pBt, pgno, &pPage, pParent);
drh8b2f49b2001-06-08 00:21:52 +00003543 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003544 rc = sqlite3pager_write(pPage->aData);
drh6019e162001-07-02 17:51:45 +00003545 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00003546 for(i=0; i<pPage->nCell; i++){
drh43605152004-05-29 21:46:49 +00003547 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00003548 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003549 rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
drh8b2f49b2001-06-08 00:21:52 +00003550 if( rc ) return rc;
3551 }
drh4b70f112004-05-02 21:12:19 +00003552 rc = clearCell(pPage, pCell);
drh8b2f49b2001-06-08 00:21:52 +00003553 if( rc ) return rc;
3554 }
drha34b6762004-05-07 13:30:42 +00003555 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003556 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
drh2aa679f2001-06-25 02:11:07 +00003557 if( rc ) return rc;
3558 }
3559 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00003560 rc = freePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00003561 }else{
drh3a4c1412004-05-09 20:40:11 +00003562 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00003563 }
drh4b70f112004-05-02 21:12:19 +00003564 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00003565 return rc;
drh8b2f49b2001-06-08 00:21:52 +00003566}
3567
3568/*
drhab01f612004-05-22 02:55:23 +00003569** Delete all information from a single table in the database. iTable is
3570** the page number of the root of the table. After this routine returns,
3571** the root page is empty, but still exists.
3572**
3573** This routine will fail with SQLITE_LOCKED if there are any open
3574** read cursors on the table. Open write cursors are moved to the
3575** root of the table.
drh8b2f49b2001-06-08 00:21:52 +00003576*/
drh3aac2dd2004-04-26 14:10:20 +00003577int sqlite3BtreeClearTable(Btree *pBt, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00003578 int rc;
drhf74b8d92002-09-01 23:20:45 +00003579 BtCursor *pCur;
drh8b2f49b2001-06-08 00:21:52 +00003580 if( !pBt->inTrans ){
drhf74b8d92002-09-01 23:20:45 +00003581 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003582 }
drhf74b8d92002-09-01 23:20:45 +00003583 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3584 if( pCur->pgnoRoot==(Pgno)iTable ){
3585 if( pCur->wrFlag==0 ) return SQLITE_LOCKED;
3586 moveToRoot(pCur);
3587 }
drhecdc7532001-09-23 02:35:53 +00003588 }
drha34b6762004-05-07 13:30:42 +00003589 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
drh8b2f49b2001-06-08 00:21:52 +00003590 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00003591 sqlite3BtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00003592 }
drh8c42ca92001-06-22 19:15:00 +00003593 return rc;
drh8b2f49b2001-06-08 00:21:52 +00003594}
3595
3596/*
3597** Erase all information in a table and add the root of the table to
3598** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00003599** page 1) is never added to the freelist.
3600**
3601** This routine will fail with SQLITE_LOCKED if there are any open
3602** cursors on the table.
drh8b2f49b2001-06-08 00:21:52 +00003603*/
drh3aac2dd2004-04-26 14:10:20 +00003604int sqlite3BtreeDropTable(Btree *pBt, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00003605 int rc;
3606 MemPage *pPage;
drhf74b8d92002-09-01 23:20:45 +00003607 BtCursor *pCur;
drh8b2f49b2001-06-08 00:21:52 +00003608 if( !pBt->inTrans ){
drhf74b8d92002-09-01 23:20:45 +00003609 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003610 }
drhf74b8d92002-09-01 23:20:45 +00003611 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3612 if( pCur->pgnoRoot==(Pgno)iTable ){
3613 return SQLITE_LOCKED; /* Cannot drop a table that has a cursor */
3614 }
drh5df72a52002-06-06 23:16:05 +00003615 }
drha34b6762004-05-07 13:30:42 +00003616 rc = getPage(pBt, (Pgno)iTable, &pPage);
drh2aa679f2001-06-25 02:11:07 +00003617 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003618 rc = sqlite3BtreeClearTable(pBt, iTable);
drh2aa679f2001-06-25 02:11:07 +00003619 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00003620 if( iTable>1 ){
drha34b6762004-05-07 13:30:42 +00003621 rc = freePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00003622 }else{
drha34b6762004-05-07 13:30:42 +00003623 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
drh8b2f49b2001-06-08 00:21:52 +00003624 }
drh4b70f112004-05-02 21:12:19 +00003625 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00003626 return rc;
3627}
3628
drh001bbcb2003-03-19 03:14:00 +00003629
drh8b2f49b2001-06-08 00:21:52 +00003630/*
drh23e11ca2004-05-04 17:27:28 +00003631** Read the meta-information out of a database file. Meta[0]
3632** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00003633** through meta[15] are available for use by higher layers. Meta[0]
3634** is read-only, the others are read/write.
3635**
3636** The schema layer numbers meta values differently. At the schema
3637** layer (and the SetCookie and ReadCookie opcodes) the number of
3638** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00003639*/
drh3aac2dd2004-04-26 14:10:20 +00003640int sqlite3BtreeGetMeta(Btree *pBt, int idx, u32 *pMeta){
drh8b2f49b2001-06-08 00:21:52 +00003641 int rc;
drh4b70f112004-05-02 21:12:19 +00003642 unsigned char *pP1;
drh8b2f49b2001-06-08 00:21:52 +00003643
drh23e11ca2004-05-04 17:27:28 +00003644 assert( idx>=0 && idx<=15 );
drha34b6762004-05-07 13:30:42 +00003645 rc = sqlite3pager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00003646 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00003647 *pMeta = get4byte(&pP1[36 + idx*4]);
drha34b6762004-05-07 13:30:42 +00003648 sqlite3pager_unref(pP1);
drh8b2f49b2001-06-08 00:21:52 +00003649 return SQLITE_OK;
3650}
3651
3652/*
drh23e11ca2004-05-04 17:27:28 +00003653** Write meta-information back into the database. Meta[0] is
3654** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00003655*/
drh3aac2dd2004-04-26 14:10:20 +00003656int sqlite3BtreeUpdateMeta(Btree *pBt, int idx, u32 iMeta){
drh4b70f112004-05-02 21:12:19 +00003657 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00003658 int rc;
drh23e11ca2004-05-04 17:27:28 +00003659 assert( idx>=1 && idx<=15 );
drh8b2f49b2001-06-08 00:21:52 +00003660 if( !pBt->inTrans ){
drhf74b8d92002-09-01 23:20:45 +00003661 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +00003662 }
drhde647132004-05-07 17:57:49 +00003663 assert( pBt->pPage1!=0 );
3664 pP1 = pBt->pPage1->aData;
drha34b6762004-05-07 13:30:42 +00003665 rc = sqlite3pager_write(pP1);
drh4b70f112004-05-02 21:12:19 +00003666 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00003667 put4byte(&pP1[36 + idx*4], iMeta);
drh8b2f49b2001-06-08 00:21:52 +00003668 return SQLITE_OK;
3669}
drh8c42ca92001-06-22 19:15:00 +00003670
drhf328bc82004-05-10 23:29:49 +00003671/*
3672** Return the flag byte at the beginning of the page that the cursor
3673** is currently pointing to.
3674*/
3675int sqlite3BtreeFlags(BtCursor *pCur){
3676 MemPage *pPage = pCur->pPage;
3677 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
3678}
3679
drh5eddca62001-06-30 21:53:53 +00003680/******************************************************************************
3681** The complete implementation of the BTree subsystem is above this line.
3682** All the code the follows is for testing and troubleshooting the BTree
3683** subsystem. None of the code that follows is used during normal operation.
drh5eddca62001-06-30 21:53:53 +00003684******************************************************************************/
drh5eddca62001-06-30 21:53:53 +00003685
drh8c42ca92001-06-22 19:15:00 +00003686/*
3687** Print a disassembly of the given page on standard output. This routine
3688** is used for debugging and testing only.
3689*/
drhaaab5722002-02-19 13:39:21 +00003690#ifdef SQLITE_TEST
drh23e11ca2004-05-04 17:27:28 +00003691int sqlite3BtreePageDump(Btree *pBt, int pgno, int recursive){
drh8c42ca92001-06-22 19:15:00 +00003692 int rc;
3693 MemPage *pPage;
drhc8629a12004-05-08 20:07:40 +00003694 int i, j, c;
drh8c42ca92001-06-22 19:15:00 +00003695 int nFree;
3696 u16 idx;
drhab9f7f12004-05-08 10:56:11 +00003697 int hdr;
drh43605152004-05-29 21:46:49 +00003698 int nCell;
drhab9f7f12004-05-08 10:56:11 +00003699 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00003700 char range[20];
3701 unsigned char payload[20];
drhab9f7f12004-05-08 10:56:11 +00003702
drh4b70f112004-05-02 21:12:19 +00003703 rc = getPage(pBt, (Pgno)pgno, &pPage);
drh8c42ca92001-06-22 19:15:00 +00003704 if( rc ){
3705 return rc;
3706 }
drhab9f7f12004-05-08 10:56:11 +00003707 hdr = pPage->hdrOffset;
3708 data = pPage->aData;
drhc8629a12004-05-08 20:07:40 +00003709 c = data[hdr];
drh8b18dd42004-05-12 19:18:15 +00003710 pPage->intKey = (c & (PTF_INTKEY|PTF_LEAFDATA))!=0;
drhc8629a12004-05-08 20:07:40 +00003711 pPage->zeroData = (c & PTF_ZERODATA)!=0;
drh8b18dd42004-05-12 19:18:15 +00003712 pPage->leafData = (c & PTF_LEAFDATA)!=0;
drhc8629a12004-05-08 20:07:40 +00003713 pPage->leaf = (c & PTF_LEAF)!=0;
drh8b18dd42004-05-12 19:18:15 +00003714 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
drh43605152004-05-29 21:46:49 +00003715 nCell = get2byte(&data[hdr+3]);
drhda200cc2004-05-09 11:51:38 +00003716 printf("PAGE %d: flags=0x%02x frag=%d parent=%d\n", pgno,
drh43605152004-05-29 21:46:49 +00003717 data[hdr], data[hdr+7],
drhda200cc2004-05-09 11:51:38 +00003718 (pPage->isInit && pPage->pParent) ? pPage->pParent->pgno : 0);
drhab9f7f12004-05-08 10:56:11 +00003719 assert( hdr == (pgno==1 ? 100 : 0) );
drh43605152004-05-29 21:46:49 +00003720 idx = hdr + 12 - pPage->leaf*4;
3721 for(i=0; i<nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00003722 CellInfo info;
drh4b70f112004-05-02 21:12:19 +00003723 Pgno child;
drh43605152004-05-29 21:46:49 +00003724 unsigned char *pCell;
drh6f11bef2004-05-13 01:12:56 +00003725 int sz;
drh43605152004-05-29 21:46:49 +00003726 int addr;
drh6f11bef2004-05-13 01:12:56 +00003727
drh43605152004-05-29 21:46:49 +00003728 addr = get2byte(&data[idx + 2*i]);
3729 pCell = &data[addr];
3730 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003731 sz = info.nSize;
drh43605152004-05-29 21:46:49 +00003732 sprintf(range,"%d..%d", addr, addr+sz-1);
drh4b70f112004-05-02 21:12:19 +00003733 if( pPage->leaf ){
3734 child = 0;
3735 }else{
drh43605152004-05-29 21:46:49 +00003736 child = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00003737 }
drh6f11bef2004-05-13 01:12:56 +00003738 sz = info.nData;
3739 if( !pPage->intKey ) sz += info.nKey;
drh8c42ca92001-06-22 19:15:00 +00003740 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
drh6f11bef2004-05-13 01:12:56 +00003741 memcpy(payload, &pCell[info.nHeader], sz);
drh8c42ca92001-06-22 19:15:00 +00003742 for(j=0; j<sz; j++){
3743 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
3744 }
3745 payload[sz] = 0;
3746 printf(
drh6f11bef2004-05-13 01:12:56 +00003747 "cell %2d: i=%-10s chld=%-4d nk=%-4lld nd=%-4d payload=%s\n",
3748 i, range, child, info.nKey, info.nData, payload
drh8c42ca92001-06-22 19:15:00 +00003749 );
drh8c42ca92001-06-22 19:15:00 +00003750 }
drh4b70f112004-05-02 21:12:19 +00003751 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003752 printf("right_child: %d\n", get4byte(&data[hdr+8]));
drh4b70f112004-05-02 21:12:19 +00003753 }
drh8c42ca92001-06-22 19:15:00 +00003754 nFree = 0;
3755 i = 0;
drhab9f7f12004-05-08 10:56:11 +00003756 idx = get2byte(&data[hdr+1]);
drhb6f41482004-05-14 01:58:11 +00003757 while( idx>0 && idx<pPage->pBt->usableSize ){
drhab9f7f12004-05-08 10:56:11 +00003758 int sz = get2byte(&data[idx+2]);
drh4b70f112004-05-02 21:12:19 +00003759 sprintf(range,"%d..%d", idx, idx+sz-1);
3760 nFree += sz;
drh8c42ca92001-06-22 19:15:00 +00003761 printf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
drh4b70f112004-05-02 21:12:19 +00003762 i, range, sz, nFree);
drhab9f7f12004-05-08 10:56:11 +00003763 idx = get2byte(&data[idx]);
drh2aa679f2001-06-25 02:11:07 +00003764 i++;
drh8c42ca92001-06-22 19:15:00 +00003765 }
3766 if( idx!=0 ){
3767 printf("ERROR: next freeblock index out of range: %d\n", idx);
3768 }
drha34b6762004-05-07 13:30:42 +00003769 if( recursive && !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003770 for(i=0; i<nCell; i++){
3771 unsigned char *pCell = findCell(pPage, i);
3772 sqlite3BtreePageDump(pBt, get4byte(pCell), 1);
drha34b6762004-05-07 13:30:42 +00003773 idx = get2byte(pCell);
drh6019e162001-07-02 17:51:45 +00003774 }
drh43605152004-05-29 21:46:49 +00003775 sqlite3BtreePageDump(pBt, get4byte(&data[hdr+8]), 1);
drh6019e162001-07-02 17:51:45 +00003776 }
drhab9f7f12004-05-08 10:56:11 +00003777 sqlite3pager_unref(data);
drh3644f082004-05-10 18:45:09 +00003778 fflush(stdout);
drh8c42ca92001-06-22 19:15:00 +00003779 return SQLITE_OK;
3780}
drhaaab5722002-02-19 13:39:21 +00003781#endif
drh8c42ca92001-06-22 19:15:00 +00003782
drhaaab5722002-02-19 13:39:21 +00003783#ifdef SQLITE_TEST
drh8c42ca92001-06-22 19:15:00 +00003784/*
drh2aa679f2001-06-25 02:11:07 +00003785** Fill aResult[] with information about the entry and page that the
3786** cursor is pointing to.
3787**
3788** aResult[0] = The page number
3789** aResult[1] = The entry number
3790** aResult[2] = Total number of entries on this page
3791** aResult[3] = Size of this entry
3792** aResult[4] = Number of free bytes on this page
3793** aResult[5] = Number of free blocks on the page
3794** aResult[6] = Page number of the left child of this entry
3795** aResult[7] = Page number of the right child for the whole page
drh5eddca62001-06-30 21:53:53 +00003796**
3797** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00003798*/
drhda200cc2004-05-09 11:51:38 +00003799int sqlite3BtreeCursorInfo(BtCursor *pCur, int *aResult){
drh2aa679f2001-06-25 02:11:07 +00003800 int cnt, idx;
3801 MemPage *pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00003802
3803 pageIntegrity(pPage);
drh4b70f112004-05-02 21:12:19 +00003804 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00003805 aResult[0] = sqlite3pager_pagenumber(pPage->aData);
drh91025292004-05-03 19:49:32 +00003806 assert( aResult[0]==pPage->pgno );
drh8c42ca92001-06-22 19:15:00 +00003807 aResult[1] = pCur->idx;
drh2aa679f2001-06-25 02:11:07 +00003808 aResult[2] = pPage->nCell;
3809 if( pCur->idx>=0 && pCur->idx<pPage->nCell ){
drh43605152004-05-29 21:46:49 +00003810 u8 *pCell = findCell(pPage, pCur->idx);
3811 aResult[3] = cellSizePtr(pPage, pCell);
3812 aResult[6] = pPage->leaf ? 0 : get4byte(pCell);
drh2aa679f2001-06-25 02:11:07 +00003813 }else{
3814 aResult[3] = 0;
3815 aResult[6] = 0;
3816 }
3817 aResult[4] = pPage->nFree;
3818 cnt = 0;
drh4b70f112004-05-02 21:12:19 +00003819 idx = get2byte(&pPage->aData[pPage->hdrOffset+1]);
drhb6f41482004-05-14 01:58:11 +00003820 while( idx>0 && idx<pPage->pBt->usableSize ){
drh2aa679f2001-06-25 02:11:07 +00003821 cnt++;
drh4b70f112004-05-02 21:12:19 +00003822 idx = get2byte(&pPage->aData[idx]);
drh2aa679f2001-06-25 02:11:07 +00003823 }
3824 aResult[5] = cnt;
drh43605152004-05-29 21:46:49 +00003825 aResult[7] = pPage->leaf ? 0 : get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh8c42ca92001-06-22 19:15:00 +00003826 return SQLITE_OK;
3827}
drhaaab5722002-02-19 13:39:21 +00003828#endif
drhdd793422001-06-28 01:54:48 +00003829
drhdd793422001-06-28 01:54:48 +00003830/*
drh5eddca62001-06-30 21:53:53 +00003831** Return the pager associated with a BTree. This routine is used for
3832** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00003833*/
drh3aac2dd2004-04-26 14:10:20 +00003834Pager *sqlite3BtreePager(Btree *pBt){
drhdd793422001-06-28 01:54:48 +00003835 return pBt->pPager;
3836}
drh5eddca62001-06-30 21:53:53 +00003837
3838/*
3839** This structure is passed around through all the sanity checking routines
3840** in order to keep track of some global state information.
3841*/
drhaaab5722002-02-19 13:39:21 +00003842typedef struct IntegrityCk IntegrityCk;
3843struct IntegrityCk {
drh100569d2001-10-02 13:01:48 +00003844 Btree *pBt; /* The tree being checked out */
3845 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
3846 int nPage; /* Number of pages in the database */
3847 int *anRef; /* Number of times each page is referenced */
drh100569d2001-10-02 13:01:48 +00003848 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00003849};
3850
3851/*
3852** Append a message to the error message string.
3853*/
drhaaab5722002-02-19 13:39:21 +00003854static void checkAppendMsg(IntegrityCk *pCheck, char *zMsg1, char *zMsg2){
drh5eddca62001-06-30 21:53:53 +00003855 if( pCheck->zErrMsg ){
3856 char *zOld = pCheck->zErrMsg;
3857 pCheck->zErrMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00003858 sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00003859 sqliteFree(zOld);
3860 }else{
danielk19774adee202004-05-08 08:23:19 +00003861 sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00003862 }
3863}
3864
3865/*
3866** Add 1 to the reference count for page iPage. If this is the second
3867** reference to the page, add an error message to pCheck->zErrMsg.
3868** Return 1 if there are 2 ore more references to the page and 0 if
3869** if this is the first reference to the page.
3870**
3871** Also check that the page number is in bounds.
3872*/
drhaaab5722002-02-19 13:39:21 +00003873static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00003874 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00003875 if( iPage>pCheck->nPage || iPage<0 ){
drh5eddca62001-06-30 21:53:53 +00003876 char zBuf[100];
3877 sprintf(zBuf, "invalid page number %d", iPage);
3878 checkAppendMsg(pCheck, zContext, zBuf);
3879 return 1;
3880 }
3881 if( pCheck->anRef[iPage]==1 ){
3882 char zBuf[100];
3883 sprintf(zBuf, "2nd reference to page %d", iPage);
3884 checkAppendMsg(pCheck, zContext, zBuf);
3885 return 1;
3886 }
3887 return (pCheck->anRef[iPage]++)>1;
3888}
3889
3890/*
3891** Check the integrity of the freelist or of an overflow page list.
3892** Verify that the number of pages on the list is N.
3893*/
drh30e58752002-03-02 20:41:57 +00003894static void checkList(
3895 IntegrityCk *pCheck, /* Integrity checking context */
3896 int isFreeList, /* True for a freelist. False for overflow page list */
3897 int iPage, /* Page number for first page in the list */
3898 int N, /* Expected number of pages in the list */
3899 char *zContext /* Context for error messages */
3900){
3901 int i;
drh3a4c1412004-05-09 20:40:11 +00003902 int expected = N;
3903 int iFirst = iPage;
drh5eddca62001-06-30 21:53:53 +00003904 char zMsg[100];
drh30e58752002-03-02 20:41:57 +00003905 while( N-- > 0 ){
drh4b70f112004-05-02 21:12:19 +00003906 unsigned char *pOvfl;
drh5eddca62001-06-30 21:53:53 +00003907 if( iPage<1 ){
drh3a4c1412004-05-09 20:40:11 +00003908 sprintf(zMsg, "%d of %d pages missing from overflow list starting at %d",
3909 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00003910 checkAppendMsg(pCheck, zContext, zMsg);
3911 break;
3912 }
3913 if( checkRef(pCheck, iPage, zContext) ) break;
drha34b6762004-05-07 13:30:42 +00003914 if( sqlite3pager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
drh5eddca62001-06-30 21:53:53 +00003915 sprintf(zMsg, "failed to get page %d", iPage);
3916 checkAppendMsg(pCheck, zContext, zMsg);
3917 break;
3918 }
drh30e58752002-03-02 20:41:57 +00003919 if( isFreeList ){
drh4b70f112004-05-02 21:12:19 +00003920 int n = get4byte(&pOvfl[4]);
drh0d316a42002-08-11 20:10:47 +00003921 for(i=0; i<n; i++){
drh4b70f112004-05-02 21:12:19 +00003922 checkRef(pCheck, get4byte(&pOvfl[8+i*4]), zContext);
drh30e58752002-03-02 20:41:57 +00003923 }
drh0d316a42002-08-11 20:10:47 +00003924 N -= n;
drh30e58752002-03-02 20:41:57 +00003925 }
drh4b70f112004-05-02 21:12:19 +00003926 iPage = get4byte(pOvfl);
drha34b6762004-05-07 13:30:42 +00003927 sqlite3pager_unref(pOvfl);
drh5eddca62001-06-30 21:53:53 +00003928 }
3929}
3930
3931/*
3932** Do various sanity checks on a single page of a tree. Return
3933** the tree depth. Root pages return 0. Parents of root pages
3934** return 1, and so forth.
3935**
3936** These checks are done:
3937**
3938** 1. Make sure that cells and freeblocks do not overlap
3939** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00003940** NO 2. Make sure cell keys are in order.
3941** NO 3. Make sure no key is less than or equal to zLowerBound.
3942** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00003943** 5. Check the integrity of overflow pages.
3944** 6. Recursively call checkTreePage on all children.
3945** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00003946** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00003947** the root of the tree.
3948*/
3949static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00003950 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00003951 int iPage, /* Page number of the page to check */
3952 MemPage *pParent, /* Parent page */
3953 char *zParentContext, /* Parent context */
3954 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00003955 int nLower, /* Number of characters in zLowerBound */
3956 char *zUpperBound, /* All keys should be less than this, if not NULL */
3957 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00003958){
3959 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00003960 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00003961 int hdr, cellStart;
3962 int nCell;
drhda200cc2004-05-09 11:51:38 +00003963 u8 *data;
drh5eddca62001-06-30 21:53:53 +00003964 BtCursor cur;
drh0d316a42002-08-11 20:10:47 +00003965 Btree *pBt;
drhb6f41482004-05-14 01:58:11 +00003966 int maxLocal, usableSize;
drh5eddca62001-06-30 21:53:53 +00003967 char zMsg[100];
3968 char zContext[100];
drhda200cc2004-05-09 11:51:38 +00003969 char hit[MX_PAGE_SIZE];
drh5eddca62001-06-30 21:53:53 +00003970
3971 /* Check that the page exists
3972 */
drh0d316a42002-08-11 20:10:47 +00003973 cur.pBt = pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00003974 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00003975 if( iPage==0 ) return 0;
3976 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh4b70f112004-05-02 21:12:19 +00003977 if( (rc = getPage(pBt, (Pgno)iPage, &pPage))!=0 ){
drh5eddca62001-06-30 21:53:53 +00003978 sprintf(zMsg, "unable to get the page. error code=%d", rc);
3979 checkAppendMsg(pCheck, zContext, zMsg);
3980 return 0;
3981 }
drh6f11bef2004-05-13 01:12:56 +00003982 maxLocal = pPage->leafData ? pBt->maxLeaf : pBt->maxLocal;
drh4b70f112004-05-02 21:12:19 +00003983 if( (rc = initPage(pPage, pParent))!=0 ){
drh5eddca62001-06-30 21:53:53 +00003984 sprintf(zMsg, "initPage() returns error code %d", rc);
3985 checkAppendMsg(pCheck, zContext, zMsg);
drh91025292004-05-03 19:49:32 +00003986 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00003987 return 0;
3988 }
3989
3990 /* Check out all the cells.
3991 */
3992 depth = 0;
drh5eddca62001-06-30 21:53:53 +00003993 cur.pPage = pPage;
drh5eddca62001-06-30 21:53:53 +00003994 for(i=0; i<pPage->nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00003995 u8 *pCell;
3996 int sz;
3997 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00003998
3999 /* Check payload overflow pages
4000 */
drh3a4c1412004-05-09 20:40:11 +00004001 sprintf(zContext, "On tree page %d cell %d: ", iPage, i);
drh43605152004-05-29 21:46:49 +00004002 pCell = findCell(pPage,i);
4003 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004004 sz = info.nData;
4005 if( !pPage->intKey ) sz += info.nKey;
4006 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00004007 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +00004008 checkList(pCheck, 0, get4byte(&pCell[info.iOverflow]),nPage,zContext);
drh5eddca62001-06-30 21:53:53 +00004009 }
4010
4011 /* Check sanity of left child page.
4012 */
drhda200cc2004-05-09 11:51:38 +00004013 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004014 pgno = get4byte(pCell);
drhda200cc2004-05-09 11:51:38 +00004015 d2 = checkTreePage(pCheck,pgno,pPage,zContext,0,0,0,0);
4016 if( i>0 && d2!=depth ){
4017 checkAppendMsg(pCheck, zContext, "Child page depth differs");
4018 }
4019 depth = d2;
drh5eddca62001-06-30 21:53:53 +00004020 }
drh5eddca62001-06-30 21:53:53 +00004021 }
drhda200cc2004-05-09 11:51:38 +00004022 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004023 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drhda200cc2004-05-09 11:51:38 +00004024 sprintf(zContext, "On page %d at right child: ", iPage);
4025 checkTreePage(pCheck, pgno, pPage, zContext,0,0,0,0);
4026 }
drh5eddca62001-06-30 21:53:53 +00004027
4028 /* Check for complete coverage of the page
4029 */
drhda200cc2004-05-09 11:51:38 +00004030 data = pPage->aData;
4031 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00004032 memset(hit, 0, usableSize);
4033 memset(hit, 1, get2byte(&data[hdr+5]));
4034 nCell = get2byte(&data[hdr+3]);
4035 cellStart = hdr + 12 - 4*pPage->leaf;
4036 for(i=0; i<nCell; i++){
4037 int pc = get2byte(&data[cellStart+i*2]);
4038 int size = cellSizePtr(pPage, &data[pc]);
drh5eddca62001-06-30 21:53:53 +00004039 int j;
drh43605152004-05-29 21:46:49 +00004040 for(j=pc+size-1; j>=pc; j--) hit[j]++;
drh5eddca62001-06-30 21:53:53 +00004041 }
drhb6f41482004-05-14 01:58:11 +00004042 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000; cnt++){
drhda200cc2004-05-09 11:51:38 +00004043 int size = get2byte(&data[i+2]);
drh5eddca62001-06-30 21:53:53 +00004044 int j;
drhda200cc2004-05-09 11:51:38 +00004045 for(j=i+size-1; j>=i; j--) hit[j]++;
4046 i = get2byte(&data[i]);
drh5eddca62001-06-30 21:53:53 +00004047 }
drhb6f41482004-05-14 01:58:11 +00004048 for(i=cnt=0; i<usableSize; i++){
drh5eddca62001-06-30 21:53:53 +00004049 if( hit[i]==0 ){
drhda200cc2004-05-09 11:51:38 +00004050 cnt++;
drh5eddca62001-06-30 21:53:53 +00004051 }else if( hit[i]>1 ){
4052 sprintf(zMsg, "Multiple uses for byte %d of page %d", i, iPage);
4053 checkAppendMsg(pCheck, zMsg, 0);
4054 break;
4055 }
4056 }
drh43605152004-05-29 21:46:49 +00004057 if( cnt!=data[hdr+7] ){
drhda200cc2004-05-09 11:51:38 +00004058 sprintf(zMsg, "Fragmented space is %d byte reported as %d on page %d",
drh43605152004-05-29 21:46:49 +00004059 cnt, data[hdr+7], iPage);
drhda200cc2004-05-09 11:51:38 +00004060 checkAppendMsg(pCheck, zMsg, 0);
4061 }
drh6019e162001-07-02 17:51:45 +00004062
drh4b70f112004-05-02 21:12:19 +00004063 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00004064 return depth+1;
drh5eddca62001-06-30 21:53:53 +00004065}
4066
4067/*
4068** This routine does a complete check of the given BTree file. aRoot[] is
4069** an array of pages numbers were each page number is the root page of
4070** a table. nRoot is the number of entries in aRoot.
4071**
4072** If everything checks out, this routine returns NULL. If something is
4073** amiss, an error message is written into memory obtained from malloc()
4074** and a pointer to that error message is returned. The calling function
4075** is responsible for freeing the error message when it is done.
4076*/
drh3aac2dd2004-04-26 14:10:20 +00004077char *sqlite3BtreeIntegrityCheck(Btree *pBt, int *aRoot, int nRoot){
drh5eddca62001-06-30 21:53:53 +00004078 int i;
4079 int nRef;
drhaaab5722002-02-19 13:39:21 +00004080 IntegrityCk sCheck;
drh5eddca62001-06-30 21:53:53 +00004081
drha34b6762004-05-07 13:30:42 +00004082 nRef = *sqlite3pager_stats(pBt->pPager);
drhefc251d2001-07-01 22:12:01 +00004083 if( lockBtree(pBt)!=SQLITE_OK ){
4084 return sqliteStrDup("Unable to acquire a read lock on the database");
4085 }
drh5eddca62001-06-30 21:53:53 +00004086 sCheck.pBt = pBt;
4087 sCheck.pPager = pBt->pPager;
drha34b6762004-05-07 13:30:42 +00004088 sCheck.nPage = sqlite3pager_pagecount(sCheck.pPager);
drh0de8c112002-07-06 16:32:14 +00004089 if( sCheck.nPage==0 ){
4090 unlockBtreeIfUnused(pBt);
4091 return 0;
4092 }
drh8c1238a2003-01-02 14:43:55 +00004093 sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
drhda200cc2004-05-09 11:51:38 +00004094 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh5eddca62001-06-30 21:53:53 +00004095 sCheck.zErrMsg = 0;
4096
4097 /* Check the integrity of the freelist
4098 */
drha34b6762004-05-07 13:30:42 +00004099 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
4100 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00004101
4102 /* Check all the tables.
4103 */
4104 for(i=0; i<nRoot; i++){
drh4ff6dfa2002-03-03 23:06:00 +00004105 if( aRoot[i]==0 ) continue;
drh1bffb9c2002-02-03 17:37:36 +00004106 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00004107 }
4108
4109 /* Make sure every page in the file is referenced
4110 */
4111 for(i=1; i<=sCheck.nPage; i++){
4112 if( sCheck.anRef[i]==0 ){
4113 char zBuf[100];
4114 sprintf(zBuf, "Page %d is never used", i);
4115 checkAppendMsg(&sCheck, zBuf, 0);
4116 }
4117 }
4118
4119 /* Make sure this analysis did not leave any unref() pages
4120 */
drh5e00f6c2001-09-13 13:46:56 +00004121 unlockBtreeIfUnused(pBt);
drha34b6762004-05-07 13:30:42 +00004122 if( nRef != *sqlite3pager_stats(pBt->pPager) ){
drh5eddca62001-06-30 21:53:53 +00004123 char zBuf[100];
4124 sprintf(zBuf,
4125 "Outstanding page count goes from %d to %d during this analysis",
drha34b6762004-05-07 13:30:42 +00004126 nRef, *sqlite3pager_stats(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00004127 );
4128 checkAppendMsg(&sCheck, zBuf, 0);
4129 }
4130
4131 /* Clean up and report errors.
4132 */
4133 sqliteFree(sCheck.anRef);
4134 return sCheck.zErrMsg;
4135}
paulb95a8862003-04-01 21:16:41 +00004136
drh73509ee2003-04-06 20:44:45 +00004137/*
4138** Return the full pathname of the underlying database file.
4139*/
drh3aac2dd2004-04-26 14:10:20 +00004140const char *sqlite3BtreeGetFilename(Btree *pBt){
drh73509ee2003-04-06 20:44:45 +00004141 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00004142 return sqlite3pager_filename(pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00004143}
4144
4145/*
drhf7c57532003-04-25 13:22:51 +00004146** Copy the complete content of pBtFrom into pBtTo. A transaction
4147** must be active for both files.
4148**
4149** The size of file pBtFrom may be reduced by this operation.
drh43605152004-05-29 21:46:49 +00004150** If anything goes wrong, the transaction on pBtFrom is rolled back.
drh73509ee2003-04-06 20:44:45 +00004151*/
drh3aac2dd2004-04-26 14:10:20 +00004152int sqlite3BtreeCopyFile(Btree *pBtTo, Btree *pBtFrom){
drhf7c57532003-04-25 13:22:51 +00004153 int rc = SQLITE_OK;
drh2e6d11b2003-04-25 15:37:57 +00004154 Pgno i, nPage, nToPage;
drhf7c57532003-04-25 13:22:51 +00004155
4156 if( !pBtTo->inTrans || !pBtFrom->inTrans ) return SQLITE_ERROR;
drhf7c57532003-04-25 13:22:51 +00004157 if( pBtTo->pCursor ) return SQLITE_BUSY;
drh465407d2004-05-20 02:01:26 +00004158 memcpy(pBtTo->pPage1->aData, pBtFrom->pPage1->aData, pBtFrom->usableSize);
4159 rc = sqlite3pager_overwrite(pBtTo->pPager, 1, pBtFrom->pPage1->aData);
drha34b6762004-05-07 13:30:42 +00004160 nToPage = sqlite3pager_pagecount(pBtTo->pPager);
4161 nPage = sqlite3pager_pagecount(pBtFrom->pPager);
drh2e6d11b2003-04-25 15:37:57 +00004162 for(i=2; rc==SQLITE_OK && i<=nPage; i++){
drhf7c57532003-04-25 13:22:51 +00004163 void *pPage;
drha34b6762004-05-07 13:30:42 +00004164 rc = sqlite3pager_get(pBtFrom->pPager, i, &pPage);
drhf7c57532003-04-25 13:22:51 +00004165 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00004166 rc = sqlite3pager_overwrite(pBtTo->pPager, i, pPage);
drh2e6d11b2003-04-25 15:37:57 +00004167 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00004168 sqlite3pager_unref(pPage);
drhf7c57532003-04-25 13:22:51 +00004169 }
drh2e6d11b2003-04-25 15:37:57 +00004170 for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
4171 void *pPage;
drha34b6762004-05-07 13:30:42 +00004172 rc = sqlite3pager_get(pBtTo->pPager, i, &pPage);
drh2e6d11b2003-04-25 15:37:57 +00004173 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00004174 rc = sqlite3pager_write(pPage);
4175 sqlite3pager_unref(pPage);
4176 sqlite3pager_dont_write(pBtTo->pPager, i);
drh2e6d11b2003-04-25 15:37:57 +00004177 }
4178 if( !rc && nPage<nToPage ){
drha34b6762004-05-07 13:30:42 +00004179 rc = sqlite3pager_truncate(pBtTo->pPager, nPage);
drh2e6d11b2003-04-25 15:37:57 +00004180 }
drhf7c57532003-04-25 13:22:51 +00004181 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00004182 sqlite3BtreeRollback(pBtTo);
drhf7c57532003-04-25 13:22:51 +00004183 }
4184 return rc;
drh73509ee2003-04-06 20:44:45 +00004185}
danielk19771d850a72004-05-31 08:26:49 +00004186
4187/*
4188** Return non-zero if a transaction is active.
4189*/
4190int sqlite3BtreeIsInTrans(Btree *pBt){
4191 return (pBt && pBt->inTrans);
4192}
4193
4194/*
4195** Return non-zero if a statement transaction is active.
4196*/
4197int sqlite3BtreeIsInStmt(Btree *pBt){
4198 return (pBt && pBt->inStmt);
4199}