blob: 9847f72c80cb72b8fba3ee8d8c1da4e600fc3275 [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*************************************************************************
drh198bf392006-01-06 21:52:49 +000012** $Id: btree.c,v 1.284 2006/01/06 21:52:50 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;
danielk1977aef0bf62005-12-30 16:28:01 +0000233typedef struct BtLock BtLock;
paulb95a8862003-04-01 21:16:41 +0000234
drh8c42ca92001-06-22 19:15:00 +0000235/*
drhbd03cae2001-06-02 02:40:57 +0000236** This is a magic string that appears at the beginning of every
drh8c42ca92001-06-22 19:15:00 +0000237** SQLite database in order to identify the file as a real database.
drh556b2a22005-06-14 16:04:05 +0000238**
239** You can change this value at compile-time by specifying a
240** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
241** header must be exactly 16 bytes including the zero-terminator so
242** the string itself should be 15 characters long. If you change
243** the header, then your custom library will not be able to read
244** databases generated by the standard tools and the standard tools
245** will not be able to read databases created by your custom library.
246*/
247#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
248# define SQLITE_FILE_HEADER "SQLite format 3"
249#endif
250static const char zMagicHeader[] = SQLITE_FILE_HEADER;
drh08ed44e2001-04-29 23:32:55 +0000251
252/*
drh4b70f112004-05-02 21:12:19 +0000253** Page type flags. An ORed combination of these flags appear as the
254** first byte of every BTree page.
drh8c42ca92001-06-22 19:15:00 +0000255*/
drhde647132004-05-07 17:57:49 +0000256#define PTF_INTKEY 0x01
drh9e572e62004-04-23 23:43:10 +0000257#define PTF_ZERODATA 0x02
drh8b18dd42004-05-12 19:18:15 +0000258#define PTF_LEAFDATA 0x04
259#define PTF_LEAF 0x08
drh8c42ca92001-06-22 19:15:00 +0000260
261/*
drh9e572e62004-04-23 23:43:10 +0000262** As each page of the file is loaded into memory, an instance of the following
263** structure is appended and initialized to zero. This structure stores
264** information about the page that is decoded from the raw file page.
drh14acc042001-06-10 19:56:58 +0000265**
drh72f82862001-05-24 21:06:34 +0000266** The pParent field points back to the parent page. This allows us to
267** walk up the BTree from any leaf to the root. Care must be taken to
268** unref() the parent page pointer when this page is no longer referenced.
drhbd03cae2001-06-02 02:40:57 +0000269** The pageDestructor() routine handles that chore.
drh7e3b0a02001-04-28 16:52:40 +0000270*/
271struct MemPage {
drha6abd042004-06-09 17:37:22 +0000272 u8 isInit; /* True if previously initialized. MUST BE FIRST! */
drh43605152004-05-29 21:46:49 +0000273 u8 idxShift; /* True if Cell indices have changed */
274 u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
275 u8 intKey; /* True if intkey flag is set */
276 u8 leaf; /* True if leaf flag is set */
277 u8 zeroData; /* True if table stores keys only */
278 u8 leafData; /* True if tables stores data on leaves only */
279 u8 hasData; /* True if this page stores data */
280 u8 hdrOffset; /* 100 for page 1. 0 otherwise */
drh271efa52004-05-30 19:19:05 +0000281 u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
drha2fce642004-06-05 00:01:44 +0000282 u16 maxLocal; /* Copy of Btree.maxLocal or Btree.maxLeaf */
283 u16 minLocal; /* Copy of Btree.minLocal or Btree.minLeaf */
drh43605152004-05-29 21:46:49 +0000284 u16 cellOffset; /* Index in aData of first cell pointer */
285 u16 idxParent; /* Index in parent of this node */
286 u16 nFree; /* Number of free bytes on the page */
287 u16 nCell; /* Number of cells on this page, local and ovfl */
288 struct _OvflCell { /* Cells that will not fit on aData[] */
danielk1977aef0bf62005-12-30 16:28:01 +0000289 u8 *pCell; /* Pointers to the body of the overflow cell */
290 u16 idx; /* Insert this cell before idx-th non-overflow cell */
drha2fce642004-06-05 00:01:44 +0000291 } aOvfl[5];
drh47ded162006-01-06 01:42:58 +0000292 BtShared *pBt; /* Pointer back to BTree structure */
293 u8 *aData; /* Pointer back to the start of the page */
294 Pgno pgno; /* Page number for this page */
295 MemPage *pParent; /* The parent of this page. NULL for root */
drh8c42ca92001-06-22 19:15:00 +0000296};
drh7e3b0a02001-04-28 16:52:40 +0000297
298/*
drh3b7511c2001-05-26 13:15:44 +0000299** The in-memory image of a disk page has the auxiliary information appended
300** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
301** that extra information.
302*/
drh3aac2dd2004-04-26 14:10:20 +0000303#define EXTRA_SIZE sizeof(MemPage)
drh3b7511c2001-05-26 13:15:44 +0000304
danielk1977aef0bf62005-12-30 16:28:01 +0000305/* Btree handle */
306struct Btree {
307 sqlite3 *pSqlite;
308 BtShared *pBt;
309 u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
310};
311
312/*
313** Btree.inTrans may take one of the following values.
314**
315** If the shared-data extension is enabled, there may be multiple users
316** of the Btree structure. At most one of these may open a write transaction,
317** but any number may have active read transactions. Variable Btree.pDb
318** points to the handle that owns any current write-transaction.
319*/
320#define TRANS_NONE 0
321#define TRANS_READ 1
322#define TRANS_WRITE 2
323
drh3b7511c2001-05-26 13:15:44 +0000324/*
drha059ad02001-04-17 20:09:11 +0000325** Everything we need to know about an open database
326*/
danielk1977aef0bf62005-12-30 16:28:01 +0000327struct BtShared {
drha059ad02001-04-17 20:09:11 +0000328 Pager *pPager; /* The page cache */
drh306dc212001-05-21 13:45:10 +0000329 BtCursor *pCursor; /* A list of all open cursors */
drh3aac2dd2004-04-26 14:10:20 +0000330 MemPage *pPage1; /* First page of the database */
drhab01f612004-05-22 02:55:23 +0000331 u8 inStmt; /* True if we are in a statement subtransaction */
drh5df72a52002-06-06 23:16:05 +0000332 u8 readOnly; /* True if the underlying file is readonly */
drhab01f612004-05-22 02:55:23 +0000333 u8 maxEmbedFrac; /* Maximum payload as % of total page size */
334 u8 minEmbedFrac; /* Minimum payload as % of total page size */
335 u8 minLeafFrac; /* Minimum leaf payload as % of total page size */
drh90f5ecb2004-07-22 01:19:35 +0000336 u8 pageSizeFixed; /* True if the page size can no longer be changed */
drh057cd3a2005-02-15 16:23:02 +0000337#ifndef SQLITE_OMIT_AUTOVACUUM
338 u8 autoVacuum; /* True if database supports auto-vacuum */
339#endif
drha2fce642004-06-05 00:01:44 +0000340 u16 pageSize; /* Total number of bytes on a page */
341 u16 usableSize; /* Number of usable bytes on each page */
drh6f11bef2004-05-13 01:12:56 +0000342 int maxLocal; /* Maximum local payload in non-LEAFDATA tables */
343 int minLocal; /* Minimum local payload in non-LEAFDATA tables */
344 int maxLeaf; /* Maximum local payload in a LEAFDATA table */
345 int minLeaf; /* Minimum local payload in a LEAFDATA table */
drhb8ef32c2005-03-14 02:01:49 +0000346 BusyHandler *pBusyHandler; /* Callback for when there is lock contention */
danielk1977aef0bf62005-12-30 16:28:01 +0000347 u8 inTransaction; /* Transaction state */
348 BtShared *pNext; /* Next in SqliteTsd.pBtree linked list */
349 int nRef; /* Number of references to this structure */
350 int nTransaction; /* Number of open transactions (read + write) */
351 BtLock *pLock; /* List of locks held on this shared-btree struct */
danielk1977da184232006-01-05 11:34:32 +0000352 void *pSchema;
353 void (*xFreeSchema)(void*);
drha059ad02001-04-17 20:09:11 +0000354};
danielk1977ee5741e2004-05-31 10:01:34 +0000355
356/*
drhfa1a98a2004-05-14 19:08:17 +0000357** An instance of the following structure is used to hold information
drh271efa52004-05-30 19:19:05 +0000358** about a cell. The parseCellPtr() function fills in this structure
drhab01f612004-05-22 02:55:23 +0000359** based on information extract from the raw disk page.
drhfa1a98a2004-05-14 19:08:17 +0000360*/
361typedef struct CellInfo CellInfo;
362struct CellInfo {
drh43605152004-05-29 21:46:49 +0000363 u8 *pCell; /* Pointer to the start of cell content */
drhfa1a98a2004-05-14 19:08:17 +0000364 i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
365 u32 nData; /* Number of bytes of data */
drh271efa52004-05-30 19:19:05 +0000366 u16 nHeader; /* Size of the cell content header in bytes */
drhfa1a98a2004-05-14 19:08:17 +0000367 u16 nLocal; /* Amount of payload held locally */
drhab01f612004-05-22 02:55:23 +0000368 u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
drh271efa52004-05-30 19:19:05 +0000369 u16 nSize; /* Size of the cell content on the main b-tree page */
drhfa1a98a2004-05-14 19:08:17 +0000370};
371
372/*
drh365d68f2001-05-11 11:02:46 +0000373** A cursor is a pointer to a particular entry in the BTree.
374** The entry is identified by its MemPage and the index in
drha34b6762004-05-07 13:30:42 +0000375** MemPage.aCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000376*/
drh72f82862001-05-24 21:06:34 +0000377struct BtCursor {
danielk1977aef0bf62005-12-30 16:28:01 +0000378 Btree *pBtree; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000379 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drh3aac2dd2004-04-26 14:10:20 +0000380 int (*xCompare)(void*,int,const void*,int,const void*); /* Key comp func */
381 void *pArg; /* First arg to xCompare() */
drh8b2f49b2001-06-08 00:21:52 +0000382 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000383 MemPage *pPage; /* Page that contains the entry */
drh3aac2dd2004-04-26 14:10:20 +0000384 int idx; /* Index of the entry in pPage->aCell[] */
drhfa1a98a2004-05-14 19:08:17 +0000385 CellInfo info; /* A parse of the cell we are pointing at */
drhecdc7532001-09-23 02:35:53 +0000386 u8 wrFlag; /* True if writable */
danielk1977da184232006-01-05 11:34:32 +0000387 u8 eState; /* One of the CURSOR_XXX constants (see below) */
388#ifndef SQLITE_OMIT_SHARED_CACHE
389 void *pKey;
390 i64 nKey;
391 int skip; /* (skip<0) -> Prev() is a no-op. (skip>0) -> Next() is */
392#endif
drh365d68f2001-05-11 11:02:46 +0000393};
drh7e3b0a02001-04-28 16:52:40 +0000394
drha059ad02001-04-17 20:09:11 +0000395/*
danielk1977da184232006-01-05 11:34:32 +0000396** Potential values for BtCursor.eState. The first two values (VALID and
397** INVALID) may occur in any build. The third (REQUIRESEEK) may only occur
398** if sqlite was compiled without the OMIT_SHARED_CACHE symbol defined.
399**
400** CURSOR_VALID:
401** Cursor points to a valid entry. getPayload() etc. may be called.
402**
403** CURSOR_INVALID:
404** Cursor does not point to a valid entry. This can happen (for example)
405** because the table is empty or because BtreeCursorFirst() has not been
406** called.
407**
408** CURSOR_REQUIRESEEK:
409** The table that this cursor was opened on still exists, but has been
410** modified since the cursor was last used. The cursor position is saved
411** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
412** this state, restoreCursorPosition() can be called to attempt to seek
413** the cursor to the saved position.
414*/
415#define CURSOR_INVALID 0
416#define CURSOR_VALID 1
417#define CURSOR_REQUIRESEEK 2
418
419/*
drh615ae552005-01-16 23:21:00 +0000420** The TRACE macro will print high-level status information about the
421** btree operation when the global variable sqlite3_btree_trace is
422** enabled.
423*/
424#if SQLITE_TEST
425# define TRACE(X) if( sqlite3_btree_trace )\
426 { sqlite3DebugPrintf X; fflush(stdout); }
427#else
428# define TRACE(X)
429#endif
430int sqlite3_btree_trace=0; /* True to enable tracing */
431
432/*
drh66cbd152004-09-01 16:12:25 +0000433** Forward declaration
434*/
danielk1977aef0bf62005-12-30 16:28:01 +0000435static int checkReadLocks(BtShared*,Pgno,BtCursor*);
drh66cbd152004-09-01 16:12:25 +0000436
drh66cbd152004-09-01 16:12:25 +0000437/*
drhab01f612004-05-22 02:55:23 +0000438** Read or write a two- and four-byte big-endian integer values.
drh0d316a42002-08-11 20:10:47 +0000439*/
drh9e572e62004-04-23 23:43:10 +0000440static u32 get2byte(unsigned char *p){
441 return (p[0]<<8) | p[1];
drh0d316a42002-08-11 20:10:47 +0000442}
drh9e572e62004-04-23 23:43:10 +0000443static u32 get4byte(unsigned char *p){
444 return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
445}
drh9e572e62004-04-23 23:43:10 +0000446static void put2byte(unsigned char *p, u32 v){
447 p[0] = v>>8;
448 p[1] = v;
449}
450static void put4byte(unsigned char *p, u32 v){
451 p[0] = v>>24;
452 p[1] = v>>16;
453 p[2] = v>>8;
454 p[3] = v;
455}
drh6f11bef2004-05-13 01:12:56 +0000456
drh9e572e62004-04-23 23:43:10 +0000457/*
drhab01f612004-05-22 02:55:23 +0000458** Routines to read and write variable-length integers. These used to
459** be defined locally, but now we use the varint routines in the util.c
460** file.
drh9e572e62004-04-23 23:43:10 +0000461*/
drh6d2fb152004-05-14 16:50:06 +0000462#define getVarint sqlite3GetVarint
463#define getVarint32 sqlite3GetVarint32
464#define putVarint sqlite3PutVarint
drh0d316a42002-08-11 20:10:47 +0000465
danielk1977599fcba2004-11-08 07:13:13 +0000466/* The database page the PENDING_BYTE occupies. This page is never used.
467** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
468** should possibly be consolidated (presumably in pager.h).
469*/
470#define PENDING_BYTE_PAGE(pBt) ((PENDING_BYTE/(pBt)->pageSize)+1)
danielk1977afcdd022004-10-31 16:25:42 +0000471
danielk1977aef0bf62005-12-30 16:28:01 +0000472/*
473** A linked list of the following structures is stored at BtShared.pLock.
474** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
475** is opened on the table with root page BtShared.iTable. Locks are removed
476** from this list when a transaction is committed or rolled back, or when
477** a btree handle is closed.
478*/
479struct BtLock {
480 Btree *pBtree; /* Btree handle holding this lock */
481 Pgno iTable; /* Root page of table */
482 u8 eLock; /* READ_LOCK or WRITE_LOCK */
483 BtLock *pNext; /* Next in BtShared.pLock list */
484};
485
486/* Candidate values for BtLock.eLock */
487#define READ_LOCK 1
488#define WRITE_LOCK 2
489
490#ifdef SQLITE_OMIT_SHARED_CACHE
491 /*
492 ** The functions queryTableLock(), lockTable() and unlockAllTables()
493 ** manipulate entries in the BtShared.pLock linked list used to store
494 ** shared-cache table level locks. If the library is compiled with the
495 ** shared-cache feature disabled, then there is only ever one user
danielk1977da184232006-01-05 11:34:32 +0000496 ** of each BtShared structure and so this locking is not necessary.
497 ** So define the lock related functions as no-ops.
danielk1977aef0bf62005-12-30 16:28:01 +0000498 */
499 #define queryTableLock(a,b,c) SQLITE_OK
500 #define lockTable(a,b,c) SQLITE_OK
danielk1977da184232006-01-05 11:34:32 +0000501 #define unlockAllTables(a)
502 #define restoreCursorPosition(a,b) SQLITE_OK
503 #define saveAllCursors(a,b,c) SQLITE_OK
504
danielk1977aef0bf62005-12-30 16:28:01 +0000505#else
506
507/*
danielk1977da184232006-01-05 11:34:32 +0000508** Save the current cursor position in the variables BtCursor.nKey
509** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
510*/
511static int saveCursorPosition(BtCursor *pCur){
512 int rc = SQLITE_OK;
513
514 assert( CURSOR_VALID==pCur->eState|| CURSOR_INVALID==pCur->eState );
515 assert( 0==pCur->pKey );
516
517 if( pCur->eState==CURSOR_VALID ){
518 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
519
520 /* If this is an intKey table, then the above call to BtreeKeySize()
521 ** stores the integer key in pCur->nKey. In this case this value is
522 ** all that is required. Otherwise, if pCur is not open on an intKey
523 ** table, then malloc space for and store the pCur->nKey bytes of key
524 ** data.
525 */
526 if( rc==SQLITE_OK && 0==pCur->pPage->intKey){
527 void *pKey = sqliteMalloc(pCur->nKey);
528 if( pKey ){
529 rc = sqlite3BtreeKey(pCur, 0, pCur->nKey, pKey);
drh47ded162006-01-06 01:42:58 +0000530 if( rc==SQLITE_OK ){
danielk1977da184232006-01-05 11:34:32 +0000531 pCur->pKey = pKey;
532 }else{
533 sqliteFree(pKey);
534 }
535 }else{
536 rc = SQLITE_NOMEM;
537 }
538 }
539 assert( !pCur->pPage->intKey || !pCur->pKey );
540
541 /* Todo: Should we drop the reference to pCur->pPage here? */
542
543 if( rc==SQLITE_OK ){
544 pCur->eState = CURSOR_REQUIRESEEK;
545 }
546 }
547
548 return rc;
549}
550
551/*
552** Save the positions of all cursors except pExcept open on the table
553** with root-page iRoot. Usually, this is called just before cursor
554** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
555*/
556static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
557 BtCursor *p;
558 if( sqlite3Tsd()->useSharedData ){
559 for(p=pBt->pCursor; p; p=p->pNext){
560 if( p!=pExcept && p->pgnoRoot==iRoot && p->eState==CURSOR_VALID ){
561 int rc = saveCursorPosition(p);
562 if( SQLITE_OK!=rc ){
563 return rc;
564 }
565 }
566 }
567 }
568 return SQLITE_OK;
569}
570
571/*
572** Restore the cursor to the position it was in (or as close to as possible)
573** when saveCursorPosition() was called. Note that this call deletes the
574** saved position info stored by saveCursorPosition(), so there can be
575** at most one effective restoreCursorPosition() call after each
576** saveCursorPosition().
577**
578** If the second argument argument - doSeek - is false, then instead of
579** returning the cursor to it's saved position, any saved position is deleted
580** and the cursor state set to CURSOR_INVALID.
581*/
582static int restoreCursorPosition(BtCursor *pCur, int doSeek){
583 int rc = SQLITE_OK;
584 if( pCur->eState==CURSOR_REQUIRESEEK ){
585 assert( sqlite3Tsd()->useSharedData );
586 if( doSeek ){
587 rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, &pCur->skip);
588 }else{
589 pCur->eState = CURSOR_INVALID;
590 }
591 if( rc==SQLITE_OK ){
592 sqliteFree(pCur->pKey);
593 pCur->pKey = 0;
594 assert( CURSOR_VALID==pCur->eState || CURSOR_INVALID==pCur->eState );
595 }
596 }
597 return rc;
598}
599
600/*
danielk1977aef0bf62005-12-30 16:28:01 +0000601** Query to see if btree handle p may obtain a lock of type eLock
602** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
603** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
danielk1977c87d34d2006-01-06 13:00:28 +0000604** SQLITE_LOCKED if not.
danielk1977aef0bf62005-12-30 16:28:01 +0000605*/
606static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
607 BtShared *pBt = p->pBt;
608 BtLock *pIter;
609
danielk1977da184232006-01-05 11:34:32 +0000610 /* This is a no-op if the shared-cache is not enabled */
611 if( 0==sqlite3Tsd()->useSharedData ){
612 return SQLITE_OK;
613 }
614
615 /* This (along with lockTable()) is where the ReadUncommitted flag is
616 ** dealt with. If the caller is querying for a read-lock and the flag is
617 ** set, it is unconditionally granted - even if there are write-locks
618 ** on the table. If a write-lock is requested, the ReadUncommitted flag
619 ** is not considered.
620 **
621 ** In function lockTable(), if a read-lock is demanded and the
622 ** ReadUncommitted flag is set, no entry is added to the locks list
623 ** (BtShared.pLock).
624 **
625 ** To summarize: If the ReadUncommitted flag is set, then read cursors do
626 ** not create or respect table locks. The locking procedure for a
627 ** write-cursor does not change.
628 */
629 if(
630 !p->pSqlite ||
631 0==(p->pSqlite->flags&SQLITE_ReadUncommitted) ||
632 eLock==WRITE_LOCK ||
drh47ded162006-01-06 01:42:58 +0000633 iTab==MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000634 ){
635 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
636 if( pIter->pBtree!=p && pIter->iTable==iTab &&
637 (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
danielk1977c87d34d2006-01-06 13:00:28 +0000638 return SQLITE_LOCKED;
danielk1977da184232006-01-05 11:34:32 +0000639 }
danielk1977aef0bf62005-12-30 16:28:01 +0000640 }
641 }
642 return SQLITE_OK;
643}
644
645/*
646** Add a lock on the table with root-page iTable to the shared-btree used
647** by Btree handle p. Parameter eLock must be either READ_LOCK or
648** WRITE_LOCK.
649**
650** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
651** SQLITE_NOMEM may also be returned.
652*/
653static int lockTable(Btree *p, Pgno iTable, u8 eLock){
654 BtShared *pBt = p->pBt;
655 BtLock *pLock = 0;
656 BtLock *pIter;
657
danielk1977da184232006-01-05 11:34:32 +0000658 /* This is a no-op if the shared-cache is not enabled */
659 if( 0==sqlite3Tsd()->useSharedData ){
660 return SQLITE_OK;
661 }
662
danielk1977aef0bf62005-12-30 16:28:01 +0000663 assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
664
danielk1977da184232006-01-05 11:34:32 +0000665 /* If the read-uncommitted flag is set and a read-lock is requested,
666 ** return early without adding an entry to the BtShared.pLock list. See
667 ** comment in function queryTableLock() for more info on handling
668 ** the ReadUncommitted flag.
669 */
670 if(
671 (p->pSqlite) &&
672 (p->pSqlite->flags&SQLITE_ReadUncommitted) &&
673 (eLock==READ_LOCK) &&
drh47ded162006-01-06 01:42:58 +0000674 iTable!=MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000675 ){
676 return SQLITE_OK;
677 }
678
danielk1977aef0bf62005-12-30 16:28:01 +0000679 /* First search the list for an existing lock on this table. */
680 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
681 if( pIter->iTable==iTable && pIter->pBtree==p ){
682 pLock = pIter;
683 break;
684 }
685 }
686
687 /* If the above search did not find a BtLock struct associating Btree p
688 ** with table iTable, allocate one and link it into the list.
689 */
690 if( !pLock ){
691 pLock = (BtLock *)sqliteMalloc(sizeof(BtLock));
692 if( !pLock ){
693 return SQLITE_NOMEM;
694 }
695 pLock->iTable = iTable;
696 pLock->pBtree = p;
697 pLock->pNext = pBt->pLock;
698 pBt->pLock = pLock;
699 }
700
701 /* Set the BtLock.eLock variable to the maximum of the current lock
702 ** and the requested lock. This means if a write-lock was already held
703 ** and a read-lock requested, we don't incorrectly downgrade the lock.
704 */
705 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000706 if( eLock>pLock->eLock ){
707 pLock->eLock = eLock;
708 }
danielk1977aef0bf62005-12-30 16:28:01 +0000709
710 return SQLITE_OK;
711}
712
713/*
714** Release all the table locks (locks obtained via calls to the lockTable()
715** procedure) held by Btree handle p.
716*/
717static void unlockAllTables(Btree *p){
718 BtLock **ppIter = &p->pBt->pLock;
danielk1977da184232006-01-05 11:34:32 +0000719
720 /* If the shared-cache extension is not enabled, there should be no
721 ** locks in the BtShared.pLock list, making this procedure a no-op. Assert
722 ** that this is the case.
723 */
724 assert( sqlite3Tsd()->useSharedData || 0==*ppIter );
725
danielk1977aef0bf62005-12-30 16:28:01 +0000726 while( *ppIter ){
727 BtLock *pLock = *ppIter;
728 if( pLock->pBtree==p ){
729 *ppIter = pLock->pNext;
730 sqliteFree(pLock);
731 }else{
732 ppIter = &pLock->pNext;
733 }
734 }
735}
736#endif /* SQLITE_OMIT_SHARED_CACHE */
737
danielk1977599fcba2004-11-08 07:13:13 +0000738#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000739/*
drh42cac6d2004-11-20 20:31:11 +0000740** These macros define the location of the pointer-map entry for a
741** database page. The first argument to each is the number of usable
742** bytes on each page of the database (often 1024). The second is the
743** page number to look up in the pointer map.
danielk1977afcdd022004-10-31 16:25:42 +0000744**
745** PTRMAP_PAGENO returns the database page number of the pointer-map
746** page that stores the required pointer. PTRMAP_PTROFFSET returns
747** the offset of the requested map entry.
748**
749** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
750** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
danielk1977599fcba2004-11-08 07:13:13 +0000751** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
752** this test.
danielk1977afcdd022004-10-31 16:25:42 +0000753*/
754#define PTRMAP_PAGENO(pgsz, pgno) (((pgno-2)/(pgsz/5+1))*(pgsz/5+1)+2)
755#define PTRMAP_PTROFFSET(pgsz, pgno) (((pgno-2)%(pgsz/5+1)-1)*5)
danielk1977a19df672004-11-03 11:37:07 +0000756#define PTRMAP_ISPAGE(pgsz, pgno) (PTRMAP_PAGENO(pgsz,pgno)==pgno)
757
danielk1977afcdd022004-10-31 16:25:42 +0000758/*
drh615ae552005-01-16 23:21:00 +0000759** The pointer map is a lookup table that identifies the parent page for
760** each child page in the database file. The parent page is the page that
761** contains a pointer to the child. Every page in the database contains
762** 0 or 1 parent pages. (In this context 'database page' refers
763** to any page that is not part of the pointer map itself.) Each pointer map
764** entry consists of a single byte 'type' and a 4 byte parent page number.
765** The PTRMAP_XXX identifiers below are the valid types.
766**
767** The purpose of the pointer map is to facility moving pages from one
768** position in the file to another as part of autovacuum. When a page
769** is moved, the pointer in its parent must be updated to point to the
770** new location. The pointer map is used to locate the parent page quickly.
danielk1977afcdd022004-10-31 16:25:42 +0000771**
danielk1977687566d2004-11-02 12:56:41 +0000772** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
773** used in this case.
danielk1977afcdd022004-10-31 16:25:42 +0000774**
danielk1977687566d2004-11-02 12:56:41 +0000775** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
776** is not used in this case.
777**
778** PTRMAP_OVERFLOW1: The database page is the first page in a list of
779** overflow pages. The page number identifies the page that
780** contains the cell with a pointer to this overflow page.
781**
782** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
783** overflow pages. The page-number identifies the previous
784** page in the overflow page list.
785**
786** PTRMAP_BTREE: The database page is a non-root btree page. The page number
787** identifies the parent page in the btree.
danielk1977afcdd022004-10-31 16:25:42 +0000788*/
danielk1977687566d2004-11-02 12:56:41 +0000789#define PTRMAP_ROOTPAGE 1
790#define PTRMAP_FREEPAGE 2
791#define PTRMAP_OVERFLOW1 3
792#define PTRMAP_OVERFLOW2 4
793#define PTRMAP_BTREE 5
danielk1977afcdd022004-10-31 16:25:42 +0000794
795/*
796** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000797**
798** This routine updates the pointer map entry for page number 'key'
799** so that it maps to type 'eType' and parent page number 'pgno'.
800** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000801*/
danielk1977aef0bf62005-12-30 16:28:01 +0000802static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
danielk1977afcdd022004-10-31 16:25:42 +0000803 u8 *pPtrmap; /* The pointer map page */
804 Pgno iPtrmap; /* The pointer map page number */
805 int offset; /* Offset in pointer map page */
806 int rc;
807
danielk1977ac11ee62005-01-15 12:45:51 +0000808 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000809 if( key==0 ){
drh49285702005-09-17 15:20:26 +0000810 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000811 }
drh42cac6d2004-11-20 20:31:11 +0000812 iPtrmap = PTRMAP_PAGENO(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000813 rc = sqlite3pager_get(pBt->pPager, iPtrmap, (void **)&pPtrmap);
danielk1977687566d2004-11-02 12:56:41 +0000814 if( rc!=SQLITE_OK ){
danielk1977afcdd022004-10-31 16:25:42 +0000815 return rc;
816 }
drh42cac6d2004-11-20 20:31:11 +0000817 offset = PTRMAP_PTROFFSET(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000818
drh615ae552005-01-16 23:21:00 +0000819 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
820 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
danielk1977afcdd022004-10-31 16:25:42 +0000821 rc = sqlite3pager_write(pPtrmap);
danielk19775558a8a2005-01-17 07:53:44 +0000822 if( rc==SQLITE_OK ){
823 pPtrmap[offset] = eType;
824 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000825 }
danielk1977afcdd022004-10-31 16:25:42 +0000826 }
827
828 sqlite3pager_unref(pPtrmap);
danielk19775558a8a2005-01-17 07:53:44 +0000829 return rc;
danielk1977afcdd022004-10-31 16:25:42 +0000830}
831
832/*
833** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000834**
835** This routine retrieves the pointer map entry for page 'key', writing
836** the type and parent page number to *pEType and *pPgno respectively.
837** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000838*/
danielk1977aef0bf62005-12-30 16:28:01 +0000839static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk1977afcdd022004-10-31 16:25:42 +0000840 int iPtrmap; /* Pointer map page index */
841 u8 *pPtrmap; /* Pointer map page data */
842 int offset; /* Offset of entry in pointer map */
843 int rc;
844
drh42cac6d2004-11-20 20:31:11 +0000845 iPtrmap = PTRMAP_PAGENO(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000846 rc = sqlite3pager_get(pBt->pPager, iPtrmap, (void **)&pPtrmap);
847 if( rc!=0 ){
848 return rc;
849 }
850
drh42cac6d2004-11-20 20:31:11 +0000851 offset = PTRMAP_PTROFFSET(pBt->usableSize, key);
danielk1977687566d2004-11-02 12:56:41 +0000852 if( pEType ) *pEType = pPtrmap[offset];
853 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000854
855 sqlite3pager_unref(pPtrmap);
drh49285702005-09-17 15:20:26 +0000856 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000857 return SQLITE_OK;
858}
859
860#endif /* SQLITE_OMIT_AUTOVACUUM */
861
drh0d316a42002-08-11 20:10:47 +0000862/*
drh271efa52004-05-30 19:19:05 +0000863** Given a btree page and a cell index (0 means the first cell on
864** the page, 1 means the second cell, and so forth) return a pointer
865** to the cell content.
866**
867** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000868*/
drh43605152004-05-29 21:46:49 +0000869static u8 *findCell(MemPage *pPage, int iCell){
870 u8 *data = pPage->aData;
871 assert( iCell>=0 );
872 assert( iCell<get2byte(&data[pPage->hdrOffset+3]) );
873 return data + get2byte(&data[pPage->cellOffset+2*iCell]);
874}
875
876/*
877** This a more complex version of findCell() that works for
878** pages that do contain overflow cells. See insert
879*/
880static u8 *findOverflowCell(MemPage *pPage, int iCell){
881 int i;
882 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000883 int k;
884 struct _OvflCell *pOvfl;
885 pOvfl = &pPage->aOvfl[i];
886 k = pOvfl->idx;
887 if( k<=iCell ){
888 if( k==iCell ){
889 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000890 }
891 iCell--;
892 }
893 }
894 return findCell(pPage, iCell);
895}
896
897/*
898** Parse a cell content block and fill in the CellInfo structure. There
899** are two versions of this function. parseCell() takes a cell index
900** as the second argument and parseCellPtr() takes a pointer to the
901** body of the cell as its second argument.
902*/
903static void parseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000904 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000905 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000906 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000907){
drh271efa52004-05-30 19:19:05 +0000908 int n; /* Number bytes in cell content header */
909 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000910
911 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000912 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000913 n = pPage->childPtrSize;
914 assert( n==4-4*pPage->leaf );
drh8b18dd42004-05-12 19:18:15 +0000915 if( pPage->hasData ){
drh271efa52004-05-30 19:19:05 +0000916 n += getVarint32(&pCell[n], &nPayload);
drh8b18dd42004-05-12 19:18:15 +0000917 }else{
drh271efa52004-05-30 19:19:05 +0000918 nPayload = 0;
drh3aac2dd2004-04-26 14:10:20 +0000919 }
danielk1977e0d4b062004-06-28 01:11:46 +0000920 n += getVarint(&pCell[n], (u64 *)&pInfo->nKey);
drh6f11bef2004-05-13 01:12:56 +0000921 pInfo->nHeader = n;
drh271efa52004-05-30 19:19:05 +0000922 pInfo->nData = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000923 if( !pPage->intKey ){
924 nPayload += pInfo->nKey;
925 }
drh271efa52004-05-30 19:19:05 +0000926 if( nPayload<=pPage->maxLocal ){
927 /* This is the (easy) common case where the entire payload fits
928 ** on the local page. No overflow is required.
929 */
930 int nSize; /* Total size of cell content in bytes */
drh6f11bef2004-05-13 01:12:56 +0000931 pInfo->nLocal = nPayload;
932 pInfo->iOverflow = 0;
drh271efa52004-05-30 19:19:05 +0000933 nSize = nPayload + n;
934 if( nSize<4 ){
935 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000936 }
drh271efa52004-05-30 19:19:05 +0000937 pInfo->nSize = nSize;
drh6f11bef2004-05-13 01:12:56 +0000938 }else{
drh271efa52004-05-30 19:19:05 +0000939 /* If the payload will not fit completely on the local page, we have
940 ** to decide how much to store locally and how much to spill onto
941 ** overflow pages. The strategy is to minimize the amount of unused
942 ** space on overflow pages while keeping the amount of local storage
943 ** in between minLocal and maxLocal.
944 **
945 ** Warning: changing the way overflow payload is distributed in any
946 ** way will result in an incompatible file format.
947 */
948 int minLocal; /* Minimum amount of payload held locally */
949 int maxLocal; /* Maximum amount of payload held locally */
950 int surplus; /* Overflow payload available for local storage */
951
952 minLocal = pPage->minLocal;
953 maxLocal = pPage->maxLocal;
954 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000955 if( surplus <= maxLocal ){
956 pInfo->nLocal = surplus;
957 }else{
958 pInfo->nLocal = minLocal;
959 }
960 pInfo->iOverflow = pInfo->nLocal + n;
961 pInfo->nSize = pInfo->iOverflow + 4;
962 }
drh3aac2dd2004-04-26 14:10:20 +0000963}
drh43605152004-05-29 21:46:49 +0000964static void parseCell(
965 MemPage *pPage, /* Page containing the cell */
966 int iCell, /* The cell index. First cell is 0 */
967 CellInfo *pInfo /* Fill in this structure */
968){
969 parseCellPtr(pPage, findCell(pPage, iCell), pInfo);
970}
drh3aac2dd2004-04-26 14:10:20 +0000971
972/*
drh43605152004-05-29 21:46:49 +0000973** Compute the total number of bytes that a Cell needs in the cell
974** data area of the btree-page. The return number includes the cell
975** data header and the local payload, but not any overflow page or
976** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000977*/
danielk1977bc6ada42004-06-30 08:20:16 +0000978#ifndef NDEBUG
drh43605152004-05-29 21:46:49 +0000979static int cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000980 CellInfo info;
drh43605152004-05-29 21:46:49 +0000981 parseCell(pPage, iCell, &info);
982 return info.nSize;
983}
danielk1977bc6ada42004-06-30 08:20:16 +0000984#endif
drh43605152004-05-29 21:46:49 +0000985static int cellSizePtr(MemPage *pPage, u8 *pCell){
986 CellInfo info;
987 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000988 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000989}
990
danielk197779a40da2005-01-16 08:00:01 +0000991#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +0000992/*
danielk197726836652005-01-17 01:33:13 +0000993** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +0000994** to an overflow page, insert an entry into the pointer-map
995** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +0000996*/
danielk197726836652005-01-17 01:33:13 +0000997static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
danielk197779a40da2005-01-16 08:00:01 +0000998 if( pCell ){
999 CellInfo info;
1000 parseCellPtr(pPage, pCell, &info);
1001 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
1002 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
1003 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
1004 }
danielk1977ac11ee62005-01-15 12:45:51 +00001005 }
danielk197779a40da2005-01-16 08:00:01 +00001006 return SQLITE_OK;
danielk1977ac11ee62005-01-15 12:45:51 +00001007}
danielk197726836652005-01-17 01:33:13 +00001008/*
1009** If the cell with index iCell on page pPage contains a pointer
1010** to an overflow page, insert an entry into the pointer-map
1011** for the overflow page.
1012*/
1013static int ptrmapPutOvfl(MemPage *pPage, int iCell){
1014 u8 *pCell;
1015 pCell = findOverflowCell(pPage, iCell);
1016 return ptrmapPutOvflPtr(pPage, pCell);
1017}
danielk197779a40da2005-01-16 08:00:01 +00001018#endif
1019
danielk1977ac11ee62005-01-15 12:45:51 +00001020
1021/*
drhda200cc2004-05-09 11:51:38 +00001022** Do sanity checking on a page. Throw an exception if anything is
1023** not right.
1024**
1025** This routine is used for internal error checking only. It is omitted
1026** from most builds.
1027*/
1028#if defined(BTREE_DEBUG) && !defined(NDEBUG) && 0
1029static void _pageIntegrity(MemPage *pPage){
drhb6f41482004-05-14 01:58:11 +00001030 int usableSize;
drhda200cc2004-05-09 11:51:38 +00001031 u8 *data;
drh43605152004-05-29 21:46:49 +00001032 int i, j, idx, c, pc, hdr, nFree;
1033 int cellOffset;
1034 int nCell, cellLimit;
drh2e38c322004-09-03 18:38:44 +00001035 u8 *used;
drhda200cc2004-05-09 11:51:38 +00001036
drh2e38c322004-09-03 18:38:44 +00001037 used = sqliteMallocRaw( pPage->pBt->pageSize );
1038 if( used==0 ) return;
drhb6f41482004-05-14 01:58:11 +00001039 usableSize = pPage->pBt->usableSize;
drh07d183d2005-05-01 22:52:42 +00001040 assert( pPage->aData==&((unsigned char*)pPage)[-pPage->pBt->pageSize] );
drhda200cc2004-05-09 11:51:38 +00001041 hdr = pPage->hdrOffset;
1042 assert( hdr==(pPage->pgno==1 ? 100 : 0) );
1043 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
1044 c = pPage->aData[hdr];
1045 if( pPage->isInit ){
1046 assert( pPage->leaf == ((c & PTF_LEAF)!=0) );
1047 assert( pPage->zeroData == ((c & PTF_ZERODATA)!=0) );
drh8b18dd42004-05-12 19:18:15 +00001048 assert( pPage->leafData == ((c & PTF_LEAFDATA)!=0) );
1049 assert( pPage->intKey == ((c & (PTF_INTKEY|PTF_LEAFDATA))!=0) );
1050 assert( pPage->hasData ==
1051 !(pPage->zeroData || (!pPage->leaf && pPage->leafData)) );
drh43605152004-05-29 21:46:49 +00001052 assert( pPage->cellOffset==pPage->hdrOffset+12-4*pPage->leaf );
1053 assert( pPage->nCell = get2byte(&pPage->aData[hdr+3]) );
drhda200cc2004-05-09 11:51:38 +00001054 }
1055 data = pPage->aData;
drhb6f41482004-05-14 01:58:11 +00001056 memset(used, 0, usableSize);
drhda200cc2004-05-09 11:51:38 +00001057 for(i=0; i<hdr+10-pPage->leaf*4; i++) used[i] = 1;
1058 nFree = 0;
1059 pc = get2byte(&data[hdr+1]);
1060 while( pc ){
1061 int size;
drhb6f41482004-05-14 01:58:11 +00001062 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +00001063 size = get2byte(&data[pc+2]);
drhb6f41482004-05-14 01:58:11 +00001064 assert( pc+size<=usableSize );
drhda200cc2004-05-09 11:51:38 +00001065 nFree += size;
1066 for(i=pc; i<pc+size; i++){
1067 assert( used[i]==0 );
1068 used[i] = 1;
1069 }
1070 pc = get2byte(&data[pc]);
1071 }
drhda200cc2004-05-09 11:51:38 +00001072 idx = 0;
drh43605152004-05-29 21:46:49 +00001073 nCell = get2byte(&data[hdr+3]);
1074 cellLimit = get2byte(&data[hdr+5]);
1075 assert( pPage->isInit==0
1076 || pPage->nFree==nFree+data[hdr+7]+cellLimit-(cellOffset+2*nCell) );
1077 cellOffset = pPage->cellOffset;
1078 for(i=0; i<nCell; i++){
drhda200cc2004-05-09 11:51:38 +00001079 int size;
drh43605152004-05-29 21:46:49 +00001080 pc = get2byte(&data[cellOffset+2*i]);
drhb6f41482004-05-14 01:58:11 +00001081 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +00001082 size = cellSize(pPage, &data[pc]);
drhb6f41482004-05-14 01:58:11 +00001083 assert( pc+size<=usableSize );
drh43605152004-05-29 21:46:49 +00001084 for(j=pc; j<pc+size; j++){
1085 assert( used[j]==0 );
1086 used[j] = 1;
drhda200cc2004-05-09 11:51:38 +00001087 }
drhda200cc2004-05-09 11:51:38 +00001088 }
drh43605152004-05-29 21:46:49 +00001089 for(i=cellOffset+2*nCell; i<cellimit; i++){
1090 assert( used[i]==0 );
1091 used[i] = 1;
1092 }
drhda200cc2004-05-09 11:51:38 +00001093 nFree = 0;
drhb6f41482004-05-14 01:58:11 +00001094 for(i=0; i<usableSize; i++){
drhda200cc2004-05-09 11:51:38 +00001095 assert( used[i]<=1 );
1096 if( used[i]==0 ) nFree++;
1097 }
drh43605152004-05-29 21:46:49 +00001098 assert( nFree==data[hdr+7] );
drh2e38c322004-09-03 18:38:44 +00001099 sqliteFree(used);
drhda200cc2004-05-09 11:51:38 +00001100}
1101#define pageIntegrity(X) _pageIntegrity(X)
1102#else
1103# define pageIntegrity(X)
1104#endif
1105
danielk1977aef0bf62005-12-30 16:28:01 +00001106/* A bunch of assert() statements to check the transaction state variables
1107** of handle p (type Btree*) are internally consistent.
1108*/
1109#define btreeIntegrity(p) \
1110 assert( p->inTrans!=TRANS_NONE || p->pBt->nTransaction<p->pBt->nRef ); \
1111 assert( p->pBt->nTransaction<=p->pBt->nRef ); \
1112 assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
1113 assert( p->pBt->inTransaction>=p->inTrans );
1114
drhda200cc2004-05-09 11:51:38 +00001115/*
drh72f82862001-05-24 21:06:34 +00001116** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +00001117** end of the page and all free space is collected into one
1118** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +00001119** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +00001120*/
drh2e38c322004-09-03 18:38:44 +00001121static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +00001122 int i; /* Loop counter */
1123 int pc; /* Address of a i-th cell */
1124 int addr; /* Offset of first byte after cell pointer array */
1125 int hdr; /* Offset to the page header */
1126 int size; /* Size of a cell */
1127 int usableSize; /* Number of usable bytes on a page */
1128 int cellOffset; /* Offset to the cell pointer array */
1129 int brk; /* Offset to the cell content area */
1130 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +00001131 unsigned char *data; /* The page data */
1132 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +00001133
drha34b6762004-05-07 13:30:42 +00001134 assert( sqlite3pager_iswriteable(pPage->aData) );
drh9e572e62004-04-23 23:43:10 +00001135 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +00001136 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +00001137 assert( pPage->nOverflow==0 );
drh2e38c322004-09-03 18:38:44 +00001138 temp = sqliteMalloc( pPage->pBt->pageSize );
1139 if( temp==0 ) return SQLITE_NOMEM;
drh43605152004-05-29 21:46:49 +00001140 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +00001141 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001142 cellOffset = pPage->cellOffset;
1143 nCell = pPage->nCell;
1144 assert( nCell==get2byte(&data[hdr+3]) );
1145 usableSize = pPage->pBt->usableSize;
1146 brk = get2byte(&data[hdr+5]);
1147 memcpy(&temp[brk], &data[brk], usableSize - brk);
1148 brk = usableSize;
1149 for(i=0; i<nCell; i++){
1150 u8 *pAddr; /* The i-th cell pointer */
1151 pAddr = &data[cellOffset + i*2];
1152 pc = get2byte(pAddr);
1153 assert( pc<pPage->pBt->usableSize );
1154 size = cellSizePtr(pPage, &temp[pc]);
1155 brk -= size;
1156 memcpy(&data[brk], &temp[pc], size);
1157 put2byte(pAddr, brk);
drh2af926b2001-05-15 00:39:25 +00001158 }
drh43605152004-05-29 21:46:49 +00001159 assert( brk>=cellOffset+2*nCell );
1160 put2byte(&data[hdr+5], brk);
1161 data[hdr+1] = 0;
1162 data[hdr+2] = 0;
1163 data[hdr+7] = 0;
1164 addr = cellOffset+2*nCell;
1165 memset(&data[addr], 0, brk-addr);
drh2e38c322004-09-03 18:38:44 +00001166 sqliteFree(temp);
1167 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +00001168}
1169
drha059ad02001-04-17 20:09:11 +00001170/*
drh43605152004-05-29 21:46:49 +00001171** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +00001172**
drh9e572e62004-04-23 23:43:10 +00001173** Return the index into pPage->aData[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +00001174** the new allocation. Or return 0 if there is not enough free
1175** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +00001176**
drh72f82862001-05-24 21:06:34 +00001177** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +00001178** nBytes of contiguous free space, then this routine automatically
1179** calls defragementPage() to consolidate all free space before
1180** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +00001181*/
drh9e572e62004-04-23 23:43:10 +00001182static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +00001183 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +00001184 int size;
drh24cd67e2004-05-10 16:18:47 +00001185 int nFrag;
drh43605152004-05-29 21:46:49 +00001186 int top;
1187 int nCell;
1188 int cellOffset;
drh9e572e62004-04-23 23:43:10 +00001189 unsigned char *data;
drh43605152004-05-29 21:46:49 +00001190
drh9e572e62004-04-23 23:43:10 +00001191 data = pPage->aData;
drha34b6762004-05-07 13:30:42 +00001192 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +00001193 assert( pPage->pBt );
1194 if( nByte<4 ) nByte = 4;
drh43605152004-05-29 21:46:49 +00001195 if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
1196 pPage->nFree -= nByte;
drh9e572e62004-04-23 23:43:10 +00001197 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001198
1199 nFrag = data[hdr+7];
1200 if( nFrag<60 ){
1201 /* Search the freelist looking for a slot big enough to satisfy the
1202 ** space request. */
1203 addr = hdr+1;
1204 while( (pc = get2byte(&data[addr]))>0 ){
1205 size = get2byte(&data[pc+2]);
1206 if( size>=nByte ){
1207 if( size<nByte+4 ){
1208 memcpy(&data[addr], &data[pc], 2);
1209 data[hdr+7] = nFrag + size - nByte;
1210 return pc;
1211 }else{
1212 put2byte(&data[pc+2], size-nByte);
1213 return pc + size - nByte;
1214 }
1215 }
1216 addr = pc;
drh9e572e62004-04-23 23:43:10 +00001217 }
1218 }
drh43605152004-05-29 21:46:49 +00001219
1220 /* Allocate memory from the gap in between the cell pointer array
1221 ** and the cell content area.
1222 */
1223 top = get2byte(&data[hdr+5]);
1224 nCell = get2byte(&data[hdr+3]);
1225 cellOffset = pPage->cellOffset;
1226 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
drh2e38c322004-09-03 18:38:44 +00001227 if( defragmentPage(pPage) ) return 0;
drh43605152004-05-29 21:46:49 +00001228 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +00001229 }
drh43605152004-05-29 21:46:49 +00001230 top -= nByte;
1231 assert( cellOffset + 2*nCell <= top );
1232 put2byte(&data[hdr+5], top);
1233 return top;
drh7e3b0a02001-04-28 16:52:40 +00001234}
1235
1236/*
drh9e572e62004-04-23 23:43:10 +00001237** Return a section of the pPage->aData to the freelist.
1238** The first byte of the new free block is pPage->aDisk[start]
1239** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +00001240**
1241** Most of the effort here is involved in coalesing adjacent
1242** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +00001243*/
drh9e572e62004-04-23 23:43:10 +00001244static void freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +00001245 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +00001246 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +00001247
drh9e572e62004-04-23 23:43:10 +00001248 assert( pPage->pBt!=0 );
drha34b6762004-05-07 13:30:42 +00001249 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +00001250 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +00001251 assert( (start + size)<=pPage->pBt->usableSize );
drh9e572e62004-04-23 23:43:10 +00001252 if( size<4 ) size = 4;
1253
1254 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +00001255 hdr = pPage->hdrOffset;
1256 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +00001257 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +00001258 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +00001259 assert( pbegin>addr );
1260 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +00001261 }
drhb6f41482004-05-14 01:58:11 +00001262 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +00001263 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +00001264 put2byte(&data[addr], start);
1265 put2byte(&data[start], pbegin);
1266 put2byte(&data[start+2], size);
drh2af926b2001-05-15 00:39:25 +00001267 pPage->nFree += size;
drh9e572e62004-04-23 23:43:10 +00001268
1269 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +00001270 addr = pPage->hdrOffset + 1;
1271 while( (pbegin = get2byte(&data[addr]))>0 ){
drh9e572e62004-04-23 23:43:10 +00001272 int pnext, psize;
drh3aac2dd2004-04-26 14:10:20 +00001273 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +00001274 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +00001275 pnext = get2byte(&data[pbegin]);
1276 psize = get2byte(&data[pbegin+2]);
1277 if( pbegin + psize + 3 >= pnext && pnext>0 ){
1278 int frag = pnext - (pbegin+psize);
drh43605152004-05-29 21:46:49 +00001279 assert( frag<=data[pPage->hdrOffset+7] );
1280 data[pPage->hdrOffset+7] -= frag;
drh9e572e62004-04-23 23:43:10 +00001281 put2byte(&data[pbegin], get2byte(&data[pnext]));
1282 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
1283 }else{
drh3aac2dd2004-04-26 14:10:20 +00001284 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +00001285 }
1286 }
drh7e3b0a02001-04-28 16:52:40 +00001287
drh43605152004-05-29 21:46:49 +00001288 /* If the cell content area begins with a freeblock, remove it. */
1289 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
1290 int top;
1291 pbegin = get2byte(&data[hdr+1]);
1292 memcpy(&data[hdr+1], &data[pbegin], 2);
1293 top = get2byte(&data[hdr+5]);
1294 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
drh4b70f112004-05-02 21:12:19 +00001295 }
drh4b70f112004-05-02 21:12:19 +00001296}
1297
1298/*
drh271efa52004-05-30 19:19:05 +00001299** Decode the flags byte (the first byte of the header) for a page
1300** and initialize fields of the MemPage structure accordingly.
1301*/
1302static void decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +00001303 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +00001304
1305 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
1306 pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
1307 pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
1308 pPage->leaf = (flagByte & PTF_LEAF)!=0;
1309 pPage->childPtrSize = 4*(pPage->leaf==0);
1310 pBt = pPage->pBt;
1311 if( flagByte & PTF_LEAFDATA ){
1312 pPage->leafData = 1;
1313 pPage->maxLocal = pBt->maxLeaf;
1314 pPage->minLocal = pBt->minLeaf;
1315 }else{
1316 pPage->leafData = 0;
1317 pPage->maxLocal = pBt->maxLocal;
1318 pPage->minLocal = pBt->minLocal;
1319 }
1320 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
1321}
1322
1323/*
drh7e3b0a02001-04-28 16:52:40 +00001324** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001325**
drhbd03cae2001-06-02 02:40:57 +00001326** The pParent parameter must be a pointer to the MemPage which
drh9e572e62004-04-23 23:43:10 +00001327** is the parent of the page being initialized. The root of a
1328** BTree has no parent and so for that page, pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +00001329**
drh72f82862001-05-24 21:06:34 +00001330** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001331** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001332** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1333** guarantee that the page is well-formed. It only shows that
1334** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001335*/
drh9e572e62004-04-23 23:43:10 +00001336static int initPage(
drh3aac2dd2004-04-26 14:10:20 +00001337 MemPage *pPage, /* The page to be initialized */
drh9e572e62004-04-23 23:43:10 +00001338 MemPage *pParent /* The parent. Might be NULL */
1339){
drh271efa52004-05-30 19:19:05 +00001340 int pc; /* Address of a freeblock within pPage->aData[] */
drh271efa52004-05-30 19:19:05 +00001341 int hdr; /* Offset to beginning of page header */
1342 u8 *data; /* Equal to pPage->aData */
danielk1977aef0bf62005-12-30 16:28:01 +00001343 BtShared *pBt; /* The main btree structure */
drh271efa52004-05-30 19:19:05 +00001344 int usableSize; /* Amount of usable space on each page */
1345 int cellOffset; /* Offset from start of page to first cell pointer */
1346 int nFree; /* Number of unused bytes on the page */
1347 int top; /* First byte of the cell content area */
drh2af926b2001-05-15 00:39:25 +00001348
drh2e38c322004-09-03 18:38:44 +00001349 pBt = pPage->pBt;
1350 assert( pBt!=0 );
1351 assert( pParent==0 || pParent->pBt==pBt );
drha34b6762004-05-07 13:30:42 +00001352 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
drh07d183d2005-05-01 22:52:42 +00001353 assert( pPage->aData == &((unsigned char*)pPage)[-pBt->pageSize] );
drhee696e22004-08-30 16:52:17 +00001354 if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
1355 /* The parent page should never change unless the file is corrupt */
drh49285702005-09-17 15:20:26 +00001356 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001357 }
drh10617cd2004-05-14 15:27:27 +00001358 if( pPage->isInit ) return SQLITE_OK;
drhda200cc2004-05-09 11:51:38 +00001359 if( pPage->pParent==0 && pParent!=0 ){
1360 pPage->pParent = pParent;
drha34b6762004-05-07 13:30:42 +00001361 sqlite3pager_ref(pParent->aData);
drh5e2f8b92001-05-28 00:41:15 +00001362 }
drhde647132004-05-07 17:57:49 +00001363 hdr = pPage->hdrOffset;
drha34b6762004-05-07 13:30:42 +00001364 data = pPage->aData;
drh271efa52004-05-30 19:19:05 +00001365 decodeFlags(pPage, data[hdr]);
drh43605152004-05-29 21:46:49 +00001366 pPage->nOverflow = 0;
drhc8629a12004-05-08 20:07:40 +00001367 pPage->idxShift = 0;
drh2e38c322004-09-03 18:38:44 +00001368 usableSize = pBt->usableSize;
drh43605152004-05-29 21:46:49 +00001369 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
1370 top = get2byte(&data[hdr+5]);
1371 pPage->nCell = get2byte(&data[hdr+3]);
drh2e38c322004-09-03 18:38:44 +00001372 if( pPage->nCell>MX_CELL(pBt) ){
drhee696e22004-08-30 16:52:17 +00001373 /* To many cells for a single page. The page must be corrupt */
drh49285702005-09-17 15:20:26 +00001374 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001375 }
1376 if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
1377 /* All pages must have at least one cell, except for root pages */
drh49285702005-09-17 15:20:26 +00001378 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001379 }
drh9e572e62004-04-23 23:43:10 +00001380
1381 /* Compute the total free space on the page */
drh9e572e62004-04-23 23:43:10 +00001382 pc = get2byte(&data[hdr+1]);
drh43605152004-05-29 21:46:49 +00001383 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
drh9e572e62004-04-23 23:43:10 +00001384 while( pc>0 ){
1385 int next, size;
drhee696e22004-08-30 16:52:17 +00001386 if( pc>usableSize-4 ){
1387 /* Free block is off the page */
drh49285702005-09-17 15:20:26 +00001388 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001389 }
drh9e572e62004-04-23 23:43:10 +00001390 next = get2byte(&data[pc]);
1391 size = get2byte(&data[pc+2]);
drhee696e22004-08-30 16:52:17 +00001392 if( next>0 && next<=pc+size+3 ){
1393 /* Free blocks must be in accending order */
drh49285702005-09-17 15:20:26 +00001394 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001395 }
drh3add3672004-05-15 00:29:24 +00001396 nFree += size;
drh9e572e62004-04-23 23:43:10 +00001397 pc = next;
1398 }
drh3add3672004-05-15 00:29:24 +00001399 pPage->nFree = nFree;
drhee696e22004-08-30 16:52:17 +00001400 if( nFree>=usableSize ){
1401 /* Free space cannot exceed total page size */
drh49285702005-09-17 15:20:26 +00001402 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001403 }
drh9e572e62004-04-23 23:43:10 +00001404
drhde647132004-05-07 17:57:49 +00001405 pPage->isInit = 1;
drhda200cc2004-05-09 11:51:38 +00001406 pageIntegrity(pPage);
drh9e572e62004-04-23 23:43:10 +00001407 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001408}
1409
1410/*
drh8b2f49b2001-06-08 00:21:52 +00001411** Set up a raw page so that it looks like a database page holding
1412** no entries.
drhbd03cae2001-06-02 02:40:57 +00001413*/
drh9e572e62004-04-23 23:43:10 +00001414static void zeroPage(MemPage *pPage, int flags){
1415 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001416 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00001417 int hdr = pPage->hdrOffset;
drh9e572e62004-04-23 23:43:10 +00001418 int first;
1419
drhda200cc2004-05-09 11:51:38 +00001420 assert( sqlite3pager_pagenumber(data)==pPage->pgno );
drh07d183d2005-05-01 22:52:42 +00001421 assert( &data[pBt->pageSize] == (unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +00001422 assert( sqlite3pager_iswriteable(data) );
drhb6f41482004-05-14 01:58:11 +00001423 memset(&data[hdr], 0, pBt->usableSize - hdr);
drh9e572e62004-04-23 23:43:10 +00001424 data[hdr] = flags;
drh43605152004-05-29 21:46:49 +00001425 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
1426 memset(&data[hdr+1], 0, 4);
1427 data[hdr+7] = 0;
1428 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +00001429 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +00001430 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +00001431 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +00001432 pPage->cellOffset = first;
1433 pPage->nOverflow = 0;
drhda200cc2004-05-09 11:51:38 +00001434 pPage->idxShift = 0;
drh43605152004-05-29 21:46:49 +00001435 pPage->nCell = 0;
drhda200cc2004-05-09 11:51:38 +00001436 pPage->isInit = 1;
1437 pageIntegrity(pPage);
drhbd03cae2001-06-02 02:40:57 +00001438}
1439
1440/*
drh3aac2dd2004-04-26 14:10:20 +00001441** Get a page from the pager. Initialize the MemPage.pBt and
1442** MemPage.aData elements if needed.
1443*/
danielk1977aef0bf62005-12-30 16:28:01 +00001444static int getPage(BtShared *pBt, Pgno pgno, MemPage **ppPage){
drh3aac2dd2004-04-26 14:10:20 +00001445 int rc;
1446 unsigned char *aData;
1447 MemPage *pPage;
drha34b6762004-05-07 13:30:42 +00001448 rc = sqlite3pager_get(pBt->pPager, pgno, (void**)&aData);
drh3aac2dd2004-04-26 14:10:20 +00001449 if( rc ) return rc;
drh07d183d2005-05-01 22:52:42 +00001450 pPage = (MemPage*)&aData[pBt->pageSize];
drh3aac2dd2004-04-26 14:10:20 +00001451 pPage->aData = aData;
1452 pPage->pBt = pBt;
1453 pPage->pgno = pgno;
drhde647132004-05-07 17:57:49 +00001454 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
drh3aac2dd2004-04-26 14:10:20 +00001455 *ppPage = pPage;
1456 return SQLITE_OK;
1457}
1458
1459/*
drhde647132004-05-07 17:57:49 +00001460** Get a page from the pager and initialize it. This routine
1461** is just a convenience wrapper around separate calls to
1462** getPage() and initPage().
1463*/
1464static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +00001465 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +00001466 Pgno pgno, /* Number of the page to get */
1467 MemPage **ppPage, /* Write the page pointer here */
1468 MemPage *pParent /* Parent of the page */
1469){
1470 int rc;
drhee696e22004-08-30 16:52:17 +00001471 if( pgno==0 ){
drh49285702005-09-17 15:20:26 +00001472 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001473 }
drhde647132004-05-07 17:57:49 +00001474 rc = getPage(pBt, pgno, ppPage);
drh10617cd2004-05-14 15:27:27 +00001475 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
drhde647132004-05-07 17:57:49 +00001476 rc = initPage(*ppPage, pParent);
1477 }
1478 return rc;
1479}
1480
1481/*
drh3aac2dd2004-04-26 14:10:20 +00001482** Release a MemPage. This should be called once for each prior
1483** call to getPage.
1484*/
drh4b70f112004-05-02 21:12:19 +00001485static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001486 if( pPage ){
1487 assert( pPage->aData );
1488 assert( pPage->pBt );
drh07d183d2005-05-01 22:52:42 +00001489 assert( &pPage->aData[pPage->pBt->pageSize]==(unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +00001490 sqlite3pager_unref(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00001491 }
1492}
1493
1494/*
drh72f82862001-05-24 21:06:34 +00001495** This routine is called when the reference count for a page
1496** reaches zero. We need to unref the pParent pointer when that
1497** happens.
1498*/
drhb6f41482004-05-14 01:58:11 +00001499static void pageDestructor(void *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +00001500 MemPage *pPage;
1501 assert( (pageSize & 7)==0 );
1502 pPage = (MemPage*)&((char*)pData)[pageSize];
drh72f82862001-05-24 21:06:34 +00001503 if( pPage->pParent ){
1504 MemPage *pParent = pPage->pParent;
1505 pPage->pParent = 0;
drha34b6762004-05-07 13:30:42 +00001506 releasePage(pParent);
drh72f82862001-05-24 21:06:34 +00001507 }
drh3aac2dd2004-04-26 14:10:20 +00001508 pPage->isInit = 0;
drh72f82862001-05-24 21:06:34 +00001509}
1510
1511/*
drha6abd042004-06-09 17:37:22 +00001512** During a rollback, when the pager reloads information into the cache
1513** so that the cache is restored to its original state at the start of
1514** the transaction, for each page restored this routine is called.
1515**
1516** This routine needs to reset the extra data section at the end of the
1517** page to agree with the restored data.
1518*/
1519static void pageReinit(void *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +00001520 MemPage *pPage;
1521 assert( (pageSize & 7)==0 );
1522 pPage = (MemPage*)&((char*)pData)[pageSize];
drha6abd042004-06-09 17:37:22 +00001523 if( pPage->isInit ){
1524 pPage->isInit = 0;
1525 initPage(pPage, pPage->pParent);
1526 }
1527}
1528
1529/*
drhad3e0102004-09-03 23:32:18 +00001530** Open a database file.
1531**
drh382c0242001-10-06 16:33:02 +00001532** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001533** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001534** database file will be deleted when sqlite3BtreeClose() is called.
drha059ad02001-04-17 20:09:11 +00001535*/
drh23e11ca2004-05-04 17:27:28 +00001536int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001537 const char *zFilename, /* Name of the file containing the BTree database */
danielk1977aef0bf62005-12-30 16:28:01 +00001538 sqlite3 *pSqlite, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001539 Btree **ppBtree, /* Pointer to new Btree object written here */
drh90f5ecb2004-07-22 01:19:35 +00001540 int flags /* Options */
drh6019e162001-07-02 17:51:45 +00001541){
danielk1977aef0bf62005-12-30 16:28:01 +00001542 BtShared *pBt; /* Shared part of btree structure */
1543 Btree *p; /* Handle to return */
drha34b6762004-05-07 13:30:42 +00001544 int rc;
drh90f5ecb2004-07-22 01:19:35 +00001545 int nReserve;
1546 unsigned char zDbHeader[100];
danielk1977da184232006-01-05 11:34:32 +00001547#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +00001548 SqliteTsd *pTsd = sqlite3Tsd();
danielk1977da184232006-01-05 11:34:32 +00001549#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001550
1551 /* Set the variable isMemdb to true for an in-memory database, or
1552 ** false for a file-based database. This symbol is only required if
1553 ** either of the shared-data or autovacuum features are compiled
1554 ** into the library.
1555 */
1556#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1557 #ifdef SQLITE_OMIT_MEMORYDB
1558 const int isMemdb = !zFilename;
1559 #else
1560 const int isMemdb = !zFilename || (strcmp(zFilename, ":memory:")?0:1);
1561 #endif
1562#endif
1563
1564 p = sqliteMalloc(sizeof(Btree));
1565 if( !p ){
1566 return SQLITE_NOMEM;
1567 }
1568 p->inTrans = TRANS_NONE;
1569 p->pSqlite = pSqlite;
1570
1571 /* Try to find an existing Btree structure opened on zFilename. */
drh198bf392006-01-06 21:52:49 +00001572#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
danielk1977aef0bf62005-12-30 16:28:01 +00001573 if( pTsd->useSharedData && zFilename && !isMemdb ){
drh66560ad2006-01-06 14:32:19 +00001574 char *zFullPathname = sqlite3OsFullPathname(zFilename);
danielk1977aef0bf62005-12-30 16:28:01 +00001575 if( !zFullPathname ){
1576 sqliteFree(p);
1577 return SQLITE_NOMEM;
1578 }
1579 for(pBt=pTsd->pBtree; pBt; pBt=pBt->pNext){
1580 if( 0==strcmp(zFullPathname, sqlite3pager_filename(pBt->pPager)) ){
1581 p->pBt = pBt;
1582 *ppBtree = p;
1583 pBt->nRef++;
1584 sqliteFree(zFullPathname);
1585 return SQLITE_OK;
1586 }
1587 }
1588 sqliteFree(zFullPathname);
1589 }
1590#endif
drha059ad02001-04-17 20:09:11 +00001591
drhd62d3d02003-01-24 12:14:20 +00001592 /*
1593 ** The following asserts make sure that structures used by the btree are
1594 ** the right size. This is to guard against size changes that result
1595 ** when compiling on a different architecture.
1596 */
drh4a1c3802004-05-12 15:15:47 +00001597 assert( sizeof(i64)==8 );
drh9e572e62004-04-23 23:43:10 +00001598 assert( sizeof(u64)==8 );
drhd62d3d02003-01-24 12:14:20 +00001599 assert( sizeof(u32)==4 );
1600 assert( sizeof(u16)==2 );
1601 assert( sizeof(Pgno)==4 );
drhd62d3d02003-01-24 12:14:20 +00001602
drha059ad02001-04-17 20:09:11 +00001603 pBt = sqliteMalloc( sizeof(*pBt) );
1604 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +00001605 *ppBtree = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00001606 sqliteFree(p);
drha059ad02001-04-17 20:09:11 +00001607 return SQLITE_NOMEM;
1608 }
drh7bec5052005-02-06 02:45:41 +00001609 rc = sqlite3pager_open(&pBt->pPager, zFilename, EXTRA_SIZE, flags);
drha059ad02001-04-17 20:09:11 +00001610 if( rc!=SQLITE_OK ){
drha34b6762004-05-07 13:30:42 +00001611 if( pBt->pPager ) sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001612 sqliteFree(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00001613 sqliteFree(p);
drha059ad02001-04-17 20:09:11 +00001614 *ppBtree = 0;
1615 return rc;
1616 }
danielk1977aef0bf62005-12-30 16:28:01 +00001617 p->pBt = pBt;
1618
drha34b6762004-05-07 13:30:42 +00001619 sqlite3pager_set_destructor(pBt->pPager, pageDestructor);
drha6abd042004-06-09 17:37:22 +00001620 sqlite3pager_set_reiniter(pBt->pPager, pageReinit);
drha059ad02001-04-17 20:09:11 +00001621 pBt->pCursor = 0;
drha34b6762004-05-07 13:30:42 +00001622 pBt->pPage1 = 0;
1623 pBt->readOnly = sqlite3pager_isreadonly(pBt->pPager);
drh90f5ecb2004-07-22 01:19:35 +00001624 sqlite3pager_read_fileheader(pBt->pPager, sizeof(zDbHeader), zDbHeader);
1625 pBt->pageSize = get2byte(&zDbHeader[16]);
drh07d183d2005-05-01 22:52:42 +00001626 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1627 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
drh90f5ecb2004-07-22 01:19:35 +00001628 pBt->pageSize = SQLITE_DEFAULT_PAGE_SIZE;
1629 pBt->maxEmbedFrac = 64; /* 25% */
1630 pBt->minEmbedFrac = 32; /* 12.5% */
1631 pBt->minLeafFrac = 32; /* 12.5% */
drheee46cf2004-11-06 00:02:48 +00001632#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197703aded42004-11-22 05:26:27 +00001633 /* If the magic name ":memory:" will create an in-memory database, then
1634 ** do not set the auto-vacuum flag, even if SQLITE_DEFAULT_AUTOVACUUM
1635 ** is true. On the other hand, if SQLITE_OMIT_MEMORYDB has been defined,
1636 ** then ":memory:" is just a regular file-name. Respect the auto-vacuum
1637 ** default in this case.
1638 */
danielk1977aef0bf62005-12-30 16:28:01 +00001639 if( zFilename && !isMemdb ){
danielk1977951af802004-11-05 15:45:09 +00001640 pBt->autoVacuum = SQLITE_DEFAULT_AUTOVACUUM;
1641 }
drheee46cf2004-11-06 00:02:48 +00001642#endif
drh90f5ecb2004-07-22 01:19:35 +00001643 nReserve = 0;
1644 }else{
1645 nReserve = zDbHeader[20];
1646 pBt->maxEmbedFrac = zDbHeader[21];
1647 pBt->minEmbedFrac = zDbHeader[22];
1648 pBt->minLeafFrac = zDbHeader[23];
1649 pBt->pageSizeFixed = 1;
danielk1977951af802004-11-05 15:45:09 +00001650#ifndef SQLITE_OMIT_AUTOVACUUM
1651 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1652#endif
drh90f5ecb2004-07-22 01:19:35 +00001653 }
1654 pBt->usableSize = pBt->pageSize - nReserve;
drh07d183d2005-05-01 22:52:42 +00001655 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
drh90f5ecb2004-07-22 01:19:35 +00001656 sqlite3pager_set_pagesize(pBt->pPager, pBt->pageSize);
danielk1977aef0bf62005-12-30 16:28:01 +00001657
1658#ifndef SQLITE_OMIT_SHARED_CACHE
1659 /* Add the new btree to the linked list starting at SqliteTsd.pBtree */
1660 if( pTsd->useSharedData && zFilename && !isMemdb ){
1661 pBt->pNext = pTsd->pBtree;
1662 pTsd->pBtree = pBt;
1663 }
danielk1977aef0bf62005-12-30 16:28:01 +00001664#endif
danielk1977da184232006-01-05 11:34:32 +00001665 pBt->nRef = 1;
danielk1977aef0bf62005-12-30 16:28:01 +00001666 *ppBtree = p;
drha059ad02001-04-17 20:09:11 +00001667 return SQLITE_OK;
1668}
1669
1670/*
1671** Close an open database and invalidate all cursors.
1672*/
danielk1977aef0bf62005-12-30 16:28:01 +00001673int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00001674 BtShared *pBt = p->pBt;
1675 BtCursor *pCur;
1676
danielk1977da184232006-01-05 11:34:32 +00001677#ifndef SQLITE_OMIT_SHARED_CACHE
1678 SqliteTsd *pTsd = sqlite3Tsd();
1679#endif
1680
danielk1977aef0bf62005-12-30 16:28:01 +00001681 /* Drop any table-locks */
1682 unlockAllTables(p);
1683
1684 /* Close all cursors opened via this handle. */
1685 pCur = pBt->pCursor;
1686 while( pCur ){
1687 BtCursor *pTmp = pCur;
1688 pCur = pCur->pNext;
1689 if( pTmp->pBtree==p ){
1690 sqlite3BtreeCloseCursor(pTmp);
1691 }
drha059ad02001-04-17 20:09:11 +00001692 }
danielk1977aef0bf62005-12-30 16:28:01 +00001693
1694 sqliteFree(p);
1695
1696#ifndef SQLITE_OMIT_SHARED_CACHE
1697 /* If there are still other outstanding references to the shared-btree
1698 ** structure, return now. The remainder of this procedure cleans
1699 ** up the shared-btree.
1700 */
1701 assert( pBt->nRef>0 );
1702 pBt->nRef--;
1703 if( pBt->nRef ){
1704 return SQLITE_OK;
1705 }
1706
1707 /* Remove the shared-btree from the thread wide list */
1708 if( pTsd->pBtree==pBt ){
1709 pTsd->pBtree = pBt->pNext;
1710 }else{
1711 BtShared *pPrev;
1712 for(pPrev=pTsd->pBtree; pPrev && pPrev->pNext!=pBt; pPrev=pPrev->pNext);
1713 if( pPrev ){
1714 pPrev->pNext = pBt->pNext;
1715 }
1716 }
1717#endif
1718
1719 /* Close the pager and free the shared-btree structure */
1720 assert( !pBt->pCursor );
drha34b6762004-05-07 13:30:42 +00001721 sqlite3pager_close(pBt->pPager);
danielk1977da184232006-01-05 11:34:32 +00001722 if( pBt->xFreeSchema && pBt->pSchema ){
1723 pBt->xFreeSchema(pBt->pSchema);
1724 }
danielk1977de0fe3e2006-01-06 06:33:12 +00001725 sqliteFree(pBt->pSchema);
drha059ad02001-04-17 20:09:11 +00001726 sqliteFree(pBt);
1727 return SQLITE_OK;
1728}
1729
1730/*
drh90f5ecb2004-07-22 01:19:35 +00001731** Change the busy handler callback function.
1732*/
danielk1977aef0bf62005-12-30 16:28:01 +00001733int sqlite3BtreeSetBusyHandler(Btree *p, BusyHandler *pHandler){
1734 BtShared *pBt = p->pBt;
drhb8ef32c2005-03-14 02:01:49 +00001735 pBt->pBusyHandler = pHandler;
drh90f5ecb2004-07-22 01:19:35 +00001736 sqlite3pager_set_busyhandler(pBt->pPager, pHandler);
1737 return SQLITE_OK;
1738}
1739
1740/*
drhda47d772002-12-02 04:25:19 +00001741** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001742**
1743** The maximum number of cache pages is set to the absolute
1744** value of mxPage. If mxPage is negative, the pager will
1745** operate asynchronously - it will not stop to do fsync()s
1746** to insure data is written to the disk surface before
1747** continuing. Transactions still work if synchronous is off,
1748** and the database cannot be corrupted if this program
1749** crashes. But if the operating system crashes or there is
1750** an abrupt power failure when synchronous is off, the database
1751** could be left in an inconsistent and unrecoverable state.
1752** Synchronous is on by default so database corruption is not
1753** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001754*/
danielk1977aef0bf62005-12-30 16:28:01 +00001755int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
1756 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00001757 sqlite3pager_set_cachesize(pBt->pPager, mxPage);
drhf57b14a2001-09-14 18:54:08 +00001758 return SQLITE_OK;
1759}
1760
1761/*
drh973b6e32003-02-12 14:09:42 +00001762** Change the way data is synced to disk in order to increase or decrease
1763** how well the database resists damage due to OS crashes and power
1764** failures. Level 1 is the same as asynchronous (no syncs() occur and
1765** there is a high probability of damage) Level 2 is the default. There
1766** is a very low but non-zero probability of damage. Level 3 reduces the
1767** probability of damage to near zero but with a write performance reduction.
1768*/
danielk197793758c82005-01-21 08:13:14 +00001769#ifndef SQLITE_OMIT_PAGER_PRAGMAS
danielk1977aef0bf62005-12-30 16:28:01 +00001770int sqlite3BtreeSetSafetyLevel(Btree *p, int level){
1771 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00001772 sqlite3pager_set_safety_level(pBt->pPager, level);
drh973b6e32003-02-12 14:09:42 +00001773 return SQLITE_OK;
1774}
danielk197793758c82005-01-21 08:13:14 +00001775#endif
drh973b6e32003-02-12 14:09:42 +00001776
drh2c8997b2005-08-27 16:36:48 +00001777/*
1778** Return TRUE if the given btree is set to safety level 1. In other
1779** words, return TRUE if no sync() occurs on the disk files.
1780*/
danielk1977aef0bf62005-12-30 16:28:01 +00001781int sqlite3BtreeSyncDisabled(Btree *p){
1782 BtShared *pBt = p->pBt;
drh2c8997b2005-08-27 16:36:48 +00001783 assert( pBt && pBt->pPager );
1784 return sqlite3pager_nosync(pBt->pPager);
1785}
1786
danielk1977576ec6b2005-01-21 11:55:25 +00001787#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001788/*
drh90f5ecb2004-07-22 01:19:35 +00001789** Change the default pages size and the number of reserved bytes per page.
drh06f50212004-11-02 14:24:33 +00001790**
1791** The page size must be a power of 2 between 512 and 65536. If the page
1792** size supplied does not meet this constraint then the page size is not
1793** changed.
1794**
1795** Page sizes are constrained to be a power of two so that the region
1796** of the database file used for locking (beginning at PENDING_BYTE,
1797** the first byte past the 1GB boundary, 0x40000000) needs to occur
1798** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001799**
1800** If parameter nReserve is less than zero, then the number of reserved
1801** bytes per page is left unchanged.
drh90f5ecb2004-07-22 01:19:35 +00001802*/
danielk1977aef0bf62005-12-30 16:28:01 +00001803int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
1804 BtShared *pBt = p->pBt;
drh90f5ecb2004-07-22 01:19:35 +00001805 if( pBt->pageSizeFixed ){
1806 return SQLITE_READONLY;
1807 }
1808 if( nReserve<0 ){
1809 nReserve = pBt->pageSize - pBt->usableSize;
1810 }
drh06f50212004-11-02 14:24:33 +00001811 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
1812 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00001813 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00001814 assert( !pBt->pPage1 && !pBt->pCursor );
drh1c7880e2005-05-20 20:01:55 +00001815 pBt->pageSize = sqlite3pager_set_pagesize(pBt->pPager, pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001816 }
1817 pBt->usableSize = pBt->pageSize - nReserve;
1818 return SQLITE_OK;
1819}
1820
1821/*
1822** Return the currently defined page size
1823*/
danielk1977aef0bf62005-12-30 16:28:01 +00001824int sqlite3BtreeGetPageSize(Btree *p){
1825 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00001826}
danielk1977aef0bf62005-12-30 16:28:01 +00001827int sqlite3BtreeGetReserve(Btree *p){
1828 return p->pBt->pageSize - p->pBt->usableSize;
drh2011d5f2004-07-22 02:40:37 +00001829}
danielk1977576ec6b2005-01-21 11:55:25 +00001830#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00001831
1832/*
danielk1977951af802004-11-05 15:45:09 +00001833** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
1834** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
1835** is disabled. The default value for the auto-vacuum property is
1836** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
1837*/
danielk1977aef0bf62005-12-30 16:28:01 +00001838int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
1839 BtShared *pBt = p->pBt;;
danielk1977951af802004-11-05 15:45:09 +00001840#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001841 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00001842#else
1843 if( pBt->pageSizeFixed ){
1844 return SQLITE_READONLY;
1845 }
1846 pBt->autoVacuum = (autoVacuum?1:0);
1847 return SQLITE_OK;
1848#endif
1849}
1850
1851/*
1852** Return the value of the 'auto-vacuum' property. If auto-vacuum is
1853** enabled 1 is returned. Otherwise 0.
1854*/
danielk1977aef0bf62005-12-30 16:28:01 +00001855int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00001856#ifdef SQLITE_OMIT_AUTOVACUUM
1857 return 0;
1858#else
danielk1977aef0bf62005-12-30 16:28:01 +00001859 return p->pBt->autoVacuum;
danielk1977951af802004-11-05 15:45:09 +00001860#endif
1861}
1862
1863
1864/*
drha34b6762004-05-07 13:30:42 +00001865** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001866** also acquire a readlock on that file.
1867**
1868** SQLITE_OK is returned on success. If the file is not a
1869** well-formed database file, then SQLITE_CORRUPT is returned.
1870** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
1871** is returned if we run out of memory. SQLITE_PROTOCOL is returned
1872** if there is a locking protocol violation.
1873*/
danielk1977aef0bf62005-12-30 16:28:01 +00001874static int lockBtree(BtShared *pBt){
drh07d183d2005-05-01 22:52:42 +00001875 int rc, pageSize;
drh3aac2dd2004-04-26 14:10:20 +00001876 MemPage *pPage1;
drha34b6762004-05-07 13:30:42 +00001877 if( pBt->pPage1 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001878 rc = getPage(pBt, 1, &pPage1);
drh306dc212001-05-21 13:45:10 +00001879 if( rc!=SQLITE_OK ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00001880
drh306dc212001-05-21 13:45:10 +00001881
1882 /* Do some checking to help insure the file we opened really is
1883 ** a valid database file.
1884 */
drhb6f41482004-05-14 01:58:11 +00001885 rc = SQLITE_NOTADB;
drha34b6762004-05-07 13:30:42 +00001886 if( sqlite3pager_pagecount(pBt->pPager)>0 ){
drhb6f41482004-05-14 01:58:11 +00001887 u8 *page1 = pPage1->aData;
1888 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001889 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001890 }
drhb6f41482004-05-14 01:58:11 +00001891 if( page1[18]>1 || page1[19]>1 ){
1892 goto page1_init_failed;
1893 }
drh07d183d2005-05-01 22:52:42 +00001894 pageSize = get2byte(&page1[16]);
1895 if( ((pageSize-1)&pageSize)!=0 ){
1896 goto page1_init_failed;
1897 }
1898 assert( (pageSize & 7)==0 );
1899 pBt->pageSize = pageSize;
1900 pBt->usableSize = pageSize - page1[20];
drhb6f41482004-05-14 01:58:11 +00001901 if( pBt->usableSize<500 ){
1902 goto page1_init_failed;
1903 }
1904 pBt->maxEmbedFrac = page1[21];
1905 pBt->minEmbedFrac = page1[22];
1906 pBt->minLeafFrac = page1[23];
drh057cd3a2005-02-15 16:23:02 +00001907#ifndef SQLITE_OMIT_AUTOVACUUM
1908 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
1909#endif
drh306dc212001-05-21 13:45:10 +00001910 }
drhb6f41482004-05-14 01:58:11 +00001911
1912 /* maxLocal is the maximum amount of payload to store locally for
1913 ** a cell. Make sure it is small enough so that at least minFanout
1914 ** cells can will fit on one page. We assume a 10-byte page header.
1915 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001916 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001917 ** 4-byte child pointer
1918 ** 9-byte nKey value
1919 ** 4-byte nData value
1920 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001921 ** So a cell consists of a 2-byte poiner, a header which is as much as
1922 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1923 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001924 */
drh43605152004-05-29 21:46:49 +00001925 pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
1926 pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
1927 pBt->maxLeaf = pBt->usableSize - 35;
1928 pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
drhb6f41482004-05-14 01:58:11 +00001929 if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
1930 goto page1_init_failed;
1931 }
drh2e38c322004-09-03 18:38:44 +00001932 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001933 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001934 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001935
drh72f82862001-05-24 21:06:34 +00001936page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001937 releasePage(pPage1);
1938 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001939 return rc;
drh306dc212001-05-21 13:45:10 +00001940}
1941
1942/*
drhb8ef32c2005-03-14 02:01:49 +00001943** This routine works like lockBtree() except that it also invokes the
1944** busy callback if there is lock contention.
1945*/
danielk1977aef0bf62005-12-30 16:28:01 +00001946static int lockBtreeWithRetry(Btree *pRef){
drhb8ef32c2005-03-14 02:01:49 +00001947 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00001948 if( pRef->inTrans==TRANS_NONE ){
1949 u8 inTransaction = pRef->pBt->inTransaction;
1950 btreeIntegrity(pRef);
1951 rc = sqlite3BtreeBeginTrans(pRef, 0);
1952 pRef->pBt->inTransaction = inTransaction;
1953 pRef->inTrans = TRANS_NONE;
1954 if( rc==SQLITE_OK ){
1955 pRef->pBt->nTransaction--;
1956 }
1957 btreeIntegrity(pRef);
drhb8ef32c2005-03-14 02:01:49 +00001958 }
1959 return rc;
1960}
1961
1962
1963/*
drhb8ca3072001-12-05 00:21:20 +00001964** If there are no outstanding cursors and we are not in the middle
1965** of a transaction but there is a read lock on the database, then
1966** this routine unrefs the first page of the database file which
1967** has the effect of releasing the read lock.
1968**
1969** If there are any outstanding cursors, this routine is a no-op.
1970**
1971** If there is a transaction in progress, this routine is a no-op.
1972*/
danielk1977aef0bf62005-12-30 16:28:01 +00001973static void unlockBtreeIfUnused(BtShared *pBt){
1974 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
drh51c6d962004-06-06 00:42:25 +00001975 if( pBt->pPage1->aData==0 ){
1976 MemPage *pPage = pBt->pPage1;
drh2646da72005-12-09 20:02:05 +00001977 pPage->aData = &((u8*)pPage)[-pBt->pageSize];
drh51c6d962004-06-06 00:42:25 +00001978 pPage->pBt = pBt;
1979 pPage->pgno = 1;
1980 }
drh3aac2dd2004-04-26 14:10:20 +00001981 releasePage(pBt->pPage1);
1982 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00001983 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001984 }
1985}
1986
1987/*
drh9e572e62004-04-23 23:43:10 +00001988** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001989** file.
drh8b2f49b2001-06-08 00:21:52 +00001990*/
danielk1977aef0bf62005-12-30 16:28:01 +00001991static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00001992 MemPage *pP1;
1993 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001994 int rc;
drhde647132004-05-07 17:57:49 +00001995 if( sqlite3pager_pagecount(pBt->pPager)>0 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001996 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00001997 assert( pP1!=0 );
1998 data = pP1->aData;
drha34b6762004-05-07 13:30:42 +00001999 rc = sqlite3pager_write(data);
drh8b2f49b2001-06-08 00:21:52 +00002000 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00002001 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
2002 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00002003 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00002004 data[18] = 1;
2005 data[19] = 1;
drhb6f41482004-05-14 01:58:11 +00002006 data[20] = pBt->pageSize - pBt->usableSize;
2007 data[21] = pBt->maxEmbedFrac;
2008 data[22] = pBt->minEmbedFrac;
2009 data[23] = pBt->minLeafFrac;
2010 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00002011 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00002012 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00002013#ifndef SQLITE_OMIT_AUTOVACUUM
2014 if( pBt->autoVacuum ){
2015 put4byte(&data[36 + 4*4], 1);
2016 }
2017#endif
drh8b2f49b2001-06-08 00:21:52 +00002018 return SQLITE_OK;
2019}
2020
2021/*
danielk1977ee5741e2004-05-31 10:01:34 +00002022** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00002023** is started if the second argument is nonzero, otherwise a read-
2024** transaction. If the second argument is 2 or more and exclusive
2025** transaction is started, meaning that no other process is allowed
2026** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00002027** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00002028** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00002029**
danielk1977ee5741e2004-05-31 10:01:34 +00002030** A write-transaction must be started before attempting any
2031** changes to the database. None of the following routines
2032** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00002033**
drh23e11ca2004-05-04 17:27:28 +00002034** sqlite3BtreeCreateTable()
2035** sqlite3BtreeCreateIndex()
2036** sqlite3BtreeClearTable()
2037** sqlite3BtreeDropTable()
2038** sqlite3BtreeInsert()
2039** sqlite3BtreeDelete()
2040** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00002041**
drhb8ef32c2005-03-14 02:01:49 +00002042** If an initial attempt to acquire the lock fails because of lock contention
2043** and the database was previously unlocked, then invoke the busy handler
2044** if there is one. But if there was previously a read-lock, do not
2045** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
2046** returned when there is already a read-lock in order to avoid a deadlock.
2047**
2048** Suppose there are two processes A and B. A has a read lock and B has
2049** a reserved lock. B tries to promote to exclusive but is blocked because
2050** of A's read lock. A tries to promote to reserved but is blocked by B.
2051** One or the other of the two processes must give way or there can be
2052** no progress. By returning SQLITE_BUSY and not invoking the busy callback
2053** when A already has a read lock, we encourage A to give up and let B
2054** proceed.
drha059ad02001-04-17 20:09:11 +00002055*/
danielk1977aef0bf62005-12-30 16:28:01 +00002056int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
2057 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00002058 int rc = SQLITE_OK;
2059
danielk1977aef0bf62005-12-30 16:28:01 +00002060 btreeIntegrity(p);
2061
danielk1977ee5741e2004-05-31 10:01:34 +00002062 /* If the btree is already in a write-transaction, or it
2063 ** is already in a read-transaction and a read-transaction
2064 ** is requested, this is a no-op.
2065 */
danielk1977aef0bf62005-12-30 16:28:01 +00002066 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
danielk1977ee5741e2004-05-31 10:01:34 +00002067 return SQLITE_OK;
2068 }
drhb8ef32c2005-03-14 02:01:49 +00002069
2070 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00002071 if( pBt->readOnly && wrflag ){
2072 return SQLITE_READONLY;
2073 }
2074
danielk1977aef0bf62005-12-30 16:28:01 +00002075 /* If another database handle has already opened a write transaction
2076 ** on this shared-btree structure and a second write transaction is
2077 ** requested, return SQLITE_BUSY.
2078 */
2079 if( pBt->inTransaction==TRANS_WRITE && wrflag ){
2080 return SQLITE_BUSY;
2081 }
2082
drhb8ef32c2005-03-14 02:01:49 +00002083 do {
2084 if( pBt->pPage1==0 ){
2085 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +00002086 }
drhb8ef32c2005-03-14 02:01:49 +00002087
2088 if( rc==SQLITE_OK && wrflag ){
2089 rc = sqlite3pager_begin(pBt->pPage1->aData, wrflag>1);
2090 if( rc==SQLITE_OK ){
2091 rc = newDatabase(pBt);
2092 }
2093 }
2094
2095 if( rc==SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00002096 if( wrflag ) pBt->inStmt = 0;
2097 }else{
2098 unlockBtreeIfUnused(pBt);
2099 }
danielk1977aef0bf62005-12-30 16:28:01 +00002100 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
drha4afb652005-07-09 02:16:02 +00002101 sqlite3InvokeBusyHandler(pBt->pBusyHandler) );
danielk1977aef0bf62005-12-30 16:28:01 +00002102
2103 if( rc==SQLITE_OK ){
2104 if( p->inTrans==TRANS_NONE ){
2105 pBt->nTransaction++;
2106 }
2107 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2108 if( p->inTrans>pBt->inTransaction ){
2109 pBt->inTransaction = p->inTrans;
2110 }
2111 }
2112
2113 btreeIntegrity(p);
drhb8ca3072001-12-05 00:21:20 +00002114 return rc;
drha059ad02001-04-17 20:09:11 +00002115}
2116
danielk1977687566d2004-11-02 12:56:41 +00002117#ifndef SQLITE_OMIT_AUTOVACUUM
2118
2119/*
2120** Set the pointer-map entries for all children of page pPage. Also, if
2121** pPage contains cells that point to overflow pages, set the pointer
2122** map entries for the overflow pages as well.
2123*/
2124static int setChildPtrmaps(MemPage *pPage){
2125 int i; /* Counter variable */
2126 int nCell; /* Number of cells in page pPage */
2127 int rc = SQLITE_OK; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00002128 BtShared *pBt = pPage->pBt;
danielk1977687566d2004-11-02 12:56:41 +00002129 int isInitOrig = pPage->isInit;
2130 Pgno pgno = pPage->pgno;
2131
2132 initPage(pPage, 0);
2133 nCell = pPage->nCell;
2134
2135 for(i=0; i<nCell; i++){
danielk1977687566d2004-11-02 12:56:41 +00002136 u8 *pCell = findCell(pPage, i);
2137
danielk197726836652005-01-17 01:33:13 +00002138 rc = ptrmapPutOvflPtr(pPage, pCell);
2139 if( rc!=SQLITE_OK ){
2140 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002141 }
danielk197726836652005-01-17 01:33:13 +00002142
danielk1977687566d2004-11-02 12:56:41 +00002143 if( !pPage->leaf ){
2144 Pgno childPgno = get4byte(pCell);
2145 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
2146 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
2147 }
2148 }
2149
2150 if( !pPage->leaf ){
2151 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
2152 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
2153 }
2154
2155set_child_ptrmaps_out:
2156 pPage->isInit = isInitOrig;
2157 return rc;
2158}
2159
2160/*
2161** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
2162** page, is a pointer to page iFrom. Modify this pointer so that it points to
2163** iTo. Parameter eType describes the type of pointer to be modified, as
2164** follows:
2165**
2166** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2167** page of pPage.
2168**
2169** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2170** page pointed to by one of the cells on pPage.
2171**
2172** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2173** overflow page in the list.
2174*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00002175static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
danielk1977687566d2004-11-02 12:56:41 +00002176 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00002177 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00002178 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00002179 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002180 }
danielk1977f78fc082004-11-02 14:40:32 +00002181 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00002182 }else{
2183 int isInitOrig = pPage->isInit;
2184 int i;
2185 int nCell;
2186
2187 initPage(pPage, 0);
2188 nCell = pPage->nCell;
2189
danielk1977687566d2004-11-02 12:56:41 +00002190 for(i=0; i<nCell; i++){
2191 u8 *pCell = findCell(pPage, i);
2192 if( eType==PTRMAP_OVERFLOW1 ){
2193 CellInfo info;
2194 parseCellPtr(pPage, pCell, &info);
2195 if( info.iOverflow ){
2196 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
2197 put4byte(&pCell[info.iOverflow], iTo);
2198 break;
2199 }
2200 }
2201 }else{
2202 if( get4byte(pCell)==iFrom ){
2203 put4byte(pCell, iTo);
2204 break;
2205 }
2206 }
2207 }
2208
2209 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00002210 if( eType!=PTRMAP_BTREE ||
2211 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00002212 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002213 }
danielk1977687566d2004-11-02 12:56:41 +00002214 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
2215 }
2216
2217 pPage->isInit = isInitOrig;
2218 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002219 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002220}
2221
danielk1977003ba062004-11-04 02:57:33 +00002222
danielk19777701e812005-01-10 12:59:51 +00002223/*
2224** Move the open database page pDbPage to location iFreePage in the
2225** database. The pDbPage reference remains valid.
2226*/
danielk1977003ba062004-11-04 02:57:33 +00002227static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00002228 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00002229 MemPage *pDbPage, /* Open page to move */
2230 u8 eType, /* Pointer map 'type' entry for pDbPage */
2231 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
2232 Pgno iFreePage /* The location to move pDbPage to */
danielk1977003ba062004-11-04 02:57:33 +00002233){
2234 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
2235 Pgno iDbPage = pDbPage->pgno;
2236 Pager *pPager = pBt->pPager;
2237 int rc;
2238
danielk1977a0bf2652004-11-04 14:30:04 +00002239 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
2240 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
danielk1977003ba062004-11-04 02:57:33 +00002241
2242 /* Move page iDbPage from it's current location to page number iFreePage */
2243 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
2244 iDbPage, iFreePage, iPtrPage, eType));
2245 rc = sqlite3pager_movepage(pPager, pDbPage->aData, iFreePage);
2246 if( rc!=SQLITE_OK ){
2247 return rc;
2248 }
2249 pDbPage->pgno = iFreePage;
2250
2251 /* If pDbPage was a btree-page, then it may have child pages and/or cells
2252 ** that point to overflow pages. The pointer map entries for all these
2253 ** pages need to be changed.
2254 **
2255 ** If pDbPage is an overflow page, then the first 4 bytes may store a
2256 ** pointer to a subsequent overflow page. If this is the case, then
2257 ** the pointer map needs to be updated for the subsequent overflow page.
2258 */
danielk1977a0bf2652004-11-04 14:30:04 +00002259 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00002260 rc = setChildPtrmaps(pDbPage);
2261 if( rc!=SQLITE_OK ){
2262 return rc;
2263 }
2264 }else{
2265 Pgno nextOvfl = get4byte(pDbPage->aData);
2266 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00002267 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
2268 if( rc!=SQLITE_OK ){
2269 return rc;
2270 }
2271 }
2272 }
2273
2274 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
2275 ** that it points at iFreePage. Also fix the pointer map entry for
2276 ** iPtrPage.
2277 */
danielk1977a0bf2652004-11-04 14:30:04 +00002278 if( eType!=PTRMAP_ROOTPAGE ){
2279 rc = getPage(pBt, iPtrPage, &pPtrPage);
2280 if( rc!=SQLITE_OK ){
2281 return rc;
2282 }
2283 rc = sqlite3pager_write(pPtrPage->aData);
2284 if( rc!=SQLITE_OK ){
2285 releasePage(pPtrPage);
2286 return rc;
2287 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002288 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00002289 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002290 if( rc==SQLITE_OK ){
2291 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
2292 }
danielk1977003ba062004-11-04 02:57:33 +00002293 }
danielk1977003ba062004-11-04 02:57:33 +00002294 return rc;
2295}
2296
danielk1977687566d2004-11-02 12:56:41 +00002297/* Forward declaration required by autoVacuumCommit(). */
danielk1977aef0bf62005-12-30 16:28:01 +00002298static int allocatePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00002299
2300/*
2301** This routine is called prior to sqlite3pager_commit when a transaction
2302** is commited for an auto-vacuum database.
2303*/
danielk1977aef0bf62005-12-30 16:28:01 +00002304static int autoVacuumCommit(BtShared *pBt, Pgno *nTrunc){
danielk1977687566d2004-11-02 12:56:41 +00002305 Pager *pPager = pBt->pPager;
2306 Pgno nFreeList; /* Number of pages remaining on the free-list. */
danielk1977a19df672004-11-03 11:37:07 +00002307 int nPtrMap; /* Number of pointer-map pages deallocated */
2308 Pgno origSize; /* Pages in the database file */
2309 Pgno finSize; /* Pages in the database file after truncation */
danielk1977687566d2004-11-02 12:56:41 +00002310 int rc; /* Return code */
2311 u8 eType;
danielk1977a19df672004-11-03 11:37:07 +00002312 int pgsz = pBt->pageSize; /* Page size for this database */
danielk1977687566d2004-11-02 12:56:41 +00002313 Pgno iDbPage; /* The database page to move */
danielk1977687566d2004-11-02 12:56:41 +00002314 MemPage *pDbMemPage = 0; /* "" */
2315 Pgno iPtrPage; /* The page that contains a pointer to iDbPage */
danielk1977687566d2004-11-02 12:56:41 +00002316 Pgno iFreePage; /* The free-list page to move iDbPage to */
2317 MemPage *pFreeMemPage = 0; /* "" */
2318
2319#ifndef NDEBUG
2320 int nRef = *sqlite3pager_stats(pPager);
2321#endif
2322
2323 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +00002324 if( PTRMAP_ISPAGE(pgsz, sqlite3pager_pagecount(pPager)) ){
drh49285702005-09-17 15:20:26 +00002325 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002326 }
danielk1977687566d2004-11-02 12:56:41 +00002327
2328 /* Figure out how many free-pages are in the database. If there are no
2329 ** free pages, then auto-vacuum is a no-op.
2330 */
2331 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977a19df672004-11-03 11:37:07 +00002332 if( nFreeList==0 ){
danielk1977d761c0c2004-11-05 16:37:02 +00002333 *nTrunc = 0;
danielk1977a19df672004-11-03 11:37:07 +00002334 return SQLITE_OK;
2335 }
danielk1977687566d2004-11-02 12:56:41 +00002336
danielk1977a19df672004-11-03 11:37:07 +00002337 origSize = sqlite3pager_pagecount(pPager);
2338 nPtrMap = (nFreeList-origSize+PTRMAP_PAGENO(pgsz, origSize)+pgsz/5)/(pgsz/5);
2339 finSize = origSize - nFreeList - nPtrMap;
danielk1977fd5f5b62005-09-16 09:52:29 +00002340 if( origSize>=PENDING_BYTE_PAGE(pBt) && finSize<=PENDING_BYTE_PAGE(pBt) ){
danielk1977599fcba2004-11-08 07:13:13 +00002341 finSize--;
drh42cac6d2004-11-20 20:31:11 +00002342 if( PTRMAP_ISPAGE(pBt->usableSize, finSize) ){
danielk1977599fcba2004-11-08 07:13:13 +00002343 finSize--;
2344 }
2345 }
danielk1977a19df672004-11-03 11:37:07 +00002346 TRACE(("AUTOVACUUM: Begin (db size %d->%d)\n", origSize, finSize));
danielk1977687566d2004-11-02 12:56:41 +00002347
danielk1977a19df672004-11-03 11:37:07 +00002348 /* Variable 'finSize' will be the size of the file in pages after
danielk1977687566d2004-11-02 12:56:41 +00002349 ** the auto-vacuum has completed (the current file size minus the number
2350 ** of pages on the free list). Loop through the pages that lie beyond
2351 ** this mark, and if they are not already on the free list, move them
danielk1977a19df672004-11-03 11:37:07 +00002352 ** to a free page earlier in the file (somewhere before finSize).
danielk1977687566d2004-11-02 12:56:41 +00002353 */
danielk1977a19df672004-11-03 11:37:07 +00002354 for( iDbPage=finSize+1; iDbPage<=origSize; iDbPage++ ){
danielk1977599fcba2004-11-08 07:13:13 +00002355 /* If iDbPage is a pointer map page, or the pending-byte page, skip it. */
2356 if( PTRMAP_ISPAGE(pgsz, iDbPage) || iDbPage==PENDING_BYTE_PAGE(pBt) ){
2357 continue;
2358 }
2359
danielk1977687566d2004-11-02 12:56:41 +00002360 rc = ptrmapGet(pBt, iDbPage, &eType, &iPtrPage);
2361 if( rc!=SQLITE_OK ) goto autovacuum_out;
drhccae6022005-02-26 17:31:26 +00002362 if( eType==PTRMAP_ROOTPAGE ){
drh49285702005-09-17 15:20:26 +00002363 rc = SQLITE_CORRUPT_BKPT;
drhccae6022005-02-26 17:31:26 +00002364 goto autovacuum_out;
2365 }
danielk1977687566d2004-11-02 12:56:41 +00002366
danielk1977599fcba2004-11-08 07:13:13 +00002367 /* If iDbPage is free, do not swap it. */
2368 if( eType==PTRMAP_FREEPAGE ){
danielk1977687566d2004-11-02 12:56:41 +00002369 continue;
2370 }
2371 rc = getPage(pBt, iDbPage, &pDbMemPage);
2372 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977687566d2004-11-02 12:56:41 +00002373
2374 /* Find the next page in the free-list that is not already at the end
2375 ** of the file. A page can be pulled off the free list using the
2376 ** allocatePage() routine.
2377 */
2378 do{
2379 if( pFreeMemPage ){
2380 releasePage(pFreeMemPage);
2381 pFreeMemPage = 0;
2382 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00002383 rc = allocatePage(pBt, &pFreeMemPage, &iFreePage, 0, 0);
danielk1977ac11ee62005-01-15 12:45:51 +00002384 if( rc!=SQLITE_OK ){
2385 releasePage(pDbMemPage);
2386 goto autovacuum_out;
2387 }
danielk1977a19df672004-11-03 11:37:07 +00002388 assert( iFreePage<=origSize );
2389 }while( iFreePage>finSize );
danielk1977687566d2004-11-02 12:56:41 +00002390 releasePage(pFreeMemPage);
2391 pFreeMemPage = 0;
danielk1977687566d2004-11-02 12:56:41 +00002392
danielk1977003ba062004-11-04 02:57:33 +00002393 rc = relocatePage(pBt, pDbMemPage, eType, iPtrPage, iFreePage);
danielk1977687566d2004-11-02 12:56:41 +00002394 releasePage(pDbMemPage);
danielk1977687566d2004-11-02 12:56:41 +00002395 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977687566d2004-11-02 12:56:41 +00002396 }
2397
2398 /* The entire free-list has been swapped to the end of the file. So
danielk1977a19df672004-11-03 11:37:07 +00002399 ** truncate the database file to finSize pages and consider the
danielk1977687566d2004-11-02 12:56:41 +00002400 ** free-list empty.
2401 */
2402 rc = sqlite3pager_write(pBt->pPage1->aData);
2403 if( rc!=SQLITE_OK ) goto autovacuum_out;
2404 put4byte(&pBt->pPage1->aData[32], 0);
2405 put4byte(&pBt->pPage1->aData[36], 0);
danielk1977687566d2004-11-02 12:56:41 +00002406 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977d761c0c2004-11-05 16:37:02 +00002407 *nTrunc = finSize;
danielk1977687566d2004-11-02 12:56:41 +00002408
2409autovacuum_out:
danielk1977687566d2004-11-02 12:56:41 +00002410 assert( nRef==*sqlite3pager_stats(pPager) );
2411 if( rc!=SQLITE_OK ){
2412 sqlite3pager_rollback(pPager);
2413 }
2414 return rc;
2415}
2416#endif
2417
2418/*
drh2aa679f2001-06-25 02:11:07 +00002419** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00002420**
2421** This will release the write lock on the database file. If there
2422** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002423*/
danielk1977aef0bf62005-12-30 16:28:01 +00002424int sqlite3BtreeCommit(Btree *p){
danielk1977ee5741e2004-05-31 10:01:34 +00002425 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002426 BtShared *pBt = p->pBt;
2427
2428 btreeIntegrity(p);
2429 unlockAllTables(p);
2430
2431 /* If the handle has a write-transaction open, commit the shared-btrees
2432 ** transaction and set the shared state to TRANS_READ.
2433 */
2434 if( p->inTrans==TRANS_WRITE ){
2435 assert( pBt->inTransaction==TRANS_WRITE );
2436 assert( pBt->nTransaction>0 );
danielk1977ee5741e2004-05-31 10:01:34 +00002437 rc = sqlite3pager_commit(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00002438 pBt->inTransaction = TRANS_READ;
2439 pBt->inStmt = 0;
danielk1977ee5741e2004-05-31 10:01:34 +00002440 }
danielk1977aef0bf62005-12-30 16:28:01 +00002441
2442 /* If the handle has any kind of transaction open, decrement the transaction
2443 ** count of the shared btree. If the transaction count reaches 0, set
2444 ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
2445 ** will unlock the pager.
2446 */
2447 if( p->inTrans!=TRANS_NONE ){
2448 pBt->nTransaction--;
2449 if( 0==pBt->nTransaction ){
2450 pBt->inTransaction = TRANS_NONE;
2451 }
2452 }
2453
2454 /* Set the handles current transaction state to TRANS_NONE and unlock
2455 ** the pager if this call closed the only read or write transaction.
2456 */
2457 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002458 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002459
2460 btreeIntegrity(p);
drha059ad02001-04-17 20:09:11 +00002461 return rc;
2462}
2463
danielk1977fbcd5852004-06-15 02:44:18 +00002464#ifndef NDEBUG
2465/*
2466** Return the number of write-cursors open on this handle. This is for use
2467** in assert() expressions, so it is only compiled if NDEBUG is not
2468** defined.
2469*/
danielk1977aef0bf62005-12-30 16:28:01 +00002470static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00002471 BtCursor *pCur;
2472 int r = 0;
2473 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
danielk1977aef0bf62005-12-30 16:28:01 +00002474 if( pCur->wrFlag ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00002475 }
2476 return r;
2477}
2478#endif
2479
drhda200cc2004-05-09 11:51:38 +00002480#ifdef SQLITE_TEST
2481/*
2482** Print debugging information about all cursors to standard output.
2483*/
danielk1977aef0bf62005-12-30 16:28:01 +00002484void sqlite3BtreeCursorList(Btree *p){
drhda200cc2004-05-09 11:51:38 +00002485 BtCursor *pCur;
danielk1977aef0bf62005-12-30 16:28:01 +00002486 BtShared *pBt = p->pBt;
drhda200cc2004-05-09 11:51:38 +00002487 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
2488 MemPage *pPage = pCur->pPage;
2489 char *zMode = pCur->wrFlag ? "rw" : "ro";
drhfe63d1c2004-09-08 20:13:04 +00002490 sqlite3DebugPrintf("CURSOR %p rooted at %4d(%s) currently at %d.%d%s\n",
2491 pCur, pCur->pgnoRoot, zMode,
drhda200cc2004-05-09 11:51:38 +00002492 pPage ? pPage->pgno : 0, pCur->idx,
danielk1977da184232006-01-05 11:34:32 +00002493 (pCur->eState==CURSOR_VALID) ? "" : " eof"
drhda200cc2004-05-09 11:51:38 +00002494 );
2495 }
2496}
2497#endif
2498
drhc39e0002004-05-07 23:50:57 +00002499/*
drhecdc7532001-09-23 02:35:53 +00002500** Rollback the transaction in progress. All cursors will be
2501** invalided by this operation. Any attempt to use a cursor
2502** that was open at the beginning of this operation will result
2503** in an error.
drh5e00f6c2001-09-13 13:46:56 +00002504**
2505** This will release the write lock on the database file. If there
2506** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002507*/
danielk1977aef0bf62005-12-30 16:28:01 +00002508int sqlite3BtreeRollback(Btree *p){
danielk1977cfe9a692004-06-16 12:00:29 +00002509 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002510 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00002511 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00002512
2513 btreeIntegrity(p);
2514 unlockAllTables(p);
2515
2516 if( p->inTrans==TRANS_WRITE ){
2517 assert( TRANS_WRITE==pBt->inTransaction );
2518
drh24cd67e2004-05-10 16:18:47 +00002519 rc = sqlite3pager_rollback(pBt->pPager);
2520 /* The rollback may have destroyed the pPage1->aData value. So
2521 ** call getPage() on page 1 again to make sure pPage1->aData is
2522 ** set correctly. */
2523 if( getPage(pBt, 1, &pPage1)==SQLITE_OK ){
2524 releasePage(pPage1);
2525 }
danielk1977fbcd5852004-06-15 02:44:18 +00002526 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002527 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00002528 }
danielk1977aef0bf62005-12-30 16:28:01 +00002529
2530 if( p->inTrans!=TRANS_NONE ){
2531 assert( pBt->nTransaction>0 );
2532 pBt->nTransaction--;
2533 if( 0==pBt->nTransaction ){
2534 pBt->inTransaction = TRANS_NONE;
2535 }
2536 }
2537
2538 p->inTrans = TRANS_NONE;
danielk1977ee5741e2004-05-31 10:01:34 +00002539 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00002540 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002541
2542 btreeIntegrity(p);
drha059ad02001-04-17 20:09:11 +00002543 return rc;
2544}
2545
2546/*
drhab01f612004-05-22 02:55:23 +00002547** Start a statement subtransaction. The subtransaction can
2548** can be rolled back independently of the main transaction.
2549** You must start a transaction before starting a subtransaction.
2550** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00002551** commits or rolls back.
2552**
drhab01f612004-05-22 02:55:23 +00002553** Only one subtransaction may be active at a time. It is an error to try
2554** to start a new subtransaction if another subtransaction is already active.
2555**
2556** Statement subtransactions are used around individual SQL statements
2557** that are contained within a BEGIN...COMMIT block. If a constraint
2558** error occurs within the statement, the effect of that one statement
2559** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00002560*/
danielk1977aef0bf62005-12-30 16:28:01 +00002561int sqlite3BtreeBeginStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002562 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002563 BtShared *pBt = p->pBt;
2564 if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
drhf74b8d92002-09-01 23:20:45 +00002565 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh0d65dc02002-02-03 00:56:09 +00002566 }
danielk1977aef0bf62005-12-30 16:28:01 +00002567 assert( pBt->inTransaction==TRANS_WRITE );
drha34b6762004-05-07 13:30:42 +00002568 rc = pBt->readOnly ? SQLITE_OK : sqlite3pager_stmt_begin(pBt->pPager);
drh3aac2dd2004-04-26 14:10:20 +00002569 pBt->inStmt = 1;
drh663fc632002-02-02 18:49:19 +00002570 return rc;
2571}
2572
2573
2574/*
drhab01f612004-05-22 02:55:23 +00002575** Commit the statment subtransaction currently in progress. If no
2576** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00002577*/
danielk1977aef0bf62005-12-30 16:28:01 +00002578int sqlite3BtreeCommitStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002579 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002580 BtShared *pBt = p->pBt;
drh3aac2dd2004-04-26 14:10:20 +00002581 if( pBt->inStmt && !pBt->readOnly ){
drha34b6762004-05-07 13:30:42 +00002582 rc = sqlite3pager_stmt_commit(pBt->pPager);
drh663fc632002-02-02 18:49:19 +00002583 }else{
2584 rc = SQLITE_OK;
2585 }
drh3aac2dd2004-04-26 14:10:20 +00002586 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00002587 return rc;
2588}
2589
2590/*
drhab01f612004-05-22 02:55:23 +00002591** Rollback the active statement subtransaction. If no subtransaction
2592** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00002593**
drhab01f612004-05-22 02:55:23 +00002594** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00002595** to use a cursor that was open at the beginning of this operation
2596** will result in an error.
2597*/
danielk1977aef0bf62005-12-30 16:28:01 +00002598int sqlite3BtreeRollbackStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002599 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002600 BtShared *pBt = p->pBt;
drh3aac2dd2004-04-26 14:10:20 +00002601 if( pBt->inStmt==0 || pBt->readOnly ) return SQLITE_OK;
drha34b6762004-05-07 13:30:42 +00002602 rc = sqlite3pager_stmt_rollback(pBt->pPager);
danielk1977fbcd5852004-06-15 02:44:18 +00002603 assert( countWriteCursors(pBt)==0 );
drh3aac2dd2004-04-26 14:10:20 +00002604 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00002605 return rc;
2606}
2607
2608/*
drh3aac2dd2004-04-26 14:10:20 +00002609** Default key comparison function to be used if no comparison function
2610** is specified on the sqlite3BtreeCursor() call.
2611*/
2612static int dfltCompare(
2613 void *NotUsed, /* User data is not used */
2614 int n1, const void *p1, /* First key to compare */
2615 int n2, const void *p2 /* Second key to compare */
2616){
2617 int c;
2618 c = memcmp(p1, p2, n1<n2 ? n1 : n2);
2619 if( c==0 ){
2620 c = n1 - n2;
2621 }
2622 return c;
2623}
2624
2625/*
drh8b2f49b2001-06-08 00:21:52 +00002626** Create a new cursor for the BTree whose root is on the page
2627** iTable. The act of acquiring a cursor gets a read lock on
2628** the database file.
drh1bee3d72001-10-15 00:44:35 +00002629**
2630** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00002631** If wrFlag==1, then the cursor can be used for reading or for
2632** writing if other conditions for writing are also met. These
2633** are the conditions that must be met in order for writing to
2634** be allowed:
drh6446c4d2001-12-15 14:22:18 +00002635**
drhf74b8d92002-09-01 23:20:45 +00002636** 1: The cursor must have been opened with wrFlag==1
2637**
2638** 2: No other cursors may be open with wrFlag==0 on the same table
2639**
2640** 3: The database must be writable (not on read-only media)
2641**
2642** 4: There must be an active transaction.
2643**
2644** Condition 2 warrants further discussion. If any cursor is opened
2645** on a table with wrFlag==0, that prevents all other cursors from
2646** writing to that table. This is a kind of "read-lock". When a cursor
2647** is opened with wrFlag==0 it is guaranteed that the table will not
2648** change as long as the cursor is open. This allows the cursor to
2649** do a sequential scan of the table without having to worry about
2650** entries being inserted or deleted during the scan. Cursors should
2651** be opened with wrFlag==0 only if this read-lock property is needed.
2652** That is to say, cursors should be opened with wrFlag==0 only if they
drh23e11ca2004-05-04 17:27:28 +00002653** intend to use the sqlite3BtreeNext() system call. All other cursors
drhf74b8d92002-09-01 23:20:45 +00002654** should be opened with wrFlag==1 even if they never really intend
2655** to write.
2656**
drh6446c4d2001-12-15 14:22:18 +00002657** No checking is done to make sure that page iTable really is the
2658** root page of a b-tree. If it is not, then the cursor acquired
2659** will not work correctly.
drh3aac2dd2004-04-26 14:10:20 +00002660**
2661** The comparison function must be logically the same for every cursor
2662** on a particular table. Changing the comparison function will result
2663** in incorrect operations. If the comparison function is NULL, a
2664** default comparison function is used. The comparison function is
2665** always ignored for INTKEY tables.
drha059ad02001-04-17 20:09:11 +00002666*/
drh3aac2dd2004-04-26 14:10:20 +00002667int sqlite3BtreeCursor(
danielk1977aef0bf62005-12-30 16:28:01 +00002668 Btree *p, /* The btree */
drh3aac2dd2004-04-26 14:10:20 +00002669 int iTable, /* Root page of table to open */
2670 int wrFlag, /* 1 to write. 0 read-only */
2671 int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
2672 void *pArg, /* First arg to xCompare() */
2673 BtCursor **ppCur /* Write new cursor here */
2674){
drha059ad02001-04-17 20:09:11 +00002675 int rc;
drh8dcd7ca2004-08-08 19:43:29 +00002676 BtCursor *pCur;
danielk1977aef0bf62005-12-30 16:28:01 +00002677 BtShared *pBt = p->pBt;
drhecdc7532001-09-23 02:35:53 +00002678
drh8dcd7ca2004-08-08 19:43:29 +00002679 *ppCur = 0;
2680 if( wrFlag ){
drh8dcd7ca2004-08-08 19:43:29 +00002681 if( pBt->readOnly ){
2682 return SQLITE_READONLY;
2683 }
2684 if( checkReadLocks(pBt, iTable, 0) ){
2685 return SQLITE_LOCKED;
2686 }
drha0c9a112004-03-10 13:42:37 +00002687 }
danielk1977aef0bf62005-12-30 16:28:01 +00002688
2689#ifndef SQLITE_OMIT_SHARED_CACHE
2690 rc = queryTableLock(p, iTable, wrFlag?WRITE_LOCK:READ_LOCK);
2691 if( rc!=SQLITE_OK ){
2692 return rc;
2693 }
2694#endif
2695
drh4b70f112004-05-02 21:12:19 +00002696 if( pBt->pPage1==0 ){
danielk1977aef0bf62005-12-30 16:28:01 +00002697 rc = lockBtreeWithRetry(p);
drha059ad02001-04-17 20:09:11 +00002698 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002699 return rc;
2700 }
2701 }
danielk1977da184232006-01-05 11:34:32 +00002702 pCur = sqliteMalloc( sizeof(*pCur) );
drha059ad02001-04-17 20:09:11 +00002703 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +00002704 rc = SQLITE_NOMEM;
2705 goto create_cursor_exception;
2706 }
drh8b2f49b2001-06-08 00:21:52 +00002707 pCur->pgnoRoot = (Pgno)iTable;
danielk19776b456a22005-03-21 04:04:02 +00002708 pCur->pPage = 0; /* For exit-handler, in case getAndInitPage() fails. */
drh24cd67e2004-05-10 16:18:47 +00002709 if( iTable==1 && sqlite3pager_pagecount(pBt->pPager)==0 ){
2710 rc = SQLITE_EMPTY;
2711 goto create_cursor_exception;
2712 }
drhde647132004-05-07 17:57:49 +00002713 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
drhbd03cae2001-06-02 02:40:57 +00002714 if( rc!=SQLITE_OK ){
2715 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002716 }
danielk1977aef0bf62005-12-30 16:28:01 +00002717
2718 /* Obtain the table-lock on the shared-btree. */
2719 rc = lockTable(p, iTable, wrFlag?WRITE_LOCK:READ_LOCK);
2720 if( rc!=SQLITE_OK ){
2721 assert( rc==SQLITE_NOMEM );
2722 goto create_cursor_exception;
2723 }
2724
2725 /* Now that no other errors can occur, finish filling in the BtCursor
2726 ** variables, link the cursor into the BtShared list and set *ppCur (the
2727 ** output argument to this function).
2728 */
drh3aac2dd2004-04-26 14:10:20 +00002729 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2730 pCur->pArg = pArg;
danielk1977aef0bf62005-12-30 16:28:01 +00002731 pCur->pBtree = p;
drhecdc7532001-09-23 02:35:53 +00002732 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +00002733 pCur->idx = 0;
drh59eb6762004-06-13 23:07:04 +00002734 memset(&pCur->info, 0, sizeof(pCur->info));
drha059ad02001-04-17 20:09:11 +00002735 pCur->pNext = pBt->pCursor;
2736 if( pCur->pNext ){
2737 pCur->pNext->pPrev = pCur;
2738 }
drh14acc042001-06-10 19:56:58 +00002739 pCur->pPrev = 0;
drha059ad02001-04-17 20:09:11 +00002740 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00002741 pCur->eState = CURSOR_INVALID;
drh2af926b2001-05-15 00:39:25 +00002742 *ppCur = pCur;
drhbd03cae2001-06-02 02:40:57 +00002743
danielk1977aef0bf62005-12-30 16:28:01 +00002744 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00002745create_cursor_exception:
drhbd03cae2001-06-02 02:40:57 +00002746 if( pCur ){
drh3aac2dd2004-04-26 14:10:20 +00002747 releasePage(pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +00002748 sqliteFree(pCur);
2749 }
drh5e00f6c2001-09-13 13:46:56 +00002750 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00002751 return rc;
drha059ad02001-04-17 20:09:11 +00002752}
2753
drh7a224de2004-06-02 01:22:02 +00002754#if 0 /* Not Used */
drhd3d39e92004-05-20 22:16:29 +00002755/*
2756** Change the value of the comparison function used by a cursor.
2757*/
danielk1977bf3b7212004-05-18 10:06:24 +00002758void sqlite3BtreeSetCompare(
drhd3d39e92004-05-20 22:16:29 +00002759 BtCursor *pCur, /* The cursor to whose comparison function is changed */
2760 int(*xCmp)(void*,int,const void*,int,const void*), /* New comparison func */
2761 void *pArg /* First argument to xCmp() */
danielk1977bf3b7212004-05-18 10:06:24 +00002762){
2763 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2764 pCur->pArg = pArg;
2765}
drh7a224de2004-06-02 01:22:02 +00002766#endif
danielk1977bf3b7212004-05-18 10:06:24 +00002767
drha059ad02001-04-17 20:09:11 +00002768/*
drh5e00f6c2001-09-13 13:46:56 +00002769** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00002770** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00002771*/
drh3aac2dd2004-04-26 14:10:20 +00002772int sqlite3BtreeCloseCursor(BtCursor *pCur){
danielk1977aef0bf62005-12-30 16:28:01 +00002773 BtShared *pBt = pCur->pBtree->pBt;
danielk1977da184232006-01-05 11:34:32 +00002774 restoreCursorPosition(pCur, 0);
drha059ad02001-04-17 20:09:11 +00002775 if( pCur->pPrev ){
2776 pCur->pPrev->pNext = pCur->pNext;
2777 }else{
2778 pBt->pCursor = pCur->pNext;
2779 }
2780 if( pCur->pNext ){
2781 pCur->pNext->pPrev = pCur->pPrev;
2782 }
drh3aac2dd2004-04-26 14:10:20 +00002783 releasePage(pCur->pPage);
drh5e00f6c2001-09-13 13:46:56 +00002784 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00002785 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +00002786 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002787}
2788
drh7e3b0a02001-04-28 16:52:40 +00002789/*
drh5e2f8b92001-05-28 00:41:15 +00002790** Make a temporary cursor by filling in the fields of pTempCur.
2791** The temporary cursor is not on the cursor list for the Btree.
2792*/
drh14acc042001-06-10 19:56:58 +00002793static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00002794 memcpy(pTempCur, pCur, sizeof(*pCur));
2795 pTempCur->pNext = 0;
2796 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00002797 if( pTempCur->pPage ){
drha34b6762004-05-07 13:30:42 +00002798 sqlite3pager_ref(pTempCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00002799 }
drh5e2f8b92001-05-28 00:41:15 +00002800}
2801
2802/*
drhbd03cae2001-06-02 02:40:57 +00002803** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00002804** function above.
2805*/
drh14acc042001-06-10 19:56:58 +00002806static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00002807 if( pCur->pPage ){
drha34b6762004-05-07 13:30:42 +00002808 sqlite3pager_unref(pCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00002809 }
drh5e2f8b92001-05-28 00:41:15 +00002810}
2811
2812/*
drh9188b382004-05-14 21:12:22 +00002813** Make sure the BtCursor.info field of the given cursor is valid.
drhab01f612004-05-22 02:55:23 +00002814** If it is not already valid, call parseCell() to fill it in.
2815**
2816** BtCursor.info is a cache of the information in the current cell.
2817** Using this cache reduces the number of calls to parseCell().
drh9188b382004-05-14 21:12:22 +00002818*/
2819static void getCellInfo(BtCursor *pCur){
drh271efa52004-05-30 19:19:05 +00002820 if( pCur->info.nSize==0 ){
drh3a41a3f2004-05-30 02:14:17 +00002821 parseCell(pCur->pPage, pCur->idx, &pCur->info);
drh9188b382004-05-14 21:12:22 +00002822 }else{
2823#ifndef NDEBUG
2824 CellInfo info;
drh51c6d962004-06-06 00:42:25 +00002825 memset(&info, 0, sizeof(info));
drh3a41a3f2004-05-30 02:14:17 +00002826 parseCell(pCur->pPage, pCur->idx, &info);
drh9188b382004-05-14 21:12:22 +00002827 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
2828#endif
2829 }
2830}
2831
2832/*
drh3aac2dd2004-04-26 14:10:20 +00002833** Set *pSize to the size of the buffer needed to hold the value of
2834** the key for the current entry. If the cursor is not pointing
2835** to a valid entry, *pSize is set to 0.
2836**
drh4b70f112004-05-02 21:12:19 +00002837** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00002838** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00002839*/
drh4a1c3802004-05-12 15:15:47 +00002840int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
danielk1977da184232006-01-05 11:34:32 +00002841 int rc = restoreCursorPosition(pCur, 1);
2842 if( rc==SQLITE_OK ){
2843 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
2844 if( pCur->eState==CURSOR_INVALID ){
2845 *pSize = 0;
2846 }else{
2847 getCellInfo(pCur);
2848 *pSize = pCur->info.nKey;
2849 }
drh72f82862001-05-24 21:06:34 +00002850 }
danielk1977da184232006-01-05 11:34:32 +00002851 return rc;
drha059ad02001-04-17 20:09:11 +00002852}
drh2af926b2001-05-15 00:39:25 +00002853
drh72f82862001-05-24 21:06:34 +00002854/*
drh0e1c19e2004-05-11 00:58:56 +00002855** Set *pSize to the number of bytes of data in the entry the
2856** cursor currently points to. Always return SQLITE_OK.
2857** Failure is not possible. If the cursor is not currently
2858** pointing to an entry (which can happen, for example, if
2859** the database is empty) then *pSize is set to 0.
2860*/
2861int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
danielk1977da184232006-01-05 11:34:32 +00002862 int rc = restoreCursorPosition(pCur, 1);
2863 if( rc==SQLITE_OK ){
2864 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
2865 if( pCur->eState==CURSOR_INVALID ){
2866 /* Not pointing at a valid entry - set *pSize to 0. */
2867 *pSize = 0;
2868 }else{
2869 getCellInfo(pCur);
2870 *pSize = pCur->info.nData;
2871 }
drh0e1c19e2004-05-11 00:58:56 +00002872 }
danielk1977da184232006-01-05 11:34:32 +00002873 return rc;
drh0e1c19e2004-05-11 00:58:56 +00002874}
2875
2876/*
drh72f82862001-05-24 21:06:34 +00002877** Read payload information from the entry that the pCur cursor is
2878** pointing to. Begin reading the payload at "offset" and read
2879** a total of "amt" bytes. Put the result in zBuf.
2880**
2881** This routine does not make a distinction between key and data.
drhab01f612004-05-22 02:55:23 +00002882** It just reads bytes from the payload area. Data might appear
2883** on the main page or be scattered out on multiple overflow pages.
drh72f82862001-05-24 21:06:34 +00002884*/
drh3aac2dd2004-04-26 14:10:20 +00002885static int getPayload(
2886 BtCursor *pCur, /* Cursor pointing to entry to read from */
2887 int offset, /* Begin reading this far into payload */
2888 int amt, /* Read this many bytes */
2889 unsigned char *pBuf, /* Write the bytes into this buffer */
2890 int skipKey /* offset begins at data if this is true */
2891){
2892 unsigned char *aPayload;
drh2af926b2001-05-15 00:39:25 +00002893 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +00002894 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002895 MemPage *pPage;
danielk1977aef0bf62005-12-30 16:28:01 +00002896 BtShared *pBt;
drh6f11bef2004-05-13 01:12:56 +00002897 int ovflSize;
drhfa1a98a2004-05-14 19:08:17 +00002898 u32 nKey;
drh3aac2dd2004-04-26 14:10:20 +00002899
drh72f82862001-05-24 21:06:34 +00002900 assert( pCur!=0 && pCur->pPage!=0 );
danielk1977da184232006-01-05 11:34:32 +00002901 assert( pCur->eState==CURSOR_VALID );
danielk1977aef0bf62005-12-30 16:28:01 +00002902 pBt = pCur->pBtree->pBt;
drh3aac2dd2004-04-26 14:10:20 +00002903 pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00002904 pageIntegrity(pPage);
drh3aac2dd2004-04-26 14:10:20 +00002905 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00002906 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00002907 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00002908 aPayload += pCur->info.nHeader;
drh3aac2dd2004-04-26 14:10:20 +00002909 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00002910 nKey = 0;
2911 }else{
2912 nKey = pCur->info.nKey;
drh3aac2dd2004-04-26 14:10:20 +00002913 }
2914 assert( offset>=0 );
2915 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00002916 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00002917 }
drhfa1a98a2004-05-14 19:08:17 +00002918 if( offset+amt > nKey+pCur->info.nData ){
drha34b6762004-05-07 13:30:42 +00002919 return SQLITE_ERROR;
drh3aac2dd2004-04-26 14:10:20 +00002920 }
drhfa1a98a2004-05-14 19:08:17 +00002921 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00002922 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00002923 if( a+offset>pCur->info.nLocal ){
2924 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00002925 }
drha34b6762004-05-07 13:30:42 +00002926 memcpy(pBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +00002927 if( a==amt ){
2928 return SQLITE_OK;
2929 }
drh2aa679f2001-06-25 02:11:07 +00002930 offset = 0;
drha34b6762004-05-07 13:30:42 +00002931 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00002932 amt -= a;
drhdd793422001-06-28 01:54:48 +00002933 }else{
drhfa1a98a2004-05-14 19:08:17 +00002934 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00002935 }
danielk1977cfe9a692004-06-16 12:00:29 +00002936 ovflSize = pBt->usableSize - 4;
drhbd03cae2001-06-02 02:40:57 +00002937 if( amt>0 ){
drhfa1a98a2004-05-14 19:08:17 +00002938 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977cfe9a692004-06-16 12:00:29 +00002939 while( amt>0 && nextPage ){
2940 rc = sqlite3pager_get(pBt->pPager, nextPage, (void**)&aPayload);
2941 if( rc!=0 ){
2942 return rc;
drh2af926b2001-05-15 00:39:25 +00002943 }
danielk1977cfe9a692004-06-16 12:00:29 +00002944 nextPage = get4byte(aPayload);
2945 if( offset<ovflSize ){
2946 int a = amt;
2947 if( a + offset > ovflSize ){
2948 a = ovflSize - offset;
2949 }
2950 memcpy(pBuf, &aPayload[offset+4], a);
2951 offset = 0;
2952 amt -= a;
2953 pBuf += a;
2954 }else{
2955 offset -= ovflSize;
2956 }
2957 sqlite3pager_unref(aPayload);
drh2af926b2001-05-15 00:39:25 +00002958 }
drh2af926b2001-05-15 00:39:25 +00002959 }
danielk1977cfe9a692004-06-16 12:00:29 +00002960
drha7fcb052001-12-14 15:09:55 +00002961 if( amt>0 ){
drh49285702005-09-17 15:20:26 +00002962 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00002963 }
2964 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00002965}
2966
drh72f82862001-05-24 21:06:34 +00002967/*
drh3aac2dd2004-04-26 14:10:20 +00002968** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002969** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002970** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00002971**
drh3aac2dd2004-04-26 14:10:20 +00002972** Return SQLITE_OK on success or an error code if anything goes
2973** wrong. An error is returned if "offset+amt" is larger than
2974** the available payload.
drh72f82862001-05-24 21:06:34 +00002975*/
drha34b6762004-05-07 13:30:42 +00002976int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
danielk1977da184232006-01-05 11:34:32 +00002977 int rc = restoreCursorPosition(pCur, 1);
2978 if( rc==SQLITE_OK ){
2979 assert( pCur->eState==CURSOR_VALID );
2980 assert( pCur->pPage!=0 );
2981 if( pCur->pPage->intKey ){
2982 return SQLITE_CORRUPT_BKPT;
2983 }
2984 assert( pCur->pPage->intKey==0 );
2985 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
2986 rc = getPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
drh6575a222005-03-10 17:06:34 +00002987 }
danielk1977da184232006-01-05 11:34:32 +00002988 return rc;
drh3aac2dd2004-04-26 14:10:20 +00002989}
2990
2991/*
drh3aac2dd2004-04-26 14:10:20 +00002992** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002993** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002994** begins at "offset".
2995**
2996** Return SQLITE_OK on success or an error code if anything goes
2997** wrong. An error is returned if "offset+amt" is larger than
2998** the available payload.
drh72f82862001-05-24 21:06:34 +00002999*/
drh3aac2dd2004-04-26 14:10:20 +00003000int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
danielk1977da184232006-01-05 11:34:32 +00003001 int rc = restoreCursorPosition(pCur, 1);
3002 if( rc==SQLITE_OK ){
3003 assert( pCur->eState==CURSOR_VALID );
3004 assert( pCur->pPage!=0 );
3005 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
3006 rc = getPayload(pCur, offset, amt, pBuf, 1);
3007 }
3008 return rc;
drh2af926b2001-05-15 00:39:25 +00003009}
3010
drh72f82862001-05-24 21:06:34 +00003011/*
drh0e1c19e2004-05-11 00:58:56 +00003012** Return a pointer to payload information from the entry that the
3013** pCur cursor is pointing to. The pointer is to the beginning of
3014** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00003015** skipKey==1. The number of bytes of available key/data is written
3016** into *pAmt. If *pAmt==0, then the value returned will not be
3017** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00003018**
3019** This routine is an optimization. It is common for the entire key
3020** and data to fit on the local page and for there to be no overflow
3021** pages. When that is so, this routine can be used to access the
3022** key and data without making a copy. If the key and/or data spills
3023** onto overflow pages, then getPayload() must be used to reassembly
3024** the key/data and copy it into a preallocated buffer.
3025**
3026** The pointer returned by this routine looks directly into the cached
3027** page of the database. The data might change or move the next time
3028** any btree routine is called.
3029*/
3030static const unsigned char *fetchPayload(
3031 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00003032 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00003033 int skipKey /* read beginning at data if this is true */
3034){
3035 unsigned char *aPayload;
3036 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00003037 u32 nKey;
3038 int nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003039
3040 assert( pCur!=0 && pCur->pPage!=0 );
danielk1977da184232006-01-05 11:34:32 +00003041 assert( pCur->eState==CURSOR_VALID );
drh0e1c19e2004-05-11 00:58:56 +00003042 pPage = pCur->pPage;
3043 pageIntegrity(pPage);
3044 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00003045 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00003046 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00003047 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00003048 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00003049 nKey = 0;
3050 }else{
3051 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00003052 }
drh0e1c19e2004-05-11 00:58:56 +00003053 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003054 aPayload += nKey;
3055 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00003056 }else{
drhfa1a98a2004-05-14 19:08:17 +00003057 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00003058 if( nLocal>nKey ){
3059 nLocal = nKey;
3060 }
drh0e1c19e2004-05-11 00:58:56 +00003061 }
drhe51c44f2004-05-30 20:46:09 +00003062 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003063 return aPayload;
3064}
3065
3066
3067/*
drhe51c44f2004-05-30 20:46:09 +00003068** For the entry that cursor pCur is point to, return as
3069** many bytes of the key or data as are available on the local
3070** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00003071**
3072** The pointer returned is ephemeral. The key/data may move
3073** or be destroyed on the next call to any Btree routine.
3074**
3075** These routines is used to get quick access to key and data
3076** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00003077*/
drhe51c44f2004-05-30 20:46:09 +00003078const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
danielk1977da184232006-01-05 11:34:32 +00003079 if( pCur->eState==CURSOR_VALID ){
3080 return (const void*)fetchPayload(pCur, pAmt, 0);
3081 }
3082 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003083}
drhe51c44f2004-05-30 20:46:09 +00003084const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
danielk1977da184232006-01-05 11:34:32 +00003085 if( pCur->eState==CURSOR_VALID ){
3086 return (const void*)fetchPayload(pCur, pAmt, 1);
3087 }
3088 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003089}
3090
3091
3092/*
drh8178a752003-01-05 21:41:40 +00003093** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00003094** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00003095*/
drh3aac2dd2004-04-26 14:10:20 +00003096static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00003097 int rc;
3098 MemPage *pNewPage;
drh3aac2dd2004-04-26 14:10:20 +00003099 MemPage *pOldPage;
danielk1977aef0bf62005-12-30 16:28:01 +00003100 BtShared *pBt = pCur->pBtree->pBt;
drh72f82862001-05-24 21:06:34 +00003101
danielk1977da184232006-01-05 11:34:32 +00003102 assert( pCur->eState==CURSOR_VALID );
drhde647132004-05-07 17:57:49 +00003103 rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00003104 if( rc ) return rc;
drhda200cc2004-05-09 11:51:38 +00003105 pageIntegrity(pNewPage);
drh428ae8c2003-01-04 16:48:09 +00003106 pNewPage->idxParent = pCur->idx;
drh3aac2dd2004-04-26 14:10:20 +00003107 pOldPage = pCur->pPage;
3108 pOldPage->idxShift = 0;
3109 releasePage(pOldPage);
drh72f82862001-05-24 21:06:34 +00003110 pCur->pPage = pNewPage;
3111 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00003112 pCur->info.nSize = 0;
drh4be295b2003-12-16 03:44:47 +00003113 if( pNewPage->nCell<1 ){
drh49285702005-09-17 15:20:26 +00003114 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00003115 }
drh72f82862001-05-24 21:06:34 +00003116 return SQLITE_OK;
3117}
3118
3119/*
drh8856d6a2004-04-29 14:42:46 +00003120** Return true if the page is the virtual root of its table.
3121**
3122** The virtual root page is the root page for most tables. But
3123** for the table rooted on page 1, sometime the real root page
3124** is empty except for the right-pointer. In such cases the
3125** virtual root page is the page that the right-pointer of page
3126** 1 is pointing to.
3127*/
3128static int isRootPage(MemPage *pPage){
3129 MemPage *pParent = pPage->pParent;
drhda200cc2004-05-09 11:51:38 +00003130 if( pParent==0 ) return 1;
3131 if( pParent->pgno>1 ) return 0;
3132 if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
drh8856d6a2004-04-29 14:42:46 +00003133 return 0;
3134}
3135
3136/*
drh5e2f8b92001-05-28 00:41:15 +00003137** Move the cursor up to the parent page.
3138**
3139** pCur->idx is set to the cell index that contains the pointer
3140** to the page we are coming from. If we are coming from the
3141** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00003142** the largest cell index.
drh72f82862001-05-24 21:06:34 +00003143*/
drh8178a752003-01-05 21:41:40 +00003144static void moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00003145 MemPage *pParent;
drh8178a752003-01-05 21:41:40 +00003146 MemPage *pPage;
drh428ae8c2003-01-04 16:48:09 +00003147 int idxParent;
drh3aac2dd2004-04-26 14:10:20 +00003148
danielk1977da184232006-01-05 11:34:32 +00003149 assert( pCur->eState==CURSOR_VALID );
drh8178a752003-01-05 21:41:40 +00003150 pPage = pCur->pPage;
3151 assert( pPage!=0 );
drh8856d6a2004-04-29 14:42:46 +00003152 assert( !isRootPage(pPage) );
drhda200cc2004-05-09 11:51:38 +00003153 pageIntegrity(pPage);
drh8178a752003-01-05 21:41:40 +00003154 pParent = pPage->pParent;
3155 assert( pParent!=0 );
drhda200cc2004-05-09 11:51:38 +00003156 pageIntegrity(pParent);
drh8178a752003-01-05 21:41:40 +00003157 idxParent = pPage->idxParent;
drha34b6762004-05-07 13:30:42 +00003158 sqlite3pager_ref(pParent->aData);
drh3aac2dd2004-04-26 14:10:20 +00003159 releasePage(pPage);
drh72f82862001-05-24 21:06:34 +00003160 pCur->pPage = pParent;
drh271efa52004-05-30 19:19:05 +00003161 pCur->info.nSize = 0;
drh428ae8c2003-01-04 16:48:09 +00003162 assert( pParent->idxShift==0 );
drh43605152004-05-29 21:46:49 +00003163 pCur->idx = idxParent;
drh72f82862001-05-24 21:06:34 +00003164}
3165
3166/*
3167** Move the cursor to the root page
3168*/
drh5e2f8b92001-05-28 00:41:15 +00003169static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00003170 MemPage *pRoot;
drhbd03cae2001-06-02 02:40:57 +00003171 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003172 BtShared *pBt = pCur->pBtree->pBt;
drhbd03cae2001-06-02 02:40:57 +00003173
danielk1977da184232006-01-05 11:34:32 +00003174 restoreCursorPosition(pCur, 0);
drhde647132004-05-07 17:57:49 +00003175 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0);
drhc39e0002004-05-07 23:50:57 +00003176 if( rc ){
danielk1977da184232006-01-05 11:34:32 +00003177 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00003178 return rc;
3179 }
drh3aac2dd2004-04-26 14:10:20 +00003180 releasePage(pCur->pPage);
drhda200cc2004-05-09 11:51:38 +00003181 pageIntegrity(pRoot);
drh3aac2dd2004-04-26 14:10:20 +00003182 pCur->pPage = pRoot;
drh72f82862001-05-24 21:06:34 +00003183 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00003184 pCur->info.nSize = 0;
drh8856d6a2004-04-29 14:42:46 +00003185 if( pRoot->nCell==0 && !pRoot->leaf ){
3186 Pgno subpage;
3187 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00003188 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00003189 assert( subpage>0 );
danielk1977da184232006-01-05 11:34:32 +00003190 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00003191 rc = moveToChild(pCur, subpage);
drh8856d6a2004-04-29 14:42:46 +00003192 }
danielk1977da184232006-01-05 11:34:32 +00003193 pCur->eState = ((pCur->pPage->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00003194 return rc;
drh72f82862001-05-24 21:06:34 +00003195}
drh2af926b2001-05-15 00:39:25 +00003196
drh5e2f8b92001-05-28 00:41:15 +00003197/*
3198** Move the cursor down to the left-most leaf entry beneath the
3199** entry to which it is currently pointing.
3200*/
3201static int moveToLeftmost(BtCursor *pCur){
3202 Pgno pgno;
3203 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003204 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00003205
danielk1977da184232006-01-05 11:34:32 +00003206 assert( pCur->eState==CURSOR_VALID );
drh3aac2dd2004-04-26 14:10:20 +00003207 while( !(pPage = pCur->pPage)->leaf ){
drha34b6762004-05-07 13:30:42 +00003208 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00003209 pgno = get4byte(findCell(pPage, pCur->idx));
drh8178a752003-01-05 21:41:40 +00003210 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00003211 if( rc ) return rc;
3212 }
3213 return SQLITE_OK;
3214}
3215
drh2dcc9aa2002-12-04 13:40:25 +00003216/*
3217** Move the cursor down to the right-most leaf entry beneath the
3218** page to which it is currently pointing. Notice the difference
3219** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
3220** finds the left-most entry beneath the *entry* whereas moveToRightmost()
3221** finds the right-most entry beneath the *page*.
3222*/
3223static int moveToRightmost(BtCursor *pCur){
3224 Pgno pgno;
3225 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003226 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003227
danielk1977da184232006-01-05 11:34:32 +00003228 assert( pCur->eState==CURSOR_VALID );
drh3aac2dd2004-04-26 14:10:20 +00003229 while( !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00003230 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh3aac2dd2004-04-26 14:10:20 +00003231 pCur->idx = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00003232 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003233 if( rc ) return rc;
3234 }
drh3aac2dd2004-04-26 14:10:20 +00003235 pCur->idx = pPage->nCell - 1;
drh271efa52004-05-30 19:19:05 +00003236 pCur->info.nSize = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003237 return SQLITE_OK;
3238}
3239
drh5e00f6c2001-09-13 13:46:56 +00003240/* Move the cursor to the first entry in the table. Return SQLITE_OK
3241** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003242** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00003243*/
drh3aac2dd2004-04-26 14:10:20 +00003244int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00003245 int rc;
3246 rc = moveToRoot(pCur);
3247 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00003248 if( pCur->eState==CURSOR_INVALID ){
drhc39e0002004-05-07 23:50:57 +00003249 assert( pCur->pPage->nCell==0 );
drh5e00f6c2001-09-13 13:46:56 +00003250 *pRes = 1;
3251 return SQLITE_OK;
3252 }
drhc39e0002004-05-07 23:50:57 +00003253 assert( pCur->pPage->nCell>0 );
drh5e00f6c2001-09-13 13:46:56 +00003254 *pRes = 0;
3255 rc = moveToLeftmost(pCur);
3256 return rc;
3257}
drh5e2f8b92001-05-28 00:41:15 +00003258
drh9562b552002-02-19 15:00:07 +00003259/* Move the cursor to the last entry in the table. Return SQLITE_OK
3260** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003261** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00003262*/
drh3aac2dd2004-04-26 14:10:20 +00003263int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00003264 int rc;
drh9562b552002-02-19 15:00:07 +00003265 rc = moveToRoot(pCur);
3266 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00003267 if( CURSOR_INVALID==pCur->eState ){
drhc39e0002004-05-07 23:50:57 +00003268 assert( pCur->pPage->nCell==0 );
drh9562b552002-02-19 15:00:07 +00003269 *pRes = 1;
3270 return SQLITE_OK;
3271 }
danielk1977da184232006-01-05 11:34:32 +00003272 assert( pCur->eState==CURSOR_VALID );
drh9562b552002-02-19 15:00:07 +00003273 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003274 rc = moveToRightmost(pCur);
drh9562b552002-02-19 15:00:07 +00003275 return rc;
3276}
3277
drh3aac2dd2004-04-26 14:10:20 +00003278/* Move the cursor so that it points to an entry near pKey/nKey.
drh72f82862001-05-24 21:06:34 +00003279** Return a success code.
3280**
drh3aac2dd2004-04-26 14:10:20 +00003281** For INTKEY tables, only the nKey parameter is used. pKey is
3282** ignored. For other tables, nKey is the number of bytes of data
drh0b2f3162005-12-21 18:36:45 +00003283** in pKey. The comparison function specified when the cursor was
drh3aac2dd2004-04-26 14:10:20 +00003284** created is used to compare keys.
3285**
drh5e2f8b92001-05-28 00:41:15 +00003286** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00003287** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00003288** were present. The cursor might point to an entry that comes
3289** before or after the key.
3290**
drhbd03cae2001-06-02 02:40:57 +00003291** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00003292** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00003293** this value is as follows:
3294**
3295** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00003296** is smaller than pKey or if the table is empty
3297** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00003298**
3299** *pRes==0 The cursor is left pointing at an entry that
3300** exactly matches pKey.
3301**
3302** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00003303** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00003304*/
drh4a1c3802004-05-12 15:15:47 +00003305int sqlite3BtreeMoveto(BtCursor *pCur, const void *pKey, i64 nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00003306 int rc;
drh5e2f8b92001-05-28 00:41:15 +00003307 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00003308 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00003309 assert( pCur->pPage );
3310 assert( pCur->pPage->isInit );
danielk1977da184232006-01-05 11:34:32 +00003311 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00003312 *pRes = -1;
drhc39e0002004-05-07 23:50:57 +00003313 assert( pCur->pPage->nCell==0 );
3314 return SQLITE_OK;
3315 }
drh4eec4c12005-01-21 00:22:37 +00003316 for(;;){
drh72f82862001-05-24 21:06:34 +00003317 int lwr, upr;
3318 Pgno chldPg;
3319 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00003320 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00003321 lwr = 0;
3322 upr = pPage->nCell-1;
drh4eec4c12005-01-21 00:22:37 +00003323 if( !pPage->intKey && pKey==0 ){
drh49285702005-09-17 15:20:26 +00003324 return SQLITE_CORRUPT_BKPT;
drh4eec4c12005-01-21 00:22:37 +00003325 }
drhda200cc2004-05-09 11:51:38 +00003326 pageIntegrity(pPage);
drh72f82862001-05-24 21:06:34 +00003327 while( lwr<=upr ){
danielk197713adf8a2004-06-03 16:08:41 +00003328 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00003329 i64 nCellKey;
drh72f82862001-05-24 21:06:34 +00003330 pCur->idx = (lwr+upr)/2;
drh271efa52004-05-30 19:19:05 +00003331 pCur->info.nSize = 0;
drhde647132004-05-07 17:57:49 +00003332 sqlite3BtreeKeySize(pCur, &nCellKey);
drh3aac2dd2004-04-26 14:10:20 +00003333 if( pPage->intKey ){
3334 if( nCellKey<nKey ){
3335 c = -1;
3336 }else if( nCellKey>nKey ){
3337 c = +1;
3338 }else{
3339 c = 0;
3340 }
drh3aac2dd2004-04-26 14:10:20 +00003341 }else{
drhe51c44f2004-05-30 20:46:09 +00003342 int available;
danielk197713adf8a2004-06-03 16:08:41 +00003343 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drhe51c44f2004-05-30 20:46:09 +00003344 if( available>=nCellKey ){
3345 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
3346 }else{
3347 pCellKey = sqliteMallocRaw( nCellKey );
3348 if( pCellKey==0 ) return SQLITE_NOMEM;
danielk197713adf8a2004-06-03 16:08:41 +00003349 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
drhe51c44f2004-05-30 20:46:09 +00003350 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
3351 sqliteFree(pCellKey);
3352 if( rc ) return rc;
3353 }
drh3aac2dd2004-04-26 14:10:20 +00003354 }
drh72f82862001-05-24 21:06:34 +00003355 if( c==0 ){
drh8b18dd42004-05-12 19:18:15 +00003356 if( pPage->leafData && !pPage->leaf ){
drhfc70e6f2004-05-12 21:11:27 +00003357 lwr = pCur->idx;
3358 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00003359 break;
3360 }else{
drh8b18dd42004-05-12 19:18:15 +00003361 if( pRes ) *pRes = 0;
3362 return SQLITE_OK;
3363 }
drh72f82862001-05-24 21:06:34 +00003364 }
3365 if( c<0 ){
3366 lwr = pCur->idx+1;
3367 }else{
3368 upr = pCur->idx-1;
3369 }
3370 }
3371 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00003372 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00003373 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00003374 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00003375 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00003376 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00003377 }else{
drh43605152004-05-29 21:46:49 +00003378 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00003379 }
3380 if( chldPg==0 ){
drhc39e0002004-05-07 23:50:57 +00003381 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00003382 if( pRes ) *pRes = c;
3383 return SQLITE_OK;
3384 }
drh428ae8c2003-01-04 16:48:09 +00003385 pCur->idx = lwr;
drh271efa52004-05-30 19:19:05 +00003386 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00003387 rc = moveToChild(pCur, chldPg);
drhc39e0002004-05-07 23:50:57 +00003388 if( rc ){
3389 return rc;
3390 }
drh72f82862001-05-24 21:06:34 +00003391 }
drhbd03cae2001-06-02 02:40:57 +00003392 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00003393}
3394
3395/*
drhc39e0002004-05-07 23:50:57 +00003396** Return TRUE if the cursor is not pointing at an entry of the table.
3397**
3398** TRUE will be returned after a call to sqlite3BtreeNext() moves
3399** past the last entry in the table or sqlite3BtreePrev() moves past
3400** the first entry. TRUE is also returned if the table is empty.
3401*/
3402int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00003403 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
3404 ** have been deleted? This API will need to change to return an error code
3405 ** as well as the boolean result value.
3406 */
3407 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00003408}
3409
3410/*
drhbd03cae2001-06-02 02:40:57 +00003411** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00003412** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00003413** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00003414** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00003415*/
drh3aac2dd2004-04-26 14:10:20 +00003416int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00003417 int rc;
drh8178a752003-01-05 21:41:40 +00003418 MemPage *pPage = pCur->pPage;
drh8b18dd42004-05-12 19:18:15 +00003419
danielk1977da184232006-01-05 11:34:32 +00003420#ifndef SQLITE_OMIT_SHARED_CACHE
3421 rc = restoreCursorPosition(pCur, 1);
3422 if( rc!=SQLITE_OK ){
3423 return rc;
3424 }
3425 if( pCur->skip>0 ){
3426 pCur->skip = 0;
3427 *pRes = 0;
3428 return SQLITE_OK;
3429 }
3430 pCur->skip = 0;
3431#endif
3432
drh8c1238a2003-01-02 14:43:55 +00003433 assert( pRes!=0 );
danielk1977da184232006-01-05 11:34:32 +00003434 if( CURSOR_INVALID==pCur->eState ){
drh8c1238a2003-01-02 14:43:55 +00003435 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00003436 return SQLITE_OK;
drhecdc7532001-09-23 02:35:53 +00003437 }
drh8178a752003-01-05 21:41:40 +00003438 assert( pPage->isInit );
drh8178a752003-01-05 21:41:40 +00003439 assert( pCur->idx<pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00003440
drh72f82862001-05-24 21:06:34 +00003441 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00003442 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00003443 if( pCur->idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00003444 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003445 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00003446 if( rc ) return rc;
3447 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003448 *pRes = 0;
3449 return rc;
drh72f82862001-05-24 21:06:34 +00003450 }
drh5e2f8b92001-05-28 00:41:15 +00003451 do{
drh8856d6a2004-04-29 14:42:46 +00003452 if( isRootPage(pPage) ){
drh8c1238a2003-01-02 14:43:55 +00003453 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00003454 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00003455 return SQLITE_OK;
3456 }
drh8178a752003-01-05 21:41:40 +00003457 moveToParent(pCur);
3458 pPage = pCur->pPage;
3459 }while( pCur->idx>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00003460 *pRes = 0;
drh8b18dd42004-05-12 19:18:15 +00003461 if( pPage->leafData ){
3462 rc = sqlite3BtreeNext(pCur, pRes);
3463 }else{
3464 rc = SQLITE_OK;
3465 }
3466 return rc;
drh8178a752003-01-05 21:41:40 +00003467 }
3468 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00003469 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00003470 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00003471 }
drh5e2f8b92001-05-28 00:41:15 +00003472 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003473 return rc;
drh72f82862001-05-24 21:06:34 +00003474}
3475
drh3b7511c2001-05-26 13:15:44 +00003476/*
drh2dcc9aa2002-12-04 13:40:25 +00003477** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00003478** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00003479** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00003480** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00003481*/
drh3aac2dd2004-04-26 14:10:20 +00003482int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00003483 int rc;
3484 Pgno pgno;
drh8178a752003-01-05 21:41:40 +00003485 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00003486
3487#ifndef SQLITE_OMIT_SHARED_CACHE
3488 rc = restoreCursorPosition(pCur, 1);
3489 if( rc!=SQLITE_OK ){
3490 return rc;
3491 }
3492 if( pCur->skip<0 ){
3493 pCur->skip = 0;
3494 *pRes = 0;
3495 return SQLITE_OK;
3496 }
3497 pCur->skip = 0;
3498#endif
3499
3500 if( CURSOR_INVALID==pCur->eState ){
drhc39e0002004-05-07 23:50:57 +00003501 *pRes = 1;
3502 return SQLITE_OK;
3503 }
danielk19776a43f9b2004-11-16 04:57:24 +00003504
drh8178a752003-01-05 21:41:40 +00003505 pPage = pCur->pPage;
drh8178a752003-01-05 21:41:40 +00003506 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00003507 assert( pCur->idx>=0 );
drha34b6762004-05-07 13:30:42 +00003508 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003509 pgno = get4byte( findCell(pPage, pCur->idx) );
drh8178a752003-01-05 21:41:40 +00003510 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003511 if( rc ) return rc;
3512 rc = moveToRightmost(pCur);
3513 }else{
3514 while( pCur->idx==0 ){
drh8856d6a2004-04-29 14:42:46 +00003515 if( isRootPage(pPage) ){
danielk1977da184232006-01-05 11:34:32 +00003516 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00003517 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00003518 return SQLITE_OK;
3519 }
drh8178a752003-01-05 21:41:40 +00003520 moveToParent(pCur);
3521 pPage = pCur->pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003522 }
3523 pCur->idx--;
drh271efa52004-05-30 19:19:05 +00003524 pCur->info.nSize = 0;
drh8237d452004-11-22 19:07:09 +00003525 if( pPage->leafData && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00003526 rc = sqlite3BtreePrevious(pCur, pRes);
3527 }else{
3528 rc = SQLITE_OK;
3529 }
drh2dcc9aa2002-12-04 13:40:25 +00003530 }
drh8178a752003-01-05 21:41:40 +00003531 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003532 return rc;
3533}
3534
3535/*
drh3b7511c2001-05-26 13:15:44 +00003536** Allocate a new page from the database file.
3537**
drha34b6762004-05-07 13:30:42 +00003538** The new page is marked as dirty. (In other words, sqlite3pager_write()
drh3b7511c2001-05-26 13:15:44 +00003539** has already been called on the new page.) The new page has also
3540** been referenced and the calling routine is responsible for calling
drha34b6762004-05-07 13:30:42 +00003541** sqlite3pager_unref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00003542**
3543** SQLITE_OK is returned on success. Any other return value indicates
3544** an error. *ppPage and *pPgno are undefined in the event of an error.
drha34b6762004-05-07 13:30:42 +00003545** Do not invoke sqlite3pager_unref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00003546**
drh199e3cf2002-07-18 11:01:47 +00003547** If the "nearby" parameter is not 0, then a (feeble) effort is made to
3548** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00003549** attempt to keep related pages close to each other in the database file,
3550** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00003551**
3552** If the "exact" parameter is not 0, and the page-number nearby exists
3553** anywhere on the free-list, then it is guarenteed to be returned. This
3554** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00003555*/
danielk1977cb1a7eb2004-11-05 12:27:02 +00003556static int allocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00003557 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00003558 MemPage **ppPage,
3559 Pgno *pPgno,
3560 Pgno nearby,
3561 u8 exact
3562){
drh3aac2dd2004-04-26 14:10:20 +00003563 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00003564 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003565 int n; /* Number of pages on the freelist */
3566 int k; /* Number of leaves on the trunk of the freelist */
drh30e58752002-03-02 20:41:57 +00003567
drh3aac2dd2004-04-26 14:10:20 +00003568 pPage1 = pBt->pPage1;
3569 n = get4byte(&pPage1->aData[36]);
3570 if( n>0 ){
drh91025292004-05-03 19:49:32 +00003571 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00003572 MemPage *pTrunk = 0;
3573 Pgno iTrunk;
3574 MemPage *pPrevTrunk = 0;
3575 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
3576
3577 /* If the 'exact' parameter was true and a query of the pointer-map
3578 ** shows that the page 'nearby' is somewhere on the free-list, then
3579 ** the entire-list will be searched for that page.
3580 */
3581#ifndef SQLITE_OMIT_AUTOVACUUM
3582 if( exact ){
3583 u8 eType;
3584 assert( nearby>0 );
3585 assert( pBt->autoVacuum );
3586 rc = ptrmapGet(pBt, nearby, &eType, 0);
3587 if( rc ) return rc;
3588 if( eType==PTRMAP_FREEPAGE ){
3589 searchList = 1;
3590 }
3591 *pPgno = nearby;
3592 }
3593#endif
3594
3595 /* Decrement the free-list count by 1. Set iTrunk to the index of the
3596 ** first free-list trunk page. iPrevTrunk is initially 1.
3597 */
drha34b6762004-05-07 13:30:42 +00003598 rc = sqlite3pager_write(pPage1->aData);
drh3b7511c2001-05-26 13:15:44 +00003599 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003600 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003601
3602 /* The code within this loop is run only once if the 'searchList' variable
3603 ** is not true. Otherwise, it runs once for each trunk-page on the
3604 ** free-list until the page 'nearby' is located.
3605 */
3606 do {
3607 pPrevTrunk = pTrunk;
3608 if( pPrevTrunk ){
3609 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00003610 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00003611 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00003612 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003613 rc = getPage(pBt, iTrunk, &pTrunk);
3614 if( rc ){
3615 releasePage(pPrevTrunk);
3616 return rc;
3617 }
3618
3619 /* TODO: This should move to after the loop? */
3620 rc = sqlite3pager_write(pTrunk->aData);
3621 if( rc ){
3622 releasePage(pTrunk);
3623 releasePage(pPrevTrunk);
3624 return rc;
3625 }
3626
3627 k = get4byte(&pTrunk->aData[4]);
3628 if( k==0 && !searchList ){
3629 /* The trunk has no leaves and the list is not being searched.
3630 ** So extract the trunk page itself and use it as the newly
3631 ** allocated page */
3632 assert( pPrevTrunk==0 );
3633 *pPgno = iTrunk;
3634 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3635 *ppPage = pTrunk;
3636 pTrunk = 0;
3637 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3638 }else if( k>pBt->usableSize/4 - 8 ){
3639 /* Value of k is out of range. Database corruption */
drh49285702005-09-17 15:20:26 +00003640 return SQLITE_CORRUPT_BKPT;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003641#ifndef SQLITE_OMIT_AUTOVACUUM
3642 }else if( searchList && nearby==iTrunk ){
3643 /* The list is being searched and this trunk page is the page
3644 ** to allocate, regardless of whether it has leaves.
3645 */
3646 assert( *pPgno==iTrunk );
3647 *ppPage = pTrunk;
3648 searchList = 0;
3649 if( k==0 ){
3650 if( !pPrevTrunk ){
3651 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3652 }else{
3653 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
3654 }
3655 }else{
3656 /* The trunk page is required by the caller but it contains
3657 ** pointers to free-list leaves. The first leaf becomes a trunk
3658 ** page in this case.
3659 */
3660 MemPage *pNewTrunk;
3661 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
3662 rc = getPage(pBt, iNewTrunk, &pNewTrunk);
3663 if( rc!=SQLITE_OK ){
3664 releasePage(pTrunk);
3665 releasePage(pPrevTrunk);
3666 return rc;
3667 }
3668 rc = sqlite3pager_write(pNewTrunk->aData);
3669 if( rc!=SQLITE_OK ){
3670 releasePage(pNewTrunk);
3671 releasePage(pTrunk);
3672 releasePage(pPrevTrunk);
3673 return rc;
3674 }
3675 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
3676 put4byte(&pNewTrunk->aData[4], k-1);
3677 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
3678 if( !pPrevTrunk ){
3679 put4byte(&pPage1->aData[32], iNewTrunk);
3680 }else{
3681 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
3682 }
3683 releasePage(pNewTrunk);
3684 }
3685 pTrunk = 0;
3686 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3687#endif
3688 }else{
3689 /* Extract a leaf from the trunk */
3690 int closest;
3691 Pgno iPage;
3692 unsigned char *aData = pTrunk->aData;
3693 if( nearby>0 ){
3694 int i, dist;
3695 closest = 0;
3696 dist = get4byte(&aData[8]) - nearby;
3697 if( dist<0 ) dist = -dist;
3698 for(i=1; i<k; i++){
3699 int d2 = get4byte(&aData[8+i*4]) - nearby;
3700 if( d2<0 ) d2 = -d2;
3701 if( d2<dist ){
3702 closest = i;
3703 dist = d2;
3704 }
3705 }
3706 }else{
3707 closest = 0;
3708 }
3709
3710 iPage = get4byte(&aData[8+closest*4]);
3711 if( !searchList || iPage==nearby ){
3712 *pPgno = iPage;
3713 if( *pPgno>sqlite3pager_pagecount(pBt->pPager) ){
3714 /* Free page off the end of the file */
drh49285702005-09-17 15:20:26 +00003715 return SQLITE_CORRUPT_BKPT;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003716 }
3717 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
3718 ": %d more free pages\n",
3719 *pPgno, closest+1, k, pTrunk->pgno, n-1));
3720 if( closest<k-1 ){
3721 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
3722 }
3723 put4byte(&aData[4], k-1);
3724 rc = getPage(pBt, *pPgno, ppPage);
3725 if( rc==SQLITE_OK ){
3726 sqlite3pager_dont_rollback((*ppPage)->aData);
3727 rc = sqlite3pager_write((*ppPage)->aData);
danielk1977aac0a382005-01-16 11:07:06 +00003728 if( rc!=SQLITE_OK ){
3729 releasePage(*ppPage);
3730 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003731 }
3732 searchList = 0;
3733 }
drhee696e22004-08-30 16:52:17 +00003734 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003735 releasePage(pPrevTrunk);
3736 }while( searchList );
3737 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003738 }else{
drh3aac2dd2004-04-26 14:10:20 +00003739 /* There are no pages on the freelist, so create a new page at the
3740 ** end of the file */
drha34b6762004-05-07 13:30:42 +00003741 *pPgno = sqlite3pager_pagecount(pBt->pPager) + 1;
danielk1977afcdd022004-10-31 16:25:42 +00003742
3743#ifndef SQLITE_OMIT_AUTOVACUUM
drh42cac6d2004-11-20 20:31:11 +00003744 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt->usableSize, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00003745 /* If *pPgno refers to a pointer-map page, allocate two new pages
3746 ** at the end of the file instead of one. The first allocated page
3747 ** becomes a new pointer-map page, the second is used by the caller.
3748 */
3749 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00003750 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977afcdd022004-10-31 16:25:42 +00003751 (*pPgno)++;
3752 }
3753#endif
3754
danielk1977599fcba2004-11-08 07:13:13 +00003755 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00003756 rc = getPage(pBt, *pPgno, ppPage);
drh3b7511c2001-05-26 13:15:44 +00003757 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003758 rc = sqlite3pager_write((*ppPage)->aData);
danielk1977aac0a382005-01-16 11:07:06 +00003759 if( rc!=SQLITE_OK ){
3760 releasePage(*ppPage);
3761 }
drh3a4c1412004-05-09 20:40:11 +00003762 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00003763 }
danielk1977599fcba2004-11-08 07:13:13 +00003764
3765 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh3b7511c2001-05-26 13:15:44 +00003766 return rc;
3767}
3768
3769/*
drh3aac2dd2004-04-26 14:10:20 +00003770** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00003771**
drha34b6762004-05-07 13:30:42 +00003772** sqlite3pager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00003773*/
drh3aac2dd2004-04-26 14:10:20 +00003774static int freePage(MemPage *pPage){
danielk1977aef0bf62005-12-30 16:28:01 +00003775 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00003776 MemPage *pPage1 = pBt->pPage1;
3777 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00003778
drh3aac2dd2004-04-26 14:10:20 +00003779 /* Prepare the page for freeing */
3780 assert( pPage->pgno>1 );
3781 pPage->isInit = 0;
3782 releasePage(pPage->pParent);
3783 pPage->pParent = 0;
3784
drha34b6762004-05-07 13:30:42 +00003785 /* Increment the free page count on pPage1 */
3786 rc = sqlite3pager_write(pPage1->aData);
drh3aac2dd2004-04-26 14:10:20 +00003787 if( rc ) return rc;
3788 n = get4byte(&pPage1->aData[36]);
3789 put4byte(&pPage1->aData[36], n+1);
3790
danielk1977687566d2004-11-02 12:56:41 +00003791#ifndef SQLITE_OMIT_AUTOVACUUM
3792 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00003793 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00003794 */
3795 if( pBt->autoVacuum ){
3796 rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
danielk1977a64a0352004-11-05 01:45:13 +00003797 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00003798 }
3799#endif
3800
drh3aac2dd2004-04-26 14:10:20 +00003801 if( n==0 ){
3802 /* This is the first free page */
drhda200cc2004-05-09 11:51:38 +00003803 rc = sqlite3pager_write(pPage->aData);
3804 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003805 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00003806 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003807 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003808 }else{
3809 /* Other free pages already exist. Retrive the first trunk page
3810 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00003811 MemPage *pTrunk;
3812 rc = getPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003813 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003814 k = get4byte(&pTrunk->aData[4]);
drhee696e22004-08-30 16:52:17 +00003815 if( k>=pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00003816 /* The trunk is full. Turn the page being freed into a new
3817 ** trunk page with no leaves. */
drha34b6762004-05-07 13:30:42 +00003818 rc = sqlite3pager_write(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00003819 if( rc ) return rc;
3820 put4byte(pPage->aData, pTrunk->pgno);
3821 put4byte(&pPage->aData[4], 0);
3822 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003823 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
3824 pPage->pgno, pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003825 }else{
3826 /* Add the newly freed page as a leaf on the current trunk */
drha34b6762004-05-07 13:30:42 +00003827 rc = sqlite3pager_write(pTrunk->aData);
drh3aac2dd2004-04-26 14:10:20 +00003828 if( rc ) return rc;
3829 put4byte(&pTrunk->aData[4], k+1);
3830 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drha34b6762004-05-07 13:30:42 +00003831 sqlite3pager_dont_write(pBt->pPager, pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003832 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003833 }
3834 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003835 }
drh3b7511c2001-05-26 13:15:44 +00003836 return rc;
3837}
3838
3839/*
drh3aac2dd2004-04-26 14:10:20 +00003840** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00003841*/
drh3aac2dd2004-04-26 14:10:20 +00003842static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00003843 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00003844 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00003845 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00003846 int rc;
drh3b7511c2001-05-26 13:15:44 +00003847
drh43605152004-05-29 21:46:49 +00003848 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003849 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00003850 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00003851 }
drh6f11bef2004-05-13 01:12:56 +00003852 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh3aac2dd2004-04-26 14:10:20 +00003853 while( ovflPgno!=0 ){
3854 MemPage *pOvfl;
danielk1977a1cb1832005-02-12 08:59:55 +00003855 if( ovflPgno>sqlite3pager_pagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00003856 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00003857 }
drh3aac2dd2004-04-26 14:10:20 +00003858 rc = getPage(pBt, ovflPgno, &pOvfl);
drh3b7511c2001-05-26 13:15:44 +00003859 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003860 ovflPgno = get4byte(pOvfl->aData);
drha34b6762004-05-07 13:30:42 +00003861 rc = freePage(pOvfl);
drha34b6762004-05-07 13:30:42 +00003862 sqlite3pager_unref(pOvfl->aData);
danielk19776b456a22005-03-21 04:04:02 +00003863 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00003864 }
drh5e2f8b92001-05-28 00:41:15 +00003865 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00003866}
3867
3868/*
drh91025292004-05-03 19:49:32 +00003869** Create the byte sequence used to represent a cell on page pPage
3870** and write that byte sequence into pCell[]. Overflow pages are
3871** allocated and filled in as necessary. The calling procedure
3872** is responsible for making sure sufficient space has been allocated
3873** for pCell[].
3874**
3875** Note that pCell does not necessary need to point to the pPage->aData
3876** area. pCell might point to some temporary storage. The cell will
3877** be constructed in this temporary area then copied into pPage->aData
3878** later.
drh3b7511c2001-05-26 13:15:44 +00003879*/
3880static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00003881 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00003882 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00003883 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00003884 const void *pData,int nData, /* The data */
3885 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00003886){
drh3b7511c2001-05-26 13:15:44 +00003887 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00003888 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00003889 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00003890 int spaceLeft;
3891 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00003892 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00003893 unsigned char *pPrior;
3894 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00003895 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00003896 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00003897 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00003898 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00003899
drh91025292004-05-03 19:49:32 +00003900 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00003901 nHeader = 0;
drh91025292004-05-03 19:49:32 +00003902 if( !pPage->leaf ){
3903 nHeader += 4;
3904 }
drh8b18dd42004-05-12 19:18:15 +00003905 if( pPage->hasData ){
drh91025292004-05-03 19:49:32 +00003906 nHeader += putVarint(&pCell[nHeader], nData);
drh6f11bef2004-05-13 01:12:56 +00003907 }else{
drh91025292004-05-03 19:49:32 +00003908 nData = 0;
3909 }
drh6f11bef2004-05-13 01:12:56 +00003910 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh43605152004-05-29 21:46:49 +00003911 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003912 assert( info.nHeader==nHeader );
3913 assert( info.nKey==nKey );
3914 assert( info.nData==nData );
3915
3916 /* Fill in the payload */
drh3aac2dd2004-04-26 14:10:20 +00003917 nPayload = nData;
3918 if( pPage->intKey ){
3919 pSrc = pData;
3920 nSrc = nData;
drh91025292004-05-03 19:49:32 +00003921 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00003922 }else{
3923 nPayload += nKey;
3924 pSrc = pKey;
3925 nSrc = nKey;
3926 }
drh6f11bef2004-05-13 01:12:56 +00003927 *pnSize = info.nSize;
3928 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00003929 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00003930 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00003931
drh3b7511c2001-05-26 13:15:44 +00003932 while( nPayload>0 ){
3933 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00003934#ifndef SQLITE_OMIT_AUTOVACUUM
3935 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
3936#endif
danielk1977cb1a7eb2004-11-05 12:27:02 +00003937 rc = allocatePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00003938#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00003939 /* If the database supports auto-vacuum, and the second or subsequent
3940 ** overflow page is being allocated, add an entry to the pointer-map
3941 ** for that page now. The entry for the first overflow page will be
3942 ** added later, by the insertCell() routine.
danielk1977afcdd022004-10-31 16:25:42 +00003943 */
danielk1977a19df672004-11-03 11:37:07 +00003944 if( pBt->autoVacuum && pgnoPtrmap!=0 && rc==SQLITE_OK ){
3945 rc = ptrmapPut(pBt, pgnoOvfl, PTRMAP_OVERFLOW2, pgnoPtrmap);
danielk1977afcdd022004-10-31 16:25:42 +00003946 }
3947#endif
drh3b7511c2001-05-26 13:15:44 +00003948 if( rc ){
drh9b171272004-05-08 02:03:22 +00003949 releasePage(pToRelease);
danielk197728129562005-01-11 10:25:06 +00003950 /* clearCell(pPage, pCell); */
drh3b7511c2001-05-26 13:15:44 +00003951 return rc;
3952 }
drh3aac2dd2004-04-26 14:10:20 +00003953 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00003954 releasePage(pToRelease);
3955 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00003956 pPrior = pOvfl->aData;
3957 put4byte(pPrior, 0);
3958 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00003959 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00003960 }
3961 n = nPayload;
3962 if( n>spaceLeft ) n = spaceLeft;
drh3aac2dd2004-04-26 14:10:20 +00003963 if( n>nSrc ) n = nSrc;
3964 memcpy(pPayload, pSrc, n);
drh3b7511c2001-05-26 13:15:44 +00003965 nPayload -= n;
drhde647132004-05-07 17:57:49 +00003966 pPayload += n;
drh9b171272004-05-08 02:03:22 +00003967 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00003968 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00003969 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00003970 if( nSrc==0 ){
3971 nSrc = nData;
3972 pSrc = pData;
3973 }
drhdd793422001-06-28 01:54:48 +00003974 }
drh9b171272004-05-08 02:03:22 +00003975 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00003976 return SQLITE_OK;
3977}
3978
3979/*
drhbd03cae2001-06-02 02:40:57 +00003980** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00003981** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00003982** pointer in the third argument.
3983*/
danielk1977aef0bf62005-12-30 16:28:01 +00003984static int reparentPage(BtShared *pBt, Pgno pgno, MemPage *pNewParent, int idx){
drhbd03cae2001-06-02 02:40:57 +00003985 MemPage *pThis;
drh4b70f112004-05-02 21:12:19 +00003986 unsigned char *aData;
drhbd03cae2001-06-02 02:40:57 +00003987
danielk1977afcdd022004-10-31 16:25:42 +00003988 if( pgno==0 ) return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00003989 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00003990 aData = sqlite3pager_lookup(pBt->pPager, pgno);
drhda200cc2004-05-09 11:51:38 +00003991 if( aData ){
drh07d183d2005-05-01 22:52:42 +00003992 pThis = (MemPage*)&aData[pBt->pageSize];
drh31276532004-09-27 12:20:52 +00003993 assert( pThis->aData==aData );
drhda200cc2004-05-09 11:51:38 +00003994 if( pThis->isInit ){
3995 if( pThis->pParent!=pNewParent ){
3996 if( pThis->pParent ) sqlite3pager_unref(pThis->pParent->aData);
3997 pThis->pParent = pNewParent;
3998 if( pNewParent ) sqlite3pager_ref(pNewParent->aData);
3999 }
4000 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00004001 }
drha34b6762004-05-07 13:30:42 +00004002 sqlite3pager_unref(aData);
drhbd03cae2001-06-02 02:40:57 +00004003 }
danielk1977afcdd022004-10-31 16:25:42 +00004004
4005#ifndef SQLITE_OMIT_AUTOVACUUM
4006 if( pBt->autoVacuum ){
4007 return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
4008 }
4009#endif
4010 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00004011}
4012
danielk1977ac11ee62005-01-15 12:45:51 +00004013
4014
drhbd03cae2001-06-02 02:40:57 +00004015/*
drh4b70f112004-05-02 21:12:19 +00004016** Change the pParent pointer of all children of pPage to point back
4017** to pPage.
4018**
drhbd03cae2001-06-02 02:40:57 +00004019** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00004020** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00004021**
4022** This routine gets called after you memcpy() one page into
4023** another.
4024*/
danielk1977afcdd022004-10-31 16:25:42 +00004025static int reparentChildPages(MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00004026 int i;
danielk1977aef0bf62005-12-30 16:28:01 +00004027 BtShared *pBt = pPage->pBt;
danielk1977afcdd022004-10-31 16:25:42 +00004028 int rc = SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00004029
danielk1977afcdd022004-10-31 16:25:42 +00004030 if( pPage->leaf ) return SQLITE_OK;
danielk1977afcdd022004-10-31 16:25:42 +00004031
drhbd03cae2001-06-02 02:40:57 +00004032 for(i=0; i<pPage->nCell; i++){
danielk1977afcdd022004-10-31 16:25:42 +00004033 u8 *pCell = findCell(pPage, i);
4034 if( !pPage->leaf ){
4035 rc = reparentPage(pBt, get4byte(pCell), pPage, i);
4036 if( rc!=SQLITE_OK ) return rc;
4037 }
drhbd03cae2001-06-02 02:40:57 +00004038 }
danielk1977afcdd022004-10-31 16:25:42 +00004039 if( !pPage->leaf ){
4040 rc = reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]),
4041 pPage, i);
4042 pPage->idxShift = 0;
4043 }
4044 return rc;
drh14acc042001-06-10 19:56:58 +00004045}
4046
4047/*
4048** Remove the i-th cell from pPage. This routine effects pPage only.
4049** The cell content is not freed or deallocated. It is assumed that
4050** the cell content has been copied someplace else. This routine just
4051** removes the reference to the cell from pPage.
4052**
4053** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00004054*/
drh4b70f112004-05-02 21:12:19 +00004055static void dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00004056 int i; /* Loop counter */
4057 int pc; /* Offset to cell content of cell being deleted */
4058 u8 *data; /* pPage->aData */
4059 u8 *ptr; /* Used to move bytes around within data[] */
4060
drh8c42ca92001-06-22 19:15:00 +00004061 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00004062 assert( sz==cellSize(pPage, idx) );
drha34b6762004-05-07 13:30:42 +00004063 assert( sqlite3pager_iswriteable(pPage->aData) );
drhda200cc2004-05-09 11:51:38 +00004064 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00004065 ptr = &data[pPage->cellOffset + 2*idx];
4066 pc = get2byte(ptr);
4067 assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
drhde647132004-05-07 17:57:49 +00004068 freeSpace(pPage, pc, sz);
drh43605152004-05-29 21:46:49 +00004069 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
4070 ptr[0] = ptr[2];
4071 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00004072 }
4073 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00004074 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
4075 pPage->nFree += 2;
drh428ae8c2003-01-04 16:48:09 +00004076 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00004077}
4078
4079/*
4080** Insert a new cell on pPage at cell index "i". pCell points to the
4081** content of the cell.
4082**
4083** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00004084** will not fit, then make a copy of the cell content into pTemp if
4085** pTemp is not null. Regardless of pTemp, allocate a new entry
4086** in pPage->aOvfl[] and make it point to the cell content (either
4087** in pTemp or the original pCell) and also record its index.
4088** Allocating a new entry in pPage->aCell[] implies that
4089** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00004090**
4091** If nSkip is non-zero, then do not copy the first nSkip bytes of the
4092** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00004093** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00004094** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00004095*/
danielk1977e80463b2004-11-03 03:01:16 +00004096static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00004097 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00004098 int i, /* New cell becomes the i-th cell of the page */
4099 u8 *pCell, /* Content of the new cell */
4100 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00004101 u8 *pTemp, /* Temp storage space for pCell, if needed */
4102 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00004103){
drh43605152004-05-29 21:46:49 +00004104 int idx; /* Where to write new cell content in data[] */
4105 int j; /* Loop counter */
4106 int top; /* First byte of content for any cell in data[] */
4107 int end; /* First byte past the last cell pointer in data[] */
4108 int ins; /* Index in data[] where new cell pointer is inserted */
4109 int hdr; /* Offset into data[] of the page header */
4110 int cellOffset; /* Address of first cell pointer in data[] */
4111 u8 *data; /* The content of the whole page */
4112 u8 *ptr; /* Used for moving information around in data[] */
4113
4114 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
4115 assert( sz==cellSizePtr(pPage, pCell) );
drha34b6762004-05-07 13:30:42 +00004116 assert( sqlite3pager_iswriteable(pPage->aData) );
drh43605152004-05-29 21:46:49 +00004117 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00004118 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00004119 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004120 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00004121 }
drh43605152004-05-29 21:46:49 +00004122 j = pPage->nOverflow++;
4123 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
4124 pPage->aOvfl[j].pCell = pCell;
4125 pPage->aOvfl[j].idx = i;
4126 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00004127 }else{
drh43605152004-05-29 21:46:49 +00004128 data = pPage->aData;
4129 hdr = pPage->hdrOffset;
4130 top = get2byte(&data[hdr+5]);
4131 cellOffset = pPage->cellOffset;
4132 end = cellOffset + 2*pPage->nCell + 2;
4133 ins = cellOffset + 2*i;
4134 if( end > top - sz ){
danielk19776b456a22005-03-21 04:04:02 +00004135 int rc = defragmentPage(pPage);
4136 if( rc!=SQLITE_OK ) return rc;
drh43605152004-05-29 21:46:49 +00004137 top = get2byte(&data[hdr+5]);
4138 assert( end + sz <= top );
4139 }
4140 idx = allocateSpace(pPage, sz);
4141 assert( idx>0 );
4142 assert( end <= get2byte(&data[hdr+5]) );
4143 pPage->nCell++;
4144 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00004145 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004146 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
4147 ptr[0] = ptr[-2];
4148 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00004149 }
drh43605152004-05-29 21:46:49 +00004150 put2byte(&data[ins], idx);
4151 put2byte(&data[hdr+3], pPage->nCell);
4152 pPage->idxShift = 1;
drhda200cc2004-05-09 11:51:38 +00004153 pageIntegrity(pPage);
danielk1977a19df672004-11-03 11:37:07 +00004154#ifndef SQLITE_OMIT_AUTOVACUUM
4155 if( pPage->pBt->autoVacuum ){
4156 /* The cell may contain a pointer to an overflow page. If so, write
4157 ** the entry for the overflow page into the pointer map.
4158 */
4159 CellInfo info;
4160 parseCellPtr(pPage, pCell, &info);
4161 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
4162 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
4163 int rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
4164 if( rc!=SQLITE_OK ) return rc;
4165 }
4166 }
4167#endif
drh14acc042001-06-10 19:56:58 +00004168 }
danielk1977e80463b2004-11-03 03:01:16 +00004169
danielk1977e80463b2004-11-03 03:01:16 +00004170 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004171}
4172
4173/*
drhfa1a98a2004-05-14 19:08:17 +00004174** Add a list of cells to a page. The page should be initially empty.
4175** The cells are guaranteed to fit on the page.
4176*/
4177static void assemblePage(
4178 MemPage *pPage, /* The page to be assemblied */
4179 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00004180 u8 **apCell, /* Pointers to cell bodies */
drhfa1a98a2004-05-14 19:08:17 +00004181 int *aSize /* Sizes of the cells */
4182){
4183 int i; /* Loop counter */
4184 int totalSize; /* Total size of all cells */
4185 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00004186 int cellptr; /* Address of next cell pointer */
4187 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00004188 u8 *data; /* Data for the page */
4189
drh43605152004-05-29 21:46:49 +00004190 assert( pPage->nOverflow==0 );
drhfa1a98a2004-05-14 19:08:17 +00004191 totalSize = 0;
4192 for(i=0; i<nCell; i++){
4193 totalSize += aSize[i];
4194 }
drh43605152004-05-29 21:46:49 +00004195 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00004196 assert( pPage->nCell==0 );
drh43605152004-05-29 21:46:49 +00004197 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00004198 data = pPage->aData;
4199 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00004200 put2byte(&data[hdr+3], nCell);
drh09d0deb2005-08-02 17:13:09 +00004201 if( nCell ){
4202 cellbody = allocateSpace(pPage, totalSize);
4203 assert( cellbody>0 );
4204 assert( pPage->nFree >= 2*nCell );
4205 pPage->nFree -= 2*nCell;
4206 for(i=0; i<nCell; i++){
4207 put2byte(&data[cellptr], cellbody);
4208 memcpy(&data[cellbody], apCell[i], aSize[i]);
4209 cellptr += 2;
4210 cellbody += aSize[i];
4211 }
4212 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00004213 }
4214 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00004215}
4216
drh14acc042001-06-10 19:56:58 +00004217/*
drhc3b70572003-01-04 19:44:07 +00004218** The following parameters determine how many adjacent pages get involved
4219** in a balancing operation. NN is the number of neighbors on either side
4220** of the page that participate in the balancing operation. NB is the
4221** total number of pages that participate, including the target page and
4222** NN neighbors on either side.
4223**
4224** The minimum value of NN is 1 (of course). Increasing NN above 1
4225** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
4226** in exchange for a larger degradation in INSERT and UPDATE performance.
4227** The value of NN appears to give the best results overall.
4228*/
4229#define NN 1 /* Number of neighbors on either side of pPage */
4230#define NB (NN*2+1) /* Total pages involved in the balance */
4231
drh43605152004-05-29 21:46:49 +00004232/* Forward reference */
danielk1977ac245ec2005-01-14 13:50:11 +00004233static int balance(MemPage*, int);
4234
drh615ae552005-01-16 23:21:00 +00004235#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004236/*
4237** This version of balance() handles the common special case where
4238** a new entry is being inserted on the extreme right-end of the
4239** tree, in other words, when the new entry will become the largest
4240** entry in the tree.
4241**
4242** Instead of trying balance the 3 right-most leaf pages, just add
4243** a new page to the right-hand side and put the one new entry in
4244** that page. This leaves the right side of the tree somewhat
4245** unbalanced. But odds are that we will be inserting new entries
4246** at the end soon afterwards so the nearly empty page will quickly
4247** fill up. On average.
4248**
4249** pPage is the leaf page which is the right-most page in the tree.
4250** pParent is its parent. pPage must have a single overflow entry
4251** which is also the right-most entry on the page.
4252*/
danielk1977ac245ec2005-01-14 13:50:11 +00004253static int balance_quick(MemPage *pPage, MemPage *pParent){
4254 int rc;
4255 MemPage *pNew;
4256 Pgno pgnoNew;
4257 u8 *pCell;
4258 int szCell;
4259 CellInfo info;
danielk1977aef0bf62005-12-30 16:28:01 +00004260 BtShared *pBt = pPage->pBt;
danielk197779a40da2005-01-16 08:00:01 +00004261 int parentIdx = pParent->nCell; /* pParent new divider cell index */
4262 int parentSize; /* Size of new divider cell */
4263 u8 parentCell[64]; /* Space for the new divider cell */
danielk1977ac245ec2005-01-14 13:50:11 +00004264
4265 /* Allocate a new page. Insert the overflow cell from pPage
4266 ** into it. Then remove the overflow cell from pPage.
4267 */
danielk1977ac11ee62005-01-15 12:45:51 +00004268 rc = allocatePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977ac245ec2005-01-14 13:50:11 +00004269 if( rc!=SQLITE_OK ){
4270 return rc;
4271 }
4272 pCell = pPage->aOvfl[0].pCell;
4273 szCell = cellSizePtr(pPage, pCell);
4274 zeroPage(pNew, pPage->aData[0]);
4275 assemblePage(pNew, 1, &pCell, &szCell);
4276 pPage->nOverflow = 0;
4277
danielk197779a40da2005-01-16 08:00:01 +00004278 /* Set the parent of the newly allocated page to pParent. */
4279 pNew->pParent = pParent;
4280 sqlite3pager_ref(pParent->aData);
4281
danielk1977ac245ec2005-01-14 13:50:11 +00004282 /* pPage is currently the right-child of pParent. Change this
4283 ** so that the right-child is the new page allocated above and
danielk197779a40da2005-01-16 08:00:01 +00004284 ** pPage is the next-to-right child.
danielk1977ac245ec2005-01-14 13:50:11 +00004285 */
danielk1977ac11ee62005-01-15 12:45:51 +00004286 assert( pPage->nCell>0 );
danielk1977ac245ec2005-01-14 13:50:11 +00004287 parseCellPtr(pPage, findCell(pPage, pPage->nCell-1), &info);
4288 rc = fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, &parentSize);
4289 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00004290 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004291 }
4292 assert( parentSize<64 );
4293 rc = insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
4294 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00004295 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004296 }
4297 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
4298 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
4299
danielk197779a40da2005-01-16 08:00:01 +00004300#ifndef SQLITE_OMIT_AUTOVACUUM
4301 /* If this is an auto-vacuum database, update the pointer map
4302 ** with entries for the new page, and any pointer from the
4303 ** cell on the page to an overflow page.
4304 */
danielk1977ac11ee62005-01-15 12:45:51 +00004305 if( pBt->autoVacuum ){
4306 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
4307 if( rc!=SQLITE_OK ){
4308 return rc;
4309 }
danielk197779a40da2005-01-16 08:00:01 +00004310 rc = ptrmapPutOvfl(pNew, 0);
4311 if( rc!=SQLITE_OK ){
4312 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00004313 }
4314 }
danielk197779a40da2005-01-16 08:00:01 +00004315#endif
danielk1977ac11ee62005-01-15 12:45:51 +00004316
danielk197779a40da2005-01-16 08:00:01 +00004317 /* Release the reference to the new page and balance the parent page,
4318 ** in case the divider cell inserted caused it to become overfull.
4319 */
danielk1977ac245ec2005-01-14 13:50:11 +00004320 releasePage(pNew);
4321 return balance(pParent, 0);
4322}
drh615ae552005-01-16 23:21:00 +00004323#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00004324
drhc3b70572003-01-04 19:44:07 +00004325/*
danielk1977ac11ee62005-01-15 12:45:51 +00004326** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
4327** if the database supports auto-vacuum or not. Because it is used
4328** within an expression that is an argument to another macro
4329** (sqliteMallocRaw), it is not possible to use conditional compilation.
4330** So, this macro is defined instead.
4331*/
4332#ifndef SQLITE_OMIT_AUTOVACUUM
4333#define ISAUTOVACUUM (pBt->autoVacuum)
4334#else
4335#define ISAUTOVACUUM 0
4336#endif
4337
4338/*
drhab01f612004-05-22 02:55:23 +00004339** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00004340** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00004341** Usually NN siblings on either side of pPage is used in the balancing,
4342** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00004343** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00004344** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00004345** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00004346**
drh0c6cc4e2004-06-15 02:13:26 +00004347** The number of siblings of pPage might be increased or decreased by one or
4348** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00004349** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00004350** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00004351** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00004352** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00004353**
drh8b2f49b2001-06-08 00:21:52 +00004354** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00004355** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00004356** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00004357** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00004358**
drh8c42ca92001-06-22 19:15:00 +00004359** In the course of balancing the siblings of pPage, the parent of pPage
4360** might become overfull or underfull. If that happens, then this routine
4361** is called recursively on the parent.
4362**
drh5e00f6c2001-09-13 13:46:56 +00004363** If this routine fails for any reason, it might leave the database
4364** in a corrupted state. So if this routine fails, the database should
4365** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00004366*/
drh43605152004-05-29 21:46:49 +00004367static int balance_nonroot(MemPage *pPage){
drh8b2f49b2001-06-08 00:21:52 +00004368 MemPage *pParent; /* The parent of pPage */
danielk1977aef0bf62005-12-30 16:28:01 +00004369 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00004370 int nCell = 0; /* Number of cells in apCell[] */
4371 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
drh8b2f49b2001-06-08 00:21:52 +00004372 int nOld; /* Number of pages in apOld[] */
4373 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00004374 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00004375 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00004376 int idx; /* Index of pPage in pParent->aCell[] */
4377 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00004378 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00004379 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00004380 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00004381 int usableSpace; /* Bytes in pPage beyond the header */
4382 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00004383 int subtotal; /* Subtotal of bytes in cells on one page */
drhb6f41482004-05-14 01:58:11 +00004384 int iSpace = 0; /* First unused byte of aSpace[] */
drhc3b70572003-01-04 19:44:07 +00004385 MemPage *apOld[NB]; /* pPage and up to two siblings */
4386 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00004387 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00004388 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
4389 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drh4b70f112004-05-02 21:12:19 +00004390 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00004391 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
4392 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00004393 u8 **apCell = 0; /* All cells begin balanced */
drh2e38c322004-09-03 18:38:44 +00004394 int *szCell; /* Local size of all cells in apCell[] */
4395 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
4396 u8 *aSpace; /* Space to hold copies of dividers cells */
danielk19774e17d142005-01-16 09:06:33 +00004397#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00004398 u8 *aFrom = 0;
4399#endif
drh8b2f49b2001-06-08 00:21:52 +00004400
drh14acc042001-06-10 19:56:58 +00004401 /*
drh43605152004-05-29 21:46:49 +00004402 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00004403 */
drh3a4c1412004-05-09 20:40:11 +00004404 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004405 assert( sqlite3pager_iswriteable(pPage->aData) );
drh4b70f112004-05-02 21:12:19 +00004406 pBt = pPage->pBt;
drh14acc042001-06-10 19:56:58 +00004407 pParent = pPage->pParent;
drh43605152004-05-29 21:46:49 +00004408 sqlite3pager_write(pParent->aData);
4409 assert( pParent );
4410 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00004411
drh615ae552005-01-16 23:21:00 +00004412#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004413 /*
4414 ** A special case: If a new entry has just been inserted into a
4415 ** table (that is, a btree with integer keys and all data at the leaves)
drh09d0deb2005-08-02 17:13:09 +00004416 ** and the new entry is the right-most entry in the tree (it has the
drhf222e712005-01-14 22:55:49 +00004417 ** largest key) then use the special balance_quick() routine for
4418 ** balancing. balance_quick() is much faster and results in a tighter
4419 ** packing of data in the common case.
4420 */
danielk1977ac245ec2005-01-14 13:50:11 +00004421 if( pPage->leaf &&
4422 pPage->intKey &&
4423 pPage->leafData &&
4424 pPage->nOverflow==1 &&
4425 pPage->aOvfl[0].idx==pPage->nCell &&
danielk1977ac11ee62005-01-15 12:45:51 +00004426 pPage->pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00004427 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
4428 ){
danielk1977ac11ee62005-01-15 12:45:51 +00004429 /*
4430 ** TODO: Check the siblings to the left of pPage. It may be that
4431 ** they are not full and no new page is required.
4432 */
danielk1977ac245ec2005-01-14 13:50:11 +00004433 return balance_quick(pPage, pParent);
4434 }
4435#endif
4436
drh2e38c322004-09-03 18:38:44 +00004437 /*
drh4b70f112004-05-02 21:12:19 +00004438 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00004439 ** to pPage. The "idx" variable is the index of that cell. If pPage
4440 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00004441 */
drhbb49aba2003-01-04 18:53:27 +00004442 if( pParent->idxShift ){
drha34b6762004-05-07 13:30:42 +00004443 Pgno pgno;
drh4b70f112004-05-02 21:12:19 +00004444 pgno = pPage->pgno;
drha34b6762004-05-07 13:30:42 +00004445 assert( pgno==sqlite3pager_pagenumber(pPage->aData) );
drhbb49aba2003-01-04 18:53:27 +00004446 for(idx=0; idx<pParent->nCell; idx++){
drh43605152004-05-29 21:46:49 +00004447 if( get4byte(findCell(pParent, idx))==pgno ){
drhbb49aba2003-01-04 18:53:27 +00004448 break;
4449 }
drh8b2f49b2001-06-08 00:21:52 +00004450 }
drh4b70f112004-05-02 21:12:19 +00004451 assert( idx<pParent->nCell
drh43605152004-05-29 21:46:49 +00004452 || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
drhbb49aba2003-01-04 18:53:27 +00004453 }else{
4454 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00004455 }
drh8b2f49b2001-06-08 00:21:52 +00004456
4457 /*
drh14acc042001-06-10 19:56:58 +00004458 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00004459 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00004460 */
drh14acc042001-06-10 19:56:58 +00004461 nOld = nNew = 0;
drha34b6762004-05-07 13:30:42 +00004462 sqlite3pager_ref(pParent->aData);
drh14acc042001-06-10 19:56:58 +00004463
4464 /*
drh4b70f112004-05-02 21:12:19 +00004465 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00004466 ** the siblings. An attempt is made to find NN siblings on either
4467 ** side of pPage. More siblings are taken from one side, however, if
4468 ** pPage there are fewer than NN siblings on the other side. If pParent
4469 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00004470 */
drhc3b70572003-01-04 19:44:07 +00004471 nxDiv = idx - NN;
4472 if( nxDiv + NB > pParent->nCell ){
4473 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00004474 }
drhc3b70572003-01-04 19:44:07 +00004475 if( nxDiv<0 ){
4476 nxDiv = 0;
4477 }
drh8b2f49b2001-06-08 00:21:52 +00004478 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00004479 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00004480 if( k<pParent->nCell ){
drh43605152004-05-29 21:46:49 +00004481 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00004482 nDiv++;
drha34b6762004-05-07 13:30:42 +00004483 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00004484 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00004485 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00004486 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00004487 }else{
4488 break;
drh8b2f49b2001-06-08 00:21:52 +00004489 }
drhde647132004-05-07 17:57:49 +00004490 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00004491 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00004492 apOld[i]->idxParent = k;
drh91025292004-05-03 19:49:32 +00004493 apCopy[i] = 0;
4494 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00004495 nOld++;
danielk1977634f2982005-03-28 08:44:07 +00004496 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
drh8b2f49b2001-06-08 00:21:52 +00004497 }
4498
drh8d97f1f2005-05-05 18:14:13 +00004499 /* Make nMaxCells a multiple of 2 in order to preserve 8-byte
4500 ** alignment */
4501 nMaxCells = (nMaxCells + 1)&~1;
4502
drh8b2f49b2001-06-08 00:21:52 +00004503 /*
danielk1977634f2982005-03-28 08:44:07 +00004504 ** Allocate space for memory structures
4505 */
4506 apCell = sqliteMallocRaw(
4507 nMaxCells*sizeof(u8*) /* apCell */
4508 + nMaxCells*sizeof(int) /* szCell */
drhc96d8532005-05-03 12:30:33 +00004509 + ROUND8(sizeof(MemPage))*NB /* aCopy */
drh07d183d2005-05-01 22:52:42 +00004510 + pBt->pageSize*(5+NB) /* aSpace */
drhc96d8532005-05-03 12:30:33 +00004511 + (ISAUTOVACUUM ? nMaxCells : 0) /* aFrom */
danielk1977634f2982005-03-28 08:44:07 +00004512 );
4513 if( apCell==0 ){
4514 rc = SQLITE_NOMEM;
4515 goto balance_cleanup;
4516 }
4517 szCell = (int*)&apCell[nMaxCells];
4518 aCopy[0] = (u8*)&szCell[nMaxCells];
drhc96d8532005-05-03 12:30:33 +00004519 assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004520 for(i=1; i<NB; i++){
drhc96d8532005-05-03 12:30:33 +00004521 aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
4522 assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004523 }
drhc96d8532005-05-03 12:30:33 +00004524 aSpace = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
4525 assert( ((aSpace - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004526#ifndef SQLITE_OMIT_AUTOVACUUM
4527 if( pBt->autoVacuum ){
drh07d183d2005-05-01 22:52:42 +00004528 aFrom = &aSpace[5*pBt->pageSize];
danielk1977634f2982005-03-28 08:44:07 +00004529 }
4530#endif
4531
4532 /*
drh14acc042001-06-10 19:56:58 +00004533 ** Make copies of the content of pPage and its siblings into aOld[].
4534 ** The rest of this function will use data from the copies rather
4535 ** that the original pages since the original pages will be in the
4536 ** process of being overwritten.
4537 */
4538 for(i=0; i<nOld; i++){
drh07d183d2005-05-01 22:52:42 +00004539 MemPage *p = apCopy[i] = (MemPage*)&aCopy[i][pBt->pageSize];
drh07d183d2005-05-01 22:52:42 +00004540 p->aData = &((u8*)p)[-pBt->pageSize];
4541 memcpy(p->aData, apOld[i]->aData, pBt->pageSize + sizeof(MemPage));
4542 /* The memcpy() above changes the value of p->aData so we have to
4543 ** set it again. */
drh07d183d2005-05-01 22:52:42 +00004544 p->aData = &((u8*)p)[-pBt->pageSize];
drh14acc042001-06-10 19:56:58 +00004545 }
4546
4547 /*
4548 ** Load pointers to all cells on sibling pages and the divider cells
4549 ** into the local apCell[] array. Make copies of the divider cells
drhb6f41482004-05-14 01:58:11 +00004550 ** into space obtained form aSpace[] and remove the the divider Cells
4551 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00004552 **
4553 ** If the siblings are on leaf pages, then the child pointers of the
4554 ** divider cells are stripped from the cells before they are copied
drh96f5b762004-05-16 16:24:36 +00004555 ** into aSpace[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00004556 ** child pointers. If siblings are not leaves, then all cell in
4557 ** apCell[] include child pointers. Either way, all cells in apCell[]
4558 ** are alike.
drh96f5b762004-05-16 16:24:36 +00004559 **
4560 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
4561 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00004562 */
4563 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00004564 leafCorrection = pPage->leaf*4;
drh8b18dd42004-05-12 19:18:15 +00004565 leafData = pPage->leafData && pPage->leaf;
drh8b2f49b2001-06-08 00:21:52 +00004566 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00004567 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00004568 int limit = pOld->nCell+pOld->nOverflow;
4569 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00004570 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00004571 apCell[nCell] = findOverflowCell(pOld, j);
4572 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk1977ac11ee62005-01-15 12:45:51 +00004573#ifndef SQLITE_OMIT_AUTOVACUUM
4574 if( pBt->autoVacuum ){
4575 int a;
4576 aFrom[nCell] = i;
4577 for(a=0; a<pOld->nOverflow; a++){
4578 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
4579 aFrom[nCell] = 0xFF;
4580 break;
4581 }
4582 }
4583 }
4584#endif
drh14acc042001-06-10 19:56:58 +00004585 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00004586 }
4587 if( i<nOld-1 ){
drh43605152004-05-29 21:46:49 +00004588 int sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00004589 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00004590 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
4591 ** are duplicates of keys on the child pages. We need to remove
4592 ** the divider cells from pParent, but the dividers cells are not
4593 ** added to apCell[] because they are duplicates of child cells.
4594 */
drh8b18dd42004-05-12 19:18:15 +00004595 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00004596 }else{
drhb6f41482004-05-14 01:58:11 +00004597 u8 *pTemp;
danielk1977634f2982005-03-28 08:44:07 +00004598 assert( nCell<nMaxCells );
drhb6f41482004-05-14 01:58:11 +00004599 szCell[nCell] = sz;
4600 pTemp = &aSpace[iSpace];
4601 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004602 assert( iSpace<=pBt->pageSize*5 );
drhb6f41482004-05-14 01:58:11 +00004603 memcpy(pTemp, apDiv[i], sz);
4604 apCell[nCell] = pTemp+leafCorrection;
danielk1977ac11ee62005-01-15 12:45:51 +00004605#ifndef SQLITE_OMIT_AUTOVACUUM
4606 if( pBt->autoVacuum ){
4607 aFrom[nCell] = 0xFF;
4608 }
4609#endif
drhb6f41482004-05-14 01:58:11 +00004610 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00004611 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00004612 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00004613 if( !pOld->leaf ){
4614 assert( leafCorrection==0 );
4615 /* The right pointer of the child page pOld becomes the left
4616 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00004617 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00004618 }else{
4619 assert( leafCorrection==4 );
4620 }
4621 nCell++;
drh4b70f112004-05-02 21:12:19 +00004622 }
drh8b2f49b2001-06-08 00:21:52 +00004623 }
4624 }
4625
4626 /*
drh6019e162001-07-02 17:51:45 +00004627 ** Figure out the number of pages needed to hold all nCell cells.
4628 ** Store this number in "k". Also compute szNew[] which is the total
4629 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00004630 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00004631 ** cntNew[k] should equal nCell.
4632 **
drh96f5b762004-05-16 16:24:36 +00004633 ** Values computed by this block:
4634 **
4635 ** k: The total number of sibling pages
4636 ** szNew[i]: Spaced used on the i-th sibling page.
4637 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
4638 ** the right of the i-th sibling page.
4639 ** usableSpace: Number of bytes of space available on each sibling.
4640 **
drh8b2f49b2001-06-08 00:21:52 +00004641 */
drh43605152004-05-29 21:46:49 +00004642 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00004643 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00004644 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00004645 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00004646 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00004647 szNew[k] = subtotal - szCell[i];
4648 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00004649 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00004650 subtotal = 0;
4651 k++;
4652 }
4653 }
4654 szNew[k] = subtotal;
4655 cntNew[k] = nCell;
4656 k++;
drh96f5b762004-05-16 16:24:36 +00004657
4658 /*
4659 ** The packing computed by the previous block is biased toward the siblings
4660 ** on the left side. The left siblings are always nearly full, while the
4661 ** right-most sibling might be nearly empty. This block of code attempts
4662 ** to adjust the packing of siblings to get a better balance.
4663 **
4664 ** This adjustment is more than an optimization. The packing above might
4665 ** be so out of balance as to be illegal. For example, the right-most
4666 ** sibling might be completely empty. This adjustment is not optional.
4667 */
drh6019e162001-07-02 17:51:45 +00004668 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00004669 int szRight = szNew[i]; /* Size of sibling on the right */
4670 int szLeft = szNew[i-1]; /* Size of sibling on the left */
4671 int r; /* Index of right-most cell in left sibling */
4672 int d; /* Index of first cell to the left of right sibling */
4673
4674 r = cntNew[i-1] - 1;
4675 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00004676 assert( d<nMaxCells );
4677 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00004678 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
4679 szRight += szCell[d] + 2;
4680 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00004681 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00004682 r = cntNew[i-1] - 1;
4683 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00004684 }
drh96f5b762004-05-16 16:24:36 +00004685 szNew[i] = szRight;
4686 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00004687 }
drh09d0deb2005-08-02 17:13:09 +00004688
4689 /* Either we found one or more cells (cntnew[0])>0) or we are the
4690 ** a virtual root page. A virtual root page is when the real root
4691 ** page is page 1 and we are the only child of that page.
4692 */
4693 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00004694
4695 /*
drh6b308672002-07-08 02:16:37 +00004696 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00004697 */
drh4b70f112004-05-02 21:12:19 +00004698 assert( pPage->pgno>1 );
4699 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00004700 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00004701 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00004702 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00004703 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00004704 pgnoNew[i] = pgnoOld[i];
4705 apOld[i] = 0;
danielk197728129562005-01-11 10:25:06 +00004706 rc = sqlite3pager_write(pNew->aData);
4707 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00004708 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004709 rc = allocatePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00004710 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00004711 apNew[i] = pNew;
drh6b308672002-07-08 02:16:37 +00004712 }
drh14acc042001-06-10 19:56:58 +00004713 nNew++;
drhda200cc2004-05-09 11:51:38 +00004714 zeroPage(pNew, pageFlags);
drh8b2f49b2001-06-08 00:21:52 +00004715 }
4716
danielk1977299b1872004-11-22 10:02:10 +00004717 /* Free any old pages that were not reused as new pages.
4718 */
4719 while( i<nOld ){
4720 rc = freePage(apOld[i]);
4721 if( rc ) goto balance_cleanup;
4722 releasePage(apOld[i]);
4723 apOld[i] = 0;
4724 i++;
4725 }
4726
drh8b2f49b2001-06-08 00:21:52 +00004727 /*
drhf9ffac92002-03-02 19:00:31 +00004728 ** Put the new pages in accending order. This helps to
4729 ** keep entries in the disk file in order so that a scan
4730 ** of the table is a linear scan through the file. That
4731 ** in turn helps the operating system to deliver pages
4732 ** from the disk more rapidly.
4733 **
4734 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00004735 ** n is never more than NB (a small constant), that should
4736 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00004737 **
drhc3b70572003-01-04 19:44:07 +00004738 ** When NB==3, this one optimization makes the database
4739 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00004740 */
4741 for(i=0; i<k-1; i++){
4742 int minV = pgnoNew[i];
4743 int minI = i;
4744 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00004745 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00004746 minI = j;
4747 minV = pgnoNew[j];
4748 }
4749 }
4750 if( minI>i ){
4751 int t;
4752 MemPage *pT;
4753 t = pgnoNew[i];
4754 pT = apNew[i];
4755 pgnoNew[i] = pgnoNew[minI];
4756 apNew[i] = apNew[minI];
4757 pgnoNew[minI] = t;
4758 apNew[minI] = pT;
4759 }
4760 }
drha2fce642004-06-05 00:01:44 +00004761 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00004762 pgnoOld[0],
4763 nOld>=2 ? pgnoOld[1] : 0,
4764 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00004765 pgnoNew[0], szNew[0],
4766 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
4767 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00004768 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
4769 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00004770
drhf9ffac92002-03-02 19:00:31 +00004771 /*
drh14acc042001-06-10 19:56:58 +00004772 ** Evenly distribute the data in apCell[] across the new pages.
4773 ** Insert divider cells into pParent as necessary.
4774 */
4775 j = 0;
4776 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00004777 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00004778 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00004779 assert( j<nMaxCells );
drh4b70f112004-05-02 21:12:19 +00004780 assert( pNew->pgno==pgnoNew[i] );
drhfa1a98a2004-05-14 19:08:17 +00004781 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00004782 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00004783 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00004784
4785#ifndef SQLITE_OMIT_AUTOVACUUM
4786 /* If this is an auto-vacuum database, update the pointer map entries
4787 ** that point to the siblings that were rearranged. These can be: left
4788 ** children of cells, the right-child of the page, or overflow pages
4789 ** pointed to by cells.
4790 */
4791 if( pBt->autoVacuum ){
4792 for(k=j; k<cntNew[i]; k++){
danielk1977634f2982005-03-28 08:44:07 +00004793 assert( k<nMaxCells );
danielk1977ac11ee62005-01-15 12:45:51 +00004794 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
danielk197779a40da2005-01-16 08:00:01 +00004795 rc = ptrmapPutOvfl(pNew, k-j);
4796 if( rc!=SQLITE_OK ){
4797 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00004798 }
4799 }
4800 }
4801 }
4802#endif
4803
4804 j = cntNew[i];
4805
4806 /* If the sibling page assembled above was not the right-most sibling,
4807 ** insert a divider cell into the parent page.
4808 */
drh14acc042001-06-10 19:56:58 +00004809 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00004810 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00004811 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00004812 int sz;
danielk1977634f2982005-03-28 08:44:07 +00004813
4814 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00004815 pCell = apCell[j];
4816 sz = szCell[j] + leafCorrection;
drh4b70f112004-05-02 21:12:19 +00004817 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00004818 memcpy(&pNew->aData[8], pCell, 4);
drh24cd67e2004-05-10 16:18:47 +00004819 pTemp = 0;
drh8b18dd42004-05-12 19:18:15 +00004820 }else if( leafData ){
danielk1977ac11ee62005-01-15 12:45:51 +00004821 /* If the tree is a leaf-data tree, and the siblings are leaves,
4822 ** then there is no divider cell in apCell[]. Instead, the divider
4823 ** cell consists of the integer key for the right-most cell of
4824 ** the sibling-page assembled above only.
4825 */
drh6f11bef2004-05-13 01:12:56 +00004826 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00004827 j--;
drh43605152004-05-29 21:46:49 +00004828 parseCellPtr(pNew, apCell[j], &info);
drhb6f41482004-05-14 01:58:11 +00004829 pCell = &aSpace[iSpace];
drh6f11bef2004-05-13 01:12:56 +00004830 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, &sz);
drhb6f41482004-05-14 01:58:11 +00004831 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004832 assert( iSpace<=pBt->pageSize*5 );
drh8b18dd42004-05-12 19:18:15 +00004833 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00004834 }else{
4835 pCell -= 4;
drhb6f41482004-05-14 01:58:11 +00004836 pTemp = &aSpace[iSpace];
4837 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004838 assert( iSpace<=pBt->pageSize*5 );
drh4b70f112004-05-02 21:12:19 +00004839 }
danielk1977a3ad5e72005-01-07 08:56:44 +00004840 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00004841 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh43605152004-05-29 21:46:49 +00004842 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +00004843#ifndef SQLITE_OMIT_AUTOVACUUM
4844 /* If this is an auto-vacuum database, and not a leaf-data tree,
4845 ** then update the pointer map with an entry for the overflow page
4846 ** that the cell just inserted points to (if any).
4847 */
4848 if( pBt->autoVacuum && !leafData ){
danielk197779a40da2005-01-16 08:00:01 +00004849 rc = ptrmapPutOvfl(pParent, nxDiv);
4850 if( rc!=SQLITE_OK ){
4851 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00004852 }
4853 }
4854#endif
drh14acc042001-06-10 19:56:58 +00004855 j++;
4856 nxDiv++;
4857 }
4858 }
drh6019e162001-07-02 17:51:45 +00004859 assert( j==nCell );
drh4b70f112004-05-02 21:12:19 +00004860 if( (pageFlags & PTF_LEAF)==0 ){
drh43605152004-05-29 21:46:49 +00004861 memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
drh14acc042001-06-10 19:56:58 +00004862 }
drh43605152004-05-29 21:46:49 +00004863 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00004864 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00004865 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00004866 }else{
4867 /* Right-most sibling is the left child of the first entry in pParent
4868 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00004869 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00004870 }
4871
4872 /*
4873 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00004874 */
4875 for(i=0; i<nNew; i++){
danielk1977afcdd022004-10-31 16:25:42 +00004876 rc = reparentChildPages(apNew[i]);
4877 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004878 }
danielk1977afcdd022004-10-31 16:25:42 +00004879 rc = reparentChildPages(pParent);
4880 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004881
4882 /*
drh3a4c1412004-05-09 20:40:11 +00004883 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00004884 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00004885 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00004886 */
drhda200cc2004-05-09 11:51:38 +00004887 assert( pParent->isInit );
drh3a4c1412004-05-09 20:40:11 +00004888 /* assert( pPage->isInit ); // No! pPage might have been added to freelist */
4889 /* pageIntegrity(pPage); // No! pPage might have been added to freelist */
danielk1977ac245ec2005-01-14 13:50:11 +00004890 rc = balance(pParent, 0);
drhda200cc2004-05-09 11:51:38 +00004891
drh8b2f49b2001-06-08 00:21:52 +00004892 /*
drh14acc042001-06-10 19:56:58 +00004893 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00004894 */
drh14acc042001-06-10 19:56:58 +00004895balance_cleanup:
drh2e38c322004-09-03 18:38:44 +00004896 sqliteFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00004897 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00004898 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00004899 }
drh14acc042001-06-10 19:56:58 +00004900 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00004901 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00004902 }
drh91025292004-05-03 19:49:32 +00004903 releasePage(pParent);
drh3a4c1412004-05-09 20:40:11 +00004904 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
4905 pPage->pgno, nOld, nNew, nCell));
drh8b2f49b2001-06-08 00:21:52 +00004906 return rc;
4907}
4908
4909/*
drh43605152004-05-29 21:46:49 +00004910** This routine is called for the root page of a btree when the root
4911** page contains no cells. This is an opportunity to make the tree
4912** shallower by one level.
4913*/
4914static int balance_shallower(MemPage *pPage){
4915 MemPage *pChild; /* The only child page of pPage */
4916 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00004917 int rc = SQLITE_OK; /* Return code from subprocedures */
danielk1977aef0bf62005-12-30 16:28:01 +00004918 BtShared *pBt; /* The main BTree structure */
drh2e38c322004-09-03 18:38:44 +00004919 int mxCellPerPage; /* Maximum number of cells per page */
4920 u8 **apCell; /* All cells from pages being balanced */
4921 int *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00004922
4923 assert( pPage->pParent==0 );
4924 assert( pPage->nCell==0 );
drh2e38c322004-09-03 18:38:44 +00004925 pBt = pPage->pBt;
4926 mxCellPerPage = MX_CELL(pBt);
4927 apCell = sqliteMallocRaw( mxCellPerPage*(sizeof(u8*)+sizeof(int)) );
4928 if( apCell==0 ) return SQLITE_NOMEM;
4929 szCell = (int*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00004930 if( pPage->leaf ){
4931 /* The table is completely empty */
4932 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
4933 }else{
4934 /* The root page is empty but has one child. Transfer the
4935 ** information from that one child into the root page if it
4936 ** will fit. This reduces the depth of the tree by one.
4937 **
4938 ** If the root page is page 1, it has less space available than
4939 ** its child (due to the 100 byte header that occurs at the beginning
4940 ** of the database fle), so it might not be able to hold all of the
4941 ** information currently contained in the child. If this is the
4942 ** case, then do not do the transfer. Leave page 1 empty except
4943 ** for the right-pointer to the child page. The child page becomes
4944 ** the virtual root of the tree.
4945 */
4946 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
4947 assert( pgnoChild>0 );
4948 assert( pgnoChild<=sqlite3pager_pagecount(pPage->pBt->pPager) );
4949 rc = getPage(pPage->pBt, pgnoChild, &pChild);
drh2e38c322004-09-03 18:38:44 +00004950 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004951 if( pPage->pgno==1 ){
4952 rc = initPage(pChild, pPage);
drh2e38c322004-09-03 18:38:44 +00004953 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004954 assert( pChild->nOverflow==0 );
4955 if( pChild->nFree>=100 ){
4956 /* The child information will fit on the root page, so do the
4957 ** copy */
4958 int i;
4959 zeroPage(pPage, pChild->aData[0]);
4960 for(i=0; i<pChild->nCell; i++){
4961 apCell[i] = findCell(pChild,i);
4962 szCell[i] = cellSizePtr(pChild, apCell[i]);
4963 }
4964 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00004965 /* Copy the right-pointer of the child to the parent. */
4966 put4byte(&pPage->aData[pPage->hdrOffset+8],
4967 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh43605152004-05-29 21:46:49 +00004968 freePage(pChild);
4969 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
4970 }else{
4971 /* The child has more information that will fit on the root.
4972 ** The tree is already balanced. Do nothing. */
4973 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
4974 }
4975 }else{
4976 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
4977 pPage->isInit = 0;
4978 pPage->pParent = 0;
4979 rc = initPage(pPage, 0);
4980 assert( rc==SQLITE_OK );
4981 freePage(pChild);
4982 TRACE(("BALANCE: transfer child %d into root %d\n",
4983 pChild->pgno, pPage->pgno));
4984 }
danielk1977afcdd022004-10-31 16:25:42 +00004985 rc = reparentChildPages(pPage);
danielk1977ac11ee62005-01-15 12:45:51 +00004986 assert( pPage->nOverflow==0 );
4987#ifndef SQLITE_OMIT_AUTOVACUUM
4988 if( pBt->autoVacuum ){
danielk1977aac0a382005-01-16 11:07:06 +00004989 int i;
danielk1977ac11ee62005-01-15 12:45:51 +00004990 for(i=0; i<pPage->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00004991 rc = ptrmapPutOvfl(pPage, i);
4992 if( rc!=SQLITE_OK ){
4993 goto end_shallow_balance;
danielk1977ac11ee62005-01-15 12:45:51 +00004994 }
4995 }
4996 }
4997#endif
danielk1977afcdd022004-10-31 16:25:42 +00004998 if( rc!=SQLITE_OK ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004999 releasePage(pChild);
5000 }
drh2e38c322004-09-03 18:38:44 +00005001end_shallow_balance:
5002 sqliteFree(apCell);
5003 return rc;
drh43605152004-05-29 21:46:49 +00005004}
5005
5006
5007/*
5008** The root page is overfull
5009**
5010** When this happens, Create a new child page and copy the
5011** contents of the root into the child. Then make the root
5012** page an empty page with rightChild pointing to the new
5013** child. Finally, call balance_internal() on the new child
5014** to cause it to split.
5015*/
5016static int balance_deeper(MemPage *pPage){
5017 int rc; /* Return value from subprocedures */
5018 MemPage *pChild; /* Pointer to a new child page */
5019 Pgno pgnoChild; /* Page number of the new child page */
danielk1977aef0bf62005-12-30 16:28:01 +00005020 BtShared *pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00005021 int usableSize; /* Total usable size of a page */
5022 u8 *data; /* Content of the parent page */
5023 u8 *cdata; /* Content of the child page */
5024 int hdr; /* Offset to page header in parent */
5025 int brk; /* Offset to content of first cell in parent */
5026
5027 assert( pPage->pParent==0 );
5028 assert( pPage->nOverflow>0 );
5029 pBt = pPage->pBt;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005030 rc = allocatePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00005031 if( rc ) return rc;
5032 assert( sqlite3pager_iswriteable(pChild->aData) );
5033 usableSize = pBt->usableSize;
5034 data = pPage->aData;
5035 hdr = pPage->hdrOffset;
5036 brk = get2byte(&data[hdr+5]);
5037 cdata = pChild->aData;
5038 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
5039 memcpy(&cdata[brk], &data[brk], usableSize-brk);
danielk1977c7dc7532004-11-17 10:22:03 +00005040 assert( pChild->isInit==0 );
drh43605152004-05-29 21:46:49 +00005041 rc = initPage(pChild, pPage);
danielk19776b456a22005-03-21 04:04:02 +00005042 if( rc ) goto balancedeeper_out;
drh43605152004-05-29 21:46:49 +00005043 memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
5044 pChild->nOverflow = pPage->nOverflow;
5045 if( pChild->nOverflow ){
5046 pChild->nFree = 0;
5047 }
5048 assert( pChild->nCell==pPage->nCell );
5049 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
5050 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
5051 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
danielk19774e17d142005-01-16 09:06:33 +00005052#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00005053 if( pBt->autoVacuum ){
5054 int i;
5055 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
danielk19776b456a22005-03-21 04:04:02 +00005056 if( rc ) goto balancedeeper_out;
danielk1977ac11ee62005-01-15 12:45:51 +00005057 for(i=0; i<pChild->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00005058 rc = ptrmapPutOvfl(pChild, i);
5059 if( rc!=SQLITE_OK ){
5060 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00005061 }
5062 }
5063 }
danielk19774e17d142005-01-16 09:06:33 +00005064#endif
drh43605152004-05-29 21:46:49 +00005065 rc = balance_nonroot(pChild);
danielk19776b456a22005-03-21 04:04:02 +00005066
5067balancedeeper_out:
drh43605152004-05-29 21:46:49 +00005068 releasePage(pChild);
5069 return rc;
5070}
5071
5072/*
5073** Decide if the page pPage needs to be balanced. If balancing is
5074** required, call the appropriate balancing routine.
5075*/
danielk1977ac245ec2005-01-14 13:50:11 +00005076static int balance(MemPage *pPage, int insert){
drh43605152004-05-29 21:46:49 +00005077 int rc = SQLITE_OK;
5078 if( pPage->pParent==0 ){
5079 if( pPage->nOverflow>0 ){
5080 rc = balance_deeper(pPage);
5081 }
danielk1977687566d2004-11-02 12:56:41 +00005082 if( rc==SQLITE_OK && pPage->nCell==0 ){
drh43605152004-05-29 21:46:49 +00005083 rc = balance_shallower(pPage);
5084 }
5085 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00005086 if( pPage->nOverflow>0 ||
5087 (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
drh43605152004-05-29 21:46:49 +00005088 rc = balance_nonroot(pPage);
5089 }
5090 }
5091 return rc;
5092}
5093
5094/*
drh8dcd7ca2004-08-08 19:43:29 +00005095** This routine checks all cursors that point to table pgnoRoot.
5096** If any of those cursors other than pExclude were opened with
drhf74b8d92002-09-01 23:20:45 +00005097** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
drh8dcd7ca2004-08-08 19:43:29 +00005098** cursors that point to pgnoRoot were opened with wrFlag==1
drhf74b8d92002-09-01 23:20:45 +00005099** then this routine returns SQLITE_OK.
danielk1977299b1872004-11-22 10:02:10 +00005100**
5101** In addition to checking for read-locks (where a read-lock
5102** means a cursor opened with wrFlag==0) this routine also moves
5103** all cursors other than pExclude so that they are pointing to the
5104** first Cell on root page. This is necessary because an insert
5105** or delete might change the number of cells on a page or delete
5106** a page entirely and we do not want to leave any cursors
5107** pointing to non-existant pages or cells.
drhf74b8d92002-09-01 23:20:45 +00005108*/
danielk1977aef0bf62005-12-30 16:28:01 +00005109static int checkReadLocks(BtShared *pBt, Pgno pgnoRoot, BtCursor *pExclude){
danielk1977299b1872004-11-22 10:02:10 +00005110 BtCursor *p;
5111 for(p=pBt->pCursor; p; p=p->pNext){
danielk1977da184232006-01-05 11:34:32 +00005112 u32 flags = (p->pBtree->pSqlite ? p->pBtree->pSqlite->flags : 0);
danielk1977299b1872004-11-22 10:02:10 +00005113 if( p->pgnoRoot!=pgnoRoot || p==pExclude ) continue;
danielk1977da184232006-01-05 11:34:32 +00005114 if( p->wrFlag==0 && flags&SQLITE_ReadUncommitted ) continue;
danielk1977299b1872004-11-22 10:02:10 +00005115 if( p->wrFlag==0 ) return SQLITE_LOCKED;
5116 if( p->pPage->pgno!=p->pgnoRoot ){
5117 moveToRoot(p);
5118 }
5119 }
drhf74b8d92002-09-01 23:20:45 +00005120 return SQLITE_OK;
5121}
5122
5123/*
drh3b7511c2001-05-26 13:15:44 +00005124** Insert a new record into the BTree. The key is given by (pKey,nKey)
5125** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00005126** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00005127** is left pointing at a random location.
5128**
5129** For an INTKEY table, only the nKey value of the key is used. pKey is
5130** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00005131*/
drh3aac2dd2004-04-26 14:10:20 +00005132int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00005133 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00005134 const void *pKey, i64 nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00005135 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00005136){
drh3b7511c2001-05-26 13:15:44 +00005137 int rc;
5138 int loc;
drh14acc042001-06-10 19:56:58 +00005139 int szNew;
drh3b7511c2001-05-26 13:15:44 +00005140 MemPage *pPage;
danielk1977aef0bf62005-12-30 16:28:01 +00005141 BtShared *pBt = pCur->pBtree->pBt;
drha34b6762004-05-07 13:30:42 +00005142 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00005143 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00005144
danielk1977aef0bf62005-12-30 16:28:01 +00005145 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005146 /* Must start a transaction before doing an insert */
5147 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005148 }
drhf74b8d92002-09-01 23:20:45 +00005149 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00005150 if( !pCur->wrFlag ){
5151 return SQLITE_PERM; /* Cursor not open for writing */
5152 }
drh8dcd7ca2004-08-08 19:43:29 +00005153 if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00005154 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5155 }
danielk1977da184232006-01-05 11:34:32 +00005156
5157 /* Save the positions of any other cursors open on this table */
5158 restoreCursorPosition(pCur, 0);
5159 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
5160 if( rc ){
5161 return rc;
5162 }
5163
drh3aac2dd2004-04-26 14:10:20 +00005164 rc = sqlite3BtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00005165 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00005166 pPage = pCur->pPage;
drh4a1c3802004-05-12 15:15:47 +00005167 assert( pPage->intKey || nKey>=0 );
drh8b18dd42004-05-12 19:18:15 +00005168 assert( pPage->leaf || !pPage->leafData );
drh3a4c1412004-05-09 20:40:11 +00005169 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
5170 pCur->pgnoRoot, nKey, nData, pPage->pgno,
5171 loc==0 ? "overwrite" : "new entry"));
drh7aa128d2002-06-21 13:09:16 +00005172 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00005173 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00005174 if( rc ) return rc;
drh2e38c322004-09-03 18:38:44 +00005175 newCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
5176 if( newCell==0 ) return SQLITE_NOMEM;
drha34b6762004-05-07 13:30:42 +00005177 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, &szNew);
drh2e38c322004-09-03 18:38:44 +00005178 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00005179 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00005180 assert( szNew<=MX_CELL_SIZE(pBt) );
danielk1977da184232006-01-05 11:34:32 +00005181 if( loc==0 && CURSOR_VALID==pCur->eState ){
drha34b6762004-05-07 13:30:42 +00005182 int szOld;
5183 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00005184 oldCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005185 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005186 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00005187 }
drh43605152004-05-29 21:46:49 +00005188 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00005189 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00005190 if( rc ) goto end_insert;
drh4b70f112004-05-02 21:12:19 +00005191 dropCell(pPage, pCur->idx, szOld);
drh7c717f72001-06-24 20:39:41 +00005192 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00005193 assert( pPage->leaf );
drh14acc042001-06-10 19:56:58 +00005194 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00005195 pCur->info.nSize = 0;
drh14acc042001-06-10 19:56:58 +00005196 }else{
drh4b70f112004-05-02 21:12:19 +00005197 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00005198 }
danielk1977a3ad5e72005-01-07 08:56:44 +00005199 rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
danielk1977e80463b2004-11-03 03:01:16 +00005200 if( rc!=SQLITE_OK ) goto end_insert;
danielk1977ac245ec2005-01-14 13:50:11 +00005201 rc = balance(pPage, 1);
drh23e11ca2004-05-04 17:27:28 +00005202 /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
drh3fc190c2001-09-14 03:24:23 +00005203 /* fflush(stdout); */
danielk1977299b1872004-11-22 10:02:10 +00005204 if( rc==SQLITE_OK ){
5205 moveToRoot(pCur);
5206 }
drh2e38c322004-09-03 18:38:44 +00005207end_insert:
5208 sqliteFree(newCell);
drh5e2f8b92001-05-28 00:41:15 +00005209 return rc;
5210}
5211
5212/*
drh4b70f112004-05-02 21:12:19 +00005213** Delete the entry that the cursor is pointing to. The cursor
5214** is left pointing at a random location.
drh3b7511c2001-05-26 13:15:44 +00005215*/
drh3aac2dd2004-04-26 14:10:20 +00005216int sqlite3BtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00005217 MemPage *pPage = pCur->pPage;
drh4b70f112004-05-02 21:12:19 +00005218 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00005219 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00005220 Pgno pgnoChild = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00005221 BtShared *pBt = pCur->pBtree->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005222
drh7aa128d2002-06-21 13:09:16 +00005223 assert( pPage->isInit );
danielk1977aef0bf62005-12-30 16:28:01 +00005224 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005225 /* Must start a transaction before doing a delete */
5226 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005227 }
drhf74b8d92002-09-01 23:20:45 +00005228 assert( !pBt->readOnly );
drhbd03cae2001-06-02 02:40:57 +00005229 if( pCur->idx >= pPage->nCell ){
5230 return SQLITE_ERROR; /* The cursor is not pointing to anything */
5231 }
drhecdc7532001-09-23 02:35:53 +00005232 if( !pCur->wrFlag ){
5233 return SQLITE_PERM; /* Did not open this cursor for writing */
5234 }
drh8dcd7ca2004-08-08 19:43:29 +00005235 if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00005236 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5237 }
danielk1977da184232006-01-05 11:34:32 +00005238
5239 /* Restore the current cursor position (a no-op if the cursor is not in
5240 ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
5241 ** open on the same table. Then call sqlite3pager_write() on the page
5242 ** that the entry will be deleted from.
5243 */
5244 if(
5245 (rc = restoreCursorPosition(pCur, 1)) ||
5246 (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
5247 (rc = sqlite3pager_write(pPage->aData))
5248 ){
5249 return rc;
5250 }
danielk1977e6efa742004-11-10 11:55:10 +00005251
5252 /* Locate the cell within it's page and leave pCell pointing to the
5253 ** data. The clearCell() call frees any overflow pages associated with the
5254 ** cell. The cell itself is still intact.
5255 */
danielk1977299b1872004-11-22 10:02:10 +00005256 pCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005257 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005258 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005259 }
danielk197728129562005-01-11 10:25:06 +00005260 rc = clearCell(pPage, pCell);
5261 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00005262
drh4b70f112004-05-02 21:12:19 +00005263 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00005264 /*
drh5e00f6c2001-09-13 13:46:56 +00005265 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00005266 ** do something we will leave a hole on an internal page.
5267 ** We have to fill the hole by moving in a cell from a leaf. The
5268 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00005269 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00005270 */
drh14acc042001-06-10 19:56:58 +00005271 BtCursor leafCur;
drh4b70f112004-05-02 21:12:19 +00005272 unsigned char *pNext;
drh14acc042001-06-10 19:56:58 +00005273 int szNext;
danielk1977299b1872004-11-22 10:02:10 +00005274 int notUsed;
danielk19776b456a22005-03-21 04:04:02 +00005275 unsigned char *tempCell = 0;
drh8b18dd42004-05-12 19:18:15 +00005276 assert( !pPage->leafData );
drh14acc042001-06-10 19:56:58 +00005277 getTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00005278 rc = sqlite3BtreeNext(&leafCur, &notUsed);
drh14acc042001-06-10 19:56:58 +00005279 if( rc!=SQLITE_OK ){
drhee696e22004-08-30 16:52:17 +00005280 if( rc!=SQLITE_NOMEM ){
drh49285702005-09-17 15:20:26 +00005281 rc = SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00005282 }
drh5e2f8b92001-05-28 00:41:15 +00005283 }
danielk19776b456a22005-03-21 04:04:02 +00005284 if( rc==SQLITE_OK ){
5285 rc = sqlite3pager_write(leafCur.pPage->aData);
5286 }
5287 if( rc==SQLITE_OK ){
5288 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
5289 pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
5290 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
5291 pNext = findCell(leafCur.pPage, leafCur.idx);
5292 szNext = cellSizePtr(leafCur.pPage, pNext);
5293 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
5294 tempCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
5295 if( tempCell==0 ){
5296 rc = SQLITE_NOMEM;
5297 }
5298 }
5299 if( rc==SQLITE_OK ){
5300 rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
5301 }
5302 if( rc==SQLITE_OK ){
5303 put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
5304 rc = balance(pPage, 0);
5305 }
5306 if( rc==SQLITE_OK ){
5307 dropCell(leafCur.pPage, leafCur.idx, szNext);
5308 rc = balance(leafCur.pPage, 0);
5309 }
drh2e38c322004-09-03 18:38:44 +00005310 sqliteFree(tempCell);
drh8c42ca92001-06-22 19:15:00 +00005311 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00005312 }else{
danielk1977299b1872004-11-22 10:02:10 +00005313 TRACE(("DELETE: table=%d delete from leaf %d\n",
5314 pCur->pgnoRoot, pPage->pgno));
5315 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
danielk1977ac245ec2005-01-14 13:50:11 +00005316 rc = balance(pPage, 0);
drh5e2f8b92001-05-28 00:41:15 +00005317 }
danielk19776b456a22005-03-21 04:04:02 +00005318 if( rc==SQLITE_OK ){
5319 moveToRoot(pCur);
5320 }
drh5e2f8b92001-05-28 00:41:15 +00005321 return rc;
drh3b7511c2001-05-26 13:15:44 +00005322}
drh8b2f49b2001-06-08 00:21:52 +00005323
5324/*
drhc6b52df2002-01-04 03:09:29 +00005325** Create a new BTree table. Write into *piTable the page
5326** number for the root page of the new table.
5327**
drhab01f612004-05-22 02:55:23 +00005328** The type of type is determined by the flags parameter. Only the
5329** following values of flags are currently in use. Other values for
5330** flags might not work:
5331**
5332** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
5333** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00005334*/
danielk1977aef0bf62005-12-30 16:28:01 +00005335int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
5336 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005337 MemPage *pRoot;
5338 Pgno pgnoRoot;
5339 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00005340 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005341 /* Must start a transaction first */
5342 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005343 }
danielk197728129562005-01-11 10:25:06 +00005344 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00005345
5346 /* It is illegal to create a table if any cursors are open on the
5347 ** database. This is because in auto-vacuum mode the backend may
5348 ** need to move a database page to make room for the new root-page.
5349 ** If an open cursor was using the page a problem would occur.
5350 */
5351 if( pBt->pCursor ){
5352 return SQLITE_LOCKED;
5353 }
5354
danielk1977003ba062004-11-04 02:57:33 +00005355#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977cb1a7eb2004-11-05 12:27:02 +00005356 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drh8b2f49b2001-06-08 00:21:52 +00005357 if( rc ) return rc;
danielk1977003ba062004-11-04 02:57:33 +00005358#else
danielk1977687566d2004-11-02 12:56:41 +00005359 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00005360 Pgno pgnoMove; /* Move a page here to make room for the root-page */
5361 MemPage *pPageMove; /* The page to move to. */
5362
danielk1977003ba062004-11-04 02:57:33 +00005363 /* Read the value of meta[3] from the database to determine where the
5364 ** root page of the new table should go. meta[3] is the largest root-page
5365 ** created so far, so the new root-page is (meta[3]+1).
5366 */
danielk1977aef0bf62005-12-30 16:28:01 +00005367 rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00005368 if( rc!=SQLITE_OK ) return rc;
5369 pgnoRoot++;
5370
danielk1977599fcba2004-11-08 07:13:13 +00005371 /* The new root-page may not be allocated on a pointer-map page, or the
5372 ** PENDING_BYTE page.
5373 */
drh42cac6d2004-11-20 20:31:11 +00005374 if( pgnoRoot==PTRMAP_PAGENO(pBt->usableSize, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00005375 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00005376 pgnoRoot++;
5377 }
5378 assert( pgnoRoot>=3 );
5379
5380 /* Allocate a page. The page that currently resides at pgnoRoot will
5381 ** be moved to the allocated page (unless the allocated page happens
5382 ** to reside at pgnoRoot).
5383 */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005384 rc = allocatePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00005385 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00005386 return rc;
5387 }
danielk1977003ba062004-11-04 02:57:33 +00005388
5389 if( pgnoMove!=pgnoRoot ){
5390 u8 eType;
5391 Pgno iPtrPage;
5392
5393 releasePage(pPageMove);
5394 rc = getPage(pBt, pgnoRoot, &pRoot);
5395 if( rc!=SQLITE_OK ){
5396 return rc;
5397 }
5398 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drhccae6022005-02-26 17:31:26 +00005399 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00005400 releasePage(pRoot);
5401 return rc;
5402 }
drhccae6022005-02-26 17:31:26 +00005403 assert( eType!=PTRMAP_ROOTPAGE );
5404 assert( eType!=PTRMAP_FREEPAGE );
danielk19775fd057a2005-03-09 13:09:43 +00005405 rc = sqlite3pager_write(pRoot->aData);
5406 if( rc!=SQLITE_OK ){
5407 releasePage(pRoot);
5408 return rc;
5409 }
danielk1977003ba062004-11-04 02:57:33 +00005410 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove);
5411 releasePage(pRoot);
5412 if( rc!=SQLITE_OK ){
5413 return rc;
5414 }
5415 rc = getPage(pBt, pgnoRoot, &pRoot);
5416 if( rc!=SQLITE_OK ){
5417 return rc;
5418 }
5419 rc = sqlite3pager_write(pRoot->aData);
5420 if( rc!=SQLITE_OK ){
5421 releasePage(pRoot);
5422 return rc;
5423 }
5424 }else{
5425 pRoot = pPageMove;
5426 }
5427
danielk197742741be2005-01-08 12:42:39 +00005428 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00005429 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
5430 if( rc ){
5431 releasePage(pRoot);
5432 return rc;
5433 }
danielk1977aef0bf62005-12-30 16:28:01 +00005434 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00005435 if( rc ){
5436 releasePage(pRoot);
5437 return rc;
5438 }
danielk197742741be2005-01-08 12:42:39 +00005439
danielk1977003ba062004-11-04 02:57:33 +00005440 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00005441 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00005442 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00005443 }
5444#endif
drha34b6762004-05-07 13:30:42 +00005445 assert( sqlite3pager_iswriteable(pRoot->aData) );
drhde647132004-05-07 17:57:49 +00005446 zeroPage(pRoot, flags | PTF_LEAF);
drha34b6762004-05-07 13:30:42 +00005447 sqlite3pager_unref(pRoot->aData);
drh8b2f49b2001-06-08 00:21:52 +00005448 *piTable = (int)pgnoRoot;
5449 return SQLITE_OK;
5450}
5451
5452/*
5453** Erase the given database page and all its children. Return
5454** the page to the freelist.
5455*/
drh4b70f112004-05-02 21:12:19 +00005456static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00005457 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00005458 Pgno pgno, /* Page number to clear */
5459 MemPage *pParent, /* Parent page. NULL for the root */
5460 int freePageFlag /* Deallocate page if true */
5461){
danielk19776b456a22005-03-21 04:04:02 +00005462 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00005463 int rc;
drh4b70f112004-05-02 21:12:19 +00005464 unsigned char *pCell;
5465 int i;
drh8b2f49b2001-06-08 00:21:52 +00005466
danielk1977a1cb1832005-02-12 08:59:55 +00005467 if( pgno>sqlite3pager_pagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00005468 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00005469 }
5470
drhde647132004-05-07 17:57:49 +00005471 rc = getAndInitPage(pBt, pgno, &pPage, pParent);
danielk19776b456a22005-03-21 04:04:02 +00005472 if( rc ) goto cleardatabasepage_out;
drha34b6762004-05-07 13:30:42 +00005473 rc = sqlite3pager_write(pPage->aData);
danielk19776b456a22005-03-21 04:04:02 +00005474 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00005475 for(i=0; i<pPage->nCell; i++){
drh43605152004-05-29 21:46:49 +00005476 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00005477 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005478 rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00005479 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00005480 }
drh4b70f112004-05-02 21:12:19 +00005481 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00005482 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00005483 }
drha34b6762004-05-07 13:30:42 +00005484 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005485 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00005486 if( rc ) goto cleardatabasepage_out;
drh2aa679f2001-06-25 02:11:07 +00005487 }
5488 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00005489 rc = freePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00005490 }else{
drh3a4c1412004-05-09 20:40:11 +00005491 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00005492 }
danielk19776b456a22005-03-21 04:04:02 +00005493
5494cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00005495 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00005496 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005497}
5498
5499/*
drhab01f612004-05-22 02:55:23 +00005500** Delete all information from a single table in the database. iTable is
5501** the page number of the root of the table. After this routine returns,
5502** the root page is empty, but still exists.
5503**
5504** This routine will fail with SQLITE_LOCKED if there are any open
5505** read cursors on the table. Open write cursors are moved to the
5506** root of the table.
drh8b2f49b2001-06-08 00:21:52 +00005507*/
danielk1977aef0bf62005-12-30 16:28:01 +00005508int sqlite3BtreeClearTable(Btree *p, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00005509 int rc;
drhf74b8d92002-09-01 23:20:45 +00005510 BtCursor *pCur;
danielk1977aef0bf62005-12-30 16:28:01 +00005511 BtShared *pBt = p->pBt;
5512 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005513 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005514 }
drhf74b8d92002-09-01 23:20:45 +00005515 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
5516 if( pCur->pgnoRoot==(Pgno)iTable ){
5517 if( pCur->wrFlag==0 ) return SQLITE_LOCKED;
5518 moveToRoot(pCur);
5519 }
drhecdc7532001-09-23 02:35:53 +00005520 }
drha34b6762004-05-07 13:30:42 +00005521 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
danielk197771fd80b2005-12-16 06:54:01 +00005522#if 0
drh8b2f49b2001-06-08 00:21:52 +00005523 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00005524 sqlite3BtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00005525 }
danielk197771fd80b2005-12-16 06:54:01 +00005526#endif
drh8c42ca92001-06-22 19:15:00 +00005527 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005528}
5529
5530/*
5531** Erase all information in a table and add the root of the table to
5532** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00005533** page 1) is never added to the freelist.
5534**
5535** This routine will fail with SQLITE_LOCKED if there are any open
5536** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00005537**
5538** If AUTOVACUUM is enabled and the page at iTable is not the last
5539** root page in the database file, then the last root page
5540** in the database file is moved into the slot formerly occupied by
5541** iTable and that last slot formerly occupied by the last root page
5542** is added to the freelist instead of iTable. In this say, all
5543** root pages are kept at the beginning of the database file, which
5544** is necessary for AUTOVACUUM to work right. *piMoved is set to the
5545** page number that used to be the last root page in the file before
5546** the move. If no page gets moved, *piMoved is set to 0.
5547** The last root page is recorded in meta[3] and the value of
5548** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00005549*/
danielk1977aef0bf62005-12-30 16:28:01 +00005550int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00005551 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00005552 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00005553 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00005554
danielk1977aef0bf62005-12-30 16:28:01 +00005555 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005556 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005557 }
danielk1977a0bf2652004-11-04 14:30:04 +00005558
danielk1977e6efa742004-11-10 11:55:10 +00005559 /* It is illegal to drop a table if any cursors are open on the
5560 ** database. This is because in auto-vacuum mode the backend may
5561 ** need to move another root-page to fill a gap left by the deleted
5562 ** root page. If an open cursor was using this page a problem would
5563 ** occur.
5564 */
5565 if( pBt->pCursor ){
5566 return SQLITE_LOCKED;
drh5df72a52002-06-06 23:16:05 +00005567 }
danielk1977a0bf2652004-11-04 14:30:04 +00005568
drha34b6762004-05-07 13:30:42 +00005569 rc = getPage(pBt, (Pgno)iTable, &pPage);
drh2aa679f2001-06-25 02:11:07 +00005570 if( rc ) return rc;
danielk1977aef0bf62005-12-30 16:28:01 +00005571 rc = sqlite3BtreeClearTable(p, iTable);
danielk19776b456a22005-03-21 04:04:02 +00005572 if( rc ){
5573 releasePage(pPage);
5574 return rc;
5575 }
danielk1977a0bf2652004-11-04 14:30:04 +00005576
drh205f48e2004-11-05 00:43:11 +00005577 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00005578
drh4b70f112004-05-02 21:12:19 +00005579 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00005580#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00005581 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00005582 releasePage(pPage);
5583#else
5584 if( pBt->autoVacuum ){
5585 Pgno maxRootPgno;
danielk1977aef0bf62005-12-30 16:28:01 +00005586 rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00005587 if( rc!=SQLITE_OK ){
5588 releasePage(pPage);
5589 return rc;
5590 }
5591
5592 if( iTable==maxRootPgno ){
5593 /* If the table being dropped is the table with the largest root-page
5594 ** number in the database, put the root page on the free list.
5595 */
5596 rc = freePage(pPage);
5597 releasePage(pPage);
5598 if( rc!=SQLITE_OK ){
5599 return rc;
5600 }
5601 }else{
5602 /* The table being dropped does not have the largest root-page
5603 ** number in the database. So move the page that does into the
5604 ** gap left by the deleted root-page.
5605 */
5606 MemPage *pMove;
5607 releasePage(pPage);
5608 rc = getPage(pBt, maxRootPgno, &pMove);
5609 if( rc!=SQLITE_OK ){
5610 return rc;
5611 }
5612 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable);
5613 releasePage(pMove);
5614 if( rc!=SQLITE_OK ){
5615 return rc;
5616 }
5617 rc = getPage(pBt, maxRootPgno, &pMove);
5618 if( rc!=SQLITE_OK ){
5619 return rc;
5620 }
5621 rc = freePage(pMove);
5622 releasePage(pMove);
5623 if( rc!=SQLITE_OK ){
5624 return rc;
5625 }
5626 *piMoved = maxRootPgno;
5627 }
5628
danielk1977599fcba2004-11-08 07:13:13 +00005629 /* Set the new 'max-root-page' value in the database header. This
5630 ** is the old value less one, less one more if that happens to
5631 ** be a root-page number, less one again if that is the
5632 ** PENDING_BYTE_PAGE.
5633 */
danielk197787a6e732004-11-05 12:58:25 +00005634 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00005635 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
5636 maxRootPgno--;
5637 }
drh42cac6d2004-11-20 20:31:11 +00005638 if( maxRootPgno==PTRMAP_PAGENO(pBt->usableSize, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00005639 maxRootPgno--;
5640 }
danielk1977599fcba2004-11-08 07:13:13 +00005641 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
5642
danielk1977aef0bf62005-12-30 16:28:01 +00005643 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00005644 }else{
5645 rc = freePage(pPage);
5646 releasePage(pPage);
5647 }
5648#endif
drh2aa679f2001-06-25 02:11:07 +00005649 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00005650 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00005651 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00005652 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00005653 }
drh8b2f49b2001-06-08 00:21:52 +00005654 return rc;
5655}
5656
drh001bbcb2003-03-19 03:14:00 +00005657
drh8b2f49b2001-06-08 00:21:52 +00005658/*
drh23e11ca2004-05-04 17:27:28 +00005659** Read the meta-information out of a database file. Meta[0]
5660** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00005661** through meta[15] are available for use by higher layers. Meta[0]
5662** is read-only, the others are read/write.
5663**
5664** The schema layer numbers meta values differently. At the schema
5665** layer (and the SetCookie and ReadCookie opcodes) the number of
5666** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00005667*/
danielk1977aef0bf62005-12-30 16:28:01 +00005668int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
drh8b2f49b2001-06-08 00:21:52 +00005669 int rc;
drh4b70f112004-05-02 21:12:19 +00005670 unsigned char *pP1;
danielk1977aef0bf62005-12-30 16:28:01 +00005671 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005672
danielk1977da184232006-01-05 11:34:32 +00005673 /* Reading a meta-data value requires a read-lock on page 1 (and hence
5674 ** the sqlite_master table. We grab this lock regardless of whether or
5675 ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
5676 ** 1 is treated as a special case by queryTableLock() and lockTable()).
5677 */
5678 rc = queryTableLock(p, 1, READ_LOCK);
5679 if( rc!=SQLITE_OK ){
5680 return rc;
5681 }
5682
drh23e11ca2004-05-04 17:27:28 +00005683 assert( idx>=0 && idx<=15 );
drha34b6762004-05-07 13:30:42 +00005684 rc = sqlite3pager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00005685 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00005686 *pMeta = get4byte(&pP1[36 + idx*4]);
drha34b6762004-05-07 13:30:42 +00005687 sqlite3pager_unref(pP1);
drhae157872004-08-14 19:20:09 +00005688
danielk1977599fcba2004-11-08 07:13:13 +00005689 /* If autovacuumed is disabled in this build but we are trying to
5690 ** access an autovacuumed database, then make the database readonly.
5691 */
danielk1977003ba062004-11-04 02:57:33 +00005692#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00005693 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00005694#endif
drhae157872004-08-14 19:20:09 +00005695
danielk1977da184232006-01-05 11:34:32 +00005696 /* Grab the read-lock on page 1. */
5697 rc = lockTable(p, 1, READ_LOCK);
5698 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005699}
5700
5701/*
drh23e11ca2004-05-04 17:27:28 +00005702** Write meta-information back into the database. Meta[0] is
5703** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00005704*/
danielk1977aef0bf62005-12-30 16:28:01 +00005705int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
5706 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00005707 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00005708 int rc;
drh23e11ca2004-05-04 17:27:28 +00005709 assert( idx>=1 && idx<=15 );
danielk1977aef0bf62005-12-30 16:28:01 +00005710 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005711 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +00005712 }
drhde647132004-05-07 17:57:49 +00005713 assert( pBt->pPage1!=0 );
5714 pP1 = pBt->pPage1->aData;
drha34b6762004-05-07 13:30:42 +00005715 rc = sqlite3pager_write(pP1);
drh4b70f112004-05-02 21:12:19 +00005716 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00005717 put4byte(&pP1[36 + idx*4], iMeta);
drh8b2f49b2001-06-08 00:21:52 +00005718 return SQLITE_OK;
5719}
drh8c42ca92001-06-22 19:15:00 +00005720
drhf328bc82004-05-10 23:29:49 +00005721/*
5722** Return the flag byte at the beginning of the page that the cursor
5723** is currently pointing to.
5724*/
5725int sqlite3BtreeFlags(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00005726 /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
5727 ** restoreCursorPosition() here.
5728 */
drhf328bc82004-05-10 23:29:49 +00005729 MemPage *pPage = pCur->pPage;
5730 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
5731}
5732
danielk1977b5402fb2005-01-12 07:15:04 +00005733#ifdef SQLITE_DEBUG
drh8c42ca92001-06-22 19:15:00 +00005734/*
5735** Print a disassembly of the given page on standard output. This routine
5736** is used for debugging and testing only.
5737*/
danielk1977aef0bf62005-12-30 16:28:01 +00005738static int btreePageDump(BtShared *pBt, int pgno, int recursive, MemPage *pParent){
drh8c42ca92001-06-22 19:15:00 +00005739 int rc;
5740 MemPage *pPage;
drhc8629a12004-05-08 20:07:40 +00005741 int i, j, c;
drh8c42ca92001-06-22 19:15:00 +00005742 int nFree;
5743 u16 idx;
drhab9f7f12004-05-08 10:56:11 +00005744 int hdr;
drh43605152004-05-29 21:46:49 +00005745 int nCell;
drha2fce642004-06-05 00:01:44 +00005746 int isInit;
drhab9f7f12004-05-08 10:56:11 +00005747 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00005748 char range[20];
5749 unsigned char payload[20];
drhab9f7f12004-05-08 10:56:11 +00005750
drh4b70f112004-05-02 21:12:19 +00005751 rc = getPage(pBt, (Pgno)pgno, &pPage);
drha2fce642004-06-05 00:01:44 +00005752 isInit = pPage->isInit;
5753 if( pPage->isInit==0 ){
danielk1977c7dc7532004-11-17 10:22:03 +00005754 initPage(pPage, pParent);
drha2fce642004-06-05 00:01:44 +00005755 }
drh8c42ca92001-06-22 19:15:00 +00005756 if( rc ){
5757 return rc;
5758 }
drhab9f7f12004-05-08 10:56:11 +00005759 hdr = pPage->hdrOffset;
5760 data = pPage->aData;
drhc8629a12004-05-08 20:07:40 +00005761 c = data[hdr];
drh8b18dd42004-05-12 19:18:15 +00005762 pPage->intKey = (c & (PTF_INTKEY|PTF_LEAFDATA))!=0;
drhc8629a12004-05-08 20:07:40 +00005763 pPage->zeroData = (c & PTF_ZERODATA)!=0;
drh8b18dd42004-05-12 19:18:15 +00005764 pPage->leafData = (c & PTF_LEAFDATA)!=0;
drhc8629a12004-05-08 20:07:40 +00005765 pPage->leaf = (c & PTF_LEAF)!=0;
drh8b18dd42004-05-12 19:18:15 +00005766 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
drh43605152004-05-29 21:46:49 +00005767 nCell = get2byte(&data[hdr+3]);
drhfe63d1c2004-09-08 20:13:04 +00005768 sqlite3DebugPrintf("PAGE %d: flags=0x%02x frag=%d parent=%d\n", pgno,
drh43605152004-05-29 21:46:49 +00005769 data[hdr], data[hdr+7],
drhda200cc2004-05-09 11:51:38 +00005770 (pPage->isInit && pPage->pParent) ? pPage->pParent->pgno : 0);
drhab9f7f12004-05-08 10:56:11 +00005771 assert( hdr == (pgno==1 ? 100 : 0) );
drh43605152004-05-29 21:46:49 +00005772 idx = hdr + 12 - pPage->leaf*4;
5773 for(i=0; i<nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00005774 CellInfo info;
drh4b70f112004-05-02 21:12:19 +00005775 Pgno child;
drh43605152004-05-29 21:46:49 +00005776 unsigned char *pCell;
drh6f11bef2004-05-13 01:12:56 +00005777 int sz;
drh43605152004-05-29 21:46:49 +00005778 int addr;
drh6f11bef2004-05-13 01:12:56 +00005779
drh43605152004-05-29 21:46:49 +00005780 addr = get2byte(&data[idx + 2*i]);
5781 pCell = &data[addr];
5782 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005783 sz = info.nSize;
drh43605152004-05-29 21:46:49 +00005784 sprintf(range,"%d..%d", addr, addr+sz-1);
drh4b70f112004-05-02 21:12:19 +00005785 if( pPage->leaf ){
5786 child = 0;
5787 }else{
drh43605152004-05-29 21:46:49 +00005788 child = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005789 }
drh6f11bef2004-05-13 01:12:56 +00005790 sz = info.nData;
5791 if( !pPage->intKey ) sz += info.nKey;
drh8c42ca92001-06-22 19:15:00 +00005792 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
drh6f11bef2004-05-13 01:12:56 +00005793 memcpy(payload, &pCell[info.nHeader], sz);
drh8c42ca92001-06-22 19:15:00 +00005794 for(j=0; j<sz; j++){
5795 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
5796 }
5797 payload[sz] = 0;
drhfe63d1c2004-09-08 20:13:04 +00005798 sqlite3DebugPrintf(
drh6f11bef2004-05-13 01:12:56 +00005799 "cell %2d: i=%-10s chld=%-4d nk=%-4lld nd=%-4d payload=%s\n",
5800 i, range, child, info.nKey, info.nData, payload
drh8c42ca92001-06-22 19:15:00 +00005801 );
drh8c42ca92001-06-22 19:15:00 +00005802 }
drh4b70f112004-05-02 21:12:19 +00005803 if( !pPage->leaf ){
drhfe63d1c2004-09-08 20:13:04 +00005804 sqlite3DebugPrintf("right_child: %d\n", get4byte(&data[hdr+8]));
drh4b70f112004-05-02 21:12:19 +00005805 }
drh8c42ca92001-06-22 19:15:00 +00005806 nFree = 0;
5807 i = 0;
drhab9f7f12004-05-08 10:56:11 +00005808 idx = get2byte(&data[hdr+1]);
drhb6f41482004-05-14 01:58:11 +00005809 while( idx>0 && idx<pPage->pBt->usableSize ){
drhab9f7f12004-05-08 10:56:11 +00005810 int sz = get2byte(&data[idx+2]);
drh4b70f112004-05-02 21:12:19 +00005811 sprintf(range,"%d..%d", idx, idx+sz-1);
5812 nFree += sz;
drhfe63d1c2004-09-08 20:13:04 +00005813 sqlite3DebugPrintf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
drh4b70f112004-05-02 21:12:19 +00005814 i, range, sz, nFree);
drhab9f7f12004-05-08 10:56:11 +00005815 idx = get2byte(&data[idx]);
drh2aa679f2001-06-25 02:11:07 +00005816 i++;
drh8c42ca92001-06-22 19:15:00 +00005817 }
5818 if( idx!=0 ){
drhfe63d1c2004-09-08 20:13:04 +00005819 sqlite3DebugPrintf("ERROR: next freeblock index out of range: %d\n", idx);
drh8c42ca92001-06-22 19:15:00 +00005820 }
drha34b6762004-05-07 13:30:42 +00005821 if( recursive && !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005822 for(i=0; i<nCell; i++){
5823 unsigned char *pCell = findCell(pPage, i);
danielk1977c7dc7532004-11-17 10:22:03 +00005824 btreePageDump(pBt, get4byte(pCell), 1, pPage);
drha34b6762004-05-07 13:30:42 +00005825 idx = get2byte(pCell);
drh6019e162001-07-02 17:51:45 +00005826 }
danielk1977c7dc7532004-11-17 10:22:03 +00005827 btreePageDump(pBt, get4byte(&data[hdr+8]), 1, pPage);
drh6019e162001-07-02 17:51:45 +00005828 }
drha2fce642004-06-05 00:01:44 +00005829 pPage->isInit = isInit;
drhab9f7f12004-05-08 10:56:11 +00005830 sqlite3pager_unref(data);
drh3644f082004-05-10 18:45:09 +00005831 fflush(stdout);
drh8c42ca92001-06-22 19:15:00 +00005832 return SQLITE_OK;
5833}
danielk1977aef0bf62005-12-30 16:28:01 +00005834int sqlite3BtreePageDump(Btree *p, int pgno, int recursive){
5835 return btreePageDump(p->pBt, pgno, recursive, 0);
danielk1977c7dc7532004-11-17 10:22:03 +00005836}
drhaaab5722002-02-19 13:39:21 +00005837#endif
drh8c42ca92001-06-22 19:15:00 +00005838
drhaaab5722002-02-19 13:39:21 +00005839#ifdef SQLITE_TEST
drh8c42ca92001-06-22 19:15:00 +00005840/*
drh2aa679f2001-06-25 02:11:07 +00005841** Fill aResult[] with information about the entry and page that the
5842** cursor is pointing to.
5843**
5844** aResult[0] = The page number
5845** aResult[1] = The entry number
5846** aResult[2] = Total number of entries on this page
drh3e27c022004-07-23 00:01:38 +00005847** aResult[3] = Cell size (local payload + header)
drh2aa679f2001-06-25 02:11:07 +00005848** aResult[4] = Number of free bytes on this page
5849** aResult[5] = Number of free blocks on the page
drh3e27c022004-07-23 00:01:38 +00005850** aResult[6] = Total payload size (local + overflow)
5851** aResult[7] = Header size in bytes
5852** aResult[8] = Local payload size
5853** aResult[9] = Parent page number
drh5eddca62001-06-30 21:53:53 +00005854**
5855** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00005856*/
drh3e27c022004-07-23 00:01:38 +00005857int sqlite3BtreeCursorInfo(BtCursor *pCur, int *aResult, int upCnt){
drh2aa679f2001-06-25 02:11:07 +00005858 int cnt, idx;
5859 MemPage *pPage = pCur->pPage;
drh3e27c022004-07-23 00:01:38 +00005860 BtCursor tmpCur;
drhda200cc2004-05-09 11:51:38 +00005861
danielk1977da184232006-01-05 11:34:32 +00005862 int rc = restoreCursorPosition(pCur, 1);
5863 if( rc!=SQLITE_OK ){
5864 return rc;
5865 }
5866
drhda200cc2004-05-09 11:51:38 +00005867 pageIntegrity(pPage);
drh4b70f112004-05-02 21:12:19 +00005868 assert( pPage->isInit );
drh3e27c022004-07-23 00:01:38 +00005869 getTempCursor(pCur, &tmpCur);
5870 while( upCnt-- ){
5871 moveToParent(&tmpCur);
5872 }
5873 pPage = tmpCur.pPage;
5874 pageIntegrity(pPage);
drha34b6762004-05-07 13:30:42 +00005875 aResult[0] = sqlite3pager_pagenumber(pPage->aData);
drh91025292004-05-03 19:49:32 +00005876 assert( aResult[0]==pPage->pgno );
drh3e27c022004-07-23 00:01:38 +00005877 aResult[1] = tmpCur.idx;
drh2aa679f2001-06-25 02:11:07 +00005878 aResult[2] = pPage->nCell;
drh3e27c022004-07-23 00:01:38 +00005879 if( tmpCur.idx>=0 && tmpCur.idx<pPage->nCell ){
5880 getCellInfo(&tmpCur);
5881 aResult[3] = tmpCur.info.nSize;
5882 aResult[6] = tmpCur.info.nData;
5883 aResult[7] = tmpCur.info.nHeader;
5884 aResult[8] = tmpCur.info.nLocal;
drh2aa679f2001-06-25 02:11:07 +00005885 }else{
5886 aResult[3] = 0;
5887 aResult[6] = 0;
drh3e27c022004-07-23 00:01:38 +00005888 aResult[7] = 0;
5889 aResult[8] = 0;
drh2aa679f2001-06-25 02:11:07 +00005890 }
5891 aResult[4] = pPage->nFree;
5892 cnt = 0;
drh4b70f112004-05-02 21:12:19 +00005893 idx = get2byte(&pPage->aData[pPage->hdrOffset+1]);
drhb6f41482004-05-14 01:58:11 +00005894 while( idx>0 && idx<pPage->pBt->usableSize ){
drh2aa679f2001-06-25 02:11:07 +00005895 cnt++;
drh4b70f112004-05-02 21:12:19 +00005896 idx = get2byte(&pPage->aData[idx]);
drh2aa679f2001-06-25 02:11:07 +00005897 }
5898 aResult[5] = cnt;
drh3e27c022004-07-23 00:01:38 +00005899 if( pPage->pParent==0 || isRootPage(pPage) ){
5900 aResult[9] = 0;
5901 }else{
5902 aResult[9] = pPage->pParent->pgno;
5903 }
5904 releaseTempCursor(&tmpCur);
drh8c42ca92001-06-22 19:15:00 +00005905 return SQLITE_OK;
5906}
drhaaab5722002-02-19 13:39:21 +00005907#endif
drhdd793422001-06-28 01:54:48 +00005908
drhdd793422001-06-28 01:54:48 +00005909/*
drh5eddca62001-06-30 21:53:53 +00005910** Return the pager associated with a BTree. This routine is used for
5911** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00005912*/
danielk1977aef0bf62005-12-30 16:28:01 +00005913Pager *sqlite3BtreePager(Btree *p){
5914 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00005915}
drh5eddca62001-06-30 21:53:53 +00005916
5917/*
5918** This structure is passed around through all the sanity checking routines
5919** in order to keep track of some global state information.
5920*/
drhaaab5722002-02-19 13:39:21 +00005921typedef struct IntegrityCk IntegrityCk;
5922struct IntegrityCk {
danielk1977aef0bf62005-12-30 16:28:01 +00005923 BtShared *pBt; /* The tree being checked out */
drh100569d2001-10-02 13:01:48 +00005924 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
5925 int nPage; /* Number of pages in the database */
5926 int *anRef; /* Number of times each page is referenced */
drh100569d2001-10-02 13:01:48 +00005927 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00005928};
5929
drhb7f91642004-10-31 02:22:47 +00005930#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005931/*
5932** Append a message to the error message string.
5933*/
drh2e38c322004-09-03 18:38:44 +00005934static void checkAppendMsg(
5935 IntegrityCk *pCheck,
5936 char *zMsg1,
5937 const char *zFormat,
5938 ...
5939){
5940 va_list ap;
5941 char *zMsg2;
5942 va_start(ap, zFormat);
5943 zMsg2 = sqlite3VMPrintf(zFormat, ap);
5944 va_end(ap);
5945 if( zMsg1==0 ) zMsg1 = "";
drh5eddca62001-06-30 21:53:53 +00005946 if( pCheck->zErrMsg ){
5947 char *zOld = pCheck->zErrMsg;
5948 pCheck->zErrMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00005949 sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00005950 sqliteFree(zOld);
5951 }else{
danielk19774adee202004-05-08 08:23:19 +00005952 sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00005953 }
drh2e38c322004-09-03 18:38:44 +00005954 sqliteFree(zMsg2);
drh5eddca62001-06-30 21:53:53 +00005955}
drhb7f91642004-10-31 02:22:47 +00005956#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005957
drhb7f91642004-10-31 02:22:47 +00005958#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005959/*
5960** Add 1 to the reference count for page iPage. If this is the second
5961** reference to the page, add an error message to pCheck->zErrMsg.
5962** Return 1 if there are 2 ore more references to the page and 0 if
5963** if this is the first reference to the page.
5964**
5965** Also check that the page number is in bounds.
5966*/
drhaaab5722002-02-19 13:39:21 +00005967static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00005968 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00005969 if( iPage>pCheck->nPage || iPage<0 ){
drh2e38c322004-09-03 18:38:44 +00005970 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005971 return 1;
5972 }
5973 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00005974 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005975 return 1;
5976 }
5977 return (pCheck->anRef[iPage]++)>1;
5978}
5979
danielk1977afcdd022004-10-31 16:25:42 +00005980#ifndef SQLITE_OMIT_AUTOVACUUM
5981/*
5982** Check that the entry in the pointer-map for page iChild maps to
5983** page iParent, pointer type ptrType. If not, append an error message
5984** to pCheck.
5985*/
5986static void checkPtrmap(
5987 IntegrityCk *pCheck, /* Integrity check context */
5988 Pgno iChild, /* Child page number */
5989 u8 eType, /* Expected pointer map type */
5990 Pgno iParent, /* Expected pointer map parent page number */
5991 char *zContext /* Context description (used for error msg) */
5992){
5993 int rc;
5994 u8 ePtrmapType;
5995 Pgno iPtrmapParent;
5996
5997 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
5998 if( rc!=SQLITE_OK ){
5999 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
6000 return;
6001 }
6002
6003 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
6004 checkAppendMsg(pCheck, zContext,
6005 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
6006 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
6007 }
6008}
6009#endif
6010
drh5eddca62001-06-30 21:53:53 +00006011/*
6012** Check the integrity of the freelist or of an overflow page list.
6013** Verify that the number of pages on the list is N.
6014*/
drh30e58752002-03-02 20:41:57 +00006015static void checkList(
6016 IntegrityCk *pCheck, /* Integrity checking context */
6017 int isFreeList, /* True for a freelist. False for overflow page list */
6018 int iPage, /* Page number for first page in the list */
6019 int N, /* Expected number of pages in the list */
6020 char *zContext /* Context for error messages */
6021){
6022 int i;
drh3a4c1412004-05-09 20:40:11 +00006023 int expected = N;
6024 int iFirst = iPage;
drh30e58752002-03-02 20:41:57 +00006025 while( N-- > 0 ){
drh4b70f112004-05-02 21:12:19 +00006026 unsigned char *pOvfl;
drh5eddca62001-06-30 21:53:53 +00006027 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00006028 checkAppendMsg(pCheck, zContext,
6029 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00006030 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00006031 break;
6032 }
6033 if( checkRef(pCheck, iPage, zContext) ) break;
drha34b6762004-05-07 13:30:42 +00006034 if( sqlite3pager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
drh2e38c322004-09-03 18:38:44 +00006035 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006036 break;
6037 }
drh30e58752002-03-02 20:41:57 +00006038 if( isFreeList ){
drh4b70f112004-05-02 21:12:19 +00006039 int n = get4byte(&pOvfl[4]);
danielk1977687566d2004-11-02 12:56:41 +00006040#ifndef SQLITE_OMIT_AUTOVACUUM
6041 if( pCheck->pBt->autoVacuum ){
6042 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
6043 }
6044#endif
drh855eb1c2004-08-31 13:45:11 +00006045 if( n>pCheck->pBt->usableSize/4-8 ){
drh2e38c322004-09-03 18:38:44 +00006046 checkAppendMsg(pCheck, zContext,
6047 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00006048 N--;
6049 }else{
6050 for(i=0; i<n; i++){
danielk1977687566d2004-11-02 12:56:41 +00006051 Pgno iFreePage = get4byte(&pOvfl[8+i*4]);
6052#ifndef SQLITE_OMIT_AUTOVACUUM
6053 if( pCheck->pBt->autoVacuum ){
6054 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
6055 }
6056#endif
6057 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00006058 }
6059 N -= n;
drh30e58752002-03-02 20:41:57 +00006060 }
drh30e58752002-03-02 20:41:57 +00006061 }
danielk1977afcdd022004-10-31 16:25:42 +00006062#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006063 else{
6064 /* If this database supports auto-vacuum and iPage is not the last
6065 ** page in this overflow list, check that the pointer-map entry for
6066 ** the following page matches iPage.
6067 */
6068 if( pCheck->pBt->autoVacuum && N>0 ){
6069 i = get4byte(pOvfl);
6070 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
6071 }
danielk1977afcdd022004-10-31 16:25:42 +00006072 }
6073#endif
drh4b70f112004-05-02 21:12:19 +00006074 iPage = get4byte(pOvfl);
drha34b6762004-05-07 13:30:42 +00006075 sqlite3pager_unref(pOvfl);
drh5eddca62001-06-30 21:53:53 +00006076 }
6077}
drhb7f91642004-10-31 02:22:47 +00006078#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006079
drhb7f91642004-10-31 02:22:47 +00006080#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006081/*
6082** Do various sanity checks on a single page of a tree. Return
6083** the tree depth. Root pages return 0. Parents of root pages
6084** return 1, and so forth.
6085**
6086** These checks are done:
6087**
6088** 1. Make sure that cells and freeblocks do not overlap
6089** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00006090** NO 2. Make sure cell keys are in order.
6091** NO 3. Make sure no key is less than or equal to zLowerBound.
6092** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00006093** 5. Check the integrity of overflow pages.
6094** 6. Recursively call checkTreePage on all children.
6095** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00006096** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00006097** the root of the tree.
6098*/
6099static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00006100 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00006101 int iPage, /* Page number of the page to check */
6102 MemPage *pParent, /* Parent page */
6103 char *zParentContext, /* Parent context */
6104 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00006105 int nLower, /* Number of characters in zLowerBound */
6106 char *zUpperBound, /* All keys should be less than this, if not NULL */
6107 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00006108){
6109 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00006110 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00006111 int hdr, cellStart;
6112 int nCell;
drhda200cc2004-05-09 11:51:38 +00006113 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00006114 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00006115 int usableSize;
drh5eddca62001-06-30 21:53:53 +00006116 char zContext[100];
drh2e38c322004-09-03 18:38:44 +00006117 char *hit;
drh5eddca62001-06-30 21:53:53 +00006118
danielk1977ef73ee92004-11-06 12:26:07 +00006119 sprintf(zContext, "Page %d: ", iPage);
6120
drh5eddca62001-06-30 21:53:53 +00006121 /* Check that the page exists
6122 */
drhd9cb6ac2005-10-20 07:28:17 +00006123 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00006124 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00006125 if( iPage==0 ) return 0;
6126 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh4b70f112004-05-02 21:12:19 +00006127 if( (rc = getPage(pBt, (Pgno)iPage, &pPage))!=0 ){
drh2e38c322004-09-03 18:38:44 +00006128 checkAppendMsg(pCheck, zContext,
6129 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00006130 return 0;
6131 }
drh4b70f112004-05-02 21:12:19 +00006132 if( (rc = initPage(pPage, pParent))!=0 ){
drh2e38c322004-09-03 18:38:44 +00006133 checkAppendMsg(pCheck, zContext, "initPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00006134 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00006135 return 0;
6136 }
6137
6138 /* Check out all the cells.
6139 */
6140 depth = 0;
drh5eddca62001-06-30 21:53:53 +00006141 for(i=0; i<pPage->nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00006142 u8 *pCell;
6143 int sz;
6144 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00006145
6146 /* Check payload overflow pages
6147 */
drh3a4c1412004-05-09 20:40:11 +00006148 sprintf(zContext, "On tree page %d cell %d: ", iPage, i);
drh43605152004-05-29 21:46:49 +00006149 pCell = findCell(pPage,i);
6150 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00006151 sz = info.nData;
6152 if( !pPage->intKey ) sz += info.nKey;
6153 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00006154 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00006155 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
6156#ifndef SQLITE_OMIT_AUTOVACUUM
6157 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006158 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00006159 }
6160#endif
6161 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00006162 }
6163
6164 /* Check sanity of left child page.
6165 */
drhda200cc2004-05-09 11:51:38 +00006166 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006167 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00006168#ifndef SQLITE_OMIT_AUTOVACUUM
6169 if( pBt->autoVacuum ){
6170 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
6171 }
6172#endif
drhda200cc2004-05-09 11:51:38 +00006173 d2 = checkTreePage(pCheck,pgno,pPage,zContext,0,0,0,0);
6174 if( i>0 && d2!=depth ){
6175 checkAppendMsg(pCheck, zContext, "Child page depth differs");
6176 }
6177 depth = d2;
drh5eddca62001-06-30 21:53:53 +00006178 }
drh5eddca62001-06-30 21:53:53 +00006179 }
drhda200cc2004-05-09 11:51:38 +00006180 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006181 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drhda200cc2004-05-09 11:51:38 +00006182 sprintf(zContext, "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00006183#ifndef SQLITE_OMIT_AUTOVACUUM
6184 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006185 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00006186 }
6187#endif
drhda200cc2004-05-09 11:51:38 +00006188 checkTreePage(pCheck, pgno, pPage, zContext,0,0,0,0);
6189 }
drh5eddca62001-06-30 21:53:53 +00006190
6191 /* Check for complete coverage of the page
6192 */
drhda200cc2004-05-09 11:51:38 +00006193 data = pPage->aData;
6194 hdr = pPage->hdrOffset;
drh2e38c322004-09-03 18:38:44 +00006195 hit = sqliteMalloc( usableSize );
6196 if( hit ){
6197 memset(hit, 1, get2byte(&data[hdr+5]));
6198 nCell = get2byte(&data[hdr+3]);
6199 cellStart = hdr + 12 - 4*pPage->leaf;
6200 for(i=0; i<nCell; i++){
6201 int pc = get2byte(&data[cellStart+i*2]);
6202 int size = cellSizePtr(pPage, &data[pc]);
6203 int j;
danielk19777701e812005-01-10 12:59:51 +00006204 if( (pc+size-1)>=usableSize || pc<0 ){
6205 checkAppendMsg(pCheck, 0,
6206 "Corruption detected in cell %d on page %d",i,iPage,0);
6207 }else{
6208 for(j=pc+size-1; j>=pc; j--) hit[j]++;
6209 }
drh2e38c322004-09-03 18:38:44 +00006210 }
6211 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
6212 cnt++){
6213 int size = get2byte(&data[i+2]);
6214 int j;
danielk19777701e812005-01-10 12:59:51 +00006215 if( (i+size-1)>=usableSize || i<0 ){
6216 checkAppendMsg(pCheck, 0,
6217 "Corruption detected in cell %d on page %d",i,iPage,0);
6218 }else{
6219 for(j=i+size-1; j>=i; j--) hit[j]++;
6220 }
drh2e38c322004-09-03 18:38:44 +00006221 i = get2byte(&data[i]);
6222 }
6223 for(i=cnt=0; i<usableSize; i++){
6224 if( hit[i]==0 ){
6225 cnt++;
6226 }else if( hit[i]>1 ){
6227 checkAppendMsg(pCheck, 0,
6228 "Multiple uses for byte %d of page %d", i, iPage);
6229 break;
6230 }
6231 }
6232 if( cnt!=data[hdr+7] ){
6233 checkAppendMsg(pCheck, 0,
6234 "Fragmented space is %d byte reported as %d on page %d",
6235 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00006236 }
6237 }
drh2e38c322004-09-03 18:38:44 +00006238 sqliteFree(hit);
drh6019e162001-07-02 17:51:45 +00006239
drh4b70f112004-05-02 21:12:19 +00006240 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00006241 return depth+1;
drh5eddca62001-06-30 21:53:53 +00006242}
drhb7f91642004-10-31 02:22:47 +00006243#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006244
drhb7f91642004-10-31 02:22:47 +00006245#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006246/*
6247** This routine does a complete check of the given BTree file. aRoot[] is
6248** an array of pages numbers were each page number is the root page of
6249** a table. nRoot is the number of entries in aRoot.
6250**
6251** If everything checks out, this routine returns NULL. If something is
6252** amiss, an error message is written into memory obtained from malloc()
6253** and a pointer to that error message is returned. The calling function
6254** is responsible for freeing the error message when it is done.
6255*/
danielk1977aef0bf62005-12-30 16:28:01 +00006256char *sqlite3BtreeIntegrityCheck(Btree *p, int *aRoot, int nRoot){
drh5eddca62001-06-30 21:53:53 +00006257 int i;
6258 int nRef;
drhaaab5722002-02-19 13:39:21 +00006259 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00006260 BtShared *pBt = p->pBt;
drh5eddca62001-06-30 21:53:53 +00006261
drha34b6762004-05-07 13:30:42 +00006262 nRef = *sqlite3pager_stats(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00006263 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
drhefc251d2001-07-01 22:12:01 +00006264 return sqliteStrDup("Unable to acquire a read lock on the database");
6265 }
drh5eddca62001-06-30 21:53:53 +00006266 sCheck.pBt = pBt;
6267 sCheck.pPager = pBt->pPager;
drha34b6762004-05-07 13:30:42 +00006268 sCheck.nPage = sqlite3pager_pagecount(sCheck.pPager);
drh0de8c112002-07-06 16:32:14 +00006269 if( sCheck.nPage==0 ){
6270 unlockBtreeIfUnused(pBt);
6271 return 0;
6272 }
drh8c1238a2003-01-02 14:43:55 +00006273 sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00006274 if( !sCheck.anRef ){
6275 unlockBtreeIfUnused(pBt);
6276 return sqlite3MPrintf("Unable to malloc %d bytes",
6277 (sCheck.nPage+1)*sizeof(sCheck.anRef[0]));
6278 }
drhda200cc2004-05-09 11:51:38 +00006279 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00006280 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00006281 if( i<=sCheck.nPage ){
6282 sCheck.anRef[i] = 1;
6283 }
drh5eddca62001-06-30 21:53:53 +00006284 sCheck.zErrMsg = 0;
6285
6286 /* Check the integrity of the freelist
6287 */
drha34b6762004-05-07 13:30:42 +00006288 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
6289 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00006290
6291 /* Check all the tables.
6292 */
6293 for(i=0; i<nRoot; i++){
drh4ff6dfa2002-03-03 23:06:00 +00006294 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00006295#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006296 if( pBt->autoVacuum && aRoot[i]>1 ){
6297 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
6298 }
6299#endif
drh1bffb9c2002-02-03 17:37:36 +00006300 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00006301 }
6302
6303 /* Make sure every page in the file is referenced
6304 */
6305 for(i=1; i<=sCheck.nPage; i++){
danielk1977afcdd022004-10-31 16:25:42 +00006306#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00006307 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00006308 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00006309 }
danielk1977afcdd022004-10-31 16:25:42 +00006310#else
6311 /* If the database supports auto-vacuum, make sure no tables contain
6312 ** references to pointer-map pages.
6313 */
6314 if( sCheck.anRef[i]==0 &&
drh42cac6d2004-11-20 20:31:11 +00006315 (PTRMAP_PAGENO(pBt->usableSize, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006316 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
6317 }
6318 if( sCheck.anRef[i]!=0 &&
drh42cac6d2004-11-20 20:31:11 +00006319 (PTRMAP_PAGENO(pBt->usableSize, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006320 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
6321 }
6322#endif
drh5eddca62001-06-30 21:53:53 +00006323 }
6324
6325 /* Make sure this analysis did not leave any unref() pages
6326 */
drh5e00f6c2001-09-13 13:46:56 +00006327 unlockBtreeIfUnused(pBt);
drha34b6762004-05-07 13:30:42 +00006328 if( nRef != *sqlite3pager_stats(pBt->pPager) ){
drh2e38c322004-09-03 18:38:44 +00006329 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00006330 "Outstanding page count goes from %d to %d during this analysis",
drha34b6762004-05-07 13:30:42 +00006331 nRef, *sqlite3pager_stats(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00006332 );
drh5eddca62001-06-30 21:53:53 +00006333 }
6334
6335 /* Clean up and report errors.
6336 */
6337 sqliteFree(sCheck.anRef);
6338 return sCheck.zErrMsg;
6339}
drhb7f91642004-10-31 02:22:47 +00006340#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00006341
drh73509ee2003-04-06 20:44:45 +00006342/*
6343** Return the full pathname of the underlying database file.
6344*/
danielk1977aef0bf62005-12-30 16:28:01 +00006345const char *sqlite3BtreeGetFilename(Btree *p){
6346 assert( p->pBt->pPager!=0 );
6347 return sqlite3pager_filename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00006348}
6349
6350/*
danielk19775865e3d2004-06-14 06:03:57 +00006351** Return the pathname of the directory that contains the database file.
6352*/
danielk1977aef0bf62005-12-30 16:28:01 +00006353const char *sqlite3BtreeGetDirname(Btree *p){
6354 assert( p->pBt->pPager!=0 );
6355 return sqlite3pager_dirname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006356}
6357
6358/*
6359** Return the pathname of the journal file for this database. The return
6360** value of this routine is the same regardless of whether the journal file
6361** has been created or not.
6362*/
danielk1977aef0bf62005-12-30 16:28:01 +00006363const char *sqlite3BtreeGetJournalname(Btree *p){
6364 assert( p->pBt->pPager!=0 );
6365 return sqlite3pager_journalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006366}
6367
drhb7f91642004-10-31 02:22:47 +00006368#ifndef SQLITE_OMIT_VACUUM
danielk19775865e3d2004-06-14 06:03:57 +00006369/*
drhf7c57532003-04-25 13:22:51 +00006370** Copy the complete content of pBtFrom into pBtTo. A transaction
6371** must be active for both files.
6372**
6373** The size of file pBtFrom may be reduced by this operation.
drh43605152004-05-29 21:46:49 +00006374** If anything goes wrong, the transaction on pBtFrom is rolled back.
drh73509ee2003-04-06 20:44:45 +00006375*/
danielk1977aef0bf62005-12-30 16:28:01 +00006376int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
drhf7c57532003-04-25 13:22:51 +00006377 int rc = SQLITE_OK;
drh50f2f432005-09-16 11:32:18 +00006378 Pgno i, nPage, nToPage, iSkip;
drhf7c57532003-04-25 13:22:51 +00006379
danielk1977aef0bf62005-12-30 16:28:01 +00006380 BtShared *pBtTo = pTo->pBt;
6381 BtShared *pBtFrom = pFrom->pBt;
6382
6383 if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
danielk1977ee5741e2004-05-31 10:01:34 +00006384 return SQLITE_ERROR;
6385 }
drhf7c57532003-04-25 13:22:51 +00006386 if( pBtTo->pCursor ) return SQLITE_BUSY;
drha34b6762004-05-07 13:30:42 +00006387 nToPage = sqlite3pager_pagecount(pBtTo->pPager);
6388 nPage = sqlite3pager_pagecount(pBtFrom->pPager);
drh50f2f432005-09-16 11:32:18 +00006389 iSkip = PENDING_BYTE_PAGE(pBtTo);
danielk1977369f27e2004-06-15 11:40:04 +00006390 for(i=1; rc==SQLITE_OK && i<=nPage; i++){
drhf7c57532003-04-25 13:22:51 +00006391 void *pPage;
drh50f2f432005-09-16 11:32:18 +00006392 if( i==iSkip ) continue;
drha34b6762004-05-07 13:30:42 +00006393 rc = sqlite3pager_get(pBtFrom->pPager, i, &pPage);
drhf7c57532003-04-25 13:22:51 +00006394 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00006395 rc = sqlite3pager_overwrite(pBtTo->pPager, i, pPage);
drh2e6d11b2003-04-25 15:37:57 +00006396 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00006397 sqlite3pager_unref(pPage);
drhf7c57532003-04-25 13:22:51 +00006398 }
drh2e6d11b2003-04-25 15:37:57 +00006399 for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
6400 void *pPage;
drh49285702005-09-17 15:20:26 +00006401 if( i==iSkip ) continue;
drha34b6762004-05-07 13:30:42 +00006402 rc = sqlite3pager_get(pBtTo->pPager, i, &pPage);
drh2e6d11b2003-04-25 15:37:57 +00006403 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00006404 rc = sqlite3pager_write(pPage);
6405 sqlite3pager_unref(pPage);
6406 sqlite3pager_dont_write(pBtTo->pPager, i);
drh2e6d11b2003-04-25 15:37:57 +00006407 }
6408 if( !rc && nPage<nToPage ){
drha34b6762004-05-07 13:30:42 +00006409 rc = sqlite3pager_truncate(pBtTo->pPager, nPage);
drh2e6d11b2003-04-25 15:37:57 +00006410 }
drhf7c57532003-04-25 13:22:51 +00006411 if( rc ){
danielk1977aef0bf62005-12-30 16:28:01 +00006412 sqlite3BtreeRollback(pTo);
drhf7c57532003-04-25 13:22:51 +00006413 }
6414 return rc;
drh73509ee2003-04-06 20:44:45 +00006415}
drhb7f91642004-10-31 02:22:47 +00006416#endif /* SQLITE_OMIT_VACUUM */
danielk19771d850a72004-05-31 08:26:49 +00006417
6418/*
6419** Return non-zero if a transaction is active.
6420*/
danielk1977aef0bf62005-12-30 16:28:01 +00006421int sqlite3BtreeIsInTrans(Btree *p){
6422 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00006423}
6424
6425/*
6426** Return non-zero if a statement transaction is active.
6427*/
danielk1977aef0bf62005-12-30 16:28:01 +00006428int sqlite3BtreeIsInStmt(Btree *p){
6429 return (p->pBt && p->pBt->inStmt);
danielk19771d850a72004-05-31 08:26:49 +00006430}
danielk197713adf8a2004-06-03 16:08:41 +00006431
6432/*
6433** This call is a no-op if no write-transaction is currently active on pBt.
6434**
6435** Otherwise, sync the database file for the btree pBt. zMaster points to
6436** the name of a master journal file that should be written into the
6437** individual journal file, or is NULL, indicating no master journal file
6438** (single database transaction).
6439**
6440** When this is called, the master journal should already have been
6441** created, populated with this journal pointer and synced to disk.
6442**
6443** Once this is routine has returned, the only thing required to commit
6444** the write-transaction for this database file is to delete the journal.
6445*/
danielk1977aef0bf62005-12-30 16:28:01 +00006446int sqlite3BtreeSync(Btree *p, const char *zMaster){
6447 if( p->inTrans==TRANS_WRITE ){
6448 BtShared *pBt = p->pBt;
danielk1977687566d2004-11-02 12:56:41 +00006449#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977d761c0c2004-11-05 16:37:02 +00006450 Pgno nTrunc = 0;
danielk1977687566d2004-11-02 12:56:41 +00006451 if( pBt->autoVacuum ){
danielk1977d761c0c2004-11-05 16:37:02 +00006452 int rc = autoVacuumCommit(pBt, &nTrunc);
danielk1977687566d2004-11-02 12:56:41 +00006453 if( rc!=SQLITE_OK ) return rc;
6454 }
danielk1977d761c0c2004-11-05 16:37:02 +00006455 return sqlite3pager_sync(pBt->pPager, zMaster, nTrunc);
danielk1977687566d2004-11-02 12:56:41 +00006456#endif
danielk1977d761c0c2004-11-05 16:37:02 +00006457 return sqlite3pager_sync(pBt->pPager, zMaster, 0);
danielk197713adf8a2004-06-03 16:08:41 +00006458 }
6459 return SQLITE_OK;
6460}
danielk1977aef0bf62005-12-30 16:28:01 +00006461
danielk1977da184232006-01-05 11:34:32 +00006462/*
6463** This function returns a pointer to a blob of memory associated with
6464** a single shared-btree. The memory is used by client code for it's own
6465** purposes (for example, to store a high-level schema associated with
6466** the shared-btree). The btree layer manages reference counting issues.
6467**
6468** The first time this is called on a shared-btree, nBytes bytes of memory
6469** are allocated, zeroed, and returned to the caller. For each subsequent
6470** call the nBytes parameter is ignored and a pointer to the same blob
6471** of memory returned.
6472**
6473** Just before the shared-btree is closed, the function passed as the
6474** xFree argument when the memory allocation was made is invoked on the
6475** blob of allocated memory. This function should not call sqliteFree()
6476** on the memory, the btree layer does that.
6477*/
6478void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
6479 BtShared *pBt = p->pBt;
6480 if( !pBt->pSchema ){
6481 pBt->pSchema = sqliteMalloc(nBytes);
6482 pBt->xFreeSchema = xFree;
6483 }
6484 return pBt->pSchema;
6485}
6486
danielk1977c87d34d2006-01-06 13:00:28 +00006487/*
6488** Return true if another user of the same shared btree as the argument
6489** handle holds an exclusive lock on the sqlite_master table.
6490*/
6491int sqlite3BtreeSchemaLocked(Btree *p){
6492 return (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
6493}
6494
danielk1977aef0bf62005-12-30 16:28:01 +00006495#ifndef SQLITE_OMIT_SHARED_CACHE
6496/*
6497** Enable the shared pager and schema features.
6498*/
6499int sqlite3_enable_shared_cache(int enable){
6500 SqliteTsd *pTsd = sqlite3Tsd();
6501 if( pTsd->pPager ){
6502 return SQLITE_MISUSE;
6503 }
6504 pTsd->useSharedData = enable;
6505 return SQLITE_OK;
6506}
6507#endif