blob: 0b85a933fcf73fb5a7faf28be4c5975fd9367c45 [file] [log] [blame]
drha059ad02001-04-17 20:09:11 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
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*************************************************************************
drhc3b70572003-01-04 19:44:07 +000012** $Id: btree.c,v 1.79 2003/01/04 19:44:08 drh Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
15** For a detailed discussion of BTrees, refer to
16**
17** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
18** "Sorting And Searching", pages 473-480. Addison-Wesley
19** Publishing Company, Reading, Massachusetts.
20**
21** The basic idea is that each page of the file contains N database
22** entries and N+1 pointers to subpages.
23**
24** ----------------------------------------------------------------
25** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N) | Ptr(N+1) |
26** ----------------------------------------------------------------
27**
28** All of the keys on the page that Ptr(0) points to have values less
29** than Key(0). All of the keys on page Ptr(1) and its subpages have
30** values greater than Key(0) and less than Key(1). All of the keys
31** on Ptr(N+1) and its subpages have values greater than Key(N). And
32** so forth.
33**
drh5e00f6c2001-09-13 13:46:56 +000034** Finding a particular key requires reading O(log(M)) pages from the
35** disk where M is the number of entries in the tree.
drh8b2f49b2001-06-08 00:21:52 +000036**
37** In this implementation, a single file can hold one or more separate
38** BTrees. Each BTree is identified by the index of its root page. The
39** key and data for any entry are combined to form the "payload". Up to
40** MX_LOCAL_PAYLOAD bytes of payload can be carried directly on the
41** database page. If the payload is larger than MX_LOCAL_PAYLOAD bytes
42** then surplus bytes are stored on overflow pages. The payload for an
43** entry and the preceding pointer are combined to form a "Cell". Each
drhb19a2bc2001-09-16 00:13:26 +000044** page has a small header which contains the Ptr(N+1) pointer.
drh8b2f49b2001-06-08 00:21:52 +000045**
46** The first page of the file contains a magic string used to verify that
47** the file really is a valid BTree database, a pointer to a list of unused
48** pages in the file, and some meta information. The root of the first
49** BTree begins on page 2 of the file. (Pages are numbered beginning with
50** 1, not 0.) Thus a minimum database contains 2 pages.
drha059ad02001-04-17 20:09:11 +000051*/
52#include "sqliteInt.h"
53#include "pager.h"
54#include "btree.h"
55#include <assert.h>
56
drh8c42ca92001-06-22 19:15:00 +000057/*
drh0d316a42002-08-11 20:10:47 +000058** Macros used for byteswapping. B is a pointer to the Btree
59** structure. This is needed to access the Btree.needSwab boolean
60** in order to tell if byte swapping is needed or not.
61** X is an unsigned integer. SWAB16 byte swaps a 16-bit integer.
62** SWAB32 byteswaps a 32-bit integer.
63*/
64#define SWAB16(B,X) ((B)->needSwab? swab16(X) : (X))
65#define SWAB32(B,X) ((B)->needSwab? swab32(X) : (X))
66#define SWAB_ADD(B,X,A) \
67 if((B)->needSwab){ X=swab32(swab32(X)+A); }else{ X += (A); }
68
69/*
70** The following global variable - available only if SQLITE_TEST is
71** defined - is used to determine whether new databases are created in
72** native byte order or in non-native byte order. Non-native byte order
73** databases are created for testing purposes only. Under normal operation,
74** only native byte-order databases should be created, but we should be
75** able to read or write existing databases regardless of the byteorder.
76*/
77#ifdef SQLITE_TEST
78int btree_native_byte_order = 1;
drh74587e52002-08-13 00:01:16 +000079#else
80# define btree_native_byte_order 1
drh0d316a42002-08-11 20:10:47 +000081#endif
82
83/*
drh365d68f2001-05-11 11:02:46 +000084** Forward declarations of structures used only in this file.
85*/
drhbd03cae2001-06-02 02:40:57 +000086typedef struct PageOne PageOne;
drh2af926b2001-05-15 00:39:25 +000087typedef struct MemPage MemPage;
drh365d68f2001-05-11 11:02:46 +000088typedef struct PageHdr PageHdr;
89typedef struct Cell Cell;
drh3b7511c2001-05-26 13:15:44 +000090typedef struct CellHdr CellHdr;
drh365d68f2001-05-11 11:02:46 +000091typedef struct FreeBlk FreeBlk;
drh2af926b2001-05-15 00:39:25 +000092typedef struct OverflowPage OverflowPage;
drh30e58752002-03-02 20:41:57 +000093typedef struct FreelistInfo FreelistInfo;
drh2af926b2001-05-15 00:39:25 +000094
95/*
96** All structures on a database page are aligned to 4-byte boundries.
97** This routine rounds up a number of bytes to the next multiple of 4.
drh306dc212001-05-21 13:45:10 +000098**
99** This might need to change for computer architectures that require
100** and 8-byte alignment boundry for structures.
drh2af926b2001-05-15 00:39:25 +0000101*/
102#define ROUNDUP(X) ((X+3) & ~3)
drha059ad02001-04-17 20:09:11 +0000103
drh08ed44e2001-04-29 23:32:55 +0000104/*
drhbd03cae2001-06-02 02:40:57 +0000105** This is a magic string that appears at the beginning of every
drh8c42ca92001-06-22 19:15:00 +0000106** SQLite database in order to identify the file as a real database.
drh08ed44e2001-04-29 23:32:55 +0000107*/
drhbd03cae2001-06-02 02:40:57 +0000108static const char zMagicHeader[] =
drh80ff32f2001-11-04 18:32:46 +0000109 "** This file contains an SQLite 2.1 database **";
drhbd03cae2001-06-02 02:40:57 +0000110#define MAGIC_SIZE (sizeof(zMagicHeader))
drh08ed44e2001-04-29 23:32:55 +0000111
112/*
drh5e00f6c2001-09-13 13:46:56 +0000113** This is a magic integer also used to test the integrity of the database
drh8c42ca92001-06-22 19:15:00 +0000114** file. This integer is used in addition to the string above so that
115** if the file is written on a little-endian architecture and read
116** on a big-endian architectures (or vice versa) we can detect the
117** problem.
118**
119** The number used was obtained at random and has no special
drhb19a2bc2001-09-16 00:13:26 +0000120** significance other than the fact that it represents a different
121** integer on little-endian and big-endian machines.
drh8c42ca92001-06-22 19:15:00 +0000122*/
123#define MAGIC 0xdae37528
124
125/*
drhbd03cae2001-06-02 02:40:57 +0000126** The first page of the database file contains a magic header string
127** to identify the file as an SQLite database file. It also contains
128** a pointer to the first free page of the file. Page 2 contains the
drh8b2f49b2001-06-08 00:21:52 +0000129** root of the principle BTree. The file might contain other BTrees
130** rooted on pages above 2.
131**
132** The first page also contains SQLITE_N_BTREE_META integers that
133** can be used by higher-level routines.
drh08ed44e2001-04-29 23:32:55 +0000134**
drhbd03cae2001-06-02 02:40:57 +0000135** Remember that pages are numbered beginning with 1. (See pager.c
136** for additional information.) Page 0 does not exist and a page
137** number of 0 is used to mean "no such page".
138*/
139struct PageOne {
140 char zMagic[MAGIC_SIZE]; /* String that identifies the file as a database */
drh8c42ca92001-06-22 19:15:00 +0000141 int iMagic; /* Integer to verify correct byte order */
142 Pgno freeList; /* First free page in a list of all free pages */
drh2aa679f2001-06-25 02:11:07 +0000143 int nFree; /* Number of pages on the free list */
144 int aMeta[SQLITE_N_BTREE_META-1]; /* User defined integers */
drhbd03cae2001-06-02 02:40:57 +0000145};
146
147/*
148** Each database page has a header that is an instance of this
149** structure.
drh08ed44e2001-04-29 23:32:55 +0000150**
drh8b2f49b2001-06-08 00:21:52 +0000151** PageHdr.firstFree is 0 if there is no free space on this page.
drh14acc042001-06-10 19:56:58 +0000152** Otherwise, PageHdr.firstFree is the index in MemPage.u.aDisk[] of a
drh8b2f49b2001-06-08 00:21:52 +0000153** FreeBlk structure that describes the first block of free space.
154** All free space is defined by a linked list of FreeBlk structures.
drh08ed44e2001-04-29 23:32:55 +0000155**
drh8b2f49b2001-06-08 00:21:52 +0000156** Data is stored in a linked list of Cell structures. PageHdr.firstCell
drh14acc042001-06-10 19:56:58 +0000157** is the index into MemPage.u.aDisk[] of the first cell on the page. The
drh306dc212001-05-21 13:45:10 +0000158** Cells are kept in sorted order.
drh8b2f49b2001-06-08 00:21:52 +0000159**
160** A Cell contains all information about a database entry and a pointer
161** to a child page that contains other entries less than itself. In
162** other words, the i-th Cell contains both Ptr(i) and Key(i). The
163** right-most pointer of the page is contained in PageHdr.rightChild.
drh08ed44e2001-04-29 23:32:55 +0000164*/
drh365d68f2001-05-11 11:02:46 +0000165struct PageHdr {
drh5e2f8b92001-05-28 00:41:15 +0000166 Pgno rightChild; /* Child page that comes after all cells on this page */
drh14acc042001-06-10 19:56:58 +0000167 u16 firstCell; /* Index in MemPage.u.aDisk[] of the first cell */
168 u16 firstFree; /* Index in MemPage.u.aDisk[] of the first free block */
drh365d68f2001-05-11 11:02:46 +0000169};
drh306dc212001-05-21 13:45:10 +0000170
drh3b7511c2001-05-26 13:15:44 +0000171/*
172** Entries on a page of the database are called "Cells". Each Cell
173** has a header and data. This structure defines the header. The
drhbd03cae2001-06-02 02:40:57 +0000174** key and data (collectively the "payload") follow this header on
175** the database page.
176**
177** A definition of the complete Cell structure is given below. The
drh8c42ca92001-06-22 19:15:00 +0000178** header for the cell must be defined first in order to do some
drhbd03cae2001-06-02 02:40:57 +0000179** of the sizing #defines that follow.
drh3b7511c2001-05-26 13:15:44 +0000180*/
181struct CellHdr {
drh5e2f8b92001-05-28 00:41:15 +0000182 Pgno leftChild; /* Child page that comes before this cell */
drh3b7511c2001-05-26 13:15:44 +0000183 u16 nKey; /* Number of bytes in the key */
drh14acc042001-06-10 19:56:58 +0000184 u16 iNext; /* Index in MemPage.u.aDisk[] of next cell in sorted order */
drh58a11682001-11-10 13:51:08 +0000185 u8 nKeyHi; /* Upper 8 bits of key size for keys larger than 64K bytes */
186 u8 nDataHi; /* Upper 8 bits of data size when the size is more than 64K */
drh80ff32f2001-11-04 18:32:46 +0000187 u16 nData; /* Number of bytes of data */
drh8c42ca92001-06-22 19:15:00 +0000188};
drh58a11682001-11-10 13:51:08 +0000189
190/*
191** The key and data size are split into a lower 16-bit segment and an
192** upper 8-bit segment in order to pack them together into a smaller
193** space. The following macros reassembly a key or data size back
194** into an integer.
195*/
drh0d316a42002-08-11 20:10:47 +0000196#define NKEY(b,h) (SWAB16(b,h.nKey) + h.nKeyHi*65536)
197#define NDATA(b,h) (SWAB16(b,h.nData) + h.nDataHi*65536)
drh3b7511c2001-05-26 13:15:44 +0000198
199/*
200** The minimum size of a complete Cell. The Cell must contain a header
drhbd03cae2001-06-02 02:40:57 +0000201** and at least 4 bytes of payload.
drh3b7511c2001-05-26 13:15:44 +0000202*/
203#define MIN_CELL_SIZE (sizeof(CellHdr)+4)
204
205/*
206** The maximum number of database entries that can be held in a single
207** page of the database.
208*/
209#define MX_CELL ((SQLITE_PAGE_SIZE-sizeof(PageHdr))/MIN_CELL_SIZE)
210
211/*
drh6019e162001-07-02 17:51:45 +0000212** The amount of usable space on a single page of the BTree. This is the
213** page size minus the overhead of the page header.
214*/
215#define USABLE_SPACE (SQLITE_PAGE_SIZE - sizeof(PageHdr))
216
217/*
drh8c42ca92001-06-22 19:15:00 +0000218** The maximum amount of payload (in bytes) that can be stored locally for
219** a database entry. If the entry contains more data than this, the
drh3b7511c2001-05-26 13:15:44 +0000220** extra goes onto overflow pages.
drhbd03cae2001-06-02 02:40:57 +0000221**
222** This number is chosen so that at least 4 cells will fit on every page.
drh3b7511c2001-05-26 13:15:44 +0000223*/
drh6019e162001-07-02 17:51:45 +0000224#define MX_LOCAL_PAYLOAD ((USABLE_SPACE/4-(sizeof(CellHdr)+sizeof(Pgno)))&~3)
drh3b7511c2001-05-26 13:15:44 +0000225
drh306dc212001-05-21 13:45:10 +0000226/*
227** Data on a database page is stored as a linked list of Cell structures.
drh5e2f8b92001-05-28 00:41:15 +0000228** Both the key and the data are stored in aPayload[]. The key always comes
229** first. The aPayload[] field grows as necessary to hold the key and data,
drh306dc212001-05-21 13:45:10 +0000230** up to a maximum of MX_LOCAL_PAYLOAD bytes. If the size of the key and
drh3b7511c2001-05-26 13:15:44 +0000231** data combined exceeds MX_LOCAL_PAYLOAD bytes, then Cell.ovfl is the
232** page number of the first overflow page.
233**
234** Though this structure is fixed in size, the Cell on the database
drhbd03cae2001-06-02 02:40:57 +0000235** page varies in size. Every cell has a CellHdr and at least 4 bytes
drh3b7511c2001-05-26 13:15:44 +0000236** of payload space. Additional payload bytes (up to the maximum of
237** MX_LOCAL_PAYLOAD) and the Cell.ovfl value are allocated only as
238** needed.
drh306dc212001-05-21 13:45:10 +0000239*/
drh365d68f2001-05-11 11:02:46 +0000240struct Cell {
drh5e2f8b92001-05-28 00:41:15 +0000241 CellHdr h; /* The cell header */
242 char aPayload[MX_LOCAL_PAYLOAD]; /* Key and data */
243 Pgno ovfl; /* The first overflow page */
drh365d68f2001-05-11 11:02:46 +0000244};
drh306dc212001-05-21 13:45:10 +0000245
246/*
247** Free space on a page is remembered using a linked list of the FreeBlk
248** structures. Space on a database page is allocated in increments of
drh72f82862001-05-24 21:06:34 +0000249** at least 4 bytes and is always aligned to a 4-byte boundry. The
drh8b2f49b2001-06-08 00:21:52 +0000250** linked list of FreeBlks is always kept in order by address.
drh306dc212001-05-21 13:45:10 +0000251*/
drh365d68f2001-05-11 11:02:46 +0000252struct FreeBlk {
drh72f82862001-05-24 21:06:34 +0000253 u16 iSize; /* Number of bytes in this block of free space */
drh14acc042001-06-10 19:56:58 +0000254 u16 iNext; /* Index in MemPage.u.aDisk[] of the next free block */
drh365d68f2001-05-11 11:02:46 +0000255};
drh306dc212001-05-21 13:45:10 +0000256
257/*
drh14acc042001-06-10 19:56:58 +0000258** The number of bytes of payload that will fit on a single overflow page.
drh3b7511c2001-05-26 13:15:44 +0000259*/
260#define OVERFLOW_SIZE (SQLITE_PAGE_SIZE-sizeof(Pgno))
261
262/*
drh306dc212001-05-21 13:45:10 +0000263** When the key and data for a single entry in the BTree will not fit in
drh8c42ca92001-06-22 19:15:00 +0000264** the MX_LOCAL_PAYLOAD bytes of space available on the database page,
drh8b2f49b2001-06-08 00:21:52 +0000265** then all extra bytes are written to a linked list of overflow pages.
drh306dc212001-05-21 13:45:10 +0000266** Each overflow page is an instance of the following structure.
267**
268** Unused pages in the database are also represented by instances of
drhbd03cae2001-06-02 02:40:57 +0000269** the OverflowPage structure. The PageOne.freeList field is the
drh306dc212001-05-21 13:45:10 +0000270** page number of the first page in a linked list of unused database
271** pages.
272*/
drh2af926b2001-05-15 00:39:25 +0000273struct OverflowPage {
drh14acc042001-06-10 19:56:58 +0000274 Pgno iNext;
drh5e2f8b92001-05-28 00:41:15 +0000275 char aPayload[OVERFLOW_SIZE];
drh7e3b0a02001-04-28 16:52:40 +0000276};
drh7e3b0a02001-04-28 16:52:40 +0000277
278/*
drh30e58752002-03-02 20:41:57 +0000279** The PageOne.freeList field points to a linked list of overflow pages
280** hold information about free pages. The aPayload section of each
281** overflow page contains an instance of the following structure. The
282** aFree[] array holds the page number of nFree unused pages in the disk
283** file.
284*/
285struct FreelistInfo {
286 int nFree;
287 Pgno aFree[(OVERFLOW_SIZE-sizeof(int))/sizeof(Pgno)];
288};
289
290/*
drh7e3b0a02001-04-28 16:52:40 +0000291** For every page in the database file, an instance of the following structure
drh14acc042001-06-10 19:56:58 +0000292** is stored in memory. The u.aDisk[] array contains the raw bits read from
drh6446c4d2001-12-15 14:22:18 +0000293** the disk. The rest is auxiliary information held in memory only. The
drhbd03cae2001-06-02 02:40:57 +0000294** auxiliary info is only valid for regular database pages - it is not
295** used for overflow pages and pages on the freelist.
drh306dc212001-05-21 13:45:10 +0000296**
drhbd03cae2001-06-02 02:40:57 +0000297** Of particular interest in the auxiliary info is the apCell[] entry. Each
drh14acc042001-06-10 19:56:58 +0000298** apCell[] entry is a pointer to a Cell structure in u.aDisk[]. The cells are
drh306dc212001-05-21 13:45:10 +0000299** put in this array so that they can be accessed in constant time, rather
drhbd03cae2001-06-02 02:40:57 +0000300** than in linear time which would be needed if we had to walk the linked
301** list on every access.
drh72f82862001-05-24 21:06:34 +0000302**
drh14acc042001-06-10 19:56:58 +0000303** Note that apCell[] contains enough space to hold up to two more Cells
304** than can possibly fit on one page. In the steady state, every apCell[]
305** points to memory inside u.aDisk[]. But in the middle of an insert
306** operation, some apCell[] entries may temporarily point to data space
307** outside of u.aDisk[]. This is a transient situation that is quickly
308** resolved. But while it is happening, it is possible for a database
309** page to hold as many as two more cells than it might otherwise hold.
drh18b81e52001-11-01 13:52:52 +0000310** The extra two entries in apCell[] are an allowance for this situation.
drh14acc042001-06-10 19:56:58 +0000311**
drh72f82862001-05-24 21:06:34 +0000312** The pParent field points back to the parent page. This allows us to
313** walk up the BTree from any leaf to the root. Care must be taken to
314** unref() the parent page pointer when this page is no longer referenced.
drhbd03cae2001-06-02 02:40:57 +0000315** The pageDestructor() routine handles that chore.
drh7e3b0a02001-04-28 16:52:40 +0000316*/
317struct MemPage {
drh14acc042001-06-10 19:56:58 +0000318 union {
319 char aDisk[SQLITE_PAGE_SIZE]; /* Page data stored on disk */
320 PageHdr hdr; /* Overlay page header */
321 } u;
drh428ae8c2003-01-04 16:48:09 +0000322 u8 isInit; /* True if auxiliary data is initialized */
323 u8 idxShift; /* True if apCell[] indices have changed */
324 u8 isOverfull; /* Some apCell[] points outside u.aDisk[] */
drh72f82862001-05-24 21:06:34 +0000325 MemPage *pParent; /* The parent of this page. NULL for root */
drh428ae8c2003-01-04 16:48:09 +0000326 int idxParent; /* Index in pParent->apCell[] of this node */
drh14acc042001-06-10 19:56:58 +0000327 int nFree; /* Number of free bytes in u.aDisk[] */
drh306dc212001-05-21 13:45:10 +0000328 int nCell; /* Number of entries on this page */
drh14acc042001-06-10 19:56:58 +0000329 Cell *apCell[MX_CELL+2]; /* All data entires in sorted order */
drh8c42ca92001-06-22 19:15:00 +0000330};
drh7e3b0a02001-04-28 16:52:40 +0000331
332/*
drh3b7511c2001-05-26 13:15:44 +0000333** The in-memory image of a disk page has the auxiliary information appended
334** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
335** that extra information.
336*/
337#define EXTRA_SIZE (sizeof(MemPage)-SQLITE_PAGE_SIZE)
338
339/*
drha059ad02001-04-17 20:09:11 +0000340** Everything we need to know about an open database
341*/
342struct Btree {
343 Pager *pPager; /* The page cache */
drh306dc212001-05-21 13:45:10 +0000344 BtCursor *pCursor; /* A list of all open cursors */
drhbd03cae2001-06-02 02:40:57 +0000345 PageOne *page1; /* First page of the database */
drh663fc632002-02-02 18:49:19 +0000346 u8 inTrans; /* True if a transaction is in progress */
347 u8 inCkpt; /* True if there is a checkpoint on the transaction */
drh5df72a52002-06-06 23:16:05 +0000348 u8 readOnly; /* True if the underlying file is readonly */
drh0d316a42002-08-11 20:10:47 +0000349 u8 needSwab; /* Need to byte-swapping */
drha059ad02001-04-17 20:09:11 +0000350};
351typedef Btree Bt;
352
drh365d68f2001-05-11 11:02:46 +0000353/*
354** A cursor is a pointer to a particular entry in the BTree.
355** The entry is identified by its MemPage and the index in
drh5e2f8b92001-05-28 00:41:15 +0000356** MemPage.apCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000357*/
drh72f82862001-05-24 21:06:34 +0000358struct BtCursor {
drh5e2f8b92001-05-28 00:41:15 +0000359 Btree *pBt; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000360 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drhf74b8d92002-09-01 23:20:45 +0000361 BtCursor *pShared; /* Loop of cursors with the same root page */
drh8b2f49b2001-06-08 00:21:52 +0000362 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000363 MemPage *pPage; /* Page that contains the entry */
drh8c42ca92001-06-22 19:15:00 +0000364 int idx; /* Index of the entry in pPage->apCell[] */
drhecdc7532001-09-23 02:35:53 +0000365 u8 wrFlag; /* True if writable */
drh2dcc9aa2002-12-04 13:40:25 +0000366 u8 eSkip; /* Determines if next step operation is a no-op */
drh5e2f8b92001-05-28 00:41:15 +0000367 u8 iMatch; /* compare result from last sqliteBtreeMoveto() */
drh365d68f2001-05-11 11:02:46 +0000368};
drh7e3b0a02001-04-28 16:52:40 +0000369
drha059ad02001-04-17 20:09:11 +0000370/*
drh2dcc9aa2002-12-04 13:40:25 +0000371** Legal values for BtCursor.eSkip.
372*/
373#define SKIP_NONE 0 /* Always step the cursor */
374#define SKIP_NEXT 1 /* The next sqliteBtreeNext() is a no-op */
375#define SKIP_PREV 2 /* The next sqliteBtreePrevious() is a no-op */
376#define SKIP_INVALID 3 /* Calls to Next() and Previous() are invalid */
377
378/*
drh0d316a42002-08-11 20:10:47 +0000379** Routines for byte swapping.
380*/
381u16 swab16(u16 x){
382 return ((x & 0xff)<<8) | ((x>>8)&0xff);
383}
384u32 swab32(u32 x){
385 return ((x & 0xff)<<24) | ((x & 0xff00)<<8) |
386 ((x>>8) & 0xff00) | ((x>>24)&0xff);
387}
388
389/*
drh3b7511c2001-05-26 13:15:44 +0000390** Compute the total number of bytes that a Cell needs on the main
drh5e2f8b92001-05-28 00:41:15 +0000391** database page. The number returned includes the Cell header,
392** local payload storage, and the pointer to overflow pages (if
drh8c42ca92001-06-22 19:15:00 +0000393** applicable). Additional space allocated on overflow pages
drhbd03cae2001-06-02 02:40:57 +0000394** is NOT included in the value returned from this routine.
drh3b7511c2001-05-26 13:15:44 +0000395*/
drh0d316a42002-08-11 20:10:47 +0000396static int cellSize(Btree *pBt, Cell *pCell){
397 int n = NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h);
drh3b7511c2001-05-26 13:15:44 +0000398 if( n>MX_LOCAL_PAYLOAD ){
399 n = MX_LOCAL_PAYLOAD + sizeof(Pgno);
400 }else{
401 n = ROUNDUP(n);
402 }
403 n += sizeof(CellHdr);
404 return n;
405}
406
407/*
drh72f82862001-05-24 21:06:34 +0000408** Defragment the page given. All Cells are moved to the
409** beginning of the page and all free space is collected
410** into one big FreeBlk at the end of the page.
drh365d68f2001-05-11 11:02:46 +0000411*/
drh0d316a42002-08-11 20:10:47 +0000412static void defragmentPage(Btree *pBt, MemPage *pPage){
drh14acc042001-06-10 19:56:58 +0000413 int pc, i, n;
drh2af926b2001-05-15 00:39:25 +0000414 FreeBlk *pFBlk;
415 char newPage[SQLITE_PAGE_SIZE];
416
drh6019e162001-07-02 17:51:45 +0000417 assert( sqlitepager_iswriteable(pPage) );
drh7aa128d2002-06-21 13:09:16 +0000418 assert( pPage->isInit );
drhbd03cae2001-06-02 02:40:57 +0000419 pc = sizeof(PageHdr);
drh0d316a42002-08-11 20:10:47 +0000420 pPage->u.hdr.firstCell = SWAB16(pBt, pc);
drh14acc042001-06-10 19:56:58 +0000421 memcpy(newPage, pPage->u.aDisk, pc);
drh2af926b2001-05-15 00:39:25 +0000422 for(i=0; i<pPage->nCell; i++){
drh2aa679f2001-06-25 02:11:07 +0000423 Cell *pCell = pPage->apCell[i];
drh8c42ca92001-06-22 19:15:00 +0000424
425 /* This routine should never be called on an overfull page. The
426 ** following asserts verify that constraint. */
drh7c717f72001-06-24 20:39:41 +0000427 assert( Addr(pCell) > Addr(pPage) );
428 assert( Addr(pCell) < Addr(pPage) + SQLITE_PAGE_SIZE );
drh8c42ca92001-06-22 19:15:00 +0000429
drh0d316a42002-08-11 20:10:47 +0000430 n = cellSize(pBt, pCell);
431 pCell->h.iNext = SWAB16(pBt, pc + n);
drh2af926b2001-05-15 00:39:25 +0000432 memcpy(&newPage[pc], pCell, n);
drh14acc042001-06-10 19:56:58 +0000433 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[pc];
drh2af926b2001-05-15 00:39:25 +0000434 pc += n;
435 }
drh72f82862001-05-24 21:06:34 +0000436 assert( pPage->nFree==SQLITE_PAGE_SIZE-pc );
drh14acc042001-06-10 19:56:58 +0000437 memcpy(pPage->u.aDisk, newPage, pc);
drh2aa679f2001-06-25 02:11:07 +0000438 if( pPage->nCell>0 ){
439 pPage->apCell[pPage->nCell-1]->h.iNext = 0;
440 }
drh8c42ca92001-06-22 19:15:00 +0000441 pFBlk = (FreeBlk*)&pPage->u.aDisk[pc];
drh0d316a42002-08-11 20:10:47 +0000442 pFBlk->iSize = SWAB16(pBt, SQLITE_PAGE_SIZE - pc);
drh2af926b2001-05-15 00:39:25 +0000443 pFBlk->iNext = 0;
drh0d316a42002-08-11 20:10:47 +0000444 pPage->u.hdr.firstFree = SWAB16(pBt, pc);
drh2af926b2001-05-15 00:39:25 +0000445 memset(&pFBlk[1], 0, SQLITE_PAGE_SIZE - pc - sizeof(FreeBlk));
drh365d68f2001-05-11 11:02:46 +0000446}
447
drha059ad02001-04-17 20:09:11 +0000448/*
drh8b2f49b2001-06-08 00:21:52 +0000449** Allocate nByte bytes of space on a page. nByte must be a
450** multiple of 4.
drhbd03cae2001-06-02 02:40:57 +0000451**
drh14acc042001-06-10 19:56:58 +0000452** Return the index into pPage->u.aDisk[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000453** the new allocation. Or return 0 if there is not enough free
454** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000455**
drh72f82862001-05-24 21:06:34 +0000456** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000457** nBytes of contiguous free space, then this routine automatically
458** calls defragementPage() to consolidate all free space before
459** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000460*/
drh0d316a42002-08-11 20:10:47 +0000461static int allocateSpace(Btree *pBt, MemPage *pPage, int nByte){
drh2af926b2001-05-15 00:39:25 +0000462 FreeBlk *p;
463 u16 *pIdx;
464 int start;
drh8c42ca92001-06-22 19:15:00 +0000465 int cnt = 0;
drh0d316a42002-08-11 20:10:47 +0000466 int iSize;
drh72f82862001-05-24 21:06:34 +0000467
drh6019e162001-07-02 17:51:45 +0000468 assert( sqlitepager_iswriteable(pPage) );
drh5e2f8b92001-05-28 00:41:15 +0000469 assert( nByte==ROUNDUP(nByte) );
drh7aa128d2002-06-21 13:09:16 +0000470 assert( pPage->isInit );
drh14acc042001-06-10 19:56:58 +0000471 if( pPage->nFree<nByte || pPage->isOverfull ) return 0;
472 pIdx = &pPage->u.hdr.firstFree;
drh0d316a42002-08-11 20:10:47 +0000473 p = (FreeBlk*)&pPage->u.aDisk[SWAB16(pBt, *pIdx)];
474 while( (iSize = SWAB16(pBt, p->iSize))<nByte ){
drh8c42ca92001-06-22 19:15:00 +0000475 assert( cnt++ < SQLITE_PAGE_SIZE/4 );
drh2af926b2001-05-15 00:39:25 +0000476 if( p->iNext==0 ){
drh0d316a42002-08-11 20:10:47 +0000477 defragmentPage(pBt, pPage);
drh14acc042001-06-10 19:56:58 +0000478 pIdx = &pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000479 }else{
480 pIdx = &p->iNext;
481 }
drh0d316a42002-08-11 20:10:47 +0000482 p = (FreeBlk*)&pPage->u.aDisk[SWAB16(pBt, *pIdx)];
drh2af926b2001-05-15 00:39:25 +0000483 }
drh0d316a42002-08-11 20:10:47 +0000484 if( iSize==nByte ){
485 start = SWAB16(pBt, *pIdx);
drh2af926b2001-05-15 00:39:25 +0000486 *pIdx = p->iNext;
487 }else{
drh8c42ca92001-06-22 19:15:00 +0000488 FreeBlk *pNew;
drh0d316a42002-08-11 20:10:47 +0000489 start = SWAB16(pBt, *pIdx);
drh8c42ca92001-06-22 19:15:00 +0000490 pNew = (FreeBlk*)&pPage->u.aDisk[start + nByte];
drh72f82862001-05-24 21:06:34 +0000491 pNew->iNext = p->iNext;
drh0d316a42002-08-11 20:10:47 +0000492 pNew->iSize = SWAB16(pBt, iSize - nByte);
493 *pIdx = SWAB16(pBt, start + nByte);
drh2af926b2001-05-15 00:39:25 +0000494 }
495 pPage->nFree -= nByte;
496 return start;
drh7e3b0a02001-04-28 16:52:40 +0000497}
498
499/*
drh14acc042001-06-10 19:56:58 +0000500** Return a section of the MemPage.u.aDisk[] to the freelist.
501** The first byte of the new free block is pPage->u.aDisk[start]
502** and the size of the block is "size" bytes. Size must be
503** a multiple of 4.
drh306dc212001-05-21 13:45:10 +0000504**
505** Most of the effort here is involved in coalesing adjacent
506** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000507*/
drh0d316a42002-08-11 20:10:47 +0000508static void freeSpace(Btree *pBt, MemPage *pPage, int start, int size){
drh2af926b2001-05-15 00:39:25 +0000509 int end = start + size;
510 u16 *pIdx, idx;
511 FreeBlk *pFBlk;
512 FreeBlk *pNew;
513 FreeBlk *pNext;
drh0d316a42002-08-11 20:10:47 +0000514 int iSize;
drh2af926b2001-05-15 00:39:25 +0000515
drh6019e162001-07-02 17:51:45 +0000516 assert( sqlitepager_iswriteable(pPage) );
drh2af926b2001-05-15 00:39:25 +0000517 assert( size == ROUNDUP(size) );
518 assert( start == ROUNDUP(start) );
drh7aa128d2002-06-21 13:09:16 +0000519 assert( pPage->isInit );
drh14acc042001-06-10 19:56:58 +0000520 pIdx = &pPage->u.hdr.firstFree;
drh0d316a42002-08-11 20:10:47 +0000521 idx = SWAB16(pBt, *pIdx);
drh2af926b2001-05-15 00:39:25 +0000522 while( idx!=0 && idx<start ){
drh14acc042001-06-10 19:56:58 +0000523 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +0000524 iSize = SWAB16(pBt, pFBlk->iSize);
525 if( idx + iSize == start ){
526 pFBlk->iSize = SWAB16(pBt, iSize + size);
527 if( idx + iSize + size == SWAB16(pBt, pFBlk->iNext) ){
528 pNext = (FreeBlk*)&pPage->u.aDisk[idx + iSize + size];
529 if( pBt->needSwab ){
530 pFBlk->iSize = swab16(swab16(pNext->iSize)+iSize+size);
531 }else{
532 pFBlk->iSize += pNext->iSize;
533 }
drh2af926b2001-05-15 00:39:25 +0000534 pFBlk->iNext = pNext->iNext;
535 }
536 pPage->nFree += size;
537 return;
538 }
539 pIdx = &pFBlk->iNext;
drh0d316a42002-08-11 20:10:47 +0000540 idx = SWAB16(pBt, *pIdx);
drh2af926b2001-05-15 00:39:25 +0000541 }
drh14acc042001-06-10 19:56:58 +0000542 pNew = (FreeBlk*)&pPage->u.aDisk[start];
drh2af926b2001-05-15 00:39:25 +0000543 if( idx != end ){
drh0d316a42002-08-11 20:10:47 +0000544 pNew->iSize = SWAB16(pBt, size);
545 pNew->iNext = SWAB16(pBt, idx);
drh2af926b2001-05-15 00:39:25 +0000546 }else{
drh14acc042001-06-10 19:56:58 +0000547 pNext = (FreeBlk*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +0000548 pNew->iSize = SWAB16(pBt, size + SWAB16(pBt, pNext->iSize));
drh2af926b2001-05-15 00:39:25 +0000549 pNew->iNext = pNext->iNext;
550 }
drh0d316a42002-08-11 20:10:47 +0000551 *pIdx = SWAB16(pBt, start);
drh2af926b2001-05-15 00:39:25 +0000552 pPage->nFree += size;
drh7e3b0a02001-04-28 16:52:40 +0000553}
554
555/*
556** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000557**
drhbd03cae2001-06-02 02:40:57 +0000558** The pParent parameter must be a pointer to the MemPage which
559** is the parent of the page being initialized. The root of the
drh8b2f49b2001-06-08 00:21:52 +0000560** BTree (usually page 2) has no parent and so for that page,
561** pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000562**
drh72f82862001-05-24 21:06:34 +0000563** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +0000564** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +0000565** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
566** guarantee that the page is well-formed. It only shows that
567** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000568*/
drh0d316a42002-08-11 20:10:47 +0000569static int initPage(Bt *pBt, MemPage *pPage, Pgno pgnoThis, MemPage *pParent){
drh14acc042001-06-10 19:56:58 +0000570 int idx; /* An index into pPage->u.aDisk[] */
571 Cell *pCell; /* A pointer to a Cell in pPage->u.aDisk[] */
572 FreeBlk *pFBlk; /* A pointer to a free block in pPage->u.aDisk[] */
drh5e2f8b92001-05-28 00:41:15 +0000573 int sz; /* The size of a Cell in bytes */
574 int freeSpace; /* Amount of free space on the page */
drh2af926b2001-05-15 00:39:25 +0000575
drh5e2f8b92001-05-28 00:41:15 +0000576 if( pPage->pParent ){
577 assert( pPage->pParent==pParent );
578 return SQLITE_OK;
579 }
580 if( pParent ){
581 pPage->pParent = pParent;
582 sqlitepager_ref(pParent);
583 }
584 if( pPage->isInit ) return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +0000585 pPage->isInit = 1;
drh7e3b0a02001-04-28 16:52:40 +0000586 pPage->nCell = 0;
drh6019e162001-07-02 17:51:45 +0000587 freeSpace = USABLE_SPACE;
drh0d316a42002-08-11 20:10:47 +0000588 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh7e3b0a02001-04-28 16:52:40 +0000589 while( idx!=0 ){
drh8c42ca92001-06-22 19:15:00 +0000590 if( idx>SQLITE_PAGE_SIZE-MIN_CELL_SIZE ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000591 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh8c42ca92001-06-22 19:15:00 +0000592 if( idx!=ROUNDUP(idx) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000593 pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +0000594 sz = cellSize(pBt, pCell);
drh5e2f8b92001-05-28 00:41:15 +0000595 if( idx+sz > SQLITE_PAGE_SIZE ) goto page_format_error;
596 freeSpace -= sz;
597 pPage->apCell[pPage->nCell++] = pCell;
drh0d316a42002-08-11 20:10:47 +0000598 idx = SWAB16(pBt, pCell->h.iNext);
drh2af926b2001-05-15 00:39:25 +0000599 }
600 pPage->nFree = 0;
drh0d316a42002-08-11 20:10:47 +0000601 idx = SWAB16(pBt, pPage->u.hdr.firstFree);
drh2af926b2001-05-15 00:39:25 +0000602 while( idx!=0 ){
drh0d316a42002-08-11 20:10:47 +0000603 int iNext;
drh2af926b2001-05-15 00:39:25 +0000604 if( idx>SQLITE_PAGE_SIZE-sizeof(FreeBlk) ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000605 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000606 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +0000607 pPage->nFree += SWAB16(pBt, pFBlk->iSize);
608 iNext = SWAB16(pBt, pFBlk->iNext);
609 if( iNext>0 && iNext <= idx ) goto page_format_error;
610 idx = iNext;
drh7e3b0a02001-04-28 16:52:40 +0000611 }
drh8b2f49b2001-06-08 00:21:52 +0000612 if( pPage->nCell==0 && pPage->nFree==0 ){
613 /* As a special case, an uninitialized root page appears to be
614 ** an empty database */
615 return SQLITE_OK;
616 }
drh5e2f8b92001-05-28 00:41:15 +0000617 if( pPage->nFree!=freeSpace ) goto page_format_error;
drh7e3b0a02001-04-28 16:52:40 +0000618 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +0000619
620page_format_error:
621 return SQLITE_CORRUPT;
drh7e3b0a02001-04-28 16:52:40 +0000622}
623
624/*
drh8b2f49b2001-06-08 00:21:52 +0000625** Set up a raw page so that it looks like a database page holding
626** no entries.
drhbd03cae2001-06-02 02:40:57 +0000627*/
drh0d316a42002-08-11 20:10:47 +0000628static void zeroPage(Btree *pBt, MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +0000629 PageHdr *pHdr;
630 FreeBlk *pFBlk;
drh6019e162001-07-02 17:51:45 +0000631 assert( sqlitepager_iswriteable(pPage) );
drhbd03cae2001-06-02 02:40:57 +0000632 memset(pPage, 0, SQLITE_PAGE_SIZE);
drh14acc042001-06-10 19:56:58 +0000633 pHdr = &pPage->u.hdr;
drhbd03cae2001-06-02 02:40:57 +0000634 pHdr->firstCell = 0;
drh0d316a42002-08-11 20:10:47 +0000635 pHdr->firstFree = SWAB16(pBt, sizeof(*pHdr));
drhbd03cae2001-06-02 02:40:57 +0000636 pFBlk = (FreeBlk*)&pHdr[1];
637 pFBlk->iNext = 0;
drh0d316a42002-08-11 20:10:47 +0000638 pPage->nFree = SQLITE_PAGE_SIZE - sizeof(*pHdr);
639 pFBlk->iSize = SWAB16(pBt, pPage->nFree);
drh8c42ca92001-06-22 19:15:00 +0000640 pPage->nCell = 0;
641 pPage->isOverfull = 0;
drhbd03cae2001-06-02 02:40:57 +0000642}
643
644/*
drh72f82862001-05-24 21:06:34 +0000645** This routine is called when the reference count for a page
646** reaches zero. We need to unref the pParent pointer when that
647** happens.
648*/
649static void pageDestructor(void *pData){
650 MemPage *pPage = (MemPage*)pData;
651 if( pPage->pParent ){
652 MemPage *pParent = pPage->pParent;
653 pPage->pParent = 0;
654 sqlitepager_unref(pParent);
655 }
656}
657
658/*
drh306dc212001-05-21 13:45:10 +0000659** Open a new database.
660**
661** Actually, this routine just sets up the internal data structures
drh72f82862001-05-24 21:06:34 +0000662** for accessing the database. We do not open the database file
663** until the first page is loaded.
drh382c0242001-10-06 16:33:02 +0000664**
665** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +0000666** a new database with a random name is created. This randomly named
667** database file will be deleted when sqliteBtreeClose() is called.
drha059ad02001-04-17 20:09:11 +0000668*/
drh6019e162001-07-02 17:51:45 +0000669int sqliteBtreeOpen(
670 const char *zFilename, /* Name of the file containing the BTree database */
drhda47d772002-12-02 04:25:19 +0000671 int omitJournal, /* if TRUE then do not journal this file */
drh6019e162001-07-02 17:51:45 +0000672 int nCache, /* How many pages in the page cache */
673 Btree **ppBtree /* Pointer to new Btree object written here */
674){
drha059ad02001-04-17 20:09:11 +0000675 Btree *pBt;
drh8c42ca92001-06-22 19:15:00 +0000676 int rc;
drha059ad02001-04-17 20:09:11 +0000677
678 pBt = sqliteMalloc( sizeof(*pBt) );
679 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +0000680 *ppBtree = 0;
drha059ad02001-04-17 20:09:11 +0000681 return SQLITE_NOMEM;
682 }
drh6019e162001-07-02 17:51:45 +0000683 if( nCache<10 ) nCache = 10;
drhda47d772002-12-02 04:25:19 +0000684 rc = sqlitepager_open(&pBt->pPager, zFilename, nCache, EXTRA_SIZE,
685 !omitJournal);
drha059ad02001-04-17 20:09:11 +0000686 if( rc!=SQLITE_OK ){
687 if( pBt->pPager ) sqlitepager_close(pBt->pPager);
688 sqliteFree(pBt);
689 *ppBtree = 0;
690 return rc;
691 }
drh72f82862001-05-24 21:06:34 +0000692 sqlitepager_set_destructor(pBt->pPager, pageDestructor);
drha059ad02001-04-17 20:09:11 +0000693 pBt->pCursor = 0;
694 pBt->page1 = 0;
drh5df72a52002-06-06 23:16:05 +0000695 pBt->readOnly = sqlitepager_isreadonly(pBt->pPager);
drha059ad02001-04-17 20:09:11 +0000696 *ppBtree = pBt;
697 return SQLITE_OK;
698}
699
700/*
701** Close an open database and invalidate all cursors.
702*/
703int sqliteBtreeClose(Btree *pBt){
704 while( pBt->pCursor ){
705 sqliteBtreeCloseCursor(pBt->pCursor);
706 }
707 sqlitepager_close(pBt->pPager);
708 sqliteFree(pBt);
709 return SQLITE_OK;
710}
711
712/*
drhda47d772002-12-02 04:25:19 +0000713** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +0000714**
715** The maximum number of cache pages is set to the absolute
716** value of mxPage. If mxPage is negative, the pager will
717** operate asynchronously - it will not stop to do fsync()s
718** to insure data is written to the disk surface before
719** continuing. Transactions still work if synchronous is off,
720** and the database cannot be corrupted if this program
721** crashes. But if the operating system crashes or there is
722** an abrupt power failure when synchronous is off, the database
723** could be left in an inconsistent and unrecoverable state.
724** Synchronous is on by default so database corruption is not
725** normally a worry.
drhf57b14a2001-09-14 18:54:08 +0000726*/
727int sqliteBtreeSetCacheSize(Btree *pBt, int mxPage){
728 sqlitepager_set_cachesize(pBt->pPager, mxPage);
729 return SQLITE_OK;
730}
731
732/*
drh306dc212001-05-21 13:45:10 +0000733** Get a reference to page1 of the database file. This will
734** also acquire a readlock on that file.
735**
736** SQLITE_OK is returned on success. If the file is not a
737** well-formed database file, then SQLITE_CORRUPT is returned.
738** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
739** is returned if we run out of memory. SQLITE_PROTOCOL is returned
740** if there is a locking protocol violation.
741*/
742static int lockBtree(Btree *pBt){
743 int rc;
744 if( pBt->page1 ) return SQLITE_OK;
drh8c42ca92001-06-22 19:15:00 +0000745 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pBt->page1);
drh306dc212001-05-21 13:45:10 +0000746 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +0000747
748 /* Do some checking to help insure the file we opened really is
749 ** a valid database file.
750 */
751 if( sqlitepager_pagecount(pBt->pPager)>0 ){
drhbd03cae2001-06-02 02:40:57 +0000752 PageOne *pP1 = pBt->page1;
drh0d316a42002-08-11 20:10:47 +0000753 if( strcmp(pP1->zMagic,zMagicHeader)!=0 ||
754 (pP1->iMagic!=MAGIC && swab32(pP1->iMagic)!=MAGIC) ){
drh306dc212001-05-21 13:45:10 +0000755 rc = SQLITE_CORRUPT;
drh72f82862001-05-24 21:06:34 +0000756 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +0000757 }
drh0d316a42002-08-11 20:10:47 +0000758 pBt->needSwab = pP1->iMagic!=MAGIC;
drh306dc212001-05-21 13:45:10 +0000759 }
760 return rc;
761
drh72f82862001-05-24 21:06:34 +0000762page1_init_failed:
drh306dc212001-05-21 13:45:10 +0000763 sqlitepager_unref(pBt->page1);
764 pBt->page1 = 0;
drh72f82862001-05-24 21:06:34 +0000765 return rc;
drh306dc212001-05-21 13:45:10 +0000766}
767
768/*
drhb8ca3072001-12-05 00:21:20 +0000769** If there are no outstanding cursors and we are not in the middle
770** of a transaction but there is a read lock on the database, then
771** this routine unrefs the first page of the database file which
772** has the effect of releasing the read lock.
773**
774** If there are any outstanding cursors, this routine is a no-op.
775**
776** If there is a transaction in progress, this routine is a no-op.
777*/
778static void unlockBtreeIfUnused(Btree *pBt){
779 if( pBt->inTrans==0 && pBt->pCursor==0 && pBt->page1!=0 ){
780 sqlitepager_unref(pBt->page1);
781 pBt->page1 = 0;
782 pBt->inTrans = 0;
drh663fc632002-02-02 18:49:19 +0000783 pBt->inCkpt = 0;
drhb8ca3072001-12-05 00:21:20 +0000784 }
785}
786
787/*
drh8c42ca92001-06-22 19:15:00 +0000788** Create a new database by initializing the first two pages of the
789** file.
drh8b2f49b2001-06-08 00:21:52 +0000790*/
791static int newDatabase(Btree *pBt){
792 MemPage *pRoot;
793 PageOne *pP1;
drh8c42ca92001-06-22 19:15:00 +0000794 int rc;
drh7c717f72001-06-24 20:39:41 +0000795 if( sqlitepager_pagecount(pBt->pPager)>1 ) return SQLITE_OK;
drh8b2f49b2001-06-08 00:21:52 +0000796 pP1 = pBt->page1;
797 rc = sqlitepager_write(pBt->page1);
798 if( rc ) return rc;
drh8c42ca92001-06-22 19:15:00 +0000799 rc = sqlitepager_get(pBt->pPager, 2, (void**)&pRoot);
drh8b2f49b2001-06-08 00:21:52 +0000800 if( rc ) return rc;
801 rc = sqlitepager_write(pRoot);
802 if( rc ){
803 sqlitepager_unref(pRoot);
804 return rc;
805 }
806 strcpy(pP1->zMagic, zMagicHeader);
drh0d316a42002-08-11 20:10:47 +0000807 if( btree_native_byte_order ){
808 pP1->iMagic = MAGIC;
809 pBt->needSwab = 0;
810 }else{
811 pP1->iMagic = swab32(MAGIC);
812 pBt->needSwab = 1;
813 }
drh0d316a42002-08-11 20:10:47 +0000814 zeroPage(pBt, pRoot);
drh8b2f49b2001-06-08 00:21:52 +0000815 sqlitepager_unref(pRoot);
816 return SQLITE_OK;
817}
818
819/*
drh72f82862001-05-24 21:06:34 +0000820** Attempt to start a new transaction.
drh8b2f49b2001-06-08 00:21:52 +0000821**
822** A transaction must be started before attempting any changes
823** to the database. None of the following routines will work
824** unless a transaction is started first:
825**
826** sqliteBtreeCreateTable()
drhc6b52df2002-01-04 03:09:29 +0000827** sqliteBtreeCreateIndex()
drh8b2f49b2001-06-08 00:21:52 +0000828** sqliteBtreeClearTable()
829** sqliteBtreeDropTable()
830** sqliteBtreeInsert()
831** sqliteBtreeDelete()
832** sqliteBtreeUpdateMeta()
drha059ad02001-04-17 20:09:11 +0000833*/
834int sqliteBtreeBeginTrans(Btree *pBt){
835 int rc;
836 if( pBt->inTrans ) return SQLITE_ERROR;
drhf74b8d92002-09-01 23:20:45 +0000837 if( pBt->readOnly ) return SQLITE_READONLY;
drha059ad02001-04-17 20:09:11 +0000838 if( pBt->page1==0 ){
drh7e3b0a02001-04-28 16:52:40 +0000839 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +0000840 if( rc!=SQLITE_OK ){
841 return rc;
842 }
drha059ad02001-04-17 20:09:11 +0000843 }
drhf74b8d92002-09-01 23:20:45 +0000844 rc = sqlitepager_begin(pBt->page1);
845 if( rc==SQLITE_OK ){
846 rc = newDatabase(pBt);
drha059ad02001-04-17 20:09:11 +0000847 }
drhb8ca3072001-12-05 00:21:20 +0000848 if( rc==SQLITE_OK ){
849 pBt->inTrans = 1;
drh663fc632002-02-02 18:49:19 +0000850 pBt->inCkpt = 0;
drhb8ca3072001-12-05 00:21:20 +0000851 }else{
852 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000853 }
drhb8ca3072001-12-05 00:21:20 +0000854 return rc;
drha059ad02001-04-17 20:09:11 +0000855}
856
857/*
drh2aa679f2001-06-25 02:11:07 +0000858** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +0000859**
860** This will release the write lock on the database file. If there
861** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000862*/
863int sqliteBtreeCommit(Btree *pBt){
864 int rc;
drh5df72a52002-06-06 23:16:05 +0000865 rc = pBt->readOnly ? SQLITE_OK : sqlitepager_commit(pBt->pPager);
drh7c717f72001-06-24 20:39:41 +0000866 pBt->inTrans = 0;
drh663fc632002-02-02 18:49:19 +0000867 pBt->inCkpt = 0;
drh5e00f6c2001-09-13 13:46:56 +0000868 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000869 return rc;
870}
871
872/*
drhecdc7532001-09-23 02:35:53 +0000873** Rollback the transaction in progress. All cursors will be
874** invalided by this operation. Any attempt to use a cursor
875** that was open at the beginning of this operation will result
876** in an error.
drh5e00f6c2001-09-13 13:46:56 +0000877**
878** This will release the write lock on the database file. If there
879** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000880*/
881int sqliteBtreeRollback(Btree *pBt){
882 int rc;
drhecdc7532001-09-23 02:35:53 +0000883 BtCursor *pCur;
drh7c717f72001-06-24 20:39:41 +0000884 if( pBt->inTrans==0 ) return SQLITE_OK;
885 pBt->inTrans = 0;
drh663fc632002-02-02 18:49:19 +0000886 pBt->inCkpt = 0;
drhecdc7532001-09-23 02:35:53 +0000887 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
888 if( pCur->pPage ){
889 sqlitepager_unref(pCur->pPage);
890 pCur->pPage = 0;
891 }
892 }
drh5df72a52002-06-06 23:16:05 +0000893 rc = pBt->readOnly ? SQLITE_OK : sqlitepager_rollback(pBt->pPager);
drh5e00f6c2001-09-13 13:46:56 +0000894 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000895 return rc;
896}
897
898/*
drh663fc632002-02-02 18:49:19 +0000899** Set the checkpoint for the current transaction. The checkpoint serves
900** as a sub-transaction that can be rolled back independently of the
901** main transaction. You must start a transaction before starting a
902** checkpoint. The checkpoint is ended automatically if the transaction
903** commits or rolls back.
904**
905** Only one checkpoint may be active at a time. It is an error to try
906** to start a new checkpoint if another checkpoint is already active.
907*/
908int sqliteBtreeBeginCkpt(Btree *pBt){
909 int rc;
drh0d65dc02002-02-03 00:56:09 +0000910 if( !pBt->inTrans || pBt->inCkpt ){
drhf74b8d92002-09-01 23:20:45 +0000911 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh0d65dc02002-02-03 00:56:09 +0000912 }
drh5df72a52002-06-06 23:16:05 +0000913 rc = pBt->readOnly ? SQLITE_OK : sqlitepager_ckpt_begin(pBt->pPager);
drh663fc632002-02-02 18:49:19 +0000914 pBt->inCkpt = 1;
915 return rc;
916}
917
918
919/*
920** Commit a checkpoint to transaction currently in progress. If no
921** checkpoint is active, this is a no-op.
922*/
923int sqliteBtreeCommitCkpt(Btree *pBt){
924 int rc;
drh5df72a52002-06-06 23:16:05 +0000925 if( pBt->inCkpt && !pBt->readOnly ){
drh663fc632002-02-02 18:49:19 +0000926 rc = sqlitepager_ckpt_commit(pBt->pPager);
927 }else{
928 rc = SQLITE_OK;
929 }
drh0d65dc02002-02-03 00:56:09 +0000930 pBt->inCkpt = 0;
drh663fc632002-02-02 18:49:19 +0000931 return rc;
932}
933
934/*
935** Rollback the checkpoint to the current transaction. If there
936** is no active checkpoint or transaction, this routine is a no-op.
937**
938** All cursors will be invalided by this operation. Any attempt
939** to use a cursor that was open at the beginning of this operation
940** will result in an error.
941*/
942int sqliteBtreeRollbackCkpt(Btree *pBt){
943 int rc;
944 BtCursor *pCur;
drh5df72a52002-06-06 23:16:05 +0000945 if( pBt->inCkpt==0 || pBt->readOnly ) return SQLITE_OK;
drh663fc632002-02-02 18:49:19 +0000946 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
947 if( pCur->pPage ){
948 sqlitepager_unref(pCur->pPage);
949 pCur->pPage = 0;
950 }
951 }
952 rc = sqlitepager_ckpt_rollback(pBt->pPager);
drh0d65dc02002-02-03 00:56:09 +0000953 pBt->inCkpt = 0;
drh663fc632002-02-02 18:49:19 +0000954 return rc;
955}
956
957/*
drh8b2f49b2001-06-08 00:21:52 +0000958** Create a new cursor for the BTree whose root is on the page
959** iTable. The act of acquiring a cursor gets a read lock on
960** the database file.
drh1bee3d72001-10-15 00:44:35 +0000961**
962** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +0000963** If wrFlag==1, then the cursor can be used for reading or for
964** writing if other conditions for writing are also met. These
965** are the conditions that must be met in order for writing to
966** be allowed:
drh6446c4d2001-12-15 14:22:18 +0000967**
drhf74b8d92002-09-01 23:20:45 +0000968** 1: The cursor must have been opened with wrFlag==1
969**
970** 2: No other cursors may be open with wrFlag==0 on the same table
971**
972** 3: The database must be writable (not on read-only media)
973**
974** 4: There must be an active transaction.
975**
976** Condition 2 warrants further discussion. If any cursor is opened
977** on a table with wrFlag==0, that prevents all other cursors from
978** writing to that table. This is a kind of "read-lock". When a cursor
979** is opened with wrFlag==0 it is guaranteed that the table will not
980** change as long as the cursor is open. This allows the cursor to
981** do a sequential scan of the table without having to worry about
982** entries being inserted or deleted during the scan. Cursors should
983** be opened with wrFlag==0 only if this read-lock property is needed.
984** That is to say, cursors should be opened with wrFlag==0 only if they
985** intend to use the sqliteBtreeNext() system call. All other cursors
986** should be opened with wrFlag==1 even if they never really intend
987** to write.
988**
drh6446c4d2001-12-15 14:22:18 +0000989** No checking is done to make sure that page iTable really is the
990** root page of a b-tree. If it is not, then the cursor acquired
991** will not work correctly.
drha059ad02001-04-17 20:09:11 +0000992*/
drhecdc7532001-09-23 02:35:53 +0000993int sqliteBtreeCursor(Btree *pBt, int iTable, int wrFlag, BtCursor **ppCur){
drha059ad02001-04-17 20:09:11 +0000994 int rc;
drhf74b8d92002-09-01 23:20:45 +0000995 BtCursor *pCur, *pRing;
drhecdc7532001-09-23 02:35:53 +0000996
drha059ad02001-04-17 20:09:11 +0000997 if( pBt->page1==0 ){
998 rc = lockBtree(pBt);
999 if( rc!=SQLITE_OK ){
1000 *ppCur = 0;
1001 return rc;
1002 }
1003 }
1004 pCur = sqliteMalloc( sizeof(*pCur) );
1005 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +00001006 rc = SQLITE_NOMEM;
1007 goto create_cursor_exception;
1008 }
drh8b2f49b2001-06-08 00:21:52 +00001009 pCur->pgnoRoot = (Pgno)iTable;
drh8c42ca92001-06-22 19:15:00 +00001010 rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +00001011 if( rc!=SQLITE_OK ){
1012 goto create_cursor_exception;
1013 }
drh0d316a42002-08-11 20:10:47 +00001014 rc = initPage(pBt, pCur->pPage, pCur->pgnoRoot, 0);
drhbd03cae2001-06-02 02:40:57 +00001015 if( rc!=SQLITE_OK ){
1016 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00001017 }
drh14acc042001-06-10 19:56:58 +00001018 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +00001019 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +00001020 pCur->idx = 0;
drh2dcc9aa2002-12-04 13:40:25 +00001021 pCur->eSkip = SKIP_INVALID;
drha059ad02001-04-17 20:09:11 +00001022 pCur->pNext = pBt->pCursor;
1023 if( pCur->pNext ){
1024 pCur->pNext->pPrev = pCur;
1025 }
drh14acc042001-06-10 19:56:58 +00001026 pCur->pPrev = 0;
drhf74b8d92002-09-01 23:20:45 +00001027 pRing = pBt->pCursor;
1028 while( pRing && pRing->pgnoRoot!=pCur->pgnoRoot ){ pRing = pRing->pNext; }
1029 if( pRing ){
1030 pCur->pShared = pRing->pShared;
1031 pRing->pShared = pCur;
1032 }else{
1033 pCur->pShared = pCur;
1034 }
drha059ad02001-04-17 20:09:11 +00001035 pBt->pCursor = pCur;
drh2af926b2001-05-15 00:39:25 +00001036 *ppCur = pCur;
1037 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00001038
1039create_cursor_exception:
1040 *ppCur = 0;
1041 if( pCur ){
1042 if( pCur->pPage ) sqlitepager_unref(pCur->pPage);
1043 sqliteFree(pCur);
1044 }
drh5e00f6c2001-09-13 13:46:56 +00001045 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00001046 return rc;
drha059ad02001-04-17 20:09:11 +00001047}
1048
1049/*
drh5e00f6c2001-09-13 13:46:56 +00001050** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00001051** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00001052*/
1053int sqliteBtreeCloseCursor(BtCursor *pCur){
1054 Btree *pBt = pCur->pBt;
drha059ad02001-04-17 20:09:11 +00001055 if( pCur->pPrev ){
1056 pCur->pPrev->pNext = pCur->pNext;
1057 }else{
1058 pBt->pCursor = pCur->pNext;
1059 }
1060 if( pCur->pNext ){
1061 pCur->pNext->pPrev = pCur->pPrev;
1062 }
drhecdc7532001-09-23 02:35:53 +00001063 if( pCur->pPage ){
1064 sqlitepager_unref(pCur->pPage);
1065 }
drhf74b8d92002-09-01 23:20:45 +00001066 if( pCur->pShared!=pCur ){
1067 BtCursor *pRing = pCur->pShared;
1068 while( pRing->pShared!=pCur ){ pRing = pRing->pShared; }
1069 pRing->pShared = pCur->pShared;
1070 }
drh5e00f6c2001-09-13 13:46:56 +00001071 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001072 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +00001073 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00001074}
1075
drh7e3b0a02001-04-28 16:52:40 +00001076/*
drh5e2f8b92001-05-28 00:41:15 +00001077** Make a temporary cursor by filling in the fields of pTempCur.
1078** The temporary cursor is not on the cursor list for the Btree.
1079*/
drh14acc042001-06-10 19:56:58 +00001080static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00001081 memcpy(pTempCur, pCur, sizeof(*pCur));
1082 pTempCur->pNext = 0;
1083 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00001084 if( pTempCur->pPage ){
1085 sqlitepager_ref(pTempCur->pPage);
1086 }
drh5e2f8b92001-05-28 00:41:15 +00001087}
1088
1089/*
drhbd03cae2001-06-02 02:40:57 +00001090** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00001091** function above.
1092*/
drh14acc042001-06-10 19:56:58 +00001093static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00001094 if( pCur->pPage ){
1095 sqlitepager_unref(pCur->pPage);
1096 }
drh5e2f8b92001-05-28 00:41:15 +00001097}
1098
1099/*
drhbd03cae2001-06-02 02:40:57 +00001100** Set *pSize to the number of bytes of key in the entry the
1101** cursor currently points to. Always return SQLITE_OK.
1102** Failure is not possible. If the cursor is not currently
1103** pointing to an entry (which can happen, for example, if
1104** the database is empty) then *pSize is set to 0.
drh7e3b0a02001-04-28 16:52:40 +00001105*/
drh72f82862001-05-24 21:06:34 +00001106int sqliteBtreeKeySize(BtCursor *pCur, int *pSize){
drh2af926b2001-05-15 00:39:25 +00001107 Cell *pCell;
1108 MemPage *pPage;
1109
1110 pPage = pCur->pPage;
drh8c1238a2003-01-02 14:43:55 +00001111 assert( pPage!=0 );
1112 if( pCur->idx >= pPage->nCell ){
drh72f82862001-05-24 21:06:34 +00001113 *pSize = 0;
1114 }else{
drh5e2f8b92001-05-28 00:41:15 +00001115 pCell = pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00001116 *pSize = NKEY(pCur->pBt, pCell->h);
drh72f82862001-05-24 21:06:34 +00001117 }
1118 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00001119}
drh2af926b2001-05-15 00:39:25 +00001120
drh72f82862001-05-24 21:06:34 +00001121/*
1122** Read payload information from the entry that the pCur cursor is
1123** pointing to. Begin reading the payload at "offset" and read
1124** a total of "amt" bytes. Put the result in zBuf.
1125**
1126** This routine does not make a distinction between key and data.
1127** It just reads bytes from the payload area.
1128*/
drh2af926b2001-05-15 00:39:25 +00001129static int getPayload(BtCursor *pCur, int offset, int amt, char *zBuf){
drh5e2f8b92001-05-28 00:41:15 +00001130 char *aPayload;
drh2af926b2001-05-15 00:39:25 +00001131 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +00001132 int rc;
drh0d316a42002-08-11 20:10:47 +00001133 Btree *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00001134 assert( pCur!=0 && pCur->pPage!=0 );
drh8c42ca92001-06-22 19:15:00 +00001135 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
1136 aPayload = pCur->pPage->apCell[pCur->idx]->aPayload;
drh2af926b2001-05-15 00:39:25 +00001137 if( offset<MX_LOCAL_PAYLOAD ){
1138 int a = amt;
1139 if( a+offset>MX_LOCAL_PAYLOAD ){
1140 a = MX_LOCAL_PAYLOAD - offset;
1141 }
drh5e2f8b92001-05-28 00:41:15 +00001142 memcpy(zBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +00001143 if( a==amt ){
1144 return SQLITE_OK;
1145 }
drh2aa679f2001-06-25 02:11:07 +00001146 offset = 0;
drh2af926b2001-05-15 00:39:25 +00001147 zBuf += a;
1148 amt -= a;
drhdd793422001-06-28 01:54:48 +00001149 }else{
1150 offset -= MX_LOCAL_PAYLOAD;
drhbd03cae2001-06-02 02:40:57 +00001151 }
1152 if( amt>0 ){
drh0d316a42002-08-11 20:10:47 +00001153 nextPage = SWAB32(pBt, pCur->pPage->apCell[pCur->idx]->ovfl);
drh2af926b2001-05-15 00:39:25 +00001154 }
1155 while( amt>0 && nextPage ){
1156 OverflowPage *pOvfl;
drh0d316a42002-08-11 20:10:47 +00001157 rc = sqlitepager_get(pBt->pPager, nextPage, (void**)&pOvfl);
drh2af926b2001-05-15 00:39:25 +00001158 if( rc!=0 ){
1159 return rc;
1160 }
drh0d316a42002-08-11 20:10:47 +00001161 nextPage = SWAB32(pBt, pOvfl->iNext);
drh2af926b2001-05-15 00:39:25 +00001162 if( offset<OVERFLOW_SIZE ){
1163 int a = amt;
1164 if( a + offset > OVERFLOW_SIZE ){
1165 a = OVERFLOW_SIZE - offset;
1166 }
drh5e2f8b92001-05-28 00:41:15 +00001167 memcpy(zBuf, &pOvfl->aPayload[offset], a);
drh2aa679f2001-06-25 02:11:07 +00001168 offset = 0;
drh2af926b2001-05-15 00:39:25 +00001169 amt -= a;
1170 zBuf += a;
drh2aa679f2001-06-25 02:11:07 +00001171 }else{
1172 offset -= OVERFLOW_SIZE;
drh2af926b2001-05-15 00:39:25 +00001173 }
1174 sqlitepager_unref(pOvfl);
1175 }
drha7fcb052001-12-14 15:09:55 +00001176 if( amt>0 ){
1177 return SQLITE_CORRUPT;
1178 }
1179 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00001180}
1181
drh72f82862001-05-24 21:06:34 +00001182/*
drh5e00f6c2001-09-13 13:46:56 +00001183** Read part of the key associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +00001184** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +00001185** begins at "offset". The number of bytes actually read is
drh8c1238a2003-01-02 14:43:55 +00001186** returned.
1187**
1188** Change: It used to be that the amount returned will be smaller
1189** than the amount requested if there are not enough bytes in the key
1190** to satisfy the request. But now, it must be the case that there
1191** is enough data available to satisfy the request. If not, an exception
1192** is raised. The change was made in an effort to boost performance
1193** by eliminating unneeded tests.
drh72f82862001-05-24 21:06:34 +00001194*/
1195int sqliteBtreeKey(BtCursor *pCur, int offset, int amt, char *zBuf){
drh72f82862001-05-24 21:06:34 +00001196 MemPage *pPage;
drha059ad02001-04-17 20:09:11 +00001197
drh8c1238a2003-01-02 14:43:55 +00001198 assert( amt>=0 );
1199 assert( offset>=0 );
1200 assert( pCur->pPage!=0 );
drh72f82862001-05-24 21:06:34 +00001201 pPage = pCur->pPage;
drh72f82862001-05-24 21:06:34 +00001202 if( pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +00001203 return 0;
drh72f82862001-05-24 21:06:34 +00001204 }
drh8c1238a2003-01-02 14:43:55 +00001205 assert( amt+offset <= NKEY(pCur->pBt, pPage->apCell[pCur->idx]->h) );
drh5e00f6c2001-09-13 13:46:56 +00001206 getPayload(pCur, offset, amt, zBuf);
1207 return amt;
drh72f82862001-05-24 21:06:34 +00001208}
1209
1210/*
drhbd03cae2001-06-02 02:40:57 +00001211** Set *pSize to the number of bytes of data in the entry the
1212** cursor currently points to. Always return SQLITE_OK.
1213** Failure is not possible. If the cursor is not currently
1214** pointing to an entry (which can happen, for example, if
1215** the database is empty) then *pSize is set to 0.
drh72f82862001-05-24 21:06:34 +00001216*/
1217int sqliteBtreeDataSize(BtCursor *pCur, int *pSize){
1218 Cell *pCell;
1219 MemPage *pPage;
1220
1221 pPage = pCur->pPage;
drh8c1238a2003-01-02 14:43:55 +00001222 assert( pPage!=0 );
1223 if( pCur->idx >= pPage->nCell ){
drh72f82862001-05-24 21:06:34 +00001224 *pSize = 0;
1225 }else{
drh5e2f8b92001-05-28 00:41:15 +00001226 pCell = pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00001227 *pSize = NDATA(pCur->pBt, pCell->h);
drh72f82862001-05-24 21:06:34 +00001228 }
1229 return SQLITE_OK;
1230}
1231
1232/*
drh5e00f6c2001-09-13 13:46:56 +00001233** Read part of the data associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +00001234** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +00001235** begins at "offset". The number of bytes actually read is
1236** returned. The amount returned will be smaller than the
1237** amount requested if there are not enough bytes in the data
1238** to satisfy the request.
drh72f82862001-05-24 21:06:34 +00001239*/
1240int sqliteBtreeData(BtCursor *pCur, int offset, int amt, char *zBuf){
1241 Cell *pCell;
1242 MemPage *pPage;
1243
drh8c1238a2003-01-02 14:43:55 +00001244 assert( amt>=0 );
1245 assert( offset>=0 );
1246 assert( pCur->pPage!=0 );
drh72f82862001-05-24 21:06:34 +00001247 pPage = pCur->pPage;
drh8c1238a2003-01-02 14:43:55 +00001248 if( pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +00001249 return 0;
drh72f82862001-05-24 21:06:34 +00001250 }
drh5e2f8b92001-05-28 00:41:15 +00001251 pCell = pPage->apCell[pCur->idx];
drh8c1238a2003-01-02 14:43:55 +00001252 assert( amt+offset <= NDATA(pCur->pBt, pCell->h) );
drh0d316a42002-08-11 20:10:47 +00001253 getPayload(pCur, offset + NKEY(pCur->pBt, pCell->h), amt, zBuf);
drh5e00f6c2001-09-13 13:46:56 +00001254 return amt;
drh72f82862001-05-24 21:06:34 +00001255}
drha059ad02001-04-17 20:09:11 +00001256
drh2af926b2001-05-15 00:39:25 +00001257/*
drh8721ce42001-11-07 14:22:00 +00001258** Compare an external key against the key on the entry that pCur points to.
1259**
1260** The external key is pKey and is nKey bytes long. The last nIgnore bytes
1261** of the key associated with pCur are ignored, as if they do not exist.
1262** (The normal case is for nIgnore to be zero in which case the entire
1263** internal key is used in the comparison.)
1264**
1265** The comparison result is written to *pRes as follows:
drh2af926b2001-05-15 00:39:25 +00001266**
drh717e6402001-09-27 03:22:32 +00001267** *pRes<0 This means pCur<pKey
1268**
1269** *pRes==0 This means pCur==pKey for all nKey bytes
1270**
1271** *pRes>0 This means pCur>pKey
1272**
drh8721ce42001-11-07 14:22:00 +00001273** When one key is an exact prefix of the other, the shorter key is
1274** considered less than the longer one. In order to be equal the
1275** keys must be exactly the same length. (The length of the pCur key
1276** is the actual key length minus nIgnore bytes.)
drh2af926b2001-05-15 00:39:25 +00001277*/
drh717e6402001-09-27 03:22:32 +00001278int sqliteBtreeKeyCompare(
drh8721ce42001-11-07 14:22:00 +00001279 BtCursor *pCur, /* Pointer to entry to compare against */
1280 const void *pKey, /* Key to compare against entry that pCur points to */
1281 int nKey, /* Number of bytes in pKey */
1282 int nIgnore, /* Ignore this many bytes at the end of pCur */
1283 int *pResult /* Write the result here */
drh5c4d9702001-08-20 00:33:58 +00001284){
drh2af926b2001-05-15 00:39:25 +00001285 Pgno nextPage;
drh8721ce42001-11-07 14:22:00 +00001286 int n, c, rc, nLocal;
drh2af926b2001-05-15 00:39:25 +00001287 Cell *pCell;
drh0d316a42002-08-11 20:10:47 +00001288 Btree *pBt = pCur->pBt;
drh717e6402001-09-27 03:22:32 +00001289 const char *zKey = (const char*)pKey;
drh2af926b2001-05-15 00:39:25 +00001290
1291 assert( pCur->pPage );
1292 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drhbd03cae2001-06-02 02:40:57 +00001293 pCell = pCur->pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00001294 nLocal = NKEY(pBt, pCell->h) - nIgnore;
drh8721ce42001-11-07 14:22:00 +00001295 if( nLocal<0 ) nLocal = 0;
1296 n = nKey<nLocal ? nKey : nLocal;
drh2af926b2001-05-15 00:39:25 +00001297 if( n>MX_LOCAL_PAYLOAD ){
1298 n = MX_LOCAL_PAYLOAD;
1299 }
drh717e6402001-09-27 03:22:32 +00001300 c = memcmp(pCell->aPayload, zKey, n);
drh2af926b2001-05-15 00:39:25 +00001301 if( c!=0 ){
1302 *pResult = c;
1303 return SQLITE_OK;
1304 }
drh717e6402001-09-27 03:22:32 +00001305 zKey += n;
drh2af926b2001-05-15 00:39:25 +00001306 nKey -= n;
drh8721ce42001-11-07 14:22:00 +00001307 nLocal -= n;
drh0d316a42002-08-11 20:10:47 +00001308 nextPage = SWAB32(pBt, pCell->ovfl);
drh8721ce42001-11-07 14:22:00 +00001309 while( nKey>0 && nLocal>0 ){
drh2af926b2001-05-15 00:39:25 +00001310 OverflowPage *pOvfl;
1311 if( nextPage==0 ){
1312 return SQLITE_CORRUPT;
1313 }
drh0d316a42002-08-11 20:10:47 +00001314 rc = sqlitepager_get(pBt->pPager, nextPage, (void**)&pOvfl);
drh72f82862001-05-24 21:06:34 +00001315 if( rc ){
drh2af926b2001-05-15 00:39:25 +00001316 return rc;
1317 }
drh0d316a42002-08-11 20:10:47 +00001318 nextPage = SWAB32(pBt, pOvfl->iNext);
drh8721ce42001-11-07 14:22:00 +00001319 n = nKey<nLocal ? nKey : nLocal;
drh2af926b2001-05-15 00:39:25 +00001320 if( n>OVERFLOW_SIZE ){
1321 n = OVERFLOW_SIZE;
1322 }
drh717e6402001-09-27 03:22:32 +00001323 c = memcmp(pOvfl->aPayload, zKey, n);
drh2af926b2001-05-15 00:39:25 +00001324 sqlitepager_unref(pOvfl);
1325 if( c!=0 ){
1326 *pResult = c;
1327 return SQLITE_OK;
1328 }
1329 nKey -= n;
drh8721ce42001-11-07 14:22:00 +00001330 nLocal -= n;
drh717e6402001-09-27 03:22:32 +00001331 zKey += n;
drh2af926b2001-05-15 00:39:25 +00001332 }
drh717e6402001-09-27 03:22:32 +00001333 if( c==0 ){
drh8721ce42001-11-07 14:22:00 +00001334 c = nLocal - nKey;
drh717e6402001-09-27 03:22:32 +00001335 }
drh2af926b2001-05-15 00:39:25 +00001336 *pResult = c;
1337 return SQLITE_OK;
1338}
1339
drh72f82862001-05-24 21:06:34 +00001340/*
1341** Move the cursor down to a new child page.
1342*/
drh5e2f8b92001-05-28 00:41:15 +00001343static int moveToChild(BtCursor *pCur, int newPgno){
drh72f82862001-05-24 21:06:34 +00001344 int rc;
1345 MemPage *pNewPage;
drh0d316a42002-08-11 20:10:47 +00001346 Btree *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00001347
drh0d316a42002-08-11 20:10:47 +00001348 rc = sqlitepager_get(pBt->pPager, newPgno, (void**)&pNewPage);
drh6019e162001-07-02 17:51:45 +00001349 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001350 rc = initPage(pBt, pNewPage, newPgno, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00001351 if( rc ) return rc;
drh428ae8c2003-01-04 16:48:09 +00001352 assert( pCur->idx>=pCur->pPage->nCell
1353 || pCur->pPage->apCell[pCur->idx]->h.leftChild==SWAB32(pBt,newPgno) );
1354 assert( pCur->idx<pCur->pPage->nCell
1355 || pCur->pPage->u.hdr.rightChild==SWAB32(pBt,newPgno) );
1356 pNewPage->idxParent = pCur->idx;
1357 pCur->pPage->idxShift = 0;
drh72f82862001-05-24 21:06:34 +00001358 sqlitepager_unref(pCur->pPage);
1359 pCur->pPage = pNewPage;
1360 pCur->idx = 0;
1361 return SQLITE_OK;
1362}
1363
1364/*
drh5e2f8b92001-05-28 00:41:15 +00001365** Move the cursor up to the parent page.
1366**
1367** pCur->idx is set to the cell index that contains the pointer
1368** to the page we are coming from. If we are coming from the
1369** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00001370** the largest cell index.
drh72f82862001-05-24 21:06:34 +00001371*/
drh5e2f8b92001-05-28 00:41:15 +00001372static int moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001373 Pgno oldPgno;
1374 MemPage *pParent;
drh428ae8c2003-01-04 16:48:09 +00001375 int idxParent;
drh72f82862001-05-24 21:06:34 +00001376 pParent = pCur->pPage->pParent;
drhbd03cae2001-06-02 02:40:57 +00001377 if( pParent==0 ) return SQLITE_INTERNAL;
drh428ae8c2003-01-04 16:48:09 +00001378 idxParent = pCur->pPage->idxParent;
drh72f82862001-05-24 21:06:34 +00001379 oldPgno = sqlitepager_pagenumber(pCur->pPage);
drh72f82862001-05-24 21:06:34 +00001380 sqlitepager_ref(pParent);
1381 sqlitepager_unref(pCur->pPage);
1382 pCur->pPage = pParent;
drh428ae8c2003-01-04 16:48:09 +00001383 assert( pParent->idxShift==0 );
1384 if( pParent->idxShift==0 ){
1385 pCur->idx = idxParent;
1386#ifndef NDEBUG
1387 /* Verify that pCur->idx is the correct index to point back to the child
1388 ** page we just came from
1389 */
1390 oldPgno = SWAB32(pCur->pBt, oldPgno);
1391 if( pCur->idx<pParent->nCell ){
1392 assert( pParent->apCell[idxParent]->h.leftChild==oldPgno );
1393 }else{
1394 assert( pParent->u.hdr.rightChild==oldPgno );
1395 }
1396#endif
1397 }else{
1398 /* The MemPage.idxShift flag indicates that cell indices might have
1399 ** changed since idxParent was set and hence idxParent might be out
1400 ** of date. So recompute the parent cell index by scanning all cells
1401 ** and locating the one that points to the child we just came from.
1402 */
1403 int i;
1404 pCur->idx = pParent->nCell;
1405 oldPgno = SWAB32(pCur->pBt, oldPgno);
1406 for(i=0; i<pParent->nCell; i++){
1407 if( pParent->apCell[i]->h.leftChild==oldPgno ){
1408 pCur->idx = i;
1409 break;
1410 }
drh72f82862001-05-24 21:06:34 +00001411 }
1412 }
drh5e2f8b92001-05-28 00:41:15 +00001413 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00001414}
1415
1416/*
1417** Move the cursor to the root page
1418*/
drh5e2f8b92001-05-28 00:41:15 +00001419static int moveToRoot(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001420 MemPage *pNew;
drhbd03cae2001-06-02 02:40:57 +00001421 int rc;
drh0d316a42002-08-11 20:10:47 +00001422 Btree *pBt = pCur->pBt;
drhbd03cae2001-06-02 02:40:57 +00001423
drh0d316a42002-08-11 20:10:47 +00001424 rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pNew);
drhbd03cae2001-06-02 02:40:57 +00001425 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001426 rc = initPage(pBt, pNew, pCur->pgnoRoot, 0);
drh6019e162001-07-02 17:51:45 +00001427 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001428 sqlitepager_unref(pCur->pPage);
1429 pCur->pPage = pNew;
1430 pCur->idx = 0;
1431 return SQLITE_OK;
1432}
drh2af926b2001-05-15 00:39:25 +00001433
drh5e2f8b92001-05-28 00:41:15 +00001434/*
1435** Move the cursor down to the left-most leaf entry beneath the
1436** entry to which it is currently pointing.
1437*/
1438static int moveToLeftmost(BtCursor *pCur){
1439 Pgno pgno;
1440 int rc;
1441
1442 while( (pgno = pCur->pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
drh0d316a42002-08-11 20:10:47 +00001443 rc = moveToChild(pCur, SWAB32(pCur->pBt, pgno));
drh5e2f8b92001-05-28 00:41:15 +00001444 if( rc ) return rc;
1445 }
1446 return SQLITE_OK;
1447}
1448
drh2dcc9aa2002-12-04 13:40:25 +00001449/*
1450** Move the cursor down to the right-most leaf entry beneath the
1451** page to which it is currently pointing. Notice the difference
1452** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
1453** finds the left-most entry beneath the *entry* whereas moveToRightmost()
1454** finds the right-most entry beneath the *page*.
1455*/
1456static int moveToRightmost(BtCursor *pCur){
1457 Pgno pgno;
1458 int rc;
1459
1460 while( (pgno = pCur->pPage->u.hdr.rightChild)!=0 ){
drh428ae8c2003-01-04 16:48:09 +00001461 pCur->idx = pCur->pPage->nCell;
drh2dcc9aa2002-12-04 13:40:25 +00001462 rc = moveToChild(pCur, SWAB32(pCur->pBt, pgno));
1463 if( rc ) return rc;
1464 }
1465 pCur->idx = pCur->pPage->nCell - 1;
1466 return SQLITE_OK;
1467}
1468
drh5e00f6c2001-09-13 13:46:56 +00001469/* Move the cursor to the first entry in the table. Return SQLITE_OK
1470** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00001471** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00001472*/
1473int sqliteBtreeFirst(BtCursor *pCur, int *pRes){
1474 int rc;
drhecdc7532001-09-23 02:35:53 +00001475 if( pCur->pPage==0 ) return SQLITE_ABORT;
drh5e00f6c2001-09-13 13:46:56 +00001476 rc = moveToRoot(pCur);
1477 if( rc ) return rc;
1478 if( pCur->pPage->nCell==0 ){
1479 *pRes = 1;
1480 return SQLITE_OK;
1481 }
1482 *pRes = 0;
1483 rc = moveToLeftmost(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00001484 pCur->eSkip = SKIP_NONE;
drh5e00f6c2001-09-13 13:46:56 +00001485 return rc;
1486}
drh5e2f8b92001-05-28 00:41:15 +00001487
drh9562b552002-02-19 15:00:07 +00001488/* Move the cursor to the last entry in the table. Return SQLITE_OK
1489** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00001490** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00001491*/
1492int sqliteBtreeLast(BtCursor *pCur, int *pRes){
1493 int rc;
drh9562b552002-02-19 15:00:07 +00001494 if( pCur->pPage==0 ) return SQLITE_ABORT;
1495 rc = moveToRoot(pCur);
1496 if( rc ) return rc;
drh7aa128d2002-06-21 13:09:16 +00001497 assert( pCur->pPage->isInit );
drh9562b552002-02-19 15:00:07 +00001498 if( pCur->pPage->nCell==0 ){
1499 *pRes = 1;
1500 return SQLITE_OK;
1501 }
1502 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00001503 rc = moveToRightmost(pCur);
1504 pCur->eSkip = SKIP_NONE;
drh9562b552002-02-19 15:00:07 +00001505 return rc;
1506}
1507
drha059ad02001-04-17 20:09:11 +00001508/* Move the cursor so that it points to an entry near pKey.
drh72f82862001-05-24 21:06:34 +00001509** Return a success code.
1510**
drh5e2f8b92001-05-28 00:41:15 +00001511** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00001512** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00001513** were present. The cursor might point to an entry that comes
1514** before or after the key.
1515**
drhbd03cae2001-06-02 02:40:57 +00001516** The result of comparing the key with the entry to which the
1517** cursor is left pointing is stored in pCur->iMatch. The same
1518** value is also written to *pRes if pRes!=NULL. The meaning of
1519** this value is as follows:
1520**
1521** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00001522** is smaller than pKey or if the table is empty
1523** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00001524**
1525** *pRes==0 The cursor is left pointing at an entry that
1526** exactly matches pKey.
1527**
1528** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001529** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00001530*/
drh5c4d9702001-08-20 00:33:58 +00001531int sqliteBtreeMoveto(BtCursor *pCur, const void *pKey, int nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00001532 int rc;
drhecdc7532001-09-23 02:35:53 +00001533 if( pCur->pPage==0 ) return SQLITE_ABORT;
drh2dcc9aa2002-12-04 13:40:25 +00001534 pCur->eSkip = SKIP_NONE;
drh5e2f8b92001-05-28 00:41:15 +00001535 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00001536 if( rc ) return rc;
1537 for(;;){
1538 int lwr, upr;
1539 Pgno chldPg;
1540 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00001541 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00001542 lwr = 0;
1543 upr = pPage->nCell-1;
1544 while( lwr<=upr ){
drh72f82862001-05-24 21:06:34 +00001545 pCur->idx = (lwr+upr)/2;
drh8721ce42001-11-07 14:22:00 +00001546 rc = sqliteBtreeKeyCompare(pCur, pKey, nKey, 0, &c);
drh72f82862001-05-24 21:06:34 +00001547 if( rc ) return rc;
1548 if( c==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001549 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001550 if( pRes ) *pRes = 0;
1551 return SQLITE_OK;
1552 }
1553 if( c<0 ){
1554 lwr = pCur->idx+1;
1555 }else{
1556 upr = pCur->idx-1;
1557 }
1558 }
1559 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00001560 assert( pPage->isInit );
drh72f82862001-05-24 21:06:34 +00001561 if( lwr>=pPage->nCell ){
drh14acc042001-06-10 19:56:58 +00001562 chldPg = pPage->u.hdr.rightChild;
drh72f82862001-05-24 21:06:34 +00001563 }else{
drh5e2f8b92001-05-28 00:41:15 +00001564 chldPg = pPage->apCell[lwr]->h.leftChild;
drh72f82862001-05-24 21:06:34 +00001565 }
1566 if( chldPg==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001567 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001568 if( pRes ) *pRes = c;
1569 return SQLITE_OK;
1570 }
drh428ae8c2003-01-04 16:48:09 +00001571 pCur->idx = lwr;
drh0d316a42002-08-11 20:10:47 +00001572 rc = moveToChild(pCur, SWAB32(pCur->pBt, chldPg));
drh72f82862001-05-24 21:06:34 +00001573 if( rc ) return rc;
1574 }
drhbd03cae2001-06-02 02:40:57 +00001575 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00001576}
1577
1578/*
drhbd03cae2001-06-02 02:40:57 +00001579** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00001580** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00001581** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00001582** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00001583*/
1584int sqliteBtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00001585 int rc;
drh8c1238a2003-01-02 14:43:55 +00001586 assert( pRes!=0 );
1587 /* assert( pCur->pPage!=0 ); */
drhecdc7532001-09-23 02:35:53 +00001588 if( pCur->pPage==0 ){
drh8c1238a2003-01-02 14:43:55 +00001589 *pRes = 1;
drhecdc7532001-09-23 02:35:53 +00001590 return SQLITE_ABORT;
1591 }
drh7aa128d2002-06-21 13:09:16 +00001592 assert( pCur->pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00001593 assert( pCur->eSkip!=SKIP_INVALID );
1594 if( pCur->pPage->nCell==0 ){
drh8c1238a2003-01-02 14:43:55 +00001595 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00001596 return SQLITE_OK;
1597 }
1598 assert( pCur->idx<pCur->pPage->nCell );
1599 if( pCur->eSkip==SKIP_NEXT ){
1600 pCur->eSkip = SKIP_NONE;
drh8c1238a2003-01-02 14:43:55 +00001601 *pRes = 0;
drh72f82862001-05-24 21:06:34 +00001602 return SQLITE_OK;
1603 }
drh2dcc9aa2002-12-04 13:40:25 +00001604 pCur->eSkip = SKIP_NONE;
drh72f82862001-05-24 21:06:34 +00001605 pCur->idx++;
drh5e2f8b92001-05-28 00:41:15 +00001606 if( pCur->idx>=pCur->pPage->nCell ){
drh8c42ca92001-06-22 19:15:00 +00001607 if( pCur->pPage->u.hdr.rightChild ){
drh0d316a42002-08-11 20:10:47 +00001608 rc = moveToChild(pCur, SWAB32(pCur->pBt, pCur->pPage->u.hdr.rightChild));
drh5e2f8b92001-05-28 00:41:15 +00001609 if( rc ) return rc;
1610 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00001611 *pRes = 0;
1612 return rc;
drh72f82862001-05-24 21:06:34 +00001613 }
drh5e2f8b92001-05-28 00:41:15 +00001614 do{
drh8c42ca92001-06-22 19:15:00 +00001615 if( pCur->pPage->pParent==0 ){
drh8c1238a2003-01-02 14:43:55 +00001616 *pRes = 1;
drh5e2f8b92001-05-28 00:41:15 +00001617 return SQLITE_OK;
1618 }
1619 rc = moveToParent(pCur);
drh8c1238a2003-01-02 14:43:55 +00001620 }while( rc==SQLITE_OK && pCur->idx>=pCur->pPage->nCell );
1621 *pRes = 0;
1622 return rc;
drh72f82862001-05-24 21:06:34 +00001623 }
drh5e2f8b92001-05-28 00:41:15 +00001624 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00001625 *pRes = 0;
1626 return rc;
drh72f82862001-05-24 21:06:34 +00001627}
1628
drh3b7511c2001-05-26 13:15:44 +00001629/*
drh2dcc9aa2002-12-04 13:40:25 +00001630** Step the cursor to the back to the previous entry in the database. If
1631** successful and pRes!=NULL then set *pRes=0. If the cursor
1632** was already pointing to the first entry in the database before
1633** this routine was called, then set *pRes=1 if pRes!=NULL.
1634*/
1635int sqliteBtreePrevious(BtCursor *pCur, int *pRes){
1636 int rc;
1637 Pgno pgno;
1638 if( pCur->pPage==0 ){
1639 if( pRes ) *pRes = 1;
1640 return SQLITE_ABORT;
1641 }
1642 assert( pCur->pPage->isInit );
1643 assert( pCur->eSkip!=SKIP_INVALID );
1644 if( pCur->pPage->nCell==0 ){
1645 if( pRes ) *pRes = 1;
1646 return SQLITE_OK;
1647 }
1648 if( pCur->eSkip==SKIP_PREV ){
1649 pCur->eSkip = SKIP_NONE;
1650 if( pRes ) *pRes = 0;
1651 return SQLITE_OK;
1652 }
1653 pCur->eSkip = SKIP_NONE;
1654 assert( pCur->idx>=0 );
1655 if( (pgno = pCur->pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
1656 rc = moveToChild(pCur, SWAB32(pCur->pBt, pgno));
1657 if( rc ) return rc;
1658 rc = moveToRightmost(pCur);
1659 }else{
1660 while( pCur->idx==0 ){
1661 if( pCur->pPage->pParent==0 ){
1662 if( pRes ) *pRes = 1;
1663 return SQLITE_OK;
1664 }
1665 rc = moveToParent(pCur);
1666 if( rc ) return rc;
1667 }
1668 pCur->idx--;
1669 rc = SQLITE_OK;
1670 }
1671 if( pRes ) *pRes = 0;
1672 return rc;
1673}
1674
1675/*
drh3b7511c2001-05-26 13:15:44 +00001676** Allocate a new page from the database file.
1677**
1678** The new page is marked as dirty. (In other words, sqlitepager_write()
1679** has already been called on the new page.) The new page has also
1680** been referenced and the calling routine is responsible for calling
1681** sqlitepager_unref() on the new page when it is done.
1682**
1683** SQLITE_OK is returned on success. Any other return value indicates
1684** an error. *ppPage and *pPgno are undefined in the event of an error.
1685** Do not invoke sqlitepager_unref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00001686**
drh199e3cf2002-07-18 11:01:47 +00001687** If the "nearby" parameter is not 0, then a (feeble) effort is made to
1688** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00001689** attempt to keep related pages close to each other in the database file,
1690** which in turn can make database access faster.
drh3b7511c2001-05-26 13:15:44 +00001691*/
drh199e3cf2002-07-18 11:01:47 +00001692static int allocatePage(Btree *pBt, MemPage **ppPage, Pgno *pPgno, Pgno nearby){
drhbd03cae2001-06-02 02:40:57 +00001693 PageOne *pPage1 = pBt->page1;
drh8c42ca92001-06-22 19:15:00 +00001694 int rc;
drh3b7511c2001-05-26 13:15:44 +00001695 if( pPage1->freeList ){
1696 OverflowPage *pOvfl;
drh30e58752002-03-02 20:41:57 +00001697 FreelistInfo *pInfo;
1698
drh3b7511c2001-05-26 13:15:44 +00001699 rc = sqlitepager_write(pPage1);
1700 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001701 SWAB_ADD(pBt, pPage1->nFree, -1);
1702 rc = sqlitepager_get(pBt->pPager, SWAB32(pBt, pPage1->freeList),
1703 (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001704 if( rc ) return rc;
1705 rc = sqlitepager_write(pOvfl);
1706 if( rc ){
1707 sqlitepager_unref(pOvfl);
1708 return rc;
1709 }
drh30e58752002-03-02 20:41:57 +00001710 pInfo = (FreelistInfo*)pOvfl->aPayload;
1711 if( pInfo->nFree==0 ){
drh0d316a42002-08-11 20:10:47 +00001712 *pPgno = SWAB32(pBt, pPage1->freeList);
drh30e58752002-03-02 20:41:57 +00001713 pPage1->freeList = pOvfl->iNext;
1714 *ppPage = (MemPage*)pOvfl;
1715 }else{
drh0d316a42002-08-11 20:10:47 +00001716 int closest, n;
1717 n = SWAB32(pBt, pInfo->nFree);
1718 if( n>1 && nearby>0 ){
drhbea00b92002-07-08 10:59:50 +00001719 int i, dist;
1720 closest = 0;
drh0d316a42002-08-11 20:10:47 +00001721 dist = SWAB32(pBt, pInfo->aFree[0]) - nearby;
drhbea00b92002-07-08 10:59:50 +00001722 if( dist<0 ) dist = -dist;
drh0d316a42002-08-11 20:10:47 +00001723 for(i=1; i<n; i++){
1724 int d2 = SWAB32(pBt, pInfo->aFree[i]) - nearby;
drhbea00b92002-07-08 10:59:50 +00001725 if( d2<0 ) d2 = -d2;
1726 if( d2<dist ) closest = i;
1727 }
1728 }else{
1729 closest = 0;
1730 }
drh0d316a42002-08-11 20:10:47 +00001731 SWAB_ADD(pBt, pInfo->nFree, -1);
1732 *pPgno = SWAB32(pBt, pInfo->aFree[closest]);
1733 pInfo->aFree[closest] = pInfo->aFree[n-1];
drh30e58752002-03-02 20:41:57 +00001734 rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
1735 sqlitepager_unref(pOvfl);
1736 if( rc==SQLITE_OK ){
1737 sqlitepager_dont_rollback(*ppPage);
1738 rc = sqlitepager_write(*ppPage);
1739 }
1740 }
drh3b7511c2001-05-26 13:15:44 +00001741 }else{
drh2aa679f2001-06-25 02:11:07 +00001742 *pPgno = sqlitepager_pagecount(pBt->pPager) + 1;
drh8c42ca92001-06-22 19:15:00 +00001743 rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
drh3b7511c2001-05-26 13:15:44 +00001744 if( rc ) return rc;
1745 rc = sqlitepager_write(*ppPage);
1746 }
1747 return rc;
1748}
1749
1750/*
1751** Add a page of the database file to the freelist. Either pgno or
1752** pPage but not both may be 0.
drh5e2f8b92001-05-28 00:41:15 +00001753**
drhdd793422001-06-28 01:54:48 +00001754** sqlitepager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00001755*/
1756static int freePage(Btree *pBt, void *pPage, Pgno pgno){
drhbd03cae2001-06-02 02:40:57 +00001757 PageOne *pPage1 = pBt->page1;
drh3b7511c2001-05-26 13:15:44 +00001758 OverflowPage *pOvfl = (OverflowPage*)pPage;
1759 int rc;
drhdd793422001-06-28 01:54:48 +00001760 int needUnref = 0;
1761 MemPage *pMemPage;
drh8b2f49b2001-06-08 00:21:52 +00001762
drh3b7511c2001-05-26 13:15:44 +00001763 if( pgno==0 ){
1764 assert( pOvfl!=0 );
1765 pgno = sqlitepager_pagenumber(pOvfl);
1766 }
drh2aa679f2001-06-25 02:11:07 +00001767 assert( pgno>2 );
drhda47d772002-12-02 04:25:19 +00001768 assert( sqlitepager_pagenumber(pOvfl)==pgno );
drh193a6b42002-07-07 16:52:46 +00001769 pMemPage = (MemPage*)pPage;
1770 pMemPage->isInit = 0;
1771 if( pMemPage->pParent ){
1772 sqlitepager_unref(pMemPage->pParent);
1773 pMemPage->pParent = 0;
1774 }
drh3b7511c2001-05-26 13:15:44 +00001775 rc = sqlitepager_write(pPage1);
1776 if( rc ){
1777 return rc;
1778 }
drh0d316a42002-08-11 20:10:47 +00001779 SWAB_ADD(pBt, pPage1->nFree, 1);
1780 if( pPage1->nFree!=0 && pPage1->freeList!=0 ){
drh30e58752002-03-02 20:41:57 +00001781 OverflowPage *pFreeIdx;
drh0d316a42002-08-11 20:10:47 +00001782 rc = sqlitepager_get(pBt->pPager, SWAB32(pBt, pPage1->freeList),
1783 (void**)&pFreeIdx);
drh30e58752002-03-02 20:41:57 +00001784 if( rc==SQLITE_OK ){
1785 FreelistInfo *pInfo = (FreelistInfo*)pFreeIdx->aPayload;
drh0d316a42002-08-11 20:10:47 +00001786 int n = SWAB32(pBt, pInfo->nFree);
1787 if( n<(sizeof(pInfo->aFree)/sizeof(pInfo->aFree[0])) ){
drh30e58752002-03-02 20:41:57 +00001788 rc = sqlitepager_write(pFreeIdx);
1789 if( rc==SQLITE_OK ){
drh0d316a42002-08-11 20:10:47 +00001790 pInfo->aFree[n] = SWAB32(pBt, pgno);
1791 SWAB_ADD(pBt, pInfo->nFree, 1);
drh30e58752002-03-02 20:41:57 +00001792 sqlitepager_unref(pFreeIdx);
1793 sqlitepager_dont_write(pBt->pPager, pgno);
1794 return rc;
1795 }
1796 }
1797 sqlitepager_unref(pFreeIdx);
1798 }
1799 }
drh3b7511c2001-05-26 13:15:44 +00001800 if( pOvfl==0 ){
1801 assert( pgno>0 );
drh8c42ca92001-06-22 19:15:00 +00001802 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001803 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001804 needUnref = 1;
drh3b7511c2001-05-26 13:15:44 +00001805 }
1806 rc = sqlitepager_write(pOvfl);
1807 if( rc ){
drhdd793422001-06-28 01:54:48 +00001808 if( needUnref ) sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001809 return rc;
1810 }
drh14acc042001-06-10 19:56:58 +00001811 pOvfl->iNext = pPage1->freeList;
drh0d316a42002-08-11 20:10:47 +00001812 pPage1->freeList = SWAB32(pBt, pgno);
drh5e2f8b92001-05-28 00:41:15 +00001813 memset(pOvfl->aPayload, 0, OVERFLOW_SIZE);
drhdd793422001-06-28 01:54:48 +00001814 if( needUnref ) rc = sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001815 return rc;
1816}
1817
1818/*
1819** Erase all the data out of a cell. This involves returning overflow
1820** pages back the freelist.
1821*/
1822static int clearCell(Btree *pBt, Cell *pCell){
1823 Pager *pPager = pBt->pPager;
1824 OverflowPage *pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001825 Pgno ovfl, nextOvfl;
1826 int rc;
1827
drh0d316a42002-08-11 20:10:47 +00001828 if( NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h) <= MX_LOCAL_PAYLOAD ){
drh5e2f8b92001-05-28 00:41:15 +00001829 return SQLITE_OK;
1830 }
drh0d316a42002-08-11 20:10:47 +00001831 ovfl = SWAB32(pBt, pCell->ovfl);
drh3b7511c2001-05-26 13:15:44 +00001832 pCell->ovfl = 0;
1833 while( ovfl ){
drh8c42ca92001-06-22 19:15:00 +00001834 rc = sqlitepager_get(pPager, ovfl, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001835 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001836 nextOvfl = SWAB32(pBt, pOvfl->iNext);
drhbd03cae2001-06-02 02:40:57 +00001837 rc = freePage(pBt, pOvfl, ovfl);
1838 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001839 sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001840 ovfl = nextOvfl;
drh3b7511c2001-05-26 13:15:44 +00001841 }
drh5e2f8b92001-05-28 00:41:15 +00001842 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00001843}
1844
1845/*
1846** Create a new cell from key and data. Overflow pages are allocated as
1847** necessary and linked to this cell.
1848*/
1849static int fillInCell(
1850 Btree *pBt, /* The whole Btree. Needed to allocate pages */
1851 Cell *pCell, /* Populate this Cell structure */
drh5c4d9702001-08-20 00:33:58 +00001852 const void *pKey, int nKey, /* The key */
1853 const void *pData,int nData /* The data */
drh3b7511c2001-05-26 13:15:44 +00001854){
drhdd793422001-06-28 01:54:48 +00001855 OverflowPage *pOvfl, *pPrior;
drh3b7511c2001-05-26 13:15:44 +00001856 Pgno *pNext;
1857 int spaceLeft;
drh8c42ca92001-06-22 19:15:00 +00001858 int n, rc;
drh3b7511c2001-05-26 13:15:44 +00001859 int nPayload;
drh5c4d9702001-08-20 00:33:58 +00001860 const char *pPayload;
drh3b7511c2001-05-26 13:15:44 +00001861 char *pSpace;
drh199e3cf2002-07-18 11:01:47 +00001862 Pgno nearby = 0;
drh3b7511c2001-05-26 13:15:44 +00001863
drh5e2f8b92001-05-28 00:41:15 +00001864 pCell->h.leftChild = 0;
drh0d316a42002-08-11 20:10:47 +00001865 pCell->h.nKey = SWAB16(pBt, nKey & 0xffff);
drh80ff32f2001-11-04 18:32:46 +00001866 pCell->h.nKeyHi = nKey >> 16;
drh0d316a42002-08-11 20:10:47 +00001867 pCell->h.nData = SWAB16(pBt, nData & 0xffff);
drh80ff32f2001-11-04 18:32:46 +00001868 pCell->h.nDataHi = nData >> 16;
drh3b7511c2001-05-26 13:15:44 +00001869 pCell->h.iNext = 0;
1870
1871 pNext = &pCell->ovfl;
drh5e2f8b92001-05-28 00:41:15 +00001872 pSpace = pCell->aPayload;
drh3b7511c2001-05-26 13:15:44 +00001873 spaceLeft = MX_LOCAL_PAYLOAD;
1874 pPayload = pKey;
1875 pKey = 0;
1876 nPayload = nKey;
drhdd793422001-06-28 01:54:48 +00001877 pPrior = 0;
drh3b7511c2001-05-26 13:15:44 +00001878 while( nPayload>0 ){
1879 if( spaceLeft==0 ){
drh199e3cf2002-07-18 11:01:47 +00001880 rc = allocatePage(pBt, (MemPage**)&pOvfl, pNext, nearby);
drh3b7511c2001-05-26 13:15:44 +00001881 if( rc ){
1882 *pNext = 0;
drhbea00b92002-07-08 10:59:50 +00001883 }else{
drh199e3cf2002-07-18 11:01:47 +00001884 nearby = *pNext;
drhdd793422001-06-28 01:54:48 +00001885 }
1886 if( pPrior ) sqlitepager_unref(pPrior);
1887 if( rc ){
drh5e2f8b92001-05-28 00:41:15 +00001888 clearCell(pBt, pCell);
drh3b7511c2001-05-26 13:15:44 +00001889 return rc;
1890 }
drh0d316a42002-08-11 20:10:47 +00001891 if( pBt->needSwab ) *pNext = swab32(*pNext);
drhdd793422001-06-28 01:54:48 +00001892 pPrior = pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001893 spaceLeft = OVERFLOW_SIZE;
drh5e2f8b92001-05-28 00:41:15 +00001894 pSpace = pOvfl->aPayload;
drh8c42ca92001-06-22 19:15:00 +00001895 pNext = &pOvfl->iNext;
drh3b7511c2001-05-26 13:15:44 +00001896 }
1897 n = nPayload;
1898 if( n>spaceLeft ) n = spaceLeft;
1899 memcpy(pSpace, pPayload, n);
1900 nPayload -= n;
1901 if( nPayload==0 && pData ){
1902 pPayload = pData;
1903 nPayload = nData;
1904 pData = 0;
1905 }else{
1906 pPayload += n;
1907 }
1908 spaceLeft -= n;
1909 pSpace += n;
1910 }
drhdd793422001-06-28 01:54:48 +00001911 *pNext = 0;
1912 if( pPrior ){
1913 sqlitepager_unref(pPrior);
1914 }
drh3b7511c2001-05-26 13:15:44 +00001915 return SQLITE_OK;
1916}
1917
1918/*
drhbd03cae2001-06-02 02:40:57 +00001919** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00001920** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00001921** pointer in the third argument.
1922*/
drh428ae8c2003-01-04 16:48:09 +00001923static void reparentPage(Pager *pPager, Pgno pgno, MemPage *pNewParent,int idx){
drhbd03cae2001-06-02 02:40:57 +00001924 MemPage *pThis;
1925
drhdd793422001-06-28 01:54:48 +00001926 if( pgno==0 ) return;
1927 assert( pPager!=0 );
drhbd03cae2001-06-02 02:40:57 +00001928 pThis = sqlitepager_lookup(pPager, pgno);
drh6019e162001-07-02 17:51:45 +00001929 if( pThis && pThis->isInit ){
drhdd793422001-06-28 01:54:48 +00001930 if( pThis->pParent!=pNewParent ){
1931 if( pThis->pParent ) sqlitepager_unref(pThis->pParent);
1932 pThis->pParent = pNewParent;
1933 if( pNewParent ) sqlitepager_ref(pNewParent);
1934 }
drh428ae8c2003-01-04 16:48:09 +00001935 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00001936 sqlitepager_unref(pThis);
drhbd03cae2001-06-02 02:40:57 +00001937 }
1938}
1939
1940/*
1941** Reparent all children of the given page to be the given page.
1942** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00001943** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00001944**
1945** This routine gets called after you memcpy() one page into
1946** another.
1947*/
drh0d316a42002-08-11 20:10:47 +00001948static void reparentChildPages(Btree *pBt, MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00001949 int i;
drh0d316a42002-08-11 20:10:47 +00001950 Pager *pPager = pBt->pPager;
drhbd03cae2001-06-02 02:40:57 +00001951 for(i=0; i<pPage->nCell; i++){
drh428ae8c2003-01-04 16:48:09 +00001952 reparentPage(pPager, SWAB32(pBt, pPage->apCell[i]->h.leftChild), pPage, i);
drhbd03cae2001-06-02 02:40:57 +00001953 }
drh428ae8c2003-01-04 16:48:09 +00001954 reparentPage(pPager, SWAB32(pBt, pPage->u.hdr.rightChild), pPage, i);
1955 pPage->idxShift = 0;
drh14acc042001-06-10 19:56:58 +00001956}
1957
1958/*
1959** Remove the i-th cell from pPage. This routine effects pPage only.
1960** The cell content is not freed or deallocated. It is assumed that
1961** the cell content has been copied someplace else. This routine just
1962** removes the reference to the cell from pPage.
1963**
1964** "sz" must be the number of bytes in the cell.
1965**
1966** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001967** Only the pPage->apCell[] array is important. The relinkCellList()
1968** routine will be called soon after this routine in order to rebuild
1969** the linked list.
drh14acc042001-06-10 19:56:58 +00001970*/
drh0d316a42002-08-11 20:10:47 +00001971static void dropCell(Btree *pBt, MemPage *pPage, int idx, int sz){
drh14acc042001-06-10 19:56:58 +00001972 int j;
drh8c42ca92001-06-22 19:15:00 +00001973 assert( idx>=0 && idx<pPage->nCell );
drh0d316a42002-08-11 20:10:47 +00001974 assert( sz==cellSize(pBt, pPage->apCell[idx]) );
drh6019e162001-07-02 17:51:45 +00001975 assert( sqlitepager_iswriteable(pPage) );
drh0d316a42002-08-11 20:10:47 +00001976 freeSpace(pBt, pPage, Addr(pPage->apCell[idx]) - Addr(pPage), sz);
drh7c717f72001-06-24 20:39:41 +00001977 for(j=idx; j<pPage->nCell-1; j++){
drh14acc042001-06-10 19:56:58 +00001978 pPage->apCell[j] = pPage->apCell[j+1];
1979 }
1980 pPage->nCell--;
drh428ae8c2003-01-04 16:48:09 +00001981 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00001982}
1983
1984/*
1985** Insert a new cell on pPage at cell index "i". pCell points to the
1986** content of the cell.
1987**
1988** If the cell content will fit on the page, then put it there. If it
1989** will not fit, then just make pPage->apCell[i] point to the content
1990** and set pPage->isOverfull.
1991**
1992** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001993** Only the pPage->apCell[] array is important. The relinkCellList()
1994** routine will be called soon after this routine in order to rebuild
1995** the linked list.
drh14acc042001-06-10 19:56:58 +00001996*/
drh0d316a42002-08-11 20:10:47 +00001997static void insertCell(Btree *pBt, MemPage *pPage, int i, Cell *pCell, int sz){
drh14acc042001-06-10 19:56:58 +00001998 int idx, j;
1999 assert( i>=0 && i<=pPage->nCell );
drh0d316a42002-08-11 20:10:47 +00002000 assert( sz==cellSize(pBt, pCell) );
drh6019e162001-07-02 17:51:45 +00002001 assert( sqlitepager_iswriteable(pPage) );
drh0d316a42002-08-11 20:10:47 +00002002 idx = allocateSpace(pBt, pPage, sz);
drh14acc042001-06-10 19:56:58 +00002003 for(j=pPage->nCell; j>i; j--){
2004 pPage->apCell[j] = pPage->apCell[j-1];
2005 }
2006 pPage->nCell++;
drh14acc042001-06-10 19:56:58 +00002007 if( idx<=0 ){
2008 pPage->isOverfull = 1;
2009 pPage->apCell[i] = pCell;
2010 }else{
2011 memcpy(&pPage->u.aDisk[idx], pCell, sz);
drh8c42ca92001-06-22 19:15:00 +00002012 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[idx];
drh14acc042001-06-10 19:56:58 +00002013 }
drh428ae8c2003-01-04 16:48:09 +00002014 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00002015}
2016
2017/*
2018** Rebuild the linked list of cells on a page so that the cells
drh8c42ca92001-06-22 19:15:00 +00002019** occur in the order specified by the pPage->apCell[] array.
2020** Invoke this routine once to repair damage after one or more
2021** invocations of either insertCell() or dropCell().
drh14acc042001-06-10 19:56:58 +00002022*/
drh0d316a42002-08-11 20:10:47 +00002023static void relinkCellList(Btree *pBt, MemPage *pPage){
drh14acc042001-06-10 19:56:58 +00002024 int i;
2025 u16 *pIdx;
drh6019e162001-07-02 17:51:45 +00002026 assert( sqlitepager_iswriteable(pPage) );
drh14acc042001-06-10 19:56:58 +00002027 pIdx = &pPage->u.hdr.firstCell;
2028 for(i=0; i<pPage->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00002029 int idx = Addr(pPage->apCell[i]) - Addr(pPage);
drh8c42ca92001-06-22 19:15:00 +00002030 assert( idx>0 && idx<SQLITE_PAGE_SIZE );
drh0d316a42002-08-11 20:10:47 +00002031 *pIdx = SWAB16(pBt, idx);
drh14acc042001-06-10 19:56:58 +00002032 pIdx = &pPage->apCell[i]->h.iNext;
2033 }
2034 *pIdx = 0;
2035}
2036
2037/*
2038** Make a copy of the contents of pFrom into pTo. The pFrom->apCell[]
drh5e00f6c2001-09-13 13:46:56 +00002039** pointers that point into pFrom->u.aDisk[] must be adjusted to point
drhdd793422001-06-28 01:54:48 +00002040** into pTo->u.aDisk[] instead. But some pFrom->apCell[] entries might
drh14acc042001-06-10 19:56:58 +00002041** not point to pFrom->u.aDisk[]. Those are unchanged.
2042*/
2043static void copyPage(MemPage *pTo, MemPage *pFrom){
2044 uptr from, to;
2045 int i;
2046 memcpy(pTo->u.aDisk, pFrom->u.aDisk, SQLITE_PAGE_SIZE);
drhdd793422001-06-28 01:54:48 +00002047 pTo->pParent = 0;
drh14acc042001-06-10 19:56:58 +00002048 pTo->isInit = 1;
2049 pTo->nCell = pFrom->nCell;
2050 pTo->nFree = pFrom->nFree;
2051 pTo->isOverfull = pFrom->isOverfull;
drh7c717f72001-06-24 20:39:41 +00002052 to = Addr(pTo);
2053 from = Addr(pFrom);
drh14acc042001-06-10 19:56:58 +00002054 for(i=0; i<pTo->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00002055 uptr x = Addr(pFrom->apCell[i]);
drh8c42ca92001-06-22 19:15:00 +00002056 if( x>from && x<from+SQLITE_PAGE_SIZE ){
2057 *((uptr*)&pTo->apCell[i]) = x + to - from;
drhdd793422001-06-28 01:54:48 +00002058 }else{
2059 pTo->apCell[i] = pFrom->apCell[i];
drh14acc042001-06-10 19:56:58 +00002060 }
2061 }
drhbd03cae2001-06-02 02:40:57 +00002062}
2063
2064/*
drhc3b70572003-01-04 19:44:07 +00002065** The following parameters determine how many adjacent pages get involved
2066** in a balancing operation. NN is the number of neighbors on either side
2067** of the page that participate in the balancing operation. NB is the
2068** total number of pages that participate, including the target page and
2069** NN neighbors on either side.
2070**
2071** The minimum value of NN is 1 (of course). Increasing NN above 1
2072** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
2073** in exchange for a larger degradation in INSERT and UPDATE performance.
2074** The value of NN appears to give the best results overall.
2075*/
2076#define NN 1 /* Number of neighbors on either side of pPage */
2077#define NB (NN*2+1) /* Total pages involved in the balance */
2078
2079/*
drh8b2f49b2001-06-08 00:21:52 +00002080** This routine redistributes Cells on pPage and up to two siblings
2081** of pPage so that all pages have about the same amount of free space.
drh14acc042001-06-10 19:56:58 +00002082** Usually one sibling on either side of pPage is used in the balancing,
drh8b2f49b2001-06-08 00:21:52 +00002083** though both siblings might come from one side if pPage is the first
2084** or last child of its parent. If pPage has fewer than two siblings
2085** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00002086** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00002087**
2088** The number of siblings of pPage might be increased or decreased by
drh8c42ca92001-06-22 19:15:00 +00002089** one in an effort to keep pages between 66% and 100% full. The root page
2090** is special and is allowed to be less than 66% full. If pPage is
2091** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00002092** or decreased by one, as necessary, to keep the root page from being
2093** overfull or empty.
2094**
drh14acc042001-06-10 19:56:58 +00002095** This routine calls relinkCellList() on its input page regardless of
2096** whether or not it does any real balancing. Client routines will typically
2097** invoke insertCell() or dropCell() before calling this routine, so we
2098** need to call relinkCellList() to clean up the mess that those other
2099** routines left behind.
2100**
2101** pCur is left pointing to the same cell as when this routine was called
drh8c42ca92001-06-22 19:15:00 +00002102** even if that cell gets moved to a different page. pCur may be NULL.
2103** Set the pCur parameter to NULL if you do not care about keeping track
2104** of a cell as that will save this routine the work of keeping track of it.
drh14acc042001-06-10 19:56:58 +00002105**
drh8b2f49b2001-06-08 00:21:52 +00002106** Note that when this routine is called, some of the Cells on pPage
drh14acc042001-06-10 19:56:58 +00002107** might not actually be stored in pPage->u.aDisk[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00002108** if the page is overfull. Part of the job of this routine is to
drh14acc042001-06-10 19:56:58 +00002109** make sure all Cells for pPage once again fit in pPage->u.aDisk[].
2110**
drh8c42ca92001-06-22 19:15:00 +00002111** In the course of balancing the siblings of pPage, the parent of pPage
2112** might become overfull or underfull. If that happens, then this routine
2113** is called recursively on the parent.
2114**
drh5e00f6c2001-09-13 13:46:56 +00002115** If this routine fails for any reason, it might leave the database
2116** in a corrupted state. So if this routine fails, the database should
2117** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00002118*/
drh14acc042001-06-10 19:56:58 +00002119static int balance(Btree *pBt, MemPage *pPage, BtCursor *pCur){
drh8b2f49b2001-06-08 00:21:52 +00002120 MemPage *pParent; /* The parent of pPage */
drh8b2f49b2001-06-08 00:21:52 +00002121 int nCell; /* Number of cells in apCell[] */
2122 int nOld; /* Number of pages in apOld[] */
2123 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00002124 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00002125 int i, j, k; /* Loop counters */
2126 int idx; /* Index of pPage in pParent->apCell[] */
2127 int nxDiv; /* Next divider slot in pParent->apCell[] */
2128 int rc; /* The return code */
2129 int iCur; /* apCell[iCur] is the cell of the cursor */
drh5edc3122001-09-13 21:53:09 +00002130 MemPage *pOldCurPage; /* The cursor originally points to this page */
drh6019e162001-07-02 17:51:45 +00002131 int subtotal; /* Subtotal of bytes in cells on one page */
drh9ca7d3b2001-06-28 11:50:21 +00002132 MemPage *extraUnref = 0; /* A page that needs to be unref-ed */
drhc3b70572003-01-04 19:44:07 +00002133 MemPage *apOld[NB]; /* pPage and up to two siblings */
2134 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
2135 MemPage *apNew[NB+1]; /* pPage and up to NB siblings after balancing */
2136 Pgno pgnoNew[NB+1]; /* Page numbers for each page in apNew[] */
2137 int idxDiv[NB]; /* Indices of divider cells in pParent */
2138 Cell *apDiv[NB]; /* Divider cells in pParent */
2139 Cell aTemp[NB]; /* Temporary holding area for apDiv[] */
2140 int cntNew[NB+1]; /* Index in apCell[] of cell after i-th page */
2141 int szNew[NB+1]; /* Combined size of cells place on i-th page */
2142 MemPage aOld[NB]; /* Temporary copies of pPage and its siblings */
2143 Cell *apCell[(MX_CELL+2)*NB]; /* All cells from pages being balanced */
2144 int szCell[(MX_CELL+2)*NB]; /* Local size of all cells */
drh8b2f49b2001-06-08 00:21:52 +00002145
drh14acc042001-06-10 19:56:58 +00002146 /*
2147 ** Return without doing any work if pPage is neither overfull nor
2148 ** underfull.
drh8b2f49b2001-06-08 00:21:52 +00002149 */
drh6019e162001-07-02 17:51:45 +00002150 assert( sqlitepager_iswriteable(pPage) );
drha1b351a2001-09-14 16:42:12 +00002151 if( !pPage->isOverfull && pPage->nFree<SQLITE_PAGE_SIZE/2
2152 && pPage->nCell>=2){
drh0d316a42002-08-11 20:10:47 +00002153 relinkCellList(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002154 return SQLITE_OK;
2155 }
2156
2157 /*
drh14acc042001-06-10 19:56:58 +00002158 ** Find the parent of the page to be balanceed.
2159 ** If there is no parent, it means this page is the root page and
drh8b2f49b2001-06-08 00:21:52 +00002160 ** special rules apply.
2161 */
drh14acc042001-06-10 19:56:58 +00002162 pParent = pPage->pParent;
drh8b2f49b2001-06-08 00:21:52 +00002163 if( pParent==0 ){
2164 Pgno pgnoChild;
drh8c42ca92001-06-22 19:15:00 +00002165 MemPage *pChild;
drh7aa128d2002-06-21 13:09:16 +00002166 assert( pPage->isInit );
drh8b2f49b2001-06-08 00:21:52 +00002167 if( pPage->nCell==0 ){
drh14acc042001-06-10 19:56:58 +00002168 if( pPage->u.hdr.rightChild ){
2169 /*
2170 ** The root page is empty. Copy the one child page
drh8b2f49b2001-06-08 00:21:52 +00002171 ** into the root page and return. This reduces the depth
2172 ** of the BTree by one.
2173 */
drh0d316a42002-08-11 20:10:47 +00002174 pgnoChild = SWAB32(pBt, pPage->u.hdr.rightChild);
drh8c42ca92001-06-22 19:15:00 +00002175 rc = sqlitepager_get(pBt->pPager, pgnoChild, (void**)&pChild);
drh8b2f49b2001-06-08 00:21:52 +00002176 if( rc ) return rc;
2177 memcpy(pPage, pChild, SQLITE_PAGE_SIZE);
2178 pPage->isInit = 0;
drh0d316a42002-08-11 20:10:47 +00002179 rc = initPage(pBt, pPage, sqlitepager_pagenumber(pPage), 0);
drh6019e162001-07-02 17:51:45 +00002180 assert( rc==SQLITE_OK );
drh0d316a42002-08-11 20:10:47 +00002181 reparentChildPages(pBt, pPage);
drh5edc3122001-09-13 21:53:09 +00002182 if( pCur && pCur->pPage==pChild ){
2183 sqlitepager_unref(pChild);
2184 pCur->pPage = pPage;
2185 sqlitepager_ref(pPage);
2186 }
drh8b2f49b2001-06-08 00:21:52 +00002187 freePage(pBt, pChild, pgnoChild);
2188 sqlitepager_unref(pChild);
drhefc251d2001-07-01 22:12:01 +00002189 }else{
drh0d316a42002-08-11 20:10:47 +00002190 relinkCellList(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002191 }
2192 return SQLITE_OK;
2193 }
drh14acc042001-06-10 19:56:58 +00002194 if( !pPage->isOverfull ){
drh8b2f49b2001-06-08 00:21:52 +00002195 /* It is OK for the root page to be less than half full.
2196 */
drh0d316a42002-08-11 20:10:47 +00002197 relinkCellList(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002198 return SQLITE_OK;
2199 }
drh14acc042001-06-10 19:56:58 +00002200 /*
2201 ** If we get to here, it means the root page is overfull.
drh8b2f49b2001-06-08 00:21:52 +00002202 ** When this happens, Create a new child page and copy the
2203 ** contents of the root into the child. Then make the root
drh14acc042001-06-10 19:56:58 +00002204 ** page an empty page with rightChild pointing to the new
drh8b2f49b2001-06-08 00:21:52 +00002205 ** child. Then fall thru to the code below which will cause
2206 ** the overfull child page to be split.
2207 */
drh14acc042001-06-10 19:56:58 +00002208 rc = sqlitepager_write(pPage);
2209 if( rc ) return rc;
drhbea00b92002-07-08 10:59:50 +00002210 rc = allocatePage(pBt, &pChild, &pgnoChild, sqlitepager_pagenumber(pPage));
drh8b2f49b2001-06-08 00:21:52 +00002211 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002212 assert( sqlitepager_iswriteable(pChild) );
drh14acc042001-06-10 19:56:58 +00002213 copyPage(pChild, pPage);
2214 pChild->pParent = pPage;
drhbb49aba2003-01-04 18:53:27 +00002215 pChild->idxParent = 0;
drhdd793422001-06-28 01:54:48 +00002216 sqlitepager_ref(pPage);
drh14acc042001-06-10 19:56:58 +00002217 pChild->isOverfull = 1;
drh5edc3122001-09-13 21:53:09 +00002218 if( pCur && pCur->pPage==pPage ){
2219 sqlitepager_unref(pPage);
drh14acc042001-06-10 19:56:58 +00002220 pCur->pPage = pChild;
drh9ca7d3b2001-06-28 11:50:21 +00002221 }else{
2222 extraUnref = pChild;
drh8b2f49b2001-06-08 00:21:52 +00002223 }
drh0d316a42002-08-11 20:10:47 +00002224 zeroPage(pBt, pPage);
2225 pPage->u.hdr.rightChild = SWAB32(pBt, pgnoChild);
drh8b2f49b2001-06-08 00:21:52 +00002226 pParent = pPage;
2227 pPage = pChild;
drh8b2f49b2001-06-08 00:21:52 +00002228 }
drh6019e162001-07-02 17:51:45 +00002229 rc = sqlitepager_write(pParent);
2230 if( rc ) return rc;
drh7aa128d2002-06-21 13:09:16 +00002231 assert( pParent->isInit );
drh14acc042001-06-10 19:56:58 +00002232
drh8b2f49b2001-06-08 00:21:52 +00002233 /*
drh14acc042001-06-10 19:56:58 +00002234 ** Find the Cell in the parent page whose h.leftChild points back
2235 ** to pPage. The "idx" variable is the index of that cell. If pPage
2236 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00002237 */
drhbb49aba2003-01-04 18:53:27 +00002238 if( pParent->idxShift ){
2239 Pgno pgno, swabPgno;
2240 pgno = sqlitepager_pagenumber(pPage);
2241 swabPgno = SWAB32(pBt, pgno);
2242 for(idx=0; idx<pParent->nCell; idx++){
2243 if( pParent->apCell[idx]->h.leftChild==swabPgno ){
2244 break;
2245 }
drh8b2f49b2001-06-08 00:21:52 +00002246 }
drhbb49aba2003-01-04 18:53:27 +00002247 assert( idx<pParent->nCell || pParent->u.hdr.rightChild==swabPgno );
2248 }else{
2249 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00002250 }
drh8b2f49b2001-06-08 00:21:52 +00002251
2252 /*
drh14acc042001-06-10 19:56:58 +00002253 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00002254 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00002255 */
drh14acc042001-06-10 19:56:58 +00002256 nOld = nNew = 0;
2257 sqlitepager_ref(pParent);
2258
2259 /*
2260 ** Find sibling pages to pPage and the Cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00002261 ** the siblings. An attempt is made to find NN siblings on either
2262 ** side of pPage. More siblings are taken from one side, however, if
2263 ** pPage there are fewer than NN siblings on the other side. If pParent
2264 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00002265 */
drhc3b70572003-01-04 19:44:07 +00002266 nxDiv = idx - NN;
2267 if( nxDiv + NB > pParent->nCell ){
2268 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00002269 }
drhc3b70572003-01-04 19:44:07 +00002270 if( nxDiv<0 ){
2271 nxDiv = 0;
2272 }
drh8b2f49b2001-06-08 00:21:52 +00002273 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00002274 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00002275 if( k<pParent->nCell ){
2276 idxDiv[i] = k;
2277 apDiv[i] = pParent->apCell[k];
drh8b2f49b2001-06-08 00:21:52 +00002278 nDiv++;
drh0d316a42002-08-11 20:10:47 +00002279 pgnoOld[i] = SWAB32(pBt, apDiv[i]->h.leftChild);
drh14acc042001-06-10 19:56:58 +00002280 }else if( k==pParent->nCell ){
drh0d316a42002-08-11 20:10:47 +00002281 pgnoOld[i] = SWAB32(pBt, pParent->u.hdr.rightChild);
drh14acc042001-06-10 19:56:58 +00002282 }else{
2283 break;
drh8b2f49b2001-06-08 00:21:52 +00002284 }
drh8c42ca92001-06-22 19:15:00 +00002285 rc = sqlitepager_get(pBt->pPager, pgnoOld[i], (void**)&apOld[i]);
drh14acc042001-06-10 19:56:58 +00002286 if( rc ) goto balance_cleanup;
drh0d316a42002-08-11 20:10:47 +00002287 rc = initPage(pBt, apOld[i], pgnoOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00002288 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00002289 apOld[i]->idxParent = k;
drh14acc042001-06-10 19:56:58 +00002290 nOld++;
drh8b2f49b2001-06-08 00:21:52 +00002291 }
2292
2293 /*
drh14acc042001-06-10 19:56:58 +00002294 ** Set iCur to be the index in apCell[] of the cell that the cursor
2295 ** is pointing to. We will need this later on in order to keep the
drh5edc3122001-09-13 21:53:09 +00002296 ** cursor pointing at the same cell. If pCur points to a page that
2297 ** has no involvement with this rebalancing, then set iCur to a large
2298 ** number so that the iCur==j tests always fail in the main cell
2299 ** distribution loop below.
drh14acc042001-06-10 19:56:58 +00002300 */
2301 if( pCur ){
drh5edc3122001-09-13 21:53:09 +00002302 iCur = 0;
2303 for(i=0; i<nOld; i++){
2304 if( pCur->pPage==apOld[i] ){
2305 iCur += pCur->idx;
2306 break;
2307 }
2308 iCur += apOld[i]->nCell;
2309 if( i<nOld-1 && pCur->pPage==pParent && pCur->idx==idxDiv[i] ){
2310 break;
2311 }
2312 iCur++;
drh14acc042001-06-10 19:56:58 +00002313 }
drh5edc3122001-09-13 21:53:09 +00002314 pOldCurPage = pCur->pPage;
drh14acc042001-06-10 19:56:58 +00002315 }
2316
2317 /*
2318 ** Make copies of the content of pPage and its siblings into aOld[].
2319 ** The rest of this function will use data from the copies rather
2320 ** that the original pages since the original pages will be in the
2321 ** process of being overwritten.
2322 */
2323 for(i=0; i<nOld; i++){
2324 copyPage(&aOld[i], apOld[i]);
drh14acc042001-06-10 19:56:58 +00002325 }
2326
2327 /*
2328 ** Load pointers to all cells on sibling pages and the divider cells
2329 ** into the local apCell[] array. Make copies of the divider cells
2330 ** into aTemp[] and remove the the divider Cells from pParent.
drh8b2f49b2001-06-08 00:21:52 +00002331 */
2332 nCell = 0;
2333 for(i=0; i<nOld; i++){
drh6b308672002-07-08 02:16:37 +00002334 MemPage *pOld = &aOld[i];
drh8b2f49b2001-06-08 00:21:52 +00002335 for(j=0; j<pOld->nCell; j++){
drh14acc042001-06-10 19:56:58 +00002336 apCell[nCell] = pOld->apCell[j];
drh0d316a42002-08-11 20:10:47 +00002337 szCell[nCell] = cellSize(pBt, apCell[nCell]);
drh14acc042001-06-10 19:56:58 +00002338 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00002339 }
2340 if( i<nOld-1 ){
drh0d316a42002-08-11 20:10:47 +00002341 szCell[nCell] = cellSize(pBt, apDiv[i]);
drh8c42ca92001-06-22 19:15:00 +00002342 memcpy(&aTemp[i], apDiv[i], szCell[nCell]);
drh14acc042001-06-10 19:56:58 +00002343 apCell[nCell] = &aTemp[i];
drh0d316a42002-08-11 20:10:47 +00002344 dropCell(pBt, pParent, nxDiv, szCell[nCell]);
2345 assert( SWAB32(pBt, apCell[nCell]->h.leftChild)==pgnoOld[i] );
drh14acc042001-06-10 19:56:58 +00002346 apCell[nCell]->h.leftChild = pOld->u.hdr.rightChild;
2347 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00002348 }
2349 }
2350
2351 /*
drh6019e162001-07-02 17:51:45 +00002352 ** Figure out the number of pages needed to hold all nCell cells.
2353 ** Store this number in "k". Also compute szNew[] which is the total
2354 ** size of all cells on the i-th page and cntNew[] which is the index
2355 ** in apCell[] of the cell that divides path i from path i+1.
2356 ** cntNew[k] should equal nCell.
2357 **
2358 ** This little patch of code is critical for keeping the tree
2359 ** balanced.
drh8b2f49b2001-06-08 00:21:52 +00002360 */
drh6019e162001-07-02 17:51:45 +00002361 for(subtotal=k=i=0; i<nCell; i++){
2362 subtotal += szCell[i];
2363 if( subtotal > USABLE_SPACE ){
2364 szNew[k] = subtotal - szCell[i];
2365 cntNew[k] = i;
2366 subtotal = 0;
2367 k++;
2368 }
2369 }
2370 szNew[k] = subtotal;
2371 cntNew[k] = nCell;
2372 k++;
2373 for(i=k-1; i>0; i--){
2374 while( szNew[i]<USABLE_SPACE/2 ){
2375 cntNew[i-1]--;
2376 assert( cntNew[i-1]>0 );
2377 szNew[i] += szCell[cntNew[i-1]];
2378 szNew[i-1] -= szCell[cntNew[i-1]-1];
2379 }
2380 }
2381 assert( cntNew[0]>0 );
drh8b2f49b2001-06-08 00:21:52 +00002382
2383 /*
drh6b308672002-07-08 02:16:37 +00002384 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00002385 */
drh14acc042001-06-10 19:56:58 +00002386 for(i=0; i<k; i++){
drh6b308672002-07-08 02:16:37 +00002387 if( i<nOld ){
2388 apNew[i] = apOld[i];
2389 pgnoNew[i] = pgnoOld[i];
2390 apOld[i] = 0;
2391 sqlitepager_write(apNew[i]);
2392 }else{
drhbea00b92002-07-08 10:59:50 +00002393 rc = allocatePage(pBt, &apNew[i], &pgnoNew[i], pgnoNew[i-1]);
drh6b308672002-07-08 02:16:37 +00002394 if( rc ) goto balance_cleanup;
2395 }
drh14acc042001-06-10 19:56:58 +00002396 nNew++;
drh0d316a42002-08-11 20:10:47 +00002397 zeroPage(pBt, apNew[i]);
drh6019e162001-07-02 17:51:45 +00002398 apNew[i]->isInit = 1;
drh8b2f49b2001-06-08 00:21:52 +00002399 }
2400
drh6b308672002-07-08 02:16:37 +00002401 /* Free any old pages that were not reused as new pages.
2402 */
2403 while( i<nOld ){
2404 rc = freePage(pBt, apOld[i], pgnoOld[i]);
2405 if( rc ) goto balance_cleanup;
2406 sqlitepager_unref(apOld[i]);
2407 apOld[i] = 0;
2408 i++;
2409 }
2410
drh8b2f49b2001-06-08 00:21:52 +00002411 /*
drhf9ffac92002-03-02 19:00:31 +00002412 ** Put the new pages in accending order. This helps to
2413 ** keep entries in the disk file in order so that a scan
2414 ** of the table is a linear scan through the file. That
2415 ** in turn helps the operating system to deliver pages
2416 ** from the disk more rapidly.
2417 **
2418 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00002419 ** n is never more than NB (a small constant), that should
2420 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00002421 **
drhc3b70572003-01-04 19:44:07 +00002422 ** When NB==3, this one optimization makes the database
2423 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00002424 */
2425 for(i=0; i<k-1; i++){
2426 int minV = pgnoNew[i];
2427 int minI = i;
2428 for(j=i+1; j<k; j++){
2429 if( pgnoNew[j]<minV ){
2430 minI = j;
2431 minV = pgnoNew[j];
2432 }
2433 }
2434 if( minI>i ){
2435 int t;
2436 MemPage *pT;
2437 t = pgnoNew[i];
2438 pT = apNew[i];
2439 pgnoNew[i] = pgnoNew[minI];
2440 apNew[i] = apNew[minI];
2441 pgnoNew[minI] = t;
2442 apNew[minI] = pT;
2443 }
2444 }
2445
2446 /*
drh14acc042001-06-10 19:56:58 +00002447 ** Evenly distribute the data in apCell[] across the new pages.
2448 ** Insert divider cells into pParent as necessary.
2449 */
2450 j = 0;
2451 for(i=0; i<nNew; i++){
2452 MemPage *pNew = apNew[i];
drh6019e162001-07-02 17:51:45 +00002453 while( j<cntNew[i] ){
2454 assert( pNew->nFree>=szCell[j] );
drh14acc042001-06-10 19:56:58 +00002455 if( pCur && iCur==j ){ pCur->pPage = pNew; pCur->idx = pNew->nCell; }
drh0d316a42002-08-11 20:10:47 +00002456 insertCell(pBt, pNew, pNew->nCell, apCell[j], szCell[j]);
drh14acc042001-06-10 19:56:58 +00002457 j++;
2458 }
drh6019e162001-07-02 17:51:45 +00002459 assert( pNew->nCell>0 );
drh14acc042001-06-10 19:56:58 +00002460 assert( !pNew->isOverfull );
drh0d316a42002-08-11 20:10:47 +00002461 relinkCellList(pBt, pNew);
drh14acc042001-06-10 19:56:58 +00002462 if( i<nNew-1 && j<nCell ){
2463 pNew->u.hdr.rightChild = apCell[j]->h.leftChild;
drh0d316a42002-08-11 20:10:47 +00002464 apCell[j]->h.leftChild = SWAB32(pBt, pgnoNew[i]);
drh14acc042001-06-10 19:56:58 +00002465 if( pCur && iCur==j ){ pCur->pPage = pParent; pCur->idx = nxDiv; }
drh0d316a42002-08-11 20:10:47 +00002466 insertCell(pBt, pParent, nxDiv, apCell[j], szCell[j]);
drh14acc042001-06-10 19:56:58 +00002467 j++;
2468 nxDiv++;
2469 }
2470 }
drh6019e162001-07-02 17:51:45 +00002471 assert( j==nCell );
drh6b308672002-07-08 02:16:37 +00002472 apNew[nNew-1]->u.hdr.rightChild = aOld[nOld-1].u.hdr.rightChild;
drh14acc042001-06-10 19:56:58 +00002473 if( nxDiv==pParent->nCell ){
drh0d316a42002-08-11 20:10:47 +00002474 pParent->u.hdr.rightChild = SWAB32(pBt, pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00002475 }else{
drh0d316a42002-08-11 20:10:47 +00002476 pParent->apCell[nxDiv]->h.leftChild = SWAB32(pBt, pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00002477 }
2478 if( pCur ){
drh3fc190c2001-09-14 03:24:23 +00002479 if( j<=iCur && pCur->pPage==pParent && pCur->idx>idxDiv[nOld-1] ){
2480 assert( pCur->pPage==pOldCurPage );
2481 pCur->idx += nNew - nOld;
2482 }else{
2483 assert( pOldCurPage!=0 );
2484 sqlitepager_ref(pCur->pPage);
2485 sqlitepager_unref(pOldCurPage);
2486 }
drh14acc042001-06-10 19:56:58 +00002487 }
2488
2489 /*
2490 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00002491 */
2492 for(i=0; i<nNew; i++){
drh0d316a42002-08-11 20:10:47 +00002493 reparentChildPages(pBt, apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002494 }
drh0d316a42002-08-11 20:10:47 +00002495 reparentChildPages(pBt, pParent);
drh8b2f49b2001-06-08 00:21:52 +00002496
2497 /*
drh14acc042001-06-10 19:56:58 +00002498 ** balance the parent page.
drh8b2f49b2001-06-08 00:21:52 +00002499 */
drh5edc3122001-09-13 21:53:09 +00002500 rc = balance(pBt, pParent, pCur);
drh8b2f49b2001-06-08 00:21:52 +00002501
2502 /*
drh14acc042001-06-10 19:56:58 +00002503 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00002504 */
drh14acc042001-06-10 19:56:58 +00002505balance_cleanup:
drh9ca7d3b2001-06-28 11:50:21 +00002506 if( extraUnref ){
2507 sqlitepager_unref(extraUnref);
2508 }
drh8b2f49b2001-06-08 00:21:52 +00002509 for(i=0; i<nOld; i++){
drh6b308672002-07-08 02:16:37 +00002510 if( apOld[i]!=0 && apOld[i]!=&aOld[i] ) sqlitepager_unref(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00002511 }
drh14acc042001-06-10 19:56:58 +00002512 for(i=0; i<nNew; i++){
2513 sqlitepager_unref(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002514 }
drh14acc042001-06-10 19:56:58 +00002515 if( pCur && pCur->pPage==0 ){
2516 pCur->pPage = pParent;
2517 pCur->idx = 0;
2518 }else{
2519 sqlitepager_unref(pParent);
drh8b2f49b2001-06-08 00:21:52 +00002520 }
2521 return rc;
2522}
2523
2524/*
drhf74b8d92002-09-01 23:20:45 +00002525** This routine checks all cursors that point to the same table
2526** as pCur points to. If any of those cursors were opened with
2527** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
2528** cursors point to the same table were opened with wrFlag==1
2529** then this routine returns SQLITE_OK.
2530**
2531** In addition to checking for read-locks (where a read-lock
2532** means a cursor opened with wrFlag==0) this routine also moves
2533** all cursors other than pCur so that they are pointing to the
2534** first Cell on root page. This is necessary because an insert
2535** or delete might change the number of cells on a page or delete
2536** a page entirely and we do not want to leave any cursors
2537** pointing to non-existant pages or cells.
2538*/
2539static int checkReadLocks(BtCursor *pCur){
2540 BtCursor *p;
2541 assert( pCur->wrFlag );
2542 for(p=pCur->pShared; p!=pCur; p=p->pShared){
2543 assert( p );
2544 assert( p->pgnoRoot==pCur->pgnoRoot );
2545 if( p->wrFlag==0 ) return SQLITE_LOCKED;
2546 if( sqlitepager_pagenumber(p->pPage)!=p->pgnoRoot ){
2547 moveToRoot(p);
2548 }
2549 }
2550 return SQLITE_OK;
2551}
2552
2553/*
drh3b7511c2001-05-26 13:15:44 +00002554** Insert a new record into the BTree. The key is given by (pKey,nKey)
2555** and the data is given by (pData,nData). The cursor is used only to
2556** define what database the record should be inserted into. The cursor
drh14acc042001-06-10 19:56:58 +00002557** is left pointing at the new record.
drh3b7511c2001-05-26 13:15:44 +00002558*/
2559int sqliteBtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00002560 BtCursor *pCur, /* Insert data into the table of this cursor */
drhbe0072d2001-09-13 14:46:09 +00002561 const void *pKey, int nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00002562 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00002563){
2564 Cell newCell;
2565 int rc;
2566 int loc;
drh14acc042001-06-10 19:56:58 +00002567 int szNew;
drh3b7511c2001-05-26 13:15:44 +00002568 MemPage *pPage;
2569 Btree *pBt = pCur->pBt;
2570
drhecdc7532001-09-23 02:35:53 +00002571 if( pCur->pPage==0 ){
2572 return SQLITE_ABORT; /* A rollback destroyed this cursor */
2573 }
drhf74b8d92002-09-01 23:20:45 +00002574 if( !pBt->inTrans || nKey+nData==0 ){
2575 /* Must start a transaction before doing an insert */
2576 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00002577 }
drhf74b8d92002-09-01 23:20:45 +00002578 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00002579 if( !pCur->wrFlag ){
2580 return SQLITE_PERM; /* Cursor not open for writing */
2581 }
drhf74b8d92002-09-01 23:20:45 +00002582 if( checkReadLocks(pCur) ){
2583 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
2584 }
drh14acc042001-06-10 19:56:58 +00002585 rc = sqliteBtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00002586 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002587 pPage = pCur->pPage;
drh7aa128d2002-06-21 13:09:16 +00002588 assert( pPage->isInit );
drh14acc042001-06-10 19:56:58 +00002589 rc = sqlitepager_write(pPage);
drhbd03cae2001-06-02 02:40:57 +00002590 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00002591 rc = fillInCell(pBt, &newCell, pKey, nKey, pData, nData);
2592 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002593 szNew = cellSize(pBt, &newCell);
drh3b7511c2001-05-26 13:15:44 +00002594 if( loc==0 ){
drh14acc042001-06-10 19:56:58 +00002595 newCell.h.leftChild = pPage->apCell[pCur->idx]->h.leftChild;
2596 rc = clearCell(pBt, pPage->apCell[pCur->idx]);
drh5e2f8b92001-05-28 00:41:15 +00002597 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002598 dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pPage->apCell[pCur->idx]));
drh7c717f72001-06-24 20:39:41 +00002599 }else if( loc<0 && pPage->nCell>0 ){
drh14acc042001-06-10 19:56:58 +00002600 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
2601 pCur->idx++;
2602 }else{
2603 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
drh3b7511c2001-05-26 13:15:44 +00002604 }
drh0d316a42002-08-11 20:10:47 +00002605 insertCell(pBt, pPage, pCur->idx, &newCell, szNew);
drh14acc042001-06-10 19:56:58 +00002606 rc = balance(pCur->pBt, pPage, pCur);
drh3fc190c2001-09-14 03:24:23 +00002607 /* sqliteBtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
2608 /* fflush(stdout); */
drh2dcc9aa2002-12-04 13:40:25 +00002609 pCur->eSkip = SKIP_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00002610 return rc;
2611}
2612
2613/*
drhbd03cae2001-06-02 02:40:57 +00002614** Delete the entry that the cursor is pointing to.
drh5e2f8b92001-05-28 00:41:15 +00002615**
drhbd03cae2001-06-02 02:40:57 +00002616** The cursor is left pointing at either the next or the previous
2617** entry. If the cursor is left pointing to the next entry, then
drh2dcc9aa2002-12-04 13:40:25 +00002618** the pCur->eSkip flag is set to SKIP_NEXT which forces the next call to
drhbd03cae2001-06-02 02:40:57 +00002619** sqliteBtreeNext() to be a no-op. That way, you can always call
2620** sqliteBtreeNext() after a delete and the cursor will be left
drh2dcc9aa2002-12-04 13:40:25 +00002621** pointing to the first entry after the deleted entry. Similarly,
2622** pCur->eSkip is set to SKIP_PREV is the cursor is left pointing to
2623** the entry prior to the deleted entry so that a subsequent call to
2624** sqliteBtreePrevious() will always leave the cursor pointing at the
2625** entry immediately before the one that was deleted.
drh3b7511c2001-05-26 13:15:44 +00002626*/
2627int sqliteBtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00002628 MemPage *pPage = pCur->pPage;
2629 Cell *pCell;
2630 int rc;
drh8c42ca92001-06-22 19:15:00 +00002631 Pgno pgnoChild;
drh0d316a42002-08-11 20:10:47 +00002632 Btree *pBt = pCur->pBt;
drh8b2f49b2001-06-08 00:21:52 +00002633
drh7aa128d2002-06-21 13:09:16 +00002634 assert( pPage->isInit );
drhecdc7532001-09-23 02:35:53 +00002635 if( pCur->pPage==0 ){
2636 return SQLITE_ABORT; /* A rollback destroyed this cursor */
2637 }
drhf74b8d92002-09-01 23:20:45 +00002638 if( !pBt->inTrans ){
2639 /* Must start a transaction before doing a delete */
2640 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00002641 }
drhf74b8d92002-09-01 23:20:45 +00002642 assert( !pBt->readOnly );
drhbd03cae2001-06-02 02:40:57 +00002643 if( pCur->idx >= pPage->nCell ){
2644 return SQLITE_ERROR; /* The cursor is not pointing to anything */
2645 }
drhecdc7532001-09-23 02:35:53 +00002646 if( !pCur->wrFlag ){
2647 return SQLITE_PERM; /* Did not open this cursor for writing */
2648 }
drhf74b8d92002-09-01 23:20:45 +00002649 if( checkReadLocks(pCur) ){
2650 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
2651 }
drhbd03cae2001-06-02 02:40:57 +00002652 rc = sqlitepager_write(pPage);
2653 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002654 pCell = pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00002655 pgnoChild = SWAB32(pBt, pCell->h.leftChild);
2656 clearCell(pBt, pCell);
drh14acc042001-06-10 19:56:58 +00002657 if( pgnoChild ){
2658 /*
drh5e00f6c2001-09-13 13:46:56 +00002659 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00002660 ** do something we will leave a hole on an internal page.
2661 ** We have to fill the hole by moving in a cell from a leaf. The
2662 ** next Cell after the one to be deleted is guaranteed to exist and
2663 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00002664 */
drh14acc042001-06-10 19:56:58 +00002665 BtCursor leafCur;
2666 Cell *pNext;
2667 int szNext;
drh8c1238a2003-01-02 14:43:55 +00002668 int notUsed;
drh14acc042001-06-10 19:56:58 +00002669 getTempCursor(pCur, &leafCur);
drh8c1238a2003-01-02 14:43:55 +00002670 rc = sqliteBtreeNext(&leafCur, &notUsed);
drh14acc042001-06-10 19:56:58 +00002671 if( rc!=SQLITE_OK ){
2672 return SQLITE_CORRUPT;
drh5e2f8b92001-05-28 00:41:15 +00002673 }
drh6019e162001-07-02 17:51:45 +00002674 rc = sqlitepager_write(leafCur.pPage);
2675 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002676 dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pCell));
drh8c42ca92001-06-22 19:15:00 +00002677 pNext = leafCur.pPage->apCell[leafCur.idx];
drh0d316a42002-08-11 20:10:47 +00002678 szNext = cellSize(pBt, pNext);
2679 pNext->h.leftChild = SWAB32(pBt, pgnoChild);
2680 insertCell(pBt, pPage, pCur->idx, pNext, szNext);
2681 rc = balance(pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002682 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00002683 pCur->eSkip = SKIP_NEXT;
drh0d316a42002-08-11 20:10:47 +00002684 dropCell(pBt, leafCur.pPage, leafCur.idx, szNext);
2685 rc = balance(pBt, leafCur.pPage, pCur);
drh8c42ca92001-06-22 19:15:00 +00002686 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00002687 }else{
drh0d316a42002-08-11 20:10:47 +00002688 dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pCell));
drh5edc3122001-09-13 21:53:09 +00002689 if( pCur->idx>=pPage->nCell ){
2690 pCur->idx = pPage->nCell-1;
drhf5bf0a72001-11-23 00:24:12 +00002691 if( pCur->idx<0 ){
2692 pCur->idx = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002693 pCur->eSkip = SKIP_NEXT;
drhf5bf0a72001-11-23 00:24:12 +00002694 }else{
drh2dcc9aa2002-12-04 13:40:25 +00002695 pCur->eSkip = SKIP_PREV;
drhf5bf0a72001-11-23 00:24:12 +00002696 }
drh6019e162001-07-02 17:51:45 +00002697 }else{
drh2dcc9aa2002-12-04 13:40:25 +00002698 pCur->eSkip = SKIP_NEXT;
drh6019e162001-07-02 17:51:45 +00002699 }
drh0d316a42002-08-11 20:10:47 +00002700 rc = balance(pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002701 }
drh5e2f8b92001-05-28 00:41:15 +00002702 return rc;
drh3b7511c2001-05-26 13:15:44 +00002703}
drh8b2f49b2001-06-08 00:21:52 +00002704
2705/*
drhc6b52df2002-01-04 03:09:29 +00002706** Create a new BTree table. Write into *piTable the page
2707** number for the root page of the new table.
2708**
2709** In the current implementation, BTree tables and BTree indices are the
2710** the same. But in the future, we may change this so that BTree tables
2711** are restricted to having a 4-byte integer key and arbitrary data and
2712** BTree indices are restricted to having an arbitrary key and no data.
drh8b2f49b2001-06-08 00:21:52 +00002713*/
2714int sqliteBtreeCreateTable(Btree *pBt, int *piTable){
2715 MemPage *pRoot;
2716 Pgno pgnoRoot;
2717 int rc;
2718 if( !pBt->inTrans ){
drhf74b8d92002-09-01 23:20:45 +00002719 /* Must start a transaction first */
2720 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00002721 }
drh5df72a52002-06-06 23:16:05 +00002722 if( pBt->readOnly ){
2723 return SQLITE_READONLY;
2724 }
drhbea00b92002-07-08 10:59:50 +00002725 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 0);
drh8b2f49b2001-06-08 00:21:52 +00002726 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002727 assert( sqlitepager_iswriteable(pRoot) );
drh0d316a42002-08-11 20:10:47 +00002728 zeroPage(pBt, pRoot);
drh8b2f49b2001-06-08 00:21:52 +00002729 sqlitepager_unref(pRoot);
2730 *piTable = (int)pgnoRoot;
2731 return SQLITE_OK;
2732}
2733
2734/*
drhc6b52df2002-01-04 03:09:29 +00002735** Create a new BTree index. Write into *piTable the page
2736** number for the root page of the new index.
2737**
2738** In the current implementation, BTree tables and BTree indices are the
2739** the same. But in the future, we may change this so that BTree tables
2740** are restricted to having a 4-byte integer key and arbitrary data and
2741** BTree indices are restricted to having an arbitrary key and no data.
2742*/
2743int sqliteBtreeCreateIndex(Btree *pBt, int *piIndex){
drh5df72a52002-06-06 23:16:05 +00002744 return sqliteBtreeCreateTable(pBt, piIndex);
drhc6b52df2002-01-04 03:09:29 +00002745}
2746
2747/*
drh8b2f49b2001-06-08 00:21:52 +00002748** Erase the given database page and all its children. Return
2749** the page to the freelist.
2750*/
drh2aa679f2001-06-25 02:11:07 +00002751static int clearDatabasePage(Btree *pBt, Pgno pgno, int freePageFlag){
drh8b2f49b2001-06-08 00:21:52 +00002752 MemPage *pPage;
2753 int rc;
drh8b2f49b2001-06-08 00:21:52 +00002754 Cell *pCell;
2755 int idx;
2756
drh8c42ca92001-06-22 19:15:00 +00002757 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pPage);
drh8b2f49b2001-06-08 00:21:52 +00002758 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002759 rc = sqlitepager_write(pPage);
2760 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002761 rc = initPage(pBt, pPage, pgno, 0);
drh7aa128d2002-06-21 13:09:16 +00002762 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002763 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh8b2f49b2001-06-08 00:21:52 +00002764 while( idx>0 ){
drh14acc042001-06-10 19:56:58 +00002765 pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +00002766 idx = SWAB16(pBt, pCell->h.iNext);
drh8b2f49b2001-06-08 00:21:52 +00002767 if( pCell->h.leftChild ){
drh0d316a42002-08-11 20:10:47 +00002768 rc = clearDatabasePage(pBt, SWAB32(pBt, pCell->h.leftChild), 1);
drh8b2f49b2001-06-08 00:21:52 +00002769 if( rc ) return rc;
2770 }
drh8c42ca92001-06-22 19:15:00 +00002771 rc = clearCell(pBt, pCell);
drh8b2f49b2001-06-08 00:21:52 +00002772 if( rc ) return rc;
2773 }
drh2aa679f2001-06-25 02:11:07 +00002774 if( pPage->u.hdr.rightChild ){
drh0d316a42002-08-11 20:10:47 +00002775 rc = clearDatabasePage(pBt, SWAB32(pBt, pPage->u.hdr.rightChild), 1);
drh2aa679f2001-06-25 02:11:07 +00002776 if( rc ) return rc;
2777 }
2778 if( freePageFlag ){
2779 rc = freePage(pBt, pPage, pgno);
2780 }else{
drh0d316a42002-08-11 20:10:47 +00002781 zeroPage(pBt, pPage);
drh2aa679f2001-06-25 02:11:07 +00002782 }
drhdd793422001-06-28 01:54:48 +00002783 sqlitepager_unref(pPage);
drh2aa679f2001-06-25 02:11:07 +00002784 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002785}
2786
2787/*
2788** Delete all information from a single table in the database.
2789*/
2790int sqliteBtreeClearTable(Btree *pBt, int iTable){
2791 int rc;
drhf74b8d92002-09-01 23:20:45 +00002792 BtCursor *pCur;
drh8b2f49b2001-06-08 00:21:52 +00002793 if( !pBt->inTrans ){
drhf74b8d92002-09-01 23:20:45 +00002794 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00002795 }
drhf74b8d92002-09-01 23:20:45 +00002796 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
2797 if( pCur->pgnoRoot==(Pgno)iTable ){
2798 if( pCur->wrFlag==0 ) return SQLITE_LOCKED;
2799 moveToRoot(pCur);
2800 }
drhecdc7532001-09-23 02:35:53 +00002801 }
drh2aa679f2001-06-25 02:11:07 +00002802 rc = clearDatabasePage(pBt, (Pgno)iTable, 0);
drh8b2f49b2001-06-08 00:21:52 +00002803 if( rc ){
2804 sqliteBtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00002805 }
drh8c42ca92001-06-22 19:15:00 +00002806 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002807}
2808
2809/*
2810** Erase all information in a table and add the root of the table to
2811** the freelist. Except, the root of the principle table (the one on
2812** page 2) is never added to the freelist.
2813*/
2814int sqliteBtreeDropTable(Btree *pBt, int iTable){
2815 int rc;
2816 MemPage *pPage;
drhf74b8d92002-09-01 23:20:45 +00002817 BtCursor *pCur;
drh8b2f49b2001-06-08 00:21:52 +00002818 if( !pBt->inTrans ){
drhf74b8d92002-09-01 23:20:45 +00002819 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00002820 }
drhf74b8d92002-09-01 23:20:45 +00002821 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
2822 if( pCur->pgnoRoot==(Pgno)iTable ){
2823 return SQLITE_LOCKED; /* Cannot drop a table that has a cursor */
2824 }
drh5df72a52002-06-06 23:16:05 +00002825 }
drh8c42ca92001-06-22 19:15:00 +00002826 rc = sqlitepager_get(pBt->pPager, (Pgno)iTable, (void**)&pPage);
drh2aa679f2001-06-25 02:11:07 +00002827 if( rc ) return rc;
2828 rc = sqliteBtreeClearTable(pBt, iTable);
2829 if( rc ) return rc;
2830 if( iTable>2 ){
2831 rc = freePage(pBt, pPage, iTable);
2832 }else{
drh0d316a42002-08-11 20:10:47 +00002833 zeroPage(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002834 }
drhdd793422001-06-28 01:54:48 +00002835 sqlitepager_unref(pPage);
drh8b2f49b2001-06-08 00:21:52 +00002836 return rc;
2837}
2838
2839/*
2840** Read the meta-information out of a database file.
2841*/
2842int sqliteBtreeGetMeta(Btree *pBt, int *aMeta){
2843 PageOne *pP1;
2844 int rc;
drh0d316a42002-08-11 20:10:47 +00002845 int i;
drh8b2f49b2001-06-08 00:21:52 +00002846
drh8c42ca92001-06-22 19:15:00 +00002847 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00002848 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002849 aMeta[0] = SWAB32(pBt, pP1->nFree);
2850 for(i=0; i<sizeof(pP1->aMeta)/sizeof(pP1->aMeta[0]); i++){
2851 aMeta[i+1] = SWAB32(pBt, pP1->aMeta[i]);
2852 }
drh8b2f49b2001-06-08 00:21:52 +00002853 sqlitepager_unref(pP1);
2854 return SQLITE_OK;
2855}
2856
2857/*
2858** Write meta-information back into the database.
2859*/
2860int sqliteBtreeUpdateMeta(Btree *pBt, int *aMeta){
2861 PageOne *pP1;
drh0d316a42002-08-11 20:10:47 +00002862 int rc, i;
drh8b2f49b2001-06-08 00:21:52 +00002863 if( !pBt->inTrans ){
drhf74b8d92002-09-01 23:20:45 +00002864 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +00002865 }
drh8b2f49b2001-06-08 00:21:52 +00002866 pP1 = pBt->page1;
2867 rc = sqlitepager_write(pP1);
drh9adf9ac2002-05-15 11:44:13 +00002868 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002869 for(i=0; i<sizeof(pP1->aMeta)/sizeof(pP1->aMeta[0]); i++){
2870 pP1->aMeta[i] = SWAB32(pBt, aMeta[i+1]);
2871 }
drh8b2f49b2001-06-08 00:21:52 +00002872 return SQLITE_OK;
2873}
drh8c42ca92001-06-22 19:15:00 +00002874
drh5eddca62001-06-30 21:53:53 +00002875/******************************************************************************
2876** The complete implementation of the BTree subsystem is above this line.
2877** All the code the follows is for testing and troubleshooting the BTree
2878** subsystem. None of the code that follows is used during normal operation.
drh5eddca62001-06-30 21:53:53 +00002879******************************************************************************/
drh5eddca62001-06-30 21:53:53 +00002880
drh8c42ca92001-06-22 19:15:00 +00002881/*
2882** Print a disassembly of the given page on standard output. This routine
2883** is used for debugging and testing only.
2884*/
drhaaab5722002-02-19 13:39:21 +00002885#ifdef SQLITE_TEST
drh6019e162001-07-02 17:51:45 +00002886int sqliteBtreePageDump(Btree *pBt, int pgno, int recursive){
drh8c42ca92001-06-22 19:15:00 +00002887 int rc;
2888 MemPage *pPage;
2889 int i, j;
2890 int nFree;
2891 u16 idx;
2892 char range[20];
2893 unsigned char payload[20];
2894 rc = sqlitepager_get(pBt->pPager, (Pgno)pgno, (void**)&pPage);
2895 if( rc ){
2896 return rc;
2897 }
drh6019e162001-07-02 17:51:45 +00002898 if( recursive ) printf("PAGE %d:\n", pgno);
drh8c42ca92001-06-22 19:15:00 +00002899 i = 0;
drh0d316a42002-08-11 20:10:47 +00002900 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh8c42ca92001-06-22 19:15:00 +00002901 while( idx>0 && idx<=SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2902 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +00002903 int sz = cellSize(pBt, pCell);
drh8c42ca92001-06-22 19:15:00 +00002904 sprintf(range,"%d..%d", idx, idx+sz-1);
drh0d316a42002-08-11 20:10:47 +00002905 sz = NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h);
drh8c42ca92001-06-22 19:15:00 +00002906 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
2907 memcpy(payload, pCell->aPayload, sz);
2908 for(j=0; j<sz; j++){
2909 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
2910 }
2911 payload[sz] = 0;
2912 printf(
drh6019e162001-07-02 17:51:45 +00002913 "cell %2d: i=%-10s chld=%-4d nk=%-4d nd=%-4d payload=%s\n",
drh0d316a42002-08-11 20:10:47 +00002914 i, range, (int)pCell->h.leftChild,
2915 NKEY(pBt, pCell->h), NDATA(pBt, pCell->h),
drh2aa679f2001-06-25 02:11:07 +00002916 payload
drh8c42ca92001-06-22 19:15:00 +00002917 );
drh6019e162001-07-02 17:51:45 +00002918 if( pPage->isInit && pPage->apCell[i]!=pCell ){
drh2aa679f2001-06-25 02:11:07 +00002919 printf("**** apCell[%d] does not match on prior entry ****\n", i);
2920 }
drh7c717f72001-06-24 20:39:41 +00002921 i++;
drh0d316a42002-08-11 20:10:47 +00002922 idx = SWAB16(pBt, pCell->h.iNext);
drh8c42ca92001-06-22 19:15:00 +00002923 }
2924 if( idx!=0 ){
2925 printf("ERROR: next cell index out of range: %d\n", idx);
2926 }
drh0d316a42002-08-11 20:10:47 +00002927 printf("right_child: %d\n", SWAB32(pBt, pPage->u.hdr.rightChild));
drh8c42ca92001-06-22 19:15:00 +00002928 nFree = 0;
2929 i = 0;
drh0d316a42002-08-11 20:10:47 +00002930 idx = SWAB16(pBt, pPage->u.hdr.firstFree);
drh8c42ca92001-06-22 19:15:00 +00002931 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2932 FreeBlk *p = (FreeBlk*)&pPage->u.aDisk[idx];
2933 sprintf(range,"%d..%d", idx, idx+p->iSize-1);
drh0d316a42002-08-11 20:10:47 +00002934 nFree += SWAB16(pBt, p->iSize);
drh8c42ca92001-06-22 19:15:00 +00002935 printf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
drh0d316a42002-08-11 20:10:47 +00002936 i, range, SWAB16(pBt, p->iSize), nFree);
2937 idx = SWAB16(pBt, p->iNext);
drh2aa679f2001-06-25 02:11:07 +00002938 i++;
drh8c42ca92001-06-22 19:15:00 +00002939 }
2940 if( idx!=0 ){
2941 printf("ERROR: next freeblock index out of range: %d\n", idx);
2942 }
drh6019e162001-07-02 17:51:45 +00002943 if( recursive && pPage->u.hdr.rightChild!=0 ){
drh0d316a42002-08-11 20:10:47 +00002944 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh6019e162001-07-02 17:51:45 +00002945 while( idx>0 && idx<SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2946 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +00002947 sqliteBtreePageDump(pBt, SWAB32(pBt, pCell->h.leftChild), 1);
2948 idx = SWAB16(pBt, pCell->h.iNext);
drh6019e162001-07-02 17:51:45 +00002949 }
drh0d316a42002-08-11 20:10:47 +00002950 sqliteBtreePageDump(pBt, SWAB32(pBt, pPage->u.hdr.rightChild), 1);
drh6019e162001-07-02 17:51:45 +00002951 }
drh8c42ca92001-06-22 19:15:00 +00002952 sqlitepager_unref(pPage);
2953 return SQLITE_OK;
2954}
drhaaab5722002-02-19 13:39:21 +00002955#endif
drh8c42ca92001-06-22 19:15:00 +00002956
drhaaab5722002-02-19 13:39:21 +00002957#ifdef SQLITE_TEST
drh8c42ca92001-06-22 19:15:00 +00002958/*
drh2aa679f2001-06-25 02:11:07 +00002959** Fill aResult[] with information about the entry and page that the
2960** cursor is pointing to.
2961**
2962** aResult[0] = The page number
2963** aResult[1] = The entry number
2964** aResult[2] = Total number of entries on this page
2965** aResult[3] = Size of this entry
2966** aResult[4] = Number of free bytes on this page
2967** aResult[5] = Number of free blocks on the page
2968** aResult[6] = Page number of the left child of this entry
2969** aResult[7] = Page number of the right child for the whole page
drh5eddca62001-06-30 21:53:53 +00002970**
2971** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00002972*/
2973int sqliteBtreeCursorDump(BtCursor *pCur, int *aResult){
drh2aa679f2001-06-25 02:11:07 +00002974 int cnt, idx;
2975 MemPage *pPage = pCur->pPage;
drh0d316a42002-08-11 20:10:47 +00002976 Btree *pBt = pCur->pBt;
drh2aa679f2001-06-25 02:11:07 +00002977 aResult[0] = sqlitepager_pagenumber(pPage);
drh8c42ca92001-06-22 19:15:00 +00002978 aResult[1] = pCur->idx;
drh2aa679f2001-06-25 02:11:07 +00002979 aResult[2] = pPage->nCell;
2980 if( pCur->idx>=0 && pCur->idx<pPage->nCell ){
drh0d316a42002-08-11 20:10:47 +00002981 aResult[3] = cellSize(pBt, pPage->apCell[pCur->idx]);
2982 aResult[6] = SWAB32(pBt, pPage->apCell[pCur->idx]->h.leftChild);
drh2aa679f2001-06-25 02:11:07 +00002983 }else{
2984 aResult[3] = 0;
2985 aResult[6] = 0;
2986 }
2987 aResult[4] = pPage->nFree;
2988 cnt = 0;
drh0d316a42002-08-11 20:10:47 +00002989 idx = SWAB16(pBt, pPage->u.hdr.firstFree);
drh2aa679f2001-06-25 02:11:07 +00002990 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2991 cnt++;
drh0d316a42002-08-11 20:10:47 +00002992 idx = SWAB16(pBt, ((FreeBlk*)&pPage->u.aDisk[idx])->iNext);
drh2aa679f2001-06-25 02:11:07 +00002993 }
2994 aResult[5] = cnt;
drh0d316a42002-08-11 20:10:47 +00002995 aResult[7] = SWAB32(pBt, pPage->u.hdr.rightChild);
drh8c42ca92001-06-22 19:15:00 +00002996 return SQLITE_OK;
2997}
drhaaab5722002-02-19 13:39:21 +00002998#endif
drhdd793422001-06-28 01:54:48 +00002999
drhaaab5722002-02-19 13:39:21 +00003000#ifdef SQLITE_TEST
drhdd793422001-06-28 01:54:48 +00003001/*
drh5eddca62001-06-30 21:53:53 +00003002** Return the pager associated with a BTree. This routine is used for
3003** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00003004*/
3005Pager *sqliteBtreePager(Btree *pBt){
3006 return pBt->pPager;
3007}
drhaaab5722002-02-19 13:39:21 +00003008#endif
drh5eddca62001-06-30 21:53:53 +00003009
3010/*
3011** This structure is passed around through all the sanity checking routines
3012** in order to keep track of some global state information.
3013*/
drhaaab5722002-02-19 13:39:21 +00003014typedef struct IntegrityCk IntegrityCk;
3015struct IntegrityCk {
drh100569d2001-10-02 13:01:48 +00003016 Btree *pBt; /* The tree being checked out */
3017 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
3018 int nPage; /* Number of pages in the database */
3019 int *anRef; /* Number of times each page is referenced */
3020 int nTreePage; /* Number of BTree pages */
3021 int nByte; /* Number of bytes of data stored on BTree pages */
3022 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00003023};
3024
3025/*
3026** Append a message to the error message string.
3027*/
drhaaab5722002-02-19 13:39:21 +00003028static void checkAppendMsg(IntegrityCk *pCheck, char *zMsg1, char *zMsg2){
drh5eddca62001-06-30 21:53:53 +00003029 if( pCheck->zErrMsg ){
3030 char *zOld = pCheck->zErrMsg;
3031 pCheck->zErrMsg = 0;
3032 sqliteSetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, 0);
3033 sqliteFree(zOld);
3034 }else{
3035 sqliteSetString(&pCheck->zErrMsg, zMsg1, zMsg2, 0);
3036 }
3037}
3038
3039/*
3040** Add 1 to the reference count for page iPage. If this is the second
3041** reference to the page, add an error message to pCheck->zErrMsg.
3042** Return 1 if there are 2 ore more references to the page and 0 if
3043** if this is the first reference to the page.
3044**
3045** Also check that the page number is in bounds.
3046*/
drhaaab5722002-02-19 13:39:21 +00003047static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00003048 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00003049 if( iPage>pCheck->nPage || iPage<0 ){
drh5eddca62001-06-30 21:53:53 +00003050 char zBuf[100];
3051 sprintf(zBuf, "invalid page number %d", iPage);
3052 checkAppendMsg(pCheck, zContext, zBuf);
3053 return 1;
3054 }
3055 if( pCheck->anRef[iPage]==1 ){
3056 char zBuf[100];
3057 sprintf(zBuf, "2nd reference to page %d", iPage);
3058 checkAppendMsg(pCheck, zContext, zBuf);
3059 return 1;
3060 }
3061 return (pCheck->anRef[iPage]++)>1;
3062}
3063
3064/*
3065** Check the integrity of the freelist or of an overflow page list.
3066** Verify that the number of pages on the list is N.
3067*/
drh30e58752002-03-02 20:41:57 +00003068static void checkList(
3069 IntegrityCk *pCheck, /* Integrity checking context */
3070 int isFreeList, /* True for a freelist. False for overflow page list */
3071 int iPage, /* Page number for first page in the list */
3072 int N, /* Expected number of pages in the list */
3073 char *zContext /* Context for error messages */
3074){
3075 int i;
drh5eddca62001-06-30 21:53:53 +00003076 char zMsg[100];
drh30e58752002-03-02 20:41:57 +00003077 while( N-- > 0 ){
drh5eddca62001-06-30 21:53:53 +00003078 OverflowPage *pOvfl;
3079 if( iPage<1 ){
3080 sprintf(zMsg, "%d pages missing from overflow list", N+1);
3081 checkAppendMsg(pCheck, zContext, zMsg);
3082 break;
3083 }
3084 if( checkRef(pCheck, iPage, zContext) ) break;
3085 if( sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
3086 sprintf(zMsg, "failed to get page %d", iPage);
3087 checkAppendMsg(pCheck, zContext, zMsg);
3088 break;
3089 }
drh30e58752002-03-02 20:41:57 +00003090 if( isFreeList ){
3091 FreelistInfo *pInfo = (FreelistInfo*)pOvfl->aPayload;
drh0d316a42002-08-11 20:10:47 +00003092 int n = SWAB32(pCheck->pBt, pInfo->nFree);
3093 for(i=0; i<n; i++){
3094 checkRef(pCheck, SWAB32(pCheck->pBt, pInfo->aFree[i]), zMsg);
drh30e58752002-03-02 20:41:57 +00003095 }
drh0d316a42002-08-11 20:10:47 +00003096 N -= n;
drh30e58752002-03-02 20:41:57 +00003097 }
drh0d316a42002-08-11 20:10:47 +00003098 iPage = SWAB32(pCheck->pBt, pOvfl->iNext);
drh5eddca62001-06-30 21:53:53 +00003099 sqlitepager_unref(pOvfl);
3100 }
3101}
3102
3103/*
drh1bffb9c2002-02-03 17:37:36 +00003104** Return negative if zKey1<zKey2.
3105** Return zero if zKey1==zKey2.
3106** Return positive if zKey1>zKey2.
3107*/
3108static int keyCompare(
3109 const char *zKey1, int nKey1,
3110 const char *zKey2, int nKey2
3111){
3112 int min = nKey1>nKey2 ? nKey2 : nKey1;
3113 int c = memcmp(zKey1, zKey2, min);
3114 if( c==0 ){
3115 c = nKey1 - nKey2;
3116 }
3117 return c;
3118}
3119
3120/*
drh5eddca62001-06-30 21:53:53 +00003121** Do various sanity checks on a single page of a tree. Return
3122** the tree depth. Root pages return 0. Parents of root pages
3123** return 1, and so forth.
3124**
3125** These checks are done:
3126**
3127** 1. Make sure that cells and freeblocks do not overlap
3128** but combine to completely cover the page.
3129** 2. Make sure cell keys are in order.
3130** 3. Make sure no key is less than or equal to zLowerBound.
3131** 4. Make sure no key is greater than or equal to zUpperBound.
3132** 5. Check the integrity of overflow pages.
3133** 6. Recursively call checkTreePage on all children.
3134** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00003135** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00003136** the root of the tree.
3137*/
3138static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00003139 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00003140 int iPage, /* Page number of the page to check */
3141 MemPage *pParent, /* Parent page */
3142 char *zParentContext, /* Parent context */
3143 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00003144 int nLower, /* Number of characters in zLowerBound */
3145 char *zUpperBound, /* All keys should be less than this, if not NULL */
3146 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00003147){
3148 MemPage *pPage;
3149 int i, rc, depth, d2, pgno;
3150 char *zKey1, *zKey2;
drh1bffb9c2002-02-03 17:37:36 +00003151 int nKey1, nKey2;
drh5eddca62001-06-30 21:53:53 +00003152 BtCursor cur;
drh0d316a42002-08-11 20:10:47 +00003153 Btree *pBt;
drh5eddca62001-06-30 21:53:53 +00003154 char zMsg[100];
3155 char zContext[100];
3156 char hit[SQLITE_PAGE_SIZE];
3157
3158 /* Check that the page exists
3159 */
drh0d316a42002-08-11 20:10:47 +00003160 cur.pBt = pBt = pCheck->pBt;
drh5eddca62001-06-30 21:53:53 +00003161 if( iPage==0 ) return 0;
3162 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
3163 sprintf(zContext, "On tree page %d: ", iPage);
3164 if( (rc = sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pPage))!=0 ){
3165 sprintf(zMsg, "unable to get the page. error code=%d", rc);
3166 checkAppendMsg(pCheck, zContext, zMsg);
3167 return 0;
3168 }
drh0d316a42002-08-11 20:10:47 +00003169 if( (rc = initPage(pBt, pPage, (Pgno)iPage, pParent))!=0 ){
drh5eddca62001-06-30 21:53:53 +00003170 sprintf(zMsg, "initPage() returns error code %d", rc);
3171 checkAppendMsg(pCheck, zContext, zMsg);
3172 sqlitepager_unref(pPage);
3173 return 0;
3174 }
3175
3176 /* Check out all the cells.
3177 */
3178 depth = 0;
drh1bffb9c2002-02-03 17:37:36 +00003179 if( zLowerBound ){
3180 zKey1 = sqliteMalloc( nLower+1 );
3181 memcpy(zKey1, zLowerBound, nLower);
3182 zKey1[nLower] = 0;
3183 }else{
3184 zKey1 = 0;
3185 }
3186 nKey1 = nLower;
drh5eddca62001-06-30 21:53:53 +00003187 cur.pPage = pPage;
drh5eddca62001-06-30 21:53:53 +00003188 for(i=0; i<pPage->nCell; i++){
3189 Cell *pCell = pPage->apCell[i];
3190 int sz;
3191
3192 /* Check payload overflow pages
3193 */
drh0d316a42002-08-11 20:10:47 +00003194 nKey2 = NKEY(pBt, pCell->h);
3195 sz = nKey2 + NDATA(pBt, pCell->h);
drh5eddca62001-06-30 21:53:53 +00003196 sprintf(zContext, "On page %d cell %d: ", iPage, i);
3197 if( sz>MX_LOCAL_PAYLOAD ){
3198 int nPage = (sz - MX_LOCAL_PAYLOAD + OVERFLOW_SIZE - 1)/OVERFLOW_SIZE;
drh0d316a42002-08-11 20:10:47 +00003199 checkList(pCheck, 0, SWAB32(pBt, pCell->ovfl), nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00003200 }
3201
3202 /* Check that keys are in the right order
3203 */
3204 cur.idx = i;
drh8c1238a2003-01-02 14:43:55 +00003205 zKey2 = sqliteMallocRaw( nKey2+1 );
drh1bffb9c2002-02-03 17:37:36 +00003206 getPayload(&cur, 0, nKey2, zKey2);
3207 if( zKey1 && keyCompare(zKey1, nKey1, zKey2, nKey2)>=0 ){
drh5eddca62001-06-30 21:53:53 +00003208 checkAppendMsg(pCheck, zContext, "Key is out of order");
3209 }
3210
3211 /* Check sanity of left child page.
3212 */
drh0d316a42002-08-11 20:10:47 +00003213 pgno = SWAB32(pBt, pCell->h.leftChild);
drh1bffb9c2002-02-03 17:37:36 +00003214 d2 = checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zKey2,nKey2);
drh5eddca62001-06-30 21:53:53 +00003215 if( i>0 && d2!=depth ){
3216 checkAppendMsg(pCheck, zContext, "Child page depth differs");
3217 }
3218 depth = d2;
3219 sqliteFree(zKey1);
3220 zKey1 = zKey2;
drh1bffb9c2002-02-03 17:37:36 +00003221 nKey1 = nKey2;
drh5eddca62001-06-30 21:53:53 +00003222 }
drh0d316a42002-08-11 20:10:47 +00003223 pgno = SWAB32(pBt, pPage->u.hdr.rightChild);
drh5eddca62001-06-30 21:53:53 +00003224 sprintf(zContext, "On page %d at right child: ", iPage);
drh1bffb9c2002-02-03 17:37:36 +00003225 checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zUpperBound,nUpper);
drh5eddca62001-06-30 21:53:53 +00003226 sqliteFree(zKey1);
3227
3228 /* Check for complete coverage of the page
3229 */
3230 memset(hit, 0, sizeof(hit));
3231 memset(hit, 1, sizeof(PageHdr));
drh0d316a42002-08-11 20:10:47 +00003232 for(i=SWAB16(pBt, pPage->u.hdr.firstCell); i>0 && i<SQLITE_PAGE_SIZE; ){
drh5eddca62001-06-30 21:53:53 +00003233 Cell *pCell = (Cell*)&pPage->u.aDisk[i];
3234 int j;
drh0d316a42002-08-11 20:10:47 +00003235 for(j=i+cellSize(pBt, pCell)-1; j>=i; j--) hit[j]++;
3236 i = SWAB16(pBt, pCell->h.iNext);
drh5eddca62001-06-30 21:53:53 +00003237 }
drh0d316a42002-08-11 20:10:47 +00003238 for(i=SWAB16(pBt,pPage->u.hdr.firstFree); i>0 && i<SQLITE_PAGE_SIZE; ){
drh5eddca62001-06-30 21:53:53 +00003239 FreeBlk *pFBlk = (FreeBlk*)&pPage->u.aDisk[i];
3240 int j;
drh0d316a42002-08-11 20:10:47 +00003241 for(j=i+SWAB16(pBt,pFBlk->iSize)-1; j>=i; j--) hit[j]++;
3242 i = SWAB16(pBt,pFBlk->iNext);
drh5eddca62001-06-30 21:53:53 +00003243 }
3244 for(i=0; i<SQLITE_PAGE_SIZE; i++){
3245 if( hit[i]==0 ){
3246 sprintf(zMsg, "Unused space at byte %d of page %d", i, iPage);
3247 checkAppendMsg(pCheck, zMsg, 0);
3248 break;
3249 }else if( hit[i]>1 ){
3250 sprintf(zMsg, "Multiple uses for byte %d of page %d", i, iPage);
3251 checkAppendMsg(pCheck, zMsg, 0);
3252 break;
3253 }
3254 }
3255
3256 /* Check that free space is kept to a minimum
3257 */
drh6019e162001-07-02 17:51:45 +00003258#if 0
3259 if( pParent && pParent->nCell>2 && pPage->nFree>3*SQLITE_PAGE_SIZE/4 ){
drh5eddca62001-06-30 21:53:53 +00003260 sprintf(zMsg, "free space (%d) greater than max (%d)", pPage->nFree,
3261 SQLITE_PAGE_SIZE/3);
3262 checkAppendMsg(pCheck, zContext, zMsg);
3263 }
drh6019e162001-07-02 17:51:45 +00003264#endif
3265
3266 /* Update freespace totals.
3267 */
3268 pCheck->nTreePage++;
3269 pCheck->nByte += USABLE_SPACE - pPage->nFree;
drh5eddca62001-06-30 21:53:53 +00003270
3271 sqlitepager_unref(pPage);
3272 return depth;
3273}
3274
3275/*
3276** This routine does a complete check of the given BTree file. aRoot[] is
3277** an array of pages numbers were each page number is the root page of
3278** a table. nRoot is the number of entries in aRoot.
3279**
3280** If everything checks out, this routine returns NULL. If something is
3281** amiss, an error message is written into memory obtained from malloc()
3282** and a pointer to that error message is returned. The calling function
3283** is responsible for freeing the error message when it is done.
3284*/
drhaaab5722002-02-19 13:39:21 +00003285char *sqliteBtreeIntegrityCheck(Btree *pBt, int *aRoot, int nRoot){
drh5eddca62001-06-30 21:53:53 +00003286 int i;
3287 int nRef;
drhaaab5722002-02-19 13:39:21 +00003288 IntegrityCk sCheck;
drh5eddca62001-06-30 21:53:53 +00003289
3290 nRef = *sqlitepager_stats(pBt->pPager);
drhefc251d2001-07-01 22:12:01 +00003291 if( lockBtree(pBt)!=SQLITE_OK ){
3292 return sqliteStrDup("Unable to acquire a read lock on the database");
3293 }
drh5eddca62001-06-30 21:53:53 +00003294 sCheck.pBt = pBt;
3295 sCheck.pPager = pBt->pPager;
3296 sCheck.nPage = sqlitepager_pagecount(sCheck.pPager);
drh0de8c112002-07-06 16:32:14 +00003297 if( sCheck.nPage==0 ){
3298 unlockBtreeIfUnused(pBt);
3299 return 0;
3300 }
drh8c1238a2003-01-02 14:43:55 +00003301 sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
drh5eddca62001-06-30 21:53:53 +00003302 sCheck.anRef[1] = 1;
3303 for(i=2; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
3304 sCheck.zErrMsg = 0;
3305
3306 /* Check the integrity of the freelist
3307 */
drh0d316a42002-08-11 20:10:47 +00003308 checkList(&sCheck, 1, SWAB32(pBt, pBt->page1->freeList),
3309 SWAB32(pBt, pBt->page1->nFree), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00003310
3311 /* Check all the tables.
3312 */
3313 for(i=0; i<nRoot; i++){
drh4ff6dfa2002-03-03 23:06:00 +00003314 if( aRoot[i]==0 ) continue;
drh1bffb9c2002-02-03 17:37:36 +00003315 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00003316 }
3317
3318 /* Make sure every page in the file is referenced
3319 */
3320 for(i=1; i<=sCheck.nPage; i++){
3321 if( sCheck.anRef[i]==0 ){
3322 char zBuf[100];
3323 sprintf(zBuf, "Page %d is never used", i);
3324 checkAppendMsg(&sCheck, zBuf, 0);
3325 }
3326 }
3327
3328 /* Make sure this analysis did not leave any unref() pages
3329 */
drh5e00f6c2001-09-13 13:46:56 +00003330 unlockBtreeIfUnused(pBt);
drh5eddca62001-06-30 21:53:53 +00003331 if( nRef != *sqlitepager_stats(pBt->pPager) ){
3332 char zBuf[100];
3333 sprintf(zBuf,
3334 "Outstanding page count goes from %d to %d during this analysis",
3335 nRef, *sqlitepager_stats(pBt->pPager)
3336 );
3337 checkAppendMsg(&sCheck, zBuf, 0);
3338 }
3339
3340 /* Clean up and report errors.
3341 */
3342 sqliteFree(sCheck.anRef);
3343 return sCheck.zErrMsg;
3344}