blob: e09c4755f9fba443c18a5b77509bcbec80f7db38 [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*************************************************************************
danielk1977fbcd5852004-06-15 02:44:18 +000012** $Id: btree.c,v 1.169 2004/06/15 02:44:19 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"
drh1f595712004-06-15 01:40:29 +0000210#include "os.h"
drha059ad02001-04-17 20:09:11 +0000211#include <assert.h>
212
drh4b70f112004-05-02 21:12:19 +0000213
214/* Maximum page size. The upper bound on this value is 65536 (a limit
drh43605152004-05-29 21:46:49 +0000215** imposed by the 2-byte size of cell array pointers.) The
drh4b70f112004-05-02 21:12:19 +0000216** maximum page size determines the amount of stack space allocated
217** by many of the routines in this module. On embedded architectures
218** or any machine where memory and especially stack memory is limited,
219** one may wish to chose a smaller value for the maximum page size.
220*/
221#ifndef MX_PAGE_SIZE
222# define MX_PAGE_SIZE 1024
223#endif
224
drh4b70f112004-05-02 21:12:19 +0000225/* The following value is the maximum cell size assuming a maximum page
226** size give above.
227*/
drh43605152004-05-29 21:46:49 +0000228#define MX_CELL_SIZE (MX_PAGE_SIZE-8)
drh4b70f112004-05-02 21:12:19 +0000229
230/* The maximum number of cells on a single page of the database. This
231** assumes a minimum cell size of 3 bytes. Such small cells will be
232** exceedingly rare, but they are possible.
233*/
drh43605152004-05-29 21:46:49 +0000234#define MX_CELL ((MX_PAGE_SIZE-8)/3)
drh4b70f112004-05-02 21:12:19 +0000235
paulb95a8862003-04-01 21:16:41 +0000236/* Forward declarations */
drh3aac2dd2004-04-26 14:10:20 +0000237typedef struct MemPage MemPage;
paulb95a8862003-04-01 21:16:41 +0000238
drh8c42ca92001-06-22 19:15:00 +0000239/*
drhbd03cae2001-06-02 02:40:57 +0000240** This is a magic string that appears at the beginning of every
drh8c42ca92001-06-22 19:15:00 +0000241** SQLite database in order to identify the file as a real database.
drhde647132004-05-07 17:57:49 +0000242** 123456789 123456 */
243static const char zMagicHeader[] = "SQLite format 3";
drh08ed44e2001-04-29 23:32:55 +0000244
245/*
drh4b70f112004-05-02 21:12:19 +0000246** Page type flags. An ORed combination of these flags appear as the
247** first byte of every BTree page.
drh8c42ca92001-06-22 19:15:00 +0000248*/
drhde647132004-05-07 17:57:49 +0000249#define PTF_INTKEY 0x01
drh9e572e62004-04-23 23:43:10 +0000250#define PTF_ZERODATA 0x02
drh8b18dd42004-05-12 19:18:15 +0000251#define PTF_LEAFDATA 0x04
252#define PTF_LEAF 0x08
drh8c42ca92001-06-22 19:15:00 +0000253
254/*
drh9e572e62004-04-23 23:43:10 +0000255** As each page of the file is loaded into memory, an instance of the following
256** structure is appended and initialized to zero. This structure stores
257** information about the page that is decoded from the raw file page.
drh14acc042001-06-10 19:56:58 +0000258**
drh72f82862001-05-24 21:06:34 +0000259** The pParent field points back to the parent page. This allows us to
260** walk up the BTree from any leaf to the root. Care must be taken to
261** unref() the parent page pointer when this page is no longer referenced.
drhbd03cae2001-06-02 02:40:57 +0000262** The pageDestructor() routine handles that chore.
drh7e3b0a02001-04-28 16:52:40 +0000263*/
264struct MemPage {
drha6abd042004-06-09 17:37:22 +0000265 u8 isInit; /* True if previously initialized. MUST BE FIRST! */
drh43605152004-05-29 21:46:49 +0000266 u8 idxShift; /* True if Cell indices have changed */
267 u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
268 u8 intKey; /* True if intkey flag is set */
269 u8 leaf; /* True if leaf flag is set */
270 u8 zeroData; /* True if table stores keys only */
271 u8 leafData; /* True if tables stores data on leaves only */
272 u8 hasData; /* True if this page stores data */
273 u8 hdrOffset; /* 100 for page 1. 0 otherwise */
drh271efa52004-05-30 19:19:05 +0000274 u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
drha2fce642004-06-05 00:01:44 +0000275 u16 maxLocal; /* Copy of Btree.maxLocal or Btree.maxLeaf */
276 u16 minLocal; /* Copy of Btree.minLocal or Btree.minLeaf */
drh43605152004-05-29 21:46:49 +0000277 u16 cellOffset; /* Index in aData of first cell pointer */
278 u16 idxParent; /* Index in parent of this node */
279 u16 nFree; /* Number of free bytes on the page */
280 u16 nCell; /* Number of cells on this page, local and ovfl */
281 struct _OvflCell { /* Cells that will not fit on aData[] */
282 u8 *pCell; /* Pointers to the body of the overflow cell */
283 u16 idx; /* Insert this cell before idx-th non-overflow cell */
drha2fce642004-06-05 00:01:44 +0000284 } aOvfl[5];
drh43605152004-05-29 21:46:49 +0000285 struct Btree *pBt; /* Pointer back to BTree structure */
286 u8 *aData; /* Pointer back to the start of the page */
287 Pgno pgno; /* Page number for this page */
288 MemPage *pParent; /* The parent of this page. NULL for root */
drh8c42ca92001-06-22 19:15:00 +0000289};
drh7e3b0a02001-04-28 16:52:40 +0000290
291/*
drh3b7511c2001-05-26 13:15:44 +0000292** The in-memory image of a disk page has the auxiliary information appended
293** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
294** that extra information.
295*/
drh3aac2dd2004-04-26 14:10:20 +0000296#define EXTRA_SIZE sizeof(MemPage)
drh3b7511c2001-05-26 13:15:44 +0000297
298/*
drha059ad02001-04-17 20:09:11 +0000299** Everything we need to know about an open database
300*/
301struct Btree {
302 Pager *pPager; /* The page cache */
drh306dc212001-05-21 13:45:10 +0000303 BtCursor *pCursor; /* A list of all open cursors */
drh3aac2dd2004-04-26 14:10:20 +0000304 MemPage *pPage1; /* First page of the database */
drh663fc632002-02-02 18:49:19 +0000305 u8 inTrans; /* True if a transaction is in progress */
drhab01f612004-05-22 02:55:23 +0000306 u8 inStmt; /* True if we are in a statement subtransaction */
drh5df72a52002-06-06 23:16:05 +0000307 u8 readOnly; /* True if the underlying file is readonly */
drhab01f612004-05-22 02:55:23 +0000308 u8 maxEmbedFrac; /* Maximum payload as % of total page size */
309 u8 minEmbedFrac; /* Minimum payload as % of total page size */
310 u8 minLeafFrac; /* Minimum leaf payload as % of total page size */
drha2fce642004-06-05 00:01:44 +0000311 u16 pageSize; /* Total number of bytes on a page */
312 u16 usableSize; /* Number of usable bytes on each page */
drh6f11bef2004-05-13 01:12:56 +0000313 int maxLocal; /* Maximum local payload in non-LEAFDATA tables */
314 int minLocal; /* Minimum local payload in non-LEAFDATA tables */
315 int maxLeaf; /* Maximum local payload in a LEAFDATA table */
316 int minLeaf; /* Minimum local payload in a LEAFDATA table */
drha059ad02001-04-17 20:09:11 +0000317};
318typedef Btree Bt;
319
drh365d68f2001-05-11 11:02:46 +0000320/*
danielk1977ee5741e2004-05-31 10:01:34 +0000321** Btree.inTrans may take one of the following values.
322*/
323#define TRANS_NONE 0
324#define TRANS_READ 1
325#define TRANS_WRITE 2
326
327/*
drhfa1a98a2004-05-14 19:08:17 +0000328** An instance of the following structure is used to hold information
drh271efa52004-05-30 19:19:05 +0000329** about a cell. The parseCellPtr() function fills in this structure
drhab01f612004-05-22 02:55:23 +0000330** based on information extract from the raw disk page.
drhfa1a98a2004-05-14 19:08:17 +0000331*/
332typedef struct CellInfo CellInfo;
333struct CellInfo {
drh43605152004-05-29 21:46:49 +0000334 u8 *pCell; /* Pointer to the start of cell content */
drhfa1a98a2004-05-14 19:08:17 +0000335 i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
336 u32 nData; /* Number of bytes of data */
drh271efa52004-05-30 19:19:05 +0000337 u16 nHeader; /* Size of the cell content header in bytes */
drhfa1a98a2004-05-14 19:08:17 +0000338 u16 nLocal; /* Amount of payload held locally */
drhab01f612004-05-22 02:55:23 +0000339 u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
drh271efa52004-05-30 19:19:05 +0000340 u16 nSize; /* Size of the cell content on the main b-tree page */
drhfa1a98a2004-05-14 19:08:17 +0000341};
342
343/*
drh365d68f2001-05-11 11:02:46 +0000344** A cursor is a pointer to a particular entry in the BTree.
345** The entry is identified by its MemPage and the index in
drha34b6762004-05-07 13:30:42 +0000346** MemPage.aCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000347*/
drh72f82862001-05-24 21:06:34 +0000348struct BtCursor {
drh5e2f8b92001-05-28 00:41:15 +0000349 Btree *pBt; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000350 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drhf74b8d92002-09-01 23:20:45 +0000351 BtCursor *pShared; /* Loop of cursors with the same root page */
drh3aac2dd2004-04-26 14:10:20 +0000352 int (*xCompare)(void*,int,const void*,int,const void*); /* Key comp func */
353 void *pArg; /* First arg to xCompare() */
drh8b2f49b2001-06-08 00:21:52 +0000354 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000355 MemPage *pPage; /* Page that contains the entry */
drh3aac2dd2004-04-26 14:10:20 +0000356 int idx; /* Index of the entry in pPage->aCell[] */
drhfa1a98a2004-05-14 19:08:17 +0000357 CellInfo info; /* A parse of the cell we are pointing at */
drhecdc7532001-09-23 02:35:53 +0000358 u8 wrFlag; /* True if writable */
drhc39e0002004-05-07 23:50:57 +0000359 u8 isValid; /* TRUE if points to a valid entry */
360 u8 status; /* Set to SQLITE_ABORT if cursors is invalidated */
drh365d68f2001-05-11 11:02:46 +0000361};
drh7e3b0a02001-04-28 16:52:40 +0000362
drha059ad02001-04-17 20:09:11 +0000363/*
drhab01f612004-05-22 02:55:23 +0000364** Read or write a two- and four-byte big-endian integer values.
drh0d316a42002-08-11 20:10:47 +0000365*/
drh9e572e62004-04-23 23:43:10 +0000366static u32 get2byte(unsigned char *p){
367 return (p[0]<<8) | p[1];
drh0d316a42002-08-11 20:10:47 +0000368}
drh9e572e62004-04-23 23:43:10 +0000369static u32 get4byte(unsigned char *p){
370 return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
371}
drh9e572e62004-04-23 23:43:10 +0000372static void put2byte(unsigned char *p, u32 v){
373 p[0] = v>>8;
374 p[1] = v;
375}
376static void put4byte(unsigned char *p, u32 v){
377 p[0] = v>>24;
378 p[1] = v>>16;
379 p[2] = v>>8;
380 p[3] = v;
381}
drh6f11bef2004-05-13 01:12:56 +0000382
drh9e572e62004-04-23 23:43:10 +0000383/*
drhab01f612004-05-22 02:55:23 +0000384** Routines to read and write variable-length integers. These used to
385** be defined locally, but now we use the varint routines in the util.c
386** file.
drh9e572e62004-04-23 23:43:10 +0000387*/
drh6d2fb152004-05-14 16:50:06 +0000388#define getVarint sqlite3GetVarint
389#define getVarint32 sqlite3GetVarint32
390#define putVarint sqlite3PutVarint
drh0d316a42002-08-11 20:10:47 +0000391
392/*
drh271efa52004-05-30 19:19:05 +0000393** Given a btree page and a cell index (0 means the first cell on
394** the page, 1 means the second cell, and so forth) return a pointer
395** to the cell content.
396**
397** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000398*/
drh43605152004-05-29 21:46:49 +0000399static u8 *findCell(MemPage *pPage, int iCell){
400 u8 *data = pPage->aData;
401 assert( iCell>=0 );
402 assert( iCell<get2byte(&data[pPage->hdrOffset+3]) );
403 return data + get2byte(&data[pPage->cellOffset+2*iCell]);
404}
405
406/*
407** This a more complex version of findCell() that works for
408** pages that do contain overflow cells. See insert
409*/
410static u8 *findOverflowCell(MemPage *pPage, int iCell){
411 int i;
412 for(i=pPage->nOverflow-1; i>=0; i--){
413 if( pPage->aOvfl[i].idx<=iCell ){
414 if( pPage->aOvfl[i].idx==iCell ){
415 return pPage->aOvfl[i].pCell;
416 }
417 iCell--;
418 }
419 }
420 return findCell(pPage, iCell);
421}
422
423/*
424** Parse a cell content block and fill in the CellInfo structure. There
425** are two versions of this function. parseCell() takes a cell index
426** as the second argument and parseCellPtr() takes a pointer to the
427** body of the cell as its second argument.
428*/
429static void parseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000430 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000431 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000432 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000433){
drh271efa52004-05-30 19:19:05 +0000434 int n; /* Number bytes in cell content header */
435 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000436
437 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000438 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000439 n = pPage->childPtrSize;
440 assert( n==4-4*pPage->leaf );
drh8b18dd42004-05-12 19:18:15 +0000441 if( pPage->hasData ){
drh271efa52004-05-30 19:19:05 +0000442 n += getVarint32(&pCell[n], &nPayload);
drh8b18dd42004-05-12 19:18:15 +0000443 }else{
drh271efa52004-05-30 19:19:05 +0000444 nPayload = 0;
drh3aac2dd2004-04-26 14:10:20 +0000445 }
drh6f11bef2004-05-13 01:12:56 +0000446 n += getVarint(&pCell[n], &pInfo->nKey);
447 pInfo->nHeader = n;
drh271efa52004-05-30 19:19:05 +0000448 pInfo->nData = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000449 if( !pPage->intKey ){
450 nPayload += pInfo->nKey;
451 }
drh271efa52004-05-30 19:19:05 +0000452 if( nPayload<=pPage->maxLocal ){
453 /* This is the (easy) common case where the entire payload fits
454 ** on the local page. No overflow is required.
455 */
456 int nSize; /* Total size of cell content in bytes */
drh6f11bef2004-05-13 01:12:56 +0000457 pInfo->nLocal = nPayload;
458 pInfo->iOverflow = 0;
drh271efa52004-05-30 19:19:05 +0000459 nSize = nPayload + n;
460 if( nSize<4 ){
461 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000462 }
drh271efa52004-05-30 19:19:05 +0000463 pInfo->nSize = nSize;
drh6f11bef2004-05-13 01:12:56 +0000464 }else{
drh271efa52004-05-30 19:19:05 +0000465 /* If the payload will not fit completely on the local page, we have
466 ** to decide how much to store locally and how much to spill onto
467 ** overflow pages. The strategy is to minimize the amount of unused
468 ** space on overflow pages while keeping the amount of local storage
469 ** in between minLocal and maxLocal.
470 **
471 ** Warning: changing the way overflow payload is distributed in any
472 ** way will result in an incompatible file format.
473 */
474 int minLocal; /* Minimum amount of payload held locally */
475 int maxLocal; /* Maximum amount of payload held locally */
476 int surplus; /* Overflow payload available for local storage */
477
478 minLocal = pPage->minLocal;
479 maxLocal = pPage->maxLocal;
480 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000481 if( surplus <= maxLocal ){
482 pInfo->nLocal = surplus;
483 }else{
484 pInfo->nLocal = minLocal;
485 }
486 pInfo->iOverflow = pInfo->nLocal + n;
487 pInfo->nSize = pInfo->iOverflow + 4;
488 }
drh3aac2dd2004-04-26 14:10:20 +0000489}
drh43605152004-05-29 21:46:49 +0000490static void parseCell(
491 MemPage *pPage, /* Page containing the cell */
492 int iCell, /* The cell index. First cell is 0 */
493 CellInfo *pInfo /* Fill in this structure */
494){
495 parseCellPtr(pPage, findCell(pPage, iCell), pInfo);
496}
drh3aac2dd2004-04-26 14:10:20 +0000497
498/*
drh43605152004-05-29 21:46:49 +0000499** Compute the total number of bytes that a Cell needs in the cell
500** data area of the btree-page. The return number includes the cell
501** data header and the local payload, but not any overflow page or
502** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000503*/
drh43605152004-05-29 21:46:49 +0000504static int cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000505 CellInfo info;
drh43605152004-05-29 21:46:49 +0000506 parseCell(pPage, iCell, &info);
507 return info.nSize;
508}
509static int cellSizePtr(MemPage *pPage, u8 *pCell){
510 CellInfo info;
511 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000512 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000513}
514
515/*
drhda200cc2004-05-09 11:51:38 +0000516** Do sanity checking on a page. Throw an exception if anything is
517** not right.
518**
519** This routine is used for internal error checking only. It is omitted
520** from most builds.
521*/
522#if defined(BTREE_DEBUG) && !defined(NDEBUG) && 0
523static void _pageIntegrity(MemPage *pPage){
drhb6f41482004-05-14 01:58:11 +0000524 int usableSize;
drhda200cc2004-05-09 11:51:38 +0000525 u8 *data;
drh43605152004-05-29 21:46:49 +0000526 int i, j, idx, c, pc, hdr, nFree;
527 int cellOffset;
528 int nCell, cellLimit;
drhda200cc2004-05-09 11:51:38 +0000529 u8 used[MX_PAGE_SIZE];
530
drhb6f41482004-05-14 01:58:11 +0000531 usableSize = pPage->pBt->usableSize;
532 assert( pPage->aData==&((unsigned char*)pPage)[-pPage->pBt->pageSize] );
drhda200cc2004-05-09 11:51:38 +0000533 hdr = pPage->hdrOffset;
534 assert( hdr==(pPage->pgno==1 ? 100 : 0) );
535 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
536 c = pPage->aData[hdr];
537 if( pPage->isInit ){
538 assert( pPage->leaf == ((c & PTF_LEAF)!=0) );
539 assert( pPage->zeroData == ((c & PTF_ZERODATA)!=0) );
drh8b18dd42004-05-12 19:18:15 +0000540 assert( pPage->leafData == ((c & PTF_LEAFDATA)!=0) );
541 assert( pPage->intKey == ((c & (PTF_INTKEY|PTF_LEAFDATA))!=0) );
542 assert( pPage->hasData ==
543 !(pPage->zeroData || (!pPage->leaf && pPage->leafData)) );
drh43605152004-05-29 21:46:49 +0000544 assert( pPage->cellOffset==pPage->hdrOffset+12-4*pPage->leaf );
545 assert( pPage->nCell = get2byte(&pPage->aData[hdr+3]) );
drhda200cc2004-05-09 11:51:38 +0000546 }
547 data = pPage->aData;
drhb6f41482004-05-14 01:58:11 +0000548 memset(used, 0, usableSize);
drhda200cc2004-05-09 11:51:38 +0000549 for(i=0; i<hdr+10-pPage->leaf*4; i++) used[i] = 1;
550 nFree = 0;
551 pc = get2byte(&data[hdr+1]);
552 while( pc ){
553 int size;
drhb6f41482004-05-14 01:58:11 +0000554 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +0000555 size = get2byte(&data[pc+2]);
drhb6f41482004-05-14 01:58:11 +0000556 assert( pc+size<=usableSize );
drhda200cc2004-05-09 11:51:38 +0000557 nFree += size;
558 for(i=pc; i<pc+size; i++){
559 assert( used[i]==0 );
560 used[i] = 1;
561 }
562 pc = get2byte(&data[pc]);
563 }
drhda200cc2004-05-09 11:51:38 +0000564 idx = 0;
drh43605152004-05-29 21:46:49 +0000565 nCell = get2byte(&data[hdr+3]);
566 cellLimit = get2byte(&data[hdr+5]);
567 assert( pPage->isInit==0
568 || pPage->nFree==nFree+data[hdr+7]+cellLimit-(cellOffset+2*nCell) );
569 cellOffset = pPage->cellOffset;
570 for(i=0; i<nCell; i++){
drhda200cc2004-05-09 11:51:38 +0000571 int size;
drh43605152004-05-29 21:46:49 +0000572 pc = get2byte(&data[cellOffset+2*i]);
drhb6f41482004-05-14 01:58:11 +0000573 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +0000574 size = cellSize(pPage, &data[pc]);
drhb6f41482004-05-14 01:58:11 +0000575 assert( pc+size<=usableSize );
drh43605152004-05-29 21:46:49 +0000576 for(j=pc; j<pc+size; j++){
577 assert( used[j]==0 );
578 used[j] = 1;
drhda200cc2004-05-09 11:51:38 +0000579 }
drhda200cc2004-05-09 11:51:38 +0000580 }
drh43605152004-05-29 21:46:49 +0000581 for(i=cellOffset+2*nCell; i<cellimit; i++){
582 assert( used[i]==0 );
583 used[i] = 1;
584 }
drhda200cc2004-05-09 11:51:38 +0000585 nFree = 0;
drhb6f41482004-05-14 01:58:11 +0000586 for(i=0; i<usableSize; i++){
drhda200cc2004-05-09 11:51:38 +0000587 assert( used[i]<=1 );
588 if( used[i]==0 ) nFree++;
589 }
drh43605152004-05-29 21:46:49 +0000590 assert( nFree==data[hdr+7] );
drhda200cc2004-05-09 11:51:38 +0000591}
592#define pageIntegrity(X) _pageIntegrity(X)
593#else
594# define pageIntegrity(X)
595#endif
596
597/*
drh72f82862001-05-24 21:06:34 +0000598** Defragment the page given. All Cells are moved to the
599** beginning of the page and all free space is collected
600** into one big FreeBlk at the end of the page.
drh365d68f2001-05-11 11:02:46 +0000601*/
drh9e572e62004-04-23 23:43:10 +0000602static void defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000603 int i; /* Loop counter */
604 int pc; /* Address of a i-th cell */
605 int addr; /* Offset of first byte after cell pointer array */
606 int hdr; /* Offset to the page header */
607 int size; /* Size of a cell */
608 int usableSize; /* Number of usable bytes on a page */
609 int cellOffset; /* Offset to the cell pointer array */
610 int brk; /* Offset to the cell content area */
611 int nCell; /* Number of cells on the page */
612 unsigned char *data; /* The page data */
613 unsigned char temp[MX_PAGE_SIZE]; /* Temp holding area for cell content */
drh2af926b2001-05-15 00:39:25 +0000614
drha34b6762004-05-07 13:30:42 +0000615 assert( sqlite3pager_iswriteable(pPage->aData) );
drh9e572e62004-04-23 23:43:10 +0000616 assert( pPage->pBt!=0 );
drhb6f41482004-05-14 01:58:11 +0000617 assert( pPage->pBt->usableSize <= MX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000618 assert( pPage->nOverflow==0 );
619 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000620 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000621 cellOffset = pPage->cellOffset;
622 nCell = pPage->nCell;
623 assert( nCell==get2byte(&data[hdr+3]) );
624 usableSize = pPage->pBt->usableSize;
625 brk = get2byte(&data[hdr+5]);
626 memcpy(&temp[brk], &data[brk], usableSize - brk);
627 brk = usableSize;
628 for(i=0; i<nCell; i++){
629 u8 *pAddr; /* The i-th cell pointer */
630 pAddr = &data[cellOffset + i*2];
631 pc = get2byte(pAddr);
632 assert( pc<pPage->pBt->usableSize );
633 size = cellSizePtr(pPage, &temp[pc]);
634 brk -= size;
635 memcpy(&data[brk], &temp[pc], size);
636 put2byte(pAddr, brk);
drh2af926b2001-05-15 00:39:25 +0000637 }
drh43605152004-05-29 21:46:49 +0000638 assert( brk>=cellOffset+2*nCell );
639 put2byte(&data[hdr+5], brk);
640 data[hdr+1] = 0;
641 data[hdr+2] = 0;
642 data[hdr+7] = 0;
643 addr = cellOffset+2*nCell;
644 memset(&data[addr], 0, brk-addr);
drh365d68f2001-05-11 11:02:46 +0000645}
646
drha059ad02001-04-17 20:09:11 +0000647/*
drh43605152004-05-29 21:46:49 +0000648** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +0000649**
drh9e572e62004-04-23 23:43:10 +0000650** Return the index into pPage->aData[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000651** the new allocation. Or return 0 if there is not enough free
652** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000653**
drh72f82862001-05-24 21:06:34 +0000654** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000655** nBytes of contiguous free space, then this routine automatically
656** calls defragementPage() to consolidate all free space before
657** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000658*/
drh9e572e62004-04-23 23:43:10 +0000659static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +0000660 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +0000661 int size;
drh24cd67e2004-05-10 16:18:47 +0000662 int nFrag;
drh43605152004-05-29 21:46:49 +0000663 int top;
664 int nCell;
665 int cellOffset;
drh9e572e62004-04-23 23:43:10 +0000666 unsigned char *data;
drh43605152004-05-29 21:46:49 +0000667
drh9e572e62004-04-23 23:43:10 +0000668 data = pPage->aData;
drha34b6762004-05-07 13:30:42 +0000669 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +0000670 assert( pPage->pBt );
671 if( nByte<4 ) nByte = 4;
drh43605152004-05-29 21:46:49 +0000672 if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
673 pPage->nFree -= nByte;
drh9e572e62004-04-23 23:43:10 +0000674 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000675
676 nFrag = data[hdr+7];
677 if( nFrag<60 ){
678 /* Search the freelist looking for a slot big enough to satisfy the
679 ** space request. */
680 addr = hdr+1;
681 while( (pc = get2byte(&data[addr]))>0 ){
682 size = get2byte(&data[pc+2]);
683 if( size>=nByte ){
684 if( size<nByte+4 ){
685 memcpy(&data[addr], &data[pc], 2);
686 data[hdr+7] = nFrag + size - nByte;
687 return pc;
688 }else{
689 put2byte(&data[pc+2], size-nByte);
690 return pc + size - nByte;
691 }
692 }
693 addr = pc;
drh9e572e62004-04-23 23:43:10 +0000694 }
695 }
drh43605152004-05-29 21:46:49 +0000696
697 /* Allocate memory from the gap in between the cell pointer array
698 ** and the cell content area.
699 */
700 top = get2byte(&data[hdr+5]);
701 nCell = get2byte(&data[hdr+3]);
702 cellOffset = pPage->cellOffset;
703 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
704 defragmentPage(pPage);
705 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +0000706 }
drh43605152004-05-29 21:46:49 +0000707 top -= nByte;
708 assert( cellOffset + 2*nCell <= top );
709 put2byte(&data[hdr+5], top);
710 return top;
drh7e3b0a02001-04-28 16:52:40 +0000711}
712
713/*
drh9e572e62004-04-23 23:43:10 +0000714** Return a section of the pPage->aData to the freelist.
715** The first byte of the new free block is pPage->aDisk[start]
716** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +0000717**
718** Most of the effort here is involved in coalesing adjacent
719** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000720*/
drh9e572e62004-04-23 23:43:10 +0000721static void freeSpace(MemPage *pPage, int start, int size){
722 int end = start + size; /* End of the segment being freed */
drh43605152004-05-29 21:46:49 +0000723 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +0000724 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +0000725
drh9e572e62004-04-23 23:43:10 +0000726 assert( pPage->pBt!=0 );
drha34b6762004-05-07 13:30:42 +0000727 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +0000728 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
drhb6f41482004-05-14 01:58:11 +0000729 assert( end<=pPage->pBt->usableSize );
drh9e572e62004-04-23 23:43:10 +0000730 if( size<4 ) size = 4;
731
732 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +0000733 hdr = pPage->hdrOffset;
734 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +0000735 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +0000736 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000737 assert( pbegin>addr );
738 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +0000739 }
drhb6f41482004-05-14 01:58:11 +0000740 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000741 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +0000742 put2byte(&data[addr], start);
743 put2byte(&data[start], pbegin);
744 put2byte(&data[start+2], size);
drh2af926b2001-05-15 00:39:25 +0000745 pPage->nFree += size;
drh9e572e62004-04-23 23:43:10 +0000746
747 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +0000748 addr = pPage->hdrOffset + 1;
749 while( (pbegin = get2byte(&data[addr]))>0 ){
drh9e572e62004-04-23 23:43:10 +0000750 int pnext, psize;
drh3aac2dd2004-04-26 14:10:20 +0000751 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +0000752 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +0000753 pnext = get2byte(&data[pbegin]);
754 psize = get2byte(&data[pbegin+2]);
755 if( pbegin + psize + 3 >= pnext && pnext>0 ){
756 int frag = pnext - (pbegin+psize);
drh43605152004-05-29 21:46:49 +0000757 assert( frag<=data[pPage->hdrOffset+7] );
758 data[pPage->hdrOffset+7] -= frag;
drh9e572e62004-04-23 23:43:10 +0000759 put2byte(&data[pbegin], get2byte(&data[pnext]));
760 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
761 }else{
drh3aac2dd2004-04-26 14:10:20 +0000762 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +0000763 }
764 }
drh7e3b0a02001-04-28 16:52:40 +0000765
drh43605152004-05-29 21:46:49 +0000766 /* If the cell content area begins with a freeblock, remove it. */
767 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
768 int top;
769 pbegin = get2byte(&data[hdr+1]);
770 memcpy(&data[hdr+1], &data[pbegin], 2);
771 top = get2byte(&data[hdr+5]);
772 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
drh4b70f112004-05-02 21:12:19 +0000773 }
drh4b70f112004-05-02 21:12:19 +0000774}
775
776/*
drh271efa52004-05-30 19:19:05 +0000777** Decode the flags byte (the first byte of the header) for a page
778** and initialize fields of the MemPage structure accordingly.
779*/
780static void decodeFlags(MemPage *pPage, int flagByte){
781 Btree *pBt; /* A copy of pPage->pBt */
782
783 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
784 pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
785 pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
786 pPage->leaf = (flagByte & PTF_LEAF)!=0;
787 pPage->childPtrSize = 4*(pPage->leaf==0);
788 pBt = pPage->pBt;
789 if( flagByte & PTF_LEAFDATA ){
790 pPage->leafData = 1;
791 pPage->maxLocal = pBt->maxLeaf;
792 pPage->minLocal = pBt->minLeaf;
793 }else{
794 pPage->leafData = 0;
795 pPage->maxLocal = pBt->maxLocal;
796 pPage->minLocal = pBt->minLocal;
797 }
798 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
799}
800
801/*
drh7e3b0a02001-04-28 16:52:40 +0000802** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000803**
drhbd03cae2001-06-02 02:40:57 +0000804** The pParent parameter must be a pointer to the MemPage which
drh9e572e62004-04-23 23:43:10 +0000805** is the parent of the page being initialized. The root of a
806** BTree has no parent and so for that page, pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000807**
drh72f82862001-05-24 21:06:34 +0000808** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +0000809** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +0000810** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
811** guarantee that the page is well-formed. It only shows that
812** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000813*/
drh9e572e62004-04-23 23:43:10 +0000814static int initPage(
drh3aac2dd2004-04-26 14:10:20 +0000815 MemPage *pPage, /* The page to be initialized */
drh9e572e62004-04-23 23:43:10 +0000816 MemPage *pParent /* The parent. Might be NULL */
817){
drh271efa52004-05-30 19:19:05 +0000818 int pc; /* Address of a freeblock within pPage->aData[] */
819 int i; /* Loop counter */
820 int hdr; /* Offset to beginning of page header */
821 u8 *data; /* Equal to pPage->aData */
822 int usableSize; /* Amount of usable space on each page */
823 int cellOffset; /* Offset from start of page to first cell pointer */
824 int nFree; /* Number of unused bytes on the page */
825 int top; /* First byte of the cell content area */
drh2af926b2001-05-15 00:39:25 +0000826
drh3aac2dd2004-04-26 14:10:20 +0000827 assert( pPage->pBt!=0 );
drh4b70f112004-05-02 21:12:19 +0000828 assert( pParent==0 || pParent->pBt==pPage->pBt );
drha34b6762004-05-07 13:30:42 +0000829 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
drhde647132004-05-07 17:57:49 +0000830 assert( pPage->aData == &((unsigned char*)pPage)[-pPage->pBt->pageSize] );
drhda200cc2004-05-09 11:51:38 +0000831 assert( pPage->pParent==0 || pPage->pParent==pParent );
drh10617cd2004-05-14 15:27:27 +0000832 assert( pPage->pParent==pParent || !pPage->isInit );
833 if( pPage->isInit ) return SQLITE_OK;
drhda200cc2004-05-09 11:51:38 +0000834 if( pPage->pParent==0 && pParent!=0 ){
835 pPage->pParent = pParent;
drha34b6762004-05-07 13:30:42 +0000836 sqlite3pager_ref(pParent->aData);
drh5e2f8b92001-05-28 00:41:15 +0000837 }
drhde647132004-05-07 17:57:49 +0000838 hdr = pPage->hdrOffset;
drha34b6762004-05-07 13:30:42 +0000839 data = pPage->aData;
drh271efa52004-05-30 19:19:05 +0000840 decodeFlags(pPage, data[hdr]);
drh43605152004-05-29 21:46:49 +0000841 pPage->nOverflow = 0;
drhc8629a12004-05-08 20:07:40 +0000842 pPage->idxShift = 0;
drhb6f41482004-05-14 01:58:11 +0000843 usableSize = pPage->pBt->usableSize;
drh43605152004-05-29 21:46:49 +0000844 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
845 top = get2byte(&data[hdr+5]);
846 pPage->nCell = get2byte(&data[hdr+3]);
drh9e572e62004-04-23 23:43:10 +0000847
848 /* Compute the total free space on the page */
drh9e572e62004-04-23 23:43:10 +0000849 pc = get2byte(&data[hdr+1]);
drh43605152004-05-29 21:46:49 +0000850 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
drh3add3672004-05-15 00:29:24 +0000851 i = 0;
drh9e572e62004-04-23 23:43:10 +0000852 while( pc>0 ){
853 int next, size;
drhb6f41482004-05-14 01:58:11 +0000854 if( pc>=usableSize ) return SQLITE_CORRUPT;
drh3add3672004-05-15 00:29:24 +0000855 if( i++>MX_PAGE_SIZE ) return SQLITE_CORRUPT;
drh9e572e62004-04-23 23:43:10 +0000856 next = get2byte(&data[pc]);
857 size = get2byte(&data[pc+2]);
drh3aac2dd2004-04-26 14:10:20 +0000858 if( next>0 && next<=pc+size+3 ) return SQLITE_CORRUPT;
drh3add3672004-05-15 00:29:24 +0000859 nFree += size;
drh9e572e62004-04-23 23:43:10 +0000860 pc = next;
861 }
drh3add3672004-05-15 00:29:24 +0000862 pPage->nFree = nFree;
863 if( nFree>=usableSize ) return SQLITE_CORRUPT;
drh9e572e62004-04-23 23:43:10 +0000864
drhde647132004-05-07 17:57:49 +0000865 pPage->isInit = 1;
drhda200cc2004-05-09 11:51:38 +0000866 pageIntegrity(pPage);
drh9e572e62004-04-23 23:43:10 +0000867 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +0000868}
869
870/*
drh8b2f49b2001-06-08 00:21:52 +0000871** Set up a raw page so that it looks like a database page holding
872** no entries.
drhbd03cae2001-06-02 02:40:57 +0000873*/
drh9e572e62004-04-23 23:43:10 +0000874static void zeroPage(MemPage *pPage, int flags){
875 unsigned char *data = pPage->aData;
876 Btree *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +0000877 int hdr = pPage->hdrOffset;
drh9e572e62004-04-23 23:43:10 +0000878 int first;
879
drhda200cc2004-05-09 11:51:38 +0000880 assert( sqlite3pager_pagenumber(data)==pPage->pgno );
881 assert( &data[pBt->pageSize] == (unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +0000882 assert( sqlite3pager_iswriteable(data) );
drhb6f41482004-05-14 01:58:11 +0000883 memset(&data[hdr], 0, pBt->usableSize - hdr);
drh9e572e62004-04-23 23:43:10 +0000884 data[hdr] = flags;
drh43605152004-05-29 21:46:49 +0000885 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
886 memset(&data[hdr+1], 0, 4);
887 data[hdr+7] = 0;
888 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +0000889 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +0000890 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +0000891 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +0000892 pPage->cellOffset = first;
893 pPage->nOverflow = 0;
drhda200cc2004-05-09 11:51:38 +0000894 pPage->idxShift = 0;
drh43605152004-05-29 21:46:49 +0000895 pPage->nCell = 0;
drhda200cc2004-05-09 11:51:38 +0000896 pPage->isInit = 1;
897 pageIntegrity(pPage);
drhbd03cae2001-06-02 02:40:57 +0000898}
899
900/*
drh3aac2dd2004-04-26 14:10:20 +0000901** Get a page from the pager. Initialize the MemPage.pBt and
902** MemPage.aData elements if needed.
903*/
904static int getPage(Btree *pBt, Pgno pgno, MemPage **ppPage){
905 int rc;
906 unsigned char *aData;
907 MemPage *pPage;
drha34b6762004-05-07 13:30:42 +0000908 rc = sqlite3pager_get(pBt->pPager, pgno, (void**)&aData);
drh3aac2dd2004-04-26 14:10:20 +0000909 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +0000910 pPage = (MemPage*)&aData[pBt->pageSize];
drh3aac2dd2004-04-26 14:10:20 +0000911 pPage->aData = aData;
912 pPage->pBt = pBt;
913 pPage->pgno = pgno;
drhde647132004-05-07 17:57:49 +0000914 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
drh3aac2dd2004-04-26 14:10:20 +0000915 *ppPage = pPage;
916 return SQLITE_OK;
917}
918
919/*
drhde647132004-05-07 17:57:49 +0000920** Get a page from the pager and initialize it. This routine
921** is just a convenience wrapper around separate calls to
922** getPage() and initPage().
923*/
924static int getAndInitPage(
925 Btree *pBt, /* The database file */
926 Pgno pgno, /* Number of the page to get */
927 MemPage **ppPage, /* Write the page pointer here */
928 MemPage *pParent /* Parent of the page */
929){
930 int rc;
931 rc = getPage(pBt, pgno, ppPage);
drh10617cd2004-05-14 15:27:27 +0000932 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
drhde647132004-05-07 17:57:49 +0000933 rc = initPage(*ppPage, pParent);
934 }
935 return rc;
936}
937
938/*
drh3aac2dd2004-04-26 14:10:20 +0000939** Release a MemPage. This should be called once for each prior
940** call to getPage.
941*/
drh4b70f112004-05-02 21:12:19 +0000942static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +0000943 if( pPage ){
944 assert( pPage->aData );
945 assert( pPage->pBt );
946 assert( &pPage->aData[pPage->pBt->pageSize]==(unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +0000947 sqlite3pager_unref(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +0000948 }
949}
950
951/*
drh72f82862001-05-24 21:06:34 +0000952** This routine is called when the reference count for a page
953** reaches zero. We need to unref the pParent pointer when that
954** happens.
955*/
drhb6f41482004-05-14 01:58:11 +0000956static void pageDestructor(void *pData, int pageSize){
957 MemPage *pPage = (MemPage*)&((char*)pData)[pageSize];
drh72f82862001-05-24 21:06:34 +0000958 if( pPage->pParent ){
959 MemPage *pParent = pPage->pParent;
960 pPage->pParent = 0;
drha34b6762004-05-07 13:30:42 +0000961 releasePage(pParent);
drh72f82862001-05-24 21:06:34 +0000962 }
drh3aac2dd2004-04-26 14:10:20 +0000963 pPage->isInit = 0;
drh72f82862001-05-24 21:06:34 +0000964}
965
966/*
drha6abd042004-06-09 17:37:22 +0000967** During a rollback, when the pager reloads information into the cache
968** so that the cache is restored to its original state at the start of
969** the transaction, for each page restored this routine is called.
970**
971** This routine needs to reset the extra data section at the end of the
972** page to agree with the restored data.
973*/
974static void pageReinit(void *pData, int pageSize){
975 MemPage *pPage = (MemPage*)&((char*)pData)[pageSize];
976 if( pPage->isInit ){
977 pPage->isInit = 0;
978 initPage(pPage, pPage->pParent);
979 }
980}
981
982/*
drh306dc212001-05-21 13:45:10 +0000983** Open a new database.
984**
985** Actually, this routine just sets up the internal data structures
drh72f82862001-05-24 21:06:34 +0000986** for accessing the database. We do not open the database file
987** until the first page is loaded.
drh382c0242001-10-06 16:33:02 +0000988**
989** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +0000990** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +0000991** database file will be deleted when sqlite3BtreeClose() is called.
drha059ad02001-04-17 20:09:11 +0000992*/
drh23e11ca2004-05-04 17:27:28 +0000993int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +0000994 const char *zFilename, /* Name of the file containing the BTree database */
995 Btree **ppBtree, /* Pointer to new Btree object written here */
996 int nCache, /* Number of cache pages */
danielk197724162fe2004-06-04 06:22:00 +0000997 int flags, /* Options */
998 void *pBusyHandler /* Busy callback info passed to pager layer */
drh6019e162001-07-02 17:51:45 +0000999){
drha059ad02001-04-17 20:09:11 +00001000 Btree *pBt;
drha34b6762004-05-07 13:30:42 +00001001 int rc;
drha059ad02001-04-17 20:09:11 +00001002
drhd62d3d02003-01-24 12:14:20 +00001003 /*
1004 ** The following asserts make sure that structures used by the btree are
1005 ** the right size. This is to guard against size changes that result
1006 ** when compiling on a different architecture.
1007 */
drh4a1c3802004-05-12 15:15:47 +00001008 assert( sizeof(i64)==8 );
drh9e572e62004-04-23 23:43:10 +00001009 assert( sizeof(u64)==8 );
drhd62d3d02003-01-24 12:14:20 +00001010 assert( sizeof(u32)==4 );
1011 assert( sizeof(u16)==2 );
1012 assert( sizeof(Pgno)==4 );
drhd62d3d02003-01-24 12:14:20 +00001013 assert( sizeof(ptr)==sizeof(char*) );
1014 assert( sizeof(uptr)==sizeof(ptr) );
1015
drha059ad02001-04-17 20:09:11 +00001016 pBt = sqliteMalloc( sizeof(*pBt) );
1017 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +00001018 *ppBtree = 0;
drha059ad02001-04-17 20:09:11 +00001019 return SQLITE_NOMEM;
1020 }
drh6019e162001-07-02 17:51:45 +00001021 if( nCache<10 ) nCache = 10;
drha34b6762004-05-07 13:30:42 +00001022 rc = sqlite3pager_open(&pBt->pPager, zFilename, nCache, EXTRA_SIZE,
danielk197724162fe2004-06-04 06:22:00 +00001023 (flags & BTREE_OMIT_JOURNAL)==0, pBusyHandler);
drha059ad02001-04-17 20:09:11 +00001024 if( rc!=SQLITE_OK ){
drha34b6762004-05-07 13:30:42 +00001025 if( pBt->pPager ) sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001026 sqliteFree(pBt);
1027 *ppBtree = 0;
1028 return rc;
1029 }
drha34b6762004-05-07 13:30:42 +00001030 sqlite3pager_set_destructor(pBt->pPager, pageDestructor);
drha6abd042004-06-09 17:37:22 +00001031 sqlite3pager_set_reiniter(pBt->pPager, pageReinit);
drha059ad02001-04-17 20:09:11 +00001032 pBt->pCursor = 0;
drha34b6762004-05-07 13:30:42 +00001033 pBt->pPage1 = 0;
1034 pBt->readOnly = sqlite3pager_isreadonly(pBt->pPager);
drh4b70f112004-05-02 21:12:19 +00001035 pBt->pageSize = SQLITE_PAGE_SIZE; /* FIX ME - read from header */
drhb6f41482004-05-14 01:58:11 +00001036 pBt->usableSize = pBt->pageSize;
drh6f11bef2004-05-13 01:12:56 +00001037 pBt->maxEmbedFrac = 64; /* FIX ME - read from header */
1038 pBt->minEmbedFrac = 32; /* FIX ME - read from header */
1039 pBt->minLeafFrac = 32; /* FIX ME - read from header */
drh3a4c1412004-05-09 20:40:11 +00001040
drha059ad02001-04-17 20:09:11 +00001041 *ppBtree = pBt;
1042 return SQLITE_OK;
1043}
1044
1045/*
1046** Close an open database and invalidate all cursors.
1047*/
drh3aac2dd2004-04-26 14:10:20 +00001048int sqlite3BtreeClose(Btree *pBt){
drha059ad02001-04-17 20:09:11 +00001049 while( pBt->pCursor ){
drh3aac2dd2004-04-26 14:10:20 +00001050 sqlite3BtreeCloseCursor(pBt->pCursor);
drha059ad02001-04-17 20:09:11 +00001051 }
drha34b6762004-05-07 13:30:42 +00001052 sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001053 sqliteFree(pBt);
1054 return SQLITE_OK;
1055}
1056
1057/*
drhda47d772002-12-02 04:25:19 +00001058** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001059**
1060** The maximum number of cache pages is set to the absolute
1061** value of mxPage. If mxPage is negative, the pager will
1062** operate asynchronously - it will not stop to do fsync()s
1063** to insure data is written to the disk surface before
1064** continuing. Transactions still work if synchronous is off,
1065** and the database cannot be corrupted if this program
1066** crashes. But if the operating system crashes or there is
1067** an abrupt power failure when synchronous is off, the database
1068** could be left in an inconsistent and unrecoverable state.
1069** Synchronous is on by default so database corruption is not
1070** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001071*/
drh23e11ca2004-05-04 17:27:28 +00001072int sqlite3BtreeSetCacheSize(Btree *pBt, int mxPage){
drha34b6762004-05-07 13:30:42 +00001073 sqlite3pager_set_cachesize(pBt->pPager, mxPage);
drhf57b14a2001-09-14 18:54:08 +00001074 return SQLITE_OK;
1075}
1076
1077/*
drh973b6e32003-02-12 14:09:42 +00001078** Change the way data is synced to disk in order to increase or decrease
1079** how well the database resists damage due to OS crashes and power
1080** failures. Level 1 is the same as asynchronous (no syncs() occur and
1081** there is a high probability of damage) Level 2 is the default. There
1082** is a very low but non-zero probability of damage. Level 3 reduces the
1083** probability of damage to near zero but with a write performance reduction.
1084*/
drh3aac2dd2004-04-26 14:10:20 +00001085int sqlite3BtreeSetSafetyLevel(Btree *pBt, int level){
drha34b6762004-05-07 13:30:42 +00001086 sqlite3pager_set_safety_level(pBt->pPager, level);
drh973b6e32003-02-12 14:09:42 +00001087 return SQLITE_OK;
1088}
1089
1090/*
drha34b6762004-05-07 13:30:42 +00001091** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001092** also acquire a readlock on that file.
1093**
1094** SQLITE_OK is returned on success. If the file is not a
1095** well-formed database file, then SQLITE_CORRUPT is returned.
1096** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
1097** is returned if we run out of memory. SQLITE_PROTOCOL is returned
1098** if there is a locking protocol violation.
1099*/
1100static int lockBtree(Btree *pBt){
1101 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001102 MemPage *pPage1;
drha34b6762004-05-07 13:30:42 +00001103 if( pBt->pPage1 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001104 rc = getPage(pBt, 1, &pPage1);
drh306dc212001-05-21 13:45:10 +00001105 if( rc!=SQLITE_OK ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00001106
drh306dc212001-05-21 13:45:10 +00001107
1108 /* Do some checking to help insure the file we opened really is
1109 ** a valid database file.
1110 */
drhb6f41482004-05-14 01:58:11 +00001111 rc = SQLITE_NOTADB;
drha34b6762004-05-07 13:30:42 +00001112 if( sqlite3pager_pagecount(pBt->pPager)>0 ){
drhb6f41482004-05-14 01:58:11 +00001113 u8 *page1 = pPage1->aData;
1114 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001115 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001116 }
drhb6f41482004-05-14 01:58:11 +00001117 if( page1[18]>1 || page1[19]>1 ){
1118 goto page1_init_failed;
1119 }
1120 pBt->pageSize = get2byte(&page1[16]);
1121 pBt->usableSize = pBt->pageSize - page1[20];
1122 if( pBt->usableSize<500 ){
1123 goto page1_init_failed;
1124 }
1125 pBt->maxEmbedFrac = page1[21];
1126 pBt->minEmbedFrac = page1[22];
1127 pBt->minLeafFrac = page1[23];
drh306dc212001-05-21 13:45:10 +00001128 }
drhb6f41482004-05-14 01:58:11 +00001129
1130 /* maxLocal is the maximum amount of payload to store locally for
1131 ** a cell. Make sure it is small enough so that at least minFanout
1132 ** cells can will fit on one page. We assume a 10-byte page header.
1133 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001134 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001135 ** 4-byte child pointer
1136 ** 9-byte nKey value
1137 ** 4-byte nData value
1138 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001139 ** So a cell consists of a 2-byte poiner, a header which is as much as
1140 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1141 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001142 */
drh43605152004-05-29 21:46:49 +00001143 pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
1144 pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
1145 pBt->maxLeaf = pBt->usableSize - 35;
1146 pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
drhb6f41482004-05-14 01:58:11 +00001147 if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
1148 goto page1_init_failed;
1149 }
1150 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE );
drh3aac2dd2004-04-26 14:10:20 +00001151 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001152 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001153
drh72f82862001-05-24 21:06:34 +00001154page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001155 releasePage(pPage1);
1156 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001157 return rc;
drh306dc212001-05-21 13:45:10 +00001158}
1159
1160/*
drhb8ca3072001-12-05 00:21:20 +00001161** If there are no outstanding cursors and we are not in the middle
1162** of a transaction but there is a read lock on the database, then
1163** this routine unrefs the first page of the database file which
1164** has the effect of releasing the read lock.
1165**
1166** If there are any outstanding cursors, this routine is a no-op.
1167**
1168** If there is a transaction in progress, this routine is a no-op.
1169*/
1170static void unlockBtreeIfUnused(Btree *pBt){
danielk1977ee5741e2004-05-31 10:01:34 +00001171 if( pBt->inTrans==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
drh51c6d962004-06-06 00:42:25 +00001172 if( pBt->pPage1->aData==0 ){
1173 MemPage *pPage = pBt->pPage1;
1174 pPage->aData = &((char*)pPage)[-pBt->pageSize];
1175 pPage->pBt = pBt;
1176 pPage->pgno = 1;
1177 }
drh3aac2dd2004-04-26 14:10:20 +00001178 releasePage(pBt->pPage1);
1179 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00001180 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001181 }
1182}
1183
1184/*
drh9e572e62004-04-23 23:43:10 +00001185** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001186** file.
drh8b2f49b2001-06-08 00:21:52 +00001187*/
1188static int newDatabase(Btree *pBt){
drh9e572e62004-04-23 23:43:10 +00001189 MemPage *pP1;
1190 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001191 int rc;
drhde647132004-05-07 17:57:49 +00001192 if( sqlite3pager_pagecount(pBt->pPager)>0 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001193 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00001194 assert( pP1!=0 );
1195 data = pP1->aData;
drha34b6762004-05-07 13:30:42 +00001196 rc = sqlite3pager_write(data);
drh8b2f49b2001-06-08 00:21:52 +00001197 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00001198 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
1199 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00001200 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00001201 data[18] = 1;
1202 data[19] = 1;
drhb6f41482004-05-14 01:58:11 +00001203 data[20] = pBt->pageSize - pBt->usableSize;
1204 data[21] = pBt->maxEmbedFrac;
1205 data[22] = pBt->minEmbedFrac;
1206 data[23] = pBt->minLeafFrac;
1207 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00001208 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drh8b2f49b2001-06-08 00:21:52 +00001209 return SQLITE_OK;
1210}
1211
1212/*
danielk1977ee5741e2004-05-31 10:01:34 +00001213** Attempt to start a new transaction. A write-transaction
1214** is started if the second argument is true, otherwise a read-
1215** transaction.
drh8b2f49b2001-06-08 00:21:52 +00001216**
danielk1977ee5741e2004-05-31 10:01:34 +00001217** A write-transaction must be started before attempting any
1218** changes to the database. None of the following routines
1219** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00001220**
drh23e11ca2004-05-04 17:27:28 +00001221** sqlite3BtreeCreateTable()
1222** sqlite3BtreeCreateIndex()
1223** sqlite3BtreeClearTable()
1224** sqlite3BtreeDropTable()
1225** sqlite3BtreeInsert()
1226** sqlite3BtreeDelete()
1227** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00001228**
1229** If wrflag is true, then nMaster specifies the maximum length of
1230** a master journal file name supplied later via sqlite3BtreeSync().
1231** This is so that appropriate space can be allocated in the journal file
1232** when it is created..
drha059ad02001-04-17 20:09:11 +00001233*/
danielk197713adf8a2004-06-03 16:08:41 +00001234int sqlite3BtreeBeginTrans(Btree *pBt, int wrflag, int nMaster){
danielk1977ee5741e2004-05-31 10:01:34 +00001235 int rc = SQLITE_OK;
1236
1237 /* If the btree is already in a write-transaction, or it
1238 ** is already in a read-transaction and a read-transaction
1239 ** is requested, this is a no-op.
1240 */
1241 if( pBt->inTrans==TRANS_WRITE ||
1242 (pBt->inTrans==TRANS_READ && !wrflag) ){
1243 return SQLITE_OK;
1244 }
1245 if( pBt->readOnly && wrflag ){
1246 return SQLITE_READONLY;
1247 }
1248
drh3aac2dd2004-04-26 14:10:20 +00001249 if( pBt->pPage1==0 ){
drh7e3b0a02001-04-28 16:52:40 +00001250 rc = lockBtree(pBt);
danielk1977ee5741e2004-05-31 10:01:34 +00001251 }
1252
1253 if( rc==SQLITE_OK && wrflag ){
drhc9e06862004-06-09 20:03:08 +00001254 rc = sqlite3pager_begin(pBt->pPage1->aData, nMaster);
danielk1977ee5741e2004-05-31 10:01:34 +00001255 if( rc==SQLITE_OK ){
1256 rc = newDatabase(pBt);
drh8c42ca92001-06-22 19:15:00 +00001257 }
drha059ad02001-04-17 20:09:11 +00001258 }
danielk1977ee5741e2004-05-31 10:01:34 +00001259
drhf74b8d92002-09-01 23:20:45 +00001260 if( rc==SQLITE_OK ){
danielk1977ee5741e2004-05-31 10:01:34 +00001261 pBt->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
1262 if( wrflag ) pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001263 }else{
1264 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001265 }
drhb8ca3072001-12-05 00:21:20 +00001266 return rc;
drha059ad02001-04-17 20:09:11 +00001267}
1268
1269/*
drh2aa679f2001-06-25 02:11:07 +00001270** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00001271**
1272** This will release the write lock on the database file. If there
1273** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00001274*/
drh3aac2dd2004-04-26 14:10:20 +00001275int sqlite3BtreeCommit(Btree *pBt){
danielk1977ee5741e2004-05-31 10:01:34 +00001276 int rc = SQLITE_OK;
1277 if( pBt->inTrans==TRANS_WRITE ){
1278 rc = sqlite3pager_commit(pBt->pPager);
1279 }
1280 pBt->inTrans = TRANS_NONE;
drh3aac2dd2004-04-26 14:10:20 +00001281 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00001282 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001283 return rc;
1284}
1285
danielk1977fbcd5852004-06-15 02:44:18 +00001286#ifndef NDEBUG
1287/*
1288** Return the number of write-cursors open on this handle. This is for use
1289** in assert() expressions, so it is only compiled if NDEBUG is not
1290** defined.
1291*/
1292static int countWriteCursors(Btree *pBt){
1293 BtCursor *pCur;
1294 int r = 0;
1295 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1296 if( pCur->wrFlag ) r++;
1297 }
1298 return r;
1299}
1300#endif
1301
1302#if 0
drha059ad02001-04-17 20:09:11 +00001303/*
drhc39e0002004-05-07 23:50:57 +00001304** Invalidate all cursors
1305*/
1306static void invalidateCursors(Btree *pBt){
1307 BtCursor *pCur;
1308 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1309 MemPage *pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00001310 if( pPage /* && !pPage->isInit */ ){
1311 pageIntegrity(pPage);
drhc39e0002004-05-07 23:50:57 +00001312 releasePage(pPage);
1313 pCur->pPage = 0;
1314 pCur->isValid = 0;
1315 pCur->status = SQLITE_ABORT;
1316 }
1317 }
1318}
danielk1977fbcd5852004-06-15 02:44:18 +00001319#endif
drhc39e0002004-05-07 23:50:57 +00001320
drhda200cc2004-05-09 11:51:38 +00001321#ifdef SQLITE_TEST
1322/*
1323** Print debugging information about all cursors to standard output.
1324*/
1325void sqlite3BtreeCursorList(Btree *pBt){
1326 BtCursor *pCur;
1327 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1328 MemPage *pPage = pCur->pPage;
1329 char *zMode = pCur->wrFlag ? "rw" : "ro";
1330 printf("CURSOR %08x rooted at %4d(%s) currently at %d.%d%s\n",
1331 (int)pCur, pCur->pgnoRoot, zMode,
1332 pPage ? pPage->pgno : 0, pCur->idx,
1333 pCur->isValid ? "" : " eof"
1334 );
1335 }
1336}
1337#endif
1338
drhc39e0002004-05-07 23:50:57 +00001339/*
drhecdc7532001-09-23 02:35:53 +00001340** Rollback the transaction in progress. All cursors will be
1341** invalided by this operation. Any attempt to use a cursor
1342** that was open at the beginning of this operation will result
1343** in an error.
drh5e00f6c2001-09-13 13:46:56 +00001344**
1345** This will release the write lock on the database file. If there
1346** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00001347*/
drh3aac2dd2004-04-26 14:10:20 +00001348int sqlite3BtreeRollback(Btree *pBt){
drha059ad02001-04-17 20:09:11 +00001349 int rc;
drh24cd67e2004-05-10 16:18:47 +00001350 MemPage *pPage1;
danielk1977ee5741e2004-05-31 10:01:34 +00001351 if( pBt->inTrans==TRANS_WRITE ){
drh24cd67e2004-05-10 16:18:47 +00001352 rc = sqlite3pager_rollback(pBt->pPager);
1353 /* The rollback may have destroyed the pPage1->aData value. So
1354 ** call getPage() on page 1 again to make sure pPage1->aData is
1355 ** set correctly. */
1356 if( getPage(pBt, 1, &pPage1)==SQLITE_OK ){
1357 releasePage(pPage1);
1358 }
danielk1977fbcd5852004-06-15 02:44:18 +00001359 assert( countWriteCursors(pBt)==0 );
drh24cd67e2004-05-10 16:18:47 +00001360 }
danielk1977ee5741e2004-05-31 10:01:34 +00001361 pBt->inTrans = TRANS_NONE;
1362 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00001363 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001364 return rc;
1365}
1366
1367/*
drhab01f612004-05-22 02:55:23 +00001368** Start a statement subtransaction. The subtransaction can
1369** can be rolled back independently of the main transaction.
1370** You must start a transaction before starting a subtransaction.
1371** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00001372** commits or rolls back.
1373**
drhab01f612004-05-22 02:55:23 +00001374** Only one subtransaction may be active at a time. It is an error to try
1375** to start a new subtransaction if another subtransaction is already active.
1376**
1377** Statement subtransactions are used around individual SQL statements
1378** that are contained within a BEGIN...COMMIT block. If a constraint
1379** error occurs within the statement, the effect of that one statement
1380** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00001381*/
drh3aac2dd2004-04-26 14:10:20 +00001382int sqlite3BtreeBeginStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00001383 int rc;
danielk1977ee5741e2004-05-31 10:01:34 +00001384 if( (pBt->inTrans!=TRANS_WRITE) || pBt->inStmt ){
drhf74b8d92002-09-01 23:20:45 +00001385 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh0d65dc02002-02-03 00:56:09 +00001386 }
drha34b6762004-05-07 13:30:42 +00001387 rc = pBt->readOnly ? SQLITE_OK : sqlite3pager_stmt_begin(pBt->pPager);
drh3aac2dd2004-04-26 14:10:20 +00001388 pBt->inStmt = 1;
drh663fc632002-02-02 18:49:19 +00001389 return rc;
1390}
1391
1392
1393/*
drhab01f612004-05-22 02:55:23 +00001394** Commit the statment subtransaction currently in progress. If no
1395** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00001396*/
drh3aac2dd2004-04-26 14:10:20 +00001397int sqlite3BtreeCommitStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00001398 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001399 if( pBt->inStmt && !pBt->readOnly ){
drha34b6762004-05-07 13:30:42 +00001400 rc = sqlite3pager_stmt_commit(pBt->pPager);
drh663fc632002-02-02 18:49:19 +00001401 }else{
1402 rc = SQLITE_OK;
1403 }
drh3aac2dd2004-04-26 14:10:20 +00001404 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00001405 return rc;
1406}
1407
1408/*
drhab01f612004-05-22 02:55:23 +00001409** Rollback the active statement subtransaction. If no subtransaction
1410** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00001411**
drhab01f612004-05-22 02:55:23 +00001412** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00001413** to use a cursor that was open at the beginning of this operation
1414** will result in an error.
1415*/
drh3aac2dd2004-04-26 14:10:20 +00001416int sqlite3BtreeRollbackStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00001417 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001418 if( pBt->inStmt==0 || pBt->readOnly ) return SQLITE_OK;
drha34b6762004-05-07 13:30:42 +00001419 rc = sqlite3pager_stmt_rollback(pBt->pPager);
danielk1977fbcd5852004-06-15 02:44:18 +00001420 assert( countWriteCursors(pBt)==0 );
drh3aac2dd2004-04-26 14:10:20 +00001421 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00001422 return rc;
1423}
1424
1425/*
drh3aac2dd2004-04-26 14:10:20 +00001426** Default key comparison function to be used if no comparison function
1427** is specified on the sqlite3BtreeCursor() call.
1428*/
1429static int dfltCompare(
1430 void *NotUsed, /* User data is not used */
1431 int n1, const void *p1, /* First key to compare */
1432 int n2, const void *p2 /* Second key to compare */
1433){
1434 int c;
1435 c = memcmp(p1, p2, n1<n2 ? n1 : n2);
1436 if( c==0 ){
1437 c = n1 - n2;
1438 }
1439 return c;
1440}
1441
1442/*
drh8b2f49b2001-06-08 00:21:52 +00001443** Create a new cursor for the BTree whose root is on the page
1444** iTable. The act of acquiring a cursor gets a read lock on
1445** the database file.
drh1bee3d72001-10-15 00:44:35 +00001446**
1447** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00001448** If wrFlag==1, then the cursor can be used for reading or for
1449** writing if other conditions for writing are also met. These
1450** are the conditions that must be met in order for writing to
1451** be allowed:
drh6446c4d2001-12-15 14:22:18 +00001452**
drhf74b8d92002-09-01 23:20:45 +00001453** 1: The cursor must have been opened with wrFlag==1
1454**
1455** 2: No other cursors may be open with wrFlag==0 on the same table
1456**
1457** 3: The database must be writable (not on read-only media)
1458**
1459** 4: There must be an active transaction.
1460**
1461** Condition 2 warrants further discussion. If any cursor is opened
1462** on a table with wrFlag==0, that prevents all other cursors from
1463** writing to that table. This is a kind of "read-lock". When a cursor
1464** is opened with wrFlag==0 it is guaranteed that the table will not
1465** change as long as the cursor is open. This allows the cursor to
1466** do a sequential scan of the table without having to worry about
1467** entries being inserted or deleted during the scan. Cursors should
1468** be opened with wrFlag==0 only if this read-lock property is needed.
1469** That is to say, cursors should be opened with wrFlag==0 only if they
drh23e11ca2004-05-04 17:27:28 +00001470** intend to use the sqlite3BtreeNext() system call. All other cursors
drhf74b8d92002-09-01 23:20:45 +00001471** should be opened with wrFlag==1 even if they never really intend
1472** to write.
1473**
drh6446c4d2001-12-15 14:22:18 +00001474** No checking is done to make sure that page iTable really is the
1475** root page of a b-tree. If it is not, then the cursor acquired
1476** will not work correctly.
drh3aac2dd2004-04-26 14:10:20 +00001477**
1478** The comparison function must be logically the same for every cursor
1479** on a particular table. Changing the comparison function will result
1480** in incorrect operations. If the comparison function is NULL, a
1481** default comparison function is used. The comparison function is
1482** always ignored for INTKEY tables.
drha059ad02001-04-17 20:09:11 +00001483*/
drh3aac2dd2004-04-26 14:10:20 +00001484int sqlite3BtreeCursor(
1485 Btree *pBt, /* The btree */
1486 int iTable, /* Root page of table to open */
1487 int wrFlag, /* 1 to write. 0 read-only */
1488 int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
1489 void *pArg, /* First arg to xCompare() */
1490 BtCursor **ppCur /* Write new cursor here */
1491){
drha059ad02001-04-17 20:09:11 +00001492 int rc;
drhf74b8d92002-09-01 23:20:45 +00001493 BtCursor *pCur, *pRing;
drhecdc7532001-09-23 02:35:53 +00001494
drha0c9a112004-03-10 13:42:37 +00001495 if( pBt->readOnly && wrFlag ){
1496 *ppCur = 0;
1497 return SQLITE_READONLY;
1498 }
drh4b70f112004-05-02 21:12:19 +00001499 if( pBt->pPage1==0 ){
drha059ad02001-04-17 20:09:11 +00001500 rc = lockBtree(pBt);
1501 if( rc!=SQLITE_OK ){
1502 *ppCur = 0;
1503 return rc;
1504 }
1505 }
drheafe05b2004-06-13 00:54:01 +00001506 pCur = sqliteMallocRaw( sizeof(*pCur) );
drha059ad02001-04-17 20:09:11 +00001507 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +00001508 rc = SQLITE_NOMEM;
1509 goto create_cursor_exception;
1510 }
drh8b2f49b2001-06-08 00:21:52 +00001511 pCur->pgnoRoot = (Pgno)iTable;
drh24cd67e2004-05-10 16:18:47 +00001512 if( iTable==1 && sqlite3pager_pagecount(pBt->pPager)==0 ){
1513 rc = SQLITE_EMPTY;
drheafe05b2004-06-13 00:54:01 +00001514 pCur->pPage = 0;
drh24cd67e2004-05-10 16:18:47 +00001515 goto create_cursor_exception;
1516 }
drhde647132004-05-07 17:57:49 +00001517 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
drhbd03cae2001-06-02 02:40:57 +00001518 if( rc!=SQLITE_OK ){
1519 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00001520 }
drh3aac2dd2004-04-26 14:10:20 +00001521 pCur->xCompare = xCmp ? xCmp : dfltCompare;
1522 pCur->pArg = pArg;
drh14acc042001-06-10 19:56:58 +00001523 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +00001524 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +00001525 pCur->idx = 0;
drh59eb6762004-06-13 23:07:04 +00001526 memset(&pCur->info, 0, sizeof(pCur->info));
drha059ad02001-04-17 20:09:11 +00001527 pCur->pNext = pBt->pCursor;
1528 if( pCur->pNext ){
1529 pCur->pNext->pPrev = pCur;
1530 }
drh14acc042001-06-10 19:56:58 +00001531 pCur->pPrev = 0;
drhf74b8d92002-09-01 23:20:45 +00001532 pRing = pBt->pCursor;
1533 while( pRing && pRing->pgnoRoot!=pCur->pgnoRoot ){ pRing = pRing->pNext; }
1534 if( pRing ){
1535 pCur->pShared = pRing->pShared;
1536 pRing->pShared = pCur;
1537 }else{
1538 pCur->pShared = pCur;
1539 }
drha059ad02001-04-17 20:09:11 +00001540 pBt->pCursor = pCur;
drhc39e0002004-05-07 23:50:57 +00001541 pCur->isValid = 0;
1542 pCur->status = SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00001543 *ppCur = pCur;
1544 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00001545
1546create_cursor_exception:
1547 *ppCur = 0;
1548 if( pCur ){
drh3aac2dd2004-04-26 14:10:20 +00001549 releasePage(pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +00001550 sqliteFree(pCur);
1551 }
drh5e00f6c2001-09-13 13:46:56 +00001552 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00001553 return rc;
drha059ad02001-04-17 20:09:11 +00001554}
1555
drh7a224de2004-06-02 01:22:02 +00001556#if 0 /* Not Used */
drhd3d39e92004-05-20 22:16:29 +00001557/*
1558** Change the value of the comparison function used by a cursor.
1559*/
danielk1977bf3b7212004-05-18 10:06:24 +00001560void sqlite3BtreeSetCompare(
drhd3d39e92004-05-20 22:16:29 +00001561 BtCursor *pCur, /* The cursor to whose comparison function is changed */
1562 int(*xCmp)(void*,int,const void*,int,const void*), /* New comparison func */
1563 void *pArg /* First argument to xCmp() */
danielk1977bf3b7212004-05-18 10:06:24 +00001564){
1565 pCur->xCompare = xCmp ? xCmp : dfltCompare;
1566 pCur->pArg = pArg;
1567}
drh7a224de2004-06-02 01:22:02 +00001568#endif
danielk1977bf3b7212004-05-18 10:06:24 +00001569
drha059ad02001-04-17 20:09:11 +00001570/*
drh5e00f6c2001-09-13 13:46:56 +00001571** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00001572** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00001573*/
drh3aac2dd2004-04-26 14:10:20 +00001574int sqlite3BtreeCloseCursor(BtCursor *pCur){
drha059ad02001-04-17 20:09:11 +00001575 Btree *pBt = pCur->pBt;
drha059ad02001-04-17 20:09:11 +00001576 if( pCur->pPrev ){
1577 pCur->pPrev->pNext = pCur->pNext;
1578 }else{
1579 pBt->pCursor = pCur->pNext;
1580 }
1581 if( pCur->pNext ){
1582 pCur->pNext->pPrev = pCur->pPrev;
1583 }
drh3aac2dd2004-04-26 14:10:20 +00001584 releasePage(pCur->pPage);
drhf74b8d92002-09-01 23:20:45 +00001585 if( pCur->pShared!=pCur ){
1586 BtCursor *pRing = pCur->pShared;
1587 while( pRing->pShared!=pCur ){ pRing = pRing->pShared; }
1588 pRing->pShared = pCur->pShared;
1589 }
drh5e00f6c2001-09-13 13:46:56 +00001590 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001591 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +00001592 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00001593}
1594
drh7e3b0a02001-04-28 16:52:40 +00001595/*
drh5e2f8b92001-05-28 00:41:15 +00001596** Make a temporary cursor by filling in the fields of pTempCur.
1597** The temporary cursor is not on the cursor list for the Btree.
1598*/
drh14acc042001-06-10 19:56:58 +00001599static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00001600 memcpy(pTempCur, pCur, sizeof(*pCur));
1601 pTempCur->pNext = 0;
1602 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00001603 if( pTempCur->pPage ){
drha34b6762004-05-07 13:30:42 +00001604 sqlite3pager_ref(pTempCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00001605 }
drh5e2f8b92001-05-28 00:41:15 +00001606}
1607
1608/*
drhbd03cae2001-06-02 02:40:57 +00001609** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00001610** function above.
1611*/
drh14acc042001-06-10 19:56:58 +00001612static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00001613 if( pCur->pPage ){
drha34b6762004-05-07 13:30:42 +00001614 sqlite3pager_unref(pCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00001615 }
drh5e2f8b92001-05-28 00:41:15 +00001616}
1617
1618/*
drh9188b382004-05-14 21:12:22 +00001619** Make sure the BtCursor.info field of the given cursor is valid.
drhab01f612004-05-22 02:55:23 +00001620** If it is not already valid, call parseCell() to fill it in.
1621**
1622** BtCursor.info is a cache of the information in the current cell.
1623** Using this cache reduces the number of calls to parseCell().
drh9188b382004-05-14 21:12:22 +00001624*/
1625static void getCellInfo(BtCursor *pCur){
drh271efa52004-05-30 19:19:05 +00001626 if( pCur->info.nSize==0 ){
drh3a41a3f2004-05-30 02:14:17 +00001627 parseCell(pCur->pPage, pCur->idx, &pCur->info);
drh9188b382004-05-14 21:12:22 +00001628 }else{
1629#ifndef NDEBUG
1630 CellInfo info;
drh51c6d962004-06-06 00:42:25 +00001631 memset(&info, 0, sizeof(info));
drh3a41a3f2004-05-30 02:14:17 +00001632 parseCell(pCur->pPage, pCur->idx, &info);
drh9188b382004-05-14 21:12:22 +00001633 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
1634#endif
1635 }
1636}
1637
1638/*
drh3aac2dd2004-04-26 14:10:20 +00001639** Set *pSize to the size of the buffer needed to hold the value of
1640** the key for the current entry. If the cursor is not pointing
1641** to a valid entry, *pSize is set to 0.
1642**
drh4b70f112004-05-02 21:12:19 +00001643** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00001644** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00001645*/
drh4a1c3802004-05-12 15:15:47 +00001646int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drhc39e0002004-05-07 23:50:57 +00001647 if( !pCur->isValid ){
drh72f82862001-05-24 21:06:34 +00001648 *pSize = 0;
1649 }else{
drh9188b382004-05-14 21:12:22 +00001650 getCellInfo(pCur);
1651 *pSize = pCur->info.nKey;
drh72f82862001-05-24 21:06:34 +00001652 }
1653 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00001654}
drh2af926b2001-05-15 00:39:25 +00001655
drh72f82862001-05-24 21:06:34 +00001656/*
drh0e1c19e2004-05-11 00:58:56 +00001657** Set *pSize to the number of bytes of data in the entry the
1658** cursor currently points to. Always return SQLITE_OK.
1659** Failure is not possible. If the cursor is not currently
1660** pointing to an entry (which can happen, for example, if
1661** the database is empty) then *pSize is set to 0.
1662*/
1663int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drh0e1c19e2004-05-11 00:58:56 +00001664 if( !pCur->isValid ){
danielk197796fc5fe2004-05-13 11:34:16 +00001665 /* Not pointing at a valid entry - set *pSize to 0. */
drh0e1c19e2004-05-11 00:58:56 +00001666 *pSize = 0;
1667 }else{
drh9188b382004-05-14 21:12:22 +00001668 getCellInfo(pCur);
1669 *pSize = pCur->info.nData;
drh0e1c19e2004-05-11 00:58:56 +00001670 }
1671 return SQLITE_OK;
1672}
1673
1674/*
drh72f82862001-05-24 21:06:34 +00001675** Read payload information from the entry that the pCur cursor is
1676** pointing to. Begin reading the payload at "offset" and read
1677** a total of "amt" bytes. Put the result in zBuf.
1678**
1679** This routine does not make a distinction between key and data.
drhab01f612004-05-22 02:55:23 +00001680** It just reads bytes from the payload area. Data might appear
1681** on the main page or be scattered out on multiple overflow pages.
drh72f82862001-05-24 21:06:34 +00001682*/
drh3aac2dd2004-04-26 14:10:20 +00001683static int getPayload(
1684 BtCursor *pCur, /* Cursor pointing to entry to read from */
1685 int offset, /* Begin reading this far into payload */
1686 int amt, /* Read this many bytes */
1687 unsigned char *pBuf, /* Write the bytes into this buffer */
1688 int skipKey /* offset begins at data if this is true */
1689){
1690 unsigned char *aPayload;
drh2af926b2001-05-15 00:39:25 +00001691 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +00001692 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001693 MemPage *pPage;
1694 Btree *pBt;
drh6f11bef2004-05-13 01:12:56 +00001695 int ovflSize;
drhfa1a98a2004-05-14 19:08:17 +00001696 u32 nKey;
drh3aac2dd2004-04-26 14:10:20 +00001697
drh72f82862001-05-24 21:06:34 +00001698 assert( pCur!=0 && pCur->pPage!=0 );
drhc39e0002004-05-07 23:50:57 +00001699 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00001700 pBt = pCur->pBt;
1701 pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00001702 pageIntegrity(pPage);
drh3aac2dd2004-04-26 14:10:20 +00001703 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00001704 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00001705 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00001706 aPayload += pCur->info.nHeader;
drh3aac2dd2004-04-26 14:10:20 +00001707 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00001708 nKey = 0;
1709 }else{
1710 nKey = pCur->info.nKey;
drh3aac2dd2004-04-26 14:10:20 +00001711 }
1712 assert( offset>=0 );
1713 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00001714 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00001715 }
drhfa1a98a2004-05-14 19:08:17 +00001716 if( offset+amt > nKey+pCur->info.nData ){
drha34b6762004-05-07 13:30:42 +00001717 return SQLITE_ERROR;
drh3aac2dd2004-04-26 14:10:20 +00001718 }
drhfa1a98a2004-05-14 19:08:17 +00001719 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00001720 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00001721 if( a+offset>pCur->info.nLocal ){
1722 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00001723 }
drha34b6762004-05-07 13:30:42 +00001724 memcpy(pBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +00001725 if( a==amt ){
1726 return SQLITE_OK;
1727 }
drh2aa679f2001-06-25 02:11:07 +00001728 offset = 0;
drha34b6762004-05-07 13:30:42 +00001729 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00001730 amt -= a;
drhdd793422001-06-28 01:54:48 +00001731 }else{
drhfa1a98a2004-05-14 19:08:17 +00001732 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00001733 }
1734 if( amt>0 ){
drhfa1a98a2004-05-14 19:08:17 +00001735 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
drh2af926b2001-05-15 00:39:25 +00001736 }
drhb6f41482004-05-14 01:58:11 +00001737 ovflSize = pBt->usableSize - 4;
drh2af926b2001-05-15 00:39:25 +00001738 while( amt>0 && nextPage ){
drha34b6762004-05-07 13:30:42 +00001739 rc = sqlite3pager_get(pBt->pPager, nextPage, (void**)&aPayload);
drh2af926b2001-05-15 00:39:25 +00001740 if( rc!=0 ){
1741 return rc;
1742 }
drha34b6762004-05-07 13:30:42 +00001743 nextPage = get4byte(aPayload);
drh3aac2dd2004-04-26 14:10:20 +00001744 if( offset<ovflSize ){
drh2af926b2001-05-15 00:39:25 +00001745 int a = amt;
drh3aac2dd2004-04-26 14:10:20 +00001746 if( a + offset > ovflSize ){
1747 a = ovflSize - offset;
drh2af926b2001-05-15 00:39:25 +00001748 }
drh9b171272004-05-08 02:03:22 +00001749 memcpy(pBuf, &aPayload[offset+4], a);
drh2aa679f2001-06-25 02:11:07 +00001750 offset = 0;
drh2af926b2001-05-15 00:39:25 +00001751 amt -= a;
drha34b6762004-05-07 13:30:42 +00001752 pBuf += a;
drh2aa679f2001-06-25 02:11:07 +00001753 }else{
drh3aac2dd2004-04-26 14:10:20 +00001754 offset -= ovflSize;
drh2af926b2001-05-15 00:39:25 +00001755 }
drha34b6762004-05-07 13:30:42 +00001756 sqlite3pager_unref(aPayload);
drh2af926b2001-05-15 00:39:25 +00001757 }
drha7fcb052001-12-14 15:09:55 +00001758 if( amt>0 ){
1759 return SQLITE_CORRUPT;
1760 }
1761 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00001762}
1763
drh72f82862001-05-24 21:06:34 +00001764/*
drh3aac2dd2004-04-26 14:10:20 +00001765** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00001766** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00001767** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00001768**
drh3aac2dd2004-04-26 14:10:20 +00001769** Return SQLITE_OK on success or an error code if anything goes
1770** wrong. An error is returned if "offset+amt" is larger than
1771** the available payload.
drh72f82862001-05-24 21:06:34 +00001772*/
drha34b6762004-05-07 13:30:42 +00001773int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drh8c1238a2003-01-02 14:43:55 +00001774 assert( amt>=0 );
1775 assert( offset>=0 );
drhc39e0002004-05-07 23:50:57 +00001776 if( pCur->isValid==0 ){
1777 return pCur->status;
drh3aac2dd2004-04-26 14:10:20 +00001778 }
drhc39e0002004-05-07 23:50:57 +00001779 assert( pCur->pPage!=0 );
1780 assert( pCur->pPage->intKey==0 );
1781 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh3aac2dd2004-04-26 14:10:20 +00001782 return getPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
1783}
1784
1785/*
drh3aac2dd2004-04-26 14:10:20 +00001786** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00001787** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00001788** begins at "offset".
1789**
1790** Return SQLITE_OK on success or an error code if anything goes
1791** wrong. An error is returned if "offset+amt" is larger than
1792** the available payload.
drh72f82862001-05-24 21:06:34 +00001793*/
drh3aac2dd2004-04-26 14:10:20 +00001794int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhc39e0002004-05-07 23:50:57 +00001795 if( !pCur->isValid ){
1796 return pCur->status ? pCur->status : SQLITE_INTERNAL;
1797 }
drh8c1238a2003-01-02 14:43:55 +00001798 assert( amt>=0 );
1799 assert( offset>=0 );
1800 assert( pCur->pPage!=0 );
drhc39e0002004-05-07 23:50:57 +00001801 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh3aac2dd2004-04-26 14:10:20 +00001802 return getPayload(pCur, offset, amt, pBuf, 1);
drh2af926b2001-05-15 00:39:25 +00001803}
1804
drh72f82862001-05-24 21:06:34 +00001805/*
drh0e1c19e2004-05-11 00:58:56 +00001806** Return a pointer to payload information from the entry that the
1807** pCur cursor is pointing to. The pointer is to the beginning of
1808** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00001809** skipKey==1. The number of bytes of available key/data is written
1810** into *pAmt. If *pAmt==0, then the value returned will not be
1811** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00001812**
1813** This routine is an optimization. It is common for the entire key
1814** and data to fit on the local page and for there to be no overflow
1815** pages. When that is so, this routine can be used to access the
1816** key and data without making a copy. If the key and/or data spills
1817** onto overflow pages, then getPayload() must be used to reassembly
1818** the key/data and copy it into a preallocated buffer.
1819**
1820** The pointer returned by this routine looks directly into the cached
1821** page of the database. The data might change or move the next time
1822** any btree routine is called.
1823*/
1824static const unsigned char *fetchPayload(
1825 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00001826 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00001827 int skipKey /* read beginning at data if this is true */
1828){
1829 unsigned char *aPayload;
1830 MemPage *pPage;
1831 Btree *pBt;
drhfa1a98a2004-05-14 19:08:17 +00001832 u32 nKey;
1833 int nLocal;
drh0e1c19e2004-05-11 00:58:56 +00001834
1835 assert( pCur!=0 && pCur->pPage!=0 );
1836 assert( pCur->isValid );
1837 pBt = pCur->pBt;
1838 pPage = pCur->pPage;
1839 pageIntegrity(pPage);
1840 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00001841 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00001842 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00001843 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00001844 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00001845 nKey = 0;
1846 }else{
1847 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00001848 }
drh0e1c19e2004-05-11 00:58:56 +00001849 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00001850 aPayload += nKey;
1851 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00001852 }else{
drhfa1a98a2004-05-14 19:08:17 +00001853 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00001854 if( nLocal>nKey ){
1855 nLocal = nKey;
1856 }
drh0e1c19e2004-05-11 00:58:56 +00001857 }
drhe51c44f2004-05-30 20:46:09 +00001858 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00001859 return aPayload;
1860}
1861
1862
1863/*
drhe51c44f2004-05-30 20:46:09 +00001864** For the entry that cursor pCur is point to, return as
1865** many bytes of the key or data as are available on the local
1866** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00001867**
1868** The pointer returned is ephemeral. The key/data may move
1869** or be destroyed on the next call to any Btree routine.
1870**
1871** These routines is used to get quick access to key and data
1872** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00001873*/
drhe51c44f2004-05-30 20:46:09 +00001874const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
1875 return (const void*)fetchPayload(pCur, pAmt, 0);
drh0e1c19e2004-05-11 00:58:56 +00001876}
drhe51c44f2004-05-30 20:46:09 +00001877const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
1878 return (const void*)fetchPayload(pCur, pAmt, 1);
drh0e1c19e2004-05-11 00:58:56 +00001879}
1880
1881
1882/*
drh8178a752003-01-05 21:41:40 +00001883** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00001884** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00001885*/
drh3aac2dd2004-04-26 14:10:20 +00001886static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00001887 int rc;
1888 MemPage *pNewPage;
drh3aac2dd2004-04-26 14:10:20 +00001889 MemPage *pOldPage;
drh0d316a42002-08-11 20:10:47 +00001890 Btree *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00001891
drhc39e0002004-05-07 23:50:57 +00001892 assert( pCur->isValid );
drhde647132004-05-07 17:57:49 +00001893 rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00001894 if( rc ) return rc;
drhda200cc2004-05-09 11:51:38 +00001895 pageIntegrity(pNewPage);
drh428ae8c2003-01-04 16:48:09 +00001896 pNewPage->idxParent = pCur->idx;
drh3aac2dd2004-04-26 14:10:20 +00001897 pOldPage = pCur->pPage;
1898 pOldPage->idxShift = 0;
1899 releasePage(pOldPage);
drh72f82862001-05-24 21:06:34 +00001900 pCur->pPage = pNewPage;
1901 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00001902 pCur->info.nSize = 0;
drh4be295b2003-12-16 03:44:47 +00001903 if( pNewPage->nCell<1 ){
1904 return SQLITE_CORRUPT;
1905 }
drh72f82862001-05-24 21:06:34 +00001906 return SQLITE_OK;
1907}
1908
1909/*
drh8856d6a2004-04-29 14:42:46 +00001910** Return true if the page is the virtual root of its table.
1911**
1912** The virtual root page is the root page for most tables. But
1913** for the table rooted on page 1, sometime the real root page
1914** is empty except for the right-pointer. In such cases the
1915** virtual root page is the page that the right-pointer of page
1916** 1 is pointing to.
1917*/
1918static int isRootPage(MemPage *pPage){
1919 MemPage *pParent = pPage->pParent;
drhda200cc2004-05-09 11:51:38 +00001920 if( pParent==0 ) return 1;
1921 if( pParent->pgno>1 ) return 0;
1922 if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
drh8856d6a2004-04-29 14:42:46 +00001923 return 0;
1924}
1925
1926/*
drh5e2f8b92001-05-28 00:41:15 +00001927** Move the cursor up to the parent page.
1928**
1929** pCur->idx is set to the cell index that contains the pointer
1930** to the page we are coming from. If we are coming from the
1931** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00001932** the largest cell index.
drh72f82862001-05-24 21:06:34 +00001933*/
drh8178a752003-01-05 21:41:40 +00001934static void moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001935 Pgno oldPgno;
1936 MemPage *pParent;
drh8178a752003-01-05 21:41:40 +00001937 MemPage *pPage;
drh428ae8c2003-01-04 16:48:09 +00001938 int idxParent;
drh3aac2dd2004-04-26 14:10:20 +00001939
drhc39e0002004-05-07 23:50:57 +00001940 assert( pCur->isValid );
drh8178a752003-01-05 21:41:40 +00001941 pPage = pCur->pPage;
1942 assert( pPage!=0 );
drh8856d6a2004-04-29 14:42:46 +00001943 assert( !isRootPage(pPage) );
drhda200cc2004-05-09 11:51:38 +00001944 pageIntegrity(pPage);
drh8178a752003-01-05 21:41:40 +00001945 pParent = pPage->pParent;
1946 assert( pParent!=0 );
drhda200cc2004-05-09 11:51:38 +00001947 pageIntegrity(pParent);
drh8178a752003-01-05 21:41:40 +00001948 idxParent = pPage->idxParent;
drha34b6762004-05-07 13:30:42 +00001949 sqlite3pager_ref(pParent->aData);
drh3aac2dd2004-04-26 14:10:20 +00001950 oldPgno = pPage->pgno;
1951 releasePage(pPage);
drh72f82862001-05-24 21:06:34 +00001952 pCur->pPage = pParent;
drh271efa52004-05-30 19:19:05 +00001953 pCur->info.nSize = 0;
drh428ae8c2003-01-04 16:48:09 +00001954 assert( pParent->idxShift==0 );
drh43605152004-05-29 21:46:49 +00001955 pCur->idx = idxParent;
drh72f82862001-05-24 21:06:34 +00001956}
1957
1958/*
1959** Move the cursor to the root page
1960*/
drh5e2f8b92001-05-28 00:41:15 +00001961static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00001962 MemPage *pRoot;
drhbd03cae2001-06-02 02:40:57 +00001963 int rc;
drh0d316a42002-08-11 20:10:47 +00001964 Btree *pBt = pCur->pBt;
drhbd03cae2001-06-02 02:40:57 +00001965
drhde647132004-05-07 17:57:49 +00001966 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0);
drhc39e0002004-05-07 23:50:57 +00001967 if( rc ){
1968 pCur->isValid = 0;
1969 return rc;
1970 }
drh3aac2dd2004-04-26 14:10:20 +00001971 releasePage(pCur->pPage);
drhda200cc2004-05-09 11:51:38 +00001972 pageIntegrity(pRoot);
drh3aac2dd2004-04-26 14:10:20 +00001973 pCur->pPage = pRoot;
drh72f82862001-05-24 21:06:34 +00001974 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00001975 pCur->info.nSize = 0;
drh8856d6a2004-04-29 14:42:46 +00001976 if( pRoot->nCell==0 && !pRoot->leaf ){
1977 Pgno subpage;
1978 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00001979 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00001980 assert( subpage>0 );
drh3644f082004-05-10 18:45:09 +00001981 pCur->isValid = 1;
drh4b70f112004-05-02 21:12:19 +00001982 rc = moveToChild(pCur, subpage);
drh8856d6a2004-04-29 14:42:46 +00001983 }
drhc39e0002004-05-07 23:50:57 +00001984 pCur->isValid = pCur->pPage->nCell>0;
drh8856d6a2004-04-29 14:42:46 +00001985 return rc;
drh72f82862001-05-24 21:06:34 +00001986}
drh2af926b2001-05-15 00:39:25 +00001987
drh5e2f8b92001-05-28 00:41:15 +00001988/*
1989** Move the cursor down to the left-most leaf entry beneath the
1990** entry to which it is currently pointing.
1991*/
1992static int moveToLeftmost(BtCursor *pCur){
1993 Pgno pgno;
1994 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001995 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00001996
drhc39e0002004-05-07 23:50:57 +00001997 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00001998 while( !(pPage = pCur->pPage)->leaf ){
drha34b6762004-05-07 13:30:42 +00001999 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00002000 pgno = get4byte(findCell(pPage, pCur->idx));
drh8178a752003-01-05 21:41:40 +00002001 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00002002 if( rc ) return rc;
2003 }
2004 return SQLITE_OK;
2005}
2006
drh2dcc9aa2002-12-04 13:40:25 +00002007/*
2008** Move the cursor down to the right-most leaf entry beneath the
2009** page to which it is currently pointing. Notice the difference
2010** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
2011** finds the left-most entry beneath the *entry* whereas moveToRightmost()
2012** finds the right-most entry beneath the *page*.
2013*/
2014static int moveToRightmost(BtCursor *pCur){
2015 Pgno pgno;
2016 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002017 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00002018
drhc39e0002004-05-07 23:50:57 +00002019 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00002020 while( !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00002021 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh3aac2dd2004-04-26 14:10:20 +00002022 pCur->idx = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00002023 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00002024 if( rc ) return rc;
2025 }
drh3aac2dd2004-04-26 14:10:20 +00002026 pCur->idx = pPage->nCell - 1;
drh271efa52004-05-30 19:19:05 +00002027 pCur->info.nSize = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002028 return SQLITE_OK;
2029}
2030
drh5e00f6c2001-09-13 13:46:56 +00002031/* Move the cursor to the first entry in the table. Return SQLITE_OK
2032** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00002033** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00002034*/
drh3aac2dd2004-04-26 14:10:20 +00002035int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00002036 int rc;
drhc39e0002004-05-07 23:50:57 +00002037 if( pCur->status ){
2038 return pCur->status;
2039 }
drh5e00f6c2001-09-13 13:46:56 +00002040 rc = moveToRoot(pCur);
2041 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00002042 if( pCur->isValid==0 ){
2043 assert( pCur->pPage->nCell==0 );
drh5e00f6c2001-09-13 13:46:56 +00002044 *pRes = 1;
2045 return SQLITE_OK;
2046 }
drhc39e0002004-05-07 23:50:57 +00002047 assert( pCur->pPage->nCell>0 );
drh5e00f6c2001-09-13 13:46:56 +00002048 *pRes = 0;
2049 rc = moveToLeftmost(pCur);
2050 return rc;
2051}
drh5e2f8b92001-05-28 00:41:15 +00002052
drh9562b552002-02-19 15:00:07 +00002053/* Move the cursor to the last entry in the table. Return SQLITE_OK
2054** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00002055** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00002056*/
drh3aac2dd2004-04-26 14:10:20 +00002057int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00002058 int rc;
drhc39e0002004-05-07 23:50:57 +00002059 if( pCur->status ){
2060 return pCur->status;
2061 }
drh9562b552002-02-19 15:00:07 +00002062 rc = moveToRoot(pCur);
2063 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00002064 if( pCur->isValid==0 ){
2065 assert( pCur->pPage->nCell==0 );
drh9562b552002-02-19 15:00:07 +00002066 *pRes = 1;
2067 return SQLITE_OK;
2068 }
drhc39e0002004-05-07 23:50:57 +00002069 assert( pCur->isValid );
drh9562b552002-02-19 15:00:07 +00002070 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002071 rc = moveToRightmost(pCur);
drh9562b552002-02-19 15:00:07 +00002072 return rc;
2073}
2074
drh3aac2dd2004-04-26 14:10:20 +00002075/* Move the cursor so that it points to an entry near pKey/nKey.
drh72f82862001-05-24 21:06:34 +00002076** Return a success code.
2077**
drh3aac2dd2004-04-26 14:10:20 +00002078** For INTKEY tables, only the nKey parameter is used. pKey is
2079** ignored. For other tables, nKey is the number of bytes of data
2080** in nKey. The comparison function specified when the cursor was
2081** created is used to compare keys.
2082**
drh5e2f8b92001-05-28 00:41:15 +00002083** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00002084** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00002085** were present. The cursor might point to an entry that comes
2086** before or after the key.
2087**
drhbd03cae2001-06-02 02:40:57 +00002088** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00002089** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00002090** this value is as follows:
2091**
2092** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00002093** is smaller than pKey or if the table is empty
2094** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00002095**
2096** *pRes==0 The cursor is left pointing at an entry that
2097** exactly matches pKey.
2098**
2099** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00002100** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00002101*/
drh4a1c3802004-05-12 15:15:47 +00002102int sqlite3BtreeMoveto(BtCursor *pCur, const void *pKey, i64 nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00002103 int rc;
drhc39e0002004-05-07 23:50:57 +00002104
2105 if( pCur->status ){
2106 return pCur->status;
2107 }
drh5e2f8b92001-05-28 00:41:15 +00002108 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00002109 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00002110 assert( pCur->pPage );
2111 assert( pCur->pPage->isInit );
2112 if( pCur->isValid==0 ){
drhf328bc82004-05-10 23:29:49 +00002113 *pRes = -1;
drhc39e0002004-05-07 23:50:57 +00002114 assert( pCur->pPage->nCell==0 );
2115 return SQLITE_OK;
2116 }
drh72f82862001-05-24 21:06:34 +00002117 for(;;){
2118 int lwr, upr;
2119 Pgno chldPg;
2120 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00002121 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00002122 lwr = 0;
2123 upr = pPage->nCell-1;
drhda200cc2004-05-09 11:51:38 +00002124 pageIntegrity(pPage);
drh72f82862001-05-24 21:06:34 +00002125 while( lwr<=upr ){
danielk197713adf8a2004-06-03 16:08:41 +00002126 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00002127 i64 nCellKey;
drh72f82862001-05-24 21:06:34 +00002128 pCur->idx = (lwr+upr)/2;
drh271efa52004-05-30 19:19:05 +00002129 pCur->info.nSize = 0;
drhde647132004-05-07 17:57:49 +00002130 sqlite3BtreeKeySize(pCur, &nCellKey);
drh3aac2dd2004-04-26 14:10:20 +00002131 if( pPage->intKey ){
2132 if( nCellKey<nKey ){
2133 c = -1;
2134 }else if( nCellKey>nKey ){
2135 c = +1;
2136 }else{
2137 c = 0;
2138 }
drh3aac2dd2004-04-26 14:10:20 +00002139 }else{
drhe51c44f2004-05-30 20:46:09 +00002140 int available;
danielk197713adf8a2004-06-03 16:08:41 +00002141 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drhe51c44f2004-05-30 20:46:09 +00002142 if( available>=nCellKey ){
2143 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
2144 }else{
2145 pCellKey = sqliteMallocRaw( nCellKey );
2146 if( pCellKey==0 ) return SQLITE_NOMEM;
danielk197713adf8a2004-06-03 16:08:41 +00002147 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
drhe51c44f2004-05-30 20:46:09 +00002148 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
2149 sqliteFree(pCellKey);
2150 if( rc ) return rc;
2151 }
drh3aac2dd2004-04-26 14:10:20 +00002152 }
drh72f82862001-05-24 21:06:34 +00002153 if( c==0 ){
drh8b18dd42004-05-12 19:18:15 +00002154 if( pPage->leafData && !pPage->leaf ){
drhfc70e6f2004-05-12 21:11:27 +00002155 lwr = pCur->idx;
2156 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00002157 break;
2158 }else{
drh8b18dd42004-05-12 19:18:15 +00002159 if( pRes ) *pRes = 0;
2160 return SQLITE_OK;
2161 }
drh72f82862001-05-24 21:06:34 +00002162 }
2163 if( c<0 ){
2164 lwr = pCur->idx+1;
2165 }else{
2166 upr = pCur->idx-1;
2167 }
2168 }
2169 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00002170 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00002171 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00002172 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00002173 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00002174 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00002175 }else{
drh43605152004-05-29 21:46:49 +00002176 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00002177 }
2178 if( chldPg==0 ){
drhc39e0002004-05-07 23:50:57 +00002179 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00002180 if( pRes ) *pRes = c;
2181 return SQLITE_OK;
2182 }
drh428ae8c2003-01-04 16:48:09 +00002183 pCur->idx = lwr;
drh271efa52004-05-30 19:19:05 +00002184 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00002185 rc = moveToChild(pCur, chldPg);
drhc39e0002004-05-07 23:50:57 +00002186 if( rc ){
2187 return rc;
2188 }
drh72f82862001-05-24 21:06:34 +00002189 }
drhbd03cae2001-06-02 02:40:57 +00002190 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00002191}
2192
2193/*
drhc39e0002004-05-07 23:50:57 +00002194** Return TRUE if the cursor is not pointing at an entry of the table.
2195**
2196** TRUE will be returned after a call to sqlite3BtreeNext() moves
2197** past the last entry in the table or sqlite3BtreePrev() moves past
2198** the first entry. TRUE is also returned if the table is empty.
2199*/
2200int sqlite3BtreeEof(BtCursor *pCur){
2201 return pCur->isValid==0;
2202}
2203
2204/*
drhbd03cae2001-06-02 02:40:57 +00002205** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00002206** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00002207** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00002208** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00002209*/
drh3aac2dd2004-04-26 14:10:20 +00002210int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00002211 int rc;
drh8178a752003-01-05 21:41:40 +00002212 MemPage *pPage = pCur->pPage;
drh8b18dd42004-05-12 19:18:15 +00002213
drh8c1238a2003-01-02 14:43:55 +00002214 assert( pRes!=0 );
drhc39e0002004-05-07 23:50:57 +00002215 if( pCur->isValid==0 ){
drh8c1238a2003-01-02 14:43:55 +00002216 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00002217 return SQLITE_OK;
drhecdc7532001-09-23 02:35:53 +00002218 }
drh8178a752003-01-05 21:41:40 +00002219 assert( pPage->isInit );
drh8178a752003-01-05 21:41:40 +00002220 assert( pCur->idx<pPage->nCell );
drh72f82862001-05-24 21:06:34 +00002221 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00002222 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00002223 if( pCur->idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00002224 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00002225 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00002226 if( rc ) return rc;
2227 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00002228 *pRes = 0;
2229 return rc;
drh72f82862001-05-24 21:06:34 +00002230 }
drh5e2f8b92001-05-28 00:41:15 +00002231 do{
drh8856d6a2004-04-29 14:42:46 +00002232 if( isRootPage(pPage) ){
drh8c1238a2003-01-02 14:43:55 +00002233 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00002234 pCur->isValid = 0;
drh5e2f8b92001-05-28 00:41:15 +00002235 return SQLITE_OK;
2236 }
drh8178a752003-01-05 21:41:40 +00002237 moveToParent(pCur);
2238 pPage = pCur->pPage;
2239 }while( pCur->idx>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00002240 *pRes = 0;
drh8b18dd42004-05-12 19:18:15 +00002241 if( pPage->leafData ){
2242 rc = sqlite3BtreeNext(pCur, pRes);
2243 }else{
2244 rc = SQLITE_OK;
2245 }
2246 return rc;
drh8178a752003-01-05 21:41:40 +00002247 }
2248 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00002249 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00002250 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00002251 }
drh5e2f8b92001-05-28 00:41:15 +00002252 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00002253 return rc;
drh72f82862001-05-24 21:06:34 +00002254}
2255
drh3b7511c2001-05-26 13:15:44 +00002256/*
drh2dcc9aa2002-12-04 13:40:25 +00002257** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00002258** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00002259** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00002260** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00002261*/
drh3aac2dd2004-04-26 14:10:20 +00002262int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00002263 int rc;
2264 Pgno pgno;
drh8178a752003-01-05 21:41:40 +00002265 MemPage *pPage;
drhc39e0002004-05-07 23:50:57 +00002266 if( pCur->isValid==0 ){
2267 *pRes = 1;
2268 return SQLITE_OK;
2269 }
drh8178a752003-01-05 21:41:40 +00002270 pPage = pCur->pPage;
drh8178a752003-01-05 21:41:40 +00002271 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00002272 assert( pCur->idx>=0 );
drha34b6762004-05-07 13:30:42 +00002273 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00002274 pgno = get4byte( findCell(pPage, pCur->idx) );
drh8178a752003-01-05 21:41:40 +00002275 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00002276 if( rc ) return rc;
2277 rc = moveToRightmost(pCur);
2278 }else{
2279 while( pCur->idx==0 ){
drh8856d6a2004-04-29 14:42:46 +00002280 if( isRootPage(pPage) ){
drhc39e0002004-05-07 23:50:57 +00002281 pCur->isValid = 0;
2282 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00002283 return SQLITE_OK;
2284 }
drh8178a752003-01-05 21:41:40 +00002285 moveToParent(pCur);
2286 pPage = pCur->pPage;
drh2dcc9aa2002-12-04 13:40:25 +00002287 }
2288 pCur->idx--;
drh271efa52004-05-30 19:19:05 +00002289 pCur->info.nSize = 0;
drh8b18dd42004-05-12 19:18:15 +00002290 if( pPage->leafData ){
2291 rc = sqlite3BtreePrevious(pCur, pRes);
2292 }else{
2293 rc = SQLITE_OK;
2294 }
drh2dcc9aa2002-12-04 13:40:25 +00002295 }
drh8178a752003-01-05 21:41:40 +00002296 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002297 return rc;
2298}
2299
2300/*
drh3a4c1412004-05-09 20:40:11 +00002301** The TRACE macro will print high-level status information about the
2302** btree operation when the global variable sqlite3_btree_trace is
2303** enabled.
2304*/
2305#if SQLITE_TEST
drhe54ca3f2004-06-07 01:52:14 +00002306# define TRACE(X) if( sqlite3_btree_trace )\
2307 { sqlite3DebugPrintf X; fflush(stdout); }
drh3a4c1412004-05-09 20:40:11 +00002308#else
2309# define TRACE(X)
2310#endif
2311int sqlite3_btree_trace=0; /* True to enable tracing */
2312
2313/*
drh3b7511c2001-05-26 13:15:44 +00002314** Allocate a new page from the database file.
2315**
drha34b6762004-05-07 13:30:42 +00002316** The new page is marked as dirty. (In other words, sqlite3pager_write()
drh3b7511c2001-05-26 13:15:44 +00002317** has already been called on the new page.) The new page has also
2318** been referenced and the calling routine is responsible for calling
drha34b6762004-05-07 13:30:42 +00002319** sqlite3pager_unref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00002320**
2321** SQLITE_OK is returned on success. Any other return value indicates
2322** an error. *ppPage and *pPgno are undefined in the event of an error.
drha34b6762004-05-07 13:30:42 +00002323** Do not invoke sqlite3pager_unref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00002324**
drh199e3cf2002-07-18 11:01:47 +00002325** If the "nearby" parameter is not 0, then a (feeble) effort is made to
2326** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00002327** attempt to keep related pages close to each other in the database file,
2328** which in turn can make database access faster.
drh3b7511c2001-05-26 13:15:44 +00002329*/
drh199e3cf2002-07-18 11:01:47 +00002330static int allocatePage(Btree *pBt, MemPage **ppPage, Pgno *pPgno, Pgno nearby){
drh3aac2dd2004-04-26 14:10:20 +00002331 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00002332 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002333 int n; /* Number of pages on the freelist */
2334 int k; /* Number of leaves on the trunk of the freelist */
drh30e58752002-03-02 20:41:57 +00002335
drh3aac2dd2004-04-26 14:10:20 +00002336 pPage1 = pBt->pPage1;
2337 n = get4byte(&pPage1->aData[36]);
2338 if( n>0 ){
drh91025292004-05-03 19:49:32 +00002339 /* There are pages on the freelist. Reuse one of those pages. */
drh3aac2dd2004-04-26 14:10:20 +00002340 MemPage *pTrunk;
drha34b6762004-05-07 13:30:42 +00002341 rc = sqlite3pager_write(pPage1->aData);
drh3b7511c2001-05-26 13:15:44 +00002342 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00002343 put4byte(&pPage1->aData[36], n-1);
2344 rc = getPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk);
drh3b7511c2001-05-26 13:15:44 +00002345 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00002346 rc = sqlite3pager_write(pTrunk->aData);
drh3b7511c2001-05-26 13:15:44 +00002347 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00002348 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00002349 return rc;
2350 }
drh3aac2dd2004-04-26 14:10:20 +00002351 k = get4byte(&pTrunk->aData[4]);
2352 if( k==0 ){
2353 /* The trunk has no leaves. So extract the trunk page itself and
2354 ** use it as the newly allocated page */
drha34b6762004-05-07 13:30:42 +00002355 *pPgno = get4byte(&pPage1->aData[32]);
drh3aac2dd2004-04-26 14:10:20 +00002356 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
2357 *ppPage = pTrunk;
drh3a4c1412004-05-09 20:40:11 +00002358 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh30e58752002-03-02 20:41:57 +00002359 }else{
drh3aac2dd2004-04-26 14:10:20 +00002360 /* Extract a leaf from the trunk */
2361 int closest;
2362 unsigned char *aData = pTrunk->aData;
2363 if( nearby>0 ){
drhbea00b92002-07-08 10:59:50 +00002364 int i, dist;
2365 closest = 0;
drh3aac2dd2004-04-26 14:10:20 +00002366 dist = get4byte(&aData[8]) - nearby;
drhbea00b92002-07-08 10:59:50 +00002367 if( dist<0 ) dist = -dist;
drh3a4c1412004-05-09 20:40:11 +00002368 for(i=1; i<k; i++){
drh3aac2dd2004-04-26 14:10:20 +00002369 int d2 = get4byte(&aData[8+i*4]) - nearby;
drhbea00b92002-07-08 10:59:50 +00002370 if( d2<0 ) d2 = -d2;
2371 if( d2<dist ) closest = i;
2372 }
2373 }else{
2374 closest = 0;
2375 }
drha34b6762004-05-07 13:30:42 +00002376 *pPgno = get4byte(&aData[8+closest*4]);
drh3a4c1412004-05-09 20:40:11 +00002377 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d: %d more free pages\n",
2378 *pPgno, closest+1, k, pTrunk->pgno, n-1));
drh9b171272004-05-08 02:03:22 +00002379 if( closest<k-1 ){
2380 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
2381 }
drh3a4c1412004-05-09 20:40:11 +00002382 put4byte(&aData[4], k-1);
drh3aac2dd2004-04-26 14:10:20 +00002383 rc = getPage(pBt, *pPgno, ppPage);
2384 releasePage(pTrunk);
drh30e58752002-03-02 20:41:57 +00002385 if( rc==SQLITE_OK ){
drh9b171272004-05-08 02:03:22 +00002386 sqlite3pager_dont_rollback((*ppPage)->aData);
drha34b6762004-05-07 13:30:42 +00002387 rc = sqlite3pager_write((*ppPage)->aData);
drh30e58752002-03-02 20:41:57 +00002388 }
2389 }
drh3b7511c2001-05-26 13:15:44 +00002390 }else{
drh3aac2dd2004-04-26 14:10:20 +00002391 /* There are no pages on the freelist, so create a new page at the
2392 ** end of the file */
drha34b6762004-05-07 13:30:42 +00002393 *pPgno = sqlite3pager_pagecount(pBt->pPager) + 1;
drh3aac2dd2004-04-26 14:10:20 +00002394 rc = getPage(pBt, *pPgno, ppPage);
drh3b7511c2001-05-26 13:15:44 +00002395 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00002396 rc = sqlite3pager_write((*ppPage)->aData);
drh3a4c1412004-05-09 20:40:11 +00002397 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00002398 }
2399 return rc;
2400}
2401
2402/*
drh3aac2dd2004-04-26 14:10:20 +00002403** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00002404**
drha34b6762004-05-07 13:30:42 +00002405** sqlite3pager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00002406*/
drh3aac2dd2004-04-26 14:10:20 +00002407static int freePage(MemPage *pPage){
2408 Btree *pBt = pPage->pBt;
2409 MemPage *pPage1 = pBt->pPage1;
2410 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00002411
drh3aac2dd2004-04-26 14:10:20 +00002412 /* Prepare the page for freeing */
2413 assert( pPage->pgno>1 );
2414 pPage->isInit = 0;
2415 releasePage(pPage->pParent);
2416 pPage->pParent = 0;
2417
drha34b6762004-05-07 13:30:42 +00002418 /* Increment the free page count on pPage1 */
2419 rc = sqlite3pager_write(pPage1->aData);
drh3aac2dd2004-04-26 14:10:20 +00002420 if( rc ) return rc;
2421 n = get4byte(&pPage1->aData[36]);
2422 put4byte(&pPage1->aData[36], n+1);
2423
2424 if( n==0 ){
2425 /* This is the first free page */
drhda200cc2004-05-09 11:51:38 +00002426 rc = sqlite3pager_write(pPage->aData);
2427 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00002428 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00002429 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00002430 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00002431 }else{
2432 /* Other free pages already exist. Retrive the first trunk page
2433 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00002434 MemPage *pTrunk;
2435 rc = getPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk);
drh3b7511c2001-05-26 13:15:44 +00002436 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00002437 k = get4byte(&pTrunk->aData[4]);
drhb6f41482004-05-14 01:58:11 +00002438 if( k==pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00002439 /* The trunk is full. Turn the page being freed into a new
2440 ** trunk page with no leaves. */
drha34b6762004-05-07 13:30:42 +00002441 rc = sqlite3pager_write(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00002442 if( rc ) return rc;
2443 put4byte(pPage->aData, pTrunk->pgno);
2444 put4byte(&pPage->aData[4], 0);
2445 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00002446 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
2447 pPage->pgno, pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00002448 }else{
2449 /* Add the newly freed page as a leaf on the current trunk */
drha34b6762004-05-07 13:30:42 +00002450 rc = sqlite3pager_write(pTrunk->aData);
drh3aac2dd2004-04-26 14:10:20 +00002451 if( rc ) return rc;
2452 put4byte(&pTrunk->aData[4], k+1);
2453 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drha34b6762004-05-07 13:30:42 +00002454 sqlite3pager_dont_write(pBt->pPager, pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00002455 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00002456 }
2457 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00002458 }
drh3b7511c2001-05-26 13:15:44 +00002459 return rc;
2460}
2461
2462/*
drh3aac2dd2004-04-26 14:10:20 +00002463** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00002464*/
drh3aac2dd2004-04-26 14:10:20 +00002465static int clearCell(MemPage *pPage, unsigned char *pCell){
2466 Btree *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00002467 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00002468 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00002469 int rc;
drh3b7511c2001-05-26 13:15:44 +00002470
drh43605152004-05-29 21:46:49 +00002471 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00002472 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00002473 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00002474 }
drh6f11bef2004-05-13 01:12:56 +00002475 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh3aac2dd2004-04-26 14:10:20 +00002476 while( ovflPgno!=0 ){
2477 MemPage *pOvfl;
2478 rc = getPage(pBt, ovflPgno, &pOvfl);
drh3b7511c2001-05-26 13:15:44 +00002479 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00002480 ovflPgno = get4byte(pOvfl->aData);
drha34b6762004-05-07 13:30:42 +00002481 rc = freePage(pOvfl);
drhbd03cae2001-06-02 02:40:57 +00002482 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00002483 sqlite3pager_unref(pOvfl->aData);
drh3b7511c2001-05-26 13:15:44 +00002484 }
drh5e2f8b92001-05-28 00:41:15 +00002485 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00002486}
2487
2488/*
drh91025292004-05-03 19:49:32 +00002489** Create the byte sequence used to represent a cell on page pPage
2490** and write that byte sequence into pCell[]. Overflow pages are
2491** allocated and filled in as necessary. The calling procedure
2492** is responsible for making sure sufficient space has been allocated
2493** for pCell[].
2494**
2495** Note that pCell does not necessary need to point to the pPage->aData
2496** area. pCell might point to some temporary storage. The cell will
2497** be constructed in this temporary area then copied into pPage->aData
2498** later.
drh3b7511c2001-05-26 13:15:44 +00002499*/
2500static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00002501 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00002502 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00002503 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00002504 const void *pData,int nData, /* The data */
2505 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00002506){
drh3b7511c2001-05-26 13:15:44 +00002507 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00002508 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00002509 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00002510 int spaceLeft;
2511 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00002512 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00002513 unsigned char *pPrior;
2514 unsigned char *pPayload;
2515 Btree *pBt = pPage->pBt;
2516 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00002517 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00002518 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00002519
drh91025292004-05-03 19:49:32 +00002520 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00002521 nHeader = 0;
drh91025292004-05-03 19:49:32 +00002522 if( !pPage->leaf ){
2523 nHeader += 4;
2524 }
drh8b18dd42004-05-12 19:18:15 +00002525 if( pPage->hasData ){
drh91025292004-05-03 19:49:32 +00002526 nHeader += putVarint(&pCell[nHeader], nData);
drh6f11bef2004-05-13 01:12:56 +00002527 }else{
drh91025292004-05-03 19:49:32 +00002528 nData = 0;
2529 }
drh6f11bef2004-05-13 01:12:56 +00002530 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh43605152004-05-29 21:46:49 +00002531 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00002532 assert( info.nHeader==nHeader );
2533 assert( info.nKey==nKey );
2534 assert( info.nData==nData );
2535
2536 /* Fill in the payload */
drh3aac2dd2004-04-26 14:10:20 +00002537 nPayload = nData;
2538 if( pPage->intKey ){
2539 pSrc = pData;
2540 nSrc = nData;
drh91025292004-05-03 19:49:32 +00002541 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00002542 }else{
2543 nPayload += nKey;
2544 pSrc = pKey;
2545 nSrc = nKey;
2546 }
drh6f11bef2004-05-13 01:12:56 +00002547 *pnSize = info.nSize;
2548 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00002549 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00002550 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00002551
drh3b7511c2001-05-26 13:15:44 +00002552 while( nPayload>0 ){
2553 if( spaceLeft==0 ){
drh3aac2dd2004-04-26 14:10:20 +00002554 rc = allocatePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl);
drh3b7511c2001-05-26 13:15:44 +00002555 if( rc ){
drh9b171272004-05-08 02:03:22 +00002556 releasePage(pToRelease);
drh3aac2dd2004-04-26 14:10:20 +00002557 clearCell(pPage, pCell);
drh3b7511c2001-05-26 13:15:44 +00002558 return rc;
2559 }
drh3aac2dd2004-04-26 14:10:20 +00002560 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00002561 releasePage(pToRelease);
2562 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00002563 pPrior = pOvfl->aData;
2564 put4byte(pPrior, 0);
2565 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00002566 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00002567 }
2568 n = nPayload;
2569 if( n>spaceLeft ) n = spaceLeft;
drh3aac2dd2004-04-26 14:10:20 +00002570 if( n>nSrc ) n = nSrc;
2571 memcpy(pPayload, pSrc, n);
drh3b7511c2001-05-26 13:15:44 +00002572 nPayload -= n;
drhde647132004-05-07 17:57:49 +00002573 pPayload += n;
drh9b171272004-05-08 02:03:22 +00002574 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00002575 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00002576 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00002577 if( nSrc==0 ){
2578 nSrc = nData;
2579 pSrc = pData;
2580 }
drhdd793422001-06-28 01:54:48 +00002581 }
drh9b171272004-05-08 02:03:22 +00002582 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00002583 return SQLITE_OK;
2584}
2585
2586/*
drhbd03cae2001-06-02 02:40:57 +00002587** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00002588** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00002589** pointer in the third argument.
2590*/
drh4b70f112004-05-02 21:12:19 +00002591static void reparentPage(Btree *pBt, Pgno pgno, MemPage *pNewParent, int idx){
drhbd03cae2001-06-02 02:40:57 +00002592 MemPage *pThis;
drh4b70f112004-05-02 21:12:19 +00002593 unsigned char *aData;
drhbd03cae2001-06-02 02:40:57 +00002594
drhdd793422001-06-28 01:54:48 +00002595 if( pgno==0 ) return;
drh4b70f112004-05-02 21:12:19 +00002596 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00002597 aData = sqlite3pager_lookup(pBt->pPager, pgno);
drhda200cc2004-05-09 11:51:38 +00002598 if( aData ){
drhb6f41482004-05-14 01:58:11 +00002599 pThis = (MemPage*)&aData[pBt->usableSize];
drhda200cc2004-05-09 11:51:38 +00002600 if( pThis->isInit ){
2601 if( pThis->pParent!=pNewParent ){
2602 if( pThis->pParent ) sqlite3pager_unref(pThis->pParent->aData);
2603 pThis->pParent = pNewParent;
2604 if( pNewParent ) sqlite3pager_ref(pNewParent->aData);
2605 }
2606 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00002607 }
drha34b6762004-05-07 13:30:42 +00002608 sqlite3pager_unref(aData);
drhbd03cae2001-06-02 02:40:57 +00002609 }
2610}
2611
2612/*
drh4b70f112004-05-02 21:12:19 +00002613** Change the pParent pointer of all children of pPage to point back
2614** to pPage.
2615**
drhbd03cae2001-06-02 02:40:57 +00002616** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00002617** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00002618**
2619** This routine gets called after you memcpy() one page into
2620** another.
2621*/
drh4b70f112004-05-02 21:12:19 +00002622static void reparentChildPages(MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00002623 int i;
drh4b70f112004-05-02 21:12:19 +00002624 Btree *pBt;
2625
drha34b6762004-05-07 13:30:42 +00002626 if( pPage->leaf ) return;
drh4b70f112004-05-02 21:12:19 +00002627 pBt = pPage->pBt;
drhbd03cae2001-06-02 02:40:57 +00002628 for(i=0; i<pPage->nCell; i++){
drh43605152004-05-29 21:46:49 +00002629 reparentPage(pBt, get4byte(findCell(pPage,i)), pPage, i);
drhbd03cae2001-06-02 02:40:57 +00002630 }
drh43605152004-05-29 21:46:49 +00002631 reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]), pPage, i);
drh428ae8c2003-01-04 16:48:09 +00002632 pPage->idxShift = 0;
drh14acc042001-06-10 19:56:58 +00002633}
2634
2635/*
2636** Remove the i-th cell from pPage. This routine effects pPage only.
2637** The cell content is not freed or deallocated. It is assumed that
2638** the cell content has been copied someplace else. This routine just
2639** removes the reference to the cell from pPage.
2640**
2641** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00002642*/
drh4b70f112004-05-02 21:12:19 +00002643static void dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00002644 int i; /* Loop counter */
2645 int pc; /* Offset to cell content of cell being deleted */
2646 u8 *data; /* pPage->aData */
2647 u8 *ptr; /* Used to move bytes around within data[] */
2648
drh8c42ca92001-06-22 19:15:00 +00002649 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00002650 assert( sz==cellSize(pPage, idx) );
drha34b6762004-05-07 13:30:42 +00002651 assert( sqlite3pager_iswriteable(pPage->aData) );
drhda200cc2004-05-09 11:51:38 +00002652 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00002653 ptr = &data[pPage->cellOffset + 2*idx];
2654 pc = get2byte(ptr);
2655 assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
drhde647132004-05-07 17:57:49 +00002656 freeSpace(pPage, pc, sz);
drh43605152004-05-29 21:46:49 +00002657 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
2658 ptr[0] = ptr[2];
2659 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00002660 }
2661 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00002662 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
2663 pPage->nFree += 2;
drh428ae8c2003-01-04 16:48:09 +00002664 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00002665}
2666
2667/*
2668** Insert a new cell on pPage at cell index "i". pCell points to the
2669** content of the cell.
2670**
2671** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00002672** will not fit, then make a copy of the cell content into pTemp if
2673** pTemp is not null. Regardless of pTemp, allocate a new entry
2674** in pPage->aOvfl[] and make it point to the cell content (either
2675** in pTemp or the original pCell) and also record its index.
2676** Allocating a new entry in pPage->aCell[] implies that
2677** pPage->nOverflow is incremented.
drh14acc042001-06-10 19:56:58 +00002678*/
drh24cd67e2004-05-10 16:18:47 +00002679static void insertCell(
2680 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00002681 int i, /* New cell becomes the i-th cell of the page */
2682 u8 *pCell, /* Content of the new cell */
2683 int sz, /* Bytes of content in pCell */
drh24cd67e2004-05-10 16:18:47 +00002684 u8 *pTemp /* Temp storage space for pCell, if needed */
2685){
drh43605152004-05-29 21:46:49 +00002686 int idx; /* Where to write new cell content in data[] */
2687 int j; /* Loop counter */
2688 int top; /* First byte of content for any cell in data[] */
2689 int end; /* First byte past the last cell pointer in data[] */
2690 int ins; /* Index in data[] where new cell pointer is inserted */
2691 int hdr; /* Offset into data[] of the page header */
2692 int cellOffset; /* Address of first cell pointer in data[] */
2693 u8 *data; /* The content of the whole page */
2694 u8 *ptr; /* Used for moving information around in data[] */
2695
2696 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
2697 assert( sz==cellSizePtr(pPage, pCell) );
drha34b6762004-05-07 13:30:42 +00002698 assert( sqlite3pager_iswriteable(pPage->aData) );
drh43605152004-05-29 21:46:49 +00002699 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00002700 if( pTemp ){
2701 memcpy(pTemp, pCell, sz);
drh43605152004-05-29 21:46:49 +00002702 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00002703 }
drh43605152004-05-29 21:46:49 +00002704 j = pPage->nOverflow++;
2705 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
2706 pPage->aOvfl[j].pCell = pCell;
2707 pPage->aOvfl[j].idx = i;
2708 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00002709 }else{
drh43605152004-05-29 21:46:49 +00002710 data = pPage->aData;
2711 hdr = pPage->hdrOffset;
2712 top = get2byte(&data[hdr+5]);
2713 cellOffset = pPage->cellOffset;
2714 end = cellOffset + 2*pPage->nCell + 2;
2715 ins = cellOffset + 2*i;
2716 if( end > top - sz ){
2717 defragmentPage(pPage);
2718 top = get2byte(&data[hdr+5]);
2719 assert( end + sz <= top );
2720 }
2721 idx = allocateSpace(pPage, sz);
2722 assert( idx>0 );
2723 assert( end <= get2byte(&data[hdr+5]) );
2724 pPage->nCell++;
2725 pPage->nFree -= 2;
drhda200cc2004-05-09 11:51:38 +00002726 memcpy(&data[idx], pCell, sz);
drh43605152004-05-29 21:46:49 +00002727 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
2728 ptr[0] = ptr[-2];
2729 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00002730 }
drh43605152004-05-29 21:46:49 +00002731 put2byte(&data[ins], idx);
2732 put2byte(&data[hdr+3], pPage->nCell);
2733 pPage->idxShift = 1;
drhda200cc2004-05-09 11:51:38 +00002734 pageIntegrity(pPage);
drh14acc042001-06-10 19:56:58 +00002735 }
2736}
2737
2738/*
drhfa1a98a2004-05-14 19:08:17 +00002739** Add a list of cells to a page. The page should be initially empty.
2740** The cells are guaranteed to fit on the page.
2741*/
2742static void assemblePage(
2743 MemPage *pPage, /* The page to be assemblied */
2744 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00002745 u8 **apCell, /* Pointers to cell bodies */
drhfa1a98a2004-05-14 19:08:17 +00002746 int *aSize /* Sizes of the cells */
2747){
2748 int i; /* Loop counter */
2749 int totalSize; /* Total size of all cells */
2750 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00002751 int cellptr; /* Address of next cell pointer */
2752 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00002753 u8 *data; /* Data for the page */
2754
drh43605152004-05-29 21:46:49 +00002755 assert( pPage->nOverflow==0 );
drhfa1a98a2004-05-14 19:08:17 +00002756 totalSize = 0;
2757 for(i=0; i<nCell; i++){
2758 totalSize += aSize[i];
2759 }
drh43605152004-05-29 21:46:49 +00002760 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00002761 assert( pPage->nCell==0 );
drh43605152004-05-29 21:46:49 +00002762 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00002763 data = pPage->aData;
2764 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00002765 put2byte(&data[hdr+3], nCell);
2766 cellbody = allocateSpace(pPage, totalSize);
2767 assert( cellbody>0 );
2768 assert( pPage->nFree >= 2*nCell );
2769 pPage->nFree -= 2*nCell;
drhfa1a98a2004-05-14 19:08:17 +00002770 for(i=0; i<nCell; i++){
drh43605152004-05-29 21:46:49 +00002771 put2byte(&data[cellptr], cellbody);
2772 memcpy(&data[cellbody], apCell[i], aSize[i]);
2773 cellptr += 2;
2774 cellbody += aSize[i];
drhfa1a98a2004-05-14 19:08:17 +00002775 }
drh43605152004-05-29 21:46:49 +00002776 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00002777 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00002778}
2779
drh14acc042001-06-10 19:56:58 +00002780/*
drhc8629a12004-05-08 20:07:40 +00002781** GCC does not define the offsetof() macro so we'll have to do it
2782** ourselves.
2783*/
2784#ifndef offsetof
2785#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
2786#endif
2787
2788/*
drhc3b70572003-01-04 19:44:07 +00002789** The following parameters determine how many adjacent pages get involved
2790** in a balancing operation. NN is the number of neighbors on either side
2791** of the page that participate in the balancing operation. NB is the
2792** total number of pages that participate, including the target page and
2793** NN neighbors on either side.
2794**
2795** The minimum value of NN is 1 (of course). Increasing NN above 1
2796** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
2797** in exchange for a larger degradation in INSERT and UPDATE performance.
2798** The value of NN appears to give the best results overall.
2799*/
2800#define NN 1 /* Number of neighbors on either side of pPage */
2801#define NB (NN*2+1) /* Total pages involved in the balance */
2802
drh43605152004-05-29 21:46:49 +00002803/* Forward reference */
2804static int balance(MemPage*);
2805
drhc3b70572003-01-04 19:44:07 +00002806/*
drhab01f612004-05-22 02:55:23 +00002807** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00002808** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00002809** Usually NN siblings on either side of pPage is used in the balancing,
2810** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00002811** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00002812** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00002813** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00002814**
drh0c6cc4e2004-06-15 02:13:26 +00002815** The number of siblings of pPage might be increased or decreased by one or
2816** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00002817** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00002818** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00002819** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00002820** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00002821**
drh8b2f49b2001-06-08 00:21:52 +00002822** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00002823** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00002824** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00002825** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00002826**
drh8c42ca92001-06-22 19:15:00 +00002827** In the course of balancing the siblings of pPage, the parent of pPage
2828** might become overfull or underfull. If that happens, then this routine
2829** is called recursively on the parent.
2830**
drh5e00f6c2001-09-13 13:46:56 +00002831** If this routine fails for any reason, it might leave the database
2832** in a corrupted state. So if this routine fails, the database should
2833** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00002834*/
drh43605152004-05-29 21:46:49 +00002835static int balance_nonroot(MemPage *pPage){
drh8b2f49b2001-06-08 00:21:52 +00002836 MemPage *pParent; /* The parent of pPage */
drh4b70f112004-05-02 21:12:19 +00002837 Btree *pBt; /* The whole database */
drha34b6762004-05-07 13:30:42 +00002838 int nCell; /* Number of cells in aCell[] */
drh8b2f49b2001-06-08 00:21:52 +00002839 int nOld; /* Number of pages in apOld[] */
2840 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00002841 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00002842 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00002843 int idx; /* Index of pPage in pParent->aCell[] */
2844 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00002845 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00002846 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00002847 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00002848 int usableSpace; /* Bytes in pPage beyond the header */
2849 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00002850 int subtotal; /* Subtotal of bytes in cells on one page */
drhb6f41482004-05-14 01:58:11 +00002851 int iSpace = 0; /* First unused byte of aSpace[] */
drhc3b70572003-01-04 19:44:07 +00002852 MemPage *apOld[NB]; /* pPage and up to two siblings */
2853 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00002854 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00002855 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
2856 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drhc3b70572003-01-04 19:44:07 +00002857 int idxDiv[NB]; /* Indices of divider cells in pParent */
drh4b70f112004-05-02 21:12:19 +00002858 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00002859 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
2860 int szNew[NB+2]; /* Combined size of cells place on i-th page */
drh4b70f112004-05-02 21:12:19 +00002861 u8 *apCell[(MX_CELL+2)*NB]; /* All cells from pages being balanced */
drhc3b70572003-01-04 19:44:07 +00002862 int szCell[(MX_CELL+2)*NB]; /* Local size of all cells */
drh4b70f112004-05-02 21:12:19 +00002863 u8 aCopy[NB][MX_PAGE_SIZE+sizeof(MemPage)]; /* Space for apCopy[] */
drha2fce642004-06-05 00:01:44 +00002864 u8 aSpace[MX_PAGE_SIZE*5]; /* Space to copies of divider cells */
drh8b2f49b2001-06-08 00:21:52 +00002865
drh14acc042001-06-10 19:56:58 +00002866 /*
drh43605152004-05-29 21:46:49 +00002867 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00002868 */
drh3a4c1412004-05-09 20:40:11 +00002869 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00002870 assert( sqlite3pager_iswriteable(pPage->aData) );
drh4b70f112004-05-02 21:12:19 +00002871 pBt = pPage->pBt;
drh14acc042001-06-10 19:56:58 +00002872 pParent = pPage->pParent;
drh43605152004-05-29 21:46:49 +00002873 sqlite3pager_write(pParent->aData);
2874 assert( pParent );
2875 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh14acc042001-06-10 19:56:58 +00002876
drh8b2f49b2001-06-08 00:21:52 +00002877 /*
drh4b70f112004-05-02 21:12:19 +00002878 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00002879 ** to pPage. The "idx" variable is the index of that cell. If pPage
2880 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00002881 */
drhbb49aba2003-01-04 18:53:27 +00002882 if( pParent->idxShift ){
drha34b6762004-05-07 13:30:42 +00002883 Pgno pgno;
drh4b70f112004-05-02 21:12:19 +00002884 pgno = pPage->pgno;
drha34b6762004-05-07 13:30:42 +00002885 assert( pgno==sqlite3pager_pagenumber(pPage->aData) );
drhbb49aba2003-01-04 18:53:27 +00002886 for(idx=0; idx<pParent->nCell; idx++){
drh43605152004-05-29 21:46:49 +00002887 if( get4byte(findCell(pParent, idx))==pgno ){
drhbb49aba2003-01-04 18:53:27 +00002888 break;
2889 }
drh8b2f49b2001-06-08 00:21:52 +00002890 }
drh4b70f112004-05-02 21:12:19 +00002891 assert( idx<pParent->nCell
drh43605152004-05-29 21:46:49 +00002892 || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
drhbb49aba2003-01-04 18:53:27 +00002893 }else{
2894 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00002895 }
drh8b2f49b2001-06-08 00:21:52 +00002896
2897 /*
drh14acc042001-06-10 19:56:58 +00002898 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00002899 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00002900 */
drh14acc042001-06-10 19:56:58 +00002901 nOld = nNew = 0;
drha34b6762004-05-07 13:30:42 +00002902 sqlite3pager_ref(pParent->aData);
drh14acc042001-06-10 19:56:58 +00002903
2904 /*
drh4b70f112004-05-02 21:12:19 +00002905 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00002906 ** the siblings. An attempt is made to find NN siblings on either
2907 ** side of pPage. More siblings are taken from one side, however, if
2908 ** pPage there are fewer than NN siblings on the other side. If pParent
2909 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00002910 */
drhc3b70572003-01-04 19:44:07 +00002911 nxDiv = idx - NN;
2912 if( nxDiv + NB > pParent->nCell ){
2913 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00002914 }
drhc3b70572003-01-04 19:44:07 +00002915 if( nxDiv<0 ){
2916 nxDiv = 0;
2917 }
drh8b2f49b2001-06-08 00:21:52 +00002918 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00002919 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00002920 if( k<pParent->nCell ){
2921 idxDiv[i] = k;
drh43605152004-05-29 21:46:49 +00002922 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00002923 nDiv++;
drha34b6762004-05-07 13:30:42 +00002924 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00002925 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00002926 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00002927 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00002928 }else{
2929 break;
drh8b2f49b2001-06-08 00:21:52 +00002930 }
drhde647132004-05-07 17:57:49 +00002931 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00002932 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00002933 apOld[i]->idxParent = k;
drh91025292004-05-03 19:49:32 +00002934 apCopy[i] = 0;
2935 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00002936 nOld++;
drh8b2f49b2001-06-08 00:21:52 +00002937 }
2938
2939 /*
drh14acc042001-06-10 19:56:58 +00002940 ** Make copies of the content of pPage and its siblings into aOld[].
2941 ** The rest of this function will use data from the copies rather
2942 ** that the original pages since the original pages will be in the
2943 ** process of being overwritten.
2944 */
2945 for(i=0; i<nOld; i++){
drhc8629a12004-05-08 20:07:40 +00002946 MemPage *p = apCopy[i] = (MemPage*)&aCopy[i+1][-sizeof(MemPage)];
drh43605152004-05-29 21:46:49 +00002947 p->aData = &((u8*)p)[-pBt->pageSize];
2948 memcpy(p->aData, apOld[i]->aData, pBt->pageSize + sizeof(MemPage));
2949 p->aData = &((u8*)p)[-pBt->pageSize];
drh14acc042001-06-10 19:56:58 +00002950 }
2951
2952 /*
2953 ** Load pointers to all cells on sibling pages and the divider cells
2954 ** into the local apCell[] array. Make copies of the divider cells
drhb6f41482004-05-14 01:58:11 +00002955 ** into space obtained form aSpace[] and remove the the divider Cells
2956 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00002957 **
2958 ** If the siblings are on leaf pages, then the child pointers of the
2959 ** divider cells are stripped from the cells before they are copied
drh96f5b762004-05-16 16:24:36 +00002960 ** into aSpace[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00002961 ** child pointers. If siblings are not leaves, then all cell in
2962 ** apCell[] include child pointers. Either way, all cells in apCell[]
2963 ** are alike.
drh96f5b762004-05-16 16:24:36 +00002964 **
2965 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
2966 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00002967 */
2968 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00002969 leafCorrection = pPage->leaf*4;
drh8b18dd42004-05-12 19:18:15 +00002970 leafData = pPage->leafData && pPage->leaf;
drh8b2f49b2001-06-08 00:21:52 +00002971 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00002972 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00002973 int limit = pOld->nCell+pOld->nOverflow;
2974 for(j=0; j<limit; j++){
2975 apCell[nCell] = findOverflowCell(pOld, j);
2976 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
drh14acc042001-06-10 19:56:58 +00002977 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00002978 }
2979 if( i<nOld-1 ){
drh43605152004-05-29 21:46:49 +00002980 int sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00002981 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00002982 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
2983 ** are duplicates of keys on the child pages. We need to remove
2984 ** the divider cells from pParent, but the dividers cells are not
2985 ** added to apCell[] because they are duplicates of child cells.
2986 */
drh8b18dd42004-05-12 19:18:15 +00002987 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00002988 }else{
drhb6f41482004-05-14 01:58:11 +00002989 u8 *pTemp;
2990 szCell[nCell] = sz;
2991 pTemp = &aSpace[iSpace];
2992 iSpace += sz;
2993 assert( iSpace<=sizeof(aSpace) );
2994 memcpy(pTemp, apDiv[i], sz);
2995 apCell[nCell] = pTemp+leafCorrection;
2996 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00002997 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00002998 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00002999 if( !pOld->leaf ){
3000 assert( leafCorrection==0 );
3001 /* The right pointer of the child page pOld becomes the left
3002 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00003003 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00003004 }else{
3005 assert( leafCorrection==4 );
3006 }
3007 nCell++;
drh4b70f112004-05-02 21:12:19 +00003008 }
drh8b2f49b2001-06-08 00:21:52 +00003009 }
3010 }
3011
3012 /*
drh6019e162001-07-02 17:51:45 +00003013 ** Figure out the number of pages needed to hold all nCell cells.
3014 ** Store this number in "k". Also compute szNew[] which is the total
3015 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00003016 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00003017 ** cntNew[k] should equal nCell.
3018 **
drh96f5b762004-05-16 16:24:36 +00003019 ** Values computed by this block:
3020 **
3021 ** k: The total number of sibling pages
3022 ** szNew[i]: Spaced used on the i-th sibling page.
3023 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
3024 ** the right of the i-th sibling page.
3025 ** usableSpace: Number of bytes of space available on each sibling.
3026 **
drh8b2f49b2001-06-08 00:21:52 +00003027 */
drh43605152004-05-29 21:46:49 +00003028 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00003029 for(subtotal=k=i=0; i<nCell; i++){
drh43605152004-05-29 21:46:49 +00003030 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00003031 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00003032 szNew[k] = subtotal - szCell[i];
3033 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00003034 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00003035 subtotal = 0;
3036 k++;
3037 }
3038 }
3039 szNew[k] = subtotal;
3040 cntNew[k] = nCell;
3041 k++;
drh96f5b762004-05-16 16:24:36 +00003042
3043 /*
3044 ** The packing computed by the previous block is biased toward the siblings
3045 ** on the left side. The left siblings are always nearly full, while the
3046 ** right-most sibling might be nearly empty. This block of code attempts
3047 ** to adjust the packing of siblings to get a better balance.
3048 **
3049 ** This adjustment is more than an optimization. The packing above might
3050 ** be so out of balance as to be illegal. For example, the right-most
3051 ** sibling might be completely empty. This adjustment is not optional.
3052 */
drh6019e162001-07-02 17:51:45 +00003053 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00003054 int szRight = szNew[i]; /* Size of sibling on the right */
3055 int szLeft = szNew[i-1]; /* Size of sibling on the left */
3056 int r; /* Index of right-most cell in left sibling */
3057 int d; /* Index of first cell to the left of right sibling */
3058
3059 r = cntNew[i-1] - 1;
3060 d = r + 1 - leafData;
drh43605152004-05-29 21:46:49 +00003061 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
3062 szRight += szCell[d] + 2;
3063 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00003064 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00003065 r = cntNew[i-1] - 1;
3066 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00003067 }
drh96f5b762004-05-16 16:24:36 +00003068 szNew[i] = szRight;
3069 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00003070 }
3071 assert( cntNew[0]>0 );
drh8b2f49b2001-06-08 00:21:52 +00003072
3073 /*
drh6b308672002-07-08 02:16:37 +00003074 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00003075 */
drh4b70f112004-05-02 21:12:19 +00003076 assert( pPage->pgno>1 );
3077 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00003078 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00003079 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00003080 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00003081 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00003082 pgnoNew[i] = pgnoOld[i];
3083 apOld[i] = 0;
drhda200cc2004-05-09 11:51:38 +00003084 sqlite3pager_write(pNew->aData);
drh6b308672002-07-08 02:16:37 +00003085 }else{
drhda200cc2004-05-09 11:51:38 +00003086 rc = allocatePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1]);
drh6b308672002-07-08 02:16:37 +00003087 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00003088 apNew[i] = pNew;
drh6b308672002-07-08 02:16:37 +00003089 }
drh14acc042001-06-10 19:56:58 +00003090 nNew++;
drhda200cc2004-05-09 11:51:38 +00003091 zeroPage(pNew, pageFlags);
drh8b2f49b2001-06-08 00:21:52 +00003092 }
3093
drh6b308672002-07-08 02:16:37 +00003094 /* Free any old pages that were not reused as new pages.
3095 */
3096 while( i<nOld ){
drh4b70f112004-05-02 21:12:19 +00003097 rc = freePage(apOld[i]);
drh6b308672002-07-08 02:16:37 +00003098 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00003099 releasePage(apOld[i]);
drh6b308672002-07-08 02:16:37 +00003100 apOld[i] = 0;
3101 i++;
3102 }
3103
drh8b2f49b2001-06-08 00:21:52 +00003104 /*
drhf9ffac92002-03-02 19:00:31 +00003105 ** Put the new pages in accending order. This helps to
3106 ** keep entries in the disk file in order so that a scan
3107 ** of the table is a linear scan through the file. That
3108 ** in turn helps the operating system to deliver pages
3109 ** from the disk more rapidly.
3110 **
3111 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00003112 ** n is never more than NB (a small constant), that should
3113 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00003114 **
drhc3b70572003-01-04 19:44:07 +00003115 ** When NB==3, this one optimization makes the database
3116 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00003117 */
3118 for(i=0; i<k-1; i++){
3119 int minV = pgnoNew[i];
3120 int minI = i;
3121 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00003122 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00003123 minI = j;
3124 minV = pgnoNew[j];
3125 }
3126 }
3127 if( minI>i ){
3128 int t;
3129 MemPage *pT;
3130 t = pgnoNew[i];
3131 pT = apNew[i];
3132 pgnoNew[i] = pgnoNew[minI];
3133 apNew[i] = apNew[minI];
3134 pgnoNew[minI] = t;
3135 apNew[minI] = pT;
3136 }
3137 }
drha2fce642004-06-05 00:01:44 +00003138 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00003139 pgnoOld[0],
3140 nOld>=2 ? pgnoOld[1] : 0,
3141 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00003142 pgnoNew[0], szNew[0],
3143 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
3144 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00003145 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
3146 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00003147
drhf9ffac92002-03-02 19:00:31 +00003148
3149 /*
drh14acc042001-06-10 19:56:58 +00003150 ** Evenly distribute the data in apCell[] across the new pages.
3151 ** Insert divider cells into pParent as necessary.
3152 */
3153 j = 0;
3154 for(i=0; i<nNew; i++){
3155 MemPage *pNew = apNew[i];
drh4b70f112004-05-02 21:12:19 +00003156 assert( pNew->pgno==pgnoNew[i] );
drhfa1a98a2004-05-14 19:08:17 +00003157 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
3158 j = cntNew[i];
drh6019e162001-07-02 17:51:45 +00003159 assert( pNew->nCell>0 );
drh43605152004-05-29 21:46:49 +00003160 assert( pNew->nOverflow==0 );
drh14acc042001-06-10 19:56:58 +00003161 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00003162 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00003163 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00003164 int sz;
3165 pCell = apCell[j];
3166 sz = szCell[j] + leafCorrection;
drh4b70f112004-05-02 21:12:19 +00003167 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00003168 memcpy(&pNew->aData[8], pCell, 4);
drh24cd67e2004-05-10 16:18:47 +00003169 pTemp = 0;
drh8b18dd42004-05-12 19:18:15 +00003170 }else if( leafData ){
drh6f11bef2004-05-13 01:12:56 +00003171 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00003172 j--;
drh43605152004-05-29 21:46:49 +00003173 parseCellPtr(pNew, apCell[j], &info);
drhb6f41482004-05-14 01:58:11 +00003174 pCell = &aSpace[iSpace];
drh6f11bef2004-05-13 01:12:56 +00003175 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, &sz);
drhb6f41482004-05-14 01:58:11 +00003176 iSpace += sz;
3177 assert( iSpace<=sizeof(aSpace) );
drh8b18dd42004-05-12 19:18:15 +00003178 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00003179 }else{
3180 pCell -= 4;
drhb6f41482004-05-14 01:58:11 +00003181 pTemp = &aSpace[iSpace];
3182 iSpace += sz;
3183 assert( iSpace<=sizeof(aSpace) );
drh4b70f112004-05-02 21:12:19 +00003184 }
drh8b18dd42004-05-12 19:18:15 +00003185 insertCell(pParent, nxDiv, pCell, sz, pTemp);
drh43605152004-05-29 21:46:49 +00003186 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
drh14acc042001-06-10 19:56:58 +00003187 j++;
3188 nxDiv++;
3189 }
3190 }
drh6019e162001-07-02 17:51:45 +00003191 assert( j==nCell );
drh4b70f112004-05-02 21:12:19 +00003192 if( (pageFlags & PTF_LEAF)==0 ){
drh43605152004-05-29 21:46:49 +00003193 memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
drh14acc042001-06-10 19:56:58 +00003194 }
drh43605152004-05-29 21:46:49 +00003195 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00003196 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00003197 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00003198 }else{
3199 /* Right-most sibling is the left child of the first entry in pParent
3200 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00003201 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00003202 }
3203
3204 /*
3205 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00003206 */
3207 for(i=0; i<nNew; i++){
drh4b70f112004-05-02 21:12:19 +00003208 reparentChildPages(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00003209 }
drh4b70f112004-05-02 21:12:19 +00003210 reparentChildPages(pParent);
drh8b2f49b2001-06-08 00:21:52 +00003211
3212 /*
drh3a4c1412004-05-09 20:40:11 +00003213 ** Balance the parent page. Note that the current page (pPage) might
3214 ** have been added to the freelist is it might no longer be initialized.
3215 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00003216 */
drhda200cc2004-05-09 11:51:38 +00003217 assert( pParent->isInit );
drh3a4c1412004-05-09 20:40:11 +00003218 /* assert( pPage->isInit ); // No! pPage might have been added to freelist */
3219 /* pageIntegrity(pPage); // No! pPage might have been added to freelist */
drh4b70f112004-05-02 21:12:19 +00003220 rc = balance(pParent);
drhda200cc2004-05-09 11:51:38 +00003221
drh8b2f49b2001-06-08 00:21:52 +00003222 /*
drh14acc042001-06-10 19:56:58 +00003223 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00003224 */
drh14acc042001-06-10 19:56:58 +00003225balance_cleanup:
drh8b2f49b2001-06-08 00:21:52 +00003226 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00003227 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00003228 }
drh14acc042001-06-10 19:56:58 +00003229 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00003230 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00003231 }
drh91025292004-05-03 19:49:32 +00003232 releasePage(pParent);
drh3a4c1412004-05-09 20:40:11 +00003233 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
3234 pPage->pgno, nOld, nNew, nCell));
drh8b2f49b2001-06-08 00:21:52 +00003235 return rc;
3236}
3237
3238/*
drh43605152004-05-29 21:46:49 +00003239** This routine is called for the root page of a btree when the root
3240** page contains no cells. This is an opportunity to make the tree
3241** shallower by one level.
3242*/
3243static int balance_shallower(MemPage *pPage){
3244 MemPage *pChild; /* The only child page of pPage */
3245 Pgno pgnoChild; /* Page number for pChild */
3246 int rc; /* Return code from subprocedures */
3247 u8 *apCell[(MX_CELL+2)*NB]; /* All cells from pages being balanced */
3248 int szCell[(MX_CELL+2)*NB]; /* Local size of all cells */
3249
3250 assert( pPage->pParent==0 );
3251 assert( pPage->nCell==0 );
3252 if( pPage->leaf ){
3253 /* The table is completely empty */
3254 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
3255 }else{
3256 /* The root page is empty but has one child. Transfer the
3257 ** information from that one child into the root page if it
3258 ** will fit. This reduces the depth of the tree by one.
3259 **
3260 ** If the root page is page 1, it has less space available than
3261 ** its child (due to the 100 byte header that occurs at the beginning
3262 ** of the database fle), so it might not be able to hold all of the
3263 ** information currently contained in the child. If this is the
3264 ** case, then do not do the transfer. Leave page 1 empty except
3265 ** for the right-pointer to the child page. The child page becomes
3266 ** the virtual root of the tree.
3267 */
3268 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
3269 assert( pgnoChild>0 );
3270 assert( pgnoChild<=sqlite3pager_pagecount(pPage->pBt->pPager) );
3271 rc = getPage(pPage->pBt, pgnoChild, &pChild);
3272 if( rc ) return rc;
3273 if( pPage->pgno==1 ){
3274 rc = initPage(pChild, pPage);
3275 if( rc ) return rc;
3276 assert( pChild->nOverflow==0 );
3277 if( pChild->nFree>=100 ){
3278 /* The child information will fit on the root page, so do the
3279 ** copy */
3280 int i;
3281 zeroPage(pPage, pChild->aData[0]);
3282 for(i=0; i<pChild->nCell; i++){
3283 apCell[i] = findCell(pChild,i);
3284 szCell[i] = cellSizePtr(pChild, apCell[i]);
3285 }
3286 assemblePage(pPage, pChild->nCell, apCell, szCell);
3287 freePage(pChild);
3288 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
3289 }else{
3290 /* The child has more information that will fit on the root.
3291 ** The tree is already balanced. Do nothing. */
3292 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
3293 }
3294 }else{
3295 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
3296 pPage->isInit = 0;
3297 pPage->pParent = 0;
3298 rc = initPage(pPage, 0);
3299 assert( rc==SQLITE_OK );
3300 freePage(pChild);
3301 TRACE(("BALANCE: transfer child %d into root %d\n",
3302 pChild->pgno, pPage->pgno));
3303 }
3304 reparentChildPages(pPage);
3305 releasePage(pChild);
3306 }
3307 return SQLITE_OK;
3308}
3309
3310
3311/*
3312** The root page is overfull
3313**
3314** When this happens, Create a new child page and copy the
3315** contents of the root into the child. Then make the root
3316** page an empty page with rightChild pointing to the new
3317** child. Finally, call balance_internal() on the new child
3318** to cause it to split.
3319*/
3320static int balance_deeper(MemPage *pPage){
3321 int rc; /* Return value from subprocedures */
3322 MemPage *pChild; /* Pointer to a new child page */
3323 Pgno pgnoChild; /* Page number of the new child page */
3324 Btree *pBt; /* The BTree */
3325 int usableSize; /* Total usable size of a page */
3326 u8 *data; /* Content of the parent page */
3327 u8 *cdata; /* Content of the child page */
3328 int hdr; /* Offset to page header in parent */
3329 int brk; /* Offset to content of first cell in parent */
3330
3331 assert( pPage->pParent==0 );
3332 assert( pPage->nOverflow>0 );
3333 pBt = pPage->pBt;
3334 rc = allocatePage(pBt, &pChild, &pgnoChild, pPage->pgno);
3335 if( rc ) return rc;
3336 assert( sqlite3pager_iswriteable(pChild->aData) );
3337 usableSize = pBt->usableSize;
3338 data = pPage->aData;
3339 hdr = pPage->hdrOffset;
3340 brk = get2byte(&data[hdr+5]);
3341 cdata = pChild->aData;
3342 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
3343 memcpy(&cdata[brk], &data[brk], usableSize-brk);
3344 rc = initPage(pChild, pPage);
3345 if( rc ) return rc;
3346 memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
3347 pChild->nOverflow = pPage->nOverflow;
3348 if( pChild->nOverflow ){
3349 pChild->nFree = 0;
3350 }
3351 assert( pChild->nCell==pPage->nCell );
3352 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
3353 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
3354 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
3355 rc = balance_nonroot(pChild);
3356 releasePage(pChild);
3357 return rc;
3358}
3359
3360/*
3361** Decide if the page pPage needs to be balanced. If balancing is
3362** required, call the appropriate balancing routine.
3363*/
3364static int balance(MemPage *pPage){
3365 int rc = SQLITE_OK;
3366 if( pPage->pParent==0 ){
3367 if( pPage->nOverflow>0 ){
3368 rc = balance_deeper(pPage);
3369 }
3370 if( pPage->nCell==0 ){
3371 rc = balance_shallower(pPage);
3372 }
3373 }else{
3374 if( pPage->nOverflow>0 || pPage->nFree>pPage->pBt->usableSize*2/3 ){
3375 rc = balance_nonroot(pPage);
3376 }
3377 }
3378 return rc;
3379}
3380
3381/*
drhf74b8d92002-09-01 23:20:45 +00003382** This routine checks all cursors that point to the same table
3383** as pCur points to. If any of those cursors were opened with
3384** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
3385** cursors point to the same table were opened with wrFlag==1
3386** then this routine returns SQLITE_OK.
3387**
3388** In addition to checking for read-locks (where a read-lock
3389** means a cursor opened with wrFlag==0) this routine also moves
3390** all cursors other than pCur so that they are pointing to the
3391** first Cell on root page. This is necessary because an insert
3392** or delete might change the number of cells on a page or delete
3393** a page entirely and we do not want to leave any cursors
3394** pointing to non-existant pages or cells.
3395*/
3396static int checkReadLocks(BtCursor *pCur){
3397 BtCursor *p;
3398 assert( pCur->wrFlag );
3399 for(p=pCur->pShared; p!=pCur; p=p->pShared){
3400 assert( p );
3401 assert( p->pgnoRoot==pCur->pgnoRoot );
drha34b6762004-05-07 13:30:42 +00003402 assert( p->pPage->pgno==sqlite3pager_pagenumber(p->pPage->aData) );
drhf74b8d92002-09-01 23:20:45 +00003403 if( p->wrFlag==0 ) return SQLITE_LOCKED;
drh91025292004-05-03 19:49:32 +00003404 if( p->pPage->pgno!=p->pgnoRoot ){
drhf74b8d92002-09-01 23:20:45 +00003405 moveToRoot(p);
3406 }
3407 }
3408 return SQLITE_OK;
3409}
3410
3411/*
drh3b7511c2001-05-26 13:15:44 +00003412** Insert a new record into the BTree. The key is given by (pKey,nKey)
3413** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00003414** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00003415** is left pointing at a random location.
3416**
3417** For an INTKEY table, only the nKey value of the key is used. pKey is
3418** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00003419*/
drh3aac2dd2004-04-26 14:10:20 +00003420int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00003421 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00003422 const void *pKey, i64 nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00003423 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00003424){
drh3b7511c2001-05-26 13:15:44 +00003425 int rc;
3426 int loc;
drh14acc042001-06-10 19:56:58 +00003427 int szNew;
drh3b7511c2001-05-26 13:15:44 +00003428 MemPage *pPage;
3429 Btree *pBt = pCur->pBt;
drha34b6762004-05-07 13:30:42 +00003430 unsigned char *oldCell;
3431 unsigned char newCell[MX_CELL_SIZE];
drh3b7511c2001-05-26 13:15:44 +00003432
drhc39e0002004-05-07 23:50:57 +00003433 if( pCur->status ){
3434 return pCur->status; /* A rollback destroyed this cursor */
drhecdc7532001-09-23 02:35:53 +00003435 }
danielk1977ee5741e2004-05-31 10:01:34 +00003436 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00003437 /* Must start a transaction before doing an insert */
3438 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003439 }
drhf74b8d92002-09-01 23:20:45 +00003440 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00003441 if( !pCur->wrFlag ){
3442 return SQLITE_PERM; /* Cursor not open for writing */
3443 }
drhf74b8d92002-09-01 23:20:45 +00003444 if( checkReadLocks(pCur) ){
3445 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
3446 }
drh3aac2dd2004-04-26 14:10:20 +00003447 rc = sqlite3BtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00003448 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00003449 pPage = pCur->pPage;
drh4a1c3802004-05-12 15:15:47 +00003450 assert( pPage->intKey || nKey>=0 );
drh8b18dd42004-05-12 19:18:15 +00003451 assert( pPage->leaf || !pPage->leafData );
drh3a4c1412004-05-09 20:40:11 +00003452 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
3453 pCur->pgnoRoot, nKey, nData, pPage->pgno,
3454 loc==0 ? "overwrite" : "new entry"));
drh7aa128d2002-06-21 13:09:16 +00003455 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00003456 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00003457 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003458 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, &szNew);
drh3b7511c2001-05-26 13:15:44 +00003459 if( rc ) return rc;
drh43605152004-05-29 21:46:49 +00003460 assert( szNew==cellSizePtr(pPage, newCell) );
drh3a4c1412004-05-09 20:40:11 +00003461 assert( szNew<=sizeof(newCell) );
drhf328bc82004-05-10 23:29:49 +00003462 if( loc==0 && pCur->isValid ){
drha34b6762004-05-07 13:30:42 +00003463 int szOld;
3464 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00003465 oldCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00003466 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003467 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00003468 }
drh43605152004-05-29 21:46:49 +00003469 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00003470 rc = clearCell(pPage, oldCell);
drh5e2f8b92001-05-28 00:41:15 +00003471 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00003472 dropCell(pPage, pCur->idx, szOld);
drh7c717f72001-06-24 20:39:41 +00003473 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00003474 assert( pPage->leaf );
drh14acc042001-06-10 19:56:58 +00003475 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00003476 pCur->info.nSize = 0;
drh14acc042001-06-10 19:56:58 +00003477 }else{
drh4b70f112004-05-02 21:12:19 +00003478 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00003479 }
drh24cd67e2004-05-10 16:18:47 +00003480 insertCell(pPage, pCur->idx, newCell, szNew, 0);
drh4b70f112004-05-02 21:12:19 +00003481 rc = balance(pPage);
drh23e11ca2004-05-04 17:27:28 +00003482 /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
drh3fc190c2001-09-14 03:24:23 +00003483 /* fflush(stdout); */
drh4b70f112004-05-02 21:12:19 +00003484 moveToRoot(pCur);
drh5e2f8b92001-05-28 00:41:15 +00003485 return rc;
3486}
3487
3488/*
drh4b70f112004-05-02 21:12:19 +00003489** Delete the entry that the cursor is pointing to. The cursor
3490** is left pointing at a random location.
drh3b7511c2001-05-26 13:15:44 +00003491*/
drh3aac2dd2004-04-26 14:10:20 +00003492int sqlite3BtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00003493 MemPage *pPage = pCur->pPage;
drh4b70f112004-05-02 21:12:19 +00003494 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00003495 int rc;
drh8c42ca92001-06-22 19:15:00 +00003496 Pgno pgnoChild;
drh0d316a42002-08-11 20:10:47 +00003497 Btree *pBt = pCur->pBt;
drh8b2f49b2001-06-08 00:21:52 +00003498
drh7aa128d2002-06-21 13:09:16 +00003499 assert( pPage->isInit );
drhc39e0002004-05-07 23:50:57 +00003500 if( pCur->status ){
3501 return pCur->status; /* A rollback destroyed this cursor */
drhecdc7532001-09-23 02:35:53 +00003502 }
danielk1977ee5741e2004-05-31 10:01:34 +00003503 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00003504 /* Must start a transaction before doing a delete */
3505 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003506 }
drhf74b8d92002-09-01 23:20:45 +00003507 assert( !pBt->readOnly );
drhbd03cae2001-06-02 02:40:57 +00003508 if( pCur->idx >= pPage->nCell ){
3509 return SQLITE_ERROR; /* The cursor is not pointing to anything */
3510 }
drhecdc7532001-09-23 02:35:53 +00003511 if( !pCur->wrFlag ){
3512 return SQLITE_PERM; /* Did not open this cursor for writing */
3513 }
drhf74b8d92002-09-01 23:20:45 +00003514 if( checkReadLocks(pCur) ){
3515 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
3516 }
drha34b6762004-05-07 13:30:42 +00003517 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00003518 if( rc ) return rc;
drh43605152004-05-29 21:46:49 +00003519 pCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00003520 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003521 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00003522 }
3523 clearCell(pPage, pCell);
3524 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00003525 /*
drh5e00f6c2001-09-13 13:46:56 +00003526 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00003527 ** do something we will leave a hole on an internal page.
3528 ** We have to fill the hole by moving in a cell from a leaf. The
3529 ** next Cell after the one to be deleted is guaranteed to exist and
3530 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00003531 */
drh14acc042001-06-10 19:56:58 +00003532 BtCursor leafCur;
drh4b70f112004-05-02 21:12:19 +00003533 unsigned char *pNext;
drh14acc042001-06-10 19:56:58 +00003534 int szNext;
drh8c1238a2003-01-02 14:43:55 +00003535 int notUsed;
drh24cd67e2004-05-10 16:18:47 +00003536 unsigned char tempCell[MX_CELL_SIZE];
drh8b18dd42004-05-12 19:18:15 +00003537 assert( !pPage->leafData );
drh14acc042001-06-10 19:56:58 +00003538 getTempCursor(pCur, &leafCur);
drh3aac2dd2004-04-26 14:10:20 +00003539 rc = sqlite3BtreeNext(&leafCur, &notUsed);
drh14acc042001-06-10 19:56:58 +00003540 if( rc!=SQLITE_OK ){
drh8a6ac0a2004-02-14 17:35:07 +00003541 if( rc!=SQLITE_NOMEM ) rc = SQLITE_CORRUPT;
3542 return rc;
drh5e2f8b92001-05-28 00:41:15 +00003543 }
drha34b6762004-05-07 13:30:42 +00003544 rc = sqlite3pager_write(leafCur.pPage->aData);
drh6019e162001-07-02 17:51:45 +00003545 if( rc ) return rc;
drh3a4c1412004-05-09 20:40:11 +00003546 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
3547 pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
drh43605152004-05-29 21:46:49 +00003548 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
3549 pNext = findCell(leafCur.pPage, leafCur.idx);
3550 szNext = cellSizePtr(leafCur.pPage, pNext);
drh24cd67e2004-05-10 16:18:47 +00003551 assert( sizeof(tempCell)>=szNext+4 );
3552 insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell);
drh43605152004-05-29 21:46:49 +00003553 put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
drh4b70f112004-05-02 21:12:19 +00003554 rc = balance(pPage);
drh5e2f8b92001-05-28 00:41:15 +00003555 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00003556 dropCell(leafCur.pPage, leafCur.idx, szNext);
3557 rc = balance(leafCur.pPage);
drh8c42ca92001-06-22 19:15:00 +00003558 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00003559 }else{
drh3a4c1412004-05-09 20:40:11 +00003560 TRACE(("DELETE: table=%d delete from leaf %d\n",
3561 pCur->pgnoRoot, pPage->pgno));
drh43605152004-05-29 21:46:49 +00003562 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
drh4b70f112004-05-02 21:12:19 +00003563 rc = balance(pPage);
drh5e2f8b92001-05-28 00:41:15 +00003564 }
drh4b70f112004-05-02 21:12:19 +00003565 moveToRoot(pCur);
drh5e2f8b92001-05-28 00:41:15 +00003566 return rc;
drh3b7511c2001-05-26 13:15:44 +00003567}
drh8b2f49b2001-06-08 00:21:52 +00003568
3569/*
drhc6b52df2002-01-04 03:09:29 +00003570** Create a new BTree table. Write into *piTable the page
3571** number for the root page of the new table.
3572**
drhab01f612004-05-22 02:55:23 +00003573** The type of type is determined by the flags parameter. Only the
3574** following values of flags are currently in use. Other values for
3575** flags might not work:
3576**
3577** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
3578** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00003579*/
drh3aac2dd2004-04-26 14:10:20 +00003580int sqlite3BtreeCreateTable(Btree *pBt, int *piTable, int flags){
drh8b2f49b2001-06-08 00:21:52 +00003581 MemPage *pRoot;
3582 Pgno pgnoRoot;
3583 int rc;
danielk1977ee5741e2004-05-31 10:01:34 +00003584 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00003585 /* Must start a transaction first */
3586 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003587 }
drh5df72a52002-06-06 23:16:05 +00003588 if( pBt->readOnly ){
3589 return SQLITE_READONLY;
3590 }
drhda200cc2004-05-09 11:51:38 +00003591 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1);
drh8b2f49b2001-06-08 00:21:52 +00003592 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003593 assert( sqlite3pager_iswriteable(pRoot->aData) );
drhde647132004-05-07 17:57:49 +00003594 zeroPage(pRoot, flags | PTF_LEAF);
drha34b6762004-05-07 13:30:42 +00003595 sqlite3pager_unref(pRoot->aData);
drh8b2f49b2001-06-08 00:21:52 +00003596 *piTable = (int)pgnoRoot;
3597 return SQLITE_OK;
3598}
3599
3600/*
3601** Erase the given database page and all its children. Return
3602** the page to the freelist.
3603*/
drh4b70f112004-05-02 21:12:19 +00003604static int clearDatabasePage(
3605 Btree *pBt, /* The BTree that contains the table */
3606 Pgno pgno, /* Page number to clear */
3607 MemPage *pParent, /* Parent page. NULL for the root */
3608 int freePageFlag /* Deallocate page if true */
3609){
drh8b2f49b2001-06-08 00:21:52 +00003610 MemPage *pPage;
3611 int rc;
drh4b70f112004-05-02 21:12:19 +00003612 unsigned char *pCell;
3613 int i;
drh8b2f49b2001-06-08 00:21:52 +00003614
drhde647132004-05-07 17:57:49 +00003615 rc = getAndInitPage(pBt, pgno, &pPage, pParent);
drh8b2f49b2001-06-08 00:21:52 +00003616 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003617 rc = sqlite3pager_write(pPage->aData);
drh6019e162001-07-02 17:51:45 +00003618 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00003619 for(i=0; i<pPage->nCell; i++){
drh43605152004-05-29 21:46:49 +00003620 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00003621 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003622 rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
drh8b2f49b2001-06-08 00:21:52 +00003623 if( rc ) return rc;
3624 }
drh4b70f112004-05-02 21:12:19 +00003625 rc = clearCell(pPage, pCell);
drh8b2f49b2001-06-08 00:21:52 +00003626 if( rc ) return rc;
3627 }
drha34b6762004-05-07 13:30:42 +00003628 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003629 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
drh2aa679f2001-06-25 02:11:07 +00003630 if( rc ) return rc;
3631 }
3632 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00003633 rc = freePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00003634 }else{
drh3a4c1412004-05-09 20:40:11 +00003635 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00003636 }
drh4b70f112004-05-02 21:12:19 +00003637 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00003638 return rc;
drh8b2f49b2001-06-08 00:21:52 +00003639}
3640
3641/*
drhab01f612004-05-22 02:55:23 +00003642** Delete all information from a single table in the database. iTable is
3643** the page number of the root of the table. After this routine returns,
3644** the root page is empty, but still exists.
3645**
3646** This routine will fail with SQLITE_LOCKED if there are any open
3647** read cursors on the table. Open write cursors are moved to the
3648** root of the table.
drh8b2f49b2001-06-08 00:21:52 +00003649*/
drh3aac2dd2004-04-26 14:10:20 +00003650int sqlite3BtreeClearTable(Btree *pBt, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00003651 int rc;
drhf74b8d92002-09-01 23:20:45 +00003652 BtCursor *pCur;
danielk1977ee5741e2004-05-31 10:01:34 +00003653 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00003654 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003655 }
drhf74b8d92002-09-01 23:20:45 +00003656 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3657 if( pCur->pgnoRoot==(Pgno)iTable ){
3658 if( pCur->wrFlag==0 ) return SQLITE_LOCKED;
3659 moveToRoot(pCur);
3660 }
drhecdc7532001-09-23 02:35:53 +00003661 }
drha34b6762004-05-07 13:30:42 +00003662 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
drh8b2f49b2001-06-08 00:21:52 +00003663 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00003664 sqlite3BtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00003665 }
drh8c42ca92001-06-22 19:15:00 +00003666 return rc;
drh8b2f49b2001-06-08 00:21:52 +00003667}
3668
3669/*
3670** Erase all information in a table and add the root of the table to
3671** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00003672** page 1) is never added to the freelist.
3673**
3674** This routine will fail with SQLITE_LOCKED if there are any open
3675** cursors on the table.
drh8b2f49b2001-06-08 00:21:52 +00003676*/
drh3aac2dd2004-04-26 14:10:20 +00003677int sqlite3BtreeDropTable(Btree *pBt, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00003678 int rc;
3679 MemPage *pPage;
drhf74b8d92002-09-01 23:20:45 +00003680 BtCursor *pCur;
danielk1977ee5741e2004-05-31 10:01:34 +00003681 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00003682 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003683 }
drhf74b8d92002-09-01 23:20:45 +00003684 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3685 if( pCur->pgnoRoot==(Pgno)iTable ){
3686 return SQLITE_LOCKED; /* Cannot drop a table that has a cursor */
3687 }
drh5df72a52002-06-06 23:16:05 +00003688 }
drha34b6762004-05-07 13:30:42 +00003689 rc = getPage(pBt, (Pgno)iTable, &pPage);
drh2aa679f2001-06-25 02:11:07 +00003690 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003691 rc = sqlite3BtreeClearTable(pBt, iTable);
drh2aa679f2001-06-25 02:11:07 +00003692 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00003693 if( iTable>1 ){
drha34b6762004-05-07 13:30:42 +00003694 rc = freePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00003695 }else{
drha34b6762004-05-07 13:30:42 +00003696 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
drh8b2f49b2001-06-08 00:21:52 +00003697 }
drh4b70f112004-05-02 21:12:19 +00003698 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00003699 return rc;
3700}
3701
drh001bbcb2003-03-19 03:14:00 +00003702
drh8b2f49b2001-06-08 00:21:52 +00003703/*
drh23e11ca2004-05-04 17:27:28 +00003704** Read the meta-information out of a database file. Meta[0]
3705** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00003706** through meta[15] are available for use by higher layers. Meta[0]
3707** is read-only, the others are read/write.
3708**
3709** The schema layer numbers meta values differently. At the schema
3710** layer (and the SetCookie and ReadCookie opcodes) the number of
3711** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00003712*/
drh3aac2dd2004-04-26 14:10:20 +00003713int sqlite3BtreeGetMeta(Btree *pBt, int idx, u32 *pMeta){
drh8b2f49b2001-06-08 00:21:52 +00003714 int rc;
drh4b70f112004-05-02 21:12:19 +00003715 unsigned char *pP1;
drh8b2f49b2001-06-08 00:21:52 +00003716
drh23e11ca2004-05-04 17:27:28 +00003717 assert( idx>=0 && idx<=15 );
drha34b6762004-05-07 13:30:42 +00003718 rc = sqlite3pager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00003719 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00003720 *pMeta = get4byte(&pP1[36 + idx*4]);
drha34b6762004-05-07 13:30:42 +00003721 sqlite3pager_unref(pP1);
drh8b2f49b2001-06-08 00:21:52 +00003722 return SQLITE_OK;
3723}
3724
3725/*
drh23e11ca2004-05-04 17:27:28 +00003726** Write meta-information back into the database. Meta[0] is
3727** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00003728*/
drh3aac2dd2004-04-26 14:10:20 +00003729int sqlite3BtreeUpdateMeta(Btree *pBt, int idx, u32 iMeta){
drh4b70f112004-05-02 21:12:19 +00003730 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00003731 int rc;
drh23e11ca2004-05-04 17:27:28 +00003732 assert( idx>=1 && idx<=15 );
danielk1977ee5741e2004-05-31 10:01:34 +00003733 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00003734 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +00003735 }
drhde647132004-05-07 17:57:49 +00003736 assert( pBt->pPage1!=0 );
3737 pP1 = pBt->pPage1->aData;
drha34b6762004-05-07 13:30:42 +00003738 rc = sqlite3pager_write(pP1);
drh4b70f112004-05-02 21:12:19 +00003739 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00003740 put4byte(&pP1[36 + idx*4], iMeta);
drh8b2f49b2001-06-08 00:21:52 +00003741 return SQLITE_OK;
3742}
drh8c42ca92001-06-22 19:15:00 +00003743
drhf328bc82004-05-10 23:29:49 +00003744/*
3745** Return the flag byte at the beginning of the page that the cursor
3746** is currently pointing to.
3747*/
3748int sqlite3BtreeFlags(BtCursor *pCur){
3749 MemPage *pPage = pCur->pPage;
3750 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
3751}
3752
drh8c42ca92001-06-22 19:15:00 +00003753/*
3754** Print a disassembly of the given page on standard output. This routine
3755** is used for debugging and testing only.
3756*/
drhaaab5722002-02-19 13:39:21 +00003757#ifdef SQLITE_TEST
drh23e11ca2004-05-04 17:27:28 +00003758int sqlite3BtreePageDump(Btree *pBt, int pgno, int recursive){
drh8c42ca92001-06-22 19:15:00 +00003759 int rc;
3760 MemPage *pPage;
drhc8629a12004-05-08 20:07:40 +00003761 int i, j, c;
drh8c42ca92001-06-22 19:15:00 +00003762 int nFree;
3763 u16 idx;
drhab9f7f12004-05-08 10:56:11 +00003764 int hdr;
drh43605152004-05-29 21:46:49 +00003765 int nCell;
drha2fce642004-06-05 00:01:44 +00003766 int isInit;
drhab9f7f12004-05-08 10:56:11 +00003767 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00003768 char range[20];
3769 unsigned char payload[20];
drhab9f7f12004-05-08 10:56:11 +00003770
drh4b70f112004-05-02 21:12:19 +00003771 rc = getPage(pBt, (Pgno)pgno, &pPage);
drha2fce642004-06-05 00:01:44 +00003772 isInit = pPage->isInit;
3773 if( pPage->isInit==0 ){
3774 initPage(pPage, 0);
3775 }
drh8c42ca92001-06-22 19:15:00 +00003776 if( rc ){
3777 return rc;
3778 }
drhab9f7f12004-05-08 10:56:11 +00003779 hdr = pPage->hdrOffset;
3780 data = pPage->aData;
drhc8629a12004-05-08 20:07:40 +00003781 c = data[hdr];
drh8b18dd42004-05-12 19:18:15 +00003782 pPage->intKey = (c & (PTF_INTKEY|PTF_LEAFDATA))!=0;
drhc8629a12004-05-08 20:07:40 +00003783 pPage->zeroData = (c & PTF_ZERODATA)!=0;
drh8b18dd42004-05-12 19:18:15 +00003784 pPage->leafData = (c & PTF_LEAFDATA)!=0;
drhc8629a12004-05-08 20:07:40 +00003785 pPage->leaf = (c & PTF_LEAF)!=0;
drh8b18dd42004-05-12 19:18:15 +00003786 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
drh43605152004-05-29 21:46:49 +00003787 nCell = get2byte(&data[hdr+3]);
drhda200cc2004-05-09 11:51:38 +00003788 printf("PAGE %d: flags=0x%02x frag=%d parent=%d\n", pgno,
drh43605152004-05-29 21:46:49 +00003789 data[hdr], data[hdr+7],
drhda200cc2004-05-09 11:51:38 +00003790 (pPage->isInit && pPage->pParent) ? pPage->pParent->pgno : 0);
drhab9f7f12004-05-08 10:56:11 +00003791 assert( hdr == (pgno==1 ? 100 : 0) );
drh43605152004-05-29 21:46:49 +00003792 idx = hdr + 12 - pPage->leaf*4;
3793 for(i=0; i<nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00003794 CellInfo info;
drh4b70f112004-05-02 21:12:19 +00003795 Pgno child;
drh43605152004-05-29 21:46:49 +00003796 unsigned char *pCell;
drh6f11bef2004-05-13 01:12:56 +00003797 int sz;
drh43605152004-05-29 21:46:49 +00003798 int addr;
drh6f11bef2004-05-13 01:12:56 +00003799
drh43605152004-05-29 21:46:49 +00003800 addr = get2byte(&data[idx + 2*i]);
3801 pCell = &data[addr];
3802 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003803 sz = info.nSize;
drh43605152004-05-29 21:46:49 +00003804 sprintf(range,"%d..%d", addr, addr+sz-1);
drh4b70f112004-05-02 21:12:19 +00003805 if( pPage->leaf ){
3806 child = 0;
3807 }else{
drh43605152004-05-29 21:46:49 +00003808 child = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00003809 }
drh6f11bef2004-05-13 01:12:56 +00003810 sz = info.nData;
3811 if( !pPage->intKey ) sz += info.nKey;
drh8c42ca92001-06-22 19:15:00 +00003812 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
drh6f11bef2004-05-13 01:12:56 +00003813 memcpy(payload, &pCell[info.nHeader], sz);
drh8c42ca92001-06-22 19:15:00 +00003814 for(j=0; j<sz; j++){
3815 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
3816 }
3817 payload[sz] = 0;
3818 printf(
drh6f11bef2004-05-13 01:12:56 +00003819 "cell %2d: i=%-10s chld=%-4d nk=%-4lld nd=%-4d payload=%s\n",
3820 i, range, child, info.nKey, info.nData, payload
drh8c42ca92001-06-22 19:15:00 +00003821 );
drh8c42ca92001-06-22 19:15:00 +00003822 }
drh4b70f112004-05-02 21:12:19 +00003823 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003824 printf("right_child: %d\n", get4byte(&data[hdr+8]));
drh4b70f112004-05-02 21:12:19 +00003825 }
drh8c42ca92001-06-22 19:15:00 +00003826 nFree = 0;
3827 i = 0;
drhab9f7f12004-05-08 10:56:11 +00003828 idx = get2byte(&data[hdr+1]);
drhb6f41482004-05-14 01:58:11 +00003829 while( idx>0 && idx<pPage->pBt->usableSize ){
drhab9f7f12004-05-08 10:56:11 +00003830 int sz = get2byte(&data[idx+2]);
drh4b70f112004-05-02 21:12:19 +00003831 sprintf(range,"%d..%d", idx, idx+sz-1);
3832 nFree += sz;
drh8c42ca92001-06-22 19:15:00 +00003833 printf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
drh4b70f112004-05-02 21:12:19 +00003834 i, range, sz, nFree);
drhab9f7f12004-05-08 10:56:11 +00003835 idx = get2byte(&data[idx]);
drh2aa679f2001-06-25 02:11:07 +00003836 i++;
drh8c42ca92001-06-22 19:15:00 +00003837 }
3838 if( idx!=0 ){
3839 printf("ERROR: next freeblock index out of range: %d\n", idx);
3840 }
drha34b6762004-05-07 13:30:42 +00003841 if( recursive && !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003842 for(i=0; i<nCell; i++){
3843 unsigned char *pCell = findCell(pPage, i);
3844 sqlite3BtreePageDump(pBt, get4byte(pCell), 1);
drha34b6762004-05-07 13:30:42 +00003845 idx = get2byte(pCell);
drh6019e162001-07-02 17:51:45 +00003846 }
drh43605152004-05-29 21:46:49 +00003847 sqlite3BtreePageDump(pBt, get4byte(&data[hdr+8]), 1);
drh6019e162001-07-02 17:51:45 +00003848 }
drha2fce642004-06-05 00:01:44 +00003849 pPage->isInit = isInit;
drhab9f7f12004-05-08 10:56:11 +00003850 sqlite3pager_unref(data);
drh3644f082004-05-10 18:45:09 +00003851 fflush(stdout);
drh8c42ca92001-06-22 19:15:00 +00003852 return SQLITE_OK;
3853}
drhaaab5722002-02-19 13:39:21 +00003854#endif
drh8c42ca92001-06-22 19:15:00 +00003855
drhaaab5722002-02-19 13:39:21 +00003856#ifdef SQLITE_TEST
drh8c42ca92001-06-22 19:15:00 +00003857/*
drh2aa679f2001-06-25 02:11:07 +00003858** Fill aResult[] with information about the entry and page that the
3859** cursor is pointing to.
3860**
3861** aResult[0] = The page number
3862** aResult[1] = The entry number
3863** aResult[2] = Total number of entries on this page
3864** aResult[3] = Size of this entry
3865** aResult[4] = Number of free bytes on this page
3866** aResult[5] = Number of free blocks on the page
3867** aResult[6] = Page number of the left child of this entry
3868** aResult[7] = Page number of the right child for the whole page
drh5eddca62001-06-30 21:53:53 +00003869**
3870** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00003871*/
drhda200cc2004-05-09 11:51:38 +00003872int sqlite3BtreeCursorInfo(BtCursor *pCur, int *aResult){
drh2aa679f2001-06-25 02:11:07 +00003873 int cnt, idx;
3874 MemPage *pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00003875
3876 pageIntegrity(pPage);
drh4b70f112004-05-02 21:12:19 +00003877 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00003878 aResult[0] = sqlite3pager_pagenumber(pPage->aData);
drh91025292004-05-03 19:49:32 +00003879 assert( aResult[0]==pPage->pgno );
drh8c42ca92001-06-22 19:15:00 +00003880 aResult[1] = pCur->idx;
drh2aa679f2001-06-25 02:11:07 +00003881 aResult[2] = pPage->nCell;
3882 if( pCur->idx>=0 && pCur->idx<pPage->nCell ){
drh43605152004-05-29 21:46:49 +00003883 u8 *pCell = findCell(pPage, pCur->idx);
3884 aResult[3] = cellSizePtr(pPage, pCell);
3885 aResult[6] = pPage->leaf ? 0 : get4byte(pCell);
drh2aa679f2001-06-25 02:11:07 +00003886 }else{
3887 aResult[3] = 0;
3888 aResult[6] = 0;
3889 }
3890 aResult[4] = pPage->nFree;
3891 cnt = 0;
drh4b70f112004-05-02 21:12:19 +00003892 idx = get2byte(&pPage->aData[pPage->hdrOffset+1]);
drhb6f41482004-05-14 01:58:11 +00003893 while( idx>0 && idx<pPage->pBt->usableSize ){
drh2aa679f2001-06-25 02:11:07 +00003894 cnt++;
drh4b70f112004-05-02 21:12:19 +00003895 idx = get2byte(&pPage->aData[idx]);
drh2aa679f2001-06-25 02:11:07 +00003896 }
3897 aResult[5] = cnt;
drh43605152004-05-29 21:46:49 +00003898 aResult[7] = pPage->leaf ? 0 : get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh8c42ca92001-06-22 19:15:00 +00003899 return SQLITE_OK;
3900}
drhaaab5722002-02-19 13:39:21 +00003901#endif
drhdd793422001-06-28 01:54:48 +00003902
drhdd793422001-06-28 01:54:48 +00003903/*
drh5eddca62001-06-30 21:53:53 +00003904** Return the pager associated with a BTree. This routine is used for
3905** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00003906*/
drh3aac2dd2004-04-26 14:10:20 +00003907Pager *sqlite3BtreePager(Btree *pBt){
drhdd793422001-06-28 01:54:48 +00003908 return pBt->pPager;
3909}
drh5eddca62001-06-30 21:53:53 +00003910
3911/*
3912** This structure is passed around through all the sanity checking routines
3913** in order to keep track of some global state information.
3914*/
drhaaab5722002-02-19 13:39:21 +00003915typedef struct IntegrityCk IntegrityCk;
3916struct IntegrityCk {
drh100569d2001-10-02 13:01:48 +00003917 Btree *pBt; /* The tree being checked out */
3918 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
3919 int nPage; /* Number of pages in the database */
3920 int *anRef; /* Number of times each page is referenced */
drh100569d2001-10-02 13:01:48 +00003921 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00003922};
3923
3924/*
3925** Append a message to the error message string.
3926*/
drhaaab5722002-02-19 13:39:21 +00003927static void checkAppendMsg(IntegrityCk *pCheck, char *zMsg1, char *zMsg2){
drh5eddca62001-06-30 21:53:53 +00003928 if( pCheck->zErrMsg ){
3929 char *zOld = pCheck->zErrMsg;
3930 pCheck->zErrMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00003931 sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00003932 sqliteFree(zOld);
3933 }else{
danielk19774adee202004-05-08 08:23:19 +00003934 sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00003935 }
3936}
3937
3938/*
3939** Add 1 to the reference count for page iPage. If this is the second
3940** reference to the page, add an error message to pCheck->zErrMsg.
3941** Return 1 if there are 2 ore more references to the page and 0 if
3942** if this is the first reference to the page.
3943**
3944** Also check that the page number is in bounds.
3945*/
drhaaab5722002-02-19 13:39:21 +00003946static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00003947 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00003948 if( iPage>pCheck->nPage || iPage<0 ){
drh5eddca62001-06-30 21:53:53 +00003949 char zBuf[100];
3950 sprintf(zBuf, "invalid page number %d", iPage);
3951 checkAppendMsg(pCheck, zContext, zBuf);
3952 return 1;
3953 }
3954 if( pCheck->anRef[iPage]==1 ){
3955 char zBuf[100];
3956 sprintf(zBuf, "2nd reference to page %d", iPage);
3957 checkAppendMsg(pCheck, zContext, zBuf);
3958 return 1;
3959 }
3960 return (pCheck->anRef[iPage]++)>1;
3961}
3962
3963/*
3964** Check the integrity of the freelist or of an overflow page list.
3965** Verify that the number of pages on the list is N.
3966*/
drh30e58752002-03-02 20:41:57 +00003967static void checkList(
3968 IntegrityCk *pCheck, /* Integrity checking context */
3969 int isFreeList, /* True for a freelist. False for overflow page list */
3970 int iPage, /* Page number for first page in the list */
3971 int N, /* Expected number of pages in the list */
3972 char *zContext /* Context for error messages */
3973){
3974 int i;
drh3a4c1412004-05-09 20:40:11 +00003975 int expected = N;
3976 int iFirst = iPage;
drh5eddca62001-06-30 21:53:53 +00003977 char zMsg[100];
drh30e58752002-03-02 20:41:57 +00003978 while( N-- > 0 ){
drh4b70f112004-05-02 21:12:19 +00003979 unsigned char *pOvfl;
drh5eddca62001-06-30 21:53:53 +00003980 if( iPage<1 ){
drh3a4c1412004-05-09 20:40:11 +00003981 sprintf(zMsg, "%d of %d pages missing from overflow list starting at %d",
3982 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00003983 checkAppendMsg(pCheck, zContext, zMsg);
3984 break;
3985 }
3986 if( checkRef(pCheck, iPage, zContext) ) break;
drha34b6762004-05-07 13:30:42 +00003987 if( sqlite3pager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
drh5eddca62001-06-30 21:53:53 +00003988 sprintf(zMsg, "failed to get page %d", iPage);
3989 checkAppendMsg(pCheck, zContext, zMsg);
3990 break;
3991 }
drh30e58752002-03-02 20:41:57 +00003992 if( isFreeList ){
drh4b70f112004-05-02 21:12:19 +00003993 int n = get4byte(&pOvfl[4]);
drh0d316a42002-08-11 20:10:47 +00003994 for(i=0; i<n; i++){
drh4b70f112004-05-02 21:12:19 +00003995 checkRef(pCheck, get4byte(&pOvfl[8+i*4]), zContext);
drh30e58752002-03-02 20:41:57 +00003996 }
drh0d316a42002-08-11 20:10:47 +00003997 N -= n;
drh30e58752002-03-02 20:41:57 +00003998 }
drh4b70f112004-05-02 21:12:19 +00003999 iPage = get4byte(pOvfl);
drha34b6762004-05-07 13:30:42 +00004000 sqlite3pager_unref(pOvfl);
drh5eddca62001-06-30 21:53:53 +00004001 }
4002}
4003
4004/*
4005** Do various sanity checks on a single page of a tree. Return
4006** the tree depth. Root pages return 0. Parents of root pages
4007** return 1, and so forth.
4008**
4009** These checks are done:
4010**
4011** 1. Make sure that cells and freeblocks do not overlap
4012** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00004013** NO 2. Make sure cell keys are in order.
4014** NO 3. Make sure no key is less than or equal to zLowerBound.
4015** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00004016** 5. Check the integrity of overflow pages.
4017** 6. Recursively call checkTreePage on all children.
4018** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00004019** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00004020** the root of the tree.
4021*/
4022static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00004023 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00004024 int iPage, /* Page number of the page to check */
4025 MemPage *pParent, /* Parent page */
4026 char *zParentContext, /* Parent context */
4027 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00004028 int nLower, /* Number of characters in zLowerBound */
4029 char *zUpperBound, /* All keys should be less than this, if not NULL */
4030 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00004031){
4032 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00004033 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00004034 int hdr, cellStart;
4035 int nCell;
drhda200cc2004-05-09 11:51:38 +00004036 u8 *data;
drh5eddca62001-06-30 21:53:53 +00004037 BtCursor cur;
drh0d316a42002-08-11 20:10:47 +00004038 Btree *pBt;
drhb6f41482004-05-14 01:58:11 +00004039 int maxLocal, usableSize;
drh5eddca62001-06-30 21:53:53 +00004040 char zMsg[100];
4041 char zContext[100];
drhda200cc2004-05-09 11:51:38 +00004042 char hit[MX_PAGE_SIZE];
drh5eddca62001-06-30 21:53:53 +00004043
4044 /* Check that the page exists
4045 */
drh0d316a42002-08-11 20:10:47 +00004046 cur.pBt = pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00004047 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00004048 if( iPage==0 ) return 0;
4049 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh4b70f112004-05-02 21:12:19 +00004050 if( (rc = getPage(pBt, (Pgno)iPage, &pPage))!=0 ){
drh5eddca62001-06-30 21:53:53 +00004051 sprintf(zMsg, "unable to get the page. error code=%d", rc);
4052 checkAppendMsg(pCheck, zContext, zMsg);
4053 return 0;
4054 }
drh6f11bef2004-05-13 01:12:56 +00004055 maxLocal = pPage->leafData ? pBt->maxLeaf : pBt->maxLocal;
drh4b70f112004-05-02 21:12:19 +00004056 if( (rc = initPage(pPage, pParent))!=0 ){
drh5eddca62001-06-30 21:53:53 +00004057 sprintf(zMsg, "initPage() returns error code %d", rc);
4058 checkAppendMsg(pCheck, zContext, zMsg);
drh91025292004-05-03 19:49:32 +00004059 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00004060 return 0;
4061 }
4062
4063 /* Check out all the cells.
4064 */
4065 depth = 0;
drh5eddca62001-06-30 21:53:53 +00004066 cur.pPage = pPage;
drh5eddca62001-06-30 21:53:53 +00004067 for(i=0; i<pPage->nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00004068 u8 *pCell;
4069 int sz;
4070 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00004071
4072 /* Check payload overflow pages
4073 */
drh3a4c1412004-05-09 20:40:11 +00004074 sprintf(zContext, "On tree page %d cell %d: ", iPage, i);
drh43605152004-05-29 21:46:49 +00004075 pCell = findCell(pPage,i);
4076 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004077 sz = info.nData;
4078 if( !pPage->intKey ) sz += info.nKey;
4079 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00004080 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +00004081 checkList(pCheck, 0, get4byte(&pCell[info.iOverflow]),nPage,zContext);
drh5eddca62001-06-30 21:53:53 +00004082 }
4083
4084 /* Check sanity of left child page.
4085 */
drhda200cc2004-05-09 11:51:38 +00004086 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004087 pgno = get4byte(pCell);
drhda200cc2004-05-09 11:51:38 +00004088 d2 = checkTreePage(pCheck,pgno,pPage,zContext,0,0,0,0);
4089 if( i>0 && d2!=depth ){
4090 checkAppendMsg(pCheck, zContext, "Child page depth differs");
4091 }
4092 depth = d2;
drh5eddca62001-06-30 21:53:53 +00004093 }
drh5eddca62001-06-30 21:53:53 +00004094 }
drhda200cc2004-05-09 11:51:38 +00004095 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004096 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drhda200cc2004-05-09 11:51:38 +00004097 sprintf(zContext, "On page %d at right child: ", iPage);
4098 checkTreePage(pCheck, pgno, pPage, zContext,0,0,0,0);
4099 }
drh5eddca62001-06-30 21:53:53 +00004100
4101 /* Check for complete coverage of the page
4102 */
drhda200cc2004-05-09 11:51:38 +00004103 data = pPage->aData;
4104 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00004105 memset(hit, 0, usableSize);
4106 memset(hit, 1, get2byte(&data[hdr+5]));
4107 nCell = get2byte(&data[hdr+3]);
4108 cellStart = hdr + 12 - 4*pPage->leaf;
4109 for(i=0; i<nCell; i++){
4110 int pc = get2byte(&data[cellStart+i*2]);
4111 int size = cellSizePtr(pPage, &data[pc]);
drh5eddca62001-06-30 21:53:53 +00004112 int j;
drh43605152004-05-29 21:46:49 +00004113 for(j=pc+size-1; j>=pc; j--) hit[j]++;
drh5eddca62001-06-30 21:53:53 +00004114 }
drhb6f41482004-05-14 01:58:11 +00004115 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000; cnt++){
drhda200cc2004-05-09 11:51:38 +00004116 int size = get2byte(&data[i+2]);
drh5eddca62001-06-30 21:53:53 +00004117 int j;
drhda200cc2004-05-09 11:51:38 +00004118 for(j=i+size-1; j>=i; j--) hit[j]++;
4119 i = get2byte(&data[i]);
drh5eddca62001-06-30 21:53:53 +00004120 }
drhb6f41482004-05-14 01:58:11 +00004121 for(i=cnt=0; i<usableSize; i++){
drh5eddca62001-06-30 21:53:53 +00004122 if( hit[i]==0 ){
drhda200cc2004-05-09 11:51:38 +00004123 cnt++;
drh5eddca62001-06-30 21:53:53 +00004124 }else if( hit[i]>1 ){
4125 sprintf(zMsg, "Multiple uses for byte %d of page %d", i, iPage);
4126 checkAppendMsg(pCheck, zMsg, 0);
4127 break;
4128 }
4129 }
drh43605152004-05-29 21:46:49 +00004130 if( cnt!=data[hdr+7] ){
drhda200cc2004-05-09 11:51:38 +00004131 sprintf(zMsg, "Fragmented space is %d byte reported as %d on page %d",
drh43605152004-05-29 21:46:49 +00004132 cnt, data[hdr+7], iPage);
drhda200cc2004-05-09 11:51:38 +00004133 checkAppendMsg(pCheck, zMsg, 0);
4134 }
drh6019e162001-07-02 17:51:45 +00004135
drh4b70f112004-05-02 21:12:19 +00004136 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00004137 return depth+1;
drh5eddca62001-06-30 21:53:53 +00004138}
4139
4140/*
4141** This routine does a complete check of the given BTree file. aRoot[] is
4142** an array of pages numbers were each page number is the root page of
4143** a table. nRoot is the number of entries in aRoot.
4144**
4145** If everything checks out, this routine returns NULL. If something is
4146** amiss, an error message is written into memory obtained from malloc()
4147** and a pointer to that error message is returned. The calling function
4148** is responsible for freeing the error message when it is done.
4149*/
drh3aac2dd2004-04-26 14:10:20 +00004150char *sqlite3BtreeIntegrityCheck(Btree *pBt, int *aRoot, int nRoot){
drh5eddca62001-06-30 21:53:53 +00004151 int i;
4152 int nRef;
drhaaab5722002-02-19 13:39:21 +00004153 IntegrityCk sCheck;
drh5eddca62001-06-30 21:53:53 +00004154
drha34b6762004-05-07 13:30:42 +00004155 nRef = *sqlite3pager_stats(pBt->pPager);
drhefc251d2001-07-01 22:12:01 +00004156 if( lockBtree(pBt)!=SQLITE_OK ){
4157 return sqliteStrDup("Unable to acquire a read lock on the database");
4158 }
drh5eddca62001-06-30 21:53:53 +00004159 sCheck.pBt = pBt;
4160 sCheck.pPager = pBt->pPager;
drha34b6762004-05-07 13:30:42 +00004161 sCheck.nPage = sqlite3pager_pagecount(sCheck.pPager);
drh0de8c112002-07-06 16:32:14 +00004162 if( sCheck.nPage==0 ){
4163 unlockBtreeIfUnused(pBt);
4164 return 0;
4165 }
drh8c1238a2003-01-02 14:43:55 +00004166 sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
drhda200cc2004-05-09 11:51:38 +00004167 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh1f595712004-06-15 01:40:29 +00004168 i = PENDING_BYTE/pBt->pageSize + 1;
4169 if( i<=sCheck.nPage ){
4170 sCheck.anRef[i] = 1;
4171 }
drh5eddca62001-06-30 21:53:53 +00004172 sCheck.zErrMsg = 0;
4173
4174 /* Check the integrity of the freelist
4175 */
drha34b6762004-05-07 13:30:42 +00004176 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
4177 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00004178
4179 /* Check all the tables.
4180 */
4181 for(i=0; i<nRoot; i++){
drh4ff6dfa2002-03-03 23:06:00 +00004182 if( aRoot[i]==0 ) continue;
drh1bffb9c2002-02-03 17:37:36 +00004183 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00004184 }
4185
4186 /* Make sure every page in the file is referenced
4187 */
4188 for(i=1; i<=sCheck.nPage; i++){
4189 if( sCheck.anRef[i]==0 ){
4190 char zBuf[100];
4191 sprintf(zBuf, "Page %d is never used", i);
4192 checkAppendMsg(&sCheck, zBuf, 0);
4193 }
4194 }
4195
4196 /* Make sure this analysis did not leave any unref() pages
4197 */
drh5e00f6c2001-09-13 13:46:56 +00004198 unlockBtreeIfUnused(pBt);
drha34b6762004-05-07 13:30:42 +00004199 if( nRef != *sqlite3pager_stats(pBt->pPager) ){
drh5eddca62001-06-30 21:53:53 +00004200 char zBuf[100];
4201 sprintf(zBuf,
4202 "Outstanding page count goes from %d to %d during this analysis",
drha34b6762004-05-07 13:30:42 +00004203 nRef, *sqlite3pager_stats(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00004204 );
4205 checkAppendMsg(&sCheck, zBuf, 0);
4206 }
4207
4208 /* Clean up and report errors.
4209 */
4210 sqliteFree(sCheck.anRef);
4211 return sCheck.zErrMsg;
4212}
paulb95a8862003-04-01 21:16:41 +00004213
drh73509ee2003-04-06 20:44:45 +00004214/*
4215** Return the full pathname of the underlying database file.
4216*/
drh3aac2dd2004-04-26 14:10:20 +00004217const char *sqlite3BtreeGetFilename(Btree *pBt){
drh73509ee2003-04-06 20:44:45 +00004218 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00004219 return sqlite3pager_filename(pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00004220}
4221
4222/*
danielk19775865e3d2004-06-14 06:03:57 +00004223** Return the pathname of the directory that contains the database file.
4224*/
4225const char *sqlite3BtreeGetDirname(Btree *pBt){
4226 assert( pBt->pPager!=0 );
4227 return sqlite3pager_dirname(pBt->pPager);
4228}
4229
4230/*
4231** Return the pathname of the journal file for this database. The return
4232** value of this routine is the same regardless of whether the journal file
4233** has been created or not.
4234*/
4235const char *sqlite3BtreeGetJournalname(Btree *pBt){
4236 assert( pBt->pPager!=0 );
4237 return sqlite3pager_journalname(pBt->pPager);
4238}
4239
4240/*
drhf7c57532003-04-25 13:22:51 +00004241** Copy the complete content of pBtFrom into pBtTo. A transaction
4242** must be active for both files.
4243**
4244** The size of file pBtFrom may be reduced by this operation.
drh43605152004-05-29 21:46:49 +00004245** If anything goes wrong, the transaction on pBtFrom is rolled back.
drh73509ee2003-04-06 20:44:45 +00004246*/
drh3aac2dd2004-04-26 14:10:20 +00004247int sqlite3BtreeCopyFile(Btree *pBtTo, Btree *pBtFrom){
drhf7c57532003-04-25 13:22:51 +00004248 int rc = SQLITE_OK;
drh2e6d11b2003-04-25 15:37:57 +00004249 Pgno i, nPage, nToPage;
drhf7c57532003-04-25 13:22:51 +00004250
danielk1977ee5741e2004-05-31 10:01:34 +00004251 if( pBtTo->inTrans!=TRANS_WRITE || pBtFrom->inTrans!=TRANS_WRITE ){
4252 return SQLITE_ERROR;
4253 }
drhf7c57532003-04-25 13:22:51 +00004254 if( pBtTo->pCursor ) return SQLITE_BUSY;
drh465407d2004-05-20 02:01:26 +00004255 memcpy(pBtTo->pPage1->aData, pBtFrom->pPage1->aData, pBtFrom->usableSize);
4256 rc = sqlite3pager_overwrite(pBtTo->pPager, 1, pBtFrom->pPage1->aData);
drha34b6762004-05-07 13:30:42 +00004257 nToPage = sqlite3pager_pagecount(pBtTo->pPager);
4258 nPage = sqlite3pager_pagecount(pBtFrom->pPager);
drh2e6d11b2003-04-25 15:37:57 +00004259 for(i=2; rc==SQLITE_OK && i<=nPage; i++){
drhf7c57532003-04-25 13:22:51 +00004260 void *pPage;
drha34b6762004-05-07 13:30:42 +00004261 rc = sqlite3pager_get(pBtFrom->pPager, i, &pPage);
drhf7c57532003-04-25 13:22:51 +00004262 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00004263 rc = sqlite3pager_overwrite(pBtTo->pPager, i, pPage);
drh2e6d11b2003-04-25 15:37:57 +00004264 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00004265 sqlite3pager_unref(pPage);
drhf7c57532003-04-25 13:22:51 +00004266 }
drh2e6d11b2003-04-25 15:37:57 +00004267 for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
4268 void *pPage;
drha34b6762004-05-07 13:30:42 +00004269 rc = sqlite3pager_get(pBtTo->pPager, i, &pPage);
drh2e6d11b2003-04-25 15:37:57 +00004270 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00004271 rc = sqlite3pager_write(pPage);
4272 sqlite3pager_unref(pPage);
4273 sqlite3pager_dont_write(pBtTo->pPager, i);
drh2e6d11b2003-04-25 15:37:57 +00004274 }
4275 if( !rc && nPage<nToPage ){
drha34b6762004-05-07 13:30:42 +00004276 rc = sqlite3pager_truncate(pBtTo->pPager, nPage);
drh2e6d11b2003-04-25 15:37:57 +00004277 }
drhf7c57532003-04-25 13:22:51 +00004278 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00004279 sqlite3BtreeRollback(pBtTo);
drhf7c57532003-04-25 13:22:51 +00004280 }
4281 return rc;
drh73509ee2003-04-06 20:44:45 +00004282}
danielk19771d850a72004-05-31 08:26:49 +00004283
4284/*
4285** Return non-zero if a transaction is active.
4286*/
4287int sqlite3BtreeIsInTrans(Btree *pBt){
danielk1977ee5741e2004-05-31 10:01:34 +00004288 return (pBt && (pBt->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00004289}
4290
4291/*
4292** Return non-zero if a statement transaction is active.
4293*/
4294int sqlite3BtreeIsInStmt(Btree *pBt){
4295 return (pBt && pBt->inStmt);
4296}
danielk197713adf8a2004-06-03 16:08:41 +00004297
4298/*
4299** This call is a no-op if no write-transaction is currently active on pBt.
4300**
4301** Otherwise, sync the database file for the btree pBt. zMaster points to
4302** the name of a master journal file that should be written into the
4303** individual journal file, or is NULL, indicating no master journal file
4304** (single database transaction).
4305**
4306** When this is called, the master journal should already have been
4307** created, populated with this journal pointer and synced to disk.
4308**
4309** Once this is routine has returned, the only thing required to commit
4310** the write-transaction for this database file is to delete the journal.
4311*/
4312int sqlite3BtreeSync(Btree *pBt, const char *zMaster){
4313 if( pBt->inTrans==TRANS_WRITE ){
4314 return sqlite3pager_sync(pBt->pPager, zMaster);
4315 }
4316 return SQLITE_OK;
4317}