blob: 87726ae2a3f1c98b31302abf0362e18a13d9c199 [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*************************************************************************
danielk197750f059b2005-03-29 02:54:03 +000012** $Id: btree.c,v 1.255 2005/03/29 02:54:03 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 */
drh057cd3a2005-02-15 16:23:02 +0000307#ifndef SQLITE_OMIT_AUTOVACUUM
308 u8 autoVacuum; /* True if database supports auto-vacuum */
309#endif
drha2fce642004-06-05 00:01:44 +0000310 u16 pageSize; /* Total number of bytes on a page */
drh887dc4c2004-10-22 16:22:57 +0000311 u16 psAligned; /* pageSize rounded up to a multiple of 8 */
drha2fce642004-06-05 00:01:44 +0000312 u16 usableSize; /* Number of usable bytes on each page */
drh6f11bef2004-05-13 01:12:56 +0000313 int maxLocal; /* Maximum local payload in non-LEAFDATA tables */
314 int minLocal; /* Minimum local payload in non-LEAFDATA tables */
315 int maxLeaf; /* Maximum local payload in a LEAFDATA table */
316 int minLeaf; /* Minimum local payload in a LEAFDATA table */
drhb8ef32c2005-03-14 02:01:49 +0000317 BusyHandler *pBusyHandler; /* Callback for when there is lock contention */
drha059ad02001-04-17 20:09:11 +0000318};
319typedef Btree Bt;
320
drh365d68f2001-05-11 11:02:46 +0000321/*
danielk1977ee5741e2004-05-31 10:01:34 +0000322** Btree.inTrans may take one of the following values.
323*/
324#define TRANS_NONE 0
325#define TRANS_READ 1
326#define TRANS_WRITE 2
327
328/*
drhfa1a98a2004-05-14 19:08:17 +0000329** An instance of the following structure is used to hold information
drh271efa52004-05-30 19:19:05 +0000330** about a cell. The parseCellPtr() function fills in this structure
drhab01f612004-05-22 02:55:23 +0000331** based on information extract from the raw disk page.
drhfa1a98a2004-05-14 19:08:17 +0000332*/
333typedef struct CellInfo CellInfo;
334struct CellInfo {
drh43605152004-05-29 21:46:49 +0000335 u8 *pCell; /* Pointer to the start of cell content */
drhfa1a98a2004-05-14 19:08:17 +0000336 i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
337 u32 nData; /* Number of bytes of data */
drh271efa52004-05-30 19:19:05 +0000338 u16 nHeader; /* Size of the cell content header in bytes */
drhfa1a98a2004-05-14 19:08:17 +0000339 u16 nLocal; /* Amount of payload held locally */
drhab01f612004-05-22 02:55:23 +0000340 u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
drh271efa52004-05-30 19:19:05 +0000341 u16 nSize; /* Size of the cell content on the main b-tree page */
drhfa1a98a2004-05-14 19:08:17 +0000342};
343
344/*
drh365d68f2001-05-11 11:02:46 +0000345** A cursor is a pointer to a particular entry in the BTree.
346** The entry is identified by its MemPage and the index in
drha34b6762004-05-07 13:30:42 +0000347** MemPage.aCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000348*/
drh72f82862001-05-24 21:06:34 +0000349struct BtCursor {
drh5e2f8b92001-05-28 00:41:15 +0000350 Btree *pBt; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000351 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drh3aac2dd2004-04-26 14:10:20 +0000352 int (*xCompare)(void*,int,const void*,int,const void*); /* Key comp func */
353 void *pArg; /* First arg to xCompare() */
drh8b2f49b2001-06-08 00:21:52 +0000354 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000355 MemPage *pPage; /* Page that contains the entry */
drh3aac2dd2004-04-26 14:10:20 +0000356 int idx; /* Index of the entry in pPage->aCell[] */
drhfa1a98a2004-05-14 19:08:17 +0000357 CellInfo info; /* A parse of the cell we are pointing at */
drhecdc7532001-09-23 02:35:53 +0000358 u8 wrFlag; /* True if writable */
drhc39e0002004-05-07 23:50:57 +0000359 u8 isValid; /* TRUE if points to a valid entry */
drh365d68f2001-05-11 11:02:46 +0000360};
drh7e3b0a02001-04-28 16:52:40 +0000361
drha059ad02001-04-17 20:09:11 +0000362/*
drh615ae552005-01-16 23:21:00 +0000363** The TRACE macro will print high-level status information about the
364** btree operation when the global variable sqlite3_btree_trace is
365** enabled.
366*/
367#if SQLITE_TEST
368# define TRACE(X) if( sqlite3_btree_trace )\
369 { sqlite3DebugPrintf X; fflush(stdout); }
370#else
371# define TRACE(X)
372#endif
373int sqlite3_btree_trace=0; /* True to enable tracing */
374
375/*
drh66cbd152004-09-01 16:12:25 +0000376** Forward declaration
377*/
378static int checkReadLocks(Btree*,Pgno,BtCursor*);
379
drh66cbd152004-09-01 16:12:25 +0000380/*
drhab01f612004-05-22 02:55:23 +0000381** Read or write a two- and four-byte big-endian integer values.
drh0d316a42002-08-11 20:10:47 +0000382*/
drh9e572e62004-04-23 23:43:10 +0000383static u32 get2byte(unsigned char *p){
384 return (p[0]<<8) | p[1];
drh0d316a42002-08-11 20:10:47 +0000385}
drh9e572e62004-04-23 23:43:10 +0000386static u32 get4byte(unsigned char *p){
387 return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
388}
drh9e572e62004-04-23 23:43:10 +0000389static void put2byte(unsigned char *p, u32 v){
390 p[0] = v>>8;
391 p[1] = v;
392}
393static void put4byte(unsigned char *p, u32 v){
394 p[0] = v>>24;
395 p[1] = v>>16;
396 p[2] = v>>8;
397 p[3] = v;
398}
drh6f11bef2004-05-13 01:12:56 +0000399
drh9e572e62004-04-23 23:43:10 +0000400/*
drhab01f612004-05-22 02:55:23 +0000401** Routines to read and write variable-length integers. These used to
402** be defined locally, but now we use the varint routines in the util.c
403** file.
drh9e572e62004-04-23 23:43:10 +0000404*/
drh6d2fb152004-05-14 16:50:06 +0000405#define getVarint sqlite3GetVarint
406#define getVarint32 sqlite3GetVarint32
407#define putVarint sqlite3PutVarint
drh0d316a42002-08-11 20:10:47 +0000408
danielk1977599fcba2004-11-08 07:13:13 +0000409/* The database page the PENDING_BYTE occupies. This page is never used.
410** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
411** should possibly be consolidated (presumably in pager.h).
412*/
413#define PENDING_BYTE_PAGE(pBt) ((PENDING_BYTE/(pBt)->pageSize)+1)
danielk1977afcdd022004-10-31 16:25:42 +0000414
danielk1977599fcba2004-11-08 07:13:13 +0000415#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000416/*
drh42cac6d2004-11-20 20:31:11 +0000417** These macros define the location of the pointer-map entry for a
418** database page. The first argument to each is the number of usable
419** bytes on each page of the database (often 1024). The second is the
420** page number to look up in the pointer map.
danielk1977afcdd022004-10-31 16:25:42 +0000421**
422** PTRMAP_PAGENO returns the database page number of the pointer-map
423** page that stores the required pointer. PTRMAP_PTROFFSET returns
424** the offset of the requested map entry.
425**
426** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
427** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
danielk1977599fcba2004-11-08 07:13:13 +0000428** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
429** this test.
danielk1977afcdd022004-10-31 16:25:42 +0000430*/
431#define PTRMAP_PAGENO(pgsz, pgno) (((pgno-2)/(pgsz/5+1))*(pgsz/5+1)+2)
432#define PTRMAP_PTROFFSET(pgsz, pgno) (((pgno-2)%(pgsz/5+1)-1)*5)
danielk1977a19df672004-11-03 11:37:07 +0000433#define PTRMAP_ISPAGE(pgsz, pgno) (PTRMAP_PAGENO(pgsz,pgno)==pgno)
434
danielk1977afcdd022004-10-31 16:25:42 +0000435/*
drh615ae552005-01-16 23:21:00 +0000436** The pointer map is a lookup table that identifies the parent page for
437** each child page in the database file. The parent page is the page that
438** contains a pointer to the child. Every page in the database contains
439** 0 or 1 parent pages. (In this context 'database page' refers
440** to any page that is not part of the pointer map itself.) Each pointer map
441** entry consists of a single byte 'type' and a 4 byte parent page number.
442** The PTRMAP_XXX identifiers below are the valid types.
443**
444** The purpose of the pointer map is to facility moving pages from one
445** position in the file to another as part of autovacuum. When a page
446** is moved, the pointer in its parent must be updated to point to the
447** new location. The pointer map is used to locate the parent page quickly.
danielk1977afcdd022004-10-31 16:25:42 +0000448**
danielk1977687566d2004-11-02 12:56:41 +0000449** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
450** used in this case.
danielk1977afcdd022004-10-31 16:25:42 +0000451**
danielk1977687566d2004-11-02 12:56:41 +0000452** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
453** is not used in this case.
454**
455** PTRMAP_OVERFLOW1: The database page is the first page in a list of
456** overflow pages. The page number identifies the page that
457** contains the cell with a pointer to this overflow page.
458**
459** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
460** overflow pages. The page-number identifies the previous
461** page in the overflow page list.
462**
463** PTRMAP_BTREE: The database page is a non-root btree page. The page number
464** identifies the parent page in the btree.
danielk1977afcdd022004-10-31 16:25:42 +0000465*/
danielk1977687566d2004-11-02 12:56:41 +0000466#define PTRMAP_ROOTPAGE 1
467#define PTRMAP_FREEPAGE 2
468#define PTRMAP_OVERFLOW1 3
469#define PTRMAP_OVERFLOW2 4
470#define PTRMAP_BTREE 5
danielk1977afcdd022004-10-31 16:25:42 +0000471
472/*
473** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000474**
475** This routine updates the pointer map entry for page number 'key'
476** so that it maps to type 'eType' and parent page number 'pgno'.
477** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000478*/
drh615ae552005-01-16 23:21:00 +0000479static int ptrmapPut(Btree *pBt, Pgno key, u8 eType, Pgno parent){
danielk1977afcdd022004-10-31 16:25:42 +0000480 u8 *pPtrmap; /* The pointer map page */
481 Pgno iPtrmap; /* The pointer map page number */
482 int offset; /* Offset in pointer map page */
483 int rc;
484
danielk1977ac11ee62005-01-15 12:45:51 +0000485 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000486 if( key==0 ){
487 return SQLITE_CORRUPT;
488 }
drh42cac6d2004-11-20 20:31:11 +0000489 iPtrmap = PTRMAP_PAGENO(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000490 rc = sqlite3pager_get(pBt->pPager, iPtrmap, (void **)&pPtrmap);
danielk1977687566d2004-11-02 12:56:41 +0000491 if( rc!=SQLITE_OK ){
danielk1977afcdd022004-10-31 16:25:42 +0000492 return rc;
493 }
drh42cac6d2004-11-20 20:31:11 +0000494 offset = PTRMAP_PTROFFSET(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000495
drh615ae552005-01-16 23:21:00 +0000496 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
497 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
danielk1977afcdd022004-10-31 16:25:42 +0000498 rc = sqlite3pager_write(pPtrmap);
danielk19775558a8a2005-01-17 07:53:44 +0000499 if( rc==SQLITE_OK ){
500 pPtrmap[offset] = eType;
501 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000502 }
danielk1977afcdd022004-10-31 16:25:42 +0000503 }
504
505 sqlite3pager_unref(pPtrmap);
danielk19775558a8a2005-01-17 07:53:44 +0000506 return rc;
danielk1977afcdd022004-10-31 16:25:42 +0000507}
508
509/*
510** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000511**
512** This routine retrieves the pointer map entry for page 'key', writing
513** the type and parent page number to *pEType and *pPgno respectively.
514** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000515*/
516static int ptrmapGet(Btree *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
517 int iPtrmap; /* Pointer map page index */
518 u8 *pPtrmap; /* Pointer map page data */
519 int offset; /* Offset of entry in pointer map */
520 int rc;
521
drh42cac6d2004-11-20 20:31:11 +0000522 iPtrmap = PTRMAP_PAGENO(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000523 rc = sqlite3pager_get(pBt->pPager, iPtrmap, (void **)&pPtrmap);
524 if( rc!=0 ){
525 return rc;
526 }
527
drh42cac6d2004-11-20 20:31:11 +0000528 offset = PTRMAP_PTROFFSET(pBt->usableSize, key);
danielk1977687566d2004-11-02 12:56:41 +0000529 if( pEType ) *pEType = pPtrmap[offset];
530 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000531
532 sqlite3pager_unref(pPtrmap);
danielk1977fdb7cdb2005-01-17 02:12:18 +0000533 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT;
danielk1977afcdd022004-10-31 16:25:42 +0000534 return SQLITE_OK;
535}
536
537#endif /* SQLITE_OMIT_AUTOVACUUM */
538
drh0d316a42002-08-11 20:10:47 +0000539/*
drh271efa52004-05-30 19:19:05 +0000540** Given a btree page and a cell index (0 means the first cell on
541** the page, 1 means the second cell, and so forth) return a pointer
542** to the cell content.
543**
544** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000545*/
drh43605152004-05-29 21:46:49 +0000546static u8 *findCell(MemPage *pPage, int iCell){
547 u8 *data = pPage->aData;
548 assert( iCell>=0 );
549 assert( iCell<get2byte(&data[pPage->hdrOffset+3]) );
550 return data + get2byte(&data[pPage->cellOffset+2*iCell]);
551}
552
553/*
554** This a more complex version of findCell() that works for
555** pages that do contain overflow cells. See insert
556*/
557static u8 *findOverflowCell(MemPage *pPage, int iCell){
558 int i;
559 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000560 int k;
561 struct _OvflCell *pOvfl;
562 pOvfl = &pPage->aOvfl[i];
563 k = pOvfl->idx;
564 if( k<=iCell ){
565 if( k==iCell ){
566 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000567 }
568 iCell--;
569 }
570 }
571 return findCell(pPage, iCell);
572}
573
574/*
575** Parse a cell content block and fill in the CellInfo structure. There
576** are two versions of this function. parseCell() takes a cell index
577** as the second argument and parseCellPtr() takes a pointer to the
578** body of the cell as its second argument.
579*/
580static void parseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000581 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000582 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000583 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000584){
drh271efa52004-05-30 19:19:05 +0000585 int n; /* Number bytes in cell content header */
586 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000587
588 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000589 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000590 n = pPage->childPtrSize;
591 assert( n==4-4*pPage->leaf );
drh8b18dd42004-05-12 19:18:15 +0000592 if( pPage->hasData ){
drh271efa52004-05-30 19:19:05 +0000593 n += getVarint32(&pCell[n], &nPayload);
drh8b18dd42004-05-12 19:18:15 +0000594 }else{
drh271efa52004-05-30 19:19:05 +0000595 nPayload = 0;
drh3aac2dd2004-04-26 14:10:20 +0000596 }
danielk1977e0d4b062004-06-28 01:11:46 +0000597 n += getVarint(&pCell[n], (u64 *)&pInfo->nKey);
drh6f11bef2004-05-13 01:12:56 +0000598 pInfo->nHeader = n;
drh271efa52004-05-30 19:19:05 +0000599 pInfo->nData = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000600 if( !pPage->intKey ){
601 nPayload += pInfo->nKey;
602 }
drh271efa52004-05-30 19:19:05 +0000603 if( nPayload<=pPage->maxLocal ){
604 /* This is the (easy) common case where the entire payload fits
605 ** on the local page. No overflow is required.
606 */
607 int nSize; /* Total size of cell content in bytes */
drh6f11bef2004-05-13 01:12:56 +0000608 pInfo->nLocal = nPayload;
609 pInfo->iOverflow = 0;
drh271efa52004-05-30 19:19:05 +0000610 nSize = nPayload + n;
611 if( nSize<4 ){
612 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000613 }
drh271efa52004-05-30 19:19:05 +0000614 pInfo->nSize = nSize;
drh6f11bef2004-05-13 01:12:56 +0000615 }else{
drh271efa52004-05-30 19:19:05 +0000616 /* If the payload will not fit completely on the local page, we have
617 ** to decide how much to store locally and how much to spill onto
618 ** overflow pages. The strategy is to minimize the amount of unused
619 ** space on overflow pages while keeping the amount of local storage
620 ** in between minLocal and maxLocal.
621 **
622 ** Warning: changing the way overflow payload is distributed in any
623 ** way will result in an incompatible file format.
624 */
625 int minLocal; /* Minimum amount of payload held locally */
626 int maxLocal; /* Maximum amount of payload held locally */
627 int surplus; /* Overflow payload available for local storage */
628
629 minLocal = pPage->minLocal;
630 maxLocal = pPage->maxLocal;
631 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000632 if( surplus <= maxLocal ){
633 pInfo->nLocal = surplus;
634 }else{
635 pInfo->nLocal = minLocal;
636 }
637 pInfo->iOverflow = pInfo->nLocal + n;
638 pInfo->nSize = pInfo->iOverflow + 4;
639 }
drh3aac2dd2004-04-26 14:10:20 +0000640}
drh43605152004-05-29 21:46:49 +0000641static void parseCell(
642 MemPage *pPage, /* Page containing the cell */
643 int iCell, /* The cell index. First cell is 0 */
644 CellInfo *pInfo /* Fill in this structure */
645){
646 parseCellPtr(pPage, findCell(pPage, iCell), pInfo);
647}
drh3aac2dd2004-04-26 14:10:20 +0000648
649/*
drh43605152004-05-29 21:46:49 +0000650** Compute the total number of bytes that a Cell needs in the cell
651** data area of the btree-page. The return number includes the cell
652** data header and the local payload, but not any overflow page or
653** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000654*/
danielk1977bc6ada42004-06-30 08:20:16 +0000655#ifndef NDEBUG
drh43605152004-05-29 21:46:49 +0000656static int cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000657 CellInfo info;
drh43605152004-05-29 21:46:49 +0000658 parseCell(pPage, iCell, &info);
659 return info.nSize;
660}
danielk1977bc6ada42004-06-30 08:20:16 +0000661#endif
drh43605152004-05-29 21:46:49 +0000662static int cellSizePtr(MemPage *pPage, u8 *pCell){
663 CellInfo info;
664 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000665 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000666}
667
danielk197779a40da2005-01-16 08:00:01 +0000668#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +0000669/*
danielk197726836652005-01-17 01:33:13 +0000670** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +0000671** to an overflow page, insert an entry into the pointer-map
672** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +0000673*/
danielk197726836652005-01-17 01:33:13 +0000674static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
danielk197779a40da2005-01-16 08:00:01 +0000675 if( pCell ){
676 CellInfo info;
677 parseCellPtr(pPage, pCell, &info);
678 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
679 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
680 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
681 }
danielk1977ac11ee62005-01-15 12:45:51 +0000682 }
danielk197779a40da2005-01-16 08:00:01 +0000683 return SQLITE_OK;
danielk1977ac11ee62005-01-15 12:45:51 +0000684}
danielk197726836652005-01-17 01:33:13 +0000685/*
686** If the cell with index iCell on page pPage contains a pointer
687** to an overflow page, insert an entry into the pointer-map
688** for the overflow page.
689*/
690static int ptrmapPutOvfl(MemPage *pPage, int iCell){
691 u8 *pCell;
692 pCell = findOverflowCell(pPage, iCell);
693 return ptrmapPutOvflPtr(pPage, pCell);
694}
danielk197779a40da2005-01-16 08:00:01 +0000695#endif
696
danielk1977ac11ee62005-01-15 12:45:51 +0000697
698/*
drhda200cc2004-05-09 11:51:38 +0000699** Do sanity checking on a page. Throw an exception if anything is
700** not right.
701**
702** This routine is used for internal error checking only. It is omitted
703** from most builds.
704*/
705#if defined(BTREE_DEBUG) && !defined(NDEBUG) && 0
706static void _pageIntegrity(MemPage *pPage){
drhb6f41482004-05-14 01:58:11 +0000707 int usableSize;
drhda200cc2004-05-09 11:51:38 +0000708 u8 *data;
drh43605152004-05-29 21:46:49 +0000709 int i, j, idx, c, pc, hdr, nFree;
710 int cellOffset;
711 int nCell, cellLimit;
drh2e38c322004-09-03 18:38:44 +0000712 u8 *used;
drhda200cc2004-05-09 11:51:38 +0000713
drh2e38c322004-09-03 18:38:44 +0000714 used = sqliteMallocRaw( pPage->pBt->pageSize );
715 if( used==0 ) return;
drhb6f41482004-05-14 01:58:11 +0000716 usableSize = pPage->pBt->usableSize;
drh887dc4c2004-10-22 16:22:57 +0000717 assert( pPage->aData==&((unsigned char*)pPage)[-pPage->pBt->psAligned] );
drhda200cc2004-05-09 11:51:38 +0000718 hdr = pPage->hdrOffset;
719 assert( hdr==(pPage->pgno==1 ? 100 : 0) );
720 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
721 c = pPage->aData[hdr];
722 if( pPage->isInit ){
723 assert( pPage->leaf == ((c & PTF_LEAF)!=0) );
724 assert( pPage->zeroData == ((c & PTF_ZERODATA)!=0) );
drh8b18dd42004-05-12 19:18:15 +0000725 assert( pPage->leafData == ((c & PTF_LEAFDATA)!=0) );
726 assert( pPage->intKey == ((c & (PTF_INTKEY|PTF_LEAFDATA))!=0) );
727 assert( pPage->hasData ==
728 !(pPage->zeroData || (!pPage->leaf && pPage->leafData)) );
drh43605152004-05-29 21:46:49 +0000729 assert( pPage->cellOffset==pPage->hdrOffset+12-4*pPage->leaf );
730 assert( pPage->nCell = get2byte(&pPage->aData[hdr+3]) );
drhda200cc2004-05-09 11:51:38 +0000731 }
732 data = pPage->aData;
drhb6f41482004-05-14 01:58:11 +0000733 memset(used, 0, usableSize);
drhda200cc2004-05-09 11:51:38 +0000734 for(i=0; i<hdr+10-pPage->leaf*4; i++) used[i] = 1;
735 nFree = 0;
736 pc = get2byte(&data[hdr+1]);
737 while( pc ){
738 int size;
drhb6f41482004-05-14 01:58:11 +0000739 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +0000740 size = get2byte(&data[pc+2]);
drhb6f41482004-05-14 01:58:11 +0000741 assert( pc+size<=usableSize );
drhda200cc2004-05-09 11:51:38 +0000742 nFree += size;
743 for(i=pc; i<pc+size; i++){
744 assert( used[i]==0 );
745 used[i] = 1;
746 }
747 pc = get2byte(&data[pc]);
748 }
drhda200cc2004-05-09 11:51:38 +0000749 idx = 0;
drh43605152004-05-29 21:46:49 +0000750 nCell = get2byte(&data[hdr+3]);
751 cellLimit = get2byte(&data[hdr+5]);
752 assert( pPage->isInit==0
753 || pPage->nFree==nFree+data[hdr+7]+cellLimit-(cellOffset+2*nCell) );
754 cellOffset = pPage->cellOffset;
755 for(i=0; i<nCell; i++){
drhda200cc2004-05-09 11:51:38 +0000756 int size;
drh43605152004-05-29 21:46:49 +0000757 pc = get2byte(&data[cellOffset+2*i]);
drhb6f41482004-05-14 01:58:11 +0000758 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +0000759 size = cellSize(pPage, &data[pc]);
drhb6f41482004-05-14 01:58:11 +0000760 assert( pc+size<=usableSize );
drh43605152004-05-29 21:46:49 +0000761 for(j=pc; j<pc+size; j++){
762 assert( used[j]==0 );
763 used[j] = 1;
drhda200cc2004-05-09 11:51:38 +0000764 }
drhda200cc2004-05-09 11:51:38 +0000765 }
drh43605152004-05-29 21:46:49 +0000766 for(i=cellOffset+2*nCell; i<cellimit; i++){
767 assert( used[i]==0 );
768 used[i] = 1;
769 }
drhda200cc2004-05-09 11:51:38 +0000770 nFree = 0;
drhb6f41482004-05-14 01:58:11 +0000771 for(i=0; i<usableSize; i++){
drhda200cc2004-05-09 11:51:38 +0000772 assert( used[i]<=1 );
773 if( used[i]==0 ) nFree++;
774 }
drh43605152004-05-29 21:46:49 +0000775 assert( nFree==data[hdr+7] );
drh2e38c322004-09-03 18:38:44 +0000776 sqliteFree(used);
drhda200cc2004-05-09 11:51:38 +0000777}
778#define pageIntegrity(X) _pageIntegrity(X)
779#else
780# define pageIntegrity(X)
781#endif
782
783/*
drh72f82862001-05-24 21:06:34 +0000784** Defragment the page given. All Cells are moved to the
785** beginning of the page and all free space is collected
786** into one big FreeBlk at the end of the page.
drh365d68f2001-05-11 11:02:46 +0000787*/
drh2e38c322004-09-03 18:38:44 +0000788static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000789 int i; /* Loop counter */
790 int pc; /* Address of a i-th cell */
791 int addr; /* Offset of first byte after cell pointer array */
792 int hdr; /* Offset to the page header */
793 int size; /* Size of a cell */
794 int usableSize; /* Number of usable bytes on a page */
795 int cellOffset; /* Offset to the cell pointer array */
796 int brk; /* Offset to the cell content area */
797 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +0000798 unsigned char *data; /* The page data */
799 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +0000800
drha34b6762004-05-07 13:30:42 +0000801 assert( sqlite3pager_iswriteable(pPage->aData) );
drh9e572e62004-04-23 23:43:10 +0000802 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +0000803 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000804 assert( pPage->nOverflow==0 );
drh2e38c322004-09-03 18:38:44 +0000805 temp = sqliteMalloc( pPage->pBt->pageSize );
806 if( temp==0 ) return SQLITE_NOMEM;
drh43605152004-05-29 21:46:49 +0000807 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000808 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000809 cellOffset = pPage->cellOffset;
810 nCell = pPage->nCell;
811 assert( nCell==get2byte(&data[hdr+3]) );
812 usableSize = pPage->pBt->usableSize;
813 brk = get2byte(&data[hdr+5]);
814 memcpy(&temp[brk], &data[brk], usableSize - brk);
815 brk = usableSize;
816 for(i=0; i<nCell; i++){
817 u8 *pAddr; /* The i-th cell pointer */
818 pAddr = &data[cellOffset + i*2];
819 pc = get2byte(pAddr);
820 assert( pc<pPage->pBt->usableSize );
821 size = cellSizePtr(pPage, &temp[pc]);
822 brk -= size;
823 memcpy(&data[brk], &temp[pc], size);
824 put2byte(pAddr, brk);
drh2af926b2001-05-15 00:39:25 +0000825 }
drh43605152004-05-29 21:46:49 +0000826 assert( brk>=cellOffset+2*nCell );
827 put2byte(&data[hdr+5], brk);
828 data[hdr+1] = 0;
829 data[hdr+2] = 0;
830 data[hdr+7] = 0;
831 addr = cellOffset+2*nCell;
832 memset(&data[addr], 0, brk-addr);
drh2e38c322004-09-03 18:38:44 +0000833 sqliteFree(temp);
834 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +0000835}
836
drha059ad02001-04-17 20:09:11 +0000837/*
drh43605152004-05-29 21:46:49 +0000838** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +0000839**
drh9e572e62004-04-23 23:43:10 +0000840** Return the index into pPage->aData[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000841** the new allocation. Or return 0 if there is not enough free
842** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000843**
drh72f82862001-05-24 21:06:34 +0000844** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000845** nBytes of contiguous free space, then this routine automatically
846** calls defragementPage() to consolidate all free space before
847** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000848*/
drh9e572e62004-04-23 23:43:10 +0000849static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +0000850 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +0000851 int size;
drh24cd67e2004-05-10 16:18:47 +0000852 int nFrag;
drh43605152004-05-29 21:46:49 +0000853 int top;
854 int nCell;
855 int cellOffset;
drh9e572e62004-04-23 23:43:10 +0000856 unsigned char *data;
drh43605152004-05-29 21:46:49 +0000857
drh9e572e62004-04-23 23:43:10 +0000858 data = pPage->aData;
drha34b6762004-05-07 13:30:42 +0000859 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +0000860 assert( pPage->pBt );
861 if( nByte<4 ) nByte = 4;
drh43605152004-05-29 21:46:49 +0000862 if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
863 pPage->nFree -= nByte;
drh9e572e62004-04-23 23:43:10 +0000864 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000865
866 nFrag = data[hdr+7];
867 if( nFrag<60 ){
868 /* Search the freelist looking for a slot big enough to satisfy the
869 ** space request. */
870 addr = hdr+1;
871 while( (pc = get2byte(&data[addr]))>0 ){
872 size = get2byte(&data[pc+2]);
873 if( size>=nByte ){
874 if( size<nByte+4 ){
875 memcpy(&data[addr], &data[pc], 2);
876 data[hdr+7] = nFrag + size - nByte;
877 return pc;
878 }else{
879 put2byte(&data[pc+2], size-nByte);
880 return pc + size - nByte;
881 }
882 }
883 addr = pc;
drh9e572e62004-04-23 23:43:10 +0000884 }
885 }
drh43605152004-05-29 21:46:49 +0000886
887 /* Allocate memory from the gap in between the cell pointer array
888 ** and the cell content area.
889 */
890 top = get2byte(&data[hdr+5]);
891 nCell = get2byte(&data[hdr+3]);
892 cellOffset = pPage->cellOffset;
893 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
drh2e38c322004-09-03 18:38:44 +0000894 if( defragmentPage(pPage) ) return 0;
drh43605152004-05-29 21:46:49 +0000895 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +0000896 }
drh43605152004-05-29 21:46:49 +0000897 top -= nByte;
898 assert( cellOffset + 2*nCell <= top );
899 put2byte(&data[hdr+5], top);
900 return top;
drh7e3b0a02001-04-28 16:52:40 +0000901}
902
903/*
drh9e572e62004-04-23 23:43:10 +0000904** Return a section of the pPage->aData to the freelist.
905** The first byte of the new free block is pPage->aDisk[start]
906** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +0000907**
908** Most of the effort here is involved in coalesing adjacent
909** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000910*/
drh9e572e62004-04-23 23:43:10 +0000911static void freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +0000912 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +0000913 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +0000914
drh9e572e62004-04-23 23:43:10 +0000915 assert( pPage->pBt!=0 );
drha34b6762004-05-07 13:30:42 +0000916 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +0000917 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +0000918 assert( (start + size)<=pPage->pBt->usableSize );
drh9e572e62004-04-23 23:43:10 +0000919 if( size<4 ) size = 4;
920
921 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +0000922 hdr = pPage->hdrOffset;
923 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +0000924 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +0000925 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000926 assert( pbegin>addr );
927 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +0000928 }
drhb6f41482004-05-14 01:58:11 +0000929 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000930 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +0000931 put2byte(&data[addr], start);
932 put2byte(&data[start], pbegin);
933 put2byte(&data[start+2], size);
drh2af926b2001-05-15 00:39:25 +0000934 pPage->nFree += size;
drh9e572e62004-04-23 23:43:10 +0000935
936 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +0000937 addr = pPage->hdrOffset + 1;
938 while( (pbegin = get2byte(&data[addr]))>0 ){
drh9e572e62004-04-23 23:43:10 +0000939 int pnext, psize;
drh3aac2dd2004-04-26 14:10:20 +0000940 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +0000941 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +0000942 pnext = get2byte(&data[pbegin]);
943 psize = get2byte(&data[pbegin+2]);
944 if( pbegin + psize + 3 >= pnext && pnext>0 ){
945 int frag = pnext - (pbegin+psize);
drh43605152004-05-29 21:46:49 +0000946 assert( frag<=data[pPage->hdrOffset+7] );
947 data[pPage->hdrOffset+7] -= frag;
drh9e572e62004-04-23 23:43:10 +0000948 put2byte(&data[pbegin], get2byte(&data[pnext]));
949 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
950 }else{
drh3aac2dd2004-04-26 14:10:20 +0000951 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +0000952 }
953 }
drh7e3b0a02001-04-28 16:52:40 +0000954
drh43605152004-05-29 21:46:49 +0000955 /* If the cell content area begins with a freeblock, remove it. */
956 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
957 int top;
958 pbegin = get2byte(&data[hdr+1]);
959 memcpy(&data[hdr+1], &data[pbegin], 2);
960 top = get2byte(&data[hdr+5]);
961 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
drh4b70f112004-05-02 21:12:19 +0000962 }
drh4b70f112004-05-02 21:12:19 +0000963}
964
965/*
drh271efa52004-05-30 19:19:05 +0000966** Decode the flags byte (the first byte of the header) for a page
967** and initialize fields of the MemPage structure accordingly.
968*/
969static void decodeFlags(MemPage *pPage, int flagByte){
970 Btree *pBt; /* A copy of pPage->pBt */
971
972 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
973 pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
974 pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
975 pPage->leaf = (flagByte & PTF_LEAF)!=0;
976 pPage->childPtrSize = 4*(pPage->leaf==0);
977 pBt = pPage->pBt;
978 if( flagByte & PTF_LEAFDATA ){
979 pPage->leafData = 1;
980 pPage->maxLocal = pBt->maxLeaf;
981 pPage->minLocal = pBt->minLeaf;
982 }else{
983 pPage->leafData = 0;
984 pPage->maxLocal = pBt->maxLocal;
985 pPage->minLocal = pBt->minLocal;
986 }
987 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
988}
989
990/*
drh7e3b0a02001-04-28 16:52:40 +0000991** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000992**
drhbd03cae2001-06-02 02:40:57 +0000993** The pParent parameter must be a pointer to the MemPage which
drh9e572e62004-04-23 23:43:10 +0000994** is the parent of the page being initialized. The root of a
995** BTree has no parent and so for that page, pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000996**
drh72f82862001-05-24 21:06:34 +0000997** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +0000998** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +0000999** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1000** guarantee that the page is well-formed. It only shows that
1001** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001002*/
drh9e572e62004-04-23 23:43:10 +00001003static int initPage(
drh3aac2dd2004-04-26 14:10:20 +00001004 MemPage *pPage, /* The page to be initialized */
drh9e572e62004-04-23 23:43:10 +00001005 MemPage *pParent /* The parent. Might be NULL */
1006){
drh271efa52004-05-30 19:19:05 +00001007 int pc; /* Address of a freeblock within pPage->aData[] */
drh271efa52004-05-30 19:19:05 +00001008 int hdr; /* Offset to beginning of page header */
1009 u8 *data; /* Equal to pPage->aData */
drh2e38c322004-09-03 18:38:44 +00001010 Btree *pBt; /* The main btree structure */
drh271efa52004-05-30 19:19:05 +00001011 int usableSize; /* Amount of usable space on each page */
1012 int cellOffset; /* Offset from start of page to first cell pointer */
1013 int nFree; /* Number of unused bytes on the page */
1014 int top; /* First byte of the cell content area */
drh2af926b2001-05-15 00:39:25 +00001015
drh2e38c322004-09-03 18:38:44 +00001016 pBt = pPage->pBt;
1017 assert( pBt!=0 );
1018 assert( pParent==0 || pParent->pBt==pBt );
drha34b6762004-05-07 13:30:42 +00001019 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
drh887dc4c2004-10-22 16:22:57 +00001020 assert( pPage->aData == &((unsigned char*)pPage)[-pBt->psAligned] );
drhee696e22004-08-30 16:52:17 +00001021 if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
1022 /* The parent page should never change unless the file is corrupt */
1023 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1024 }
drh10617cd2004-05-14 15:27:27 +00001025 if( pPage->isInit ) return SQLITE_OK;
drhda200cc2004-05-09 11:51:38 +00001026 if( pPage->pParent==0 && pParent!=0 ){
1027 pPage->pParent = pParent;
drha34b6762004-05-07 13:30:42 +00001028 sqlite3pager_ref(pParent->aData);
drh5e2f8b92001-05-28 00:41:15 +00001029 }
drhde647132004-05-07 17:57:49 +00001030 hdr = pPage->hdrOffset;
drha34b6762004-05-07 13:30:42 +00001031 data = pPage->aData;
drh271efa52004-05-30 19:19:05 +00001032 decodeFlags(pPage, data[hdr]);
drh43605152004-05-29 21:46:49 +00001033 pPage->nOverflow = 0;
drhc8629a12004-05-08 20:07:40 +00001034 pPage->idxShift = 0;
drh2e38c322004-09-03 18:38:44 +00001035 usableSize = pBt->usableSize;
drh43605152004-05-29 21:46:49 +00001036 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
1037 top = get2byte(&data[hdr+5]);
1038 pPage->nCell = get2byte(&data[hdr+3]);
drh2e38c322004-09-03 18:38:44 +00001039 if( pPage->nCell>MX_CELL(pBt) ){
drhee696e22004-08-30 16:52:17 +00001040 /* To many cells for a single page. The page must be corrupt */
1041 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1042 }
1043 if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
1044 /* All pages must have at least one cell, except for root pages */
1045 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1046 }
drh9e572e62004-04-23 23:43:10 +00001047
1048 /* Compute the total free space on the page */
drh9e572e62004-04-23 23:43:10 +00001049 pc = get2byte(&data[hdr+1]);
drh43605152004-05-29 21:46:49 +00001050 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
drh9e572e62004-04-23 23:43:10 +00001051 while( pc>0 ){
1052 int next, size;
drhee696e22004-08-30 16:52:17 +00001053 if( pc>usableSize-4 ){
1054 /* Free block is off the page */
1055 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1056 }
drh9e572e62004-04-23 23:43:10 +00001057 next = get2byte(&data[pc]);
1058 size = get2byte(&data[pc+2]);
drhee696e22004-08-30 16:52:17 +00001059 if( next>0 && next<=pc+size+3 ){
1060 /* Free blocks must be in accending order */
1061 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1062 }
drh3add3672004-05-15 00:29:24 +00001063 nFree += size;
drh9e572e62004-04-23 23:43:10 +00001064 pc = next;
1065 }
drh3add3672004-05-15 00:29:24 +00001066 pPage->nFree = nFree;
drhee696e22004-08-30 16:52:17 +00001067 if( nFree>=usableSize ){
1068 /* Free space cannot exceed total page size */
1069 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1070 }
drh9e572e62004-04-23 23:43:10 +00001071
drhde647132004-05-07 17:57:49 +00001072 pPage->isInit = 1;
drhda200cc2004-05-09 11:51:38 +00001073 pageIntegrity(pPage);
drh9e572e62004-04-23 23:43:10 +00001074 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001075}
1076
1077/*
drh8b2f49b2001-06-08 00:21:52 +00001078** Set up a raw page so that it looks like a database page holding
1079** no entries.
drhbd03cae2001-06-02 02:40:57 +00001080*/
drh9e572e62004-04-23 23:43:10 +00001081static void zeroPage(MemPage *pPage, int flags){
1082 unsigned char *data = pPage->aData;
1083 Btree *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00001084 int hdr = pPage->hdrOffset;
drh9e572e62004-04-23 23:43:10 +00001085 int first;
1086
drhda200cc2004-05-09 11:51:38 +00001087 assert( sqlite3pager_pagenumber(data)==pPage->pgno );
drh887dc4c2004-10-22 16:22:57 +00001088 assert( &data[pBt->psAligned] == (unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +00001089 assert( sqlite3pager_iswriteable(data) );
drhb6f41482004-05-14 01:58:11 +00001090 memset(&data[hdr], 0, pBt->usableSize - hdr);
drh9e572e62004-04-23 23:43:10 +00001091 data[hdr] = flags;
drh43605152004-05-29 21:46:49 +00001092 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
1093 memset(&data[hdr+1], 0, 4);
1094 data[hdr+7] = 0;
1095 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +00001096 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +00001097 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +00001098 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +00001099 pPage->cellOffset = first;
1100 pPage->nOverflow = 0;
drhda200cc2004-05-09 11:51:38 +00001101 pPage->idxShift = 0;
drh43605152004-05-29 21:46:49 +00001102 pPage->nCell = 0;
drhda200cc2004-05-09 11:51:38 +00001103 pPage->isInit = 1;
1104 pageIntegrity(pPage);
drhbd03cae2001-06-02 02:40:57 +00001105}
1106
1107/*
drh3aac2dd2004-04-26 14:10:20 +00001108** Get a page from the pager. Initialize the MemPage.pBt and
1109** MemPage.aData elements if needed.
1110*/
1111static int getPage(Btree *pBt, Pgno pgno, MemPage **ppPage){
1112 int rc;
1113 unsigned char *aData;
1114 MemPage *pPage;
drha34b6762004-05-07 13:30:42 +00001115 rc = sqlite3pager_get(pBt->pPager, pgno, (void**)&aData);
drh3aac2dd2004-04-26 14:10:20 +00001116 if( rc ) return rc;
drh887dc4c2004-10-22 16:22:57 +00001117 pPage = (MemPage*)&aData[pBt->psAligned];
drh3aac2dd2004-04-26 14:10:20 +00001118 pPage->aData = aData;
1119 pPage->pBt = pBt;
1120 pPage->pgno = pgno;
drhde647132004-05-07 17:57:49 +00001121 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
drh3aac2dd2004-04-26 14:10:20 +00001122 *ppPage = pPage;
1123 return SQLITE_OK;
1124}
1125
1126/*
drhde647132004-05-07 17:57:49 +00001127** Get a page from the pager and initialize it. This routine
1128** is just a convenience wrapper around separate calls to
1129** getPage() and initPage().
1130*/
1131static int getAndInitPage(
1132 Btree *pBt, /* The database file */
1133 Pgno pgno, /* Number of the page to get */
1134 MemPage **ppPage, /* Write the page pointer here */
1135 MemPage *pParent /* Parent of the page */
1136){
1137 int rc;
drhee696e22004-08-30 16:52:17 +00001138 if( pgno==0 ){
1139 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1140 }
drhde647132004-05-07 17:57:49 +00001141 rc = getPage(pBt, pgno, ppPage);
drh10617cd2004-05-14 15:27:27 +00001142 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
drhde647132004-05-07 17:57:49 +00001143 rc = initPage(*ppPage, pParent);
1144 }
1145 return rc;
1146}
1147
1148/*
drh3aac2dd2004-04-26 14:10:20 +00001149** Release a MemPage. This should be called once for each prior
1150** call to getPage.
1151*/
drh4b70f112004-05-02 21:12:19 +00001152static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001153 if( pPage ){
1154 assert( pPage->aData );
1155 assert( pPage->pBt );
drh887dc4c2004-10-22 16:22:57 +00001156 assert( &pPage->aData[pPage->pBt->psAligned]==(unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +00001157 sqlite3pager_unref(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00001158 }
1159}
1160
1161/*
drh72f82862001-05-24 21:06:34 +00001162** This routine is called when the reference count for a page
1163** reaches zero. We need to unref the pParent pointer when that
1164** happens.
1165*/
drhb6f41482004-05-14 01:58:11 +00001166static void pageDestructor(void *pData, int pageSize){
drh887dc4c2004-10-22 16:22:57 +00001167 MemPage *pPage = (MemPage*)&((char*)pData)[FORCE_ALIGNMENT(pageSize)];
drh72f82862001-05-24 21:06:34 +00001168 if( pPage->pParent ){
1169 MemPage *pParent = pPage->pParent;
1170 pPage->pParent = 0;
drha34b6762004-05-07 13:30:42 +00001171 releasePage(pParent);
drh72f82862001-05-24 21:06:34 +00001172 }
drh3aac2dd2004-04-26 14:10:20 +00001173 pPage->isInit = 0;
drh72f82862001-05-24 21:06:34 +00001174}
1175
1176/*
drha6abd042004-06-09 17:37:22 +00001177** During a rollback, when the pager reloads information into the cache
1178** so that the cache is restored to its original state at the start of
1179** the transaction, for each page restored this routine is called.
1180**
1181** This routine needs to reset the extra data section at the end of the
1182** page to agree with the restored data.
1183*/
1184static void pageReinit(void *pData, int pageSize){
drh887dc4c2004-10-22 16:22:57 +00001185 MemPage *pPage = (MemPage*)&((char*)pData)[FORCE_ALIGNMENT(pageSize)];
drha6abd042004-06-09 17:37:22 +00001186 if( pPage->isInit ){
1187 pPage->isInit = 0;
1188 initPage(pPage, pPage->pParent);
1189 }
1190}
1191
1192/*
drhad3e0102004-09-03 23:32:18 +00001193** Open a database file.
1194**
drh382c0242001-10-06 16:33:02 +00001195** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001196** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001197** database file will be deleted when sqlite3BtreeClose() is called.
drha059ad02001-04-17 20:09:11 +00001198*/
drh23e11ca2004-05-04 17:27:28 +00001199int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001200 const char *zFilename, /* Name of the file containing the BTree database */
1201 Btree **ppBtree, /* Pointer to new Btree object written here */
drh90f5ecb2004-07-22 01:19:35 +00001202 int flags /* Options */
drh6019e162001-07-02 17:51:45 +00001203){
drha059ad02001-04-17 20:09:11 +00001204 Btree *pBt;
drha34b6762004-05-07 13:30:42 +00001205 int rc;
drh90f5ecb2004-07-22 01:19:35 +00001206 int nReserve;
1207 unsigned char zDbHeader[100];
drha059ad02001-04-17 20:09:11 +00001208
drhd62d3d02003-01-24 12:14:20 +00001209 /*
1210 ** The following asserts make sure that structures used by the btree are
1211 ** the right size. This is to guard against size changes that result
1212 ** when compiling on a different architecture.
1213 */
drh4a1c3802004-05-12 15:15:47 +00001214 assert( sizeof(i64)==8 );
drh9e572e62004-04-23 23:43:10 +00001215 assert( sizeof(u64)==8 );
drhd62d3d02003-01-24 12:14:20 +00001216 assert( sizeof(u32)==4 );
1217 assert( sizeof(u16)==2 );
1218 assert( sizeof(Pgno)==4 );
drhd62d3d02003-01-24 12:14:20 +00001219 assert( sizeof(ptr)==sizeof(char*) );
1220 assert( sizeof(uptr)==sizeof(ptr) );
1221
drha059ad02001-04-17 20:09:11 +00001222 pBt = sqliteMalloc( sizeof(*pBt) );
1223 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +00001224 *ppBtree = 0;
drha059ad02001-04-17 20:09:11 +00001225 return SQLITE_NOMEM;
1226 }
drh7bec5052005-02-06 02:45:41 +00001227 rc = sqlite3pager_open(&pBt->pPager, zFilename, EXTRA_SIZE, flags);
drha059ad02001-04-17 20:09:11 +00001228 if( rc!=SQLITE_OK ){
drha34b6762004-05-07 13:30:42 +00001229 if( pBt->pPager ) sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001230 sqliteFree(pBt);
1231 *ppBtree = 0;
1232 return rc;
1233 }
drha34b6762004-05-07 13:30:42 +00001234 sqlite3pager_set_destructor(pBt->pPager, pageDestructor);
drha6abd042004-06-09 17:37:22 +00001235 sqlite3pager_set_reiniter(pBt->pPager, pageReinit);
drha059ad02001-04-17 20:09:11 +00001236 pBt->pCursor = 0;
drha34b6762004-05-07 13:30:42 +00001237 pBt->pPage1 = 0;
1238 pBt->readOnly = sqlite3pager_isreadonly(pBt->pPager);
drh90f5ecb2004-07-22 01:19:35 +00001239 sqlite3pager_read_fileheader(pBt->pPager, sizeof(zDbHeader), zDbHeader);
1240 pBt->pageSize = get2byte(&zDbHeader[16]);
1241 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE ){
1242 pBt->pageSize = SQLITE_DEFAULT_PAGE_SIZE;
1243 pBt->maxEmbedFrac = 64; /* 25% */
1244 pBt->minEmbedFrac = 32; /* 12.5% */
1245 pBt->minLeafFrac = 32; /* 12.5% */
drheee46cf2004-11-06 00:02:48 +00001246#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197703aded42004-11-22 05:26:27 +00001247 /* If the magic name ":memory:" will create an in-memory database, then
1248 ** do not set the auto-vacuum flag, even if SQLITE_DEFAULT_AUTOVACUUM
1249 ** is true. On the other hand, if SQLITE_OMIT_MEMORYDB has been defined,
1250 ** then ":memory:" is just a regular file-name. Respect the auto-vacuum
1251 ** default in this case.
1252 */
1253#ifndef SQLITE_OMIT_MEMORYDB
danielk1977951af802004-11-05 15:45:09 +00001254 if( zFilename && strcmp(zFilename,":memory:") ){
danielk197703aded42004-11-22 05:26:27 +00001255#else
1256 if( zFilename ){
1257#endif
danielk1977951af802004-11-05 15:45:09 +00001258 pBt->autoVacuum = SQLITE_DEFAULT_AUTOVACUUM;
1259 }
drheee46cf2004-11-06 00:02:48 +00001260#endif
drh90f5ecb2004-07-22 01:19:35 +00001261 nReserve = 0;
1262 }else{
1263 nReserve = zDbHeader[20];
1264 pBt->maxEmbedFrac = zDbHeader[21];
1265 pBt->minEmbedFrac = zDbHeader[22];
1266 pBt->minLeafFrac = zDbHeader[23];
1267 pBt->pageSizeFixed = 1;
danielk1977951af802004-11-05 15:45:09 +00001268#ifndef SQLITE_OMIT_AUTOVACUUM
1269 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1270#endif
drh90f5ecb2004-07-22 01:19:35 +00001271 }
1272 pBt->usableSize = pBt->pageSize - nReserve;
drh887dc4c2004-10-22 16:22:57 +00001273 pBt->psAligned = FORCE_ALIGNMENT(pBt->pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001274 sqlite3pager_set_pagesize(pBt->pPager, pBt->pageSize);
drha059ad02001-04-17 20:09:11 +00001275 *ppBtree = pBt;
1276 return SQLITE_OK;
1277}
1278
1279/*
1280** Close an open database and invalidate all cursors.
1281*/
drh3aac2dd2004-04-26 14:10:20 +00001282int sqlite3BtreeClose(Btree *pBt){
drha059ad02001-04-17 20:09:11 +00001283 while( pBt->pCursor ){
drh3aac2dd2004-04-26 14:10:20 +00001284 sqlite3BtreeCloseCursor(pBt->pCursor);
drha059ad02001-04-17 20:09:11 +00001285 }
drha34b6762004-05-07 13:30:42 +00001286 sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001287 sqliteFree(pBt);
1288 return SQLITE_OK;
1289}
1290
1291/*
drh90f5ecb2004-07-22 01:19:35 +00001292** Change the busy handler callback function.
1293*/
1294int sqlite3BtreeSetBusyHandler(Btree *pBt, BusyHandler *pHandler){
drhb8ef32c2005-03-14 02:01:49 +00001295 pBt->pBusyHandler = pHandler;
drh90f5ecb2004-07-22 01:19:35 +00001296 sqlite3pager_set_busyhandler(pBt->pPager, pHandler);
1297 return SQLITE_OK;
1298}
1299
1300/*
drhda47d772002-12-02 04:25:19 +00001301** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001302**
1303** The maximum number of cache pages is set to the absolute
1304** value of mxPage. If mxPage is negative, the pager will
1305** operate asynchronously - it will not stop to do fsync()s
1306** to insure data is written to the disk surface before
1307** continuing. Transactions still work if synchronous is off,
1308** and the database cannot be corrupted if this program
1309** crashes. But if the operating system crashes or there is
1310** an abrupt power failure when synchronous is off, the database
1311** could be left in an inconsistent and unrecoverable state.
1312** Synchronous is on by default so database corruption is not
1313** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001314*/
drh23e11ca2004-05-04 17:27:28 +00001315int sqlite3BtreeSetCacheSize(Btree *pBt, int mxPage){
drha34b6762004-05-07 13:30:42 +00001316 sqlite3pager_set_cachesize(pBt->pPager, mxPage);
drhf57b14a2001-09-14 18:54:08 +00001317 return SQLITE_OK;
1318}
1319
1320/*
drh973b6e32003-02-12 14:09:42 +00001321** Change the way data is synced to disk in order to increase or decrease
1322** how well the database resists damage due to OS crashes and power
1323** failures. Level 1 is the same as asynchronous (no syncs() occur and
1324** there is a high probability of damage) Level 2 is the default. There
1325** is a very low but non-zero probability of damage. Level 3 reduces the
1326** probability of damage to near zero but with a write performance reduction.
1327*/
danielk197793758c82005-01-21 08:13:14 +00001328#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drh3aac2dd2004-04-26 14:10:20 +00001329int sqlite3BtreeSetSafetyLevel(Btree *pBt, int level){
drha34b6762004-05-07 13:30:42 +00001330 sqlite3pager_set_safety_level(pBt->pPager, level);
drh973b6e32003-02-12 14:09:42 +00001331 return SQLITE_OK;
1332}
danielk197793758c82005-01-21 08:13:14 +00001333#endif
drh973b6e32003-02-12 14:09:42 +00001334
danielk1977576ec6b2005-01-21 11:55:25 +00001335#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001336/*
drh90f5ecb2004-07-22 01:19:35 +00001337** Change the default pages size and the number of reserved bytes per page.
drh06f50212004-11-02 14:24:33 +00001338**
1339** The page size must be a power of 2 between 512 and 65536. If the page
1340** size supplied does not meet this constraint then the page size is not
1341** changed.
1342**
1343** Page sizes are constrained to be a power of two so that the region
1344** of the database file used for locking (beginning at PENDING_BYTE,
1345** the first byte past the 1GB boundary, 0x40000000) needs to occur
1346** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001347**
1348** If parameter nReserve is less than zero, then the number of reserved
1349** bytes per page is left unchanged.
drh90f5ecb2004-07-22 01:19:35 +00001350*/
1351int sqlite3BtreeSetPageSize(Btree *pBt, int pageSize, int nReserve){
1352 if( pBt->pageSizeFixed ){
1353 return SQLITE_READONLY;
1354 }
1355 if( nReserve<0 ){
1356 nReserve = pBt->pageSize - pBt->usableSize;
1357 }
drh06f50212004-11-02 14:24:33 +00001358 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
1359 ((pageSize-1)&pageSize)==0 ){
drh90f5ecb2004-07-22 01:19:35 +00001360 pBt->pageSize = pageSize;
drh887dc4c2004-10-22 16:22:57 +00001361 pBt->psAligned = FORCE_ALIGNMENT(pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001362 sqlite3pager_set_pagesize(pBt->pPager, pageSize);
1363 }
1364 pBt->usableSize = pBt->pageSize - nReserve;
1365 return SQLITE_OK;
1366}
1367
1368/*
1369** Return the currently defined page size
1370*/
1371int sqlite3BtreeGetPageSize(Btree *pBt){
1372 return pBt->pageSize;
1373}
drh2011d5f2004-07-22 02:40:37 +00001374int sqlite3BtreeGetReserve(Btree *pBt){
1375 return pBt->pageSize - pBt->usableSize;
1376}
danielk1977576ec6b2005-01-21 11:55:25 +00001377#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00001378
1379/*
danielk1977951af802004-11-05 15:45:09 +00001380** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
1381** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
1382** is disabled. The default value for the auto-vacuum property is
1383** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
1384*/
1385int sqlite3BtreeSetAutoVacuum(Btree *pBt, int autoVacuum){
1386#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001387 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00001388#else
1389 if( pBt->pageSizeFixed ){
1390 return SQLITE_READONLY;
1391 }
1392 pBt->autoVacuum = (autoVacuum?1:0);
1393 return SQLITE_OK;
1394#endif
1395}
1396
1397/*
1398** Return the value of the 'auto-vacuum' property. If auto-vacuum is
1399** enabled 1 is returned. Otherwise 0.
1400*/
1401int sqlite3BtreeGetAutoVacuum(Btree *pBt){
1402#ifdef SQLITE_OMIT_AUTOVACUUM
1403 return 0;
1404#else
1405 return pBt->autoVacuum;
1406#endif
1407}
1408
1409
1410/*
drha34b6762004-05-07 13:30:42 +00001411** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001412** also acquire a readlock on that file.
1413**
1414** SQLITE_OK is returned on success. If the file is not a
1415** well-formed database file, then SQLITE_CORRUPT is returned.
1416** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
1417** is returned if we run out of memory. SQLITE_PROTOCOL is returned
1418** if there is a locking protocol violation.
1419*/
1420static int lockBtree(Btree *pBt){
1421 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001422 MemPage *pPage1;
drha34b6762004-05-07 13:30:42 +00001423 if( pBt->pPage1 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001424 rc = getPage(pBt, 1, &pPage1);
drh306dc212001-05-21 13:45:10 +00001425 if( rc!=SQLITE_OK ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00001426
drh306dc212001-05-21 13:45:10 +00001427
1428 /* Do some checking to help insure the file we opened really is
1429 ** a valid database file.
1430 */
drhb6f41482004-05-14 01:58:11 +00001431 rc = SQLITE_NOTADB;
drha34b6762004-05-07 13:30:42 +00001432 if( sqlite3pager_pagecount(pBt->pPager)>0 ){
drhb6f41482004-05-14 01:58:11 +00001433 u8 *page1 = pPage1->aData;
1434 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001435 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001436 }
drhb6f41482004-05-14 01:58:11 +00001437 if( page1[18]>1 || page1[19]>1 ){
1438 goto page1_init_failed;
1439 }
1440 pBt->pageSize = get2byte(&page1[16]);
1441 pBt->usableSize = pBt->pageSize - page1[20];
1442 if( pBt->usableSize<500 ){
1443 goto page1_init_failed;
1444 }
drh887dc4c2004-10-22 16:22:57 +00001445 pBt->psAligned = FORCE_ALIGNMENT(pBt->pageSize);
drhb6f41482004-05-14 01:58:11 +00001446 pBt->maxEmbedFrac = page1[21];
1447 pBt->minEmbedFrac = page1[22];
1448 pBt->minLeafFrac = page1[23];
drh057cd3a2005-02-15 16:23:02 +00001449#ifndef SQLITE_OMIT_AUTOVACUUM
1450 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
1451#endif
drh306dc212001-05-21 13:45:10 +00001452 }
drhb6f41482004-05-14 01:58:11 +00001453
1454 /* maxLocal is the maximum amount of payload to store locally for
1455 ** a cell. Make sure it is small enough so that at least minFanout
1456 ** cells can will fit on one page. We assume a 10-byte page header.
1457 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001458 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001459 ** 4-byte child pointer
1460 ** 9-byte nKey value
1461 ** 4-byte nData value
1462 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001463 ** So a cell consists of a 2-byte poiner, a header which is as much as
1464 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1465 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001466 */
drh43605152004-05-29 21:46:49 +00001467 pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
1468 pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
1469 pBt->maxLeaf = pBt->usableSize - 35;
1470 pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
drhb6f41482004-05-14 01:58:11 +00001471 if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
1472 goto page1_init_failed;
1473 }
drh2e38c322004-09-03 18:38:44 +00001474 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001475 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001476 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001477
drh72f82862001-05-24 21:06:34 +00001478page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001479 releasePage(pPage1);
1480 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001481 return rc;
drh306dc212001-05-21 13:45:10 +00001482}
1483
1484/*
drhb8ef32c2005-03-14 02:01:49 +00001485** This routine works like lockBtree() except that it also invokes the
1486** busy callback if there is lock contention.
1487*/
1488static int lockBtreeWithRetry(Btree *pBt){
1489 int rc = SQLITE_OK;
1490 if( pBt->inTrans==TRANS_NONE ){
1491 rc = sqlite3BtreeBeginTrans(pBt, 0);
1492 pBt->inTrans = TRANS_NONE;
1493 }
1494 return rc;
1495}
1496
1497
1498/*
drhb8ca3072001-12-05 00:21:20 +00001499** If there are no outstanding cursors and we are not in the middle
1500** of a transaction but there is a read lock on the database, then
1501** this routine unrefs the first page of the database file which
1502** has the effect of releasing the read lock.
1503**
1504** If there are any outstanding cursors, this routine is a no-op.
1505**
1506** If there is a transaction in progress, this routine is a no-op.
1507*/
1508static void unlockBtreeIfUnused(Btree *pBt){
danielk1977ee5741e2004-05-31 10:01:34 +00001509 if( pBt->inTrans==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
drh51c6d962004-06-06 00:42:25 +00001510 if( pBt->pPage1->aData==0 ){
1511 MemPage *pPage = pBt->pPage1;
drh887dc4c2004-10-22 16:22:57 +00001512 pPage->aData = &((char*)pPage)[-pBt->psAligned];
drh51c6d962004-06-06 00:42:25 +00001513 pPage->pBt = pBt;
1514 pPage->pgno = 1;
1515 }
drh3aac2dd2004-04-26 14:10:20 +00001516 releasePage(pBt->pPage1);
1517 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00001518 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001519 }
1520}
1521
1522/*
drh9e572e62004-04-23 23:43:10 +00001523** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001524** file.
drh8b2f49b2001-06-08 00:21:52 +00001525*/
1526static int newDatabase(Btree *pBt){
drh9e572e62004-04-23 23:43:10 +00001527 MemPage *pP1;
1528 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001529 int rc;
drhde647132004-05-07 17:57:49 +00001530 if( sqlite3pager_pagecount(pBt->pPager)>0 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001531 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00001532 assert( pP1!=0 );
1533 data = pP1->aData;
drha34b6762004-05-07 13:30:42 +00001534 rc = sqlite3pager_write(data);
drh8b2f49b2001-06-08 00:21:52 +00001535 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00001536 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
1537 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00001538 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00001539 data[18] = 1;
1540 data[19] = 1;
drhb6f41482004-05-14 01:58:11 +00001541 data[20] = pBt->pageSize - pBt->usableSize;
1542 data[21] = pBt->maxEmbedFrac;
1543 data[22] = pBt->minEmbedFrac;
1544 data[23] = pBt->minLeafFrac;
1545 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00001546 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00001547 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00001548#ifndef SQLITE_OMIT_AUTOVACUUM
1549 if( pBt->autoVacuum ){
1550 put4byte(&data[36 + 4*4], 1);
1551 }
1552#endif
drh8b2f49b2001-06-08 00:21:52 +00001553 return SQLITE_OK;
1554}
1555
1556/*
danielk1977ee5741e2004-05-31 10:01:34 +00001557** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00001558** is started if the second argument is nonzero, otherwise a read-
1559** transaction. If the second argument is 2 or more and exclusive
1560** transaction is started, meaning that no other process is allowed
1561** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00001562** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00001563** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00001564**
danielk1977ee5741e2004-05-31 10:01:34 +00001565** A write-transaction must be started before attempting any
1566** changes to the database. None of the following routines
1567** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00001568**
drh23e11ca2004-05-04 17:27:28 +00001569** sqlite3BtreeCreateTable()
1570** sqlite3BtreeCreateIndex()
1571** sqlite3BtreeClearTable()
1572** sqlite3BtreeDropTable()
1573** sqlite3BtreeInsert()
1574** sqlite3BtreeDelete()
1575** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00001576**
drhb8ef32c2005-03-14 02:01:49 +00001577** If an initial attempt to acquire the lock fails because of lock contention
1578** and the database was previously unlocked, then invoke the busy handler
1579** if there is one. But if there was previously a read-lock, do not
1580** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
1581** returned when there is already a read-lock in order to avoid a deadlock.
1582**
1583** Suppose there are two processes A and B. A has a read lock and B has
1584** a reserved lock. B tries to promote to exclusive but is blocked because
1585** of A's read lock. A tries to promote to reserved but is blocked by B.
1586** One or the other of the two processes must give way or there can be
1587** no progress. By returning SQLITE_BUSY and not invoking the busy callback
1588** when A already has a read lock, we encourage A to give up and let B
1589** proceed.
drha059ad02001-04-17 20:09:11 +00001590*/
danielk197740b38dc2004-06-26 08:38:24 +00001591int sqlite3BtreeBeginTrans(Btree *pBt, int wrflag){
danielk1977ee5741e2004-05-31 10:01:34 +00001592 int rc = SQLITE_OK;
drhb8ef32c2005-03-14 02:01:49 +00001593 int busy = 0;
1594 BusyHandler *pH;
danielk1977ee5741e2004-05-31 10:01:34 +00001595
1596 /* If the btree is already in a write-transaction, or it
1597 ** is already in a read-transaction and a read-transaction
1598 ** is requested, this is a no-op.
1599 */
drhb8ef32c2005-03-14 02:01:49 +00001600 if( pBt->inTrans==TRANS_WRITE || (pBt->inTrans==TRANS_READ && !wrflag) ){
danielk1977ee5741e2004-05-31 10:01:34 +00001601 return SQLITE_OK;
1602 }
drhb8ef32c2005-03-14 02:01:49 +00001603
1604 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00001605 if( pBt->readOnly && wrflag ){
1606 return SQLITE_READONLY;
1607 }
1608
drhb8ef32c2005-03-14 02:01:49 +00001609 do {
1610 if( pBt->pPage1==0 ){
1611 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +00001612 }
drhb8ef32c2005-03-14 02:01:49 +00001613
1614 if( rc==SQLITE_OK && wrflag ){
1615 rc = sqlite3pager_begin(pBt->pPage1->aData, wrflag>1);
1616 if( rc==SQLITE_OK ){
1617 rc = newDatabase(pBt);
1618 }
1619 }
1620
1621 if( rc==SQLITE_OK ){
1622 pBt->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
1623 if( wrflag ) pBt->inStmt = 0;
1624 }else{
1625 unlockBtreeIfUnused(pBt);
1626 }
1627 }while( rc==SQLITE_BUSY && pBt->inTrans==TRANS_NONE &&
1628 (pH = pBt->pBusyHandler)!=0 &&
1629 pH->xFunc && pH->xFunc(pH->pArg, busy++)
1630 );
drhb8ca3072001-12-05 00:21:20 +00001631 return rc;
drha059ad02001-04-17 20:09:11 +00001632}
1633
danielk1977687566d2004-11-02 12:56:41 +00001634#ifndef SQLITE_OMIT_AUTOVACUUM
1635
1636/*
1637** Set the pointer-map entries for all children of page pPage. Also, if
1638** pPage contains cells that point to overflow pages, set the pointer
1639** map entries for the overflow pages as well.
1640*/
1641static int setChildPtrmaps(MemPage *pPage){
1642 int i; /* Counter variable */
1643 int nCell; /* Number of cells in page pPage */
1644 int rc = SQLITE_OK; /* Return code */
1645 Btree *pBt = pPage->pBt;
1646 int isInitOrig = pPage->isInit;
1647 Pgno pgno = pPage->pgno;
1648
1649 initPage(pPage, 0);
1650 nCell = pPage->nCell;
1651
1652 for(i=0; i<nCell; i++){
danielk1977687566d2004-11-02 12:56:41 +00001653 u8 *pCell = findCell(pPage, i);
1654
danielk197726836652005-01-17 01:33:13 +00001655 rc = ptrmapPutOvflPtr(pPage, pCell);
1656 if( rc!=SQLITE_OK ){
1657 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00001658 }
danielk197726836652005-01-17 01:33:13 +00001659
danielk1977687566d2004-11-02 12:56:41 +00001660 if( !pPage->leaf ){
1661 Pgno childPgno = get4byte(pCell);
1662 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
1663 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
1664 }
1665 }
1666
1667 if( !pPage->leaf ){
1668 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
1669 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
1670 }
1671
1672set_child_ptrmaps_out:
1673 pPage->isInit = isInitOrig;
1674 return rc;
1675}
1676
1677/*
1678** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
1679** page, is a pointer to page iFrom. Modify this pointer so that it points to
1680** iTo. Parameter eType describes the type of pointer to be modified, as
1681** follows:
1682**
1683** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
1684** page of pPage.
1685**
1686** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
1687** page pointed to by one of the cells on pPage.
1688**
1689** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
1690** overflow page in the list.
1691*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00001692static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
danielk1977687566d2004-11-02 12:56:41 +00001693 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00001694 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00001695 if( get4byte(pPage->aData)!=iFrom ){
1696 return SQLITE_CORRUPT;
1697 }
danielk1977f78fc082004-11-02 14:40:32 +00001698 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00001699 }else{
1700 int isInitOrig = pPage->isInit;
1701 int i;
1702 int nCell;
1703
1704 initPage(pPage, 0);
1705 nCell = pPage->nCell;
1706
danielk1977687566d2004-11-02 12:56:41 +00001707 for(i=0; i<nCell; i++){
1708 u8 *pCell = findCell(pPage, i);
1709 if( eType==PTRMAP_OVERFLOW1 ){
1710 CellInfo info;
1711 parseCellPtr(pPage, pCell, &info);
1712 if( info.iOverflow ){
1713 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
1714 put4byte(&pCell[info.iOverflow], iTo);
1715 break;
1716 }
1717 }
1718 }else{
1719 if( get4byte(pCell)==iFrom ){
1720 put4byte(pCell, iTo);
1721 break;
1722 }
1723 }
1724 }
1725
1726 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00001727 if( eType!=PTRMAP_BTREE ||
1728 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
1729 return SQLITE_CORRUPT;
1730 }
danielk1977687566d2004-11-02 12:56:41 +00001731 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
1732 }
1733
1734 pPage->isInit = isInitOrig;
1735 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00001736 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00001737}
1738
danielk1977003ba062004-11-04 02:57:33 +00001739
danielk19777701e812005-01-10 12:59:51 +00001740/*
1741** Move the open database page pDbPage to location iFreePage in the
1742** database. The pDbPage reference remains valid.
1743*/
danielk1977003ba062004-11-04 02:57:33 +00001744static int relocatePage(
danielk19777701e812005-01-10 12:59:51 +00001745 Btree *pBt, /* Btree */
1746 MemPage *pDbPage, /* Open page to move */
1747 u8 eType, /* Pointer map 'type' entry for pDbPage */
1748 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
1749 Pgno iFreePage /* The location to move pDbPage to */
danielk1977003ba062004-11-04 02:57:33 +00001750){
1751 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
1752 Pgno iDbPage = pDbPage->pgno;
1753 Pager *pPager = pBt->pPager;
1754 int rc;
1755
danielk1977a0bf2652004-11-04 14:30:04 +00001756 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
1757 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
danielk1977003ba062004-11-04 02:57:33 +00001758
1759 /* Move page iDbPage from it's current location to page number iFreePage */
1760 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
1761 iDbPage, iFreePage, iPtrPage, eType));
1762 rc = sqlite3pager_movepage(pPager, pDbPage->aData, iFreePage);
1763 if( rc!=SQLITE_OK ){
1764 return rc;
1765 }
1766 pDbPage->pgno = iFreePage;
1767
1768 /* If pDbPage was a btree-page, then it may have child pages and/or cells
1769 ** that point to overflow pages. The pointer map entries for all these
1770 ** pages need to be changed.
1771 **
1772 ** If pDbPage is an overflow page, then the first 4 bytes may store a
1773 ** pointer to a subsequent overflow page. If this is the case, then
1774 ** the pointer map needs to be updated for the subsequent overflow page.
1775 */
danielk1977a0bf2652004-11-04 14:30:04 +00001776 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00001777 rc = setChildPtrmaps(pDbPage);
1778 if( rc!=SQLITE_OK ){
1779 return rc;
1780 }
1781 }else{
1782 Pgno nextOvfl = get4byte(pDbPage->aData);
1783 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00001784 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
1785 if( rc!=SQLITE_OK ){
1786 return rc;
1787 }
1788 }
1789 }
1790
1791 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
1792 ** that it points at iFreePage. Also fix the pointer map entry for
1793 ** iPtrPage.
1794 */
danielk1977a0bf2652004-11-04 14:30:04 +00001795 if( eType!=PTRMAP_ROOTPAGE ){
1796 rc = getPage(pBt, iPtrPage, &pPtrPage);
1797 if( rc!=SQLITE_OK ){
1798 return rc;
1799 }
1800 rc = sqlite3pager_write(pPtrPage->aData);
1801 if( rc!=SQLITE_OK ){
1802 releasePage(pPtrPage);
1803 return rc;
1804 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00001805 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00001806 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00001807 if( rc==SQLITE_OK ){
1808 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
1809 }
danielk1977003ba062004-11-04 02:57:33 +00001810 }
danielk1977003ba062004-11-04 02:57:33 +00001811 return rc;
1812}
1813
danielk1977687566d2004-11-02 12:56:41 +00001814/* Forward declaration required by autoVacuumCommit(). */
danielk1977cb1a7eb2004-11-05 12:27:02 +00001815static int allocatePage(Btree *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00001816
1817/*
1818** This routine is called prior to sqlite3pager_commit when a transaction
1819** is commited for an auto-vacuum database.
1820*/
danielk1977d761c0c2004-11-05 16:37:02 +00001821static int autoVacuumCommit(Btree *pBt, Pgno *nTrunc){
danielk1977687566d2004-11-02 12:56:41 +00001822 Pager *pPager = pBt->pPager;
1823 Pgno nFreeList; /* Number of pages remaining on the free-list. */
danielk1977a19df672004-11-03 11:37:07 +00001824 int nPtrMap; /* Number of pointer-map pages deallocated */
1825 Pgno origSize; /* Pages in the database file */
1826 Pgno finSize; /* Pages in the database file after truncation */
danielk1977687566d2004-11-02 12:56:41 +00001827 int rc; /* Return code */
1828 u8 eType;
danielk1977a19df672004-11-03 11:37:07 +00001829 int pgsz = pBt->pageSize; /* Page size for this database */
danielk1977687566d2004-11-02 12:56:41 +00001830 Pgno iDbPage; /* The database page to move */
danielk1977687566d2004-11-02 12:56:41 +00001831 MemPage *pDbMemPage = 0; /* "" */
1832 Pgno iPtrPage; /* The page that contains a pointer to iDbPage */
danielk1977687566d2004-11-02 12:56:41 +00001833 Pgno iFreePage; /* The free-list page to move iDbPage to */
1834 MemPage *pFreeMemPage = 0; /* "" */
1835
1836#ifndef NDEBUG
1837 int nRef = *sqlite3pager_stats(pPager);
1838#endif
1839
1840 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +00001841 if( PTRMAP_ISPAGE(pgsz, sqlite3pager_pagecount(pPager)) ){
1842 return SQLITE_CORRUPT;
1843 }
danielk1977687566d2004-11-02 12:56:41 +00001844
1845 /* Figure out how many free-pages are in the database. If there are no
1846 ** free pages, then auto-vacuum is a no-op.
1847 */
1848 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977a19df672004-11-03 11:37:07 +00001849 if( nFreeList==0 ){
danielk1977d761c0c2004-11-05 16:37:02 +00001850 *nTrunc = 0;
danielk1977a19df672004-11-03 11:37:07 +00001851 return SQLITE_OK;
1852 }
danielk1977687566d2004-11-02 12:56:41 +00001853
danielk1977a19df672004-11-03 11:37:07 +00001854 origSize = sqlite3pager_pagecount(pPager);
1855 nPtrMap = (nFreeList-origSize+PTRMAP_PAGENO(pgsz, origSize)+pgsz/5)/(pgsz/5);
1856 finSize = origSize - nFreeList - nPtrMap;
danielk1977599fcba2004-11-08 07:13:13 +00001857 if( origSize>PENDING_BYTE_PAGE(pBt) && finSize<=PENDING_BYTE_PAGE(pBt) ){
1858 finSize--;
drh42cac6d2004-11-20 20:31:11 +00001859 if( PTRMAP_ISPAGE(pBt->usableSize, finSize) ){
danielk1977599fcba2004-11-08 07:13:13 +00001860 finSize--;
1861 }
1862 }
danielk1977a19df672004-11-03 11:37:07 +00001863 TRACE(("AUTOVACUUM: Begin (db size %d->%d)\n", origSize, finSize));
danielk1977687566d2004-11-02 12:56:41 +00001864
danielk1977a19df672004-11-03 11:37:07 +00001865 /* Variable 'finSize' will be the size of the file in pages after
danielk1977687566d2004-11-02 12:56:41 +00001866 ** the auto-vacuum has completed (the current file size minus the number
1867 ** of pages on the free list). Loop through the pages that lie beyond
1868 ** this mark, and if they are not already on the free list, move them
danielk1977a19df672004-11-03 11:37:07 +00001869 ** to a free page earlier in the file (somewhere before finSize).
danielk1977687566d2004-11-02 12:56:41 +00001870 */
danielk1977a19df672004-11-03 11:37:07 +00001871 for( iDbPage=finSize+1; iDbPage<=origSize; iDbPage++ ){
danielk1977599fcba2004-11-08 07:13:13 +00001872 /* If iDbPage is a pointer map page, or the pending-byte page, skip it. */
1873 if( PTRMAP_ISPAGE(pgsz, iDbPage) || iDbPage==PENDING_BYTE_PAGE(pBt) ){
1874 continue;
1875 }
1876
danielk1977687566d2004-11-02 12:56:41 +00001877 rc = ptrmapGet(pBt, iDbPage, &eType, &iPtrPage);
1878 if( rc!=SQLITE_OK ) goto autovacuum_out;
drhccae6022005-02-26 17:31:26 +00001879 if( eType==PTRMAP_ROOTPAGE ){
1880 rc = SQLITE_CORRUPT;
1881 goto autovacuum_out;
1882 }
danielk1977687566d2004-11-02 12:56:41 +00001883
danielk1977599fcba2004-11-08 07:13:13 +00001884 /* If iDbPage is free, do not swap it. */
1885 if( eType==PTRMAP_FREEPAGE ){
danielk1977687566d2004-11-02 12:56:41 +00001886 continue;
1887 }
1888 rc = getPage(pBt, iDbPage, &pDbMemPage);
1889 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977687566d2004-11-02 12:56:41 +00001890
1891 /* Find the next page in the free-list that is not already at the end
1892 ** of the file. A page can be pulled off the free list using the
1893 ** allocatePage() routine.
1894 */
1895 do{
1896 if( pFreeMemPage ){
1897 releasePage(pFreeMemPage);
1898 pFreeMemPage = 0;
1899 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00001900 rc = allocatePage(pBt, &pFreeMemPage, &iFreePage, 0, 0);
danielk1977ac11ee62005-01-15 12:45:51 +00001901 if( rc!=SQLITE_OK ){
1902 releasePage(pDbMemPage);
1903 goto autovacuum_out;
1904 }
danielk1977a19df672004-11-03 11:37:07 +00001905 assert( iFreePage<=origSize );
1906 }while( iFreePage>finSize );
danielk1977687566d2004-11-02 12:56:41 +00001907 releasePage(pFreeMemPage);
1908 pFreeMemPage = 0;
danielk1977687566d2004-11-02 12:56:41 +00001909
danielk1977003ba062004-11-04 02:57:33 +00001910 rc = relocatePage(pBt, pDbMemPage, eType, iPtrPage, iFreePage);
danielk1977687566d2004-11-02 12:56:41 +00001911 releasePage(pDbMemPage);
danielk1977687566d2004-11-02 12:56:41 +00001912 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977687566d2004-11-02 12:56:41 +00001913 }
1914
1915 /* The entire free-list has been swapped to the end of the file. So
danielk1977a19df672004-11-03 11:37:07 +00001916 ** truncate the database file to finSize pages and consider the
danielk1977687566d2004-11-02 12:56:41 +00001917 ** free-list empty.
1918 */
1919 rc = sqlite3pager_write(pBt->pPage1->aData);
1920 if( rc!=SQLITE_OK ) goto autovacuum_out;
1921 put4byte(&pBt->pPage1->aData[32], 0);
1922 put4byte(&pBt->pPage1->aData[36], 0);
danielk1977687566d2004-11-02 12:56:41 +00001923 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977d761c0c2004-11-05 16:37:02 +00001924 *nTrunc = finSize;
danielk1977687566d2004-11-02 12:56:41 +00001925
1926autovacuum_out:
danielk1977687566d2004-11-02 12:56:41 +00001927 assert( nRef==*sqlite3pager_stats(pPager) );
1928 if( rc!=SQLITE_OK ){
1929 sqlite3pager_rollback(pPager);
1930 }
1931 return rc;
1932}
1933#endif
1934
1935/*
drh2aa679f2001-06-25 02:11:07 +00001936** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00001937**
1938** This will release the write lock on the database file. If there
1939** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00001940*/
drh3aac2dd2004-04-26 14:10:20 +00001941int sqlite3BtreeCommit(Btree *pBt){
danielk1977ee5741e2004-05-31 10:01:34 +00001942 int rc = SQLITE_OK;
1943 if( pBt->inTrans==TRANS_WRITE ){
1944 rc = sqlite3pager_commit(pBt->pPager);
1945 }
1946 pBt->inTrans = TRANS_NONE;
drh3aac2dd2004-04-26 14:10:20 +00001947 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00001948 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001949 return rc;
1950}
1951
danielk1977fbcd5852004-06-15 02:44:18 +00001952#ifndef NDEBUG
1953/*
1954** Return the number of write-cursors open on this handle. This is for use
1955** in assert() expressions, so it is only compiled if NDEBUG is not
1956** defined.
1957*/
1958static int countWriteCursors(Btree *pBt){
1959 BtCursor *pCur;
1960 int r = 0;
1961 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1962 if( pCur->wrFlag ) r++;
1963 }
1964 return r;
1965}
1966#endif
1967
drhda200cc2004-05-09 11:51:38 +00001968#ifdef SQLITE_TEST
1969/*
1970** Print debugging information about all cursors to standard output.
1971*/
1972void sqlite3BtreeCursorList(Btree *pBt){
1973 BtCursor *pCur;
1974 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1975 MemPage *pPage = pCur->pPage;
1976 char *zMode = pCur->wrFlag ? "rw" : "ro";
drhfe63d1c2004-09-08 20:13:04 +00001977 sqlite3DebugPrintf("CURSOR %p rooted at %4d(%s) currently at %d.%d%s\n",
1978 pCur, pCur->pgnoRoot, zMode,
drhda200cc2004-05-09 11:51:38 +00001979 pPage ? pPage->pgno : 0, pCur->idx,
1980 pCur->isValid ? "" : " eof"
1981 );
1982 }
1983}
1984#endif
1985
drhc39e0002004-05-07 23:50:57 +00001986/*
drhecdc7532001-09-23 02:35:53 +00001987** Rollback the transaction in progress. All cursors will be
1988** invalided by this operation. Any attempt to use a cursor
1989** that was open at the beginning of this operation will result
1990** in an error.
drh5e00f6c2001-09-13 13:46:56 +00001991**
1992** This will release the write lock on the database file. If there
1993** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00001994*/
drh3aac2dd2004-04-26 14:10:20 +00001995int sqlite3BtreeRollback(Btree *pBt){
danielk1977cfe9a692004-06-16 12:00:29 +00001996 int rc = SQLITE_OK;
drh24cd67e2004-05-10 16:18:47 +00001997 MemPage *pPage1;
danielk1977ee5741e2004-05-31 10:01:34 +00001998 if( pBt->inTrans==TRANS_WRITE ){
drh24cd67e2004-05-10 16:18:47 +00001999 rc = sqlite3pager_rollback(pBt->pPager);
2000 /* The rollback may have destroyed the pPage1->aData value. So
2001 ** call getPage() on page 1 again to make sure pPage1->aData is
2002 ** set correctly. */
2003 if( getPage(pBt, 1, &pPage1)==SQLITE_OK ){
2004 releasePage(pPage1);
2005 }
danielk1977fbcd5852004-06-15 02:44:18 +00002006 assert( countWriteCursors(pBt)==0 );
drh24cd67e2004-05-10 16:18:47 +00002007 }
danielk1977ee5741e2004-05-31 10:01:34 +00002008 pBt->inTrans = TRANS_NONE;
2009 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00002010 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00002011 return rc;
2012}
2013
2014/*
drhab01f612004-05-22 02:55:23 +00002015** Start a statement subtransaction. The subtransaction can
2016** can be rolled back independently of the main transaction.
2017** You must start a transaction before starting a subtransaction.
2018** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00002019** commits or rolls back.
2020**
drhab01f612004-05-22 02:55:23 +00002021** Only one subtransaction may be active at a time. It is an error to try
2022** to start a new subtransaction if another subtransaction is already active.
2023**
2024** Statement subtransactions are used around individual SQL statements
2025** that are contained within a BEGIN...COMMIT block. If a constraint
2026** error occurs within the statement, the effect of that one statement
2027** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00002028*/
drh3aac2dd2004-04-26 14:10:20 +00002029int sqlite3BtreeBeginStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00002030 int rc;
danielk1977ee5741e2004-05-31 10:01:34 +00002031 if( (pBt->inTrans!=TRANS_WRITE) || pBt->inStmt ){
drhf74b8d92002-09-01 23:20:45 +00002032 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh0d65dc02002-02-03 00:56:09 +00002033 }
drha34b6762004-05-07 13:30:42 +00002034 rc = pBt->readOnly ? SQLITE_OK : sqlite3pager_stmt_begin(pBt->pPager);
drh3aac2dd2004-04-26 14:10:20 +00002035 pBt->inStmt = 1;
drh663fc632002-02-02 18:49:19 +00002036 return rc;
2037}
2038
2039
2040/*
drhab01f612004-05-22 02:55:23 +00002041** Commit the statment subtransaction currently in progress. If no
2042** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00002043*/
drh3aac2dd2004-04-26 14:10:20 +00002044int sqlite3BtreeCommitStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00002045 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002046 if( pBt->inStmt && !pBt->readOnly ){
drha34b6762004-05-07 13:30:42 +00002047 rc = sqlite3pager_stmt_commit(pBt->pPager);
drh663fc632002-02-02 18:49:19 +00002048 }else{
2049 rc = SQLITE_OK;
2050 }
drh3aac2dd2004-04-26 14:10:20 +00002051 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00002052 return rc;
2053}
2054
2055/*
drhab01f612004-05-22 02:55:23 +00002056** Rollback the active statement subtransaction. If no subtransaction
2057** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00002058**
drhab01f612004-05-22 02:55:23 +00002059** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00002060** to use a cursor that was open at the beginning of this operation
2061** will result in an error.
2062*/
drh3aac2dd2004-04-26 14:10:20 +00002063int sqlite3BtreeRollbackStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00002064 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002065 if( pBt->inStmt==0 || pBt->readOnly ) return SQLITE_OK;
drha34b6762004-05-07 13:30:42 +00002066 rc = sqlite3pager_stmt_rollback(pBt->pPager);
danielk1977fbcd5852004-06-15 02:44:18 +00002067 assert( countWriteCursors(pBt)==0 );
drh3aac2dd2004-04-26 14:10:20 +00002068 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00002069 return rc;
2070}
2071
2072/*
drh3aac2dd2004-04-26 14:10:20 +00002073** Default key comparison function to be used if no comparison function
2074** is specified on the sqlite3BtreeCursor() call.
2075*/
2076static int dfltCompare(
2077 void *NotUsed, /* User data is not used */
2078 int n1, const void *p1, /* First key to compare */
2079 int n2, const void *p2 /* Second key to compare */
2080){
2081 int c;
2082 c = memcmp(p1, p2, n1<n2 ? n1 : n2);
2083 if( c==0 ){
2084 c = n1 - n2;
2085 }
2086 return c;
2087}
2088
2089/*
drh8b2f49b2001-06-08 00:21:52 +00002090** Create a new cursor for the BTree whose root is on the page
2091** iTable. The act of acquiring a cursor gets a read lock on
2092** the database file.
drh1bee3d72001-10-15 00:44:35 +00002093**
2094** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00002095** If wrFlag==1, then the cursor can be used for reading or for
2096** writing if other conditions for writing are also met. These
2097** are the conditions that must be met in order for writing to
2098** be allowed:
drh6446c4d2001-12-15 14:22:18 +00002099**
drhf74b8d92002-09-01 23:20:45 +00002100** 1: The cursor must have been opened with wrFlag==1
2101**
2102** 2: No other cursors may be open with wrFlag==0 on the same table
2103**
2104** 3: The database must be writable (not on read-only media)
2105**
2106** 4: There must be an active transaction.
2107**
2108** Condition 2 warrants further discussion. If any cursor is opened
2109** on a table with wrFlag==0, that prevents all other cursors from
2110** writing to that table. This is a kind of "read-lock". When a cursor
2111** is opened with wrFlag==0 it is guaranteed that the table will not
2112** change as long as the cursor is open. This allows the cursor to
2113** do a sequential scan of the table without having to worry about
2114** entries being inserted or deleted during the scan. Cursors should
2115** be opened with wrFlag==0 only if this read-lock property is needed.
2116** That is to say, cursors should be opened with wrFlag==0 only if they
drh23e11ca2004-05-04 17:27:28 +00002117** intend to use the sqlite3BtreeNext() system call. All other cursors
drhf74b8d92002-09-01 23:20:45 +00002118** should be opened with wrFlag==1 even if they never really intend
2119** to write.
2120**
drh6446c4d2001-12-15 14:22:18 +00002121** No checking is done to make sure that page iTable really is the
2122** root page of a b-tree. If it is not, then the cursor acquired
2123** will not work correctly.
drh3aac2dd2004-04-26 14:10:20 +00002124**
2125** The comparison function must be logically the same for every cursor
2126** on a particular table. Changing the comparison function will result
2127** in incorrect operations. If the comparison function is NULL, a
2128** default comparison function is used. The comparison function is
2129** always ignored for INTKEY tables.
drha059ad02001-04-17 20:09:11 +00002130*/
drh3aac2dd2004-04-26 14:10:20 +00002131int sqlite3BtreeCursor(
2132 Btree *pBt, /* The btree */
2133 int iTable, /* Root page of table to open */
2134 int wrFlag, /* 1 to write. 0 read-only */
2135 int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
2136 void *pArg, /* First arg to xCompare() */
2137 BtCursor **ppCur /* Write new cursor here */
2138){
drha059ad02001-04-17 20:09:11 +00002139 int rc;
drh8dcd7ca2004-08-08 19:43:29 +00002140 BtCursor *pCur;
drhecdc7532001-09-23 02:35:53 +00002141
drh8dcd7ca2004-08-08 19:43:29 +00002142 *ppCur = 0;
2143 if( wrFlag ){
drh8dcd7ca2004-08-08 19:43:29 +00002144 if( pBt->readOnly ){
2145 return SQLITE_READONLY;
2146 }
2147 if( checkReadLocks(pBt, iTable, 0) ){
2148 return SQLITE_LOCKED;
2149 }
drha0c9a112004-03-10 13:42:37 +00002150 }
drh4b70f112004-05-02 21:12:19 +00002151 if( pBt->pPage1==0 ){
drhb8ef32c2005-03-14 02:01:49 +00002152 rc = lockBtreeWithRetry(pBt);
drha059ad02001-04-17 20:09:11 +00002153 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002154 return rc;
2155 }
2156 }
drheafe05b2004-06-13 00:54:01 +00002157 pCur = sqliteMallocRaw( sizeof(*pCur) );
drha059ad02001-04-17 20:09:11 +00002158 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +00002159 rc = SQLITE_NOMEM;
2160 goto create_cursor_exception;
2161 }
drh8b2f49b2001-06-08 00:21:52 +00002162 pCur->pgnoRoot = (Pgno)iTable;
danielk19776b456a22005-03-21 04:04:02 +00002163 pCur->pPage = 0; /* For exit-handler, in case getAndInitPage() fails. */
drh24cd67e2004-05-10 16:18:47 +00002164 if( iTable==1 && sqlite3pager_pagecount(pBt->pPager)==0 ){
2165 rc = SQLITE_EMPTY;
2166 goto create_cursor_exception;
2167 }
drhde647132004-05-07 17:57:49 +00002168 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
drhbd03cae2001-06-02 02:40:57 +00002169 if( rc!=SQLITE_OK ){
2170 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002171 }
drh3aac2dd2004-04-26 14:10:20 +00002172 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2173 pCur->pArg = pArg;
drh14acc042001-06-10 19:56:58 +00002174 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +00002175 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +00002176 pCur->idx = 0;
drh59eb6762004-06-13 23:07:04 +00002177 memset(&pCur->info, 0, sizeof(pCur->info));
drha059ad02001-04-17 20:09:11 +00002178 pCur->pNext = pBt->pCursor;
2179 if( pCur->pNext ){
2180 pCur->pNext->pPrev = pCur;
2181 }
drh14acc042001-06-10 19:56:58 +00002182 pCur->pPrev = 0;
drha059ad02001-04-17 20:09:11 +00002183 pBt->pCursor = pCur;
drhc39e0002004-05-07 23:50:57 +00002184 pCur->isValid = 0;
drh2af926b2001-05-15 00:39:25 +00002185 *ppCur = pCur;
2186 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00002187
2188create_cursor_exception:
drhbd03cae2001-06-02 02:40:57 +00002189 if( pCur ){
drh3aac2dd2004-04-26 14:10:20 +00002190 releasePage(pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +00002191 sqliteFree(pCur);
2192 }
drh5e00f6c2001-09-13 13:46:56 +00002193 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00002194 return rc;
drha059ad02001-04-17 20:09:11 +00002195}
2196
drh7a224de2004-06-02 01:22:02 +00002197#if 0 /* Not Used */
drhd3d39e92004-05-20 22:16:29 +00002198/*
2199** Change the value of the comparison function used by a cursor.
2200*/
danielk1977bf3b7212004-05-18 10:06:24 +00002201void sqlite3BtreeSetCompare(
drhd3d39e92004-05-20 22:16:29 +00002202 BtCursor *pCur, /* The cursor to whose comparison function is changed */
2203 int(*xCmp)(void*,int,const void*,int,const void*), /* New comparison func */
2204 void *pArg /* First argument to xCmp() */
danielk1977bf3b7212004-05-18 10:06:24 +00002205){
2206 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2207 pCur->pArg = pArg;
2208}
drh7a224de2004-06-02 01:22:02 +00002209#endif
danielk1977bf3b7212004-05-18 10:06:24 +00002210
drha059ad02001-04-17 20:09:11 +00002211/*
drh5e00f6c2001-09-13 13:46:56 +00002212** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00002213** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00002214*/
drh3aac2dd2004-04-26 14:10:20 +00002215int sqlite3BtreeCloseCursor(BtCursor *pCur){
drha059ad02001-04-17 20:09:11 +00002216 Btree *pBt = pCur->pBt;
drha059ad02001-04-17 20:09:11 +00002217 if( pCur->pPrev ){
2218 pCur->pPrev->pNext = pCur->pNext;
2219 }else{
2220 pBt->pCursor = pCur->pNext;
2221 }
2222 if( pCur->pNext ){
2223 pCur->pNext->pPrev = pCur->pPrev;
2224 }
drh3aac2dd2004-04-26 14:10:20 +00002225 releasePage(pCur->pPage);
drh5e00f6c2001-09-13 13:46:56 +00002226 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00002227 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +00002228 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002229}
2230
drh7e3b0a02001-04-28 16:52:40 +00002231/*
drh5e2f8b92001-05-28 00:41:15 +00002232** Make a temporary cursor by filling in the fields of pTempCur.
2233** The temporary cursor is not on the cursor list for the Btree.
2234*/
drh14acc042001-06-10 19:56:58 +00002235static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00002236 memcpy(pTempCur, pCur, sizeof(*pCur));
2237 pTempCur->pNext = 0;
2238 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00002239 if( pTempCur->pPage ){
drha34b6762004-05-07 13:30:42 +00002240 sqlite3pager_ref(pTempCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00002241 }
drh5e2f8b92001-05-28 00:41:15 +00002242}
2243
2244/*
drhbd03cae2001-06-02 02:40:57 +00002245** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00002246** function above.
2247*/
drh14acc042001-06-10 19:56:58 +00002248static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00002249 if( pCur->pPage ){
drha34b6762004-05-07 13:30:42 +00002250 sqlite3pager_unref(pCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00002251 }
drh5e2f8b92001-05-28 00:41:15 +00002252}
2253
2254/*
drh9188b382004-05-14 21:12:22 +00002255** Make sure the BtCursor.info field of the given cursor is valid.
drhab01f612004-05-22 02:55:23 +00002256** If it is not already valid, call parseCell() to fill it in.
2257**
2258** BtCursor.info is a cache of the information in the current cell.
2259** Using this cache reduces the number of calls to parseCell().
drh9188b382004-05-14 21:12:22 +00002260*/
2261static void getCellInfo(BtCursor *pCur){
drh271efa52004-05-30 19:19:05 +00002262 if( pCur->info.nSize==0 ){
drh3a41a3f2004-05-30 02:14:17 +00002263 parseCell(pCur->pPage, pCur->idx, &pCur->info);
drh9188b382004-05-14 21:12:22 +00002264 }else{
2265#ifndef NDEBUG
2266 CellInfo info;
drh51c6d962004-06-06 00:42:25 +00002267 memset(&info, 0, sizeof(info));
drh3a41a3f2004-05-30 02:14:17 +00002268 parseCell(pCur->pPage, pCur->idx, &info);
drh9188b382004-05-14 21:12:22 +00002269 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
2270#endif
2271 }
2272}
2273
2274/*
drh3aac2dd2004-04-26 14:10:20 +00002275** Set *pSize to the size of the buffer needed to hold the value of
2276** the key for the current entry. If the cursor is not pointing
2277** to a valid entry, *pSize is set to 0.
2278**
drh4b70f112004-05-02 21:12:19 +00002279** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00002280** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00002281*/
drh4a1c3802004-05-12 15:15:47 +00002282int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
danielk1977299b1872004-11-22 10:02:10 +00002283 if( !pCur->isValid ){
drh72f82862001-05-24 21:06:34 +00002284 *pSize = 0;
2285 }else{
drh9188b382004-05-14 21:12:22 +00002286 getCellInfo(pCur);
2287 *pSize = pCur->info.nKey;
drh72f82862001-05-24 21:06:34 +00002288 }
2289 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002290}
drh2af926b2001-05-15 00:39:25 +00002291
drh72f82862001-05-24 21:06:34 +00002292/*
drh0e1c19e2004-05-11 00:58:56 +00002293** Set *pSize to the number of bytes of data in the entry the
2294** cursor currently points to. Always return SQLITE_OK.
2295** Failure is not possible. If the cursor is not currently
2296** pointing to an entry (which can happen, for example, if
2297** the database is empty) then *pSize is set to 0.
2298*/
2299int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
danielk1977299b1872004-11-22 10:02:10 +00002300 if( !pCur->isValid ){
danielk197796fc5fe2004-05-13 11:34:16 +00002301 /* Not pointing at a valid entry - set *pSize to 0. */
drh0e1c19e2004-05-11 00:58:56 +00002302 *pSize = 0;
2303 }else{
drh9188b382004-05-14 21:12:22 +00002304 getCellInfo(pCur);
2305 *pSize = pCur->info.nData;
drh0e1c19e2004-05-11 00:58:56 +00002306 }
2307 return SQLITE_OK;
2308}
2309
2310/*
drh72f82862001-05-24 21:06:34 +00002311** Read payload information from the entry that the pCur cursor is
2312** pointing to. Begin reading the payload at "offset" and read
2313** a total of "amt" bytes. Put the result in zBuf.
2314**
2315** This routine does not make a distinction between key and data.
drhab01f612004-05-22 02:55:23 +00002316** It just reads bytes from the payload area. Data might appear
2317** on the main page or be scattered out on multiple overflow pages.
drh72f82862001-05-24 21:06:34 +00002318*/
drh3aac2dd2004-04-26 14:10:20 +00002319static int getPayload(
2320 BtCursor *pCur, /* Cursor pointing to entry to read from */
2321 int offset, /* Begin reading this far into payload */
2322 int amt, /* Read this many bytes */
2323 unsigned char *pBuf, /* Write the bytes into this buffer */
2324 int skipKey /* offset begins at data if this is true */
2325){
2326 unsigned char *aPayload;
drh2af926b2001-05-15 00:39:25 +00002327 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +00002328 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002329 MemPage *pPage;
2330 Btree *pBt;
drh6f11bef2004-05-13 01:12:56 +00002331 int ovflSize;
drhfa1a98a2004-05-14 19:08:17 +00002332 u32 nKey;
drh3aac2dd2004-04-26 14:10:20 +00002333
drh72f82862001-05-24 21:06:34 +00002334 assert( pCur!=0 && pCur->pPage!=0 );
drhc39e0002004-05-07 23:50:57 +00002335 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00002336 pBt = pCur->pBt;
2337 pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00002338 pageIntegrity(pPage);
drh3aac2dd2004-04-26 14:10:20 +00002339 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00002340 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00002341 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00002342 aPayload += pCur->info.nHeader;
drh3aac2dd2004-04-26 14:10:20 +00002343 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00002344 nKey = 0;
2345 }else{
2346 nKey = pCur->info.nKey;
drh3aac2dd2004-04-26 14:10:20 +00002347 }
2348 assert( offset>=0 );
2349 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00002350 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00002351 }
drhfa1a98a2004-05-14 19:08:17 +00002352 if( offset+amt > nKey+pCur->info.nData ){
drha34b6762004-05-07 13:30:42 +00002353 return SQLITE_ERROR;
drh3aac2dd2004-04-26 14:10:20 +00002354 }
drhfa1a98a2004-05-14 19:08:17 +00002355 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00002356 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00002357 if( a+offset>pCur->info.nLocal ){
2358 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00002359 }
drha34b6762004-05-07 13:30:42 +00002360 memcpy(pBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +00002361 if( a==amt ){
2362 return SQLITE_OK;
2363 }
drh2aa679f2001-06-25 02:11:07 +00002364 offset = 0;
drha34b6762004-05-07 13:30:42 +00002365 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00002366 amt -= a;
drhdd793422001-06-28 01:54:48 +00002367 }else{
drhfa1a98a2004-05-14 19:08:17 +00002368 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00002369 }
danielk1977cfe9a692004-06-16 12:00:29 +00002370 ovflSize = pBt->usableSize - 4;
drhbd03cae2001-06-02 02:40:57 +00002371 if( amt>0 ){
drhfa1a98a2004-05-14 19:08:17 +00002372 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977cfe9a692004-06-16 12:00:29 +00002373 while( amt>0 && nextPage ){
2374 rc = sqlite3pager_get(pBt->pPager, nextPage, (void**)&aPayload);
2375 if( rc!=0 ){
2376 return rc;
drh2af926b2001-05-15 00:39:25 +00002377 }
danielk1977cfe9a692004-06-16 12:00:29 +00002378 nextPage = get4byte(aPayload);
2379 if( offset<ovflSize ){
2380 int a = amt;
2381 if( a + offset > ovflSize ){
2382 a = ovflSize - offset;
2383 }
2384 memcpy(pBuf, &aPayload[offset+4], a);
2385 offset = 0;
2386 amt -= a;
2387 pBuf += a;
2388 }else{
2389 offset -= ovflSize;
2390 }
2391 sqlite3pager_unref(aPayload);
drh2af926b2001-05-15 00:39:25 +00002392 }
drh2af926b2001-05-15 00:39:25 +00002393 }
danielk1977cfe9a692004-06-16 12:00:29 +00002394
drha7fcb052001-12-14 15:09:55 +00002395 if( amt>0 ){
drhee696e22004-08-30 16:52:17 +00002396 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
drha7fcb052001-12-14 15:09:55 +00002397 }
2398 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00002399}
2400
drh72f82862001-05-24 21:06:34 +00002401/*
drh3aac2dd2004-04-26 14:10:20 +00002402** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002403** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002404** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00002405**
drh3aac2dd2004-04-26 14:10:20 +00002406** Return SQLITE_OK on success or an error code if anything goes
2407** wrong. An error is returned if "offset+amt" is larger than
2408** the available payload.
drh72f82862001-05-24 21:06:34 +00002409*/
drha34b6762004-05-07 13:30:42 +00002410int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
danielk197728129562005-01-11 10:25:06 +00002411 assert( pCur->isValid );
drhc39e0002004-05-07 23:50:57 +00002412 assert( pCur->pPage!=0 );
drh6575a222005-03-10 17:06:34 +00002413 if( pCur->pPage->intKey ){
2414 return SQLITE_CORRUPT;
2415 }
drhc39e0002004-05-07 23:50:57 +00002416 assert( pCur->pPage->intKey==0 );
2417 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh3aac2dd2004-04-26 14:10:20 +00002418 return getPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
2419}
2420
2421/*
drh3aac2dd2004-04-26 14:10:20 +00002422** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002423** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002424** begins at "offset".
2425**
2426** Return SQLITE_OK on success or an error code if anything goes
2427** wrong. An error is returned if "offset+amt" is larger than
2428** the available payload.
drh72f82862001-05-24 21:06:34 +00002429*/
drh3aac2dd2004-04-26 14:10:20 +00002430int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
danielk197728129562005-01-11 10:25:06 +00002431 assert( pCur->isValid );
drh8c1238a2003-01-02 14:43:55 +00002432 assert( pCur->pPage!=0 );
drhc39e0002004-05-07 23:50:57 +00002433 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh3aac2dd2004-04-26 14:10:20 +00002434 return getPayload(pCur, offset, amt, pBuf, 1);
drh2af926b2001-05-15 00:39:25 +00002435}
2436
drh72f82862001-05-24 21:06:34 +00002437/*
drh0e1c19e2004-05-11 00:58:56 +00002438** Return a pointer to payload information from the entry that the
2439** pCur cursor is pointing to. The pointer is to the beginning of
2440** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00002441** skipKey==1. The number of bytes of available key/data is written
2442** into *pAmt. If *pAmt==0, then the value returned will not be
2443** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00002444**
2445** This routine is an optimization. It is common for the entire key
2446** and data to fit on the local page and for there to be no overflow
2447** pages. When that is so, this routine can be used to access the
2448** key and data without making a copy. If the key and/or data spills
2449** onto overflow pages, then getPayload() must be used to reassembly
2450** the key/data and copy it into a preallocated buffer.
2451**
2452** The pointer returned by this routine looks directly into the cached
2453** page of the database. The data might change or move the next time
2454** any btree routine is called.
2455*/
2456static const unsigned char *fetchPayload(
2457 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00002458 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00002459 int skipKey /* read beginning at data if this is true */
2460){
2461 unsigned char *aPayload;
2462 MemPage *pPage;
2463 Btree *pBt;
drhfa1a98a2004-05-14 19:08:17 +00002464 u32 nKey;
2465 int nLocal;
drh0e1c19e2004-05-11 00:58:56 +00002466
2467 assert( pCur!=0 && pCur->pPage!=0 );
2468 assert( pCur->isValid );
2469 pBt = pCur->pBt;
2470 pPage = pCur->pPage;
2471 pageIntegrity(pPage);
2472 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00002473 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00002474 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00002475 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00002476 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00002477 nKey = 0;
2478 }else{
2479 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00002480 }
drh0e1c19e2004-05-11 00:58:56 +00002481 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00002482 aPayload += nKey;
2483 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00002484 }else{
drhfa1a98a2004-05-14 19:08:17 +00002485 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00002486 if( nLocal>nKey ){
2487 nLocal = nKey;
2488 }
drh0e1c19e2004-05-11 00:58:56 +00002489 }
drhe51c44f2004-05-30 20:46:09 +00002490 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00002491 return aPayload;
2492}
2493
2494
2495/*
drhe51c44f2004-05-30 20:46:09 +00002496** For the entry that cursor pCur is point to, return as
2497** many bytes of the key or data as are available on the local
2498** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00002499**
2500** The pointer returned is ephemeral. The key/data may move
2501** or be destroyed on the next call to any Btree routine.
2502**
2503** These routines is used to get quick access to key and data
2504** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00002505*/
drhe51c44f2004-05-30 20:46:09 +00002506const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
2507 return (const void*)fetchPayload(pCur, pAmt, 0);
drh0e1c19e2004-05-11 00:58:56 +00002508}
drhe51c44f2004-05-30 20:46:09 +00002509const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
2510 return (const void*)fetchPayload(pCur, pAmt, 1);
drh0e1c19e2004-05-11 00:58:56 +00002511}
2512
2513
2514/*
drh8178a752003-01-05 21:41:40 +00002515** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00002516** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00002517*/
drh3aac2dd2004-04-26 14:10:20 +00002518static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00002519 int rc;
2520 MemPage *pNewPage;
drh3aac2dd2004-04-26 14:10:20 +00002521 MemPage *pOldPage;
drh0d316a42002-08-11 20:10:47 +00002522 Btree *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00002523
drhc39e0002004-05-07 23:50:57 +00002524 assert( pCur->isValid );
drhde647132004-05-07 17:57:49 +00002525 rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00002526 if( rc ) return rc;
drhda200cc2004-05-09 11:51:38 +00002527 pageIntegrity(pNewPage);
drh428ae8c2003-01-04 16:48:09 +00002528 pNewPage->idxParent = pCur->idx;
drh3aac2dd2004-04-26 14:10:20 +00002529 pOldPage = pCur->pPage;
2530 pOldPage->idxShift = 0;
2531 releasePage(pOldPage);
drh72f82862001-05-24 21:06:34 +00002532 pCur->pPage = pNewPage;
2533 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00002534 pCur->info.nSize = 0;
drh4be295b2003-12-16 03:44:47 +00002535 if( pNewPage->nCell<1 ){
drhee696e22004-08-30 16:52:17 +00002536 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
drh4be295b2003-12-16 03:44:47 +00002537 }
drh72f82862001-05-24 21:06:34 +00002538 return SQLITE_OK;
2539}
2540
2541/*
drh8856d6a2004-04-29 14:42:46 +00002542** Return true if the page is the virtual root of its table.
2543**
2544** The virtual root page is the root page for most tables. But
2545** for the table rooted on page 1, sometime the real root page
2546** is empty except for the right-pointer. In such cases the
2547** virtual root page is the page that the right-pointer of page
2548** 1 is pointing to.
2549*/
2550static int isRootPage(MemPage *pPage){
2551 MemPage *pParent = pPage->pParent;
drhda200cc2004-05-09 11:51:38 +00002552 if( pParent==0 ) return 1;
2553 if( pParent->pgno>1 ) return 0;
2554 if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
drh8856d6a2004-04-29 14:42:46 +00002555 return 0;
2556}
2557
2558/*
drh5e2f8b92001-05-28 00:41:15 +00002559** Move the cursor up to the parent page.
2560**
2561** pCur->idx is set to the cell index that contains the pointer
2562** to the page we are coming from. If we are coming from the
2563** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00002564** the largest cell index.
drh72f82862001-05-24 21:06:34 +00002565*/
drh8178a752003-01-05 21:41:40 +00002566static void moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00002567 Pgno oldPgno;
2568 MemPage *pParent;
drh8178a752003-01-05 21:41:40 +00002569 MemPage *pPage;
drh428ae8c2003-01-04 16:48:09 +00002570 int idxParent;
drh3aac2dd2004-04-26 14:10:20 +00002571
drhc39e0002004-05-07 23:50:57 +00002572 assert( pCur->isValid );
drh8178a752003-01-05 21:41:40 +00002573 pPage = pCur->pPage;
2574 assert( pPage!=0 );
drh8856d6a2004-04-29 14:42:46 +00002575 assert( !isRootPage(pPage) );
drhda200cc2004-05-09 11:51:38 +00002576 pageIntegrity(pPage);
drh8178a752003-01-05 21:41:40 +00002577 pParent = pPage->pParent;
2578 assert( pParent!=0 );
drhda200cc2004-05-09 11:51:38 +00002579 pageIntegrity(pParent);
drh8178a752003-01-05 21:41:40 +00002580 idxParent = pPage->idxParent;
drha34b6762004-05-07 13:30:42 +00002581 sqlite3pager_ref(pParent->aData);
drh3aac2dd2004-04-26 14:10:20 +00002582 oldPgno = pPage->pgno;
2583 releasePage(pPage);
drh72f82862001-05-24 21:06:34 +00002584 pCur->pPage = pParent;
drh271efa52004-05-30 19:19:05 +00002585 pCur->info.nSize = 0;
drh428ae8c2003-01-04 16:48:09 +00002586 assert( pParent->idxShift==0 );
drh43605152004-05-29 21:46:49 +00002587 pCur->idx = idxParent;
drh72f82862001-05-24 21:06:34 +00002588}
2589
2590/*
2591** Move the cursor to the root page
2592*/
drh5e2f8b92001-05-28 00:41:15 +00002593static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00002594 MemPage *pRoot;
drhbd03cae2001-06-02 02:40:57 +00002595 int rc;
drh0d316a42002-08-11 20:10:47 +00002596 Btree *pBt = pCur->pBt;
drhbd03cae2001-06-02 02:40:57 +00002597
drhde647132004-05-07 17:57:49 +00002598 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0);
drhc39e0002004-05-07 23:50:57 +00002599 if( rc ){
2600 pCur->isValid = 0;
2601 return rc;
2602 }
drh3aac2dd2004-04-26 14:10:20 +00002603 releasePage(pCur->pPage);
drhda200cc2004-05-09 11:51:38 +00002604 pageIntegrity(pRoot);
drh3aac2dd2004-04-26 14:10:20 +00002605 pCur->pPage = pRoot;
drh72f82862001-05-24 21:06:34 +00002606 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00002607 pCur->info.nSize = 0;
drh8856d6a2004-04-29 14:42:46 +00002608 if( pRoot->nCell==0 && !pRoot->leaf ){
2609 Pgno subpage;
2610 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00002611 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00002612 assert( subpage>0 );
drh3644f082004-05-10 18:45:09 +00002613 pCur->isValid = 1;
drh4b70f112004-05-02 21:12:19 +00002614 rc = moveToChild(pCur, subpage);
drh8856d6a2004-04-29 14:42:46 +00002615 }
drhc39e0002004-05-07 23:50:57 +00002616 pCur->isValid = pCur->pPage->nCell>0;
drh8856d6a2004-04-29 14:42:46 +00002617 return rc;
drh72f82862001-05-24 21:06:34 +00002618}
drh2af926b2001-05-15 00:39:25 +00002619
drh5e2f8b92001-05-28 00:41:15 +00002620/*
2621** Move the cursor down to the left-most leaf entry beneath the
2622** entry to which it is currently pointing.
2623*/
2624static int moveToLeftmost(BtCursor *pCur){
2625 Pgno pgno;
2626 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002627 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00002628
drhc39e0002004-05-07 23:50:57 +00002629 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00002630 while( !(pPage = pCur->pPage)->leaf ){
drha34b6762004-05-07 13:30:42 +00002631 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00002632 pgno = get4byte(findCell(pPage, pCur->idx));
drh8178a752003-01-05 21:41:40 +00002633 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00002634 if( rc ) return rc;
2635 }
2636 return SQLITE_OK;
2637}
2638
drh2dcc9aa2002-12-04 13:40:25 +00002639/*
2640** Move the cursor down to the right-most leaf entry beneath the
2641** page to which it is currently pointing. Notice the difference
2642** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
2643** finds the left-most entry beneath the *entry* whereas moveToRightmost()
2644** finds the right-most entry beneath the *page*.
2645*/
2646static int moveToRightmost(BtCursor *pCur){
2647 Pgno pgno;
2648 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002649 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00002650
drhc39e0002004-05-07 23:50:57 +00002651 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00002652 while( !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00002653 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh3aac2dd2004-04-26 14:10:20 +00002654 pCur->idx = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00002655 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00002656 if( rc ) return rc;
2657 }
drh3aac2dd2004-04-26 14:10:20 +00002658 pCur->idx = pPage->nCell - 1;
drh271efa52004-05-30 19:19:05 +00002659 pCur->info.nSize = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002660 return SQLITE_OK;
2661}
2662
drh5e00f6c2001-09-13 13:46:56 +00002663/* Move the cursor to the first entry in the table. Return SQLITE_OK
2664** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00002665** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00002666*/
drh3aac2dd2004-04-26 14:10:20 +00002667int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00002668 int rc;
2669 rc = moveToRoot(pCur);
2670 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00002671 if( pCur->isValid==0 ){
2672 assert( pCur->pPage->nCell==0 );
drh5e00f6c2001-09-13 13:46:56 +00002673 *pRes = 1;
2674 return SQLITE_OK;
2675 }
drhc39e0002004-05-07 23:50:57 +00002676 assert( pCur->pPage->nCell>0 );
drh5e00f6c2001-09-13 13:46:56 +00002677 *pRes = 0;
2678 rc = moveToLeftmost(pCur);
2679 return rc;
2680}
drh5e2f8b92001-05-28 00:41:15 +00002681
drh9562b552002-02-19 15:00:07 +00002682/* Move the cursor to the last entry in the table. Return SQLITE_OK
2683** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00002684** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00002685*/
drh3aac2dd2004-04-26 14:10:20 +00002686int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00002687 int rc;
drh9562b552002-02-19 15:00:07 +00002688 rc = moveToRoot(pCur);
2689 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00002690 if( pCur->isValid==0 ){
2691 assert( pCur->pPage->nCell==0 );
drh9562b552002-02-19 15:00:07 +00002692 *pRes = 1;
2693 return SQLITE_OK;
2694 }
drhc39e0002004-05-07 23:50:57 +00002695 assert( pCur->isValid );
drh9562b552002-02-19 15:00:07 +00002696 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002697 rc = moveToRightmost(pCur);
drh9562b552002-02-19 15:00:07 +00002698 return rc;
2699}
2700
drh3aac2dd2004-04-26 14:10:20 +00002701/* Move the cursor so that it points to an entry near pKey/nKey.
drh72f82862001-05-24 21:06:34 +00002702** Return a success code.
2703**
drh3aac2dd2004-04-26 14:10:20 +00002704** For INTKEY tables, only the nKey parameter is used. pKey is
2705** ignored. For other tables, nKey is the number of bytes of data
2706** in nKey. The comparison function specified when the cursor was
2707** created is used to compare keys.
2708**
drh5e2f8b92001-05-28 00:41:15 +00002709** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00002710** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00002711** were present. The cursor might point to an entry that comes
2712** before or after the key.
2713**
drhbd03cae2001-06-02 02:40:57 +00002714** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00002715** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00002716** this value is as follows:
2717**
2718** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00002719** is smaller than pKey or if the table is empty
2720** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00002721**
2722** *pRes==0 The cursor is left pointing at an entry that
2723** exactly matches pKey.
2724**
2725** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00002726** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00002727*/
drh4a1c3802004-05-12 15:15:47 +00002728int sqlite3BtreeMoveto(BtCursor *pCur, const void *pKey, i64 nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00002729 int rc;
drh5e2f8b92001-05-28 00:41:15 +00002730 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00002731 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00002732 assert( pCur->pPage );
2733 assert( pCur->pPage->isInit );
2734 if( pCur->isValid==0 ){
drhf328bc82004-05-10 23:29:49 +00002735 *pRes = -1;
drhc39e0002004-05-07 23:50:57 +00002736 assert( pCur->pPage->nCell==0 );
2737 return SQLITE_OK;
2738 }
drh4eec4c12005-01-21 00:22:37 +00002739 for(;;){
drh72f82862001-05-24 21:06:34 +00002740 int lwr, upr;
2741 Pgno chldPg;
2742 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00002743 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00002744 lwr = 0;
2745 upr = pPage->nCell-1;
drh4eec4c12005-01-21 00:22:37 +00002746 if( !pPage->intKey && pKey==0 ){
2747 return SQLITE_CORRUPT;
2748 }
drhda200cc2004-05-09 11:51:38 +00002749 pageIntegrity(pPage);
drh72f82862001-05-24 21:06:34 +00002750 while( lwr<=upr ){
danielk197713adf8a2004-06-03 16:08:41 +00002751 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00002752 i64 nCellKey;
drh72f82862001-05-24 21:06:34 +00002753 pCur->idx = (lwr+upr)/2;
drh271efa52004-05-30 19:19:05 +00002754 pCur->info.nSize = 0;
drhde647132004-05-07 17:57:49 +00002755 sqlite3BtreeKeySize(pCur, &nCellKey);
drh3aac2dd2004-04-26 14:10:20 +00002756 if( pPage->intKey ){
2757 if( nCellKey<nKey ){
2758 c = -1;
2759 }else if( nCellKey>nKey ){
2760 c = +1;
2761 }else{
2762 c = 0;
2763 }
drh3aac2dd2004-04-26 14:10:20 +00002764 }else{
drhe51c44f2004-05-30 20:46:09 +00002765 int available;
danielk197713adf8a2004-06-03 16:08:41 +00002766 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drhe51c44f2004-05-30 20:46:09 +00002767 if( available>=nCellKey ){
2768 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
2769 }else{
2770 pCellKey = sqliteMallocRaw( nCellKey );
2771 if( pCellKey==0 ) return SQLITE_NOMEM;
danielk197713adf8a2004-06-03 16:08:41 +00002772 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
drhe51c44f2004-05-30 20:46:09 +00002773 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
2774 sqliteFree(pCellKey);
2775 if( rc ) return rc;
2776 }
drh3aac2dd2004-04-26 14:10:20 +00002777 }
drh72f82862001-05-24 21:06:34 +00002778 if( c==0 ){
drh8b18dd42004-05-12 19:18:15 +00002779 if( pPage->leafData && !pPage->leaf ){
drhfc70e6f2004-05-12 21:11:27 +00002780 lwr = pCur->idx;
2781 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00002782 break;
2783 }else{
drh8b18dd42004-05-12 19:18:15 +00002784 if( pRes ) *pRes = 0;
2785 return SQLITE_OK;
2786 }
drh72f82862001-05-24 21:06:34 +00002787 }
2788 if( c<0 ){
2789 lwr = pCur->idx+1;
2790 }else{
2791 upr = pCur->idx-1;
2792 }
2793 }
2794 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00002795 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00002796 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00002797 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00002798 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00002799 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00002800 }else{
drh43605152004-05-29 21:46:49 +00002801 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00002802 }
2803 if( chldPg==0 ){
drhc39e0002004-05-07 23:50:57 +00002804 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00002805 if( pRes ) *pRes = c;
2806 return SQLITE_OK;
2807 }
drh428ae8c2003-01-04 16:48:09 +00002808 pCur->idx = lwr;
drh271efa52004-05-30 19:19:05 +00002809 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00002810 rc = moveToChild(pCur, chldPg);
drhc39e0002004-05-07 23:50:57 +00002811 if( rc ){
2812 return rc;
2813 }
drh72f82862001-05-24 21:06:34 +00002814 }
drhbd03cae2001-06-02 02:40:57 +00002815 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00002816}
2817
2818/*
drhc39e0002004-05-07 23:50:57 +00002819** Return TRUE if the cursor is not pointing at an entry of the table.
2820**
2821** TRUE will be returned after a call to sqlite3BtreeNext() moves
2822** past the last entry in the table or sqlite3BtreePrev() moves past
2823** the first entry. TRUE is also returned if the table is empty.
2824*/
2825int sqlite3BtreeEof(BtCursor *pCur){
2826 return pCur->isValid==0;
2827}
2828
2829/*
drhbd03cae2001-06-02 02:40:57 +00002830** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00002831** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00002832** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00002833** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00002834*/
drh3aac2dd2004-04-26 14:10:20 +00002835int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00002836 int rc;
drh8178a752003-01-05 21:41:40 +00002837 MemPage *pPage = pCur->pPage;
drh8b18dd42004-05-12 19:18:15 +00002838
drh8c1238a2003-01-02 14:43:55 +00002839 assert( pRes!=0 );
drhc39e0002004-05-07 23:50:57 +00002840 if( pCur->isValid==0 ){
drh8c1238a2003-01-02 14:43:55 +00002841 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00002842 return SQLITE_OK;
drhecdc7532001-09-23 02:35:53 +00002843 }
drh8178a752003-01-05 21:41:40 +00002844 assert( pPage->isInit );
drh8178a752003-01-05 21:41:40 +00002845 assert( pCur->idx<pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00002846
drh72f82862001-05-24 21:06:34 +00002847 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00002848 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00002849 if( pCur->idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00002850 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00002851 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00002852 if( rc ) return rc;
2853 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00002854 *pRes = 0;
2855 return rc;
drh72f82862001-05-24 21:06:34 +00002856 }
drh5e2f8b92001-05-28 00:41:15 +00002857 do{
drh8856d6a2004-04-29 14:42:46 +00002858 if( isRootPage(pPage) ){
drh8c1238a2003-01-02 14:43:55 +00002859 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00002860 pCur->isValid = 0;
drh5e2f8b92001-05-28 00:41:15 +00002861 return SQLITE_OK;
2862 }
drh8178a752003-01-05 21:41:40 +00002863 moveToParent(pCur);
2864 pPage = pCur->pPage;
2865 }while( pCur->idx>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00002866 *pRes = 0;
drh8b18dd42004-05-12 19:18:15 +00002867 if( pPage->leafData ){
2868 rc = sqlite3BtreeNext(pCur, pRes);
2869 }else{
2870 rc = SQLITE_OK;
2871 }
2872 return rc;
drh8178a752003-01-05 21:41:40 +00002873 }
2874 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00002875 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00002876 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00002877 }
drh5e2f8b92001-05-28 00:41:15 +00002878 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00002879 return rc;
drh72f82862001-05-24 21:06:34 +00002880}
2881
drh3b7511c2001-05-26 13:15:44 +00002882/*
drh2dcc9aa2002-12-04 13:40:25 +00002883** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00002884** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00002885** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00002886** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00002887*/
drh3aac2dd2004-04-26 14:10:20 +00002888int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00002889 int rc;
2890 Pgno pgno;
drh8178a752003-01-05 21:41:40 +00002891 MemPage *pPage;
drhc39e0002004-05-07 23:50:57 +00002892 if( pCur->isValid==0 ){
2893 *pRes = 1;
2894 return SQLITE_OK;
2895 }
danielk19776a43f9b2004-11-16 04:57:24 +00002896
drh8178a752003-01-05 21:41:40 +00002897 pPage = pCur->pPage;
drh8178a752003-01-05 21:41:40 +00002898 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00002899 assert( pCur->idx>=0 );
drha34b6762004-05-07 13:30:42 +00002900 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00002901 pgno = get4byte( findCell(pPage, pCur->idx) );
drh8178a752003-01-05 21:41:40 +00002902 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00002903 if( rc ) return rc;
2904 rc = moveToRightmost(pCur);
2905 }else{
2906 while( pCur->idx==0 ){
drh8856d6a2004-04-29 14:42:46 +00002907 if( isRootPage(pPage) ){
drhc39e0002004-05-07 23:50:57 +00002908 pCur->isValid = 0;
2909 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00002910 return SQLITE_OK;
2911 }
drh8178a752003-01-05 21:41:40 +00002912 moveToParent(pCur);
2913 pPage = pCur->pPage;
drh2dcc9aa2002-12-04 13:40:25 +00002914 }
2915 pCur->idx--;
drh271efa52004-05-30 19:19:05 +00002916 pCur->info.nSize = 0;
drh8237d452004-11-22 19:07:09 +00002917 if( pPage->leafData && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00002918 rc = sqlite3BtreePrevious(pCur, pRes);
2919 }else{
2920 rc = SQLITE_OK;
2921 }
drh2dcc9aa2002-12-04 13:40:25 +00002922 }
drh8178a752003-01-05 21:41:40 +00002923 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002924 return rc;
2925}
2926
2927/*
drh3b7511c2001-05-26 13:15:44 +00002928** Allocate a new page from the database file.
2929**
drha34b6762004-05-07 13:30:42 +00002930** The new page is marked as dirty. (In other words, sqlite3pager_write()
drh3b7511c2001-05-26 13:15:44 +00002931** has already been called on the new page.) The new page has also
2932** been referenced and the calling routine is responsible for calling
drha34b6762004-05-07 13:30:42 +00002933** sqlite3pager_unref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00002934**
2935** SQLITE_OK is returned on success. Any other return value indicates
2936** an error. *ppPage and *pPgno are undefined in the event of an error.
drha34b6762004-05-07 13:30:42 +00002937** Do not invoke sqlite3pager_unref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00002938**
drh199e3cf2002-07-18 11:01:47 +00002939** If the "nearby" parameter is not 0, then a (feeble) effort is made to
2940** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00002941** attempt to keep related pages close to each other in the database file,
2942** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00002943**
2944** If the "exact" parameter is not 0, and the page-number nearby exists
2945** anywhere on the free-list, then it is guarenteed to be returned. This
2946** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00002947*/
danielk1977cb1a7eb2004-11-05 12:27:02 +00002948static int allocatePage(
2949 Btree *pBt,
2950 MemPage **ppPage,
2951 Pgno *pPgno,
2952 Pgno nearby,
2953 u8 exact
2954){
drh3aac2dd2004-04-26 14:10:20 +00002955 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00002956 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002957 int n; /* Number of pages on the freelist */
2958 int k; /* Number of leaves on the trunk of the freelist */
drh30e58752002-03-02 20:41:57 +00002959
drh3aac2dd2004-04-26 14:10:20 +00002960 pPage1 = pBt->pPage1;
2961 n = get4byte(&pPage1->aData[36]);
2962 if( n>0 ){
drh91025292004-05-03 19:49:32 +00002963 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00002964 MemPage *pTrunk = 0;
2965 Pgno iTrunk;
2966 MemPage *pPrevTrunk = 0;
2967 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
2968
2969 /* If the 'exact' parameter was true and a query of the pointer-map
2970 ** shows that the page 'nearby' is somewhere on the free-list, then
2971 ** the entire-list will be searched for that page.
2972 */
2973#ifndef SQLITE_OMIT_AUTOVACUUM
2974 if( exact ){
2975 u8 eType;
2976 assert( nearby>0 );
2977 assert( pBt->autoVacuum );
2978 rc = ptrmapGet(pBt, nearby, &eType, 0);
2979 if( rc ) return rc;
2980 if( eType==PTRMAP_FREEPAGE ){
2981 searchList = 1;
2982 }
2983 *pPgno = nearby;
2984 }
2985#endif
2986
2987 /* Decrement the free-list count by 1. Set iTrunk to the index of the
2988 ** first free-list trunk page. iPrevTrunk is initially 1.
2989 */
drha34b6762004-05-07 13:30:42 +00002990 rc = sqlite3pager_write(pPage1->aData);
drh3b7511c2001-05-26 13:15:44 +00002991 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00002992 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00002993
2994 /* The code within this loop is run only once if the 'searchList' variable
2995 ** is not true. Otherwise, it runs once for each trunk-page on the
2996 ** free-list until the page 'nearby' is located.
2997 */
2998 do {
2999 pPrevTrunk = pTrunk;
3000 if( pPrevTrunk ){
3001 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00003002 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00003003 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00003004 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003005 rc = getPage(pBt, iTrunk, &pTrunk);
3006 if( rc ){
3007 releasePage(pPrevTrunk);
3008 return rc;
3009 }
3010
3011 /* TODO: This should move to after the loop? */
3012 rc = sqlite3pager_write(pTrunk->aData);
3013 if( rc ){
3014 releasePage(pTrunk);
3015 releasePage(pPrevTrunk);
3016 return rc;
3017 }
3018
3019 k = get4byte(&pTrunk->aData[4]);
3020 if( k==0 && !searchList ){
3021 /* The trunk has no leaves and the list is not being searched.
3022 ** So extract the trunk page itself and use it as the newly
3023 ** allocated page */
3024 assert( pPrevTrunk==0 );
3025 *pPgno = iTrunk;
3026 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3027 *ppPage = pTrunk;
3028 pTrunk = 0;
3029 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3030 }else if( k>pBt->usableSize/4 - 8 ){
3031 /* Value of k is out of range. Database corruption */
drhee696e22004-08-30 16:52:17 +00003032 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
danielk1977cb1a7eb2004-11-05 12:27:02 +00003033#ifndef SQLITE_OMIT_AUTOVACUUM
3034 }else if( searchList && nearby==iTrunk ){
3035 /* The list is being searched and this trunk page is the page
3036 ** to allocate, regardless of whether it has leaves.
3037 */
3038 assert( *pPgno==iTrunk );
3039 *ppPage = pTrunk;
3040 searchList = 0;
3041 if( k==0 ){
3042 if( !pPrevTrunk ){
3043 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3044 }else{
3045 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
3046 }
3047 }else{
3048 /* The trunk page is required by the caller but it contains
3049 ** pointers to free-list leaves. The first leaf becomes a trunk
3050 ** page in this case.
3051 */
3052 MemPage *pNewTrunk;
3053 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
3054 rc = getPage(pBt, iNewTrunk, &pNewTrunk);
3055 if( rc!=SQLITE_OK ){
3056 releasePage(pTrunk);
3057 releasePage(pPrevTrunk);
3058 return rc;
3059 }
3060 rc = sqlite3pager_write(pNewTrunk->aData);
3061 if( rc!=SQLITE_OK ){
3062 releasePage(pNewTrunk);
3063 releasePage(pTrunk);
3064 releasePage(pPrevTrunk);
3065 return rc;
3066 }
3067 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
3068 put4byte(&pNewTrunk->aData[4], k-1);
3069 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
3070 if( !pPrevTrunk ){
3071 put4byte(&pPage1->aData[32], iNewTrunk);
3072 }else{
3073 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
3074 }
3075 releasePage(pNewTrunk);
3076 }
3077 pTrunk = 0;
3078 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3079#endif
3080 }else{
3081 /* Extract a leaf from the trunk */
3082 int closest;
3083 Pgno iPage;
3084 unsigned char *aData = pTrunk->aData;
3085 if( nearby>0 ){
3086 int i, dist;
3087 closest = 0;
3088 dist = get4byte(&aData[8]) - nearby;
3089 if( dist<0 ) dist = -dist;
3090 for(i=1; i<k; i++){
3091 int d2 = get4byte(&aData[8+i*4]) - nearby;
3092 if( d2<0 ) d2 = -d2;
3093 if( d2<dist ){
3094 closest = i;
3095 dist = d2;
3096 }
3097 }
3098 }else{
3099 closest = 0;
3100 }
3101
3102 iPage = get4byte(&aData[8+closest*4]);
3103 if( !searchList || iPage==nearby ){
3104 *pPgno = iPage;
3105 if( *pPgno>sqlite3pager_pagecount(pBt->pPager) ){
3106 /* Free page off the end of the file */
3107 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
3108 }
3109 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
3110 ": %d more free pages\n",
3111 *pPgno, closest+1, k, pTrunk->pgno, n-1));
3112 if( closest<k-1 ){
3113 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
3114 }
3115 put4byte(&aData[4], k-1);
3116 rc = getPage(pBt, *pPgno, ppPage);
3117 if( rc==SQLITE_OK ){
3118 sqlite3pager_dont_rollback((*ppPage)->aData);
3119 rc = sqlite3pager_write((*ppPage)->aData);
danielk1977aac0a382005-01-16 11:07:06 +00003120 if( rc!=SQLITE_OK ){
3121 releasePage(*ppPage);
3122 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003123 }
3124 searchList = 0;
3125 }
drhee696e22004-08-30 16:52:17 +00003126 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003127 releasePage(pPrevTrunk);
3128 }while( searchList );
3129 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003130 }else{
drh3aac2dd2004-04-26 14:10:20 +00003131 /* There are no pages on the freelist, so create a new page at the
3132 ** end of the file */
drha34b6762004-05-07 13:30:42 +00003133 *pPgno = sqlite3pager_pagecount(pBt->pPager) + 1;
danielk1977afcdd022004-10-31 16:25:42 +00003134
3135#ifndef SQLITE_OMIT_AUTOVACUUM
drh42cac6d2004-11-20 20:31:11 +00003136 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt->usableSize, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00003137 /* If *pPgno refers to a pointer-map page, allocate two new pages
3138 ** at the end of the file instead of one. The first allocated page
3139 ** becomes a new pointer-map page, the second is used by the caller.
3140 */
3141 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00003142 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977afcdd022004-10-31 16:25:42 +00003143 (*pPgno)++;
3144 }
3145#endif
3146
danielk1977599fcba2004-11-08 07:13:13 +00003147 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00003148 rc = getPage(pBt, *pPgno, ppPage);
drh3b7511c2001-05-26 13:15:44 +00003149 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003150 rc = sqlite3pager_write((*ppPage)->aData);
danielk1977aac0a382005-01-16 11:07:06 +00003151 if( rc!=SQLITE_OK ){
3152 releasePage(*ppPage);
3153 }
drh3a4c1412004-05-09 20:40:11 +00003154 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00003155 }
danielk1977599fcba2004-11-08 07:13:13 +00003156
3157 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh3b7511c2001-05-26 13:15:44 +00003158 return rc;
3159}
3160
3161/*
drh3aac2dd2004-04-26 14:10:20 +00003162** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00003163**
drha34b6762004-05-07 13:30:42 +00003164** sqlite3pager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00003165*/
drh3aac2dd2004-04-26 14:10:20 +00003166static int freePage(MemPage *pPage){
3167 Btree *pBt = pPage->pBt;
3168 MemPage *pPage1 = pBt->pPage1;
3169 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00003170
drh3aac2dd2004-04-26 14:10:20 +00003171 /* Prepare the page for freeing */
3172 assert( pPage->pgno>1 );
3173 pPage->isInit = 0;
3174 releasePage(pPage->pParent);
3175 pPage->pParent = 0;
3176
drha34b6762004-05-07 13:30:42 +00003177 /* Increment the free page count on pPage1 */
3178 rc = sqlite3pager_write(pPage1->aData);
drh3aac2dd2004-04-26 14:10:20 +00003179 if( rc ) return rc;
3180 n = get4byte(&pPage1->aData[36]);
3181 put4byte(&pPage1->aData[36], n+1);
3182
danielk1977687566d2004-11-02 12:56:41 +00003183#ifndef SQLITE_OMIT_AUTOVACUUM
3184 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00003185 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00003186 */
3187 if( pBt->autoVacuum ){
3188 rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
danielk1977a64a0352004-11-05 01:45:13 +00003189 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00003190 }
3191#endif
3192
drh3aac2dd2004-04-26 14:10:20 +00003193 if( n==0 ){
3194 /* This is the first free page */
drhda200cc2004-05-09 11:51:38 +00003195 rc = sqlite3pager_write(pPage->aData);
3196 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003197 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00003198 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003199 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003200 }else{
3201 /* Other free pages already exist. Retrive the first trunk page
3202 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00003203 MemPage *pTrunk;
3204 rc = getPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003205 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003206 k = get4byte(&pTrunk->aData[4]);
drhee696e22004-08-30 16:52:17 +00003207 if( k>=pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00003208 /* The trunk is full. Turn the page being freed into a new
3209 ** trunk page with no leaves. */
drha34b6762004-05-07 13:30:42 +00003210 rc = sqlite3pager_write(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00003211 if( rc ) return rc;
3212 put4byte(pPage->aData, pTrunk->pgno);
3213 put4byte(&pPage->aData[4], 0);
3214 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003215 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
3216 pPage->pgno, pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003217 }else{
3218 /* Add the newly freed page as a leaf on the current trunk */
drha34b6762004-05-07 13:30:42 +00003219 rc = sqlite3pager_write(pTrunk->aData);
drh3aac2dd2004-04-26 14:10:20 +00003220 if( rc ) return rc;
3221 put4byte(&pTrunk->aData[4], k+1);
3222 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drha34b6762004-05-07 13:30:42 +00003223 sqlite3pager_dont_write(pBt->pPager, pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003224 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003225 }
3226 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003227 }
drh3b7511c2001-05-26 13:15:44 +00003228 return rc;
3229}
3230
3231/*
drh3aac2dd2004-04-26 14:10:20 +00003232** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00003233*/
drh3aac2dd2004-04-26 14:10:20 +00003234static int clearCell(MemPage *pPage, unsigned char *pCell){
3235 Btree *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00003236 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00003237 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00003238 int rc;
drh3b7511c2001-05-26 13:15:44 +00003239
drh43605152004-05-29 21:46:49 +00003240 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003241 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00003242 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00003243 }
drh6f11bef2004-05-13 01:12:56 +00003244 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh3aac2dd2004-04-26 14:10:20 +00003245 while( ovflPgno!=0 ){
3246 MemPage *pOvfl;
danielk1977a1cb1832005-02-12 08:59:55 +00003247 if( ovflPgno>sqlite3pager_pagecount(pBt->pPager) ){
3248 return SQLITE_CORRUPT;
3249 }
drh3aac2dd2004-04-26 14:10:20 +00003250 rc = getPage(pBt, ovflPgno, &pOvfl);
drh3b7511c2001-05-26 13:15:44 +00003251 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003252 ovflPgno = get4byte(pOvfl->aData);
drha34b6762004-05-07 13:30:42 +00003253 rc = freePage(pOvfl);
drha34b6762004-05-07 13:30:42 +00003254 sqlite3pager_unref(pOvfl->aData);
danielk19776b456a22005-03-21 04:04:02 +00003255 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00003256 }
drh5e2f8b92001-05-28 00:41:15 +00003257 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00003258}
3259
3260/*
drh91025292004-05-03 19:49:32 +00003261** Create the byte sequence used to represent a cell on page pPage
3262** and write that byte sequence into pCell[]. Overflow pages are
3263** allocated and filled in as necessary. The calling procedure
3264** is responsible for making sure sufficient space has been allocated
3265** for pCell[].
3266**
3267** Note that pCell does not necessary need to point to the pPage->aData
3268** area. pCell might point to some temporary storage. The cell will
3269** be constructed in this temporary area then copied into pPage->aData
3270** later.
drh3b7511c2001-05-26 13:15:44 +00003271*/
3272static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00003273 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00003274 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00003275 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00003276 const void *pData,int nData, /* The data */
3277 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00003278){
drh3b7511c2001-05-26 13:15:44 +00003279 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00003280 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00003281 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00003282 int spaceLeft;
3283 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00003284 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00003285 unsigned char *pPrior;
3286 unsigned char *pPayload;
3287 Btree *pBt = pPage->pBt;
3288 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00003289 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00003290 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00003291
drh91025292004-05-03 19:49:32 +00003292 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00003293 nHeader = 0;
drh91025292004-05-03 19:49:32 +00003294 if( !pPage->leaf ){
3295 nHeader += 4;
3296 }
drh8b18dd42004-05-12 19:18:15 +00003297 if( pPage->hasData ){
drh91025292004-05-03 19:49:32 +00003298 nHeader += putVarint(&pCell[nHeader], nData);
drh6f11bef2004-05-13 01:12:56 +00003299 }else{
drh91025292004-05-03 19:49:32 +00003300 nData = 0;
3301 }
drh6f11bef2004-05-13 01:12:56 +00003302 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh43605152004-05-29 21:46:49 +00003303 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003304 assert( info.nHeader==nHeader );
3305 assert( info.nKey==nKey );
3306 assert( info.nData==nData );
3307
3308 /* Fill in the payload */
drh3aac2dd2004-04-26 14:10:20 +00003309 nPayload = nData;
3310 if( pPage->intKey ){
3311 pSrc = pData;
3312 nSrc = nData;
drh91025292004-05-03 19:49:32 +00003313 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00003314 }else{
3315 nPayload += nKey;
3316 pSrc = pKey;
3317 nSrc = nKey;
3318 }
drh6f11bef2004-05-13 01:12:56 +00003319 *pnSize = info.nSize;
3320 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00003321 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00003322 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00003323
drh3b7511c2001-05-26 13:15:44 +00003324 while( nPayload>0 ){
3325 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00003326#ifndef SQLITE_OMIT_AUTOVACUUM
3327 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
3328#endif
danielk1977cb1a7eb2004-11-05 12:27:02 +00003329 rc = allocatePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00003330#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00003331 /* If the database supports auto-vacuum, and the second or subsequent
3332 ** overflow page is being allocated, add an entry to the pointer-map
3333 ** for that page now. The entry for the first overflow page will be
3334 ** added later, by the insertCell() routine.
danielk1977afcdd022004-10-31 16:25:42 +00003335 */
danielk1977a19df672004-11-03 11:37:07 +00003336 if( pBt->autoVacuum && pgnoPtrmap!=0 && rc==SQLITE_OK ){
3337 rc = ptrmapPut(pBt, pgnoOvfl, PTRMAP_OVERFLOW2, pgnoPtrmap);
danielk1977afcdd022004-10-31 16:25:42 +00003338 }
3339#endif
drh3b7511c2001-05-26 13:15:44 +00003340 if( rc ){
drh9b171272004-05-08 02:03:22 +00003341 releasePage(pToRelease);
danielk197728129562005-01-11 10:25:06 +00003342 /* clearCell(pPage, pCell); */
drh3b7511c2001-05-26 13:15:44 +00003343 return rc;
3344 }
drh3aac2dd2004-04-26 14:10:20 +00003345 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00003346 releasePage(pToRelease);
3347 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00003348 pPrior = pOvfl->aData;
3349 put4byte(pPrior, 0);
3350 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00003351 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00003352 }
3353 n = nPayload;
3354 if( n>spaceLeft ) n = spaceLeft;
drh3aac2dd2004-04-26 14:10:20 +00003355 if( n>nSrc ) n = nSrc;
3356 memcpy(pPayload, pSrc, n);
drh3b7511c2001-05-26 13:15:44 +00003357 nPayload -= n;
drhde647132004-05-07 17:57:49 +00003358 pPayload += n;
drh9b171272004-05-08 02:03:22 +00003359 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00003360 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00003361 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00003362 if( nSrc==0 ){
3363 nSrc = nData;
3364 pSrc = pData;
3365 }
drhdd793422001-06-28 01:54:48 +00003366 }
drh9b171272004-05-08 02:03:22 +00003367 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00003368 return SQLITE_OK;
3369}
3370
3371/*
drhbd03cae2001-06-02 02:40:57 +00003372** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00003373** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00003374** pointer in the third argument.
3375*/
danielk1977afcdd022004-10-31 16:25:42 +00003376static int reparentPage(Btree *pBt, Pgno pgno, MemPage *pNewParent, int idx){
drhbd03cae2001-06-02 02:40:57 +00003377 MemPage *pThis;
drh4b70f112004-05-02 21:12:19 +00003378 unsigned char *aData;
drhbd03cae2001-06-02 02:40:57 +00003379
danielk1977afcdd022004-10-31 16:25:42 +00003380 if( pgno==0 ) return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00003381 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00003382 aData = sqlite3pager_lookup(pBt->pPager, pgno);
drhda200cc2004-05-09 11:51:38 +00003383 if( aData ){
drh887dc4c2004-10-22 16:22:57 +00003384 pThis = (MemPage*)&aData[pBt->psAligned];
drh31276532004-09-27 12:20:52 +00003385 assert( pThis->aData==aData );
drhda200cc2004-05-09 11:51:38 +00003386 if( pThis->isInit ){
3387 if( pThis->pParent!=pNewParent ){
3388 if( pThis->pParent ) sqlite3pager_unref(pThis->pParent->aData);
3389 pThis->pParent = pNewParent;
3390 if( pNewParent ) sqlite3pager_ref(pNewParent->aData);
3391 }
3392 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00003393 }
drha34b6762004-05-07 13:30:42 +00003394 sqlite3pager_unref(aData);
drhbd03cae2001-06-02 02:40:57 +00003395 }
danielk1977afcdd022004-10-31 16:25:42 +00003396
3397#ifndef SQLITE_OMIT_AUTOVACUUM
3398 if( pBt->autoVacuum ){
3399 return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
3400 }
3401#endif
3402 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00003403}
3404
danielk1977ac11ee62005-01-15 12:45:51 +00003405
3406
drhbd03cae2001-06-02 02:40:57 +00003407/*
drh4b70f112004-05-02 21:12:19 +00003408** Change the pParent pointer of all children of pPage to point back
3409** to pPage.
3410**
drhbd03cae2001-06-02 02:40:57 +00003411** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00003412** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00003413**
3414** This routine gets called after you memcpy() one page into
3415** another.
3416*/
danielk1977afcdd022004-10-31 16:25:42 +00003417static int reparentChildPages(MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00003418 int i;
danielk1977afcdd022004-10-31 16:25:42 +00003419 Btree *pBt = pPage->pBt;
3420 int rc = SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00003421
danielk1977afcdd022004-10-31 16:25:42 +00003422 if( pPage->leaf ) return SQLITE_OK;
danielk1977afcdd022004-10-31 16:25:42 +00003423
drhbd03cae2001-06-02 02:40:57 +00003424 for(i=0; i<pPage->nCell; i++){
danielk1977afcdd022004-10-31 16:25:42 +00003425 u8 *pCell = findCell(pPage, i);
3426 if( !pPage->leaf ){
3427 rc = reparentPage(pBt, get4byte(pCell), pPage, i);
3428 if( rc!=SQLITE_OK ) return rc;
3429 }
drhbd03cae2001-06-02 02:40:57 +00003430 }
danielk1977afcdd022004-10-31 16:25:42 +00003431 if( !pPage->leaf ){
3432 rc = reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]),
3433 pPage, i);
3434 pPage->idxShift = 0;
3435 }
3436 return rc;
drh14acc042001-06-10 19:56:58 +00003437}
3438
3439/*
3440** Remove the i-th cell from pPage. This routine effects pPage only.
3441** The cell content is not freed or deallocated. It is assumed that
3442** the cell content has been copied someplace else. This routine just
3443** removes the reference to the cell from pPage.
3444**
3445** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00003446*/
drh4b70f112004-05-02 21:12:19 +00003447static void dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00003448 int i; /* Loop counter */
3449 int pc; /* Offset to cell content of cell being deleted */
3450 u8 *data; /* pPage->aData */
3451 u8 *ptr; /* Used to move bytes around within data[] */
3452
drh8c42ca92001-06-22 19:15:00 +00003453 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00003454 assert( sz==cellSize(pPage, idx) );
drha34b6762004-05-07 13:30:42 +00003455 assert( sqlite3pager_iswriteable(pPage->aData) );
drhda200cc2004-05-09 11:51:38 +00003456 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00003457 ptr = &data[pPage->cellOffset + 2*idx];
3458 pc = get2byte(ptr);
3459 assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
drhde647132004-05-07 17:57:49 +00003460 freeSpace(pPage, pc, sz);
drh43605152004-05-29 21:46:49 +00003461 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
3462 ptr[0] = ptr[2];
3463 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00003464 }
3465 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00003466 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
3467 pPage->nFree += 2;
drh428ae8c2003-01-04 16:48:09 +00003468 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00003469}
3470
3471/*
3472** Insert a new cell on pPage at cell index "i". pCell points to the
3473** content of the cell.
3474**
3475** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00003476** will not fit, then make a copy of the cell content into pTemp if
3477** pTemp is not null. Regardless of pTemp, allocate a new entry
3478** in pPage->aOvfl[] and make it point to the cell content (either
3479** in pTemp or the original pCell) and also record its index.
3480** Allocating a new entry in pPage->aCell[] implies that
3481** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00003482**
3483** If nSkip is non-zero, then do not copy the first nSkip bytes of the
3484** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00003485** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00003486** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00003487*/
danielk1977e80463b2004-11-03 03:01:16 +00003488static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00003489 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00003490 int i, /* New cell becomes the i-th cell of the page */
3491 u8 *pCell, /* Content of the new cell */
3492 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00003493 u8 *pTemp, /* Temp storage space for pCell, if needed */
3494 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00003495){
drh43605152004-05-29 21:46:49 +00003496 int idx; /* Where to write new cell content in data[] */
3497 int j; /* Loop counter */
3498 int top; /* First byte of content for any cell in data[] */
3499 int end; /* First byte past the last cell pointer in data[] */
3500 int ins; /* Index in data[] where new cell pointer is inserted */
3501 int hdr; /* Offset into data[] of the page header */
3502 int cellOffset; /* Address of first cell pointer in data[] */
3503 u8 *data; /* The content of the whole page */
3504 u8 *ptr; /* Used for moving information around in data[] */
3505
3506 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
3507 assert( sz==cellSizePtr(pPage, pCell) );
drha34b6762004-05-07 13:30:42 +00003508 assert( sqlite3pager_iswriteable(pPage->aData) );
drh43605152004-05-29 21:46:49 +00003509 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00003510 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00003511 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00003512 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00003513 }
drh43605152004-05-29 21:46:49 +00003514 j = pPage->nOverflow++;
3515 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
3516 pPage->aOvfl[j].pCell = pCell;
3517 pPage->aOvfl[j].idx = i;
3518 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00003519 }else{
drh43605152004-05-29 21:46:49 +00003520 data = pPage->aData;
3521 hdr = pPage->hdrOffset;
3522 top = get2byte(&data[hdr+5]);
3523 cellOffset = pPage->cellOffset;
3524 end = cellOffset + 2*pPage->nCell + 2;
3525 ins = cellOffset + 2*i;
3526 if( end > top - sz ){
danielk19776b456a22005-03-21 04:04:02 +00003527 int rc = defragmentPage(pPage);
3528 if( rc!=SQLITE_OK ) return rc;
drh43605152004-05-29 21:46:49 +00003529 top = get2byte(&data[hdr+5]);
3530 assert( end + sz <= top );
3531 }
3532 idx = allocateSpace(pPage, sz);
3533 assert( idx>0 );
3534 assert( end <= get2byte(&data[hdr+5]) );
3535 pPage->nCell++;
3536 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00003537 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00003538 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
3539 ptr[0] = ptr[-2];
3540 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00003541 }
drh43605152004-05-29 21:46:49 +00003542 put2byte(&data[ins], idx);
3543 put2byte(&data[hdr+3], pPage->nCell);
3544 pPage->idxShift = 1;
drhda200cc2004-05-09 11:51:38 +00003545 pageIntegrity(pPage);
danielk1977a19df672004-11-03 11:37:07 +00003546#ifndef SQLITE_OMIT_AUTOVACUUM
3547 if( pPage->pBt->autoVacuum ){
3548 /* The cell may contain a pointer to an overflow page. If so, write
3549 ** the entry for the overflow page into the pointer map.
3550 */
3551 CellInfo info;
3552 parseCellPtr(pPage, pCell, &info);
3553 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
3554 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
3555 int rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
3556 if( rc!=SQLITE_OK ) return rc;
3557 }
3558 }
3559#endif
drh14acc042001-06-10 19:56:58 +00003560 }
danielk1977e80463b2004-11-03 03:01:16 +00003561
danielk1977e80463b2004-11-03 03:01:16 +00003562 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00003563}
3564
3565/*
drhfa1a98a2004-05-14 19:08:17 +00003566** Add a list of cells to a page. The page should be initially empty.
3567** The cells are guaranteed to fit on the page.
3568*/
3569static void assemblePage(
3570 MemPage *pPage, /* The page to be assemblied */
3571 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00003572 u8 **apCell, /* Pointers to cell bodies */
drhfa1a98a2004-05-14 19:08:17 +00003573 int *aSize /* Sizes of the cells */
3574){
3575 int i; /* Loop counter */
3576 int totalSize; /* Total size of all cells */
3577 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00003578 int cellptr; /* Address of next cell pointer */
3579 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00003580 u8 *data; /* Data for the page */
3581
drh43605152004-05-29 21:46:49 +00003582 assert( pPage->nOverflow==0 );
drhfa1a98a2004-05-14 19:08:17 +00003583 totalSize = 0;
3584 for(i=0; i<nCell; i++){
3585 totalSize += aSize[i];
3586 }
drh43605152004-05-29 21:46:49 +00003587 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00003588 assert( pPage->nCell==0 );
drh43605152004-05-29 21:46:49 +00003589 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00003590 data = pPage->aData;
3591 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00003592 put2byte(&data[hdr+3], nCell);
3593 cellbody = allocateSpace(pPage, totalSize);
3594 assert( cellbody>0 );
3595 assert( pPage->nFree >= 2*nCell );
3596 pPage->nFree -= 2*nCell;
drhfa1a98a2004-05-14 19:08:17 +00003597 for(i=0; i<nCell; i++){
drh43605152004-05-29 21:46:49 +00003598 put2byte(&data[cellptr], cellbody);
3599 memcpy(&data[cellbody], apCell[i], aSize[i]);
3600 cellptr += 2;
3601 cellbody += aSize[i];
drhfa1a98a2004-05-14 19:08:17 +00003602 }
drh43605152004-05-29 21:46:49 +00003603 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00003604 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00003605}
3606
drh14acc042001-06-10 19:56:58 +00003607/*
drhc3b70572003-01-04 19:44:07 +00003608** The following parameters determine how many adjacent pages get involved
3609** in a balancing operation. NN is the number of neighbors on either side
3610** of the page that participate in the balancing operation. NB is the
3611** total number of pages that participate, including the target page and
3612** NN neighbors on either side.
3613**
3614** The minimum value of NN is 1 (of course). Increasing NN above 1
3615** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
3616** in exchange for a larger degradation in INSERT and UPDATE performance.
3617** The value of NN appears to give the best results overall.
3618*/
3619#define NN 1 /* Number of neighbors on either side of pPage */
3620#define NB (NN*2+1) /* Total pages involved in the balance */
3621
drh43605152004-05-29 21:46:49 +00003622/* Forward reference */
danielk1977ac245ec2005-01-14 13:50:11 +00003623static int balance(MemPage*, int);
3624
drh615ae552005-01-16 23:21:00 +00003625#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00003626/*
3627** This version of balance() handles the common special case where
3628** a new entry is being inserted on the extreme right-end of the
3629** tree, in other words, when the new entry will become the largest
3630** entry in the tree.
3631**
3632** Instead of trying balance the 3 right-most leaf pages, just add
3633** a new page to the right-hand side and put the one new entry in
3634** that page. This leaves the right side of the tree somewhat
3635** unbalanced. But odds are that we will be inserting new entries
3636** at the end soon afterwards so the nearly empty page will quickly
3637** fill up. On average.
3638**
3639** pPage is the leaf page which is the right-most page in the tree.
3640** pParent is its parent. pPage must have a single overflow entry
3641** which is also the right-most entry on the page.
3642*/
danielk1977ac245ec2005-01-14 13:50:11 +00003643static int balance_quick(MemPage *pPage, MemPage *pParent){
3644 int rc;
3645 MemPage *pNew;
3646 Pgno pgnoNew;
3647 u8 *pCell;
3648 int szCell;
3649 CellInfo info;
danielk1977ac11ee62005-01-15 12:45:51 +00003650 Btree *pBt = pPage->pBt;
danielk197779a40da2005-01-16 08:00:01 +00003651 int parentIdx = pParent->nCell; /* pParent new divider cell index */
3652 int parentSize; /* Size of new divider cell */
3653 u8 parentCell[64]; /* Space for the new divider cell */
danielk1977ac245ec2005-01-14 13:50:11 +00003654
3655 /* Allocate a new page. Insert the overflow cell from pPage
3656 ** into it. Then remove the overflow cell from pPage.
3657 */
danielk1977ac11ee62005-01-15 12:45:51 +00003658 rc = allocatePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977ac245ec2005-01-14 13:50:11 +00003659 if( rc!=SQLITE_OK ){
3660 return rc;
3661 }
3662 pCell = pPage->aOvfl[0].pCell;
3663 szCell = cellSizePtr(pPage, pCell);
3664 zeroPage(pNew, pPage->aData[0]);
3665 assemblePage(pNew, 1, &pCell, &szCell);
3666 pPage->nOverflow = 0;
3667
danielk197779a40da2005-01-16 08:00:01 +00003668 /* Set the parent of the newly allocated page to pParent. */
3669 pNew->pParent = pParent;
3670 sqlite3pager_ref(pParent->aData);
3671
danielk1977ac245ec2005-01-14 13:50:11 +00003672 /* pPage is currently the right-child of pParent. Change this
3673 ** so that the right-child is the new page allocated above and
danielk197779a40da2005-01-16 08:00:01 +00003674 ** pPage is the next-to-right child.
danielk1977ac245ec2005-01-14 13:50:11 +00003675 */
danielk1977ac11ee62005-01-15 12:45:51 +00003676 assert( pPage->nCell>0 );
danielk1977ac245ec2005-01-14 13:50:11 +00003677 parseCellPtr(pPage, findCell(pPage, pPage->nCell-1), &info);
3678 rc = fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, &parentSize);
3679 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00003680 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00003681 }
3682 assert( parentSize<64 );
3683 rc = insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
3684 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00003685 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00003686 }
3687 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
3688 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
3689
danielk197779a40da2005-01-16 08:00:01 +00003690#ifndef SQLITE_OMIT_AUTOVACUUM
3691 /* If this is an auto-vacuum database, update the pointer map
3692 ** with entries for the new page, and any pointer from the
3693 ** cell on the page to an overflow page.
3694 */
danielk1977ac11ee62005-01-15 12:45:51 +00003695 if( pBt->autoVacuum ){
3696 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
3697 if( rc!=SQLITE_OK ){
3698 return rc;
3699 }
danielk197779a40da2005-01-16 08:00:01 +00003700 rc = ptrmapPutOvfl(pNew, 0);
3701 if( rc!=SQLITE_OK ){
3702 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00003703 }
3704 }
danielk197779a40da2005-01-16 08:00:01 +00003705#endif
danielk1977ac11ee62005-01-15 12:45:51 +00003706
danielk197779a40da2005-01-16 08:00:01 +00003707 /* Release the reference to the new page and balance the parent page,
3708 ** in case the divider cell inserted caused it to become overfull.
3709 */
danielk1977ac245ec2005-01-14 13:50:11 +00003710 releasePage(pNew);
3711 return balance(pParent, 0);
3712}
drh615ae552005-01-16 23:21:00 +00003713#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00003714
drhc3b70572003-01-04 19:44:07 +00003715/*
danielk1977ac11ee62005-01-15 12:45:51 +00003716** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
3717** if the database supports auto-vacuum or not. Because it is used
3718** within an expression that is an argument to another macro
3719** (sqliteMallocRaw), it is not possible to use conditional compilation.
3720** So, this macro is defined instead.
3721*/
3722#ifndef SQLITE_OMIT_AUTOVACUUM
3723#define ISAUTOVACUUM (pBt->autoVacuum)
3724#else
3725#define ISAUTOVACUUM 0
3726#endif
3727
3728/*
drhab01f612004-05-22 02:55:23 +00003729** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00003730** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00003731** Usually NN siblings on either side of pPage is used in the balancing,
3732** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00003733** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00003734** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00003735** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00003736**
drh0c6cc4e2004-06-15 02:13:26 +00003737** The number of siblings of pPage might be increased or decreased by one or
3738** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00003739** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00003740** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00003741** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00003742** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00003743**
drh8b2f49b2001-06-08 00:21:52 +00003744** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00003745** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00003746** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00003747** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00003748**
drh8c42ca92001-06-22 19:15:00 +00003749** In the course of balancing the siblings of pPage, the parent of pPage
3750** might become overfull or underfull. If that happens, then this routine
3751** is called recursively on the parent.
3752**
drh5e00f6c2001-09-13 13:46:56 +00003753** If this routine fails for any reason, it might leave the database
3754** in a corrupted state. So if this routine fails, the database should
3755** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00003756*/
drh43605152004-05-29 21:46:49 +00003757static int balance_nonroot(MemPage *pPage){
drh8b2f49b2001-06-08 00:21:52 +00003758 MemPage *pParent; /* The parent of pPage */
drh4b70f112004-05-02 21:12:19 +00003759 Btree *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00003760 int nCell = 0; /* Number of cells in apCell[] */
3761 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
drh8b2f49b2001-06-08 00:21:52 +00003762 int nOld; /* Number of pages in apOld[] */
3763 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00003764 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00003765 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00003766 int idx; /* Index of pPage in pParent->aCell[] */
3767 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00003768 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00003769 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00003770 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00003771 int usableSpace; /* Bytes in pPage beyond the header */
3772 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00003773 int subtotal; /* Subtotal of bytes in cells on one page */
drhb6f41482004-05-14 01:58:11 +00003774 int iSpace = 0; /* First unused byte of aSpace[] */
drhc3b70572003-01-04 19:44:07 +00003775 MemPage *apOld[NB]; /* pPage and up to two siblings */
3776 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00003777 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00003778 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
3779 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drhc3b70572003-01-04 19:44:07 +00003780 int idxDiv[NB]; /* Indices of divider cells in pParent */
drh4b70f112004-05-02 21:12:19 +00003781 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00003782 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
3783 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00003784 u8 **apCell = 0; /* All cells begin balanced */
drh2e38c322004-09-03 18:38:44 +00003785 int *szCell; /* Local size of all cells in apCell[] */
3786 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
3787 u8 *aSpace; /* Space to hold copies of dividers cells */
danielk19774e17d142005-01-16 09:06:33 +00003788#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00003789 u8 *aFrom = 0;
3790#endif
drh8b2f49b2001-06-08 00:21:52 +00003791
drh14acc042001-06-10 19:56:58 +00003792 /*
drh43605152004-05-29 21:46:49 +00003793 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00003794 */
drh3a4c1412004-05-09 20:40:11 +00003795 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00003796 assert( sqlite3pager_iswriteable(pPage->aData) );
drh4b70f112004-05-02 21:12:19 +00003797 pBt = pPage->pBt;
drh14acc042001-06-10 19:56:58 +00003798 pParent = pPage->pParent;
drh43605152004-05-29 21:46:49 +00003799 sqlite3pager_write(pParent->aData);
3800 assert( pParent );
3801 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00003802
drh615ae552005-01-16 23:21:00 +00003803#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00003804 /*
3805 ** A special case: If a new entry has just been inserted into a
3806 ** table (that is, a btree with integer keys and all data at the leaves)
3807 ** an the new entry is the right-most entry in the tree (it has the
3808 ** largest key) then use the special balance_quick() routine for
3809 ** balancing. balance_quick() is much faster and results in a tighter
3810 ** packing of data in the common case.
3811 */
danielk1977ac245ec2005-01-14 13:50:11 +00003812 if( pPage->leaf &&
3813 pPage->intKey &&
3814 pPage->leafData &&
3815 pPage->nOverflow==1 &&
3816 pPage->aOvfl[0].idx==pPage->nCell &&
danielk1977ac11ee62005-01-15 12:45:51 +00003817 pPage->pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00003818 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
3819 ){
danielk1977ac11ee62005-01-15 12:45:51 +00003820 /*
3821 ** TODO: Check the siblings to the left of pPage. It may be that
3822 ** they are not full and no new page is required.
3823 */
danielk1977ac245ec2005-01-14 13:50:11 +00003824 return balance_quick(pPage, pParent);
3825 }
3826#endif
3827
drh2e38c322004-09-03 18:38:44 +00003828 /*
drh4b70f112004-05-02 21:12:19 +00003829 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00003830 ** to pPage. The "idx" variable is the index of that cell. If pPage
3831 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00003832 */
drhbb49aba2003-01-04 18:53:27 +00003833 if( pParent->idxShift ){
drha34b6762004-05-07 13:30:42 +00003834 Pgno pgno;
drh4b70f112004-05-02 21:12:19 +00003835 pgno = pPage->pgno;
drha34b6762004-05-07 13:30:42 +00003836 assert( pgno==sqlite3pager_pagenumber(pPage->aData) );
drhbb49aba2003-01-04 18:53:27 +00003837 for(idx=0; idx<pParent->nCell; idx++){
drh43605152004-05-29 21:46:49 +00003838 if( get4byte(findCell(pParent, idx))==pgno ){
drhbb49aba2003-01-04 18:53:27 +00003839 break;
3840 }
drh8b2f49b2001-06-08 00:21:52 +00003841 }
drh4b70f112004-05-02 21:12:19 +00003842 assert( idx<pParent->nCell
drh43605152004-05-29 21:46:49 +00003843 || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
drhbb49aba2003-01-04 18:53:27 +00003844 }else{
3845 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00003846 }
drh8b2f49b2001-06-08 00:21:52 +00003847
3848 /*
drh14acc042001-06-10 19:56:58 +00003849 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00003850 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00003851 */
drh14acc042001-06-10 19:56:58 +00003852 nOld = nNew = 0;
drha34b6762004-05-07 13:30:42 +00003853 sqlite3pager_ref(pParent->aData);
drh14acc042001-06-10 19:56:58 +00003854
3855 /*
drh4b70f112004-05-02 21:12:19 +00003856 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00003857 ** the siblings. An attempt is made to find NN siblings on either
3858 ** side of pPage. More siblings are taken from one side, however, if
3859 ** pPage there are fewer than NN siblings on the other side. If pParent
3860 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00003861 */
drhc3b70572003-01-04 19:44:07 +00003862 nxDiv = idx - NN;
3863 if( nxDiv + NB > pParent->nCell ){
3864 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00003865 }
drhc3b70572003-01-04 19:44:07 +00003866 if( nxDiv<0 ){
3867 nxDiv = 0;
3868 }
drh8b2f49b2001-06-08 00:21:52 +00003869 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00003870 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00003871 if( k<pParent->nCell ){
3872 idxDiv[i] = k;
drh43605152004-05-29 21:46:49 +00003873 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00003874 nDiv++;
drha34b6762004-05-07 13:30:42 +00003875 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00003876 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00003877 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00003878 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00003879 }else{
3880 break;
drh8b2f49b2001-06-08 00:21:52 +00003881 }
drhde647132004-05-07 17:57:49 +00003882 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00003883 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00003884 apOld[i]->idxParent = k;
drh91025292004-05-03 19:49:32 +00003885 apCopy[i] = 0;
3886 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00003887 nOld++;
danielk1977634f2982005-03-28 08:44:07 +00003888 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
drh8b2f49b2001-06-08 00:21:52 +00003889 }
3890
3891 /*
danielk1977634f2982005-03-28 08:44:07 +00003892 ** Allocate space for memory structures
3893 */
3894 apCell = sqliteMallocRaw(
3895 nMaxCells*sizeof(u8*) /* apCell */
3896 + nMaxCells*sizeof(int) /* szCell */
3897 + sizeof(MemPage)*NB /* aCopy */
3898 + pBt->psAligned*(5+NB) /* aSpace */
3899 + (ISAUTOVACUUM ? nMaxCells : 0) /* aFrom */
3900 );
3901 if( apCell==0 ){
3902 rc = SQLITE_NOMEM;
3903 goto balance_cleanup;
3904 }
3905 szCell = (int*)&apCell[nMaxCells];
3906 aCopy[0] = (u8*)&szCell[nMaxCells];
3907 for(i=1; i<NB; i++){
3908 aCopy[i] = &aCopy[i-1][pBt->psAligned+sizeof(MemPage)];
3909 }
3910 aSpace = &aCopy[NB-1][pBt->psAligned+sizeof(MemPage)];
3911#ifndef SQLITE_OMIT_AUTOVACUUM
3912 if( pBt->autoVacuum ){
3913 aFrom = &aSpace[5*pBt->psAligned];
3914 }
3915#endif
3916
3917 /*
drh14acc042001-06-10 19:56:58 +00003918 ** Make copies of the content of pPage and its siblings into aOld[].
3919 ** The rest of this function will use data from the copies rather
3920 ** that the original pages since the original pages will be in the
3921 ** process of being overwritten.
3922 */
3923 for(i=0; i<nOld; i++){
drh887dc4c2004-10-22 16:22:57 +00003924 MemPage *p = apCopy[i] = (MemPage*)&aCopy[i][pBt->psAligned];
3925 p->aData = &((u8*)p)[-pBt->psAligned];
3926 memcpy(p->aData, apOld[i]->aData, pBt->psAligned + sizeof(MemPage));
3927 p->aData = &((u8*)p)[-pBt->psAligned];
drh14acc042001-06-10 19:56:58 +00003928 }
3929
3930 /*
3931 ** Load pointers to all cells on sibling pages and the divider cells
3932 ** into the local apCell[] array. Make copies of the divider cells
drhb6f41482004-05-14 01:58:11 +00003933 ** into space obtained form aSpace[] and remove the the divider Cells
3934 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00003935 **
3936 ** If the siblings are on leaf pages, then the child pointers of the
3937 ** divider cells are stripped from the cells before they are copied
drh96f5b762004-05-16 16:24:36 +00003938 ** into aSpace[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00003939 ** child pointers. If siblings are not leaves, then all cell in
3940 ** apCell[] include child pointers. Either way, all cells in apCell[]
3941 ** are alike.
drh96f5b762004-05-16 16:24:36 +00003942 **
3943 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
3944 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00003945 */
3946 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00003947 leafCorrection = pPage->leaf*4;
drh8b18dd42004-05-12 19:18:15 +00003948 leafData = pPage->leafData && pPage->leaf;
drh8b2f49b2001-06-08 00:21:52 +00003949 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00003950 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00003951 int limit = pOld->nCell+pOld->nOverflow;
3952 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00003953 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00003954 apCell[nCell] = findOverflowCell(pOld, j);
3955 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk1977ac11ee62005-01-15 12:45:51 +00003956#ifndef SQLITE_OMIT_AUTOVACUUM
3957 if( pBt->autoVacuum ){
3958 int a;
3959 aFrom[nCell] = i;
3960 for(a=0; a<pOld->nOverflow; a++){
3961 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
3962 aFrom[nCell] = 0xFF;
3963 break;
3964 }
3965 }
3966 }
3967#endif
drh14acc042001-06-10 19:56:58 +00003968 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00003969 }
3970 if( i<nOld-1 ){
drh43605152004-05-29 21:46:49 +00003971 int sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00003972 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00003973 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
3974 ** are duplicates of keys on the child pages. We need to remove
3975 ** the divider cells from pParent, but the dividers cells are not
3976 ** added to apCell[] because they are duplicates of child cells.
3977 */
drh8b18dd42004-05-12 19:18:15 +00003978 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00003979 }else{
drhb6f41482004-05-14 01:58:11 +00003980 u8 *pTemp;
danielk1977634f2982005-03-28 08:44:07 +00003981 assert( nCell<nMaxCells );
drhb6f41482004-05-14 01:58:11 +00003982 szCell[nCell] = sz;
3983 pTemp = &aSpace[iSpace];
3984 iSpace += sz;
drh887dc4c2004-10-22 16:22:57 +00003985 assert( iSpace<=pBt->psAligned*5 );
drhb6f41482004-05-14 01:58:11 +00003986 memcpy(pTemp, apDiv[i], sz);
3987 apCell[nCell] = pTemp+leafCorrection;
danielk1977ac11ee62005-01-15 12:45:51 +00003988#ifndef SQLITE_OMIT_AUTOVACUUM
3989 if( pBt->autoVacuum ){
3990 aFrom[nCell] = 0xFF;
3991 }
3992#endif
drhb6f41482004-05-14 01:58:11 +00003993 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00003994 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00003995 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00003996 if( !pOld->leaf ){
3997 assert( leafCorrection==0 );
3998 /* The right pointer of the child page pOld becomes the left
3999 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00004000 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00004001 }else{
4002 assert( leafCorrection==4 );
4003 }
4004 nCell++;
drh4b70f112004-05-02 21:12:19 +00004005 }
drh8b2f49b2001-06-08 00:21:52 +00004006 }
4007 }
4008
4009 /*
drh6019e162001-07-02 17:51:45 +00004010 ** Figure out the number of pages needed to hold all nCell cells.
4011 ** Store this number in "k". Also compute szNew[] which is the total
4012 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00004013 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00004014 ** cntNew[k] should equal nCell.
4015 **
drh96f5b762004-05-16 16:24:36 +00004016 ** Values computed by this block:
4017 **
4018 ** k: The total number of sibling pages
4019 ** szNew[i]: Spaced used on the i-th sibling page.
4020 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
4021 ** the right of the i-th sibling page.
4022 ** usableSpace: Number of bytes of space available on each sibling.
4023 **
drh8b2f49b2001-06-08 00:21:52 +00004024 */
drh43605152004-05-29 21:46:49 +00004025 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00004026 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00004027 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00004028 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00004029 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00004030 szNew[k] = subtotal - szCell[i];
4031 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00004032 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00004033 subtotal = 0;
4034 k++;
4035 }
4036 }
4037 szNew[k] = subtotal;
4038 cntNew[k] = nCell;
4039 k++;
drh96f5b762004-05-16 16:24:36 +00004040
4041 /*
4042 ** The packing computed by the previous block is biased toward the siblings
4043 ** on the left side. The left siblings are always nearly full, while the
4044 ** right-most sibling might be nearly empty. This block of code attempts
4045 ** to adjust the packing of siblings to get a better balance.
4046 **
4047 ** This adjustment is more than an optimization. The packing above might
4048 ** be so out of balance as to be illegal. For example, the right-most
4049 ** sibling might be completely empty. This adjustment is not optional.
4050 */
drh6019e162001-07-02 17:51:45 +00004051 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00004052 int szRight = szNew[i]; /* Size of sibling on the right */
4053 int szLeft = szNew[i-1]; /* Size of sibling on the left */
4054 int r; /* Index of right-most cell in left sibling */
4055 int d; /* Index of first cell to the left of right sibling */
4056
4057 r = cntNew[i-1] - 1;
4058 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00004059 assert( d<nMaxCells );
4060 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00004061 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
4062 szRight += szCell[d] + 2;
4063 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00004064 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00004065 r = cntNew[i-1] - 1;
4066 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00004067 }
drh96f5b762004-05-16 16:24:36 +00004068 szNew[i] = szRight;
4069 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00004070 }
4071 assert( cntNew[0]>0 );
drh8b2f49b2001-06-08 00:21:52 +00004072
4073 /*
drh6b308672002-07-08 02:16:37 +00004074 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00004075 */
drh4b70f112004-05-02 21:12:19 +00004076 assert( pPage->pgno>1 );
4077 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00004078 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00004079 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00004080 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00004081 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00004082 pgnoNew[i] = pgnoOld[i];
4083 apOld[i] = 0;
danielk197728129562005-01-11 10:25:06 +00004084 rc = sqlite3pager_write(pNew->aData);
4085 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00004086 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004087 rc = allocatePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00004088 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00004089 apNew[i] = pNew;
drh6b308672002-07-08 02:16:37 +00004090 }
drh14acc042001-06-10 19:56:58 +00004091 nNew++;
drhda200cc2004-05-09 11:51:38 +00004092 zeroPage(pNew, pageFlags);
drh8b2f49b2001-06-08 00:21:52 +00004093 }
4094
danielk1977299b1872004-11-22 10:02:10 +00004095 /* Free any old pages that were not reused as new pages.
4096 */
4097 while( i<nOld ){
4098 rc = freePage(apOld[i]);
4099 if( rc ) goto balance_cleanup;
4100 releasePage(apOld[i]);
4101 apOld[i] = 0;
4102 i++;
4103 }
4104
drh8b2f49b2001-06-08 00:21:52 +00004105 /*
drhf9ffac92002-03-02 19:00:31 +00004106 ** Put the new pages in accending order. This helps to
4107 ** keep entries in the disk file in order so that a scan
4108 ** of the table is a linear scan through the file. That
4109 ** in turn helps the operating system to deliver pages
4110 ** from the disk more rapidly.
4111 **
4112 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00004113 ** n is never more than NB (a small constant), that should
4114 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00004115 **
drhc3b70572003-01-04 19:44:07 +00004116 ** When NB==3, this one optimization makes the database
4117 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00004118 */
4119 for(i=0; i<k-1; i++){
4120 int minV = pgnoNew[i];
4121 int minI = i;
4122 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00004123 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00004124 minI = j;
4125 minV = pgnoNew[j];
4126 }
4127 }
4128 if( minI>i ){
4129 int t;
4130 MemPage *pT;
4131 t = pgnoNew[i];
4132 pT = apNew[i];
4133 pgnoNew[i] = pgnoNew[minI];
4134 apNew[i] = apNew[minI];
4135 pgnoNew[minI] = t;
4136 apNew[minI] = pT;
4137 }
4138 }
drha2fce642004-06-05 00:01:44 +00004139 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00004140 pgnoOld[0],
4141 nOld>=2 ? pgnoOld[1] : 0,
4142 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00004143 pgnoNew[0], szNew[0],
4144 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
4145 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00004146 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
4147 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00004148
drhf9ffac92002-03-02 19:00:31 +00004149 /*
drh14acc042001-06-10 19:56:58 +00004150 ** Evenly distribute the data in apCell[] across the new pages.
4151 ** Insert divider cells into pParent as necessary.
4152 */
4153 j = 0;
4154 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00004155 /* Assemble the new sibling page. */
danielk1977634f2982005-03-28 08:44:07 +00004156 assert( j<nMaxCells );
drh14acc042001-06-10 19:56:58 +00004157 MemPage *pNew = apNew[i];
drh4b70f112004-05-02 21:12:19 +00004158 assert( pNew->pgno==pgnoNew[i] );
drhfa1a98a2004-05-14 19:08:17 +00004159 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh6019e162001-07-02 17:51:45 +00004160 assert( pNew->nCell>0 );
drh43605152004-05-29 21:46:49 +00004161 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00004162
4163#ifndef SQLITE_OMIT_AUTOVACUUM
4164 /* If this is an auto-vacuum database, update the pointer map entries
4165 ** that point to the siblings that were rearranged. These can be: left
4166 ** children of cells, the right-child of the page, or overflow pages
4167 ** pointed to by cells.
4168 */
4169 if( pBt->autoVacuum ){
4170 for(k=j; k<cntNew[i]; k++){
danielk1977634f2982005-03-28 08:44:07 +00004171 assert( k<nMaxCells );
danielk1977ac11ee62005-01-15 12:45:51 +00004172 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
danielk197779a40da2005-01-16 08:00:01 +00004173 rc = ptrmapPutOvfl(pNew, k-j);
4174 if( rc!=SQLITE_OK ){
4175 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00004176 }
4177 }
4178 }
4179 }
4180#endif
4181
4182 j = cntNew[i];
4183
4184 /* If the sibling page assembled above was not the right-most sibling,
4185 ** insert a divider cell into the parent page.
4186 */
drh14acc042001-06-10 19:56:58 +00004187 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00004188 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00004189 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00004190 int sz;
danielk1977634f2982005-03-28 08:44:07 +00004191
4192 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00004193 pCell = apCell[j];
4194 sz = szCell[j] + leafCorrection;
drh4b70f112004-05-02 21:12:19 +00004195 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00004196 memcpy(&pNew->aData[8], pCell, 4);
drh24cd67e2004-05-10 16:18:47 +00004197 pTemp = 0;
drh8b18dd42004-05-12 19:18:15 +00004198 }else if( leafData ){
danielk1977ac11ee62005-01-15 12:45:51 +00004199 /* If the tree is a leaf-data tree, and the siblings are leaves,
4200 ** then there is no divider cell in apCell[]. Instead, the divider
4201 ** cell consists of the integer key for the right-most cell of
4202 ** the sibling-page assembled above only.
4203 */
drh6f11bef2004-05-13 01:12:56 +00004204 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00004205 j--;
drh43605152004-05-29 21:46:49 +00004206 parseCellPtr(pNew, apCell[j], &info);
drhb6f41482004-05-14 01:58:11 +00004207 pCell = &aSpace[iSpace];
drh6f11bef2004-05-13 01:12:56 +00004208 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, &sz);
drhb6f41482004-05-14 01:58:11 +00004209 iSpace += sz;
drh887dc4c2004-10-22 16:22:57 +00004210 assert( iSpace<=pBt->psAligned*5 );
drh8b18dd42004-05-12 19:18:15 +00004211 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00004212 }else{
4213 pCell -= 4;
drhb6f41482004-05-14 01:58:11 +00004214 pTemp = &aSpace[iSpace];
4215 iSpace += sz;
drh887dc4c2004-10-22 16:22:57 +00004216 assert( iSpace<=pBt->psAligned*5 );
drh4b70f112004-05-02 21:12:19 +00004217 }
danielk1977a3ad5e72005-01-07 08:56:44 +00004218 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00004219 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh43605152004-05-29 21:46:49 +00004220 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +00004221#ifndef SQLITE_OMIT_AUTOVACUUM
4222 /* If this is an auto-vacuum database, and not a leaf-data tree,
4223 ** then update the pointer map with an entry for the overflow page
4224 ** that the cell just inserted points to (if any).
4225 */
4226 if( pBt->autoVacuum && !leafData ){
danielk197779a40da2005-01-16 08:00:01 +00004227 rc = ptrmapPutOvfl(pParent, nxDiv);
4228 if( rc!=SQLITE_OK ){
4229 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00004230 }
4231 }
4232#endif
drh14acc042001-06-10 19:56:58 +00004233 j++;
4234 nxDiv++;
4235 }
4236 }
drh6019e162001-07-02 17:51:45 +00004237 assert( j==nCell );
drh4b70f112004-05-02 21:12:19 +00004238 if( (pageFlags & PTF_LEAF)==0 ){
drh43605152004-05-29 21:46:49 +00004239 memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
drh14acc042001-06-10 19:56:58 +00004240 }
drh43605152004-05-29 21:46:49 +00004241 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00004242 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00004243 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00004244 }else{
4245 /* Right-most sibling is the left child of the first entry in pParent
4246 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00004247 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00004248 }
4249
4250 /*
4251 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00004252 */
4253 for(i=0; i<nNew; i++){
danielk1977afcdd022004-10-31 16:25:42 +00004254 rc = reparentChildPages(apNew[i]);
4255 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004256 }
danielk1977afcdd022004-10-31 16:25:42 +00004257 rc = reparentChildPages(pParent);
4258 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004259
4260 /*
drh3a4c1412004-05-09 20:40:11 +00004261 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00004262 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00004263 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00004264 */
drhda200cc2004-05-09 11:51:38 +00004265 assert( pParent->isInit );
drh3a4c1412004-05-09 20:40:11 +00004266 /* assert( pPage->isInit ); // No! pPage might have been added to freelist */
4267 /* pageIntegrity(pPage); // No! pPage might have been added to freelist */
danielk1977ac245ec2005-01-14 13:50:11 +00004268 rc = balance(pParent, 0);
drhda200cc2004-05-09 11:51:38 +00004269
drh8b2f49b2001-06-08 00:21:52 +00004270 /*
drh14acc042001-06-10 19:56:58 +00004271 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00004272 */
drh14acc042001-06-10 19:56:58 +00004273balance_cleanup:
drh2e38c322004-09-03 18:38:44 +00004274 sqliteFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00004275 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00004276 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00004277 }
drh14acc042001-06-10 19:56:58 +00004278 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00004279 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00004280 }
drh91025292004-05-03 19:49:32 +00004281 releasePage(pParent);
drh3a4c1412004-05-09 20:40:11 +00004282 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
4283 pPage->pgno, nOld, nNew, nCell));
drh8b2f49b2001-06-08 00:21:52 +00004284 return rc;
4285}
4286
4287/*
drh43605152004-05-29 21:46:49 +00004288** This routine is called for the root page of a btree when the root
4289** page contains no cells. This is an opportunity to make the tree
4290** shallower by one level.
4291*/
4292static int balance_shallower(MemPage *pPage){
4293 MemPage *pChild; /* The only child page of pPage */
4294 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00004295 int rc = SQLITE_OK; /* Return code from subprocedures */
4296 Btree *pBt; /* The main BTree structure */
4297 int mxCellPerPage; /* Maximum number of cells per page */
4298 u8 **apCell; /* All cells from pages being balanced */
4299 int *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00004300
4301 assert( pPage->pParent==0 );
4302 assert( pPage->nCell==0 );
drh2e38c322004-09-03 18:38:44 +00004303 pBt = pPage->pBt;
4304 mxCellPerPage = MX_CELL(pBt);
4305 apCell = sqliteMallocRaw( mxCellPerPage*(sizeof(u8*)+sizeof(int)) );
4306 if( apCell==0 ) return SQLITE_NOMEM;
4307 szCell = (int*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00004308 if( pPage->leaf ){
4309 /* The table is completely empty */
4310 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
4311 }else{
4312 /* The root page is empty but has one child. Transfer the
4313 ** information from that one child into the root page if it
4314 ** will fit. This reduces the depth of the tree by one.
4315 **
4316 ** If the root page is page 1, it has less space available than
4317 ** its child (due to the 100 byte header that occurs at the beginning
4318 ** of the database fle), so it might not be able to hold all of the
4319 ** information currently contained in the child. If this is the
4320 ** case, then do not do the transfer. Leave page 1 empty except
4321 ** for the right-pointer to the child page. The child page becomes
4322 ** the virtual root of the tree.
4323 */
4324 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
4325 assert( pgnoChild>0 );
4326 assert( pgnoChild<=sqlite3pager_pagecount(pPage->pBt->pPager) );
4327 rc = getPage(pPage->pBt, pgnoChild, &pChild);
drh2e38c322004-09-03 18:38:44 +00004328 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004329 if( pPage->pgno==1 ){
4330 rc = initPage(pChild, pPage);
drh2e38c322004-09-03 18:38:44 +00004331 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004332 assert( pChild->nOverflow==0 );
4333 if( pChild->nFree>=100 ){
4334 /* The child information will fit on the root page, so do the
4335 ** copy */
4336 int i;
4337 zeroPage(pPage, pChild->aData[0]);
4338 for(i=0; i<pChild->nCell; i++){
4339 apCell[i] = findCell(pChild,i);
4340 szCell[i] = cellSizePtr(pChild, apCell[i]);
4341 }
4342 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00004343 /* Copy the right-pointer of the child to the parent. */
4344 put4byte(&pPage->aData[pPage->hdrOffset+8],
4345 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh43605152004-05-29 21:46:49 +00004346 freePage(pChild);
4347 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
4348 }else{
4349 /* The child has more information that will fit on the root.
4350 ** The tree is already balanced. Do nothing. */
4351 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
4352 }
4353 }else{
4354 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
4355 pPage->isInit = 0;
4356 pPage->pParent = 0;
4357 rc = initPage(pPage, 0);
4358 assert( rc==SQLITE_OK );
4359 freePage(pChild);
4360 TRACE(("BALANCE: transfer child %d into root %d\n",
4361 pChild->pgno, pPage->pgno));
4362 }
danielk1977afcdd022004-10-31 16:25:42 +00004363 rc = reparentChildPages(pPage);
danielk1977ac11ee62005-01-15 12:45:51 +00004364 assert( pPage->nOverflow==0 );
4365#ifndef SQLITE_OMIT_AUTOVACUUM
4366 if( pBt->autoVacuum ){
danielk1977aac0a382005-01-16 11:07:06 +00004367 int i;
danielk1977ac11ee62005-01-15 12:45:51 +00004368 for(i=0; i<pPage->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00004369 rc = ptrmapPutOvfl(pPage, i);
4370 if( rc!=SQLITE_OK ){
4371 goto end_shallow_balance;
danielk1977ac11ee62005-01-15 12:45:51 +00004372 }
4373 }
4374 }
4375#endif
danielk1977afcdd022004-10-31 16:25:42 +00004376 if( rc!=SQLITE_OK ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004377 releasePage(pChild);
4378 }
drh2e38c322004-09-03 18:38:44 +00004379end_shallow_balance:
4380 sqliteFree(apCell);
4381 return rc;
drh43605152004-05-29 21:46:49 +00004382}
4383
4384
4385/*
4386** The root page is overfull
4387**
4388** When this happens, Create a new child page and copy the
4389** contents of the root into the child. Then make the root
4390** page an empty page with rightChild pointing to the new
4391** child. Finally, call balance_internal() on the new child
4392** to cause it to split.
4393*/
4394static int balance_deeper(MemPage *pPage){
4395 int rc; /* Return value from subprocedures */
4396 MemPage *pChild; /* Pointer to a new child page */
4397 Pgno pgnoChild; /* Page number of the new child page */
4398 Btree *pBt; /* The BTree */
4399 int usableSize; /* Total usable size of a page */
4400 u8 *data; /* Content of the parent page */
4401 u8 *cdata; /* Content of the child page */
4402 int hdr; /* Offset to page header in parent */
4403 int brk; /* Offset to content of first cell in parent */
4404
4405 assert( pPage->pParent==0 );
4406 assert( pPage->nOverflow>0 );
4407 pBt = pPage->pBt;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004408 rc = allocatePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00004409 if( rc ) return rc;
4410 assert( sqlite3pager_iswriteable(pChild->aData) );
4411 usableSize = pBt->usableSize;
4412 data = pPage->aData;
4413 hdr = pPage->hdrOffset;
4414 brk = get2byte(&data[hdr+5]);
4415 cdata = pChild->aData;
4416 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
4417 memcpy(&cdata[brk], &data[brk], usableSize-brk);
danielk1977c7dc7532004-11-17 10:22:03 +00004418 assert( pChild->isInit==0 );
drh43605152004-05-29 21:46:49 +00004419 rc = initPage(pChild, pPage);
danielk19776b456a22005-03-21 04:04:02 +00004420 if( rc ) goto balancedeeper_out;
drh43605152004-05-29 21:46:49 +00004421 memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
4422 pChild->nOverflow = pPage->nOverflow;
4423 if( pChild->nOverflow ){
4424 pChild->nFree = 0;
4425 }
4426 assert( pChild->nCell==pPage->nCell );
4427 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
4428 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
4429 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
danielk19774e17d142005-01-16 09:06:33 +00004430#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00004431 if( pBt->autoVacuum ){
4432 int i;
4433 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
danielk19776b456a22005-03-21 04:04:02 +00004434 if( rc ) goto balancedeeper_out;
danielk1977ac11ee62005-01-15 12:45:51 +00004435 for(i=0; i<pChild->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00004436 rc = ptrmapPutOvfl(pChild, i);
4437 if( rc!=SQLITE_OK ){
4438 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00004439 }
4440 }
4441 }
danielk19774e17d142005-01-16 09:06:33 +00004442#endif
drh43605152004-05-29 21:46:49 +00004443 rc = balance_nonroot(pChild);
danielk19776b456a22005-03-21 04:04:02 +00004444
4445balancedeeper_out:
drh43605152004-05-29 21:46:49 +00004446 releasePage(pChild);
4447 return rc;
4448}
4449
4450/*
4451** Decide if the page pPage needs to be balanced. If balancing is
4452** required, call the appropriate balancing routine.
4453*/
danielk1977ac245ec2005-01-14 13:50:11 +00004454static int balance(MemPage *pPage, int insert){
drh43605152004-05-29 21:46:49 +00004455 int rc = SQLITE_OK;
4456 if( pPage->pParent==0 ){
4457 if( pPage->nOverflow>0 ){
4458 rc = balance_deeper(pPage);
4459 }
danielk1977687566d2004-11-02 12:56:41 +00004460 if( rc==SQLITE_OK && pPage->nCell==0 ){
drh43605152004-05-29 21:46:49 +00004461 rc = balance_shallower(pPage);
4462 }
4463 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00004464 if( pPage->nOverflow>0 ||
4465 (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
drh43605152004-05-29 21:46:49 +00004466 rc = balance_nonroot(pPage);
4467 }
4468 }
4469 return rc;
4470}
4471
4472/*
drh8dcd7ca2004-08-08 19:43:29 +00004473** This routine checks all cursors that point to table pgnoRoot.
4474** If any of those cursors other than pExclude were opened with
drhf74b8d92002-09-01 23:20:45 +00004475** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
drh8dcd7ca2004-08-08 19:43:29 +00004476** cursors that point to pgnoRoot were opened with wrFlag==1
drhf74b8d92002-09-01 23:20:45 +00004477** then this routine returns SQLITE_OK.
danielk1977299b1872004-11-22 10:02:10 +00004478**
4479** In addition to checking for read-locks (where a read-lock
4480** means a cursor opened with wrFlag==0) this routine also moves
4481** all cursors other than pExclude so that they are pointing to the
4482** first Cell on root page. This is necessary because an insert
4483** or delete might change the number of cells on a page or delete
4484** a page entirely and we do not want to leave any cursors
4485** pointing to non-existant pages or cells.
drhf74b8d92002-09-01 23:20:45 +00004486*/
drh8dcd7ca2004-08-08 19:43:29 +00004487static int checkReadLocks(Btree *pBt, Pgno pgnoRoot, BtCursor *pExclude){
danielk1977299b1872004-11-22 10:02:10 +00004488 BtCursor *p;
4489 for(p=pBt->pCursor; p; p=p->pNext){
4490 if( p->pgnoRoot!=pgnoRoot || p==pExclude ) continue;
4491 if( p->wrFlag==0 ) return SQLITE_LOCKED;
4492 if( p->pPage->pgno!=p->pgnoRoot ){
4493 moveToRoot(p);
4494 }
4495 }
drhf74b8d92002-09-01 23:20:45 +00004496 return SQLITE_OK;
4497}
4498
4499/*
drh3b7511c2001-05-26 13:15:44 +00004500** Insert a new record into the BTree. The key is given by (pKey,nKey)
4501** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00004502** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00004503** is left pointing at a random location.
4504**
4505** For an INTKEY table, only the nKey value of the key is used. pKey is
4506** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00004507*/
drh3aac2dd2004-04-26 14:10:20 +00004508int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00004509 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00004510 const void *pKey, i64 nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00004511 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00004512){
drh3b7511c2001-05-26 13:15:44 +00004513 int rc;
4514 int loc;
drh14acc042001-06-10 19:56:58 +00004515 int szNew;
drh3b7511c2001-05-26 13:15:44 +00004516 MemPage *pPage;
4517 Btree *pBt = pCur->pBt;
drha34b6762004-05-07 13:30:42 +00004518 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00004519 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00004520
danielk1977ee5741e2004-05-31 10:01:34 +00004521 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00004522 /* Must start a transaction before doing an insert */
4523 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00004524 }
drhf74b8d92002-09-01 23:20:45 +00004525 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00004526 if( !pCur->wrFlag ){
4527 return SQLITE_PERM; /* Cursor not open for writing */
4528 }
drh8dcd7ca2004-08-08 19:43:29 +00004529 if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00004530 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
4531 }
drh3aac2dd2004-04-26 14:10:20 +00004532 rc = sqlite3BtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00004533 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00004534 pPage = pCur->pPage;
drh4a1c3802004-05-12 15:15:47 +00004535 assert( pPage->intKey || nKey>=0 );
drh8b18dd42004-05-12 19:18:15 +00004536 assert( pPage->leaf || !pPage->leafData );
drh3a4c1412004-05-09 20:40:11 +00004537 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
4538 pCur->pgnoRoot, nKey, nData, pPage->pgno,
4539 loc==0 ? "overwrite" : "new entry"));
drh7aa128d2002-06-21 13:09:16 +00004540 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004541 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00004542 if( rc ) return rc;
drh2e38c322004-09-03 18:38:44 +00004543 newCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
4544 if( newCell==0 ) return SQLITE_NOMEM;
drha34b6762004-05-07 13:30:42 +00004545 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, &szNew);
drh2e38c322004-09-03 18:38:44 +00004546 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00004547 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00004548 assert( szNew<=MX_CELL_SIZE(pBt) );
drhf328bc82004-05-10 23:29:49 +00004549 if( loc==0 && pCur->isValid ){
drha34b6762004-05-07 13:30:42 +00004550 int szOld;
4551 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00004552 oldCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00004553 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004554 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00004555 }
drh43605152004-05-29 21:46:49 +00004556 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00004557 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00004558 if( rc ) goto end_insert;
drh4b70f112004-05-02 21:12:19 +00004559 dropCell(pPage, pCur->idx, szOld);
drh7c717f72001-06-24 20:39:41 +00004560 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00004561 assert( pPage->leaf );
drh14acc042001-06-10 19:56:58 +00004562 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00004563 pCur->info.nSize = 0;
drh14acc042001-06-10 19:56:58 +00004564 }else{
drh4b70f112004-05-02 21:12:19 +00004565 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00004566 }
danielk1977a3ad5e72005-01-07 08:56:44 +00004567 rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
danielk1977e80463b2004-11-03 03:01:16 +00004568 if( rc!=SQLITE_OK ) goto end_insert;
danielk1977ac245ec2005-01-14 13:50:11 +00004569 rc = balance(pPage, 1);
drh23e11ca2004-05-04 17:27:28 +00004570 /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
drh3fc190c2001-09-14 03:24:23 +00004571 /* fflush(stdout); */
danielk1977299b1872004-11-22 10:02:10 +00004572 if( rc==SQLITE_OK ){
4573 moveToRoot(pCur);
4574 }
drh2e38c322004-09-03 18:38:44 +00004575end_insert:
4576 sqliteFree(newCell);
drh5e2f8b92001-05-28 00:41:15 +00004577 return rc;
4578}
4579
4580/*
drh4b70f112004-05-02 21:12:19 +00004581** Delete the entry that the cursor is pointing to. The cursor
4582** is left pointing at a random location.
drh3b7511c2001-05-26 13:15:44 +00004583*/
drh3aac2dd2004-04-26 14:10:20 +00004584int sqlite3BtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00004585 MemPage *pPage = pCur->pPage;
drh4b70f112004-05-02 21:12:19 +00004586 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00004587 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00004588 Pgno pgnoChild = 0;
drh0d316a42002-08-11 20:10:47 +00004589 Btree *pBt = pCur->pBt;
drh8b2f49b2001-06-08 00:21:52 +00004590
drh7aa128d2002-06-21 13:09:16 +00004591 assert( pPage->isInit );
danielk1977ee5741e2004-05-31 10:01:34 +00004592 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00004593 /* Must start a transaction before doing a delete */
4594 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00004595 }
drhf74b8d92002-09-01 23:20:45 +00004596 assert( !pBt->readOnly );
drhbd03cae2001-06-02 02:40:57 +00004597 if( pCur->idx >= pPage->nCell ){
4598 return SQLITE_ERROR; /* The cursor is not pointing to anything */
4599 }
drhecdc7532001-09-23 02:35:53 +00004600 if( !pCur->wrFlag ){
4601 return SQLITE_PERM; /* Did not open this cursor for writing */
4602 }
drh8dcd7ca2004-08-08 19:43:29 +00004603 if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00004604 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
4605 }
drha34b6762004-05-07 13:30:42 +00004606 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00004607 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00004608
4609 /* Locate the cell within it's page and leave pCell pointing to the
4610 ** data. The clearCell() call frees any overflow pages associated with the
4611 ** cell. The cell itself is still intact.
4612 */
danielk1977299b1872004-11-22 10:02:10 +00004613 pCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00004614 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004615 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00004616 }
danielk197728129562005-01-11 10:25:06 +00004617 rc = clearCell(pPage, pCell);
4618 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00004619
drh4b70f112004-05-02 21:12:19 +00004620 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00004621 /*
drh5e00f6c2001-09-13 13:46:56 +00004622 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00004623 ** do something we will leave a hole on an internal page.
4624 ** We have to fill the hole by moving in a cell from a leaf. The
4625 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00004626 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00004627 */
drh14acc042001-06-10 19:56:58 +00004628 BtCursor leafCur;
drh4b70f112004-05-02 21:12:19 +00004629 unsigned char *pNext;
drh14acc042001-06-10 19:56:58 +00004630 int szNext;
danielk1977299b1872004-11-22 10:02:10 +00004631 int notUsed;
danielk19776b456a22005-03-21 04:04:02 +00004632 unsigned char *tempCell = 0;
drh8b18dd42004-05-12 19:18:15 +00004633 assert( !pPage->leafData );
drh14acc042001-06-10 19:56:58 +00004634 getTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00004635 rc = sqlite3BtreeNext(&leafCur, &notUsed);
drh14acc042001-06-10 19:56:58 +00004636 if( rc!=SQLITE_OK ){
drhee696e22004-08-30 16:52:17 +00004637 if( rc!=SQLITE_NOMEM ){
4638 rc = SQLITE_CORRUPT; /* bkpt-CORRUPT */
4639 }
drh5e2f8b92001-05-28 00:41:15 +00004640 }
danielk19776b456a22005-03-21 04:04:02 +00004641 if( rc==SQLITE_OK ){
4642 rc = sqlite3pager_write(leafCur.pPage->aData);
4643 }
4644 if( rc==SQLITE_OK ){
4645 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
4646 pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
4647 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
4648 pNext = findCell(leafCur.pPage, leafCur.idx);
4649 szNext = cellSizePtr(leafCur.pPage, pNext);
4650 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
4651 tempCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
4652 if( tempCell==0 ){
4653 rc = SQLITE_NOMEM;
4654 }
4655 }
4656 if( rc==SQLITE_OK ){
4657 rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
4658 }
4659 if( rc==SQLITE_OK ){
4660 put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
4661 rc = balance(pPage, 0);
4662 }
4663 if( rc==SQLITE_OK ){
4664 dropCell(leafCur.pPage, leafCur.idx, szNext);
4665 rc = balance(leafCur.pPage, 0);
4666 }
drh2e38c322004-09-03 18:38:44 +00004667 sqliteFree(tempCell);
drh8c42ca92001-06-22 19:15:00 +00004668 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00004669 }else{
danielk1977299b1872004-11-22 10:02:10 +00004670 TRACE(("DELETE: table=%d delete from leaf %d\n",
4671 pCur->pgnoRoot, pPage->pgno));
4672 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
danielk1977ac245ec2005-01-14 13:50:11 +00004673 rc = balance(pPage, 0);
drh5e2f8b92001-05-28 00:41:15 +00004674 }
danielk19776b456a22005-03-21 04:04:02 +00004675 if( rc==SQLITE_OK ){
4676 moveToRoot(pCur);
4677 }
drh5e2f8b92001-05-28 00:41:15 +00004678 return rc;
drh3b7511c2001-05-26 13:15:44 +00004679}
drh8b2f49b2001-06-08 00:21:52 +00004680
4681/*
drhc6b52df2002-01-04 03:09:29 +00004682** Create a new BTree table. Write into *piTable the page
4683** number for the root page of the new table.
4684**
drhab01f612004-05-22 02:55:23 +00004685** The type of type is determined by the flags parameter. Only the
4686** following values of flags are currently in use. Other values for
4687** flags might not work:
4688**
4689** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
4690** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00004691*/
drh3aac2dd2004-04-26 14:10:20 +00004692int sqlite3BtreeCreateTable(Btree *pBt, int *piTable, int flags){
drh8b2f49b2001-06-08 00:21:52 +00004693 MemPage *pRoot;
4694 Pgno pgnoRoot;
4695 int rc;
danielk1977ee5741e2004-05-31 10:01:34 +00004696 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00004697 /* Must start a transaction first */
4698 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00004699 }
danielk197728129562005-01-11 10:25:06 +00004700 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00004701
4702 /* It is illegal to create a table if any cursors are open on the
4703 ** database. This is because in auto-vacuum mode the backend may
4704 ** need to move a database page to make room for the new root-page.
4705 ** If an open cursor was using the page a problem would occur.
4706 */
4707 if( pBt->pCursor ){
4708 return SQLITE_LOCKED;
4709 }
4710
danielk1977003ba062004-11-04 02:57:33 +00004711#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977cb1a7eb2004-11-05 12:27:02 +00004712 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drh8b2f49b2001-06-08 00:21:52 +00004713 if( rc ) return rc;
danielk1977003ba062004-11-04 02:57:33 +00004714#else
danielk1977687566d2004-11-02 12:56:41 +00004715 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00004716 Pgno pgnoMove; /* Move a page here to make room for the root-page */
4717 MemPage *pPageMove; /* The page to move to. */
4718
danielk1977003ba062004-11-04 02:57:33 +00004719 /* Read the value of meta[3] from the database to determine where the
4720 ** root page of the new table should go. meta[3] is the largest root-page
4721 ** created so far, so the new root-page is (meta[3]+1).
4722 */
4723 rc = sqlite3BtreeGetMeta(pBt, 4, &pgnoRoot);
4724 if( rc!=SQLITE_OK ) return rc;
4725 pgnoRoot++;
4726
danielk1977599fcba2004-11-08 07:13:13 +00004727 /* The new root-page may not be allocated on a pointer-map page, or the
4728 ** PENDING_BYTE page.
4729 */
drh42cac6d2004-11-20 20:31:11 +00004730 if( pgnoRoot==PTRMAP_PAGENO(pBt->usableSize, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00004731 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00004732 pgnoRoot++;
4733 }
4734 assert( pgnoRoot>=3 );
4735
4736 /* Allocate a page. The page that currently resides at pgnoRoot will
4737 ** be moved to the allocated page (unless the allocated page happens
4738 ** to reside at pgnoRoot).
4739 */
danielk1977cb1a7eb2004-11-05 12:27:02 +00004740 rc = allocatePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00004741 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00004742 return rc;
4743 }
danielk1977003ba062004-11-04 02:57:33 +00004744
4745 if( pgnoMove!=pgnoRoot ){
4746 u8 eType;
4747 Pgno iPtrPage;
4748
4749 releasePage(pPageMove);
4750 rc = getPage(pBt, pgnoRoot, &pRoot);
4751 if( rc!=SQLITE_OK ){
4752 return rc;
4753 }
4754 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drhccae6022005-02-26 17:31:26 +00004755 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00004756 releasePage(pRoot);
4757 return rc;
4758 }
drhccae6022005-02-26 17:31:26 +00004759 assert( eType!=PTRMAP_ROOTPAGE );
4760 assert( eType!=PTRMAP_FREEPAGE );
danielk19775fd057a2005-03-09 13:09:43 +00004761 rc = sqlite3pager_write(pRoot->aData);
4762 if( rc!=SQLITE_OK ){
4763 releasePage(pRoot);
4764 return rc;
4765 }
danielk1977003ba062004-11-04 02:57:33 +00004766 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove);
4767 releasePage(pRoot);
4768 if( rc!=SQLITE_OK ){
4769 return rc;
4770 }
4771 rc = getPage(pBt, pgnoRoot, &pRoot);
4772 if( rc!=SQLITE_OK ){
4773 return rc;
4774 }
4775 rc = sqlite3pager_write(pRoot->aData);
4776 if( rc!=SQLITE_OK ){
4777 releasePage(pRoot);
4778 return rc;
4779 }
4780 }else{
4781 pRoot = pPageMove;
4782 }
4783
danielk197742741be2005-01-08 12:42:39 +00004784 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00004785 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
4786 if( rc ){
4787 releasePage(pRoot);
4788 return rc;
4789 }
4790 rc = sqlite3BtreeUpdateMeta(pBt, 4, pgnoRoot);
4791 if( rc ){
4792 releasePage(pRoot);
4793 return rc;
4794 }
danielk197742741be2005-01-08 12:42:39 +00004795
danielk1977003ba062004-11-04 02:57:33 +00004796 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004797 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00004798 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00004799 }
4800#endif
drha34b6762004-05-07 13:30:42 +00004801 assert( sqlite3pager_iswriteable(pRoot->aData) );
drhde647132004-05-07 17:57:49 +00004802 zeroPage(pRoot, flags | PTF_LEAF);
drha34b6762004-05-07 13:30:42 +00004803 sqlite3pager_unref(pRoot->aData);
drh8b2f49b2001-06-08 00:21:52 +00004804 *piTable = (int)pgnoRoot;
4805 return SQLITE_OK;
4806}
4807
4808/*
4809** Erase the given database page and all its children. Return
4810** the page to the freelist.
4811*/
drh4b70f112004-05-02 21:12:19 +00004812static int clearDatabasePage(
4813 Btree *pBt, /* The BTree that contains the table */
4814 Pgno pgno, /* Page number to clear */
4815 MemPage *pParent, /* Parent page. NULL for the root */
4816 int freePageFlag /* Deallocate page if true */
4817){
danielk19776b456a22005-03-21 04:04:02 +00004818 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00004819 int rc;
drh4b70f112004-05-02 21:12:19 +00004820 unsigned char *pCell;
4821 int i;
drh8b2f49b2001-06-08 00:21:52 +00004822
danielk1977a1cb1832005-02-12 08:59:55 +00004823 if( pgno>sqlite3pager_pagecount(pBt->pPager) ){
4824 return SQLITE_CORRUPT;
4825 }
4826
drhde647132004-05-07 17:57:49 +00004827 rc = getAndInitPage(pBt, pgno, &pPage, pParent);
danielk19776b456a22005-03-21 04:04:02 +00004828 if( rc ) goto cleardatabasepage_out;
drha34b6762004-05-07 13:30:42 +00004829 rc = sqlite3pager_write(pPage->aData);
danielk19776b456a22005-03-21 04:04:02 +00004830 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00004831 for(i=0; i<pPage->nCell; i++){
drh43605152004-05-29 21:46:49 +00004832 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00004833 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004834 rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00004835 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00004836 }
drh4b70f112004-05-02 21:12:19 +00004837 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00004838 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00004839 }
drha34b6762004-05-07 13:30:42 +00004840 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004841 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00004842 if( rc ) goto cleardatabasepage_out;
drh2aa679f2001-06-25 02:11:07 +00004843 }
4844 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00004845 rc = freePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00004846 }else{
drh3a4c1412004-05-09 20:40:11 +00004847 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00004848 }
danielk19776b456a22005-03-21 04:04:02 +00004849
4850cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00004851 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00004852 return rc;
drh8b2f49b2001-06-08 00:21:52 +00004853}
4854
4855/*
drhab01f612004-05-22 02:55:23 +00004856** Delete all information from a single table in the database. iTable is
4857** the page number of the root of the table. After this routine returns,
4858** the root page is empty, but still exists.
4859**
4860** This routine will fail with SQLITE_LOCKED if there are any open
4861** read cursors on the table. Open write cursors are moved to the
4862** root of the table.
drh8b2f49b2001-06-08 00:21:52 +00004863*/
drh3aac2dd2004-04-26 14:10:20 +00004864int sqlite3BtreeClearTable(Btree *pBt, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00004865 int rc;
drhf74b8d92002-09-01 23:20:45 +00004866 BtCursor *pCur;
danielk1977ee5741e2004-05-31 10:01:34 +00004867 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00004868 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00004869 }
drhf74b8d92002-09-01 23:20:45 +00004870 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
4871 if( pCur->pgnoRoot==(Pgno)iTable ){
4872 if( pCur->wrFlag==0 ) return SQLITE_LOCKED;
4873 moveToRoot(pCur);
4874 }
drhecdc7532001-09-23 02:35:53 +00004875 }
drha34b6762004-05-07 13:30:42 +00004876 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
drh8b2f49b2001-06-08 00:21:52 +00004877 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00004878 sqlite3BtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00004879 }
drh8c42ca92001-06-22 19:15:00 +00004880 return rc;
drh8b2f49b2001-06-08 00:21:52 +00004881}
4882
4883/*
4884** Erase all information in a table and add the root of the table to
4885** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00004886** page 1) is never added to the freelist.
4887**
4888** This routine will fail with SQLITE_LOCKED if there are any open
4889** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00004890**
4891** If AUTOVACUUM is enabled and the page at iTable is not the last
4892** root page in the database file, then the last root page
4893** in the database file is moved into the slot formerly occupied by
4894** iTable and that last slot formerly occupied by the last root page
4895** is added to the freelist instead of iTable. In this say, all
4896** root pages are kept at the beginning of the database file, which
4897** is necessary for AUTOVACUUM to work right. *piMoved is set to the
4898** page number that used to be the last root page in the file before
4899** the move. If no page gets moved, *piMoved is set to 0.
4900** The last root page is recorded in meta[3] and the value of
4901** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00004902*/
danielk1977a0bf2652004-11-04 14:30:04 +00004903int sqlite3BtreeDropTable(Btree *pBt, int iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00004904 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00004905 MemPage *pPage = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00004906
danielk1977ee5741e2004-05-31 10:01:34 +00004907 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00004908 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00004909 }
danielk1977a0bf2652004-11-04 14:30:04 +00004910
danielk1977e6efa742004-11-10 11:55:10 +00004911 /* It is illegal to drop a table if any cursors are open on the
4912 ** database. This is because in auto-vacuum mode the backend may
4913 ** need to move another root-page to fill a gap left by the deleted
4914 ** root page. If an open cursor was using this page a problem would
4915 ** occur.
4916 */
4917 if( pBt->pCursor ){
4918 return SQLITE_LOCKED;
drh5df72a52002-06-06 23:16:05 +00004919 }
danielk1977a0bf2652004-11-04 14:30:04 +00004920
drha34b6762004-05-07 13:30:42 +00004921 rc = getPage(pBt, (Pgno)iTable, &pPage);
drh2aa679f2001-06-25 02:11:07 +00004922 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004923 rc = sqlite3BtreeClearTable(pBt, iTable);
danielk19776b456a22005-03-21 04:04:02 +00004924 if( rc ){
4925 releasePage(pPage);
4926 return rc;
4927 }
danielk1977a0bf2652004-11-04 14:30:04 +00004928
drh205f48e2004-11-05 00:43:11 +00004929 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00004930
drh4b70f112004-05-02 21:12:19 +00004931 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00004932#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00004933 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00004934 releasePage(pPage);
4935#else
4936 if( pBt->autoVacuum ){
4937 Pgno maxRootPgno;
4938 rc = sqlite3BtreeGetMeta(pBt, 4, &maxRootPgno);
4939 if( rc!=SQLITE_OK ){
4940 releasePage(pPage);
4941 return rc;
4942 }
4943
4944 if( iTable==maxRootPgno ){
4945 /* If the table being dropped is the table with the largest root-page
4946 ** number in the database, put the root page on the free list.
4947 */
4948 rc = freePage(pPage);
4949 releasePage(pPage);
4950 if( rc!=SQLITE_OK ){
4951 return rc;
4952 }
4953 }else{
4954 /* The table being dropped does not have the largest root-page
4955 ** number in the database. So move the page that does into the
4956 ** gap left by the deleted root-page.
4957 */
4958 MemPage *pMove;
4959 releasePage(pPage);
4960 rc = getPage(pBt, maxRootPgno, &pMove);
4961 if( rc!=SQLITE_OK ){
4962 return rc;
4963 }
4964 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable);
4965 releasePage(pMove);
4966 if( rc!=SQLITE_OK ){
4967 return rc;
4968 }
4969 rc = getPage(pBt, maxRootPgno, &pMove);
4970 if( rc!=SQLITE_OK ){
4971 return rc;
4972 }
4973 rc = freePage(pMove);
4974 releasePage(pMove);
4975 if( rc!=SQLITE_OK ){
4976 return rc;
4977 }
4978 *piMoved = maxRootPgno;
4979 }
4980
danielk1977599fcba2004-11-08 07:13:13 +00004981 /* Set the new 'max-root-page' value in the database header. This
4982 ** is the old value less one, less one more if that happens to
4983 ** be a root-page number, less one again if that is the
4984 ** PENDING_BYTE_PAGE.
4985 */
danielk197787a6e732004-11-05 12:58:25 +00004986 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00004987 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
4988 maxRootPgno--;
4989 }
drh42cac6d2004-11-20 20:31:11 +00004990 if( maxRootPgno==PTRMAP_PAGENO(pBt->usableSize, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00004991 maxRootPgno--;
4992 }
danielk1977599fcba2004-11-08 07:13:13 +00004993 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
4994
danielk197787a6e732004-11-05 12:58:25 +00004995 rc = sqlite3BtreeUpdateMeta(pBt, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00004996 }else{
4997 rc = freePage(pPage);
4998 releasePage(pPage);
4999 }
5000#endif
drh2aa679f2001-06-25 02:11:07 +00005001 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00005002 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00005003 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00005004 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00005005 }
drh8b2f49b2001-06-08 00:21:52 +00005006 return rc;
5007}
5008
drh001bbcb2003-03-19 03:14:00 +00005009
drh8b2f49b2001-06-08 00:21:52 +00005010/*
drh23e11ca2004-05-04 17:27:28 +00005011** Read the meta-information out of a database file. Meta[0]
5012** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00005013** through meta[15] are available for use by higher layers. Meta[0]
5014** is read-only, the others are read/write.
5015**
5016** The schema layer numbers meta values differently. At the schema
5017** layer (and the SetCookie and ReadCookie opcodes) the number of
5018** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00005019*/
drh3aac2dd2004-04-26 14:10:20 +00005020int sqlite3BtreeGetMeta(Btree *pBt, int idx, u32 *pMeta){
drh8b2f49b2001-06-08 00:21:52 +00005021 int rc;
drh4b70f112004-05-02 21:12:19 +00005022 unsigned char *pP1;
drh8b2f49b2001-06-08 00:21:52 +00005023
drh23e11ca2004-05-04 17:27:28 +00005024 assert( idx>=0 && idx<=15 );
drha34b6762004-05-07 13:30:42 +00005025 rc = sqlite3pager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00005026 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00005027 *pMeta = get4byte(&pP1[36 + idx*4]);
drha34b6762004-05-07 13:30:42 +00005028 sqlite3pager_unref(pP1);
drhae157872004-08-14 19:20:09 +00005029
danielk1977599fcba2004-11-08 07:13:13 +00005030 /* If autovacuumed is disabled in this build but we are trying to
5031 ** access an autovacuumed database, then make the database readonly.
5032 */
danielk1977003ba062004-11-04 02:57:33 +00005033#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00005034 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00005035#endif
drhae157872004-08-14 19:20:09 +00005036
drh8b2f49b2001-06-08 00:21:52 +00005037 return SQLITE_OK;
5038}
5039
5040/*
drh23e11ca2004-05-04 17:27:28 +00005041** Write meta-information back into the database. Meta[0] is
5042** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00005043*/
drh3aac2dd2004-04-26 14:10:20 +00005044int sqlite3BtreeUpdateMeta(Btree *pBt, int idx, u32 iMeta){
drh4b70f112004-05-02 21:12:19 +00005045 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00005046 int rc;
drh23e11ca2004-05-04 17:27:28 +00005047 assert( idx>=1 && idx<=15 );
danielk1977ee5741e2004-05-31 10:01:34 +00005048 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005049 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +00005050 }
drhde647132004-05-07 17:57:49 +00005051 assert( pBt->pPage1!=0 );
5052 pP1 = pBt->pPage1->aData;
drha34b6762004-05-07 13:30:42 +00005053 rc = sqlite3pager_write(pP1);
drh4b70f112004-05-02 21:12:19 +00005054 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00005055 put4byte(&pP1[36 + idx*4], iMeta);
drh8b2f49b2001-06-08 00:21:52 +00005056 return SQLITE_OK;
5057}
drh8c42ca92001-06-22 19:15:00 +00005058
drhf328bc82004-05-10 23:29:49 +00005059/*
5060** Return the flag byte at the beginning of the page that the cursor
5061** is currently pointing to.
5062*/
5063int sqlite3BtreeFlags(BtCursor *pCur){
5064 MemPage *pPage = pCur->pPage;
5065 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
5066}
5067
danielk1977b5402fb2005-01-12 07:15:04 +00005068#ifdef SQLITE_DEBUG
drh8c42ca92001-06-22 19:15:00 +00005069/*
5070** Print a disassembly of the given page on standard output. This routine
5071** is used for debugging and testing only.
5072*/
danielk1977c7dc7532004-11-17 10:22:03 +00005073static int btreePageDump(Btree *pBt, int pgno, int recursive, MemPage *pParent){
drh8c42ca92001-06-22 19:15:00 +00005074 int rc;
5075 MemPage *pPage;
drhc8629a12004-05-08 20:07:40 +00005076 int i, j, c;
drh8c42ca92001-06-22 19:15:00 +00005077 int nFree;
5078 u16 idx;
drhab9f7f12004-05-08 10:56:11 +00005079 int hdr;
drh43605152004-05-29 21:46:49 +00005080 int nCell;
drha2fce642004-06-05 00:01:44 +00005081 int isInit;
drhab9f7f12004-05-08 10:56:11 +00005082 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00005083 char range[20];
5084 unsigned char payload[20];
drhab9f7f12004-05-08 10:56:11 +00005085
drh4b70f112004-05-02 21:12:19 +00005086 rc = getPage(pBt, (Pgno)pgno, &pPage);
drha2fce642004-06-05 00:01:44 +00005087 isInit = pPage->isInit;
5088 if( pPage->isInit==0 ){
danielk1977c7dc7532004-11-17 10:22:03 +00005089 initPage(pPage, pParent);
drha2fce642004-06-05 00:01:44 +00005090 }
drh8c42ca92001-06-22 19:15:00 +00005091 if( rc ){
5092 return rc;
5093 }
drhab9f7f12004-05-08 10:56:11 +00005094 hdr = pPage->hdrOffset;
5095 data = pPage->aData;
drhc8629a12004-05-08 20:07:40 +00005096 c = data[hdr];
drh8b18dd42004-05-12 19:18:15 +00005097 pPage->intKey = (c & (PTF_INTKEY|PTF_LEAFDATA))!=0;
drhc8629a12004-05-08 20:07:40 +00005098 pPage->zeroData = (c & PTF_ZERODATA)!=0;
drh8b18dd42004-05-12 19:18:15 +00005099 pPage->leafData = (c & PTF_LEAFDATA)!=0;
drhc8629a12004-05-08 20:07:40 +00005100 pPage->leaf = (c & PTF_LEAF)!=0;
drh8b18dd42004-05-12 19:18:15 +00005101 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
drh43605152004-05-29 21:46:49 +00005102 nCell = get2byte(&data[hdr+3]);
drhfe63d1c2004-09-08 20:13:04 +00005103 sqlite3DebugPrintf("PAGE %d: flags=0x%02x frag=%d parent=%d\n", pgno,
drh43605152004-05-29 21:46:49 +00005104 data[hdr], data[hdr+7],
drhda200cc2004-05-09 11:51:38 +00005105 (pPage->isInit && pPage->pParent) ? pPage->pParent->pgno : 0);
drhab9f7f12004-05-08 10:56:11 +00005106 assert( hdr == (pgno==1 ? 100 : 0) );
drh43605152004-05-29 21:46:49 +00005107 idx = hdr + 12 - pPage->leaf*4;
5108 for(i=0; i<nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00005109 CellInfo info;
drh4b70f112004-05-02 21:12:19 +00005110 Pgno child;
drh43605152004-05-29 21:46:49 +00005111 unsigned char *pCell;
drh6f11bef2004-05-13 01:12:56 +00005112 int sz;
drh43605152004-05-29 21:46:49 +00005113 int addr;
drh6f11bef2004-05-13 01:12:56 +00005114
drh43605152004-05-29 21:46:49 +00005115 addr = get2byte(&data[idx + 2*i]);
5116 pCell = &data[addr];
5117 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005118 sz = info.nSize;
drh43605152004-05-29 21:46:49 +00005119 sprintf(range,"%d..%d", addr, addr+sz-1);
drh4b70f112004-05-02 21:12:19 +00005120 if( pPage->leaf ){
5121 child = 0;
5122 }else{
drh43605152004-05-29 21:46:49 +00005123 child = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005124 }
drh6f11bef2004-05-13 01:12:56 +00005125 sz = info.nData;
5126 if( !pPage->intKey ) sz += info.nKey;
drh8c42ca92001-06-22 19:15:00 +00005127 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
drh6f11bef2004-05-13 01:12:56 +00005128 memcpy(payload, &pCell[info.nHeader], sz);
drh8c42ca92001-06-22 19:15:00 +00005129 for(j=0; j<sz; j++){
5130 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
5131 }
5132 payload[sz] = 0;
drhfe63d1c2004-09-08 20:13:04 +00005133 sqlite3DebugPrintf(
drh6f11bef2004-05-13 01:12:56 +00005134 "cell %2d: i=%-10s chld=%-4d nk=%-4lld nd=%-4d payload=%s\n",
5135 i, range, child, info.nKey, info.nData, payload
drh8c42ca92001-06-22 19:15:00 +00005136 );
drh8c42ca92001-06-22 19:15:00 +00005137 }
drh4b70f112004-05-02 21:12:19 +00005138 if( !pPage->leaf ){
drhfe63d1c2004-09-08 20:13:04 +00005139 sqlite3DebugPrintf("right_child: %d\n", get4byte(&data[hdr+8]));
drh4b70f112004-05-02 21:12:19 +00005140 }
drh8c42ca92001-06-22 19:15:00 +00005141 nFree = 0;
5142 i = 0;
drhab9f7f12004-05-08 10:56:11 +00005143 idx = get2byte(&data[hdr+1]);
drhb6f41482004-05-14 01:58:11 +00005144 while( idx>0 && idx<pPage->pBt->usableSize ){
drhab9f7f12004-05-08 10:56:11 +00005145 int sz = get2byte(&data[idx+2]);
drh4b70f112004-05-02 21:12:19 +00005146 sprintf(range,"%d..%d", idx, idx+sz-1);
5147 nFree += sz;
drhfe63d1c2004-09-08 20:13:04 +00005148 sqlite3DebugPrintf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
drh4b70f112004-05-02 21:12:19 +00005149 i, range, sz, nFree);
drhab9f7f12004-05-08 10:56:11 +00005150 idx = get2byte(&data[idx]);
drh2aa679f2001-06-25 02:11:07 +00005151 i++;
drh8c42ca92001-06-22 19:15:00 +00005152 }
5153 if( idx!=0 ){
drhfe63d1c2004-09-08 20:13:04 +00005154 sqlite3DebugPrintf("ERROR: next freeblock index out of range: %d\n", idx);
drh8c42ca92001-06-22 19:15:00 +00005155 }
drha34b6762004-05-07 13:30:42 +00005156 if( recursive && !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005157 for(i=0; i<nCell; i++){
5158 unsigned char *pCell = findCell(pPage, i);
danielk1977c7dc7532004-11-17 10:22:03 +00005159 btreePageDump(pBt, get4byte(pCell), 1, pPage);
drha34b6762004-05-07 13:30:42 +00005160 idx = get2byte(pCell);
drh6019e162001-07-02 17:51:45 +00005161 }
danielk1977c7dc7532004-11-17 10:22:03 +00005162 btreePageDump(pBt, get4byte(&data[hdr+8]), 1, pPage);
drh6019e162001-07-02 17:51:45 +00005163 }
drha2fce642004-06-05 00:01:44 +00005164 pPage->isInit = isInit;
drhab9f7f12004-05-08 10:56:11 +00005165 sqlite3pager_unref(data);
drh3644f082004-05-10 18:45:09 +00005166 fflush(stdout);
drh8c42ca92001-06-22 19:15:00 +00005167 return SQLITE_OK;
5168}
danielk1977c7dc7532004-11-17 10:22:03 +00005169int sqlite3BtreePageDump(Btree *pBt, int pgno, int recursive){
5170 return btreePageDump(pBt, pgno, recursive, 0);
5171}
drhaaab5722002-02-19 13:39:21 +00005172#endif
drh8c42ca92001-06-22 19:15:00 +00005173
drhaaab5722002-02-19 13:39:21 +00005174#ifdef SQLITE_TEST
drh8c42ca92001-06-22 19:15:00 +00005175/*
drh2aa679f2001-06-25 02:11:07 +00005176** Fill aResult[] with information about the entry and page that the
5177** cursor is pointing to.
5178**
5179** aResult[0] = The page number
5180** aResult[1] = The entry number
5181** aResult[2] = Total number of entries on this page
drh3e27c022004-07-23 00:01:38 +00005182** aResult[3] = Cell size (local payload + header)
drh2aa679f2001-06-25 02:11:07 +00005183** aResult[4] = Number of free bytes on this page
5184** aResult[5] = Number of free blocks on the page
drh3e27c022004-07-23 00:01:38 +00005185** aResult[6] = Total payload size (local + overflow)
5186** aResult[7] = Header size in bytes
5187** aResult[8] = Local payload size
5188** aResult[9] = Parent page number
drh5eddca62001-06-30 21:53:53 +00005189**
5190** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00005191*/
drh3e27c022004-07-23 00:01:38 +00005192int sqlite3BtreeCursorInfo(BtCursor *pCur, int *aResult, int upCnt){
drh2aa679f2001-06-25 02:11:07 +00005193 int cnt, idx;
5194 MemPage *pPage = pCur->pPage;
drh3e27c022004-07-23 00:01:38 +00005195 BtCursor tmpCur;
drhda200cc2004-05-09 11:51:38 +00005196
5197 pageIntegrity(pPage);
drh4b70f112004-05-02 21:12:19 +00005198 assert( pPage->isInit );
drh3e27c022004-07-23 00:01:38 +00005199 getTempCursor(pCur, &tmpCur);
5200 while( upCnt-- ){
5201 moveToParent(&tmpCur);
5202 }
5203 pPage = tmpCur.pPage;
5204 pageIntegrity(pPage);
drha34b6762004-05-07 13:30:42 +00005205 aResult[0] = sqlite3pager_pagenumber(pPage->aData);
drh91025292004-05-03 19:49:32 +00005206 assert( aResult[0]==pPage->pgno );
drh3e27c022004-07-23 00:01:38 +00005207 aResult[1] = tmpCur.idx;
drh2aa679f2001-06-25 02:11:07 +00005208 aResult[2] = pPage->nCell;
drh3e27c022004-07-23 00:01:38 +00005209 if( tmpCur.idx>=0 && tmpCur.idx<pPage->nCell ){
5210 getCellInfo(&tmpCur);
5211 aResult[3] = tmpCur.info.nSize;
5212 aResult[6] = tmpCur.info.nData;
5213 aResult[7] = tmpCur.info.nHeader;
5214 aResult[8] = tmpCur.info.nLocal;
drh2aa679f2001-06-25 02:11:07 +00005215 }else{
5216 aResult[3] = 0;
5217 aResult[6] = 0;
drh3e27c022004-07-23 00:01:38 +00005218 aResult[7] = 0;
5219 aResult[8] = 0;
drh2aa679f2001-06-25 02:11:07 +00005220 }
5221 aResult[4] = pPage->nFree;
5222 cnt = 0;
drh4b70f112004-05-02 21:12:19 +00005223 idx = get2byte(&pPage->aData[pPage->hdrOffset+1]);
drhb6f41482004-05-14 01:58:11 +00005224 while( idx>0 && idx<pPage->pBt->usableSize ){
drh2aa679f2001-06-25 02:11:07 +00005225 cnt++;
drh4b70f112004-05-02 21:12:19 +00005226 idx = get2byte(&pPage->aData[idx]);
drh2aa679f2001-06-25 02:11:07 +00005227 }
5228 aResult[5] = cnt;
drh3e27c022004-07-23 00:01:38 +00005229 if( pPage->pParent==0 || isRootPage(pPage) ){
5230 aResult[9] = 0;
5231 }else{
5232 aResult[9] = pPage->pParent->pgno;
5233 }
5234 releaseTempCursor(&tmpCur);
drh8c42ca92001-06-22 19:15:00 +00005235 return SQLITE_OK;
5236}
drhaaab5722002-02-19 13:39:21 +00005237#endif
drhdd793422001-06-28 01:54:48 +00005238
drhdd793422001-06-28 01:54:48 +00005239/*
drh5eddca62001-06-30 21:53:53 +00005240** Return the pager associated with a BTree. This routine is used for
5241** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00005242*/
drh3aac2dd2004-04-26 14:10:20 +00005243Pager *sqlite3BtreePager(Btree *pBt){
drhdd793422001-06-28 01:54:48 +00005244 return pBt->pPager;
5245}
drh5eddca62001-06-30 21:53:53 +00005246
5247/*
5248** This structure is passed around through all the sanity checking routines
5249** in order to keep track of some global state information.
5250*/
drhaaab5722002-02-19 13:39:21 +00005251typedef struct IntegrityCk IntegrityCk;
5252struct IntegrityCk {
drh100569d2001-10-02 13:01:48 +00005253 Btree *pBt; /* The tree being checked out */
5254 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
5255 int nPage; /* Number of pages in the database */
5256 int *anRef; /* Number of times each page is referenced */
drh100569d2001-10-02 13:01:48 +00005257 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00005258};
5259
drhb7f91642004-10-31 02:22:47 +00005260#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005261/*
5262** Append a message to the error message string.
5263*/
drh2e38c322004-09-03 18:38:44 +00005264static void checkAppendMsg(
5265 IntegrityCk *pCheck,
5266 char *zMsg1,
5267 const char *zFormat,
5268 ...
5269){
5270 va_list ap;
5271 char *zMsg2;
5272 va_start(ap, zFormat);
5273 zMsg2 = sqlite3VMPrintf(zFormat, ap);
5274 va_end(ap);
5275 if( zMsg1==0 ) zMsg1 = "";
drh5eddca62001-06-30 21:53:53 +00005276 if( pCheck->zErrMsg ){
5277 char *zOld = pCheck->zErrMsg;
5278 pCheck->zErrMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00005279 sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00005280 sqliteFree(zOld);
5281 }else{
danielk19774adee202004-05-08 08:23:19 +00005282 sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00005283 }
drh2e38c322004-09-03 18:38:44 +00005284 sqliteFree(zMsg2);
drh5eddca62001-06-30 21:53:53 +00005285}
drhb7f91642004-10-31 02:22:47 +00005286#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005287
drhb7f91642004-10-31 02:22:47 +00005288#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005289/*
5290** Add 1 to the reference count for page iPage. If this is the second
5291** reference to the page, add an error message to pCheck->zErrMsg.
5292** Return 1 if there are 2 ore more references to the page and 0 if
5293** if this is the first reference to the page.
5294**
5295** Also check that the page number is in bounds.
5296*/
drhaaab5722002-02-19 13:39:21 +00005297static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00005298 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00005299 if( iPage>pCheck->nPage || iPage<0 ){
drh2e38c322004-09-03 18:38:44 +00005300 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005301 return 1;
5302 }
5303 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00005304 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005305 return 1;
5306 }
5307 return (pCheck->anRef[iPage]++)>1;
5308}
5309
danielk1977afcdd022004-10-31 16:25:42 +00005310#ifndef SQLITE_OMIT_AUTOVACUUM
5311/*
5312** Check that the entry in the pointer-map for page iChild maps to
5313** page iParent, pointer type ptrType. If not, append an error message
5314** to pCheck.
5315*/
5316static void checkPtrmap(
5317 IntegrityCk *pCheck, /* Integrity check context */
5318 Pgno iChild, /* Child page number */
5319 u8 eType, /* Expected pointer map type */
5320 Pgno iParent, /* Expected pointer map parent page number */
5321 char *zContext /* Context description (used for error msg) */
5322){
5323 int rc;
5324 u8 ePtrmapType;
5325 Pgno iPtrmapParent;
5326
5327 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
5328 if( rc!=SQLITE_OK ){
5329 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
5330 return;
5331 }
5332
5333 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
5334 checkAppendMsg(pCheck, zContext,
5335 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
5336 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
5337 }
5338}
5339#endif
5340
drh5eddca62001-06-30 21:53:53 +00005341/*
5342** Check the integrity of the freelist or of an overflow page list.
5343** Verify that the number of pages on the list is N.
5344*/
drh30e58752002-03-02 20:41:57 +00005345static void checkList(
5346 IntegrityCk *pCheck, /* Integrity checking context */
5347 int isFreeList, /* True for a freelist. False for overflow page list */
5348 int iPage, /* Page number for first page in the list */
5349 int N, /* Expected number of pages in the list */
5350 char *zContext /* Context for error messages */
5351){
5352 int i;
drh3a4c1412004-05-09 20:40:11 +00005353 int expected = N;
5354 int iFirst = iPage;
drh30e58752002-03-02 20:41:57 +00005355 while( N-- > 0 ){
drh4b70f112004-05-02 21:12:19 +00005356 unsigned char *pOvfl;
drh5eddca62001-06-30 21:53:53 +00005357 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00005358 checkAppendMsg(pCheck, zContext,
5359 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00005360 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00005361 break;
5362 }
5363 if( checkRef(pCheck, iPage, zContext) ) break;
drha34b6762004-05-07 13:30:42 +00005364 if( sqlite3pager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
drh2e38c322004-09-03 18:38:44 +00005365 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005366 break;
5367 }
drh30e58752002-03-02 20:41:57 +00005368 if( isFreeList ){
drh4b70f112004-05-02 21:12:19 +00005369 int n = get4byte(&pOvfl[4]);
danielk1977687566d2004-11-02 12:56:41 +00005370#ifndef SQLITE_OMIT_AUTOVACUUM
5371 if( pCheck->pBt->autoVacuum ){
5372 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
5373 }
5374#endif
drh855eb1c2004-08-31 13:45:11 +00005375 if( n>pCheck->pBt->usableSize/4-8 ){
drh2e38c322004-09-03 18:38:44 +00005376 checkAppendMsg(pCheck, zContext,
5377 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00005378 N--;
5379 }else{
5380 for(i=0; i<n; i++){
danielk1977687566d2004-11-02 12:56:41 +00005381 Pgno iFreePage = get4byte(&pOvfl[8+i*4]);
5382#ifndef SQLITE_OMIT_AUTOVACUUM
5383 if( pCheck->pBt->autoVacuum ){
5384 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
5385 }
5386#endif
5387 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00005388 }
5389 N -= n;
drh30e58752002-03-02 20:41:57 +00005390 }
drh30e58752002-03-02 20:41:57 +00005391 }
danielk1977afcdd022004-10-31 16:25:42 +00005392#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00005393 else{
5394 /* If this database supports auto-vacuum and iPage is not the last
5395 ** page in this overflow list, check that the pointer-map entry for
5396 ** the following page matches iPage.
5397 */
5398 if( pCheck->pBt->autoVacuum && N>0 ){
5399 i = get4byte(pOvfl);
5400 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
5401 }
danielk1977afcdd022004-10-31 16:25:42 +00005402 }
5403#endif
drh4b70f112004-05-02 21:12:19 +00005404 iPage = get4byte(pOvfl);
drha34b6762004-05-07 13:30:42 +00005405 sqlite3pager_unref(pOvfl);
drh5eddca62001-06-30 21:53:53 +00005406 }
5407}
drhb7f91642004-10-31 02:22:47 +00005408#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005409
drhb7f91642004-10-31 02:22:47 +00005410#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005411/*
5412** Do various sanity checks on a single page of a tree. Return
5413** the tree depth. Root pages return 0. Parents of root pages
5414** return 1, and so forth.
5415**
5416** These checks are done:
5417**
5418** 1. Make sure that cells and freeblocks do not overlap
5419** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00005420** NO 2. Make sure cell keys are in order.
5421** NO 3. Make sure no key is less than or equal to zLowerBound.
5422** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00005423** 5. Check the integrity of overflow pages.
5424** 6. Recursively call checkTreePage on all children.
5425** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00005426** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00005427** the root of the tree.
5428*/
5429static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00005430 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00005431 int iPage, /* Page number of the page to check */
5432 MemPage *pParent, /* Parent page */
5433 char *zParentContext, /* Parent context */
5434 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00005435 int nLower, /* Number of characters in zLowerBound */
5436 char *zUpperBound, /* All keys should be less than this, if not NULL */
5437 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00005438){
5439 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00005440 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00005441 int hdr, cellStart;
5442 int nCell;
drhda200cc2004-05-09 11:51:38 +00005443 u8 *data;
drh5eddca62001-06-30 21:53:53 +00005444 BtCursor cur;
drh0d316a42002-08-11 20:10:47 +00005445 Btree *pBt;
drhb6f41482004-05-14 01:58:11 +00005446 int maxLocal, usableSize;
drh5eddca62001-06-30 21:53:53 +00005447 char zContext[100];
drh2e38c322004-09-03 18:38:44 +00005448 char *hit;
drh5eddca62001-06-30 21:53:53 +00005449
danielk1977ef73ee92004-11-06 12:26:07 +00005450 sprintf(zContext, "Page %d: ", iPage);
5451
drh5eddca62001-06-30 21:53:53 +00005452 /* Check that the page exists
5453 */
drh0d316a42002-08-11 20:10:47 +00005454 cur.pBt = pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00005455 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00005456 if( iPage==0 ) return 0;
5457 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh4b70f112004-05-02 21:12:19 +00005458 if( (rc = getPage(pBt, (Pgno)iPage, &pPage))!=0 ){
drh2e38c322004-09-03 18:38:44 +00005459 checkAppendMsg(pCheck, zContext,
5460 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00005461 return 0;
5462 }
drh6f11bef2004-05-13 01:12:56 +00005463 maxLocal = pPage->leafData ? pBt->maxLeaf : pBt->maxLocal;
drh4b70f112004-05-02 21:12:19 +00005464 if( (rc = initPage(pPage, pParent))!=0 ){
drh2e38c322004-09-03 18:38:44 +00005465 checkAppendMsg(pCheck, zContext, "initPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00005466 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00005467 return 0;
5468 }
5469
5470 /* Check out all the cells.
5471 */
5472 depth = 0;
drh5eddca62001-06-30 21:53:53 +00005473 cur.pPage = pPage;
drh5eddca62001-06-30 21:53:53 +00005474 for(i=0; i<pPage->nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00005475 u8 *pCell;
5476 int sz;
5477 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00005478
5479 /* Check payload overflow pages
5480 */
drh3a4c1412004-05-09 20:40:11 +00005481 sprintf(zContext, "On tree page %d cell %d: ", iPage, i);
drh43605152004-05-29 21:46:49 +00005482 pCell = findCell(pPage,i);
5483 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005484 sz = info.nData;
5485 if( !pPage->intKey ) sz += info.nKey;
5486 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00005487 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00005488 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
5489#ifndef SQLITE_OMIT_AUTOVACUUM
5490 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00005491 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00005492 }
5493#endif
5494 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00005495 }
5496
5497 /* Check sanity of left child page.
5498 */
drhda200cc2004-05-09 11:51:38 +00005499 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005500 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00005501#ifndef SQLITE_OMIT_AUTOVACUUM
5502 if( pBt->autoVacuum ){
5503 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
5504 }
5505#endif
drhda200cc2004-05-09 11:51:38 +00005506 d2 = checkTreePage(pCheck,pgno,pPage,zContext,0,0,0,0);
5507 if( i>0 && d2!=depth ){
5508 checkAppendMsg(pCheck, zContext, "Child page depth differs");
5509 }
5510 depth = d2;
drh5eddca62001-06-30 21:53:53 +00005511 }
drh5eddca62001-06-30 21:53:53 +00005512 }
drhda200cc2004-05-09 11:51:38 +00005513 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005514 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drhda200cc2004-05-09 11:51:38 +00005515 sprintf(zContext, "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00005516#ifndef SQLITE_OMIT_AUTOVACUUM
5517 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00005518 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00005519 }
5520#endif
drhda200cc2004-05-09 11:51:38 +00005521 checkTreePage(pCheck, pgno, pPage, zContext,0,0,0,0);
5522 }
drh5eddca62001-06-30 21:53:53 +00005523
5524 /* Check for complete coverage of the page
5525 */
drhda200cc2004-05-09 11:51:38 +00005526 data = pPage->aData;
5527 hdr = pPage->hdrOffset;
drh2e38c322004-09-03 18:38:44 +00005528 hit = sqliteMalloc( usableSize );
5529 if( hit ){
5530 memset(hit, 1, get2byte(&data[hdr+5]));
5531 nCell = get2byte(&data[hdr+3]);
5532 cellStart = hdr + 12 - 4*pPage->leaf;
5533 for(i=0; i<nCell; i++){
5534 int pc = get2byte(&data[cellStart+i*2]);
5535 int size = cellSizePtr(pPage, &data[pc]);
5536 int j;
danielk19777701e812005-01-10 12:59:51 +00005537 if( (pc+size-1)>=usableSize || pc<0 ){
5538 checkAppendMsg(pCheck, 0,
5539 "Corruption detected in cell %d on page %d",i,iPage,0);
5540 }else{
5541 for(j=pc+size-1; j>=pc; j--) hit[j]++;
5542 }
drh2e38c322004-09-03 18:38:44 +00005543 }
5544 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
5545 cnt++){
5546 int size = get2byte(&data[i+2]);
5547 int j;
danielk19777701e812005-01-10 12:59:51 +00005548 if( (i+size-1)>=usableSize || i<0 ){
5549 checkAppendMsg(pCheck, 0,
5550 "Corruption detected in cell %d on page %d",i,iPage,0);
5551 }else{
5552 for(j=i+size-1; j>=i; j--) hit[j]++;
5553 }
drh2e38c322004-09-03 18:38:44 +00005554 i = get2byte(&data[i]);
5555 }
5556 for(i=cnt=0; i<usableSize; i++){
5557 if( hit[i]==0 ){
5558 cnt++;
5559 }else if( hit[i]>1 ){
5560 checkAppendMsg(pCheck, 0,
5561 "Multiple uses for byte %d of page %d", i, iPage);
5562 break;
5563 }
5564 }
5565 if( cnt!=data[hdr+7] ){
5566 checkAppendMsg(pCheck, 0,
5567 "Fragmented space is %d byte reported as %d on page %d",
5568 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00005569 }
5570 }
drh2e38c322004-09-03 18:38:44 +00005571 sqliteFree(hit);
drh6019e162001-07-02 17:51:45 +00005572
drh4b70f112004-05-02 21:12:19 +00005573 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00005574 return depth+1;
drh5eddca62001-06-30 21:53:53 +00005575}
drhb7f91642004-10-31 02:22:47 +00005576#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005577
drhb7f91642004-10-31 02:22:47 +00005578#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005579/*
5580** This routine does a complete check of the given BTree file. aRoot[] is
5581** an array of pages numbers were each page number is the root page of
5582** a table. nRoot is the number of entries in aRoot.
5583**
5584** If everything checks out, this routine returns NULL. If something is
5585** amiss, an error message is written into memory obtained from malloc()
5586** and a pointer to that error message is returned. The calling function
5587** is responsible for freeing the error message when it is done.
5588*/
drh3aac2dd2004-04-26 14:10:20 +00005589char *sqlite3BtreeIntegrityCheck(Btree *pBt, int *aRoot, int nRoot){
drh5eddca62001-06-30 21:53:53 +00005590 int i;
5591 int nRef;
drhaaab5722002-02-19 13:39:21 +00005592 IntegrityCk sCheck;
drh5eddca62001-06-30 21:53:53 +00005593
drha34b6762004-05-07 13:30:42 +00005594 nRef = *sqlite3pager_stats(pBt->pPager);
drhb8ef32c2005-03-14 02:01:49 +00005595 if( lockBtreeWithRetry(pBt)!=SQLITE_OK ){
drhefc251d2001-07-01 22:12:01 +00005596 return sqliteStrDup("Unable to acquire a read lock on the database");
5597 }
drh5eddca62001-06-30 21:53:53 +00005598 sCheck.pBt = pBt;
5599 sCheck.pPager = pBt->pPager;
drha34b6762004-05-07 13:30:42 +00005600 sCheck.nPage = sqlite3pager_pagecount(sCheck.pPager);
drh0de8c112002-07-06 16:32:14 +00005601 if( sCheck.nPage==0 ){
5602 unlockBtreeIfUnused(pBt);
5603 return 0;
5604 }
drh8c1238a2003-01-02 14:43:55 +00005605 sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00005606 if( !sCheck.anRef ){
5607 unlockBtreeIfUnused(pBt);
5608 return sqlite3MPrintf("Unable to malloc %d bytes",
5609 (sCheck.nPage+1)*sizeof(sCheck.anRef[0]));
5610 }
drhda200cc2004-05-09 11:51:38 +00005611 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00005612 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00005613 if( i<=sCheck.nPage ){
5614 sCheck.anRef[i] = 1;
5615 }
drh5eddca62001-06-30 21:53:53 +00005616 sCheck.zErrMsg = 0;
5617
5618 /* Check the integrity of the freelist
5619 */
drha34b6762004-05-07 13:30:42 +00005620 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
5621 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00005622
5623 /* Check all the tables.
5624 */
5625 for(i=0; i<nRoot; i++){
drh4ff6dfa2002-03-03 23:06:00 +00005626 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00005627#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00005628 if( pBt->autoVacuum && aRoot[i]>1 ){
5629 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
5630 }
5631#endif
drh1bffb9c2002-02-03 17:37:36 +00005632 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00005633 }
5634
5635 /* Make sure every page in the file is referenced
5636 */
5637 for(i=1; i<=sCheck.nPage; i++){
danielk1977afcdd022004-10-31 16:25:42 +00005638#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00005639 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00005640 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00005641 }
danielk1977afcdd022004-10-31 16:25:42 +00005642#else
5643 /* If the database supports auto-vacuum, make sure no tables contain
5644 ** references to pointer-map pages.
5645 */
5646 if( sCheck.anRef[i]==0 &&
drh42cac6d2004-11-20 20:31:11 +00005647 (PTRMAP_PAGENO(pBt->usableSize, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00005648 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
5649 }
5650 if( sCheck.anRef[i]!=0 &&
drh42cac6d2004-11-20 20:31:11 +00005651 (PTRMAP_PAGENO(pBt->usableSize, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00005652 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
5653 }
5654#endif
drh5eddca62001-06-30 21:53:53 +00005655 }
5656
5657 /* Make sure this analysis did not leave any unref() pages
5658 */
drh5e00f6c2001-09-13 13:46:56 +00005659 unlockBtreeIfUnused(pBt);
drha34b6762004-05-07 13:30:42 +00005660 if( nRef != *sqlite3pager_stats(pBt->pPager) ){
drh2e38c322004-09-03 18:38:44 +00005661 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00005662 "Outstanding page count goes from %d to %d during this analysis",
drha34b6762004-05-07 13:30:42 +00005663 nRef, *sqlite3pager_stats(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00005664 );
drh5eddca62001-06-30 21:53:53 +00005665 }
5666
5667 /* Clean up and report errors.
5668 */
5669 sqliteFree(sCheck.anRef);
5670 return sCheck.zErrMsg;
5671}
drhb7f91642004-10-31 02:22:47 +00005672#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00005673
drh73509ee2003-04-06 20:44:45 +00005674/*
5675** Return the full pathname of the underlying database file.
5676*/
drh3aac2dd2004-04-26 14:10:20 +00005677const char *sqlite3BtreeGetFilename(Btree *pBt){
drh73509ee2003-04-06 20:44:45 +00005678 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00005679 return sqlite3pager_filename(pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00005680}
5681
5682/*
danielk19775865e3d2004-06-14 06:03:57 +00005683** Return the pathname of the directory that contains the database file.
5684*/
5685const char *sqlite3BtreeGetDirname(Btree *pBt){
5686 assert( pBt->pPager!=0 );
5687 return sqlite3pager_dirname(pBt->pPager);
5688}
5689
5690/*
5691** Return the pathname of the journal file for this database. The return
5692** value of this routine is the same regardless of whether the journal file
5693** has been created or not.
5694*/
5695const char *sqlite3BtreeGetJournalname(Btree *pBt){
5696 assert( pBt->pPager!=0 );
5697 return sqlite3pager_journalname(pBt->pPager);
5698}
5699
drhb7f91642004-10-31 02:22:47 +00005700#ifndef SQLITE_OMIT_VACUUM
danielk19775865e3d2004-06-14 06:03:57 +00005701/*
drhf7c57532003-04-25 13:22:51 +00005702** Copy the complete content of pBtFrom into pBtTo. A transaction
5703** must be active for both files.
5704**
5705** The size of file pBtFrom may be reduced by this operation.
drh43605152004-05-29 21:46:49 +00005706** If anything goes wrong, the transaction on pBtFrom is rolled back.
drh73509ee2003-04-06 20:44:45 +00005707*/
drh3aac2dd2004-04-26 14:10:20 +00005708int sqlite3BtreeCopyFile(Btree *pBtTo, Btree *pBtFrom){
drhf7c57532003-04-25 13:22:51 +00005709 int rc = SQLITE_OK;
drh2e6d11b2003-04-25 15:37:57 +00005710 Pgno i, nPage, nToPage;
drhf7c57532003-04-25 13:22:51 +00005711
danielk1977ee5741e2004-05-31 10:01:34 +00005712 if( pBtTo->inTrans!=TRANS_WRITE || pBtFrom->inTrans!=TRANS_WRITE ){
5713 return SQLITE_ERROR;
5714 }
drhf7c57532003-04-25 13:22:51 +00005715 if( pBtTo->pCursor ) return SQLITE_BUSY;
drha34b6762004-05-07 13:30:42 +00005716 nToPage = sqlite3pager_pagecount(pBtTo->pPager);
5717 nPage = sqlite3pager_pagecount(pBtFrom->pPager);
danielk1977369f27e2004-06-15 11:40:04 +00005718 for(i=1; rc==SQLITE_OK && i<=nPage; i++){
drhf7c57532003-04-25 13:22:51 +00005719 void *pPage;
drha34b6762004-05-07 13:30:42 +00005720 rc = sqlite3pager_get(pBtFrom->pPager, i, &pPage);
drhf7c57532003-04-25 13:22:51 +00005721 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00005722 rc = sqlite3pager_overwrite(pBtTo->pPager, i, pPage);
drh2e6d11b2003-04-25 15:37:57 +00005723 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00005724 sqlite3pager_unref(pPage);
drhf7c57532003-04-25 13:22:51 +00005725 }
drh2e6d11b2003-04-25 15:37:57 +00005726 for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
5727 void *pPage;
drha34b6762004-05-07 13:30:42 +00005728 rc = sqlite3pager_get(pBtTo->pPager, i, &pPage);
drh2e6d11b2003-04-25 15:37:57 +00005729 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00005730 rc = sqlite3pager_write(pPage);
5731 sqlite3pager_unref(pPage);
5732 sqlite3pager_dont_write(pBtTo->pPager, i);
drh2e6d11b2003-04-25 15:37:57 +00005733 }
5734 if( !rc && nPage<nToPage ){
drha34b6762004-05-07 13:30:42 +00005735 rc = sqlite3pager_truncate(pBtTo->pPager, nPage);
drh2e6d11b2003-04-25 15:37:57 +00005736 }
drhf7c57532003-04-25 13:22:51 +00005737 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00005738 sqlite3BtreeRollback(pBtTo);
drhf7c57532003-04-25 13:22:51 +00005739 }
5740 return rc;
drh73509ee2003-04-06 20:44:45 +00005741}
drhb7f91642004-10-31 02:22:47 +00005742#endif /* SQLITE_OMIT_VACUUM */
danielk19771d850a72004-05-31 08:26:49 +00005743
5744/*
5745** Return non-zero if a transaction is active.
5746*/
5747int sqlite3BtreeIsInTrans(Btree *pBt){
danielk1977ee5741e2004-05-31 10:01:34 +00005748 return (pBt && (pBt->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00005749}
5750
5751/*
5752** Return non-zero if a statement transaction is active.
5753*/
5754int sqlite3BtreeIsInStmt(Btree *pBt){
5755 return (pBt && pBt->inStmt);
5756}
danielk197713adf8a2004-06-03 16:08:41 +00005757
5758/*
5759** This call is a no-op if no write-transaction is currently active on pBt.
5760**
5761** Otherwise, sync the database file for the btree pBt. zMaster points to
5762** the name of a master journal file that should be written into the
5763** individual journal file, or is NULL, indicating no master journal file
5764** (single database transaction).
5765**
5766** When this is called, the master journal should already have been
5767** created, populated with this journal pointer and synced to disk.
5768**
5769** Once this is routine has returned, the only thing required to commit
5770** the write-transaction for this database file is to delete the journal.
5771*/
5772int sqlite3BtreeSync(Btree *pBt, const char *zMaster){
5773 if( pBt->inTrans==TRANS_WRITE ){
danielk1977687566d2004-11-02 12:56:41 +00005774#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977d761c0c2004-11-05 16:37:02 +00005775 Pgno nTrunc = 0;
danielk1977687566d2004-11-02 12:56:41 +00005776 if( pBt->autoVacuum ){
danielk1977d761c0c2004-11-05 16:37:02 +00005777 int rc = autoVacuumCommit(pBt, &nTrunc);
danielk1977687566d2004-11-02 12:56:41 +00005778 if( rc!=SQLITE_OK ) return rc;
5779 }
danielk1977d761c0c2004-11-05 16:37:02 +00005780 return sqlite3pager_sync(pBt->pPager, zMaster, nTrunc);
danielk1977687566d2004-11-02 12:56:41 +00005781#endif
danielk1977d761c0c2004-11-05 16:37:02 +00005782 return sqlite3pager_sync(pBt->pPager, zMaster, 0);
danielk197713adf8a2004-06-03 16:08:41 +00005783 }
5784 return SQLITE_OK;
5785}
danielk19776b456a22005-03-21 04:04:02 +00005786
5787#ifndef SQLITE_OMIT_GLOBALRECOVER
5788/*
5789** Reset the btree and underlying pager after a malloc() failure. Any
5790** transaction that was active when malloc() failed is rolled back.
5791*/
5792int sqlite3BtreeReset(Btree *pBt){
5793 if( pBt->pCursor ) return SQLITE_BUSY;
5794 pBt->inTrans = TRANS_NONE;
5795 unlockBtreeIfUnused(pBt);
5796 return sqlite3pager_reset(pBt->pPager);
5797}
5798#endif