blob: 6b778b4adfe176ceb0b0233d5dd91c48ac895a85 [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*************************************************************************
drh4f26bb62005-09-08 14:17:20 +000012** $Id: btree.c,v 1.266 2005/09/08 14:17:20 drh 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
drhc96d8532005-05-03 12:30:33 +0000214/* Round up a number to the next larger multiple of 8. This is used
215** to force 8-byte alignment on 64-bit architectures.
216*/
217#define ROUND8(x) ((x+7)&~7)
218
219
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.
drh556b2a22005-06-14 16:04:05 +0000237**
238** You can change this value at compile-time by specifying a
239** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
240** header must be exactly 16 bytes including the zero-terminator so
241** the string itself should be 15 characters long. If you change
242** the header, then your custom library will not be able to read
243** databases generated by the standard tools and the standard tools
244** will not be able to read databases created by your custom library.
245*/
246#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
247# define SQLITE_FILE_HEADER "SQLite format 3"
248#endif
249static const char zMagicHeader[] = SQLITE_FILE_HEADER;
drh08ed44e2001-04-29 23:32:55 +0000250
251/*
drh4b70f112004-05-02 21:12:19 +0000252** Page type flags. An ORed combination of these flags appear as the
253** first byte of every BTree page.
drh8c42ca92001-06-22 19:15:00 +0000254*/
drhde647132004-05-07 17:57:49 +0000255#define PTF_INTKEY 0x01
drh9e572e62004-04-23 23:43:10 +0000256#define PTF_ZERODATA 0x02
drh8b18dd42004-05-12 19:18:15 +0000257#define PTF_LEAFDATA 0x04
258#define PTF_LEAF 0x08
drh8c42ca92001-06-22 19:15:00 +0000259
260/*
drh9e572e62004-04-23 23:43:10 +0000261** As each page of the file is loaded into memory, an instance of the following
262** structure is appended and initialized to zero. This structure stores
263** information about the page that is decoded from the raw file page.
drh14acc042001-06-10 19:56:58 +0000264**
drh72f82862001-05-24 21:06:34 +0000265** The pParent field points back to the parent page. This allows us to
266** walk up the BTree from any leaf to the root. Care must be taken to
267** unref() the parent page pointer when this page is no longer referenced.
drhbd03cae2001-06-02 02:40:57 +0000268** The pageDestructor() routine handles that chore.
drh7e3b0a02001-04-28 16:52:40 +0000269*/
270struct MemPage {
drha6abd042004-06-09 17:37:22 +0000271 u8 isInit; /* True if previously initialized. MUST BE FIRST! */
drh43605152004-05-29 21:46:49 +0000272 u8 idxShift; /* True if Cell indices have changed */
273 u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
274 u8 intKey; /* True if intkey flag is set */
275 u8 leaf; /* True if leaf flag is set */
276 u8 zeroData; /* True if table stores keys only */
277 u8 leafData; /* True if tables stores data on leaves only */
278 u8 hasData; /* True if this page stores data */
279 u8 hdrOffset; /* 100 for page 1. 0 otherwise */
drh271efa52004-05-30 19:19:05 +0000280 u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
drha2fce642004-06-05 00:01:44 +0000281 u16 maxLocal; /* Copy of Btree.maxLocal or Btree.maxLeaf */
282 u16 minLocal; /* Copy of Btree.minLocal or Btree.minLeaf */
drh43605152004-05-29 21:46:49 +0000283 u16 cellOffset; /* Index in aData of first cell pointer */
284 u16 idxParent; /* Index in parent of this node */
285 u16 nFree; /* Number of free bytes on the page */
286 u16 nCell; /* Number of cells on this page, local and ovfl */
287 struct _OvflCell { /* Cells that will not fit on aData[] */
288 u8 *pCell; /* Pointers to the body of the overflow cell */
289 u16 idx; /* Insert this cell before idx-th non-overflow cell */
drha2fce642004-06-05 00:01:44 +0000290 } aOvfl[5];
drh43605152004-05-29 21:46:49 +0000291 struct Btree *pBt; /* Pointer back to BTree structure */
292 u8 *aData; /* Pointer back to the start of the page */
293 Pgno pgno; /* Page number for this page */
294 MemPage *pParent; /* The parent of this page. NULL for root */
drh8c42ca92001-06-22 19:15:00 +0000295};
drh7e3b0a02001-04-28 16:52:40 +0000296
297/*
drh3b7511c2001-05-26 13:15:44 +0000298** The in-memory image of a disk page has the auxiliary information appended
299** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
300** that extra information.
301*/
drh3aac2dd2004-04-26 14:10:20 +0000302#define EXTRA_SIZE sizeof(MemPage)
drh3b7511c2001-05-26 13:15:44 +0000303
304/*
drha059ad02001-04-17 20:09:11 +0000305** Everything we need to know about an open database
306*/
307struct Btree {
308 Pager *pPager; /* The page cache */
drh306dc212001-05-21 13:45:10 +0000309 BtCursor *pCursor; /* A list of all open cursors */
drh3aac2dd2004-04-26 14:10:20 +0000310 MemPage *pPage1; /* First page of the database */
drh663fc632002-02-02 18:49:19 +0000311 u8 inTrans; /* True if a transaction is in progress */
drhab01f612004-05-22 02:55:23 +0000312 u8 inStmt; /* True if we are in a statement subtransaction */
drh5df72a52002-06-06 23:16:05 +0000313 u8 readOnly; /* True if the underlying file is readonly */
drhab01f612004-05-22 02:55:23 +0000314 u8 maxEmbedFrac; /* Maximum payload as % of total page size */
315 u8 minEmbedFrac; /* Minimum payload as % of total page size */
316 u8 minLeafFrac; /* Minimum leaf payload as % of total page size */
drh90f5ecb2004-07-22 01:19:35 +0000317 u8 pageSizeFixed; /* True if the page size can no longer be changed */
drh057cd3a2005-02-15 16:23:02 +0000318#ifndef SQLITE_OMIT_AUTOVACUUM
319 u8 autoVacuum; /* True if database supports auto-vacuum */
320#endif
drha2fce642004-06-05 00:01:44 +0000321 u16 pageSize; /* Total number of bytes on a page */
322 u16 usableSize; /* Number of usable bytes on each page */
drh6f11bef2004-05-13 01:12:56 +0000323 int maxLocal; /* Maximum local payload in non-LEAFDATA tables */
324 int minLocal; /* Minimum local payload in non-LEAFDATA tables */
325 int maxLeaf; /* Maximum local payload in a LEAFDATA table */
326 int minLeaf; /* Minimum local payload in a LEAFDATA table */
drhb8ef32c2005-03-14 02:01:49 +0000327 BusyHandler *pBusyHandler; /* Callback for when there is lock contention */
drha059ad02001-04-17 20:09:11 +0000328};
329typedef Btree Bt;
330
drh365d68f2001-05-11 11:02:46 +0000331/*
danielk1977ee5741e2004-05-31 10:01:34 +0000332** Btree.inTrans may take one of the following values.
333*/
334#define TRANS_NONE 0
335#define TRANS_READ 1
336#define TRANS_WRITE 2
337
338/*
drhfa1a98a2004-05-14 19:08:17 +0000339** An instance of the following structure is used to hold information
drh271efa52004-05-30 19:19:05 +0000340** about a cell. The parseCellPtr() function fills in this structure
drhab01f612004-05-22 02:55:23 +0000341** based on information extract from the raw disk page.
drhfa1a98a2004-05-14 19:08:17 +0000342*/
343typedef struct CellInfo CellInfo;
344struct CellInfo {
drh43605152004-05-29 21:46:49 +0000345 u8 *pCell; /* Pointer to the start of cell content */
drhfa1a98a2004-05-14 19:08:17 +0000346 i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
347 u32 nData; /* Number of bytes of data */
drh271efa52004-05-30 19:19:05 +0000348 u16 nHeader; /* Size of the cell content header in bytes */
drhfa1a98a2004-05-14 19:08:17 +0000349 u16 nLocal; /* Amount of payload held locally */
drhab01f612004-05-22 02:55:23 +0000350 u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
drh271efa52004-05-30 19:19:05 +0000351 u16 nSize; /* Size of the cell content on the main b-tree page */
drhfa1a98a2004-05-14 19:08:17 +0000352};
353
354/*
drh365d68f2001-05-11 11:02:46 +0000355** A cursor is a pointer to a particular entry in the BTree.
356** The entry is identified by its MemPage and the index in
drha34b6762004-05-07 13:30:42 +0000357** MemPage.aCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000358*/
drh72f82862001-05-24 21:06:34 +0000359struct BtCursor {
drh5e2f8b92001-05-28 00:41:15 +0000360 Btree *pBt; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000361 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drh3aac2dd2004-04-26 14:10:20 +0000362 int (*xCompare)(void*,int,const void*,int,const void*); /* Key comp func */
363 void *pArg; /* First arg to xCompare() */
drh8b2f49b2001-06-08 00:21:52 +0000364 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000365 MemPage *pPage; /* Page that contains the entry */
drh3aac2dd2004-04-26 14:10:20 +0000366 int idx; /* Index of the entry in pPage->aCell[] */
drhfa1a98a2004-05-14 19:08:17 +0000367 CellInfo info; /* A parse of the cell we are pointing at */
drhecdc7532001-09-23 02:35:53 +0000368 u8 wrFlag; /* True if writable */
drhc39e0002004-05-07 23:50:57 +0000369 u8 isValid; /* TRUE if points to a valid entry */
drh365d68f2001-05-11 11:02:46 +0000370};
drh7e3b0a02001-04-28 16:52:40 +0000371
drha059ad02001-04-17 20:09:11 +0000372/*
drh615ae552005-01-16 23:21:00 +0000373** The TRACE macro will print high-level status information about the
374** btree operation when the global variable sqlite3_btree_trace is
375** enabled.
376*/
377#if SQLITE_TEST
378# define TRACE(X) if( sqlite3_btree_trace )\
379 { sqlite3DebugPrintf X; fflush(stdout); }
380#else
381# define TRACE(X)
382#endif
383int sqlite3_btree_trace=0; /* True to enable tracing */
384
385/*
drh66cbd152004-09-01 16:12:25 +0000386** Forward declaration
387*/
388static int checkReadLocks(Btree*,Pgno,BtCursor*);
389
drh66cbd152004-09-01 16:12:25 +0000390/*
drhab01f612004-05-22 02:55:23 +0000391** Read or write a two- and four-byte big-endian integer values.
drh0d316a42002-08-11 20:10:47 +0000392*/
drh9e572e62004-04-23 23:43:10 +0000393static u32 get2byte(unsigned char *p){
394 return (p[0]<<8) | p[1];
drh0d316a42002-08-11 20:10:47 +0000395}
drh9e572e62004-04-23 23:43:10 +0000396static u32 get4byte(unsigned char *p){
397 return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
398}
drh9e572e62004-04-23 23:43:10 +0000399static void put2byte(unsigned char *p, u32 v){
400 p[0] = v>>8;
401 p[1] = v;
402}
403static void put4byte(unsigned char *p, u32 v){
404 p[0] = v>>24;
405 p[1] = v>>16;
406 p[2] = v>>8;
407 p[3] = v;
408}
drh6f11bef2004-05-13 01:12:56 +0000409
drh9e572e62004-04-23 23:43:10 +0000410/*
drhab01f612004-05-22 02:55:23 +0000411** Routines to read and write variable-length integers. These used to
412** be defined locally, but now we use the varint routines in the util.c
413** file.
drh9e572e62004-04-23 23:43:10 +0000414*/
drh6d2fb152004-05-14 16:50:06 +0000415#define getVarint sqlite3GetVarint
416#define getVarint32 sqlite3GetVarint32
417#define putVarint sqlite3PutVarint
drh0d316a42002-08-11 20:10:47 +0000418
danielk1977599fcba2004-11-08 07:13:13 +0000419/* The database page the PENDING_BYTE occupies. This page is never used.
420** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
421** should possibly be consolidated (presumably in pager.h).
422*/
423#define PENDING_BYTE_PAGE(pBt) ((PENDING_BYTE/(pBt)->pageSize)+1)
danielk1977afcdd022004-10-31 16:25:42 +0000424
danielk1977599fcba2004-11-08 07:13:13 +0000425#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000426/*
drh42cac6d2004-11-20 20:31:11 +0000427** These macros define the location of the pointer-map entry for a
428** database page. The first argument to each is the number of usable
429** bytes on each page of the database (often 1024). The second is the
430** page number to look up in the pointer map.
danielk1977afcdd022004-10-31 16:25:42 +0000431**
432** PTRMAP_PAGENO returns the database page number of the pointer-map
433** page that stores the required pointer. PTRMAP_PTROFFSET returns
434** the offset of the requested map entry.
435**
436** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
437** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
danielk1977599fcba2004-11-08 07:13:13 +0000438** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
439** this test.
danielk1977afcdd022004-10-31 16:25:42 +0000440*/
441#define PTRMAP_PAGENO(pgsz, pgno) (((pgno-2)/(pgsz/5+1))*(pgsz/5+1)+2)
442#define PTRMAP_PTROFFSET(pgsz, pgno) (((pgno-2)%(pgsz/5+1)-1)*5)
danielk1977a19df672004-11-03 11:37:07 +0000443#define PTRMAP_ISPAGE(pgsz, pgno) (PTRMAP_PAGENO(pgsz,pgno)==pgno)
444
danielk1977afcdd022004-10-31 16:25:42 +0000445/*
drh615ae552005-01-16 23:21:00 +0000446** The pointer map is a lookup table that identifies the parent page for
447** each child page in the database file. The parent page is the page that
448** contains a pointer to the child. Every page in the database contains
449** 0 or 1 parent pages. (In this context 'database page' refers
450** to any page that is not part of the pointer map itself.) Each pointer map
451** entry consists of a single byte 'type' and a 4 byte parent page number.
452** The PTRMAP_XXX identifiers below are the valid types.
453**
454** The purpose of the pointer map is to facility moving pages from one
455** position in the file to another as part of autovacuum. When a page
456** is moved, the pointer in its parent must be updated to point to the
457** new location. The pointer map is used to locate the parent page quickly.
danielk1977afcdd022004-10-31 16:25:42 +0000458**
danielk1977687566d2004-11-02 12:56:41 +0000459** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
460** used in this case.
danielk1977afcdd022004-10-31 16:25:42 +0000461**
danielk1977687566d2004-11-02 12:56:41 +0000462** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
463** is not used in this case.
464**
465** PTRMAP_OVERFLOW1: The database page is the first page in a list of
466** overflow pages. The page number identifies the page that
467** contains the cell with a pointer to this overflow page.
468**
469** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
470** overflow pages. The page-number identifies the previous
471** page in the overflow page list.
472**
473** PTRMAP_BTREE: The database page is a non-root btree page. The page number
474** identifies the parent page in the btree.
danielk1977afcdd022004-10-31 16:25:42 +0000475*/
danielk1977687566d2004-11-02 12:56:41 +0000476#define PTRMAP_ROOTPAGE 1
477#define PTRMAP_FREEPAGE 2
478#define PTRMAP_OVERFLOW1 3
479#define PTRMAP_OVERFLOW2 4
480#define PTRMAP_BTREE 5
danielk1977afcdd022004-10-31 16:25:42 +0000481
482/*
483** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000484**
485** This routine updates the pointer map entry for page number 'key'
486** so that it maps to type 'eType' and parent page number 'pgno'.
487** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000488*/
drh615ae552005-01-16 23:21:00 +0000489static int ptrmapPut(Btree *pBt, Pgno key, u8 eType, Pgno parent){
danielk1977afcdd022004-10-31 16:25:42 +0000490 u8 *pPtrmap; /* The pointer map page */
491 Pgno iPtrmap; /* The pointer map page number */
492 int offset; /* Offset in pointer map page */
493 int rc;
494
danielk1977ac11ee62005-01-15 12:45:51 +0000495 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000496 if( key==0 ){
497 return SQLITE_CORRUPT;
498 }
drh42cac6d2004-11-20 20:31:11 +0000499 iPtrmap = PTRMAP_PAGENO(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000500 rc = sqlite3pager_get(pBt->pPager, iPtrmap, (void **)&pPtrmap);
danielk1977687566d2004-11-02 12:56:41 +0000501 if( rc!=SQLITE_OK ){
danielk1977afcdd022004-10-31 16:25:42 +0000502 return rc;
503 }
drh42cac6d2004-11-20 20:31:11 +0000504 offset = PTRMAP_PTROFFSET(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000505
drh615ae552005-01-16 23:21:00 +0000506 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
507 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
danielk1977afcdd022004-10-31 16:25:42 +0000508 rc = sqlite3pager_write(pPtrmap);
danielk19775558a8a2005-01-17 07:53:44 +0000509 if( rc==SQLITE_OK ){
510 pPtrmap[offset] = eType;
511 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000512 }
danielk1977afcdd022004-10-31 16:25:42 +0000513 }
514
515 sqlite3pager_unref(pPtrmap);
danielk19775558a8a2005-01-17 07:53:44 +0000516 return rc;
danielk1977afcdd022004-10-31 16:25:42 +0000517}
518
519/*
520** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000521**
522** This routine retrieves the pointer map entry for page 'key', writing
523** the type and parent page number to *pEType and *pPgno respectively.
524** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000525*/
526static int ptrmapGet(Btree *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
527 int iPtrmap; /* Pointer map page index */
528 u8 *pPtrmap; /* Pointer map page data */
529 int offset; /* Offset of entry in pointer map */
530 int rc;
531
drh42cac6d2004-11-20 20:31:11 +0000532 iPtrmap = PTRMAP_PAGENO(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000533 rc = sqlite3pager_get(pBt->pPager, iPtrmap, (void **)&pPtrmap);
534 if( rc!=0 ){
535 return rc;
536 }
537
drh42cac6d2004-11-20 20:31:11 +0000538 offset = PTRMAP_PTROFFSET(pBt->usableSize, key);
danielk1977687566d2004-11-02 12:56:41 +0000539 if( pEType ) *pEType = pPtrmap[offset];
540 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000541
542 sqlite3pager_unref(pPtrmap);
danielk1977fdb7cdb2005-01-17 02:12:18 +0000543 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT;
danielk1977afcdd022004-10-31 16:25:42 +0000544 return SQLITE_OK;
545}
546
547#endif /* SQLITE_OMIT_AUTOVACUUM */
548
drh0d316a42002-08-11 20:10:47 +0000549/*
drh271efa52004-05-30 19:19:05 +0000550** Given a btree page and a cell index (0 means the first cell on
551** the page, 1 means the second cell, and so forth) return a pointer
552** to the cell content.
553**
554** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000555*/
drh43605152004-05-29 21:46:49 +0000556static u8 *findCell(MemPage *pPage, int iCell){
557 u8 *data = pPage->aData;
558 assert( iCell>=0 );
559 assert( iCell<get2byte(&data[pPage->hdrOffset+3]) );
560 return data + get2byte(&data[pPage->cellOffset+2*iCell]);
561}
562
563/*
564** This a more complex version of findCell() that works for
565** pages that do contain overflow cells. See insert
566*/
567static u8 *findOverflowCell(MemPage *pPage, int iCell){
568 int i;
569 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000570 int k;
571 struct _OvflCell *pOvfl;
572 pOvfl = &pPage->aOvfl[i];
573 k = pOvfl->idx;
574 if( k<=iCell ){
575 if( k==iCell ){
576 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000577 }
578 iCell--;
579 }
580 }
581 return findCell(pPage, iCell);
582}
583
584/*
585** Parse a cell content block and fill in the CellInfo structure. There
586** are two versions of this function. parseCell() takes a cell index
587** as the second argument and parseCellPtr() takes a pointer to the
588** body of the cell as its second argument.
589*/
590static void parseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000591 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000592 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000593 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000594){
drh271efa52004-05-30 19:19:05 +0000595 int n; /* Number bytes in cell content header */
596 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000597
598 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000599 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000600 n = pPage->childPtrSize;
601 assert( n==4-4*pPage->leaf );
drh8b18dd42004-05-12 19:18:15 +0000602 if( pPage->hasData ){
drh271efa52004-05-30 19:19:05 +0000603 n += getVarint32(&pCell[n], &nPayload);
drh8b18dd42004-05-12 19:18:15 +0000604 }else{
drh271efa52004-05-30 19:19:05 +0000605 nPayload = 0;
drh3aac2dd2004-04-26 14:10:20 +0000606 }
danielk1977e0d4b062004-06-28 01:11:46 +0000607 n += getVarint(&pCell[n], (u64 *)&pInfo->nKey);
drh6f11bef2004-05-13 01:12:56 +0000608 pInfo->nHeader = n;
drh271efa52004-05-30 19:19:05 +0000609 pInfo->nData = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000610 if( !pPage->intKey ){
611 nPayload += pInfo->nKey;
612 }
drh271efa52004-05-30 19:19:05 +0000613 if( nPayload<=pPage->maxLocal ){
614 /* This is the (easy) common case where the entire payload fits
615 ** on the local page. No overflow is required.
616 */
617 int nSize; /* Total size of cell content in bytes */
drh6f11bef2004-05-13 01:12:56 +0000618 pInfo->nLocal = nPayload;
619 pInfo->iOverflow = 0;
drh271efa52004-05-30 19:19:05 +0000620 nSize = nPayload + n;
621 if( nSize<4 ){
622 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000623 }
drh271efa52004-05-30 19:19:05 +0000624 pInfo->nSize = nSize;
drh6f11bef2004-05-13 01:12:56 +0000625 }else{
drh271efa52004-05-30 19:19:05 +0000626 /* If the payload will not fit completely on the local page, we have
627 ** to decide how much to store locally and how much to spill onto
628 ** overflow pages. The strategy is to minimize the amount of unused
629 ** space on overflow pages while keeping the amount of local storage
630 ** in between minLocal and maxLocal.
631 **
632 ** Warning: changing the way overflow payload is distributed in any
633 ** way will result in an incompatible file format.
634 */
635 int minLocal; /* Minimum amount of payload held locally */
636 int maxLocal; /* Maximum amount of payload held locally */
637 int surplus; /* Overflow payload available for local storage */
638
639 minLocal = pPage->minLocal;
640 maxLocal = pPage->maxLocal;
641 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000642 if( surplus <= maxLocal ){
643 pInfo->nLocal = surplus;
644 }else{
645 pInfo->nLocal = minLocal;
646 }
647 pInfo->iOverflow = pInfo->nLocal + n;
648 pInfo->nSize = pInfo->iOverflow + 4;
649 }
drh3aac2dd2004-04-26 14:10:20 +0000650}
drh43605152004-05-29 21:46:49 +0000651static void parseCell(
652 MemPage *pPage, /* Page containing the cell */
653 int iCell, /* The cell index. First cell is 0 */
654 CellInfo *pInfo /* Fill in this structure */
655){
656 parseCellPtr(pPage, findCell(pPage, iCell), pInfo);
657}
drh3aac2dd2004-04-26 14:10:20 +0000658
659/*
drh43605152004-05-29 21:46:49 +0000660** Compute the total number of bytes that a Cell needs in the cell
661** data area of the btree-page. The return number includes the cell
662** data header and the local payload, but not any overflow page or
663** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000664*/
danielk1977bc6ada42004-06-30 08:20:16 +0000665#ifndef NDEBUG
drh43605152004-05-29 21:46:49 +0000666static int cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000667 CellInfo info;
drh43605152004-05-29 21:46:49 +0000668 parseCell(pPage, iCell, &info);
669 return info.nSize;
670}
danielk1977bc6ada42004-06-30 08:20:16 +0000671#endif
drh43605152004-05-29 21:46:49 +0000672static int cellSizePtr(MemPage *pPage, u8 *pCell){
673 CellInfo info;
674 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000675 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000676}
677
danielk197779a40da2005-01-16 08:00:01 +0000678#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +0000679/*
danielk197726836652005-01-17 01:33:13 +0000680** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +0000681** to an overflow page, insert an entry into the pointer-map
682** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +0000683*/
danielk197726836652005-01-17 01:33:13 +0000684static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
danielk197779a40da2005-01-16 08:00:01 +0000685 if( pCell ){
686 CellInfo info;
687 parseCellPtr(pPage, pCell, &info);
688 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
689 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
690 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
691 }
danielk1977ac11ee62005-01-15 12:45:51 +0000692 }
danielk197779a40da2005-01-16 08:00:01 +0000693 return SQLITE_OK;
danielk1977ac11ee62005-01-15 12:45:51 +0000694}
danielk197726836652005-01-17 01:33:13 +0000695/*
696** If the cell with index iCell on page pPage contains a pointer
697** to an overflow page, insert an entry into the pointer-map
698** for the overflow page.
699*/
700static int ptrmapPutOvfl(MemPage *pPage, int iCell){
701 u8 *pCell;
702 pCell = findOverflowCell(pPage, iCell);
703 return ptrmapPutOvflPtr(pPage, pCell);
704}
danielk197779a40da2005-01-16 08:00:01 +0000705#endif
706
danielk1977ac11ee62005-01-15 12:45:51 +0000707
708/*
drhda200cc2004-05-09 11:51:38 +0000709** Do sanity checking on a page. Throw an exception if anything is
710** not right.
711**
712** This routine is used for internal error checking only. It is omitted
713** from most builds.
714*/
715#if defined(BTREE_DEBUG) && !defined(NDEBUG) && 0
716static void _pageIntegrity(MemPage *pPage){
drhb6f41482004-05-14 01:58:11 +0000717 int usableSize;
drhda200cc2004-05-09 11:51:38 +0000718 u8 *data;
drh43605152004-05-29 21:46:49 +0000719 int i, j, idx, c, pc, hdr, nFree;
720 int cellOffset;
721 int nCell, cellLimit;
drh2e38c322004-09-03 18:38:44 +0000722 u8 *used;
drhda200cc2004-05-09 11:51:38 +0000723
drh2e38c322004-09-03 18:38:44 +0000724 used = sqliteMallocRaw( pPage->pBt->pageSize );
725 if( used==0 ) return;
drhb6f41482004-05-14 01:58:11 +0000726 usableSize = pPage->pBt->usableSize;
drh07d183d2005-05-01 22:52:42 +0000727 assert( pPage->aData==&((unsigned char*)pPage)[-pPage->pBt->pageSize] );
drhda200cc2004-05-09 11:51:38 +0000728 hdr = pPage->hdrOffset;
729 assert( hdr==(pPage->pgno==1 ? 100 : 0) );
730 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
731 c = pPage->aData[hdr];
732 if( pPage->isInit ){
733 assert( pPage->leaf == ((c & PTF_LEAF)!=0) );
734 assert( pPage->zeroData == ((c & PTF_ZERODATA)!=0) );
drh8b18dd42004-05-12 19:18:15 +0000735 assert( pPage->leafData == ((c & PTF_LEAFDATA)!=0) );
736 assert( pPage->intKey == ((c & (PTF_INTKEY|PTF_LEAFDATA))!=0) );
737 assert( pPage->hasData ==
738 !(pPage->zeroData || (!pPage->leaf && pPage->leafData)) );
drh43605152004-05-29 21:46:49 +0000739 assert( pPage->cellOffset==pPage->hdrOffset+12-4*pPage->leaf );
740 assert( pPage->nCell = get2byte(&pPage->aData[hdr+3]) );
drhda200cc2004-05-09 11:51:38 +0000741 }
742 data = pPage->aData;
drhb6f41482004-05-14 01:58:11 +0000743 memset(used, 0, usableSize);
drhda200cc2004-05-09 11:51:38 +0000744 for(i=0; i<hdr+10-pPage->leaf*4; i++) used[i] = 1;
745 nFree = 0;
746 pc = get2byte(&data[hdr+1]);
747 while( pc ){
748 int size;
drhb6f41482004-05-14 01:58:11 +0000749 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +0000750 size = get2byte(&data[pc+2]);
drhb6f41482004-05-14 01:58:11 +0000751 assert( pc+size<=usableSize );
drhda200cc2004-05-09 11:51:38 +0000752 nFree += size;
753 for(i=pc; i<pc+size; i++){
754 assert( used[i]==0 );
755 used[i] = 1;
756 }
757 pc = get2byte(&data[pc]);
758 }
drhda200cc2004-05-09 11:51:38 +0000759 idx = 0;
drh43605152004-05-29 21:46:49 +0000760 nCell = get2byte(&data[hdr+3]);
761 cellLimit = get2byte(&data[hdr+5]);
762 assert( pPage->isInit==0
763 || pPage->nFree==nFree+data[hdr+7]+cellLimit-(cellOffset+2*nCell) );
764 cellOffset = pPage->cellOffset;
765 for(i=0; i<nCell; i++){
drhda200cc2004-05-09 11:51:38 +0000766 int size;
drh43605152004-05-29 21:46:49 +0000767 pc = get2byte(&data[cellOffset+2*i]);
drhb6f41482004-05-14 01:58:11 +0000768 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +0000769 size = cellSize(pPage, &data[pc]);
drhb6f41482004-05-14 01:58:11 +0000770 assert( pc+size<=usableSize );
drh43605152004-05-29 21:46:49 +0000771 for(j=pc; j<pc+size; j++){
772 assert( used[j]==0 );
773 used[j] = 1;
drhda200cc2004-05-09 11:51:38 +0000774 }
drhda200cc2004-05-09 11:51:38 +0000775 }
drh43605152004-05-29 21:46:49 +0000776 for(i=cellOffset+2*nCell; i<cellimit; i++){
777 assert( used[i]==0 );
778 used[i] = 1;
779 }
drhda200cc2004-05-09 11:51:38 +0000780 nFree = 0;
drhb6f41482004-05-14 01:58:11 +0000781 for(i=0; i<usableSize; i++){
drhda200cc2004-05-09 11:51:38 +0000782 assert( used[i]<=1 );
783 if( used[i]==0 ) nFree++;
784 }
drh43605152004-05-29 21:46:49 +0000785 assert( nFree==data[hdr+7] );
drh2e38c322004-09-03 18:38:44 +0000786 sqliteFree(used);
drhda200cc2004-05-09 11:51:38 +0000787}
788#define pageIntegrity(X) _pageIntegrity(X)
789#else
790# define pageIntegrity(X)
791#endif
792
793/*
drh72f82862001-05-24 21:06:34 +0000794** Defragment the page given. All Cells are moved to the
795** beginning of the page and all free space is collected
796** into one big FreeBlk at the end of the page.
drh365d68f2001-05-11 11:02:46 +0000797*/
drh2e38c322004-09-03 18:38:44 +0000798static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000799 int i; /* Loop counter */
800 int pc; /* Address of a i-th cell */
801 int addr; /* Offset of first byte after cell pointer array */
802 int hdr; /* Offset to the page header */
803 int size; /* Size of a cell */
804 int usableSize; /* Number of usable bytes on a page */
805 int cellOffset; /* Offset to the cell pointer array */
806 int brk; /* Offset to the cell content area */
807 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +0000808 unsigned char *data; /* The page data */
809 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +0000810
drha34b6762004-05-07 13:30:42 +0000811 assert( sqlite3pager_iswriteable(pPage->aData) );
drh9e572e62004-04-23 23:43:10 +0000812 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +0000813 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000814 assert( pPage->nOverflow==0 );
drh2e38c322004-09-03 18:38:44 +0000815 temp = sqliteMalloc( pPage->pBt->pageSize );
816 if( temp==0 ) return SQLITE_NOMEM;
drh43605152004-05-29 21:46:49 +0000817 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000818 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000819 cellOffset = pPage->cellOffset;
820 nCell = pPage->nCell;
821 assert( nCell==get2byte(&data[hdr+3]) );
822 usableSize = pPage->pBt->usableSize;
823 brk = get2byte(&data[hdr+5]);
824 memcpy(&temp[brk], &data[brk], usableSize - brk);
825 brk = usableSize;
826 for(i=0; i<nCell; i++){
827 u8 *pAddr; /* The i-th cell pointer */
828 pAddr = &data[cellOffset + i*2];
829 pc = get2byte(pAddr);
830 assert( pc<pPage->pBt->usableSize );
831 size = cellSizePtr(pPage, &temp[pc]);
832 brk -= size;
833 memcpy(&data[brk], &temp[pc], size);
834 put2byte(pAddr, brk);
drh2af926b2001-05-15 00:39:25 +0000835 }
drh43605152004-05-29 21:46:49 +0000836 assert( brk>=cellOffset+2*nCell );
837 put2byte(&data[hdr+5], brk);
838 data[hdr+1] = 0;
839 data[hdr+2] = 0;
840 data[hdr+7] = 0;
841 addr = cellOffset+2*nCell;
842 memset(&data[addr], 0, brk-addr);
drh2e38c322004-09-03 18:38:44 +0000843 sqliteFree(temp);
844 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +0000845}
846
drha059ad02001-04-17 20:09:11 +0000847/*
drh43605152004-05-29 21:46:49 +0000848** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +0000849**
drh9e572e62004-04-23 23:43:10 +0000850** Return the index into pPage->aData[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000851** the new allocation. Or return 0 if there is not enough free
852** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000853**
drh72f82862001-05-24 21:06:34 +0000854** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000855** nBytes of contiguous free space, then this routine automatically
856** calls defragementPage() to consolidate all free space before
857** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000858*/
drh9e572e62004-04-23 23:43:10 +0000859static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +0000860 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +0000861 int size;
drh24cd67e2004-05-10 16:18:47 +0000862 int nFrag;
drh43605152004-05-29 21:46:49 +0000863 int top;
864 int nCell;
865 int cellOffset;
drh9e572e62004-04-23 23:43:10 +0000866 unsigned char *data;
drh43605152004-05-29 21:46:49 +0000867
drh9e572e62004-04-23 23:43:10 +0000868 data = pPage->aData;
drha34b6762004-05-07 13:30:42 +0000869 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +0000870 assert( pPage->pBt );
871 if( nByte<4 ) nByte = 4;
drh43605152004-05-29 21:46:49 +0000872 if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
873 pPage->nFree -= nByte;
drh9e572e62004-04-23 23:43:10 +0000874 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000875
876 nFrag = data[hdr+7];
877 if( nFrag<60 ){
878 /* Search the freelist looking for a slot big enough to satisfy the
879 ** space request. */
880 addr = hdr+1;
881 while( (pc = get2byte(&data[addr]))>0 ){
882 size = get2byte(&data[pc+2]);
883 if( size>=nByte ){
884 if( size<nByte+4 ){
885 memcpy(&data[addr], &data[pc], 2);
886 data[hdr+7] = nFrag + size - nByte;
887 return pc;
888 }else{
889 put2byte(&data[pc+2], size-nByte);
890 return pc + size - nByte;
891 }
892 }
893 addr = pc;
drh9e572e62004-04-23 23:43:10 +0000894 }
895 }
drh43605152004-05-29 21:46:49 +0000896
897 /* Allocate memory from the gap in between the cell pointer array
898 ** and the cell content area.
899 */
900 top = get2byte(&data[hdr+5]);
901 nCell = get2byte(&data[hdr+3]);
902 cellOffset = pPage->cellOffset;
903 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
drh2e38c322004-09-03 18:38:44 +0000904 if( defragmentPage(pPage) ) return 0;
drh43605152004-05-29 21:46:49 +0000905 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +0000906 }
drh43605152004-05-29 21:46:49 +0000907 top -= nByte;
908 assert( cellOffset + 2*nCell <= top );
909 put2byte(&data[hdr+5], top);
910 return top;
drh7e3b0a02001-04-28 16:52:40 +0000911}
912
913/*
drh9e572e62004-04-23 23:43:10 +0000914** Return a section of the pPage->aData to the freelist.
915** The first byte of the new free block is pPage->aDisk[start]
916** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +0000917**
918** Most of the effort here is involved in coalesing adjacent
919** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000920*/
drh9e572e62004-04-23 23:43:10 +0000921static void freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +0000922 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +0000923 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +0000924
drh9e572e62004-04-23 23:43:10 +0000925 assert( pPage->pBt!=0 );
drha34b6762004-05-07 13:30:42 +0000926 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +0000927 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +0000928 assert( (start + size)<=pPage->pBt->usableSize );
drh9e572e62004-04-23 23:43:10 +0000929 if( size<4 ) size = 4;
930
931 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +0000932 hdr = pPage->hdrOffset;
933 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +0000934 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +0000935 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000936 assert( pbegin>addr );
937 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +0000938 }
drhb6f41482004-05-14 01:58:11 +0000939 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000940 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +0000941 put2byte(&data[addr], start);
942 put2byte(&data[start], pbegin);
943 put2byte(&data[start+2], size);
drh2af926b2001-05-15 00:39:25 +0000944 pPage->nFree += size;
drh9e572e62004-04-23 23:43:10 +0000945
946 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +0000947 addr = pPage->hdrOffset + 1;
948 while( (pbegin = get2byte(&data[addr]))>0 ){
drh9e572e62004-04-23 23:43:10 +0000949 int pnext, psize;
drh3aac2dd2004-04-26 14:10:20 +0000950 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +0000951 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +0000952 pnext = get2byte(&data[pbegin]);
953 psize = get2byte(&data[pbegin+2]);
954 if( pbegin + psize + 3 >= pnext && pnext>0 ){
955 int frag = pnext - (pbegin+psize);
drh43605152004-05-29 21:46:49 +0000956 assert( frag<=data[pPage->hdrOffset+7] );
957 data[pPage->hdrOffset+7] -= frag;
drh9e572e62004-04-23 23:43:10 +0000958 put2byte(&data[pbegin], get2byte(&data[pnext]));
959 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
960 }else{
drh3aac2dd2004-04-26 14:10:20 +0000961 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +0000962 }
963 }
drh7e3b0a02001-04-28 16:52:40 +0000964
drh43605152004-05-29 21:46:49 +0000965 /* If the cell content area begins with a freeblock, remove it. */
966 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
967 int top;
968 pbegin = get2byte(&data[hdr+1]);
969 memcpy(&data[hdr+1], &data[pbegin], 2);
970 top = get2byte(&data[hdr+5]);
971 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
drh4b70f112004-05-02 21:12:19 +0000972 }
drh4b70f112004-05-02 21:12:19 +0000973}
974
975/*
drh271efa52004-05-30 19:19:05 +0000976** Decode the flags byte (the first byte of the header) for a page
977** and initialize fields of the MemPage structure accordingly.
978*/
979static void decodeFlags(MemPage *pPage, int flagByte){
980 Btree *pBt; /* A copy of pPage->pBt */
981
982 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
983 pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
984 pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
985 pPage->leaf = (flagByte & PTF_LEAF)!=0;
986 pPage->childPtrSize = 4*(pPage->leaf==0);
987 pBt = pPage->pBt;
988 if( flagByte & PTF_LEAFDATA ){
989 pPage->leafData = 1;
990 pPage->maxLocal = pBt->maxLeaf;
991 pPage->minLocal = pBt->minLeaf;
992 }else{
993 pPage->leafData = 0;
994 pPage->maxLocal = pBt->maxLocal;
995 pPage->minLocal = pBt->minLocal;
996 }
997 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
998}
999
1000/*
drh7e3b0a02001-04-28 16:52:40 +00001001** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001002**
drhbd03cae2001-06-02 02:40:57 +00001003** The pParent parameter must be a pointer to the MemPage which
drh9e572e62004-04-23 23:43:10 +00001004** is the parent of the page being initialized. The root of a
1005** BTree has no parent and so for that page, pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +00001006**
drh72f82862001-05-24 21:06:34 +00001007** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001008** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001009** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1010** guarantee that the page is well-formed. It only shows that
1011** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001012*/
drh9e572e62004-04-23 23:43:10 +00001013static int initPage(
drh3aac2dd2004-04-26 14:10:20 +00001014 MemPage *pPage, /* The page to be initialized */
drh9e572e62004-04-23 23:43:10 +00001015 MemPage *pParent /* The parent. Might be NULL */
1016){
drh271efa52004-05-30 19:19:05 +00001017 int pc; /* Address of a freeblock within pPage->aData[] */
drh271efa52004-05-30 19:19:05 +00001018 int hdr; /* Offset to beginning of page header */
1019 u8 *data; /* Equal to pPage->aData */
drh2e38c322004-09-03 18:38:44 +00001020 Btree *pBt; /* The main btree structure */
drh271efa52004-05-30 19:19:05 +00001021 int usableSize; /* Amount of usable space on each page */
1022 int cellOffset; /* Offset from start of page to first cell pointer */
1023 int nFree; /* Number of unused bytes on the page */
1024 int top; /* First byte of the cell content area */
drh2af926b2001-05-15 00:39:25 +00001025
drh2e38c322004-09-03 18:38:44 +00001026 pBt = pPage->pBt;
1027 assert( pBt!=0 );
1028 assert( pParent==0 || pParent->pBt==pBt );
drha34b6762004-05-07 13:30:42 +00001029 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
drh07d183d2005-05-01 22:52:42 +00001030 assert( pPage->aData == &((unsigned char*)pPage)[-pBt->pageSize] );
drhee696e22004-08-30 16:52:17 +00001031 if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
1032 /* The parent page should never change unless the file is corrupt */
1033 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1034 }
drh10617cd2004-05-14 15:27:27 +00001035 if( pPage->isInit ) return SQLITE_OK;
drhda200cc2004-05-09 11:51:38 +00001036 if( pPage->pParent==0 && pParent!=0 ){
1037 pPage->pParent = pParent;
drha34b6762004-05-07 13:30:42 +00001038 sqlite3pager_ref(pParent->aData);
drh5e2f8b92001-05-28 00:41:15 +00001039 }
drhde647132004-05-07 17:57:49 +00001040 hdr = pPage->hdrOffset;
drha34b6762004-05-07 13:30:42 +00001041 data = pPage->aData;
drh271efa52004-05-30 19:19:05 +00001042 decodeFlags(pPage, data[hdr]);
drh43605152004-05-29 21:46:49 +00001043 pPage->nOverflow = 0;
drhc8629a12004-05-08 20:07:40 +00001044 pPage->idxShift = 0;
drh2e38c322004-09-03 18:38:44 +00001045 usableSize = pBt->usableSize;
drh43605152004-05-29 21:46:49 +00001046 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
1047 top = get2byte(&data[hdr+5]);
1048 pPage->nCell = get2byte(&data[hdr+3]);
drh2e38c322004-09-03 18:38:44 +00001049 if( pPage->nCell>MX_CELL(pBt) ){
drhee696e22004-08-30 16:52:17 +00001050 /* To many cells for a single page. The page must be corrupt */
1051 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1052 }
1053 if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
1054 /* All pages must have at least one cell, except for root pages */
1055 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1056 }
drh9e572e62004-04-23 23:43:10 +00001057
1058 /* Compute the total free space on the page */
drh9e572e62004-04-23 23:43:10 +00001059 pc = get2byte(&data[hdr+1]);
drh43605152004-05-29 21:46:49 +00001060 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
drh9e572e62004-04-23 23:43:10 +00001061 while( pc>0 ){
1062 int next, size;
drhee696e22004-08-30 16:52:17 +00001063 if( pc>usableSize-4 ){
1064 /* Free block is off the page */
1065 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1066 }
drh9e572e62004-04-23 23:43:10 +00001067 next = get2byte(&data[pc]);
1068 size = get2byte(&data[pc+2]);
drhee696e22004-08-30 16:52:17 +00001069 if( next>0 && next<=pc+size+3 ){
1070 /* Free blocks must be in accending order */
1071 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1072 }
drh3add3672004-05-15 00:29:24 +00001073 nFree += size;
drh9e572e62004-04-23 23:43:10 +00001074 pc = next;
1075 }
drh3add3672004-05-15 00:29:24 +00001076 pPage->nFree = nFree;
drhee696e22004-08-30 16:52:17 +00001077 if( nFree>=usableSize ){
1078 /* Free space cannot exceed total page size */
1079 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1080 }
drh9e572e62004-04-23 23:43:10 +00001081
drhde647132004-05-07 17:57:49 +00001082 pPage->isInit = 1;
drhda200cc2004-05-09 11:51:38 +00001083 pageIntegrity(pPage);
drh9e572e62004-04-23 23:43:10 +00001084 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001085}
1086
1087/*
drh8b2f49b2001-06-08 00:21:52 +00001088** Set up a raw page so that it looks like a database page holding
1089** no entries.
drhbd03cae2001-06-02 02:40:57 +00001090*/
drh9e572e62004-04-23 23:43:10 +00001091static void zeroPage(MemPage *pPage, int flags){
1092 unsigned char *data = pPage->aData;
1093 Btree *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00001094 int hdr = pPage->hdrOffset;
drh9e572e62004-04-23 23:43:10 +00001095 int first;
1096
drhda200cc2004-05-09 11:51:38 +00001097 assert( sqlite3pager_pagenumber(data)==pPage->pgno );
drh07d183d2005-05-01 22:52:42 +00001098 assert( &data[pBt->pageSize] == (unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +00001099 assert( sqlite3pager_iswriteable(data) );
drhb6f41482004-05-14 01:58:11 +00001100 memset(&data[hdr], 0, pBt->usableSize - hdr);
drh9e572e62004-04-23 23:43:10 +00001101 data[hdr] = flags;
drh43605152004-05-29 21:46:49 +00001102 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
1103 memset(&data[hdr+1], 0, 4);
1104 data[hdr+7] = 0;
1105 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +00001106 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +00001107 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +00001108 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +00001109 pPage->cellOffset = first;
1110 pPage->nOverflow = 0;
drhda200cc2004-05-09 11:51:38 +00001111 pPage->idxShift = 0;
drh43605152004-05-29 21:46:49 +00001112 pPage->nCell = 0;
drhda200cc2004-05-09 11:51:38 +00001113 pPage->isInit = 1;
1114 pageIntegrity(pPage);
drhbd03cae2001-06-02 02:40:57 +00001115}
1116
1117/*
drh3aac2dd2004-04-26 14:10:20 +00001118** Get a page from the pager. Initialize the MemPage.pBt and
1119** MemPage.aData elements if needed.
1120*/
1121static int getPage(Btree *pBt, Pgno pgno, MemPage **ppPage){
1122 int rc;
1123 unsigned char *aData;
1124 MemPage *pPage;
drha34b6762004-05-07 13:30:42 +00001125 rc = sqlite3pager_get(pBt->pPager, pgno, (void**)&aData);
drh3aac2dd2004-04-26 14:10:20 +00001126 if( rc ) return rc;
drh07d183d2005-05-01 22:52:42 +00001127 pPage = (MemPage*)&aData[pBt->pageSize];
drh3aac2dd2004-04-26 14:10:20 +00001128 pPage->aData = aData;
1129 pPage->pBt = pBt;
1130 pPage->pgno = pgno;
drhde647132004-05-07 17:57:49 +00001131 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
drh3aac2dd2004-04-26 14:10:20 +00001132 *ppPage = pPage;
1133 return SQLITE_OK;
1134}
1135
1136/*
drhde647132004-05-07 17:57:49 +00001137** Get a page from the pager and initialize it. This routine
1138** is just a convenience wrapper around separate calls to
1139** getPage() and initPage().
1140*/
1141static int getAndInitPage(
1142 Btree *pBt, /* The database file */
1143 Pgno pgno, /* Number of the page to get */
1144 MemPage **ppPage, /* Write the page pointer here */
1145 MemPage *pParent /* Parent of the page */
1146){
1147 int rc;
drhee696e22004-08-30 16:52:17 +00001148 if( pgno==0 ){
1149 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
1150 }
drhde647132004-05-07 17:57:49 +00001151 rc = getPage(pBt, pgno, ppPage);
drh10617cd2004-05-14 15:27:27 +00001152 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
drhde647132004-05-07 17:57:49 +00001153 rc = initPage(*ppPage, pParent);
1154 }
1155 return rc;
1156}
1157
1158/*
drh3aac2dd2004-04-26 14:10:20 +00001159** Release a MemPage. This should be called once for each prior
1160** call to getPage.
1161*/
drh4b70f112004-05-02 21:12:19 +00001162static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001163 if( pPage ){
1164 assert( pPage->aData );
1165 assert( pPage->pBt );
drh07d183d2005-05-01 22:52:42 +00001166 assert( &pPage->aData[pPage->pBt->pageSize]==(unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +00001167 sqlite3pager_unref(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00001168 }
1169}
1170
1171/*
drh72f82862001-05-24 21:06:34 +00001172** This routine is called when the reference count for a page
1173** reaches zero. We need to unref the pParent pointer when that
1174** happens.
1175*/
drhb6f41482004-05-14 01:58:11 +00001176static void pageDestructor(void *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +00001177 MemPage *pPage;
1178 assert( (pageSize & 7)==0 );
1179 pPage = (MemPage*)&((char*)pData)[pageSize];
drh72f82862001-05-24 21:06:34 +00001180 if( pPage->pParent ){
1181 MemPage *pParent = pPage->pParent;
1182 pPage->pParent = 0;
drha34b6762004-05-07 13:30:42 +00001183 releasePage(pParent);
drh72f82862001-05-24 21:06:34 +00001184 }
drh3aac2dd2004-04-26 14:10:20 +00001185 pPage->isInit = 0;
drh72f82862001-05-24 21:06:34 +00001186}
1187
1188/*
drha6abd042004-06-09 17:37:22 +00001189** During a rollback, when the pager reloads information into the cache
1190** so that the cache is restored to its original state at the start of
1191** the transaction, for each page restored this routine is called.
1192**
1193** This routine needs to reset the extra data section at the end of the
1194** page to agree with the restored data.
1195*/
1196static void pageReinit(void *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +00001197 MemPage *pPage;
1198 assert( (pageSize & 7)==0 );
1199 pPage = (MemPage*)&((char*)pData)[pageSize];
drha6abd042004-06-09 17:37:22 +00001200 if( pPage->isInit ){
1201 pPage->isInit = 0;
1202 initPage(pPage, pPage->pParent);
1203 }
1204}
1205
1206/*
drhad3e0102004-09-03 23:32:18 +00001207** Open a database file.
1208**
drh382c0242001-10-06 16:33:02 +00001209** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001210** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001211** database file will be deleted when sqlite3BtreeClose() is called.
drha059ad02001-04-17 20:09:11 +00001212*/
drh23e11ca2004-05-04 17:27:28 +00001213int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001214 const char *zFilename, /* Name of the file containing the BTree database */
1215 Btree **ppBtree, /* Pointer to new Btree object written here */
drh90f5ecb2004-07-22 01:19:35 +00001216 int flags /* Options */
drh6019e162001-07-02 17:51:45 +00001217){
drha059ad02001-04-17 20:09:11 +00001218 Btree *pBt;
drha34b6762004-05-07 13:30:42 +00001219 int rc;
drh90f5ecb2004-07-22 01:19:35 +00001220 int nReserve;
1221 unsigned char zDbHeader[100];
drha059ad02001-04-17 20:09:11 +00001222
drhd62d3d02003-01-24 12:14:20 +00001223 /*
1224 ** The following asserts make sure that structures used by the btree are
1225 ** the right size. This is to guard against size changes that result
1226 ** when compiling on a different architecture.
1227 */
drh4a1c3802004-05-12 15:15:47 +00001228 assert( sizeof(i64)==8 );
drh9e572e62004-04-23 23:43:10 +00001229 assert( sizeof(u64)==8 );
drhd62d3d02003-01-24 12:14:20 +00001230 assert( sizeof(u32)==4 );
1231 assert( sizeof(u16)==2 );
1232 assert( sizeof(Pgno)==4 );
drhd62d3d02003-01-24 12:14:20 +00001233
drha059ad02001-04-17 20:09:11 +00001234 pBt = sqliteMalloc( sizeof(*pBt) );
1235 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +00001236 *ppBtree = 0;
drha059ad02001-04-17 20:09:11 +00001237 return SQLITE_NOMEM;
1238 }
drh7bec5052005-02-06 02:45:41 +00001239 rc = sqlite3pager_open(&pBt->pPager, zFilename, EXTRA_SIZE, flags);
drha059ad02001-04-17 20:09:11 +00001240 if( rc!=SQLITE_OK ){
drha34b6762004-05-07 13:30:42 +00001241 if( pBt->pPager ) sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001242 sqliteFree(pBt);
1243 *ppBtree = 0;
1244 return rc;
1245 }
drha34b6762004-05-07 13:30:42 +00001246 sqlite3pager_set_destructor(pBt->pPager, pageDestructor);
drha6abd042004-06-09 17:37:22 +00001247 sqlite3pager_set_reiniter(pBt->pPager, pageReinit);
drha059ad02001-04-17 20:09:11 +00001248 pBt->pCursor = 0;
drha34b6762004-05-07 13:30:42 +00001249 pBt->pPage1 = 0;
1250 pBt->readOnly = sqlite3pager_isreadonly(pBt->pPager);
drh90f5ecb2004-07-22 01:19:35 +00001251 sqlite3pager_read_fileheader(pBt->pPager, sizeof(zDbHeader), zDbHeader);
1252 pBt->pageSize = get2byte(&zDbHeader[16]);
drh07d183d2005-05-01 22:52:42 +00001253 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1254 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
drh90f5ecb2004-07-22 01:19:35 +00001255 pBt->pageSize = SQLITE_DEFAULT_PAGE_SIZE;
1256 pBt->maxEmbedFrac = 64; /* 25% */
1257 pBt->minEmbedFrac = 32; /* 12.5% */
1258 pBt->minLeafFrac = 32; /* 12.5% */
drheee46cf2004-11-06 00:02:48 +00001259#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197703aded42004-11-22 05:26:27 +00001260 /* If the magic name ":memory:" will create an in-memory database, then
1261 ** do not set the auto-vacuum flag, even if SQLITE_DEFAULT_AUTOVACUUM
1262 ** is true. On the other hand, if SQLITE_OMIT_MEMORYDB has been defined,
1263 ** then ":memory:" is just a regular file-name. Respect the auto-vacuum
1264 ** default in this case.
1265 */
1266#ifndef SQLITE_OMIT_MEMORYDB
danielk1977951af802004-11-05 15:45:09 +00001267 if( zFilename && strcmp(zFilename,":memory:") ){
danielk197703aded42004-11-22 05:26:27 +00001268#else
1269 if( zFilename ){
1270#endif
danielk1977951af802004-11-05 15:45:09 +00001271 pBt->autoVacuum = SQLITE_DEFAULT_AUTOVACUUM;
1272 }
drheee46cf2004-11-06 00:02:48 +00001273#endif
drh90f5ecb2004-07-22 01:19:35 +00001274 nReserve = 0;
1275 }else{
1276 nReserve = zDbHeader[20];
1277 pBt->maxEmbedFrac = zDbHeader[21];
1278 pBt->minEmbedFrac = zDbHeader[22];
1279 pBt->minLeafFrac = zDbHeader[23];
1280 pBt->pageSizeFixed = 1;
danielk1977951af802004-11-05 15:45:09 +00001281#ifndef SQLITE_OMIT_AUTOVACUUM
1282 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1283#endif
drh90f5ecb2004-07-22 01:19:35 +00001284 }
1285 pBt->usableSize = pBt->pageSize - nReserve;
drh07d183d2005-05-01 22:52:42 +00001286 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
drh90f5ecb2004-07-22 01:19:35 +00001287 sqlite3pager_set_pagesize(pBt->pPager, pBt->pageSize);
drha059ad02001-04-17 20:09:11 +00001288 *ppBtree = pBt;
1289 return SQLITE_OK;
1290}
1291
1292/*
1293** Close an open database and invalidate all cursors.
1294*/
drh3aac2dd2004-04-26 14:10:20 +00001295int sqlite3BtreeClose(Btree *pBt){
drha059ad02001-04-17 20:09:11 +00001296 while( pBt->pCursor ){
drh3aac2dd2004-04-26 14:10:20 +00001297 sqlite3BtreeCloseCursor(pBt->pCursor);
drha059ad02001-04-17 20:09:11 +00001298 }
drha34b6762004-05-07 13:30:42 +00001299 sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001300 sqliteFree(pBt);
1301 return SQLITE_OK;
1302}
1303
1304/*
drh90f5ecb2004-07-22 01:19:35 +00001305** Change the busy handler callback function.
1306*/
1307int sqlite3BtreeSetBusyHandler(Btree *pBt, BusyHandler *pHandler){
drhb8ef32c2005-03-14 02:01:49 +00001308 pBt->pBusyHandler = pHandler;
drh90f5ecb2004-07-22 01:19:35 +00001309 sqlite3pager_set_busyhandler(pBt->pPager, pHandler);
1310 return SQLITE_OK;
1311}
1312
1313/*
drhda47d772002-12-02 04:25:19 +00001314** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001315**
1316** The maximum number of cache pages is set to the absolute
1317** value of mxPage. If mxPage is negative, the pager will
1318** operate asynchronously - it will not stop to do fsync()s
1319** to insure data is written to the disk surface before
1320** continuing. Transactions still work if synchronous is off,
1321** and the database cannot be corrupted if this program
1322** crashes. But if the operating system crashes or there is
1323** an abrupt power failure when synchronous is off, the database
1324** could be left in an inconsistent and unrecoverable state.
1325** Synchronous is on by default so database corruption is not
1326** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001327*/
drh23e11ca2004-05-04 17:27:28 +00001328int sqlite3BtreeSetCacheSize(Btree *pBt, int mxPage){
drha34b6762004-05-07 13:30:42 +00001329 sqlite3pager_set_cachesize(pBt->pPager, mxPage);
drhf57b14a2001-09-14 18:54:08 +00001330 return SQLITE_OK;
1331}
1332
1333/*
drh973b6e32003-02-12 14:09:42 +00001334** Change the way data is synced to disk in order to increase or decrease
1335** how well the database resists damage due to OS crashes and power
1336** failures. Level 1 is the same as asynchronous (no syncs() occur and
1337** there is a high probability of damage) Level 2 is the default. There
1338** is a very low but non-zero probability of damage. Level 3 reduces the
1339** probability of damage to near zero but with a write performance reduction.
1340*/
danielk197793758c82005-01-21 08:13:14 +00001341#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drh3aac2dd2004-04-26 14:10:20 +00001342int sqlite3BtreeSetSafetyLevel(Btree *pBt, int level){
drha34b6762004-05-07 13:30:42 +00001343 sqlite3pager_set_safety_level(pBt->pPager, level);
drh973b6e32003-02-12 14:09:42 +00001344 return SQLITE_OK;
1345}
danielk197793758c82005-01-21 08:13:14 +00001346#endif
drh973b6e32003-02-12 14:09:42 +00001347
drh2c8997b2005-08-27 16:36:48 +00001348/*
1349** Return TRUE if the given btree is set to safety level 1. In other
1350** words, return TRUE if no sync() occurs on the disk files.
1351*/
1352int sqlite3BtreeSyncDisabled(Btree *pBt){
1353 assert( pBt && pBt->pPager );
1354 return sqlite3pager_nosync(pBt->pPager);
1355}
1356
danielk1977576ec6b2005-01-21 11:55:25 +00001357#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001358/*
drh90f5ecb2004-07-22 01:19:35 +00001359** Change the default pages size and the number of reserved bytes per page.
drh06f50212004-11-02 14:24:33 +00001360**
1361** The page size must be a power of 2 between 512 and 65536. If the page
1362** size supplied does not meet this constraint then the page size is not
1363** changed.
1364**
1365** Page sizes are constrained to be a power of two so that the region
1366** of the database file used for locking (beginning at PENDING_BYTE,
1367** the first byte past the 1GB boundary, 0x40000000) needs to occur
1368** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001369**
1370** If parameter nReserve is less than zero, then the number of reserved
1371** bytes per page is left unchanged.
drh90f5ecb2004-07-22 01:19:35 +00001372*/
1373int sqlite3BtreeSetPageSize(Btree *pBt, int pageSize, int nReserve){
1374 if( pBt->pageSizeFixed ){
1375 return SQLITE_READONLY;
1376 }
1377 if( nReserve<0 ){
1378 nReserve = pBt->pageSize - pBt->usableSize;
1379 }
drh06f50212004-11-02 14:24:33 +00001380 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
1381 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00001382 assert( (pageSize & 7)==0 );
drh1c7880e2005-05-20 20:01:55 +00001383 pBt->pageSize = sqlite3pager_set_pagesize(pBt->pPager, pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001384 }
1385 pBt->usableSize = pBt->pageSize - nReserve;
1386 return SQLITE_OK;
1387}
1388
1389/*
1390** Return the currently defined page size
1391*/
1392int sqlite3BtreeGetPageSize(Btree *pBt){
1393 return pBt->pageSize;
1394}
drh2011d5f2004-07-22 02:40:37 +00001395int sqlite3BtreeGetReserve(Btree *pBt){
1396 return pBt->pageSize - pBt->usableSize;
1397}
danielk1977576ec6b2005-01-21 11:55:25 +00001398#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00001399
1400/*
danielk1977951af802004-11-05 15:45:09 +00001401** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
1402** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
1403** is disabled. The default value for the auto-vacuum property is
1404** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
1405*/
1406int sqlite3BtreeSetAutoVacuum(Btree *pBt, int autoVacuum){
1407#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001408 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00001409#else
1410 if( pBt->pageSizeFixed ){
1411 return SQLITE_READONLY;
1412 }
1413 pBt->autoVacuum = (autoVacuum?1:0);
1414 return SQLITE_OK;
1415#endif
1416}
1417
1418/*
1419** Return the value of the 'auto-vacuum' property. If auto-vacuum is
1420** enabled 1 is returned. Otherwise 0.
1421*/
1422int sqlite3BtreeGetAutoVacuum(Btree *pBt){
1423#ifdef SQLITE_OMIT_AUTOVACUUM
1424 return 0;
1425#else
1426 return pBt->autoVacuum;
1427#endif
1428}
1429
1430
1431/*
drha34b6762004-05-07 13:30:42 +00001432** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001433** also acquire a readlock on that file.
1434**
1435** SQLITE_OK is returned on success. If the file is not a
1436** well-formed database file, then SQLITE_CORRUPT is returned.
1437** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
1438** is returned if we run out of memory. SQLITE_PROTOCOL is returned
1439** if there is a locking protocol violation.
1440*/
1441static int lockBtree(Btree *pBt){
drh07d183d2005-05-01 22:52:42 +00001442 int rc, pageSize;
drh3aac2dd2004-04-26 14:10:20 +00001443 MemPage *pPage1;
drha34b6762004-05-07 13:30:42 +00001444 if( pBt->pPage1 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001445 rc = getPage(pBt, 1, &pPage1);
drh306dc212001-05-21 13:45:10 +00001446 if( rc!=SQLITE_OK ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00001447
drh306dc212001-05-21 13:45:10 +00001448
1449 /* Do some checking to help insure the file we opened really is
1450 ** a valid database file.
1451 */
drhb6f41482004-05-14 01:58:11 +00001452 rc = SQLITE_NOTADB;
drha34b6762004-05-07 13:30:42 +00001453 if( sqlite3pager_pagecount(pBt->pPager)>0 ){
drhb6f41482004-05-14 01:58:11 +00001454 u8 *page1 = pPage1->aData;
1455 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001456 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001457 }
drhb6f41482004-05-14 01:58:11 +00001458 if( page1[18]>1 || page1[19]>1 ){
1459 goto page1_init_failed;
1460 }
drh07d183d2005-05-01 22:52:42 +00001461 pageSize = get2byte(&page1[16]);
1462 if( ((pageSize-1)&pageSize)!=0 ){
1463 goto page1_init_failed;
1464 }
1465 assert( (pageSize & 7)==0 );
1466 pBt->pageSize = pageSize;
1467 pBt->usableSize = pageSize - page1[20];
drhb6f41482004-05-14 01:58:11 +00001468 if( pBt->usableSize<500 ){
1469 goto page1_init_failed;
1470 }
1471 pBt->maxEmbedFrac = page1[21];
1472 pBt->minEmbedFrac = page1[22];
1473 pBt->minLeafFrac = page1[23];
drh057cd3a2005-02-15 16:23:02 +00001474#ifndef SQLITE_OMIT_AUTOVACUUM
1475 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
1476#endif
drh306dc212001-05-21 13:45:10 +00001477 }
drhb6f41482004-05-14 01:58:11 +00001478
1479 /* maxLocal is the maximum amount of payload to store locally for
1480 ** a cell. Make sure it is small enough so that at least minFanout
1481 ** cells can will fit on one page. We assume a 10-byte page header.
1482 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001483 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001484 ** 4-byte child pointer
1485 ** 9-byte nKey value
1486 ** 4-byte nData value
1487 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001488 ** So a cell consists of a 2-byte poiner, a header which is as much as
1489 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1490 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001491 */
drh43605152004-05-29 21:46:49 +00001492 pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
1493 pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
1494 pBt->maxLeaf = pBt->usableSize - 35;
1495 pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
drhb6f41482004-05-14 01:58:11 +00001496 if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
1497 goto page1_init_failed;
1498 }
drh2e38c322004-09-03 18:38:44 +00001499 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001500 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001501 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001502
drh72f82862001-05-24 21:06:34 +00001503page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001504 releasePage(pPage1);
1505 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001506 return rc;
drh306dc212001-05-21 13:45:10 +00001507}
1508
1509/*
drhb8ef32c2005-03-14 02:01:49 +00001510** This routine works like lockBtree() except that it also invokes the
1511** busy callback if there is lock contention.
1512*/
1513static int lockBtreeWithRetry(Btree *pBt){
1514 int rc = SQLITE_OK;
1515 if( pBt->inTrans==TRANS_NONE ){
1516 rc = sqlite3BtreeBeginTrans(pBt, 0);
1517 pBt->inTrans = TRANS_NONE;
1518 }
1519 return rc;
1520}
1521
1522
1523/*
drhb8ca3072001-12-05 00:21:20 +00001524** If there are no outstanding cursors and we are not in the middle
1525** of a transaction but there is a read lock on the database, then
1526** this routine unrefs the first page of the database file which
1527** has the effect of releasing the read lock.
1528**
1529** If there are any outstanding cursors, this routine is a no-op.
1530**
1531** If there is a transaction in progress, this routine is a no-op.
1532*/
1533static void unlockBtreeIfUnused(Btree *pBt){
danielk1977ee5741e2004-05-31 10:01:34 +00001534 if( pBt->inTrans==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
drh51c6d962004-06-06 00:42:25 +00001535 if( pBt->pPage1->aData==0 ){
1536 MemPage *pPage = pBt->pPage1;
drh07d183d2005-05-01 22:52:42 +00001537 pPage->aData = &((char*)pPage)[-pBt->pageSize];
drh51c6d962004-06-06 00:42:25 +00001538 pPage->pBt = pBt;
1539 pPage->pgno = 1;
1540 }
drh3aac2dd2004-04-26 14:10:20 +00001541 releasePage(pBt->pPage1);
1542 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00001543 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001544 }
1545}
1546
1547/*
drh9e572e62004-04-23 23:43:10 +00001548** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001549** file.
drh8b2f49b2001-06-08 00:21:52 +00001550*/
1551static int newDatabase(Btree *pBt){
drh9e572e62004-04-23 23:43:10 +00001552 MemPage *pP1;
1553 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001554 int rc;
drhde647132004-05-07 17:57:49 +00001555 if( sqlite3pager_pagecount(pBt->pPager)>0 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001556 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00001557 assert( pP1!=0 );
1558 data = pP1->aData;
drha34b6762004-05-07 13:30:42 +00001559 rc = sqlite3pager_write(data);
drh8b2f49b2001-06-08 00:21:52 +00001560 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00001561 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
1562 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00001563 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00001564 data[18] = 1;
1565 data[19] = 1;
drhb6f41482004-05-14 01:58:11 +00001566 data[20] = pBt->pageSize - pBt->usableSize;
1567 data[21] = pBt->maxEmbedFrac;
1568 data[22] = pBt->minEmbedFrac;
1569 data[23] = pBt->minLeafFrac;
1570 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00001571 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00001572 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00001573#ifndef SQLITE_OMIT_AUTOVACUUM
1574 if( pBt->autoVacuum ){
1575 put4byte(&data[36 + 4*4], 1);
1576 }
1577#endif
drh8b2f49b2001-06-08 00:21:52 +00001578 return SQLITE_OK;
1579}
1580
1581/*
danielk1977ee5741e2004-05-31 10:01:34 +00001582** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00001583** is started if the second argument is nonzero, otherwise a read-
1584** transaction. If the second argument is 2 or more and exclusive
1585** transaction is started, meaning that no other process is allowed
1586** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00001587** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00001588** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00001589**
danielk1977ee5741e2004-05-31 10:01:34 +00001590** A write-transaction must be started before attempting any
1591** changes to the database. None of the following routines
1592** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00001593**
drh23e11ca2004-05-04 17:27:28 +00001594** sqlite3BtreeCreateTable()
1595** sqlite3BtreeCreateIndex()
1596** sqlite3BtreeClearTable()
1597** sqlite3BtreeDropTable()
1598** sqlite3BtreeInsert()
1599** sqlite3BtreeDelete()
1600** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00001601**
drhb8ef32c2005-03-14 02:01:49 +00001602** If an initial attempt to acquire the lock fails because of lock contention
1603** and the database was previously unlocked, then invoke the busy handler
1604** if there is one. But if there was previously a read-lock, do not
1605** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
1606** returned when there is already a read-lock in order to avoid a deadlock.
1607**
1608** Suppose there are two processes A and B. A has a read lock and B has
1609** a reserved lock. B tries to promote to exclusive but is blocked because
1610** of A's read lock. A tries to promote to reserved but is blocked by B.
1611** One or the other of the two processes must give way or there can be
1612** no progress. By returning SQLITE_BUSY and not invoking the busy callback
1613** when A already has a read lock, we encourage A to give up and let B
1614** proceed.
drha059ad02001-04-17 20:09:11 +00001615*/
danielk197740b38dc2004-06-26 08:38:24 +00001616int sqlite3BtreeBeginTrans(Btree *pBt, int wrflag){
danielk1977ee5741e2004-05-31 10:01:34 +00001617 int rc = SQLITE_OK;
1618
1619 /* If the btree is already in a write-transaction, or it
1620 ** is already in a read-transaction and a read-transaction
1621 ** is requested, this is a no-op.
1622 */
drhb8ef32c2005-03-14 02:01:49 +00001623 if( pBt->inTrans==TRANS_WRITE || (pBt->inTrans==TRANS_READ && !wrflag) ){
danielk1977ee5741e2004-05-31 10:01:34 +00001624 return SQLITE_OK;
1625 }
drhb8ef32c2005-03-14 02:01:49 +00001626
1627 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00001628 if( pBt->readOnly && wrflag ){
1629 return SQLITE_READONLY;
1630 }
1631
drhb8ef32c2005-03-14 02:01:49 +00001632 do {
1633 if( pBt->pPage1==0 ){
1634 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +00001635 }
drhb8ef32c2005-03-14 02:01:49 +00001636
1637 if( rc==SQLITE_OK && wrflag ){
1638 rc = sqlite3pager_begin(pBt->pPage1->aData, wrflag>1);
1639 if( rc==SQLITE_OK ){
1640 rc = newDatabase(pBt);
1641 }
1642 }
1643
1644 if( rc==SQLITE_OK ){
1645 pBt->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
1646 if( wrflag ) pBt->inStmt = 0;
1647 }else{
1648 unlockBtreeIfUnused(pBt);
1649 }
1650 }while( rc==SQLITE_BUSY && pBt->inTrans==TRANS_NONE &&
drha4afb652005-07-09 02:16:02 +00001651 sqlite3InvokeBusyHandler(pBt->pBusyHandler) );
drhb8ca3072001-12-05 00:21:20 +00001652 return rc;
drha059ad02001-04-17 20:09:11 +00001653}
1654
danielk1977687566d2004-11-02 12:56:41 +00001655#ifndef SQLITE_OMIT_AUTOVACUUM
1656
1657/*
1658** Set the pointer-map entries for all children of page pPage. Also, if
1659** pPage contains cells that point to overflow pages, set the pointer
1660** map entries for the overflow pages as well.
1661*/
1662static int setChildPtrmaps(MemPage *pPage){
1663 int i; /* Counter variable */
1664 int nCell; /* Number of cells in page pPage */
1665 int rc = SQLITE_OK; /* Return code */
1666 Btree *pBt = pPage->pBt;
1667 int isInitOrig = pPage->isInit;
1668 Pgno pgno = pPage->pgno;
1669
1670 initPage(pPage, 0);
1671 nCell = pPage->nCell;
1672
1673 for(i=0; i<nCell; i++){
danielk1977687566d2004-11-02 12:56:41 +00001674 u8 *pCell = findCell(pPage, i);
1675
danielk197726836652005-01-17 01:33:13 +00001676 rc = ptrmapPutOvflPtr(pPage, pCell);
1677 if( rc!=SQLITE_OK ){
1678 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00001679 }
danielk197726836652005-01-17 01:33:13 +00001680
danielk1977687566d2004-11-02 12:56:41 +00001681 if( !pPage->leaf ){
1682 Pgno childPgno = get4byte(pCell);
1683 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
1684 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
1685 }
1686 }
1687
1688 if( !pPage->leaf ){
1689 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
1690 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
1691 }
1692
1693set_child_ptrmaps_out:
1694 pPage->isInit = isInitOrig;
1695 return rc;
1696}
1697
1698/*
1699** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
1700** page, is a pointer to page iFrom. Modify this pointer so that it points to
1701** iTo. Parameter eType describes the type of pointer to be modified, as
1702** follows:
1703**
1704** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
1705** page of pPage.
1706**
1707** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
1708** page pointed to by one of the cells on pPage.
1709**
1710** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
1711** overflow page in the list.
1712*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00001713static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
danielk1977687566d2004-11-02 12:56:41 +00001714 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00001715 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00001716 if( get4byte(pPage->aData)!=iFrom ){
1717 return SQLITE_CORRUPT;
1718 }
danielk1977f78fc082004-11-02 14:40:32 +00001719 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00001720 }else{
1721 int isInitOrig = pPage->isInit;
1722 int i;
1723 int nCell;
1724
1725 initPage(pPage, 0);
1726 nCell = pPage->nCell;
1727
danielk1977687566d2004-11-02 12:56:41 +00001728 for(i=0; i<nCell; i++){
1729 u8 *pCell = findCell(pPage, i);
1730 if( eType==PTRMAP_OVERFLOW1 ){
1731 CellInfo info;
1732 parseCellPtr(pPage, pCell, &info);
1733 if( info.iOverflow ){
1734 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
1735 put4byte(&pCell[info.iOverflow], iTo);
1736 break;
1737 }
1738 }
1739 }else{
1740 if( get4byte(pCell)==iFrom ){
1741 put4byte(pCell, iTo);
1742 break;
1743 }
1744 }
1745 }
1746
1747 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00001748 if( eType!=PTRMAP_BTREE ||
1749 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
1750 return SQLITE_CORRUPT;
1751 }
danielk1977687566d2004-11-02 12:56:41 +00001752 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
1753 }
1754
1755 pPage->isInit = isInitOrig;
1756 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00001757 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00001758}
1759
danielk1977003ba062004-11-04 02:57:33 +00001760
danielk19777701e812005-01-10 12:59:51 +00001761/*
1762** Move the open database page pDbPage to location iFreePage in the
1763** database. The pDbPage reference remains valid.
1764*/
danielk1977003ba062004-11-04 02:57:33 +00001765static int relocatePage(
danielk19777701e812005-01-10 12:59:51 +00001766 Btree *pBt, /* Btree */
1767 MemPage *pDbPage, /* Open page to move */
1768 u8 eType, /* Pointer map 'type' entry for pDbPage */
1769 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
1770 Pgno iFreePage /* The location to move pDbPage to */
danielk1977003ba062004-11-04 02:57:33 +00001771){
1772 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
1773 Pgno iDbPage = pDbPage->pgno;
1774 Pager *pPager = pBt->pPager;
1775 int rc;
1776
danielk1977a0bf2652004-11-04 14:30:04 +00001777 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
1778 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
danielk1977003ba062004-11-04 02:57:33 +00001779
1780 /* Move page iDbPage from it's current location to page number iFreePage */
1781 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
1782 iDbPage, iFreePage, iPtrPage, eType));
1783 rc = sqlite3pager_movepage(pPager, pDbPage->aData, iFreePage);
1784 if( rc!=SQLITE_OK ){
1785 return rc;
1786 }
1787 pDbPage->pgno = iFreePage;
1788
1789 /* If pDbPage was a btree-page, then it may have child pages and/or cells
1790 ** that point to overflow pages. The pointer map entries for all these
1791 ** pages need to be changed.
1792 **
1793 ** If pDbPage is an overflow page, then the first 4 bytes may store a
1794 ** pointer to a subsequent overflow page. If this is the case, then
1795 ** the pointer map needs to be updated for the subsequent overflow page.
1796 */
danielk1977a0bf2652004-11-04 14:30:04 +00001797 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00001798 rc = setChildPtrmaps(pDbPage);
1799 if( rc!=SQLITE_OK ){
1800 return rc;
1801 }
1802 }else{
1803 Pgno nextOvfl = get4byte(pDbPage->aData);
1804 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00001805 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
1806 if( rc!=SQLITE_OK ){
1807 return rc;
1808 }
1809 }
1810 }
1811
1812 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
1813 ** that it points at iFreePage. Also fix the pointer map entry for
1814 ** iPtrPage.
1815 */
danielk1977a0bf2652004-11-04 14:30:04 +00001816 if( eType!=PTRMAP_ROOTPAGE ){
1817 rc = getPage(pBt, iPtrPage, &pPtrPage);
1818 if( rc!=SQLITE_OK ){
1819 return rc;
1820 }
1821 rc = sqlite3pager_write(pPtrPage->aData);
1822 if( rc!=SQLITE_OK ){
1823 releasePage(pPtrPage);
1824 return rc;
1825 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00001826 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00001827 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00001828 if( rc==SQLITE_OK ){
1829 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
1830 }
danielk1977003ba062004-11-04 02:57:33 +00001831 }
danielk1977003ba062004-11-04 02:57:33 +00001832 return rc;
1833}
1834
danielk1977687566d2004-11-02 12:56:41 +00001835/* Forward declaration required by autoVacuumCommit(). */
danielk1977cb1a7eb2004-11-05 12:27:02 +00001836static int allocatePage(Btree *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00001837
1838/*
1839** This routine is called prior to sqlite3pager_commit when a transaction
1840** is commited for an auto-vacuum database.
1841*/
danielk1977d761c0c2004-11-05 16:37:02 +00001842static int autoVacuumCommit(Btree *pBt, Pgno *nTrunc){
danielk1977687566d2004-11-02 12:56:41 +00001843 Pager *pPager = pBt->pPager;
1844 Pgno nFreeList; /* Number of pages remaining on the free-list. */
danielk1977a19df672004-11-03 11:37:07 +00001845 int nPtrMap; /* Number of pointer-map pages deallocated */
1846 Pgno origSize; /* Pages in the database file */
1847 Pgno finSize; /* Pages in the database file after truncation */
danielk1977687566d2004-11-02 12:56:41 +00001848 int rc; /* Return code */
1849 u8 eType;
danielk1977a19df672004-11-03 11:37:07 +00001850 int pgsz = pBt->pageSize; /* Page size for this database */
danielk1977687566d2004-11-02 12:56:41 +00001851 Pgno iDbPage; /* The database page to move */
danielk1977687566d2004-11-02 12:56:41 +00001852 MemPage *pDbMemPage = 0; /* "" */
1853 Pgno iPtrPage; /* The page that contains a pointer to iDbPage */
danielk1977687566d2004-11-02 12:56:41 +00001854 Pgno iFreePage; /* The free-list page to move iDbPage to */
1855 MemPage *pFreeMemPage = 0; /* "" */
1856
1857#ifndef NDEBUG
1858 int nRef = *sqlite3pager_stats(pPager);
1859#endif
1860
1861 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +00001862 if( PTRMAP_ISPAGE(pgsz, sqlite3pager_pagecount(pPager)) ){
1863 return SQLITE_CORRUPT;
1864 }
danielk1977687566d2004-11-02 12:56:41 +00001865
1866 /* Figure out how many free-pages are in the database. If there are no
1867 ** free pages, then auto-vacuum is a no-op.
1868 */
1869 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977a19df672004-11-03 11:37:07 +00001870 if( nFreeList==0 ){
danielk1977d761c0c2004-11-05 16:37:02 +00001871 *nTrunc = 0;
danielk1977a19df672004-11-03 11:37:07 +00001872 return SQLITE_OK;
1873 }
danielk1977687566d2004-11-02 12:56:41 +00001874
danielk1977a19df672004-11-03 11:37:07 +00001875 origSize = sqlite3pager_pagecount(pPager);
1876 nPtrMap = (nFreeList-origSize+PTRMAP_PAGENO(pgsz, origSize)+pgsz/5)/(pgsz/5);
1877 finSize = origSize - nFreeList - nPtrMap;
danielk1977599fcba2004-11-08 07:13:13 +00001878 if( origSize>PENDING_BYTE_PAGE(pBt) && finSize<=PENDING_BYTE_PAGE(pBt) ){
1879 finSize--;
drh42cac6d2004-11-20 20:31:11 +00001880 if( PTRMAP_ISPAGE(pBt->usableSize, finSize) ){
danielk1977599fcba2004-11-08 07:13:13 +00001881 finSize--;
1882 }
1883 }
danielk1977a19df672004-11-03 11:37:07 +00001884 TRACE(("AUTOVACUUM: Begin (db size %d->%d)\n", origSize, finSize));
danielk1977687566d2004-11-02 12:56:41 +00001885
danielk1977a19df672004-11-03 11:37:07 +00001886 /* Variable 'finSize' will be the size of the file in pages after
danielk1977687566d2004-11-02 12:56:41 +00001887 ** the auto-vacuum has completed (the current file size minus the number
1888 ** of pages on the free list). Loop through the pages that lie beyond
1889 ** this mark, and if they are not already on the free list, move them
danielk1977a19df672004-11-03 11:37:07 +00001890 ** to a free page earlier in the file (somewhere before finSize).
danielk1977687566d2004-11-02 12:56:41 +00001891 */
danielk1977a19df672004-11-03 11:37:07 +00001892 for( iDbPage=finSize+1; iDbPage<=origSize; iDbPage++ ){
danielk1977599fcba2004-11-08 07:13:13 +00001893 /* If iDbPage is a pointer map page, or the pending-byte page, skip it. */
1894 if( PTRMAP_ISPAGE(pgsz, iDbPage) || iDbPage==PENDING_BYTE_PAGE(pBt) ){
1895 continue;
1896 }
1897
danielk1977687566d2004-11-02 12:56:41 +00001898 rc = ptrmapGet(pBt, iDbPage, &eType, &iPtrPage);
1899 if( rc!=SQLITE_OK ) goto autovacuum_out;
drhccae6022005-02-26 17:31:26 +00001900 if( eType==PTRMAP_ROOTPAGE ){
1901 rc = SQLITE_CORRUPT;
1902 goto autovacuum_out;
1903 }
danielk1977687566d2004-11-02 12:56:41 +00001904
danielk1977599fcba2004-11-08 07:13:13 +00001905 /* If iDbPage is free, do not swap it. */
1906 if( eType==PTRMAP_FREEPAGE ){
danielk1977687566d2004-11-02 12:56:41 +00001907 continue;
1908 }
1909 rc = getPage(pBt, iDbPage, &pDbMemPage);
1910 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977687566d2004-11-02 12:56:41 +00001911
1912 /* Find the next page in the free-list that is not already at the end
1913 ** of the file. A page can be pulled off the free list using the
1914 ** allocatePage() routine.
1915 */
1916 do{
1917 if( pFreeMemPage ){
1918 releasePage(pFreeMemPage);
1919 pFreeMemPage = 0;
1920 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00001921 rc = allocatePage(pBt, &pFreeMemPage, &iFreePage, 0, 0);
danielk1977ac11ee62005-01-15 12:45:51 +00001922 if( rc!=SQLITE_OK ){
1923 releasePage(pDbMemPage);
1924 goto autovacuum_out;
1925 }
danielk1977a19df672004-11-03 11:37:07 +00001926 assert( iFreePage<=origSize );
1927 }while( iFreePage>finSize );
danielk1977687566d2004-11-02 12:56:41 +00001928 releasePage(pFreeMemPage);
1929 pFreeMemPage = 0;
danielk1977687566d2004-11-02 12:56:41 +00001930
danielk1977003ba062004-11-04 02:57:33 +00001931 rc = relocatePage(pBt, pDbMemPage, eType, iPtrPage, iFreePage);
danielk1977687566d2004-11-02 12:56:41 +00001932 releasePage(pDbMemPage);
danielk1977687566d2004-11-02 12:56:41 +00001933 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977687566d2004-11-02 12:56:41 +00001934 }
1935
1936 /* The entire free-list has been swapped to the end of the file. So
danielk1977a19df672004-11-03 11:37:07 +00001937 ** truncate the database file to finSize pages and consider the
danielk1977687566d2004-11-02 12:56:41 +00001938 ** free-list empty.
1939 */
1940 rc = sqlite3pager_write(pBt->pPage1->aData);
1941 if( rc!=SQLITE_OK ) goto autovacuum_out;
1942 put4byte(&pBt->pPage1->aData[32], 0);
1943 put4byte(&pBt->pPage1->aData[36], 0);
danielk1977687566d2004-11-02 12:56:41 +00001944 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977d761c0c2004-11-05 16:37:02 +00001945 *nTrunc = finSize;
danielk1977687566d2004-11-02 12:56:41 +00001946
1947autovacuum_out:
danielk1977687566d2004-11-02 12:56:41 +00001948 assert( nRef==*sqlite3pager_stats(pPager) );
1949 if( rc!=SQLITE_OK ){
1950 sqlite3pager_rollback(pPager);
1951 }
1952 return rc;
1953}
1954#endif
1955
1956/*
drh2aa679f2001-06-25 02:11:07 +00001957** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00001958**
1959** This will release the write lock on the database file. If there
1960** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00001961*/
drh3aac2dd2004-04-26 14:10:20 +00001962int sqlite3BtreeCommit(Btree *pBt){
danielk1977ee5741e2004-05-31 10:01:34 +00001963 int rc = SQLITE_OK;
1964 if( pBt->inTrans==TRANS_WRITE ){
1965 rc = sqlite3pager_commit(pBt->pPager);
1966 }
1967 pBt->inTrans = TRANS_NONE;
drh3aac2dd2004-04-26 14:10:20 +00001968 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00001969 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001970 return rc;
1971}
1972
danielk1977fbcd5852004-06-15 02:44:18 +00001973#ifndef NDEBUG
1974/*
1975** Return the number of write-cursors open on this handle. This is for use
1976** in assert() expressions, so it is only compiled if NDEBUG is not
1977** defined.
1978*/
1979static int countWriteCursors(Btree *pBt){
1980 BtCursor *pCur;
1981 int r = 0;
1982 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1983 if( pCur->wrFlag ) r++;
1984 }
1985 return r;
1986}
1987#endif
1988
drhda200cc2004-05-09 11:51:38 +00001989#ifdef SQLITE_TEST
1990/*
1991** Print debugging information about all cursors to standard output.
1992*/
1993void sqlite3BtreeCursorList(Btree *pBt){
1994 BtCursor *pCur;
1995 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
1996 MemPage *pPage = pCur->pPage;
1997 char *zMode = pCur->wrFlag ? "rw" : "ro";
drhfe63d1c2004-09-08 20:13:04 +00001998 sqlite3DebugPrintf("CURSOR %p rooted at %4d(%s) currently at %d.%d%s\n",
1999 pCur, pCur->pgnoRoot, zMode,
drhda200cc2004-05-09 11:51:38 +00002000 pPage ? pPage->pgno : 0, pCur->idx,
2001 pCur->isValid ? "" : " eof"
2002 );
2003 }
2004}
2005#endif
2006
drhc39e0002004-05-07 23:50:57 +00002007/*
drhecdc7532001-09-23 02:35:53 +00002008** Rollback the transaction in progress. All cursors will be
2009** invalided by this operation. Any attempt to use a cursor
2010** that was open at the beginning of this operation will result
2011** in an error.
drh5e00f6c2001-09-13 13:46:56 +00002012**
2013** This will release the write lock on the database file. If there
2014** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002015*/
drh3aac2dd2004-04-26 14:10:20 +00002016int sqlite3BtreeRollback(Btree *pBt){
danielk1977cfe9a692004-06-16 12:00:29 +00002017 int rc = SQLITE_OK;
drh24cd67e2004-05-10 16:18:47 +00002018 MemPage *pPage1;
danielk1977ee5741e2004-05-31 10:01:34 +00002019 if( pBt->inTrans==TRANS_WRITE ){
drh24cd67e2004-05-10 16:18:47 +00002020 rc = sqlite3pager_rollback(pBt->pPager);
2021 /* The rollback may have destroyed the pPage1->aData value. So
2022 ** call getPage() on page 1 again to make sure pPage1->aData is
2023 ** set correctly. */
2024 if( getPage(pBt, 1, &pPage1)==SQLITE_OK ){
2025 releasePage(pPage1);
2026 }
danielk1977fbcd5852004-06-15 02:44:18 +00002027 assert( countWriteCursors(pBt)==0 );
drh24cd67e2004-05-10 16:18:47 +00002028 }
danielk1977ee5741e2004-05-31 10:01:34 +00002029 pBt->inTrans = TRANS_NONE;
2030 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00002031 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00002032 return rc;
2033}
2034
2035/*
drhab01f612004-05-22 02:55:23 +00002036** Start a statement subtransaction. The subtransaction can
2037** can be rolled back independently of the main transaction.
2038** You must start a transaction before starting a subtransaction.
2039** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00002040** commits or rolls back.
2041**
drhab01f612004-05-22 02:55:23 +00002042** Only one subtransaction may be active at a time. It is an error to try
2043** to start a new subtransaction if another subtransaction is already active.
2044**
2045** Statement subtransactions are used around individual SQL statements
2046** that are contained within a BEGIN...COMMIT block. If a constraint
2047** error occurs within the statement, the effect of that one statement
2048** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00002049*/
drh3aac2dd2004-04-26 14:10:20 +00002050int sqlite3BtreeBeginStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00002051 int rc;
danielk1977ee5741e2004-05-31 10:01:34 +00002052 if( (pBt->inTrans!=TRANS_WRITE) || pBt->inStmt ){
drhf74b8d92002-09-01 23:20:45 +00002053 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh0d65dc02002-02-03 00:56:09 +00002054 }
drha34b6762004-05-07 13:30:42 +00002055 rc = pBt->readOnly ? SQLITE_OK : sqlite3pager_stmt_begin(pBt->pPager);
drh3aac2dd2004-04-26 14:10:20 +00002056 pBt->inStmt = 1;
drh663fc632002-02-02 18:49:19 +00002057 return rc;
2058}
2059
2060
2061/*
drhab01f612004-05-22 02:55:23 +00002062** Commit the statment subtransaction currently in progress. If no
2063** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00002064*/
drh3aac2dd2004-04-26 14:10:20 +00002065int sqlite3BtreeCommitStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00002066 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002067 if( pBt->inStmt && !pBt->readOnly ){
drha34b6762004-05-07 13:30:42 +00002068 rc = sqlite3pager_stmt_commit(pBt->pPager);
drh663fc632002-02-02 18:49:19 +00002069 }else{
2070 rc = SQLITE_OK;
2071 }
drh3aac2dd2004-04-26 14:10:20 +00002072 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00002073 return rc;
2074}
2075
2076/*
drhab01f612004-05-22 02:55:23 +00002077** Rollback the active statement subtransaction. If no subtransaction
2078** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00002079**
drhab01f612004-05-22 02:55:23 +00002080** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00002081** to use a cursor that was open at the beginning of this operation
2082** will result in an error.
2083*/
drh3aac2dd2004-04-26 14:10:20 +00002084int sqlite3BtreeRollbackStmt(Btree *pBt){
drh663fc632002-02-02 18:49:19 +00002085 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002086 if( pBt->inStmt==0 || pBt->readOnly ) return SQLITE_OK;
drha34b6762004-05-07 13:30:42 +00002087 rc = sqlite3pager_stmt_rollback(pBt->pPager);
danielk1977fbcd5852004-06-15 02:44:18 +00002088 assert( countWriteCursors(pBt)==0 );
drh3aac2dd2004-04-26 14:10:20 +00002089 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00002090 return rc;
2091}
2092
2093/*
drh3aac2dd2004-04-26 14:10:20 +00002094** Default key comparison function to be used if no comparison function
2095** is specified on the sqlite3BtreeCursor() call.
2096*/
2097static int dfltCompare(
2098 void *NotUsed, /* User data is not used */
2099 int n1, const void *p1, /* First key to compare */
2100 int n2, const void *p2 /* Second key to compare */
2101){
2102 int c;
2103 c = memcmp(p1, p2, n1<n2 ? n1 : n2);
2104 if( c==0 ){
2105 c = n1 - n2;
2106 }
2107 return c;
2108}
2109
2110/*
drh8b2f49b2001-06-08 00:21:52 +00002111** Create a new cursor for the BTree whose root is on the page
2112** iTable. The act of acquiring a cursor gets a read lock on
2113** the database file.
drh1bee3d72001-10-15 00:44:35 +00002114**
2115** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00002116** If wrFlag==1, then the cursor can be used for reading or for
2117** writing if other conditions for writing are also met. These
2118** are the conditions that must be met in order for writing to
2119** be allowed:
drh6446c4d2001-12-15 14:22:18 +00002120**
drhf74b8d92002-09-01 23:20:45 +00002121** 1: The cursor must have been opened with wrFlag==1
2122**
2123** 2: No other cursors may be open with wrFlag==0 on the same table
2124**
2125** 3: The database must be writable (not on read-only media)
2126**
2127** 4: There must be an active transaction.
2128**
2129** Condition 2 warrants further discussion. If any cursor is opened
2130** on a table with wrFlag==0, that prevents all other cursors from
2131** writing to that table. This is a kind of "read-lock". When a cursor
2132** is opened with wrFlag==0 it is guaranteed that the table will not
2133** change as long as the cursor is open. This allows the cursor to
2134** do a sequential scan of the table without having to worry about
2135** entries being inserted or deleted during the scan. Cursors should
2136** be opened with wrFlag==0 only if this read-lock property is needed.
2137** That is to say, cursors should be opened with wrFlag==0 only if they
drh23e11ca2004-05-04 17:27:28 +00002138** intend to use the sqlite3BtreeNext() system call. All other cursors
drhf74b8d92002-09-01 23:20:45 +00002139** should be opened with wrFlag==1 even if they never really intend
2140** to write.
2141**
drh6446c4d2001-12-15 14:22:18 +00002142** No checking is done to make sure that page iTable really is the
2143** root page of a b-tree. If it is not, then the cursor acquired
2144** will not work correctly.
drh3aac2dd2004-04-26 14:10:20 +00002145**
2146** The comparison function must be logically the same for every cursor
2147** on a particular table. Changing the comparison function will result
2148** in incorrect operations. If the comparison function is NULL, a
2149** default comparison function is used. The comparison function is
2150** always ignored for INTKEY tables.
drha059ad02001-04-17 20:09:11 +00002151*/
drh3aac2dd2004-04-26 14:10:20 +00002152int sqlite3BtreeCursor(
2153 Btree *pBt, /* The btree */
2154 int iTable, /* Root page of table to open */
2155 int wrFlag, /* 1 to write. 0 read-only */
2156 int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
2157 void *pArg, /* First arg to xCompare() */
2158 BtCursor **ppCur /* Write new cursor here */
2159){
drha059ad02001-04-17 20:09:11 +00002160 int rc;
drh8dcd7ca2004-08-08 19:43:29 +00002161 BtCursor *pCur;
drhecdc7532001-09-23 02:35:53 +00002162
drh8dcd7ca2004-08-08 19:43:29 +00002163 *ppCur = 0;
2164 if( wrFlag ){
drh8dcd7ca2004-08-08 19:43:29 +00002165 if( pBt->readOnly ){
2166 return SQLITE_READONLY;
2167 }
2168 if( checkReadLocks(pBt, iTable, 0) ){
2169 return SQLITE_LOCKED;
2170 }
drha0c9a112004-03-10 13:42:37 +00002171 }
drh4b70f112004-05-02 21:12:19 +00002172 if( pBt->pPage1==0 ){
drhb8ef32c2005-03-14 02:01:49 +00002173 rc = lockBtreeWithRetry(pBt);
drha059ad02001-04-17 20:09:11 +00002174 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002175 return rc;
2176 }
2177 }
drheafe05b2004-06-13 00:54:01 +00002178 pCur = sqliteMallocRaw( sizeof(*pCur) );
drha059ad02001-04-17 20:09:11 +00002179 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +00002180 rc = SQLITE_NOMEM;
2181 goto create_cursor_exception;
2182 }
drh8b2f49b2001-06-08 00:21:52 +00002183 pCur->pgnoRoot = (Pgno)iTable;
danielk19776b456a22005-03-21 04:04:02 +00002184 pCur->pPage = 0; /* For exit-handler, in case getAndInitPage() fails. */
drh24cd67e2004-05-10 16:18:47 +00002185 if( iTable==1 && sqlite3pager_pagecount(pBt->pPager)==0 ){
2186 rc = SQLITE_EMPTY;
2187 goto create_cursor_exception;
2188 }
drhde647132004-05-07 17:57:49 +00002189 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
drhbd03cae2001-06-02 02:40:57 +00002190 if( rc!=SQLITE_OK ){
2191 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002192 }
drh3aac2dd2004-04-26 14:10:20 +00002193 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2194 pCur->pArg = pArg;
drh14acc042001-06-10 19:56:58 +00002195 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +00002196 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +00002197 pCur->idx = 0;
drh59eb6762004-06-13 23:07:04 +00002198 memset(&pCur->info, 0, sizeof(pCur->info));
drha059ad02001-04-17 20:09:11 +00002199 pCur->pNext = pBt->pCursor;
2200 if( pCur->pNext ){
2201 pCur->pNext->pPrev = pCur;
2202 }
drh14acc042001-06-10 19:56:58 +00002203 pCur->pPrev = 0;
drha059ad02001-04-17 20:09:11 +00002204 pBt->pCursor = pCur;
drhc39e0002004-05-07 23:50:57 +00002205 pCur->isValid = 0;
drh2af926b2001-05-15 00:39:25 +00002206 *ppCur = pCur;
2207 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00002208
2209create_cursor_exception:
drhbd03cae2001-06-02 02:40:57 +00002210 if( pCur ){
drh3aac2dd2004-04-26 14:10:20 +00002211 releasePage(pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +00002212 sqliteFree(pCur);
2213 }
drh5e00f6c2001-09-13 13:46:56 +00002214 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00002215 return rc;
drha059ad02001-04-17 20:09:11 +00002216}
2217
drh7a224de2004-06-02 01:22:02 +00002218#if 0 /* Not Used */
drhd3d39e92004-05-20 22:16:29 +00002219/*
2220** Change the value of the comparison function used by a cursor.
2221*/
danielk1977bf3b7212004-05-18 10:06:24 +00002222void sqlite3BtreeSetCompare(
drhd3d39e92004-05-20 22:16:29 +00002223 BtCursor *pCur, /* The cursor to whose comparison function is changed */
2224 int(*xCmp)(void*,int,const void*,int,const void*), /* New comparison func */
2225 void *pArg /* First argument to xCmp() */
danielk1977bf3b7212004-05-18 10:06:24 +00002226){
2227 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2228 pCur->pArg = pArg;
2229}
drh7a224de2004-06-02 01:22:02 +00002230#endif
danielk1977bf3b7212004-05-18 10:06:24 +00002231
drha059ad02001-04-17 20:09:11 +00002232/*
drh5e00f6c2001-09-13 13:46:56 +00002233** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00002234** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00002235*/
drh3aac2dd2004-04-26 14:10:20 +00002236int sqlite3BtreeCloseCursor(BtCursor *pCur){
drha059ad02001-04-17 20:09:11 +00002237 Btree *pBt = pCur->pBt;
drha059ad02001-04-17 20:09:11 +00002238 if( pCur->pPrev ){
2239 pCur->pPrev->pNext = pCur->pNext;
2240 }else{
2241 pBt->pCursor = pCur->pNext;
2242 }
2243 if( pCur->pNext ){
2244 pCur->pNext->pPrev = pCur->pPrev;
2245 }
drh3aac2dd2004-04-26 14:10:20 +00002246 releasePage(pCur->pPage);
drh5e00f6c2001-09-13 13:46:56 +00002247 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00002248 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +00002249 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002250}
2251
drh7e3b0a02001-04-28 16:52:40 +00002252/*
drh5e2f8b92001-05-28 00:41:15 +00002253** Make a temporary cursor by filling in the fields of pTempCur.
2254** The temporary cursor is not on the cursor list for the Btree.
2255*/
drh14acc042001-06-10 19:56:58 +00002256static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00002257 memcpy(pTempCur, pCur, sizeof(*pCur));
2258 pTempCur->pNext = 0;
2259 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00002260 if( pTempCur->pPage ){
drha34b6762004-05-07 13:30:42 +00002261 sqlite3pager_ref(pTempCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00002262 }
drh5e2f8b92001-05-28 00:41:15 +00002263}
2264
2265/*
drhbd03cae2001-06-02 02:40:57 +00002266** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00002267** function above.
2268*/
drh14acc042001-06-10 19:56:58 +00002269static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00002270 if( pCur->pPage ){
drha34b6762004-05-07 13:30:42 +00002271 sqlite3pager_unref(pCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00002272 }
drh5e2f8b92001-05-28 00:41:15 +00002273}
2274
2275/*
drh9188b382004-05-14 21:12:22 +00002276** Make sure the BtCursor.info field of the given cursor is valid.
drhab01f612004-05-22 02:55:23 +00002277** If it is not already valid, call parseCell() to fill it in.
2278**
2279** BtCursor.info is a cache of the information in the current cell.
2280** Using this cache reduces the number of calls to parseCell().
drh9188b382004-05-14 21:12:22 +00002281*/
2282static void getCellInfo(BtCursor *pCur){
drh271efa52004-05-30 19:19:05 +00002283 if( pCur->info.nSize==0 ){
drh3a41a3f2004-05-30 02:14:17 +00002284 parseCell(pCur->pPage, pCur->idx, &pCur->info);
drh9188b382004-05-14 21:12:22 +00002285 }else{
2286#ifndef NDEBUG
2287 CellInfo info;
drh51c6d962004-06-06 00:42:25 +00002288 memset(&info, 0, sizeof(info));
drh3a41a3f2004-05-30 02:14:17 +00002289 parseCell(pCur->pPage, pCur->idx, &info);
drh9188b382004-05-14 21:12:22 +00002290 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
2291#endif
2292 }
2293}
2294
2295/*
drh3aac2dd2004-04-26 14:10:20 +00002296** Set *pSize to the size of the buffer needed to hold the value of
2297** the key for the current entry. If the cursor is not pointing
2298** to a valid entry, *pSize is set to 0.
2299**
drh4b70f112004-05-02 21:12:19 +00002300** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00002301** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00002302*/
drh4a1c3802004-05-12 15:15:47 +00002303int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
danielk1977299b1872004-11-22 10:02:10 +00002304 if( !pCur->isValid ){
drh72f82862001-05-24 21:06:34 +00002305 *pSize = 0;
2306 }else{
drh9188b382004-05-14 21:12:22 +00002307 getCellInfo(pCur);
2308 *pSize = pCur->info.nKey;
drh72f82862001-05-24 21:06:34 +00002309 }
2310 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002311}
drh2af926b2001-05-15 00:39:25 +00002312
drh72f82862001-05-24 21:06:34 +00002313/*
drh0e1c19e2004-05-11 00:58:56 +00002314** Set *pSize to the number of bytes of data in the entry the
2315** cursor currently points to. Always return SQLITE_OK.
2316** Failure is not possible. If the cursor is not currently
2317** pointing to an entry (which can happen, for example, if
2318** the database is empty) then *pSize is set to 0.
2319*/
2320int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
danielk1977299b1872004-11-22 10:02:10 +00002321 if( !pCur->isValid ){
danielk197796fc5fe2004-05-13 11:34:16 +00002322 /* Not pointing at a valid entry - set *pSize to 0. */
drh0e1c19e2004-05-11 00:58:56 +00002323 *pSize = 0;
2324 }else{
drh9188b382004-05-14 21:12:22 +00002325 getCellInfo(pCur);
2326 *pSize = pCur->info.nData;
drh0e1c19e2004-05-11 00:58:56 +00002327 }
2328 return SQLITE_OK;
2329}
2330
2331/*
drh72f82862001-05-24 21:06:34 +00002332** Read payload information from the entry that the pCur cursor is
2333** pointing to. Begin reading the payload at "offset" and read
2334** a total of "amt" bytes. Put the result in zBuf.
2335**
2336** This routine does not make a distinction between key and data.
drhab01f612004-05-22 02:55:23 +00002337** It just reads bytes from the payload area. Data might appear
2338** on the main page or be scattered out on multiple overflow pages.
drh72f82862001-05-24 21:06:34 +00002339*/
drh3aac2dd2004-04-26 14:10:20 +00002340static int getPayload(
2341 BtCursor *pCur, /* Cursor pointing to entry to read from */
2342 int offset, /* Begin reading this far into payload */
2343 int amt, /* Read this many bytes */
2344 unsigned char *pBuf, /* Write the bytes into this buffer */
2345 int skipKey /* offset begins at data if this is true */
2346){
2347 unsigned char *aPayload;
drh2af926b2001-05-15 00:39:25 +00002348 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +00002349 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002350 MemPage *pPage;
2351 Btree *pBt;
drh6f11bef2004-05-13 01:12:56 +00002352 int ovflSize;
drhfa1a98a2004-05-14 19:08:17 +00002353 u32 nKey;
drh3aac2dd2004-04-26 14:10:20 +00002354
drh72f82862001-05-24 21:06:34 +00002355 assert( pCur!=0 && pCur->pPage!=0 );
drhc39e0002004-05-07 23:50:57 +00002356 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00002357 pBt = pCur->pBt;
2358 pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00002359 pageIntegrity(pPage);
drh3aac2dd2004-04-26 14:10:20 +00002360 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00002361 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00002362 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00002363 aPayload += pCur->info.nHeader;
drh3aac2dd2004-04-26 14:10:20 +00002364 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00002365 nKey = 0;
2366 }else{
2367 nKey = pCur->info.nKey;
drh3aac2dd2004-04-26 14:10:20 +00002368 }
2369 assert( offset>=0 );
2370 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00002371 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00002372 }
drhfa1a98a2004-05-14 19:08:17 +00002373 if( offset+amt > nKey+pCur->info.nData ){
drha34b6762004-05-07 13:30:42 +00002374 return SQLITE_ERROR;
drh3aac2dd2004-04-26 14:10:20 +00002375 }
drhfa1a98a2004-05-14 19:08:17 +00002376 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00002377 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00002378 if( a+offset>pCur->info.nLocal ){
2379 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00002380 }
drha34b6762004-05-07 13:30:42 +00002381 memcpy(pBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +00002382 if( a==amt ){
2383 return SQLITE_OK;
2384 }
drh2aa679f2001-06-25 02:11:07 +00002385 offset = 0;
drha34b6762004-05-07 13:30:42 +00002386 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00002387 amt -= a;
drhdd793422001-06-28 01:54:48 +00002388 }else{
drhfa1a98a2004-05-14 19:08:17 +00002389 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00002390 }
danielk1977cfe9a692004-06-16 12:00:29 +00002391 ovflSize = pBt->usableSize - 4;
drhbd03cae2001-06-02 02:40:57 +00002392 if( amt>0 ){
drhfa1a98a2004-05-14 19:08:17 +00002393 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977cfe9a692004-06-16 12:00:29 +00002394 while( amt>0 && nextPage ){
2395 rc = sqlite3pager_get(pBt->pPager, nextPage, (void**)&aPayload);
2396 if( rc!=0 ){
2397 return rc;
drh2af926b2001-05-15 00:39:25 +00002398 }
danielk1977cfe9a692004-06-16 12:00:29 +00002399 nextPage = get4byte(aPayload);
2400 if( offset<ovflSize ){
2401 int a = amt;
2402 if( a + offset > ovflSize ){
2403 a = ovflSize - offset;
2404 }
2405 memcpy(pBuf, &aPayload[offset+4], a);
2406 offset = 0;
2407 amt -= a;
2408 pBuf += a;
2409 }else{
2410 offset -= ovflSize;
2411 }
2412 sqlite3pager_unref(aPayload);
drh2af926b2001-05-15 00:39:25 +00002413 }
drh2af926b2001-05-15 00:39:25 +00002414 }
danielk1977cfe9a692004-06-16 12:00:29 +00002415
drha7fcb052001-12-14 15:09:55 +00002416 if( amt>0 ){
drhee696e22004-08-30 16:52:17 +00002417 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
drha7fcb052001-12-14 15:09:55 +00002418 }
2419 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00002420}
2421
drh72f82862001-05-24 21:06:34 +00002422/*
drh3aac2dd2004-04-26 14:10:20 +00002423** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002424** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002425** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00002426**
drh3aac2dd2004-04-26 14:10:20 +00002427** Return SQLITE_OK on success or an error code if anything goes
2428** wrong. An error is returned if "offset+amt" is larger than
2429** the available payload.
drh72f82862001-05-24 21:06:34 +00002430*/
drha34b6762004-05-07 13:30:42 +00002431int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
danielk197728129562005-01-11 10:25:06 +00002432 assert( pCur->isValid );
drhc39e0002004-05-07 23:50:57 +00002433 assert( pCur->pPage!=0 );
drh6575a222005-03-10 17:06:34 +00002434 if( pCur->pPage->intKey ){
2435 return SQLITE_CORRUPT;
2436 }
drhc39e0002004-05-07 23:50:57 +00002437 assert( pCur->pPage->intKey==0 );
2438 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh3aac2dd2004-04-26 14:10:20 +00002439 return getPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
2440}
2441
2442/*
drh3aac2dd2004-04-26 14:10:20 +00002443** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002444** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002445** begins at "offset".
2446**
2447** Return SQLITE_OK on success or an error code if anything goes
2448** wrong. An error is returned if "offset+amt" is larger than
2449** the available payload.
drh72f82862001-05-24 21:06:34 +00002450*/
drh3aac2dd2004-04-26 14:10:20 +00002451int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
danielk197728129562005-01-11 10:25:06 +00002452 assert( pCur->isValid );
drh8c1238a2003-01-02 14:43:55 +00002453 assert( pCur->pPage!=0 );
drhc39e0002004-05-07 23:50:57 +00002454 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh3aac2dd2004-04-26 14:10:20 +00002455 return getPayload(pCur, offset, amt, pBuf, 1);
drh2af926b2001-05-15 00:39:25 +00002456}
2457
drh72f82862001-05-24 21:06:34 +00002458/*
drh0e1c19e2004-05-11 00:58:56 +00002459** Return a pointer to payload information from the entry that the
2460** pCur cursor is pointing to. The pointer is to the beginning of
2461** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00002462** skipKey==1. The number of bytes of available key/data is written
2463** into *pAmt. If *pAmt==0, then the value returned will not be
2464** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00002465**
2466** This routine is an optimization. It is common for the entire key
2467** and data to fit on the local page and for there to be no overflow
2468** pages. When that is so, this routine can be used to access the
2469** key and data without making a copy. If the key and/or data spills
2470** onto overflow pages, then getPayload() must be used to reassembly
2471** the key/data and copy it into a preallocated buffer.
2472**
2473** The pointer returned by this routine looks directly into the cached
2474** page of the database. The data might change or move the next time
2475** any btree routine is called.
2476*/
2477static const unsigned char *fetchPayload(
2478 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00002479 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00002480 int skipKey /* read beginning at data if this is true */
2481){
2482 unsigned char *aPayload;
2483 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00002484 u32 nKey;
2485 int nLocal;
drh0e1c19e2004-05-11 00:58:56 +00002486
2487 assert( pCur!=0 && pCur->pPage!=0 );
2488 assert( pCur->isValid );
drh0e1c19e2004-05-11 00:58:56 +00002489 pPage = pCur->pPage;
2490 pageIntegrity(pPage);
2491 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00002492 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00002493 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00002494 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00002495 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00002496 nKey = 0;
2497 }else{
2498 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00002499 }
drh0e1c19e2004-05-11 00:58:56 +00002500 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00002501 aPayload += nKey;
2502 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00002503 }else{
drhfa1a98a2004-05-14 19:08:17 +00002504 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00002505 if( nLocal>nKey ){
2506 nLocal = nKey;
2507 }
drh0e1c19e2004-05-11 00:58:56 +00002508 }
drhe51c44f2004-05-30 20:46:09 +00002509 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00002510 return aPayload;
2511}
2512
2513
2514/*
drhe51c44f2004-05-30 20:46:09 +00002515** For the entry that cursor pCur is point to, return as
2516** many bytes of the key or data as are available on the local
2517** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00002518**
2519** The pointer returned is ephemeral. The key/data may move
2520** or be destroyed on the next call to any Btree routine.
2521**
2522** These routines is used to get quick access to key and data
2523** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00002524*/
drhe51c44f2004-05-30 20:46:09 +00002525const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
2526 return (const void*)fetchPayload(pCur, pAmt, 0);
drh0e1c19e2004-05-11 00:58:56 +00002527}
drhe51c44f2004-05-30 20:46:09 +00002528const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
2529 return (const void*)fetchPayload(pCur, pAmt, 1);
drh0e1c19e2004-05-11 00:58:56 +00002530}
2531
2532
2533/*
drh8178a752003-01-05 21:41:40 +00002534** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00002535** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00002536*/
drh3aac2dd2004-04-26 14:10:20 +00002537static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00002538 int rc;
2539 MemPage *pNewPage;
drh3aac2dd2004-04-26 14:10:20 +00002540 MemPage *pOldPage;
drh0d316a42002-08-11 20:10:47 +00002541 Btree *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00002542
drhc39e0002004-05-07 23:50:57 +00002543 assert( pCur->isValid );
drhde647132004-05-07 17:57:49 +00002544 rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00002545 if( rc ) return rc;
drhda200cc2004-05-09 11:51:38 +00002546 pageIntegrity(pNewPage);
drh428ae8c2003-01-04 16:48:09 +00002547 pNewPage->idxParent = pCur->idx;
drh3aac2dd2004-04-26 14:10:20 +00002548 pOldPage = pCur->pPage;
2549 pOldPage->idxShift = 0;
2550 releasePage(pOldPage);
drh72f82862001-05-24 21:06:34 +00002551 pCur->pPage = pNewPage;
2552 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00002553 pCur->info.nSize = 0;
drh4be295b2003-12-16 03:44:47 +00002554 if( pNewPage->nCell<1 ){
drhee696e22004-08-30 16:52:17 +00002555 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
drh4be295b2003-12-16 03:44:47 +00002556 }
drh72f82862001-05-24 21:06:34 +00002557 return SQLITE_OK;
2558}
2559
2560/*
drh8856d6a2004-04-29 14:42:46 +00002561** Return true if the page is the virtual root of its table.
2562**
2563** The virtual root page is the root page for most tables. But
2564** for the table rooted on page 1, sometime the real root page
2565** is empty except for the right-pointer. In such cases the
2566** virtual root page is the page that the right-pointer of page
2567** 1 is pointing to.
2568*/
2569static int isRootPage(MemPage *pPage){
2570 MemPage *pParent = pPage->pParent;
drhda200cc2004-05-09 11:51:38 +00002571 if( pParent==0 ) return 1;
2572 if( pParent->pgno>1 ) return 0;
2573 if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
drh8856d6a2004-04-29 14:42:46 +00002574 return 0;
2575}
2576
2577/*
drh5e2f8b92001-05-28 00:41:15 +00002578** Move the cursor up to the parent page.
2579**
2580** pCur->idx is set to the cell index that contains the pointer
2581** to the page we are coming from. If we are coming from the
2582** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00002583** the largest cell index.
drh72f82862001-05-24 21:06:34 +00002584*/
drh8178a752003-01-05 21:41:40 +00002585static void moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00002586 MemPage *pParent;
drh8178a752003-01-05 21:41:40 +00002587 MemPage *pPage;
drh428ae8c2003-01-04 16:48:09 +00002588 int idxParent;
drh3aac2dd2004-04-26 14:10:20 +00002589
drhc39e0002004-05-07 23:50:57 +00002590 assert( pCur->isValid );
drh8178a752003-01-05 21:41:40 +00002591 pPage = pCur->pPage;
2592 assert( pPage!=0 );
drh8856d6a2004-04-29 14:42:46 +00002593 assert( !isRootPage(pPage) );
drhda200cc2004-05-09 11:51:38 +00002594 pageIntegrity(pPage);
drh8178a752003-01-05 21:41:40 +00002595 pParent = pPage->pParent;
2596 assert( pParent!=0 );
drhda200cc2004-05-09 11:51:38 +00002597 pageIntegrity(pParent);
drh8178a752003-01-05 21:41:40 +00002598 idxParent = pPage->idxParent;
drha34b6762004-05-07 13:30:42 +00002599 sqlite3pager_ref(pParent->aData);
drh3aac2dd2004-04-26 14:10:20 +00002600 releasePage(pPage);
drh72f82862001-05-24 21:06:34 +00002601 pCur->pPage = pParent;
drh271efa52004-05-30 19:19:05 +00002602 pCur->info.nSize = 0;
drh428ae8c2003-01-04 16:48:09 +00002603 assert( pParent->idxShift==0 );
drh43605152004-05-29 21:46:49 +00002604 pCur->idx = idxParent;
drh72f82862001-05-24 21:06:34 +00002605}
2606
2607/*
2608** Move the cursor to the root page
2609*/
drh5e2f8b92001-05-28 00:41:15 +00002610static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00002611 MemPage *pRoot;
drhbd03cae2001-06-02 02:40:57 +00002612 int rc;
drh0d316a42002-08-11 20:10:47 +00002613 Btree *pBt = pCur->pBt;
drhbd03cae2001-06-02 02:40:57 +00002614
drhde647132004-05-07 17:57:49 +00002615 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0);
drhc39e0002004-05-07 23:50:57 +00002616 if( rc ){
2617 pCur->isValid = 0;
2618 return rc;
2619 }
drh3aac2dd2004-04-26 14:10:20 +00002620 releasePage(pCur->pPage);
drhda200cc2004-05-09 11:51:38 +00002621 pageIntegrity(pRoot);
drh3aac2dd2004-04-26 14:10:20 +00002622 pCur->pPage = pRoot;
drh72f82862001-05-24 21:06:34 +00002623 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00002624 pCur->info.nSize = 0;
drh8856d6a2004-04-29 14:42:46 +00002625 if( pRoot->nCell==0 && !pRoot->leaf ){
2626 Pgno subpage;
2627 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00002628 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00002629 assert( subpage>0 );
drh3644f082004-05-10 18:45:09 +00002630 pCur->isValid = 1;
drh4b70f112004-05-02 21:12:19 +00002631 rc = moveToChild(pCur, subpage);
drh8856d6a2004-04-29 14:42:46 +00002632 }
drhc39e0002004-05-07 23:50:57 +00002633 pCur->isValid = pCur->pPage->nCell>0;
drh8856d6a2004-04-29 14:42:46 +00002634 return rc;
drh72f82862001-05-24 21:06:34 +00002635}
drh2af926b2001-05-15 00:39:25 +00002636
drh5e2f8b92001-05-28 00:41:15 +00002637/*
2638** Move the cursor down to the left-most leaf entry beneath the
2639** entry to which it is currently pointing.
2640*/
2641static int moveToLeftmost(BtCursor *pCur){
2642 Pgno pgno;
2643 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002644 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00002645
drhc39e0002004-05-07 23:50:57 +00002646 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00002647 while( !(pPage = pCur->pPage)->leaf ){
drha34b6762004-05-07 13:30:42 +00002648 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00002649 pgno = get4byte(findCell(pPage, pCur->idx));
drh8178a752003-01-05 21:41:40 +00002650 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00002651 if( rc ) return rc;
2652 }
2653 return SQLITE_OK;
2654}
2655
drh2dcc9aa2002-12-04 13:40:25 +00002656/*
2657** Move the cursor down to the right-most leaf entry beneath the
2658** page to which it is currently pointing. Notice the difference
2659** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
2660** finds the left-most entry beneath the *entry* whereas moveToRightmost()
2661** finds the right-most entry beneath the *page*.
2662*/
2663static int moveToRightmost(BtCursor *pCur){
2664 Pgno pgno;
2665 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002666 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00002667
drhc39e0002004-05-07 23:50:57 +00002668 assert( pCur->isValid );
drh3aac2dd2004-04-26 14:10:20 +00002669 while( !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00002670 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh3aac2dd2004-04-26 14:10:20 +00002671 pCur->idx = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00002672 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00002673 if( rc ) return rc;
2674 }
drh3aac2dd2004-04-26 14:10:20 +00002675 pCur->idx = pPage->nCell - 1;
drh271efa52004-05-30 19:19:05 +00002676 pCur->info.nSize = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002677 return SQLITE_OK;
2678}
2679
drh5e00f6c2001-09-13 13:46:56 +00002680/* Move the cursor to the first entry in the table. Return SQLITE_OK
2681** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00002682** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00002683*/
drh3aac2dd2004-04-26 14:10:20 +00002684int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00002685 int rc;
2686 rc = moveToRoot(pCur);
2687 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00002688 if( pCur->isValid==0 ){
2689 assert( pCur->pPage->nCell==0 );
drh5e00f6c2001-09-13 13:46:56 +00002690 *pRes = 1;
2691 return SQLITE_OK;
2692 }
drhc39e0002004-05-07 23:50:57 +00002693 assert( pCur->pPage->nCell>0 );
drh5e00f6c2001-09-13 13:46:56 +00002694 *pRes = 0;
2695 rc = moveToLeftmost(pCur);
2696 return rc;
2697}
drh5e2f8b92001-05-28 00:41:15 +00002698
drh9562b552002-02-19 15:00:07 +00002699/* Move the cursor to the last entry in the table. Return SQLITE_OK
2700** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00002701** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00002702*/
drh3aac2dd2004-04-26 14:10:20 +00002703int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00002704 int rc;
drh9562b552002-02-19 15:00:07 +00002705 rc = moveToRoot(pCur);
2706 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00002707 if( pCur->isValid==0 ){
2708 assert( pCur->pPage->nCell==0 );
drh9562b552002-02-19 15:00:07 +00002709 *pRes = 1;
2710 return SQLITE_OK;
2711 }
drhc39e0002004-05-07 23:50:57 +00002712 assert( pCur->isValid );
drh9562b552002-02-19 15:00:07 +00002713 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002714 rc = moveToRightmost(pCur);
drh9562b552002-02-19 15:00:07 +00002715 return rc;
2716}
2717
drh3aac2dd2004-04-26 14:10:20 +00002718/* Move the cursor so that it points to an entry near pKey/nKey.
drh72f82862001-05-24 21:06:34 +00002719** Return a success code.
2720**
drh3aac2dd2004-04-26 14:10:20 +00002721** For INTKEY tables, only the nKey parameter is used. pKey is
2722** ignored. For other tables, nKey is the number of bytes of data
2723** in nKey. The comparison function specified when the cursor was
2724** created is used to compare keys.
2725**
drh5e2f8b92001-05-28 00:41:15 +00002726** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00002727** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00002728** were present. The cursor might point to an entry that comes
2729** before or after the key.
2730**
drhbd03cae2001-06-02 02:40:57 +00002731** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00002732** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00002733** this value is as follows:
2734**
2735** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00002736** is smaller than pKey or if the table is empty
2737** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00002738**
2739** *pRes==0 The cursor is left pointing at an entry that
2740** exactly matches pKey.
2741**
2742** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00002743** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00002744*/
drh4a1c3802004-05-12 15:15:47 +00002745int sqlite3BtreeMoveto(BtCursor *pCur, const void *pKey, i64 nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00002746 int rc;
drh5e2f8b92001-05-28 00:41:15 +00002747 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00002748 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00002749 assert( pCur->pPage );
2750 assert( pCur->pPage->isInit );
2751 if( pCur->isValid==0 ){
drhf328bc82004-05-10 23:29:49 +00002752 *pRes = -1;
drhc39e0002004-05-07 23:50:57 +00002753 assert( pCur->pPage->nCell==0 );
2754 return SQLITE_OK;
2755 }
drh4eec4c12005-01-21 00:22:37 +00002756 for(;;){
drh72f82862001-05-24 21:06:34 +00002757 int lwr, upr;
2758 Pgno chldPg;
2759 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00002760 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00002761 lwr = 0;
2762 upr = pPage->nCell-1;
drh4eec4c12005-01-21 00:22:37 +00002763 if( !pPage->intKey && pKey==0 ){
2764 return SQLITE_CORRUPT;
2765 }
drhda200cc2004-05-09 11:51:38 +00002766 pageIntegrity(pPage);
drh72f82862001-05-24 21:06:34 +00002767 while( lwr<=upr ){
danielk197713adf8a2004-06-03 16:08:41 +00002768 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00002769 i64 nCellKey;
drh72f82862001-05-24 21:06:34 +00002770 pCur->idx = (lwr+upr)/2;
drh271efa52004-05-30 19:19:05 +00002771 pCur->info.nSize = 0;
drhde647132004-05-07 17:57:49 +00002772 sqlite3BtreeKeySize(pCur, &nCellKey);
drh3aac2dd2004-04-26 14:10:20 +00002773 if( pPage->intKey ){
2774 if( nCellKey<nKey ){
2775 c = -1;
2776 }else if( nCellKey>nKey ){
2777 c = +1;
2778 }else{
2779 c = 0;
2780 }
drh3aac2dd2004-04-26 14:10:20 +00002781 }else{
drhe51c44f2004-05-30 20:46:09 +00002782 int available;
danielk197713adf8a2004-06-03 16:08:41 +00002783 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drhe51c44f2004-05-30 20:46:09 +00002784 if( available>=nCellKey ){
2785 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
2786 }else{
2787 pCellKey = sqliteMallocRaw( nCellKey );
2788 if( pCellKey==0 ) return SQLITE_NOMEM;
danielk197713adf8a2004-06-03 16:08:41 +00002789 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
drhe51c44f2004-05-30 20:46:09 +00002790 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
2791 sqliteFree(pCellKey);
2792 if( rc ) return rc;
2793 }
drh3aac2dd2004-04-26 14:10:20 +00002794 }
drh72f82862001-05-24 21:06:34 +00002795 if( c==0 ){
drh8b18dd42004-05-12 19:18:15 +00002796 if( pPage->leafData && !pPage->leaf ){
drhfc70e6f2004-05-12 21:11:27 +00002797 lwr = pCur->idx;
2798 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00002799 break;
2800 }else{
drh8b18dd42004-05-12 19:18:15 +00002801 if( pRes ) *pRes = 0;
2802 return SQLITE_OK;
2803 }
drh72f82862001-05-24 21:06:34 +00002804 }
2805 if( c<0 ){
2806 lwr = pCur->idx+1;
2807 }else{
2808 upr = pCur->idx-1;
2809 }
2810 }
2811 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00002812 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00002813 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00002814 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00002815 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00002816 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00002817 }else{
drh43605152004-05-29 21:46:49 +00002818 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00002819 }
2820 if( chldPg==0 ){
drhc39e0002004-05-07 23:50:57 +00002821 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00002822 if( pRes ) *pRes = c;
2823 return SQLITE_OK;
2824 }
drh428ae8c2003-01-04 16:48:09 +00002825 pCur->idx = lwr;
drh271efa52004-05-30 19:19:05 +00002826 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00002827 rc = moveToChild(pCur, chldPg);
drhc39e0002004-05-07 23:50:57 +00002828 if( rc ){
2829 return rc;
2830 }
drh72f82862001-05-24 21:06:34 +00002831 }
drhbd03cae2001-06-02 02:40:57 +00002832 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00002833}
2834
2835/*
drhc39e0002004-05-07 23:50:57 +00002836** Return TRUE if the cursor is not pointing at an entry of the table.
2837**
2838** TRUE will be returned after a call to sqlite3BtreeNext() moves
2839** past the last entry in the table or sqlite3BtreePrev() moves past
2840** the first entry. TRUE is also returned if the table is empty.
2841*/
2842int sqlite3BtreeEof(BtCursor *pCur){
2843 return pCur->isValid==0;
2844}
2845
2846/*
drhbd03cae2001-06-02 02:40:57 +00002847** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00002848** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00002849** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00002850** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00002851*/
drh3aac2dd2004-04-26 14:10:20 +00002852int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00002853 int rc;
drh8178a752003-01-05 21:41:40 +00002854 MemPage *pPage = pCur->pPage;
drh8b18dd42004-05-12 19:18:15 +00002855
drh8c1238a2003-01-02 14:43:55 +00002856 assert( pRes!=0 );
drhc39e0002004-05-07 23:50:57 +00002857 if( pCur->isValid==0 ){
drh8c1238a2003-01-02 14:43:55 +00002858 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00002859 return SQLITE_OK;
drhecdc7532001-09-23 02:35:53 +00002860 }
drh8178a752003-01-05 21:41:40 +00002861 assert( pPage->isInit );
drh8178a752003-01-05 21:41:40 +00002862 assert( pCur->idx<pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00002863
drh72f82862001-05-24 21:06:34 +00002864 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00002865 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00002866 if( pCur->idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00002867 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00002868 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00002869 if( rc ) return rc;
2870 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00002871 *pRes = 0;
2872 return rc;
drh72f82862001-05-24 21:06:34 +00002873 }
drh5e2f8b92001-05-28 00:41:15 +00002874 do{
drh8856d6a2004-04-29 14:42:46 +00002875 if( isRootPage(pPage) ){
drh8c1238a2003-01-02 14:43:55 +00002876 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00002877 pCur->isValid = 0;
drh5e2f8b92001-05-28 00:41:15 +00002878 return SQLITE_OK;
2879 }
drh8178a752003-01-05 21:41:40 +00002880 moveToParent(pCur);
2881 pPage = pCur->pPage;
2882 }while( pCur->idx>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00002883 *pRes = 0;
drh8b18dd42004-05-12 19:18:15 +00002884 if( pPage->leafData ){
2885 rc = sqlite3BtreeNext(pCur, pRes);
2886 }else{
2887 rc = SQLITE_OK;
2888 }
2889 return rc;
drh8178a752003-01-05 21:41:40 +00002890 }
2891 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00002892 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00002893 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00002894 }
drh5e2f8b92001-05-28 00:41:15 +00002895 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00002896 return rc;
drh72f82862001-05-24 21:06:34 +00002897}
2898
drh3b7511c2001-05-26 13:15:44 +00002899/*
drh2dcc9aa2002-12-04 13:40:25 +00002900** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00002901** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00002902** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00002903** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00002904*/
drh3aac2dd2004-04-26 14:10:20 +00002905int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00002906 int rc;
2907 Pgno pgno;
drh8178a752003-01-05 21:41:40 +00002908 MemPage *pPage;
drhc39e0002004-05-07 23:50:57 +00002909 if( pCur->isValid==0 ){
2910 *pRes = 1;
2911 return SQLITE_OK;
2912 }
danielk19776a43f9b2004-11-16 04:57:24 +00002913
drh8178a752003-01-05 21:41:40 +00002914 pPage = pCur->pPage;
drh8178a752003-01-05 21:41:40 +00002915 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00002916 assert( pCur->idx>=0 );
drha34b6762004-05-07 13:30:42 +00002917 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00002918 pgno = get4byte( findCell(pPage, pCur->idx) );
drh8178a752003-01-05 21:41:40 +00002919 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00002920 if( rc ) return rc;
2921 rc = moveToRightmost(pCur);
2922 }else{
2923 while( pCur->idx==0 ){
drh8856d6a2004-04-29 14:42:46 +00002924 if( isRootPage(pPage) ){
drhc39e0002004-05-07 23:50:57 +00002925 pCur->isValid = 0;
2926 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00002927 return SQLITE_OK;
2928 }
drh8178a752003-01-05 21:41:40 +00002929 moveToParent(pCur);
2930 pPage = pCur->pPage;
drh2dcc9aa2002-12-04 13:40:25 +00002931 }
2932 pCur->idx--;
drh271efa52004-05-30 19:19:05 +00002933 pCur->info.nSize = 0;
drh8237d452004-11-22 19:07:09 +00002934 if( pPage->leafData && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00002935 rc = sqlite3BtreePrevious(pCur, pRes);
2936 }else{
2937 rc = SQLITE_OK;
2938 }
drh2dcc9aa2002-12-04 13:40:25 +00002939 }
drh8178a752003-01-05 21:41:40 +00002940 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002941 return rc;
2942}
2943
2944/*
drh3b7511c2001-05-26 13:15:44 +00002945** Allocate a new page from the database file.
2946**
drha34b6762004-05-07 13:30:42 +00002947** The new page is marked as dirty. (In other words, sqlite3pager_write()
drh3b7511c2001-05-26 13:15:44 +00002948** has already been called on the new page.) The new page has also
2949** been referenced and the calling routine is responsible for calling
drha34b6762004-05-07 13:30:42 +00002950** sqlite3pager_unref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00002951**
2952** SQLITE_OK is returned on success. Any other return value indicates
2953** an error. *ppPage and *pPgno are undefined in the event of an error.
drha34b6762004-05-07 13:30:42 +00002954** Do not invoke sqlite3pager_unref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00002955**
drh199e3cf2002-07-18 11:01:47 +00002956** If the "nearby" parameter is not 0, then a (feeble) effort is made to
2957** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00002958** attempt to keep related pages close to each other in the database file,
2959** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00002960**
2961** If the "exact" parameter is not 0, and the page-number nearby exists
2962** anywhere on the free-list, then it is guarenteed to be returned. This
2963** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00002964*/
danielk1977cb1a7eb2004-11-05 12:27:02 +00002965static int allocatePage(
2966 Btree *pBt,
2967 MemPage **ppPage,
2968 Pgno *pPgno,
2969 Pgno nearby,
2970 u8 exact
2971){
drh3aac2dd2004-04-26 14:10:20 +00002972 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00002973 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002974 int n; /* Number of pages on the freelist */
2975 int k; /* Number of leaves on the trunk of the freelist */
drh30e58752002-03-02 20:41:57 +00002976
drh3aac2dd2004-04-26 14:10:20 +00002977 pPage1 = pBt->pPage1;
2978 n = get4byte(&pPage1->aData[36]);
2979 if( n>0 ){
drh91025292004-05-03 19:49:32 +00002980 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00002981 MemPage *pTrunk = 0;
2982 Pgno iTrunk;
2983 MemPage *pPrevTrunk = 0;
2984 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
2985
2986 /* If the 'exact' parameter was true and a query of the pointer-map
2987 ** shows that the page 'nearby' is somewhere on the free-list, then
2988 ** the entire-list will be searched for that page.
2989 */
2990#ifndef SQLITE_OMIT_AUTOVACUUM
2991 if( exact ){
2992 u8 eType;
2993 assert( nearby>0 );
2994 assert( pBt->autoVacuum );
2995 rc = ptrmapGet(pBt, nearby, &eType, 0);
2996 if( rc ) return rc;
2997 if( eType==PTRMAP_FREEPAGE ){
2998 searchList = 1;
2999 }
3000 *pPgno = nearby;
3001 }
3002#endif
3003
3004 /* Decrement the free-list count by 1. Set iTrunk to the index of the
3005 ** first free-list trunk page. iPrevTrunk is initially 1.
3006 */
drha34b6762004-05-07 13:30:42 +00003007 rc = sqlite3pager_write(pPage1->aData);
drh3b7511c2001-05-26 13:15:44 +00003008 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003009 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003010
3011 /* The code within this loop is run only once if the 'searchList' variable
3012 ** is not true. Otherwise, it runs once for each trunk-page on the
3013 ** free-list until the page 'nearby' is located.
3014 */
3015 do {
3016 pPrevTrunk = pTrunk;
3017 if( pPrevTrunk ){
3018 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00003019 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00003020 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00003021 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003022 rc = getPage(pBt, iTrunk, &pTrunk);
3023 if( rc ){
3024 releasePage(pPrevTrunk);
3025 return rc;
3026 }
3027
3028 /* TODO: This should move to after the loop? */
3029 rc = sqlite3pager_write(pTrunk->aData);
3030 if( rc ){
3031 releasePage(pTrunk);
3032 releasePage(pPrevTrunk);
3033 return rc;
3034 }
3035
3036 k = get4byte(&pTrunk->aData[4]);
3037 if( k==0 && !searchList ){
3038 /* The trunk has no leaves and the list is not being searched.
3039 ** So extract the trunk page itself and use it as the newly
3040 ** allocated page */
3041 assert( pPrevTrunk==0 );
3042 *pPgno = iTrunk;
3043 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3044 *ppPage = pTrunk;
3045 pTrunk = 0;
3046 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3047 }else if( k>pBt->usableSize/4 - 8 ){
3048 /* Value of k is out of range. Database corruption */
drhee696e22004-08-30 16:52:17 +00003049 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
danielk1977cb1a7eb2004-11-05 12:27:02 +00003050#ifndef SQLITE_OMIT_AUTOVACUUM
3051 }else if( searchList && nearby==iTrunk ){
3052 /* The list is being searched and this trunk page is the page
3053 ** to allocate, regardless of whether it has leaves.
3054 */
3055 assert( *pPgno==iTrunk );
3056 *ppPage = pTrunk;
3057 searchList = 0;
3058 if( k==0 ){
3059 if( !pPrevTrunk ){
3060 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3061 }else{
3062 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
3063 }
3064 }else{
3065 /* The trunk page is required by the caller but it contains
3066 ** pointers to free-list leaves. The first leaf becomes a trunk
3067 ** page in this case.
3068 */
3069 MemPage *pNewTrunk;
3070 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
3071 rc = getPage(pBt, iNewTrunk, &pNewTrunk);
3072 if( rc!=SQLITE_OK ){
3073 releasePage(pTrunk);
3074 releasePage(pPrevTrunk);
3075 return rc;
3076 }
3077 rc = sqlite3pager_write(pNewTrunk->aData);
3078 if( rc!=SQLITE_OK ){
3079 releasePage(pNewTrunk);
3080 releasePage(pTrunk);
3081 releasePage(pPrevTrunk);
3082 return rc;
3083 }
3084 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
3085 put4byte(&pNewTrunk->aData[4], k-1);
3086 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
3087 if( !pPrevTrunk ){
3088 put4byte(&pPage1->aData[32], iNewTrunk);
3089 }else{
3090 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
3091 }
3092 releasePage(pNewTrunk);
3093 }
3094 pTrunk = 0;
3095 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3096#endif
3097 }else{
3098 /* Extract a leaf from the trunk */
3099 int closest;
3100 Pgno iPage;
3101 unsigned char *aData = pTrunk->aData;
3102 if( nearby>0 ){
3103 int i, dist;
3104 closest = 0;
3105 dist = get4byte(&aData[8]) - nearby;
3106 if( dist<0 ) dist = -dist;
3107 for(i=1; i<k; i++){
3108 int d2 = get4byte(&aData[8+i*4]) - nearby;
3109 if( d2<0 ) d2 = -d2;
3110 if( d2<dist ){
3111 closest = i;
3112 dist = d2;
3113 }
3114 }
3115 }else{
3116 closest = 0;
3117 }
3118
3119 iPage = get4byte(&aData[8+closest*4]);
3120 if( !searchList || iPage==nearby ){
3121 *pPgno = iPage;
3122 if( *pPgno>sqlite3pager_pagecount(pBt->pPager) ){
3123 /* Free page off the end of the file */
3124 return SQLITE_CORRUPT; /* bkpt-CORRUPT */
3125 }
3126 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
3127 ": %d more free pages\n",
3128 *pPgno, closest+1, k, pTrunk->pgno, n-1));
3129 if( closest<k-1 ){
3130 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
3131 }
3132 put4byte(&aData[4], k-1);
3133 rc = getPage(pBt, *pPgno, ppPage);
3134 if( rc==SQLITE_OK ){
3135 sqlite3pager_dont_rollback((*ppPage)->aData);
3136 rc = sqlite3pager_write((*ppPage)->aData);
danielk1977aac0a382005-01-16 11:07:06 +00003137 if( rc!=SQLITE_OK ){
3138 releasePage(*ppPage);
3139 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003140 }
3141 searchList = 0;
3142 }
drhee696e22004-08-30 16:52:17 +00003143 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003144 releasePage(pPrevTrunk);
3145 }while( searchList );
3146 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003147 }else{
drh3aac2dd2004-04-26 14:10:20 +00003148 /* There are no pages on the freelist, so create a new page at the
3149 ** end of the file */
drha34b6762004-05-07 13:30:42 +00003150 *pPgno = sqlite3pager_pagecount(pBt->pPager) + 1;
danielk1977afcdd022004-10-31 16:25:42 +00003151
3152#ifndef SQLITE_OMIT_AUTOVACUUM
drh42cac6d2004-11-20 20:31:11 +00003153 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt->usableSize, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00003154 /* If *pPgno refers to a pointer-map page, allocate two new pages
3155 ** at the end of the file instead of one. The first allocated page
3156 ** becomes a new pointer-map page, the second is used by the caller.
3157 */
3158 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00003159 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977afcdd022004-10-31 16:25:42 +00003160 (*pPgno)++;
3161 }
3162#endif
3163
danielk1977599fcba2004-11-08 07:13:13 +00003164 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00003165 rc = getPage(pBt, *pPgno, ppPage);
drh3b7511c2001-05-26 13:15:44 +00003166 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003167 rc = sqlite3pager_write((*ppPage)->aData);
danielk1977aac0a382005-01-16 11:07:06 +00003168 if( rc!=SQLITE_OK ){
3169 releasePage(*ppPage);
3170 }
drh3a4c1412004-05-09 20:40:11 +00003171 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00003172 }
danielk1977599fcba2004-11-08 07:13:13 +00003173
3174 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh3b7511c2001-05-26 13:15:44 +00003175 return rc;
3176}
3177
3178/*
drh3aac2dd2004-04-26 14:10:20 +00003179** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00003180**
drha34b6762004-05-07 13:30:42 +00003181** sqlite3pager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00003182*/
drh3aac2dd2004-04-26 14:10:20 +00003183static int freePage(MemPage *pPage){
3184 Btree *pBt = pPage->pBt;
3185 MemPage *pPage1 = pBt->pPage1;
3186 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00003187
drh3aac2dd2004-04-26 14:10:20 +00003188 /* Prepare the page for freeing */
3189 assert( pPage->pgno>1 );
3190 pPage->isInit = 0;
3191 releasePage(pPage->pParent);
3192 pPage->pParent = 0;
3193
drha34b6762004-05-07 13:30:42 +00003194 /* Increment the free page count on pPage1 */
3195 rc = sqlite3pager_write(pPage1->aData);
drh3aac2dd2004-04-26 14:10:20 +00003196 if( rc ) return rc;
3197 n = get4byte(&pPage1->aData[36]);
3198 put4byte(&pPage1->aData[36], n+1);
3199
danielk1977687566d2004-11-02 12:56:41 +00003200#ifndef SQLITE_OMIT_AUTOVACUUM
3201 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00003202 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00003203 */
3204 if( pBt->autoVacuum ){
3205 rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
danielk1977a64a0352004-11-05 01:45:13 +00003206 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00003207 }
3208#endif
3209
drh3aac2dd2004-04-26 14:10:20 +00003210 if( n==0 ){
3211 /* This is the first free page */
drhda200cc2004-05-09 11:51:38 +00003212 rc = sqlite3pager_write(pPage->aData);
3213 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003214 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00003215 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003216 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003217 }else{
3218 /* Other free pages already exist. Retrive the first trunk page
3219 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00003220 MemPage *pTrunk;
3221 rc = getPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003222 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003223 k = get4byte(&pTrunk->aData[4]);
drhee696e22004-08-30 16:52:17 +00003224 if( k>=pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00003225 /* The trunk is full. Turn the page being freed into a new
3226 ** trunk page with no leaves. */
drha34b6762004-05-07 13:30:42 +00003227 rc = sqlite3pager_write(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00003228 if( rc ) return rc;
3229 put4byte(pPage->aData, pTrunk->pgno);
3230 put4byte(&pPage->aData[4], 0);
3231 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003232 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
3233 pPage->pgno, pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003234 }else{
3235 /* Add the newly freed page as a leaf on the current trunk */
drha34b6762004-05-07 13:30:42 +00003236 rc = sqlite3pager_write(pTrunk->aData);
drh3aac2dd2004-04-26 14:10:20 +00003237 if( rc ) return rc;
3238 put4byte(&pTrunk->aData[4], k+1);
3239 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drha34b6762004-05-07 13:30:42 +00003240 sqlite3pager_dont_write(pBt->pPager, pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003241 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003242 }
3243 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003244 }
drh3b7511c2001-05-26 13:15:44 +00003245 return rc;
3246}
3247
3248/*
drh3aac2dd2004-04-26 14:10:20 +00003249** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00003250*/
drh3aac2dd2004-04-26 14:10:20 +00003251static int clearCell(MemPage *pPage, unsigned char *pCell){
3252 Btree *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00003253 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00003254 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00003255 int rc;
drh3b7511c2001-05-26 13:15:44 +00003256
drh43605152004-05-29 21:46:49 +00003257 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003258 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00003259 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00003260 }
drh6f11bef2004-05-13 01:12:56 +00003261 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh3aac2dd2004-04-26 14:10:20 +00003262 while( ovflPgno!=0 ){
3263 MemPage *pOvfl;
danielk1977a1cb1832005-02-12 08:59:55 +00003264 if( ovflPgno>sqlite3pager_pagecount(pBt->pPager) ){
3265 return SQLITE_CORRUPT;
3266 }
drh3aac2dd2004-04-26 14:10:20 +00003267 rc = getPage(pBt, ovflPgno, &pOvfl);
drh3b7511c2001-05-26 13:15:44 +00003268 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003269 ovflPgno = get4byte(pOvfl->aData);
drha34b6762004-05-07 13:30:42 +00003270 rc = freePage(pOvfl);
drha34b6762004-05-07 13:30:42 +00003271 sqlite3pager_unref(pOvfl->aData);
danielk19776b456a22005-03-21 04:04:02 +00003272 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00003273 }
drh5e2f8b92001-05-28 00:41:15 +00003274 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00003275}
3276
3277/*
drh91025292004-05-03 19:49:32 +00003278** Create the byte sequence used to represent a cell on page pPage
3279** and write that byte sequence into pCell[]. Overflow pages are
3280** allocated and filled in as necessary. The calling procedure
3281** is responsible for making sure sufficient space has been allocated
3282** for pCell[].
3283**
3284** Note that pCell does not necessary need to point to the pPage->aData
3285** area. pCell might point to some temporary storage. The cell will
3286** be constructed in this temporary area then copied into pPage->aData
3287** later.
drh3b7511c2001-05-26 13:15:44 +00003288*/
3289static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00003290 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00003291 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00003292 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00003293 const void *pData,int nData, /* The data */
3294 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00003295){
drh3b7511c2001-05-26 13:15:44 +00003296 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00003297 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00003298 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00003299 int spaceLeft;
3300 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00003301 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00003302 unsigned char *pPrior;
3303 unsigned char *pPayload;
3304 Btree *pBt = pPage->pBt;
3305 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00003306 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00003307 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00003308
drh91025292004-05-03 19:49:32 +00003309 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00003310 nHeader = 0;
drh91025292004-05-03 19:49:32 +00003311 if( !pPage->leaf ){
3312 nHeader += 4;
3313 }
drh8b18dd42004-05-12 19:18:15 +00003314 if( pPage->hasData ){
drh91025292004-05-03 19:49:32 +00003315 nHeader += putVarint(&pCell[nHeader], nData);
drh6f11bef2004-05-13 01:12:56 +00003316 }else{
drh91025292004-05-03 19:49:32 +00003317 nData = 0;
3318 }
drh6f11bef2004-05-13 01:12:56 +00003319 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh43605152004-05-29 21:46:49 +00003320 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003321 assert( info.nHeader==nHeader );
3322 assert( info.nKey==nKey );
3323 assert( info.nData==nData );
3324
3325 /* Fill in the payload */
drh3aac2dd2004-04-26 14:10:20 +00003326 nPayload = nData;
3327 if( pPage->intKey ){
3328 pSrc = pData;
3329 nSrc = nData;
drh91025292004-05-03 19:49:32 +00003330 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00003331 }else{
3332 nPayload += nKey;
3333 pSrc = pKey;
3334 nSrc = nKey;
3335 }
drh6f11bef2004-05-13 01:12:56 +00003336 *pnSize = info.nSize;
3337 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00003338 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00003339 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00003340
drh3b7511c2001-05-26 13:15:44 +00003341 while( nPayload>0 ){
3342 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00003343#ifndef SQLITE_OMIT_AUTOVACUUM
3344 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
3345#endif
danielk1977cb1a7eb2004-11-05 12:27:02 +00003346 rc = allocatePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00003347#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00003348 /* If the database supports auto-vacuum, and the second or subsequent
3349 ** overflow page is being allocated, add an entry to the pointer-map
3350 ** for that page now. The entry for the first overflow page will be
3351 ** added later, by the insertCell() routine.
danielk1977afcdd022004-10-31 16:25:42 +00003352 */
danielk1977a19df672004-11-03 11:37:07 +00003353 if( pBt->autoVacuum && pgnoPtrmap!=0 && rc==SQLITE_OK ){
3354 rc = ptrmapPut(pBt, pgnoOvfl, PTRMAP_OVERFLOW2, pgnoPtrmap);
danielk1977afcdd022004-10-31 16:25:42 +00003355 }
3356#endif
drh3b7511c2001-05-26 13:15:44 +00003357 if( rc ){
drh9b171272004-05-08 02:03:22 +00003358 releasePage(pToRelease);
danielk197728129562005-01-11 10:25:06 +00003359 /* clearCell(pPage, pCell); */
drh3b7511c2001-05-26 13:15:44 +00003360 return rc;
3361 }
drh3aac2dd2004-04-26 14:10:20 +00003362 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00003363 releasePage(pToRelease);
3364 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00003365 pPrior = pOvfl->aData;
3366 put4byte(pPrior, 0);
3367 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00003368 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00003369 }
3370 n = nPayload;
3371 if( n>spaceLeft ) n = spaceLeft;
drh3aac2dd2004-04-26 14:10:20 +00003372 if( n>nSrc ) n = nSrc;
3373 memcpy(pPayload, pSrc, n);
drh3b7511c2001-05-26 13:15:44 +00003374 nPayload -= n;
drhde647132004-05-07 17:57:49 +00003375 pPayload += n;
drh9b171272004-05-08 02:03:22 +00003376 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00003377 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00003378 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00003379 if( nSrc==0 ){
3380 nSrc = nData;
3381 pSrc = pData;
3382 }
drhdd793422001-06-28 01:54:48 +00003383 }
drh9b171272004-05-08 02:03:22 +00003384 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00003385 return SQLITE_OK;
3386}
3387
3388/*
drhbd03cae2001-06-02 02:40:57 +00003389** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00003390** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00003391** pointer in the third argument.
3392*/
danielk1977afcdd022004-10-31 16:25:42 +00003393static int reparentPage(Btree *pBt, Pgno pgno, MemPage *pNewParent, int idx){
drhbd03cae2001-06-02 02:40:57 +00003394 MemPage *pThis;
drh4b70f112004-05-02 21:12:19 +00003395 unsigned char *aData;
drhbd03cae2001-06-02 02:40:57 +00003396
danielk1977afcdd022004-10-31 16:25:42 +00003397 if( pgno==0 ) return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00003398 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00003399 aData = sqlite3pager_lookup(pBt->pPager, pgno);
drhda200cc2004-05-09 11:51:38 +00003400 if( aData ){
drh07d183d2005-05-01 22:52:42 +00003401 pThis = (MemPage*)&aData[pBt->pageSize];
drh31276532004-09-27 12:20:52 +00003402 assert( pThis->aData==aData );
drhda200cc2004-05-09 11:51:38 +00003403 if( pThis->isInit ){
3404 if( pThis->pParent!=pNewParent ){
3405 if( pThis->pParent ) sqlite3pager_unref(pThis->pParent->aData);
3406 pThis->pParent = pNewParent;
3407 if( pNewParent ) sqlite3pager_ref(pNewParent->aData);
3408 }
3409 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00003410 }
drha34b6762004-05-07 13:30:42 +00003411 sqlite3pager_unref(aData);
drhbd03cae2001-06-02 02:40:57 +00003412 }
danielk1977afcdd022004-10-31 16:25:42 +00003413
3414#ifndef SQLITE_OMIT_AUTOVACUUM
3415 if( pBt->autoVacuum ){
3416 return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
3417 }
3418#endif
3419 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00003420}
3421
danielk1977ac11ee62005-01-15 12:45:51 +00003422
3423
drhbd03cae2001-06-02 02:40:57 +00003424/*
drh4b70f112004-05-02 21:12:19 +00003425** Change the pParent pointer of all children of pPage to point back
3426** to pPage.
3427**
drhbd03cae2001-06-02 02:40:57 +00003428** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00003429** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00003430**
3431** This routine gets called after you memcpy() one page into
3432** another.
3433*/
danielk1977afcdd022004-10-31 16:25:42 +00003434static int reparentChildPages(MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00003435 int i;
danielk1977afcdd022004-10-31 16:25:42 +00003436 Btree *pBt = pPage->pBt;
3437 int rc = SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00003438
danielk1977afcdd022004-10-31 16:25:42 +00003439 if( pPage->leaf ) return SQLITE_OK;
danielk1977afcdd022004-10-31 16:25:42 +00003440
drhbd03cae2001-06-02 02:40:57 +00003441 for(i=0; i<pPage->nCell; i++){
danielk1977afcdd022004-10-31 16:25:42 +00003442 u8 *pCell = findCell(pPage, i);
3443 if( !pPage->leaf ){
3444 rc = reparentPage(pBt, get4byte(pCell), pPage, i);
3445 if( rc!=SQLITE_OK ) return rc;
3446 }
drhbd03cae2001-06-02 02:40:57 +00003447 }
danielk1977afcdd022004-10-31 16:25:42 +00003448 if( !pPage->leaf ){
3449 rc = reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]),
3450 pPage, i);
3451 pPage->idxShift = 0;
3452 }
3453 return rc;
drh14acc042001-06-10 19:56:58 +00003454}
3455
3456/*
3457** Remove the i-th cell from pPage. This routine effects pPage only.
3458** The cell content is not freed or deallocated. It is assumed that
3459** the cell content has been copied someplace else. This routine just
3460** removes the reference to the cell from pPage.
3461**
3462** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00003463*/
drh4b70f112004-05-02 21:12:19 +00003464static void dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00003465 int i; /* Loop counter */
3466 int pc; /* Offset to cell content of cell being deleted */
3467 u8 *data; /* pPage->aData */
3468 u8 *ptr; /* Used to move bytes around within data[] */
3469
drh8c42ca92001-06-22 19:15:00 +00003470 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00003471 assert( sz==cellSize(pPage, idx) );
drha34b6762004-05-07 13:30:42 +00003472 assert( sqlite3pager_iswriteable(pPage->aData) );
drhda200cc2004-05-09 11:51:38 +00003473 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00003474 ptr = &data[pPage->cellOffset + 2*idx];
3475 pc = get2byte(ptr);
3476 assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
drhde647132004-05-07 17:57:49 +00003477 freeSpace(pPage, pc, sz);
drh43605152004-05-29 21:46:49 +00003478 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
3479 ptr[0] = ptr[2];
3480 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00003481 }
3482 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00003483 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
3484 pPage->nFree += 2;
drh428ae8c2003-01-04 16:48:09 +00003485 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00003486}
3487
3488/*
3489** Insert a new cell on pPage at cell index "i". pCell points to the
3490** content of the cell.
3491**
3492** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00003493** will not fit, then make a copy of the cell content into pTemp if
3494** pTemp is not null. Regardless of pTemp, allocate a new entry
3495** in pPage->aOvfl[] and make it point to the cell content (either
3496** in pTemp or the original pCell) and also record its index.
3497** Allocating a new entry in pPage->aCell[] implies that
3498** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00003499**
3500** If nSkip is non-zero, then do not copy the first nSkip bytes of the
3501** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00003502** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00003503** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00003504*/
danielk1977e80463b2004-11-03 03:01:16 +00003505static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00003506 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00003507 int i, /* New cell becomes the i-th cell of the page */
3508 u8 *pCell, /* Content of the new cell */
3509 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00003510 u8 *pTemp, /* Temp storage space for pCell, if needed */
3511 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00003512){
drh43605152004-05-29 21:46:49 +00003513 int idx; /* Where to write new cell content in data[] */
3514 int j; /* Loop counter */
3515 int top; /* First byte of content for any cell in data[] */
3516 int end; /* First byte past the last cell pointer in data[] */
3517 int ins; /* Index in data[] where new cell pointer is inserted */
3518 int hdr; /* Offset into data[] of the page header */
3519 int cellOffset; /* Address of first cell pointer in data[] */
3520 u8 *data; /* The content of the whole page */
3521 u8 *ptr; /* Used for moving information around in data[] */
3522
3523 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
3524 assert( sz==cellSizePtr(pPage, pCell) );
drha34b6762004-05-07 13:30:42 +00003525 assert( sqlite3pager_iswriteable(pPage->aData) );
drh43605152004-05-29 21:46:49 +00003526 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00003527 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00003528 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00003529 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00003530 }
drh43605152004-05-29 21:46:49 +00003531 j = pPage->nOverflow++;
3532 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
3533 pPage->aOvfl[j].pCell = pCell;
3534 pPage->aOvfl[j].idx = i;
3535 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00003536 }else{
drh43605152004-05-29 21:46:49 +00003537 data = pPage->aData;
3538 hdr = pPage->hdrOffset;
3539 top = get2byte(&data[hdr+5]);
3540 cellOffset = pPage->cellOffset;
3541 end = cellOffset + 2*pPage->nCell + 2;
3542 ins = cellOffset + 2*i;
3543 if( end > top - sz ){
danielk19776b456a22005-03-21 04:04:02 +00003544 int rc = defragmentPage(pPage);
3545 if( rc!=SQLITE_OK ) return rc;
drh43605152004-05-29 21:46:49 +00003546 top = get2byte(&data[hdr+5]);
3547 assert( end + sz <= top );
3548 }
3549 idx = allocateSpace(pPage, sz);
3550 assert( idx>0 );
3551 assert( end <= get2byte(&data[hdr+5]) );
3552 pPage->nCell++;
3553 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00003554 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00003555 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
3556 ptr[0] = ptr[-2];
3557 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00003558 }
drh43605152004-05-29 21:46:49 +00003559 put2byte(&data[ins], idx);
3560 put2byte(&data[hdr+3], pPage->nCell);
3561 pPage->idxShift = 1;
drhda200cc2004-05-09 11:51:38 +00003562 pageIntegrity(pPage);
danielk1977a19df672004-11-03 11:37:07 +00003563#ifndef SQLITE_OMIT_AUTOVACUUM
3564 if( pPage->pBt->autoVacuum ){
3565 /* The cell may contain a pointer to an overflow page. If so, write
3566 ** the entry for the overflow page into the pointer map.
3567 */
3568 CellInfo info;
3569 parseCellPtr(pPage, pCell, &info);
3570 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
3571 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
3572 int rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
3573 if( rc!=SQLITE_OK ) return rc;
3574 }
3575 }
3576#endif
drh14acc042001-06-10 19:56:58 +00003577 }
danielk1977e80463b2004-11-03 03:01:16 +00003578
danielk1977e80463b2004-11-03 03:01:16 +00003579 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00003580}
3581
3582/*
drhfa1a98a2004-05-14 19:08:17 +00003583** Add a list of cells to a page. The page should be initially empty.
3584** The cells are guaranteed to fit on the page.
3585*/
3586static void assemblePage(
3587 MemPage *pPage, /* The page to be assemblied */
3588 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00003589 u8 **apCell, /* Pointers to cell bodies */
drhfa1a98a2004-05-14 19:08:17 +00003590 int *aSize /* Sizes of the cells */
3591){
3592 int i; /* Loop counter */
3593 int totalSize; /* Total size of all cells */
3594 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00003595 int cellptr; /* Address of next cell pointer */
3596 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00003597 u8 *data; /* Data for the page */
3598
drh43605152004-05-29 21:46:49 +00003599 assert( pPage->nOverflow==0 );
drhfa1a98a2004-05-14 19:08:17 +00003600 totalSize = 0;
3601 for(i=0; i<nCell; i++){
3602 totalSize += aSize[i];
3603 }
drh43605152004-05-29 21:46:49 +00003604 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00003605 assert( pPage->nCell==0 );
drh43605152004-05-29 21:46:49 +00003606 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00003607 data = pPage->aData;
3608 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00003609 put2byte(&data[hdr+3], nCell);
drh09d0deb2005-08-02 17:13:09 +00003610 if( nCell ){
3611 cellbody = allocateSpace(pPage, totalSize);
3612 assert( cellbody>0 );
3613 assert( pPage->nFree >= 2*nCell );
3614 pPage->nFree -= 2*nCell;
3615 for(i=0; i<nCell; i++){
3616 put2byte(&data[cellptr], cellbody);
3617 memcpy(&data[cellbody], apCell[i], aSize[i]);
3618 cellptr += 2;
3619 cellbody += aSize[i];
3620 }
3621 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00003622 }
3623 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00003624}
3625
drh14acc042001-06-10 19:56:58 +00003626/*
drhc3b70572003-01-04 19:44:07 +00003627** The following parameters determine how many adjacent pages get involved
3628** in a balancing operation. NN is the number of neighbors on either side
3629** of the page that participate in the balancing operation. NB is the
3630** total number of pages that participate, including the target page and
3631** NN neighbors on either side.
3632**
3633** The minimum value of NN is 1 (of course). Increasing NN above 1
3634** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
3635** in exchange for a larger degradation in INSERT and UPDATE performance.
3636** The value of NN appears to give the best results overall.
3637*/
3638#define NN 1 /* Number of neighbors on either side of pPage */
3639#define NB (NN*2+1) /* Total pages involved in the balance */
3640
drh43605152004-05-29 21:46:49 +00003641/* Forward reference */
danielk1977ac245ec2005-01-14 13:50:11 +00003642static int balance(MemPage*, int);
3643
drh615ae552005-01-16 23:21:00 +00003644#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00003645/*
3646** This version of balance() handles the common special case where
3647** a new entry is being inserted on the extreme right-end of the
3648** tree, in other words, when the new entry will become the largest
3649** entry in the tree.
3650**
3651** Instead of trying balance the 3 right-most leaf pages, just add
3652** a new page to the right-hand side and put the one new entry in
3653** that page. This leaves the right side of the tree somewhat
3654** unbalanced. But odds are that we will be inserting new entries
3655** at the end soon afterwards so the nearly empty page will quickly
3656** fill up. On average.
3657**
3658** pPage is the leaf page which is the right-most page in the tree.
3659** pParent is its parent. pPage must have a single overflow entry
3660** which is also the right-most entry on the page.
3661*/
danielk1977ac245ec2005-01-14 13:50:11 +00003662static int balance_quick(MemPage *pPage, MemPage *pParent){
3663 int rc;
3664 MemPage *pNew;
3665 Pgno pgnoNew;
3666 u8 *pCell;
3667 int szCell;
3668 CellInfo info;
danielk1977ac11ee62005-01-15 12:45:51 +00003669 Btree *pBt = pPage->pBt;
danielk197779a40da2005-01-16 08:00:01 +00003670 int parentIdx = pParent->nCell; /* pParent new divider cell index */
3671 int parentSize; /* Size of new divider cell */
3672 u8 parentCell[64]; /* Space for the new divider cell */
danielk1977ac245ec2005-01-14 13:50:11 +00003673
3674 /* Allocate a new page. Insert the overflow cell from pPage
3675 ** into it. Then remove the overflow cell from pPage.
3676 */
danielk1977ac11ee62005-01-15 12:45:51 +00003677 rc = allocatePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977ac245ec2005-01-14 13:50:11 +00003678 if( rc!=SQLITE_OK ){
3679 return rc;
3680 }
3681 pCell = pPage->aOvfl[0].pCell;
3682 szCell = cellSizePtr(pPage, pCell);
3683 zeroPage(pNew, pPage->aData[0]);
3684 assemblePage(pNew, 1, &pCell, &szCell);
3685 pPage->nOverflow = 0;
3686
danielk197779a40da2005-01-16 08:00:01 +00003687 /* Set the parent of the newly allocated page to pParent. */
3688 pNew->pParent = pParent;
3689 sqlite3pager_ref(pParent->aData);
3690
danielk1977ac245ec2005-01-14 13:50:11 +00003691 /* pPage is currently the right-child of pParent. Change this
3692 ** so that the right-child is the new page allocated above and
danielk197779a40da2005-01-16 08:00:01 +00003693 ** pPage is the next-to-right child.
danielk1977ac245ec2005-01-14 13:50:11 +00003694 */
danielk1977ac11ee62005-01-15 12:45:51 +00003695 assert( pPage->nCell>0 );
danielk1977ac245ec2005-01-14 13:50:11 +00003696 parseCellPtr(pPage, findCell(pPage, pPage->nCell-1), &info);
3697 rc = fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, &parentSize);
3698 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00003699 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00003700 }
3701 assert( parentSize<64 );
3702 rc = insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
3703 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00003704 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00003705 }
3706 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
3707 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
3708
danielk197779a40da2005-01-16 08:00:01 +00003709#ifndef SQLITE_OMIT_AUTOVACUUM
3710 /* If this is an auto-vacuum database, update the pointer map
3711 ** with entries for the new page, and any pointer from the
3712 ** cell on the page to an overflow page.
3713 */
danielk1977ac11ee62005-01-15 12:45:51 +00003714 if( pBt->autoVacuum ){
3715 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
3716 if( rc!=SQLITE_OK ){
3717 return rc;
3718 }
danielk197779a40da2005-01-16 08:00:01 +00003719 rc = ptrmapPutOvfl(pNew, 0);
3720 if( rc!=SQLITE_OK ){
3721 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00003722 }
3723 }
danielk197779a40da2005-01-16 08:00:01 +00003724#endif
danielk1977ac11ee62005-01-15 12:45:51 +00003725
danielk197779a40da2005-01-16 08:00:01 +00003726 /* Release the reference to the new page and balance the parent page,
3727 ** in case the divider cell inserted caused it to become overfull.
3728 */
danielk1977ac245ec2005-01-14 13:50:11 +00003729 releasePage(pNew);
3730 return balance(pParent, 0);
3731}
drh615ae552005-01-16 23:21:00 +00003732#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00003733
drhc3b70572003-01-04 19:44:07 +00003734/*
danielk1977ac11ee62005-01-15 12:45:51 +00003735** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
3736** if the database supports auto-vacuum or not. Because it is used
3737** within an expression that is an argument to another macro
3738** (sqliteMallocRaw), it is not possible to use conditional compilation.
3739** So, this macro is defined instead.
3740*/
3741#ifndef SQLITE_OMIT_AUTOVACUUM
3742#define ISAUTOVACUUM (pBt->autoVacuum)
3743#else
3744#define ISAUTOVACUUM 0
3745#endif
3746
3747/*
drhab01f612004-05-22 02:55:23 +00003748** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00003749** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00003750** Usually NN siblings on either side of pPage is used in the balancing,
3751** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00003752** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00003753** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00003754** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00003755**
drh0c6cc4e2004-06-15 02:13:26 +00003756** The number of siblings of pPage might be increased or decreased by one or
3757** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00003758** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00003759** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00003760** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00003761** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00003762**
drh8b2f49b2001-06-08 00:21:52 +00003763** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00003764** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00003765** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00003766** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00003767**
drh8c42ca92001-06-22 19:15:00 +00003768** In the course of balancing the siblings of pPage, the parent of pPage
3769** might become overfull or underfull. If that happens, then this routine
3770** is called recursively on the parent.
3771**
drh5e00f6c2001-09-13 13:46:56 +00003772** If this routine fails for any reason, it might leave the database
3773** in a corrupted state. So if this routine fails, the database should
3774** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00003775*/
drh43605152004-05-29 21:46:49 +00003776static int balance_nonroot(MemPage *pPage){
drh8b2f49b2001-06-08 00:21:52 +00003777 MemPage *pParent; /* The parent of pPage */
drh4b70f112004-05-02 21:12:19 +00003778 Btree *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00003779 int nCell = 0; /* Number of cells in apCell[] */
3780 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
drh8b2f49b2001-06-08 00:21:52 +00003781 int nOld; /* Number of pages in apOld[] */
3782 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00003783 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00003784 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00003785 int idx; /* Index of pPage in pParent->aCell[] */
3786 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00003787 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00003788 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00003789 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00003790 int usableSpace; /* Bytes in pPage beyond the header */
3791 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00003792 int subtotal; /* Subtotal of bytes in cells on one page */
drhb6f41482004-05-14 01:58:11 +00003793 int iSpace = 0; /* First unused byte of aSpace[] */
drhc3b70572003-01-04 19:44:07 +00003794 MemPage *apOld[NB]; /* pPage and up to two siblings */
3795 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00003796 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00003797 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
3798 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drhc3b70572003-01-04 19:44:07 +00003799 int idxDiv[NB]; /* Indices of divider cells in pParent */
drh4b70f112004-05-02 21:12:19 +00003800 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00003801 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
3802 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00003803 u8 **apCell = 0; /* All cells begin balanced */
drh2e38c322004-09-03 18:38:44 +00003804 int *szCell; /* Local size of all cells in apCell[] */
3805 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
3806 u8 *aSpace; /* Space to hold copies of dividers cells */
danielk19774e17d142005-01-16 09:06:33 +00003807#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00003808 u8 *aFrom = 0;
3809#endif
drh8b2f49b2001-06-08 00:21:52 +00003810
drh14acc042001-06-10 19:56:58 +00003811 /*
drh43605152004-05-29 21:46:49 +00003812 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00003813 */
drh3a4c1412004-05-09 20:40:11 +00003814 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00003815 assert( sqlite3pager_iswriteable(pPage->aData) );
drh4b70f112004-05-02 21:12:19 +00003816 pBt = pPage->pBt;
drh14acc042001-06-10 19:56:58 +00003817 pParent = pPage->pParent;
drh43605152004-05-29 21:46:49 +00003818 sqlite3pager_write(pParent->aData);
3819 assert( pParent );
3820 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00003821
drh615ae552005-01-16 23:21:00 +00003822#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00003823 /*
3824 ** A special case: If a new entry has just been inserted into a
3825 ** table (that is, a btree with integer keys and all data at the leaves)
drh09d0deb2005-08-02 17:13:09 +00003826 ** and the new entry is the right-most entry in the tree (it has the
drhf222e712005-01-14 22:55:49 +00003827 ** largest key) then use the special balance_quick() routine for
3828 ** balancing. balance_quick() is much faster and results in a tighter
3829 ** packing of data in the common case.
3830 */
danielk1977ac245ec2005-01-14 13:50:11 +00003831 if( pPage->leaf &&
3832 pPage->intKey &&
3833 pPage->leafData &&
3834 pPage->nOverflow==1 &&
3835 pPage->aOvfl[0].idx==pPage->nCell &&
danielk1977ac11ee62005-01-15 12:45:51 +00003836 pPage->pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00003837 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
3838 ){
danielk1977ac11ee62005-01-15 12:45:51 +00003839 /*
3840 ** TODO: Check the siblings to the left of pPage. It may be that
3841 ** they are not full and no new page is required.
3842 */
danielk1977ac245ec2005-01-14 13:50:11 +00003843 return balance_quick(pPage, pParent);
3844 }
3845#endif
3846
drh2e38c322004-09-03 18:38:44 +00003847 /*
drh4b70f112004-05-02 21:12:19 +00003848 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00003849 ** to pPage. The "idx" variable is the index of that cell. If pPage
3850 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00003851 */
drhbb49aba2003-01-04 18:53:27 +00003852 if( pParent->idxShift ){
drha34b6762004-05-07 13:30:42 +00003853 Pgno pgno;
drh4b70f112004-05-02 21:12:19 +00003854 pgno = pPage->pgno;
drha34b6762004-05-07 13:30:42 +00003855 assert( pgno==sqlite3pager_pagenumber(pPage->aData) );
drhbb49aba2003-01-04 18:53:27 +00003856 for(idx=0; idx<pParent->nCell; idx++){
drh43605152004-05-29 21:46:49 +00003857 if( get4byte(findCell(pParent, idx))==pgno ){
drhbb49aba2003-01-04 18:53:27 +00003858 break;
3859 }
drh8b2f49b2001-06-08 00:21:52 +00003860 }
drh4b70f112004-05-02 21:12:19 +00003861 assert( idx<pParent->nCell
drh43605152004-05-29 21:46:49 +00003862 || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
drhbb49aba2003-01-04 18:53:27 +00003863 }else{
3864 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00003865 }
drh8b2f49b2001-06-08 00:21:52 +00003866
3867 /*
drh14acc042001-06-10 19:56:58 +00003868 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00003869 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00003870 */
drh14acc042001-06-10 19:56:58 +00003871 nOld = nNew = 0;
drha34b6762004-05-07 13:30:42 +00003872 sqlite3pager_ref(pParent->aData);
drh14acc042001-06-10 19:56:58 +00003873
3874 /*
drh4b70f112004-05-02 21:12:19 +00003875 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00003876 ** the siblings. An attempt is made to find NN siblings on either
3877 ** side of pPage. More siblings are taken from one side, however, if
3878 ** pPage there are fewer than NN siblings on the other side. If pParent
3879 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00003880 */
drhc3b70572003-01-04 19:44:07 +00003881 nxDiv = idx - NN;
3882 if( nxDiv + NB > pParent->nCell ){
3883 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00003884 }
drhc3b70572003-01-04 19:44:07 +00003885 if( nxDiv<0 ){
3886 nxDiv = 0;
3887 }
drh8b2f49b2001-06-08 00:21:52 +00003888 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00003889 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00003890 if( k<pParent->nCell ){
3891 idxDiv[i] = k;
drh43605152004-05-29 21:46:49 +00003892 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00003893 nDiv++;
drha34b6762004-05-07 13:30:42 +00003894 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00003895 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00003896 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00003897 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00003898 }else{
3899 break;
drh8b2f49b2001-06-08 00:21:52 +00003900 }
drhde647132004-05-07 17:57:49 +00003901 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00003902 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00003903 apOld[i]->idxParent = k;
drh91025292004-05-03 19:49:32 +00003904 apCopy[i] = 0;
3905 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00003906 nOld++;
danielk1977634f2982005-03-28 08:44:07 +00003907 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
drh8b2f49b2001-06-08 00:21:52 +00003908 }
3909
drh8d97f1f2005-05-05 18:14:13 +00003910 /* Make nMaxCells a multiple of 2 in order to preserve 8-byte
3911 ** alignment */
3912 nMaxCells = (nMaxCells + 1)&~1;
3913
drh8b2f49b2001-06-08 00:21:52 +00003914 /*
danielk1977634f2982005-03-28 08:44:07 +00003915 ** Allocate space for memory structures
3916 */
3917 apCell = sqliteMallocRaw(
3918 nMaxCells*sizeof(u8*) /* apCell */
3919 + nMaxCells*sizeof(int) /* szCell */
drhc96d8532005-05-03 12:30:33 +00003920 + ROUND8(sizeof(MemPage))*NB /* aCopy */
drh07d183d2005-05-01 22:52:42 +00003921 + pBt->pageSize*(5+NB) /* aSpace */
drhc96d8532005-05-03 12:30:33 +00003922 + (ISAUTOVACUUM ? nMaxCells : 0) /* aFrom */
danielk1977634f2982005-03-28 08:44:07 +00003923 );
3924 if( apCell==0 ){
3925 rc = SQLITE_NOMEM;
3926 goto balance_cleanup;
3927 }
3928 szCell = (int*)&apCell[nMaxCells];
3929 aCopy[0] = (u8*)&szCell[nMaxCells];
drhc96d8532005-05-03 12:30:33 +00003930 assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00003931 for(i=1; i<NB; i++){
drhc96d8532005-05-03 12:30:33 +00003932 aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
3933 assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00003934 }
drhc96d8532005-05-03 12:30:33 +00003935 aSpace = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
3936 assert( ((aSpace - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00003937#ifndef SQLITE_OMIT_AUTOVACUUM
3938 if( pBt->autoVacuum ){
drh07d183d2005-05-01 22:52:42 +00003939 aFrom = &aSpace[5*pBt->pageSize];
danielk1977634f2982005-03-28 08:44:07 +00003940 }
3941#endif
3942
3943 /*
drh14acc042001-06-10 19:56:58 +00003944 ** Make copies of the content of pPage and its siblings into aOld[].
3945 ** The rest of this function will use data from the copies rather
3946 ** that the original pages since the original pages will be in the
3947 ** process of being overwritten.
3948 */
3949 for(i=0; i<nOld; i++){
drh07d183d2005-05-01 22:52:42 +00003950 MemPage *p = apCopy[i] = (MemPage*)&aCopy[i][pBt->pageSize];
drh07d183d2005-05-01 22:52:42 +00003951 p->aData = &((u8*)p)[-pBt->pageSize];
3952 memcpy(p->aData, apOld[i]->aData, pBt->pageSize + sizeof(MemPage));
3953 /* The memcpy() above changes the value of p->aData so we have to
3954 ** set it again. */
drh07d183d2005-05-01 22:52:42 +00003955 p->aData = &((u8*)p)[-pBt->pageSize];
drh14acc042001-06-10 19:56:58 +00003956 }
3957
3958 /*
3959 ** Load pointers to all cells on sibling pages and the divider cells
3960 ** into the local apCell[] array. Make copies of the divider cells
drhb6f41482004-05-14 01:58:11 +00003961 ** into space obtained form aSpace[] and remove the the divider Cells
3962 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00003963 **
3964 ** If the siblings are on leaf pages, then the child pointers of the
3965 ** divider cells are stripped from the cells before they are copied
drh96f5b762004-05-16 16:24:36 +00003966 ** into aSpace[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00003967 ** child pointers. If siblings are not leaves, then all cell in
3968 ** apCell[] include child pointers. Either way, all cells in apCell[]
3969 ** are alike.
drh96f5b762004-05-16 16:24:36 +00003970 **
3971 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
3972 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00003973 */
3974 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00003975 leafCorrection = pPage->leaf*4;
drh8b18dd42004-05-12 19:18:15 +00003976 leafData = pPage->leafData && pPage->leaf;
drh8b2f49b2001-06-08 00:21:52 +00003977 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00003978 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00003979 int limit = pOld->nCell+pOld->nOverflow;
3980 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00003981 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00003982 apCell[nCell] = findOverflowCell(pOld, j);
3983 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk1977ac11ee62005-01-15 12:45:51 +00003984#ifndef SQLITE_OMIT_AUTOVACUUM
3985 if( pBt->autoVacuum ){
3986 int a;
3987 aFrom[nCell] = i;
3988 for(a=0; a<pOld->nOverflow; a++){
3989 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
3990 aFrom[nCell] = 0xFF;
3991 break;
3992 }
3993 }
3994 }
3995#endif
drh14acc042001-06-10 19:56:58 +00003996 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00003997 }
3998 if( i<nOld-1 ){
drh43605152004-05-29 21:46:49 +00003999 int sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00004000 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00004001 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
4002 ** are duplicates of keys on the child pages. We need to remove
4003 ** the divider cells from pParent, but the dividers cells are not
4004 ** added to apCell[] because they are duplicates of child cells.
4005 */
drh8b18dd42004-05-12 19:18:15 +00004006 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00004007 }else{
drhb6f41482004-05-14 01:58:11 +00004008 u8 *pTemp;
danielk1977634f2982005-03-28 08:44:07 +00004009 assert( nCell<nMaxCells );
drhb6f41482004-05-14 01:58:11 +00004010 szCell[nCell] = sz;
4011 pTemp = &aSpace[iSpace];
4012 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004013 assert( iSpace<=pBt->pageSize*5 );
drhb6f41482004-05-14 01:58:11 +00004014 memcpy(pTemp, apDiv[i], sz);
4015 apCell[nCell] = pTemp+leafCorrection;
danielk1977ac11ee62005-01-15 12:45:51 +00004016#ifndef SQLITE_OMIT_AUTOVACUUM
4017 if( pBt->autoVacuum ){
4018 aFrom[nCell] = 0xFF;
4019 }
4020#endif
drhb6f41482004-05-14 01:58:11 +00004021 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00004022 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00004023 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00004024 if( !pOld->leaf ){
4025 assert( leafCorrection==0 );
4026 /* The right pointer of the child page pOld becomes the left
4027 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00004028 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00004029 }else{
4030 assert( leafCorrection==4 );
4031 }
4032 nCell++;
drh4b70f112004-05-02 21:12:19 +00004033 }
drh8b2f49b2001-06-08 00:21:52 +00004034 }
4035 }
4036
4037 /*
drh6019e162001-07-02 17:51:45 +00004038 ** Figure out the number of pages needed to hold all nCell cells.
4039 ** Store this number in "k". Also compute szNew[] which is the total
4040 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00004041 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00004042 ** cntNew[k] should equal nCell.
4043 **
drh96f5b762004-05-16 16:24:36 +00004044 ** Values computed by this block:
4045 **
4046 ** k: The total number of sibling pages
4047 ** szNew[i]: Spaced used on the i-th sibling page.
4048 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
4049 ** the right of the i-th sibling page.
4050 ** usableSpace: Number of bytes of space available on each sibling.
4051 **
drh8b2f49b2001-06-08 00:21:52 +00004052 */
drh43605152004-05-29 21:46:49 +00004053 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00004054 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00004055 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00004056 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00004057 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00004058 szNew[k] = subtotal - szCell[i];
4059 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00004060 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00004061 subtotal = 0;
4062 k++;
4063 }
4064 }
4065 szNew[k] = subtotal;
4066 cntNew[k] = nCell;
4067 k++;
drh96f5b762004-05-16 16:24:36 +00004068
4069 /*
4070 ** The packing computed by the previous block is biased toward the siblings
4071 ** on the left side. The left siblings are always nearly full, while the
4072 ** right-most sibling might be nearly empty. This block of code attempts
4073 ** to adjust the packing of siblings to get a better balance.
4074 **
4075 ** This adjustment is more than an optimization. The packing above might
4076 ** be so out of balance as to be illegal. For example, the right-most
4077 ** sibling might be completely empty. This adjustment is not optional.
4078 */
drh6019e162001-07-02 17:51:45 +00004079 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00004080 int szRight = szNew[i]; /* Size of sibling on the right */
4081 int szLeft = szNew[i-1]; /* Size of sibling on the left */
4082 int r; /* Index of right-most cell in left sibling */
4083 int d; /* Index of first cell to the left of right sibling */
4084
4085 r = cntNew[i-1] - 1;
4086 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00004087 assert( d<nMaxCells );
4088 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00004089 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
4090 szRight += szCell[d] + 2;
4091 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00004092 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00004093 r = cntNew[i-1] - 1;
4094 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00004095 }
drh96f5b762004-05-16 16:24:36 +00004096 szNew[i] = szRight;
4097 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00004098 }
drh09d0deb2005-08-02 17:13:09 +00004099
4100 /* Either we found one or more cells (cntnew[0])>0) or we are the
4101 ** a virtual root page. A virtual root page is when the real root
4102 ** page is page 1 and we are the only child of that page.
4103 */
4104 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00004105
4106 /*
drh6b308672002-07-08 02:16:37 +00004107 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00004108 */
drh4b70f112004-05-02 21:12:19 +00004109 assert( pPage->pgno>1 );
4110 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00004111 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00004112 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00004113 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00004114 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00004115 pgnoNew[i] = pgnoOld[i];
4116 apOld[i] = 0;
danielk197728129562005-01-11 10:25:06 +00004117 rc = sqlite3pager_write(pNew->aData);
4118 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00004119 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004120 rc = allocatePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00004121 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00004122 apNew[i] = pNew;
drh6b308672002-07-08 02:16:37 +00004123 }
drh14acc042001-06-10 19:56:58 +00004124 nNew++;
drhda200cc2004-05-09 11:51:38 +00004125 zeroPage(pNew, pageFlags);
drh8b2f49b2001-06-08 00:21:52 +00004126 }
4127
danielk1977299b1872004-11-22 10:02:10 +00004128 /* Free any old pages that were not reused as new pages.
4129 */
4130 while( i<nOld ){
4131 rc = freePage(apOld[i]);
4132 if( rc ) goto balance_cleanup;
4133 releasePage(apOld[i]);
4134 apOld[i] = 0;
4135 i++;
4136 }
4137
drh8b2f49b2001-06-08 00:21:52 +00004138 /*
drhf9ffac92002-03-02 19:00:31 +00004139 ** Put the new pages in accending order. This helps to
4140 ** keep entries in the disk file in order so that a scan
4141 ** of the table is a linear scan through the file. That
4142 ** in turn helps the operating system to deliver pages
4143 ** from the disk more rapidly.
4144 **
4145 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00004146 ** n is never more than NB (a small constant), that should
4147 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00004148 **
drhc3b70572003-01-04 19:44:07 +00004149 ** When NB==3, this one optimization makes the database
4150 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00004151 */
4152 for(i=0; i<k-1; i++){
4153 int minV = pgnoNew[i];
4154 int minI = i;
4155 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00004156 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00004157 minI = j;
4158 minV = pgnoNew[j];
4159 }
4160 }
4161 if( minI>i ){
4162 int t;
4163 MemPage *pT;
4164 t = pgnoNew[i];
4165 pT = apNew[i];
4166 pgnoNew[i] = pgnoNew[minI];
4167 apNew[i] = apNew[minI];
4168 pgnoNew[minI] = t;
4169 apNew[minI] = pT;
4170 }
4171 }
drha2fce642004-06-05 00:01:44 +00004172 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00004173 pgnoOld[0],
4174 nOld>=2 ? pgnoOld[1] : 0,
4175 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00004176 pgnoNew[0], szNew[0],
4177 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
4178 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00004179 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
4180 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00004181
drhf9ffac92002-03-02 19:00:31 +00004182 /*
drh14acc042001-06-10 19:56:58 +00004183 ** Evenly distribute the data in apCell[] across the new pages.
4184 ** Insert divider cells into pParent as necessary.
4185 */
4186 j = 0;
4187 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00004188 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00004189 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00004190 assert( j<nMaxCells );
drh4b70f112004-05-02 21:12:19 +00004191 assert( pNew->pgno==pgnoNew[i] );
drhfa1a98a2004-05-14 19:08:17 +00004192 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00004193 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00004194 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00004195
4196#ifndef SQLITE_OMIT_AUTOVACUUM
4197 /* If this is an auto-vacuum database, update the pointer map entries
4198 ** that point to the siblings that were rearranged. These can be: left
4199 ** children of cells, the right-child of the page, or overflow pages
4200 ** pointed to by cells.
4201 */
4202 if( pBt->autoVacuum ){
4203 for(k=j; k<cntNew[i]; k++){
danielk1977634f2982005-03-28 08:44:07 +00004204 assert( k<nMaxCells );
danielk1977ac11ee62005-01-15 12:45:51 +00004205 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
danielk197779a40da2005-01-16 08:00:01 +00004206 rc = ptrmapPutOvfl(pNew, k-j);
4207 if( rc!=SQLITE_OK ){
4208 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00004209 }
4210 }
4211 }
4212 }
4213#endif
4214
4215 j = cntNew[i];
4216
4217 /* If the sibling page assembled above was not the right-most sibling,
4218 ** insert a divider cell into the parent page.
4219 */
drh14acc042001-06-10 19:56:58 +00004220 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00004221 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00004222 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00004223 int sz;
danielk1977634f2982005-03-28 08:44:07 +00004224
4225 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00004226 pCell = apCell[j];
4227 sz = szCell[j] + leafCorrection;
drh4b70f112004-05-02 21:12:19 +00004228 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00004229 memcpy(&pNew->aData[8], pCell, 4);
drh24cd67e2004-05-10 16:18:47 +00004230 pTemp = 0;
drh8b18dd42004-05-12 19:18:15 +00004231 }else if( leafData ){
danielk1977ac11ee62005-01-15 12:45:51 +00004232 /* If the tree is a leaf-data tree, and the siblings are leaves,
4233 ** then there is no divider cell in apCell[]. Instead, the divider
4234 ** cell consists of the integer key for the right-most cell of
4235 ** the sibling-page assembled above only.
4236 */
drh6f11bef2004-05-13 01:12:56 +00004237 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00004238 j--;
drh43605152004-05-29 21:46:49 +00004239 parseCellPtr(pNew, apCell[j], &info);
drhb6f41482004-05-14 01:58:11 +00004240 pCell = &aSpace[iSpace];
drh6f11bef2004-05-13 01:12:56 +00004241 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, &sz);
drhb6f41482004-05-14 01:58:11 +00004242 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004243 assert( iSpace<=pBt->pageSize*5 );
drh8b18dd42004-05-12 19:18:15 +00004244 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00004245 }else{
4246 pCell -= 4;
drhb6f41482004-05-14 01:58:11 +00004247 pTemp = &aSpace[iSpace];
4248 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004249 assert( iSpace<=pBt->pageSize*5 );
drh4b70f112004-05-02 21:12:19 +00004250 }
danielk1977a3ad5e72005-01-07 08:56:44 +00004251 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00004252 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh43605152004-05-29 21:46:49 +00004253 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +00004254#ifndef SQLITE_OMIT_AUTOVACUUM
4255 /* If this is an auto-vacuum database, and not a leaf-data tree,
4256 ** then update the pointer map with an entry for the overflow page
4257 ** that the cell just inserted points to (if any).
4258 */
4259 if( pBt->autoVacuum && !leafData ){
danielk197779a40da2005-01-16 08:00:01 +00004260 rc = ptrmapPutOvfl(pParent, nxDiv);
4261 if( rc!=SQLITE_OK ){
4262 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00004263 }
4264 }
4265#endif
drh14acc042001-06-10 19:56:58 +00004266 j++;
4267 nxDiv++;
4268 }
4269 }
drh6019e162001-07-02 17:51:45 +00004270 assert( j==nCell );
drh4b70f112004-05-02 21:12:19 +00004271 if( (pageFlags & PTF_LEAF)==0 ){
drh43605152004-05-29 21:46:49 +00004272 memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
drh14acc042001-06-10 19:56:58 +00004273 }
drh43605152004-05-29 21:46:49 +00004274 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00004275 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00004276 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00004277 }else{
4278 /* Right-most sibling is the left child of the first entry in pParent
4279 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00004280 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00004281 }
4282
4283 /*
4284 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00004285 */
4286 for(i=0; i<nNew; i++){
danielk1977afcdd022004-10-31 16:25:42 +00004287 rc = reparentChildPages(apNew[i]);
4288 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004289 }
danielk1977afcdd022004-10-31 16:25:42 +00004290 rc = reparentChildPages(pParent);
4291 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004292
4293 /*
drh3a4c1412004-05-09 20:40:11 +00004294 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00004295 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00004296 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00004297 */
drhda200cc2004-05-09 11:51:38 +00004298 assert( pParent->isInit );
drh3a4c1412004-05-09 20:40:11 +00004299 /* assert( pPage->isInit ); // No! pPage might have been added to freelist */
4300 /* pageIntegrity(pPage); // No! pPage might have been added to freelist */
danielk1977ac245ec2005-01-14 13:50:11 +00004301 rc = balance(pParent, 0);
drhda200cc2004-05-09 11:51:38 +00004302
drh8b2f49b2001-06-08 00:21:52 +00004303 /*
drh14acc042001-06-10 19:56:58 +00004304 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00004305 */
drh14acc042001-06-10 19:56:58 +00004306balance_cleanup:
drh2e38c322004-09-03 18:38:44 +00004307 sqliteFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00004308 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00004309 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00004310 }
drh14acc042001-06-10 19:56:58 +00004311 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00004312 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00004313 }
drh91025292004-05-03 19:49:32 +00004314 releasePage(pParent);
drh3a4c1412004-05-09 20:40:11 +00004315 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
4316 pPage->pgno, nOld, nNew, nCell));
drh8b2f49b2001-06-08 00:21:52 +00004317 return rc;
4318}
4319
4320/*
drh43605152004-05-29 21:46:49 +00004321** This routine is called for the root page of a btree when the root
4322** page contains no cells. This is an opportunity to make the tree
4323** shallower by one level.
4324*/
4325static int balance_shallower(MemPage *pPage){
4326 MemPage *pChild; /* The only child page of pPage */
4327 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00004328 int rc = SQLITE_OK; /* Return code from subprocedures */
4329 Btree *pBt; /* The main BTree structure */
4330 int mxCellPerPage; /* Maximum number of cells per page */
4331 u8 **apCell; /* All cells from pages being balanced */
4332 int *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00004333
4334 assert( pPage->pParent==0 );
4335 assert( pPage->nCell==0 );
drh2e38c322004-09-03 18:38:44 +00004336 pBt = pPage->pBt;
4337 mxCellPerPage = MX_CELL(pBt);
4338 apCell = sqliteMallocRaw( mxCellPerPage*(sizeof(u8*)+sizeof(int)) );
4339 if( apCell==0 ) return SQLITE_NOMEM;
4340 szCell = (int*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00004341 if( pPage->leaf ){
4342 /* The table is completely empty */
4343 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
4344 }else{
4345 /* The root page is empty but has one child. Transfer the
4346 ** information from that one child into the root page if it
4347 ** will fit. This reduces the depth of the tree by one.
4348 **
4349 ** If the root page is page 1, it has less space available than
4350 ** its child (due to the 100 byte header that occurs at the beginning
4351 ** of the database fle), so it might not be able to hold all of the
4352 ** information currently contained in the child. If this is the
4353 ** case, then do not do the transfer. Leave page 1 empty except
4354 ** for the right-pointer to the child page. The child page becomes
4355 ** the virtual root of the tree.
4356 */
4357 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
4358 assert( pgnoChild>0 );
4359 assert( pgnoChild<=sqlite3pager_pagecount(pPage->pBt->pPager) );
4360 rc = getPage(pPage->pBt, pgnoChild, &pChild);
drh2e38c322004-09-03 18:38:44 +00004361 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004362 if( pPage->pgno==1 ){
4363 rc = initPage(pChild, pPage);
drh2e38c322004-09-03 18:38:44 +00004364 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004365 assert( pChild->nOverflow==0 );
4366 if( pChild->nFree>=100 ){
4367 /* The child information will fit on the root page, so do the
4368 ** copy */
4369 int i;
4370 zeroPage(pPage, pChild->aData[0]);
4371 for(i=0; i<pChild->nCell; i++){
4372 apCell[i] = findCell(pChild,i);
4373 szCell[i] = cellSizePtr(pChild, apCell[i]);
4374 }
4375 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00004376 /* Copy the right-pointer of the child to the parent. */
4377 put4byte(&pPage->aData[pPage->hdrOffset+8],
4378 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh43605152004-05-29 21:46:49 +00004379 freePage(pChild);
4380 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
4381 }else{
4382 /* The child has more information that will fit on the root.
4383 ** The tree is already balanced. Do nothing. */
4384 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
4385 }
4386 }else{
4387 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
4388 pPage->isInit = 0;
4389 pPage->pParent = 0;
4390 rc = initPage(pPage, 0);
4391 assert( rc==SQLITE_OK );
4392 freePage(pChild);
4393 TRACE(("BALANCE: transfer child %d into root %d\n",
4394 pChild->pgno, pPage->pgno));
4395 }
danielk1977afcdd022004-10-31 16:25:42 +00004396 rc = reparentChildPages(pPage);
danielk1977ac11ee62005-01-15 12:45:51 +00004397 assert( pPage->nOverflow==0 );
4398#ifndef SQLITE_OMIT_AUTOVACUUM
4399 if( pBt->autoVacuum ){
danielk1977aac0a382005-01-16 11:07:06 +00004400 int i;
danielk1977ac11ee62005-01-15 12:45:51 +00004401 for(i=0; i<pPage->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00004402 rc = ptrmapPutOvfl(pPage, i);
4403 if( rc!=SQLITE_OK ){
4404 goto end_shallow_balance;
danielk1977ac11ee62005-01-15 12:45:51 +00004405 }
4406 }
4407 }
4408#endif
danielk1977afcdd022004-10-31 16:25:42 +00004409 if( rc!=SQLITE_OK ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004410 releasePage(pChild);
4411 }
drh2e38c322004-09-03 18:38:44 +00004412end_shallow_balance:
4413 sqliteFree(apCell);
4414 return rc;
drh43605152004-05-29 21:46:49 +00004415}
4416
4417
4418/*
4419** The root page is overfull
4420**
4421** When this happens, Create a new child page and copy the
4422** contents of the root into the child. Then make the root
4423** page an empty page with rightChild pointing to the new
4424** child. Finally, call balance_internal() on the new child
4425** to cause it to split.
4426*/
4427static int balance_deeper(MemPage *pPage){
4428 int rc; /* Return value from subprocedures */
4429 MemPage *pChild; /* Pointer to a new child page */
4430 Pgno pgnoChild; /* Page number of the new child page */
4431 Btree *pBt; /* The BTree */
4432 int usableSize; /* Total usable size of a page */
4433 u8 *data; /* Content of the parent page */
4434 u8 *cdata; /* Content of the child page */
4435 int hdr; /* Offset to page header in parent */
4436 int brk; /* Offset to content of first cell in parent */
4437
4438 assert( pPage->pParent==0 );
4439 assert( pPage->nOverflow>0 );
4440 pBt = pPage->pBt;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004441 rc = allocatePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00004442 if( rc ) return rc;
4443 assert( sqlite3pager_iswriteable(pChild->aData) );
4444 usableSize = pBt->usableSize;
4445 data = pPage->aData;
4446 hdr = pPage->hdrOffset;
4447 brk = get2byte(&data[hdr+5]);
4448 cdata = pChild->aData;
4449 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
4450 memcpy(&cdata[brk], &data[brk], usableSize-brk);
danielk1977c7dc7532004-11-17 10:22:03 +00004451 assert( pChild->isInit==0 );
drh43605152004-05-29 21:46:49 +00004452 rc = initPage(pChild, pPage);
danielk19776b456a22005-03-21 04:04:02 +00004453 if( rc ) goto balancedeeper_out;
drh43605152004-05-29 21:46:49 +00004454 memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
4455 pChild->nOverflow = pPage->nOverflow;
4456 if( pChild->nOverflow ){
4457 pChild->nFree = 0;
4458 }
4459 assert( pChild->nCell==pPage->nCell );
4460 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
4461 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
4462 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
danielk19774e17d142005-01-16 09:06:33 +00004463#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00004464 if( pBt->autoVacuum ){
4465 int i;
4466 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
danielk19776b456a22005-03-21 04:04:02 +00004467 if( rc ) goto balancedeeper_out;
danielk1977ac11ee62005-01-15 12:45:51 +00004468 for(i=0; i<pChild->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00004469 rc = ptrmapPutOvfl(pChild, i);
4470 if( rc!=SQLITE_OK ){
4471 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00004472 }
4473 }
4474 }
danielk19774e17d142005-01-16 09:06:33 +00004475#endif
drh43605152004-05-29 21:46:49 +00004476 rc = balance_nonroot(pChild);
danielk19776b456a22005-03-21 04:04:02 +00004477
4478balancedeeper_out:
drh43605152004-05-29 21:46:49 +00004479 releasePage(pChild);
4480 return rc;
4481}
4482
4483/*
4484** Decide if the page pPage needs to be balanced. If balancing is
4485** required, call the appropriate balancing routine.
4486*/
danielk1977ac245ec2005-01-14 13:50:11 +00004487static int balance(MemPage *pPage, int insert){
drh43605152004-05-29 21:46:49 +00004488 int rc = SQLITE_OK;
4489 if( pPage->pParent==0 ){
4490 if( pPage->nOverflow>0 ){
4491 rc = balance_deeper(pPage);
4492 }
danielk1977687566d2004-11-02 12:56:41 +00004493 if( rc==SQLITE_OK && pPage->nCell==0 ){
drh43605152004-05-29 21:46:49 +00004494 rc = balance_shallower(pPage);
4495 }
4496 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00004497 if( pPage->nOverflow>0 ||
4498 (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
drh43605152004-05-29 21:46:49 +00004499 rc = balance_nonroot(pPage);
4500 }
4501 }
4502 return rc;
4503}
4504
4505/*
drh8dcd7ca2004-08-08 19:43:29 +00004506** This routine checks all cursors that point to table pgnoRoot.
4507** If any of those cursors other than pExclude were opened with
drhf74b8d92002-09-01 23:20:45 +00004508** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
drh8dcd7ca2004-08-08 19:43:29 +00004509** cursors that point to pgnoRoot were opened with wrFlag==1
drhf74b8d92002-09-01 23:20:45 +00004510** then this routine returns SQLITE_OK.
danielk1977299b1872004-11-22 10:02:10 +00004511**
4512** In addition to checking for read-locks (where a read-lock
4513** means a cursor opened with wrFlag==0) this routine also moves
4514** all cursors other than pExclude so that they are pointing to the
4515** first Cell on root page. This is necessary because an insert
4516** or delete might change the number of cells on a page or delete
4517** a page entirely and we do not want to leave any cursors
4518** pointing to non-existant pages or cells.
drhf74b8d92002-09-01 23:20:45 +00004519*/
drh8dcd7ca2004-08-08 19:43:29 +00004520static int checkReadLocks(Btree *pBt, Pgno pgnoRoot, BtCursor *pExclude){
danielk1977299b1872004-11-22 10:02:10 +00004521 BtCursor *p;
4522 for(p=pBt->pCursor; p; p=p->pNext){
4523 if( p->pgnoRoot!=pgnoRoot || p==pExclude ) continue;
4524 if( p->wrFlag==0 ) return SQLITE_LOCKED;
4525 if( p->pPage->pgno!=p->pgnoRoot ){
4526 moveToRoot(p);
4527 }
4528 }
drhf74b8d92002-09-01 23:20:45 +00004529 return SQLITE_OK;
4530}
4531
4532/*
drh3b7511c2001-05-26 13:15:44 +00004533** Insert a new record into the BTree. The key is given by (pKey,nKey)
4534** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00004535** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00004536** is left pointing at a random location.
4537**
4538** For an INTKEY table, only the nKey value of the key is used. pKey is
4539** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00004540*/
drh3aac2dd2004-04-26 14:10:20 +00004541int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00004542 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00004543 const void *pKey, i64 nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00004544 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00004545){
drh3b7511c2001-05-26 13:15:44 +00004546 int rc;
4547 int loc;
drh14acc042001-06-10 19:56:58 +00004548 int szNew;
drh3b7511c2001-05-26 13:15:44 +00004549 MemPage *pPage;
4550 Btree *pBt = pCur->pBt;
drha34b6762004-05-07 13:30:42 +00004551 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00004552 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00004553
danielk1977ee5741e2004-05-31 10:01:34 +00004554 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00004555 /* Must start a transaction before doing an insert */
4556 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00004557 }
drhf74b8d92002-09-01 23:20:45 +00004558 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00004559 if( !pCur->wrFlag ){
4560 return SQLITE_PERM; /* Cursor not open for writing */
4561 }
drh8dcd7ca2004-08-08 19:43:29 +00004562 if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00004563 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
4564 }
drh3aac2dd2004-04-26 14:10:20 +00004565 rc = sqlite3BtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00004566 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00004567 pPage = pCur->pPage;
drh4a1c3802004-05-12 15:15:47 +00004568 assert( pPage->intKey || nKey>=0 );
drh8b18dd42004-05-12 19:18:15 +00004569 assert( pPage->leaf || !pPage->leafData );
drh3a4c1412004-05-09 20:40:11 +00004570 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
4571 pCur->pgnoRoot, nKey, nData, pPage->pgno,
4572 loc==0 ? "overwrite" : "new entry"));
drh7aa128d2002-06-21 13:09:16 +00004573 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004574 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00004575 if( rc ) return rc;
drh2e38c322004-09-03 18:38:44 +00004576 newCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
4577 if( newCell==0 ) return SQLITE_NOMEM;
drha34b6762004-05-07 13:30:42 +00004578 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, &szNew);
drh2e38c322004-09-03 18:38:44 +00004579 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00004580 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00004581 assert( szNew<=MX_CELL_SIZE(pBt) );
drhf328bc82004-05-10 23:29:49 +00004582 if( loc==0 && pCur->isValid ){
drha34b6762004-05-07 13:30:42 +00004583 int szOld;
4584 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00004585 oldCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00004586 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004587 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00004588 }
drh43605152004-05-29 21:46:49 +00004589 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00004590 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00004591 if( rc ) goto end_insert;
drh4b70f112004-05-02 21:12:19 +00004592 dropCell(pPage, pCur->idx, szOld);
drh7c717f72001-06-24 20:39:41 +00004593 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00004594 assert( pPage->leaf );
drh14acc042001-06-10 19:56:58 +00004595 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00004596 pCur->info.nSize = 0;
drh14acc042001-06-10 19:56:58 +00004597 }else{
drh4b70f112004-05-02 21:12:19 +00004598 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00004599 }
danielk1977a3ad5e72005-01-07 08:56:44 +00004600 rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
danielk1977e80463b2004-11-03 03:01:16 +00004601 if( rc!=SQLITE_OK ) goto end_insert;
danielk1977ac245ec2005-01-14 13:50:11 +00004602 rc = balance(pPage, 1);
drh23e11ca2004-05-04 17:27:28 +00004603 /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
drh3fc190c2001-09-14 03:24:23 +00004604 /* fflush(stdout); */
danielk1977299b1872004-11-22 10:02:10 +00004605 if( rc==SQLITE_OK ){
4606 moveToRoot(pCur);
4607 }
drh2e38c322004-09-03 18:38:44 +00004608end_insert:
4609 sqliteFree(newCell);
drh5e2f8b92001-05-28 00:41:15 +00004610 return rc;
4611}
4612
4613/*
drh4b70f112004-05-02 21:12:19 +00004614** Delete the entry that the cursor is pointing to. The cursor
4615** is left pointing at a random location.
drh3b7511c2001-05-26 13:15:44 +00004616*/
drh3aac2dd2004-04-26 14:10:20 +00004617int sqlite3BtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00004618 MemPage *pPage = pCur->pPage;
drh4b70f112004-05-02 21:12:19 +00004619 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00004620 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00004621 Pgno pgnoChild = 0;
drh0d316a42002-08-11 20:10:47 +00004622 Btree *pBt = pCur->pBt;
drh8b2f49b2001-06-08 00:21:52 +00004623
drh7aa128d2002-06-21 13:09:16 +00004624 assert( pPage->isInit );
danielk1977ee5741e2004-05-31 10:01:34 +00004625 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00004626 /* Must start a transaction before doing a delete */
4627 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00004628 }
drhf74b8d92002-09-01 23:20:45 +00004629 assert( !pBt->readOnly );
drhbd03cae2001-06-02 02:40:57 +00004630 if( pCur->idx >= pPage->nCell ){
4631 return SQLITE_ERROR; /* The cursor is not pointing to anything */
4632 }
drhecdc7532001-09-23 02:35:53 +00004633 if( !pCur->wrFlag ){
4634 return SQLITE_PERM; /* Did not open this cursor for writing */
4635 }
drh8dcd7ca2004-08-08 19:43:29 +00004636 if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00004637 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
4638 }
drha34b6762004-05-07 13:30:42 +00004639 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00004640 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00004641
4642 /* Locate the cell within it's page and leave pCell pointing to the
4643 ** data. The clearCell() call frees any overflow pages associated with the
4644 ** cell. The cell itself is still intact.
4645 */
danielk1977299b1872004-11-22 10:02:10 +00004646 pCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00004647 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004648 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00004649 }
danielk197728129562005-01-11 10:25:06 +00004650 rc = clearCell(pPage, pCell);
4651 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00004652
drh4b70f112004-05-02 21:12:19 +00004653 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00004654 /*
drh5e00f6c2001-09-13 13:46:56 +00004655 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00004656 ** do something we will leave a hole on an internal page.
4657 ** We have to fill the hole by moving in a cell from a leaf. The
4658 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00004659 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00004660 */
drh14acc042001-06-10 19:56:58 +00004661 BtCursor leafCur;
drh4b70f112004-05-02 21:12:19 +00004662 unsigned char *pNext;
drh14acc042001-06-10 19:56:58 +00004663 int szNext;
danielk1977299b1872004-11-22 10:02:10 +00004664 int notUsed;
danielk19776b456a22005-03-21 04:04:02 +00004665 unsigned char *tempCell = 0;
drh8b18dd42004-05-12 19:18:15 +00004666 assert( !pPage->leafData );
drh14acc042001-06-10 19:56:58 +00004667 getTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00004668 rc = sqlite3BtreeNext(&leafCur, &notUsed);
drh14acc042001-06-10 19:56:58 +00004669 if( rc!=SQLITE_OK ){
drhee696e22004-08-30 16:52:17 +00004670 if( rc!=SQLITE_NOMEM ){
4671 rc = SQLITE_CORRUPT; /* bkpt-CORRUPT */
4672 }
drh5e2f8b92001-05-28 00:41:15 +00004673 }
danielk19776b456a22005-03-21 04:04:02 +00004674 if( rc==SQLITE_OK ){
4675 rc = sqlite3pager_write(leafCur.pPage->aData);
4676 }
4677 if( rc==SQLITE_OK ){
4678 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
4679 pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
4680 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
4681 pNext = findCell(leafCur.pPage, leafCur.idx);
4682 szNext = cellSizePtr(leafCur.pPage, pNext);
4683 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
4684 tempCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
4685 if( tempCell==0 ){
4686 rc = SQLITE_NOMEM;
4687 }
4688 }
4689 if( rc==SQLITE_OK ){
4690 rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
4691 }
4692 if( rc==SQLITE_OK ){
4693 put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
4694 rc = balance(pPage, 0);
4695 }
4696 if( rc==SQLITE_OK ){
4697 dropCell(leafCur.pPage, leafCur.idx, szNext);
4698 rc = balance(leafCur.pPage, 0);
4699 }
drh2e38c322004-09-03 18:38:44 +00004700 sqliteFree(tempCell);
drh8c42ca92001-06-22 19:15:00 +00004701 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00004702 }else{
danielk1977299b1872004-11-22 10:02:10 +00004703 TRACE(("DELETE: table=%d delete from leaf %d\n",
4704 pCur->pgnoRoot, pPage->pgno));
4705 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
danielk1977ac245ec2005-01-14 13:50:11 +00004706 rc = balance(pPage, 0);
drh5e2f8b92001-05-28 00:41:15 +00004707 }
danielk19776b456a22005-03-21 04:04:02 +00004708 if( rc==SQLITE_OK ){
4709 moveToRoot(pCur);
4710 }
drh5e2f8b92001-05-28 00:41:15 +00004711 return rc;
drh3b7511c2001-05-26 13:15:44 +00004712}
drh8b2f49b2001-06-08 00:21:52 +00004713
4714/*
drhc6b52df2002-01-04 03:09:29 +00004715** Create a new BTree table. Write into *piTable the page
4716** number for the root page of the new table.
4717**
drhab01f612004-05-22 02:55:23 +00004718** The type of type is determined by the flags parameter. Only the
4719** following values of flags are currently in use. Other values for
4720** flags might not work:
4721**
4722** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
4723** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00004724*/
drh3aac2dd2004-04-26 14:10:20 +00004725int sqlite3BtreeCreateTable(Btree *pBt, int *piTable, int flags){
drh8b2f49b2001-06-08 00:21:52 +00004726 MemPage *pRoot;
4727 Pgno pgnoRoot;
4728 int rc;
danielk1977ee5741e2004-05-31 10:01:34 +00004729 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00004730 /* Must start a transaction first */
4731 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00004732 }
danielk197728129562005-01-11 10:25:06 +00004733 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00004734
4735 /* It is illegal to create a table if any cursors are open on the
4736 ** database. This is because in auto-vacuum mode the backend may
4737 ** need to move a database page to make room for the new root-page.
4738 ** If an open cursor was using the page a problem would occur.
4739 */
4740 if( pBt->pCursor ){
4741 return SQLITE_LOCKED;
4742 }
4743
danielk1977003ba062004-11-04 02:57:33 +00004744#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977cb1a7eb2004-11-05 12:27:02 +00004745 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drh8b2f49b2001-06-08 00:21:52 +00004746 if( rc ) return rc;
danielk1977003ba062004-11-04 02:57:33 +00004747#else
danielk1977687566d2004-11-02 12:56:41 +00004748 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00004749 Pgno pgnoMove; /* Move a page here to make room for the root-page */
4750 MemPage *pPageMove; /* The page to move to. */
4751
danielk1977003ba062004-11-04 02:57:33 +00004752 /* Read the value of meta[3] from the database to determine where the
4753 ** root page of the new table should go. meta[3] is the largest root-page
4754 ** created so far, so the new root-page is (meta[3]+1).
4755 */
4756 rc = sqlite3BtreeGetMeta(pBt, 4, &pgnoRoot);
4757 if( rc!=SQLITE_OK ) return rc;
4758 pgnoRoot++;
4759
danielk1977599fcba2004-11-08 07:13:13 +00004760 /* The new root-page may not be allocated on a pointer-map page, or the
4761 ** PENDING_BYTE page.
4762 */
drh42cac6d2004-11-20 20:31:11 +00004763 if( pgnoRoot==PTRMAP_PAGENO(pBt->usableSize, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00004764 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00004765 pgnoRoot++;
4766 }
4767 assert( pgnoRoot>=3 );
4768
4769 /* Allocate a page. The page that currently resides at pgnoRoot will
4770 ** be moved to the allocated page (unless the allocated page happens
4771 ** to reside at pgnoRoot).
4772 */
danielk1977cb1a7eb2004-11-05 12:27:02 +00004773 rc = allocatePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00004774 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00004775 return rc;
4776 }
danielk1977003ba062004-11-04 02:57:33 +00004777
4778 if( pgnoMove!=pgnoRoot ){
4779 u8 eType;
4780 Pgno iPtrPage;
4781
4782 releasePage(pPageMove);
4783 rc = getPage(pBt, pgnoRoot, &pRoot);
4784 if( rc!=SQLITE_OK ){
4785 return rc;
4786 }
4787 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drhccae6022005-02-26 17:31:26 +00004788 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00004789 releasePage(pRoot);
4790 return rc;
4791 }
drhccae6022005-02-26 17:31:26 +00004792 assert( eType!=PTRMAP_ROOTPAGE );
4793 assert( eType!=PTRMAP_FREEPAGE );
danielk19775fd057a2005-03-09 13:09:43 +00004794 rc = sqlite3pager_write(pRoot->aData);
4795 if( rc!=SQLITE_OK ){
4796 releasePage(pRoot);
4797 return rc;
4798 }
danielk1977003ba062004-11-04 02:57:33 +00004799 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove);
4800 releasePage(pRoot);
4801 if( rc!=SQLITE_OK ){
4802 return rc;
4803 }
4804 rc = getPage(pBt, pgnoRoot, &pRoot);
4805 if( rc!=SQLITE_OK ){
4806 return rc;
4807 }
4808 rc = sqlite3pager_write(pRoot->aData);
4809 if( rc!=SQLITE_OK ){
4810 releasePage(pRoot);
4811 return rc;
4812 }
4813 }else{
4814 pRoot = pPageMove;
4815 }
4816
danielk197742741be2005-01-08 12:42:39 +00004817 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00004818 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
4819 if( rc ){
4820 releasePage(pRoot);
4821 return rc;
4822 }
4823 rc = sqlite3BtreeUpdateMeta(pBt, 4, pgnoRoot);
4824 if( rc ){
4825 releasePage(pRoot);
4826 return rc;
4827 }
danielk197742741be2005-01-08 12:42:39 +00004828
danielk1977003ba062004-11-04 02:57:33 +00004829 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004830 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00004831 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00004832 }
4833#endif
drha34b6762004-05-07 13:30:42 +00004834 assert( sqlite3pager_iswriteable(pRoot->aData) );
drhde647132004-05-07 17:57:49 +00004835 zeroPage(pRoot, flags | PTF_LEAF);
drha34b6762004-05-07 13:30:42 +00004836 sqlite3pager_unref(pRoot->aData);
drh8b2f49b2001-06-08 00:21:52 +00004837 *piTable = (int)pgnoRoot;
4838 return SQLITE_OK;
4839}
4840
4841/*
4842** Erase the given database page and all its children. Return
4843** the page to the freelist.
4844*/
drh4b70f112004-05-02 21:12:19 +00004845static int clearDatabasePage(
4846 Btree *pBt, /* The BTree that contains the table */
4847 Pgno pgno, /* Page number to clear */
4848 MemPage *pParent, /* Parent page. NULL for the root */
4849 int freePageFlag /* Deallocate page if true */
4850){
danielk19776b456a22005-03-21 04:04:02 +00004851 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00004852 int rc;
drh4b70f112004-05-02 21:12:19 +00004853 unsigned char *pCell;
4854 int i;
drh8b2f49b2001-06-08 00:21:52 +00004855
danielk1977a1cb1832005-02-12 08:59:55 +00004856 if( pgno>sqlite3pager_pagecount(pBt->pPager) ){
4857 return SQLITE_CORRUPT;
4858 }
4859
drhde647132004-05-07 17:57:49 +00004860 rc = getAndInitPage(pBt, pgno, &pPage, pParent);
danielk19776b456a22005-03-21 04:04:02 +00004861 if( rc ) goto cleardatabasepage_out;
drha34b6762004-05-07 13:30:42 +00004862 rc = sqlite3pager_write(pPage->aData);
danielk19776b456a22005-03-21 04:04:02 +00004863 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00004864 for(i=0; i<pPage->nCell; i++){
drh43605152004-05-29 21:46:49 +00004865 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00004866 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004867 rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00004868 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00004869 }
drh4b70f112004-05-02 21:12:19 +00004870 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00004871 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00004872 }
drha34b6762004-05-07 13:30:42 +00004873 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004874 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00004875 if( rc ) goto cleardatabasepage_out;
drh2aa679f2001-06-25 02:11:07 +00004876 }
4877 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00004878 rc = freePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00004879 }else{
drh3a4c1412004-05-09 20:40:11 +00004880 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00004881 }
danielk19776b456a22005-03-21 04:04:02 +00004882
4883cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00004884 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00004885 return rc;
drh8b2f49b2001-06-08 00:21:52 +00004886}
4887
4888/*
drhab01f612004-05-22 02:55:23 +00004889** Delete all information from a single table in the database. iTable is
4890** the page number of the root of the table. After this routine returns,
4891** the root page is empty, but still exists.
4892**
4893** This routine will fail with SQLITE_LOCKED if there are any open
4894** read cursors on the table. Open write cursors are moved to the
4895** root of the table.
drh8b2f49b2001-06-08 00:21:52 +00004896*/
drh3aac2dd2004-04-26 14:10:20 +00004897int sqlite3BtreeClearTable(Btree *pBt, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00004898 int rc;
drhf74b8d92002-09-01 23:20:45 +00004899 BtCursor *pCur;
danielk1977ee5741e2004-05-31 10:01:34 +00004900 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00004901 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00004902 }
drhf74b8d92002-09-01 23:20:45 +00004903 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
4904 if( pCur->pgnoRoot==(Pgno)iTable ){
4905 if( pCur->wrFlag==0 ) return SQLITE_LOCKED;
4906 moveToRoot(pCur);
4907 }
drhecdc7532001-09-23 02:35:53 +00004908 }
drha34b6762004-05-07 13:30:42 +00004909 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
drh8b2f49b2001-06-08 00:21:52 +00004910 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00004911 sqlite3BtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00004912 }
drh8c42ca92001-06-22 19:15:00 +00004913 return rc;
drh8b2f49b2001-06-08 00:21:52 +00004914}
4915
4916/*
4917** Erase all information in a table and add the root of the table to
4918** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00004919** page 1) is never added to the freelist.
4920**
4921** This routine will fail with SQLITE_LOCKED if there are any open
4922** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00004923**
4924** If AUTOVACUUM is enabled and the page at iTable is not the last
4925** root page in the database file, then the last root page
4926** in the database file is moved into the slot formerly occupied by
4927** iTable and that last slot formerly occupied by the last root page
4928** is added to the freelist instead of iTable. In this say, all
4929** root pages are kept at the beginning of the database file, which
4930** is necessary for AUTOVACUUM to work right. *piMoved is set to the
4931** page number that used to be the last root page in the file before
4932** the move. If no page gets moved, *piMoved is set to 0.
4933** The last root page is recorded in meta[3] and the value of
4934** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00004935*/
danielk1977a0bf2652004-11-04 14:30:04 +00004936int sqlite3BtreeDropTable(Btree *pBt, int iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00004937 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00004938 MemPage *pPage = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00004939
danielk1977ee5741e2004-05-31 10:01:34 +00004940 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00004941 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00004942 }
danielk1977a0bf2652004-11-04 14:30:04 +00004943
danielk1977e6efa742004-11-10 11:55:10 +00004944 /* It is illegal to drop a table if any cursors are open on the
4945 ** database. This is because in auto-vacuum mode the backend may
4946 ** need to move another root-page to fill a gap left by the deleted
4947 ** root page. If an open cursor was using this page a problem would
4948 ** occur.
4949 */
4950 if( pBt->pCursor ){
4951 return SQLITE_LOCKED;
drh5df72a52002-06-06 23:16:05 +00004952 }
danielk1977a0bf2652004-11-04 14:30:04 +00004953
drha34b6762004-05-07 13:30:42 +00004954 rc = getPage(pBt, (Pgno)iTable, &pPage);
drh2aa679f2001-06-25 02:11:07 +00004955 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004956 rc = sqlite3BtreeClearTable(pBt, iTable);
danielk19776b456a22005-03-21 04:04:02 +00004957 if( rc ){
4958 releasePage(pPage);
4959 return rc;
4960 }
danielk1977a0bf2652004-11-04 14:30:04 +00004961
drh205f48e2004-11-05 00:43:11 +00004962 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00004963
drh4b70f112004-05-02 21:12:19 +00004964 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00004965#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00004966 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00004967 releasePage(pPage);
4968#else
4969 if( pBt->autoVacuum ){
4970 Pgno maxRootPgno;
4971 rc = sqlite3BtreeGetMeta(pBt, 4, &maxRootPgno);
4972 if( rc!=SQLITE_OK ){
4973 releasePage(pPage);
4974 return rc;
4975 }
4976
4977 if( iTable==maxRootPgno ){
4978 /* If the table being dropped is the table with the largest root-page
4979 ** number in the database, put the root page on the free list.
4980 */
4981 rc = freePage(pPage);
4982 releasePage(pPage);
4983 if( rc!=SQLITE_OK ){
4984 return rc;
4985 }
4986 }else{
4987 /* The table being dropped does not have the largest root-page
4988 ** number in the database. So move the page that does into the
4989 ** gap left by the deleted root-page.
4990 */
4991 MemPage *pMove;
4992 releasePage(pPage);
4993 rc = getPage(pBt, maxRootPgno, &pMove);
4994 if( rc!=SQLITE_OK ){
4995 return rc;
4996 }
4997 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable);
4998 releasePage(pMove);
4999 if( rc!=SQLITE_OK ){
5000 return rc;
5001 }
5002 rc = getPage(pBt, maxRootPgno, &pMove);
5003 if( rc!=SQLITE_OK ){
5004 return rc;
5005 }
5006 rc = freePage(pMove);
5007 releasePage(pMove);
5008 if( rc!=SQLITE_OK ){
5009 return rc;
5010 }
5011 *piMoved = maxRootPgno;
5012 }
5013
danielk1977599fcba2004-11-08 07:13:13 +00005014 /* Set the new 'max-root-page' value in the database header. This
5015 ** is the old value less one, less one more if that happens to
5016 ** be a root-page number, less one again if that is the
5017 ** PENDING_BYTE_PAGE.
5018 */
danielk197787a6e732004-11-05 12:58:25 +00005019 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00005020 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
5021 maxRootPgno--;
5022 }
drh42cac6d2004-11-20 20:31:11 +00005023 if( maxRootPgno==PTRMAP_PAGENO(pBt->usableSize, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00005024 maxRootPgno--;
5025 }
danielk1977599fcba2004-11-08 07:13:13 +00005026 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
5027
danielk197787a6e732004-11-05 12:58:25 +00005028 rc = sqlite3BtreeUpdateMeta(pBt, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00005029 }else{
5030 rc = freePage(pPage);
5031 releasePage(pPage);
5032 }
5033#endif
drh2aa679f2001-06-25 02:11:07 +00005034 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00005035 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00005036 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00005037 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00005038 }
drh8b2f49b2001-06-08 00:21:52 +00005039 return rc;
5040}
5041
drh001bbcb2003-03-19 03:14:00 +00005042
drh8b2f49b2001-06-08 00:21:52 +00005043/*
drh23e11ca2004-05-04 17:27:28 +00005044** Read the meta-information out of a database file. Meta[0]
5045** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00005046** through meta[15] are available for use by higher layers. Meta[0]
5047** is read-only, the others are read/write.
5048**
5049** The schema layer numbers meta values differently. At the schema
5050** layer (and the SetCookie and ReadCookie opcodes) the number of
5051** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00005052*/
drh3aac2dd2004-04-26 14:10:20 +00005053int sqlite3BtreeGetMeta(Btree *pBt, int idx, u32 *pMeta){
drh8b2f49b2001-06-08 00:21:52 +00005054 int rc;
drh4b70f112004-05-02 21:12:19 +00005055 unsigned char *pP1;
drh8b2f49b2001-06-08 00:21:52 +00005056
drh23e11ca2004-05-04 17:27:28 +00005057 assert( idx>=0 && idx<=15 );
drha34b6762004-05-07 13:30:42 +00005058 rc = sqlite3pager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00005059 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00005060 *pMeta = get4byte(&pP1[36 + idx*4]);
drha34b6762004-05-07 13:30:42 +00005061 sqlite3pager_unref(pP1);
drhae157872004-08-14 19:20:09 +00005062
danielk1977599fcba2004-11-08 07:13:13 +00005063 /* If autovacuumed is disabled in this build but we are trying to
5064 ** access an autovacuumed database, then make the database readonly.
5065 */
danielk1977003ba062004-11-04 02:57:33 +00005066#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00005067 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00005068#endif
drhae157872004-08-14 19:20:09 +00005069
drh8b2f49b2001-06-08 00:21:52 +00005070 return SQLITE_OK;
5071}
5072
5073/*
drh23e11ca2004-05-04 17:27:28 +00005074** Write meta-information back into the database. Meta[0] is
5075** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00005076*/
drh3aac2dd2004-04-26 14:10:20 +00005077int sqlite3BtreeUpdateMeta(Btree *pBt, int idx, u32 iMeta){
drh4b70f112004-05-02 21:12:19 +00005078 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00005079 int rc;
drh23e11ca2004-05-04 17:27:28 +00005080 assert( idx>=1 && idx<=15 );
danielk1977ee5741e2004-05-31 10:01:34 +00005081 if( pBt->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005082 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +00005083 }
drhde647132004-05-07 17:57:49 +00005084 assert( pBt->pPage1!=0 );
5085 pP1 = pBt->pPage1->aData;
drha34b6762004-05-07 13:30:42 +00005086 rc = sqlite3pager_write(pP1);
drh4b70f112004-05-02 21:12:19 +00005087 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00005088 put4byte(&pP1[36 + idx*4], iMeta);
drh8b2f49b2001-06-08 00:21:52 +00005089 return SQLITE_OK;
5090}
drh8c42ca92001-06-22 19:15:00 +00005091
drhf328bc82004-05-10 23:29:49 +00005092/*
5093** Return the flag byte at the beginning of the page that the cursor
5094** is currently pointing to.
5095*/
5096int sqlite3BtreeFlags(BtCursor *pCur){
5097 MemPage *pPage = pCur->pPage;
5098 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
5099}
5100
danielk1977b5402fb2005-01-12 07:15:04 +00005101#ifdef SQLITE_DEBUG
drh8c42ca92001-06-22 19:15:00 +00005102/*
5103** Print a disassembly of the given page on standard output. This routine
5104** is used for debugging and testing only.
5105*/
danielk1977c7dc7532004-11-17 10:22:03 +00005106static int btreePageDump(Btree *pBt, int pgno, int recursive, MemPage *pParent){
drh8c42ca92001-06-22 19:15:00 +00005107 int rc;
5108 MemPage *pPage;
drhc8629a12004-05-08 20:07:40 +00005109 int i, j, c;
drh8c42ca92001-06-22 19:15:00 +00005110 int nFree;
5111 u16 idx;
drhab9f7f12004-05-08 10:56:11 +00005112 int hdr;
drh43605152004-05-29 21:46:49 +00005113 int nCell;
drha2fce642004-06-05 00:01:44 +00005114 int isInit;
drhab9f7f12004-05-08 10:56:11 +00005115 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00005116 char range[20];
5117 unsigned char payload[20];
drhab9f7f12004-05-08 10:56:11 +00005118
drh4b70f112004-05-02 21:12:19 +00005119 rc = getPage(pBt, (Pgno)pgno, &pPage);
drha2fce642004-06-05 00:01:44 +00005120 isInit = pPage->isInit;
5121 if( pPage->isInit==0 ){
danielk1977c7dc7532004-11-17 10:22:03 +00005122 initPage(pPage, pParent);
drha2fce642004-06-05 00:01:44 +00005123 }
drh8c42ca92001-06-22 19:15:00 +00005124 if( rc ){
5125 return rc;
5126 }
drhab9f7f12004-05-08 10:56:11 +00005127 hdr = pPage->hdrOffset;
5128 data = pPage->aData;
drhc8629a12004-05-08 20:07:40 +00005129 c = data[hdr];
drh8b18dd42004-05-12 19:18:15 +00005130 pPage->intKey = (c & (PTF_INTKEY|PTF_LEAFDATA))!=0;
drhc8629a12004-05-08 20:07:40 +00005131 pPage->zeroData = (c & PTF_ZERODATA)!=0;
drh8b18dd42004-05-12 19:18:15 +00005132 pPage->leafData = (c & PTF_LEAFDATA)!=0;
drhc8629a12004-05-08 20:07:40 +00005133 pPage->leaf = (c & PTF_LEAF)!=0;
drh8b18dd42004-05-12 19:18:15 +00005134 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
drh43605152004-05-29 21:46:49 +00005135 nCell = get2byte(&data[hdr+3]);
drhfe63d1c2004-09-08 20:13:04 +00005136 sqlite3DebugPrintf("PAGE %d: flags=0x%02x frag=%d parent=%d\n", pgno,
drh43605152004-05-29 21:46:49 +00005137 data[hdr], data[hdr+7],
drhda200cc2004-05-09 11:51:38 +00005138 (pPage->isInit && pPage->pParent) ? pPage->pParent->pgno : 0);
drhab9f7f12004-05-08 10:56:11 +00005139 assert( hdr == (pgno==1 ? 100 : 0) );
drh43605152004-05-29 21:46:49 +00005140 idx = hdr + 12 - pPage->leaf*4;
5141 for(i=0; i<nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00005142 CellInfo info;
drh4b70f112004-05-02 21:12:19 +00005143 Pgno child;
drh43605152004-05-29 21:46:49 +00005144 unsigned char *pCell;
drh6f11bef2004-05-13 01:12:56 +00005145 int sz;
drh43605152004-05-29 21:46:49 +00005146 int addr;
drh6f11bef2004-05-13 01:12:56 +00005147
drh43605152004-05-29 21:46:49 +00005148 addr = get2byte(&data[idx + 2*i]);
5149 pCell = &data[addr];
5150 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005151 sz = info.nSize;
drh43605152004-05-29 21:46:49 +00005152 sprintf(range,"%d..%d", addr, addr+sz-1);
drh4b70f112004-05-02 21:12:19 +00005153 if( pPage->leaf ){
5154 child = 0;
5155 }else{
drh43605152004-05-29 21:46:49 +00005156 child = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005157 }
drh6f11bef2004-05-13 01:12:56 +00005158 sz = info.nData;
5159 if( !pPage->intKey ) sz += info.nKey;
drh8c42ca92001-06-22 19:15:00 +00005160 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
drh6f11bef2004-05-13 01:12:56 +00005161 memcpy(payload, &pCell[info.nHeader], sz);
drh8c42ca92001-06-22 19:15:00 +00005162 for(j=0; j<sz; j++){
5163 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
5164 }
5165 payload[sz] = 0;
drhfe63d1c2004-09-08 20:13:04 +00005166 sqlite3DebugPrintf(
drh6f11bef2004-05-13 01:12:56 +00005167 "cell %2d: i=%-10s chld=%-4d nk=%-4lld nd=%-4d payload=%s\n",
5168 i, range, child, info.nKey, info.nData, payload
drh8c42ca92001-06-22 19:15:00 +00005169 );
drh8c42ca92001-06-22 19:15:00 +00005170 }
drh4b70f112004-05-02 21:12:19 +00005171 if( !pPage->leaf ){
drhfe63d1c2004-09-08 20:13:04 +00005172 sqlite3DebugPrintf("right_child: %d\n", get4byte(&data[hdr+8]));
drh4b70f112004-05-02 21:12:19 +00005173 }
drh8c42ca92001-06-22 19:15:00 +00005174 nFree = 0;
5175 i = 0;
drhab9f7f12004-05-08 10:56:11 +00005176 idx = get2byte(&data[hdr+1]);
drhb6f41482004-05-14 01:58:11 +00005177 while( idx>0 && idx<pPage->pBt->usableSize ){
drhab9f7f12004-05-08 10:56:11 +00005178 int sz = get2byte(&data[idx+2]);
drh4b70f112004-05-02 21:12:19 +00005179 sprintf(range,"%d..%d", idx, idx+sz-1);
5180 nFree += sz;
drhfe63d1c2004-09-08 20:13:04 +00005181 sqlite3DebugPrintf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
drh4b70f112004-05-02 21:12:19 +00005182 i, range, sz, nFree);
drhab9f7f12004-05-08 10:56:11 +00005183 idx = get2byte(&data[idx]);
drh2aa679f2001-06-25 02:11:07 +00005184 i++;
drh8c42ca92001-06-22 19:15:00 +00005185 }
5186 if( idx!=0 ){
drhfe63d1c2004-09-08 20:13:04 +00005187 sqlite3DebugPrintf("ERROR: next freeblock index out of range: %d\n", idx);
drh8c42ca92001-06-22 19:15:00 +00005188 }
drha34b6762004-05-07 13:30:42 +00005189 if( recursive && !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005190 for(i=0; i<nCell; i++){
5191 unsigned char *pCell = findCell(pPage, i);
danielk1977c7dc7532004-11-17 10:22:03 +00005192 btreePageDump(pBt, get4byte(pCell), 1, pPage);
drha34b6762004-05-07 13:30:42 +00005193 idx = get2byte(pCell);
drh6019e162001-07-02 17:51:45 +00005194 }
danielk1977c7dc7532004-11-17 10:22:03 +00005195 btreePageDump(pBt, get4byte(&data[hdr+8]), 1, pPage);
drh6019e162001-07-02 17:51:45 +00005196 }
drha2fce642004-06-05 00:01:44 +00005197 pPage->isInit = isInit;
drhab9f7f12004-05-08 10:56:11 +00005198 sqlite3pager_unref(data);
drh3644f082004-05-10 18:45:09 +00005199 fflush(stdout);
drh8c42ca92001-06-22 19:15:00 +00005200 return SQLITE_OK;
5201}
danielk1977c7dc7532004-11-17 10:22:03 +00005202int sqlite3BtreePageDump(Btree *pBt, int pgno, int recursive){
5203 return btreePageDump(pBt, pgno, recursive, 0);
5204}
drhaaab5722002-02-19 13:39:21 +00005205#endif
drh8c42ca92001-06-22 19:15:00 +00005206
drhaaab5722002-02-19 13:39:21 +00005207#ifdef SQLITE_TEST
drh8c42ca92001-06-22 19:15:00 +00005208/*
drh2aa679f2001-06-25 02:11:07 +00005209** Fill aResult[] with information about the entry and page that the
5210** cursor is pointing to.
5211**
5212** aResult[0] = The page number
5213** aResult[1] = The entry number
5214** aResult[2] = Total number of entries on this page
drh3e27c022004-07-23 00:01:38 +00005215** aResult[3] = Cell size (local payload + header)
drh2aa679f2001-06-25 02:11:07 +00005216** aResult[4] = Number of free bytes on this page
5217** aResult[5] = Number of free blocks on the page
drh3e27c022004-07-23 00:01:38 +00005218** aResult[6] = Total payload size (local + overflow)
5219** aResult[7] = Header size in bytes
5220** aResult[8] = Local payload size
5221** aResult[9] = Parent page number
drh5eddca62001-06-30 21:53:53 +00005222**
5223** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00005224*/
drh3e27c022004-07-23 00:01:38 +00005225int sqlite3BtreeCursorInfo(BtCursor *pCur, int *aResult, int upCnt){
drh2aa679f2001-06-25 02:11:07 +00005226 int cnt, idx;
5227 MemPage *pPage = pCur->pPage;
drh3e27c022004-07-23 00:01:38 +00005228 BtCursor tmpCur;
drhda200cc2004-05-09 11:51:38 +00005229
5230 pageIntegrity(pPage);
drh4b70f112004-05-02 21:12:19 +00005231 assert( pPage->isInit );
drh3e27c022004-07-23 00:01:38 +00005232 getTempCursor(pCur, &tmpCur);
5233 while( upCnt-- ){
5234 moveToParent(&tmpCur);
5235 }
5236 pPage = tmpCur.pPage;
5237 pageIntegrity(pPage);
drha34b6762004-05-07 13:30:42 +00005238 aResult[0] = sqlite3pager_pagenumber(pPage->aData);
drh91025292004-05-03 19:49:32 +00005239 assert( aResult[0]==pPage->pgno );
drh3e27c022004-07-23 00:01:38 +00005240 aResult[1] = tmpCur.idx;
drh2aa679f2001-06-25 02:11:07 +00005241 aResult[2] = pPage->nCell;
drh3e27c022004-07-23 00:01:38 +00005242 if( tmpCur.idx>=0 && tmpCur.idx<pPage->nCell ){
5243 getCellInfo(&tmpCur);
5244 aResult[3] = tmpCur.info.nSize;
5245 aResult[6] = tmpCur.info.nData;
5246 aResult[7] = tmpCur.info.nHeader;
5247 aResult[8] = tmpCur.info.nLocal;
drh2aa679f2001-06-25 02:11:07 +00005248 }else{
5249 aResult[3] = 0;
5250 aResult[6] = 0;
drh3e27c022004-07-23 00:01:38 +00005251 aResult[7] = 0;
5252 aResult[8] = 0;
drh2aa679f2001-06-25 02:11:07 +00005253 }
5254 aResult[4] = pPage->nFree;
5255 cnt = 0;
drh4b70f112004-05-02 21:12:19 +00005256 idx = get2byte(&pPage->aData[pPage->hdrOffset+1]);
drhb6f41482004-05-14 01:58:11 +00005257 while( idx>0 && idx<pPage->pBt->usableSize ){
drh2aa679f2001-06-25 02:11:07 +00005258 cnt++;
drh4b70f112004-05-02 21:12:19 +00005259 idx = get2byte(&pPage->aData[idx]);
drh2aa679f2001-06-25 02:11:07 +00005260 }
5261 aResult[5] = cnt;
drh3e27c022004-07-23 00:01:38 +00005262 if( pPage->pParent==0 || isRootPage(pPage) ){
5263 aResult[9] = 0;
5264 }else{
5265 aResult[9] = pPage->pParent->pgno;
5266 }
5267 releaseTempCursor(&tmpCur);
drh8c42ca92001-06-22 19:15:00 +00005268 return SQLITE_OK;
5269}
drhaaab5722002-02-19 13:39:21 +00005270#endif
drhdd793422001-06-28 01:54:48 +00005271
drhdd793422001-06-28 01:54:48 +00005272/*
drh5eddca62001-06-30 21:53:53 +00005273** Return the pager associated with a BTree. This routine is used for
5274** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00005275*/
drh3aac2dd2004-04-26 14:10:20 +00005276Pager *sqlite3BtreePager(Btree *pBt){
drhdd793422001-06-28 01:54:48 +00005277 return pBt->pPager;
5278}
drh5eddca62001-06-30 21:53:53 +00005279
5280/*
5281** This structure is passed around through all the sanity checking routines
5282** in order to keep track of some global state information.
5283*/
drhaaab5722002-02-19 13:39:21 +00005284typedef struct IntegrityCk IntegrityCk;
5285struct IntegrityCk {
drh100569d2001-10-02 13:01:48 +00005286 Btree *pBt; /* The tree being checked out */
5287 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
5288 int nPage; /* Number of pages in the database */
5289 int *anRef; /* Number of times each page is referenced */
drh100569d2001-10-02 13:01:48 +00005290 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00005291};
5292
drhb7f91642004-10-31 02:22:47 +00005293#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005294/*
5295** Append a message to the error message string.
5296*/
drh2e38c322004-09-03 18:38:44 +00005297static void checkAppendMsg(
5298 IntegrityCk *pCheck,
5299 char *zMsg1,
5300 const char *zFormat,
5301 ...
5302){
5303 va_list ap;
5304 char *zMsg2;
5305 va_start(ap, zFormat);
5306 zMsg2 = sqlite3VMPrintf(zFormat, ap);
5307 va_end(ap);
5308 if( zMsg1==0 ) zMsg1 = "";
drh5eddca62001-06-30 21:53:53 +00005309 if( pCheck->zErrMsg ){
5310 char *zOld = pCheck->zErrMsg;
5311 pCheck->zErrMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00005312 sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00005313 sqliteFree(zOld);
5314 }else{
danielk19774adee202004-05-08 08:23:19 +00005315 sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00005316 }
drh2e38c322004-09-03 18:38:44 +00005317 sqliteFree(zMsg2);
drh5eddca62001-06-30 21:53:53 +00005318}
drhb7f91642004-10-31 02:22:47 +00005319#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005320
drhb7f91642004-10-31 02:22:47 +00005321#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005322/*
5323** Add 1 to the reference count for page iPage. If this is the second
5324** reference to the page, add an error message to pCheck->zErrMsg.
5325** Return 1 if there are 2 ore more references to the page and 0 if
5326** if this is the first reference to the page.
5327**
5328** Also check that the page number is in bounds.
5329*/
drhaaab5722002-02-19 13:39:21 +00005330static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00005331 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00005332 if( iPage>pCheck->nPage || iPage<0 ){
drh2e38c322004-09-03 18:38:44 +00005333 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005334 return 1;
5335 }
5336 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00005337 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005338 return 1;
5339 }
5340 return (pCheck->anRef[iPage]++)>1;
5341}
5342
danielk1977afcdd022004-10-31 16:25:42 +00005343#ifndef SQLITE_OMIT_AUTOVACUUM
5344/*
5345** Check that the entry in the pointer-map for page iChild maps to
5346** page iParent, pointer type ptrType. If not, append an error message
5347** to pCheck.
5348*/
5349static void checkPtrmap(
5350 IntegrityCk *pCheck, /* Integrity check context */
5351 Pgno iChild, /* Child page number */
5352 u8 eType, /* Expected pointer map type */
5353 Pgno iParent, /* Expected pointer map parent page number */
5354 char *zContext /* Context description (used for error msg) */
5355){
5356 int rc;
5357 u8 ePtrmapType;
5358 Pgno iPtrmapParent;
5359
5360 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
5361 if( rc!=SQLITE_OK ){
5362 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
5363 return;
5364 }
5365
5366 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
5367 checkAppendMsg(pCheck, zContext,
5368 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
5369 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
5370 }
5371}
5372#endif
5373
drh5eddca62001-06-30 21:53:53 +00005374/*
5375** Check the integrity of the freelist or of an overflow page list.
5376** Verify that the number of pages on the list is N.
5377*/
drh30e58752002-03-02 20:41:57 +00005378static void checkList(
5379 IntegrityCk *pCheck, /* Integrity checking context */
5380 int isFreeList, /* True for a freelist. False for overflow page list */
5381 int iPage, /* Page number for first page in the list */
5382 int N, /* Expected number of pages in the list */
5383 char *zContext /* Context for error messages */
5384){
5385 int i;
drh3a4c1412004-05-09 20:40:11 +00005386 int expected = N;
5387 int iFirst = iPage;
drh30e58752002-03-02 20:41:57 +00005388 while( N-- > 0 ){
drh4b70f112004-05-02 21:12:19 +00005389 unsigned char *pOvfl;
drh5eddca62001-06-30 21:53:53 +00005390 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00005391 checkAppendMsg(pCheck, zContext,
5392 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00005393 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00005394 break;
5395 }
5396 if( checkRef(pCheck, iPage, zContext) ) break;
drha34b6762004-05-07 13:30:42 +00005397 if( sqlite3pager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
drh2e38c322004-09-03 18:38:44 +00005398 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005399 break;
5400 }
drh30e58752002-03-02 20:41:57 +00005401 if( isFreeList ){
drh4b70f112004-05-02 21:12:19 +00005402 int n = get4byte(&pOvfl[4]);
danielk1977687566d2004-11-02 12:56:41 +00005403#ifndef SQLITE_OMIT_AUTOVACUUM
5404 if( pCheck->pBt->autoVacuum ){
5405 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
5406 }
5407#endif
drh855eb1c2004-08-31 13:45:11 +00005408 if( n>pCheck->pBt->usableSize/4-8 ){
drh2e38c322004-09-03 18:38:44 +00005409 checkAppendMsg(pCheck, zContext,
5410 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00005411 N--;
5412 }else{
5413 for(i=0; i<n; i++){
danielk1977687566d2004-11-02 12:56:41 +00005414 Pgno iFreePage = get4byte(&pOvfl[8+i*4]);
5415#ifndef SQLITE_OMIT_AUTOVACUUM
5416 if( pCheck->pBt->autoVacuum ){
5417 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
5418 }
5419#endif
5420 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00005421 }
5422 N -= n;
drh30e58752002-03-02 20:41:57 +00005423 }
drh30e58752002-03-02 20:41:57 +00005424 }
danielk1977afcdd022004-10-31 16:25:42 +00005425#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00005426 else{
5427 /* If this database supports auto-vacuum and iPage is not the last
5428 ** page in this overflow list, check that the pointer-map entry for
5429 ** the following page matches iPage.
5430 */
5431 if( pCheck->pBt->autoVacuum && N>0 ){
5432 i = get4byte(pOvfl);
5433 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
5434 }
danielk1977afcdd022004-10-31 16:25:42 +00005435 }
5436#endif
drh4b70f112004-05-02 21:12:19 +00005437 iPage = get4byte(pOvfl);
drha34b6762004-05-07 13:30:42 +00005438 sqlite3pager_unref(pOvfl);
drh5eddca62001-06-30 21:53:53 +00005439 }
5440}
drhb7f91642004-10-31 02:22:47 +00005441#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005442
drhb7f91642004-10-31 02:22:47 +00005443#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005444/*
5445** Do various sanity checks on a single page of a tree. Return
5446** the tree depth. Root pages return 0. Parents of root pages
5447** return 1, and so forth.
5448**
5449** These checks are done:
5450**
5451** 1. Make sure that cells and freeblocks do not overlap
5452** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00005453** NO 2. Make sure cell keys are in order.
5454** NO 3. Make sure no key is less than or equal to zLowerBound.
5455** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00005456** 5. Check the integrity of overflow pages.
5457** 6. Recursively call checkTreePage on all children.
5458** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00005459** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00005460** the root of the tree.
5461*/
5462static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00005463 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00005464 int iPage, /* Page number of the page to check */
5465 MemPage *pParent, /* Parent page */
5466 char *zParentContext, /* Parent context */
5467 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00005468 int nLower, /* Number of characters in zLowerBound */
5469 char *zUpperBound, /* All keys should be less than this, if not NULL */
5470 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00005471){
5472 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00005473 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00005474 int hdr, cellStart;
5475 int nCell;
drhda200cc2004-05-09 11:51:38 +00005476 u8 *data;
drh5eddca62001-06-30 21:53:53 +00005477 BtCursor cur;
drh0d316a42002-08-11 20:10:47 +00005478 Btree *pBt;
drh4f26bb62005-09-08 14:17:20 +00005479 int usableSize;
drh5eddca62001-06-30 21:53:53 +00005480 char zContext[100];
drh2e38c322004-09-03 18:38:44 +00005481 char *hit;
drh5eddca62001-06-30 21:53:53 +00005482
danielk1977ef73ee92004-11-06 12:26:07 +00005483 sprintf(zContext, "Page %d: ", iPage);
5484
drh5eddca62001-06-30 21:53:53 +00005485 /* Check that the page exists
5486 */
drh0d316a42002-08-11 20:10:47 +00005487 cur.pBt = pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00005488 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00005489 if( iPage==0 ) return 0;
5490 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh4b70f112004-05-02 21:12:19 +00005491 if( (rc = getPage(pBt, (Pgno)iPage, &pPage))!=0 ){
drh2e38c322004-09-03 18:38:44 +00005492 checkAppendMsg(pCheck, zContext,
5493 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00005494 return 0;
5495 }
drh4b70f112004-05-02 21:12:19 +00005496 if( (rc = initPage(pPage, pParent))!=0 ){
drh2e38c322004-09-03 18:38:44 +00005497 checkAppendMsg(pCheck, zContext, "initPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00005498 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00005499 return 0;
5500 }
5501
5502 /* Check out all the cells.
5503 */
5504 depth = 0;
drh5eddca62001-06-30 21:53:53 +00005505 cur.pPage = pPage;
drh5eddca62001-06-30 21:53:53 +00005506 for(i=0; i<pPage->nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00005507 u8 *pCell;
5508 int sz;
5509 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00005510
5511 /* Check payload overflow pages
5512 */
drh3a4c1412004-05-09 20:40:11 +00005513 sprintf(zContext, "On tree page %d cell %d: ", iPage, i);
drh43605152004-05-29 21:46:49 +00005514 pCell = findCell(pPage,i);
5515 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005516 sz = info.nData;
5517 if( !pPage->intKey ) sz += info.nKey;
5518 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00005519 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00005520 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
5521#ifndef SQLITE_OMIT_AUTOVACUUM
5522 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00005523 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00005524 }
5525#endif
5526 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00005527 }
5528
5529 /* Check sanity of left child page.
5530 */
drhda200cc2004-05-09 11:51:38 +00005531 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005532 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00005533#ifndef SQLITE_OMIT_AUTOVACUUM
5534 if( pBt->autoVacuum ){
5535 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
5536 }
5537#endif
drhda200cc2004-05-09 11:51:38 +00005538 d2 = checkTreePage(pCheck,pgno,pPage,zContext,0,0,0,0);
5539 if( i>0 && d2!=depth ){
5540 checkAppendMsg(pCheck, zContext, "Child page depth differs");
5541 }
5542 depth = d2;
drh5eddca62001-06-30 21:53:53 +00005543 }
drh5eddca62001-06-30 21:53:53 +00005544 }
drhda200cc2004-05-09 11:51:38 +00005545 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005546 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drhda200cc2004-05-09 11:51:38 +00005547 sprintf(zContext, "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00005548#ifndef SQLITE_OMIT_AUTOVACUUM
5549 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00005550 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00005551 }
5552#endif
drhda200cc2004-05-09 11:51:38 +00005553 checkTreePage(pCheck, pgno, pPage, zContext,0,0,0,0);
5554 }
drh5eddca62001-06-30 21:53:53 +00005555
5556 /* Check for complete coverage of the page
5557 */
drhda200cc2004-05-09 11:51:38 +00005558 data = pPage->aData;
5559 hdr = pPage->hdrOffset;
drh2e38c322004-09-03 18:38:44 +00005560 hit = sqliteMalloc( usableSize );
5561 if( hit ){
5562 memset(hit, 1, get2byte(&data[hdr+5]));
5563 nCell = get2byte(&data[hdr+3]);
5564 cellStart = hdr + 12 - 4*pPage->leaf;
5565 for(i=0; i<nCell; i++){
5566 int pc = get2byte(&data[cellStart+i*2]);
5567 int size = cellSizePtr(pPage, &data[pc]);
5568 int j;
danielk19777701e812005-01-10 12:59:51 +00005569 if( (pc+size-1)>=usableSize || pc<0 ){
5570 checkAppendMsg(pCheck, 0,
5571 "Corruption detected in cell %d on page %d",i,iPage,0);
5572 }else{
5573 for(j=pc+size-1; j>=pc; j--) hit[j]++;
5574 }
drh2e38c322004-09-03 18:38:44 +00005575 }
5576 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
5577 cnt++){
5578 int size = get2byte(&data[i+2]);
5579 int j;
danielk19777701e812005-01-10 12:59:51 +00005580 if( (i+size-1)>=usableSize || i<0 ){
5581 checkAppendMsg(pCheck, 0,
5582 "Corruption detected in cell %d on page %d",i,iPage,0);
5583 }else{
5584 for(j=i+size-1; j>=i; j--) hit[j]++;
5585 }
drh2e38c322004-09-03 18:38:44 +00005586 i = get2byte(&data[i]);
5587 }
5588 for(i=cnt=0; i<usableSize; i++){
5589 if( hit[i]==0 ){
5590 cnt++;
5591 }else if( hit[i]>1 ){
5592 checkAppendMsg(pCheck, 0,
5593 "Multiple uses for byte %d of page %d", i, iPage);
5594 break;
5595 }
5596 }
5597 if( cnt!=data[hdr+7] ){
5598 checkAppendMsg(pCheck, 0,
5599 "Fragmented space is %d byte reported as %d on page %d",
5600 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00005601 }
5602 }
drh2e38c322004-09-03 18:38:44 +00005603 sqliteFree(hit);
drh6019e162001-07-02 17:51:45 +00005604
drh4b70f112004-05-02 21:12:19 +00005605 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00005606 return depth+1;
drh5eddca62001-06-30 21:53:53 +00005607}
drhb7f91642004-10-31 02:22:47 +00005608#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005609
drhb7f91642004-10-31 02:22:47 +00005610#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005611/*
5612** This routine does a complete check of the given BTree file. aRoot[] is
5613** an array of pages numbers were each page number is the root page of
5614** a table. nRoot is the number of entries in aRoot.
5615**
5616** If everything checks out, this routine returns NULL. If something is
5617** amiss, an error message is written into memory obtained from malloc()
5618** and a pointer to that error message is returned. The calling function
5619** is responsible for freeing the error message when it is done.
5620*/
drh3aac2dd2004-04-26 14:10:20 +00005621char *sqlite3BtreeIntegrityCheck(Btree *pBt, int *aRoot, int nRoot){
drh5eddca62001-06-30 21:53:53 +00005622 int i;
5623 int nRef;
drhaaab5722002-02-19 13:39:21 +00005624 IntegrityCk sCheck;
drh5eddca62001-06-30 21:53:53 +00005625
drha34b6762004-05-07 13:30:42 +00005626 nRef = *sqlite3pager_stats(pBt->pPager);
drhb8ef32c2005-03-14 02:01:49 +00005627 if( lockBtreeWithRetry(pBt)!=SQLITE_OK ){
drhefc251d2001-07-01 22:12:01 +00005628 return sqliteStrDup("Unable to acquire a read lock on the database");
5629 }
drh5eddca62001-06-30 21:53:53 +00005630 sCheck.pBt = pBt;
5631 sCheck.pPager = pBt->pPager;
drha34b6762004-05-07 13:30:42 +00005632 sCheck.nPage = sqlite3pager_pagecount(sCheck.pPager);
drh0de8c112002-07-06 16:32:14 +00005633 if( sCheck.nPage==0 ){
5634 unlockBtreeIfUnused(pBt);
5635 return 0;
5636 }
drh8c1238a2003-01-02 14:43:55 +00005637 sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00005638 if( !sCheck.anRef ){
5639 unlockBtreeIfUnused(pBt);
5640 return sqlite3MPrintf("Unable to malloc %d bytes",
5641 (sCheck.nPage+1)*sizeof(sCheck.anRef[0]));
5642 }
drhda200cc2004-05-09 11:51:38 +00005643 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00005644 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00005645 if( i<=sCheck.nPage ){
5646 sCheck.anRef[i] = 1;
5647 }
drh5eddca62001-06-30 21:53:53 +00005648 sCheck.zErrMsg = 0;
5649
5650 /* Check the integrity of the freelist
5651 */
drha34b6762004-05-07 13:30:42 +00005652 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
5653 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00005654
5655 /* Check all the tables.
5656 */
5657 for(i=0; i<nRoot; i++){
drh4ff6dfa2002-03-03 23:06:00 +00005658 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00005659#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00005660 if( pBt->autoVacuum && aRoot[i]>1 ){
5661 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
5662 }
5663#endif
drh1bffb9c2002-02-03 17:37:36 +00005664 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00005665 }
5666
5667 /* Make sure every page in the file is referenced
5668 */
5669 for(i=1; i<=sCheck.nPage; i++){
danielk1977afcdd022004-10-31 16:25:42 +00005670#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00005671 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00005672 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00005673 }
danielk1977afcdd022004-10-31 16:25:42 +00005674#else
5675 /* If the database supports auto-vacuum, make sure no tables contain
5676 ** references to pointer-map pages.
5677 */
5678 if( sCheck.anRef[i]==0 &&
drh42cac6d2004-11-20 20:31:11 +00005679 (PTRMAP_PAGENO(pBt->usableSize, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00005680 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
5681 }
5682 if( sCheck.anRef[i]!=0 &&
drh42cac6d2004-11-20 20:31:11 +00005683 (PTRMAP_PAGENO(pBt->usableSize, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00005684 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
5685 }
5686#endif
drh5eddca62001-06-30 21:53:53 +00005687 }
5688
5689 /* Make sure this analysis did not leave any unref() pages
5690 */
drh5e00f6c2001-09-13 13:46:56 +00005691 unlockBtreeIfUnused(pBt);
drha34b6762004-05-07 13:30:42 +00005692 if( nRef != *sqlite3pager_stats(pBt->pPager) ){
drh2e38c322004-09-03 18:38:44 +00005693 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00005694 "Outstanding page count goes from %d to %d during this analysis",
drha34b6762004-05-07 13:30:42 +00005695 nRef, *sqlite3pager_stats(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00005696 );
drh5eddca62001-06-30 21:53:53 +00005697 }
5698
5699 /* Clean up and report errors.
5700 */
5701 sqliteFree(sCheck.anRef);
5702 return sCheck.zErrMsg;
5703}
drhb7f91642004-10-31 02:22:47 +00005704#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00005705
drh73509ee2003-04-06 20:44:45 +00005706/*
5707** Return the full pathname of the underlying database file.
5708*/
drh3aac2dd2004-04-26 14:10:20 +00005709const char *sqlite3BtreeGetFilename(Btree *pBt){
drh73509ee2003-04-06 20:44:45 +00005710 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00005711 return sqlite3pager_filename(pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00005712}
5713
5714/*
danielk19775865e3d2004-06-14 06:03:57 +00005715** Return the pathname of the directory that contains the database file.
5716*/
5717const char *sqlite3BtreeGetDirname(Btree *pBt){
5718 assert( pBt->pPager!=0 );
5719 return sqlite3pager_dirname(pBt->pPager);
5720}
5721
5722/*
5723** Return the pathname of the journal file for this database. The return
5724** value of this routine is the same regardless of whether the journal file
5725** has been created or not.
5726*/
5727const char *sqlite3BtreeGetJournalname(Btree *pBt){
5728 assert( pBt->pPager!=0 );
5729 return sqlite3pager_journalname(pBt->pPager);
5730}
5731
drhb7f91642004-10-31 02:22:47 +00005732#ifndef SQLITE_OMIT_VACUUM
danielk19775865e3d2004-06-14 06:03:57 +00005733/*
drhf7c57532003-04-25 13:22:51 +00005734** Copy the complete content of pBtFrom into pBtTo. A transaction
5735** must be active for both files.
5736**
5737** The size of file pBtFrom may be reduced by this operation.
drh43605152004-05-29 21:46:49 +00005738** If anything goes wrong, the transaction on pBtFrom is rolled back.
drh73509ee2003-04-06 20:44:45 +00005739*/
drh3aac2dd2004-04-26 14:10:20 +00005740int sqlite3BtreeCopyFile(Btree *pBtTo, Btree *pBtFrom){
drhf7c57532003-04-25 13:22:51 +00005741 int rc = SQLITE_OK;
drh2e6d11b2003-04-25 15:37:57 +00005742 Pgno i, nPage, nToPage;
drhf7c57532003-04-25 13:22:51 +00005743
danielk1977ee5741e2004-05-31 10:01:34 +00005744 if( pBtTo->inTrans!=TRANS_WRITE || pBtFrom->inTrans!=TRANS_WRITE ){
5745 return SQLITE_ERROR;
5746 }
drhf7c57532003-04-25 13:22:51 +00005747 if( pBtTo->pCursor ) return SQLITE_BUSY;
drha34b6762004-05-07 13:30:42 +00005748 nToPage = sqlite3pager_pagecount(pBtTo->pPager);
5749 nPage = sqlite3pager_pagecount(pBtFrom->pPager);
danielk1977369f27e2004-06-15 11:40:04 +00005750 for(i=1; rc==SQLITE_OK && i<=nPage; i++){
drhf7c57532003-04-25 13:22:51 +00005751 void *pPage;
drha34b6762004-05-07 13:30:42 +00005752 rc = sqlite3pager_get(pBtFrom->pPager, i, &pPage);
drhf7c57532003-04-25 13:22:51 +00005753 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00005754 rc = sqlite3pager_overwrite(pBtTo->pPager, i, pPage);
drh2e6d11b2003-04-25 15:37:57 +00005755 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00005756 sqlite3pager_unref(pPage);
drhf7c57532003-04-25 13:22:51 +00005757 }
drh2e6d11b2003-04-25 15:37:57 +00005758 for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
5759 void *pPage;
drha34b6762004-05-07 13:30:42 +00005760 rc = sqlite3pager_get(pBtTo->pPager, i, &pPage);
drh2e6d11b2003-04-25 15:37:57 +00005761 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00005762 rc = sqlite3pager_write(pPage);
5763 sqlite3pager_unref(pPage);
5764 sqlite3pager_dont_write(pBtTo->pPager, i);
drh2e6d11b2003-04-25 15:37:57 +00005765 }
5766 if( !rc && nPage<nToPage ){
drha34b6762004-05-07 13:30:42 +00005767 rc = sqlite3pager_truncate(pBtTo->pPager, nPage);
drh2e6d11b2003-04-25 15:37:57 +00005768 }
drhf7c57532003-04-25 13:22:51 +00005769 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00005770 sqlite3BtreeRollback(pBtTo);
drhf7c57532003-04-25 13:22:51 +00005771 }
5772 return rc;
drh73509ee2003-04-06 20:44:45 +00005773}
drhb7f91642004-10-31 02:22:47 +00005774#endif /* SQLITE_OMIT_VACUUM */
danielk19771d850a72004-05-31 08:26:49 +00005775
5776/*
5777** Return non-zero if a transaction is active.
5778*/
5779int sqlite3BtreeIsInTrans(Btree *pBt){
danielk1977ee5741e2004-05-31 10:01:34 +00005780 return (pBt && (pBt->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00005781}
5782
5783/*
5784** Return non-zero if a statement transaction is active.
5785*/
5786int sqlite3BtreeIsInStmt(Btree *pBt){
5787 return (pBt && pBt->inStmt);
5788}
danielk197713adf8a2004-06-03 16:08:41 +00005789
5790/*
5791** This call is a no-op if no write-transaction is currently active on pBt.
5792**
5793** Otherwise, sync the database file for the btree pBt. zMaster points to
5794** the name of a master journal file that should be written into the
5795** individual journal file, or is NULL, indicating no master journal file
5796** (single database transaction).
5797**
5798** When this is called, the master journal should already have been
5799** created, populated with this journal pointer and synced to disk.
5800**
5801** Once this is routine has returned, the only thing required to commit
5802** the write-transaction for this database file is to delete the journal.
5803*/
5804int sqlite3BtreeSync(Btree *pBt, const char *zMaster){
5805 if( pBt->inTrans==TRANS_WRITE ){
danielk1977687566d2004-11-02 12:56:41 +00005806#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977d761c0c2004-11-05 16:37:02 +00005807 Pgno nTrunc = 0;
danielk1977687566d2004-11-02 12:56:41 +00005808 if( pBt->autoVacuum ){
danielk1977d761c0c2004-11-05 16:37:02 +00005809 int rc = autoVacuumCommit(pBt, &nTrunc);
danielk1977687566d2004-11-02 12:56:41 +00005810 if( rc!=SQLITE_OK ) return rc;
5811 }
danielk1977d761c0c2004-11-05 16:37:02 +00005812 return sqlite3pager_sync(pBt->pPager, zMaster, nTrunc);
danielk1977687566d2004-11-02 12:56:41 +00005813#endif
danielk1977d761c0c2004-11-05 16:37:02 +00005814 return sqlite3pager_sync(pBt->pPager, zMaster, 0);
danielk197713adf8a2004-06-03 16:08:41 +00005815 }
5816 return SQLITE_OK;
5817}
danielk19776b456a22005-03-21 04:04:02 +00005818
5819#ifndef SQLITE_OMIT_GLOBALRECOVER
5820/*
5821** Reset the btree and underlying pager after a malloc() failure. Any
5822** transaction that was active when malloc() failed is rolled back.
5823*/
5824int sqlite3BtreeReset(Btree *pBt){
5825 if( pBt->pCursor ) return SQLITE_BUSY;
5826 pBt->inTrans = TRANS_NONE;
5827 unlockBtreeIfUnused(pBt);
5828 return sqlite3pager_reset(pBt->pPager);
5829}
5830#endif