blob: d21324e564011b2466a94fec5b7f87a33b414425 [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*************************************************************************
danielk1977ac11ee62005-01-15 12:45:51 +000012** $Id: btree.c,v 1.234 2005/01/15 12:45:51 danielk1977 Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
15** For a detailed discussion of BTrees, refer to
16**
17** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
18** "Sorting And Searching", pages 473-480. Addison-Wesley
19** Publishing Company, Reading, Massachusetts.
20**
21** The basic idea is that each page of the file contains N database
22** entries and N+1 pointers to subpages.
23**
24** ----------------------------------------------------------------
25** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N) | Ptr(N+1) |
26** ----------------------------------------------------------------
27**
28** All of the keys on the page that Ptr(0) points to have values less
29** than Key(0). All of the keys on page Ptr(1) and its subpages have
30** values greater than Key(0) and less than Key(1). All of the keys
31** on Ptr(N+1) and its subpages have values greater than Key(N). And
32** so forth.
33**
drh5e00f6c2001-09-13 13:46:56 +000034** Finding a particular key requires reading O(log(M)) pages from the
35** disk where M is the number of entries in the tree.
drh8b2f49b2001-06-08 00:21:52 +000036**
37** In this implementation, a single file can hold one or more separate
38** BTrees. Each BTree is identified by the index of its root page. The
drh9e572e62004-04-23 23:43:10 +000039** key and data for any entry are combined to form the "payload". A
40** fixed amount of payload can be carried directly on the database
41** page. If the payload is larger than the preset amount then surplus
42** bytes are stored on overflow pages. The payload for an entry
43** and the preceding pointer are combined to form a "Cell". Each
44** page has a small header which contains the Ptr(N+1) pointer and other
45** information such as the size of key and data.
drh8b2f49b2001-06-08 00:21:52 +000046**
drh9e572e62004-04-23 23:43:10 +000047** FORMAT DETAILS
48**
49** The file is divided into pages. The first page is called page 1,
50** the second is page 2, and so forth. A page number of zero indicates
51** "no such page". The page size can be anything between 512 and 65536.
52** Each page can be either a btree page, a freelist page or an overflow
53** page.
54**
55** The first page is always a btree page. The first 100 bytes of the first
drh271efa52004-05-30 19:19:05 +000056** page contain a special header (the "file header") that describes the file.
57** The format of the file header is as follows:
drh9e572e62004-04-23 23:43:10 +000058**
59** OFFSET SIZE DESCRIPTION
drhde647132004-05-07 17:57:49 +000060** 0 16 Header string: "SQLite format 3\000"
drh9e572e62004-04-23 23:43:10 +000061** 16 2 Page size in bytes.
62** 18 1 File format write version
63** 19 1 File format read version
drh6f11bef2004-05-13 01:12:56 +000064** 20 1 Bytes of unused space at the end of each page
65** 21 1 Max embedded payload fraction
66** 22 1 Min embedded payload fraction
67** 23 1 Min leaf payload fraction
68** 24 4 File change counter
69** 28 4 Reserved for future use
drh9e572e62004-04-23 23:43:10 +000070** 32 4 First freelist page
71** 36 4 Number of freelist pages in the file
72** 40 60 15 4-byte meta values passed to higher layers
73**
74** All of the integer values are big-endian (most significant byte first).
drh6f11bef2004-05-13 01:12:56 +000075**
drhab01f612004-05-22 02:55:23 +000076** The file change counter is incremented when the database is changed more
drh6f11bef2004-05-13 01:12:56 +000077** than once within the same second. This counter, together with the
78** modification time of the file, allows other processes to know
79** when the file has changed and thus when they need to flush their
80** cache.
81**
82** The max embedded payload fraction is the amount of the total usable
83** space in a page that can be consumed by a single cell for standard
84** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
85** is to limit the maximum cell size so that at least 4 cells will fit
drhab01f612004-05-22 02:55:23 +000086** on one page. Thus the default max embedded payload fraction is 64.
drh6f11bef2004-05-13 01:12:56 +000087**
88** If the payload for a cell is larger than the max payload, then extra
89** payload is spilled to overflow pages. Once an overflow page is allocated,
90** as many bytes as possible are moved into the overflow pages without letting
91** the cell size drop below the min embedded payload fraction.
92**
93** The min leaf payload fraction is like the min embedded payload fraction
94** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
95** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
96** not specified in the header.
drh9e572e62004-04-23 23:43:10 +000097**
drh43605152004-05-29 21:46:49 +000098** Each btree pages is divided into three sections: The header, the
99** cell pointer array, and the cell area area. Page 1 also has a 100-byte
drh271efa52004-05-30 19:19:05 +0000100** file header that occurs before the page header.
101**
102** |----------------|
103** | file header | 100 bytes. Page 1 only.
104** |----------------|
105** | page header | 8 bytes for leaves. 12 bytes for interior nodes
106** |----------------|
107** | cell pointer | | 2 bytes per cell. Sorted order.
108** | array | | Grows downward
109** | | v
110** |----------------|
111** | unallocated |
112** | space |
113** |----------------| ^ Grows upwards
114** | cell content | | Arbitrary order interspersed with freeblocks.
115** | area | | and free space fragments.
116** |----------------|
drh43605152004-05-29 21:46:49 +0000117**
118** The page headers looks like this:
drh9e572e62004-04-23 23:43:10 +0000119**
120** OFFSET SIZE DESCRIPTION
drh6f11bef2004-05-13 01:12:56 +0000121** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
drh9e572e62004-04-23 23:43:10 +0000122** 1 2 byte offset to the first freeblock
drh43605152004-05-29 21:46:49 +0000123** 3 2 number of cells on this page
drh271efa52004-05-30 19:19:05 +0000124** 5 2 first byte of the cell content area
drh43605152004-05-29 21:46:49 +0000125** 7 1 number of fragmented free bytes
drh271efa52004-05-30 19:19:05 +0000126** 8 4 Right child (the Ptr(N+1) value). Omitted on leaves.
drh9e572e62004-04-23 23:43:10 +0000127**
128** The flags define the format of this btree page. The leaf flag means that
129** this page has no children. The zerodata flag means that this page carries
drh44f87bd2004-09-27 13:19:51 +0000130** only keys and no data. The intkey flag means that the key is a integer
131** which is stored in the key size entry of the cell header rather than in
132** the payload area.
drh9e572e62004-04-23 23:43:10 +0000133**
drh43605152004-05-29 21:46:49 +0000134** The cell pointer array begins on the first byte after the page header.
135** The cell pointer array contains zero or more 2-byte numbers which are
136** offsets from the beginning of the page to the cell content in the cell
137** content area. The cell pointers occur in sorted order. The system strives
138** to keep free space after the last cell pointer so that new cells can
drh44f87bd2004-09-27 13:19:51 +0000139** be easily added without having to defragment the page.
drh43605152004-05-29 21:46:49 +0000140**
141** Cell content is stored at the very end of the page and grows toward the
142** beginning of the page.
143**
144** Unused space within the cell content area is collected into a linked list of
145** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
146** to the first freeblock is given in the header. Freeblocks occur in
147** increasing order. Because a freeblock must be at least 4 bytes in size,
148** any group of 3 or fewer unused bytes in the cell content area cannot
149** exist on the freeblock chain. A group of 3 or fewer free bytes is called
150** a fragment. The total number of bytes in all fragments is recorded.
151** in the page header at offset 7.
152**
153** SIZE DESCRIPTION
154** 2 Byte offset of the next freeblock
155** 2 Bytes in this freeblock
156**
157** Cells are of variable length. Cells are stored in the cell content area at
158** the end of the page. Pointers to the cells are in the cell pointer array
159** that immediately follows the page header. Cells is not necessarily
160** contiguous or in order, but cell pointers are contiguous and in order.
161**
162** Cell content makes use of variable length integers. A variable
163** length integer is 1 to 9 bytes where the lower 7 bits of each
drh9e572e62004-04-23 23:43:10 +0000164** byte are used. The integer consists of all bytes that have bit 8 set and
drh6f11bef2004-05-13 01:12:56 +0000165** the first byte with bit 8 clear. The most significant byte of the integer
drhab01f612004-05-22 02:55:23 +0000166** appears first. A variable-length integer may not be more than 9 bytes long.
167** As a special case, all 8 bytes of the 9th byte are used as data. This
168** allows a 64-bit integer to be encoded in 9 bytes.
drh9e572e62004-04-23 23:43:10 +0000169**
170** 0x00 becomes 0x00000000
drh6f11bef2004-05-13 01:12:56 +0000171** 0x7f becomes 0x0000007f
172** 0x81 0x00 becomes 0x00000080
173** 0x82 0x00 becomes 0x00000100
174** 0x80 0x7f becomes 0x0000007f
175** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
drh9e572e62004-04-23 23:43:10 +0000176** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
177**
178** Variable length integers are used for rowids and to hold the number of
179** bytes of key and data in a btree cell.
180**
drh43605152004-05-29 21:46:49 +0000181** The content of a cell looks like this:
drh9e572e62004-04-23 23:43:10 +0000182**
183** SIZE DESCRIPTION
drh3aac2dd2004-04-26 14:10:20 +0000184** 4 Page number of the left child. Omitted if leaf flag is set.
185** var Number of bytes of data. Omitted if the zerodata flag is set.
186** var Number of bytes of key. Or the key itself if intkey flag is set.
drh9e572e62004-04-23 23:43:10 +0000187** * Payload
188** 4 First page of the overflow chain. Omitted if no overflow
189**
190** Overflow pages form a linked list. Each page except the last is completely
191** filled with data (pagesize - 4 bytes). The last page can have as little
192** as 1 byte of data.
193**
194** SIZE DESCRIPTION
195** 4 Page number of next overflow page
196** * Data
197**
198** Freelist pages come in two subtypes: trunk pages and leaf pages. The
199** file header points to first in a linked list of trunk page. Each trunk
200** page points to multiple leaf pages. The content of a leaf page is
201** unspecified. A trunk page looks like this:
202**
203** SIZE DESCRIPTION
204** 4 Page number of next trunk page
205** 4 Number of leaf pointers on this page
206** * zero or more pages numbers of leaves
drha059ad02001-04-17 20:09:11 +0000207*/
208#include "sqliteInt.h"
209#include "pager.h"
210#include "btree.h"
drh1f595712004-06-15 01:40:29 +0000211#include "os.h"
drha059ad02001-04-17 20:09:11 +0000212#include <assert.h>
213
drh887dc4c2004-10-22 16:22:57 +0000214/*
215** This macro rounds values up so that if the value is an address it
216** is guaranteed to be an address that is aligned to an 8-byte boundary.
217*/
218#define FORCE_ALIGNMENT(X) (((X)+7)&~7)
drh4b70f112004-05-02 21:12:19 +0000219
drh4b70f112004-05-02 21:12:19 +0000220/* The following value is the maximum cell size assuming a maximum page
221** size give above.
222*/
drh2e38c322004-09-03 18:38:44 +0000223#define MX_CELL_SIZE(pBt) (pBt->pageSize-8)
drh4b70f112004-05-02 21:12:19 +0000224
225/* The maximum number of cells on a single page of the database. This
226** assumes a minimum cell size of 3 bytes. Such small cells will be
227** exceedingly rare, but they are possible.
228*/
drh2e38c322004-09-03 18:38:44 +0000229#define MX_CELL(pBt) ((pBt->pageSize-8)/3)
drh4b70f112004-05-02 21:12:19 +0000230
paulb95a8862003-04-01 21:16:41 +0000231/* Forward declarations */
drh3aac2dd2004-04-26 14:10:20 +0000232typedef struct MemPage MemPage;
paulb95a8862003-04-01 21:16:41 +0000233
drh8c42ca92001-06-22 19:15:00 +0000234/*
drhbd03cae2001-06-02 02:40:57 +0000235** This is a magic string that appears at the beginning of every
drh8c42ca92001-06-22 19:15:00 +0000236** SQLite database in order to identify the file as a real database.
drhde647132004-05-07 17:57:49 +0000237** 123456789 123456 */
238static const char zMagicHeader[] = "SQLite format 3";
drh08ed44e2001-04-29 23:32:55 +0000239
240/*
drh4b70f112004-05-02 21:12:19 +0000241** Page type flags. An ORed combination of these flags appear as the
242** first byte of every BTree page.
drh8c42ca92001-06-22 19:15:00 +0000243*/
drhde647132004-05-07 17:57:49 +0000244#define PTF_INTKEY 0x01
drh9e572e62004-04-23 23:43:10 +0000245#define PTF_ZERODATA 0x02
drh8b18dd42004-05-12 19:18:15 +0000246#define PTF_LEAFDATA 0x04
247#define PTF_LEAF 0x08
drh8c42ca92001-06-22 19:15:00 +0000248
249/*
drh9e572e62004-04-23 23:43:10 +0000250** As each page of the file is loaded into memory, an instance of the following
251** structure is appended and initialized to zero. This structure stores
252** information about the page that is decoded from the raw file page.
drh14acc042001-06-10 19:56:58 +0000253**
drh72f82862001-05-24 21:06:34 +0000254** The pParent field points back to the parent page. This allows us to
255** walk up the BTree from any leaf to the root. Care must be taken to
256** unref() the parent page pointer when this page is no longer referenced.
drhbd03cae2001-06-02 02:40:57 +0000257** The pageDestructor() routine handles that chore.
drh7e3b0a02001-04-28 16:52:40 +0000258*/
259struct MemPage {
drha6abd042004-06-09 17:37:22 +0000260 u8 isInit; /* True if previously initialized. MUST BE FIRST! */
drh43605152004-05-29 21:46:49 +0000261 u8 idxShift; /* True if Cell indices have changed */
262 u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
263 u8 intKey; /* True if intkey flag is set */
264 u8 leaf; /* True if leaf flag is set */
265 u8 zeroData; /* True if table stores keys only */
266 u8 leafData; /* True if tables stores data on leaves only */
267 u8 hasData; /* True if this page stores data */
268 u8 hdrOffset; /* 100 for page 1. 0 otherwise */
drh271efa52004-05-30 19:19:05 +0000269 u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
drha2fce642004-06-05 00:01:44 +0000270 u16 maxLocal; /* Copy of Btree.maxLocal or Btree.maxLeaf */
271 u16 minLocal; /* Copy of Btree.minLocal or Btree.minLeaf */
drh43605152004-05-29 21:46:49 +0000272 u16 cellOffset; /* Index in aData of first cell pointer */
273 u16 idxParent; /* Index in parent of this node */
274 u16 nFree; /* Number of free bytes on the page */
275 u16 nCell; /* Number of cells on this page, local and ovfl */
276 struct _OvflCell { /* Cells that will not fit on aData[] */
277 u8 *pCell; /* Pointers to the body of the overflow cell */
278 u16 idx; /* Insert this cell before idx-th non-overflow cell */
drha2fce642004-06-05 00:01:44 +0000279 } aOvfl[5];
drh43605152004-05-29 21:46:49 +0000280 struct Btree *pBt; /* Pointer back to BTree structure */
281 u8 *aData; /* Pointer back to the start of the page */
282 Pgno pgno; /* Page number for this page */
283 MemPage *pParent; /* The parent of this page. NULL for root */
drh8c42ca92001-06-22 19:15:00 +0000284};
drh7e3b0a02001-04-28 16:52:40 +0000285
286/*
drh3b7511c2001-05-26 13:15:44 +0000287** The in-memory image of a disk page has the auxiliary information appended
288** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
289** that extra information.
290*/
drh3aac2dd2004-04-26 14:10:20 +0000291#define EXTRA_SIZE sizeof(MemPage)
drh3b7511c2001-05-26 13:15:44 +0000292
293/*
drha059ad02001-04-17 20:09:11 +0000294** Everything we need to know about an open database
295*/
296struct Btree {
297 Pager *pPager; /* The page cache */
drh306dc212001-05-21 13:45:10 +0000298 BtCursor *pCursor; /* A list of all open cursors */
drh3aac2dd2004-04-26 14:10:20 +0000299 MemPage *pPage1; /* First page of the database */
drh663fc632002-02-02 18:49:19 +0000300 u8 inTrans; /* True if a transaction is in progress */
drhab01f612004-05-22 02:55:23 +0000301 u8 inStmt; /* True if we are in a statement subtransaction */
drh5df72a52002-06-06 23:16:05 +0000302 u8 readOnly; /* True if the underlying file is readonly */
drhab01f612004-05-22 02:55:23 +0000303 u8 maxEmbedFrac; /* Maximum payload as % of total page size */
304 u8 minEmbedFrac; /* Minimum payload as % of total page size */
305 u8 minLeafFrac; /* Minimum leaf payload as % of total page size */
drh90f5ecb2004-07-22 01:19:35 +0000306 u8 pageSizeFixed; /* True if the page size can no longer be changed */
drha2fce642004-06-05 00:01:44 +0000307 u16 pageSize; /* Total number of bytes on a page */
drh887dc4c2004-10-22 16:22:57 +0000308 u16 psAligned; /* pageSize rounded up to a multiple of 8 */
drha2fce642004-06-05 00:01:44 +0000309 u16 usableSize; /* Number of usable bytes on each page */
drh6f11bef2004-05-13 01:12:56 +0000310 int maxLocal; /* Maximum local payload in non-LEAFDATA tables */
311 int minLocal; /* Minimum local payload in non-LEAFDATA tables */
312 int maxLeaf; /* Maximum local payload in a LEAFDATA table */
313 int minLeaf; /* Minimum local payload in a LEAFDATA table */
danielk1977afcdd022004-10-31 16:25:42 +0000314#ifndef SQLITE_OMIT_AUTOVACUUM
315 u8 autoVacuum; /* True if database supports auto-vacuum */
316#endif
drha059ad02001-04-17 20:09:11 +0000317};
318typedef Btree Bt;
319
drh365d68f2001-05-11 11:02:46 +0000320/*
danielk1977ee5741e2004-05-31 10:01:34 +0000321** Btree.inTrans may take one of the following values.
322*/
323#define TRANS_NONE 0
324#define TRANS_READ 1
325#define TRANS_WRITE 2
326
327/*
drhfa1a98a2004-05-14 19:08:17 +0000328** An instance of the following structure is used to hold information
drh271efa52004-05-30 19:19:05 +0000329** about a cell. The parseCellPtr() function fills in this structure
drhab01f612004-05-22 02:55:23 +0000330** based on information extract from the raw disk page.
drhfa1a98a2004-05-14 19:08:17 +0000331*/
332typedef struct CellInfo CellInfo;
333struct CellInfo {
drh43605152004-05-29 21:46:49 +0000334 u8 *pCell; /* Pointer to the start of cell content */
drhfa1a98a2004-05-14 19:08:17 +0000335 i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
336 u32 nData; /* Number of bytes of data */
drh271efa52004-05-30 19:19:05 +0000337 u16 nHeader; /* Size of the cell content header in bytes */
drhfa1a98a2004-05-14 19:08:17 +0000338 u16 nLocal; /* Amount of payload held locally */
drhab01f612004-05-22 02:55:23 +0000339 u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
drh271efa52004-05-30 19:19:05 +0000340 u16 nSize; /* Size of the cell content on the main b-tree page */
drhfa1a98a2004-05-14 19:08:17 +0000341};
342
343/*
drh365d68f2001-05-11 11:02:46 +0000344** A cursor is a pointer to a particular entry in the BTree.
345** The entry is identified by its MemPage and the index in
drha34b6762004-05-07 13:30:42 +0000346** MemPage.aCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000347*/
drh72f82862001-05-24 21:06:34 +0000348struct BtCursor {
drh5e2f8b92001-05-28 00:41:15 +0000349 Btree *pBt; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000350 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
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 */
drh365d68f2001-05-11 11:02:46 +0000359};
drh7e3b0a02001-04-28 16:52:40 +0000360
drha059ad02001-04-17 20:09:11 +0000361/*
drh66cbd152004-09-01 16:12:25 +0000362** Forward declaration
363*/
364static int checkReadLocks(Btree*,Pgno,BtCursor*);
365
366
367/*
drhab01f612004-05-22 02:55:23 +0000368** Read or write a two- and four-byte big-endian integer values.
drh0d316a42002-08-11 20:10:47 +0000369*/
drh9e572e62004-04-23 23:43:10 +0000370static u32 get2byte(unsigned char *p){
371 return (p[0]<<8) | p[1];
drh0d316a42002-08-11 20:10:47 +0000372}
drh9e572e62004-04-23 23:43:10 +0000373static u32 get4byte(unsigned char *p){
374 return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
375}
drh9e572e62004-04-23 23:43:10 +0000376static void put2byte(unsigned char *p, u32 v){
377 p[0] = v>>8;
378 p[1] = v;
379}
380static void put4byte(unsigned char *p, u32 v){
381 p[0] = v>>24;
382 p[1] = v>>16;
383 p[2] = v>>8;
384 p[3] = v;
385}
drh6f11bef2004-05-13 01:12:56 +0000386
drh9e572e62004-04-23 23:43:10 +0000387/*
drhab01f612004-05-22 02:55:23 +0000388** Routines to read and write variable-length integers. These used to
389** be defined locally, but now we use the varint routines in the util.c
390** file.
drh9e572e62004-04-23 23:43:10 +0000391*/
drh6d2fb152004-05-14 16:50:06 +0000392#define getVarint sqlite3GetVarint
393#define getVarint32 sqlite3GetVarint32
394#define putVarint sqlite3PutVarint
drh0d316a42002-08-11 20:10:47 +0000395
danielk1977599fcba2004-11-08 07:13:13 +0000396/* The database page the PENDING_BYTE occupies. This page is never used.
397** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
398** should possibly be consolidated (presumably in pager.h).
399*/
400#define PENDING_BYTE_PAGE(pBt) ((PENDING_BYTE/(pBt)->pageSize)+1)
danielk1977afcdd022004-10-31 16:25:42 +0000401
danielk1977599fcba2004-11-08 07:13:13 +0000402#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000403/*
drh42cac6d2004-11-20 20:31:11 +0000404** These macros define the location of the pointer-map entry for a
405** database page. The first argument to each is the number of usable
406** bytes on each page of the database (often 1024). The second is the
407** page number to look up in the pointer map.
danielk1977afcdd022004-10-31 16:25:42 +0000408**
409** PTRMAP_PAGENO returns the database page number of the pointer-map
410** page that stores the required pointer. PTRMAP_PTROFFSET returns
411** the offset of the requested map entry.
412**
413** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
414** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
danielk1977599fcba2004-11-08 07:13:13 +0000415** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
416** this test.
danielk1977afcdd022004-10-31 16:25:42 +0000417*/
418#define PTRMAP_PAGENO(pgsz, pgno) (((pgno-2)/(pgsz/5+1))*(pgsz/5+1)+2)
419#define PTRMAP_PTROFFSET(pgsz, pgno) (((pgno-2)%(pgsz/5+1)-1)*5)
danielk1977a19df672004-11-03 11:37:07 +0000420#define PTRMAP_ISPAGE(pgsz, pgno) (PTRMAP_PAGENO(pgsz,pgno)==pgno)
421
danielk1977afcdd022004-10-31 16:25:42 +0000422/*
danielk1977687566d2004-11-02 12:56:41 +0000423** The pointer map is a lookup table that contains an entry for each database
424** page in the file except for page 1. In this context 'database page' refers
425** to any page that is not part of the pointer map itself. Each pointer map
426** entry consists of a single byte 'type' and a 4 byte page number. The
427** PTRMAP_XXX identifiers below are the valid types. The interpretation
428** of the page-number depends on the type, as follows:
danielk1977afcdd022004-10-31 16:25:42 +0000429**
danielk1977687566d2004-11-02 12:56:41 +0000430** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
431** used in this case.
danielk1977afcdd022004-10-31 16:25:42 +0000432**
danielk1977687566d2004-11-02 12:56:41 +0000433** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
434** is not used in this case.
435**
436** PTRMAP_OVERFLOW1: The database page is the first page in a list of
437** overflow pages. The page number identifies the page that
438** contains the cell with a pointer to this overflow page.
439**
440** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
441** overflow pages. The page-number identifies the previous
442** page in the overflow page list.
443**
444** PTRMAP_BTREE: The database page is a non-root btree page. The page number
445** identifies the parent page in the btree.
danielk1977afcdd022004-10-31 16:25:42 +0000446*/
danielk1977687566d2004-11-02 12:56:41 +0000447#define PTRMAP_ROOTPAGE 1
448#define PTRMAP_FREEPAGE 2
449#define PTRMAP_OVERFLOW1 3
450#define PTRMAP_OVERFLOW2 4
451#define PTRMAP_BTREE 5
danielk1977afcdd022004-10-31 16:25:42 +0000452
453/*
454** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000455**
456** This routine updates the pointer map entry for page number 'key'
457** so that it maps to type 'eType' and parent page number 'pgno'.
458** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000459*/
460static int ptrmapPut(Btree *pBt, Pgno key, u8 eType, Pgno pgno){
461 u8 *pPtrmap; /* The pointer map page */
462 Pgno iPtrmap; /* The pointer map page number */
463 int offset; /* Offset in pointer map page */
464 int rc;
465
danielk1977ac11ee62005-01-15 12:45:51 +0000466 assert( pBt->autoVacuum );
danielk1977599fcba2004-11-08 07:13:13 +0000467 assert( key!=0 );
drh42cac6d2004-11-20 20:31:11 +0000468 iPtrmap = PTRMAP_PAGENO(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000469 rc = sqlite3pager_get(pBt->pPager, iPtrmap, (void **)&pPtrmap);
danielk1977687566d2004-11-02 12:56:41 +0000470 if( rc!=SQLITE_OK ){
danielk1977afcdd022004-10-31 16:25:42 +0000471 return rc;
472 }
drh42cac6d2004-11-20 20:31:11 +0000473 offset = PTRMAP_PTROFFSET(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000474
475 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=pgno ){
476 rc = sqlite3pager_write(pPtrmap);
477 if( rc!=0 ){
478 return rc;
479 }
480 pPtrmap[offset] = eType;
481 put4byte(&pPtrmap[offset+1], pgno);
482 }
483
484 sqlite3pager_unref(pPtrmap);
485 return SQLITE_OK;
486}
487
488/*
489** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000490**
491** This routine retrieves the pointer map entry for page 'key', writing
492** the type and parent page number to *pEType and *pPgno respectively.
493** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000494*/
495static int ptrmapGet(Btree *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
496 int iPtrmap; /* Pointer map page index */
497 u8 *pPtrmap; /* Pointer map page data */
498 int offset; /* Offset of entry in pointer map */
499 int rc;
500
drh42cac6d2004-11-20 20:31:11 +0000501 iPtrmap = PTRMAP_PAGENO(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000502 rc = sqlite3pager_get(pBt->pPager, iPtrmap, (void **)&pPtrmap);
503 if( rc!=0 ){
504 return rc;
505 }
506
drh42cac6d2004-11-20 20:31:11 +0000507 offset = PTRMAP_PTROFFSET(pBt->usableSize, key);
danielk1977687566d2004-11-02 12:56:41 +0000508 if( pEType ) *pEType = pPtrmap[offset];
509 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000510
511 sqlite3pager_unref(pPtrmap);
512 return SQLITE_OK;
513}
514
515#endif /* SQLITE_OMIT_AUTOVACUUM */
516
drh0d316a42002-08-11 20:10:47 +0000517/*
drh271efa52004-05-30 19:19:05 +0000518** Given a btree page and a cell index (0 means the first cell on
519** the page, 1 means the second cell, and so forth) return a pointer
520** to the cell content.
521**
522** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000523*/
drh43605152004-05-29 21:46:49 +0000524static u8 *findCell(MemPage *pPage, int iCell){
525 u8 *data = pPage->aData;
526 assert( iCell>=0 );
527 assert( iCell<get2byte(&data[pPage->hdrOffset+3]) );
528 return data + get2byte(&data[pPage->cellOffset+2*iCell]);
529}
530
531/*
532** This a more complex version of findCell() that works for
533** pages that do contain overflow cells. See insert
534*/
535static u8 *findOverflowCell(MemPage *pPage, int iCell){
536 int i;
537 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000538 int k;
539 struct _OvflCell *pOvfl;
540 pOvfl = &pPage->aOvfl[i];
541 k = pOvfl->idx;
542 if( k<=iCell ){
543 if( k==iCell ){
544 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000545 }
546 iCell--;
547 }
548 }
549 return findCell(pPage, iCell);
550}
551
552/*
553** Parse a cell content block and fill in the CellInfo structure. There
554** are two versions of this function. parseCell() takes a cell index
555** as the second argument and parseCellPtr() takes a pointer to the
556** body of the cell as its second argument.
557*/
558static void parseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000559 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000560 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000561 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000562){
drh271efa52004-05-30 19:19:05 +0000563 int n; /* Number bytes in cell content header */
564 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000565
566 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000567 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000568 n = pPage->childPtrSize;
569 assert( n==4-4*pPage->leaf );
drh8b18dd42004-05-12 19:18:15 +0000570 if( pPage->hasData ){
drh271efa52004-05-30 19:19:05 +0000571 n += getVarint32(&pCell[n], &nPayload);
drh8b18dd42004-05-12 19:18:15 +0000572 }else{
drh271efa52004-05-30 19:19:05 +0000573 nPayload = 0;
drh3aac2dd2004-04-26 14:10:20 +0000574 }
danielk1977e0d4b062004-06-28 01:11:46 +0000575 n += getVarint(&pCell[n], (u64 *)&pInfo->nKey);
drh6f11bef2004-05-13 01:12:56 +0000576 pInfo->nHeader = n;
drh271efa52004-05-30 19:19:05 +0000577 pInfo->nData = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000578 if( !pPage->intKey ){
579 nPayload += pInfo->nKey;
580 }
drh271efa52004-05-30 19:19:05 +0000581 if( nPayload<=pPage->maxLocal ){
582 /* This is the (easy) common case where the entire payload fits
583 ** on the local page. No overflow is required.
584 */
585 int nSize; /* Total size of cell content in bytes */
drh6f11bef2004-05-13 01:12:56 +0000586 pInfo->nLocal = nPayload;
587 pInfo->iOverflow = 0;
drh271efa52004-05-30 19:19:05 +0000588 nSize = nPayload + n;
589 if( nSize<4 ){
590 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000591 }
drh271efa52004-05-30 19:19:05 +0000592 pInfo->nSize = nSize;
drh6f11bef2004-05-13 01:12:56 +0000593 }else{
drh271efa52004-05-30 19:19:05 +0000594 /* If the payload will not fit completely on the local page, we have
595 ** to decide how much to store locally and how much to spill onto
596 ** overflow pages. The strategy is to minimize the amount of unused
597 ** space on overflow pages while keeping the amount of local storage
598 ** in between minLocal and maxLocal.
599 **
600 ** Warning: changing the way overflow payload is distributed in any
601 ** way will result in an incompatible file format.
602 */
603 int minLocal; /* Minimum amount of payload held locally */
604 int maxLocal; /* Maximum amount of payload held locally */
605 int surplus; /* Overflow payload available for local storage */
606
607 minLocal = pPage->minLocal;
608 maxLocal = pPage->maxLocal;
609 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000610 if( surplus <= maxLocal ){
611 pInfo->nLocal = surplus;
612 }else{
613 pInfo->nLocal = minLocal;
614 }
615 pInfo->iOverflow = pInfo->nLocal + n;
616 pInfo->nSize = pInfo->iOverflow + 4;
617 }
drh3aac2dd2004-04-26 14:10:20 +0000618}
drh43605152004-05-29 21:46:49 +0000619static void parseCell(
620 MemPage *pPage, /* Page containing the cell */
621 int iCell, /* The cell index. First cell is 0 */
622 CellInfo *pInfo /* Fill in this structure */
623){
624 parseCellPtr(pPage, findCell(pPage, iCell), pInfo);
625}
drh3aac2dd2004-04-26 14:10:20 +0000626
627/*
drh43605152004-05-29 21:46:49 +0000628** Compute the total number of bytes that a Cell needs in the cell
629** data area of the btree-page. The return number includes the cell
630** data header and the local payload, but not any overflow page or
631** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000632*/
danielk1977bc6ada42004-06-30 08:20:16 +0000633#ifndef NDEBUG
drh43605152004-05-29 21:46:49 +0000634static int cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000635 CellInfo info;
drh43605152004-05-29 21:46:49 +0000636 parseCell(pPage, iCell, &info);
637 return info.nSize;
638}
danielk1977bc6ada42004-06-30 08:20:16 +0000639#endif
drh43605152004-05-29 21:46:49 +0000640static int cellSizePtr(MemPage *pPage, u8 *pCell){
641 CellInfo info;
642 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000643 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000644}
645
646/*
danielk1977ac11ee62005-01-15 12:45:51 +0000647** If pCell, part of pPage, contains a pointer to an overflow page,
648** return the overflow page number. Otherwise return 0.
649*/
650static Pgno ovflPagePtr(MemPage *pPage, u8 *pCell){
651 CellInfo info;
652 parseCellPtr(pPage, pCell, &info);
653 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
654 return get4byte(&pCell[info.iOverflow]);
655 }
656 return 0;
657}
658
659/*
drhda200cc2004-05-09 11:51:38 +0000660** Do sanity checking on a page. Throw an exception if anything is
661** not right.
662**
663** This routine is used for internal error checking only. It is omitted
664** from most builds.
665*/
666#if defined(BTREE_DEBUG) && !defined(NDEBUG) && 0
667static void _pageIntegrity(MemPage *pPage){
drhb6f41482004-05-14 01:58:11 +0000668 int usableSize;
drhda200cc2004-05-09 11:51:38 +0000669 u8 *data;
drh43605152004-05-29 21:46:49 +0000670 int i, j, idx, c, pc, hdr, nFree;
671 int cellOffset;
672 int nCell, cellLimit;
drh2e38c322004-09-03 18:38:44 +0000673 u8 *used;
drhda200cc2004-05-09 11:51:38 +0000674
drh2e38c322004-09-03 18:38:44 +0000675 used = sqliteMallocRaw( pPage->pBt->pageSize );
676 if( used==0 ) return;
drhb6f41482004-05-14 01:58:11 +0000677 usableSize = pPage->pBt->usableSize;
drh887dc4c2004-10-22 16:22:57 +0000678 assert( pPage->aData==&((unsigned char*)pPage)[-pPage->pBt->psAligned] );
drhda200cc2004-05-09 11:51:38 +0000679 hdr = pPage->hdrOffset;
680 assert( hdr==(pPage->pgno==1 ? 100 : 0) );
681 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
682 c = pPage->aData[hdr];
683 if( pPage->isInit ){
684 assert( pPage->leaf == ((c & PTF_LEAF)!=0) );
685 assert( pPage->zeroData == ((c & PTF_ZERODATA)!=0) );
drh8b18dd42004-05-12 19:18:15 +0000686 assert( pPage->leafData == ((c & PTF_LEAFDATA)!=0) );
687 assert( pPage->intKey == ((c & (PTF_INTKEY|PTF_LEAFDATA))!=0) );
688 assert( pPage->hasData ==
689 !(pPage->zeroData || (!pPage->leaf && pPage->leafData)) );
drh43605152004-05-29 21:46:49 +0000690 assert( pPage->cellOffset==pPage->hdrOffset+12-4*pPage->leaf );
691 assert( pPage->nCell = get2byte(&pPage->aData[hdr+3]) );
drhda200cc2004-05-09 11:51:38 +0000692 }
693 data = pPage->aData;
drhb6f41482004-05-14 01:58:11 +0000694 memset(used, 0, usableSize);
drhda200cc2004-05-09 11:51:38 +0000695 for(i=0; i<hdr+10-pPage->leaf*4; i++) used[i] = 1;
696 nFree = 0;
697 pc = get2byte(&data[hdr+1]);
698 while( pc ){
699 int size;
drhb6f41482004-05-14 01:58:11 +0000700 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +0000701 size = get2byte(&data[pc+2]);
drhb6f41482004-05-14 01:58:11 +0000702 assert( pc+size<=usableSize );
drhda200cc2004-05-09 11:51:38 +0000703 nFree += size;
704 for(i=pc; i<pc+size; i++){
705 assert( used[i]==0 );
706 used[i] = 1;
707 }
708 pc = get2byte(&data[pc]);
709 }
drhda200cc2004-05-09 11:51:38 +0000710 idx = 0;
drh43605152004-05-29 21:46:49 +0000711 nCell = get2byte(&data[hdr+3]);
712 cellLimit = get2byte(&data[hdr+5]);
713 assert( pPage->isInit==0
714 || pPage->nFree==nFree+data[hdr+7]+cellLimit-(cellOffset+2*nCell) );
715 cellOffset = pPage->cellOffset;
716 for(i=0; i<nCell; i++){
drhda200cc2004-05-09 11:51:38 +0000717 int size;
drh43605152004-05-29 21:46:49 +0000718 pc = get2byte(&data[cellOffset+2*i]);
drhb6f41482004-05-14 01:58:11 +0000719 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +0000720 size = cellSize(pPage, &data[pc]);
drhb6f41482004-05-14 01:58:11 +0000721 assert( pc+size<=usableSize );
drh43605152004-05-29 21:46:49 +0000722 for(j=pc; j<pc+size; j++){
723 assert( used[j]==0 );
724 used[j] = 1;
drhda200cc2004-05-09 11:51:38 +0000725 }
drhda200cc2004-05-09 11:51:38 +0000726 }
drh43605152004-05-29 21:46:49 +0000727 for(i=cellOffset+2*nCell; i<cellimit; i++){
728 assert( used[i]==0 );
729 used[i] = 1;
730 }
drhda200cc2004-05-09 11:51:38 +0000731 nFree = 0;
drhb6f41482004-05-14 01:58:11 +0000732 for(i=0; i<usableSize; i++){
drhda200cc2004-05-09 11:51:38 +0000733 assert( used[i]<=1 );
734 if( used[i]==0 ) nFree++;
735 }
drh43605152004-05-29 21:46:49 +0000736 assert( nFree==data[hdr+7] );
drh2e38c322004-09-03 18:38:44 +0000737 sqliteFree(used);
drhda200cc2004-05-09 11:51:38 +0000738}
739#define pageIntegrity(X) _pageIntegrity(X)
740#else
741# define pageIntegrity(X)
742#endif
743
744/*
drh72f82862001-05-24 21:06:34 +0000745** Defragment the page given. All Cells are moved to the
746** beginning of the page and all free space is collected
747** into one big FreeBlk at the end of the page.
drh365d68f2001-05-11 11:02:46 +0000748*/
drh2e38c322004-09-03 18:38:44 +0000749static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000750 int i; /* Loop counter */
751 int pc; /* Address of a i-th cell */
752 int addr; /* Offset of first byte after cell pointer array */
753 int hdr; /* Offset to the page header */
754 int size; /* Size of a cell */
755 int usableSize; /* Number of usable bytes on a page */
756 int cellOffset; /* Offset to the cell pointer array */
757 int brk; /* Offset to the cell content area */
758 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +0000759 unsigned char *data; /* The page data */
760 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +0000761
drha34b6762004-05-07 13:30:42 +0000762 assert( sqlite3pager_iswriteable(pPage->aData) );
drh9e572e62004-04-23 23:43:10 +0000763 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +0000764 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000765 assert( pPage->nOverflow==0 );
drh2e38c322004-09-03 18:38:44 +0000766 temp = sqliteMalloc( pPage->pBt->pageSize );
767 if( temp==0 ) return SQLITE_NOMEM;
drh43605152004-05-29 21:46:49 +0000768 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000769 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000770 cellOffset = pPage->cellOffset;
771 nCell = pPage->nCell;
772 assert( nCell==get2byte(&data[hdr+3]) );
773 usableSize = pPage->pBt->usableSize;
774 brk = get2byte(&data[hdr+5]);
775 memcpy(&temp[brk], &data[brk], usableSize - brk);
776 brk = usableSize;
777 for(i=0; i<nCell; i++){
778 u8 *pAddr; /* The i-th cell pointer */
779 pAddr = &data[cellOffset + i*2];
780 pc = get2byte(pAddr);
781 assert( pc<pPage->pBt->usableSize );
782 size = cellSizePtr(pPage, &temp[pc]);
783 brk -= size;
784 memcpy(&data[brk], &temp[pc], size);
785 put2byte(pAddr, brk);
drh2af926b2001-05-15 00:39:25 +0000786 }
drh43605152004-05-29 21:46:49 +0000787 assert( brk>=cellOffset+2*nCell );
788 put2byte(&data[hdr+5], brk);
789 data[hdr+1] = 0;
790 data[hdr+2] = 0;
791 data[hdr+7] = 0;
792 addr = cellOffset+2*nCell;
793 memset(&data[addr], 0, brk-addr);
drh2e38c322004-09-03 18:38:44 +0000794 sqliteFree(temp);
795 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +0000796}
797
drha059ad02001-04-17 20:09:11 +0000798/*
drh43605152004-05-29 21:46:49 +0000799** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +0000800**
drh9e572e62004-04-23 23:43:10 +0000801** Return the index into pPage->aData[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000802** the new allocation. Or return 0 if there is not enough free
803** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000804**
drh72f82862001-05-24 21:06:34 +0000805** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000806** nBytes of contiguous free space, then this routine automatically
807** calls defragementPage() to consolidate all free space before
808** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000809*/
drh9e572e62004-04-23 23:43:10 +0000810static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +0000811 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +0000812 int size;
drh24cd67e2004-05-10 16:18:47 +0000813 int nFrag;
drh43605152004-05-29 21:46:49 +0000814 int top;
815 int nCell;
816 int cellOffset;
drh9e572e62004-04-23 23:43:10 +0000817 unsigned char *data;
drh43605152004-05-29 21:46:49 +0000818
drh9e572e62004-04-23 23:43:10 +0000819 data = pPage->aData;
drha34b6762004-05-07 13:30:42 +0000820 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +0000821 assert( pPage->pBt );
822 if( nByte<4 ) nByte = 4;
drh43605152004-05-29 21:46:49 +0000823 if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
824 pPage->nFree -= nByte;
drh9e572e62004-04-23 23:43:10 +0000825 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000826
827 nFrag = data[hdr+7];
828 if( nFrag<60 ){
829 /* Search the freelist looking for a slot big enough to satisfy the
830 ** space request. */
831 addr = hdr+1;
832 while( (pc = get2byte(&data[addr]))>0 ){
833 size = get2byte(&data[pc+2]);
834 if( size>=nByte ){
835 if( size<nByte+4 ){
836 memcpy(&data[addr], &data[pc], 2);
837 data[hdr+7] = nFrag + size - nByte;
838 return pc;
839 }else{
840 put2byte(&data[pc+2], size-nByte);
841 return pc + size - nByte;
842 }
843 }
844 addr = pc;
drh9e572e62004-04-23 23:43:10 +0000845 }
846 }
drh43605152004-05-29 21:46:49 +0000847
848 /* Allocate memory from the gap in between the cell pointer array
849 ** and the cell content area.
850 */
851 top = get2byte(&data[hdr+5]);
852 nCell = get2byte(&data[hdr+3]);
853 cellOffset = pPage->cellOffset;
854 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
drh2e38c322004-09-03 18:38:44 +0000855 if( defragmentPage(pPage) ) return 0;
drh43605152004-05-29 21:46:49 +0000856 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +0000857 }
drh43605152004-05-29 21:46:49 +0000858 top -= nByte;
859 assert( cellOffset + 2*nCell <= top );
860 put2byte(&data[hdr+5], top);
861 return top;
drh7e3b0a02001-04-28 16:52:40 +0000862}
863
864/*
drh9e572e62004-04-23 23:43:10 +0000865** Return a section of the pPage->aData to the freelist.
866** The first byte of the new free block is pPage->aDisk[start]
867** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +0000868**
869** Most of the effort here is involved in coalesing adjacent
870** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000871*/
drh9e572e62004-04-23 23:43:10 +0000872static void freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +0000873 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +0000874 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +0000875
drh9e572e62004-04-23 23:43:10 +0000876 assert( pPage->pBt!=0 );
drha34b6762004-05-07 13:30:42 +0000877 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +0000878 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +0000879 assert( (start + size)<=pPage->pBt->usableSize );
drh9e572e62004-04-23 23:43:10 +0000880 if( size<4 ) size = 4;
881
882 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +0000883 hdr = pPage->hdrOffset;
884 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +0000885 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +0000886 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000887 assert( pbegin>addr );
888 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +0000889 }
drhb6f41482004-05-14 01:58:11 +0000890 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000891 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +0000892 put2byte(&data[addr], start);
893 put2byte(&data[start], pbegin);
894 put2byte(&data[start+2], size);
drh2af926b2001-05-15 00:39:25 +0000895 pPage->nFree += size;
drh9e572e62004-04-23 23:43:10 +0000896
897 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +0000898 addr = pPage->hdrOffset + 1;
899 while( (pbegin = get2byte(&data[addr]))>0 ){
drh9e572e62004-04-23 23:43:10 +0000900 int pnext, psize;
drh3aac2dd2004-04-26 14:10:20 +0000901 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +0000902 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +0000903 pnext = get2byte(&data[pbegin]);
904 psize = get2byte(&data[pbegin+2]);
905 if( pbegin + psize + 3 >= pnext && pnext>0 ){
906 int frag = pnext - (pbegin+psize);
drh43605152004-05-29 21:46:49 +0000907 assert( frag<=data[pPage->hdrOffset+7] );
908 data[pPage->hdrOffset+7] -= frag;
drh9e572e62004-04-23 23:43:10 +0000909 put2byte(&data[pbegin], get2byte(&data[pnext]));
910 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
911 }else{
drh3aac2dd2004-04-26 14:10:20 +0000912 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +0000913 }
914 }
drh7e3b0a02001-04-28 16:52:40 +0000915
drh43605152004-05-29 21:46:49 +0000916 /* If the cell content area begins with a freeblock, remove it. */
917 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
918 int top;
919 pbegin = get2byte(&data[hdr+1]);
920 memcpy(&data[hdr+1], &data[pbegin], 2);
921 top = get2byte(&data[hdr+5]);
922 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
drh4b70f112004-05-02 21:12:19 +0000923 }
drh4b70f112004-05-02 21:12:19 +0000924}
925
926/*
drh271efa52004-05-30 19:19:05 +0000927** Decode the flags byte (the first byte of the header) for a page
928** and initialize fields of the MemPage structure accordingly.
929*/
930static void decodeFlags(MemPage *pPage, int flagByte){
931 Btree *pBt; /* A copy of pPage->pBt */
932
933 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
934 pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
935 pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
936 pPage->leaf = (flagByte & PTF_LEAF)!=0;
937 pPage->childPtrSize = 4*(pPage->leaf==0);
938 pBt = pPage->pBt;
939 if( flagByte & PTF_LEAFDATA ){
940 pPage->leafData = 1;
941 pPage->maxLocal = pBt->maxLeaf;
942 pPage->minLocal = pBt->minLeaf;
943 }else{
944 pPage->leafData = 0;
945 pPage->maxLocal = pBt->maxLocal;
946 pPage->minLocal = pBt->minLocal;
947 }
948 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
949}
950
951/*
drh7e3b0a02001-04-28 16:52:40 +0000952** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000953**
drhbd03cae2001-06-02 02:40:57 +0000954** The pParent parameter must be a pointer to the MemPage which
drh9e572e62004-04-23 23:43:10 +0000955** is the parent of the page being initialized. The root of a
956** BTree has no parent and so for that page, pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000957**
drh72f82862001-05-24 21:06:34 +0000958** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +0000959** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +0000960** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
961** guarantee that the page is well-formed. It only shows that
962** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000963*/
drh9e572e62004-04-23 23:43:10 +0000964static int initPage(
drh3aac2dd2004-04-26 14:10:20 +0000965 MemPage *pPage, /* The page to be initialized */
drh9e572e62004-04-23 23:43:10 +0000966 MemPage *pParent /* The parent. Might be NULL */
967){
drh271efa52004-05-30 19:19:05 +0000968 int pc; /* Address of a freeblock within pPage->aData[] */
drh271efa52004-05-30 19:19:05 +0000969 int hdr; /* Offset to beginning of page header */
970 u8 *data; /* Equal to pPage->aData */
drh2e38c322004-09-03 18:38:44 +0000971 Btree *pBt; /* The main btree structure */
drh271efa52004-05-30 19:19:05 +0000972 int usableSize; /* Amount of usable space on each page */
973 int cellOffset; /* Offset from start of page to first cell pointer */
974 int nFree; /* Number of unused bytes on the page */
975 int top; /* First byte of the cell content area */
drh2af926b2001-05-15 00:39:25 +0000976
drh2e38c322004-09-03 18:38:44 +0000977 pBt = pPage->pBt;
978 assert( pBt!=0 );
979 assert( pParent==0 || pParent->pBt==pBt );
drha34b6762004-05-07 13:30:42 +0000980 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
drh887dc4c2004-10-22 16:22:57 +0000981 assert( pPage->aData == &((unsigned char*)pPage)[-pBt->psAligned] );
drhee696e22004-08-30 16:52:17 +0000982 if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
983 /* The parent page should never change unless the file is corrupt */
984 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
985 }
drh10617cd2004-05-14 15:27:27 +0000986 if( pPage->isInit ) return SQLITE_OK;
drhda200cc2004-05-09 11:51:38 +0000987 if( pPage->pParent==0 && pParent!=0 ){
988 pPage->pParent = pParent;
drha34b6762004-05-07 13:30:42 +0000989 sqlite3pager_ref(pParent->aData);
drh5e2f8b92001-05-28 00:41:15 +0000990 }
drhde647132004-05-07 17:57:49 +0000991 hdr = pPage->hdrOffset;
drha34b6762004-05-07 13:30:42 +0000992 data = pPage->aData;
drh271efa52004-05-30 19:19:05 +0000993 decodeFlags(pPage, data[hdr]);
drh43605152004-05-29 21:46:49 +0000994 pPage->nOverflow = 0;
drhc8629a12004-05-08 20:07:40 +0000995 pPage->idxShift = 0;
drh2e38c322004-09-03 18:38:44 +0000996 usableSize = pBt->usableSize;
drh43605152004-05-29 21:46:49 +0000997 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
998 top = get2byte(&data[hdr+5]);
999 pPage->nCell = get2byte(&data[hdr+3]);
drh2e38c322004-09-03 18:38:44 +00001000 if( pPage->nCell>MX_CELL(pBt) ){
drhee696e22004-08-30 16:52:17 +00001001 /* To many cells for a single page. The page must be corrupt */
1002 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1003 }
1004 if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
1005 /* All pages must have at least one cell, except for root pages */
1006 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1007 }
drh9e572e62004-04-23 23:43:10 +00001008
1009 /* Compute the total free space on the page */
drh9e572e62004-04-23 23:43:10 +00001010 pc = get2byte(&data[hdr+1]);
drh43605152004-05-29 21:46:49 +00001011 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
drh9e572e62004-04-23 23:43:10 +00001012 while( pc>0 ){
1013 int next, size;
drhee696e22004-08-30 16:52:17 +00001014 if( pc>usableSize-4 ){
1015 /* Free block is off the page */
1016 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1017 }
drh9e572e62004-04-23 23:43:10 +00001018 next = get2byte(&data[pc]);
1019 size = get2byte(&data[pc+2]);
drhee696e22004-08-30 16:52:17 +00001020 if( next>0 && next<=pc+size+3 ){
1021 /* Free blocks must be in accending order */
1022 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1023 }
drh3add3672004-05-15 00:29:24 +00001024 nFree += size;
drh9e572e62004-04-23 23:43:10 +00001025 pc = next;
1026 }
drh3add3672004-05-15 00:29:24 +00001027 pPage->nFree = nFree;
drhee696e22004-08-30 16:52:17 +00001028 if( nFree>=usableSize ){
1029 /* Free space cannot exceed total page size */
1030 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1031 }
drh9e572e62004-04-23 23:43:10 +00001032
drhde647132004-05-07 17:57:49 +00001033 pPage->isInit = 1;
drhda200cc2004-05-09 11:51:38 +00001034 pageIntegrity(pPage);
drh9e572e62004-04-23 23:43:10 +00001035 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001036}
1037
1038/*
drh8b2f49b2001-06-08 00:21:52 +00001039** Set up a raw page so that it looks like a database page holding
1040** no entries.
drhbd03cae2001-06-02 02:40:57 +00001041*/
drh9e572e62004-04-23 23:43:10 +00001042static void zeroPage(MemPage *pPage, int flags){
1043 unsigned char *data = pPage->aData;
1044 Btree *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00001045 int hdr = pPage->hdrOffset;
drh9e572e62004-04-23 23:43:10 +00001046 int first;
1047
drhda200cc2004-05-09 11:51:38 +00001048 assert( sqlite3pager_pagenumber(data)==pPage->pgno );
drh887dc4c2004-10-22 16:22:57 +00001049 assert( &data[pBt->psAligned] == (unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +00001050 assert( sqlite3pager_iswriteable(data) );
drhb6f41482004-05-14 01:58:11 +00001051 memset(&data[hdr], 0, pBt->usableSize - hdr);
drh9e572e62004-04-23 23:43:10 +00001052 data[hdr] = flags;
drh43605152004-05-29 21:46:49 +00001053 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
1054 memset(&data[hdr+1], 0, 4);
1055 data[hdr+7] = 0;
1056 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +00001057 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +00001058 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +00001059 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +00001060 pPage->cellOffset = first;
1061 pPage->nOverflow = 0;
drhda200cc2004-05-09 11:51:38 +00001062 pPage->idxShift = 0;
drh43605152004-05-29 21:46:49 +00001063 pPage->nCell = 0;
drhda200cc2004-05-09 11:51:38 +00001064 pPage->isInit = 1;
1065 pageIntegrity(pPage);
drhbd03cae2001-06-02 02:40:57 +00001066}
1067
1068/*
drh3aac2dd2004-04-26 14:10:20 +00001069** Get a page from the pager. Initialize the MemPage.pBt and
1070** MemPage.aData elements if needed.
1071*/
1072static int getPage(Btree *pBt, Pgno pgno, MemPage **ppPage){
1073 int rc;
1074 unsigned char *aData;
1075 MemPage *pPage;
drha34b6762004-05-07 13:30:42 +00001076 rc = sqlite3pager_get(pBt->pPager, pgno, (void**)&aData);
drh3aac2dd2004-04-26 14:10:20 +00001077 if( rc ) return rc;
drh887dc4c2004-10-22 16:22:57 +00001078 pPage = (MemPage*)&aData[pBt->psAligned];
drh3aac2dd2004-04-26 14:10:20 +00001079 pPage->aData = aData;
1080 pPage->pBt = pBt;
1081 pPage->pgno = pgno;
drhde647132004-05-07 17:57:49 +00001082 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
drh3aac2dd2004-04-26 14:10:20 +00001083 *ppPage = pPage;
1084 return SQLITE_OK;
1085}
1086
1087/*
drhde647132004-05-07 17:57:49 +00001088** Get a page from the pager and initialize it. This routine
1089** is just a convenience wrapper around separate calls to
1090** getPage() and initPage().
1091*/
1092static int getAndInitPage(
1093 Btree *pBt, /* The database file */
1094 Pgno pgno, /* Number of the page to get */
1095 MemPage **ppPage, /* Write the page pointer here */
1096 MemPage *pParent /* Parent of the page */
1097){
1098 int rc;
drhee696e22004-08-30 16:52:17 +00001099 if( pgno==0 ){
1100 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1101 }
drhde647132004-05-07 17:57:49 +00001102 rc = getPage(pBt, pgno, ppPage);
drh10617cd2004-05-14 15:27:27 +00001103 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
drhde647132004-05-07 17:57:49 +00001104 rc = initPage(*ppPage, pParent);
1105 }
1106 return rc;
1107}
1108
1109/*
drh3aac2dd2004-04-26 14:10:20 +00001110** Release a MemPage. This should be called once for each prior
1111** call to getPage.
1112*/
drh4b70f112004-05-02 21:12:19 +00001113static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001114 if( pPage ){
1115 assert( pPage->aData );
1116 assert( pPage->pBt );
drh887dc4c2004-10-22 16:22:57 +00001117 assert( &pPage->aData[pPage->pBt->psAligned]==(unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +00001118 sqlite3pager_unref(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00001119 }
1120}
1121
1122/*
drh72f82862001-05-24 21:06:34 +00001123** This routine is called when the reference count for a page
1124** reaches zero. We need to unref the pParent pointer when that
1125** happens.
1126*/
drhb6f41482004-05-14 01:58:11 +00001127static void pageDestructor(void *pData, int pageSize){
drh887dc4c2004-10-22 16:22:57 +00001128 MemPage *pPage = (MemPage*)&((char*)pData)[FORCE_ALIGNMENT(pageSize)];
drh72f82862001-05-24 21:06:34 +00001129 if( pPage->pParent ){
1130 MemPage *pParent = pPage->pParent;
1131 pPage->pParent = 0;
drha34b6762004-05-07 13:30:42 +00001132 releasePage(pParent);
drh72f82862001-05-24 21:06:34 +00001133 }
drh3aac2dd2004-04-26 14:10:20 +00001134 pPage->isInit = 0;
drh72f82862001-05-24 21:06:34 +00001135}
1136
1137/*
drha6abd042004-06-09 17:37:22 +00001138** During a rollback, when the pager reloads information into the cache
1139** so that the cache is restored to its original state at the start of
1140** the transaction, for each page restored this routine is called.
1141**
1142** This routine needs to reset the extra data section at the end of the
1143** page to agree with the restored data.
1144*/
1145static void pageReinit(void *pData, int pageSize){
drh887dc4c2004-10-22 16:22:57 +00001146 MemPage *pPage = (MemPage*)&((char*)pData)[FORCE_ALIGNMENT(pageSize)];
drha6abd042004-06-09 17:37:22 +00001147 if( pPage->isInit ){
1148 pPage->isInit = 0;
1149 initPage(pPage, pPage->pParent);
1150 }
1151}
1152
1153/*
drhad3e0102004-09-03 23:32:18 +00001154** Open a database file.
1155**
drh382c0242001-10-06 16:33:02 +00001156** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001157** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001158** database file will be deleted when sqlite3BtreeClose() is called.
drha059ad02001-04-17 20:09:11 +00001159*/
drh23e11ca2004-05-04 17:27:28 +00001160int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001161 const char *zFilename, /* Name of the file containing the BTree database */
1162 Btree **ppBtree, /* Pointer to new Btree object written here */
drh90f5ecb2004-07-22 01:19:35 +00001163 int flags /* Options */
drh6019e162001-07-02 17:51:45 +00001164){
drha059ad02001-04-17 20:09:11 +00001165 Btree *pBt;
drha34b6762004-05-07 13:30:42 +00001166 int rc;
drh90f5ecb2004-07-22 01:19:35 +00001167 int nReserve;
1168 unsigned char zDbHeader[100];
drha059ad02001-04-17 20:09:11 +00001169
drhd62d3d02003-01-24 12:14:20 +00001170 /*
1171 ** The following asserts make sure that structures used by the btree are
1172 ** the right size. This is to guard against size changes that result
1173 ** when compiling on a different architecture.
1174 */
drh4a1c3802004-05-12 15:15:47 +00001175 assert( sizeof(i64)==8 );
drh9e572e62004-04-23 23:43:10 +00001176 assert( sizeof(u64)==8 );
drhd62d3d02003-01-24 12:14:20 +00001177 assert( sizeof(u32)==4 );
1178 assert( sizeof(u16)==2 );
1179 assert( sizeof(Pgno)==4 );
drhd62d3d02003-01-24 12:14:20 +00001180 assert( sizeof(ptr)==sizeof(char*) );
1181 assert( sizeof(uptr)==sizeof(ptr) );
1182
drha059ad02001-04-17 20:09:11 +00001183 pBt = sqliteMalloc( sizeof(*pBt) );
1184 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +00001185 *ppBtree = 0;
drha059ad02001-04-17 20:09:11 +00001186 return SQLITE_NOMEM;
1187 }
drh90f5ecb2004-07-22 01:19:35 +00001188 rc = sqlite3pager_open(&pBt->pPager, zFilename, EXTRA_SIZE,
1189 (flags & BTREE_OMIT_JOURNAL)==0);
drha059ad02001-04-17 20:09:11 +00001190 if( rc!=SQLITE_OK ){
drha34b6762004-05-07 13:30:42 +00001191 if( pBt->pPager ) sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001192 sqliteFree(pBt);
1193 *ppBtree = 0;
1194 return rc;
1195 }
drha34b6762004-05-07 13:30:42 +00001196 sqlite3pager_set_destructor(pBt->pPager, pageDestructor);
drha6abd042004-06-09 17:37:22 +00001197 sqlite3pager_set_reiniter(pBt->pPager, pageReinit);
drha059ad02001-04-17 20:09:11 +00001198 pBt->pCursor = 0;
drha34b6762004-05-07 13:30:42 +00001199 pBt->pPage1 = 0;
1200 pBt->readOnly = sqlite3pager_isreadonly(pBt->pPager);
drh90f5ecb2004-07-22 01:19:35 +00001201 sqlite3pager_read_fileheader(pBt->pPager, sizeof(zDbHeader), zDbHeader);
1202 pBt->pageSize = get2byte(&zDbHeader[16]);
1203 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE ){
1204 pBt->pageSize = SQLITE_DEFAULT_PAGE_SIZE;
1205 pBt->maxEmbedFrac = 64; /* 25% */
1206 pBt->minEmbedFrac = 32; /* 12.5% */
1207 pBt->minLeafFrac = 32; /* 12.5% */
drheee46cf2004-11-06 00:02:48 +00001208#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197703aded42004-11-22 05:26:27 +00001209 /* If the magic name ":memory:" will create an in-memory database, then
1210 ** do not set the auto-vacuum flag, even if SQLITE_DEFAULT_AUTOVACUUM
1211 ** is true. On the other hand, if SQLITE_OMIT_MEMORYDB has been defined,
1212 ** then ":memory:" is just a regular file-name. Respect the auto-vacuum
1213 ** default in this case.
1214 */
1215#ifndef SQLITE_OMIT_MEMORYDB
danielk1977951af802004-11-05 15:45:09 +00001216 if( zFilename && strcmp(zFilename,":memory:") ){
danielk197703aded42004-11-22 05:26:27 +00001217#else
1218 if( zFilename ){
1219#endif
danielk1977951af802004-11-05 15:45:09 +00001220 pBt->autoVacuum = SQLITE_DEFAULT_AUTOVACUUM;
1221 }
drheee46cf2004-11-06 00:02:48 +00001222#endif
drh90f5ecb2004-07-22 01:19:35 +00001223 nReserve = 0;
1224 }else{
1225 nReserve = zDbHeader[20];
1226 pBt->maxEmbedFrac = zDbHeader[21];
1227 pBt->minEmbedFrac = zDbHeader[22];
1228 pBt->minLeafFrac = zDbHeader[23];
1229 pBt->pageSizeFixed = 1;
danielk1977951af802004-11-05 15:45:09 +00001230#ifndef SQLITE_OMIT_AUTOVACUUM
1231 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1232#endif
drh90f5ecb2004-07-22 01:19:35 +00001233 }
1234 pBt->usableSize = pBt->pageSize - nReserve;
drh887dc4c2004-10-22 16:22:57 +00001235 pBt->psAligned = FORCE_ALIGNMENT(pBt->pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001236 sqlite3pager_set_pagesize(pBt->pPager, pBt->pageSize);
drha059ad02001-04-17 20:09:11 +00001237 *ppBtree = pBt;
1238 return SQLITE_OK;
1239}
1240
1241/*
1242** Close an open database and invalidate all cursors.
1243*/
drh3aac2dd2004-04-26 14:10:20 +00001244int sqlite3BtreeClose(Btree *pBt){
drha059ad02001-04-17 20:09:11 +00001245 while( pBt->pCursor ){
drh3aac2dd2004-04-26 14:10:20 +00001246 sqlite3BtreeCloseCursor(pBt->pCursor);
drha059ad02001-04-17 20:09:11 +00001247 }
drha34b6762004-05-07 13:30:42 +00001248 sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001249 sqliteFree(pBt);
1250 return SQLITE_OK;
1251}
1252
1253/*
drh90f5ecb2004-07-22 01:19:35 +00001254** Change the busy handler callback function.
1255*/
1256int sqlite3BtreeSetBusyHandler(Btree *pBt, BusyHandler *pHandler){
1257 sqlite3pager_set_busyhandler(pBt->pPager, pHandler);
1258 return SQLITE_OK;
1259}
1260
1261/*
drhda47d772002-12-02 04:25:19 +00001262** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001263**
1264** The maximum number of cache pages is set to the absolute
1265** value of mxPage. If mxPage is negative, the pager will
1266** operate asynchronously - it will not stop to do fsync()s
1267** to insure data is written to the disk surface before
1268** continuing. Transactions still work if synchronous is off,
1269** and the database cannot be corrupted if this program
1270** crashes. But if the operating system crashes or there is
1271** an abrupt power failure when synchronous is off, the database
1272** could be left in an inconsistent and unrecoverable state.
1273** Synchronous is on by default so database corruption is not
1274** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001275*/
drh23e11ca2004-05-04 17:27:28 +00001276int sqlite3BtreeSetCacheSize(Btree *pBt, int mxPage){
drha34b6762004-05-07 13:30:42 +00001277 sqlite3pager_set_cachesize(pBt->pPager, mxPage);
drhf57b14a2001-09-14 18:54:08 +00001278 return SQLITE_OK;
1279}
1280
1281/*
drh973b6e32003-02-12 14:09:42 +00001282** Change the way data is synced to disk in order to increase or decrease
1283** how well the database resists damage due to OS crashes and power
1284** failures. Level 1 is the same as asynchronous (no syncs() occur and
1285** there is a high probability of damage) Level 2 is the default. There
1286** is a very low but non-zero probability of damage. Level 3 reduces the
1287** probability of damage to near zero but with a write performance reduction.
1288*/
drh3aac2dd2004-04-26 14:10:20 +00001289int sqlite3BtreeSetSafetyLevel(Btree *pBt, int level){
drha34b6762004-05-07 13:30:42 +00001290 sqlite3pager_set_safety_level(pBt->pPager, level);
drh973b6e32003-02-12 14:09:42 +00001291 return SQLITE_OK;
1292}
1293
1294/*
drh90f5ecb2004-07-22 01:19:35 +00001295** Change the default pages size and the number of reserved bytes per page.
drh06f50212004-11-02 14:24:33 +00001296**
1297** The page size must be a power of 2 between 512 and 65536. If the page
1298** size supplied does not meet this constraint then the page size is not
1299** changed.
1300**
1301** Page sizes are constrained to be a power of two so that the region
1302** of the database file used for locking (beginning at PENDING_BYTE,
1303** the first byte past the 1GB boundary, 0x40000000) needs to occur
1304** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001305**
1306** If parameter nReserve is less than zero, then the number of reserved
1307** bytes per page is left unchanged.
drh90f5ecb2004-07-22 01:19:35 +00001308*/
1309int sqlite3BtreeSetPageSize(Btree *pBt, int pageSize, int nReserve){
1310 if( pBt->pageSizeFixed ){
1311 return SQLITE_READONLY;
1312 }
1313 if( nReserve<0 ){
1314 nReserve = pBt->pageSize - pBt->usableSize;
1315 }
drh06f50212004-11-02 14:24:33 +00001316 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
1317 ((pageSize-1)&pageSize)==0 ){
drh90f5ecb2004-07-22 01:19:35 +00001318 pBt->pageSize = pageSize;
drh887dc4c2004-10-22 16:22:57 +00001319 pBt->psAligned = FORCE_ALIGNMENT(pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001320 sqlite3pager_set_pagesize(pBt->pPager, pageSize);
1321 }
1322 pBt->usableSize = pBt->pageSize - nReserve;
1323 return SQLITE_OK;
1324}
1325
1326/*
1327** Return the currently defined page size
1328*/
1329int sqlite3BtreeGetPageSize(Btree *pBt){
1330 return pBt->pageSize;
1331}
drh2011d5f2004-07-22 02:40:37 +00001332int sqlite3BtreeGetReserve(Btree *pBt){
1333 return pBt->pageSize - pBt->usableSize;
1334}
drh90f5ecb2004-07-22 01:19:35 +00001335
1336/*
danielk1977951af802004-11-05 15:45:09 +00001337** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
1338** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
1339** is disabled. The default value for the auto-vacuum property is
1340** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
1341*/
1342int sqlite3BtreeSetAutoVacuum(Btree *pBt, int autoVacuum){
1343#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001344 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00001345#else
1346 if( pBt->pageSizeFixed ){
1347 return SQLITE_READONLY;
1348 }
1349 pBt->autoVacuum = (autoVacuum?1:0);
1350 return SQLITE_OK;
1351#endif
1352}
1353
1354/*
1355** Return the value of the 'auto-vacuum' property. If auto-vacuum is
1356** enabled 1 is returned. Otherwise 0.
1357*/
1358int sqlite3BtreeGetAutoVacuum(Btree *pBt){
1359#ifdef SQLITE_OMIT_AUTOVACUUM
1360 return 0;
1361#else
1362 return pBt->autoVacuum;
1363#endif
1364}
1365
1366
1367/*
drha34b6762004-05-07 13:30:42 +00001368** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001369** also acquire a readlock on that file.
1370**
1371** SQLITE_OK is returned on success. If the file is not a
1372** well-formed database file, then SQLITE_CORRUPT is returned.
1373** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
1374** is returned if we run out of memory. SQLITE_PROTOCOL is returned
1375** if there is a locking protocol violation.
1376*/
1377static int lockBtree(Btree *pBt){
1378 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001379 MemPage *pPage1;
drha34b6762004-05-07 13:30:42 +00001380 if( pBt->pPage1 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001381 rc = getPage(pBt, 1, &pPage1);
drh306dc212001-05-21 13:45:10 +00001382 if( rc!=SQLITE_OK ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00001383
drh306dc212001-05-21 13:45:10 +00001384
1385 /* Do some checking to help insure the file we opened really is
1386 ** a valid database file.
1387 */
drhb6f41482004-05-14 01:58:11 +00001388 rc = SQLITE_NOTADB;
drha34b6762004-05-07 13:30:42 +00001389 if( sqlite3pager_pagecount(pBt->pPager)>0 ){
drhb6f41482004-05-14 01:58:11 +00001390 u8 *page1 = pPage1->aData;
1391 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001392 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001393 }
drhb6f41482004-05-14 01:58:11 +00001394 if( page1[18]>1 || page1[19]>1 ){
1395 goto page1_init_failed;
1396 }
1397 pBt->pageSize = get2byte(&page1[16]);
1398 pBt->usableSize = pBt->pageSize - page1[20];
1399 if( pBt->usableSize<500 ){
1400 goto page1_init_failed;
1401 }
drh887dc4c2004-10-22 16:22:57 +00001402 pBt->psAligned = FORCE_ALIGNMENT(pBt->pageSize);
drhb6f41482004-05-14 01:58:11 +00001403 pBt->maxEmbedFrac = page1[21];
1404 pBt->minEmbedFrac = page1[22];
1405 pBt->minLeafFrac = page1[23];
drh306dc212001-05-21 13:45:10 +00001406 }
drhb6f41482004-05-14 01:58:11 +00001407
1408 /* maxLocal is the maximum amount of payload to store locally for
1409 ** a cell. Make sure it is small enough so that at least minFanout
1410 ** cells can will fit on one page. We assume a 10-byte page header.
1411 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001412 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001413 ** 4-byte child pointer
1414 ** 9-byte nKey value
1415 ** 4-byte nData value
1416 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001417 ** So a cell consists of a 2-byte poiner, a header which is as much as
1418 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1419 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001420 */
drh43605152004-05-29 21:46:49 +00001421 pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
1422 pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
1423 pBt->maxLeaf = pBt->usableSize - 35;
1424 pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
drhb6f41482004-05-14 01:58:11 +00001425 if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
1426 goto page1_init_failed;
1427 }
drh2e38c322004-09-03 18:38:44 +00001428 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001429 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001430 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001431
drh72f82862001-05-24 21:06:34 +00001432page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001433 releasePage(pPage1);
1434 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001435 return rc;
drh306dc212001-05-21 13:45:10 +00001436}
1437
1438/*
drhb8ca3072001-12-05 00:21:20 +00001439** If there are no outstanding cursors and we are not in the middle
1440** of a transaction but there is a read lock on the database, then
1441** this routine unrefs the first page of the database file which
1442** has the effect of releasing the read lock.
1443**
1444** If there are any outstanding cursors, this routine is a no-op.
1445**
1446** If there is a transaction in progress, this routine is a no-op.
1447*/
1448static void unlockBtreeIfUnused(Btree *pBt){
danielk1977ee5741e2004-05-31 10:01:34 +00001449 if( pBt->inTrans==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
drh51c6d962004-06-06 00:42:25 +00001450 if( pBt->pPage1->aData==0 ){
1451 MemPage *pPage = pBt->pPage1;
drh887dc4c2004-10-22 16:22:57 +00001452 pPage->aData = &((char*)pPage)[-pBt->psAligned];
drh51c6d962004-06-06 00:42:25 +00001453 pPage->pBt = pBt;
1454 pPage->pgno = 1;
1455 }
drh3aac2dd2004-04-26 14:10:20 +00001456 releasePage(pBt->pPage1);
1457 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00001458 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001459 }
1460}
1461
1462/*
drh9e572e62004-04-23 23:43:10 +00001463** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001464** file.
drh8b2f49b2001-06-08 00:21:52 +00001465*/
1466static int newDatabase(Btree *pBt){
drh9e572e62004-04-23 23:43:10 +00001467 MemPage *pP1;
1468 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001469 int rc;
drhde647132004-05-07 17:57:49 +00001470 if( sqlite3pager_pagecount(pBt->pPager)>0 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001471 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00001472 assert( pP1!=0 );
1473 data = pP1->aData;
drha34b6762004-05-07 13:30:42 +00001474 rc = sqlite3pager_write(data);
drh8b2f49b2001-06-08 00:21:52 +00001475 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00001476 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
1477 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00001478 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00001479 data[18] = 1;
1480 data[19] = 1;
drhb6f41482004-05-14 01:58:11 +00001481 data[20] = pBt->pageSize - pBt->usableSize;
1482 data[21] = pBt->maxEmbedFrac;
1483 data[22] = pBt->minEmbedFrac;
1484 data[23] = pBt->minLeafFrac;
1485 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00001486 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00001487 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00001488#ifndef SQLITE_OMIT_AUTOVACUUM
1489 if( pBt->autoVacuum ){
1490 put4byte(&data[36 + 4*4], 1);
1491 }
1492#endif
drh8b2f49b2001-06-08 00:21:52 +00001493 return SQLITE_OK;
1494}
1495
1496/*
danielk1977ee5741e2004-05-31 10:01:34 +00001497** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00001498** is started if the second argument is nonzero, otherwise a read-
1499** transaction. If the second argument is 2 or more and exclusive
1500** transaction is started, meaning that no other process is allowed
1501** to access the database. A preexisting transaction may not be
1502** upgrade to exclusive by calling this routine a second time - the
1503** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00001504**
danielk1977ee5741e2004-05-31 10:01:34 +00001505** A write-transaction must be started before attempting any
1506** changes to the database. None of the following routines
1507** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00001508**
drh23e11ca2004-05-04 17:27:28 +00001509** sqlite3BtreeCreateTable()
1510** sqlite3BtreeCreateIndex()
1511** sqlite3BtreeClearTable()
1512** sqlite3BtreeDropTable()
1513** sqlite3BtreeInsert()
1514** sqlite3BtreeDelete()
1515** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00001516**
1517** If wrflag is true, then nMaster specifies the maximum length of
1518** a master journal file name supplied later via sqlite3BtreeSync().
1519** This is so that appropriate space can be allocated in the journal file
1520** when it is created..
drha059ad02001-04-17 20:09:11 +00001521*/
danielk197740b38dc2004-06-26 08:38:24 +00001522int sqlite3BtreeBeginTrans(Btree *pBt, int wrflag){
danielk1977ee5741e2004-05-31 10:01:34 +00001523 int rc = SQLITE_OK;
1524
1525 /* If the btree is already in a write-transaction, or it
1526 ** is already in a read-transaction and a read-transaction
1527 ** is requested, this is a no-op.
1528 */
1529 if( pBt->inTrans==TRANS_WRITE ||
1530 (pBt->inTrans==TRANS_READ && !wrflag) ){
1531 return SQLITE_OK;
1532 }
1533 if( pBt->readOnly && wrflag ){
1534 return SQLITE_READONLY;
1535 }
1536
drh3aac2dd2004-04-26 14:10:20 +00001537 if( pBt->pPage1==0 ){
drh7e3b0a02001-04-28 16:52:40 +00001538 rc = lockBtree(pBt);
danielk1977ee5741e2004-05-31 10:01:34 +00001539 }
1540
1541 if( rc==SQLITE_OK && wrflag ){
drh684917c2004-10-05 02:41:42 +00001542 rc = sqlite3pager_begin(pBt->pPage1->aData, wrflag>1);
danielk1977ee5741e2004-05-31 10:01:34 +00001543 if( rc==SQLITE_OK ){
1544 rc = newDatabase(pBt);
drh8c42ca92001-06-22 19:15:00 +00001545 }
drha059ad02001-04-17 20:09:11 +00001546 }
danielk1977ee5741e2004-05-31 10:01:34 +00001547
drhf74b8d92002-09-01 23:20:45 +00001548 if( rc==SQLITE_OK ){
danielk1977ee5741e2004-05-31 10:01:34 +00001549 pBt->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
1550 if( wrflag ) pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001551 }else{
1552 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001553 }
drhb8ca3072001-12-05 00:21:20 +00001554 return rc;
drha059ad02001-04-17 20:09:11 +00001555}
1556
1557/*
danielk1977687566d2004-11-02 12:56:41 +00001558** The TRACE macro will print high-level status information about the
1559** btree operation when the global variable sqlite3_btree_trace is
1560** enabled.
1561*/
1562#if SQLITE_TEST
1563# define TRACE(X) if( sqlite3_btree_trace )\
1564 { sqlite3DebugPrintf X; fflush(stdout); }
1565#else
1566# define TRACE(X)
1567#endif
1568int sqlite3_btree_trace=0; /* True to enable tracing */
1569
1570#ifndef SQLITE_OMIT_AUTOVACUUM
1571
1572/*
1573** Set the pointer-map entries for all children of page pPage. Also, if
1574** pPage contains cells that point to overflow pages, set the pointer
1575** map entries for the overflow pages as well.
1576*/
1577static int setChildPtrmaps(MemPage *pPage){
1578 int i; /* Counter variable */
1579 int nCell; /* Number of cells in page pPage */
1580 int rc = SQLITE_OK; /* Return code */
1581 Btree *pBt = pPage->pBt;
1582 int isInitOrig = pPage->isInit;
1583 Pgno pgno = pPage->pgno;
1584
1585 initPage(pPage, 0);
1586 nCell = pPage->nCell;
1587
1588 for(i=0; i<nCell; i++){
1589 CellInfo info;
1590 u8 *pCell = findCell(pPage, i);
1591
1592 parseCellPtr(pPage, pCell, &info);
1593 if( info.iOverflow ){
1594 Pgno ovflPgno = get4byte(&pCell[info.iOverflow]);
1595 rc = ptrmapPut(pBt, ovflPgno, PTRMAP_OVERFLOW1, pgno);
1596 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
1597 }
1598 if( !pPage->leaf ){
1599 Pgno childPgno = get4byte(pCell);
1600 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
1601 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
1602 }
1603 }
1604
1605 if( !pPage->leaf ){
1606 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
1607 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
1608 }
1609
1610set_child_ptrmaps_out:
1611 pPage->isInit = isInitOrig;
1612 return rc;
1613}
1614
1615/*
1616** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
1617** page, is a pointer to page iFrom. Modify this pointer so that it points to
1618** iTo. Parameter eType describes the type of pointer to be modified, as
1619** follows:
1620**
1621** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
1622** page of pPage.
1623**
1624** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
1625** page pointed to by one of the cells on pPage.
1626**
1627** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
1628** overflow page in the list.
1629*/
1630static void modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
1631
1632 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00001633 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977687566d2004-11-02 12:56:41 +00001634 assert( get4byte(pPage->aData)==iFrom );
danielk1977f78fc082004-11-02 14:40:32 +00001635 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00001636 }else{
1637 int isInitOrig = pPage->isInit;
1638 int i;
1639 int nCell;
1640
1641 initPage(pPage, 0);
1642 nCell = pPage->nCell;
1643
danielk1977687566d2004-11-02 12:56:41 +00001644 for(i=0; i<nCell; i++){
1645 u8 *pCell = findCell(pPage, i);
1646 if( eType==PTRMAP_OVERFLOW1 ){
1647 CellInfo info;
1648 parseCellPtr(pPage, pCell, &info);
1649 if( info.iOverflow ){
1650 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
1651 put4byte(&pCell[info.iOverflow], iTo);
1652 break;
1653 }
1654 }
1655 }else{
1656 if( get4byte(pCell)==iFrom ){
1657 put4byte(pCell, iTo);
1658 break;
1659 }
1660 }
1661 }
1662
1663 if( i==nCell ){
1664 assert( eType==PTRMAP_BTREE );
1665 assert( get4byte(&pPage->aData[pPage->hdrOffset+8])==iFrom );
1666 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
1667 }
1668
1669 pPage->isInit = isInitOrig;
1670 }
1671}
1672
danielk1977003ba062004-11-04 02:57:33 +00001673
danielk19777701e812005-01-10 12:59:51 +00001674/*
1675** Move the open database page pDbPage to location iFreePage in the
1676** database. The pDbPage reference remains valid.
1677*/
danielk1977003ba062004-11-04 02:57:33 +00001678static int relocatePage(
danielk19777701e812005-01-10 12:59:51 +00001679 Btree *pBt, /* Btree */
1680 MemPage *pDbPage, /* Open page to move */
1681 u8 eType, /* Pointer map 'type' entry for pDbPage */
1682 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
1683 Pgno iFreePage /* The location to move pDbPage to */
danielk1977003ba062004-11-04 02:57:33 +00001684){
1685 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
1686 Pgno iDbPage = pDbPage->pgno;
1687 Pager *pPager = pBt->pPager;
1688 int rc;
1689
danielk1977a0bf2652004-11-04 14:30:04 +00001690 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
1691 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
danielk1977003ba062004-11-04 02:57:33 +00001692
1693 /* Move page iDbPage from it's current location to page number iFreePage */
1694 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
1695 iDbPage, iFreePage, iPtrPage, eType));
1696 rc = sqlite3pager_movepage(pPager, pDbPage->aData, iFreePage);
1697 if( rc!=SQLITE_OK ){
1698 return rc;
1699 }
1700 pDbPage->pgno = iFreePage;
1701
1702 /* If pDbPage was a btree-page, then it may have child pages and/or cells
1703 ** that point to overflow pages. The pointer map entries for all these
1704 ** pages need to be changed.
1705 **
1706 ** If pDbPage is an overflow page, then the first 4 bytes may store a
1707 ** pointer to a subsequent overflow page. If this is the case, then
1708 ** the pointer map needs to be updated for the subsequent overflow page.
1709 */
danielk1977a0bf2652004-11-04 14:30:04 +00001710 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00001711 rc = setChildPtrmaps(pDbPage);
1712 if( rc!=SQLITE_OK ){
1713 return rc;
1714 }
1715 }else{
1716 Pgno nextOvfl = get4byte(pDbPage->aData);
1717 if( nextOvfl!=0 ){
1718 assert( nextOvfl<=sqlite3pager_pagecount(pPager) );
1719 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
1720 if( rc!=SQLITE_OK ){
1721 return rc;
1722 }
1723 }
1724 }
1725
1726 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
1727 ** that it points at iFreePage. Also fix the pointer map entry for
1728 ** iPtrPage.
1729 */
danielk1977a0bf2652004-11-04 14:30:04 +00001730 if( eType!=PTRMAP_ROOTPAGE ){
1731 rc = getPage(pBt, iPtrPage, &pPtrPage);
1732 if( rc!=SQLITE_OK ){
1733 return rc;
1734 }
1735 rc = sqlite3pager_write(pPtrPage->aData);
1736 if( rc!=SQLITE_OK ){
1737 releasePage(pPtrPage);
1738 return rc;
1739 }
1740 modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
1741 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
danielk1977003ba062004-11-04 02:57:33 +00001742 releasePage(pPtrPage);
danielk1977003ba062004-11-04 02:57:33 +00001743 }
danielk1977003ba062004-11-04 02:57:33 +00001744 return rc;
1745}
1746
danielk1977687566d2004-11-02 12:56:41 +00001747/* Forward declaration required by autoVacuumCommit(). */
danielk1977cb1a7eb2004-11-05 12:27:02 +00001748static int allocatePage(Btree *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00001749
1750/*
1751** This routine is called prior to sqlite3pager_commit when a transaction
1752** is commited for an auto-vacuum database.
1753*/
danielk1977d761c0c2004-11-05 16:37:02 +00001754static int autoVacuumCommit(Btree *pBt, Pgno *nTrunc){
danielk1977687566d2004-11-02 12:56:41 +00001755 Pager *pPager = pBt->pPager;
1756 Pgno nFreeList; /* Number of pages remaining on the free-list. */
danielk1977a19df672004-11-03 11:37:07 +00001757 int nPtrMap; /* Number of pointer-map pages deallocated */
1758 Pgno origSize; /* Pages in the database file */
1759 Pgno finSize; /* Pages in the database file after truncation */
danielk1977687566d2004-11-02 12:56:41 +00001760 int rc; /* Return code */
1761 u8 eType;
danielk1977a19df672004-11-03 11:37:07 +00001762 int pgsz = pBt->pageSize; /* Page size for this database */
danielk1977687566d2004-11-02 12:56:41 +00001763 Pgno iDbPage; /* The database page to move */
danielk1977687566d2004-11-02 12:56:41 +00001764 MemPage *pDbMemPage = 0; /* "" */
1765 Pgno iPtrPage; /* The page that contains a pointer to iDbPage */
danielk1977687566d2004-11-02 12:56:41 +00001766 Pgno iFreePage; /* The free-list page to move iDbPage to */
1767 MemPage *pFreeMemPage = 0; /* "" */
1768
1769#ifndef NDEBUG
1770 int nRef = *sqlite3pager_stats(pPager);
1771#endif
1772
1773 assert( pBt->autoVacuum );
danielk1977a19df672004-11-03 11:37:07 +00001774 assert( 0==PTRMAP_ISPAGE(pgsz, sqlite3pager_pagecount(pPager)) );
danielk1977687566d2004-11-02 12:56:41 +00001775
1776 /* Figure out how many free-pages are in the database. If there are no
1777 ** free pages, then auto-vacuum is a no-op.
1778 */
1779 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977a19df672004-11-03 11:37:07 +00001780 if( nFreeList==0 ){
danielk1977d761c0c2004-11-05 16:37:02 +00001781 *nTrunc = 0;
danielk1977a19df672004-11-03 11:37:07 +00001782 return SQLITE_OK;
1783 }
danielk1977687566d2004-11-02 12:56:41 +00001784
danielk1977a19df672004-11-03 11:37:07 +00001785 origSize = sqlite3pager_pagecount(pPager);
1786 nPtrMap = (nFreeList-origSize+PTRMAP_PAGENO(pgsz, origSize)+pgsz/5)/(pgsz/5);
1787 finSize = origSize - nFreeList - nPtrMap;
danielk1977599fcba2004-11-08 07:13:13 +00001788 if( origSize>PENDING_BYTE_PAGE(pBt) && finSize<=PENDING_BYTE_PAGE(pBt) ){
1789 finSize--;
drh42cac6d2004-11-20 20:31:11 +00001790 if( PTRMAP_ISPAGE(pBt->usableSize, finSize) ){
danielk1977599fcba2004-11-08 07:13:13 +00001791 finSize--;
1792 }
1793 }
danielk1977a19df672004-11-03 11:37:07 +00001794 TRACE(("AUTOVACUUM: Begin (db size %d->%d)\n", origSize, finSize));
danielk1977687566d2004-11-02 12:56:41 +00001795
danielk1977a19df672004-11-03 11:37:07 +00001796 /* Variable 'finSize' will be the size of the file in pages after
danielk1977687566d2004-11-02 12:56:41 +00001797 ** the auto-vacuum has completed (the current file size minus the number
1798 ** of pages on the free list). Loop through the pages that lie beyond
1799 ** this mark, and if they are not already on the free list, move them
danielk1977a19df672004-11-03 11:37:07 +00001800 ** to a free page earlier in the file (somewhere before finSize).
danielk1977687566d2004-11-02 12:56:41 +00001801 */
danielk1977a19df672004-11-03 11:37:07 +00001802 for( iDbPage=finSize+1; iDbPage<=origSize; iDbPage++ ){
danielk1977599fcba2004-11-08 07:13:13 +00001803 /* If iDbPage is a pointer map page, or the pending-byte page, skip it. */
1804 if( PTRMAP_ISPAGE(pgsz, iDbPage) || iDbPage==PENDING_BYTE_PAGE(pBt) ){
1805 continue;
1806 }
1807
danielk1977687566d2004-11-02 12:56:41 +00001808 rc = ptrmapGet(pBt, iDbPage, &eType, &iPtrPage);
1809 if( rc!=SQLITE_OK ) goto autovacuum_out;
1810 assert( eType!=PTRMAP_ROOTPAGE );
1811
danielk1977599fcba2004-11-08 07:13:13 +00001812 /* If iDbPage is free, do not swap it. */
1813 if( eType==PTRMAP_FREEPAGE ){
danielk1977687566d2004-11-02 12:56:41 +00001814 continue;
1815 }
1816 rc = getPage(pBt, iDbPage, &pDbMemPage);
1817 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977687566d2004-11-02 12:56:41 +00001818
1819 /* Find the next page in the free-list that is not already at the end
1820 ** of the file. A page can be pulled off the free list using the
1821 ** allocatePage() routine.
1822 */
1823 do{
1824 if( pFreeMemPage ){
1825 releasePage(pFreeMemPage);
1826 pFreeMemPage = 0;
1827 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00001828 rc = allocatePage(pBt, &pFreeMemPage, &iFreePage, 0, 0);
danielk1977ac11ee62005-01-15 12:45:51 +00001829 if( rc!=SQLITE_OK ){
1830 releasePage(pDbMemPage);
1831 goto autovacuum_out;
1832 }
danielk1977a19df672004-11-03 11:37:07 +00001833 assert( iFreePage<=origSize );
1834 }while( iFreePage>finSize );
danielk1977687566d2004-11-02 12:56:41 +00001835 releasePage(pFreeMemPage);
1836 pFreeMemPage = 0;
danielk1977687566d2004-11-02 12:56:41 +00001837
danielk1977003ba062004-11-04 02:57:33 +00001838 rc = relocatePage(pBt, pDbMemPage, eType, iPtrPage, iFreePage);
danielk1977687566d2004-11-02 12:56:41 +00001839 releasePage(pDbMemPage);
danielk1977687566d2004-11-02 12:56:41 +00001840 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977687566d2004-11-02 12:56:41 +00001841 }
1842
1843 /* The entire free-list has been swapped to the end of the file. So
danielk1977a19df672004-11-03 11:37:07 +00001844 ** truncate the database file to finSize pages and consider the
danielk1977687566d2004-11-02 12:56:41 +00001845 ** free-list empty.
1846 */
1847 rc = sqlite3pager_write(pBt->pPage1->aData);
1848 if( rc!=SQLITE_OK ) goto autovacuum_out;
1849 put4byte(&pBt->pPage1->aData[32], 0);
1850 put4byte(&pBt->pPage1->aData[36], 0);
danielk1977687566d2004-11-02 12:56:41 +00001851 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977d761c0c2004-11-05 16:37:02 +00001852 *nTrunc = finSize;
danielk1977687566d2004-11-02 12:56:41 +00001853
1854autovacuum_out:
danielk1977687566d2004-11-02 12:56:41 +00001855 assert( nRef==*sqlite3pager_stats(pPager) );
1856 if( rc!=SQLITE_OK ){
1857 sqlite3pager_rollback(pPager);
1858 }
1859 return rc;
1860}
1861#endif
1862
1863/*
drh2aa679f2001-06-25 02:11:07 +00001864** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00001865**
1866** This will release the write lock on the database file. If there
1867** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00001868*/
drh3aac2dd2004-04-26 14:10:20 +00001869int sqlite3BtreeCommit(Btree *pBt){
danielk1977ee5741e2004-05-31 10:01:34 +00001870 int rc = SQLITE_OK;
1871 if( pBt->inTrans==TRANS_WRITE ){
1872 rc = sqlite3pager_commit(pBt->pPager);
1873 }
1874 pBt->inTrans = TRANS_NONE;
drh3aac2dd2004-04-26 14:10:20 +00001875 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00001876 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001877 return rc;
1878}
1879
danielk1977fbcd5852004-06-15 02:44:18 +00001880#ifndef NDEBUG
1881/*
1882** Return the number of write-cursors open on this handle. This is for use
1883** in assert() expressions, so it is only compiled if NDEBUG is not
1884** defined.
1885*/
1886static int countWriteCursors(Btree *pBt){
1887 BtCursor *pCur;
1888 int r = 0;
1889 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1890 if( pCur->wrFlag ) r++;
1891 }
1892 return r;
1893}
1894#endif
1895
1896#if 0
drha059ad02001-04-17 20:09:11 +00001897/*
drhc39e0002004-05-07 23:50:57 +00001898** Invalidate all cursors
1899*/
1900static void invalidateCursors(Btree *pBt){
1901 BtCursor *pCur;
1902 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1903 MemPage *pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00001904 if( pPage /* && !pPage->isInit */ ){
1905 pageIntegrity(pPage);
drhc39e0002004-05-07 23:50:57 +00001906 releasePage(pPage);
1907 pCur->pPage = 0;
1908 pCur->isValid = 0;
1909 pCur->status = SQLITE_ABORT;
1910 }
1911 }
1912}
danielk1977fbcd5852004-06-15 02:44:18 +00001913#endif
drhc39e0002004-05-07 23:50:57 +00001914
drhda200cc2004-05-09 11:51:38 +00001915#ifdef SQLITE_TEST
1916/*
1917** Print debugging information about all cursors to standard output.
1918*/
1919void sqlite3BtreeCursorList(Btree *pBt){
danielk197728129562005-01-11 10:25:06 +00001920#ifndef SQLITE_OMIT_CURSOR
drhda200cc2004-05-09 11:51:38 +00001921 BtCursor *pCur;
1922 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1923 MemPage *pPage = pCur->pPage;
1924 char *zMode = pCur->wrFlag ? "rw" : "ro";
drhfe63d1c2004-09-08 20:13:04 +00001925 sqlite3DebugPrintf("CURSOR %p rooted at %4d(%s) currently at %d.%d%s\n",
1926 pCur, pCur->pgnoRoot, zMode,
drhda200cc2004-05-09 11:51:38 +00001927 pPage ? pPage->pgno : 0, pCur->idx,
1928 pCur->isValid ? "" : " eof"
1929 );
1930 }
danielk197728129562005-01-11 10:25:06 +00001931#endif
drhda200cc2004-05-09 11:51:38 +00001932}
1933#endif
1934
drhc39e0002004-05-07 23:50:57 +00001935/*
drhecdc7532001-09-23 02:35:53 +00001936** Rollback the transaction in progress. All cursors will be
1937** invalided by this operation. Any attempt to use a cursor
1938** that was open at the beginning of this operation will result
1939** in an error.
drh5e00f6c2001-09-13 13:46:56 +00001940**
1941** This will release the write lock on the database file. If there
1942** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00001943*/
drh3aac2dd2004-04-26 14:10:20 +00001944int sqlite3BtreeRollback(Btree *pBt){
danielk1977cfe9a692004-06-16 12:00:29 +00001945 int rc = SQLITE_OK;
drh24cd67e2004-05-10 16:18:47 +00001946 MemPage *pPage1;
danielk1977ee5741e2004-05-31 10:01:34 +00001947 if( pBt->inTrans==TRANS_WRITE ){
drh24cd67e2004-05-10 16:18:47 +00001948 rc = sqlite3pager_rollback(pBt->pPager);
1949 /* The rollback may have destroyed the pPage1->aData value. So
1950 ** call getPage() on page 1 again to make sure pPage1->aData is
1951 ** set correctly. */
1952 if( getPage(pBt, 1, &pPage1)==SQLITE_OK ){
1953 releasePage(pPage1);
1954 }
danielk1977fbcd5852004-06-15 02:44:18 +00001955 assert( countWriteCursors(pBt)==0 );
drh24cd67e2004-05-10 16:18:47 +00001956 }
danielk1977ee5741e2004-05-31 10:01:34 +00001957 pBt->inTrans = TRANS_NONE;
1958 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00001959 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001960 return rc;
1961}
1962
1963/*
drhab01f612004-05-22 02:55:23 +00001964** Start a statement subtransaction. The subtransaction can
1965** can be rolled back independently of the main transaction.
1966** You must start a transaction before starting a subtransaction.
1967** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00001968** commits or rolls back.
1969**
drhab01f612004-05-22 02:55:23 +00001970** Only one subtransaction may be active at a time. It is an error to try
1971** to start a new subtransaction if another subtransaction is already active.
1972**
1973** Statement subtransactions are used around individual SQL statements
1974** that are contained within a BEGIN...COMMIT block. If a constraint
1975** error occurs within the statement, the effect of that one statement
1976** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00001977*/
drh3aac2dd2004-04-26 14:10:20 +00001978int sqlite3BtreeBeginStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00001979 int rc;
danielk1977ee5741e2004-05-31 10:01:34 +00001980 if( (pBt->inTrans!=TRANS_WRITE) || pBt->inStmt ){
drhf74b8d92002-09-01 23:20:45 +00001981 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh0d65dc02002-02-03 00:56:09 +00001982 }
drha34b6762004-05-07 13:30:42 +00001983 rc = pBt->readOnly ? SQLITE_OK : sqlite3pager_stmt_begin(pBt->pPager);
drh3aac2dd2004-04-26 14:10:20 +00001984 pBt->inStmt = 1;
drh663fc632002-02-02 18:49:19 +00001985 return rc;
1986}
1987
1988
1989/*
drhab01f612004-05-22 02:55:23 +00001990** Commit the statment subtransaction currently in progress. If no
1991** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00001992*/
drh3aac2dd2004-04-26 14:10:20 +00001993int sqlite3BtreeCommitStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00001994 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001995 if( pBt->inStmt && !pBt->readOnly ){
drha34b6762004-05-07 13:30:42 +00001996 rc = sqlite3pager_stmt_commit(pBt->pPager);
drh663fc632002-02-02 18:49:19 +00001997 }else{
1998 rc = SQLITE_OK;
1999 }
drh3aac2dd2004-04-26 14:10:20 +00002000 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00002001 return rc;
2002}
2003
2004/*
drhab01f612004-05-22 02:55:23 +00002005** Rollback the active statement subtransaction. If no subtransaction
2006** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00002007**
drhab01f612004-05-22 02:55:23 +00002008** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00002009** to use a cursor that was open at the beginning of this operation
2010** will result in an error.
2011*/
drh3aac2dd2004-04-26 14:10:20 +00002012int sqlite3BtreeRollbackStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00002013 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002014 if( pBt->inStmt==0 || pBt->readOnly ) return SQLITE_OK;
drha34b6762004-05-07 13:30:42 +00002015 rc = sqlite3pager_stmt_rollback(pBt->pPager);
danielk1977fbcd5852004-06-15 02:44:18 +00002016 assert( countWriteCursors(pBt)==0 );
drh3aac2dd2004-04-26 14:10:20 +00002017 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00002018 return rc;
2019}
2020
2021/*
drh3aac2dd2004-04-26 14:10:20 +00002022** Default key comparison function to be used if no comparison function
2023** is specified on the sqlite3BtreeCursor() call.
2024*/
2025static int dfltCompare(
2026 void *NotUsed, /* User data is not used */
2027 int n1, const void *p1, /* First key to compare */
2028 int n2, const void *p2 /* Second key to compare */
2029){
2030 int c;
2031 c = memcmp(p1, p2, n1<n2 ? n1 : n2);
2032 if( c==0 ){
2033 c = n1 - n2;
2034 }
2035 return c;
2036}
2037
2038/*
drh8b2f49b2001-06-08 00:21:52 +00002039** Create a new cursor for the BTree whose root is on the page
2040** iTable. The act of acquiring a cursor gets a read lock on
2041** the database file.
drh1bee3d72001-10-15 00:44:35 +00002042**
2043** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00002044** If wrFlag==1, then the cursor can be used for reading or for
2045** writing if other conditions for writing are also met. These
2046** are the conditions that must be met in order for writing to
2047** be allowed:
drh6446c4d2001-12-15 14:22:18 +00002048**
drhf74b8d92002-09-01 23:20:45 +00002049** 1: The cursor must have been opened with wrFlag==1
2050**
2051** 2: No other cursors may be open with wrFlag==0 on the same table
2052**
2053** 3: The database must be writable (not on read-only media)
2054**
2055** 4: There must be an active transaction.
2056**
2057** Condition 2 warrants further discussion. If any cursor is opened
2058** on a table with wrFlag==0, that prevents all other cursors from
2059** writing to that table. This is a kind of "read-lock". When a cursor
2060** is opened with wrFlag==0 it is guaranteed that the table will not
2061** change as long as the cursor is open. This allows the cursor to
2062** do a sequential scan of the table without having to worry about
2063** entries being inserted or deleted during the scan. Cursors should
2064** be opened with wrFlag==0 only if this read-lock property is needed.
2065** That is to say, cursors should be opened with wrFlag==0 only if they
drh23e11ca2004-05-04 17:27:28 +00002066** intend to use the sqlite3BtreeNext() system call. All other cursors
drhf74b8d92002-09-01 23:20:45 +00002067** should be opened with wrFlag==1 even if they never really intend
2068** to write.
2069**
drh6446c4d2001-12-15 14:22:18 +00002070** No checking is done to make sure that page iTable really is the
2071** root page of a b-tree. If it is not, then the cursor acquired
2072** will not work correctly.
drh3aac2dd2004-04-26 14:10:20 +00002073**
2074** The comparison function must be logically the same for every cursor
2075** on a particular table. Changing the comparison function will result
2076** in incorrect operations. If the comparison function is NULL, a
2077** default comparison function is used. The comparison function is
2078** always ignored for INTKEY tables.
drha059ad02001-04-17 20:09:11 +00002079*/
drh3aac2dd2004-04-26 14:10:20 +00002080int sqlite3BtreeCursor(
2081 Btree *pBt, /* The btree */
2082 int iTable, /* Root page of table to open */
2083 int wrFlag, /* 1 to write. 0 read-only */
2084 int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
2085 void *pArg, /* First arg to xCompare() */
2086 BtCursor **ppCur /* Write new cursor here */
2087){
drha059ad02001-04-17 20:09:11 +00002088 int rc;
drh8dcd7ca2004-08-08 19:43:29 +00002089 BtCursor *pCur;
drhecdc7532001-09-23 02:35:53 +00002090
drh8dcd7ca2004-08-08 19:43:29 +00002091 *ppCur = 0;
2092 if( wrFlag ){
drh8dcd7ca2004-08-08 19:43:29 +00002093 if( pBt->readOnly ){
2094 return SQLITE_READONLY;
2095 }
2096 if( checkReadLocks(pBt, iTable, 0) ){
2097 return SQLITE_LOCKED;
2098 }
drha0c9a112004-03-10 13:42:37 +00002099 }
drh4b70f112004-05-02 21:12:19 +00002100 if( pBt->pPage1==0 ){
drha059ad02001-04-17 20:09:11 +00002101 rc = lockBtree(pBt);
2102 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002103 return rc;
2104 }
2105 }
drheafe05b2004-06-13 00:54:01 +00002106 pCur = sqliteMallocRaw( sizeof(*pCur) );
drha059ad02001-04-17 20:09:11 +00002107 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +00002108 rc = SQLITE_NOMEM;
2109 goto create_cursor_exception;
2110 }
drh8b2f49b2001-06-08 00:21:52 +00002111 pCur->pgnoRoot = (Pgno)iTable;
drh24cd67e2004-05-10 16:18:47 +00002112 if( iTable==1 && sqlite3pager_pagecount(pBt->pPager)==0 ){
2113 rc = SQLITE_EMPTY;
drheafe05b2004-06-13 00:54:01 +00002114 pCur->pPage = 0;
drh24cd67e2004-05-10 16:18:47 +00002115 goto create_cursor_exception;
2116 }
danielk1977369f27e2004-06-15 11:40:04 +00002117 pCur->pPage = 0; /* For exit-handler, in case getAndInitPage() fails. */
drhde647132004-05-07 17:57:49 +00002118 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
drhbd03cae2001-06-02 02:40:57 +00002119 if( rc!=SQLITE_OK ){
2120 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002121 }
drh3aac2dd2004-04-26 14:10:20 +00002122 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2123 pCur->pArg = pArg;
drh14acc042001-06-10 19:56:58 +00002124 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +00002125 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +00002126 pCur->idx = 0;
drh59eb6762004-06-13 23:07:04 +00002127 memset(&pCur->info, 0, sizeof(pCur->info));
drha059ad02001-04-17 20:09:11 +00002128 pCur->pNext = pBt->pCursor;
2129 if( pCur->pNext ){
2130 pCur->pNext->pPrev = pCur;
2131 }
drh14acc042001-06-10 19:56:58 +00002132 pCur->pPrev = 0;
drha059ad02001-04-17 20:09:11 +00002133 pBt->pCursor = pCur;
drhc39e0002004-05-07 23:50:57 +00002134 pCur->isValid = 0;
drh2af926b2001-05-15 00:39:25 +00002135 *ppCur = pCur;
2136 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00002137
2138create_cursor_exception:
drhbd03cae2001-06-02 02:40:57 +00002139 if( pCur ){
drh3aac2dd2004-04-26 14:10:20 +00002140 releasePage(pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +00002141 sqliteFree(pCur);
2142 }
drh5e00f6c2001-09-13 13:46:56 +00002143 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00002144 return rc;
drha059ad02001-04-17 20:09:11 +00002145}
2146
drh7a224de2004-06-02 01:22:02 +00002147#if 0 /* Not Used */
drhd3d39e92004-05-20 22:16:29 +00002148/*
2149** Change the value of the comparison function used by a cursor.
2150*/
danielk1977bf3b7212004-05-18 10:06:24 +00002151void sqlite3BtreeSetCompare(
drhd3d39e92004-05-20 22:16:29 +00002152 BtCursor *pCur, /* The cursor to whose comparison function is changed */
2153 int(*xCmp)(void*,int,const void*,int,const void*), /* New comparison func */
2154 void *pArg /* First argument to xCmp() */
danielk1977bf3b7212004-05-18 10:06:24 +00002155){
2156 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2157 pCur->pArg = pArg;
2158}
drh7a224de2004-06-02 01:22:02 +00002159#endif
danielk1977bf3b7212004-05-18 10:06:24 +00002160
drha059ad02001-04-17 20:09:11 +00002161/*
drh5e00f6c2001-09-13 13:46:56 +00002162** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00002163** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00002164*/
drh3aac2dd2004-04-26 14:10:20 +00002165int sqlite3BtreeCloseCursor(BtCursor *pCur){
drha059ad02001-04-17 20:09:11 +00002166 Btree *pBt = pCur->pBt;
drha059ad02001-04-17 20:09:11 +00002167 if( pCur->pPrev ){
2168 pCur->pPrev->pNext = pCur->pNext;
2169 }else{
2170 pBt->pCursor = pCur->pNext;
2171 }
2172 if( pCur->pNext ){
2173 pCur->pNext->pPrev = pCur->pPrev;
2174 }
drh3aac2dd2004-04-26 14:10:20 +00002175 releasePage(pCur->pPage);
drh5e00f6c2001-09-13 13:46:56 +00002176 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00002177 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +00002178 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002179}
2180
drh7e3b0a02001-04-28 16:52:40 +00002181/*
drh5e2f8b92001-05-28 00:41:15 +00002182** Make a temporary cursor by filling in the fields of pTempCur.
2183** The temporary cursor is not on the cursor list for the Btree.
2184*/
drh14acc042001-06-10 19:56:58 +00002185static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00002186 memcpy(pTempCur, pCur, sizeof(*pCur));
2187 pTempCur->pNext = 0;
2188 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00002189 if( pTempCur->pPage ){
drha34b6762004-05-07 13:30:42 +00002190 sqlite3pager_ref(pTempCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00002191 }
drh5e2f8b92001-05-28 00:41:15 +00002192}
2193
2194/*
drhbd03cae2001-06-02 02:40:57 +00002195** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00002196** function above.
2197*/
drh14acc042001-06-10 19:56:58 +00002198static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00002199 if( pCur->pPage ){
drha34b6762004-05-07 13:30:42 +00002200 sqlite3pager_unref(pCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00002201 }
drh5e2f8b92001-05-28 00:41:15 +00002202}
2203
2204/*
drh9188b382004-05-14 21:12:22 +00002205** Make sure the BtCursor.info field of the given cursor is valid.
drhab01f612004-05-22 02:55:23 +00002206** If it is not already valid, call parseCell() to fill it in.
2207**
2208** BtCursor.info is a cache of the information in the current cell.
2209** Using this cache reduces the number of calls to parseCell().
drh9188b382004-05-14 21:12:22 +00002210*/
2211static void getCellInfo(BtCursor *pCur){
drh271efa52004-05-30 19:19:05 +00002212 if( pCur->info.nSize==0 ){
drh3a41a3f2004-05-30 02:14:17 +00002213 parseCell(pCur->pPage, pCur->idx, &pCur->info);
drh9188b382004-05-14 21:12:22 +00002214 }else{
2215#ifndef NDEBUG
2216 CellInfo info;
drh51c6d962004-06-06 00:42:25 +00002217 memset(&info, 0, sizeof(info));
drh3a41a3f2004-05-30 02:14:17 +00002218 parseCell(pCur->pPage, pCur->idx, &info);
drh9188b382004-05-14 21:12:22 +00002219 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
2220#endif
2221 }
2222}
2223
2224/*
drh3aac2dd2004-04-26 14:10:20 +00002225** Set *pSize to the size of the buffer needed to hold the value of
2226** the key for the current entry. If the cursor is not pointing
2227** to a valid entry, *pSize is set to 0.
2228**
drh4b70f112004-05-02 21:12:19 +00002229** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00002230** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00002231*/
drh4a1c3802004-05-12 15:15:47 +00002232int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
danielk1977299b1872004-11-22 10:02:10 +00002233 if( !pCur->isValid ){
drh72f82862001-05-24 21:06:34 +00002234 *pSize = 0;
2235 }else{
drh9188b382004-05-14 21:12:22 +00002236 getCellInfo(pCur);
2237 *pSize = pCur->info.nKey;
drh72f82862001-05-24 21:06:34 +00002238 }
2239 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002240}
drh2af926b2001-05-15 00:39:25 +00002241
drh72f82862001-05-24 21:06:34 +00002242/*
drh0e1c19e2004-05-11 00:58:56 +00002243** Set *pSize to the number of bytes of data in the entry the
2244** cursor currently points to. Always return SQLITE_OK.
2245** Failure is not possible. If the cursor is not currently
2246** pointing to an entry (which can happen, for example, if
2247** the database is empty) then *pSize is set to 0.
2248*/
2249int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
danielk1977299b1872004-11-22 10:02:10 +00002250 if( !pCur->isValid ){
danielk197796fc5fe2004-05-13 11:34:16 +00002251 /* Not pointing at a valid entry - set *pSize to 0. */
drh0e1c19e2004-05-11 00:58:56 +00002252 *pSize = 0;
2253 }else{
drh9188b382004-05-14 21:12:22 +00002254 getCellInfo(pCur);
2255 *pSize = pCur->info.nData;
drh0e1c19e2004-05-11 00:58:56 +00002256 }
2257 return SQLITE_OK;
2258}
2259
2260/*
drh72f82862001-05-24 21:06:34 +00002261** Read payload information from the entry that the pCur cursor is
2262** pointing to. Begin reading the payload at "offset" and read
2263** a total of "amt" bytes. Put the result in zBuf.
2264**
2265** This routine does not make a distinction between key and data.
drhab01f612004-05-22 02:55:23 +00002266** It just reads bytes from the payload area. Data might appear
2267** on the main page or be scattered out on multiple overflow pages.
drh72f82862001-05-24 21:06:34 +00002268*/
drh3aac2dd2004-04-26 14:10:20 +00002269static int getPayload(
2270 BtCursor *pCur, /* Cursor pointing to entry to read from */
2271 int offset, /* Begin reading this far into payload */
2272 int amt, /* Read this many bytes */
2273 unsigned char *pBuf, /* Write the bytes into this buffer */
2274 int skipKey /* offset begins at data if this is true */
2275){
2276 unsigned char *aPayload;
drh2af926b2001-05-15 00:39:25 +00002277 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +00002278 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002279 MemPage *pPage;
2280 Btree *pBt;
drh6f11bef2004-05-13 01:12:56 +00002281 int ovflSize;
drhfa1a98a2004-05-14 19:08:17 +00002282 u32 nKey;
drh3aac2dd2004-04-26 14:10:20 +00002283
drh72f82862001-05-24 21:06:34 +00002284 assert( pCur!=0 && pCur->pPage!=0 );
drhc39e0002004-05-07 23:50:57 +00002285 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00002286 pBt = pCur->pBt;
2287 pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00002288 pageIntegrity(pPage);
drh3aac2dd2004-04-26 14:10:20 +00002289 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00002290 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00002291 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00002292 aPayload += pCur->info.nHeader;
drh3aac2dd2004-04-26 14:10:20 +00002293 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00002294 nKey = 0;
2295 }else{
2296 nKey = pCur->info.nKey;
drh3aac2dd2004-04-26 14:10:20 +00002297 }
2298 assert( offset>=0 );
2299 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00002300 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00002301 }
drhfa1a98a2004-05-14 19:08:17 +00002302 if( offset+amt > nKey+pCur->info.nData ){
drha34b6762004-05-07 13:30:42 +00002303 return SQLITE_ERROR;
drh3aac2dd2004-04-26 14:10:20 +00002304 }
drhfa1a98a2004-05-14 19:08:17 +00002305 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00002306 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00002307 if( a+offset>pCur->info.nLocal ){
2308 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00002309 }
drha34b6762004-05-07 13:30:42 +00002310 memcpy(pBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +00002311 if( a==amt ){
2312 return SQLITE_OK;
2313 }
drh2aa679f2001-06-25 02:11:07 +00002314 offset = 0;
drha34b6762004-05-07 13:30:42 +00002315 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00002316 amt -= a;
drhdd793422001-06-28 01:54:48 +00002317 }else{
drhfa1a98a2004-05-14 19:08:17 +00002318 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00002319 }
danielk1977cfe9a692004-06-16 12:00:29 +00002320 ovflSize = pBt->usableSize - 4;
drhbd03cae2001-06-02 02:40:57 +00002321 if( amt>0 ){
drhfa1a98a2004-05-14 19:08:17 +00002322 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977cfe9a692004-06-16 12:00:29 +00002323 while( amt>0 && nextPage ){
2324 rc = sqlite3pager_get(pBt->pPager, nextPage, (void**)&aPayload);
2325 if( rc!=0 ){
2326 return rc;
drh2af926b2001-05-15 00:39:25 +00002327 }
danielk1977cfe9a692004-06-16 12:00:29 +00002328 nextPage = get4byte(aPayload);
2329 if( offset<ovflSize ){
2330 int a = amt;
2331 if( a + offset > ovflSize ){
2332 a = ovflSize - offset;
2333 }
2334 memcpy(pBuf, &aPayload[offset+4], a);
2335 offset = 0;
2336 amt -= a;
2337 pBuf += a;
2338 }else{
2339 offset -= ovflSize;
2340 }
2341 sqlite3pager_unref(aPayload);
drh2af926b2001-05-15 00:39:25 +00002342 }
drh2af926b2001-05-15 00:39:25 +00002343 }
danielk1977cfe9a692004-06-16 12:00:29 +00002344
drha7fcb052001-12-14 15:09:55 +00002345 if( amt>0 ){
drhee696e22004-08-30 16:52:17 +00002346 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
drha7fcb052001-12-14 15:09:55 +00002347 }
2348 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00002349}
2350
drh72f82862001-05-24 21:06:34 +00002351/*
drh3aac2dd2004-04-26 14:10:20 +00002352** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002353** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002354** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00002355**
drh3aac2dd2004-04-26 14:10:20 +00002356** Return SQLITE_OK on success or an error code if anything goes
2357** wrong. An error is returned if "offset+amt" is larger than
2358** the available payload.
drh72f82862001-05-24 21:06:34 +00002359*/
drha34b6762004-05-07 13:30:42 +00002360int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
danielk197728129562005-01-11 10:25:06 +00002361 assert( pCur->isValid );
drhc39e0002004-05-07 23:50:57 +00002362 assert( pCur->pPage!=0 );
2363 assert( pCur->pPage->intKey==0 );
2364 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh3aac2dd2004-04-26 14:10:20 +00002365 return getPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
2366}
2367
2368/*
drh3aac2dd2004-04-26 14:10:20 +00002369** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002370** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002371** begins at "offset".
2372**
2373** Return SQLITE_OK on success or an error code if anything goes
2374** wrong. An error is returned if "offset+amt" is larger than
2375** the available payload.
drh72f82862001-05-24 21:06:34 +00002376*/
drh3aac2dd2004-04-26 14:10:20 +00002377int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
danielk197728129562005-01-11 10:25:06 +00002378 assert( pCur->isValid );
drh8c1238a2003-01-02 14:43:55 +00002379 assert( pCur->pPage!=0 );
drhc39e0002004-05-07 23:50:57 +00002380 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh3aac2dd2004-04-26 14:10:20 +00002381 return getPayload(pCur, offset, amt, pBuf, 1);
drh2af926b2001-05-15 00:39:25 +00002382}
2383
drh72f82862001-05-24 21:06:34 +00002384/*
drh0e1c19e2004-05-11 00:58:56 +00002385** Return a pointer to payload information from the entry that the
2386** pCur cursor is pointing to. The pointer is to the beginning of
2387** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00002388** skipKey==1. The number of bytes of available key/data is written
2389** into *pAmt. If *pAmt==0, then the value returned will not be
2390** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00002391**
2392** This routine is an optimization. It is common for the entire key
2393** and data to fit on the local page and for there to be no overflow
2394** pages. When that is so, this routine can be used to access the
2395** key and data without making a copy. If the key and/or data spills
2396** onto overflow pages, then getPayload() must be used to reassembly
2397** the key/data and copy it into a preallocated buffer.
2398**
2399** The pointer returned by this routine looks directly into the cached
2400** page of the database. The data might change or move the next time
2401** any btree routine is called.
2402*/
2403static const unsigned char *fetchPayload(
2404 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00002405 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00002406 int skipKey /* read beginning at data if this is true */
2407){
2408 unsigned char *aPayload;
2409 MemPage *pPage;
2410 Btree *pBt;
drhfa1a98a2004-05-14 19:08:17 +00002411 u32 nKey;
2412 int nLocal;
drh0e1c19e2004-05-11 00:58:56 +00002413
2414 assert( pCur!=0 && pCur->pPage!=0 );
2415 assert( pCur->isValid );
2416 pBt = pCur->pBt;
2417 pPage = pCur->pPage;
2418 pageIntegrity(pPage);
2419 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00002420 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00002421 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00002422 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00002423 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00002424 nKey = 0;
2425 }else{
2426 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00002427 }
drh0e1c19e2004-05-11 00:58:56 +00002428 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00002429 aPayload += nKey;
2430 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00002431 }else{
drhfa1a98a2004-05-14 19:08:17 +00002432 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00002433 if( nLocal>nKey ){
2434 nLocal = nKey;
2435 }
drh0e1c19e2004-05-11 00:58:56 +00002436 }
drhe51c44f2004-05-30 20:46:09 +00002437 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00002438 return aPayload;
2439}
2440
2441
2442/*
drhe51c44f2004-05-30 20:46:09 +00002443** For the entry that cursor pCur is point to, return as
2444** many bytes of the key or data as are available on the local
2445** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00002446**
2447** The pointer returned is ephemeral. The key/data may move
2448** or be destroyed on the next call to any Btree routine.
2449**
2450** These routines is used to get quick access to key and data
2451** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00002452*/
drhe51c44f2004-05-30 20:46:09 +00002453const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
2454 return (const void*)fetchPayload(pCur, pAmt, 0);
drh0e1c19e2004-05-11 00:58:56 +00002455}
drhe51c44f2004-05-30 20:46:09 +00002456const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
2457 return (const void*)fetchPayload(pCur, pAmt, 1);
drh0e1c19e2004-05-11 00:58:56 +00002458}
2459
2460
2461/*
drh8178a752003-01-05 21:41:40 +00002462** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00002463** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00002464*/
drh3aac2dd2004-04-26 14:10:20 +00002465static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00002466 int rc;
2467 MemPage *pNewPage;
drh3aac2dd2004-04-26 14:10:20 +00002468 MemPage *pOldPage;
drh0d316a42002-08-11 20:10:47 +00002469 Btree *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00002470
drhc39e0002004-05-07 23:50:57 +00002471 assert( pCur->isValid );
drhde647132004-05-07 17:57:49 +00002472 rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00002473 if( rc ) return rc;
drhda200cc2004-05-09 11:51:38 +00002474 pageIntegrity(pNewPage);
drh428ae8c2003-01-04 16:48:09 +00002475 pNewPage->idxParent = pCur->idx;
drh3aac2dd2004-04-26 14:10:20 +00002476 pOldPage = pCur->pPage;
2477 pOldPage->idxShift = 0;
2478 releasePage(pOldPage);
drh72f82862001-05-24 21:06:34 +00002479 pCur->pPage = pNewPage;
2480 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00002481 pCur->info.nSize = 0;
drh4be295b2003-12-16 03:44:47 +00002482 if( pNewPage->nCell<1 ){
drhee696e22004-08-30 16:52:17 +00002483 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
drh4be295b2003-12-16 03:44:47 +00002484 }
drh72f82862001-05-24 21:06:34 +00002485 return SQLITE_OK;
2486}
2487
2488/*
drh8856d6a2004-04-29 14:42:46 +00002489** Return true if the page is the virtual root of its table.
2490**
2491** The virtual root page is the root page for most tables. But
2492** for the table rooted on page 1, sometime the real root page
2493** is empty except for the right-pointer. In such cases the
2494** virtual root page is the page that the right-pointer of page
2495** 1 is pointing to.
2496*/
2497static int isRootPage(MemPage *pPage){
2498 MemPage *pParent = pPage->pParent;
drhda200cc2004-05-09 11:51:38 +00002499 if( pParent==0 ) return 1;
2500 if( pParent->pgno>1 ) return 0;
2501 if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
drh8856d6a2004-04-29 14:42:46 +00002502 return 0;
2503}
2504
2505/*
drh5e2f8b92001-05-28 00:41:15 +00002506** Move the cursor up to the parent page.
2507**
2508** pCur->idx is set to the cell index that contains the pointer
2509** to the page we are coming from. If we are coming from the
2510** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00002511** the largest cell index.
drh72f82862001-05-24 21:06:34 +00002512*/
drh8178a752003-01-05 21:41:40 +00002513static void moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00002514 Pgno oldPgno;
2515 MemPage *pParent;
drh8178a752003-01-05 21:41:40 +00002516 MemPage *pPage;
drh428ae8c2003-01-04 16:48:09 +00002517 int idxParent;
drh3aac2dd2004-04-26 14:10:20 +00002518
drhc39e0002004-05-07 23:50:57 +00002519 assert( pCur->isValid );
drh8178a752003-01-05 21:41:40 +00002520 pPage = pCur->pPage;
2521 assert( pPage!=0 );
drh8856d6a2004-04-29 14:42:46 +00002522 assert( !isRootPage(pPage) );
drhda200cc2004-05-09 11:51:38 +00002523 pageIntegrity(pPage);
drh8178a752003-01-05 21:41:40 +00002524 pParent = pPage->pParent;
2525 assert( pParent!=0 );
drhda200cc2004-05-09 11:51:38 +00002526 pageIntegrity(pParent);
drh8178a752003-01-05 21:41:40 +00002527 idxParent = pPage->idxParent;
drha34b6762004-05-07 13:30:42 +00002528 sqlite3pager_ref(pParent->aData);
drh3aac2dd2004-04-26 14:10:20 +00002529 oldPgno = pPage->pgno;
2530 releasePage(pPage);
drh72f82862001-05-24 21:06:34 +00002531 pCur->pPage = pParent;
drh271efa52004-05-30 19:19:05 +00002532 pCur->info.nSize = 0;
drh428ae8c2003-01-04 16:48:09 +00002533 assert( pParent->idxShift==0 );
drh43605152004-05-29 21:46:49 +00002534 pCur->idx = idxParent;
drh72f82862001-05-24 21:06:34 +00002535}
2536
2537/*
2538** Move the cursor to the root page
2539*/
drh5e2f8b92001-05-28 00:41:15 +00002540static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00002541 MemPage *pRoot;
drhbd03cae2001-06-02 02:40:57 +00002542 int rc;
drh0d316a42002-08-11 20:10:47 +00002543 Btree *pBt = pCur->pBt;
drhbd03cae2001-06-02 02:40:57 +00002544
drhde647132004-05-07 17:57:49 +00002545 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0);
drhc39e0002004-05-07 23:50:57 +00002546 if( rc ){
2547 pCur->isValid = 0;
2548 return rc;
2549 }
drh3aac2dd2004-04-26 14:10:20 +00002550 releasePage(pCur->pPage);
drhda200cc2004-05-09 11:51:38 +00002551 pageIntegrity(pRoot);
drh3aac2dd2004-04-26 14:10:20 +00002552 pCur->pPage = pRoot;
drh72f82862001-05-24 21:06:34 +00002553 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00002554 pCur->info.nSize = 0;
drh8856d6a2004-04-29 14:42:46 +00002555 if( pRoot->nCell==0 && !pRoot->leaf ){
2556 Pgno subpage;
2557 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00002558 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00002559 assert( subpage>0 );
drh3644f082004-05-10 18:45:09 +00002560 pCur->isValid = 1;
drh4b70f112004-05-02 21:12:19 +00002561 rc = moveToChild(pCur, subpage);
drh8856d6a2004-04-29 14:42:46 +00002562 }
drhc39e0002004-05-07 23:50:57 +00002563 pCur->isValid = pCur->pPage->nCell>0;
drh8856d6a2004-04-29 14:42:46 +00002564 return rc;
drh72f82862001-05-24 21:06:34 +00002565}
drh2af926b2001-05-15 00:39:25 +00002566
drh5e2f8b92001-05-28 00:41:15 +00002567/*
2568** Move the cursor down to the left-most leaf entry beneath the
2569** entry to which it is currently pointing.
2570*/
2571static int moveToLeftmost(BtCursor *pCur){
2572 Pgno pgno;
2573 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002574 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00002575
drhc39e0002004-05-07 23:50:57 +00002576 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00002577 while( !(pPage = pCur->pPage)->leaf ){
drha34b6762004-05-07 13:30:42 +00002578 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00002579 pgno = get4byte(findCell(pPage, pCur->idx));
drh8178a752003-01-05 21:41:40 +00002580 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00002581 if( rc ) return rc;
2582 }
2583 return SQLITE_OK;
2584}
2585
drh2dcc9aa2002-12-04 13:40:25 +00002586/*
2587** Move the cursor down to the right-most leaf entry beneath the
2588** page to which it is currently pointing. Notice the difference
2589** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
2590** finds the left-most entry beneath the *entry* whereas moveToRightmost()
2591** finds the right-most entry beneath the *page*.
2592*/
2593static int moveToRightmost(BtCursor *pCur){
2594 Pgno pgno;
2595 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002596 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00002597
drhc39e0002004-05-07 23:50:57 +00002598 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00002599 while( !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00002600 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh3aac2dd2004-04-26 14:10:20 +00002601 pCur->idx = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00002602 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00002603 if( rc ) return rc;
2604 }
drh3aac2dd2004-04-26 14:10:20 +00002605 pCur->idx = pPage->nCell - 1;
drh271efa52004-05-30 19:19:05 +00002606 pCur->info.nSize = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002607 return SQLITE_OK;
2608}
2609
drh5e00f6c2001-09-13 13:46:56 +00002610/* Move the cursor to the first entry in the table. Return SQLITE_OK
2611** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00002612** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00002613*/
drh3aac2dd2004-04-26 14:10:20 +00002614int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00002615 int rc;
2616 rc = moveToRoot(pCur);
2617 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00002618 if( pCur->isValid==0 ){
2619 assert( pCur->pPage->nCell==0 );
drh5e00f6c2001-09-13 13:46:56 +00002620 *pRes = 1;
2621 return SQLITE_OK;
2622 }
drhc39e0002004-05-07 23:50:57 +00002623 assert( pCur->pPage->nCell>0 );
drh5e00f6c2001-09-13 13:46:56 +00002624 *pRes = 0;
2625 rc = moveToLeftmost(pCur);
2626 return rc;
2627}
drh5e2f8b92001-05-28 00:41:15 +00002628
drh9562b552002-02-19 15:00:07 +00002629/* Move the cursor to the last entry in the table. Return SQLITE_OK
2630** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00002631** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00002632*/
drh3aac2dd2004-04-26 14:10:20 +00002633int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00002634 int rc;
drh9562b552002-02-19 15:00:07 +00002635 rc = moveToRoot(pCur);
2636 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00002637 if( pCur->isValid==0 ){
2638 assert( pCur->pPage->nCell==0 );
drh9562b552002-02-19 15:00:07 +00002639 *pRes = 1;
2640 return SQLITE_OK;
2641 }
drhc39e0002004-05-07 23:50:57 +00002642 assert( pCur->isValid );
drh9562b552002-02-19 15:00:07 +00002643 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002644 rc = moveToRightmost(pCur);
drh9562b552002-02-19 15:00:07 +00002645 return rc;
2646}
2647
drh3aac2dd2004-04-26 14:10:20 +00002648/* Move the cursor so that it points to an entry near pKey/nKey.
drh72f82862001-05-24 21:06:34 +00002649** Return a success code.
2650**
drh3aac2dd2004-04-26 14:10:20 +00002651** For INTKEY tables, only the nKey parameter is used. pKey is
2652** ignored. For other tables, nKey is the number of bytes of data
2653** in nKey. The comparison function specified when the cursor was
2654** created is used to compare keys.
2655**
drh5e2f8b92001-05-28 00:41:15 +00002656** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00002657** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00002658** were present. The cursor might point to an entry that comes
2659** before or after the key.
2660**
drhbd03cae2001-06-02 02:40:57 +00002661** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00002662** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00002663** this value is as follows:
2664**
2665** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00002666** is smaller than pKey or if the table is empty
2667** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00002668**
2669** *pRes==0 The cursor is left pointing at an entry that
2670** exactly matches pKey.
2671**
2672** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00002673** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00002674*/
drh4a1c3802004-05-12 15:15:47 +00002675int sqlite3BtreeMoveto(BtCursor *pCur, const void *pKey, i64 nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00002676 int rc;
drh5e2f8b92001-05-28 00:41:15 +00002677 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00002678 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00002679 assert( pCur->pPage );
2680 assert( pCur->pPage->isInit );
2681 if( pCur->isValid==0 ){
drhf328bc82004-05-10 23:29:49 +00002682 *pRes = -1;
drhc39e0002004-05-07 23:50:57 +00002683 assert( pCur->pPage->nCell==0 );
2684 return SQLITE_OK;
2685 }
drh72f82862001-05-24 21:06:34 +00002686 for(;;){
2687 int lwr, upr;
2688 Pgno chldPg;
2689 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00002690 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00002691 lwr = 0;
2692 upr = pPage->nCell-1;
drhda200cc2004-05-09 11:51:38 +00002693 pageIntegrity(pPage);
drh72f82862001-05-24 21:06:34 +00002694 while( lwr<=upr ){
danielk197713adf8a2004-06-03 16:08:41 +00002695 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00002696 i64 nCellKey;
drh72f82862001-05-24 21:06:34 +00002697 pCur->idx = (lwr+upr)/2;
drh271efa52004-05-30 19:19:05 +00002698 pCur->info.nSize = 0;
drhde647132004-05-07 17:57:49 +00002699 sqlite3BtreeKeySize(pCur, &nCellKey);
drh3aac2dd2004-04-26 14:10:20 +00002700 if( pPage->intKey ){
2701 if( nCellKey<nKey ){
2702 c = -1;
2703 }else if( nCellKey>nKey ){
2704 c = +1;
2705 }else{
2706 c = 0;
2707 }
drh3aac2dd2004-04-26 14:10:20 +00002708 }else{
drhe51c44f2004-05-30 20:46:09 +00002709 int available;
danielk197713adf8a2004-06-03 16:08:41 +00002710 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drhe51c44f2004-05-30 20:46:09 +00002711 if( available>=nCellKey ){
2712 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
2713 }else{
2714 pCellKey = sqliteMallocRaw( nCellKey );
2715 if( pCellKey==0 ) return SQLITE_NOMEM;
danielk197713adf8a2004-06-03 16:08:41 +00002716 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
drhe51c44f2004-05-30 20:46:09 +00002717 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
2718 sqliteFree(pCellKey);
2719 if( rc ) return rc;
2720 }
drh3aac2dd2004-04-26 14:10:20 +00002721 }
drh72f82862001-05-24 21:06:34 +00002722 if( c==0 ){
drh8b18dd42004-05-12 19:18:15 +00002723 if( pPage->leafData && !pPage->leaf ){
drhfc70e6f2004-05-12 21:11:27 +00002724 lwr = pCur->idx;
2725 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00002726 break;
2727 }else{
drh8b18dd42004-05-12 19:18:15 +00002728 if( pRes ) *pRes = 0;
2729 return SQLITE_OK;
2730 }
drh72f82862001-05-24 21:06:34 +00002731 }
2732 if( c<0 ){
2733 lwr = pCur->idx+1;
2734 }else{
2735 upr = pCur->idx-1;
2736 }
2737 }
2738 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00002739 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00002740 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00002741 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00002742 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00002743 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00002744 }else{
drh43605152004-05-29 21:46:49 +00002745 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00002746 }
2747 if( chldPg==0 ){
drhc39e0002004-05-07 23:50:57 +00002748 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00002749 if( pRes ) *pRes = c;
2750 return SQLITE_OK;
2751 }
drh428ae8c2003-01-04 16:48:09 +00002752 pCur->idx = lwr;
drh271efa52004-05-30 19:19:05 +00002753 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00002754 rc = moveToChild(pCur, chldPg);
drhc39e0002004-05-07 23:50:57 +00002755 if( rc ){
2756 return rc;
2757 }
drh72f82862001-05-24 21:06:34 +00002758 }
drhbd03cae2001-06-02 02:40:57 +00002759 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00002760}
2761
2762/*
drhc39e0002004-05-07 23:50:57 +00002763** Return TRUE if the cursor is not pointing at an entry of the table.
2764**
2765** TRUE will be returned after a call to sqlite3BtreeNext() moves
2766** past the last entry in the table or sqlite3BtreePrev() moves past
2767** the first entry. TRUE is also returned if the table is empty.
2768*/
2769int sqlite3BtreeEof(BtCursor *pCur){
2770 return pCur->isValid==0;
2771}
2772
2773/*
drhbd03cae2001-06-02 02:40:57 +00002774** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00002775** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00002776** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00002777** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00002778*/
drh3aac2dd2004-04-26 14:10:20 +00002779int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00002780 int rc;
drh8178a752003-01-05 21:41:40 +00002781 MemPage *pPage = pCur->pPage;
drh8b18dd42004-05-12 19:18:15 +00002782
drh8c1238a2003-01-02 14:43:55 +00002783 assert( pRes!=0 );
drhc39e0002004-05-07 23:50:57 +00002784 if( pCur->isValid==0 ){
drh8c1238a2003-01-02 14:43:55 +00002785 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00002786 return SQLITE_OK;
drhecdc7532001-09-23 02:35:53 +00002787 }
drh8178a752003-01-05 21:41:40 +00002788 assert( pPage->isInit );
drh8178a752003-01-05 21:41:40 +00002789 assert( pCur->idx<pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00002790
drh72f82862001-05-24 21:06:34 +00002791 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00002792 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00002793 if( pCur->idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00002794 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00002795 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00002796 if( rc ) return rc;
2797 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00002798 *pRes = 0;
2799 return rc;
drh72f82862001-05-24 21:06:34 +00002800 }
drh5e2f8b92001-05-28 00:41:15 +00002801 do{
drh8856d6a2004-04-29 14:42:46 +00002802 if( isRootPage(pPage) ){
drh8c1238a2003-01-02 14:43:55 +00002803 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00002804 pCur->isValid = 0;
drh5e2f8b92001-05-28 00:41:15 +00002805 return SQLITE_OK;
2806 }
drh8178a752003-01-05 21:41:40 +00002807 moveToParent(pCur);
2808 pPage = pCur->pPage;
2809 }while( pCur->idx>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00002810 *pRes = 0;
drh8b18dd42004-05-12 19:18:15 +00002811 if( pPage->leafData ){
2812 rc = sqlite3BtreeNext(pCur, pRes);
2813 }else{
2814 rc = SQLITE_OK;
2815 }
2816 return rc;
drh8178a752003-01-05 21:41:40 +00002817 }
2818 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00002819 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00002820 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00002821 }
drh5e2f8b92001-05-28 00:41:15 +00002822 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00002823 return rc;
drh72f82862001-05-24 21:06:34 +00002824}
2825
drh3b7511c2001-05-26 13:15:44 +00002826/*
drh2dcc9aa2002-12-04 13:40:25 +00002827** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00002828** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00002829** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00002830** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00002831*/
drh3aac2dd2004-04-26 14:10:20 +00002832int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00002833 int rc;
2834 Pgno pgno;
drh8178a752003-01-05 21:41:40 +00002835 MemPage *pPage;
drhc39e0002004-05-07 23:50:57 +00002836 if( pCur->isValid==0 ){
2837 *pRes = 1;
2838 return SQLITE_OK;
2839 }
danielk19776a43f9b2004-11-16 04:57:24 +00002840
drh8178a752003-01-05 21:41:40 +00002841 pPage = pCur->pPage;
drh8178a752003-01-05 21:41:40 +00002842 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00002843 assert( pCur->idx>=0 );
drha34b6762004-05-07 13:30:42 +00002844 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00002845 pgno = get4byte( findCell(pPage, pCur->idx) );
drh8178a752003-01-05 21:41:40 +00002846 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00002847 if( rc ) return rc;
2848 rc = moveToRightmost(pCur);
2849 }else{
2850 while( pCur->idx==0 ){
drh8856d6a2004-04-29 14:42:46 +00002851 if( isRootPage(pPage) ){
drhc39e0002004-05-07 23:50:57 +00002852 pCur->isValid = 0;
2853 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00002854 return SQLITE_OK;
2855 }
drh8178a752003-01-05 21:41:40 +00002856 moveToParent(pCur);
2857 pPage = pCur->pPage;
drh2dcc9aa2002-12-04 13:40:25 +00002858 }
2859 pCur->idx--;
drh271efa52004-05-30 19:19:05 +00002860 pCur->info.nSize = 0;
drh8237d452004-11-22 19:07:09 +00002861 if( pPage->leafData && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00002862 rc = sqlite3BtreePrevious(pCur, pRes);
2863 }else{
2864 rc = SQLITE_OK;
2865 }
drh2dcc9aa2002-12-04 13:40:25 +00002866 }
drh8178a752003-01-05 21:41:40 +00002867 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002868 return rc;
2869}
2870
2871/*
drh3b7511c2001-05-26 13:15:44 +00002872** Allocate a new page from the database file.
2873**
drha34b6762004-05-07 13:30:42 +00002874** The new page is marked as dirty. (In other words, sqlite3pager_write()
drh3b7511c2001-05-26 13:15:44 +00002875** has already been called on the new page.) The new page has also
2876** been referenced and the calling routine is responsible for calling
drha34b6762004-05-07 13:30:42 +00002877** sqlite3pager_unref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00002878**
2879** SQLITE_OK is returned on success. Any other return value indicates
2880** an error. *ppPage and *pPgno are undefined in the event of an error.
drha34b6762004-05-07 13:30:42 +00002881** Do not invoke sqlite3pager_unref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00002882**
drh199e3cf2002-07-18 11:01:47 +00002883** If the "nearby" parameter is not 0, then a (feeble) effort is made to
2884** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00002885** attempt to keep related pages close to each other in the database file,
2886** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00002887**
2888** If the "exact" parameter is not 0, and the page-number nearby exists
2889** anywhere on the free-list, then it is guarenteed to be returned. This
2890** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00002891*/
danielk1977cb1a7eb2004-11-05 12:27:02 +00002892static int allocatePage(
2893 Btree *pBt,
2894 MemPage **ppPage,
2895 Pgno *pPgno,
2896 Pgno nearby,
2897 u8 exact
2898){
drh3aac2dd2004-04-26 14:10:20 +00002899 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00002900 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002901 int n; /* Number of pages on the freelist */
2902 int k; /* Number of leaves on the trunk of the freelist */
drh30e58752002-03-02 20:41:57 +00002903
drh3aac2dd2004-04-26 14:10:20 +00002904 pPage1 = pBt->pPage1;
2905 n = get4byte(&pPage1->aData[36]);
2906 if( n>0 ){
drh91025292004-05-03 19:49:32 +00002907 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00002908 MemPage *pTrunk = 0;
2909 Pgno iTrunk;
2910 MemPage *pPrevTrunk = 0;
2911 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
2912
2913 /* If the 'exact' parameter was true and a query of the pointer-map
2914 ** shows that the page 'nearby' is somewhere on the free-list, then
2915 ** the entire-list will be searched for that page.
2916 */
2917#ifndef SQLITE_OMIT_AUTOVACUUM
2918 if( exact ){
2919 u8 eType;
2920 assert( nearby>0 );
2921 assert( pBt->autoVacuum );
2922 rc = ptrmapGet(pBt, nearby, &eType, 0);
2923 if( rc ) return rc;
2924 if( eType==PTRMAP_FREEPAGE ){
2925 searchList = 1;
2926 }
2927 *pPgno = nearby;
2928 }
2929#endif
2930
2931 /* Decrement the free-list count by 1. Set iTrunk to the index of the
2932 ** first free-list trunk page. iPrevTrunk is initially 1.
2933 */
drha34b6762004-05-07 13:30:42 +00002934 rc = sqlite3pager_write(pPage1->aData);
drh3b7511c2001-05-26 13:15:44 +00002935 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00002936 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00002937
2938 /* The code within this loop is run only once if the 'searchList' variable
2939 ** is not true. Otherwise, it runs once for each trunk-page on the
2940 ** free-list until the page 'nearby' is located.
2941 */
2942 do {
2943 pPrevTrunk = pTrunk;
2944 if( pPrevTrunk ){
2945 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00002946 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00002947 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00002948 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00002949 rc = getPage(pBt, iTrunk, &pTrunk);
2950 if( rc ){
2951 releasePage(pPrevTrunk);
2952 return rc;
2953 }
2954
2955 /* TODO: This should move to after the loop? */
2956 rc = sqlite3pager_write(pTrunk->aData);
2957 if( rc ){
2958 releasePage(pTrunk);
2959 releasePage(pPrevTrunk);
2960 return rc;
2961 }
2962
2963 k = get4byte(&pTrunk->aData[4]);
2964 if( k==0 && !searchList ){
2965 /* The trunk has no leaves and the list is not being searched.
2966 ** So extract the trunk page itself and use it as the newly
2967 ** allocated page */
2968 assert( pPrevTrunk==0 );
2969 *pPgno = iTrunk;
2970 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
2971 *ppPage = pTrunk;
2972 pTrunk = 0;
2973 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
2974 }else if( k>pBt->usableSize/4 - 8 ){
2975 /* Value of k is out of range. Database corruption */
drhee696e22004-08-30 16:52:17 +00002976 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
danielk1977cb1a7eb2004-11-05 12:27:02 +00002977#ifndef SQLITE_OMIT_AUTOVACUUM
2978 }else if( searchList && nearby==iTrunk ){
2979 /* The list is being searched and this trunk page is the page
2980 ** to allocate, regardless of whether it has leaves.
2981 */
2982 assert( *pPgno==iTrunk );
2983 *ppPage = pTrunk;
2984 searchList = 0;
2985 if( k==0 ){
2986 if( !pPrevTrunk ){
2987 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
2988 }else{
2989 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
2990 }
2991 }else{
2992 /* The trunk page is required by the caller but it contains
2993 ** pointers to free-list leaves. The first leaf becomes a trunk
2994 ** page in this case.
2995 */
2996 MemPage *pNewTrunk;
2997 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
2998 rc = getPage(pBt, iNewTrunk, &pNewTrunk);
2999 if( rc!=SQLITE_OK ){
3000 releasePage(pTrunk);
3001 releasePage(pPrevTrunk);
3002 return rc;
3003 }
3004 rc = sqlite3pager_write(pNewTrunk->aData);
3005 if( rc!=SQLITE_OK ){
3006 releasePage(pNewTrunk);
3007 releasePage(pTrunk);
3008 releasePage(pPrevTrunk);
3009 return rc;
3010 }
3011 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
3012 put4byte(&pNewTrunk->aData[4], k-1);
3013 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
3014 if( !pPrevTrunk ){
3015 put4byte(&pPage1->aData[32], iNewTrunk);
3016 }else{
3017 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
3018 }
3019 releasePage(pNewTrunk);
3020 }
3021 pTrunk = 0;
3022 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3023#endif
3024 }else{
3025 /* Extract a leaf from the trunk */
3026 int closest;
3027 Pgno iPage;
3028 unsigned char *aData = pTrunk->aData;
3029 if( nearby>0 ){
3030 int i, dist;
3031 closest = 0;
3032 dist = get4byte(&aData[8]) - nearby;
3033 if( dist<0 ) dist = -dist;
3034 for(i=1; i<k; i++){
3035 int d2 = get4byte(&aData[8+i*4]) - nearby;
3036 if( d2<0 ) d2 = -d2;
3037 if( d2<dist ){
3038 closest = i;
3039 dist = d2;
3040 }
3041 }
3042 }else{
3043 closest = 0;
3044 }
3045
3046 iPage = get4byte(&aData[8+closest*4]);
3047 if( !searchList || iPage==nearby ){
3048 *pPgno = iPage;
3049 if( *pPgno>sqlite3pager_pagecount(pBt->pPager) ){
3050 /* Free page off the end of the file */
3051 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
3052 }
3053 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
3054 ": %d more free pages\n",
3055 *pPgno, closest+1, k, pTrunk->pgno, n-1));
3056 if( closest<k-1 ){
3057 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
3058 }
3059 put4byte(&aData[4], k-1);
3060 rc = getPage(pBt, *pPgno, ppPage);
3061 if( rc==SQLITE_OK ){
3062 sqlite3pager_dont_rollback((*ppPage)->aData);
3063 rc = sqlite3pager_write((*ppPage)->aData);
3064 }
3065 searchList = 0;
3066 }
drhee696e22004-08-30 16:52:17 +00003067 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003068 releasePage(pPrevTrunk);
3069 }while( searchList );
3070 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003071 }else{
drh3aac2dd2004-04-26 14:10:20 +00003072 /* There are no pages on the freelist, so create a new page at the
3073 ** end of the file */
drha34b6762004-05-07 13:30:42 +00003074 *pPgno = sqlite3pager_pagecount(pBt->pPager) + 1;
danielk1977afcdd022004-10-31 16:25:42 +00003075
3076#ifndef SQLITE_OMIT_AUTOVACUUM
drh42cac6d2004-11-20 20:31:11 +00003077 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt->usableSize, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00003078 /* If *pPgno refers to a pointer-map page, allocate two new pages
3079 ** at the end of the file instead of one. The first allocated page
3080 ** becomes a new pointer-map page, the second is used by the caller.
3081 */
3082 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00003083 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977afcdd022004-10-31 16:25:42 +00003084 (*pPgno)++;
3085 }
3086#endif
3087
danielk1977599fcba2004-11-08 07:13:13 +00003088 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00003089 rc = getPage(pBt, *pPgno, ppPage);
drh3b7511c2001-05-26 13:15:44 +00003090 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003091 rc = sqlite3pager_write((*ppPage)->aData);
drh3a4c1412004-05-09 20:40:11 +00003092 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00003093 }
danielk1977599fcba2004-11-08 07:13:13 +00003094
3095 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh3b7511c2001-05-26 13:15:44 +00003096 return rc;
3097}
3098
3099/*
drh3aac2dd2004-04-26 14:10:20 +00003100** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00003101**
drha34b6762004-05-07 13:30:42 +00003102** sqlite3pager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00003103*/
drh3aac2dd2004-04-26 14:10:20 +00003104static int freePage(MemPage *pPage){
3105 Btree *pBt = pPage->pBt;
3106 MemPage *pPage1 = pBt->pPage1;
3107 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00003108
drh3aac2dd2004-04-26 14:10:20 +00003109 /* Prepare the page for freeing */
3110 assert( pPage->pgno>1 );
3111 pPage->isInit = 0;
3112 releasePage(pPage->pParent);
3113 pPage->pParent = 0;
3114
drha34b6762004-05-07 13:30:42 +00003115 /* Increment the free page count on pPage1 */
3116 rc = sqlite3pager_write(pPage1->aData);
drh3aac2dd2004-04-26 14:10:20 +00003117 if( rc ) return rc;
3118 n = get4byte(&pPage1->aData[36]);
3119 put4byte(&pPage1->aData[36], n+1);
3120
danielk1977687566d2004-11-02 12:56:41 +00003121#ifndef SQLITE_OMIT_AUTOVACUUM
3122 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00003123 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00003124 */
3125 if( pBt->autoVacuum ){
3126 rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
danielk1977a64a0352004-11-05 01:45:13 +00003127 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00003128 }
3129#endif
3130
drh3aac2dd2004-04-26 14:10:20 +00003131 if( n==0 ){
3132 /* This is the first free page */
drhda200cc2004-05-09 11:51:38 +00003133 rc = sqlite3pager_write(pPage->aData);
3134 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003135 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00003136 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003137 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003138 }else{
3139 /* Other free pages already exist. Retrive the first trunk page
3140 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00003141 MemPage *pTrunk;
3142 rc = getPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003143 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003144 k = get4byte(&pTrunk->aData[4]);
drhee696e22004-08-30 16:52:17 +00003145 if( k>=pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00003146 /* The trunk is full. Turn the page being freed into a new
3147 ** trunk page with no leaves. */
drha34b6762004-05-07 13:30:42 +00003148 rc = sqlite3pager_write(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00003149 if( rc ) return rc;
3150 put4byte(pPage->aData, pTrunk->pgno);
3151 put4byte(&pPage->aData[4], 0);
3152 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003153 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
3154 pPage->pgno, pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003155 }else{
3156 /* Add the newly freed page as a leaf on the current trunk */
drha34b6762004-05-07 13:30:42 +00003157 rc = sqlite3pager_write(pTrunk->aData);
drh3aac2dd2004-04-26 14:10:20 +00003158 if( rc ) return rc;
3159 put4byte(&pTrunk->aData[4], k+1);
3160 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drha34b6762004-05-07 13:30:42 +00003161 sqlite3pager_dont_write(pBt->pPager, pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003162 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003163 }
3164 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003165 }
drh3b7511c2001-05-26 13:15:44 +00003166 return rc;
3167}
3168
3169/*
drh3aac2dd2004-04-26 14:10:20 +00003170** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00003171*/
drh3aac2dd2004-04-26 14:10:20 +00003172static int clearCell(MemPage *pPage, unsigned char *pCell){
3173 Btree *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00003174 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00003175 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00003176 int rc;
drh3b7511c2001-05-26 13:15:44 +00003177
drh43605152004-05-29 21:46:49 +00003178 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003179 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00003180 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00003181 }
drh6f11bef2004-05-13 01:12:56 +00003182 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh3aac2dd2004-04-26 14:10:20 +00003183 while( ovflPgno!=0 ){
3184 MemPage *pOvfl;
3185 rc = getPage(pBt, ovflPgno, &pOvfl);
drh3b7511c2001-05-26 13:15:44 +00003186 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003187 ovflPgno = get4byte(pOvfl->aData);
drha34b6762004-05-07 13:30:42 +00003188 rc = freePage(pOvfl);
drhbd03cae2001-06-02 02:40:57 +00003189 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003190 sqlite3pager_unref(pOvfl->aData);
drh3b7511c2001-05-26 13:15:44 +00003191 }
drh5e2f8b92001-05-28 00:41:15 +00003192 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00003193}
3194
3195/*
drh91025292004-05-03 19:49:32 +00003196** Create the byte sequence used to represent a cell on page pPage
3197** and write that byte sequence into pCell[]. Overflow pages are
3198** allocated and filled in as necessary. The calling procedure
3199** is responsible for making sure sufficient space has been allocated
3200** for pCell[].
3201**
3202** Note that pCell does not necessary need to point to the pPage->aData
3203** area. pCell might point to some temporary storage. The cell will
3204** be constructed in this temporary area then copied into pPage->aData
3205** later.
drh3b7511c2001-05-26 13:15:44 +00003206*/
3207static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00003208 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00003209 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00003210 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00003211 const void *pData,int nData, /* The data */
3212 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00003213){
drh3b7511c2001-05-26 13:15:44 +00003214 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00003215 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00003216 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00003217 int spaceLeft;
3218 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00003219 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00003220 unsigned char *pPrior;
3221 unsigned char *pPayload;
3222 Btree *pBt = pPage->pBt;
3223 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00003224 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00003225 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00003226
drh91025292004-05-03 19:49:32 +00003227 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00003228 nHeader = 0;
drh91025292004-05-03 19:49:32 +00003229 if( !pPage->leaf ){
3230 nHeader += 4;
3231 }
drh8b18dd42004-05-12 19:18:15 +00003232 if( pPage->hasData ){
drh91025292004-05-03 19:49:32 +00003233 nHeader += putVarint(&pCell[nHeader], nData);
drh6f11bef2004-05-13 01:12:56 +00003234 }else{
drh91025292004-05-03 19:49:32 +00003235 nData = 0;
3236 }
drh6f11bef2004-05-13 01:12:56 +00003237 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh43605152004-05-29 21:46:49 +00003238 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003239 assert( info.nHeader==nHeader );
3240 assert( info.nKey==nKey );
3241 assert( info.nData==nData );
3242
3243 /* Fill in the payload */
drh3aac2dd2004-04-26 14:10:20 +00003244 nPayload = nData;
3245 if( pPage->intKey ){
3246 pSrc = pData;
3247 nSrc = nData;
drh91025292004-05-03 19:49:32 +00003248 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00003249 }else{
3250 nPayload += nKey;
3251 pSrc = pKey;
3252 nSrc = nKey;
3253 }
drh6f11bef2004-05-13 01:12:56 +00003254 *pnSize = info.nSize;
3255 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00003256 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00003257 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00003258
drh3b7511c2001-05-26 13:15:44 +00003259 while( nPayload>0 ){
3260 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00003261#ifndef SQLITE_OMIT_AUTOVACUUM
3262 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
3263#endif
danielk1977cb1a7eb2004-11-05 12:27:02 +00003264 rc = allocatePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00003265#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00003266 /* If the database supports auto-vacuum, and the second or subsequent
3267 ** overflow page is being allocated, add an entry to the pointer-map
3268 ** for that page now. The entry for the first overflow page will be
3269 ** added later, by the insertCell() routine.
danielk1977afcdd022004-10-31 16:25:42 +00003270 */
danielk1977a19df672004-11-03 11:37:07 +00003271 if( pBt->autoVacuum && pgnoPtrmap!=0 && rc==SQLITE_OK ){
3272 rc = ptrmapPut(pBt, pgnoOvfl, PTRMAP_OVERFLOW2, pgnoPtrmap);
danielk1977afcdd022004-10-31 16:25:42 +00003273 }
3274#endif
drh3b7511c2001-05-26 13:15:44 +00003275 if( rc ){
drh9b171272004-05-08 02:03:22 +00003276 releasePage(pToRelease);
danielk197728129562005-01-11 10:25:06 +00003277 /* clearCell(pPage, pCell); */
drh3b7511c2001-05-26 13:15:44 +00003278 return rc;
3279 }
drh3aac2dd2004-04-26 14:10:20 +00003280 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00003281 releasePage(pToRelease);
3282 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00003283 pPrior = pOvfl->aData;
3284 put4byte(pPrior, 0);
3285 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00003286 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00003287 }
3288 n = nPayload;
3289 if( n>spaceLeft ) n = spaceLeft;
drh3aac2dd2004-04-26 14:10:20 +00003290 if( n>nSrc ) n = nSrc;
3291 memcpy(pPayload, pSrc, n);
drh3b7511c2001-05-26 13:15:44 +00003292 nPayload -= n;
drhde647132004-05-07 17:57:49 +00003293 pPayload += n;
drh9b171272004-05-08 02:03:22 +00003294 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00003295 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00003296 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00003297 if( nSrc==0 ){
3298 nSrc = nData;
3299 pSrc = pData;
3300 }
drhdd793422001-06-28 01:54:48 +00003301 }
drh9b171272004-05-08 02:03:22 +00003302 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00003303 return SQLITE_OK;
3304}
3305
3306/*
drhbd03cae2001-06-02 02:40:57 +00003307** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00003308** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00003309** pointer in the third argument.
3310*/
danielk1977afcdd022004-10-31 16:25:42 +00003311static int reparentPage(Btree *pBt, Pgno pgno, MemPage *pNewParent, int idx){
drhbd03cae2001-06-02 02:40:57 +00003312 MemPage *pThis;
drh4b70f112004-05-02 21:12:19 +00003313 unsigned char *aData;
drhbd03cae2001-06-02 02:40:57 +00003314
danielk1977afcdd022004-10-31 16:25:42 +00003315 if( pgno==0 ) return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00003316 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00003317 aData = sqlite3pager_lookup(pBt->pPager, pgno);
drhda200cc2004-05-09 11:51:38 +00003318 if( aData ){
drh887dc4c2004-10-22 16:22:57 +00003319 pThis = (MemPage*)&aData[pBt->psAligned];
drh31276532004-09-27 12:20:52 +00003320 assert( pThis->aData==aData );
drhda200cc2004-05-09 11:51:38 +00003321 if( pThis->isInit ){
3322 if( pThis->pParent!=pNewParent ){
3323 if( pThis->pParent ) sqlite3pager_unref(pThis->pParent->aData);
3324 pThis->pParent = pNewParent;
3325 if( pNewParent ) sqlite3pager_ref(pNewParent->aData);
3326 }
3327 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00003328 }
drha34b6762004-05-07 13:30:42 +00003329 sqlite3pager_unref(aData);
drhbd03cae2001-06-02 02:40:57 +00003330 }
danielk1977afcdd022004-10-31 16:25:42 +00003331
3332#ifndef SQLITE_OMIT_AUTOVACUUM
3333 if( pBt->autoVacuum ){
3334 return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
3335 }
3336#endif
3337 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00003338}
3339
danielk1977ac11ee62005-01-15 12:45:51 +00003340
3341
drhbd03cae2001-06-02 02:40:57 +00003342/*
drh4b70f112004-05-02 21:12:19 +00003343** Change the pParent pointer of all children of pPage to point back
3344** to pPage.
3345**
drhbd03cae2001-06-02 02:40:57 +00003346** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00003347** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00003348**
3349** This routine gets called after you memcpy() one page into
3350** another.
3351*/
danielk1977afcdd022004-10-31 16:25:42 +00003352static int reparentChildPages(MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00003353 int i;
danielk1977afcdd022004-10-31 16:25:42 +00003354 Btree *pBt = pPage->pBt;
3355 int rc = SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00003356
danielk1977afcdd022004-10-31 16:25:42 +00003357 if( pPage->leaf ) return SQLITE_OK;
danielk1977afcdd022004-10-31 16:25:42 +00003358
drhbd03cae2001-06-02 02:40:57 +00003359 for(i=0; i<pPage->nCell; i++){
danielk1977afcdd022004-10-31 16:25:42 +00003360 u8 *pCell = findCell(pPage, i);
3361 if( !pPage->leaf ){
3362 rc = reparentPage(pBt, get4byte(pCell), pPage, i);
3363 if( rc!=SQLITE_OK ) return rc;
3364 }
drhbd03cae2001-06-02 02:40:57 +00003365 }
danielk1977afcdd022004-10-31 16:25:42 +00003366 if( !pPage->leaf ){
3367 rc = reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]),
3368 pPage, i);
3369 pPage->idxShift = 0;
3370 }
3371 return rc;
drh14acc042001-06-10 19:56:58 +00003372}
3373
3374/*
3375** Remove the i-th cell from pPage. This routine effects pPage only.
3376** The cell content is not freed or deallocated. It is assumed that
3377** the cell content has been copied someplace else. This routine just
3378** removes the reference to the cell from pPage.
3379**
3380** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00003381*/
drh4b70f112004-05-02 21:12:19 +00003382static void dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00003383 int i; /* Loop counter */
3384 int pc; /* Offset to cell content of cell being deleted */
3385 u8 *data; /* pPage->aData */
3386 u8 *ptr; /* Used to move bytes around within data[] */
3387
drh8c42ca92001-06-22 19:15:00 +00003388 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00003389 assert( sz==cellSize(pPage, idx) );
drha34b6762004-05-07 13:30:42 +00003390 assert( sqlite3pager_iswriteable(pPage->aData) );
drhda200cc2004-05-09 11:51:38 +00003391 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00003392 ptr = &data[pPage->cellOffset + 2*idx];
3393 pc = get2byte(ptr);
3394 assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
drhde647132004-05-07 17:57:49 +00003395 freeSpace(pPage, pc, sz);
drh43605152004-05-29 21:46:49 +00003396 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
3397 ptr[0] = ptr[2];
3398 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00003399 }
3400 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00003401 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
3402 pPage->nFree += 2;
drh428ae8c2003-01-04 16:48:09 +00003403 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00003404}
3405
3406/*
3407** Insert a new cell on pPage at cell index "i". pCell points to the
3408** content of the cell.
3409**
3410** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00003411** will not fit, then make a copy of the cell content into pTemp if
3412** pTemp is not null. Regardless of pTemp, allocate a new entry
3413** in pPage->aOvfl[] and make it point to the cell content (either
3414** in pTemp or the original pCell) and also record its index.
3415** Allocating a new entry in pPage->aCell[] implies that
3416** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00003417**
3418** If nSkip is non-zero, then do not copy the first nSkip bytes of the
3419** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00003420** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00003421** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00003422*/
danielk1977e80463b2004-11-03 03:01:16 +00003423static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00003424 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00003425 int i, /* New cell becomes the i-th cell of the page */
3426 u8 *pCell, /* Content of the new cell */
3427 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00003428 u8 *pTemp, /* Temp storage space for pCell, if needed */
3429 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00003430){
drh43605152004-05-29 21:46:49 +00003431 int idx; /* Where to write new cell content in data[] */
3432 int j; /* Loop counter */
3433 int top; /* First byte of content for any cell in data[] */
3434 int end; /* First byte past the last cell pointer in data[] */
3435 int ins; /* Index in data[] where new cell pointer is inserted */
3436 int hdr; /* Offset into data[] of the page header */
3437 int cellOffset; /* Address of first cell pointer in data[] */
3438 u8 *data; /* The content of the whole page */
3439 u8 *ptr; /* Used for moving information around in data[] */
3440
3441 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
3442 assert( sz==cellSizePtr(pPage, pCell) );
drha34b6762004-05-07 13:30:42 +00003443 assert( sqlite3pager_iswriteable(pPage->aData) );
drh43605152004-05-29 21:46:49 +00003444 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00003445 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00003446 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00003447 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00003448 }
drh43605152004-05-29 21:46:49 +00003449 j = pPage->nOverflow++;
3450 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
3451 pPage->aOvfl[j].pCell = pCell;
3452 pPage->aOvfl[j].idx = i;
3453 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00003454 }else{
drh43605152004-05-29 21:46:49 +00003455 data = pPage->aData;
3456 hdr = pPage->hdrOffset;
3457 top = get2byte(&data[hdr+5]);
3458 cellOffset = pPage->cellOffset;
3459 end = cellOffset + 2*pPage->nCell + 2;
3460 ins = cellOffset + 2*i;
3461 if( end > top - sz ){
3462 defragmentPage(pPage);
3463 top = get2byte(&data[hdr+5]);
3464 assert( end + sz <= top );
3465 }
3466 idx = allocateSpace(pPage, sz);
3467 assert( idx>0 );
3468 assert( end <= get2byte(&data[hdr+5]) );
3469 pPage->nCell++;
3470 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00003471 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00003472 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
3473 ptr[0] = ptr[-2];
3474 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00003475 }
drh43605152004-05-29 21:46:49 +00003476 put2byte(&data[ins], idx);
3477 put2byte(&data[hdr+3], pPage->nCell);
3478 pPage->idxShift = 1;
drhda200cc2004-05-09 11:51:38 +00003479 pageIntegrity(pPage);
danielk1977a19df672004-11-03 11:37:07 +00003480#ifndef SQLITE_OMIT_AUTOVACUUM
3481 if( pPage->pBt->autoVacuum ){
3482 /* The cell may contain a pointer to an overflow page. If so, write
3483 ** the entry for the overflow page into the pointer map.
3484 */
3485 CellInfo info;
3486 parseCellPtr(pPage, pCell, &info);
3487 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
3488 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
3489 int rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
3490 if( rc!=SQLITE_OK ) return rc;
3491 }
3492 }
3493#endif
drh14acc042001-06-10 19:56:58 +00003494 }
danielk1977e80463b2004-11-03 03:01:16 +00003495
danielk1977e80463b2004-11-03 03:01:16 +00003496 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00003497}
3498
3499/*
drhfa1a98a2004-05-14 19:08:17 +00003500** Add a list of cells to a page. The page should be initially empty.
3501** The cells are guaranteed to fit on the page.
3502*/
3503static void assemblePage(
3504 MemPage *pPage, /* The page to be assemblied */
3505 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00003506 u8 **apCell, /* Pointers to cell bodies */
drhfa1a98a2004-05-14 19:08:17 +00003507 int *aSize /* Sizes of the cells */
3508){
3509 int i; /* Loop counter */
3510 int totalSize; /* Total size of all cells */
3511 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00003512 int cellptr; /* Address of next cell pointer */
3513 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00003514 u8 *data; /* Data for the page */
3515
drh43605152004-05-29 21:46:49 +00003516 assert( pPage->nOverflow==0 );
drhfa1a98a2004-05-14 19:08:17 +00003517 totalSize = 0;
3518 for(i=0; i<nCell; i++){
3519 totalSize += aSize[i];
3520 }
drh43605152004-05-29 21:46:49 +00003521 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00003522 assert( pPage->nCell==0 );
drh43605152004-05-29 21:46:49 +00003523 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00003524 data = pPage->aData;
3525 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00003526 put2byte(&data[hdr+3], nCell);
3527 cellbody = allocateSpace(pPage, totalSize);
3528 assert( cellbody>0 );
3529 assert( pPage->nFree >= 2*nCell );
3530 pPage->nFree -= 2*nCell;
drhfa1a98a2004-05-14 19:08:17 +00003531 for(i=0; i<nCell; i++){
drh43605152004-05-29 21:46:49 +00003532 put2byte(&data[cellptr], cellbody);
3533 memcpy(&data[cellbody], apCell[i], aSize[i]);
3534 cellptr += 2;
3535 cellbody += aSize[i];
drhfa1a98a2004-05-14 19:08:17 +00003536 }
drh43605152004-05-29 21:46:49 +00003537 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00003538 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00003539}
3540
drh14acc042001-06-10 19:56:58 +00003541/*
drhc3b70572003-01-04 19:44:07 +00003542** The following parameters determine how many adjacent pages get involved
3543** in a balancing operation. NN is the number of neighbors on either side
3544** of the page that participate in the balancing operation. NB is the
3545** total number of pages that participate, including the target page and
3546** NN neighbors on either side.
3547**
3548** The minimum value of NN is 1 (of course). Increasing NN above 1
3549** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
3550** in exchange for a larger degradation in INSERT and UPDATE performance.
3551** The value of NN appears to give the best results overall.
3552*/
3553#define NN 1 /* Number of neighbors on either side of pPage */
3554#define NB (NN*2+1) /* Total pages involved in the balance */
3555
drh43605152004-05-29 21:46:49 +00003556/* Forward reference */
danielk1977ac245ec2005-01-14 13:50:11 +00003557static int balance(MemPage*, int);
3558
drhf222e712005-01-14 22:55:49 +00003559/*
3560** This version of balance() handles the common special case where
3561** a new entry is being inserted on the extreme right-end of the
3562** tree, in other words, when the new entry will become the largest
3563** entry in the tree.
3564**
3565** Instead of trying balance the 3 right-most leaf pages, just add
3566** a new page to the right-hand side and put the one new entry in
3567** that page. This leaves the right side of the tree somewhat
3568** unbalanced. But odds are that we will be inserting new entries
3569** at the end soon afterwards so the nearly empty page will quickly
3570** fill up. On average.
3571**
3572** pPage is the leaf page which is the right-most page in the tree.
3573** pParent is its parent. pPage must have a single overflow entry
3574** which is also the right-most entry on the page.
3575*/
danielk1977ac245ec2005-01-14 13:50:11 +00003576static int balance_quick(MemPage *pPage, MemPage *pParent){
3577 int rc;
3578 MemPage *pNew;
3579 Pgno pgnoNew;
3580 u8 *pCell;
3581 int szCell;
3582 CellInfo info;
danielk1977ac11ee62005-01-15 12:45:51 +00003583 Btree *pBt = pPage->pBt;
danielk1977ac245ec2005-01-14 13:50:11 +00003584
3585 u8 parentCell[64]; /* How big should this be? */
3586 int parentIdx = pParent->nCell;
3587 int parentSize;
3588
3589 /* Allocate a new page. Insert the overflow cell from pPage
3590 ** into it. Then remove the overflow cell from pPage.
3591 */
danielk1977ac11ee62005-01-15 12:45:51 +00003592 rc = allocatePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977ac245ec2005-01-14 13:50:11 +00003593 if( rc!=SQLITE_OK ){
3594 return rc;
3595 }
3596 pCell = pPage->aOvfl[0].pCell;
3597 szCell = cellSizePtr(pPage, pCell);
3598 zeroPage(pNew, pPage->aData[0]);
3599 assemblePage(pNew, 1, &pCell, &szCell);
3600 pPage->nOverflow = 0;
3601
3602 /* pPage is currently the right-child of pParent. Change this
3603 ** so that the right-child is the new page allocated above and
3604 ** pPage is the next-to-right child. Then balance() the parent
3605 ** page, in case it is now overfull.
3606 */
danielk1977ac11ee62005-01-15 12:45:51 +00003607 assert( pPage->nCell>0 );
danielk1977ac245ec2005-01-14 13:50:11 +00003608 parseCellPtr(pPage, findCell(pPage, pPage->nCell-1), &info);
3609 rc = fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, &parentSize);
3610 if( rc!=SQLITE_OK ){
3611 return SQLITE_OK;
3612 }
3613 assert( parentSize<64 );
3614 rc = insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
3615 if( rc!=SQLITE_OK ){
3616 return SQLITE_OK;
3617 }
3618 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
3619 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
3620
3621 pNew->pParent = pParent;
3622 sqlite3pager_ref(pParent->aData);
3623
danielk1977ac11ee62005-01-15 12:45:51 +00003624 if( pBt->autoVacuum ){
3625 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
3626 if( rc!=SQLITE_OK ){
3627 return rc;
3628 }
3629 pCell = findCell(pNew, 0);
3630 parseCellPtr(pNew, pCell, &info);
3631 if( info.nData>info.nLocal ){
3632 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
3633 rc = ptrmapPut(pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pgnoNew);
3634 if( rc!=SQLITE_OK ){
3635 return rc;
3636 }
3637 }
3638 }
3639
danielk1977ac245ec2005-01-14 13:50:11 +00003640 releasePage(pNew);
3641 return balance(pParent, 0);
3642}
drh43605152004-05-29 21:46:49 +00003643
drhc3b70572003-01-04 19:44:07 +00003644/*
danielk1977ac11ee62005-01-15 12:45:51 +00003645** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
3646** if the database supports auto-vacuum or not. Because it is used
3647** within an expression that is an argument to another macro
3648** (sqliteMallocRaw), it is not possible to use conditional compilation.
3649** So, this macro is defined instead.
3650*/
3651#ifndef SQLITE_OMIT_AUTOVACUUM
3652#define ISAUTOVACUUM (pBt->autoVacuum)
3653#else
3654#define ISAUTOVACUUM 0
3655#endif
3656
3657/*
drhab01f612004-05-22 02:55:23 +00003658** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00003659** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00003660** Usually NN siblings on either side of pPage is used in the balancing,
3661** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00003662** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00003663** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00003664** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00003665**
drh0c6cc4e2004-06-15 02:13:26 +00003666** The number of siblings of pPage might be increased or decreased by one or
3667** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00003668** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00003669** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00003670** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00003671** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00003672**
drh8b2f49b2001-06-08 00:21:52 +00003673** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00003674** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00003675** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00003676** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00003677**
drh8c42ca92001-06-22 19:15:00 +00003678** In the course of balancing the siblings of pPage, the parent of pPage
3679** might become overfull or underfull. If that happens, then this routine
3680** is called recursively on the parent.
3681**
drh5e00f6c2001-09-13 13:46:56 +00003682** If this routine fails for any reason, it might leave the database
3683** in a corrupted state. So if this routine fails, the database should
3684** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00003685*/
drh43605152004-05-29 21:46:49 +00003686static int balance_nonroot(MemPage *pPage){
drh8b2f49b2001-06-08 00:21:52 +00003687 MemPage *pParent; /* The parent of pPage */
drh4b70f112004-05-02 21:12:19 +00003688 Btree *pBt; /* The whole database */
danielk1977cfe9a692004-06-16 12:00:29 +00003689 int nCell = 0; /* Number of cells in aCell[] */
drh8b2f49b2001-06-08 00:21:52 +00003690 int nOld; /* Number of pages in apOld[] */
3691 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00003692 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00003693 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00003694 int idx; /* Index of pPage in pParent->aCell[] */
3695 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00003696 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00003697 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00003698 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00003699 int usableSpace; /* Bytes in pPage beyond the header */
3700 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00003701 int subtotal; /* Subtotal of bytes in cells on one page */
drhb6f41482004-05-14 01:58:11 +00003702 int iSpace = 0; /* First unused byte of aSpace[] */
drh2e38c322004-09-03 18:38:44 +00003703 int mxCellPerPage; /* Maximum number of cells in one page */
drhc3b70572003-01-04 19:44:07 +00003704 MemPage *apOld[NB]; /* pPage and up to two siblings */
3705 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00003706 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00003707 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
3708 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drhc3b70572003-01-04 19:44:07 +00003709 int idxDiv[NB]; /* Indices of divider cells in pParent */
drh4b70f112004-05-02 21:12:19 +00003710 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00003711 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
3712 int szNew[NB+2]; /* Combined size of cells place on i-th page */
drh2e38c322004-09-03 18:38:44 +00003713 u8 **apCell; /* All cells begin balanced */
3714 int *szCell; /* Local size of all cells in apCell[] */
3715 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
3716 u8 *aSpace; /* Space to hold copies of dividers cells */
danielk1977ac11ee62005-01-15 12:45:51 +00003717#ifndef SQLITE_OMIT_VACUUM
3718 u8 *aFrom = 0;
3719#endif
drh8b2f49b2001-06-08 00:21:52 +00003720
drh14acc042001-06-10 19:56:58 +00003721 /*
drh43605152004-05-29 21:46:49 +00003722 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00003723 */
drh3a4c1412004-05-09 20:40:11 +00003724 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00003725 assert( sqlite3pager_iswriteable(pPage->aData) );
drh4b70f112004-05-02 21:12:19 +00003726 pBt = pPage->pBt;
drh14acc042001-06-10 19:56:58 +00003727 pParent = pPage->pParent;
drh43605152004-05-29 21:46:49 +00003728 sqlite3pager_write(pParent->aData);
3729 assert( pParent );
3730 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00003731
danielk1977ac245ec2005-01-14 13:50:11 +00003732#ifdef SQLITE_BALANCE_QUICK
drhf222e712005-01-14 22:55:49 +00003733 /*
3734 ** A special case: If a new entry has just been inserted into a
3735 ** table (that is, a btree with integer keys and all data at the leaves)
3736 ** an the new entry is the right-most entry in the tree (it has the
3737 ** largest key) then use the special balance_quick() routine for
3738 ** balancing. balance_quick() is much faster and results in a tighter
3739 ** packing of data in the common case.
3740 */
danielk1977ac245ec2005-01-14 13:50:11 +00003741 if( pPage->leaf &&
3742 pPage->intKey &&
3743 pPage->leafData &&
3744 pPage->nOverflow==1 &&
3745 pPage->aOvfl[0].idx==pPage->nCell &&
danielk1977ac11ee62005-01-15 12:45:51 +00003746 pPage->pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00003747 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
3748 ){
danielk1977ac11ee62005-01-15 12:45:51 +00003749 /*
3750 ** TODO: Check the siblings to the left of pPage. It may be that
3751 ** they are not full and no new page is required.
3752 */
danielk1977ac245ec2005-01-14 13:50:11 +00003753 return balance_quick(pPage, pParent);
3754 }
3755#endif
3756
drh2e38c322004-09-03 18:38:44 +00003757 /*
3758 ** Allocate space for memory structures
3759 */
3760 mxCellPerPage = MX_CELL(pBt);
3761 apCell = sqliteMallocRaw(
3762 (mxCellPerPage+2)*NB*(sizeof(u8*)+sizeof(int))
3763 + sizeof(MemPage)*NB
drh887dc4c2004-10-22 16:22:57 +00003764 + pBt->psAligned*(5+NB)
danielk1977ac11ee62005-01-15 12:45:51 +00003765 + (ISAUTOVACUUM ? (mxCellPerPage+2)*NN*2 : 0)
drh2e38c322004-09-03 18:38:44 +00003766 );
3767 if( apCell==0 ){
3768 return SQLITE_NOMEM;
3769 }
3770 szCell = (int*)&apCell[(mxCellPerPage+2)*NB];
3771 aCopy[0] = (u8*)&szCell[(mxCellPerPage+2)*NB];
3772 for(i=1; i<NB; i++){
drh887dc4c2004-10-22 16:22:57 +00003773 aCopy[i] = &aCopy[i-1][pBt->psAligned+sizeof(MemPage)];
drh2e38c322004-09-03 18:38:44 +00003774 }
drh887dc4c2004-10-22 16:22:57 +00003775 aSpace = &aCopy[NB-1][pBt->psAligned+sizeof(MemPage)];
danielk1977ac11ee62005-01-15 12:45:51 +00003776#ifndef SQLITE_OMIT_AUTOVACUUM
3777 if( pBt->autoVacuum ){
3778 aFrom = &aSpace[5*pBt->psAligned];
3779 }
3780#endif
drh14acc042001-06-10 19:56:58 +00003781
drh8b2f49b2001-06-08 00:21:52 +00003782 /*
drh4b70f112004-05-02 21:12:19 +00003783 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00003784 ** to pPage. The "idx" variable is the index of that cell. If pPage
3785 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00003786 */
drhbb49aba2003-01-04 18:53:27 +00003787 if( pParent->idxShift ){
drha34b6762004-05-07 13:30:42 +00003788 Pgno pgno;
drh4b70f112004-05-02 21:12:19 +00003789 pgno = pPage->pgno;
drha34b6762004-05-07 13:30:42 +00003790 assert( pgno==sqlite3pager_pagenumber(pPage->aData) );
drhbb49aba2003-01-04 18:53:27 +00003791 for(idx=0; idx<pParent->nCell; idx++){
drh43605152004-05-29 21:46:49 +00003792 if( get4byte(findCell(pParent, idx))==pgno ){
drhbb49aba2003-01-04 18:53:27 +00003793 break;
3794 }
drh8b2f49b2001-06-08 00:21:52 +00003795 }
drh4b70f112004-05-02 21:12:19 +00003796 assert( idx<pParent->nCell
drh43605152004-05-29 21:46:49 +00003797 || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
drhbb49aba2003-01-04 18:53:27 +00003798 }else{
3799 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00003800 }
drh8b2f49b2001-06-08 00:21:52 +00003801
3802 /*
drh14acc042001-06-10 19:56:58 +00003803 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00003804 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00003805 */
drh14acc042001-06-10 19:56:58 +00003806 nOld = nNew = 0;
drha34b6762004-05-07 13:30:42 +00003807 sqlite3pager_ref(pParent->aData);
drh14acc042001-06-10 19:56:58 +00003808
3809 /*
drh4b70f112004-05-02 21:12:19 +00003810 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00003811 ** the siblings. An attempt is made to find NN siblings on either
3812 ** side of pPage. More siblings are taken from one side, however, if
3813 ** pPage there are fewer than NN siblings on the other side. If pParent
3814 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00003815 */
drhc3b70572003-01-04 19:44:07 +00003816 nxDiv = idx - NN;
3817 if( nxDiv + NB > pParent->nCell ){
3818 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00003819 }
drhc3b70572003-01-04 19:44:07 +00003820 if( nxDiv<0 ){
3821 nxDiv = 0;
3822 }
drh8b2f49b2001-06-08 00:21:52 +00003823 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00003824 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00003825 if( k<pParent->nCell ){
3826 idxDiv[i] = k;
drh43605152004-05-29 21:46:49 +00003827 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00003828 nDiv++;
drha34b6762004-05-07 13:30:42 +00003829 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00003830 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00003831 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00003832 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00003833 }else{
3834 break;
drh8b2f49b2001-06-08 00:21:52 +00003835 }
drhde647132004-05-07 17:57:49 +00003836 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00003837 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00003838 apOld[i]->idxParent = k;
drh91025292004-05-03 19:49:32 +00003839 apCopy[i] = 0;
3840 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00003841 nOld++;
drh8b2f49b2001-06-08 00:21:52 +00003842 }
3843
3844 /*
drh14acc042001-06-10 19:56:58 +00003845 ** Make copies of the content of pPage and its siblings into aOld[].
3846 ** The rest of this function will use data from the copies rather
3847 ** that the original pages since the original pages will be in the
3848 ** process of being overwritten.
3849 */
3850 for(i=0; i<nOld; i++){
drh887dc4c2004-10-22 16:22:57 +00003851 MemPage *p = apCopy[i] = (MemPage*)&aCopy[i][pBt->psAligned];
3852 p->aData = &((u8*)p)[-pBt->psAligned];
3853 memcpy(p->aData, apOld[i]->aData, pBt->psAligned + sizeof(MemPage));
3854 p->aData = &((u8*)p)[-pBt->psAligned];
drh14acc042001-06-10 19:56:58 +00003855 }
3856
3857 /*
3858 ** Load pointers to all cells on sibling pages and the divider cells
3859 ** into the local apCell[] array. Make copies of the divider cells
drhb6f41482004-05-14 01:58:11 +00003860 ** into space obtained form aSpace[] and remove the the divider Cells
3861 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00003862 **
3863 ** If the siblings are on leaf pages, then the child pointers of the
3864 ** divider cells are stripped from the cells before they are copied
drh96f5b762004-05-16 16:24:36 +00003865 ** into aSpace[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00003866 ** child pointers. If siblings are not leaves, then all cell in
3867 ** apCell[] include child pointers. Either way, all cells in apCell[]
3868 ** are alike.
drh96f5b762004-05-16 16:24:36 +00003869 **
3870 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
3871 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00003872 */
3873 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00003874 leafCorrection = pPage->leaf*4;
drh8b18dd42004-05-12 19:18:15 +00003875 leafData = pPage->leafData && pPage->leaf;
drh8b2f49b2001-06-08 00:21:52 +00003876 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00003877 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00003878 int limit = pOld->nCell+pOld->nOverflow;
3879 for(j=0; j<limit; j++){
3880 apCell[nCell] = findOverflowCell(pOld, j);
3881 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk1977ac11ee62005-01-15 12:45:51 +00003882#ifndef SQLITE_OMIT_AUTOVACUUM
3883 if( pBt->autoVacuum ){
3884 int a;
3885 aFrom[nCell] = i;
3886 for(a=0; a<pOld->nOverflow; a++){
3887 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
3888 aFrom[nCell] = 0xFF;
3889 break;
3890 }
3891 }
3892 }
3893#endif
drh14acc042001-06-10 19:56:58 +00003894 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00003895 }
3896 if( i<nOld-1 ){
drh43605152004-05-29 21:46:49 +00003897 int sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00003898 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00003899 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
3900 ** are duplicates of keys on the child pages. We need to remove
3901 ** the divider cells from pParent, but the dividers cells are not
3902 ** added to apCell[] because they are duplicates of child cells.
3903 */
drh8b18dd42004-05-12 19:18:15 +00003904 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00003905 }else{
drhb6f41482004-05-14 01:58:11 +00003906 u8 *pTemp;
3907 szCell[nCell] = sz;
3908 pTemp = &aSpace[iSpace];
3909 iSpace += sz;
drh887dc4c2004-10-22 16:22:57 +00003910 assert( iSpace<=pBt->psAligned*5 );
drhb6f41482004-05-14 01:58:11 +00003911 memcpy(pTemp, apDiv[i], sz);
3912 apCell[nCell] = pTemp+leafCorrection;
danielk1977ac11ee62005-01-15 12:45:51 +00003913#ifndef SQLITE_OMIT_AUTOVACUUM
3914 if( pBt->autoVacuum ){
3915 aFrom[nCell] = 0xFF;
3916 }
3917#endif
drhb6f41482004-05-14 01:58:11 +00003918 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00003919 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00003920 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00003921 if( !pOld->leaf ){
3922 assert( leafCorrection==0 );
3923 /* The right pointer of the child page pOld becomes the left
3924 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00003925 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00003926 }else{
3927 assert( leafCorrection==4 );
3928 }
3929 nCell++;
drh4b70f112004-05-02 21:12:19 +00003930 }
drh8b2f49b2001-06-08 00:21:52 +00003931 }
3932 }
3933
3934 /*
drh6019e162001-07-02 17:51:45 +00003935 ** Figure out the number of pages needed to hold all nCell cells.
3936 ** Store this number in "k". Also compute szNew[] which is the total
3937 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00003938 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00003939 ** cntNew[k] should equal nCell.
3940 **
drh96f5b762004-05-16 16:24:36 +00003941 ** Values computed by this block:
3942 **
3943 ** k: The total number of sibling pages
3944 ** szNew[i]: Spaced used on the i-th sibling page.
3945 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
3946 ** the right of the i-th sibling page.
3947 ** usableSpace: Number of bytes of space available on each sibling.
3948 **
drh8b2f49b2001-06-08 00:21:52 +00003949 */
drh43605152004-05-29 21:46:49 +00003950 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00003951 for(subtotal=k=i=0; i<nCell; i++){
drh43605152004-05-29 21:46:49 +00003952 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00003953 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00003954 szNew[k] = subtotal - szCell[i];
3955 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00003956 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00003957 subtotal = 0;
3958 k++;
3959 }
3960 }
3961 szNew[k] = subtotal;
3962 cntNew[k] = nCell;
3963 k++;
drh96f5b762004-05-16 16:24:36 +00003964
3965 /*
3966 ** The packing computed by the previous block is biased toward the siblings
3967 ** on the left side. The left siblings are always nearly full, while the
3968 ** right-most sibling might be nearly empty. This block of code attempts
3969 ** to adjust the packing of siblings to get a better balance.
3970 **
3971 ** This adjustment is more than an optimization. The packing above might
3972 ** be so out of balance as to be illegal. For example, the right-most
3973 ** sibling might be completely empty. This adjustment is not optional.
3974 */
drh6019e162001-07-02 17:51:45 +00003975 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00003976 int szRight = szNew[i]; /* Size of sibling on the right */
3977 int szLeft = szNew[i-1]; /* Size of sibling on the left */
3978 int r; /* Index of right-most cell in left sibling */
3979 int d; /* Index of first cell to the left of right sibling */
3980
3981 r = cntNew[i-1] - 1;
3982 d = r + 1 - leafData;
drh43605152004-05-29 21:46:49 +00003983 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
3984 szRight += szCell[d] + 2;
3985 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00003986 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00003987 r = cntNew[i-1] - 1;
3988 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00003989 }
drh96f5b762004-05-16 16:24:36 +00003990 szNew[i] = szRight;
3991 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00003992 }
3993 assert( cntNew[0]>0 );
drh8b2f49b2001-06-08 00:21:52 +00003994
3995 /*
drh6b308672002-07-08 02:16:37 +00003996 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00003997 */
drh4b70f112004-05-02 21:12:19 +00003998 assert( pPage->pgno>1 );
3999 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00004000 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00004001 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00004002 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00004003 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00004004 pgnoNew[i] = pgnoOld[i];
4005 apOld[i] = 0;
danielk197728129562005-01-11 10:25:06 +00004006 rc = sqlite3pager_write(pNew->aData);
4007 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00004008 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004009 rc = allocatePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00004010 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00004011 apNew[i] = pNew;
drh6b308672002-07-08 02:16:37 +00004012 }
drh14acc042001-06-10 19:56:58 +00004013 nNew++;
drhda200cc2004-05-09 11:51:38 +00004014 zeroPage(pNew, pageFlags);
drh8b2f49b2001-06-08 00:21:52 +00004015 }
4016
danielk1977299b1872004-11-22 10:02:10 +00004017 /* Free any old pages that were not reused as new pages.
4018 */
4019 while( i<nOld ){
4020 rc = freePage(apOld[i]);
4021 if( rc ) goto balance_cleanup;
4022 releasePage(apOld[i]);
4023 apOld[i] = 0;
4024 i++;
4025 }
4026
drh8b2f49b2001-06-08 00:21:52 +00004027 /*
drhf9ffac92002-03-02 19:00:31 +00004028 ** Put the new pages in accending order. This helps to
4029 ** keep entries in the disk file in order so that a scan
4030 ** of the table is a linear scan through the file. That
4031 ** in turn helps the operating system to deliver pages
4032 ** from the disk more rapidly.
4033 **
4034 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00004035 ** n is never more than NB (a small constant), that should
4036 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00004037 **
drhc3b70572003-01-04 19:44:07 +00004038 ** When NB==3, this one optimization makes the database
4039 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00004040 */
4041 for(i=0; i<k-1; i++){
4042 int minV = pgnoNew[i];
4043 int minI = i;
4044 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00004045 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00004046 minI = j;
4047 minV = pgnoNew[j];
4048 }
4049 }
4050 if( minI>i ){
4051 int t;
4052 MemPage *pT;
4053 t = pgnoNew[i];
4054 pT = apNew[i];
4055 pgnoNew[i] = pgnoNew[minI];
4056 apNew[i] = apNew[minI];
4057 pgnoNew[minI] = t;
4058 apNew[minI] = pT;
4059 }
4060 }
drha2fce642004-06-05 00:01:44 +00004061 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00004062 pgnoOld[0],
4063 nOld>=2 ? pgnoOld[1] : 0,
4064 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00004065 pgnoNew[0], szNew[0],
4066 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
4067 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00004068 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
4069 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00004070
drhf9ffac92002-03-02 19:00:31 +00004071 /*
drh14acc042001-06-10 19:56:58 +00004072 ** Evenly distribute the data in apCell[] across the new pages.
4073 ** Insert divider cells into pParent as necessary.
4074 */
4075 j = 0;
4076 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00004077 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00004078 MemPage *pNew = apNew[i];
drh4b70f112004-05-02 21:12:19 +00004079 assert( pNew->pgno==pgnoNew[i] );
drhfa1a98a2004-05-14 19:08:17 +00004080 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh6019e162001-07-02 17:51:45 +00004081 assert( pNew->nCell>0 );
drh43605152004-05-29 21:46:49 +00004082 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00004083
4084#ifndef SQLITE_OMIT_AUTOVACUUM
4085 /* If this is an auto-vacuum database, update the pointer map entries
4086 ** that point to the siblings that were rearranged. These can be: left
4087 ** children of cells, the right-child of the page, or overflow pages
4088 ** pointed to by cells.
4089 */
4090 if( pBt->autoVacuum ){
4091 for(k=j; k<cntNew[i]; k++){
4092 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
4093 Pgno ovfl = ovflPagePtr(pNew, findCell(pNew, k-j));
4094 if( ovfl ){
4095 rc = ptrmapPut(pBt, ovfl, PTRMAP_OVERFLOW1, pNew->pgno);
4096 if( rc!=SQLITE_OK ){
4097 goto balance_cleanup;
4098 }
4099 }
4100 }
4101 }
4102 }
4103#endif
4104
4105 j = cntNew[i];
4106
4107 /* If the sibling page assembled above was not the right-most sibling,
4108 ** insert a divider cell into the parent page.
4109 */
drh14acc042001-06-10 19:56:58 +00004110 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00004111 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00004112 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00004113 int sz;
4114 pCell = apCell[j];
4115 sz = szCell[j] + leafCorrection;
drh4b70f112004-05-02 21:12:19 +00004116 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00004117 memcpy(&pNew->aData[8], pCell, 4);
drh24cd67e2004-05-10 16:18:47 +00004118 pTemp = 0;
drh8b18dd42004-05-12 19:18:15 +00004119 }else if( leafData ){
danielk1977ac11ee62005-01-15 12:45:51 +00004120 /* If the tree is a leaf-data tree, and the siblings are leaves,
4121 ** then there is no divider cell in apCell[]. Instead, the divider
4122 ** cell consists of the integer key for the right-most cell of
4123 ** the sibling-page assembled above only.
4124 */
drh6f11bef2004-05-13 01:12:56 +00004125 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00004126 j--;
drh43605152004-05-29 21:46:49 +00004127 parseCellPtr(pNew, apCell[j], &info);
drhb6f41482004-05-14 01:58:11 +00004128 pCell = &aSpace[iSpace];
drh6f11bef2004-05-13 01:12:56 +00004129 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, &sz);
drhb6f41482004-05-14 01:58:11 +00004130 iSpace += sz;
drh887dc4c2004-10-22 16:22:57 +00004131 assert( iSpace<=pBt->psAligned*5 );
drh8b18dd42004-05-12 19:18:15 +00004132 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00004133 }else{
4134 pCell -= 4;
drhb6f41482004-05-14 01:58:11 +00004135 pTemp = &aSpace[iSpace];
4136 iSpace += sz;
drh887dc4c2004-10-22 16:22:57 +00004137 assert( iSpace<=pBt->psAligned*5 );
drh4b70f112004-05-02 21:12:19 +00004138 }
danielk1977a3ad5e72005-01-07 08:56:44 +00004139 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00004140 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh43605152004-05-29 21:46:49 +00004141 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +00004142#ifndef SQLITE_OMIT_AUTOVACUUM
4143 /* If this is an auto-vacuum database, and not a leaf-data tree,
4144 ** then update the pointer map with an entry for the overflow page
4145 ** that the cell just inserted points to (if any).
4146 */
4147 if( pBt->autoVacuum && !leafData ){
4148 Pgno ovfl = ovflPagePtr(pParent, findOverflowCell(pParent, nxDiv));
4149 if( ovfl ){
4150 rc = ptrmapPut(pBt, ovfl, PTRMAP_OVERFLOW1, pParent->pgno);
4151 if( rc!=SQLITE_OK ){
4152 goto balance_cleanup;
4153 }
4154 }
4155 }
4156#endif
drh14acc042001-06-10 19:56:58 +00004157 j++;
4158 nxDiv++;
4159 }
4160 }
drh6019e162001-07-02 17:51:45 +00004161 assert( j==nCell );
drh4b70f112004-05-02 21:12:19 +00004162 if( (pageFlags & PTF_LEAF)==0 ){
drh43605152004-05-29 21:46:49 +00004163 memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
drh14acc042001-06-10 19:56:58 +00004164 }
drh43605152004-05-29 21:46:49 +00004165 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00004166 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00004167 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00004168 }else{
4169 /* Right-most sibling is the left child of the first entry in pParent
4170 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00004171 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00004172 }
4173
4174 /*
4175 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00004176 */
4177 for(i=0; i<nNew; i++){
danielk1977afcdd022004-10-31 16:25:42 +00004178 rc = reparentChildPages(apNew[i]);
4179 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004180 }
danielk1977afcdd022004-10-31 16:25:42 +00004181 rc = reparentChildPages(pParent);
4182 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004183
4184 /*
drh3a4c1412004-05-09 20:40:11 +00004185 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00004186 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00004187 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00004188 */
drhda200cc2004-05-09 11:51:38 +00004189 assert( pParent->isInit );
drh3a4c1412004-05-09 20:40:11 +00004190 /* assert( pPage->isInit ); // No! pPage might have been added to freelist */
4191 /* pageIntegrity(pPage); // No! pPage might have been added to freelist */
danielk1977ac245ec2005-01-14 13:50:11 +00004192 rc = balance(pParent, 0);
drhda200cc2004-05-09 11:51:38 +00004193
drh8b2f49b2001-06-08 00:21:52 +00004194 /*
drh14acc042001-06-10 19:56:58 +00004195 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00004196 */
drh14acc042001-06-10 19:56:58 +00004197balance_cleanup:
drh2e38c322004-09-03 18:38:44 +00004198 sqliteFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00004199 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00004200 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00004201 }
drh14acc042001-06-10 19:56:58 +00004202 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00004203 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00004204 }
drh91025292004-05-03 19:49:32 +00004205 releasePage(pParent);
drh3a4c1412004-05-09 20:40:11 +00004206 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
4207 pPage->pgno, nOld, nNew, nCell));
drh8b2f49b2001-06-08 00:21:52 +00004208 return rc;
4209}
4210
4211/*
drh43605152004-05-29 21:46:49 +00004212** This routine is called for the root page of a btree when the root
4213** page contains no cells. This is an opportunity to make the tree
4214** shallower by one level.
4215*/
4216static int balance_shallower(MemPage *pPage){
4217 MemPage *pChild; /* The only child page of pPage */
4218 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00004219 int rc = SQLITE_OK; /* Return code from subprocedures */
4220 Btree *pBt; /* The main BTree structure */
4221 int mxCellPerPage; /* Maximum number of cells per page */
4222 u8 **apCell; /* All cells from pages being balanced */
4223 int *szCell; /* Local size of all cells */
danielk1977ac11ee62005-01-15 12:45:51 +00004224 int i;
drh43605152004-05-29 21:46:49 +00004225
4226 assert( pPage->pParent==0 );
4227 assert( pPage->nCell==0 );
drh2e38c322004-09-03 18:38:44 +00004228 pBt = pPage->pBt;
4229 mxCellPerPage = MX_CELL(pBt);
4230 apCell = sqliteMallocRaw( mxCellPerPage*(sizeof(u8*)+sizeof(int)) );
4231 if( apCell==0 ) return SQLITE_NOMEM;
4232 szCell = (int*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00004233 if( pPage->leaf ){
4234 /* The table is completely empty */
4235 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
4236 }else{
4237 /* The root page is empty but has one child. Transfer the
4238 ** information from that one child into the root page if it
4239 ** will fit. This reduces the depth of the tree by one.
4240 **
4241 ** If the root page is page 1, it has less space available than
4242 ** its child (due to the 100 byte header that occurs at the beginning
4243 ** of the database fle), so it might not be able to hold all of the
4244 ** information currently contained in the child. If this is the
4245 ** case, then do not do the transfer. Leave page 1 empty except
4246 ** for the right-pointer to the child page. The child page becomes
4247 ** the virtual root of the tree.
4248 */
4249 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
4250 assert( pgnoChild>0 );
4251 assert( pgnoChild<=sqlite3pager_pagecount(pPage->pBt->pPager) );
4252 rc = getPage(pPage->pBt, pgnoChild, &pChild);
drh2e38c322004-09-03 18:38:44 +00004253 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004254 if( pPage->pgno==1 ){
4255 rc = initPage(pChild, pPage);
drh2e38c322004-09-03 18:38:44 +00004256 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004257 assert( pChild->nOverflow==0 );
4258 if( pChild->nFree>=100 ){
4259 /* The child information will fit on the root page, so do the
4260 ** copy */
4261 int i;
4262 zeroPage(pPage, pChild->aData[0]);
4263 for(i=0; i<pChild->nCell; i++){
4264 apCell[i] = findCell(pChild,i);
4265 szCell[i] = cellSizePtr(pChild, apCell[i]);
4266 }
4267 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00004268 /* Copy the right-pointer of the child to the parent. */
4269 put4byte(&pPage->aData[pPage->hdrOffset+8],
4270 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh43605152004-05-29 21:46:49 +00004271 freePage(pChild);
4272 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
4273 }else{
4274 /* The child has more information that will fit on the root.
4275 ** The tree is already balanced. Do nothing. */
4276 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
4277 }
4278 }else{
4279 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
4280 pPage->isInit = 0;
4281 pPage->pParent = 0;
4282 rc = initPage(pPage, 0);
4283 assert( rc==SQLITE_OK );
4284 freePage(pChild);
4285 TRACE(("BALANCE: transfer child %d into root %d\n",
4286 pChild->pgno, pPage->pgno));
4287 }
danielk1977afcdd022004-10-31 16:25:42 +00004288 rc = reparentChildPages(pPage);
danielk1977ac11ee62005-01-15 12:45:51 +00004289 assert( pPage->nOverflow==0 );
4290#ifndef SQLITE_OMIT_AUTOVACUUM
4291 if( pBt->autoVacuum ){
4292 for(i=0; i<pPage->nCell; i++){
4293 Pgno ovfl = ovflPagePtr(pPage, findCell(pPage, i));
4294 if( ovfl ){
4295 rc = ptrmapPut(pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
4296 if( rc!=SQLITE_OK ){
4297 goto end_shallow_balance;
4298 }
4299 }
4300 }
4301 }
4302#endif
danielk1977afcdd022004-10-31 16:25:42 +00004303 if( rc!=SQLITE_OK ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004304 releasePage(pChild);
4305 }
drh2e38c322004-09-03 18:38:44 +00004306end_shallow_balance:
4307 sqliteFree(apCell);
4308 return rc;
drh43605152004-05-29 21:46:49 +00004309}
4310
4311
4312/*
4313** The root page is overfull
4314**
4315** When this happens, Create a new child page and copy the
4316** contents of the root into the child. Then make the root
4317** page an empty page with rightChild pointing to the new
4318** child. Finally, call balance_internal() on the new child
4319** to cause it to split.
4320*/
4321static int balance_deeper(MemPage *pPage){
4322 int rc; /* Return value from subprocedures */
4323 MemPage *pChild; /* Pointer to a new child page */
4324 Pgno pgnoChild; /* Page number of the new child page */
4325 Btree *pBt; /* The BTree */
4326 int usableSize; /* Total usable size of a page */
4327 u8 *data; /* Content of the parent page */
4328 u8 *cdata; /* Content of the child page */
4329 int hdr; /* Offset to page header in parent */
4330 int brk; /* Offset to content of first cell in parent */
4331
4332 assert( pPage->pParent==0 );
4333 assert( pPage->nOverflow>0 );
4334 pBt = pPage->pBt;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004335 rc = allocatePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00004336 if( rc ) return rc;
4337 assert( sqlite3pager_iswriteable(pChild->aData) );
4338 usableSize = pBt->usableSize;
4339 data = pPage->aData;
4340 hdr = pPage->hdrOffset;
4341 brk = get2byte(&data[hdr+5]);
4342 cdata = pChild->aData;
4343 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
4344 memcpy(&cdata[brk], &data[brk], usableSize-brk);
danielk1977c7dc7532004-11-17 10:22:03 +00004345 assert( pChild->isInit==0 );
drh43605152004-05-29 21:46:49 +00004346 rc = initPage(pChild, pPage);
4347 if( rc ) return rc;
4348 memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
4349 pChild->nOverflow = pPage->nOverflow;
4350 if( pChild->nOverflow ){
4351 pChild->nFree = 0;
4352 }
4353 assert( pChild->nCell==pPage->nCell );
4354 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
4355 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
4356 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
danielk1977ac11ee62005-01-15 12:45:51 +00004357 if( pBt->autoVacuum ){
4358 int i;
4359 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
4360 if( rc ) return rc;
4361 for(i=0; i<pChild->nCell; i++){
4362 Pgno pgno = ovflPagePtr(pChild, findOverflowCell(pChild, i));
4363 if( pgno ){
4364 rc = ptrmapPut(pBt, pgno, PTRMAP_OVERFLOW1, pChild->pgno);
4365 if( rc ) return rc;
4366 }
4367 }
4368 }
drh43605152004-05-29 21:46:49 +00004369 rc = balance_nonroot(pChild);
4370 releasePage(pChild);
4371 return rc;
4372}
4373
4374/*
4375** Decide if the page pPage needs to be balanced. If balancing is
4376** required, call the appropriate balancing routine.
4377*/
danielk1977ac245ec2005-01-14 13:50:11 +00004378static int balance(MemPage *pPage, int insert){
drh43605152004-05-29 21:46:49 +00004379 int rc = SQLITE_OK;
4380 if( pPage->pParent==0 ){
4381 if( pPage->nOverflow>0 ){
4382 rc = balance_deeper(pPage);
4383 }
danielk1977687566d2004-11-02 12:56:41 +00004384 if( rc==SQLITE_OK && pPage->nCell==0 ){
drh43605152004-05-29 21:46:49 +00004385 rc = balance_shallower(pPage);
4386 }
4387 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00004388 if( pPage->nOverflow>0 ||
4389 (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
drh43605152004-05-29 21:46:49 +00004390 rc = balance_nonroot(pPage);
4391 }
4392 }
4393 return rc;
4394}
4395
4396/*
drh8dcd7ca2004-08-08 19:43:29 +00004397** This routine checks all cursors that point to table pgnoRoot.
4398** If any of those cursors other than pExclude were opened with
drhf74b8d92002-09-01 23:20:45 +00004399** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
drh8dcd7ca2004-08-08 19:43:29 +00004400** cursors that point to pgnoRoot were opened with wrFlag==1
drhf74b8d92002-09-01 23:20:45 +00004401** then this routine returns SQLITE_OK.
danielk1977299b1872004-11-22 10:02:10 +00004402**
4403** In addition to checking for read-locks (where a read-lock
4404** means a cursor opened with wrFlag==0) this routine also moves
4405** all cursors other than pExclude so that they are pointing to the
4406** first Cell on root page. This is necessary because an insert
4407** or delete might change the number of cells on a page or delete
4408** a page entirely and we do not want to leave any cursors
4409** pointing to non-existant pages or cells.
drhf74b8d92002-09-01 23:20:45 +00004410*/
drh8dcd7ca2004-08-08 19:43:29 +00004411static int checkReadLocks(Btree *pBt, Pgno pgnoRoot, BtCursor *pExclude){
danielk1977299b1872004-11-22 10:02:10 +00004412 BtCursor *p;
4413 for(p=pBt->pCursor; p; p=p->pNext){
4414 if( p->pgnoRoot!=pgnoRoot || p==pExclude ) continue;
4415 if( p->wrFlag==0 ) return SQLITE_LOCKED;
4416 if( p->pPage->pgno!=p->pgnoRoot ){
4417 moveToRoot(p);
4418 }
4419 }
drhf74b8d92002-09-01 23:20:45 +00004420 return SQLITE_OK;
4421}
4422
4423/*
drh3b7511c2001-05-26 13:15:44 +00004424** Insert a new record into the BTree. The key is given by (pKey,nKey)
4425** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00004426** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00004427** is left pointing at a random location.
4428**
4429** For an INTKEY table, only the nKey value of the key is used. pKey is
4430** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00004431*/
drh3aac2dd2004-04-26 14:10:20 +00004432int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00004433 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00004434 const void *pKey, i64 nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00004435 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00004436){
drh3b7511c2001-05-26 13:15:44 +00004437 int rc;
4438 int loc;
drh14acc042001-06-10 19:56:58 +00004439 int szNew;
drh3b7511c2001-05-26 13:15:44 +00004440 MemPage *pPage;
4441 Btree *pBt = pCur->pBt;
drha34b6762004-05-07 13:30:42 +00004442 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00004443 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00004444
danielk1977ee5741e2004-05-31 10:01:34 +00004445 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00004446 /* Must start a transaction before doing an insert */
4447 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00004448 }
drhf74b8d92002-09-01 23:20:45 +00004449 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00004450 if( !pCur->wrFlag ){
4451 return SQLITE_PERM; /* Cursor not open for writing */
4452 }
drh8dcd7ca2004-08-08 19:43:29 +00004453 if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00004454 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
4455 }
drh3aac2dd2004-04-26 14:10:20 +00004456 rc = sqlite3BtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00004457 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00004458 pPage = pCur->pPage;
drh4a1c3802004-05-12 15:15:47 +00004459 assert( pPage->intKey || nKey>=0 );
drh8b18dd42004-05-12 19:18:15 +00004460 assert( pPage->leaf || !pPage->leafData );
drh3a4c1412004-05-09 20:40:11 +00004461 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
4462 pCur->pgnoRoot, nKey, nData, pPage->pgno,
4463 loc==0 ? "overwrite" : "new entry"));
drh7aa128d2002-06-21 13:09:16 +00004464 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004465 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00004466 if( rc ) return rc;
drh2e38c322004-09-03 18:38:44 +00004467 newCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
4468 if( newCell==0 ) return SQLITE_NOMEM;
drha34b6762004-05-07 13:30:42 +00004469 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, &szNew);
drh2e38c322004-09-03 18:38:44 +00004470 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00004471 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00004472 assert( szNew<=MX_CELL_SIZE(pBt) );
drhf328bc82004-05-10 23:29:49 +00004473 if( loc==0 && pCur->isValid ){
drha34b6762004-05-07 13:30:42 +00004474 int szOld;
4475 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00004476 oldCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00004477 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004478 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00004479 }
drh43605152004-05-29 21:46:49 +00004480 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00004481 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00004482 if( rc ) goto end_insert;
drh4b70f112004-05-02 21:12:19 +00004483 dropCell(pPage, pCur->idx, szOld);
drh7c717f72001-06-24 20:39:41 +00004484 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00004485 assert( pPage->leaf );
drh14acc042001-06-10 19:56:58 +00004486 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00004487 pCur->info.nSize = 0;
drh14acc042001-06-10 19:56:58 +00004488 }else{
drh4b70f112004-05-02 21:12:19 +00004489 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00004490 }
danielk1977a3ad5e72005-01-07 08:56:44 +00004491 rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
danielk1977e80463b2004-11-03 03:01:16 +00004492 if( rc!=SQLITE_OK ) goto end_insert;
danielk1977ac245ec2005-01-14 13:50:11 +00004493 rc = balance(pPage, 1);
drh23e11ca2004-05-04 17:27:28 +00004494 /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
drh3fc190c2001-09-14 03:24:23 +00004495 /* fflush(stdout); */
danielk1977299b1872004-11-22 10:02:10 +00004496 if( rc==SQLITE_OK ){
4497 moveToRoot(pCur);
4498 }
drh2e38c322004-09-03 18:38:44 +00004499end_insert:
4500 sqliteFree(newCell);
drh5e2f8b92001-05-28 00:41:15 +00004501 return rc;
4502}
4503
4504/*
drh4b70f112004-05-02 21:12:19 +00004505** Delete the entry that the cursor is pointing to. The cursor
4506** is left pointing at a random location.
drh3b7511c2001-05-26 13:15:44 +00004507*/
drh3aac2dd2004-04-26 14:10:20 +00004508int sqlite3BtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00004509 MemPage *pPage = pCur->pPage;
drh4b70f112004-05-02 21:12:19 +00004510 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00004511 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00004512 Pgno pgnoChild = 0;
drh0d316a42002-08-11 20:10:47 +00004513 Btree *pBt = pCur->pBt;
drh8b2f49b2001-06-08 00:21:52 +00004514
drh7aa128d2002-06-21 13:09:16 +00004515 assert( pPage->isInit );
danielk1977ee5741e2004-05-31 10:01:34 +00004516 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00004517 /* Must start a transaction before doing a delete */
4518 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00004519 }
drhf74b8d92002-09-01 23:20:45 +00004520 assert( !pBt->readOnly );
drhbd03cae2001-06-02 02:40:57 +00004521 if( pCur->idx >= pPage->nCell ){
4522 return SQLITE_ERROR; /* The cursor is not pointing to anything */
4523 }
drhecdc7532001-09-23 02:35:53 +00004524 if( !pCur->wrFlag ){
4525 return SQLITE_PERM; /* Did not open this cursor for writing */
4526 }
drh8dcd7ca2004-08-08 19:43:29 +00004527 if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00004528 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
4529 }
drha34b6762004-05-07 13:30:42 +00004530 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00004531 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00004532
4533 /* Locate the cell within it's page and leave pCell pointing to the
4534 ** data. The clearCell() call frees any overflow pages associated with the
4535 ** cell. The cell itself is still intact.
4536 */
danielk1977299b1872004-11-22 10:02:10 +00004537 pCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00004538 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004539 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00004540 }
danielk197728129562005-01-11 10:25:06 +00004541 rc = clearCell(pPage, pCell);
4542 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00004543
drh4b70f112004-05-02 21:12:19 +00004544 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00004545 /*
drh5e00f6c2001-09-13 13:46:56 +00004546 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00004547 ** do something we will leave a hole on an internal page.
4548 ** We have to fill the hole by moving in a cell from a leaf. The
4549 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00004550 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00004551 */
drh14acc042001-06-10 19:56:58 +00004552 BtCursor leafCur;
drh4b70f112004-05-02 21:12:19 +00004553 unsigned char *pNext;
drh14acc042001-06-10 19:56:58 +00004554 int szNext;
danielk1977299b1872004-11-22 10:02:10 +00004555 int notUsed;
drh2e38c322004-09-03 18:38:44 +00004556 unsigned char *tempCell;
drh8b18dd42004-05-12 19:18:15 +00004557 assert( !pPage->leafData );
drh14acc042001-06-10 19:56:58 +00004558 getTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00004559 rc = sqlite3BtreeNext(&leafCur, &notUsed);
drh14acc042001-06-10 19:56:58 +00004560 if( rc!=SQLITE_OK ){
drhee696e22004-08-30 16:52:17 +00004561 if( rc!=SQLITE_NOMEM ){
4562 rc = SQLITE_CORRUPT; /* bkpt-CORRUPT */
4563 }
danielk1977299b1872004-11-22 10:02:10 +00004564 return rc;
drh5e2f8b92001-05-28 00:41:15 +00004565 }
drha34b6762004-05-07 13:30:42 +00004566 rc = sqlite3pager_write(leafCur.pPage->aData);
danielk1977299b1872004-11-22 10:02:10 +00004567 if( rc ) return rc;
4568 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
4569 pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
4570 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
drh43605152004-05-29 21:46:49 +00004571 pNext = findCell(leafCur.pPage, leafCur.idx);
4572 szNext = cellSizePtr(leafCur.pPage, pNext);
drh2e38c322004-09-03 18:38:44 +00004573 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
4574 tempCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
danielk1977299b1872004-11-22 10:02:10 +00004575 if( tempCell==0 ) return SQLITE_NOMEM;
danielk1977a3ad5e72005-01-07 08:56:44 +00004576 rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
danielk1977299b1872004-11-22 10:02:10 +00004577 if( rc!=SQLITE_OK ) return rc;
4578 put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
danielk1977ac245ec2005-01-14 13:50:11 +00004579 rc = balance(pPage, 0);
drh2e38c322004-09-03 18:38:44 +00004580 sqliteFree(tempCell);
danielk1977299b1872004-11-22 10:02:10 +00004581 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00004582 dropCell(leafCur.pPage, leafCur.idx, szNext);
danielk1977ac245ec2005-01-14 13:50:11 +00004583 rc = balance(leafCur.pPage, 0);
drh8c42ca92001-06-22 19:15:00 +00004584 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00004585 }else{
danielk1977299b1872004-11-22 10:02:10 +00004586 TRACE(("DELETE: table=%d delete from leaf %d\n",
4587 pCur->pgnoRoot, pPage->pgno));
4588 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
danielk1977ac245ec2005-01-14 13:50:11 +00004589 rc = balance(pPage, 0);
drh5e2f8b92001-05-28 00:41:15 +00004590 }
danielk1977299b1872004-11-22 10:02:10 +00004591 moveToRoot(pCur);
drh5e2f8b92001-05-28 00:41:15 +00004592 return rc;
drh3b7511c2001-05-26 13:15:44 +00004593}
drh8b2f49b2001-06-08 00:21:52 +00004594
4595/*
drhc6b52df2002-01-04 03:09:29 +00004596** Create a new BTree table. Write into *piTable the page
4597** number for the root page of the new table.
4598**
drhab01f612004-05-22 02:55:23 +00004599** The type of type is determined by the flags parameter. Only the
4600** following values of flags are currently in use. Other values for
4601** flags might not work:
4602**
4603** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
4604** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00004605*/
drh3aac2dd2004-04-26 14:10:20 +00004606int sqlite3BtreeCreateTable(Btree *pBt, int *piTable, int flags){
drh8b2f49b2001-06-08 00:21:52 +00004607 MemPage *pRoot;
4608 Pgno pgnoRoot;
4609 int rc;
danielk1977ee5741e2004-05-31 10:01:34 +00004610 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00004611 /* Must start a transaction first */
4612 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00004613 }
danielk197728129562005-01-11 10:25:06 +00004614 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00004615
4616 /* It is illegal to create a table if any cursors are open on the
4617 ** database. This is because in auto-vacuum mode the backend may
4618 ** need to move a database page to make room for the new root-page.
4619 ** If an open cursor was using the page a problem would occur.
4620 */
4621 if( pBt->pCursor ){
4622 return SQLITE_LOCKED;
4623 }
4624
danielk1977003ba062004-11-04 02:57:33 +00004625#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977cb1a7eb2004-11-05 12:27:02 +00004626 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drh8b2f49b2001-06-08 00:21:52 +00004627 if( rc ) return rc;
danielk1977003ba062004-11-04 02:57:33 +00004628#else
danielk1977687566d2004-11-02 12:56:41 +00004629 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00004630 Pgno pgnoMove; /* Move a page here to make room for the root-page */
4631 MemPage *pPageMove; /* The page to move to. */
4632
danielk1977003ba062004-11-04 02:57:33 +00004633 /* Read the value of meta[3] from the database to determine where the
4634 ** root page of the new table should go. meta[3] is the largest root-page
4635 ** created so far, so the new root-page is (meta[3]+1).
4636 */
4637 rc = sqlite3BtreeGetMeta(pBt, 4, &pgnoRoot);
4638 if( rc!=SQLITE_OK ) return rc;
4639 pgnoRoot++;
4640
danielk1977599fcba2004-11-08 07:13:13 +00004641 /* The new root-page may not be allocated on a pointer-map page, or the
4642 ** PENDING_BYTE page.
4643 */
drh42cac6d2004-11-20 20:31:11 +00004644 if( pgnoRoot==PTRMAP_PAGENO(pBt->usableSize, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00004645 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00004646 pgnoRoot++;
4647 }
4648 assert( pgnoRoot>=3 );
4649
4650 /* Allocate a page. The page that currently resides at pgnoRoot will
4651 ** be moved to the allocated page (unless the allocated page happens
4652 ** to reside at pgnoRoot).
4653 */
danielk1977cb1a7eb2004-11-05 12:27:02 +00004654 rc = allocatePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00004655 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00004656 return rc;
4657 }
danielk1977003ba062004-11-04 02:57:33 +00004658
4659 if( pgnoMove!=pgnoRoot ){
4660 u8 eType;
4661 Pgno iPtrPage;
4662
4663 releasePage(pPageMove);
4664 rc = getPage(pBt, pgnoRoot, &pRoot);
4665 if( rc!=SQLITE_OK ){
4666 return rc;
4667 }
4668 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
danielk1977a0bf2652004-11-04 14:30:04 +00004669 assert( eType!=PTRMAP_ROOTPAGE );
danielk1977a64a0352004-11-05 01:45:13 +00004670 assert( eType!=PTRMAP_FREEPAGE );
danielk1977003ba062004-11-04 02:57:33 +00004671 if( rc!=SQLITE_OK ){
4672 releasePage(pRoot);
4673 return rc;
4674 }
4675 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove);
4676 releasePage(pRoot);
4677 if( rc!=SQLITE_OK ){
4678 return rc;
4679 }
4680 rc = getPage(pBt, pgnoRoot, &pRoot);
4681 if( rc!=SQLITE_OK ){
4682 return rc;
4683 }
4684 rc = sqlite3pager_write(pRoot->aData);
4685 if( rc!=SQLITE_OK ){
4686 releasePage(pRoot);
4687 return rc;
4688 }
4689 }else{
4690 pRoot = pPageMove;
4691 }
4692
danielk197742741be2005-01-08 12:42:39 +00004693 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00004694 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
4695 if( rc ){
4696 releasePage(pRoot);
4697 return rc;
4698 }
4699 rc = sqlite3BtreeUpdateMeta(pBt, 4, pgnoRoot);
4700 if( rc ){
4701 releasePage(pRoot);
4702 return rc;
4703 }
danielk197742741be2005-01-08 12:42:39 +00004704
danielk1977003ba062004-11-04 02:57:33 +00004705 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004706 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00004707 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00004708 }
4709#endif
drha34b6762004-05-07 13:30:42 +00004710 assert( sqlite3pager_iswriteable(pRoot->aData) );
drhde647132004-05-07 17:57:49 +00004711 zeroPage(pRoot, flags | PTF_LEAF);
drha34b6762004-05-07 13:30:42 +00004712 sqlite3pager_unref(pRoot->aData);
drh8b2f49b2001-06-08 00:21:52 +00004713 *piTable = (int)pgnoRoot;
4714 return SQLITE_OK;
4715}
4716
4717/*
4718** Erase the given database page and all its children. Return
4719** the page to the freelist.
4720*/
drh4b70f112004-05-02 21:12:19 +00004721static int clearDatabasePage(
4722 Btree *pBt, /* The BTree that contains the table */
4723 Pgno pgno, /* Page number to clear */
4724 MemPage *pParent, /* Parent page. NULL for the root */
4725 int freePageFlag /* Deallocate page if true */
4726){
drh8b2f49b2001-06-08 00:21:52 +00004727 MemPage *pPage;
4728 int rc;
drh4b70f112004-05-02 21:12:19 +00004729 unsigned char *pCell;
4730 int i;
drh8b2f49b2001-06-08 00:21:52 +00004731
drhde647132004-05-07 17:57:49 +00004732 rc = getAndInitPage(pBt, pgno, &pPage, pParent);
drh8b2f49b2001-06-08 00:21:52 +00004733 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00004734 rc = sqlite3pager_write(pPage->aData);
drh6019e162001-07-02 17:51:45 +00004735 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00004736 for(i=0; i<pPage->nCell; i++){
drh43605152004-05-29 21:46:49 +00004737 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00004738 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004739 rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
drh8b2f49b2001-06-08 00:21:52 +00004740 if( rc ) return rc;
4741 }
drh4b70f112004-05-02 21:12:19 +00004742 rc = clearCell(pPage, pCell);
drh8b2f49b2001-06-08 00:21:52 +00004743 if( rc ) return rc;
4744 }
drha34b6762004-05-07 13:30:42 +00004745 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004746 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
drh2aa679f2001-06-25 02:11:07 +00004747 if( rc ) return rc;
4748 }
4749 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00004750 rc = freePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00004751 }else{
drh3a4c1412004-05-09 20:40:11 +00004752 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00004753 }
drh4b70f112004-05-02 21:12:19 +00004754 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00004755 return rc;
drh8b2f49b2001-06-08 00:21:52 +00004756}
4757
4758/*
drhab01f612004-05-22 02:55:23 +00004759** Delete all information from a single table in the database. iTable is
4760** the page number of the root of the table. After this routine returns,
4761** the root page is empty, but still exists.
4762**
4763** This routine will fail with SQLITE_LOCKED if there are any open
4764** read cursors on the table. Open write cursors are moved to the
4765** root of the table.
drh8b2f49b2001-06-08 00:21:52 +00004766*/
drh3aac2dd2004-04-26 14:10:20 +00004767int sqlite3BtreeClearTable(Btree *pBt, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00004768 int rc;
drhf74b8d92002-09-01 23:20:45 +00004769 BtCursor *pCur;
danielk1977ee5741e2004-05-31 10:01:34 +00004770 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00004771 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00004772 }
drhf74b8d92002-09-01 23:20:45 +00004773 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
4774 if( pCur->pgnoRoot==(Pgno)iTable ){
4775 if( pCur->wrFlag==0 ) return SQLITE_LOCKED;
4776 moveToRoot(pCur);
4777 }
drhecdc7532001-09-23 02:35:53 +00004778 }
drha34b6762004-05-07 13:30:42 +00004779 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
drh8b2f49b2001-06-08 00:21:52 +00004780 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00004781 sqlite3BtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00004782 }
drh8c42ca92001-06-22 19:15:00 +00004783 return rc;
drh8b2f49b2001-06-08 00:21:52 +00004784}
4785
4786/*
4787** Erase all information in a table and add the root of the table to
4788** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00004789** page 1) is never added to the freelist.
4790**
4791** This routine will fail with SQLITE_LOCKED if there are any open
4792** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00004793**
4794** If AUTOVACUUM is enabled and the page at iTable is not the last
4795** root page in the database file, then the last root page
4796** in the database file is moved into the slot formerly occupied by
4797** iTable and that last slot formerly occupied by the last root page
4798** is added to the freelist instead of iTable. In this say, all
4799** root pages are kept at the beginning of the database file, which
4800** is necessary for AUTOVACUUM to work right. *piMoved is set to the
4801** page number that used to be the last root page in the file before
4802** the move. If no page gets moved, *piMoved is set to 0.
4803** The last root page is recorded in meta[3] and the value of
4804** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00004805*/
danielk1977a0bf2652004-11-04 14:30:04 +00004806int sqlite3BtreeDropTable(Btree *pBt, int iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00004807 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00004808 MemPage *pPage = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00004809
danielk1977ee5741e2004-05-31 10:01:34 +00004810 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00004811 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00004812 }
danielk1977a0bf2652004-11-04 14:30:04 +00004813
danielk1977e6efa742004-11-10 11:55:10 +00004814 /* It is illegal to drop a table if any cursors are open on the
4815 ** database. This is because in auto-vacuum mode the backend may
4816 ** need to move another root-page to fill a gap left by the deleted
4817 ** root page. If an open cursor was using this page a problem would
4818 ** occur.
4819 */
4820 if( pBt->pCursor ){
4821 return SQLITE_LOCKED;
drh5df72a52002-06-06 23:16:05 +00004822 }
danielk1977a0bf2652004-11-04 14:30:04 +00004823
drha34b6762004-05-07 13:30:42 +00004824 rc = getPage(pBt, (Pgno)iTable, &pPage);
drh2aa679f2001-06-25 02:11:07 +00004825 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004826 rc = sqlite3BtreeClearTable(pBt, iTable);
drh2aa679f2001-06-25 02:11:07 +00004827 if( rc ) return rc;
danielk1977a0bf2652004-11-04 14:30:04 +00004828
drh205f48e2004-11-05 00:43:11 +00004829 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00004830
drh4b70f112004-05-02 21:12:19 +00004831 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00004832#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00004833 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00004834 releasePage(pPage);
4835#else
4836 if( pBt->autoVacuum ){
4837 Pgno maxRootPgno;
4838 rc = sqlite3BtreeGetMeta(pBt, 4, &maxRootPgno);
4839 if( rc!=SQLITE_OK ){
4840 releasePage(pPage);
4841 return rc;
4842 }
4843
4844 if( iTable==maxRootPgno ){
4845 /* If the table being dropped is the table with the largest root-page
4846 ** number in the database, put the root page on the free list.
4847 */
4848 rc = freePage(pPage);
4849 releasePage(pPage);
4850 if( rc!=SQLITE_OK ){
4851 return rc;
4852 }
4853 }else{
4854 /* The table being dropped does not have the largest root-page
4855 ** number in the database. So move the page that does into the
4856 ** gap left by the deleted root-page.
4857 */
4858 MemPage *pMove;
4859 releasePage(pPage);
4860 rc = getPage(pBt, maxRootPgno, &pMove);
4861 if( rc!=SQLITE_OK ){
4862 return rc;
4863 }
4864 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable);
4865 releasePage(pMove);
4866 if( rc!=SQLITE_OK ){
4867 return rc;
4868 }
4869 rc = getPage(pBt, maxRootPgno, &pMove);
4870 if( rc!=SQLITE_OK ){
4871 return rc;
4872 }
4873 rc = freePage(pMove);
4874 releasePage(pMove);
4875 if( rc!=SQLITE_OK ){
4876 return rc;
4877 }
4878 *piMoved = maxRootPgno;
4879 }
4880
danielk1977599fcba2004-11-08 07:13:13 +00004881 /* Set the new 'max-root-page' value in the database header. This
4882 ** is the old value less one, less one more if that happens to
4883 ** be a root-page number, less one again if that is the
4884 ** PENDING_BYTE_PAGE.
4885 */
danielk197787a6e732004-11-05 12:58:25 +00004886 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00004887 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
4888 maxRootPgno--;
4889 }
drh42cac6d2004-11-20 20:31:11 +00004890 if( maxRootPgno==PTRMAP_PAGENO(pBt->usableSize, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00004891 maxRootPgno--;
4892 }
danielk1977599fcba2004-11-08 07:13:13 +00004893 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
4894
danielk197787a6e732004-11-05 12:58:25 +00004895 rc = sqlite3BtreeUpdateMeta(pBt, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00004896 }else{
4897 rc = freePage(pPage);
4898 releasePage(pPage);
4899 }
4900#endif
drh2aa679f2001-06-25 02:11:07 +00004901 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00004902 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00004903 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00004904 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00004905 }
drh8b2f49b2001-06-08 00:21:52 +00004906 return rc;
4907}
4908
drh001bbcb2003-03-19 03:14:00 +00004909
drh8b2f49b2001-06-08 00:21:52 +00004910/*
drh23e11ca2004-05-04 17:27:28 +00004911** Read the meta-information out of a database file. Meta[0]
4912** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00004913** through meta[15] are available for use by higher layers. Meta[0]
4914** is read-only, the others are read/write.
4915**
4916** The schema layer numbers meta values differently. At the schema
4917** layer (and the SetCookie and ReadCookie opcodes) the number of
4918** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00004919*/
drh3aac2dd2004-04-26 14:10:20 +00004920int sqlite3BtreeGetMeta(Btree *pBt, int idx, u32 *pMeta){
drh8b2f49b2001-06-08 00:21:52 +00004921 int rc;
drh4b70f112004-05-02 21:12:19 +00004922 unsigned char *pP1;
drh8b2f49b2001-06-08 00:21:52 +00004923
drh23e11ca2004-05-04 17:27:28 +00004924 assert( idx>=0 && idx<=15 );
drha34b6762004-05-07 13:30:42 +00004925 rc = sqlite3pager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00004926 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00004927 *pMeta = get4byte(&pP1[36 + idx*4]);
drha34b6762004-05-07 13:30:42 +00004928 sqlite3pager_unref(pP1);
drhae157872004-08-14 19:20:09 +00004929
danielk1977599fcba2004-11-08 07:13:13 +00004930 /* If autovacuumed is disabled in this build but we are trying to
4931 ** access an autovacuumed database, then make the database readonly.
4932 */
danielk1977003ba062004-11-04 02:57:33 +00004933#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00004934 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00004935#endif
drhae157872004-08-14 19:20:09 +00004936
drh8b2f49b2001-06-08 00:21:52 +00004937 return SQLITE_OK;
4938}
4939
4940/*
drh23e11ca2004-05-04 17:27:28 +00004941** Write meta-information back into the database. Meta[0] is
4942** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00004943*/
drh3aac2dd2004-04-26 14:10:20 +00004944int sqlite3BtreeUpdateMeta(Btree *pBt, int idx, u32 iMeta){
drh4b70f112004-05-02 21:12:19 +00004945 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00004946 int rc;
drh23e11ca2004-05-04 17:27:28 +00004947 assert( idx>=1 && idx<=15 );
danielk1977ee5741e2004-05-31 10:01:34 +00004948 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00004949 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +00004950 }
drhde647132004-05-07 17:57:49 +00004951 assert( pBt->pPage1!=0 );
4952 pP1 = pBt->pPage1->aData;
drha34b6762004-05-07 13:30:42 +00004953 rc = sqlite3pager_write(pP1);
drh4b70f112004-05-02 21:12:19 +00004954 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00004955 put4byte(&pP1[36 + idx*4], iMeta);
drh8b2f49b2001-06-08 00:21:52 +00004956 return SQLITE_OK;
4957}
drh8c42ca92001-06-22 19:15:00 +00004958
drhf328bc82004-05-10 23:29:49 +00004959/*
4960** Return the flag byte at the beginning of the page that the cursor
4961** is currently pointing to.
4962*/
4963int sqlite3BtreeFlags(BtCursor *pCur){
4964 MemPage *pPage = pCur->pPage;
4965 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
4966}
4967
danielk1977b5402fb2005-01-12 07:15:04 +00004968#ifdef SQLITE_DEBUG
drh8c42ca92001-06-22 19:15:00 +00004969/*
4970** Print a disassembly of the given page on standard output. This routine
4971** is used for debugging and testing only.
4972*/
danielk1977c7dc7532004-11-17 10:22:03 +00004973static int btreePageDump(Btree *pBt, int pgno, int recursive, MemPage *pParent){
drh8c42ca92001-06-22 19:15:00 +00004974 int rc;
4975 MemPage *pPage;
drhc8629a12004-05-08 20:07:40 +00004976 int i, j, c;
drh8c42ca92001-06-22 19:15:00 +00004977 int nFree;
4978 u16 idx;
drhab9f7f12004-05-08 10:56:11 +00004979 int hdr;
drh43605152004-05-29 21:46:49 +00004980 int nCell;
drha2fce642004-06-05 00:01:44 +00004981 int isInit;
drhab9f7f12004-05-08 10:56:11 +00004982 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00004983 char range[20];
4984 unsigned char payload[20];
drhab9f7f12004-05-08 10:56:11 +00004985
drh4b70f112004-05-02 21:12:19 +00004986 rc = getPage(pBt, (Pgno)pgno, &pPage);
drha2fce642004-06-05 00:01:44 +00004987 isInit = pPage->isInit;
4988 if( pPage->isInit==0 ){
danielk1977c7dc7532004-11-17 10:22:03 +00004989 initPage(pPage, pParent);
drha2fce642004-06-05 00:01:44 +00004990 }
drh8c42ca92001-06-22 19:15:00 +00004991 if( rc ){
4992 return rc;
4993 }
drhab9f7f12004-05-08 10:56:11 +00004994 hdr = pPage->hdrOffset;
4995 data = pPage->aData;
drhc8629a12004-05-08 20:07:40 +00004996 c = data[hdr];
drh8b18dd42004-05-12 19:18:15 +00004997 pPage->intKey = (c & (PTF_INTKEY|PTF_LEAFDATA))!=0;
drhc8629a12004-05-08 20:07:40 +00004998 pPage->zeroData = (c & PTF_ZERODATA)!=0;
drh8b18dd42004-05-12 19:18:15 +00004999 pPage->leafData = (c & PTF_LEAFDATA)!=0;
drhc8629a12004-05-08 20:07:40 +00005000 pPage->leaf = (c & PTF_LEAF)!=0;
drh8b18dd42004-05-12 19:18:15 +00005001 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
drh43605152004-05-29 21:46:49 +00005002 nCell = get2byte(&data[hdr+3]);
drhfe63d1c2004-09-08 20:13:04 +00005003 sqlite3DebugPrintf("PAGE %d: flags=0x%02x frag=%d parent=%d\n", pgno,
drh43605152004-05-29 21:46:49 +00005004 data[hdr], data[hdr+7],
drhda200cc2004-05-09 11:51:38 +00005005 (pPage->isInit && pPage->pParent) ? pPage->pParent->pgno : 0);
drhab9f7f12004-05-08 10:56:11 +00005006 assert( hdr == (pgno==1 ? 100 : 0) );
drh43605152004-05-29 21:46:49 +00005007 idx = hdr + 12 - pPage->leaf*4;
5008 for(i=0; i<nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00005009 CellInfo info;
drh4b70f112004-05-02 21:12:19 +00005010 Pgno child;
drh43605152004-05-29 21:46:49 +00005011 unsigned char *pCell;
drh6f11bef2004-05-13 01:12:56 +00005012 int sz;
drh43605152004-05-29 21:46:49 +00005013 int addr;
drh6f11bef2004-05-13 01:12:56 +00005014
drh43605152004-05-29 21:46:49 +00005015 addr = get2byte(&data[idx + 2*i]);
5016 pCell = &data[addr];
5017 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005018 sz = info.nSize;
drh43605152004-05-29 21:46:49 +00005019 sprintf(range,"%d..%d", addr, addr+sz-1);
drh4b70f112004-05-02 21:12:19 +00005020 if( pPage->leaf ){
5021 child = 0;
5022 }else{
drh43605152004-05-29 21:46:49 +00005023 child = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005024 }
drh6f11bef2004-05-13 01:12:56 +00005025 sz = info.nData;
5026 if( !pPage->intKey ) sz += info.nKey;
drh8c42ca92001-06-22 19:15:00 +00005027 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
drh6f11bef2004-05-13 01:12:56 +00005028 memcpy(payload, &pCell[info.nHeader], sz);
drh8c42ca92001-06-22 19:15:00 +00005029 for(j=0; j<sz; j++){
5030 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
5031 }
5032 payload[sz] = 0;
drhfe63d1c2004-09-08 20:13:04 +00005033 sqlite3DebugPrintf(
drh6f11bef2004-05-13 01:12:56 +00005034 "cell %2d: i=%-10s chld=%-4d nk=%-4lld nd=%-4d payload=%s\n",
5035 i, range, child, info.nKey, info.nData, payload
drh8c42ca92001-06-22 19:15:00 +00005036 );
drh8c42ca92001-06-22 19:15:00 +00005037 }
drh4b70f112004-05-02 21:12:19 +00005038 if( !pPage->leaf ){
drhfe63d1c2004-09-08 20:13:04 +00005039 sqlite3DebugPrintf("right_child: %d\n", get4byte(&data[hdr+8]));
drh4b70f112004-05-02 21:12:19 +00005040 }
drh8c42ca92001-06-22 19:15:00 +00005041 nFree = 0;
5042 i = 0;
drhab9f7f12004-05-08 10:56:11 +00005043 idx = get2byte(&data[hdr+1]);
drhb6f41482004-05-14 01:58:11 +00005044 while( idx>0 && idx<pPage->pBt->usableSize ){
drhab9f7f12004-05-08 10:56:11 +00005045 int sz = get2byte(&data[idx+2]);
drh4b70f112004-05-02 21:12:19 +00005046 sprintf(range,"%d..%d", idx, idx+sz-1);
5047 nFree += sz;
drhfe63d1c2004-09-08 20:13:04 +00005048 sqlite3DebugPrintf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
drh4b70f112004-05-02 21:12:19 +00005049 i, range, sz, nFree);
drhab9f7f12004-05-08 10:56:11 +00005050 idx = get2byte(&data[idx]);
drh2aa679f2001-06-25 02:11:07 +00005051 i++;
drh8c42ca92001-06-22 19:15:00 +00005052 }
5053 if( idx!=0 ){
drhfe63d1c2004-09-08 20:13:04 +00005054 sqlite3DebugPrintf("ERROR: next freeblock index out of range: %d\n", idx);
drh8c42ca92001-06-22 19:15:00 +00005055 }
drha34b6762004-05-07 13:30:42 +00005056 if( recursive && !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005057 for(i=0; i<nCell; i++){
5058 unsigned char *pCell = findCell(pPage, i);
danielk1977c7dc7532004-11-17 10:22:03 +00005059 btreePageDump(pBt, get4byte(pCell), 1, pPage);
drha34b6762004-05-07 13:30:42 +00005060 idx = get2byte(pCell);
drh6019e162001-07-02 17:51:45 +00005061 }
danielk1977c7dc7532004-11-17 10:22:03 +00005062 btreePageDump(pBt, get4byte(&data[hdr+8]), 1, pPage);
drh6019e162001-07-02 17:51:45 +00005063 }
drha2fce642004-06-05 00:01:44 +00005064 pPage->isInit = isInit;
drhab9f7f12004-05-08 10:56:11 +00005065 sqlite3pager_unref(data);
drh3644f082004-05-10 18:45:09 +00005066 fflush(stdout);
drh8c42ca92001-06-22 19:15:00 +00005067 return SQLITE_OK;
5068}
danielk1977c7dc7532004-11-17 10:22:03 +00005069int sqlite3BtreePageDump(Btree *pBt, int pgno, int recursive){
5070 return btreePageDump(pBt, pgno, recursive, 0);
5071}
drhaaab5722002-02-19 13:39:21 +00005072#endif
drh8c42ca92001-06-22 19:15:00 +00005073
drhaaab5722002-02-19 13:39:21 +00005074#ifdef SQLITE_TEST
drh8c42ca92001-06-22 19:15:00 +00005075/*
drh2aa679f2001-06-25 02:11:07 +00005076** Fill aResult[] with information about the entry and page that the
5077** cursor is pointing to.
5078**
5079** aResult[0] = The page number
5080** aResult[1] = The entry number
5081** aResult[2] = Total number of entries on this page
drh3e27c022004-07-23 00:01:38 +00005082** aResult[3] = Cell size (local payload + header)
drh2aa679f2001-06-25 02:11:07 +00005083** aResult[4] = Number of free bytes on this page
5084** aResult[5] = Number of free blocks on the page
drh3e27c022004-07-23 00:01:38 +00005085** aResult[6] = Total payload size (local + overflow)
5086** aResult[7] = Header size in bytes
5087** aResult[8] = Local payload size
5088** aResult[9] = Parent page number
drh5eddca62001-06-30 21:53:53 +00005089**
5090** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00005091*/
drh3e27c022004-07-23 00:01:38 +00005092int sqlite3BtreeCursorInfo(BtCursor *pCur, int *aResult, int upCnt){
drh2aa679f2001-06-25 02:11:07 +00005093 int cnt, idx;
5094 MemPage *pPage = pCur->pPage;
drh3e27c022004-07-23 00:01:38 +00005095 BtCursor tmpCur;
drhda200cc2004-05-09 11:51:38 +00005096
5097 pageIntegrity(pPage);
drh4b70f112004-05-02 21:12:19 +00005098 assert( pPage->isInit );
drh3e27c022004-07-23 00:01:38 +00005099 getTempCursor(pCur, &tmpCur);
5100 while( upCnt-- ){
5101 moveToParent(&tmpCur);
5102 }
5103 pPage = tmpCur.pPage;
5104 pageIntegrity(pPage);
drha34b6762004-05-07 13:30:42 +00005105 aResult[0] = sqlite3pager_pagenumber(pPage->aData);
drh91025292004-05-03 19:49:32 +00005106 assert( aResult[0]==pPage->pgno );
drh3e27c022004-07-23 00:01:38 +00005107 aResult[1] = tmpCur.idx;
drh2aa679f2001-06-25 02:11:07 +00005108 aResult[2] = pPage->nCell;
drh3e27c022004-07-23 00:01:38 +00005109 if( tmpCur.idx>=0 && tmpCur.idx<pPage->nCell ){
5110 getCellInfo(&tmpCur);
5111 aResult[3] = tmpCur.info.nSize;
5112 aResult[6] = tmpCur.info.nData;
5113 aResult[7] = tmpCur.info.nHeader;
5114 aResult[8] = tmpCur.info.nLocal;
drh2aa679f2001-06-25 02:11:07 +00005115 }else{
5116 aResult[3] = 0;
5117 aResult[6] = 0;
drh3e27c022004-07-23 00:01:38 +00005118 aResult[7] = 0;
5119 aResult[8] = 0;
drh2aa679f2001-06-25 02:11:07 +00005120 }
5121 aResult[4] = pPage->nFree;
5122 cnt = 0;
drh4b70f112004-05-02 21:12:19 +00005123 idx = get2byte(&pPage->aData[pPage->hdrOffset+1]);
drhb6f41482004-05-14 01:58:11 +00005124 while( idx>0 && idx<pPage->pBt->usableSize ){
drh2aa679f2001-06-25 02:11:07 +00005125 cnt++;
drh4b70f112004-05-02 21:12:19 +00005126 idx = get2byte(&pPage->aData[idx]);
drh2aa679f2001-06-25 02:11:07 +00005127 }
5128 aResult[5] = cnt;
drh3e27c022004-07-23 00:01:38 +00005129 if( pPage->pParent==0 || isRootPage(pPage) ){
5130 aResult[9] = 0;
5131 }else{
5132 aResult[9] = pPage->pParent->pgno;
5133 }
5134 releaseTempCursor(&tmpCur);
drh8c42ca92001-06-22 19:15:00 +00005135 return SQLITE_OK;
5136}
drhaaab5722002-02-19 13:39:21 +00005137#endif
drhdd793422001-06-28 01:54:48 +00005138
drhdd793422001-06-28 01:54:48 +00005139/*
drh5eddca62001-06-30 21:53:53 +00005140** Return the pager associated with a BTree. This routine is used for
5141** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00005142*/
drh3aac2dd2004-04-26 14:10:20 +00005143Pager *sqlite3BtreePager(Btree *pBt){
drhdd793422001-06-28 01:54:48 +00005144 return pBt->pPager;
5145}
drh5eddca62001-06-30 21:53:53 +00005146
5147/*
5148** This structure is passed around through all the sanity checking routines
5149** in order to keep track of some global state information.
5150*/
drhaaab5722002-02-19 13:39:21 +00005151typedef struct IntegrityCk IntegrityCk;
5152struct IntegrityCk {
drh100569d2001-10-02 13:01:48 +00005153 Btree *pBt; /* The tree being checked out */
5154 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
5155 int nPage; /* Number of pages in the database */
5156 int *anRef; /* Number of times each page is referenced */
drh100569d2001-10-02 13:01:48 +00005157 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00005158};
5159
drhb7f91642004-10-31 02:22:47 +00005160#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005161/*
5162** Append a message to the error message string.
5163*/
drh2e38c322004-09-03 18:38:44 +00005164static void checkAppendMsg(
5165 IntegrityCk *pCheck,
5166 char *zMsg1,
5167 const char *zFormat,
5168 ...
5169){
5170 va_list ap;
5171 char *zMsg2;
5172 va_start(ap, zFormat);
5173 zMsg2 = sqlite3VMPrintf(zFormat, ap);
5174 va_end(ap);
5175 if( zMsg1==0 ) zMsg1 = "";
drh5eddca62001-06-30 21:53:53 +00005176 if( pCheck->zErrMsg ){
5177 char *zOld = pCheck->zErrMsg;
5178 pCheck->zErrMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00005179 sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00005180 sqliteFree(zOld);
5181 }else{
danielk19774adee202004-05-08 08:23:19 +00005182 sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00005183 }
drh2e38c322004-09-03 18:38:44 +00005184 sqliteFree(zMsg2);
drh5eddca62001-06-30 21:53:53 +00005185}
drhb7f91642004-10-31 02:22:47 +00005186#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005187
drhb7f91642004-10-31 02:22:47 +00005188#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005189/*
5190** Add 1 to the reference count for page iPage. If this is the second
5191** reference to the page, add an error message to pCheck->zErrMsg.
5192** Return 1 if there are 2 ore more references to the page and 0 if
5193** if this is the first reference to the page.
5194**
5195** Also check that the page number is in bounds.
5196*/
drhaaab5722002-02-19 13:39:21 +00005197static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00005198 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00005199 if( iPage>pCheck->nPage || iPage<0 ){
drh2e38c322004-09-03 18:38:44 +00005200 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005201 return 1;
5202 }
5203 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00005204 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005205 return 1;
5206 }
5207 return (pCheck->anRef[iPage]++)>1;
5208}
5209
danielk1977afcdd022004-10-31 16:25:42 +00005210#ifndef SQLITE_OMIT_AUTOVACUUM
5211/*
5212** Check that the entry in the pointer-map for page iChild maps to
5213** page iParent, pointer type ptrType. If not, append an error message
5214** to pCheck.
5215*/
5216static void checkPtrmap(
5217 IntegrityCk *pCheck, /* Integrity check context */
5218 Pgno iChild, /* Child page number */
5219 u8 eType, /* Expected pointer map type */
5220 Pgno iParent, /* Expected pointer map parent page number */
5221 char *zContext /* Context description (used for error msg) */
5222){
5223 int rc;
5224 u8 ePtrmapType;
5225 Pgno iPtrmapParent;
5226
5227 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
5228 if( rc!=SQLITE_OK ){
5229 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
5230 return;
5231 }
5232
5233 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
5234 checkAppendMsg(pCheck, zContext,
5235 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
5236 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
5237 }
5238}
5239#endif
5240
drh5eddca62001-06-30 21:53:53 +00005241/*
5242** Check the integrity of the freelist or of an overflow page list.
5243** Verify that the number of pages on the list is N.
5244*/
drh30e58752002-03-02 20:41:57 +00005245static void checkList(
5246 IntegrityCk *pCheck, /* Integrity checking context */
5247 int isFreeList, /* True for a freelist. False for overflow page list */
5248 int iPage, /* Page number for first page in the list */
5249 int N, /* Expected number of pages in the list */
5250 char *zContext /* Context for error messages */
5251){
5252 int i;
drh3a4c1412004-05-09 20:40:11 +00005253 int expected = N;
5254 int iFirst = iPage;
drh30e58752002-03-02 20:41:57 +00005255 while( N-- > 0 ){
drh4b70f112004-05-02 21:12:19 +00005256 unsigned char *pOvfl;
drh5eddca62001-06-30 21:53:53 +00005257 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00005258 checkAppendMsg(pCheck, zContext,
5259 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00005260 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00005261 break;
5262 }
5263 if( checkRef(pCheck, iPage, zContext) ) break;
drha34b6762004-05-07 13:30:42 +00005264 if( sqlite3pager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
drh2e38c322004-09-03 18:38:44 +00005265 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005266 break;
5267 }
drh30e58752002-03-02 20:41:57 +00005268 if( isFreeList ){
drh4b70f112004-05-02 21:12:19 +00005269 int n = get4byte(&pOvfl[4]);
danielk1977687566d2004-11-02 12:56:41 +00005270#ifndef SQLITE_OMIT_AUTOVACUUM
5271 if( pCheck->pBt->autoVacuum ){
5272 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
5273 }
5274#endif
drh855eb1c2004-08-31 13:45:11 +00005275 if( n>pCheck->pBt->usableSize/4-8 ){
drh2e38c322004-09-03 18:38:44 +00005276 checkAppendMsg(pCheck, zContext,
5277 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00005278 N--;
5279 }else{
5280 for(i=0; i<n; i++){
danielk1977687566d2004-11-02 12:56:41 +00005281 Pgno iFreePage = get4byte(&pOvfl[8+i*4]);
5282#ifndef SQLITE_OMIT_AUTOVACUUM
5283 if( pCheck->pBt->autoVacuum ){
5284 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
5285 }
5286#endif
5287 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00005288 }
5289 N -= n;
drh30e58752002-03-02 20:41:57 +00005290 }
drh30e58752002-03-02 20:41:57 +00005291 }
danielk1977afcdd022004-10-31 16:25:42 +00005292#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00005293 else{
5294 /* If this database supports auto-vacuum and iPage is not the last
5295 ** page in this overflow list, check that the pointer-map entry for
5296 ** the following page matches iPage.
5297 */
5298 if( pCheck->pBt->autoVacuum && N>0 ){
5299 i = get4byte(pOvfl);
5300 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
5301 }
danielk1977afcdd022004-10-31 16:25:42 +00005302 }
5303#endif
drh4b70f112004-05-02 21:12:19 +00005304 iPage = get4byte(pOvfl);
drha34b6762004-05-07 13:30:42 +00005305 sqlite3pager_unref(pOvfl);
drh5eddca62001-06-30 21:53:53 +00005306 }
5307}
drhb7f91642004-10-31 02:22:47 +00005308#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005309
drhb7f91642004-10-31 02:22:47 +00005310#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005311/*
5312** Do various sanity checks on a single page of a tree. Return
5313** the tree depth. Root pages return 0. Parents of root pages
5314** return 1, and so forth.
5315**
5316** These checks are done:
5317**
5318** 1. Make sure that cells and freeblocks do not overlap
5319** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00005320** NO 2. Make sure cell keys are in order.
5321** NO 3. Make sure no key is less than or equal to zLowerBound.
5322** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00005323** 5. Check the integrity of overflow pages.
5324** 6. Recursively call checkTreePage on all children.
5325** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00005326** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00005327** the root of the tree.
5328*/
5329static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00005330 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00005331 int iPage, /* Page number of the page to check */
5332 MemPage *pParent, /* Parent page */
5333 char *zParentContext, /* Parent context */
5334 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00005335 int nLower, /* Number of characters in zLowerBound */
5336 char *zUpperBound, /* All keys should be less than this, if not NULL */
5337 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00005338){
5339 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00005340 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00005341 int hdr, cellStart;
5342 int nCell;
drhda200cc2004-05-09 11:51:38 +00005343 u8 *data;
drh5eddca62001-06-30 21:53:53 +00005344 BtCursor cur;
drh0d316a42002-08-11 20:10:47 +00005345 Btree *pBt;
drhb6f41482004-05-14 01:58:11 +00005346 int maxLocal, usableSize;
drh5eddca62001-06-30 21:53:53 +00005347 char zContext[100];
drh2e38c322004-09-03 18:38:44 +00005348 char *hit;
drh5eddca62001-06-30 21:53:53 +00005349
danielk1977ef73ee92004-11-06 12:26:07 +00005350 sprintf(zContext, "Page %d: ", iPage);
5351
drh5eddca62001-06-30 21:53:53 +00005352 /* Check that the page exists
5353 */
drh0d316a42002-08-11 20:10:47 +00005354 cur.pBt = pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00005355 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00005356 if( iPage==0 ) return 0;
5357 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh4b70f112004-05-02 21:12:19 +00005358 if( (rc = getPage(pBt, (Pgno)iPage, &pPage))!=0 ){
drh2e38c322004-09-03 18:38:44 +00005359 checkAppendMsg(pCheck, zContext,
5360 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00005361 return 0;
5362 }
drh6f11bef2004-05-13 01:12:56 +00005363 maxLocal = pPage->leafData ? pBt->maxLeaf : pBt->maxLocal;
drh4b70f112004-05-02 21:12:19 +00005364 if( (rc = initPage(pPage, pParent))!=0 ){
drh2e38c322004-09-03 18:38:44 +00005365 checkAppendMsg(pCheck, zContext, "initPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00005366 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00005367 return 0;
5368 }
5369
5370 /* Check out all the cells.
5371 */
5372 depth = 0;
drh5eddca62001-06-30 21:53:53 +00005373 cur.pPage = pPage;
drh5eddca62001-06-30 21:53:53 +00005374 for(i=0; i<pPage->nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00005375 u8 *pCell;
5376 int sz;
5377 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00005378
5379 /* Check payload overflow pages
5380 */
drh3a4c1412004-05-09 20:40:11 +00005381 sprintf(zContext, "On tree page %d cell %d: ", iPage, i);
drh43605152004-05-29 21:46:49 +00005382 pCell = findCell(pPage,i);
5383 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005384 sz = info.nData;
5385 if( !pPage->intKey ) sz += info.nKey;
5386 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00005387 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00005388 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
5389#ifndef SQLITE_OMIT_AUTOVACUUM
5390 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00005391 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00005392 }
5393#endif
5394 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00005395 }
5396
5397 /* Check sanity of left child page.
5398 */
drhda200cc2004-05-09 11:51:38 +00005399 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005400 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00005401#ifndef SQLITE_OMIT_AUTOVACUUM
5402 if( pBt->autoVacuum ){
5403 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
5404 }
5405#endif
drhda200cc2004-05-09 11:51:38 +00005406 d2 = checkTreePage(pCheck,pgno,pPage,zContext,0,0,0,0);
5407 if( i>0 && d2!=depth ){
5408 checkAppendMsg(pCheck, zContext, "Child page depth differs");
5409 }
5410 depth = d2;
drh5eddca62001-06-30 21:53:53 +00005411 }
drh5eddca62001-06-30 21:53:53 +00005412 }
drhda200cc2004-05-09 11:51:38 +00005413 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005414 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drhda200cc2004-05-09 11:51:38 +00005415 sprintf(zContext, "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00005416#ifndef SQLITE_OMIT_AUTOVACUUM
5417 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00005418 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00005419 }
5420#endif
drhda200cc2004-05-09 11:51:38 +00005421 checkTreePage(pCheck, pgno, pPage, zContext,0,0,0,0);
5422 }
drh5eddca62001-06-30 21:53:53 +00005423
5424 /* Check for complete coverage of the page
5425 */
drhda200cc2004-05-09 11:51:38 +00005426 data = pPage->aData;
5427 hdr = pPage->hdrOffset;
drh2e38c322004-09-03 18:38:44 +00005428 hit = sqliteMalloc( usableSize );
5429 if( hit ){
5430 memset(hit, 1, get2byte(&data[hdr+5]));
5431 nCell = get2byte(&data[hdr+3]);
5432 cellStart = hdr + 12 - 4*pPage->leaf;
5433 for(i=0; i<nCell; i++){
5434 int pc = get2byte(&data[cellStart+i*2]);
5435 int size = cellSizePtr(pPage, &data[pc]);
5436 int j;
danielk19777701e812005-01-10 12:59:51 +00005437 if( (pc+size-1)>=usableSize || pc<0 ){
5438 checkAppendMsg(pCheck, 0,
5439 "Corruption detected in cell %d on page %d",i,iPage,0);
5440 }else{
5441 for(j=pc+size-1; j>=pc; j--) hit[j]++;
5442 }
drh2e38c322004-09-03 18:38:44 +00005443 }
5444 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
5445 cnt++){
5446 int size = get2byte(&data[i+2]);
5447 int j;
danielk19777701e812005-01-10 12:59:51 +00005448 if( (i+size-1)>=usableSize || i<0 ){
5449 checkAppendMsg(pCheck, 0,
5450 "Corruption detected in cell %d on page %d",i,iPage,0);
5451 }else{
5452 for(j=i+size-1; j>=i; j--) hit[j]++;
5453 }
drh2e38c322004-09-03 18:38:44 +00005454 i = get2byte(&data[i]);
5455 }
5456 for(i=cnt=0; i<usableSize; i++){
5457 if( hit[i]==0 ){
5458 cnt++;
5459 }else if( hit[i]>1 ){
5460 checkAppendMsg(pCheck, 0,
5461 "Multiple uses for byte %d of page %d", i, iPage);
5462 break;
5463 }
5464 }
5465 if( cnt!=data[hdr+7] ){
5466 checkAppendMsg(pCheck, 0,
5467 "Fragmented space is %d byte reported as %d on page %d",
5468 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00005469 }
5470 }
drh2e38c322004-09-03 18:38:44 +00005471 sqliteFree(hit);
drh6019e162001-07-02 17:51:45 +00005472
drh4b70f112004-05-02 21:12:19 +00005473 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00005474 return depth+1;
drh5eddca62001-06-30 21:53:53 +00005475}
drhb7f91642004-10-31 02:22:47 +00005476#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005477
drhb7f91642004-10-31 02:22:47 +00005478#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005479/*
5480** This routine does a complete check of the given BTree file. aRoot[] is
5481** an array of pages numbers were each page number is the root page of
5482** a table. nRoot is the number of entries in aRoot.
5483**
5484** If everything checks out, this routine returns NULL. If something is
5485** amiss, an error message is written into memory obtained from malloc()
5486** and a pointer to that error message is returned. The calling function
5487** is responsible for freeing the error message when it is done.
5488*/
drh3aac2dd2004-04-26 14:10:20 +00005489char *sqlite3BtreeIntegrityCheck(Btree *pBt, int *aRoot, int nRoot){
drh5eddca62001-06-30 21:53:53 +00005490 int i;
5491 int nRef;
drhaaab5722002-02-19 13:39:21 +00005492 IntegrityCk sCheck;
drh5eddca62001-06-30 21:53:53 +00005493
drha34b6762004-05-07 13:30:42 +00005494 nRef = *sqlite3pager_stats(pBt->pPager);
drhefc251d2001-07-01 22:12:01 +00005495 if( lockBtree(pBt)!=SQLITE_OK ){
5496 return sqliteStrDup("Unable to acquire a read lock on the database");
5497 }
drh5eddca62001-06-30 21:53:53 +00005498 sCheck.pBt = pBt;
5499 sCheck.pPager = pBt->pPager;
drha34b6762004-05-07 13:30:42 +00005500 sCheck.nPage = sqlite3pager_pagecount(sCheck.pPager);
drh0de8c112002-07-06 16:32:14 +00005501 if( sCheck.nPage==0 ){
5502 unlockBtreeIfUnused(pBt);
5503 return 0;
5504 }
drh8c1238a2003-01-02 14:43:55 +00005505 sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00005506 if( !sCheck.anRef ){
5507 unlockBtreeIfUnused(pBt);
5508 return sqlite3MPrintf("Unable to malloc %d bytes",
5509 (sCheck.nPage+1)*sizeof(sCheck.anRef[0]));
5510 }
drhda200cc2004-05-09 11:51:38 +00005511 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00005512 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00005513 if( i<=sCheck.nPage ){
5514 sCheck.anRef[i] = 1;
5515 }
drh5eddca62001-06-30 21:53:53 +00005516 sCheck.zErrMsg = 0;
5517
5518 /* Check the integrity of the freelist
5519 */
drha34b6762004-05-07 13:30:42 +00005520 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
5521 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00005522
5523 /* Check all the tables.
5524 */
5525 for(i=0; i<nRoot; i++){
drh4ff6dfa2002-03-03 23:06:00 +00005526 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00005527#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00005528 if( pBt->autoVacuum && aRoot[i]>1 ){
5529 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
5530 }
5531#endif
drh1bffb9c2002-02-03 17:37:36 +00005532 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00005533 }
5534
5535 /* Make sure every page in the file is referenced
5536 */
5537 for(i=1; i<=sCheck.nPage; i++){
danielk1977afcdd022004-10-31 16:25:42 +00005538#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00005539 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00005540 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00005541 }
danielk1977afcdd022004-10-31 16:25:42 +00005542#else
5543 /* If the database supports auto-vacuum, make sure no tables contain
5544 ** references to pointer-map pages.
5545 */
5546 if( sCheck.anRef[i]==0 &&
drh42cac6d2004-11-20 20:31:11 +00005547 (PTRMAP_PAGENO(pBt->usableSize, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00005548 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
5549 }
5550 if( sCheck.anRef[i]!=0 &&
drh42cac6d2004-11-20 20:31:11 +00005551 (PTRMAP_PAGENO(pBt->usableSize, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00005552 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
5553 }
5554#endif
drh5eddca62001-06-30 21:53:53 +00005555 }
5556
5557 /* Make sure this analysis did not leave any unref() pages
5558 */
drh5e00f6c2001-09-13 13:46:56 +00005559 unlockBtreeIfUnused(pBt);
drha34b6762004-05-07 13:30:42 +00005560 if( nRef != *sqlite3pager_stats(pBt->pPager) ){
drh2e38c322004-09-03 18:38:44 +00005561 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00005562 "Outstanding page count goes from %d to %d during this analysis",
drha34b6762004-05-07 13:30:42 +00005563 nRef, *sqlite3pager_stats(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00005564 );
drh5eddca62001-06-30 21:53:53 +00005565 }
5566
5567 /* Clean up and report errors.
5568 */
5569 sqliteFree(sCheck.anRef);
5570 return sCheck.zErrMsg;
5571}
drhb7f91642004-10-31 02:22:47 +00005572#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00005573
drh73509ee2003-04-06 20:44:45 +00005574/*
5575** Return the full pathname of the underlying database file.
5576*/
drh3aac2dd2004-04-26 14:10:20 +00005577const char *sqlite3BtreeGetFilename(Btree *pBt){
drh73509ee2003-04-06 20:44:45 +00005578 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00005579 return sqlite3pager_filename(pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00005580}
5581
5582/*
danielk19775865e3d2004-06-14 06:03:57 +00005583** Return the pathname of the directory that contains the database file.
5584*/
5585const char *sqlite3BtreeGetDirname(Btree *pBt){
5586 assert( pBt->pPager!=0 );
5587 return sqlite3pager_dirname(pBt->pPager);
5588}
5589
5590/*
5591** Return the pathname of the journal file for this database. The return
5592** value of this routine is the same regardless of whether the journal file
5593** has been created or not.
5594*/
5595const char *sqlite3BtreeGetJournalname(Btree *pBt){
5596 assert( pBt->pPager!=0 );
5597 return sqlite3pager_journalname(pBt->pPager);
5598}
5599
drhb7f91642004-10-31 02:22:47 +00005600#ifndef SQLITE_OMIT_VACUUM
danielk19775865e3d2004-06-14 06:03:57 +00005601/*
drhf7c57532003-04-25 13:22:51 +00005602** Copy the complete content of pBtFrom into pBtTo. A transaction
5603** must be active for both files.
5604**
5605** The size of file pBtFrom may be reduced by this operation.
drh43605152004-05-29 21:46:49 +00005606** If anything goes wrong, the transaction on pBtFrom is rolled back.
drh73509ee2003-04-06 20:44:45 +00005607*/
drh3aac2dd2004-04-26 14:10:20 +00005608int sqlite3BtreeCopyFile(Btree *pBtTo, Btree *pBtFrom){
drhf7c57532003-04-25 13:22:51 +00005609 int rc = SQLITE_OK;
drh2e6d11b2003-04-25 15:37:57 +00005610 Pgno i, nPage, nToPage;
drhf7c57532003-04-25 13:22:51 +00005611
danielk1977ee5741e2004-05-31 10:01:34 +00005612 if( pBtTo->inTrans!=TRANS_WRITE || pBtFrom->inTrans!=TRANS_WRITE ){
5613 return SQLITE_ERROR;
5614 }
drhf7c57532003-04-25 13:22:51 +00005615 if( pBtTo->pCursor ) return SQLITE_BUSY;
drha34b6762004-05-07 13:30:42 +00005616 nToPage = sqlite3pager_pagecount(pBtTo->pPager);
5617 nPage = sqlite3pager_pagecount(pBtFrom->pPager);
danielk1977369f27e2004-06-15 11:40:04 +00005618 for(i=1; rc==SQLITE_OK && i<=nPage; i++){
drhf7c57532003-04-25 13:22:51 +00005619 void *pPage;
drha34b6762004-05-07 13:30:42 +00005620 rc = sqlite3pager_get(pBtFrom->pPager, i, &pPage);
drhf7c57532003-04-25 13:22:51 +00005621 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00005622 rc = sqlite3pager_overwrite(pBtTo->pPager, i, pPage);
drh2e6d11b2003-04-25 15:37:57 +00005623 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00005624 sqlite3pager_unref(pPage);
drhf7c57532003-04-25 13:22:51 +00005625 }
drh2e6d11b2003-04-25 15:37:57 +00005626 for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
5627 void *pPage;
drha34b6762004-05-07 13:30:42 +00005628 rc = sqlite3pager_get(pBtTo->pPager, i, &pPage);
drh2e6d11b2003-04-25 15:37:57 +00005629 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00005630 rc = sqlite3pager_write(pPage);
5631 sqlite3pager_unref(pPage);
5632 sqlite3pager_dont_write(pBtTo->pPager, i);
drh2e6d11b2003-04-25 15:37:57 +00005633 }
5634 if( !rc && nPage<nToPage ){
drha34b6762004-05-07 13:30:42 +00005635 rc = sqlite3pager_truncate(pBtTo->pPager, nPage);
drh2e6d11b2003-04-25 15:37:57 +00005636 }
drhf7c57532003-04-25 13:22:51 +00005637 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00005638 sqlite3BtreeRollback(pBtTo);
drhf7c57532003-04-25 13:22:51 +00005639 }
5640 return rc;
drh73509ee2003-04-06 20:44:45 +00005641}
drhb7f91642004-10-31 02:22:47 +00005642#endif /* SQLITE_OMIT_VACUUM */
danielk19771d850a72004-05-31 08:26:49 +00005643
5644/*
5645** Return non-zero if a transaction is active.
5646*/
5647int sqlite3BtreeIsInTrans(Btree *pBt){
danielk1977ee5741e2004-05-31 10:01:34 +00005648 return (pBt && (pBt->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00005649}
5650
5651/*
5652** Return non-zero if a statement transaction is active.
5653*/
5654int sqlite3BtreeIsInStmt(Btree *pBt){
5655 return (pBt && pBt->inStmt);
5656}
danielk197713adf8a2004-06-03 16:08:41 +00005657
5658/*
5659** This call is a no-op if no write-transaction is currently active on pBt.
5660**
5661** Otherwise, sync the database file for the btree pBt. zMaster points to
5662** the name of a master journal file that should be written into the
5663** individual journal file, or is NULL, indicating no master journal file
5664** (single database transaction).
5665**
5666** When this is called, the master journal should already have been
5667** created, populated with this journal pointer and synced to disk.
5668**
5669** Once this is routine has returned, the only thing required to commit
5670** the write-transaction for this database file is to delete the journal.
5671*/
5672int sqlite3BtreeSync(Btree *pBt, const char *zMaster){
5673 if( pBt->inTrans==TRANS_WRITE ){
danielk1977687566d2004-11-02 12:56:41 +00005674#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977d761c0c2004-11-05 16:37:02 +00005675 Pgno nTrunc = 0;
danielk1977687566d2004-11-02 12:56:41 +00005676 if( pBt->autoVacuum ){
danielk1977d761c0c2004-11-05 16:37:02 +00005677 int rc = autoVacuumCommit(pBt, &nTrunc);
danielk1977687566d2004-11-02 12:56:41 +00005678 if( rc!=SQLITE_OK ) return rc;
5679 }
danielk1977d761c0c2004-11-05 16:37:02 +00005680 return sqlite3pager_sync(pBt->pPager, zMaster, nTrunc);
danielk1977687566d2004-11-02 12:56:41 +00005681#endif
danielk1977d761c0c2004-11-05 16:37:02 +00005682 return sqlite3pager_sync(pBt->pPager, zMaster, 0);
danielk197713adf8a2004-06-03 16:08:41 +00005683 }
5684 return SQLITE_OK;
5685}