blob: 935e5276621573ce143e7b1463b4e71f641cf30b [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*************************************************************************
drh0d316a42002-08-11 20:10:47 +000012** $Id: btree.c,v 1.69 2002/08/11 20:10:47 drh Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
15** For a detailed discussion of BTrees, refer to
16**
17** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
18** "Sorting And Searching", pages 473-480. Addison-Wesley
19** Publishing Company, Reading, Massachusetts.
20**
21** The basic idea is that each page of the file contains N database
22** entries and N+1 pointers to subpages.
23**
24** ----------------------------------------------------------------
25** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N) | Ptr(N+1) |
26** ----------------------------------------------------------------
27**
28** All of the keys on the page that Ptr(0) points to have values less
29** than Key(0). All of the keys on page Ptr(1) and its subpages have
30** values greater than Key(0) and less than Key(1). All of the keys
31** on Ptr(N+1) and its subpages have values greater than Key(N). And
32** so forth.
33**
drh5e00f6c2001-09-13 13:46:56 +000034** Finding a particular key requires reading O(log(M)) pages from the
35** disk where M is the number of entries in the tree.
drh8b2f49b2001-06-08 00:21:52 +000036**
37** In this implementation, a single file can hold one or more separate
38** BTrees. Each BTree is identified by the index of its root page. The
39** key and data for any entry are combined to form the "payload". Up to
40** MX_LOCAL_PAYLOAD bytes of payload can be carried directly on the
41** database page. If the payload is larger than MX_LOCAL_PAYLOAD bytes
42** then surplus bytes are stored on overflow pages. The payload for an
43** entry and the preceding pointer are combined to form a "Cell". Each
drhb19a2bc2001-09-16 00:13:26 +000044** page has a small header which contains the Ptr(N+1) pointer.
drh8b2f49b2001-06-08 00:21:52 +000045**
46** The first page of the file contains a magic string used to verify that
47** the file really is a valid BTree database, a pointer to a list of unused
48** pages in the file, and some meta information. The root of the first
49** BTree begins on page 2 of the file. (Pages are numbered beginning with
50** 1, not 0.) Thus a minimum database contains 2 pages.
drha059ad02001-04-17 20:09:11 +000051*/
52#include "sqliteInt.h"
53#include "pager.h"
54#include "btree.h"
55#include <assert.h>
56
drh8c42ca92001-06-22 19:15:00 +000057/*
drh0d316a42002-08-11 20:10:47 +000058** Macros used for byteswapping. B is a pointer to the Btree
59** structure. This is needed to access the Btree.needSwab boolean
60** in order to tell if byte swapping is needed or not.
61** X is an unsigned integer. SWAB16 byte swaps a 16-bit integer.
62** SWAB32 byteswaps a 32-bit integer.
63*/
64#define SWAB16(B,X) ((B)->needSwab? swab16(X) : (X))
65#define SWAB32(B,X) ((B)->needSwab? swab32(X) : (X))
66#define SWAB_ADD(B,X,A) \
67 if((B)->needSwab){ X=swab32(swab32(X)+A); }else{ X += (A); }
68
69/*
70** The following global variable - available only if SQLITE_TEST is
71** defined - is used to determine whether new databases are created in
72** native byte order or in non-native byte order. Non-native byte order
73** databases are created for testing purposes only. Under normal operation,
74** only native byte-order databases should be created, but we should be
75** able to read or write existing databases regardless of the byteorder.
76*/
77#ifdef SQLITE_TEST
78int btree_native_byte_order = 1;
79#endif
80
81/*
drh365d68f2001-05-11 11:02:46 +000082** Forward declarations of structures used only in this file.
83*/
drhbd03cae2001-06-02 02:40:57 +000084typedef struct PageOne PageOne;
drh2af926b2001-05-15 00:39:25 +000085typedef struct MemPage MemPage;
drh365d68f2001-05-11 11:02:46 +000086typedef struct PageHdr PageHdr;
87typedef struct Cell Cell;
drh3b7511c2001-05-26 13:15:44 +000088typedef struct CellHdr CellHdr;
drh365d68f2001-05-11 11:02:46 +000089typedef struct FreeBlk FreeBlk;
drh2af926b2001-05-15 00:39:25 +000090typedef struct OverflowPage OverflowPage;
drh30e58752002-03-02 20:41:57 +000091typedef struct FreelistInfo FreelistInfo;
drh2af926b2001-05-15 00:39:25 +000092
93/*
94** All structures on a database page are aligned to 4-byte boundries.
95** This routine rounds up a number of bytes to the next multiple of 4.
drh306dc212001-05-21 13:45:10 +000096**
97** This might need to change for computer architectures that require
98** and 8-byte alignment boundry for structures.
drh2af926b2001-05-15 00:39:25 +000099*/
100#define ROUNDUP(X) ((X+3) & ~3)
drha059ad02001-04-17 20:09:11 +0000101
drh08ed44e2001-04-29 23:32:55 +0000102/*
drhbd03cae2001-06-02 02:40:57 +0000103** This is a magic string that appears at the beginning of every
drh8c42ca92001-06-22 19:15:00 +0000104** SQLite database in order to identify the file as a real database.
drh08ed44e2001-04-29 23:32:55 +0000105*/
drhbd03cae2001-06-02 02:40:57 +0000106static const char zMagicHeader[] =
drh80ff32f2001-11-04 18:32:46 +0000107 "** This file contains an SQLite 2.1 database **";
drhbd03cae2001-06-02 02:40:57 +0000108#define MAGIC_SIZE (sizeof(zMagicHeader))
drh08ed44e2001-04-29 23:32:55 +0000109
110/*
drh5e00f6c2001-09-13 13:46:56 +0000111** This is a magic integer also used to test the integrity of the database
drh8c42ca92001-06-22 19:15:00 +0000112** file. This integer is used in addition to the string above so that
113** if the file is written on a little-endian architecture and read
114** on a big-endian architectures (or vice versa) we can detect the
115** problem.
116**
117** The number used was obtained at random and has no special
drhb19a2bc2001-09-16 00:13:26 +0000118** significance other than the fact that it represents a different
119** integer on little-endian and big-endian machines.
drh8c42ca92001-06-22 19:15:00 +0000120*/
121#define MAGIC 0xdae37528
122
123/*
drhbd03cae2001-06-02 02:40:57 +0000124** The first page of the database file contains a magic header string
125** to identify the file as an SQLite database file. It also contains
126** a pointer to the first free page of the file. Page 2 contains the
drh8b2f49b2001-06-08 00:21:52 +0000127** root of the principle BTree. The file might contain other BTrees
128** rooted on pages above 2.
129**
130** The first page also contains SQLITE_N_BTREE_META integers that
131** can be used by higher-level routines.
drh08ed44e2001-04-29 23:32:55 +0000132**
drhbd03cae2001-06-02 02:40:57 +0000133** Remember that pages are numbered beginning with 1. (See pager.c
134** for additional information.) Page 0 does not exist and a page
135** number of 0 is used to mean "no such page".
136*/
137struct PageOne {
138 char zMagic[MAGIC_SIZE]; /* String that identifies the file as a database */
drh8c42ca92001-06-22 19:15:00 +0000139 int iMagic; /* Integer to verify correct byte order */
140 Pgno freeList; /* First free page in a list of all free pages */
drh2aa679f2001-06-25 02:11:07 +0000141 int nFree; /* Number of pages on the free list */
142 int aMeta[SQLITE_N_BTREE_META-1]; /* User defined integers */
drhbd03cae2001-06-02 02:40:57 +0000143};
144
145/*
146** Each database page has a header that is an instance of this
147** structure.
drh08ed44e2001-04-29 23:32:55 +0000148**
drh8b2f49b2001-06-08 00:21:52 +0000149** PageHdr.firstFree is 0 if there is no free space on this page.
drh14acc042001-06-10 19:56:58 +0000150** Otherwise, PageHdr.firstFree is the index in MemPage.u.aDisk[] of a
drh8b2f49b2001-06-08 00:21:52 +0000151** FreeBlk structure that describes the first block of free space.
152** All free space is defined by a linked list of FreeBlk structures.
drh08ed44e2001-04-29 23:32:55 +0000153**
drh8b2f49b2001-06-08 00:21:52 +0000154** Data is stored in a linked list of Cell structures. PageHdr.firstCell
drh14acc042001-06-10 19:56:58 +0000155** is the index into MemPage.u.aDisk[] of the first cell on the page. The
drh306dc212001-05-21 13:45:10 +0000156** Cells are kept in sorted order.
drh8b2f49b2001-06-08 00:21:52 +0000157**
158** A Cell contains all information about a database entry and a pointer
159** to a child page that contains other entries less than itself. In
160** other words, the i-th Cell contains both Ptr(i) and Key(i). The
161** right-most pointer of the page is contained in PageHdr.rightChild.
drh08ed44e2001-04-29 23:32:55 +0000162*/
drh365d68f2001-05-11 11:02:46 +0000163struct PageHdr {
drh5e2f8b92001-05-28 00:41:15 +0000164 Pgno rightChild; /* Child page that comes after all cells on this page */
drh14acc042001-06-10 19:56:58 +0000165 u16 firstCell; /* Index in MemPage.u.aDisk[] of the first cell */
166 u16 firstFree; /* Index in MemPage.u.aDisk[] of the first free block */
drh365d68f2001-05-11 11:02:46 +0000167};
drh306dc212001-05-21 13:45:10 +0000168
drh3b7511c2001-05-26 13:15:44 +0000169/*
170** Entries on a page of the database are called "Cells". Each Cell
171** has a header and data. This structure defines the header. The
drhbd03cae2001-06-02 02:40:57 +0000172** key and data (collectively the "payload") follow this header on
173** the database page.
174**
175** A definition of the complete Cell structure is given below. The
drh8c42ca92001-06-22 19:15:00 +0000176** header for the cell must be defined first in order to do some
drhbd03cae2001-06-02 02:40:57 +0000177** of the sizing #defines that follow.
drh3b7511c2001-05-26 13:15:44 +0000178*/
179struct CellHdr {
drh5e2f8b92001-05-28 00:41:15 +0000180 Pgno leftChild; /* Child page that comes before this cell */
drh3b7511c2001-05-26 13:15:44 +0000181 u16 nKey; /* Number of bytes in the key */
drh14acc042001-06-10 19:56:58 +0000182 u16 iNext; /* Index in MemPage.u.aDisk[] of next cell in sorted order */
drh58a11682001-11-10 13:51:08 +0000183 u8 nKeyHi; /* Upper 8 bits of key size for keys larger than 64K bytes */
184 u8 nDataHi; /* Upper 8 bits of data size when the size is more than 64K */
drh80ff32f2001-11-04 18:32:46 +0000185 u16 nData; /* Number of bytes of data */
drh8c42ca92001-06-22 19:15:00 +0000186};
drh58a11682001-11-10 13:51:08 +0000187
188/*
189** The key and data size are split into a lower 16-bit segment and an
190** upper 8-bit segment in order to pack them together into a smaller
191** space. The following macros reassembly a key or data size back
192** into an integer.
193*/
drh0d316a42002-08-11 20:10:47 +0000194#define NKEY(b,h) (SWAB16(b,h.nKey) + h.nKeyHi*65536)
195#define NDATA(b,h) (SWAB16(b,h.nData) + h.nDataHi*65536)
drh3b7511c2001-05-26 13:15:44 +0000196
197/*
198** The minimum size of a complete Cell. The Cell must contain a header
drhbd03cae2001-06-02 02:40:57 +0000199** and at least 4 bytes of payload.
drh3b7511c2001-05-26 13:15:44 +0000200*/
201#define MIN_CELL_SIZE (sizeof(CellHdr)+4)
202
203/*
204** The maximum number of database entries that can be held in a single
205** page of the database.
206*/
207#define MX_CELL ((SQLITE_PAGE_SIZE-sizeof(PageHdr))/MIN_CELL_SIZE)
208
209/*
drh6019e162001-07-02 17:51:45 +0000210** The amount of usable space on a single page of the BTree. This is the
211** page size minus the overhead of the page header.
212*/
213#define USABLE_SPACE (SQLITE_PAGE_SIZE - sizeof(PageHdr))
214
215/*
drh8c42ca92001-06-22 19:15:00 +0000216** The maximum amount of payload (in bytes) that can be stored locally for
217** a database entry. If the entry contains more data than this, the
drh3b7511c2001-05-26 13:15:44 +0000218** extra goes onto overflow pages.
drhbd03cae2001-06-02 02:40:57 +0000219**
220** This number is chosen so that at least 4 cells will fit on every page.
drh3b7511c2001-05-26 13:15:44 +0000221*/
drh6019e162001-07-02 17:51:45 +0000222#define MX_LOCAL_PAYLOAD ((USABLE_SPACE/4-(sizeof(CellHdr)+sizeof(Pgno)))&~3)
drh3b7511c2001-05-26 13:15:44 +0000223
drh306dc212001-05-21 13:45:10 +0000224/*
225** Data on a database page is stored as a linked list of Cell structures.
drh5e2f8b92001-05-28 00:41:15 +0000226** Both the key and the data are stored in aPayload[]. The key always comes
227** first. The aPayload[] field grows as necessary to hold the key and data,
drh306dc212001-05-21 13:45:10 +0000228** up to a maximum of MX_LOCAL_PAYLOAD bytes. If the size of the key and
drh3b7511c2001-05-26 13:15:44 +0000229** data combined exceeds MX_LOCAL_PAYLOAD bytes, then Cell.ovfl is the
230** page number of the first overflow page.
231**
232** Though this structure is fixed in size, the Cell on the database
drhbd03cae2001-06-02 02:40:57 +0000233** page varies in size. Every cell has a CellHdr and at least 4 bytes
drh3b7511c2001-05-26 13:15:44 +0000234** of payload space. Additional payload bytes (up to the maximum of
235** MX_LOCAL_PAYLOAD) and the Cell.ovfl value are allocated only as
236** needed.
drh306dc212001-05-21 13:45:10 +0000237*/
drh365d68f2001-05-11 11:02:46 +0000238struct Cell {
drh5e2f8b92001-05-28 00:41:15 +0000239 CellHdr h; /* The cell header */
240 char aPayload[MX_LOCAL_PAYLOAD]; /* Key and data */
241 Pgno ovfl; /* The first overflow page */
drh365d68f2001-05-11 11:02:46 +0000242};
drh306dc212001-05-21 13:45:10 +0000243
244/*
245** Free space on a page is remembered using a linked list of the FreeBlk
246** structures. Space on a database page is allocated in increments of
drh72f82862001-05-24 21:06:34 +0000247** at least 4 bytes and is always aligned to a 4-byte boundry. The
drh8b2f49b2001-06-08 00:21:52 +0000248** linked list of FreeBlks is always kept in order by address.
drh306dc212001-05-21 13:45:10 +0000249*/
drh365d68f2001-05-11 11:02:46 +0000250struct FreeBlk {
drh72f82862001-05-24 21:06:34 +0000251 u16 iSize; /* Number of bytes in this block of free space */
drh14acc042001-06-10 19:56:58 +0000252 u16 iNext; /* Index in MemPage.u.aDisk[] of the next free block */
drh365d68f2001-05-11 11:02:46 +0000253};
drh306dc212001-05-21 13:45:10 +0000254
255/*
drh14acc042001-06-10 19:56:58 +0000256** The number of bytes of payload that will fit on a single overflow page.
drh3b7511c2001-05-26 13:15:44 +0000257*/
258#define OVERFLOW_SIZE (SQLITE_PAGE_SIZE-sizeof(Pgno))
259
260/*
drh306dc212001-05-21 13:45:10 +0000261** When the key and data for a single entry in the BTree will not fit in
drh8c42ca92001-06-22 19:15:00 +0000262** the MX_LOCAL_PAYLOAD bytes of space available on the database page,
drh8b2f49b2001-06-08 00:21:52 +0000263** then all extra bytes are written to a linked list of overflow pages.
drh306dc212001-05-21 13:45:10 +0000264** Each overflow page is an instance of the following structure.
265**
266** Unused pages in the database are also represented by instances of
drhbd03cae2001-06-02 02:40:57 +0000267** the OverflowPage structure. The PageOne.freeList field is the
drh306dc212001-05-21 13:45:10 +0000268** page number of the first page in a linked list of unused database
269** pages.
270*/
drh2af926b2001-05-15 00:39:25 +0000271struct OverflowPage {
drh14acc042001-06-10 19:56:58 +0000272 Pgno iNext;
drh5e2f8b92001-05-28 00:41:15 +0000273 char aPayload[OVERFLOW_SIZE];
drh7e3b0a02001-04-28 16:52:40 +0000274};
drh7e3b0a02001-04-28 16:52:40 +0000275
276/*
drh30e58752002-03-02 20:41:57 +0000277** The PageOne.freeList field points to a linked list of overflow pages
278** hold information about free pages. The aPayload section of each
279** overflow page contains an instance of the following structure. The
280** aFree[] array holds the page number of nFree unused pages in the disk
281** file.
282*/
283struct FreelistInfo {
284 int nFree;
285 Pgno aFree[(OVERFLOW_SIZE-sizeof(int))/sizeof(Pgno)];
286};
287
288/*
drh7e3b0a02001-04-28 16:52:40 +0000289** For every page in the database file, an instance of the following structure
drh14acc042001-06-10 19:56:58 +0000290** is stored in memory. The u.aDisk[] array contains the raw bits read from
drh6446c4d2001-12-15 14:22:18 +0000291** the disk. The rest is auxiliary information held in memory only. The
drhbd03cae2001-06-02 02:40:57 +0000292** auxiliary info is only valid for regular database pages - it is not
293** used for overflow pages and pages on the freelist.
drh306dc212001-05-21 13:45:10 +0000294**
drhbd03cae2001-06-02 02:40:57 +0000295** Of particular interest in the auxiliary info is the apCell[] entry. Each
drh14acc042001-06-10 19:56:58 +0000296** apCell[] entry is a pointer to a Cell structure in u.aDisk[]. The cells are
drh306dc212001-05-21 13:45:10 +0000297** put in this array so that they can be accessed in constant time, rather
drhbd03cae2001-06-02 02:40:57 +0000298** than in linear time which would be needed if we had to walk the linked
299** list on every access.
drh72f82862001-05-24 21:06:34 +0000300**
drh14acc042001-06-10 19:56:58 +0000301** Note that apCell[] contains enough space to hold up to two more Cells
302** than can possibly fit on one page. In the steady state, every apCell[]
303** points to memory inside u.aDisk[]. But in the middle of an insert
304** operation, some apCell[] entries may temporarily point to data space
305** outside of u.aDisk[]. This is a transient situation that is quickly
306** resolved. But while it is happening, it is possible for a database
307** page to hold as many as two more cells than it might otherwise hold.
drh18b81e52001-11-01 13:52:52 +0000308** The extra two entries in apCell[] are an allowance for this situation.
drh14acc042001-06-10 19:56:58 +0000309**
drh72f82862001-05-24 21:06:34 +0000310** The pParent field points back to the parent page. This allows us to
311** walk up the BTree from any leaf to the root. Care must be taken to
312** unref() the parent page pointer when this page is no longer referenced.
drhbd03cae2001-06-02 02:40:57 +0000313** The pageDestructor() routine handles that chore.
drh7e3b0a02001-04-28 16:52:40 +0000314*/
315struct MemPage {
drh14acc042001-06-10 19:56:58 +0000316 union {
317 char aDisk[SQLITE_PAGE_SIZE]; /* Page data stored on disk */
318 PageHdr hdr; /* Overlay page header */
319 } u;
drh5e2f8b92001-05-28 00:41:15 +0000320 int isInit; /* True if auxiliary data is initialized */
drh72f82862001-05-24 21:06:34 +0000321 MemPage *pParent; /* The parent of this page. NULL for root */
drh14acc042001-06-10 19:56:58 +0000322 int nFree; /* Number of free bytes in u.aDisk[] */
drh306dc212001-05-21 13:45:10 +0000323 int nCell; /* Number of entries on this page */
drh14acc042001-06-10 19:56:58 +0000324 int isOverfull; /* Some apCell[] points outside u.aDisk[] */
325 Cell *apCell[MX_CELL+2]; /* All data entires in sorted order */
drh8c42ca92001-06-22 19:15:00 +0000326};
drh7e3b0a02001-04-28 16:52:40 +0000327
328/*
drh3b7511c2001-05-26 13:15:44 +0000329** The in-memory image of a disk page has the auxiliary information appended
330** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
331** that extra information.
332*/
333#define EXTRA_SIZE (sizeof(MemPage)-SQLITE_PAGE_SIZE)
334
335/*
drha059ad02001-04-17 20:09:11 +0000336** Everything we need to know about an open database
337*/
338struct Btree {
339 Pager *pPager; /* The page cache */
drh306dc212001-05-21 13:45:10 +0000340 BtCursor *pCursor; /* A list of all open cursors */
drhbd03cae2001-06-02 02:40:57 +0000341 PageOne *page1; /* First page of the database */
drh663fc632002-02-02 18:49:19 +0000342 u8 inTrans; /* True if a transaction is in progress */
343 u8 inCkpt; /* True if there is a checkpoint on the transaction */
drh5df72a52002-06-06 23:16:05 +0000344 u8 readOnly; /* True if the underlying file is readonly */
drh0d316a42002-08-11 20:10:47 +0000345 u8 needSwab; /* Need to byte-swapping */
drhecdc7532001-09-23 02:35:53 +0000346 Hash locks; /* Key: root page number. Data: lock count */
drha059ad02001-04-17 20:09:11 +0000347};
348typedef Btree Bt;
349
drh365d68f2001-05-11 11:02:46 +0000350/*
351** A cursor is a pointer to a particular entry in the BTree.
352** The entry is identified by its MemPage and the index in
drh5e2f8b92001-05-28 00:41:15 +0000353** MemPage.apCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000354*/
drh72f82862001-05-24 21:06:34 +0000355struct BtCursor {
drh5e2f8b92001-05-28 00:41:15 +0000356 Btree *pBt; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000357 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drh8b2f49b2001-06-08 00:21:52 +0000358 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000359 MemPage *pPage; /* Page that contains the entry */
drh8c42ca92001-06-22 19:15:00 +0000360 int idx; /* Index of the entry in pPage->apCell[] */
drhecdc7532001-09-23 02:35:53 +0000361 u8 wrFlag; /* True if writable */
drh5e2f8b92001-05-28 00:41:15 +0000362 u8 bSkipNext; /* sqliteBtreeNext() is no-op if true */
363 u8 iMatch; /* compare result from last sqliteBtreeMoveto() */
drh365d68f2001-05-11 11:02:46 +0000364};
drh7e3b0a02001-04-28 16:52:40 +0000365
drha059ad02001-04-17 20:09:11 +0000366/*
drh0d316a42002-08-11 20:10:47 +0000367** Routines for byte swapping.
368*/
369u16 swab16(u16 x){
370 return ((x & 0xff)<<8) | ((x>>8)&0xff);
371}
372u32 swab32(u32 x){
373 return ((x & 0xff)<<24) | ((x & 0xff00)<<8) |
374 ((x>>8) & 0xff00) | ((x>>24)&0xff);
375}
376
377/*
drh3b7511c2001-05-26 13:15:44 +0000378** Compute the total number of bytes that a Cell needs on the main
drh5e2f8b92001-05-28 00:41:15 +0000379** database page. The number returned includes the Cell header,
380** local payload storage, and the pointer to overflow pages (if
drh8c42ca92001-06-22 19:15:00 +0000381** applicable). Additional space allocated on overflow pages
drhbd03cae2001-06-02 02:40:57 +0000382** is NOT included in the value returned from this routine.
drh3b7511c2001-05-26 13:15:44 +0000383*/
drh0d316a42002-08-11 20:10:47 +0000384static int cellSize(Btree *pBt, Cell *pCell){
385 int n = NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h);
drh3b7511c2001-05-26 13:15:44 +0000386 if( n>MX_LOCAL_PAYLOAD ){
387 n = MX_LOCAL_PAYLOAD + sizeof(Pgno);
388 }else{
389 n = ROUNDUP(n);
390 }
391 n += sizeof(CellHdr);
392 return n;
393}
394
395/*
drh72f82862001-05-24 21:06:34 +0000396** Defragment the page given. All Cells are moved to the
397** beginning of the page and all free space is collected
398** into one big FreeBlk at the end of the page.
drh365d68f2001-05-11 11:02:46 +0000399*/
drh0d316a42002-08-11 20:10:47 +0000400static void defragmentPage(Btree *pBt, MemPage *pPage){
drh14acc042001-06-10 19:56:58 +0000401 int pc, i, n;
drh2af926b2001-05-15 00:39:25 +0000402 FreeBlk *pFBlk;
403 char newPage[SQLITE_PAGE_SIZE];
404
drh6019e162001-07-02 17:51:45 +0000405 assert( sqlitepager_iswriteable(pPage) );
drh7aa128d2002-06-21 13:09:16 +0000406 assert( pPage->isInit );
drhbd03cae2001-06-02 02:40:57 +0000407 pc = sizeof(PageHdr);
drh0d316a42002-08-11 20:10:47 +0000408 pPage->u.hdr.firstCell = SWAB16(pBt, pc);
drh14acc042001-06-10 19:56:58 +0000409 memcpy(newPage, pPage->u.aDisk, pc);
drh2af926b2001-05-15 00:39:25 +0000410 for(i=0; i<pPage->nCell; i++){
drh2aa679f2001-06-25 02:11:07 +0000411 Cell *pCell = pPage->apCell[i];
drh8c42ca92001-06-22 19:15:00 +0000412
413 /* This routine should never be called on an overfull page. The
414 ** following asserts verify that constraint. */
drh7c717f72001-06-24 20:39:41 +0000415 assert( Addr(pCell) > Addr(pPage) );
416 assert( Addr(pCell) < Addr(pPage) + SQLITE_PAGE_SIZE );
drh8c42ca92001-06-22 19:15:00 +0000417
drh0d316a42002-08-11 20:10:47 +0000418 n = cellSize(pBt, pCell);
419 pCell->h.iNext = SWAB16(pBt, pc + n);
drh2af926b2001-05-15 00:39:25 +0000420 memcpy(&newPage[pc], pCell, n);
drh14acc042001-06-10 19:56:58 +0000421 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[pc];
drh2af926b2001-05-15 00:39:25 +0000422 pc += n;
423 }
drh72f82862001-05-24 21:06:34 +0000424 assert( pPage->nFree==SQLITE_PAGE_SIZE-pc );
drh14acc042001-06-10 19:56:58 +0000425 memcpy(pPage->u.aDisk, newPage, pc);
drh2aa679f2001-06-25 02:11:07 +0000426 if( pPage->nCell>0 ){
427 pPage->apCell[pPage->nCell-1]->h.iNext = 0;
428 }
drh8c42ca92001-06-22 19:15:00 +0000429 pFBlk = (FreeBlk*)&pPage->u.aDisk[pc];
drh0d316a42002-08-11 20:10:47 +0000430 pFBlk->iSize = SWAB16(pBt, SQLITE_PAGE_SIZE - pc);
drh2af926b2001-05-15 00:39:25 +0000431 pFBlk->iNext = 0;
drh0d316a42002-08-11 20:10:47 +0000432 pPage->u.hdr.firstFree = SWAB16(pBt, pc);
drh2af926b2001-05-15 00:39:25 +0000433 memset(&pFBlk[1], 0, SQLITE_PAGE_SIZE - pc - sizeof(FreeBlk));
drh365d68f2001-05-11 11:02:46 +0000434}
435
drha059ad02001-04-17 20:09:11 +0000436/*
drh8b2f49b2001-06-08 00:21:52 +0000437** Allocate nByte bytes of space on a page. nByte must be a
438** multiple of 4.
drhbd03cae2001-06-02 02:40:57 +0000439**
drh14acc042001-06-10 19:56:58 +0000440** Return the index into pPage->u.aDisk[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000441** the new allocation. Or return 0 if there is not enough free
442** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000443**
drh72f82862001-05-24 21:06:34 +0000444** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000445** nBytes of contiguous free space, then this routine automatically
446** calls defragementPage() to consolidate all free space before
447** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000448*/
drh0d316a42002-08-11 20:10:47 +0000449static int allocateSpace(Btree *pBt, MemPage *pPage, int nByte){
drh2af926b2001-05-15 00:39:25 +0000450 FreeBlk *p;
451 u16 *pIdx;
452 int start;
drh8c42ca92001-06-22 19:15:00 +0000453 int cnt = 0;
drh0d316a42002-08-11 20:10:47 +0000454 int iSize;
drh72f82862001-05-24 21:06:34 +0000455
drh6019e162001-07-02 17:51:45 +0000456 assert( sqlitepager_iswriteable(pPage) );
drh5e2f8b92001-05-28 00:41:15 +0000457 assert( nByte==ROUNDUP(nByte) );
drh7aa128d2002-06-21 13:09:16 +0000458 assert( pPage->isInit );
drh14acc042001-06-10 19:56:58 +0000459 if( pPage->nFree<nByte || pPage->isOverfull ) return 0;
460 pIdx = &pPage->u.hdr.firstFree;
drh0d316a42002-08-11 20:10:47 +0000461 p = (FreeBlk*)&pPage->u.aDisk[SWAB16(pBt, *pIdx)];
462 while( (iSize = SWAB16(pBt, p->iSize))<nByte ){
drh8c42ca92001-06-22 19:15:00 +0000463 assert( cnt++ < SQLITE_PAGE_SIZE/4 );
drh2af926b2001-05-15 00:39:25 +0000464 if( p->iNext==0 ){
drh0d316a42002-08-11 20:10:47 +0000465 defragmentPage(pBt, pPage);
drh14acc042001-06-10 19:56:58 +0000466 pIdx = &pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000467 }else{
468 pIdx = &p->iNext;
469 }
drh0d316a42002-08-11 20:10:47 +0000470 p = (FreeBlk*)&pPage->u.aDisk[SWAB16(pBt, *pIdx)];
drh2af926b2001-05-15 00:39:25 +0000471 }
drh0d316a42002-08-11 20:10:47 +0000472 if( iSize==nByte ){
473 start = SWAB16(pBt, *pIdx);
drh2af926b2001-05-15 00:39:25 +0000474 *pIdx = p->iNext;
475 }else{
drh8c42ca92001-06-22 19:15:00 +0000476 FreeBlk *pNew;
drh0d316a42002-08-11 20:10:47 +0000477 start = SWAB16(pBt, *pIdx);
drh8c42ca92001-06-22 19:15:00 +0000478 pNew = (FreeBlk*)&pPage->u.aDisk[start + nByte];
drh72f82862001-05-24 21:06:34 +0000479 pNew->iNext = p->iNext;
drh0d316a42002-08-11 20:10:47 +0000480 pNew->iSize = SWAB16(pBt, iSize - nByte);
481 *pIdx = SWAB16(pBt, start + nByte);
drh2af926b2001-05-15 00:39:25 +0000482 }
483 pPage->nFree -= nByte;
484 return start;
drh7e3b0a02001-04-28 16:52:40 +0000485}
486
487/*
drh14acc042001-06-10 19:56:58 +0000488** Return a section of the MemPage.u.aDisk[] to the freelist.
489** The first byte of the new free block is pPage->u.aDisk[start]
490** and the size of the block is "size" bytes. Size must be
491** a multiple of 4.
drh306dc212001-05-21 13:45:10 +0000492**
493** Most of the effort here is involved in coalesing adjacent
494** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000495*/
drh0d316a42002-08-11 20:10:47 +0000496static void freeSpace(Btree *pBt, MemPage *pPage, int start, int size){
drh2af926b2001-05-15 00:39:25 +0000497 int end = start + size;
498 u16 *pIdx, idx;
499 FreeBlk *pFBlk;
500 FreeBlk *pNew;
501 FreeBlk *pNext;
drh0d316a42002-08-11 20:10:47 +0000502 int iSize;
drh2af926b2001-05-15 00:39:25 +0000503
drh6019e162001-07-02 17:51:45 +0000504 assert( sqlitepager_iswriteable(pPage) );
drh2af926b2001-05-15 00:39:25 +0000505 assert( size == ROUNDUP(size) );
506 assert( start == ROUNDUP(start) );
drh7aa128d2002-06-21 13:09:16 +0000507 assert( pPage->isInit );
drh14acc042001-06-10 19:56:58 +0000508 pIdx = &pPage->u.hdr.firstFree;
drh0d316a42002-08-11 20:10:47 +0000509 idx = SWAB16(pBt, *pIdx);
drh2af926b2001-05-15 00:39:25 +0000510 while( idx!=0 && idx<start ){
drh14acc042001-06-10 19:56:58 +0000511 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +0000512 iSize = SWAB16(pBt, pFBlk->iSize);
513 if( idx + iSize == start ){
514 pFBlk->iSize = SWAB16(pBt, iSize + size);
515 if( idx + iSize + size == SWAB16(pBt, pFBlk->iNext) ){
516 pNext = (FreeBlk*)&pPage->u.aDisk[idx + iSize + size];
517 if( pBt->needSwab ){
518 pFBlk->iSize = swab16(swab16(pNext->iSize)+iSize+size);
519 }else{
520 pFBlk->iSize += pNext->iSize;
521 }
drh2af926b2001-05-15 00:39:25 +0000522 pFBlk->iNext = pNext->iNext;
523 }
524 pPage->nFree += size;
525 return;
526 }
527 pIdx = &pFBlk->iNext;
drh0d316a42002-08-11 20:10:47 +0000528 idx = SWAB16(pBt, *pIdx);
drh2af926b2001-05-15 00:39:25 +0000529 }
drh14acc042001-06-10 19:56:58 +0000530 pNew = (FreeBlk*)&pPage->u.aDisk[start];
drh2af926b2001-05-15 00:39:25 +0000531 if( idx != end ){
drh0d316a42002-08-11 20:10:47 +0000532 pNew->iSize = SWAB16(pBt, size);
533 pNew->iNext = SWAB16(pBt, idx);
drh2af926b2001-05-15 00:39:25 +0000534 }else{
drh14acc042001-06-10 19:56:58 +0000535 pNext = (FreeBlk*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +0000536 pNew->iSize = SWAB16(pBt, size + SWAB16(pBt, pNext->iSize));
drh2af926b2001-05-15 00:39:25 +0000537 pNew->iNext = pNext->iNext;
538 }
drh0d316a42002-08-11 20:10:47 +0000539 *pIdx = SWAB16(pBt, start);
drh2af926b2001-05-15 00:39:25 +0000540 pPage->nFree += size;
drh7e3b0a02001-04-28 16:52:40 +0000541}
542
543/*
544** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000545**
drhbd03cae2001-06-02 02:40:57 +0000546** The pParent parameter must be a pointer to the MemPage which
547** is the parent of the page being initialized. The root of the
drh8b2f49b2001-06-08 00:21:52 +0000548** BTree (usually page 2) has no parent and so for that page,
549** pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000550**
drh72f82862001-05-24 21:06:34 +0000551** Return SQLITE_OK on success. If we see that the page does
552** not contained a well-formed database page, then return
553** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
554** guarantee that the page is well-formed. It only shows that
555** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000556*/
drh0d316a42002-08-11 20:10:47 +0000557static int initPage(Bt *pBt, MemPage *pPage, Pgno pgnoThis, MemPage *pParent){
drh14acc042001-06-10 19:56:58 +0000558 int idx; /* An index into pPage->u.aDisk[] */
559 Cell *pCell; /* A pointer to a Cell in pPage->u.aDisk[] */
560 FreeBlk *pFBlk; /* A pointer to a free block in pPage->u.aDisk[] */
drh5e2f8b92001-05-28 00:41:15 +0000561 int sz; /* The size of a Cell in bytes */
562 int freeSpace; /* Amount of free space on the page */
drh2af926b2001-05-15 00:39:25 +0000563
drh5e2f8b92001-05-28 00:41:15 +0000564 if( pPage->pParent ){
565 assert( pPage->pParent==pParent );
566 return SQLITE_OK;
567 }
568 if( pParent ){
569 pPage->pParent = pParent;
570 sqlitepager_ref(pParent);
571 }
572 if( pPage->isInit ) return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +0000573 pPage->isInit = 1;
drh7e3b0a02001-04-28 16:52:40 +0000574 pPage->nCell = 0;
drh6019e162001-07-02 17:51:45 +0000575 freeSpace = USABLE_SPACE;
drh0d316a42002-08-11 20:10:47 +0000576 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh7e3b0a02001-04-28 16:52:40 +0000577 while( idx!=0 ){
drh8c42ca92001-06-22 19:15:00 +0000578 if( idx>SQLITE_PAGE_SIZE-MIN_CELL_SIZE ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000579 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh8c42ca92001-06-22 19:15:00 +0000580 if( idx!=ROUNDUP(idx) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000581 pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +0000582 sz = cellSize(pBt, pCell);
drh5e2f8b92001-05-28 00:41:15 +0000583 if( idx+sz > SQLITE_PAGE_SIZE ) goto page_format_error;
584 freeSpace -= sz;
585 pPage->apCell[pPage->nCell++] = pCell;
drh0d316a42002-08-11 20:10:47 +0000586 idx = SWAB16(pBt, pCell->h.iNext);
drh2af926b2001-05-15 00:39:25 +0000587 }
588 pPage->nFree = 0;
drh0d316a42002-08-11 20:10:47 +0000589 idx = SWAB16(pBt, pPage->u.hdr.firstFree);
drh2af926b2001-05-15 00:39:25 +0000590 while( idx!=0 ){
drh0d316a42002-08-11 20:10:47 +0000591 int iNext;
drh2af926b2001-05-15 00:39:25 +0000592 if( idx>SQLITE_PAGE_SIZE-sizeof(FreeBlk) ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000593 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000594 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +0000595 pPage->nFree += SWAB16(pBt, pFBlk->iSize);
596 iNext = SWAB16(pBt, pFBlk->iNext);
597 if( iNext>0 && iNext <= idx ) goto page_format_error;
598 idx = iNext;
drh7e3b0a02001-04-28 16:52:40 +0000599 }
drh8b2f49b2001-06-08 00:21:52 +0000600 if( pPage->nCell==0 && pPage->nFree==0 ){
601 /* As a special case, an uninitialized root page appears to be
602 ** an empty database */
603 return SQLITE_OK;
604 }
drh5e2f8b92001-05-28 00:41:15 +0000605 if( pPage->nFree!=freeSpace ) goto page_format_error;
drh7e3b0a02001-04-28 16:52:40 +0000606 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +0000607
608page_format_error:
609 return SQLITE_CORRUPT;
drh7e3b0a02001-04-28 16:52:40 +0000610}
611
612/*
drh8b2f49b2001-06-08 00:21:52 +0000613** Set up a raw page so that it looks like a database page holding
614** no entries.
drhbd03cae2001-06-02 02:40:57 +0000615*/
drh0d316a42002-08-11 20:10:47 +0000616static void zeroPage(Btree *pBt, MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +0000617 PageHdr *pHdr;
618 FreeBlk *pFBlk;
drh6019e162001-07-02 17:51:45 +0000619 assert( sqlitepager_iswriteable(pPage) );
drhbd03cae2001-06-02 02:40:57 +0000620 memset(pPage, 0, SQLITE_PAGE_SIZE);
drh14acc042001-06-10 19:56:58 +0000621 pHdr = &pPage->u.hdr;
drhbd03cae2001-06-02 02:40:57 +0000622 pHdr->firstCell = 0;
drh0d316a42002-08-11 20:10:47 +0000623 pHdr->firstFree = SWAB16(pBt, sizeof(*pHdr));
drhbd03cae2001-06-02 02:40:57 +0000624 pFBlk = (FreeBlk*)&pHdr[1];
625 pFBlk->iNext = 0;
drh0d316a42002-08-11 20:10:47 +0000626 pPage->nFree = SQLITE_PAGE_SIZE - sizeof(*pHdr);
627 pFBlk->iSize = SWAB16(pBt, pPage->nFree);
drh8c42ca92001-06-22 19:15:00 +0000628 pPage->nCell = 0;
629 pPage->isOverfull = 0;
drhbd03cae2001-06-02 02:40:57 +0000630}
631
632/*
drh72f82862001-05-24 21:06:34 +0000633** This routine is called when the reference count for a page
634** reaches zero. We need to unref the pParent pointer when that
635** happens.
636*/
637static void pageDestructor(void *pData){
638 MemPage *pPage = (MemPage*)pData;
639 if( pPage->pParent ){
640 MemPage *pParent = pPage->pParent;
641 pPage->pParent = 0;
642 sqlitepager_unref(pParent);
643 }
644}
645
646/*
drh306dc212001-05-21 13:45:10 +0000647** Open a new database.
648**
649** Actually, this routine just sets up the internal data structures
drh72f82862001-05-24 21:06:34 +0000650** for accessing the database. We do not open the database file
651** until the first page is loaded.
drh382c0242001-10-06 16:33:02 +0000652**
653** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +0000654** a new database with a random name is created. This randomly named
655** database file will be deleted when sqliteBtreeClose() is called.
drha059ad02001-04-17 20:09:11 +0000656*/
drh6019e162001-07-02 17:51:45 +0000657int sqliteBtreeOpen(
658 const char *zFilename, /* Name of the file containing the BTree database */
659 int mode, /* Not currently used */
660 int nCache, /* How many pages in the page cache */
661 Btree **ppBtree /* Pointer to new Btree object written here */
662){
drha059ad02001-04-17 20:09:11 +0000663 Btree *pBt;
drh8c42ca92001-06-22 19:15:00 +0000664 int rc;
drha059ad02001-04-17 20:09:11 +0000665
666 pBt = sqliteMalloc( sizeof(*pBt) );
667 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +0000668 *ppBtree = 0;
drha059ad02001-04-17 20:09:11 +0000669 return SQLITE_NOMEM;
670 }
drh6019e162001-07-02 17:51:45 +0000671 if( nCache<10 ) nCache = 10;
672 rc = sqlitepager_open(&pBt->pPager, zFilename, nCache, EXTRA_SIZE);
drha059ad02001-04-17 20:09:11 +0000673 if( rc!=SQLITE_OK ){
674 if( pBt->pPager ) sqlitepager_close(pBt->pPager);
675 sqliteFree(pBt);
676 *ppBtree = 0;
677 return rc;
678 }
drh72f82862001-05-24 21:06:34 +0000679 sqlitepager_set_destructor(pBt->pPager, pageDestructor);
drha059ad02001-04-17 20:09:11 +0000680 pBt->pCursor = 0;
681 pBt->page1 = 0;
drh5df72a52002-06-06 23:16:05 +0000682 pBt->readOnly = sqlitepager_isreadonly(pBt->pPager);
drhecdc7532001-09-23 02:35:53 +0000683 sqliteHashInit(&pBt->locks, SQLITE_HASH_INT, 0);
drha059ad02001-04-17 20:09:11 +0000684 *ppBtree = pBt;
685 return SQLITE_OK;
686}
687
688/*
689** Close an open database and invalidate all cursors.
690*/
691int sqliteBtreeClose(Btree *pBt){
692 while( pBt->pCursor ){
693 sqliteBtreeCloseCursor(pBt->pCursor);
694 }
695 sqlitepager_close(pBt->pPager);
drhecdc7532001-09-23 02:35:53 +0000696 sqliteHashClear(&pBt->locks);
drha059ad02001-04-17 20:09:11 +0000697 sqliteFree(pBt);
698 return SQLITE_OK;
699}
700
701/*
drh6446c4d2001-12-15 14:22:18 +0000702** Change the limit on the number of pages allowed the cache.
drhcd61c282002-03-06 22:01:34 +0000703**
704** The maximum number of cache pages is set to the absolute
705** value of mxPage. If mxPage is negative, the pager will
706** operate asynchronously - it will not stop to do fsync()s
707** to insure data is written to the disk surface before
708** continuing. Transactions still work if synchronous is off,
709** and the database cannot be corrupted if this program
710** crashes. But if the operating system crashes or there is
711** an abrupt power failure when synchronous is off, the database
712** could be left in an inconsistent and unrecoverable state.
713** Synchronous is on by default so database corruption is not
714** normally a worry.
drhf57b14a2001-09-14 18:54:08 +0000715*/
716int sqliteBtreeSetCacheSize(Btree *pBt, int mxPage){
717 sqlitepager_set_cachesize(pBt->pPager, mxPage);
718 return SQLITE_OK;
719}
720
721/*
drh306dc212001-05-21 13:45:10 +0000722** Get a reference to page1 of the database file. This will
723** also acquire a readlock on that file.
724**
725** SQLITE_OK is returned on success. If the file is not a
726** well-formed database file, then SQLITE_CORRUPT is returned.
727** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
728** is returned if we run out of memory. SQLITE_PROTOCOL is returned
729** if there is a locking protocol violation.
730*/
731static int lockBtree(Btree *pBt){
732 int rc;
733 if( pBt->page1 ) return SQLITE_OK;
drh8c42ca92001-06-22 19:15:00 +0000734 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pBt->page1);
drh306dc212001-05-21 13:45:10 +0000735 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +0000736
737 /* Do some checking to help insure the file we opened really is
738 ** a valid database file.
739 */
740 if( sqlitepager_pagecount(pBt->pPager)>0 ){
drhbd03cae2001-06-02 02:40:57 +0000741 PageOne *pP1 = pBt->page1;
drh0d316a42002-08-11 20:10:47 +0000742 if( strcmp(pP1->zMagic,zMagicHeader)!=0 ||
743 (pP1->iMagic!=MAGIC && swab32(pP1->iMagic)!=MAGIC) ){
drh306dc212001-05-21 13:45:10 +0000744 rc = SQLITE_CORRUPT;
drh72f82862001-05-24 21:06:34 +0000745 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +0000746 }
drh0d316a42002-08-11 20:10:47 +0000747 pBt->needSwab = pP1->iMagic!=MAGIC;
drh306dc212001-05-21 13:45:10 +0000748 }
749 return rc;
750
drh72f82862001-05-24 21:06:34 +0000751page1_init_failed:
drh306dc212001-05-21 13:45:10 +0000752 sqlitepager_unref(pBt->page1);
753 pBt->page1 = 0;
drh72f82862001-05-24 21:06:34 +0000754 return rc;
drh306dc212001-05-21 13:45:10 +0000755}
756
757/*
drhb8ca3072001-12-05 00:21:20 +0000758** If there are no outstanding cursors and we are not in the middle
759** of a transaction but there is a read lock on the database, then
760** this routine unrefs the first page of the database file which
761** has the effect of releasing the read lock.
762**
763** If there are any outstanding cursors, this routine is a no-op.
764**
765** If there is a transaction in progress, this routine is a no-op.
766*/
767static void unlockBtreeIfUnused(Btree *pBt){
768 if( pBt->inTrans==0 && pBt->pCursor==0 && pBt->page1!=0 ){
769 sqlitepager_unref(pBt->page1);
770 pBt->page1 = 0;
771 pBt->inTrans = 0;
drh663fc632002-02-02 18:49:19 +0000772 pBt->inCkpt = 0;
drhb8ca3072001-12-05 00:21:20 +0000773 }
774}
775
776/*
drh8c42ca92001-06-22 19:15:00 +0000777** Create a new database by initializing the first two pages of the
778** file.
drh8b2f49b2001-06-08 00:21:52 +0000779*/
780static int newDatabase(Btree *pBt){
781 MemPage *pRoot;
782 PageOne *pP1;
drh8c42ca92001-06-22 19:15:00 +0000783 int rc;
drh7c717f72001-06-24 20:39:41 +0000784 if( sqlitepager_pagecount(pBt->pPager)>1 ) return SQLITE_OK;
drh8b2f49b2001-06-08 00:21:52 +0000785 pP1 = pBt->page1;
786 rc = sqlitepager_write(pBt->page1);
787 if( rc ) return rc;
drh8c42ca92001-06-22 19:15:00 +0000788 rc = sqlitepager_get(pBt->pPager, 2, (void**)&pRoot);
drh8b2f49b2001-06-08 00:21:52 +0000789 if( rc ) return rc;
790 rc = sqlitepager_write(pRoot);
791 if( rc ){
792 sqlitepager_unref(pRoot);
793 return rc;
794 }
795 strcpy(pP1->zMagic, zMagicHeader);
drh0d316a42002-08-11 20:10:47 +0000796#ifdef SQLITE_TEST
797 if( btree_native_byte_order ){
798 pP1->iMagic = MAGIC;
799 pBt->needSwab = 0;
800 }else{
801 pP1->iMagic = swab32(MAGIC);
802 pBt->needSwab = 1;
803 }
804#else
drh8c42ca92001-06-22 19:15:00 +0000805 pP1->iMagic = MAGIC;
drh0d316a42002-08-11 20:10:47 +0000806 pBt->needSwab = 0;
807#endif
808 zeroPage(pBt, pRoot);
drh8b2f49b2001-06-08 00:21:52 +0000809 sqlitepager_unref(pRoot);
810 return SQLITE_OK;
811}
812
813/*
drh72f82862001-05-24 21:06:34 +0000814** Attempt to start a new transaction.
drh8b2f49b2001-06-08 00:21:52 +0000815**
816** A transaction must be started before attempting any changes
817** to the database. None of the following routines will work
818** unless a transaction is started first:
819**
820** sqliteBtreeCreateTable()
drhc6b52df2002-01-04 03:09:29 +0000821** sqliteBtreeCreateIndex()
drh8b2f49b2001-06-08 00:21:52 +0000822** sqliteBtreeClearTable()
823** sqliteBtreeDropTable()
824** sqliteBtreeInsert()
825** sqliteBtreeDelete()
826** sqliteBtreeUpdateMeta()
drha059ad02001-04-17 20:09:11 +0000827*/
828int sqliteBtreeBeginTrans(Btree *pBt){
829 int rc;
830 if( pBt->inTrans ) return SQLITE_ERROR;
831 if( pBt->page1==0 ){
drh7e3b0a02001-04-28 16:52:40 +0000832 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +0000833 if( rc!=SQLITE_OK ){
834 return rc;
835 }
drha059ad02001-04-17 20:09:11 +0000836 }
drh5df72a52002-06-06 23:16:05 +0000837 if( pBt->readOnly ){
838 rc = SQLITE_OK;
839 }else{
840 rc = sqlitepager_begin(pBt->page1);
841 if( rc==SQLITE_OK ){
842 rc = newDatabase(pBt);
843 }
drha059ad02001-04-17 20:09:11 +0000844 }
drhb8ca3072001-12-05 00:21:20 +0000845 if( rc==SQLITE_OK ){
846 pBt->inTrans = 1;
drh663fc632002-02-02 18:49:19 +0000847 pBt->inCkpt = 0;
drhb8ca3072001-12-05 00:21:20 +0000848 }else{
849 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000850 }
drhb8ca3072001-12-05 00:21:20 +0000851 return rc;
drha059ad02001-04-17 20:09:11 +0000852}
853
854/*
drh2aa679f2001-06-25 02:11:07 +0000855** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +0000856**
857** This will release the write lock on the database file. If there
858** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000859*/
860int sqliteBtreeCommit(Btree *pBt){
861 int rc;
drh2aa679f2001-06-25 02:11:07 +0000862 if( pBt->inTrans==0 ) return SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +0000863 rc = pBt->readOnly ? SQLITE_OK : sqlitepager_commit(pBt->pPager);
drh7c717f72001-06-24 20:39:41 +0000864 pBt->inTrans = 0;
drh663fc632002-02-02 18:49:19 +0000865 pBt->inCkpt = 0;
drh5e00f6c2001-09-13 13:46:56 +0000866 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000867 return rc;
868}
869
870/*
drhecdc7532001-09-23 02:35:53 +0000871** Rollback the transaction in progress. All cursors will be
872** invalided by this operation. Any attempt to use a cursor
873** that was open at the beginning of this operation will result
874** in an error.
drh5e00f6c2001-09-13 13:46:56 +0000875**
876** This will release the write lock on the database file. If there
877** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000878*/
879int sqliteBtreeRollback(Btree *pBt){
880 int rc;
drhecdc7532001-09-23 02:35:53 +0000881 BtCursor *pCur;
drh7c717f72001-06-24 20:39:41 +0000882 if( pBt->inTrans==0 ) return SQLITE_OK;
883 pBt->inTrans = 0;
drh663fc632002-02-02 18:49:19 +0000884 pBt->inCkpt = 0;
drhecdc7532001-09-23 02:35:53 +0000885 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
886 if( pCur->pPage ){
887 sqlitepager_unref(pCur->pPage);
888 pCur->pPage = 0;
889 }
890 }
drh5df72a52002-06-06 23:16:05 +0000891 rc = pBt->readOnly ? SQLITE_OK : sqlitepager_rollback(pBt->pPager);
drh5e00f6c2001-09-13 13:46:56 +0000892 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000893 return rc;
894}
895
896/*
drh663fc632002-02-02 18:49:19 +0000897** Set the checkpoint for the current transaction. The checkpoint serves
898** as a sub-transaction that can be rolled back independently of the
899** main transaction. You must start a transaction before starting a
900** checkpoint. The checkpoint is ended automatically if the transaction
901** commits or rolls back.
902**
903** Only one checkpoint may be active at a time. It is an error to try
904** to start a new checkpoint if another checkpoint is already active.
905*/
906int sqliteBtreeBeginCkpt(Btree *pBt){
907 int rc;
drh0d65dc02002-02-03 00:56:09 +0000908 if( !pBt->inTrans || pBt->inCkpt ){
909 return SQLITE_ERROR;
910 }
drh5df72a52002-06-06 23:16:05 +0000911 rc = pBt->readOnly ? SQLITE_OK : sqlitepager_ckpt_begin(pBt->pPager);
drh663fc632002-02-02 18:49:19 +0000912 pBt->inCkpt = 1;
913 return rc;
914}
915
916
917/*
918** Commit a checkpoint to transaction currently in progress. If no
919** checkpoint is active, this is a no-op.
920*/
921int sqliteBtreeCommitCkpt(Btree *pBt){
922 int rc;
drh5df72a52002-06-06 23:16:05 +0000923 if( pBt->inCkpt && !pBt->readOnly ){
drh663fc632002-02-02 18:49:19 +0000924 rc = sqlitepager_ckpt_commit(pBt->pPager);
925 }else{
926 rc = SQLITE_OK;
927 }
drh0d65dc02002-02-03 00:56:09 +0000928 pBt->inCkpt = 0;
drh663fc632002-02-02 18:49:19 +0000929 return rc;
930}
931
932/*
933** Rollback the checkpoint to the current transaction. If there
934** is no active checkpoint or transaction, this routine is a no-op.
935**
936** All cursors will be invalided by this operation. Any attempt
937** to use a cursor that was open at the beginning of this operation
938** will result in an error.
939*/
940int sqliteBtreeRollbackCkpt(Btree *pBt){
941 int rc;
942 BtCursor *pCur;
drh5df72a52002-06-06 23:16:05 +0000943 if( pBt->inCkpt==0 || pBt->readOnly ) return SQLITE_OK;
drh663fc632002-02-02 18:49:19 +0000944 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
945 if( pCur->pPage ){
946 sqlitepager_unref(pCur->pPage);
947 pCur->pPage = 0;
948 }
949 }
950 rc = sqlitepager_ckpt_rollback(pBt->pPager);
drh0d65dc02002-02-03 00:56:09 +0000951 pBt->inCkpt = 0;
drh663fc632002-02-02 18:49:19 +0000952 return rc;
953}
954
955/*
drh8b2f49b2001-06-08 00:21:52 +0000956** Create a new cursor for the BTree whose root is on the page
957** iTable. The act of acquiring a cursor gets a read lock on
958** the database file.
drh1bee3d72001-10-15 00:44:35 +0000959**
960** If wrFlag==0, then the cursor can only be used for reading.
961** If wrFlag==1, then the cursor can be used for reading or writing.
962** A read/write cursor requires exclusive access to its table. There
drh6446c4d2001-12-15 14:22:18 +0000963** cannot be two or more cursors open on the same table if any one of
drh1bee3d72001-10-15 00:44:35 +0000964** cursors is a read/write cursor. But there can be two or more
965** read-only cursors open on the same table.
drh6446c4d2001-12-15 14:22:18 +0000966**
967** No checking is done to make sure that page iTable really is the
968** root page of a b-tree. If it is not, then the cursor acquired
969** will not work correctly.
drha059ad02001-04-17 20:09:11 +0000970*/
drhecdc7532001-09-23 02:35:53 +0000971int sqliteBtreeCursor(Btree *pBt, int iTable, int wrFlag, BtCursor **ppCur){
drha059ad02001-04-17 20:09:11 +0000972 int rc;
973 BtCursor *pCur;
drh5a2c2c22001-11-21 02:21:11 +0000974 ptr nLock;
drhecdc7532001-09-23 02:35:53 +0000975
drha059ad02001-04-17 20:09:11 +0000976 if( pBt->page1==0 ){
977 rc = lockBtree(pBt);
978 if( rc!=SQLITE_OK ){
979 *ppCur = 0;
980 return rc;
981 }
982 }
drh5df72a52002-06-06 23:16:05 +0000983 if( wrFlag && pBt->readOnly ){
984 *ppCur = 0;
985 return SQLITE_READONLY;
986 }
drha059ad02001-04-17 20:09:11 +0000987 pCur = sqliteMalloc( sizeof(*pCur) );
988 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +0000989 rc = SQLITE_NOMEM;
990 goto create_cursor_exception;
991 }
drh8b2f49b2001-06-08 00:21:52 +0000992 pCur->pgnoRoot = (Pgno)iTable;
drh8c42ca92001-06-22 19:15:00 +0000993 rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +0000994 if( rc!=SQLITE_OK ){
995 goto create_cursor_exception;
996 }
drh0d316a42002-08-11 20:10:47 +0000997 rc = initPage(pBt, pCur->pPage, pCur->pgnoRoot, 0);
drhbd03cae2001-06-02 02:40:57 +0000998 if( rc!=SQLITE_OK ){
999 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00001000 }
drh5a2c2c22001-11-21 02:21:11 +00001001 nLock = (ptr)sqliteHashFind(&pBt->locks, 0, iTable);
drhecdc7532001-09-23 02:35:53 +00001002 if( nLock<0 || (nLock>0 && wrFlag) ){
1003 rc = SQLITE_LOCKED;
1004 goto create_cursor_exception;
1005 }
1006 nLock = wrFlag ? -1 : nLock+1;
1007 sqliteHashInsert(&pBt->locks, 0, iTable, (void*)nLock);
drh14acc042001-06-10 19:56:58 +00001008 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +00001009 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +00001010 pCur->idx = 0;
drha059ad02001-04-17 20:09:11 +00001011 pCur->pNext = pBt->pCursor;
1012 if( pCur->pNext ){
1013 pCur->pNext->pPrev = pCur;
1014 }
drh14acc042001-06-10 19:56:58 +00001015 pCur->pPrev = 0;
drha059ad02001-04-17 20:09:11 +00001016 pBt->pCursor = pCur;
drh2af926b2001-05-15 00:39:25 +00001017 *ppCur = pCur;
1018 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00001019
1020create_cursor_exception:
1021 *ppCur = 0;
1022 if( pCur ){
1023 if( pCur->pPage ) sqlitepager_unref(pCur->pPage);
1024 sqliteFree(pCur);
1025 }
drh5e00f6c2001-09-13 13:46:56 +00001026 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00001027 return rc;
drha059ad02001-04-17 20:09:11 +00001028}
1029
1030/*
drh5e00f6c2001-09-13 13:46:56 +00001031** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00001032** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00001033*/
1034int sqliteBtreeCloseCursor(BtCursor *pCur){
drh5a2c2c22001-11-21 02:21:11 +00001035 ptr nLock;
drha059ad02001-04-17 20:09:11 +00001036 Btree *pBt = pCur->pBt;
drha059ad02001-04-17 20:09:11 +00001037 if( pCur->pPrev ){
1038 pCur->pPrev->pNext = pCur->pNext;
1039 }else{
1040 pBt->pCursor = pCur->pNext;
1041 }
1042 if( pCur->pNext ){
1043 pCur->pNext->pPrev = pCur->pPrev;
1044 }
drhecdc7532001-09-23 02:35:53 +00001045 if( pCur->pPage ){
1046 sqlitepager_unref(pCur->pPage);
1047 }
drh5e00f6c2001-09-13 13:46:56 +00001048 unlockBtreeIfUnused(pBt);
drh5a2c2c22001-11-21 02:21:11 +00001049 nLock = (ptr)sqliteHashFind(&pBt->locks, 0, pCur->pgnoRoot);
drh6d4abfb2001-10-22 02:58:08 +00001050 assert( nLock!=0 || sqlite_malloc_failed );
drhecdc7532001-09-23 02:35:53 +00001051 nLock = nLock<0 ? 0 : nLock-1;
1052 sqliteHashInsert(&pBt->locks, 0, pCur->pgnoRoot, (void*)nLock);
drha059ad02001-04-17 20:09:11 +00001053 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +00001054 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00001055}
1056
drh7e3b0a02001-04-28 16:52:40 +00001057/*
drh5e2f8b92001-05-28 00:41:15 +00001058** Make a temporary cursor by filling in the fields of pTempCur.
1059** The temporary cursor is not on the cursor list for the Btree.
1060*/
drh14acc042001-06-10 19:56:58 +00001061static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00001062 memcpy(pTempCur, pCur, sizeof(*pCur));
1063 pTempCur->pNext = 0;
1064 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00001065 if( pTempCur->pPage ){
1066 sqlitepager_ref(pTempCur->pPage);
1067 }
drh5e2f8b92001-05-28 00:41:15 +00001068}
1069
1070/*
drhbd03cae2001-06-02 02:40:57 +00001071** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00001072** function above.
1073*/
drh14acc042001-06-10 19:56:58 +00001074static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00001075 if( pCur->pPage ){
1076 sqlitepager_unref(pCur->pPage);
1077 }
drh5e2f8b92001-05-28 00:41:15 +00001078}
1079
1080/*
drhbd03cae2001-06-02 02:40:57 +00001081** Set *pSize to the number of bytes of key in the entry the
1082** cursor currently points to. Always return SQLITE_OK.
1083** Failure is not possible. If the cursor is not currently
1084** pointing to an entry (which can happen, for example, if
1085** the database is empty) then *pSize is set to 0.
drh7e3b0a02001-04-28 16:52:40 +00001086*/
drh72f82862001-05-24 21:06:34 +00001087int sqliteBtreeKeySize(BtCursor *pCur, int *pSize){
drh2af926b2001-05-15 00:39:25 +00001088 Cell *pCell;
1089 MemPage *pPage;
1090
1091 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001092 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh72f82862001-05-24 21:06:34 +00001093 *pSize = 0;
1094 }else{
drh5e2f8b92001-05-28 00:41:15 +00001095 pCell = pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00001096 *pSize = NKEY(pCur->pBt, pCell->h);
drh72f82862001-05-24 21:06:34 +00001097 }
1098 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00001099}
drh2af926b2001-05-15 00:39:25 +00001100
drh72f82862001-05-24 21:06:34 +00001101/*
1102** Read payload information from the entry that the pCur cursor is
1103** pointing to. Begin reading the payload at "offset" and read
1104** a total of "amt" bytes. Put the result in zBuf.
1105**
1106** This routine does not make a distinction between key and data.
1107** It just reads bytes from the payload area.
1108*/
drh2af926b2001-05-15 00:39:25 +00001109static int getPayload(BtCursor *pCur, int offset, int amt, char *zBuf){
drh5e2f8b92001-05-28 00:41:15 +00001110 char *aPayload;
drh2af926b2001-05-15 00:39:25 +00001111 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +00001112 int rc;
drh0d316a42002-08-11 20:10:47 +00001113 Btree *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00001114 assert( pCur!=0 && pCur->pPage!=0 );
drh8c42ca92001-06-22 19:15:00 +00001115 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
1116 aPayload = pCur->pPage->apCell[pCur->idx]->aPayload;
drh2af926b2001-05-15 00:39:25 +00001117 if( offset<MX_LOCAL_PAYLOAD ){
1118 int a = amt;
1119 if( a+offset>MX_LOCAL_PAYLOAD ){
1120 a = MX_LOCAL_PAYLOAD - offset;
1121 }
drh5e2f8b92001-05-28 00:41:15 +00001122 memcpy(zBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +00001123 if( a==amt ){
1124 return SQLITE_OK;
1125 }
drh2aa679f2001-06-25 02:11:07 +00001126 offset = 0;
drh2af926b2001-05-15 00:39:25 +00001127 zBuf += a;
1128 amt -= a;
drhdd793422001-06-28 01:54:48 +00001129 }else{
1130 offset -= MX_LOCAL_PAYLOAD;
drhbd03cae2001-06-02 02:40:57 +00001131 }
1132 if( amt>0 ){
drh0d316a42002-08-11 20:10:47 +00001133 nextPage = SWAB32(pBt, pCur->pPage->apCell[pCur->idx]->ovfl);
drh2af926b2001-05-15 00:39:25 +00001134 }
1135 while( amt>0 && nextPage ){
1136 OverflowPage *pOvfl;
drh0d316a42002-08-11 20:10:47 +00001137 rc = sqlitepager_get(pBt->pPager, nextPage, (void**)&pOvfl);
drh2af926b2001-05-15 00:39:25 +00001138 if( rc!=0 ){
1139 return rc;
1140 }
drh0d316a42002-08-11 20:10:47 +00001141 nextPage = SWAB32(pBt, pOvfl->iNext);
drh2af926b2001-05-15 00:39:25 +00001142 if( offset<OVERFLOW_SIZE ){
1143 int a = amt;
1144 if( a + offset > OVERFLOW_SIZE ){
1145 a = OVERFLOW_SIZE - offset;
1146 }
drh5e2f8b92001-05-28 00:41:15 +00001147 memcpy(zBuf, &pOvfl->aPayload[offset], a);
drh2aa679f2001-06-25 02:11:07 +00001148 offset = 0;
drh2af926b2001-05-15 00:39:25 +00001149 amt -= a;
1150 zBuf += a;
drh2aa679f2001-06-25 02:11:07 +00001151 }else{
1152 offset -= OVERFLOW_SIZE;
drh2af926b2001-05-15 00:39:25 +00001153 }
1154 sqlitepager_unref(pOvfl);
1155 }
drha7fcb052001-12-14 15:09:55 +00001156 if( amt>0 ){
1157 return SQLITE_CORRUPT;
1158 }
1159 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00001160}
1161
drh72f82862001-05-24 21:06:34 +00001162/*
drh5e00f6c2001-09-13 13:46:56 +00001163** Read part of the key associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +00001164** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +00001165** begins at "offset". The number of bytes actually read is
1166** returned. The amount returned will be smaller than the
1167** amount requested if there are not enough bytes in the key
1168** to satisfy the request.
drh72f82862001-05-24 21:06:34 +00001169*/
1170int sqliteBtreeKey(BtCursor *pCur, int offset, int amt, char *zBuf){
1171 Cell *pCell;
1172 MemPage *pPage;
drha059ad02001-04-17 20:09:11 +00001173
drh5e00f6c2001-09-13 13:46:56 +00001174 if( amt<0 ) return 0;
1175 if( offset<0 ) return 0;
1176 if( amt==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001177 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001178 if( pPage==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001179 if( pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +00001180 return 0;
drh72f82862001-05-24 21:06:34 +00001181 }
drh5e2f8b92001-05-28 00:41:15 +00001182 pCell = pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00001183 if( amt+offset > NKEY(pCur->pBt, pCell->h) ){
1184 amt = NKEY(pCur->pBt, pCell->h) - offset;
drh5e00f6c2001-09-13 13:46:56 +00001185 if( amt<=0 ){
1186 return 0;
1187 }
drhbd03cae2001-06-02 02:40:57 +00001188 }
drh5e00f6c2001-09-13 13:46:56 +00001189 getPayload(pCur, offset, amt, zBuf);
1190 return amt;
drh72f82862001-05-24 21:06:34 +00001191}
1192
1193/*
drhbd03cae2001-06-02 02:40:57 +00001194** Set *pSize to the number of bytes of data in the entry the
1195** cursor currently points to. Always return SQLITE_OK.
1196** Failure is not possible. If the cursor is not currently
1197** pointing to an entry (which can happen, for example, if
1198** the database is empty) then *pSize is set to 0.
drh72f82862001-05-24 21:06:34 +00001199*/
1200int sqliteBtreeDataSize(BtCursor *pCur, int *pSize){
1201 Cell *pCell;
1202 MemPage *pPage;
1203
1204 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001205 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh72f82862001-05-24 21:06:34 +00001206 *pSize = 0;
1207 }else{
drh5e2f8b92001-05-28 00:41:15 +00001208 pCell = pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00001209 *pSize = NDATA(pCur->pBt, pCell->h);
drh72f82862001-05-24 21:06:34 +00001210 }
1211 return SQLITE_OK;
1212}
1213
1214/*
drh5e00f6c2001-09-13 13:46:56 +00001215** Read part of the data associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +00001216** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +00001217** begins at "offset". The number of bytes actually read is
1218** returned. The amount returned will be smaller than the
1219** amount requested if there are not enough bytes in the data
1220** to satisfy the request.
drh72f82862001-05-24 21:06:34 +00001221*/
1222int sqliteBtreeData(BtCursor *pCur, int offset, int amt, char *zBuf){
1223 Cell *pCell;
1224 MemPage *pPage;
drh0d316a42002-08-11 20:10:47 +00001225 int nData;
drh72f82862001-05-24 21:06:34 +00001226
drh5e00f6c2001-09-13 13:46:56 +00001227 if( amt<0 ) return 0;
1228 if( offset<0 ) return 0;
1229 if( amt==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001230 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001231 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +00001232 return 0;
drh72f82862001-05-24 21:06:34 +00001233 }
drh5e2f8b92001-05-28 00:41:15 +00001234 pCell = pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00001235 nData = NDATA(pCur->pBt, pCell->h);
1236 if( amt+offset > nData ){
1237 amt = nData - offset;
drh5e00f6c2001-09-13 13:46:56 +00001238 if( amt<=0 ){
1239 return 0;
1240 }
drhbd03cae2001-06-02 02:40:57 +00001241 }
drh0d316a42002-08-11 20:10:47 +00001242 getPayload(pCur, offset + NKEY(pCur->pBt, pCell->h), amt, zBuf);
drh5e00f6c2001-09-13 13:46:56 +00001243 return amt;
drh72f82862001-05-24 21:06:34 +00001244}
drha059ad02001-04-17 20:09:11 +00001245
drh2af926b2001-05-15 00:39:25 +00001246/*
drh8721ce42001-11-07 14:22:00 +00001247** Compare an external key against the key on the entry that pCur points to.
1248**
1249** The external key is pKey and is nKey bytes long. The last nIgnore bytes
1250** of the key associated with pCur are ignored, as if they do not exist.
1251** (The normal case is for nIgnore to be zero in which case the entire
1252** internal key is used in the comparison.)
1253**
1254** The comparison result is written to *pRes as follows:
drh2af926b2001-05-15 00:39:25 +00001255**
drh717e6402001-09-27 03:22:32 +00001256** *pRes<0 This means pCur<pKey
1257**
1258** *pRes==0 This means pCur==pKey for all nKey bytes
1259**
1260** *pRes>0 This means pCur>pKey
1261**
drh8721ce42001-11-07 14:22:00 +00001262** When one key is an exact prefix of the other, the shorter key is
1263** considered less than the longer one. In order to be equal the
1264** keys must be exactly the same length. (The length of the pCur key
1265** is the actual key length minus nIgnore bytes.)
drh2af926b2001-05-15 00:39:25 +00001266*/
drh717e6402001-09-27 03:22:32 +00001267int sqliteBtreeKeyCompare(
drh8721ce42001-11-07 14:22:00 +00001268 BtCursor *pCur, /* Pointer to entry to compare against */
1269 const void *pKey, /* Key to compare against entry that pCur points to */
1270 int nKey, /* Number of bytes in pKey */
1271 int nIgnore, /* Ignore this many bytes at the end of pCur */
1272 int *pResult /* Write the result here */
drh5c4d9702001-08-20 00:33:58 +00001273){
drh2af926b2001-05-15 00:39:25 +00001274 Pgno nextPage;
drh8721ce42001-11-07 14:22:00 +00001275 int n, c, rc, nLocal;
drh2af926b2001-05-15 00:39:25 +00001276 Cell *pCell;
drh0d316a42002-08-11 20:10:47 +00001277 Btree *pBt = pCur->pBt;
drh717e6402001-09-27 03:22:32 +00001278 const char *zKey = (const char*)pKey;
drh2af926b2001-05-15 00:39:25 +00001279
1280 assert( pCur->pPage );
1281 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drhbd03cae2001-06-02 02:40:57 +00001282 pCell = pCur->pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00001283 nLocal = NKEY(pBt, pCell->h) - nIgnore;
drh8721ce42001-11-07 14:22:00 +00001284 if( nLocal<0 ) nLocal = 0;
1285 n = nKey<nLocal ? nKey : nLocal;
drh2af926b2001-05-15 00:39:25 +00001286 if( n>MX_LOCAL_PAYLOAD ){
1287 n = MX_LOCAL_PAYLOAD;
1288 }
drh717e6402001-09-27 03:22:32 +00001289 c = memcmp(pCell->aPayload, zKey, n);
drh2af926b2001-05-15 00:39:25 +00001290 if( c!=0 ){
1291 *pResult = c;
1292 return SQLITE_OK;
1293 }
drh717e6402001-09-27 03:22:32 +00001294 zKey += n;
drh2af926b2001-05-15 00:39:25 +00001295 nKey -= n;
drh8721ce42001-11-07 14:22:00 +00001296 nLocal -= n;
drh0d316a42002-08-11 20:10:47 +00001297 nextPage = SWAB32(pBt, pCell->ovfl);
drh8721ce42001-11-07 14:22:00 +00001298 while( nKey>0 && nLocal>0 ){
drh2af926b2001-05-15 00:39:25 +00001299 OverflowPage *pOvfl;
1300 if( nextPage==0 ){
1301 return SQLITE_CORRUPT;
1302 }
drh0d316a42002-08-11 20:10:47 +00001303 rc = sqlitepager_get(pBt->pPager, nextPage, (void**)&pOvfl);
drh72f82862001-05-24 21:06:34 +00001304 if( rc ){
drh2af926b2001-05-15 00:39:25 +00001305 return rc;
1306 }
drh0d316a42002-08-11 20:10:47 +00001307 nextPage = SWAB32(pBt, pOvfl->iNext);
drh8721ce42001-11-07 14:22:00 +00001308 n = nKey<nLocal ? nKey : nLocal;
drh2af926b2001-05-15 00:39:25 +00001309 if( n>OVERFLOW_SIZE ){
1310 n = OVERFLOW_SIZE;
1311 }
drh717e6402001-09-27 03:22:32 +00001312 c = memcmp(pOvfl->aPayload, zKey, n);
drh2af926b2001-05-15 00:39:25 +00001313 sqlitepager_unref(pOvfl);
1314 if( c!=0 ){
1315 *pResult = c;
1316 return SQLITE_OK;
1317 }
1318 nKey -= n;
drh8721ce42001-11-07 14:22:00 +00001319 nLocal -= n;
drh717e6402001-09-27 03:22:32 +00001320 zKey += n;
drh2af926b2001-05-15 00:39:25 +00001321 }
drh717e6402001-09-27 03:22:32 +00001322 if( c==0 ){
drh8721ce42001-11-07 14:22:00 +00001323 c = nLocal - nKey;
drh717e6402001-09-27 03:22:32 +00001324 }
drh2af926b2001-05-15 00:39:25 +00001325 *pResult = c;
1326 return SQLITE_OK;
1327}
1328
drh72f82862001-05-24 21:06:34 +00001329/*
1330** Move the cursor down to a new child page.
1331*/
drh5e2f8b92001-05-28 00:41:15 +00001332static int moveToChild(BtCursor *pCur, int newPgno){
drh72f82862001-05-24 21:06:34 +00001333 int rc;
1334 MemPage *pNewPage;
drh0d316a42002-08-11 20:10:47 +00001335 Btree *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00001336
drh0d316a42002-08-11 20:10:47 +00001337 rc = sqlitepager_get(pBt->pPager, newPgno, (void**)&pNewPage);
drh6019e162001-07-02 17:51:45 +00001338 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001339 rc = initPage(pBt, pNewPage, newPgno, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00001340 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001341 sqlitepager_unref(pCur->pPage);
1342 pCur->pPage = pNewPage;
1343 pCur->idx = 0;
1344 return SQLITE_OK;
1345}
1346
1347/*
drh5e2f8b92001-05-28 00:41:15 +00001348** Move the cursor up to the parent page.
1349**
1350** pCur->idx is set to the cell index that contains the pointer
1351** to the page we are coming from. If we are coming from the
1352** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00001353** the largest cell index.
drh72f82862001-05-24 21:06:34 +00001354*/
drh5e2f8b92001-05-28 00:41:15 +00001355static int moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001356 Pgno oldPgno;
1357 MemPage *pParent;
drh8c42ca92001-06-22 19:15:00 +00001358 int i;
drh72f82862001-05-24 21:06:34 +00001359 pParent = pCur->pPage->pParent;
drhbd03cae2001-06-02 02:40:57 +00001360 if( pParent==0 ) return SQLITE_INTERNAL;
drh72f82862001-05-24 21:06:34 +00001361 oldPgno = sqlitepager_pagenumber(pCur->pPage);
drh72f82862001-05-24 21:06:34 +00001362 sqlitepager_ref(pParent);
1363 sqlitepager_unref(pCur->pPage);
1364 pCur->pPage = pParent;
drh8c42ca92001-06-22 19:15:00 +00001365 pCur->idx = pParent->nCell;
drh0d316a42002-08-11 20:10:47 +00001366 oldPgno = SWAB32(pCur->pBt, oldPgno);
drh8c42ca92001-06-22 19:15:00 +00001367 for(i=0; i<pParent->nCell; i++){
1368 if( pParent->apCell[i]->h.leftChild==oldPgno ){
drh72f82862001-05-24 21:06:34 +00001369 pCur->idx = i;
1370 break;
1371 }
1372 }
drh5e2f8b92001-05-28 00:41:15 +00001373 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00001374}
1375
1376/*
1377** Move the cursor to the root page
1378*/
drh5e2f8b92001-05-28 00:41:15 +00001379static int moveToRoot(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001380 MemPage *pNew;
drhbd03cae2001-06-02 02:40:57 +00001381 int rc;
drh0d316a42002-08-11 20:10:47 +00001382 Btree *pBt = pCur->pBt;
drhbd03cae2001-06-02 02:40:57 +00001383
drh0d316a42002-08-11 20:10:47 +00001384 rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pNew);
drhbd03cae2001-06-02 02:40:57 +00001385 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001386 rc = initPage(pBt, pNew, pCur->pgnoRoot, 0);
drh6019e162001-07-02 17:51:45 +00001387 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001388 sqlitepager_unref(pCur->pPage);
1389 pCur->pPage = pNew;
1390 pCur->idx = 0;
1391 return SQLITE_OK;
1392}
drh2af926b2001-05-15 00:39:25 +00001393
drh5e2f8b92001-05-28 00:41:15 +00001394/*
1395** Move the cursor down to the left-most leaf entry beneath the
1396** entry to which it is currently pointing.
1397*/
1398static int moveToLeftmost(BtCursor *pCur){
1399 Pgno pgno;
1400 int rc;
1401
1402 while( (pgno = pCur->pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
drh0d316a42002-08-11 20:10:47 +00001403 rc = moveToChild(pCur, SWAB32(pCur->pBt, pgno));
drh5e2f8b92001-05-28 00:41:15 +00001404 if( rc ) return rc;
1405 }
1406 return SQLITE_OK;
1407}
1408
drh5e00f6c2001-09-13 13:46:56 +00001409/* Move the cursor to the first entry in the table. Return SQLITE_OK
1410** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00001411** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00001412*/
1413int sqliteBtreeFirst(BtCursor *pCur, int *pRes){
1414 int rc;
drhecdc7532001-09-23 02:35:53 +00001415 if( pCur->pPage==0 ) return SQLITE_ABORT;
drh5e00f6c2001-09-13 13:46:56 +00001416 rc = moveToRoot(pCur);
1417 if( rc ) return rc;
1418 if( pCur->pPage->nCell==0 ){
1419 *pRes = 1;
1420 return SQLITE_OK;
1421 }
1422 *pRes = 0;
1423 rc = moveToLeftmost(pCur);
drh0ce92ed2001-12-15 02:47:28 +00001424 pCur->bSkipNext = 0;
drh5e00f6c2001-09-13 13:46:56 +00001425 return rc;
1426}
drh5e2f8b92001-05-28 00:41:15 +00001427
drh9562b552002-02-19 15:00:07 +00001428/* Move the cursor to the last entry in the table. Return SQLITE_OK
1429** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00001430** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00001431*/
1432int sqliteBtreeLast(BtCursor *pCur, int *pRes){
1433 int rc;
1434 Pgno pgno;
1435 if( pCur->pPage==0 ) return SQLITE_ABORT;
1436 rc = moveToRoot(pCur);
1437 if( rc ) return rc;
drh7aa128d2002-06-21 13:09:16 +00001438 assert( pCur->pPage->isInit );
drh9562b552002-02-19 15:00:07 +00001439 if( pCur->pPage->nCell==0 ){
1440 *pRes = 1;
1441 return SQLITE_OK;
1442 }
1443 *pRes = 0;
1444 while( (pgno = pCur->pPage->u.hdr.rightChild)!=0 ){
drh0d316a42002-08-11 20:10:47 +00001445 rc = moveToChild(pCur, SWAB32(pCur->pBt, pgno));
drh9562b552002-02-19 15:00:07 +00001446 if( rc ) return rc;
1447 }
1448 pCur->idx = pCur->pPage->nCell-1;
1449 pCur->bSkipNext = 0;
1450 return rc;
1451}
1452
drha059ad02001-04-17 20:09:11 +00001453/* Move the cursor so that it points to an entry near pKey.
drh72f82862001-05-24 21:06:34 +00001454** Return a success code.
1455**
drh5e2f8b92001-05-28 00:41:15 +00001456** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00001457** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00001458** were present. The cursor might point to an entry that comes
1459** before or after the key.
1460**
drhbd03cae2001-06-02 02:40:57 +00001461** The result of comparing the key with the entry to which the
1462** cursor is left pointing is stored in pCur->iMatch. The same
1463** value is also written to *pRes if pRes!=NULL. The meaning of
1464** this value is as follows:
1465**
1466** *pRes<0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001467** is smaller than pKey.
drhbd03cae2001-06-02 02:40:57 +00001468**
1469** *pRes==0 The cursor is left pointing at an entry that
1470** exactly matches pKey.
1471**
1472** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001473** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00001474*/
drh5c4d9702001-08-20 00:33:58 +00001475int sqliteBtreeMoveto(BtCursor *pCur, const void *pKey, int nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00001476 int rc;
drhecdc7532001-09-23 02:35:53 +00001477 if( pCur->pPage==0 ) return SQLITE_ABORT;
drh7c717f72001-06-24 20:39:41 +00001478 pCur->bSkipNext = 0;
drh5e2f8b92001-05-28 00:41:15 +00001479 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00001480 if( rc ) return rc;
1481 for(;;){
1482 int lwr, upr;
1483 Pgno chldPg;
1484 MemPage *pPage = pCur->pPage;
drh8b2f49b2001-06-08 00:21:52 +00001485 int c = -1;
drh72f82862001-05-24 21:06:34 +00001486 lwr = 0;
1487 upr = pPage->nCell-1;
1488 while( lwr<=upr ){
drh72f82862001-05-24 21:06:34 +00001489 pCur->idx = (lwr+upr)/2;
drh8721ce42001-11-07 14:22:00 +00001490 rc = sqliteBtreeKeyCompare(pCur, pKey, nKey, 0, &c);
drh72f82862001-05-24 21:06:34 +00001491 if( rc ) return rc;
1492 if( c==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001493 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001494 if( pRes ) *pRes = 0;
1495 return SQLITE_OK;
1496 }
1497 if( c<0 ){
1498 lwr = pCur->idx+1;
1499 }else{
1500 upr = pCur->idx-1;
1501 }
1502 }
1503 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00001504 assert( pPage->isInit );
drh72f82862001-05-24 21:06:34 +00001505 if( lwr>=pPage->nCell ){
drh14acc042001-06-10 19:56:58 +00001506 chldPg = pPage->u.hdr.rightChild;
drh72f82862001-05-24 21:06:34 +00001507 }else{
drh5e2f8b92001-05-28 00:41:15 +00001508 chldPg = pPage->apCell[lwr]->h.leftChild;
drh72f82862001-05-24 21:06:34 +00001509 }
1510 if( chldPg==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001511 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001512 if( pRes ) *pRes = c;
1513 return SQLITE_OK;
1514 }
drh0d316a42002-08-11 20:10:47 +00001515 rc = moveToChild(pCur, SWAB32(pCur->pBt, chldPg));
drh72f82862001-05-24 21:06:34 +00001516 if( rc ) return rc;
1517 }
drhbd03cae2001-06-02 02:40:57 +00001518 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00001519}
1520
1521/*
drhbd03cae2001-06-02 02:40:57 +00001522** Advance the cursor to the next entry in the database. If
1523** successful and pRes!=NULL then set *pRes=0. If the cursor
1524** was already pointing to the last entry in the database before
1525** this routine was called, then set *pRes=1 if pRes!=NULL.
drh72f82862001-05-24 21:06:34 +00001526*/
1527int sqliteBtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00001528 int rc;
drhecdc7532001-09-23 02:35:53 +00001529 if( pCur->pPage==0 ){
drh1bee3d72001-10-15 00:44:35 +00001530 if( pRes ) *pRes = 1;
drhecdc7532001-09-23 02:35:53 +00001531 return SQLITE_ABORT;
1532 }
drh7aa128d2002-06-21 13:09:16 +00001533 assert( pCur->pPage->isInit );
drhf5bf0a72001-11-23 00:24:12 +00001534 if( pCur->bSkipNext && pCur->idx<pCur->pPage->nCell ){
drh5e2f8b92001-05-28 00:41:15 +00001535 pCur->bSkipNext = 0;
drh72f82862001-05-24 21:06:34 +00001536 if( pRes ) *pRes = 0;
1537 return SQLITE_OK;
1538 }
drh72f82862001-05-24 21:06:34 +00001539 pCur->idx++;
drh5e2f8b92001-05-28 00:41:15 +00001540 if( pCur->idx>=pCur->pPage->nCell ){
drh8c42ca92001-06-22 19:15:00 +00001541 if( pCur->pPage->u.hdr.rightChild ){
drh0d316a42002-08-11 20:10:47 +00001542 rc = moveToChild(pCur, SWAB32(pCur->pBt, pCur->pPage->u.hdr.rightChild));
drh5e2f8b92001-05-28 00:41:15 +00001543 if( rc ) return rc;
1544 rc = moveToLeftmost(pCur);
1545 if( rc ) return rc;
1546 if( pRes ) *pRes = 0;
drh72f82862001-05-24 21:06:34 +00001547 return SQLITE_OK;
1548 }
drh5e2f8b92001-05-28 00:41:15 +00001549 do{
drh8c42ca92001-06-22 19:15:00 +00001550 if( pCur->pPage->pParent==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001551 if( pRes ) *pRes = 1;
1552 return SQLITE_OK;
1553 }
1554 rc = moveToParent(pCur);
1555 if( rc ) return rc;
1556 }while( pCur->idx>=pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00001557 if( pRes ) *pRes = 0;
1558 return SQLITE_OK;
1559 }
drh5e2f8b92001-05-28 00:41:15 +00001560 rc = moveToLeftmost(pCur);
1561 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001562 if( pRes ) *pRes = 0;
1563 return SQLITE_OK;
1564}
1565
drh3b7511c2001-05-26 13:15:44 +00001566/*
1567** Allocate a new page from the database file.
1568**
1569** The new page is marked as dirty. (In other words, sqlitepager_write()
1570** has already been called on the new page.) The new page has also
1571** been referenced and the calling routine is responsible for calling
1572** sqlitepager_unref() on the new page when it is done.
1573**
1574** SQLITE_OK is returned on success. Any other return value indicates
1575** an error. *ppPage and *pPgno are undefined in the event of an error.
1576** Do not invoke sqlitepager_unref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00001577**
drh199e3cf2002-07-18 11:01:47 +00001578** If the "nearby" parameter is not 0, then a (feeble) effort is made to
1579** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00001580** attempt to keep related pages close to each other in the database file,
1581** which in turn can make database access faster.
drh3b7511c2001-05-26 13:15:44 +00001582*/
drh199e3cf2002-07-18 11:01:47 +00001583static int allocatePage(Btree *pBt, MemPage **ppPage, Pgno *pPgno, Pgno nearby){
drhbd03cae2001-06-02 02:40:57 +00001584 PageOne *pPage1 = pBt->page1;
drh8c42ca92001-06-22 19:15:00 +00001585 int rc;
drh3b7511c2001-05-26 13:15:44 +00001586 if( pPage1->freeList ){
1587 OverflowPage *pOvfl;
drh30e58752002-03-02 20:41:57 +00001588 FreelistInfo *pInfo;
1589
drh3b7511c2001-05-26 13:15:44 +00001590 rc = sqlitepager_write(pPage1);
1591 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001592 SWAB_ADD(pBt, pPage1->nFree, -1);
1593 rc = sqlitepager_get(pBt->pPager, SWAB32(pBt, pPage1->freeList),
1594 (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001595 if( rc ) return rc;
1596 rc = sqlitepager_write(pOvfl);
1597 if( rc ){
1598 sqlitepager_unref(pOvfl);
1599 return rc;
1600 }
drh30e58752002-03-02 20:41:57 +00001601 pInfo = (FreelistInfo*)pOvfl->aPayload;
1602 if( pInfo->nFree==0 ){
drh0d316a42002-08-11 20:10:47 +00001603 *pPgno = SWAB32(pBt, pPage1->freeList);
drh30e58752002-03-02 20:41:57 +00001604 pPage1->freeList = pOvfl->iNext;
1605 *ppPage = (MemPage*)pOvfl;
1606 }else{
drh0d316a42002-08-11 20:10:47 +00001607 int closest, n;
1608 n = SWAB32(pBt, pInfo->nFree);
1609 if( n>1 && nearby>0 ){
drhbea00b92002-07-08 10:59:50 +00001610 int i, dist;
1611 closest = 0;
drh0d316a42002-08-11 20:10:47 +00001612 dist = SWAB32(pBt, pInfo->aFree[0]) - nearby;
drhbea00b92002-07-08 10:59:50 +00001613 if( dist<0 ) dist = -dist;
drh0d316a42002-08-11 20:10:47 +00001614 for(i=1; i<n; i++){
1615 int d2 = SWAB32(pBt, pInfo->aFree[i]) - nearby;
drhbea00b92002-07-08 10:59:50 +00001616 if( d2<0 ) d2 = -d2;
1617 if( d2<dist ) closest = i;
1618 }
1619 }else{
1620 closest = 0;
1621 }
drh0d316a42002-08-11 20:10:47 +00001622 SWAB_ADD(pBt, pInfo->nFree, -1);
1623 *pPgno = SWAB32(pBt, pInfo->aFree[closest]);
1624 pInfo->aFree[closest] = pInfo->aFree[n-1];
drh30e58752002-03-02 20:41:57 +00001625 rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
1626 sqlitepager_unref(pOvfl);
1627 if( rc==SQLITE_OK ){
1628 sqlitepager_dont_rollback(*ppPage);
1629 rc = sqlitepager_write(*ppPage);
1630 }
1631 }
drh3b7511c2001-05-26 13:15:44 +00001632 }else{
drh2aa679f2001-06-25 02:11:07 +00001633 *pPgno = sqlitepager_pagecount(pBt->pPager) + 1;
drh8c42ca92001-06-22 19:15:00 +00001634 rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
drh3b7511c2001-05-26 13:15:44 +00001635 if( rc ) return rc;
1636 rc = sqlitepager_write(*ppPage);
1637 }
1638 return rc;
1639}
1640
1641/*
1642** Add a page of the database file to the freelist. Either pgno or
1643** pPage but not both may be 0.
drh5e2f8b92001-05-28 00:41:15 +00001644**
drhdd793422001-06-28 01:54:48 +00001645** sqlitepager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00001646*/
1647static int freePage(Btree *pBt, void *pPage, Pgno pgno){
drhbd03cae2001-06-02 02:40:57 +00001648 PageOne *pPage1 = pBt->page1;
drh3b7511c2001-05-26 13:15:44 +00001649 OverflowPage *pOvfl = (OverflowPage*)pPage;
1650 int rc;
drhdd793422001-06-28 01:54:48 +00001651 int needUnref = 0;
1652 MemPage *pMemPage;
drh8b2f49b2001-06-08 00:21:52 +00001653
drh3b7511c2001-05-26 13:15:44 +00001654 if( pgno==0 ){
1655 assert( pOvfl!=0 );
1656 pgno = sqlitepager_pagenumber(pOvfl);
1657 }
drh2aa679f2001-06-25 02:11:07 +00001658 assert( pgno>2 );
drh193a6b42002-07-07 16:52:46 +00001659 pMemPage = (MemPage*)pPage;
1660 pMemPage->isInit = 0;
1661 if( pMemPage->pParent ){
1662 sqlitepager_unref(pMemPage->pParent);
1663 pMemPage->pParent = 0;
1664 }
drh3b7511c2001-05-26 13:15:44 +00001665 rc = sqlitepager_write(pPage1);
1666 if( rc ){
1667 return rc;
1668 }
drh0d316a42002-08-11 20:10:47 +00001669 SWAB_ADD(pBt, pPage1->nFree, 1);
1670 if( pPage1->nFree!=0 && pPage1->freeList!=0 ){
drh30e58752002-03-02 20:41:57 +00001671 OverflowPage *pFreeIdx;
drh0d316a42002-08-11 20:10:47 +00001672 rc = sqlitepager_get(pBt->pPager, SWAB32(pBt, pPage1->freeList),
1673 (void**)&pFreeIdx);
drh30e58752002-03-02 20:41:57 +00001674 if( rc==SQLITE_OK ){
1675 FreelistInfo *pInfo = (FreelistInfo*)pFreeIdx->aPayload;
drh0d316a42002-08-11 20:10:47 +00001676 int n = SWAB32(pBt, pInfo->nFree);
1677 if( n<(sizeof(pInfo->aFree)/sizeof(pInfo->aFree[0])) ){
drh30e58752002-03-02 20:41:57 +00001678 rc = sqlitepager_write(pFreeIdx);
1679 if( rc==SQLITE_OK ){
drh0d316a42002-08-11 20:10:47 +00001680 pInfo->aFree[n] = SWAB32(pBt, pgno);
1681 SWAB_ADD(pBt, pInfo->nFree, 1);
drh30e58752002-03-02 20:41:57 +00001682 sqlitepager_unref(pFreeIdx);
1683 sqlitepager_dont_write(pBt->pPager, pgno);
1684 return rc;
1685 }
1686 }
1687 sqlitepager_unref(pFreeIdx);
1688 }
1689 }
drh3b7511c2001-05-26 13:15:44 +00001690 if( pOvfl==0 ){
1691 assert( pgno>0 );
drh8c42ca92001-06-22 19:15:00 +00001692 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001693 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001694 needUnref = 1;
drh3b7511c2001-05-26 13:15:44 +00001695 }
1696 rc = sqlitepager_write(pOvfl);
1697 if( rc ){
drhdd793422001-06-28 01:54:48 +00001698 if( needUnref ) sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001699 return rc;
1700 }
drh14acc042001-06-10 19:56:58 +00001701 pOvfl->iNext = pPage1->freeList;
drh0d316a42002-08-11 20:10:47 +00001702 pPage1->freeList = SWAB32(pBt, pgno);
drh5e2f8b92001-05-28 00:41:15 +00001703 memset(pOvfl->aPayload, 0, OVERFLOW_SIZE);
drhdd793422001-06-28 01:54:48 +00001704 if( needUnref ) rc = sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001705 return rc;
1706}
1707
1708/*
1709** Erase all the data out of a cell. This involves returning overflow
1710** pages back the freelist.
1711*/
1712static int clearCell(Btree *pBt, Cell *pCell){
1713 Pager *pPager = pBt->pPager;
1714 OverflowPage *pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001715 Pgno ovfl, nextOvfl;
1716 int rc;
1717
drh0d316a42002-08-11 20:10:47 +00001718 if( NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h) <= MX_LOCAL_PAYLOAD ){
drh5e2f8b92001-05-28 00:41:15 +00001719 return SQLITE_OK;
1720 }
drh0d316a42002-08-11 20:10:47 +00001721 ovfl = SWAB32(pBt, pCell->ovfl);
drh3b7511c2001-05-26 13:15:44 +00001722 pCell->ovfl = 0;
1723 while( ovfl ){
drh8c42ca92001-06-22 19:15:00 +00001724 rc = sqlitepager_get(pPager, ovfl, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001725 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001726 nextOvfl = SWAB32(pBt, pOvfl->iNext);
drhbd03cae2001-06-02 02:40:57 +00001727 rc = freePage(pBt, pOvfl, ovfl);
1728 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001729 sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001730 ovfl = nextOvfl;
drh3b7511c2001-05-26 13:15:44 +00001731 }
drh5e2f8b92001-05-28 00:41:15 +00001732 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00001733}
1734
1735/*
1736** Create a new cell from key and data. Overflow pages are allocated as
1737** necessary and linked to this cell.
1738*/
1739static int fillInCell(
1740 Btree *pBt, /* The whole Btree. Needed to allocate pages */
1741 Cell *pCell, /* Populate this Cell structure */
drh5c4d9702001-08-20 00:33:58 +00001742 const void *pKey, int nKey, /* The key */
1743 const void *pData,int nData /* The data */
drh3b7511c2001-05-26 13:15:44 +00001744){
drhdd793422001-06-28 01:54:48 +00001745 OverflowPage *pOvfl, *pPrior;
drh3b7511c2001-05-26 13:15:44 +00001746 Pgno *pNext;
1747 int spaceLeft;
drh8c42ca92001-06-22 19:15:00 +00001748 int n, rc;
drh3b7511c2001-05-26 13:15:44 +00001749 int nPayload;
drh5c4d9702001-08-20 00:33:58 +00001750 const char *pPayload;
drh3b7511c2001-05-26 13:15:44 +00001751 char *pSpace;
drh199e3cf2002-07-18 11:01:47 +00001752 Pgno nearby = 0;
drh3b7511c2001-05-26 13:15:44 +00001753
drh5e2f8b92001-05-28 00:41:15 +00001754 pCell->h.leftChild = 0;
drh0d316a42002-08-11 20:10:47 +00001755 pCell->h.nKey = SWAB16(pBt, nKey & 0xffff);
drh80ff32f2001-11-04 18:32:46 +00001756 pCell->h.nKeyHi = nKey >> 16;
drh0d316a42002-08-11 20:10:47 +00001757 pCell->h.nData = SWAB16(pBt, nData & 0xffff);
drh80ff32f2001-11-04 18:32:46 +00001758 pCell->h.nDataHi = nData >> 16;
drh3b7511c2001-05-26 13:15:44 +00001759 pCell->h.iNext = 0;
1760
1761 pNext = &pCell->ovfl;
drh5e2f8b92001-05-28 00:41:15 +00001762 pSpace = pCell->aPayload;
drh3b7511c2001-05-26 13:15:44 +00001763 spaceLeft = MX_LOCAL_PAYLOAD;
1764 pPayload = pKey;
1765 pKey = 0;
1766 nPayload = nKey;
drhdd793422001-06-28 01:54:48 +00001767 pPrior = 0;
drh3b7511c2001-05-26 13:15:44 +00001768 while( nPayload>0 ){
1769 if( spaceLeft==0 ){
drh199e3cf2002-07-18 11:01:47 +00001770 rc = allocatePage(pBt, (MemPage**)&pOvfl, pNext, nearby);
drh3b7511c2001-05-26 13:15:44 +00001771 if( rc ){
1772 *pNext = 0;
drhbea00b92002-07-08 10:59:50 +00001773 }else{
drh199e3cf2002-07-18 11:01:47 +00001774 nearby = *pNext;
drhdd793422001-06-28 01:54:48 +00001775 }
1776 if( pPrior ) sqlitepager_unref(pPrior);
1777 if( rc ){
drh5e2f8b92001-05-28 00:41:15 +00001778 clearCell(pBt, pCell);
drh3b7511c2001-05-26 13:15:44 +00001779 return rc;
1780 }
drh0d316a42002-08-11 20:10:47 +00001781 if( pBt->needSwab ) *pNext = swab32(*pNext);
drhdd793422001-06-28 01:54:48 +00001782 pPrior = pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001783 spaceLeft = OVERFLOW_SIZE;
drh5e2f8b92001-05-28 00:41:15 +00001784 pSpace = pOvfl->aPayload;
drh8c42ca92001-06-22 19:15:00 +00001785 pNext = &pOvfl->iNext;
drh3b7511c2001-05-26 13:15:44 +00001786 }
1787 n = nPayload;
1788 if( n>spaceLeft ) n = spaceLeft;
1789 memcpy(pSpace, pPayload, n);
1790 nPayload -= n;
1791 if( nPayload==0 && pData ){
1792 pPayload = pData;
1793 nPayload = nData;
1794 pData = 0;
1795 }else{
1796 pPayload += n;
1797 }
1798 spaceLeft -= n;
1799 pSpace += n;
1800 }
drhdd793422001-06-28 01:54:48 +00001801 *pNext = 0;
1802 if( pPrior ){
1803 sqlitepager_unref(pPrior);
1804 }
drh3b7511c2001-05-26 13:15:44 +00001805 return SQLITE_OK;
1806}
1807
1808/*
drhbd03cae2001-06-02 02:40:57 +00001809** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00001810** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00001811** pointer in the third argument.
1812*/
1813static void reparentPage(Pager *pPager, Pgno pgno, MemPage *pNewParent){
1814 MemPage *pThis;
1815
drhdd793422001-06-28 01:54:48 +00001816 if( pgno==0 ) return;
1817 assert( pPager!=0 );
drhbd03cae2001-06-02 02:40:57 +00001818 pThis = sqlitepager_lookup(pPager, pgno);
drh6019e162001-07-02 17:51:45 +00001819 if( pThis && pThis->isInit ){
drhdd793422001-06-28 01:54:48 +00001820 if( pThis->pParent!=pNewParent ){
1821 if( pThis->pParent ) sqlitepager_unref(pThis->pParent);
1822 pThis->pParent = pNewParent;
1823 if( pNewParent ) sqlitepager_ref(pNewParent);
1824 }
1825 sqlitepager_unref(pThis);
drhbd03cae2001-06-02 02:40:57 +00001826 }
1827}
1828
1829/*
1830** Reparent all children of the given page to be the given page.
1831** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00001832** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00001833**
1834** This routine gets called after you memcpy() one page into
1835** another.
1836*/
drh0d316a42002-08-11 20:10:47 +00001837static void reparentChildPages(Btree *pBt, MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00001838 int i;
drh0d316a42002-08-11 20:10:47 +00001839 Pager *pPager = pBt->pPager;
drhbd03cae2001-06-02 02:40:57 +00001840 for(i=0; i<pPage->nCell; i++){
drh0d316a42002-08-11 20:10:47 +00001841 reparentPage(pPager, SWAB32(pBt, pPage->apCell[i]->h.leftChild), pPage);
drhbd03cae2001-06-02 02:40:57 +00001842 }
drh0d316a42002-08-11 20:10:47 +00001843 reparentPage(pPager, SWAB32(pBt, pPage->u.hdr.rightChild), pPage);
drh14acc042001-06-10 19:56:58 +00001844}
1845
1846/*
1847** Remove the i-th cell from pPage. This routine effects pPage only.
1848** The cell content is not freed or deallocated. It is assumed that
1849** the cell content has been copied someplace else. This routine just
1850** removes the reference to the cell from pPage.
1851**
1852** "sz" must be the number of bytes in the cell.
1853**
1854** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001855** Only the pPage->apCell[] array is important. The relinkCellList()
1856** routine will be called soon after this routine in order to rebuild
1857** the linked list.
drh14acc042001-06-10 19:56:58 +00001858*/
drh0d316a42002-08-11 20:10:47 +00001859static void dropCell(Btree *pBt, MemPage *pPage, int idx, int sz){
drh14acc042001-06-10 19:56:58 +00001860 int j;
drh8c42ca92001-06-22 19:15:00 +00001861 assert( idx>=0 && idx<pPage->nCell );
drh0d316a42002-08-11 20:10:47 +00001862 assert( sz==cellSize(pBt, pPage->apCell[idx]) );
drh6019e162001-07-02 17:51:45 +00001863 assert( sqlitepager_iswriteable(pPage) );
drh0d316a42002-08-11 20:10:47 +00001864 freeSpace(pBt, pPage, Addr(pPage->apCell[idx]) - Addr(pPage), sz);
drh7c717f72001-06-24 20:39:41 +00001865 for(j=idx; j<pPage->nCell-1; j++){
drh14acc042001-06-10 19:56:58 +00001866 pPage->apCell[j] = pPage->apCell[j+1];
1867 }
1868 pPage->nCell--;
1869}
1870
1871/*
1872** Insert a new cell on pPage at cell index "i". pCell points to the
1873** content of the cell.
1874**
1875** If the cell content will fit on the page, then put it there. If it
1876** will not fit, then just make pPage->apCell[i] point to the content
1877** and set pPage->isOverfull.
1878**
1879** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001880** Only the pPage->apCell[] array is important. The relinkCellList()
1881** routine will be called soon after this routine in order to rebuild
1882** the linked list.
drh14acc042001-06-10 19:56:58 +00001883*/
drh0d316a42002-08-11 20:10:47 +00001884static void insertCell(Btree *pBt, MemPage *pPage, int i, Cell *pCell, int sz){
drh14acc042001-06-10 19:56:58 +00001885 int idx, j;
1886 assert( i>=0 && i<=pPage->nCell );
drh0d316a42002-08-11 20:10:47 +00001887 assert( sz==cellSize(pBt, pCell) );
drh6019e162001-07-02 17:51:45 +00001888 assert( sqlitepager_iswriteable(pPage) );
drh0d316a42002-08-11 20:10:47 +00001889 idx = allocateSpace(pBt, pPage, sz);
drh14acc042001-06-10 19:56:58 +00001890 for(j=pPage->nCell; j>i; j--){
1891 pPage->apCell[j] = pPage->apCell[j-1];
1892 }
1893 pPage->nCell++;
drh14acc042001-06-10 19:56:58 +00001894 if( idx<=0 ){
1895 pPage->isOverfull = 1;
1896 pPage->apCell[i] = pCell;
1897 }else{
1898 memcpy(&pPage->u.aDisk[idx], pCell, sz);
drh8c42ca92001-06-22 19:15:00 +00001899 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[idx];
drh14acc042001-06-10 19:56:58 +00001900 }
1901}
1902
1903/*
1904** Rebuild the linked list of cells on a page so that the cells
drh8c42ca92001-06-22 19:15:00 +00001905** occur in the order specified by the pPage->apCell[] array.
1906** Invoke this routine once to repair damage after one or more
1907** invocations of either insertCell() or dropCell().
drh14acc042001-06-10 19:56:58 +00001908*/
drh0d316a42002-08-11 20:10:47 +00001909static void relinkCellList(Btree *pBt, MemPage *pPage){
drh14acc042001-06-10 19:56:58 +00001910 int i;
1911 u16 *pIdx;
drh6019e162001-07-02 17:51:45 +00001912 assert( sqlitepager_iswriteable(pPage) );
drh14acc042001-06-10 19:56:58 +00001913 pIdx = &pPage->u.hdr.firstCell;
1914 for(i=0; i<pPage->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00001915 int idx = Addr(pPage->apCell[i]) - Addr(pPage);
drh8c42ca92001-06-22 19:15:00 +00001916 assert( idx>0 && idx<SQLITE_PAGE_SIZE );
drh0d316a42002-08-11 20:10:47 +00001917 *pIdx = SWAB16(pBt, idx);
drh14acc042001-06-10 19:56:58 +00001918 pIdx = &pPage->apCell[i]->h.iNext;
1919 }
1920 *pIdx = 0;
1921}
1922
1923/*
1924** Make a copy of the contents of pFrom into pTo. The pFrom->apCell[]
drh5e00f6c2001-09-13 13:46:56 +00001925** pointers that point into pFrom->u.aDisk[] must be adjusted to point
drhdd793422001-06-28 01:54:48 +00001926** into pTo->u.aDisk[] instead. But some pFrom->apCell[] entries might
drh14acc042001-06-10 19:56:58 +00001927** not point to pFrom->u.aDisk[]. Those are unchanged.
1928*/
1929static void copyPage(MemPage *pTo, MemPage *pFrom){
1930 uptr from, to;
1931 int i;
1932 memcpy(pTo->u.aDisk, pFrom->u.aDisk, SQLITE_PAGE_SIZE);
drhdd793422001-06-28 01:54:48 +00001933 pTo->pParent = 0;
drh14acc042001-06-10 19:56:58 +00001934 pTo->isInit = 1;
1935 pTo->nCell = pFrom->nCell;
1936 pTo->nFree = pFrom->nFree;
1937 pTo->isOverfull = pFrom->isOverfull;
drh7c717f72001-06-24 20:39:41 +00001938 to = Addr(pTo);
1939 from = Addr(pFrom);
drh14acc042001-06-10 19:56:58 +00001940 for(i=0; i<pTo->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00001941 uptr x = Addr(pFrom->apCell[i]);
drh8c42ca92001-06-22 19:15:00 +00001942 if( x>from && x<from+SQLITE_PAGE_SIZE ){
1943 *((uptr*)&pTo->apCell[i]) = x + to - from;
drhdd793422001-06-28 01:54:48 +00001944 }else{
1945 pTo->apCell[i] = pFrom->apCell[i];
drh14acc042001-06-10 19:56:58 +00001946 }
1947 }
drhbd03cae2001-06-02 02:40:57 +00001948}
1949
1950/*
drh8b2f49b2001-06-08 00:21:52 +00001951** This routine redistributes Cells on pPage and up to two siblings
1952** of pPage so that all pages have about the same amount of free space.
drh14acc042001-06-10 19:56:58 +00001953** Usually one sibling on either side of pPage is used in the balancing,
drh8b2f49b2001-06-08 00:21:52 +00001954** though both siblings might come from one side if pPage is the first
1955** or last child of its parent. If pPage has fewer than two siblings
1956** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00001957** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00001958**
1959** The number of siblings of pPage might be increased or decreased by
drh8c42ca92001-06-22 19:15:00 +00001960** one in an effort to keep pages between 66% and 100% full. The root page
1961** is special and is allowed to be less than 66% full. If pPage is
1962** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00001963** or decreased by one, as necessary, to keep the root page from being
1964** overfull or empty.
1965**
drh14acc042001-06-10 19:56:58 +00001966** This routine calls relinkCellList() on its input page regardless of
1967** whether or not it does any real balancing. Client routines will typically
1968** invoke insertCell() or dropCell() before calling this routine, so we
1969** need to call relinkCellList() to clean up the mess that those other
1970** routines left behind.
1971**
1972** pCur is left pointing to the same cell as when this routine was called
drh8c42ca92001-06-22 19:15:00 +00001973** even if that cell gets moved to a different page. pCur may be NULL.
1974** Set the pCur parameter to NULL if you do not care about keeping track
1975** of a cell as that will save this routine the work of keeping track of it.
drh14acc042001-06-10 19:56:58 +00001976**
drh8b2f49b2001-06-08 00:21:52 +00001977** Note that when this routine is called, some of the Cells on pPage
drh14acc042001-06-10 19:56:58 +00001978** might not actually be stored in pPage->u.aDisk[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00001979** if the page is overfull. Part of the job of this routine is to
drh14acc042001-06-10 19:56:58 +00001980** make sure all Cells for pPage once again fit in pPage->u.aDisk[].
1981**
drh8c42ca92001-06-22 19:15:00 +00001982** In the course of balancing the siblings of pPage, the parent of pPage
1983** might become overfull or underfull. If that happens, then this routine
1984** is called recursively on the parent.
1985**
drh5e00f6c2001-09-13 13:46:56 +00001986** If this routine fails for any reason, it might leave the database
1987** in a corrupted state. So if this routine fails, the database should
1988** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00001989*/
drh14acc042001-06-10 19:56:58 +00001990static int balance(Btree *pBt, MemPage *pPage, BtCursor *pCur){
drh8b2f49b2001-06-08 00:21:52 +00001991 MemPage *pParent; /* The parent of pPage */
drh14acc042001-06-10 19:56:58 +00001992 MemPage *apOld[3]; /* pPage and up to two siblings */
drh8b2f49b2001-06-08 00:21:52 +00001993 Pgno pgnoOld[3]; /* Page numbers for each page in apOld[] */
drh14acc042001-06-10 19:56:58 +00001994 MemPage *apNew[4]; /* pPage and up to 3 siblings after balancing */
1995 Pgno pgnoNew[4]; /* Page numbers for each page in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00001996 int idxDiv[3]; /* Indices of divider cells in pParent */
1997 Cell *apDiv[3]; /* Divider cells in pParent */
1998 int nCell; /* Number of cells in apCell[] */
1999 int nOld; /* Number of pages in apOld[] */
2000 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00002001 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00002002 int i, j, k; /* Loop counters */
2003 int idx; /* Index of pPage in pParent->apCell[] */
2004 int nxDiv; /* Next divider slot in pParent->apCell[] */
2005 int rc; /* The return code */
2006 int iCur; /* apCell[iCur] is the cell of the cursor */
drh5edc3122001-09-13 21:53:09 +00002007 MemPage *pOldCurPage; /* The cursor originally points to this page */
drh8c42ca92001-06-22 19:15:00 +00002008 int totalSize; /* Total bytes for all cells */
drh6019e162001-07-02 17:51:45 +00002009 int subtotal; /* Subtotal of bytes in cells on one page */
2010 int cntNew[4]; /* Index in apCell[] of cell after i-th page */
2011 int szNew[4]; /* Combined size of cells place on i-th page */
drh9ca7d3b2001-06-28 11:50:21 +00002012 MemPage *extraUnref = 0; /* A page that needs to be unref-ed */
drh0d316a42002-08-11 20:10:47 +00002013 Pgno pgno, swabPgno; /* Page number */
drh14acc042001-06-10 19:56:58 +00002014 Cell *apCell[MX_CELL*3+5]; /* All cells from pages being balanceed */
2015 int szCell[MX_CELL*3+5]; /* Local size of all cells */
2016 Cell aTemp[2]; /* Temporary holding area for apDiv[] */
2017 MemPage aOld[3]; /* Temporary copies of pPage and its siblings */
drh8b2f49b2001-06-08 00:21:52 +00002018
drh14acc042001-06-10 19:56:58 +00002019 /*
2020 ** Return without doing any work if pPage is neither overfull nor
2021 ** underfull.
drh8b2f49b2001-06-08 00:21:52 +00002022 */
drh6019e162001-07-02 17:51:45 +00002023 assert( sqlitepager_iswriteable(pPage) );
drha1b351a2001-09-14 16:42:12 +00002024 if( !pPage->isOverfull && pPage->nFree<SQLITE_PAGE_SIZE/2
2025 && pPage->nCell>=2){
drh0d316a42002-08-11 20:10:47 +00002026 relinkCellList(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002027 return SQLITE_OK;
2028 }
2029
2030 /*
drh14acc042001-06-10 19:56:58 +00002031 ** Find the parent of the page to be balanceed.
2032 ** If there is no parent, it means this page is the root page and
drh8b2f49b2001-06-08 00:21:52 +00002033 ** special rules apply.
2034 */
drh14acc042001-06-10 19:56:58 +00002035 pParent = pPage->pParent;
drh8b2f49b2001-06-08 00:21:52 +00002036 if( pParent==0 ){
2037 Pgno pgnoChild;
drh8c42ca92001-06-22 19:15:00 +00002038 MemPage *pChild;
drh7aa128d2002-06-21 13:09:16 +00002039 assert( pPage->isInit );
drh8b2f49b2001-06-08 00:21:52 +00002040 if( pPage->nCell==0 ){
drh14acc042001-06-10 19:56:58 +00002041 if( pPage->u.hdr.rightChild ){
2042 /*
2043 ** The root page is empty. Copy the one child page
drh8b2f49b2001-06-08 00:21:52 +00002044 ** into the root page and return. This reduces the depth
2045 ** of the BTree by one.
2046 */
drh0d316a42002-08-11 20:10:47 +00002047 pgnoChild = SWAB32(pBt, pPage->u.hdr.rightChild);
drh8c42ca92001-06-22 19:15:00 +00002048 rc = sqlitepager_get(pBt->pPager, pgnoChild, (void**)&pChild);
drh8b2f49b2001-06-08 00:21:52 +00002049 if( rc ) return rc;
2050 memcpy(pPage, pChild, SQLITE_PAGE_SIZE);
2051 pPage->isInit = 0;
drh0d316a42002-08-11 20:10:47 +00002052 rc = initPage(pBt, pPage, sqlitepager_pagenumber(pPage), 0);
drh6019e162001-07-02 17:51:45 +00002053 assert( rc==SQLITE_OK );
drh0d316a42002-08-11 20:10:47 +00002054 reparentChildPages(pBt, pPage);
drh5edc3122001-09-13 21:53:09 +00002055 if( pCur && pCur->pPage==pChild ){
2056 sqlitepager_unref(pChild);
2057 pCur->pPage = pPage;
2058 sqlitepager_ref(pPage);
2059 }
drh8b2f49b2001-06-08 00:21:52 +00002060 freePage(pBt, pChild, pgnoChild);
2061 sqlitepager_unref(pChild);
drhefc251d2001-07-01 22:12:01 +00002062 }else{
drh0d316a42002-08-11 20:10:47 +00002063 relinkCellList(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002064 }
2065 return SQLITE_OK;
2066 }
drh14acc042001-06-10 19:56:58 +00002067 if( !pPage->isOverfull ){
drh8b2f49b2001-06-08 00:21:52 +00002068 /* It is OK for the root page to be less than half full.
2069 */
drh0d316a42002-08-11 20:10:47 +00002070 relinkCellList(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002071 return SQLITE_OK;
2072 }
drh14acc042001-06-10 19:56:58 +00002073 /*
2074 ** If we get to here, it means the root page is overfull.
drh8b2f49b2001-06-08 00:21:52 +00002075 ** When this happens, Create a new child page and copy the
2076 ** contents of the root into the child. Then make the root
drh14acc042001-06-10 19:56:58 +00002077 ** page an empty page with rightChild pointing to the new
drh8b2f49b2001-06-08 00:21:52 +00002078 ** child. Then fall thru to the code below which will cause
2079 ** the overfull child page to be split.
2080 */
drh14acc042001-06-10 19:56:58 +00002081 rc = sqlitepager_write(pPage);
2082 if( rc ) return rc;
drhbea00b92002-07-08 10:59:50 +00002083 rc = allocatePage(pBt, &pChild, &pgnoChild, sqlitepager_pagenumber(pPage));
drh8b2f49b2001-06-08 00:21:52 +00002084 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002085 assert( sqlitepager_iswriteable(pChild) );
drh14acc042001-06-10 19:56:58 +00002086 copyPage(pChild, pPage);
2087 pChild->pParent = pPage;
drhdd793422001-06-28 01:54:48 +00002088 sqlitepager_ref(pPage);
drh14acc042001-06-10 19:56:58 +00002089 pChild->isOverfull = 1;
drh5edc3122001-09-13 21:53:09 +00002090 if( pCur && pCur->pPage==pPage ){
2091 sqlitepager_unref(pPage);
drh14acc042001-06-10 19:56:58 +00002092 pCur->pPage = pChild;
drh9ca7d3b2001-06-28 11:50:21 +00002093 }else{
2094 extraUnref = pChild;
drh8b2f49b2001-06-08 00:21:52 +00002095 }
drh0d316a42002-08-11 20:10:47 +00002096 zeroPage(pBt, pPage);
2097 pPage->u.hdr.rightChild = SWAB32(pBt, pgnoChild);
drh8b2f49b2001-06-08 00:21:52 +00002098 pParent = pPage;
2099 pPage = pChild;
drh8b2f49b2001-06-08 00:21:52 +00002100 }
drh6019e162001-07-02 17:51:45 +00002101 rc = sqlitepager_write(pParent);
2102 if( rc ) return rc;
drh7aa128d2002-06-21 13:09:16 +00002103 assert( pParent->isInit );
drh14acc042001-06-10 19:56:58 +00002104
drh8b2f49b2001-06-08 00:21:52 +00002105 /*
drh14acc042001-06-10 19:56:58 +00002106 ** Find the Cell in the parent page whose h.leftChild points back
2107 ** to pPage. The "idx" variable is the index of that cell. If pPage
2108 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00002109 */
2110 idx = -1;
2111 pgno = sqlitepager_pagenumber(pPage);
drh0d316a42002-08-11 20:10:47 +00002112 swabPgno = SWAB32(pBt, pgno);
drh8b2f49b2001-06-08 00:21:52 +00002113 for(i=0; i<pParent->nCell; i++){
drh0d316a42002-08-11 20:10:47 +00002114 if( pParent->apCell[i]->h.leftChild==swabPgno ){
drh8b2f49b2001-06-08 00:21:52 +00002115 idx = i;
2116 break;
2117 }
2118 }
drh0d316a42002-08-11 20:10:47 +00002119 if( idx<0 && pParent->u.hdr.rightChild==swabPgno ){
drhdd793422001-06-28 01:54:48 +00002120 idx = pParent->nCell;
drh8b2f49b2001-06-08 00:21:52 +00002121 }
2122 if( idx<0 ){
drh14acc042001-06-10 19:56:58 +00002123 return SQLITE_CORRUPT;
drh8b2f49b2001-06-08 00:21:52 +00002124 }
2125
2126 /*
drh14acc042001-06-10 19:56:58 +00002127 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00002128 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00002129 */
drh14acc042001-06-10 19:56:58 +00002130 nOld = nNew = 0;
2131 sqlitepager_ref(pParent);
2132
2133 /*
2134 ** Find sibling pages to pPage and the Cells in pParent that divide
2135 ** the siblings. An attempt is made to find one sibling on either
2136 ** side of pPage. Both siblings are taken from one side, however, if
2137 ** pPage is either the first or last child of its parent. If pParent
2138 ** has 3 or fewer children then all children of pParent are taken.
2139 */
2140 if( idx==pParent->nCell ){
2141 nxDiv = idx - 2;
drh8b2f49b2001-06-08 00:21:52 +00002142 }else{
drh14acc042001-06-10 19:56:58 +00002143 nxDiv = idx - 1;
drh8b2f49b2001-06-08 00:21:52 +00002144 }
drh14acc042001-06-10 19:56:58 +00002145 if( nxDiv<0 ) nxDiv = 0;
drh8b2f49b2001-06-08 00:21:52 +00002146 nDiv = 0;
drh14acc042001-06-10 19:56:58 +00002147 for(i=0, k=nxDiv; i<3; i++, k++){
2148 if( k<pParent->nCell ){
2149 idxDiv[i] = k;
2150 apDiv[i] = pParent->apCell[k];
drh8b2f49b2001-06-08 00:21:52 +00002151 nDiv++;
drh0d316a42002-08-11 20:10:47 +00002152 pgnoOld[i] = SWAB32(pBt, apDiv[i]->h.leftChild);
drh14acc042001-06-10 19:56:58 +00002153 }else if( k==pParent->nCell ){
drh0d316a42002-08-11 20:10:47 +00002154 pgnoOld[i] = SWAB32(pBt, pParent->u.hdr.rightChild);
drh14acc042001-06-10 19:56:58 +00002155 }else{
2156 break;
drh8b2f49b2001-06-08 00:21:52 +00002157 }
drh8c42ca92001-06-22 19:15:00 +00002158 rc = sqlitepager_get(pBt->pPager, pgnoOld[i], (void**)&apOld[i]);
drh14acc042001-06-10 19:56:58 +00002159 if( rc ) goto balance_cleanup;
drh0d316a42002-08-11 20:10:47 +00002160 rc = initPage(pBt, apOld[i], pgnoOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00002161 if( rc ) goto balance_cleanup;
drh14acc042001-06-10 19:56:58 +00002162 nOld++;
drh8b2f49b2001-06-08 00:21:52 +00002163 }
2164
2165 /*
drh14acc042001-06-10 19:56:58 +00002166 ** Set iCur to be the index in apCell[] of the cell that the cursor
2167 ** is pointing to. We will need this later on in order to keep the
drh5edc3122001-09-13 21:53:09 +00002168 ** cursor pointing at the same cell. If pCur points to a page that
2169 ** has no involvement with this rebalancing, then set iCur to a large
2170 ** number so that the iCur==j tests always fail in the main cell
2171 ** distribution loop below.
drh14acc042001-06-10 19:56:58 +00002172 */
2173 if( pCur ){
drh5edc3122001-09-13 21:53:09 +00002174 iCur = 0;
2175 for(i=0; i<nOld; i++){
2176 if( pCur->pPage==apOld[i] ){
2177 iCur += pCur->idx;
2178 break;
2179 }
2180 iCur += apOld[i]->nCell;
2181 if( i<nOld-1 && pCur->pPage==pParent && pCur->idx==idxDiv[i] ){
2182 break;
2183 }
2184 iCur++;
drh14acc042001-06-10 19:56:58 +00002185 }
drh5edc3122001-09-13 21:53:09 +00002186 pOldCurPage = pCur->pPage;
drh14acc042001-06-10 19:56:58 +00002187 }
2188
2189 /*
2190 ** Make copies of the content of pPage and its siblings into aOld[].
2191 ** The rest of this function will use data from the copies rather
2192 ** that the original pages since the original pages will be in the
2193 ** process of being overwritten.
2194 */
2195 for(i=0; i<nOld; i++){
2196 copyPage(&aOld[i], apOld[i]);
drh14acc042001-06-10 19:56:58 +00002197 }
2198
2199 /*
2200 ** Load pointers to all cells on sibling pages and the divider cells
2201 ** into the local apCell[] array. Make copies of the divider cells
2202 ** into aTemp[] and remove the the divider Cells from pParent.
drh8b2f49b2001-06-08 00:21:52 +00002203 */
2204 nCell = 0;
2205 for(i=0; i<nOld; i++){
drh6b308672002-07-08 02:16:37 +00002206 MemPage *pOld = &aOld[i];
drh8b2f49b2001-06-08 00:21:52 +00002207 for(j=0; j<pOld->nCell; j++){
drh14acc042001-06-10 19:56:58 +00002208 apCell[nCell] = pOld->apCell[j];
drh0d316a42002-08-11 20:10:47 +00002209 szCell[nCell] = cellSize(pBt, apCell[nCell]);
drh14acc042001-06-10 19:56:58 +00002210 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00002211 }
2212 if( i<nOld-1 ){
drh0d316a42002-08-11 20:10:47 +00002213 szCell[nCell] = cellSize(pBt, apDiv[i]);
drh8c42ca92001-06-22 19:15:00 +00002214 memcpy(&aTemp[i], apDiv[i], szCell[nCell]);
drh14acc042001-06-10 19:56:58 +00002215 apCell[nCell] = &aTemp[i];
drh0d316a42002-08-11 20:10:47 +00002216 dropCell(pBt, pParent, nxDiv, szCell[nCell]);
2217 assert( SWAB32(pBt, apCell[nCell]->h.leftChild)==pgnoOld[i] );
drh14acc042001-06-10 19:56:58 +00002218 apCell[nCell]->h.leftChild = pOld->u.hdr.rightChild;
2219 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00002220 }
2221 }
2222
2223 /*
drh6019e162001-07-02 17:51:45 +00002224 ** Figure out the number of pages needed to hold all nCell cells.
2225 ** Store this number in "k". Also compute szNew[] which is the total
2226 ** size of all cells on the i-th page and cntNew[] which is the index
2227 ** in apCell[] of the cell that divides path i from path i+1.
2228 ** cntNew[k] should equal nCell.
2229 **
2230 ** This little patch of code is critical for keeping the tree
2231 ** balanced.
drh8b2f49b2001-06-08 00:21:52 +00002232 */
2233 totalSize = 0;
2234 for(i=0; i<nCell; i++){
drh14acc042001-06-10 19:56:58 +00002235 totalSize += szCell[i];
drh8b2f49b2001-06-08 00:21:52 +00002236 }
drh6019e162001-07-02 17:51:45 +00002237 for(subtotal=k=i=0; i<nCell; i++){
2238 subtotal += szCell[i];
2239 if( subtotal > USABLE_SPACE ){
2240 szNew[k] = subtotal - szCell[i];
2241 cntNew[k] = i;
2242 subtotal = 0;
2243 k++;
2244 }
2245 }
2246 szNew[k] = subtotal;
2247 cntNew[k] = nCell;
2248 k++;
2249 for(i=k-1; i>0; i--){
2250 while( szNew[i]<USABLE_SPACE/2 ){
2251 cntNew[i-1]--;
2252 assert( cntNew[i-1]>0 );
2253 szNew[i] += szCell[cntNew[i-1]];
2254 szNew[i-1] -= szCell[cntNew[i-1]-1];
2255 }
2256 }
2257 assert( cntNew[0]>0 );
drh8b2f49b2001-06-08 00:21:52 +00002258
2259 /*
drh6b308672002-07-08 02:16:37 +00002260 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00002261 */
drh14acc042001-06-10 19:56:58 +00002262 for(i=0; i<k; i++){
drh6b308672002-07-08 02:16:37 +00002263 if( i<nOld ){
2264 apNew[i] = apOld[i];
2265 pgnoNew[i] = pgnoOld[i];
2266 apOld[i] = 0;
2267 sqlitepager_write(apNew[i]);
2268 }else{
drhbea00b92002-07-08 10:59:50 +00002269 rc = allocatePage(pBt, &apNew[i], &pgnoNew[i], pgnoNew[i-1]);
drh6b308672002-07-08 02:16:37 +00002270 if( rc ) goto balance_cleanup;
2271 }
drh14acc042001-06-10 19:56:58 +00002272 nNew++;
drh0d316a42002-08-11 20:10:47 +00002273 zeroPage(pBt, apNew[i]);
drh6019e162001-07-02 17:51:45 +00002274 apNew[i]->isInit = 1;
drh8b2f49b2001-06-08 00:21:52 +00002275 }
2276
drh6b308672002-07-08 02:16:37 +00002277 /* Free any old pages that were not reused as new pages.
2278 */
2279 while( i<nOld ){
2280 rc = freePage(pBt, apOld[i], pgnoOld[i]);
2281 if( rc ) goto balance_cleanup;
2282 sqlitepager_unref(apOld[i]);
2283 apOld[i] = 0;
2284 i++;
2285 }
2286
drh8b2f49b2001-06-08 00:21:52 +00002287 /*
drhf9ffac92002-03-02 19:00:31 +00002288 ** Put the new pages in accending order. This helps to
2289 ** keep entries in the disk file in order so that a scan
2290 ** of the table is a linear scan through the file. That
2291 ** in turn helps the operating system to deliver pages
2292 ** from the disk more rapidly.
2293 **
2294 ** An O(n^2) insertion sort algorithm is used, but since
2295 ** n is never more than 3, that should not be a problem.
2296 **
2297 ** This one optimization makes the database about 25%
2298 ** faster for large insertions and deletions.
2299 */
2300 for(i=0; i<k-1; i++){
2301 int minV = pgnoNew[i];
2302 int minI = i;
2303 for(j=i+1; j<k; j++){
2304 if( pgnoNew[j]<minV ){
2305 minI = j;
2306 minV = pgnoNew[j];
2307 }
2308 }
2309 if( minI>i ){
2310 int t;
2311 MemPage *pT;
2312 t = pgnoNew[i];
2313 pT = apNew[i];
2314 pgnoNew[i] = pgnoNew[minI];
2315 apNew[i] = apNew[minI];
2316 pgnoNew[minI] = t;
2317 apNew[minI] = pT;
2318 }
2319 }
2320
2321 /*
drh14acc042001-06-10 19:56:58 +00002322 ** Evenly distribute the data in apCell[] across the new pages.
2323 ** Insert divider cells into pParent as necessary.
2324 */
2325 j = 0;
2326 for(i=0; i<nNew; i++){
2327 MemPage *pNew = apNew[i];
drh6019e162001-07-02 17:51:45 +00002328 while( j<cntNew[i] ){
2329 assert( pNew->nFree>=szCell[j] );
drh14acc042001-06-10 19:56:58 +00002330 if( pCur && iCur==j ){ pCur->pPage = pNew; pCur->idx = pNew->nCell; }
drh0d316a42002-08-11 20:10:47 +00002331 insertCell(pBt, pNew, pNew->nCell, apCell[j], szCell[j]);
drh14acc042001-06-10 19:56:58 +00002332 j++;
2333 }
drh6019e162001-07-02 17:51:45 +00002334 assert( pNew->nCell>0 );
drh14acc042001-06-10 19:56:58 +00002335 assert( !pNew->isOverfull );
drh0d316a42002-08-11 20:10:47 +00002336 relinkCellList(pBt, pNew);
drh14acc042001-06-10 19:56:58 +00002337 if( i<nNew-1 && j<nCell ){
2338 pNew->u.hdr.rightChild = apCell[j]->h.leftChild;
drh0d316a42002-08-11 20:10:47 +00002339 apCell[j]->h.leftChild = SWAB32(pBt, pgnoNew[i]);
drh14acc042001-06-10 19:56:58 +00002340 if( pCur && iCur==j ){ pCur->pPage = pParent; pCur->idx = nxDiv; }
drh0d316a42002-08-11 20:10:47 +00002341 insertCell(pBt, pParent, nxDiv, apCell[j], szCell[j]);
drh14acc042001-06-10 19:56:58 +00002342 j++;
2343 nxDiv++;
2344 }
2345 }
drh6019e162001-07-02 17:51:45 +00002346 assert( j==nCell );
drh6b308672002-07-08 02:16:37 +00002347 apNew[nNew-1]->u.hdr.rightChild = aOld[nOld-1].u.hdr.rightChild;
drh14acc042001-06-10 19:56:58 +00002348 if( nxDiv==pParent->nCell ){
drh0d316a42002-08-11 20:10:47 +00002349 pParent->u.hdr.rightChild = SWAB32(pBt, pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00002350 }else{
drh0d316a42002-08-11 20:10:47 +00002351 pParent->apCell[nxDiv]->h.leftChild = SWAB32(pBt, pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00002352 }
2353 if( pCur ){
drh3fc190c2001-09-14 03:24:23 +00002354 if( j<=iCur && pCur->pPage==pParent && pCur->idx>idxDiv[nOld-1] ){
2355 assert( pCur->pPage==pOldCurPage );
2356 pCur->idx += nNew - nOld;
2357 }else{
2358 assert( pOldCurPage!=0 );
2359 sqlitepager_ref(pCur->pPage);
2360 sqlitepager_unref(pOldCurPage);
2361 }
drh14acc042001-06-10 19:56:58 +00002362 }
2363
2364 /*
2365 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00002366 */
2367 for(i=0; i<nNew; i++){
drh0d316a42002-08-11 20:10:47 +00002368 reparentChildPages(pBt, apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002369 }
drh0d316a42002-08-11 20:10:47 +00002370 reparentChildPages(pBt, pParent);
drh8b2f49b2001-06-08 00:21:52 +00002371
2372 /*
drh14acc042001-06-10 19:56:58 +00002373 ** balance the parent page.
drh8b2f49b2001-06-08 00:21:52 +00002374 */
drh5edc3122001-09-13 21:53:09 +00002375 rc = balance(pBt, pParent, pCur);
drh8b2f49b2001-06-08 00:21:52 +00002376
2377 /*
drh14acc042001-06-10 19:56:58 +00002378 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00002379 */
drh14acc042001-06-10 19:56:58 +00002380balance_cleanup:
drh9ca7d3b2001-06-28 11:50:21 +00002381 if( extraUnref ){
2382 sqlitepager_unref(extraUnref);
2383 }
drh8b2f49b2001-06-08 00:21:52 +00002384 for(i=0; i<nOld; i++){
drh6b308672002-07-08 02:16:37 +00002385 if( apOld[i]!=0 && apOld[i]!=&aOld[i] ) sqlitepager_unref(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00002386 }
drh14acc042001-06-10 19:56:58 +00002387 for(i=0; i<nNew; i++){
2388 sqlitepager_unref(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002389 }
drh14acc042001-06-10 19:56:58 +00002390 if( pCur && pCur->pPage==0 ){
2391 pCur->pPage = pParent;
2392 pCur->idx = 0;
2393 }else{
2394 sqlitepager_unref(pParent);
drh8b2f49b2001-06-08 00:21:52 +00002395 }
2396 return rc;
2397}
2398
2399/*
drh3b7511c2001-05-26 13:15:44 +00002400** Insert a new record into the BTree. The key is given by (pKey,nKey)
2401** and the data is given by (pData,nData). The cursor is used only to
2402** define what database the record should be inserted into. The cursor
drh14acc042001-06-10 19:56:58 +00002403** is left pointing at the new record.
drh3b7511c2001-05-26 13:15:44 +00002404*/
2405int sqliteBtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00002406 BtCursor *pCur, /* Insert data into the table of this cursor */
drhbe0072d2001-09-13 14:46:09 +00002407 const void *pKey, int nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00002408 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00002409){
2410 Cell newCell;
2411 int rc;
2412 int loc;
drh14acc042001-06-10 19:56:58 +00002413 int szNew;
drh3b7511c2001-05-26 13:15:44 +00002414 MemPage *pPage;
2415 Btree *pBt = pCur->pBt;
2416
drhecdc7532001-09-23 02:35:53 +00002417 if( pCur->pPage==0 ){
2418 return SQLITE_ABORT; /* A rollback destroyed this cursor */
2419 }
drh5edc3122001-09-13 21:53:09 +00002420 if( !pCur->pBt->inTrans || nKey+nData==0 ){
drh8b2f49b2001-06-08 00:21:52 +00002421 return SQLITE_ERROR; /* Must start a transaction first */
2422 }
drhecdc7532001-09-23 02:35:53 +00002423 if( !pCur->wrFlag ){
2424 return SQLITE_PERM; /* Cursor not open for writing */
2425 }
drh14acc042001-06-10 19:56:58 +00002426 rc = sqliteBtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00002427 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002428 pPage = pCur->pPage;
drh7aa128d2002-06-21 13:09:16 +00002429 assert( pPage->isInit );
drh14acc042001-06-10 19:56:58 +00002430 rc = sqlitepager_write(pPage);
drhbd03cae2001-06-02 02:40:57 +00002431 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00002432 rc = fillInCell(pBt, &newCell, pKey, nKey, pData, nData);
2433 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002434 szNew = cellSize(pBt, &newCell);
drh3b7511c2001-05-26 13:15:44 +00002435 if( loc==0 ){
drh14acc042001-06-10 19:56:58 +00002436 newCell.h.leftChild = pPage->apCell[pCur->idx]->h.leftChild;
2437 rc = clearCell(pBt, pPage->apCell[pCur->idx]);
drh5e2f8b92001-05-28 00:41:15 +00002438 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002439 dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pPage->apCell[pCur->idx]));
drh7c717f72001-06-24 20:39:41 +00002440 }else if( loc<0 && pPage->nCell>0 ){
drh14acc042001-06-10 19:56:58 +00002441 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
2442 pCur->idx++;
2443 }else{
2444 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
drh3b7511c2001-05-26 13:15:44 +00002445 }
drh0d316a42002-08-11 20:10:47 +00002446 insertCell(pBt, pPage, pCur->idx, &newCell, szNew);
drh14acc042001-06-10 19:56:58 +00002447 rc = balance(pCur->pBt, pPage, pCur);
drh3fc190c2001-09-14 03:24:23 +00002448 /* sqliteBtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
2449 /* fflush(stdout); */
drh5e2f8b92001-05-28 00:41:15 +00002450 return rc;
2451}
2452
2453/*
drhbd03cae2001-06-02 02:40:57 +00002454** Delete the entry that the cursor is pointing to.
drh5e2f8b92001-05-28 00:41:15 +00002455**
drhbd03cae2001-06-02 02:40:57 +00002456** The cursor is left pointing at either the next or the previous
2457** entry. If the cursor is left pointing to the next entry, then
2458** the pCur->bSkipNext flag is set which forces the next call to
2459** sqliteBtreeNext() to be a no-op. That way, you can always call
2460** sqliteBtreeNext() after a delete and the cursor will be left
2461** pointing to the first entry after the deleted entry.
drh3b7511c2001-05-26 13:15:44 +00002462*/
2463int sqliteBtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00002464 MemPage *pPage = pCur->pPage;
2465 Cell *pCell;
2466 int rc;
drh8c42ca92001-06-22 19:15:00 +00002467 Pgno pgnoChild;
drh0d316a42002-08-11 20:10:47 +00002468 Btree *pBt = pCur->pBt;
drh8b2f49b2001-06-08 00:21:52 +00002469
drh7aa128d2002-06-21 13:09:16 +00002470 assert( pPage->isInit );
drhecdc7532001-09-23 02:35:53 +00002471 if( pCur->pPage==0 ){
2472 return SQLITE_ABORT; /* A rollback destroyed this cursor */
2473 }
drh8b2f49b2001-06-08 00:21:52 +00002474 if( !pCur->pBt->inTrans ){
2475 return SQLITE_ERROR; /* Must start a transaction first */
2476 }
drhbd03cae2001-06-02 02:40:57 +00002477 if( pCur->idx >= pPage->nCell ){
2478 return SQLITE_ERROR; /* The cursor is not pointing to anything */
2479 }
drhecdc7532001-09-23 02:35:53 +00002480 if( !pCur->wrFlag ){
2481 return SQLITE_PERM; /* Did not open this cursor for writing */
2482 }
drhbd03cae2001-06-02 02:40:57 +00002483 rc = sqlitepager_write(pPage);
2484 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002485 pCell = pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00002486 pgnoChild = SWAB32(pBt, pCell->h.leftChild);
2487 clearCell(pBt, pCell);
drh14acc042001-06-10 19:56:58 +00002488 if( pgnoChild ){
2489 /*
drh5e00f6c2001-09-13 13:46:56 +00002490 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00002491 ** do something we will leave a hole on an internal page.
2492 ** We have to fill the hole by moving in a cell from a leaf. The
2493 ** next Cell after the one to be deleted is guaranteed to exist and
2494 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00002495 */
drh14acc042001-06-10 19:56:58 +00002496 BtCursor leafCur;
2497 Cell *pNext;
2498 int szNext;
2499 getTempCursor(pCur, &leafCur);
2500 rc = sqliteBtreeNext(&leafCur, 0);
2501 if( rc!=SQLITE_OK ){
2502 return SQLITE_CORRUPT;
drh5e2f8b92001-05-28 00:41:15 +00002503 }
drh6019e162001-07-02 17:51:45 +00002504 rc = sqlitepager_write(leafCur.pPage);
2505 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002506 dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pCell));
drh8c42ca92001-06-22 19:15:00 +00002507 pNext = leafCur.pPage->apCell[leafCur.idx];
drh0d316a42002-08-11 20:10:47 +00002508 szNext = cellSize(pBt, pNext);
2509 pNext->h.leftChild = SWAB32(pBt, pgnoChild);
2510 insertCell(pBt, pPage, pCur->idx, pNext, szNext);
2511 rc = balance(pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002512 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002513 pCur->bSkipNext = 1;
drh0d316a42002-08-11 20:10:47 +00002514 dropCell(pBt, leafCur.pPage, leafCur.idx, szNext);
2515 rc = balance(pBt, leafCur.pPage, pCur);
drh8c42ca92001-06-22 19:15:00 +00002516 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00002517 }else{
drh0d316a42002-08-11 20:10:47 +00002518 dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pCell));
drh5edc3122001-09-13 21:53:09 +00002519 if( pCur->idx>=pPage->nCell ){
2520 pCur->idx = pPage->nCell-1;
drhf5bf0a72001-11-23 00:24:12 +00002521 if( pCur->idx<0 ){
2522 pCur->idx = 0;
2523 pCur->bSkipNext = 1;
2524 }else{
2525 pCur->bSkipNext = 0;
2526 }
drh6019e162001-07-02 17:51:45 +00002527 }else{
2528 pCur->bSkipNext = 1;
2529 }
drh0d316a42002-08-11 20:10:47 +00002530 rc = balance(pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002531 }
drh5e2f8b92001-05-28 00:41:15 +00002532 return rc;
drh3b7511c2001-05-26 13:15:44 +00002533}
drh8b2f49b2001-06-08 00:21:52 +00002534
2535/*
drhc6b52df2002-01-04 03:09:29 +00002536** Create a new BTree table. Write into *piTable the page
2537** number for the root page of the new table.
2538**
2539** In the current implementation, BTree tables and BTree indices are the
2540** the same. But in the future, we may change this so that BTree tables
2541** are restricted to having a 4-byte integer key and arbitrary data and
2542** BTree indices are restricted to having an arbitrary key and no data.
drh8b2f49b2001-06-08 00:21:52 +00002543*/
2544int sqliteBtreeCreateTable(Btree *pBt, int *piTable){
2545 MemPage *pRoot;
2546 Pgno pgnoRoot;
2547 int rc;
2548 if( !pBt->inTrans ){
2549 return SQLITE_ERROR; /* Must start a transaction first */
2550 }
drh5df72a52002-06-06 23:16:05 +00002551 if( pBt->readOnly ){
2552 return SQLITE_READONLY;
2553 }
drhbea00b92002-07-08 10:59:50 +00002554 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 0);
drh8b2f49b2001-06-08 00:21:52 +00002555 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002556 assert( sqlitepager_iswriteable(pRoot) );
drh0d316a42002-08-11 20:10:47 +00002557 zeroPage(pBt, pRoot);
drh8b2f49b2001-06-08 00:21:52 +00002558 sqlitepager_unref(pRoot);
2559 *piTable = (int)pgnoRoot;
2560 return SQLITE_OK;
2561}
2562
2563/*
drhc6b52df2002-01-04 03:09:29 +00002564** Create a new BTree index. Write into *piTable the page
2565** number for the root page of the new index.
2566**
2567** In the current implementation, BTree tables and BTree indices are the
2568** the same. But in the future, we may change this so that BTree tables
2569** are restricted to having a 4-byte integer key and arbitrary data and
2570** BTree indices are restricted to having an arbitrary key and no data.
2571*/
2572int sqliteBtreeCreateIndex(Btree *pBt, int *piIndex){
drh5df72a52002-06-06 23:16:05 +00002573 return sqliteBtreeCreateTable(pBt, piIndex);
drhc6b52df2002-01-04 03:09:29 +00002574}
2575
2576/*
drh8b2f49b2001-06-08 00:21:52 +00002577** Erase the given database page and all its children. Return
2578** the page to the freelist.
2579*/
drh2aa679f2001-06-25 02:11:07 +00002580static int clearDatabasePage(Btree *pBt, Pgno pgno, int freePageFlag){
drh8b2f49b2001-06-08 00:21:52 +00002581 MemPage *pPage;
2582 int rc;
drh8b2f49b2001-06-08 00:21:52 +00002583 Cell *pCell;
2584 int idx;
2585
drh8c42ca92001-06-22 19:15:00 +00002586 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pPage);
drh8b2f49b2001-06-08 00:21:52 +00002587 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002588 rc = sqlitepager_write(pPage);
2589 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002590 rc = initPage(pBt, pPage, pgno, 0);
drh7aa128d2002-06-21 13:09:16 +00002591 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002592 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh8b2f49b2001-06-08 00:21:52 +00002593 while( idx>0 ){
drh14acc042001-06-10 19:56:58 +00002594 pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +00002595 idx = SWAB16(pBt, pCell->h.iNext);
drh8b2f49b2001-06-08 00:21:52 +00002596 if( pCell->h.leftChild ){
drh0d316a42002-08-11 20:10:47 +00002597 rc = clearDatabasePage(pBt, SWAB32(pBt, pCell->h.leftChild), 1);
drh8b2f49b2001-06-08 00:21:52 +00002598 if( rc ) return rc;
2599 }
drh8c42ca92001-06-22 19:15:00 +00002600 rc = clearCell(pBt, pCell);
drh8b2f49b2001-06-08 00:21:52 +00002601 if( rc ) return rc;
2602 }
drh2aa679f2001-06-25 02:11:07 +00002603 if( pPage->u.hdr.rightChild ){
drh0d316a42002-08-11 20:10:47 +00002604 rc = clearDatabasePage(pBt, SWAB32(pBt, pPage->u.hdr.rightChild), 1);
drh2aa679f2001-06-25 02:11:07 +00002605 if( rc ) return rc;
2606 }
2607 if( freePageFlag ){
2608 rc = freePage(pBt, pPage, pgno);
2609 }else{
drh0d316a42002-08-11 20:10:47 +00002610 zeroPage(pBt, pPage);
drh2aa679f2001-06-25 02:11:07 +00002611 }
drhdd793422001-06-28 01:54:48 +00002612 sqlitepager_unref(pPage);
drh2aa679f2001-06-25 02:11:07 +00002613 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002614}
2615
2616/*
2617** Delete all information from a single table in the database.
2618*/
2619int sqliteBtreeClearTable(Btree *pBt, int iTable){
2620 int rc;
drh5a2c2c22001-11-21 02:21:11 +00002621 ptr nLock;
drh8b2f49b2001-06-08 00:21:52 +00002622 if( !pBt->inTrans ){
2623 return SQLITE_ERROR; /* Must start a transaction first */
2624 }
drh5df72a52002-06-06 23:16:05 +00002625 if( pBt->readOnly ){
2626 return SQLITE_READONLY;
2627 }
drh5a2c2c22001-11-21 02:21:11 +00002628 nLock = (ptr)sqliteHashFind(&pBt->locks, 0, iTable);
drhecdc7532001-09-23 02:35:53 +00002629 if( nLock ){
2630 return SQLITE_LOCKED;
2631 }
drh2aa679f2001-06-25 02:11:07 +00002632 rc = clearDatabasePage(pBt, (Pgno)iTable, 0);
drh8b2f49b2001-06-08 00:21:52 +00002633 if( rc ){
2634 sqliteBtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00002635 }
drh8c42ca92001-06-22 19:15:00 +00002636 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002637}
2638
2639/*
2640** Erase all information in a table and add the root of the table to
2641** the freelist. Except, the root of the principle table (the one on
2642** page 2) is never added to the freelist.
2643*/
2644int sqliteBtreeDropTable(Btree *pBt, int iTable){
2645 int rc;
2646 MemPage *pPage;
2647 if( !pBt->inTrans ){
2648 return SQLITE_ERROR; /* Must start a transaction first */
2649 }
drh5df72a52002-06-06 23:16:05 +00002650 if( pBt->readOnly ){
2651 return SQLITE_READONLY;
2652 }
drh8c42ca92001-06-22 19:15:00 +00002653 rc = sqlitepager_get(pBt->pPager, (Pgno)iTable, (void**)&pPage);
drh2aa679f2001-06-25 02:11:07 +00002654 if( rc ) return rc;
2655 rc = sqliteBtreeClearTable(pBt, iTable);
2656 if( rc ) return rc;
2657 if( iTable>2 ){
2658 rc = freePage(pBt, pPage, iTable);
2659 }else{
drh0d316a42002-08-11 20:10:47 +00002660 zeroPage(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002661 }
drhdd793422001-06-28 01:54:48 +00002662 sqlitepager_unref(pPage);
drh8b2f49b2001-06-08 00:21:52 +00002663 return rc;
2664}
2665
2666/*
2667** Read the meta-information out of a database file.
2668*/
2669int sqliteBtreeGetMeta(Btree *pBt, int *aMeta){
2670 PageOne *pP1;
2671 int rc;
drh0d316a42002-08-11 20:10:47 +00002672 int i;
drh8b2f49b2001-06-08 00:21:52 +00002673
drh8c42ca92001-06-22 19:15:00 +00002674 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00002675 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002676 aMeta[0] = SWAB32(pBt, pP1->nFree);
2677 for(i=0; i<sizeof(pP1->aMeta)/sizeof(pP1->aMeta[0]); i++){
2678 aMeta[i+1] = SWAB32(pBt, pP1->aMeta[i]);
2679 }
drh8b2f49b2001-06-08 00:21:52 +00002680 sqlitepager_unref(pP1);
2681 return SQLITE_OK;
2682}
2683
2684/*
2685** Write meta-information back into the database.
2686*/
2687int sqliteBtreeUpdateMeta(Btree *pBt, int *aMeta){
2688 PageOne *pP1;
drh0d316a42002-08-11 20:10:47 +00002689 int rc, i;
drh8b2f49b2001-06-08 00:21:52 +00002690 if( !pBt->inTrans ){
2691 return SQLITE_ERROR; /* Must start a transaction first */
2692 }
drh5df72a52002-06-06 23:16:05 +00002693 if( pBt->readOnly ){
2694 return SQLITE_READONLY;
2695 }
drh8b2f49b2001-06-08 00:21:52 +00002696 pP1 = pBt->page1;
2697 rc = sqlitepager_write(pP1);
drh9adf9ac2002-05-15 11:44:13 +00002698 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002699 for(i=0; i<sizeof(pP1->aMeta)/sizeof(pP1->aMeta[0]); i++){
2700 pP1->aMeta[i] = SWAB32(pBt, aMeta[i+1]);
2701 }
drh8b2f49b2001-06-08 00:21:52 +00002702 return SQLITE_OK;
2703}
drh8c42ca92001-06-22 19:15:00 +00002704
drh5eddca62001-06-30 21:53:53 +00002705/******************************************************************************
2706** The complete implementation of the BTree subsystem is above this line.
2707** All the code the follows is for testing and troubleshooting the BTree
2708** subsystem. None of the code that follows is used during normal operation.
drh5eddca62001-06-30 21:53:53 +00002709******************************************************************************/
drh5eddca62001-06-30 21:53:53 +00002710
drh8c42ca92001-06-22 19:15:00 +00002711/*
2712** Print a disassembly of the given page on standard output. This routine
2713** is used for debugging and testing only.
2714*/
drhaaab5722002-02-19 13:39:21 +00002715#ifdef SQLITE_TEST
drh6019e162001-07-02 17:51:45 +00002716int sqliteBtreePageDump(Btree *pBt, int pgno, int recursive){
drh8c42ca92001-06-22 19:15:00 +00002717 int rc;
2718 MemPage *pPage;
2719 int i, j;
2720 int nFree;
2721 u16 idx;
2722 char range[20];
2723 unsigned char payload[20];
2724 rc = sqlitepager_get(pBt->pPager, (Pgno)pgno, (void**)&pPage);
2725 if( rc ){
2726 return rc;
2727 }
drh6019e162001-07-02 17:51:45 +00002728 if( recursive ) printf("PAGE %d:\n", pgno);
drh8c42ca92001-06-22 19:15:00 +00002729 i = 0;
drh0d316a42002-08-11 20:10:47 +00002730 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh8c42ca92001-06-22 19:15:00 +00002731 while( idx>0 && idx<=SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2732 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +00002733 int sz = cellSize(pBt, pCell);
drh8c42ca92001-06-22 19:15:00 +00002734 sprintf(range,"%d..%d", idx, idx+sz-1);
drh0d316a42002-08-11 20:10:47 +00002735 sz = NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h);
drh8c42ca92001-06-22 19:15:00 +00002736 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
2737 memcpy(payload, pCell->aPayload, sz);
2738 for(j=0; j<sz; j++){
2739 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
2740 }
2741 payload[sz] = 0;
2742 printf(
drh6019e162001-07-02 17:51:45 +00002743 "cell %2d: i=%-10s chld=%-4d nk=%-4d nd=%-4d payload=%s\n",
drh0d316a42002-08-11 20:10:47 +00002744 i, range, (int)pCell->h.leftChild,
2745 NKEY(pBt, pCell->h), NDATA(pBt, pCell->h),
drh2aa679f2001-06-25 02:11:07 +00002746 payload
drh8c42ca92001-06-22 19:15:00 +00002747 );
drh6019e162001-07-02 17:51:45 +00002748 if( pPage->isInit && pPage->apCell[i]!=pCell ){
drh2aa679f2001-06-25 02:11:07 +00002749 printf("**** apCell[%d] does not match on prior entry ****\n", i);
2750 }
drh7c717f72001-06-24 20:39:41 +00002751 i++;
drh0d316a42002-08-11 20:10:47 +00002752 idx = SWAB16(pBt, pCell->h.iNext);
drh8c42ca92001-06-22 19:15:00 +00002753 }
2754 if( idx!=0 ){
2755 printf("ERROR: next cell index out of range: %d\n", idx);
2756 }
drh0d316a42002-08-11 20:10:47 +00002757 printf("right_child: %d\n", SWAB32(pBt, pPage->u.hdr.rightChild));
drh8c42ca92001-06-22 19:15:00 +00002758 nFree = 0;
2759 i = 0;
drh0d316a42002-08-11 20:10:47 +00002760 idx = SWAB16(pBt, pPage->u.hdr.firstFree);
drh8c42ca92001-06-22 19:15:00 +00002761 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2762 FreeBlk *p = (FreeBlk*)&pPage->u.aDisk[idx];
2763 sprintf(range,"%d..%d", idx, idx+p->iSize-1);
drh0d316a42002-08-11 20:10:47 +00002764 nFree += SWAB16(pBt, p->iSize);
drh8c42ca92001-06-22 19:15:00 +00002765 printf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
drh0d316a42002-08-11 20:10:47 +00002766 i, range, SWAB16(pBt, p->iSize), nFree);
2767 idx = SWAB16(pBt, p->iNext);
drh2aa679f2001-06-25 02:11:07 +00002768 i++;
drh8c42ca92001-06-22 19:15:00 +00002769 }
2770 if( idx!=0 ){
2771 printf("ERROR: next freeblock index out of range: %d\n", idx);
2772 }
drh6019e162001-07-02 17:51:45 +00002773 if( recursive && pPage->u.hdr.rightChild!=0 ){
drh0d316a42002-08-11 20:10:47 +00002774 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh6019e162001-07-02 17:51:45 +00002775 while( idx>0 && idx<SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2776 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +00002777 sqliteBtreePageDump(pBt, SWAB32(pBt, pCell->h.leftChild), 1);
2778 idx = SWAB16(pBt, pCell->h.iNext);
drh6019e162001-07-02 17:51:45 +00002779 }
drh0d316a42002-08-11 20:10:47 +00002780 sqliteBtreePageDump(pBt, SWAB32(pBt, pPage->u.hdr.rightChild), 1);
drh6019e162001-07-02 17:51:45 +00002781 }
drh8c42ca92001-06-22 19:15:00 +00002782 sqlitepager_unref(pPage);
2783 return SQLITE_OK;
2784}
drhaaab5722002-02-19 13:39:21 +00002785#endif
drh8c42ca92001-06-22 19:15:00 +00002786
drhaaab5722002-02-19 13:39:21 +00002787#ifdef SQLITE_TEST
drh8c42ca92001-06-22 19:15:00 +00002788/*
drh2aa679f2001-06-25 02:11:07 +00002789** Fill aResult[] with information about the entry and page that the
2790** cursor is pointing to.
2791**
2792** aResult[0] = The page number
2793** aResult[1] = The entry number
2794** aResult[2] = Total number of entries on this page
2795** aResult[3] = Size of this entry
2796** aResult[4] = Number of free bytes on this page
2797** aResult[5] = Number of free blocks on the page
2798** aResult[6] = Page number of the left child of this entry
2799** aResult[7] = Page number of the right child for the whole page
drh5eddca62001-06-30 21:53:53 +00002800**
2801** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00002802*/
2803int sqliteBtreeCursorDump(BtCursor *pCur, int *aResult){
drh2aa679f2001-06-25 02:11:07 +00002804 int cnt, idx;
2805 MemPage *pPage = pCur->pPage;
drh0d316a42002-08-11 20:10:47 +00002806 Btree *pBt = pCur->pBt;
drh2aa679f2001-06-25 02:11:07 +00002807 aResult[0] = sqlitepager_pagenumber(pPage);
drh8c42ca92001-06-22 19:15:00 +00002808 aResult[1] = pCur->idx;
drh2aa679f2001-06-25 02:11:07 +00002809 aResult[2] = pPage->nCell;
2810 if( pCur->idx>=0 && pCur->idx<pPage->nCell ){
drh0d316a42002-08-11 20:10:47 +00002811 aResult[3] = cellSize(pBt, pPage->apCell[pCur->idx]);
2812 aResult[6] = SWAB32(pBt, pPage->apCell[pCur->idx]->h.leftChild);
drh2aa679f2001-06-25 02:11:07 +00002813 }else{
2814 aResult[3] = 0;
2815 aResult[6] = 0;
2816 }
2817 aResult[4] = pPage->nFree;
2818 cnt = 0;
drh0d316a42002-08-11 20:10:47 +00002819 idx = SWAB16(pBt, pPage->u.hdr.firstFree);
drh2aa679f2001-06-25 02:11:07 +00002820 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2821 cnt++;
drh0d316a42002-08-11 20:10:47 +00002822 idx = SWAB16(pBt, ((FreeBlk*)&pPage->u.aDisk[idx])->iNext);
drh2aa679f2001-06-25 02:11:07 +00002823 }
2824 aResult[5] = cnt;
drh0d316a42002-08-11 20:10:47 +00002825 aResult[7] = SWAB32(pBt, pPage->u.hdr.rightChild);
drh8c42ca92001-06-22 19:15:00 +00002826 return SQLITE_OK;
2827}
drhaaab5722002-02-19 13:39:21 +00002828#endif
drhdd793422001-06-28 01:54:48 +00002829
drhaaab5722002-02-19 13:39:21 +00002830#ifdef SQLITE_TEST
drhdd793422001-06-28 01:54:48 +00002831/*
drh5eddca62001-06-30 21:53:53 +00002832** Return the pager associated with a BTree. This routine is used for
2833** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00002834*/
2835Pager *sqliteBtreePager(Btree *pBt){
2836 return pBt->pPager;
2837}
drhaaab5722002-02-19 13:39:21 +00002838#endif
drh5eddca62001-06-30 21:53:53 +00002839
2840/*
2841** This structure is passed around through all the sanity checking routines
2842** in order to keep track of some global state information.
2843*/
drhaaab5722002-02-19 13:39:21 +00002844typedef struct IntegrityCk IntegrityCk;
2845struct IntegrityCk {
drh100569d2001-10-02 13:01:48 +00002846 Btree *pBt; /* The tree being checked out */
2847 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
2848 int nPage; /* Number of pages in the database */
2849 int *anRef; /* Number of times each page is referenced */
2850 int nTreePage; /* Number of BTree pages */
2851 int nByte; /* Number of bytes of data stored on BTree pages */
2852 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00002853};
2854
2855/*
2856** Append a message to the error message string.
2857*/
drhaaab5722002-02-19 13:39:21 +00002858static void checkAppendMsg(IntegrityCk *pCheck, char *zMsg1, char *zMsg2){
drh5eddca62001-06-30 21:53:53 +00002859 if( pCheck->zErrMsg ){
2860 char *zOld = pCheck->zErrMsg;
2861 pCheck->zErrMsg = 0;
2862 sqliteSetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, 0);
2863 sqliteFree(zOld);
2864 }else{
2865 sqliteSetString(&pCheck->zErrMsg, zMsg1, zMsg2, 0);
2866 }
2867}
2868
2869/*
2870** Add 1 to the reference count for page iPage. If this is the second
2871** reference to the page, add an error message to pCheck->zErrMsg.
2872** Return 1 if there are 2 ore more references to the page and 0 if
2873** if this is the first reference to the page.
2874**
2875** Also check that the page number is in bounds.
2876*/
drhaaab5722002-02-19 13:39:21 +00002877static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00002878 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00002879 if( iPage>pCheck->nPage || iPage<0 ){
drh5eddca62001-06-30 21:53:53 +00002880 char zBuf[100];
2881 sprintf(zBuf, "invalid page number %d", iPage);
2882 checkAppendMsg(pCheck, zContext, zBuf);
2883 return 1;
2884 }
2885 if( pCheck->anRef[iPage]==1 ){
2886 char zBuf[100];
2887 sprintf(zBuf, "2nd reference to page %d", iPage);
2888 checkAppendMsg(pCheck, zContext, zBuf);
2889 return 1;
2890 }
2891 return (pCheck->anRef[iPage]++)>1;
2892}
2893
2894/*
2895** Check the integrity of the freelist or of an overflow page list.
2896** Verify that the number of pages on the list is N.
2897*/
drh30e58752002-03-02 20:41:57 +00002898static void checkList(
2899 IntegrityCk *pCheck, /* Integrity checking context */
2900 int isFreeList, /* True for a freelist. False for overflow page list */
2901 int iPage, /* Page number for first page in the list */
2902 int N, /* Expected number of pages in the list */
2903 char *zContext /* Context for error messages */
2904){
2905 int i;
drh5eddca62001-06-30 21:53:53 +00002906 char zMsg[100];
drh30e58752002-03-02 20:41:57 +00002907 while( N-- > 0 ){
drh5eddca62001-06-30 21:53:53 +00002908 OverflowPage *pOvfl;
2909 if( iPage<1 ){
2910 sprintf(zMsg, "%d pages missing from overflow list", N+1);
2911 checkAppendMsg(pCheck, zContext, zMsg);
2912 break;
2913 }
2914 if( checkRef(pCheck, iPage, zContext) ) break;
2915 if( sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
2916 sprintf(zMsg, "failed to get page %d", iPage);
2917 checkAppendMsg(pCheck, zContext, zMsg);
2918 break;
2919 }
drh30e58752002-03-02 20:41:57 +00002920 if( isFreeList ){
2921 FreelistInfo *pInfo = (FreelistInfo*)pOvfl->aPayload;
drh0d316a42002-08-11 20:10:47 +00002922 int n = SWAB32(pCheck->pBt, pInfo->nFree);
2923 for(i=0; i<n; i++){
2924 checkRef(pCheck, SWAB32(pCheck->pBt, pInfo->aFree[i]), zMsg);
drh30e58752002-03-02 20:41:57 +00002925 }
drh0d316a42002-08-11 20:10:47 +00002926 N -= n;
drh30e58752002-03-02 20:41:57 +00002927 }
drh0d316a42002-08-11 20:10:47 +00002928 iPage = SWAB32(pCheck->pBt, pOvfl->iNext);
drh5eddca62001-06-30 21:53:53 +00002929 sqlitepager_unref(pOvfl);
2930 }
2931}
2932
2933/*
drh1bffb9c2002-02-03 17:37:36 +00002934** Return negative if zKey1<zKey2.
2935** Return zero if zKey1==zKey2.
2936** Return positive if zKey1>zKey2.
2937*/
2938static int keyCompare(
2939 const char *zKey1, int nKey1,
2940 const char *zKey2, int nKey2
2941){
2942 int min = nKey1>nKey2 ? nKey2 : nKey1;
2943 int c = memcmp(zKey1, zKey2, min);
2944 if( c==0 ){
2945 c = nKey1 - nKey2;
2946 }
2947 return c;
2948}
2949
2950/*
drh5eddca62001-06-30 21:53:53 +00002951** Do various sanity checks on a single page of a tree. Return
2952** the tree depth. Root pages return 0. Parents of root pages
2953** return 1, and so forth.
2954**
2955** These checks are done:
2956**
2957** 1. Make sure that cells and freeblocks do not overlap
2958** but combine to completely cover the page.
2959** 2. Make sure cell keys are in order.
2960** 3. Make sure no key is less than or equal to zLowerBound.
2961** 4. Make sure no key is greater than or equal to zUpperBound.
2962** 5. Check the integrity of overflow pages.
2963** 6. Recursively call checkTreePage on all children.
2964** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00002965** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00002966** the root of the tree.
2967*/
2968static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00002969 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00002970 int iPage, /* Page number of the page to check */
2971 MemPage *pParent, /* Parent page */
2972 char *zParentContext, /* Parent context */
2973 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00002974 int nLower, /* Number of characters in zLowerBound */
2975 char *zUpperBound, /* All keys should be less than this, if not NULL */
2976 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00002977){
2978 MemPage *pPage;
2979 int i, rc, depth, d2, pgno;
2980 char *zKey1, *zKey2;
drh1bffb9c2002-02-03 17:37:36 +00002981 int nKey1, nKey2;
drh5eddca62001-06-30 21:53:53 +00002982 BtCursor cur;
drh0d316a42002-08-11 20:10:47 +00002983 Btree *pBt;
drh5eddca62001-06-30 21:53:53 +00002984 char zMsg[100];
2985 char zContext[100];
2986 char hit[SQLITE_PAGE_SIZE];
2987
2988 /* Check that the page exists
2989 */
drh0d316a42002-08-11 20:10:47 +00002990 cur.pBt = pBt = pCheck->pBt;
drh5eddca62001-06-30 21:53:53 +00002991 if( iPage==0 ) return 0;
2992 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
2993 sprintf(zContext, "On tree page %d: ", iPage);
2994 if( (rc = sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pPage))!=0 ){
2995 sprintf(zMsg, "unable to get the page. error code=%d", rc);
2996 checkAppendMsg(pCheck, zContext, zMsg);
2997 return 0;
2998 }
drh0d316a42002-08-11 20:10:47 +00002999 if( (rc = initPage(pBt, pPage, (Pgno)iPage, pParent))!=0 ){
drh5eddca62001-06-30 21:53:53 +00003000 sprintf(zMsg, "initPage() returns error code %d", rc);
3001 checkAppendMsg(pCheck, zContext, zMsg);
3002 sqlitepager_unref(pPage);
3003 return 0;
3004 }
3005
3006 /* Check out all the cells.
3007 */
3008 depth = 0;
drh1bffb9c2002-02-03 17:37:36 +00003009 if( zLowerBound ){
3010 zKey1 = sqliteMalloc( nLower+1 );
3011 memcpy(zKey1, zLowerBound, nLower);
3012 zKey1[nLower] = 0;
3013 }else{
3014 zKey1 = 0;
3015 }
3016 nKey1 = nLower;
drh5eddca62001-06-30 21:53:53 +00003017 cur.pPage = pPage;
drh5eddca62001-06-30 21:53:53 +00003018 for(i=0; i<pPage->nCell; i++){
3019 Cell *pCell = pPage->apCell[i];
3020 int sz;
3021
3022 /* Check payload overflow pages
3023 */
drh0d316a42002-08-11 20:10:47 +00003024 nKey2 = NKEY(pBt, pCell->h);
3025 sz = nKey2 + NDATA(pBt, pCell->h);
drh5eddca62001-06-30 21:53:53 +00003026 sprintf(zContext, "On page %d cell %d: ", iPage, i);
3027 if( sz>MX_LOCAL_PAYLOAD ){
3028 int nPage = (sz - MX_LOCAL_PAYLOAD + OVERFLOW_SIZE - 1)/OVERFLOW_SIZE;
drh0d316a42002-08-11 20:10:47 +00003029 checkList(pCheck, 0, SWAB32(pBt, pCell->ovfl), nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00003030 }
3031
3032 /* Check that keys are in the right order
3033 */
3034 cur.idx = i;
drh1bffb9c2002-02-03 17:37:36 +00003035 zKey2 = sqliteMalloc( nKey2+1 );
3036 getPayload(&cur, 0, nKey2, zKey2);
3037 if( zKey1 && keyCompare(zKey1, nKey1, zKey2, nKey2)>=0 ){
drh5eddca62001-06-30 21:53:53 +00003038 checkAppendMsg(pCheck, zContext, "Key is out of order");
3039 }
3040
3041 /* Check sanity of left child page.
3042 */
drh0d316a42002-08-11 20:10:47 +00003043 pgno = SWAB32(pBt, pCell->h.leftChild);
drh1bffb9c2002-02-03 17:37:36 +00003044 d2 = checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zKey2,nKey2);
drh5eddca62001-06-30 21:53:53 +00003045 if( i>0 && d2!=depth ){
3046 checkAppendMsg(pCheck, zContext, "Child page depth differs");
3047 }
3048 depth = d2;
3049 sqliteFree(zKey1);
3050 zKey1 = zKey2;
drh1bffb9c2002-02-03 17:37:36 +00003051 nKey1 = nKey2;
drh5eddca62001-06-30 21:53:53 +00003052 }
drh0d316a42002-08-11 20:10:47 +00003053 pgno = SWAB32(pBt, pPage->u.hdr.rightChild);
drh5eddca62001-06-30 21:53:53 +00003054 sprintf(zContext, "On page %d at right child: ", iPage);
drh1bffb9c2002-02-03 17:37:36 +00003055 checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zUpperBound,nUpper);
drh5eddca62001-06-30 21:53:53 +00003056 sqliteFree(zKey1);
3057
3058 /* Check for complete coverage of the page
3059 */
3060 memset(hit, 0, sizeof(hit));
3061 memset(hit, 1, sizeof(PageHdr));
drh0d316a42002-08-11 20:10:47 +00003062 for(i=SWAB16(pBt, pPage->u.hdr.firstCell); i>0 && i<SQLITE_PAGE_SIZE; ){
drh5eddca62001-06-30 21:53:53 +00003063 Cell *pCell = (Cell*)&pPage->u.aDisk[i];
3064 int j;
drh0d316a42002-08-11 20:10:47 +00003065 for(j=i+cellSize(pBt, pCell)-1; j>=i; j--) hit[j]++;
3066 i = SWAB16(pBt, pCell->h.iNext);
drh5eddca62001-06-30 21:53:53 +00003067 }
drh0d316a42002-08-11 20:10:47 +00003068 for(i=SWAB16(pBt,pPage->u.hdr.firstFree); i>0 && i<SQLITE_PAGE_SIZE; ){
drh5eddca62001-06-30 21:53:53 +00003069 FreeBlk *pFBlk = (FreeBlk*)&pPage->u.aDisk[i];
3070 int j;
drh0d316a42002-08-11 20:10:47 +00003071 for(j=i+SWAB16(pBt,pFBlk->iSize)-1; j>=i; j--) hit[j]++;
3072 i = SWAB16(pBt,pFBlk->iNext);
drh5eddca62001-06-30 21:53:53 +00003073 }
3074 for(i=0; i<SQLITE_PAGE_SIZE; i++){
3075 if( hit[i]==0 ){
3076 sprintf(zMsg, "Unused space at byte %d of page %d", i, iPage);
3077 checkAppendMsg(pCheck, zMsg, 0);
3078 break;
3079 }else if( hit[i]>1 ){
3080 sprintf(zMsg, "Multiple uses for byte %d of page %d", i, iPage);
3081 checkAppendMsg(pCheck, zMsg, 0);
3082 break;
3083 }
3084 }
3085
3086 /* Check that free space is kept to a minimum
3087 */
drh6019e162001-07-02 17:51:45 +00003088#if 0
3089 if( pParent && pParent->nCell>2 && pPage->nFree>3*SQLITE_PAGE_SIZE/4 ){
drh5eddca62001-06-30 21:53:53 +00003090 sprintf(zMsg, "free space (%d) greater than max (%d)", pPage->nFree,
3091 SQLITE_PAGE_SIZE/3);
3092 checkAppendMsg(pCheck, zContext, zMsg);
3093 }
drh6019e162001-07-02 17:51:45 +00003094#endif
3095
3096 /* Update freespace totals.
3097 */
3098 pCheck->nTreePage++;
3099 pCheck->nByte += USABLE_SPACE - pPage->nFree;
drh5eddca62001-06-30 21:53:53 +00003100
3101 sqlitepager_unref(pPage);
3102 return depth;
3103}
3104
3105/*
3106** This routine does a complete check of the given BTree file. aRoot[] is
3107** an array of pages numbers were each page number is the root page of
3108** a table. nRoot is the number of entries in aRoot.
3109**
3110** If everything checks out, this routine returns NULL. If something is
3111** amiss, an error message is written into memory obtained from malloc()
3112** and a pointer to that error message is returned. The calling function
3113** is responsible for freeing the error message when it is done.
3114*/
drhaaab5722002-02-19 13:39:21 +00003115char *sqliteBtreeIntegrityCheck(Btree *pBt, int *aRoot, int nRoot){
drh5eddca62001-06-30 21:53:53 +00003116 int i;
3117 int nRef;
drhaaab5722002-02-19 13:39:21 +00003118 IntegrityCk sCheck;
drh5eddca62001-06-30 21:53:53 +00003119
3120 nRef = *sqlitepager_stats(pBt->pPager);
drhefc251d2001-07-01 22:12:01 +00003121 if( lockBtree(pBt)!=SQLITE_OK ){
3122 return sqliteStrDup("Unable to acquire a read lock on the database");
3123 }
drh5eddca62001-06-30 21:53:53 +00003124 sCheck.pBt = pBt;
3125 sCheck.pPager = pBt->pPager;
3126 sCheck.nPage = sqlitepager_pagecount(sCheck.pPager);
drh0de8c112002-07-06 16:32:14 +00003127 if( sCheck.nPage==0 ){
3128 unlockBtreeIfUnused(pBt);
3129 return 0;
3130 }
drh5eddca62001-06-30 21:53:53 +00003131 sCheck.anRef = sqliteMalloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
3132 sCheck.anRef[1] = 1;
3133 for(i=2; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
3134 sCheck.zErrMsg = 0;
3135
3136 /* Check the integrity of the freelist
3137 */
drh0d316a42002-08-11 20:10:47 +00003138 checkList(&sCheck, 1, SWAB32(pBt, pBt->page1->freeList),
3139 SWAB32(pBt, pBt->page1->nFree), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00003140
3141 /* Check all the tables.
3142 */
3143 for(i=0; i<nRoot; i++){
drh4ff6dfa2002-03-03 23:06:00 +00003144 if( aRoot[i]==0 ) continue;
drh1bffb9c2002-02-03 17:37:36 +00003145 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00003146 }
3147
3148 /* Make sure every page in the file is referenced
3149 */
3150 for(i=1; i<=sCheck.nPage; i++){
3151 if( sCheck.anRef[i]==0 ){
3152 char zBuf[100];
3153 sprintf(zBuf, "Page %d is never used", i);
3154 checkAppendMsg(&sCheck, zBuf, 0);
3155 }
3156 }
3157
3158 /* Make sure this analysis did not leave any unref() pages
3159 */
drh5e00f6c2001-09-13 13:46:56 +00003160 unlockBtreeIfUnused(pBt);
drh5eddca62001-06-30 21:53:53 +00003161 if( nRef != *sqlitepager_stats(pBt->pPager) ){
3162 char zBuf[100];
3163 sprintf(zBuf,
3164 "Outstanding page count goes from %d to %d during this analysis",
3165 nRef, *sqlitepager_stats(pBt->pPager)
3166 );
3167 checkAppendMsg(&sCheck, zBuf, 0);
3168 }
3169
3170 /* Clean up and report errors.
3171 */
3172 sqliteFree(sCheck.anRef);
3173 return sCheck.zErrMsg;
3174}