blob: 909ead07d2189964418dc0a87e97319dd7657ea0 [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*************************************************************************
drhecdc7532001-09-23 02:35:53 +000012** $Id: btree.c,v 1.30 2001/09/23 02:35:53 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
drh2af926b2001-05-15 00:39:25 +000057
drh2af926b2001-05-15 00:39:25 +000058/*
59** Primitive data types. u32 must be 4 bytes and u16 must be 2 bytes.
drh14acc042001-06-10 19:56:58 +000060** The uptr type must be big enough to hold a pointer.
drh306dc212001-05-21 13:45:10 +000061** Change these typedefs when porting to new architectures.
drh2af926b2001-05-15 00:39:25 +000062*/
drh14acc042001-06-10 19:56:58 +000063typedef unsigned int uptr;
drh092d0352001-09-15 13:15:12 +000064
drhb19a2bc2001-09-16 00:13:26 +000065/* There are already defined in sqliteInt.h...
drh092d0352001-09-15 13:15:12 +000066** typedef unsigned int u32;
67** typedef unsigned short int u16;
68** typedef unsigned char u8;
69*/
drh365d68f2001-05-11 11:02:46 +000070
71/*
drh8c42ca92001-06-22 19:15:00 +000072** This macro casts a pointer to an integer. Useful for doing
73** pointer arithmetic.
74*/
drh7c717f72001-06-24 20:39:41 +000075#define Addr(X) ((uptr)X)
drh8c42ca92001-06-22 19:15:00 +000076
77/*
drh365d68f2001-05-11 11:02:46 +000078** Forward declarations of structures used only in this file.
79*/
drhbd03cae2001-06-02 02:40:57 +000080typedef struct PageOne PageOne;
drh2af926b2001-05-15 00:39:25 +000081typedef struct MemPage MemPage;
drh365d68f2001-05-11 11:02:46 +000082typedef struct PageHdr PageHdr;
83typedef struct Cell Cell;
drh3b7511c2001-05-26 13:15:44 +000084typedef struct CellHdr CellHdr;
drh365d68f2001-05-11 11:02:46 +000085typedef struct FreeBlk FreeBlk;
drh2af926b2001-05-15 00:39:25 +000086typedef struct OverflowPage OverflowPage;
87
88/*
89** All structures on a database page are aligned to 4-byte boundries.
90** This routine rounds up a number of bytes to the next multiple of 4.
drh306dc212001-05-21 13:45:10 +000091**
92** This might need to change for computer architectures that require
93** and 8-byte alignment boundry for structures.
drh2af926b2001-05-15 00:39:25 +000094*/
95#define ROUNDUP(X) ((X+3) & ~3)
drha059ad02001-04-17 20:09:11 +000096
drh08ed44e2001-04-29 23:32:55 +000097/*
drhbd03cae2001-06-02 02:40:57 +000098** This is a magic string that appears at the beginning of every
drh8c42ca92001-06-22 19:15:00 +000099** SQLite database in order to identify the file as a real database.
drh08ed44e2001-04-29 23:32:55 +0000100*/
drhbd03cae2001-06-02 02:40:57 +0000101static const char zMagicHeader[] =
drh8c42ca92001-06-22 19:15:00 +0000102 "** This file contains an SQLite 2.0 database **";
drhbd03cae2001-06-02 02:40:57 +0000103#define MAGIC_SIZE (sizeof(zMagicHeader))
drh08ed44e2001-04-29 23:32:55 +0000104
105/*
drh5e00f6c2001-09-13 13:46:56 +0000106** This is a magic integer also used to test the integrity of the database
drh8c42ca92001-06-22 19:15:00 +0000107** file. This integer is used in addition to the string above so that
108** if the file is written on a little-endian architecture and read
109** on a big-endian architectures (or vice versa) we can detect the
110** problem.
111**
112** The number used was obtained at random and has no special
drhb19a2bc2001-09-16 00:13:26 +0000113** significance other than the fact that it represents a different
114** integer on little-endian and big-endian machines.
drh8c42ca92001-06-22 19:15:00 +0000115*/
116#define MAGIC 0xdae37528
117
118/*
drhbd03cae2001-06-02 02:40:57 +0000119** The first page of the database file contains a magic header string
120** to identify the file as an SQLite database file. It also contains
121** a pointer to the first free page of the file. Page 2 contains the
drh8b2f49b2001-06-08 00:21:52 +0000122** root of the principle BTree. The file might contain other BTrees
123** rooted on pages above 2.
124**
125** The first page also contains SQLITE_N_BTREE_META integers that
126** can be used by higher-level routines.
drh08ed44e2001-04-29 23:32:55 +0000127**
drhbd03cae2001-06-02 02:40:57 +0000128** Remember that pages are numbered beginning with 1. (See pager.c
129** for additional information.) Page 0 does not exist and a page
130** number of 0 is used to mean "no such page".
131*/
132struct PageOne {
133 char zMagic[MAGIC_SIZE]; /* String that identifies the file as a database */
drh8c42ca92001-06-22 19:15:00 +0000134 int iMagic; /* Integer to verify correct byte order */
135 Pgno freeList; /* First free page in a list of all free pages */
drh2aa679f2001-06-25 02:11:07 +0000136 int nFree; /* Number of pages on the free list */
137 int aMeta[SQLITE_N_BTREE_META-1]; /* User defined integers */
drhbd03cae2001-06-02 02:40:57 +0000138};
139
140/*
141** Each database page has a header that is an instance of this
142** structure.
drh08ed44e2001-04-29 23:32:55 +0000143**
drh8b2f49b2001-06-08 00:21:52 +0000144** PageHdr.firstFree is 0 if there is no free space on this page.
drh14acc042001-06-10 19:56:58 +0000145** Otherwise, PageHdr.firstFree is the index in MemPage.u.aDisk[] of a
drh8b2f49b2001-06-08 00:21:52 +0000146** FreeBlk structure that describes the first block of free space.
147** All free space is defined by a linked list of FreeBlk structures.
drh08ed44e2001-04-29 23:32:55 +0000148**
drh8b2f49b2001-06-08 00:21:52 +0000149** Data is stored in a linked list of Cell structures. PageHdr.firstCell
drh14acc042001-06-10 19:56:58 +0000150** is the index into MemPage.u.aDisk[] of the first cell on the page. The
drh306dc212001-05-21 13:45:10 +0000151** Cells are kept in sorted order.
drh8b2f49b2001-06-08 00:21:52 +0000152**
153** A Cell contains all information about a database entry and a pointer
154** to a child page that contains other entries less than itself. In
155** other words, the i-th Cell contains both Ptr(i) and Key(i). The
156** right-most pointer of the page is contained in PageHdr.rightChild.
drh08ed44e2001-04-29 23:32:55 +0000157*/
drh365d68f2001-05-11 11:02:46 +0000158struct PageHdr {
drh5e2f8b92001-05-28 00:41:15 +0000159 Pgno rightChild; /* Child page that comes after all cells on this page */
drh14acc042001-06-10 19:56:58 +0000160 u16 firstCell; /* Index in MemPage.u.aDisk[] of the first cell */
161 u16 firstFree; /* Index in MemPage.u.aDisk[] of the first free block */
drh365d68f2001-05-11 11:02:46 +0000162};
drh306dc212001-05-21 13:45:10 +0000163
drh3b7511c2001-05-26 13:15:44 +0000164/*
165** Entries on a page of the database are called "Cells". Each Cell
166** has a header and data. This structure defines the header. The
drhbd03cae2001-06-02 02:40:57 +0000167** key and data (collectively the "payload") follow this header on
168** the database page.
169**
170** A definition of the complete Cell structure is given below. The
drh8c42ca92001-06-22 19:15:00 +0000171** header for the cell must be defined first in order to do some
drhbd03cae2001-06-02 02:40:57 +0000172** of the sizing #defines that follow.
drh3b7511c2001-05-26 13:15:44 +0000173*/
174struct CellHdr {
drh5e2f8b92001-05-28 00:41:15 +0000175 Pgno leftChild; /* Child page that comes before this cell */
drh3b7511c2001-05-26 13:15:44 +0000176 u16 nKey; /* Number of bytes in the key */
drh14acc042001-06-10 19:56:58 +0000177 u16 iNext; /* Index in MemPage.u.aDisk[] of next cell in sorted order */
drh3b7511c2001-05-26 13:15:44 +0000178 u32 nData; /* Number of bytes of data */
drh8c42ca92001-06-22 19:15:00 +0000179};
drh3b7511c2001-05-26 13:15:44 +0000180
181/*
182** The minimum size of a complete Cell. The Cell must contain a header
drhbd03cae2001-06-02 02:40:57 +0000183** and at least 4 bytes of payload.
drh3b7511c2001-05-26 13:15:44 +0000184*/
185#define MIN_CELL_SIZE (sizeof(CellHdr)+4)
186
187/*
188** The maximum number of database entries that can be held in a single
189** page of the database.
190*/
191#define MX_CELL ((SQLITE_PAGE_SIZE-sizeof(PageHdr))/MIN_CELL_SIZE)
192
193/*
drh6019e162001-07-02 17:51:45 +0000194** The amount of usable space on a single page of the BTree. This is the
195** page size minus the overhead of the page header.
196*/
197#define USABLE_SPACE (SQLITE_PAGE_SIZE - sizeof(PageHdr))
198
199/*
drh8c42ca92001-06-22 19:15:00 +0000200** The maximum amount of payload (in bytes) that can be stored locally for
201** a database entry. If the entry contains more data than this, the
drh3b7511c2001-05-26 13:15:44 +0000202** extra goes onto overflow pages.
drhbd03cae2001-06-02 02:40:57 +0000203**
204** This number is chosen so that at least 4 cells will fit on every page.
drh3b7511c2001-05-26 13:15:44 +0000205*/
drh6019e162001-07-02 17:51:45 +0000206#define MX_LOCAL_PAYLOAD ((USABLE_SPACE/4-(sizeof(CellHdr)+sizeof(Pgno)))&~3)
drh3b7511c2001-05-26 13:15:44 +0000207
drh306dc212001-05-21 13:45:10 +0000208/*
209** Data on a database page is stored as a linked list of Cell structures.
drh5e2f8b92001-05-28 00:41:15 +0000210** Both the key and the data are stored in aPayload[]. The key always comes
211** first. The aPayload[] field grows as necessary to hold the key and data,
drh306dc212001-05-21 13:45:10 +0000212** up to a maximum of MX_LOCAL_PAYLOAD bytes. If the size of the key and
drh3b7511c2001-05-26 13:15:44 +0000213** data combined exceeds MX_LOCAL_PAYLOAD bytes, then Cell.ovfl is the
214** page number of the first overflow page.
215**
216** Though this structure is fixed in size, the Cell on the database
drhbd03cae2001-06-02 02:40:57 +0000217** page varies in size. Every cell has a CellHdr and at least 4 bytes
drh3b7511c2001-05-26 13:15:44 +0000218** of payload space. Additional payload bytes (up to the maximum of
219** MX_LOCAL_PAYLOAD) and the Cell.ovfl value are allocated only as
220** needed.
drh306dc212001-05-21 13:45:10 +0000221*/
drh365d68f2001-05-11 11:02:46 +0000222struct Cell {
drh5e2f8b92001-05-28 00:41:15 +0000223 CellHdr h; /* The cell header */
224 char aPayload[MX_LOCAL_PAYLOAD]; /* Key and data */
225 Pgno ovfl; /* The first overflow page */
drh365d68f2001-05-11 11:02:46 +0000226};
drh306dc212001-05-21 13:45:10 +0000227
228/*
229** Free space on a page is remembered using a linked list of the FreeBlk
230** structures. Space on a database page is allocated in increments of
drh72f82862001-05-24 21:06:34 +0000231** at least 4 bytes and is always aligned to a 4-byte boundry. The
drh8b2f49b2001-06-08 00:21:52 +0000232** linked list of FreeBlks is always kept in order by address.
drh306dc212001-05-21 13:45:10 +0000233*/
drh365d68f2001-05-11 11:02:46 +0000234struct FreeBlk {
drh72f82862001-05-24 21:06:34 +0000235 u16 iSize; /* Number of bytes in this block of free space */
drh14acc042001-06-10 19:56:58 +0000236 u16 iNext; /* Index in MemPage.u.aDisk[] of the next free block */
drh365d68f2001-05-11 11:02:46 +0000237};
drh306dc212001-05-21 13:45:10 +0000238
239/*
drh14acc042001-06-10 19:56:58 +0000240** The number of bytes of payload that will fit on a single overflow page.
drh3b7511c2001-05-26 13:15:44 +0000241*/
242#define OVERFLOW_SIZE (SQLITE_PAGE_SIZE-sizeof(Pgno))
243
244/*
drh306dc212001-05-21 13:45:10 +0000245** When the key and data for a single entry in the BTree will not fit in
drh8c42ca92001-06-22 19:15:00 +0000246** the MX_LOCAL_PAYLOAD bytes of space available on the database page,
drh8b2f49b2001-06-08 00:21:52 +0000247** then all extra bytes are written to a linked list of overflow pages.
drh306dc212001-05-21 13:45:10 +0000248** Each overflow page is an instance of the following structure.
249**
250** Unused pages in the database are also represented by instances of
drhbd03cae2001-06-02 02:40:57 +0000251** the OverflowPage structure. The PageOne.freeList field is the
drh306dc212001-05-21 13:45:10 +0000252** page number of the first page in a linked list of unused database
253** pages.
254*/
drh2af926b2001-05-15 00:39:25 +0000255struct OverflowPage {
drh14acc042001-06-10 19:56:58 +0000256 Pgno iNext;
drh5e2f8b92001-05-28 00:41:15 +0000257 char aPayload[OVERFLOW_SIZE];
drh7e3b0a02001-04-28 16:52:40 +0000258};
drh7e3b0a02001-04-28 16:52:40 +0000259
260/*
261** For every page in the database file, an instance of the following structure
drh14acc042001-06-10 19:56:58 +0000262** is stored in memory. The u.aDisk[] array contains the raw bits read from
drhbd03cae2001-06-02 02:40:57 +0000263** the disk. The rest is auxiliary information that held in memory only. The
264** auxiliary info is only valid for regular database pages - it is not
265** used for overflow pages and pages on the freelist.
drh306dc212001-05-21 13:45:10 +0000266**
drhbd03cae2001-06-02 02:40:57 +0000267** Of particular interest in the auxiliary info is the apCell[] entry. Each
drh14acc042001-06-10 19:56:58 +0000268** apCell[] entry is a pointer to a Cell structure in u.aDisk[]. The cells are
drh306dc212001-05-21 13:45:10 +0000269** put in this array so that they can be accessed in constant time, rather
drhbd03cae2001-06-02 02:40:57 +0000270** than in linear time which would be needed if we had to walk the linked
271** list on every access.
drh72f82862001-05-24 21:06:34 +0000272**
drh14acc042001-06-10 19:56:58 +0000273** Note that apCell[] contains enough space to hold up to two more Cells
274** than can possibly fit on one page. In the steady state, every apCell[]
275** points to memory inside u.aDisk[]. But in the middle of an insert
276** operation, some apCell[] entries may temporarily point to data space
277** outside of u.aDisk[]. This is a transient situation that is quickly
278** resolved. But while it is happening, it is possible for a database
279** page to hold as many as two more cells than it might otherwise hold.
280** The extra too entries in apCell[] are an allowance for this situation.
281**
drh72f82862001-05-24 21:06:34 +0000282** The pParent field points back to the parent page. This allows us to
283** walk up the BTree from any leaf to the root. Care must be taken to
284** unref() the parent page pointer when this page is no longer referenced.
drhbd03cae2001-06-02 02:40:57 +0000285** The pageDestructor() routine handles that chore.
drh7e3b0a02001-04-28 16:52:40 +0000286*/
287struct MemPage {
drh14acc042001-06-10 19:56:58 +0000288 union {
289 char aDisk[SQLITE_PAGE_SIZE]; /* Page data stored on disk */
290 PageHdr hdr; /* Overlay page header */
291 } u;
drh5e2f8b92001-05-28 00:41:15 +0000292 int isInit; /* True if auxiliary data is initialized */
drh72f82862001-05-24 21:06:34 +0000293 MemPage *pParent; /* The parent of this page. NULL for root */
drh14acc042001-06-10 19:56:58 +0000294 int nFree; /* Number of free bytes in u.aDisk[] */
drh306dc212001-05-21 13:45:10 +0000295 int nCell; /* Number of entries on this page */
drh14acc042001-06-10 19:56:58 +0000296 int isOverfull; /* Some apCell[] points outside u.aDisk[] */
297 Cell *apCell[MX_CELL+2]; /* All data entires in sorted order */
drh8c42ca92001-06-22 19:15:00 +0000298};
drh7e3b0a02001-04-28 16:52:40 +0000299
300/*
drh3b7511c2001-05-26 13:15:44 +0000301** The in-memory image of a disk page has the auxiliary information appended
302** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
303** that extra information.
304*/
305#define EXTRA_SIZE (sizeof(MemPage)-SQLITE_PAGE_SIZE)
306
307/*
drha059ad02001-04-17 20:09:11 +0000308** Everything we need to know about an open database
309*/
310struct Btree {
311 Pager *pPager; /* The page cache */
drh306dc212001-05-21 13:45:10 +0000312 BtCursor *pCursor; /* A list of all open cursors */
drhbd03cae2001-06-02 02:40:57 +0000313 PageOne *page1; /* First page of the database */
drh306dc212001-05-21 13:45:10 +0000314 int inTrans; /* True if a transaction is in progress */
drhecdc7532001-09-23 02:35:53 +0000315 Hash locks; /* Key: root page number. Data: lock count */
drha059ad02001-04-17 20:09:11 +0000316};
317typedef Btree Bt;
318
drh365d68f2001-05-11 11:02:46 +0000319/*
320** A cursor is a pointer to a particular entry in the BTree.
321** The entry is identified by its MemPage and the index in
drh5e2f8b92001-05-28 00:41:15 +0000322** MemPage.apCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000323*/
drh72f82862001-05-24 21:06:34 +0000324struct BtCursor {
drh5e2f8b92001-05-28 00:41:15 +0000325 Btree *pBt; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000326 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drh8b2f49b2001-06-08 00:21:52 +0000327 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000328 MemPage *pPage; /* Page that contains the entry */
drh8c42ca92001-06-22 19:15:00 +0000329 int idx; /* Index of the entry in pPage->apCell[] */
drhecdc7532001-09-23 02:35:53 +0000330 u8 wrFlag; /* True if writable */
drh5e2f8b92001-05-28 00:41:15 +0000331 u8 bSkipNext; /* sqliteBtreeNext() is no-op if true */
332 u8 iMatch; /* compare result from last sqliteBtreeMoveto() */
drh365d68f2001-05-11 11:02:46 +0000333};
drh7e3b0a02001-04-28 16:52:40 +0000334
drha059ad02001-04-17 20:09:11 +0000335/*
drh3b7511c2001-05-26 13:15:44 +0000336** Compute the total number of bytes that a Cell needs on the main
drh5e2f8b92001-05-28 00:41:15 +0000337** database page. The number returned includes the Cell header,
338** local payload storage, and the pointer to overflow pages (if
drh8c42ca92001-06-22 19:15:00 +0000339** applicable). Additional space allocated on overflow pages
drhbd03cae2001-06-02 02:40:57 +0000340** is NOT included in the value returned from this routine.
drh3b7511c2001-05-26 13:15:44 +0000341*/
342static int cellSize(Cell *pCell){
343 int n = pCell->h.nKey + pCell->h.nData;
344 if( n>MX_LOCAL_PAYLOAD ){
345 n = MX_LOCAL_PAYLOAD + sizeof(Pgno);
346 }else{
347 n = ROUNDUP(n);
348 }
349 n += sizeof(CellHdr);
350 return n;
351}
352
353/*
drh72f82862001-05-24 21:06:34 +0000354** Defragment the page given. All Cells are moved to the
355** beginning of the page and all free space is collected
356** into one big FreeBlk at the end of the page.
drh365d68f2001-05-11 11:02:46 +0000357*/
358static void defragmentPage(MemPage *pPage){
drh14acc042001-06-10 19:56:58 +0000359 int pc, i, n;
drh2af926b2001-05-15 00:39:25 +0000360 FreeBlk *pFBlk;
361 char newPage[SQLITE_PAGE_SIZE];
362
drh6019e162001-07-02 17:51:45 +0000363 assert( sqlitepager_iswriteable(pPage) );
drhbd03cae2001-06-02 02:40:57 +0000364 pc = sizeof(PageHdr);
drh14acc042001-06-10 19:56:58 +0000365 pPage->u.hdr.firstCell = pc;
366 memcpy(newPage, pPage->u.aDisk, pc);
drh2af926b2001-05-15 00:39:25 +0000367 for(i=0; i<pPage->nCell; i++){
drh2aa679f2001-06-25 02:11:07 +0000368 Cell *pCell = pPage->apCell[i];
drh8c42ca92001-06-22 19:15:00 +0000369
370 /* This routine should never be called on an overfull page. The
371 ** following asserts verify that constraint. */
drh7c717f72001-06-24 20:39:41 +0000372 assert( Addr(pCell) > Addr(pPage) );
373 assert( Addr(pCell) < Addr(pPage) + SQLITE_PAGE_SIZE );
drh8c42ca92001-06-22 19:15:00 +0000374
drh3b7511c2001-05-26 13:15:44 +0000375 n = cellSize(pCell);
drh2aa679f2001-06-25 02:11:07 +0000376 pCell->h.iNext = pc + n;
drh2af926b2001-05-15 00:39:25 +0000377 memcpy(&newPage[pc], pCell, n);
drh14acc042001-06-10 19:56:58 +0000378 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[pc];
drh2af926b2001-05-15 00:39:25 +0000379 pc += n;
380 }
drh72f82862001-05-24 21:06:34 +0000381 assert( pPage->nFree==SQLITE_PAGE_SIZE-pc );
drh14acc042001-06-10 19:56:58 +0000382 memcpy(pPage->u.aDisk, newPage, pc);
drh2aa679f2001-06-25 02:11:07 +0000383 if( pPage->nCell>0 ){
384 pPage->apCell[pPage->nCell-1]->h.iNext = 0;
385 }
drh8c42ca92001-06-22 19:15:00 +0000386 pFBlk = (FreeBlk*)&pPage->u.aDisk[pc];
drh2af926b2001-05-15 00:39:25 +0000387 pFBlk->iSize = SQLITE_PAGE_SIZE - pc;
388 pFBlk->iNext = 0;
drh14acc042001-06-10 19:56:58 +0000389 pPage->u.hdr.firstFree = pc;
drh2af926b2001-05-15 00:39:25 +0000390 memset(&pFBlk[1], 0, SQLITE_PAGE_SIZE - pc - sizeof(FreeBlk));
drh365d68f2001-05-11 11:02:46 +0000391}
392
drha059ad02001-04-17 20:09:11 +0000393/*
drh8b2f49b2001-06-08 00:21:52 +0000394** Allocate nByte bytes of space on a page. nByte must be a
395** multiple of 4.
drhbd03cae2001-06-02 02:40:57 +0000396**
drh14acc042001-06-10 19:56:58 +0000397** Return the index into pPage->u.aDisk[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000398** the new allocation. Or return 0 if there is not enough free
399** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000400**
drh72f82862001-05-24 21:06:34 +0000401** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000402** nBytes of contiguous free space, then this routine automatically
403** calls defragementPage() to consolidate all free space before
404** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000405*/
drhbd03cae2001-06-02 02:40:57 +0000406static int allocateSpace(MemPage *pPage, int nByte){
drh2af926b2001-05-15 00:39:25 +0000407 FreeBlk *p;
408 u16 *pIdx;
409 int start;
drh8c42ca92001-06-22 19:15:00 +0000410 int cnt = 0;
drh72f82862001-05-24 21:06:34 +0000411
drh6019e162001-07-02 17:51:45 +0000412 assert( sqlitepager_iswriteable(pPage) );
drh5e2f8b92001-05-28 00:41:15 +0000413 assert( nByte==ROUNDUP(nByte) );
drh14acc042001-06-10 19:56:58 +0000414 if( pPage->nFree<nByte || pPage->isOverfull ) return 0;
415 pIdx = &pPage->u.hdr.firstFree;
416 p = (FreeBlk*)&pPage->u.aDisk[*pIdx];
drh2af926b2001-05-15 00:39:25 +0000417 while( p->iSize<nByte ){
drh8c42ca92001-06-22 19:15:00 +0000418 assert( cnt++ < SQLITE_PAGE_SIZE/4 );
drh2af926b2001-05-15 00:39:25 +0000419 if( p->iNext==0 ){
420 defragmentPage(pPage);
drh14acc042001-06-10 19:56:58 +0000421 pIdx = &pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000422 }else{
423 pIdx = &p->iNext;
424 }
drh14acc042001-06-10 19:56:58 +0000425 p = (FreeBlk*)&pPage->u.aDisk[*pIdx];
drh2af926b2001-05-15 00:39:25 +0000426 }
427 if( p->iSize==nByte ){
428 start = *pIdx;
429 *pIdx = p->iNext;
430 }else{
drh8c42ca92001-06-22 19:15:00 +0000431 FreeBlk *pNew;
drh72f82862001-05-24 21:06:34 +0000432 start = *pIdx;
drh8c42ca92001-06-22 19:15:00 +0000433 pNew = (FreeBlk*)&pPage->u.aDisk[start + nByte];
drh72f82862001-05-24 21:06:34 +0000434 pNew->iNext = p->iNext;
435 pNew->iSize = p->iSize - nByte;
436 *pIdx = start + nByte;
drh2af926b2001-05-15 00:39:25 +0000437 }
438 pPage->nFree -= nByte;
439 return start;
drh7e3b0a02001-04-28 16:52:40 +0000440}
441
442/*
drh14acc042001-06-10 19:56:58 +0000443** Return a section of the MemPage.u.aDisk[] to the freelist.
444** The first byte of the new free block is pPage->u.aDisk[start]
445** and the size of the block is "size" bytes. Size must be
446** a multiple of 4.
drh306dc212001-05-21 13:45:10 +0000447**
448** Most of the effort here is involved in coalesing adjacent
449** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000450*/
451static void freeSpace(MemPage *pPage, int start, int size){
drh2af926b2001-05-15 00:39:25 +0000452 int end = start + size;
453 u16 *pIdx, idx;
454 FreeBlk *pFBlk;
455 FreeBlk *pNew;
456 FreeBlk *pNext;
457
drh6019e162001-07-02 17:51:45 +0000458 assert( sqlitepager_iswriteable(pPage) );
drh2af926b2001-05-15 00:39:25 +0000459 assert( size == ROUNDUP(size) );
460 assert( start == ROUNDUP(start) );
drh14acc042001-06-10 19:56:58 +0000461 pIdx = &pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000462 idx = *pIdx;
463 while( idx!=0 && idx<start ){
drh14acc042001-06-10 19:56:58 +0000464 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh2af926b2001-05-15 00:39:25 +0000465 if( idx + pFBlk->iSize == start ){
466 pFBlk->iSize += size;
467 if( idx + pFBlk->iSize == pFBlk->iNext ){
drh8c42ca92001-06-22 19:15:00 +0000468 pNext = (FreeBlk*)&pPage->u.aDisk[pFBlk->iNext];
drh2af926b2001-05-15 00:39:25 +0000469 pFBlk->iSize += pNext->iSize;
470 pFBlk->iNext = pNext->iNext;
471 }
472 pPage->nFree += size;
473 return;
474 }
475 pIdx = &pFBlk->iNext;
476 idx = *pIdx;
477 }
drh14acc042001-06-10 19:56:58 +0000478 pNew = (FreeBlk*)&pPage->u.aDisk[start];
drh2af926b2001-05-15 00:39:25 +0000479 if( idx != end ){
480 pNew->iSize = size;
481 pNew->iNext = idx;
482 }else{
drh14acc042001-06-10 19:56:58 +0000483 pNext = (FreeBlk*)&pPage->u.aDisk[idx];
drh2af926b2001-05-15 00:39:25 +0000484 pNew->iSize = size + pNext->iSize;
485 pNew->iNext = pNext->iNext;
486 }
487 *pIdx = start;
488 pPage->nFree += size;
drh7e3b0a02001-04-28 16:52:40 +0000489}
490
491/*
492** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000493**
drhbd03cae2001-06-02 02:40:57 +0000494** The pParent parameter must be a pointer to the MemPage which
495** is the parent of the page being initialized. The root of the
drh8b2f49b2001-06-08 00:21:52 +0000496** BTree (usually page 2) has no parent and so for that page,
497** pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000498**
drh72f82862001-05-24 21:06:34 +0000499** Return SQLITE_OK on success. If we see that the page does
500** not contained a well-formed database page, then return
501** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
502** guarantee that the page is well-formed. It only shows that
503** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000504*/
drh72f82862001-05-24 21:06:34 +0000505static int initPage(MemPage *pPage, Pgno pgnoThis, MemPage *pParent){
drh14acc042001-06-10 19:56:58 +0000506 int idx; /* An index into pPage->u.aDisk[] */
507 Cell *pCell; /* A pointer to a Cell in pPage->u.aDisk[] */
508 FreeBlk *pFBlk; /* A pointer to a free block in pPage->u.aDisk[] */
drh5e2f8b92001-05-28 00:41:15 +0000509 int sz; /* The size of a Cell in bytes */
510 int freeSpace; /* Amount of free space on the page */
drh2af926b2001-05-15 00:39:25 +0000511
drh5e2f8b92001-05-28 00:41:15 +0000512 if( pPage->pParent ){
513 assert( pPage->pParent==pParent );
514 return SQLITE_OK;
515 }
516 if( pParent ){
517 pPage->pParent = pParent;
518 sqlitepager_ref(pParent);
519 }
520 if( pPage->isInit ) return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +0000521 pPage->isInit = 1;
drh7e3b0a02001-04-28 16:52:40 +0000522 pPage->nCell = 0;
drh6019e162001-07-02 17:51:45 +0000523 freeSpace = USABLE_SPACE;
drh14acc042001-06-10 19:56:58 +0000524 idx = pPage->u.hdr.firstCell;
drh7e3b0a02001-04-28 16:52:40 +0000525 while( idx!=0 ){
drh8c42ca92001-06-22 19:15:00 +0000526 if( idx>SQLITE_PAGE_SIZE-MIN_CELL_SIZE ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000527 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh8c42ca92001-06-22 19:15:00 +0000528 if( idx!=ROUNDUP(idx) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000529 pCell = (Cell*)&pPage->u.aDisk[idx];
drh5e2f8b92001-05-28 00:41:15 +0000530 sz = cellSize(pCell);
531 if( idx+sz > SQLITE_PAGE_SIZE ) goto page_format_error;
532 freeSpace -= sz;
533 pPage->apCell[pPage->nCell++] = pCell;
drh3b7511c2001-05-26 13:15:44 +0000534 idx = pCell->h.iNext;
drh2af926b2001-05-15 00:39:25 +0000535 }
536 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +0000537 idx = pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000538 while( idx!=0 ){
539 if( idx>SQLITE_PAGE_SIZE-sizeof(FreeBlk) ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000540 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000541 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh2af926b2001-05-15 00:39:25 +0000542 pPage->nFree += pFBlk->iSize;
drh7c717f72001-06-24 20:39:41 +0000543 if( pFBlk->iNext>0 && pFBlk->iNext <= idx ) goto page_format_error;
drh2af926b2001-05-15 00:39:25 +0000544 idx = pFBlk->iNext;
drh7e3b0a02001-04-28 16:52:40 +0000545 }
drh8b2f49b2001-06-08 00:21:52 +0000546 if( pPage->nCell==0 && pPage->nFree==0 ){
547 /* As a special case, an uninitialized root page appears to be
548 ** an empty database */
549 return SQLITE_OK;
550 }
drh5e2f8b92001-05-28 00:41:15 +0000551 if( pPage->nFree!=freeSpace ) goto page_format_error;
drh7e3b0a02001-04-28 16:52:40 +0000552 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +0000553
554page_format_error:
555 return SQLITE_CORRUPT;
drh7e3b0a02001-04-28 16:52:40 +0000556}
557
558/*
drh8b2f49b2001-06-08 00:21:52 +0000559** Set up a raw page so that it looks like a database page holding
560** no entries.
drhbd03cae2001-06-02 02:40:57 +0000561*/
562static void zeroPage(MemPage *pPage){
563 PageHdr *pHdr;
564 FreeBlk *pFBlk;
drh6019e162001-07-02 17:51:45 +0000565 assert( sqlitepager_iswriteable(pPage) );
drhbd03cae2001-06-02 02:40:57 +0000566 memset(pPage, 0, SQLITE_PAGE_SIZE);
drh14acc042001-06-10 19:56:58 +0000567 pHdr = &pPage->u.hdr;
drhbd03cae2001-06-02 02:40:57 +0000568 pHdr->firstCell = 0;
569 pHdr->firstFree = sizeof(*pHdr);
570 pFBlk = (FreeBlk*)&pHdr[1];
571 pFBlk->iNext = 0;
572 pFBlk->iSize = SQLITE_PAGE_SIZE - sizeof(*pHdr);
drh8c42ca92001-06-22 19:15:00 +0000573 pPage->nFree = pFBlk->iSize;
574 pPage->nCell = 0;
575 pPage->isOverfull = 0;
drhbd03cae2001-06-02 02:40:57 +0000576}
577
578/*
drh72f82862001-05-24 21:06:34 +0000579** This routine is called when the reference count for a page
580** reaches zero. We need to unref the pParent pointer when that
581** happens.
582*/
583static void pageDestructor(void *pData){
584 MemPage *pPage = (MemPage*)pData;
585 if( pPage->pParent ){
586 MemPage *pParent = pPage->pParent;
587 pPage->pParent = 0;
588 sqlitepager_unref(pParent);
589 }
590}
591
592/*
drh306dc212001-05-21 13:45:10 +0000593** Open a new database.
594**
595** Actually, this routine just sets up the internal data structures
drh72f82862001-05-24 21:06:34 +0000596** for accessing the database. We do not open the database file
597** until the first page is loaded.
drha059ad02001-04-17 20:09:11 +0000598*/
drh6019e162001-07-02 17:51:45 +0000599int sqliteBtreeOpen(
600 const char *zFilename, /* Name of the file containing the BTree database */
601 int mode, /* Not currently used */
602 int nCache, /* How many pages in the page cache */
603 Btree **ppBtree /* Pointer to new Btree object written here */
604){
drha059ad02001-04-17 20:09:11 +0000605 Btree *pBt;
drh8c42ca92001-06-22 19:15:00 +0000606 int rc;
drha059ad02001-04-17 20:09:11 +0000607
608 pBt = sqliteMalloc( sizeof(*pBt) );
609 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +0000610 *ppBtree = 0;
drha059ad02001-04-17 20:09:11 +0000611 return SQLITE_NOMEM;
612 }
drh6019e162001-07-02 17:51:45 +0000613 if( nCache<10 ) nCache = 10;
614 rc = sqlitepager_open(&pBt->pPager, zFilename, nCache, EXTRA_SIZE);
drha059ad02001-04-17 20:09:11 +0000615 if( rc!=SQLITE_OK ){
616 if( pBt->pPager ) sqlitepager_close(pBt->pPager);
617 sqliteFree(pBt);
618 *ppBtree = 0;
619 return rc;
620 }
drh72f82862001-05-24 21:06:34 +0000621 sqlitepager_set_destructor(pBt->pPager, pageDestructor);
drha059ad02001-04-17 20:09:11 +0000622 pBt->pCursor = 0;
623 pBt->page1 = 0;
drhecdc7532001-09-23 02:35:53 +0000624 sqliteHashInit(&pBt->locks, SQLITE_HASH_INT, 0);
drha059ad02001-04-17 20:09:11 +0000625 *ppBtree = pBt;
626 return SQLITE_OK;
627}
628
629/*
630** Close an open database and invalidate all cursors.
631*/
632int sqliteBtreeClose(Btree *pBt){
633 while( pBt->pCursor ){
634 sqliteBtreeCloseCursor(pBt->pCursor);
635 }
636 sqlitepager_close(pBt->pPager);
drhecdc7532001-09-23 02:35:53 +0000637 sqliteHashClear(&pBt->locks);
drha059ad02001-04-17 20:09:11 +0000638 sqliteFree(pBt);
639 return SQLITE_OK;
640}
641
642/*
drhf57b14a2001-09-14 18:54:08 +0000643** Change the number of pages in the cache.
644*/
645int sqliteBtreeSetCacheSize(Btree *pBt, int mxPage){
646 sqlitepager_set_cachesize(pBt->pPager, mxPage);
647 return SQLITE_OK;
648}
649
650/*
drh306dc212001-05-21 13:45:10 +0000651** Get a reference to page1 of the database file. This will
652** also acquire a readlock on that file.
653**
654** SQLITE_OK is returned on success. If the file is not a
655** well-formed database file, then SQLITE_CORRUPT is returned.
656** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
657** is returned if we run out of memory. SQLITE_PROTOCOL is returned
658** if there is a locking protocol violation.
659*/
660static int lockBtree(Btree *pBt){
661 int rc;
662 if( pBt->page1 ) return SQLITE_OK;
drh8c42ca92001-06-22 19:15:00 +0000663 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pBt->page1);
drh306dc212001-05-21 13:45:10 +0000664 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +0000665
666 /* Do some checking to help insure the file we opened really is
667 ** a valid database file.
668 */
669 if( sqlitepager_pagecount(pBt->pPager)>0 ){
drhbd03cae2001-06-02 02:40:57 +0000670 PageOne *pP1 = pBt->page1;
drh8c42ca92001-06-22 19:15:00 +0000671 if( strcmp(pP1->zMagic,zMagicHeader)!=0 || pP1->iMagic!=MAGIC ){
drh306dc212001-05-21 13:45:10 +0000672 rc = SQLITE_CORRUPT;
drh72f82862001-05-24 21:06:34 +0000673 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +0000674 }
675 }
676 return rc;
677
drh72f82862001-05-24 21:06:34 +0000678page1_init_failed:
drh306dc212001-05-21 13:45:10 +0000679 sqlitepager_unref(pBt->page1);
680 pBt->page1 = 0;
drh72f82862001-05-24 21:06:34 +0000681 return rc;
drh306dc212001-05-21 13:45:10 +0000682}
683
684/*
drh8c42ca92001-06-22 19:15:00 +0000685** Create a new database by initializing the first two pages of the
686** file.
drh8b2f49b2001-06-08 00:21:52 +0000687*/
688static int newDatabase(Btree *pBt){
689 MemPage *pRoot;
690 PageOne *pP1;
drh8c42ca92001-06-22 19:15:00 +0000691 int rc;
drh7c717f72001-06-24 20:39:41 +0000692 if( sqlitepager_pagecount(pBt->pPager)>1 ) return SQLITE_OK;
drh8b2f49b2001-06-08 00:21:52 +0000693 pP1 = pBt->page1;
694 rc = sqlitepager_write(pBt->page1);
695 if( rc ) return rc;
drh8c42ca92001-06-22 19:15:00 +0000696 rc = sqlitepager_get(pBt->pPager, 2, (void**)&pRoot);
drh8b2f49b2001-06-08 00:21:52 +0000697 if( rc ) return rc;
698 rc = sqlitepager_write(pRoot);
699 if( rc ){
700 sqlitepager_unref(pRoot);
701 return rc;
702 }
703 strcpy(pP1->zMagic, zMagicHeader);
drh8c42ca92001-06-22 19:15:00 +0000704 pP1->iMagic = MAGIC;
drh8b2f49b2001-06-08 00:21:52 +0000705 zeroPage(pRoot);
706 sqlitepager_unref(pRoot);
707 return SQLITE_OK;
708}
709
710/*
drh72f82862001-05-24 21:06:34 +0000711** Attempt to start a new transaction.
drh8b2f49b2001-06-08 00:21:52 +0000712**
713** A transaction must be started before attempting any changes
714** to the database. None of the following routines will work
715** unless a transaction is started first:
716**
717** sqliteBtreeCreateTable()
718** sqliteBtreeClearTable()
719** sqliteBtreeDropTable()
720** sqliteBtreeInsert()
721** sqliteBtreeDelete()
722** sqliteBtreeUpdateMeta()
drha059ad02001-04-17 20:09:11 +0000723*/
724int sqliteBtreeBeginTrans(Btree *pBt){
725 int rc;
726 if( pBt->inTrans ) return SQLITE_ERROR;
727 if( pBt->page1==0 ){
drh7e3b0a02001-04-28 16:52:40 +0000728 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +0000729 if( rc!=SQLITE_OK ){
730 return rc;
731 }
drha059ad02001-04-17 20:09:11 +0000732 }
drhbe0072d2001-09-13 14:46:09 +0000733 if( !sqlitepager_isreadonly(pBt->pPager) ){
drh5e00f6c2001-09-13 13:46:56 +0000734 rc = sqlitepager_write(pBt->page1);
735 if( rc!=SQLITE_OK ){
736 return rc;
737 }
738 rc = newDatabase(pBt);
drha059ad02001-04-17 20:09:11 +0000739 }
drh8c42ca92001-06-22 19:15:00 +0000740 pBt->inTrans = 1;
drh8c42ca92001-06-22 19:15:00 +0000741 return rc;
drha059ad02001-04-17 20:09:11 +0000742}
743
744/*
drh5e00f6c2001-09-13 13:46:56 +0000745** If there are no outstanding cursors and we are not in the middle
746** of a transaction but there is a read lock on the database, then
747** this routine unrefs the first page of the database file which
748** has the effect of releasing the read lock.
749**
750** If there are any outstanding cursors, this routine is a no-op.
751**
752** If there is a transaction in progress, this routine is a no-op.
drha059ad02001-04-17 20:09:11 +0000753*/
drh5e00f6c2001-09-13 13:46:56 +0000754static void unlockBtreeIfUnused(Btree *pBt){
drh7c717f72001-06-24 20:39:41 +0000755 if( pBt->inTrans==0 && pBt->pCursor==0 && pBt->page1!=0 ){
drha059ad02001-04-17 20:09:11 +0000756 sqlitepager_unref(pBt->page1);
757 pBt->page1 = 0;
758 pBt->inTrans = 0;
759 }
760}
761
762/*
drh2aa679f2001-06-25 02:11:07 +0000763** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +0000764**
765** This will release the write lock on the database file. If there
766** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000767*/
768int sqliteBtreeCommit(Btree *pBt){
769 int rc;
drh2aa679f2001-06-25 02:11:07 +0000770 if( pBt->inTrans==0 ) return SQLITE_ERROR;
drha059ad02001-04-17 20:09:11 +0000771 rc = sqlitepager_commit(pBt->pPager);
drh7c717f72001-06-24 20:39:41 +0000772 pBt->inTrans = 0;
drh5e00f6c2001-09-13 13:46:56 +0000773 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000774 return rc;
775}
776
777/*
drhecdc7532001-09-23 02:35:53 +0000778** Rollback the transaction in progress. All cursors will be
779** invalided by this operation. Any attempt to use a cursor
780** that was open at the beginning of this operation will result
781** in an error.
drh5e00f6c2001-09-13 13:46:56 +0000782**
783** This will release the write lock on the database file. If there
784** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000785*/
786int sqliteBtreeRollback(Btree *pBt){
787 int rc;
drhecdc7532001-09-23 02:35:53 +0000788 BtCursor *pCur;
drh7c717f72001-06-24 20:39:41 +0000789 if( pBt->inTrans==0 ) return SQLITE_OK;
790 pBt->inTrans = 0;
drhecdc7532001-09-23 02:35:53 +0000791 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
792 if( pCur->pPage ){
793 sqlitepager_unref(pCur->pPage);
794 pCur->pPage = 0;
795 }
796 }
drha059ad02001-04-17 20:09:11 +0000797 rc = sqlitepager_rollback(pBt->pPager);
drh5e00f6c2001-09-13 13:46:56 +0000798 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000799 return rc;
800}
801
802/*
drh8b2f49b2001-06-08 00:21:52 +0000803** Create a new cursor for the BTree whose root is on the page
804** iTable. The act of acquiring a cursor gets a read lock on
805** the database file.
drha059ad02001-04-17 20:09:11 +0000806*/
drhecdc7532001-09-23 02:35:53 +0000807int sqliteBtreeCursor(Btree *pBt, int iTable, int wrFlag, BtCursor **ppCur){
drha059ad02001-04-17 20:09:11 +0000808 int rc;
809 BtCursor *pCur;
drhecdc7532001-09-23 02:35:53 +0000810 int nLock;
811
drha059ad02001-04-17 20:09:11 +0000812 if( pBt->page1==0 ){
813 rc = lockBtree(pBt);
814 if( rc!=SQLITE_OK ){
815 *ppCur = 0;
816 return rc;
817 }
818 }
819 pCur = sqliteMalloc( sizeof(*pCur) );
820 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +0000821 rc = SQLITE_NOMEM;
822 goto create_cursor_exception;
823 }
drh8b2f49b2001-06-08 00:21:52 +0000824 pCur->pgnoRoot = (Pgno)iTable;
drh8c42ca92001-06-22 19:15:00 +0000825 rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +0000826 if( rc!=SQLITE_OK ){
827 goto create_cursor_exception;
828 }
drh8b2f49b2001-06-08 00:21:52 +0000829 rc = initPage(pCur->pPage, pCur->pgnoRoot, 0);
drhbd03cae2001-06-02 02:40:57 +0000830 if( rc!=SQLITE_OK ){
831 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +0000832 }
drhecdc7532001-09-23 02:35:53 +0000833 nLock = (int)sqliteHashFind(&pBt->locks, 0, iTable);
834 if( nLock<0 || (nLock>0 && wrFlag) ){
835 rc = SQLITE_LOCKED;
836 goto create_cursor_exception;
837 }
838 nLock = wrFlag ? -1 : nLock+1;
839 sqliteHashInsert(&pBt->locks, 0, iTable, (void*)nLock);
drh14acc042001-06-10 19:56:58 +0000840 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +0000841 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +0000842 pCur->idx = 0;
drha059ad02001-04-17 20:09:11 +0000843 pCur->pNext = pBt->pCursor;
844 if( pCur->pNext ){
845 pCur->pNext->pPrev = pCur;
846 }
drh14acc042001-06-10 19:56:58 +0000847 pCur->pPrev = 0;
drha059ad02001-04-17 20:09:11 +0000848 pBt->pCursor = pCur;
drh2af926b2001-05-15 00:39:25 +0000849 *ppCur = pCur;
850 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +0000851
852create_cursor_exception:
853 *ppCur = 0;
854 if( pCur ){
855 if( pCur->pPage ) sqlitepager_unref(pCur->pPage);
856 sqliteFree(pCur);
857 }
drh5e00f6c2001-09-13 13:46:56 +0000858 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +0000859 return rc;
drha059ad02001-04-17 20:09:11 +0000860}
861
862/*
drh5e00f6c2001-09-13 13:46:56 +0000863** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +0000864** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +0000865*/
866int sqliteBtreeCloseCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +0000867 int nLock;
drha059ad02001-04-17 20:09:11 +0000868 Btree *pBt = pCur->pBt;
drha059ad02001-04-17 20:09:11 +0000869 if( pCur->pPrev ){
870 pCur->pPrev->pNext = pCur->pNext;
871 }else{
872 pBt->pCursor = pCur->pNext;
873 }
874 if( pCur->pNext ){
875 pCur->pNext->pPrev = pCur->pPrev;
876 }
drhecdc7532001-09-23 02:35:53 +0000877 if( pCur->pPage ){
878 sqlitepager_unref(pCur->pPage);
879 }
drh5e00f6c2001-09-13 13:46:56 +0000880 unlockBtreeIfUnused(pBt);
drhecdc7532001-09-23 02:35:53 +0000881 nLock = (int)sqliteHashFind(&pBt->locks, 0, pCur->pgnoRoot);
882 assert( nLock!=0 );
883 nLock = nLock<0 ? 0 : nLock-1;
884 sqliteHashInsert(&pBt->locks, 0, pCur->pgnoRoot, (void*)nLock);
drha059ad02001-04-17 20:09:11 +0000885 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +0000886 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +0000887}
888
drh7e3b0a02001-04-28 16:52:40 +0000889/*
drh5e2f8b92001-05-28 00:41:15 +0000890** Make a temporary cursor by filling in the fields of pTempCur.
891** The temporary cursor is not on the cursor list for the Btree.
892*/
drh14acc042001-06-10 19:56:58 +0000893static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +0000894 memcpy(pTempCur, pCur, sizeof(*pCur));
895 pTempCur->pNext = 0;
896 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +0000897 if( pTempCur->pPage ){
898 sqlitepager_ref(pTempCur->pPage);
899 }
drh5e2f8b92001-05-28 00:41:15 +0000900}
901
902/*
drhbd03cae2001-06-02 02:40:57 +0000903** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +0000904** function above.
905*/
drh14acc042001-06-10 19:56:58 +0000906static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +0000907 if( pCur->pPage ){
908 sqlitepager_unref(pCur->pPage);
909 }
drh5e2f8b92001-05-28 00:41:15 +0000910}
911
912/*
drhbd03cae2001-06-02 02:40:57 +0000913** Set *pSize to the number of bytes of key in the entry the
914** cursor currently points to. Always return SQLITE_OK.
915** Failure is not possible. If the cursor is not currently
916** pointing to an entry (which can happen, for example, if
917** the database is empty) then *pSize is set to 0.
drh7e3b0a02001-04-28 16:52:40 +0000918*/
drh72f82862001-05-24 21:06:34 +0000919int sqliteBtreeKeySize(BtCursor *pCur, int *pSize){
drh2af926b2001-05-15 00:39:25 +0000920 Cell *pCell;
921 MemPage *pPage;
922
923 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +0000924 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh72f82862001-05-24 21:06:34 +0000925 *pSize = 0;
926 }else{
drh5e2f8b92001-05-28 00:41:15 +0000927 pCell = pPage->apCell[pCur->idx];
drh8c42ca92001-06-22 19:15:00 +0000928 *pSize = pCell->h.nKey;
drh72f82862001-05-24 21:06:34 +0000929 }
930 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +0000931}
drh2af926b2001-05-15 00:39:25 +0000932
drh72f82862001-05-24 21:06:34 +0000933/*
934** Read payload information from the entry that the pCur cursor is
935** pointing to. Begin reading the payload at "offset" and read
936** a total of "amt" bytes. Put the result in zBuf.
937**
938** This routine does not make a distinction between key and data.
939** It just reads bytes from the payload area.
940*/
drh2af926b2001-05-15 00:39:25 +0000941static int getPayload(BtCursor *pCur, int offset, int amt, char *zBuf){
drh5e2f8b92001-05-28 00:41:15 +0000942 char *aPayload;
drh2af926b2001-05-15 00:39:25 +0000943 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +0000944 int rc;
drh72f82862001-05-24 21:06:34 +0000945 assert( pCur!=0 && pCur->pPage!=0 );
drh8c42ca92001-06-22 19:15:00 +0000946 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
947 aPayload = pCur->pPage->apCell[pCur->idx]->aPayload;
drh2af926b2001-05-15 00:39:25 +0000948 if( offset<MX_LOCAL_PAYLOAD ){
949 int a = amt;
950 if( a+offset>MX_LOCAL_PAYLOAD ){
951 a = MX_LOCAL_PAYLOAD - offset;
952 }
drh5e2f8b92001-05-28 00:41:15 +0000953 memcpy(zBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +0000954 if( a==amt ){
955 return SQLITE_OK;
956 }
drh2aa679f2001-06-25 02:11:07 +0000957 offset = 0;
drh2af926b2001-05-15 00:39:25 +0000958 zBuf += a;
959 amt -= a;
drhdd793422001-06-28 01:54:48 +0000960 }else{
961 offset -= MX_LOCAL_PAYLOAD;
drhbd03cae2001-06-02 02:40:57 +0000962 }
963 if( amt>0 ){
drh8c42ca92001-06-22 19:15:00 +0000964 nextPage = pCur->pPage->apCell[pCur->idx]->ovfl;
drh2af926b2001-05-15 00:39:25 +0000965 }
966 while( amt>0 && nextPage ){
967 OverflowPage *pOvfl;
drh8c42ca92001-06-22 19:15:00 +0000968 rc = sqlitepager_get(pCur->pBt->pPager, nextPage, (void**)&pOvfl);
drh2af926b2001-05-15 00:39:25 +0000969 if( rc!=0 ){
970 return rc;
971 }
drh14acc042001-06-10 19:56:58 +0000972 nextPage = pOvfl->iNext;
drh2af926b2001-05-15 00:39:25 +0000973 if( offset<OVERFLOW_SIZE ){
974 int a = amt;
975 if( a + offset > OVERFLOW_SIZE ){
976 a = OVERFLOW_SIZE - offset;
977 }
drh5e2f8b92001-05-28 00:41:15 +0000978 memcpy(zBuf, &pOvfl->aPayload[offset], a);
drh2aa679f2001-06-25 02:11:07 +0000979 offset = 0;
drh2af926b2001-05-15 00:39:25 +0000980 amt -= a;
981 zBuf += a;
drh2aa679f2001-06-25 02:11:07 +0000982 }else{
983 offset -= OVERFLOW_SIZE;
drh2af926b2001-05-15 00:39:25 +0000984 }
985 sqlitepager_unref(pOvfl);
986 }
987 return amt==0 ? SQLITE_OK : SQLITE_CORRUPT;
988}
989
drh72f82862001-05-24 21:06:34 +0000990/*
drh5e00f6c2001-09-13 13:46:56 +0000991** Read part of the key associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +0000992** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +0000993** begins at "offset". The number of bytes actually read is
994** returned. The amount returned will be smaller than the
995** amount requested if there are not enough bytes in the key
996** to satisfy the request.
drh72f82862001-05-24 21:06:34 +0000997*/
998int sqliteBtreeKey(BtCursor *pCur, int offset, int amt, char *zBuf){
999 Cell *pCell;
1000 MemPage *pPage;
drha059ad02001-04-17 20:09:11 +00001001
drh5e00f6c2001-09-13 13:46:56 +00001002 if( amt<0 ) return 0;
1003 if( offset<0 ) return 0;
1004 if( amt==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001005 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001006 if( pPage==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001007 if( pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +00001008 return 0;
drh72f82862001-05-24 21:06:34 +00001009 }
drh5e2f8b92001-05-28 00:41:15 +00001010 pCell = pPage->apCell[pCur->idx];
drh3b7511c2001-05-26 13:15:44 +00001011 if( amt+offset > pCell->h.nKey ){
drh5e00f6c2001-09-13 13:46:56 +00001012 amt = pCell->h.nKey - offset;
1013 if( amt<=0 ){
1014 return 0;
1015 }
drhbd03cae2001-06-02 02:40:57 +00001016 }
drh5e00f6c2001-09-13 13:46:56 +00001017 getPayload(pCur, offset, amt, zBuf);
1018 return amt;
drh72f82862001-05-24 21:06:34 +00001019}
1020
1021/*
drhbd03cae2001-06-02 02:40:57 +00001022** Set *pSize to the number of bytes of data in the entry the
1023** cursor currently points to. Always return SQLITE_OK.
1024** Failure is not possible. If the cursor is not currently
1025** pointing to an entry (which can happen, for example, if
1026** the database is empty) then *pSize is set to 0.
drh72f82862001-05-24 21:06:34 +00001027*/
1028int sqliteBtreeDataSize(BtCursor *pCur, int *pSize){
1029 Cell *pCell;
1030 MemPage *pPage;
1031
1032 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001033 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh72f82862001-05-24 21:06:34 +00001034 *pSize = 0;
1035 }else{
drh5e2f8b92001-05-28 00:41:15 +00001036 pCell = pPage->apCell[pCur->idx];
drh3b7511c2001-05-26 13:15:44 +00001037 *pSize = pCell->h.nData;
drh72f82862001-05-24 21:06:34 +00001038 }
1039 return SQLITE_OK;
1040}
1041
1042/*
drh5e00f6c2001-09-13 13:46:56 +00001043** Read part of the data associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +00001044** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +00001045** begins at "offset". The number of bytes actually read is
1046** returned. The amount returned will be smaller than the
1047** amount requested if there are not enough bytes in the data
1048** to satisfy the request.
drh72f82862001-05-24 21:06:34 +00001049*/
1050int sqliteBtreeData(BtCursor *pCur, int offset, int amt, char *zBuf){
1051 Cell *pCell;
1052 MemPage *pPage;
1053
drh5e00f6c2001-09-13 13:46:56 +00001054 if( amt<0 ) return 0;
1055 if( offset<0 ) return 0;
1056 if( amt==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001057 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001058 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +00001059 return 0;
drh72f82862001-05-24 21:06:34 +00001060 }
drh5e2f8b92001-05-28 00:41:15 +00001061 pCell = pPage->apCell[pCur->idx];
drhbd03cae2001-06-02 02:40:57 +00001062 if( amt+offset > pCell->h.nData ){
drh5e00f6c2001-09-13 13:46:56 +00001063 amt = pCell->h.nData - offset;
1064 if( amt<=0 ){
1065 return 0;
1066 }
drhbd03cae2001-06-02 02:40:57 +00001067 }
drh5e00f6c2001-09-13 13:46:56 +00001068 getPayload(pCur, offset + pCell->h.nKey, amt, zBuf);
1069 return amt;
drh72f82862001-05-24 21:06:34 +00001070}
drha059ad02001-04-17 20:09:11 +00001071
drh2af926b2001-05-15 00:39:25 +00001072/*
1073** Compare the key for the entry that pCur points to against the
1074** given key (pKey,nKeyOrig). Put the comparison result in *pResult.
1075** The result is negative if pCur<pKey, zero if they are equal and
1076** positive if pCur>pKey.
1077**
1078** SQLITE_OK is returned on success. If part of the cursor key
1079** is on overflow pages and we are unable to access those overflow
1080** pages, then some other value might be returned to indicate the
1081** reason for the error.
1082*/
drh5c4d9702001-08-20 00:33:58 +00001083static int compareKey(
1084 BtCursor *pCur, /* Points to the entry against which we are comparing */
1085 const char *pKey, /* The comparison key */
1086 int nKeyOrig, /* Number of bytes in the comparison key */
1087 int *pResult /* Write the comparison results here */
1088){
drh2af926b2001-05-15 00:39:25 +00001089 Pgno nextPage;
1090 int nKey = nKeyOrig;
drh8c42ca92001-06-22 19:15:00 +00001091 int n, c, rc;
drh2af926b2001-05-15 00:39:25 +00001092 Cell *pCell;
1093
1094 assert( pCur->pPage );
1095 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drhbd03cae2001-06-02 02:40:57 +00001096 pCell = pCur->pPage->apCell[pCur->idx];
drh3b7511c2001-05-26 13:15:44 +00001097 if( nKey > pCell->h.nKey ){
1098 nKey = pCell->h.nKey;
drh2af926b2001-05-15 00:39:25 +00001099 }
1100 n = nKey;
1101 if( n>MX_LOCAL_PAYLOAD ){
1102 n = MX_LOCAL_PAYLOAD;
1103 }
drh5e2f8b92001-05-28 00:41:15 +00001104 c = memcmp(pCell->aPayload, pKey, n);
drh2af926b2001-05-15 00:39:25 +00001105 if( c!=0 ){
1106 *pResult = c;
1107 return SQLITE_OK;
1108 }
1109 pKey += n;
1110 nKey -= n;
drh3b7511c2001-05-26 13:15:44 +00001111 nextPage = pCell->ovfl;
drh2af926b2001-05-15 00:39:25 +00001112 while( nKey>0 ){
1113 OverflowPage *pOvfl;
1114 if( nextPage==0 ){
1115 return SQLITE_CORRUPT;
1116 }
drh8c42ca92001-06-22 19:15:00 +00001117 rc = sqlitepager_get(pCur->pBt->pPager, nextPage, (void**)&pOvfl);
drh72f82862001-05-24 21:06:34 +00001118 if( rc ){
drh2af926b2001-05-15 00:39:25 +00001119 return rc;
1120 }
drh14acc042001-06-10 19:56:58 +00001121 nextPage = pOvfl->iNext;
drh2af926b2001-05-15 00:39:25 +00001122 n = nKey;
1123 if( n>OVERFLOW_SIZE ){
1124 n = OVERFLOW_SIZE;
1125 }
drh5e2f8b92001-05-28 00:41:15 +00001126 c = memcmp(pOvfl->aPayload, pKey, n);
drh2af926b2001-05-15 00:39:25 +00001127 sqlitepager_unref(pOvfl);
1128 if( c!=0 ){
1129 *pResult = c;
1130 return SQLITE_OK;
1131 }
1132 nKey -= n;
1133 pKey += n;
1134 }
drh3b7511c2001-05-26 13:15:44 +00001135 c = pCell->h.nKey - nKeyOrig;
drh2af926b2001-05-15 00:39:25 +00001136 *pResult = c;
1137 return SQLITE_OK;
1138}
1139
drh72f82862001-05-24 21:06:34 +00001140/*
1141** Move the cursor down to a new child page.
1142*/
drh5e2f8b92001-05-28 00:41:15 +00001143static int moveToChild(BtCursor *pCur, int newPgno){
drh72f82862001-05-24 21:06:34 +00001144 int rc;
1145 MemPage *pNewPage;
1146
drh8c42ca92001-06-22 19:15:00 +00001147 rc = sqlitepager_get(pCur->pBt->pPager, newPgno, (void**)&pNewPage);
drh6019e162001-07-02 17:51:45 +00001148 if( rc ) return rc;
1149 rc = initPage(pNewPage, newPgno, pCur->pPage);
1150 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001151 sqlitepager_unref(pCur->pPage);
1152 pCur->pPage = pNewPage;
1153 pCur->idx = 0;
1154 return SQLITE_OK;
1155}
1156
1157/*
drh5e2f8b92001-05-28 00:41:15 +00001158** Move the cursor up to the parent page.
1159**
1160** pCur->idx is set to the cell index that contains the pointer
1161** to the page we are coming from. If we are coming from the
1162** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00001163** the largest cell index.
drh72f82862001-05-24 21:06:34 +00001164*/
drh5e2f8b92001-05-28 00:41:15 +00001165static int moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001166 Pgno oldPgno;
1167 MemPage *pParent;
drh8c42ca92001-06-22 19:15:00 +00001168 int i;
drh72f82862001-05-24 21:06:34 +00001169 pParent = pCur->pPage->pParent;
drhbd03cae2001-06-02 02:40:57 +00001170 if( pParent==0 ) return SQLITE_INTERNAL;
drh72f82862001-05-24 21:06:34 +00001171 oldPgno = sqlitepager_pagenumber(pCur->pPage);
drh72f82862001-05-24 21:06:34 +00001172 sqlitepager_ref(pParent);
1173 sqlitepager_unref(pCur->pPage);
1174 pCur->pPage = pParent;
drh8c42ca92001-06-22 19:15:00 +00001175 pCur->idx = pParent->nCell;
1176 for(i=0; i<pParent->nCell; i++){
1177 if( pParent->apCell[i]->h.leftChild==oldPgno ){
drh72f82862001-05-24 21:06:34 +00001178 pCur->idx = i;
1179 break;
1180 }
1181 }
drh5e2f8b92001-05-28 00:41:15 +00001182 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00001183}
1184
1185/*
1186** Move the cursor to the root page
1187*/
drh5e2f8b92001-05-28 00:41:15 +00001188static int moveToRoot(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001189 MemPage *pNew;
drhbd03cae2001-06-02 02:40:57 +00001190 int rc;
1191
drh8c42ca92001-06-22 19:15:00 +00001192 rc = sqlitepager_get(pCur->pBt->pPager, pCur->pgnoRoot, (void**)&pNew);
drhbd03cae2001-06-02 02:40:57 +00001193 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00001194 rc = initPage(pNew, pCur->pgnoRoot, 0);
1195 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001196 sqlitepager_unref(pCur->pPage);
1197 pCur->pPage = pNew;
1198 pCur->idx = 0;
1199 return SQLITE_OK;
1200}
drh2af926b2001-05-15 00:39:25 +00001201
drh5e2f8b92001-05-28 00:41:15 +00001202/*
1203** Move the cursor down to the left-most leaf entry beneath the
1204** entry to which it is currently pointing.
1205*/
1206static int moveToLeftmost(BtCursor *pCur){
1207 Pgno pgno;
1208 int rc;
1209
1210 while( (pgno = pCur->pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
1211 rc = moveToChild(pCur, pgno);
1212 if( rc ) return rc;
1213 }
1214 return SQLITE_OK;
1215}
1216
drh5e00f6c2001-09-13 13:46:56 +00001217/* Move the cursor to the first entry in the table. Return SQLITE_OK
1218** on success. Set *pRes to 0 if the cursor actually points to something
1219** or set *pRes to 1 if the table is empty and there is no first element.
1220*/
1221int sqliteBtreeFirst(BtCursor *pCur, int *pRes){
1222 int rc;
drhecdc7532001-09-23 02:35:53 +00001223 if( pCur->pPage==0 ) return SQLITE_ABORT;
drh5e00f6c2001-09-13 13:46:56 +00001224 rc = moveToRoot(pCur);
1225 if( rc ) return rc;
1226 if( pCur->pPage->nCell==0 ){
1227 *pRes = 1;
1228 return SQLITE_OK;
1229 }
1230 *pRes = 0;
1231 rc = moveToLeftmost(pCur);
1232 return rc;
1233}
drh5e2f8b92001-05-28 00:41:15 +00001234
drha059ad02001-04-17 20:09:11 +00001235/* Move the cursor so that it points to an entry near pKey.
drh72f82862001-05-24 21:06:34 +00001236** Return a success code.
1237**
drh5e2f8b92001-05-28 00:41:15 +00001238** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00001239** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00001240** were present. The cursor might point to an entry that comes
1241** before or after the key.
1242**
drhbd03cae2001-06-02 02:40:57 +00001243** The result of comparing the key with the entry to which the
1244** cursor is left pointing is stored in pCur->iMatch. The same
1245** value is also written to *pRes if pRes!=NULL. The meaning of
1246** this value is as follows:
1247**
1248** *pRes<0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001249** is smaller than pKey.
drhbd03cae2001-06-02 02:40:57 +00001250**
1251** *pRes==0 The cursor is left pointing at an entry that
1252** exactly matches pKey.
1253**
1254** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001255** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00001256*/
drh5c4d9702001-08-20 00:33:58 +00001257int sqliteBtreeMoveto(BtCursor *pCur, const void *pKey, int nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00001258 int rc;
drhecdc7532001-09-23 02:35:53 +00001259 if( pCur->pPage==0 ) return SQLITE_ABORT;
drh7c717f72001-06-24 20:39:41 +00001260 pCur->bSkipNext = 0;
drh5e2f8b92001-05-28 00:41:15 +00001261 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00001262 if( rc ) return rc;
1263 for(;;){
1264 int lwr, upr;
1265 Pgno chldPg;
1266 MemPage *pPage = pCur->pPage;
drh8b2f49b2001-06-08 00:21:52 +00001267 int c = -1;
drh72f82862001-05-24 21:06:34 +00001268 lwr = 0;
1269 upr = pPage->nCell-1;
1270 while( lwr<=upr ){
drh72f82862001-05-24 21:06:34 +00001271 pCur->idx = (lwr+upr)/2;
1272 rc = compareKey(pCur, pKey, nKey, &c);
1273 if( rc ) return rc;
1274 if( c==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001275 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001276 if( pRes ) *pRes = 0;
1277 return SQLITE_OK;
1278 }
1279 if( c<0 ){
1280 lwr = pCur->idx+1;
1281 }else{
1282 upr = pCur->idx-1;
1283 }
1284 }
1285 assert( lwr==upr+1 );
1286 if( lwr>=pPage->nCell ){
drh14acc042001-06-10 19:56:58 +00001287 chldPg = pPage->u.hdr.rightChild;
drh72f82862001-05-24 21:06:34 +00001288 }else{
drh5e2f8b92001-05-28 00:41:15 +00001289 chldPg = pPage->apCell[lwr]->h.leftChild;
drh72f82862001-05-24 21:06:34 +00001290 }
1291 if( chldPg==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001292 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001293 if( pRes ) *pRes = c;
1294 return SQLITE_OK;
1295 }
drh5e2f8b92001-05-28 00:41:15 +00001296 rc = moveToChild(pCur, chldPg);
drh72f82862001-05-24 21:06:34 +00001297 if( rc ) return rc;
1298 }
drhbd03cae2001-06-02 02:40:57 +00001299 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00001300}
1301
1302/*
drhbd03cae2001-06-02 02:40:57 +00001303** Advance the cursor to the next entry in the database. If
1304** successful and pRes!=NULL then set *pRes=0. If the cursor
1305** was already pointing to the last entry in the database before
1306** this routine was called, then set *pRes=1 if pRes!=NULL.
drh72f82862001-05-24 21:06:34 +00001307*/
1308int sqliteBtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00001309 int rc;
drhecdc7532001-09-23 02:35:53 +00001310 if( pCur->pPage==0 ){
1311 return SQLITE_ABORT;
1312 }
drh5e2f8b92001-05-28 00:41:15 +00001313 if( pCur->bSkipNext ){
1314 pCur->bSkipNext = 0;
drh72f82862001-05-24 21:06:34 +00001315 if( pRes ) *pRes = 0;
1316 return SQLITE_OK;
1317 }
drh72f82862001-05-24 21:06:34 +00001318 pCur->idx++;
drh5e2f8b92001-05-28 00:41:15 +00001319 if( pCur->idx>=pCur->pPage->nCell ){
drh8c42ca92001-06-22 19:15:00 +00001320 if( pCur->pPage->u.hdr.rightChild ){
1321 rc = moveToChild(pCur, pCur->pPage->u.hdr.rightChild);
drh5e2f8b92001-05-28 00:41:15 +00001322 if( rc ) return rc;
1323 rc = moveToLeftmost(pCur);
1324 if( rc ) return rc;
1325 if( pRes ) *pRes = 0;
drh72f82862001-05-24 21:06:34 +00001326 return SQLITE_OK;
1327 }
drh5e2f8b92001-05-28 00:41:15 +00001328 do{
drh8c42ca92001-06-22 19:15:00 +00001329 if( pCur->pPage->pParent==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001330 if( pRes ) *pRes = 1;
1331 return SQLITE_OK;
1332 }
1333 rc = moveToParent(pCur);
1334 if( rc ) return rc;
1335 }while( pCur->idx>=pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00001336 if( pRes ) *pRes = 0;
1337 return SQLITE_OK;
1338 }
drh5e2f8b92001-05-28 00:41:15 +00001339 rc = moveToLeftmost(pCur);
1340 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001341 if( pRes ) *pRes = 0;
1342 return SQLITE_OK;
1343}
1344
drh3b7511c2001-05-26 13:15:44 +00001345/*
1346** Allocate a new page from the database file.
1347**
1348** The new page is marked as dirty. (In other words, sqlitepager_write()
1349** has already been called on the new page.) The new page has also
1350** been referenced and the calling routine is responsible for calling
1351** sqlitepager_unref() on the new page when it is done.
1352**
1353** SQLITE_OK is returned on success. Any other return value indicates
1354** an error. *ppPage and *pPgno are undefined in the event of an error.
1355** Do not invoke sqlitepager_unref() on *ppPage if an error is returned.
1356*/
1357static int allocatePage(Btree *pBt, MemPage **ppPage, Pgno *pPgno){
drhbd03cae2001-06-02 02:40:57 +00001358 PageOne *pPage1 = pBt->page1;
drh8c42ca92001-06-22 19:15:00 +00001359 int rc;
drh3b7511c2001-05-26 13:15:44 +00001360 if( pPage1->freeList ){
1361 OverflowPage *pOvfl;
1362 rc = sqlitepager_write(pPage1);
1363 if( rc ) return rc;
1364 *pPgno = pPage1->freeList;
drh8c42ca92001-06-22 19:15:00 +00001365 rc = sqlitepager_get(pBt->pPager, pPage1->freeList, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001366 if( rc ) return rc;
1367 rc = sqlitepager_write(pOvfl);
1368 if( rc ){
1369 sqlitepager_unref(pOvfl);
1370 return rc;
1371 }
drh14acc042001-06-10 19:56:58 +00001372 pPage1->freeList = pOvfl->iNext;
drh2aa679f2001-06-25 02:11:07 +00001373 pPage1->nFree--;
drh3b7511c2001-05-26 13:15:44 +00001374 *ppPage = (MemPage*)pOvfl;
1375 }else{
drh2aa679f2001-06-25 02:11:07 +00001376 *pPgno = sqlitepager_pagecount(pBt->pPager) + 1;
drh8c42ca92001-06-22 19:15:00 +00001377 rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
drh3b7511c2001-05-26 13:15:44 +00001378 if( rc ) return rc;
1379 rc = sqlitepager_write(*ppPage);
1380 }
1381 return rc;
1382}
1383
1384/*
1385** Add a page of the database file to the freelist. Either pgno or
1386** pPage but not both may be 0.
drh5e2f8b92001-05-28 00:41:15 +00001387**
drhdd793422001-06-28 01:54:48 +00001388** sqlitepager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00001389*/
1390static int freePage(Btree *pBt, void *pPage, Pgno pgno){
drhbd03cae2001-06-02 02:40:57 +00001391 PageOne *pPage1 = pBt->page1;
drh3b7511c2001-05-26 13:15:44 +00001392 OverflowPage *pOvfl = (OverflowPage*)pPage;
1393 int rc;
drhdd793422001-06-28 01:54:48 +00001394 int needUnref = 0;
1395 MemPage *pMemPage;
drh8b2f49b2001-06-08 00:21:52 +00001396
drh3b7511c2001-05-26 13:15:44 +00001397 if( pgno==0 ){
1398 assert( pOvfl!=0 );
1399 pgno = sqlitepager_pagenumber(pOvfl);
1400 }
drh2aa679f2001-06-25 02:11:07 +00001401 assert( pgno>2 );
drh3b7511c2001-05-26 13:15:44 +00001402 rc = sqlitepager_write(pPage1);
1403 if( rc ){
1404 return rc;
1405 }
1406 if( pOvfl==0 ){
1407 assert( pgno>0 );
drh8c42ca92001-06-22 19:15:00 +00001408 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001409 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001410 needUnref = 1;
drh3b7511c2001-05-26 13:15:44 +00001411 }
1412 rc = sqlitepager_write(pOvfl);
1413 if( rc ){
drhdd793422001-06-28 01:54:48 +00001414 if( needUnref ) sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001415 return rc;
1416 }
drh14acc042001-06-10 19:56:58 +00001417 pOvfl->iNext = pPage1->freeList;
drh3b7511c2001-05-26 13:15:44 +00001418 pPage1->freeList = pgno;
drh2aa679f2001-06-25 02:11:07 +00001419 pPage1->nFree++;
drh5e2f8b92001-05-28 00:41:15 +00001420 memset(pOvfl->aPayload, 0, OVERFLOW_SIZE);
drhdd793422001-06-28 01:54:48 +00001421 pMemPage = (MemPage*)pPage;
1422 pMemPage->isInit = 0;
1423 if( pMemPage->pParent ){
1424 sqlitepager_unref(pMemPage->pParent);
1425 pMemPage->pParent = 0;
1426 }
1427 if( needUnref ) rc = sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001428 return rc;
1429}
1430
1431/*
1432** Erase all the data out of a cell. This involves returning overflow
1433** pages back the freelist.
1434*/
1435static int clearCell(Btree *pBt, Cell *pCell){
1436 Pager *pPager = pBt->pPager;
1437 OverflowPage *pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001438 Pgno ovfl, nextOvfl;
1439 int rc;
1440
drh5e2f8b92001-05-28 00:41:15 +00001441 if( pCell->h.nKey + pCell->h.nData <= MX_LOCAL_PAYLOAD ){
1442 return SQLITE_OK;
1443 }
drh3b7511c2001-05-26 13:15:44 +00001444 ovfl = pCell->ovfl;
1445 pCell->ovfl = 0;
1446 while( ovfl ){
drh8c42ca92001-06-22 19:15:00 +00001447 rc = sqlitepager_get(pPager, ovfl, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001448 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00001449 nextOvfl = pOvfl->iNext;
drhbd03cae2001-06-02 02:40:57 +00001450 rc = freePage(pBt, pOvfl, ovfl);
1451 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001452 sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001453 ovfl = nextOvfl;
drh3b7511c2001-05-26 13:15:44 +00001454 }
drh5e2f8b92001-05-28 00:41:15 +00001455 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00001456}
1457
1458/*
1459** Create a new cell from key and data. Overflow pages are allocated as
1460** necessary and linked to this cell.
1461*/
1462static int fillInCell(
1463 Btree *pBt, /* The whole Btree. Needed to allocate pages */
1464 Cell *pCell, /* Populate this Cell structure */
drh5c4d9702001-08-20 00:33:58 +00001465 const void *pKey, int nKey, /* The key */
1466 const void *pData,int nData /* The data */
drh3b7511c2001-05-26 13:15:44 +00001467){
drhdd793422001-06-28 01:54:48 +00001468 OverflowPage *pOvfl, *pPrior;
drh3b7511c2001-05-26 13:15:44 +00001469 Pgno *pNext;
1470 int spaceLeft;
drh8c42ca92001-06-22 19:15:00 +00001471 int n, rc;
drh3b7511c2001-05-26 13:15:44 +00001472 int nPayload;
drh5c4d9702001-08-20 00:33:58 +00001473 const char *pPayload;
drh3b7511c2001-05-26 13:15:44 +00001474 char *pSpace;
1475
drh5e2f8b92001-05-28 00:41:15 +00001476 pCell->h.leftChild = 0;
drh3b7511c2001-05-26 13:15:44 +00001477 pCell->h.nKey = nKey;
1478 pCell->h.nData = nData;
1479 pCell->h.iNext = 0;
1480
1481 pNext = &pCell->ovfl;
drh5e2f8b92001-05-28 00:41:15 +00001482 pSpace = pCell->aPayload;
drh3b7511c2001-05-26 13:15:44 +00001483 spaceLeft = MX_LOCAL_PAYLOAD;
1484 pPayload = pKey;
1485 pKey = 0;
1486 nPayload = nKey;
drhdd793422001-06-28 01:54:48 +00001487 pPrior = 0;
drh3b7511c2001-05-26 13:15:44 +00001488 while( nPayload>0 ){
1489 if( spaceLeft==0 ){
drh8c42ca92001-06-22 19:15:00 +00001490 rc = allocatePage(pBt, (MemPage**)&pOvfl, pNext);
drh3b7511c2001-05-26 13:15:44 +00001491 if( rc ){
1492 *pNext = 0;
drhdd793422001-06-28 01:54:48 +00001493 }
1494 if( pPrior ) sqlitepager_unref(pPrior);
1495 if( rc ){
drh5e2f8b92001-05-28 00:41:15 +00001496 clearCell(pBt, pCell);
drh3b7511c2001-05-26 13:15:44 +00001497 return rc;
1498 }
drhdd793422001-06-28 01:54:48 +00001499 pPrior = pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001500 spaceLeft = OVERFLOW_SIZE;
drh5e2f8b92001-05-28 00:41:15 +00001501 pSpace = pOvfl->aPayload;
drh8c42ca92001-06-22 19:15:00 +00001502 pNext = &pOvfl->iNext;
drh3b7511c2001-05-26 13:15:44 +00001503 }
1504 n = nPayload;
1505 if( n>spaceLeft ) n = spaceLeft;
1506 memcpy(pSpace, pPayload, n);
1507 nPayload -= n;
1508 if( nPayload==0 && pData ){
1509 pPayload = pData;
1510 nPayload = nData;
1511 pData = 0;
1512 }else{
1513 pPayload += n;
1514 }
1515 spaceLeft -= n;
1516 pSpace += n;
1517 }
drhdd793422001-06-28 01:54:48 +00001518 *pNext = 0;
1519 if( pPrior ){
1520 sqlitepager_unref(pPrior);
1521 }
drh3b7511c2001-05-26 13:15:44 +00001522 return SQLITE_OK;
1523}
1524
1525/*
drhbd03cae2001-06-02 02:40:57 +00001526** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00001527** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00001528** pointer in the third argument.
1529*/
1530static void reparentPage(Pager *pPager, Pgno pgno, MemPage *pNewParent){
1531 MemPage *pThis;
1532
drhdd793422001-06-28 01:54:48 +00001533 if( pgno==0 ) return;
1534 assert( pPager!=0 );
drhbd03cae2001-06-02 02:40:57 +00001535 pThis = sqlitepager_lookup(pPager, pgno);
drh6019e162001-07-02 17:51:45 +00001536 if( pThis && pThis->isInit ){
drhdd793422001-06-28 01:54:48 +00001537 if( pThis->pParent!=pNewParent ){
1538 if( pThis->pParent ) sqlitepager_unref(pThis->pParent);
1539 pThis->pParent = pNewParent;
1540 if( pNewParent ) sqlitepager_ref(pNewParent);
1541 }
1542 sqlitepager_unref(pThis);
drhbd03cae2001-06-02 02:40:57 +00001543 }
1544}
1545
1546/*
1547** Reparent all children of the given page to be the given page.
1548** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00001549** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00001550**
1551** This routine gets called after you memcpy() one page into
1552** another.
1553*/
drh8c42ca92001-06-22 19:15:00 +00001554static void reparentChildPages(Pager *pPager, MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00001555 int i;
1556 for(i=0; i<pPage->nCell; i++){
drh8c42ca92001-06-22 19:15:00 +00001557 reparentPage(pPager, pPage->apCell[i]->h.leftChild, pPage);
drhbd03cae2001-06-02 02:40:57 +00001558 }
drh14acc042001-06-10 19:56:58 +00001559 reparentPage(pPager, pPage->u.hdr.rightChild, pPage);
1560}
1561
1562/*
1563** Remove the i-th cell from pPage. This routine effects pPage only.
1564** The cell content is not freed or deallocated. It is assumed that
1565** the cell content has been copied someplace else. This routine just
1566** removes the reference to the cell from pPage.
1567**
1568** "sz" must be the number of bytes in the cell.
1569**
1570** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001571** Only the pPage->apCell[] array is important. The relinkCellList()
1572** routine will be called soon after this routine in order to rebuild
1573** the linked list.
drh14acc042001-06-10 19:56:58 +00001574*/
drh8c42ca92001-06-22 19:15:00 +00001575static void dropCell(MemPage *pPage, int idx, int sz){
drh14acc042001-06-10 19:56:58 +00001576 int j;
drh8c42ca92001-06-22 19:15:00 +00001577 assert( idx>=0 && idx<pPage->nCell );
1578 assert( sz==cellSize(pPage->apCell[idx]) );
drh6019e162001-07-02 17:51:45 +00001579 assert( sqlitepager_iswriteable(pPage) );
drh7c717f72001-06-24 20:39:41 +00001580 freeSpace(pPage, Addr(pPage->apCell[idx]) - Addr(pPage), sz);
1581 for(j=idx; j<pPage->nCell-1; j++){
drh14acc042001-06-10 19:56:58 +00001582 pPage->apCell[j] = pPage->apCell[j+1];
1583 }
1584 pPage->nCell--;
1585}
1586
1587/*
1588** Insert a new cell on pPage at cell index "i". pCell points to the
1589** content of the cell.
1590**
1591** If the cell content will fit on the page, then put it there. If it
1592** will not fit, then just make pPage->apCell[i] point to the content
1593** and set pPage->isOverfull.
1594**
1595** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001596** Only the pPage->apCell[] array is important. The relinkCellList()
1597** routine will be called soon after this routine in order to rebuild
1598** the linked list.
drh14acc042001-06-10 19:56:58 +00001599*/
1600static void insertCell(MemPage *pPage, int i, Cell *pCell, int sz){
1601 int idx, j;
1602 assert( i>=0 && i<=pPage->nCell );
1603 assert( sz==cellSize(pCell) );
drh6019e162001-07-02 17:51:45 +00001604 assert( sqlitepager_iswriteable(pPage) );
drh2aa679f2001-06-25 02:11:07 +00001605 idx = allocateSpace(pPage, sz);
drh14acc042001-06-10 19:56:58 +00001606 for(j=pPage->nCell; j>i; j--){
1607 pPage->apCell[j] = pPage->apCell[j-1];
1608 }
1609 pPage->nCell++;
drh14acc042001-06-10 19:56:58 +00001610 if( idx<=0 ){
1611 pPage->isOverfull = 1;
1612 pPage->apCell[i] = pCell;
1613 }else{
1614 memcpy(&pPage->u.aDisk[idx], pCell, sz);
drh8c42ca92001-06-22 19:15:00 +00001615 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[idx];
drh14acc042001-06-10 19:56:58 +00001616 }
1617}
1618
1619/*
1620** Rebuild the linked list of cells on a page so that the cells
drh8c42ca92001-06-22 19:15:00 +00001621** occur in the order specified by the pPage->apCell[] array.
1622** Invoke this routine once to repair damage after one or more
1623** invocations of either insertCell() or dropCell().
drh14acc042001-06-10 19:56:58 +00001624*/
1625static void relinkCellList(MemPage *pPage){
1626 int i;
1627 u16 *pIdx;
drh6019e162001-07-02 17:51:45 +00001628 assert( sqlitepager_iswriteable(pPage) );
drh14acc042001-06-10 19:56:58 +00001629 pIdx = &pPage->u.hdr.firstCell;
1630 for(i=0; i<pPage->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00001631 int idx = Addr(pPage->apCell[i]) - Addr(pPage);
drh8c42ca92001-06-22 19:15:00 +00001632 assert( idx>0 && idx<SQLITE_PAGE_SIZE );
drh14acc042001-06-10 19:56:58 +00001633 *pIdx = idx;
1634 pIdx = &pPage->apCell[i]->h.iNext;
1635 }
1636 *pIdx = 0;
1637}
1638
1639/*
1640** Make a copy of the contents of pFrom into pTo. The pFrom->apCell[]
drh5e00f6c2001-09-13 13:46:56 +00001641** pointers that point into pFrom->u.aDisk[] must be adjusted to point
drhdd793422001-06-28 01:54:48 +00001642** into pTo->u.aDisk[] instead. But some pFrom->apCell[] entries might
drh14acc042001-06-10 19:56:58 +00001643** not point to pFrom->u.aDisk[]. Those are unchanged.
1644*/
1645static void copyPage(MemPage *pTo, MemPage *pFrom){
1646 uptr from, to;
1647 int i;
1648 memcpy(pTo->u.aDisk, pFrom->u.aDisk, SQLITE_PAGE_SIZE);
drhdd793422001-06-28 01:54:48 +00001649 pTo->pParent = 0;
drh14acc042001-06-10 19:56:58 +00001650 pTo->isInit = 1;
1651 pTo->nCell = pFrom->nCell;
1652 pTo->nFree = pFrom->nFree;
1653 pTo->isOverfull = pFrom->isOverfull;
drh7c717f72001-06-24 20:39:41 +00001654 to = Addr(pTo);
1655 from = Addr(pFrom);
drh14acc042001-06-10 19:56:58 +00001656 for(i=0; i<pTo->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00001657 uptr x = Addr(pFrom->apCell[i]);
drh8c42ca92001-06-22 19:15:00 +00001658 if( x>from && x<from+SQLITE_PAGE_SIZE ){
1659 *((uptr*)&pTo->apCell[i]) = x + to - from;
drhdd793422001-06-28 01:54:48 +00001660 }else{
1661 pTo->apCell[i] = pFrom->apCell[i];
drh14acc042001-06-10 19:56:58 +00001662 }
1663 }
drhbd03cae2001-06-02 02:40:57 +00001664}
1665
1666/*
drh8b2f49b2001-06-08 00:21:52 +00001667** This routine redistributes Cells on pPage and up to two siblings
1668** of pPage so that all pages have about the same amount of free space.
drh14acc042001-06-10 19:56:58 +00001669** Usually one sibling on either side of pPage is used in the balancing,
drh8b2f49b2001-06-08 00:21:52 +00001670** though both siblings might come from one side if pPage is the first
1671** or last child of its parent. If pPage has fewer than two siblings
1672** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00001673** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00001674**
1675** The number of siblings of pPage might be increased or decreased by
drh8c42ca92001-06-22 19:15:00 +00001676** one in an effort to keep pages between 66% and 100% full. The root page
1677** is special and is allowed to be less than 66% full. If pPage is
1678** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00001679** or decreased by one, as necessary, to keep the root page from being
1680** overfull or empty.
1681**
drh14acc042001-06-10 19:56:58 +00001682** This routine calls relinkCellList() on its input page regardless of
1683** whether or not it does any real balancing. Client routines will typically
1684** invoke insertCell() or dropCell() before calling this routine, so we
1685** need to call relinkCellList() to clean up the mess that those other
1686** routines left behind.
1687**
1688** pCur is left pointing to the same cell as when this routine was called
drh8c42ca92001-06-22 19:15:00 +00001689** even if that cell gets moved to a different page. pCur may be NULL.
1690** Set the pCur parameter to NULL if you do not care about keeping track
1691** of a cell as that will save this routine the work of keeping track of it.
drh14acc042001-06-10 19:56:58 +00001692**
drh8b2f49b2001-06-08 00:21:52 +00001693** Note that when this routine is called, some of the Cells on pPage
drh14acc042001-06-10 19:56:58 +00001694** might not actually be stored in pPage->u.aDisk[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00001695** if the page is overfull. Part of the job of this routine is to
drh14acc042001-06-10 19:56:58 +00001696** make sure all Cells for pPage once again fit in pPage->u.aDisk[].
1697**
drh8c42ca92001-06-22 19:15:00 +00001698** In the course of balancing the siblings of pPage, the parent of pPage
1699** might become overfull or underfull. If that happens, then this routine
1700** is called recursively on the parent.
1701**
drh5e00f6c2001-09-13 13:46:56 +00001702** If this routine fails for any reason, it might leave the database
1703** in a corrupted state. So if this routine fails, the database should
1704** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00001705*/
drh14acc042001-06-10 19:56:58 +00001706static int balance(Btree *pBt, MemPage *pPage, BtCursor *pCur){
drh8b2f49b2001-06-08 00:21:52 +00001707 MemPage *pParent; /* The parent of pPage */
drh14acc042001-06-10 19:56:58 +00001708 MemPage *apOld[3]; /* pPage and up to two siblings */
drh8b2f49b2001-06-08 00:21:52 +00001709 Pgno pgnoOld[3]; /* Page numbers for each page in apOld[] */
drh14acc042001-06-10 19:56:58 +00001710 MemPage *apNew[4]; /* pPage and up to 3 siblings after balancing */
1711 Pgno pgnoNew[4]; /* Page numbers for each page in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00001712 int idxDiv[3]; /* Indices of divider cells in pParent */
1713 Cell *apDiv[3]; /* Divider cells in pParent */
1714 int nCell; /* Number of cells in apCell[] */
1715 int nOld; /* Number of pages in apOld[] */
1716 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00001717 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00001718 int i, j, k; /* Loop counters */
1719 int idx; /* Index of pPage in pParent->apCell[] */
1720 int nxDiv; /* Next divider slot in pParent->apCell[] */
1721 int rc; /* The return code */
1722 int iCur; /* apCell[iCur] is the cell of the cursor */
drh5edc3122001-09-13 21:53:09 +00001723 MemPage *pOldCurPage; /* The cursor originally points to this page */
drh8c42ca92001-06-22 19:15:00 +00001724 int totalSize; /* Total bytes for all cells */
drh6019e162001-07-02 17:51:45 +00001725 int subtotal; /* Subtotal of bytes in cells on one page */
1726 int cntNew[4]; /* Index in apCell[] of cell after i-th page */
1727 int szNew[4]; /* Combined size of cells place on i-th page */
drh9ca7d3b2001-06-28 11:50:21 +00001728 MemPage *extraUnref = 0; /* A page that needs to be unref-ed */
drh8c42ca92001-06-22 19:15:00 +00001729 Pgno pgno; /* Page number */
drh14acc042001-06-10 19:56:58 +00001730 Cell *apCell[MX_CELL*3+5]; /* All cells from pages being balanceed */
1731 int szCell[MX_CELL*3+5]; /* Local size of all cells */
1732 Cell aTemp[2]; /* Temporary holding area for apDiv[] */
1733 MemPage aOld[3]; /* Temporary copies of pPage and its siblings */
drh8b2f49b2001-06-08 00:21:52 +00001734
drh14acc042001-06-10 19:56:58 +00001735 /*
1736 ** Return without doing any work if pPage is neither overfull nor
1737 ** underfull.
drh8b2f49b2001-06-08 00:21:52 +00001738 */
drh6019e162001-07-02 17:51:45 +00001739 assert( sqlitepager_iswriteable(pPage) );
drha1b351a2001-09-14 16:42:12 +00001740 if( !pPage->isOverfull && pPage->nFree<SQLITE_PAGE_SIZE/2
1741 && pPage->nCell>=2){
drh14acc042001-06-10 19:56:58 +00001742 relinkCellList(pPage);
drh8b2f49b2001-06-08 00:21:52 +00001743 return SQLITE_OK;
1744 }
1745
1746 /*
drh14acc042001-06-10 19:56:58 +00001747 ** Find the parent of the page to be balanceed.
1748 ** If there is no parent, it means this page is the root page and
drh8b2f49b2001-06-08 00:21:52 +00001749 ** special rules apply.
1750 */
drh14acc042001-06-10 19:56:58 +00001751 pParent = pPage->pParent;
drh8b2f49b2001-06-08 00:21:52 +00001752 if( pParent==0 ){
1753 Pgno pgnoChild;
drh8c42ca92001-06-22 19:15:00 +00001754 MemPage *pChild;
drh8b2f49b2001-06-08 00:21:52 +00001755 if( pPage->nCell==0 ){
drh14acc042001-06-10 19:56:58 +00001756 if( pPage->u.hdr.rightChild ){
1757 /*
1758 ** The root page is empty. Copy the one child page
drh8b2f49b2001-06-08 00:21:52 +00001759 ** into the root page and return. This reduces the depth
1760 ** of the BTree by one.
1761 */
drh14acc042001-06-10 19:56:58 +00001762 pgnoChild = pPage->u.hdr.rightChild;
drh8c42ca92001-06-22 19:15:00 +00001763 rc = sqlitepager_get(pBt->pPager, pgnoChild, (void**)&pChild);
drh8b2f49b2001-06-08 00:21:52 +00001764 if( rc ) return rc;
1765 memcpy(pPage, pChild, SQLITE_PAGE_SIZE);
1766 pPage->isInit = 0;
drh6019e162001-07-02 17:51:45 +00001767 rc = initPage(pPage, sqlitepager_pagenumber(pPage), 0);
1768 assert( rc==SQLITE_OK );
drh8b2f49b2001-06-08 00:21:52 +00001769 reparentChildPages(pBt->pPager, pPage);
drh5edc3122001-09-13 21:53:09 +00001770 if( pCur && pCur->pPage==pChild ){
1771 sqlitepager_unref(pChild);
1772 pCur->pPage = pPage;
1773 sqlitepager_ref(pPage);
1774 }
drh8b2f49b2001-06-08 00:21:52 +00001775 freePage(pBt, pChild, pgnoChild);
1776 sqlitepager_unref(pChild);
drhefc251d2001-07-01 22:12:01 +00001777 }else{
1778 relinkCellList(pPage);
drh8b2f49b2001-06-08 00:21:52 +00001779 }
1780 return SQLITE_OK;
1781 }
drh14acc042001-06-10 19:56:58 +00001782 if( !pPage->isOverfull ){
drh8b2f49b2001-06-08 00:21:52 +00001783 /* It is OK for the root page to be less than half full.
1784 */
drh14acc042001-06-10 19:56:58 +00001785 relinkCellList(pPage);
drh8b2f49b2001-06-08 00:21:52 +00001786 return SQLITE_OK;
1787 }
drh14acc042001-06-10 19:56:58 +00001788 /*
1789 ** If we get to here, it means the root page is overfull.
drh8b2f49b2001-06-08 00:21:52 +00001790 ** When this happens, Create a new child page and copy the
1791 ** contents of the root into the child. Then make the root
drh14acc042001-06-10 19:56:58 +00001792 ** page an empty page with rightChild pointing to the new
drh8b2f49b2001-06-08 00:21:52 +00001793 ** child. Then fall thru to the code below which will cause
1794 ** the overfull child page to be split.
1795 */
drh14acc042001-06-10 19:56:58 +00001796 rc = sqlitepager_write(pPage);
1797 if( rc ) return rc;
drh8b2f49b2001-06-08 00:21:52 +00001798 rc = allocatePage(pBt, &pChild, &pgnoChild);
1799 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00001800 assert( sqlitepager_iswriteable(pChild) );
drh14acc042001-06-10 19:56:58 +00001801 copyPage(pChild, pPage);
1802 pChild->pParent = pPage;
drhdd793422001-06-28 01:54:48 +00001803 sqlitepager_ref(pPage);
drh14acc042001-06-10 19:56:58 +00001804 pChild->isOverfull = 1;
drh5edc3122001-09-13 21:53:09 +00001805 if( pCur && pCur->pPage==pPage ){
1806 sqlitepager_unref(pPage);
drh14acc042001-06-10 19:56:58 +00001807 pCur->pPage = pChild;
drh9ca7d3b2001-06-28 11:50:21 +00001808 }else{
1809 extraUnref = pChild;
drh8b2f49b2001-06-08 00:21:52 +00001810 }
drh8b2f49b2001-06-08 00:21:52 +00001811 zeroPage(pPage);
drh14acc042001-06-10 19:56:58 +00001812 pPage->u.hdr.rightChild = pgnoChild;
drh8b2f49b2001-06-08 00:21:52 +00001813 pParent = pPage;
1814 pPage = pChild;
drh8b2f49b2001-06-08 00:21:52 +00001815 }
drh6019e162001-07-02 17:51:45 +00001816 rc = sqlitepager_write(pParent);
1817 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00001818
drh8b2f49b2001-06-08 00:21:52 +00001819 /*
drh14acc042001-06-10 19:56:58 +00001820 ** Find the Cell in the parent page whose h.leftChild points back
1821 ** to pPage. The "idx" variable is the index of that cell. If pPage
1822 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00001823 */
1824 idx = -1;
1825 pgno = sqlitepager_pagenumber(pPage);
1826 for(i=0; i<pParent->nCell; i++){
1827 if( pParent->apCell[i]->h.leftChild==pgno ){
1828 idx = i;
1829 break;
1830 }
1831 }
drhdd793422001-06-28 01:54:48 +00001832 if( idx<0 && pParent->u.hdr.rightChild==pgno ){
1833 idx = pParent->nCell;
drh8b2f49b2001-06-08 00:21:52 +00001834 }
1835 if( idx<0 ){
drh14acc042001-06-10 19:56:58 +00001836 return SQLITE_CORRUPT;
drh8b2f49b2001-06-08 00:21:52 +00001837 }
1838
1839 /*
drh14acc042001-06-10 19:56:58 +00001840 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00001841 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00001842 */
drh14acc042001-06-10 19:56:58 +00001843 nOld = nNew = 0;
1844 sqlitepager_ref(pParent);
1845
1846 /*
1847 ** Find sibling pages to pPage and the Cells in pParent that divide
1848 ** the siblings. An attempt is made to find one sibling on either
1849 ** side of pPage. Both siblings are taken from one side, however, if
1850 ** pPage is either the first or last child of its parent. If pParent
1851 ** has 3 or fewer children then all children of pParent are taken.
1852 */
1853 if( idx==pParent->nCell ){
1854 nxDiv = idx - 2;
drh8b2f49b2001-06-08 00:21:52 +00001855 }else{
drh14acc042001-06-10 19:56:58 +00001856 nxDiv = idx - 1;
drh8b2f49b2001-06-08 00:21:52 +00001857 }
drh14acc042001-06-10 19:56:58 +00001858 if( nxDiv<0 ) nxDiv = 0;
drh8b2f49b2001-06-08 00:21:52 +00001859 nDiv = 0;
drh14acc042001-06-10 19:56:58 +00001860 for(i=0, k=nxDiv; i<3; i++, k++){
1861 if( k<pParent->nCell ){
1862 idxDiv[i] = k;
1863 apDiv[i] = pParent->apCell[k];
drh8b2f49b2001-06-08 00:21:52 +00001864 nDiv++;
1865 pgnoOld[i] = apDiv[i]->h.leftChild;
drh14acc042001-06-10 19:56:58 +00001866 }else if( k==pParent->nCell ){
drh8c42ca92001-06-22 19:15:00 +00001867 pgnoOld[i] = pParent->u.hdr.rightChild;
drh14acc042001-06-10 19:56:58 +00001868 }else{
1869 break;
drh8b2f49b2001-06-08 00:21:52 +00001870 }
drh8c42ca92001-06-22 19:15:00 +00001871 rc = sqlitepager_get(pBt->pPager, pgnoOld[i], (void**)&apOld[i]);
drh14acc042001-06-10 19:56:58 +00001872 if( rc ) goto balance_cleanup;
drh6019e162001-07-02 17:51:45 +00001873 rc = initPage(apOld[i], pgnoOld[i], pParent);
1874 if( rc ) goto balance_cleanup;
drh14acc042001-06-10 19:56:58 +00001875 nOld++;
drh8b2f49b2001-06-08 00:21:52 +00001876 }
1877
1878 /*
drh14acc042001-06-10 19:56:58 +00001879 ** Set iCur to be the index in apCell[] of the cell that the cursor
1880 ** is pointing to. We will need this later on in order to keep the
drh5edc3122001-09-13 21:53:09 +00001881 ** cursor pointing at the same cell. If pCur points to a page that
1882 ** has no involvement with this rebalancing, then set iCur to a large
1883 ** number so that the iCur==j tests always fail in the main cell
1884 ** distribution loop below.
drh14acc042001-06-10 19:56:58 +00001885 */
1886 if( pCur ){
drh5edc3122001-09-13 21:53:09 +00001887 iCur = 0;
1888 for(i=0; i<nOld; i++){
1889 if( pCur->pPage==apOld[i] ){
1890 iCur += pCur->idx;
1891 break;
1892 }
1893 iCur += apOld[i]->nCell;
1894 if( i<nOld-1 && pCur->pPage==pParent && pCur->idx==idxDiv[i] ){
1895 break;
1896 }
1897 iCur++;
drh14acc042001-06-10 19:56:58 +00001898 }
drh5edc3122001-09-13 21:53:09 +00001899 pOldCurPage = pCur->pPage;
drh14acc042001-06-10 19:56:58 +00001900 }
1901
1902 /*
1903 ** Make copies of the content of pPage and its siblings into aOld[].
1904 ** The rest of this function will use data from the copies rather
1905 ** that the original pages since the original pages will be in the
1906 ** process of being overwritten.
1907 */
1908 for(i=0; i<nOld; i++){
1909 copyPage(&aOld[i], apOld[i]);
1910 rc = freePage(pBt, apOld[i], pgnoOld[i]);
1911 if( rc ) goto balance_cleanup;
drhdd793422001-06-28 01:54:48 +00001912 sqlitepager_unref(apOld[i]);
drh14acc042001-06-10 19:56:58 +00001913 apOld[i] = &aOld[i];
1914 }
1915
1916 /*
1917 ** Load pointers to all cells on sibling pages and the divider cells
1918 ** into the local apCell[] array. Make copies of the divider cells
1919 ** into aTemp[] and remove the the divider Cells from pParent.
drh8b2f49b2001-06-08 00:21:52 +00001920 */
1921 nCell = 0;
1922 for(i=0; i<nOld; i++){
1923 MemPage *pOld = apOld[i];
1924 for(j=0; j<pOld->nCell; j++){
drh14acc042001-06-10 19:56:58 +00001925 apCell[nCell] = pOld->apCell[j];
1926 szCell[nCell] = cellSize(apCell[nCell]);
1927 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00001928 }
1929 if( i<nOld-1 ){
drh14acc042001-06-10 19:56:58 +00001930 szCell[nCell] = cellSize(apDiv[i]);
drh8c42ca92001-06-22 19:15:00 +00001931 memcpy(&aTemp[i], apDiv[i], szCell[nCell]);
drh14acc042001-06-10 19:56:58 +00001932 apCell[nCell] = &aTemp[i];
1933 dropCell(pParent, nxDiv, szCell[nCell]);
1934 assert( apCell[nCell]->h.leftChild==pgnoOld[i] );
1935 apCell[nCell]->h.leftChild = pOld->u.hdr.rightChild;
1936 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00001937 }
1938 }
1939
1940 /*
drh6019e162001-07-02 17:51:45 +00001941 ** Figure out the number of pages needed to hold all nCell cells.
1942 ** Store this number in "k". Also compute szNew[] which is the total
1943 ** size of all cells on the i-th page and cntNew[] which is the index
1944 ** in apCell[] of the cell that divides path i from path i+1.
1945 ** cntNew[k] should equal nCell.
1946 **
1947 ** This little patch of code is critical for keeping the tree
1948 ** balanced.
drh8b2f49b2001-06-08 00:21:52 +00001949 */
1950 totalSize = 0;
1951 for(i=0; i<nCell; i++){
drh14acc042001-06-10 19:56:58 +00001952 totalSize += szCell[i];
drh8b2f49b2001-06-08 00:21:52 +00001953 }
drh6019e162001-07-02 17:51:45 +00001954 for(subtotal=k=i=0; i<nCell; i++){
1955 subtotal += szCell[i];
1956 if( subtotal > USABLE_SPACE ){
1957 szNew[k] = subtotal - szCell[i];
1958 cntNew[k] = i;
1959 subtotal = 0;
1960 k++;
1961 }
1962 }
1963 szNew[k] = subtotal;
1964 cntNew[k] = nCell;
1965 k++;
1966 for(i=k-1; i>0; i--){
1967 while( szNew[i]<USABLE_SPACE/2 ){
1968 cntNew[i-1]--;
1969 assert( cntNew[i-1]>0 );
1970 szNew[i] += szCell[cntNew[i-1]];
1971 szNew[i-1] -= szCell[cntNew[i-1]-1];
1972 }
1973 }
1974 assert( cntNew[0]>0 );
drh8b2f49b2001-06-08 00:21:52 +00001975
1976 /*
drh6019e162001-07-02 17:51:45 +00001977 ** Allocate k new pages
drh8b2f49b2001-06-08 00:21:52 +00001978 */
drh14acc042001-06-10 19:56:58 +00001979 for(i=0; i<k; i++){
drh8b2f49b2001-06-08 00:21:52 +00001980 rc = allocatePage(pBt, &apNew[i], &pgnoNew[i]);
drh14acc042001-06-10 19:56:58 +00001981 if( rc ) goto balance_cleanup;
1982 nNew++;
drh8b2f49b2001-06-08 00:21:52 +00001983 zeroPage(apNew[i]);
drh6019e162001-07-02 17:51:45 +00001984 apNew[i]->isInit = 1;
drh8b2f49b2001-06-08 00:21:52 +00001985 }
1986
1987 /*
drh14acc042001-06-10 19:56:58 +00001988 ** Evenly distribute the data in apCell[] across the new pages.
1989 ** Insert divider cells into pParent as necessary.
1990 */
1991 j = 0;
1992 for(i=0; i<nNew; i++){
1993 MemPage *pNew = apNew[i];
drh6019e162001-07-02 17:51:45 +00001994 while( j<cntNew[i] ){
1995 assert( pNew->nFree>=szCell[j] );
drh14acc042001-06-10 19:56:58 +00001996 if( pCur && iCur==j ){ pCur->pPage = pNew; pCur->idx = pNew->nCell; }
1997 insertCell(pNew, pNew->nCell, apCell[j], szCell[j]);
1998 j++;
1999 }
drh6019e162001-07-02 17:51:45 +00002000 assert( pNew->nCell>0 );
drh14acc042001-06-10 19:56:58 +00002001 assert( !pNew->isOverfull );
2002 relinkCellList(pNew);
2003 if( i<nNew-1 && j<nCell ){
2004 pNew->u.hdr.rightChild = apCell[j]->h.leftChild;
2005 apCell[j]->h.leftChild = pgnoNew[i];
2006 if( pCur && iCur==j ){ pCur->pPage = pParent; pCur->idx = nxDiv; }
2007 insertCell(pParent, nxDiv, apCell[j], szCell[j]);
2008 j++;
2009 nxDiv++;
2010 }
2011 }
drh6019e162001-07-02 17:51:45 +00002012 assert( j==nCell );
drh14acc042001-06-10 19:56:58 +00002013 apNew[nNew-1]->u.hdr.rightChild = apOld[nOld-1]->u.hdr.rightChild;
2014 if( nxDiv==pParent->nCell ){
2015 pParent->u.hdr.rightChild = pgnoNew[nNew-1];
2016 }else{
2017 pParent->apCell[nxDiv]->h.leftChild = pgnoNew[nNew-1];
2018 }
2019 if( pCur ){
drh3fc190c2001-09-14 03:24:23 +00002020 if( j<=iCur && pCur->pPage==pParent && pCur->idx>idxDiv[nOld-1] ){
2021 assert( pCur->pPage==pOldCurPage );
2022 pCur->idx += nNew - nOld;
2023 }else{
2024 assert( pOldCurPage!=0 );
2025 sqlitepager_ref(pCur->pPage);
2026 sqlitepager_unref(pOldCurPage);
2027 }
drh14acc042001-06-10 19:56:58 +00002028 }
2029
2030 /*
2031 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00002032 */
2033 for(i=0; i<nNew; i++){
drh14acc042001-06-10 19:56:58 +00002034 reparentChildPages(pBt->pPager, apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002035 }
drh14acc042001-06-10 19:56:58 +00002036 reparentChildPages(pBt->pPager, pParent);
drh8b2f49b2001-06-08 00:21:52 +00002037
2038 /*
drh14acc042001-06-10 19:56:58 +00002039 ** balance the parent page.
drh8b2f49b2001-06-08 00:21:52 +00002040 */
drh5edc3122001-09-13 21:53:09 +00002041 rc = balance(pBt, pParent, pCur);
drh8b2f49b2001-06-08 00:21:52 +00002042
2043 /*
drh14acc042001-06-10 19:56:58 +00002044 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00002045 */
drh14acc042001-06-10 19:56:58 +00002046balance_cleanup:
drh9ca7d3b2001-06-28 11:50:21 +00002047 if( extraUnref ){
2048 sqlitepager_unref(extraUnref);
2049 }
drh8b2f49b2001-06-08 00:21:52 +00002050 for(i=0; i<nOld; i++){
drhdd793422001-06-28 01:54:48 +00002051 if( apOld[i]!=&aOld[i] ) sqlitepager_unref(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00002052 }
drh14acc042001-06-10 19:56:58 +00002053 for(i=0; i<nNew; i++){
2054 sqlitepager_unref(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002055 }
drh14acc042001-06-10 19:56:58 +00002056 if( pCur && pCur->pPage==0 ){
2057 pCur->pPage = pParent;
2058 pCur->idx = 0;
2059 }else{
2060 sqlitepager_unref(pParent);
drh8b2f49b2001-06-08 00:21:52 +00002061 }
2062 return rc;
2063}
2064
2065/*
drh3b7511c2001-05-26 13:15:44 +00002066** Insert a new record into the BTree. The key is given by (pKey,nKey)
2067** and the data is given by (pData,nData). The cursor is used only to
2068** define what database the record should be inserted into. The cursor
drh14acc042001-06-10 19:56:58 +00002069** is left pointing at the new record.
drh3b7511c2001-05-26 13:15:44 +00002070*/
2071int sqliteBtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00002072 BtCursor *pCur, /* Insert data into the table of this cursor */
drhbe0072d2001-09-13 14:46:09 +00002073 const void *pKey, int nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00002074 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00002075){
2076 Cell newCell;
2077 int rc;
2078 int loc;
drh14acc042001-06-10 19:56:58 +00002079 int szNew;
drh3b7511c2001-05-26 13:15:44 +00002080 MemPage *pPage;
2081 Btree *pBt = pCur->pBt;
2082
drhecdc7532001-09-23 02:35:53 +00002083 if( pCur->pPage==0 ){
2084 return SQLITE_ABORT; /* A rollback destroyed this cursor */
2085 }
drh5edc3122001-09-13 21:53:09 +00002086 if( !pCur->pBt->inTrans || nKey+nData==0 ){
drh8b2f49b2001-06-08 00:21:52 +00002087 return SQLITE_ERROR; /* Must start a transaction first */
2088 }
drhecdc7532001-09-23 02:35:53 +00002089 if( !pCur->wrFlag ){
2090 return SQLITE_PERM; /* Cursor not open for writing */
2091 }
drh14acc042001-06-10 19:56:58 +00002092 rc = sqliteBtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00002093 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002094 pPage = pCur->pPage;
2095 rc = sqlitepager_write(pPage);
drhbd03cae2001-06-02 02:40:57 +00002096 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00002097 rc = fillInCell(pBt, &newCell, pKey, nKey, pData, nData);
2098 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002099 szNew = cellSize(&newCell);
drh3b7511c2001-05-26 13:15:44 +00002100 if( loc==0 ){
drh14acc042001-06-10 19:56:58 +00002101 newCell.h.leftChild = pPage->apCell[pCur->idx]->h.leftChild;
2102 rc = clearCell(pBt, pPage->apCell[pCur->idx]);
drh5e2f8b92001-05-28 00:41:15 +00002103 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002104 dropCell(pPage, pCur->idx, cellSize(pPage->apCell[pCur->idx]));
drh7c717f72001-06-24 20:39:41 +00002105 }else if( loc<0 && pPage->nCell>0 ){
drh14acc042001-06-10 19:56:58 +00002106 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
2107 pCur->idx++;
2108 }else{
2109 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
drh3b7511c2001-05-26 13:15:44 +00002110 }
drh7c717f72001-06-24 20:39:41 +00002111 insertCell(pPage, pCur->idx, &newCell, szNew);
drh14acc042001-06-10 19:56:58 +00002112 rc = balance(pCur->pBt, pPage, pCur);
drh3fc190c2001-09-14 03:24:23 +00002113 /* sqliteBtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
2114 /* fflush(stdout); */
drh5e2f8b92001-05-28 00:41:15 +00002115 return rc;
2116}
2117
2118/*
drhbd03cae2001-06-02 02:40:57 +00002119** Delete the entry that the cursor is pointing to.
drh5e2f8b92001-05-28 00:41:15 +00002120**
drhbd03cae2001-06-02 02:40:57 +00002121** The cursor is left pointing at either the next or the previous
2122** entry. If the cursor is left pointing to the next entry, then
2123** the pCur->bSkipNext flag is set which forces the next call to
2124** sqliteBtreeNext() to be a no-op. That way, you can always call
2125** sqliteBtreeNext() after a delete and the cursor will be left
2126** pointing to the first entry after the deleted entry.
drh3b7511c2001-05-26 13:15:44 +00002127*/
2128int sqliteBtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00002129 MemPage *pPage = pCur->pPage;
2130 Cell *pCell;
2131 int rc;
drh8c42ca92001-06-22 19:15:00 +00002132 Pgno pgnoChild;
drh8b2f49b2001-06-08 00:21:52 +00002133
drhecdc7532001-09-23 02:35:53 +00002134 if( pCur->pPage==0 ){
2135 return SQLITE_ABORT; /* A rollback destroyed this cursor */
2136 }
drh8b2f49b2001-06-08 00:21:52 +00002137 if( !pCur->pBt->inTrans ){
2138 return SQLITE_ERROR; /* Must start a transaction first */
2139 }
drhbd03cae2001-06-02 02:40:57 +00002140 if( pCur->idx >= pPage->nCell ){
2141 return SQLITE_ERROR; /* The cursor is not pointing to anything */
2142 }
drhecdc7532001-09-23 02:35:53 +00002143 if( !pCur->wrFlag ){
2144 return SQLITE_PERM; /* Did not open this cursor for writing */
2145 }
drhbd03cae2001-06-02 02:40:57 +00002146 rc = sqlitepager_write(pPage);
2147 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002148 pCell = pPage->apCell[pCur->idx];
drh14acc042001-06-10 19:56:58 +00002149 pgnoChild = pCell->h.leftChild;
drh8c42ca92001-06-22 19:15:00 +00002150 clearCell(pCur->pBt, pCell);
drh14acc042001-06-10 19:56:58 +00002151 if( pgnoChild ){
2152 /*
drh5e00f6c2001-09-13 13:46:56 +00002153 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00002154 ** do something we will leave a hole on an internal page.
2155 ** We have to fill the hole by moving in a cell from a leaf. The
2156 ** next Cell after the one to be deleted is guaranteed to exist and
2157 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00002158 */
drh14acc042001-06-10 19:56:58 +00002159 BtCursor leafCur;
2160 Cell *pNext;
2161 int szNext;
2162 getTempCursor(pCur, &leafCur);
2163 rc = sqliteBtreeNext(&leafCur, 0);
2164 if( rc!=SQLITE_OK ){
2165 return SQLITE_CORRUPT;
drh5e2f8b92001-05-28 00:41:15 +00002166 }
drh6019e162001-07-02 17:51:45 +00002167 rc = sqlitepager_write(leafCur.pPage);
2168 if( rc ) return rc;
drh9ca7d3b2001-06-28 11:50:21 +00002169 dropCell(pPage, pCur->idx, cellSize(pCell));
drh8c42ca92001-06-22 19:15:00 +00002170 pNext = leafCur.pPage->apCell[leafCur.idx];
drh14acc042001-06-10 19:56:58 +00002171 szNext = cellSize(pNext);
drh8c42ca92001-06-22 19:15:00 +00002172 pNext->h.leftChild = pgnoChild;
drh14acc042001-06-10 19:56:58 +00002173 insertCell(pPage, pCur->idx, pNext, szNext);
2174 rc = balance(pCur->pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002175 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002176 pCur->bSkipNext = 1;
drh14acc042001-06-10 19:56:58 +00002177 dropCell(leafCur.pPage, leafCur.idx, szNext);
2178 rc = balance(pCur->pBt, leafCur.pPage, 0);
drh8c42ca92001-06-22 19:15:00 +00002179 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00002180 }else{
drh9ca7d3b2001-06-28 11:50:21 +00002181 dropCell(pPage, pCur->idx, cellSize(pCell));
drh5edc3122001-09-13 21:53:09 +00002182 if( pCur->idx>=pPage->nCell ){
2183 pCur->idx = pPage->nCell-1;
2184 if( pCur->idx<0 ){ pCur->idx = 0; }
2185 pCur->bSkipNext = 0;
drh6019e162001-07-02 17:51:45 +00002186 }else{
2187 pCur->bSkipNext = 1;
2188 }
drh14acc042001-06-10 19:56:58 +00002189 rc = balance(pCur->pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002190 }
drh5e2f8b92001-05-28 00:41:15 +00002191 return rc;
drh3b7511c2001-05-26 13:15:44 +00002192}
drh8b2f49b2001-06-08 00:21:52 +00002193
2194/*
2195** Create a new BTree in the same file. Write into *piTable the index
2196** of the root page of the new table.
2197*/
2198int sqliteBtreeCreateTable(Btree *pBt, int *piTable){
2199 MemPage *pRoot;
2200 Pgno pgnoRoot;
2201 int rc;
2202 if( !pBt->inTrans ){
2203 return SQLITE_ERROR; /* Must start a transaction first */
2204 }
2205 rc = allocatePage(pBt, &pRoot, &pgnoRoot);
2206 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002207 assert( sqlitepager_iswriteable(pRoot) );
drh8b2f49b2001-06-08 00:21:52 +00002208 zeroPage(pRoot);
2209 sqlitepager_unref(pRoot);
2210 *piTable = (int)pgnoRoot;
2211 return SQLITE_OK;
2212}
2213
2214/*
2215** Erase the given database page and all its children. Return
2216** the page to the freelist.
2217*/
drh2aa679f2001-06-25 02:11:07 +00002218static int clearDatabasePage(Btree *pBt, Pgno pgno, int freePageFlag){
drh8b2f49b2001-06-08 00:21:52 +00002219 MemPage *pPage;
2220 int rc;
drh8b2f49b2001-06-08 00:21:52 +00002221 Cell *pCell;
2222 int idx;
2223
drh8c42ca92001-06-22 19:15:00 +00002224 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pPage);
drh8b2f49b2001-06-08 00:21:52 +00002225 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002226 rc = sqlitepager_write(pPage);
2227 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002228 idx = pPage->u.hdr.firstCell;
drh8b2f49b2001-06-08 00:21:52 +00002229 while( idx>0 ){
drh14acc042001-06-10 19:56:58 +00002230 pCell = (Cell*)&pPage->u.aDisk[idx];
drh8b2f49b2001-06-08 00:21:52 +00002231 idx = pCell->h.iNext;
2232 if( pCell->h.leftChild ){
drh2aa679f2001-06-25 02:11:07 +00002233 rc = clearDatabasePage(pBt, pCell->h.leftChild, 1);
drh8b2f49b2001-06-08 00:21:52 +00002234 if( rc ) return rc;
2235 }
drh8c42ca92001-06-22 19:15:00 +00002236 rc = clearCell(pBt, pCell);
drh8b2f49b2001-06-08 00:21:52 +00002237 if( rc ) return rc;
2238 }
drh2aa679f2001-06-25 02:11:07 +00002239 if( pPage->u.hdr.rightChild ){
2240 rc = clearDatabasePage(pBt, pPage->u.hdr.rightChild, 1);
2241 if( rc ) return rc;
2242 }
2243 if( freePageFlag ){
2244 rc = freePage(pBt, pPage, pgno);
2245 }else{
2246 zeroPage(pPage);
2247 }
drhdd793422001-06-28 01:54:48 +00002248 sqlitepager_unref(pPage);
drh2aa679f2001-06-25 02:11:07 +00002249 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002250}
2251
2252/*
2253** Delete all information from a single table in the database.
2254*/
2255int sqliteBtreeClearTable(Btree *pBt, int iTable){
2256 int rc;
drhecdc7532001-09-23 02:35:53 +00002257 int nLock;
drh8b2f49b2001-06-08 00:21:52 +00002258 if( !pBt->inTrans ){
2259 return SQLITE_ERROR; /* Must start a transaction first */
2260 }
drhecdc7532001-09-23 02:35:53 +00002261 nLock = (int)sqliteHashFind(&pBt->locks, 0, iTable);
2262 if( nLock ){
2263 return SQLITE_LOCKED;
2264 }
drh2aa679f2001-06-25 02:11:07 +00002265 rc = clearDatabasePage(pBt, (Pgno)iTable, 0);
drh8b2f49b2001-06-08 00:21:52 +00002266 if( rc ){
2267 sqliteBtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00002268 }
drh8c42ca92001-06-22 19:15:00 +00002269 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002270}
2271
2272/*
2273** Erase all information in a table and add the root of the table to
2274** the freelist. Except, the root of the principle table (the one on
2275** page 2) is never added to the freelist.
2276*/
2277int sqliteBtreeDropTable(Btree *pBt, int iTable){
2278 int rc;
2279 MemPage *pPage;
2280 if( !pBt->inTrans ){
2281 return SQLITE_ERROR; /* Must start a transaction first */
2282 }
drh8c42ca92001-06-22 19:15:00 +00002283 rc = sqlitepager_get(pBt->pPager, (Pgno)iTable, (void**)&pPage);
drh2aa679f2001-06-25 02:11:07 +00002284 if( rc ) return rc;
2285 rc = sqliteBtreeClearTable(pBt, iTable);
2286 if( rc ) return rc;
2287 if( iTable>2 ){
2288 rc = freePage(pBt, pPage, iTable);
2289 }else{
2290 zeroPage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00002291 }
drhdd793422001-06-28 01:54:48 +00002292 sqlitepager_unref(pPage);
drh8b2f49b2001-06-08 00:21:52 +00002293 return rc;
2294}
2295
2296/*
2297** Read the meta-information out of a database file.
2298*/
2299int sqliteBtreeGetMeta(Btree *pBt, int *aMeta){
2300 PageOne *pP1;
2301 int rc;
2302
drh8c42ca92001-06-22 19:15:00 +00002303 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00002304 if( rc ) return rc;
drh2aa679f2001-06-25 02:11:07 +00002305 aMeta[0] = pP1->nFree;
2306 memcpy(&aMeta[1], pP1->aMeta, sizeof(pP1->aMeta));
drh8b2f49b2001-06-08 00:21:52 +00002307 sqlitepager_unref(pP1);
2308 return SQLITE_OK;
2309}
2310
2311/*
2312** Write meta-information back into the database.
2313*/
2314int sqliteBtreeUpdateMeta(Btree *pBt, int *aMeta){
2315 PageOne *pP1;
2316 int rc;
2317 if( !pBt->inTrans ){
2318 return SQLITE_ERROR; /* Must start a transaction first */
2319 }
2320 pP1 = pBt->page1;
2321 rc = sqlitepager_write(pP1);
drh2aa679f2001-06-25 02:11:07 +00002322 if( rc ) return rc;
2323 memcpy(pP1->aMeta, &aMeta[1], sizeof(pP1->aMeta));
drh8b2f49b2001-06-08 00:21:52 +00002324 return SQLITE_OK;
2325}
drh8c42ca92001-06-22 19:15:00 +00002326
drh5eddca62001-06-30 21:53:53 +00002327/******************************************************************************
2328** The complete implementation of the BTree subsystem is above this line.
2329** All the code the follows is for testing and troubleshooting the BTree
2330** subsystem. None of the code that follows is used during normal operation.
2331** All of the following code is omitted unless the library is compiled with
2332** the -DSQLITE_TEST=1 compiler option.
2333******************************************************************************/
drh5edc3122001-09-13 21:53:09 +00002334#if 1
drh5eddca62001-06-30 21:53:53 +00002335
drh8c42ca92001-06-22 19:15:00 +00002336/*
2337** Print a disassembly of the given page on standard output. This routine
2338** is used for debugging and testing only.
2339*/
drh6019e162001-07-02 17:51:45 +00002340int sqliteBtreePageDump(Btree *pBt, int pgno, int recursive){
drh8c42ca92001-06-22 19:15:00 +00002341 int rc;
2342 MemPage *pPage;
2343 int i, j;
2344 int nFree;
2345 u16 idx;
2346 char range[20];
2347 unsigned char payload[20];
2348 rc = sqlitepager_get(pBt->pPager, (Pgno)pgno, (void**)&pPage);
2349 if( rc ){
2350 return rc;
2351 }
drh6019e162001-07-02 17:51:45 +00002352 if( recursive ) printf("PAGE %d:\n", pgno);
drh8c42ca92001-06-22 19:15:00 +00002353 i = 0;
2354 idx = pPage->u.hdr.firstCell;
2355 while( idx>0 && idx<=SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2356 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
2357 int sz = cellSize(pCell);
2358 sprintf(range,"%d..%d", idx, idx+sz-1);
drh2aa679f2001-06-25 02:11:07 +00002359 sz = pCell->h.nKey + pCell->h.nData;
drh8c42ca92001-06-22 19:15:00 +00002360 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
2361 memcpy(payload, pCell->aPayload, sz);
2362 for(j=0; j<sz; j++){
2363 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
2364 }
2365 payload[sz] = 0;
2366 printf(
drh6019e162001-07-02 17:51:45 +00002367 "cell %2d: i=%-10s chld=%-4d nk=%-4d nd=%-4d payload=%s\n",
drh8c42ca92001-06-22 19:15:00 +00002368 i, range, (int)pCell->h.leftChild, pCell->h.nKey, pCell->h.nData,
drh2aa679f2001-06-25 02:11:07 +00002369 payload
drh8c42ca92001-06-22 19:15:00 +00002370 );
drh6019e162001-07-02 17:51:45 +00002371 if( pPage->isInit && pPage->apCell[i]!=pCell ){
drh2aa679f2001-06-25 02:11:07 +00002372 printf("**** apCell[%d] does not match on prior entry ****\n", i);
2373 }
drh7c717f72001-06-24 20:39:41 +00002374 i++;
drh8c42ca92001-06-22 19:15:00 +00002375 idx = pCell->h.iNext;
2376 }
2377 if( idx!=0 ){
2378 printf("ERROR: next cell index out of range: %d\n", idx);
2379 }
2380 printf("right_child: %d\n", pPage->u.hdr.rightChild);
2381 nFree = 0;
2382 i = 0;
2383 idx = pPage->u.hdr.firstFree;
2384 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2385 FreeBlk *p = (FreeBlk*)&pPage->u.aDisk[idx];
2386 sprintf(range,"%d..%d", idx, idx+p->iSize-1);
2387 nFree += p->iSize;
2388 printf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
2389 i, range, p->iSize, nFree);
2390 idx = p->iNext;
drh2aa679f2001-06-25 02:11:07 +00002391 i++;
drh8c42ca92001-06-22 19:15:00 +00002392 }
2393 if( idx!=0 ){
2394 printf("ERROR: next freeblock index out of range: %d\n", idx);
2395 }
drh6019e162001-07-02 17:51:45 +00002396 if( recursive && pPage->u.hdr.rightChild!=0 ){
2397 idx = pPage->u.hdr.firstCell;
2398 while( idx>0 && idx<SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2399 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
2400 sqliteBtreePageDump(pBt, pCell->h.leftChild, 1);
2401 idx = pCell->h.iNext;
2402 }
2403 sqliteBtreePageDump(pBt, pPage->u.hdr.rightChild, 1);
2404 }
drh8c42ca92001-06-22 19:15:00 +00002405 sqlitepager_unref(pPage);
2406 return SQLITE_OK;
2407}
drh8c42ca92001-06-22 19:15:00 +00002408
drh8c42ca92001-06-22 19:15:00 +00002409/*
drh2aa679f2001-06-25 02:11:07 +00002410** Fill aResult[] with information about the entry and page that the
2411** cursor is pointing to.
2412**
2413** aResult[0] = The page number
2414** aResult[1] = The entry number
2415** aResult[2] = Total number of entries on this page
2416** aResult[3] = Size of this entry
2417** aResult[4] = Number of free bytes on this page
2418** aResult[5] = Number of free blocks on the page
2419** aResult[6] = Page number of the left child of this entry
2420** aResult[7] = Page number of the right child for the whole page
drh5eddca62001-06-30 21:53:53 +00002421**
2422** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00002423*/
2424int sqliteBtreeCursorDump(BtCursor *pCur, int *aResult){
drh2aa679f2001-06-25 02:11:07 +00002425 int cnt, idx;
2426 MemPage *pPage = pCur->pPage;
2427 aResult[0] = sqlitepager_pagenumber(pPage);
drh8c42ca92001-06-22 19:15:00 +00002428 aResult[1] = pCur->idx;
drh2aa679f2001-06-25 02:11:07 +00002429 aResult[2] = pPage->nCell;
2430 if( pCur->idx>=0 && pCur->idx<pPage->nCell ){
2431 aResult[3] = cellSize(pPage->apCell[pCur->idx]);
2432 aResult[6] = pPage->apCell[pCur->idx]->h.leftChild;
2433 }else{
2434 aResult[3] = 0;
2435 aResult[6] = 0;
2436 }
2437 aResult[4] = pPage->nFree;
2438 cnt = 0;
2439 idx = pPage->u.hdr.firstFree;
2440 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2441 cnt++;
2442 idx = ((FreeBlk*)&pPage->u.aDisk[idx])->iNext;
2443 }
2444 aResult[5] = cnt;
2445 aResult[7] = pPage->u.hdr.rightChild;
drh8c42ca92001-06-22 19:15:00 +00002446 return SQLITE_OK;
2447}
drhdd793422001-06-28 01:54:48 +00002448
drhdd793422001-06-28 01:54:48 +00002449/*
drh5eddca62001-06-30 21:53:53 +00002450** Return the pager associated with a BTree. This routine is used for
2451** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00002452*/
2453Pager *sqliteBtreePager(Btree *pBt){
2454 return pBt->pPager;
2455}
drh5eddca62001-06-30 21:53:53 +00002456
2457/*
2458** This structure is passed around through all the sanity checking routines
2459** in order to keep track of some global state information.
2460*/
2461typedef struct SanityCheck SanityCheck;
2462struct SanityCheck {
2463 Btree *pBt; // The tree being checked out
2464 Pager *pPager; // The associated pager. Also accessible by pBt->pPager
2465 int nPage; // Number of pages in the database
2466 int *anRef; // Number of times each page is referenced
drh6019e162001-07-02 17:51:45 +00002467 int nTreePage; // Number of BTree pages
2468 int nByte; // Number of bytes of data stored on BTree pages
drh5eddca62001-06-30 21:53:53 +00002469 char *zErrMsg; // An error message. NULL of no errors seen.
2470};
2471
2472/*
2473** Append a message to the error message string.
2474*/
2475static void checkAppendMsg(SanityCheck *pCheck, char *zMsg1, char *zMsg2){
2476 if( pCheck->zErrMsg ){
2477 char *zOld = pCheck->zErrMsg;
2478 pCheck->zErrMsg = 0;
2479 sqliteSetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, 0);
2480 sqliteFree(zOld);
2481 }else{
2482 sqliteSetString(&pCheck->zErrMsg, zMsg1, zMsg2, 0);
2483 }
2484}
2485
2486/*
2487** Add 1 to the reference count for page iPage. If this is the second
2488** reference to the page, add an error message to pCheck->zErrMsg.
2489** Return 1 if there are 2 ore more references to the page and 0 if
2490** if this is the first reference to the page.
2491**
2492** Also check that the page number is in bounds.
2493*/
2494static int checkRef(SanityCheck *pCheck, int iPage, char *zContext){
2495 if( iPage==0 ) return 1;
2496 if( iPage>pCheck->nPage ){
2497 char zBuf[100];
2498 sprintf(zBuf, "invalid page number %d", iPage);
2499 checkAppendMsg(pCheck, zContext, zBuf);
2500 return 1;
2501 }
2502 if( pCheck->anRef[iPage]==1 ){
2503 char zBuf[100];
2504 sprintf(zBuf, "2nd reference to page %d", iPage);
2505 checkAppendMsg(pCheck, zContext, zBuf);
2506 return 1;
2507 }
2508 return (pCheck->anRef[iPage]++)>1;
2509}
2510
2511/*
2512** Check the integrity of the freelist or of an overflow page list.
2513** Verify that the number of pages on the list is N.
2514*/
2515static void checkList(SanityCheck *pCheck, int iPage, int N, char *zContext){
2516 char zMsg[100];
2517 while( N-- ){
2518 OverflowPage *pOvfl;
2519 if( iPage<1 ){
2520 sprintf(zMsg, "%d pages missing from overflow list", N+1);
2521 checkAppendMsg(pCheck, zContext, zMsg);
2522 break;
2523 }
2524 if( checkRef(pCheck, iPage, zContext) ) break;
2525 if( sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
2526 sprintf(zMsg, "failed to get page %d", iPage);
2527 checkAppendMsg(pCheck, zContext, zMsg);
2528 break;
2529 }
2530 iPage = (int)pOvfl->iNext;
2531 sqlitepager_unref(pOvfl);
2532 }
2533}
2534
2535/*
2536** Do various sanity checks on a single page of a tree. Return
2537** the tree depth. Root pages return 0. Parents of root pages
2538** return 1, and so forth.
2539**
2540** These checks are done:
2541**
2542** 1. Make sure that cells and freeblocks do not overlap
2543** but combine to completely cover the page.
2544** 2. Make sure cell keys are in order.
2545** 3. Make sure no key is less than or equal to zLowerBound.
2546** 4. Make sure no key is greater than or equal to zUpperBound.
2547** 5. Check the integrity of overflow pages.
2548** 6. Recursively call checkTreePage on all children.
2549** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00002550** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00002551** the root of the tree.
2552*/
2553static int checkTreePage(
2554 SanityCheck *pCheck, /* Context for the sanity check */
2555 int iPage, /* Page number of the page to check */
2556 MemPage *pParent, /* Parent page */
2557 char *zParentContext, /* Parent context */
2558 char *zLowerBound, /* All keys should be greater than this, if not NULL */
2559 char *zUpperBound /* All keys should be less than this, if not NULL */
2560){
2561 MemPage *pPage;
2562 int i, rc, depth, d2, pgno;
2563 char *zKey1, *zKey2;
2564 BtCursor cur;
2565 char zMsg[100];
2566 char zContext[100];
2567 char hit[SQLITE_PAGE_SIZE];
2568
2569 /* Check that the page exists
2570 */
2571 if( iPage==0 ) return 0;
2572 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
2573 sprintf(zContext, "On tree page %d: ", iPage);
2574 if( (rc = sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pPage))!=0 ){
2575 sprintf(zMsg, "unable to get the page. error code=%d", rc);
2576 checkAppendMsg(pCheck, zContext, zMsg);
2577 return 0;
2578 }
2579 if( (rc = initPage(pPage, (Pgno)iPage, pParent))!=0 ){
2580 sprintf(zMsg, "initPage() returns error code %d", rc);
2581 checkAppendMsg(pCheck, zContext, zMsg);
2582 sqlitepager_unref(pPage);
2583 return 0;
2584 }
2585
2586 /* Check out all the cells.
2587 */
2588 depth = 0;
2589 zKey1 = zLowerBound ? sqliteStrDup(zLowerBound) : 0;
2590 cur.pPage = pPage;
2591 cur.pBt = pCheck->pBt;
2592 for(i=0; i<pPage->nCell; i++){
2593 Cell *pCell = pPage->apCell[i];
2594 int sz;
2595
2596 /* Check payload overflow pages
2597 */
2598 sz = pCell->h.nKey + pCell->h.nData;
2599 sprintf(zContext, "On page %d cell %d: ", iPage, i);
2600 if( sz>MX_LOCAL_PAYLOAD ){
2601 int nPage = (sz - MX_LOCAL_PAYLOAD + OVERFLOW_SIZE - 1)/OVERFLOW_SIZE;
2602 checkList(pCheck, pCell->ovfl, nPage, zContext);
2603 }
2604
2605 /* Check that keys are in the right order
2606 */
2607 cur.idx = i;
2608 zKey2 = sqliteMalloc( pCell->h.nKey+1 );
2609 getPayload(&cur, 0, pCell->h.nKey, zKey2);
2610 if( zKey1 && strcmp(zKey1,zKey2)>=0 ){
2611 checkAppendMsg(pCheck, zContext, "Key is out of order");
2612 }
2613
2614 /* Check sanity of left child page.
2615 */
2616 pgno = (int)pCell->h.leftChild;
2617 d2 = checkTreePage(pCheck, pgno, pPage, zContext, zKey1, zKey2);
2618 if( i>0 && d2!=depth ){
2619 checkAppendMsg(pCheck, zContext, "Child page depth differs");
2620 }
2621 depth = d2;
2622 sqliteFree(zKey1);
2623 zKey1 = zKey2;
2624 }
2625 pgno = pPage->u.hdr.rightChild;
2626 sprintf(zContext, "On page %d at right child: ", iPage);
2627 checkTreePage(pCheck, pgno, pPage, zContext, zKey1, zUpperBound);
2628 sqliteFree(zKey1);
2629
2630 /* Check for complete coverage of the page
2631 */
2632 memset(hit, 0, sizeof(hit));
2633 memset(hit, 1, sizeof(PageHdr));
2634 for(i=pPage->u.hdr.firstCell; i>0 && i<SQLITE_PAGE_SIZE; ){
2635 Cell *pCell = (Cell*)&pPage->u.aDisk[i];
2636 int j;
2637 for(j=i+cellSize(pCell)-1; j>=i; j--) hit[j]++;
2638 i = pCell->h.iNext;
2639 }
2640 for(i=pPage->u.hdr.firstFree; i>0 && i<SQLITE_PAGE_SIZE; ){
2641 FreeBlk *pFBlk = (FreeBlk*)&pPage->u.aDisk[i];
2642 int j;
2643 for(j=i+pFBlk->iSize-1; j>=i; j--) hit[j]++;
2644 i = pFBlk->iNext;
2645 }
2646 for(i=0; i<SQLITE_PAGE_SIZE; i++){
2647 if( hit[i]==0 ){
2648 sprintf(zMsg, "Unused space at byte %d of page %d", i, iPage);
2649 checkAppendMsg(pCheck, zMsg, 0);
2650 break;
2651 }else if( hit[i]>1 ){
2652 sprintf(zMsg, "Multiple uses for byte %d of page %d", i, iPage);
2653 checkAppendMsg(pCheck, zMsg, 0);
2654 break;
2655 }
2656 }
2657
2658 /* Check that free space is kept to a minimum
2659 */
drh6019e162001-07-02 17:51:45 +00002660#if 0
2661 if( pParent && pParent->nCell>2 && pPage->nFree>3*SQLITE_PAGE_SIZE/4 ){
drh5eddca62001-06-30 21:53:53 +00002662 sprintf(zMsg, "free space (%d) greater than max (%d)", pPage->nFree,
2663 SQLITE_PAGE_SIZE/3);
2664 checkAppendMsg(pCheck, zContext, zMsg);
2665 }
drh6019e162001-07-02 17:51:45 +00002666#endif
2667
2668 /* Update freespace totals.
2669 */
2670 pCheck->nTreePage++;
2671 pCheck->nByte += USABLE_SPACE - pPage->nFree;
drh5eddca62001-06-30 21:53:53 +00002672
2673 sqlitepager_unref(pPage);
2674 return depth;
2675}
2676
2677/*
2678** This routine does a complete check of the given BTree file. aRoot[] is
2679** an array of pages numbers were each page number is the root page of
2680** a table. nRoot is the number of entries in aRoot.
2681**
2682** If everything checks out, this routine returns NULL. If something is
2683** amiss, an error message is written into memory obtained from malloc()
2684** and a pointer to that error message is returned. The calling function
2685** is responsible for freeing the error message when it is done.
2686*/
2687char *sqliteBtreeSanityCheck(Btree *pBt, int *aRoot, int nRoot){
2688 int i;
2689 int nRef;
2690 SanityCheck sCheck;
2691
2692 nRef = *sqlitepager_stats(pBt->pPager);
drhefc251d2001-07-01 22:12:01 +00002693 if( lockBtree(pBt)!=SQLITE_OK ){
2694 return sqliteStrDup("Unable to acquire a read lock on the database");
2695 }
drh5eddca62001-06-30 21:53:53 +00002696 sCheck.pBt = pBt;
2697 sCheck.pPager = pBt->pPager;
2698 sCheck.nPage = sqlitepager_pagecount(sCheck.pPager);
2699 sCheck.anRef = sqliteMalloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
2700 sCheck.anRef[1] = 1;
2701 for(i=2; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
2702 sCheck.zErrMsg = 0;
2703
2704 /* Check the integrity of the freelist
2705 */
2706 checkList(&sCheck, pBt->page1->freeList, pBt->page1->nFree,"Main freelist: ");
2707
2708 /* Check all the tables.
2709 */
2710 for(i=0; i<nRoot; i++){
2711 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0, 0);
2712 }
2713
2714 /* Make sure every page in the file is referenced
2715 */
2716 for(i=1; i<=sCheck.nPage; i++){
2717 if( sCheck.anRef[i]==0 ){
2718 char zBuf[100];
2719 sprintf(zBuf, "Page %d is never used", i);
2720 checkAppendMsg(&sCheck, zBuf, 0);
2721 }
2722 }
2723
2724 /* Make sure this analysis did not leave any unref() pages
2725 */
drh5e00f6c2001-09-13 13:46:56 +00002726 unlockBtreeIfUnused(pBt);
drh5eddca62001-06-30 21:53:53 +00002727 if( nRef != *sqlitepager_stats(pBt->pPager) ){
2728 char zBuf[100];
2729 sprintf(zBuf,
2730 "Outstanding page count goes from %d to %d during this analysis",
2731 nRef, *sqlitepager_stats(pBt->pPager)
2732 );
2733 checkAppendMsg(&sCheck, zBuf, 0);
2734 }
2735
2736 /* Clean up and report errors.
2737 */
2738 sqliteFree(sCheck.anRef);
2739 return sCheck.zErrMsg;
2740}
2741
2742#endif /* SQLITE_TEST */