blob: 07ebaa9d57dc96e3723ac71c84fb872a13a740b8 [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*************************************************************************
danielk197713adf8a2004-06-03 16:08:41 +000012** $Id: btree.c,v 1.156 2004/06/03 16:08:41 danielk1977 Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
15** For a detailed discussion of BTrees, refer to
16**
17** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
18** "Sorting And Searching", pages 473-480. Addison-Wesley
19** Publishing Company, Reading, Massachusetts.
20**
21** The basic idea is that each page of the file contains N database
22** entries and N+1 pointers to subpages.
23**
24** ----------------------------------------------------------------
25** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N) | Ptr(N+1) |
26** ----------------------------------------------------------------
27**
28** All of the keys on the page that Ptr(0) points to have values less
29** than Key(0). All of the keys on page Ptr(1) and its subpages have
30** values greater than Key(0) and less than Key(1). All of the keys
31** on Ptr(N+1) and its subpages have values greater than Key(N). And
32** so forth.
33**
drh5e00f6c2001-09-13 13:46:56 +000034** Finding a particular key requires reading O(log(M)) pages from the
35** disk where M is the number of entries in the tree.
drh8b2f49b2001-06-08 00:21:52 +000036**
37** In this implementation, a single file can hold one or more separate
38** BTrees. Each BTree is identified by the index of its root page. The
drh9e572e62004-04-23 23:43:10 +000039** key and data for any entry are combined to form the "payload". A
40** fixed amount of payload can be carried directly on the database
41** page. If the payload is larger than the preset amount then surplus
42** bytes are stored on overflow pages. The payload for an entry
43** and the preceding pointer are combined to form a "Cell". Each
44** page has a small header which contains the Ptr(N+1) pointer and other
45** information such as the size of key and data.
drh8b2f49b2001-06-08 00:21:52 +000046**
drh9e572e62004-04-23 23:43:10 +000047** FORMAT DETAILS
48**
49** The file is divided into pages. The first page is called page 1,
50** the second is page 2, and so forth. A page number of zero indicates
51** "no such page". The page size can be anything between 512 and 65536.
52** Each page can be either a btree page, a freelist page or an overflow
53** page.
54**
55** The first page is always a btree page. The first 100 bytes of the first
drh271efa52004-05-30 19:19:05 +000056** page contain a special header (the "file header") that describes the file.
57** The format of the file header is as follows:
drh9e572e62004-04-23 23:43:10 +000058**
59** OFFSET SIZE DESCRIPTION
drhde647132004-05-07 17:57:49 +000060** 0 16 Header string: "SQLite format 3\000"
drh9e572e62004-04-23 23:43:10 +000061** 16 2 Page size in bytes.
62** 18 1 File format write version
63** 19 1 File format read version
drh6f11bef2004-05-13 01:12:56 +000064** 20 1 Bytes of unused space at the end of each page
65** 21 1 Max embedded payload fraction
66** 22 1 Min embedded payload fraction
67** 23 1 Min leaf payload fraction
68** 24 4 File change counter
69** 28 4 Reserved for future use
drh9e572e62004-04-23 23:43:10 +000070** 32 4 First freelist page
71** 36 4 Number of freelist pages in the file
72** 40 60 15 4-byte meta values passed to higher layers
73**
74** All of the integer values are big-endian (most significant byte first).
drh6f11bef2004-05-13 01:12:56 +000075**
drhab01f612004-05-22 02:55:23 +000076** The file change counter is incremented when the database is changed more
drh6f11bef2004-05-13 01:12:56 +000077** than once within the same second. This counter, together with the
78** modification time of the file, allows other processes to know
79** when the file has changed and thus when they need to flush their
80** cache.
81**
82** The max embedded payload fraction is the amount of the total usable
83** space in a page that can be consumed by a single cell for standard
84** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
85** is to limit the maximum cell size so that at least 4 cells will fit
drhab01f612004-05-22 02:55:23 +000086** on one page. Thus the default max embedded payload fraction is 64.
drh6f11bef2004-05-13 01:12:56 +000087**
88** If the payload for a cell is larger than the max payload, then extra
89** payload is spilled to overflow pages. Once an overflow page is allocated,
90** as many bytes as possible are moved into the overflow pages without letting
91** the cell size drop below the min embedded payload fraction.
92**
93** The min leaf payload fraction is like the min embedded payload fraction
94** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
95** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
96** not specified in the header.
drh9e572e62004-04-23 23:43:10 +000097**
drh43605152004-05-29 21:46:49 +000098** Each btree pages is divided into three sections: The header, the
99** cell pointer array, and the cell area area. Page 1 also has a 100-byte
drh271efa52004-05-30 19:19:05 +0000100** file header that occurs before the page header.
101**
102** |----------------|
103** | file header | 100 bytes. Page 1 only.
104** |----------------|
105** | page header | 8 bytes for leaves. 12 bytes for interior nodes
106** |----------------|
107** | cell pointer | | 2 bytes per cell. Sorted order.
108** | array | | Grows downward
109** | | v
110** |----------------|
111** | unallocated |
112** | space |
113** |----------------| ^ Grows upwards
114** | cell content | | Arbitrary order interspersed with freeblocks.
115** | area | | and free space fragments.
116** |----------------|
drh43605152004-05-29 21:46:49 +0000117**
118** The page headers looks like this:
drh9e572e62004-04-23 23:43:10 +0000119**
120** OFFSET SIZE DESCRIPTION
drh6f11bef2004-05-13 01:12:56 +0000121** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
drh9e572e62004-04-23 23:43:10 +0000122** 1 2 byte offset to the first freeblock
drh43605152004-05-29 21:46:49 +0000123** 3 2 number of cells on this page
drh271efa52004-05-30 19:19:05 +0000124** 5 2 first byte of the cell content area
drh43605152004-05-29 21:46:49 +0000125** 7 1 number of fragmented free bytes
drh271efa52004-05-30 19:19:05 +0000126** 8 4 Right child (the Ptr(N+1) value). Omitted on leaves.
drh9e572e62004-04-23 23:43:10 +0000127**
128** The flags define the format of this btree page. The leaf flag means that
129** this page has no children. The zerodata flag means that this page carries
130** only keys and no data. The intkey flag means that the key is a single
131** variable length integer at the beginning of the payload.
132**
drh43605152004-05-29 21:46:49 +0000133** The cell pointer array begins on the first byte after the page header.
134** The cell pointer array contains zero or more 2-byte numbers which are
135** offsets from the beginning of the page to the cell content in the cell
136** content area. The cell pointers occur in sorted order. The system strives
137** to keep free space after the last cell pointer so that new cells can
138** be easily added without have to defragment the page.
139**
140** Cell content is stored at the very end of the page and grows toward the
141** beginning of the page.
142**
143** Unused space within the cell content area is collected into a linked list of
144** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
145** to the first freeblock is given in the header. Freeblocks occur in
146** increasing order. Because a freeblock must be at least 4 bytes in size,
147** any group of 3 or fewer unused bytes in the cell content area cannot
148** exist on the freeblock chain. A group of 3 or fewer free bytes is called
149** a fragment. The total number of bytes in all fragments is recorded.
150** in the page header at offset 7.
151**
152** SIZE DESCRIPTION
153** 2 Byte offset of the next freeblock
154** 2 Bytes in this freeblock
155**
156** Cells are of variable length. Cells are stored in the cell content area at
157** the end of the page. Pointers to the cells are in the cell pointer array
158** that immediately follows the page header. Cells is not necessarily
159** contiguous or in order, but cell pointers are contiguous and in order.
160**
161** Cell content makes use of variable length integers. A variable
162** length integer is 1 to 9 bytes where the lower 7 bits of each
drh9e572e62004-04-23 23:43:10 +0000163** byte are used. The integer consists of all bytes that have bit 8 set and
drh6f11bef2004-05-13 01:12:56 +0000164** the first byte with bit 8 clear. The most significant byte of the integer
drhab01f612004-05-22 02:55:23 +0000165** appears first. A variable-length integer may not be more than 9 bytes long.
166** As a special case, all 8 bytes of the 9th byte are used as data. This
167** allows a 64-bit integer to be encoded in 9 bytes.
drh9e572e62004-04-23 23:43:10 +0000168**
169** 0x00 becomes 0x00000000
drh6f11bef2004-05-13 01:12:56 +0000170** 0x7f becomes 0x0000007f
171** 0x81 0x00 becomes 0x00000080
172** 0x82 0x00 becomes 0x00000100
173** 0x80 0x7f becomes 0x0000007f
174** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
drh9e572e62004-04-23 23:43:10 +0000175** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
176**
177** Variable length integers are used for rowids and to hold the number of
178** bytes of key and data in a btree cell.
179**
drh43605152004-05-29 21:46:49 +0000180** The content of a cell looks like this:
drh9e572e62004-04-23 23:43:10 +0000181**
182** SIZE DESCRIPTION
drh3aac2dd2004-04-26 14:10:20 +0000183** 4 Page number of the left child. Omitted if leaf flag is set.
184** var Number of bytes of data. Omitted if the zerodata flag is set.
185** var Number of bytes of key. Or the key itself if intkey flag is set.
drh9e572e62004-04-23 23:43:10 +0000186** * Payload
187** 4 First page of the overflow chain. Omitted if no overflow
188**
189** Overflow pages form a linked list. Each page except the last is completely
190** filled with data (pagesize - 4 bytes). The last page can have as little
191** as 1 byte of data.
192**
193** SIZE DESCRIPTION
194** 4 Page number of next overflow page
195** * Data
196**
197** Freelist pages come in two subtypes: trunk pages and leaf pages. The
198** file header points to first in a linked list of trunk page. Each trunk
199** page points to multiple leaf pages. The content of a leaf page is
200** unspecified. A trunk page looks like this:
201**
202** SIZE DESCRIPTION
203** 4 Page number of next trunk page
204** 4 Number of leaf pointers on this page
205** * zero or more pages numbers of leaves
drha059ad02001-04-17 20:09:11 +0000206*/
207#include "sqliteInt.h"
208#include "pager.h"
209#include "btree.h"
210#include <assert.h>
211
drh4b70f112004-05-02 21:12:19 +0000212
213/* Maximum page size. The upper bound on this value is 65536 (a limit
drh43605152004-05-29 21:46:49 +0000214** imposed by the 2-byte size of cell array pointers.) The
drh4b70f112004-05-02 21:12:19 +0000215** maximum page size determines the amount of stack space allocated
216** by many of the routines in this module. On embedded architectures
217** or any machine where memory and especially stack memory is limited,
218** one may wish to chose a smaller value for the maximum page size.
219*/
220#ifndef MX_PAGE_SIZE
221# define MX_PAGE_SIZE 1024
222#endif
223
drh4b70f112004-05-02 21:12:19 +0000224/* The following value is the maximum cell size assuming a maximum page
225** size give above.
226*/
drh43605152004-05-29 21:46:49 +0000227#define MX_CELL_SIZE (MX_PAGE_SIZE-8)
drh4b70f112004-05-02 21:12:19 +0000228
229/* The maximum number of cells on a single page of the database. This
230** assumes a minimum cell size of 3 bytes. Such small cells will be
231** exceedingly rare, but they are possible.
232*/
drh43605152004-05-29 21:46:49 +0000233#define MX_CELL ((MX_PAGE_SIZE-8)/3)
drh4b70f112004-05-02 21:12:19 +0000234
paulb95a8862003-04-01 21:16:41 +0000235/* Forward declarations */
drh3aac2dd2004-04-26 14:10:20 +0000236typedef struct MemPage MemPage;
paulb95a8862003-04-01 21:16:41 +0000237
drh8c42ca92001-06-22 19:15:00 +0000238/*
drhbd03cae2001-06-02 02:40:57 +0000239** This is a magic string that appears at the beginning of every
drh8c42ca92001-06-22 19:15:00 +0000240** SQLite database in order to identify the file as a real database.
drhde647132004-05-07 17:57:49 +0000241** 123456789 123456 */
242static const char zMagicHeader[] = "SQLite format 3";
drh08ed44e2001-04-29 23:32:55 +0000243
244/*
drh4b70f112004-05-02 21:12:19 +0000245** Page type flags. An ORed combination of these flags appear as the
246** first byte of every BTree page.
drh8c42ca92001-06-22 19:15:00 +0000247*/
drhde647132004-05-07 17:57:49 +0000248#define PTF_INTKEY 0x01
drh9e572e62004-04-23 23:43:10 +0000249#define PTF_ZERODATA 0x02
drh8b18dd42004-05-12 19:18:15 +0000250#define PTF_LEAFDATA 0x04
251#define PTF_LEAF 0x08
drh8c42ca92001-06-22 19:15:00 +0000252
253/*
drh9e572e62004-04-23 23:43:10 +0000254** As each page of the file is loaded into memory, an instance of the following
255** structure is appended and initialized to zero. This structure stores
256** information about the page that is decoded from the raw file page.
drh14acc042001-06-10 19:56:58 +0000257**
drh72f82862001-05-24 21:06:34 +0000258** The pParent field points back to the parent page. This allows us to
259** walk up the BTree from any leaf to the root. Care must be taken to
260** unref() the parent page pointer when this page is no longer referenced.
drhbd03cae2001-06-02 02:40:57 +0000261** The pageDestructor() routine handles that chore.
drh7e3b0a02001-04-28 16:52:40 +0000262*/
263struct MemPage {
drh43605152004-05-29 21:46:49 +0000264 u8 isInit; /* True if previously initialized */
265 u8 idxShift; /* True if Cell indices have changed */
266 u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
267 u8 intKey; /* True if intkey flag is set */
268 u8 leaf; /* True if leaf flag is set */
269 u8 zeroData; /* True if table stores keys only */
270 u8 leafData; /* True if tables stores data on leaves only */
271 u8 hasData; /* True if this page stores data */
272 u8 hdrOffset; /* 100 for page 1. 0 otherwise */
drh271efa52004-05-30 19:19:05 +0000273 u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
274 u8 maxLocal; /* Copy of Btree.maxLocal or Btree.maxLeaf */
275 u8 minLocal; /* Copy of Btree.minLocal or Btree.minLeaf */
drh43605152004-05-29 21:46:49 +0000276 u16 cellOffset; /* Index in aData of first cell pointer */
277 u16 idxParent; /* Index in parent of this node */
278 u16 nFree; /* Number of free bytes on the page */
279 u16 nCell; /* Number of cells on this page, local and ovfl */
280 struct _OvflCell { /* Cells that will not fit on aData[] */
281 u8 *pCell; /* Pointers to the body of the overflow cell */
282 u16 idx; /* Insert this cell before idx-th non-overflow cell */
283 } aOvfl[3];
284 struct Btree *pBt; /* Pointer back to BTree structure */
285 u8 *aData; /* Pointer back to the start of the page */
286 Pgno pgno; /* Page number for this page */
287 MemPage *pParent; /* The parent of this page. NULL for root */
drh8c42ca92001-06-22 19:15:00 +0000288};
drh7e3b0a02001-04-28 16:52:40 +0000289
290/*
drh3b7511c2001-05-26 13:15:44 +0000291** The in-memory image of a disk page has the auxiliary information appended
292** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
293** that extra information.
294*/
drh3aac2dd2004-04-26 14:10:20 +0000295#define EXTRA_SIZE sizeof(MemPage)
drh3b7511c2001-05-26 13:15:44 +0000296
297/*
drha059ad02001-04-17 20:09:11 +0000298** Everything we need to know about an open database
299*/
300struct Btree {
301 Pager *pPager; /* The page cache */
drh306dc212001-05-21 13:45:10 +0000302 BtCursor *pCursor; /* A list of all open cursors */
drh3aac2dd2004-04-26 14:10:20 +0000303 MemPage *pPage1; /* First page of the database */
drh663fc632002-02-02 18:49:19 +0000304 u8 inTrans; /* True if a transaction is in progress */
drhab01f612004-05-22 02:55:23 +0000305 u8 inStmt; /* True if we are in a statement subtransaction */
drh5df72a52002-06-06 23:16:05 +0000306 u8 readOnly; /* True if the underlying file is readonly */
drhab01f612004-05-22 02:55:23 +0000307 u8 maxEmbedFrac; /* Maximum payload as % of total page size */
308 u8 minEmbedFrac; /* Minimum payload as % of total page size */
309 u8 minLeafFrac; /* Minimum leaf payload as % of total page size */
drhb6f41482004-05-14 01:58:11 +0000310 int pageSize; /* Total number of bytes on a page */
311 int usableSize; /* Number of usable bytes on each page */
drh6f11bef2004-05-13 01:12:56 +0000312 int maxLocal; /* Maximum local payload in non-LEAFDATA tables */
313 int minLocal; /* Minimum local payload in non-LEAFDATA tables */
314 int maxLeaf; /* Maximum local payload in a LEAFDATA table */
315 int minLeaf; /* Minimum local payload in a LEAFDATA table */
drha059ad02001-04-17 20:09:11 +0000316};
317typedef Btree Bt;
318
drh365d68f2001-05-11 11:02:46 +0000319/*
danielk1977ee5741e2004-05-31 10:01:34 +0000320** Btree.inTrans may take one of the following values.
321*/
322#define TRANS_NONE 0
323#define TRANS_READ 1
324#define TRANS_WRITE 2
325
326/*
drhfa1a98a2004-05-14 19:08:17 +0000327** An instance of the following structure is used to hold information
drh271efa52004-05-30 19:19:05 +0000328** about a cell. The parseCellPtr() function fills in this structure
drhab01f612004-05-22 02:55:23 +0000329** based on information extract from the raw disk page.
drhfa1a98a2004-05-14 19:08:17 +0000330*/
331typedef struct CellInfo CellInfo;
332struct CellInfo {
drh43605152004-05-29 21:46:49 +0000333 u8 *pCell; /* Pointer to the start of cell content */
drhfa1a98a2004-05-14 19:08:17 +0000334 i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
335 u32 nData; /* Number of bytes of data */
drh271efa52004-05-30 19:19:05 +0000336 u16 nHeader; /* Size of the cell content header in bytes */
drhfa1a98a2004-05-14 19:08:17 +0000337 u16 nLocal; /* Amount of payload held locally */
drhab01f612004-05-22 02:55:23 +0000338 u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
drh271efa52004-05-30 19:19:05 +0000339 u16 nSize; /* Size of the cell content on the main b-tree page */
drhfa1a98a2004-05-14 19:08:17 +0000340};
341
342/*
drh365d68f2001-05-11 11:02:46 +0000343** A cursor is a pointer to a particular entry in the BTree.
344** The entry is identified by its MemPage and the index in
drha34b6762004-05-07 13:30:42 +0000345** MemPage.aCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000346*/
drh72f82862001-05-24 21:06:34 +0000347struct BtCursor {
drh5e2f8b92001-05-28 00:41:15 +0000348 Btree *pBt; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000349 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drhf74b8d92002-09-01 23:20:45 +0000350 BtCursor *pShared; /* Loop of cursors with the same root page */
drh3aac2dd2004-04-26 14:10:20 +0000351 int (*xCompare)(void*,int,const void*,int,const void*); /* Key comp func */
352 void *pArg; /* First arg to xCompare() */
drh8b2f49b2001-06-08 00:21:52 +0000353 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000354 MemPage *pPage; /* Page that contains the entry */
drh3aac2dd2004-04-26 14:10:20 +0000355 int idx; /* Index of the entry in pPage->aCell[] */
drhfa1a98a2004-05-14 19:08:17 +0000356 CellInfo info; /* A parse of the cell we are pointing at */
drhecdc7532001-09-23 02:35:53 +0000357 u8 wrFlag; /* True if writable */
drhc39e0002004-05-07 23:50:57 +0000358 u8 isValid; /* TRUE if points to a valid entry */
359 u8 status; /* Set to SQLITE_ABORT if cursors is invalidated */
drh365d68f2001-05-11 11:02:46 +0000360};
drh7e3b0a02001-04-28 16:52:40 +0000361
drha059ad02001-04-17 20:09:11 +0000362/*
drhab01f612004-05-22 02:55:23 +0000363** Read or write a two- and four-byte big-endian integer values.
drh0d316a42002-08-11 20:10:47 +0000364*/
drh9e572e62004-04-23 23:43:10 +0000365static u32 get2byte(unsigned char *p){
366 return (p[0]<<8) | p[1];
drh0d316a42002-08-11 20:10:47 +0000367}
drh9e572e62004-04-23 23:43:10 +0000368static u32 get4byte(unsigned char *p){
369 return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
370}
drh9e572e62004-04-23 23:43:10 +0000371static void put2byte(unsigned char *p, u32 v){
372 p[0] = v>>8;
373 p[1] = v;
374}
375static void put4byte(unsigned char *p, u32 v){
376 p[0] = v>>24;
377 p[1] = v>>16;
378 p[2] = v>>8;
379 p[3] = v;
380}
drh6f11bef2004-05-13 01:12:56 +0000381
drh9e572e62004-04-23 23:43:10 +0000382/*
drhab01f612004-05-22 02:55:23 +0000383** Routines to read and write variable-length integers. These used to
384** be defined locally, but now we use the varint routines in the util.c
385** file.
drh9e572e62004-04-23 23:43:10 +0000386*/
drh6d2fb152004-05-14 16:50:06 +0000387#define getVarint sqlite3GetVarint
388#define getVarint32 sqlite3GetVarint32
389#define putVarint sqlite3PutVarint
drh0d316a42002-08-11 20:10:47 +0000390
391/*
drh271efa52004-05-30 19:19:05 +0000392** Given a btree page and a cell index (0 means the first cell on
393** the page, 1 means the second cell, and so forth) return a pointer
394** to the cell content.
395**
396** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000397*/
drh43605152004-05-29 21:46:49 +0000398static u8 *findCell(MemPage *pPage, int iCell){
399 u8 *data = pPage->aData;
400 assert( iCell>=0 );
401 assert( iCell<get2byte(&data[pPage->hdrOffset+3]) );
402 return data + get2byte(&data[pPage->cellOffset+2*iCell]);
403}
404
405/*
406** This a more complex version of findCell() that works for
407** pages that do contain overflow cells. See insert
408*/
409static u8 *findOverflowCell(MemPage *pPage, int iCell){
410 int i;
411 for(i=pPage->nOverflow-1; i>=0; i--){
412 if( pPage->aOvfl[i].idx<=iCell ){
413 if( pPage->aOvfl[i].idx==iCell ){
414 return pPage->aOvfl[i].pCell;
415 }
416 iCell--;
417 }
418 }
419 return findCell(pPage, iCell);
420}
421
422/*
423** Parse a cell content block and fill in the CellInfo structure. There
424** are two versions of this function. parseCell() takes a cell index
425** as the second argument and parseCellPtr() takes a pointer to the
426** body of the cell as its second argument.
427*/
428static void parseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000429 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000430 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000431 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000432){
drh271efa52004-05-30 19:19:05 +0000433 int n; /* Number bytes in cell content header */
434 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000435
436 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000437 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000438 n = pPage->childPtrSize;
439 assert( n==4-4*pPage->leaf );
drh8b18dd42004-05-12 19:18:15 +0000440 if( pPage->hasData ){
drh271efa52004-05-30 19:19:05 +0000441 n += getVarint32(&pCell[n], &nPayload);
drh8b18dd42004-05-12 19:18:15 +0000442 }else{
drh271efa52004-05-30 19:19:05 +0000443 nPayload = 0;
drh3aac2dd2004-04-26 14:10:20 +0000444 }
drh6f11bef2004-05-13 01:12:56 +0000445 n += getVarint(&pCell[n], &pInfo->nKey);
446 pInfo->nHeader = n;
drh271efa52004-05-30 19:19:05 +0000447 pInfo->nData = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000448 if( !pPage->intKey ){
449 nPayload += pInfo->nKey;
450 }
drh271efa52004-05-30 19:19:05 +0000451 if( nPayload<=pPage->maxLocal ){
452 /* This is the (easy) common case where the entire payload fits
453 ** on the local page. No overflow is required.
454 */
455 int nSize; /* Total size of cell content in bytes */
drh6f11bef2004-05-13 01:12:56 +0000456 pInfo->nLocal = nPayload;
457 pInfo->iOverflow = 0;
drh271efa52004-05-30 19:19:05 +0000458 nSize = nPayload + n;
459 if( nSize<4 ){
460 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000461 }
drh271efa52004-05-30 19:19:05 +0000462 pInfo->nSize = nSize;
drh6f11bef2004-05-13 01:12:56 +0000463 }else{
drh271efa52004-05-30 19:19:05 +0000464 /* If the payload will not fit completely on the local page, we have
465 ** to decide how much to store locally and how much to spill onto
466 ** overflow pages. The strategy is to minimize the amount of unused
467 ** space on overflow pages while keeping the amount of local storage
468 ** in between minLocal and maxLocal.
469 **
470 ** Warning: changing the way overflow payload is distributed in any
471 ** way will result in an incompatible file format.
472 */
473 int minLocal; /* Minimum amount of payload held locally */
474 int maxLocal; /* Maximum amount of payload held locally */
475 int surplus; /* Overflow payload available for local storage */
476
477 minLocal = pPage->minLocal;
478 maxLocal = pPage->maxLocal;
479 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000480 if( surplus <= maxLocal ){
481 pInfo->nLocal = surplus;
482 }else{
483 pInfo->nLocal = minLocal;
484 }
485 pInfo->iOverflow = pInfo->nLocal + n;
486 pInfo->nSize = pInfo->iOverflow + 4;
487 }
drh3aac2dd2004-04-26 14:10:20 +0000488}
drh43605152004-05-29 21:46:49 +0000489static void parseCell(
490 MemPage *pPage, /* Page containing the cell */
491 int iCell, /* The cell index. First cell is 0 */
492 CellInfo *pInfo /* Fill in this structure */
493){
494 parseCellPtr(pPage, findCell(pPage, iCell), pInfo);
495}
drh3aac2dd2004-04-26 14:10:20 +0000496
497/*
drh43605152004-05-29 21:46:49 +0000498** Compute the total number of bytes that a Cell needs in the cell
499** data area of the btree-page. The return number includes the cell
500** data header and the local payload, but not any overflow page or
501** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000502*/
drh43605152004-05-29 21:46:49 +0000503static int cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000504 CellInfo info;
drh43605152004-05-29 21:46:49 +0000505 parseCell(pPage, iCell, &info);
506 return info.nSize;
507}
508static int cellSizePtr(MemPage *pPage, u8 *pCell){
509 CellInfo info;
510 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000511 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000512}
513
514/*
drhda200cc2004-05-09 11:51:38 +0000515** Do sanity checking on a page. Throw an exception if anything is
516** not right.
517**
518** This routine is used for internal error checking only. It is omitted
519** from most builds.
520*/
521#if defined(BTREE_DEBUG) && !defined(NDEBUG) && 0
522static void _pageIntegrity(MemPage *pPage){
drhb6f41482004-05-14 01:58:11 +0000523 int usableSize;
drhda200cc2004-05-09 11:51:38 +0000524 u8 *data;
drh43605152004-05-29 21:46:49 +0000525 int i, j, idx, c, pc, hdr, nFree;
526 int cellOffset;
527 int nCell, cellLimit;
drhda200cc2004-05-09 11:51:38 +0000528 u8 used[MX_PAGE_SIZE];
529
drhb6f41482004-05-14 01:58:11 +0000530 usableSize = pPage->pBt->usableSize;
531 assert( pPage->aData==&((unsigned char*)pPage)[-pPage->pBt->pageSize] );
drhda200cc2004-05-09 11:51:38 +0000532 hdr = pPage->hdrOffset;
533 assert( hdr==(pPage->pgno==1 ? 100 : 0) );
534 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
535 c = pPage->aData[hdr];
536 if( pPage->isInit ){
537 assert( pPage->leaf == ((c & PTF_LEAF)!=0) );
538 assert( pPage->zeroData == ((c & PTF_ZERODATA)!=0) );
drh8b18dd42004-05-12 19:18:15 +0000539 assert( pPage->leafData == ((c & PTF_LEAFDATA)!=0) );
540 assert( pPage->intKey == ((c & (PTF_INTKEY|PTF_LEAFDATA))!=0) );
541 assert( pPage->hasData ==
542 !(pPage->zeroData || (!pPage->leaf && pPage->leafData)) );
drh43605152004-05-29 21:46:49 +0000543 assert( pPage->cellOffset==pPage->hdrOffset+12-4*pPage->leaf );
544 assert( pPage->nCell = get2byte(&pPage->aData[hdr+3]) );
drhda200cc2004-05-09 11:51:38 +0000545 }
546 data = pPage->aData;
drhb6f41482004-05-14 01:58:11 +0000547 memset(used, 0, usableSize);
drhda200cc2004-05-09 11:51:38 +0000548 for(i=0; i<hdr+10-pPage->leaf*4; i++) used[i] = 1;
549 nFree = 0;
550 pc = get2byte(&data[hdr+1]);
551 while( pc ){
552 int size;
drhb6f41482004-05-14 01:58:11 +0000553 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +0000554 size = get2byte(&data[pc+2]);
drhb6f41482004-05-14 01:58:11 +0000555 assert( pc+size<=usableSize );
drhda200cc2004-05-09 11:51:38 +0000556 nFree += size;
557 for(i=pc; i<pc+size; i++){
558 assert( used[i]==0 );
559 used[i] = 1;
560 }
561 pc = get2byte(&data[pc]);
562 }
drhda200cc2004-05-09 11:51:38 +0000563 idx = 0;
drh43605152004-05-29 21:46:49 +0000564 nCell = get2byte(&data[hdr+3]);
565 cellLimit = get2byte(&data[hdr+5]);
566 assert( pPage->isInit==0
567 || pPage->nFree==nFree+data[hdr+7]+cellLimit-(cellOffset+2*nCell) );
568 cellOffset = pPage->cellOffset;
569 for(i=0; i<nCell; i++){
drhda200cc2004-05-09 11:51:38 +0000570 int size;
drh43605152004-05-29 21:46:49 +0000571 pc = get2byte(&data[cellOffset+2*i]);
drhb6f41482004-05-14 01:58:11 +0000572 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +0000573 size = cellSize(pPage, &data[pc]);
drhb6f41482004-05-14 01:58:11 +0000574 assert( pc+size<=usableSize );
drh43605152004-05-29 21:46:49 +0000575 for(j=pc; j<pc+size; j++){
576 assert( used[j]==0 );
577 used[j] = 1;
drhda200cc2004-05-09 11:51:38 +0000578 }
drhda200cc2004-05-09 11:51:38 +0000579 }
drh43605152004-05-29 21:46:49 +0000580 for(i=cellOffset+2*nCell; i<cellimit; i++){
581 assert( used[i]==0 );
582 used[i] = 1;
583 }
drhda200cc2004-05-09 11:51:38 +0000584 nFree = 0;
drhb6f41482004-05-14 01:58:11 +0000585 for(i=0; i<usableSize; i++){
drhda200cc2004-05-09 11:51:38 +0000586 assert( used[i]<=1 );
587 if( used[i]==0 ) nFree++;
588 }
drh43605152004-05-29 21:46:49 +0000589 assert( nFree==data[hdr+7] );
drhda200cc2004-05-09 11:51:38 +0000590}
591#define pageIntegrity(X) _pageIntegrity(X)
592#else
593# define pageIntegrity(X)
594#endif
595
596/*
drh72f82862001-05-24 21:06:34 +0000597** Defragment the page given. All Cells are moved to the
598** beginning of the page and all free space is collected
599** into one big FreeBlk at the end of the page.
drh365d68f2001-05-11 11:02:46 +0000600*/
drh9e572e62004-04-23 23:43:10 +0000601static void defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000602 int i; /* Loop counter */
603 int pc; /* Address of a i-th cell */
604 int addr; /* Offset of first byte after cell pointer array */
605 int hdr; /* Offset to the page header */
606 int size; /* Size of a cell */
607 int usableSize; /* Number of usable bytes on a page */
608 int cellOffset; /* Offset to the cell pointer array */
609 int brk; /* Offset to the cell content area */
610 int nCell; /* Number of cells on the page */
611 unsigned char *data; /* The page data */
612 unsigned char temp[MX_PAGE_SIZE]; /* Temp holding area for cell content */
drh2af926b2001-05-15 00:39:25 +0000613
drha34b6762004-05-07 13:30:42 +0000614 assert( sqlite3pager_iswriteable(pPage->aData) );
drh9e572e62004-04-23 23:43:10 +0000615 assert( pPage->pBt!=0 );
drhb6f41482004-05-14 01:58:11 +0000616 assert( pPage->pBt->usableSize <= MX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000617 assert( pPage->nOverflow==0 );
618 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000619 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000620 cellOffset = pPage->cellOffset;
621 nCell = pPage->nCell;
622 assert( nCell==get2byte(&data[hdr+3]) );
623 usableSize = pPage->pBt->usableSize;
624 brk = get2byte(&data[hdr+5]);
625 memcpy(&temp[brk], &data[brk], usableSize - brk);
626 brk = usableSize;
627 for(i=0; i<nCell; i++){
628 u8 *pAddr; /* The i-th cell pointer */
629 pAddr = &data[cellOffset + i*2];
630 pc = get2byte(pAddr);
631 assert( pc<pPage->pBt->usableSize );
632 size = cellSizePtr(pPage, &temp[pc]);
633 brk -= size;
634 memcpy(&data[brk], &temp[pc], size);
635 put2byte(pAddr, brk);
drh2af926b2001-05-15 00:39:25 +0000636 }
drh43605152004-05-29 21:46:49 +0000637 assert( brk>=cellOffset+2*nCell );
638 put2byte(&data[hdr+5], brk);
639 data[hdr+1] = 0;
640 data[hdr+2] = 0;
641 data[hdr+7] = 0;
642 addr = cellOffset+2*nCell;
643 memset(&data[addr], 0, brk-addr);
drh365d68f2001-05-11 11:02:46 +0000644}
645
drha059ad02001-04-17 20:09:11 +0000646/*
drh43605152004-05-29 21:46:49 +0000647** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +0000648**
drh9e572e62004-04-23 23:43:10 +0000649** Return the index into pPage->aData[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000650** the new allocation. Or return 0 if there is not enough free
651** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000652**
drh72f82862001-05-24 21:06:34 +0000653** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000654** nBytes of contiguous free space, then this routine automatically
655** calls defragementPage() to consolidate all free space before
656** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000657*/
drh9e572e62004-04-23 23:43:10 +0000658static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +0000659 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +0000660 int size;
drh24cd67e2004-05-10 16:18:47 +0000661 int nFrag;
drh43605152004-05-29 21:46:49 +0000662 int top;
663 int nCell;
664 int cellOffset;
drh9e572e62004-04-23 23:43:10 +0000665 unsigned char *data;
drh43605152004-05-29 21:46:49 +0000666
drh9e572e62004-04-23 23:43:10 +0000667 data = pPage->aData;
drha34b6762004-05-07 13:30:42 +0000668 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +0000669 assert( pPage->pBt );
670 if( nByte<4 ) nByte = 4;
drh43605152004-05-29 21:46:49 +0000671 if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
672 pPage->nFree -= nByte;
drh9e572e62004-04-23 23:43:10 +0000673 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000674
675 nFrag = data[hdr+7];
676 if( nFrag<60 ){
677 /* Search the freelist looking for a slot big enough to satisfy the
678 ** space request. */
679 addr = hdr+1;
680 while( (pc = get2byte(&data[addr]))>0 ){
681 size = get2byte(&data[pc+2]);
682 if( size>=nByte ){
683 if( size<nByte+4 ){
684 memcpy(&data[addr], &data[pc], 2);
685 data[hdr+7] = nFrag + size - nByte;
686 return pc;
687 }else{
688 put2byte(&data[pc+2], size-nByte);
689 return pc + size - nByte;
690 }
691 }
692 addr = pc;
drh9e572e62004-04-23 23:43:10 +0000693 }
694 }
drh43605152004-05-29 21:46:49 +0000695
696 /* Allocate memory from the gap in between the cell pointer array
697 ** and the cell content area.
698 */
699 top = get2byte(&data[hdr+5]);
700 nCell = get2byte(&data[hdr+3]);
701 cellOffset = pPage->cellOffset;
702 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
703 defragmentPage(pPage);
704 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +0000705 }
drh43605152004-05-29 21:46:49 +0000706 top -= nByte;
707 assert( cellOffset + 2*nCell <= top );
708 put2byte(&data[hdr+5], top);
709 return top;
drh7e3b0a02001-04-28 16:52:40 +0000710}
711
712/*
drh9e572e62004-04-23 23:43:10 +0000713** Return a section of the pPage->aData to the freelist.
714** The first byte of the new free block is pPage->aDisk[start]
715** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +0000716**
717** Most of the effort here is involved in coalesing adjacent
718** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000719*/
drh9e572e62004-04-23 23:43:10 +0000720static void freeSpace(MemPage *pPage, int start, int size){
721 int end = start + size; /* End of the segment being freed */
drh43605152004-05-29 21:46:49 +0000722 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +0000723 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +0000724
drh9e572e62004-04-23 23:43:10 +0000725 assert( pPage->pBt!=0 );
drha34b6762004-05-07 13:30:42 +0000726 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +0000727 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
drhb6f41482004-05-14 01:58:11 +0000728 assert( end<=pPage->pBt->usableSize );
drh9e572e62004-04-23 23:43:10 +0000729 if( size<4 ) size = 4;
730
731 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +0000732 hdr = pPage->hdrOffset;
733 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +0000734 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +0000735 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000736 assert( pbegin>addr );
737 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +0000738 }
drhb6f41482004-05-14 01:58:11 +0000739 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000740 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +0000741 put2byte(&data[addr], start);
742 put2byte(&data[start], pbegin);
743 put2byte(&data[start+2], size);
drh2af926b2001-05-15 00:39:25 +0000744 pPage->nFree += size;
drh9e572e62004-04-23 23:43:10 +0000745
746 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +0000747 addr = pPage->hdrOffset + 1;
748 while( (pbegin = get2byte(&data[addr]))>0 ){
drh9e572e62004-04-23 23:43:10 +0000749 int pnext, psize;
drh3aac2dd2004-04-26 14:10:20 +0000750 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +0000751 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +0000752 pnext = get2byte(&data[pbegin]);
753 psize = get2byte(&data[pbegin+2]);
754 if( pbegin + psize + 3 >= pnext && pnext>0 ){
755 int frag = pnext - (pbegin+psize);
drh43605152004-05-29 21:46:49 +0000756 assert( frag<=data[pPage->hdrOffset+7] );
757 data[pPage->hdrOffset+7] -= frag;
drh9e572e62004-04-23 23:43:10 +0000758 put2byte(&data[pbegin], get2byte(&data[pnext]));
759 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
760 }else{
drh3aac2dd2004-04-26 14:10:20 +0000761 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +0000762 }
763 }
drh7e3b0a02001-04-28 16:52:40 +0000764
drh43605152004-05-29 21:46:49 +0000765 /* If the cell content area begins with a freeblock, remove it. */
766 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
767 int top;
768 pbegin = get2byte(&data[hdr+1]);
769 memcpy(&data[hdr+1], &data[pbegin], 2);
770 top = get2byte(&data[hdr+5]);
771 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
drh4b70f112004-05-02 21:12:19 +0000772 }
drh4b70f112004-05-02 21:12:19 +0000773}
774
775/*
drh271efa52004-05-30 19:19:05 +0000776** Decode the flags byte (the first byte of the header) for a page
777** and initialize fields of the MemPage structure accordingly.
778*/
779static void decodeFlags(MemPage *pPage, int flagByte){
780 Btree *pBt; /* A copy of pPage->pBt */
781
782 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
783 pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
784 pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
785 pPage->leaf = (flagByte & PTF_LEAF)!=0;
786 pPage->childPtrSize = 4*(pPage->leaf==0);
787 pBt = pPage->pBt;
788 if( flagByte & PTF_LEAFDATA ){
789 pPage->leafData = 1;
790 pPage->maxLocal = pBt->maxLeaf;
791 pPage->minLocal = pBt->minLeaf;
792 }else{
793 pPage->leafData = 0;
794 pPage->maxLocal = pBt->maxLocal;
795 pPage->minLocal = pBt->minLocal;
796 }
797 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
798}
799
800/*
drh7e3b0a02001-04-28 16:52:40 +0000801** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000802**
drhbd03cae2001-06-02 02:40:57 +0000803** The pParent parameter must be a pointer to the MemPage which
drh9e572e62004-04-23 23:43:10 +0000804** is the parent of the page being initialized. The root of a
805** BTree has no parent and so for that page, pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000806**
drh72f82862001-05-24 21:06:34 +0000807** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +0000808** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +0000809** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
810** guarantee that the page is well-formed. It only shows that
811** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000812*/
drh9e572e62004-04-23 23:43:10 +0000813static int initPage(
drh3aac2dd2004-04-26 14:10:20 +0000814 MemPage *pPage, /* The page to be initialized */
drh9e572e62004-04-23 23:43:10 +0000815 MemPage *pParent /* The parent. Might be NULL */
816){
drh271efa52004-05-30 19:19:05 +0000817 int pc; /* Address of a freeblock within pPage->aData[] */
818 int i; /* Loop counter */
819 int hdr; /* Offset to beginning of page header */
820 u8 *data; /* Equal to pPage->aData */
821 int usableSize; /* Amount of usable space on each page */
822 int cellOffset; /* Offset from start of page to first cell pointer */
823 int nFree; /* Number of unused bytes on the page */
824 int top; /* First byte of the cell content area */
drh2af926b2001-05-15 00:39:25 +0000825
drh3aac2dd2004-04-26 14:10:20 +0000826 assert( pPage->pBt!=0 );
drh4b70f112004-05-02 21:12:19 +0000827 assert( pParent==0 || pParent->pBt==pPage->pBt );
drha34b6762004-05-07 13:30:42 +0000828 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
drhde647132004-05-07 17:57:49 +0000829 assert( pPage->aData == &((unsigned char*)pPage)[-pPage->pBt->pageSize] );
drhda200cc2004-05-09 11:51:38 +0000830 assert( pPage->pParent==0 || pPage->pParent==pParent );
drh10617cd2004-05-14 15:27:27 +0000831 assert( pPage->pParent==pParent || !pPage->isInit );
832 if( pPage->isInit ) return SQLITE_OK;
drhda200cc2004-05-09 11:51:38 +0000833 if( pPage->pParent==0 && pParent!=0 ){
834 pPage->pParent = pParent;
drha34b6762004-05-07 13:30:42 +0000835 sqlite3pager_ref(pParent->aData);
drh5e2f8b92001-05-28 00:41:15 +0000836 }
drhde647132004-05-07 17:57:49 +0000837 hdr = pPage->hdrOffset;
drha34b6762004-05-07 13:30:42 +0000838 data = pPage->aData;
drh271efa52004-05-30 19:19:05 +0000839 decodeFlags(pPage, data[hdr]);
drh43605152004-05-29 21:46:49 +0000840 pPage->nOverflow = 0;
drhc8629a12004-05-08 20:07:40 +0000841 pPage->idxShift = 0;
drhb6f41482004-05-14 01:58:11 +0000842 usableSize = pPage->pBt->usableSize;
drh43605152004-05-29 21:46:49 +0000843 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
844 top = get2byte(&data[hdr+5]);
845 pPage->nCell = get2byte(&data[hdr+3]);
drh9e572e62004-04-23 23:43:10 +0000846
847 /* Compute the total free space on the page */
drh9e572e62004-04-23 23:43:10 +0000848 pc = get2byte(&data[hdr+1]);
drh43605152004-05-29 21:46:49 +0000849 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
drh3add3672004-05-15 00:29:24 +0000850 i = 0;
drh9e572e62004-04-23 23:43:10 +0000851 while( pc>0 ){
852 int next, size;
drhb6f41482004-05-14 01:58:11 +0000853 if( pc>=usableSize ) return SQLITE_CORRUPT;
drh3add3672004-05-15 00:29:24 +0000854 if( i++>MX_PAGE_SIZE ) return SQLITE_CORRUPT;
drh9e572e62004-04-23 23:43:10 +0000855 next = get2byte(&data[pc]);
856 size = get2byte(&data[pc+2]);
drh3aac2dd2004-04-26 14:10:20 +0000857 if( next>0 && next<=pc+size+3 ) return SQLITE_CORRUPT;
drh3add3672004-05-15 00:29:24 +0000858 nFree += size;
drh9e572e62004-04-23 23:43:10 +0000859 pc = next;
860 }
drh3add3672004-05-15 00:29:24 +0000861 pPage->nFree = nFree;
862 if( nFree>=usableSize ) return SQLITE_CORRUPT;
drh9e572e62004-04-23 23:43:10 +0000863
drhde647132004-05-07 17:57:49 +0000864 pPage->isInit = 1;
drhda200cc2004-05-09 11:51:38 +0000865 pageIntegrity(pPage);
drh9e572e62004-04-23 23:43:10 +0000866 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +0000867}
868
869/*
drh8b2f49b2001-06-08 00:21:52 +0000870** Set up a raw page so that it looks like a database page holding
871** no entries.
drhbd03cae2001-06-02 02:40:57 +0000872*/
drh9e572e62004-04-23 23:43:10 +0000873static void zeroPage(MemPage *pPage, int flags){
874 unsigned char *data = pPage->aData;
875 Btree *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +0000876 int hdr = pPage->hdrOffset;
drh9e572e62004-04-23 23:43:10 +0000877 int first;
878
drhda200cc2004-05-09 11:51:38 +0000879 assert( sqlite3pager_pagenumber(data)==pPage->pgno );
880 assert( &data[pBt->pageSize] == (unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +0000881 assert( sqlite3pager_iswriteable(data) );
drhb6f41482004-05-14 01:58:11 +0000882 memset(&data[hdr], 0, pBt->usableSize - hdr);
drh9e572e62004-04-23 23:43:10 +0000883 data[hdr] = flags;
drh43605152004-05-29 21:46:49 +0000884 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
885 memset(&data[hdr+1], 0, 4);
886 data[hdr+7] = 0;
887 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +0000888 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +0000889 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +0000890 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +0000891 pPage->cellOffset = first;
892 pPage->nOverflow = 0;
drhda200cc2004-05-09 11:51:38 +0000893 pPage->idxShift = 0;
drh43605152004-05-29 21:46:49 +0000894 pPage->nCell = 0;
drhda200cc2004-05-09 11:51:38 +0000895 pPage->isInit = 1;
896 pageIntegrity(pPage);
drhbd03cae2001-06-02 02:40:57 +0000897}
898
899/*
drh3aac2dd2004-04-26 14:10:20 +0000900** Get a page from the pager. Initialize the MemPage.pBt and
901** MemPage.aData elements if needed.
902*/
903static int getPage(Btree *pBt, Pgno pgno, MemPage **ppPage){
904 int rc;
905 unsigned char *aData;
906 MemPage *pPage;
drha34b6762004-05-07 13:30:42 +0000907 rc = sqlite3pager_get(pBt->pPager, pgno, (void**)&aData);
drh3aac2dd2004-04-26 14:10:20 +0000908 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +0000909 pPage = (MemPage*)&aData[pBt->pageSize];
drh3aac2dd2004-04-26 14:10:20 +0000910 pPage->aData = aData;
911 pPage->pBt = pBt;
912 pPage->pgno = pgno;
drhde647132004-05-07 17:57:49 +0000913 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
drh3aac2dd2004-04-26 14:10:20 +0000914 *ppPage = pPage;
915 return SQLITE_OK;
916}
917
918/*
drhde647132004-05-07 17:57:49 +0000919** Get a page from the pager and initialize it. This routine
920** is just a convenience wrapper around separate calls to
921** getPage() and initPage().
922*/
923static int getAndInitPage(
924 Btree *pBt, /* The database file */
925 Pgno pgno, /* Number of the page to get */
926 MemPage **ppPage, /* Write the page pointer here */
927 MemPage *pParent /* Parent of the page */
928){
929 int rc;
930 rc = getPage(pBt, pgno, ppPage);
drh10617cd2004-05-14 15:27:27 +0000931 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
drhde647132004-05-07 17:57:49 +0000932 rc = initPage(*ppPage, pParent);
933 }
934 return rc;
935}
936
937/*
drh3aac2dd2004-04-26 14:10:20 +0000938** Release a MemPage. This should be called once for each prior
939** call to getPage.
940*/
drh4b70f112004-05-02 21:12:19 +0000941static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +0000942 if( pPage ){
943 assert( pPage->aData );
944 assert( pPage->pBt );
945 assert( &pPage->aData[pPage->pBt->pageSize]==(unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +0000946 sqlite3pager_unref(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +0000947 }
948}
949
950/*
drh72f82862001-05-24 21:06:34 +0000951** This routine is called when the reference count for a page
952** reaches zero. We need to unref the pParent pointer when that
953** happens.
954*/
drhb6f41482004-05-14 01:58:11 +0000955static void pageDestructor(void *pData, int pageSize){
956 MemPage *pPage = (MemPage*)&((char*)pData)[pageSize];
drh72f82862001-05-24 21:06:34 +0000957 if( pPage->pParent ){
958 MemPage *pParent = pPage->pParent;
959 pPage->pParent = 0;
drha34b6762004-05-07 13:30:42 +0000960 releasePage(pParent);
drh72f82862001-05-24 21:06:34 +0000961 }
drh3aac2dd2004-04-26 14:10:20 +0000962 pPage->isInit = 0;
drh72f82862001-05-24 21:06:34 +0000963}
964
965/*
drh306dc212001-05-21 13:45:10 +0000966** Open a new database.
967**
968** Actually, this routine just sets up the internal data structures
drh72f82862001-05-24 21:06:34 +0000969** for accessing the database. We do not open the database file
970** until the first page is loaded.
drh382c0242001-10-06 16:33:02 +0000971**
972** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +0000973** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +0000974** database file will be deleted when sqlite3BtreeClose() is called.
drha059ad02001-04-17 20:09:11 +0000975*/
drh23e11ca2004-05-04 17:27:28 +0000976int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +0000977 const char *zFilename, /* Name of the file containing the BTree database */
978 Btree **ppBtree, /* Pointer to new Btree object written here */
979 int nCache, /* Number of cache pages */
980 int flags /* Options */
drh6019e162001-07-02 17:51:45 +0000981){
drha059ad02001-04-17 20:09:11 +0000982 Btree *pBt;
drha34b6762004-05-07 13:30:42 +0000983 int rc;
drha059ad02001-04-17 20:09:11 +0000984
drhd62d3d02003-01-24 12:14:20 +0000985 /*
986 ** The following asserts make sure that structures used by the btree are
987 ** the right size. This is to guard against size changes that result
988 ** when compiling on a different architecture.
989 */
drh4a1c3802004-05-12 15:15:47 +0000990 assert( sizeof(i64)==8 );
drh9e572e62004-04-23 23:43:10 +0000991 assert( sizeof(u64)==8 );
drhd62d3d02003-01-24 12:14:20 +0000992 assert( sizeof(u32)==4 );
993 assert( sizeof(u16)==2 );
994 assert( sizeof(Pgno)==4 );
drhd62d3d02003-01-24 12:14:20 +0000995 assert( sizeof(ptr)==sizeof(char*) );
996 assert( sizeof(uptr)==sizeof(ptr) );
997
drha059ad02001-04-17 20:09:11 +0000998 pBt = sqliteMalloc( sizeof(*pBt) );
999 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +00001000 *ppBtree = 0;
drha059ad02001-04-17 20:09:11 +00001001 return SQLITE_NOMEM;
1002 }
drh6019e162001-07-02 17:51:45 +00001003 if( nCache<10 ) nCache = 10;
drha34b6762004-05-07 13:30:42 +00001004 rc = sqlite3pager_open(&pBt->pPager, zFilename, nCache, EXTRA_SIZE,
drh3aac2dd2004-04-26 14:10:20 +00001005 (flags & BTREE_OMIT_JOURNAL)==0);
drha059ad02001-04-17 20:09:11 +00001006 if( rc!=SQLITE_OK ){
drha34b6762004-05-07 13:30:42 +00001007 if( pBt->pPager ) sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001008 sqliteFree(pBt);
1009 *ppBtree = 0;
1010 return rc;
1011 }
drha34b6762004-05-07 13:30:42 +00001012 sqlite3pager_set_destructor(pBt->pPager, pageDestructor);
drha059ad02001-04-17 20:09:11 +00001013 pBt->pCursor = 0;
drha34b6762004-05-07 13:30:42 +00001014 pBt->pPage1 = 0;
1015 pBt->readOnly = sqlite3pager_isreadonly(pBt->pPager);
drh4b70f112004-05-02 21:12:19 +00001016 pBt->pageSize = SQLITE_PAGE_SIZE; /* FIX ME - read from header */
drhb6f41482004-05-14 01:58:11 +00001017 pBt->usableSize = pBt->pageSize;
drh6f11bef2004-05-13 01:12:56 +00001018 pBt->maxEmbedFrac = 64; /* FIX ME - read from header */
1019 pBt->minEmbedFrac = 32; /* FIX ME - read from header */
1020 pBt->minLeafFrac = 32; /* FIX ME - read from header */
drh3a4c1412004-05-09 20:40:11 +00001021
drha059ad02001-04-17 20:09:11 +00001022 *ppBtree = pBt;
1023 return SQLITE_OK;
1024}
1025
1026/*
1027** Close an open database and invalidate all cursors.
1028*/
drh3aac2dd2004-04-26 14:10:20 +00001029int sqlite3BtreeClose(Btree *pBt){
drha059ad02001-04-17 20:09:11 +00001030 while( pBt->pCursor ){
drh3aac2dd2004-04-26 14:10:20 +00001031 sqlite3BtreeCloseCursor(pBt->pCursor);
drha059ad02001-04-17 20:09:11 +00001032 }
drha34b6762004-05-07 13:30:42 +00001033 sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001034 sqliteFree(pBt);
1035 return SQLITE_OK;
1036}
1037
1038/*
drhda47d772002-12-02 04:25:19 +00001039** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001040**
1041** The maximum number of cache pages is set to the absolute
1042** value of mxPage. If mxPage is negative, the pager will
1043** operate asynchronously - it will not stop to do fsync()s
1044** to insure data is written to the disk surface before
1045** continuing. Transactions still work if synchronous is off,
1046** and the database cannot be corrupted if this program
1047** crashes. But if the operating system crashes or there is
1048** an abrupt power failure when synchronous is off, the database
1049** could be left in an inconsistent and unrecoverable state.
1050** Synchronous is on by default so database corruption is not
1051** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001052*/
drh23e11ca2004-05-04 17:27:28 +00001053int sqlite3BtreeSetCacheSize(Btree *pBt, int mxPage){
drha34b6762004-05-07 13:30:42 +00001054 sqlite3pager_set_cachesize(pBt->pPager, mxPage);
drhf57b14a2001-09-14 18:54:08 +00001055 return SQLITE_OK;
1056}
1057
1058/*
drh973b6e32003-02-12 14:09:42 +00001059** Change the way data is synced to disk in order to increase or decrease
1060** how well the database resists damage due to OS crashes and power
1061** failures. Level 1 is the same as asynchronous (no syncs() occur and
1062** there is a high probability of damage) Level 2 is the default. There
1063** is a very low but non-zero probability of damage. Level 3 reduces the
1064** probability of damage to near zero but with a write performance reduction.
1065*/
drh3aac2dd2004-04-26 14:10:20 +00001066int sqlite3BtreeSetSafetyLevel(Btree *pBt, int level){
drha34b6762004-05-07 13:30:42 +00001067 sqlite3pager_set_safety_level(pBt->pPager, level);
drh973b6e32003-02-12 14:09:42 +00001068 return SQLITE_OK;
1069}
1070
1071/*
drha34b6762004-05-07 13:30:42 +00001072** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001073** also acquire a readlock on that file.
1074**
1075** SQLITE_OK is returned on success. If the file is not a
1076** well-formed database file, then SQLITE_CORRUPT is returned.
1077** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
1078** is returned if we run out of memory. SQLITE_PROTOCOL is returned
1079** if there is a locking protocol violation.
1080*/
1081static int lockBtree(Btree *pBt){
1082 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001083 MemPage *pPage1;
drha34b6762004-05-07 13:30:42 +00001084 if( pBt->pPage1 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001085 rc = getPage(pBt, 1, &pPage1);
drh306dc212001-05-21 13:45:10 +00001086 if( rc!=SQLITE_OK ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00001087
drh306dc212001-05-21 13:45:10 +00001088
1089 /* Do some checking to help insure the file we opened really is
1090 ** a valid database file.
1091 */
drhb6f41482004-05-14 01:58:11 +00001092 rc = SQLITE_NOTADB;
drha34b6762004-05-07 13:30:42 +00001093 if( sqlite3pager_pagecount(pBt->pPager)>0 ){
drhb6f41482004-05-14 01:58:11 +00001094 u8 *page1 = pPage1->aData;
1095 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001096 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001097 }
drhb6f41482004-05-14 01:58:11 +00001098 if( page1[18]>1 || page1[19]>1 ){
1099 goto page1_init_failed;
1100 }
1101 pBt->pageSize = get2byte(&page1[16]);
1102 pBt->usableSize = pBt->pageSize - page1[20];
1103 if( pBt->usableSize<500 ){
1104 goto page1_init_failed;
1105 }
1106 pBt->maxEmbedFrac = page1[21];
1107 pBt->minEmbedFrac = page1[22];
1108 pBt->minLeafFrac = page1[23];
drh306dc212001-05-21 13:45:10 +00001109 }
drhb6f41482004-05-14 01:58:11 +00001110
1111 /* maxLocal is the maximum amount of payload to store locally for
1112 ** a cell. Make sure it is small enough so that at least minFanout
1113 ** cells can will fit on one page. We assume a 10-byte page header.
1114 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001115 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001116 ** 4-byte child pointer
1117 ** 9-byte nKey value
1118 ** 4-byte nData value
1119 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001120 ** So a cell consists of a 2-byte poiner, a header which is as much as
1121 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1122 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001123 */
drh43605152004-05-29 21:46:49 +00001124 pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
1125 pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
1126 pBt->maxLeaf = pBt->usableSize - 35;
1127 pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
drhb6f41482004-05-14 01:58:11 +00001128 if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
1129 goto page1_init_failed;
1130 }
1131 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE );
drh3aac2dd2004-04-26 14:10:20 +00001132 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001133 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001134
drh72f82862001-05-24 21:06:34 +00001135page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001136 releasePage(pPage1);
1137 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001138 return rc;
drh306dc212001-05-21 13:45:10 +00001139}
1140
1141/*
drhb8ca3072001-12-05 00:21:20 +00001142** If there are no outstanding cursors and we are not in the middle
1143** of a transaction but there is a read lock on the database, then
1144** this routine unrefs the first page of the database file which
1145** has the effect of releasing the read lock.
1146**
1147** If there are any outstanding cursors, this routine is a no-op.
1148**
1149** If there is a transaction in progress, this routine is a no-op.
1150*/
1151static void unlockBtreeIfUnused(Btree *pBt){
danielk1977ee5741e2004-05-31 10:01:34 +00001152 if( pBt->inTrans==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
drh3aac2dd2004-04-26 14:10:20 +00001153 releasePage(pBt->pPage1);
1154 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00001155 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001156 }
1157}
1158
1159/*
drh9e572e62004-04-23 23:43:10 +00001160** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001161** file.
drh8b2f49b2001-06-08 00:21:52 +00001162*/
1163static int newDatabase(Btree *pBt){
drh9e572e62004-04-23 23:43:10 +00001164 MemPage *pP1;
1165 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001166 int rc;
drhde647132004-05-07 17:57:49 +00001167 if( sqlite3pager_pagecount(pBt->pPager)>0 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001168 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00001169 assert( pP1!=0 );
1170 data = pP1->aData;
drha34b6762004-05-07 13:30:42 +00001171 rc = sqlite3pager_write(data);
drh8b2f49b2001-06-08 00:21:52 +00001172 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00001173 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
1174 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00001175 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00001176 data[18] = 1;
1177 data[19] = 1;
drhb6f41482004-05-14 01:58:11 +00001178 data[20] = pBt->pageSize - pBt->usableSize;
1179 data[21] = pBt->maxEmbedFrac;
1180 data[22] = pBt->minEmbedFrac;
1181 data[23] = pBt->minLeafFrac;
1182 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00001183 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drh8b2f49b2001-06-08 00:21:52 +00001184 return SQLITE_OK;
1185}
1186
1187/*
danielk1977ee5741e2004-05-31 10:01:34 +00001188** Attempt to start a new transaction. A write-transaction
1189** is started if the second argument is true, otherwise a read-
1190** transaction.
drh8b2f49b2001-06-08 00:21:52 +00001191**
danielk1977ee5741e2004-05-31 10:01:34 +00001192** A write-transaction must be started before attempting any
1193** changes to the database. None of the following routines
1194** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00001195**
drh23e11ca2004-05-04 17:27:28 +00001196** sqlite3BtreeCreateTable()
1197** sqlite3BtreeCreateIndex()
1198** sqlite3BtreeClearTable()
1199** sqlite3BtreeDropTable()
1200** sqlite3BtreeInsert()
1201** sqlite3BtreeDelete()
1202** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00001203**
1204** If wrflag is true, then nMaster specifies the maximum length of
1205** a master journal file name supplied later via sqlite3BtreeSync().
1206** This is so that appropriate space can be allocated in the journal file
1207** when it is created..
drha059ad02001-04-17 20:09:11 +00001208*/
danielk197713adf8a2004-06-03 16:08:41 +00001209int sqlite3BtreeBeginTrans(Btree *pBt, int wrflag, int nMaster){
danielk1977ee5741e2004-05-31 10:01:34 +00001210 int rc = SQLITE_OK;
1211
1212 /* If the btree is already in a write-transaction, or it
1213 ** is already in a read-transaction and a read-transaction
1214 ** is requested, this is a no-op.
1215 */
1216 if( pBt->inTrans==TRANS_WRITE ||
1217 (pBt->inTrans==TRANS_READ && !wrflag) ){
1218 return SQLITE_OK;
1219 }
1220 if( pBt->readOnly && wrflag ){
1221 return SQLITE_READONLY;
1222 }
1223
drh3aac2dd2004-04-26 14:10:20 +00001224 if( pBt->pPage1==0 ){
drh7e3b0a02001-04-28 16:52:40 +00001225 rc = lockBtree(pBt);
danielk1977ee5741e2004-05-31 10:01:34 +00001226 }
1227
1228 if( rc==SQLITE_OK && wrflag ){
danielk197713adf8a2004-06-03 16:08:41 +00001229 rc = sqlite3pager_begin(pBt->pPage1->aData, 0);
danielk1977ee5741e2004-05-31 10:01:34 +00001230 if( rc==SQLITE_OK ){
1231 rc = newDatabase(pBt);
drh8c42ca92001-06-22 19:15:00 +00001232 }
drha059ad02001-04-17 20:09:11 +00001233 }
danielk1977ee5741e2004-05-31 10:01:34 +00001234
drhf74b8d92002-09-01 23:20:45 +00001235 if( rc==SQLITE_OK ){
danielk1977ee5741e2004-05-31 10:01:34 +00001236 pBt->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
1237 if( wrflag ) pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001238 }else{
1239 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001240 }
drhb8ca3072001-12-05 00:21:20 +00001241 return rc;
drha059ad02001-04-17 20:09:11 +00001242}
1243
1244/*
drh2aa679f2001-06-25 02:11:07 +00001245** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00001246**
1247** This will release the write lock on the database file. If there
1248** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00001249*/
drh3aac2dd2004-04-26 14:10:20 +00001250int sqlite3BtreeCommit(Btree *pBt){
danielk1977ee5741e2004-05-31 10:01:34 +00001251 int rc = SQLITE_OK;
1252 if( pBt->inTrans==TRANS_WRITE ){
1253 rc = sqlite3pager_commit(pBt->pPager);
1254 }
1255 pBt->inTrans = TRANS_NONE;
drh3aac2dd2004-04-26 14:10:20 +00001256 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00001257 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001258 return rc;
1259}
1260
1261/*
drhc39e0002004-05-07 23:50:57 +00001262** Invalidate all cursors
1263*/
1264static void invalidateCursors(Btree *pBt){
1265 BtCursor *pCur;
1266 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1267 MemPage *pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00001268 if( pPage /* && !pPage->isInit */ ){
1269 pageIntegrity(pPage);
drhc39e0002004-05-07 23:50:57 +00001270 releasePage(pPage);
1271 pCur->pPage = 0;
1272 pCur->isValid = 0;
1273 pCur->status = SQLITE_ABORT;
1274 }
1275 }
1276}
1277
drhda200cc2004-05-09 11:51:38 +00001278#ifdef SQLITE_TEST
1279/*
1280** Print debugging information about all cursors to standard output.
1281*/
1282void sqlite3BtreeCursorList(Btree *pBt){
1283 BtCursor *pCur;
1284 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1285 MemPage *pPage = pCur->pPage;
1286 char *zMode = pCur->wrFlag ? "rw" : "ro";
1287 printf("CURSOR %08x rooted at %4d(%s) currently at %d.%d%s\n",
1288 (int)pCur, pCur->pgnoRoot, zMode,
1289 pPage ? pPage->pgno : 0, pCur->idx,
1290 pCur->isValid ? "" : " eof"
1291 );
1292 }
1293}
1294#endif
1295
drhc39e0002004-05-07 23:50:57 +00001296/*
drhecdc7532001-09-23 02:35:53 +00001297** Rollback the transaction in progress. All cursors will be
1298** invalided by this operation. Any attempt to use a cursor
1299** that was open at the beginning of this operation will result
1300** in an error.
drh5e00f6c2001-09-13 13:46:56 +00001301**
1302** This will release the write lock on the database file. If there
1303** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00001304*/
drh3aac2dd2004-04-26 14:10:20 +00001305int sqlite3BtreeRollback(Btree *pBt){
drha059ad02001-04-17 20:09:11 +00001306 int rc;
drh24cd67e2004-05-10 16:18:47 +00001307 MemPage *pPage1;
danielk1977ee5741e2004-05-31 10:01:34 +00001308 if( pBt->inTrans==TRANS_WRITE ){
drh24cd67e2004-05-10 16:18:47 +00001309 rc = sqlite3pager_rollback(pBt->pPager);
1310 /* The rollback may have destroyed the pPage1->aData value. So
1311 ** call getPage() on page 1 again to make sure pPage1->aData is
1312 ** set correctly. */
1313 if( getPage(pBt, 1, &pPage1)==SQLITE_OK ){
1314 releasePage(pPage1);
1315 }
danielk1977ee5741e2004-05-31 10:01:34 +00001316 invalidateCursors(pBt);
drh24cd67e2004-05-10 16:18:47 +00001317 }
danielk1977ee5741e2004-05-31 10:01:34 +00001318 pBt->inTrans = TRANS_NONE;
1319 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00001320 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001321 return rc;
1322}
1323
1324/*
drhab01f612004-05-22 02:55:23 +00001325** Start a statement subtransaction. The subtransaction can
1326** can be rolled back independently of the main transaction.
1327** You must start a transaction before starting a subtransaction.
1328** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00001329** commits or rolls back.
1330**
drhab01f612004-05-22 02:55:23 +00001331** Only one subtransaction may be active at a time. It is an error to try
1332** to start a new subtransaction if another subtransaction is already active.
1333**
1334** Statement subtransactions are used around individual SQL statements
1335** that are contained within a BEGIN...COMMIT block. If a constraint
1336** error occurs within the statement, the effect of that one statement
1337** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00001338*/
drh3aac2dd2004-04-26 14:10:20 +00001339int sqlite3BtreeBeginStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00001340 int rc;
danielk1977ee5741e2004-05-31 10:01:34 +00001341 if( (pBt->inTrans!=TRANS_WRITE) || pBt->inStmt ){
drhf74b8d92002-09-01 23:20:45 +00001342 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh0d65dc02002-02-03 00:56:09 +00001343 }
drha34b6762004-05-07 13:30:42 +00001344 rc = pBt->readOnly ? SQLITE_OK : sqlite3pager_stmt_begin(pBt->pPager);
drh3aac2dd2004-04-26 14:10:20 +00001345 pBt->inStmt = 1;
drh663fc632002-02-02 18:49:19 +00001346 return rc;
1347}
1348
1349
1350/*
drhab01f612004-05-22 02:55:23 +00001351** Commit the statment subtransaction currently in progress. If no
1352** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00001353*/
drh3aac2dd2004-04-26 14:10:20 +00001354int sqlite3BtreeCommitStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00001355 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001356 if( pBt->inStmt && !pBt->readOnly ){
drha34b6762004-05-07 13:30:42 +00001357 rc = sqlite3pager_stmt_commit(pBt->pPager);
drh663fc632002-02-02 18:49:19 +00001358 }else{
1359 rc = SQLITE_OK;
1360 }
drh3aac2dd2004-04-26 14:10:20 +00001361 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00001362 return rc;
1363}
1364
1365/*
drhab01f612004-05-22 02:55:23 +00001366** Rollback the active statement subtransaction. If no subtransaction
1367** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00001368**
drhab01f612004-05-22 02:55:23 +00001369** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00001370** to use a cursor that was open at the beginning of this operation
1371** will result in an error.
1372*/
drh3aac2dd2004-04-26 14:10:20 +00001373int sqlite3BtreeRollbackStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00001374 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001375 if( pBt->inStmt==0 || pBt->readOnly ) return SQLITE_OK;
drha34b6762004-05-07 13:30:42 +00001376 rc = sqlite3pager_stmt_rollback(pBt->pPager);
drhc39e0002004-05-07 23:50:57 +00001377 invalidateCursors(pBt);
drh3aac2dd2004-04-26 14:10:20 +00001378 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00001379 return rc;
1380}
1381
1382/*
drh3aac2dd2004-04-26 14:10:20 +00001383** Default key comparison function to be used if no comparison function
1384** is specified on the sqlite3BtreeCursor() call.
1385*/
1386static int dfltCompare(
1387 void *NotUsed, /* User data is not used */
1388 int n1, const void *p1, /* First key to compare */
1389 int n2, const void *p2 /* Second key to compare */
1390){
1391 int c;
1392 c = memcmp(p1, p2, n1<n2 ? n1 : n2);
1393 if( c==0 ){
1394 c = n1 - n2;
1395 }
1396 return c;
1397}
1398
1399/*
drh8b2f49b2001-06-08 00:21:52 +00001400** Create a new cursor for the BTree whose root is on the page
1401** iTable. The act of acquiring a cursor gets a read lock on
1402** the database file.
drh1bee3d72001-10-15 00:44:35 +00001403**
1404** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00001405** If wrFlag==1, then the cursor can be used for reading or for
1406** writing if other conditions for writing are also met. These
1407** are the conditions that must be met in order for writing to
1408** be allowed:
drh6446c4d2001-12-15 14:22:18 +00001409**
drhf74b8d92002-09-01 23:20:45 +00001410** 1: The cursor must have been opened with wrFlag==1
1411**
1412** 2: No other cursors may be open with wrFlag==0 on the same table
1413**
1414** 3: The database must be writable (not on read-only media)
1415**
1416** 4: There must be an active transaction.
1417**
1418** Condition 2 warrants further discussion. If any cursor is opened
1419** on a table with wrFlag==0, that prevents all other cursors from
1420** writing to that table. This is a kind of "read-lock". When a cursor
1421** is opened with wrFlag==0 it is guaranteed that the table will not
1422** change as long as the cursor is open. This allows the cursor to
1423** do a sequential scan of the table without having to worry about
1424** entries being inserted or deleted during the scan. Cursors should
1425** be opened with wrFlag==0 only if this read-lock property is needed.
1426** That is to say, cursors should be opened with wrFlag==0 only if they
drh23e11ca2004-05-04 17:27:28 +00001427** intend to use the sqlite3BtreeNext() system call. All other cursors
drhf74b8d92002-09-01 23:20:45 +00001428** should be opened with wrFlag==1 even if they never really intend
1429** to write.
1430**
drh6446c4d2001-12-15 14:22:18 +00001431** No checking is done to make sure that page iTable really is the
1432** root page of a b-tree. If it is not, then the cursor acquired
1433** will not work correctly.
drh3aac2dd2004-04-26 14:10:20 +00001434**
1435** The comparison function must be logically the same for every cursor
1436** on a particular table. Changing the comparison function will result
1437** in incorrect operations. If the comparison function is NULL, a
1438** default comparison function is used. The comparison function is
1439** always ignored for INTKEY tables.
drha059ad02001-04-17 20:09:11 +00001440*/
drh3aac2dd2004-04-26 14:10:20 +00001441int sqlite3BtreeCursor(
1442 Btree *pBt, /* The btree */
1443 int iTable, /* Root page of table to open */
1444 int wrFlag, /* 1 to write. 0 read-only */
1445 int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
1446 void *pArg, /* First arg to xCompare() */
1447 BtCursor **ppCur /* Write new cursor here */
1448){
drha059ad02001-04-17 20:09:11 +00001449 int rc;
drhf74b8d92002-09-01 23:20:45 +00001450 BtCursor *pCur, *pRing;
drhecdc7532001-09-23 02:35:53 +00001451
drha0c9a112004-03-10 13:42:37 +00001452 if( pBt->readOnly && wrFlag ){
1453 *ppCur = 0;
1454 return SQLITE_READONLY;
1455 }
drh4b70f112004-05-02 21:12:19 +00001456 if( pBt->pPage1==0 ){
drha059ad02001-04-17 20:09:11 +00001457 rc = lockBtree(pBt);
1458 if( rc!=SQLITE_OK ){
1459 *ppCur = 0;
1460 return rc;
1461 }
1462 }
1463 pCur = sqliteMalloc( sizeof(*pCur) );
1464 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +00001465 rc = SQLITE_NOMEM;
1466 goto create_cursor_exception;
1467 }
drh8b2f49b2001-06-08 00:21:52 +00001468 pCur->pgnoRoot = (Pgno)iTable;
drh24cd67e2004-05-10 16:18:47 +00001469 if( iTable==1 && sqlite3pager_pagecount(pBt->pPager)==0 ){
1470 rc = SQLITE_EMPTY;
1471 goto create_cursor_exception;
1472 }
drhde647132004-05-07 17:57:49 +00001473 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
drhbd03cae2001-06-02 02:40:57 +00001474 if( rc!=SQLITE_OK ){
1475 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00001476 }
drh3aac2dd2004-04-26 14:10:20 +00001477 pCur->xCompare = xCmp ? xCmp : dfltCompare;
1478 pCur->pArg = pArg;
drh14acc042001-06-10 19:56:58 +00001479 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +00001480 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +00001481 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00001482 pCur->info.nSize = 0;
drha059ad02001-04-17 20:09:11 +00001483 pCur->pNext = pBt->pCursor;
1484 if( pCur->pNext ){
1485 pCur->pNext->pPrev = pCur;
1486 }
drh14acc042001-06-10 19:56:58 +00001487 pCur->pPrev = 0;
drhf74b8d92002-09-01 23:20:45 +00001488 pRing = pBt->pCursor;
1489 while( pRing && pRing->pgnoRoot!=pCur->pgnoRoot ){ pRing = pRing->pNext; }
1490 if( pRing ){
1491 pCur->pShared = pRing->pShared;
1492 pRing->pShared = pCur;
1493 }else{
1494 pCur->pShared = pCur;
1495 }
drha059ad02001-04-17 20:09:11 +00001496 pBt->pCursor = pCur;
drhc39e0002004-05-07 23:50:57 +00001497 pCur->isValid = 0;
1498 pCur->status = SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00001499 *ppCur = pCur;
1500 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00001501
1502create_cursor_exception:
1503 *ppCur = 0;
1504 if( pCur ){
drh3aac2dd2004-04-26 14:10:20 +00001505 releasePage(pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +00001506 sqliteFree(pCur);
1507 }
drh5e00f6c2001-09-13 13:46:56 +00001508 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00001509 return rc;
drha059ad02001-04-17 20:09:11 +00001510}
1511
drh7a224de2004-06-02 01:22:02 +00001512#if 0 /* Not Used */
drhd3d39e92004-05-20 22:16:29 +00001513/*
1514** Change the value of the comparison function used by a cursor.
1515*/
danielk1977bf3b7212004-05-18 10:06:24 +00001516void sqlite3BtreeSetCompare(
drhd3d39e92004-05-20 22:16:29 +00001517 BtCursor *pCur, /* The cursor to whose comparison function is changed */
1518 int(*xCmp)(void*,int,const void*,int,const void*), /* New comparison func */
1519 void *pArg /* First argument to xCmp() */
danielk1977bf3b7212004-05-18 10:06:24 +00001520){
1521 pCur->xCompare = xCmp ? xCmp : dfltCompare;
1522 pCur->pArg = pArg;
1523}
drh7a224de2004-06-02 01:22:02 +00001524#endif
danielk1977bf3b7212004-05-18 10:06:24 +00001525
drha059ad02001-04-17 20:09:11 +00001526/*
drh5e00f6c2001-09-13 13:46:56 +00001527** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00001528** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00001529*/
drh3aac2dd2004-04-26 14:10:20 +00001530int sqlite3BtreeCloseCursor(BtCursor *pCur){
drha059ad02001-04-17 20:09:11 +00001531 Btree *pBt = pCur->pBt;
drha059ad02001-04-17 20:09:11 +00001532 if( pCur->pPrev ){
1533 pCur->pPrev->pNext = pCur->pNext;
1534 }else{
1535 pBt->pCursor = pCur->pNext;
1536 }
1537 if( pCur->pNext ){
1538 pCur->pNext->pPrev = pCur->pPrev;
1539 }
drh3aac2dd2004-04-26 14:10:20 +00001540 releasePage(pCur->pPage);
drhf74b8d92002-09-01 23:20:45 +00001541 if( pCur->pShared!=pCur ){
1542 BtCursor *pRing = pCur->pShared;
1543 while( pRing->pShared!=pCur ){ pRing = pRing->pShared; }
1544 pRing->pShared = pCur->pShared;
1545 }
drh5e00f6c2001-09-13 13:46:56 +00001546 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001547 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +00001548 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00001549}
1550
drh7e3b0a02001-04-28 16:52:40 +00001551/*
drh5e2f8b92001-05-28 00:41:15 +00001552** Make a temporary cursor by filling in the fields of pTempCur.
1553** The temporary cursor is not on the cursor list for the Btree.
1554*/
drh14acc042001-06-10 19:56:58 +00001555static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00001556 memcpy(pTempCur, pCur, sizeof(*pCur));
1557 pTempCur->pNext = 0;
1558 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00001559 if( pTempCur->pPage ){
drha34b6762004-05-07 13:30:42 +00001560 sqlite3pager_ref(pTempCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00001561 }
drh5e2f8b92001-05-28 00:41:15 +00001562}
1563
1564/*
drhbd03cae2001-06-02 02:40:57 +00001565** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00001566** function above.
1567*/
drh14acc042001-06-10 19:56:58 +00001568static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00001569 if( pCur->pPage ){
drha34b6762004-05-07 13:30:42 +00001570 sqlite3pager_unref(pCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00001571 }
drh5e2f8b92001-05-28 00:41:15 +00001572}
1573
1574/*
drh9188b382004-05-14 21:12:22 +00001575** Make sure the BtCursor.info field of the given cursor is valid.
drhab01f612004-05-22 02:55:23 +00001576** If it is not already valid, call parseCell() to fill it in.
1577**
1578** BtCursor.info is a cache of the information in the current cell.
1579** Using this cache reduces the number of calls to parseCell().
drh9188b382004-05-14 21:12:22 +00001580*/
1581static void getCellInfo(BtCursor *pCur){
drh271efa52004-05-30 19:19:05 +00001582 if( pCur->info.nSize==0 ){
drh3a41a3f2004-05-30 02:14:17 +00001583 parseCell(pCur->pPage, pCur->idx, &pCur->info);
drh9188b382004-05-14 21:12:22 +00001584 }else{
1585#ifndef NDEBUG
1586 CellInfo info;
drh3a41a3f2004-05-30 02:14:17 +00001587 parseCell(pCur->pPage, pCur->idx, &info);
drh9188b382004-05-14 21:12:22 +00001588 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
1589#endif
1590 }
1591}
1592
1593/*
drh3aac2dd2004-04-26 14:10:20 +00001594** Set *pSize to the size of the buffer needed to hold the value of
1595** the key for the current entry. If the cursor is not pointing
1596** to a valid entry, *pSize is set to 0.
1597**
drh4b70f112004-05-02 21:12:19 +00001598** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00001599** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00001600*/
drh4a1c3802004-05-12 15:15:47 +00001601int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drhc39e0002004-05-07 23:50:57 +00001602 if( !pCur->isValid ){
drh72f82862001-05-24 21:06:34 +00001603 *pSize = 0;
1604 }else{
drh9188b382004-05-14 21:12:22 +00001605 getCellInfo(pCur);
1606 *pSize = pCur->info.nKey;
drh72f82862001-05-24 21:06:34 +00001607 }
1608 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00001609}
drh2af926b2001-05-15 00:39:25 +00001610
drh72f82862001-05-24 21:06:34 +00001611/*
drh0e1c19e2004-05-11 00:58:56 +00001612** Set *pSize to the number of bytes of data in the entry the
1613** cursor currently points to. Always return SQLITE_OK.
1614** Failure is not possible. If the cursor is not currently
1615** pointing to an entry (which can happen, for example, if
1616** the database is empty) then *pSize is set to 0.
1617*/
1618int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drh0e1c19e2004-05-11 00:58:56 +00001619 if( !pCur->isValid ){
danielk197796fc5fe2004-05-13 11:34:16 +00001620 /* Not pointing at a valid entry - set *pSize to 0. */
drh0e1c19e2004-05-11 00:58:56 +00001621 *pSize = 0;
1622 }else{
drh9188b382004-05-14 21:12:22 +00001623 getCellInfo(pCur);
1624 *pSize = pCur->info.nData;
drh0e1c19e2004-05-11 00:58:56 +00001625 }
1626 return SQLITE_OK;
1627}
1628
1629/*
drh72f82862001-05-24 21:06:34 +00001630** Read payload information from the entry that the pCur cursor is
1631** pointing to. Begin reading the payload at "offset" and read
1632** a total of "amt" bytes. Put the result in zBuf.
1633**
1634** This routine does not make a distinction between key and data.
drhab01f612004-05-22 02:55:23 +00001635** It just reads bytes from the payload area. Data might appear
1636** on the main page or be scattered out on multiple overflow pages.
drh72f82862001-05-24 21:06:34 +00001637*/
drh3aac2dd2004-04-26 14:10:20 +00001638static int getPayload(
1639 BtCursor *pCur, /* Cursor pointing to entry to read from */
1640 int offset, /* Begin reading this far into payload */
1641 int amt, /* Read this many bytes */
1642 unsigned char *pBuf, /* Write the bytes into this buffer */
1643 int skipKey /* offset begins at data if this is true */
1644){
1645 unsigned char *aPayload;
drh2af926b2001-05-15 00:39:25 +00001646 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +00001647 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001648 MemPage *pPage;
1649 Btree *pBt;
drh6f11bef2004-05-13 01:12:56 +00001650 int ovflSize;
drhfa1a98a2004-05-14 19:08:17 +00001651 u32 nKey;
drh3aac2dd2004-04-26 14:10:20 +00001652
drh72f82862001-05-24 21:06:34 +00001653 assert( pCur!=0 && pCur->pPage!=0 );
drhc39e0002004-05-07 23:50:57 +00001654 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00001655 pBt = pCur->pBt;
1656 pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00001657 pageIntegrity(pPage);
drh3aac2dd2004-04-26 14:10:20 +00001658 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00001659 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00001660 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00001661 aPayload += pCur->info.nHeader;
drh3aac2dd2004-04-26 14:10:20 +00001662 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00001663 nKey = 0;
1664 }else{
1665 nKey = pCur->info.nKey;
drh3aac2dd2004-04-26 14:10:20 +00001666 }
1667 assert( offset>=0 );
1668 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00001669 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00001670 }
drhfa1a98a2004-05-14 19:08:17 +00001671 if( offset+amt > nKey+pCur->info.nData ){
drha34b6762004-05-07 13:30:42 +00001672 return SQLITE_ERROR;
drh3aac2dd2004-04-26 14:10:20 +00001673 }
drhfa1a98a2004-05-14 19:08:17 +00001674 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00001675 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00001676 if( a+offset>pCur->info.nLocal ){
1677 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00001678 }
drha34b6762004-05-07 13:30:42 +00001679 memcpy(pBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +00001680 if( a==amt ){
1681 return SQLITE_OK;
1682 }
drh2aa679f2001-06-25 02:11:07 +00001683 offset = 0;
drha34b6762004-05-07 13:30:42 +00001684 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00001685 amt -= a;
drhdd793422001-06-28 01:54:48 +00001686 }else{
drhfa1a98a2004-05-14 19:08:17 +00001687 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00001688 }
1689 if( amt>0 ){
drhfa1a98a2004-05-14 19:08:17 +00001690 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
drh2af926b2001-05-15 00:39:25 +00001691 }
drhb6f41482004-05-14 01:58:11 +00001692 ovflSize = pBt->usableSize - 4;
drh2af926b2001-05-15 00:39:25 +00001693 while( amt>0 && nextPage ){
drha34b6762004-05-07 13:30:42 +00001694 rc = sqlite3pager_get(pBt->pPager, nextPage, (void**)&aPayload);
drh2af926b2001-05-15 00:39:25 +00001695 if( rc!=0 ){
1696 return rc;
1697 }
drha34b6762004-05-07 13:30:42 +00001698 nextPage = get4byte(aPayload);
drh3aac2dd2004-04-26 14:10:20 +00001699 if( offset<ovflSize ){
drh2af926b2001-05-15 00:39:25 +00001700 int a = amt;
drh3aac2dd2004-04-26 14:10:20 +00001701 if( a + offset > ovflSize ){
1702 a = ovflSize - offset;
drh2af926b2001-05-15 00:39:25 +00001703 }
drh9b171272004-05-08 02:03:22 +00001704 memcpy(pBuf, &aPayload[offset+4], a);
drh2aa679f2001-06-25 02:11:07 +00001705 offset = 0;
drh2af926b2001-05-15 00:39:25 +00001706 amt -= a;
drha34b6762004-05-07 13:30:42 +00001707 pBuf += a;
drh2aa679f2001-06-25 02:11:07 +00001708 }else{
drh3aac2dd2004-04-26 14:10:20 +00001709 offset -= ovflSize;
drh2af926b2001-05-15 00:39:25 +00001710 }
drha34b6762004-05-07 13:30:42 +00001711 sqlite3pager_unref(aPayload);
drh2af926b2001-05-15 00:39:25 +00001712 }
drha7fcb052001-12-14 15:09:55 +00001713 if( amt>0 ){
1714 return SQLITE_CORRUPT;
1715 }
1716 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00001717}
1718
drh72f82862001-05-24 21:06:34 +00001719/*
drh3aac2dd2004-04-26 14:10:20 +00001720** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00001721** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00001722** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00001723**
drh3aac2dd2004-04-26 14:10:20 +00001724** Return SQLITE_OK on success or an error code if anything goes
1725** wrong. An error is returned if "offset+amt" is larger than
1726** the available payload.
drh72f82862001-05-24 21:06:34 +00001727*/
drha34b6762004-05-07 13:30:42 +00001728int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drh8c1238a2003-01-02 14:43:55 +00001729 assert( amt>=0 );
1730 assert( offset>=0 );
drhc39e0002004-05-07 23:50:57 +00001731 if( pCur->isValid==0 ){
1732 return pCur->status;
drh3aac2dd2004-04-26 14:10:20 +00001733 }
drhc39e0002004-05-07 23:50:57 +00001734 assert( pCur->pPage!=0 );
1735 assert( pCur->pPage->intKey==0 );
1736 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh3aac2dd2004-04-26 14:10:20 +00001737 return getPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
1738}
1739
1740/*
drh3aac2dd2004-04-26 14:10:20 +00001741** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00001742** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00001743** begins at "offset".
1744**
1745** Return SQLITE_OK on success or an error code if anything goes
1746** wrong. An error is returned if "offset+amt" is larger than
1747** the available payload.
drh72f82862001-05-24 21:06:34 +00001748*/
drh3aac2dd2004-04-26 14:10:20 +00001749int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhc39e0002004-05-07 23:50:57 +00001750 if( !pCur->isValid ){
1751 return pCur->status ? pCur->status : SQLITE_INTERNAL;
1752 }
drh8c1238a2003-01-02 14:43:55 +00001753 assert( amt>=0 );
1754 assert( offset>=0 );
1755 assert( pCur->pPage!=0 );
drhc39e0002004-05-07 23:50:57 +00001756 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh3aac2dd2004-04-26 14:10:20 +00001757 return getPayload(pCur, offset, amt, pBuf, 1);
drh2af926b2001-05-15 00:39:25 +00001758}
1759
drh72f82862001-05-24 21:06:34 +00001760/*
drh0e1c19e2004-05-11 00:58:56 +00001761** Return a pointer to payload information from the entry that the
1762** pCur cursor is pointing to. The pointer is to the beginning of
1763** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00001764** skipKey==1. The number of bytes of available key/data is written
1765** into *pAmt. If *pAmt==0, then the value returned will not be
1766** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00001767**
1768** This routine is an optimization. It is common for the entire key
1769** and data to fit on the local page and for there to be no overflow
1770** pages. When that is so, this routine can be used to access the
1771** key and data without making a copy. If the key and/or data spills
1772** onto overflow pages, then getPayload() must be used to reassembly
1773** the key/data and copy it into a preallocated buffer.
1774**
1775** The pointer returned by this routine looks directly into the cached
1776** page of the database. The data might change or move the next time
1777** any btree routine is called.
1778*/
1779static const unsigned char *fetchPayload(
1780 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00001781 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00001782 int skipKey /* read beginning at data if this is true */
1783){
1784 unsigned char *aPayload;
1785 MemPage *pPage;
1786 Btree *pBt;
drhfa1a98a2004-05-14 19:08:17 +00001787 u32 nKey;
1788 int nLocal;
drh0e1c19e2004-05-11 00:58:56 +00001789
1790 assert( pCur!=0 && pCur->pPage!=0 );
1791 assert( pCur->isValid );
1792 pBt = pCur->pBt;
1793 pPage = pCur->pPage;
1794 pageIntegrity(pPage);
1795 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00001796 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00001797 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00001798 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00001799 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00001800 nKey = 0;
1801 }else{
1802 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00001803 }
drh0e1c19e2004-05-11 00:58:56 +00001804 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00001805 aPayload += nKey;
1806 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00001807 }else{
drhfa1a98a2004-05-14 19:08:17 +00001808 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00001809 if( nLocal>nKey ){
1810 nLocal = nKey;
1811 }
drh0e1c19e2004-05-11 00:58:56 +00001812 }
drhe51c44f2004-05-30 20:46:09 +00001813 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00001814 return aPayload;
1815}
1816
1817
1818/*
drhe51c44f2004-05-30 20:46:09 +00001819** For the entry that cursor pCur is point to, return as
1820** many bytes of the key or data as are available on the local
1821** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00001822**
1823** The pointer returned is ephemeral. The key/data may move
1824** or be destroyed on the next call to any Btree routine.
1825**
1826** These routines is used to get quick access to key and data
1827** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00001828*/
drhe51c44f2004-05-30 20:46:09 +00001829const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
1830 return (const void*)fetchPayload(pCur, pAmt, 0);
drh0e1c19e2004-05-11 00:58:56 +00001831}
drhe51c44f2004-05-30 20:46:09 +00001832const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
1833 return (const void*)fetchPayload(pCur, pAmt, 1);
drh0e1c19e2004-05-11 00:58:56 +00001834}
1835
1836
1837/*
drh8178a752003-01-05 21:41:40 +00001838** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00001839** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00001840*/
drh3aac2dd2004-04-26 14:10:20 +00001841static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00001842 int rc;
1843 MemPage *pNewPage;
drh3aac2dd2004-04-26 14:10:20 +00001844 MemPage *pOldPage;
drh0d316a42002-08-11 20:10:47 +00001845 Btree *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00001846
drhc39e0002004-05-07 23:50:57 +00001847 assert( pCur->isValid );
drhde647132004-05-07 17:57:49 +00001848 rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00001849 if( rc ) return rc;
drhda200cc2004-05-09 11:51:38 +00001850 pageIntegrity(pNewPage);
drh428ae8c2003-01-04 16:48:09 +00001851 pNewPage->idxParent = pCur->idx;
drh3aac2dd2004-04-26 14:10:20 +00001852 pOldPage = pCur->pPage;
1853 pOldPage->idxShift = 0;
1854 releasePage(pOldPage);
drh72f82862001-05-24 21:06:34 +00001855 pCur->pPage = pNewPage;
1856 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00001857 pCur->info.nSize = 0;
drh4be295b2003-12-16 03:44:47 +00001858 if( pNewPage->nCell<1 ){
1859 return SQLITE_CORRUPT;
1860 }
drh72f82862001-05-24 21:06:34 +00001861 return SQLITE_OK;
1862}
1863
1864/*
drh8856d6a2004-04-29 14:42:46 +00001865** Return true if the page is the virtual root of its table.
1866**
1867** The virtual root page is the root page for most tables. But
1868** for the table rooted on page 1, sometime the real root page
1869** is empty except for the right-pointer. In such cases the
1870** virtual root page is the page that the right-pointer of page
1871** 1 is pointing to.
1872*/
1873static int isRootPage(MemPage *pPage){
1874 MemPage *pParent = pPage->pParent;
drhda200cc2004-05-09 11:51:38 +00001875 if( pParent==0 ) return 1;
1876 if( pParent->pgno>1 ) return 0;
1877 if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
drh8856d6a2004-04-29 14:42:46 +00001878 return 0;
1879}
1880
1881/*
drh5e2f8b92001-05-28 00:41:15 +00001882** Move the cursor up to the parent page.
1883**
1884** pCur->idx is set to the cell index that contains the pointer
1885** to the page we are coming from. If we are coming from the
1886** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00001887** the largest cell index.
drh72f82862001-05-24 21:06:34 +00001888*/
drh8178a752003-01-05 21:41:40 +00001889static void moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001890 Pgno oldPgno;
1891 MemPage *pParent;
drh8178a752003-01-05 21:41:40 +00001892 MemPage *pPage;
drh428ae8c2003-01-04 16:48:09 +00001893 int idxParent;
drh3aac2dd2004-04-26 14:10:20 +00001894
drhc39e0002004-05-07 23:50:57 +00001895 assert( pCur->isValid );
drh8178a752003-01-05 21:41:40 +00001896 pPage = pCur->pPage;
1897 assert( pPage!=0 );
drh8856d6a2004-04-29 14:42:46 +00001898 assert( !isRootPage(pPage) );
drhda200cc2004-05-09 11:51:38 +00001899 pageIntegrity(pPage);
drh8178a752003-01-05 21:41:40 +00001900 pParent = pPage->pParent;
1901 assert( pParent!=0 );
drhda200cc2004-05-09 11:51:38 +00001902 pageIntegrity(pParent);
drh8178a752003-01-05 21:41:40 +00001903 idxParent = pPage->idxParent;
drha34b6762004-05-07 13:30:42 +00001904 sqlite3pager_ref(pParent->aData);
drh3aac2dd2004-04-26 14:10:20 +00001905 oldPgno = pPage->pgno;
1906 releasePage(pPage);
drh72f82862001-05-24 21:06:34 +00001907 pCur->pPage = pParent;
drh271efa52004-05-30 19:19:05 +00001908 pCur->info.nSize = 0;
drh428ae8c2003-01-04 16:48:09 +00001909 assert( pParent->idxShift==0 );
drh43605152004-05-29 21:46:49 +00001910 pCur->idx = idxParent;
drh72f82862001-05-24 21:06:34 +00001911}
1912
1913/*
1914** Move the cursor to the root page
1915*/
drh5e2f8b92001-05-28 00:41:15 +00001916static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00001917 MemPage *pRoot;
drhbd03cae2001-06-02 02:40:57 +00001918 int rc;
drh0d316a42002-08-11 20:10:47 +00001919 Btree *pBt = pCur->pBt;
drhbd03cae2001-06-02 02:40:57 +00001920
drhde647132004-05-07 17:57:49 +00001921 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0);
drhc39e0002004-05-07 23:50:57 +00001922 if( rc ){
1923 pCur->isValid = 0;
1924 return rc;
1925 }
drh3aac2dd2004-04-26 14:10:20 +00001926 releasePage(pCur->pPage);
drhda200cc2004-05-09 11:51:38 +00001927 pageIntegrity(pRoot);
drh3aac2dd2004-04-26 14:10:20 +00001928 pCur->pPage = pRoot;
drh72f82862001-05-24 21:06:34 +00001929 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00001930 pCur->info.nSize = 0;
drh8856d6a2004-04-29 14:42:46 +00001931 if( pRoot->nCell==0 && !pRoot->leaf ){
1932 Pgno subpage;
1933 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00001934 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00001935 assert( subpage>0 );
drh3644f082004-05-10 18:45:09 +00001936 pCur->isValid = 1;
drh4b70f112004-05-02 21:12:19 +00001937 rc = moveToChild(pCur, subpage);
drh8856d6a2004-04-29 14:42:46 +00001938 }
drhc39e0002004-05-07 23:50:57 +00001939 pCur->isValid = pCur->pPage->nCell>0;
drh8856d6a2004-04-29 14:42:46 +00001940 return rc;
drh72f82862001-05-24 21:06:34 +00001941}
drh2af926b2001-05-15 00:39:25 +00001942
drh5e2f8b92001-05-28 00:41:15 +00001943/*
1944** Move the cursor down to the left-most leaf entry beneath the
1945** entry to which it is currently pointing.
1946*/
1947static int moveToLeftmost(BtCursor *pCur){
1948 Pgno pgno;
1949 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001950 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00001951
drhc39e0002004-05-07 23:50:57 +00001952 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00001953 while( !(pPage = pCur->pPage)->leaf ){
drha34b6762004-05-07 13:30:42 +00001954 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00001955 pgno = get4byte(findCell(pPage, pCur->idx));
drh8178a752003-01-05 21:41:40 +00001956 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00001957 if( rc ) return rc;
1958 }
1959 return SQLITE_OK;
1960}
1961
drh2dcc9aa2002-12-04 13:40:25 +00001962/*
1963** Move the cursor down to the right-most leaf entry beneath the
1964** page to which it is currently pointing. Notice the difference
1965** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
1966** finds the left-most entry beneath the *entry* whereas moveToRightmost()
1967** finds the right-most entry beneath the *page*.
1968*/
1969static int moveToRightmost(BtCursor *pCur){
1970 Pgno pgno;
1971 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001972 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00001973
drhc39e0002004-05-07 23:50:57 +00001974 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00001975 while( !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00001976 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh3aac2dd2004-04-26 14:10:20 +00001977 pCur->idx = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00001978 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00001979 if( rc ) return rc;
1980 }
drh3aac2dd2004-04-26 14:10:20 +00001981 pCur->idx = pPage->nCell - 1;
drh271efa52004-05-30 19:19:05 +00001982 pCur->info.nSize = 0;
drh2dcc9aa2002-12-04 13:40:25 +00001983 return SQLITE_OK;
1984}
1985
drh5e00f6c2001-09-13 13:46:56 +00001986/* Move the cursor to the first entry in the table. Return SQLITE_OK
1987** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00001988** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00001989*/
drh3aac2dd2004-04-26 14:10:20 +00001990int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00001991 int rc;
drhc39e0002004-05-07 23:50:57 +00001992 if( pCur->status ){
1993 return pCur->status;
1994 }
drh5e00f6c2001-09-13 13:46:56 +00001995 rc = moveToRoot(pCur);
1996 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00001997 if( pCur->isValid==0 ){
1998 assert( pCur->pPage->nCell==0 );
drh5e00f6c2001-09-13 13:46:56 +00001999 *pRes = 1;
2000 return SQLITE_OK;
2001 }
drhc39e0002004-05-07 23:50:57 +00002002 assert( pCur->pPage->nCell>0 );
drh5e00f6c2001-09-13 13:46:56 +00002003 *pRes = 0;
2004 rc = moveToLeftmost(pCur);
2005 return rc;
2006}
drh5e2f8b92001-05-28 00:41:15 +00002007
drh9562b552002-02-19 15:00:07 +00002008/* Move the cursor to the last entry in the table. Return SQLITE_OK
2009** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00002010** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00002011*/
drh3aac2dd2004-04-26 14:10:20 +00002012int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00002013 int rc;
drhc39e0002004-05-07 23:50:57 +00002014 if( pCur->status ){
2015 return pCur->status;
2016 }
drh9562b552002-02-19 15:00:07 +00002017 rc = moveToRoot(pCur);
2018 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00002019 if( pCur->isValid==0 ){
2020 assert( pCur->pPage->nCell==0 );
drh9562b552002-02-19 15:00:07 +00002021 *pRes = 1;
2022 return SQLITE_OK;
2023 }
drhc39e0002004-05-07 23:50:57 +00002024 assert( pCur->isValid );
drh9562b552002-02-19 15:00:07 +00002025 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002026 rc = moveToRightmost(pCur);
drh9562b552002-02-19 15:00:07 +00002027 return rc;
2028}
2029
drh3aac2dd2004-04-26 14:10:20 +00002030/* Move the cursor so that it points to an entry near pKey/nKey.
drh72f82862001-05-24 21:06:34 +00002031** Return a success code.
2032**
drh3aac2dd2004-04-26 14:10:20 +00002033** For INTKEY tables, only the nKey parameter is used. pKey is
2034** ignored. For other tables, nKey is the number of bytes of data
2035** in nKey. The comparison function specified when the cursor was
2036** created is used to compare keys.
2037**
drh5e2f8b92001-05-28 00:41:15 +00002038** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00002039** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00002040** were present. The cursor might point to an entry that comes
2041** before or after the key.
2042**
drhbd03cae2001-06-02 02:40:57 +00002043** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00002044** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00002045** this value is as follows:
2046**
2047** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00002048** is smaller than pKey or if the table is empty
2049** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00002050**
2051** *pRes==0 The cursor is left pointing at an entry that
2052** exactly matches pKey.
2053**
2054** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00002055** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00002056*/
drh4a1c3802004-05-12 15:15:47 +00002057int sqlite3BtreeMoveto(BtCursor *pCur, const void *pKey, i64 nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00002058 int rc;
drhc39e0002004-05-07 23:50:57 +00002059
2060 if( pCur->status ){
2061 return pCur->status;
2062 }
drh5e2f8b92001-05-28 00:41:15 +00002063 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00002064 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00002065 assert( pCur->pPage );
2066 assert( pCur->pPage->isInit );
2067 if( pCur->isValid==0 ){
drhf328bc82004-05-10 23:29:49 +00002068 *pRes = -1;
drhc39e0002004-05-07 23:50:57 +00002069 assert( pCur->pPage->nCell==0 );
2070 return SQLITE_OK;
2071 }
drh72f82862001-05-24 21:06:34 +00002072 for(;;){
2073 int lwr, upr;
2074 Pgno chldPg;
2075 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00002076 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00002077 lwr = 0;
2078 upr = pPage->nCell-1;
drhda200cc2004-05-09 11:51:38 +00002079 pageIntegrity(pPage);
drh72f82862001-05-24 21:06:34 +00002080 while( lwr<=upr ){
danielk197713adf8a2004-06-03 16:08:41 +00002081 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00002082 i64 nCellKey;
drh72f82862001-05-24 21:06:34 +00002083 pCur->idx = (lwr+upr)/2;
drh271efa52004-05-30 19:19:05 +00002084 pCur->info.nSize = 0;
drhde647132004-05-07 17:57:49 +00002085 sqlite3BtreeKeySize(pCur, &nCellKey);
drh3aac2dd2004-04-26 14:10:20 +00002086 if( pPage->intKey ){
2087 if( nCellKey<nKey ){
2088 c = -1;
2089 }else if( nCellKey>nKey ){
2090 c = +1;
2091 }else{
2092 c = 0;
2093 }
drh3aac2dd2004-04-26 14:10:20 +00002094 }else{
drhe51c44f2004-05-30 20:46:09 +00002095 int available;
danielk197713adf8a2004-06-03 16:08:41 +00002096 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drhe51c44f2004-05-30 20:46:09 +00002097 if( available>=nCellKey ){
2098 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
2099 }else{
2100 pCellKey = sqliteMallocRaw( nCellKey );
2101 if( pCellKey==0 ) return SQLITE_NOMEM;
danielk197713adf8a2004-06-03 16:08:41 +00002102 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
drhe51c44f2004-05-30 20:46:09 +00002103 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
2104 sqliteFree(pCellKey);
2105 if( rc ) return rc;
2106 }
drh3aac2dd2004-04-26 14:10:20 +00002107 }
drh72f82862001-05-24 21:06:34 +00002108 if( c==0 ){
drh8b18dd42004-05-12 19:18:15 +00002109 if( pPage->leafData && !pPage->leaf ){
drhfc70e6f2004-05-12 21:11:27 +00002110 lwr = pCur->idx;
2111 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00002112 break;
2113 }else{
drh8b18dd42004-05-12 19:18:15 +00002114 if( pRes ) *pRes = 0;
2115 return SQLITE_OK;
2116 }
drh72f82862001-05-24 21:06:34 +00002117 }
2118 if( c<0 ){
2119 lwr = pCur->idx+1;
2120 }else{
2121 upr = pCur->idx-1;
2122 }
2123 }
2124 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00002125 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00002126 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00002127 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00002128 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00002129 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00002130 }else{
drh43605152004-05-29 21:46:49 +00002131 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00002132 }
2133 if( chldPg==0 ){
drhc39e0002004-05-07 23:50:57 +00002134 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00002135 if( pRes ) *pRes = c;
2136 return SQLITE_OK;
2137 }
drh428ae8c2003-01-04 16:48:09 +00002138 pCur->idx = lwr;
drh271efa52004-05-30 19:19:05 +00002139 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00002140 rc = moveToChild(pCur, chldPg);
drhc39e0002004-05-07 23:50:57 +00002141 if( rc ){
2142 return rc;
2143 }
drh72f82862001-05-24 21:06:34 +00002144 }
drhbd03cae2001-06-02 02:40:57 +00002145 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00002146}
2147
2148/*
drhc39e0002004-05-07 23:50:57 +00002149** Return TRUE if the cursor is not pointing at an entry of the table.
2150**
2151** TRUE will be returned after a call to sqlite3BtreeNext() moves
2152** past the last entry in the table or sqlite3BtreePrev() moves past
2153** the first entry. TRUE is also returned if the table is empty.
2154*/
2155int sqlite3BtreeEof(BtCursor *pCur){
2156 return pCur->isValid==0;
2157}
2158
2159/*
drhbd03cae2001-06-02 02:40:57 +00002160** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00002161** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00002162** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00002163** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00002164*/
drh3aac2dd2004-04-26 14:10:20 +00002165int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00002166 int rc;
drh8178a752003-01-05 21:41:40 +00002167 MemPage *pPage = pCur->pPage;
drh8b18dd42004-05-12 19:18:15 +00002168
drh8c1238a2003-01-02 14:43:55 +00002169 assert( pRes!=0 );
drhc39e0002004-05-07 23:50:57 +00002170 if( pCur->isValid==0 ){
drh8c1238a2003-01-02 14:43:55 +00002171 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00002172 return SQLITE_OK;
drhecdc7532001-09-23 02:35:53 +00002173 }
drh8178a752003-01-05 21:41:40 +00002174 assert( pPage->isInit );
drh8178a752003-01-05 21:41:40 +00002175 assert( pCur->idx<pPage->nCell );
drh72f82862001-05-24 21:06:34 +00002176 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00002177 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00002178 if( pCur->idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00002179 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00002180 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00002181 if( rc ) return rc;
2182 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00002183 *pRes = 0;
2184 return rc;
drh72f82862001-05-24 21:06:34 +00002185 }
drh5e2f8b92001-05-28 00:41:15 +00002186 do{
drh8856d6a2004-04-29 14:42:46 +00002187 if( isRootPage(pPage) ){
drh8c1238a2003-01-02 14:43:55 +00002188 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00002189 pCur->isValid = 0;
drh5e2f8b92001-05-28 00:41:15 +00002190 return SQLITE_OK;
2191 }
drh8178a752003-01-05 21:41:40 +00002192 moveToParent(pCur);
2193 pPage = pCur->pPage;
2194 }while( pCur->idx>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00002195 *pRes = 0;
drh8b18dd42004-05-12 19:18:15 +00002196 if( pPage->leafData ){
2197 rc = sqlite3BtreeNext(pCur, pRes);
2198 }else{
2199 rc = SQLITE_OK;
2200 }
2201 return rc;
drh8178a752003-01-05 21:41:40 +00002202 }
2203 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00002204 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00002205 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00002206 }
drh5e2f8b92001-05-28 00:41:15 +00002207 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00002208 return rc;
drh72f82862001-05-24 21:06:34 +00002209}
2210
drh3b7511c2001-05-26 13:15:44 +00002211/*
drh2dcc9aa2002-12-04 13:40:25 +00002212** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00002213** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00002214** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00002215** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00002216*/
drh3aac2dd2004-04-26 14:10:20 +00002217int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00002218 int rc;
2219 Pgno pgno;
drh8178a752003-01-05 21:41:40 +00002220 MemPage *pPage;
drhc39e0002004-05-07 23:50:57 +00002221 if( pCur->isValid==0 ){
2222 *pRes = 1;
2223 return SQLITE_OK;
2224 }
drh8178a752003-01-05 21:41:40 +00002225 pPage = pCur->pPage;
drh8178a752003-01-05 21:41:40 +00002226 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00002227 assert( pCur->idx>=0 );
drha34b6762004-05-07 13:30:42 +00002228 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00002229 pgno = get4byte( findCell(pPage, pCur->idx) );
drh8178a752003-01-05 21:41:40 +00002230 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00002231 if( rc ) return rc;
2232 rc = moveToRightmost(pCur);
2233 }else{
2234 while( pCur->idx==0 ){
drh8856d6a2004-04-29 14:42:46 +00002235 if( isRootPage(pPage) ){
drhc39e0002004-05-07 23:50:57 +00002236 pCur->isValid = 0;
2237 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00002238 return SQLITE_OK;
2239 }
drh8178a752003-01-05 21:41:40 +00002240 moveToParent(pCur);
2241 pPage = pCur->pPage;
drh2dcc9aa2002-12-04 13:40:25 +00002242 }
2243 pCur->idx--;
drh271efa52004-05-30 19:19:05 +00002244 pCur->info.nSize = 0;
drh8b18dd42004-05-12 19:18:15 +00002245 if( pPage->leafData ){
2246 rc = sqlite3BtreePrevious(pCur, pRes);
2247 }else{
2248 rc = SQLITE_OK;
2249 }
drh2dcc9aa2002-12-04 13:40:25 +00002250 }
drh8178a752003-01-05 21:41:40 +00002251 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002252 return rc;
2253}
2254
2255/*
drh3a4c1412004-05-09 20:40:11 +00002256** The TRACE macro will print high-level status information about the
2257** btree operation when the global variable sqlite3_btree_trace is
2258** enabled.
2259*/
2260#if SQLITE_TEST
2261# define TRACE(X) if( sqlite3_btree_trace ){ printf X; fflush(stdout); }
2262#else
2263# define TRACE(X)
2264#endif
2265int sqlite3_btree_trace=0; /* True to enable tracing */
2266
2267/*
drh3b7511c2001-05-26 13:15:44 +00002268** Allocate a new page from the database file.
2269**
drha34b6762004-05-07 13:30:42 +00002270** The new page is marked as dirty. (In other words, sqlite3pager_write()
drh3b7511c2001-05-26 13:15:44 +00002271** has already been called on the new page.) The new page has also
2272** been referenced and the calling routine is responsible for calling
drha34b6762004-05-07 13:30:42 +00002273** sqlite3pager_unref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00002274**
2275** SQLITE_OK is returned on success. Any other return value indicates
2276** an error. *ppPage and *pPgno are undefined in the event of an error.
drha34b6762004-05-07 13:30:42 +00002277** Do not invoke sqlite3pager_unref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00002278**
drh199e3cf2002-07-18 11:01:47 +00002279** If the "nearby" parameter is not 0, then a (feeble) effort is made to
2280** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00002281** attempt to keep related pages close to each other in the database file,
2282** which in turn can make database access faster.
drh3b7511c2001-05-26 13:15:44 +00002283*/
drh199e3cf2002-07-18 11:01:47 +00002284static int allocatePage(Btree *pBt, MemPage **ppPage, Pgno *pPgno, Pgno nearby){
drh3aac2dd2004-04-26 14:10:20 +00002285 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00002286 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002287 int n; /* Number of pages on the freelist */
2288 int k; /* Number of leaves on the trunk of the freelist */
drh30e58752002-03-02 20:41:57 +00002289
drh3aac2dd2004-04-26 14:10:20 +00002290 pPage1 = pBt->pPage1;
2291 n = get4byte(&pPage1->aData[36]);
2292 if( n>0 ){
drh91025292004-05-03 19:49:32 +00002293 /* There are pages on the freelist. Reuse one of those pages. */
drh3aac2dd2004-04-26 14:10:20 +00002294 MemPage *pTrunk;
drha34b6762004-05-07 13:30:42 +00002295 rc = sqlite3pager_write(pPage1->aData);
drh3b7511c2001-05-26 13:15:44 +00002296 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00002297 put4byte(&pPage1->aData[36], n-1);
2298 rc = getPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk);
drh3b7511c2001-05-26 13:15:44 +00002299 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00002300 rc = sqlite3pager_write(pTrunk->aData);
drh3b7511c2001-05-26 13:15:44 +00002301 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00002302 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00002303 return rc;
2304 }
drh3aac2dd2004-04-26 14:10:20 +00002305 k = get4byte(&pTrunk->aData[4]);
2306 if( k==0 ){
2307 /* The trunk has no leaves. So extract the trunk page itself and
2308 ** use it as the newly allocated page */
drha34b6762004-05-07 13:30:42 +00002309 *pPgno = get4byte(&pPage1->aData[32]);
drh3aac2dd2004-04-26 14:10:20 +00002310 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
2311 *ppPage = pTrunk;
drh3a4c1412004-05-09 20:40:11 +00002312 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh30e58752002-03-02 20:41:57 +00002313 }else{
drh3aac2dd2004-04-26 14:10:20 +00002314 /* Extract a leaf from the trunk */
2315 int closest;
2316 unsigned char *aData = pTrunk->aData;
2317 if( nearby>0 ){
drhbea00b92002-07-08 10:59:50 +00002318 int i, dist;
2319 closest = 0;
drh3aac2dd2004-04-26 14:10:20 +00002320 dist = get4byte(&aData[8]) - nearby;
drhbea00b92002-07-08 10:59:50 +00002321 if( dist<0 ) dist = -dist;
drh3a4c1412004-05-09 20:40:11 +00002322 for(i=1; i<k; i++){
drh3aac2dd2004-04-26 14:10:20 +00002323 int d2 = get4byte(&aData[8+i*4]) - nearby;
drhbea00b92002-07-08 10:59:50 +00002324 if( d2<0 ) d2 = -d2;
2325 if( d2<dist ) closest = i;
2326 }
2327 }else{
2328 closest = 0;
2329 }
drha34b6762004-05-07 13:30:42 +00002330 *pPgno = get4byte(&aData[8+closest*4]);
drh3a4c1412004-05-09 20:40:11 +00002331 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d: %d more free pages\n",
2332 *pPgno, closest+1, k, pTrunk->pgno, n-1));
drh9b171272004-05-08 02:03:22 +00002333 if( closest<k-1 ){
2334 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
2335 }
drh3a4c1412004-05-09 20:40:11 +00002336 put4byte(&aData[4], k-1);
drh3aac2dd2004-04-26 14:10:20 +00002337 rc = getPage(pBt, *pPgno, ppPage);
2338 releasePage(pTrunk);
drh30e58752002-03-02 20:41:57 +00002339 if( rc==SQLITE_OK ){
drh9b171272004-05-08 02:03:22 +00002340 sqlite3pager_dont_rollback((*ppPage)->aData);
drha34b6762004-05-07 13:30:42 +00002341 rc = sqlite3pager_write((*ppPage)->aData);
drh30e58752002-03-02 20:41:57 +00002342 }
2343 }
drh3b7511c2001-05-26 13:15:44 +00002344 }else{
drh3aac2dd2004-04-26 14:10:20 +00002345 /* There are no pages on the freelist, so create a new page at the
2346 ** end of the file */
drha34b6762004-05-07 13:30:42 +00002347 *pPgno = sqlite3pager_pagecount(pBt->pPager) + 1;
drh3aac2dd2004-04-26 14:10:20 +00002348 rc = getPage(pBt, *pPgno, ppPage);
drh3b7511c2001-05-26 13:15:44 +00002349 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00002350 rc = sqlite3pager_write((*ppPage)->aData);
drh3a4c1412004-05-09 20:40:11 +00002351 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00002352 }
2353 return rc;
2354}
2355
2356/*
drh3aac2dd2004-04-26 14:10:20 +00002357** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00002358**
drha34b6762004-05-07 13:30:42 +00002359** sqlite3pager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00002360*/
drh3aac2dd2004-04-26 14:10:20 +00002361static int freePage(MemPage *pPage){
2362 Btree *pBt = pPage->pBt;
2363 MemPage *pPage1 = pBt->pPage1;
2364 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00002365
drh3aac2dd2004-04-26 14:10:20 +00002366 /* Prepare the page for freeing */
2367 assert( pPage->pgno>1 );
2368 pPage->isInit = 0;
2369 releasePage(pPage->pParent);
2370 pPage->pParent = 0;
2371
drha34b6762004-05-07 13:30:42 +00002372 /* Increment the free page count on pPage1 */
2373 rc = sqlite3pager_write(pPage1->aData);
drh3aac2dd2004-04-26 14:10:20 +00002374 if( rc ) return rc;
2375 n = get4byte(&pPage1->aData[36]);
2376 put4byte(&pPage1->aData[36], n+1);
2377
2378 if( n==0 ){
2379 /* This is the first free page */
drhda200cc2004-05-09 11:51:38 +00002380 rc = sqlite3pager_write(pPage->aData);
2381 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00002382 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00002383 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00002384 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00002385 }else{
2386 /* Other free pages already exist. Retrive the first trunk page
2387 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00002388 MemPage *pTrunk;
2389 rc = getPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk);
drh3b7511c2001-05-26 13:15:44 +00002390 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00002391 k = get4byte(&pTrunk->aData[4]);
drhb6f41482004-05-14 01:58:11 +00002392 if( k==pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00002393 /* The trunk is full. Turn the page being freed into a new
2394 ** trunk page with no leaves. */
drha34b6762004-05-07 13:30:42 +00002395 rc = sqlite3pager_write(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00002396 if( rc ) return rc;
2397 put4byte(pPage->aData, pTrunk->pgno);
2398 put4byte(&pPage->aData[4], 0);
2399 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00002400 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
2401 pPage->pgno, pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00002402 }else{
2403 /* Add the newly freed page as a leaf on the current trunk */
drha34b6762004-05-07 13:30:42 +00002404 rc = sqlite3pager_write(pTrunk->aData);
drh3aac2dd2004-04-26 14:10:20 +00002405 if( rc ) return rc;
2406 put4byte(&pTrunk->aData[4], k+1);
2407 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drha34b6762004-05-07 13:30:42 +00002408 sqlite3pager_dont_write(pBt->pPager, pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00002409 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00002410 }
2411 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00002412 }
drh3b7511c2001-05-26 13:15:44 +00002413 return rc;
2414}
2415
2416/*
drh3aac2dd2004-04-26 14:10:20 +00002417** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00002418*/
drh3aac2dd2004-04-26 14:10:20 +00002419static int clearCell(MemPage *pPage, unsigned char *pCell){
2420 Btree *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00002421 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00002422 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00002423 int rc;
drh3b7511c2001-05-26 13:15:44 +00002424
drh43605152004-05-29 21:46:49 +00002425 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00002426 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00002427 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00002428 }
drh6f11bef2004-05-13 01:12:56 +00002429 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh3aac2dd2004-04-26 14:10:20 +00002430 while( ovflPgno!=0 ){
2431 MemPage *pOvfl;
2432 rc = getPage(pBt, ovflPgno, &pOvfl);
drh3b7511c2001-05-26 13:15:44 +00002433 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00002434 ovflPgno = get4byte(pOvfl->aData);
drha34b6762004-05-07 13:30:42 +00002435 rc = freePage(pOvfl);
drhbd03cae2001-06-02 02:40:57 +00002436 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00002437 sqlite3pager_unref(pOvfl->aData);
drh3b7511c2001-05-26 13:15:44 +00002438 }
drh5e2f8b92001-05-28 00:41:15 +00002439 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00002440}
2441
2442/*
drh91025292004-05-03 19:49:32 +00002443** Create the byte sequence used to represent a cell on page pPage
2444** and write that byte sequence into pCell[]. Overflow pages are
2445** allocated and filled in as necessary. The calling procedure
2446** is responsible for making sure sufficient space has been allocated
2447** for pCell[].
2448**
2449** Note that pCell does not necessary need to point to the pPage->aData
2450** area. pCell might point to some temporary storage. The cell will
2451** be constructed in this temporary area then copied into pPage->aData
2452** later.
drh3b7511c2001-05-26 13:15:44 +00002453*/
2454static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00002455 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00002456 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00002457 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00002458 const void *pData,int nData, /* The data */
2459 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00002460){
drh3b7511c2001-05-26 13:15:44 +00002461 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00002462 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00002463 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00002464 int spaceLeft;
2465 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00002466 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00002467 unsigned char *pPrior;
2468 unsigned char *pPayload;
2469 Btree *pBt = pPage->pBt;
2470 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00002471 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00002472 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00002473
drh91025292004-05-03 19:49:32 +00002474 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00002475 nHeader = 0;
drh91025292004-05-03 19:49:32 +00002476 if( !pPage->leaf ){
2477 nHeader += 4;
2478 }
drh8b18dd42004-05-12 19:18:15 +00002479 if( pPage->hasData ){
drh91025292004-05-03 19:49:32 +00002480 nHeader += putVarint(&pCell[nHeader], nData);
drh6f11bef2004-05-13 01:12:56 +00002481 }else{
drh91025292004-05-03 19:49:32 +00002482 nData = 0;
2483 }
drh6f11bef2004-05-13 01:12:56 +00002484 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh43605152004-05-29 21:46:49 +00002485 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00002486 assert( info.nHeader==nHeader );
2487 assert( info.nKey==nKey );
2488 assert( info.nData==nData );
2489
2490 /* Fill in the payload */
drh3aac2dd2004-04-26 14:10:20 +00002491 nPayload = nData;
2492 if( pPage->intKey ){
2493 pSrc = pData;
2494 nSrc = nData;
drh91025292004-05-03 19:49:32 +00002495 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00002496 }else{
2497 nPayload += nKey;
2498 pSrc = pKey;
2499 nSrc = nKey;
2500 }
drh6f11bef2004-05-13 01:12:56 +00002501 *pnSize = info.nSize;
2502 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00002503 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00002504 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00002505
drh3b7511c2001-05-26 13:15:44 +00002506 while( nPayload>0 ){
2507 if( spaceLeft==0 ){
drh3aac2dd2004-04-26 14:10:20 +00002508 rc = allocatePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl);
drh3b7511c2001-05-26 13:15:44 +00002509 if( rc ){
drh9b171272004-05-08 02:03:22 +00002510 releasePage(pToRelease);
drh3aac2dd2004-04-26 14:10:20 +00002511 clearCell(pPage, pCell);
drh3b7511c2001-05-26 13:15:44 +00002512 return rc;
2513 }
drh3aac2dd2004-04-26 14:10:20 +00002514 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00002515 releasePage(pToRelease);
2516 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00002517 pPrior = pOvfl->aData;
2518 put4byte(pPrior, 0);
2519 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00002520 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00002521 }
2522 n = nPayload;
2523 if( n>spaceLeft ) n = spaceLeft;
drh3aac2dd2004-04-26 14:10:20 +00002524 if( n>nSrc ) n = nSrc;
2525 memcpy(pPayload, pSrc, n);
drh3b7511c2001-05-26 13:15:44 +00002526 nPayload -= n;
drhde647132004-05-07 17:57:49 +00002527 pPayload += n;
drh9b171272004-05-08 02:03:22 +00002528 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00002529 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00002530 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00002531 if( nSrc==0 ){
2532 nSrc = nData;
2533 pSrc = pData;
2534 }
drhdd793422001-06-28 01:54:48 +00002535 }
drh9b171272004-05-08 02:03:22 +00002536 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00002537 return SQLITE_OK;
2538}
2539
2540/*
drhbd03cae2001-06-02 02:40:57 +00002541** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00002542** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00002543** pointer in the third argument.
2544*/
drh4b70f112004-05-02 21:12:19 +00002545static void reparentPage(Btree *pBt, Pgno pgno, MemPage *pNewParent, int idx){
drhbd03cae2001-06-02 02:40:57 +00002546 MemPage *pThis;
drh4b70f112004-05-02 21:12:19 +00002547 unsigned char *aData;
drhbd03cae2001-06-02 02:40:57 +00002548
drhdd793422001-06-28 01:54:48 +00002549 if( pgno==0 ) return;
drh4b70f112004-05-02 21:12:19 +00002550 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00002551 aData = sqlite3pager_lookup(pBt->pPager, pgno);
drhda200cc2004-05-09 11:51:38 +00002552 if( aData ){
drhb6f41482004-05-14 01:58:11 +00002553 pThis = (MemPage*)&aData[pBt->usableSize];
drhda200cc2004-05-09 11:51:38 +00002554 if( pThis->isInit ){
2555 if( pThis->pParent!=pNewParent ){
2556 if( pThis->pParent ) sqlite3pager_unref(pThis->pParent->aData);
2557 pThis->pParent = pNewParent;
2558 if( pNewParent ) sqlite3pager_ref(pNewParent->aData);
2559 }
2560 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00002561 }
drha34b6762004-05-07 13:30:42 +00002562 sqlite3pager_unref(aData);
drhbd03cae2001-06-02 02:40:57 +00002563 }
2564}
2565
2566/*
drh4b70f112004-05-02 21:12:19 +00002567** Change the pParent pointer of all children of pPage to point back
2568** to pPage.
2569**
drhbd03cae2001-06-02 02:40:57 +00002570** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00002571** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00002572**
2573** This routine gets called after you memcpy() one page into
2574** another.
2575*/
drh4b70f112004-05-02 21:12:19 +00002576static void reparentChildPages(MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00002577 int i;
drh4b70f112004-05-02 21:12:19 +00002578 Btree *pBt;
2579
drha34b6762004-05-07 13:30:42 +00002580 if( pPage->leaf ) return;
drh4b70f112004-05-02 21:12:19 +00002581 pBt = pPage->pBt;
drhbd03cae2001-06-02 02:40:57 +00002582 for(i=0; i<pPage->nCell; i++){
drh43605152004-05-29 21:46:49 +00002583 reparentPage(pBt, get4byte(findCell(pPage,i)), pPage, i);
drhbd03cae2001-06-02 02:40:57 +00002584 }
drh43605152004-05-29 21:46:49 +00002585 reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]), pPage, i);
drh428ae8c2003-01-04 16:48:09 +00002586 pPage->idxShift = 0;
drh14acc042001-06-10 19:56:58 +00002587}
2588
2589/*
2590** Remove the i-th cell from pPage. This routine effects pPage only.
2591** The cell content is not freed or deallocated. It is assumed that
2592** the cell content has been copied someplace else. This routine just
2593** removes the reference to the cell from pPage.
2594**
2595** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00002596*/
drh4b70f112004-05-02 21:12:19 +00002597static void dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00002598 int i; /* Loop counter */
2599 int pc; /* Offset to cell content of cell being deleted */
2600 u8 *data; /* pPage->aData */
2601 u8 *ptr; /* Used to move bytes around within data[] */
2602
drh8c42ca92001-06-22 19:15:00 +00002603 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00002604 assert( sz==cellSize(pPage, idx) );
drha34b6762004-05-07 13:30:42 +00002605 assert( sqlite3pager_iswriteable(pPage->aData) );
drhda200cc2004-05-09 11:51:38 +00002606 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00002607 ptr = &data[pPage->cellOffset + 2*idx];
2608 pc = get2byte(ptr);
2609 assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
drhde647132004-05-07 17:57:49 +00002610 freeSpace(pPage, pc, sz);
drh43605152004-05-29 21:46:49 +00002611 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
2612 ptr[0] = ptr[2];
2613 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00002614 }
2615 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00002616 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
2617 pPage->nFree += 2;
drh428ae8c2003-01-04 16:48:09 +00002618 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00002619}
2620
2621/*
2622** Insert a new cell on pPage at cell index "i". pCell points to the
2623** content of the cell.
2624**
2625** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00002626** will not fit, then make a copy of the cell content into pTemp if
2627** pTemp is not null. Regardless of pTemp, allocate a new entry
2628** in pPage->aOvfl[] and make it point to the cell content (either
2629** in pTemp or the original pCell) and also record its index.
2630** Allocating a new entry in pPage->aCell[] implies that
2631** pPage->nOverflow is incremented.
drh14acc042001-06-10 19:56:58 +00002632*/
drh24cd67e2004-05-10 16:18:47 +00002633static void insertCell(
2634 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00002635 int i, /* New cell becomes the i-th cell of the page */
2636 u8 *pCell, /* Content of the new cell */
2637 int sz, /* Bytes of content in pCell */
drh24cd67e2004-05-10 16:18:47 +00002638 u8 *pTemp /* Temp storage space for pCell, if needed */
2639){
drh43605152004-05-29 21:46:49 +00002640 int idx; /* Where to write new cell content in data[] */
2641 int j; /* Loop counter */
2642 int top; /* First byte of content for any cell in data[] */
2643 int end; /* First byte past the last cell pointer in data[] */
2644 int ins; /* Index in data[] where new cell pointer is inserted */
2645 int hdr; /* Offset into data[] of the page header */
2646 int cellOffset; /* Address of first cell pointer in data[] */
2647 u8 *data; /* The content of the whole page */
2648 u8 *ptr; /* Used for moving information around in data[] */
2649
2650 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
2651 assert( sz==cellSizePtr(pPage, pCell) );
drha34b6762004-05-07 13:30:42 +00002652 assert( sqlite3pager_iswriteable(pPage->aData) );
drh43605152004-05-29 21:46:49 +00002653 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00002654 if( pTemp ){
2655 memcpy(pTemp, pCell, sz);
drh43605152004-05-29 21:46:49 +00002656 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00002657 }
drh43605152004-05-29 21:46:49 +00002658 j = pPage->nOverflow++;
2659 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
2660 pPage->aOvfl[j].pCell = pCell;
2661 pPage->aOvfl[j].idx = i;
2662 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00002663 }else{
drh43605152004-05-29 21:46:49 +00002664 data = pPage->aData;
2665 hdr = pPage->hdrOffset;
2666 top = get2byte(&data[hdr+5]);
2667 cellOffset = pPage->cellOffset;
2668 end = cellOffset + 2*pPage->nCell + 2;
2669 ins = cellOffset + 2*i;
2670 if( end > top - sz ){
2671 defragmentPage(pPage);
2672 top = get2byte(&data[hdr+5]);
2673 assert( end + sz <= top );
2674 }
2675 idx = allocateSpace(pPage, sz);
2676 assert( idx>0 );
2677 assert( end <= get2byte(&data[hdr+5]) );
2678 pPage->nCell++;
2679 pPage->nFree -= 2;
drhda200cc2004-05-09 11:51:38 +00002680 memcpy(&data[idx], pCell, sz);
drh43605152004-05-29 21:46:49 +00002681 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
2682 ptr[0] = ptr[-2];
2683 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00002684 }
drh43605152004-05-29 21:46:49 +00002685 put2byte(&data[ins], idx);
2686 put2byte(&data[hdr+3], pPage->nCell);
2687 pPage->idxShift = 1;
drhda200cc2004-05-09 11:51:38 +00002688 pageIntegrity(pPage);
drh14acc042001-06-10 19:56:58 +00002689 }
2690}
2691
2692/*
drhfa1a98a2004-05-14 19:08:17 +00002693** Add a list of cells to a page. The page should be initially empty.
2694** The cells are guaranteed to fit on the page.
2695*/
2696static void assemblePage(
2697 MemPage *pPage, /* The page to be assemblied */
2698 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00002699 u8 **apCell, /* Pointers to cell bodies */
drhfa1a98a2004-05-14 19:08:17 +00002700 int *aSize /* Sizes of the cells */
2701){
2702 int i; /* Loop counter */
2703 int totalSize; /* Total size of all cells */
2704 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00002705 int cellptr; /* Address of next cell pointer */
2706 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00002707 u8 *data; /* Data for the page */
2708
drh43605152004-05-29 21:46:49 +00002709 assert( pPage->nOverflow==0 );
drhfa1a98a2004-05-14 19:08:17 +00002710 totalSize = 0;
2711 for(i=0; i<nCell; i++){
2712 totalSize += aSize[i];
2713 }
drh43605152004-05-29 21:46:49 +00002714 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00002715 assert( pPage->nCell==0 );
drh43605152004-05-29 21:46:49 +00002716 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00002717 data = pPage->aData;
2718 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00002719 put2byte(&data[hdr+3], nCell);
2720 cellbody = allocateSpace(pPage, totalSize);
2721 assert( cellbody>0 );
2722 assert( pPage->nFree >= 2*nCell );
2723 pPage->nFree -= 2*nCell;
drhfa1a98a2004-05-14 19:08:17 +00002724 for(i=0; i<nCell; i++){
drh43605152004-05-29 21:46:49 +00002725 put2byte(&data[cellptr], cellbody);
2726 memcpy(&data[cellbody], apCell[i], aSize[i]);
2727 cellptr += 2;
2728 cellbody += aSize[i];
drhfa1a98a2004-05-14 19:08:17 +00002729 }
drh43605152004-05-29 21:46:49 +00002730 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00002731 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00002732}
2733
drh14acc042001-06-10 19:56:58 +00002734/*
drhc8629a12004-05-08 20:07:40 +00002735** GCC does not define the offsetof() macro so we'll have to do it
2736** ourselves.
2737*/
2738#ifndef offsetof
2739#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
2740#endif
2741
2742/*
drhc3b70572003-01-04 19:44:07 +00002743** The following parameters determine how many adjacent pages get involved
2744** in a balancing operation. NN is the number of neighbors on either side
2745** of the page that participate in the balancing operation. NB is the
2746** total number of pages that participate, including the target page and
2747** NN neighbors on either side.
2748**
2749** The minimum value of NN is 1 (of course). Increasing NN above 1
2750** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
2751** in exchange for a larger degradation in INSERT and UPDATE performance.
2752** The value of NN appears to give the best results overall.
2753*/
2754#define NN 1 /* Number of neighbors on either side of pPage */
2755#define NB (NN*2+1) /* Total pages involved in the balance */
2756
drh43605152004-05-29 21:46:49 +00002757/* Forward reference */
2758static int balance(MemPage*);
2759
drhc3b70572003-01-04 19:44:07 +00002760/*
drhab01f612004-05-22 02:55:23 +00002761** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00002762** of pPage so that all pages have about the same amount of free space.
drh14acc042001-06-10 19:56:58 +00002763** Usually one sibling on either side of pPage is used in the balancing,
drh8b2f49b2001-06-08 00:21:52 +00002764** though both siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00002765** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00002766** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00002767** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00002768**
2769** The number of siblings of pPage might be increased or decreased by
drhab01f612004-05-22 02:55:23 +00002770** one in an effort to keep pages nearly full but not over full. The root page
2771** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00002772** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00002773** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00002774** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00002775**
drh8b2f49b2001-06-08 00:21:52 +00002776** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00002777** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00002778** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00002779** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00002780**
drh8c42ca92001-06-22 19:15:00 +00002781** In the course of balancing the siblings of pPage, the parent of pPage
2782** might become overfull or underfull. If that happens, then this routine
2783** is called recursively on the parent.
2784**
drh5e00f6c2001-09-13 13:46:56 +00002785** If this routine fails for any reason, it might leave the database
2786** in a corrupted state. So if this routine fails, the database should
2787** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00002788*/
drh43605152004-05-29 21:46:49 +00002789static int balance_nonroot(MemPage *pPage){
drh8b2f49b2001-06-08 00:21:52 +00002790 MemPage *pParent; /* The parent of pPage */
drh4b70f112004-05-02 21:12:19 +00002791 Btree *pBt; /* The whole database */
drha34b6762004-05-07 13:30:42 +00002792 int nCell; /* Number of cells in aCell[] */
drh8b2f49b2001-06-08 00:21:52 +00002793 int nOld; /* Number of pages in apOld[] */
2794 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00002795 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00002796 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00002797 int idx; /* Index of pPage in pParent->aCell[] */
2798 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00002799 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00002800 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00002801 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00002802 int usableSpace; /* Bytes in pPage beyond the header */
2803 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00002804 int subtotal; /* Subtotal of bytes in cells on one page */
drhb6f41482004-05-14 01:58:11 +00002805 int iSpace = 0; /* First unused byte of aSpace[] */
drhc3b70572003-01-04 19:44:07 +00002806 MemPage *apOld[NB]; /* pPage and up to two siblings */
2807 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00002808 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drhc3b70572003-01-04 19:44:07 +00002809 MemPage *apNew[NB+1]; /* pPage and up to NB siblings after balancing */
2810 Pgno pgnoNew[NB+1]; /* Page numbers for each page in apNew[] */
2811 int idxDiv[NB]; /* Indices of divider cells in pParent */
drh4b70f112004-05-02 21:12:19 +00002812 u8 *apDiv[NB]; /* Divider cells in pParent */
drha34b6762004-05-07 13:30:42 +00002813 int cntNew[NB+1]; /* Index in aCell[] of cell after i-th page */
drhc3b70572003-01-04 19:44:07 +00002814 int szNew[NB+1]; /* Combined size of cells place on i-th page */
drh4b70f112004-05-02 21:12:19 +00002815 u8 *apCell[(MX_CELL+2)*NB]; /* All cells from pages being balanced */
drhc3b70572003-01-04 19:44:07 +00002816 int szCell[(MX_CELL+2)*NB]; /* Local size of all cells */
drh4b70f112004-05-02 21:12:19 +00002817 u8 aCopy[NB][MX_PAGE_SIZE+sizeof(MemPage)]; /* Space for apCopy[] */
drhb6f41482004-05-14 01:58:11 +00002818 u8 aSpace[MX_PAGE_SIZE*4]; /* Space to copies of divider cells */
drh8b2f49b2001-06-08 00:21:52 +00002819
drh14acc042001-06-10 19:56:58 +00002820 /*
drh43605152004-05-29 21:46:49 +00002821 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00002822 */
drh3a4c1412004-05-09 20:40:11 +00002823 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00002824 assert( sqlite3pager_iswriteable(pPage->aData) );
drh4b70f112004-05-02 21:12:19 +00002825 pBt = pPage->pBt;
drh14acc042001-06-10 19:56:58 +00002826 pParent = pPage->pParent;
drh43605152004-05-29 21:46:49 +00002827 sqlite3pager_write(pParent->aData);
2828 assert( pParent );
2829 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh14acc042001-06-10 19:56:58 +00002830
drh8b2f49b2001-06-08 00:21:52 +00002831 /*
drh4b70f112004-05-02 21:12:19 +00002832 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00002833 ** to pPage. The "idx" variable is the index of that cell. If pPage
2834 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00002835 */
drhbb49aba2003-01-04 18:53:27 +00002836 if( pParent->idxShift ){
drha34b6762004-05-07 13:30:42 +00002837 Pgno pgno;
drh4b70f112004-05-02 21:12:19 +00002838 pgno = pPage->pgno;
drha34b6762004-05-07 13:30:42 +00002839 assert( pgno==sqlite3pager_pagenumber(pPage->aData) );
drhbb49aba2003-01-04 18:53:27 +00002840 for(idx=0; idx<pParent->nCell; idx++){
drh43605152004-05-29 21:46:49 +00002841 if( get4byte(findCell(pParent, idx))==pgno ){
drhbb49aba2003-01-04 18:53:27 +00002842 break;
2843 }
drh8b2f49b2001-06-08 00:21:52 +00002844 }
drh4b70f112004-05-02 21:12:19 +00002845 assert( idx<pParent->nCell
drh43605152004-05-29 21:46:49 +00002846 || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
drhbb49aba2003-01-04 18:53:27 +00002847 }else{
2848 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00002849 }
drh8b2f49b2001-06-08 00:21:52 +00002850
2851 /*
drh14acc042001-06-10 19:56:58 +00002852 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00002853 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00002854 */
drh14acc042001-06-10 19:56:58 +00002855 nOld = nNew = 0;
drha34b6762004-05-07 13:30:42 +00002856 sqlite3pager_ref(pParent->aData);
drh14acc042001-06-10 19:56:58 +00002857
2858 /*
drh4b70f112004-05-02 21:12:19 +00002859 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00002860 ** the siblings. An attempt is made to find NN siblings on either
2861 ** side of pPage. More siblings are taken from one side, however, if
2862 ** pPage there are fewer than NN siblings on the other side. If pParent
2863 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00002864 */
drhc3b70572003-01-04 19:44:07 +00002865 nxDiv = idx - NN;
2866 if( nxDiv + NB > pParent->nCell ){
2867 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00002868 }
drhc3b70572003-01-04 19:44:07 +00002869 if( nxDiv<0 ){
2870 nxDiv = 0;
2871 }
drh8b2f49b2001-06-08 00:21:52 +00002872 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00002873 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00002874 if( k<pParent->nCell ){
2875 idxDiv[i] = k;
drh43605152004-05-29 21:46:49 +00002876 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00002877 nDiv++;
drha34b6762004-05-07 13:30:42 +00002878 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00002879 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00002880 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00002881 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00002882 }else{
2883 break;
drh8b2f49b2001-06-08 00:21:52 +00002884 }
drhde647132004-05-07 17:57:49 +00002885 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00002886 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00002887 apOld[i]->idxParent = k;
drh91025292004-05-03 19:49:32 +00002888 apCopy[i] = 0;
2889 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00002890 nOld++;
drh8b2f49b2001-06-08 00:21:52 +00002891 }
2892
2893 /*
drh14acc042001-06-10 19:56:58 +00002894 ** Make copies of the content of pPage and its siblings into aOld[].
2895 ** The rest of this function will use data from the copies rather
2896 ** that the original pages since the original pages will be in the
2897 ** process of being overwritten.
2898 */
2899 for(i=0; i<nOld; i++){
drhc8629a12004-05-08 20:07:40 +00002900 MemPage *p = apCopy[i] = (MemPage*)&aCopy[i+1][-sizeof(MemPage)];
drh43605152004-05-29 21:46:49 +00002901 p->aData = &((u8*)p)[-pBt->pageSize];
2902 memcpy(p->aData, apOld[i]->aData, pBt->pageSize + sizeof(MemPage));
2903 p->aData = &((u8*)p)[-pBt->pageSize];
drh14acc042001-06-10 19:56:58 +00002904 }
2905
2906 /*
2907 ** Load pointers to all cells on sibling pages and the divider cells
2908 ** into the local apCell[] array. Make copies of the divider cells
drhb6f41482004-05-14 01:58:11 +00002909 ** into space obtained form aSpace[] and remove the the divider Cells
2910 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00002911 **
2912 ** If the siblings are on leaf pages, then the child pointers of the
2913 ** divider cells are stripped from the cells before they are copied
drh96f5b762004-05-16 16:24:36 +00002914 ** into aSpace[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00002915 ** child pointers. If siblings are not leaves, then all cell in
2916 ** apCell[] include child pointers. Either way, all cells in apCell[]
2917 ** are alike.
drh96f5b762004-05-16 16:24:36 +00002918 **
2919 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
2920 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00002921 */
2922 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00002923 leafCorrection = pPage->leaf*4;
drh8b18dd42004-05-12 19:18:15 +00002924 leafData = pPage->leafData && pPage->leaf;
drh8b2f49b2001-06-08 00:21:52 +00002925 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00002926 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00002927 int limit = pOld->nCell+pOld->nOverflow;
2928 for(j=0; j<limit; j++){
2929 apCell[nCell] = findOverflowCell(pOld, j);
2930 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
drh14acc042001-06-10 19:56:58 +00002931 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00002932 }
2933 if( i<nOld-1 ){
drh43605152004-05-29 21:46:49 +00002934 int sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00002935 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00002936 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
2937 ** are duplicates of keys on the child pages. We need to remove
2938 ** the divider cells from pParent, but the dividers cells are not
2939 ** added to apCell[] because they are duplicates of child cells.
2940 */
drh8b18dd42004-05-12 19:18:15 +00002941 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00002942 }else{
drhb6f41482004-05-14 01:58:11 +00002943 u8 *pTemp;
2944 szCell[nCell] = sz;
2945 pTemp = &aSpace[iSpace];
2946 iSpace += sz;
2947 assert( iSpace<=sizeof(aSpace) );
2948 memcpy(pTemp, apDiv[i], sz);
2949 apCell[nCell] = pTemp+leafCorrection;
2950 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00002951 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00002952 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00002953 if( !pOld->leaf ){
2954 assert( leafCorrection==0 );
2955 /* The right pointer of the child page pOld becomes the left
2956 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00002957 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00002958 }else{
2959 assert( leafCorrection==4 );
2960 }
2961 nCell++;
drh4b70f112004-05-02 21:12:19 +00002962 }
drh8b2f49b2001-06-08 00:21:52 +00002963 }
2964 }
2965
2966 /*
drh6019e162001-07-02 17:51:45 +00002967 ** Figure out the number of pages needed to hold all nCell cells.
2968 ** Store this number in "k". Also compute szNew[] which is the total
2969 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00002970 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00002971 ** cntNew[k] should equal nCell.
2972 **
drh96f5b762004-05-16 16:24:36 +00002973 ** Values computed by this block:
2974 **
2975 ** k: The total number of sibling pages
2976 ** szNew[i]: Spaced used on the i-th sibling page.
2977 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
2978 ** the right of the i-th sibling page.
2979 ** usableSpace: Number of bytes of space available on each sibling.
2980 **
drh8b2f49b2001-06-08 00:21:52 +00002981 */
drh43605152004-05-29 21:46:49 +00002982 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00002983 for(subtotal=k=i=0; i<nCell; i++){
drh43605152004-05-29 21:46:49 +00002984 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00002985 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00002986 szNew[k] = subtotal - szCell[i];
2987 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00002988 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00002989 subtotal = 0;
2990 k++;
2991 }
2992 }
2993 szNew[k] = subtotal;
2994 cntNew[k] = nCell;
2995 k++;
drh96f5b762004-05-16 16:24:36 +00002996
2997 /*
2998 ** The packing computed by the previous block is biased toward the siblings
2999 ** on the left side. The left siblings are always nearly full, while the
3000 ** right-most sibling might be nearly empty. This block of code attempts
3001 ** to adjust the packing of siblings to get a better balance.
3002 **
3003 ** This adjustment is more than an optimization. The packing above might
3004 ** be so out of balance as to be illegal. For example, the right-most
3005 ** sibling might be completely empty. This adjustment is not optional.
3006 */
drh6019e162001-07-02 17:51:45 +00003007 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00003008 int szRight = szNew[i]; /* Size of sibling on the right */
3009 int szLeft = szNew[i-1]; /* Size of sibling on the left */
3010 int r; /* Index of right-most cell in left sibling */
3011 int d; /* Index of first cell to the left of right sibling */
3012
3013 r = cntNew[i-1] - 1;
3014 d = r + 1 - leafData;
drh43605152004-05-29 21:46:49 +00003015 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
3016 szRight += szCell[d] + 2;
3017 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00003018 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00003019 r = cntNew[i-1] - 1;
3020 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00003021 }
drh96f5b762004-05-16 16:24:36 +00003022 szNew[i] = szRight;
3023 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00003024 }
3025 assert( cntNew[0]>0 );
drh8b2f49b2001-06-08 00:21:52 +00003026
3027 /*
drh6b308672002-07-08 02:16:37 +00003028 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00003029 */
drh4b70f112004-05-02 21:12:19 +00003030 assert( pPage->pgno>1 );
3031 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00003032 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00003033 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00003034 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00003035 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00003036 pgnoNew[i] = pgnoOld[i];
3037 apOld[i] = 0;
drhda200cc2004-05-09 11:51:38 +00003038 sqlite3pager_write(pNew->aData);
drh6b308672002-07-08 02:16:37 +00003039 }else{
drhda200cc2004-05-09 11:51:38 +00003040 rc = allocatePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1]);
drh6b308672002-07-08 02:16:37 +00003041 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00003042 apNew[i] = pNew;
drh6b308672002-07-08 02:16:37 +00003043 }
drh14acc042001-06-10 19:56:58 +00003044 nNew++;
drhda200cc2004-05-09 11:51:38 +00003045 zeroPage(pNew, pageFlags);
drh8b2f49b2001-06-08 00:21:52 +00003046 }
3047
drh6b308672002-07-08 02:16:37 +00003048 /* Free any old pages that were not reused as new pages.
3049 */
3050 while( i<nOld ){
drh4b70f112004-05-02 21:12:19 +00003051 rc = freePage(apOld[i]);
drh6b308672002-07-08 02:16:37 +00003052 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00003053 releasePage(apOld[i]);
drh6b308672002-07-08 02:16:37 +00003054 apOld[i] = 0;
3055 i++;
3056 }
3057
drh8b2f49b2001-06-08 00:21:52 +00003058 /*
drhf9ffac92002-03-02 19:00:31 +00003059 ** Put the new pages in accending order. This helps to
3060 ** keep entries in the disk file in order so that a scan
3061 ** of the table is a linear scan through the file. That
3062 ** in turn helps the operating system to deliver pages
3063 ** from the disk more rapidly.
3064 **
3065 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00003066 ** n is never more than NB (a small constant), that should
3067 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00003068 **
drhc3b70572003-01-04 19:44:07 +00003069 ** When NB==3, this one optimization makes the database
3070 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00003071 */
3072 for(i=0; i<k-1; i++){
3073 int minV = pgnoNew[i];
3074 int minI = i;
3075 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00003076 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00003077 minI = j;
3078 minV = pgnoNew[j];
3079 }
3080 }
3081 if( minI>i ){
3082 int t;
3083 MemPage *pT;
3084 t = pgnoNew[i];
3085 pT = apNew[i];
3086 pgnoNew[i] = pgnoNew[minI];
3087 apNew[i] = apNew[minI];
3088 pgnoNew[minI] = t;
3089 apNew[minI] = pT;
3090 }
3091 }
drh10c0fa62004-05-18 12:50:17 +00003092 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00003093 pgnoOld[0],
3094 nOld>=2 ? pgnoOld[1] : 0,
3095 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00003096 pgnoNew[0], szNew[0],
3097 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
3098 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
3099 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0));
drh24cd67e2004-05-10 16:18:47 +00003100
drhf9ffac92002-03-02 19:00:31 +00003101
3102 /*
drh14acc042001-06-10 19:56:58 +00003103 ** Evenly distribute the data in apCell[] across the new pages.
3104 ** Insert divider cells into pParent as necessary.
3105 */
3106 j = 0;
3107 for(i=0; i<nNew; i++){
3108 MemPage *pNew = apNew[i];
drh4b70f112004-05-02 21:12:19 +00003109 assert( pNew->pgno==pgnoNew[i] );
drhfa1a98a2004-05-14 19:08:17 +00003110 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
3111 j = cntNew[i];
drh6019e162001-07-02 17:51:45 +00003112 assert( pNew->nCell>0 );
drh43605152004-05-29 21:46:49 +00003113 assert( pNew->nOverflow==0 );
drh14acc042001-06-10 19:56:58 +00003114 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00003115 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00003116 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00003117 int sz;
3118 pCell = apCell[j];
3119 sz = szCell[j] + leafCorrection;
drh4b70f112004-05-02 21:12:19 +00003120 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00003121 memcpy(&pNew->aData[8], pCell, 4);
drh24cd67e2004-05-10 16:18:47 +00003122 pTemp = 0;
drh8b18dd42004-05-12 19:18:15 +00003123 }else if( leafData ){
drh6f11bef2004-05-13 01:12:56 +00003124 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00003125 j--;
drh43605152004-05-29 21:46:49 +00003126 parseCellPtr(pNew, apCell[j], &info);
drhb6f41482004-05-14 01:58:11 +00003127 pCell = &aSpace[iSpace];
drh6f11bef2004-05-13 01:12:56 +00003128 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, &sz);
drhb6f41482004-05-14 01:58:11 +00003129 iSpace += sz;
3130 assert( iSpace<=sizeof(aSpace) );
drh8b18dd42004-05-12 19:18:15 +00003131 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00003132 }else{
3133 pCell -= 4;
drhb6f41482004-05-14 01:58:11 +00003134 pTemp = &aSpace[iSpace];
3135 iSpace += sz;
3136 assert( iSpace<=sizeof(aSpace) );
drh4b70f112004-05-02 21:12:19 +00003137 }
drh8b18dd42004-05-12 19:18:15 +00003138 insertCell(pParent, nxDiv, pCell, sz, pTemp);
drh43605152004-05-29 21:46:49 +00003139 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
drh14acc042001-06-10 19:56:58 +00003140 j++;
3141 nxDiv++;
3142 }
3143 }
drh6019e162001-07-02 17:51:45 +00003144 assert( j==nCell );
drh4b70f112004-05-02 21:12:19 +00003145 if( (pageFlags & PTF_LEAF)==0 ){
drh43605152004-05-29 21:46:49 +00003146 memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
drh14acc042001-06-10 19:56:58 +00003147 }
drh43605152004-05-29 21:46:49 +00003148 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00003149 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00003150 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00003151 }else{
3152 /* Right-most sibling is the left child of the first entry in pParent
3153 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00003154 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00003155 }
3156
3157 /*
3158 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00003159 */
3160 for(i=0; i<nNew; i++){
drh4b70f112004-05-02 21:12:19 +00003161 reparentChildPages(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00003162 }
drh4b70f112004-05-02 21:12:19 +00003163 reparentChildPages(pParent);
drh8b2f49b2001-06-08 00:21:52 +00003164
3165 /*
drh3a4c1412004-05-09 20:40:11 +00003166 ** Balance the parent page. Note that the current page (pPage) might
3167 ** have been added to the freelist is it might no longer be initialized.
3168 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00003169 */
drhda200cc2004-05-09 11:51:38 +00003170 assert( pParent->isInit );
drh3a4c1412004-05-09 20:40:11 +00003171 /* assert( pPage->isInit ); // No! pPage might have been added to freelist */
3172 /* pageIntegrity(pPage); // No! pPage might have been added to freelist */
drh4b70f112004-05-02 21:12:19 +00003173 rc = balance(pParent);
drhda200cc2004-05-09 11:51:38 +00003174
drh8b2f49b2001-06-08 00:21:52 +00003175 /*
drh14acc042001-06-10 19:56:58 +00003176 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00003177 */
drh14acc042001-06-10 19:56:58 +00003178balance_cleanup:
drh8b2f49b2001-06-08 00:21:52 +00003179 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00003180 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00003181 }
drh14acc042001-06-10 19:56:58 +00003182 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00003183 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00003184 }
drh91025292004-05-03 19:49:32 +00003185 releasePage(pParent);
drh3a4c1412004-05-09 20:40:11 +00003186 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
3187 pPage->pgno, nOld, nNew, nCell));
drh8b2f49b2001-06-08 00:21:52 +00003188 return rc;
3189}
3190
3191/*
drh43605152004-05-29 21:46:49 +00003192** This routine is called for the root page of a btree when the root
3193** page contains no cells. This is an opportunity to make the tree
3194** shallower by one level.
3195*/
3196static int balance_shallower(MemPage *pPage){
3197 MemPage *pChild; /* The only child page of pPage */
3198 Pgno pgnoChild; /* Page number for pChild */
3199 int rc; /* Return code from subprocedures */
3200 u8 *apCell[(MX_CELL+2)*NB]; /* All cells from pages being balanced */
3201 int szCell[(MX_CELL+2)*NB]; /* Local size of all cells */
3202
3203 assert( pPage->pParent==0 );
3204 assert( pPage->nCell==0 );
3205 if( pPage->leaf ){
3206 /* The table is completely empty */
3207 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
3208 }else{
3209 /* The root page is empty but has one child. Transfer the
3210 ** information from that one child into the root page if it
3211 ** will fit. This reduces the depth of the tree by one.
3212 **
3213 ** If the root page is page 1, it has less space available than
3214 ** its child (due to the 100 byte header that occurs at the beginning
3215 ** of the database fle), so it might not be able to hold all of the
3216 ** information currently contained in the child. If this is the
3217 ** case, then do not do the transfer. Leave page 1 empty except
3218 ** for the right-pointer to the child page. The child page becomes
3219 ** the virtual root of the tree.
3220 */
3221 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
3222 assert( pgnoChild>0 );
3223 assert( pgnoChild<=sqlite3pager_pagecount(pPage->pBt->pPager) );
3224 rc = getPage(pPage->pBt, pgnoChild, &pChild);
3225 if( rc ) return rc;
3226 if( pPage->pgno==1 ){
3227 rc = initPage(pChild, pPage);
3228 if( rc ) return rc;
3229 assert( pChild->nOverflow==0 );
3230 if( pChild->nFree>=100 ){
3231 /* The child information will fit on the root page, so do the
3232 ** copy */
3233 int i;
3234 zeroPage(pPage, pChild->aData[0]);
3235 for(i=0; i<pChild->nCell; i++){
3236 apCell[i] = findCell(pChild,i);
3237 szCell[i] = cellSizePtr(pChild, apCell[i]);
3238 }
3239 assemblePage(pPage, pChild->nCell, apCell, szCell);
3240 freePage(pChild);
3241 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
3242 }else{
3243 /* The child has more information that will fit on the root.
3244 ** The tree is already balanced. Do nothing. */
3245 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
3246 }
3247 }else{
3248 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
3249 pPage->isInit = 0;
3250 pPage->pParent = 0;
3251 rc = initPage(pPage, 0);
3252 assert( rc==SQLITE_OK );
3253 freePage(pChild);
3254 TRACE(("BALANCE: transfer child %d into root %d\n",
3255 pChild->pgno, pPage->pgno));
3256 }
3257 reparentChildPages(pPage);
3258 releasePage(pChild);
3259 }
3260 return SQLITE_OK;
3261}
3262
3263
3264/*
3265** The root page is overfull
3266**
3267** When this happens, Create a new child page and copy the
3268** contents of the root into the child. Then make the root
3269** page an empty page with rightChild pointing to the new
3270** child. Finally, call balance_internal() on the new child
3271** to cause it to split.
3272*/
3273static int balance_deeper(MemPage *pPage){
3274 int rc; /* Return value from subprocedures */
3275 MemPage *pChild; /* Pointer to a new child page */
3276 Pgno pgnoChild; /* Page number of the new child page */
3277 Btree *pBt; /* The BTree */
3278 int usableSize; /* Total usable size of a page */
3279 u8 *data; /* Content of the parent page */
3280 u8 *cdata; /* Content of the child page */
3281 int hdr; /* Offset to page header in parent */
3282 int brk; /* Offset to content of first cell in parent */
3283
3284 assert( pPage->pParent==0 );
3285 assert( pPage->nOverflow>0 );
3286 pBt = pPage->pBt;
3287 rc = allocatePage(pBt, &pChild, &pgnoChild, pPage->pgno);
3288 if( rc ) return rc;
3289 assert( sqlite3pager_iswriteable(pChild->aData) );
3290 usableSize = pBt->usableSize;
3291 data = pPage->aData;
3292 hdr = pPage->hdrOffset;
3293 brk = get2byte(&data[hdr+5]);
3294 cdata = pChild->aData;
3295 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
3296 memcpy(&cdata[brk], &data[brk], usableSize-brk);
3297 rc = initPage(pChild, pPage);
3298 if( rc ) return rc;
3299 memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
3300 pChild->nOverflow = pPage->nOverflow;
3301 if( pChild->nOverflow ){
3302 pChild->nFree = 0;
3303 }
3304 assert( pChild->nCell==pPage->nCell );
3305 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
3306 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
3307 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
3308 rc = balance_nonroot(pChild);
3309 releasePage(pChild);
3310 return rc;
3311}
3312
3313/*
3314** Decide if the page pPage needs to be balanced. If balancing is
3315** required, call the appropriate balancing routine.
3316*/
3317static int balance(MemPage *pPage){
3318 int rc = SQLITE_OK;
3319 if( pPage->pParent==0 ){
3320 if( pPage->nOverflow>0 ){
3321 rc = balance_deeper(pPage);
3322 }
3323 if( pPage->nCell==0 ){
3324 rc = balance_shallower(pPage);
3325 }
3326 }else{
3327 if( pPage->nOverflow>0 || pPage->nFree>pPage->pBt->usableSize*2/3 ){
3328 rc = balance_nonroot(pPage);
3329 }
3330 }
3331 return rc;
3332}
3333
3334/*
drhf74b8d92002-09-01 23:20:45 +00003335** This routine checks all cursors that point to the same table
3336** as pCur points to. If any of those cursors were opened with
3337** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
3338** cursors point to the same table were opened with wrFlag==1
3339** then this routine returns SQLITE_OK.
3340**
3341** In addition to checking for read-locks (where a read-lock
3342** means a cursor opened with wrFlag==0) this routine also moves
3343** all cursors other than pCur so that they are pointing to the
3344** first Cell on root page. This is necessary because an insert
3345** or delete might change the number of cells on a page or delete
3346** a page entirely and we do not want to leave any cursors
3347** pointing to non-existant pages or cells.
3348*/
3349static int checkReadLocks(BtCursor *pCur){
3350 BtCursor *p;
3351 assert( pCur->wrFlag );
3352 for(p=pCur->pShared; p!=pCur; p=p->pShared){
3353 assert( p );
3354 assert( p->pgnoRoot==pCur->pgnoRoot );
drha34b6762004-05-07 13:30:42 +00003355 assert( p->pPage->pgno==sqlite3pager_pagenumber(p->pPage->aData) );
drhf74b8d92002-09-01 23:20:45 +00003356 if( p->wrFlag==0 ) return SQLITE_LOCKED;
drh91025292004-05-03 19:49:32 +00003357 if( p->pPage->pgno!=p->pgnoRoot ){
drhf74b8d92002-09-01 23:20:45 +00003358 moveToRoot(p);
3359 }
3360 }
3361 return SQLITE_OK;
3362}
3363
3364/*
drh3b7511c2001-05-26 13:15:44 +00003365** Insert a new record into the BTree. The key is given by (pKey,nKey)
3366** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00003367** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00003368** is left pointing at a random location.
3369**
3370** For an INTKEY table, only the nKey value of the key is used. pKey is
3371** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00003372*/
drh3aac2dd2004-04-26 14:10:20 +00003373int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00003374 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00003375 const void *pKey, i64 nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00003376 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00003377){
drh3b7511c2001-05-26 13:15:44 +00003378 int rc;
3379 int loc;
drh14acc042001-06-10 19:56:58 +00003380 int szNew;
drh3b7511c2001-05-26 13:15:44 +00003381 MemPage *pPage;
3382 Btree *pBt = pCur->pBt;
drha34b6762004-05-07 13:30:42 +00003383 unsigned char *oldCell;
3384 unsigned char newCell[MX_CELL_SIZE];
drh3b7511c2001-05-26 13:15:44 +00003385
drhc39e0002004-05-07 23:50:57 +00003386 if( pCur->status ){
3387 return pCur->status; /* A rollback destroyed this cursor */
drhecdc7532001-09-23 02:35:53 +00003388 }
danielk1977ee5741e2004-05-31 10:01:34 +00003389 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00003390 /* Must start a transaction before doing an insert */
3391 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003392 }
drhf74b8d92002-09-01 23:20:45 +00003393 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00003394 if( !pCur->wrFlag ){
3395 return SQLITE_PERM; /* Cursor not open for writing */
3396 }
drhf74b8d92002-09-01 23:20:45 +00003397 if( checkReadLocks(pCur) ){
3398 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
3399 }
drh3aac2dd2004-04-26 14:10:20 +00003400 rc = sqlite3BtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00003401 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00003402 pPage = pCur->pPage;
drh4a1c3802004-05-12 15:15:47 +00003403 assert( pPage->intKey || nKey>=0 );
drh8b18dd42004-05-12 19:18:15 +00003404 assert( pPage->leaf || !pPage->leafData );
drh3a4c1412004-05-09 20:40:11 +00003405 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
3406 pCur->pgnoRoot, nKey, nData, pPage->pgno,
3407 loc==0 ? "overwrite" : "new entry"));
drh7aa128d2002-06-21 13:09:16 +00003408 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00003409 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00003410 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003411 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, &szNew);
drh3b7511c2001-05-26 13:15:44 +00003412 if( rc ) return rc;
drh43605152004-05-29 21:46:49 +00003413 assert( szNew==cellSizePtr(pPage, newCell) );
drh3a4c1412004-05-09 20:40:11 +00003414 assert( szNew<=sizeof(newCell) );
drhf328bc82004-05-10 23:29:49 +00003415 if( loc==0 && pCur->isValid ){
drha34b6762004-05-07 13:30:42 +00003416 int szOld;
3417 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00003418 oldCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00003419 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003420 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00003421 }
drh43605152004-05-29 21:46:49 +00003422 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00003423 rc = clearCell(pPage, oldCell);
drh5e2f8b92001-05-28 00:41:15 +00003424 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00003425 dropCell(pPage, pCur->idx, szOld);
drh7c717f72001-06-24 20:39:41 +00003426 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00003427 assert( pPage->leaf );
drh14acc042001-06-10 19:56:58 +00003428 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00003429 pCur->info.nSize = 0;
drh14acc042001-06-10 19:56:58 +00003430 }else{
drh4b70f112004-05-02 21:12:19 +00003431 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00003432 }
drh24cd67e2004-05-10 16:18:47 +00003433 insertCell(pPage, pCur->idx, newCell, szNew, 0);
drh4b70f112004-05-02 21:12:19 +00003434 rc = balance(pPage);
drh23e11ca2004-05-04 17:27:28 +00003435 /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
drh3fc190c2001-09-14 03:24:23 +00003436 /* fflush(stdout); */
drh4b70f112004-05-02 21:12:19 +00003437 moveToRoot(pCur);
drh5e2f8b92001-05-28 00:41:15 +00003438 return rc;
3439}
3440
3441/*
drh4b70f112004-05-02 21:12:19 +00003442** Delete the entry that the cursor is pointing to. The cursor
3443** is left pointing at a random location.
drh3b7511c2001-05-26 13:15:44 +00003444*/
drh3aac2dd2004-04-26 14:10:20 +00003445int sqlite3BtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00003446 MemPage *pPage = pCur->pPage;
drh4b70f112004-05-02 21:12:19 +00003447 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00003448 int rc;
drh8c42ca92001-06-22 19:15:00 +00003449 Pgno pgnoChild;
drh0d316a42002-08-11 20:10:47 +00003450 Btree *pBt = pCur->pBt;
drh8b2f49b2001-06-08 00:21:52 +00003451
drh7aa128d2002-06-21 13:09:16 +00003452 assert( pPage->isInit );
drhc39e0002004-05-07 23:50:57 +00003453 if( pCur->status ){
3454 return pCur->status; /* A rollback destroyed this cursor */
drhecdc7532001-09-23 02:35:53 +00003455 }
danielk1977ee5741e2004-05-31 10:01:34 +00003456 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00003457 /* Must start a transaction before doing a delete */
3458 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003459 }
drhf74b8d92002-09-01 23:20:45 +00003460 assert( !pBt->readOnly );
drhbd03cae2001-06-02 02:40:57 +00003461 if( pCur->idx >= pPage->nCell ){
3462 return SQLITE_ERROR; /* The cursor is not pointing to anything */
3463 }
drhecdc7532001-09-23 02:35:53 +00003464 if( !pCur->wrFlag ){
3465 return SQLITE_PERM; /* Did not open this cursor for writing */
3466 }
drhf74b8d92002-09-01 23:20:45 +00003467 if( checkReadLocks(pCur) ){
3468 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
3469 }
drha34b6762004-05-07 13:30:42 +00003470 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00003471 if( rc ) return rc;
drh43605152004-05-29 21:46:49 +00003472 pCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00003473 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003474 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00003475 }
3476 clearCell(pPage, pCell);
3477 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00003478 /*
drh5e00f6c2001-09-13 13:46:56 +00003479 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00003480 ** do something we will leave a hole on an internal page.
3481 ** We have to fill the hole by moving in a cell from a leaf. The
3482 ** next Cell after the one to be deleted is guaranteed to exist and
3483 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00003484 */
drh14acc042001-06-10 19:56:58 +00003485 BtCursor leafCur;
drh4b70f112004-05-02 21:12:19 +00003486 unsigned char *pNext;
drh14acc042001-06-10 19:56:58 +00003487 int szNext;
drh8c1238a2003-01-02 14:43:55 +00003488 int notUsed;
drh24cd67e2004-05-10 16:18:47 +00003489 unsigned char tempCell[MX_CELL_SIZE];
drh8b18dd42004-05-12 19:18:15 +00003490 assert( !pPage->leafData );
drh14acc042001-06-10 19:56:58 +00003491 getTempCursor(pCur, &leafCur);
drh3aac2dd2004-04-26 14:10:20 +00003492 rc = sqlite3BtreeNext(&leafCur, &notUsed);
drh14acc042001-06-10 19:56:58 +00003493 if( rc!=SQLITE_OK ){
drh8a6ac0a2004-02-14 17:35:07 +00003494 if( rc!=SQLITE_NOMEM ) rc = SQLITE_CORRUPT;
3495 return rc;
drh5e2f8b92001-05-28 00:41:15 +00003496 }
drha34b6762004-05-07 13:30:42 +00003497 rc = sqlite3pager_write(leafCur.pPage->aData);
drh6019e162001-07-02 17:51:45 +00003498 if( rc ) return rc;
drh3a4c1412004-05-09 20:40:11 +00003499 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
3500 pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
drh43605152004-05-29 21:46:49 +00003501 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
3502 pNext = findCell(leafCur.pPage, leafCur.idx);
3503 szNext = cellSizePtr(leafCur.pPage, pNext);
drh24cd67e2004-05-10 16:18:47 +00003504 assert( sizeof(tempCell)>=szNext+4 );
3505 insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell);
drh43605152004-05-29 21:46:49 +00003506 put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
drh4b70f112004-05-02 21:12:19 +00003507 rc = balance(pPage);
drh5e2f8b92001-05-28 00:41:15 +00003508 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00003509 dropCell(leafCur.pPage, leafCur.idx, szNext);
3510 rc = balance(leafCur.pPage);
drh8c42ca92001-06-22 19:15:00 +00003511 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00003512 }else{
drh3a4c1412004-05-09 20:40:11 +00003513 TRACE(("DELETE: table=%d delete from leaf %d\n",
3514 pCur->pgnoRoot, pPage->pgno));
drh43605152004-05-29 21:46:49 +00003515 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
drh4b70f112004-05-02 21:12:19 +00003516 rc = balance(pPage);
drh5e2f8b92001-05-28 00:41:15 +00003517 }
drh4b70f112004-05-02 21:12:19 +00003518 moveToRoot(pCur);
drh5e2f8b92001-05-28 00:41:15 +00003519 return rc;
drh3b7511c2001-05-26 13:15:44 +00003520}
drh8b2f49b2001-06-08 00:21:52 +00003521
3522/*
drhc6b52df2002-01-04 03:09:29 +00003523** Create a new BTree table. Write into *piTable the page
3524** number for the root page of the new table.
3525**
drhab01f612004-05-22 02:55:23 +00003526** The type of type is determined by the flags parameter. Only the
3527** following values of flags are currently in use. Other values for
3528** flags might not work:
3529**
3530** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
3531** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00003532*/
drh3aac2dd2004-04-26 14:10:20 +00003533int sqlite3BtreeCreateTable(Btree *pBt, int *piTable, int flags){
drh8b2f49b2001-06-08 00:21:52 +00003534 MemPage *pRoot;
3535 Pgno pgnoRoot;
3536 int rc;
danielk1977ee5741e2004-05-31 10:01:34 +00003537 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00003538 /* Must start a transaction first */
3539 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003540 }
drh5df72a52002-06-06 23:16:05 +00003541 if( pBt->readOnly ){
3542 return SQLITE_READONLY;
3543 }
drhda200cc2004-05-09 11:51:38 +00003544 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1);
drh8b2f49b2001-06-08 00:21:52 +00003545 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003546 assert( sqlite3pager_iswriteable(pRoot->aData) );
drhde647132004-05-07 17:57:49 +00003547 zeroPage(pRoot, flags | PTF_LEAF);
drha34b6762004-05-07 13:30:42 +00003548 sqlite3pager_unref(pRoot->aData);
drh8b2f49b2001-06-08 00:21:52 +00003549 *piTable = (int)pgnoRoot;
3550 return SQLITE_OK;
3551}
3552
3553/*
3554** Erase the given database page and all its children. Return
3555** the page to the freelist.
3556*/
drh4b70f112004-05-02 21:12:19 +00003557static int clearDatabasePage(
3558 Btree *pBt, /* The BTree that contains the table */
3559 Pgno pgno, /* Page number to clear */
3560 MemPage *pParent, /* Parent page. NULL for the root */
3561 int freePageFlag /* Deallocate page if true */
3562){
drh8b2f49b2001-06-08 00:21:52 +00003563 MemPage *pPage;
3564 int rc;
drh4b70f112004-05-02 21:12:19 +00003565 unsigned char *pCell;
3566 int i;
drh8b2f49b2001-06-08 00:21:52 +00003567
drhde647132004-05-07 17:57:49 +00003568 rc = getAndInitPage(pBt, pgno, &pPage, pParent);
drh8b2f49b2001-06-08 00:21:52 +00003569 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003570 rc = sqlite3pager_write(pPage->aData);
drh6019e162001-07-02 17:51:45 +00003571 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00003572 for(i=0; i<pPage->nCell; i++){
drh43605152004-05-29 21:46:49 +00003573 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00003574 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003575 rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
drh8b2f49b2001-06-08 00:21:52 +00003576 if( rc ) return rc;
3577 }
drh4b70f112004-05-02 21:12:19 +00003578 rc = clearCell(pPage, pCell);
drh8b2f49b2001-06-08 00:21:52 +00003579 if( rc ) return rc;
3580 }
drha34b6762004-05-07 13:30:42 +00003581 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003582 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
drh2aa679f2001-06-25 02:11:07 +00003583 if( rc ) return rc;
3584 }
3585 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00003586 rc = freePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00003587 }else{
drh3a4c1412004-05-09 20:40:11 +00003588 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00003589 }
drh4b70f112004-05-02 21:12:19 +00003590 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00003591 return rc;
drh8b2f49b2001-06-08 00:21:52 +00003592}
3593
3594/*
drhab01f612004-05-22 02:55:23 +00003595** Delete all information from a single table in the database. iTable is
3596** the page number of the root of the table. After this routine returns,
3597** the root page is empty, but still exists.
3598**
3599** This routine will fail with SQLITE_LOCKED if there are any open
3600** read cursors on the table. Open write cursors are moved to the
3601** root of the table.
drh8b2f49b2001-06-08 00:21:52 +00003602*/
drh3aac2dd2004-04-26 14:10:20 +00003603int sqlite3BtreeClearTable(Btree *pBt, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00003604 int rc;
drhf74b8d92002-09-01 23:20:45 +00003605 BtCursor *pCur;
danielk1977ee5741e2004-05-31 10:01:34 +00003606 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00003607 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003608 }
drhf74b8d92002-09-01 23:20:45 +00003609 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3610 if( pCur->pgnoRoot==(Pgno)iTable ){
3611 if( pCur->wrFlag==0 ) return SQLITE_LOCKED;
3612 moveToRoot(pCur);
3613 }
drhecdc7532001-09-23 02:35:53 +00003614 }
drha34b6762004-05-07 13:30:42 +00003615 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
drh8b2f49b2001-06-08 00:21:52 +00003616 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00003617 sqlite3BtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00003618 }
drh8c42ca92001-06-22 19:15:00 +00003619 return rc;
drh8b2f49b2001-06-08 00:21:52 +00003620}
3621
3622/*
3623** Erase all information in a table and add the root of the table to
3624** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00003625** page 1) is never added to the freelist.
3626**
3627** This routine will fail with SQLITE_LOCKED if there are any open
3628** cursors on the table.
drh8b2f49b2001-06-08 00:21:52 +00003629*/
drh3aac2dd2004-04-26 14:10:20 +00003630int sqlite3BtreeDropTable(Btree *pBt, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00003631 int rc;
3632 MemPage *pPage;
drhf74b8d92002-09-01 23:20:45 +00003633 BtCursor *pCur;
danielk1977ee5741e2004-05-31 10:01:34 +00003634 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00003635 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00003636 }
drhf74b8d92002-09-01 23:20:45 +00003637 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3638 if( pCur->pgnoRoot==(Pgno)iTable ){
3639 return SQLITE_LOCKED; /* Cannot drop a table that has a cursor */
3640 }
drh5df72a52002-06-06 23:16:05 +00003641 }
drha34b6762004-05-07 13:30:42 +00003642 rc = getPage(pBt, (Pgno)iTable, &pPage);
drh2aa679f2001-06-25 02:11:07 +00003643 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003644 rc = sqlite3BtreeClearTable(pBt, iTable);
drh2aa679f2001-06-25 02:11:07 +00003645 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00003646 if( iTable>1 ){
drha34b6762004-05-07 13:30:42 +00003647 rc = freePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00003648 }else{
drha34b6762004-05-07 13:30:42 +00003649 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
drh8b2f49b2001-06-08 00:21:52 +00003650 }
drh4b70f112004-05-02 21:12:19 +00003651 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00003652 return rc;
3653}
3654
drh001bbcb2003-03-19 03:14:00 +00003655
drh8b2f49b2001-06-08 00:21:52 +00003656/*
drh23e11ca2004-05-04 17:27:28 +00003657** Read the meta-information out of a database file. Meta[0]
3658** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00003659** through meta[15] are available for use by higher layers. Meta[0]
3660** is read-only, the others are read/write.
3661**
3662** The schema layer numbers meta values differently. At the schema
3663** layer (and the SetCookie and ReadCookie opcodes) the number of
3664** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00003665*/
drh3aac2dd2004-04-26 14:10:20 +00003666int sqlite3BtreeGetMeta(Btree *pBt, int idx, u32 *pMeta){
drh8b2f49b2001-06-08 00:21:52 +00003667 int rc;
drh4b70f112004-05-02 21:12:19 +00003668 unsigned char *pP1;
drh8b2f49b2001-06-08 00:21:52 +00003669
drh23e11ca2004-05-04 17:27:28 +00003670 assert( idx>=0 && idx<=15 );
drha34b6762004-05-07 13:30:42 +00003671 rc = sqlite3pager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00003672 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00003673 *pMeta = get4byte(&pP1[36 + idx*4]);
drha34b6762004-05-07 13:30:42 +00003674 sqlite3pager_unref(pP1);
drh8b2f49b2001-06-08 00:21:52 +00003675 return SQLITE_OK;
3676}
3677
3678/*
drh23e11ca2004-05-04 17:27:28 +00003679** Write meta-information back into the database. Meta[0] is
3680** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00003681*/
drh3aac2dd2004-04-26 14:10:20 +00003682int sqlite3BtreeUpdateMeta(Btree *pBt, int idx, u32 iMeta){
drh4b70f112004-05-02 21:12:19 +00003683 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00003684 int rc;
drh23e11ca2004-05-04 17:27:28 +00003685 assert( idx>=1 && idx<=15 );
danielk1977ee5741e2004-05-31 10:01:34 +00003686 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00003687 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +00003688 }
drhde647132004-05-07 17:57:49 +00003689 assert( pBt->pPage1!=0 );
3690 pP1 = pBt->pPage1->aData;
drha34b6762004-05-07 13:30:42 +00003691 rc = sqlite3pager_write(pP1);
drh4b70f112004-05-02 21:12:19 +00003692 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00003693 put4byte(&pP1[36 + idx*4], iMeta);
drh8b2f49b2001-06-08 00:21:52 +00003694 return SQLITE_OK;
3695}
drh8c42ca92001-06-22 19:15:00 +00003696
drhf328bc82004-05-10 23:29:49 +00003697/*
3698** Return the flag byte at the beginning of the page that the cursor
3699** is currently pointing to.
3700*/
3701int sqlite3BtreeFlags(BtCursor *pCur){
3702 MemPage *pPage = pCur->pPage;
3703 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
3704}
3705
drh5eddca62001-06-30 21:53:53 +00003706/******************************************************************************
3707** The complete implementation of the BTree subsystem is above this line.
3708** All the code the follows is for testing and troubleshooting the BTree
3709** subsystem. None of the code that follows is used during normal operation.
drh5eddca62001-06-30 21:53:53 +00003710******************************************************************************/
drh5eddca62001-06-30 21:53:53 +00003711
drh8c42ca92001-06-22 19:15:00 +00003712/*
3713** Print a disassembly of the given page on standard output. This routine
3714** is used for debugging and testing only.
3715*/
drhaaab5722002-02-19 13:39:21 +00003716#ifdef SQLITE_TEST
drh23e11ca2004-05-04 17:27:28 +00003717int sqlite3BtreePageDump(Btree *pBt, int pgno, int recursive){
drh8c42ca92001-06-22 19:15:00 +00003718 int rc;
3719 MemPage *pPage;
drhc8629a12004-05-08 20:07:40 +00003720 int i, j, c;
drh8c42ca92001-06-22 19:15:00 +00003721 int nFree;
3722 u16 idx;
drhab9f7f12004-05-08 10:56:11 +00003723 int hdr;
drh43605152004-05-29 21:46:49 +00003724 int nCell;
drhab9f7f12004-05-08 10:56:11 +00003725 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00003726 char range[20];
3727 unsigned char payload[20];
drhab9f7f12004-05-08 10:56:11 +00003728
drh4b70f112004-05-02 21:12:19 +00003729 rc = getPage(pBt, (Pgno)pgno, &pPage);
drh8c42ca92001-06-22 19:15:00 +00003730 if( rc ){
3731 return rc;
3732 }
drhab9f7f12004-05-08 10:56:11 +00003733 hdr = pPage->hdrOffset;
3734 data = pPage->aData;
drhc8629a12004-05-08 20:07:40 +00003735 c = data[hdr];
drh8b18dd42004-05-12 19:18:15 +00003736 pPage->intKey = (c & (PTF_INTKEY|PTF_LEAFDATA))!=0;
drhc8629a12004-05-08 20:07:40 +00003737 pPage->zeroData = (c & PTF_ZERODATA)!=0;
drh8b18dd42004-05-12 19:18:15 +00003738 pPage->leafData = (c & PTF_LEAFDATA)!=0;
drhc8629a12004-05-08 20:07:40 +00003739 pPage->leaf = (c & PTF_LEAF)!=0;
drh8b18dd42004-05-12 19:18:15 +00003740 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
drh43605152004-05-29 21:46:49 +00003741 nCell = get2byte(&data[hdr+3]);
drhda200cc2004-05-09 11:51:38 +00003742 printf("PAGE %d: flags=0x%02x frag=%d parent=%d\n", pgno,
drh43605152004-05-29 21:46:49 +00003743 data[hdr], data[hdr+7],
drhda200cc2004-05-09 11:51:38 +00003744 (pPage->isInit && pPage->pParent) ? pPage->pParent->pgno : 0);
drhab9f7f12004-05-08 10:56:11 +00003745 assert( hdr == (pgno==1 ? 100 : 0) );
drh43605152004-05-29 21:46:49 +00003746 idx = hdr + 12 - pPage->leaf*4;
3747 for(i=0; i<nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00003748 CellInfo info;
drh4b70f112004-05-02 21:12:19 +00003749 Pgno child;
drh43605152004-05-29 21:46:49 +00003750 unsigned char *pCell;
drh6f11bef2004-05-13 01:12:56 +00003751 int sz;
drh43605152004-05-29 21:46:49 +00003752 int addr;
drh6f11bef2004-05-13 01:12:56 +00003753
drh43605152004-05-29 21:46:49 +00003754 addr = get2byte(&data[idx + 2*i]);
3755 pCell = &data[addr];
3756 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003757 sz = info.nSize;
drh43605152004-05-29 21:46:49 +00003758 sprintf(range,"%d..%d", addr, addr+sz-1);
drh4b70f112004-05-02 21:12:19 +00003759 if( pPage->leaf ){
3760 child = 0;
3761 }else{
drh43605152004-05-29 21:46:49 +00003762 child = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00003763 }
drh6f11bef2004-05-13 01:12:56 +00003764 sz = info.nData;
3765 if( !pPage->intKey ) sz += info.nKey;
drh8c42ca92001-06-22 19:15:00 +00003766 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
drh6f11bef2004-05-13 01:12:56 +00003767 memcpy(payload, &pCell[info.nHeader], sz);
drh8c42ca92001-06-22 19:15:00 +00003768 for(j=0; j<sz; j++){
3769 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
3770 }
3771 payload[sz] = 0;
3772 printf(
drh6f11bef2004-05-13 01:12:56 +00003773 "cell %2d: i=%-10s chld=%-4d nk=%-4lld nd=%-4d payload=%s\n",
3774 i, range, child, info.nKey, info.nData, payload
drh8c42ca92001-06-22 19:15:00 +00003775 );
drh8c42ca92001-06-22 19:15:00 +00003776 }
drh4b70f112004-05-02 21:12:19 +00003777 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003778 printf("right_child: %d\n", get4byte(&data[hdr+8]));
drh4b70f112004-05-02 21:12:19 +00003779 }
drh8c42ca92001-06-22 19:15:00 +00003780 nFree = 0;
3781 i = 0;
drhab9f7f12004-05-08 10:56:11 +00003782 idx = get2byte(&data[hdr+1]);
drhb6f41482004-05-14 01:58:11 +00003783 while( idx>0 && idx<pPage->pBt->usableSize ){
drhab9f7f12004-05-08 10:56:11 +00003784 int sz = get2byte(&data[idx+2]);
drh4b70f112004-05-02 21:12:19 +00003785 sprintf(range,"%d..%d", idx, idx+sz-1);
3786 nFree += sz;
drh8c42ca92001-06-22 19:15:00 +00003787 printf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
drh4b70f112004-05-02 21:12:19 +00003788 i, range, sz, nFree);
drhab9f7f12004-05-08 10:56:11 +00003789 idx = get2byte(&data[idx]);
drh2aa679f2001-06-25 02:11:07 +00003790 i++;
drh8c42ca92001-06-22 19:15:00 +00003791 }
3792 if( idx!=0 ){
3793 printf("ERROR: next freeblock index out of range: %d\n", idx);
3794 }
drha34b6762004-05-07 13:30:42 +00003795 if( recursive && !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003796 for(i=0; i<nCell; i++){
3797 unsigned char *pCell = findCell(pPage, i);
3798 sqlite3BtreePageDump(pBt, get4byte(pCell), 1);
drha34b6762004-05-07 13:30:42 +00003799 idx = get2byte(pCell);
drh6019e162001-07-02 17:51:45 +00003800 }
drh43605152004-05-29 21:46:49 +00003801 sqlite3BtreePageDump(pBt, get4byte(&data[hdr+8]), 1);
drh6019e162001-07-02 17:51:45 +00003802 }
drhab9f7f12004-05-08 10:56:11 +00003803 sqlite3pager_unref(data);
drh3644f082004-05-10 18:45:09 +00003804 fflush(stdout);
drh8c42ca92001-06-22 19:15:00 +00003805 return SQLITE_OK;
3806}
drhaaab5722002-02-19 13:39:21 +00003807#endif
drh8c42ca92001-06-22 19:15:00 +00003808
drhaaab5722002-02-19 13:39:21 +00003809#ifdef SQLITE_TEST
drh8c42ca92001-06-22 19:15:00 +00003810/*
drh2aa679f2001-06-25 02:11:07 +00003811** Fill aResult[] with information about the entry and page that the
3812** cursor is pointing to.
3813**
3814** aResult[0] = The page number
3815** aResult[1] = The entry number
3816** aResult[2] = Total number of entries on this page
3817** aResult[3] = Size of this entry
3818** aResult[4] = Number of free bytes on this page
3819** aResult[5] = Number of free blocks on the page
3820** aResult[6] = Page number of the left child of this entry
3821** aResult[7] = Page number of the right child for the whole page
drh5eddca62001-06-30 21:53:53 +00003822**
3823** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00003824*/
drhda200cc2004-05-09 11:51:38 +00003825int sqlite3BtreeCursorInfo(BtCursor *pCur, int *aResult){
drh2aa679f2001-06-25 02:11:07 +00003826 int cnt, idx;
3827 MemPage *pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00003828
3829 pageIntegrity(pPage);
drh4b70f112004-05-02 21:12:19 +00003830 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00003831 aResult[0] = sqlite3pager_pagenumber(pPage->aData);
drh91025292004-05-03 19:49:32 +00003832 assert( aResult[0]==pPage->pgno );
drh8c42ca92001-06-22 19:15:00 +00003833 aResult[1] = pCur->idx;
drh2aa679f2001-06-25 02:11:07 +00003834 aResult[2] = pPage->nCell;
3835 if( pCur->idx>=0 && pCur->idx<pPage->nCell ){
drh43605152004-05-29 21:46:49 +00003836 u8 *pCell = findCell(pPage, pCur->idx);
3837 aResult[3] = cellSizePtr(pPage, pCell);
3838 aResult[6] = pPage->leaf ? 0 : get4byte(pCell);
drh2aa679f2001-06-25 02:11:07 +00003839 }else{
3840 aResult[3] = 0;
3841 aResult[6] = 0;
3842 }
3843 aResult[4] = pPage->nFree;
3844 cnt = 0;
drh4b70f112004-05-02 21:12:19 +00003845 idx = get2byte(&pPage->aData[pPage->hdrOffset+1]);
drhb6f41482004-05-14 01:58:11 +00003846 while( idx>0 && idx<pPage->pBt->usableSize ){
drh2aa679f2001-06-25 02:11:07 +00003847 cnt++;
drh4b70f112004-05-02 21:12:19 +00003848 idx = get2byte(&pPage->aData[idx]);
drh2aa679f2001-06-25 02:11:07 +00003849 }
3850 aResult[5] = cnt;
drh43605152004-05-29 21:46:49 +00003851 aResult[7] = pPage->leaf ? 0 : get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh8c42ca92001-06-22 19:15:00 +00003852 return SQLITE_OK;
3853}
drhaaab5722002-02-19 13:39:21 +00003854#endif
drhdd793422001-06-28 01:54:48 +00003855
drhdd793422001-06-28 01:54:48 +00003856/*
drh5eddca62001-06-30 21:53:53 +00003857** Return the pager associated with a BTree. This routine is used for
3858** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00003859*/
drh3aac2dd2004-04-26 14:10:20 +00003860Pager *sqlite3BtreePager(Btree *pBt){
drhdd793422001-06-28 01:54:48 +00003861 return pBt->pPager;
3862}
drh5eddca62001-06-30 21:53:53 +00003863
3864/*
3865** This structure is passed around through all the sanity checking routines
3866** in order to keep track of some global state information.
3867*/
drhaaab5722002-02-19 13:39:21 +00003868typedef struct IntegrityCk IntegrityCk;
3869struct IntegrityCk {
drh100569d2001-10-02 13:01:48 +00003870 Btree *pBt; /* The tree being checked out */
3871 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
3872 int nPage; /* Number of pages in the database */
3873 int *anRef; /* Number of times each page is referenced */
drh100569d2001-10-02 13:01:48 +00003874 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00003875};
3876
3877/*
3878** Append a message to the error message string.
3879*/
drhaaab5722002-02-19 13:39:21 +00003880static void checkAppendMsg(IntegrityCk *pCheck, char *zMsg1, char *zMsg2){
drh5eddca62001-06-30 21:53:53 +00003881 if( pCheck->zErrMsg ){
3882 char *zOld = pCheck->zErrMsg;
3883 pCheck->zErrMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00003884 sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00003885 sqliteFree(zOld);
3886 }else{
danielk19774adee202004-05-08 08:23:19 +00003887 sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00003888 }
3889}
3890
3891/*
3892** Add 1 to the reference count for page iPage. If this is the second
3893** reference to the page, add an error message to pCheck->zErrMsg.
3894** Return 1 if there are 2 ore more references to the page and 0 if
3895** if this is the first reference to the page.
3896**
3897** Also check that the page number is in bounds.
3898*/
drhaaab5722002-02-19 13:39:21 +00003899static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00003900 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00003901 if( iPage>pCheck->nPage || iPage<0 ){
drh5eddca62001-06-30 21:53:53 +00003902 char zBuf[100];
3903 sprintf(zBuf, "invalid page number %d", iPage);
3904 checkAppendMsg(pCheck, zContext, zBuf);
3905 return 1;
3906 }
3907 if( pCheck->anRef[iPage]==1 ){
3908 char zBuf[100];
3909 sprintf(zBuf, "2nd reference to page %d", iPage);
3910 checkAppendMsg(pCheck, zContext, zBuf);
3911 return 1;
3912 }
3913 return (pCheck->anRef[iPage]++)>1;
3914}
3915
3916/*
3917** Check the integrity of the freelist or of an overflow page list.
3918** Verify that the number of pages on the list is N.
3919*/
drh30e58752002-03-02 20:41:57 +00003920static void checkList(
3921 IntegrityCk *pCheck, /* Integrity checking context */
3922 int isFreeList, /* True for a freelist. False for overflow page list */
3923 int iPage, /* Page number for first page in the list */
3924 int N, /* Expected number of pages in the list */
3925 char *zContext /* Context for error messages */
3926){
3927 int i;
drh3a4c1412004-05-09 20:40:11 +00003928 int expected = N;
3929 int iFirst = iPage;
drh5eddca62001-06-30 21:53:53 +00003930 char zMsg[100];
drh30e58752002-03-02 20:41:57 +00003931 while( N-- > 0 ){
drh4b70f112004-05-02 21:12:19 +00003932 unsigned char *pOvfl;
drh5eddca62001-06-30 21:53:53 +00003933 if( iPage<1 ){
drh3a4c1412004-05-09 20:40:11 +00003934 sprintf(zMsg, "%d of %d pages missing from overflow list starting at %d",
3935 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00003936 checkAppendMsg(pCheck, zContext, zMsg);
3937 break;
3938 }
3939 if( checkRef(pCheck, iPage, zContext) ) break;
drha34b6762004-05-07 13:30:42 +00003940 if( sqlite3pager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
drh5eddca62001-06-30 21:53:53 +00003941 sprintf(zMsg, "failed to get page %d", iPage);
3942 checkAppendMsg(pCheck, zContext, zMsg);
3943 break;
3944 }
drh30e58752002-03-02 20:41:57 +00003945 if( isFreeList ){
drh4b70f112004-05-02 21:12:19 +00003946 int n = get4byte(&pOvfl[4]);
drh0d316a42002-08-11 20:10:47 +00003947 for(i=0; i<n; i++){
drh4b70f112004-05-02 21:12:19 +00003948 checkRef(pCheck, get4byte(&pOvfl[8+i*4]), zContext);
drh30e58752002-03-02 20:41:57 +00003949 }
drh0d316a42002-08-11 20:10:47 +00003950 N -= n;
drh30e58752002-03-02 20:41:57 +00003951 }
drh4b70f112004-05-02 21:12:19 +00003952 iPage = get4byte(pOvfl);
drha34b6762004-05-07 13:30:42 +00003953 sqlite3pager_unref(pOvfl);
drh5eddca62001-06-30 21:53:53 +00003954 }
3955}
3956
3957/*
3958** Do various sanity checks on a single page of a tree. Return
3959** the tree depth. Root pages return 0. Parents of root pages
3960** return 1, and so forth.
3961**
3962** These checks are done:
3963**
3964** 1. Make sure that cells and freeblocks do not overlap
3965** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00003966** NO 2. Make sure cell keys are in order.
3967** NO 3. Make sure no key is less than or equal to zLowerBound.
3968** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00003969** 5. Check the integrity of overflow pages.
3970** 6. Recursively call checkTreePage on all children.
3971** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00003972** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00003973** the root of the tree.
3974*/
3975static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00003976 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00003977 int iPage, /* Page number of the page to check */
3978 MemPage *pParent, /* Parent page */
3979 char *zParentContext, /* Parent context */
3980 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00003981 int nLower, /* Number of characters in zLowerBound */
3982 char *zUpperBound, /* All keys should be less than this, if not NULL */
3983 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00003984){
3985 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00003986 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00003987 int hdr, cellStart;
3988 int nCell;
drhda200cc2004-05-09 11:51:38 +00003989 u8 *data;
drh5eddca62001-06-30 21:53:53 +00003990 BtCursor cur;
drh0d316a42002-08-11 20:10:47 +00003991 Btree *pBt;
drhb6f41482004-05-14 01:58:11 +00003992 int maxLocal, usableSize;
drh5eddca62001-06-30 21:53:53 +00003993 char zMsg[100];
3994 char zContext[100];
drhda200cc2004-05-09 11:51:38 +00003995 char hit[MX_PAGE_SIZE];
drh5eddca62001-06-30 21:53:53 +00003996
3997 /* Check that the page exists
3998 */
drh0d316a42002-08-11 20:10:47 +00003999 cur.pBt = pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00004000 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00004001 if( iPage==0 ) return 0;
4002 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh4b70f112004-05-02 21:12:19 +00004003 if( (rc = getPage(pBt, (Pgno)iPage, &pPage))!=0 ){
drh5eddca62001-06-30 21:53:53 +00004004 sprintf(zMsg, "unable to get the page. error code=%d", rc);
4005 checkAppendMsg(pCheck, zContext, zMsg);
4006 return 0;
4007 }
drh6f11bef2004-05-13 01:12:56 +00004008 maxLocal = pPage->leafData ? pBt->maxLeaf : pBt->maxLocal;
drh4b70f112004-05-02 21:12:19 +00004009 if( (rc = initPage(pPage, pParent))!=0 ){
drh5eddca62001-06-30 21:53:53 +00004010 sprintf(zMsg, "initPage() returns error code %d", rc);
4011 checkAppendMsg(pCheck, zContext, zMsg);
drh91025292004-05-03 19:49:32 +00004012 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00004013 return 0;
4014 }
4015
4016 /* Check out all the cells.
4017 */
4018 depth = 0;
drh5eddca62001-06-30 21:53:53 +00004019 cur.pPage = pPage;
drh5eddca62001-06-30 21:53:53 +00004020 for(i=0; i<pPage->nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00004021 u8 *pCell;
4022 int sz;
4023 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00004024
4025 /* Check payload overflow pages
4026 */
drh3a4c1412004-05-09 20:40:11 +00004027 sprintf(zContext, "On tree page %d cell %d: ", iPage, i);
drh43605152004-05-29 21:46:49 +00004028 pCell = findCell(pPage,i);
4029 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004030 sz = info.nData;
4031 if( !pPage->intKey ) sz += info.nKey;
4032 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00004033 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +00004034 checkList(pCheck, 0, get4byte(&pCell[info.iOverflow]),nPage,zContext);
drh5eddca62001-06-30 21:53:53 +00004035 }
4036
4037 /* Check sanity of left child page.
4038 */
drhda200cc2004-05-09 11:51:38 +00004039 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004040 pgno = get4byte(pCell);
drhda200cc2004-05-09 11:51:38 +00004041 d2 = checkTreePage(pCheck,pgno,pPage,zContext,0,0,0,0);
4042 if( i>0 && d2!=depth ){
4043 checkAppendMsg(pCheck, zContext, "Child page depth differs");
4044 }
4045 depth = d2;
drh5eddca62001-06-30 21:53:53 +00004046 }
drh5eddca62001-06-30 21:53:53 +00004047 }
drhda200cc2004-05-09 11:51:38 +00004048 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004049 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drhda200cc2004-05-09 11:51:38 +00004050 sprintf(zContext, "On page %d at right child: ", iPage);
4051 checkTreePage(pCheck, pgno, pPage, zContext,0,0,0,0);
4052 }
drh5eddca62001-06-30 21:53:53 +00004053
4054 /* Check for complete coverage of the page
4055 */
drhda200cc2004-05-09 11:51:38 +00004056 data = pPage->aData;
4057 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00004058 memset(hit, 0, usableSize);
4059 memset(hit, 1, get2byte(&data[hdr+5]));
4060 nCell = get2byte(&data[hdr+3]);
4061 cellStart = hdr + 12 - 4*pPage->leaf;
4062 for(i=0; i<nCell; i++){
4063 int pc = get2byte(&data[cellStart+i*2]);
4064 int size = cellSizePtr(pPage, &data[pc]);
drh5eddca62001-06-30 21:53:53 +00004065 int j;
drh43605152004-05-29 21:46:49 +00004066 for(j=pc+size-1; j>=pc; j--) hit[j]++;
drh5eddca62001-06-30 21:53:53 +00004067 }
drhb6f41482004-05-14 01:58:11 +00004068 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000; cnt++){
drhda200cc2004-05-09 11:51:38 +00004069 int size = get2byte(&data[i+2]);
drh5eddca62001-06-30 21:53:53 +00004070 int j;
drhda200cc2004-05-09 11:51:38 +00004071 for(j=i+size-1; j>=i; j--) hit[j]++;
4072 i = get2byte(&data[i]);
drh5eddca62001-06-30 21:53:53 +00004073 }
drhb6f41482004-05-14 01:58:11 +00004074 for(i=cnt=0; i<usableSize; i++){
drh5eddca62001-06-30 21:53:53 +00004075 if( hit[i]==0 ){
drhda200cc2004-05-09 11:51:38 +00004076 cnt++;
drh5eddca62001-06-30 21:53:53 +00004077 }else if( hit[i]>1 ){
4078 sprintf(zMsg, "Multiple uses for byte %d of page %d", i, iPage);
4079 checkAppendMsg(pCheck, zMsg, 0);
4080 break;
4081 }
4082 }
drh43605152004-05-29 21:46:49 +00004083 if( cnt!=data[hdr+7] ){
drhda200cc2004-05-09 11:51:38 +00004084 sprintf(zMsg, "Fragmented space is %d byte reported as %d on page %d",
drh43605152004-05-29 21:46:49 +00004085 cnt, data[hdr+7], iPage);
drhda200cc2004-05-09 11:51:38 +00004086 checkAppendMsg(pCheck, zMsg, 0);
4087 }
drh6019e162001-07-02 17:51:45 +00004088
drh4b70f112004-05-02 21:12:19 +00004089 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00004090 return depth+1;
drh5eddca62001-06-30 21:53:53 +00004091}
4092
4093/*
4094** This routine does a complete check of the given BTree file. aRoot[] is
4095** an array of pages numbers were each page number is the root page of
4096** a table. nRoot is the number of entries in aRoot.
4097**
4098** If everything checks out, this routine returns NULL. If something is
4099** amiss, an error message is written into memory obtained from malloc()
4100** and a pointer to that error message is returned. The calling function
4101** is responsible for freeing the error message when it is done.
4102*/
drh3aac2dd2004-04-26 14:10:20 +00004103char *sqlite3BtreeIntegrityCheck(Btree *pBt, int *aRoot, int nRoot){
drh5eddca62001-06-30 21:53:53 +00004104 int i;
4105 int nRef;
drhaaab5722002-02-19 13:39:21 +00004106 IntegrityCk sCheck;
drh5eddca62001-06-30 21:53:53 +00004107
drha34b6762004-05-07 13:30:42 +00004108 nRef = *sqlite3pager_stats(pBt->pPager);
drhefc251d2001-07-01 22:12:01 +00004109 if( lockBtree(pBt)!=SQLITE_OK ){
4110 return sqliteStrDup("Unable to acquire a read lock on the database");
4111 }
drh5eddca62001-06-30 21:53:53 +00004112 sCheck.pBt = pBt;
4113 sCheck.pPager = pBt->pPager;
drha34b6762004-05-07 13:30:42 +00004114 sCheck.nPage = sqlite3pager_pagecount(sCheck.pPager);
drh0de8c112002-07-06 16:32:14 +00004115 if( sCheck.nPage==0 ){
4116 unlockBtreeIfUnused(pBt);
4117 return 0;
4118 }
drh8c1238a2003-01-02 14:43:55 +00004119 sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
drhda200cc2004-05-09 11:51:38 +00004120 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh5eddca62001-06-30 21:53:53 +00004121 sCheck.zErrMsg = 0;
4122
4123 /* Check the integrity of the freelist
4124 */
drha34b6762004-05-07 13:30:42 +00004125 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
4126 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00004127
4128 /* Check all the tables.
4129 */
4130 for(i=0; i<nRoot; i++){
drh4ff6dfa2002-03-03 23:06:00 +00004131 if( aRoot[i]==0 ) continue;
drh1bffb9c2002-02-03 17:37:36 +00004132 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00004133 }
4134
4135 /* Make sure every page in the file is referenced
4136 */
4137 for(i=1; i<=sCheck.nPage; i++){
4138 if( sCheck.anRef[i]==0 ){
4139 char zBuf[100];
4140 sprintf(zBuf, "Page %d is never used", i);
4141 checkAppendMsg(&sCheck, zBuf, 0);
4142 }
4143 }
4144
4145 /* Make sure this analysis did not leave any unref() pages
4146 */
drh5e00f6c2001-09-13 13:46:56 +00004147 unlockBtreeIfUnused(pBt);
drha34b6762004-05-07 13:30:42 +00004148 if( nRef != *sqlite3pager_stats(pBt->pPager) ){
drh5eddca62001-06-30 21:53:53 +00004149 char zBuf[100];
4150 sprintf(zBuf,
4151 "Outstanding page count goes from %d to %d during this analysis",
drha34b6762004-05-07 13:30:42 +00004152 nRef, *sqlite3pager_stats(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00004153 );
4154 checkAppendMsg(&sCheck, zBuf, 0);
4155 }
4156
4157 /* Clean up and report errors.
4158 */
4159 sqliteFree(sCheck.anRef);
4160 return sCheck.zErrMsg;
4161}
paulb95a8862003-04-01 21:16:41 +00004162
drh73509ee2003-04-06 20:44:45 +00004163/*
4164** Return the full pathname of the underlying database file.
4165*/
drh3aac2dd2004-04-26 14:10:20 +00004166const char *sqlite3BtreeGetFilename(Btree *pBt){
drh73509ee2003-04-06 20:44:45 +00004167 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00004168 return sqlite3pager_filename(pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00004169}
4170
4171/*
drhf7c57532003-04-25 13:22:51 +00004172** Copy the complete content of pBtFrom into pBtTo. A transaction
4173** must be active for both files.
4174**
4175** The size of file pBtFrom may be reduced by this operation.
drh43605152004-05-29 21:46:49 +00004176** If anything goes wrong, the transaction on pBtFrom is rolled back.
drh73509ee2003-04-06 20:44:45 +00004177*/
drh3aac2dd2004-04-26 14:10:20 +00004178int sqlite3BtreeCopyFile(Btree *pBtTo, Btree *pBtFrom){
drhf7c57532003-04-25 13:22:51 +00004179 int rc = SQLITE_OK;
drh2e6d11b2003-04-25 15:37:57 +00004180 Pgno i, nPage, nToPage;
drhf7c57532003-04-25 13:22:51 +00004181
danielk1977ee5741e2004-05-31 10:01:34 +00004182 if( pBtTo->inTrans!=TRANS_WRITE || pBtFrom->inTrans!=TRANS_WRITE ){
4183 return SQLITE_ERROR;
4184 }
drhf7c57532003-04-25 13:22:51 +00004185 if( pBtTo->pCursor ) return SQLITE_BUSY;
drh465407d2004-05-20 02:01:26 +00004186 memcpy(pBtTo->pPage1->aData, pBtFrom->pPage1->aData, pBtFrom->usableSize);
4187 rc = sqlite3pager_overwrite(pBtTo->pPager, 1, pBtFrom->pPage1->aData);
drha34b6762004-05-07 13:30:42 +00004188 nToPage = sqlite3pager_pagecount(pBtTo->pPager);
4189 nPage = sqlite3pager_pagecount(pBtFrom->pPager);
drh2e6d11b2003-04-25 15:37:57 +00004190 for(i=2; rc==SQLITE_OK && i<=nPage; i++){
drhf7c57532003-04-25 13:22:51 +00004191 void *pPage;
drha34b6762004-05-07 13:30:42 +00004192 rc = sqlite3pager_get(pBtFrom->pPager, i, &pPage);
drhf7c57532003-04-25 13:22:51 +00004193 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00004194 rc = sqlite3pager_overwrite(pBtTo->pPager, i, pPage);
drh2e6d11b2003-04-25 15:37:57 +00004195 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00004196 sqlite3pager_unref(pPage);
drhf7c57532003-04-25 13:22:51 +00004197 }
drh2e6d11b2003-04-25 15:37:57 +00004198 for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
4199 void *pPage;
drha34b6762004-05-07 13:30:42 +00004200 rc = sqlite3pager_get(pBtTo->pPager, i, &pPage);
drh2e6d11b2003-04-25 15:37:57 +00004201 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00004202 rc = sqlite3pager_write(pPage);
4203 sqlite3pager_unref(pPage);
4204 sqlite3pager_dont_write(pBtTo->pPager, i);
drh2e6d11b2003-04-25 15:37:57 +00004205 }
4206 if( !rc && nPage<nToPage ){
drha34b6762004-05-07 13:30:42 +00004207 rc = sqlite3pager_truncate(pBtTo->pPager, nPage);
drh2e6d11b2003-04-25 15:37:57 +00004208 }
drhf7c57532003-04-25 13:22:51 +00004209 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00004210 sqlite3BtreeRollback(pBtTo);
drhf7c57532003-04-25 13:22:51 +00004211 }
4212 return rc;
drh73509ee2003-04-06 20:44:45 +00004213}
danielk19771d850a72004-05-31 08:26:49 +00004214
4215/*
4216** Return non-zero if a transaction is active.
4217*/
4218int sqlite3BtreeIsInTrans(Btree *pBt){
danielk1977ee5741e2004-05-31 10:01:34 +00004219 return (pBt && (pBt->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00004220}
4221
4222/*
4223** Return non-zero if a statement transaction is active.
4224*/
4225int sqlite3BtreeIsInStmt(Btree *pBt){
4226 return (pBt && pBt->inStmt);
4227}
danielk197713adf8a2004-06-03 16:08:41 +00004228
4229/*
4230** This call is a no-op if no write-transaction is currently active on pBt.
4231**
4232** Otherwise, sync the database file for the btree pBt. zMaster points to
4233** the name of a master journal file that should be written into the
4234** individual journal file, or is NULL, indicating no master journal file
4235** (single database transaction).
4236**
4237** When this is called, the master journal should already have been
4238** created, populated with this journal pointer and synced to disk.
4239**
4240** Once this is routine has returned, the only thing required to commit
4241** the write-transaction for this database file is to delete the journal.
4242*/
4243int sqlite3BtreeSync(Btree *pBt, const char *zMaster){
4244 if( pBt->inTrans==TRANS_WRITE ){
4245 return sqlite3pager_sync(pBt->pPager, zMaster);
4246 }
4247 return SQLITE_OK;
4248}
4249
4250