blob: 193c224d663349f2beeb1bd5f3a7ddec8214b54a [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*************************************************************************
drh1a844c32002-12-04 22:29:28 +000012** $Id: btree.c,v 1.75 2002/12/04 22:29:28 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;
drh5e2f8b92001-05-28 00:41:15 +0000322 int isInit; /* True if auxiliary data is initialized */
drh72f82862001-05-24 21:06:34 +0000323 MemPage *pParent; /* The parent of this page. NULL for root */
drh14acc042001-06-10 19:56:58 +0000324 int nFree; /* Number of free bytes in u.aDisk[] */
drh306dc212001-05-21 13:45:10 +0000325 int nCell; /* Number of entries on this page */
drh14acc042001-06-10 19:56:58 +0000326 int isOverfull; /* Some apCell[] points outside u.aDisk[] */
327 Cell *apCell[MX_CELL+2]; /* All data entires in sorted order */
drh8c42ca92001-06-22 19:15:00 +0000328};
drh7e3b0a02001-04-28 16:52:40 +0000329
330/*
drh3b7511c2001-05-26 13:15:44 +0000331** The in-memory image of a disk page has the auxiliary information appended
332** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
333** that extra information.
334*/
335#define EXTRA_SIZE (sizeof(MemPage)-SQLITE_PAGE_SIZE)
336
337/*
drha059ad02001-04-17 20:09:11 +0000338** Everything we need to know about an open database
339*/
340struct Btree {
341 Pager *pPager; /* The page cache */
drh306dc212001-05-21 13:45:10 +0000342 BtCursor *pCursor; /* A list of all open cursors */
drhbd03cae2001-06-02 02:40:57 +0000343 PageOne *page1; /* First page of the database */
drh663fc632002-02-02 18:49:19 +0000344 u8 inTrans; /* True if a transaction is in progress */
345 u8 inCkpt; /* True if there is a checkpoint on the transaction */
drh5df72a52002-06-06 23:16:05 +0000346 u8 readOnly; /* True if the underlying file is readonly */
drh0d316a42002-08-11 20:10:47 +0000347 u8 needSwab; /* Need to byte-swapping */
drha059ad02001-04-17 20:09:11 +0000348};
349typedef Btree Bt;
350
drh365d68f2001-05-11 11:02:46 +0000351/*
352** A cursor is a pointer to a particular entry in the BTree.
353** The entry is identified by its MemPage and the index in
drh5e2f8b92001-05-28 00:41:15 +0000354** MemPage.apCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000355*/
drh72f82862001-05-24 21:06:34 +0000356struct BtCursor {
drh5e2f8b92001-05-28 00:41:15 +0000357 Btree *pBt; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000358 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drhf74b8d92002-09-01 23:20:45 +0000359 BtCursor *pShared; /* Loop of cursors with the same root page */
drh8b2f49b2001-06-08 00:21:52 +0000360 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000361 MemPage *pPage; /* Page that contains the entry */
drh8c42ca92001-06-22 19:15:00 +0000362 int idx; /* Index of the entry in pPage->apCell[] */
drhecdc7532001-09-23 02:35:53 +0000363 u8 wrFlag; /* True if writable */
drh2dcc9aa2002-12-04 13:40:25 +0000364 u8 eSkip; /* Determines if next step operation is a no-op */
drh5e2f8b92001-05-28 00:41:15 +0000365 u8 iMatch; /* compare result from last sqliteBtreeMoveto() */
drh365d68f2001-05-11 11:02:46 +0000366};
drh7e3b0a02001-04-28 16:52:40 +0000367
drha059ad02001-04-17 20:09:11 +0000368/*
drh2dcc9aa2002-12-04 13:40:25 +0000369** Legal values for BtCursor.eSkip.
370*/
371#define SKIP_NONE 0 /* Always step the cursor */
372#define SKIP_NEXT 1 /* The next sqliteBtreeNext() is a no-op */
373#define SKIP_PREV 2 /* The next sqliteBtreePrevious() is a no-op */
374#define SKIP_INVALID 3 /* Calls to Next() and Previous() are invalid */
375
376/*
drh0d316a42002-08-11 20:10:47 +0000377** Routines for byte swapping.
378*/
379u16 swab16(u16 x){
380 return ((x & 0xff)<<8) | ((x>>8)&0xff);
381}
382u32 swab32(u32 x){
383 return ((x & 0xff)<<24) | ((x & 0xff00)<<8) |
384 ((x>>8) & 0xff00) | ((x>>24)&0xff);
385}
386
387/*
drh3b7511c2001-05-26 13:15:44 +0000388** Compute the total number of bytes that a Cell needs on the main
drh5e2f8b92001-05-28 00:41:15 +0000389** database page. The number returned includes the Cell header,
390** local payload storage, and the pointer to overflow pages (if
drh8c42ca92001-06-22 19:15:00 +0000391** applicable). Additional space allocated on overflow pages
drhbd03cae2001-06-02 02:40:57 +0000392** is NOT included in the value returned from this routine.
drh3b7511c2001-05-26 13:15:44 +0000393*/
drh0d316a42002-08-11 20:10:47 +0000394static int cellSize(Btree *pBt, Cell *pCell){
395 int n = NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h);
drh3b7511c2001-05-26 13:15:44 +0000396 if( n>MX_LOCAL_PAYLOAD ){
397 n = MX_LOCAL_PAYLOAD + sizeof(Pgno);
398 }else{
399 n = ROUNDUP(n);
400 }
401 n += sizeof(CellHdr);
402 return n;
403}
404
405/*
drh72f82862001-05-24 21:06:34 +0000406** Defragment the page given. All Cells are moved to the
407** beginning of the page and all free space is collected
408** into one big FreeBlk at the end of the page.
drh365d68f2001-05-11 11:02:46 +0000409*/
drh0d316a42002-08-11 20:10:47 +0000410static void defragmentPage(Btree *pBt, MemPage *pPage){
drh14acc042001-06-10 19:56:58 +0000411 int pc, i, n;
drh2af926b2001-05-15 00:39:25 +0000412 FreeBlk *pFBlk;
413 char newPage[SQLITE_PAGE_SIZE];
414
drh6019e162001-07-02 17:51:45 +0000415 assert( sqlitepager_iswriteable(pPage) );
drh7aa128d2002-06-21 13:09:16 +0000416 assert( pPage->isInit );
drhbd03cae2001-06-02 02:40:57 +0000417 pc = sizeof(PageHdr);
drh0d316a42002-08-11 20:10:47 +0000418 pPage->u.hdr.firstCell = SWAB16(pBt, pc);
drh14acc042001-06-10 19:56:58 +0000419 memcpy(newPage, pPage->u.aDisk, pc);
drh2af926b2001-05-15 00:39:25 +0000420 for(i=0; i<pPage->nCell; i++){
drh2aa679f2001-06-25 02:11:07 +0000421 Cell *pCell = pPage->apCell[i];
drh8c42ca92001-06-22 19:15:00 +0000422
423 /* This routine should never be called on an overfull page. The
424 ** following asserts verify that constraint. */
drh7c717f72001-06-24 20:39:41 +0000425 assert( Addr(pCell) > Addr(pPage) );
426 assert( Addr(pCell) < Addr(pPage) + SQLITE_PAGE_SIZE );
drh8c42ca92001-06-22 19:15:00 +0000427
drh0d316a42002-08-11 20:10:47 +0000428 n = cellSize(pBt, pCell);
429 pCell->h.iNext = SWAB16(pBt, pc + n);
drh2af926b2001-05-15 00:39:25 +0000430 memcpy(&newPage[pc], pCell, n);
drh14acc042001-06-10 19:56:58 +0000431 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[pc];
drh2af926b2001-05-15 00:39:25 +0000432 pc += n;
433 }
drh72f82862001-05-24 21:06:34 +0000434 assert( pPage->nFree==SQLITE_PAGE_SIZE-pc );
drh14acc042001-06-10 19:56:58 +0000435 memcpy(pPage->u.aDisk, newPage, pc);
drh2aa679f2001-06-25 02:11:07 +0000436 if( pPage->nCell>0 ){
437 pPage->apCell[pPage->nCell-1]->h.iNext = 0;
438 }
drh8c42ca92001-06-22 19:15:00 +0000439 pFBlk = (FreeBlk*)&pPage->u.aDisk[pc];
drh0d316a42002-08-11 20:10:47 +0000440 pFBlk->iSize = SWAB16(pBt, SQLITE_PAGE_SIZE - pc);
drh2af926b2001-05-15 00:39:25 +0000441 pFBlk->iNext = 0;
drh0d316a42002-08-11 20:10:47 +0000442 pPage->u.hdr.firstFree = SWAB16(pBt, pc);
drh2af926b2001-05-15 00:39:25 +0000443 memset(&pFBlk[1], 0, SQLITE_PAGE_SIZE - pc - sizeof(FreeBlk));
drh365d68f2001-05-11 11:02:46 +0000444}
445
drha059ad02001-04-17 20:09:11 +0000446/*
drh8b2f49b2001-06-08 00:21:52 +0000447** Allocate nByte bytes of space on a page. nByte must be a
448** multiple of 4.
drhbd03cae2001-06-02 02:40:57 +0000449**
drh14acc042001-06-10 19:56:58 +0000450** Return the index into pPage->u.aDisk[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000451** the new allocation. Or return 0 if there is not enough free
452** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000453**
drh72f82862001-05-24 21:06:34 +0000454** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000455** nBytes of contiguous free space, then this routine automatically
456** calls defragementPage() to consolidate all free space before
457** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000458*/
drh0d316a42002-08-11 20:10:47 +0000459static int allocateSpace(Btree *pBt, MemPage *pPage, int nByte){
drh2af926b2001-05-15 00:39:25 +0000460 FreeBlk *p;
461 u16 *pIdx;
462 int start;
drh8c42ca92001-06-22 19:15:00 +0000463 int cnt = 0;
drh0d316a42002-08-11 20:10:47 +0000464 int iSize;
drh72f82862001-05-24 21:06:34 +0000465
drh6019e162001-07-02 17:51:45 +0000466 assert( sqlitepager_iswriteable(pPage) );
drh5e2f8b92001-05-28 00:41:15 +0000467 assert( nByte==ROUNDUP(nByte) );
drh7aa128d2002-06-21 13:09:16 +0000468 assert( pPage->isInit );
drh14acc042001-06-10 19:56:58 +0000469 if( pPage->nFree<nByte || pPage->isOverfull ) return 0;
470 pIdx = &pPage->u.hdr.firstFree;
drh0d316a42002-08-11 20:10:47 +0000471 p = (FreeBlk*)&pPage->u.aDisk[SWAB16(pBt, *pIdx)];
472 while( (iSize = SWAB16(pBt, p->iSize))<nByte ){
drh8c42ca92001-06-22 19:15:00 +0000473 assert( cnt++ < SQLITE_PAGE_SIZE/4 );
drh2af926b2001-05-15 00:39:25 +0000474 if( p->iNext==0 ){
drh0d316a42002-08-11 20:10:47 +0000475 defragmentPage(pBt, pPage);
drh14acc042001-06-10 19:56:58 +0000476 pIdx = &pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000477 }else{
478 pIdx = &p->iNext;
479 }
drh0d316a42002-08-11 20:10:47 +0000480 p = (FreeBlk*)&pPage->u.aDisk[SWAB16(pBt, *pIdx)];
drh2af926b2001-05-15 00:39:25 +0000481 }
drh0d316a42002-08-11 20:10:47 +0000482 if( iSize==nByte ){
483 start = SWAB16(pBt, *pIdx);
drh2af926b2001-05-15 00:39:25 +0000484 *pIdx = p->iNext;
485 }else{
drh8c42ca92001-06-22 19:15:00 +0000486 FreeBlk *pNew;
drh0d316a42002-08-11 20:10:47 +0000487 start = SWAB16(pBt, *pIdx);
drh8c42ca92001-06-22 19:15:00 +0000488 pNew = (FreeBlk*)&pPage->u.aDisk[start + nByte];
drh72f82862001-05-24 21:06:34 +0000489 pNew->iNext = p->iNext;
drh0d316a42002-08-11 20:10:47 +0000490 pNew->iSize = SWAB16(pBt, iSize - nByte);
491 *pIdx = SWAB16(pBt, start + nByte);
drh2af926b2001-05-15 00:39:25 +0000492 }
493 pPage->nFree -= nByte;
494 return start;
drh7e3b0a02001-04-28 16:52:40 +0000495}
496
497/*
drh14acc042001-06-10 19:56:58 +0000498** Return a section of the MemPage.u.aDisk[] to the freelist.
499** The first byte of the new free block is pPage->u.aDisk[start]
500** and the size of the block is "size" bytes. Size must be
501** a multiple of 4.
drh306dc212001-05-21 13:45:10 +0000502**
503** Most of the effort here is involved in coalesing adjacent
504** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000505*/
drh0d316a42002-08-11 20:10:47 +0000506static void freeSpace(Btree *pBt, MemPage *pPage, int start, int size){
drh2af926b2001-05-15 00:39:25 +0000507 int end = start + size;
508 u16 *pIdx, idx;
509 FreeBlk *pFBlk;
510 FreeBlk *pNew;
511 FreeBlk *pNext;
drh0d316a42002-08-11 20:10:47 +0000512 int iSize;
drh2af926b2001-05-15 00:39:25 +0000513
drh6019e162001-07-02 17:51:45 +0000514 assert( sqlitepager_iswriteable(pPage) );
drh2af926b2001-05-15 00:39:25 +0000515 assert( size == ROUNDUP(size) );
516 assert( start == ROUNDUP(start) );
drh7aa128d2002-06-21 13:09:16 +0000517 assert( pPage->isInit );
drh14acc042001-06-10 19:56:58 +0000518 pIdx = &pPage->u.hdr.firstFree;
drh0d316a42002-08-11 20:10:47 +0000519 idx = SWAB16(pBt, *pIdx);
drh2af926b2001-05-15 00:39:25 +0000520 while( idx!=0 && idx<start ){
drh14acc042001-06-10 19:56:58 +0000521 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +0000522 iSize = SWAB16(pBt, pFBlk->iSize);
523 if( idx + iSize == start ){
524 pFBlk->iSize = SWAB16(pBt, iSize + size);
525 if( idx + iSize + size == SWAB16(pBt, pFBlk->iNext) ){
526 pNext = (FreeBlk*)&pPage->u.aDisk[idx + iSize + size];
527 if( pBt->needSwab ){
528 pFBlk->iSize = swab16(swab16(pNext->iSize)+iSize+size);
529 }else{
530 pFBlk->iSize += pNext->iSize;
531 }
drh2af926b2001-05-15 00:39:25 +0000532 pFBlk->iNext = pNext->iNext;
533 }
534 pPage->nFree += size;
535 return;
536 }
537 pIdx = &pFBlk->iNext;
drh0d316a42002-08-11 20:10:47 +0000538 idx = SWAB16(pBt, *pIdx);
drh2af926b2001-05-15 00:39:25 +0000539 }
drh14acc042001-06-10 19:56:58 +0000540 pNew = (FreeBlk*)&pPage->u.aDisk[start];
drh2af926b2001-05-15 00:39:25 +0000541 if( idx != end ){
drh0d316a42002-08-11 20:10:47 +0000542 pNew->iSize = SWAB16(pBt, size);
543 pNew->iNext = SWAB16(pBt, idx);
drh2af926b2001-05-15 00:39:25 +0000544 }else{
drh14acc042001-06-10 19:56:58 +0000545 pNext = (FreeBlk*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +0000546 pNew->iSize = SWAB16(pBt, size + SWAB16(pBt, pNext->iSize));
drh2af926b2001-05-15 00:39:25 +0000547 pNew->iNext = pNext->iNext;
548 }
drh0d316a42002-08-11 20:10:47 +0000549 *pIdx = SWAB16(pBt, start);
drh2af926b2001-05-15 00:39:25 +0000550 pPage->nFree += size;
drh7e3b0a02001-04-28 16:52:40 +0000551}
552
553/*
554** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000555**
drhbd03cae2001-06-02 02:40:57 +0000556** The pParent parameter must be a pointer to the MemPage which
557** is the parent of the page being initialized. The root of the
drh8b2f49b2001-06-08 00:21:52 +0000558** BTree (usually page 2) has no parent and so for that page,
559** pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000560**
drh72f82862001-05-24 21:06:34 +0000561** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +0000562** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +0000563** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
564** guarantee that the page is well-formed. It only shows that
565** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000566*/
drh0d316a42002-08-11 20:10:47 +0000567static int initPage(Bt *pBt, MemPage *pPage, Pgno pgnoThis, MemPage *pParent){
drh14acc042001-06-10 19:56:58 +0000568 int idx; /* An index into pPage->u.aDisk[] */
569 Cell *pCell; /* A pointer to a Cell in pPage->u.aDisk[] */
570 FreeBlk *pFBlk; /* A pointer to a free block in pPage->u.aDisk[] */
drh5e2f8b92001-05-28 00:41:15 +0000571 int sz; /* The size of a Cell in bytes */
572 int freeSpace; /* Amount of free space on the page */
drh2af926b2001-05-15 00:39:25 +0000573
drh5e2f8b92001-05-28 00:41:15 +0000574 if( pPage->pParent ){
575 assert( pPage->pParent==pParent );
576 return SQLITE_OK;
577 }
578 if( pParent ){
579 pPage->pParent = pParent;
580 sqlitepager_ref(pParent);
581 }
582 if( pPage->isInit ) return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +0000583 pPage->isInit = 1;
drh7e3b0a02001-04-28 16:52:40 +0000584 pPage->nCell = 0;
drh6019e162001-07-02 17:51:45 +0000585 freeSpace = USABLE_SPACE;
drh0d316a42002-08-11 20:10:47 +0000586 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh7e3b0a02001-04-28 16:52:40 +0000587 while( idx!=0 ){
drh8c42ca92001-06-22 19:15:00 +0000588 if( idx>SQLITE_PAGE_SIZE-MIN_CELL_SIZE ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000589 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh8c42ca92001-06-22 19:15:00 +0000590 if( idx!=ROUNDUP(idx) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000591 pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +0000592 sz = cellSize(pBt, pCell);
drh5e2f8b92001-05-28 00:41:15 +0000593 if( idx+sz > SQLITE_PAGE_SIZE ) goto page_format_error;
594 freeSpace -= sz;
595 pPage->apCell[pPage->nCell++] = pCell;
drh0d316a42002-08-11 20:10:47 +0000596 idx = SWAB16(pBt, pCell->h.iNext);
drh2af926b2001-05-15 00:39:25 +0000597 }
598 pPage->nFree = 0;
drh0d316a42002-08-11 20:10:47 +0000599 idx = SWAB16(pBt, pPage->u.hdr.firstFree);
drh2af926b2001-05-15 00:39:25 +0000600 while( idx!=0 ){
drh0d316a42002-08-11 20:10:47 +0000601 int iNext;
drh2af926b2001-05-15 00:39:25 +0000602 if( idx>SQLITE_PAGE_SIZE-sizeof(FreeBlk) ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000603 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000604 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +0000605 pPage->nFree += SWAB16(pBt, pFBlk->iSize);
606 iNext = SWAB16(pBt, pFBlk->iNext);
607 if( iNext>0 && iNext <= idx ) goto page_format_error;
608 idx = iNext;
drh7e3b0a02001-04-28 16:52:40 +0000609 }
drh8b2f49b2001-06-08 00:21:52 +0000610 if( pPage->nCell==0 && pPage->nFree==0 ){
611 /* As a special case, an uninitialized root page appears to be
612 ** an empty database */
613 return SQLITE_OK;
614 }
drh5e2f8b92001-05-28 00:41:15 +0000615 if( pPage->nFree!=freeSpace ) goto page_format_error;
drh7e3b0a02001-04-28 16:52:40 +0000616 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +0000617
618page_format_error:
619 return SQLITE_CORRUPT;
drh7e3b0a02001-04-28 16:52:40 +0000620}
621
622/*
drh8b2f49b2001-06-08 00:21:52 +0000623** Set up a raw page so that it looks like a database page holding
624** no entries.
drhbd03cae2001-06-02 02:40:57 +0000625*/
drh0d316a42002-08-11 20:10:47 +0000626static void zeroPage(Btree *pBt, MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +0000627 PageHdr *pHdr;
628 FreeBlk *pFBlk;
drh6019e162001-07-02 17:51:45 +0000629 assert( sqlitepager_iswriteable(pPage) );
drhbd03cae2001-06-02 02:40:57 +0000630 memset(pPage, 0, SQLITE_PAGE_SIZE);
drh14acc042001-06-10 19:56:58 +0000631 pHdr = &pPage->u.hdr;
drhbd03cae2001-06-02 02:40:57 +0000632 pHdr->firstCell = 0;
drh0d316a42002-08-11 20:10:47 +0000633 pHdr->firstFree = SWAB16(pBt, sizeof(*pHdr));
drhbd03cae2001-06-02 02:40:57 +0000634 pFBlk = (FreeBlk*)&pHdr[1];
635 pFBlk->iNext = 0;
drh0d316a42002-08-11 20:10:47 +0000636 pPage->nFree = SQLITE_PAGE_SIZE - sizeof(*pHdr);
637 pFBlk->iSize = SWAB16(pBt, pPage->nFree);
drh8c42ca92001-06-22 19:15:00 +0000638 pPage->nCell = 0;
639 pPage->isOverfull = 0;
drhbd03cae2001-06-02 02:40:57 +0000640}
641
642/*
drh72f82862001-05-24 21:06:34 +0000643** This routine is called when the reference count for a page
644** reaches zero. We need to unref the pParent pointer when that
645** happens.
646*/
647static void pageDestructor(void *pData){
648 MemPage *pPage = (MemPage*)pData;
649 if( pPage->pParent ){
650 MemPage *pParent = pPage->pParent;
651 pPage->pParent = 0;
652 sqlitepager_unref(pParent);
653 }
654}
655
656/*
drh306dc212001-05-21 13:45:10 +0000657** Open a new database.
658**
659** Actually, this routine just sets up the internal data structures
drh72f82862001-05-24 21:06:34 +0000660** for accessing the database. We do not open the database file
661** until the first page is loaded.
drh382c0242001-10-06 16:33:02 +0000662**
663** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +0000664** a new database with a random name is created. This randomly named
665** database file will be deleted when sqliteBtreeClose() is called.
drha059ad02001-04-17 20:09:11 +0000666*/
drh6019e162001-07-02 17:51:45 +0000667int sqliteBtreeOpen(
668 const char *zFilename, /* Name of the file containing the BTree database */
drhda47d772002-12-02 04:25:19 +0000669 int omitJournal, /* if TRUE then do not journal this file */
drh6019e162001-07-02 17:51:45 +0000670 int nCache, /* How many pages in the page cache */
671 Btree **ppBtree /* Pointer to new Btree object written here */
672){
drha059ad02001-04-17 20:09:11 +0000673 Btree *pBt;
drh8c42ca92001-06-22 19:15:00 +0000674 int rc;
drha059ad02001-04-17 20:09:11 +0000675
676 pBt = sqliteMalloc( sizeof(*pBt) );
677 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +0000678 *ppBtree = 0;
drha059ad02001-04-17 20:09:11 +0000679 return SQLITE_NOMEM;
680 }
drh6019e162001-07-02 17:51:45 +0000681 if( nCache<10 ) nCache = 10;
drhda47d772002-12-02 04:25:19 +0000682 rc = sqlitepager_open(&pBt->pPager, zFilename, nCache, EXTRA_SIZE,
683 !omitJournal);
drha059ad02001-04-17 20:09:11 +0000684 if( rc!=SQLITE_OK ){
685 if( pBt->pPager ) sqlitepager_close(pBt->pPager);
686 sqliteFree(pBt);
687 *ppBtree = 0;
688 return rc;
689 }
drh72f82862001-05-24 21:06:34 +0000690 sqlitepager_set_destructor(pBt->pPager, pageDestructor);
drha059ad02001-04-17 20:09:11 +0000691 pBt->pCursor = 0;
692 pBt->page1 = 0;
drh5df72a52002-06-06 23:16:05 +0000693 pBt->readOnly = sqlitepager_isreadonly(pBt->pPager);
drha059ad02001-04-17 20:09:11 +0000694 *ppBtree = pBt;
695 return SQLITE_OK;
696}
697
698/*
699** Close an open database and invalidate all cursors.
700*/
701int sqliteBtreeClose(Btree *pBt){
702 while( pBt->pCursor ){
703 sqliteBtreeCloseCursor(pBt->pCursor);
704 }
705 sqlitepager_close(pBt->pPager);
706 sqliteFree(pBt);
707 return SQLITE_OK;
708}
709
710/*
drhda47d772002-12-02 04:25:19 +0000711** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +0000712**
713** The maximum number of cache pages is set to the absolute
714** value of mxPage. If mxPage is negative, the pager will
715** operate asynchronously - it will not stop to do fsync()s
716** to insure data is written to the disk surface before
717** continuing. Transactions still work if synchronous is off,
718** and the database cannot be corrupted if this program
719** crashes. But if the operating system crashes or there is
720** an abrupt power failure when synchronous is off, the database
721** could be left in an inconsistent and unrecoverable state.
722** Synchronous is on by default so database corruption is not
723** normally a worry.
drhf57b14a2001-09-14 18:54:08 +0000724*/
725int sqliteBtreeSetCacheSize(Btree *pBt, int mxPage){
726 sqlitepager_set_cachesize(pBt->pPager, mxPage);
727 return SQLITE_OK;
728}
729
730/*
drh306dc212001-05-21 13:45:10 +0000731** Get a reference to page1 of the database file. This will
732** also acquire a readlock on that file.
733**
734** SQLITE_OK is returned on success. If the file is not a
735** well-formed database file, then SQLITE_CORRUPT is returned.
736** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
737** is returned if we run out of memory. SQLITE_PROTOCOL is returned
738** if there is a locking protocol violation.
739*/
740static int lockBtree(Btree *pBt){
741 int rc;
742 if( pBt->page1 ) return SQLITE_OK;
drh8c42ca92001-06-22 19:15:00 +0000743 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pBt->page1);
drh306dc212001-05-21 13:45:10 +0000744 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +0000745
746 /* Do some checking to help insure the file we opened really is
747 ** a valid database file.
748 */
749 if( sqlitepager_pagecount(pBt->pPager)>0 ){
drhbd03cae2001-06-02 02:40:57 +0000750 PageOne *pP1 = pBt->page1;
drh0d316a42002-08-11 20:10:47 +0000751 if( strcmp(pP1->zMagic,zMagicHeader)!=0 ||
752 (pP1->iMagic!=MAGIC && swab32(pP1->iMagic)!=MAGIC) ){
drh306dc212001-05-21 13:45:10 +0000753 rc = SQLITE_CORRUPT;
drh72f82862001-05-24 21:06:34 +0000754 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +0000755 }
drh0d316a42002-08-11 20:10:47 +0000756 pBt->needSwab = pP1->iMagic!=MAGIC;
drh306dc212001-05-21 13:45:10 +0000757 }
758 return rc;
759
drh72f82862001-05-24 21:06:34 +0000760page1_init_failed:
drh306dc212001-05-21 13:45:10 +0000761 sqlitepager_unref(pBt->page1);
762 pBt->page1 = 0;
drh72f82862001-05-24 21:06:34 +0000763 return rc;
drh306dc212001-05-21 13:45:10 +0000764}
765
766/*
drhb8ca3072001-12-05 00:21:20 +0000767** If there are no outstanding cursors and we are not in the middle
768** of a transaction but there is a read lock on the database, then
769** this routine unrefs the first page of the database file which
770** has the effect of releasing the read lock.
771**
772** If there are any outstanding cursors, this routine is a no-op.
773**
774** If there is a transaction in progress, this routine is a no-op.
775*/
776static void unlockBtreeIfUnused(Btree *pBt){
777 if( pBt->inTrans==0 && pBt->pCursor==0 && pBt->page1!=0 ){
778 sqlitepager_unref(pBt->page1);
779 pBt->page1 = 0;
780 pBt->inTrans = 0;
drh663fc632002-02-02 18:49:19 +0000781 pBt->inCkpt = 0;
drhb8ca3072001-12-05 00:21:20 +0000782 }
783}
784
785/*
drh8c42ca92001-06-22 19:15:00 +0000786** Create a new database by initializing the first two pages of the
787** file.
drh8b2f49b2001-06-08 00:21:52 +0000788*/
789static int newDatabase(Btree *pBt){
790 MemPage *pRoot;
791 PageOne *pP1;
drh8c42ca92001-06-22 19:15:00 +0000792 int rc;
drh7c717f72001-06-24 20:39:41 +0000793 if( sqlitepager_pagecount(pBt->pPager)>1 ) return SQLITE_OK;
drh8b2f49b2001-06-08 00:21:52 +0000794 pP1 = pBt->page1;
795 rc = sqlitepager_write(pBt->page1);
796 if( rc ) return rc;
drh8c42ca92001-06-22 19:15:00 +0000797 rc = sqlitepager_get(pBt->pPager, 2, (void**)&pRoot);
drh8b2f49b2001-06-08 00:21:52 +0000798 if( rc ) return rc;
799 rc = sqlitepager_write(pRoot);
800 if( rc ){
801 sqlitepager_unref(pRoot);
802 return rc;
803 }
804 strcpy(pP1->zMagic, zMagicHeader);
drh0d316a42002-08-11 20:10:47 +0000805 if( btree_native_byte_order ){
806 pP1->iMagic = MAGIC;
807 pBt->needSwab = 0;
808 }else{
809 pP1->iMagic = swab32(MAGIC);
810 pBt->needSwab = 1;
811 }
drh0d316a42002-08-11 20:10:47 +0000812 zeroPage(pBt, pRoot);
drh8b2f49b2001-06-08 00:21:52 +0000813 sqlitepager_unref(pRoot);
814 return SQLITE_OK;
815}
816
817/*
drh72f82862001-05-24 21:06:34 +0000818** Attempt to start a new transaction.
drh8b2f49b2001-06-08 00:21:52 +0000819**
820** A transaction must be started before attempting any changes
821** to the database. None of the following routines will work
822** unless a transaction is started first:
823**
824** sqliteBtreeCreateTable()
drhc6b52df2002-01-04 03:09:29 +0000825** sqliteBtreeCreateIndex()
drh8b2f49b2001-06-08 00:21:52 +0000826** sqliteBtreeClearTable()
827** sqliteBtreeDropTable()
828** sqliteBtreeInsert()
829** sqliteBtreeDelete()
830** sqliteBtreeUpdateMeta()
drha059ad02001-04-17 20:09:11 +0000831*/
832int sqliteBtreeBeginTrans(Btree *pBt){
833 int rc;
834 if( pBt->inTrans ) return SQLITE_ERROR;
drhf74b8d92002-09-01 23:20:45 +0000835 if( pBt->readOnly ) return SQLITE_READONLY;
drha059ad02001-04-17 20:09:11 +0000836 if( pBt->page1==0 ){
drh7e3b0a02001-04-28 16:52:40 +0000837 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +0000838 if( rc!=SQLITE_OK ){
839 return rc;
840 }
drha059ad02001-04-17 20:09:11 +0000841 }
drhf74b8d92002-09-01 23:20:45 +0000842 rc = sqlitepager_begin(pBt->page1);
843 if( rc==SQLITE_OK ){
844 rc = newDatabase(pBt);
drha059ad02001-04-17 20:09:11 +0000845 }
drhb8ca3072001-12-05 00:21:20 +0000846 if( rc==SQLITE_OK ){
847 pBt->inTrans = 1;
drh663fc632002-02-02 18:49:19 +0000848 pBt->inCkpt = 0;
drhb8ca3072001-12-05 00:21:20 +0000849 }else{
850 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000851 }
drhb8ca3072001-12-05 00:21:20 +0000852 return rc;
drha059ad02001-04-17 20:09:11 +0000853}
854
855/*
drh2aa679f2001-06-25 02:11:07 +0000856** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +0000857**
858** This will release the write lock on the database file. If there
859** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000860*/
861int sqliteBtreeCommit(Btree *pBt){
862 int rc;
drh5df72a52002-06-06 23:16:05 +0000863 rc = pBt->readOnly ? SQLITE_OK : sqlitepager_commit(pBt->pPager);
drh7c717f72001-06-24 20:39:41 +0000864 pBt->inTrans = 0;
drh663fc632002-02-02 18:49:19 +0000865 pBt->inCkpt = 0;
drh5e00f6c2001-09-13 13:46:56 +0000866 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000867 return rc;
868}
869
870/*
drhecdc7532001-09-23 02:35:53 +0000871** Rollback the transaction in progress. All cursors will be
872** invalided by this operation. Any attempt to use a cursor
873** that was open at the beginning of this operation will result
874** in an error.
drh5e00f6c2001-09-13 13:46:56 +0000875**
876** This will release the write lock on the database file. If there
877** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000878*/
879int sqliteBtreeRollback(Btree *pBt){
880 int rc;
drhecdc7532001-09-23 02:35:53 +0000881 BtCursor *pCur;
drh7c717f72001-06-24 20:39:41 +0000882 if( pBt->inTrans==0 ) return SQLITE_OK;
883 pBt->inTrans = 0;
drh663fc632002-02-02 18:49:19 +0000884 pBt->inCkpt = 0;
drhecdc7532001-09-23 02:35:53 +0000885 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
886 if( pCur->pPage ){
887 sqlitepager_unref(pCur->pPage);
888 pCur->pPage = 0;
889 }
890 }
drh5df72a52002-06-06 23:16:05 +0000891 rc = pBt->readOnly ? SQLITE_OK : sqlitepager_rollback(pBt->pPager);
drh5e00f6c2001-09-13 13:46:56 +0000892 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000893 return rc;
894}
895
896/*
drh663fc632002-02-02 18:49:19 +0000897** Set the checkpoint for the current transaction. The checkpoint serves
898** as a sub-transaction that can be rolled back independently of the
899** main transaction. You must start a transaction before starting a
900** checkpoint. The checkpoint is ended automatically if the transaction
901** commits or rolls back.
902**
903** Only one checkpoint may be active at a time. It is an error to try
904** to start a new checkpoint if another checkpoint is already active.
905*/
906int sqliteBtreeBeginCkpt(Btree *pBt){
907 int rc;
drh0d65dc02002-02-03 00:56:09 +0000908 if( !pBt->inTrans || pBt->inCkpt ){
drhf74b8d92002-09-01 23:20:45 +0000909 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh0d65dc02002-02-03 00:56:09 +0000910 }
drh5df72a52002-06-06 23:16:05 +0000911 rc = pBt->readOnly ? SQLITE_OK : sqlitepager_ckpt_begin(pBt->pPager);
drh663fc632002-02-02 18:49:19 +0000912 pBt->inCkpt = 1;
913 return rc;
914}
915
916
917/*
918** Commit a checkpoint to transaction currently in progress. If no
919** checkpoint is active, this is a no-op.
920*/
921int sqliteBtreeCommitCkpt(Btree *pBt){
922 int rc;
drh5df72a52002-06-06 23:16:05 +0000923 if( pBt->inCkpt && !pBt->readOnly ){
drh663fc632002-02-02 18:49:19 +0000924 rc = sqlitepager_ckpt_commit(pBt->pPager);
925 }else{
926 rc = SQLITE_OK;
927 }
drh0d65dc02002-02-03 00:56:09 +0000928 pBt->inCkpt = 0;
drh663fc632002-02-02 18:49:19 +0000929 return rc;
930}
931
932/*
933** Rollback the checkpoint to the current transaction. If there
934** is no active checkpoint or transaction, this routine is a no-op.
935**
936** All cursors will be invalided by this operation. Any attempt
937** to use a cursor that was open at the beginning of this operation
938** will result in an error.
939*/
940int sqliteBtreeRollbackCkpt(Btree *pBt){
941 int rc;
942 BtCursor *pCur;
drh5df72a52002-06-06 23:16:05 +0000943 if( pBt->inCkpt==0 || pBt->readOnly ) return SQLITE_OK;
drh663fc632002-02-02 18:49:19 +0000944 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
945 if( pCur->pPage ){
946 sqlitepager_unref(pCur->pPage);
947 pCur->pPage = 0;
948 }
949 }
950 rc = sqlitepager_ckpt_rollback(pBt->pPager);
drh0d65dc02002-02-03 00:56:09 +0000951 pBt->inCkpt = 0;
drh663fc632002-02-02 18:49:19 +0000952 return rc;
953}
954
955/*
drh8b2f49b2001-06-08 00:21:52 +0000956** Create a new cursor for the BTree whose root is on the page
957** iTable. The act of acquiring a cursor gets a read lock on
958** the database file.
drh1bee3d72001-10-15 00:44:35 +0000959**
960** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +0000961** If wrFlag==1, then the cursor can be used for reading or for
962** writing if other conditions for writing are also met. These
963** are the conditions that must be met in order for writing to
964** be allowed:
drh6446c4d2001-12-15 14:22:18 +0000965**
drhf74b8d92002-09-01 23:20:45 +0000966** 1: The cursor must have been opened with wrFlag==1
967**
968** 2: No other cursors may be open with wrFlag==0 on the same table
969**
970** 3: The database must be writable (not on read-only media)
971**
972** 4: There must be an active transaction.
973**
974** Condition 2 warrants further discussion. If any cursor is opened
975** on a table with wrFlag==0, that prevents all other cursors from
976** writing to that table. This is a kind of "read-lock". When a cursor
977** is opened with wrFlag==0 it is guaranteed that the table will not
978** change as long as the cursor is open. This allows the cursor to
979** do a sequential scan of the table without having to worry about
980** entries being inserted or deleted during the scan. Cursors should
981** be opened with wrFlag==0 only if this read-lock property is needed.
982** That is to say, cursors should be opened with wrFlag==0 only if they
983** intend to use the sqliteBtreeNext() system call. All other cursors
984** should be opened with wrFlag==1 even if they never really intend
985** to write.
986**
drh6446c4d2001-12-15 14:22:18 +0000987** No checking is done to make sure that page iTable really is the
988** root page of a b-tree. If it is not, then the cursor acquired
989** will not work correctly.
drha059ad02001-04-17 20:09:11 +0000990*/
drhecdc7532001-09-23 02:35:53 +0000991int sqliteBtreeCursor(Btree *pBt, int iTable, int wrFlag, BtCursor **ppCur){
drha059ad02001-04-17 20:09:11 +0000992 int rc;
drhf74b8d92002-09-01 23:20:45 +0000993 BtCursor *pCur, *pRing;
drhecdc7532001-09-23 02:35:53 +0000994
drha059ad02001-04-17 20:09:11 +0000995 if( pBt->page1==0 ){
996 rc = lockBtree(pBt);
997 if( rc!=SQLITE_OK ){
998 *ppCur = 0;
999 return rc;
1000 }
1001 }
1002 pCur = sqliteMalloc( sizeof(*pCur) );
1003 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +00001004 rc = SQLITE_NOMEM;
1005 goto create_cursor_exception;
1006 }
drh8b2f49b2001-06-08 00:21:52 +00001007 pCur->pgnoRoot = (Pgno)iTable;
drh8c42ca92001-06-22 19:15:00 +00001008 rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +00001009 if( rc!=SQLITE_OK ){
1010 goto create_cursor_exception;
1011 }
drh0d316a42002-08-11 20:10:47 +00001012 rc = initPage(pBt, pCur->pPage, pCur->pgnoRoot, 0);
drhbd03cae2001-06-02 02:40:57 +00001013 if( rc!=SQLITE_OK ){
1014 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00001015 }
drh14acc042001-06-10 19:56:58 +00001016 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +00001017 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +00001018 pCur->idx = 0;
drh2dcc9aa2002-12-04 13:40:25 +00001019 pCur->eSkip = SKIP_INVALID;
drha059ad02001-04-17 20:09:11 +00001020 pCur->pNext = pBt->pCursor;
1021 if( pCur->pNext ){
1022 pCur->pNext->pPrev = pCur;
1023 }
drh14acc042001-06-10 19:56:58 +00001024 pCur->pPrev = 0;
drhf74b8d92002-09-01 23:20:45 +00001025 pRing = pBt->pCursor;
1026 while( pRing && pRing->pgnoRoot!=pCur->pgnoRoot ){ pRing = pRing->pNext; }
1027 if( pRing ){
1028 pCur->pShared = pRing->pShared;
1029 pRing->pShared = pCur;
1030 }else{
1031 pCur->pShared = pCur;
1032 }
drha059ad02001-04-17 20:09:11 +00001033 pBt->pCursor = pCur;
drh2af926b2001-05-15 00:39:25 +00001034 *ppCur = pCur;
1035 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00001036
1037create_cursor_exception:
1038 *ppCur = 0;
1039 if( pCur ){
1040 if( pCur->pPage ) sqlitepager_unref(pCur->pPage);
1041 sqliteFree(pCur);
1042 }
drh5e00f6c2001-09-13 13:46:56 +00001043 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00001044 return rc;
drha059ad02001-04-17 20:09:11 +00001045}
1046
1047/*
drh5e00f6c2001-09-13 13:46:56 +00001048** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00001049** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00001050*/
1051int sqliteBtreeCloseCursor(BtCursor *pCur){
1052 Btree *pBt = pCur->pBt;
drha059ad02001-04-17 20:09:11 +00001053 if( pCur->pPrev ){
1054 pCur->pPrev->pNext = pCur->pNext;
1055 }else{
1056 pBt->pCursor = pCur->pNext;
1057 }
1058 if( pCur->pNext ){
1059 pCur->pNext->pPrev = pCur->pPrev;
1060 }
drhecdc7532001-09-23 02:35:53 +00001061 if( pCur->pPage ){
1062 sqlitepager_unref(pCur->pPage);
1063 }
drhf74b8d92002-09-01 23:20:45 +00001064 if( pCur->pShared!=pCur ){
1065 BtCursor *pRing = pCur->pShared;
1066 while( pRing->pShared!=pCur ){ pRing = pRing->pShared; }
1067 pRing->pShared = pCur->pShared;
1068 }
drh5e00f6c2001-09-13 13:46:56 +00001069 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +00001070 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +00001071 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00001072}
1073
drh7e3b0a02001-04-28 16:52:40 +00001074/*
drh5e2f8b92001-05-28 00:41:15 +00001075** Make a temporary cursor by filling in the fields of pTempCur.
1076** The temporary cursor is not on the cursor list for the Btree.
1077*/
drh14acc042001-06-10 19:56:58 +00001078static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00001079 memcpy(pTempCur, pCur, sizeof(*pCur));
1080 pTempCur->pNext = 0;
1081 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00001082 if( pTempCur->pPage ){
1083 sqlitepager_ref(pTempCur->pPage);
1084 }
drh5e2f8b92001-05-28 00:41:15 +00001085}
1086
1087/*
drhbd03cae2001-06-02 02:40:57 +00001088** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00001089** function above.
1090*/
drh14acc042001-06-10 19:56:58 +00001091static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00001092 if( pCur->pPage ){
1093 sqlitepager_unref(pCur->pPage);
1094 }
drh5e2f8b92001-05-28 00:41:15 +00001095}
1096
1097/*
drhbd03cae2001-06-02 02:40:57 +00001098** Set *pSize to the number of bytes of key in the entry the
1099** cursor currently points to. Always return SQLITE_OK.
1100** Failure is not possible. If the cursor is not currently
1101** pointing to an entry (which can happen, for example, if
1102** the database is empty) then *pSize is set to 0.
drh7e3b0a02001-04-28 16:52:40 +00001103*/
drh72f82862001-05-24 21:06:34 +00001104int sqliteBtreeKeySize(BtCursor *pCur, int *pSize){
drh2af926b2001-05-15 00:39:25 +00001105 Cell *pCell;
1106 MemPage *pPage;
1107
1108 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001109 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh72f82862001-05-24 21:06:34 +00001110 *pSize = 0;
1111 }else{
drh5e2f8b92001-05-28 00:41:15 +00001112 pCell = pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00001113 *pSize = NKEY(pCur->pBt, pCell->h);
drh72f82862001-05-24 21:06:34 +00001114 }
1115 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00001116}
drh2af926b2001-05-15 00:39:25 +00001117
drh72f82862001-05-24 21:06:34 +00001118/*
1119** Read payload information from the entry that the pCur cursor is
1120** pointing to. Begin reading the payload at "offset" and read
1121** a total of "amt" bytes. Put the result in zBuf.
1122**
1123** This routine does not make a distinction between key and data.
1124** It just reads bytes from the payload area.
1125*/
drh2af926b2001-05-15 00:39:25 +00001126static int getPayload(BtCursor *pCur, int offset, int amt, char *zBuf){
drh5e2f8b92001-05-28 00:41:15 +00001127 char *aPayload;
drh2af926b2001-05-15 00:39:25 +00001128 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +00001129 int rc;
drh0d316a42002-08-11 20:10:47 +00001130 Btree *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00001131 assert( pCur!=0 && pCur->pPage!=0 );
drh8c42ca92001-06-22 19:15:00 +00001132 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
1133 aPayload = pCur->pPage->apCell[pCur->idx]->aPayload;
drh2af926b2001-05-15 00:39:25 +00001134 if( offset<MX_LOCAL_PAYLOAD ){
1135 int a = amt;
1136 if( a+offset>MX_LOCAL_PAYLOAD ){
1137 a = MX_LOCAL_PAYLOAD - offset;
1138 }
drh5e2f8b92001-05-28 00:41:15 +00001139 memcpy(zBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +00001140 if( a==amt ){
1141 return SQLITE_OK;
1142 }
drh2aa679f2001-06-25 02:11:07 +00001143 offset = 0;
drh2af926b2001-05-15 00:39:25 +00001144 zBuf += a;
1145 amt -= a;
drhdd793422001-06-28 01:54:48 +00001146 }else{
1147 offset -= MX_LOCAL_PAYLOAD;
drhbd03cae2001-06-02 02:40:57 +00001148 }
1149 if( amt>0 ){
drh0d316a42002-08-11 20:10:47 +00001150 nextPage = SWAB32(pBt, pCur->pPage->apCell[pCur->idx]->ovfl);
drh2af926b2001-05-15 00:39:25 +00001151 }
1152 while( amt>0 && nextPage ){
1153 OverflowPage *pOvfl;
drh0d316a42002-08-11 20:10:47 +00001154 rc = sqlitepager_get(pBt->pPager, nextPage, (void**)&pOvfl);
drh2af926b2001-05-15 00:39:25 +00001155 if( rc!=0 ){
1156 return rc;
1157 }
drh0d316a42002-08-11 20:10:47 +00001158 nextPage = SWAB32(pBt, pOvfl->iNext);
drh2af926b2001-05-15 00:39:25 +00001159 if( offset<OVERFLOW_SIZE ){
1160 int a = amt;
1161 if( a + offset > OVERFLOW_SIZE ){
1162 a = OVERFLOW_SIZE - offset;
1163 }
drh5e2f8b92001-05-28 00:41:15 +00001164 memcpy(zBuf, &pOvfl->aPayload[offset], a);
drh2aa679f2001-06-25 02:11:07 +00001165 offset = 0;
drh2af926b2001-05-15 00:39:25 +00001166 amt -= a;
1167 zBuf += a;
drh2aa679f2001-06-25 02:11:07 +00001168 }else{
1169 offset -= OVERFLOW_SIZE;
drh2af926b2001-05-15 00:39:25 +00001170 }
1171 sqlitepager_unref(pOvfl);
1172 }
drha7fcb052001-12-14 15:09:55 +00001173 if( amt>0 ){
1174 return SQLITE_CORRUPT;
1175 }
1176 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00001177}
1178
drh72f82862001-05-24 21:06:34 +00001179/*
drh5e00f6c2001-09-13 13:46:56 +00001180** Read part of the key associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +00001181** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +00001182** begins at "offset". The number of bytes actually read is
1183** returned. The amount returned will be smaller than the
1184** amount requested if there are not enough bytes in the key
1185** to satisfy the request.
drh72f82862001-05-24 21:06:34 +00001186*/
1187int sqliteBtreeKey(BtCursor *pCur, int offset, int amt, char *zBuf){
1188 Cell *pCell;
1189 MemPage *pPage;
drha059ad02001-04-17 20:09:11 +00001190
drh5e00f6c2001-09-13 13:46:56 +00001191 if( amt<0 ) return 0;
1192 if( offset<0 ) return 0;
1193 if( amt==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001194 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001195 if( pPage==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001196 if( pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +00001197 return 0;
drh72f82862001-05-24 21:06:34 +00001198 }
drh5e2f8b92001-05-28 00:41:15 +00001199 pCell = pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00001200 if( amt+offset > NKEY(pCur->pBt, pCell->h) ){
1201 amt = NKEY(pCur->pBt, pCell->h) - offset;
drh5e00f6c2001-09-13 13:46:56 +00001202 if( amt<=0 ){
1203 return 0;
1204 }
drhbd03cae2001-06-02 02:40:57 +00001205 }
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;
drhecdc7532001-09-23 02:35:53 +00001222 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh72f82862001-05-24 21:06:34 +00001223 *pSize = 0;
1224 }else{
drh5e2f8b92001-05-28 00:41:15 +00001225 pCell = pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00001226 *pSize = NDATA(pCur->pBt, pCell->h);
drh72f82862001-05-24 21:06:34 +00001227 }
1228 return SQLITE_OK;
1229}
1230
1231/*
drh5e00f6c2001-09-13 13:46:56 +00001232** Read part of the data associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +00001233** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +00001234** begins at "offset". The number of bytes actually read is
1235** returned. The amount returned will be smaller than the
1236** amount requested if there are not enough bytes in the data
1237** to satisfy the request.
drh72f82862001-05-24 21:06:34 +00001238*/
1239int sqliteBtreeData(BtCursor *pCur, int offset, int amt, char *zBuf){
1240 Cell *pCell;
1241 MemPage *pPage;
drh0d316a42002-08-11 20:10:47 +00001242 int nData;
drh72f82862001-05-24 21:06:34 +00001243
drh5e00f6c2001-09-13 13:46:56 +00001244 if( amt<0 ) return 0;
1245 if( offset<0 ) return 0;
1246 if( amt==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001247 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001248 if( pPage==0 || 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];
drh0d316a42002-08-11 20:10:47 +00001252 nData = NDATA(pCur->pBt, pCell->h);
1253 if( amt+offset > nData ){
1254 amt = nData - offset;
drh5e00f6c2001-09-13 13:46:56 +00001255 if( amt<=0 ){
1256 return 0;
1257 }
drhbd03cae2001-06-02 02:40:57 +00001258 }
drh0d316a42002-08-11 20:10:47 +00001259 getPayload(pCur, offset + NKEY(pCur->pBt, pCell->h), amt, zBuf);
drh5e00f6c2001-09-13 13:46:56 +00001260 return amt;
drh72f82862001-05-24 21:06:34 +00001261}
drha059ad02001-04-17 20:09:11 +00001262
drh2af926b2001-05-15 00:39:25 +00001263/*
drh8721ce42001-11-07 14:22:00 +00001264** Compare an external key against the key on the entry that pCur points to.
1265**
1266** The external key is pKey and is nKey bytes long. The last nIgnore bytes
1267** of the key associated with pCur are ignored, as if they do not exist.
1268** (The normal case is for nIgnore to be zero in which case the entire
1269** internal key is used in the comparison.)
1270**
1271** The comparison result is written to *pRes as follows:
drh2af926b2001-05-15 00:39:25 +00001272**
drh717e6402001-09-27 03:22:32 +00001273** *pRes<0 This means pCur<pKey
1274**
1275** *pRes==0 This means pCur==pKey for all nKey bytes
1276**
1277** *pRes>0 This means pCur>pKey
1278**
drh8721ce42001-11-07 14:22:00 +00001279** When one key is an exact prefix of the other, the shorter key is
1280** considered less than the longer one. In order to be equal the
1281** keys must be exactly the same length. (The length of the pCur key
1282** is the actual key length minus nIgnore bytes.)
drh2af926b2001-05-15 00:39:25 +00001283*/
drh717e6402001-09-27 03:22:32 +00001284int sqliteBtreeKeyCompare(
drh8721ce42001-11-07 14:22:00 +00001285 BtCursor *pCur, /* Pointer to entry to compare against */
1286 const void *pKey, /* Key to compare against entry that pCur points to */
1287 int nKey, /* Number of bytes in pKey */
1288 int nIgnore, /* Ignore this many bytes at the end of pCur */
1289 int *pResult /* Write the result here */
drh5c4d9702001-08-20 00:33:58 +00001290){
drh2af926b2001-05-15 00:39:25 +00001291 Pgno nextPage;
drh8721ce42001-11-07 14:22:00 +00001292 int n, c, rc, nLocal;
drh2af926b2001-05-15 00:39:25 +00001293 Cell *pCell;
drh0d316a42002-08-11 20:10:47 +00001294 Btree *pBt = pCur->pBt;
drh717e6402001-09-27 03:22:32 +00001295 const char *zKey = (const char*)pKey;
drh2af926b2001-05-15 00:39:25 +00001296
1297 assert( pCur->pPage );
1298 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drhbd03cae2001-06-02 02:40:57 +00001299 pCell = pCur->pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00001300 nLocal = NKEY(pBt, pCell->h) - nIgnore;
drh8721ce42001-11-07 14:22:00 +00001301 if( nLocal<0 ) nLocal = 0;
1302 n = nKey<nLocal ? nKey : nLocal;
drh2af926b2001-05-15 00:39:25 +00001303 if( n>MX_LOCAL_PAYLOAD ){
1304 n = MX_LOCAL_PAYLOAD;
1305 }
drh717e6402001-09-27 03:22:32 +00001306 c = memcmp(pCell->aPayload, zKey, n);
drh2af926b2001-05-15 00:39:25 +00001307 if( c!=0 ){
1308 *pResult = c;
1309 return SQLITE_OK;
1310 }
drh717e6402001-09-27 03:22:32 +00001311 zKey += n;
drh2af926b2001-05-15 00:39:25 +00001312 nKey -= n;
drh8721ce42001-11-07 14:22:00 +00001313 nLocal -= n;
drh0d316a42002-08-11 20:10:47 +00001314 nextPage = SWAB32(pBt, pCell->ovfl);
drh8721ce42001-11-07 14:22:00 +00001315 while( nKey>0 && nLocal>0 ){
drh2af926b2001-05-15 00:39:25 +00001316 OverflowPage *pOvfl;
1317 if( nextPage==0 ){
1318 return SQLITE_CORRUPT;
1319 }
drh0d316a42002-08-11 20:10:47 +00001320 rc = sqlitepager_get(pBt->pPager, nextPage, (void**)&pOvfl);
drh72f82862001-05-24 21:06:34 +00001321 if( rc ){
drh2af926b2001-05-15 00:39:25 +00001322 return rc;
1323 }
drh0d316a42002-08-11 20:10:47 +00001324 nextPage = SWAB32(pBt, pOvfl->iNext);
drh8721ce42001-11-07 14:22:00 +00001325 n = nKey<nLocal ? nKey : nLocal;
drh2af926b2001-05-15 00:39:25 +00001326 if( n>OVERFLOW_SIZE ){
1327 n = OVERFLOW_SIZE;
1328 }
drh717e6402001-09-27 03:22:32 +00001329 c = memcmp(pOvfl->aPayload, zKey, n);
drh2af926b2001-05-15 00:39:25 +00001330 sqlitepager_unref(pOvfl);
1331 if( c!=0 ){
1332 *pResult = c;
1333 return SQLITE_OK;
1334 }
1335 nKey -= n;
drh8721ce42001-11-07 14:22:00 +00001336 nLocal -= n;
drh717e6402001-09-27 03:22:32 +00001337 zKey += n;
drh2af926b2001-05-15 00:39:25 +00001338 }
drh717e6402001-09-27 03:22:32 +00001339 if( c==0 ){
drh8721ce42001-11-07 14:22:00 +00001340 c = nLocal - nKey;
drh717e6402001-09-27 03:22:32 +00001341 }
drh2af926b2001-05-15 00:39:25 +00001342 *pResult = c;
1343 return SQLITE_OK;
1344}
1345
drh72f82862001-05-24 21:06:34 +00001346/*
1347** Move the cursor down to a new child page.
1348*/
drh5e2f8b92001-05-28 00:41:15 +00001349static int moveToChild(BtCursor *pCur, int newPgno){
drh72f82862001-05-24 21:06:34 +00001350 int rc;
1351 MemPage *pNewPage;
drh0d316a42002-08-11 20:10:47 +00001352 Btree *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00001353
drh0d316a42002-08-11 20:10:47 +00001354 rc = sqlitepager_get(pBt->pPager, newPgno, (void**)&pNewPage);
drh6019e162001-07-02 17:51:45 +00001355 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001356 rc = initPage(pBt, pNewPage, newPgno, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00001357 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001358 sqlitepager_unref(pCur->pPage);
1359 pCur->pPage = pNewPage;
1360 pCur->idx = 0;
1361 return SQLITE_OK;
1362}
1363
1364/*
drh5e2f8b92001-05-28 00:41:15 +00001365** Move the cursor up to the parent page.
1366**
1367** pCur->idx is set to the cell index that contains the pointer
1368** to the page we are coming from. If we are coming from the
1369** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00001370** the largest cell index.
drh72f82862001-05-24 21:06:34 +00001371*/
drh5e2f8b92001-05-28 00:41:15 +00001372static int moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001373 Pgno oldPgno;
1374 MemPage *pParent;
drh8c42ca92001-06-22 19:15:00 +00001375 int i;
drh72f82862001-05-24 21:06:34 +00001376 pParent = pCur->pPage->pParent;
drhbd03cae2001-06-02 02:40:57 +00001377 if( pParent==0 ) return SQLITE_INTERNAL;
drh72f82862001-05-24 21:06:34 +00001378 oldPgno = sqlitepager_pagenumber(pCur->pPage);
drh72f82862001-05-24 21:06:34 +00001379 sqlitepager_ref(pParent);
1380 sqlitepager_unref(pCur->pPage);
1381 pCur->pPage = pParent;
drh8c42ca92001-06-22 19:15:00 +00001382 pCur->idx = pParent->nCell;
drh0d316a42002-08-11 20:10:47 +00001383 oldPgno = SWAB32(pCur->pBt, oldPgno);
drh8c42ca92001-06-22 19:15:00 +00001384 for(i=0; i<pParent->nCell; i++){
1385 if( pParent->apCell[i]->h.leftChild==oldPgno ){
drh72f82862001-05-24 21:06:34 +00001386 pCur->idx = i;
1387 break;
1388 }
1389 }
drh5e2f8b92001-05-28 00:41:15 +00001390 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00001391}
1392
1393/*
1394** Move the cursor to the root page
1395*/
drh5e2f8b92001-05-28 00:41:15 +00001396static int moveToRoot(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001397 MemPage *pNew;
drhbd03cae2001-06-02 02:40:57 +00001398 int rc;
drh0d316a42002-08-11 20:10:47 +00001399 Btree *pBt = pCur->pBt;
drhbd03cae2001-06-02 02:40:57 +00001400
drh0d316a42002-08-11 20:10:47 +00001401 rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pNew);
drhbd03cae2001-06-02 02:40:57 +00001402 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001403 rc = initPage(pBt, pNew, pCur->pgnoRoot, 0);
drh6019e162001-07-02 17:51:45 +00001404 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001405 sqlitepager_unref(pCur->pPage);
1406 pCur->pPage = pNew;
1407 pCur->idx = 0;
1408 return SQLITE_OK;
1409}
drh2af926b2001-05-15 00:39:25 +00001410
drh5e2f8b92001-05-28 00:41:15 +00001411/*
1412** Move the cursor down to the left-most leaf entry beneath the
1413** entry to which it is currently pointing.
1414*/
1415static int moveToLeftmost(BtCursor *pCur){
1416 Pgno pgno;
1417 int rc;
1418
1419 while( (pgno = pCur->pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
drh0d316a42002-08-11 20:10:47 +00001420 rc = moveToChild(pCur, SWAB32(pCur->pBt, pgno));
drh5e2f8b92001-05-28 00:41:15 +00001421 if( rc ) return rc;
1422 }
1423 return SQLITE_OK;
1424}
1425
drh2dcc9aa2002-12-04 13:40:25 +00001426/*
1427** Move the cursor down to the right-most leaf entry beneath the
1428** page to which it is currently pointing. Notice the difference
1429** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
1430** finds the left-most entry beneath the *entry* whereas moveToRightmost()
1431** finds the right-most entry beneath the *page*.
1432*/
1433static int moveToRightmost(BtCursor *pCur){
1434 Pgno pgno;
1435 int rc;
1436
1437 while( (pgno = pCur->pPage->u.hdr.rightChild)!=0 ){
1438 rc = moveToChild(pCur, SWAB32(pCur->pBt, pgno));
1439 if( rc ) return rc;
1440 }
1441 pCur->idx = pCur->pPage->nCell - 1;
1442 return SQLITE_OK;
1443}
1444
drh5e00f6c2001-09-13 13:46:56 +00001445/* Move the cursor to the first entry in the table. Return SQLITE_OK
1446** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00001447** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00001448*/
1449int sqliteBtreeFirst(BtCursor *pCur, int *pRes){
1450 int rc;
drhecdc7532001-09-23 02:35:53 +00001451 if( pCur->pPage==0 ) return SQLITE_ABORT;
drh5e00f6c2001-09-13 13:46:56 +00001452 rc = moveToRoot(pCur);
1453 if( rc ) return rc;
1454 if( pCur->pPage->nCell==0 ){
1455 *pRes = 1;
1456 return SQLITE_OK;
1457 }
1458 *pRes = 0;
1459 rc = moveToLeftmost(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00001460 pCur->eSkip = SKIP_NONE;
drh5e00f6c2001-09-13 13:46:56 +00001461 return rc;
1462}
drh5e2f8b92001-05-28 00:41:15 +00001463
drh9562b552002-02-19 15:00:07 +00001464/* Move the cursor to the last entry in the table. Return SQLITE_OK
1465** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00001466** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00001467*/
1468int sqliteBtreeLast(BtCursor *pCur, int *pRes){
1469 int rc;
drh9562b552002-02-19 15:00:07 +00001470 if( pCur->pPage==0 ) return SQLITE_ABORT;
1471 rc = moveToRoot(pCur);
1472 if( rc ) return rc;
drh7aa128d2002-06-21 13:09:16 +00001473 assert( pCur->pPage->isInit );
drh9562b552002-02-19 15:00:07 +00001474 if( pCur->pPage->nCell==0 ){
1475 *pRes = 1;
1476 return SQLITE_OK;
1477 }
1478 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00001479 rc = moveToRightmost(pCur);
1480 pCur->eSkip = SKIP_NONE;
drh9562b552002-02-19 15:00:07 +00001481 return rc;
1482}
1483
drha059ad02001-04-17 20:09:11 +00001484/* Move the cursor so that it points to an entry near pKey.
drh72f82862001-05-24 21:06:34 +00001485** Return a success code.
1486**
drh5e2f8b92001-05-28 00:41:15 +00001487** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00001488** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00001489** were present. The cursor might point to an entry that comes
1490** before or after the key.
1491**
drhbd03cae2001-06-02 02:40:57 +00001492** The result of comparing the key with the entry to which the
1493** cursor is left pointing is stored in pCur->iMatch. The same
1494** value is also written to *pRes if pRes!=NULL. The meaning of
1495** this value is as follows:
1496**
1497** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00001498** is smaller than pKey or if the table is empty
1499** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00001500**
1501** *pRes==0 The cursor is left pointing at an entry that
1502** exactly matches pKey.
1503**
1504** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001505** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00001506*/
drh5c4d9702001-08-20 00:33:58 +00001507int sqliteBtreeMoveto(BtCursor *pCur, const void *pKey, int nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00001508 int rc;
drhecdc7532001-09-23 02:35:53 +00001509 if( pCur->pPage==0 ) return SQLITE_ABORT;
drh2dcc9aa2002-12-04 13:40:25 +00001510 pCur->eSkip = SKIP_NONE;
drh5e2f8b92001-05-28 00:41:15 +00001511 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00001512 if( rc ) return rc;
1513 for(;;){
1514 int lwr, upr;
1515 Pgno chldPg;
1516 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00001517 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00001518 lwr = 0;
1519 upr = pPage->nCell-1;
1520 while( lwr<=upr ){
drh72f82862001-05-24 21:06:34 +00001521 pCur->idx = (lwr+upr)/2;
drh8721ce42001-11-07 14:22:00 +00001522 rc = sqliteBtreeKeyCompare(pCur, pKey, nKey, 0, &c);
drh72f82862001-05-24 21:06:34 +00001523 if( rc ) return rc;
1524 if( c==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001525 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001526 if( pRes ) *pRes = 0;
1527 return SQLITE_OK;
1528 }
1529 if( c<0 ){
1530 lwr = pCur->idx+1;
1531 }else{
1532 upr = pCur->idx-1;
1533 }
1534 }
1535 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00001536 assert( pPage->isInit );
drh72f82862001-05-24 21:06:34 +00001537 if( lwr>=pPage->nCell ){
drh14acc042001-06-10 19:56:58 +00001538 chldPg = pPage->u.hdr.rightChild;
drh72f82862001-05-24 21:06:34 +00001539 }else{
drh5e2f8b92001-05-28 00:41:15 +00001540 chldPg = pPage->apCell[lwr]->h.leftChild;
drh72f82862001-05-24 21:06:34 +00001541 }
1542 if( chldPg==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001543 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001544 if( pRes ) *pRes = c;
1545 return SQLITE_OK;
1546 }
drh0d316a42002-08-11 20:10:47 +00001547 rc = moveToChild(pCur, SWAB32(pCur->pBt, chldPg));
drh72f82862001-05-24 21:06:34 +00001548 if( rc ) return rc;
1549 }
drhbd03cae2001-06-02 02:40:57 +00001550 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00001551}
1552
1553/*
drhbd03cae2001-06-02 02:40:57 +00001554** Advance the cursor to the next entry in the database. If
1555** successful and pRes!=NULL then set *pRes=0. If the cursor
1556** was already pointing to the last entry in the database before
1557** this routine was called, then set *pRes=1 if pRes!=NULL.
drh72f82862001-05-24 21:06:34 +00001558*/
1559int sqliteBtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00001560 int rc;
drhecdc7532001-09-23 02:35:53 +00001561 if( pCur->pPage==0 ){
drh1bee3d72001-10-15 00:44:35 +00001562 if( pRes ) *pRes = 1;
drhecdc7532001-09-23 02:35:53 +00001563 return SQLITE_ABORT;
1564 }
drh7aa128d2002-06-21 13:09:16 +00001565 assert( pCur->pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00001566 assert( pCur->eSkip!=SKIP_INVALID );
1567 if( pCur->pPage->nCell==0 ){
1568 if( pRes ) *pRes = 1;
1569 return SQLITE_OK;
1570 }
1571 assert( pCur->idx<pCur->pPage->nCell );
1572 if( pCur->eSkip==SKIP_NEXT ){
1573 pCur->eSkip = SKIP_NONE;
drh72f82862001-05-24 21:06:34 +00001574 if( pRes ) *pRes = 0;
1575 return SQLITE_OK;
1576 }
drh2dcc9aa2002-12-04 13:40:25 +00001577 pCur->eSkip = SKIP_NONE;
drh72f82862001-05-24 21:06:34 +00001578 pCur->idx++;
drh5e2f8b92001-05-28 00:41:15 +00001579 if( pCur->idx>=pCur->pPage->nCell ){
drh8c42ca92001-06-22 19:15:00 +00001580 if( pCur->pPage->u.hdr.rightChild ){
drh0d316a42002-08-11 20:10:47 +00001581 rc = moveToChild(pCur, SWAB32(pCur->pBt, pCur->pPage->u.hdr.rightChild));
drh5e2f8b92001-05-28 00:41:15 +00001582 if( rc ) return rc;
1583 rc = moveToLeftmost(pCur);
1584 if( rc ) return rc;
1585 if( pRes ) *pRes = 0;
drh72f82862001-05-24 21:06:34 +00001586 return SQLITE_OK;
1587 }
drh5e2f8b92001-05-28 00:41:15 +00001588 do{
drh8c42ca92001-06-22 19:15:00 +00001589 if( pCur->pPage->pParent==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001590 if( pRes ) *pRes = 1;
1591 return SQLITE_OK;
1592 }
1593 rc = moveToParent(pCur);
1594 if( rc ) return rc;
1595 }while( pCur->idx>=pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00001596 if( pRes ) *pRes = 0;
1597 return SQLITE_OK;
1598 }
drh5e2f8b92001-05-28 00:41:15 +00001599 rc = moveToLeftmost(pCur);
1600 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001601 if( pRes ) *pRes = 0;
1602 return SQLITE_OK;
1603}
1604
drh3b7511c2001-05-26 13:15:44 +00001605/*
drh2dcc9aa2002-12-04 13:40:25 +00001606** Step the cursor to the back to the previous entry in the database. If
1607** successful and pRes!=NULL then set *pRes=0. If the cursor
1608** was already pointing to the first entry in the database before
1609** this routine was called, then set *pRes=1 if pRes!=NULL.
1610*/
1611int sqliteBtreePrevious(BtCursor *pCur, int *pRes){
1612 int rc;
1613 Pgno pgno;
1614 if( pCur->pPage==0 ){
1615 if( pRes ) *pRes = 1;
1616 return SQLITE_ABORT;
1617 }
1618 assert( pCur->pPage->isInit );
1619 assert( pCur->eSkip!=SKIP_INVALID );
1620 if( pCur->pPage->nCell==0 ){
1621 if( pRes ) *pRes = 1;
1622 return SQLITE_OK;
1623 }
1624 if( pCur->eSkip==SKIP_PREV ){
1625 pCur->eSkip = SKIP_NONE;
1626 if( pRes ) *pRes = 0;
1627 return SQLITE_OK;
1628 }
1629 pCur->eSkip = SKIP_NONE;
1630 assert( pCur->idx>=0 );
1631 if( (pgno = pCur->pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
1632 rc = moveToChild(pCur, SWAB32(pCur->pBt, pgno));
1633 if( rc ) return rc;
1634 rc = moveToRightmost(pCur);
1635 }else{
1636 while( pCur->idx==0 ){
1637 if( pCur->pPage->pParent==0 ){
1638 if( pRes ) *pRes = 1;
1639 return SQLITE_OK;
1640 }
1641 rc = moveToParent(pCur);
1642 if( rc ) return rc;
1643 }
1644 pCur->idx--;
1645 rc = SQLITE_OK;
1646 }
1647 if( pRes ) *pRes = 0;
1648 return rc;
1649}
1650
1651/*
drh3b7511c2001-05-26 13:15:44 +00001652** Allocate a new page from the database file.
1653**
1654** The new page is marked as dirty. (In other words, sqlitepager_write()
1655** has already been called on the new page.) The new page has also
1656** been referenced and the calling routine is responsible for calling
1657** sqlitepager_unref() on the new page when it is done.
1658**
1659** SQLITE_OK is returned on success. Any other return value indicates
1660** an error. *ppPage and *pPgno are undefined in the event of an error.
1661** Do not invoke sqlitepager_unref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00001662**
drh199e3cf2002-07-18 11:01:47 +00001663** If the "nearby" parameter is not 0, then a (feeble) effort is made to
1664** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00001665** attempt to keep related pages close to each other in the database file,
1666** which in turn can make database access faster.
drh3b7511c2001-05-26 13:15:44 +00001667*/
drh199e3cf2002-07-18 11:01:47 +00001668static int allocatePage(Btree *pBt, MemPage **ppPage, Pgno *pPgno, Pgno nearby){
drhbd03cae2001-06-02 02:40:57 +00001669 PageOne *pPage1 = pBt->page1;
drh8c42ca92001-06-22 19:15:00 +00001670 int rc;
drh3b7511c2001-05-26 13:15:44 +00001671 if( pPage1->freeList ){
1672 OverflowPage *pOvfl;
drh30e58752002-03-02 20:41:57 +00001673 FreelistInfo *pInfo;
1674
drh3b7511c2001-05-26 13:15:44 +00001675 rc = sqlitepager_write(pPage1);
1676 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001677 SWAB_ADD(pBt, pPage1->nFree, -1);
1678 rc = sqlitepager_get(pBt->pPager, SWAB32(pBt, pPage1->freeList),
1679 (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001680 if( rc ) return rc;
1681 rc = sqlitepager_write(pOvfl);
1682 if( rc ){
1683 sqlitepager_unref(pOvfl);
1684 return rc;
1685 }
drh30e58752002-03-02 20:41:57 +00001686 pInfo = (FreelistInfo*)pOvfl->aPayload;
1687 if( pInfo->nFree==0 ){
drh0d316a42002-08-11 20:10:47 +00001688 *pPgno = SWAB32(pBt, pPage1->freeList);
drh30e58752002-03-02 20:41:57 +00001689 pPage1->freeList = pOvfl->iNext;
1690 *ppPage = (MemPage*)pOvfl;
1691 }else{
drh0d316a42002-08-11 20:10:47 +00001692 int closest, n;
1693 n = SWAB32(pBt, pInfo->nFree);
1694 if( n>1 && nearby>0 ){
drhbea00b92002-07-08 10:59:50 +00001695 int i, dist;
1696 closest = 0;
drh0d316a42002-08-11 20:10:47 +00001697 dist = SWAB32(pBt, pInfo->aFree[0]) - nearby;
drhbea00b92002-07-08 10:59:50 +00001698 if( dist<0 ) dist = -dist;
drh0d316a42002-08-11 20:10:47 +00001699 for(i=1; i<n; i++){
1700 int d2 = SWAB32(pBt, pInfo->aFree[i]) - nearby;
drhbea00b92002-07-08 10:59:50 +00001701 if( d2<0 ) d2 = -d2;
1702 if( d2<dist ) closest = i;
1703 }
1704 }else{
1705 closest = 0;
1706 }
drh0d316a42002-08-11 20:10:47 +00001707 SWAB_ADD(pBt, pInfo->nFree, -1);
1708 *pPgno = SWAB32(pBt, pInfo->aFree[closest]);
1709 pInfo->aFree[closest] = pInfo->aFree[n-1];
drh30e58752002-03-02 20:41:57 +00001710 rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
1711 sqlitepager_unref(pOvfl);
1712 if( rc==SQLITE_OK ){
1713 sqlitepager_dont_rollback(*ppPage);
1714 rc = sqlitepager_write(*ppPage);
1715 }
1716 }
drh3b7511c2001-05-26 13:15:44 +00001717 }else{
drh2aa679f2001-06-25 02:11:07 +00001718 *pPgno = sqlitepager_pagecount(pBt->pPager) + 1;
drh8c42ca92001-06-22 19:15:00 +00001719 rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
drh3b7511c2001-05-26 13:15:44 +00001720 if( rc ) return rc;
1721 rc = sqlitepager_write(*ppPage);
1722 }
1723 return rc;
1724}
1725
1726/*
1727** Add a page of the database file to the freelist. Either pgno or
1728** pPage but not both may be 0.
drh5e2f8b92001-05-28 00:41:15 +00001729**
drhdd793422001-06-28 01:54:48 +00001730** sqlitepager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00001731*/
1732static int freePage(Btree *pBt, void *pPage, Pgno pgno){
drhbd03cae2001-06-02 02:40:57 +00001733 PageOne *pPage1 = pBt->page1;
drh3b7511c2001-05-26 13:15:44 +00001734 OverflowPage *pOvfl = (OverflowPage*)pPage;
1735 int rc;
drhdd793422001-06-28 01:54:48 +00001736 int needUnref = 0;
1737 MemPage *pMemPage;
drh8b2f49b2001-06-08 00:21:52 +00001738
drh3b7511c2001-05-26 13:15:44 +00001739 if( pgno==0 ){
1740 assert( pOvfl!=0 );
1741 pgno = sqlitepager_pagenumber(pOvfl);
1742 }
drh2aa679f2001-06-25 02:11:07 +00001743 assert( pgno>2 );
drhda47d772002-12-02 04:25:19 +00001744 assert( sqlitepager_pagenumber(pOvfl)==pgno );
drh193a6b42002-07-07 16:52:46 +00001745 pMemPage = (MemPage*)pPage;
1746 pMemPage->isInit = 0;
1747 if( pMemPage->pParent ){
1748 sqlitepager_unref(pMemPage->pParent);
1749 pMemPage->pParent = 0;
1750 }
drh3b7511c2001-05-26 13:15:44 +00001751 rc = sqlitepager_write(pPage1);
1752 if( rc ){
1753 return rc;
1754 }
drh0d316a42002-08-11 20:10:47 +00001755 SWAB_ADD(pBt, pPage1->nFree, 1);
1756 if( pPage1->nFree!=0 && pPage1->freeList!=0 ){
drh30e58752002-03-02 20:41:57 +00001757 OverflowPage *pFreeIdx;
drh0d316a42002-08-11 20:10:47 +00001758 rc = sqlitepager_get(pBt->pPager, SWAB32(pBt, pPage1->freeList),
1759 (void**)&pFreeIdx);
drh30e58752002-03-02 20:41:57 +00001760 if( rc==SQLITE_OK ){
1761 FreelistInfo *pInfo = (FreelistInfo*)pFreeIdx->aPayload;
drh0d316a42002-08-11 20:10:47 +00001762 int n = SWAB32(pBt, pInfo->nFree);
1763 if( n<(sizeof(pInfo->aFree)/sizeof(pInfo->aFree[0])) ){
drh30e58752002-03-02 20:41:57 +00001764 rc = sqlitepager_write(pFreeIdx);
1765 if( rc==SQLITE_OK ){
drh0d316a42002-08-11 20:10:47 +00001766 pInfo->aFree[n] = SWAB32(pBt, pgno);
1767 SWAB_ADD(pBt, pInfo->nFree, 1);
drh30e58752002-03-02 20:41:57 +00001768 sqlitepager_unref(pFreeIdx);
1769 sqlitepager_dont_write(pBt->pPager, pgno);
1770 return rc;
1771 }
1772 }
1773 sqlitepager_unref(pFreeIdx);
1774 }
1775 }
drh3b7511c2001-05-26 13:15:44 +00001776 if( pOvfl==0 ){
1777 assert( pgno>0 );
drh8c42ca92001-06-22 19:15:00 +00001778 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001779 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001780 needUnref = 1;
drh3b7511c2001-05-26 13:15:44 +00001781 }
1782 rc = sqlitepager_write(pOvfl);
1783 if( rc ){
drhdd793422001-06-28 01:54:48 +00001784 if( needUnref ) sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001785 return rc;
1786 }
drh14acc042001-06-10 19:56:58 +00001787 pOvfl->iNext = pPage1->freeList;
drh0d316a42002-08-11 20:10:47 +00001788 pPage1->freeList = SWAB32(pBt, pgno);
drh5e2f8b92001-05-28 00:41:15 +00001789 memset(pOvfl->aPayload, 0, OVERFLOW_SIZE);
drhdd793422001-06-28 01:54:48 +00001790 if( needUnref ) rc = sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001791 return rc;
1792}
1793
1794/*
1795** Erase all the data out of a cell. This involves returning overflow
1796** pages back the freelist.
1797*/
1798static int clearCell(Btree *pBt, Cell *pCell){
1799 Pager *pPager = pBt->pPager;
1800 OverflowPage *pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001801 Pgno ovfl, nextOvfl;
1802 int rc;
1803
drh0d316a42002-08-11 20:10:47 +00001804 if( NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h) <= MX_LOCAL_PAYLOAD ){
drh5e2f8b92001-05-28 00:41:15 +00001805 return SQLITE_OK;
1806 }
drh0d316a42002-08-11 20:10:47 +00001807 ovfl = SWAB32(pBt, pCell->ovfl);
drh3b7511c2001-05-26 13:15:44 +00001808 pCell->ovfl = 0;
1809 while( ovfl ){
drh8c42ca92001-06-22 19:15:00 +00001810 rc = sqlitepager_get(pPager, ovfl, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001811 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001812 nextOvfl = SWAB32(pBt, pOvfl->iNext);
drhbd03cae2001-06-02 02:40:57 +00001813 rc = freePage(pBt, pOvfl, ovfl);
1814 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001815 sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001816 ovfl = nextOvfl;
drh3b7511c2001-05-26 13:15:44 +00001817 }
drh5e2f8b92001-05-28 00:41:15 +00001818 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00001819}
1820
1821/*
1822** Create a new cell from key and data. Overflow pages are allocated as
1823** necessary and linked to this cell.
1824*/
1825static int fillInCell(
1826 Btree *pBt, /* The whole Btree. Needed to allocate pages */
1827 Cell *pCell, /* Populate this Cell structure */
drh5c4d9702001-08-20 00:33:58 +00001828 const void *pKey, int nKey, /* The key */
1829 const void *pData,int nData /* The data */
drh3b7511c2001-05-26 13:15:44 +00001830){
drhdd793422001-06-28 01:54:48 +00001831 OverflowPage *pOvfl, *pPrior;
drh3b7511c2001-05-26 13:15:44 +00001832 Pgno *pNext;
1833 int spaceLeft;
drh8c42ca92001-06-22 19:15:00 +00001834 int n, rc;
drh3b7511c2001-05-26 13:15:44 +00001835 int nPayload;
drh5c4d9702001-08-20 00:33:58 +00001836 const char *pPayload;
drh3b7511c2001-05-26 13:15:44 +00001837 char *pSpace;
drh199e3cf2002-07-18 11:01:47 +00001838 Pgno nearby = 0;
drh3b7511c2001-05-26 13:15:44 +00001839
drh5e2f8b92001-05-28 00:41:15 +00001840 pCell->h.leftChild = 0;
drh0d316a42002-08-11 20:10:47 +00001841 pCell->h.nKey = SWAB16(pBt, nKey & 0xffff);
drh80ff32f2001-11-04 18:32:46 +00001842 pCell->h.nKeyHi = nKey >> 16;
drh0d316a42002-08-11 20:10:47 +00001843 pCell->h.nData = SWAB16(pBt, nData & 0xffff);
drh80ff32f2001-11-04 18:32:46 +00001844 pCell->h.nDataHi = nData >> 16;
drh3b7511c2001-05-26 13:15:44 +00001845 pCell->h.iNext = 0;
1846
1847 pNext = &pCell->ovfl;
drh5e2f8b92001-05-28 00:41:15 +00001848 pSpace = pCell->aPayload;
drh3b7511c2001-05-26 13:15:44 +00001849 spaceLeft = MX_LOCAL_PAYLOAD;
1850 pPayload = pKey;
1851 pKey = 0;
1852 nPayload = nKey;
drhdd793422001-06-28 01:54:48 +00001853 pPrior = 0;
drh3b7511c2001-05-26 13:15:44 +00001854 while( nPayload>0 ){
1855 if( spaceLeft==0 ){
drh199e3cf2002-07-18 11:01:47 +00001856 rc = allocatePage(pBt, (MemPage**)&pOvfl, pNext, nearby);
drh3b7511c2001-05-26 13:15:44 +00001857 if( rc ){
1858 *pNext = 0;
drhbea00b92002-07-08 10:59:50 +00001859 }else{
drh199e3cf2002-07-18 11:01:47 +00001860 nearby = *pNext;
drhdd793422001-06-28 01:54:48 +00001861 }
1862 if( pPrior ) sqlitepager_unref(pPrior);
1863 if( rc ){
drh5e2f8b92001-05-28 00:41:15 +00001864 clearCell(pBt, pCell);
drh3b7511c2001-05-26 13:15:44 +00001865 return rc;
1866 }
drh0d316a42002-08-11 20:10:47 +00001867 if( pBt->needSwab ) *pNext = swab32(*pNext);
drhdd793422001-06-28 01:54:48 +00001868 pPrior = pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001869 spaceLeft = OVERFLOW_SIZE;
drh5e2f8b92001-05-28 00:41:15 +00001870 pSpace = pOvfl->aPayload;
drh8c42ca92001-06-22 19:15:00 +00001871 pNext = &pOvfl->iNext;
drh3b7511c2001-05-26 13:15:44 +00001872 }
1873 n = nPayload;
1874 if( n>spaceLeft ) n = spaceLeft;
1875 memcpy(pSpace, pPayload, n);
1876 nPayload -= n;
1877 if( nPayload==0 && pData ){
1878 pPayload = pData;
1879 nPayload = nData;
1880 pData = 0;
1881 }else{
1882 pPayload += n;
1883 }
1884 spaceLeft -= n;
1885 pSpace += n;
1886 }
drhdd793422001-06-28 01:54:48 +00001887 *pNext = 0;
1888 if( pPrior ){
1889 sqlitepager_unref(pPrior);
1890 }
drh3b7511c2001-05-26 13:15:44 +00001891 return SQLITE_OK;
1892}
1893
1894/*
drhbd03cae2001-06-02 02:40:57 +00001895** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00001896** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00001897** pointer in the third argument.
1898*/
1899static void reparentPage(Pager *pPager, Pgno pgno, MemPage *pNewParent){
1900 MemPage *pThis;
1901
drhdd793422001-06-28 01:54:48 +00001902 if( pgno==0 ) return;
1903 assert( pPager!=0 );
drhbd03cae2001-06-02 02:40:57 +00001904 pThis = sqlitepager_lookup(pPager, pgno);
drh6019e162001-07-02 17:51:45 +00001905 if( pThis && pThis->isInit ){
drhdd793422001-06-28 01:54:48 +00001906 if( pThis->pParent!=pNewParent ){
1907 if( pThis->pParent ) sqlitepager_unref(pThis->pParent);
1908 pThis->pParent = pNewParent;
1909 if( pNewParent ) sqlitepager_ref(pNewParent);
1910 }
1911 sqlitepager_unref(pThis);
drhbd03cae2001-06-02 02:40:57 +00001912 }
1913}
1914
1915/*
1916** Reparent all children of the given page to be the given page.
1917** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00001918** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00001919**
1920** This routine gets called after you memcpy() one page into
1921** another.
1922*/
drh0d316a42002-08-11 20:10:47 +00001923static void reparentChildPages(Btree *pBt, MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00001924 int i;
drh0d316a42002-08-11 20:10:47 +00001925 Pager *pPager = pBt->pPager;
drhbd03cae2001-06-02 02:40:57 +00001926 for(i=0; i<pPage->nCell; i++){
drh0d316a42002-08-11 20:10:47 +00001927 reparentPage(pPager, SWAB32(pBt, pPage->apCell[i]->h.leftChild), pPage);
drhbd03cae2001-06-02 02:40:57 +00001928 }
drh0d316a42002-08-11 20:10:47 +00001929 reparentPage(pPager, SWAB32(pBt, pPage->u.hdr.rightChild), pPage);
drh14acc042001-06-10 19:56:58 +00001930}
1931
1932/*
1933** Remove the i-th cell from pPage. This routine effects pPage only.
1934** The cell content is not freed or deallocated. It is assumed that
1935** the cell content has been copied someplace else. This routine just
1936** removes the reference to the cell from pPage.
1937**
1938** "sz" must be the number of bytes in the cell.
1939**
1940** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001941** Only the pPage->apCell[] array is important. The relinkCellList()
1942** routine will be called soon after this routine in order to rebuild
1943** the linked list.
drh14acc042001-06-10 19:56:58 +00001944*/
drh0d316a42002-08-11 20:10:47 +00001945static void dropCell(Btree *pBt, MemPage *pPage, int idx, int sz){
drh14acc042001-06-10 19:56:58 +00001946 int j;
drh8c42ca92001-06-22 19:15:00 +00001947 assert( idx>=0 && idx<pPage->nCell );
drh0d316a42002-08-11 20:10:47 +00001948 assert( sz==cellSize(pBt, pPage->apCell[idx]) );
drh6019e162001-07-02 17:51:45 +00001949 assert( sqlitepager_iswriteable(pPage) );
drh0d316a42002-08-11 20:10:47 +00001950 freeSpace(pBt, pPage, Addr(pPage->apCell[idx]) - Addr(pPage), sz);
drh7c717f72001-06-24 20:39:41 +00001951 for(j=idx; j<pPage->nCell-1; j++){
drh14acc042001-06-10 19:56:58 +00001952 pPage->apCell[j] = pPage->apCell[j+1];
1953 }
1954 pPage->nCell--;
1955}
1956
1957/*
1958** Insert a new cell on pPage at cell index "i". pCell points to the
1959** content of the cell.
1960**
1961** If the cell content will fit on the page, then put it there. If it
1962** will not fit, then just make pPage->apCell[i] point to the content
1963** and set pPage->isOverfull.
1964**
1965** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001966** Only the pPage->apCell[] array is important. The relinkCellList()
1967** routine will be called soon after this routine in order to rebuild
1968** the linked list.
drh14acc042001-06-10 19:56:58 +00001969*/
drh0d316a42002-08-11 20:10:47 +00001970static void insertCell(Btree *pBt, MemPage *pPage, int i, Cell *pCell, int sz){
drh14acc042001-06-10 19:56:58 +00001971 int idx, j;
1972 assert( i>=0 && i<=pPage->nCell );
drh0d316a42002-08-11 20:10:47 +00001973 assert( sz==cellSize(pBt, pCell) );
drh6019e162001-07-02 17:51:45 +00001974 assert( sqlitepager_iswriteable(pPage) );
drh0d316a42002-08-11 20:10:47 +00001975 idx = allocateSpace(pBt, pPage, sz);
drh14acc042001-06-10 19:56:58 +00001976 for(j=pPage->nCell; j>i; j--){
1977 pPage->apCell[j] = pPage->apCell[j-1];
1978 }
1979 pPage->nCell++;
drh14acc042001-06-10 19:56:58 +00001980 if( idx<=0 ){
1981 pPage->isOverfull = 1;
1982 pPage->apCell[i] = pCell;
1983 }else{
1984 memcpy(&pPage->u.aDisk[idx], pCell, sz);
drh8c42ca92001-06-22 19:15:00 +00001985 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[idx];
drh14acc042001-06-10 19:56:58 +00001986 }
1987}
1988
1989/*
1990** Rebuild the linked list of cells on a page so that the cells
drh8c42ca92001-06-22 19:15:00 +00001991** occur in the order specified by the pPage->apCell[] array.
1992** Invoke this routine once to repair damage after one or more
1993** invocations of either insertCell() or dropCell().
drh14acc042001-06-10 19:56:58 +00001994*/
drh0d316a42002-08-11 20:10:47 +00001995static void relinkCellList(Btree *pBt, MemPage *pPage){
drh14acc042001-06-10 19:56:58 +00001996 int i;
1997 u16 *pIdx;
drh6019e162001-07-02 17:51:45 +00001998 assert( sqlitepager_iswriteable(pPage) );
drh14acc042001-06-10 19:56:58 +00001999 pIdx = &pPage->u.hdr.firstCell;
2000 for(i=0; i<pPage->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00002001 int idx = Addr(pPage->apCell[i]) - Addr(pPage);
drh8c42ca92001-06-22 19:15:00 +00002002 assert( idx>0 && idx<SQLITE_PAGE_SIZE );
drh0d316a42002-08-11 20:10:47 +00002003 *pIdx = SWAB16(pBt, idx);
drh14acc042001-06-10 19:56:58 +00002004 pIdx = &pPage->apCell[i]->h.iNext;
2005 }
2006 *pIdx = 0;
2007}
2008
2009/*
2010** Make a copy of the contents of pFrom into pTo. The pFrom->apCell[]
drh5e00f6c2001-09-13 13:46:56 +00002011** pointers that point into pFrom->u.aDisk[] must be adjusted to point
drhdd793422001-06-28 01:54:48 +00002012** into pTo->u.aDisk[] instead. But some pFrom->apCell[] entries might
drh14acc042001-06-10 19:56:58 +00002013** not point to pFrom->u.aDisk[]. Those are unchanged.
2014*/
2015static void copyPage(MemPage *pTo, MemPage *pFrom){
2016 uptr from, to;
2017 int i;
2018 memcpy(pTo->u.aDisk, pFrom->u.aDisk, SQLITE_PAGE_SIZE);
drhdd793422001-06-28 01:54:48 +00002019 pTo->pParent = 0;
drh14acc042001-06-10 19:56:58 +00002020 pTo->isInit = 1;
2021 pTo->nCell = pFrom->nCell;
2022 pTo->nFree = pFrom->nFree;
2023 pTo->isOverfull = pFrom->isOverfull;
drh7c717f72001-06-24 20:39:41 +00002024 to = Addr(pTo);
2025 from = Addr(pFrom);
drh14acc042001-06-10 19:56:58 +00002026 for(i=0; i<pTo->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00002027 uptr x = Addr(pFrom->apCell[i]);
drh8c42ca92001-06-22 19:15:00 +00002028 if( x>from && x<from+SQLITE_PAGE_SIZE ){
2029 *((uptr*)&pTo->apCell[i]) = x + to - from;
drhdd793422001-06-28 01:54:48 +00002030 }else{
2031 pTo->apCell[i] = pFrom->apCell[i];
drh14acc042001-06-10 19:56:58 +00002032 }
2033 }
drhbd03cae2001-06-02 02:40:57 +00002034}
2035
2036/*
drh8b2f49b2001-06-08 00:21:52 +00002037** This routine redistributes Cells on pPage and up to two siblings
2038** of pPage so that all pages have about the same amount of free space.
drh14acc042001-06-10 19:56:58 +00002039** Usually one sibling on either side of pPage is used in the balancing,
drh8b2f49b2001-06-08 00:21:52 +00002040** though both siblings might come from one side if pPage is the first
2041** or last child of its parent. If pPage has fewer than two siblings
2042** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00002043** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00002044**
2045** The number of siblings of pPage might be increased or decreased by
drh8c42ca92001-06-22 19:15:00 +00002046** one in an effort to keep pages between 66% and 100% full. The root page
2047** is special and is allowed to be less than 66% full. If pPage is
2048** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00002049** or decreased by one, as necessary, to keep the root page from being
2050** overfull or empty.
2051**
drh14acc042001-06-10 19:56:58 +00002052** This routine calls relinkCellList() on its input page regardless of
2053** whether or not it does any real balancing. Client routines will typically
2054** invoke insertCell() or dropCell() before calling this routine, so we
2055** need to call relinkCellList() to clean up the mess that those other
2056** routines left behind.
2057**
2058** pCur is left pointing to the same cell as when this routine was called
drh8c42ca92001-06-22 19:15:00 +00002059** even if that cell gets moved to a different page. pCur may be NULL.
2060** Set the pCur parameter to NULL if you do not care about keeping track
2061** of a cell as that will save this routine the work of keeping track of it.
drh14acc042001-06-10 19:56:58 +00002062**
drh8b2f49b2001-06-08 00:21:52 +00002063** Note that when this routine is called, some of the Cells on pPage
drh14acc042001-06-10 19:56:58 +00002064** might not actually be stored in pPage->u.aDisk[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00002065** if the page is overfull. Part of the job of this routine is to
drh14acc042001-06-10 19:56:58 +00002066** make sure all Cells for pPage once again fit in pPage->u.aDisk[].
2067**
drh8c42ca92001-06-22 19:15:00 +00002068** In the course of balancing the siblings of pPage, the parent of pPage
2069** might become overfull or underfull. If that happens, then this routine
2070** is called recursively on the parent.
2071**
drh5e00f6c2001-09-13 13:46:56 +00002072** If this routine fails for any reason, it might leave the database
2073** in a corrupted state. So if this routine fails, the database should
2074** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00002075*/
drh14acc042001-06-10 19:56:58 +00002076static int balance(Btree *pBt, MemPage *pPage, BtCursor *pCur){
drh8b2f49b2001-06-08 00:21:52 +00002077 MemPage *pParent; /* The parent of pPage */
drh14acc042001-06-10 19:56:58 +00002078 MemPage *apOld[3]; /* pPage and up to two siblings */
drh8b2f49b2001-06-08 00:21:52 +00002079 Pgno pgnoOld[3]; /* Page numbers for each page in apOld[] */
drh14acc042001-06-10 19:56:58 +00002080 MemPage *apNew[4]; /* pPage and up to 3 siblings after balancing */
2081 Pgno pgnoNew[4]; /* Page numbers for each page in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00002082 int idxDiv[3]; /* Indices of divider cells in pParent */
2083 Cell *apDiv[3]; /* Divider cells in pParent */
2084 int nCell; /* Number of cells in apCell[] */
2085 int nOld; /* Number of pages in apOld[] */
2086 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00002087 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00002088 int i, j, k; /* Loop counters */
2089 int idx; /* Index of pPage in pParent->apCell[] */
2090 int nxDiv; /* Next divider slot in pParent->apCell[] */
2091 int rc; /* The return code */
2092 int iCur; /* apCell[iCur] is the cell of the cursor */
drh5edc3122001-09-13 21:53:09 +00002093 MemPage *pOldCurPage; /* The cursor originally points to this page */
drh6019e162001-07-02 17:51:45 +00002094 int subtotal; /* Subtotal of bytes in cells on one page */
2095 int cntNew[4]; /* Index in apCell[] of cell after i-th page */
2096 int szNew[4]; /* Combined size of cells place on i-th page */
drh9ca7d3b2001-06-28 11:50:21 +00002097 MemPage *extraUnref = 0; /* A page that needs to be unref-ed */
drh0d316a42002-08-11 20:10:47 +00002098 Pgno pgno, swabPgno; /* Page number */
drh14acc042001-06-10 19:56:58 +00002099 Cell *apCell[MX_CELL*3+5]; /* All cells from pages being balanceed */
2100 int szCell[MX_CELL*3+5]; /* Local size of all cells */
2101 Cell aTemp[2]; /* Temporary holding area for apDiv[] */
2102 MemPage aOld[3]; /* Temporary copies of pPage and its siblings */
drh8b2f49b2001-06-08 00:21:52 +00002103
drh14acc042001-06-10 19:56:58 +00002104 /*
2105 ** Return without doing any work if pPage is neither overfull nor
2106 ** underfull.
drh8b2f49b2001-06-08 00:21:52 +00002107 */
drh6019e162001-07-02 17:51:45 +00002108 assert( sqlitepager_iswriteable(pPage) );
drha1b351a2001-09-14 16:42:12 +00002109 if( !pPage->isOverfull && pPage->nFree<SQLITE_PAGE_SIZE/2
2110 && pPage->nCell>=2){
drh0d316a42002-08-11 20:10:47 +00002111 relinkCellList(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002112 return SQLITE_OK;
2113 }
2114
2115 /*
drh14acc042001-06-10 19:56:58 +00002116 ** Find the parent of the page to be balanceed.
2117 ** If there is no parent, it means this page is the root page and
drh8b2f49b2001-06-08 00:21:52 +00002118 ** special rules apply.
2119 */
drh14acc042001-06-10 19:56:58 +00002120 pParent = pPage->pParent;
drh8b2f49b2001-06-08 00:21:52 +00002121 if( pParent==0 ){
2122 Pgno pgnoChild;
drh8c42ca92001-06-22 19:15:00 +00002123 MemPage *pChild;
drh7aa128d2002-06-21 13:09:16 +00002124 assert( pPage->isInit );
drh8b2f49b2001-06-08 00:21:52 +00002125 if( pPage->nCell==0 ){
drh14acc042001-06-10 19:56:58 +00002126 if( pPage->u.hdr.rightChild ){
2127 /*
2128 ** The root page is empty. Copy the one child page
drh8b2f49b2001-06-08 00:21:52 +00002129 ** into the root page and return. This reduces the depth
2130 ** of the BTree by one.
2131 */
drh0d316a42002-08-11 20:10:47 +00002132 pgnoChild = SWAB32(pBt, pPage->u.hdr.rightChild);
drh8c42ca92001-06-22 19:15:00 +00002133 rc = sqlitepager_get(pBt->pPager, pgnoChild, (void**)&pChild);
drh8b2f49b2001-06-08 00:21:52 +00002134 if( rc ) return rc;
2135 memcpy(pPage, pChild, SQLITE_PAGE_SIZE);
2136 pPage->isInit = 0;
drh0d316a42002-08-11 20:10:47 +00002137 rc = initPage(pBt, pPage, sqlitepager_pagenumber(pPage), 0);
drh6019e162001-07-02 17:51:45 +00002138 assert( rc==SQLITE_OK );
drh0d316a42002-08-11 20:10:47 +00002139 reparentChildPages(pBt, pPage);
drh5edc3122001-09-13 21:53:09 +00002140 if( pCur && pCur->pPage==pChild ){
2141 sqlitepager_unref(pChild);
2142 pCur->pPage = pPage;
2143 sqlitepager_ref(pPage);
2144 }
drh8b2f49b2001-06-08 00:21:52 +00002145 freePage(pBt, pChild, pgnoChild);
2146 sqlitepager_unref(pChild);
drhefc251d2001-07-01 22:12:01 +00002147 }else{
drh0d316a42002-08-11 20:10:47 +00002148 relinkCellList(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002149 }
2150 return SQLITE_OK;
2151 }
drh14acc042001-06-10 19:56:58 +00002152 if( !pPage->isOverfull ){
drh8b2f49b2001-06-08 00:21:52 +00002153 /* It is OK for the root page to be less than half full.
2154 */
drh0d316a42002-08-11 20:10:47 +00002155 relinkCellList(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002156 return SQLITE_OK;
2157 }
drh14acc042001-06-10 19:56:58 +00002158 /*
2159 ** If we get to here, it means the root page is overfull.
drh8b2f49b2001-06-08 00:21:52 +00002160 ** When this happens, Create a new child page and copy the
2161 ** contents of the root into the child. Then make the root
drh14acc042001-06-10 19:56:58 +00002162 ** page an empty page with rightChild pointing to the new
drh8b2f49b2001-06-08 00:21:52 +00002163 ** child. Then fall thru to the code below which will cause
2164 ** the overfull child page to be split.
2165 */
drh14acc042001-06-10 19:56:58 +00002166 rc = sqlitepager_write(pPage);
2167 if( rc ) return rc;
drhbea00b92002-07-08 10:59:50 +00002168 rc = allocatePage(pBt, &pChild, &pgnoChild, sqlitepager_pagenumber(pPage));
drh8b2f49b2001-06-08 00:21:52 +00002169 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002170 assert( sqlitepager_iswriteable(pChild) );
drh14acc042001-06-10 19:56:58 +00002171 copyPage(pChild, pPage);
2172 pChild->pParent = pPage;
drhdd793422001-06-28 01:54:48 +00002173 sqlitepager_ref(pPage);
drh14acc042001-06-10 19:56:58 +00002174 pChild->isOverfull = 1;
drh5edc3122001-09-13 21:53:09 +00002175 if( pCur && pCur->pPage==pPage ){
2176 sqlitepager_unref(pPage);
drh14acc042001-06-10 19:56:58 +00002177 pCur->pPage = pChild;
drh9ca7d3b2001-06-28 11:50:21 +00002178 }else{
2179 extraUnref = pChild;
drh8b2f49b2001-06-08 00:21:52 +00002180 }
drh0d316a42002-08-11 20:10:47 +00002181 zeroPage(pBt, pPage);
2182 pPage->u.hdr.rightChild = SWAB32(pBt, pgnoChild);
drh8b2f49b2001-06-08 00:21:52 +00002183 pParent = pPage;
2184 pPage = pChild;
drh8b2f49b2001-06-08 00:21:52 +00002185 }
drh6019e162001-07-02 17:51:45 +00002186 rc = sqlitepager_write(pParent);
2187 if( rc ) return rc;
drh7aa128d2002-06-21 13:09:16 +00002188 assert( pParent->isInit );
drh14acc042001-06-10 19:56:58 +00002189
drh8b2f49b2001-06-08 00:21:52 +00002190 /*
drh14acc042001-06-10 19:56:58 +00002191 ** Find the Cell in the parent page whose h.leftChild points back
2192 ** to pPage. The "idx" variable is the index of that cell. If pPage
2193 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00002194 */
2195 idx = -1;
2196 pgno = sqlitepager_pagenumber(pPage);
drh0d316a42002-08-11 20:10:47 +00002197 swabPgno = SWAB32(pBt, pgno);
drh8b2f49b2001-06-08 00:21:52 +00002198 for(i=0; i<pParent->nCell; i++){
drh0d316a42002-08-11 20:10:47 +00002199 if( pParent->apCell[i]->h.leftChild==swabPgno ){
drh8b2f49b2001-06-08 00:21:52 +00002200 idx = i;
2201 break;
2202 }
2203 }
drh0d316a42002-08-11 20:10:47 +00002204 if( idx<0 && pParent->u.hdr.rightChild==swabPgno ){
drhdd793422001-06-28 01:54:48 +00002205 idx = pParent->nCell;
drh8b2f49b2001-06-08 00:21:52 +00002206 }
2207 if( idx<0 ){
drh14acc042001-06-10 19:56:58 +00002208 return SQLITE_CORRUPT;
drh8b2f49b2001-06-08 00:21:52 +00002209 }
2210
2211 /*
drh14acc042001-06-10 19:56:58 +00002212 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00002213 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00002214 */
drh14acc042001-06-10 19:56:58 +00002215 nOld = nNew = 0;
2216 sqlitepager_ref(pParent);
2217
2218 /*
2219 ** Find sibling pages to pPage and the Cells in pParent that divide
2220 ** the siblings. An attempt is made to find one sibling on either
2221 ** side of pPage. Both siblings are taken from one side, however, if
2222 ** pPage is either the first or last child of its parent. If pParent
2223 ** has 3 or fewer children then all children of pParent are taken.
2224 */
2225 if( idx==pParent->nCell ){
2226 nxDiv = idx - 2;
drh8b2f49b2001-06-08 00:21:52 +00002227 }else{
drh14acc042001-06-10 19:56:58 +00002228 nxDiv = idx - 1;
drh8b2f49b2001-06-08 00:21:52 +00002229 }
drh14acc042001-06-10 19:56:58 +00002230 if( nxDiv<0 ) nxDiv = 0;
drh8b2f49b2001-06-08 00:21:52 +00002231 nDiv = 0;
drh14acc042001-06-10 19:56:58 +00002232 for(i=0, k=nxDiv; i<3; i++, k++){
2233 if( k<pParent->nCell ){
2234 idxDiv[i] = k;
2235 apDiv[i] = pParent->apCell[k];
drh8b2f49b2001-06-08 00:21:52 +00002236 nDiv++;
drh0d316a42002-08-11 20:10:47 +00002237 pgnoOld[i] = SWAB32(pBt, apDiv[i]->h.leftChild);
drh14acc042001-06-10 19:56:58 +00002238 }else if( k==pParent->nCell ){
drh0d316a42002-08-11 20:10:47 +00002239 pgnoOld[i] = SWAB32(pBt, pParent->u.hdr.rightChild);
drh14acc042001-06-10 19:56:58 +00002240 }else{
2241 break;
drh8b2f49b2001-06-08 00:21:52 +00002242 }
drh8c42ca92001-06-22 19:15:00 +00002243 rc = sqlitepager_get(pBt->pPager, pgnoOld[i], (void**)&apOld[i]);
drh14acc042001-06-10 19:56:58 +00002244 if( rc ) goto balance_cleanup;
drh0d316a42002-08-11 20:10:47 +00002245 rc = initPage(pBt, apOld[i], pgnoOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00002246 if( rc ) goto balance_cleanup;
drh14acc042001-06-10 19:56:58 +00002247 nOld++;
drh8b2f49b2001-06-08 00:21:52 +00002248 }
2249
2250 /*
drh14acc042001-06-10 19:56:58 +00002251 ** Set iCur to be the index in apCell[] of the cell that the cursor
2252 ** is pointing to. We will need this later on in order to keep the
drh5edc3122001-09-13 21:53:09 +00002253 ** cursor pointing at the same cell. If pCur points to a page that
2254 ** has no involvement with this rebalancing, then set iCur to a large
2255 ** number so that the iCur==j tests always fail in the main cell
2256 ** distribution loop below.
drh14acc042001-06-10 19:56:58 +00002257 */
2258 if( pCur ){
drh5edc3122001-09-13 21:53:09 +00002259 iCur = 0;
2260 for(i=0; i<nOld; i++){
2261 if( pCur->pPage==apOld[i] ){
2262 iCur += pCur->idx;
2263 break;
2264 }
2265 iCur += apOld[i]->nCell;
2266 if( i<nOld-1 && pCur->pPage==pParent && pCur->idx==idxDiv[i] ){
2267 break;
2268 }
2269 iCur++;
drh14acc042001-06-10 19:56:58 +00002270 }
drh5edc3122001-09-13 21:53:09 +00002271 pOldCurPage = pCur->pPage;
drh14acc042001-06-10 19:56:58 +00002272 }
2273
2274 /*
2275 ** Make copies of the content of pPage and its siblings into aOld[].
2276 ** The rest of this function will use data from the copies rather
2277 ** that the original pages since the original pages will be in the
2278 ** process of being overwritten.
2279 */
2280 for(i=0; i<nOld; i++){
2281 copyPage(&aOld[i], apOld[i]);
drh14acc042001-06-10 19:56:58 +00002282 }
2283
2284 /*
2285 ** Load pointers to all cells on sibling pages and the divider cells
2286 ** into the local apCell[] array. Make copies of the divider cells
2287 ** into aTemp[] and remove the the divider Cells from pParent.
drh8b2f49b2001-06-08 00:21:52 +00002288 */
2289 nCell = 0;
2290 for(i=0; i<nOld; i++){
drh6b308672002-07-08 02:16:37 +00002291 MemPage *pOld = &aOld[i];
drh8b2f49b2001-06-08 00:21:52 +00002292 for(j=0; j<pOld->nCell; j++){
drh14acc042001-06-10 19:56:58 +00002293 apCell[nCell] = pOld->apCell[j];
drh0d316a42002-08-11 20:10:47 +00002294 szCell[nCell] = cellSize(pBt, apCell[nCell]);
drh14acc042001-06-10 19:56:58 +00002295 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00002296 }
2297 if( i<nOld-1 ){
drh0d316a42002-08-11 20:10:47 +00002298 szCell[nCell] = cellSize(pBt, apDiv[i]);
drh8c42ca92001-06-22 19:15:00 +00002299 memcpy(&aTemp[i], apDiv[i], szCell[nCell]);
drh14acc042001-06-10 19:56:58 +00002300 apCell[nCell] = &aTemp[i];
drh0d316a42002-08-11 20:10:47 +00002301 dropCell(pBt, pParent, nxDiv, szCell[nCell]);
2302 assert( SWAB32(pBt, apCell[nCell]->h.leftChild)==pgnoOld[i] );
drh14acc042001-06-10 19:56:58 +00002303 apCell[nCell]->h.leftChild = pOld->u.hdr.rightChild;
2304 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00002305 }
2306 }
2307
2308 /*
drh6019e162001-07-02 17:51:45 +00002309 ** Figure out the number of pages needed to hold all nCell cells.
2310 ** Store this number in "k". Also compute szNew[] which is the total
2311 ** size of all cells on the i-th page and cntNew[] which is the index
2312 ** in apCell[] of the cell that divides path i from path i+1.
2313 ** cntNew[k] should equal nCell.
2314 **
2315 ** This little patch of code is critical for keeping the tree
2316 ** balanced.
drh8b2f49b2001-06-08 00:21:52 +00002317 */
drh6019e162001-07-02 17:51:45 +00002318 for(subtotal=k=i=0; i<nCell; i++){
2319 subtotal += szCell[i];
2320 if( subtotal > USABLE_SPACE ){
2321 szNew[k] = subtotal - szCell[i];
2322 cntNew[k] = i;
2323 subtotal = 0;
2324 k++;
2325 }
2326 }
2327 szNew[k] = subtotal;
2328 cntNew[k] = nCell;
2329 k++;
2330 for(i=k-1; i>0; i--){
2331 while( szNew[i]<USABLE_SPACE/2 ){
2332 cntNew[i-1]--;
2333 assert( cntNew[i-1]>0 );
2334 szNew[i] += szCell[cntNew[i-1]];
2335 szNew[i-1] -= szCell[cntNew[i-1]-1];
2336 }
2337 }
2338 assert( cntNew[0]>0 );
drh8b2f49b2001-06-08 00:21:52 +00002339
2340 /*
drh6b308672002-07-08 02:16:37 +00002341 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00002342 */
drh14acc042001-06-10 19:56:58 +00002343 for(i=0; i<k; i++){
drh6b308672002-07-08 02:16:37 +00002344 if( i<nOld ){
2345 apNew[i] = apOld[i];
2346 pgnoNew[i] = pgnoOld[i];
2347 apOld[i] = 0;
2348 sqlitepager_write(apNew[i]);
2349 }else{
drhbea00b92002-07-08 10:59:50 +00002350 rc = allocatePage(pBt, &apNew[i], &pgnoNew[i], pgnoNew[i-1]);
drh6b308672002-07-08 02:16:37 +00002351 if( rc ) goto balance_cleanup;
2352 }
drh14acc042001-06-10 19:56:58 +00002353 nNew++;
drh0d316a42002-08-11 20:10:47 +00002354 zeroPage(pBt, apNew[i]);
drh6019e162001-07-02 17:51:45 +00002355 apNew[i]->isInit = 1;
drh8b2f49b2001-06-08 00:21:52 +00002356 }
2357
drh6b308672002-07-08 02:16:37 +00002358 /* Free any old pages that were not reused as new pages.
2359 */
2360 while( i<nOld ){
2361 rc = freePage(pBt, apOld[i], pgnoOld[i]);
2362 if( rc ) goto balance_cleanup;
2363 sqlitepager_unref(apOld[i]);
2364 apOld[i] = 0;
2365 i++;
2366 }
2367
drh8b2f49b2001-06-08 00:21:52 +00002368 /*
drhf9ffac92002-03-02 19:00:31 +00002369 ** Put the new pages in accending order. This helps to
2370 ** keep entries in the disk file in order so that a scan
2371 ** of the table is a linear scan through the file. That
2372 ** in turn helps the operating system to deliver pages
2373 ** from the disk more rapidly.
2374 **
2375 ** An O(n^2) insertion sort algorithm is used, but since
2376 ** n is never more than 3, that should not be a problem.
2377 **
2378 ** This one optimization makes the database about 25%
2379 ** faster for large insertions and deletions.
2380 */
2381 for(i=0; i<k-1; i++){
2382 int minV = pgnoNew[i];
2383 int minI = i;
2384 for(j=i+1; j<k; j++){
2385 if( pgnoNew[j]<minV ){
2386 minI = j;
2387 minV = pgnoNew[j];
2388 }
2389 }
2390 if( minI>i ){
2391 int t;
2392 MemPage *pT;
2393 t = pgnoNew[i];
2394 pT = apNew[i];
2395 pgnoNew[i] = pgnoNew[minI];
2396 apNew[i] = apNew[minI];
2397 pgnoNew[minI] = t;
2398 apNew[minI] = pT;
2399 }
2400 }
2401
2402 /*
drh14acc042001-06-10 19:56:58 +00002403 ** Evenly distribute the data in apCell[] across the new pages.
2404 ** Insert divider cells into pParent as necessary.
2405 */
2406 j = 0;
2407 for(i=0; i<nNew; i++){
2408 MemPage *pNew = apNew[i];
drh6019e162001-07-02 17:51:45 +00002409 while( j<cntNew[i] ){
2410 assert( pNew->nFree>=szCell[j] );
drh14acc042001-06-10 19:56:58 +00002411 if( pCur && iCur==j ){ pCur->pPage = pNew; pCur->idx = pNew->nCell; }
drh0d316a42002-08-11 20:10:47 +00002412 insertCell(pBt, pNew, pNew->nCell, apCell[j], szCell[j]);
drh14acc042001-06-10 19:56:58 +00002413 j++;
2414 }
drh6019e162001-07-02 17:51:45 +00002415 assert( pNew->nCell>0 );
drh14acc042001-06-10 19:56:58 +00002416 assert( !pNew->isOverfull );
drh0d316a42002-08-11 20:10:47 +00002417 relinkCellList(pBt, pNew);
drh14acc042001-06-10 19:56:58 +00002418 if( i<nNew-1 && j<nCell ){
2419 pNew->u.hdr.rightChild = apCell[j]->h.leftChild;
drh0d316a42002-08-11 20:10:47 +00002420 apCell[j]->h.leftChild = SWAB32(pBt, pgnoNew[i]);
drh14acc042001-06-10 19:56:58 +00002421 if( pCur && iCur==j ){ pCur->pPage = pParent; pCur->idx = nxDiv; }
drh0d316a42002-08-11 20:10:47 +00002422 insertCell(pBt, pParent, nxDiv, apCell[j], szCell[j]);
drh14acc042001-06-10 19:56:58 +00002423 j++;
2424 nxDiv++;
2425 }
2426 }
drh6019e162001-07-02 17:51:45 +00002427 assert( j==nCell );
drh6b308672002-07-08 02:16:37 +00002428 apNew[nNew-1]->u.hdr.rightChild = aOld[nOld-1].u.hdr.rightChild;
drh14acc042001-06-10 19:56:58 +00002429 if( nxDiv==pParent->nCell ){
drh0d316a42002-08-11 20:10:47 +00002430 pParent->u.hdr.rightChild = SWAB32(pBt, pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00002431 }else{
drh0d316a42002-08-11 20:10:47 +00002432 pParent->apCell[nxDiv]->h.leftChild = SWAB32(pBt, pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00002433 }
2434 if( pCur ){
drh3fc190c2001-09-14 03:24:23 +00002435 if( j<=iCur && pCur->pPage==pParent && pCur->idx>idxDiv[nOld-1] ){
2436 assert( pCur->pPage==pOldCurPage );
2437 pCur->idx += nNew - nOld;
2438 }else{
2439 assert( pOldCurPage!=0 );
2440 sqlitepager_ref(pCur->pPage);
2441 sqlitepager_unref(pOldCurPage);
2442 }
drh14acc042001-06-10 19:56:58 +00002443 }
2444
2445 /*
2446 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00002447 */
2448 for(i=0; i<nNew; i++){
drh0d316a42002-08-11 20:10:47 +00002449 reparentChildPages(pBt, apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002450 }
drh0d316a42002-08-11 20:10:47 +00002451 reparentChildPages(pBt, pParent);
drh8b2f49b2001-06-08 00:21:52 +00002452
2453 /*
drh14acc042001-06-10 19:56:58 +00002454 ** balance the parent page.
drh8b2f49b2001-06-08 00:21:52 +00002455 */
drh5edc3122001-09-13 21:53:09 +00002456 rc = balance(pBt, pParent, pCur);
drh8b2f49b2001-06-08 00:21:52 +00002457
2458 /*
drh14acc042001-06-10 19:56:58 +00002459 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00002460 */
drh14acc042001-06-10 19:56:58 +00002461balance_cleanup:
drh9ca7d3b2001-06-28 11:50:21 +00002462 if( extraUnref ){
2463 sqlitepager_unref(extraUnref);
2464 }
drh8b2f49b2001-06-08 00:21:52 +00002465 for(i=0; i<nOld; i++){
drh6b308672002-07-08 02:16:37 +00002466 if( apOld[i]!=0 && apOld[i]!=&aOld[i] ) sqlitepager_unref(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00002467 }
drh14acc042001-06-10 19:56:58 +00002468 for(i=0; i<nNew; i++){
2469 sqlitepager_unref(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002470 }
drh14acc042001-06-10 19:56:58 +00002471 if( pCur && pCur->pPage==0 ){
2472 pCur->pPage = pParent;
2473 pCur->idx = 0;
2474 }else{
2475 sqlitepager_unref(pParent);
drh8b2f49b2001-06-08 00:21:52 +00002476 }
2477 return rc;
2478}
2479
2480/*
drhf74b8d92002-09-01 23:20:45 +00002481** This routine checks all cursors that point to the same table
2482** as pCur points to. If any of those cursors were opened with
2483** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
2484** cursors point to the same table were opened with wrFlag==1
2485** then this routine returns SQLITE_OK.
2486**
2487** In addition to checking for read-locks (where a read-lock
2488** means a cursor opened with wrFlag==0) this routine also moves
2489** all cursors other than pCur so that they are pointing to the
2490** first Cell on root page. This is necessary because an insert
2491** or delete might change the number of cells on a page or delete
2492** a page entirely and we do not want to leave any cursors
2493** pointing to non-existant pages or cells.
2494*/
2495static int checkReadLocks(BtCursor *pCur){
2496 BtCursor *p;
2497 assert( pCur->wrFlag );
2498 for(p=pCur->pShared; p!=pCur; p=p->pShared){
2499 assert( p );
2500 assert( p->pgnoRoot==pCur->pgnoRoot );
2501 if( p->wrFlag==0 ) return SQLITE_LOCKED;
2502 if( sqlitepager_pagenumber(p->pPage)!=p->pgnoRoot ){
2503 moveToRoot(p);
2504 }
2505 }
2506 return SQLITE_OK;
2507}
2508
2509/*
drh3b7511c2001-05-26 13:15:44 +00002510** Insert a new record into the BTree. The key is given by (pKey,nKey)
2511** and the data is given by (pData,nData). The cursor is used only to
2512** define what database the record should be inserted into. The cursor
drh14acc042001-06-10 19:56:58 +00002513** is left pointing at the new record.
drh3b7511c2001-05-26 13:15:44 +00002514*/
2515int sqliteBtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00002516 BtCursor *pCur, /* Insert data into the table of this cursor */
drhbe0072d2001-09-13 14:46:09 +00002517 const void *pKey, int nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00002518 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00002519){
2520 Cell newCell;
2521 int rc;
2522 int loc;
drh14acc042001-06-10 19:56:58 +00002523 int szNew;
drh3b7511c2001-05-26 13:15:44 +00002524 MemPage *pPage;
2525 Btree *pBt = pCur->pBt;
2526
drhecdc7532001-09-23 02:35:53 +00002527 if( pCur->pPage==0 ){
2528 return SQLITE_ABORT; /* A rollback destroyed this cursor */
2529 }
drhf74b8d92002-09-01 23:20:45 +00002530 if( !pBt->inTrans || nKey+nData==0 ){
2531 /* Must start a transaction before doing an insert */
2532 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00002533 }
drhf74b8d92002-09-01 23:20:45 +00002534 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00002535 if( !pCur->wrFlag ){
2536 return SQLITE_PERM; /* Cursor not open for writing */
2537 }
drhf74b8d92002-09-01 23:20:45 +00002538 if( checkReadLocks(pCur) ){
2539 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
2540 }
drh14acc042001-06-10 19:56:58 +00002541 rc = sqliteBtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00002542 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002543 pPage = pCur->pPage;
drh7aa128d2002-06-21 13:09:16 +00002544 assert( pPage->isInit );
drh14acc042001-06-10 19:56:58 +00002545 rc = sqlitepager_write(pPage);
drhbd03cae2001-06-02 02:40:57 +00002546 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00002547 rc = fillInCell(pBt, &newCell, pKey, nKey, pData, nData);
2548 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002549 szNew = cellSize(pBt, &newCell);
drh3b7511c2001-05-26 13:15:44 +00002550 if( loc==0 ){
drh14acc042001-06-10 19:56:58 +00002551 newCell.h.leftChild = pPage->apCell[pCur->idx]->h.leftChild;
2552 rc = clearCell(pBt, pPage->apCell[pCur->idx]);
drh5e2f8b92001-05-28 00:41:15 +00002553 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002554 dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pPage->apCell[pCur->idx]));
drh7c717f72001-06-24 20:39:41 +00002555 }else if( loc<0 && pPage->nCell>0 ){
drh14acc042001-06-10 19:56:58 +00002556 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
2557 pCur->idx++;
2558 }else{
2559 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
drh3b7511c2001-05-26 13:15:44 +00002560 }
drh0d316a42002-08-11 20:10:47 +00002561 insertCell(pBt, pPage, pCur->idx, &newCell, szNew);
drh14acc042001-06-10 19:56:58 +00002562 rc = balance(pCur->pBt, pPage, pCur);
drh3fc190c2001-09-14 03:24:23 +00002563 /* sqliteBtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
2564 /* fflush(stdout); */
drh2dcc9aa2002-12-04 13:40:25 +00002565 pCur->eSkip = SKIP_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00002566 return rc;
2567}
2568
2569/*
drhbd03cae2001-06-02 02:40:57 +00002570** Delete the entry that the cursor is pointing to.
drh5e2f8b92001-05-28 00:41:15 +00002571**
drhbd03cae2001-06-02 02:40:57 +00002572** The cursor is left pointing at either the next or the previous
2573** entry. If the cursor is left pointing to the next entry, then
drh2dcc9aa2002-12-04 13:40:25 +00002574** the pCur->eSkip flag is set to SKIP_NEXT which forces the next call to
drhbd03cae2001-06-02 02:40:57 +00002575** sqliteBtreeNext() to be a no-op. That way, you can always call
2576** sqliteBtreeNext() after a delete and the cursor will be left
drh2dcc9aa2002-12-04 13:40:25 +00002577** pointing to the first entry after the deleted entry. Similarly,
2578** pCur->eSkip is set to SKIP_PREV is the cursor is left pointing to
2579** the entry prior to the deleted entry so that a subsequent call to
2580** sqliteBtreePrevious() will always leave the cursor pointing at the
2581** entry immediately before the one that was deleted.
drh3b7511c2001-05-26 13:15:44 +00002582*/
2583int sqliteBtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00002584 MemPage *pPage = pCur->pPage;
2585 Cell *pCell;
2586 int rc;
drh8c42ca92001-06-22 19:15:00 +00002587 Pgno pgnoChild;
drh0d316a42002-08-11 20:10:47 +00002588 Btree *pBt = pCur->pBt;
drh8b2f49b2001-06-08 00:21:52 +00002589
drh7aa128d2002-06-21 13:09:16 +00002590 assert( pPage->isInit );
drhecdc7532001-09-23 02:35:53 +00002591 if( pCur->pPage==0 ){
2592 return SQLITE_ABORT; /* A rollback destroyed this cursor */
2593 }
drhf74b8d92002-09-01 23:20:45 +00002594 if( !pBt->inTrans ){
2595 /* Must start a transaction before doing a delete */
2596 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00002597 }
drhf74b8d92002-09-01 23:20:45 +00002598 assert( !pBt->readOnly );
drhbd03cae2001-06-02 02:40:57 +00002599 if( pCur->idx >= pPage->nCell ){
2600 return SQLITE_ERROR; /* The cursor is not pointing to anything */
2601 }
drhecdc7532001-09-23 02:35:53 +00002602 if( !pCur->wrFlag ){
2603 return SQLITE_PERM; /* Did not open this cursor for writing */
2604 }
drhf74b8d92002-09-01 23:20:45 +00002605 if( checkReadLocks(pCur) ){
2606 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
2607 }
drhbd03cae2001-06-02 02:40:57 +00002608 rc = sqlitepager_write(pPage);
2609 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002610 pCell = pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00002611 pgnoChild = SWAB32(pBt, pCell->h.leftChild);
2612 clearCell(pBt, pCell);
drh14acc042001-06-10 19:56:58 +00002613 if( pgnoChild ){
2614 /*
drh5e00f6c2001-09-13 13:46:56 +00002615 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00002616 ** do something we will leave a hole on an internal page.
2617 ** We have to fill the hole by moving in a cell from a leaf. The
2618 ** next Cell after the one to be deleted is guaranteed to exist and
2619 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00002620 */
drh14acc042001-06-10 19:56:58 +00002621 BtCursor leafCur;
2622 Cell *pNext;
2623 int szNext;
2624 getTempCursor(pCur, &leafCur);
2625 rc = sqliteBtreeNext(&leafCur, 0);
2626 if( rc!=SQLITE_OK ){
2627 return SQLITE_CORRUPT;
drh5e2f8b92001-05-28 00:41:15 +00002628 }
drh6019e162001-07-02 17:51:45 +00002629 rc = sqlitepager_write(leafCur.pPage);
2630 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002631 dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pCell));
drh8c42ca92001-06-22 19:15:00 +00002632 pNext = leafCur.pPage->apCell[leafCur.idx];
drh0d316a42002-08-11 20:10:47 +00002633 szNext = cellSize(pBt, pNext);
2634 pNext->h.leftChild = SWAB32(pBt, pgnoChild);
2635 insertCell(pBt, pPage, pCur->idx, pNext, szNext);
2636 rc = balance(pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002637 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00002638 pCur->eSkip = SKIP_NEXT;
drh0d316a42002-08-11 20:10:47 +00002639 dropCell(pBt, leafCur.pPage, leafCur.idx, szNext);
2640 rc = balance(pBt, leafCur.pPage, pCur);
drh8c42ca92001-06-22 19:15:00 +00002641 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00002642 }else{
drh0d316a42002-08-11 20:10:47 +00002643 dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pCell));
drh5edc3122001-09-13 21:53:09 +00002644 if( pCur->idx>=pPage->nCell ){
2645 pCur->idx = pPage->nCell-1;
drhf5bf0a72001-11-23 00:24:12 +00002646 if( pCur->idx<0 ){
2647 pCur->idx = 0;
drh2dcc9aa2002-12-04 13:40:25 +00002648 pCur->eSkip = SKIP_NEXT;
drhf5bf0a72001-11-23 00:24:12 +00002649 }else{
drh2dcc9aa2002-12-04 13:40:25 +00002650 pCur->eSkip = SKIP_PREV;
drhf5bf0a72001-11-23 00:24:12 +00002651 }
drh6019e162001-07-02 17:51:45 +00002652 }else{
drh2dcc9aa2002-12-04 13:40:25 +00002653 pCur->eSkip = SKIP_NEXT;
drh6019e162001-07-02 17:51:45 +00002654 }
drh0d316a42002-08-11 20:10:47 +00002655 rc = balance(pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002656 }
drh5e2f8b92001-05-28 00:41:15 +00002657 return rc;
drh3b7511c2001-05-26 13:15:44 +00002658}
drh8b2f49b2001-06-08 00:21:52 +00002659
2660/*
drhc6b52df2002-01-04 03:09:29 +00002661** Create a new BTree table. Write into *piTable the page
2662** number for the root page of the new table.
2663**
2664** In the current implementation, BTree tables and BTree indices are the
2665** the same. But in the future, we may change this so that BTree tables
2666** are restricted to having a 4-byte integer key and arbitrary data and
2667** BTree indices are restricted to having an arbitrary key and no data.
drh8b2f49b2001-06-08 00:21:52 +00002668*/
2669int sqliteBtreeCreateTable(Btree *pBt, int *piTable){
2670 MemPage *pRoot;
2671 Pgno pgnoRoot;
2672 int rc;
2673 if( !pBt->inTrans ){
drhf74b8d92002-09-01 23:20:45 +00002674 /* Must start a transaction first */
2675 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00002676 }
drh5df72a52002-06-06 23:16:05 +00002677 if( pBt->readOnly ){
2678 return SQLITE_READONLY;
2679 }
drhbea00b92002-07-08 10:59:50 +00002680 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 0);
drh8b2f49b2001-06-08 00:21:52 +00002681 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002682 assert( sqlitepager_iswriteable(pRoot) );
drh0d316a42002-08-11 20:10:47 +00002683 zeroPage(pBt, pRoot);
drh8b2f49b2001-06-08 00:21:52 +00002684 sqlitepager_unref(pRoot);
2685 *piTable = (int)pgnoRoot;
2686 return SQLITE_OK;
2687}
2688
2689/*
drhc6b52df2002-01-04 03:09:29 +00002690** Create a new BTree index. Write into *piTable the page
2691** number for the root page of the new index.
2692**
2693** In the current implementation, BTree tables and BTree indices are the
2694** the same. But in the future, we may change this so that BTree tables
2695** are restricted to having a 4-byte integer key and arbitrary data and
2696** BTree indices are restricted to having an arbitrary key and no data.
2697*/
2698int sqliteBtreeCreateIndex(Btree *pBt, int *piIndex){
drh5df72a52002-06-06 23:16:05 +00002699 return sqliteBtreeCreateTable(pBt, piIndex);
drhc6b52df2002-01-04 03:09:29 +00002700}
2701
2702/*
drh8b2f49b2001-06-08 00:21:52 +00002703** Erase the given database page and all its children. Return
2704** the page to the freelist.
2705*/
drh2aa679f2001-06-25 02:11:07 +00002706static int clearDatabasePage(Btree *pBt, Pgno pgno, int freePageFlag){
drh8b2f49b2001-06-08 00:21:52 +00002707 MemPage *pPage;
2708 int rc;
drh8b2f49b2001-06-08 00:21:52 +00002709 Cell *pCell;
2710 int idx;
2711
drh8c42ca92001-06-22 19:15:00 +00002712 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pPage);
drh8b2f49b2001-06-08 00:21:52 +00002713 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002714 rc = sqlitepager_write(pPage);
2715 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002716 rc = initPage(pBt, pPage, pgno, 0);
drh7aa128d2002-06-21 13:09:16 +00002717 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002718 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh8b2f49b2001-06-08 00:21:52 +00002719 while( idx>0 ){
drh14acc042001-06-10 19:56:58 +00002720 pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +00002721 idx = SWAB16(pBt, pCell->h.iNext);
drh8b2f49b2001-06-08 00:21:52 +00002722 if( pCell->h.leftChild ){
drh0d316a42002-08-11 20:10:47 +00002723 rc = clearDatabasePage(pBt, SWAB32(pBt, pCell->h.leftChild), 1);
drh8b2f49b2001-06-08 00:21:52 +00002724 if( rc ) return rc;
2725 }
drh8c42ca92001-06-22 19:15:00 +00002726 rc = clearCell(pBt, pCell);
drh8b2f49b2001-06-08 00:21:52 +00002727 if( rc ) return rc;
2728 }
drh2aa679f2001-06-25 02:11:07 +00002729 if( pPage->u.hdr.rightChild ){
drh0d316a42002-08-11 20:10:47 +00002730 rc = clearDatabasePage(pBt, SWAB32(pBt, pPage->u.hdr.rightChild), 1);
drh2aa679f2001-06-25 02:11:07 +00002731 if( rc ) return rc;
2732 }
2733 if( freePageFlag ){
2734 rc = freePage(pBt, pPage, pgno);
2735 }else{
drh0d316a42002-08-11 20:10:47 +00002736 zeroPage(pBt, pPage);
drh2aa679f2001-06-25 02:11:07 +00002737 }
drhdd793422001-06-28 01:54:48 +00002738 sqlitepager_unref(pPage);
drh2aa679f2001-06-25 02:11:07 +00002739 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002740}
2741
2742/*
2743** Delete all information from a single table in the database.
2744*/
2745int sqliteBtreeClearTable(Btree *pBt, int iTable){
2746 int rc;
drhf74b8d92002-09-01 23:20:45 +00002747 BtCursor *pCur;
drh8b2f49b2001-06-08 00:21:52 +00002748 if( !pBt->inTrans ){
drhf74b8d92002-09-01 23:20:45 +00002749 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00002750 }
drhf74b8d92002-09-01 23:20:45 +00002751 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
2752 if( pCur->pgnoRoot==(Pgno)iTable ){
2753 if( pCur->wrFlag==0 ) return SQLITE_LOCKED;
2754 moveToRoot(pCur);
2755 }
drhecdc7532001-09-23 02:35:53 +00002756 }
drh2aa679f2001-06-25 02:11:07 +00002757 rc = clearDatabasePage(pBt, (Pgno)iTable, 0);
drh8b2f49b2001-06-08 00:21:52 +00002758 if( rc ){
2759 sqliteBtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00002760 }
drh8c42ca92001-06-22 19:15:00 +00002761 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002762}
2763
2764/*
2765** Erase all information in a table and add the root of the table to
2766** the freelist. Except, the root of the principle table (the one on
2767** page 2) is never added to the freelist.
2768*/
2769int sqliteBtreeDropTable(Btree *pBt, int iTable){
2770 int rc;
2771 MemPage *pPage;
drhf74b8d92002-09-01 23:20:45 +00002772 BtCursor *pCur;
drh8b2f49b2001-06-08 00:21:52 +00002773 if( !pBt->inTrans ){
drhf74b8d92002-09-01 23:20:45 +00002774 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00002775 }
drhf74b8d92002-09-01 23:20:45 +00002776 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
2777 if( pCur->pgnoRoot==(Pgno)iTable ){
2778 return SQLITE_LOCKED; /* Cannot drop a table that has a cursor */
2779 }
drh5df72a52002-06-06 23:16:05 +00002780 }
drh8c42ca92001-06-22 19:15:00 +00002781 rc = sqlitepager_get(pBt->pPager, (Pgno)iTable, (void**)&pPage);
drh2aa679f2001-06-25 02:11:07 +00002782 if( rc ) return rc;
2783 rc = sqliteBtreeClearTable(pBt, iTable);
2784 if( rc ) return rc;
2785 if( iTable>2 ){
2786 rc = freePage(pBt, pPage, iTable);
2787 }else{
drh0d316a42002-08-11 20:10:47 +00002788 zeroPage(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002789 }
drhdd793422001-06-28 01:54:48 +00002790 sqlitepager_unref(pPage);
drh8b2f49b2001-06-08 00:21:52 +00002791 return rc;
2792}
2793
2794/*
2795** Read the meta-information out of a database file.
2796*/
2797int sqliteBtreeGetMeta(Btree *pBt, int *aMeta){
2798 PageOne *pP1;
2799 int rc;
drh0d316a42002-08-11 20:10:47 +00002800 int i;
drh8b2f49b2001-06-08 00:21:52 +00002801
drh8c42ca92001-06-22 19:15:00 +00002802 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00002803 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002804 aMeta[0] = SWAB32(pBt, pP1->nFree);
2805 for(i=0; i<sizeof(pP1->aMeta)/sizeof(pP1->aMeta[0]); i++){
2806 aMeta[i+1] = SWAB32(pBt, pP1->aMeta[i]);
2807 }
drh8b2f49b2001-06-08 00:21:52 +00002808 sqlitepager_unref(pP1);
2809 return SQLITE_OK;
2810}
2811
2812/*
2813** Write meta-information back into the database.
2814*/
2815int sqliteBtreeUpdateMeta(Btree *pBt, int *aMeta){
2816 PageOne *pP1;
drh0d316a42002-08-11 20:10:47 +00002817 int rc, i;
drh8b2f49b2001-06-08 00:21:52 +00002818 if( !pBt->inTrans ){
drhf74b8d92002-09-01 23:20:45 +00002819 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +00002820 }
drh8b2f49b2001-06-08 00:21:52 +00002821 pP1 = pBt->page1;
2822 rc = sqlitepager_write(pP1);
drh9adf9ac2002-05-15 11:44:13 +00002823 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002824 for(i=0; i<sizeof(pP1->aMeta)/sizeof(pP1->aMeta[0]); i++){
2825 pP1->aMeta[i] = SWAB32(pBt, aMeta[i+1]);
2826 }
drh8b2f49b2001-06-08 00:21:52 +00002827 return SQLITE_OK;
2828}
drh8c42ca92001-06-22 19:15:00 +00002829
drh5eddca62001-06-30 21:53:53 +00002830/******************************************************************************
2831** The complete implementation of the BTree subsystem is above this line.
2832** All the code the follows is for testing and troubleshooting the BTree
2833** subsystem. None of the code that follows is used during normal operation.
drh5eddca62001-06-30 21:53:53 +00002834******************************************************************************/
drh5eddca62001-06-30 21:53:53 +00002835
drh8c42ca92001-06-22 19:15:00 +00002836/*
2837** Print a disassembly of the given page on standard output. This routine
2838** is used for debugging and testing only.
2839*/
drhaaab5722002-02-19 13:39:21 +00002840#ifdef SQLITE_TEST
drh6019e162001-07-02 17:51:45 +00002841int sqliteBtreePageDump(Btree *pBt, int pgno, int recursive){
drh8c42ca92001-06-22 19:15:00 +00002842 int rc;
2843 MemPage *pPage;
2844 int i, j;
2845 int nFree;
2846 u16 idx;
2847 char range[20];
2848 unsigned char payload[20];
2849 rc = sqlitepager_get(pBt->pPager, (Pgno)pgno, (void**)&pPage);
2850 if( rc ){
2851 return rc;
2852 }
drh6019e162001-07-02 17:51:45 +00002853 if( recursive ) printf("PAGE %d:\n", pgno);
drh8c42ca92001-06-22 19:15:00 +00002854 i = 0;
drh0d316a42002-08-11 20:10:47 +00002855 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh8c42ca92001-06-22 19:15:00 +00002856 while( idx>0 && idx<=SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2857 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +00002858 int sz = cellSize(pBt, pCell);
drh8c42ca92001-06-22 19:15:00 +00002859 sprintf(range,"%d..%d", idx, idx+sz-1);
drh0d316a42002-08-11 20:10:47 +00002860 sz = NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h);
drh8c42ca92001-06-22 19:15:00 +00002861 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
2862 memcpy(payload, pCell->aPayload, sz);
2863 for(j=0; j<sz; j++){
2864 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
2865 }
2866 payload[sz] = 0;
2867 printf(
drh6019e162001-07-02 17:51:45 +00002868 "cell %2d: i=%-10s chld=%-4d nk=%-4d nd=%-4d payload=%s\n",
drh0d316a42002-08-11 20:10:47 +00002869 i, range, (int)pCell->h.leftChild,
2870 NKEY(pBt, pCell->h), NDATA(pBt, pCell->h),
drh2aa679f2001-06-25 02:11:07 +00002871 payload
drh8c42ca92001-06-22 19:15:00 +00002872 );
drh6019e162001-07-02 17:51:45 +00002873 if( pPage->isInit && pPage->apCell[i]!=pCell ){
drh2aa679f2001-06-25 02:11:07 +00002874 printf("**** apCell[%d] does not match on prior entry ****\n", i);
2875 }
drh7c717f72001-06-24 20:39:41 +00002876 i++;
drh0d316a42002-08-11 20:10:47 +00002877 idx = SWAB16(pBt, pCell->h.iNext);
drh8c42ca92001-06-22 19:15:00 +00002878 }
2879 if( idx!=0 ){
2880 printf("ERROR: next cell index out of range: %d\n", idx);
2881 }
drh0d316a42002-08-11 20:10:47 +00002882 printf("right_child: %d\n", SWAB32(pBt, pPage->u.hdr.rightChild));
drh8c42ca92001-06-22 19:15:00 +00002883 nFree = 0;
2884 i = 0;
drh0d316a42002-08-11 20:10:47 +00002885 idx = SWAB16(pBt, pPage->u.hdr.firstFree);
drh8c42ca92001-06-22 19:15:00 +00002886 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2887 FreeBlk *p = (FreeBlk*)&pPage->u.aDisk[idx];
2888 sprintf(range,"%d..%d", idx, idx+p->iSize-1);
drh0d316a42002-08-11 20:10:47 +00002889 nFree += SWAB16(pBt, p->iSize);
drh8c42ca92001-06-22 19:15:00 +00002890 printf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
drh0d316a42002-08-11 20:10:47 +00002891 i, range, SWAB16(pBt, p->iSize), nFree);
2892 idx = SWAB16(pBt, p->iNext);
drh2aa679f2001-06-25 02:11:07 +00002893 i++;
drh8c42ca92001-06-22 19:15:00 +00002894 }
2895 if( idx!=0 ){
2896 printf("ERROR: next freeblock index out of range: %d\n", idx);
2897 }
drh6019e162001-07-02 17:51:45 +00002898 if( recursive && pPage->u.hdr.rightChild!=0 ){
drh0d316a42002-08-11 20:10:47 +00002899 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh6019e162001-07-02 17:51:45 +00002900 while( idx>0 && idx<SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2901 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +00002902 sqliteBtreePageDump(pBt, SWAB32(pBt, pCell->h.leftChild), 1);
2903 idx = SWAB16(pBt, pCell->h.iNext);
drh6019e162001-07-02 17:51:45 +00002904 }
drh0d316a42002-08-11 20:10:47 +00002905 sqliteBtreePageDump(pBt, SWAB32(pBt, pPage->u.hdr.rightChild), 1);
drh6019e162001-07-02 17:51:45 +00002906 }
drh8c42ca92001-06-22 19:15:00 +00002907 sqlitepager_unref(pPage);
2908 return SQLITE_OK;
2909}
drhaaab5722002-02-19 13:39:21 +00002910#endif
drh8c42ca92001-06-22 19:15:00 +00002911
drhaaab5722002-02-19 13:39:21 +00002912#ifdef SQLITE_TEST
drh8c42ca92001-06-22 19:15:00 +00002913/*
drh2aa679f2001-06-25 02:11:07 +00002914** Fill aResult[] with information about the entry and page that the
2915** cursor is pointing to.
2916**
2917** aResult[0] = The page number
2918** aResult[1] = The entry number
2919** aResult[2] = Total number of entries on this page
2920** aResult[3] = Size of this entry
2921** aResult[4] = Number of free bytes on this page
2922** aResult[5] = Number of free blocks on the page
2923** aResult[6] = Page number of the left child of this entry
2924** aResult[7] = Page number of the right child for the whole page
drh5eddca62001-06-30 21:53:53 +00002925**
2926** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00002927*/
2928int sqliteBtreeCursorDump(BtCursor *pCur, int *aResult){
drh2aa679f2001-06-25 02:11:07 +00002929 int cnt, idx;
2930 MemPage *pPage = pCur->pPage;
drh0d316a42002-08-11 20:10:47 +00002931 Btree *pBt = pCur->pBt;
drh2aa679f2001-06-25 02:11:07 +00002932 aResult[0] = sqlitepager_pagenumber(pPage);
drh8c42ca92001-06-22 19:15:00 +00002933 aResult[1] = pCur->idx;
drh2aa679f2001-06-25 02:11:07 +00002934 aResult[2] = pPage->nCell;
2935 if( pCur->idx>=0 && pCur->idx<pPage->nCell ){
drh0d316a42002-08-11 20:10:47 +00002936 aResult[3] = cellSize(pBt, pPage->apCell[pCur->idx]);
2937 aResult[6] = SWAB32(pBt, pPage->apCell[pCur->idx]->h.leftChild);
drh2aa679f2001-06-25 02:11:07 +00002938 }else{
2939 aResult[3] = 0;
2940 aResult[6] = 0;
2941 }
2942 aResult[4] = pPage->nFree;
2943 cnt = 0;
drh0d316a42002-08-11 20:10:47 +00002944 idx = SWAB16(pBt, pPage->u.hdr.firstFree);
drh2aa679f2001-06-25 02:11:07 +00002945 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2946 cnt++;
drh0d316a42002-08-11 20:10:47 +00002947 idx = SWAB16(pBt, ((FreeBlk*)&pPage->u.aDisk[idx])->iNext);
drh2aa679f2001-06-25 02:11:07 +00002948 }
2949 aResult[5] = cnt;
drh0d316a42002-08-11 20:10:47 +00002950 aResult[7] = SWAB32(pBt, pPage->u.hdr.rightChild);
drh8c42ca92001-06-22 19:15:00 +00002951 return SQLITE_OK;
2952}
drhaaab5722002-02-19 13:39:21 +00002953#endif
drhdd793422001-06-28 01:54:48 +00002954
drhaaab5722002-02-19 13:39:21 +00002955#ifdef SQLITE_TEST
drhdd793422001-06-28 01:54:48 +00002956/*
drh5eddca62001-06-30 21:53:53 +00002957** Return the pager associated with a BTree. This routine is used for
2958** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00002959*/
2960Pager *sqliteBtreePager(Btree *pBt){
2961 return pBt->pPager;
2962}
drhaaab5722002-02-19 13:39:21 +00002963#endif
drh5eddca62001-06-30 21:53:53 +00002964
2965/*
2966** This structure is passed around through all the sanity checking routines
2967** in order to keep track of some global state information.
2968*/
drhaaab5722002-02-19 13:39:21 +00002969typedef struct IntegrityCk IntegrityCk;
2970struct IntegrityCk {
drh100569d2001-10-02 13:01:48 +00002971 Btree *pBt; /* The tree being checked out */
2972 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
2973 int nPage; /* Number of pages in the database */
2974 int *anRef; /* Number of times each page is referenced */
2975 int nTreePage; /* Number of BTree pages */
2976 int nByte; /* Number of bytes of data stored on BTree pages */
2977 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00002978};
2979
2980/*
2981** Append a message to the error message string.
2982*/
drhaaab5722002-02-19 13:39:21 +00002983static void checkAppendMsg(IntegrityCk *pCheck, char *zMsg1, char *zMsg2){
drh5eddca62001-06-30 21:53:53 +00002984 if( pCheck->zErrMsg ){
2985 char *zOld = pCheck->zErrMsg;
2986 pCheck->zErrMsg = 0;
2987 sqliteSetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, 0);
2988 sqliteFree(zOld);
2989 }else{
2990 sqliteSetString(&pCheck->zErrMsg, zMsg1, zMsg2, 0);
2991 }
2992}
2993
2994/*
2995** Add 1 to the reference count for page iPage. If this is the second
2996** reference to the page, add an error message to pCheck->zErrMsg.
2997** Return 1 if there are 2 ore more references to the page and 0 if
2998** if this is the first reference to the page.
2999**
3000** Also check that the page number is in bounds.
3001*/
drhaaab5722002-02-19 13:39:21 +00003002static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00003003 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00003004 if( iPage>pCheck->nPage || iPage<0 ){
drh5eddca62001-06-30 21:53:53 +00003005 char zBuf[100];
3006 sprintf(zBuf, "invalid page number %d", iPage);
3007 checkAppendMsg(pCheck, zContext, zBuf);
3008 return 1;
3009 }
3010 if( pCheck->anRef[iPage]==1 ){
3011 char zBuf[100];
3012 sprintf(zBuf, "2nd reference to page %d", iPage);
3013 checkAppendMsg(pCheck, zContext, zBuf);
3014 return 1;
3015 }
3016 return (pCheck->anRef[iPage]++)>1;
3017}
3018
3019/*
3020** Check the integrity of the freelist or of an overflow page list.
3021** Verify that the number of pages on the list is N.
3022*/
drh30e58752002-03-02 20:41:57 +00003023static void checkList(
3024 IntegrityCk *pCheck, /* Integrity checking context */
3025 int isFreeList, /* True for a freelist. False for overflow page list */
3026 int iPage, /* Page number for first page in the list */
3027 int N, /* Expected number of pages in the list */
3028 char *zContext /* Context for error messages */
3029){
3030 int i;
drh5eddca62001-06-30 21:53:53 +00003031 char zMsg[100];
drh30e58752002-03-02 20:41:57 +00003032 while( N-- > 0 ){
drh5eddca62001-06-30 21:53:53 +00003033 OverflowPage *pOvfl;
3034 if( iPage<1 ){
3035 sprintf(zMsg, "%d pages missing from overflow list", N+1);
3036 checkAppendMsg(pCheck, zContext, zMsg);
3037 break;
3038 }
3039 if( checkRef(pCheck, iPage, zContext) ) break;
3040 if( sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
3041 sprintf(zMsg, "failed to get page %d", iPage);
3042 checkAppendMsg(pCheck, zContext, zMsg);
3043 break;
3044 }
drh30e58752002-03-02 20:41:57 +00003045 if( isFreeList ){
3046 FreelistInfo *pInfo = (FreelistInfo*)pOvfl->aPayload;
drh0d316a42002-08-11 20:10:47 +00003047 int n = SWAB32(pCheck->pBt, pInfo->nFree);
3048 for(i=0; i<n; i++){
3049 checkRef(pCheck, SWAB32(pCheck->pBt, pInfo->aFree[i]), zMsg);
drh30e58752002-03-02 20:41:57 +00003050 }
drh0d316a42002-08-11 20:10:47 +00003051 N -= n;
drh30e58752002-03-02 20:41:57 +00003052 }
drh0d316a42002-08-11 20:10:47 +00003053 iPage = SWAB32(pCheck->pBt, pOvfl->iNext);
drh5eddca62001-06-30 21:53:53 +00003054 sqlitepager_unref(pOvfl);
3055 }
3056}
3057
3058/*
drh1bffb9c2002-02-03 17:37:36 +00003059** Return negative if zKey1<zKey2.
3060** Return zero if zKey1==zKey2.
3061** Return positive if zKey1>zKey2.
3062*/
3063static int keyCompare(
3064 const char *zKey1, int nKey1,
3065 const char *zKey2, int nKey2
3066){
3067 int min = nKey1>nKey2 ? nKey2 : nKey1;
3068 int c = memcmp(zKey1, zKey2, min);
3069 if( c==0 ){
3070 c = nKey1 - nKey2;
3071 }
3072 return c;
3073}
3074
3075/*
drh5eddca62001-06-30 21:53:53 +00003076** Do various sanity checks on a single page of a tree. Return
3077** the tree depth. Root pages return 0. Parents of root pages
3078** return 1, and so forth.
3079**
3080** These checks are done:
3081**
3082** 1. Make sure that cells and freeblocks do not overlap
3083** but combine to completely cover the page.
3084** 2. Make sure cell keys are in order.
3085** 3. Make sure no key is less than or equal to zLowerBound.
3086** 4. Make sure no key is greater than or equal to zUpperBound.
3087** 5. Check the integrity of overflow pages.
3088** 6. Recursively call checkTreePage on all children.
3089** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00003090** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00003091** the root of the tree.
3092*/
3093static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00003094 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00003095 int iPage, /* Page number of the page to check */
3096 MemPage *pParent, /* Parent page */
3097 char *zParentContext, /* Parent context */
3098 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00003099 int nLower, /* Number of characters in zLowerBound */
3100 char *zUpperBound, /* All keys should be less than this, if not NULL */
3101 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00003102){
3103 MemPage *pPage;
3104 int i, rc, depth, d2, pgno;
3105 char *zKey1, *zKey2;
drh1bffb9c2002-02-03 17:37:36 +00003106 int nKey1, nKey2;
drh5eddca62001-06-30 21:53:53 +00003107 BtCursor cur;
drh0d316a42002-08-11 20:10:47 +00003108 Btree *pBt;
drh5eddca62001-06-30 21:53:53 +00003109 char zMsg[100];
3110 char zContext[100];
3111 char hit[SQLITE_PAGE_SIZE];
3112
3113 /* Check that the page exists
3114 */
drh0d316a42002-08-11 20:10:47 +00003115 cur.pBt = pBt = pCheck->pBt;
drh5eddca62001-06-30 21:53:53 +00003116 if( iPage==0 ) return 0;
3117 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
3118 sprintf(zContext, "On tree page %d: ", iPage);
3119 if( (rc = sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pPage))!=0 ){
3120 sprintf(zMsg, "unable to get the page. error code=%d", rc);
3121 checkAppendMsg(pCheck, zContext, zMsg);
3122 return 0;
3123 }
drh0d316a42002-08-11 20:10:47 +00003124 if( (rc = initPage(pBt, pPage, (Pgno)iPage, pParent))!=0 ){
drh5eddca62001-06-30 21:53:53 +00003125 sprintf(zMsg, "initPage() returns error code %d", rc);
3126 checkAppendMsg(pCheck, zContext, zMsg);
3127 sqlitepager_unref(pPage);
3128 return 0;
3129 }
3130
3131 /* Check out all the cells.
3132 */
3133 depth = 0;
drh1bffb9c2002-02-03 17:37:36 +00003134 if( zLowerBound ){
3135 zKey1 = sqliteMalloc( nLower+1 );
3136 memcpy(zKey1, zLowerBound, nLower);
3137 zKey1[nLower] = 0;
3138 }else{
3139 zKey1 = 0;
3140 }
3141 nKey1 = nLower;
drh5eddca62001-06-30 21:53:53 +00003142 cur.pPage = pPage;
drh5eddca62001-06-30 21:53:53 +00003143 for(i=0; i<pPage->nCell; i++){
3144 Cell *pCell = pPage->apCell[i];
3145 int sz;
3146
3147 /* Check payload overflow pages
3148 */
drh0d316a42002-08-11 20:10:47 +00003149 nKey2 = NKEY(pBt, pCell->h);
3150 sz = nKey2 + NDATA(pBt, pCell->h);
drh5eddca62001-06-30 21:53:53 +00003151 sprintf(zContext, "On page %d cell %d: ", iPage, i);
3152 if( sz>MX_LOCAL_PAYLOAD ){
3153 int nPage = (sz - MX_LOCAL_PAYLOAD + OVERFLOW_SIZE - 1)/OVERFLOW_SIZE;
drh0d316a42002-08-11 20:10:47 +00003154 checkList(pCheck, 0, SWAB32(pBt, pCell->ovfl), nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00003155 }
3156
3157 /* Check that keys are in the right order
3158 */
3159 cur.idx = i;
drh1bffb9c2002-02-03 17:37:36 +00003160 zKey2 = sqliteMalloc( nKey2+1 );
3161 getPayload(&cur, 0, nKey2, zKey2);
3162 if( zKey1 && keyCompare(zKey1, nKey1, zKey2, nKey2)>=0 ){
drh5eddca62001-06-30 21:53:53 +00003163 checkAppendMsg(pCheck, zContext, "Key is out of order");
3164 }
3165
3166 /* Check sanity of left child page.
3167 */
drh0d316a42002-08-11 20:10:47 +00003168 pgno = SWAB32(pBt, pCell->h.leftChild);
drh1bffb9c2002-02-03 17:37:36 +00003169 d2 = checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zKey2,nKey2);
drh5eddca62001-06-30 21:53:53 +00003170 if( i>0 && d2!=depth ){
3171 checkAppendMsg(pCheck, zContext, "Child page depth differs");
3172 }
3173 depth = d2;
3174 sqliteFree(zKey1);
3175 zKey1 = zKey2;
drh1bffb9c2002-02-03 17:37:36 +00003176 nKey1 = nKey2;
drh5eddca62001-06-30 21:53:53 +00003177 }
drh0d316a42002-08-11 20:10:47 +00003178 pgno = SWAB32(pBt, pPage->u.hdr.rightChild);
drh5eddca62001-06-30 21:53:53 +00003179 sprintf(zContext, "On page %d at right child: ", iPage);
drh1bffb9c2002-02-03 17:37:36 +00003180 checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zUpperBound,nUpper);
drh5eddca62001-06-30 21:53:53 +00003181 sqliteFree(zKey1);
3182
3183 /* Check for complete coverage of the page
3184 */
3185 memset(hit, 0, sizeof(hit));
3186 memset(hit, 1, sizeof(PageHdr));
drh0d316a42002-08-11 20:10:47 +00003187 for(i=SWAB16(pBt, pPage->u.hdr.firstCell); i>0 && i<SQLITE_PAGE_SIZE; ){
drh5eddca62001-06-30 21:53:53 +00003188 Cell *pCell = (Cell*)&pPage->u.aDisk[i];
3189 int j;
drh0d316a42002-08-11 20:10:47 +00003190 for(j=i+cellSize(pBt, pCell)-1; j>=i; j--) hit[j]++;
3191 i = SWAB16(pBt, pCell->h.iNext);
drh5eddca62001-06-30 21:53:53 +00003192 }
drh0d316a42002-08-11 20:10:47 +00003193 for(i=SWAB16(pBt,pPage->u.hdr.firstFree); i>0 && i<SQLITE_PAGE_SIZE; ){
drh5eddca62001-06-30 21:53:53 +00003194 FreeBlk *pFBlk = (FreeBlk*)&pPage->u.aDisk[i];
3195 int j;
drh0d316a42002-08-11 20:10:47 +00003196 for(j=i+SWAB16(pBt,pFBlk->iSize)-1; j>=i; j--) hit[j]++;
3197 i = SWAB16(pBt,pFBlk->iNext);
drh5eddca62001-06-30 21:53:53 +00003198 }
3199 for(i=0; i<SQLITE_PAGE_SIZE; i++){
3200 if( hit[i]==0 ){
3201 sprintf(zMsg, "Unused space at byte %d of page %d", i, iPage);
3202 checkAppendMsg(pCheck, zMsg, 0);
3203 break;
3204 }else if( hit[i]>1 ){
3205 sprintf(zMsg, "Multiple uses for byte %d of page %d", i, iPage);
3206 checkAppendMsg(pCheck, zMsg, 0);
3207 break;
3208 }
3209 }
3210
3211 /* Check that free space is kept to a minimum
3212 */
drh6019e162001-07-02 17:51:45 +00003213#if 0
3214 if( pParent && pParent->nCell>2 && pPage->nFree>3*SQLITE_PAGE_SIZE/4 ){
drh5eddca62001-06-30 21:53:53 +00003215 sprintf(zMsg, "free space (%d) greater than max (%d)", pPage->nFree,
3216 SQLITE_PAGE_SIZE/3);
3217 checkAppendMsg(pCheck, zContext, zMsg);
3218 }
drh6019e162001-07-02 17:51:45 +00003219#endif
3220
3221 /* Update freespace totals.
3222 */
3223 pCheck->nTreePage++;
3224 pCheck->nByte += USABLE_SPACE - pPage->nFree;
drh5eddca62001-06-30 21:53:53 +00003225
3226 sqlitepager_unref(pPage);
3227 return depth;
3228}
3229
3230/*
3231** This routine does a complete check of the given BTree file. aRoot[] is
3232** an array of pages numbers were each page number is the root page of
3233** a table. nRoot is the number of entries in aRoot.
3234**
3235** If everything checks out, this routine returns NULL. If something is
3236** amiss, an error message is written into memory obtained from malloc()
3237** and a pointer to that error message is returned. The calling function
3238** is responsible for freeing the error message when it is done.
3239*/
drhaaab5722002-02-19 13:39:21 +00003240char *sqliteBtreeIntegrityCheck(Btree *pBt, int *aRoot, int nRoot){
drh5eddca62001-06-30 21:53:53 +00003241 int i;
3242 int nRef;
drhaaab5722002-02-19 13:39:21 +00003243 IntegrityCk sCheck;
drh5eddca62001-06-30 21:53:53 +00003244
3245 nRef = *sqlitepager_stats(pBt->pPager);
drhefc251d2001-07-01 22:12:01 +00003246 if( lockBtree(pBt)!=SQLITE_OK ){
3247 return sqliteStrDup("Unable to acquire a read lock on the database");
3248 }
drh5eddca62001-06-30 21:53:53 +00003249 sCheck.pBt = pBt;
3250 sCheck.pPager = pBt->pPager;
3251 sCheck.nPage = sqlitepager_pagecount(sCheck.pPager);
drh0de8c112002-07-06 16:32:14 +00003252 if( sCheck.nPage==0 ){
3253 unlockBtreeIfUnused(pBt);
3254 return 0;
3255 }
drh5eddca62001-06-30 21:53:53 +00003256 sCheck.anRef = sqliteMalloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
3257 sCheck.anRef[1] = 1;
3258 for(i=2; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
3259 sCheck.zErrMsg = 0;
3260
3261 /* Check the integrity of the freelist
3262 */
drh0d316a42002-08-11 20:10:47 +00003263 checkList(&sCheck, 1, SWAB32(pBt, pBt->page1->freeList),
3264 SWAB32(pBt, pBt->page1->nFree), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00003265
3266 /* Check all the tables.
3267 */
3268 for(i=0; i<nRoot; i++){
drh4ff6dfa2002-03-03 23:06:00 +00003269 if( aRoot[i]==0 ) continue;
drh1bffb9c2002-02-03 17:37:36 +00003270 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00003271 }
3272
3273 /* Make sure every page in the file is referenced
3274 */
3275 for(i=1; i<=sCheck.nPage; i++){
3276 if( sCheck.anRef[i]==0 ){
3277 char zBuf[100];
3278 sprintf(zBuf, "Page %d is never used", i);
3279 checkAppendMsg(&sCheck, zBuf, 0);
3280 }
3281 }
3282
3283 /* Make sure this analysis did not leave any unref() pages
3284 */
drh5e00f6c2001-09-13 13:46:56 +00003285 unlockBtreeIfUnused(pBt);
drh5eddca62001-06-30 21:53:53 +00003286 if( nRef != *sqlitepager_stats(pBt->pPager) ){
3287 char zBuf[100];
3288 sprintf(zBuf,
3289 "Outstanding page count goes from %d to %d during this analysis",
3290 nRef, *sqlitepager_stats(pBt->pPager)
3291 );
3292 checkAppendMsg(&sCheck, zBuf, 0);
3293 }
3294
3295 /* Clean up and report errors.
3296 */
3297 sqliteFree(sCheck.anRef);
3298 return sCheck.zErrMsg;
3299}