blob: 564d9ad878b4005452426bb728d7e6c3c27d730f [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*************************************************************************
drh8178a752003-01-05 21:41:40 +000012** $Id: btree.c,v 1.80 2003/01/05 21:41:41 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/*
drh8178a752003-01-05 21:41:40 +00001341** Move the cursor down to a new child page. The newPgno argument is the
1342** page number of the child page in the byte order of the disk image.
drh72f82862001-05-24 21:06:34 +00001343*/
drh5e2f8b92001-05-28 00:41:15 +00001344static int moveToChild(BtCursor *pCur, int newPgno){
drh72f82862001-05-24 21:06:34 +00001345 int rc;
1346 MemPage *pNewPage;
drh0d316a42002-08-11 20:10:47 +00001347 Btree *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00001348
drh8178a752003-01-05 21:41:40 +00001349 newPgno = SWAB32(pBt, newPgno);
drh0d316a42002-08-11 20:10:47 +00001350 rc = sqlitepager_get(pBt->pPager, newPgno, (void**)&pNewPage);
drh6019e162001-07-02 17:51:45 +00001351 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001352 rc = initPage(pBt, pNewPage, newPgno, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00001353 if( rc ) return rc;
drh428ae8c2003-01-04 16:48:09 +00001354 assert( pCur->idx>=pCur->pPage->nCell
1355 || pCur->pPage->apCell[pCur->idx]->h.leftChild==SWAB32(pBt,newPgno) );
1356 assert( pCur->idx<pCur->pPage->nCell
1357 || pCur->pPage->u.hdr.rightChild==SWAB32(pBt,newPgno) );
1358 pNewPage->idxParent = pCur->idx;
1359 pCur->pPage->idxShift = 0;
drh72f82862001-05-24 21:06:34 +00001360 sqlitepager_unref(pCur->pPage);
1361 pCur->pPage = pNewPage;
1362 pCur->idx = 0;
1363 return SQLITE_OK;
1364}
1365
1366/*
drh5e2f8b92001-05-28 00:41:15 +00001367** Move the cursor up to the parent page.
1368**
1369** pCur->idx is set to the cell index that contains the pointer
1370** to the page we are coming from. If we are coming from the
1371** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00001372** the largest cell index.
drh72f82862001-05-24 21:06:34 +00001373*/
drh8178a752003-01-05 21:41:40 +00001374static void moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001375 Pgno oldPgno;
1376 MemPage *pParent;
drh8178a752003-01-05 21:41:40 +00001377 MemPage *pPage;
drh428ae8c2003-01-04 16:48:09 +00001378 int idxParent;
drh8178a752003-01-05 21:41:40 +00001379 pPage = pCur->pPage;
1380 assert( pPage!=0 );
1381 pParent = pPage->pParent;
1382 assert( pParent!=0 );
1383 idxParent = pPage->idxParent;
drh72f82862001-05-24 21:06:34 +00001384 sqlitepager_ref(pParent);
drh8178a752003-01-05 21:41:40 +00001385 sqlitepager_unref(pPage);
drh72f82862001-05-24 21:06:34 +00001386 pCur->pPage = pParent;
drh428ae8c2003-01-04 16:48:09 +00001387 assert( pParent->idxShift==0 );
1388 if( pParent->idxShift==0 ){
1389 pCur->idx = idxParent;
1390#ifndef NDEBUG
1391 /* Verify that pCur->idx is the correct index to point back to the child
1392 ** page we just came from
1393 */
drh8178a752003-01-05 21:41:40 +00001394 oldPgno = SWAB32(pCur->pBt, sqlitepager_pagenumber(pPage));
drh428ae8c2003-01-04 16:48:09 +00001395 if( pCur->idx<pParent->nCell ){
1396 assert( pParent->apCell[idxParent]->h.leftChild==oldPgno );
1397 }else{
1398 assert( pParent->u.hdr.rightChild==oldPgno );
1399 }
1400#endif
1401 }else{
1402 /* The MemPage.idxShift flag indicates that cell indices might have
1403 ** changed since idxParent was set and hence idxParent might be out
1404 ** of date. So recompute the parent cell index by scanning all cells
1405 ** and locating the one that points to the child we just came from.
1406 */
1407 int i;
1408 pCur->idx = pParent->nCell;
drh8178a752003-01-05 21:41:40 +00001409 oldPgno = SWAB32(pCur->pBt, sqlitepager_pagenumber(pPage));
drh428ae8c2003-01-04 16:48:09 +00001410 for(i=0; i<pParent->nCell; i++){
1411 if( pParent->apCell[i]->h.leftChild==oldPgno ){
1412 pCur->idx = i;
1413 break;
1414 }
drh72f82862001-05-24 21:06:34 +00001415 }
1416 }
1417}
1418
1419/*
1420** Move the cursor to the root page
1421*/
drh5e2f8b92001-05-28 00:41:15 +00001422static int moveToRoot(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001423 MemPage *pNew;
drhbd03cae2001-06-02 02:40:57 +00001424 int rc;
drh0d316a42002-08-11 20:10:47 +00001425 Btree *pBt = pCur->pBt;
drhbd03cae2001-06-02 02:40:57 +00001426
drh0d316a42002-08-11 20:10:47 +00001427 rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pNew);
drhbd03cae2001-06-02 02:40:57 +00001428 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001429 rc = initPage(pBt, pNew, pCur->pgnoRoot, 0);
drh6019e162001-07-02 17:51:45 +00001430 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001431 sqlitepager_unref(pCur->pPage);
1432 pCur->pPage = pNew;
1433 pCur->idx = 0;
1434 return SQLITE_OK;
1435}
drh2af926b2001-05-15 00:39:25 +00001436
drh5e2f8b92001-05-28 00:41:15 +00001437/*
1438** Move the cursor down to the left-most leaf entry beneath the
1439** entry to which it is currently pointing.
1440*/
1441static int moveToLeftmost(BtCursor *pCur){
1442 Pgno pgno;
1443 int rc;
1444
1445 while( (pgno = pCur->pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
drh8178a752003-01-05 21:41:40 +00001446 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00001447 if( rc ) return rc;
1448 }
1449 return SQLITE_OK;
1450}
1451
drh2dcc9aa2002-12-04 13:40:25 +00001452/*
1453** Move the cursor down to the right-most leaf entry beneath the
1454** page to which it is currently pointing. Notice the difference
1455** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
1456** finds the left-most entry beneath the *entry* whereas moveToRightmost()
1457** finds the right-most entry beneath the *page*.
1458*/
1459static int moveToRightmost(BtCursor *pCur){
1460 Pgno pgno;
1461 int rc;
1462
1463 while( (pgno = pCur->pPage->u.hdr.rightChild)!=0 ){
drh428ae8c2003-01-04 16:48:09 +00001464 pCur->idx = pCur->pPage->nCell;
drh8178a752003-01-05 21:41:40 +00001465 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00001466 if( rc ) return rc;
1467 }
1468 pCur->idx = pCur->pPage->nCell - 1;
1469 return SQLITE_OK;
1470}
1471
drh5e00f6c2001-09-13 13:46:56 +00001472/* Move the cursor to the first entry in the table. Return SQLITE_OK
1473** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00001474** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00001475*/
1476int sqliteBtreeFirst(BtCursor *pCur, int *pRes){
1477 int rc;
drhecdc7532001-09-23 02:35:53 +00001478 if( pCur->pPage==0 ) return SQLITE_ABORT;
drh5e00f6c2001-09-13 13:46:56 +00001479 rc = moveToRoot(pCur);
1480 if( rc ) return rc;
1481 if( pCur->pPage->nCell==0 ){
1482 *pRes = 1;
1483 return SQLITE_OK;
1484 }
1485 *pRes = 0;
1486 rc = moveToLeftmost(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00001487 pCur->eSkip = SKIP_NONE;
drh5e00f6c2001-09-13 13:46:56 +00001488 return rc;
1489}
drh5e2f8b92001-05-28 00:41:15 +00001490
drh9562b552002-02-19 15:00:07 +00001491/* Move the cursor to the last entry in the table. Return SQLITE_OK
1492** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00001493** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00001494*/
1495int sqliteBtreeLast(BtCursor *pCur, int *pRes){
1496 int rc;
drh9562b552002-02-19 15:00:07 +00001497 if( pCur->pPage==0 ) return SQLITE_ABORT;
1498 rc = moveToRoot(pCur);
1499 if( rc ) return rc;
drh7aa128d2002-06-21 13:09:16 +00001500 assert( pCur->pPage->isInit );
drh9562b552002-02-19 15:00:07 +00001501 if( pCur->pPage->nCell==0 ){
1502 *pRes = 1;
1503 return SQLITE_OK;
1504 }
1505 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00001506 rc = moveToRightmost(pCur);
1507 pCur->eSkip = SKIP_NONE;
drh9562b552002-02-19 15:00:07 +00001508 return rc;
1509}
1510
drha059ad02001-04-17 20:09:11 +00001511/* Move the cursor so that it points to an entry near pKey.
drh72f82862001-05-24 21:06:34 +00001512** Return a success code.
1513**
drh5e2f8b92001-05-28 00:41:15 +00001514** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00001515** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00001516** were present. The cursor might point to an entry that comes
1517** before or after the key.
1518**
drhbd03cae2001-06-02 02:40:57 +00001519** The result of comparing the key with the entry to which the
1520** cursor is left pointing is stored in pCur->iMatch. The same
1521** value is also written to *pRes if pRes!=NULL. The meaning of
1522** this value is as follows:
1523**
1524** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00001525** is smaller than pKey or if the table is empty
1526** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00001527**
1528** *pRes==0 The cursor is left pointing at an entry that
1529** exactly matches pKey.
1530**
1531** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001532** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00001533*/
drh5c4d9702001-08-20 00:33:58 +00001534int sqliteBtreeMoveto(BtCursor *pCur, const void *pKey, int nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00001535 int rc;
drhecdc7532001-09-23 02:35:53 +00001536 if( pCur->pPage==0 ) return SQLITE_ABORT;
drh2dcc9aa2002-12-04 13:40:25 +00001537 pCur->eSkip = SKIP_NONE;
drh5e2f8b92001-05-28 00:41:15 +00001538 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00001539 if( rc ) return rc;
1540 for(;;){
1541 int lwr, upr;
1542 Pgno chldPg;
1543 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00001544 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00001545 lwr = 0;
1546 upr = pPage->nCell-1;
1547 while( lwr<=upr ){
drh72f82862001-05-24 21:06:34 +00001548 pCur->idx = (lwr+upr)/2;
drh8721ce42001-11-07 14:22:00 +00001549 rc = sqliteBtreeKeyCompare(pCur, pKey, nKey, 0, &c);
drh72f82862001-05-24 21:06:34 +00001550 if( rc ) return rc;
1551 if( c==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001552 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001553 if( pRes ) *pRes = 0;
1554 return SQLITE_OK;
1555 }
1556 if( c<0 ){
1557 lwr = pCur->idx+1;
1558 }else{
1559 upr = pCur->idx-1;
1560 }
1561 }
1562 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00001563 assert( pPage->isInit );
drh72f82862001-05-24 21:06:34 +00001564 if( lwr>=pPage->nCell ){
drh14acc042001-06-10 19:56:58 +00001565 chldPg = pPage->u.hdr.rightChild;
drh72f82862001-05-24 21:06:34 +00001566 }else{
drh5e2f8b92001-05-28 00:41:15 +00001567 chldPg = pPage->apCell[lwr]->h.leftChild;
drh72f82862001-05-24 21:06:34 +00001568 }
1569 if( chldPg==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001570 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001571 if( pRes ) *pRes = c;
1572 return SQLITE_OK;
1573 }
drh428ae8c2003-01-04 16:48:09 +00001574 pCur->idx = lwr;
drh8178a752003-01-05 21:41:40 +00001575 rc = moveToChild(pCur, chldPg);
drh72f82862001-05-24 21:06:34 +00001576 if( rc ) return rc;
1577 }
drhbd03cae2001-06-02 02:40:57 +00001578 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00001579}
1580
1581/*
drhbd03cae2001-06-02 02:40:57 +00001582** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00001583** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00001584** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00001585** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00001586*/
1587int sqliteBtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00001588 int rc;
drh8178a752003-01-05 21:41:40 +00001589 MemPage *pPage = pCur->pPage;
drh8c1238a2003-01-02 14:43:55 +00001590 assert( pRes!=0 );
drh8178a752003-01-05 21:41:40 +00001591 if( pPage==0 ){
drh8c1238a2003-01-02 14:43:55 +00001592 *pRes = 1;
drhecdc7532001-09-23 02:35:53 +00001593 return SQLITE_ABORT;
1594 }
drh8178a752003-01-05 21:41:40 +00001595 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00001596 assert( pCur->eSkip!=SKIP_INVALID );
drh8178a752003-01-05 21:41:40 +00001597 if( pPage->nCell==0 ){
drh8c1238a2003-01-02 14:43:55 +00001598 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00001599 return SQLITE_OK;
1600 }
drh8178a752003-01-05 21:41:40 +00001601 assert( pCur->idx<pPage->nCell );
drh2dcc9aa2002-12-04 13:40:25 +00001602 if( pCur->eSkip==SKIP_NEXT ){
1603 pCur->eSkip = SKIP_NONE;
drh8c1238a2003-01-02 14:43:55 +00001604 *pRes = 0;
drh72f82862001-05-24 21:06:34 +00001605 return SQLITE_OK;
1606 }
drh2dcc9aa2002-12-04 13:40:25 +00001607 pCur->eSkip = SKIP_NONE;
drh72f82862001-05-24 21:06:34 +00001608 pCur->idx++;
drh8178a752003-01-05 21:41:40 +00001609 if( pCur->idx>=pPage->nCell ){
1610 if( pPage->u.hdr.rightChild ){
1611 rc = moveToChild(pCur, pPage->u.hdr.rightChild);
drh5e2f8b92001-05-28 00:41:15 +00001612 if( rc ) return rc;
1613 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00001614 *pRes = 0;
1615 return rc;
drh72f82862001-05-24 21:06:34 +00001616 }
drh5e2f8b92001-05-28 00:41:15 +00001617 do{
drh8178a752003-01-05 21:41:40 +00001618 if( pPage->pParent==0 ){
drh8c1238a2003-01-02 14:43:55 +00001619 *pRes = 1;
drh5e2f8b92001-05-28 00:41:15 +00001620 return SQLITE_OK;
1621 }
drh8178a752003-01-05 21:41:40 +00001622 moveToParent(pCur);
1623 pPage = pCur->pPage;
1624 }while( pCur->idx>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00001625 *pRes = 0;
drh8178a752003-01-05 21:41:40 +00001626 return SQLITE_OK;
1627 }
1628 *pRes = 0;
1629 if( pPage->u.hdr.rightChild==0 ){
1630 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00001631 }
drh5e2f8b92001-05-28 00:41:15 +00001632 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00001633 return rc;
drh72f82862001-05-24 21:06:34 +00001634}
1635
drh3b7511c2001-05-26 13:15:44 +00001636/*
drh2dcc9aa2002-12-04 13:40:25 +00001637** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00001638** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00001639** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00001640** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00001641*/
1642int sqliteBtreePrevious(BtCursor *pCur, int *pRes){
1643 int rc;
1644 Pgno pgno;
drh8178a752003-01-05 21:41:40 +00001645 MemPage *pPage;
1646 pPage = pCur->pPage;
1647 if( pPage==0 ){
1648 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00001649 return SQLITE_ABORT;
1650 }
drh8178a752003-01-05 21:41:40 +00001651 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00001652 assert( pCur->eSkip!=SKIP_INVALID );
drh8178a752003-01-05 21:41:40 +00001653 if( pPage->nCell==0 ){
1654 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00001655 return SQLITE_OK;
1656 }
1657 if( pCur->eSkip==SKIP_PREV ){
1658 pCur->eSkip = SKIP_NONE;
drh8178a752003-01-05 21:41:40 +00001659 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00001660 return SQLITE_OK;
1661 }
1662 pCur->eSkip = SKIP_NONE;
1663 assert( pCur->idx>=0 );
drh8178a752003-01-05 21:41:40 +00001664 if( (pgno = pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
1665 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00001666 if( rc ) return rc;
1667 rc = moveToRightmost(pCur);
1668 }else{
1669 while( pCur->idx==0 ){
drh8178a752003-01-05 21:41:40 +00001670 if( pPage->pParent==0 ){
drh2dcc9aa2002-12-04 13:40:25 +00001671 if( pRes ) *pRes = 1;
1672 return SQLITE_OK;
1673 }
drh8178a752003-01-05 21:41:40 +00001674 moveToParent(pCur);
1675 pPage = pCur->pPage;
drh2dcc9aa2002-12-04 13:40:25 +00001676 }
1677 pCur->idx--;
1678 rc = SQLITE_OK;
1679 }
drh8178a752003-01-05 21:41:40 +00001680 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00001681 return rc;
1682}
1683
1684/*
drh3b7511c2001-05-26 13:15:44 +00001685** Allocate a new page from the database file.
1686**
1687** The new page is marked as dirty. (In other words, sqlitepager_write()
1688** has already been called on the new page.) The new page has also
1689** been referenced and the calling routine is responsible for calling
1690** sqlitepager_unref() on the new page when it is done.
1691**
1692** SQLITE_OK is returned on success. Any other return value indicates
1693** an error. *ppPage and *pPgno are undefined in the event of an error.
1694** Do not invoke sqlitepager_unref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00001695**
drh199e3cf2002-07-18 11:01:47 +00001696** If the "nearby" parameter is not 0, then a (feeble) effort is made to
1697** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00001698** attempt to keep related pages close to each other in the database file,
1699** which in turn can make database access faster.
drh3b7511c2001-05-26 13:15:44 +00001700*/
drh199e3cf2002-07-18 11:01:47 +00001701static int allocatePage(Btree *pBt, MemPage **ppPage, Pgno *pPgno, Pgno nearby){
drhbd03cae2001-06-02 02:40:57 +00001702 PageOne *pPage1 = pBt->page1;
drh8c42ca92001-06-22 19:15:00 +00001703 int rc;
drh3b7511c2001-05-26 13:15:44 +00001704 if( pPage1->freeList ){
1705 OverflowPage *pOvfl;
drh30e58752002-03-02 20:41:57 +00001706 FreelistInfo *pInfo;
1707
drh3b7511c2001-05-26 13:15:44 +00001708 rc = sqlitepager_write(pPage1);
1709 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001710 SWAB_ADD(pBt, pPage1->nFree, -1);
1711 rc = sqlitepager_get(pBt->pPager, SWAB32(pBt, pPage1->freeList),
1712 (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001713 if( rc ) return rc;
1714 rc = sqlitepager_write(pOvfl);
1715 if( rc ){
1716 sqlitepager_unref(pOvfl);
1717 return rc;
1718 }
drh30e58752002-03-02 20:41:57 +00001719 pInfo = (FreelistInfo*)pOvfl->aPayload;
1720 if( pInfo->nFree==0 ){
drh0d316a42002-08-11 20:10:47 +00001721 *pPgno = SWAB32(pBt, pPage1->freeList);
drh30e58752002-03-02 20:41:57 +00001722 pPage1->freeList = pOvfl->iNext;
1723 *ppPage = (MemPage*)pOvfl;
1724 }else{
drh0d316a42002-08-11 20:10:47 +00001725 int closest, n;
1726 n = SWAB32(pBt, pInfo->nFree);
1727 if( n>1 && nearby>0 ){
drhbea00b92002-07-08 10:59:50 +00001728 int i, dist;
1729 closest = 0;
drh0d316a42002-08-11 20:10:47 +00001730 dist = SWAB32(pBt, pInfo->aFree[0]) - nearby;
drhbea00b92002-07-08 10:59:50 +00001731 if( dist<0 ) dist = -dist;
drh0d316a42002-08-11 20:10:47 +00001732 for(i=1; i<n; i++){
1733 int d2 = SWAB32(pBt, pInfo->aFree[i]) - nearby;
drhbea00b92002-07-08 10:59:50 +00001734 if( d2<0 ) d2 = -d2;
1735 if( d2<dist ) closest = i;
1736 }
1737 }else{
1738 closest = 0;
1739 }
drh0d316a42002-08-11 20:10:47 +00001740 SWAB_ADD(pBt, pInfo->nFree, -1);
1741 *pPgno = SWAB32(pBt, pInfo->aFree[closest]);
1742 pInfo->aFree[closest] = pInfo->aFree[n-1];
drh30e58752002-03-02 20:41:57 +00001743 rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
1744 sqlitepager_unref(pOvfl);
1745 if( rc==SQLITE_OK ){
1746 sqlitepager_dont_rollback(*ppPage);
1747 rc = sqlitepager_write(*ppPage);
1748 }
1749 }
drh3b7511c2001-05-26 13:15:44 +00001750 }else{
drh2aa679f2001-06-25 02:11:07 +00001751 *pPgno = sqlitepager_pagecount(pBt->pPager) + 1;
drh8c42ca92001-06-22 19:15:00 +00001752 rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
drh3b7511c2001-05-26 13:15:44 +00001753 if( rc ) return rc;
1754 rc = sqlitepager_write(*ppPage);
1755 }
1756 return rc;
1757}
1758
1759/*
1760** Add a page of the database file to the freelist. Either pgno or
1761** pPage but not both may be 0.
drh5e2f8b92001-05-28 00:41:15 +00001762**
drhdd793422001-06-28 01:54:48 +00001763** sqlitepager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00001764*/
1765static int freePage(Btree *pBt, void *pPage, Pgno pgno){
drhbd03cae2001-06-02 02:40:57 +00001766 PageOne *pPage1 = pBt->page1;
drh3b7511c2001-05-26 13:15:44 +00001767 OverflowPage *pOvfl = (OverflowPage*)pPage;
1768 int rc;
drhdd793422001-06-28 01:54:48 +00001769 int needUnref = 0;
1770 MemPage *pMemPage;
drh8b2f49b2001-06-08 00:21:52 +00001771
drh3b7511c2001-05-26 13:15:44 +00001772 if( pgno==0 ){
1773 assert( pOvfl!=0 );
1774 pgno = sqlitepager_pagenumber(pOvfl);
1775 }
drh2aa679f2001-06-25 02:11:07 +00001776 assert( pgno>2 );
drhda47d772002-12-02 04:25:19 +00001777 assert( sqlitepager_pagenumber(pOvfl)==pgno );
drh193a6b42002-07-07 16:52:46 +00001778 pMemPage = (MemPage*)pPage;
1779 pMemPage->isInit = 0;
1780 if( pMemPage->pParent ){
1781 sqlitepager_unref(pMemPage->pParent);
1782 pMemPage->pParent = 0;
1783 }
drh3b7511c2001-05-26 13:15:44 +00001784 rc = sqlitepager_write(pPage1);
1785 if( rc ){
1786 return rc;
1787 }
drh0d316a42002-08-11 20:10:47 +00001788 SWAB_ADD(pBt, pPage1->nFree, 1);
1789 if( pPage1->nFree!=0 && pPage1->freeList!=0 ){
drh30e58752002-03-02 20:41:57 +00001790 OverflowPage *pFreeIdx;
drh0d316a42002-08-11 20:10:47 +00001791 rc = sqlitepager_get(pBt->pPager, SWAB32(pBt, pPage1->freeList),
1792 (void**)&pFreeIdx);
drh30e58752002-03-02 20:41:57 +00001793 if( rc==SQLITE_OK ){
1794 FreelistInfo *pInfo = (FreelistInfo*)pFreeIdx->aPayload;
drh0d316a42002-08-11 20:10:47 +00001795 int n = SWAB32(pBt, pInfo->nFree);
1796 if( n<(sizeof(pInfo->aFree)/sizeof(pInfo->aFree[0])) ){
drh30e58752002-03-02 20:41:57 +00001797 rc = sqlitepager_write(pFreeIdx);
1798 if( rc==SQLITE_OK ){
drh0d316a42002-08-11 20:10:47 +00001799 pInfo->aFree[n] = SWAB32(pBt, pgno);
1800 SWAB_ADD(pBt, pInfo->nFree, 1);
drh30e58752002-03-02 20:41:57 +00001801 sqlitepager_unref(pFreeIdx);
1802 sqlitepager_dont_write(pBt->pPager, pgno);
1803 return rc;
1804 }
1805 }
1806 sqlitepager_unref(pFreeIdx);
1807 }
1808 }
drh3b7511c2001-05-26 13:15:44 +00001809 if( pOvfl==0 ){
1810 assert( pgno>0 );
drh8c42ca92001-06-22 19:15:00 +00001811 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001812 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001813 needUnref = 1;
drh3b7511c2001-05-26 13:15:44 +00001814 }
1815 rc = sqlitepager_write(pOvfl);
1816 if( rc ){
drhdd793422001-06-28 01:54:48 +00001817 if( needUnref ) sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001818 return rc;
1819 }
drh14acc042001-06-10 19:56:58 +00001820 pOvfl->iNext = pPage1->freeList;
drh0d316a42002-08-11 20:10:47 +00001821 pPage1->freeList = SWAB32(pBt, pgno);
drh5e2f8b92001-05-28 00:41:15 +00001822 memset(pOvfl->aPayload, 0, OVERFLOW_SIZE);
drhdd793422001-06-28 01:54:48 +00001823 if( needUnref ) rc = sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001824 return rc;
1825}
1826
1827/*
1828** Erase all the data out of a cell. This involves returning overflow
1829** pages back the freelist.
1830*/
1831static int clearCell(Btree *pBt, Cell *pCell){
1832 Pager *pPager = pBt->pPager;
1833 OverflowPage *pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001834 Pgno ovfl, nextOvfl;
1835 int rc;
1836
drh0d316a42002-08-11 20:10:47 +00001837 if( NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h) <= MX_LOCAL_PAYLOAD ){
drh5e2f8b92001-05-28 00:41:15 +00001838 return SQLITE_OK;
1839 }
drh0d316a42002-08-11 20:10:47 +00001840 ovfl = SWAB32(pBt, pCell->ovfl);
drh3b7511c2001-05-26 13:15:44 +00001841 pCell->ovfl = 0;
1842 while( ovfl ){
drh8c42ca92001-06-22 19:15:00 +00001843 rc = sqlitepager_get(pPager, ovfl, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001844 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001845 nextOvfl = SWAB32(pBt, pOvfl->iNext);
drhbd03cae2001-06-02 02:40:57 +00001846 rc = freePage(pBt, pOvfl, ovfl);
1847 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001848 sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001849 ovfl = nextOvfl;
drh3b7511c2001-05-26 13:15:44 +00001850 }
drh5e2f8b92001-05-28 00:41:15 +00001851 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00001852}
1853
1854/*
1855** Create a new cell from key and data. Overflow pages are allocated as
1856** necessary and linked to this cell.
1857*/
1858static int fillInCell(
1859 Btree *pBt, /* The whole Btree. Needed to allocate pages */
1860 Cell *pCell, /* Populate this Cell structure */
drh5c4d9702001-08-20 00:33:58 +00001861 const void *pKey, int nKey, /* The key */
1862 const void *pData,int nData /* The data */
drh3b7511c2001-05-26 13:15:44 +00001863){
drhdd793422001-06-28 01:54:48 +00001864 OverflowPage *pOvfl, *pPrior;
drh3b7511c2001-05-26 13:15:44 +00001865 Pgno *pNext;
1866 int spaceLeft;
drh8c42ca92001-06-22 19:15:00 +00001867 int n, rc;
drh3b7511c2001-05-26 13:15:44 +00001868 int nPayload;
drh5c4d9702001-08-20 00:33:58 +00001869 const char *pPayload;
drh3b7511c2001-05-26 13:15:44 +00001870 char *pSpace;
drh199e3cf2002-07-18 11:01:47 +00001871 Pgno nearby = 0;
drh3b7511c2001-05-26 13:15:44 +00001872
drh5e2f8b92001-05-28 00:41:15 +00001873 pCell->h.leftChild = 0;
drh0d316a42002-08-11 20:10:47 +00001874 pCell->h.nKey = SWAB16(pBt, nKey & 0xffff);
drh80ff32f2001-11-04 18:32:46 +00001875 pCell->h.nKeyHi = nKey >> 16;
drh0d316a42002-08-11 20:10:47 +00001876 pCell->h.nData = SWAB16(pBt, nData & 0xffff);
drh80ff32f2001-11-04 18:32:46 +00001877 pCell->h.nDataHi = nData >> 16;
drh3b7511c2001-05-26 13:15:44 +00001878 pCell->h.iNext = 0;
1879
1880 pNext = &pCell->ovfl;
drh5e2f8b92001-05-28 00:41:15 +00001881 pSpace = pCell->aPayload;
drh3b7511c2001-05-26 13:15:44 +00001882 spaceLeft = MX_LOCAL_PAYLOAD;
1883 pPayload = pKey;
1884 pKey = 0;
1885 nPayload = nKey;
drhdd793422001-06-28 01:54:48 +00001886 pPrior = 0;
drh3b7511c2001-05-26 13:15:44 +00001887 while( nPayload>0 ){
1888 if( spaceLeft==0 ){
drh199e3cf2002-07-18 11:01:47 +00001889 rc = allocatePage(pBt, (MemPage**)&pOvfl, pNext, nearby);
drh3b7511c2001-05-26 13:15:44 +00001890 if( rc ){
1891 *pNext = 0;
drhbea00b92002-07-08 10:59:50 +00001892 }else{
drh199e3cf2002-07-18 11:01:47 +00001893 nearby = *pNext;
drhdd793422001-06-28 01:54:48 +00001894 }
1895 if( pPrior ) sqlitepager_unref(pPrior);
1896 if( rc ){
drh5e2f8b92001-05-28 00:41:15 +00001897 clearCell(pBt, pCell);
drh3b7511c2001-05-26 13:15:44 +00001898 return rc;
1899 }
drh0d316a42002-08-11 20:10:47 +00001900 if( pBt->needSwab ) *pNext = swab32(*pNext);
drhdd793422001-06-28 01:54:48 +00001901 pPrior = pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001902 spaceLeft = OVERFLOW_SIZE;
drh5e2f8b92001-05-28 00:41:15 +00001903 pSpace = pOvfl->aPayload;
drh8c42ca92001-06-22 19:15:00 +00001904 pNext = &pOvfl->iNext;
drh3b7511c2001-05-26 13:15:44 +00001905 }
1906 n = nPayload;
1907 if( n>spaceLeft ) n = spaceLeft;
1908 memcpy(pSpace, pPayload, n);
1909 nPayload -= n;
1910 if( nPayload==0 && pData ){
1911 pPayload = pData;
1912 nPayload = nData;
1913 pData = 0;
1914 }else{
1915 pPayload += n;
1916 }
1917 spaceLeft -= n;
1918 pSpace += n;
1919 }
drhdd793422001-06-28 01:54:48 +00001920 *pNext = 0;
1921 if( pPrior ){
1922 sqlitepager_unref(pPrior);
1923 }
drh3b7511c2001-05-26 13:15:44 +00001924 return SQLITE_OK;
1925}
1926
1927/*
drhbd03cae2001-06-02 02:40:57 +00001928** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00001929** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00001930** pointer in the third argument.
1931*/
drh428ae8c2003-01-04 16:48:09 +00001932static void reparentPage(Pager *pPager, Pgno pgno, MemPage *pNewParent,int idx){
drhbd03cae2001-06-02 02:40:57 +00001933 MemPage *pThis;
1934
drhdd793422001-06-28 01:54:48 +00001935 if( pgno==0 ) return;
1936 assert( pPager!=0 );
drhbd03cae2001-06-02 02:40:57 +00001937 pThis = sqlitepager_lookup(pPager, pgno);
drh6019e162001-07-02 17:51:45 +00001938 if( pThis && pThis->isInit ){
drhdd793422001-06-28 01:54:48 +00001939 if( pThis->pParent!=pNewParent ){
1940 if( pThis->pParent ) sqlitepager_unref(pThis->pParent);
1941 pThis->pParent = pNewParent;
1942 if( pNewParent ) sqlitepager_ref(pNewParent);
1943 }
drh428ae8c2003-01-04 16:48:09 +00001944 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00001945 sqlitepager_unref(pThis);
drhbd03cae2001-06-02 02:40:57 +00001946 }
1947}
1948
1949/*
1950** Reparent all children of the given page to be the given page.
1951** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00001952** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00001953**
1954** This routine gets called after you memcpy() one page into
1955** another.
1956*/
drh0d316a42002-08-11 20:10:47 +00001957static void reparentChildPages(Btree *pBt, MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00001958 int i;
drh0d316a42002-08-11 20:10:47 +00001959 Pager *pPager = pBt->pPager;
drhbd03cae2001-06-02 02:40:57 +00001960 for(i=0; i<pPage->nCell; i++){
drh428ae8c2003-01-04 16:48:09 +00001961 reparentPage(pPager, SWAB32(pBt, pPage->apCell[i]->h.leftChild), pPage, i);
drhbd03cae2001-06-02 02:40:57 +00001962 }
drh428ae8c2003-01-04 16:48:09 +00001963 reparentPage(pPager, SWAB32(pBt, pPage->u.hdr.rightChild), pPage, i);
1964 pPage->idxShift = 0;
drh14acc042001-06-10 19:56:58 +00001965}
1966
1967/*
1968** Remove the i-th cell from pPage. This routine effects pPage only.
1969** The cell content is not freed or deallocated. It is assumed that
1970** the cell content has been copied someplace else. This routine just
1971** removes the reference to the cell from pPage.
1972**
1973** "sz" must be the number of bytes in the cell.
1974**
1975** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001976** Only the pPage->apCell[] array is important. The relinkCellList()
1977** routine will be called soon after this routine in order to rebuild
1978** the linked list.
drh14acc042001-06-10 19:56:58 +00001979*/
drh0d316a42002-08-11 20:10:47 +00001980static void dropCell(Btree *pBt, MemPage *pPage, int idx, int sz){
drh14acc042001-06-10 19:56:58 +00001981 int j;
drh8c42ca92001-06-22 19:15:00 +00001982 assert( idx>=0 && idx<pPage->nCell );
drh0d316a42002-08-11 20:10:47 +00001983 assert( sz==cellSize(pBt, pPage->apCell[idx]) );
drh6019e162001-07-02 17:51:45 +00001984 assert( sqlitepager_iswriteable(pPage) );
drh0d316a42002-08-11 20:10:47 +00001985 freeSpace(pBt, pPage, Addr(pPage->apCell[idx]) - Addr(pPage), sz);
drh7c717f72001-06-24 20:39:41 +00001986 for(j=idx; j<pPage->nCell-1; j++){
drh14acc042001-06-10 19:56:58 +00001987 pPage->apCell[j] = pPage->apCell[j+1];
1988 }
1989 pPage->nCell--;
drh428ae8c2003-01-04 16:48:09 +00001990 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00001991}
1992
1993/*
1994** Insert a new cell on pPage at cell index "i". pCell points to the
1995** content of the cell.
1996**
1997** If the cell content will fit on the page, then put it there. If it
1998** will not fit, then just make pPage->apCell[i] point to the content
1999** and set pPage->isOverfull.
2000**
2001** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00002002** Only the pPage->apCell[] array is important. The relinkCellList()
2003** routine will be called soon after this routine in order to rebuild
2004** the linked list.
drh14acc042001-06-10 19:56:58 +00002005*/
drh0d316a42002-08-11 20:10:47 +00002006static void insertCell(Btree *pBt, MemPage *pPage, int i, Cell *pCell, int sz){
drh14acc042001-06-10 19:56:58 +00002007 int idx, j;
2008 assert( i>=0 && i<=pPage->nCell );
drh0d316a42002-08-11 20:10:47 +00002009 assert( sz==cellSize(pBt, pCell) );
drh6019e162001-07-02 17:51:45 +00002010 assert( sqlitepager_iswriteable(pPage) );
drh0d316a42002-08-11 20:10:47 +00002011 idx = allocateSpace(pBt, pPage, sz);
drh14acc042001-06-10 19:56:58 +00002012 for(j=pPage->nCell; j>i; j--){
2013 pPage->apCell[j] = pPage->apCell[j-1];
2014 }
2015 pPage->nCell++;
drh14acc042001-06-10 19:56:58 +00002016 if( idx<=0 ){
2017 pPage->isOverfull = 1;
2018 pPage->apCell[i] = pCell;
2019 }else{
2020 memcpy(&pPage->u.aDisk[idx], pCell, sz);
drh8c42ca92001-06-22 19:15:00 +00002021 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[idx];
drh14acc042001-06-10 19:56:58 +00002022 }
drh428ae8c2003-01-04 16:48:09 +00002023 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00002024}
2025
2026/*
2027** Rebuild the linked list of cells on a page so that the cells
drh8c42ca92001-06-22 19:15:00 +00002028** occur in the order specified by the pPage->apCell[] array.
2029** Invoke this routine once to repair damage after one or more
2030** invocations of either insertCell() or dropCell().
drh14acc042001-06-10 19:56:58 +00002031*/
drh0d316a42002-08-11 20:10:47 +00002032static void relinkCellList(Btree *pBt, MemPage *pPage){
drh14acc042001-06-10 19:56:58 +00002033 int i;
2034 u16 *pIdx;
drh6019e162001-07-02 17:51:45 +00002035 assert( sqlitepager_iswriteable(pPage) );
drh14acc042001-06-10 19:56:58 +00002036 pIdx = &pPage->u.hdr.firstCell;
2037 for(i=0; i<pPage->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00002038 int idx = Addr(pPage->apCell[i]) - Addr(pPage);
drh8c42ca92001-06-22 19:15:00 +00002039 assert( idx>0 && idx<SQLITE_PAGE_SIZE );
drh0d316a42002-08-11 20:10:47 +00002040 *pIdx = SWAB16(pBt, idx);
drh14acc042001-06-10 19:56:58 +00002041 pIdx = &pPage->apCell[i]->h.iNext;
2042 }
2043 *pIdx = 0;
2044}
2045
2046/*
2047** Make a copy of the contents of pFrom into pTo. The pFrom->apCell[]
drh5e00f6c2001-09-13 13:46:56 +00002048** pointers that point into pFrom->u.aDisk[] must be adjusted to point
drhdd793422001-06-28 01:54:48 +00002049** into pTo->u.aDisk[] instead. But some pFrom->apCell[] entries might
drh14acc042001-06-10 19:56:58 +00002050** not point to pFrom->u.aDisk[]. Those are unchanged.
2051*/
2052static void copyPage(MemPage *pTo, MemPage *pFrom){
2053 uptr from, to;
2054 int i;
2055 memcpy(pTo->u.aDisk, pFrom->u.aDisk, SQLITE_PAGE_SIZE);
drhdd793422001-06-28 01:54:48 +00002056 pTo->pParent = 0;
drh14acc042001-06-10 19:56:58 +00002057 pTo->isInit = 1;
2058 pTo->nCell = pFrom->nCell;
2059 pTo->nFree = pFrom->nFree;
2060 pTo->isOverfull = pFrom->isOverfull;
drh7c717f72001-06-24 20:39:41 +00002061 to = Addr(pTo);
2062 from = Addr(pFrom);
drh14acc042001-06-10 19:56:58 +00002063 for(i=0; i<pTo->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00002064 uptr x = Addr(pFrom->apCell[i]);
drh8c42ca92001-06-22 19:15:00 +00002065 if( x>from && x<from+SQLITE_PAGE_SIZE ){
2066 *((uptr*)&pTo->apCell[i]) = x + to - from;
drhdd793422001-06-28 01:54:48 +00002067 }else{
2068 pTo->apCell[i] = pFrom->apCell[i];
drh14acc042001-06-10 19:56:58 +00002069 }
2070 }
drhbd03cae2001-06-02 02:40:57 +00002071}
2072
2073/*
drhc3b70572003-01-04 19:44:07 +00002074** The following parameters determine how many adjacent pages get involved
2075** in a balancing operation. NN is the number of neighbors on either side
2076** of the page that participate in the balancing operation. NB is the
2077** total number of pages that participate, including the target page and
2078** NN neighbors on either side.
2079**
2080** The minimum value of NN is 1 (of course). Increasing NN above 1
2081** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
2082** in exchange for a larger degradation in INSERT and UPDATE performance.
2083** The value of NN appears to give the best results overall.
2084*/
2085#define NN 1 /* Number of neighbors on either side of pPage */
2086#define NB (NN*2+1) /* Total pages involved in the balance */
2087
2088/*
drh8b2f49b2001-06-08 00:21:52 +00002089** This routine redistributes Cells on pPage and up to two siblings
2090** of pPage so that all pages have about the same amount of free space.
drh14acc042001-06-10 19:56:58 +00002091** Usually one sibling on either side of pPage is used in the balancing,
drh8b2f49b2001-06-08 00:21:52 +00002092** though both siblings might come from one side if pPage is the first
2093** or last child of its parent. If pPage has fewer than two siblings
2094** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00002095** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00002096**
2097** The number of siblings of pPage might be increased or decreased by
drh8c42ca92001-06-22 19:15:00 +00002098** one in an effort to keep pages between 66% and 100% full. The root page
2099** is special and is allowed to be less than 66% full. If pPage is
2100** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00002101** or decreased by one, as necessary, to keep the root page from being
2102** overfull or empty.
2103**
drh14acc042001-06-10 19:56:58 +00002104** This routine calls relinkCellList() on its input page regardless of
2105** whether or not it does any real balancing. Client routines will typically
2106** invoke insertCell() or dropCell() before calling this routine, so we
2107** need to call relinkCellList() to clean up the mess that those other
2108** routines left behind.
2109**
2110** pCur is left pointing to the same cell as when this routine was called
drh8c42ca92001-06-22 19:15:00 +00002111** even if that cell gets moved to a different page. pCur may be NULL.
2112** Set the pCur parameter to NULL if you do not care about keeping track
2113** of a cell as that will save this routine the work of keeping track of it.
drh14acc042001-06-10 19:56:58 +00002114**
drh8b2f49b2001-06-08 00:21:52 +00002115** Note that when this routine is called, some of the Cells on pPage
drh14acc042001-06-10 19:56:58 +00002116** might not actually be stored in pPage->u.aDisk[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00002117** if the page is overfull. Part of the job of this routine is to
drh14acc042001-06-10 19:56:58 +00002118** make sure all Cells for pPage once again fit in pPage->u.aDisk[].
2119**
drh8c42ca92001-06-22 19:15:00 +00002120** In the course of balancing the siblings of pPage, the parent of pPage
2121** might become overfull or underfull. If that happens, then this routine
2122** is called recursively on the parent.
2123**
drh5e00f6c2001-09-13 13:46:56 +00002124** If this routine fails for any reason, it might leave the database
2125** in a corrupted state. So if this routine fails, the database should
2126** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00002127*/
drh14acc042001-06-10 19:56:58 +00002128static int balance(Btree *pBt, MemPage *pPage, BtCursor *pCur){
drh8b2f49b2001-06-08 00:21:52 +00002129 MemPage *pParent; /* The parent of pPage */
drh8b2f49b2001-06-08 00:21:52 +00002130 int nCell; /* Number of cells in apCell[] */
2131 int nOld; /* Number of pages in apOld[] */
2132 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00002133 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00002134 int i, j, k; /* Loop counters */
2135 int idx; /* Index of pPage in pParent->apCell[] */
2136 int nxDiv; /* Next divider slot in pParent->apCell[] */
2137 int rc; /* The return code */
2138 int iCur; /* apCell[iCur] is the cell of the cursor */
drh5edc3122001-09-13 21:53:09 +00002139 MemPage *pOldCurPage; /* The cursor originally points to this page */
drh6019e162001-07-02 17:51:45 +00002140 int subtotal; /* Subtotal of bytes in cells on one page */
drh9ca7d3b2001-06-28 11:50:21 +00002141 MemPage *extraUnref = 0; /* A page that needs to be unref-ed */
drhc3b70572003-01-04 19:44:07 +00002142 MemPage *apOld[NB]; /* pPage and up to two siblings */
2143 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
2144 MemPage *apNew[NB+1]; /* pPage and up to NB siblings after balancing */
2145 Pgno pgnoNew[NB+1]; /* Page numbers for each page in apNew[] */
2146 int idxDiv[NB]; /* Indices of divider cells in pParent */
2147 Cell *apDiv[NB]; /* Divider cells in pParent */
2148 Cell aTemp[NB]; /* Temporary holding area for apDiv[] */
2149 int cntNew[NB+1]; /* Index in apCell[] of cell after i-th page */
2150 int szNew[NB+1]; /* Combined size of cells place on i-th page */
2151 MemPage aOld[NB]; /* Temporary copies of pPage and its siblings */
2152 Cell *apCell[(MX_CELL+2)*NB]; /* All cells from pages being balanced */
2153 int szCell[(MX_CELL+2)*NB]; /* Local size of all cells */
drh8b2f49b2001-06-08 00:21:52 +00002154
drh14acc042001-06-10 19:56:58 +00002155 /*
2156 ** Return without doing any work if pPage is neither overfull nor
2157 ** underfull.
drh8b2f49b2001-06-08 00:21:52 +00002158 */
drh6019e162001-07-02 17:51:45 +00002159 assert( sqlitepager_iswriteable(pPage) );
drha1b351a2001-09-14 16:42:12 +00002160 if( !pPage->isOverfull && pPage->nFree<SQLITE_PAGE_SIZE/2
2161 && pPage->nCell>=2){
drh0d316a42002-08-11 20:10:47 +00002162 relinkCellList(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002163 return SQLITE_OK;
2164 }
2165
2166 /*
drh14acc042001-06-10 19:56:58 +00002167 ** Find the parent of the page to be balanceed.
2168 ** If there is no parent, it means this page is the root page and
drh8b2f49b2001-06-08 00:21:52 +00002169 ** special rules apply.
2170 */
drh14acc042001-06-10 19:56:58 +00002171 pParent = pPage->pParent;
drh8b2f49b2001-06-08 00:21:52 +00002172 if( pParent==0 ){
2173 Pgno pgnoChild;
drh8c42ca92001-06-22 19:15:00 +00002174 MemPage *pChild;
drh7aa128d2002-06-21 13:09:16 +00002175 assert( pPage->isInit );
drh8b2f49b2001-06-08 00:21:52 +00002176 if( pPage->nCell==0 ){
drh14acc042001-06-10 19:56:58 +00002177 if( pPage->u.hdr.rightChild ){
2178 /*
2179 ** The root page is empty. Copy the one child page
drh8b2f49b2001-06-08 00:21:52 +00002180 ** into the root page and return. This reduces the depth
2181 ** of the BTree by one.
2182 */
drh0d316a42002-08-11 20:10:47 +00002183 pgnoChild = SWAB32(pBt, pPage->u.hdr.rightChild);
drh8c42ca92001-06-22 19:15:00 +00002184 rc = sqlitepager_get(pBt->pPager, pgnoChild, (void**)&pChild);
drh8b2f49b2001-06-08 00:21:52 +00002185 if( rc ) return rc;
2186 memcpy(pPage, pChild, SQLITE_PAGE_SIZE);
2187 pPage->isInit = 0;
drh0d316a42002-08-11 20:10:47 +00002188 rc = initPage(pBt, pPage, sqlitepager_pagenumber(pPage), 0);
drh6019e162001-07-02 17:51:45 +00002189 assert( rc==SQLITE_OK );
drh0d316a42002-08-11 20:10:47 +00002190 reparentChildPages(pBt, pPage);
drh5edc3122001-09-13 21:53:09 +00002191 if( pCur && pCur->pPage==pChild ){
2192 sqlitepager_unref(pChild);
2193 pCur->pPage = pPage;
2194 sqlitepager_ref(pPage);
2195 }
drh8b2f49b2001-06-08 00:21:52 +00002196 freePage(pBt, pChild, pgnoChild);
2197 sqlitepager_unref(pChild);
drhefc251d2001-07-01 22:12:01 +00002198 }else{
drh0d316a42002-08-11 20:10:47 +00002199 relinkCellList(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002200 }
2201 return SQLITE_OK;
2202 }
drh14acc042001-06-10 19:56:58 +00002203 if( !pPage->isOverfull ){
drh8b2f49b2001-06-08 00:21:52 +00002204 /* It is OK for the root page to be less than half full.
2205 */
drh0d316a42002-08-11 20:10:47 +00002206 relinkCellList(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002207 return SQLITE_OK;
2208 }
drh14acc042001-06-10 19:56:58 +00002209 /*
2210 ** If we get to here, it means the root page is overfull.
drh8b2f49b2001-06-08 00:21:52 +00002211 ** When this happens, Create a new child page and copy the
2212 ** contents of the root into the child. Then make the root
drh14acc042001-06-10 19:56:58 +00002213 ** page an empty page with rightChild pointing to the new
drh8b2f49b2001-06-08 00:21:52 +00002214 ** child. Then fall thru to the code below which will cause
2215 ** the overfull child page to be split.
2216 */
drh14acc042001-06-10 19:56:58 +00002217 rc = sqlitepager_write(pPage);
2218 if( rc ) return rc;
drhbea00b92002-07-08 10:59:50 +00002219 rc = allocatePage(pBt, &pChild, &pgnoChild, sqlitepager_pagenumber(pPage));
drh8b2f49b2001-06-08 00:21:52 +00002220 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002221 assert( sqlitepager_iswriteable(pChild) );
drh14acc042001-06-10 19:56:58 +00002222 copyPage(pChild, pPage);
2223 pChild->pParent = pPage;
drhbb49aba2003-01-04 18:53:27 +00002224 pChild->idxParent = 0;
drhdd793422001-06-28 01:54:48 +00002225 sqlitepager_ref(pPage);
drh14acc042001-06-10 19:56:58 +00002226 pChild->isOverfull = 1;
drh5edc3122001-09-13 21:53:09 +00002227 if( pCur && pCur->pPage==pPage ){
2228 sqlitepager_unref(pPage);
drh14acc042001-06-10 19:56:58 +00002229 pCur->pPage = pChild;
drh9ca7d3b2001-06-28 11:50:21 +00002230 }else{
2231 extraUnref = pChild;
drh8b2f49b2001-06-08 00:21:52 +00002232 }
drh0d316a42002-08-11 20:10:47 +00002233 zeroPage(pBt, pPage);
2234 pPage->u.hdr.rightChild = SWAB32(pBt, pgnoChild);
drh8b2f49b2001-06-08 00:21:52 +00002235 pParent = pPage;
2236 pPage = pChild;
drh8b2f49b2001-06-08 00:21:52 +00002237 }
drh6019e162001-07-02 17:51:45 +00002238 rc = sqlitepager_write(pParent);
2239 if( rc ) return rc;
drh7aa128d2002-06-21 13:09:16 +00002240 assert( pParent->isInit );
drh14acc042001-06-10 19:56:58 +00002241
drh8b2f49b2001-06-08 00:21:52 +00002242 /*
drh14acc042001-06-10 19:56:58 +00002243 ** Find the Cell in the parent page whose h.leftChild points back
2244 ** to pPage. The "idx" variable is the index of that cell. If pPage
2245 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00002246 */
drhbb49aba2003-01-04 18:53:27 +00002247 if( pParent->idxShift ){
2248 Pgno pgno, swabPgno;
2249 pgno = sqlitepager_pagenumber(pPage);
2250 swabPgno = SWAB32(pBt, pgno);
2251 for(idx=0; idx<pParent->nCell; idx++){
2252 if( pParent->apCell[idx]->h.leftChild==swabPgno ){
2253 break;
2254 }
drh8b2f49b2001-06-08 00:21:52 +00002255 }
drhbb49aba2003-01-04 18:53:27 +00002256 assert( idx<pParent->nCell || pParent->u.hdr.rightChild==swabPgno );
2257 }else{
2258 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00002259 }
drh8b2f49b2001-06-08 00:21:52 +00002260
2261 /*
drh14acc042001-06-10 19:56:58 +00002262 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00002263 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00002264 */
drh14acc042001-06-10 19:56:58 +00002265 nOld = nNew = 0;
2266 sqlitepager_ref(pParent);
2267
2268 /*
2269 ** Find sibling pages to pPage and the Cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00002270 ** the siblings. An attempt is made to find NN siblings on either
2271 ** side of pPage. More siblings are taken from one side, however, if
2272 ** pPage there are fewer than NN siblings on the other side. If pParent
2273 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00002274 */
drhc3b70572003-01-04 19:44:07 +00002275 nxDiv = idx - NN;
2276 if( nxDiv + NB > pParent->nCell ){
2277 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00002278 }
drhc3b70572003-01-04 19:44:07 +00002279 if( nxDiv<0 ){
2280 nxDiv = 0;
2281 }
drh8b2f49b2001-06-08 00:21:52 +00002282 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00002283 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00002284 if( k<pParent->nCell ){
2285 idxDiv[i] = k;
2286 apDiv[i] = pParent->apCell[k];
drh8b2f49b2001-06-08 00:21:52 +00002287 nDiv++;
drh0d316a42002-08-11 20:10:47 +00002288 pgnoOld[i] = SWAB32(pBt, apDiv[i]->h.leftChild);
drh14acc042001-06-10 19:56:58 +00002289 }else if( k==pParent->nCell ){
drh0d316a42002-08-11 20:10:47 +00002290 pgnoOld[i] = SWAB32(pBt, pParent->u.hdr.rightChild);
drh14acc042001-06-10 19:56:58 +00002291 }else{
2292 break;
drh8b2f49b2001-06-08 00:21:52 +00002293 }
drh8c42ca92001-06-22 19:15:00 +00002294 rc = sqlitepager_get(pBt->pPager, pgnoOld[i], (void**)&apOld[i]);
drh14acc042001-06-10 19:56:58 +00002295 if( rc ) goto balance_cleanup;
drh0d316a42002-08-11 20:10:47 +00002296 rc = initPage(pBt, apOld[i], pgnoOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00002297 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00002298 apOld[i]->idxParent = k;
drh14acc042001-06-10 19:56:58 +00002299 nOld++;
drh8b2f49b2001-06-08 00:21:52 +00002300 }
2301
2302 /*
drh14acc042001-06-10 19:56:58 +00002303 ** Set iCur to be the index in apCell[] of the cell that the cursor
2304 ** is pointing to. We will need this later on in order to keep the
drh5edc3122001-09-13 21:53:09 +00002305 ** cursor pointing at the same cell. If pCur points to a page that
2306 ** has no involvement with this rebalancing, then set iCur to a large
2307 ** number so that the iCur==j tests always fail in the main cell
2308 ** distribution loop below.
drh14acc042001-06-10 19:56:58 +00002309 */
2310 if( pCur ){
drh5edc3122001-09-13 21:53:09 +00002311 iCur = 0;
2312 for(i=0; i<nOld; i++){
2313 if( pCur->pPage==apOld[i] ){
2314 iCur += pCur->idx;
2315 break;
2316 }
2317 iCur += apOld[i]->nCell;
2318 if( i<nOld-1 && pCur->pPage==pParent && pCur->idx==idxDiv[i] ){
2319 break;
2320 }
2321 iCur++;
drh14acc042001-06-10 19:56:58 +00002322 }
drh5edc3122001-09-13 21:53:09 +00002323 pOldCurPage = pCur->pPage;
drh14acc042001-06-10 19:56:58 +00002324 }
2325
2326 /*
2327 ** Make copies of the content of pPage and its siblings into aOld[].
2328 ** The rest of this function will use data from the copies rather
2329 ** that the original pages since the original pages will be in the
2330 ** process of being overwritten.
2331 */
2332 for(i=0; i<nOld; i++){
2333 copyPage(&aOld[i], apOld[i]);
drh14acc042001-06-10 19:56:58 +00002334 }
2335
2336 /*
2337 ** Load pointers to all cells on sibling pages and the divider cells
2338 ** into the local apCell[] array. Make copies of the divider cells
2339 ** into aTemp[] and remove the the divider Cells from pParent.
drh8b2f49b2001-06-08 00:21:52 +00002340 */
2341 nCell = 0;
2342 for(i=0; i<nOld; i++){
drh6b308672002-07-08 02:16:37 +00002343 MemPage *pOld = &aOld[i];
drh8b2f49b2001-06-08 00:21:52 +00002344 for(j=0; j<pOld->nCell; j++){
drh14acc042001-06-10 19:56:58 +00002345 apCell[nCell] = pOld->apCell[j];
drh0d316a42002-08-11 20:10:47 +00002346 szCell[nCell] = cellSize(pBt, apCell[nCell]);
drh14acc042001-06-10 19:56:58 +00002347 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00002348 }
2349 if( i<nOld-1 ){
drh0d316a42002-08-11 20:10:47 +00002350 szCell[nCell] = cellSize(pBt, apDiv[i]);
drh8c42ca92001-06-22 19:15:00 +00002351 memcpy(&aTemp[i], apDiv[i], szCell[nCell]);
drh14acc042001-06-10 19:56:58 +00002352 apCell[nCell] = &aTemp[i];
drh0d316a42002-08-11 20:10:47 +00002353 dropCell(pBt, pParent, nxDiv, szCell[nCell]);
2354 assert( SWAB32(pBt, apCell[nCell]->h.leftChild)==pgnoOld[i] );
drh14acc042001-06-10 19:56:58 +00002355 apCell[nCell]->h.leftChild = pOld->u.hdr.rightChild;
2356 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00002357 }
2358 }
2359
2360 /*
drh6019e162001-07-02 17:51:45 +00002361 ** Figure out the number of pages needed to hold all nCell cells.
2362 ** Store this number in "k". Also compute szNew[] which is the total
2363 ** size of all cells on the i-th page and cntNew[] which is the index
2364 ** in apCell[] of the cell that divides path i from path i+1.
2365 ** cntNew[k] should equal nCell.
2366 **
2367 ** This little patch of code is critical for keeping the tree
2368 ** balanced.
drh8b2f49b2001-06-08 00:21:52 +00002369 */
drh6019e162001-07-02 17:51:45 +00002370 for(subtotal=k=i=0; i<nCell; i++){
2371 subtotal += szCell[i];
2372 if( subtotal > USABLE_SPACE ){
2373 szNew[k] = subtotal - szCell[i];
2374 cntNew[k] = i;
2375 subtotal = 0;
2376 k++;
2377 }
2378 }
2379 szNew[k] = subtotal;
2380 cntNew[k] = nCell;
2381 k++;
2382 for(i=k-1; i>0; i--){
2383 while( szNew[i]<USABLE_SPACE/2 ){
2384 cntNew[i-1]--;
2385 assert( cntNew[i-1]>0 );
2386 szNew[i] += szCell[cntNew[i-1]];
2387 szNew[i-1] -= szCell[cntNew[i-1]-1];
2388 }
2389 }
2390 assert( cntNew[0]>0 );
drh8b2f49b2001-06-08 00:21:52 +00002391
2392 /*
drh6b308672002-07-08 02:16:37 +00002393 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00002394 */
drh14acc042001-06-10 19:56:58 +00002395 for(i=0; i<k; i++){
drh6b308672002-07-08 02:16:37 +00002396 if( i<nOld ){
2397 apNew[i] = apOld[i];
2398 pgnoNew[i] = pgnoOld[i];
2399 apOld[i] = 0;
2400 sqlitepager_write(apNew[i]);
2401 }else{
drhbea00b92002-07-08 10:59:50 +00002402 rc = allocatePage(pBt, &apNew[i], &pgnoNew[i], pgnoNew[i-1]);
drh6b308672002-07-08 02:16:37 +00002403 if( rc ) goto balance_cleanup;
2404 }
drh14acc042001-06-10 19:56:58 +00002405 nNew++;
drh0d316a42002-08-11 20:10:47 +00002406 zeroPage(pBt, apNew[i]);
drh6019e162001-07-02 17:51:45 +00002407 apNew[i]->isInit = 1;
drh8b2f49b2001-06-08 00:21:52 +00002408 }
2409
drh6b308672002-07-08 02:16:37 +00002410 /* Free any old pages that were not reused as new pages.
2411 */
2412 while( i<nOld ){
2413 rc = freePage(pBt, apOld[i], pgnoOld[i]);
2414 if( rc ) goto balance_cleanup;
2415 sqlitepager_unref(apOld[i]);
2416 apOld[i] = 0;
2417 i++;
2418 }
2419
drh8b2f49b2001-06-08 00:21:52 +00002420 /*
drhf9ffac92002-03-02 19:00:31 +00002421 ** Put the new pages in accending order. This helps to
2422 ** keep entries in the disk file in order so that a scan
2423 ** of the table is a linear scan through the file. That
2424 ** in turn helps the operating system to deliver pages
2425 ** from the disk more rapidly.
2426 **
2427 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00002428 ** n is never more than NB (a small constant), that should
2429 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00002430 **
drhc3b70572003-01-04 19:44:07 +00002431 ** When NB==3, this one optimization makes the database
2432 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00002433 */
2434 for(i=0; i<k-1; i++){
2435 int minV = pgnoNew[i];
2436 int minI = i;
2437 for(j=i+1; j<k; j++){
2438 if( pgnoNew[j]<minV ){
2439 minI = j;
2440 minV = pgnoNew[j];
2441 }
2442 }
2443 if( minI>i ){
2444 int t;
2445 MemPage *pT;
2446 t = pgnoNew[i];
2447 pT = apNew[i];
2448 pgnoNew[i] = pgnoNew[minI];
2449 apNew[i] = apNew[minI];
2450 pgnoNew[minI] = t;
2451 apNew[minI] = pT;
2452 }
2453 }
2454
2455 /*
drh14acc042001-06-10 19:56:58 +00002456 ** Evenly distribute the data in apCell[] across the new pages.
2457 ** Insert divider cells into pParent as necessary.
2458 */
2459 j = 0;
2460 for(i=0; i<nNew; i++){
2461 MemPage *pNew = apNew[i];
drh6019e162001-07-02 17:51:45 +00002462 while( j<cntNew[i] ){
2463 assert( pNew->nFree>=szCell[j] );
drh14acc042001-06-10 19:56:58 +00002464 if( pCur && iCur==j ){ pCur->pPage = pNew; pCur->idx = pNew->nCell; }
drh0d316a42002-08-11 20:10:47 +00002465 insertCell(pBt, pNew, pNew->nCell, apCell[j], szCell[j]);
drh14acc042001-06-10 19:56:58 +00002466 j++;
2467 }
drh6019e162001-07-02 17:51:45 +00002468 assert( pNew->nCell>0 );
drh14acc042001-06-10 19:56:58 +00002469 assert( !pNew->isOverfull );
drh0d316a42002-08-11 20:10:47 +00002470 relinkCellList(pBt, pNew);
drh14acc042001-06-10 19:56:58 +00002471 if( i<nNew-1 && j<nCell ){
2472 pNew->u.hdr.rightChild = apCell[j]->h.leftChild;
drh0d316a42002-08-11 20:10:47 +00002473 apCell[j]->h.leftChild = SWAB32(pBt, pgnoNew[i]);
drh14acc042001-06-10 19:56:58 +00002474 if( pCur && iCur==j ){ pCur->pPage = pParent; pCur->idx = nxDiv; }
drh0d316a42002-08-11 20:10:47 +00002475 insertCell(pBt, pParent, nxDiv, apCell[j], szCell[j]);
drh14acc042001-06-10 19:56:58 +00002476 j++;
2477 nxDiv++;
2478 }
2479 }
drh6019e162001-07-02 17:51:45 +00002480 assert( j==nCell );
drh6b308672002-07-08 02:16:37 +00002481 apNew[nNew-1]->u.hdr.rightChild = aOld[nOld-1].u.hdr.rightChild;
drh14acc042001-06-10 19:56:58 +00002482 if( nxDiv==pParent->nCell ){
drh0d316a42002-08-11 20:10:47 +00002483 pParent->u.hdr.rightChild = SWAB32(pBt, pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00002484 }else{
drh0d316a42002-08-11 20:10:47 +00002485 pParent->apCell[nxDiv]->h.leftChild = SWAB32(pBt, pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00002486 }
2487 if( pCur ){
drh3fc190c2001-09-14 03:24:23 +00002488 if( j<=iCur && pCur->pPage==pParent && pCur->idx>idxDiv[nOld-1] ){
2489 assert( pCur->pPage==pOldCurPage );
2490 pCur->idx += nNew - nOld;
2491 }else{
2492 assert( pOldCurPage!=0 );
2493 sqlitepager_ref(pCur->pPage);
2494 sqlitepager_unref(pOldCurPage);
2495 }
drh14acc042001-06-10 19:56:58 +00002496 }
2497
2498 /*
2499 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00002500 */
2501 for(i=0; i<nNew; i++){
drh0d316a42002-08-11 20:10:47 +00002502 reparentChildPages(pBt, apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002503 }
drh0d316a42002-08-11 20:10:47 +00002504 reparentChildPages(pBt, pParent);
drh8b2f49b2001-06-08 00:21:52 +00002505
2506 /*
drh14acc042001-06-10 19:56:58 +00002507 ** balance the parent page.
drh8b2f49b2001-06-08 00:21:52 +00002508 */
drh5edc3122001-09-13 21:53:09 +00002509 rc = balance(pBt, pParent, pCur);
drh8b2f49b2001-06-08 00:21:52 +00002510
2511 /*
drh14acc042001-06-10 19:56:58 +00002512 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00002513 */
drh14acc042001-06-10 19:56:58 +00002514balance_cleanup:
drh9ca7d3b2001-06-28 11:50:21 +00002515 if( extraUnref ){
2516 sqlitepager_unref(extraUnref);
2517 }
drh8b2f49b2001-06-08 00:21:52 +00002518 for(i=0; i<nOld; i++){
drh6b308672002-07-08 02:16:37 +00002519 if( apOld[i]!=0 && apOld[i]!=&aOld[i] ) sqlitepager_unref(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00002520 }
drh14acc042001-06-10 19:56:58 +00002521 for(i=0; i<nNew; i++){
2522 sqlitepager_unref(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002523 }
drh14acc042001-06-10 19:56:58 +00002524 if( pCur && pCur->pPage==0 ){
2525 pCur->pPage = pParent;
2526 pCur->idx = 0;
2527 }else{
2528 sqlitepager_unref(pParent);
drh8b2f49b2001-06-08 00:21:52 +00002529 }
2530 return rc;
2531}
2532
2533/*
drhf74b8d92002-09-01 23:20:45 +00002534** This routine checks all cursors that point to the same table
2535** as pCur points to. If any of those cursors were opened with
2536** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
2537** cursors point to the same table were opened with wrFlag==1
2538** then this routine returns SQLITE_OK.
2539**
2540** In addition to checking for read-locks (where a read-lock
2541** means a cursor opened with wrFlag==0) this routine also moves
2542** all cursors other than pCur so that they are pointing to the
2543** first Cell on root page. This is necessary because an insert
2544** or delete might change the number of cells on a page or delete
2545** a page entirely and we do not want to leave any cursors
2546** pointing to non-existant pages or cells.
2547*/
2548static int checkReadLocks(BtCursor *pCur){
2549 BtCursor *p;
2550 assert( pCur->wrFlag );
2551 for(p=pCur->pShared; p!=pCur; p=p->pShared){
2552 assert( p );
2553 assert( p->pgnoRoot==pCur->pgnoRoot );
2554 if( p->wrFlag==0 ) return SQLITE_LOCKED;
2555 if( sqlitepager_pagenumber(p->pPage)!=p->pgnoRoot ){
2556 moveToRoot(p);
2557 }
2558 }
2559 return SQLITE_OK;
2560}
2561
2562/*
drh3b7511c2001-05-26 13:15:44 +00002563** Insert a new record into the BTree. The key is given by (pKey,nKey)
2564** and the data is given by (pData,nData). The cursor is used only to
2565** define what database the record should be inserted into. The cursor
drh14acc042001-06-10 19:56:58 +00002566** is left pointing at the new record.
drh3b7511c2001-05-26 13:15:44 +00002567*/
2568int sqliteBtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00002569 BtCursor *pCur, /* Insert data into the table of this cursor */
drhbe0072d2001-09-13 14:46:09 +00002570 const void *pKey, int nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00002571 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00002572){
2573 Cell newCell;
2574 int rc;
2575 int loc;
drh14acc042001-06-10 19:56:58 +00002576 int szNew;
drh3b7511c2001-05-26 13:15:44 +00002577 MemPage *pPage;
2578 Btree *pBt = pCur->pBt;
2579
drhecdc7532001-09-23 02:35:53 +00002580 if( pCur->pPage==0 ){
2581 return SQLITE_ABORT; /* A rollback destroyed this cursor */
2582 }
drhf74b8d92002-09-01 23:20:45 +00002583 if( !pBt->inTrans || nKey+nData==0 ){
2584 /* Must start a transaction before doing an insert */
2585 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00002586 }
drhf74b8d92002-09-01 23:20:45 +00002587 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00002588 if( !pCur->wrFlag ){
2589 return SQLITE_PERM; /* Cursor not open for writing */
2590 }
drhf74b8d92002-09-01 23:20:45 +00002591 if( checkReadLocks(pCur) ){
2592 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
2593 }
drh14acc042001-06-10 19:56:58 +00002594 rc = sqliteBtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00002595 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002596 pPage = pCur->pPage;
drh7aa128d2002-06-21 13:09:16 +00002597 assert( pPage->isInit );
drh14acc042001-06-10 19:56:58 +00002598 rc = sqlitepager_write(pPage);
drhbd03cae2001-06-02 02:40:57 +00002599 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00002600 rc = fillInCell(pBt, &newCell, pKey, nKey, pData, nData);
2601 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002602 szNew = cellSize(pBt, &newCell);
drh3b7511c2001-05-26 13:15:44 +00002603 if( loc==0 ){
drh14acc042001-06-10 19:56:58 +00002604 newCell.h.leftChild = pPage->apCell[pCur->idx]->h.leftChild;
2605 rc = clearCell(pBt, pPage->apCell[pCur->idx]);
drh5e2f8b92001-05-28 00:41:15 +00002606 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002607 dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pPage->apCell[pCur->idx]));
drh7c717f72001-06-24 20:39:41 +00002608 }else if( loc<0 && pPage->nCell>0 ){
drh14acc042001-06-10 19:56:58 +00002609 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
2610 pCur->idx++;
2611 }else{
2612 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
drh3b7511c2001-05-26 13:15:44 +00002613 }
drh0d316a42002-08-11 20:10:47 +00002614 insertCell(pBt, pPage, pCur->idx, &newCell, szNew);
drh14acc042001-06-10 19:56:58 +00002615 rc = balance(pCur->pBt, pPage, pCur);
drh3fc190c2001-09-14 03:24:23 +00002616 /* sqliteBtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
2617 /* fflush(stdout); */
drh2dcc9aa2002-12-04 13:40:25 +00002618 pCur->eSkip = SKIP_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00002619 return rc;
2620}
2621
2622/*
drhbd03cae2001-06-02 02:40:57 +00002623** Delete the entry that the cursor is pointing to.
drh5e2f8b92001-05-28 00:41:15 +00002624**
drhbd03cae2001-06-02 02:40:57 +00002625** The cursor is left pointing at either the next or the previous
2626** entry. If the cursor is left pointing to the next entry, then
drh2dcc9aa2002-12-04 13:40:25 +00002627** the pCur->eSkip flag is set to SKIP_NEXT which forces the next call to
drhbd03cae2001-06-02 02:40:57 +00002628** sqliteBtreeNext() to be a no-op. That way, you can always call
2629** sqliteBtreeNext() after a delete and the cursor will be left
drh2dcc9aa2002-12-04 13:40:25 +00002630** pointing to the first entry after the deleted entry. Similarly,
2631** pCur->eSkip is set to SKIP_PREV is the cursor is left pointing to
2632** the entry prior to the deleted entry so that a subsequent call to
2633** sqliteBtreePrevious() will always leave the cursor pointing at the
2634** entry immediately before the one that was deleted.
drh3b7511c2001-05-26 13:15:44 +00002635*/
2636int sqliteBtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00002637 MemPage *pPage = pCur->pPage;
2638 Cell *pCell;
2639 int rc;
drh8c42ca92001-06-22 19:15:00 +00002640 Pgno pgnoChild;
drh0d316a42002-08-11 20:10:47 +00002641 Btree *pBt = pCur->pBt;
drh8b2f49b2001-06-08 00:21:52 +00002642
drh7aa128d2002-06-21 13:09:16 +00002643 assert( pPage->isInit );
drhecdc7532001-09-23 02:35:53 +00002644 if( pCur->pPage==0 ){
2645 return SQLITE_ABORT; /* A rollback destroyed this cursor */
2646 }
drhf74b8d92002-09-01 23:20:45 +00002647 if( !pBt->inTrans ){
2648 /* Must start a transaction before doing a delete */
2649 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00002650 }
drhf74b8d92002-09-01 23:20:45 +00002651 assert( !pBt->readOnly );
drhbd03cae2001-06-02 02:40:57 +00002652 if( pCur->idx >= pPage->nCell ){
2653 return SQLITE_ERROR; /* The cursor is not pointing to anything */
2654 }
drhecdc7532001-09-23 02:35:53 +00002655 if( !pCur->wrFlag ){
2656 return SQLITE_PERM; /* Did not open this cursor for writing */
2657 }
drhf74b8d92002-09-01 23:20:45 +00002658 if( checkReadLocks(pCur) ){
2659 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
2660 }
drhbd03cae2001-06-02 02:40:57 +00002661 rc = sqlitepager_write(pPage);
2662 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002663 pCell = pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00002664 pgnoChild = SWAB32(pBt, pCell->h.leftChild);
2665 clearCell(pBt, pCell);
drh14acc042001-06-10 19:56:58 +00002666 if( pgnoChild ){
2667 /*
drh5e00f6c2001-09-13 13:46:56 +00002668 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00002669 ** do something we will leave a hole on an internal page.
2670 ** We have to fill the hole by moving in a cell from a leaf. The
2671 ** next Cell after the one to be deleted is guaranteed to exist and
2672 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00002673 */
drh14acc042001-06-10 19:56:58 +00002674 BtCursor leafCur;
2675 Cell *pNext;
2676 int szNext;
drh8c1238a2003-01-02 14:43:55 +00002677 int notUsed;
drh14acc042001-06-10 19:56:58 +00002678 getTempCursor(pCur, &leafCur);
drh8c1238a2003-01-02 14:43:55 +00002679 rc = sqliteBtreeNext(&leafCur, &notUsed);
drh14acc042001-06-10 19:56:58 +00002680 if( rc!=SQLITE_OK ){
2681 return SQLITE_CORRUPT;
drh5e2f8b92001-05-28 00:41:15 +00002682 }
drh6019e162001-07-02 17:51:45 +00002683 rc = sqlitepager_write(leafCur.pPage);
2684 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002685 dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pCell));
drh8c42ca92001-06-22 19:15:00 +00002686 pNext = leafCur.pPage->apCell[leafCur.idx];
drh0d316a42002-08-11 20:10:47 +00002687 szNext = cellSize(pBt, pNext);
2688 pNext->h.leftChild = SWAB32(pBt, pgnoChild);
2689 insertCell(pBt, pPage, pCur->idx, pNext, szNext);
2690 rc = balance(pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002691 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00002692 pCur->eSkip = SKIP_NEXT;
drh0d316a42002-08-11 20:10:47 +00002693 dropCell(pBt, leafCur.pPage, leafCur.idx, szNext);
2694 rc = balance(pBt, leafCur.pPage, pCur);
drh8c42ca92001-06-22 19:15:00 +00002695 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00002696 }else{
drh0d316a42002-08-11 20:10:47 +00002697 dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pCell));
drh5edc3122001-09-13 21:53:09 +00002698 if( pCur->idx>=pPage->nCell ){
2699 pCur->idx = pPage->nCell-1;
drhf5bf0a72001-11-23 00:24:12 +00002700 if( pCur->idx<0 ){
2701 pCur->idx = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002702 pCur->eSkip = SKIP_NEXT;
drhf5bf0a72001-11-23 00:24:12 +00002703 }else{
drh2dcc9aa2002-12-04 13:40:25 +00002704 pCur->eSkip = SKIP_PREV;
drhf5bf0a72001-11-23 00:24:12 +00002705 }
drh6019e162001-07-02 17:51:45 +00002706 }else{
drh2dcc9aa2002-12-04 13:40:25 +00002707 pCur->eSkip = SKIP_NEXT;
drh6019e162001-07-02 17:51:45 +00002708 }
drh0d316a42002-08-11 20:10:47 +00002709 rc = balance(pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002710 }
drh5e2f8b92001-05-28 00:41:15 +00002711 return rc;
drh3b7511c2001-05-26 13:15:44 +00002712}
drh8b2f49b2001-06-08 00:21:52 +00002713
2714/*
drhc6b52df2002-01-04 03:09:29 +00002715** Create a new BTree table. Write into *piTable the page
2716** number for the root page of the new table.
2717**
2718** In the current implementation, BTree tables and BTree indices are the
2719** the same. But in the future, we may change this so that BTree tables
2720** are restricted to having a 4-byte integer key and arbitrary data and
2721** BTree indices are restricted to having an arbitrary key and no data.
drh8b2f49b2001-06-08 00:21:52 +00002722*/
2723int sqliteBtreeCreateTable(Btree *pBt, int *piTable){
2724 MemPage *pRoot;
2725 Pgno pgnoRoot;
2726 int rc;
2727 if( !pBt->inTrans ){
drhf74b8d92002-09-01 23:20:45 +00002728 /* Must start a transaction first */
2729 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00002730 }
drh5df72a52002-06-06 23:16:05 +00002731 if( pBt->readOnly ){
2732 return SQLITE_READONLY;
2733 }
drhbea00b92002-07-08 10:59:50 +00002734 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 0);
drh8b2f49b2001-06-08 00:21:52 +00002735 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002736 assert( sqlitepager_iswriteable(pRoot) );
drh0d316a42002-08-11 20:10:47 +00002737 zeroPage(pBt, pRoot);
drh8b2f49b2001-06-08 00:21:52 +00002738 sqlitepager_unref(pRoot);
2739 *piTable = (int)pgnoRoot;
2740 return SQLITE_OK;
2741}
2742
2743/*
drhc6b52df2002-01-04 03:09:29 +00002744** Create a new BTree index. Write into *piTable the page
2745** number for the root page of the new index.
2746**
2747** In the current implementation, BTree tables and BTree indices are the
2748** the same. But in the future, we may change this so that BTree tables
2749** are restricted to having a 4-byte integer key and arbitrary data and
2750** BTree indices are restricted to having an arbitrary key and no data.
2751*/
2752int sqliteBtreeCreateIndex(Btree *pBt, int *piIndex){
drh5df72a52002-06-06 23:16:05 +00002753 return sqliteBtreeCreateTable(pBt, piIndex);
drhc6b52df2002-01-04 03:09:29 +00002754}
2755
2756/*
drh8b2f49b2001-06-08 00:21:52 +00002757** Erase the given database page and all its children. Return
2758** the page to the freelist.
2759*/
drh2aa679f2001-06-25 02:11:07 +00002760static int clearDatabasePage(Btree *pBt, Pgno pgno, int freePageFlag){
drh8b2f49b2001-06-08 00:21:52 +00002761 MemPage *pPage;
2762 int rc;
drh8b2f49b2001-06-08 00:21:52 +00002763 Cell *pCell;
2764 int idx;
2765
drh8c42ca92001-06-22 19:15:00 +00002766 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pPage);
drh8b2f49b2001-06-08 00:21:52 +00002767 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002768 rc = sqlitepager_write(pPage);
2769 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002770 rc = initPage(pBt, pPage, pgno, 0);
drh7aa128d2002-06-21 13:09:16 +00002771 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002772 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh8b2f49b2001-06-08 00:21:52 +00002773 while( idx>0 ){
drh14acc042001-06-10 19:56:58 +00002774 pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +00002775 idx = SWAB16(pBt, pCell->h.iNext);
drh8b2f49b2001-06-08 00:21:52 +00002776 if( pCell->h.leftChild ){
drh0d316a42002-08-11 20:10:47 +00002777 rc = clearDatabasePage(pBt, SWAB32(pBt, pCell->h.leftChild), 1);
drh8b2f49b2001-06-08 00:21:52 +00002778 if( rc ) return rc;
2779 }
drh8c42ca92001-06-22 19:15:00 +00002780 rc = clearCell(pBt, pCell);
drh8b2f49b2001-06-08 00:21:52 +00002781 if( rc ) return rc;
2782 }
drh2aa679f2001-06-25 02:11:07 +00002783 if( pPage->u.hdr.rightChild ){
drh0d316a42002-08-11 20:10:47 +00002784 rc = clearDatabasePage(pBt, SWAB32(pBt, pPage->u.hdr.rightChild), 1);
drh2aa679f2001-06-25 02:11:07 +00002785 if( rc ) return rc;
2786 }
2787 if( freePageFlag ){
2788 rc = freePage(pBt, pPage, pgno);
2789 }else{
drh0d316a42002-08-11 20:10:47 +00002790 zeroPage(pBt, pPage);
drh2aa679f2001-06-25 02:11:07 +00002791 }
drhdd793422001-06-28 01:54:48 +00002792 sqlitepager_unref(pPage);
drh2aa679f2001-06-25 02:11:07 +00002793 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002794}
2795
2796/*
2797** Delete all information from a single table in the database.
2798*/
2799int sqliteBtreeClearTable(Btree *pBt, int iTable){
2800 int rc;
drhf74b8d92002-09-01 23:20:45 +00002801 BtCursor *pCur;
drh8b2f49b2001-06-08 00:21:52 +00002802 if( !pBt->inTrans ){
drhf74b8d92002-09-01 23:20:45 +00002803 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00002804 }
drhf74b8d92002-09-01 23:20:45 +00002805 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
2806 if( pCur->pgnoRoot==(Pgno)iTable ){
2807 if( pCur->wrFlag==0 ) return SQLITE_LOCKED;
2808 moveToRoot(pCur);
2809 }
drhecdc7532001-09-23 02:35:53 +00002810 }
drh2aa679f2001-06-25 02:11:07 +00002811 rc = clearDatabasePage(pBt, (Pgno)iTable, 0);
drh8b2f49b2001-06-08 00:21:52 +00002812 if( rc ){
2813 sqliteBtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00002814 }
drh8c42ca92001-06-22 19:15:00 +00002815 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002816}
2817
2818/*
2819** Erase all information in a table and add the root of the table to
2820** the freelist. Except, the root of the principle table (the one on
2821** page 2) is never added to the freelist.
2822*/
2823int sqliteBtreeDropTable(Btree *pBt, int iTable){
2824 int rc;
2825 MemPage *pPage;
drhf74b8d92002-09-01 23:20:45 +00002826 BtCursor *pCur;
drh8b2f49b2001-06-08 00:21:52 +00002827 if( !pBt->inTrans ){
drhf74b8d92002-09-01 23:20:45 +00002828 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00002829 }
drhf74b8d92002-09-01 23:20:45 +00002830 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
2831 if( pCur->pgnoRoot==(Pgno)iTable ){
2832 return SQLITE_LOCKED; /* Cannot drop a table that has a cursor */
2833 }
drh5df72a52002-06-06 23:16:05 +00002834 }
drh8c42ca92001-06-22 19:15:00 +00002835 rc = sqlitepager_get(pBt->pPager, (Pgno)iTable, (void**)&pPage);
drh2aa679f2001-06-25 02:11:07 +00002836 if( rc ) return rc;
2837 rc = sqliteBtreeClearTable(pBt, iTable);
2838 if( rc ) return rc;
2839 if( iTable>2 ){
2840 rc = freePage(pBt, pPage, iTable);
2841 }else{
drh0d316a42002-08-11 20:10:47 +00002842 zeroPage(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002843 }
drhdd793422001-06-28 01:54:48 +00002844 sqlitepager_unref(pPage);
drh8b2f49b2001-06-08 00:21:52 +00002845 return rc;
2846}
2847
2848/*
2849** Read the meta-information out of a database file.
2850*/
2851int sqliteBtreeGetMeta(Btree *pBt, int *aMeta){
2852 PageOne *pP1;
2853 int rc;
drh0d316a42002-08-11 20:10:47 +00002854 int i;
drh8b2f49b2001-06-08 00:21:52 +00002855
drh8c42ca92001-06-22 19:15:00 +00002856 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00002857 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002858 aMeta[0] = SWAB32(pBt, pP1->nFree);
2859 for(i=0; i<sizeof(pP1->aMeta)/sizeof(pP1->aMeta[0]); i++){
2860 aMeta[i+1] = SWAB32(pBt, pP1->aMeta[i]);
2861 }
drh8b2f49b2001-06-08 00:21:52 +00002862 sqlitepager_unref(pP1);
2863 return SQLITE_OK;
2864}
2865
2866/*
2867** Write meta-information back into the database.
2868*/
2869int sqliteBtreeUpdateMeta(Btree *pBt, int *aMeta){
2870 PageOne *pP1;
drh0d316a42002-08-11 20:10:47 +00002871 int rc, i;
drh8b2f49b2001-06-08 00:21:52 +00002872 if( !pBt->inTrans ){
drhf74b8d92002-09-01 23:20:45 +00002873 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +00002874 }
drh8b2f49b2001-06-08 00:21:52 +00002875 pP1 = pBt->page1;
2876 rc = sqlitepager_write(pP1);
drh9adf9ac2002-05-15 11:44:13 +00002877 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002878 for(i=0; i<sizeof(pP1->aMeta)/sizeof(pP1->aMeta[0]); i++){
2879 pP1->aMeta[i] = SWAB32(pBt, aMeta[i+1]);
2880 }
drh8b2f49b2001-06-08 00:21:52 +00002881 return SQLITE_OK;
2882}
drh8c42ca92001-06-22 19:15:00 +00002883
drh5eddca62001-06-30 21:53:53 +00002884/******************************************************************************
2885** The complete implementation of the BTree subsystem is above this line.
2886** All the code the follows is for testing and troubleshooting the BTree
2887** subsystem. None of the code that follows is used during normal operation.
drh5eddca62001-06-30 21:53:53 +00002888******************************************************************************/
drh5eddca62001-06-30 21:53:53 +00002889
drh8c42ca92001-06-22 19:15:00 +00002890/*
2891** Print a disassembly of the given page on standard output. This routine
2892** is used for debugging and testing only.
2893*/
drhaaab5722002-02-19 13:39:21 +00002894#ifdef SQLITE_TEST
drh6019e162001-07-02 17:51:45 +00002895int sqliteBtreePageDump(Btree *pBt, int pgno, int recursive){
drh8c42ca92001-06-22 19:15:00 +00002896 int rc;
2897 MemPage *pPage;
2898 int i, j;
2899 int nFree;
2900 u16 idx;
2901 char range[20];
2902 unsigned char payload[20];
2903 rc = sqlitepager_get(pBt->pPager, (Pgno)pgno, (void**)&pPage);
2904 if( rc ){
2905 return rc;
2906 }
drh6019e162001-07-02 17:51:45 +00002907 if( recursive ) printf("PAGE %d:\n", pgno);
drh8c42ca92001-06-22 19:15:00 +00002908 i = 0;
drh0d316a42002-08-11 20:10:47 +00002909 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh8c42ca92001-06-22 19:15:00 +00002910 while( idx>0 && idx<=SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2911 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +00002912 int sz = cellSize(pBt, pCell);
drh8c42ca92001-06-22 19:15:00 +00002913 sprintf(range,"%d..%d", idx, idx+sz-1);
drh0d316a42002-08-11 20:10:47 +00002914 sz = NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h);
drh8c42ca92001-06-22 19:15:00 +00002915 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
2916 memcpy(payload, pCell->aPayload, sz);
2917 for(j=0; j<sz; j++){
2918 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
2919 }
2920 payload[sz] = 0;
2921 printf(
drh6019e162001-07-02 17:51:45 +00002922 "cell %2d: i=%-10s chld=%-4d nk=%-4d nd=%-4d payload=%s\n",
drh0d316a42002-08-11 20:10:47 +00002923 i, range, (int)pCell->h.leftChild,
2924 NKEY(pBt, pCell->h), NDATA(pBt, pCell->h),
drh2aa679f2001-06-25 02:11:07 +00002925 payload
drh8c42ca92001-06-22 19:15:00 +00002926 );
drh6019e162001-07-02 17:51:45 +00002927 if( pPage->isInit && pPage->apCell[i]!=pCell ){
drh2aa679f2001-06-25 02:11:07 +00002928 printf("**** apCell[%d] does not match on prior entry ****\n", i);
2929 }
drh7c717f72001-06-24 20:39:41 +00002930 i++;
drh0d316a42002-08-11 20:10:47 +00002931 idx = SWAB16(pBt, pCell->h.iNext);
drh8c42ca92001-06-22 19:15:00 +00002932 }
2933 if( idx!=0 ){
2934 printf("ERROR: next cell index out of range: %d\n", idx);
2935 }
drh0d316a42002-08-11 20:10:47 +00002936 printf("right_child: %d\n", SWAB32(pBt, pPage->u.hdr.rightChild));
drh8c42ca92001-06-22 19:15:00 +00002937 nFree = 0;
2938 i = 0;
drh0d316a42002-08-11 20:10:47 +00002939 idx = SWAB16(pBt, pPage->u.hdr.firstFree);
drh8c42ca92001-06-22 19:15:00 +00002940 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2941 FreeBlk *p = (FreeBlk*)&pPage->u.aDisk[idx];
2942 sprintf(range,"%d..%d", idx, idx+p->iSize-1);
drh0d316a42002-08-11 20:10:47 +00002943 nFree += SWAB16(pBt, p->iSize);
drh8c42ca92001-06-22 19:15:00 +00002944 printf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
drh0d316a42002-08-11 20:10:47 +00002945 i, range, SWAB16(pBt, p->iSize), nFree);
2946 idx = SWAB16(pBt, p->iNext);
drh2aa679f2001-06-25 02:11:07 +00002947 i++;
drh8c42ca92001-06-22 19:15:00 +00002948 }
2949 if( idx!=0 ){
2950 printf("ERROR: next freeblock index out of range: %d\n", idx);
2951 }
drh6019e162001-07-02 17:51:45 +00002952 if( recursive && pPage->u.hdr.rightChild!=0 ){
drh0d316a42002-08-11 20:10:47 +00002953 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh6019e162001-07-02 17:51:45 +00002954 while( idx>0 && idx<SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2955 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +00002956 sqliteBtreePageDump(pBt, SWAB32(pBt, pCell->h.leftChild), 1);
2957 idx = SWAB16(pBt, pCell->h.iNext);
drh6019e162001-07-02 17:51:45 +00002958 }
drh0d316a42002-08-11 20:10:47 +00002959 sqliteBtreePageDump(pBt, SWAB32(pBt, pPage->u.hdr.rightChild), 1);
drh6019e162001-07-02 17:51:45 +00002960 }
drh8c42ca92001-06-22 19:15:00 +00002961 sqlitepager_unref(pPage);
2962 return SQLITE_OK;
2963}
drhaaab5722002-02-19 13:39:21 +00002964#endif
drh8c42ca92001-06-22 19:15:00 +00002965
drhaaab5722002-02-19 13:39:21 +00002966#ifdef SQLITE_TEST
drh8c42ca92001-06-22 19:15:00 +00002967/*
drh2aa679f2001-06-25 02:11:07 +00002968** Fill aResult[] with information about the entry and page that the
2969** cursor is pointing to.
2970**
2971** aResult[0] = The page number
2972** aResult[1] = The entry number
2973** aResult[2] = Total number of entries on this page
2974** aResult[3] = Size of this entry
2975** aResult[4] = Number of free bytes on this page
2976** aResult[5] = Number of free blocks on the page
2977** aResult[6] = Page number of the left child of this entry
2978** aResult[7] = Page number of the right child for the whole page
drh5eddca62001-06-30 21:53:53 +00002979**
2980** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00002981*/
2982int sqliteBtreeCursorDump(BtCursor *pCur, int *aResult){
drh2aa679f2001-06-25 02:11:07 +00002983 int cnt, idx;
2984 MemPage *pPage = pCur->pPage;
drh0d316a42002-08-11 20:10:47 +00002985 Btree *pBt = pCur->pBt;
drh2aa679f2001-06-25 02:11:07 +00002986 aResult[0] = sqlitepager_pagenumber(pPage);
drh8c42ca92001-06-22 19:15:00 +00002987 aResult[1] = pCur->idx;
drh2aa679f2001-06-25 02:11:07 +00002988 aResult[2] = pPage->nCell;
2989 if( pCur->idx>=0 && pCur->idx<pPage->nCell ){
drh0d316a42002-08-11 20:10:47 +00002990 aResult[3] = cellSize(pBt, pPage->apCell[pCur->idx]);
2991 aResult[6] = SWAB32(pBt, pPage->apCell[pCur->idx]->h.leftChild);
drh2aa679f2001-06-25 02:11:07 +00002992 }else{
2993 aResult[3] = 0;
2994 aResult[6] = 0;
2995 }
2996 aResult[4] = pPage->nFree;
2997 cnt = 0;
drh0d316a42002-08-11 20:10:47 +00002998 idx = SWAB16(pBt, pPage->u.hdr.firstFree);
drh2aa679f2001-06-25 02:11:07 +00002999 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
3000 cnt++;
drh0d316a42002-08-11 20:10:47 +00003001 idx = SWAB16(pBt, ((FreeBlk*)&pPage->u.aDisk[idx])->iNext);
drh2aa679f2001-06-25 02:11:07 +00003002 }
3003 aResult[5] = cnt;
drh0d316a42002-08-11 20:10:47 +00003004 aResult[7] = SWAB32(pBt, pPage->u.hdr.rightChild);
drh8c42ca92001-06-22 19:15:00 +00003005 return SQLITE_OK;
3006}
drhaaab5722002-02-19 13:39:21 +00003007#endif
drhdd793422001-06-28 01:54:48 +00003008
drhaaab5722002-02-19 13:39:21 +00003009#ifdef SQLITE_TEST
drhdd793422001-06-28 01:54:48 +00003010/*
drh5eddca62001-06-30 21:53:53 +00003011** Return the pager associated with a BTree. This routine is used for
3012** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00003013*/
3014Pager *sqliteBtreePager(Btree *pBt){
3015 return pBt->pPager;
3016}
drhaaab5722002-02-19 13:39:21 +00003017#endif
drh5eddca62001-06-30 21:53:53 +00003018
3019/*
3020** This structure is passed around through all the sanity checking routines
3021** in order to keep track of some global state information.
3022*/
drhaaab5722002-02-19 13:39:21 +00003023typedef struct IntegrityCk IntegrityCk;
3024struct IntegrityCk {
drh100569d2001-10-02 13:01:48 +00003025 Btree *pBt; /* The tree being checked out */
3026 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
3027 int nPage; /* Number of pages in the database */
3028 int *anRef; /* Number of times each page is referenced */
3029 int nTreePage; /* Number of BTree pages */
3030 int nByte; /* Number of bytes of data stored on BTree pages */
3031 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00003032};
3033
3034/*
3035** Append a message to the error message string.
3036*/
drhaaab5722002-02-19 13:39:21 +00003037static void checkAppendMsg(IntegrityCk *pCheck, char *zMsg1, char *zMsg2){
drh5eddca62001-06-30 21:53:53 +00003038 if( pCheck->zErrMsg ){
3039 char *zOld = pCheck->zErrMsg;
3040 pCheck->zErrMsg = 0;
3041 sqliteSetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, 0);
3042 sqliteFree(zOld);
3043 }else{
3044 sqliteSetString(&pCheck->zErrMsg, zMsg1, zMsg2, 0);
3045 }
3046}
3047
3048/*
3049** Add 1 to the reference count for page iPage. If this is the second
3050** reference to the page, add an error message to pCheck->zErrMsg.
3051** Return 1 if there are 2 ore more references to the page and 0 if
3052** if this is the first reference to the page.
3053**
3054** Also check that the page number is in bounds.
3055*/
drhaaab5722002-02-19 13:39:21 +00003056static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00003057 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00003058 if( iPage>pCheck->nPage || iPage<0 ){
drh5eddca62001-06-30 21:53:53 +00003059 char zBuf[100];
3060 sprintf(zBuf, "invalid page number %d", iPage);
3061 checkAppendMsg(pCheck, zContext, zBuf);
3062 return 1;
3063 }
3064 if( pCheck->anRef[iPage]==1 ){
3065 char zBuf[100];
3066 sprintf(zBuf, "2nd reference to page %d", iPage);
3067 checkAppendMsg(pCheck, zContext, zBuf);
3068 return 1;
3069 }
3070 return (pCheck->anRef[iPage]++)>1;
3071}
3072
3073/*
3074** Check the integrity of the freelist or of an overflow page list.
3075** Verify that the number of pages on the list is N.
3076*/
drh30e58752002-03-02 20:41:57 +00003077static void checkList(
3078 IntegrityCk *pCheck, /* Integrity checking context */
3079 int isFreeList, /* True for a freelist. False for overflow page list */
3080 int iPage, /* Page number for first page in the list */
3081 int N, /* Expected number of pages in the list */
3082 char *zContext /* Context for error messages */
3083){
3084 int i;
drh5eddca62001-06-30 21:53:53 +00003085 char zMsg[100];
drh30e58752002-03-02 20:41:57 +00003086 while( N-- > 0 ){
drh5eddca62001-06-30 21:53:53 +00003087 OverflowPage *pOvfl;
3088 if( iPage<1 ){
3089 sprintf(zMsg, "%d pages missing from overflow list", N+1);
3090 checkAppendMsg(pCheck, zContext, zMsg);
3091 break;
3092 }
3093 if( checkRef(pCheck, iPage, zContext) ) break;
3094 if( sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
3095 sprintf(zMsg, "failed to get page %d", iPage);
3096 checkAppendMsg(pCheck, zContext, zMsg);
3097 break;
3098 }
drh30e58752002-03-02 20:41:57 +00003099 if( isFreeList ){
3100 FreelistInfo *pInfo = (FreelistInfo*)pOvfl->aPayload;
drh0d316a42002-08-11 20:10:47 +00003101 int n = SWAB32(pCheck->pBt, pInfo->nFree);
3102 for(i=0; i<n; i++){
3103 checkRef(pCheck, SWAB32(pCheck->pBt, pInfo->aFree[i]), zMsg);
drh30e58752002-03-02 20:41:57 +00003104 }
drh0d316a42002-08-11 20:10:47 +00003105 N -= n;
drh30e58752002-03-02 20:41:57 +00003106 }
drh0d316a42002-08-11 20:10:47 +00003107 iPage = SWAB32(pCheck->pBt, pOvfl->iNext);
drh5eddca62001-06-30 21:53:53 +00003108 sqlitepager_unref(pOvfl);
3109 }
3110}
3111
3112/*
drh1bffb9c2002-02-03 17:37:36 +00003113** Return negative if zKey1<zKey2.
3114** Return zero if zKey1==zKey2.
3115** Return positive if zKey1>zKey2.
3116*/
3117static int keyCompare(
3118 const char *zKey1, int nKey1,
3119 const char *zKey2, int nKey2
3120){
3121 int min = nKey1>nKey2 ? nKey2 : nKey1;
3122 int c = memcmp(zKey1, zKey2, min);
3123 if( c==0 ){
3124 c = nKey1 - nKey2;
3125 }
3126 return c;
3127}
3128
3129/*
drh5eddca62001-06-30 21:53:53 +00003130** Do various sanity checks on a single page of a tree. Return
3131** the tree depth. Root pages return 0. Parents of root pages
3132** return 1, and so forth.
3133**
3134** These checks are done:
3135**
3136** 1. Make sure that cells and freeblocks do not overlap
3137** but combine to completely cover the page.
3138** 2. Make sure cell keys are in order.
3139** 3. Make sure no key is less than or equal to zLowerBound.
3140** 4. Make sure no key is greater than or equal to zUpperBound.
3141** 5. Check the integrity of overflow pages.
3142** 6. Recursively call checkTreePage on all children.
3143** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00003144** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00003145** the root of the tree.
3146*/
3147static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00003148 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00003149 int iPage, /* Page number of the page to check */
3150 MemPage *pParent, /* Parent page */
3151 char *zParentContext, /* Parent context */
3152 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00003153 int nLower, /* Number of characters in zLowerBound */
3154 char *zUpperBound, /* All keys should be less than this, if not NULL */
3155 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00003156){
3157 MemPage *pPage;
3158 int i, rc, depth, d2, pgno;
3159 char *zKey1, *zKey2;
drh1bffb9c2002-02-03 17:37:36 +00003160 int nKey1, nKey2;
drh5eddca62001-06-30 21:53:53 +00003161 BtCursor cur;
drh0d316a42002-08-11 20:10:47 +00003162 Btree *pBt;
drh5eddca62001-06-30 21:53:53 +00003163 char zMsg[100];
3164 char zContext[100];
3165 char hit[SQLITE_PAGE_SIZE];
3166
3167 /* Check that the page exists
3168 */
drh0d316a42002-08-11 20:10:47 +00003169 cur.pBt = pBt = pCheck->pBt;
drh5eddca62001-06-30 21:53:53 +00003170 if( iPage==0 ) return 0;
3171 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
3172 sprintf(zContext, "On tree page %d: ", iPage);
3173 if( (rc = sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pPage))!=0 ){
3174 sprintf(zMsg, "unable to get the page. error code=%d", rc);
3175 checkAppendMsg(pCheck, zContext, zMsg);
3176 return 0;
3177 }
drh0d316a42002-08-11 20:10:47 +00003178 if( (rc = initPage(pBt, pPage, (Pgno)iPage, pParent))!=0 ){
drh5eddca62001-06-30 21:53:53 +00003179 sprintf(zMsg, "initPage() returns error code %d", rc);
3180 checkAppendMsg(pCheck, zContext, zMsg);
3181 sqlitepager_unref(pPage);
3182 return 0;
3183 }
3184
3185 /* Check out all the cells.
3186 */
3187 depth = 0;
drh1bffb9c2002-02-03 17:37:36 +00003188 if( zLowerBound ){
3189 zKey1 = sqliteMalloc( nLower+1 );
3190 memcpy(zKey1, zLowerBound, nLower);
3191 zKey1[nLower] = 0;
3192 }else{
3193 zKey1 = 0;
3194 }
3195 nKey1 = nLower;
drh5eddca62001-06-30 21:53:53 +00003196 cur.pPage = pPage;
drh5eddca62001-06-30 21:53:53 +00003197 for(i=0; i<pPage->nCell; i++){
3198 Cell *pCell = pPage->apCell[i];
3199 int sz;
3200
3201 /* Check payload overflow pages
3202 */
drh0d316a42002-08-11 20:10:47 +00003203 nKey2 = NKEY(pBt, pCell->h);
3204 sz = nKey2 + NDATA(pBt, pCell->h);
drh5eddca62001-06-30 21:53:53 +00003205 sprintf(zContext, "On page %d cell %d: ", iPage, i);
3206 if( sz>MX_LOCAL_PAYLOAD ){
3207 int nPage = (sz - MX_LOCAL_PAYLOAD + OVERFLOW_SIZE - 1)/OVERFLOW_SIZE;
drh0d316a42002-08-11 20:10:47 +00003208 checkList(pCheck, 0, SWAB32(pBt, pCell->ovfl), nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00003209 }
3210
3211 /* Check that keys are in the right order
3212 */
3213 cur.idx = i;
drh8c1238a2003-01-02 14:43:55 +00003214 zKey2 = sqliteMallocRaw( nKey2+1 );
drh1bffb9c2002-02-03 17:37:36 +00003215 getPayload(&cur, 0, nKey2, zKey2);
3216 if( zKey1 && keyCompare(zKey1, nKey1, zKey2, nKey2)>=0 ){
drh5eddca62001-06-30 21:53:53 +00003217 checkAppendMsg(pCheck, zContext, "Key is out of order");
3218 }
3219
3220 /* Check sanity of left child page.
3221 */
drh0d316a42002-08-11 20:10:47 +00003222 pgno = SWAB32(pBt, pCell->h.leftChild);
drh1bffb9c2002-02-03 17:37:36 +00003223 d2 = checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zKey2,nKey2);
drh5eddca62001-06-30 21:53:53 +00003224 if( i>0 && d2!=depth ){
3225 checkAppendMsg(pCheck, zContext, "Child page depth differs");
3226 }
3227 depth = d2;
3228 sqliteFree(zKey1);
3229 zKey1 = zKey2;
drh1bffb9c2002-02-03 17:37:36 +00003230 nKey1 = nKey2;
drh5eddca62001-06-30 21:53:53 +00003231 }
drh0d316a42002-08-11 20:10:47 +00003232 pgno = SWAB32(pBt, pPage->u.hdr.rightChild);
drh5eddca62001-06-30 21:53:53 +00003233 sprintf(zContext, "On page %d at right child: ", iPage);
drh1bffb9c2002-02-03 17:37:36 +00003234 checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zUpperBound,nUpper);
drh5eddca62001-06-30 21:53:53 +00003235 sqliteFree(zKey1);
3236
3237 /* Check for complete coverage of the page
3238 */
3239 memset(hit, 0, sizeof(hit));
3240 memset(hit, 1, sizeof(PageHdr));
drh0d316a42002-08-11 20:10:47 +00003241 for(i=SWAB16(pBt, pPage->u.hdr.firstCell); i>0 && i<SQLITE_PAGE_SIZE; ){
drh5eddca62001-06-30 21:53:53 +00003242 Cell *pCell = (Cell*)&pPage->u.aDisk[i];
3243 int j;
drh0d316a42002-08-11 20:10:47 +00003244 for(j=i+cellSize(pBt, pCell)-1; j>=i; j--) hit[j]++;
3245 i = SWAB16(pBt, pCell->h.iNext);
drh5eddca62001-06-30 21:53:53 +00003246 }
drh0d316a42002-08-11 20:10:47 +00003247 for(i=SWAB16(pBt,pPage->u.hdr.firstFree); i>0 && i<SQLITE_PAGE_SIZE; ){
drh5eddca62001-06-30 21:53:53 +00003248 FreeBlk *pFBlk = (FreeBlk*)&pPage->u.aDisk[i];
3249 int j;
drh0d316a42002-08-11 20:10:47 +00003250 for(j=i+SWAB16(pBt,pFBlk->iSize)-1; j>=i; j--) hit[j]++;
3251 i = SWAB16(pBt,pFBlk->iNext);
drh5eddca62001-06-30 21:53:53 +00003252 }
3253 for(i=0; i<SQLITE_PAGE_SIZE; i++){
3254 if( hit[i]==0 ){
3255 sprintf(zMsg, "Unused space at byte %d of page %d", i, iPage);
3256 checkAppendMsg(pCheck, zMsg, 0);
3257 break;
3258 }else if( hit[i]>1 ){
3259 sprintf(zMsg, "Multiple uses for byte %d of page %d", i, iPage);
3260 checkAppendMsg(pCheck, zMsg, 0);
3261 break;
3262 }
3263 }
3264
3265 /* Check that free space is kept to a minimum
3266 */
drh6019e162001-07-02 17:51:45 +00003267#if 0
3268 if( pParent && pParent->nCell>2 && pPage->nFree>3*SQLITE_PAGE_SIZE/4 ){
drh5eddca62001-06-30 21:53:53 +00003269 sprintf(zMsg, "free space (%d) greater than max (%d)", pPage->nFree,
3270 SQLITE_PAGE_SIZE/3);
3271 checkAppendMsg(pCheck, zContext, zMsg);
3272 }
drh6019e162001-07-02 17:51:45 +00003273#endif
3274
3275 /* Update freespace totals.
3276 */
3277 pCheck->nTreePage++;
3278 pCheck->nByte += USABLE_SPACE - pPage->nFree;
drh5eddca62001-06-30 21:53:53 +00003279
3280 sqlitepager_unref(pPage);
3281 return depth;
3282}
3283
3284/*
3285** This routine does a complete check of the given BTree file. aRoot[] is
3286** an array of pages numbers were each page number is the root page of
3287** a table. nRoot is the number of entries in aRoot.
3288**
3289** If everything checks out, this routine returns NULL. If something is
3290** amiss, an error message is written into memory obtained from malloc()
3291** and a pointer to that error message is returned. The calling function
3292** is responsible for freeing the error message when it is done.
3293*/
drhaaab5722002-02-19 13:39:21 +00003294char *sqliteBtreeIntegrityCheck(Btree *pBt, int *aRoot, int nRoot){
drh5eddca62001-06-30 21:53:53 +00003295 int i;
3296 int nRef;
drhaaab5722002-02-19 13:39:21 +00003297 IntegrityCk sCheck;
drh5eddca62001-06-30 21:53:53 +00003298
3299 nRef = *sqlitepager_stats(pBt->pPager);
drhefc251d2001-07-01 22:12:01 +00003300 if( lockBtree(pBt)!=SQLITE_OK ){
3301 return sqliteStrDup("Unable to acquire a read lock on the database");
3302 }
drh5eddca62001-06-30 21:53:53 +00003303 sCheck.pBt = pBt;
3304 sCheck.pPager = pBt->pPager;
3305 sCheck.nPage = sqlitepager_pagecount(sCheck.pPager);
drh0de8c112002-07-06 16:32:14 +00003306 if( sCheck.nPage==0 ){
3307 unlockBtreeIfUnused(pBt);
3308 return 0;
3309 }
drh8c1238a2003-01-02 14:43:55 +00003310 sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
drh5eddca62001-06-30 21:53:53 +00003311 sCheck.anRef[1] = 1;
3312 for(i=2; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
3313 sCheck.zErrMsg = 0;
3314
3315 /* Check the integrity of the freelist
3316 */
drh0d316a42002-08-11 20:10:47 +00003317 checkList(&sCheck, 1, SWAB32(pBt, pBt->page1->freeList),
3318 SWAB32(pBt, pBt->page1->nFree), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00003319
3320 /* Check all the tables.
3321 */
3322 for(i=0; i<nRoot; i++){
drh4ff6dfa2002-03-03 23:06:00 +00003323 if( aRoot[i]==0 ) continue;
drh1bffb9c2002-02-03 17:37:36 +00003324 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00003325 }
3326
3327 /* Make sure every page in the file is referenced
3328 */
3329 for(i=1; i<=sCheck.nPage; i++){
3330 if( sCheck.anRef[i]==0 ){
3331 char zBuf[100];
3332 sprintf(zBuf, "Page %d is never used", i);
3333 checkAppendMsg(&sCheck, zBuf, 0);
3334 }
3335 }
3336
3337 /* Make sure this analysis did not leave any unref() pages
3338 */
drh5e00f6c2001-09-13 13:46:56 +00003339 unlockBtreeIfUnused(pBt);
drh5eddca62001-06-30 21:53:53 +00003340 if( nRef != *sqlitepager_stats(pBt->pPager) ){
3341 char zBuf[100];
3342 sprintf(zBuf,
3343 "Outstanding page count goes from %d to %d during this analysis",
3344 nRef, *sqlitepager_stats(pBt->pPager)
3345 );
3346 checkAppendMsg(&sCheck, zBuf, 0);
3347 }
3348
3349 /* Clean up and report errors.
3350 */
3351 sqliteFree(sCheck.anRef);
3352 return sCheck.zErrMsg;
3353}