blob: 895d075648499218b1fdd04af0acea6a58fcab4c [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*************************************************************************
danielk19772b8c13e2006-01-24 14:21:24 +000012** $Id: btree.c,v 1.310 2006/01/24 14:21:24 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 */
danielk1977aef0bf62005-12-30 16:28:01 +0000348 int nRef; /* Number of references to this structure */
349 int nTransaction; /* Number of open transactions (read + write) */
danielk19772e94d4d2006-01-09 05:36:27 +0000350 void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
351 void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
352#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000353 BtLock *pLock; /* List of locks held on this shared-btree struct */
danielk1977e501b892006-01-09 06:29:47 +0000354 BtShared *pNext; /* Next in ThreadData.pBtree linked list */
danielk19772e94d4d2006-01-09 05:36:27 +0000355#endif
drha059ad02001-04-17 20:09:11 +0000356};
danielk1977ee5741e2004-05-31 10:01:34 +0000357
358/*
drhfa1a98a2004-05-14 19:08:17 +0000359** An instance of the following structure is used to hold information
drh271efa52004-05-30 19:19:05 +0000360** about a cell. The parseCellPtr() function fills in this structure
drhab01f612004-05-22 02:55:23 +0000361** based on information extract from the raw disk page.
drhfa1a98a2004-05-14 19:08:17 +0000362*/
363typedef struct CellInfo CellInfo;
364struct CellInfo {
drh43605152004-05-29 21:46:49 +0000365 u8 *pCell; /* Pointer to the start of cell content */
drhfa1a98a2004-05-14 19:08:17 +0000366 i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
367 u32 nData; /* Number of bytes of data */
drh271efa52004-05-30 19:19:05 +0000368 u16 nHeader; /* Size of the cell content header in bytes */
drhfa1a98a2004-05-14 19:08:17 +0000369 u16 nLocal; /* Amount of payload held locally */
drhab01f612004-05-22 02:55:23 +0000370 u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
drh271efa52004-05-30 19:19:05 +0000371 u16 nSize; /* Size of the cell content on the main b-tree page */
drhfa1a98a2004-05-14 19:08:17 +0000372};
373
374/*
drh365d68f2001-05-11 11:02:46 +0000375** A cursor is a pointer to a particular entry in the BTree.
376** The entry is identified by its MemPage and the index in
drha34b6762004-05-07 13:30:42 +0000377** MemPage.aCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000378*/
drh72f82862001-05-24 21:06:34 +0000379struct BtCursor {
danielk1977aef0bf62005-12-30 16:28:01 +0000380 Btree *pBtree; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000381 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drh3aac2dd2004-04-26 14:10:20 +0000382 int (*xCompare)(void*,int,const void*,int,const void*); /* Key comp func */
383 void *pArg; /* First arg to xCompare() */
drh8b2f49b2001-06-08 00:21:52 +0000384 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000385 MemPage *pPage; /* Page that contains the entry */
drh3aac2dd2004-04-26 14:10:20 +0000386 int idx; /* Index of the entry in pPage->aCell[] */
drhfa1a98a2004-05-14 19:08:17 +0000387 CellInfo info; /* A parse of the cell we are pointing at */
drhecdc7532001-09-23 02:35:53 +0000388 u8 wrFlag; /* True if writable */
danielk1977da184232006-01-05 11:34:32 +0000389 u8 eState; /* One of the CURSOR_XXX constants (see below) */
390#ifndef SQLITE_OMIT_SHARED_CACHE
391 void *pKey;
392 i64 nKey;
393 int skip; /* (skip<0) -> Prev() is a no-op. (skip>0) -> Next() is */
394#endif
drh365d68f2001-05-11 11:02:46 +0000395};
drh7e3b0a02001-04-28 16:52:40 +0000396
drha059ad02001-04-17 20:09:11 +0000397/*
danielk1977da184232006-01-05 11:34:32 +0000398** Potential values for BtCursor.eState. The first two values (VALID and
399** INVALID) may occur in any build. The third (REQUIRESEEK) may only occur
400** if sqlite was compiled without the OMIT_SHARED_CACHE symbol defined.
401**
402** CURSOR_VALID:
403** Cursor points to a valid entry. getPayload() etc. may be called.
404**
405** CURSOR_INVALID:
406** Cursor does not point to a valid entry. This can happen (for example)
407** because the table is empty or because BtreeCursorFirst() has not been
408** called.
409**
410** CURSOR_REQUIRESEEK:
411** The table that this cursor was opened on still exists, but has been
412** modified since the cursor was last used. The cursor position is saved
413** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
drh777e4c42006-01-13 04:31:58 +0000414** this state, restoreOrClearCursorPosition() can be called to attempt to seek
danielk1977da184232006-01-05 11:34:32 +0000415** the cursor to the saved position.
416*/
417#define CURSOR_INVALID 0
418#define CURSOR_VALID 1
419#define CURSOR_REQUIRESEEK 2
420
421/*
drh615ae552005-01-16 23:21:00 +0000422** The TRACE macro will print high-level status information about the
423** btree operation when the global variable sqlite3_btree_trace is
424** enabled.
425*/
426#if SQLITE_TEST
427# define TRACE(X) if( sqlite3_btree_trace )\
428 { sqlite3DebugPrintf X; fflush(stdout); }
429#else
430# define TRACE(X)
431#endif
432int sqlite3_btree_trace=0; /* True to enable tracing */
433
434/*
drh66cbd152004-09-01 16:12:25 +0000435** Forward declaration
436*/
danielk1977aef0bf62005-12-30 16:28:01 +0000437static int checkReadLocks(BtShared*,Pgno,BtCursor*);
drh66cbd152004-09-01 16:12:25 +0000438
drh66cbd152004-09-01 16:12:25 +0000439/*
drhab01f612004-05-22 02:55:23 +0000440** Read or write a two- and four-byte big-endian integer values.
drh0d316a42002-08-11 20:10:47 +0000441*/
drh9e572e62004-04-23 23:43:10 +0000442static u32 get2byte(unsigned char *p){
443 return (p[0]<<8) | p[1];
drh0d316a42002-08-11 20:10:47 +0000444}
drh9e572e62004-04-23 23:43:10 +0000445static u32 get4byte(unsigned char *p){
446 return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
447}
drh9e572e62004-04-23 23:43:10 +0000448static void put2byte(unsigned char *p, u32 v){
449 p[0] = v>>8;
450 p[1] = v;
451}
452static void put4byte(unsigned char *p, u32 v){
453 p[0] = v>>24;
454 p[1] = v>>16;
455 p[2] = v>>8;
456 p[3] = v;
457}
drh6f11bef2004-05-13 01:12:56 +0000458
drh9e572e62004-04-23 23:43:10 +0000459/*
drhab01f612004-05-22 02:55:23 +0000460** Routines to read and write variable-length integers. These used to
461** be defined locally, but now we use the varint routines in the util.c
462** file.
drh9e572e62004-04-23 23:43:10 +0000463*/
drh6d2fb152004-05-14 16:50:06 +0000464#define getVarint sqlite3GetVarint
drh504b6982006-01-22 21:52:56 +0000465/* #define getVarint32 sqlite3GetVarint32 */
466#define getVarint32(A,B) ((*B=*(A))<=0x7f?1:sqlite3GetVarint32(A,B))
drh6d2fb152004-05-14 16:50:06 +0000467#define putVarint sqlite3PutVarint
drh0d316a42002-08-11 20:10:47 +0000468
danielk1977599fcba2004-11-08 07:13:13 +0000469/* The database page the PENDING_BYTE occupies. This page is never used.
470** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
471** should possibly be consolidated (presumably in pager.h).
472*/
473#define PENDING_BYTE_PAGE(pBt) ((PENDING_BYTE/(pBt)->pageSize)+1)
danielk1977afcdd022004-10-31 16:25:42 +0000474
danielk1977aef0bf62005-12-30 16:28:01 +0000475/*
476** A linked list of the following structures is stored at BtShared.pLock.
477** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
478** is opened on the table with root page BtShared.iTable. Locks are removed
479** from this list when a transaction is committed or rolled back, or when
480** a btree handle is closed.
481*/
482struct BtLock {
483 Btree *pBtree; /* Btree handle holding this lock */
484 Pgno iTable; /* Root page of table */
485 u8 eLock; /* READ_LOCK or WRITE_LOCK */
486 BtLock *pNext; /* Next in BtShared.pLock list */
487};
488
489/* Candidate values for BtLock.eLock */
490#define READ_LOCK 1
491#define WRITE_LOCK 2
492
493#ifdef SQLITE_OMIT_SHARED_CACHE
494 /*
495 ** The functions queryTableLock(), lockTable() and unlockAllTables()
496 ** manipulate entries in the BtShared.pLock linked list used to store
497 ** shared-cache table level locks. If the library is compiled with the
498 ** shared-cache feature disabled, then there is only ever one user
danielk1977da184232006-01-05 11:34:32 +0000499 ** of each BtShared structure and so this locking is not necessary.
500 ** So define the lock related functions as no-ops.
danielk1977aef0bf62005-12-30 16:28:01 +0000501 */
502 #define queryTableLock(a,b,c) SQLITE_OK
503 #define lockTable(a,b,c) SQLITE_OK
danielk1977da184232006-01-05 11:34:32 +0000504 #define unlockAllTables(a)
drh777e4c42006-01-13 04:31:58 +0000505 #define restoreOrClearCursorPosition(a,b) SQLITE_OK
danielk1977da184232006-01-05 11:34:32 +0000506 #define saveAllCursors(a,b,c) SQLITE_OK
507
danielk1977aef0bf62005-12-30 16:28:01 +0000508#else
509
danielk197797a227c2006-01-20 16:32:04 +0000510static void releasePage(MemPage *pPage);
511
danielk1977aef0bf62005-12-30 16:28:01 +0000512/*
danielk1977da184232006-01-05 11:34:32 +0000513** Save the current cursor position in the variables BtCursor.nKey
514** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
515*/
516static int saveCursorPosition(BtCursor *pCur){
danielk1977191c3e72006-01-19 07:18:14 +0000517 int rc;
danielk1977da184232006-01-05 11:34:32 +0000518
danielk1977191c3e72006-01-19 07:18:14 +0000519 assert( CURSOR_VALID==pCur->eState );
danielk1977da184232006-01-05 11:34:32 +0000520 assert( 0==pCur->pKey );
521
danielk1977191c3e72006-01-19 07:18:14 +0000522 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
danielk1977da184232006-01-05 11:34:32 +0000523
danielk1977191c3e72006-01-19 07:18:14 +0000524 /* If this is an intKey table, then the above call to BtreeKeySize()
525 ** stores the integer key in pCur->nKey. In this case this value is
526 ** all that is required. Otherwise, if pCur is not open on an intKey
527 ** table, then malloc space for and store the pCur->nKey bytes of key
528 ** data.
529 */
530 if( rc==SQLITE_OK && 0==pCur->pPage->intKey){
531 void *pKey = sqliteMalloc(pCur->nKey);
532 if( pKey ){
533 rc = sqlite3BtreeKey(pCur, 0, pCur->nKey, pKey);
534 if( rc==SQLITE_OK ){
535 pCur->pKey = pKey;
danielk1977da184232006-01-05 11:34:32 +0000536 }else{
danielk1977191c3e72006-01-19 07:18:14 +0000537 sqliteFree(pKey);
danielk1977da184232006-01-05 11:34:32 +0000538 }
danielk1977191c3e72006-01-19 07:18:14 +0000539 }else{
540 rc = SQLITE_NOMEM;
danielk1977da184232006-01-05 11:34:32 +0000541 }
danielk1977191c3e72006-01-19 07:18:14 +0000542 }
543 assert( !pCur->pPage->intKey || !pCur->pKey );
danielk1977da184232006-01-05 11:34:32 +0000544
danielk1977191c3e72006-01-19 07:18:14 +0000545 if( rc==SQLITE_OK ){
danielk1977c4da5b92006-01-21 12:08:54 +0000546 releasePage(pCur->pPage);
547 pCur->pPage = 0;
danielk1977191c3e72006-01-19 07:18:14 +0000548 pCur->eState = CURSOR_REQUIRESEEK;
danielk1977da184232006-01-05 11:34:32 +0000549 }
550
551 return rc;
552}
553
554/*
555** Save the positions of all cursors except pExcept open on the table
556** with root-page iRoot. Usually, this is called just before cursor
557** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
558*/
559static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
560 BtCursor *p;
drh6f7adc82006-01-11 21:41:20 +0000561 if( sqlite3ThreadDataReadOnly()->useSharedData ){
danielk1977da184232006-01-05 11:34:32 +0000562 for(p=pBt->pCursor; p; p=p->pNext){
danielk19772b8c13e2006-01-24 14:21:24 +0000563 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
564 p->eState==CURSOR_VALID ){
danielk1977da184232006-01-05 11:34:32 +0000565 int rc = saveCursorPosition(p);
566 if( SQLITE_OK!=rc ){
567 return rc;
568 }
569 }
570 }
571 }
572 return SQLITE_OK;
573}
574
575/*
576** Restore the cursor to the position it was in (or as close to as possible)
577** when saveCursorPosition() was called. Note that this call deletes the
578** saved position info stored by saveCursorPosition(), so there can be
drh777e4c42006-01-13 04:31:58 +0000579** at most one effective restoreOrClearCursorPosition() call after each
danielk1977da184232006-01-05 11:34:32 +0000580** saveCursorPosition().
581**
582** If the second argument argument - doSeek - is false, then instead of
583** returning the cursor to it's saved position, any saved position is deleted
584** and the cursor state set to CURSOR_INVALID.
585*/
danielk1977e7259292006-01-13 06:33:23 +0000586static int restoreOrClearCursorPositionX(BtCursor *pCur, int doSeek){
danielk1977da184232006-01-05 11:34:32 +0000587 int rc = SQLITE_OK;
danielk1977e7259292006-01-13 06:33:23 +0000588 assert( sqlite3ThreadDataReadOnly()->useSharedData );
589 assert( pCur->eState==CURSOR_REQUIRESEEK );
danielk1977191c3e72006-01-19 07:18:14 +0000590 pCur->eState = CURSOR_INVALID;
danielk1977e7259292006-01-13 06:33:23 +0000591 if( doSeek ){
592 rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, &pCur->skip);
danielk1977e7259292006-01-13 06:33:23 +0000593 }
594 if( rc==SQLITE_OK ){
595 sqliteFree(pCur->pKey);
596 pCur->pKey = 0;
597 assert( CURSOR_VALID==pCur->eState || CURSOR_INVALID==pCur->eState );
danielk1977da184232006-01-05 11:34:32 +0000598 }
599 return rc;
600}
601
danielk1977e7259292006-01-13 06:33:23 +0000602#define restoreOrClearCursorPosition(p,x) \
603 (p->eState==CURSOR_REQUIRESEEK?restoreOrClearCursorPositionX(p,x):SQLITE_OK)
604
danielk1977da184232006-01-05 11:34:32 +0000605/*
danielk1977aef0bf62005-12-30 16:28:01 +0000606** Query to see if btree handle p may obtain a lock of type eLock
607** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
608** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
danielk1977c87d34d2006-01-06 13:00:28 +0000609** SQLITE_LOCKED if not.
danielk1977aef0bf62005-12-30 16:28:01 +0000610*/
611static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
612 BtShared *pBt = p->pBt;
613 BtLock *pIter;
614
danielk1977da184232006-01-05 11:34:32 +0000615 /* This is a no-op if the shared-cache is not enabled */
drh6f7adc82006-01-11 21:41:20 +0000616 if( 0==sqlite3ThreadDataReadOnly()->useSharedData ){
danielk1977da184232006-01-05 11:34:32 +0000617 return SQLITE_OK;
618 }
619
620 /* This (along with lockTable()) is where the ReadUncommitted flag is
621 ** dealt with. If the caller is querying for a read-lock and the flag is
622 ** set, it is unconditionally granted - even if there are write-locks
623 ** on the table. If a write-lock is requested, the ReadUncommitted flag
624 ** is not considered.
625 **
626 ** In function lockTable(), if a read-lock is demanded and the
627 ** ReadUncommitted flag is set, no entry is added to the locks list
628 ** (BtShared.pLock).
629 **
630 ** To summarize: If the ReadUncommitted flag is set, then read cursors do
631 ** not create or respect table locks. The locking procedure for a
632 ** write-cursor does not change.
633 */
634 if(
635 !p->pSqlite ||
636 0==(p->pSqlite->flags&SQLITE_ReadUncommitted) ||
637 eLock==WRITE_LOCK ||
drh47ded162006-01-06 01:42:58 +0000638 iTab==MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000639 ){
640 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
641 if( pIter->pBtree!=p && pIter->iTable==iTab &&
642 (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
danielk1977c87d34d2006-01-06 13:00:28 +0000643 return SQLITE_LOCKED;
danielk1977da184232006-01-05 11:34:32 +0000644 }
danielk1977aef0bf62005-12-30 16:28:01 +0000645 }
646 }
647 return SQLITE_OK;
648}
649
650/*
651** Add a lock on the table with root-page iTable to the shared-btree used
652** by Btree handle p. Parameter eLock must be either READ_LOCK or
653** WRITE_LOCK.
654**
655** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
656** SQLITE_NOMEM may also be returned.
657*/
658static int lockTable(Btree *p, Pgno iTable, u8 eLock){
659 BtShared *pBt = p->pBt;
660 BtLock *pLock = 0;
661 BtLock *pIter;
662
danielk1977da184232006-01-05 11:34:32 +0000663 /* This is a no-op if the shared-cache is not enabled */
drh6f7adc82006-01-11 21:41:20 +0000664 if( 0==sqlite3ThreadDataReadOnly()->useSharedData ){
danielk1977da184232006-01-05 11:34:32 +0000665 return SQLITE_OK;
666 }
667
danielk1977aef0bf62005-12-30 16:28:01 +0000668 assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
669
danielk1977da184232006-01-05 11:34:32 +0000670 /* If the read-uncommitted flag is set and a read-lock is requested,
671 ** return early without adding an entry to the BtShared.pLock list. See
672 ** comment in function queryTableLock() for more info on handling
673 ** the ReadUncommitted flag.
674 */
675 if(
676 (p->pSqlite) &&
677 (p->pSqlite->flags&SQLITE_ReadUncommitted) &&
678 (eLock==READ_LOCK) &&
drh47ded162006-01-06 01:42:58 +0000679 iTable!=MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000680 ){
681 return SQLITE_OK;
682 }
683
danielk1977aef0bf62005-12-30 16:28:01 +0000684 /* First search the list for an existing lock on this table. */
685 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
686 if( pIter->iTable==iTable && pIter->pBtree==p ){
687 pLock = pIter;
688 break;
689 }
690 }
691
692 /* If the above search did not find a BtLock struct associating Btree p
693 ** with table iTable, allocate one and link it into the list.
694 */
695 if( !pLock ){
696 pLock = (BtLock *)sqliteMalloc(sizeof(BtLock));
697 if( !pLock ){
698 return SQLITE_NOMEM;
699 }
700 pLock->iTable = iTable;
701 pLock->pBtree = p;
702 pLock->pNext = pBt->pLock;
703 pBt->pLock = pLock;
704 }
705
706 /* Set the BtLock.eLock variable to the maximum of the current lock
707 ** and the requested lock. This means if a write-lock was already held
708 ** and a read-lock requested, we don't incorrectly downgrade the lock.
709 */
710 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000711 if( eLock>pLock->eLock ){
712 pLock->eLock = eLock;
713 }
danielk1977aef0bf62005-12-30 16:28:01 +0000714
715 return SQLITE_OK;
716}
717
718/*
719** Release all the table locks (locks obtained via calls to the lockTable()
720** procedure) held by Btree handle p.
721*/
722static void unlockAllTables(Btree *p){
723 BtLock **ppIter = &p->pBt->pLock;
danielk1977da184232006-01-05 11:34:32 +0000724
725 /* If the shared-cache extension is not enabled, there should be no
726 ** locks in the BtShared.pLock list, making this procedure a no-op. Assert
727 ** that this is the case.
728 */
drh6f7adc82006-01-11 21:41:20 +0000729 assert( sqlite3ThreadDataReadOnly()->useSharedData || 0==*ppIter );
danielk1977da184232006-01-05 11:34:32 +0000730
danielk1977aef0bf62005-12-30 16:28:01 +0000731 while( *ppIter ){
732 BtLock *pLock = *ppIter;
733 if( pLock->pBtree==p ){
734 *ppIter = pLock->pNext;
735 sqliteFree(pLock);
736 }else{
737 ppIter = &pLock->pNext;
738 }
739 }
740}
741#endif /* SQLITE_OMIT_SHARED_CACHE */
742
danielk1977599fcba2004-11-08 07:13:13 +0000743#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000744/*
drh42cac6d2004-11-20 20:31:11 +0000745** These macros define the location of the pointer-map entry for a
746** database page. The first argument to each is the number of usable
747** bytes on each page of the database (often 1024). The second is the
748** page number to look up in the pointer map.
danielk1977afcdd022004-10-31 16:25:42 +0000749**
750** PTRMAP_PAGENO returns the database page number of the pointer-map
751** page that stores the required pointer. PTRMAP_PTROFFSET returns
752** the offset of the requested map entry.
753**
754** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
755** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
danielk1977599fcba2004-11-08 07:13:13 +0000756** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
757** this test.
danielk1977afcdd022004-10-31 16:25:42 +0000758*/
759#define PTRMAP_PAGENO(pgsz, pgno) (((pgno-2)/(pgsz/5+1))*(pgsz/5+1)+2)
760#define PTRMAP_PTROFFSET(pgsz, pgno) (((pgno-2)%(pgsz/5+1)-1)*5)
danielk1977a19df672004-11-03 11:37:07 +0000761#define PTRMAP_ISPAGE(pgsz, pgno) (PTRMAP_PAGENO(pgsz,pgno)==pgno)
762
danielk1977afcdd022004-10-31 16:25:42 +0000763/*
drh615ae552005-01-16 23:21:00 +0000764** The pointer map is a lookup table that identifies the parent page for
765** each child page in the database file. The parent page is the page that
766** contains a pointer to the child. Every page in the database contains
767** 0 or 1 parent pages. (In this context 'database page' refers
768** to any page that is not part of the pointer map itself.) Each pointer map
769** entry consists of a single byte 'type' and a 4 byte parent page number.
770** The PTRMAP_XXX identifiers below are the valid types.
771**
772** The purpose of the pointer map is to facility moving pages from one
773** position in the file to another as part of autovacuum. When a page
774** is moved, the pointer in its parent must be updated to point to the
775** new location. The pointer map is used to locate the parent page quickly.
danielk1977afcdd022004-10-31 16:25:42 +0000776**
danielk1977687566d2004-11-02 12:56:41 +0000777** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
778** used in this case.
danielk1977afcdd022004-10-31 16:25:42 +0000779**
danielk1977687566d2004-11-02 12:56:41 +0000780** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
781** is not used in this case.
782**
783** PTRMAP_OVERFLOW1: The database page is the first page in a list of
784** overflow pages. The page number identifies the page that
785** contains the cell with a pointer to this overflow page.
786**
787** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
788** overflow pages. The page-number identifies the previous
789** page in the overflow page list.
790**
791** PTRMAP_BTREE: The database page is a non-root btree page. The page number
792** identifies the parent page in the btree.
danielk1977afcdd022004-10-31 16:25:42 +0000793*/
danielk1977687566d2004-11-02 12:56:41 +0000794#define PTRMAP_ROOTPAGE 1
795#define PTRMAP_FREEPAGE 2
796#define PTRMAP_OVERFLOW1 3
797#define PTRMAP_OVERFLOW2 4
798#define PTRMAP_BTREE 5
danielk1977afcdd022004-10-31 16:25:42 +0000799
800/*
801** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000802**
803** This routine updates the pointer map entry for page number 'key'
804** so that it maps to type 'eType' and parent page number 'pgno'.
805** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000806*/
danielk1977aef0bf62005-12-30 16:28:01 +0000807static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
danielk1977afcdd022004-10-31 16:25:42 +0000808 u8 *pPtrmap; /* The pointer map page */
809 Pgno iPtrmap; /* The pointer map page number */
810 int offset; /* Offset in pointer map page */
811 int rc;
812
danielk1977ac11ee62005-01-15 12:45:51 +0000813 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000814 if( key==0 ){
drh49285702005-09-17 15:20:26 +0000815 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000816 }
drh42cac6d2004-11-20 20:31:11 +0000817 iPtrmap = PTRMAP_PAGENO(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000818 rc = sqlite3pager_get(pBt->pPager, iPtrmap, (void **)&pPtrmap);
danielk1977687566d2004-11-02 12:56:41 +0000819 if( rc!=SQLITE_OK ){
danielk1977afcdd022004-10-31 16:25:42 +0000820 return rc;
821 }
drh42cac6d2004-11-20 20:31:11 +0000822 offset = PTRMAP_PTROFFSET(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000823
drh615ae552005-01-16 23:21:00 +0000824 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
825 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
danielk1977afcdd022004-10-31 16:25:42 +0000826 rc = sqlite3pager_write(pPtrmap);
danielk19775558a8a2005-01-17 07:53:44 +0000827 if( rc==SQLITE_OK ){
828 pPtrmap[offset] = eType;
829 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000830 }
danielk1977afcdd022004-10-31 16:25:42 +0000831 }
832
833 sqlite3pager_unref(pPtrmap);
danielk19775558a8a2005-01-17 07:53:44 +0000834 return rc;
danielk1977afcdd022004-10-31 16:25:42 +0000835}
836
837/*
838** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000839**
840** This routine retrieves the pointer map entry for page 'key', writing
841** the type and parent page number to *pEType and *pPgno respectively.
842** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000843*/
danielk1977aef0bf62005-12-30 16:28:01 +0000844static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk1977afcdd022004-10-31 16:25:42 +0000845 int iPtrmap; /* Pointer map page index */
846 u8 *pPtrmap; /* Pointer map page data */
847 int offset; /* Offset of entry in pointer map */
848 int rc;
849
drh42cac6d2004-11-20 20:31:11 +0000850 iPtrmap = PTRMAP_PAGENO(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000851 rc = sqlite3pager_get(pBt->pPager, iPtrmap, (void **)&pPtrmap);
852 if( rc!=0 ){
853 return rc;
854 }
855
drh42cac6d2004-11-20 20:31:11 +0000856 offset = PTRMAP_PTROFFSET(pBt->usableSize, key);
danielk1977687566d2004-11-02 12:56:41 +0000857 if( pEType ) *pEType = pPtrmap[offset];
858 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000859
860 sqlite3pager_unref(pPtrmap);
drh49285702005-09-17 15:20:26 +0000861 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000862 return SQLITE_OK;
863}
864
865#endif /* SQLITE_OMIT_AUTOVACUUM */
866
drh0d316a42002-08-11 20:10:47 +0000867/*
drh271efa52004-05-30 19:19:05 +0000868** Given a btree page and a cell index (0 means the first cell on
869** the page, 1 means the second cell, and so forth) return a pointer
870** to the cell content.
871**
872** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000873*/
drh43605152004-05-29 21:46:49 +0000874static u8 *findCell(MemPage *pPage, int iCell){
875 u8 *data = pPage->aData;
876 assert( iCell>=0 );
877 assert( iCell<get2byte(&data[pPage->hdrOffset+3]) );
878 return data + get2byte(&data[pPage->cellOffset+2*iCell]);
879}
880
881/*
882** This a more complex version of findCell() that works for
883** pages that do contain overflow cells. See insert
884*/
885static u8 *findOverflowCell(MemPage *pPage, int iCell){
886 int i;
887 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000888 int k;
889 struct _OvflCell *pOvfl;
890 pOvfl = &pPage->aOvfl[i];
891 k = pOvfl->idx;
892 if( k<=iCell ){
893 if( k==iCell ){
894 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000895 }
896 iCell--;
897 }
898 }
899 return findCell(pPage, iCell);
900}
901
902/*
903** Parse a cell content block and fill in the CellInfo structure. There
904** are two versions of this function. parseCell() takes a cell index
905** as the second argument and parseCellPtr() takes a pointer to the
906** body of the cell as its second argument.
907*/
908static void parseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000909 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000910 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000911 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000912){
drh271efa52004-05-30 19:19:05 +0000913 int n; /* Number bytes in cell content header */
914 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000915
916 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000917 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000918 n = pPage->childPtrSize;
919 assert( n==4-4*pPage->leaf );
drh8b18dd42004-05-12 19:18:15 +0000920 if( pPage->hasData ){
drh271efa52004-05-30 19:19:05 +0000921 n += getVarint32(&pCell[n], &nPayload);
drh8b18dd42004-05-12 19:18:15 +0000922 }else{
drh271efa52004-05-30 19:19:05 +0000923 nPayload = 0;
drh3aac2dd2004-04-26 14:10:20 +0000924 }
drh271efa52004-05-30 19:19:05 +0000925 pInfo->nData = nPayload;
drh504b6982006-01-22 21:52:56 +0000926 if( pPage->intKey ){
927 n += getVarint(&pCell[n], (u64 *)&pInfo->nKey);
928 }else{
929 u32 x;
930 n += getVarint32(&pCell[n], &x);
931 pInfo->nKey = x;
932 nPayload += x;
drh6f11bef2004-05-13 01:12:56 +0000933 }
drh504b6982006-01-22 21:52:56 +0000934 pInfo->nHeader = n;
drh271efa52004-05-30 19:19:05 +0000935 if( nPayload<=pPage->maxLocal ){
936 /* This is the (easy) common case where the entire payload fits
937 ** on the local page. No overflow is required.
938 */
939 int nSize; /* Total size of cell content in bytes */
drh6f11bef2004-05-13 01:12:56 +0000940 pInfo->nLocal = nPayload;
941 pInfo->iOverflow = 0;
drh271efa52004-05-30 19:19:05 +0000942 nSize = nPayload + n;
943 if( nSize<4 ){
944 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000945 }
drh271efa52004-05-30 19:19:05 +0000946 pInfo->nSize = nSize;
drh6f11bef2004-05-13 01:12:56 +0000947 }else{
drh271efa52004-05-30 19:19:05 +0000948 /* If the payload will not fit completely on the local page, we have
949 ** to decide how much to store locally and how much to spill onto
950 ** overflow pages. The strategy is to minimize the amount of unused
951 ** space on overflow pages while keeping the amount of local storage
952 ** in between minLocal and maxLocal.
953 **
954 ** Warning: changing the way overflow payload is distributed in any
955 ** way will result in an incompatible file format.
956 */
957 int minLocal; /* Minimum amount of payload held locally */
958 int maxLocal; /* Maximum amount of payload held locally */
959 int surplus; /* Overflow payload available for local storage */
960
961 minLocal = pPage->minLocal;
962 maxLocal = pPage->maxLocal;
963 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000964 if( surplus <= maxLocal ){
965 pInfo->nLocal = surplus;
966 }else{
967 pInfo->nLocal = minLocal;
968 }
969 pInfo->iOverflow = pInfo->nLocal + n;
970 pInfo->nSize = pInfo->iOverflow + 4;
971 }
drh3aac2dd2004-04-26 14:10:20 +0000972}
drh43605152004-05-29 21:46:49 +0000973static void parseCell(
974 MemPage *pPage, /* Page containing the cell */
975 int iCell, /* The cell index. First cell is 0 */
976 CellInfo *pInfo /* Fill in this structure */
977){
978 parseCellPtr(pPage, findCell(pPage, iCell), pInfo);
979}
drh3aac2dd2004-04-26 14:10:20 +0000980
981/*
drh43605152004-05-29 21:46:49 +0000982** Compute the total number of bytes that a Cell needs in the cell
983** data area of the btree-page. The return number includes the cell
984** data header and the local payload, but not any overflow page or
985** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000986*/
danielk1977bc6ada42004-06-30 08:20:16 +0000987#ifndef NDEBUG
drh43605152004-05-29 21:46:49 +0000988static int cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000989 CellInfo info;
drh43605152004-05-29 21:46:49 +0000990 parseCell(pPage, iCell, &info);
991 return info.nSize;
992}
danielk1977bc6ada42004-06-30 08:20:16 +0000993#endif
drh43605152004-05-29 21:46:49 +0000994static int cellSizePtr(MemPage *pPage, u8 *pCell){
995 CellInfo info;
996 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000997 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000998}
999
danielk197779a40da2005-01-16 08:00:01 +00001000#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +00001001/*
danielk197726836652005-01-17 01:33:13 +00001002** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +00001003** to an overflow page, insert an entry into the pointer-map
1004** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +00001005*/
danielk197726836652005-01-17 01:33:13 +00001006static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
danielk197779a40da2005-01-16 08:00:01 +00001007 if( pCell ){
1008 CellInfo info;
1009 parseCellPtr(pPage, pCell, &info);
1010 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
1011 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
1012 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
1013 }
danielk1977ac11ee62005-01-15 12:45:51 +00001014 }
danielk197779a40da2005-01-16 08:00:01 +00001015 return SQLITE_OK;
danielk1977ac11ee62005-01-15 12:45:51 +00001016}
danielk197726836652005-01-17 01:33:13 +00001017/*
1018** If the cell with index iCell on page pPage contains a pointer
1019** to an overflow page, insert an entry into the pointer-map
1020** for the overflow page.
1021*/
1022static int ptrmapPutOvfl(MemPage *pPage, int iCell){
1023 u8 *pCell;
1024 pCell = findOverflowCell(pPage, iCell);
1025 return ptrmapPutOvflPtr(pPage, pCell);
1026}
danielk197779a40da2005-01-16 08:00:01 +00001027#endif
1028
danielk1977ac11ee62005-01-15 12:45:51 +00001029
1030/*
drhda200cc2004-05-09 11:51:38 +00001031** Do sanity checking on a page. Throw an exception if anything is
1032** not right.
1033**
1034** This routine is used for internal error checking only. It is omitted
1035** from most builds.
1036*/
1037#if defined(BTREE_DEBUG) && !defined(NDEBUG) && 0
1038static void _pageIntegrity(MemPage *pPage){
drhb6f41482004-05-14 01:58:11 +00001039 int usableSize;
drhda200cc2004-05-09 11:51:38 +00001040 u8 *data;
drh43605152004-05-29 21:46:49 +00001041 int i, j, idx, c, pc, hdr, nFree;
1042 int cellOffset;
1043 int nCell, cellLimit;
drh2e38c322004-09-03 18:38:44 +00001044 u8 *used;
drhda200cc2004-05-09 11:51:38 +00001045
drh2e38c322004-09-03 18:38:44 +00001046 used = sqliteMallocRaw( pPage->pBt->pageSize );
1047 if( used==0 ) return;
drhb6f41482004-05-14 01:58:11 +00001048 usableSize = pPage->pBt->usableSize;
drh07d183d2005-05-01 22:52:42 +00001049 assert( pPage->aData==&((unsigned char*)pPage)[-pPage->pBt->pageSize] );
drhda200cc2004-05-09 11:51:38 +00001050 hdr = pPage->hdrOffset;
1051 assert( hdr==(pPage->pgno==1 ? 100 : 0) );
1052 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
1053 c = pPage->aData[hdr];
1054 if( pPage->isInit ){
1055 assert( pPage->leaf == ((c & PTF_LEAF)!=0) );
1056 assert( pPage->zeroData == ((c & PTF_ZERODATA)!=0) );
drh8b18dd42004-05-12 19:18:15 +00001057 assert( pPage->leafData == ((c & PTF_LEAFDATA)!=0) );
1058 assert( pPage->intKey == ((c & (PTF_INTKEY|PTF_LEAFDATA))!=0) );
1059 assert( pPage->hasData ==
1060 !(pPage->zeroData || (!pPage->leaf && pPage->leafData)) );
drh43605152004-05-29 21:46:49 +00001061 assert( pPage->cellOffset==pPage->hdrOffset+12-4*pPage->leaf );
1062 assert( pPage->nCell = get2byte(&pPage->aData[hdr+3]) );
drhda200cc2004-05-09 11:51:38 +00001063 }
1064 data = pPage->aData;
drhb6f41482004-05-14 01:58:11 +00001065 memset(used, 0, usableSize);
drhda200cc2004-05-09 11:51:38 +00001066 for(i=0; i<hdr+10-pPage->leaf*4; i++) used[i] = 1;
1067 nFree = 0;
1068 pc = get2byte(&data[hdr+1]);
1069 while( pc ){
1070 int size;
drhb6f41482004-05-14 01:58:11 +00001071 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +00001072 size = get2byte(&data[pc+2]);
drhb6f41482004-05-14 01:58:11 +00001073 assert( pc+size<=usableSize );
drhda200cc2004-05-09 11:51:38 +00001074 nFree += size;
1075 for(i=pc; i<pc+size; i++){
1076 assert( used[i]==0 );
1077 used[i] = 1;
1078 }
1079 pc = get2byte(&data[pc]);
1080 }
drhda200cc2004-05-09 11:51:38 +00001081 idx = 0;
drh43605152004-05-29 21:46:49 +00001082 nCell = get2byte(&data[hdr+3]);
1083 cellLimit = get2byte(&data[hdr+5]);
1084 assert( pPage->isInit==0
1085 || pPage->nFree==nFree+data[hdr+7]+cellLimit-(cellOffset+2*nCell) );
1086 cellOffset = pPage->cellOffset;
1087 for(i=0; i<nCell; i++){
drhda200cc2004-05-09 11:51:38 +00001088 int size;
drh43605152004-05-29 21:46:49 +00001089 pc = get2byte(&data[cellOffset+2*i]);
drhb6f41482004-05-14 01:58:11 +00001090 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +00001091 size = cellSize(pPage, &data[pc]);
drhb6f41482004-05-14 01:58:11 +00001092 assert( pc+size<=usableSize );
drh43605152004-05-29 21:46:49 +00001093 for(j=pc; j<pc+size; j++){
1094 assert( used[j]==0 );
1095 used[j] = 1;
drhda200cc2004-05-09 11:51:38 +00001096 }
drhda200cc2004-05-09 11:51:38 +00001097 }
drh43605152004-05-29 21:46:49 +00001098 for(i=cellOffset+2*nCell; i<cellimit; i++){
1099 assert( used[i]==0 );
1100 used[i] = 1;
1101 }
drhda200cc2004-05-09 11:51:38 +00001102 nFree = 0;
drhb6f41482004-05-14 01:58:11 +00001103 for(i=0; i<usableSize; i++){
drhda200cc2004-05-09 11:51:38 +00001104 assert( used[i]<=1 );
1105 if( used[i]==0 ) nFree++;
1106 }
drh43605152004-05-29 21:46:49 +00001107 assert( nFree==data[hdr+7] );
drh2e38c322004-09-03 18:38:44 +00001108 sqliteFree(used);
drhda200cc2004-05-09 11:51:38 +00001109}
1110#define pageIntegrity(X) _pageIntegrity(X)
1111#else
1112# define pageIntegrity(X)
1113#endif
1114
danielk1977aef0bf62005-12-30 16:28:01 +00001115/* A bunch of assert() statements to check the transaction state variables
1116** of handle p (type Btree*) are internally consistent.
1117*/
1118#define btreeIntegrity(p) \
1119 assert( p->inTrans!=TRANS_NONE || p->pBt->nTransaction<p->pBt->nRef ); \
1120 assert( p->pBt->nTransaction<=p->pBt->nRef ); \
1121 assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
1122 assert( p->pBt->inTransaction>=p->inTrans );
1123
drhda200cc2004-05-09 11:51:38 +00001124/*
drh72f82862001-05-24 21:06:34 +00001125** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +00001126** end of the page and all free space is collected into one
1127** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +00001128** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +00001129*/
drh2e38c322004-09-03 18:38:44 +00001130static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +00001131 int i; /* Loop counter */
1132 int pc; /* Address of a i-th cell */
1133 int addr; /* Offset of first byte after cell pointer array */
1134 int hdr; /* Offset to the page header */
1135 int size; /* Size of a cell */
1136 int usableSize; /* Number of usable bytes on a page */
1137 int cellOffset; /* Offset to the cell pointer array */
1138 int brk; /* Offset to the cell content area */
1139 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +00001140 unsigned char *data; /* The page data */
1141 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +00001142
drha34b6762004-05-07 13:30:42 +00001143 assert( sqlite3pager_iswriteable(pPage->aData) );
drh9e572e62004-04-23 23:43:10 +00001144 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +00001145 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +00001146 assert( pPage->nOverflow==0 );
drh2e38c322004-09-03 18:38:44 +00001147 temp = sqliteMalloc( pPage->pBt->pageSize );
1148 if( temp==0 ) return SQLITE_NOMEM;
drh43605152004-05-29 21:46:49 +00001149 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +00001150 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001151 cellOffset = pPage->cellOffset;
1152 nCell = pPage->nCell;
1153 assert( nCell==get2byte(&data[hdr+3]) );
1154 usableSize = pPage->pBt->usableSize;
1155 brk = get2byte(&data[hdr+5]);
1156 memcpy(&temp[brk], &data[brk], usableSize - brk);
1157 brk = usableSize;
1158 for(i=0; i<nCell; i++){
1159 u8 *pAddr; /* The i-th cell pointer */
1160 pAddr = &data[cellOffset + i*2];
1161 pc = get2byte(pAddr);
1162 assert( pc<pPage->pBt->usableSize );
1163 size = cellSizePtr(pPage, &temp[pc]);
1164 brk -= size;
1165 memcpy(&data[brk], &temp[pc], size);
1166 put2byte(pAddr, brk);
drh2af926b2001-05-15 00:39:25 +00001167 }
drh43605152004-05-29 21:46:49 +00001168 assert( brk>=cellOffset+2*nCell );
1169 put2byte(&data[hdr+5], brk);
1170 data[hdr+1] = 0;
1171 data[hdr+2] = 0;
1172 data[hdr+7] = 0;
1173 addr = cellOffset+2*nCell;
1174 memset(&data[addr], 0, brk-addr);
drh2e38c322004-09-03 18:38:44 +00001175 sqliteFree(temp);
1176 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +00001177}
1178
drha059ad02001-04-17 20:09:11 +00001179/*
drh43605152004-05-29 21:46:49 +00001180** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +00001181**
drh9e572e62004-04-23 23:43:10 +00001182** Return the index into pPage->aData[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +00001183** the new allocation. Or return 0 if there is not enough free
1184** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +00001185**
drh72f82862001-05-24 21:06:34 +00001186** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +00001187** nBytes of contiguous free space, then this routine automatically
1188** calls defragementPage() to consolidate all free space before
1189** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +00001190*/
drh9e572e62004-04-23 23:43:10 +00001191static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +00001192 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +00001193 int size;
drh24cd67e2004-05-10 16:18:47 +00001194 int nFrag;
drh43605152004-05-29 21:46:49 +00001195 int top;
1196 int nCell;
1197 int cellOffset;
drh9e572e62004-04-23 23:43:10 +00001198 unsigned char *data;
drh43605152004-05-29 21:46:49 +00001199
drh9e572e62004-04-23 23:43:10 +00001200 data = pPage->aData;
drha34b6762004-05-07 13:30:42 +00001201 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +00001202 assert( pPage->pBt );
1203 if( nByte<4 ) nByte = 4;
drh43605152004-05-29 21:46:49 +00001204 if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
1205 pPage->nFree -= nByte;
drh9e572e62004-04-23 23:43:10 +00001206 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001207
1208 nFrag = data[hdr+7];
1209 if( nFrag<60 ){
1210 /* Search the freelist looking for a slot big enough to satisfy the
1211 ** space request. */
1212 addr = hdr+1;
1213 while( (pc = get2byte(&data[addr]))>0 ){
1214 size = get2byte(&data[pc+2]);
1215 if( size>=nByte ){
1216 if( size<nByte+4 ){
1217 memcpy(&data[addr], &data[pc], 2);
1218 data[hdr+7] = nFrag + size - nByte;
1219 return pc;
1220 }else{
1221 put2byte(&data[pc+2], size-nByte);
1222 return pc + size - nByte;
1223 }
1224 }
1225 addr = pc;
drh9e572e62004-04-23 23:43:10 +00001226 }
1227 }
drh43605152004-05-29 21:46:49 +00001228
1229 /* Allocate memory from the gap in between the cell pointer array
1230 ** and the cell content area.
1231 */
1232 top = get2byte(&data[hdr+5]);
1233 nCell = get2byte(&data[hdr+3]);
1234 cellOffset = pPage->cellOffset;
1235 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
drh2e38c322004-09-03 18:38:44 +00001236 if( defragmentPage(pPage) ) return 0;
drh43605152004-05-29 21:46:49 +00001237 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +00001238 }
drh43605152004-05-29 21:46:49 +00001239 top -= nByte;
1240 assert( cellOffset + 2*nCell <= top );
1241 put2byte(&data[hdr+5], top);
1242 return top;
drh7e3b0a02001-04-28 16:52:40 +00001243}
1244
1245/*
drh9e572e62004-04-23 23:43:10 +00001246** Return a section of the pPage->aData to the freelist.
1247** The first byte of the new free block is pPage->aDisk[start]
1248** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +00001249**
1250** Most of the effort here is involved in coalesing adjacent
1251** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +00001252*/
drh9e572e62004-04-23 23:43:10 +00001253static void freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +00001254 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +00001255 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +00001256
drh9e572e62004-04-23 23:43:10 +00001257 assert( pPage->pBt!=0 );
drha34b6762004-05-07 13:30:42 +00001258 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +00001259 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +00001260 assert( (start + size)<=pPage->pBt->usableSize );
drh9e572e62004-04-23 23:43:10 +00001261 if( size<4 ) size = 4;
1262
1263 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +00001264 hdr = pPage->hdrOffset;
1265 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +00001266 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +00001267 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +00001268 assert( pbegin>addr );
1269 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +00001270 }
drhb6f41482004-05-14 01:58:11 +00001271 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +00001272 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +00001273 put2byte(&data[addr], start);
1274 put2byte(&data[start], pbegin);
1275 put2byte(&data[start+2], size);
drh2af926b2001-05-15 00:39:25 +00001276 pPage->nFree += size;
drh9e572e62004-04-23 23:43:10 +00001277
1278 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +00001279 addr = pPage->hdrOffset + 1;
1280 while( (pbegin = get2byte(&data[addr]))>0 ){
drh9e572e62004-04-23 23:43:10 +00001281 int pnext, psize;
drh3aac2dd2004-04-26 14:10:20 +00001282 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +00001283 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +00001284 pnext = get2byte(&data[pbegin]);
1285 psize = get2byte(&data[pbegin+2]);
1286 if( pbegin + psize + 3 >= pnext && pnext>0 ){
1287 int frag = pnext - (pbegin+psize);
drh43605152004-05-29 21:46:49 +00001288 assert( frag<=data[pPage->hdrOffset+7] );
1289 data[pPage->hdrOffset+7] -= frag;
drh9e572e62004-04-23 23:43:10 +00001290 put2byte(&data[pbegin], get2byte(&data[pnext]));
1291 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
1292 }else{
drh3aac2dd2004-04-26 14:10:20 +00001293 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +00001294 }
1295 }
drh7e3b0a02001-04-28 16:52:40 +00001296
drh43605152004-05-29 21:46:49 +00001297 /* If the cell content area begins with a freeblock, remove it. */
1298 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
1299 int top;
1300 pbegin = get2byte(&data[hdr+1]);
1301 memcpy(&data[hdr+1], &data[pbegin], 2);
1302 top = get2byte(&data[hdr+5]);
1303 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
drh4b70f112004-05-02 21:12:19 +00001304 }
drh4b70f112004-05-02 21:12:19 +00001305}
1306
1307/*
drh271efa52004-05-30 19:19:05 +00001308** Decode the flags byte (the first byte of the header) for a page
1309** and initialize fields of the MemPage structure accordingly.
1310*/
1311static void decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +00001312 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +00001313
1314 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
1315 pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
1316 pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
1317 pPage->leaf = (flagByte & PTF_LEAF)!=0;
1318 pPage->childPtrSize = 4*(pPage->leaf==0);
1319 pBt = pPage->pBt;
1320 if( flagByte & PTF_LEAFDATA ){
1321 pPage->leafData = 1;
1322 pPage->maxLocal = pBt->maxLeaf;
1323 pPage->minLocal = pBt->minLeaf;
1324 }else{
1325 pPage->leafData = 0;
1326 pPage->maxLocal = pBt->maxLocal;
1327 pPage->minLocal = pBt->minLocal;
1328 }
1329 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
1330}
1331
1332/*
drh7e3b0a02001-04-28 16:52:40 +00001333** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001334**
drhbd03cae2001-06-02 02:40:57 +00001335** The pParent parameter must be a pointer to the MemPage which
drh9e572e62004-04-23 23:43:10 +00001336** is the parent of the page being initialized. The root of a
1337** BTree has no parent and so for that page, pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +00001338**
drh72f82862001-05-24 21:06:34 +00001339** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001340** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001341** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1342** guarantee that the page is well-formed. It only shows that
1343** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001344*/
drh9e572e62004-04-23 23:43:10 +00001345static int initPage(
drh3aac2dd2004-04-26 14:10:20 +00001346 MemPage *pPage, /* The page to be initialized */
drh9e572e62004-04-23 23:43:10 +00001347 MemPage *pParent /* The parent. Might be NULL */
1348){
drh271efa52004-05-30 19:19:05 +00001349 int pc; /* Address of a freeblock within pPage->aData[] */
drh271efa52004-05-30 19:19:05 +00001350 int hdr; /* Offset to beginning of page header */
1351 u8 *data; /* Equal to pPage->aData */
danielk1977aef0bf62005-12-30 16:28:01 +00001352 BtShared *pBt; /* The main btree structure */
drh271efa52004-05-30 19:19:05 +00001353 int usableSize; /* Amount of usable space on each page */
1354 int cellOffset; /* Offset from start of page to first cell pointer */
1355 int nFree; /* Number of unused bytes on the page */
1356 int top; /* First byte of the cell content area */
drh2af926b2001-05-15 00:39:25 +00001357
drh2e38c322004-09-03 18:38:44 +00001358 pBt = pPage->pBt;
1359 assert( pBt!=0 );
1360 assert( pParent==0 || pParent->pBt==pBt );
drha34b6762004-05-07 13:30:42 +00001361 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
drh07d183d2005-05-01 22:52:42 +00001362 assert( pPage->aData == &((unsigned char*)pPage)[-pBt->pageSize] );
drhee696e22004-08-30 16:52:17 +00001363 if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
1364 /* The parent page should never change unless the file is corrupt */
drh49285702005-09-17 15:20:26 +00001365 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001366 }
drh10617cd2004-05-14 15:27:27 +00001367 if( pPage->isInit ) return SQLITE_OK;
drhda200cc2004-05-09 11:51:38 +00001368 if( pPage->pParent==0 && pParent!=0 ){
1369 pPage->pParent = pParent;
drha34b6762004-05-07 13:30:42 +00001370 sqlite3pager_ref(pParent->aData);
drh5e2f8b92001-05-28 00:41:15 +00001371 }
drhde647132004-05-07 17:57:49 +00001372 hdr = pPage->hdrOffset;
drha34b6762004-05-07 13:30:42 +00001373 data = pPage->aData;
drh271efa52004-05-30 19:19:05 +00001374 decodeFlags(pPage, data[hdr]);
drh43605152004-05-29 21:46:49 +00001375 pPage->nOverflow = 0;
drhc8629a12004-05-08 20:07:40 +00001376 pPage->idxShift = 0;
drh2e38c322004-09-03 18:38:44 +00001377 usableSize = pBt->usableSize;
drh43605152004-05-29 21:46:49 +00001378 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
1379 top = get2byte(&data[hdr+5]);
1380 pPage->nCell = get2byte(&data[hdr+3]);
drh2e38c322004-09-03 18:38:44 +00001381 if( pPage->nCell>MX_CELL(pBt) ){
drhee696e22004-08-30 16:52:17 +00001382 /* To many cells for a single page. The page must be corrupt */
drh49285702005-09-17 15:20:26 +00001383 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001384 }
1385 if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
1386 /* All pages must have at least one cell, except for root pages */
drh49285702005-09-17 15:20:26 +00001387 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001388 }
drh9e572e62004-04-23 23:43:10 +00001389
1390 /* Compute the total free space on the page */
drh9e572e62004-04-23 23:43:10 +00001391 pc = get2byte(&data[hdr+1]);
drh43605152004-05-29 21:46:49 +00001392 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
drh9e572e62004-04-23 23:43:10 +00001393 while( pc>0 ){
1394 int next, size;
drhee696e22004-08-30 16:52:17 +00001395 if( pc>usableSize-4 ){
1396 /* Free block is off the page */
drh49285702005-09-17 15:20:26 +00001397 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001398 }
drh9e572e62004-04-23 23:43:10 +00001399 next = get2byte(&data[pc]);
1400 size = get2byte(&data[pc+2]);
drhee696e22004-08-30 16:52:17 +00001401 if( next>0 && next<=pc+size+3 ){
1402 /* Free blocks must be in accending order */
drh49285702005-09-17 15:20:26 +00001403 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001404 }
drh3add3672004-05-15 00:29:24 +00001405 nFree += size;
drh9e572e62004-04-23 23:43:10 +00001406 pc = next;
1407 }
drh3add3672004-05-15 00:29:24 +00001408 pPage->nFree = nFree;
drhee696e22004-08-30 16:52:17 +00001409 if( nFree>=usableSize ){
1410 /* Free space cannot exceed total page size */
drh49285702005-09-17 15:20:26 +00001411 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001412 }
drh9e572e62004-04-23 23:43:10 +00001413
drhde647132004-05-07 17:57:49 +00001414 pPage->isInit = 1;
drhda200cc2004-05-09 11:51:38 +00001415 pageIntegrity(pPage);
drh9e572e62004-04-23 23:43:10 +00001416 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001417}
1418
1419/*
drh8b2f49b2001-06-08 00:21:52 +00001420** Set up a raw page so that it looks like a database page holding
1421** no entries.
drhbd03cae2001-06-02 02:40:57 +00001422*/
drh9e572e62004-04-23 23:43:10 +00001423static void zeroPage(MemPage *pPage, int flags){
1424 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001425 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00001426 int hdr = pPage->hdrOffset;
drh9e572e62004-04-23 23:43:10 +00001427 int first;
1428
drhda200cc2004-05-09 11:51:38 +00001429 assert( sqlite3pager_pagenumber(data)==pPage->pgno );
drh07d183d2005-05-01 22:52:42 +00001430 assert( &data[pBt->pageSize] == (unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +00001431 assert( sqlite3pager_iswriteable(data) );
drhb6f41482004-05-14 01:58:11 +00001432 memset(&data[hdr], 0, pBt->usableSize - hdr);
drh9e572e62004-04-23 23:43:10 +00001433 data[hdr] = flags;
drh43605152004-05-29 21:46:49 +00001434 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
1435 memset(&data[hdr+1], 0, 4);
1436 data[hdr+7] = 0;
1437 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +00001438 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +00001439 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +00001440 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +00001441 pPage->cellOffset = first;
1442 pPage->nOverflow = 0;
drhda200cc2004-05-09 11:51:38 +00001443 pPage->idxShift = 0;
drh43605152004-05-29 21:46:49 +00001444 pPage->nCell = 0;
drhda200cc2004-05-09 11:51:38 +00001445 pPage->isInit = 1;
1446 pageIntegrity(pPage);
drhbd03cae2001-06-02 02:40:57 +00001447}
1448
1449/*
drh3aac2dd2004-04-26 14:10:20 +00001450** Get a page from the pager. Initialize the MemPage.pBt and
1451** MemPage.aData elements if needed.
1452*/
danielk1977aef0bf62005-12-30 16:28:01 +00001453static int getPage(BtShared *pBt, Pgno pgno, MemPage **ppPage){
drh3aac2dd2004-04-26 14:10:20 +00001454 int rc;
1455 unsigned char *aData;
1456 MemPage *pPage;
drha34b6762004-05-07 13:30:42 +00001457 rc = sqlite3pager_get(pBt->pPager, pgno, (void**)&aData);
drh3aac2dd2004-04-26 14:10:20 +00001458 if( rc ) return rc;
drh07d183d2005-05-01 22:52:42 +00001459 pPage = (MemPage*)&aData[pBt->pageSize];
drh3aac2dd2004-04-26 14:10:20 +00001460 pPage->aData = aData;
1461 pPage->pBt = pBt;
1462 pPage->pgno = pgno;
drhde647132004-05-07 17:57:49 +00001463 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
drh3aac2dd2004-04-26 14:10:20 +00001464 *ppPage = pPage;
1465 return SQLITE_OK;
1466}
1467
1468/*
drhde647132004-05-07 17:57:49 +00001469** Get a page from the pager and initialize it. This routine
1470** is just a convenience wrapper around separate calls to
1471** getPage() and initPage().
1472*/
1473static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +00001474 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +00001475 Pgno pgno, /* Number of the page to get */
1476 MemPage **ppPage, /* Write the page pointer here */
1477 MemPage *pParent /* Parent of the page */
1478){
1479 int rc;
drhee696e22004-08-30 16:52:17 +00001480 if( pgno==0 ){
drh49285702005-09-17 15:20:26 +00001481 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001482 }
drhde647132004-05-07 17:57:49 +00001483 rc = getPage(pBt, pgno, ppPage);
drh10617cd2004-05-14 15:27:27 +00001484 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
drhde647132004-05-07 17:57:49 +00001485 rc = initPage(*ppPage, pParent);
1486 }
1487 return rc;
1488}
1489
1490/*
drh3aac2dd2004-04-26 14:10:20 +00001491** Release a MemPage. This should be called once for each prior
1492** call to getPage.
1493*/
drh4b70f112004-05-02 21:12:19 +00001494static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001495 if( pPage ){
1496 assert( pPage->aData );
1497 assert( pPage->pBt );
drh07d183d2005-05-01 22:52:42 +00001498 assert( &pPage->aData[pPage->pBt->pageSize]==(unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +00001499 sqlite3pager_unref(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00001500 }
1501}
1502
1503/*
drh72f82862001-05-24 21:06:34 +00001504** This routine is called when the reference count for a page
1505** reaches zero. We need to unref the pParent pointer when that
1506** happens.
1507*/
drhb6f41482004-05-14 01:58:11 +00001508static void pageDestructor(void *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +00001509 MemPage *pPage;
1510 assert( (pageSize & 7)==0 );
1511 pPage = (MemPage*)&((char*)pData)[pageSize];
drh72f82862001-05-24 21:06:34 +00001512 if( pPage->pParent ){
1513 MemPage *pParent = pPage->pParent;
1514 pPage->pParent = 0;
drha34b6762004-05-07 13:30:42 +00001515 releasePage(pParent);
drh72f82862001-05-24 21:06:34 +00001516 }
drh3aac2dd2004-04-26 14:10:20 +00001517 pPage->isInit = 0;
drh72f82862001-05-24 21:06:34 +00001518}
1519
1520/*
drha6abd042004-06-09 17:37:22 +00001521** During a rollback, when the pager reloads information into the cache
1522** so that the cache is restored to its original state at the start of
1523** the transaction, for each page restored this routine is called.
1524**
1525** This routine needs to reset the extra data section at the end of the
1526** page to agree with the restored data.
1527*/
1528static void pageReinit(void *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +00001529 MemPage *pPage;
1530 assert( (pageSize & 7)==0 );
1531 pPage = (MemPage*)&((char*)pData)[pageSize];
drha6abd042004-06-09 17:37:22 +00001532 if( pPage->isInit ){
1533 pPage->isInit = 0;
1534 initPage(pPage, pPage->pParent);
1535 }
1536}
1537
1538/*
drhad3e0102004-09-03 23:32:18 +00001539** Open a database file.
1540**
drh382c0242001-10-06 16:33:02 +00001541** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001542** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001543** database file will be deleted when sqlite3BtreeClose() is called.
drha059ad02001-04-17 20:09:11 +00001544*/
drh23e11ca2004-05-04 17:27:28 +00001545int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001546 const char *zFilename, /* Name of the file containing the BTree database */
danielk1977aef0bf62005-12-30 16:28:01 +00001547 sqlite3 *pSqlite, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001548 Btree **ppBtree, /* Pointer to new Btree object written here */
drh90f5ecb2004-07-22 01:19:35 +00001549 int flags /* Options */
drh6019e162001-07-02 17:51:45 +00001550){
danielk1977aef0bf62005-12-30 16:28:01 +00001551 BtShared *pBt; /* Shared part of btree structure */
1552 Btree *p; /* Handle to return */
drha34b6762004-05-07 13:30:42 +00001553 int rc;
drh90f5ecb2004-07-22 01:19:35 +00001554 int nReserve;
1555 unsigned char zDbHeader[100];
drh6f7adc82006-01-11 21:41:20 +00001556#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1557 const ThreadData *pTsdro;
danielk1977da184232006-01-05 11:34:32 +00001558#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001559
1560 /* Set the variable isMemdb to true for an in-memory database, or
1561 ** false for a file-based database. This symbol is only required if
1562 ** either of the shared-data or autovacuum features are compiled
1563 ** into the library.
1564 */
1565#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1566 #ifdef SQLITE_OMIT_MEMORYDB
1567 const int isMemdb = !zFilename;
1568 #else
1569 const int isMemdb = !zFilename || (strcmp(zFilename, ":memory:")?0:1);
1570 #endif
1571#endif
1572
1573 p = sqliteMalloc(sizeof(Btree));
1574 if( !p ){
1575 return SQLITE_NOMEM;
1576 }
1577 p->inTrans = TRANS_NONE;
1578 p->pSqlite = pSqlite;
1579
1580 /* Try to find an existing Btree structure opened on zFilename. */
drh198bf392006-01-06 21:52:49 +00001581#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drh6f7adc82006-01-11 21:41:20 +00001582 pTsdro = sqlite3ThreadDataReadOnly();
1583 if( pTsdro->useSharedData && zFilename && !isMemdb ){
drh66560ad2006-01-06 14:32:19 +00001584 char *zFullPathname = sqlite3OsFullPathname(zFilename);
danielk1977aef0bf62005-12-30 16:28:01 +00001585 if( !zFullPathname ){
1586 sqliteFree(p);
1587 return SQLITE_NOMEM;
1588 }
drh6f7adc82006-01-11 21:41:20 +00001589 for(pBt=pTsdro->pBtree; pBt; pBt=pBt->pNext){
danielk1977b82e7ed2006-01-11 14:09:31 +00001590 assert( pBt->nRef>0 );
danielk1977aef0bf62005-12-30 16:28:01 +00001591 if( 0==strcmp(zFullPathname, sqlite3pager_filename(pBt->pPager)) ){
1592 p->pBt = pBt;
1593 *ppBtree = p;
1594 pBt->nRef++;
1595 sqliteFree(zFullPathname);
1596 return SQLITE_OK;
1597 }
1598 }
1599 sqliteFree(zFullPathname);
1600 }
1601#endif
drha059ad02001-04-17 20:09:11 +00001602
drhd62d3d02003-01-24 12:14:20 +00001603 /*
1604 ** The following asserts make sure that structures used by the btree are
1605 ** the right size. This is to guard against size changes that result
1606 ** when compiling on a different architecture.
1607 */
drh4a1c3802004-05-12 15:15:47 +00001608 assert( sizeof(i64)==8 );
drh9e572e62004-04-23 23:43:10 +00001609 assert( sizeof(u64)==8 );
drhd62d3d02003-01-24 12:14:20 +00001610 assert( sizeof(u32)==4 );
1611 assert( sizeof(u16)==2 );
1612 assert( sizeof(Pgno)==4 );
drhd62d3d02003-01-24 12:14:20 +00001613
drha059ad02001-04-17 20:09:11 +00001614 pBt = sqliteMalloc( sizeof(*pBt) );
1615 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +00001616 *ppBtree = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00001617 sqliteFree(p);
drha059ad02001-04-17 20:09:11 +00001618 return SQLITE_NOMEM;
1619 }
drh7bec5052005-02-06 02:45:41 +00001620 rc = sqlite3pager_open(&pBt->pPager, zFilename, EXTRA_SIZE, flags);
drha059ad02001-04-17 20:09:11 +00001621 if( rc!=SQLITE_OK ){
drha34b6762004-05-07 13:30:42 +00001622 if( pBt->pPager ) sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001623 sqliteFree(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00001624 sqliteFree(p);
drha059ad02001-04-17 20:09:11 +00001625 *ppBtree = 0;
1626 return rc;
1627 }
danielk1977aef0bf62005-12-30 16:28:01 +00001628 p->pBt = pBt;
1629
drha34b6762004-05-07 13:30:42 +00001630 sqlite3pager_set_destructor(pBt->pPager, pageDestructor);
drha6abd042004-06-09 17:37:22 +00001631 sqlite3pager_set_reiniter(pBt->pPager, pageReinit);
drha059ad02001-04-17 20:09:11 +00001632 pBt->pCursor = 0;
drha34b6762004-05-07 13:30:42 +00001633 pBt->pPage1 = 0;
1634 pBt->readOnly = sqlite3pager_isreadonly(pBt->pPager);
drh90f5ecb2004-07-22 01:19:35 +00001635 sqlite3pager_read_fileheader(pBt->pPager, sizeof(zDbHeader), zDbHeader);
1636 pBt->pageSize = get2byte(&zDbHeader[16]);
drh07d183d2005-05-01 22:52:42 +00001637 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1638 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
drh90f5ecb2004-07-22 01:19:35 +00001639 pBt->pageSize = SQLITE_DEFAULT_PAGE_SIZE;
1640 pBt->maxEmbedFrac = 64; /* 25% */
1641 pBt->minEmbedFrac = 32; /* 12.5% */
1642 pBt->minLeafFrac = 32; /* 12.5% */
drheee46cf2004-11-06 00:02:48 +00001643#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197703aded42004-11-22 05:26:27 +00001644 /* If the magic name ":memory:" will create an in-memory database, then
1645 ** do not set the auto-vacuum flag, even if SQLITE_DEFAULT_AUTOVACUUM
1646 ** is true. On the other hand, if SQLITE_OMIT_MEMORYDB has been defined,
1647 ** then ":memory:" is just a regular file-name. Respect the auto-vacuum
1648 ** default in this case.
1649 */
danielk1977aef0bf62005-12-30 16:28:01 +00001650 if( zFilename && !isMemdb ){
danielk1977951af802004-11-05 15:45:09 +00001651 pBt->autoVacuum = SQLITE_DEFAULT_AUTOVACUUM;
1652 }
drheee46cf2004-11-06 00:02:48 +00001653#endif
drh90f5ecb2004-07-22 01:19:35 +00001654 nReserve = 0;
1655 }else{
1656 nReserve = zDbHeader[20];
1657 pBt->maxEmbedFrac = zDbHeader[21];
1658 pBt->minEmbedFrac = zDbHeader[22];
1659 pBt->minLeafFrac = zDbHeader[23];
1660 pBt->pageSizeFixed = 1;
danielk1977951af802004-11-05 15:45:09 +00001661#ifndef SQLITE_OMIT_AUTOVACUUM
1662 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1663#endif
drh90f5ecb2004-07-22 01:19:35 +00001664 }
1665 pBt->usableSize = pBt->pageSize - nReserve;
drh07d183d2005-05-01 22:52:42 +00001666 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
drh90f5ecb2004-07-22 01:19:35 +00001667 sqlite3pager_set_pagesize(pBt->pPager, pBt->pageSize);
danielk1977aef0bf62005-12-30 16:28:01 +00001668
1669#ifndef SQLITE_OMIT_SHARED_CACHE
danielk197754f01982006-01-18 15:25:17 +00001670 /* Add the new btree to the linked list starting at ThreadData.pBtree.
1671 ** There is no chance that a malloc() may fail inside of the
1672 ** sqlite3ThreadData() call, as the ThreadData structure must have already
1673 ** been allocated for pTsdro->useSharedData to be non-zero.
1674 */
drh6f7adc82006-01-11 21:41:20 +00001675 if( pTsdro->useSharedData && zFilename && !isMemdb ){
1676 pBt->pNext = pTsdro->pBtree;
1677 sqlite3ThreadData()->pBtree = pBt;
danielk1977aef0bf62005-12-30 16:28:01 +00001678 }
danielk1977aef0bf62005-12-30 16:28:01 +00001679#endif
danielk1977da184232006-01-05 11:34:32 +00001680 pBt->nRef = 1;
danielk1977aef0bf62005-12-30 16:28:01 +00001681 *ppBtree = p;
drha059ad02001-04-17 20:09:11 +00001682 return SQLITE_OK;
1683}
1684
1685/*
1686** Close an open database and invalidate all cursors.
1687*/
danielk1977aef0bf62005-12-30 16:28:01 +00001688int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00001689 BtShared *pBt = p->pBt;
1690 BtCursor *pCur;
1691
danielk1977da184232006-01-05 11:34:32 +00001692#ifndef SQLITE_OMIT_SHARED_CACHE
drh6f7adc82006-01-11 21:41:20 +00001693 ThreadData *pTsd;
danielk1977da184232006-01-05 11:34:32 +00001694#endif
1695
danielk1977aef0bf62005-12-30 16:28:01 +00001696 /* Drop any table-locks */
1697 unlockAllTables(p);
1698
1699 /* Close all cursors opened via this handle. */
1700 pCur = pBt->pCursor;
1701 while( pCur ){
1702 BtCursor *pTmp = pCur;
1703 pCur = pCur->pNext;
1704 if( pTmp->pBtree==p ){
1705 sqlite3BtreeCloseCursor(pTmp);
1706 }
drha059ad02001-04-17 20:09:11 +00001707 }
danielk1977aef0bf62005-12-30 16:28:01 +00001708
danielk1977b597f742006-01-15 11:39:18 +00001709 /* Rollback any active transaction and free the handle structure */
1710 sqlite3BtreeRollback(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001711 sqliteFree(p);
1712
1713#ifndef SQLITE_OMIT_SHARED_CACHE
1714 /* If there are still other outstanding references to the shared-btree
1715 ** structure, return now. The remainder of this procedure cleans
1716 ** up the shared-btree.
1717 */
1718 assert( pBt->nRef>0 );
1719 pBt->nRef--;
1720 if( pBt->nRef ){
1721 return SQLITE_OK;
1722 }
1723
danielk197754f01982006-01-18 15:25:17 +00001724 /* Remove the shared-btree from the thread wide list. Call
1725 ** ThreadDataReadOnly() and then cast away the const property of the
1726 ** pointer to avoid allocating thread data if it is not really required.
1727 */
1728 pTsd = (ThreadData *)sqlite3ThreadDataReadOnly();
danielk1977aef0bf62005-12-30 16:28:01 +00001729 if( pTsd->pBtree==pBt ){
danielk197754f01982006-01-18 15:25:17 +00001730 assert( pTsd==sqlite3ThreadData() );
danielk1977aef0bf62005-12-30 16:28:01 +00001731 pTsd->pBtree = pBt->pNext;
1732 }else{
1733 BtShared *pPrev;
1734 for(pPrev=pTsd->pBtree; pPrev && pPrev->pNext!=pBt; pPrev=pPrev->pNext);
1735 if( pPrev ){
danielk197754f01982006-01-18 15:25:17 +00001736 assert( pTsd==sqlite3ThreadData() );
danielk1977aef0bf62005-12-30 16:28:01 +00001737 pPrev->pNext = pBt->pNext;
1738 }
1739 }
1740#endif
1741
1742 /* Close the pager and free the shared-btree structure */
1743 assert( !pBt->pCursor );
drha34b6762004-05-07 13:30:42 +00001744 sqlite3pager_close(pBt->pPager);
danielk1977da184232006-01-05 11:34:32 +00001745 if( pBt->xFreeSchema && pBt->pSchema ){
1746 pBt->xFreeSchema(pBt->pSchema);
1747 }
danielk1977de0fe3e2006-01-06 06:33:12 +00001748 sqliteFree(pBt->pSchema);
drha059ad02001-04-17 20:09:11 +00001749 sqliteFree(pBt);
1750 return SQLITE_OK;
1751}
1752
1753/*
drh90f5ecb2004-07-22 01:19:35 +00001754** Change the busy handler callback function.
1755*/
danielk1977aef0bf62005-12-30 16:28:01 +00001756int sqlite3BtreeSetBusyHandler(Btree *p, BusyHandler *pHandler){
1757 BtShared *pBt = p->pBt;
drhb8ef32c2005-03-14 02:01:49 +00001758 pBt->pBusyHandler = pHandler;
drh90f5ecb2004-07-22 01:19:35 +00001759 sqlite3pager_set_busyhandler(pBt->pPager, pHandler);
1760 return SQLITE_OK;
1761}
1762
1763/*
drhda47d772002-12-02 04:25:19 +00001764** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001765**
1766** The maximum number of cache pages is set to the absolute
1767** value of mxPage. If mxPage is negative, the pager will
1768** operate asynchronously - it will not stop to do fsync()s
1769** to insure data is written to the disk surface before
1770** continuing. Transactions still work if synchronous is off,
1771** and the database cannot be corrupted if this program
1772** crashes. But if the operating system crashes or there is
1773** an abrupt power failure when synchronous is off, the database
1774** could be left in an inconsistent and unrecoverable state.
1775** Synchronous is on by default so database corruption is not
1776** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001777*/
danielk1977aef0bf62005-12-30 16:28:01 +00001778int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
1779 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00001780 sqlite3pager_set_cachesize(pBt->pPager, mxPage);
drhf57b14a2001-09-14 18:54:08 +00001781 return SQLITE_OK;
1782}
1783
1784/*
drh973b6e32003-02-12 14:09:42 +00001785** Change the way data is synced to disk in order to increase or decrease
1786** how well the database resists damage due to OS crashes and power
1787** failures. Level 1 is the same as asynchronous (no syncs() occur and
1788** there is a high probability of damage) Level 2 is the default. There
1789** is a very low but non-zero probability of damage. Level 3 reduces the
1790** probability of damage to near zero but with a write performance reduction.
1791*/
danielk197793758c82005-01-21 08:13:14 +00001792#ifndef SQLITE_OMIT_PAGER_PRAGMAS
danielk1977aef0bf62005-12-30 16:28:01 +00001793int sqlite3BtreeSetSafetyLevel(Btree *p, int level){
1794 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00001795 sqlite3pager_set_safety_level(pBt->pPager, level);
drh973b6e32003-02-12 14:09:42 +00001796 return SQLITE_OK;
1797}
danielk197793758c82005-01-21 08:13:14 +00001798#endif
drh973b6e32003-02-12 14:09:42 +00001799
drh2c8997b2005-08-27 16:36:48 +00001800/*
1801** Return TRUE if the given btree is set to safety level 1. In other
1802** words, return TRUE if no sync() occurs on the disk files.
1803*/
danielk1977aef0bf62005-12-30 16:28:01 +00001804int sqlite3BtreeSyncDisabled(Btree *p){
1805 BtShared *pBt = p->pBt;
drh2c8997b2005-08-27 16:36:48 +00001806 assert( pBt && pBt->pPager );
1807 return sqlite3pager_nosync(pBt->pPager);
1808}
1809
danielk1977576ec6b2005-01-21 11:55:25 +00001810#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001811/*
drh90f5ecb2004-07-22 01:19:35 +00001812** Change the default pages size and the number of reserved bytes per page.
drh06f50212004-11-02 14:24:33 +00001813**
1814** The page size must be a power of 2 between 512 and 65536. If the page
1815** size supplied does not meet this constraint then the page size is not
1816** changed.
1817**
1818** Page sizes are constrained to be a power of two so that the region
1819** of the database file used for locking (beginning at PENDING_BYTE,
1820** the first byte past the 1GB boundary, 0x40000000) needs to occur
1821** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001822**
1823** If parameter nReserve is less than zero, then the number of reserved
1824** bytes per page is left unchanged.
drh90f5ecb2004-07-22 01:19:35 +00001825*/
danielk1977aef0bf62005-12-30 16:28:01 +00001826int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
1827 BtShared *pBt = p->pBt;
drh90f5ecb2004-07-22 01:19:35 +00001828 if( pBt->pageSizeFixed ){
1829 return SQLITE_READONLY;
1830 }
1831 if( nReserve<0 ){
1832 nReserve = pBt->pageSize - pBt->usableSize;
1833 }
drh06f50212004-11-02 14:24:33 +00001834 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
1835 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00001836 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00001837 assert( !pBt->pPage1 && !pBt->pCursor );
drh1c7880e2005-05-20 20:01:55 +00001838 pBt->pageSize = sqlite3pager_set_pagesize(pBt->pPager, pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001839 }
1840 pBt->usableSize = pBt->pageSize - nReserve;
1841 return SQLITE_OK;
1842}
1843
1844/*
1845** Return the currently defined page size
1846*/
danielk1977aef0bf62005-12-30 16:28:01 +00001847int sqlite3BtreeGetPageSize(Btree *p){
1848 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00001849}
danielk1977aef0bf62005-12-30 16:28:01 +00001850int sqlite3BtreeGetReserve(Btree *p){
1851 return p->pBt->pageSize - p->pBt->usableSize;
drh2011d5f2004-07-22 02:40:37 +00001852}
danielk1977576ec6b2005-01-21 11:55:25 +00001853#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00001854
1855/*
danielk1977951af802004-11-05 15:45:09 +00001856** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
1857** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
1858** is disabled. The default value for the auto-vacuum property is
1859** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
1860*/
danielk1977aef0bf62005-12-30 16:28:01 +00001861int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
1862 BtShared *pBt = p->pBt;;
danielk1977951af802004-11-05 15:45:09 +00001863#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001864 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00001865#else
1866 if( pBt->pageSizeFixed ){
1867 return SQLITE_READONLY;
1868 }
1869 pBt->autoVacuum = (autoVacuum?1:0);
1870 return SQLITE_OK;
1871#endif
1872}
1873
1874/*
1875** Return the value of the 'auto-vacuum' property. If auto-vacuum is
1876** enabled 1 is returned. Otherwise 0.
1877*/
danielk1977aef0bf62005-12-30 16:28:01 +00001878int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00001879#ifdef SQLITE_OMIT_AUTOVACUUM
1880 return 0;
1881#else
danielk1977aef0bf62005-12-30 16:28:01 +00001882 return p->pBt->autoVacuum;
danielk1977951af802004-11-05 15:45:09 +00001883#endif
1884}
1885
1886
1887/*
drha34b6762004-05-07 13:30:42 +00001888** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001889** also acquire a readlock on that file.
1890**
1891** SQLITE_OK is returned on success. If the file is not a
1892** well-formed database file, then SQLITE_CORRUPT is returned.
1893** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
1894** is returned if we run out of memory. SQLITE_PROTOCOL is returned
1895** if there is a locking protocol violation.
1896*/
danielk1977aef0bf62005-12-30 16:28:01 +00001897static int lockBtree(BtShared *pBt){
drh07d183d2005-05-01 22:52:42 +00001898 int rc, pageSize;
drh3aac2dd2004-04-26 14:10:20 +00001899 MemPage *pPage1;
drha34b6762004-05-07 13:30:42 +00001900 if( pBt->pPage1 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001901 rc = getPage(pBt, 1, &pPage1);
drh306dc212001-05-21 13:45:10 +00001902 if( rc!=SQLITE_OK ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00001903
drh306dc212001-05-21 13:45:10 +00001904
1905 /* Do some checking to help insure the file we opened really is
1906 ** a valid database file.
1907 */
drhb6f41482004-05-14 01:58:11 +00001908 rc = SQLITE_NOTADB;
drha34b6762004-05-07 13:30:42 +00001909 if( sqlite3pager_pagecount(pBt->pPager)>0 ){
drhb6f41482004-05-14 01:58:11 +00001910 u8 *page1 = pPage1->aData;
1911 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001912 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001913 }
drhb6f41482004-05-14 01:58:11 +00001914 if( page1[18]>1 || page1[19]>1 ){
1915 goto page1_init_failed;
1916 }
drh07d183d2005-05-01 22:52:42 +00001917 pageSize = get2byte(&page1[16]);
1918 if( ((pageSize-1)&pageSize)!=0 ){
1919 goto page1_init_failed;
1920 }
1921 assert( (pageSize & 7)==0 );
1922 pBt->pageSize = pageSize;
1923 pBt->usableSize = pageSize - page1[20];
drhb6f41482004-05-14 01:58:11 +00001924 if( pBt->usableSize<500 ){
1925 goto page1_init_failed;
1926 }
1927 pBt->maxEmbedFrac = page1[21];
1928 pBt->minEmbedFrac = page1[22];
1929 pBt->minLeafFrac = page1[23];
drh057cd3a2005-02-15 16:23:02 +00001930#ifndef SQLITE_OMIT_AUTOVACUUM
1931 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
1932#endif
drh306dc212001-05-21 13:45:10 +00001933 }
drhb6f41482004-05-14 01:58:11 +00001934
1935 /* maxLocal is the maximum amount of payload to store locally for
1936 ** a cell. Make sure it is small enough so that at least minFanout
1937 ** cells can will fit on one page. We assume a 10-byte page header.
1938 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001939 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001940 ** 4-byte child pointer
1941 ** 9-byte nKey value
1942 ** 4-byte nData value
1943 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001944 ** So a cell consists of a 2-byte poiner, a header which is as much as
1945 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1946 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001947 */
drh43605152004-05-29 21:46:49 +00001948 pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
1949 pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
1950 pBt->maxLeaf = pBt->usableSize - 35;
1951 pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
drhb6f41482004-05-14 01:58:11 +00001952 if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
1953 goto page1_init_failed;
1954 }
drh2e38c322004-09-03 18:38:44 +00001955 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001956 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001957 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001958
drh72f82862001-05-24 21:06:34 +00001959page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001960 releasePage(pPage1);
1961 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001962 return rc;
drh306dc212001-05-21 13:45:10 +00001963}
1964
1965/*
drhb8ef32c2005-03-14 02:01:49 +00001966** This routine works like lockBtree() except that it also invokes the
1967** busy callback if there is lock contention.
1968*/
danielk1977aef0bf62005-12-30 16:28:01 +00001969static int lockBtreeWithRetry(Btree *pRef){
drhb8ef32c2005-03-14 02:01:49 +00001970 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00001971 if( pRef->inTrans==TRANS_NONE ){
1972 u8 inTransaction = pRef->pBt->inTransaction;
1973 btreeIntegrity(pRef);
1974 rc = sqlite3BtreeBeginTrans(pRef, 0);
1975 pRef->pBt->inTransaction = inTransaction;
1976 pRef->inTrans = TRANS_NONE;
1977 if( rc==SQLITE_OK ){
1978 pRef->pBt->nTransaction--;
1979 }
1980 btreeIntegrity(pRef);
drhb8ef32c2005-03-14 02:01:49 +00001981 }
1982 return rc;
1983}
1984
1985
1986/*
drhb8ca3072001-12-05 00:21:20 +00001987** If there are no outstanding cursors and we are not in the middle
1988** of a transaction but there is a read lock on the database, then
1989** this routine unrefs the first page of the database file which
1990** has the effect of releasing the read lock.
1991**
1992** If there are any outstanding cursors, this routine is a no-op.
1993**
1994** If there is a transaction in progress, this routine is a no-op.
1995*/
danielk1977aef0bf62005-12-30 16:28:01 +00001996static void unlockBtreeIfUnused(BtShared *pBt){
1997 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
drh51c6d962004-06-06 00:42:25 +00001998 if( pBt->pPage1->aData==0 ){
1999 MemPage *pPage = pBt->pPage1;
drh2646da72005-12-09 20:02:05 +00002000 pPage->aData = &((u8*)pPage)[-pBt->pageSize];
drh51c6d962004-06-06 00:42:25 +00002001 pPage->pBt = pBt;
2002 pPage->pgno = 1;
2003 }
drh3aac2dd2004-04-26 14:10:20 +00002004 releasePage(pBt->pPage1);
2005 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00002006 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00002007 }
2008}
2009
2010/*
drh9e572e62004-04-23 23:43:10 +00002011** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00002012** file.
drh8b2f49b2001-06-08 00:21:52 +00002013*/
danielk1977aef0bf62005-12-30 16:28:01 +00002014static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00002015 MemPage *pP1;
2016 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00002017 int rc;
drhde647132004-05-07 17:57:49 +00002018 if( sqlite3pager_pagecount(pBt->pPager)>0 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00002019 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00002020 assert( pP1!=0 );
2021 data = pP1->aData;
drha34b6762004-05-07 13:30:42 +00002022 rc = sqlite3pager_write(data);
drh8b2f49b2001-06-08 00:21:52 +00002023 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00002024 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
2025 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00002026 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00002027 data[18] = 1;
2028 data[19] = 1;
drhb6f41482004-05-14 01:58:11 +00002029 data[20] = pBt->pageSize - pBt->usableSize;
2030 data[21] = pBt->maxEmbedFrac;
2031 data[22] = pBt->minEmbedFrac;
2032 data[23] = pBt->minLeafFrac;
2033 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00002034 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00002035 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00002036#ifndef SQLITE_OMIT_AUTOVACUUM
2037 if( pBt->autoVacuum ){
2038 put4byte(&data[36 + 4*4], 1);
2039 }
2040#endif
drh8b2f49b2001-06-08 00:21:52 +00002041 return SQLITE_OK;
2042}
2043
2044/*
danielk1977ee5741e2004-05-31 10:01:34 +00002045** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00002046** is started if the second argument is nonzero, otherwise a read-
2047** transaction. If the second argument is 2 or more and exclusive
2048** transaction is started, meaning that no other process is allowed
2049** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00002050** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00002051** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00002052**
danielk1977ee5741e2004-05-31 10:01:34 +00002053** A write-transaction must be started before attempting any
2054** changes to the database. None of the following routines
2055** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00002056**
drh23e11ca2004-05-04 17:27:28 +00002057** sqlite3BtreeCreateTable()
2058** sqlite3BtreeCreateIndex()
2059** sqlite3BtreeClearTable()
2060** sqlite3BtreeDropTable()
2061** sqlite3BtreeInsert()
2062** sqlite3BtreeDelete()
2063** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00002064**
drhb8ef32c2005-03-14 02:01:49 +00002065** If an initial attempt to acquire the lock fails because of lock contention
2066** and the database was previously unlocked, then invoke the busy handler
2067** if there is one. But if there was previously a read-lock, do not
2068** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
2069** returned when there is already a read-lock in order to avoid a deadlock.
2070**
2071** Suppose there are two processes A and B. A has a read lock and B has
2072** a reserved lock. B tries to promote to exclusive but is blocked because
2073** of A's read lock. A tries to promote to reserved but is blocked by B.
2074** One or the other of the two processes must give way or there can be
2075** no progress. By returning SQLITE_BUSY and not invoking the busy callback
2076** when A already has a read lock, we encourage A to give up and let B
2077** proceed.
drha059ad02001-04-17 20:09:11 +00002078*/
danielk1977aef0bf62005-12-30 16:28:01 +00002079int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
2080 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00002081 int rc = SQLITE_OK;
2082
danielk1977aef0bf62005-12-30 16:28:01 +00002083 btreeIntegrity(p);
2084
danielk1977ee5741e2004-05-31 10:01:34 +00002085 /* If the btree is already in a write-transaction, or it
2086 ** is already in a read-transaction and a read-transaction
2087 ** is requested, this is a no-op.
2088 */
danielk1977aef0bf62005-12-30 16:28:01 +00002089 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
danielk1977ee5741e2004-05-31 10:01:34 +00002090 return SQLITE_OK;
2091 }
drhb8ef32c2005-03-14 02:01:49 +00002092
2093 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00002094 if( pBt->readOnly && wrflag ){
2095 return SQLITE_READONLY;
2096 }
2097
danielk1977aef0bf62005-12-30 16:28:01 +00002098 /* If another database handle has already opened a write transaction
2099 ** on this shared-btree structure and a second write transaction is
2100 ** requested, return SQLITE_BUSY.
2101 */
2102 if( pBt->inTransaction==TRANS_WRITE && wrflag ){
2103 return SQLITE_BUSY;
2104 }
2105
drhb8ef32c2005-03-14 02:01:49 +00002106 do {
2107 if( pBt->pPage1==0 ){
2108 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +00002109 }
drhb8ef32c2005-03-14 02:01:49 +00002110
2111 if( rc==SQLITE_OK && wrflag ){
2112 rc = sqlite3pager_begin(pBt->pPage1->aData, wrflag>1);
2113 if( rc==SQLITE_OK ){
2114 rc = newDatabase(pBt);
2115 }
2116 }
2117
2118 if( rc==SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00002119 if( wrflag ) pBt->inStmt = 0;
2120 }else{
2121 unlockBtreeIfUnused(pBt);
2122 }
danielk1977aef0bf62005-12-30 16:28:01 +00002123 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
drha4afb652005-07-09 02:16:02 +00002124 sqlite3InvokeBusyHandler(pBt->pBusyHandler) );
danielk1977aef0bf62005-12-30 16:28:01 +00002125
2126 if( rc==SQLITE_OK ){
2127 if( p->inTrans==TRANS_NONE ){
2128 pBt->nTransaction++;
2129 }
2130 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2131 if( p->inTrans>pBt->inTransaction ){
2132 pBt->inTransaction = p->inTrans;
2133 }
2134 }
2135
2136 btreeIntegrity(p);
drhb8ca3072001-12-05 00:21:20 +00002137 return rc;
drha059ad02001-04-17 20:09:11 +00002138}
2139
danielk1977687566d2004-11-02 12:56:41 +00002140#ifndef SQLITE_OMIT_AUTOVACUUM
2141
2142/*
2143** Set the pointer-map entries for all children of page pPage. Also, if
2144** pPage contains cells that point to overflow pages, set the pointer
2145** map entries for the overflow pages as well.
2146*/
2147static int setChildPtrmaps(MemPage *pPage){
2148 int i; /* Counter variable */
2149 int nCell; /* Number of cells in page pPage */
2150 int rc = SQLITE_OK; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00002151 BtShared *pBt = pPage->pBt;
danielk1977687566d2004-11-02 12:56:41 +00002152 int isInitOrig = pPage->isInit;
2153 Pgno pgno = pPage->pgno;
2154
2155 initPage(pPage, 0);
2156 nCell = pPage->nCell;
2157
2158 for(i=0; i<nCell; i++){
danielk1977687566d2004-11-02 12:56:41 +00002159 u8 *pCell = findCell(pPage, i);
2160
danielk197726836652005-01-17 01:33:13 +00002161 rc = ptrmapPutOvflPtr(pPage, pCell);
2162 if( rc!=SQLITE_OK ){
2163 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002164 }
danielk197726836652005-01-17 01:33:13 +00002165
danielk1977687566d2004-11-02 12:56:41 +00002166 if( !pPage->leaf ){
2167 Pgno childPgno = get4byte(pCell);
2168 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
2169 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
2170 }
2171 }
2172
2173 if( !pPage->leaf ){
2174 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
2175 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
2176 }
2177
2178set_child_ptrmaps_out:
2179 pPage->isInit = isInitOrig;
2180 return rc;
2181}
2182
2183/*
2184** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
2185** page, is a pointer to page iFrom. Modify this pointer so that it points to
2186** iTo. Parameter eType describes the type of pointer to be modified, as
2187** follows:
2188**
2189** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2190** page of pPage.
2191**
2192** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2193** page pointed to by one of the cells on pPage.
2194**
2195** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2196** overflow page in the list.
2197*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00002198static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
danielk1977687566d2004-11-02 12:56:41 +00002199 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00002200 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00002201 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00002202 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002203 }
danielk1977f78fc082004-11-02 14:40:32 +00002204 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00002205 }else{
2206 int isInitOrig = pPage->isInit;
2207 int i;
2208 int nCell;
2209
2210 initPage(pPage, 0);
2211 nCell = pPage->nCell;
2212
danielk1977687566d2004-11-02 12:56:41 +00002213 for(i=0; i<nCell; i++){
2214 u8 *pCell = findCell(pPage, i);
2215 if( eType==PTRMAP_OVERFLOW1 ){
2216 CellInfo info;
2217 parseCellPtr(pPage, pCell, &info);
2218 if( info.iOverflow ){
2219 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
2220 put4byte(&pCell[info.iOverflow], iTo);
2221 break;
2222 }
2223 }
2224 }else{
2225 if( get4byte(pCell)==iFrom ){
2226 put4byte(pCell, iTo);
2227 break;
2228 }
2229 }
2230 }
2231
2232 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00002233 if( eType!=PTRMAP_BTREE ||
2234 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00002235 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002236 }
danielk1977687566d2004-11-02 12:56:41 +00002237 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
2238 }
2239
2240 pPage->isInit = isInitOrig;
2241 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002242 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002243}
2244
danielk1977003ba062004-11-04 02:57:33 +00002245
danielk19777701e812005-01-10 12:59:51 +00002246/*
2247** Move the open database page pDbPage to location iFreePage in the
2248** database. The pDbPage reference remains valid.
2249*/
danielk1977003ba062004-11-04 02:57:33 +00002250static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00002251 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00002252 MemPage *pDbPage, /* Open page to move */
2253 u8 eType, /* Pointer map 'type' entry for pDbPage */
2254 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
2255 Pgno iFreePage /* The location to move pDbPage to */
danielk1977003ba062004-11-04 02:57:33 +00002256){
2257 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
2258 Pgno iDbPage = pDbPage->pgno;
2259 Pager *pPager = pBt->pPager;
2260 int rc;
2261
danielk1977a0bf2652004-11-04 14:30:04 +00002262 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
2263 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
danielk1977003ba062004-11-04 02:57:33 +00002264
2265 /* Move page iDbPage from it's current location to page number iFreePage */
2266 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
2267 iDbPage, iFreePage, iPtrPage, eType));
2268 rc = sqlite3pager_movepage(pPager, pDbPage->aData, iFreePage);
2269 if( rc!=SQLITE_OK ){
2270 return rc;
2271 }
2272 pDbPage->pgno = iFreePage;
2273
2274 /* If pDbPage was a btree-page, then it may have child pages and/or cells
2275 ** that point to overflow pages. The pointer map entries for all these
2276 ** pages need to be changed.
2277 **
2278 ** If pDbPage is an overflow page, then the first 4 bytes may store a
2279 ** pointer to a subsequent overflow page. If this is the case, then
2280 ** the pointer map needs to be updated for the subsequent overflow page.
2281 */
danielk1977a0bf2652004-11-04 14:30:04 +00002282 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00002283 rc = setChildPtrmaps(pDbPage);
2284 if( rc!=SQLITE_OK ){
2285 return rc;
2286 }
2287 }else{
2288 Pgno nextOvfl = get4byte(pDbPage->aData);
2289 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00002290 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
2291 if( rc!=SQLITE_OK ){
2292 return rc;
2293 }
2294 }
2295 }
2296
2297 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
2298 ** that it points at iFreePage. Also fix the pointer map entry for
2299 ** iPtrPage.
2300 */
danielk1977a0bf2652004-11-04 14:30:04 +00002301 if( eType!=PTRMAP_ROOTPAGE ){
2302 rc = getPage(pBt, iPtrPage, &pPtrPage);
2303 if( rc!=SQLITE_OK ){
2304 return rc;
2305 }
2306 rc = sqlite3pager_write(pPtrPage->aData);
2307 if( rc!=SQLITE_OK ){
2308 releasePage(pPtrPage);
2309 return rc;
2310 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002311 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00002312 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002313 if( rc==SQLITE_OK ){
2314 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
2315 }
danielk1977003ba062004-11-04 02:57:33 +00002316 }
danielk1977003ba062004-11-04 02:57:33 +00002317 return rc;
2318}
2319
danielk1977687566d2004-11-02 12:56:41 +00002320/* Forward declaration required by autoVacuumCommit(). */
danielk1977aef0bf62005-12-30 16:28:01 +00002321static int allocatePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00002322
2323/*
2324** This routine is called prior to sqlite3pager_commit when a transaction
2325** is commited for an auto-vacuum database.
2326*/
danielk1977aef0bf62005-12-30 16:28:01 +00002327static int autoVacuumCommit(BtShared *pBt, Pgno *nTrunc){
danielk1977687566d2004-11-02 12:56:41 +00002328 Pager *pPager = pBt->pPager;
danielk1977e501b892006-01-09 06:29:47 +00002329 Pgno nFreeList; /* Number of pages remaining on the free-list. */
2330 int nPtrMap; /* Number of pointer-map pages deallocated */
2331 Pgno origSize; /* Pages in the database file */
2332 Pgno finSize; /* Pages in the database file after truncation */
2333 int rc; /* Return code */
danielk1977687566d2004-11-02 12:56:41 +00002334 u8 eType;
danielk1977a19df672004-11-03 11:37:07 +00002335 int pgsz = pBt->pageSize; /* Page size for this database */
danielk1977687566d2004-11-02 12:56:41 +00002336 Pgno iDbPage; /* The database page to move */
danielk1977687566d2004-11-02 12:56:41 +00002337 MemPage *pDbMemPage = 0; /* "" */
2338 Pgno iPtrPage; /* The page that contains a pointer to iDbPage */
danielk1977687566d2004-11-02 12:56:41 +00002339 Pgno iFreePage; /* The free-list page to move iDbPage to */
2340 MemPage *pFreeMemPage = 0; /* "" */
2341
2342#ifndef NDEBUG
2343 int nRef = *sqlite3pager_stats(pPager);
2344#endif
2345
2346 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +00002347 if( PTRMAP_ISPAGE(pgsz, sqlite3pager_pagecount(pPager)) ){
drh49285702005-09-17 15:20:26 +00002348 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002349 }
danielk1977687566d2004-11-02 12:56:41 +00002350
2351 /* Figure out how many free-pages are in the database. If there are no
2352 ** free pages, then auto-vacuum is a no-op.
2353 */
2354 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977a19df672004-11-03 11:37:07 +00002355 if( nFreeList==0 ){
danielk1977d761c0c2004-11-05 16:37:02 +00002356 *nTrunc = 0;
danielk1977a19df672004-11-03 11:37:07 +00002357 return SQLITE_OK;
2358 }
danielk1977687566d2004-11-02 12:56:41 +00002359
danielk1977a19df672004-11-03 11:37:07 +00002360 origSize = sqlite3pager_pagecount(pPager);
2361 nPtrMap = (nFreeList-origSize+PTRMAP_PAGENO(pgsz, origSize)+pgsz/5)/(pgsz/5);
2362 finSize = origSize - nFreeList - nPtrMap;
danielk1977fd5f5b62005-09-16 09:52:29 +00002363 if( origSize>=PENDING_BYTE_PAGE(pBt) && finSize<=PENDING_BYTE_PAGE(pBt) ){
danielk1977599fcba2004-11-08 07:13:13 +00002364 finSize--;
drh42cac6d2004-11-20 20:31:11 +00002365 if( PTRMAP_ISPAGE(pBt->usableSize, finSize) ){
danielk1977599fcba2004-11-08 07:13:13 +00002366 finSize--;
2367 }
2368 }
danielk1977a19df672004-11-03 11:37:07 +00002369 TRACE(("AUTOVACUUM: Begin (db size %d->%d)\n", origSize, finSize));
danielk1977687566d2004-11-02 12:56:41 +00002370
danielk1977a19df672004-11-03 11:37:07 +00002371 /* Variable 'finSize' will be the size of the file in pages after
danielk1977687566d2004-11-02 12:56:41 +00002372 ** the auto-vacuum has completed (the current file size minus the number
2373 ** of pages on the free list). Loop through the pages that lie beyond
2374 ** this mark, and if they are not already on the free list, move them
danielk1977a19df672004-11-03 11:37:07 +00002375 ** to a free page earlier in the file (somewhere before finSize).
danielk1977687566d2004-11-02 12:56:41 +00002376 */
danielk1977a19df672004-11-03 11:37:07 +00002377 for( iDbPage=finSize+1; iDbPage<=origSize; iDbPage++ ){
danielk1977599fcba2004-11-08 07:13:13 +00002378 /* If iDbPage is a pointer map page, or the pending-byte page, skip it. */
2379 if( PTRMAP_ISPAGE(pgsz, iDbPage) || iDbPage==PENDING_BYTE_PAGE(pBt) ){
2380 continue;
2381 }
2382
danielk1977687566d2004-11-02 12:56:41 +00002383 rc = ptrmapGet(pBt, iDbPage, &eType, &iPtrPage);
2384 if( rc!=SQLITE_OK ) goto autovacuum_out;
drhccae6022005-02-26 17:31:26 +00002385 if( eType==PTRMAP_ROOTPAGE ){
drh49285702005-09-17 15:20:26 +00002386 rc = SQLITE_CORRUPT_BKPT;
drhccae6022005-02-26 17:31:26 +00002387 goto autovacuum_out;
2388 }
danielk1977687566d2004-11-02 12:56:41 +00002389
danielk1977599fcba2004-11-08 07:13:13 +00002390 /* If iDbPage is free, do not swap it. */
2391 if( eType==PTRMAP_FREEPAGE ){
danielk1977687566d2004-11-02 12:56:41 +00002392 continue;
2393 }
2394 rc = getPage(pBt, iDbPage, &pDbMemPage);
2395 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977687566d2004-11-02 12:56:41 +00002396
2397 /* Find the next page in the free-list that is not already at the end
2398 ** of the file. A page can be pulled off the free list using the
2399 ** allocatePage() routine.
2400 */
2401 do{
2402 if( pFreeMemPage ){
2403 releasePage(pFreeMemPage);
2404 pFreeMemPage = 0;
2405 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00002406 rc = allocatePage(pBt, &pFreeMemPage, &iFreePage, 0, 0);
danielk1977ac11ee62005-01-15 12:45:51 +00002407 if( rc!=SQLITE_OK ){
2408 releasePage(pDbMemPage);
2409 goto autovacuum_out;
2410 }
danielk1977a19df672004-11-03 11:37:07 +00002411 assert( iFreePage<=origSize );
2412 }while( iFreePage>finSize );
danielk1977687566d2004-11-02 12:56:41 +00002413 releasePage(pFreeMemPage);
2414 pFreeMemPage = 0;
danielk1977687566d2004-11-02 12:56:41 +00002415
danielk1977e501b892006-01-09 06:29:47 +00002416 /* Relocate the page into the body of the file. Note that although the
2417 ** page has moved within the database file, the pDbMemPage pointer
2418 ** remains valid. This means that this function can run without
2419 ** invalidating cursors open on the btree. This is important in
2420 ** shared-cache mode.
2421 */
danielk1977003ba062004-11-04 02:57:33 +00002422 rc = relocatePage(pBt, pDbMemPage, eType, iPtrPage, iFreePage);
danielk1977687566d2004-11-02 12:56:41 +00002423 releasePage(pDbMemPage);
danielk1977687566d2004-11-02 12:56:41 +00002424 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977687566d2004-11-02 12:56:41 +00002425 }
2426
2427 /* The entire free-list has been swapped to the end of the file. So
danielk1977a19df672004-11-03 11:37:07 +00002428 ** truncate the database file to finSize pages and consider the
danielk1977687566d2004-11-02 12:56:41 +00002429 ** free-list empty.
2430 */
2431 rc = sqlite3pager_write(pBt->pPage1->aData);
2432 if( rc!=SQLITE_OK ) goto autovacuum_out;
2433 put4byte(&pBt->pPage1->aData[32], 0);
2434 put4byte(&pBt->pPage1->aData[36], 0);
danielk1977687566d2004-11-02 12:56:41 +00002435 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977d761c0c2004-11-05 16:37:02 +00002436 *nTrunc = finSize;
danielk1977687566d2004-11-02 12:56:41 +00002437
2438autovacuum_out:
danielk1977687566d2004-11-02 12:56:41 +00002439 assert( nRef==*sqlite3pager_stats(pPager) );
2440 if( rc!=SQLITE_OK ){
2441 sqlite3pager_rollback(pPager);
2442 }
2443 return rc;
2444}
2445#endif
2446
2447/*
drh2aa679f2001-06-25 02:11:07 +00002448** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00002449**
2450** This will release the write lock on the database file. If there
2451** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002452*/
danielk1977aef0bf62005-12-30 16:28:01 +00002453int sqlite3BtreeCommit(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002454 BtShared *pBt = p->pBt;
2455
2456 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002457
2458 /* If the handle has a write-transaction open, commit the shared-btrees
2459 ** transaction and set the shared state to TRANS_READ.
2460 */
2461 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00002462 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002463 assert( pBt->inTransaction==TRANS_WRITE );
2464 assert( pBt->nTransaction>0 );
danielk1977ee5741e2004-05-31 10:01:34 +00002465 rc = sqlite3pager_commit(pBt->pPager);
danielk19777f7bc662006-01-23 13:47:47 +00002466 if( rc!=SQLITE_OK ){
2467 return rc;
2468 }
danielk1977aef0bf62005-12-30 16:28:01 +00002469 pBt->inTransaction = TRANS_READ;
2470 pBt->inStmt = 0;
danielk1977ee5741e2004-05-31 10:01:34 +00002471 }
danielk19777f7bc662006-01-23 13:47:47 +00002472 unlockAllTables(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002473
2474 /* If the handle has any kind of transaction open, decrement the transaction
2475 ** count of the shared btree. If the transaction count reaches 0, set
2476 ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
2477 ** will unlock the pager.
2478 */
2479 if( p->inTrans!=TRANS_NONE ){
2480 pBt->nTransaction--;
2481 if( 0==pBt->nTransaction ){
2482 pBt->inTransaction = TRANS_NONE;
2483 }
2484 }
2485
2486 /* Set the handles current transaction state to TRANS_NONE and unlock
2487 ** the pager if this call closed the only read or write transaction.
2488 */
2489 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002490 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002491
2492 btreeIntegrity(p);
danielk19777f7bc662006-01-23 13:47:47 +00002493 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002494}
2495
danielk1977fbcd5852004-06-15 02:44:18 +00002496#ifndef NDEBUG
2497/*
2498** Return the number of write-cursors open on this handle. This is for use
2499** in assert() expressions, so it is only compiled if NDEBUG is not
2500** defined.
2501*/
danielk1977aef0bf62005-12-30 16:28:01 +00002502static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00002503 BtCursor *pCur;
2504 int r = 0;
2505 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
danielk1977aef0bf62005-12-30 16:28:01 +00002506 if( pCur->wrFlag ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00002507 }
2508 return r;
2509}
2510#endif
2511
danielk197707cb5602006-01-20 10:55:05 +00002512#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drhda200cc2004-05-09 11:51:38 +00002513/*
2514** Print debugging information about all cursors to standard output.
2515*/
danielk1977aef0bf62005-12-30 16:28:01 +00002516void sqlite3BtreeCursorList(Btree *p){
drhda200cc2004-05-09 11:51:38 +00002517 BtCursor *pCur;
danielk1977aef0bf62005-12-30 16:28:01 +00002518 BtShared *pBt = p->pBt;
drhda200cc2004-05-09 11:51:38 +00002519 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
2520 MemPage *pPage = pCur->pPage;
2521 char *zMode = pCur->wrFlag ? "rw" : "ro";
drhfe63d1c2004-09-08 20:13:04 +00002522 sqlite3DebugPrintf("CURSOR %p rooted at %4d(%s) currently at %d.%d%s\n",
2523 pCur, pCur->pgnoRoot, zMode,
drhda200cc2004-05-09 11:51:38 +00002524 pPage ? pPage->pgno : 0, pCur->idx,
danielk1977da184232006-01-05 11:34:32 +00002525 (pCur->eState==CURSOR_VALID) ? "" : " eof"
drhda200cc2004-05-09 11:51:38 +00002526 );
2527 }
2528}
2529#endif
2530
drhc39e0002004-05-07 23:50:57 +00002531/*
drhecdc7532001-09-23 02:35:53 +00002532** Rollback the transaction in progress. All cursors will be
2533** invalided by this operation. Any attempt to use a cursor
2534** that was open at the beginning of this operation will result
2535** in an error.
drh5e00f6c2001-09-13 13:46:56 +00002536**
2537** This will release the write lock on the database file. If there
2538** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002539*/
danielk1977aef0bf62005-12-30 16:28:01 +00002540int sqlite3BtreeRollback(Btree *p){
danielk1977cfe9a692004-06-16 12:00:29 +00002541 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002542 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00002543 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00002544
danielk19772b8c13e2006-01-24 14:21:24 +00002545 rc = saveAllCursors(pBt, 0, 0);
2546 if( rc!=SQLITE_OK ){
2547 return rc;
2548 }
danielk1977aef0bf62005-12-30 16:28:01 +00002549 btreeIntegrity(p);
2550 unlockAllTables(p);
2551
2552 if( p->inTrans==TRANS_WRITE ){
2553 assert( TRANS_WRITE==pBt->inTransaction );
2554
drh24cd67e2004-05-10 16:18:47 +00002555 rc = sqlite3pager_rollback(pBt->pPager);
2556 /* The rollback may have destroyed the pPage1->aData value. So
2557 ** call getPage() on page 1 again to make sure pPage1->aData is
2558 ** set correctly. */
2559 if( getPage(pBt, 1, &pPage1)==SQLITE_OK ){
2560 releasePage(pPage1);
2561 }
danielk1977fbcd5852004-06-15 02:44:18 +00002562 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002563 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00002564 }
danielk1977aef0bf62005-12-30 16:28:01 +00002565
2566 if( p->inTrans!=TRANS_NONE ){
2567 assert( pBt->nTransaction>0 );
2568 pBt->nTransaction--;
2569 if( 0==pBt->nTransaction ){
2570 pBt->inTransaction = TRANS_NONE;
2571 }
2572 }
2573
2574 p->inTrans = TRANS_NONE;
danielk1977ee5741e2004-05-31 10:01:34 +00002575 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00002576 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002577
2578 btreeIntegrity(p);
drha059ad02001-04-17 20:09:11 +00002579 return rc;
2580}
2581
2582/*
drhab01f612004-05-22 02:55:23 +00002583** Start a statement subtransaction. The subtransaction can
2584** can be rolled back independently of the main transaction.
2585** You must start a transaction before starting a subtransaction.
2586** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00002587** commits or rolls back.
2588**
drhab01f612004-05-22 02:55:23 +00002589** Only one subtransaction may be active at a time. It is an error to try
2590** to start a new subtransaction if another subtransaction is already active.
2591**
2592** Statement subtransactions are used around individual SQL statements
2593** that are contained within a BEGIN...COMMIT block. If a constraint
2594** error occurs within the statement, the effect of that one statement
2595** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00002596*/
danielk1977aef0bf62005-12-30 16:28:01 +00002597int sqlite3BtreeBeginStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002598 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002599 BtShared *pBt = p->pBt;
2600 if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
drhf74b8d92002-09-01 23:20:45 +00002601 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh0d65dc02002-02-03 00:56:09 +00002602 }
danielk1977aef0bf62005-12-30 16:28:01 +00002603 assert( pBt->inTransaction==TRANS_WRITE );
drha34b6762004-05-07 13:30:42 +00002604 rc = pBt->readOnly ? SQLITE_OK : sqlite3pager_stmt_begin(pBt->pPager);
drh3aac2dd2004-04-26 14:10:20 +00002605 pBt->inStmt = 1;
drh663fc632002-02-02 18:49:19 +00002606 return rc;
2607}
2608
2609
2610/*
drhab01f612004-05-22 02:55:23 +00002611** Commit the statment subtransaction currently in progress. If no
2612** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00002613*/
danielk1977aef0bf62005-12-30 16:28:01 +00002614int sqlite3BtreeCommitStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002615 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002616 BtShared *pBt = p->pBt;
drh3aac2dd2004-04-26 14:10:20 +00002617 if( pBt->inStmt && !pBt->readOnly ){
drha34b6762004-05-07 13:30:42 +00002618 rc = sqlite3pager_stmt_commit(pBt->pPager);
drh663fc632002-02-02 18:49:19 +00002619 }else{
2620 rc = SQLITE_OK;
2621 }
drh3aac2dd2004-04-26 14:10:20 +00002622 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00002623 return rc;
2624}
2625
2626/*
drhab01f612004-05-22 02:55:23 +00002627** Rollback the active statement subtransaction. If no subtransaction
2628** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00002629**
drhab01f612004-05-22 02:55:23 +00002630** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00002631** to use a cursor that was open at the beginning of this operation
2632** will result in an error.
2633*/
danielk1977aef0bf62005-12-30 16:28:01 +00002634int sqlite3BtreeRollbackStmt(Btree *p){
danielk197797a227c2006-01-20 16:32:04 +00002635 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002636 BtShared *pBt = p->pBt;
danielk197797a227c2006-01-20 16:32:04 +00002637 sqlite3MallocDisallow();
2638 if( pBt->inStmt && !pBt->readOnly ){
2639 rc = sqlite3pager_stmt_rollback(pBt->pPager);
2640 assert( countWriteCursors(pBt)==0 );
2641 pBt->inStmt = 0;
2642 }
2643 sqlite3MallocAllow();
drh663fc632002-02-02 18:49:19 +00002644 return rc;
2645}
2646
2647/*
drh3aac2dd2004-04-26 14:10:20 +00002648** Default key comparison function to be used if no comparison function
2649** is specified on the sqlite3BtreeCursor() call.
2650*/
2651static int dfltCompare(
2652 void *NotUsed, /* User data is not used */
2653 int n1, const void *p1, /* First key to compare */
2654 int n2, const void *p2 /* Second key to compare */
2655){
2656 int c;
2657 c = memcmp(p1, p2, n1<n2 ? n1 : n2);
2658 if( c==0 ){
2659 c = n1 - n2;
2660 }
2661 return c;
2662}
2663
2664/*
drh8b2f49b2001-06-08 00:21:52 +00002665** Create a new cursor for the BTree whose root is on the page
2666** iTable. The act of acquiring a cursor gets a read lock on
2667** the database file.
drh1bee3d72001-10-15 00:44:35 +00002668**
2669** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00002670** If wrFlag==1, then the cursor can be used for reading or for
2671** writing if other conditions for writing are also met. These
2672** are the conditions that must be met in order for writing to
2673** be allowed:
drh6446c4d2001-12-15 14:22:18 +00002674**
drhf74b8d92002-09-01 23:20:45 +00002675** 1: The cursor must have been opened with wrFlag==1
2676**
2677** 2: No other cursors may be open with wrFlag==0 on the same table
2678**
2679** 3: The database must be writable (not on read-only media)
2680**
2681** 4: There must be an active transaction.
2682**
2683** Condition 2 warrants further discussion. If any cursor is opened
2684** on a table with wrFlag==0, that prevents all other cursors from
2685** writing to that table. This is a kind of "read-lock". When a cursor
2686** is opened with wrFlag==0 it is guaranteed that the table will not
2687** change as long as the cursor is open. This allows the cursor to
2688** do a sequential scan of the table without having to worry about
2689** entries being inserted or deleted during the scan. Cursors should
2690** be opened with wrFlag==0 only if this read-lock property is needed.
2691** That is to say, cursors should be opened with wrFlag==0 only if they
drh23e11ca2004-05-04 17:27:28 +00002692** intend to use the sqlite3BtreeNext() system call. All other cursors
drhf74b8d92002-09-01 23:20:45 +00002693** should be opened with wrFlag==1 even if they never really intend
2694** to write.
2695**
drh6446c4d2001-12-15 14:22:18 +00002696** No checking is done to make sure that page iTable really is the
2697** root page of a b-tree. If it is not, then the cursor acquired
2698** will not work correctly.
drh3aac2dd2004-04-26 14:10:20 +00002699**
2700** The comparison function must be logically the same for every cursor
2701** on a particular table. Changing the comparison function will result
2702** in incorrect operations. If the comparison function is NULL, a
2703** default comparison function is used. The comparison function is
2704** always ignored for INTKEY tables.
drha059ad02001-04-17 20:09:11 +00002705*/
drh3aac2dd2004-04-26 14:10:20 +00002706int sqlite3BtreeCursor(
danielk1977aef0bf62005-12-30 16:28:01 +00002707 Btree *p, /* The btree */
drh3aac2dd2004-04-26 14:10:20 +00002708 int iTable, /* Root page of table to open */
2709 int wrFlag, /* 1 to write. 0 read-only */
2710 int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
2711 void *pArg, /* First arg to xCompare() */
2712 BtCursor **ppCur /* Write new cursor here */
2713){
drha059ad02001-04-17 20:09:11 +00002714 int rc;
drh8dcd7ca2004-08-08 19:43:29 +00002715 BtCursor *pCur;
danielk1977aef0bf62005-12-30 16:28:01 +00002716 BtShared *pBt = p->pBt;
drhecdc7532001-09-23 02:35:53 +00002717
drh8dcd7ca2004-08-08 19:43:29 +00002718 *ppCur = 0;
2719 if( wrFlag ){
drh8dcd7ca2004-08-08 19:43:29 +00002720 if( pBt->readOnly ){
2721 return SQLITE_READONLY;
2722 }
2723 if( checkReadLocks(pBt, iTable, 0) ){
2724 return SQLITE_LOCKED;
2725 }
drha0c9a112004-03-10 13:42:37 +00002726 }
danielk1977aef0bf62005-12-30 16:28:01 +00002727
drh4b70f112004-05-02 21:12:19 +00002728 if( pBt->pPage1==0 ){
danielk1977aef0bf62005-12-30 16:28:01 +00002729 rc = lockBtreeWithRetry(p);
drha059ad02001-04-17 20:09:11 +00002730 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002731 return rc;
2732 }
2733 }
danielk1977da184232006-01-05 11:34:32 +00002734 pCur = sqliteMalloc( sizeof(*pCur) );
drha059ad02001-04-17 20:09:11 +00002735 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +00002736 rc = SQLITE_NOMEM;
2737 goto create_cursor_exception;
2738 }
drh8b2f49b2001-06-08 00:21:52 +00002739 pCur->pgnoRoot = (Pgno)iTable;
drh24cd67e2004-05-10 16:18:47 +00002740 if( iTable==1 && sqlite3pager_pagecount(pBt->pPager)==0 ){
2741 rc = SQLITE_EMPTY;
2742 goto create_cursor_exception;
2743 }
drhde647132004-05-07 17:57:49 +00002744 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
drhbd03cae2001-06-02 02:40:57 +00002745 if( rc!=SQLITE_OK ){
2746 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002747 }
danielk1977aef0bf62005-12-30 16:28:01 +00002748
danielk1977aef0bf62005-12-30 16:28:01 +00002749 /* Now that no other errors can occur, finish filling in the BtCursor
2750 ** variables, link the cursor into the BtShared list and set *ppCur (the
2751 ** output argument to this function).
2752 */
drh3aac2dd2004-04-26 14:10:20 +00002753 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2754 pCur->pArg = pArg;
danielk1977aef0bf62005-12-30 16:28:01 +00002755 pCur->pBtree = p;
drhecdc7532001-09-23 02:35:53 +00002756 pCur->wrFlag = wrFlag;
drha059ad02001-04-17 20:09:11 +00002757 pCur->pNext = pBt->pCursor;
2758 if( pCur->pNext ){
2759 pCur->pNext->pPrev = pCur;
2760 }
2761 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00002762 pCur->eState = CURSOR_INVALID;
drh2af926b2001-05-15 00:39:25 +00002763 *ppCur = pCur;
drhbd03cae2001-06-02 02:40:57 +00002764
danielk1977aef0bf62005-12-30 16:28:01 +00002765 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00002766create_cursor_exception:
drhbd03cae2001-06-02 02:40:57 +00002767 if( pCur ){
drh3aac2dd2004-04-26 14:10:20 +00002768 releasePage(pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +00002769 sqliteFree(pCur);
2770 }
drh5e00f6c2001-09-13 13:46:56 +00002771 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00002772 return rc;
drha059ad02001-04-17 20:09:11 +00002773}
2774
drh7a224de2004-06-02 01:22:02 +00002775#if 0 /* Not Used */
drhd3d39e92004-05-20 22:16:29 +00002776/*
2777** Change the value of the comparison function used by a cursor.
2778*/
danielk1977bf3b7212004-05-18 10:06:24 +00002779void sqlite3BtreeSetCompare(
drhd3d39e92004-05-20 22:16:29 +00002780 BtCursor *pCur, /* The cursor to whose comparison function is changed */
2781 int(*xCmp)(void*,int,const void*,int,const void*), /* New comparison func */
2782 void *pArg /* First argument to xCmp() */
danielk1977bf3b7212004-05-18 10:06:24 +00002783){
2784 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2785 pCur->pArg = pArg;
2786}
drh7a224de2004-06-02 01:22:02 +00002787#endif
danielk1977bf3b7212004-05-18 10:06:24 +00002788
drha059ad02001-04-17 20:09:11 +00002789/*
drh5e00f6c2001-09-13 13:46:56 +00002790** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00002791** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00002792*/
drh3aac2dd2004-04-26 14:10:20 +00002793int sqlite3BtreeCloseCursor(BtCursor *pCur){
danielk1977aef0bf62005-12-30 16:28:01 +00002794 BtShared *pBt = pCur->pBtree->pBt;
drh777e4c42006-01-13 04:31:58 +00002795 restoreOrClearCursorPosition(pCur, 0);
drha059ad02001-04-17 20:09:11 +00002796 if( pCur->pPrev ){
2797 pCur->pPrev->pNext = pCur->pNext;
2798 }else{
2799 pBt->pCursor = pCur->pNext;
2800 }
2801 if( pCur->pNext ){
2802 pCur->pNext->pPrev = pCur->pPrev;
2803 }
drh3aac2dd2004-04-26 14:10:20 +00002804 releasePage(pCur->pPage);
drh5e00f6c2001-09-13 13:46:56 +00002805 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00002806 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +00002807 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002808}
2809
drh7e3b0a02001-04-28 16:52:40 +00002810/*
drh5e2f8b92001-05-28 00:41:15 +00002811** Make a temporary cursor by filling in the fields of pTempCur.
2812** The temporary cursor is not on the cursor list for the Btree.
2813*/
drh14acc042001-06-10 19:56:58 +00002814static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00002815 memcpy(pTempCur, pCur, sizeof(*pCur));
2816 pTempCur->pNext = 0;
2817 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00002818 if( pTempCur->pPage ){
drha34b6762004-05-07 13:30:42 +00002819 sqlite3pager_ref(pTempCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00002820 }
drh5e2f8b92001-05-28 00:41:15 +00002821}
2822
2823/*
drhbd03cae2001-06-02 02:40:57 +00002824** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00002825** function above.
2826*/
drh14acc042001-06-10 19:56:58 +00002827static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00002828 if( pCur->pPage ){
drha34b6762004-05-07 13:30:42 +00002829 sqlite3pager_unref(pCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00002830 }
drh5e2f8b92001-05-28 00:41:15 +00002831}
2832
2833/*
drh9188b382004-05-14 21:12:22 +00002834** Make sure the BtCursor.info field of the given cursor is valid.
drhab01f612004-05-22 02:55:23 +00002835** If it is not already valid, call parseCell() to fill it in.
2836**
2837** BtCursor.info is a cache of the information in the current cell.
2838** Using this cache reduces the number of calls to parseCell().
drh9188b382004-05-14 21:12:22 +00002839*/
2840static void getCellInfo(BtCursor *pCur){
drh271efa52004-05-30 19:19:05 +00002841 if( pCur->info.nSize==0 ){
drh3a41a3f2004-05-30 02:14:17 +00002842 parseCell(pCur->pPage, pCur->idx, &pCur->info);
drh9188b382004-05-14 21:12:22 +00002843 }else{
2844#ifndef NDEBUG
2845 CellInfo info;
drh51c6d962004-06-06 00:42:25 +00002846 memset(&info, 0, sizeof(info));
drh3a41a3f2004-05-30 02:14:17 +00002847 parseCell(pCur->pPage, pCur->idx, &info);
drh9188b382004-05-14 21:12:22 +00002848 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
2849#endif
2850 }
2851}
2852
2853/*
drh3aac2dd2004-04-26 14:10:20 +00002854** Set *pSize to the size of the buffer needed to hold the value of
2855** the key for the current entry. If the cursor is not pointing
2856** to a valid entry, *pSize is set to 0.
2857**
drh4b70f112004-05-02 21:12:19 +00002858** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00002859** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00002860*/
drh4a1c3802004-05-12 15:15:47 +00002861int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drh777e4c42006-01-13 04:31:58 +00002862 int rc = restoreOrClearCursorPosition(pCur, 1);
danielk1977da184232006-01-05 11:34:32 +00002863 if( rc==SQLITE_OK ){
2864 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
2865 if( pCur->eState==CURSOR_INVALID ){
2866 *pSize = 0;
2867 }else{
2868 getCellInfo(pCur);
2869 *pSize = pCur->info.nKey;
2870 }
drh72f82862001-05-24 21:06:34 +00002871 }
danielk1977da184232006-01-05 11:34:32 +00002872 return rc;
drha059ad02001-04-17 20:09:11 +00002873}
drh2af926b2001-05-15 00:39:25 +00002874
drh72f82862001-05-24 21:06:34 +00002875/*
drh0e1c19e2004-05-11 00:58:56 +00002876** Set *pSize to the number of bytes of data in the entry the
2877** cursor currently points to. Always return SQLITE_OK.
2878** Failure is not possible. If the cursor is not currently
2879** pointing to an entry (which can happen, for example, if
2880** the database is empty) then *pSize is set to 0.
2881*/
2882int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drh777e4c42006-01-13 04:31:58 +00002883 int rc = restoreOrClearCursorPosition(pCur, 1);
danielk1977da184232006-01-05 11:34:32 +00002884 if( rc==SQLITE_OK ){
2885 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
2886 if( pCur->eState==CURSOR_INVALID ){
2887 /* Not pointing at a valid entry - set *pSize to 0. */
2888 *pSize = 0;
2889 }else{
2890 getCellInfo(pCur);
2891 *pSize = pCur->info.nData;
2892 }
drh0e1c19e2004-05-11 00:58:56 +00002893 }
danielk1977da184232006-01-05 11:34:32 +00002894 return rc;
drh0e1c19e2004-05-11 00:58:56 +00002895}
2896
2897/*
drh72f82862001-05-24 21:06:34 +00002898** Read payload information from the entry that the pCur cursor is
2899** pointing to. Begin reading the payload at "offset" and read
2900** a total of "amt" bytes. Put the result in zBuf.
2901**
2902** This routine does not make a distinction between key and data.
drhab01f612004-05-22 02:55:23 +00002903** It just reads bytes from the payload area. Data might appear
2904** on the main page or be scattered out on multiple overflow pages.
drh72f82862001-05-24 21:06:34 +00002905*/
drh3aac2dd2004-04-26 14:10:20 +00002906static int getPayload(
2907 BtCursor *pCur, /* Cursor pointing to entry to read from */
2908 int offset, /* Begin reading this far into payload */
2909 int amt, /* Read this many bytes */
2910 unsigned char *pBuf, /* Write the bytes into this buffer */
2911 int skipKey /* offset begins at data if this is true */
2912){
2913 unsigned char *aPayload;
drh2af926b2001-05-15 00:39:25 +00002914 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +00002915 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002916 MemPage *pPage;
danielk1977aef0bf62005-12-30 16:28:01 +00002917 BtShared *pBt;
drh6f11bef2004-05-13 01:12:56 +00002918 int ovflSize;
drhfa1a98a2004-05-14 19:08:17 +00002919 u32 nKey;
drh3aac2dd2004-04-26 14:10:20 +00002920
drh72f82862001-05-24 21:06:34 +00002921 assert( pCur!=0 && pCur->pPage!=0 );
danielk1977da184232006-01-05 11:34:32 +00002922 assert( pCur->eState==CURSOR_VALID );
danielk1977aef0bf62005-12-30 16:28:01 +00002923 pBt = pCur->pBtree->pBt;
drh3aac2dd2004-04-26 14:10:20 +00002924 pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00002925 pageIntegrity(pPage);
drh3aac2dd2004-04-26 14:10:20 +00002926 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00002927 getCellInfo(pCur);
drh366fda62006-01-13 02:35:09 +00002928 aPayload = pCur->info.pCell + pCur->info.nHeader;
drh3aac2dd2004-04-26 14:10:20 +00002929 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00002930 nKey = 0;
2931 }else{
2932 nKey = pCur->info.nKey;
drh3aac2dd2004-04-26 14:10:20 +00002933 }
2934 assert( offset>=0 );
2935 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00002936 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00002937 }
drhfa1a98a2004-05-14 19:08:17 +00002938 if( offset+amt > nKey+pCur->info.nData ){
drha34b6762004-05-07 13:30:42 +00002939 return SQLITE_ERROR;
drh3aac2dd2004-04-26 14:10:20 +00002940 }
drhfa1a98a2004-05-14 19:08:17 +00002941 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00002942 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00002943 if( a+offset>pCur->info.nLocal ){
2944 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00002945 }
drha34b6762004-05-07 13:30:42 +00002946 memcpy(pBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +00002947 if( a==amt ){
2948 return SQLITE_OK;
2949 }
drh2aa679f2001-06-25 02:11:07 +00002950 offset = 0;
drha34b6762004-05-07 13:30:42 +00002951 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00002952 amt -= a;
drhdd793422001-06-28 01:54:48 +00002953 }else{
drhfa1a98a2004-05-14 19:08:17 +00002954 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00002955 }
danielk1977cfe9a692004-06-16 12:00:29 +00002956 ovflSize = pBt->usableSize - 4;
drhbd03cae2001-06-02 02:40:57 +00002957 if( amt>0 ){
drhfa1a98a2004-05-14 19:08:17 +00002958 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977cfe9a692004-06-16 12:00:29 +00002959 while( amt>0 && nextPage ){
2960 rc = sqlite3pager_get(pBt->pPager, nextPage, (void**)&aPayload);
2961 if( rc!=0 ){
2962 return rc;
drh2af926b2001-05-15 00:39:25 +00002963 }
danielk1977cfe9a692004-06-16 12:00:29 +00002964 nextPage = get4byte(aPayload);
2965 if( offset<ovflSize ){
2966 int a = amt;
2967 if( a + offset > ovflSize ){
2968 a = ovflSize - offset;
2969 }
2970 memcpy(pBuf, &aPayload[offset+4], a);
2971 offset = 0;
2972 amt -= a;
2973 pBuf += a;
2974 }else{
2975 offset -= ovflSize;
2976 }
2977 sqlite3pager_unref(aPayload);
drh2af926b2001-05-15 00:39:25 +00002978 }
drh2af926b2001-05-15 00:39:25 +00002979 }
danielk1977cfe9a692004-06-16 12:00:29 +00002980
drha7fcb052001-12-14 15:09:55 +00002981 if( amt>0 ){
drh49285702005-09-17 15:20:26 +00002982 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00002983 }
2984 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00002985}
2986
drh72f82862001-05-24 21:06:34 +00002987/*
drh3aac2dd2004-04-26 14:10:20 +00002988** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002989** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002990** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00002991**
drh3aac2dd2004-04-26 14:10:20 +00002992** Return SQLITE_OK on success or an error code if anything goes
2993** wrong. An error is returned if "offset+amt" is larger than
2994** the available payload.
drh72f82862001-05-24 21:06:34 +00002995*/
drha34b6762004-05-07 13:30:42 +00002996int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drh777e4c42006-01-13 04:31:58 +00002997 int rc = restoreOrClearCursorPosition(pCur, 1);
danielk1977da184232006-01-05 11:34:32 +00002998 if( rc==SQLITE_OK ){
2999 assert( pCur->eState==CURSOR_VALID );
3000 assert( pCur->pPage!=0 );
3001 if( pCur->pPage->intKey ){
3002 return SQLITE_CORRUPT_BKPT;
3003 }
3004 assert( pCur->pPage->intKey==0 );
3005 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
3006 rc = getPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
drh6575a222005-03-10 17:06:34 +00003007 }
danielk1977da184232006-01-05 11:34:32 +00003008 return rc;
drh3aac2dd2004-04-26 14:10:20 +00003009}
3010
3011/*
drh3aac2dd2004-04-26 14:10:20 +00003012** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003013** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003014** begins at "offset".
3015**
3016** Return SQLITE_OK on success or an error code if anything goes
3017** wrong. An error is returned if "offset+amt" is larger than
3018** the available payload.
drh72f82862001-05-24 21:06:34 +00003019*/
drh3aac2dd2004-04-26 14:10:20 +00003020int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drh777e4c42006-01-13 04:31:58 +00003021 int rc = restoreOrClearCursorPosition(pCur, 1);
danielk1977da184232006-01-05 11:34:32 +00003022 if( rc==SQLITE_OK ){
3023 assert( pCur->eState==CURSOR_VALID );
3024 assert( pCur->pPage!=0 );
3025 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
3026 rc = getPayload(pCur, offset, amt, pBuf, 1);
3027 }
3028 return rc;
drh2af926b2001-05-15 00:39:25 +00003029}
3030
drh72f82862001-05-24 21:06:34 +00003031/*
drh0e1c19e2004-05-11 00:58:56 +00003032** Return a pointer to payload information from the entry that the
3033** pCur cursor is pointing to. The pointer is to the beginning of
3034** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00003035** skipKey==1. The number of bytes of available key/data is written
3036** into *pAmt. If *pAmt==0, then the value returned will not be
3037** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00003038**
3039** This routine is an optimization. It is common for the entire key
3040** and data to fit on the local page and for there to be no overflow
3041** pages. When that is so, this routine can be used to access the
3042** key and data without making a copy. If the key and/or data spills
3043** onto overflow pages, then getPayload() must be used to reassembly
3044** the key/data and copy it into a preallocated buffer.
3045**
3046** The pointer returned by this routine looks directly into the cached
3047** page of the database. The data might change or move the next time
3048** any btree routine is called.
3049*/
3050static const unsigned char *fetchPayload(
3051 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00003052 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00003053 int skipKey /* read beginning at data if this is true */
3054){
3055 unsigned char *aPayload;
3056 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00003057 u32 nKey;
3058 int nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003059
3060 assert( pCur!=0 && pCur->pPage!=0 );
danielk1977da184232006-01-05 11:34:32 +00003061 assert( pCur->eState==CURSOR_VALID );
drh0e1c19e2004-05-11 00:58:56 +00003062 pPage = pCur->pPage;
3063 pageIntegrity(pPage);
3064 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00003065 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00003066 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00003067 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00003068 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00003069 nKey = 0;
3070 }else{
3071 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00003072 }
drh0e1c19e2004-05-11 00:58:56 +00003073 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003074 aPayload += nKey;
3075 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00003076 }else{
drhfa1a98a2004-05-14 19:08:17 +00003077 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00003078 if( nLocal>nKey ){
3079 nLocal = nKey;
3080 }
drh0e1c19e2004-05-11 00:58:56 +00003081 }
drhe51c44f2004-05-30 20:46:09 +00003082 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003083 return aPayload;
3084}
3085
3086
3087/*
drhe51c44f2004-05-30 20:46:09 +00003088** For the entry that cursor pCur is point to, return as
3089** many bytes of the key or data as are available on the local
3090** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00003091**
3092** The pointer returned is ephemeral. The key/data may move
3093** or be destroyed on the next call to any Btree routine.
3094**
3095** These routines is used to get quick access to key and data
3096** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00003097*/
drhe51c44f2004-05-30 20:46:09 +00003098const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
danielk1977da184232006-01-05 11:34:32 +00003099 if( pCur->eState==CURSOR_VALID ){
3100 return (const void*)fetchPayload(pCur, pAmt, 0);
3101 }
3102 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003103}
drhe51c44f2004-05-30 20:46:09 +00003104const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
danielk1977da184232006-01-05 11:34:32 +00003105 if( pCur->eState==CURSOR_VALID ){
3106 return (const void*)fetchPayload(pCur, pAmt, 1);
3107 }
3108 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003109}
3110
3111
3112/*
drh8178a752003-01-05 21:41:40 +00003113** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00003114** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00003115*/
drh3aac2dd2004-04-26 14:10:20 +00003116static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00003117 int rc;
3118 MemPage *pNewPage;
drh3aac2dd2004-04-26 14:10:20 +00003119 MemPage *pOldPage;
danielk1977aef0bf62005-12-30 16:28:01 +00003120 BtShared *pBt = pCur->pBtree->pBt;
drh72f82862001-05-24 21:06:34 +00003121
danielk1977da184232006-01-05 11:34:32 +00003122 assert( pCur->eState==CURSOR_VALID );
drhde647132004-05-07 17:57:49 +00003123 rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00003124 if( rc ) return rc;
drhda200cc2004-05-09 11:51:38 +00003125 pageIntegrity(pNewPage);
drh428ae8c2003-01-04 16:48:09 +00003126 pNewPage->idxParent = pCur->idx;
drh3aac2dd2004-04-26 14:10:20 +00003127 pOldPage = pCur->pPage;
3128 pOldPage->idxShift = 0;
3129 releasePage(pOldPage);
drh72f82862001-05-24 21:06:34 +00003130 pCur->pPage = pNewPage;
3131 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00003132 pCur->info.nSize = 0;
drh4be295b2003-12-16 03:44:47 +00003133 if( pNewPage->nCell<1 ){
drh49285702005-09-17 15:20:26 +00003134 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00003135 }
drh72f82862001-05-24 21:06:34 +00003136 return SQLITE_OK;
3137}
3138
3139/*
drh8856d6a2004-04-29 14:42:46 +00003140** Return true if the page is the virtual root of its table.
3141**
3142** The virtual root page is the root page for most tables. But
3143** for the table rooted on page 1, sometime the real root page
3144** is empty except for the right-pointer. In such cases the
3145** virtual root page is the page that the right-pointer of page
3146** 1 is pointing to.
3147*/
3148static int isRootPage(MemPage *pPage){
3149 MemPage *pParent = pPage->pParent;
drhda200cc2004-05-09 11:51:38 +00003150 if( pParent==0 ) return 1;
3151 if( pParent->pgno>1 ) return 0;
3152 if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
drh8856d6a2004-04-29 14:42:46 +00003153 return 0;
3154}
3155
3156/*
drh5e2f8b92001-05-28 00:41:15 +00003157** Move the cursor up to the parent page.
3158**
3159** pCur->idx is set to the cell index that contains the pointer
3160** to the page we are coming from. If we are coming from the
3161** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00003162** the largest cell index.
drh72f82862001-05-24 21:06:34 +00003163*/
drh8178a752003-01-05 21:41:40 +00003164static void moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00003165 MemPage *pParent;
drh8178a752003-01-05 21:41:40 +00003166 MemPage *pPage;
drh428ae8c2003-01-04 16:48:09 +00003167 int idxParent;
drh3aac2dd2004-04-26 14:10:20 +00003168
danielk1977da184232006-01-05 11:34:32 +00003169 assert( pCur->eState==CURSOR_VALID );
drh8178a752003-01-05 21:41:40 +00003170 pPage = pCur->pPage;
3171 assert( pPage!=0 );
drh8856d6a2004-04-29 14:42:46 +00003172 assert( !isRootPage(pPage) );
drhda200cc2004-05-09 11:51:38 +00003173 pageIntegrity(pPage);
drh8178a752003-01-05 21:41:40 +00003174 pParent = pPage->pParent;
3175 assert( pParent!=0 );
drhda200cc2004-05-09 11:51:38 +00003176 pageIntegrity(pParent);
drh8178a752003-01-05 21:41:40 +00003177 idxParent = pPage->idxParent;
drha34b6762004-05-07 13:30:42 +00003178 sqlite3pager_ref(pParent->aData);
drh3aac2dd2004-04-26 14:10:20 +00003179 releasePage(pPage);
drh72f82862001-05-24 21:06:34 +00003180 pCur->pPage = pParent;
drh271efa52004-05-30 19:19:05 +00003181 pCur->info.nSize = 0;
drh428ae8c2003-01-04 16:48:09 +00003182 assert( pParent->idxShift==0 );
drh43605152004-05-29 21:46:49 +00003183 pCur->idx = idxParent;
drh72f82862001-05-24 21:06:34 +00003184}
3185
3186/*
3187** Move the cursor to the root page
3188*/
drh5e2f8b92001-05-28 00:41:15 +00003189static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00003190 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00003191 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00003192 BtShared *pBt = pCur->pBtree->pBt;
drhbd03cae2001-06-02 02:40:57 +00003193
drh777e4c42006-01-13 04:31:58 +00003194 restoreOrClearCursorPosition(pCur, 0);
drh777e4c42006-01-13 04:31:58 +00003195 pRoot = pCur->pPage;
danielk197797a227c2006-01-20 16:32:04 +00003196 if( pRoot && pRoot->pgno==pCur->pgnoRoot ){
drh777e4c42006-01-13 04:31:58 +00003197 assert( pRoot->isInit );
3198 }else{
3199 if(
3200 SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0))
3201 ){
3202 pCur->eState = CURSOR_INVALID;
3203 return rc;
3204 }
3205 releasePage(pCur->pPage);
3206 pageIntegrity(pRoot);
3207 pCur->pPage = pRoot;
drhc39e0002004-05-07 23:50:57 +00003208 }
drh72f82862001-05-24 21:06:34 +00003209 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00003210 pCur->info.nSize = 0;
drh8856d6a2004-04-29 14:42:46 +00003211 if( pRoot->nCell==0 && !pRoot->leaf ){
3212 Pgno subpage;
3213 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00003214 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00003215 assert( subpage>0 );
danielk1977da184232006-01-05 11:34:32 +00003216 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00003217 rc = moveToChild(pCur, subpage);
drh8856d6a2004-04-29 14:42:46 +00003218 }
danielk1977da184232006-01-05 11:34:32 +00003219 pCur->eState = ((pCur->pPage->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00003220 return rc;
drh72f82862001-05-24 21:06:34 +00003221}
drh2af926b2001-05-15 00:39:25 +00003222
drh5e2f8b92001-05-28 00:41:15 +00003223/*
3224** Move the cursor down to the left-most leaf entry beneath the
3225** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00003226**
3227** The left-most leaf is the one with the smallest key - the first
3228** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00003229*/
3230static int moveToLeftmost(BtCursor *pCur){
3231 Pgno pgno;
3232 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003233 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00003234
danielk1977da184232006-01-05 11:34:32 +00003235 assert( pCur->eState==CURSOR_VALID );
drh3aac2dd2004-04-26 14:10:20 +00003236 while( !(pPage = pCur->pPage)->leaf ){
drha34b6762004-05-07 13:30:42 +00003237 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00003238 pgno = get4byte(findCell(pPage, pCur->idx));
drh8178a752003-01-05 21:41:40 +00003239 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00003240 if( rc ) return rc;
3241 }
3242 return SQLITE_OK;
3243}
3244
drh2dcc9aa2002-12-04 13:40:25 +00003245/*
3246** Move the cursor down to the right-most leaf entry beneath the
3247** page to which it is currently pointing. Notice the difference
3248** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
3249** finds the left-most entry beneath the *entry* whereas moveToRightmost()
3250** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00003251**
3252** The right-most entry is the one with the largest key - the last
3253** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00003254*/
3255static int moveToRightmost(BtCursor *pCur){
3256 Pgno pgno;
3257 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003258 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003259
danielk1977da184232006-01-05 11:34:32 +00003260 assert( pCur->eState==CURSOR_VALID );
drh3aac2dd2004-04-26 14:10:20 +00003261 while( !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00003262 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh3aac2dd2004-04-26 14:10:20 +00003263 pCur->idx = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00003264 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003265 if( rc ) return rc;
3266 }
drh3aac2dd2004-04-26 14:10:20 +00003267 pCur->idx = pPage->nCell - 1;
drh271efa52004-05-30 19:19:05 +00003268 pCur->info.nSize = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003269 return SQLITE_OK;
3270}
3271
drh5e00f6c2001-09-13 13:46:56 +00003272/* Move the cursor to the first entry in the table. Return SQLITE_OK
3273** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003274** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00003275*/
drh3aac2dd2004-04-26 14:10:20 +00003276int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00003277 int rc;
3278 rc = moveToRoot(pCur);
3279 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00003280 if( pCur->eState==CURSOR_INVALID ){
drhc39e0002004-05-07 23:50:57 +00003281 assert( pCur->pPage->nCell==0 );
drh5e00f6c2001-09-13 13:46:56 +00003282 *pRes = 1;
3283 return SQLITE_OK;
3284 }
drhc39e0002004-05-07 23:50:57 +00003285 assert( pCur->pPage->nCell>0 );
drh5e00f6c2001-09-13 13:46:56 +00003286 *pRes = 0;
3287 rc = moveToLeftmost(pCur);
3288 return rc;
3289}
drh5e2f8b92001-05-28 00:41:15 +00003290
drh9562b552002-02-19 15:00:07 +00003291/* Move the cursor to the last entry in the table. Return SQLITE_OK
3292** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003293** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00003294*/
drh3aac2dd2004-04-26 14:10:20 +00003295int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00003296 int rc;
drh9562b552002-02-19 15:00:07 +00003297 rc = moveToRoot(pCur);
3298 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00003299 if( CURSOR_INVALID==pCur->eState ){
drhc39e0002004-05-07 23:50:57 +00003300 assert( pCur->pPage->nCell==0 );
drh9562b552002-02-19 15:00:07 +00003301 *pRes = 1;
3302 return SQLITE_OK;
3303 }
danielk1977da184232006-01-05 11:34:32 +00003304 assert( pCur->eState==CURSOR_VALID );
drh9562b552002-02-19 15:00:07 +00003305 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003306 rc = moveToRightmost(pCur);
drh9562b552002-02-19 15:00:07 +00003307 return rc;
3308}
3309
drh3aac2dd2004-04-26 14:10:20 +00003310/* Move the cursor so that it points to an entry near pKey/nKey.
drh72f82862001-05-24 21:06:34 +00003311** Return a success code.
3312**
drh3aac2dd2004-04-26 14:10:20 +00003313** For INTKEY tables, only the nKey parameter is used. pKey is
3314** ignored. For other tables, nKey is the number of bytes of data
drh0b2f3162005-12-21 18:36:45 +00003315** in pKey. The comparison function specified when the cursor was
drh3aac2dd2004-04-26 14:10:20 +00003316** created is used to compare keys.
3317**
drh5e2f8b92001-05-28 00:41:15 +00003318** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00003319** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00003320** were present. The cursor might point to an entry that comes
3321** before or after the key.
3322**
drhbd03cae2001-06-02 02:40:57 +00003323** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00003324** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00003325** this value is as follows:
3326**
3327** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00003328** is smaller than pKey or if the table is empty
3329** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00003330**
3331** *pRes==0 The cursor is left pointing at an entry that
3332** exactly matches pKey.
3333**
3334** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00003335** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00003336*/
drh4a1c3802004-05-12 15:15:47 +00003337int sqlite3BtreeMoveto(BtCursor *pCur, const void *pKey, i64 nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00003338 int rc;
drh777e4c42006-01-13 04:31:58 +00003339 int tryRightmost;
drh5e2f8b92001-05-28 00:41:15 +00003340 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00003341 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00003342 assert( pCur->pPage );
3343 assert( pCur->pPage->isInit );
drh777e4c42006-01-13 04:31:58 +00003344 tryRightmost = pCur->pPage->intKey;
danielk1977da184232006-01-05 11:34:32 +00003345 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00003346 *pRes = -1;
drhc39e0002004-05-07 23:50:57 +00003347 assert( pCur->pPage->nCell==0 );
3348 return SQLITE_OK;
3349 }
drh4eec4c12005-01-21 00:22:37 +00003350 for(;;){
drh72f82862001-05-24 21:06:34 +00003351 int lwr, upr;
3352 Pgno chldPg;
3353 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00003354 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00003355 lwr = 0;
3356 upr = pPage->nCell-1;
drh4eec4c12005-01-21 00:22:37 +00003357 if( !pPage->intKey && pKey==0 ){
drh49285702005-09-17 15:20:26 +00003358 return SQLITE_CORRUPT_BKPT;
drh4eec4c12005-01-21 00:22:37 +00003359 }
drhda200cc2004-05-09 11:51:38 +00003360 pageIntegrity(pPage);
drh72f82862001-05-24 21:06:34 +00003361 while( lwr<=upr ){
danielk197713adf8a2004-06-03 16:08:41 +00003362 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00003363 i64 nCellKey;
drh72f82862001-05-24 21:06:34 +00003364 pCur->idx = (lwr+upr)/2;
drh366fda62006-01-13 02:35:09 +00003365 pCur->info.nSize = 0;
drh3aac2dd2004-04-26 14:10:20 +00003366 if( pPage->intKey ){
drh777e4c42006-01-13 04:31:58 +00003367 u8 *pCell;
3368 if( tryRightmost ){
3369 pCur->idx = upr;
3370 }
3371 pCell = findCell(pPage, pCur->idx) + pPage->childPtrSize;
drhd172f862006-01-12 15:01:15 +00003372 if( pPage->hasData ){
danielk1977bab45c62006-01-16 15:14:27 +00003373 u32 dummy;
drhd172f862006-01-12 15:01:15 +00003374 pCell += getVarint32(pCell, &dummy);
3375 }
danielk1977bab45c62006-01-16 15:14:27 +00003376 getVarint(pCell, (u64 *)&nCellKey);
drh3aac2dd2004-04-26 14:10:20 +00003377 if( nCellKey<nKey ){
3378 c = -1;
3379 }else if( nCellKey>nKey ){
3380 c = +1;
drh777e4c42006-01-13 04:31:58 +00003381 tryRightmost = 0;
drh3aac2dd2004-04-26 14:10:20 +00003382 }else{
3383 c = 0;
3384 }
drh3aac2dd2004-04-26 14:10:20 +00003385 }else{
drhe51c44f2004-05-30 20:46:09 +00003386 int available;
danielk197713adf8a2004-06-03 16:08:41 +00003387 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drh366fda62006-01-13 02:35:09 +00003388 nCellKey = pCur->info.nKey;
drhe51c44f2004-05-30 20:46:09 +00003389 if( available>=nCellKey ){
3390 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
3391 }else{
3392 pCellKey = sqliteMallocRaw( nCellKey );
3393 if( pCellKey==0 ) return SQLITE_NOMEM;
danielk197713adf8a2004-06-03 16:08:41 +00003394 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
drhe51c44f2004-05-30 20:46:09 +00003395 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
3396 sqliteFree(pCellKey);
3397 if( rc ) return rc;
3398 }
drh3aac2dd2004-04-26 14:10:20 +00003399 }
drh72f82862001-05-24 21:06:34 +00003400 if( c==0 ){
drh8b18dd42004-05-12 19:18:15 +00003401 if( pPage->leafData && !pPage->leaf ){
drhfc70e6f2004-05-12 21:11:27 +00003402 lwr = pCur->idx;
3403 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00003404 break;
3405 }else{
drh8b18dd42004-05-12 19:18:15 +00003406 if( pRes ) *pRes = 0;
3407 return SQLITE_OK;
3408 }
drh72f82862001-05-24 21:06:34 +00003409 }
3410 if( c<0 ){
3411 lwr = pCur->idx+1;
3412 }else{
3413 upr = pCur->idx-1;
3414 }
3415 }
3416 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00003417 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00003418 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00003419 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00003420 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00003421 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00003422 }else{
drh43605152004-05-29 21:46:49 +00003423 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00003424 }
3425 if( chldPg==0 ){
drhc39e0002004-05-07 23:50:57 +00003426 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00003427 if( pRes ) *pRes = c;
3428 return SQLITE_OK;
3429 }
drh428ae8c2003-01-04 16:48:09 +00003430 pCur->idx = lwr;
drh271efa52004-05-30 19:19:05 +00003431 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00003432 rc = moveToChild(pCur, chldPg);
drhc39e0002004-05-07 23:50:57 +00003433 if( rc ){
3434 return rc;
3435 }
drh72f82862001-05-24 21:06:34 +00003436 }
drhbd03cae2001-06-02 02:40:57 +00003437 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00003438}
3439
3440/*
drhc39e0002004-05-07 23:50:57 +00003441** Return TRUE if the cursor is not pointing at an entry of the table.
3442**
3443** TRUE will be returned after a call to sqlite3BtreeNext() moves
3444** past the last entry in the table or sqlite3BtreePrev() moves past
3445** the first entry. TRUE is also returned if the table is empty.
3446*/
3447int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00003448 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
3449 ** have been deleted? This API will need to change to return an error code
3450 ** as well as the boolean result value.
3451 */
3452 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00003453}
3454
3455/*
drhbd03cae2001-06-02 02:40:57 +00003456** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00003457** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00003458** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00003459** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00003460*/
drh3aac2dd2004-04-26 14:10:20 +00003461int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00003462 int rc;
danielk197797a227c2006-01-20 16:32:04 +00003463 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00003464
danielk1977da184232006-01-05 11:34:32 +00003465#ifndef SQLITE_OMIT_SHARED_CACHE
drh777e4c42006-01-13 04:31:58 +00003466 rc = restoreOrClearCursorPosition(pCur, 1);
danielk1977da184232006-01-05 11:34:32 +00003467 if( rc!=SQLITE_OK ){
3468 return rc;
3469 }
3470 if( pCur->skip>0 ){
3471 pCur->skip = 0;
3472 *pRes = 0;
3473 return SQLITE_OK;
3474 }
3475 pCur->skip = 0;
danielk197797a227c2006-01-20 16:32:04 +00003476#endif
danielk1977da184232006-01-05 11:34:32 +00003477
drh8c1238a2003-01-02 14:43:55 +00003478 assert( pRes!=0 );
danielk197797a227c2006-01-20 16:32:04 +00003479 pPage = pCur->pPage;
danielk1977da184232006-01-05 11:34:32 +00003480 if( CURSOR_INVALID==pCur->eState ){
drh8c1238a2003-01-02 14:43:55 +00003481 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00003482 return SQLITE_OK;
drhecdc7532001-09-23 02:35:53 +00003483 }
drh8178a752003-01-05 21:41:40 +00003484 assert( pPage->isInit );
drh8178a752003-01-05 21:41:40 +00003485 assert( pCur->idx<pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00003486
drh72f82862001-05-24 21:06:34 +00003487 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00003488 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00003489 if( pCur->idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00003490 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003491 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00003492 if( rc ) return rc;
3493 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003494 *pRes = 0;
3495 return rc;
drh72f82862001-05-24 21:06:34 +00003496 }
drh5e2f8b92001-05-28 00:41:15 +00003497 do{
drh8856d6a2004-04-29 14:42:46 +00003498 if( isRootPage(pPage) ){
drh8c1238a2003-01-02 14:43:55 +00003499 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00003500 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00003501 return SQLITE_OK;
3502 }
drh8178a752003-01-05 21:41:40 +00003503 moveToParent(pCur);
3504 pPage = pCur->pPage;
3505 }while( pCur->idx>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00003506 *pRes = 0;
drh8b18dd42004-05-12 19:18:15 +00003507 if( pPage->leafData ){
3508 rc = sqlite3BtreeNext(pCur, pRes);
3509 }else{
3510 rc = SQLITE_OK;
3511 }
3512 return rc;
drh8178a752003-01-05 21:41:40 +00003513 }
3514 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00003515 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00003516 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00003517 }
drh5e2f8b92001-05-28 00:41:15 +00003518 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003519 return rc;
drh72f82862001-05-24 21:06:34 +00003520}
3521
drh3b7511c2001-05-26 13:15:44 +00003522/*
drh2dcc9aa2002-12-04 13:40:25 +00003523** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00003524** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00003525** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00003526** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00003527*/
drh3aac2dd2004-04-26 14:10:20 +00003528int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00003529 int rc;
3530 Pgno pgno;
drh8178a752003-01-05 21:41:40 +00003531 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00003532
3533#ifndef SQLITE_OMIT_SHARED_CACHE
drh777e4c42006-01-13 04:31:58 +00003534 rc = restoreOrClearCursorPosition(pCur, 1);
danielk1977da184232006-01-05 11:34:32 +00003535 if( rc!=SQLITE_OK ){
3536 return rc;
3537 }
3538 if( pCur->skip<0 ){
3539 pCur->skip = 0;
3540 *pRes = 0;
3541 return SQLITE_OK;
3542 }
3543 pCur->skip = 0;
3544#endif
3545
3546 if( CURSOR_INVALID==pCur->eState ){
drhc39e0002004-05-07 23:50:57 +00003547 *pRes = 1;
3548 return SQLITE_OK;
3549 }
danielk19776a43f9b2004-11-16 04:57:24 +00003550
drh8178a752003-01-05 21:41:40 +00003551 pPage = pCur->pPage;
drh8178a752003-01-05 21:41:40 +00003552 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00003553 assert( pCur->idx>=0 );
drha34b6762004-05-07 13:30:42 +00003554 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003555 pgno = get4byte( findCell(pPage, pCur->idx) );
drh8178a752003-01-05 21:41:40 +00003556 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003557 if( rc ) return rc;
3558 rc = moveToRightmost(pCur);
3559 }else{
3560 while( pCur->idx==0 ){
drh8856d6a2004-04-29 14:42:46 +00003561 if( isRootPage(pPage) ){
danielk1977da184232006-01-05 11:34:32 +00003562 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00003563 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00003564 return SQLITE_OK;
3565 }
drh8178a752003-01-05 21:41:40 +00003566 moveToParent(pCur);
3567 pPage = pCur->pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003568 }
3569 pCur->idx--;
drh271efa52004-05-30 19:19:05 +00003570 pCur->info.nSize = 0;
drh8237d452004-11-22 19:07:09 +00003571 if( pPage->leafData && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00003572 rc = sqlite3BtreePrevious(pCur, pRes);
3573 }else{
3574 rc = SQLITE_OK;
3575 }
drh2dcc9aa2002-12-04 13:40:25 +00003576 }
drh8178a752003-01-05 21:41:40 +00003577 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003578 return rc;
3579}
3580
3581/*
drh3b7511c2001-05-26 13:15:44 +00003582** Allocate a new page from the database file.
3583**
drha34b6762004-05-07 13:30:42 +00003584** The new page is marked as dirty. (In other words, sqlite3pager_write()
drh3b7511c2001-05-26 13:15:44 +00003585** has already been called on the new page.) The new page has also
3586** been referenced and the calling routine is responsible for calling
drha34b6762004-05-07 13:30:42 +00003587** sqlite3pager_unref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00003588**
3589** SQLITE_OK is returned on success. Any other return value indicates
3590** an error. *ppPage and *pPgno are undefined in the event of an error.
drha34b6762004-05-07 13:30:42 +00003591** Do not invoke sqlite3pager_unref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00003592**
drh199e3cf2002-07-18 11:01:47 +00003593** If the "nearby" parameter is not 0, then a (feeble) effort is made to
3594** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00003595** attempt to keep related pages close to each other in the database file,
3596** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00003597**
3598** If the "exact" parameter is not 0, and the page-number nearby exists
3599** anywhere on the free-list, then it is guarenteed to be returned. This
3600** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00003601*/
danielk1977cb1a7eb2004-11-05 12:27:02 +00003602static int allocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00003603 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00003604 MemPage **ppPage,
3605 Pgno *pPgno,
3606 Pgno nearby,
3607 u8 exact
3608){
drh3aac2dd2004-04-26 14:10:20 +00003609 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00003610 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003611 int n; /* Number of pages on the freelist */
3612 int k; /* Number of leaves on the trunk of the freelist */
drh30e58752002-03-02 20:41:57 +00003613
drh3aac2dd2004-04-26 14:10:20 +00003614 pPage1 = pBt->pPage1;
3615 n = get4byte(&pPage1->aData[36]);
3616 if( n>0 ){
drh91025292004-05-03 19:49:32 +00003617 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00003618 MemPage *pTrunk = 0;
3619 Pgno iTrunk;
3620 MemPage *pPrevTrunk = 0;
3621 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
3622
3623 /* If the 'exact' parameter was true and a query of the pointer-map
3624 ** shows that the page 'nearby' is somewhere on the free-list, then
3625 ** the entire-list will be searched for that page.
3626 */
3627#ifndef SQLITE_OMIT_AUTOVACUUM
3628 if( exact ){
3629 u8 eType;
3630 assert( nearby>0 );
3631 assert( pBt->autoVacuum );
3632 rc = ptrmapGet(pBt, nearby, &eType, 0);
3633 if( rc ) return rc;
3634 if( eType==PTRMAP_FREEPAGE ){
3635 searchList = 1;
3636 }
3637 *pPgno = nearby;
3638 }
3639#endif
3640
3641 /* Decrement the free-list count by 1. Set iTrunk to the index of the
3642 ** first free-list trunk page. iPrevTrunk is initially 1.
3643 */
drha34b6762004-05-07 13:30:42 +00003644 rc = sqlite3pager_write(pPage1->aData);
drh3b7511c2001-05-26 13:15:44 +00003645 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003646 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003647
3648 /* The code within this loop is run only once if the 'searchList' variable
3649 ** is not true. Otherwise, it runs once for each trunk-page on the
3650 ** free-list until the page 'nearby' is located.
3651 */
3652 do {
3653 pPrevTrunk = pTrunk;
3654 if( pPrevTrunk ){
3655 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00003656 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00003657 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00003658 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003659 rc = getPage(pBt, iTrunk, &pTrunk);
3660 if( rc ){
3661 releasePage(pPrevTrunk);
3662 return rc;
3663 }
3664
3665 /* TODO: This should move to after the loop? */
3666 rc = sqlite3pager_write(pTrunk->aData);
3667 if( rc ){
3668 releasePage(pTrunk);
3669 releasePage(pPrevTrunk);
3670 return rc;
3671 }
3672
3673 k = get4byte(&pTrunk->aData[4]);
3674 if( k==0 && !searchList ){
3675 /* The trunk has no leaves and the list is not being searched.
3676 ** So extract the trunk page itself and use it as the newly
3677 ** allocated page */
3678 assert( pPrevTrunk==0 );
3679 *pPgno = iTrunk;
3680 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3681 *ppPage = pTrunk;
3682 pTrunk = 0;
3683 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3684 }else if( k>pBt->usableSize/4 - 8 ){
3685 /* Value of k is out of range. Database corruption */
drh49285702005-09-17 15:20:26 +00003686 return SQLITE_CORRUPT_BKPT;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003687#ifndef SQLITE_OMIT_AUTOVACUUM
3688 }else if( searchList && nearby==iTrunk ){
3689 /* The list is being searched and this trunk page is the page
3690 ** to allocate, regardless of whether it has leaves.
3691 */
3692 assert( *pPgno==iTrunk );
3693 *ppPage = pTrunk;
3694 searchList = 0;
3695 if( k==0 ){
3696 if( !pPrevTrunk ){
3697 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3698 }else{
3699 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
3700 }
3701 }else{
3702 /* The trunk page is required by the caller but it contains
3703 ** pointers to free-list leaves. The first leaf becomes a trunk
3704 ** page in this case.
3705 */
3706 MemPage *pNewTrunk;
3707 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
3708 rc = getPage(pBt, iNewTrunk, &pNewTrunk);
3709 if( rc!=SQLITE_OK ){
3710 releasePage(pTrunk);
3711 releasePage(pPrevTrunk);
3712 return rc;
3713 }
3714 rc = sqlite3pager_write(pNewTrunk->aData);
3715 if( rc!=SQLITE_OK ){
3716 releasePage(pNewTrunk);
3717 releasePage(pTrunk);
3718 releasePage(pPrevTrunk);
3719 return rc;
3720 }
3721 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
3722 put4byte(&pNewTrunk->aData[4], k-1);
3723 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
3724 if( !pPrevTrunk ){
3725 put4byte(&pPage1->aData[32], iNewTrunk);
3726 }else{
3727 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
3728 }
3729 releasePage(pNewTrunk);
3730 }
3731 pTrunk = 0;
3732 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3733#endif
3734 }else{
3735 /* Extract a leaf from the trunk */
3736 int closest;
3737 Pgno iPage;
3738 unsigned char *aData = pTrunk->aData;
3739 if( nearby>0 ){
3740 int i, dist;
3741 closest = 0;
3742 dist = get4byte(&aData[8]) - nearby;
3743 if( dist<0 ) dist = -dist;
3744 for(i=1; i<k; i++){
3745 int d2 = get4byte(&aData[8+i*4]) - nearby;
3746 if( d2<0 ) d2 = -d2;
3747 if( d2<dist ){
3748 closest = i;
3749 dist = d2;
3750 }
3751 }
3752 }else{
3753 closest = 0;
3754 }
3755
3756 iPage = get4byte(&aData[8+closest*4]);
3757 if( !searchList || iPage==nearby ){
3758 *pPgno = iPage;
3759 if( *pPgno>sqlite3pager_pagecount(pBt->pPager) ){
3760 /* Free page off the end of the file */
drh49285702005-09-17 15:20:26 +00003761 return SQLITE_CORRUPT_BKPT;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003762 }
3763 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
3764 ": %d more free pages\n",
3765 *pPgno, closest+1, k, pTrunk->pgno, n-1));
3766 if( closest<k-1 ){
3767 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
3768 }
3769 put4byte(&aData[4], k-1);
3770 rc = getPage(pBt, *pPgno, ppPage);
3771 if( rc==SQLITE_OK ){
3772 sqlite3pager_dont_rollback((*ppPage)->aData);
3773 rc = sqlite3pager_write((*ppPage)->aData);
danielk1977aac0a382005-01-16 11:07:06 +00003774 if( rc!=SQLITE_OK ){
3775 releasePage(*ppPage);
3776 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003777 }
3778 searchList = 0;
3779 }
drhee696e22004-08-30 16:52:17 +00003780 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003781 releasePage(pPrevTrunk);
3782 }while( searchList );
3783 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003784 }else{
drh3aac2dd2004-04-26 14:10:20 +00003785 /* There are no pages on the freelist, so create a new page at the
3786 ** end of the file */
drha34b6762004-05-07 13:30:42 +00003787 *pPgno = sqlite3pager_pagecount(pBt->pPager) + 1;
danielk1977afcdd022004-10-31 16:25:42 +00003788
3789#ifndef SQLITE_OMIT_AUTOVACUUM
drh42cac6d2004-11-20 20:31:11 +00003790 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt->usableSize, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00003791 /* If *pPgno refers to a pointer-map page, allocate two new pages
3792 ** at the end of the file instead of one. The first allocated page
3793 ** becomes a new pointer-map page, the second is used by the caller.
3794 */
3795 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00003796 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977afcdd022004-10-31 16:25:42 +00003797 (*pPgno)++;
3798 }
3799#endif
3800
danielk1977599fcba2004-11-08 07:13:13 +00003801 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00003802 rc = getPage(pBt, *pPgno, ppPage);
drh3b7511c2001-05-26 13:15:44 +00003803 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003804 rc = sqlite3pager_write((*ppPage)->aData);
danielk1977aac0a382005-01-16 11:07:06 +00003805 if( rc!=SQLITE_OK ){
3806 releasePage(*ppPage);
3807 }
drh3a4c1412004-05-09 20:40:11 +00003808 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00003809 }
danielk1977599fcba2004-11-08 07:13:13 +00003810
3811 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh3b7511c2001-05-26 13:15:44 +00003812 return rc;
3813}
3814
3815/*
drh3aac2dd2004-04-26 14:10:20 +00003816** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00003817**
drha34b6762004-05-07 13:30:42 +00003818** sqlite3pager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00003819*/
drh3aac2dd2004-04-26 14:10:20 +00003820static int freePage(MemPage *pPage){
danielk1977aef0bf62005-12-30 16:28:01 +00003821 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00003822 MemPage *pPage1 = pBt->pPage1;
3823 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00003824
drh3aac2dd2004-04-26 14:10:20 +00003825 /* Prepare the page for freeing */
3826 assert( pPage->pgno>1 );
3827 pPage->isInit = 0;
3828 releasePage(pPage->pParent);
3829 pPage->pParent = 0;
3830
drha34b6762004-05-07 13:30:42 +00003831 /* Increment the free page count on pPage1 */
3832 rc = sqlite3pager_write(pPage1->aData);
drh3aac2dd2004-04-26 14:10:20 +00003833 if( rc ) return rc;
3834 n = get4byte(&pPage1->aData[36]);
3835 put4byte(&pPage1->aData[36], n+1);
3836
danielk1977687566d2004-11-02 12:56:41 +00003837#ifndef SQLITE_OMIT_AUTOVACUUM
3838 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00003839 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00003840 */
3841 if( pBt->autoVacuum ){
3842 rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
danielk1977a64a0352004-11-05 01:45:13 +00003843 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00003844 }
3845#endif
3846
drh3aac2dd2004-04-26 14:10:20 +00003847 if( n==0 ){
3848 /* This is the first free page */
drhda200cc2004-05-09 11:51:38 +00003849 rc = sqlite3pager_write(pPage->aData);
3850 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003851 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00003852 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003853 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003854 }else{
3855 /* Other free pages already exist. Retrive the first trunk page
3856 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00003857 MemPage *pTrunk;
3858 rc = getPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003859 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003860 k = get4byte(&pTrunk->aData[4]);
drhee696e22004-08-30 16:52:17 +00003861 if( k>=pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00003862 /* The trunk is full. Turn the page being freed into a new
3863 ** trunk page with no leaves. */
drha34b6762004-05-07 13:30:42 +00003864 rc = sqlite3pager_write(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00003865 if( rc ) return rc;
3866 put4byte(pPage->aData, pTrunk->pgno);
3867 put4byte(&pPage->aData[4], 0);
3868 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003869 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
3870 pPage->pgno, pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003871 }else{
3872 /* Add the newly freed page as a leaf on the current trunk */
drha34b6762004-05-07 13:30:42 +00003873 rc = sqlite3pager_write(pTrunk->aData);
drh3aac2dd2004-04-26 14:10:20 +00003874 if( rc ) return rc;
3875 put4byte(&pTrunk->aData[4], k+1);
3876 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drha34b6762004-05-07 13:30:42 +00003877 sqlite3pager_dont_write(pBt->pPager, pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003878 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003879 }
3880 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003881 }
drh3b7511c2001-05-26 13:15:44 +00003882 return rc;
3883}
3884
3885/*
drh3aac2dd2004-04-26 14:10:20 +00003886** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00003887*/
drh3aac2dd2004-04-26 14:10:20 +00003888static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00003889 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00003890 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00003891 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00003892 int rc;
drh3b7511c2001-05-26 13:15:44 +00003893
drh43605152004-05-29 21:46:49 +00003894 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003895 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00003896 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00003897 }
drh6f11bef2004-05-13 01:12:56 +00003898 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh3aac2dd2004-04-26 14:10:20 +00003899 while( ovflPgno!=0 ){
3900 MemPage *pOvfl;
danielk1977a1cb1832005-02-12 08:59:55 +00003901 if( ovflPgno>sqlite3pager_pagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00003902 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00003903 }
drh3aac2dd2004-04-26 14:10:20 +00003904 rc = getPage(pBt, ovflPgno, &pOvfl);
drh3b7511c2001-05-26 13:15:44 +00003905 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003906 ovflPgno = get4byte(pOvfl->aData);
drha34b6762004-05-07 13:30:42 +00003907 rc = freePage(pOvfl);
drha34b6762004-05-07 13:30:42 +00003908 sqlite3pager_unref(pOvfl->aData);
danielk19776b456a22005-03-21 04:04:02 +00003909 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00003910 }
drh5e2f8b92001-05-28 00:41:15 +00003911 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00003912}
3913
3914/*
drh91025292004-05-03 19:49:32 +00003915** Create the byte sequence used to represent a cell on page pPage
3916** and write that byte sequence into pCell[]. Overflow pages are
3917** allocated and filled in as necessary. The calling procedure
3918** is responsible for making sure sufficient space has been allocated
3919** for pCell[].
3920**
3921** Note that pCell does not necessary need to point to the pPage->aData
3922** area. pCell might point to some temporary storage. The cell will
3923** be constructed in this temporary area then copied into pPage->aData
3924** later.
drh3b7511c2001-05-26 13:15:44 +00003925*/
3926static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00003927 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00003928 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00003929 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00003930 const void *pData,int nData, /* The data */
3931 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00003932){
drh3b7511c2001-05-26 13:15:44 +00003933 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00003934 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00003935 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00003936 int spaceLeft;
3937 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00003938 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00003939 unsigned char *pPrior;
3940 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00003941 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00003942 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00003943 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00003944 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00003945
drh91025292004-05-03 19:49:32 +00003946 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00003947 nHeader = 0;
drh91025292004-05-03 19:49:32 +00003948 if( !pPage->leaf ){
3949 nHeader += 4;
3950 }
drh8b18dd42004-05-12 19:18:15 +00003951 if( pPage->hasData ){
drh91025292004-05-03 19:49:32 +00003952 nHeader += putVarint(&pCell[nHeader], nData);
drh6f11bef2004-05-13 01:12:56 +00003953 }else{
drh91025292004-05-03 19:49:32 +00003954 nData = 0;
3955 }
drh6f11bef2004-05-13 01:12:56 +00003956 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh43605152004-05-29 21:46:49 +00003957 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003958 assert( info.nHeader==nHeader );
3959 assert( info.nKey==nKey );
3960 assert( info.nData==nData );
3961
3962 /* Fill in the payload */
drh3aac2dd2004-04-26 14:10:20 +00003963 nPayload = nData;
3964 if( pPage->intKey ){
3965 pSrc = pData;
3966 nSrc = nData;
drh91025292004-05-03 19:49:32 +00003967 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00003968 }else{
3969 nPayload += nKey;
3970 pSrc = pKey;
3971 nSrc = nKey;
3972 }
drh6f11bef2004-05-13 01:12:56 +00003973 *pnSize = info.nSize;
3974 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00003975 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00003976 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00003977
drh3b7511c2001-05-26 13:15:44 +00003978 while( nPayload>0 ){
3979 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00003980#ifndef SQLITE_OMIT_AUTOVACUUM
3981 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
3982#endif
danielk1977cb1a7eb2004-11-05 12:27:02 +00003983 rc = allocatePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00003984#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00003985 /* If the database supports auto-vacuum, and the second or subsequent
3986 ** overflow page is being allocated, add an entry to the pointer-map
3987 ** for that page now. The entry for the first overflow page will be
3988 ** added later, by the insertCell() routine.
danielk1977afcdd022004-10-31 16:25:42 +00003989 */
danielk1977a19df672004-11-03 11:37:07 +00003990 if( pBt->autoVacuum && pgnoPtrmap!=0 && rc==SQLITE_OK ){
3991 rc = ptrmapPut(pBt, pgnoOvfl, PTRMAP_OVERFLOW2, pgnoPtrmap);
danielk1977afcdd022004-10-31 16:25:42 +00003992 }
3993#endif
drh3b7511c2001-05-26 13:15:44 +00003994 if( rc ){
drh9b171272004-05-08 02:03:22 +00003995 releasePage(pToRelease);
danielk197728129562005-01-11 10:25:06 +00003996 /* clearCell(pPage, pCell); */
drh3b7511c2001-05-26 13:15:44 +00003997 return rc;
3998 }
drh3aac2dd2004-04-26 14:10:20 +00003999 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00004000 releasePage(pToRelease);
4001 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00004002 pPrior = pOvfl->aData;
4003 put4byte(pPrior, 0);
4004 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00004005 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00004006 }
4007 n = nPayload;
4008 if( n>spaceLeft ) n = spaceLeft;
drh3aac2dd2004-04-26 14:10:20 +00004009 if( n>nSrc ) n = nSrc;
4010 memcpy(pPayload, pSrc, n);
drh3b7511c2001-05-26 13:15:44 +00004011 nPayload -= n;
drhde647132004-05-07 17:57:49 +00004012 pPayload += n;
drh9b171272004-05-08 02:03:22 +00004013 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00004014 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00004015 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00004016 if( nSrc==0 ){
4017 nSrc = nData;
4018 pSrc = pData;
4019 }
drhdd793422001-06-28 01:54:48 +00004020 }
drh9b171272004-05-08 02:03:22 +00004021 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004022 return SQLITE_OK;
4023}
4024
4025/*
drhbd03cae2001-06-02 02:40:57 +00004026** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00004027** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00004028** pointer in the third argument.
4029*/
danielk1977aef0bf62005-12-30 16:28:01 +00004030static int reparentPage(BtShared *pBt, Pgno pgno, MemPage *pNewParent, int idx){
drhbd03cae2001-06-02 02:40:57 +00004031 MemPage *pThis;
drh4b70f112004-05-02 21:12:19 +00004032 unsigned char *aData;
drhbd03cae2001-06-02 02:40:57 +00004033
danielk1977afcdd022004-10-31 16:25:42 +00004034 if( pgno==0 ) return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00004035 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00004036 aData = sqlite3pager_lookup(pBt->pPager, pgno);
drhda200cc2004-05-09 11:51:38 +00004037 if( aData ){
drh07d183d2005-05-01 22:52:42 +00004038 pThis = (MemPage*)&aData[pBt->pageSize];
drh31276532004-09-27 12:20:52 +00004039 assert( pThis->aData==aData );
drhda200cc2004-05-09 11:51:38 +00004040 if( pThis->isInit ){
4041 if( pThis->pParent!=pNewParent ){
4042 if( pThis->pParent ) sqlite3pager_unref(pThis->pParent->aData);
4043 pThis->pParent = pNewParent;
4044 if( pNewParent ) sqlite3pager_ref(pNewParent->aData);
4045 }
4046 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00004047 }
drha34b6762004-05-07 13:30:42 +00004048 sqlite3pager_unref(aData);
drhbd03cae2001-06-02 02:40:57 +00004049 }
danielk1977afcdd022004-10-31 16:25:42 +00004050
4051#ifndef SQLITE_OMIT_AUTOVACUUM
4052 if( pBt->autoVacuum ){
4053 return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
4054 }
4055#endif
4056 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00004057}
4058
danielk1977ac11ee62005-01-15 12:45:51 +00004059
4060
drhbd03cae2001-06-02 02:40:57 +00004061/*
drh4b70f112004-05-02 21:12:19 +00004062** Change the pParent pointer of all children of pPage to point back
4063** to pPage.
4064**
drhbd03cae2001-06-02 02:40:57 +00004065** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00004066** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00004067**
4068** This routine gets called after you memcpy() one page into
4069** another.
4070*/
danielk1977afcdd022004-10-31 16:25:42 +00004071static int reparentChildPages(MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00004072 int i;
danielk1977aef0bf62005-12-30 16:28:01 +00004073 BtShared *pBt = pPage->pBt;
danielk1977afcdd022004-10-31 16:25:42 +00004074 int rc = SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00004075
danielk1977afcdd022004-10-31 16:25:42 +00004076 if( pPage->leaf ) return SQLITE_OK;
danielk1977afcdd022004-10-31 16:25:42 +00004077
drhbd03cae2001-06-02 02:40:57 +00004078 for(i=0; i<pPage->nCell; i++){
danielk1977afcdd022004-10-31 16:25:42 +00004079 u8 *pCell = findCell(pPage, i);
4080 if( !pPage->leaf ){
4081 rc = reparentPage(pBt, get4byte(pCell), pPage, i);
4082 if( rc!=SQLITE_OK ) return rc;
4083 }
drhbd03cae2001-06-02 02:40:57 +00004084 }
danielk1977afcdd022004-10-31 16:25:42 +00004085 if( !pPage->leaf ){
4086 rc = reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]),
4087 pPage, i);
4088 pPage->idxShift = 0;
4089 }
4090 return rc;
drh14acc042001-06-10 19:56:58 +00004091}
4092
4093/*
4094** Remove the i-th cell from pPage. This routine effects pPage only.
4095** The cell content is not freed or deallocated. It is assumed that
4096** the cell content has been copied someplace else. This routine just
4097** removes the reference to the cell from pPage.
4098**
4099** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00004100*/
drh4b70f112004-05-02 21:12:19 +00004101static void dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00004102 int i; /* Loop counter */
4103 int pc; /* Offset to cell content of cell being deleted */
4104 u8 *data; /* pPage->aData */
4105 u8 *ptr; /* Used to move bytes around within data[] */
4106
drh8c42ca92001-06-22 19:15:00 +00004107 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00004108 assert( sz==cellSize(pPage, idx) );
drha34b6762004-05-07 13:30:42 +00004109 assert( sqlite3pager_iswriteable(pPage->aData) );
drhda200cc2004-05-09 11:51:38 +00004110 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00004111 ptr = &data[pPage->cellOffset + 2*idx];
4112 pc = get2byte(ptr);
4113 assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
drhde647132004-05-07 17:57:49 +00004114 freeSpace(pPage, pc, sz);
drh43605152004-05-29 21:46:49 +00004115 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
4116 ptr[0] = ptr[2];
4117 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00004118 }
4119 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00004120 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
4121 pPage->nFree += 2;
drh428ae8c2003-01-04 16:48:09 +00004122 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00004123}
4124
4125/*
4126** Insert a new cell on pPage at cell index "i". pCell points to the
4127** content of the cell.
4128**
4129** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00004130** will not fit, then make a copy of the cell content into pTemp if
4131** pTemp is not null. Regardless of pTemp, allocate a new entry
4132** in pPage->aOvfl[] and make it point to the cell content (either
4133** in pTemp or the original pCell) and also record its index.
4134** Allocating a new entry in pPage->aCell[] implies that
4135** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00004136**
4137** If nSkip is non-zero, then do not copy the first nSkip bytes of the
4138** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00004139** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00004140** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00004141*/
danielk1977e80463b2004-11-03 03:01:16 +00004142static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00004143 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00004144 int i, /* New cell becomes the i-th cell of the page */
4145 u8 *pCell, /* Content of the new cell */
4146 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00004147 u8 *pTemp, /* Temp storage space for pCell, if needed */
4148 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00004149){
drh43605152004-05-29 21:46:49 +00004150 int idx; /* Where to write new cell content in data[] */
4151 int j; /* Loop counter */
4152 int top; /* First byte of content for any cell in data[] */
4153 int end; /* First byte past the last cell pointer in data[] */
4154 int ins; /* Index in data[] where new cell pointer is inserted */
4155 int hdr; /* Offset into data[] of the page header */
4156 int cellOffset; /* Address of first cell pointer in data[] */
4157 u8 *data; /* The content of the whole page */
4158 u8 *ptr; /* Used for moving information around in data[] */
4159
4160 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
4161 assert( sz==cellSizePtr(pPage, pCell) );
drha34b6762004-05-07 13:30:42 +00004162 assert( sqlite3pager_iswriteable(pPage->aData) );
drh43605152004-05-29 21:46:49 +00004163 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00004164 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00004165 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004166 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00004167 }
drh43605152004-05-29 21:46:49 +00004168 j = pPage->nOverflow++;
4169 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
4170 pPage->aOvfl[j].pCell = pCell;
4171 pPage->aOvfl[j].idx = i;
4172 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00004173 }else{
drh43605152004-05-29 21:46:49 +00004174 data = pPage->aData;
4175 hdr = pPage->hdrOffset;
4176 top = get2byte(&data[hdr+5]);
4177 cellOffset = pPage->cellOffset;
4178 end = cellOffset + 2*pPage->nCell + 2;
4179 ins = cellOffset + 2*i;
4180 if( end > top - sz ){
danielk19776b456a22005-03-21 04:04:02 +00004181 int rc = defragmentPage(pPage);
4182 if( rc!=SQLITE_OK ) return rc;
drh43605152004-05-29 21:46:49 +00004183 top = get2byte(&data[hdr+5]);
4184 assert( end + sz <= top );
4185 }
4186 idx = allocateSpace(pPage, sz);
4187 assert( idx>0 );
4188 assert( end <= get2byte(&data[hdr+5]) );
4189 pPage->nCell++;
4190 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00004191 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004192 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
4193 ptr[0] = ptr[-2];
4194 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00004195 }
drh43605152004-05-29 21:46:49 +00004196 put2byte(&data[ins], idx);
4197 put2byte(&data[hdr+3], pPage->nCell);
4198 pPage->idxShift = 1;
drhda200cc2004-05-09 11:51:38 +00004199 pageIntegrity(pPage);
danielk1977a19df672004-11-03 11:37:07 +00004200#ifndef SQLITE_OMIT_AUTOVACUUM
4201 if( pPage->pBt->autoVacuum ){
4202 /* The cell may contain a pointer to an overflow page. If so, write
4203 ** the entry for the overflow page into the pointer map.
4204 */
4205 CellInfo info;
4206 parseCellPtr(pPage, pCell, &info);
4207 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
4208 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
4209 int rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
4210 if( rc!=SQLITE_OK ) return rc;
4211 }
4212 }
4213#endif
drh14acc042001-06-10 19:56:58 +00004214 }
danielk1977e80463b2004-11-03 03:01:16 +00004215
danielk1977e80463b2004-11-03 03:01:16 +00004216 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004217}
4218
4219/*
drhfa1a98a2004-05-14 19:08:17 +00004220** Add a list of cells to a page. The page should be initially empty.
4221** The cells are guaranteed to fit on the page.
4222*/
4223static void assemblePage(
4224 MemPage *pPage, /* The page to be assemblied */
4225 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00004226 u8 **apCell, /* Pointers to cell bodies */
drhfa1a98a2004-05-14 19:08:17 +00004227 int *aSize /* Sizes of the cells */
4228){
4229 int i; /* Loop counter */
4230 int totalSize; /* Total size of all cells */
4231 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00004232 int cellptr; /* Address of next cell pointer */
4233 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00004234 u8 *data; /* Data for the page */
4235
drh43605152004-05-29 21:46:49 +00004236 assert( pPage->nOverflow==0 );
drhfa1a98a2004-05-14 19:08:17 +00004237 totalSize = 0;
4238 for(i=0; i<nCell; i++){
4239 totalSize += aSize[i];
4240 }
drh43605152004-05-29 21:46:49 +00004241 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00004242 assert( pPage->nCell==0 );
drh43605152004-05-29 21:46:49 +00004243 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00004244 data = pPage->aData;
4245 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00004246 put2byte(&data[hdr+3], nCell);
drh09d0deb2005-08-02 17:13:09 +00004247 if( nCell ){
4248 cellbody = allocateSpace(pPage, totalSize);
4249 assert( cellbody>0 );
4250 assert( pPage->nFree >= 2*nCell );
4251 pPage->nFree -= 2*nCell;
4252 for(i=0; i<nCell; i++){
4253 put2byte(&data[cellptr], cellbody);
4254 memcpy(&data[cellbody], apCell[i], aSize[i]);
4255 cellptr += 2;
4256 cellbody += aSize[i];
4257 }
4258 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00004259 }
4260 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00004261}
4262
drh14acc042001-06-10 19:56:58 +00004263/*
drhc3b70572003-01-04 19:44:07 +00004264** The following parameters determine how many adjacent pages get involved
4265** in a balancing operation. NN is the number of neighbors on either side
4266** of the page that participate in the balancing operation. NB is the
4267** total number of pages that participate, including the target page and
4268** NN neighbors on either side.
4269**
4270** The minimum value of NN is 1 (of course). Increasing NN above 1
4271** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
4272** in exchange for a larger degradation in INSERT and UPDATE performance.
4273** The value of NN appears to give the best results overall.
4274*/
4275#define NN 1 /* Number of neighbors on either side of pPage */
4276#define NB (NN*2+1) /* Total pages involved in the balance */
4277
drh43605152004-05-29 21:46:49 +00004278/* Forward reference */
danielk1977ac245ec2005-01-14 13:50:11 +00004279static int balance(MemPage*, int);
4280
drh615ae552005-01-16 23:21:00 +00004281#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004282/*
4283** This version of balance() handles the common special case where
4284** a new entry is being inserted on the extreme right-end of the
4285** tree, in other words, when the new entry will become the largest
4286** entry in the tree.
4287**
4288** Instead of trying balance the 3 right-most leaf pages, just add
4289** a new page to the right-hand side and put the one new entry in
4290** that page. This leaves the right side of the tree somewhat
4291** unbalanced. But odds are that we will be inserting new entries
4292** at the end soon afterwards so the nearly empty page will quickly
4293** fill up. On average.
4294**
4295** pPage is the leaf page which is the right-most page in the tree.
4296** pParent is its parent. pPage must have a single overflow entry
4297** which is also the right-most entry on the page.
4298*/
danielk1977ac245ec2005-01-14 13:50:11 +00004299static int balance_quick(MemPage *pPage, MemPage *pParent){
4300 int rc;
4301 MemPage *pNew;
4302 Pgno pgnoNew;
4303 u8 *pCell;
4304 int szCell;
4305 CellInfo info;
danielk1977aef0bf62005-12-30 16:28:01 +00004306 BtShared *pBt = pPage->pBt;
danielk197779a40da2005-01-16 08:00:01 +00004307 int parentIdx = pParent->nCell; /* pParent new divider cell index */
4308 int parentSize; /* Size of new divider cell */
4309 u8 parentCell[64]; /* Space for the new divider cell */
danielk1977ac245ec2005-01-14 13:50:11 +00004310
4311 /* Allocate a new page. Insert the overflow cell from pPage
4312 ** into it. Then remove the overflow cell from pPage.
4313 */
danielk1977ac11ee62005-01-15 12:45:51 +00004314 rc = allocatePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977ac245ec2005-01-14 13:50:11 +00004315 if( rc!=SQLITE_OK ){
4316 return rc;
4317 }
4318 pCell = pPage->aOvfl[0].pCell;
4319 szCell = cellSizePtr(pPage, pCell);
4320 zeroPage(pNew, pPage->aData[0]);
4321 assemblePage(pNew, 1, &pCell, &szCell);
4322 pPage->nOverflow = 0;
4323
danielk197779a40da2005-01-16 08:00:01 +00004324 /* Set the parent of the newly allocated page to pParent. */
4325 pNew->pParent = pParent;
4326 sqlite3pager_ref(pParent->aData);
4327
danielk1977ac245ec2005-01-14 13:50:11 +00004328 /* pPage is currently the right-child of pParent. Change this
4329 ** so that the right-child is the new page allocated above and
danielk197779a40da2005-01-16 08:00:01 +00004330 ** pPage is the next-to-right child.
danielk1977ac245ec2005-01-14 13:50:11 +00004331 */
danielk1977ac11ee62005-01-15 12:45:51 +00004332 assert( pPage->nCell>0 );
danielk1977ac245ec2005-01-14 13:50:11 +00004333 parseCellPtr(pPage, findCell(pPage, pPage->nCell-1), &info);
4334 rc = fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, &parentSize);
4335 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00004336 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004337 }
4338 assert( parentSize<64 );
4339 rc = insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
4340 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00004341 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004342 }
4343 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
4344 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
4345
danielk197779a40da2005-01-16 08:00:01 +00004346#ifndef SQLITE_OMIT_AUTOVACUUM
4347 /* If this is an auto-vacuum database, update the pointer map
4348 ** with entries for the new page, and any pointer from the
4349 ** cell on the page to an overflow page.
4350 */
danielk1977ac11ee62005-01-15 12:45:51 +00004351 if( pBt->autoVacuum ){
4352 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
4353 if( rc!=SQLITE_OK ){
4354 return rc;
4355 }
danielk197779a40da2005-01-16 08:00:01 +00004356 rc = ptrmapPutOvfl(pNew, 0);
4357 if( rc!=SQLITE_OK ){
4358 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00004359 }
4360 }
danielk197779a40da2005-01-16 08:00:01 +00004361#endif
danielk1977ac11ee62005-01-15 12:45:51 +00004362
danielk197779a40da2005-01-16 08:00:01 +00004363 /* Release the reference to the new page and balance the parent page,
4364 ** in case the divider cell inserted caused it to become overfull.
4365 */
danielk1977ac245ec2005-01-14 13:50:11 +00004366 releasePage(pNew);
4367 return balance(pParent, 0);
4368}
drh615ae552005-01-16 23:21:00 +00004369#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00004370
drhc3b70572003-01-04 19:44:07 +00004371/*
danielk1977ac11ee62005-01-15 12:45:51 +00004372** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
4373** if the database supports auto-vacuum or not. Because it is used
4374** within an expression that is an argument to another macro
4375** (sqliteMallocRaw), it is not possible to use conditional compilation.
4376** So, this macro is defined instead.
4377*/
4378#ifndef SQLITE_OMIT_AUTOVACUUM
4379#define ISAUTOVACUUM (pBt->autoVacuum)
4380#else
4381#define ISAUTOVACUUM 0
4382#endif
4383
4384/*
drhab01f612004-05-22 02:55:23 +00004385** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00004386** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00004387** Usually NN siblings on either side of pPage is used in the balancing,
4388** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00004389** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00004390** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00004391** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00004392**
drh0c6cc4e2004-06-15 02:13:26 +00004393** The number of siblings of pPage might be increased or decreased by one or
4394** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00004395** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00004396** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00004397** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00004398** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00004399**
drh8b2f49b2001-06-08 00:21:52 +00004400** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00004401** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00004402** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00004403** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00004404**
drh8c42ca92001-06-22 19:15:00 +00004405** In the course of balancing the siblings of pPage, the parent of pPage
4406** might become overfull or underfull. If that happens, then this routine
4407** is called recursively on the parent.
4408**
drh5e00f6c2001-09-13 13:46:56 +00004409** If this routine fails for any reason, it might leave the database
4410** in a corrupted state. So if this routine fails, the database should
4411** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00004412*/
drh43605152004-05-29 21:46:49 +00004413static int balance_nonroot(MemPage *pPage){
drh8b2f49b2001-06-08 00:21:52 +00004414 MemPage *pParent; /* The parent of pPage */
danielk1977aef0bf62005-12-30 16:28:01 +00004415 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00004416 int nCell = 0; /* Number of cells in apCell[] */
4417 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
drh8b2f49b2001-06-08 00:21:52 +00004418 int nOld; /* Number of pages in apOld[] */
4419 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00004420 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00004421 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00004422 int idx; /* Index of pPage in pParent->aCell[] */
4423 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00004424 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00004425 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00004426 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00004427 int usableSpace; /* Bytes in pPage beyond the header */
4428 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00004429 int subtotal; /* Subtotal of bytes in cells on one page */
drhb6f41482004-05-14 01:58:11 +00004430 int iSpace = 0; /* First unused byte of aSpace[] */
drhc3b70572003-01-04 19:44:07 +00004431 MemPage *apOld[NB]; /* pPage and up to two siblings */
4432 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00004433 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00004434 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
4435 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drh4b70f112004-05-02 21:12:19 +00004436 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00004437 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
4438 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00004439 u8 **apCell = 0; /* All cells begin balanced */
drh2e38c322004-09-03 18:38:44 +00004440 int *szCell; /* Local size of all cells in apCell[] */
4441 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
4442 u8 *aSpace; /* Space to hold copies of dividers cells */
danielk19774e17d142005-01-16 09:06:33 +00004443#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00004444 u8 *aFrom = 0;
4445#endif
drh8b2f49b2001-06-08 00:21:52 +00004446
drh14acc042001-06-10 19:56:58 +00004447 /*
drh43605152004-05-29 21:46:49 +00004448 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00004449 */
drh3a4c1412004-05-09 20:40:11 +00004450 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004451 assert( sqlite3pager_iswriteable(pPage->aData) );
drh4b70f112004-05-02 21:12:19 +00004452 pBt = pPage->pBt;
drh14acc042001-06-10 19:56:58 +00004453 pParent = pPage->pParent;
drh43605152004-05-29 21:46:49 +00004454 assert( pParent );
danielk197707cb5602006-01-20 10:55:05 +00004455 if( SQLITE_OK!=(rc = sqlite3pager_write(pParent->aData)) ){
4456 return rc;
4457 }
drh43605152004-05-29 21:46:49 +00004458 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00004459
drh615ae552005-01-16 23:21:00 +00004460#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004461 /*
4462 ** A special case: If a new entry has just been inserted into a
4463 ** table (that is, a btree with integer keys and all data at the leaves)
drh09d0deb2005-08-02 17:13:09 +00004464 ** and the new entry is the right-most entry in the tree (it has the
drhf222e712005-01-14 22:55:49 +00004465 ** largest key) then use the special balance_quick() routine for
4466 ** balancing. balance_quick() is much faster and results in a tighter
4467 ** packing of data in the common case.
4468 */
danielk1977ac245ec2005-01-14 13:50:11 +00004469 if( pPage->leaf &&
4470 pPage->intKey &&
4471 pPage->leafData &&
4472 pPage->nOverflow==1 &&
4473 pPage->aOvfl[0].idx==pPage->nCell &&
danielk1977ac11ee62005-01-15 12:45:51 +00004474 pPage->pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00004475 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
4476 ){
danielk1977ac11ee62005-01-15 12:45:51 +00004477 /*
4478 ** TODO: Check the siblings to the left of pPage. It may be that
4479 ** they are not full and no new page is required.
4480 */
danielk1977ac245ec2005-01-14 13:50:11 +00004481 return balance_quick(pPage, pParent);
4482 }
4483#endif
4484
drh2e38c322004-09-03 18:38:44 +00004485 /*
drh4b70f112004-05-02 21:12:19 +00004486 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00004487 ** to pPage. The "idx" variable is the index of that cell. If pPage
4488 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00004489 */
drhbb49aba2003-01-04 18:53:27 +00004490 if( pParent->idxShift ){
drha34b6762004-05-07 13:30:42 +00004491 Pgno pgno;
drh4b70f112004-05-02 21:12:19 +00004492 pgno = pPage->pgno;
drha34b6762004-05-07 13:30:42 +00004493 assert( pgno==sqlite3pager_pagenumber(pPage->aData) );
drhbb49aba2003-01-04 18:53:27 +00004494 for(idx=0; idx<pParent->nCell; idx++){
drh43605152004-05-29 21:46:49 +00004495 if( get4byte(findCell(pParent, idx))==pgno ){
drhbb49aba2003-01-04 18:53:27 +00004496 break;
4497 }
drh8b2f49b2001-06-08 00:21:52 +00004498 }
drh4b70f112004-05-02 21:12:19 +00004499 assert( idx<pParent->nCell
drh43605152004-05-29 21:46:49 +00004500 || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
drhbb49aba2003-01-04 18:53:27 +00004501 }else{
4502 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00004503 }
drh8b2f49b2001-06-08 00:21:52 +00004504
4505 /*
drh14acc042001-06-10 19:56:58 +00004506 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00004507 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00004508 */
drh14acc042001-06-10 19:56:58 +00004509 nOld = nNew = 0;
drha34b6762004-05-07 13:30:42 +00004510 sqlite3pager_ref(pParent->aData);
drh14acc042001-06-10 19:56:58 +00004511
4512 /*
drh4b70f112004-05-02 21:12:19 +00004513 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00004514 ** the siblings. An attempt is made to find NN siblings on either
4515 ** side of pPage. More siblings are taken from one side, however, if
4516 ** pPage there are fewer than NN siblings on the other side. If pParent
4517 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00004518 */
drhc3b70572003-01-04 19:44:07 +00004519 nxDiv = idx - NN;
4520 if( nxDiv + NB > pParent->nCell ){
4521 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00004522 }
drhc3b70572003-01-04 19:44:07 +00004523 if( nxDiv<0 ){
4524 nxDiv = 0;
4525 }
drh8b2f49b2001-06-08 00:21:52 +00004526 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00004527 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00004528 if( k<pParent->nCell ){
drh43605152004-05-29 21:46:49 +00004529 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00004530 nDiv++;
drha34b6762004-05-07 13:30:42 +00004531 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00004532 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00004533 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00004534 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00004535 }else{
4536 break;
drh8b2f49b2001-06-08 00:21:52 +00004537 }
drhde647132004-05-07 17:57:49 +00004538 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00004539 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00004540 apOld[i]->idxParent = k;
drh91025292004-05-03 19:49:32 +00004541 apCopy[i] = 0;
4542 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00004543 nOld++;
danielk1977634f2982005-03-28 08:44:07 +00004544 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
drh8b2f49b2001-06-08 00:21:52 +00004545 }
4546
drh8d97f1f2005-05-05 18:14:13 +00004547 /* Make nMaxCells a multiple of 2 in order to preserve 8-byte
4548 ** alignment */
4549 nMaxCells = (nMaxCells + 1)&~1;
4550
drh8b2f49b2001-06-08 00:21:52 +00004551 /*
danielk1977634f2982005-03-28 08:44:07 +00004552 ** Allocate space for memory structures
4553 */
4554 apCell = sqliteMallocRaw(
4555 nMaxCells*sizeof(u8*) /* apCell */
4556 + nMaxCells*sizeof(int) /* szCell */
drhc96d8532005-05-03 12:30:33 +00004557 + ROUND8(sizeof(MemPage))*NB /* aCopy */
drh07d183d2005-05-01 22:52:42 +00004558 + pBt->pageSize*(5+NB) /* aSpace */
drhc96d8532005-05-03 12:30:33 +00004559 + (ISAUTOVACUUM ? nMaxCells : 0) /* aFrom */
danielk1977634f2982005-03-28 08:44:07 +00004560 );
4561 if( apCell==0 ){
4562 rc = SQLITE_NOMEM;
4563 goto balance_cleanup;
4564 }
4565 szCell = (int*)&apCell[nMaxCells];
4566 aCopy[0] = (u8*)&szCell[nMaxCells];
drhc96d8532005-05-03 12:30:33 +00004567 assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004568 for(i=1; i<NB; i++){
drhc96d8532005-05-03 12:30:33 +00004569 aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
4570 assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004571 }
drhc96d8532005-05-03 12:30:33 +00004572 aSpace = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
4573 assert( ((aSpace - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004574#ifndef SQLITE_OMIT_AUTOVACUUM
4575 if( pBt->autoVacuum ){
drh07d183d2005-05-01 22:52:42 +00004576 aFrom = &aSpace[5*pBt->pageSize];
danielk1977634f2982005-03-28 08:44:07 +00004577 }
4578#endif
4579
4580 /*
drh14acc042001-06-10 19:56:58 +00004581 ** Make copies of the content of pPage and its siblings into aOld[].
4582 ** The rest of this function will use data from the copies rather
4583 ** that the original pages since the original pages will be in the
4584 ** process of being overwritten.
4585 */
4586 for(i=0; i<nOld; i++){
drh07d183d2005-05-01 22:52:42 +00004587 MemPage *p = apCopy[i] = (MemPage*)&aCopy[i][pBt->pageSize];
drh07d183d2005-05-01 22:52:42 +00004588 p->aData = &((u8*)p)[-pBt->pageSize];
4589 memcpy(p->aData, apOld[i]->aData, pBt->pageSize + sizeof(MemPage));
4590 /* The memcpy() above changes the value of p->aData so we have to
4591 ** set it again. */
drh07d183d2005-05-01 22:52:42 +00004592 p->aData = &((u8*)p)[-pBt->pageSize];
drh14acc042001-06-10 19:56:58 +00004593 }
4594
4595 /*
4596 ** Load pointers to all cells on sibling pages and the divider cells
4597 ** into the local apCell[] array. Make copies of the divider cells
drhb6f41482004-05-14 01:58:11 +00004598 ** into space obtained form aSpace[] and remove the the divider Cells
4599 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00004600 **
4601 ** If the siblings are on leaf pages, then the child pointers of the
4602 ** divider cells are stripped from the cells before they are copied
drh96f5b762004-05-16 16:24:36 +00004603 ** into aSpace[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00004604 ** child pointers. If siblings are not leaves, then all cell in
4605 ** apCell[] include child pointers. Either way, all cells in apCell[]
4606 ** are alike.
drh96f5b762004-05-16 16:24:36 +00004607 **
4608 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
4609 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00004610 */
4611 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00004612 leafCorrection = pPage->leaf*4;
drh8b18dd42004-05-12 19:18:15 +00004613 leafData = pPage->leafData && pPage->leaf;
drh8b2f49b2001-06-08 00:21:52 +00004614 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00004615 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00004616 int limit = pOld->nCell+pOld->nOverflow;
4617 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00004618 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00004619 apCell[nCell] = findOverflowCell(pOld, j);
4620 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk1977ac11ee62005-01-15 12:45:51 +00004621#ifndef SQLITE_OMIT_AUTOVACUUM
4622 if( pBt->autoVacuum ){
4623 int a;
4624 aFrom[nCell] = i;
4625 for(a=0; a<pOld->nOverflow; a++){
4626 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
4627 aFrom[nCell] = 0xFF;
4628 break;
4629 }
4630 }
4631 }
4632#endif
drh14acc042001-06-10 19:56:58 +00004633 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00004634 }
4635 if( i<nOld-1 ){
drh43605152004-05-29 21:46:49 +00004636 int sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00004637 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00004638 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
4639 ** are duplicates of keys on the child pages. We need to remove
4640 ** the divider cells from pParent, but the dividers cells are not
4641 ** added to apCell[] because they are duplicates of child cells.
4642 */
drh8b18dd42004-05-12 19:18:15 +00004643 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00004644 }else{
drhb6f41482004-05-14 01:58:11 +00004645 u8 *pTemp;
danielk1977634f2982005-03-28 08:44:07 +00004646 assert( nCell<nMaxCells );
drhb6f41482004-05-14 01:58:11 +00004647 szCell[nCell] = sz;
4648 pTemp = &aSpace[iSpace];
4649 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004650 assert( iSpace<=pBt->pageSize*5 );
drhb6f41482004-05-14 01:58:11 +00004651 memcpy(pTemp, apDiv[i], sz);
4652 apCell[nCell] = pTemp+leafCorrection;
danielk1977ac11ee62005-01-15 12:45:51 +00004653#ifndef SQLITE_OMIT_AUTOVACUUM
4654 if( pBt->autoVacuum ){
4655 aFrom[nCell] = 0xFF;
4656 }
4657#endif
drhb6f41482004-05-14 01:58:11 +00004658 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00004659 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00004660 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00004661 if( !pOld->leaf ){
4662 assert( leafCorrection==0 );
4663 /* The right pointer of the child page pOld becomes the left
4664 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00004665 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00004666 }else{
4667 assert( leafCorrection==4 );
4668 }
4669 nCell++;
drh4b70f112004-05-02 21:12:19 +00004670 }
drh8b2f49b2001-06-08 00:21:52 +00004671 }
4672 }
4673
4674 /*
drh6019e162001-07-02 17:51:45 +00004675 ** Figure out the number of pages needed to hold all nCell cells.
4676 ** Store this number in "k". Also compute szNew[] which is the total
4677 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00004678 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00004679 ** cntNew[k] should equal nCell.
4680 **
drh96f5b762004-05-16 16:24:36 +00004681 ** Values computed by this block:
4682 **
4683 ** k: The total number of sibling pages
4684 ** szNew[i]: Spaced used on the i-th sibling page.
4685 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
4686 ** the right of the i-th sibling page.
4687 ** usableSpace: Number of bytes of space available on each sibling.
4688 **
drh8b2f49b2001-06-08 00:21:52 +00004689 */
drh43605152004-05-29 21:46:49 +00004690 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00004691 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00004692 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00004693 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00004694 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00004695 szNew[k] = subtotal - szCell[i];
4696 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00004697 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00004698 subtotal = 0;
4699 k++;
4700 }
4701 }
4702 szNew[k] = subtotal;
4703 cntNew[k] = nCell;
4704 k++;
drh96f5b762004-05-16 16:24:36 +00004705
4706 /*
4707 ** The packing computed by the previous block is biased toward the siblings
4708 ** on the left side. The left siblings are always nearly full, while the
4709 ** right-most sibling might be nearly empty. This block of code attempts
4710 ** to adjust the packing of siblings to get a better balance.
4711 **
4712 ** This adjustment is more than an optimization. The packing above might
4713 ** be so out of balance as to be illegal. For example, the right-most
4714 ** sibling might be completely empty. This adjustment is not optional.
4715 */
drh6019e162001-07-02 17:51:45 +00004716 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00004717 int szRight = szNew[i]; /* Size of sibling on the right */
4718 int szLeft = szNew[i-1]; /* Size of sibling on the left */
4719 int r; /* Index of right-most cell in left sibling */
4720 int d; /* Index of first cell to the left of right sibling */
4721
4722 r = cntNew[i-1] - 1;
4723 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00004724 assert( d<nMaxCells );
4725 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00004726 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
4727 szRight += szCell[d] + 2;
4728 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00004729 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00004730 r = cntNew[i-1] - 1;
4731 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00004732 }
drh96f5b762004-05-16 16:24:36 +00004733 szNew[i] = szRight;
4734 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00004735 }
drh09d0deb2005-08-02 17:13:09 +00004736
4737 /* Either we found one or more cells (cntnew[0])>0) or we are the
4738 ** a virtual root page. A virtual root page is when the real root
4739 ** page is page 1 and we are the only child of that page.
4740 */
4741 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00004742
4743 /*
drh6b308672002-07-08 02:16:37 +00004744 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00004745 */
drh4b70f112004-05-02 21:12:19 +00004746 assert( pPage->pgno>1 );
4747 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00004748 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00004749 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00004750 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00004751 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00004752 pgnoNew[i] = pgnoOld[i];
4753 apOld[i] = 0;
danielk197728129562005-01-11 10:25:06 +00004754 rc = sqlite3pager_write(pNew->aData);
4755 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00004756 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004757 rc = allocatePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00004758 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00004759 apNew[i] = pNew;
drh6b308672002-07-08 02:16:37 +00004760 }
drh14acc042001-06-10 19:56:58 +00004761 nNew++;
drhda200cc2004-05-09 11:51:38 +00004762 zeroPage(pNew, pageFlags);
drh8b2f49b2001-06-08 00:21:52 +00004763 }
4764
danielk1977299b1872004-11-22 10:02:10 +00004765 /* Free any old pages that were not reused as new pages.
4766 */
4767 while( i<nOld ){
4768 rc = freePage(apOld[i]);
4769 if( rc ) goto balance_cleanup;
4770 releasePage(apOld[i]);
4771 apOld[i] = 0;
4772 i++;
4773 }
4774
drh8b2f49b2001-06-08 00:21:52 +00004775 /*
drhf9ffac92002-03-02 19:00:31 +00004776 ** Put the new pages in accending order. This helps to
4777 ** keep entries in the disk file in order so that a scan
4778 ** of the table is a linear scan through the file. That
4779 ** in turn helps the operating system to deliver pages
4780 ** from the disk more rapidly.
4781 **
4782 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00004783 ** n is never more than NB (a small constant), that should
4784 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00004785 **
drhc3b70572003-01-04 19:44:07 +00004786 ** When NB==3, this one optimization makes the database
4787 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00004788 */
4789 for(i=0; i<k-1; i++){
4790 int minV = pgnoNew[i];
4791 int minI = i;
4792 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00004793 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00004794 minI = j;
4795 minV = pgnoNew[j];
4796 }
4797 }
4798 if( minI>i ){
4799 int t;
4800 MemPage *pT;
4801 t = pgnoNew[i];
4802 pT = apNew[i];
4803 pgnoNew[i] = pgnoNew[minI];
4804 apNew[i] = apNew[minI];
4805 pgnoNew[minI] = t;
4806 apNew[minI] = pT;
4807 }
4808 }
drha2fce642004-06-05 00:01:44 +00004809 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00004810 pgnoOld[0],
4811 nOld>=2 ? pgnoOld[1] : 0,
4812 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00004813 pgnoNew[0], szNew[0],
4814 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
4815 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00004816 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
4817 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00004818
drhf9ffac92002-03-02 19:00:31 +00004819 /*
drh14acc042001-06-10 19:56:58 +00004820 ** Evenly distribute the data in apCell[] across the new pages.
4821 ** Insert divider cells into pParent as necessary.
4822 */
4823 j = 0;
4824 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00004825 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00004826 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00004827 assert( j<nMaxCells );
drh4b70f112004-05-02 21:12:19 +00004828 assert( pNew->pgno==pgnoNew[i] );
drhfa1a98a2004-05-14 19:08:17 +00004829 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00004830 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00004831 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00004832
4833#ifndef SQLITE_OMIT_AUTOVACUUM
4834 /* If this is an auto-vacuum database, update the pointer map entries
4835 ** that point to the siblings that were rearranged. These can be: left
4836 ** children of cells, the right-child of the page, or overflow pages
4837 ** pointed to by cells.
4838 */
4839 if( pBt->autoVacuum ){
4840 for(k=j; k<cntNew[i]; k++){
danielk1977634f2982005-03-28 08:44:07 +00004841 assert( k<nMaxCells );
danielk1977ac11ee62005-01-15 12:45:51 +00004842 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
danielk197779a40da2005-01-16 08:00:01 +00004843 rc = ptrmapPutOvfl(pNew, k-j);
4844 if( rc!=SQLITE_OK ){
4845 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00004846 }
4847 }
4848 }
4849 }
4850#endif
4851
4852 j = cntNew[i];
4853
4854 /* If the sibling page assembled above was not the right-most sibling,
4855 ** insert a divider cell into the parent page.
4856 */
drh14acc042001-06-10 19:56:58 +00004857 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00004858 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00004859 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00004860 int sz;
danielk1977634f2982005-03-28 08:44:07 +00004861
4862 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00004863 pCell = apCell[j];
4864 sz = szCell[j] + leafCorrection;
drh4b70f112004-05-02 21:12:19 +00004865 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00004866 memcpy(&pNew->aData[8], pCell, 4);
drh24cd67e2004-05-10 16:18:47 +00004867 pTemp = 0;
drh8b18dd42004-05-12 19:18:15 +00004868 }else if( leafData ){
danielk1977ac11ee62005-01-15 12:45:51 +00004869 /* If the tree is a leaf-data tree, and the siblings are leaves,
4870 ** then there is no divider cell in apCell[]. Instead, the divider
4871 ** cell consists of the integer key for the right-most cell of
4872 ** the sibling-page assembled above only.
4873 */
drh6f11bef2004-05-13 01:12:56 +00004874 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00004875 j--;
drh43605152004-05-29 21:46:49 +00004876 parseCellPtr(pNew, apCell[j], &info);
drhb6f41482004-05-14 01:58:11 +00004877 pCell = &aSpace[iSpace];
drh6f11bef2004-05-13 01:12:56 +00004878 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, &sz);
drhb6f41482004-05-14 01:58:11 +00004879 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004880 assert( iSpace<=pBt->pageSize*5 );
drh8b18dd42004-05-12 19:18:15 +00004881 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00004882 }else{
4883 pCell -= 4;
drhb6f41482004-05-14 01:58:11 +00004884 pTemp = &aSpace[iSpace];
4885 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004886 assert( iSpace<=pBt->pageSize*5 );
drh4b70f112004-05-02 21:12:19 +00004887 }
danielk1977a3ad5e72005-01-07 08:56:44 +00004888 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00004889 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh43605152004-05-29 21:46:49 +00004890 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +00004891#ifndef SQLITE_OMIT_AUTOVACUUM
4892 /* If this is an auto-vacuum database, and not a leaf-data tree,
4893 ** then update the pointer map with an entry for the overflow page
4894 ** that the cell just inserted points to (if any).
4895 */
4896 if( pBt->autoVacuum && !leafData ){
danielk197779a40da2005-01-16 08:00:01 +00004897 rc = ptrmapPutOvfl(pParent, nxDiv);
4898 if( rc!=SQLITE_OK ){
4899 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00004900 }
4901 }
4902#endif
drh14acc042001-06-10 19:56:58 +00004903 j++;
4904 nxDiv++;
4905 }
4906 }
drh6019e162001-07-02 17:51:45 +00004907 assert( j==nCell );
drh4b70f112004-05-02 21:12:19 +00004908 if( (pageFlags & PTF_LEAF)==0 ){
drh43605152004-05-29 21:46:49 +00004909 memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
drh14acc042001-06-10 19:56:58 +00004910 }
drh43605152004-05-29 21:46:49 +00004911 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00004912 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00004913 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00004914 }else{
4915 /* Right-most sibling is the left child of the first entry in pParent
4916 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00004917 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00004918 }
4919
4920 /*
4921 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00004922 */
4923 for(i=0; i<nNew; i++){
danielk1977afcdd022004-10-31 16:25:42 +00004924 rc = reparentChildPages(apNew[i]);
4925 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004926 }
danielk1977afcdd022004-10-31 16:25:42 +00004927 rc = reparentChildPages(pParent);
4928 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004929
4930 /*
drh3a4c1412004-05-09 20:40:11 +00004931 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00004932 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00004933 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00004934 */
drhda200cc2004-05-09 11:51:38 +00004935 assert( pParent->isInit );
drh3a4c1412004-05-09 20:40:11 +00004936 /* assert( pPage->isInit ); // No! pPage might have been added to freelist */
4937 /* pageIntegrity(pPage); // No! pPage might have been added to freelist */
danielk1977ac245ec2005-01-14 13:50:11 +00004938 rc = balance(pParent, 0);
drhda200cc2004-05-09 11:51:38 +00004939
drh8b2f49b2001-06-08 00:21:52 +00004940 /*
drh14acc042001-06-10 19:56:58 +00004941 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00004942 */
drh14acc042001-06-10 19:56:58 +00004943balance_cleanup:
drh2e38c322004-09-03 18:38:44 +00004944 sqliteFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00004945 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00004946 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00004947 }
drh14acc042001-06-10 19:56:58 +00004948 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00004949 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00004950 }
drh91025292004-05-03 19:49:32 +00004951 releasePage(pParent);
drh3a4c1412004-05-09 20:40:11 +00004952 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
4953 pPage->pgno, nOld, nNew, nCell));
drh8b2f49b2001-06-08 00:21:52 +00004954 return rc;
4955}
4956
4957/*
drh43605152004-05-29 21:46:49 +00004958** This routine is called for the root page of a btree when the root
4959** page contains no cells. This is an opportunity to make the tree
4960** shallower by one level.
4961*/
4962static int balance_shallower(MemPage *pPage){
4963 MemPage *pChild; /* The only child page of pPage */
4964 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00004965 int rc = SQLITE_OK; /* Return code from subprocedures */
danielk1977aef0bf62005-12-30 16:28:01 +00004966 BtShared *pBt; /* The main BTree structure */
drh2e38c322004-09-03 18:38:44 +00004967 int mxCellPerPage; /* Maximum number of cells per page */
4968 u8 **apCell; /* All cells from pages being balanced */
4969 int *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00004970
4971 assert( pPage->pParent==0 );
4972 assert( pPage->nCell==0 );
drh2e38c322004-09-03 18:38:44 +00004973 pBt = pPage->pBt;
4974 mxCellPerPage = MX_CELL(pBt);
4975 apCell = sqliteMallocRaw( mxCellPerPage*(sizeof(u8*)+sizeof(int)) );
4976 if( apCell==0 ) return SQLITE_NOMEM;
4977 szCell = (int*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00004978 if( pPage->leaf ){
4979 /* The table is completely empty */
4980 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
4981 }else{
4982 /* The root page is empty but has one child. Transfer the
4983 ** information from that one child into the root page if it
4984 ** will fit. This reduces the depth of the tree by one.
4985 **
4986 ** If the root page is page 1, it has less space available than
4987 ** its child (due to the 100 byte header that occurs at the beginning
4988 ** of the database fle), so it might not be able to hold all of the
4989 ** information currently contained in the child. If this is the
4990 ** case, then do not do the transfer. Leave page 1 empty except
4991 ** for the right-pointer to the child page. The child page becomes
4992 ** the virtual root of the tree.
4993 */
4994 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
4995 assert( pgnoChild>0 );
4996 assert( pgnoChild<=sqlite3pager_pagecount(pPage->pBt->pPager) );
4997 rc = getPage(pPage->pBt, pgnoChild, &pChild);
drh2e38c322004-09-03 18:38:44 +00004998 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004999 if( pPage->pgno==1 ){
5000 rc = initPage(pChild, pPage);
drh2e38c322004-09-03 18:38:44 +00005001 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005002 assert( pChild->nOverflow==0 );
5003 if( pChild->nFree>=100 ){
5004 /* The child information will fit on the root page, so do the
5005 ** copy */
5006 int i;
5007 zeroPage(pPage, pChild->aData[0]);
5008 for(i=0; i<pChild->nCell; i++){
5009 apCell[i] = findCell(pChild,i);
5010 szCell[i] = cellSizePtr(pChild, apCell[i]);
5011 }
5012 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00005013 /* Copy the right-pointer of the child to the parent. */
5014 put4byte(&pPage->aData[pPage->hdrOffset+8],
5015 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh43605152004-05-29 21:46:49 +00005016 freePage(pChild);
5017 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
5018 }else{
5019 /* The child has more information that will fit on the root.
5020 ** The tree is already balanced. Do nothing. */
5021 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
5022 }
5023 }else{
5024 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
5025 pPage->isInit = 0;
5026 pPage->pParent = 0;
5027 rc = initPage(pPage, 0);
5028 assert( rc==SQLITE_OK );
5029 freePage(pChild);
5030 TRACE(("BALANCE: transfer child %d into root %d\n",
5031 pChild->pgno, pPage->pgno));
5032 }
danielk1977afcdd022004-10-31 16:25:42 +00005033 rc = reparentChildPages(pPage);
danielk1977ac11ee62005-01-15 12:45:51 +00005034 assert( pPage->nOverflow==0 );
5035#ifndef SQLITE_OMIT_AUTOVACUUM
5036 if( pBt->autoVacuum ){
danielk1977aac0a382005-01-16 11:07:06 +00005037 int i;
danielk1977ac11ee62005-01-15 12:45:51 +00005038 for(i=0; i<pPage->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00005039 rc = ptrmapPutOvfl(pPage, i);
5040 if( rc!=SQLITE_OK ){
5041 goto end_shallow_balance;
danielk1977ac11ee62005-01-15 12:45:51 +00005042 }
5043 }
5044 }
5045#endif
danielk1977afcdd022004-10-31 16:25:42 +00005046 if( rc!=SQLITE_OK ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005047 releasePage(pChild);
5048 }
drh2e38c322004-09-03 18:38:44 +00005049end_shallow_balance:
5050 sqliteFree(apCell);
5051 return rc;
drh43605152004-05-29 21:46:49 +00005052}
5053
5054
5055/*
5056** The root page is overfull
5057**
5058** When this happens, Create a new child page and copy the
5059** contents of the root into the child. Then make the root
5060** page an empty page with rightChild pointing to the new
5061** child. Finally, call balance_internal() on the new child
5062** to cause it to split.
5063*/
5064static int balance_deeper(MemPage *pPage){
5065 int rc; /* Return value from subprocedures */
5066 MemPage *pChild; /* Pointer to a new child page */
5067 Pgno pgnoChild; /* Page number of the new child page */
danielk1977aef0bf62005-12-30 16:28:01 +00005068 BtShared *pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00005069 int usableSize; /* Total usable size of a page */
5070 u8 *data; /* Content of the parent page */
5071 u8 *cdata; /* Content of the child page */
5072 int hdr; /* Offset to page header in parent */
5073 int brk; /* Offset to content of first cell in parent */
5074
5075 assert( pPage->pParent==0 );
5076 assert( pPage->nOverflow>0 );
5077 pBt = pPage->pBt;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005078 rc = allocatePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00005079 if( rc ) return rc;
5080 assert( sqlite3pager_iswriteable(pChild->aData) );
5081 usableSize = pBt->usableSize;
5082 data = pPage->aData;
5083 hdr = pPage->hdrOffset;
5084 brk = get2byte(&data[hdr+5]);
5085 cdata = pChild->aData;
5086 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
5087 memcpy(&cdata[brk], &data[brk], usableSize-brk);
danielk1977c7dc7532004-11-17 10:22:03 +00005088 assert( pChild->isInit==0 );
drh43605152004-05-29 21:46:49 +00005089 rc = initPage(pChild, pPage);
danielk19776b456a22005-03-21 04:04:02 +00005090 if( rc ) goto balancedeeper_out;
drh43605152004-05-29 21:46:49 +00005091 memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
5092 pChild->nOverflow = pPage->nOverflow;
5093 if( pChild->nOverflow ){
5094 pChild->nFree = 0;
5095 }
5096 assert( pChild->nCell==pPage->nCell );
5097 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
5098 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
5099 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
danielk19774e17d142005-01-16 09:06:33 +00005100#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00005101 if( pBt->autoVacuum ){
5102 int i;
5103 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
danielk19776b456a22005-03-21 04:04:02 +00005104 if( rc ) goto balancedeeper_out;
danielk1977ac11ee62005-01-15 12:45:51 +00005105 for(i=0; i<pChild->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00005106 rc = ptrmapPutOvfl(pChild, i);
5107 if( rc!=SQLITE_OK ){
5108 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00005109 }
5110 }
5111 }
danielk19774e17d142005-01-16 09:06:33 +00005112#endif
drh43605152004-05-29 21:46:49 +00005113 rc = balance_nonroot(pChild);
danielk19776b456a22005-03-21 04:04:02 +00005114
5115balancedeeper_out:
drh43605152004-05-29 21:46:49 +00005116 releasePage(pChild);
5117 return rc;
5118}
5119
5120/*
5121** Decide if the page pPage needs to be balanced. If balancing is
5122** required, call the appropriate balancing routine.
5123*/
danielk1977ac245ec2005-01-14 13:50:11 +00005124static int balance(MemPage *pPage, int insert){
drh43605152004-05-29 21:46:49 +00005125 int rc = SQLITE_OK;
5126 if( pPage->pParent==0 ){
5127 if( pPage->nOverflow>0 ){
5128 rc = balance_deeper(pPage);
5129 }
danielk1977687566d2004-11-02 12:56:41 +00005130 if( rc==SQLITE_OK && pPage->nCell==0 ){
drh43605152004-05-29 21:46:49 +00005131 rc = balance_shallower(pPage);
5132 }
5133 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00005134 if( pPage->nOverflow>0 ||
5135 (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
drh43605152004-05-29 21:46:49 +00005136 rc = balance_nonroot(pPage);
5137 }
5138 }
5139 return rc;
5140}
5141
5142/*
drh8dcd7ca2004-08-08 19:43:29 +00005143** This routine checks all cursors that point to table pgnoRoot.
5144** If any of those cursors other than pExclude were opened with
drhf74b8d92002-09-01 23:20:45 +00005145** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
drh8dcd7ca2004-08-08 19:43:29 +00005146** cursors that point to pgnoRoot were opened with wrFlag==1
drhf74b8d92002-09-01 23:20:45 +00005147** then this routine returns SQLITE_OK.
danielk1977299b1872004-11-22 10:02:10 +00005148**
5149** In addition to checking for read-locks (where a read-lock
5150** means a cursor opened with wrFlag==0) this routine also moves
5151** all cursors other than pExclude so that they are pointing to the
5152** first Cell on root page. This is necessary because an insert
5153** or delete might change the number of cells on a page or delete
5154** a page entirely and we do not want to leave any cursors
5155** pointing to non-existant pages or cells.
drhf74b8d92002-09-01 23:20:45 +00005156*/
danielk1977aef0bf62005-12-30 16:28:01 +00005157static int checkReadLocks(BtShared *pBt, Pgno pgnoRoot, BtCursor *pExclude){
danielk1977299b1872004-11-22 10:02:10 +00005158 BtCursor *p;
5159 for(p=pBt->pCursor; p; p=p->pNext){
danielk1977da184232006-01-05 11:34:32 +00005160 u32 flags = (p->pBtree->pSqlite ? p->pBtree->pSqlite->flags : 0);
danielk1977299b1872004-11-22 10:02:10 +00005161 if( p->pgnoRoot!=pgnoRoot || p==pExclude ) continue;
danielk1977da184232006-01-05 11:34:32 +00005162 if( p->wrFlag==0 && flags&SQLITE_ReadUncommitted ) continue;
danielk1977299b1872004-11-22 10:02:10 +00005163 if( p->wrFlag==0 ) return SQLITE_LOCKED;
5164 if( p->pPage->pgno!=p->pgnoRoot ){
5165 moveToRoot(p);
5166 }
5167 }
drhf74b8d92002-09-01 23:20:45 +00005168 return SQLITE_OK;
5169}
5170
5171/*
drh3b7511c2001-05-26 13:15:44 +00005172** Insert a new record into the BTree. The key is given by (pKey,nKey)
5173** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00005174** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00005175** is left pointing at a random location.
5176**
5177** For an INTKEY table, only the nKey value of the key is used. pKey is
5178** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00005179*/
drh3aac2dd2004-04-26 14:10:20 +00005180int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00005181 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00005182 const void *pKey, i64 nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00005183 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00005184){
drh3b7511c2001-05-26 13:15:44 +00005185 int rc;
5186 int loc;
drh14acc042001-06-10 19:56:58 +00005187 int szNew;
drh3b7511c2001-05-26 13:15:44 +00005188 MemPage *pPage;
danielk1977aef0bf62005-12-30 16:28:01 +00005189 BtShared *pBt = pCur->pBtree->pBt;
drha34b6762004-05-07 13:30:42 +00005190 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00005191 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00005192
danielk1977aef0bf62005-12-30 16:28:01 +00005193 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005194 /* Must start a transaction before doing an insert */
5195 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005196 }
drhf74b8d92002-09-01 23:20:45 +00005197 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00005198 if( !pCur->wrFlag ){
5199 return SQLITE_PERM; /* Cursor not open for writing */
5200 }
drh8dcd7ca2004-08-08 19:43:29 +00005201 if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00005202 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5203 }
danielk1977da184232006-01-05 11:34:32 +00005204
5205 /* Save the positions of any other cursors open on this table */
drh777e4c42006-01-13 04:31:58 +00005206 restoreOrClearCursorPosition(pCur, 0);
danielk19772e94d4d2006-01-09 05:36:27 +00005207 if(
danielk19772e94d4d2006-01-09 05:36:27 +00005208 SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
5209 SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, &loc))
5210 ){
danielk1977da184232006-01-05 11:34:32 +00005211 return rc;
5212 }
5213
drh14acc042001-06-10 19:56:58 +00005214 pPage = pCur->pPage;
drh4a1c3802004-05-12 15:15:47 +00005215 assert( pPage->intKey || nKey>=0 );
drh8b18dd42004-05-12 19:18:15 +00005216 assert( pPage->leaf || !pPage->leafData );
drh3a4c1412004-05-09 20:40:11 +00005217 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
5218 pCur->pgnoRoot, nKey, nData, pPage->pgno,
5219 loc==0 ? "overwrite" : "new entry"));
drh7aa128d2002-06-21 13:09:16 +00005220 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00005221 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00005222 if( rc ) return rc;
drh2e38c322004-09-03 18:38:44 +00005223 newCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
5224 if( newCell==0 ) return SQLITE_NOMEM;
drha34b6762004-05-07 13:30:42 +00005225 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, &szNew);
drh2e38c322004-09-03 18:38:44 +00005226 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00005227 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00005228 assert( szNew<=MX_CELL_SIZE(pBt) );
danielk1977da184232006-01-05 11:34:32 +00005229 if( loc==0 && CURSOR_VALID==pCur->eState ){
drha34b6762004-05-07 13:30:42 +00005230 int szOld;
5231 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00005232 oldCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005233 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005234 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00005235 }
drh43605152004-05-29 21:46:49 +00005236 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00005237 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00005238 if( rc ) goto end_insert;
drh4b70f112004-05-02 21:12:19 +00005239 dropCell(pPage, pCur->idx, szOld);
drh7c717f72001-06-24 20:39:41 +00005240 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00005241 assert( pPage->leaf );
drh14acc042001-06-10 19:56:58 +00005242 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00005243 pCur->info.nSize = 0;
drh14acc042001-06-10 19:56:58 +00005244 }else{
drh4b70f112004-05-02 21:12:19 +00005245 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00005246 }
danielk1977a3ad5e72005-01-07 08:56:44 +00005247 rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
danielk1977e80463b2004-11-03 03:01:16 +00005248 if( rc!=SQLITE_OK ) goto end_insert;
danielk1977ac245ec2005-01-14 13:50:11 +00005249 rc = balance(pPage, 1);
drh23e11ca2004-05-04 17:27:28 +00005250 /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
drh3fc190c2001-09-14 03:24:23 +00005251 /* fflush(stdout); */
danielk1977299b1872004-11-22 10:02:10 +00005252 if( rc==SQLITE_OK ){
5253 moveToRoot(pCur);
5254 }
drh2e38c322004-09-03 18:38:44 +00005255end_insert:
5256 sqliteFree(newCell);
drh5e2f8b92001-05-28 00:41:15 +00005257 return rc;
5258}
5259
5260/*
drh4b70f112004-05-02 21:12:19 +00005261** Delete the entry that the cursor is pointing to. The cursor
5262** is left pointing at a random location.
drh3b7511c2001-05-26 13:15:44 +00005263*/
drh3aac2dd2004-04-26 14:10:20 +00005264int sqlite3BtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00005265 MemPage *pPage = pCur->pPage;
drh4b70f112004-05-02 21:12:19 +00005266 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00005267 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00005268 Pgno pgnoChild = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00005269 BtShared *pBt = pCur->pBtree->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005270
drh7aa128d2002-06-21 13:09:16 +00005271 assert( pPage->isInit );
danielk1977aef0bf62005-12-30 16:28:01 +00005272 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005273 /* Must start a transaction before doing a delete */
5274 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005275 }
drhf74b8d92002-09-01 23:20:45 +00005276 assert( !pBt->readOnly );
drhbd03cae2001-06-02 02:40:57 +00005277 if( pCur->idx >= pPage->nCell ){
5278 return SQLITE_ERROR; /* The cursor is not pointing to anything */
5279 }
drhecdc7532001-09-23 02:35:53 +00005280 if( !pCur->wrFlag ){
5281 return SQLITE_PERM; /* Did not open this cursor for writing */
5282 }
drh8dcd7ca2004-08-08 19:43:29 +00005283 if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00005284 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5285 }
danielk1977da184232006-01-05 11:34:32 +00005286
5287 /* Restore the current cursor position (a no-op if the cursor is not in
5288 ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
5289 ** open on the same table. Then call sqlite3pager_write() on the page
5290 ** that the entry will be deleted from.
5291 */
5292 if(
drhd1167392006-01-23 13:00:35 +00005293 (rc = restoreOrClearCursorPosition(pCur, 1))!=0 ||
5294 (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
5295 (rc = sqlite3pager_write(pPage->aData))!=0
danielk1977da184232006-01-05 11:34:32 +00005296 ){
5297 return rc;
5298 }
danielk1977e6efa742004-11-10 11:55:10 +00005299
5300 /* Locate the cell within it's page and leave pCell pointing to the
5301 ** data. The clearCell() call frees any overflow pages associated with the
5302 ** cell. The cell itself is still intact.
5303 */
danielk1977299b1872004-11-22 10:02:10 +00005304 pCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005305 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005306 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005307 }
danielk197728129562005-01-11 10:25:06 +00005308 rc = clearCell(pPage, pCell);
5309 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00005310
drh4b70f112004-05-02 21:12:19 +00005311 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00005312 /*
drh5e00f6c2001-09-13 13:46:56 +00005313 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00005314 ** do something we will leave a hole on an internal page.
5315 ** We have to fill the hole by moving in a cell from a leaf. The
5316 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00005317 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00005318 */
drh14acc042001-06-10 19:56:58 +00005319 BtCursor leafCur;
drh4b70f112004-05-02 21:12:19 +00005320 unsigned char *pNext;
drh02afc862006-01-20 18:10:57 +00005321 int szNext; /* The compiler warning is wrong: szNext is always
5322 ** initialized before use. Adding an extra initialization
5323 ** to silence the compiler slows down the code. */
danielk1977299b1872004-11-22 10:02:10 +00005324 int notUsed;
danielk19776b456a22005-03-21 04:04:02 +00005325 unsigned char *tempCell = 0;
drh8b18dd42004-05-12 19:18:15 +00005326 assert( !pPage->leafData );
drh14acc042001-06-10 19:56:58 +00005327 getTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00005328 rc = sqlite3BtreeNext(&leafCur, &notUsed);
drh14acc042001-06-10 19:56:58 +00005329 if( rc!=SQLITE_OK ){
drhee696e22004-08-30 16:52:17 +00005330 if( rc!=SQLITE_NOMEM ){
drh49285702005-09-17 15:20:26 +00005331 rc = SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00005332 }
drh5e2f8b92001-05-28 00:41:15 +00005333 }
danielk19776b456a22005-03-21 04:04:02 +00005334 if( rc==SQLITE_OK ){
5335 rc = sqlite3pager_write(leafCur.pPage->aData);
5336 }
5337 if( rc==SQLITE_OK ){
5338 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
5339 pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
5340 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
5341 pNext = findCell(leafCur.pPage, leafCur.idx);
5342 szNext = cellSizePtr(leafCur.pPage, pNext);
5343 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
5344 tempCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
5345 if( tempCell==0 ){
5346 rc = SQLITE_NOMEM;
5347 }
5348 }
5349 if( rc==SQLITE_OK ){
5350 rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
5351 }
5352 if( rc==SQLITE_OK ){
5353 put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
5354 rc = balance(pPage, 0);
5355 }
5356 if( rc==SQLITE_OK ){
5357 dropCell(leafCur.pPage, leafCur.idx, szNext);
5358 rc = balance(leafCur.pPage, 0);
5359 }
drh2e38c322004-09-03 18:38:44 +00005360 sqliteFree(tempCell);
drh8c42ca92001-06-22 19:15:00 +00005361 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00005362 }else{
danielk1977299b1872004-11-22 10:02:10 +00005363 TRACE(("DELETE: table=%d delete from leaf %d\n",
5364 pCur->pgnoRoot, pPage->pgno));
5365 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
danielk1977ac245ec2005-01-14 13:50:11 +00005366 rc = balance(pPage, 0);
drh5e2f8b92001-05-28 00:41:15 +00005367 }
danielk19776b456a22005-03-21 04:04:02 +00005368 if( rc==SQLITE_OK ){
5369 moveToRoot(pCur);
5370 }
drh5e2f8b92001-05-28 00:41:15 +00005371 return rc;
drh3b7511c2001-05-26 13:15:44 +00005372}
drh8b2f49b2001-06-08 00:21:52 +00005373
5374/*
drhc6b52df2002-01-04 03:09:29 +00005375** Create a new BTree table. Write into *piTable the page
5376** number for the root page of the new table.
5377**
drhab01f612004-05-22 02:55:23 +00005378** The type of type is determined by the flags parameter. Only the
5379** following values of flags are currently in use. Other values for
5380** flags might not work:
5381**
5382** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
5383** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00005384*/
danielk1977aef0bf62005-12-30 16:28:01 +00005385int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
5386 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005387 MemPage *pRoot;
5388 Pgno pgnoRoot;
5389 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00005390 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005391 /* Must start a transaction first */
5392 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005393 }
danielk197728129562005-01-11 10:25:06 +00005394 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00005395
5396 /* It is illegal to create a table if any cursors are open on the
5397 ** database. This is because in auto-vacuum mode the backend may
5398 ** need to move a database page to make room for the new root-page.
5399 ** If an open cursor was using the page a problem would occur.
5400 */
5401 if( pBt->pCursor ){
5402 return SQLITE_LOCKED;
5403 }
5404
danielk1977003ba062004-11-04 02:57:33 +00005405#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977cb1a7eb2004-11-05 12:27:02 +00005406 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drh8b2f49b2001-06-08 00:21:52 +00005407 if( rc ) return rc;
danielk1977003ba062004-11-04 02:57:33 +00005408#else
danielk1977687566d2004-11-02 12:56:41 +00005409 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00005410 Pgno pgnoMove; /* Move a page here to make room for the root-page */
5411 MemPage *pPageMove; /* The page to move to. */
5412
danielk1977003ba062004-11-04 02:57:33 +00005413 /* Read the value of meta[3] from the database to determine where the
5414 ** root page of the new table should go. meta[3] is the largest root-page
5415 ** created so far, so the new root-page is (meta[3]+1).
5416 */
danielk1977aef0bf62005-12-30 16:28:01 +00005417 rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00005418 if( rc!=SQLITE_OK ) return rc;
5419 pgnoRoot++;
5420
danielk1977599fcba2004-11-08 07:13:13 +00005421 /* The new root-page may not be allocated on a pointer-map page, or the
5422 ** PENDING_BYTE page.
5423 */
drh42cac6d2004-11-20 20:31:11 +00005424 if( pgnoRoot==PTRMAP_PAGENO(pBt->usableSize, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00005425 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00005426 pgnoRoot++;
5427 }
5428 assert( pgnoRoot>=3 );
5429
5430 /* Allocate a page. The page that currently resides at pgnoRoot will
5431 ** be moved to the allocated page (unless the allocated page happens
5432 ** to reside at pgnoRoot).
5433 */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005434 rc = allocatePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00005435 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00005436 return rc;
5437 }
danielk1977003ba062004-11-04 02:57:33 +00005438
5439 if( pgnoMove!=pgnoRoot ){
5440 u8 eType;
5441 Pgno iPtrPage;
5442
5443 releasePage(pPageMove);
5444 rc = getPage(pBt, pgnoRoot, &pRoot);
5445 if( rc!=SQLITE_OK ){
5446 return rc;
5447 }
5448 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drhccae6022005-02-26 17:31:26 +00005449 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00005450 releasePage(pRoot);
5451 return rc;
5452 }
drhccae6022005-02-26 17:31:26 +00005453 assert( eType!=PTRMAP_ROOTPAGE );
5454 assert( eType!=PTRMAP_FREEPAGE );
danielk19775fd057a2005-03-09 13:09:43 +00005455 rc = sqlite3pager_write(pRoot->aData);
5456 if( rc!=SQLITE_OK ){
5457 releasePage(pRoot);
5458 return rc;
5459 }
danielk1977003ba062004-11-04 02:57:33 +00005460 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove);
5461 releasePage(pRoot);
5462 if( rc!=SQLITE_OK ){
5463 return rc;
5464 }
5465 rc = getPage(pBt, pgnoRoot, &pRoot);
5466 if( rc!=SQLITE_OK ){
5467 return rc;
5468 }
5469 rc = sqlite3pager_write(pRoot->aData);
5470 if( rc!=SQLITE_OK ){
5471 releasePage(pRoot);
5472 return rc;
5473 }
5474 }else{
5475 pRoot = pPageMove;
5476 }
5477
danielk197742741be2005-01-08 12:42:39 +00005478 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00005479 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
5480 if( rc ){
5481 releasePage(pRoot);
5482 return rc;
5483 }
danielk1977aef0bf62005-12-30 16:28:01 +00005484 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00005485 if( rc ){
5486 releasePage(pRoot);
5487 return rc;
5488 }
danielk197742741be2005-01-08 12:42:39 +00005489
danielk1977003ba062004-11-04 02:57:33 +00005490 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00005491 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00005492 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00005493 }
5494#endif
drha34b6762004-05-07 13:30:42 +00005495 assert( sqlite3pager_iswriteable(pRoot->aData) );
drhde647132004-05-07 17:57:49 +00005496 zeroPage(pRoot, flags | PTF_LEAF);
drha34b6762004-05-07 13:30:42 +00005497 sqlite3pager_unref(pRoot->aData);
drh8b2f49b2001-06-08 00:21:52 +00005498 *piTable = (int)pgnoRoot;
5499 return SQLITE_OK;
5500}
5501
5502/*
5503** Erase the given database page and all its children. Return
5504** the page to the freelist.
5505*/
drh4b70f112004-05-02 21:12:19 +00005506static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00005507 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00005508 Pgno pgno, /* Page number to clear */
5509 MemPage *pParent, /* Parent page. NULL for the root */
5510 int freePageFlag /* Deallocate page if true */
5511){
danielk19776b456a22005-03-21 04:04:02 +00005512 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00005513 int rc;
drh4b70f112004-05-02 21:12:19 +00005514 unsigned char *pCell;
5515 int i;
drh8b2f49b2001-06-08 00:21:52 +00005516
danielk1977a1cb1832005-02-12 08:59:55 +00005517 if( pgno>sqlite3pager_pagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00005518 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00005519 }
5520
drhde647132004-05-07 17:57:49 +00005521 rc = getAndInitPage(pBt, pgno, &pPage, pParent);
danielk19776b456a22005-03-21 04:04:02 +00005522 if( rc ) goto cleardatabasepage_out;
drha34b6762004-05-07 13:30:42 +00005523 rc = sqlite3pager_write(pPage->aData);
danielk19776b456a22005-03-21 04:04:02 +00005524 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00005525 for(i=0; i<pPage->nCell; i++){
drh43605152004-05-29 21:46:49 +00005526 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00005527 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005528 rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00005529 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00005530 }
drh4b70f112004-05-02 21:12:19 +00005531 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00005532 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00005533 }
drha34b6762004-05-07 13:30:42 +00005534 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005535 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00005536 if( rc ) goto cleardatabasepage_out;
drh2aa679f2001-06-25 02:11:07 +00005537 }
5538 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00005539 rc = freePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00005540 }else{
drh3a4c1412004-05-09 20:40:11 +00005541 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00005542 }
danielk19776b456a22005-03-21 04:04:02 +00005543
5544cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00005545 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00005546 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005547}
5548
5549/*
drhab01f612004-05-22 02:55:23 +00005550** Delete all information from a single table in the database. iTable is
5551** the page number of the root of the table. After this routine returns,
5552** the root page is empty, but still exists.
5553**
5554** This routine will fail with SQLITE_LOCKED if there are any open
5555** read cursors on the table. Open write cursors are moved to the
5556** root of the table.
drh8b2f49b2001-06-08 00:21:52 +00005557*/
danielk1977aef0bf62005-12-30 16:28:01 +00005558int sqlite3BtreeClearTable(Btree *p, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00005559 int rc;
drhf74b8d92002-09-01 23:20:45 +00005560 BtCursor *pCur;
danielk1977aef0bf62005-12-30 16:28:01 +00005561 BtShared *pBt = p->pBt;
danielk1977ed429312006-01-19 08:43:31 +00005562 sqlite3 *db = p->pSqlite;
danielk1977aef0bf62005-12-30 16:28:01 +00005563 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005564 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005565 }
danielk1977ed429312006-01-19 08:43:31 +00005566
5567 /* If this connection is not in read-uncommitted mode and currently has
5568 ** a read-cursor open on the table being cleared, return SQLITE_LOCKED.
5569 */
5570 if( 0==db || 0==(db->flags&SQLITE_ReadUncommitted) ){
5571 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
5572 if( pCur->pBtree==p && pCur->pgnoRoot==(Pgno)iTable ){
5573 if( 0==pCur->wrFlag ){
5574 return SQLITE_LOCKED;
5575 }
5576 moveToRoot(pCur);
5577 }
drhf74b8d92002-09-01 23:20:45 +00005578 }
drhecdc7532001-09-23 02:35:53 +00005579 }
danielk1977ed429312006-01-19 08:43:31 +00005580
5581 /* Save the position of all cursors open on this table */
5582 if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
5583 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005584 }
danielk1977ed429312006-01-19 08:43:31 +00005585
5586 return clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
drh8b2f49b2001-06-08 00:21:52 +00005587}
5588
5589/*
5590** Erase all information in a table and add the root of the table to
5591** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00005592** page 1) is never added to the freelist.
5593**
5594** This routine will fail with SQLITE_LOCKED if there are any open
5595** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00005596**
5597** If AUTOVACUUM is enabled and the page at iTable is not the last
5598** root page in the database file, then the last root page
5599** in the database file is moved into the slot formerly occupied by
5600** iTable and that last slot formerly occupied by the last root page
5601** is added to the freelist instead of iTable. In this say, all
5602** root pages are kept at the beginning of the database file, which
5603** is necessary for AUTOVACUUM to work right. *piMoved is set to the
5604** page number that used to be the last root page in the file before
5605** the move. If no page gets moved, *piMoved is set to 0.
5606** The last root page is recorded in meta[3] and the value of
5607** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00005608*/
danielk1977aef0bf62005-12-30 16:28:01 +00005609int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00005610 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00005611 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00005612 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00005613
danielk1977aef0bf62005-12-30 16:28:01 +00005614 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005615 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005616 }
danielk1977a0bf2652004-11-04 14:30:04 +00005617
danielk1977e6efa742004-11-10 11:55:10 +00005618 /* It is illegal to drop a table if any cursors are open on the
5619 ** database. This is because in auto-vacuum mode the backend may
5620 ** need to move another root-page to fill a gap left by the deleted
5621 ** root page. If an open cursor was using this page a problem would
5622 ** occur.
5623 */
5624 if( pBt->pCursor ){
5625 return SQLITE_LOCKED;
drh5df72a52002-06-06 23:16:05 +00005626 }
danielk1977a0bf2652004-11-04 14:30:04 +00005627
drha34b6762004-05-07 13:30:42 +00005628 rc = getPage(pBt, (Pgno)iTable, &pPage);
drh2aa679f2001-06-25 02:11:07 +00005629 if( rc ) return rc;
danielk1977aef0bf62005-12-30 16:28:01 +00005630 rc = sqlite3BtreeClearTable(p, iTable);
danielk19776b456a22005-03-21 04:04:02 +00005631 if( rc ){
5632 releasePage(pPage);
5633 return rc;
5634 }
danielk1977a0bf2652004-11-04 14:30:04 +00005635
drh205f48e2004-11-05 00:43:11 +00005636 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00005637
drh4b70f112004-05-02 21:12:19 +00005638 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00005639#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00005640 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00005641 releasePage(pPage);
5642#else
5643 if( pBt->autoVacuum ){
5644 Pgno maxRootPgno;
danielk1977aef0bf62005-12-30 16:28:01 +00005645 rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00005646 if( rc!=SQLITE_OK ){
5647 releasePage(pPage);
5648 return rc;
5649 }
5650
5651 if( iTable==maxRootPgno ){
5652 /* If the table being dropped is the table with the largest root-page
5653 ** number in the database, put the root page on the free list.
5654 */
5655 rc = freePage(pPage);
5656 releasePage(pPage);
5657 if( rc!=SQLITE_OK ){
5658 return rc;
5659 }
5660 }else{
5661 /* The table being dropped does not have the largest root-page
5662 ** number in the database. So move the page that does into the
5663 ** gap left by the deleted root-page.
5664 */
5665 MemPage *pMove;
5666 releasePage(pPage);
5667 rc = getPage(pBt, maxRootPgno, &pMove);
5668 if( rc!=SQLITE_OK ){
5669 return rc;
5670 }
5671 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable);
5672 releasePage(pMove);
5673 if( rc!=SQLITE_OK ){
5674 return rc;
5675 }
5676 rc = getPage(pBt, maxRootPgno, &pMove);
5677 if( rc!=SQLITE_OK ){
5678 return rc;
5679 }
5680 rc = freePage(pMove);
5681 releasePage(pMove);
5682 if( rc!=SQLITE_OK ){
5683 return rc;
5684 }
5685 *piMoved = maxRootPgno;
5686 }
5687
danielk1977599fcba2004-11-08 07:13:13 +00005688 /* Set the new 'max-root-page' value in the database header. This
5689 ** is the old value less one, less one more if that happens to
5690 ** be a root-page number, less one again if that is the
5691 ** PENDING_BYTE_PAGE.
5692 */
danielk197787a6e732004-11-05 12:58:25 +00005693 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00005694 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
5695 maxRootPgno--;
5696 }
drh42cac6d2004-11-20 20:31:11 +00005697 if( maxRootPgno==PTRMAP_PAGENO(pBt->usableSize, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00005698 maxRootPgno--;
5699 }
danielk1977599fcba2004-11-08 07:13:13 +00005700 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
5701
danielk1977aef0bf62005-12-30 16:28:01 +00005702 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00005703 }else{
5704 rc = freePage(pPage);
5705 releasePage(pPage);
5706 }
5707#endif
drh2aa679f2001-06-25 02:11:07 +00005708 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00005709 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00005710 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00005711 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00005712 }
drh8b2f49b2001-06-08 00:21:52 +00005713 return rc;
5714}
5715
drh001bbcb2003-03-19 03:14:00 +00005716
drh8b2f49b2001-06-08 00:21:52 +00005717/*
drh23e11ca2004-05-04 17:27:28 +00005718** Read the meta-information out of a database file. Meta[0]
5719** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00005720** through meta[15] are available for use by higher layers. Meta[0]
5721** is read-only, the others are read/write.
5722**
5723** The schema layer numbers meta values differently. At the schema
5724** layer (and the SetCookie and ReadCookie opcodes) the number of
5725** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00005726*/
danielk1977aef0bf62005-12-30 16:28:01 +00005727int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
drh8b2f49b2001-06-08 00:21:52 +00005728 int rc;
drh4b70f112004-05-02 21:12:19 +00005729 unsigned char *pP1;
danielk1977aef0bf62005-12-30 16:28:01 +00005730 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005731
danielk1977da184232006-01-05 11:34:32 +00005732 /* Reading a meta-data value requires a read-lock on page 1 (and hence
5733 ** the sqlite_master table. We grab this lock regardless of whether or
5734 ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
5735 ** 1 is treated as a special case by queryTableLock() and lockTable()).
5736 */
5737 rc = queryTableLock(p, 1, READ_LOCK);
5738 if( rc!=SQLITE_OK ){
5739 return rc;
5740 }
5741
drh23e11ca2004-05-04 17:27:28 +00005742 assert( idx>=0 && idx<=15 );
drha34b6762004-05-07 13:30:42 +00005743 rc = sqlite3pager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00005744 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00005745 *pMeta = get4byte(&pP1[36 + idx*4]);
drha34b6762004-05-07 13:30:42 +00005746 sqlite3pager_unref(pP1);
drhae157872004-08-14 19:20:09 +00005747
danielk1977599fcba2004-11-08 07:13:13 +00005748 /* If autovacuumed is disabled in this build but we are trying to
5749 ** access an autovacuumed database, then make the database readonly.
5750 */
danielk1977003ba062004-11-04 02:57:33 +00005751#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00005752 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00005753#endif
drhae157872004-08-14 19:20:09 +00005754
danielk1977da184232006-01-05 11:34:32 +00005755 /* Grab the read-lock on page 1. */
5756 rc = lockTable(p, 1, READ_LOCK);
5757 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005758}
5759
5760/*
drh23e11ca2004-05-04 17:27:28 +00005761** Write meta-information back into the database. Meta[0] is
5762** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00005763*/
danielk1977aef0bf62005-12-30 16:28:01 +00005764int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
5765 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00005766 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00005767 int rc;
drh23e11ca2004-05-04 17:27:28 +00005768 assert( idx>=1 && idx<=15 );
danielk1977aef0bf62005-12-30 16:28:01 +00005769 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005770 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +00005771 }
drhde647132004-05-07 17:57:49 +00005772 assert( pBt->pPage1!=0 );
5773 pP1 = pBt->pPage1->aData;
drha34b6762004-05-07 13:30:42 +00005774 rc = sqlite3pager_write(pP1);
drh4b70f112004-05-02 21:12:19 +00005775 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00005776 put4byte(&pP1[36 + idx*4], iMeta);
drh8b2f49b2001-06-08 00:21:52 +00005777 return SQLITE_OK;
5778}
drh8c42ca92001-06-22 19:15:00 +00005779
drhf328bc82004-05-10 23:29:49 +00005780/*
5781** Return the flag byte at the beginning of the page that the cursor
5782** is currently pointing to.
5783*/
5784int sqlite3BtreeFlags(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00005785 /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
drh777e4c42006-01-13 04:31:58 +00005786 ** restoreOrClearCursorPosition() here.
danielk1977da184232006-01-05 11:34:32 +00005787 */
drhf328bc82004-05-10 23:29:49 +00005788 MemPage *pPage = pCur->pPage;
5789 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
5790}
5791
danielk1977b5402fb2005-01-12 07:15:04 +00005792#ifdef SQLITE_DEBUG
drh8c42ca92001-06-22 19:15:00 +00005793/*
5794** Print a disassembly of the given page on standard output. This routine
5795** is used for debugging and testing only.
5796*/
danielk1977aef0bf62005-12-30 16:28:01 +00005797static int btreePageDump(BtShared *pBt, int pgno, int recursive, MemPage *pParent){
drh8c42ca92001-06-22 19:15:00 +00005798 int rc;
5799 MemPage *pPage;
drhc8629a12004-05-08 20:07:40 +00005800 int i, j, c;
drh8c42ca92001-06-22 19:15:00 +00005801 int nFree;
5802 u16 idx;
drhab9f7f12004-05-08 10:56:11 +00005803 int hdr;
drh43605152004-05-29 21:46:49 +00005804 int nCell;
drha2fce642004-06-05 00:01:44 +00005805 int isInit;
drhab9f7f12004-05-08 10:56:11 +00005806 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00005807 char range[20];
5808 unsigned char payload[20];
drhab9f7f12004-05-08 10:56:11 +00005809
drh4b70f112004-05-02 21:12:19 +00005810 rc = getPage(pBt, (Pgno)pgno, &pPage);
drha2fce642004-06-05 00:01:44 +00005811 isInit = pPage->isInit;
5812 if( pPage->isInit==0 ){
danielk1977c7dc7532004-11-17 10:22:03 +00005813 initPage(pPage, pParent);
drha2fce642004-06-05 00:01:44 +00005814 }
drh8c42ca92001-06-22 19:15:00 +00005815 if( rc ){
5816 return rc;
5817 }
drhab9f7f12004-05-08 10:56:11 +00005818 hdr = pPage->hdrOffset;
5819 data = pPage->aData;
drhc8629a12004-05-08 20:07:40 +00005820 c = data[hdr];
drh8b18dd42004-05-12 19:18:15 +00005821 pPage->intKey = (c & (PTF_INTKEY|PTF_LEAFDATA))!=0;
drhc8629a12004-05-08 20:07:40 +00005822 pPage->zeroData = (c & PTF_ZERODATA)!=0;
drh8b18dd42004-05-12 19:18:15 +00005823 pPage->leafData = (c & PTF_LEAFDATA)!=0;
drhc8629a12004-05-08 20:07:40 +00005824 pPage->leaf = (c & PTF_LEAF)!=0;
drh8b18dd42004-05-12 19:18:15 +00005825 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
drh43605152004-05-29 21:46:49 +00005826 nCell = get2byte(&data[hdr+3]);
drhfe63d1c2004-09-08 20:13:04 +00005827 sqlite3DebugPrintf("PAGE %d: flags=0x%02x frag=%d parent=%d\n", pgno,
drh43605152004-05-29 21:46:49 +00005828 data[hdr], data[hdr+7],
drhda200cc2004-05-09 11:51:38 +00005829 (pPage->isInit && pPage->pParent) ? pPage->pParent->pgno : 0);
drhab9f7f12004-05-08 10:56:11 +00005830 assert( hdr == (pgno==1 ? 100 : 0) );
drh43605152004-05-29 21:46:49 +00005831 idx = hdr + 12 - pPage->leaf*4;
5832 for(i=0; i<nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00005833 CellInfo info;
drh4b70f112004-05-02 21:12:19 +00005834 Pgno child;
drh43605152004-05-29 21:46:49 +00005835 unsigned char *pCell;
drh6f11bef2004-05-13 01:12:56 +00005836 int sz;
drh43605152004-05-29 21:46:49 +00005837 int addr;
drh6f11bef2004-05-13 01:12:56 +00005838
drh43605152004-05-29 21:46:49 +00005839 addr = get2byte(&data[idx + 2*i]);
5840 pCell = &data[addr];
5841 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005842 sz = info.nSize;
drh43605152004-05-29 21:46:49 +00005843 sprintf(range,"%d..%d", addr, addr+sz-1);
drh4b70f112004-05-02 21:12:19 +00005844 if( pPage->leaf ){
5845 child = 0;
5846 }else{
drh43605152004-05-29 21:46:49 +00005847 child = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005848 }
drh6f11bef2004-05-13 01:12:56 +00005849 sz = info.nData;
5850 if( !pPage->intKey ) sz += info.nKey;
drh8c42ca92001-06-22 19:15:00 +00005851 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
drh6f11bef2004-05-13 01:12:56 +00005852 memcpy(payload, &pCell[info.nHeader], sz);
drh8c42ca92001-06-22 19:15:00 +00005853 for(j=0; j<sz; j++){
5854 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
5855 }
5856 payload[sz] = 0;
drhfe63d1c2004-09-08 20:13:04 +00005857 sqlite3DebugPrintf(
drh6f11bef2004-05-13 01:12:56 +00005858 "cell %2d: i=%-10s chld=%-4d nk=%-4lld nd=%-4d payload=%s\n",
5859 i, range, child, info.nKey, info.nData, payload
drh8c42ca92001-06-22 19:15:00 +00005860 );
drh8c42ca92001-06-22 19:15:00 +00005861 }
drh4b70f112004-05-02 21:12:19 +00005862 if( !pPage->leaf ){
drhfe63d1c2004-09-08 20:13:04 +00005863 sqlite3DebugPrintf("right_child: %d\n", get4byte(&data[hdr+8]));
drh4b70f112004-05-02 21:12:19 +00005864 }
drh8c42ca92001-06-22 19:15:00 +00005865 nFree = 0;
5866 i = 0;
drhab9f7f12004-05-08 10:56:11 +00005867 idx = get2byte(&data[hdr+1]);
drhb6f41482004-05-14 01:58:11 +00005868 while( idx>0 && idx<pPage->pBt->usableSize ){
drhab9f7f12004-05-08 10:56:11 +00005869 int sz = get2byte(&data[idx+2]);
drh4b70f112004-05-02 21:12:19 +00005870 sprintf(range,"%d..%d", idx, idx+sz-1);
5871 nFree += sz;
drhfe63d1c2004-09-08 20:13:04 +00005872 sqlite3DebugPrintf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
drh4b70f112004-05-02 21:12:19 +00005873 i, range, sz, nFree);
drhab9f7f12004-05-08 10:56:11 +00005874 idx = get2byte(&data[idx]);
drh2aa679f2001-06-25 02:11:07 +00005875 i++;
drh8c42ca92001-06-22 19:15:00 +00005876 }
5877 if( idx!=0 ){
drhfe63d1c2004-09-08 20:13:04 +00005878 sqlite3DebugPrintf("ERROR: next freeblock index out of range: %d\n", idx);
drh8c42ca92001-06-22 19:15:00 +00005879 }
drha34b6762004-05-07 13:30:42 +00005880 if( recursive && !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005881 for(i=0; i<nCell; i++){
5882 unsigned char *pCell = findCell(pPage, i);
danielk1977c7dc7532004-11-17 10:22:03 +00005883 btreePageDump(pBt, get4byte(pCell), 1, pPage);
drha34b6762004-05-07 13:30:42 +00005884 idx = get2byte(pCell);
drh6019e162001-07-02 17:51:45 +00005885 }
danielk1977c7dc7532004-11-17 10:22:03 +00005886 btreePageDump(pBt, get4byte(&data[hdr+8]), 1, pPage);
drh6019e162001-07-02 17:51:45 +00005887 }
drha2fce642004-06-05 00:01:44 +00005888 pPage->isInit = isInit;
drhab9f7f12004-05-08 10:56:11 +00005889 sqlite3pager_unref(data);
drh3644f082004-05-10 18:45:09 +00005890 fflush(stdout);
drh8c42ca92001-06-22 19:15:00 +00005891 return SQLITE_OK;
5892}
danielk1977aef0bf62005-12-30 16:28:01 +00005893int sqlite3BtreePageDump(Btree *p, int pgno, int recursive){
5894 return btreePageDump(p->pBt, pgno, recursive, 0);
danielk1977c7dc7532004-11-17 10:22:03 +00005895}
drhaaab5722002-02-19 13:39:21 +00005896#endif
drh8c42ca92001-06-22 19:15:00 +00005897
danielk197707cb5602006-01-20 10:55:05 +00005898#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh8c42ca92001-06-22 19:15:00 +00005899/*
drh2aa679f2001-06-25 02:11:07 +00005900** Fill aResult[] with information about the entry and page that the
5901** cursor is pointing to.
5902**
5903** aResult[0] = The page number
5904** aResult[1] = The entry number
5905** aResult[2] = Total number of entries on this page
drh3e27c022004-07-23 00:01:38 +00005906** aResult[3] = Cell size (local payload + header)
drh2aa679f2001-06-25 02:11:07 +00005907** aResult[4] = Number of free bytes on this page
5908** aResult[5] = Number of free blocks on the page
drh3e27c022004-07-23 00:01:38 +00005909** aResult[6] = Total payload size (local + overflow)
5910** aResult[7] = Header size in bytes
5911** aResult[8] = Local payload size
5912** aResult[9] = Parent page number
drh5eddca62001-06-30 21:53:53 +00005913**
5914** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00005915*/
drh3e27c022004-07-23 00:01:38 +00005916int sqlite3BtreeCursorInfo(BtCursor *pCur, int *aResult, int upCnt){
drh2aa679f2001-06-25 02:11:07 +00005917 int cnt, idx;
5918 MemPage *pPage = pCur->pPage;
drh3e27c022004-07-23 00:01:38 +00005919 BtCursor tmpCur;
drhda200cc2004-05-09 11:51:38 +00005920
drh777e4c42006-01-13 04:31:58 +00005921 int rc = restoreOrClearCursorPosition(pCur, 1);
danielk1977da184232006-01-05 11:34:32 +00005922 if( rc!=SQLITE_OK ){
5923 return rc;
5924 }
5925
drhda200cc2004-05-09 11:51:38 +00005926 pageIntegrity(pPage);
drh4b70f112004-05-02 21:12:19 +00005927 assert( pPage->isInit );
drh3e27c022004-07-23 00:01:38 +00005928 getTempCursor(pCur, &tmpCur);
5929 while( upCnt-- ){
5930 moveToParent(&tmpCur);
5931 }
5932 pPage = tmpCur.pPage;
5933 pageIntegrity(pPage);
drha34b6762004-05-07 13:30:42 +00005934 aResult[0] = sqlite3pager_pagenumber(pPage->aData);
drh91025292004-05-03 19:49:32 +00005935 assert( aResult[0]==pPage->pgno );
drh3e27c022004-07-23 00:01:38 +00005936 aResult[1] = tmpCur.idx;
drh2aa679f2001-06-25 02:11:07 +00005937 aResult[2] = pPage->nCell;
drh3e27c022004-07-23 00:01:38 +00005938 if( tmpCur.idx>=0 && tmpCur.idx<pPage->nCell ){
5939 getCellInfo(&tmpCur);
5940 aResult[3] = tmpCur.info.nSize;
5941 aResult[6] = tmpCur.info.nData;
5942 aResult[7] = tmpCur.info.nHeader;
5943 aResult[8] = tmpCur.info.nLocal;
drh2aa679f2001-06-25 02:11:07 +00005944 }else{
5945 aResult[3] = 0;
5946 aResult[6] = 0;
drh3e27c022004-07-23 00:01:38 +00005947 aResult[7] = 0;
5948 aResult[8] = 0;
drh2aa679f2001-06-25 02:11:07 +00005949 }
5950 aResult[4] = pPage->nFree;
5951 cnt = 0;
drh4b70f112004-05-02 21:12:19 +00005952 idx = get2byte(&pPage->aData[pPage->hdrOffset+1]);
drhb6f41482004-05-14 01:58:11 +00005953 while( idx>0 && idx<pPage->pBt->usableSize ){
drh2aa679f2001-06-25 02:11:07 +00005954 cnt++;
drh4b70f112004-05-02 21:12:19 +00005955 idx = get2byte(&pPage->aData[idx]);
drh2aa679f2001-06-25 02:11:07 +00005956 }
5957 aResult[5] = cnt;
drh3e27c022004-07-23 00:01:38 +00005958 if( pPage->pParent==0 || isRootPage(pPage) ){
5959 aResult[9] = 0;
5960 }else{
5961 aResult[9] = pPage->pParent->pgno;
5962 }
5963 releaseTempCursor(&tmpCur);
drh8c42ca92001-06-22 19:15:00 +00005964 return SQLITE_OK;
5965}
drhaaab5722002-02-19 13:39:21 +00005966#endif
drhdd793422001-06-28 01:54:48 +00005967
drhdd793422001-06-28 01:54:48 +00005968/*
drh5eddca62001-06-30 21:53:53 +00005969** Return the pager associated with a BTree. This routine is used for
5970** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00005971*/
danielk1977aef0bf62005-12-30 16:28:01 +00005972Pager *sqlite3BtreePager(Btree *p){
5973 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00005974}
drh5eddca62001-06-30 21:53:53 +00005975
5976/*
5977** This structure is passed around through all the sanity checking routines
5978** in order to keep track of some global state information.
5979*/
drhaaab5722002-02-19 13:39:21 +00005980typedef struct IntegrityCk IntegrityCk;
5981struct IntegrityCk {
danielk1977aef0bf62005-12-30 16:28:01 +00005982 BtShared *pBt; /* The tree being checked out */
drh100569d2001-10-02 13:01:48 +00005983 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
5984 int nPage; /* Number of pages in the database */
5985 int *anRef; /* Number of times each page is referenced */
drh100569d2001-10-02 13:01:48 +00005986 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00005987};
5988
drhb7f91642004-10-31 02:22:47 +00005989#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005990/*
5991** Append a message to the error message string.
5992*/
drh2e38c322004-09-03 18:38:44 +00005993static void checkAppendMsg(
5994 IntegrityCk *pCheck,
5995 char *zMsg1,
5996 const char *zFormat,
5997 ...
5998){
5999 va_list ap;
6000 char *zMsg2;
6001 va_start(ap, zFormat);
6002 zMsg2 = sqlite3VMPrintf(zFormat, ap);
6003 va_end(ap);
6004 if( zMsg1==0 ) zMsg1 = "";
drh5eddca62001-06-30 21:53:53 +00006005 if( pCheck->zErrMsg ){
6006 char *zOld = pCheck->zErrMsg;
6007 pCheck->zErrMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00006008 sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00006009 sqliteFree(zOld);
6010 }else{
danielk19774adee202004-05-08 08:23:19 +00006011 sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00006012 }
drh2e38c322004-09-03 18:38:44 +00006013 sqliteFree(zMsg2);
drh5eddca62001-06-30 21:53:53 +00006014}
drhb7f91642004-10-31 02:22:47 +00006015#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006016
drhb7f91642004-10-31 02:22:47 +00006017#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006018/*
6019** Add 1 to the reference count for page iPage. If this is the second
6020** reference to the page, add an error message to pCheck->zErrMsg.
6021** Return 1 if there are 2 ore more references to the page and 0 if
6022** if this is the first reference to the page.
6023**
6024** Also check that the page number is in bounds.
6025*/
drhaaab5722002-02-19 13:39:21 +00006026static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00006027 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00006028 if( iPage>pCheck->nPage || iPage<0 ){
drh2e38c322004-09-03 18:38:44 +00006029 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006030 return 1;
6031 }
6032 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00006033 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006034 return 1;
6035 }
6036 return (pCheck->anRef[iPage]++)>1;
6037}
6038
danielk1977afcdd022004-10-31 16:25:42 +00006039#ifndef SQLITE_OMIT_AUTOVACUUM
6040/*
6041** Check that the entry in the pointer-map for page iChild maps to
6042** page iParent, pointer type ptrType. If not, append an error message
6043** to pCheck.
6044*/
6045static void checkPtrmap(
6046 IntegrityCk *pCheck, /* Integrity check context */
6047 Pgno iChild, /* Child page number */
6048 u8 eType, /* Expected pointer map type */
6049 Pgno iParent, /* Expected pointer map parent page number */
6050 char *zContext /* Context description (used for error msg) */
6051){
6052 int rc;
6053 u8 ePtrmapType;
6054 Pgno iPtrmapParent;
6055
6056 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
6057 if( rc!=SQLITE_OK ){
6058 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
6059 return;
6060 }
6061
6062 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
6063 checkAppendMsg(pCheck, zContext,
6064 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
6065 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
6066 }
6067}
6068#endif
6069
drh5eddca62001-06-30 21:53:53 +00006070/*
6071** Check the integrity of the freelist or of an overflow page list.
6072** Verify that the number of pages on the list is N.
6073*/
drh30e58752002-03-02 20:41:57 +00006074static void checkList(
6075 IntegrityCk *pCheck, /* Integrity checking context */
6076 int isFreeList, /* True for a freelist. False for overflow page list */
6077 int iPage, /* Page number for first page in the list */
6078 int N, /* Expected number of pages in the list */
6079 char *zContext /* Context for error messages */
6080){
6081 int i;
drh3a4c1412004-05-09 20:40:11 +00006082 int expected = N;
6083 int iFirst = iPage;
drh30e58752002-03-02 20:41:57 +00006084 while( N-- > 0 ){
drh4b70f112004-05-02 21:12:19 +00006085 unsigned char *pOvfl;
drh5eddca62001-06-30 21:53:53 +00006086 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00006087 checkAppendMsg(pCheck, zContext,
6088 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00006089 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00006090 break;
6091 }
6092 if( checkRef(pCheck, iPage, zContext) ) break;
drha34b6762004-05-07 13:30:42 +00006093 if( sqlite3pager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
drh2e38c322004-09-03 18:38:44 +00006094 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006095 break;
6096 }
drh30e58752002-03-02 20:41:57 +00006097 if( isFreeList ){
drh4b70f112004-05-02 21:12:19 +00006098 int n = get4byte(&pOvfl[4]);
danielk1977687566d2004-11-02 12:56:41 +00006099#ifndef SQLITE_OMIT_AUTOVACUUM
6100 if( pCheck->pBt->autoVacuum ){
6101 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
6102 }
6103#endif
drh855eb1c2004-08-31 13:45:11 +00006104 if( n>pCheck->pBt->usableSize/4-8 ){
drh2e38c322004-09-03 18:38:44 +00006105 checkAppendMsg(pCheck, zContext,
6106 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00006107 N--;
6108 }else{
6109 for(i=0; i<n; i++){
danielk1977687566d2004-11-02 12:56:41 +00006110 Pgno iFreePage = get4byte(&pOvfl[8+i*4]);
6111#ifndef SQLITE_OMIT_AUTOVACUUM
6112 if( pCheck->pBt->autoVacuum ){
6113 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
6114 }
6115#endif
6116 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00006117 }
6118 N -= n;
drh30e58752002-03-02 20:41:57 +00006119 }
drh30e58752002-03-02 20:41:57 +00006120 }
danielk1977afcdd022004-10-31 16:25:42 +00006121#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006122 else{
6123 /* If this database supports auto-vacuum and iPage is not the last
6124 ** page in this overflow list, check that the pointer-map entry for
6125 ** the following page matches iPage.
6126 */
6127 if( pCheck->pBt->autoVacuum && N>0 ){
6128 i = get4byte(pOvfl);
6129 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
6130 }
danielk1977afcdd022004-10-31 16:25:42 +00006131 }
6132#endif
drh4b70f112004-05-02 21:12:19 +00006133 iPage = get4byte(pOvfl);
drha34b6762004-05-07 13:30:42 +00006134 sqlite3pager_unref(pOvfl);
drh5eddca62001-06-30 21:53:53 +00006135 }
6136}
drhb7f91642004-10-31 02:22:47 +00006137#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006138
drhb7f91642004-10-31 02:22:47 +00006139#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006140/*
6141** Do various sanity checks on a single page of a tree. Return
6142** the tree depth. Root pages return 0. Parents of root pages
6143** return 1, and so forth.
6144**
6145** These checks are done:
6146**
6147** 1. Make sure that cells and freeblocks do not overlap
6148** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00006149** NO 2. Make sure cell keys are in order.
6150** NO 3. Make sure no key is less than or equal to zLowerBound.
6151** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00006152** 5. Check the integrity of overflow pages.
6153** 6. Recursively call checkTreePage on all children.
6154** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00006155** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00006156** the root of the tree.
6157*/
6158static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00006159 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00006160 int iPage, /* Page number of the page to check */
6161 MemPage *pParent, /* Parent page */
6162 char *zParentContext, /* Parent context */
6163 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00006164 int nLower, /* Number of characters in zLowerBound */
6165 char *zUpperBound, /* All keys should be less than this, if not NULL */
6166 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00006167){
6168 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00006169 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00006170 int hdr, cellStart;
6171 int nCell;
drhda200cc2004-05-09 11:51:38 +00006172 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00006173 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00006174 int usableSize;
drh5eddca62001-06-30 21:53:53 +00006175 char zContext[100];
drh2e38c322004-09-03 18:38:44 +00006176 char *hit;
drh5eddca62001-06-30 21:53:53 +00006177
danielk1977ef73ee92004-11-06 12:26:07 +00006178 sprintf(zContext, "Page %d: ", iPage);
6179
drh5eddca62001-06-30 21:53:53 +00006180 /* Check that the page exists
6181 */
drhd9cb6ac2005-10-20 07:28:17 +00006182 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00006183 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00006184 if( iPage==0 ) return 0;
6185 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh4b70f112004-05-02 21:12:19 +00006186 if( (rc = getPage(pBt, (Pgno)iPage, &pPage))!=0 ){
drh2e38c322004-09-03 18:38:44 +00006187 checkAppendMsg(pCheck, zContext,
6188 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00006189 return 0;
6190 }
drh4b70f112004-05-02 21:12:19 +00006191 if( (rc = initPage(pPage, pParent))!=0 ){
drh2e38c322004-09-03 18:38:44 +00006192 checkAppendMsg(pCheck, zContext, "initPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00006193 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00006194 return 0;
6195 }
6196
6197 /* Check out all the cells.
6198 */
6199 depth = 0;
drh5eddca62001-06-30 21:53:53 +00006200 for(i=0; i<pPage->nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00006201 u8 *pCell;
6202 int sz;
6203 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00006204
6205 /* Check payload overflow pages
6206 */
drh3a4c1412004-05-09 20:40:11 +00006207 sprintf(zContext, "On tree page %d cell %d: ", iPage, i);
drh43605152004-05-29 21:46:49 +00006208 pCell = findCell(pPage,i);
6209 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00006210 sz = info.nData;
6211 if( !pPage->intKey ) sz += info.nKey;
6212 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00006213 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00006214 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
6215#ifndef SQLITE_OMIT_AUTOVACUUM
6216 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006217 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00006218 }
6219#endif
6220 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00006221 }
6222
6223 /* Check sanity of left child page.
6224 */
drhda200cc2004-05-09 11:51:38 +00006225 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006226 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00006227#ifndef SQLITE_OMIT_AUTOVACUUM
6228 if( pBt->autoVacuum ){
6229 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
6230 }
6231#endif
drhda200cc2004-05-09 11:51:38 +00006232 d2 = checkTreePage(pCheck,pgno,pPage,zContext,0,0,0,0);
6233 if( i>0 && d2!=depth ){
6234 checkAppendMsg(pCheck, zContext, "Child page depth differs");
6235 }
6236 depth = d2;
drh5eddca62001-06-30 21:53:53 +00006237 }
drh5eddca62001-06-30 21:53:53 +00006238 }
drhda200cc2004-05-09 11:51:38 +00006239 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006240 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drhda200cc2004-05-09 11:51:38 +00006241 sprintf(zContext, "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00006242#ifndef SQLITE_OMIT_AUTOVACUUM
6243 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006244 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00006245 }
6246#endif
drhda200cc2004-05-09 11:51:38 +00006247 checkTreePage(pCheck, pgno, pPage, zContext,0,0,0,0);
6248 }
drh5eddca62001-06-30 21:53:53 +00006249
6250 /* Check for complete coverage of the page
6251 */
drhda200cc2004-05-09 11:51:38 +00006252 data = pPage->aData;
6253 hdr = pPage->hdrOffset;
drh2e38c322004-09-03 18:38:44 +00006254 hit = sqliteMalloc( usableSize );
6255 if( hit ){
6256 memset(hit, 1, get2byte(&data[hdr+5]));
6257 nCell = get2byte(&data[hdr+3]);
6258 cellStart = hdr + 12 - 4*pPage->leaf;
6259 for(i=0; i<nCell; i++){
6260 int pc = get2byte(&data[cellStart+i*2]);
6261 int size = cellSizePtr(pPage, &data[pc]);
6262 int j;
danielk19777701e812005-01-10 12:59:51 +00006263 if( (pc+size-1)>=usableSize || pc<0 ){
6264 checkAppendMsg(pCheck, 0,
6265 "Corruption detected in cell %d on page %d",i,iPage,0);
6266 }else{
6267 for(j=pc+size-1; j>=pc; j--) hit[j]++;
6268 }
drh2e38c322004-09-03 18:38:44 +00006269 }
6270 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
6271 cnt++){
6272 int size = get2byte(&data[i+2]);
6273 int j;
danielk19777701e812005-01-10 12:59:51 +00006274 if( (i+size-1)>=usableSize || i<0 ){
6275 checkAppendMsg(pCheck, 0,
6276 "Corruption detected in cell %d on page %d",i,iPage,0);
6277 }else{
6278 for(j=i+size-1; j>=i; j--) hit[j]++;
6279 }
drh2e38c322004-09-03 18:38:44 +00006280 i = get2byte(&data[i]);
6281 }
6282 for(i=cnt=0; i<usableSize; i++){
6283 if( hit[i]==0 ){
6284 cnt++;
6285 }else if( hit[i]>1 ){
6286 checkAppendMsg(pCheck, 0,
6287 "Multiple uses for byte %d of page %d", i, iPage);
6288 break;
6289 }
6290 }
6291 if( cnt!=data[hdr+7] ){
6292 checkAppendMsg(pCheck, 0,
6293 "Fragmented space is %d byte reported as %d on page %d",
6294 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00006295 }
6296 }
drh2e38c322004-09-03 18:38:44 +00006297 sqliteFree(hit);
drh6019e162001-07-02 17:51:45 +00006298
drh4b70f112004-05-02 21:12:19 +00006299 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00006300 return depth+1;
drh5eddca62001-06-30 21:53:53 +00006301}
drhb7f91642004-10-31 02:22:47 +00006302#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006303
drhb7f91642004-10-31 02:22:47 +00006304#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006305/*
6306** This routine does a complete check of the given BTree file. aRoot[] is
6307** an array of pages numbers were each page number is the root page of
6308** a table. nRoot is the number of entries in aRoot.
6309**
6310** If everything checks out, this routine returns NULL. If something is
6311** amiss, an error message is written into memory obtained from malloc()
6312** and a pointer to that error message is returned. The calling function
6313** is responsible for freeing the error message when it is done.
6314*/
danielk1977aef0bf62005-12-30 16:28:01 +00006315char *sqlite3BtreeIntegrityCheck(Btree *p, int *aRoot, int nRoot){
drh5eddca62001-06-30 21:53:53 +00006316 int i;
6317 int nRef;
drhaaab5722002-02-19 13:39:21 +00006318 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00006319 BtShared *pBt = p->pBt;
drh5eddca62001-06-30 21:53:53 +00006320
drha34b6762004-05-07 13:30:42 +00006321 nRef = *sqlite3pager_stats(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00006322 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
drhefc251d2001-07-01 22:12:01 +00006323 return sqliteStrDup("Unable to acquire a read lock on the database");
6324 }
drh5eddca62001-06-30 21:53:53 +00006325 sCheck.pBt = pBt;
6326 sCheck.pPager = pBt->pPager;
drha34b6762004-05-07 13:30:42 +00006327 sCheck.nPage = sqlite3pager_pagecount(sCheck.pPager);
drh0de8c112002-07-06 16:32:14 +00006328 if( sCheck.nPage==0 ){
6329 unlockBtreeIfUnused(pBt);
6330 return 0;
6331 }
drh8c1238a2003-01-02 14:43:55 +00006332 sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00006333 if( !sCheck.anRef ){
6334 unlockBtreeIfUnused(pBt);
6335 return sqlite3MPrintf("Unable to malloc %d bytes",
6336 (sCheck.nPage+1)*sizeof(sCheck.anRef[0]));
6337 }
drhda200cc2004-05-09 11:51:38 +00006338 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00006339 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00006340 if( i<=sCheck.nPage ){
6341 sCheck.anRef[i] = 1;
6342 }
drh5eddca62001-06-30 21:53:53 +00006343 sCheck.zErrMsg = 0;
6344
6345 /* Check the integrity of the freelist
6346 */
drha34b6762004-05-07 13:30:42 +00006347 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
6348 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00006349
6350 /* Check all the tables.
6351 */
6352 for(i=0; i<nRoot; i++){
drh4ff6dfa2002-03-03 23:06:00 +00006353 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00006354#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006355 if( pBt->autoVacuum && aRoot[i]>1 ){
6356 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
6357 }
6358#endif
drh1bffb9c2002-02-03 17:37:36 +00006359 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00006360 }
6361
6362 /* Make sure every page in the file is referenced
6363 */
6364 for(i=1; i<=sCheck.nPage; i++){
danielk1977afcdd022004-10-31 16:25:42 +00006365#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00006366 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00006367 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00006368 }
danielk1977afcdd022004-10-31 16:25:42 +00006369#else
6370 /* If the database supports auto-vacuum, make sure no tables contain
6371 ** references to pointer-map pages.
6372 */
6373 if( sCheck.anRef[i]==0 &&
drh42cac6d2004-11-20 20:31:11 +00006374 (PTRMAP_PAGENO(pBt->usableSize, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006375 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
6376 }
6377 if( sCheck.anRef[i]!=0 &&
drh42cac6d2004-11-20 20:31:11 +00006378 (PTRMAP_PAGENO(pBt->usableSize, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006379 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
6380 }
6381#endif
drh5eddca62001-06-30 21:53:53 +00006382 }
6383
6384 /* Make sure this analysis did not leave any unref() pages
6385 */
drh5e00f6c2001-09-13 13:46:56 +00006386 unlockBtreeIfUnused(pBt);
drha34b6762004-05-07 13:30:42 +00006387 if( nRef != *sqlite3pager_stats(pBt->pPager) ){
drh2e38c322004-09-03 18:38:44 +00006388 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00006389 "Outstanding page count goes from %d to %d during this analysis",
drha34b6762004-05-07 13:30:42 +00006390 nRef, *sqlite3pager_stats(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00006391 );
drh5eddca62001-06-30 21:53:53 +00006392 }
6393
6394 /* Clean up and report errors.
6395 */
6396 sqliteFree(sCheck.anRef);
6397 return sCheck.zErrMsg;
6398}
drhb7f91642004-10-31 02:22:47 +00006399#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00006400
drh73509ee2003-04-06 20:44:45 +00006401/*
6402** Return the full pathname of the underlying database file.
6403*/
danielk1977aef0bf62005-12-30 16:28:01 +00006404const char *sqlite3BtreeGetFilename(Btree *p){
6405 assert( p->pBt->pPager!=0 );
6406 return sqlite3pager_filename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00006407}
6408
6409/*
danielk19775865e3d2004-06-14 06:03:57 +00006410** Return the pathname of the directory that contains the database file.
6411*/
danielk1977aef0bf62005-12-30 16:28:01 +00006412const char *sqlite3BtreeGetDirname(Btree *p){
6413 assert( p->pBt->pPager!=0 );
6414 return sqlite3pager_dirname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006415}
6416
6417/*
6418** Return the pathname of the journal file for this database. The return
6419** value of this routine is the same regardless of whether the journal file
6420** has been created or not.
6421*/
danielk1977aef0bf62005-12-30 16:28:01 +00006422const char *sqlite3BtreeGetJournalname(Btree *p){
6423 assert( p->pBt->pPager!=0 );
6424 return sqlite3pager_journalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006425}
6426
drhb7f91642004-10-31 02:22:47 +00006427#ifndef SQLITE_OMIT_VACUUM
danielk19775865e3d2004-06-14 06:03:57 +00006428/*
drhf7c57532003-04-25 13:22:51 +00006429** Copy the complete content of pBtFrom into pBtTo. A transaction
6430** must be active for both files.
6431**
6432** The size of file pBtFrom may be reduced by this operation.
drh43605152004-05-29 21:46:49 +00006433** If anything goes wrong, the transaction on pBtFrom is rolled back.
drh73509ee2003-04-06 20:44:45 +00006434*/
danielk1977aef0bf62005-12-30 16:28:01 +00006435int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
drhf7c57532003-04-25 13:22:51 +00006436 int rc = SQLITE_OK;
drh50f2f432005-09-16 11:32:18 +00006437 Pgno i, nPage, nToPage, iSkip;
drhf7c57532003-04-25 13:22:51 +00006438
danielk1977aef0bf62005-12-30 16:28:01 +00006439 BtShared *pBtTo = pTo->pBt;
6440 BtShared *pBtFrom = pFrom->pBt;
6441
6442 if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
danielk1977ee5741e2004-05-31 10:01:34 +00006443 return SQLITE_ERROR;
6444 }
drhf7c57532003-04-25 13:22:51 +00006445 if( pBtTo->pCursor ) return SQLITE_BUSY;
drha34b6762004-05-07 13:30:42 +00006446 nToPage = sqlite3pager_pagecount(pBtTo->pPager);
6447 nPage = sqlite3pager_pagecount(pBtFrom->pPager);
drh50f2f432005-09-16 11:32:18 +00006448 iSkip = PENDING_BYTE_PAGE(pBtTo);
danielk1977369f27e2004-06-15 11:40:04 +00006449 for(i=1; rc==SQLITE_OK && i<=nPage; i++){
drhf7c57532003-04-25 13:22:51 +00006450 void *pPage;
drh50f2f432005-09-16 11:32:18 +00006451 if( i==iSkip ) continue;
drha34b6762004-05-07 13:30:42 +00006452 rc = sqlite3pager_get(pBtFrom->pPager, i, &pPage);
drhf7c57532003-04-25 13:22:51 +00006453 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00006454 rc = sqlite3pager_overwrite(pBtTo->pPager, i, pPage);
drh2e6d11b2003-04-25 15:37:57 +00006455 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00006456 sqlite3pager_unref(pPage);
drhf7c57532003-04-25 13:22:51 +00006457 }
drh2e6d11b2003-04-25 15:37:57 +00006458 for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
6459 void *pPage;
drh49285702005-09-17 15:20:26 +00006460 if( i==iSkip ) continue;
drha34b6762004-05-07 13:30:42 +00006461 rc = sqlite3pager_get(pBtTo->pPager, i, &pPage);
drh2e6d11b2003-04-25 15:37:57 +00006462 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00006463 rc = sqlite3pager_write(pPage);
6464 sqlite3pager_unref(pPage);
6465 sqlite3pager_dont_write(pBtTo->pPager, i);
drh2e6d11b2003-04-25 15:37:57 +00006466 }
6467 if( !rc && nPage<nToPage ){
drha34b6762004-05-07 13:30:42 +00006468 rc = sqlite3pager_truncate(pBtTo->pPager, nPage);
drh2e6d11b2003-04-25 15:37:57 +00006469 }
drhf7c57532003-04-25 13:22:51 +00006470 if( rc ){
danielk1977aef0bf62005-12-30 16:28:01 +00006471 sqlite3BtreeRollback(pTo);
drhf7c57532003-04-25 13:22:51 +00006472 }
6473 return rc;
drh73509ee2003-04-06 20:44:45 +00006474}
drhb7f91642004-10-31 02:22:47 +00006475#endif /* SQLITE_OMIT_VACUUM */
danielk19771d850a72004-05-31 08:26:49 +00006476
6477/*
6478** Return non-zero if a transaction is active.
6479*/
danielk1977aef0bf62005-12-30 16:28:01 +00006480int sqlite3BtreeIsInTrans(Btree *p){
6481 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00006482}
6483
6484/*
6485** Return non-zero if a statement transaction is active.
6486*/
danielk1977aef0bf62005-12-30 16:28:01 +00006487int sqlite3BtreeIsInStmt(Btree *p){
6488 return (p->pBt && p->pBt->inStmt);
danielk19771d850a72004-05-31 08:26:49 +00006489}
danielk197713adf8a2004-06-03 16:08:41 +00006490
6491/*
6492** This call is a no-op if no write-transaction is currently active on pBt.
6493**
6494** Otherwise, sync the database file for the btree pBt. zMaster points to
6495** the name of a master journal file that should be written into the
6496** individual journal file, or is NULL, indicating no master journal file
6497** (single database transaction).
6498**
6499** When this is called, the master journal should already have been
6500** created, populated with this journal pointer and synced to disk.
6501**
6502** Once this is routine has returned, the only thing required to commit
6503** the write-transaction for this database file is to delete the journal.
6504*/
danielk1977aef0bf62005-12-30 16:28:01 +00006505int sqlite3BtreeSync(Btree *p, const char *zMaster){
6506 if( p->inTrans==TRANS_WRITE ){
6507 BtShared *pBt = p->pBt;
danielk1977687566d2004-11-02 12:56:41 +00006508#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977d761c0c2004-11-05 16:37:02 +00006509 Pgno nTrunc = 0;
danielk1977687566d2004-11-02 12:56:41 +00006510 if( pBt->autoVacuum ){
danielk1977d761c0c2004-11-05 16:37:02 +00006511 int rc = autoVacuumCommit(pBt, &nTrunc);
danielk1977687566d2004-11-02 12:56:41 +00006512 if( rc!=SQLITE_OK ) return rc;
6513 }
danielk1977d761c0c2004-11-05 16:37:02 +00006514 return sqlite3pager_sync(pBt->pPager, zMaster, nTrunc);
danielk1977687566d2004-11-02 12:56:41 +00006515#endif
danielk1977d761c0c2004-11-05 16:37:02 +00006516 return sqlite3pager_sync(pBt->pPager, zMaster, 0);
danielk197713adf8a2004-06-03 16:08:41 +00006517 }
6518 return SQLITE_OK;
6519}
danielk1977aef0bf62005-12-30 16:28:01 +00006520
danielk1977da184232006-01-05 11:34:32 +00006521/*
6522** This function returns a pointer to a blob of memory associated with
6523** a single shared-btree. The memory is used by client code for it's own
6524** purposes (for example, to store a high-level schema associated with
6525** the shared-btree). The btree layer manages reference counting issues.
6526**
6527** The first time this is called on a shared-btree, nBytes bytes of memory
6528** are allocated, zeroed, and returned to the caller. For each subsequent
6529** call the nBytes parameter is ignored and a pointer to the same blob
6530** of memory returned.
6531**
6532** Just before the shared-btree is closed, the function passed as the
6533** xFree argument when the memory allocation was made is invoked on the
6534** blob of allocated memory. This function should not call sqliteFree()
6535** on the memory, the btree layer does that.
6536*/
6537void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
6538 BtShared *pBt = p->pBt;
6539 if( !pBt->pSchema ){
6540 pBt->pSchema = sqliteMalloc(nBytes);
6541 pBt->xFreeSchema = xFree;
6542 }
6543 return pBt->pSchema;
6544}
6545
danielk1977c87d34d2006-01-06 13:00:28 +00006546/*
6547** Return true if another user of the same shared btree as the argument
6548** handle holds an exclusive lock on the sqlite_master table.
6549*/
6550int sqlite3BtreeSchemaLocked(Btree *p){
6551 return (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
6552}
6553
danielk1977c00da102006-01-07 13:21:04 +00006554int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00006555 int rc = SQLITE_OK;
6556#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977c00da102006-01-07 13:21:04 +00006557 u8 lockType = (isWriteLock?WRITE_LOCK:READ_LOCK);
danielk19772e94d4d2006-01-09 05:36:27 +00006558 rc = queryTableLock(p, iTab, lockType);
danielk1977c00da102006-01-07 13:21:04 +00006559 if( rc==SQLITE_OK ){
6560 rc = lockTable(p, iTab, lockType);
6561 }
danielk19772e94d4d2006-01-09 05:36:27 +00006562#endif
danielk1977c00da102006-01-07 13:21:04 +00006563 return rc;
6564}
danielk1977b82e7ed2006-01-11 14:09:31 +00006565
drh6f7adc82006-01-11 21:41:20 +00006566/*
6567** The following debugging interface has to be in this file (rather
6568** than in, for example, test1.c) so that it can get access to
6569** the definition of BtShared.
6570*/
danielk197707cb5602006-01-20 10:55:05 +00006571#if defined(SQLITE_DEBUG) && defined(TCLSH)
danielk1977b82e7ed2006-01-11 14:09:31 +00006572#include <tcl.h>
6573int sqlite3_shared_cache_report(
6574 void * clientData,
6575 Tcl_Interp *interp,
6576 int objc,
6577 Tcl_Obj *CONST objv[]
6578){
drh6f7adc82006-01-11 21:41:20 +00006579 const ThreadData *pTd = sqlite3ThreadDataReadOnly();
danielk1977b82e7ed2006-01-11 14:09:31 +00006580 if( pTd->useSharedData ){
6581 BtShared *pBt;
6582 Tcl_Obj *pRet = Tcl_NewObj();
6583 for(pBt=pTd->pBtree; pBt; pBt=pBt->pNext){
6584 const char *zFile = sqlite3pager_filename(pBt->pPager);
6585 Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj(zFile, -1));
6586 Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(pBt->nRef));
6587 }
6588 Tcl_SetObjResult(interp, pRet);
6589 }
6590 return TCL_OK;
6591}
6592#endif