blob: b1bd141ed1b029ccd9854a9cb3e7afc5d78000a4 [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*************************************************************************
danielk1977b82e7ed2006-01-11 14:09:31 +000012** $Id: btree.c,v 1.290 2006/01/11 14:09:31 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
414** this state, restoreCursorPosition() can be called to attempt to seek
415** 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
465#define getVarint32 sqlite3GetVarint32
466#define putVarint sqlite3PutVarint
drh0d316a42002-08-11 20:10:47 +0000467
danielk1977599fcba2004-11-08 07:13:13 +0000468/* The database page the PENDING_BYTE occupies. This page is never used.
469** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
470** should possibly be consolidated (presumably in pager.h).
471*/
472#define PENDING_BYTE_PAGE(pBt) ((PENDING_BYTE/(pBt)->pageSize)+1)
danielk1977afcdd022004-10-31 16:25:42 +0000473
danielk1977aef0bf62005-12-30 16:28:01 +0000474/*
475** A linked list of the following structures is stored at BtShared.pLock.
476** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
477** is opened on the table with root page BtShared.iTable. Locks are removed
478** from this list when a transaction is committed or rolled back, or when
479** a btree handle is closed.
480*/
481struct BtLock {
482 Btree *pBtree; /* Btree handle holding this lock */
483 Pgno iTable; /* Root page of table */
484 u8 eLock; /* READ_LOCK or WRITE_LOCK */
485 BtLock *pNext; /* Next in BtShared.pLock list */
486};
487
488/* Candidate values for BtLock.eLock */
489#define READ_LOCK 1
490#define WRITE_LOCK 2
491
492#ifdef SQLITE_OMIT_SHARED_CACHE
493 /*
494 ** The functions queryTableLock(), lockTable() and unlockAllTables()
495 ** manipulate entries in the BtShared.pLock linked list used to store
496 ** shared-cache table level locks. If the library is compiled with the
497 ** shared-cache feature disabled, then there is only ever one user
danielk1977da184232006-01-05 11:34:32 +0000498 ** of each BtShared structure and so this locking is not necessary.
499 ** So define the lock related functions as no-ops.
danielk1977aef0bf62005-12-30 16:28:01 +0000500 */
501 #define queryTableLock(a,b,c) SQLITE_OK
502 #define lockTable(a,b,c) SQLITE_OK
danielk1977da184232006-01-05 11:34:32 +0000503 #define unlockAllTables(a)
504 #define restoreCursorPosition(a,b) SQLITE_OK
505 #define saveAllCursors(a,b,c) SQLITE_OK
506
danielk1977aef0bf62005-12-30 16:28:01 +0000507#else
508
509/*
danielk1977da184232006-01-05 11:34:32 +0000510** Save the current cursor position in the variables BtCursor.nKey
511** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
512*/
513static int saveCursorPosition(BtCursor *pCur){
514 int rc = SQLITE_OK;
515
516 assert( CURSOR_VALID==pCur->eState|| CURSOR_INVALID==pCur->eState );
517 assert( 0==pCur->pKey );
518
519 if( pCur->eState==CURSOR_VALID ){
520 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
521
522 /* If this is an intKey table, then the above call to BtreeKeySize()
523 ** stores the integer key in pCur->nKey. In this case this value is
524 ** all that is required. Otherwise, if pCur is not open on an intKey
525 ** table, then malloc space for and store the pCur->nKey bytes of key
526 ** data.
527 */
528 if( rc==SQLITE_OK && 0==pCur->pPage->intKey){
529 void *pKey = sqliteMalloc(pCur->nKey);
530 if( pKey ){
531 rc = sqlite3BtreeKey(pCur, 0, pCur->nKey, pKey);
drh47ded162006-01-06 01:42:58 +0000532 if( rc==SQLITE_OK ){
danielk1977da184232006-01-05 11:34:32 +0000533 pCur->pKey = pKey;
534 }else{
535 sqliteFree(pKey);
536 }
537 }else{
538 rc = SQLITE_NOMEM;
539 }
540 }
541 assert( !pCur->pPage->intKey || !pCur->pKey );
542
543 /* Todo: Should we drop the reference to pCur->pPage here? */
544
545 if( rc==SQLITE_OK ){
546 pCur->eState = CURSOR_REQUIRESEEK;
547 }
548 }
549
550 return rc;
551}
552
553/*
554** Save the positions of all cursors except pExcept open on the table
555** with root-page iRoot. Usually, this is called just before cursor
556** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
557*/
558static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
559 BtCursor *p;
danielk1977e501b892006-01-09 06:29:47 +0000560 if( sqlite3ThreadData()->useSharedData ){
danielk1977da184232006-01-05 11:34:32 +0000561 for(p=pBt->pCursor; p; p=p->pNext){
562 if( p!=pExcept && p->pgnoRoot==iRoot && p->eState==CURSOR_VALID ){
563 int rc = saveCursorPosition(p);
564 if( SQLITE_OK!=rc ){
565 return rc;
566 }
567 }
568 }
569 }
570 return SQLITE_OK;
571}
572
573/*
574** Restore the cursor to the position it was in (or as close to as possible)
575** when saveCursorPosition() was called. Note that this call deletes the
576** saved position info stored by saveCursorPosition(), so there can be
577** at most one effective restoreCursorPosition() call after each
578** saveCursorPosition().
579**
580** If the second argument argument - doSeek - is false, then instead of
581** returning the cursor to it's saved position, any saved position is deleted
582** and the cursor state set to CURSOR_INVALID.
583*/
584static int restoreCursorPosition(BtCursor *pCur, int doSeek){
585 int rc = SQLITE_OK;
586 if( pCur->eState==CURSOR_REQUIRESEEK ){
danielk1977e501b892006-01-09 06:29:47 +0000587 assert( sqlite3ThreadData()->useSharedData );
danielk1977da184232006-01-05 11:34:32 +0000588 if( doSeek ){
589 rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, &pCur->skip);
590 }else{
591 pCur->eState = CURSOR_INVALID;
592 }
593 if( rc==SQLITE_OK ){
594 sqliteFree(pCur->pKey);
595 pCur->pKey = 0;
596 assert( CURSOR_VALID==pCur->eState || CURSOR_INVALID==pCur->eState );
597 }
598 }
599 return rc;
600}
601
602/*
danielk1977aef0bf62005-12-30 16:28:01 +0000603** Query to see if btree handle p may obtain a lock of type eLock
604** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
605** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
danielk1977c87d34d2006-01-06 13:00:28 +0000606** SQLITE_LOCKED if not.
danielk1977aef0bf62005-12-30 16:28:01 +0000607*/
608static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
609 BtShared *pBt = p->pBt;
610 BtLock *pIter;
611
danielk1977da184232006-01-05 11:34:32 +0000612 /* This is a no-op if the shared-cache is not enabled */
danielk1977e501b892006-01-09 06:29:47 +0000613 if( 0==sqlite3ThreadData()->useSharedData ){
danielk1977da184232006-01-05 11:34:32 +0000614 return SQLITE_OK;
615 }
616
617 /* This (along with lockTable()) is where the ReadUncommitted flag is
618 ** dealt with. If the caller is querying for a read-lock and the flag is
619 ** set, it is unconditionally granted - even if there are write-locks
620 ** on the table. If a write-lock is requested, the ReadUncommitted flag
621 ** is not considered.
622 **
623 ** In function lockTable(), if a read-lock is demanded and the
624 ** ReadUncommitted flag is set, no entry is added to the locks list
625 ** (BtShared.pLock).
626 **
627 ** To summarize: If the ReadUncommitted flag is set, then read cursors do
628 ** not create or respect table locks. The locking procedure for a
629 ** write-cursor does not change.
630 */
631 if(
632 !p->pSqlite ||
633 0==(p->pSqlite->flags&SQLITE_ReadUncommitted) ||
634 eLock==WRITE_LOCK ||
drh47ded162006-01-06 01:42:58 +0000635 iTab==MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000636 ){
637 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
638 if( pIter->pBtree!=p && pIter->iTable==iTab &&
639 (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
danielk1977c87d34d2006-01-06 13:00:28 +0000640 return SQLITE_LOCKED;
danielk1977da184232006-01-05 11:34:32 +0000641 }
danielk1977aef0bf62005-12-30 16:28:01 +0000642 }
643 }
644 return SQLITE_OK;
645}
646
647/*
648** Add a lock on the table with root-page iTable to the shared-btree used
649** by Btree handle p. Parameter eLock must be either READ_LOCK or
650** WRITE_LOCK.
651**
652** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
653** SQLITE_NOMEM may also be returned.
654*/
655static int lockTable(Btree *p, Pgno iTable, u8 eLock){
656 BtShared *pBt = p->pBt;
657 BtLock *pLock = 0;
658 BtLock *pIter;
659
danielk1977da184232006-01-05 11:34:32 +0000660 /* This is a no-op if the shared-cache is not enabled */
danielk1977e501b892006-01-09 06:29:47 +0000661 if( 0==sqlite3ThreadData()->useSharedData ){
danielk1977da184232006-01-05 11:34:32 +0000662 return SQLITE_OK;
663 }
664
danielk1977aef0bf62005-12-30 16:28:01 +0000665 assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
666
danielk1977da184232006-01-05 11:34:32 +0000667 /* If the read-uncommitted flag is set and a read-lock is requested,
668 ** return early without adding an entry to the BtShared.pLock list. See
669 ** comment in function queryTableLock() for more info on handling
670 ** the ReadUncommitted flag.
671 */
672 if(
673 (p->pSqlite) &&
674 (p->pSqlite->flags&SQLITE_ReadUncommitted) &&
675 (eLock==READ_LOCK) &&
drh47ded162006-01-06 01:42:58 +0000676 iTable!=MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000677 ){
678 return SQLITE_OK;
679 }
680
danielk1977aef0bf62005-12-30 16:28:01 +0000681 /* First search the list for an existing lock on this table. */
682 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
683 if( pIter->iTable==iTable && pIter->pBtree==p ){
684 pLock = pIter;
685 break;
686 }
687 }
688
689 /* If the above search did not find a BtLock struct associating Btree p
690 ** with table iTable, allocate one and link it into the list.
691 */
692 if( !pLock ){
693 pLock = (BtLock *)sqliteMalloc(sizeof(BtLock));
694 if( !pLock ){
695 return SQLITE_NOMEM;
696 }
697 pLock->iTable = iTable;
698 pLock->pBtree = p;
699 pLock->pNext = pBt->pLock;
700 pBt->pLock = pLock;
701 }
702
703 /* Set the BtLock.eLock variable to the maximum of the current lock
704 ** and the requested lock. This means if a write-lock was already held
705 ** and a read-lock requested, we don't incorrectly downgrade the lock.
706 */
707 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000708 if( eLock>pLock->eLock ){
709 pLock->eLock = eLock;
710 }
danielk1977aef0bf62005-12-30 16:28:01 +0000711
712 return SQLITE_OK;
713}
714
715/*
716** Release all the table locks (locks obtained via calls to the lockTable()
717** procedure) held by Btree handle p.
718*/
719static void unlockAllTables(Btree *p){
720 BtLock **ppIter = &p->pBt->pLock;
danielk1977da184232006-01-05 11:34:32 +0000721
722 /* If the shared-cache extension is not enabled, there should be no
723 ** locks in the BtShared.pLock list, making this procedure a no-op. Assert
724 ** that this is the case.
725 */
danielk1977e501b892006-01-09 06:29:47 +0000726 assert( sqlite3ThreadData()->useSharedData || 0==*ppIter );
danielk1977da184232006-01-05 11:34:32 +0000727
danielk1977aef0bf62005-12-30 16:28:01 +0000728 while( *ppIter ){
729 BtLock *pLock = *ppIter;
730 if( pLock->pBtree==p ){
731 *ppIter = pLock->pNext;
732 sqliteFree(pLock);
733 }else{
734 ppIter = &pLock->pNext;
735 }
736 }
737}
738#endif /* SQLITE_OMIT_SHARED_CACHE */
739
danielk1977599fcba2004-11-08 07:13:13 +0000740#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000741/*
drh42cac6d2004-11-20 20:31:11 +0000742** These macros define the location of the pointer-map entry for a
743** database page. The first argument to each is the number of usable
744** bytes on each page of the database (often 1024). The second is the
745** page number to look up in the pointer map.
danielk1977afcdd022004-10-31 16:25:42 +0000746**
747** PTRMAP_PAGENO returns the database page number of the pointer-map
748** page that stores the required pointer. PTRMAP_PTROFFSET returns
749** the offset of the requested map entry.
750**
751** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
752** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
danielk1977599fcba2004-11-08 07:13:13 +0000753** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
754** this test.
danielk1977afcdd022004-10-31 16:25:42 +0000755*/
756#define PTRMAP_PAGENO(pgsz, pgno) (((pgno-2)/(pgsz/5+1))*(pgsz/5+1)+2)
757#define PTRMAP_PTROFFSET(pgsz, pgno) (((pgno-2)%(pgsz/5+1)-1)*5)
danielk1977a19df672004-11-03 11:37:07 +0000758#define PTRMAP_ISPAGE(pgsz, pgno) (PTRMAP_PAGENO(pgsz,pgno)==pgno)
759
danielk1977afcdd022004-10-31 16:25:42 +0000760/*
drh615ae552005-01-16 23:21:00 +0000761** The pointer map is a lookup table that identifies the parent page for
762** each child page in the database file. The parent page is the page that
763** contains a pointer to the child. Every page in the database contains
764** 0 or 1 parent pages. (In this context 'database page' refers
765** to any page that is not part of the pointer map itself.) Each pointer map
766** entry consists of a single byte 'type' and a 4 byte parent page number.
767** The PTRMAP_XXX identifiers below are the valid types.
768**
769** The purpose of the pointer map is to facility moving pages from one
770** position in the file to another as part of autovacuum. When a page
771** is moved, the pointer in its parent must be updated to point to the
772** new location. The pointer map is used to locate the parent page quickly.
danielk1977afcdd022004-10-31 16:25:42 +0000773**
danielk1977687566d2004-11-02 12:56:41 +0000774** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
775** used in this case.
danielk1977afcdd022004-10-31 16:25:42 +0000776**
danielk1977687566d2004-11-02 12:56:41 +0000777** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
778** is not used in this case.
779**
780** PTRMAP_OVERFLOW1: The database page is the first page in a list of
781** overflow pages. The page number identifies the page that
782** contains the cell with a pointer to this overflow page.
783**
784** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
785** overflow pages. The page-number identifies the previous
786** page in the overflow page list.
787**
788** PTRMAP_BTREE: The database page is a non-root btree page. The page number
789** identifies the parent page in the btree.
danielk1977afcdd022004-10-31 16:25:42 +0000790*/
danielk1977687566d2004-11-02 12:56:41 +0000791#define PTRMAP_ROOTPAGE 1
792#define PTRMAP_FREEPAGE 2
793#define PTRMAP_OVERFLOW1 3
794#define PTRMAP_OVERFLOW2 4
795#define PTRMAP_BTREE 5
danielk1977afcdd022004-10-31 16:25:42 +0000796
797/*
798** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000799**
800** This routine updates the pointer map entry for page number 'key'
801** so that it maps to type 'eType' and parent page number 'pgno'.
802** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000803*/
danielk1977aef0bf62005-12-30 16:28:01 +0000804static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
danielk1977afcdd022004-10-31 16:25:42 +0000805 u8 *pPtrmap; /* The pointer map page */
806 Pgno iPtrmap; /* The pointer map page number */
807 int offset; /* Offset in pointer map page */
808 int rc;
809
danielk1977ac11ee62005-01-15 12:45:51 +0000810 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000811 if( key==0 ){
drh49285702005-09-17 15:20:26 +0000812 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000813 }
drh42cac6d2004-11-20 20:31:11 +0000814 iPtrmap = PTRMAP_PAGENO(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000815 rc = sqlite3pager_get(pBt->pPager, iPtrmap, (void **)&pPtrmap);
danielk1977687566d2004-11-02 12:56:41 +0000816 if( rc!=SQLITE_OK ){
danielk1977afcdd022004-10-31 16:25:42 +0000817 return rc;
818 }
drh42cac6d2004-11-20 20:31:11 +0000819 offset = PTRMAP_PTROFFSET(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000820
drh615ae552005-01-16 23:21:00 +0000821 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
822 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
danielk1977afcdd022004-10-31 16:25:42 +0000823 rc = sqlite3pager_write(pPtrmap);
danielk19775558a8a2005-01-17 07:53:44 +0000824 if( rc==SQLITE_OK ){
825 pPtrmap[offset] = eType;
826 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000827 }
danielk1977afcdd022004-10-31 16:25:42 +0000828 }
829
830 sqlite3pager_unref(pPtrmap);
danielk19775558a8a2005-01-17 07:53:44 +0000831 return rc;
danielk1977afcdd022004-10-31 16:25:42 +0000832}
833
834/*
835** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000836**
837** This routine retrieves the pointer map entry for page 'key', writing
838** the type and parent page number to *pEType and *pPgno respectively.
839** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000840*/
danielk1977aef0bf62005-12-30 16:28:01 +0000841static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk1977afcdd022004-10-31 16:25:42 +0000842 int iPtrmap; /* Pointer map page index */
843 u8 *pPtrmap; /* Pointer map page data */
844 int offset; /* Offset of entry in pointer map */
845 int rc;
846
drh42cac6d2004-11-20 20:31:11 +0000847 iPtrmap = PTRMAP_PAGENO(pBt->usableSize, key);
danielk1977afcdd022004-10-31 16:25:42 +0000848 rc = sqlite3pager_get(pBt->pPager, iPtrmap, (void **)&pPtrmap);
849 if( rc!=0 ){
850 return rc;
851 }
852
drh42cac6d2004-11-20 20:31:11 +0000853 offset = PTRMAP_PTROFFSET(pBt->usableSize, key);
danielk1977687566d2004-11-02 12:56:41 +0000854 if( pEType ) *pEType = pPtrmap[offset];
855 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000856
857 sqlite3pager_unref(pPtrmap);
drh49285702005-09-17 15:20:26 +0000858 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000859 return SQLITE_OK;
860}
861
862#endif /* SQLITE_OMIT_AUTOVACUUM */
863
drh0d316a42002-08-11 20:10:47 +0000864/*
drh271efa52004-05-30 19:19:05 +0000865** Given a btree page and a cell index (0 means the first cell on
866** the page, 1 means the second cell, and so forth) return a pointer
867** to the cell content.
868**
869** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000870*/
drh43605152004-05-29 21:46:49 +0000871static u8 *findCell(MemPage *pPage, int iCell){
872 u8 *data = pPage->aData;
873 assert( iCell>=0 );
874 assert( iCell<get2byte(&data[pPage->hdrOffset+3]) );
875 return data + get2byte(&data[pPage->cellOffset+2*iCell]);
876}
877
878/*
879** This a more complex version of findCell() that works for
880** pages that do contain overflow cells. See insert
881*/
882static u8 *findOverflowCell(MemPage *pPage, int iCell){
883 int i;
884 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000885 int k;
886 struct _OvflCell *pOvfl;
887 pOvfl = &pPage->aOvfl[i];
888 k = pOvfl->idx;
889 if( k<=iCell ){
890 if( k==iCell ){
891 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000892 }
893 iCell--;
894 }
895 }
896 return findCell(pPage, iCell);
897}
898
899/*
900** Parse a cell content block and fill in the CellInfo structure. There
901** are two versions of this function. parseCell() takes a cell index
902** as the second argument and parseCellPtr() takes a pointer to the
903** body of the cell as its second argument.
904*/
905static void parseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000906 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000907 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000908 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000909){
drh271efa52004-05-30 19:19:05 +0000910 int n; /* Number bytes in cell content header */
911 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000912
913 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000914 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000915 n = pPage->childPtrSize;
916 assert( n==4-4*pPage->leaf );
drh8b18dd42004-05-12 19:18:15 +0000917 if( pPage->hasData ){
drh271efa52004-05-30 19:19:05 +0000918 n += getVarint32(&pCell[n], &nPayload);
drh8b18dd42004-05-12 19:18:15 +0000919 }else{
drh271efa52004-05-30 19:19:05 +0000920 nPayload = 0;
drh3aac2dd2004-04-26 14:10:20 +0000921 }
danielk1977e0d4b062004-06-28 01:11:46 +0000922 n += getVarint(&pCell[n], (u64 *)&pInfo->nKey);
drh6f11bef2004-05-13 01:12:56 +0000923 pInfo->nHeader = n;
drh271efa52004-05-30 19:19:05 +0000924 pInfo->nData = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000925 if( !pPage->intKey ){
926 nPayload += pInfo->nKey;
927 }
drh271efa52004-05-30 19:19:05 +0000928 if( nPayload<=pPage->maxLocal ){
929 /* This is the (easy) common case where the entire payload fits
930 ** on the local page. No overflow is required.
931 */
932 int nSize; /* Total size of cell content in bytes */
drh6f11bef2004-05-13 01:12:56 +0000933 pInfo->nLocal = nPayload;
934 pInfo->iOverflow = 0;
drh271efa52004-05-30 19:19:05 +0000935 nSize = nPayload + n;
936 if( nSize<4 ){
937 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000938 }
drh271efa52004-05-30 19:19:05 +0000939 pInfo->nSize = nSize;
drh6f11bef2004-05-13 01:12:56 +0000940 }else{
drh271efa52004-05-30 19:19:05 +0000941 /* If the payload will not fit completely on the local page, we have
942 ** to decide how much to store locally and how much to spill onto
943 ** overflow pages. The strategy is to minimize the amount of unused
944 ** space on overflow pages while keeping the amount of local storage
945 ** in between minLocal and maxLocal.
946 **
947 ** Warning: changing the way overflow payload is distributed in any
948 ** way will result in an incompatible file format.
949 */
950 int minLocal; /* Minimum amount of payload held locally */
951 int maxLocal; /* Maximum amount of payload held locally */
952 int surplus; /* Overflow payload available for local storage */
953
954 minLocal = pPage->minLocal;
955 maxLocal = pPage->maxLocal;
956 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000957 if( surplus <= maxLocal ){
958 pInfo->nLocal = surplus;
959 }else{
960 pInfo->nLocal = minLocal;
961 }
962 pInfo->iOverflow = pInfo->nLocal + n;
963 pInfo->nSize = pInfo->iOverflow + 4;
964 }
drh3aac2dd2004-04-26 14:10:20 +0000965}
drh43605152004-05-29 21:46:49 +0000966static void parseCell(
967 MemPage *pPage, /* Page containing the cell */
968 int iCell, /* The cell index. First cell is 0 */
969 CellInfo *pInfo /* Fill in this structure */
970){
971 parseCellPtr(pPage, findCell(pPage, iCell), pInfo);
972}
drh3aac2dd2004-04-26 14:10:20 +0000973
974/*
drh43605152004-05-29 21:46:49 +0000975** Compute the total number of bytes that a Cell needs in the cell
976** data area of the btree-page. The return number includes the cell
977** data header and the local payload, but not any overflow page or
978** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000979*/
danielk1977bc6ada42004-06-30 08:20:16 +0000980#ifndef NDEBUG
drh43605152004-05-29 21:46:49 +0000981static int cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000982 CellInfo info;
drh43605152004-05-29 21:46:49 +0000983 parseCell(pPage, iCell, &info);
984 return info.nSize;
985}
danielk1977bc6ada42004-06-30 08:20:16 +0000986#endif
drh43605152004-05-29 21:46:49 +0000987static int cellSizePtr(MemPage *pPage, u8 *pCell){
988 CellInfo info;
989 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000990 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000991}
992
danielk197779a40da2005-01-16 08:00:01 +0000993#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +0000994/*
danielk197726836652005-01-17 01:33:13 +0000995** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +0000996** to an overflow page, insert an entry into the pointer-map
997** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +0000998*/
danielk197726836652005-01-17 01:33:13 +0000999static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
danielk197779a40da2005-01-16 08:00:01 +00001000 if( pCell ){
1001 CellInfo info;
1002 parseCellPtr(pPage, pCell, &info);
1003 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
1004 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
1005 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
1006 }
danielk1977ac11ee62005-01-15 12:45:51 +00001007 }
danielk197779a40da2005-01-16 08:00:01 +00001008 return SQLITE_OK;
danielk1977ac11ee62005-01-15 12:45:51 +00001009}
danielk197726836652005-01-17 01:33:13 +00001010/*
1011** If the cell with index iCell on page pPage contains a pointer
1012** to an overflow page, insert an entry into the pointer-map
1013** for the overflow page.
1014*/
1015static int ptrmapPutOvfl(MemPage *pPage, int iCell){
1016 u8 *pCell;
1017 pCell = findOverflowCell(pPage, iCell);
1018 return ptrmapPutOvflPtr(pPage, pCell);
1019}
danielk197779a40da2005-01-16 08:00:01 +00001020#endif
1021
danielk1977ac11ee62005-01-15 12:45:51 +00001022
1023/*
drhda200cc2004-05-09 11:51:38 +00001024** Do sanity checking on a page. Throw an exception if anything is
1025** not right.
1026**
1027** This routine is used for internal error checking only. It is omitted
1028** from most builds.
1029*/
1030#if defined(BTREE_DEBUG) && !defined(NDEBUG) && 0
1031static void _pageIntegrity(MemPage *pPage){
drhb6f41482004-05-14 01:58:11 +00001032 int usableSize;
drhda200cc2004-05-09 11:51:38 +00001033 u8 *data;
drh43605152004-05-29 21:46:49 +00001034 int i, j, idx, c, pc, hdr, nFree;
1035 int cellOffset;
1036 int nCell, cellLimit;
drh2e38c322004-09-03 18:38:44 +00001037 u8 *used;
drhda200cc2004-05-09 11:51:38 +00001038
drh2e38c322004-09-03 18:38:44 +00001039 used = sqliteMallocRaw( pPage->pBt->pageSize );
1040 if( used==0 ) return;
drhb6f41482004-05-14 01:58:11 +00001041 usableSize = pPage->pBt->usableSize;
drh07d183d2005-05-01 22:52:42 +00001042 assert( pPage->aData==&((unsigned char*)pPage)[-pPage->pBt->pageSize] );
drhda200cc2004-05-09 11:51:38 +00001043 hdr = pPage->hdrOffset;
1044 assert( hdr==(pPage->pgno==1 ? 100 : 0) );
1045 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
1046 c = pPage->aData[hdr];
1047 if( pPage->isInit ){
1048 assert( pPage->leaf == ((c & PTF_LEAF)!=0) );
1049 assert( pPage->zeroData == ((c & PTF_ZERODATA)!=0) );
drh8b18dd42004-05-12 19:18:15 +00001050 assert( pPage->leafData == ((c & PTF_LEAFDATA)!=0) );
1051 assert( pPage->intKey == ((c & (PTF_INTKEY|PTF_LEAFDATA))!=0) );
1052 assert( pPage->hasData ==
1053 !(pPage->zeroData || (!pPage->leaf && pPage->leafData)) );
drh43605152004-05-29 21:46:49 +00001054 assert( pPage->cellOffset==pPage->hdrOffset+12-4*pPage->leaf );
1055 assert( pPage->nCell = get2byte(&pPage->aData[hdr+3]) );
drhda200cc2004-05-09 11:51:38 +00001056 }
1057 data = pPage->aData;
drhb6f41482004-05-14 01:58:11 +00001058 memset(used, 0, usableSize);
drhda200cc2004-05-09 11:51:38 +00001059 for(i=0; i<hdr+10-pPage->leaf*4; i++) used[i] = 1;
1060 nFree = 0;
1061 pc = get2byte(&data[hdr+1]);
1062 while( pc ){
1063 int size;
drhb6f41482004-05-14 01:58:11 +00001064 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +00001065 size = get2byte(&data[pc+2]);
drhb6f41482004-05-14 01:58:11 +00001066 assert( pc+size<=usableSize );
drhda200cc2004-05-09 11:51:38 +00001067 nFree += size;
1068 for(i=pc; i<pc+size; i++){
1069 assert( used[i]==0 );
1070 used[i] = 1;
1071 }
1072 pc = get2byte(&data[pc]);
1073 }
drhda200cc2004-05-09 11:51:38 +00001074 idx = 0;
drh43605152004-05-29 21:46:49 +00001075 nCell = get2byte(&data[hdr+3]);
1076 cellLimit = get2byte(&data[hdr+5]);
1077 assert( pPage->isInit==0
1078 || pPage->nFree==nFree+data[hdr+7]+cellLimit-(cellOffset+2*nCell) );
1079 cellOffset = pPage->cellOffset;
1080 for(i=0; i<nCell; i++){
drhda200cc2004-05-09 11:51:38 +00001081 int size;
drh43605152004-05-29 21:46:49 +00001082 pc = get2byte(&data[cellOffset+2*i]);
drhb6f41482004-05-14 01:58:11 +00001083 assert( pc>0 && pc<usableSize-4 );
drhda200cc2004-05-09 11:51:38 +00001084 size = cellSize(pPage, &data[pc]);
drhb6f41482004-05-14 01:58:11 +00001085 assert( pc+size<=usableSize );
drh43605152004-05-29 21:46:49 +00001086 for(j=pc; j<pc+size; j++){
1087 assert( used[j]==0 );
1088 used[j] = 1;
drhda200cc2004-05-09 11:51:38 +00001089 }
drhda200cc2004-05-09 11:51:38 +00001090 }
drh43605152004-05-29 21:46:49 +00001091 for(i=cellOffset+2*nCell; i<cellimit; i++){
1092 assert( used[i]==0 );
1093 used[i] = 1;
1094 }
drhda200cc2004-05-09 11:51:38 +00001095 nFree = 0;
drhb6f41482004-05-14 01:58:11 +00001096 for(i=0; i<usableSize; i++){
drhda200cc2004-05-09 11:51:38 +00001097 assert( used[i]<=1 );
1098 if( used[i]==0 ) nFree++;
1099 }
drh43605152004-05-29 21:46:49 +00001100 assert( nFree==data[hdr+7] );
drh2e38c322004-09-03 18:38:44 +00001101 sqliteFree(used);
drhda200cc2004-05-09 11:51:38 +00001102}
1103#define pageIntegrity(X) _pageIntegrity(X)
1104#else
1105# define pageIntegrity(X)
1106#endif
1107
danielk1977aef0bf62005-12-30 16:28:01 +00001108/* A bunch of assert() statements to check the transaction state variables
1109** of handle p (type Btree*) are internally consistent.
1110*/
1111#define btreeIntegrity(p) \
1112 assert( p->inTrans!=TRANS_NONE || p->pBt->nTransaction<p->pBt->nRef ); \
1113 assert( p->pBt->nTransaction<=p->pBt->nRef ); \
1114 assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
1115 assert( p->pBt->inTransaction>=p->inTrans );
1116
drhda200cc2004-05-09 11:51:38 +00001117/*
drh72f82862001-05-24 21:06:34 +00001118** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +00001119** end of the page and all free space is collected into one
1120** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +00001121** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +00001122*/
drh2e38c322004-09-03 18:38:44 +00001123static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +00001124 int i; /* Loop counter */
1125 int pc; /* Address of a i-th cell */
1126 int addr; /* Offset of first byte after cell pointer array */
1127 int hdr; /* Offset to the page header */
1128 int size; /* Size of a cell */
1129 int usableSize; /* Number of usable bytes on a page */
1130 int cellOffset; /* Offset to the cell pointer array */
1131 int brk; /* Offset to the cell content area */
1132 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +00001133 unsigned char *data; /* The page data */
1134 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +00001135
drha34b6762004-05-07 13:30:42 +00001136 assert( sqlite3pager_iswriteable(pPage->aData) );
drh9e572e62004-04-23 23:43:10 +00001137 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +00001138 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +00001139 assert( pPage->nOverflow==0 );
drh2e38c322004-09-03 18:38:44 +00001140 temp = sqliteMalloc( pPage->pBt->pageSize );
1141 if( temp==0 ) return SQLITE_NOMEM;
drh43605152004-05-29 21:46:49 +00001142 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +00001143 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001144 cellOffset = pPage->cellOffset;
1145 nCell = pPage->nCell;
1146 assert( nCell==get2byte(&data[hdr+3]) );
1147 usableSize = pPage->pBt->usableSize;
1148 brk = get2byte(&data[hdr+5]);
1149 memcpy(&temp[brk], &data[brk], usableSize - brk);
1150 brk = usableSize;
1151 for(i=0; i<nCell; i++){
1152 u8 *pAddr; /* The i-th cell pointer */
1153 pAddr = &data[cellOffset + i*2];
1154 pc = get2byte(pAddr);
1155 assert( pc<pPage->pBt->usableSize );
1156 size = cellSizePtr(pPage, &temp[pc]);
1157 brk -= size;
1158 memcpy(&data[brk], &temp[pc], size);
1159 put2byte(pAddr, brk);
drh2af926b2001-05-15 00:39:25 +00001160 }
drh43605152004-05-29 21:46:49 +00001161 assert( brk>=cellOffset+2*nCell );
1162 put2byte(&data[hdr+5], brk);
1163 data[hdr+1] = 0;
1164 data[hdr+2] = 0;
1165 data[hdr+7] = 0;
1166 addr = cellOffset+2*nCell;
1167 memset(&data[addr], 0, brk-addr);
drh2e38c322004-09-03 18:38:44 +00001168 sqliteFree(temp);
1169 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +00001170}
1171
drha059ad02001-04-17 20:09:11 +00001172/*
drh43605152004-05-29 21:46:49 +00001173** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +00001174**
drh9e572e62004-04-23 23:43:10 +00001175** Return the index into pPage->aData[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +00001176** the new allocation. Or return 0 if there is not enough free
1177** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +00001178**
drh72f82862001-05-24 21:06:34 +00001179** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +00001180** nBytes of contiguous free space, then this routine automatically
1181** calls defragementPage() to consolidate all free space before
1182** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +00001183*/
drh9e572e62004-04-23 23:43:10 +00001184static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +00001185 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +00001186 int size;
drh24cd67e2004-05-10 16:18:47 +00001187 int nFrag;
drh43605152004-05-29 21:46:49 +00001188 int top;
1189 int nCell;
1190 int cellOffset;
drh9e572e62004-04-23 23:43:10 +00001191 unsigned char *data;
drh43605152004-05-29 21:46:49 +00001192
drh9e572e62004-04-23 23:43:10 +00001193 data = pPage->aData;
drha34b6762004-05-07 13:30:42 +00001194 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +00001195 assert( pPage->pBt );
1196 if( nByte<4 ) nByte = 4;
drh43605152004-05-29 21:46:49 +00001197 if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
1198 pPage->nFree -= nByte;
drh9e572e62004-04-23 23:43:10 +00001199 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001200
1201 nFrag = data[hdr+7];
1202 if( nFrag<60 ){
1203 /* Search the freelist looking for a slot big enough to satisfy the
1204 ** space request. */
1205 addr = hdr+1;
1206 while( (pc = get2byte(&data[addr]))>0 ){
1207 size = get2byte(&data[pc+2]);
1208 if( size>=nByte ){
1209 if( size<nByte+4 ){
1210 memcpy(&data[addr], &data[pc], 2);
1211 data[hdr+7] = nFrag + size - nByte;
1212 return pc;
1213 }else{
1214 put2byte(&data[pc+2], size-nByte);
1215 return pc + size - nByte;
1216 }
1217 }
1218 addr = pc;
drh9e572e62004-04-23 23:43:10 +00001219 }
1220 }
drh43605152004-05-29 21:46:49 +00001221
1222 /* Allocate memory from the gap in between the cell pointer array
1223 ** and the cell content area.
1224 */
1225 top = get2byte(&data[hdr+5]);
1226 nCell = get2byte(&data[hdr+3]);
1227 cellOffset = pPage->cellOffset;
1228 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
drh2e38c322004-09-03 18:38:44 +00001229 if( defragmentPage(pPage) ) return 0;
drh43605152004-05-29 21:46:49 +00001230 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +00001231 }
drh43605152004-05-29 21:46:49 +00001232 top -= nByte;
1233 assert( cellOffset + 2*nCell <= top );
1234 put2byte(&data[hdr+5], top);
1235 return top;
drh7e3b0a02001-04-28 16:52:40 +00001236}
1237
1238/*
drh9e572e62004-04-23 23:43:10 +00001239** Return a section of the pPage->aData to the freelist.
1240** The first byte of the new free block is pPage->aDisk[start]
1241** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +00001242**
1243** Most of the effort here is involved in coalesing adjacent
1244** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +00001245*/
drh9e572e62004-04-23 23:43:10 +00001246static void freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +00001247 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +00001248 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +00001249
drh9e572e62004-04-23 23:43:10 +00001250 assert( pPage->pBt!=0 );
drha34b6762004-05-07 13:30:42 +00001251 assert( sqlite3pager_iswriteable(data) );
drh9e572e62004-04-23 23:43:10 +00001252 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +00001253 assert( (start + size)<=pPage->pBt->usableSize );
drh9e572e62004-04-23 23:43:10 +00001254 if( size<4 ) size = 4;
1255
1256 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +00001257 hdr = pPage->hdrOffset;
1258 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +00001259 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +00001260 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +00001261 assert( pbegin>addr );
1262 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +00001263 }
drhb6f41482004-05-14 01:58:11 +00001264 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +00001265 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +00001266 put2byte(&data[addr], start);
1267 put2byte(&data[start], pbegin);
1268 put2byte(&data[start+2], size);
drh2af926b2001-05-15 00:39:25 +00001269 pPage->nFree += size;
drh9e572e62004-04-23 23:43:10 +00001270
1271 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +00001272 addr = pPage->hdrOffset + 1;
1273 while( (pbegin = get2byte(&data[addr]))>0 ){
drh9e572e62004-04-23 23:43:10 +00001274 int pnext, psize;
drh3aac2dd2004-04-26 14:10:20 +00001275 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +00001276 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +00001277 pnext = get2byte(&data[pbegin]);
1278 psize = get2byte(&data[pbegin+2]);
1279 if( pbegin + psize + 3 >= pnext && pnext>0 ){
1280 int frag = pnext - (pbegin+psize);
drh43605152004-05-29 21:46:49 +00001281 assert( frag<=data[pPage->hdrOffset+7] );
1282 data[pPage->hdrOffset+7] -= frag;
drh9e572e62004-04-23 23:43:10 +00001283 put2byte(&data[pbegin], get2byte(&data[pnext]));
1284 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
1285 }else{
drh3aac2dd2004-04-26 14:10:20 +00001286 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +00001287 }
1288 }
drh7e3b0a02001-04-28 16:52:40 +00001289
drh43605152004-05-29 21:46:49 +00001290 /* If the cell content area begins with a freeblock, remove it. */
1291 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
1292 int top;
1293 pbegin = get2byte(&data[hdr+1]);
1294 memcpy(&data[hdr+1], &data[pbegin], 2);
1295 top = get2byte(&data[hdr+5]);
1296 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
drh4b70f112004-05-02 21:12:19 +00001297 }
drh4b70f112004-05-02 21:12:19 +00001298}
1299
1300/*
drh271efa52004-05-30 19:19:05 +00001301** Decode the flags byte (the first byte of the header) for a page
1302** and initialize fields of the MemPage structure accordingly.
1303*/
1304static void decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +00001305 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +00001306
1307 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
1308 pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
1309 pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
1310 pPage->leaf = (flagByte & PTF_LEAF)!=0;
1311 pPage->childPtrSize = 4*(pPage->leaf==0);
1312 pBt = pPage->pBt;
1313 if( flagByte & PTF_LEAFDATA ){
1314 pPage->leafData = 1;
1315 pPage->maxLocal = pBt->maxLeaf;
1316 pPage->minLocal = pBt->minLeaf;
1317 }else{
1318 pPage->leafData = 0;
1319 pPage->maxLocal = pBt->maxLocal;
1320 pPage->minLocal = pBt->minLocal;
1321 }
1322 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
1323}
1324
1325/*
drh7e3b0a02001-04-28 16:52:40 +00001326** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001327**
drhbd03cae2001-06-02 02:40:57 +00001328** The pParent parameter must be a pointer to the MemPage which
drh9e572e62004-04-23 23:43:10 +00001329** is the parent of the page being initialized. The root of a
1330** BTree has no parent and so for that page, pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +00001331**
drh72f82862001-05-24 21:06:34 +00001332** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001333** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001334** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1335** guarantee that the page is well-formed. It only shows that
1336** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001337*/
drh9e572e62004-04-23 23:43:10 +00001338static int initPage(
drh3aac2dd2004-04-26 14:10:20 +00001339 MemPage *pPage, /* The page to be initialized */
drh9e572e62004-04-23 23:43:10 +00001340 MemPage *pParent /* The parent. Might be NULL */
1341){
drh271efa52004-05-30 19:19:05 +00001342 int pc; /* Address of a freeblock within pPage->aData[] */
drh271efa52004-05-30 19:19:05 +00001343 int hdr; /* Offset to beginning of page header */
1344 u8 *data; /* Equal to pPage->aData */
danielk1977aef0bf62005-12-30 16:28:01 +00001345 BtShared *pBt; /* The main btree structure */
drh271efa52004-05-30 19:19:05 +00001346 int usableSize; /* Amount of usable space on each page */
1347 int cellOffset; /* Offset from start of page to first cell pointer */
1348 int nFree; /* Number of unused bytes on the page */
1349 int top; /* First byte of the cell content area */
drh2af926b2001-05-15 00:39:25 +00001350
drh2e38c322004-09-03 18:38:44 +00001351 pBt = pPage->pBt;
1352 assert( pBt!=0 );
1353 assert( pParent==0 || pParent->pBt==pBt );
drha34b6762004-05-07 13:30:42 +00001354 assert( pPage->pgno==sqlite3pager_pagenumber(pPage->aData) );
drh07d183d2005-05-01 22:52:42 +00001355 assert( pPage->aData == &((unsigned char*)pPage)[-pBt->pageSize] );
drhee696e22004-08-30 16:52:17 +00001356 if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
1357 /* The parent page should never change unless the file is corrupt */
drh49285702005-09-17 15:20:26 +00001358 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001359 }
drh10617cd2004-05-14 15:27:27 +00001360 if( pPage->isInit ) return SQLITE_OK;
drhda200cc2004-05-09 11:51:38 +00001361 if( pPage->pParent==0 && pParent!=0 ){
1362 pPage->pParent = pParent;
drha34b6762004-05-07 13:30:42 +00001363 sqlite3pager_ref(pParent->aData);
drh5e2f8b92001-05-28 00:41:15 +00001364 }
drhde647132004-05-07 17:57:49 +00001365 hdr = pPage->hdrOffset;
drha34b6762004-05-07 13:30:42 +00001366 data = pPage->aData;
drh271efa52004-05-30 19:19:05 +00001367 decodeFlags(pPage, data[hdr]);
drh43605152004-05-29 21:46:49 +00001368 pPage->nOverflow = 0;
drhc8629a12004-05-08 20:07:40 +00001369 pPage->idxShift = 0;
drh2e38c322004-09-03 18:38:44 +00001370 usableSize = pBt->usableSize;
drh43605152004-05-29 21:46:49 +00001371 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
1372 top = get2byte(&data[hdr+5]);
1373 pPage->nCell = get2byte(&data[hdr+3]);
drh2e38c322004-09-03 18:38:44 +00001374 if( pPage->nCell>MX_CELL(pBt) ){
drhee696e22004-08-30 16:52:17 +00001375 /* To many cells for a single page. The page must be corrupt */
drh49285702005-09-17 15:20:26 +00001376 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001377 }
1378 if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
1379 /* All pages must have at least one cell, except for root pages */
drh49285702005-09-17 15:20:26 +00001380 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001381 }
drh9e572e62004-04-23 23:43:10 +00001382
1383 /* Compute the total free space on the page */
drh9e572e62004-04-23 23:43:10 +00001384 pc = get2byte(&data[hdr+1]);
drh43605152004-05-29 21:46:49 +00001385 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
drh9e572e62004-04-23 23:43:10 +00001386 while( pc>0 ){
1387 int next, size;
drhee696e22004-08-30 16:52:17 +00001388 if( pc>usableSize-4 ){
1389 /* Free block is off the page */
drh49285702005-09-17 15:20:26 +00001390 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001391 }
drh9e572e62004-04-23 23:43:10 +00001392 next = get2byte(&data[pc]);
1393 size = get2byte(&data[pc+2]);
drhee696e22004-08-30 16:52:17 +00001394 if( next>0 && next<=pc+size+3 ){
1395 /* Free blocks must be in accending order */
drh49285702005-09-17 15:20:26 +00001396 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001397 }
drh3add3672004-05-15 00:29:24 +00001398 nFree += size;
drh9e572e62004-04-23 23:43:10 +00001399 pc = next;
1400 }
drh3add3672004-05-15 00:29:24 +00001401 pPage->nFree = nFree;
drhee696e22004-08-30 16:52:17 +00001402 if( nFree>=usableSize ){
1403 /* Free space cannot exceed total page size */
drh49285702005-09-17 15:20:26 +00001404 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001405 }
drh9e572e62004-04-23 23:43:10 +00001406
drhde647132004-05-07 17:57:49 +00001407 pPage->isInit = 1;
drhda200cc2004-05-09 11:51:38 +00001408 pageIntegrity(pPage);
drh9e572e62004-04-23 23:43:10 +00001409 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001410}
1411
1412/*
drh8b2f49b2001-06-08 00:21:52 +00001413** Set up a raw page so that it looks like a database page holding
1414** no entries.
drhbd03cae2001-06-02 02:40:57 +00001415*/
drh9e572e62004-04-23 23:43:10 +00001416static void zeroPage(MemPage *pPage, int flags){
1417 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001418 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00001419 int hdr = pPage->hdrOffset;
drh9e572e62004-04-23 23:43:10 +00001420 int first;
1421
drhda200cc2004-05-09 11:51:38 +00001422 assert( sqlite3pager_pagenumber(data)==pPage->pgno );
drh07d183d2005-05-01 22:52:42 +00001423 assert( &data[pBt->pageSize] == (unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +00001424 assert( sqlite3pager_iswriteable(data) );
drhb6f41482004-05-14 01:58:11 +00001425 memset(&data[hdr], 0, pBt->usableSize - hdr);
drh9e572e62004-04-23 23:43:10 +00001426 data[hdr] = flags;
drh43605152004-05-29 21:46:49 +00001427 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
1428 memset(&data[hdr+1], 0, 4);
1429 data[hdr+7] = 0;
1430 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +00001431 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +00001432 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +00001433 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +00001434 pPage->cellOffset = first;
1435 pPage->nOverflow = 0;
drhda200cc2004-05-09 11:51:38 +00001436 pPage->idxShift = 0;
drh43605152004-05-29 21:46:49 +00001437 pPage->nCell = 0;
drhda200cc2004-05-09 11:51:38 +00001438 pPage->isInit = 1;
1439 pageIntegrity(pPage);
drhbd03cae2001-06-02 02:40:57 +00001440}
1441
1442/*
drh3aac2dd2004-04-26 14:10:20 +00001443** Get a page from the pager. Initialize the MemPage.pBt and
1444** MemPage.aData elements if needed.
1445*/
danielk1977aef0bf62005-12-30 16:28:01 +00001446static int getPage(BtShared *pBt, Pgno pgno, MemPage **ppPage){
drh3aac2dd2004-04-26 14:10:20 +00001447 int rc;
1448 unsigned char *aData;
1449 MemPage *pPage;
drha34b6762004-05-07 13:30:42 +00001450 rc = sqlite3pager_get(pBt->pPager, pgno, (void**)&aData);
drh3aac2dd2004-04-26 14:10:20 +00001451 if( rc ) return rc;
drh07d183d2005-05-01 22:52:42 +00001452 pPage = (MemPage*)&aData[pBt->pageSize];
drh3aac2dd2004-04-26 14:10:20 +00001453 pPage->aData = aData;
1454 pPage->pBt = pBt;
1455 pPage->pgno = pgno;
drhde647132004-05-07 17:57:49 +00001456 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
drh3aac2dd2004-04-26 14:10:20 +00001457 *ppPage = pPage;
1458 return SQLITE_OK;
1459}
1460
1461/*
drhde647132004-05-07 17:57:49 +00001462** Get a page from the pager and initialize it. This routine
1463** is just a convenience wrapper around separate calls to
1464** getPage() and initPage().
1465*/
1466static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +00001467 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +00001468 Pgno pgno, /* Number of the page to get */
1469 MemPage **ppPage, /* Write the page pointer here */
1470 MemPage *pParent /* Parent of the page */
1471){
1472 int rc;
drhee696e22004-08-30 16:52:17 +00001473 if( pgno==0 ){
drh49285702005-09-17 15:20:26 +00001474 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001475 }
drhde647132004-05-07 17:57:49 +00001476 rc = getPage(pBt, pgno, ppPage);
drh10617cd2004-05-14 15:27:27 +00001477 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
drhde647132004-05-07 17:57:49 +00001478 rc = initPage(*ppPage, pParent);
1479 }
1480 return rc;
1481}
1482
1483/*
drh3aac2dd2004-04-26 14:10:20 +00001484** Release a MemPage. This should be called once for each prior
1485** call to getPage.
1486*/
drh4b70f112004-05-02 21:12:19 +00001487static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001488 if( pPage ){
1489 assert( pPage->aData );
1490 assert( pPage->pBt );
drh07d183d2005-05-01 22:52:42 +00001491 assert( &pPage->aData[pPage->pBt->pageSize]==(unsigned char*)pPage );
drha34b6762004-05-07 13:30:42 +00001492 sqlite3pager_unref(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00001493 }
1494}
1495
1496/*
drh72f82862001-05-24 21:06:34 +00001497** This routine is called when the reference count for a page
1498** reaches zero. We need to unref the pParent pointer when that
1499** happens.
1500*/
drhb6f41482004-05-14 01:58:11 +00001501static void pageDestructor(void *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +00001502 MemPage *pPage;
1503 assert( (pageSize & 7)==0 );
1504 pPage = (MemPage*)&((char*)pData)[pageSize];
drh72f82862001-05-24 21:06:34 +00001505 if( pPage->pParent ){
1506 MemPage *pParent = pPage->pParent;
1507 pPage->pParent = 0;
drha34b6762004-05-07 13:30:42 +00001508 releasePage(pParent);
drh72f82862001-05-24 21:06:34 +00001509 }
drh3aac2dd2004-04-26 14:10:20 +00001510 pPage->isInit = 0;
drh72f82862001-05-24 21:06:34 +00001511}
1512
1513/*
drha6abd042004-06-09 17:37:22 +00001514** During a rollback, when the pager reloads information into the cache
1515** so that the cache is restored to its original state at the start of
1516** the transaction, for each page restored this routine is called.
1517**
1518** This routine needs to reset the extra data section at the end of the
1519** page to agree with the restored data.
1520*/
1521static void pageReinit(void *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +00001522 MemPage *pPage;
1523 assert( (pageSize & 7)==0 );
1524 pPage = (MemPage*)&((char*)pData)[pageSize];
drha6abd042004-06-09 17:37:22 +00001525 if( pPage->isInit ){
1526 pPage->isInit = 0;
1527 initPage(pPage, pPage->pParent);
1528 }
1529}
1530
1531/*
drhad3e0102004-09-03 23:32:18 +00001532** Open a database file.
1533**
drh382c0242001-10-06 16:33:02 +00001534** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001535** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001536** database file will be deleted when sqlite3BtreeClose() is called.
drha059ad02001-04-17 20:09:11 +00001537*/
drh23e11ca2004-05-04 17:27:28 +00001538int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001539 const char *zFilename, /* Name of the file containing the BTree database */
danielk1977aef0bf62005-12-30 16:28:01 +00001540 sqlite3 *pSqlite, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001541 Btree **ppBtree, /* Pointer to new Btree object written here */
drh90f5ecb2004-07-22 01:19:35 +00001542 int flags /* Options */
drh6019e162001-07-02 17:51:45 +00001543){
danielk1977aef0bf62005-12-30 16:28:01 +00001544 BtShared *pBt; /* Shared part of btree structure */
1545 Btree *p; /* Handle to return */
drha34b6762004-05-07 13:30:42 +00001546 int rc;
drh90f5ecb2004-07-22 01:19:35 +00001547 int nReserve;
1548 unsigned char zDbHeader[100];
danielk1977da184232006-01-05 11:34:32 +00001549#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977e501b892006-01-09 06:29:47 +00001550 ThreadData *pTsd = sqlite3ThreadData();
danielk1977da184232006-01-05 11:34:32 +00001551#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001552
1553 /* Set the variable isMemdb to true for an in-memory database, or
1554 ** false for a file-based database. This symbol is only required if
1555 ** either of the shared-data or autovacuum features are compiled
1556 ** into the library.
1557 */
1558#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1559 #ifdef SQLITE_OMIT_MEMORYDB
1560 const int isMemdb = !zFilename;
1561 #else
1562 const int isMemdb = !zFilename || (strcmp(zFilename, ":memory:")?0:1);
1563 #endif
1564#endif
1565
1566 p = sqliteMalloc(sizeof(Btree));
1567 if( !p ){
1568 return SQLITE_NOMEM;
1569 }
1570 p->inTrans = TRANS_NONE;
1571 p->pSqlite = pSqlite;
1572
1573 /* Try to find an existing Btree structure opened on zFilename. */
drh198bf392006-01-06 21:52:49 +00001574#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
danielk1977aef0bf62005-12-30 16:28:01 +00001575 if( pTsd->useSharedData && zFilename && !isMemdb ){
drh66560ad2006-01-06 14:32:19 +00001576 char *zFullPathname = sqlite3OsFullPathname(zFilename);
danielk1977aef0bf62005-12-30 16:28:01 +00001577 if( !zFullPathname ){
1578 sqliteFree(p);
1579 return SQLITE_NOMEM;
1580 }
1581 for(pBt=pTsd->pBtree; pBt; pBt=pBt->pNext){
danielk1977b82e7ed2006-01-11 14:09:31 +00001582 assert( pBt->nRef>0 );
danielk1977aef0bf62005-12-30 16:28:01 +00001583 if( 0==strcmp(zFullPathname, sqlite3pager_filename(pBt->pPager)) ){
1584 p->pBt = pBt;
1585 *ppBtree = p;
1586 pBt->nRef++;
1587 sqliteFree(zFullPathname);
1588 return SQLITE_OK;
1589 }
1590 }
1591 sqliteFree(zFullPathname);
1592 }
1593#endif
drha059ad02001-04-17 20:09:11 +00001594
drhd62d3d02003-01-24 12:14:20 +00001595 /*
1596 ** The following asserts make sure that structures used by the btree are
1597 ** the right size. This is to guard against size changes that result
1598 ** when compiling on a different architecture.
1599 */
drh4a1c3802004-05-12 15:15:47 +00001600 assert( sizeof(i64)==8 );
drh9e572e62004-04-23 23:43:10 +00001601 assert( sizeof(u64)==8 );
drhd62d3d02003-01-24 12:14:20 +00001602 assert( sizeof(u32)==4 );
1603 assert( sizeof(u16)==2 );
1604 assert( sizeof(Pgno)==4 );
drhd62d3d02003-01-24 12:14:20 +00001605
drha059ad02001-04-17 20:09:11 +00001606 pBt = sqliteMalloc( sizeof(*pBt) );
1607 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +00001608 *ppBtree = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00001609 sqliteFree(p);
drha059ad02001-04-17 20:09:11 +00001610 return SQLITE_NOMEM;
1611 }
drh7bec5052005-02-06 02:45:41 +00001612 rc = sqlite3pager_open(&pBt->pPager, zFilename, EXTRA_SIZE, flags);
drha059ad02001-04-17 20:09:11 +00001613 if( rc!=SQLITE_OK ){
drha34b6762004-05-07 13:30:42 +00001614 if( pBt->pPager ) sqlite3pager_close(pBt->pPager);
drha059ad02001-04-17 20:09:11 +00001615 sqliteFree(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00001616 sqliteFree(p);
drha059ad02001-04-17 20:09:11 +00001617 *ppBtree = 0;
1618 return rc;
1619 }
danielk1977aef0bf62005-12-30 16:28:01 +00001620 p->pBt = pBt;
1621
drha34b6762004-05-07 13:30:42 +00001622 sqlite3pager_set_destructor(pBt->pPager, pageDestructor);
drha6abd042004-06-09 17:37:22 +00001623 sqlite3pager_set_reiniter(pBt->pPager, pageReinit);
drha059ad02001-04-17 20:09:11 +00001624 pBt->pCursor = 0;
drha34b6762004-05-07 13:30:42 +00001625 pBt->pPage1 = 0;
1626 pBt->readOnly = sqlite3pager_isreadonly(pBt->pPager);
drh90f5ecb2004-07-22 01:19:35 +00001627 sqlite3pager_read_fileheader(pBt->pPager, sizeof(zDbHeader), zDbHeader);
1628 pBt->pageSize = get2byte(&zDbHeader[16]);
drh07d183d2005-05-01 22:52:42 +00001629 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1630 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
drh90f5ecb2004-07-22 01:19:35 +00001631 pBt->pageSize = SQLITE_DEFAULT_PAGE_SIZE;
1632 pBt->maxEmbedFrac = 64; /* 25% */
1633 pBt->minEmbedFrac = 32; /* 12.5% */
1634 pBt->minLeafFrac = 32; /* 12.5% */
drheee46cf2004-11-06 00:02:48 +00001635#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197703aded42004-11-22 05:26:27 +00001636 /* If the magic name ":memory:" will create an in-memory database, then
1637 ** do not set the auto-vacuum flag, even if SQLITE_DEFAULT_AUTOVACUUM
1638 ** is true. On the other hand, if SQLITE_OMIT_MEMORYDB has been defined,
1639 ** then ":memory:" is just a regular file-name. Respect the auto-vacuum
1640 ** default in this case.
1641 */
danielk1977aef0bf62005-12-30 16:28:01 +00001642 if( zFilename && !isMemdb ){
danielk1977951af802004-11-05 15:45:09 +00001643 pBt->autoVacuum = SQLITE_DEFAULT_AUTOVACUUM;
1644 }
drheee46cf2004-11-06 00:02:48 +00001645#endif
drh90f5ecb2004-07-22 01:19:35 +00001646 nReserve = 0;
1647 }else{
1648 nReserve = zDbHeader[20];
1649 pBt->maxEmbedFrac = zDbHeader[21];
1650 pBt->minEmbedFrac = zDbHeader[22];
1651 pBt->minLeafFrac = zDbHeader[23];
1652 pBt->pageSizeFixed = 1;
danielk1977951af802004-11-05 15:45:09 +00001653#ifndef SQLITE_OMIT_AUTOVACUUM
1654 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1655#endif
drh90f5ecb2004-07-22 01:19:35 +00001656 }
1657 pBt->usableSize = pBt->pageSize - nReserve;
drh07d183d2005-05-01 22:52:42 +00001658 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
drh90f5ecb2004-07-22 01:19:35 +00001659 sqlite3pager_set_pagesize(pBt->pPager, pBt->pageSize);
danielk1977aef0bf62005-12-30 16:28:01 +00001660
1661#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977e501b892006-01-09 06:29:47 +00001662 /* Add the new btree to the linked list starting at ThreadData.pBtree */
danielk1977aef0bf62005-12-30 16:28:01 +00001663 if( pTsd->useSharedData && zFilename && !isMemdb ){
1664 pBt->pNext = pTsd->pBtree;
1665 pTsd->pBtree = pBt;
1666 }
danielk1977aef0bf62005-12-30 16:28:01 +00001667#endif
danielk1977da184232006-01-05 11:34:32 +00001668 pBt->nRef = 1;
danielk1977aef0bf62005-12-30 16:28:01 +00001669 *ppBtree = p;
drha059ad02001-04-17 20:09:11 +00001670 return SQLITE_OK;
1671}
1672
1673/*
1674** Close an open database and invalidate all cursors.
1675*/
danielk1977aef0bf62005-12-30 16:28:01 +00001676int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00001677 BtShared *pBt = p->pBt;
1678 BtCursor *pCur;
1679
danielk1977da184232006-01-05 11:34:32 +00001680#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977e501b892006-01-09 06:29:47 +00001681 ThreadData *pTsd = sqlite3ThreadData();
danielk1977da184232006-01-05 11:34:32 +00001682#endif
1683
danielk1977aef0bf62005-12-30 16:28:01 +00001684 /* Drop any table-locks */
1685 unlockAllTables(p);
1686
1687 /* Close all cursors opened via this handle. */
1688 pCur = pBt->pCursor;
1689 while( pCur ){
1690 BtCursor *pTmp = pCur;
1691 pCur = pCur->pNext;
1692 if( pTmp->pBtree==p ){
1693 sqlite3BtreeCloseCursor(pTmp);
1694 }
drha059ad02001-04-17 20:09:11 +00001695 }
danielk1977aef0bf62005-12-30 16:28:01 +00001696
1697 sqliteFree(p);
1698
1699#ifndef SQLITE_OMIT_SHARED_CACHE
1700 /* If there are still other outstanding references to the shared-btree
1701 ** structure, return now. The remainder of this procedure cleans
1702 ** up the shared-btree.
1703 */
1704 assert( pBt->nRef>0 );
1705 pBt->nRef--;
1706 if( pBt->nRef ){
1707 return SQLITE_OK;
1708 }
1709
1710 /* Remove the shared-btree from the thread wide list */
1711 if( pTsd->pBtree==pBt ){
1712 pTsd->pBtree = pBt->pNext;
1713 }else{
1714 BtShared *pPrev;
1715 for(pPrev=pTsd->pBtree; pPrev && pPrev->pNext!=pBt; pPrev=pPrev->pNext);
1716 if( pPrev ){
1717 pPrev->pNext = pBt->pNext;
1718 }
1719 }
1720#endif
1721
1722 /* Close the pager and free the shared-btree structure */
1723 assert( !pBt->pCursor );
drha34b6762004-05-07 13:30:42 +00001724 sqlite3pager_close(pBt->pPager);
danielk1977da184232006-01-05 11:34:32 +00001725 if( pBt->xFreeSchema && pBt->pSchema ){
1726 pBt->xFreeSchema(pBt->pSchema);
1727 }
danielk1977de0fe3e2006-01-06 06:33:12 +00001728 sqliteFree(pBt->pSchema);
drha059ad02001-04-17 20:09:11 +00001729 sqliteFree(pBt);
1730 return SQLITE_OK;
1731}
1732
1733/*
drh90f5ecb2004-07-22 01:19:35 +00001734** Change the busy handler callback function.
1735*/
danielk1977aef0bf62005-12-30 16:28:01 +00001736int sqlite3BtreeSetBusyHandler(Btree *p, BusyHandler *pHandler){
1737 BtShared *pBt = p->pBt;
drhb8ef32c2005-03-14 02:01:49 +00001738 pBt->pBusyHandler = pHandler;
drh90f5ecb2004-07-22 01:19:35 +00001739 sqlite3pager_set_busyhandler(pBt->pPager, pHandler);
1740 return SQLITE_OK;
1741}
1742
1743/*
drhda47d772002-12-02 04:25:19 +00001744** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001745**
1746** The maximum number of cache pages is set to the absolute
1747** value of mxPage. If mxPage is negative, the pager will
1748** operate asynchronously - it will not stop to do fsync()s
1749** to insure data is written to the disk surface before
1750** continuing. Transactions still work if synchronous is off,
1751** and the database cannot be corrupted if this program
1752** crashes. But if the operating system crashes or there is
1753** an abrupt power failure when synchronous is off, the database
1754** could be left in an inconsistent and unrecoverable state.
1755** Synchronous is on by default so database corruption is not
1756** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001757*/
danielk1977aef0bf62005-12-30 16:28:01 +00001758int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
1759 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00001760 sqlite3pager_set_cachesize(pBt->pPager, mxPage);
drhf57b14a2001-09-14 18:54:08 +00001761 return SQLITE_OK;
1762}
1763
1764/*
drh973b6e32003-02-12 14:09:42 +00001765** Change the way data is synced to disk in order to increase or decrease
1766** how well the database resists damage due to OS crashes and power
1767** failures. Level 1 is the same as asynchronous (no syncs() occur and
1768** there is a high probability of damage) Level 2 is the default. There
1769** is a very low but non-zero probability of damage. Level 3 reduces the
1770** probability of damage to near zero but with a write performance reduction.
1771*/
danielk197793758c82005-01-21 08:13:14 +00001772#ifndef SQLITE_OMIT_PAGER_PRAGMAS
danielk1977aef0bf62005-12-30 16:28:01 +00001773int sqlite3BtreeSetSafetyLevel(Btree *p, int level){
1774 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00001775 sqlite3pager_set_safety_level(pBt->pPager, level);
drh973b6e32003-02-12 14:09:42 +00001776 return SQLITE_OK;
1777}
danielk197793758c82005-01-21 08:13:14 +00001778#endif
drh973b6e32003-02-12 14:09:42 +00001779
drh2c8997b2005-08-27 16:36:48 +00001780/*
1781** Return TRUE if the given btree is set to safety level 1. In other
1782** words, return TRUE if no sync() occurs on the disk files.
1783*/
danielk1977aef0bf62005-12-30 16:28:01 +00001784int sqlite3BtreeSyncDisabled(Btree *p){
1785 BtShared *pBt = p->pBt;
drh2c8997b2005-08-27 16:36:48 +00001786 assert( pBt && pBt->pPager );
1787 return sqlite3pager_nosync(pBt->pPager);
1788}
1789
danielk1977576ec6b2005-01-21 11:55:25 +00001790#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001791/*
drh90f5ecb2004-07-22 01:19:35 +00001792** Change the default pages size and the number of reserved bytes per page.
drh06f50212004-11-02 14:24:33 +00001793**
1794** The page size must be a power of 2 between 512 and 65536. If the page
1795** size supplied does not meet this constraint then the page size is not
1796** changed.
1797**
1798** Page sizes are constrained to be a power of two so that the region
1799** of the database file used for locking (beginning at PENDING_BYTE,
1800** the first byte past the 1GB boundary, 0x40000000) needs to occur
1801** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001802**
1803** If parameter nReserve is less than zero, then the number of reserved
1804** bytes per page is left unchanged.
drh90f5ecb2004-07-22 01:19:35 +00001805*/
danielk1977aef0bf62005-12-30 16:28:01 +00001806int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
1807 BtShared *pBt = p->pBt;
drh90f5ecb2004-07-22 01:19:35 +00001808 if( pBt->pageSizeFixed ){
1809 return SQLITE_READONLY;
1810 }
1811 if( nReserve<0 ){
1812 nReserve = pBt->pageSize - pBt->usableSize;
1813 }
drh06f50212004-11-02 14:24:33 +00001814 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
1815 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00001816 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00001817 assert( !pBt->pPage1 && !pBt->pCursor );
drh1c7880e2005-05-20 20:01:55 +00001818 pBt->pageSize = sqlite3pager_set_pagesize(pBt->pPager, pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001819 }
1820 pBt->usableSize = pBt->pageSize - nReserve;
1821 return SQLITE_OK;
1822}
1823
1824/*
1825** Return the currently defined page size
1826*/
danielk1977aef0bf62005-12-30 16:28:01 +00001827int sqlite3BtreeGetPageSize(Btree *p){
1828 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00001829}
danielk1977aef0bf62005-12-30 16:28:01 +00001830int sqlite3BtreeGetReserve(Btree *p){
1831 return p->pBt->pageSize - p->pBt->usableSize;
drh2011d5f2004-07-22 02:40:37 +00001832}
danielk1977576ec6b2005-01-21 11:55:25 +00001833#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00001834
1835/*
danielk1977951af802004-11-05 15:45:09 +00001836** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
1837** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
1838** is disabled. The default value for the auto-vacuum property is
1839** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
1840*/
danielk1977aef0bf62005-12-30 16:28:01 +00001841int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
1842 BtShared *pBt = p->pBt;;
danielk1977951af802004-11-05 15:45:09 +00001843#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001844 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00001845#else
1846 if( pBt->pageSizeFixed ){
1847 return SQLITE_READONLY;
1848 }
1849 pBt->autoVacuum = (autoVacuum?1:0);
1850 return SQLITE_OK;
1851#endif
1852}
1853
1854/*
1855** Return the value of the 'auto-vacuum' property. If auto-vacuum is
1856** enabled 1 is returned. Otherwise 0.
1857*/
danielk1977aef0bf62005-12-30 16:28:01 +00001858int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00001859#ifdef SQLITE_OMIT_AUTOVACUUM
1860 return 0;
1861#else
danielk1977aef0bf62005-12-30 16:28:01 +00001862 return p->pBt->autoVacuum;
danielk1977951af802004-11-05 15:45:09 +00001863#endif
1864}
1865
1866
1867/*
drha34b6762004-05-07 13:30:42 +00001868** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001869** also acquire a readlock on that file.
1870**
1871** SQLITE_OK is returned on success. If the file is not a
1872** well-formed database file, then SQLITE_CORRUPT is returned.
1873** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
1874** is returned if we run out of memory. SQLITE_PROTOCOL is returned
1875** if there is a locking protocol violation.
1876*/
danielk1977aef0bf62005-12-30 16:28:01 +00001877static int lockBtree(BtShared *pBt){
drh07d183d2005-05-01 22:52:42 +00001878 int rc, pageSize;
drh3aac2dd2004-04-26 14:10:20 +00001879 MemPage *pPage1;
drha34b6762004-05-07 13:30:42 +00001880 if( pBt->pPage1 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001881 rc = getPage(pBt, 1, &pPage1);
drh306dc212001-05-21 13:45:10 +00001882 if( rc!=SQLITE_OK ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00001883
drh306dc212001-05-21 13:45:10 +00001884
1885 /* Do some checking to help insure the file we opened really is
1886 ** a valid database file.
1887 */
drhb6f41482004-05-14 01:58:11 +00001888 rc = SQLITE_NOTADB;
drha34b6762004-05-07 13:30:42 +00001889 if( sqlite3pager_pagecount(pBt->pPager)>0 ){
drhb6f41482004-05-14 01:58:11 +00001890 u8 *page1 = pPage1->aData;
1891 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001892 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001893 }
drhb6f41482004-05-14 01:58:11 +00001894 if( page1[18]>1 || page1[19]>1 ){
1895 goto page1_init_failed;
1896 }
drh07d183d2005-05-01 22:52:42 +00001897 pageSize = get2byte(&page1[16]);
1898 if( ((pageSize-1)&pageSize)!=0 ){
1899 goto page1_init_failed;
1900 }
1901 assert( (pageSize & 7)==0 );
1902 pBt->pageSize = pageSize;
1903 pBt->usableSize = pageSize - page1[20];
drhb6f41482004-05-14 01:58:11 +00001904 if( pBt->usableSize<500 ){
1905 goto page1_init_failed;
1906 }
1907 pBt->maxEmbedFrac = page1[21];
1908 pBt->minEmbedFrac = page1[22];
1909 pBt->minLeafFrac = page1[23];
drh057cd3a2005-02-15 16:23:02 +00001910#ifndef SQLITE_OMIT_AUTOVACUUM
1911 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
1912#endif
drh306dc212001-05-21 13:45:10 +00001913 }
drhb6f41482004-05-14 01:58:11 +00001914
1915 /* maxLocal is the maximum amount of payload to store locally for
1916 ** a cell. Make sure it is small enough so that at least minFanout
1917 ** cells can will fit on one page. We assume a 10-byte page header.
1918 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001919 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001920 ** 4-byte child pointer
1921 ** 9-byte nKey value
1922 ** 4-byte nData value
1923 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001924 ** So a cell consists of a 2-byte poiner, a header which is as much as
1925 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1926 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001927 */
drh43605152004-05-29 21:46:49 +00001928 pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
1929 pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
1930 pBt->maxLeaf = pBt->usableSize - 35;
1931 pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
drhb6f41482004-05-14 01:58:11 +00001932 if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
1933 goto page1_init_failed;
1934 }
drh2e38c322004-09-03 18:38:44 +00001935 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001936 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001937 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001938
drh72f82862001-05-24 21:06:34 +00001939page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001940 releasePage(pPage1);
1941 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001942 return rc;
drh306dc212001-05-21 13:45:10 +00001943}
1944
1945/*
drhb8ef32c2005-03-14 02:01:49 +00001946** This routine works like lockBtree() except that it also invokes the
1947** busy callback if there is lock contention.
1948*/
danielk1977aef0bf62005-12-30 16:28:01 +00001949static int lockBtreeWithRetry(Btree *pRef){
drhb8ef32c2005-03-14 02:01:49 +00001950 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00001951 if( pRef->inTrans==TRANS_NONE ){
1952 u8 inTransaction = pRef->pBt->inTransaction;
1953 btreeIntegrity(pRef);
1954 rc = sqlite3BtreeBeginTrans(pRef, 0);
1955 pRef->pBt->inTransaction = inTransaction;
1956 pRef->inTrans = TRANS_NONE;
1957 if( rc==SQLITE_OK ){
1958 pRef->pBt->nTransaction--;
1959 }
1960 btreeIntegrity(pRef);
drhb8ef32c2005-03-14 02:01:49 +00001961 }
1962 return rc;
1963}
1964
1965
1966/*
drhb8ca3072001-12-05 00:21:20 +00001967** If there are no outstanding cursors and we are not in the middle
1968** of a transaction but there is a read lock on the database, then
1969** this routine unrefs the first page of the database file which
1970** has the effect of releasing the read lock.
1971**
1972** If there are any outstanding cursors, this routine is a no-op.
1973**
1974** If there is a transaction in progress, this routine is a no-op.
1975*/
danielk1977aef0bf62005-12-30 16:28:01 +00001976static void unlockBtreeIfUnused(BtShared *pBt){
1977 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
drh51c6d962004-06-06 00:42:25 +00001978 if( pBt->pPage1->aData==0 ){
1979 MemPage *pPage = pBt->pPage1;
drh2646da72005-12-09 20:02:05 +00001980 pPage->aData = &((u8*)pPage)[-pBt->pageSize];
drh51c6d962004-06-06 00:42:25 +00001981 pPage->pBt = pBt;
1982 pPage->pgno = 1;
1983 }
drh3aac2dd2004-04-26 14:10:20 +00001984 releasePage(pBt->pPage1);
1985 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00001986 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001987 }
1988}
1989
1990/*
drh9e572e62004-04-23 23:43:10 +00001991** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001992** file.
drh8b2f49b2001-06-08 00:21:52 +00001993*/
danielk1977aef0bf62005-12-30 16:28:01 +00001994static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00001995 MemPage *pP1;
1996 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001997 int rc;
drhde647132004-05-07 17:57:49 +00001998 if( sqlite3pager_pagecount(pBt->pPager)>0 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001999 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00002000 assert( pP1!=0 );
2001 data = pP1->aData;
drha34b6762004-05-07 13:30:42 +00002002 rc = sqlite3pager_write(data);
drh8b2f49b2001-06-08 00:21:52 +00002003 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00002004 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
2005 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00002006 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00002007 data[18] = 1;
2008 data[19] = 1;
drhb6f41482004-05-14 01:58:11 +00002009 data[20] = pBt->pageSize - pBt->usableSize;
2010 data[21] = pBt->maxEmbedFrac;
2011 data[22] = pBt->minEmbedFrac;
2012 data[23] = pBt->minLeafFrac;
2013 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00002014 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00002015 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00002016#ifndef SQLITE_OMIT_AUTOVACUUM
2017 if( pBt->autoVacuum ){
2018 put4byte(&data[36 + 4*4], 1);
2019 }
2020#endif
drh8b2f49b2001-06-08 00:21:52 +00002021 return SQLITE_OK;
2022}
2023
2024/*
danielk1977ee5741e2004-05-31 10:01:34 +00002025** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00002026** is started if the second argument is nonzero, otherwise a read-
2027** transaction. If the second argument is 2 or more and exclusive
2028** transaction is started, meaning that no other process is allowed
2029** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00002030** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00002031** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00002032**
danielk1977ee5741e2004-05-31 10:01:34 +00002033** A write-transaction must be started before attempting any
2034** changes to the database. None of the following routines
2035** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00002036**
drh23e11ca2004-05-04 17:27:28 +00002037** sqlite3BtreeCreateTable()
2038** sqlite3BtreeCreateIndex()
2039** sqlite3BtreeClearTable()
2040** sqlite3BtreeDropTable()
2041** sqlite3BtreeInsert()
2042** sqlite3BtreeDelete()
2043** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00002044**
drhb8ef32c2005-03-14 02:01:49 +00002045** If an initial attempt to acquire the lock fails because of lock contention
2046** and the database was previously unlocked, then invoke the busy handler
2047** if there is one. But if there was previously a read-lock, do not
2048** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
2049** returned when there is already a read-lock in order to avoid a deadlock.
2050**
2051** Suppose there are two processes A and B. A has a read lock and B has
2052** a reserved lock. B tries to promote to exclusive but is blocked because
2053** of A's read lock. A tries to promote to reserved but is blocked by B.
2054** One or the other of the two processes must give way or there can be
2055** no progress. By returning SQLITE_BUSY and not invoking the busy callback
2056** when A already has a read lock, we encourage A to give up and let B
2057** proceed.
drha059ad02001-04-17 20:09:11 +00002058*/
danielk1977aef0bf62005-12-30 16:28:01 +00002059int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
2060 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00002061 int rc = SQLITE_OK;
2062
danielk1977aef0bf62005-12-30 16:28:01 +00002063 btreeIntegrity(p);
2064
danielk1977ee5741e2004-05-31 10:01:34 +00002065 /* If the btree is already in a write-transaction, or it
2066 ** is already in a read-transaction and a read-transaction
2067 ** is requested, this is a no-op.
2068 */
danielk1977aef0bf62005-12-30 16:28:01 +00002069 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
danielk1977ee5741e2004-05-31 10:01:34 +00002070 return SQLITE_OK;
2071 }
drhb8ef32c2005-03-14 02:01:49 +00002072
2073 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00002074 if( pBt->readOnly && wrflag ){
2075 return SQLITE_READONLY;
2076 }
2077
danielk1977aef0bf62005-12-30 16:28:01 +00002078 /* If another database handle has already opened a write transaction
2079 ** on this shared-btree structure and a second write transaction is
2080 ** requested, return SQLITE_BUSY.
2081 */
2082 if( pBt->inTransaction==TRANS_WRITE && wrflag ){
2083 return SQLITE_BUSY;
2084 }
2085
drhb8ef32c2005-03-14 02:01:49 +00002086 do {
2087 if( pBt->pPage1==0 ){
2088 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +00002089 }
drhb8ef32c2005-03-14 02:01:49 +00002090
2091 if( rc==SQLITE_OK && wrflag ){
2092 rc = sqlite3pager_begin(pBt->pPage1->aData, wrflag>1);
2093 if( rc==SQLITE_OK ){
2094 rc = newDatabase(pBt);
2095 }
2096 }
2097
2098 if( rc==SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00002099 if( wrflag ) pBt->inStmt = 0;
2100 }else{
2101 unlockBtreeIfUnused(pBt);
2102 }
danielk1977aef0bf62005-12-30 16:28:01 +00002103 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
drha4afb652005-07-09 02:16:02 +00002104 sqlite3InvokeBusyHandler(pBt->pBusyHandler) );
danielk1977aef0bf62005-12-30 16:28:01 +00002105
2106 if( rc==SQLITE_OK ){
2107 if( p->inTrans==TRANS_NONE ){
2108 pBt->nTransaction++;
2109 }
2110 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2111 if( p->inTrans>pBt->inTransaction ){
2112 pBt->inTransaction = p->inTrans;
2113 }
2114 }
2115
2116 btreeIntegrity(p);
drhb8ca3072001-12-05 00:21:20 +00002117 return rc;
drha059ad02001-04-17 20:09:11 +00002118}
2119
danielk1977687566d2004-11-02 12:56:41 +00002120#ifndef SQLITE_OMIT_AUTOVACUUM
2121
2122/*
2123** Set the pointer-map entries for all children of page pPage. Also, if
2124** pPage contains cells that point to overflow pages, set the pointer
2125** map entries for the overflow pages as well.
2126*/
2127static int setChildPtrmaps(MemPage *pPage){
2128 int i; /* Counter variable */
2129 int nCell; /* Number of cells in page pPage */
2130 int rc = SQLITE_OK; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00002131 BtShared *pBt = pPage->pBt;
danielk1977687566d2004-11-02 12:56:41 +00002132 int isInitOrig = pPage->isInit;
2133 Pgno pgno = pPage->pgno;
2134
2135 initPage(pPage, 0);
2136 nCell = pPage->nCell;
2137
2138 for(i=0; i<nCell; i++){
danielk1977687566d2004-11-02 12:56:41 +00002139 u8 *pCell = findCell(pPage, i);
2140
danielk197726836652005-01-17 01:33:13 +00002141 rc = ptrmapPutOvflPtr(pPage, pCell);
2142 if( rc!=SQLITE_OK ){
2143 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002144 }
danielk197726836652005-01-17 01:33:13 +00002145
danielk1977687566d2004-11-02 12:56:41 +00002146 if( !pPage->leaf ){
2147 Pgno childPgno = get4byte(pCell);
2148 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
2149 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
2150 }
2151 }
2152
2153 if( !pPage->leaf ){
2154 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
2155 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
2156 }
2157
2158set_child_ptrmaps_out:
2159 pPage->isInit = isInitOrig;
2160 return rc;
2161}
2162
2163/*
2164** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
2165** page, is a pointer to page iFrom. Modify this pointer so that it points to
2166** iTo. Parameter eType describes the type of pointer to be modified, as
2167** follows:
2168**
2169** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2170** page of pPage.
2171**
2172** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2173** page pointed to by one of the cells on pPage.
2174**
2175** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2176** overflow page in the list.
2177*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00002178static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
danielk1977687566d2004-11-02 12:56:41 +00002179 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00002180 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00002181 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00002182 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002183 }
danielk1977f78fc082004-11-02 14:40:32 +00002184 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00002185 }else{
2186 int isInitOrig = pPage->isInit;
2187 int i;
2188 int nCell;
2189
2190 initPage(pPage, 0);
2191 nCell = pPage->nCell;
2192
danielk1977687566d2004-11-02 12:56:41 +00002193 for(i=0; i<nCell; i++){
2194 u8 *pCell = findCell(pPage, i);
2195 if( eType==PTRMAP_OVERFLOW1 ){
2196 CellInfo info;
2197 parseCellPtr(pPage, pCell, &info);
2198 if( info.iOverflow ){
2199 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
2200 put4byte(&pCell[info.iOverflow], iTo);
2201 break;
2202 }
2203 }
2204 }else{
2205 if( get4byte(pCell)==iFrom ){
2206 put4byte(pCell, iTo);
2207 break;
2208 }
2209 }
2210 }
2211
2212 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00002213 if( eType!=PTRMAP_BTREE ||
2214 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00002215 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002216 }
danielk1977687566d2004-11-02 12:56:41 +00002217 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
2218 }
2219
2220 pPage->isInit = isInitOrig;
2221 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002222 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002223}
2224
danielk1977003ba062004-11-04 02:57:33 +00002225
danielk19777701e812005-01-10 12:59:51 +00002226/*
2227** Move the open database page pDbPage to location iFreePage in the
2228** database. The pDbPage reference remains valid.
2229*/
danielk1977003ba062004-11-04 02:57:33 +00002230static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00002231 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00002232 MemPage *pDbPage, /* Open page to move */
2233 u8 eType, /* Pointer map 'type' entry for pDbPage */
2234 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
2235 Pgno iFreePage /* The location to move pDbPage to */
danielk1977003ba062004-11-04 02:57:33 +00002236){
2237 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
2238 Pgno iDbPage = pDbPage->pgno;
2239 Pager *pPager = pBt->pPager;
2240 int rc;
2241
danielk1977a0bf2652004-11-04 14:30:04 +00002242 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
2243 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
danielk1977003ba062004-11-04 02:57:33 +00002244
2245 /* Move page iDbPage from it's current location to page number iFreePage */
2246 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
2247 iDbPage, iFreePage, iPtrPage, eType));
2248 rc = sqlite3pager_movepage(pPager, pDbPage->aData, iFreePage);
2249 if( rc!=SQLITE_OK ){
2250 return rc;
2251 }
2252 pDbPage->pgno = iFreePage;
2253
2254 /* If pDbPage was a btree-page, then it may have child pages and/or cells
2255 ** that point to overflow pages. The pointer map entries for all these
2256 ** pages need to be changed.
2257 **
2258 ** If pDbPage is an overflow page, then the first 4 bytes may store a
2259 ** pointer to a subsequent overflow page. If this is the case, then
2260 ** the pointer map needs to be updated for the subsequent overflow page.
2261 */
danielk1977a0bf2652004-11-04 14:30:04 +00002262 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00002263 rc = setChildPtrmaps(pDbPage);
2264 if( rc!=SQLITE_OK ){
2265 return rc;
2266 }
2267 }else{
2268 Pgno nextOvfl = get4byte(pDbPage->aData);
2269 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00002270 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
2271 if( rc!=SQLITE_OK ){
2272 return rc;
2273 }
2274 }
2275 }
2276
2277 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
2278 ** that it points at iFreePage. Also fix the pointer map entry for
2279 ** iPtrPage.
2280 */
danielk1977a0bf2652004-11-04 14:30:04 +00002281 if( eType!=PTRMAP_ROOTPAGE ){
2282 rc = getPage(pBt, iPtrPage, &pPtrPage);
2283 if( rc!=SQLITE_OK ){
2284 return rc;
2285 }
2286 rc = sqlite3pager_write(pPtrPage->aData);
2287 if( rc!=SQLITE_OK ){
2288 releasePage(pPtrPage);
2289 return rc;
2290 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002291 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00002292 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002293 if( rc==SQLITE_OK ){
2294 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
2295 }
danielk1977003ba062004-11-04 02:57:33 +00002296 }
danielk1977003ba062004-11-04 02:57:33 +00002297 return rc;
2298}
2299
danielk1977687566d2004-11-02 12:56:41 +00002300/* Forward declaration required by autoVacuumCommit(). */
danielk1977aef0bf62005-12-30 16:28:01 +00002301static int allocatePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00002302
2303/*
2304** This routine is called prior to sqlite3pager_commit when a transaction
2305** is commited for an auto-vacuum database.
2306*/
danielk1977aef0bf62005-12-30 16:28:01 +00002307static int autoVacuumCommit(BtShared *pBt, Pgno *nTrunc){
danielk1977687566d2004-11-02 12:56:41 +00002308 Pager *pPager = pBt->pPager;
danielk1977e501b892006-01-09 06:29:47 +00002309 Pgno nFreeList; /* Number of pages remaining on the free-list. */
2310 int nPtrMap; /* Number of pointer-map pages deallocated */
2311 Pgno origSize; /* Pages in the database file */
2312 Pgno finSize; /* Pages in the database file after truncation */
2313 int rc; /* Return code */
danielk1977687566d2004-11-02 12:56:41 +00002314 u8 eType;
danielk1977a19df672004-11-03 11:37:07 +00002315 int pgsz = pBt->pageSize; /* Page size for this database */
danielk1977687566d2004-11-02 12:56:41 +00002316 Pgno iDbPage; /* The database page to move */
danielk1977687566d2004-11-02 12:56:41 +00002317 MemPage *pDbMemPage = 0; /* "" */
2318 Pgno iPtrPage; /* The page that contains a pointer to iDbPage */
danielk1977687566d2004-11-02 12:56:41 +00002319 Pgno iFreePage; /* The free-list page to move iDbPage to */
2320 MemPage *pFreeMemPage = 0; /* "" */
2321
2322#ifndef NDEBUG
2323 int nRef = *sqlite3pager_stats(pPager);
2324#endif
2325
2326 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +00002327 if( PTRMAP_ISPAGE(pgsz, sqlite3pager_pagecount(pPager)) ){
drh49285702005-09-17 15:20:26 +00002328 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002329 }
danielk1977687566d2004-11-02 12:56:41 +00002330
2331 /* Figure out how many free-pages are in the database. If there are no
2332 ** free pages, then auto-vacuum is a no-op.
2333 */
2334 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977a19df672004-11-03 11:37:07 +00002335 if( nFreeList==0 ){
danielk1977d761c0c2004-11-05 16:37:02 +00002336 *nTrunc = 0;
danielk1977a19df672004-11-03 11:37:07 +00002337 return SQLITE_OK;
2338 }
danielk1977687566d2004-11-02 12:56:41 +00002339
danielk1977a19df672004-11-03 11:37:07 +00002340 origSize = sqlite3pager_pagecount(pPager);
2341 nPtrMap = (nFreeList-origSize+PTRMAP_PAGENO(pgsz, origSize)+pgsz/5)/(pgsz/5);
2342 finSize = origSize - nFreeList - nPtrMap;
danielk1977fd5f5b62005-09-16 09:52:29 +00002343 if( origSize>=PENDING_BYTE_PAGE(pBt) && finSize<=PENDING_BYTE_PAGE(pBt) ){
danielk1977599fcba2004-11-08 07:13:13 +00002344 finSize--;
drh42cac6d2004-11-20 20:31:11 +00002345 if( PTRMAP_ISPAGE(pBt->usableSize, finSize) ){
danielk1977599fcba2004-11-08 07:13:13 +00002346 finSize--;
2347 }
2348 }
danielk1977a19df672004-11-03 11:37:07 +00002349 TRACE(("AUTOVACUUM: Begin (db size %d->%d)\n", origSize, finSize));
danielk1977687566d2004-11-02 12:56:41 +00002350
danielk1977a19df672004-11-03 11:37:07 +00002351 /* Variable 'finSize' will be the size of the file in pages after
danielk1977687566d2004-11-02 12:56:41 +00002352 ** the auto-vacuum has completed (the current file size minus the number
2353 ** of pages on the free list). Loop through the pages that lie beyond
2354 ** this mark, and if they are not already on the free list, move them
danielk1977a19df672004-11-03 11:37:07 +00002355 ** to a free page earlier in the file (somewhere before finSize).
danielk1977687566d2004-11-02 12:56:41 +00002356 */
danielk1977a19df672004-11-03 11:37:07 +00002357 for( iDbPage=finSize+1; iDbPage<=origSize; iDbPage++ ){
danielk1977599fcba2004-11-08 07:13:13 +00002358 /* If iDbPage is a pointer map page, or the pending-byte page, skip it. */
2359 if( PTRMAP_ISPAGE(pgsz, iDbPage) || iDbPage==PENDING_BYTE_PAGE(pBt) ){
2360 continue;
2361 }
2362
danielk1977687566d2004-11-02 12:56:41 +00002363 rc = ptrmapGet(pBt, iDbPage, &eType, &iPtrPage);
2364 if( rc!=SQLITE_OK ) goto autovacuum_out;
drhccae6022005-02-26 17:31:26 +00002365 if( eType==PTRMAP_ROOTPAGE ){
drh49285702005-09-17 15:20:26 +00002366 rc = SQLITE_CORRUPT_BKPT;
drhccae6022005-02-26 17:31:26 +00002367 goto autovacuum_out;
2368 }
danielk1977687566d2004-11-02 12:56:41 +00002369
danielk1977599fcba2004-11-08 07:13:13 +00002370 /* If iDbPage is free, do not swap it. */
2371 if( eType==PTRMAP_FREEPAGE ){
danielk1977687566d2004-11-02 12:56:41 +00002372 continue;
2373 }
2374 rc = getPage(pBt, iDbPage, &pDbMemPage);
2375 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977687566d2004-11-02 12:56:41 +00002376
2377 /* Find the next page in the free-list that is not already at the end
2378 ** of the file. A page can be pulled off the free list using the
2379 ** allocatePage() routine.
2380 */
2381 do{
2382 if( pFreeMemPage ){
2383 releasePage(pFreeMemPage);
2384 pFreeMemPage = 0;
2385 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00002386 rc = allocatePage(pBt, &pFreeMemPage, &iFreePage, 0, 0);
danielk1977ac11ee62005-01-15 12:45:51 +00002387 if( rc!=SQLITE_OK ){
2388 releasePage(pDbMemPage);
2389 goto autovacuum_out;
2390 }
danielk1977a19df672004-11-03 11:37:07 +00002391 assert( iFreePage<=origSize );
2392 }while( iFreePage>finSize );
danielk1977687566d2004-11-02 12:56:41 +00002393 releasePage(pFreeMemPage);
2394 pFreeMemPage = 0;
danielk1977687566d2004-11-02 12:56:41 +00002395
danielk1977e501b892006-01-09 06:29:47 +00002396 /* Relocate the page into the body of the file. Note that although the
2397 ** page has moved within the database file, the pDbMemPage pointer
2398 ** remains valid. This means that this function can run without
2399 ** invalidating cursors open on the btree. This is important in
2400 ** shared-cache mode.
2401 */
danielk1977003ba062004-11-04 02:57:33 +00002402 rc = relocatePage(pBt, pDbMemPage, eType, iPtrPage, iFreePage);
danielk1977687566d2004-11-02 12:56:41 +00002403 releasePage(pDbMemPage);
danielk1977687566d2004-11-02 12:56:41 +00002404 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977687566d2004-11-02 12:56:41 +00002405 }
2406
2407 /* The entire free-list has been swapped to the end of the file. So
danielk1977a19df672004-11-03 11:37:07 +00002408 ** truncate the database file to finSize pages and consider the
danielk1977687566d2004-11-02 12:56:41 +00002409 ** free-list empty.
2410 */
2411 rc = sqlite3pager_write(pBt->pPage1->aData);
2412 if( rc!=SQLITE_OK ) goto autovacuum_out;
2413 put4byte(&pBt->pPage1->aData[32], 0);
2414 put4byte(&pBt->pPage1->aData[36], 0);
danielk1977687566d2004-11-02 12:56:41 +00002415 if( rc!=SQLITE_OK ) goto autovacuum_out;
danielk1977d761c0c2004-11-05 16:37:02 +00002416 *nTrunc = finSize;
danielk1977687566d2004-11-02 12:56:41 +00002417
2418autovacuum_out:
danielk1977687566d2004-11-02 12:56:41 +00002419 assert( nRef==*sqlite3pager_stats(pPager) );
2420 if( rc!=SQLITE_OK ){
2421 sqlite3pager_rollback(pPager);
2422 }
2423 return rc;
2424}
2425#endif
2426
2427/*
drh2aa679f2001-06-25 02:11:07 +00002428** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00002429**
2430** This will release the write lock on the database file. If there
2431** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002432*/
danielk1977aef0bf62005-12-30 16:28:01 +00002433int sqlite3BtreeCommit(Btree *p){
danielk1977ee5741e2004-05-31 10:01:34 +00002434 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002435 BtShared *pBt = p->pBt;
2436
2437 btreeIntegrity(p);
2438 unlockAllTables(p);
2439
2440 /* If the handle has a write-transaction open, commit the shared-btrees
2441 ** transaction and set the shared state to TRANS_READ.
2442 */
2443 if( p->inTrans==TRANS_WRITE ){
2444 assert( pBt->inTransaction==TRANS_WRITE );
2445 assert( pBt->nTransaction>0 );
danielk1977ee5741e2004-05-31 10:01:34 +00002446 rc = sqlite3pager_commit(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00002447 pBt->inTransaction = TRANS_READ;
2448 pBt->inStmt = 0;
danielk1977ee5741e2004-05-31 10:01:34 +00002449 }
danielk1977aef0bf62005-12-30 16:28:01 +00002450
2451 /* If the handle has any kind of transaction open, decrement the transaction
2452 ** count of the shared btree. If the transaction count reaches 0, set
2453 ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
2454 ** will unlock the pager.
2455 */
2456 if( p->inTrans!=TRANS_NONE ){
2457 pBt->nTransaction--;
2458 if( 0==pBt->nTransaction ){
2459 pBt->inTransaction = TRANS_NONE;
2460 }
2461 }
2462
2463 /* Set the handles current transaction state to TRANS_NONE and unlock
2464 ** the pager if this call closed the only read or write transaction.
2465 */
2466 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002467 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002468
2469 btreeIntegrity(p);
drha059ad02001-04-17 20:09:11 +00002470 return rc;
2471}
2472
danielk1977fbcd5852004-06-15 02:44:18 +00002473#ifndef NDEBUG
2474/*
2475** Return the number of write-cursors open on this handle. This is for use
2476** in assert() expressions, so it is only compiled if NDEBUG is not
2477** defined.
2478*/
danielk1977aef0bf62005-12-30 16:28:01 +00002479static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00002480 BtCursor *pCur;
2481 int r = 0;
2482 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
danielk1977aef0bf62005-12-30 16:28:01 +00002483 if( pCur->wrFlag ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00002484 }
2485 return r;
2486}
2487#endif
2488
drhda200cc2004-05-09 11:51:38 +00002489#ifdef SQLITE_TEST
2490/*
2491** Print debugging information about all cursors to standard output.
2492*/
danielk1977aef0bf62005-12-30 16:28:01 +00002493void sqlite3BtreeCursorList(Btree *p){
drhda200cc2004-05-09 11:51:38 +00002494 BtCursor *pCur;
danielk1977aef0bf62005-12-30 16:28:01 +00002495 BtShared *pBt = p->pBt;
drhda200cc2004-05-09 11:51:38 +00002496 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
2497 MemPage *pPage = pCur->pPage;
2498 char *zMode = pCur->wrFlag ? "rw" : "ro";
drhfe63d1c2004-09-08 20:13:04 +00002499 sqlite3DebugPrintf("CURSOR %p rooted at %4d(%s) currently at %d.%d%s\n",
2500 pCur, pCur->pgnoRoot, zMode,
drhda200cc2004-05-09 11:51:38 +00002501 pPage ? pPage->pgno : 0, pCur->idx,
danielk1977da184232006-01-05 11:34:32 +00002502 (pCur->eState==CURSOR_VALID) ? "" : " eof"
drhda200cc2004-05-09 11:51:38 +00002503 );
2504 }
2505}
2506#endif
2507
drhc39e0002004-05-07 23:50:57 +00002508/*
drhecdc7532001-09-23 02:35:53 +00002509** Rollback the transaction in progress. All cursors will be
2510** invalided by this operation. Any attempt to use a cursor
2511** that was open at the beginning of this operation will result
2512** in an error.
drh5e00f6c2001-09-13 13:46:56 +00002513**
2514** This will release the write lock on the database file. If there
2515** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002516*/
danielk1977aef0bf62005-12-30 16:28:01 +00002517int sqlite3BtreeRollback(Btree *p){
danielk1977cfe9a692004-06-16 12:00:29 +00002518 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002519 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00002520 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00002521
2522 btreeIntegrity(p);
2523 unlockAllTables(p);
2524
2525 if( p->inTrans==TRANS_WRITE ){
2526 assert( TRANS_WRITE==pBt->inTransaction );
2527
drh24cd67e2004-05-10 16:18:47 +00002528 rc = sqlite3pager_rollback(pBt->pPager);
2529 /* The rollback may have destroyed the pPage1->aData value. So
2530 ** call getPage() on page 1 again to make sure pPage1->aData is
2531 ** set correctly. */
2532 if( getPage(pBt, 1, &pPage1)==SQLITE_OK ){
2533 releasePage(pPage1);
2534 }
danielk1977fbcd5852004-06-15 02:44:18 +00002535 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002536 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00002537 }
danielk1977aef0bf62005-12-30 16:28:01 +00002538
2539 if( p->inTrans!=TRANS_NONE ){
2540 assert( pBt->nTransaction>0 );
2541 pBt->nTransaction--;
2542 if( 0==pBt->nTransaction ){
2543 pBt->inTransaction = TRANS_NONE;
2544 }
2545 }
2546
2547 p->inTrans = TRANS_NONE;
danielk1977ee5741e2004-05-31 10:01:34 +00002548 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00002549 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002550
2551 btreeIntegrity(p);
drha059ad02001-04-17 20:09:11 +00002552 return rc;
2553}
2554
2555/*
drhab01f612004-05-22 02:55:23 +00002556** Start a statement subtransaction. The subtransaction can
2557** can be rolled back independently of the main transaction.
2558** You must start a transaction before starting a subtransaction.
2559** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00002560** commits or rolls back.
2561**
drhab01f612004-05-22 02:55:23 +00002562** Only one subtransaction may be active at a time. It is an error to try
2563** to start a new subtransaction if another subtransaction is already active.
2564**
2565** Statement subtransactions are used around individual SQL statements
2566** that are contained within a BEGIN...COMMIT block. If a constraint
2567** error occurs within the statement, the effect of that one statement
2568** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00002569*/
danielk1977aef0bf62005-12-30 16:28:01 +00002570int sqlite3BtreeBeginStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002571 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002572 BtShared *pBt = p->pBt;
2573 if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
drhf74b8d92002-09-01 23:20:45 +00002574 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh0d65dc02002-02-03 00:56:09 +00002575 }
danielk1977aef0bf62005-12-30 16:28:01 +00002576 assert( pBt->inTransaction==TRANS_WRITE );
drha34b6762004-05-07 13:30:42 +00002577 rc = pBt->readOnly ? SQLITE_OK : sqlite3pager_stmt_begin(pBt->pPager);
drh3aac2dd2004-04-26 14:10:20 +00002578 pBt->inStmt = 1;
drh663fc632002-02-02 18:49:19 +00002579 return rc;
2580}
2581
2582
2583/*
drhab01f612004-05-22 02:55:23 +00002584** Commit the statment subtransaction currently in progress. If no
2585** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00002586*/
danielk1977aef0bf62005-12-30 16:28:01 +00002587int sqlite3BtreeCommitStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002588 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002589 BtShared *pBt = p->pBt;
drh3aac2dd2004-04-26 14:10:20 +00002590 if( pBt->inStmt && !pBt->readOnly ){
drha34b6762004-05-07 13:30:42 +00002591 rc = sqlite3pager_stmt_commit(pBt->pPager);
drh663fc632002-02-02 18:49:19 +00002592 }else{
2593 rc = SQLITE_OK;
2594 }
drh3aac2dd2004-04-26 14:10:20 +00002595 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00002596 return rc;
2597}
2598
2599/*
drhab01f612004-05-22 02:55:23 +00002600** Rollback the active statement subtransaction. If no subtransaction
2601** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00002602**
drhab01f612004-05-22 02:55:23 +00002603** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00002604** to use a cursor that was open at the beginning of this operation
2605** will result in an error.
2606*/
danielk1977aef0bf62005-12-30 16:28:01 +00002607int sqlite3BtreeRollbackStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002608 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002609 BtShared *pBt = p->pBt;
drh3aac2dd2004-04-26 14:10:20 +00002610 if( pBt->inStmt==0 || pBt->readOnly ) return SQLITE_OK;
drha34b6762004-05-07 13:30:42 +00002611 rc = sqlite3pager_stmt_rollback(pBt->pPager);
danielk1977fbcd5852004-06-15 02:44:18 +00002612 assert( countWriteCursors(pBt)==0 );
drh3aac2dd2004-04-26 14:10:20 +00002613 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00002614 return rc;
2615}
2616
2617/*
drh3aac2dd2004-04-26 14:10:20 +00002618** Default key comparison function to be used if no comparison function
2619** is specified on the sqlite3BtreeCursor() call.
2620*/
2621static int dfltCompare(
2622 void *NotUsed, /* User data is not used */
2623 int n1, const void *p1, /* First key to compare */
2624 int n2, const void *p2 /* Second key to compare */
2625){
2626 int c;
2627 c = memcmp(p1, p2, n1<n2 ? n1 : n2);
2628 if( c==0 ){
2629 c = n1 - n2;
2630 }
2631 return c;
2632}
2633
2634/*
drh8b2f49b2001-06-08 00:21:52 +00002635** Create a new cursor for the BTree whose root is on the page
2636** iTable. The act of acquiring a cursor gets a read lock on
2637** the database file.
drh1bee3d72001-10-15 00:44:35 +00002638**
2639** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00002640** If wrFlag==1, then the cursor can be used for reading or for
2641** writing if other conditions for writing are also met. These
2642** are the conditions that must be met in order for writing to
2643** be allowed:
drh6446c4d2001-12-15 14:22:18 +00002644**
drhf74b8d92002-09-01 23:20:45 +00002645** 1: The cursor must have been opened with wrFlag==1
2646**
2647** 2: No other cursors may be open with wrFlag==0 on the same table
2648**
2649** 3: The database must be writable (not on read-only media)
2650**
2651** 4: There must be an active transaction.
2652**
2653** Condition 2 warrants further discussion. If any cursor is opened
2654** on a table with wrFlag==0, that prevents all other cursors from
2655** writing to that table. This is a kind of "read-lock". When a cursor
2656** is opened with wrFlag==0 it is guaranteed that the table will not
2657** change as long as the cursor is open. This allows the cursor to
2658** do a sequential scan of the table without having to worry about
2659** entries being inserted or deleted during the scan. Cursors should
2660** be opened with wrFlag==0 only if this read-lock property is needed.
2661** That is to say, cursors should be opened with wrFlag==0 only if they
drh23e11ca2004-05-04 17:27:28 +00002662** intend to use the sqlite3BtreeNext() system call. All other cursors
drhf74b8d92002-09-01 23:20:45 +00002663** should be opened with wrFlag==1 even if they never really intend
2664** to write.
2665**
drh6446c4d2001-12-15 14:22:18 +00002666** No checking is done to make sure that page iTable really is the
2667** root page of a b-tree. If it is not, then the cursor acquired
2668** will not work correctly.
drh3aac2dd2004-04-26 14:10:20 +00002669**
2670** The comparison function must be logically the same for every cursor
2671** on a particular table. Changing the comparison function will result
2672** in incorrect operations. If the comparison function is NULL, a
2673** default comparison function is used. The comparison function is
2674** always ignored for INTKEY tables.
drha059ad02001-04-17 20:09:11 +00002675*/
drh3aac2dd2004-04-26 14:10:20 +00002676int sqlite3BtreeCursor(
danielk1977aef0bf62005-12-30 16:28:01 +00002677 Btree *p, /* The btree */
drh3aac2dd2004-04-26 14:10:20 +00002678 int iTable, /* Root page of table to open */
2679 int wrFlag, /* 1 to write. 0 read-only */
2680 int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
2681 void *pArg, /* First arg to xCompare() */
2682 BtCursor **ppCur /* Write new cursor here */
2683){
drha059ad02001-04-17 20:09:11 +00002684 int rc;
drh8dcd7ca2004-08-08 19:43:29 +00002685 BtCursor *pCur;
danielk1977aef0bf62005-12-30 16:28:01 +00002686 BtShared *pBt = p->pBt;
drhecdc7532001-09-23 02:35:53 +00002687
drh8dcd7ca2004-08-08 19:43:29 +00002688 *ppCur = 0;
2689 if( wrFlag ){
drh8dcd7ca2004-08-08 19:43:29 +00002690 if( pBt->readOnly ){
2691 return SQLITE_READONLY;
2692 }
2693 if( checkReadLocks(pBt, iTable, 0) ){
2694 return SQLITE_LOCKED;
2695 }
drha0c9a112004-03-10 13:42:37 +00002696 }
danielk1977aef0bf62005-12-30 16:28:01 +00002697
drh4b70f112004-05-02 21:12:19 +00002698 if( pBt->pPage1==0 ){
danielk1977aef0bf62005-12-30 16:28:01 +00002699 rc = lockBtreeWithRetry(p);
drha059ad02001-04-17 20:09:11 +00002700 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002701 return rc;
2702 }
2703 }
danielk1977da184232006-01-05 11:34:32 +00002704 pCur = sqliteMalloc( sizeof(*pCur) );
drha059ad02001-04-17 20:09:11 +00002705 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +00002706 rc = SQLITE_NOMEM;
2707 goto create_cursor_exception;
2708 }
drh8b2f49b2001-06-08 00:21:52 +00002709 pCur->pgnoRoot = (Pgno)iTable;
danielk19776b456a22005-03-21 04:04:02 +00002710 pCur->pPage = 0; /* For exit-handler, in case getAndInitPage() fails. */
drh24cd67e2004-05-10 16:18:47 +00002711 if( iTable==1 && sqlite3pager_pagecount(pBt->pPager)==0 ){
2712 rc = SQLITE_EMPTY;
2713 goto create_cursor_exception;
2714 }
drhde647132004-05-07 17:57:49 +00002715 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
drhbd03cae2001-06-02 02:40:57 +00002716 if( rc!=SQLITE_OK ){
2717 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002718 }
danielk1977aef0bf62005-12-30 16:28:01 +00002719
danielk1977aef0bf62005-12-30 16:28:01 +00002720 /* Now that no other errors can occur, finish filling in the BtCursor
2721 ** variables, link the cursor into the BtShared list and set *ppCur (the
2722 ** output argument to this function).
2723 */
drh3aac2dd2004-04-26 14:10:20 +00002724 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2725 pCur->pArg = pArg;
danielk1977aef0bf62005-12-30 16:28:01 +00002726 pCur->pBtree = p;
drhecdc7532001-09-23 02:35:53 +00002727 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +00002728 pCur->idx = 0;
drh59eb6762004-06-13 23:07:04 +00002729 memset(&pCur->info, 0, sizeof(pCur->info));
drha059ad02001-04-17 20:09:11 +00002730 pCur->pNext = pBt->pCursor;
2731 if( pCur->pNext ){
2732 pCur->pNext->pPrev = pCur;
2733 }
drh14acc042001-06-10 19:56:58 +00002734 pCur->pPrev = 0;
drha059ad02001-04-17 20:09:11 +00002735 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00002736 pCur->eState = CURSOR_INVALID;
drh2af926b2001-05-15 00:39:25 +00002737 *ppCur = pCur;
drhbd03cae2001-06-02 02:40:57 +00002738
danielk1977aef0bf62005-12-30 16:28:01 +00002739 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00002740create_cursor_exception:
drhbd03cae2001-06-02 02:40:57 +00002741 if( pCur ){
drh3aac2dd2004-04-26 14:10:20 +00002742 releasePage(pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +00002743 sqliteFree(pCur);
2744 }
drh5e00f6c2001-09-13 13:46:56 +00002745 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00002746 return rc;
drha059ad02001-04-17 20:09:11 +00002747}
2748
drh7a224de2004-06-02 01:22:02 +00002749#if 0 /* Not Used */
drhd3d39e92004-05-20 22:16:29 +00002750/*
2751** Change the value of the comparison function used by a cursor.
2752*/
danielk1977bf3b7212004-05-18 10:06:24 +00002753void sqlite3BtreeSetCompare(
drhd3d39e92004-05-20 22:16:29 +00002754 BtCursor *pCur, /* The cursor to whose comparison function is changed */
2755 int(*xCmp)(void*,int,const void*,int,const void*), /* New comparison func */
2756 void *pArg /* First argument to xCmp() */
danielk1977bf3b7212004-05-18 10:06:24 +00002757){
2758 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2759 pCur->pArg = pArg;
2760}
drh7a224de2004-06-02 01:22:02 +00002761#endif
danielk1977bf3b7212004-05-18 10:06:24 +00002762
drha059ad02001-04-17 20:09:11 +00002763/*
drh5e00f6c2001-09-13 13:46:56 +00002764** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00002765** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00002766*/
drh3aac2dd2004-04-26 14:10:20 +00002767int sqlite3BtreeCloseCursor(BtCursor *pCur){
danielk1977aef0bf62005-12-30 16:28:01 +00002768 BtShared *pBt = pCur->pBtree->pBt;
danielk1977da184232006-01-05 11:34:32 +00002769 restoreCursorPosition(pCur, 0);
drha059ad02001-04-17 20:09:11 +00002770 if( pCur->pPrev ){
2771 pCur->pPrev->pNext = pCur->pNext;
2772 }else{
2773 pBt->pCursor = pCur->pNext;
2774 }
2775 if( pCur->pNext ){
2776 pCur->pNext->pPrev = pCur->pPrev;
2777 }
drh3aac2dd2004-04-26 14:10:20 +00002778 releasePage(pCur->pPage);
drh5e00f6c2001-09-13 13:46:56 +00002779 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00002780 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +00002781 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002782}
2783
drh7e3b0a02001-04-28 16:52:40 +00002784/*
drh5e2f8b92001-05-28 00:41:15 +00002785** Make a temporary cursor by filling in the fields of pTempCur.
2786** The temporary cursor is not on the cursor list for the Btree.
2787*/
drh14acc042001-06-10 19:56:58 +00002788static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00002789 memcpy(pTempCur, pCur, sizeof(*pCur));
2790 pTempCur->pNext = 0;
2791 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00002792 if( pTempCur->pPage ){
drha34b6762004-05-07 13:30:42 +00002793 sqlite3pager_ref(pTempCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00002794 }
drh5e2f8b92001-05-28 00:41:15 +00002795}
2796
2797/*
drhbd03cae2001-06-02 02:40:57 +00002798** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00002799** function above.
2800*/
drh14acc042001-06-10 19:56:58 +00002801static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00002802 if( pCur->pPage ){
drha34b6762004-05-07 13:30:42 +00002803 sqlite3pager_unref(pCur->pPage->aData);
drhecdc7532001-09-23 02:35:53 +00002804 }
drh5e2f8b92001-05-28 00:41:15 +00002805}
2806
2807/*
drh9188b382004-05-14 21:12:22 +00002808** Make sure the BtCursor.info field of the given cursor is valid.
drhab01f612004-05-22 02:55:23 +00002809** If it is not already valid, call parseCell() to fill it in.
2810**
2811** BtCursor.info is a cache of the information in the current cell.
2812** Using this cache reduces the number of calls to parseCell().
drh9188b382004-05-14 21:12:22 +00002813*/
2814static void getCellInfo(BtCursor *pCur){
drh271efa52004-05-30 19:19:05 +00002815 if( pCur->info.nSize==0 ){
drh3a41a3f2004-05-30 02:14:17 +00002816 parseCell(pCur->pPage, pCur->idx, &pCur->info);
drh9188b382004-05-14 21:12:22 +00002817 }else{
2818#ifndef NDEBUG
2819 CellInfo info;
drh51c6d962004-06-06 00:42:25 +00002820 memset(&info, 0, sizeof(info));
drh3a41a3f2004-05-30 02:14:17 +00002821 parseCell(pCur->pPage, pCur->idx, &info);
drh9188b382004-05-14 21:12:22 +00002822 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
2823#endif
2824 }
2825}
2826
2827/*
drh3aac2dd2004-04-26 14:10:20 +00002828** Set *pSize to the size of the buffer needed to hold the value of
2829** the key for the current entry. If the cursor is not pointing
2830** to a valid entry, *pSize is set to 0.
2831**
drh4b70f112004-05-02 21:12:19 +00002832** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00002833** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00002834*/
drh4a1c3802004-05-12 15:15:47 +00002835int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
danielk1977da184232006-01-05 11:34:32 +00002836 int rc = restoreCursorPosition(pCur, 1);
2837 if( rc==SQLITE_OK ){
2838 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
2839 if( pCur->eState==CURSOR_INVALID ){
2840 *pSize = 0;
2841 }else{
2842 getCellInfo(pCur);
2843 *pSize = pCur->info.nKey;
2844 }
drh72f82862001-05-24 21:06:34 +00002845 }
danielk1977da184232006-01-05 11:34:32 +00002846 return rc;
drha059ad02001-04-17 20:09:11 +00002847}
drh2af926b2001-05-15 00:39:25 +00002848
drh72f82862001-05-24 21:06:34 +00002849/*
drh0e1c19e2004-05-11 00:58:56 +00002850** Set *pSize to the number of bytes of data in the entry the
2851** cursor currently points to. Always return SQLITE_OK.
2852** Failure is not possible. If the cursor is not currently
2853** pointing to an entry (which can happen, for example, if
2854** the database is empty) then *pSize is set to 0.
2855*/
2856int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
danielk1977da184232006-01-05 11:34:32 +00002857 int rc = restoreCursorPosition(pCur, 1);
2858 if( rc==SQLITE_OK ){
2859 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
2860 if( pCur->eState==CURSOR_INVALID ){
2861 /* Not pointing at a valid entry - set *pSize to 0. */
2862 *pSize = 0;
2863 }else{
2864 getCellInfo(pCur);
2865 *pSize = pCur->info.nData;
2866 }
drh0e1c19e2004-05-11 00:58:56 +00002867 }
danielk1977da184232006-01-05 11:34:32 +00002868 return rc;
drh0e1c19e2004-05-11 00:58:56 +00002869}
2870
2871/*
drh72f82862001-05-24 21:06:34 +00002872** Read payload information from the entry that the pCur cursor is
2873** pointing to. Begin reading the payload at "offset" and read
2874** a total of "amt" bytes. Put the result in zBuf.
2875**
2876** This routine does not make a distinction between key and data.
drhab01f612004-05-22 02:55:23 +00002877** It just reads bytes from the payload area. Data might appear
2878** on the main page or be scattered out on multiple overflow pages.
drh72f82862001-05-24 21:06:34 +00002879*/
drh3aac2dd2004-04-26 14:10:20 +00002880static int getPayload(
2881 BtCursor *pCur, /* Cursor pointing to entry to read from */
2882 int offset, /* Begin reading this far into payload */
2883 int amt, /* Read this many bytes */
2884 unsigned char *pBuf, /* Write the bytes into this buffer */
2885 int skipKey /* offset begins at data if this is true */
2886){
2887 unsigned char *aPayload;
drh2af926b2001-05-15 00:39:25 +00002888 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +00002889 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002890 MemPage *pPage;
danielk1977aef0bf62005-12-30 16:28:01 +00002891 BtShared *pBt;
drh6f11bef2004-05-13 01:12:56 +00002892 int ovflSize;
drhfa1a98a2004-05-14 19:08:17 +00002893 u32 nKey;
drh3aac2dd2004-04-26 14:10:20 +00002894
drh72f82862001-05-24 21:06:34 +00002895 assert( pCur!=0 && pCur->pPage!=0 );
danielk1977da184232006-01-05 11:34:32 +00002896 assert( pCur->eState==CURSOR_VALID );
danielk1977aef0bf62005-12-30 16:28:01 +00002897 pBt = pCur->pBtree->pBt;
drh3aac2dd2004-04-26 14:10:20 +00002898 pPage = pCur->pPage;
drhda200cc2004-05-09 11:51:38 +00002899 pageIntegrity(pPage);
drh3aac2dd2004-04-26 14:10:20 +00002900 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00002901 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00002902 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00002903 aPayload += pCur->info.nHeader;
drh3aac2dd2004-04-26 14:10:20 +00002904 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00002905 nKey = 0;
2906 }else{
2907 nKey = pCur->info.nKey;
drh3aac2dd2004-04-26 14:10:20 +00002908 }
2909 assert( offset>=0 );
2910 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00002911 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00002912 }
drhfa1a98a2004-05-14 19:08:17 +00002913 if( offset+amt > nKey+pCur->info.nData ){
drha34b6762004-05-07 13:30:42 +00002914 return SQLITE_ERROR;
drh3aac2dd2004-04-26 14:10:20 +00002915 }
drhfa1a98a2004-05-14 19:08:17 +00002916 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00002917 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00002918 if( a+offset>pCur->info.nLocal ){
2919 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00002920 }
drha34b6762004-05-07 13:30:42 +00002921 memcpy(pBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +00002922 if( a==amt ){
2923 return SQLITE_OK;
2924 }
drh2aa679f2001-06-25 02:11:07 +00002925 offset = 0;
drha34b6762004-05-07 13:30:42 +00002926 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00002927 amt -= a;
drhdd793422001-06-28 01:54:48 +00002928 }else{
drhfa1a98a2004-05-14 19:08:17 +00002929 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00002930 }
danielk1977cfe9a692004-06-16 12:00:29 +00002931 ovflSize = pBt->usableSize - 4;
drhbd03cae2001-06-02 02:40:57 +00002932 if( amt>0 ){
drhfa1a98a2004-05-14 19:08:17 +00002933 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977cfe9a692004-06-16 12:00:29 +00002934 while( amt>0 && nextPage ){
2935 rc = sqlite3pager_get(pBt->pPager, nextPage, (void**)&aPayload);
2936 if( rc!=0 ){
2937 return rc;
drh2af926b2001-05-15 00:39:25 +00002938 }
danielk1977cfe9a692004-06-16 12:00:29 +00002939 nextPage = get4byte(aPayload);
2940 if( offset<ovflSize ){
2941 int a = amt;
2942 if( a + offset > ovflSize ){
2943 a = ovflSize - offset;
2944 }
2945 memcpy(pBuf, &aPayload[offset+4], a);
2946 offset = 0;
2947 amt -= a;
2948 pBuf += a;
2949 }else{
2950 offset -= ovflSize;
2951 }
2952 sqlite3pager_unref(aPayload);
drh2af926b2001-05-15 00:39:25 +00002953 }
drh2af926b2001-05-15 00:39:25 +00002954 }
danielk1977cfe9a692004-06-16 12:00:29 +00002955
drha7fcb052001-12-14 15:09:55 +00002956 if( amt>0 ){
drh49285702005-09-17 15:20:26 +00002957 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00002958 }
2959 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00002960}
2961
drh72f82862001-05-24 21:06:34 +00002962/*
drh3aac2dd2004-04-26 14:10:20 +00002963** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002964** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002965** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00002966**
drh3aac2dd2004-04-26 14:10:20 +00002967** Return SQLITE_OK on success or an error code if anything goes
2968** wrong. An error is returned if "offset+amt" is larger than
2969** the available payload.
drh72f82862001-05-24 21:06:34 +00002970*/
drha34b6762004-05-07 13:30:42 +00002971int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
danielk1977da184232006-01-05 11:34:32 +00002972 int rc = restoreCursorPosition(pCur, 1);
2973 if( rc==SQLITE_OK ){
2974 assert( pCur->eState==CURSOR_VALID );
2975 assert( pCur->pPage!=0 );
2976 if( pCur->pPage->intKey ){
2977 return SQLITE_CORRUPT_BKPT;
2978 }
2979 assert( pCur->pPage->intKey==0 );
2980 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
2981 rc = getPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
drh6575a222005-03-10 17:06:34 +00002982 }
danielk1977da184232006-01-05 11:34:32 +00002983 return rc;
drh3aac2dd2004-04-26 14:10:20 +00002984}
2985
2986/*
drh3aac2dd2004-04-26 14:10:20 +00002987** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002988** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002989** begins at "offset".
2990**
2991** Return SQLITE_OK on success or an error code if anything goes
2992** wrong. An error is returned if "offset+amt" is larger than
2993** the available payload.
drh72f82862001-05-24 21:06:34 +00002994*/
drh3aac2dd2004-04-26 14:10:20 +00002995int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
danielk1977da184232006-01-05 11:34:32 +00002996 int rc = restoreCursorPosition(pCur, 1);
2997 if( rc==SQLITE_OK ){
2998 assert( pCur->eState==CURSOR_VALID );
2999 assert( pCur->pPage!=0 );
3000 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
3001 rc = getPayload(pCur, offset, amt, pBuf, 1);
3002 }
3003 return rc;
drh2af926b2001-05-15 00:39:25 +00003004}
3005
drh72f82862001-05-24 21:06:34 +00003006/*
drh0e1c19e2004-05-11 00:58:56 +00003007** Return a pointer to payload information from the entry that the
3008** pCur cursor is pointing to. The pointer is to the beginning of
3009** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00003010** skipKey==1. The number of bytes of available key/data is written
3011** into *pAmt. If *pAmt==0, then the value returned will not be
3012** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00003013**
3014** This routine is an optimization. It is common for the entire key
3015** and data to fit on the local page and for there to be no overflow
3016** pages. When that is so, this routine can be used to access the
3017** key and data without making a copy. If the key and/or data spills
3018** onto overflow pages, then getPayload() must be used to reassembly
3019** the key/data and copy it into a preallocated buffer.
3020**
3021** The pointer returned by this routine looks directly into the cached
3022** page of the database. The data might change or move the next time
3023** any btree routine is called.
3024*/
3025static const unsigned char *fetchPayload(
3026 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00003027 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00003028 int skipKey /* read beginning at data if this is true */
3029){
3030 unsigned char *aPayload;
3031 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00003032 u32 nKey;
3033 int nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003034
3035 assert( pCur!=0 && pCur->pPage!=0 );
danielk1977da184232006-01-05 11:34:32 +00003036 assert( pCur->eState==CURSOR_VALID );
drh0e1c19e2004-05-11 00:58:56 +00003037 pPage = pCur->pPage;
3038 pageIntegrity(pPage);
3039 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh9188b382004-05-14 21:12:22 +00003040 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00003041 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00003042 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00003043 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00003044 nKey = 0;
3045 }else{
3046 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00003047 }
drh0e1c19e2004-05-11 00:58:56 +00003048 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003049 aPayload += nKey;
3050 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00003051 }else{
drhfa1a98a2004-05-14 19:08:17 +00003052 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00003053 if( nLocal>nKey ){
3054 nLocal = nKey;
3055 }
drh0e1c19e2004-05-11 00:58:56 +00003056 }
drhe51c44f2004-05-30 20:46:09 +00003057 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003058 return aPayload;
3059}
3060
3061
3062/*
drhe51c44f2004-05-30 20:46:09 +00003063** For the entry that cursor pCur is point to, return as
3064** many bytes of the key or data as are available on the local
3065** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00003066**
3067** The pointer returned is ephemeral. The key/data may move
3068** or be destroyed on the next call to any Btree routine.
3069**
3070** These routines is used to get quick access to key and data
3071** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00003072*/
drhe51c44f2004-05-30 20:46:09 +00003073const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
danielk1977da184232006-01-05 11:34:32 +00003074 if( pCur->eState==CURSOR_VALID ){
3075 return (const void*)fetchPayload(pCur, pAmt, 0);
3076 }
3077 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003078}
drhe51c44f2004-05-30 20:46:09 +00003079const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
danielk1977da184232006-01-05 11:34:32 +00003080 if( pCur->eState==CURSOR_VALID ){
3081 return (const void*)fetchPayload(pCur, pAmt, 1);
3082 }
3083 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003084}
3085
3086
3087/*
drh8178a752003-01-05 21:41:40 +00003088** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00003089** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00003090*/
drh3aac2dd2004-04-26 14:10:20 +00003091static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00003092 int rc;
3093 MemPage *pNewPage;
drh3aac2dd2004-04-26 14:10:20 +00003094 MemPage *pOldPage;
danielk1977aef0bf62005-12-30 16:28:01 +00003095 BtShared *pBt = pCur->pBtree->pBt;
drh72f82862001-05-24 21:06:34 +00003096
danielk1977da184232006-01-05 11:34:32 +00003097 assert( pCur->eState==CURSOR_VALID );
drhde647132004-05-07 17:57:49 +00003098 rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00003099 if( rc ) return rc;
drhda200cc2004-05-09 11:51:38 +00003100 pageIntegrity(pNewPage);
drh428ae8c2003-01-04 16:48:09 +00003101 pNewPage->idxParent = pCur->idx;
drh3aac2dd2004-04-26 14:10:20 +00003102 pOldPage = pCur->pPage;
3103 pOldPage->idxShift = 0;
3104 releasePage(pOldPage);
drh72f82862001-05-24 21:06:34 +00003105 pCur->pPage = pNewPage;
3106 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00003107 pCur->info.nSize = 0;
drh4be295b2003-12-16 03:44:47 +00003108 if( pNewPage->nCell<1 ){
drh49285702005-09-17 15:20:26 +00003109 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00003110 }
drh72f82862001-05-24 21:06:34 +00003111 return SQLITE_OK;
3112}
3113
3114/*
drh8856d6a2004-04-29 14:42:46 +00003115** Return true if the page is the virtual root of its table.
3116**
3117** The virtual root page is the root page for most tables. But
3118** for the table rooted on page 1, sometime the real root page
3119** is empty except for the right-pointer. In such cases the
3120** virtual root page is the page that the right-pointer of page
3121** 1 is pointing to.
3122*/
3123static int isRootPage(MemPage *pPage){
3124 MemPage *pParent = pPage->pParent;
drhda200cc2004-05-09 11:51:38 +00003125 if( pParent==0 ) return 1;
3126 if( pParent->pgno>1 ) return 0;
3127 if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
drh8856d6a2004-04-29 14:42:46 +00003128 return 0;
3129}
3130
3131/*
drh5e2f8b92001-05-28 00:41:15 +00003132** Move the cursor up to the parent page.
3133**
3134** pCur->idx is set to the cell index that contains the pointer
3135** to the page we are coming from. If we are coming from the
3136** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00003137** the largest cell index.
drh72f82862001-05-24 21:06:34 +00003138*/
drh8178a752003-01-05 21:41:40 +00003139static void moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00003140 MemPage *pParent;
drh8178a752003-01-05 21:41:40 +00003141 MemPage *pPage;
drh428ae8c2003-01-04 16:48:09 +00003142 int idxParent;
drh3aac2dd2004-04-26 14:10:20 +00003143
danielk1977da184232006-01-05 11:34:32 +00003144 assert( pCur->eState==CURSOR_VALID );
drh8178a752003-01-05 21:41:40 +00003145 pPage = pCur->pPage;
3146 assert( pPage!=0 );
drh8856d6a2004-04-29 14:42:46 +00003147 assert( !isRootPage(pPage) );
drhda200cc2004-05-09 11:51:38 +00003148 pageIntegrity(pPage);
drh8178a752003-01-05 21:41:40 +00003149 pParent = pPage->pParent;
3150 assert( pParent!=0 );
drhda200cc2004-05-09 11:51:38 +00003151 pageIntegrity(pParent);
drh8178a752003-01-05 21:41:40 +00003152 idxParent = pPage->idxParent;
drha34b6762004-05-07 13:30:42 +00003153 sqlite3pager_ref(pParent->aData);
drh3aac2dd2004-04-26 14:10:20 +00003154 releasePage(pPage);
drh72f82862001-05-24 21:06:34 +00003155 pCur->pPage = pParent;
drh271efa52004-05-30 19:19:05 +00003156 pCur->info.nSize = 0;
drh428ae8c2003-01-04 16:48:09 +00003157 assert( pParent->idxShift==0 );
drh43605152004-05-29 21:46:49 +00003158 pCur->idx = idxParent;
drh72f82862001-05-24 21:06:34 +00003159}
3160
3161/*
3162** Move the cursor to the root page
3163*/
drh5e2f8b92001-05-28 00:41:15 +00003164static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00003165 MemPage *pRoot;
drhbd03cae2001-06-02 02:40:57 +00003166 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003167 BtShared *pBt = pCur->pBtree->pBt;
drhbd03cae2001-06-02 02:40:57 +00003168
danielk19772e94d4d2006-01-09 05:36:27 +00003169 if(
3170 SQLITE_OK!=(rc = restoreCursorPosition(pCur, 0)) ||
3171 SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0))
3172 ){
danielk1977da184232006-01-05 11:34:32 +00003173 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00003174 return rc;
3175 }
drh3aac2dd2004-04-26 14:10:20 +00003176 releasePage(pCur->pPage);
drhda200cc2004-05-09 11:51:38 +00003177 pageIntegrity(pRoot);
drh3aac2dd2004-04-26 14:10:20 +00003178 pCur->pPage = pRoot;
drh72f82862001-05-24 21:06:34 +00003179 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00003180 pCur->info.nSize = 0;
drh8856d6a2004-04-29 14:42:46 +00003181 if( pRoot->nCell==0 && !pRoot->leaf ){
3182 Pgno subpage;
3183 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00003184 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00003185 assert( subpage>0 );
danielk1977da184232006-01-05 11:34:32 +00003186 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00003187 rc = moveToChild(pCur, subpage);
drh8856d6a2004-04-29 14:42:46 +00003188 }
danielk1977da184232006-01-05 11:34:32 +00003189 pCur->eState = ((pCur->pPage->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00003190 return rc;
drh72f82862001-05-24 21:06:34 +00003191}
drh2af926b2001-05-15 00:39:25 +00003192
drh5e2f8b92001-05-28 00:41:15 +00003193/*
3194** Move the cursor down to the left-most leaf entry beneath the
3195** entry to which it is currently pointing.
3196*/
3197static int moveToLeftmost(BtCursor *pCur){
3198 Pgno pgno;
3199 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003200 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00003201
danielk1977da184232006-01-05 11:34:32 +00003202 assert( pCur->eState==CURSOR_VALID );
drh3aac2dd2004-04-26 14:10:20 +00003203 while( !(pPage = pCur->pPage)->leaf ){
drha34b6762004-05-07 13:30:42 +00003204 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00003205 pgno = get4byte(findCell(pPage, pCur->idx));
drh8178a752003-01-05 21:41:40 +00003206 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00003207 if( rc ) return rc;
3208 }
3209 return SQLITE_OK;
3210}
3211
drh2dcc9aa2002-12-04 13:40:25 +00003212/*
3213** Move the cursor down to the right-most leaf entry beneath the
3214** page to which it is currently pointing. Notice the difference
3215** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
3216** finds the left-most entry beneath the *entry* whereas moveToRightmost()
3217** finds the right-most entry beneath the *page*.
3218*/
3219static int moveToRightmost(BtCursor *pCur){
3220 Pgno pgno;
3221 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003222 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003223
danielk1977da184232006-01-05 11:34:32 +00003224 assert( pCur->eState==CURSOR_VALID );
drh3aac2dd2004-04-26 14:10:20 +00003225 while( !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00003226 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh3aac2dd2004-04-26 14:10:20 +00003227 pCur->idx = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00003228 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003229 if( rc ) return rc;
3230 }
drh3aac2dd2004-04-26 14:10:20 +00003231 pCur->idx = pPage->nCell - 1;
drh271efa52004-05-30 19:19:05 +00003232 pCur->info.nSize = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003233 return SQLITE_OK;
3234}
3235
drh5e00f6c2001-09-13 13:46:56 +00003236/* Move the cursor to the first entry in the table. Return SQLITE_OK
3237** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003238** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00003239*/
drh3aac2dd2004-04-26 14:10:20 +00003240int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00003241 int rc;
3242 rc = moveToRoot(pCur);
3243 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00003244 if( pCur->eState==CURSOR_INVALID ){
drhc39e0002004-05-07 23:50:57 +00003245 assert( pCur->pPage->nCell==0 );
drh5e00f6c2001-09-13 13:46:56 +00003246 *pRes = 1;
3247 return SQLITE_OK;
3248 }
drhc39e0002004-05-07 23:50:57 +00003249 assert( pCur->pPage->nCell>0 );
drh5e00f6c2001-09-13 13:46:56 +00003250 *pRes = 0;
3251 rc = moveToLeftmost(pCur);
3252 return rc;
3253}
drh5e2f8b92001-05-28 00:41:15 +00003254
drh9562b552002-02-19 15:00:07 +00003255/* Move the cursor to the last entry in the table. Return SQLITE_OK
3256** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003257** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00003258*/
drh3aac2dd2004-04-26 14:10:20 +00003259int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00003260 int rc;
drh9562b552002-02-19 15:00:07 +00003261 rc = moveToRoot(pCur);
3262 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00003263 if( CURSOR_INVALID==pCur->eState ){
drhc39e0002004-05-07 23:50:57 +00003264 assert( pCur->pPage->nCell==0 );
drh9562b552002-02-19 15:00:07 +00003265 *pRes = 1;
3266 return SQLITE_OK;
3267 }
danielk1977da184232006-01-05 11:34:32 +00003268 assert( pCur->eState==CURSOR_VALID );
drh9562b552002-02-19 15:00:07 +00003269 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003270 rc = moveToRightmost(pCur);
drh9562b552002-02-19 15:00:07 +00003271 return rc;
3272}
3273
drh3aac2dd2004-04-26 14:10:20 +00003274/* Move the cursor so that it points to an entry near pKey/nKey.
drh72f82862001-05-24 21:06:34 +00003275** Return a success code.
3276**
drh3aac2dd2004-04-26 14:10:20 +00003277** For INTKEY tables, only the nKey parameter is used. pKey is
3278** ignored. For other tables, nKey is the number of bytes of data
drh0b2f3162005-12-21 18:36:45 +00003279** in pKey. The comparison function specified when the cursor was
drh3aac2dd2004-04-26 14:10:20 +00003280** created is used to compare keys.
3281**
drh5e2f8b92001-05-28 00:41:15 +00003282** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00003283** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00003284** were present. The cursor might point to an entry that comes
3285** before or after the key.
3286**
drhbd03cae2001-06-02 02:40:57 +00003287** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00003288** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00003289** this value is as follows:
3290**
3291** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00003292** is smaller than pKey or if the table is empty
3293** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00003294**
3295** *pRes==0 The cursor is left pointing at an entry that
3296** exactly matches pKey.
3297**
3298** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00003299** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00003300*/
drh4a1c3802004-05-12 15:15:47 +00003301int sqlite3BtreeMoveto(BtCursor *pCur, const void *pKey, i64 nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00003302 int rc;
drh5e2f8b92001-05-28 00:41:15 +00003303 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00003304 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00003305 assert( pCur->pPage );
3306 assert( pCur->pPage->isInit );
danielk1977da184232006-01-05 11:34:32 +00003307 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00003308 *pRes = -1;
drhc39e0002004-05-07 23:50:57 +00003309 assert( pCur->pPage->nCell==0 );
3310 return SQLITE_OK;
3311 }
drh4eec4c12005-01-21 00:22:37 +00003312 for(;;){
drh72f82862001-05-24 21:06:34 +00003313 int lwr, upr;
3314 Pgno chldPg;
3315 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00003316 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00003317 lwr = 0;
3318 upr = pPage->nCell-1;
drh4eec4c12005-01-21 00:22:37 +00003319 if( !pPage->intKey && pKey==0 ){
drh49285702005-09-17 15:20:26 +00003320 return SQLITE_CORRUPT_BKPT;
drh4eec4c12005-01-21 00:22:37 +00003321 }
drhda200cc2004-05-09 11:51:38 +00003322 pageIntegrity(pPage);
drh72f82862001-05-24 21:06:34 +00003323 while( lwr<=upr ){
danielk197713adf8a2004-06-03 16:08:41 +00003324 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00003325 i64 nCellKey;
drh72f82862001-05-24 21:06:34 +00003326 pCur->idx = (lwr+upr)/2;
drh271efa52004-05-30 19:19:05 +00003327 pCur->info.nSize = 0;
drhde647132004-05-07 17:57:49 +00003328 sqlite3BtreeKeySize(pCur, &nCellKey);
drh3aac2dd2004-04-26 14:10:20 +00003329 if( pPage->intKey ){
3330 if( nCellKey<nKey ){
3331 c = -1;
3332 }else if( nCellKey>nKey ){
3333 c = +1;
3334 }else{
3335 c = 0;
3336 }
drh3aac2dd2004-04-26 14:10:20 +00003337 }else{
drhe51c44f2004-05-30 20:46:09 +00003338 int available;
danielk197713adf8a2004-06-03 16:08:41 +00003339 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drhe51c44f2004-05-30 20:46:09 +00003340 if( available>=nCellKey ){
3341 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
3342 }else{
3343 pCellKey = sqliteMallocRaw( nCellKey );
3344 if( pCellKey==0 ) return SQLITE_NOMEM;
danielk197713adf8a2004-06-03 16:08:41 +00003345 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
drhe51c44f2004-05-30 20:46:09 +00003346 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
3347 sqliteFree(pCellKey);
3348 if( rc ) return rc;
3349 }
drh3aac2dd2004-04-26 14:10:20 +00003350 }
drh72f82862001-05-24 21:06:34 +00003351 if( c==0 ){
drh8b18dd42004-05-12 19:18:15 +00003352 if( pPage->leafData && !pPage->leaf ){
drhfc70e6f2004-05-12 21:11:27 +00003353 lwr = pCur->idx;
3354 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00003355 break;
3356 }else{
drh8b18dd42004-05-12 19:18:15 +00003357 if( pRes ) *pRes = 0;
3358 return SQLITE_OK;
3359 }
drh72f82862001-05-24 21:06:34 +00003360 }
3361 if( c<0 ){
3362 lwr = pCur->idx+1;
3363 }else{
3364 upr = pCur->idx-1;
3365 }
3366 }
3367 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00003368 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00003369 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00003370 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00003371 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00003372 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00003373 }else{
drh43605152004-05-29 21:46:49 +00003374 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00003375 }
3376 if( chldPg==0 ){
drhc39e0002004-05-07 23:50:57 +00003377 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00003378 if( pRes ) *pRes = c;
3379 return SQLITE_OK;
3380 }
drh428ae8c2003-01-04 16:48:09 +00003381 pCur->idx = lwr;
drh271efa52004-05-30 19:19:05 +00003382 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00003383 rc = moveToChild(pCur, chldPg);
drhc39e0002004-05-07 23:50:57 +00003384 if( rc ){
3385 return rc;
3386 }
drh72f82862001-05-24 21:06:34 +00003387 }
drhbd03cae2001-06-02 02:40:57 +00003388 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00003389}
3390
3391/*
drhc39e0002004-05-07 23:50:57 +00003392** Return TRUE if the cursor is not pointing at an entry of the table.
3393**
3394** TRUE will be returned after a call to sqlite3BtreeNext() moves
3395** past the last entry in the table or sqlite3BtreePrev() moves past
3396** the first entry. TRUE is also returned if the table is empty.
3397*/
3398int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00003399 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
3400 ** have been deleted? This API will need to change to return an error code
3401 ** as well as the boolean result value.
3402 */
3403 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00003404}
3405
3406/*
drhbd03cae2001-06-02 02:40:57 +00003407** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00003408** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00003409** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00003410** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00003411*/
drh3aac2dd2004-04-26 14:10:20 +00003412int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00003413 int rc;
drh8178a752003-01-05 21:41:40 +00003414 MemPage *pPage = pCur->pPage;
drh8b18dd42004-05-12 19:18:15 +00003415
danielk1977da184232006-01-05 11:34:32 +00003416#ifndef SQLITE_OMIT_SHARED_CACHE
3417 rc = restoreCursorPosition(pCur, 1);
3418 if( rc!=SQLITE_OK ){
3419 return rc;
3420 }
3421 if( pCur->skip>0 ){
3422 pCur->skip = 0;
3423 *pRes = 0;
3424 return SQLITE_OK;
3425 }
3426 pCur->skip = 0;
3427#endif
3428
drh8c1238a2003-01-02 14:43:55 +00003429 assert( pRes!=0 );
danielk1977da184232006-01-05 11:34:32 +00003430 if( CURSOR_INVALID==pCur->eState ){
drh8c1238a2003-01-02 14:43:55 +00003431 *pRes = 1;
drhc39e0002004-05-07 23:50:57 +00003432 return SQLITE_OK;
drhecdc7532001-09-23 02:35:53 +00003433 }
drh8178a752003-01-05 21:41:40 +00003434 assert( pPage->isInit );
drh8178a752003-01-05 21:41:40 +00003435 assert( pCur->idx<pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00003436
drh72f82862001-05-24 21:06:34 +00003437 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00003438 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00003439 if( pCur->idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00003440 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003441 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00003442 if( rc ) return rc;
3443 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003444 *pRes = 0;
3445 return rc;
drh72f82862001-05-24 21:06:34 +00003446 }
drh5e2f8b92001-05-28 00:41:15 +00003447 do{
drh8856d6a2004-04-29 14:42:46 +00003448 if( isRootPage(pPage) ){
drh8c1238a2003-01-02 14:43:55 +00003449 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00003450 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00003451 return SQLITE_OK;
3452 }
drh8178a752003-01-05 21:41:40 +00003453 moveToParent(pCur);
3454 pPage = pCur->pPage;
3455 }while( pCur->idx>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00003456 *pRes = 0;
drh8b18dd42004-05-12 19:18:15 +00003457 if( pPage->leafData ){
3458 rc = sqlite3BtreeNext(pCur, pRes);
3459 }else{
3460 rc = SQLITE_OK;
3461 }
3462 return rc;
drh8178a752003-01-05 21:41:40 +00003463 }
3464 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00003465 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00003466 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00003467 }
drh5e2f8b92001-05-28 00:41:15 +00003468 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003469 return rc;
drh72f82862001-05-24 21:06:34 +00003470}
3471
drh3b7511c2001-05-26 13:15:44 +00003472/*
drh2dcc9aa2002-12-04 13:40:25 +00003473** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00003474** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00003475** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00003476** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00003477*/
drh3aac2dd2004-04-26 14:10:20 +00003478int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00003479 int rc;
3480 Pgno pgno;
drh8178a752003-01-05 21:41:40 +00003481 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00003482
3483#ifndef SQLITE_OMIT_SHARED_CACHE
3484 rc = restoreCursorPosition(pCur, 1);
3485 if( rc!=SQLITE_OK ){
3486 return rc;
3487 }
3488 if( pCur->skip<0 ){
3489 pCur->skip = 0;
3490 *pRes = 0;
3491 return SQLITE_OK;
3492 }
3493 pCur->skip = 0;
3494#endif
3495
3496 if( CURSOR_INVALID==pCur->eState ){
drhc39e0002004-05-07 23:50:57 +00003497 *pRes = 1;
3498 return SQLITE_OK;
3499 }
danielk19776a43f9b2004-11-16 04:57:24 +00003500
drh8178a752003-01-05 21:41:40 +00003501 pPage = pCur->pPage;
drh8178a752003-01-05 21:41:40 +00003502 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00003503 assert( pCur->idx>=0 );
drha34b6762004-05-07 13:30:42 +00003504 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003505 pgno = get4byte( findCell(pPage, pCur->idx) );
drh8178a752003-01-05 21:41:40 +00003506 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003507 if( rc ) return rc;
3508 rc = moveToRightmost(pCur);
3509 }else{
3510 while( pCur->idx==0 ){
drh8856d6a2004-04-29 14:42:46 +00003511 if( isRootPage(pPage) ){
danielk1977da184232006-01-05 11:34:32 +00003512 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00003513 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00003514 return SQLITE_OK;
3515 }
drh8178a752003-01-05 21:41:40 +00003516 moveToParent(pCur);
3517 pPage = pCur->pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003518 }
3519 pCur->idx--;
drh271efa52004-05-30 19:19:05 +00003520 pCur->info.nSize = 0;
drh8237d452004-11-22 19:07:09 +00003521 if( pPage->leafData && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00003522 rc = sqlite3BtreePrevious(pCur, pRes);
3523 }else{
3524 rc = SQLITE_OK;
3525 }
drh2dcc9aa2002-12-04 13:40:25 +00003526 }
drh8178a752003-01-05 21:41:40 +00003527 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003528 return rc;
3529}
3530
3531/*
drh3b7511c2001-05-26 13:15:44 +00003532** Allocate a new page from the database file.
3533**
drha34b6762004-05-07 13:30:42 +00003534** The new page is marked as dirty. (In other words, sqlite3pager_write()
drh3b7511c2001-05-26 13:15:44 +00003535** has already been called on the new page.) The new page has also
3536** been referenced and the calling routine is responsible for calling
drha34b6762004-05-07 13:30:42 +00003537** sqlite3pager_unref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00003538**
3539** SQLITE_OK is returned on success. Any other return value indicates
3540** an error. *ppPage and *pPgno are undefined in the event of an error.
drha34b6762004-05-07 13:30:42 +00003541** Do not invoke sqlite3pager_unref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00003542**
drh199e3cf2002-07-18 11:01:47 +00003543** If the "nearby" parameter is not 0, then a (feeble) effort is made to
3544** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00003545** attempt to keep related pages close to each other in the database file,
3546** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00003547**
3548** If the "exact" parameter is not 0, and the page-number nearby exists
3549** anywhere on the free-list, then it is guarenteed to be returned. This
3550** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00003551*/
danielk1977cb1a7eb2004-11-05 12:27:02 +00003552static int allocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00003553 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00003554 MemPage **ppPage,
3555 Pgno *pPgno,
3556 Pgno nearby,
3557 u8 exact
3558){
drh3aac2dd2004-04-26 14:10:20 +00003559 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00003560 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003561 int n; /* Number of pages on the freelist */
3562 int k; /* Number of leaves on the trunk of the freelist */
drh30e58752002-03-02 20:41:57 +00003563
drh3aac2dd2004-04-26 14:10:20 +00003564 pPage1 = pBt->pPage1;
3565 n = get4byte(&pPage1->aData[36]);
3566 if( n>0 ){
drh91025292004-05-03 19:49:32 +00003567 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00003568 MemPage *pTrunk = 0;
3569 Pgno iTrunk;
3570 MemPage *pPrevTrunk = 0;
3571 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
3572
3573 /* If the 'exact' parameter was true and a query of the pointer-map
3574 ** shows that the page 'nearby' is somewhere on the free-list, then
3575 ** the entire-list will be searched for that page.
3576 */
3577#ifndef SQLITE_OMIT_AUTOVACUUM
3578 if( exact ){
3579 u8 eType;
3580 assert( nearby>0 );
3581 assert( pBt->autoVacuum );
3582 rc = ptrmapGet(pBt, nearby, &eType, 0);
3583 if( rc ) return rc;
3584 if( eType==PTRMAP_FREEPAGE ){
3585 searchList = 1;
3586 }
3587 *pPgno = nearby;
3588 }
3589#endif
3590
3591 /* Decrement the free-list count by 1. Set iTrunk to the index of the
3592 ** first free-list trunk page. iPrevTrunk is initially 1.
3593 */
drha34b6762004-05-07 13:30:42 +00003594 rc = sqlite3pager_write(pPage1->aData);
drh3b7511c2001-05-26 13:15:44 +00003595 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003596 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003597
3598 /* The code within this loop is run only once if the 'searchList' variable
3599 ** is not true. Otherwise, it runs once for each trunk-page on the
3600 ** free-list until the page 'nearby' is located.
3601 */
3602 do {
3603 pPrevTrunk = pTrunk;
3604 if( pPrevTrunk ){
3605 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00003606 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00003607 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00003608 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003609 rc = getPage(pBt, iTrunk, &pTrunk);
3610 if( rc ){
3611 releasePage(pPrevTrunk);
3612 return rc;
3613 }
3614
3615 /* TODO: This should move to after the loop? */
3616 rc = sqlite3pager_write(pTrunk->aData);
3617 if( rc ){
3618 releasePage(pTrunk);
3619 releasePage(pPrevTrunk);
3620 return rc;
3621 }
3622
3623 k = get4byte(&pTrunk->aData[4]);
3624 if( k==0 && !searchList ){
3625 /* The trunk has no leaves and the list is not being searched.
3626 ** So extract the trunk page itself and use it as the newly
3627 ** allocated page */
3628 assert( pPrevTrunk==0 );
3629 *pPgno = iTrunk;
3630 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3631 *ppPage = pTrunk;
3632 pTrunk = 0;
3633 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3634 }else if( k>pBt->usableSize/4 - 8 ){
3635 /* Value of k is out of range. Database corruption */
drh49285702005-09-17 15:20:26 +00003636 return SQLITE_CORRUPT_BKPT;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003637#ifndef SQLITE_OMIT_AUTOVACUUM
3638 }else if( searchList && nearby==iTrunk ){
3639 /* The list is being searched and this trunk page is the page
3640 ** to allocate, regardless of whether it has leaves.
3641 */
3642 assert( *pPgno==iTrunk );
3643 *ppPage = pTrunk;
3644 searchList = 0;
3645 if( k==0 ){
3646 if( !pPrevTrunk ){
3647 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3648 }else{
3649 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
3650 }
3651 }else{
3652 /* The trunk page is required by the caller but it contains
3653 ** pointers to free-list leaves. The first leaf becomes a trunk
3654 ** page in this case.
3655 */
3656 MemPage *pNewTrunk;
3657 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
3658 rc = getPage(pBt, iNewTrunk, &pNewTrunk);
3659 if( rc!=SQLITE_OK ){
3660 releasePage(pTrunk);
3661 releasePage(pPrevTrunk);
3662 return rc;
3663 }
3664 rc = sqlite3pager_write(pNewTrunk->aData);
3665 if( rc!=SQLITE_OK ){
3666 releasePage(pNewTrunk);
3667 releasePage(pTrunk);
3668 releasePage(pPrevTrunk);
3669 return rc;
3670 }
3671 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
3672 put4byte(&pNewTrunk->aData[4], k-1);
3673 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
3674 if( !pPrevTrunk ){
3675 put4byte(&pPage1->aData[32], iNewTrunk);
3676 }else{
3677 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
3678 }
3679 releasePage(pNewTrunk);
3680 }
3681 pTrunk = 0;
3682 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3683#endif
3684 }else{
3685 /* Extract a leaf from the trunk */
3686 int closest;
3687 Pgno iPage;
3688 unsigned char *aData = pTrunk->aData;
3689 if( nearby>0 ){
3690 int i, dist;
3691 closest = 0;
3692 dist = get4byte(&aData[8]) - nearby;
3693 if( dist<0 ) dist = -dist;
3694 for(i=1; i<k; i++){
3695 int d2 = get4byte(&aData[8+i*4]) - nearby;
3696 if( d2<0 ) d2 = -d2;
3697 if( d2<dist ){
3698 closest = i;
3699 dist = d2;
3700 }
3701 }
3702 }else{
3703 closest = 0;
3704 }
3705
3706 iPage = get4byte(&aData[8+closest*4]);
3707 if( !searchList || iPage==nearby ){
3708 *pPgno = iPage;
3709 if( *pPgno>sqlite3pager_pagecount(pBt->pPager) ){
3710 /* Free page off the end of the file */
drh49285702005-09-17 15:20:26 +00003711 return SQLITE_CORRUPT_BKPT;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003712 }
3713 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
3714 ": %d more free pages\n",
3715 *pPgno, closest+1, k, pTrunk->pgno, n-1));
3716 if( closest<k-1 ){
3717 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
3718 }
3719 put4byte(&aData[4], k-1);
3720 rc = getPage(pBt, *pPgno, ppPage);
3721 if( rc==SQLITE_OK ){
3722 sqlite3pager_dont_rollback((*ppPage)->aData);
3723 rc = sqlite3pager_write((*ppPage)->aData);
danielk1977aac0a382005-01-16 11:07:06 +00003724 if( rc!=SQLITE_OK ){
3725 releasePage(*ppPage);
3726 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003727 }
3728 searchList = 0;
3729 }
drhee696e22004-08-30 16:52:17 +00003730 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003731 releasePage(pPrevTrunk);
3732 }while( searchList );
3733 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003734 }else{
drh3aac2dd2004-04-26 14:10:20 +00003735 /* There are no pages on the freelist, so create a new page at the
3736 ** end of the file */
drha34b6762004-05-07 13:30:42 +00003737 *pPgno = sqlite3pager_pagecount(pBt->pPager) + 1;
danielk1977afcdd022004-10-31 16:25:42 +00003738
3739#ifndef SQLITE_OMIT_AUTOVACUUM
drh42cac6d2004-11-20 20:31:11 +00003740 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt->usableSize, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00003741 /* If *pPgno refers to a pointer-map page, allocate two new pages
3742 ** at the end of the file instead of one. The first allocated page
3743 ** becomes a new pointer-map page, the second is used by the caller.
3744 */
3745 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00003746 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977afcdd022004-10-31 16:25:42 +00003747 (*pPgno)++;
3748 }
3749#endif
3750
danielk1977599fcba2004-11-08 07:13:13 +00003751 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00003752 rc = getPage(pBt, *pPgno, ppPage);
drh3b7511c2001-05-26 13:15:44 +00003753 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003754 rc = sqlite3pager_write((*ppPage)->aData);
danielk1977aac0a382005-01-16 11:07:06 +00003755 if( rc!=SQLITE_OK ){
3756 releasePage(*ppPage);
3757 }
drh3a4c1412004-05-09 20:40:11 +00003758 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00003759 }
danielk1977599fcba2004-11-08 07:13:13 +00003760
3761 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh3b7511c2001-05-26 13:15:44 +00003762 return rc;
3763}
3764
3765/*
drh3aac2dd2004-04-26 14:10:20 +00003766** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00003767**
drha34b6762004-05-07 13:30:42 +00003768** sqlite3pager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00003769*/
drh3aac2dd2004-04-26 14:10:20 +00003770static int freePage(MemPage *pPage){
danielk1977aef0bf62005-12-30 16:28:01 +00003771 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00003772 MemPage *pPage1 = pBt->pPage1;
3773 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00003774
drh3aac2dd2004-04-26 14:10:20 +00003775 /* Prepare the page for freeing */
3776 assert( pPage->pgno>1 );
3777 pPage->isInit = 0;
3778 releasePage(pPage->pParent);
3779 pPage->pParent = 0;
3780
drha34b6762004-05-07 13:30:42 +00003781 /* Increment the free page count on pPage1 */
3782 rc = sqlite3pager_write(pPage1->aData);
drh3aac2dd2004-04-26 14:10:20 +00003783 if( rc ) return rc;
3784 n = get4byte(&pPage1->aData[36]);
3785 put4byte(&pPage1->aData[36], n+1);
3786
danielk1977687566d2004-11-02 12:56:41 +00003787#ifndef SQLITE_OMIT_AUTOVACUUM
3788 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00003789 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00003790 */
3791 if( pBt->autoVacuum ){
3792 rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
danielk1977a64a0352004-11-05 01:45:13 +00003793 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00003794 }
3795#endif
3796
drh3aac2dd2004-04-26 14:10:20 +00003797 if( n==0 ){
3798 /* This is the first free page */
drhda200cc2004-05-09 11:51:38 +00003799 rc = sqlite3pager_write(pPage->aData);
3800 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003801 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00003802 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003803 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003804 }else{
3805 /* Other free pages already exist. Retrive the first trunk page
3806 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00003807 MemPage *pTrunk;
3808 rc = getPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003809 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003810 k = get4byte(&pTrunk->aData[4]);
drhee696e22004-08-30 16:52:17 +00003811 if( k>=pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00003812 /* The trunk is full. Turn the page being freed into a new
3813 ** trunk page with no leaves. */
drha34b6762004-05-07 13:30:42 +00003814 rc = sqlite3pager_write(pPage->aData);
drh3aac2dd2004-04-26 14:10:20 +00003815 if( rc ) return rc;
3816 put4byte(pPage->aData, pTrunk->pgno);
3817 put4byte(&pPage->aData[4], 0);
3818 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003819 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
3820 pPage->pgno, pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003821 }else{
3822 /* Add the newly freed page as a leaf on the current trunk */
drha34b6762004-05-07 13:30:42 +00003823 rc = sqlite3pager_write(pTrunk->aData);
drh3aac2dd2004-04-26 14:10:20 +00003824 if( rc ) return rc;
3825 put4byte(&pTrunk->aData[4], k+1);
3826 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drha34b6762004-05-07 13:30:42 +00003827 sqlite3pager_dont_write(pBt->pPager, pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003828 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003829 }
3830 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003831 }
drh3b7511c2001-05-26 13:15:44 +00003832 return rc;
3833}
3834
3835/*
drh3aac2dd2004-04-26 14:10:20 +00003836** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00003837*/
drh3aac2dd2004-04-26 14:10:20 +00003838static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00003839 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00003840 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00003841 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00003842 int rc;
drh3b7511c2001-05-26 13:15:44 +00003843
drh43605152004-05-29 21:46:49 +00003844 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003845 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00003846 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00003847 }
drh6f11bef2004-05-13 01:12:56 +00003848 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh3aac2dd2004-04-26 14:10:20 +00003849 while( ovflPgno!=0 ){
3850 MemPage *pOvfl;
danielk1977a1cb1832005-02-12 08:59:55 +00003851 if( ovflPgno>sqlite3pager_pagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00003852 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00003853 }
drh3aac2dd2004-04-26 14:10:20 +00003854 rc = getPage(pBt, ovflPgno, &pOvfl);
drh3b7511c2001-05-26 13:15:44 +00003855 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003856 ovflPgno = get4byte(pOvfl->aData);
drha34b6762004-05-07 13:30:42 +00003857 rc = freePage(pOvfl);
drha34b6762004-05-07 13:30:42 +00003858 sqlite3pager_unref(pOvfl->aData);
danielk19776b456a22005-03-21 04:04:02 +00003859 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00003860 }
drh5e2f8b92001-05-28 00:41:15 +00003861 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00003862}
3863
3864/*
drh91025292004-05-03 19:49:32 +00003865** Create the byte sequence used to represent a cell on page pPage
3866** and write that byte sequence into pCell[]. Overflow pages are
3867** allocated and filled in as necessary. The calling procedure
3868** is responsible for making sure sufficient space has been allocated
3869** for pCell[].
3870**
3871** Note that pCell does not necessary need to point to the pPage->aData
3872** area. pCell might point to some temporary storage. The cell will
3873** be constructed in this temporary area then copied into pPage->aData
3874** later.
drh3b7511c2001-05-26 13:15:44 +00003875*/
3876static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00003877 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00003878 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00003879 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00003880 const void *pData,int nData, /* The data */
3881 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00003882){
drh3b7511c2001-05-26 13:15:44 +00003883 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00003884 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00003885 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00003886 int spaceLeft;
3887 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00003888 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00003889 unsigned char *pPrior;
3890 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00003891 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00003892 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00003893 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00003894 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00003895
drh91025292004-05-03 19:49:32 +00003896 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00003897 nHeader = 0;
drh91025292004-05-03 19:49:32 +00003898 if( !pPage->leaf ){
3899 nHeader += 4;
3900 }
drh8b18dd42004-05-12 19:18:15 +00003901 if( pPage->hasData ){
drh91025292004-05-03 19:49:32 +00003902 nHeader += putVarint(&pCell[nHeader], nData);
drh6f11bef2004-05-13 01:12:56 +00003903 }else{
drh91025292004-05-03 19:49:32 +00003904 nData = 0;
3905 }
drh6f11bef2004-05-13 01:12:56 +00003906 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh43605152004-05-29 21:46:49 +00003907 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003908 assert( info.nHeader==nHeader );
3909 assert( info.nKey==nKey );
3910 assert( info.nData==nData );
3911
3912 /* Fill in the payload */
drh3aac2dd2004-04-26 14:10:20 +00003913 nPayload = nData;
3914 if( pPage->intKey ){
3915 pSrc = pData;
3916 nSrc = nData;
drh91025292004-05-03 19:49:32 +00003917 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00003918 }else{
3919 nPayload += nKey;
3920 pSrc = pKey;
3921 nSrc = nKey;
3922 }
drh6f11bef2004-05-13 01:12:56 +00003923 *pnSize = info.nSize;
3924 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00003925 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00003926 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00003927
drh3b7511c2001-05-26 13:15:44 +00003928 while( nPayload>0 ){
3929 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00003930#ifndef SQLITE_OMIT_AUTOVACUUM
3931 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
3932#endif
danielk1977cb1a7eb2004-11-05 12:27:02 +00003933 rc = allocatePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00003934#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00003935 /* If the database supports auto-vacuum, and the second or subsequent
3936 ** overflow page is being allocated, add an entry to the pointer-map
3937 ** for that page now. The entry for the first overflow page will be
3938 ** added later, by the insertCell() routine.
danielk1977afcdd022004-10-31 16:25:42 +00003939 */
danielk1977a19df672004-11-03 11:37:07 +00003940 if( pBt->autoVacuum && pgnoPtrmap!=0 && rc==SQLITE_OK ){
3941 rc = ptrmapPut(pBt, pgnoOvfl, PTRMAP_OVERFLOW2, pgnoPtrmap);
danielk1977afcdd022004-10-31 16:25:42 +00003942 }
3943#endif
drh3b7511c2001-05-26 13:15:44 +00003944 if( rc ){
drh9b171272004-05-08 02:03:22 +00003945 releasePage(pToRelease);
danielk197728129562005-01-11 10:25:06 +00003946 /* clearCell(pPage, pCell); */
drh3b7511c2001-05-26 13:15:44 +00003947 return rc;
3948 }
drh3aac2dd2004-04-26 14:10:20 +00003949 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00003950 releasePage(pToRelease);
3951 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00003952 pPrior = pOvfl->aData;
3953 put4byte(pPrior, 0);
3954 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00003955 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00003956 }
3957 n = nPayload;
3958 if( n>spaceLeft ) n = spaceLeft;
drh3aac2dd2004-04-26 14:10:20 +00003959 if( n>nSrc ) n = nSrc;
3960 memcpy(pPayload, pSrc, n);
drh3b7511c2001-05-26 13:15:44 +00003961 nPayload -= n;
drhde647132004-05-07 17:57:49 +00003962 pPayload += n;
drh9b171272004-05-08 02:03:22 +00003963 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00003964 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00003965 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00003966 if( nSrc==0 ){
3967 nSrc = nData;
3968 pSrc = pData;
3969 }
drhdd793422001-06-28 01:54:48 +00003970 }
drh9b171272004-05-08 02:03:22 +00003971 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00003972 return SQLITE_OK;
3973}
3974
3975/*
drhbd03cae2001-06-02 02:40:57 +00003976** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00003977** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00003978** pointer in the third argument.
3979*/
danielk1977aef0bf62005-12-30 16:28:01 +00003980static int reparentPage(BtShared *pBt, Pgno pgno, MemPage *pNewParent, int idx){
drhbd03cae2001-06-02 02:40:57 +00003981 MemPage *pThis;
drh4b70f112004-05-02 21:12:19 +00003982 unsigned char *aData;
drhbd03cae2001-06-02 02:40:57 +00003983
danielk1977afcdd022004-10-31 16:25:42 +00003984 if( pgno==0 ) return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00003985 assert( pBt->pPager!=0 );
drha34b6762004-05-07 13:30:42 +00003986 aData = sqlite3pager_lookup(pBt->pPager, pgno);
drhda200cc2004-05-09 11:51:38 +00003987 if( aData ){
drh07d183d2005-05-01 22:52:42 +00003988 pThis = (MemPage*)&aData[pBt->pageSize];
drh31276532004-09-27 12:20:52 +00003989 assert( pThis->aData==aData );
drhda200cc2004-05-09 11:51:38 +00003990 if( pThis->isInit ){
3991 if( pThis->pParent!=pNewParent ){
3992 if( pThis->pParent ) sqlite3pager_unref(pThis->pParent->aData);
3993 pThis->pParent = pNewParent;
3994 if( pNewParent ) sqlite3pager_ref(pNewParent->aData);
3995 }
3996 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00003997 }
drha34b6762004-05-07 13:30:42 +00003998 sqlite3pager_unref(aData);
drhbd03cae2001-06-02 02:40:57 +00003999 }
danielk1977afcdd022004-10-31 16:25:42 +00004000
4001#ifndef SQLITE_OMIT_AUTOVACUUM
4002 if( pBt->autoVacuum ){
4003 return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
4004 }
4005#endif
4006 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00004007}
4008
danielk1977ac11ee62005-01-15 12:45:51 +00004009
4010
drhbd03cae2001-06-02 02:40:57 +00004011/*
drh4b70f112004-05-02 21:12:19 +00004012** Change the pParent pointer of all children of pPage to point back
4013** to pPage.
4014**
drhbd03cae2001-06-02 02:40:57 +00004015** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00004016** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00004017**
4018** This routine gets called after you memcpy() one page into
4019** another.
4020*/
danielk1977afcdd022004-10-31 16:25:42 +00004021static int reparentChildPages(MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00004022 int i;
danielk1977aef0bf62005-12-30 16:28:01 +00004023 BtShared *pBt = pPage->pBt;
danielk1977afcdd022004-10-31 16:25:42 +00004024 int rc = SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00004025
danielk1977afcdd022004-10-31 16:25:42 +00004026 if( pPage->leaf ) return SQLITE_OK;
danielk1977afcdd022004-10-31 16:25:42 +00004027
drhbd03cae2001-06-02 02:40:57 +00004028 for(i=0; i<pPage->nCell; i++){
danielk1977afcdd022004-10-31 16:25:42 +00004029 u8 *pCell = findCell(pPage, i);
4030 if( !pPage->leaf ){
4031 rc = reparentPage(pBt, get4byte(pCell), pPage, i);
4032 if( rc!=SQLITE_OK ) return rc;
4033 }
drhbd03cae2001-06-02 02:40:57 +00004034 }
danielk1977afcdd022004-10-31 16:25:42 +00004035 if( !pPage->leaf ){
4036 rc = reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]),
4037 pPage, i);
4038 pPage->idxShift = 0;
4039 }
4040 return rc;
drh14acc042001-06-10 19:56:58 +00004041}
4042
4043/*
4044** Remove the i-th cell from pPage. This routine effects pPage only.
4045** The cell content is not freed or deallocated. It is assumed that
4046** the cell content has been copied someplace else. This routine just
4047** removes the reference to the cell from pPage.
4048**
4049** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00004050*/
drh4b70f112004-05-02 21:12:19 +00004051static void dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00004052 int i; /* Loop counter */
4053 int pc; /* Offset to cell content of cell being deleted */
4054 u8 *data; /* pPage->aData */
4055 u8 *ptr; /* Used to move bytes around within data[] */
4056
drh8c42ca92001-06-22 19:15:00 +00004057 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00004058 assert( sz==cellSize(pPage, idx) );
drha34b6762004-05-07 13:30:42 +00004059 assert( sqlite3pager_iswriteable(pPage->aData) );
drhda200cc2004-05-09 11:51:38 +00004060 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00004061 ptr = &data[pPage->cellOffset + 2*idx];
4062 pc = get2byte(ptr);
4063 assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
drhde647132004-05-07 17:57:49 +00004064 freeSpace(pPage, pc, sz);
drh43605152004-05-29 21:46:49 +00004065 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
4066 ptr[0] = ptr[2];
4067 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00004068 }
4069 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00004070 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
4071 pPage->nFree += 2;
drh428ae8c2003-01-04 16:48:09 +00004072 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00004073}
4074
4075/*
4076** Insert a new cell on pPage at cell index "i". pCell points to the
4077** content of the cell.
4078**
4079** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00004080** will not fit, then make a copy of the cell content into pTemp if
4081** pTemp is not null. Regardless of pTemp, allocate a new entry
4082** in pPage->aOvfl[] and make it point to the cell content (either
4083** in pTemp or the original pCell) and also record its index.
4084** Allocating a new entry in pPage->aCell[] implies that
4085** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00004086**
4087** If nSkip is non-zero, then do not copy the first nSkip bytes of the
4088** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00004089** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00004090** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00004091*/
danielk1977e80463b2004-11-03 03:01:16 +00004092static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00004093 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00004094 int i, /* New cell becomes the i-th cell of the page */
4095 u8 *pCell, /* Content of the new cell */
4096 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00004097 u8 *pTemp, /* Temp storage space for pCell, if needed */
4098 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00004099){
drh43605152004-05-29 21:46:49 +00004100 int idx; /* Where to write new cell content in data[] */
4101 int j; /* Loop counter */
4102 int top; /* First byte of content for any cell in data[] */
4103 int end; /* First byte past the last cell pointer in data[] */
4104 int ins; /* Index in data[] where new cell pointer is inserted */
4105 int hdr; /* Offset into data[] of the page header */
4106 int cellOffset; /* Address of first cell pointer in data[] */
4107 u8 *data; /* The content of the whole page */
4108 u8 *ptr; /* Used for moving information around in data[] */
4109
4110 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
4111 assert( sz==cellSizePtr(pPage, pCell) );
drha34b6762004-05-07 13:30:42 +00004112 assert( sqlite3pager_iswriteable(pPage->aData) );
drh43605152004-05-29 21:46:49 +00004113 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00004114 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00004115 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004116 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00004117 }
drh43605152004-05-29 21:46:49 +00004118 j = pPage->nOverflow++;
4119 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
4120 pPage->aOvfl[j].pCell = pCell;
4121 pPage->aOvfl[j].idx = i;
4122 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00004123 }else{
drh43605152004-05-29 21:46:49 +00004124 data = pPage->aData;
4125 hdr = pPage->hdrOffset;
4126 top = get2byte(&data[hdr+5]);
4127 cellOffset = pPage->cellOffset;
4128 end = cellOffset + 2*pPage->nCell + 2;
4129 ins = cellOffset + 2*i;
4130 if( end > top - sz ){
danielk19776b456a22005-03-21 04:04:02 +00004131 int rc = defragmentPage(pPage);
4132 if( rc!=SQLITE_OK ) return rc;
drh43605152004-05-29 21:46:49 +00004133 top = get2byte(&data[hdr+5]);
4134 assert( end + sz <= top );
4135 }
4136 idx = allocateSpace(pPage, sz);
4137 assert( idx>0 );
4138 assert( end <= get2byte(&data[hdr+5]) );
4139 pPage->nCell++;
4140 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00004141 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004142 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
4143 ptr[0] = ptr[-2];
4144 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00004145 }
drh43605152004-05-29 21:46:49 +00004146 put2byte(&data[ins], idx);
4147 put2byte(&data[hdr+3], pPage->nCell);
4148 pPage->idxShift = 1;
drhda200cc2004-05-09 11:51:38 +00004149 pageIntegrity(pPage);
danielk1977a19df672004-11-03 11:37:07 +00004150#ifndef SQLITE_OMIT_AUTOVACUUM
4151 if( pPage->pBt->autoVacuum ){
4152 /* The cell may contain a pointer to an overflow page. If so, write
4153 ** the entry for the overflow page into the pointer map.
4154 */
4155 CellInfo info;
4156 parseCellPtr(pPage, pCell, &info);
4157 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
4158 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
4159 int rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
4160 if( rc!=SQLITE_OK ) return rc;
4161 }
4162 }
4163#endif
drh14acc042001-06-10 19:56:58 +00004164 }
danielk1977e80463b2004-11-03 03:01:16 +00004165
danielk1977e80463b2004-11-03 03:01:16 +00004166 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004167}
4168
4169/*
drhfa1a98a2004-05-14 19:08:17 +00004170** Add a list of cells to a page. The page should be initially empty.
4171** The cells are guaranteed to fit on the page.
4172*/
4173static void assemblePage(
4174 MemPage *pPage, /* The page to be assemblied */
4175 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00004176 u8 **apCell, /* Pointers to cell bodies */
drhfa1a98a2004-05-14 19:08:17 +00004177 int *aSize /* Sizes of the cells */
4178){
4179 int i; /* Loop counter */
4180 int totalSize; /* Total size of all cells */
4181 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00004182 int cellptr; /* Address of next cell pointer */
4183 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00004184 u8 *data; /* Data for the page */
4185
drh43605152004-05-29 21:46:49 +00004186 assert( pPage->nOverflow==0 );
drhfa1a98a2004-05-14 19:08:17 +00004187 totalSize = 0;
4188 for(i=0; i<nCell; i++){
4189 totalSize += aSize[i];
4190 }
drh43605152004-05-29 21:46:49 +00004191 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00004192 assert( pPage->nCell==0 );
drh43605152004-05-29 21:46:49 +00004193 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00004194 data = pPage->aData;
4195 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00004196 put2byte(&data[hdr+3], nCell);
drh09d0deb2005-08-02 17:13:09 +00004197 if( nCell ){
4198 cellbody = allocateSpace(pPage, totalSize);
4199 assert( cellbody>0 );
4200 assert( pPage->nFree >= 2*nCell );
4201 pPage->nFree -= 2*nCell;
4202 for(i=0; i<nCell; i++){
4203 put2byte(&data[cellptr], cellbody);
4204 memcpy(&data[cellbody], apCell[i], aSize[i]);
4205 cellptr += 2;
4206 cellbody += aSize[i];
4207 }
4208 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00004209 }
4210 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00004211}
4212
drh14acc042001-06-10 19:56:58 +00004213/*
drhc3b70572003-01-04 19:44:07 +00004214** The following parameters determine how many adjacent pages get involved
4215** in a balancing operation. NN is the number of neighbors on either side
4216** of the page that participate in the balancing operation. NB is the
4217** total number of pages that participate, including the target page and
4218** NN neighbors on either side.
4219**
4220** The minimum value of NN is 1 (of course). Increasing NN above 1
4221** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
4222** in exchange for a larger degradation in INSERT and UPDATE performance.
4223** The value of NN appears to give the best results overall.
4224*/
4225#define NN 1 /* Number of neighbors on either side of pPage */
4226#define NB (NN*2+1) /* Total pages involved in the balance */
4227
drh43605152004-05-29 21:46:49 +00004228/* Forward reference */
danielk1977ac245ec2005-01-14 13:50:11 +00004229static int balance(MemPage*, int);
4230
drh615ae552005-01-16 23:21:00 +00004231#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004232/*
4233** This version of balance() handles the common special case where
4234** a new entry is being inserted on the extreme right-end of the
4235** tree, in other words, when the new entry will become the largest
4236** entry in the tree.
4237**
4238** Instead of trying balance the 3 right-most leaf pages, just add
4239** a new page to the right-hand side and put the one new entry in
4240** that page. This leaves the right side of the tree somewhat
4241** unbalanced. But odds are that we will be inserting new entries
4242** at the end soon afterwards so the nearly empty page will quickly
4243** fill up. On average.
4244**
4245** pPage is the leaf page which is the right-most page in the tree.
4246** pParent is its parent. pPage must have a single overflow entry
4247** which is also the right-most entry on the page.
4248*/
danielk1977ac245ec2005-01-14 13:50:11 +00004249static int balance_quick(MemPage *pPage, MemPage *pParent){
4250 int rc;
4251 MemPage *pNew;
4252 Pgno pgnoNew;
4253 u8 *pCell;
4254 int szCell;
4255 CellInfo info;
danielk1977aef0bf62005-12-30 16:28:01 +00004256 BtShared *pBt = pPage->pBt;
danielk197779a40da2005-01-16 08:00:01 +00004257 int parentIdx = pParent->nCell; /* pParent new divider cell index */
4258 int parentSize; /* Size of new divider cell */
4259 u8 parentCell[64]; /* Space for the new divider cell */
danielk1977ac245ec2005-01-14 13:50:11 +00004260
4261 /* Allocate a new page. Insert the overflow cell from pPage
4262 ** into it. Then remove the overflow cell from pPage.
4263 */
danielk1977ac11ee62005-01-15 12:45:51 +00004264 rc = allocatePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977ac245ec2005-01-14 13:50:11 +00004265 if( rc!=SQLITE_OK ){
4266 return rc;
4267 }
4268 pCell = pPage->aOvfl[0].pCell;
4269 szCell = cellSizePtr(pPage, pCell);
4270 zeroPage(pNew, pPage->aData[0]);
4271 assemblePage(pNew, 1, &pCell, &szCell);
4272 pPage->nOverflow = 0;
4273
danielk197779a40da2005-01-16 08:00:01 +00004274 /* Set the parent of the newly allocated page to pParent. */
4275 pNew->pParent = pParent;
4276 sqlite3pager_ref(pParent->aData);
4277
danielk1977ac245ec2005-01-14 13:50:11 +00004278 /* pPage is currently the right-child of pParent. Change this
4279 ** so that the right-child is the new page allocated above and
danielk197779a40da2005-01-16 08:00:01 +00004280 ** pPage is the next-to-right child.
danielk1977ac245ec2005-01-14 13:50:11 +00004281 */
danielk1977ac11ee62005-01-15 12:45:51 +00004282 assert( pPage->nCell>0 );
danielk1977ac245ec2005-01-14 13:50:11 +00004283 parseCellPtr(pPage, findCell(pPage, pPage->nCell-1), &info);
4284 rc = fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, &parentSize);
4285 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00004286 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004287 }
4288 assert( parentSize<64 );
4289 rc = insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
4290 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00004291 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004292 }
4293 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
4294 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
4295
danielk197779a40da2005-01-16 08:00:01 +00004296#ifndef SQLITE_OMIT_AUTOVACUUM
4297 /* If this is an auto-vacuum database, update the pointer map
4298 ** with entries for the new page, and any pointer from the
4299 ** cell on the page to an overflow page.
4300 */
danielk1977ac11ee62005-01-15 12:45:51 +00004301 if( pBt->autoVacuum ){
4302 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
4303 if( rc!=SQLITE_OK ){
4304 return rc;
4305 }
danielk197779a40da2005-01-16 08:00:01 +00004306 rc = ptrmapPutOvfl(pNew, 0);
4307 if( rc!=SQLITE_OK ){
4308 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00004309 }
4310 }
danielk197779a40da2005-01-16 08:00:01 +00004311#endif
danielk1977ac11ee62005-01-15 12:45:51 +00004312
danielk197779a40da2005-01-16 08:00:01 +00004313 /* Release the reference to the new page and balance the parent page,
4314 ** in case the divider cell inserted caused it to become overfull.
4315 */
danielk1977ac245ec2005-01-14 13:50:11 +00004316 releasePage(pNew);
4317 return balance(pParent, 0);
4318}
drh615ae552005-01-16 23:21:00 +00004319#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00004320
drhc3b70572003-01-04 19:44:07 +00004321/*
danielk1977ac11ee62005-01-15 12:45:51 +00004322** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
4323** if the database supports auto-vacuum or not. Because it is used
4324** within an expression that is an argument to another macro
4325** (sqliteMallocRaw), it is not possible to use conditional compilation.
4326** So, this macro is defined instead.
4327*/
4328#ifndef SQLITE_OMIT_AUTOVACUUM
4329#define ISAUTOVACUUM (pBt->autoVacuum)
4330#else
4331#define ISAUTOVACUUM 0
4332#endif
4333
4334/*
drhab01f612004-05-22 02:55:23 +00004335** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00004336** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00004337** Usually NN siblings on either side of pPage is used in the balancing,
4338** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00004339** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00004340** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00004341** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00004342**
drh0c6cc4e2004-06-15 02:13:26 +00004343** The number of siblings of pPage might be increased or decreased by one or
4344** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00004345** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00004346** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00004347** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00004348** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00004349**
drh8b2f49b2001-06-08 00:21:52 +00004350** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00004351** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00004352** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00004353** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00004354**
drh8c42ca92001-06-22 19:15:00 +00004355** In the course of balancing the siblings of pPage, the parent of pPage
4356** might become overfull or underfull. If that happens, then this routine
4357** is called recursively on the parent.
4358**
drh5e00f6c2001-09-13 13:46:56 +00004359** If this routine fails for any reason, it might leave the database
4360** in a corrupted state. So if this routine fails, the database should
4361** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00004362*/
drh43605152004-05-29 21:46:49 +00004363static int balance_nonroot(MemPage *pPage){
drh8b2f49b2001-06-08 00:21:52 +00004364 MemPage *pParent; /* The parent of pPage */
danielk1977aef0bf62005-12-30 16:28:01 +00004365 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00004366 int nCell = 0; /* Number of cells in apCell[] */
4367 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
drh8b2f49b2001-06-08 00:21:52 +00004368 int nOld; /* Number of pages in apOld[] */
4369 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00004370 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00004371 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00004372 int idx; /* Index of pPage in pParent->aCell[] */
4373 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00004374 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00004375 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00004376 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00004377 int usableSpace; /* Bytes in pPage beyond the header */
4378 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00004379 int subtotal; /* Subtotal of bytes in cells on one page */
drhb6f41482004-05-14 01:58:11 +00004380 int iSpace = 0; /* First unused byte of aSpace[] */
drhc3b70572003-01-04 19:44:07 +00004381 MemPage *apOld[NB]; /* pPage and up to two siblings */
4382 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00004383 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00004384 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
4385 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drh4b70f112004-05-02 21:12:19 +00004386 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00004387 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
4388 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00004389 u8 **apCell = 0; /* All cells begin balanced */
drh2e38c322004-09-03 18:38:44 +00004390 int *szCell; /* Local size of all cells in apCell[] */
4391 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
4392 u8 *aSpace; /* Space to hold copies of dividers cells */
danielk19774e17d142005-01-16 09:06:33 +00004393#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00004394 u8 *aFrom = 0;
4395#endif
drh8b2f49b2001-06-08 00:21:52 +00004396
drh14acc042001-06-10 19:56:58 +00004397 /*
drh43605152004-05-29 21:46:49 +00004398 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00004399 */
drh3a4c1412004-05-09 20:40:11 +00004400 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004401 assert( sqlite3pager_iswriteable(pPage->aData) );
drh4b70f112004-05-02 21:12:19 +00004402 pBt = pPage->pBt;
drh14acc042001-06-10 19:56:58 +00004403 pParent = pPage->pParent;
drh43605152004-05-29 21:46:49 +00004404 sqlite3pager_write(pParent->aData);
4405 assert( pParent );
4406 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00004407
drh615ae552005-01-16 23:21:00 +00004408#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004409 /*
4410 ** A special case: If a new entry has just been inserted into a
4411 ** table (that is, a btree with integer keys and all data at the leaves)
drh09d0deb2005-08-02 17:13:09 +00004412 ** and the new entry is the right-most entry in the tree (it has the
drhf222e712005-01-14 22:55:49 +00004413 ** largest key) then use the special balance_quick() routine for
4414 ** balancing. balance_quick() is much faster and results in a tighter
4415 ** packing of data in the common case.
4416 */
danielk1977ac245ec2005-01-14 13:50:11 +00004417 if( pPage->leaf &&
4418 pPage->intKey &&
4419 pPage->leafData &&
4420 pPage->nOverflow==1 &&
4421 pPage->aOvfl[0].idx==pPage->nCell &&
danielk1977ac11ee62005-01-15 12:45:51 +00004422 pPage->pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00004423 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
4424 ){
danielk1977ac11ee62005-01-15 12:45:51 +00004425 /*
4426 ** TODO: Check the siblings to the left of pPage. It may be that
4427 ** they are not full and no new page is required.
4428 */
danielk1977ac245ec2005-01-14 13:50:11 +00004429 return balance_quick(pPage, pParent);
4430 }
4431#endif
4432
drh2e38c322004-09-03 18:38:44 +00004433 /*
drh4b70f112004-05-02 21:12:19 +00004434 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00004435 ** to pPage. The "idx" variable is the index of that cell. If pPage
4436 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00004437 */
drhbb49aba2003-01-04 18:53:27 +00004438 if( pParent->idxShift ){
drha34b6762004-05-07 13:30:42 +00004439 Pgno pgno;
drh4b70f112004-05-02 21:12:19 +00004440 pgno = pPage->pgno;
drha34b6762004-05-07 13:30:42 +00004441 assert( pgno==sqlite3pager_pagenumber(pPage->aData) );
drhbb49aba2003-01-04 18:53:27 +00004442 for(idx=0; idx<pParent->nCell; idx++){
drh43605152004-05-29 21:46:49 +00004443 if( get4byte(findCell(pParent, idx))==pgno ){
drhbb49aba2003-01-04 18:53:27 +00004444 break;
4445 }
drh8b2f49b2001-06-08 00:21:52 +00004446 }
drh4b70f112004-05-02 21:12:19 +00004447 assert( idx<pParent->nCell
drh43605152004-05-29 21:46:49 +00004448 || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
drhbb49aba2003-01-04 18:53:27 +00004449 }else{
4450 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00004451 }
drh8b2f49b2001-06-08 00:21:52 +00004452
4453 /*
drh14acc042001-06-10 19:56:58 +00004454 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00004455 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00004456 */
drh14acc042001-06-10 19:56:58 +00004457 nOld = nNew = 0;
drha34b6762004-05-07 13:30:42 +00004458 sqlite3pager_ref(pParent->aData);
drh14acc042001-06-10 19:56:58 +00004459
4460 /*
drh4b70f112004-05-02 21:12:19 +00004461 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00004462 ** the siblings. An attempt is made to find NN siblings on either
4463 ** side of pPage. More siblings are taken from one side, however, if
4464 ** pPage there are fewer than NN siblings on the other side. If pParent
4465 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00004466 */
drhc3b70572003-01-04 19:44:07 +00004467 nxDiv = idx - NN;
4468 if( nxDiv + NB > pParent->nCell ){
4469 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00004470 }
drhc3b70572003-01-04 19:44:07 +00004471 if( nxDiv<0 ){
4472 nxDiv = 0;
4473 }
drh8b2f49b2001-06-08 00:21:52 +00004474 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00004475 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00004476 if( k<pParent->nCell ){
drh43605152004-05-29 21:46:49 +00004477 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00004478 nDiv++;
drha34b6762004-05-07 13:30:42 +00004479 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00004480 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00004481 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00004482 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00004483 }else{
4484 break;
drh8b2f49b2001-06-08 00:21:52 +00004485 }
drhde647132004-05-07 17:57:49 +00004486 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00004487 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00004488 apOld[i]->idxParent = k;
drh91025292004-05-03 19:49:32 +00004489 apCopy[i] = 0;
4490 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00004491 nOld++;
danielk1977634f2982005-03-28 08:44:07 +00004492 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
drh8b2f49b2001-06-08 00:21:52 +00004493 }
4494
drh8d97f1f2005-05-05 18:14:13 +00004495 /* Make nMaxCells a multiple of 2 in order to preserve 8-byte
4496 ** alignment */
4497 nMaxCells = (nMaxCells + 1)&~1;
4498
drh8b2f49b2001-06-08 00:21:52 +00004499 /*
danielk1977634f2982005-03-28 08:44:07 +00004500 ** Allocate space for memory structures
4501 */
4502 apCell = sqliteMallocRaw(
4503 nMaxCells*sizeof(u8*) /* apCell */
4504 + nMaxCells*sizeof(int) /* szCell */
drhc96d8532005-05-03 12:30:33 +00004505 + ROUND8(sizeof(MemPage))*NB /* aCopy */
drh07d183d2005-05-01 22:52:42 +00004506 + pBt->pageSize*(5+NB) /* aSpace */
drhc96d8532005-05-03 12:30:33 +00004507 + (ISAUTOVACUUM ? nMaxCells : 0) /* aFrom */
danielk1977634f2982005-03-28 08:44:07 +00004508 );
4509 if( apCell==0 ){
4510 rc = SQLITE_NOMEM;
4511 goto balance_cleanup;
4512 }
4513 szCell = (int*)&apCell[nMaxCells];
4514 aCopy[0] = (u8*)&szCell[nMaxCells];
drhc96d8532005-05-03 12:30:33 +00004515 assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004516 for(i=1; i<NB; i++){
drhc96d8532005-05-03 12:30:33 +00004517 aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
4518 assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004519 }
drhc96d8532005-05-03 12:30:33 +00004520 aSpace = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
4521 assert( ((aSpace - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004522#ifndef SQLITE_OMIT_AUTOVACUUM
4523 if( pBt->autoVacuum ){
drh07d183d2005-05-01 22:52:42 +00004524 aFrom = &aSpace[5*pBt->pageSize];
danielk1977634f2982005-03-28 08:44:07 +00004525 }
4526#endif
4527
4528 /*
drh14acc042001-06-10 19:56:58 +00004529 ** Make copies of the content of pPage and its siblings into aOld[].
4530 ** The rest of this function will use data from the copies rather
4531 ** that the original pages since the original pages will be in the
4532 ** process of being overwritten.
4533 */
4534 for(i=0; i<nOld; i++){
drh07d183d2005-05-01 22:52:42 +00004535 MemPage *p = apCopy[i] = (MemPage*)&aCopy[i][pBt->pageSize];
drh07d183d2005-05-01 22:52:42 +00004536 p->aData = &((u8*)p)[-pBt->pageSize];
4537 memcpy(p->aData, apOld[i]->aData, pBt->pageSize + sizeof(MemPage));
4538 /* The memcpy() above changes the value of p->aData so we have to
4539 ** set it again. */
drh07d183d2005-05-01 22:52:42 +00004540 p->aData = &((u8*)p)[-pBt->pageSize];
drh14acc042001-06-10 19:56:58 +00004541 }
4542
4543 /*
4544 ** Load pointers to all cells on sibling pages and the divider cells
4545 ** into the local apCell[] array. Make copies of the divider cells
drhb6f41482004-05-14 01:58:11 +00004546 ** into space obtained form aSpace[] and remove the the divider Cells
4547 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00004548 **
4549 ** If the siblings are on leaf pages, then the child pointers of the
4550 ** divider cells are stripped from the cells before they are copied
drh96f5b762004-05-16 16:24:36 +00004551 ** into aSpace[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00004552 ** child pointers. If siblings are not leaves, then all cell in
4553 ** apCell[] include child pointers. Either way, all cells in apCell[]
4554 ** are alike.
drh96f5b762004-05-16 16:24:36 +00004555 **
4556 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
4557 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00004558 */
4559 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00004560 leafCorrection = pPage->leaf*4;
drh8b18dd42004-05-12 19:18:15 +00004561 leafData = pPage->leafData && pPage->leaf;
drh8b2f49b2001-06-08 00:21:52 +00004562 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00004563 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00004564 int limit = pOld->nCell+pOld->nOverflow;
4565 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00004566 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00004567 apCell[nCell] = findOverflowCell(pOld, j);
4568 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk1977ac11ee62005-01-15 12:45:51 +00004569#ifndef SQLITE_OMIT_AUTOVACUUM
4570 if( pBt->autoVacuum ){
4571 int a;
4572 aFrom[nCell] = i;
4573 for(a=0; a<pOld->nOverflow; a++){
4574 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
4575 aFrom[nCell] = 0xFF;
4576 break;
4577 }
4578 }
4579 }
4580#endif
drh14acc042001-06-10 19:56:58 +00004581 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00004582 }
4583 if( i<nOld-1 ){
drh43605152004-05-29 21:46:49 +00004584 int sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00004585 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00004586 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
4587 ** are duplicates of keys on the child pages. We need to remove
4588 ** the divider cells from pParent, but the dividers cells are not
4589 ** added to apCell[] because they are duplicates of child cells.
4590 */
drh8b18dd42004-05-12 19:18:15 +00004591 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00004592 }else{
drhb6f41482004-05-14 01:58:11 +00004593 u8 *pTemp;
danielk1977634f2982005-03-28 08:44:07 +00004594 assert( nCell<nMaxCells );
drhb6f41482004-05-14 01:58:11 +00004595 szCell[nCell] = sz;
4596 pTemp = &aSpace[iSpace];
4597 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004598 assert( iSpace<=pBt->pageSize*5 );
drhb6f41482004-05-14 01:58:11 +00004599 memcpy(pTemp, apDiv[i], sz);
4600 apCell[nCell] = pTemp+leafCorrection;
danielk1977ac11ee62005-01-15 12:45:51 +00004601#ifndef SQLITE_OMIT_AUTOVACUUM
4602 if( pBt->autoVacuum ){
4603 aFrom[nCell] = 0xFF;
4604 }
4605#endif
drhb6f41482004-05-14 01:58:11 +00004606 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00004607 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00004608 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00004609 if( !pOld->leaf ){
4610 assert( leafCorrection==0 );
4611 /* The right pointer of the child page pOld becomes the left
4612 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00004613 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00004614 }else{
4615 assert( leafCorrection==4 );
4616 }
4617 nCell++;
drh4b70f112004-05-02 21:12:19 +00004618 }
drh8b2f49b2001-06-08 00:21:52 +00004619 }
4620 }
4621
4622 /*
drh6019e162001-07-02 17:51:45 +00004623 ** Figure out the number of pages needed to hold all nCell cells.
4624 ** Store this number in "k". Also compute szNew[] which is the total
4625 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00004626 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00004627 ** cntNew[k] should equal nCell.
4628 **
drh96f5b762004-05-16 16:24:36 +00004629 ** Values computed by this block:
4630 **
4631 ** k: The total number of sibling pages
4632 ** szNew[i]: Spaced used on the i-th sibling page.
4633 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
4634 ** the right of the i-th sibling page.
4635 ** usableSpace: Number of bytes of space available on each sibling.
4636 **
drh8b2f49b2001-06-08 00:21:52 +00004637 */
drh43605152004-05-29 21:46:49 +00004638 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00004639 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00004640 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00004641 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00004642 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00004643 szNew[k] = subtotal - szCell[i];
4644 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00004645 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00004646 subtotal = 0;
4647 k++;
4648 }
4649 }
4650 szNew[k] = subtotal;
4651 cntNew[k] = nCell;
4652 k++;
drh96f5b762004-05-16 16:24:36 +00004653
4654 /*
4655 ** The packing computed by the previous block is biased toward the siblings
4656 ** on the left side. The left siblings are always nearly full, while the
4657 ** right-most sibling might be nearly empty. This block of code attempts
4658 ** to adjust the packing of siblings to get a better balance.
4659 **
4660 ** This adjustment is more than an optimization. The packing above might
4661 ** be so out of balance as to be illegal. For example, the right-most
4662 ** sibling might be completely empty. This adjustment is not optional.
4663 */
drh6019e162001-07-02 17:51:45 +00004664 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00004665 int szRight = szNew[i]; /* Size of sibling on the right */
4666 int szLeft = szNew[i-1]; /* Size of sibling on the left */
4667 int r; /* Index of right-most cell in left sibling */
4668 int d; /* Index of first cell to the left of right sibling */
4669
4670 r = cntNew[i-1] - 1;
4671 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00004672 assert( d<nMaxCells );
4673 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00004674 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
4675 szRight += szCell[d] + 2;
4676 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00004677 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00004678 r = cntNew[i-1] - 1;
4679 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00004680 }
drh96f5b762004-05-16 16:24:36 +00004681 szNew[i] = szRight;
4682 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00004683 }
drh09d0deb2005-08-02 17:13:09 +00004684
4685 /* Either we found one or more cells (cntnew[0])>0) or we are the
4686 ** a virtual root page. A virtual root page is when the real root
4687 ** page is page 1 and we are the only child of that page.
4688 */
4689 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00004690
4691 /*
drh6b308672002-07-08 02:16:37 +00004692 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00004693 */
drh4b70f112004-05-02 21:12:19 +00004694 assert( pPage->pgno>1 );
4695 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00004696 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00004697 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00004698 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00004699 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00004700 pgnoNew[i] = pgnoOld[i];
4701 apOld[i] = 0;
danielk197728129562005-01-11 10:25:06 +00004702 rc = sqlite3pager_write(pNew->aData);
4703 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00004704 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004705 rc = allocatePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00004706 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00004707 apNew[i] = pNew;
drh6b308672002-07-08 02:16:37 +00004708 }
drh14acc042001-06-10 19:56:58 +00004709 nNew++;
drhda200cc2004-05-09 11:51:38 +00004710 zeroPage(pNew, pageFlags);
drh8b2f49b2001-06-08 00:21:52 +00004711 }
4712
danielk1977299b1872004-11-22 10:02:10 +00004713 /* Free any old pages that were not reused as new pages.
4714 */
4715 while( i<nOld ){
4716 rc = freePage(apOld[i]);
4717 if( rc ) goto balance_cleanup;
4718 releasePage(apOld[i]);
4719 apOld[i] = 0;
4720 i++;
4721 }
4722
drh8b2f49b2001-06-08 00:21:52 +00004723 /*
drhf9ffac92002-03-02 19:00:31 +00004724 ** Put the new pages in accending order. This helps to
4725 ** keep entries in the disk file in order so that a scan
4726 ** of the table is a linear scan through the file. That
4727 ** in turn helps the operating system to deliver pages
4728 ** from the disk more rapidly.
4729 **
4730 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00004731 ** n is never more than NB (a small constant), that should
4732 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00004733 **
drhc3b70572003-01-04 19:44:07 +00004734 ** When NB==3, this one optimization makes the database
4735 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00004736 */
4737 for(i=0; i<k-1; i++){
4738 int minV = pgnoNew[i];
4739 int minI = i;
4740 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00004741 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00004742 minI = j;
4743 minV = pgnoNew[j];
4744 }
4745 }
4746 if( minI>i ){
4747 int t;
4748 MemPage *pT;
4749 t = pgnoNew[i];
4750 pT = apNew[i];
4751 pgnoNew[i] = pgnoNew[minI];
4752 apNew[i] = apNew[minI];
4753 pgnoNew[minI] = t;
4754 apNew[minI] = pT;
4755 }
4756 }
drha2fce642004-06-05 00:01:44 +00004757 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00004758 pgnoOld[0],
4759 nOld>=2 ? pgnoOld[1] : 0,
4760 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00004761 pgnoNew[0], szNew[0],
4762 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
4763 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00004764 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
4765 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00004766
drhf9ffac92002-03-02 19:00:31 +00004767 /*
drh14acc042001-06-10 19:56:58 +00004768 ** Evenly distribute the data in apCell[] across the new pages.
4769 ** Insert divider cells into pParent as necessary.
4770 */
4771 j = 0;
4772 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00004773 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00004774 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00004775 assert( j<nMaxCells );
drh4b70f112004-05-02 21:12:19 +00004776 assert( pNew->pgno==pgnoNew[i] );
drhfa1a98a2004-05-14 19:08:17 +00004777 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00004778 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00004779 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00004780
4781#ifndef SQLITE_OMIT_AUTOVACUUM
4782 /* If this is an auto-vacuum database, update the pointer map entries
4783 ** that point to the siblings that were rearranged. These can be: left
4784 ** children of cells, the right-child of the page, or overflow pages
4785 ** pointed to by cells.
4786 */
4787 if( pBt->autoVacuum ){
4788 for(k=j; k<cntNew[i]; k++){
danielk1977634f2982005-03-28 08:44:07 +00004789 assert( k<nMaxCells );
danielk1977ac11ee62005-01-15 12:45:51 +00004790 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
danielk197779a40da2005-01-16 08:00:01 +00004791 rc = ptrmapPutOvfl(pNew, k-j);
4792 if( rc!=SQLITE_OK ){
4793 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00004794 }
4795 }
4796 }
4797 }
4798#endif
4799
4800 j = cntNew[i];
4801
4802 /* If the sibling page assembled above was not the right-most sibling,
4803 ** insert a divider cell into the parent page.
4804 */
drh14acc042001-06-10 19:56:58 +00004805 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00004806 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00004807 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00004808 int sz;
danielk1977634f2982005-03-28 08:44:07 +00004809
4810 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00004811 pCell = apCell[j];
4812 sz = szCell[j] + leafCorrection;
drh4b70f112004-05-02 21:12:19 +00004813 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00004814 memcpy(&pNew->aData[8], pCell, 4);
drh24cd67e2004-05-10 16:18:47 +00004815 pTemp = 0;
drh8b18dd42004-05-12 19:18:15 +00004816 }else if( leafData ){
danielk1977ac11ee62005-01-15 12:45:51 +00004817 /* If the tree is a leaf-data tree, and the siblings are leaves,
4818 ** then there is no divider cell in apCell[]. Instead, the divider
4819 ** cell consists of the integer key for the right-most cell of
4820 ** the sibling-page assembled above only.
4821 */
drh6f11bef2004-05-13 01:12:56 +00004822 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00004823 j--;
drh43605152004-05-29 21:46:49 +00004824 parseCellPtr(pNew, apCell[j], &info);
drhb6f41482004-05-14 01:58:11 +00004825 pCell = &aSpace[iSpace];
drh6f11bef2004-05-13 01:12:56 +00004826 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, &sz);
drhb6f41482004-05-14 01:58:11 +00004827 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004828 assert( iSpace<=pBt->pageSize*5 );
drh8b18dd42004-05-12 19:18:15 +00004829 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00004830 }else{
4831 pCell -= 4;
drhb6f41482004-05-14 01:58:11 +00004832 pTemp = &aSpace[iSpace];
4833 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004834 assert( iSpace<=pBt->pageSize*5 );
drh4b70f112004-05-02 21:12:19 +00004835 }
danielk1977a3ad5e72005-01-07 08:56:44 +00004836 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00004837 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh43605152004-05-29 21:46:49 +00004838 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +00004839#ifndef SQLITE_OMIT_AUTOVACUUM
4840 /* If this is an auto-vacuum database, and not a leaf-data tree,
4841 ** then update the pointer map with an entry for the overflow page
4842 ** that the cell just inserted points to (if any).
4843 */
4844 if( pBt->autoVacuum && !leafData ){
danielk197779a40da2005-01-16 08:00:01 +00004845 rc = ptrmapPutOvfl(pParent, nxDiv);
4846 if( rc!=SQLITE_OK ){
4847 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00004848 }
4849 }
4850#endif
drh14acc042001-06-10 19:56:58 +00004851 j++;
4852 nxDiv++;
4853 }
4854 }
drh6019e162001-07-02 17:51:45 +00004855 assert( j==nCell );
drh4b70f112004-05-02 21:12:19 +00004856 if( (pageFlags & PTF_LEAF)==0 ){
drh43605152004-05-29 21:46:49 +00004857 memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
drh14acc042001-06-10 19:56:58 +00004858 }
drh43605152004-05-29 21:46:49 +00004859 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00004860 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00004861 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00004862 }else{
4863 /* Right-most sibling is the left child of the first entry in pParent
4864 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00004865 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00004866 }
4867
4868 /*
4869 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00004870 */
4871 for(i=0; i<nNew; i++){
danielk1977afcdd022004-10-31 16:25:42 +00004872 rc = reparentChildPages(apNew[i]);
4873 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004874 }
danielk1977afcdd022004-10-31 16:25:42 +00004875 rc = reparentChildPages(pParent);
4876 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004877
4878 /*
drh3a4c1412004-05-09 20:40:11 +00004879 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00004880 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00004881 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00004882 */
drhda200cc2004-05-09 11:51:38 +00004883 assert( pParent->isInit );
drh3a4c1412004-05-09 20:40:11 +00004884 /* assert( pPage->isInit ); // No! pPage might have been added to freelist */
4885 /* pageIntegrity(pPage); // No! pPage might have been added to freelist */
danielk1977ac245ec2005-01-14 13:50:11 +00004886 rc = balance(pParent, 0);
drhda200cc2004-05-09 11:51:38 +00004887
drh8b2f49b2001-06-08 00:21:52 +00004888 /*
drh14acc042001-06-10 19:56:58 +00004889 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00004890 */
drh14acc042001-06-10 19:56:58 +00004891balance_cleanup:
drh2e38c322004-09-03 18:38:44 +00004892 sqliteFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00004893 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00004894 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00004895 }
drh14acc042001-06-10 19:56:58 +00004896 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00004897 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00004898 }
drh91025292004-05-03 19:49:32 +00004899 releasePage(pParent);
drh3a4c1412004-05-09 20:40:11 +00004900 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
4901 pPage->pgno, nOld, nNew, nCell));
drh8b2f49b2001-06-08 00:21:52 +00004902 return rc;
4903}
4904
4905/*
drh43605152004-05-29 21:46:49 +00004906** This routine is called for the root page of a btree when the root
4907** page contains no cells. This is an opportunity to make the tree
4908** shallower by one level.
4909*/
4910static int balance_shallower(MemPage *pPage){
4911 MemPage *pChild; /* The only child page of pPage */
4912 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00004913 int rc = SQLITE_OK; /* Return code from subprocedures */
danielk1977aef0bf62005-12-30 16:28:01 +00004914 BtShared *pBt; /* The main BTree structure */
drh2e38c322004-09-03 18:38:44 +00004915 int mxCellPerPage; /* Maximum number of cells per page */
4916 u8 **apCell; /* All cells from pages being balanced */
4917 int *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00004918
4919 assert( pPage->pParent==0 );
4920 assert( pPage->nCell==0 );
drh2e38c322004-09-03 18:38:44 +00004921 pBt = pPage->pBt;
4922 mxCellPerPage = MX_CELL(pBt);
4923 apCell = sqliteMallocRaw( mxCellPerPage*(sizeof(u8*)+sizeof(int)) );
4924 if( apCell==0 ) return SQLITE_NOMEM;
4925 szCell = (int*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00004926 if( pPage->leaf ){
4927 /* The table is completely empty */
4928 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
4929 }else{
4930 /* The root page is empty but has one child. Transfer the
4931 ** information from that one child into the root page if it
4932 ** will fit. This reduces the depth of the tree by one.
4933 **
4934 ** If the root page is page 1, it has less space available than
4935 ** its child (due to the 100 byte header that occurs at the beginning
4936 ** of the database fle), so it might not be able to hold all of the
4937 ** information currently contained in the child. If this is the
4938 ** case, then do not do the transfer. Leave page 1 empty except
4939 ** for the right-pointer to the child page. The child page becomes
4940 ** the virtual root of the tree.
4941 */
4942 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
4943 assert( pgnoChild>0 );
4944 assert( pgnoChild<=sqlite3pager_pagecount(pPage->pBt->pPager) );
4945 rc = getPage(pPage->pBt, pgnoChild, &pChild);
drh2e38c322004-09-03 18:38:44 +00004946 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004947 if( pPage->pgno==1 ){
4948 rc = initPage(pChild, pPage);
drh2e38c322004-09-03 18:38:44 +00004949 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004950 assert( pChild->nOverflow==0 );
4951 if( pChild->nFree>=100 ){
4952 /* The child information will fit on the root page, so do the
4953 ** copy */
4954 int i;
4955 zeroPage(pPage, pChild->aData[0]);
4956 for(i=0; i<pChild->nCell; i++){
4957 apCell[i] = findCell(pChild,i);
4958 szCell[i] = cellSizePtr(pChild, apCell[i]);
4959 }
4960 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00004961 /* Copy the right-pointer of the child to the parent. */
4962 put4byte(&pPage->aData[pPage->hdrOffset+8],
4963 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh43605152004-05-29 21:46:49 +00004964 freePage(pChild);
4965 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
4966 }else{
4967 /* The child has more information that will fit on the root.
4968 ** The tree is already balanced. Do nothing. */
4969 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
4970 }
4971 }else{
4972 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
4973 pPage->isInit = 0;
4974 pPage->pParent = 0;
4975 rc = initPage(pPage, 0);
4976 assert( rc==SQLITE_OK );
4977 freePage(pChild);
4978 TRACE(("BALANCE: transfer child %d into root %d\n",
4979 pChild->pgno, pPage->pgno));
4980 }
danielk1977afcdd022004-10-31 16:25:42 +00004981 rc = reparentChildPages(pPage);
danielk1977ac11ee62005-01-15 12:45:51 +00004982 assert( pPage->nOverflow==0 );
4983#ifndef SQLITE_OMIT_AUTOVACUUM
4984 if( pBt->autoVacuum ){
danielk1977aac0a382005-01-16 11:07:06 +00004985 int i;
danielk1977ac11ee62005-01-15 12:45:51 +00004986 for(i=0; i<pPage->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00004987 rc = ptrmapPutOvfl(pPage, i);
4988 if( rc!=SQLITE_OK ){
4989 goto end_shallow_balance;
danielk1977ac11ee62005-01-15 12:45:51 +00004990 }
4991 }
4992 }
4993#endif
danielk1977afcdd022004-10-31 16:25:42 +00004994 if( rc!=SQLITE_OK ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004995 releasePage(pChild);
4996 }
drh2e38c322004-09-03 18:38:44 +00004997end_shallow_balance:
4998 sqliteFree(apCell);
4999 return rc;
drh43605152004-05-29 21:46:49 +00005000}
5001
5002
5003/*
5004** The root page is overfull
5005**
5006** When this happens, Create a new child page and copy the
5007** contents of the root into the child. Then make the root
5008** page an empty page with rightChild pointing to the new
5009** child. Finally, call balance_internal() on the new child
5010** to cause it to split.
5011*/
5012static int balance_deeper(MemPage *pPage){
5013 int rc; /* Return value from subprocedures */
5014 MemPage *pChild; /* Pointer to a new child page */
5015 Pgno pgnoChild; /* Page number of the new child page */
danielk1977aef0bf62005-12-30 16:28:01 +00005016 BtShared *pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00005017 int usableSize; /* Total usable size of a page */
5018 u8 *data; /* Content of the parent page */
5019 u8 *cdata; /* Content of the child page */
5020 int hdr; /* Offset to page header in parent */
5021 int brk; /* Offset to content of first cell in parent */
5022
5023 assert( pPage->pParent==0 );
5024 assert( pPage->nOverflow>0 );
5025 pBt = pPage->pBt;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005026 rc = allocatePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00005027 if( rc ) return rc;
5028 assert( sqlite3pager_iswriteable(pChild->aData) );
5029 usableSize = pBt->usableSize;
5030 data = pPage->aData;
5031 hdr = pPage->hdrOffset;
5032 brk = get2byte(&data[hdr+5]);
5033 cdata = pChild->aData;
5034 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
5035 memcpy(&cdata[brk], &data[brk], usableSize-brk);
danielk1977c7dc7532004-11-17 10:22:03 +00005036 assert( pChild->isInit==0 );
drh43605152004-05-29 21:46:49 +00005037 rc = initPage(pChild, pPage);
danielk19776b456a22005-03-21 04:04:02 +00005038 if( rc ) goto balancedeeper_out;
drh43605152004-05-29 21:46:49 +00005039 memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
5040 pChild->nOverflow = pPage->nOverflow;
5041 if( pChild->nOverflow ){
5042 pChild->nFree = 0;
5043 }
5044 assert( pChild->nCell==pPage->nCell );
5045 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
5046 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
5047 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
danielk19774e17d142005-01-16 09:06:33 +00005048#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00005049 if( pBt->autoVacuum ){
5050 int i;
5051 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
danielk19776b456a22005-03-21 04:04:02 +00005052 if( rc ) goto balancedeeper_out;
danielk1977ac11ee62005-01-15 12:45:51 +00005053 for(i=0; i<pChild->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00005054 rc = ptrmapPutOvfl(pChild, i);
5055 if( rc!=SQLITE_OK ){
5056 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00005057 }
5058 }
5059 }
danielk19774e17d142005-01-16 09:06:33 +00005060#endif
drh43605152004-05-29 21:46:49 +00005061 rc = balance_nonroot(pChild);
danielk19776b456a22005-03-21 04:04:02 +00005062
5063balancedeeper_out:
drh43605152004-05-29 21:46:49 +00005064 releasePage(pChild);
5065 return rc;
5066}
5067
5068/*
5069** Decide if the page pPage needs to be balanced. If balancing is
5070** required, call the appropriate balancing routine.
5071*/
danielk1977ac245ec2005-01-14 13:50:11 +00005072static int balance(MemPage *pPage, int insert){
drh43605152004-05-29 21:46:49 +00005073 int rc = SQLITE_OK;
5074 if( pPage->pParent==0 ){
5075 if( pPage->nOverflow>0 ){
5076 rc = balance_deeper(pPage);
5077 }
danielk1977687566d2004-11-02 12:56:41 +00005078 if( rc==SQLITE_OK && pPage->nCell==0 ){
drh43605152004-05-29 21:46:49 +00005079 rc = balance_shallower(pPage);
5080 }
5081 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00005082 if( pPage->nOverflow>0 ||
5083 (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
drh43605152004-05-29 21:46:49 +00005084 rc = balance_nonroot(pPage);
5085 }
5086 }
5087 return rc;
5088}
5089
5090/*
drh8dcd7ca2004-08-08 19:43:29 +00005091** This routine checks all cursors that point to table pgnoRoot.
5092** If any of those cursors other than pExclude were opened with
drhf74b8d92002-09-01 23:20:45 +00005093** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
drh8dcd7ca2004-08-08 19:43:29 +00005094** cursors that point to pgnoRoot were opened with wrFlag==1
drhf74b8d92002-09-01 23:20:45 +00005095** then this routine returns SQLITE_OK.
danielk1977299b1872004-11-22 10:02:10 +00005096**
5097** In addition to checking for read-locks (where a read-lock
5098** means a cursor opened with wrFlag==0) this routine also moves
5099** all cursors other than pExclude so that they are pointing to the
5100** first Cell on root page. This is necessary because an insert
5101** or delete might change the number of cells on a page or delete
5102** a page entirely and we do not want to leave any cursors
5103** pointing to non-existant pages or cells.
drhf74b8d92002-09-01 23:20:45 +00005104*/
danielk1977aef0bf62005-12-30 16:28:01 +00005105static int checkReadLocks(BtShared *pBt, Pgno pgnoRoot, BtCursor *pExclude){
danielk1977299b1872004-11-22 10:02:10 +00005106 BtCursor *p;
5107 for(p=pBt->pCursor; p; p=p->pNext){
danielk1977da184232006-01-05 11:34:32 +00005108 u32 flags = (p->pBtree->pSqlite ? p->pBtree->pSqlite->flags : 0);
danielk1977299b1872004-11-22 10:02:10 +00005109 if( p->pgnoRoot!=pgnoRoot || p==pExclude ) continue;
danielk1977da184232006-01-05 11:34:32 +00005110 if( p->wrFlag==0 && flags&SQLITE_ReadUncommitted ) continue;
danielk1977299b1872004-11-22 10:02:10 +00005111 if( p->wrFlag==0 ) return SQLITE_LOCKED;
5112 if( p->pPage->pgno!=p->pgnoRoot ){
5113 moveToRoot(p);
5114 }
5115 }
drhf74b8d92002-09-01 23:20:45 +00005116 return SQLITE_OK;
5117}
5118
5119/*
drh3b7511c2001-05-26 13:15:44 +00005120** Insert a new record into the BTree. The key is given by (pKey,nKey)
5121** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00005122** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00005123** is left pointing at a random location.
5124**
5125** For an INTKEY table, only the nKey value of the key is used. pKey is
5126** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00005127*/
drh3aac2dd2004-04-26 14:10:20 +00005128int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00005129 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00005130 const void *pKey, i64 nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00005131 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00005132){
drh3b7511c2001-05-26 13:15:44 +00005133 int rc;
5134 int loc;
drh14acc042001-06-10 19:56:58 +00005135 int szNew;
drh3b7511c2001-05-26 13:15:44 +00005136 MemPage *pPage;
danielk1977aef0bf62005-12-30 16:28:01 +00005137 BtShared *pBt = pCur->pBtree->pBt;
drha34b6762004-05-07 13:30:42 +00005138 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00005139 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00005140
danielk1977aef0bf62005-12-30 16:28:01 +00005141 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005142 /* Must start a transaction before doing an insert */
5143 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005144 }
drhf74b8d92002-09-01 23:20:45 +00005145 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00005146 if( !pCur->wrFlag ){
5147 return SQLITE_PERM; /* Cursor not open for writing */
5148 }
drh8dcd7ca2004-08-08 19:43:29 +00005149 if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00005150 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5151 }
danielk1977da184232006-01-05 11:34:32 +00005152
5153 /* Save the positions of any other cursors open on this table */
danielk19772e94d4d2006-01-09 05:36:27 +00005154 if(
5155 SQLITE_OK!=(rc = restoreCursorPosition(pCur, 0)) ||
5156 SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
5157 SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, &loc))
5158 ){
danielk1977da184232006-01-05 11:34:32 +00005159 return rc;
5160 }
5161
drh14acc042001-06-10 19:56:58 +00005162 pPage = pCur->pPage;
drh4a1c3802004-05-12 15:15:47 +00005163 assert( pPage->intKey || nKey>=0 );
drh8b18dd42004-05-12 19:18:15 +00005164 assert( pPage->leaf || !pPage->leafData );
drh3a4c1412004-05-09 20:40:11 +00005165 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
5166 pCur->pgnoRoot, nKey, nData, pPage->pgno,
5167 loc==0 ? "overwrite" : "new entry"));
drh7aa128d2002-06-21 13:09:16 +00005168 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00005169 rc = sqlite3pager_write(pPage->aData);
drhbd03cae2001-06-02 02:40:57 +00005170 if( rc ) return rc;
drh2e38c322004-09-03 18:38:44 +00005171 newCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
5172 if( newCell==0 ) return SQLITE_NOMEM;
drha34b6762004-05-07 13:30:42 +00005173 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, &szNew);
drh2e38c322004-09-03 18:38:44 +00005174 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00005175 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00005176 assert( szNew<=MX_CELL_SIZE(pBt) );
danielk1977da184232006-01-05 11:34:32 +00005177 if( loc==0 && CURSOR_VALID==pCur->eState ){
drha34b6762004-05-07 13:30:42 +00005178 int szOld;
5179 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00005180 oldCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005181 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005182 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00005183 }
drh43605152004-05-29 21:46:49 +00005184 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00005185 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00005186 if( rc ) goto end_insert;
drh4b70f112004-05-02 21:12:19 +00005187 dropCell(pPage, pCur->idx, szOld);
drh7c717f72001-06-24 20:39:41 +00005188 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00005189 assert( pPage->leaf );
drh14acc042001-06-10 19:56:58 +00005190 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00005191 pCur->info.nSize = 0;
drh14acc042001-06-10 19:56:58 +00005192 }else{
drh4b70f112004-05-02 21:12:19 +00005193 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00005194 }
danielk1977a3ad5e72005-01-07 08:56:44 +00005195 rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
danielk1977e80463b2004-11-03 03:01:16 +00005196 if( rc!=SQLITE_OK ) goto end_insert;
danielk1977ac245ec2005-01-14 13:50:11 +00005197 rc = balance(pPage, 1);
drh23e11ca2004-05-04 17:27:28 +00005198 /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
drh3fc190c2001-09-14 03:24:23 +00005199 /* fflush(stdout); */
danielk1977299b1872004-11-22 10:02:10 +00005200 if( rc==SQLITE_OK ){
5201 moveToRoot(pCur);
5202 }
drh2e38c322004-09-03 18:38:44 +00005203end_insert:
5204 sqliteFree(newCell);
drh5e2f8b92001-05-28 00:41:15 +00005205 return rc;
5206}
5207
5208/*
drh4b70f112004-05-02 21:12:19 +00005209** Delete the entry that the cursor is pointing to. The cursor
5210** is left pointing at a random location.
drh3b7511c2001-05-26 13:15:44 +00005211*/
drh3aac2dd2004-04-26 14:10:20 +00005212int sqlite3BtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00005213 MemPage *pPage = pCur->pPage;
drh4b70f112004-05-02 21:12:19 +00005214 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00005215 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00005216 Pgno pgnoChild = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00005217 BtShared *pBt = pCur->pBtree->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005218
drh7aa128d2002-06-21 13:09:16 +00005219 assert( pPage->isInit );
danielk1977aef0bf62005-12-30 16:28:01 +00005220 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005221 /* Must start a transaction before doing a delete */
5222 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005223 }
drhf74b8d92002-09-01 23:20:45 +00005224 assert( !pBt->readOnly );
drhbd03cae2001-06-02 02:40:57 +00005225 if( pCur->idx >= pPage->nCell ){
5226 return SQLITE_ERROR; /* The cursor is not pointing to anything */
5227 }
drhecdc7532001-09-23 02:35:53 +00005228 if( !pCur->wrFlag ){
5229 return SQLITE_PERM; /* Did not open this cursor for writing */
5230 }
drh8dcd7ca2004-08-08 19:43:29 +00005231 if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00005232 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5233 }
danielk1977da184232006-01-05 11:34:32 +00005234
5235 /* Restore the current cursor position (a no-op if the cursor is not in
5236 ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
5237 ** open on the same table. Then call sqlite3pager_write() on the page
5238 ** that the entry will be deleted from.
5239 */
5240 if(
5241 (rc = restoreCursorPosition(pCur, 1)) ||
5242 (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
5243 (rc = sqlite3pager_write(pPage->aData))
5244 ){
5245 return rc;
5246 }
danielk1977e6efa742004-11-10 11:55:10 +00005247
5248 /* Locate the cell within it's page and leave pCell pointing to the
5249 ** data. The clearCell() call frees any overflow pages associated with the
5250 ** cell. The cell itself is still intact.
5251 */
danielk1977299b1872004-11-22 10:02:10 +00005252 pCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005253 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005254 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005255 }
danielk197728129562005-01-11 10:25:06 +00005256 rc = clearCell(pPage, pCell);
5257 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00005258
drh4b70f112004-05-02 21:12:19 +00005259 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00005260 /*
drh5e00f6c2001-09-13 13:46:56 +00005261 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00005262 ** do something we will leave a hole on an internal page.
5263 ** We have to fill the hole by moving in a cell from a leaf. The
5264 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00005265 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00005266 */
drh14acc042001-06-10 19:56:58 +00005267 BtCursor leafCur;
drh4b70f112004-05-02 21:12:19 +00005268 unsigned char *pNext;
drh14acc042001-06-10 19:56:58 +00005269 int szNext;
danielk1977299b1872004-11-22 10:02:10 +00005270 int notUsed;
danielk19776b456a22005-03-21 04:04:02 +00005271 unsigned char *tempCell = 0;
drh8b18dd42004-05-12 19:18:15 +00005272 assert( !pPage->leafData );
drh14acc042001-06-10 19:56:58 +00005273 getTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00005274 rc = sqlite3BtreeNext(&leafCur, &notUsed);
drh14acc042001-06-10 19:56:58 +00005275 if( rc!=SQLITE_OK ){
drhee696e22004-08-30 16:52:17 +00005276 if( rc!=SQLITE_NOMEM ){
drh49285702005-09-17 15:20:26 +00005277 rc = SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00005278 }
drh5e2f8b92001-05-28 00:41:15 +00005279 }
danielk19776b456a22005-03-21 04:04:02 +00005280 if( rc==SQLITE_OK ){
5281 rc = sqlite3pager_write(leafCur.pPage->aData);
5282 }
5283 if( rc==SQLITE_OK ){
5284 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
5285 pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
5286 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
5287 pNext = findCell(leafCur.pPage, leafCur.idx);
5288 szNext = cellSizePtr(leafCur.pPage, pNext);
5289 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
5290 tempCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
5291 if( tempCell==0 ){
5292 rc = SQLITE_NOMEM;
5293 }
5294 }
5295 if( rc==SQLITE_OK ){
5296 rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
5297 }
5298 if( rc==SQLITE_OK ){
5299 put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
5300 rc = balance(pPage, 0);
5301 }
5302 if( rc==SQLITE_OK ){
5303 dropCell(leafCur.pPage, leafCur.idx, szNext);
5304 rc = balance(leafCur.pPage, 0);
5305 }
drh2e38c322004-09-03 18:38:44 +00005306 sqliteFree(tempCell);
drh8c42ca92001-06-22 19:15:00 +00005307 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00005308 }else{
danielk1977299b1872004-11-22 10:02:10 +00005309 TRACE(("DELETE: table=%d delete from leaf %d\n",
5310 pCur->pgnoRoot, pPage->pgno));
5311 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
danielk1977ac245ec2005-01-14 13:50:11 +00005312 rc = balance(pPage, 0);
drh5e2f8b92001-05-28 00:41:15 +00005313 }
danielk19776b456a22005-03-21 04:04:02 +00005314 if( rc==SQLITE_OK ){
5315 moveToRoot(pCur);
5316 }
drh5e2f8b92001-05-28 00:41:15 +00005317 return rc;
drh3b7511c2001-05-26 13:15:44 +00005318}
drh8b2f49b2001-06-08 00:21:52 +00005319
5320/*
drhc6b52df2002-01-04 03:09:29 +00005321** Create a new BTree table. Write into *piTable the page
5322** number for the root page of the new table.
5323**
drhab01f612004-05-22 02:55:23 +00005324** The type of type is determined by the flags parameter. Only the
5325** following values of flags are currently in use. Other values for
5326** flags might not work:
5327**
5328** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
5329** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00005330*/
danielk1977aef0bf62005-12-30 16:28:01 +00005331int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
5332 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005333 MemPage *pRoot;
5334 Pgno pgnoRoot;
5335 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00005336 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005337 /* Must start a transaction first */
5338 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005339 }
danielk197728129562005-01-11 10:25:06 +00005340 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00005341
5342 /* It is illegal to create a table if any cursors are open on the
5343 ** database. This is because in auto-vacuum mode the backend may
5344 ** need to move a database page to make room for the new root-page.
5345 ** If an open cursor was using the page a problem would occur.
5346 */
5347 if( pBt->pCursor ){
5348 return SQLITE_LOCKED;
5349 }
5350
danielk1977003ba062004-11-04 02:57:33 +00005351#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977cb1a7eb2004-11-05 12:27:02 +00005352 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drh8b2f49b2001-06-08 00:21:52 +00005353 if( rc ) return rc;
danielk1977003ba062004-11-04 02:57:33 +00005354#else
danielk1977687566d2004-11-02 12:56:41 +00005355 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00005356 Pgno pgnoMove; /* Move a page here to make room for the root-page */
5357 MemPage *pPageMove; /* The page to move to. */
5358
danielk1977003ba062004-11-04 02:57:33 +00005359 /* Read the value of meta[3] from the database to determine where the
5360 ** root page of the new table should go. meta[3] is the largest root-page
5361 ** created so far, so the new root-page is (meta[3]+1).
5362 */
danielk1977aef0bf62005-12-30 16:28:01 +00005363 rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00005364 if( rc!=SQLITE_OK ) return rc;
5365 pgnoRoot++;
5366
danielk1977599fcba2004-11-08 07:13:13 +00005367 /* The new root-page may not be allocated on a pointer-map page, or the
5368 ** PENDING_BYTE page.
5369 */
drh42cac6d2004-11-20 20:31:11 +00005370 if( pgnoRoot==PTRMAP_PAGENO(pBt->usableSize, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00005371 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00005372 pgnoRoot++;
5373 }
5374 assert( pgnoRoot>=3 );
5375
5376 /* Allocate a page. The page that currently resides at pgnoRoot will
5377 ** be moved to the allocated page (unless the allocated page happens
5378 ** to reside at pgnoRoot).
5379 */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005380 rc = allocatePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00005381 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00005382 return rc;
5383 }
danielk1977003ba062004-11-04 02:57:33 +00005384
5385 if( pgnoMove!=pgnoRoot ){
5386 u8 eType;
5387 Pgno iPtrPage;
5388
5389 releasePage(pPageMove);
5390 rc = getPage(pBt, pgnoRoot, &pRoot);
5391 if( rc!=SQLITE_OK ){
5392 return rc;
5393 }
5394 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drhccae6022005-02-26 17:31:26 +00005395 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00005396 releasePage(pRoot);
5397 return rc;
5398 }
drhccae6022005-02-26 17:31:26 +00005399 assert( eType!=PTRMAP_ROOTPAGE );
5400 assert( eType!=PTRMAP_FREEPAGE );
danielk19775fd057a2005-03-09 13:09:43 +00005401 rc = sqlite3pager_write(pRoot->aData);
5402 if( rc!=SQLITE_OK ){
5403 releasePage(pRoot);
5404 return rc;
5405 }
danielk1977003ba062004-11-04 02:57:33 +00005406 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove);
5407 releasePage(pRoot);
5408 if( rc!=SQLITE_OK ){
5409 return rc;
5410 }
5411 rc = getPage(pBt, pgnoRoot, &pRoot);
5412 if( rc!=SQLITE_OK ){
5413 return rc;
5414 }
5415 rc = sqlite3pager_write(pRoot->aData);
5416 if( rc!=SQLITE_OK ){
5417 releasePage(pRoot);
5418 return rc;
5419 }
5420 }else{
5421 pRoot = pPageMove;
5422 }
5423
danielk197742741be2005-01-08 12:42:39 +00005424 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00005425 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
5426 if( rc ){
5427 releasePage(pRoot);
5428 return rc;
5429 }
danielk1977aef0bf62005-12-30 16:28:01 +00005430 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00005431 if( rc ){
5432 releasePage(pRoot);
5433 return rc;
5434 }
danielk197742741be2005-01-08 12:42:39 +00005435
danielk1977003ba062004-11-04 02:57:33 +00005436 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00005437 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00005438 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00005439 }
5440#endif
drha34b6762004-05-07 13:30:42 +00005441 assert( sqlite3pager_iswriteable(pRoot->aData) );
drhde647132004-05-07 17:57:49 +00005442 zeroPage(pRoot, flags | PTF_LEAF);
drha34b6762004-05-07 13:30:42 +00005443 sqlite3pager_unref(pRoot->aData);
drh8b2f49b2001-06-08 00:21:52 +00005444 *piTable = (int)pgnoRoot;
5445 return SQLITE_OK;
5446}
5447
5448/*
5449** Erase the given database page and all its children. Return
5450** the page to the freelist.
5451*/
drh4b70f112004-05-02 21:12:19 +00005452static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00005453 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00005454 Pgno pgno, /* Page number to clear */
5455 MemPage *pParent, /* Parent page. NULL for the root */
5456 int freePageFlag /* Deallocate page if true */
5457){
danielk19776b456a22005-03-21 04:04:02 +00005458 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00005459 int rc;
drh4b70f112004-05-02 21:12:19 +00005460 unsigned char *pCell;
5461 int i;
drh8b2f49b2001-06-08 00:21:52 +00005462
danielk1977a1cb1832005-02-12 08:59:55 +00005463 if( pgno>sqlite3pager_pagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00005464 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00005465 }
5466
drhde647132004-05-07 17:57:49 +00005467 rc = getAndInitPage(pBt, pgno, &pPage, pParent);
danielk19776b456a22005-03-21 04:04:02 +00005468 if( rc ) goto cleardatabasepage_out;
drha34b6762004-05-07 13:30:42 +00005469 rc = sqlite3pager_write(pPage->aData);
danielk19776b456a22005-03-21 04:04:02 +00005470 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00005471 for(i=0; i<pPage->nCell; i++){
drh43605152004-05-29 21:46:49 +00005472 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00005473 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005474 rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00005475 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00005476 }
drh4b70f112004-05-02 21:12:19 +00005477 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00005478 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00005479 }
drha34b6762004-05-07 13:30:42 +00005480 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005481 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00005482 if( rc ) goto cleardatabasepage_out;
drh2aa679f2001-06-25 02:11:07 +00005483 }
5484 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00005485 rc = freePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00005486 }else{
drh3a4c1412004-05-09 20:40:11 +00005487 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00005488 }
danielk19776b456a22005-03-21 04:04:02 +00005489
5490cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00005491 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00005492 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005493}
5494
5495/*
drhab01f612004-05-22 02:55:23 +00005496** Delete all information from a single table in the database. iTable is
5497** the page number of the root of the table. After this routine returns,
5498** the root page is empty, but still exists.
5499**
5500** This routine will fail with SQLITE_LOCKED if there are any open
5501** read cursors on the table. Open write cursors are moved to the
5502** root of the table.
drh8b2f49b2001-06-08 00:21:52 +00005503*/
danielk1977aef0bf62005-12-30 16:28:01 +00005504int sqlite3BtreeClearTable(Btree *p, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00005505 int rc;
drhf74b8d92002-09-01 23:20:45 +00005506 BtCursor *pCur;
danielk1977aef0bf62005-12-30 16:28:01 +00005507 BtShared *pBt = p->pBt;
5508 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005509 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005510 }
drhf74b8d92002-09-01 23:20:45 +00005511 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
5512 if( pCur->pgnoRoot==(Pgno)iTable ){
5513 if( pCur->wrFlag==0 ) return SQLITE_LOCKED;
5514 moveToRoot(pCur);
5515 }
drhecdc7532001-09-23 02:35:53 +00005516 }
drha34b6762004-05-07 13:30:42 +00005517 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
danielk197771fd80b2005-12-16 06:54:01 +00005518#if 0
drh8b2f49b2001-06-08 00:21:52 +00005519 if( rc ){
drh3aac2dd2004-04-26 14:10:20 +00005520 sqlite3BtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00005521 }
danielk197771fd80b2005-12-16 06:54:01 +00005522#endif
drh8c42ca92001-06-22 19:15:00 +00005523 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005524}
5525
5526/*
5527** Erase all information in a table and add the root of the table to
5528** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00005529** page 1) is never added to the freelist.
5530**
5531** This routine will fail with SQLITE_LOCKED if there are any open
5532** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00005533**
5534** If AUTOVACUUM is enabled and the page at iTable is not the last
5535** root page in the database file, then the last root page
5536** in the database file is moved into the slot formerly occupied by
5537** iTable and that last slot formerly occupied by the last root page
5538** is added to the freelist instead of iTable. In this say, all
5539** root pages are kept at the beginning of the database file, which
5540** is necessary for AUTOVACUUM to work right. *piMoved is set to the
5541** page number that used to be the last root page in the file before
5542** the move. If no page gets moved, *piMoved is set to 0.
5543** The last root page is recorded in meta[3] and the value of
5544** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00005545*/
danielk1977aef0bf62005-12-30 16:28:01 +00005546int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00005547 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00005548 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00005549 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00005550
danielk1977aef0bf62005-12-30 16:28:01 +00005551 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005552 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005553 }
danielk1977a0bf2652004-11-04 14:30:04 +00005554
danielk1977e6efa742004-11-10 11:55:10 +00005555 /* It is illegal to drop a table if any cursors are open on the
5556 ** database. This is because in auto-vacuum mode the backend may
5557 ** need to move another root-page to fill a gap left by the deleted
5558 ** root page. If an open cursor was using this page a problem would
5559 ** occur.
5560 */
5561 if( pBt->pCursor ){
5562 return SQLITE_LOCKED;
drh5df72a52002-06-06 23:16:05 +00005563 }
danielk1977a0bf2652004-11-04 14:30:04 +00005564
drha34b6762004-05-07 13:30:42 +00005565 rc = getPage(pBt, (Pgno)iTable, &pPage);
drh2aa679f2001-06-25 02:11:07 +00005566 if( rc ) return rc;
danielk1977aef0bf62005-12-30 16:28:01 +00005567 rc = sqlite3BtreeClearTable(p, iTable);
danielk19776b456a22005-03-21 04:04:02 +00005568 if( rc ){
5569 releasePage(pPage);
5570 return rc;
5571 }
danielk1977a0bf2652004-11-04 14:30:04 +00005572
drh205f48e2004-11-05 00:43:11 +00005573 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00005574
drh4b70f112004-05-02 21:12:19 +00005575 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00005576#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00005577 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00005578 releasePage(pPage);
5579#else
5580 if( pBt->autoVacuum ){
5581 Pgno maxRootPgno;
danielk1977aef0bf62005-12-30 16:28:01 +00005582 rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00005583 if( rc!=SQLITE_OK ){
5584 releasePage(pPage);
5585 return rc;
5586 }
5587
5588 if( iTable==maxRootPgno ){
5589 /* If the table being dropped is the table with the largest root-page
5590 ** number in the database, put the root page on the free list.
5591 */
5592 rc = freePage(pPage);
5593 releasePage(pPage);
5594 if( rc!=SQLITE_OK ){
5595 return rc;
5596 }
5597 }else{
5598 /* The table being dropped does not have the largest root-page
5599 ** number in the database. So move the page that does into the
5600 ** gap left by the deleted root-page.
5601 */
5602 MemPage *pMove;
5603 releasePage(pPage);
5604 rc = getPage(pBt, maxRootPgno, &pMove);
5605 if( rc!=SQLITE_OK ){
5606 return rc;
5607 }
5608 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable);
5609 releasePage(pMove);
5610 if( rc!=SQLITE_OK ){
5611 return rc;
5612 }
5613 rc = getPage(pBt, maxRootPgno, &pMove);
5614 if( rc!=SQLITE_OK ){
5615 return rc;
5616 }
5617 rc = freePage(pMove);
5618 releasePage(pMove);
5619 if( rc!=SQLITE_OK ){
5620 return rc;
5621 }
5622 *piMoved = maxRootPgno;
5623 }
5624
danielk1977599fcba2004-11-08 07:13:13 +00005625 /* Set the new 'max-root-page' value in the database header. This
5626 ** is the old value less one, less one more if that happens to
5627 ** be a root-page number, less one again if that is the
5628 ** PENDING_BYTE_PAGE.
5629 */
danielk197787a6e732004-11-05 12:58:25 +00005630 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00005631 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
5632 maxRootPgno--;
5633 }
drh42cac6d2004-11-20 20:31:11 +00005634 if( maxRootPgno==PTRMAP_PAGENO(pBt->usableSize, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00005635 maxRootPgno--;
5636 }
danielk1977599fcba2004-11-08 07:13:13 +00005637 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
5638
danielk1977aef0bf62005-12-30 16:28:01 +00005639 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00005640 }else{
5641 rc = freePage(pPage);
5642 releasePage(pPage);
5643 }
5644#endif
drh2aa679f2001-06-25 02:11:07 +00005645 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00005646 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00005647 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00005648 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00005649 }
drh8b2f49b2001-06-08 00:21:52 +00005650 return rc;
5651}
5652
drh001bbcb2003-03-19 03:14:00 +00005653
drh8b2f49b2001-06-08 00:21:52 +00005654/*
drh23e11ca2004-05-04 17:27:28 +00005655** Read the meta-information out of a database file. Meta[0]
5656** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00005657** through meta[15] are available for use by higher layers. Meta[0]
5658** is read-only, the others are read/write.
5659**
5660** The schema layer numbers meta values differently. At the schema
5661** layer (and the SetCookie and ReadCookie opcodes) the number of
5662** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00005663*/
danielk1977aef0bf62005-12-30 16:28:01 +00005664int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
drh8b2f49b2001-06-08 00:21:52 +00005665 int rc;
drh4b70f112004-05-02 21:12:19 +00005666 unsigned char *pP1;
danielk1977aef0bf62005-12-30 16:28:01 +00005667 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005668
danielk1977da184232006-01-05 11:34:32 +00005669 /* Reading a meta-data value requires a read-lock on page 1 (and hence
5670 ** the sqlite_master table. We grab this lock regardless of whether or
5671 ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
5672 ** 1 is treated as a special case by queryTableLock() and lockTable()).
5673 */
5674 rc = queryTableLock(p, 1, READ_LOCK);
5675 if( rc!=SQLITE_OK ){
5676 return rc;
5677 }
5678
drh23e11ca2004-05-04 17:27:28 +00005679 assert( idx>=0 && idx<=15 );
drha34b6762004-05-07 13:30:42 +00005680 rc = sqlite3pager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00005681 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00005682 *pMeta = get4byte(&pP1[36 + idx*4]);
drha34b6762004-05-07 13:30:42 +00005683 sqlite3pager_unref(pP1);
drhae157872004-08-14 19:20:09 +00005684
danielk1977599fcba2004-11-08 07:13:13 +00005685 /* If autovacuumed is disabled in this build but we are trying to
5686 ** access an autovacuumed database, then make the database readonly.
5687 */
danielk1977003ba062004-11-04 02:57:33 +00005688#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00005689 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00005690#endif
drhae157872004-08-14 19:20:09 +00005691
danielk1977da184232006-01-05 11:34:32 +00005692 /* Grab the read-lock on page 1. */
5693 rc = lockTable(p, 1, READ_LOCK);
5694 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005695}
5696
5697/*
drh23e11ca2004-05-04 17:27:28 +00005698** Write meta-information back into the database. Meta[0] is
5699** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00005700*/
danielk1977aef0bf62005-12-30 16:28:01 +00005701int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
5702 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00005703 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00005704 int rc;
drh23e11ca2004-05-04 17:27:28 +00005705 assert( idx>=1 && idx<=15 );
danielk1977aef0bf62005-12-30 16:28:01 +00005706 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005707 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +00005708 }
drhde647132004-05-07 17:57:49 +00005709 assert( pBt->pPage1!=0 );
5710 pP1 = pBt->pPage1->aData;
drha34b6762004-05-07 13:30:42 +00005711 rc = sqlite3pager_write(pP1);
drh4b70f112004-05-02 21:12:19 +00005712 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00005713 put4byte(&pP1[36 + idx*4], iMeta);
drh8b2f49b2001-06-08 00:21:52 +00005714 return SQLITE_OK;
5715}
drh8c42ca92001-06-22 19:15:00 +00005716
drhf328bc82004-05-10 23:29:49 +00005717/*
5718** Return the flag byte at the beginning of the page that the cursor
5719** is currently pointing to.
5720*/
5721int sqlite3BtreeFlags(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00005722 /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
5723 ** restoreCursorPosition() here.
5724 */
drhf328bc82004-05-10 23:29:49 +00005725 MemPage *pPage = pCur->pPage;
5726 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
5727}
5728
danielk1977b5402fb2005-01-12 07:15:04 +00005729#ifdef SQLITE_DEBUG
drh8c42ca92001-06-22 19:15:00 +00005730/*
5731** Print a disassembly of the given page on standard output. This routine
5732** is used for debugging and testing only.
5733*/
danielk1977aef0bf62005-12-30 16:28:01 +00005734static int btreePageDump(BtShared *pBt, int pgno, int recursive, MemPage *pParent){
drh8c42ca92001-06-22 19:15:00 +00005735 int rc;
5736 MemPage *pPage;
drhc8629a12004-05-08 20:07:40 +00005737 int i, j, c;
drh8c42ca92001-06-22 19:15:00 +00005738 int nFree;
5739 u16 idx;
drhab9f7f12004-05-08 10:56:11 +00005740 int hdr;
drh43605152004-05-29 21:46:49 +00005741 int nCell;
drha2fce642004-06-05 00:01:44 +00005742 int isInit;
drhab9f7f12004-05-08 10:56:11 +00005743 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00005744 char range[20];
5745 unsigned char payload[20];
drhab9f7f12004-05-08 10:56:11 +00005746
drh4b70f112004-05-02 21:12:19 +00005747 rc = getPage(pBt, (Pgno)pgno, &pPage);
drha2fce642004-06-05 00:01:44 +00005748 isInit = pPage->isInit;
5749 if( pPage->isInit==0 ){
danielk1977c7dc7532004-11-17 10:22:03 +00005750 initPage(pPage, pParent);
drha2fce642004-06-05 00:01:44 +00005751 }
drh8c42ca92001-06-22 19:15:00 +00005752 if( rc ){
5753 return rc;
5754 }
drhab9f7f12004-05-08 10:56:11 +00005755 hdr = pPage->hdrOffset;
5756 data = pPage->aData;
drhc8629a12004-05-08 20:07:40 +00005757 c = data[hdr];
drh8b18dd42004-05-12 19:18:15 +00005758 pPage->intKey = (c & (PTF_INTKEY|PTF_LEAFDATA))!=0;
drhc8629a12004-05-08 20:07:40 +00005759 pPage->zeroData = (c & PTF_ZERODATA)!=0;
drh8b18dd42004-05-12 19:18:15 +00005760 pPage->leafData = (c & PTF_LEAFDATA)!=0;
drhc8629a12004-05-08 20:07:40 +00005761 pPage->leaf = (c & PTF_LEAF)!=0;
drh8b18dd42004-05-12 19:18:15 +00005762 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
drh43605152004-05-29 21:46:49 +00005763 nCell = get2byte(&data[hdr+3]);
drhfe63d1c2004-09-08 20:13:04 +00005764 sqlite3DebugPrintf("PAGE %d: flags=0x%02x frag=%d parent=%d\n", pgno,
drh43605152004-05-29 21:46:49 +00005765 data[hdr], data[hdr+7],
drhda200cc2004-05-09 11:51:38 +00005766 (pPage->isInit && pPage->pParent) ? pPage->pParent->pgno : 0);
drhab9f7f12004-05-08 10:56:11 +00005767 assert( hdr == (pgno==1 ? 100 : 0) );
drh43605152004-05-29 21:46:49 +00005768 idx = hdr + 12 - pPage->leaf*4;
5769 for(i=0; i<nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00005770 CellInfo info;
drh4b70f112004-05-02 21:12:19 +00005771 Pgno child;
drh43605152004-05-29 21:46:49 +00005772 unsigned char *pCell;
drh6f11bef2004-05-13 01:12:56 +00005773 int sz;
drh43605152004-05-29 21:46:49 +00005774 int addr;
drh6f11bef2004-05-13 01:12:56 +00005775
drh43605152004-05-29 21:46:49 +00005776 addr = get2byte(&data[idx + 2*i]);
5777 pCell = &data[addr];
5778 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005779 sz = info.nSize;
drh43605152004-05-29 21:46:49 +00005780 sprintf(range,"%d..%d", addr, addr+sz-1);
drh4b70f112004-05-02 21:12:19 +00005781 if( pPage->leaf ){
5782 child = 0;
5783 }else{
drh43605152004-05-29 21:46:49 +00005784 child = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005785 }
drh6f11bef2004-05-13 01:12:56 +00005786 sz = info.nData;
5787 if( !pPage->intKey ) sz += info.nKey;
drh8c42ca92001-06-22 19:15:00 +00005788 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
drh6f11bef2004-05-13 01:12:56 +00005789 memcpy(payload, &pCell[info.nHeader], sz);
drh8c42ca92001-06-22 19:15:00 +00005790 for(j=0; j<sz; j++){
5791 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
5792 }
5793 payload[sz] = 0;
drhfe63d1c2004-09-08 20:13:04 +00005794 sqlite3DebugPrintf(
drh6f11bef2004-05-13 01:12:56 +00005795 "cell %2d: i=%-10s chld=%-4d nk=%-4lld nd=%-4d payload=%s\n",
5796 i, range, child, info.nKey, info.nData, payload
drh8c42ca92001-06-22 19:15:00 +00005797 );
drh8c42ca92001-06-22 19:15:00 +00005798 }
drh4b70f112004-05-02 21:12:19 +00005799 if( !pPage->leaf ){
drhfe63d1c2004-09-08 20:13:04 +00005800 sqlite3DebugPrintf("right_child: %d\n", get4byte(&data[hdr+8]));
drh4b70f112004-05-02 21:12:19 +00005801 }
drh8c42ca92001-06-22 19:15:00 +00005802 nFree = 0;
5803 i = 0;
drhab9f7f12004-05-08 10:56:11 +00005804 idx = get2byte(&data[hdr+1]);
drhb6f41482004-05-14 01:58:11 +00005805 while( idx>0 && idx<pPage->pBt->usableSize ){
drhab9f7f12004-05-08 10:56:11 +00005806 int sz = get2byte(&data[idx+2]);
drh4b70f112004-05-02 21:12:19 +00005807 sprintf(range,"%d..%d", idx, idx+sz-1);
5808 nFree += sz;
drhfe63d1c2004-09-08 20:13:04 +00005809 sqlite3DebugPrintf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
drh4b70f112004-05-02 21:12:19 +00005810 i, range, sz, nFree);
drhab9f7f12004-05-08 10:56:11 +00005811 idx = get2byte(&data[idx]);
drh2aa679f2001-06-25 02:11:07 +00005812 i++;
drh8c42ca92001-06-22 19:15:00 +00005813 }
5814 if( idx!=0 ){
drhfe63d1c2004-09-08 20:13:04 +00005815 sqlite3DebugPrintf("ERROR: next freeblock index out of range: %d\n", idx);
drh8c42ca92001-06-22 19:15:00 +00005816 }
drha34b6762004-05-07 13:30:42 +00005817 if( recursive && !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005818 for(i=0; i<nCell; i++){
5819 unsigned char *pCell = findCell(pPage, i);
danielk1977c7dc7532004-11-17 10:22:03 +00005820 btreePageDump(pBt, get4byte(pCell), 1, pPage);
drha34b6762004-05-07 13:30:42 +00005821 idx = get2byte(pCell);
drh6019e162001-07-02 17:51:45 +00005822 }
danielk1977c7dc7532004-11-17 10:22:03 +00005823 btreePageDump(pBt, get4byte(&data[hdr+8]), 1, pPage);
drh6019e162001-07-02 17:51:45 +00005824 }
drha2fce642004-06-05 00:01:44 +00005825 pPage->isInit = isInit;
drhab9f7f12004-05-08 10:56:11 +00005826 sqlite3pager_unref(data);
drh3644f082004-05-10 18:45:09 +00005827 fflush(stdout);
drh8c42ca92001-06-22 19:15:00 +00005828 return SQLITE_OK;
5829}
danielk1977aef0bf62005-12-30 16:28:01 +00005830int sqlite3BtreePageDump(Btree *p, int pgno, int recursive){
5831 return btreePageDump(p->pBt, pgno, recursive, 0);
danielk1977c7dc7532004-11-17 10:22:03 +00005832}
drhaaab5722002-02-19 13:39:21 +00005833#endif
drh8c42ca92001-06-22 19:15:00 +00005834
drhaaab5722002-02-19 13:39:21 +00005835#ifdef SQLITE_TEST
drh8c42ca92001-06-22 19:15:00 +00005836/*
drh2aa679f2001-06-25 02:11:07 +00005837** Fill aResult[] with information about the entry and page that the
5838** cursor is pointing to.
5839**
5840** aResult[0] = The page number
5841** aResult[1] = The entry number
5842** aResult[2] = Total number of entries on this page
drh3e27c022004-07-23 00:01:38 +00005843** aResult[3] = Cell size (local payload + header)
drh2aa679f2001-06-25 02:11:07 +00005844** aResult[4] = Number of free bytes on this page
5845** aResult[5] = Number of free blocks on the page
drh3e27c022004-07-23 00:01:38 +00005846** aResult[6] = Total payload size (local + overflow)
5847** aResult[7] = Header size in bytes
5848** aResult[8] = Local payload size
5849** aResult[9] = Parent page number
drh5eddca62001-06-30 21:53:53 +00005850**
5851** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00005852*/
drh3e27c022004-07-23 00:01:38 +00005853int sqlite3BtreeCursorInfo(BtCursor *pCur, int *aResult, int upCnt){
drh2aa679f2001-06-25 02:11:07 +00005854 int cnt, idx;
5855 MemPage *pPage = pCur->pPage;
drh3e27c022004-07-23 00:01:38 +00005856 BtCursor tmpCur;
drhda200cc2004-05-09 11:51:38 +00005857
danielk1977da184232006-01-05 11:34:32 +00005858 int rc = restoreCursorPosition(pCur, 1);
5859 if( rc!=SQLITE_OK ){
5860 return rc;
5861 }
5862
drhda200cc2004-05-09 11:51:38 +00005863 pageIntegrity(pPage);
drh4b70f112004-05-02 21:12:19 +00005864 assert( pPage->isInit );
drh3e27c022004-07-23 00:01:38 +00005865 getTempCursor(pCur, &tmpCur);
5866 while( upCnt-- ){
5867 moveToParent(&tmpCur);
5868 }
5869 pPage = tmpCur.pPage;
5870 pageIntegrity(pPage);
drha34b6762004-05-07 13:30:42 +00005871 aResult[0] = sqlite3pager_pagenumber(pPage->aData);
drh91025292004-05-03 19:49:32 +00005872 assert( aResult[0]==pPage->pgno );
drh3e27c022004-07-23 00:01:38 +00005873 aResult[1] = tmpCur.idx;
drh2aa679f2001-06-25 02:11:07 +00005874 aResult[2] = pPage->nCell;
drh3e27c022004-07-23 00:01:38 +00005875 if( tmpCur.idx>=0 && tmpCur.idx<pPage->nCell ){
5876 getCellInfo(&tmpCur);
5877 aResult[3] = tmpCur.info.nSize;
5878 aResult[6] = tmpCur.info.nData;
5879 aResult[7] = tmpCur.info.nHeader;
5880 aResult[8] = tmpCur.info.nLocal;
drh2aa679f2001-06-25 02:11:07 +00005881 }else{
5882 aResult[3] = 0;
5883 aResult[6] = 0;
drh3e27c022004-07-23 00:01:38 +00005884 aResult[7] = 0;
5885 aResult[8] = 0;
drh2aa679f2001-06-25 02:11:07 +00005886 }
5887 aResult[4] = pPage->nFree;
5888 cnt = 0;
drh4b70f112004-05-02 21:12:19 +00005889 idx = get2byte(&pPage->aData[pPage->hdrOffset+1]);
drhb6f41482004-05-14 01:58:11 +00005890 while( idx>0 && idx<pPage->pBt->usableSize ){
drh2aa679f2001-06-25 02:11:07 +00005891 cnt++;
drh4b70f112004-05-02 21:12:19 +00005892 idx = get2byte(&pPage->aData[idx]);
drh2aa679f2001-06-25 02:11:07 +00005893 }
5894 aResult[5] = cnt;
drh3e27c022004-07-23 00:01:38 +00005895 if( pPage->pParent==0 || isRootPage(pPage) ){
5896 aResult[9] = 0;
5897 }else{
5898 aResult[9] = pPage->pParent->pgno;
5899 }
5900 releaseTempCursor(&tmpCur);
drh8c42ca92001-06-22 19:15:00 +00005901 return SQLITE_OK;
5902}
drhaaab5722002-02-19 13:39:21 +00005903#endif
drhdd793422001-06-28 01:54:48 +00005904
drhdd793422001-06-28 01:54:48 +00005905/*
drh5eddca62001-06-30 21:53:53 +00005906** Return the pager associated with a BTree. This routine is used for
5907** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00005908*/
danielk1977aef0bf62005-12-30 16:28:01 +00005909Pager *sqlite3BtreePager(Btree *p){
5910 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00005911}
drh5eddca62001-06-30 21:53:53 +00005912
5913/*
5914** This structure is passed around through all the sanity checking routines
5915** in order to keep track of some global state information.
5916*/
drhaaab5722002-02-19 13:39:21 +00005917typedef struct IntegrityCk IntegrityCk;
5918struct IntegrityCk {
danielk1977aef0bf62005-12-30 16:28:01 +00005919 BtShared *pBt; /* The tree being checked out */
drh100569d2001-10-02 13:01:48 +00005920 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
5921 int nPage; /* Number of pages in the database */
5922 int *anRef; /* Number of times each page is referenced */
drh100569d2001-10-02 13:01:48 +00005923 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00005924};
5925
drhb7f91642004-10-31 02:22:47 +00005926#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005927/*
5928** Append a message to the error message string.
5929*/
drh2e38c322004-09-03 18:38:44 +00005930static void checkAppendMsg(
5931 IntegrityCk *pCheck,
5932 char *zMsg1,
5933 const char *zFormat,
5934 ...
5935){
5936 va_list ap;
5937 char *zMsg2;
5938 va_start(ap, zFormat);
5939 zMsg2 = sqlite3VMPrintf(zFormat, ap);
5940 va_end(ap);
5941 if( zMsg1==0 ) zMsg1 = "";
drh5eddca62001-06-30 21:53:53 +00005942 if( pCheck->zErrMsg ){
5943 char *zOld = pCheck->zErrMsg;
5944 pCheck->zErrMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00005945 sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00005946 sqliteFree(zOld);
5947 }else{
danielk19774adee202004-05-08 08:23:19 +00005948 sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00005949 }
drh2e38c322004-09-03 18:38:44 +00005950 sqliteFree(zMsg2);
drh5eddca62001-06-30 21:53:53 +00005951}
drhb7f91642004-10-31 02:22:47 +00005952#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005953
drhb7f91642004-10-31 02:22:47 +00005954#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005955/*
5956** Add 1 to the reference count for page iPage. If this is the second
5957** reference to the page, add an error message to pCheck->zErrMsg.
5958** Return 1 if there are 2 ore more references to the page and 0 if
5959** if this is the first reference to the page.
5960**
5961** Also check that the page number is in bounds.
5962*/
drhaaab5722002-02-19 13:39:21 +00005963static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00005964 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00005965 if( iPage>pCheck->nPage || iPage<0 ){
drh2e38c322004-09-03 18:38:44 +00005966 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005967 return 1;
5968 }
5969 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00005970 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005971 return 1;
5972 }
5973 return (pCheck->anRef[iPage]++)>1;
5974}
5975
danielk1977afcdd022004-10-31 16:25:42 +00005976#ifndef SQLITE_OMIT_AUTOVACUUM
5977/*
5978** Check that the entry in the pointer-map for page iChild maps to
5979** page iParent, pointer type ptrType. If not, append an error message
5980** to pCheck.
5981*/
5982static void checkPtrmap(
5983 IntegrityCk *pCheck, /* Integrity check context */
5984 Pgno iChild, /* Child page number */
5985 u8 eType, /* Expected pointer map type */
5986 Pgno iParent, /* Expected pointer map parent page number */
5987 char *zContext /* Context description (used for error msg) */
5988){
5989 int rc;
5990 u8 ePtrmapType;
5991 Pgno iPtrmapParent;
5992
5993 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
5994 if( rc!=SQLITE_OK ){
5995 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
5996 return;
5997 }
5998
5999 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
6000 checkAppendMsg(pCheck, zContext,
6001 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
6002 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
6003 }
6004}
6005#endif
6006
drh5eddca62001-06-30 21:53:53 +00006007/*
6008** Check the integrity of the freelist or of an overflow page list.
6009** Verify that the number of pages on the list is N.
6010*/
drh30e58752002-03-02 20:41:57 +00006011static void checkList(
6012 IntegrityCk *pCheck, /* Integrity checking context */
6013 int isFreeList, /* True for a freelist. False for overflow page list */
6014 int iPage, /* Page number for first page in the list */
6015 int N, /* Expected number of pages in the list */
6016 char *zContext /* Context for error messages */
6017){
6018 int i;
drh3a4c1412004-05-09 20:40:11 +00006019 int expected = N;
6020 int iFirst = iPage;
drh30e58752002-03-02 20:41:57 +00006021 while( N-- > 0 ){
drh4b70f112004-05-02 21:12:19 +00006022 unsigned char *pOvfl;
drh5eddca62001-06-30 21:53:53 +00006023 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00006024 checkAppendMsg(pCheck, zContext,
6025 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00006026 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00006027 break;
6028 }
6029 if( checkRef(pCheck, iPage, zContext) ) break;
drha34b6762004-05-07 13:30:42 +00006030 if( sqlite3pager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
drh2e38c322004-09-03 18:38:44 +00006031 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006032 break;
6033 }
drh30e58752002-03-02 20:41:57 +00006034 if( isFreeList ){
drh4b70f112004-05-02 21:12:19 +00006035 int n = get4byte(&pOvfl[4]);
danielk1977687566d2004-11-02 12:56:41 +00006036#ifndef SQLITE_OMIT_AUTOVACUUM
6037 if( pCheck->pBt->autoVacuum ){
6038 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
6039 }
6040#endif
drh855eb1c2004-08-31 13:45:11 +00006041 if( n>pCheck->pBt->usableSize/4-8 ){
drh2e38c322004-09-03 18:38:44 +00006042 checkAppendMsg(pCheck, zContext,
6043 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00006044 N--;
6045 }else{
6046 for(i=0; i<n; i++){
danielk1977687566d2004-11-02 12:56:41 +00006047 Pgno iFreePage = get4byte(&pOvfl[8+i*4]);
6048#ifndef SQLITE_OMIT_AUTOVACUUM
6049 if( pCheck->pBt->autoVacuum ){
6050 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
6051 }
6052#endif
6053 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00006054 }
6055 N -= n;
drh30e58752002-03-02 20:41:57 +00006056 }
drh30e58752002-03-02 20:41:57 +00006057 }
danielk1977afcdd022004-10-31 16:25:42 +00006058#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006059 else{
6060 /* If this database supports auto-vacuum and iPage is not the last
6061 ** page in this overflow list, check that the pointer-map entry for
6062 ** the following page matches iPage.
6063 */
6064 if( pCheck->pBt->autoVacuum && N>0 ){
6065 i = get4byte(pOvfl);
6066 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
6067 }
danielk1977afcdd022004-10-31 16:25:42 +00006068 }
6069#endif
drh4b70f112004-05-02 21:12:19 +00006070 iPage = get4byte(pOvfl);
drha34b6762004-05-07 13:30:42 +00006071 sqlite3pager_unref(pOvfl);
drh5eddca62001-06-30 21:53:53 +00006072 }
6073}
drhb7f91642004-10-31 02:22:47 +00006074#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006075
drhb7f91642004-10-31 02:22:47 +00006076#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006077/*
6078** Do various sanity checks on a single page of a tree. Return
6079** the tree depth. Root pages return 0. Parents of root pages
6080** return 1, and so forth.
6081**
6082** These checks are done:
6083**
6084** 1. Make sure that cells and freeblocks do not overlap
6085** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00006086** NO 2. Make sure cell keys are in order.
6087** NO 3. Make sure no key is less than or equal to zLowerBound.
6088** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00006089** 5. Check the integrity of overflow pages.
6090** 6. Recursively call checkTreePage on all children.
6091** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00006092** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00006093** the root of the tree.
6094*/
6095static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00006096 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00006097 int iPage, /* Page number of the page to check */
6098 MemPage *pParent, /* Parent page */
6099 char *zParentContext, /* Parent context */
6100 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00006101 int nLower, /* Number of characters in zLowerBound */
6102 char *zUpperBound, /* All keys should be less than this, if not NULL */
6103 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00006104){
6105 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00006106 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00006107 int hdr, cellStart;
6108 int nCell;
drhda200cc2004-05-09 11:51:38 +00006109 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00006110 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00006111 int usableSize;
drh5eddca62001-06-30 21:53:53 +00006112 char zContext[100];
drh2e38c322004-09-03 18:38:44 +00006113 char *hit;
drh5eddca62001-06-30 21:53:53 +00006114
danielk1977ef73ee92004-11-06 12:26:07 +00006115 sprintf(zContext, "Page %d: ", iPage);
6116
drh5eddca62001-06-30 21:53:53 +00006117 /* Check that the page exists
6118 */
drhd9cb6ac2005-10-20 07:28:17 +00006119 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00006120 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00006121 if( iPage==0 ) return 0;
6122 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh4b70f112004-05-02 21:12:19 +00006123 if( (rc = getPage(pBt, (Pgno)iPage, &pPage))!=0 ){
drh2e38c322004-09-03 18:38:44 +00006124 checkAppendMsg(pCheck, zContext,
6125 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00006126 return 0;
6127 }
drh4b70f112004-05-02 21:12:19 +00006128 if( (rc = initPage(pPage, pParent))!=0 ){
drh2e38c322004-09-03 18:38:44 +00006129 checkAppendMsg(pCheck, zContext, "initPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00006130 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00006131 return 0;
6132 }
6133
6134 /* Check out all the cells.
6135 */
6136 depth = 0;
drh5eddca62001-06-30 21:53:53 +00006137 for(i=0; i<pPage->nCell; i++){
drh6f11bef2004-05-13 01:12:56 +00006138 u8 *pCell;
6139 int sz;
6140 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00006141
6142 /* Check payload overflow pages
6143 */
drh3a4c1412004-05-09 20:40:11 +00006144 sprintf(zContext, "On tree page %d cell %d: ", iPage, i);
drh43605152004-05-29 21:46:49 +00006145 pCell = findCell(pPage,i);
6146 parseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00006147 sz = info.nData;
6148 if( !pPage->intKey ) sz += info.nKey;
6149 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00006150 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00006151 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
6152#ifndef SQLITE_OMIT_AUTOVACUUM
6153 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006154 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00006155 }
6156#endif
6157 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00006158 }
6159
6160 /* Check sanity of left child page.
6161 */
drhda200cc2004-05-09 11:51:38 +00006162 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006163 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00006164#ifndef SQLITE_OMIT_AUTOVACUUM
6165 if( pBt->autoVacuum ){
6166 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
6167 }
6168#endif
drhda200cc2004-05-09 11:51:38 +00006169 d2 = checkTreePage(pCheck,pgno,pPage,zContext,0,0,0,0);
6170 if( i>0 && d2!=depth ){
6171 checkAppendMsg(pCheck, zContext, "Child page depth differs");
6172 }
6173 depth = d2;
drh5eddca62001-06-30 21:53:53 +00006174 }
drh5eddca62001-06-30 21:53:53 +00006175 }
drhda200cc2004-05-09 11:51:38 +00006176 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006177 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drhda200cc2004-05-09 11:51:38 +00006178 sprintf(zContext, "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00006179#ifndef SQLITE_OMIT_AUTOVACUUM
6180 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006181 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00006182 }
6183#endif
drhda200cc2004-05-09 11:51:38 +00006184 checkTreePage(pCheck, pgno, pPage, zContext,0,0,0,0);
6185 }
drh5eddca62001-06-30 21:53:53 +00006186
6187 /* Check for complete coverage of the page
6188 */
drhda200cc2004-05-09 11:51:38 +00006189 data = pPage->aData;
6190 hdr = pPage->hdrOffset;
drh2e38c322004-09-03 18:38:44 +00006191 hit = sqliteMalloc( usableSize );
6192 if( hit ){
6193 memset(hit, 1, get2byte(&data[hdr+5]));
6194 nCell = get2byte(&data[hdr+3]);
6195 cellStart = hdr + 12 - 4*pPage->leaf;
6196 for(i=0; i<nCell; i++){
6197 int pc = get2byte(&data[cellStart+i*2]);
6198 int size = cellSizePtr(pPage, &data[pc]);
6199 int j;
danielk19777701e812005-01-10 12:59:51 +00006200 if( (pc+size-1)>=usableSize || pc<0 ){
6201 checkAppendMsg(pCheck, 0,
6202 "Corruption detected in cell %d on page %d",i,iPage,0);
6203 }else{
6204 for(j=pc+size-1; j>=pc; j--) hit[j]++;
6205 }
drh2e38c322004-09-03 18:38:44 +00006206 }
6207 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
6208 cnt++){
6209 int size = get2byte(&data[i+2]);
6210 int j;
danielk19777701e812005-01-10 12:59:51 +00006211 if( (i+size-1)>=usableSize || i<0 ){
6212 checkAppendMsg(pCheck, 0,
6213 "Corruption detected in cell %d on page %d",i,iPage,0);
6214 }else{
6215 for(j=i+size-1; j>=i; j--) hit[j]++;
6216 }
drh2e38c322004-09-03 18:38:44 +00006217 i = get2byte(&data[i]);
6218 }
6219 for(i=cnt=0; i<usableSize; i++){
6220 if( hit[i]==0 ){
6221 cnt++;
6222 }else if( hit[i]>1 ){
6223 checkAppendMsg(pCheck, 0,
6224 "Multiple uses for byte %d of page %d", i, iPage);
6225 break;
6226 }
6227 }
6228 if( cnt!=data[hdr+7] ){
6229 checkAppendMsg(pCheck, 0,
6230 "Fragmented space is %d byte reported as %d on page %d",
6231 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00006232 }
6233 }
drh2e38c322004-09-03 18:38:44 +00006234 sqliteFree(hit);
drh6019e162001-07-02 17:51:45 +00006235
drh4b70f112004-05-02 21:12:19 +00006236 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00006237 return depth+1;
drh5eddca62001-06-30 21:53:53 +00006238}
drhb7f91642004-10-31 02:22:47 +00006239#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006240
drhb7f91642004-10-31 02:22:47 +00006241#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006242/*
6243** This routine does a complete check of the given BTree file. aRoot[] is
6244** an array of pages numbers were each page number is the root page of
6245** a table. nRoot is the number of entries in aRoot.
6246**
6247** If everything checks out, this routine returns NULL. If something is
6248** amiss, an error message is written into memory obtained from malloc()
6249** and a pointer to that error message is returned. The calling function
6250** is responsible for freeing the error message when it is done.
6251*/
danielk1977aef0bf62005-12-30 16:28:01 +00006252char *sqlite3BtreeIntegrityCheck(Btree *p, int *aRoot, int nRoot){
drh5eddca62001-06-30 21:53:53 +00006253 int i;
6254 int nRef;
drhaaab5722002-02-19 13:39:21 +00006255 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00006256 BtShared *pBt = p->pBt;
drh5eddca62001-06-30 21:53:53 +00006257
drha34b6762004-05-07 13:30:42 +00006258 nRef = *sqlite3pager_stats(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00006259 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
drhefc251d2001-07-01 22:12:01 +00006260 return sqliteStrDup("Unable to acquire a read lock on the database");
6261 }
drh5eddca62001-06-30 21:53:53 +00006262 sCheck.pBt = pBt;
6263 sCheck.pPager = pBt->pPager;
drha34b6762004-05-07 13:30:42 +00006264 sCheck.nPage = sqlite3pager_pagecount(sCheck.pPager);
drh0de8c112002-07-06 16:32:14 +00006265 if( sCheck.nPage==0 ){
6266 unlockBtreeIfUnused(pBt);
6267 return 0;
6268 }
drh8c1238a2003-01-02 14:43:55 +00006269 sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00006270 if( !sCheck.anRef ){
6271 unlockBtreeIfUnused(pBt);
6272 return sqlite3MPrintf("Unable to malloc %d bytes",
6273 (sCheck.nPage+1)*sizeof(sCheck.anRef[0]));
6274 }
drhda200cc2004-05-09 11:51:38 +00006275 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00006276 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00006277 if( i<=sCheck.nPage ){
6278 sCheck.anRef[i] = 1;
6279 }
drh5eddca62001-06-30 21:53:53 +00006280 sCheck.zErrMsg = 0;
6281
6282 /* Check the integrity of the freelist
6283 */
drha34b6762004-05-07 13:30:42 +00006284 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
6285 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00006286
6287 /* Check all the tables.
6288 */
6289 for(i=0; i<nRoot; i++){
drh4ff6dfa2002-03-03 23:06:00 +00006290 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00006291#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006292 if( pBt->autoVacuum && aRoot[i]>1 ){
6293 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
6294 }
6295#endif
drh1bffb9c2002-02-03 17:37:36 +00006296 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00006297 }
6298
6299 /* Make sure every page in the file is referenced
6300 */
6301 for(i=1; i<=sCheck.nPage; i++){
danielk1977afcdd022004-10-31 16:25:42 +00006302#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00006303 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00006304 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00006305 }
danielk1977afcdd022004-10-31 16:25:42 +00006306#else
6307 /* If the database supports auto-vacuum, make sure no tables contain
6308 ** references to pointer-map pages.
6309 */
6310 if( sCheck.anRef[i]==0 &&
drh42cac6d2004-11-20 20:31:11 +00006311 (PTRMAP_PAGENO(pBt->usableSize, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006312 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
6313 }
6314 if( sCheck.anRef[i]!=0 &&
drh42cac6d2004-11-20 20:31:11 +00006315 (PTRMAP_PAGENO(pBt->usableSize, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006316 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
6317 }
6318#endif
drh5eddca62001-06-30 21:53:53 +00006319 }
6320
6321 /* Make sure this analysis did not leave any unref() pages
6322 */
drh5e00f6c2001-09-13 13:46:56 +00006323 unlockBtreeIfUnused(pBt);
drha34b6762004-05-07 13:30:42 +00006324 if( nRef != *sqlite3pager_stats(pBt->pPager) ){
drh2e38c322004-09-03 18:38:44 +00006325 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00006326 "Outstanding page count goes from %d to %d during this analysis",
drha34b6762004-05-07 13:30:42 +00006327 nRef, *sqlite3pager_stats(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00006328 );
drh5eddca62001-06-30 21:53:53 +00006329 }
6330
6331 /* Clean up and report errors.
6332 */
6333 sqliteFree(sCheck.anRef);
6334 return sCheck.zErrMsg;
6335}
drhb7f91642004-10-31 02:22:47 +00006336#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00006337
drh73509ee2003-04-06 20:44:45 +00006338/*
6339** Return the full pathname of the underlying database file.
6340*/
danielk1977aef0bf62005-12-30 16:28:01 +00006341const char *sqlite3BtreeGetFilename(Btree *p){
6342 assert( p->pBt->pPager!=0 );
6343 return sqlite3pager_filename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00006344}
6345
6346/*
danielk19775865e3d2004-06-14 06:03:57 +00006347** Return the pathname of the directory that contains the database file.
6348*/
danielk1977aef0bf62005-12-30 16:28:01 +00006349const char *sqlite3BtreeGetDirname(Btree *p){
6350 assert( p->pBt->pPager!=0 );
6351 return sqlite3pager_dirname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006352}
6353
6354/*
6355** Return the pathname of the journal file for this database. The return
6356** value of this routine is the same regardless of whether the journal file
6357** has been created or not.
6358*/
danielk1977aef0bf62005-12-30 16:28:01 +00006359const char *sqlite3BtreeGetJournalname(Btree *p){
6360 assert( p->pBt->pPager!=0 );
6361 return sqlite3pager_journalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006362}
6363
drhb7f91642004-10-31 02:22:47 +00006364#ifndef SQLITE_OMIT_VACUUM
danielk19775865e3d2004-06-14 06:03:57 +00006365/*
drhf7c57532003-04-25 13:22:51 +00006366** Copy the complete content of pBtFrom into pBtTo. A transaction
6367** must be active for both files.
6368**
6369** The size of file pBtFrom may be reduced by this operation.
drh43605152004-05-29 21:46:49 +00006370** If anything goes wrong, the transaction on pBtFrom is rolled back.
drh73509ee2003-04-06 20:44:45 +00006371*/
danielk1977aef0bf62005-12-30 16:28:01 +00006372int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
drhf7c57532003-04-25 13:22:51 +00006373 int rc = SQLITE_OK;
drh50f2f432005-09-16 11:32:18 +00006374 Pgno i, nPage, nToPage, iSkip;
drhf7c57532003-04-25 13:22:51 +00006375
danielk1977aef0bf62005-12-30 16:28:01 +00006376 BtShared *pBtTo = pTo->pBt;
6377 BtShared *pBtFrom = pFrom->pBt;
6378
6379 if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
danielk1977ee5741e2004-05-31 10:01:34 +00006380 return SQLITE_ERROR;
6381 }
drhf7c57532003-04-25 13:22:51 +00006382 if( pBtTo->pCursor ) return SQLITE_BUSY;
drha34b6762004-05-07 13:30:42 +00006383 nToPage = sqlite3pager_pagecount(pBtTo->pPager);
6384 nPage = sqlite3pager_pagecount(pBtFrom->pPager);
drh50f2f432005-09-16 11:32:18 +00006385 iSkip = PENDING_BYTE_PAGE(pBtTo);
danielk1977369f27e2004-06-15 11:40:04 +00006386 for(i=1; rc==SQLITE_OK && i<=nPage; i++){
drhf7c57532003-04-25 13:22:51 +00006387 void *pPage;
drh50f2f432005-09-16 11:32:18 +00006388 if( i==iSkip ) continue;
drha34b6762004-05-07 13:30:42 +00006389 rc = sqlite3pager_get(pBtFrom->pPager, i, &pPage);
drhf7c57532003-04-25 13:22:51 +00006390 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00006391 rc = sqlite3pager_overwrite(pBtTo->pPager, i, pPage);
drh2e6d11b2003-04-25 15:37:57 +00006392 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00006393 sqlite3pager_unref(pPage);
drhf7c57532003-04-25 13:22:51 +00006394 }
drh2e6d11b2003-04-25 15:37:57 +00006395 for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
6396 void *pPage;
drh49285702005-09-17 15:20:26 +00006397 if( i==iSkip ) continue;
drha34b6762004-05-07 13:30:42 +00006398 rc = sqlite3pager_get(pBtTo->pPager, i, &pPage);
drh2e6d11b2003-04-25 15:37:57 +00006399 if( rc ) break;
drha34b6762004-05-07 13:30:42 +00006400 rc = sqlite3pager_write(pPage);
6401 sqlite3pager_unref(pPage);
6402 sqlite3pager_dont_write(pBtTo->pPager, i);
drh2e6d11b2003-04-25 15:37:57 +00006403 }
6404 if( !rc && nPage<nToPage ){
drha34b6762004-05-07 13:30:42 +00006405 rc = sqlite3pager_truncate(pBtTo->pPager, nPage);
drh2e6d11b2003-04-25 15:37:57 +00006406 }
drhf7c57532003-04-25 13:22:51 +00006407 if( rc ){
danielk1977aef0bf62005-12-30 16:28:01 +00006408 sqlite3BtreeRollback(pTo);
drhf7c57532003-04-25 13:22:51 +00006409 }
6410 return rc;
drh73509ee2003-04-06 20:44:45 +00006411}
drhb7f91642004-10-31 02:22:47 +00006412#endif /* SQLITE_OMIT_VACUUM */
danielk19771d850a72004-05-31 08:26:49 +00006413
6414/*
6415** Return non-zero if a transaction is active.
6416*/
danielk1977aef0bf62005-12-30 16:28:01 +00006417int sqlite3BtreeIsInTrans(Btree *p){
6418 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00006419}
6420
6421/*
6422** Return non-zero if a statement transaction is active.
6423*/
danielk1977aef0bf62005-12-30 16:28:01 +00006424int sqlite3BtreeIsInStmt(Btree *p){
6425 return (p->pBt && p->pBt->inStmt);
danielk19771d850a72004-05-31 08:26:49 +00006426}
danielk197713adf8a2004-06-03 16:08:41 +00006427
6428/*
6429** This call is a no-op if no write-transaction is currently active on pBt.
6430**
6431** Otherwise, sync the database file for the btree pBt. zMaster points to
6432** the name of a master journal file that should be written into the
6433** individual journal file, or is NULL, indicating no master journal file
6434** (single database transaction).
6435**
6436** When this is called, the master journal should already have been
6437** created, populated with this journal pointer and synced to disk.
6438**
6439** Once this is routine has returned, the only thing required to commit
6440** the write-transaction for this database file is to delete the journal.
6441*/
danielk1977aef0bf62005-12-30 16:28:01 +00006442int sqlite3BtreeSync(Btree *p, const char *zMaster){
6443 if( p->inTrans==TRANS_WRITE ){
6444 BtShared *pBt = p->pBt;
danielk1977687566d2004-11-02 12:56:41 +00006445#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977d761c0c2004-11-05 16:37:02 +00006446 Pgno nTrunc = 0;
danielk1977687566d2004-11-02 12:56:41 +00006447 if( pBt->autoVacuum ){
danielk1977d761c0c2004-11-05 16:37:02 +00006448 int rc = autoVacuumCommit(pBt, &nTrunc);
danielk1977687566d2004-11-02 12:56:41 +00006449 if( rc!=SQLITE_OK ) return rc;
6450 }
danielk1977d761c0c2004-11-05 16:37:02 +00006451 return sqlite3pager_sync(pBt->pPager, zMaster, nTrunc);
danielk1977687566d2004-11-02 12:56:41 +00006452#endif
danielk1977d761c0c2004-11-05 16:37:02 +00006453 return sqlite3pager_sync(pBt->pPager, zMaster, 0);
danielk197713adf8a2004-06-03 16:08:41 +00006454 }
6455 return SQLITE_OK;
6456}
danielk1977aef0bf62005-12-30 16:28:01 +00006457
danielk1977da184232006-01-05 11:34:32 +00006458/*
6459** This function returns a pointer to a blob of memory associated with
6460** a single shared-btree. The memory is used by client code for it's own
6461** purposes (for example, to store a high-level schema associated with
6462** the shared-btree). The btree layer manages reference counting issues.
6463**
6464** The first time this is called on a shared-btree, nBytes bytes of memory
6465** are allocated, zeroed, and returned to the caller. For each subsequent
6466** call the nBytes parameter is ignored and a pointer to the same blob
6467** of memory returned.
6468**
6469** Just before the shared-btree is closed, the function passed as the
6470** xFree argument when the memory allocation was made is invoked on the
6471** blob of allocated memory. This function should not call sqliteFree()
6472** on the memory, the btree layer does that.
6473*/
6474void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
6475 BtShared *pBt = p->pBt;
6476 if( !pBt->pSchema ){
6477 pBt->pSchema = sqliteMalloc(nBytes);
6478 pBt->xFreeSchema = xFree;
6479 }
6480 return pBt->pSchema;
6481}
6482
danielk1977c87d34d2006-01-06 13:00:28 +00006483/*
6484** Return true if another user of the same shared btree as the argument
6485** handle holds an exclusive lock on the sqlite_master table.
6486*/
6487int sqlite3BtreeSchemaLocked(Btree *p){
6488 return (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
6489}
6490
danielk1977c00da102006-01-07 13:21:04 +00006491int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00006492 int rc = SQLITE_OK;
6493#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977c00da102006-01-07 13:21:04 +00006494 u8 lockType = (isWriteLock?WRITE_LOCK:READ_LOCK);
danielk19772e94d4d2006-01-09 05:36:27 +00006495 rc = queryTableLock(p, iTab, lockType);
danielk1977c00da102006-01-07 13:21:04 +00006496 if( rc==SQLITE_OK ){
6497 rc = lockTable(p, iTab, lockType);
6498 }
danielk19772e94d4d2006-01-09 05:36:27 +00006499#endif
danielk1977c00da102006-01-07 13:21:04 +00006500 return rc;
6501}
danielk1977b82e7ed2006-01-11 14:09:31 +00006502
6503#if defined(SQLITE_TEST) && !defined(NO_TCL)
6504#include <tcl.h>
6505int sqlite3_shared_cache_report(
6506 void * clientData,
6507 Tcl_Interp *interp,
6508 int objc,
6509 Tcl_Obj *CONST objv[]
6510){
6511 ThreadData *pTd = sqlite3ThreadData();
6512 if( pTd->useSharedData ){
6513 BtShared *pBt;
6514 Tcl_Obj *pRet = Tcl_NewObj();
6515 for(pBt=pTd->pBtree; pBt; pBt=pBt->pNext){
6516 const char *zFile = sqlite3pager_filename(pBt->pPager);
6517 Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj(zFile, -1));
6518 Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(pBt->nRef));
6519 }
6520 Tcl_SetObjResult(interp, pRet);
6521 }
6522 return TCL_OK;
6523}
6524#endif
6525