blob: 9f0a2e7f55223bbd6a2e75e19feda882df545ffd [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*************************************************************************
danielk1977c00da102006-01-07 13:21:04 +000012** $Id: btree.c,v 1.285 2006/01/07 13:21:04 danielk1977 Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
15** For a detailed discussion of BTrees, refer to
16**
17** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
18** "Sorting And Searching", pages 473-480. Addison-Wesley
19** Publishing Company, Reading, Massachusetts.
20**
21** The basic idea is that each page of the file contains N database
22** entries and N+1 pointers to subpages.
23**
24** ----------------------------------------------------------------
25** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N) | Ptr(N+1) |
26** ----------------------------------------------------------------
27**
28** All of the keys on the page that Ptr(0) points to have values less
29** than Key(0). All of the keys on page Ptr(1) and its subpages have
30** values greater than Key(0) and less than Key(1). All of the keys
31** on Ptr(N+1) and its subpages have values greater than Key(N). And
32** so forth.
33**
drh5e00f6c2001-09-13 13:46:56 +000034** Finding a particular key requires reading O(log(M)) pages from the
35** disk where M is the number of entries in the tree.
drh8b2f49b2001-06-08 00:21:52 +000036**
37** In this implementation, a single file can hold one or more separate
38** BTrees. Each BTree is identified by the index of its root page. The
drh9e572e62004-04-23 23:43:10 +000039** key and data for any entry are combined to form the "payload". A
40** fixed amount of payload can be carried directly on the database
41** page. If the payload is larger than the preset amount then surplus
42** bytes are stored on overflow pages. The payload for an entry
43** and the preceding pointer are combined to form a "Cell". Each
44** page has a small header which contains the Ptr(N+1) pointer and other
45** information such as the size of key and data.
drh8b2f49b2001-06-08 00:21:52 +000046**
drh9e572e62004-04-23 23:43:10 +000047** FORMAT DETAILS
48**
49** The file is divided into pages. The first page is called page 1,
50** the second is page 2, and so forth. A page number of zero indicates
51** "no such page". The page size can be anything between 512 and 65536.
52** Each page can be either a btree page, a freelist page or an overflow
53** page.
54**
55** The first page is always a btree page. The first 100 bytes of the first
drh271efa52004-05-30 19:19:05 +000056** page contain a special header (the "file header") that describes the file.
57** The format of the file header is as follows:
drh9e572e62004-04-23 23:43:10 +000058**
59** OFFSET SIZE DESCRIPTION
drhde647132004-05-07 17:57:49 +000060** 0 16 Header string: "SQLite format 3\000"
drh9e572e62004-04-23 23:43:10 +000061** 16 2 Page size in bytes.
62** 18 1 File format write version
63** 19 1 File format read version
drh6f11bef2004-05-13 01:12:56 +000064** 20 1 Bytes of unused space at the end of each page
65** 21 1 Max embedded payload fraction
66** 22 1 Min embedded payload fraction
67** 23 1 Min leaf payload fraction
68** 24 4 File change counter
69** 28 4 Reserved for future use
drh9e572e62004-04-23 23:43:10 +000070** 32 4 First freelist page
71** 36 4 Number of freelist pages in the file
72** 40 60 15 4-byte meta values passed to higher layers
73**
74** All of the integer values are big-endian (most significant byte first).
drh6f11bef2004-05-13 01:12:56 +000075**
drhab01f612004-05-22 02:55:23 +000076** The file change counter is incremented when the database is changed more
drh6f11bef2004-05-13 01:12:56 +000077** than once within the same second. This counter, together with the
78** modification time of the file, allows other processes to know
79** when the file has changed and thus when they need to flush their
80** cache.
81**
82** The max embedded payload fraction is the amount of the total usable
83** space in a page that can be consumed by a single cell for standard
84** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
85** is to limit the maximum cell size so that at least 4 cells will fit
drhab01f612004-05-22 02:55:23 +000086** on one page. Thus the default max embedded payload fraction is 64.
drh6f11bef2004-05-13 01:12:56 +000087**
88** If the payload for a cell is larger than the max payload, then extra
89** payload is spilled to overflow pages. Once an overflow page is allocated,
90** as many bytes as possible are moved into the overflow pages without letting
91** the cell size drop below the min embedded payload fraction.
92**
93** The min leaf payload fraction is like the min embedded payload fraction
94** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
95** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
96** not specified in the header.
drh9e572e62004-04-23 23:43:10 +000097**
drh43605152004-05-29 21:46:49 +000098** Each btree pages is divided into three sections: The header, the
99** cell pointer array, and the cell area area. Page 1 also has a 100-byte
drh271efa52004-05-30 19:19:05 +0000100** file header that occurs before the page header.
101**
102** |----------------|
103** | file header | 100 bytes. Page 1 only.
104** |----------------|
105** | page header | 8 bytes for leaves. 12 bytes for interior nodes
106** |----------------|
107** | cell pointer | | 2 bytes per cell. Sorted order.
108** | array | | Grows downward
109** | | v
110** |----------------|
111** | unallocated |
112** | space |
113** |----------------| ^ Grows upwards
114** | cell content | | Arbitrary order interspersed with freeblocks.
115** | area | | and free space fragments.
116** |----------------|
drh43605152004-05-29 21:46:49 +0000117**
118** The page headers looks like this:
drh9e572e62004-04-23 23:43:10 +0000119**
120** OFFSET SIZE DESCRIPTION
drh6f11bef2004-05-13 01:12:56 +0000121** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
drh9e572e62004-04-23 23:43:10 +0000122** 1 2 byte offset to the first freeblock
drh43605152004-05-29 21:46:49 +0000123** 3 2 number of cells on this page
drh271efa52004-05-30 19:19:05 +0000124** 5 2 first byte of the cell content area
drh43605152004-05-29 21:46:49 +0000125** 7 1 number of fragmented free bytes
drh271efa52004-05-30 19:19:05 +0000126** 8 4 Right child (the Ptr(N+1) value). Omitted on leaves.
drh9e572e62004-04-23 23:43:10 +0000127**
128** The flags define the format of this btree page. The leaf flag means that
129** this page has no children. The zerodata flag means that this page carries
drh44f87bd2004-09-27 13:19:51 +0000130** only keys and no data. The intkey flag means that the key is a integer
131** which is stored in the key size entry of the cell header rather than in
132** the payload area.
drh9e572e62004-04-23 23:43:10 +0000133**
drh43605152004-05-29 21:46:49 +0000134** The cell pointer array begins on the first byte after the page header.
135** The cell pointer array contains zero or more 2-byte numbers which are
136** offsets from the beginning of the page to the cell content in the cell
137** content area. The cell pointers occur in sorted order. The system strives
138** to keep free space after the last cell pointer so that new cells can
drh44f87bd2004-09-27 13:19:51 +0000139** be easily added without having to defragment the page.
drh43605152004-05-29 21:46:49 +0000140**
141** Cell content is stored at the very end of the page and grows toward the
142** beginning of the page.
143**
144** Unused space within the cell content area is collected into a linked list of
145** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
146** to the first freeblock is given in the header. Freeblocks occur in
147** increasing order. Because a freeblock must be at least 4 bytes in size,
148** any group of 3 or fewer unused bytes in the cell content area cannot
149** exist on the freeblock chain. A group of 3 or fewer free bytes is called
150** a fragment. The total number of bytes in all fragments is recorded.
151** in the page header at offset 7.
152**
153** SIZE DESCRIPTION
154** 2 Byte offset of the next freeblock
155** 2 Bytes in this freeblock
156**
157** Cells are of variable length. Cells are stored in the cell content area at
158** the end of the page. Pointers to the cells are in the cell pointer array
159** that immediately follows the page header. Cells is not necessarily
160** contiguous or in order, but cell pointers are contiguous and in order.
161**
162** Cell content makes use of variable length integers. A variable
163** length integer is 1 to 9 bytes where the lower 7 bits of each
drh9e572e62004-04-23 23:43:10 +0000164** byte are used. The integer consists of all bytes that have bit 8 set and
drh6f11bef2004-05-13 01:12:56 +0000165** the first byte with bit 8 clear. The most significant byte of the integer
drhab01f612004-05-22 02:55:23 +0000166** appears first. A variable-length integer may not be more than 9 bytes long.
167** As a special case, all 8 bytes of the 9th byte are used as data. This
168** allows a 64-bit integer to be encoded in 9 bytes.
drh9e572e62004-04-23 23:43:10 +0000169**
170** 0x00 becomes 0x00000000
drh6f11bef2004-05-13 01:12:56 +0000171** 0x7f becomes 0x0000007f
172** 0x81 0x00 becomes 0x00000080
173** 0x82 0x00 becomes 0x00000100
174** 0x80 0x7f becomes 0x0000007f
175** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
drh9e572e62004-04-23 23:43:10 +0000176** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
177**
178** Variable length integers are used for rowids and to hold the number of
179** bytes of key and data in a btree cell.
180**
drh43605152004-05-29 21:46:49 +0000181** The content of a cell looks like this:
drh9e572e62004-04-23 23:43:10 +0000182**
183** SIZE DESCRIPTION
drh3aac2dd2004-04-26 14:10:20 +0000184** 4 Page number of the left child. Omitted if leaf flag is set.
185** var Number of bytes of data. Omitted if the zerodata flag is set.
186** var Number of bytes of key. Or the key itself if intkey flag is set.
drh9e572e62004-04-23 23:43:10 +0000187** * Payload
188** 4 First page of the overflow chain. Omitted if no overflow
189**
190** Overflow pages form a linked list. Each page except the last is completely
191** filled with data (pagesize - 4 bytes). The last page can have as little
192** as 1 byte of data.
193**
194** SIZE DESCRIPTION
195** 4 Page number of next overflow page
196** * Data
197**
198** Freelist pages come in two subtypes: trunk pages and leaf pages. The
199** file header points to first in a linked list of trunk page. Each trunk
200** page points to multiple leaf pages. The content of a leaf page is
201** unspecified. A trunk page looks like this:
202**
203** SIZE DESCRIPTION
204** 4 Page number of next trunk page
205** 4 Number of leaf pointers on this page
206** * zero or more pages numbers of leaves
drha059ad02001-04-17 20:09:11 +0000207*/
208#include "sqliteInt.h"
209#include "pager.h"
210#include "btree.h"
drh1f595712004-06-15 01:40:29 +0000211#include "os.h"
drha059ad02001-04-17 20:09:11 +0000212#include <assert.h>
213
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
drh4b70f112004-05-02 21:12:19 +00002689 if( pBt->pPage1==0 ){
danielk1977aef0bf62005-12-30 16:28:01 +00002690 rc = lockBtreeWithRetry(p);
drha059ad02001-04-17 20:09:11 +00002691 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002692 return rc;
2693 }
2694 }
danielk1977da184232006-01-05 11:34:32 +00002695 pCur = sqliteMalloc( sizeof(*pCur) );
drha059ad02001-04-17 20:09:11 +00002696 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +00002697 rc = SQLITE_NOMEM;
2698 goto create_cursor_exception;
2699 }
drh8b2f49b2001-06-08 00:21:52 +00002700 pCur->pgnoRoot = (Pgno)iTable;
danielk19776b456a22005-03-21 04:04:02 +00002701 pCur->pPage = 0; /* For exit-handler, in case getAndInitPage() fails. */
drh24cd67e2004-05-10 16:18:47 +00002702 if( iTable==1 && sqlite3pager_pagecount(pBt->pPager)==0 ){
2703 rc = SQLITE_EMPTY;
2704 goto create_cursor_exception;
2705 }
drhde647132004-05-07 17:57:49 +00002706 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
drhbd03cae2001-06-02 02:40:57 +00002707 if( rc!=SQLITE_OK ){
2708 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002709 }
danielk1977aef0bf62005-12-30 16:28:01 +00002710
danielk1977aef0bf62005-12-30 16:28:01 +00002711 /* Now that no other errors can occur, finish filling in the BtCursor
2712 ** variables, link the cursor into the BtShared list and set *ppCur (the
2713 ** output argument to this function).
2714 */
drh3aac2dd2004-04-26 14:10:20 +00002715 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2716 pCur->pArg = pArg;
danielk1977aef0bf62005-12-30 16:28:01 +00002717 pCur->pBtree = p;
drhecdc7532001-09-23 02:35:53 +00002718 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +00002719 pCur->idx = 0;
drh59eb6762004-06-13 23:07:04 +00002720 memset(&pCur->info, 0, sizeof(pCur->info));
drha059ad02001-04-17 20:09:11 +00002721 pCur->pNext = pBt->pCursor;
2722 if( pCur->pNext ){
2723 pCur->pNext->pPrev = pCur;
2724 }
drh14acc042001-06-10 19:56:58 +00002725 pCur->pPrev = 0;
drha059ad02001-04-17 20:09:11 +00002726 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00002727 pCur->eState = CURSOR_INVALID;
drh2af926b2001-05-15 00:39:25 +00002728 *ppCur = pCur;
drhbd03cae2001-06-02 02:40:57 +00002729
danielk1977aef0bf62005-12-30 16:28:01 +00002730 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00002731create_cursor_exception:
drhbd03cae2001-06-02 02:40:57 +00002732 if( pCur ){
drh3aac2dd2004-04-26 14:10:20 +00002733 releasePage(pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +00002734 sqliteFree(pCur);
2735 }
drh5e00f6c2001-09-13 13:46:56 +00002736 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00002737 return rc;
drha059ad02001-04-17 20:09:11 +00002738}
2739
drh7a224de2004-06-02 01:22:02 +00002740#if 0 /* Not Used */
drhd3d39e92004-05-20 22:16:29 +00002741/*
2742** Change the value of the comparison function used by a cursor.
2743*/
danielk1977bf3b7212004-05-18 10:06:24 +00002744void sqlite3BtreeSetCompare(
drhd3d39e92004-05-20 22:16:29 +00002745 BtCursor *pCur, /* The cursor to whose comparison function is changed */
2746 int(*xCmp)(void*,int,const void*,int,const void*), /* New comparison func */
2747 void *pArg /* First argument to xCmp() */
danielk1977bf3b7212004-05-18 10:06:24 +00002748){
2749 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2750 pCur->pArg = pArg;
2751}
drh7a224de2004-06-02 01:22:02 +00002752#endif
danielk1977bf3b7212004-05-18 10:06:24 +00002753
drha059ad02001-04-17 20:09:11 +00002754/*
drh5e00f6c2001-09-13 13:46:56 +00002755** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00002756** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00002757*/
drh3aac2dd2004-04-26 14:10:20 +00002758int sqlite3BtreeCloseCursor(BtCursor *pCur){
danielk1977aef0bf62005-12-30 16:28:01 +00002759 BtShared *pBt = pCur->pBtree->pBt;
danielk1977da184232006-01-05 11:34:32 +00002760 restoreCursorPosition(pCur, 0);
drha059ad02001-04-17 20:09:11 +00002761 if( pCur->pPrev ){
2762 pCur->pPrev->pNext = pCur->pNext;
2763 }else{
2764 pBt->pCursor = pCur->pNext;
2765 }
2766 if( pCur->pNext ){
2767 pCur->pNext->pPrev = pCur->pPrev;
2768 }
drh3aac2dd2004-04-26 14:10:20 +00002769 releasePage(pCur->pPage);
drh5e00f6c2001-09-13 13:46:56 +00002770 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00002771 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +00002772 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002773}
2774
drh7e3b0a02001-04-28 16:52:40 +00002775/*
drh5e2f8b92001-05-28 00:41:15 +00002776** Make a temporary cursor by filling in the fields of pTempCur.
2777** The temporary cursor is not on the cursor list for the Btree.
2778*/
drh14acc042001-06-10 19:56:58 +00002779static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00002780 memcpy(pTempCur, pCur, sizeof(*pCur));
2781 pTempCur->pNext = 0;
2782 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00002783 if( pTempCur->pPage ){
drha34b6762004-05-07 13:30:42 +00002784 sqlite3pager_ref(pTempCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00002785 }
drh5e2f8b92001-05-28 00:41:15 +00002786}
2787
2788/*
drhbd03cae2001-06-02 02:40:57 +00002789** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00002790** function above.
2791*/
drh14acc042001-06-10 19:56:58 +00002792static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00002793 if( pCur->pPage ){
drha34b6762004-05-07 13:30:42 +00002794 sqlite3pager_unref(pCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00002795 }
drh5e2f8b92001-05-28 00:41:15 +00002796}
2797
2798/*
drh9188b382004-05-14 21:12:22 +00002799** Make sure the BtCursor.info field of the given cursor is valid.
drhab01f612004-05-22 02:55:23 +00002800** If it is not already valid, call parseCell() to fill it in.
2801**
2802** BtCursor.info is a cache of the information in the current cell.
2803** Using this cache reduces the number of calls to parseCell().
drh9188b382004-05-14 21:12:22 +00002804*/
2805static void getCellInfo(BtCursor *pCur){
drh271efa52004-05-30 19:19:05 +00002806 if( pCur->info.nSize==0 ){
drh3a41a3f2004-05-30 02:14:17 +00002807 parseCell(pCur->pPage, pCur->idx, &pCur->info);
drh9188b382004-05-14 21:12:22 +00002808 }else{
2809#ifndef NDEBUG
2810 CellInfo info;
drh51c6d962004-06-06 00:42:25 +00002811 memset(&info, 0, sizeof(info));
drh3a41a3f2004-05-30 02:14:17 +00002812 parseCell(pCur->pPage, pCur->idx, &info);
drh9188b382004-05-14 21:12:22 +00002813 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
2814#endif
2815 }
2816}
2817
2818/*
drh3aac2dd2004-04-26 14:10:20 +00002819** Set *pSize to the size of the buffer needed to hold the value of
2820** the key for the current entry. If the cursor is not pointing
2821** to a valid entry, *pSize is set to 0.
2822**
drh4b70f112004-05-02 21:12:19 +00002823** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00002824** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00002825*/
drh4a1c3802004-05-12 15:15:47 +00002826int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
danielk1977da184232006-01-05 11:34:32 +00002827 int rc = restoreCursorPosition(pCur, 1);
2828 if( rc==SQLITE_OK ){
2829 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
2830 if( pCur->eState==CURSOR_INVALID ){
2831 *pSize = 0;
2832 }else{
2833 getCellInfo(pCur);
2834 *pSize = pCur->info.nKey;
2835 }
drh72f82862001-05-24 21:06:34 +00002836 }
danielk1977da184232006-01-05 11:34:32 +00002837 return rc;
drha059ad02001-04-17 20:09:11 +00002838}
drh2af926b2001-05-15 00:39:25 +00002839
drh72f82862001-05-24 21:06:34 +00002840/*
drh0e1c19e2004-05-11 00:58:56 +00002841** Set *pSize to the number of bytes of data in the entry the
2842** cursor currently points to. Always return SQLITE_OK.
2843** Failure is not possible. If the cursor is not currently
2844** pointing to an entry (which can happen, for example, if
2845** the database is empty) then *pSize is set to 0.
2846*/
2847int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
danielk1977da184232006-01-05 11:34:32 +00002848 int rc = restoreCursorPosition(pCur, 1);
2849 if( rc==SQLITE_OK ){
2850 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
2851 if( pCur->eState==CURSOR_INVALID ){
2852 /* Not pointing at a valid entry - set *pSize to 0. */
2853 *pSize = 0;
2854 }else{
2855 getCellInfo(pCur);
2856 *pSize = pCur->info.nData;
2857 }
drh0e1c19e2004-05-11 00:58:56 +00002858 }
danielk1977da184232006-01-05 11:34:32 +00002859 return rc;
drh0e1c19e2004-05-11 00:58:56 +00002860}
2861
2862/*
drh72f82862001-05-24 21:06:34 +00002863** Read payload information from the entry that the pCur cursor is
2864** pointing to. Begin reading the payload at "offset" and read
2865** a total of "amt" bytes. Put the result in zBuf.
2866**
2867** This routine does not make a distinction between key and data.
drhab01f612004-05-22 02:55:23 +00002868** It just reads bytes from the payload area. Data might appear
2869** on the main page or be scattered out on multiple overflow pages.
drh72f82862001-05-24 21:06:34 +00002870*/
drh3aac2dd2004-04-26 14:10:20 +00002871static int getPayload(
2872 BtCursor *pCur, /* Cursor pointing to entry to read from */
2873 int offset, /* Begin reading this far into payload */
2874 int amt, /* Read this many bytes */
2875 unsigned char *pBuf, /* Write the bytes into this buffer */
2876 int skipKey /* offset begins at data if this is true */
2877){
2878 unsigned char *aPayload;
drh2af926b2001-05-15 00:39:25 +00002879 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +00002880 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002881 MemPage *pPage;
danielk1977aef0bf62005-12-30 16:28:01 +00002882 BtShared *pBt;
drh6f11bef2004-05-13 01:12:56 +00002883 int ovflSize;
drhfa1a98a2004-05-14 19:08:17 +00002884 u32 nKey;
drh3aac2dd2004-04-26 14:10:20 +00002885
drh72f82862001-05-24 21:06:34 +00002886 assert( pCur!=0 && pCur->pPage!=0 );
danielk1977da184232006-01-05 11:34:32 +00002887 assert( pCur->eState==CURSOR_VALID );
danielk1977aef0bf62005-12-30 16:28:01 +00002888 pBt = pCur->pBtree->pBt;
drh3aac2dd2004-04-26 14:10:20 +00002889 pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00002890 pageIntegrity(pPage);
drh3aac2dd2004-04-26 14:10:20 +00002891 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00002892 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00002893 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00002894 aPayload += pCur->info.nHeader;
drh3aac2dd2004-04-26 14:10:20 +00002895 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00002896 nKey = 0;
2897 }else{
2898 nKey = pCur->info.nKey;
drh3aac2dd2004-04-26 14:10:20 +00002899 }
2900 assert( offset>=0 );
2901 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00002902 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00002903 }
drhfa1a98a2004-05-14 19:08:17 +00002904 if( offset+amt > nKey+pCur->info.nData ){
drha34b6762004-05-07 13:30:42 +00002905 return SQLITE_ERROR;
drh3aac2dd2004-04-26 14:10:20 +00002906 }
drhfa1a98a2004-05-14 19:08:17 +00002907 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00002908 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00002909 if( a+offset>pCur->info.nLocal ){
2910 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00002911 }
drha34b6762004-05-07 13:30:42 +00002912 memcpy(pBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +00002913 if( a==amt ){
2914 return SQLITE_OK;
2915 }
drh2aa679f2001-06-25 02:11:07 +00002916 offset = 0;
drha34b6762004-05-07 13:30:42 +00002917 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00002918 amt -= a;
drhdd793422001-06-28 01:54:48 +00002919 }else{
drhfa1a98a2004-05-14 19:08:17 +00002920 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00002921 }
danielk1977cfe9a692004-06-16 12:00:29 +00002922 ovflSize = pBt->usableSize - 4;
drhbd03cae2001-06-02 02:40:57 +00002923 if( amt>0 ){
drhfa1a98a2004-05-14 19:08:17 +00002924 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977cfe9a692004-06-16 12:00:29 +00002925 while( amt>0 && nextPage ){
2926 rc = sqlite3pager_get(pBt->pPager, nextPage, (void**)&aPayload);
2927 if( rc!=0 ){
2928 return rc;
drh2af926b2001-05-15 00:39:25 +00002929 }
danielk1977cfe9a692004-06-16 12:00:29 +00002930 nextPage = get4byte(aPayload);
2931 if( offset<ovflSize ){
2932 int a = amt;
2933 if( a + offset > ovflSize ){
2934 a = ovflSize - offset;
2935 }
2936 memcpy(pBuf, &aPayload[offset+4], a);
2937 offset = 0;
2938 amt -= a;
2939 pBuf += a;
2940 }else{
2941 offset -= ovflSize;
2942 }
2943 sqlite3pager_unref(aPayload);
drh2af926b2001-05-15 00:39:25 +00002944 }
drh2af926b2001-05-15 00:39:25 +00002945 }
danielk1977cfe9a692004-06-16 12:00:29 +00002946
drha7fcb052001-12-14 15:09:55 +00002947 if( amt>0 ){
drh49285702005-09-17 15:20:26 +00002948 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00002949 }
2950 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00002951}
2952
drh72f82862001-05-24 21:06:34 +00002953/*
drh3aac2dd2004-04-26 14:10:20 +00002954** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002955** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002956** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00002957**
drh3aac2dd2004-04-26 14:10:20 +00002958** Return SQLITE_OK on success or an error code if anything goes
2959** wrong. An error is returned if "offset+amt" is larger than
2960** the available payload.
drh72f82862001-05-24 21:06:34 +00002961*/
drha34b6762004-05-07 13:30:42 +00002962int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
danielk1977da184232006-01-05 11:34:32 +00002963 int rc = restoreCursorPosition(pCur, 1);
2964 if( rc==SQLITE_OK ){
2965 assert( pCur->eState==CURSOR_VALID );
2966 assert( pCur->pPage!=0 );
2967 if( pCur->pPage->intKey ){
2968 return SQLITE_CORRUPT_BKPT;
2969 }
2970 assert( pCur->pPage->intKey==0 );
2971 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
2972 rc = getPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
drh6575a222005-03-10 17:06:34 +00002973 }
danielk1977da184232006-01-05 11:34:32 +00002974 return rc;
drh3aac2dd2004-04-26 14:10:20 +00002975}
2976
2977/*
drh3aac2dd2004-04-26 14:10:20 +00002978** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002979** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002980** begins at "offset".
2981**
2982** Return SQLITE_OK on success or an error code if anything goes
2983** wrong. An error is returned if "offset+amt" is larger than
2984** the available payload.
drh72f82862001-05-24 21:06:34 +00002985*/
drh3aac2dd2004-04-26 14:10:20 +00002986int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
danielk1977da184232006-01-05 11:34:32 +00002987 int rc = restoreCursorPosition(pCur, 1);
2988 if( rc==SQLITE_OK ){
2989 assert( pCur->eState==CURSOR_VALID );
2990 assert( pCur->pPage!=0 );
2991 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
2992 rc = getPayload(pCur, offset, amt, pBuf, 1);
2993 }
2994 return rc;
drh2af926b2001-05-15 00:39:25 +00002995}
2996
drh72f82862001-05-24 21:06:34 +00002997/*
drh0e1c19e2004-05-11 00:58:56 +00002998** Return a pointer to payload information from the entry that the
2999** pCur cursor is pointing to. The pointer is to the beginning of
3000** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00003001** skipKey==1. The number of bytes of available key/data is written
3002** into *pAmt. If *pAmt==0, then the value returned will not be
3003** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00003004**
3005** This routine is an optimization. It is common for the entire key
3006** and data to fit on the local page and for there to be no overflow
3007** pages. When that is so, this routine can be used to access the
3008** key and data without making a copy. If the key and/or data spills
3009** onto overflow pages, then getPayload() must be used to reassembly
3010** the key/data and copy it into a preallocated buffer.
3011**
3012** The pointer returned by this routine looks directly into the cached
3013** page of the database. The data might change or move the next time
3014** any btree routine is called.
3015*/
3016static const unsigned char *fetchPayload(
3017 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00003018 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00003019 int skipKey /* read beginning at data if this is true */
3020){
3021 unsigned char *aPayload;
3022 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00003023 u32 nKey;
3024 int nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003025
3026 assert( pCur!=0 && pCur->pPage!=0 );
danielk1977da184232006-01-05 11:34:32 +00003027 assert( pCur->eState==CURSOR_VALID );
drh0e1c19e2004-05-11 00:58:56 +00003028 pPage = pCur->pPage;
3029 pageIntegrity(pPage);
3030 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00003031 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00003032 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00003033 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00003034 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00003035 nKey = 0;
3036 }else{
3037 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00003038 }
drh0e1c19e2004-05-11 00:58:56 +00003039 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003040 aPayload += nKey;
3041 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00003042 }else{
drhfa1a98a2004-05-14 19:08:17 +00003043 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00003044 if( nLocal>nKey ){
3045 nLocal = nKey;
3046 }
drh0e1c19e2004-05-11 00:58:56 +00003047 }
drhe51c44f2004-05-30 20:46:09 +00003048 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003049 return aPayload;
3050}
3051
3052
3053/*
drhe51c44f2004-05-30 20:46:09 +00003054** For the entry that cursor pCur is point to, return as
3055** many bytes of the key or data as are available on the local
3056** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00003057**
3058** The pointer returned is ephemeral. The key/data may move
3059** or be destroyed on the next call to any Btree routine.
3060**
3061** These routines is used to get quick access to key and data
3062** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00003063*/
drhe51c44f2004-05-30 20:46:09 +00003064const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
danielk1977da184232006-01-05 11:34:32 +00003065 if( pCur->eState==CURSOR_VALID ){
3066 return (const void*)fetchPayload(pCur, pAmt, 0);
3067 }
3068 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003069}
drhe51c44f2004-05-30 20:46:09 +00003070const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
danielk1977da184232006-01-05 11:34:32 +00003071 if( pCur->eState==CURSOR_VALID ){
3072 return (const void*)fetchPayload(pCur, pAmt, 1);
3073 }
3074 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003075}
3076
3077
3078/*
drh8178a752003-01-05 21:41:40 +00003079** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00003080** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00003081*/
drh3aac2dd2004-04-26 14:10:20 +00003082static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00003083 int rc;
3084 MemPage *pNewPage;
drh3aac2dd2004-04-26 14:10:20 +00003085 MemPage *pOldPage;
danielk1977aef0bf62005-12-30 16:28:01 +00003086 BtShared *pBt = pCur->pBtree->pBt;
drh72f82862001-05-24 21:06:34 +00003087
danielk1977da184232006-01-05 11:34:32 +00003088 assert( pCur->eState==CURSOR_VALID );
drhde647132004-05-07 17:57:49 +00003089 rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00003090 if( rc ) return rc;
drhda200cc2004-05-09 11:51:38 +00003091 pageIntegrity(pNewPage);
drh428ae8c2003-01-04 16:48:09 +00003092 pNewPage->idxParent = pCur->idx;
drh3aac2dd2004-04-26 14:10:20 +00003093 pOldPage = pCur->pPage;
3094 pOldPage->idxShift = 0;
3095 releasePage(pOldPage);
drh72f82862001-05-24 21:06:34 +00003096 pCur->pPage = pNewPage;
3097 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00003098 pCur->info.nSize = 0;
drh4be295b2003-12-16 03:44:47 +00003099 if( pNewPage->nCell<1 ){
drh49285702005-09-17 15:20:26 +00003100 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00003101 }
drh72f82862001-05-24 21:06:34 +00003102 return SQLITE_OK;
3103}
3104
3105/*
drh8856d6a2004-04-29 14:42:46 +00003106** Return true if the page is the virtual root of its table.
3107**
3108** The virtual root page is the root page for most tables. But
3109** for the table rooted on page 1, sometime the real root page
3110** is empty except for the right-pointer. In such cases the
3111** virtual root page is the page that the right-pointer of page
3112** 1 is pointing to.
3113*/
3114static int isRootPage(MemPage *pPage){
3115 MemPage *pParent = pPage->pParent;
drhda200cc2004-05-09 11:51:38 +00003116 if( pParent==0 ) return 1;
3117 if( pParent->pgno>1 ) return 0;
3118 if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
drh8856d6a2004-04-29 14:42:46 +00003119 return 0;
3120}
3121
3122/*
drh5e2f8b92001-05-28 00:41:15 +00003123** Move the cursor up to the parent page.
3124**
3125** pCur->idx is set to the cell index that contains the pointer
3126** to the page we are coming from. If we are coming from the
3127** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00003128** the largest cell index.
drh72f82862001-05-24 21:06:34 +00003129*/
drh8178a752003-01-05 21:41:40 +00003130static void moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00003131 MemPage *pParent;
drh8178a752003-01-05 21:41:40 +00003132 MemPage *pPage;
drh428ae8c2003-01-04 16:48:09 +00003133 int idxParent;
drh3aac2dd2004-04-26 14:10:20 +00003134
danielk1977da184232006-01-05 11:34:32 +00003135 assert( pCur->eState==CURSOR_VALID );
drh8178a752003-01-05 21:41:40 +00003136 pPage = pCur->pPage;
3137 assert( pPage!=0 );
drh8856d6a2004-04-29 14:42:46 +00003138 assert( !isRootPage(pPage) );
drhda200cc2004-05-09 11:51:38 +00003139 pageIntegrity(pPage);
drh8178a752003-01-05 21:41:40 +00003140 pParent = pPage->pParent;
3141 assert( pParent!=0 );
drhda200cc2004-05-09 11:51:38 +00003142 pageIntegrity(pParent);
drh8178a752003-01-05 21:41:40 +00003143 idxParent = pPage->idxParent;
drha34b6762004-05-07 13:30:42 +00003144 sqlite3pager_ref(pParent->aData);
drh3aac2dd2004-04-26 14:10:20 +00003145 releasePage(pPage);
drh72f82862001-05-24 21:06:34 +00003146 pCur->pPage = pParent;
drh271efa52004-05-30 19:19:05 +00003147 pCur->info.nSize = 0;
drh428ae8c2003-01-04 16:48:09 +00003148 assert( pParent->idxShift==0 );
drh43605152004-05-29 21:46:49 +00003149 pCur->idx = idxParent;
drh72f82862001-05-24 21:06:34 +00003150}
3151
3152/*
3153** Move the cursor to the root page
3154*/
drh5e2f8b92001-05-28 00:41:15 +00003155static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00003156 MemPage *pRoot;
drhbd03cae2001-06-02 02:40:57 +00003157 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003158 BtShared *pBt = pCur->pBtree->pBt;
drhbd03cae2001-06-02 02:40:57 +00003159
danielk1977da184232006-01-05 11:34:32 +00003160 restoreCursorPosition(pCur, 0);
drhde647132004-05-07 17:57:49 +00003161 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0);
drhc39e0002004-05-07 23:50:57 +00003162 if( rc ){
danielk1977da184232006-01-05 11:34:32 +00003163 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00003164 return rc;
3165 }
drh3aac2dd2004-04-26 14:10:20 +00003166 releasePage(pCur->pPage);
drhda200cc2004-05-09 11:51:38 +00003167 pageIntegrity(pRoot);
drh3aac2dd2004-04-26 14:10:20 +00003168 pCur->pPage = pRoot;
drh72f82862001-05-24 21:06:34 +00003169 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00003170 pCur->info.nSize = 0;
drh8856d6a2004-04-29 14:42:46 +00003171 if( pRoot->nCell==0 && !pRoot->leaf ){
3172 Pgno subpage;
3173 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00003174 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00003175 assert( subpage>0 );
danielk1977da184232006-01-05 11:34:32 +00003176 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00003177 rc = moveToChild(pCur, subpage);
drh8856d6a2004-04-29 14:42:46 +00003178 }
danielk1977da184232006-01-05 11:34:32 +00003179 pCur->eState = ((pCur->pPage->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00003180 return rc;
drh72f82862001-05-24 21:06:34 +00003181}
drh2af926b2001-05-15 00:39:25 +00003182
drh5e2f8b92001-05-28 00:41:15 +00003183/*
3184** Move the cursor down to the left-most leaf entry beneath the
3185** entry to which it is currently pointing.
3186*/
3187static int moveToLeftmost(BtCursor *pCur){
3188 Pgno pgno;
3189 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003190 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00003191
danielk1977da184232006-01-05 11:34:32 +00003192 assert( pCur->eState==CURSOR_VALID );
drh3aac2dd2004-04-26 14:10:20 +00003193 while( !(pPage = pCur->pPage)->leaf ){
drha34b6762004-05-07 13:30:42 +00003194 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00003195 pgno = get4byte(findCell(pPage, pCur->idx));
drh8178a752003-01-05 21:41:40 +00003196 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00003197 if( rc ) return rc;
3198 }
3199 return SQLITE_OK;
3200}
3201
drh2dcc9aa2002-12-04 13:40:25 +00003202/*
3203** Move the cursor down to the right-most leaf entry beneath the
3204** page to which it is currently pointing. Notice the difference
3205** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
3206** finds the left-most entry beneath the *entry* whereas moveToRightmost()
3207** finds the right-most entry beneath the *page*.
3208*/
3209static int moveToRightmost(BtCursor *pCur){
3210 Pgno pgno;
3211 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003212 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003213
danielk1977da184232006-01-05 11:34:32 +00003214 assert( pCur->eState==CURSOR_VALID );
drh3aac2dd2004-04-26 14:10:20 +00003215 while( !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00003216 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh3aac2dd2004-04-26 14:10:20 +00003217 pCur->idx = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00003218 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003219 if( rc ) return rc;
3220 }
drh3aac2dd2004-04-26 14:10:20 +00003221 pCur->idx = pPage->nCell - 1;
drh271efa52004-05-30 19:19:05 +00003222 pCur->info.nSize = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003223 return SQLITE_OK;
3224}
3225
drh5e00f6c2001-09-13 13:46:56 +00003226/* Move the cursor to the first entry in the table. Return SQLITE_OK
3227** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003228** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00003229*/
drh3aac2dd2004-04-26 14:10:20 +00003230int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00003231 int rc;
3232 rc = moveToRoot(pCur);
3233 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00003234 if( pCur->eState==CURSOR_INVALID ){
drhc39e0002004-05-07 23:50:57 +00003235 assert( pCur->pPage->nCell==0 );
drh5e00f6c2001-09-13 13:46:56 +00003236 *pRes = 1;
3237 return SQLITE_OK;
3238 }
drhc39e0002004-05-07 23:50:57 +00003239 assert( pCur->pPage->nCell>0 );
drh5e00f6c2001-09-13 13:46:56 +00003240 *pRes = 0;
3241 rc = moveToLeftmost(pCur);
3242 return rc;
3243}
drh5e2f8b92001-05-28 00:41:15 +00003244
drh9562b552002-02-19 15:00:07 +00003245/* Move the cursor to the last entry in the table. Return SQLITE_OK
3246** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003247** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00003248*/
drh3aac2dd2004-04-26 14:10:20 +00003249int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00003250 int rc;
drh9562b552002-02-19 15:00:07 +00003251 rc = moveToRoot(pCur);
3252 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00003253 if( CURSOR_INVALID==pCur->eState ){
drhc39e0002004-05-07 23:50:57 +00003254 assert( pCur->pPage->nCell==0 );
drh9562b552002-02-19 15:00:07 +00003255 *pRes = 1;
3256 return SQLITE_OK;
3257 }
danielk1977da184232006-01-05 11:34:32 +00003258 assert( pCur->eState==CURSOR_VALID );
drh9562b552002-02-19 15:00:07 +00003259 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003260 rc = moveToRightmost(pCur);
drh9562b552002-02-19 15:00:07 +00003261 return rc;
3262}
3263
drh3aac2dd2004-04-26 14:10:20 +00003264/* Move the cursor so that it points to an entry near pKey/nKey.
drh72f82862001-05-24 21:06:34 +00003265** Return a success code.
3266**
drh3aac2dd2004-04-26 14:10:20 +00003267** For INTKEY tables, only the nKey parameter is used. pKey is
3268** ignored. For other tables, nKey is the number of bytes of data
drh0b2f3162005-12-21 18:36:45 +00003269** in pKey. The comparison function specified when the cursor was
drh3aac2dd2004-04-26 14:10:20 +00003270** created is used to compare keys.
3271**
drh5e2f8b92001-05-28 00:41:15 +00003272** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00003273** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00003274** were present. The cursor might point to an entry that comes
3275** before or after the key.
3276**
drhbd03cae2001-06-02 02:40:57 +00003277** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00003278** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00003279** this value is as follows:
3280**
3281** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00003282** is smaller than pKey or if the table is empty
3283** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00003284**
3285** *pRes==0 The cursor is left pointing at an entry that
3286** exactly matches pKey.
3287**
3288** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00003289** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00003290*/
drh4a1c3802004-05-12 15:15:47 +00003291int sqlite3BtreeMoveto(BtCursor *pCur, const void *pKey, i64 nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00003292 int rc;
drh5e2f8b92001-05-28 00:41:15 +00003293 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00003294 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00003295 assert( pCur->pPage );
3296 assert( pCur->pPage->isInit );
danielk1977da184232006-01-05 11:34:32 +00003297 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00003298 *pRes = -1;
drhc39e0002004-05-07 23:50:57 +00003299 assert( pCur->pPage->nCell==0 );
3300 return SQLITE_OK;
3301 }
drh4eec4c12005-01-21 00:22:37 +00003302 for(;;){
drh72f82862001-05-24 21:06:34 +00003303 int lwr, upr;
3304 Pgno chldPg;
3305 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00003306 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00003307 lwr = 0;
3308 upr = pPage->nCell-1;
drh4eec4c12005-01-21 00:22:37 +00003309 if( !pPage->intKey && pKey==0 ){
drh49285702005-09-17 15:20:26 +00003310 return SQLITE_CORRUPT_BKPT;
drh4eec4c12005-01-21 00:22:37 +00003311 }
drhda200cc2004-05-09 11:51:38 +00003312 pageIntegrity(pPage);
drh72f82862001-05-24 21:06:34 +00003313 while( lwr<=upr ){
danielk197713adf8a2004-06-03 16:08:41 +00003314 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00003315 i64 nCellKey;
drh72f82862001-05-24 21:06:34 +00003316 pCur->idx = (lwr+upr)/2;
drh271efa52004-05-30 19:19:05 +00003317 pCur->info.nSize = 0;
drhde647132004-05-07 17:57:49 +00003318 sqlite3BtreeKeySize(pCur, &nCellKey);
drh3aac2dd2004-04-26 14:10:20 +00003319 if( pPage->intKey ){
3320 if( nCellKey<nKey ){
3321 c = -1;
3322 }else if( nCellKey>nKey ){
3323 c = +1;
3324 }else{
3325 c = 0;
3326 }
drh3aac2dd2004-04-26 14:10:20 +00003327 }else{
drhe51c44f2004-05-30 20:46:09 +00003328 int available;
danielk197713adf8a2004-06-03 16:08:41 +00003329 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drhe51c44f2004-05-30 20:46:09 +00003330 if( available>=nCellKey ){
3331 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
3332 }else{
3333 pCellKey = sqliteMallocRaw( nCellKey );
3334 if( pCellKey==0 ) return SQLITE_NOMEM;
danielk197713adf8a2004-06-03 16:08:41 +00003335 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
drhe51c44f2004-05-30 20:46:09 +00003336 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
3337 sqliteFree(pCellKey);
3338 if( rc ) return rc;
3339 }
drh3aac2dd2004-04-26 14:10:20 +00003340 }
drh72f82862001-05-24 21:06:34 +00003341 if( c==0 ){
drh8b18dd42004-05-12 19:18:15 +00003342 if( pPage->leafData && !pPage->leaf ){
drhfc70e6f2004-05-12 21:11:27 +00003343 lwr = pCur->idx;
3344 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00003345 break;
3346 }else{
drh8b18dd42004-05-12 19:18:15 +00003347 if( pRes ) *pRes = 0;
3348 return SQLITE_OK;
3349 }
drh72f82862001-05-24 21:06:34 +00003350 }
3351 if( c<0 ){
3352 lwr = pCur->idx+1;
3353 }else{
3354 upr = pCur->idx-1;
3355 }
3356 }
3357 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00003358 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00003359 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00003360 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00003361 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00003362 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00003363 }else{
drh43605152004-05-29 21:46:49 +00003364 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00003365 }
3366 if( chldPg==0 ){
drhc39e0002004-05-07 23:50:57 +00003367 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00003368 if( pRes ) *pRes = c;
3369 return SQLITE_OK;
3370 }
drh428ae8c2003-01-04 16:48:09 +00003371 pCur->idx = lwr;
drh271efa52004-05-30 19:19:05 +00003372 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00003373 rc = moveToChild(pCur, chldPg);
drhc39e0002004-05-07 23:50:57 +00003374 if( rc ){
3375 return rc;
3376 }
drh72f82862001-05-24 21:06:34 +00003377 }
drhbd03cae2001-06-02 02:40:57 +00003378 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00003379}
3380
3381/*
drhc39e0002004-05-07 23:50:57 +00003382** Return TRUE if the cursor is not pointing at an entry of the table.
3383**
3384** TRUE will be returned after a call to sqlite3BtreeNext() moves
3385** past the last entry in the table or sqlite3BtreePrev() moves past
3386** the first entry. TRUE is also returned if the table is empty.
3387*/
3388int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00003389 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
3390 ** have been deleted? This API will need to change to return an error code
3391 ** as well as the boolean result value.
3392 */
3393 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00003394}
3395
3396/*
drhbd03cae2001-06-02 02:40:57 +00003397** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00003398** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00003399** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00003400** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00003401*/
drh3aac2dd2004-04-26 14:10:20 +00003402int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00003403 int rc;
drh8178a752003-01-05 21:41:40 +00003404 MemPage *pPage = pCur->pPage;
drh8b18dd42004-05-12 19:18:15 +00003405
danielk1977da184232006-01-05 11:34:32 +00003406#ifndef SQLITE_OMIT_SHARED_CACHE
3407 rc = restoreCursorPosition(pCur, 1);
3408 if( rc!=SQLITE_OK ){
3409 return rc;
3410 }
3411 if( pCur->skip>0 ){
3412 pCur->skip = 0;
3413 *pRes = 0;
3414 return SQLITE_OK;
3415 }
3416 pCur->skip = 0;
3417#endif
3418
drh8c1238a2003-01-02 14:43:55 +00003419 assert( pRes!=0 );
danielk1977da184232006-01-05 11:34:32 +00003420 if( CURSOR_INVALID==pCur->eState ){
drh8c1238a2003-01-02 14:43:55 +00003421 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00003422 return SQLITE_OK;
drhecdc7532001-09-23 02:35:53 +00003423 }
drh8178a752003-01-05 21:41:40 +00003424 assert( pPage->isInit );
drh8178a752003-01-05 21:41:40 +00003425 assert( pCur->idx<pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00003426
drh72f82862001-05-24 21:06:34 +00003427 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00003428 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00003429 if( pCur->idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00003430 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003431 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00003432 if( rc ) return rc;
3433 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003434 *pRes = 0;
3435 return rc;
drh72f82862001-05-24 21:06:34 +00003436 }
drh5e2f8b92001-05-28 00:41:15 +00003437 do{
drh8856d6a2004-04-29 14:42:46 +00003438 if( isRootPage(pPage) ){
drh8c1238a2003-01-02 14:43:55 +00003439 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00003440 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00003441 return SQLITE_OK;
3442 }
drh8178a752003-01-05 21:41:40 +00003443 moveToParent(pCur);
3444 pPage = pCur->pPage;
3445 }while( pCur->idx>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00003446 *pRes = 0;
drh8b18dd42004-05-12 19:18:15 +00003447 if( pPage->leafData ){
3448 rc = sqlite3BtreeNext(pCur, pRes);
3449 }else{
3450 rc = SQLITE_OK;
3451 }
3452 return rc;
drh8178a752003-01-05 21:41:40 +00003453 }
3454 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00003455 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00003456 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00003457 }
drh5e2f8b92001-05-28 00:41:15 +00003458 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003459 return rc;
drh72f82862001-05-24 21:06:34 +00003460}
3461
drh3b7511c2001-05-26 13:15:44 +00003462/*
drh2dcc9aa2002-12-04 13:40:25 +00003463** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00003464** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00003465** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00003466** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00003467*/
drh3aac2dd2004-04-26 14:10:20 +00003468int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00003469 int rc;
3470 Pgno pgno;
drh8178a752003-01-05 21:41:40 +00003471 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00003472
3473#ifndef SQLITE_OMIT_SHARED_CACHE
3474 rc = restoreCursorPosition(pCur, 1);
3475 if( rc!=SQLITE_OK ){
3476 return rc;
3477 }
3478 if( pCur->skip<0 ){
3479 pCur->skip = 0;
3480 *pRes = 0;
3481 return SQLITE_OK;
3482 }
3483 pCur->skip = 0;
3484#endif
3485
3486 if( CURSOR_INVALID==pCur->eState ){
drhc39e0002004-05-07 23:50:57 +00003487 *pRes = 1;
3488 return SQLITE_OK;
3489 }
danielk19776a43f9b2004-11-16 04:57:24 +00003490
drh8178a752003-01-05 21:41:40 +00003491 pPage = pCur->pPage;
drh8178a752003-01-05 21:41:40 +00003492 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00003493 assert( pCur->idx>=0 );
drha34b6762004-05-07 13:30:42 +00003494 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003495 pgno = get4byte( findCell(pPage, pCur->idx) );
drh8178a752003-01-05 21:41:40 +00003496 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003497 if( rc ) return rc;
3498 rc = moveToRightmost(pCur);
3499 }else{
3500 while( pCur->idx==0 ){
drh8856d6a2004-04-29 14:42:46 +00003501 if( isRootPage(pPage) ){
danielk1977da184232006-01-05 11:34:32 +00003502 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00003503 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00003504 return SQLITE_OK;
3505 }
drh8178a752003-01-05 21:41:40 +00003506 moveToParent(pCur);
3507 pPage = pCur->pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003508 }
3509 pCur->idx--;
drh271efa52004-05-30 19:19:05 +00003510 pCur->info.nSize = 0;
drh8237d452004-11-22 19:07:09 +00003511 if( pPage->leafData && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00003512 rc = sqlite3BtreePrevious(pCur, pRes);
3513 }else{
3514 rc = SQLITE_OK;
3515 }
drh2dcc9aa2002-12-04 13:40:25 +00003516 }
drh8178a752003-01-05 21:41:40 +00003517 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003518 return rc;
3519}
3520
3521/*
drh3b7511c2001-05-26 13:15:44 +00003522** Allocate a new page from the database file.
3523**
drha34b6762004-05-07 13:30:42 +00003524** The new page is marked as dirty. (In other words, sqlite3pager_write()
drh3b7511c2001-05-26 13:15:44 +00003525** has already been called on the new page.) The new page has also
3526** been referenced and the calling routine is responsible for calling
drha34b6762004-05-07 13:30:42 +00003527** sqlite3pager_unref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00003528**
3529** SQLITE_OK is returned on success. Any other return value indicates
3530** an error. *ppPage and *pPgno are undefined in the event of an error.
drha34b6762004-05-07 13:30:42 +00003531** Do not invoke sqlite3pager_unref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00003532**
drh199e3cf2002-07-18 11:01:47 +00003533** If the "nearby" parameter is not 0, then a (feeble) effort is made to
3534** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00003535** attempt to keep related pages close to each other in the database file,
3536** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00003537**
3538** If the "exact" parameter is not 0, and the page-number nearby exists
3539** anywhere on the free-list, then it is guarenteed to be returned. This
3540** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00003541*/
danielk1977cb1a7eb2004-11-05 12:27:02 +00003542static int allocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00003543 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00003544 MemPage **ppPage,
3545 Pgno *pPgno,
3546 Pgno nearby,
3547 u8 exact
3548){
drh3aac2dd2004-04-26 14:10:20 +00003549 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00003550 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003551 int n; /* Number of pages on the freelist */
3552 int k; /* Number of leaves on the trunk of the freelist */
drh30e58752002-03-02 20:41:57 +00003553
drh3aac2dd2004-04-26 14:10:20 +00003554 pPage1 = pBt->pPage1;
3555 n = get4byte(&pPage1->aData[36]);
3556 if( n>0 ){
drh91025292004-05-03 19:49:32 +00003557 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00003558 MemPage *pTrunk = 0;
3559 Pgno iTrunk;
3560 MemPage *pPrevTrunk = 0;
3561 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
3562
3563 /* If the 'exact' parameter was true and a query of the pointer-map
3564 ** shows that the page 'nearby' is somewhere on the free-list, then
3565 ** the entire-list will be searched for that page.
3566 */
3567#ifndef SQLITE_OMIT_AUTOVACUUM
3568 if( exact ){
3569 u8 eType;
3570 assert( nearby>0 );
3571 assert( pBt->autoVacuum );
3572 rc = ptrmapGet(pBt, nearby, &eType, 0);
3573 if( rc ) return rc;
3574 if( eType==PTRMAP_FREEPAGE ){
3575 searchList = 1;
3576 }
3577 *pPgno = nearby;
3578 }
3579#endif
3580
3581 /* Decrement the free-list count by 1. Set iTrunk to the index of the
3582 ** first free-list trunk page. iPrevTrunk is initially 1.
3583 */
drha34b6762004-05-07 13:30:42 +00003584 rc = sqlite3pager_write(pPage1->aData);
drh3b7511c2001-05-26 13:15:44 +00003585 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003586 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003587
3588 /* The code within this loop is run only once if the 'searchList' variable
3589 ** is not true. Otherwise, it runs once for each trunk-page on the
3590 ** free-list until the page 'nearby' is located.
3591 */
3592 do {
3593 pPrevTrunk = pTrunk;
3594 if( pPrevTrunk ){
3595 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00003596 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00003597 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00003598 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003599 rc = getPage(pBt, iTrunk, &pTrunk);
3600 if( rc ){
3601 releasePage(pPrevTrunk);
3602 return rc;
3603 }
3604
3605 /* TODO: This should move to after the loop? */
3606 rc = sqlite3pager_write(pTrunk->aData);
3607 if( rc ){
3608 releasePage(pTrunk);
3609 releasePage(pPrevTrunk);
3610 return rc;
3611 }
3612
3613 k = get4byte(&pTrunk->aData[4]);
3614 if( k==0 && !searchList ){
3615 /* The trunk has no leaves and the list is not being searched.
3616 ** So extract the trunk page itself and use it as the newly
3617 ** allocated page */
3618 assert( pPrevTrunk==0 );
3619 *pPgno = iTrunk;
3620 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3621 *ppPage = pTrunk;
3622 pTrunk = 0;
3623 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3624 }else if( k>pBt->usableSize/4 - 8 ){
3625 /* Value of k is out of range. Database corruption */
drh49285702005-09-17 15:20:26 +00003626 return SQLITE_CORRUPT_BKPT;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003627#ifndef SQLITE_OMIT_AUTOVACUUM
3628 }else if( searchList && nearby==iTrunk ){
3629 /* The list is being searched and this trunk page is the page
3630 ** to allocate, regardless of whether it has leaves.
3631 */
3632 assert( *pPgno==iTrunk );
3633 *ppPage = pTrunk;
3634 searchList = 0;
3635 if( k==0 ){
3636 if( !pPrevTrunk ){
3637 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3638 }else{
3639 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
3640 }
3641 }else{
3642 /* The trunk page is required by the caller but it contains
3643 ** pointers to free-list leaves. The first leaf becomes a trunk
3644 ** page in this case.
3645 */
3646 MemPage *pNewTrunk;
3647 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
3648 rc = getPage(pBt, iNewTrunk, &pNewTrunk);
3649 if( rc!=SQLITE_OK ){
3650 releasePage(pTrunk);
3651 releasePage(pPrevTrunk);
3652 return rc;
3653 }
3654 rc = sqlite3pager_write(pNewTrunk->aData);
3655 if( rc!=SQLITE_OK ){
3656 releasePage(pNewTrunk);
3657 releasePage(pTrunk);
3658 releasePage(pPrevTrunk);
3659 return rc;
3660 }
3661 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
3662 put4byte(&pNewTrunk->aData[4], k-1);
3663 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
3664 if( !pPrevTrunk ){
3665 put4byte(&pPage1->aData[32], iNewTrunk);
3666 }else{
3667 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
3668 }
3669 releasePage(pNewTrunk);
3670 }
3671 pTrunk = 0;
3672 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3673#endif
3674 }else{
3675 /* Extract a leaf from the trunk */
3676 int closest;
3677 Pgno iPage;
3678 unsigned char *aData = pTrunk->aData;
3679 if( nearby>0 ){
3680 int i, dist;
3681 closest = 0;
3682 dist = get4byte(&aData[8]) - nearby;
3683 if( dist<0 ) dist = -dist;
3684 for(i=1; i<k; i++){
3685 int d2 = get4byte(&aData[8+i*4]) - nearby;
3686 if( d2<0 ) d2 = -d2;
3687 if( d2<dist ){
3688 closest = i;
3689 dist = d2;
3690 }
3691 }
3692 }else{
3693 closest = 0;
3694 }
3695
3696 iPage = get4byte(&aData[8+closest*4]);
3697 if( !searchList || iPage==nearby ){
3698 *pPgno = iPage;
3699 if( *pPgno>sqlite3pager_pagecount(pBt->pPager) ){
3700 /* Free page off the end of the file */
drh49285702005-09-17 15:20:26 +00003701 return SQLITE_CORRUPT_BKPT;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003702 }
3703 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
3704 ": %d more free pages\n",
3705 *pPgno, closest+1, k, pTrunk->pgno, n-1));
3706 if( closest<k-1 ){
3707 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
3708 }
3709 put4byte(&aData[4], k-1);
3710 rc = getPage(pBt, *pPgno, ppPage);
3711 if( rc==SQLITE_OK ){
3712 sqlite3pager_dont_rollback((*ppPage)->aData);
3713 rc = sqlite3pager_write((*ppPage)->aData);
danielk1977aac0a382005-01-16 11:07:06 +00003714 if( rc!=SQLITE_OK ){
3715 releasePage(*ppPage);
3716 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003717 }
3718 searchList = 0;
3719 }
drhee696e22004-08-30 16:52:17 +00003720 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003721 releasePage(pPrevTrunk);
3722 }while( searchList );
3723 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003724 }else{
drh3aac2dd2004-04-26 14:10:20 +00003725 /* There are no pages on the freelist, so create a new page at the
3726 ** end of the file */
drha34b6762004-05-07 13:30:42 +00003727 *pPgno = sqlite3pager_pagecount(pBt->pPager) + 1;
danielk1977afcdd022004-10-31 16:25:42 +00003728
3729#ifndef SQLITE_OMIT_AUTOVACUUM
drh42cac6d2004-11-20 20:31:11 +00003730 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt->usableSize, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00003731 /* If *pPgno refers to a pointer-map page, allocate two new pages
3732 ** at the end of the file instead of one. The first allocated page
3733 ** becomes a new pointer-map page, the second is used by the caller.
3734 */
3735 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00003736 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977afcdd022004-10-31 16:25:42 +00003737 (*pPgno)++;
3738 }
3739#endif
3740
danielk1977599fcba2004-11-08 07:13:13 +00003741 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00003742 rc = getPage(pBt, *pPgno, ppPage);
drh3b7511c2001-05-26 13:15:44 +00003743 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003744 rc = sqlite3pager_write((*ppPage)->aData);
danielk1977aac0a382005-01-16 11:07:06 +00003745 if( rc!=SQLITE_OK ){
3746 releasePage(*ppPage);
3747 }
drh3a4c1412004-05-09 20:40:11 +00003748 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00003749 }
danielk1977599fcba2004-11-08 07:13:13 +00003750
3751 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh3b7511c2001-05-26 13:15:44 +00003752 return rc;
3753}
3754
3755/*
drh3aac2dd2004-04-26 14:10:20 +00003756** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00003757**
drha34b6762004-05-07 13:30:42 +00003758** sqlite3pager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00003759*/
drh3aac2dd2004-04-26 14:10:20 +00003760static int freePage(MemPage *pPage){
danielk1977aef0bf62005-12-30 16:28:01 +00003761 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00003762 MemPage *pPage1 = pBt->pPage1;
3763 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00003764
drh3aac2dd2004-04-26 14:10:20 +00003765 /* Prepare the page for freeing */
3766 assert( pPage->pgno>1 );
3767 pPage->isInit = 0;
3768 releasePage(pPage->pParent);
3769 pPage->pParent = 0;
3770
drha34b6762004-05-07 13:30:42 +00003771 /* Increment the free page count on pPage1 */
3772 rc = sqlite3pager_write(pPage1->aData);
drh3aac2dd2004-04-26 14:10:20 +00003773 if( rc ) return rc;
3774 n = get4byte(&pPage1->aData[36]);
3775 put4byte(&pPage1->aData[36], n+1);
3776
danielk1977687566d2004-11-02 12:56:41 +00003777#ifndef SQLITE_OMIT_AUTOVACUUM
3778 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00003779 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00003780 */
3781 if( pBt->autoVacuum ){
3782 rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
danielk1977a64a0352004-11-05 01:45:13 +00003783 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00003784 }
3785#endif
3786
drh3aac2dd2004-04-26 14:10:20 +00003787 if( n==0 ){
3788 /* This is the first free page */
drhda200cc2004-05-09 11:51:38 +00003789 rc = sqlite3pager_write(pPage->aData);
3790 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003791 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00003792 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003793 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003794 }else{
3795 /* Other free pages already exist. Retrive the first trunk page
3796 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00003797 MemPage *pTrunk;
3798 rc = getPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003799 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003800 k = get4byte(&pTrunk->aData[4]);
drhee696e22004-08-30 16:52:17 +00003801 if( k>=pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00003802 /* The trunk is full. Turn the page being freed into a new
3803 ** trunk page with no leaves. */
drha34b6762004-05-07 13:30:42 +00003804 rc = sqlite3pager_write(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00003805 if( rc ) return rc;
3806 put4byte(pPage->aData, pTrunk->pgno);
3807 put4byte(&pPage->aData[4], 0);
3808 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003809 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
3810 pPage->pgno, pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003811 }else{
3812 /* Add the newly freed page as a leaf on the current trunk */
drha34b6762004-05-07 13:30:42 +00003813 rc = sqlite3pager_write(pTrunk->aData);
drh3aac2dd2004-04-26 14:10:20 +00003814 if( rc ) return rc;
3815 put4byte(&pTrunk->aData[4], k+1);
3816 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drha34b6762004-05-07 13:30:42 +00003817 sqlite3pager_dont_write(pBt->pPager, pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003818 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003819 }
3820 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003821 }
drh3b7511c2001-05-26 13:15:44 +00003822 return rc;
3823}
3824
3825/*
drh3aac2dd2004-04-26 14:10:20 +00003826** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00003827*/
drh3aac2dd2004-04-26 14:10:20 +00003828static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00003829 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00003830 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00003831 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00003832 int rc;
drh3b7511c2001-05-26 13:15:44 +00003833
drh43605152004-05-29 21:46:49 +00003834 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003835 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00003836 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00003837 }
drh6f11bef2004-05-13 01:12:56 +00003838 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh3aac2dd2004-04-26 14:10:20 +00003839 while( ovflPgno!=0 ){
3840 MemPage *pOvfl;
danielk1977a1cb1832005-02-12 08:59:55 +00003841 if( ovflPgno>sqlite3pager_pagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00003842 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00003843 }
drh3aac2dd2004-04-26 14:10:20 +00003844 rc = getPage(pBt, ovflPgno, &pOvfl);
drh3b7511c2001-05-26 13:15:44 +00003845 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003846 ovflPgno = get4byte(pOvfl->aData);
drha34b6762004-05-07 13:30:42 +00003847 rc = freePage(pOvfl);
drha34b6762004-05-07 13:30:42 +00003848 sqlite3pager_unref(pOvfl->aData);
danielk19776b456a22005-03-21 04:04:02 +00003849 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00003850 }
drh5e2f8b92001-05-28 00:41:15 +00003851 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00003852}
3853
3854/*
drh91025292004-05-03 19:49:32 +00003855** Create the byte sequence used to represent a cell on page pPage
3856** and write that byte sequence into pCell[]. Overflow pages are
3857** allocated and filled in as necessary. The calling procedure
3858** is responsible for making sure sufficient space has been allocated
3859** for pCell[].
3860**
3861** Note that pCell does not necessary need to point to the pPage->aData
3862** area. pCell might point to some temporary storage. The cell will
3863** be constructed in this temporary area then copied into pPage->aData
3864** later.
drh3b7511c2001-05-26 13:15:44 +00003865*/
3866static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00003867 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00003868 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00003869 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00003870 const void *pData,int nData, /* The data */
3871 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00003872){
drh3b7511c2001-05-26 13:15:44 +00003873 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00003874 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00003875 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00003876 int spaceLeft;
3877 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00003878 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00003879 unsigned char *pPrior;
3880 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00003881 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00003882 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00003883 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00003884 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00003885
drh91025292004-05-03 19:49:32 +00003886 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00003887 nHeader = 0;
drh91025292004-05-03 19:49:32 +00003888 if( !pPage->leaf ){
3889 nHeader += 4;
3890 }
drh8b18dd42004-05-12 19:18:15 +00003891 if( pPage->hasData ){
drh91025292004-05-03 19:49:32 +00003892 nHeader += putVarint(&pCell[nHeader], nData);
drh6f11bef2004-05-13 01:12:56 +00003893 }else{
drh91025292004-05-03 19:49:32 +00003894 nData = 0;
3895 }
drh6f11bef2004-05-13 01:12:56 +00003896 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh43605152004-05-29 21:46:49 +00003897 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003898 assert( info.nHeader==nHeader );
3899 assert( info.nKey==nKey );
3900 assert( info.nData==nData );
3901
3902 /* Fill in the payload */
drh3aac2dd2004-04-26 14:10:20 +00003903 nPayload = nData;
3904 if( pPage->intKey ){
3905 pSrc = pData;
3906 nSrc = nData;
drh91025292004-05-03 19:49:32 +00003907 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00003908 }else{
3909 nPayload += nKey;
3910 pSrc = pKey;
3911 nSrc = nKey;
3912 }
drh6f11bef2004-05-13 01:12:56 +00003913 *pnSize = info.nSize;
3914 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00003915 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00003916 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00003917
drh3b7511c2001-05-26 13:15:44 +00003918 while( nPayload>0 ){
3919 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00003920#ifndef SQLITE_OMIT_AUTOVACUUM
3921 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
3922#endif
danielk1977cb1a7eb2004-11-05 12:27:02 +00003923 rc = allocatePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00003924#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00003925 /* If the database supports auto-vacuum, and the second or subsequent
3926 ** overflow page is being allocated, add an entry to the pointer-map
3927 ** for that page now. The entry for the first overflow page will be
3928 ** added later, by the insertCell() routine.
danielk1977afcdd022004-10-31 16:25:42 +00003929 */
danielk1977a19df672004-11-03 11:37:07 +00003930 if( pBt->autoVacuum && pgnoPtrmap!=0 && rc==SQLITE_OK ){
3931 rc = ptrmapPut(pBt, pgnoOvfl, PTRMAP_OVERFLOW2, pgnoPtrmap);
danielk1977afcdd022004-10-31 16:25:42 +00003932 }
3933#endif
drh3b7511c2001-05-26 13:15:44 +00003934 if( rc ){
drh9b171272004-05-08 02:03:22 +00003935 releasePage(pToRelease);
danielk197728129562005-01-11 10:25:06 +00003936 /* clearCell(pPage, pCell); */
drh3b7511c2001-05-26 13:15:44 +00003937 return rc;
3938 }
drh3aac2dd2004-04-26 14:10:20 +00003939 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00003940 releasePage(pToRelease);
3941 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00003942 pPrior = pOvfl->aData;
3943 put4byte(pPrior, 0);
3944 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00003945 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00003946 }
3947 n = nPayload;
3948 if( n>spaceLeft ) n = spaceLeft;
drh3aac2dd2004-04-26 14:10:20 +00003949 if( n>nSrc ) n = nSrc;
3950 memcpy(pPayload, pSrc, n);
drh3b7511c2001-05-26 13:15:44 +00003951 nPayload -= n;
drhde647132004-05-07 17:57:49 +00003952 pPayload += n;
drh9b171272004-05-08 02:03:22 +00003953 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00003954 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00003955 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00003956 if( nSrc==0 ){
3957 nSrc = nData;
3958 pSrc = pData;
3959 }
drhdd793422001-06-28 01:54:48 +00003960 }
drh9b171272004-05-08 02:03:22 +00003961 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00003962 return SQLITE_OK;
3963}
3964
3965/*
drhbd03cae2001-06-02 02:40:57 +00003966** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00003967** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00003968** pointer in the third argument.
3969*/
danielk1977aef0bf62005-12-30 16:28:01 +00003970static int reparentPage(BtShared *pBt, Pgno pgno, MemPage *pNewParent, int idx){
drhbd03cae2001-06-02 02:40:57 +00003971 MemPage *pThis;
drh4b70f112004-05-02 21:12:19 +00003972 unsigned char *aData;
drhbd03cae2001-06-02 02:40:57 +00003973
danielk1977afcdd022004-10-31 16:25:42 +00003974 if( pgno==0 ) return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00003975 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00003976 aData = sqlite3pager_lookup(pBt->pPager, pgno);
drhda200cc2004-05-09 11:51:38 +00003977 if( aData ){
drh07d183d2005-05-01 22:52:42 +00003978 pThis = (MemPage*)&aData[pBt->pageSize];
drh31276532004-09-27 12:20:52 +00003979 assert( pThis->aData==aData );
drhda200cc2004-05-09 11:51:38 +00003980 if( pThis->isInit ){
3981 if( pThis->pParent!=pNewParent ){
3982 if( pThis->pParent ) sqlite3pager_unref(pThis->pParent->aData);
3983 pThis->pParent = pNewParent;
3984 if( pNewParent ) sqlite3pager_ref(pNewParent->aData);
3985 }
3986 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00003987 }
drha34b6762004-05-07 13:30:42 +00003988 sqlite3pager_unref(aData);
drhbd03cae2001-06-02 02:40:57 +00003989 }
danielk1977afcdd022004-10-31 16:25:42 +00003990
3991#ifndef SQLITE_OMIT_AUTOVACUUM
3992 if( pBt->autoVacuum ){
3993 return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
3994 }
3995#endif
3996 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00003997}
3998
danielk1977ac11ee62005-01-15 12:45:51 +00003999
4000
drhbd03cae2001-06-02 02:40:57 +00004001/*
drh4b70f112004-05-02 21:12:19 +00004002** Change the pParent pointer of all children of pPage to point back
4003** to pPage.
4004**
drhbd03cae2001-06-02 02:40:57 +00004005** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00004006** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00004007**
4008** This routine gets called after you memcpy() one page into
4009** another.
4010*/
danielk1977afcdd022004-10-31 16:25:42 +00004011static int reparentChildPages(MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00004012 int i;
danielk1977aef0bf62005-12-30 16:28:01 +00004013 BtShared *pBt = pPage->pBt;
danielk1977afcdd022004-10-31 16:25:42 +00004014 int rc = SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00004015
danielk1977afcdd022004-10-31 16:25:42 +00004016 if( pPage->leaf ) return SQLITE_OK;
danielk1977afcdd022004-10-31 16:25:42 +00004017
drhbd03cae2001-06-02 02:40:57 +00004018 for(i=0; i<pPage->nCell; i++){
danielk1977afcdd022004-10-31 16:25:42 +00004019 u8 *pCell = findCell(pPage, i);
4020 if( !pPage->leaf ){
4021 rc = reparentPage(pBt, get4byte(pCell), pPage, i);
4022 if( rc!=SQLITE_OK ) return rc;
4023 }
drhbd03cae2001-06-02 02:40:57 +00004024 }
danielk1977afcdd022004-10-31 16:25:42 +00004025 if( !pPage->leaf ){
4026 rc = reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]),
4027 pPage, i);
4028 pPage->idxShift = 0;
4029 }
4030 return rc;
drh14acc042001-06-10 19:56:58 +00004031}
4032
4033/*
4034** Remove the i-th cell from pPage. This routine effects pPage only.
4035** The cell content is not freed or deallocated. It is assumed that
4036** the cell content has been copied someplace else. This routine just
4037** removes the reference to the cell from pPage.
4038**
4039** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00004040*/
drh4b70f112004-05-02 21:12:19 +00004041static void dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00004042 int i; /* Loop counter */
4043 int pc; /* Offset to cell content of cell being deleted */
4044 u8 *data; /* pPage->aData */
4045 u8 *ptr; /* Used to move bytes around within data[] */
4046
drh8c42ca92001-06-22 19:15:00 +00004047 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00004048 assert( sz==cellSize(pPage, idx) );
drha34b6762004-05-07 13:30:42 +00004049 assert( sqlite3pager_iswriteable(pPage->aData) );
drhda200cc2004-05-09 11:51:38 +00004050 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00004051 ptr = &data[pPage->cellOffset + 2*idx];
4052 pc = get2byte(ptr);
4053 assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
drhde647132004-05-07 17:57:49 +00004054 freeSpace(pPage, pc, sz);
drh43605152004-05-29 21:46:49 +00004055 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
4056 ptr[0] = ptr[2];
4057 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00004058 }
4059 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00004060 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
4061 pPage->nFree += 2;
drh428ae8c2003-01-04 16:48:09 +00004062 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00004063}
4064
4065/*
4066** Insert a new cell on pPage at cell index "i". pCell points to the
4067** content of the cell.
4068**
4069** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00004070** will not fit, then make a copy of the cell content into pTemp if
4071** pTemp is not null. Regardless of pTemp, allocate a new entry
4072** in pPage->aOvfl[] and make it point to the cell content (either
4073** in pTemp or the original pCell) and also record its index.
4074** Allocating a new entry in pPage->aCell[] implies that
4075** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00004076**
4077** If nSkip is non-zero, then do not copy the first nSkip bytes of the
4078** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00004079** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00004080** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00004081*/
danielk1977e80463b2004-11-03 03:01:16 +00004082static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00004083 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00004084 int i, /* New cell becomes the i-th cell of the page */
4085 u8 *pCell, /* Content of the new cell */
4086 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00004087 u8 *pTemp, /* Temp storage space for pCell, if needed */
4088 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00004089){
drh43605152004-05-29 21:46:49 +00004090 int idx; /* Where to write new cell content in data[] */
4091 int j; /* Loop counter */
4092 int top; /* First byte of content for any cell in data[] */
4093 int end; /* First byte past the last cell pointer in data[] */
4094 int ins; /* Index in data[] where new cell pointer is inserted */
4095 int hdr; /* Offset into data[] of the page header */
4096 int cellOffset; /* Address of first cell pointer in data[] */
4097 u8 *data; /* The content of the whole page */
4098 u8 *ptr; /* Used for moving information around in data[] */
4099
4100 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
4101 assert( sz==cellSizePtr(pPage, pCell) );
drha34b6762004-05-07 13:30:42 +00004102 assert( sqlite3pager_iswriteable(pPage->aData) );
drh43605152004-05-29 21:46:49 +00004103 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00004104 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00004105 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004106 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00004107 }
drh43605152004-05-29 21:46:49 +00004108 j = pPage->nOverflow++;
4109 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
4110 pPage->aOvfl[j].pCell = pCell;
4111 pPage->aOvfl[j].idx = i;
4112 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00004113 }else{
drh43605152004-05-29 21:46:49 +00004114 data = pPage->aData;
4115 hdr = pPage->hdrOffset;
4116 top = get2byte(&data[hdr+5]);
4117 cellOffset = pPage->cellOffset;
4118 end = cellOffset + 2*pPage->nCell + 2;
4119 ins = cellOffset + 2*i;
4120 if( end > top - sz ){
danielk19776b456a22005-03-21 04:04:02 +00004121 int rc = defragmentPage(pPage);
4122 if( rc!=SQLITE_OK ) return rc;
drh43605152004-05-29 21:46:49 +00004123 top = get2byte(&data[hdr+5]);
4124 assert( end + sz <= top );
4125 }
4126 idx = allocateSpace(pPage, sz);
4127 assert( idx>0 );
4128 assert( end <= get2byte(&data[hdr+5]) );
4129 pPage->nCell++;
4130 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00004131 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004132 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
4133 ptr[0] = ptr[-2];
4134 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00004135 }
drh43605152004-05-29 21:46:49 +00004136 put2byte(&data[ins], idx);
4137 put2byte(&data[hdr+3], pPage->nCell);
4138 pPage->idxShift = 1;
drhda200cc2004-05-09 11:51:38 +00004139 pageIntegrity(pPage);
danielk1977a19df672004-11-03 11:37:07 +00004140#ifndef SQLITE_OMIT_AUTOVACUUM
4141 if( pPage->pBt->autoVacuum ){
4142 /* The cell may contain a pointer to an overflow page. If so, write
4143 ** the entry for the overflow page into the pointer map.
4144 */
4145 CellInfo info;
4146 parseCellPtr(pPage, pCell, &info);
4147 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
4148 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
4149 int rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
4150 if( rc!=SQLITE_OK ) return rc;
4151 }
4152 }
4153#endif
drh14acc042001-06-10 19:56:58 +00004154 }
danielk1977e80463b2004-11-03 03:01:16 +00004155
danielk1977e80463b2004-11-03 03:01:16 +00004156 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004157}
4158
4159/*
drhfa1a98a2004-05-14 19:08:17 +00004160** Add a list of cells to a page. The page should be initially empty.
4161** The cells are guaranteed to fit on the page.
4162*/
4163static void assemblePage(
4164 MemPage *pPage, /* The page to be assemblied */
4165 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00004166 u8 **apCell, /* Pointers to cell bodies */
drhfa1a98a2004-05-14 19:08:17 +00004167 int *aSize /* Sizes of the cells */
4168){
4169 int i; /* Loop counter */
4170 int totalSize; /* Total size of all cells */
4171 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00004172 int cellptr; /* Address of next cell pointer */
4173 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00004174 u8 *data; /* Data for the page */
4175
drh43605152004-05-29 21:46:49 +00004176 assert( pPage->nOverflow==0 );
drhfa1a98a2004-05-14 19:08:17 +00004177 totalSize = 0;
4178 for(i=0; i<nCell; i++){
4179 totalSize += aSize[i];
4180 }
drh43605152004-05-29 21:46:49 +00004181 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00004182 assert( pPage->nCell==0 );
drh43605152004-05-29 21:46:49 +00004183 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00004184 data = pPage->aData;
4185 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00004186 put2byte(&data[hdr+3], nCell);
drh09d0deb2005-08-02 17:13:09 +00004187 if( nCell ){
4188 cellbody = allocateSpace(pPage, totalSize);
4189 assert( cellbody>0 );
4190 assert( pPage->nFree >= 2*nCell );
4191 pPage->nFree -= 2*nCell;
4192 for(i=0; i<nCell; i++){
4193 put2byte(&data[cellptr], cellbody);
4194 memcpy(&data[cellbody], apCell[i], aSize[i]);
4195 cellptr += 2;
4196 cellbody += aSize[i];
4197 }
4198 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00004199 }
4200 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00004201}
4202
drh14acc042001-06-10 19:56:58 +00004203/*
drhc3b70572003-01-04 19:44:07 +00004204** The following parameters determine how many adjacent pages get involved
4205** in a balancing operation. NN is the number of neighbors on either side
4206** of the page that participate in the balancing operation. NB is the
4207** total number of pages that participate, including the target page and
4208** NN neighbors on either side.
4209**
4210** The minimum value of NN is 1 (of course). Increasing NN above 1
4211** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
4212** in exchange for a larger degradation in INSERT and UPDATE performance.
4213** The value of NN appears to give the best results overall.
4214*/
4215#define NN 1 /* Number of neighbors on either side of pPage */
4216#define NB (NN*2+1) /* Total pages involved in the balance */
4217
drh43605152004-05-29 21:46:49 +00004218/* Forward reference */
danielk1977ac245ec2005-01-14 13:50:11 +00004219static int balance(MemPage*, int);
4220
drh615ae552005-01-16 23:21:00 +00004221#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004222/*
4223** This version of balance() handles the common special case where
4224** a new entry is being inserted on the extreme right-end of the
4225** tree, in other words, when the new entry will become the largest
4226** entry in the tree.
4227**
4228** Instead of trying balance the 3 right-most leaf pages, just add
4229** a new page to the right-hand side and put the one new entry in
4230** that page. This leaves the right side of the tree somewhat
4231** unbalanced. But odds are that we will be inserting new entries
4232** at the end soon afterwards so the nearly empty page will quickly
4233** fill up. On average.
4234**
4235** pPage is the leaf page which is the right-most page in the tree.
4236** pParent is its parent. pPage must have a single overflow entry
4237** which is also the right-most entry on the page.
4238*/
danielk1977ac245ec2005-01-14 13:50:11 +00004239static int balance_quick(MemPage *pPage, MemPage *pParent){
4240 int rc;
4241 MemPage *pNew;
4242 Pgno pgnoNew;
4243 u8 *pCell;
4244 int szCell;
4245 CellInfo info;
danielk1977aef0bf62005-12-30 16:28:01 +00004246 BtShared *pBt = pPage->pBt;
danielk197779a40da2005-01-16 08:00:01 +00004247 int parentIdx = pParent->nCell; /* pParent new divider cell index */
4248 int parentSize; /* Size of new divider cell */
4249 u8 parentCell[64]; /* Space for the new divider cell */
danielk1977ac245ec2005-01-14 13:50:11 +00004250
4251 /* Allocate a new page. Insert the overflow cell from pPage
4252 ** into it. Then remove the overflow cell from pPage.
4253 */
danielk1977ac11ee62005-01-15 12:45:51 +00004254 rc = allocatePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977ac245ec2005-01-14 13:50:11 +00004255 if( rc!=SQLITE_OK ){
4256 return rc;
4257 }
4258 pCell = pPage->aOvfl[0].pCell;
4259 szCell = cellSizePtr(pPage, pCell);
4260 zeroPage(pNew, pPage->aData[0]);
4261 assemblePage(pNew, 1, &pCell, &szCell);
4262 pPage->nOverflow = 0;
4263
danielk197779a40da2005-01-16 08:00:01 +00004264 /* Set the parent of the newly allocated page to pParent. */
4265 pNew->pParent = pParent;
4266 sqlite3pager_ref(pParent->aData);
4267
danielk1977ac245ec2005-01-14 13:50:11 +00004268 /* pPage is currently the right-child of pParent. Change this
4269 ** so that the right-child is the new page allocated above and
danielk197779a40da2005-01-16 08:00:01 +00004270 ** pPage is the next-to-right child.
danielk1977ac245ec2005-01-14 13:50:11 +00004271 */
danielk1977ac11ee62005-01-15 12:45:51 +00004272 assert( pPage->nCell>0 );
danielk1977ac245ec2005-01-14 13:50:11 +00004273 parseCellPtr(pPage, findCell(pPage, pPage->nCell-1), &info);
4274 rc = fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, &parentSize);
4275 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00004276 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004277 }
4278 assert( parentSize<64 );
4279 rc = insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
4280 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00004281 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004282 }
4283 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
4284 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
4285
danielk197779a40da2005-01-16 08:00:01 +00004286#ifndef SQLITE_OMIT_AUTOVACUUM
4287 /* If this is an auto-vacuum database, update the pointer map
4288 ** with entries for the new page, and any pointer from the
4289 ** cell on the page to an overflow page.
4290 */
danielk1977ac11ee62005-01-15 12:45:51 +00004291 if( pBt->autoVacuum ){
4292 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
4293 if( rc!=SQLITE_OK ){
4294 return rc;
4295 }
danielk197779a40da2005-01-16 08:00:01 +00004296 rc = ptrmapPutOvfl(pNew, 0);
4297 if( rc!=SQLITE_OK ){
4298 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00004299 }
4300 }
danielk197779a40da2005-01-16 08:00:01 +00004301#endif
danielk1977ac11ee62005-01-15 12:45:51 +00004302
danielk197779a40da2005-01-16 08:00:01 +00004303 /* Release the reference to the new page and balance the parent page,
4304 ** in case the divider cell inserted caused it to become overfull.
4305 */
danielk1977ac245ec2005-01-14 13:50:11 +00004306 releasePage(pNew);
4307 return balance(pParent, 0);
4308}
drh615ae552005-01-16 23:21:00 +00004309#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00004310
drhc3b70572003-01-04 19:44:07 +00004311/*
danielk1977ac11ee62005-01-15 12:45:51 +00004312** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
4313** if the database supports auto-vacuum or not. Because it is used
4314** within an expression that is an argument to another macro
4315** (sqliteMallocRaw), it is not possible to use conditional compilation.
4316** So, this macro is defined instead.
4317*/
4318#ifndef SQLITE_OMIT_AUTOVACUUM
4319#define ISAUTOVACUUM (pBt->autoVacuum)
4320#else
4321#define ISAUTOVACUUM 0
4322#endif
4323
4324/*
drhab01f612004-05-22 02:55:23 +00004325** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00004326** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00004327** Usually NN siblings on either side of pPage is used in the balancing,
4328** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00004329** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00004330** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00004331** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00004332**
drh0c6cc4e2004-06-15 02:13:26 +00004333** The number of siblings of pPage might be increased or decreased by one or
4334** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00004335** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00004336** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00004337** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00004338** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00004339**
drh8b2f49b2001-06-08 00:21:52 +00004340** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00004341** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00004342** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00004343** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00004344**
drh8c42ca92001-06-22 19:15:00 +00004345** In the course of balancing the siblings of pPage, the parent of pPage
4346** might become overfull or underfull. If that happens, then this routine
4347** is called recursively on the parent.
4348**
drh5e00f6c2001-09-13 13:46:56 +00004349** If this routine fails for any reason, it might leave the database
4350** in a corrupted state. So if this routine fails, the database should
4351** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00004352*/
drh43605152004-05-29 21:46:49 +00004353static int balance_nonroot(MemPage *pPage){
drh8b2f49b2001-06-08 00:21:52 +00004354 MemPage *pParent; /* The parent of pPage */
danielk1977aef0bf62005-12-30 16:28:01 +00004355 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00004356 int nCell = 0; /* Number of cells in apCell[] */
4357 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
drh8b2f49b2001-06-08 00:21:52 +00004358 int nOld; /* Number of pages in apOld[] */
4359 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00004360 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00004361 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00004362 int idx; /* Index of pPage in pParent->aCell[] */
4363 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00004364 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00004365 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00004366 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00004367 int usableSpace; /* Bytes in pPage beyond the header */
4368 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00004369 int subtotal; /* Subtotal of bytes in cells on one page */
drhb6f41482004-05-14 01:58:11 +00004370 int iSpace = 0; /* First unused byte of aSpace[] */
drhc3b70572003-01-04 19:44:07 +00004371 MemPage *apOld[NB]; /* pPage and up to two siblings */
4372 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00004373 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00004374 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
4375 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drh4b70f112004-05-02 21:12:19 +00004376 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00004377 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
4378 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00004379 u8 **apCell = 0; /* All cells begin balanced */
drh2e38c322004-09-03 18:38:44 +00004380 int *szCell; /* Local size of all cells in apCell[] */
4381 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
4382 u8 *aSpace; /* Space to hold copies of dividers cells */
danielk19774e17d142005-01-16 09:06:33 +00004383#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00004384 u8 *aFrom = 0;
4385#endif
drh8b2f49b2001-06-08 00:21:52 +00004386
drh14acc042001-06-10 19:56:58 +00004387 /*
drh43605152004-05-29 21:46:49 +00004388 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00004389 */
drh3a4c1412004-05-09 20:40:11 +00004390 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004391 assert( sqlite3pager_iswriteable(pPage->aData) );
drh4b70f112004-05-02 21:12:19 +00004392 pBt = pPage->pBt;
drh14acc042001-06-10 19:56:58 +00004393 pParent = pPage->pParent;
drh43605152004-05-29 21:46:49 +00004394 sqlite3pager_write(pParent->aData);
4395 assert( pParent );
4396 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00004397
drh615ae552005-01-16 23:21:00 +00004398#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004399 /*
4400 ** A special case: If a new entry has just been inserted into a
4401 ** table (that is, a btree with integer keys and all data at the leaves)
drh09d0deb2005-08-02 17:13:09 +00004402 ** and the new entry is the right-most entry in the tree (it has the
drhf222e712005-01-14 22:55:49 +00004403 ** largest key) then use the special balance_quick() routine for
4404 ** balancing. balance_quick() is much faster and results in a tighter
4405 ** packing of data in the common case.
4406 */
danielk1977ac245ec2005-01-14 13:50:11 +00004407 if( pPage->leaf &&
4408 pPage->intKey &&
4409 pPage->leafData &&
4410 pPage->nOverflow==1 &&
4411 pPage->aOvfl[0].idx==pPage->nCell &&
danielk1977ac11ee62005-01-15 12:45:51 +00004412 pPage->pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00004413 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
4414 ){
danielk1977ac11ee62005-01-15 12:45:51 +00004415 /*
4416 ** TODO: Check the siblings to the left of pPage. It may be that
4417 ** they are not full and no new page is required.
4418 */
danielk1977ac245ec2005-01-14 13:50:11 +00004419 return balance_quick(pPage, pParent);
4420 }
4421#endif
4422
drh2e38c322004-09-03 18:38:44 +00004423 /*
drh4b70f112004-05-02 21:12:19 +00004424 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00004425 ** to pPage. The "idx" variable is the index of that cell. If pPage
4426 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00004427 */
drhbb49aba2003-01-04 18:53:27 +00004428 if( pParent->idxShift ){
drha34b6762004-05-07 13:30:42 +00004429 Pgno pgno;
drh4b70f112004-05-02 21:12:19 +00004430 pgno = pPage->pgno;
drha34b6762004-05-07 13:30:42 +00004431 assert( pgno==sqlite3pager_pagenumber(pPage->aData) );
drhbb49aba2003-01-04 18:53:27 +00004432 for(idx=0; idx<pParent->nCell; idx++){
drh43605152004-05-29 21:46:49 +00004433 if( get4byte(findCell(pParent, idx))==pgno ){
drhbb49aba2003-01-04 18:53:27 +00004434 break;
4435 }
drh8b2f49b2001-06-08 00:21:52 +00004436 }
drh4b70f112004-05-02 21:12:19 +00004437 assert( idx<pParent->nCell
drh43605152004-05-29 21:46:49 +00004438 || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
drhbb49aba2003-01-04 18:53:27 +00004439 }else{
4440 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00004441 }
drh8b2f49b2001-06-08 00:21:52 +00004442
4443 /*
drh14acc042001-06-10 19:56:58 +00004444 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00004445 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00004446 */
drh14acc042001-06-10 19:56:58 +00004447 nOld = nNew = 0;
drha34b6762004-05-07 13:30:42 +00004448 sqlite3pager_ref(pParent->aData);
drh14acc042001-06-10 19:56:58 +00004449
4450 /*
drh4b70f112004-05-02 21:12:19 +00004451 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00004452 ** the siblings. An attempt is made to find NN siblings on either
4453 ** side of pPage. More siblings are taken from one side, however, if
4454 ** pPage there are fewer than NN siblings on the other side. If pParent
4455 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00004456 */
drhc3b70572003-01-04 19:44:07 +00004457 nxDiv = idx - NN;
4458 if( nxDiv + NB > pParent->nCell ){
4459 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00004460 }
drhc3b70572003-01-04 19:44:07 +00004461 if( nxDiv<0 ){
4462 nxDiv = 0;
4463 }
drh8b2f49b2001-06-08 00:21:52 +00004464 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00004465 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00004466 if( k<pParent->nCell ){
drh43605152004-05-29 21:46:49 +00004467 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00004468 nDiv++;
drha34b6762004-05-07 13:30:42 +00004469 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00004470 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00004471 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00004472 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00004473 }else{
4474 break;
drh8b2f49b2001-06-08 00:21:52 +00004475 }
drhde647132004-05-07 17:57:49 +00004476 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00004477 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00004478 apOld[i]->idxParent = k;
drh91025292004-05-03 19:49:32 +00004479 apCopy[i] = 0;
4480 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00004481 nOld++;
danielk1977634f2982005-03-28 08:44:07 +00004482 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
drh8b2f49b2001-06-08 00:21:52 +00004483 }
4484
drh8d97f1f2005-05-05 18:14:13 +00004485 /* Make nMaxCells a multiple of 2 in order to preserve 8-byte
4486 ** alignment */
4487 nMaxCells = (nMaxCells + 1)&~1;
4488
drh8b2f49b2001-06-08 00:21:52 +00004489 /*
danielk1977634f2982005-03-28 08:44:07 +00004490 ** Allocate space for memory structures
4491 */
4492 apCell = sqliteMallocRaw(
4493 nMaxCells*sizeof(u8*) /* apCell */
4494 + nMaxCells*sizeof(int) /* szCell */
drhc96d8532005-05-03 12:30:33 +00004495 + ROUND8(sizeof(MemPage))*NB /* aCopy */
drh07d183d2005-05-01 22:52:42 +00004496 + pBt->pageSize*(5+NB) /* aSpace */
drhc96d8532005-05-03 12:30:33 +00004497 + (ISAUTOVACUUM ? nMaxCells : 0) /* aFrom */
danielk1977634f2982005-03-28 08:44:07 +00004498 );
4499 if( apCell==0 ){
4500 rc = SQLITE_NOMEM;
4501 goto balance_cleanup;
4502 }
4503 szCell = (int*)&apCell[nMaxCells];
4504 aCopy[0] = (u8*)&szCell[nMaxCells];
drhc96d8532005-05-03 12:30:33 +00004505 assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004506 for(i=1; i<NB; i++){
drhc96d8532005-05-03 12:30:33 +00004507 aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
4508 assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004509 }
drhc96d8532005-05-03 12:30:33 +00004510 aSpace = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
4511 assert( ((aSpace - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004512#ifndef SQLITE_OMIT_AUTOVACUUM
4513 if( pBt->autoVacuum ){
drh07d183d2005-05-01 22:52:42 +00004514 aFrom = &aSpace[5*pBt->pageSize];
danielk1977634f2982005-03-28 08:44:07 +00004515 }
4516#endif
4517
4518 /*
drh14acc042001-06-10 19:56:58 +00004519 ** Make copies of the content of pPage and its siblings into aOld[].
4520 ** The rest of this function will use data from the copies rather
4521 ** that the original pages since the original pages will be in the
4522 ** process of being overwritten.
4523 */
4524 for(i=0; i<nOld; i++){
drh07d183d2005-05-01 22:52:42 +00004525 MemPage *p = apCopy[i] = (MemPage*)&aCopy[i][pBt->pageSize];
drh07d183d2005-05-01 22:52:42 +00004526 p->aData = &((u8*)p)[-pBt->pageSize];
4527 memcpy(p->aData, apOld[i]->aData, pBt->pageSize + sizeof(MemPage));
4528 /* The memcpy() above changes the value of p->aData so we have to
4529 ** set it again. */
drh07d183d2005-05-01 22:52:42 +00004530 p->aData = &((u8*)p)[-pBt->pageSize];
drh14acc042001-06-10 19:56:58 +00004531 }
4532
4533 /*
4534 ** Load pointers to all cells on sibling pages and the divider cells
4535 ** into the local apCell[] array. Make copies of the divider cells
drhb6f41482004-05-14 01:58:11 +00004536 ** into space obtained form aSpace[] and remove the the divider Cells
4537 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00004538 **
4539 ** If the siblings are on leaf pages, then the child pointers of the
4540 ** divider cells are stripped from the cells before they are copied
drh96f5b762004-05-16 16:24:36 +00004541 ** into aSpace[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00004542 ** child pointers. If siblings are not leaves, then all cell in
4543 ** apCell[] include child pointers. Either way, all cells in apCell[]
4544 ** are alike.
drh96f5b762004-05-16 16:24:36 +00004545 **
4546 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
4547 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00004548 */
4549 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00004550 leafCorrection = pPage->leaf*4;
drh8b18dd42004-05-12 19:18:15 +00004551 leafData = pPage->leafData && pPage->leaf;
drh8b2f49b2001-06-08 00:21:52 +00004552 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00004553 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00004554 int limit = pOld->nCell+pOld->nOverflow;
4555 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00004556 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00004557 apCell[nCell] = findOverflowCell(pOld, j);
4558 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk1977ac11ee62005-01-15 12:45:51 +00004559#ifndef SQLITE_OMIT_AUTOVACUUM
4560 if( pBt->autoVacuum ){
4561 int a;
4562 aFrom[nCell] = i;
4563 for(a=0; a<pOld->nOverflow; a++){
4564 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
4565 aFrom[nCell] = 0xFF;
4566 break;
4567 }
4568 }
4569 }
4570#endif
drh14acc042001-06-10 19:56:58 +00004571 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00004572 }
4573 if( i<nOld-1 ){
drh43605152004-05-29 21:46:49 +00004574 int sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00004575 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00004576 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
4577 ** are duplicates of keys on the child pages. We need to remove
4578 ** the divider cells from pParent, but the dividers cells are not
4579 ** added to apCell[] because they are duplicates of child cells.
4580 */
drh8b18dd42004-05-12 19:18:15 +00004581 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00004582 }else{
drhb6f41482004-05-14 01:58:11 +00004583 u8 *pTemp;
danielk1977634f2982005-03-28 08:44:07 +00004584 assert( nCell<nMaxCells );
drhb6f41482004-05-14 01:58:11 +00004585 szCell[nCell] = sz;
4586 pTemp = &aSpace[iSpace];
4587 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004588 assert( iSpace<=pBt->pageSize*5 );
drhb6f41482004-05-14 01:58:11 +00004589 memcpy(pTemp, apDiv[i], sz);
4590 apCell[nCell] = pTemp+leafCorrection;
danielk1977ac11ee62005-01-15 12:45:51 +00004591#ifndef SQLITE_OMIT_AUTOVACUUM
4592 if( pBt->autoVacuum ){
4593 aFrom[nCell] = 0xFF;
4594 }
4595#endif
drhb6f41482004-05-14 01:58:11 +00004596 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00004597 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00004598 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00004599 if( !pOld->leaf ){
4600 assert( leafCorrection==0 );
4601 /* The right pointer of the child page pOld becomes the left
4602 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00004603 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00004604 }else{
4605 assert( leafCorrection==4 );
4606 }
4607 nCell++;
drh4b70f112004-05-02 21:12:19 +00004608 }
drh8b2f49b2001-06-08 00:21:52 +00004609 }
4610 }
4611
4612 /*
drh6019e162001-07-02 17:51:45 +00004613 ** Figure out the number of pages needed to hold all nCell cells.
4614 ** Store this number in "k". Also compute szNew[] which is the total
4615 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00004616 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00004617 ** cntNew[k] should equal nCell.
4618 **
drh96f5b762004-05-16 16:24:36 +00004619 ** Values computed by this block:
4620 **
4621 ** k: The total number of sibling pages
4622 ** szNew[i]: Spaced used on the i-th sibling page.
4623 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
4624 ** the right of the i-th sibling page.
4625 ** usableSpace: Number of bytes of space available on each sibling.
4626 **
drh8b2f49b2001-06-08 00:21:52 +00004627 */
drh43605152004-05-29 21:46:49 +00004628 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00004629 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00004630 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00004631 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00004632 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00004633 szNew[k] = subtotal - szCell[i];
4634 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00004635 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00004636 subtotal = 0;
4637 k++;
4638 }
4639 }
4640 szNew[k] = subtotal;
4641 cntNew[k] = nCell;
4642 k++;
drh96f5b762004-05-16 16:24:36 +00004643
4644 /*
4645 ** The packing computed by the previous block is biased toward the siblings
4646 ** on the left side. The left siblings are always nearly full, while the
4647 ** right-most sibling might be nearly empty. This block of code attempts
4648 ** to adjust the packing of siblings to get a better balance.
4649 **
4650 ** This adjustment is more than an optimization. The packing above might
4651 ** be so out of balance as to be illegal. For example, the right-most
4652 ** sibling might be completely empty. This adjustment is not optional.
4653 */
drh6019e162001-07-02 17:51:45 +00004654 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00004655 int szRight = szNew[i]; /* Size of sibling on the right */
4656 int szLeft = szNew[i-1]; /* Size of sibling on the left */
4657 int r; /* Index of right-most cell in left sibling */
4658 int d; /* Index of first cell to the left of right sibling */
4659
4660 r = cntNew[i-1] - 1;
4661 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00004662 assert( d<nMaxCells );
4663 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00004664 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
4665 szRight += szCell[d] + 2;
4666 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00004667 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00004668 r = cntNew[i-1] - 1;
4669 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00004670 }
drh96f5b762004-05-16 16:24:36 +00004671 szNew[i] = szRight;
4672 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00004673 }
drh09d0deb2005-08-02 17:13:09 +00004674
4675 /* Either we found one or more cells (cntnew[0])>0) or we are the
4676 ** a virtual root page. A virtual root page is when the real root
4677 ** page is page 1 and we are the only child of that page.
4678 */
4679 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00004680
4681 /*
drh6b308672002-07-08 02:16:37 +00004682 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00004683 */
drh4b70f112004-05-02 21:12:19 +00004684 assert( pPage->pgno>1 );
4685 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00004686 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00004687 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00004688 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00004689 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00004690 pgnoNew[i] = pgnoOld[i];
4691 apOld[i] = 0;
danielk197728129562005-01-11 10:25:06 +00004692 rc = sqlite3pager_write(pNew->aData);
4693 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00004694 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004695 rc = allocatePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00004696 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00004697 apNew[i] = pNew;
drh6b308672002-07-08 02:16:37 +00004698 }
drh14acc042001-06-10 19:56:58 +00004699 nNew++;
drhda200cc2004-05-09 11:51:38 +00004700 zeroPage(pNew, pageFlags);
drh8b2f49b2001-06-08 00:21:52 +00004701 }
4702
danielk1977299b1872004-11-22 10:02:10 +00004703 /* Free any old pages that were not reused as new pages.
4704 */
4705 while( i<nOld ){
4706 rc = freePage(apOld[i]);
4707 if( rc ) goto balance_cleanup;
4708 releasePage(apOld[i]);
4709 apOld[i] = 0;
4710 i++;
4711 }
4712
drh8b2f49b2001-06-08 00:21:52 +00004713 /*
drhf9ffac92002-03-02 19:00:31 +00004714 ** Put the new pages in accending order. This helps to
4715 ** keep entries in the disk file in order so that a scan
4716 ** of the table is a linear scan through the file. That
4717 ** in turn helps the operating system to deliver pages
4718 ** from the disk more rapidly.
4719 **
4720 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00004721 ** n is never more than NB (a small constant), that should
4722 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00004723 **
drhc3b70572003-01-04 19:44:07 +00004724 ** When NB==3, this one optimization makes the database
4725 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00004726 */
4727 for(i=0; i<k-1; i++){
4728 int minV = pgnoNew[i];
4729 int minI = i;
4730 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00004731 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00004732 minI = j;
4733 minV = pgnoNew[j];
4734 }
4735 }
4736 if( minI>i ){
4737 int t;
4738 MemPage *pT;
4739 t = pgnoNew[i];
4740 pT = apNew[i];
4741 pgnoNew[i] = pgnoNew[minI];
4742 apNew[i] = apNew[minI];
4743 pgnoNew[minI] = t;
4744 apNew[minI] = pT;
4745 }
4746 }
drha2fce642004-06-05 00:01:44 +00004747 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00004748 pgnoOld[0],
4749 nOld>=2 ? pgnoOld[1] : 0,
4750 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00004751 pgnoNew[0], szNew[0],
4752 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
4753 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00004754 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
4755 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00004756
drhf9ffac92002-03-02 19:00:31 +00004757 /*
drh14acc042001-06-10 19:56:58 +00004758 ** Evenly distribute the data in apCell[] across the new pages.
4759 ** Insert divider cells into pParent as necessary.
4760 */
4761 j = 0;
4762 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00004763 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00004764 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00004765 assert( j<nMaxCells );
drh4b70f112004-05-02 21:12:19 +00004766 assert( pNew->pgno==pgnoNew[i] );
drhfa1a98a2004-05-14 19:08:17 +00004767 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00004768 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00004769 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00004770
4771#ifndef SQLITE_OMIT_AUTOVACUUM
4772 /* If this is an auto-vacuum database, update the pointer map entries
4773 ** that point to the siblings that were rearranged. These can be: left
4774 ** children of cells, the right-child of the page, or overflow pages
4775 ** pointed to by cells.
4776 */
4777 if( pBt->autoVacuum ){
4778 for(k=j; k<cntNew[i]; k++){
danielk1977634f2982005-03-28 08:44:07 +00004779 assert( k<nMaxCells );
danielk1977ac11ee62005-01-15 12:45:51 +00004780 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
danielk197779a40da2005-01-16 08:00:01 +00004781 rc = ptrmapPutOvfl(pNew, k-j);
4782 if( rc!=SQLITE_OK ){
4783 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00004784 }
4785 }
4786 }
4787 }
4788#endif
4789
4790 j = cntNew[i];
4791
4792 /* If the sibling page assembled above was not the right-most sibling,
4793 ** insert a divider cell into the parent page.
4794 */
drh14acc042001-06-10 19:56:58 +00004795 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00004796 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00004797 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00004798 int sz;
danielk1977634f2982005-03-28 08:44:07 +00004799
4800 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00004801 pCell = apCell[j];
4802 sz = szCell[j] + leafCorrection;
drh4b70f112004-05-02 21:12:19 +00004803 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00004804 memcpy(&pNew->aData[8], pCell, 4);
drh24cd67e2004-05-10 16:18:47 +00004805 pTemp = 0;
drh8b18dd42004-05-12 19:18:15 +00004806 }else if( leafData ){
danielk1977ac11ee62005-01-15 12:45:51 +00004807 /* If the tree is a leaf-data tree, and the siblings are leaves,
4808 ** then there is no divider cell in apCell[]. Instead, the divider
4809 ** cell consists of the integer key for the right-most cell of
4810 ** the sibling-page assembled above only.
4811 */
drh6f11bef2004-05-13 01:12:56 +00004812 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00004813 j--;
drh43605152004-05-29 21:46:49 +00004814 parseCellPtr(pNew, apCell[j], &info);
drhb6f41482004-05-14 01:58:11 +00004815 pCell = &aSpace[iSpace];
drh6f11bef2004-05-13 01:12:56 +00004816 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, &sz);
drhb6f41482004-05-14 01:58:11 +00004817 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004818 assert( iSpace<=pBt->pageSize*5 );
drh8b18dd42004-05-12 19:18:15 +00004819 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00004820 }else{
4821 pCell -= 4;
drhb6f41482004-05-14 01:58:11 +00004822 pTemp = &aSpace[iSpace];
4823 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004824 assert( iSpace<=pBt->pageSize*5 );
drh4b70f112004-05-02 21:12:19 +00004825 }
danielk1977a3ad5e72005-01-07 08:56:44 +00004826 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00004827 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh43605152004-05-29 21:46:49 +00004828 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +00004829#ifndef SQLITE_OMIT_AUTOVACUUM
4830 /* If this is an auto-vacuum database, and not a leaf-data tree,
4831 ** then update the pointer map with an entry for the overflow page
4832 ** that the cell just inserted points to (if any).
4833 */
4834 if( pBt->autoVacuum && !leafData ){
danielk197779a40da2005-01-16 08:00:01 +00004835 rc = ptrmapPutOvfl(pParent, nxDiv);
4836 if( rc!=SQLITE_OK ){
4837 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00004838 }
4839 }
4840#endif
drh14acc042001-06-10 19:56:58 +00004841 j++;
4842 nxDiv++;
4843 }
4844 }
drh6019e162001-07-02 17:51:45 +00004845 assert( j==nCell );
drh4b70f112004-05-02 21:12:19 +00004846 if( (pageFlags & PTF_LEAF)==0 ){
drh43605152004-05-29 21:46:49 +00004847 memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
drh14acc042001-06-10 19:56:58 +00004848 }
drh43605152004-05-29 21:46:49 +00004849 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00004850 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00004851 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00004852 }else{
4853 /* Right-most sibling is the left child of the first entry in pParent
4854 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00004855 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00004856 }
4857
4858 /*
4859 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00004860 */
4861 for(i=0; i<nNew; i++){
danielk1977afcdd022004-10-31 16:25:42 +00004862 rc = reparentChildPages(apNew[i]);
4863 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004864 }
danielk1977afcdd022004-10-31 16:25:42 +00004865 rc = reparentChildPages(pParent);
4866 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004867
4868 /*
drh3a4c1412004-05-09 20:40:11 +00004869 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00004870 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00004871 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00004872 */
drhda200cc2004-05-09 11:51:38 +00004873 assert( pParent->isInit );
drh3a4c1412004-05-09 20:40:11 +00004874 /* assert( pPage->isInit ); // No! pPage might have been added to freelist */
4875 /* pageIntegrity(pPage); // No! pPage might have been added to freelist */
danielk1977ac245ec2005-01-14 13:50:11 +00004876 rc = balance(pParent, 0);
drhda200cc2004-05-09 11:51:38 +00004877
drh8b2f49b2001-06-08 00:21:52 +00004878 /*
drh14acc042001-06-10 19:56:58 +00004879 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00004880 */
drh14acc042001-06-10 19:56:58 +00004881balance_cleanup:
drh2e38c322004-09-03 18:38:44 +00004882 sqliteFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00004883 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00004884 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00004885 }
drh14acc042001-06-10 19:56:58 +00004886 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00004887 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00004888 }
drh91025292004-05-03 19:49:32 +00004889 releasePage(pParent);
drh3a4c1412004-05-09 20:40:11 +00004890 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
4891 pPage->pgno, nOld, nNew, nCell));
drh8b2f49b2001-06-08 00:21:52 +00004892 return rc;
4893}
4894
4895/*
drh43605152004-05-29 21:46:49 +00004896** This routine is called for the root page of a btree when the root
4897** page contains no cells. This is an opportunity to make the tree
4898** shallower by one level.
4899*/
4900static int balance_shallower(MemPage *pPage){
4901 MemPage *pChild; /* The only child page of pPage */
4902 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00004903 int rc = SQLITE_OK; /* Return code from subprocedures */
danielk1977aef0bf62005-12-30 16:28:01 +00004904 BtShared *pBt; /* The main BTree structure */
drh2e38c322004-09-03 18:38:44 +00004905 int mxCellPerPage; /* Maximum number of cells per page */
4906 u8 **apCell; /* All cells from pages being balanced */
4907 int *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00004908
4909 assert( pPage->pParent==0 );
4910 assert( pPage->nCell==0 );
drh2e38c322004-09-03 18:38:44 +00004911 pBt = pPage->pBt;
4912 mxCellPerPage = MX_CELL(pBt);
4913 apCell = sqliteMallocRaw( mxCellPerPage*(sizeof(u8*)+sizeof(int)) );
4914 if( apCell==0 ) return SQLITE_NOMEM;
4915 szCell = (int*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00004916 if( pPage->leaf ){
4917 /* The table is completely empty */
4918 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
4919 }else{
4920 /* The root page is empty but has one child. Transfer the
4921 ** information from that one child into the root page if it
4922 ** will fit. This reduces the depth of the tree by one.
4923 **
4924 ** If the root page is page 1, it has less space available than
4925 ** its child (due to the 100 byte header that occurs at the beginning
4926 ** of the database fle), so it might not be able to hold all of the
4927 ** information currently contained in the child. If this is the
4928 ** case, then do not do the transfer. Leave page 1 empty except
4929 ** for the right-pointer to the child page. The child page becomes
4930 ** the virtual root of the tree.
4931 */
4932 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
4933 assert( pgnoChild>0 );
4934 assert( pgnoChild<=sqlite3pager_pagecount(pPage->pBt->pPager) );
4935 rc = getPage(pPage->pBt, pgnoChild, &pChild);
drh2e38c322004-09-03 18:38:44 +00004936 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004937 if( pPage->pgno==1 ){
4938 rc = initPage(pChild, pPage);
drh2e38c322004-09-03 18:38:44 +00004939 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004940 assert( pChild->nOverflow==0 );
4941 if( pChild->nFree>=100 ){
4942 /* The child information will fit on the root page, so do the
4943 ** copy */
4944 int i;
4945 zeroPage(pPage, pChild->aData[0]);
4946 for(i=0; i<pChild->nCell; i++){
4947 apCell[i] = findCell(pChild,i);
4948 szCell[i] = cellSizePtr(pChild, apCell[i]);
4949 }
4950 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00004951 /* Copy the right-pointer of the child to the parent. */
4952 put4byte(&pPage->aData[pPage->hdrOffset+8],
4953 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh43605152004-05-29 21:46:49 +00004954 freePage(pChild);
4955 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
4956 }else{
4957 /* The child has more information that will fit on the root.
4958 ** The tree is already balanced. Do nothing. */
4959 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
4960 }
4961 }else{
4962 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
4963 pPage->isInit = 0;
4964 pPage->pParent = 0;
4965 rc = initPage(pPage, 0);
4966 assert( rc==SQLITE_OK );
4967 freePage(pChild);
4968 TRACE(("BALANCE: transfer child %d into root %d\n",
4969 pChild->pgno, pPage->pgno));
4970 }
danielk1977afcdd022004-10-31 16:25:42 +00004971 rc = reparentChildPages(pPage);
danielk1977ac11ee62005-01-15 12:45:51 +00004972 assert( pPage->nOverflow==0 );
4973#ifndef SQLITE_OMIT_AUTOVACUUM
4974 if( pBt->autoVacuum ){
danielk1977aac0a382005-01-16 11:07:06 +00004975 int i;
danielk1977ac11ee62005-01-15 12:45:51 +00004976 for(i=0; i<pPage->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00004977 rc = ptrmapPutOvfl(pPage, i);
4978 if( rc!=SQLITE_OK ){
4979 goto end_shallow_balance;
danielk1977ac11ee62005-01-15 12:45:51 +00004980 }
4981 }
4982 }
4983#endif
danielk1977afcdd022004-10-31 16:25:42 +00004984 if( rc!=SQLITE_OK ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004985 releasePage(pChild);
4986 }
drh2e38c322004-09-03 18:38:44 +00004987end_shallow_balance:
4988 sqliteFree(apCell);
4989 return rc;
drh43605152004-05-29 21:46:49 +00004990}
4991
4992
4993/*
4994** The root page is overfull
4995**
4996** When this happens, Create a new child page and copy the
4997** contents of the root into the child. Then make the root
4998** page an empty page with rightChild pointing to the new
4999** child. Finally, call balance_internal() on the new child
5000** to cause it to split.
5001*/
5002static int balance_deeper(MemPage *pPage){
5003 int rc; /* Return value from subprocedures */
5004 MemPage *pChild; /* Pointer to a new child page */
5005 Pgno pgnoChild; /* Page number of the new child page */
danielk1977aef0bf62005-12-30 16:28:01 +00005006 BtShared *pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00005007 int usableSize; /* Total usable size of a page */
5008 u8 *data; /* Content of the parent page */
5009 u8 *cdata; /* Content of the child page */
5010 int hdr; /* Offset to page header in parent */
5011 int brk; /* Offset to content of first cell in parent */
5012
5013 assert( pPage->pParent==0 );
5014 assert( pPage->nOverflow>0 );
5015 pBt = pPage->pBt;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005016 rc = allocatePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00005017 if( rc ) return rc;
5018 assert( sqlite3pager_iswriteable(pChild->aData) );
5019 usableSize = pBt->usableSize;
5020 data = pPage->aData;
5021 hdr = pPage->hdrOffset;
5022 brk = get2byte(&data[hdr+5]);
5023 cdata = pChild->aData;
5024 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
5025 memcpy(&cdata[brk], &data[brk], usableSize-brk);
danielk1977c7dc7532004-11-17 10:22:03 +00005026 assert( pChild->isInit==0 );
drh43605152004-05-29 21:46:49 +00005027 rc = initPage(pChild, pPage);
danielk19776b456a22005-03-21 04:04:02 +00005028 if( rc ) goto balancedeeper_out;
drh43605152004-05-29 21:46:49 +00005029 memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
5030 pChild->nOverflow = pPage->nOverflow;
5031 if( pChild->nOverflow ){
5032 pChild->nFree = 0;
5033 }
5034 assert( pChild->nCell==pPage->nCell );
5035 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
5036 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
5037 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
danielk19774e17d142005-01-16 09:06:33 +00005038#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00005039 if( pBt->autoVacuum ){
5040 int i;
5041 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
danielk19776b456a22005-03-21 04:04:02 +00005042 if( rc ) goto balancedeeper_out;
danielk1977ac11ee62005-01-15 12:45:51 +00005043 for(i=0; i<pChild->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00005044 rc = ptrmapPutOvfl(pChild, i);
5045 if( rc!=SQLITE_OK ){
5046 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00005047 }
5048 }
5049 }
danielk19774e17d142005-01-16 09:06:33 +00005050#endif
drh43605152004-05-29 21:46:49 +00005051 rc = balance_nonroot(pChild);
danielk19776b456a22005-03-21 04:04:02 +00005052
5053balancedeeper_out:
drh43605152004-05-29 21:46:49 +00005054 releasePage(pChild);
5055 return rc;
5056}
5057
5058/*
5059** Decide if the page pPage needs to be balanced. If balancing is
5060** required, call the appropriate balancing routine.
5061*/
danielk1977ac245ec2005-01-14 13:50:11 +00005062static int balance(MemPage *pPage, int insert){
drh43605152004-05-29 21:46:49 +00005063 int rc = SQLITE_OK;
5064 if( pPage->pParent==0 ){
5065 if( pPage->nOverflow>0 ){
5066 rc = balance_deeper(pPage);
5067 }
danielk1977687566d2004-11-02 12:56:41 +00005068 if( rc==SQLITE_OK && pPage->nCell==0 ){
drh43605152004-05-29 21:46:49 +00005069 rc = balance_shallower(pPage);
5070 }
5071 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00005072 if( pPage->nOverflow>0 ||
5073 (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
drh43605152004-05-29 21:46:49 +00005074 rc = balance_nonroot(pPage);
5075 }
5076 }
5077 return rc;
5078}
5079
5080/*
drh8dcd7ca2004-08-08 19:43:29 +00005081** This routine checks all cursors that point to table pgnoRoot.
5082** If any of those cursors other than pExclude were opened with
drhf74b8d92002-09-01 23:20:45 +00005083** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
drh8dcd7ca2004-08-08 19:43:29 +00005084** cursors that point to pgnoRoot were opened with wrFlag==1
drhf74b8d92002-09-01 23:20:45 +00005085** then this routine returns SQLITE_OK.
danielk1977299b1872004-11-22 10:02:10 +00005086**
5087** In addition to checking for read-locks (where a read-lock
5088** means a cursor opened with wrFlag==0) this routine also moves
5089** all cursors other than pExclude so that they are pointing to the
5090** first Cell on root page. This is necessary because an insert
5091** or delete might change the number of cells on a page or delete
5092** a page entirely and we do not want to leave any cursors
5093** pointing to non-existant pages or cells.
drhf74b8d92002-09-01 23:20:45 +00005094*/
danielk1977aef0bf62005-12-30 16:28:01 +00005095static int checkReadLocks(BtShared *pBt, Pgno pgnoRoot, BtCursor *pExclude){
danielk1977299b1872004-11-22 10:02:10 +00005096 BtCursor *p;
5097 for(p=pBt->pCursor; p; p=p->pNext){
danielk1977da184232006-01-05 11:34:32 +00005098 u32 flags = (p->pBtree->pSqlite ? p->pBtree->pSqlite->flags : 0);
danielk1977299b1872004-11-22 10:02:10 +00005099 if( p->pgnoRoot!=pgnoRoot || p==pExclude ) continue;
danielk1977da184232006-01-05 11:34:32 +00005100 if( p->wrFlag==0 && flags&SQLITE_ReadUncommitted ) continue;
danielk1977299b1872004-11-22 10:02:10 +00005101 if( p->wrFlag==0 ) return SQLITE_LOCKED;
5102 if( p->pPage->pgno!=p->pgnoRoot ){
5103 moveToRoot(p);
5104 }
5105 }
drhf74b8d92002-09-01 23:20:45 +00005106 return SQLITE_OK;
5107}
5108
5109/*
drh3b7511c2001-05-26 13:15:44 +00005110** Insert a new record into the BTree. The key is given by (pKey,nKey)
5111** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00005112** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00005113** is left pointing at a random location.
5114**
5115** For an INTKEY table, only the nKey value of the key is used. pKey is
5116** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00005117*/
drh3aac2dd2004-04-26 14:10:20 +00005118int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00005119 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00005120 const void *pKey, i64 nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00005121 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00005122){
drh3b7511c2001-05-26 13:15:44 +00005123 int rc;
5124 int loc;
drh14acc042001-06-10 19:56:58 +00005125 int szNew;
drh3b7511c2001-05-26 13:15:44 +00005126 MemPage *pPage;
danielk1977aef0bf62005-12-30 16:28:01 +00005127 BtShared *pBt = pCur->pBtree->pBt;
drha34b6762004-05-07 13:30:42 +00005128 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00005129 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00005130
danielk1977aef0bf62005-12-30 16:28:01 +00005131 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005132 /* Must start a transaction before doing an insert */
5133 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005134 }
drhf74b8d92002-09-01 23:20:45 +00005135 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00005136 if( !pCur->wrFlag ){
5137 return SQLITE_PERM; /* Cursor not open for writing */
5138 }
drh8dcd7ca2004-08-08 19:43:29 +00005139 if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00005140 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5141 }
danielk1977da184232006-01-05 11:34:32 +00005142
5143 /* Save the positions of any other cursors open on this table */
5144 restoreCursorPosition(pCur, 0);
5145 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
5146 if( rc ){
5147 return rc;
5148 }
5149
drh3aac2dd2004-04-26 14:10:20 +00005150 rc = sqlite3BtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00005151 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00005152 pPage = pCur->pPage;
drh4a1c3802004-05-12 15:15:47 +00005153 assert( pPage->intKey || nKey>=0 );
drh8b18dd42004-05-12 19:18:15 +00005154 assert( pPage->leaf || !pPage->leafData );
drh3a4c1412004-05-09 20:40:11 +00005155 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
5156 pCur->pgnoRoot, nKey, nData, pPage->pgno,
5157 loc==0 ? "overwrite" : "new entry"));
drh7aa128d2002-06-21 13:09:16 +00005158 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00005159 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00005160 if( rc ) return rc;
drh2e38c322004-09-03 18:38:44 +00005161 newCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
5162 if( newCell==0 ) return SQLITE_NOMEM;
drha34b6762004-05-07 13:30:42 +00005163 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, &szNew);
drh2e38c322004-09-03 18:38:44 +00005164 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00005165 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00005166 assert( szNew<=MX_CELL_SIZE(pBt) );
danielk1977da184232006-01-05 11:34:32 +00005167 if( loc==0 && CURSOR_VALID==pCur->eState ){
drha34b6762004-05-07 13:30:42 +00005168 int szOld;
5169 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00005170 oldCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005171 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005172 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00005173 }
drh43605152004-05-29 21:46:49 +00005174 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00005175 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00005176 if( rc ) goto end_insert;
drh4b70f112004-05-02 21:12:19 +00005177 dropCell(pPage, pCur->idx, szOld);
drh7c717f72001-06-24 20:39:41 +00005178 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00005179 assert( pPage->leaf );
drh14acc042001-06-10 19:56:58 +00005180 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00005181 pCur->info.nSize = 0;
drh14acc042001-06-10 19:56:58 +00005182 }else{
drh4b70f112004-05-02 21:12:19 +00005183 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00005184 }
danielk1977a3ad5e72005-01-07 08:56:44 +00005185 rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
danielk1977e80463b2004-11-03 03:01:16 +00005186 if( rc!=SQLITE_OK ) goto end_insert;
danielk1977ac245ec2005-01-14 13:50:11 +00005187 rc = balance(pPage, 1);
drh23e11ca2004-05-04 17:27:28 +00005188 /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
drh3fc190c2001-09-14 03:24:23 +00005189 /* fflush(stdout); */
danielk1977299b1872004-11-22 10:02:10 +00005190 if( rc==SQLITE_OK ){
5191 moveToRoot(pCur);
5192 }
drh2e38c322004-09-03 18:38:44 +00005193end_insert:
5194 sqliteFree(newCell);
drh5e2f8b92001-05-28 00:41:15 +00005195 return rc;
5196}
5197
5198/*
drh4b70f112004-05-02 21:12:19 +00005199** Delete the entry that the cursor is pointing to. The cursor
5200** is left pointing at a random location.
drh3b7511c2001-05-26 13:15:44 +00005201*/
drh3aac2dd2004-04-26 14:10:20 +00005202int sqlite3BtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00005203 MemPage *pPage = pCur->pPage;
drh4b70f112004-05-02 21:12:19 +00005204 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00005205 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00005206 Pgno pgnoChild = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00005207 BtShared *pBt = pCur->pBtree->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005208
drh7aa128d2002-06-21 13:09:16 +00005209 assert( pPage->isInit );
danielk1977aef0bf62005-12-30 16:28:01 +00005210 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005211 /* Must start a transaction before doing a delete */
5212 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005213 }
drhf74b8d92002-09-01 23:20:45 +00005214 assert( !pBt->readOnly );
drhbd03cae2001-06-02 02:40:57 +00005215 if( pCur->idx >= pPage->nCell ){
5216 return SQLITE_ERROR; /* The cursor is not pointing to anything */
5217 }
drhecdc7532001-09-23 02:35:53 +00005218 if( !pCur->wrFlag ){
5219 return SQLITE_PERM; /* Did not open this cursor for writing */
5220 }
drh8dcd7ca2004-08-08 19:43:29 +00005221 if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00005222 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5223 }
danielk1977da184232006-01-05 11:34:32 +00005224
5225 /* Restore the current cursor position (a no-op if the cursor is not in
5226 ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
5227 ** open on the same table. Then call sqlite3pager_write() on the page
5228 ** that the entry will be deleted from.
5229 */
5230 if(
5231 (rc = restoreCursorPosition(pCur, 1)) ||
5232 (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
5233 (rc = sqlite3pager_write(pPage->aData))
5234 ){
5235 return rc;
5236 }
danielk1977e6efa742004-11-10 11:55:10 +00005237
5238 /* Locate the cell within it's page and leave pCell pointing to the
5239 ** data. The clearCell() call frees any overflow pages associated with the
5240 ** cell. The cell itself is still intact.
5241 */
danielk1977299b1872004-11-22 10:02:10 +00005242 pCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005243 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005244 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005245 }
danielk197728129562005-01-11 10:25:06 +00005246 rc = clearCell(pPage, pCell);
5247 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00005248
drh4b70f112004-05-02 21:12:19 +00005249 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00005250 /*
drh5e00f6c2001-09-13 13:46:56 +00005251 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00005252 ** do something we will leave a hole on an internal page.
5253 ** We have to fill the hole by moving in a cell from a leaf. The
5254 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00005255 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00005256 */
drh14acc042001-06-10 19:56:58 +00005257 BtCursor leafCur;
drh4b70f112004-05-02 21:12:19 +00005258 unsigned char *pNext;
drh14acc042001-06-10 19:56:58 +00005259 int szNext;
danielk1977299b1872004-11-22 10:02:10 +00005260 int notUsed;
danielk19776b456a22005-03-21 04:04:02 +00005261 unsigned char *tempCell = 0;
drh8b18dd42004-05-12 19:18:15 +00005262 assert( !pPage->leafData );
drh14acc042001-06-10 19:56:58 +00005263 getTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00005264 rc = sqlite3BtreeNext(&leafCur, &notUsed);
drh14acc042001-06-10 19:56:58 +00005265 if( rc!=SQLITE_OK ){
drhee696e22004-08-30 16:52:17 +00005266 if( rc!=SQLITE_NOMEM ){
drh49285702005-09-17 15:20:26 +00005267 rc = SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00005268 }
drh5e2f8b92001-05-28 00:41:15 +00005269 }
danielk19776b456a22005-03-21 04:04:02 +00005270 if( rc==SQLITE_OK ){
5271 rc = sqlite3pager_write(leafCur.pPage->aData);
5272 }
5273 if( rc==SQLITE_OK ){
5274 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
5275 pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
5276 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
5277 pNext = findCell(leafCur.pPage, leafCur.idx);
5278 szNext = cellSizePtr(leafCur.pPage, pNext);
5279 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
5280 tempCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
5281 if( tempCell==0 ){
5282 rc = SQLITE_NOMEM;
5283 }
5284 }
5285 if( rc==SQLITE_OK ){
5286 rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
5287 }
5288 if( rc==SQLITE_OK ){
5289 put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
5290 rc = balance(pPage, 0);
5291 }
5292 if( rc==SQLITE_OK ){
5293 dropCell(leafCur.pPage, leafCur.idx, szNext);
5294 rc = balance(leafCur.pPage, 0);
5295 }
drh2e38c322004-09-03 18:38:44 +00005296 sqliteFree(tempCell);
drh8c42ca92001-06-22 19:15:00 +00005297 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00005298 }else{
danielk1977299b1872004-11-22 10:02:10 +00005299 TRACE(("DELETE: table=%d delete from leaf %d\n",
5300 pCur->pgnoRoot, pPage->pgno));
5301 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
danielk1977ac245ec2005-01-14 13:50:11 +00005302 rc = balance(pPage, 0);
drh5e2f8b92001-05-28 00:41:15 +00005303 }
danielk19776b456a22005-03-21 04:04:02 +00005304 if( rc==SQLITE_OK ){
5305 moveToRoot(pCur);
5306 }
drh5e2f8b92001-05-28 00:41:15 +00005307 return rc;
drh3b7511c2001-05-26 13:15:44 +00005308}
drh8b2f49b2001-06-08 00:21:52 +00005309
5310/*
drhc6b52df2002-01-04 03:09:29 +00005311** Create a new BTree table. Write into *piTable the page
5312** number for the root page of the new table.
5313**
drhab01f612004-05-22 02:55:23 +00005314** The type of type is determined by the flags parameter. Only the
5315** following values of flags are currently in use. Other values for
5316** flags might not work:
5317**
5318** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
5319** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00005320*/
danielk1977aef0bf62005-12-30 16:28:01 +00005321int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
5322 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005323 MemPage *pRoot;
5324 Pgno pgnoRoot;
5325 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00005326 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005327 /* Must start a transaction first */
5328 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005329 }
danielk197728129562005-01-11 10:25:06 +00005330 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00005331
5332 /* It is illegal to create a table if any cursors are open on the
5333 ** database. This is because in auto-vacuum mode the backend may
5334 ** need to move a database page to make room for the new root-page.
5335 ** If an open cursor was using the page a problem would occur.
5336 */
5337 if( pBt->pCursor ){
5338 return SQLITE_LOCKED;
5339 }
5340
danielk1977003ba062004-11-04 02:57:33 +00005341#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977cb1a7eb2004-11-05 12:27:02 +00005342 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drh8b2f49b2001-06-08 00:21:52 +00005343 if( rc ) return rc;
danielk1977003ba062004-11-04 02:57:33 +00005344#else
danielk1977687566d2004-11-02 12:56:41 +00005345 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00005346 Pgno pgnoMove; /* Move a page here to make room for the root-page */
5347 MemPage *pPageMove; /* The page to move to. */
5348
danielk1977003ba062004-11-04 02:57:33 +00005349 /* Read the value of meta[3] from the database to determine where the
5350 ** root page of the new table should go. meta[3] is the largest root-page
5351 ** created so far, so the new root-page is (meta[3]+1).
5352 */
danielk1977aef0bf62005-12-30 16:28:01 +00005353 rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00005354 if( rc!=SQLITE_OK ) return rc;
5355 pgnoRoot++;
5356
danielk1977599fcba2004-11-08 07:13:13 +00005357 /* The new root-page may not be allocated on a pointer-map page, or the
5358 ** PENDING_BYTE page.
5359 */
drh42cac6d2004-11-20 20:31:11 +00005360 if( pgnoRoot==PTRMAP_PAGENO(pBt->usableSize, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00005361 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00005362 pgnoRoot++;
5363 }
5364 assert( pgnoRoot>=3 );
5365
5366 /* Allocate a page. The page that currently resides at pgnoRoot will
5367 ** be moved to the allocated page (unless the allocated page happens
5368 ** to reside at pgnoRoot).
5369 */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005370 rc = allocatePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00005371 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00005372 return rc;
5373 }
danielk1977003ba062004-11-04 02:57:33 +00005374
5375 if( pgnoMove!=pgnoRoot ){
5376 u8 eType;
5377 Pgno iPtrPage;
5378
5379 releasePage(pPageMove);
5380 rc = getPage(pBt, pgnoRoot, &pRoot);
5381 if( rc!=SQLITE_OK ){
5382 return rc;
5383 }
5384 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drhccae6022005-02-26 17:31:26 +00005385 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00005386 releasePage(pRoot);
5387 return rc;
5388 }
drhccae6022005-02-26 17:31:26 +00005389 assert( eType!=PTRMAP_ROOTPAGE );
5390 assert( eType!=PTRMAP_FREEPAGE );
danielk19775fd057a2005-03-09 13:09:43 +00005391 rc = sqlite3pager_write(pRoot->aData);
5392 if( rc!=SQLITE_OK ){
5393 releasePage(pRoot);
5394 return rc;
5395 }
danielk1977003ba062004-11-04 02:57:33 +00005396 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove);
5397 releasePage(pRoot);
5398 if( rc!=SQLITE_OK ){
5399 return rc;
5400 }
5401 rc = getPage(pBt, pgnoRoot, &pRoot);
5402 if( rc!=SQLITE_OK ){
5403 return rc;
5404 }
5405 rc = sqlite3pager_write(pRoot->aData);
5406 if( rc!=SQLITE_OK ){
5407 releasePage(pRoot);
5408 return rc;
5409 }
5410 }else{
5411 pRoot = pPageMove;
5412 }
5413
danielk197742741be2005-01-08 12:42:39 +00005414 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00005415 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
5416 if( rc ){
5417 releasePage(pRoot);
5418 return rc;
5419 }
danielk1977aef0bf62005-12-30 16:28:01 +00005420 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00005421 if( rc ){
5422 releasePage(pRoot);
5423 return rc;
5424 }
danielk197742741be2005-01-08 12:42:39 +00005425
danielk1977003ba062004-11-04 02:57:33 +00005426 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00005427 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00005428 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00005429 }
5430#endif
drha34b6762004-05-07 13:30:42 +00005431 assert( sqlite3pager_iswriteable(pRoot->aData) );
drhde647132004-05-07 17:57:49 +00005432 zeroPage(pRoot, flags | PTF_LEAF);
drha34b6762004-05-07 13:30:42 +00005433 sqlite3pager_unref(pRoot->aData);
drh8b2f49b2001-06-08 00:21:52 +00005434 *piTable = (int)pgnoRoot;
5435 return SQLITE_OK;
5436}
5437
5438/*
5439** Erase the given database page and all its children. Return
5440** the page to the freelist.
5441*/
drh4b70f112004-05-02 21:12:19 +00005442static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00005443 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00005444 Pgno pgno, /* Page number to clear */
5445 MemPage *pParent, /* Parent page. NULL for the root */
5446 int freePageFlag /* Deallocate page if true */
5447){
danielk19776b456a22005-03-21 04:04:02 +00005448 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00005449 int rc;
drh4b70f112004-05-02 21:12:19 +00005450 unsigned char *pCell;
5451 int i;
drh8b2f49b2001-06-08 00:21:52 +00005452
danielk1977a1cb1832005-02-12 08:59:55 +00005453 if( pgno>sqlite3pager_pagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00005454 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00005455 }
5456
drhde647132004-05-07 17:57:49 +00005457 rc = getAndInitPage(pBt, pgno, &pPage, pParent);
danielk19776b456a22005-03-21 04:04:02 +00005458 if( rc ) goto cleardatabasepage_out;
drha34b6762004-05-07 13:30:42 +00005459 rc = sqlite3pager_write(pPage->aData);
danielk19776b456a22005-03-21 04:04:02 +00005460 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00005461 for(i=0; i<pPage->nCell; i++){
drh43605152004-05-29 21:46:49 +00005462 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00005463 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005464 rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00005465 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00005466 }
drh4b70f112004-05-02 21:12:19 +00005467 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00005468 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00005469 }
drha34b6762004-05-07 13:30:42 +00005470 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005471 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00005472 if( rc ) goto cleardatabasepage_out;
drh2aa679f2001-06-25 02:11:07 +00005473 }
5474 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00005475 rc = freePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00005476 }else{
drh3a4c1412004-05-09 20:40:11 +00005477 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00005478 }
danielk19776b456a22005-03-21 04:04:02 +00005479
5480cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00005481 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00005482 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005483}
5484
5485/*
drhab01f612004-05-22 02:55:23 +00005486** Delete all information from a single table in the database. iTable is
5487** the page number of the root of the table. After this routine returns,
5488** the root page is empty, but still exists.
5489**
5490** This routine will fail with SQLITE_LOCKED if there are any open
5491** read cursors on the table. Open write cursors are moved to the
5492** root of the table.
drh8b2f49b2001-06-08 00:21:52 +00005493*/
danielk1977aef0bf62005-12-30 16:28:01 +00005494int sqlite3BtreeClearTable(Btree *p, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00005495 int rc;
drhf74b8d92002-09-01 23:20:45 +00005496 BtCursor *pCur;
danielk1977aef0bf62005-12-30 16:28:01 +00005497 BtShared *pBt = p->pBt;
5498 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005499 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005500 }
drhf74b8d92002-09-01 23:20:45 +00005501 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
5502 if( pCur->pgnoRoot==(Pgno)iTable ){
5503 if( pCur->wrFlag==0 ) return SQLITE_LOCKED;
5504 moveToRoot(pCur);
5505 }
drhecdc7532001-09-23 02:35:53 +00005506 }
drha34b6762004-05-07 13:30:42 +00005507 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
danielk197771fd80b2005-12-16 06:54:01 +00005508#if 0
drh8b2f49b2001-06-08 00:21:52 +00005509 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00005510 sqlite3BtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00005511 }
danielk197771fd80b2005-12-16 06:54:01 +00005512#endif
drh8c42ca92001-06-22 19:15:00 +00005513 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005514}
5515
5516/*
5517** Erase all information in a table and add the root of the table to
5518** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00005519** page 1) is never added to the freelist.
5520**
5521** This routine will fail with SQLITE_LOCKED if there are any open
5522** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00005523**
5524** If AUTOVACUUM is enabled and the page at iTable is not the last
5525** root page in the database file, then the last root page
5526** in the database file is moved into the slot formerly occupied by
5527** iTable and that last slot formerly occupied by the last root page
5528** is added to the freelist instead of iTable. In this say, all
5529** root pages are kept at the beginning of the database file, which
5530** is necessary for AUTOVACUUM to work right. *piMoved is set to the
5531** page number that used to be the last root page in the file before
5532** the move. If no page gets moved, *piMoved is set to 0.
5533** The last root page is recorded in meta[3] and the value of
5534** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00005535*/
danielk1977aef0bf62005-12-30 16:28:01 +00005536int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00005537 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00005538 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00005539 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00005540
danielk1977aef0bf62005-12-30 16:28:01 +00005541 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005542 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005543 }
danielk1977a0bf2652004-11-04 14:30:04 +00005544
danielk1977e6efa742004-11-10 11:55:10 +00005545 /* It is illegal to drop a table if any cursors are open on the
5546 ** database. This is because in auto-vacuum mode the backend may
5547 ** need to move another root-page to fill a gap left by the deleted
5548 ** root page. If an open cursor was using this page a problem would
5549 ** occur.
5550 */
5551 if( pBt->pCursor ){
5552 return SQLITE_LOCKED;
drh5df72a52002-06-06 23:16:05 +00005553 }
danielk1977a0bf2652004-11-04 14:30:04 +00005554
drha34b6762004-05-07 13:30:42 +00005555 rc = getPage(pBt, (Pgno)iTable, &pPage);
drh2aa679f2001-06-25 02:11:07 +00005556 if( rc ) return rc;
danielk1977aef0bf62005-12-30 16:28:01 +00005557 rc = sqlite3BtreeClearTable(p, iTable);
danielk19776b456a22005-03-21 04:04:02 +00005558 if( rc ){
5559 releasePage(pPage);
5560 return rc;
5561 }
danielk1977a0bf2652004-11-04 14:30:04 +00005562
drh205f48e2004-11-05 00:43:11 +00005563 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00005564
drh4b70f112004-05-02 21:12:19 +00005565 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00005566#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00005567 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00005568 releasePage(pPage);
5569#else
5570 if( pBt->autoVacuum ){
5571 Pgno maxRootPgno;
danielk1977aef0bf62005-12-30 16:28:01 +00005572 rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00005573 if( rc!=SQLITE_OK ){
5574 releasePage(pPage);
5575 return rc;
5576 }
5577
5578 if( iTable==maxRootPgno ){
5579 /* If the table being dropped is the table with the largest root-page
5580 ** number in the database, put the root page on the free list.
5581 */
5582 rc = freePage(pPage);
5583 releasePage(pPage);
5584 if( rc!=SQLITE_OK ){
5585 return rc;
5586 }
5587 }else{
5588 /* The table being dropped does not have the largest root-page
5589 ** number in the database. So move the page that does into the
5590 ** gap left by the deleted root-page.
5591 */
5592 MemPage *pMove;
5593 releasePage(pPage);
5594 rc = getPage(pBt, maxRootPgno, &pMove);
5595 if( rc!=SQLITE_OK ){
5596 return rc;
5597 }
5598 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable);
5599 releasePage(pMove);
5600 if( rc!=SQLITE_OK ){
5601 return rc;
5602 }
5603 rc = getPage(pBt, maxRootPgno, &pMove);
5604 if( rc!=SQLITE_OK ){
5605 return rc;
5606 }
5607 rc = freePage(pMove);
5608 releasePage(pMove);
5609 if( rc!=SQLITE_OK ){
5610 return rc;
5611 }
5612 *piMoved = maxRootPgno;
5613 }
5614
danielk1977599fcba2004-11-08 07:13:13 +00005615 /* Set the new 'max-root-page' value in the database header. This
5616 ** is the old value less one, less one more if that happens to
5617 ** be a root-page number, less one again if that is the
5618 ** PENDING_BYTE_PAGE.
5619 */
danielk197787a6e732004-11-05 12:58:25 +00005620 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00005621 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
5622 maxRootPgno--;
5623 }
drh42cac6d2004-11-20 20:31:11 +00005624 if( maxRootPgno==PTRMAP_PAGENO(pBt->usableSize, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00005625 maxRootPgno--;
5626 }
danielk1977599fcba2004-11-08 07:13:13 +00005627 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
5628
danielk1977aef0bf62005-12-30 16:28:01 +00005629 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00005630 }else{
5631 rc = freePage(pPage);
5632 releasePage(pPage);
5633 }
5634#endif
drh2aa679f2001-06-25 02:11:07 +00005635 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00005636 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00005637 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00005638 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00005639 }
drh8b2f49b2001-06-08 00:21:52 +00005640 return rc;
5641}
5642
drh001bbcb2003-03-19 03:14:00 +00005643
drh8b2f49b2001-06-08 00:21:52 +00005644/*
drh23e11ca2004-05-04 17:27:28 +00005645** Read the meta-information out of a database file. Meta[0]
5646** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00005647** through meta[15] are available for use by higher layers. Meta[0]
5648** is read-only, the others are read/write.
5649**
5650** The schema layer numbers meta values differently. At the schema
5651** layer (and the SetCookie and ReadCookie opcodes) the number of
5652** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00005653*/
danielk1977aef0bf62005-12-30 16:28:01 +00005654int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
drh8b2f49b2001-06-08 00:21:52 +00005655 int rc;
drh4b70f112004-05-02 21:12:19 +00005656 unsigned char *pP1;
danielk1977aef0bf62005-12-30 16:28:01 +00005657 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005658
danielk1977da184232006-01-05 11:34:32 +00005659 /* Reading a meta-data value requires a read-lock on page 1 (and hence
5660 ** the sqlite_master table. We grab this lock regardless of whether or
5661 ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
5662 ** 1 is treated as a special case by queryTableLock() and lockTable()).
5663 */
5664 rc = queryTableLock(p, 1, READ_LOCK);
5665 if( rc!=SQLITE_OK ){
5666 return rc;
5667 }
5668
drh23e11ca2004-05-04 17:27:28 +00005669 assert( idx>=0 && idx<=15 );
drha34b6762004-05-07 13:30:42 +00005670 rc = sqlite3pager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00005671 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00005672 *pMeta = get4byte(&pP1[36 + idx*4]);
drha34b6762004-05-07 13:30:42 +00005673 sqlite3pager_unref(pP1);
drhae157872004-08-14 19:20:09 +00005674
danielk1977599fcba2004-11-08 07:13:13 +00005675 /* If autovacuumed is disabled in this build but we are trying to
5676 ** access an autovacuumed database, then make the database readonly.
5677 */
danielk1977003ba062004-11-04 02:57:33 +00005678#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00005679 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00005680#endif
drhae157872004-08-14 19:20:09 +00005681
danielk1977da184232006-01-05 11:34:32 +00005682 /* Grab the read-lock on page 1. */
5683 rc = lockTable(p, 1, READ_LOCK);
5684 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005685}
5686
5687/*
drh23e11ca2004-05-04 17:27:28 +00005688** Write meta-information back into the database. Meta[0] is
5689** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00005690*/
danielk1977aef0bf62005-12-30 16:28:01 +00005691int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
5692 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00005693 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00005694 int rc;
drh23e11ca2004-05-04 17:27:28 +00005695 assert( idx>=1 && idx<=15 );
danielk1977aef0bf62005-12-30 16:28:01 +00005696 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005697 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +00005698 }
drhde647132004-05-07 17:57:49 +00005699 assert( pBt->pPage1!=0 );
5700 pP1 = pBt->pPage1->aData;
drha34b6762004-05-07 13:30:42 +00005701 rc = sqlite3pager_write(pP1);
drh4b70f112004-05-02 21:12:19 +00005702 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00005703 put4byte(&pP1[36 + idx*4], iMeta);
drh8b2f49b2001-06-08 00:21:52 +00005704 return SQLITE_OK;
5705}
drh8c42ca92001-06-22 19:15:00 +00005706
drhf328bc82004-05-10 23:29:49 +00005707/*
5708** Return the flag byte at the beginning of the page that the cursor
5709** is currently pointing to.
5710*/
5711int sqlite3BtreeFlags(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00005712 /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
5713 ** restoreCursorPosition() here.
5714 */
drhf328bc82004-05-10 23:29:49 +00005715 MemPage *pPage = pCur->pPage;
5716 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
5717}
5718
danielk1977b5402fb2005-01-12 07:15:04 +00005719#ifdef SQLITE_DEBUG
drh8c42ca92001-06-22 19:15:00 +00005720/*
5721** Print a disassembly of the given page on standard output. This routine
5722** is used for debugging and testing only.
5723*/
danielk1977aef0bf62005-12-30 16:28:01 +00005724static int btreePageDump(BtShared *pBt, int pgno, int recursive, MemPage *pParent){
drh8c42ca92001-06-22 19:15:00 +00005725 int rc;
5726 MemPage *pPage;
drhc8629a12004-05-08 20:07:40 +00005727 int i, j, c;
drh8c42ca92001-06-22 19:15:00 +00005728 int nFree;
5729 u16 idx;
drhab9f7f12004-05-08 10:56:11 +00005730 int hdr;
drh43605152004-05-29 21:46:49 +00005731 int nCell;
drha2fce642004-06-05 00:01:44 +00005732 int isInit;
drhab9f7f12004-05-08 10:56:11 +00005733 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00005734 char range[20];
5735 unsigned char payload[20];
drhab9f7f12004-05-08 10:56:11 +00005736
drh4b70f112004-05-02 21:12:19 +00005737 rc = getPage(pBt, (Pgno)pgno, &pPage);
drha2fce642004-06-05 00:01:44 +00005738 isInit = pPage->isInit;
5739 if( pPage->isInit==0 ){
danielk1977c7dc7532004-11-17 10:22:03 +00005740 initPage(pPage, pParent);
drha2fce642004-06-05 00:01:44 +00005741 }
drh8c42ca92001-06-22 19:15:00 +00005742 if( rc ){
5743 return rc;
5744 }
drhab9f7f12004-05-08 10:56:11 +00005745 hdr = pPage->hdrOffset;
5746 data = pPage->aData;
drhc8629a12004-05-08 20:07:40 +00005747 c = data[hdr];
drh8b18dd42004-05-12 19:18:15 +00005748 pPage->intKey = (c & (PTF_INTKEY|PTF_LEAFDATA))!=0;
drhc8629a12004-05-08 20:07:40 +00005749 pPage->zeroData = (c & PTF_ZERODATA)!=0;
drh8b18dd42004-05-12 19:18:15 +00005750 pPage->leafData = (c & PTF_LEAFDATA)!=0;
drhc8629a12004-05-08 20:07:40 +00005751 pPage->leaf = (c & PTF_LEAF)!=0;
drh8b18dd42004-05-12 19:18:15 +00005752 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
drh43605152004-05-29 21:46:49 +00005753 nCell = get2byte(&data[hdr+3]);
drhfe63d1c2004-09-08 20:13:04 +00005754 sqlite3DebugPrintf("PAGE %d: flags=0x%02x frag=%d parent=%d\n", pgno,
drh43605152004-05-29 21:46:49 +00005755 data[hdr], data[hdr+7],
drhda200cc2004-05-09 11:51:38 +00005756 (pPage->isInit && pPage->pParent) ? pPage->pParent->pgno : 0);
drhab9f7f12004-05-08 10:56:11 +00005757 assert( hdr == (pgno==1 ? 100 : 0) );
drh43605152004-05-29 21:46:49 +00005758 idx = hdr + 12 - pPage->leaf*4;
5759 for(i=0; i<nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00005760 CellInfo info;
drh4b70f112004-05-02 21:12:19 +00005761 Pgno child;
drh43605152004-05-29 21:46:49 +00005762 unsigned char *pCell;
drh6f11bef2004-05-13 01:12:56 +00005763 int sz;
drh43605152004-05-29 21:46:49 +00005764 int addr;
drh6f11bef2004-05-13 01:12:56 +00005765
drh43605152004-05-29 21:46:49 +00005766 addr = get2byte(&data[idx + 2*i]);
5767 pCell = &data[addr];
5768 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005769 sz = info.nSize;
drh43605152004-05-29 21:46:49 +00005770 sprintf(range,"%d..%d", addr, addr+sz-1);
drh4b70f112004-05-02 21:12:19 +00005771 if( pPage->leaf ){
5772 child = 0;
5773 }else{
drh43605152004-05-29 21:46:49 +00005774 child = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005775 }
drh6f11bef2004-05-13 01:12:56 +00005776 sz = info.nData;
5777 if( !pPage->intKey ) sz += info.nKey;
drh8c42ca92001-06-22 19:15:00 +00005778 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
drh6f11bef2004-05-13 01:12:56 +00005779 memcpy(payload, &pCell[info.nHeader], sz);
drh8c42ca92001-06-22 19:15:00 +00005780 for(j=0; j<sz; j++){
5781 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
5782 }
5783 payload[sz] = 0;
drhfe63d1c2004-09-08 20:13:04 +00005784 sqlite3DebugPrintf(
drh6f11bef2004-05-13 01:12:56 +00005785 "cell %2d: i=%-10s chld=%-4d nk=%-4lld nd=%-4d payload=%s\n",
5786 i, range, child, info.nKey, info.nData, payload
drh8c42ca92001-06-22 19:15:00 +00005787 );
drh8c42ca92001-06-22 19:15:00 +00005788 }
drh4b70f112004-05-02 21:12:19 +00005789 if( !pPage->leaf ){
drhfe63d1c2004-09-08 20:13:04 +00005790 sqlite3DebugPrintf("right_child: %d\n", get4byte(&data[hdr+8]));
drh4b70f112004-05-02 21:12:19 +00005791 }
drh8c42ca92001-06-22 19:15:00 +00005792 nFree = 0;
5793 i = 0;
drhab9f7f12004-05-08 10:56:11 +00005794 idx = get2byte(&data[hdr+1]);
drhb6f41482004-05-14 01:58:11 +00005795 while( idx>0 && idx<pPage->pBt->usableSize ){
drhab9f7f12004-05-08 10:56:11 +00005796 int sz = get2byte(&data[idx+2]);
drh4b70f112004-05-02 21:12:19 +00005797 sprintf(range,"%d..%d", idx, idx+sz-1);
5798 nFree += sz;
drhfe63d1c2004-09-08 20:13:04 +00005799 sqlite3DebugPrintf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
drh4b70f112004-05-02 21:12:19 +00005800 i, range, sz, nFree);
drhab9f7f12004-05-08 10:56:11 +00005801 idx = get2byte(&data[idx]);
drh2aa679f2001-06-25 02:11:07 +00005802 i++;
drh8c42ca92001-06-22 19:15:00 +00005803 }
5804 if( idx!=0 ){
drhfe63d1c2004-09-08 20:13:04 +00005805 sqlite3DebugPrintf("ERROR: next freeblock index out of range: %d\n", idx);
drh8c42ca92001-06-22 19:15:00 +00005806 }
drha34b6762004-05-07 13:30:42 +00005807 if( recursive && !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005808 for(i=0; i<nCell; i++){
5809 unsigned char *pCell = findCell(pPage, i);
danielk1977c7dc7532004-11-17 10:22:03 +00005810 btreePageDump(pBt, get4byte(pCell), 1, pPage);
drha34b6762004-05-07 13:30:42 +00005811 idx = get2byte(pCell);
drh6019e162001-07-02 17:51:45 +00005812 }
danielk1977c7dc7532004-11-17 10:22:03 +00005813 btreePageDump(pBt, get4byte(&data[hdr+8]), 1, pPage);
drh6019e162001-07-02 17:51:45 +00005814 }
drha2fce642004-06-05 00:01:44 +00005815 pPage->isInit = isInit;
drhab9f7f12004-05-08 10:56:11 +00005816 sqlite3pager_unref(data);
drh3644f082004-05-10 18:45:09 +00005817 fflush(stdout);
drh8c42ca92001-06-22 19:15:00 +00005818 return SQLITE_OK;
5819}
danielk1977aef0bf62005-12-30 16:28:01 +00005820int sqlite3BtreePageDump(Btree *p, int pgno, int recursive){
5821 return btreePageDump(p->pBt, pgno, recursive, 0);
danielk1977c7dc7532004-11-17 10:22:03 +00005822}
drhaaab5722002-02-19 13:39:21 +00005823#endif
drh8c42ca92001-06-22 19:15:00 +00005824
drhaaab5722002-02-19 13:39:21 +00005825#ifdef SQLITE_TEST
drh8c42ca92001-06-22 19:15:00 +00005826/*
drh2aa679f2001-06-25 02:11:07 +00005827** Fill aResult[] with information about the entry and page that the
5828** cursor is pointing to.
5829**
5830** aResult[0] = The page number
5831** aResult[1] = The entry number
5832** aResult[2] = Total number of entries on this page
drh3e27c022004-07-23 00:01:38 +00005833** aResult[3] = Cell size (local payload + header)
drh2aa679f2001-06-25 02:11:07 +00005834** aResult[4] = Number of free bytes on this page
5835** aResult[5] = Number of free blocks on the page
drh3e27c022004-07-23 00:01:38 +00005836** aResult[6] = Total payload size (local + overflow)
5837** aResult[7] = Header size in bytes
5838** aResult[8] = Local payload size
5839** aResult[9] = Parent page number
drh5eddca62001-06-30 21:53:53 +00005840**
5841** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00005842*/
drh3e27c022004-07-23 00:01:38 +00005843int sqlite3BtreeCursorInfo(BtCursor *pCur, int *aResult, int upCnt){
drh2aa679f2001-06-25 02:11:07 +00005844 int cnt, idx;
5845 MemPage *pPage = pCur->pPage;
drh3e27c022004-07-23 00:01:38 +00005846 BtCursor tmpCur;
drhda200cc2004-05-09 11:51:38 +00005847
danielk1977da184232006-01-05 11:34:32 +00005848 int rc = restoreCursorPosition(pCur, 1);
5849 if( rc!=SQLITE_OK ){
5850 return rc;
5851 }
5852
drhda200cc2004-05-09 11:51:38 +00005853 pageIntegrity(pPage);
drh4b70f112004-05-02 21:12:19 +00005854 assert( pPage->isInit );
drh3e27c022004-07-23 00:01:38 +00005855 getTempCursor(pCur, &tmpCur);
5856 while( upCnt-- ){
5857 moveToParent(&tmpCur);
5858 }
5859 pPage = tmpCur.pPage;
5860 pageIntegrity(pPage);
drha34b6762004-05-07 13:30:42 +00005861 aResult[0] = sqlite3pager_pagenumber(pPage->aData);
drh91025292004-05-03 19:49:32 +00005862 assert( aResult[0]==pPage->pgno );
drh3e27c022004-07-23 00:01:38 +00005863 aResult[1] = tmpCur.idx;
drh2aa679f2001-06-25 02:11:07 +00005864 aResult[2] = pPage->nCell;
drh3e27c022004-07-23 00:01:38 +00005865 if( tmpCur.idx>=0 && tmpCur.idx<pPage->nCell ){
5866 getCellInfo(&tmpCur);
5867 aResult[3] = tmpCur.info.nSize;
5868 aResult[6] = tmpCur.info.nData;
5869 aResult[7] = tmpCur.info.nHeader;
5870 aResult[8] = tmpCur.info.nLocal;
drh2aa679f2001-06-25 02:11:07 +00005871 }else{
5872 aResult[3] = 0;
5873 aResult[6] = 0;
drh3e27c022004-07-23 00:01:38 +00005874 aResult[7] = 0;
5875 aResult[8] = 0;
drh2aa679f2001-06-25 02:11:07 +00005876 }
5877 aResult[4] = pPage->nFree;
5878 cnt = 0;
drh4b70f112004-05-02 21:12:19 +00005879 idx = get2byte(&pPage->aData[pPage->hdrOffset+1]);
drhb6f41482004-05-14 01:58:11 +00005880 while( idx>0 && idx<pPage->pBt->usableSize ){
drh2aa679f2001-06-25 02:11:07 +00005881 cnt++;
drh4b70f112004-05-02 21:12:19 +00005882 idx = get2byte(&pPage->aData[idx]);
drh2aa679f2001-06-25 02:11:07 +00005883 }
5884 aResult[5] = cnt;
drh3e27c022004-07-23 00:01:38 +00005885 if( pPage->pParent==0 || isRootPage(pPage) ){
5886 aResult[9] = 0;
5887 }else{
5888 aResult[9] = pPage->pParent->pgno;
5889 }
5890 releaseTempCursor(&tmpCur);
drh8c42ca92001-06-22 19:15:00 +00005891 return SQLITE_OK;
5892}
drhaaab5722002-02-19 13:39:21 +00005893#endif
drhdd793422001-06-28 01:54:48 +00005894
drhdd793422001-06-28 01:54:48 +00005895/*
drh5eddca62001-06-30 21:53:53 +00005896** Return the pager associated with a BTree. This routine is used for
5897** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00005898*/
danielk1977aef0bf62005-12-30 16:28:01 +00005899Pager *sqlite3BtreePager(Btree *p){
5900 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00005901}
drh5eddca62001-06-30 21:53:53 +00005902
5903/*
5904** This structure is passed around through all the sanity checking routines
5905** in order to keep track of some global state information.
5906*/
drhaaab5722002-02-19 13:39:21 +00005907typedef struct IntegrityCk IntegrityCk;
5908struct IntegrityCk {
danielk1977aef0bf62005-12-30 16:28:01 +00005909 BtShared *pBt; /* The tree being checked out */
drh100569d2001-10-02 13:01:48 +00005910 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
5911 int nPage; /* Number of pages in the database */
5912 int *anRef; /* Number of times each page is referenced */
drh100569d2001-10-02 13:01:48 +00005913 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00005914};
5915
drhb7f91642004-10-31 02:22:47 +00005916#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005917/*
5918** Append a message to the error message string.
5919*/
drh2e38c322004-09-03 18:38:44 +00005920static void checkAppendMsg(
5921 IntegrityCk *pCheck,
5922 char *zMsg1,
5923 const char *zFormat,
5924 ...
5925){
5926 va_list ap;
5927 char *zMsg2;
5928 va_start(ap, zFormat);
5929 zMsg2 = sqlite3VMPrintf(zFormat, ap);
5930 va_end(ap);
5931 if( zMsg1==0 ) zMsg1 = "";
drh5eddca62001-06-30 21:53:53 +00005932 if( pCheck->zErrMsg ){
5933 char *zOld = pCheck->zErrMsg;
5934 pCheck->zErrMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00005935 sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00005936 sqliteFree(zOld);
5937 }else{
danielk19774adee202004-05-08 08:23:19 +00005938 sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00005939 }
drh2e38c322004-09-03 18:38:44 +00005940 sqliteFree(zMsg2);
drh5eddca62001-06-30 21:53:53 +00005941}
drhb7f91642004-10-31 02:22:47 +00005942#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005943
drhb7f91642004-10-31 02:22:47 +00005944#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005945/*
5946** Add 1 to the reference count for page iPage. If this is the second
5947** reference to the page, add an error message to pCheck->zErrMsg.
5948** Return 1 if there are 2 ore more references to the page and 0 if
5949** if this is the first reference to the page.
5950**
5951** Also check that the page number is in bounds.
5952*/
drhaaab5722002-02-19 13:39:21 +00005953static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00005954 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00005955 if( iPage>pCheck->nPage || iPage<0 ){
drh2e38c322004-09-03 18:38:44 +00005956 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005957 return 1;
5958 }
5959 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00005960 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005961 return 1;
5962 }
5963 return (pCheck->anRef[iPage]++)>1;
5964}
5965
danielk1977afcdd022004-10-31 16:25:42 +00005966#ifndef SQLITE_OMIT_AUTOVACUUM
5967/*
5968** Check that the entry in the pointer-map for page iChild maps to
5969** page iParent, pointer type ptrType. If not, append an error message
5970** to pCheck.
5971*/
5972static void checkPtrmap(
5973 IntegrityCk *pCheck, /* Integrity check context */
5974 Pgno iChild, /* Child page number */
5975 u8 eType, /* Expected pointer map type */
5976 Pgno iParent, /* Expected pointer map parent page number */
5977 char *zContext /* Context description (used for error msg) */
5978){
5979 int rc;
5980 u8 ePtrmapType;
5981 Pgno iPtrmapParent;
5982
5983 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
5984 if( rc!=SQLITE_OK ){
5985 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
5986 return;
5987 }
5988
5989 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
5990 checkAppendMsg(pCheck, zContext,
5991 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
5992 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
5993 }
5994}
5995#endif
5996
drh5eddca62001-06-30 21:53:53 +00005997/*
5998** Check the integrity of the freelist or of an overflow page list.
5999** Verify that the number of pages on the list is N.
6000*/
drh30e58752002-03-02 20:41:57 +00006001static void checkList(
6002 IntegrityCk *pCheck, /* Integrity checking context */
6003 int isFreeList, /* True for a freelist. False for overflow page list */
6004 int iPage, /* Page number for first page in the list */
6005 int N, /* Expected number of pages in the list */
6006 char *zContext /* Context for error messages */
6007){
6008 int i;
drh3a4c1412004-05-09 20:40:11 +00006009 int expected = N;
6010 int iFirst = iPage;
drh30e58752002-03-02 20:41:57 +00006011 while( N-- > 0 ){
drh4b70f112004-05-02 21:12:19 +00006012 unsigned char *pOvfl;
drh5eddca62001-06-30 21:53:53 +00006013 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00006014 checkAppendMsg(pCheck, zContext,
6015 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00006016 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00006017 break;
6018 }
6019 if( checkRef(pCheck, iPage, zContext) ) break;
drha34b6762004-05-07 13:30:42 +00006020 if( sqlite3pager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
drh2e38c322004-09-03 18:38:44 +00006021 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006022 break;
6023 }
drh30e58752002-03-02 20:41:57 +00006024 if( isFreeList ){
drh4b70f112004-05-02 21:12:19 +00006025 int n = get4byte(&pOvfl[4]);
danielk1977687566d2004-11-02 12:56:41 +00006026#ifndef SQLITE_OMIT_AUTOVACUUM
6027 if( pCheck->pBt->autoVacuum ){
6028 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
6029 }
6030#endif
drh855eb1c2004-08-31 13:45:11 +00006031 if( n>pCheck->pBt->usableSize/4-8 ){
drh2e38c322004-09-03 18:38:44 +00006032 checkAppendMsg(pCheck, zContext,
6033 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00006034 N--;
6035 }else{
6036 for(i=0; i<n; i++){
danielk1977687566d2004-11-02 12:56:41 +00006037 Pgno iFreePage = get4byte(&pOvfl[8+i*4]);
6038#ifndef SQLITE_OMIT_AUTOVACUUM
6039 if( pCheck->pBt->autoVacuum ){
6040 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
6041 }
6042#endif
6043 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00006044 }
6045 N -= n;
drh30e58752002-03-02 20:41:57 +00006046 }
drh30e58752002-03-02 20:41:57 +00006047 }
danielk1977afcdd022004-10-31 16:25:42 +00006048#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006049 else{
6050 /* If this database supports auto-vacuum and iPage is not the last
6051 ** page in this overflow list, check that the pointer-map entry for
6052 ** the following page matches iPage.
6053 */
6054 if( pCheck->pBt->autoVacuum && N>0 ){
6055 i = get4byte(pOvfl);
6056 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
6057 }
danielk1977afcdd022004-10-31 16:25:42 +00006058 }
6059#endif
drh4b70f112004-05-02 21:12:19 +00006060 iPage = get4byte(pOvfl);
drha34b6762004-05-07 13:30:42 +00006061 sqlite3pager_unref(pOvfl);
drh5eddca62001-06-30 21:53:53 +00006062 }
6063}
drhb7f91642004-10-31 02:22:47 +00006064#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006065
drhb7f91642004-10-31 02:22:47 +00006066#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006067/*
6068** Do various sanity checks on a single page of a tree. Return
6069** the tree depth. Root pages return 0. Parents of root pages
6070** return 1, and so forth.
6071**
6072** These checks are done:
6073**
6074** 1. Make sure that cells and freeblocks do not overlap
6075** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00006076** NO 2. Make sure cell keys are in order.
6077** NO 3. Make sure no key is less than or equal to zLowerBound.
6078** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00006079** 5. Check the integrity of overflow pages.
6080** 6. Recursively call checkTreePage on all children.
6081** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00006082** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00006083** the root of the tree.
6084*/
6085static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00006086 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00006087 int iPage, /* Page number of the page to check */
6088 MemPage *pParent, /* Parent page */
6089 char *zParentContext, /* Parent context */
6090 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00006091 int nLower, /* Number of characters in zLowerBound */
6092 char *zUpperBound, /* All keys should be less than this, if not NULL */
6093 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00006094){
6095 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00006096 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00006097 int hdr, cellStart;
6098 int nCell;
drhda200cc2004-05-09 11:51:38 +00006099 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00006100 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00006101 int usableSize;
drh5eddca62001-06-30 21:53:53 +00006102 char zContext[100];
drh2e38c322004-09-03 18:38:44 +00006103 char *hit;
drh5eddca62001-06-30 21:53:53 +00006104
danielk1977ef73ee92004-11-06 12:26:07 +00006105 sprintf(zContext, "Page %d: ", iPage);
6106
drh5eddca62001-06-30 21:53:53 +00006107 /* Check that the page exists
6108 */
drhd9cb6ac2005-10-20 07:28:17 +00006109 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00006110 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00006111 if( iPage==0 ) return 0;
6112 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh4b70f112004-05-02 21:12:19 +00006113 if( (rc = getPage(pBt, (Pgno)iPage, &pPage))!=0 ){
drh2e38c322004-09-03 18:38:44 +00006114 checkAppendMsg(pCheck, zContext,
6115 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00006116 return 0;
6117 }
drh4b70f112004-05-02 21:12:19 +00006118 if( (rc = initPage(pPage, pParent))!=0 ){
drh2e38c322004-09-03 18:38:44 +00006119 checkAppendMsg(pCheck, zContext, "initPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00006120 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00006121 return 0;
6122 }
6123
6124 /* Check out all the cells.
6125 */
6126 depth = 0;
drh5eddca62001-06-30 21:53:53 +00006127 for(i=0; i<pPage->nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00006128 u8 *pCell;
6129 int sz;
6130 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00006131
6132 /* Check payload overflow pages
6133 */
drh3a4c1412004-05-09 20:40:11 +00006134 sprintf(zContext, "On tree page %d cell %d: ", iPage, i);
drh43605152004-05-29 21:46:49 +00006135 pCell = findCell(pPage,i);
6136 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00006137 sz = info.nData;
6138 if( !pPage->intKey ) sz += info.nKey;
6139 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00006140 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00006141 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
6142#ifndef SQLITE_OMIT_AUTOVACUUM
6143 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006144 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00006145 }
6146#endif
6147 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00006148 }
6149
6150 /* Check sanity of left child page.
6151 */
drhda200cc2004-05-09 11:51:38 +00006152 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006153 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00006154#ifndef SQLITE_OMIT_AUTOVACUUM
6155 if( pBt->autoVacuum ){
6156 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
6157 }
6158#endif
drhda200cc2004-05-09 11:51:38 +00006159 d2 = checkTreePage(pCheck,pgno,pPage,zContext,0,0,0,0);
6160 if( i>0 && d2!=depth ){
6161 checkAppendMsg(pCheck, zContext, "Child page depth differs");
6162 }
6163 depth = d2;
drh5eddca62001-06-30 21:53:53 +00006164 }
drh5eddca62001-06-30 21:53:53 +00006165 }
drhda200cc2004-05-09 11:51:38 +00006166 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006167 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drhda200cc2004-05-09 11:51:38 +00006168 sprintf(zContext, "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00006169#ifndef SQLITE_OMIT_AUTOVACUUM
6170 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006171 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00006172 }
6173#endif
drhda200cc2004-05-09 11:51:38 +00006174 checkTreePage(pCheck, pgno, pPage, zContext,0,0,0,0);
6175 }
drh5eddca62001-06-30 21:53:53 +00006176
6177 /* Check for complete coverage of the page
6178 */
drhda200cc2004-05-09 11:51:38 +00006179 data = pPage->aData;
6180 hdr = pPage->hdrOffset;
drh2e38c322004-09-03 18:38:44 +00006181 hit = sqliteMalloc( usableSize );
6182 if( hit ){
6183 memset(hit, 1, get2byte(&data[hdr+5]));
6184 nCell = get2byte(&data[hdr+3]);
6185 cellStart = hdr + 12 - 4*pPage->leaf;
6186 for(i=0; i<nCell; i++){
6187 int pc = get2byte(&data[cellStart+i*2]);
6188 int size = cellSizePtr(pPage, &data[pc]);
6189 int j;
danielk19777701e812005-01-10 12:59:51 +00006190 if( (pc+size-1)>=usableSize || pc<0 ){
6191 checkAppendMsg(pCheck, 0,
6192 "Corruption detected in cell %d on page %d",i,iPage,0);
6193 }else{
6194 for(j=pc+size-1; j>=pc; j--) hit[j]++;
6195 }
drh2e38c322004-09-03 18:38:44 +00006196 }
6197 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
6198 cnt++){
6199 int size = get2byte(&data[i+2]);
6200 int j;
danielk19777701e812005-01-10 12:59:51 +00006201 if( (i+size-1)>=usableSize || i<0 ){
6202 checkAppendMsg(pCheck, 0,
6203 "Corruption detected in cell %d on page %d",i,iPage,0);
6204 }else{
6205 for(j=i+size-1; j>=i; j--) hit[j]++;
6206 }
drh2e38c322004-09-03 18:38:44 +00006207 i = get2byte(&data[i]);
6208 }
6209 for(i=cnt=0; i<usableSize; i++){
6210 if( hit[i]==0 ){
6211 cnt++;
6212 }else if( hit[i]>1 ){
6213 checkAppendMsg(pCheck, 0,
6214 "Multiple uses for byte %d of page %d", i, iPage);
6215 break;
6216 }
6217 }
6218 if( cnt!=data[hdr+7] ){
6219 checkAppendMsg(pCheck, 0,
6220 "Fragmented space is %d byte reported as %d on page %d",
6221 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00006222 }
6223 }
drh2e38c322004-09-03 18:38:44 +00006224 sqliteFree(hit);
drh6019e162001-07-02 17:51:45 +00006225
drh4b70f112004-05-02 21:12:19 +00006226 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00006227 return depth+1;
drh5eddca62001-06-30 21:53:53 +00006228}
drhb7f91642004-10-31 02:22:47 +00006229#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006230
drhb7f91642004-10-31 02:22:47 +00006231#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006232/*
6233** This routine does a complete check of the given BTree file. aRoot[] is
6234** an array of pages numbers were each page number is the root page of
6235** a table. nRoot is the number of entries in aRoot.
6236**
6237** If everything checks out, this routine returns NULL. If something is
6238** amiss, an error message is written into memory obtained from malloc()
6239** and a pointer to that error message is returned. The calling function
6240** is responsible for freeing the error message when it is done.
6241*/
danielk1977aef0bf62005-12-30 16:28:01 +00006242char *sqlite3BtreeIntegrityCheck(Btree *p, int *aRoot, int nRoot){
drh5eddca62001-06-30 21:53:53 +00006243 int i;
6244 int nRef;
drhaaab5722002-02-19 13:39:21 +00006245 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00006246 BtShared *pBt = p->pBt;
drh5eddca62001-06-30 21:53:53 +00006247
drha34b6762004-05-07 13:30:42 +00006248 nRef = *sqlite3pager_stats(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00006249 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
drhefc251d2001-07-01 22:12:01 +00006250 return sqliteStrDup("Unable to acquire a read lock on the database");
6251 }
drh5eddca62001-06-30 21:53:53 +00006252 sCheck.pBt = pBt;
6253 sCheck.pPager = pBt->pPager;
drha34b6762004-05-07 13:30:42 +00006254 sCheck.nPage = sqlite3pager_pagecount(sCheck.pPager);
drh0de8c112002-07-06 16:32:14 +00006255 if( sCheck.nPage==0 ){
6256 unlockBtreeIfUnused(pBt);
6257 return 0;
6258 }
drh8c1238a2003-01-02 14:43:55 +00006259 sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00006260 if( !sCheck.anRef ){
6261 unlockBtreeIfUnused(pBt);
6262 return sqlite3MPrintf("Unable to malloc %d bytes",
6263 (sCheck.nPage+1)*sizeof(sCheck.anRef[0]));
6264 }
drhda200cc2004-05-09 11:51:38 +00006265 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00006266 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00006267 if( i<=sCheck.nPage ){
6268 sCheck.anRef[i] = 1;
6269 }
drh5eddca62001-06-30 21:53:53 +00006270 sCheck.zErrMsg = 0;
6271
6272 /* Check the integrity of the freelist
6273 */
drha34b6762004-05-07 13:30:42 +00006274 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
6275 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00006276
6277 /* Check all the tables.
6278 */
6279 for(i=0; i<nRoot; i++){
drh4ff6dfa2002-03-03 23:06:00 +00006280 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00006281#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006282 if( pBt->autoVacuum && aRoot[i]>1 ){
6283 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
6284 }
6285#endif
drh1bffb9c2002-02-03 17:37:36 +00006286 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00006287 }
6288
6289 /* Make sure every page in the file is referenced
6290 */
6291 for(i=1; i<=sCheck.nPage; i++){
danielk1977afcdd022004-10-31 16:25:42 +00006292#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00006293 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00006294 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00006295 }
danielk1977afcdd022004-10-31 16:25:42 +00006296#else
6297 /* If the database supports auto-vacuum, make sure no tables contain
6298 ** references to pointer-map pages.
6299 */
6300 if( sCheck.anRef[i]==0 &&
drh42cac6d2004-11-20 20:31:11 +00006301 (PTRMAP_PAGENO(pBt->usableSize, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006302 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
6303 }
6304 if( sCheck.anRef[i]!=0 &&
drh42cac6d2004-11-20 20:31:11 +00006305 (PTRMAP_PAGENO(pBt->usableSize, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006306 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
6307 }
6308#endif
drh5eddca62001-06-30 21:53:53 +00006309 }
6310
6311 /* Make sure this analysis did not leave any unref() pages
6312 */
drh5e00f6c2001-09-13 13:46:56 +00006313 unlockBtreeIfUnused(pBt);
drha34b6762004-05-07 13:30:42 +00006314 if( nRef != *sqlite3pager_stats(pBt->pPager) ){
drh2e38c322004-09-03 18:38:44 +00006315 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00006316 "Outstanding page count goes from %d to %d during this analysis",
drha34b6762004-05-07 13:30:42 +00006317 nRef, *sqlite3pager_stats(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00006318 );
drh5eddca62001-06-30 21:53:53 +00006319 }
6320
6321 /* Clean up and report errors.
6322 */
6323 sqliteFree(sCheck.anRef);
6324 return sCheck.zErrMsg;
6325}
drhb7f91642004-10-31 02:22:47 +00006326#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00006327
drh73509ee2003-04-06 20:44:45 +00006328/*
6329** Return the full pathname of the underlying database file.
6330*/
danielk1977aef0bf62005-12-30 16:28:01 +00006331const char *sqlite3BtreeGetFilename(Btree *p){
6332 assert( p->pBt->pPager!=0 );
6333 return sqlite3pager_filename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00006334}
6335
6336/*
danielk19775865e3d2004-06-14 06:03:57 +00006337** Return the pathname of the directory that contains the database file.
6338*/
danielk1977aef0bf62005-12-30 16:28:01 +00006339const char *sqlite3BtreeGetDirname(Btree *p){
6340 assert( p->pBt->pPager!=0 );
6341 return sqlite3pager_dirname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006342}
6343
6344/*
6345** Return the pathname of the journal file for this database. The return
6346** value of this routine is the same regardless of whether the journal file
6347** has been created or not.
6348*/
danielk1977aef0bf62005-12-30 16:28:01 +00006349const char *sqlite3BtreeGetJournalname(Btree *p){
6350 assert( p->pBt->pPager!=0 );
6351 return sqlite3pager_journalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006352}
6353
drhb7f91642004-10-31 02:22:47 +00006354#ifndef SQLITE_OMIT_VACUUM
danielk19775865e3d2004-06-14 06:03:57 +00006355/*
drhf7c57532003-04-25 13:22:51 +00006356** Copy the complete content of pBtFrom into pBtTo. A transaction
6357** must be active for both files.
6358**
6359** The size of file pBtFrom may be reduced by this operation.
drh43605152004-05-29 21:46:49 +00006360** If anything goes wrong, the transaction on pBtFrom is rolled back.
drh73509ee2003-04-06 20:44:45 +00006361*/
danielk1977aef0bf62005-12-30 16:28:01 +00006362int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
drhf7c57532003-04-25 13:22:51 +00006363 int rc = SQLITE_OK;
drh50f2f432005-09-16 11:32:18 +00006364 Pgno i, nPage, nToPage, iSkip;
drhf7c57532003-04-25 13:22:51 +00006365
danielk1977aef0bf62005-12-30 16:28:01 +00006366 BtShared *pBtTo = pTo->pBt;
6367 BtShared *pBtFrom = pFrom->pBt;
6368
6369 if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
danielk1977ee5741e2004-05-31 10:01:34 +00006370 return SQLITE_ERROR;
6371 }
drhf7c57532003-04-25 13:22:51 +00006372 if( pBtTo->pCursor ) return SQLITE_BUSY;
drha34b6762004-05-07 13:30:42 +00006373 nToPage = sqlite3pager_pagecount(pBtTo->pPager);
6374 nPage = sqlite3pager_pagecount(pBtFrom->pPager);
drh50f2f432005-09-16 11:32:18 +00006375 iSkip = PENDING_BYTE_PAGE(pBtTo);
danielk1977369f27e2004-06-15 11:40:04 +00006376 for(i=1; rc==SQLITE_OK && i<=nPage; i++){
drhf7c57532003-04-25 13:22:51 +00006377 void *pPage;
drh50f2f432005-09-16 11:32:18 +00006378 if( i==iSkip ) continue;
drha34b6762004-05-07 13:30:42 +00006379 rc = sqlite3pager_get(pBtFrom->pPager, i, &pPage);
drhf7c57532003-04-25 13:22:51 +00006380 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00006381 rc = sqlite3pager_overwrite(pBtTo->pPager, i, pPage);
drh2e6d11b2003-04-25 15:37:57 +00006382 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00006383 sqlite3pager_unref(pPage);
drhf7c57532003-04-25 13:22:51 +00006384 }
drh2e6d11b2003-04-25 15:37:57 +00006385 for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
6386 void *pPage;
drh49285702005-09-17 15:20:26 +00006387 if( i==iSkip ) continue;
drha34b6762004-05-07 13:30:42 +00006388 rc = sqlite3pager_get(pBtTo->pPager, i, &pPage);
drh2e6d11b2003-04-25 15:37:57 +00006389 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00006390 rc = sqlite3pager_write(pPage);
6391 sqlite3pager_unref(pPage);
6392 sqlite3pager_dont_write(pBtTo->pPager, i);
drh2e6d11b2003-04-25 15:37:57 +00006393 }
6394 if( !rc && nPage<nToPage ){
drha34b6762004-05-07 13:30:42 +00006395 rc = sqlite3pager_truncate(pBtTo->pPager, nPage);
drh2e6d11b2003-04-25 15:37:57 +00006396 }
drhf7c57532003-04-25 13:22:51 +00006397 if( rc ){
danielk1977aef0bf62005-12-30 16:28:01 +00006398 sqlite3BtreeRollback(pTo);
drhf7c57532003-04-25 13:22:51 +00006399 }
6400 return rc;
drh73509ee2003-04-06 20:44:45 +00006401}
drhb7f91642004-10-31 02:22:47 +00006402#endif /* SQLITE_OMIT_VACUUM */
danielk19771d850a72004-05-31 08:26:49 +00006403
6404/*
6405** Return non-zero if a transaction is active.
6406*/
danielk1977aef0bf62005-12-30 16:28:01 +00006407int sqlite3BtreeIsInTrans(Btree *p){
6408 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00006409}
6410
6411/*
6412** Return non-zero if a statement transaction is active.
6413*/
danielk1977aef0bf62005-12-30 16:28:01 +00006414int sqlite3BtreeIsInStmt(Btree *p){
6415 return (p->pBt && p->pBt->inStmt);
danielk19771d850a72004-05-31 08:26:49 +00006416}
danielk197713adf8a2004-06-03 16:08:41 +00006417
6418/*
6419** This call is a no-op if no write-transaction is currently active on pBt.
6420**
6421** Otherwise, sync the database file for the btree pBt. zMaster points to
6422** the name of a master journal file that should be written into the
6423** individual journal file, or is NULL, indicating no master journal file
6424** (single database transaction).
6425**
6426** When this is called, the master journal should already have been
6427** created, populated with this journal pointer and synced to disk.
6428**
6429** Once this is routine has returned, the only thing required to commit
6430** the write-transaction for this database file is to delete the journal.
6431*/
danielk1977aef0bf62005-12-30 16:28:01 +00006432int sqlite3BtreeSync(Btree *p, const char *zMaster){
6433 if( p->inTrans==TRANS_WRITE ){
6434 BtShared *pBt = p->pBt;
danielk1977687566d2004-11-02 12:56:41 +00006435#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977d761c0c2004-11-05 16:37:02 +00006436 Pgno nTrunc = 0;
danielk1977687566d2004-11-02 12:56:41 +00006437 if( pBt->autoVacuum ){
danielk1977d761c0c2004-11-05 16:37:02 +00006438 int rc = autoVacuumCommit(pBt, &nTrunc);
danielk1977687566d2004-11-02 12:56:41 +00006439 if( rc!=SQLITE_OK ) return rc;
6440 }
danielk1977d761c0c2004-11-05 16:37:02 +00006441 return sqlite3pager_sync(pBt->pPager, zMaster, nTrunc);
danielk1977687566d2004-11-02 12:56:41 +00006442#endif
danielk1977d761c0c2004-11-05 16:37:02 +00006443 return sqlite3pager_sync(pBt->pPager, zMaster, 0);
danielk197713adf8a2004-06-03 16:08:41 +00006444 }
6445 return SQLITE_OK;
6446}
danielk1977aef0bf62005-12-30 16:28:01 +00006447
danielk1977da184232006-01-05 11:34:32 +00006448/*
6449** This function returns a pointer to a blob of memory associated with
6450** a single shared-btree. The memory is used by client code for it's own
6451** purposes (for example, to store a high-level schema associated with
6452** the shared-btree). The btree layer manages reference counting issues.
6453**
6454** The first time this is called on a shared-btree, nBytes bytes of memory
6455** are allocated, zeroed, and returned to the caller. For each subsequent
6456** call the nBytes parameter is ignored and a pointer to the same blob
6457** of memory returned.
6458**
6459** Just before the shared-btree is closed, the function passed as the
6460** xFree argument when the memory allocation was made is invoked on the
6461** blob of allocated memory. This function should not call sqliteFree()
6462** on the memory, the btree layer does that.
6463*/
6464void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
6465 BtShared *pBt = p->pBt;
6466 if( !pBt->pSchema ){
6467 pBt->pSchema = sqliteMalloc(nBytes);
6468 pBt->xFreeSchema = xFree;
6469 }
6470 return pBt->pSchema;
6471}
6472
danielk1977c87d34d2006-01-06 13:00:28 +00006473/*
6474** Return true if another user of the same shared btree as the argument
6475** handle holds an exclusive lock on the sqlite_master table.
6476*/
6477int sqlite3BtreeSchemaLocked(Btree *p){
6478 return (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
6479}
6480
danielk1977c00da102006-01-07 13:21:04 +00006481int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
6482 u8 lockType = (isWriteLock?WRITE_LOCK:READ_LOCK);
6483 int rc = queryTableLock(p, iTab, lockType);
6484 if( rc==SQLITE_OK ){
6485 rc = lockTable(p, iTab, lockType);
6486 }
6487 return rc;
6488}
6489
danielk1977aef0bf62005-12-30 16:28:01 +00006490#ifndef SQLITE_OMIT_SHARED_CACHE
6491/*
6492** Enable the shared pager and schema features.
6493*/
6494int sqlite3_enable_shared_cache(int enable){
6495 SqliteTsd *pTsd = sqlite3Tsd();
6496 if( pTsd->pPager ){
6497 return SQLITE_MISUSE;
6498 }
6499 pTsd->useSharedData = enable;
6500 return SQLITE_OK;
6501}
6502#endif