blob: a52878cbe52199ab1570bc5ec6f9a11010bd4991 [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*************************************************************************
drh74587e52002-08-13 00:01:16 +000012** $Id: btree.c,v 1.70 2002/08/13 00:01:17 drh Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
15** For a detailed discussion of BTrees, refer to
16**
17** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
18** "Sorting And Searching", pages 473-480. Addison-Wesley
19** Publishing Company, Reading, Massachusetts.
20**
21** The basic idea is that each page of the file contains N database
22** entries and N+1 pointers to subpages.
23**
24** ----------------------------------------------------------------
25** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N) | Ptr(N+1) |
26** ----------------------------------------------------------------
27**
28** All of the keys on the page that Ptr(0) points to have values less
29** than Key(0). All of the keys on page Ptr(1) and its subpages have
30** values greater than Key(0) and less than Key(1). All of the keys
31** on Ptr(N+1) and its subpages have values greater than Key(N). And
32** so forth.
33**
drh5e00f6c2001-09-13 13:46:56 +000034** Finding a particular key requires reading O(log(M)) pages from the
35** disk where M is the number of entries in the tree.
drh8b2f49b2001-06-08 00:21:52 +000036**
37** In this implementation, a single file can hold one or more separate
38** BTrees. Each BTree is identified by the index of its root page. The
39** key and data for any entry are combined to form the "payload". Up to
40** MX_LOCAL_PAYLOAD bytes of payload can be carried directly on the
41** database page. If the payload is larger than MX_LOCAL_PAYLOAD bytes
42** then surplus bytes are stored on overflow pages. The payload for an
43** entry and the preceding pointer are combined to form a "Cell". Each
drhb19a2bc2001-09-16 00:13:26 +000044** page has a small header which contains the Ptr(N+1) pointer.
drh8b2f49b2001-06-08 00:21:52 +000045**
46** The first page of the file contains a magic string used to verify that
47** the file really is a valid BTree database, a pointer to a list of unused
48** pages in the file, and some meta information. The root of the first
49** BTree begins on page 2 of the file. (Pages are numbered beginning with
50** 1, not 0.) Thus a minimum database contains 2 pages.
drha059ad02001-04-17 20:09:11 +000051*/
52#include "sqliteInt.h"
53#include "pager.h"
54#include "btree.h"
55#include <assert.h>
56
drh8c42ca92001-06-22 19:15:00 +000057/*
drh0d316a42002-08-11 20:10:47 +000058** Macros used for byteswapping. B is a pointer to the Btree
59** structure. This is needed to access the Btree.needSwab boolean
60** in order to tell if byte swapping is needed or not.
61** X is an unsigned integer. SWAB16 byte swaps a 16-bit integer.
62** SWAB32 byteswaps a 32-bit integer.
63*/
64#define SWAB16(B,X) ((B)->needSwab? swab16(X) : (X))
65#define SWAB32(B,X) ((B)->needSwab? swab32(X) : (X))
66#define SWAB_ADD(B,X,A) \
67 if((B)->needSwab){ X=swab32(swab32(X)+A); }else{ X += (A); }
68
69/*
70** The following global variable - available only if SQLITE_TEST is
71** defined - is used to determine whether new databases are created in
72** native byte order or in non-native byte order. Non-native byte order
73** databases are created for testing purposes only. Under normal operation,
74** only native byte-order databases should be created, but we should be
75** able to read or write existing databases regardless of the byteorder.
76*/
77#ifdef SQLITE_TEST
78int btree_native_byte_order = 1;
drh74587e52002-08-13 00:01:16 +000079#else
80# define btree_native_byte_order 1
drh0d316a42002-08-11 20:10:47 +000081#endif
82
83/*
drh365d68f2001-05-11 11:02:46 +000084** Forward declarations of structures used only in this file.
85*/
drhbd03cae2001-06-02 02:40:57 +000086typedef struct PageOne PageOne;
drh2af926b2001-05-15 00:39:25 +000087typedef struct MemPage MemPage;
drh365d68f2001-05-11 11:02:46 +000088typedef struct PageHdr PageHdr;
89typedef struct Cell Cell;
drh3b7511c2001-05-26 13:15:44 +000090typedef struct CellHdr CellHdr;
drh365d68f2001-05-11 11:02:46 +000091typedef struct FreeBlk FreeBlk;
drh2af926b2001-05-15 00:39:25 +000092typedef struct OverflowPage OverflowPage;
drh30e58752002-03-02 20:41:57 +000093typedef struct FreelistInfo FreelistInfo;
drh2af926b2001-05-15 00:39:25 +000094
95/*
96** All structures on a database page are aligned to 4-byte boundries.
97** This routine rounds up a number of bytes to the next multiple of 4.
drh306dc212001-05-21 13:45:10 +000098**
99** This might need to change for computer architectures that require
100** and 8-byte alignment boundry for structures.
drh2af926b2001-05-15 00:39:25 +0000101*/
102#define ROUNDUP(X) ((X+3) & ~3)
drha059ad02001-04-17 20:09:11 +0000103
drh08ed44e2001-04-29 23:32:55 +0000104/*
drhbd03cae2001-06-02 02:40:57 +0000105** This is a magic string that appears at the beginning of every
drh8c42ca92001-06-22 19:15:00 +0000106** SQLite database in order to identify the file as a real database.
drh08ed44e2001-04-29 23:32:55 +0000107*/
drhbd03cae2001-06-02 02:40:57 +0000108static const char zMagicHeader[] =
drh80ff32f2001-11-04 18:32:46 +0000109 "** This file contains an SQLite 2.1 database **";
drhbd03cae2001-06-02 02:40:57 +0000110#define MAGIC_SIZE (sizeof(zMagicHeader))
drh08ed44e2001-04-29 23:32:55 +0000111
112/*
drh5e00f6c2001-09-13 13:46:56 +0000113** This is a magic integer also used to test the integrity of the database
drh8c42ca92001-06-22 19:15:00 +0000114** file. This integer is used in addition to the string above so that
115** if the file is written on a little-endian architecture and read
116** on a big-endian architectures (or vice versa) we can detect the
117** problem.
118**
119** The number used was obtained at random and has no special
drhb19a2bc2001-09-16 00:13:26 +0000120** significance other than the fact that it represents a different
121** integer on little-endian and big-endian machines.
drh8c42ca92001-06-22 19:15:00 +0000122*/
123#define MAGIC 0xdae37528
124
125/*
drhbd03cae2001-06-02 02:40:57 +0000126** The first page of the database file contains a magic header string
127** to identify the file as an SQLite database file. It also contains
128** a pointer to the first free page of the file. Page 2 contains the
drh8b2f49b2001-06-08 00:21:52 +0000129** root of the principle BTree. The file might contain other BTrees
130** rooted on pages above 2.
131**
132** The first page also contains SQLITE_N_BTREE_META integers that
133** can be used by higher-level routines.
drh08ed44e2001-04-29 23:32:55 +0000134**
drhbd03cae2001-06-02 02:40:57 +0000135** Remember that pages are numbered beginning with 1. (See pager.c
136** for additional information.) Page 0 does not exist and a page
137** number of 0 is used to mean "no such page".
138*/
139struct PageOne {
140 char zMagic[MAGIC_SIZE]; /* String that identifies the file as a database */
drh8c42ca92001-06-22 19:15:00 +0000141 int iMagic; /* Integer to verify correct byte order */
142 Pgno freeList; /* First free page in a list of all free pages */
drh2aa679f2001-06-25 02:11:07 +0000143 int nFree; /* Number of pages on the free list */
144 int aMeta[SQLITE_N_BTREE_META-1]; /* User defined integers */
drhbd03cae2001-06-02 02:40:57 +0000145};
146
147/*
148** Each database page has a header that is an instance of this
149** structure.
drh08ed44e2001-04-29 23:32:55 +0000150**
drh8b2f49b2001-06-08 00:21:52 +0000151** PageHdr.firstFree is 0 if there is no free space on this page.
drh14acc042001-06-10 19:56:58 +0000152** Otherwise, PageHdr.firstFree is the index in MemPage.u.aDisk[] of a
drh8b2f49b2001-06-08 00:21:52 +0000153** FreeBlk structure that describes the first block of free space.
154** All free space is defined by a linked list of FreeBlk structures.
drh08ed44e2001-04-29 23:32:55 +0000155**
drh8b2f49b2001-06-08 00:21:52 +0000156** Data is stored in a linked list of Cell structures. PageHdr.firstCell
drh14acc042001-06-10 19:56:58 +0000157** is the index into MemPage.u.aDisk[] of the first cell on the page. The
drh306dc212001-05-21 13:45:10 +0000158** Cells are kept in sorted order.
drh8b2f49b2001-06-08 00:21:52 +0000159**
160** A Cell contains all information about a database entry and a pointer
161** to a child page that contains other entries less than itself. In
162** other words, the i-th Cell contains both Ptr(i) and Key(i). The
163** right-most pointer of the page is contained in PageHdr.rightChild.
drh08ed44e2001-04-29 23:32:55 +0000164*/
drh365d68f2001-05-11 11:02:46 +0000165struct PageHdr {
drh5e2f8b92001-05-28 00:41:15 +0000166 Pgno rightChild; /* Child page that comes after all cells on this page */
drh14acc042001-06-10 19:56:58 +0000167 u16 firstCell; /* Index in MemPage.u.aDisk[] of the first cell */
168 u16 firstFree; /* Index in MemPage.u.aDisk[] of the first free block */
drh365d68f2001-05-11 11:02:46 +0000169};
drh306dc212001-05-21 13:45:10 +0000170
drh3b7511c2001-05-26 13:15:44 +0000171/*
172** Entries on a page of the database are called "Cells". Each Cell
173** has a header and data. This structure defines the header. The
drhbd03cae2001-06-02 02:40:57 +0000174** key and data (collectively the "payload") follow this header on
175** the database page.
176**
177** A definition of the complete Cell structure is given below. The
drh8c42ca92001-06-22 19:15:00 +0000178** header for the cell must be defined first in order to do some
drhbd03cae2001-06-02 02:40:57 +0000179** of the sizing #defines that follow.
drh3b7511c2001-05-26 13:15:44 +0000180*/
181struct CellHdr {
drh5e2f8b92001-05-28 00:41:15 +0000182 Pgno leftChild; /* Child page that comes before this cell */
drh3b7511c2001-05-26 13:15:44 +0000183 u16 nKey; /* Number of bytes in the key */
drh14acc042001-06-10 19:56:58 +0000184 u16 iNext; /* Index in MemPage.u.aDisk[] of next cell in sorted order */
drh58a11682001-11-10 13:51:08 +0000185 u8 nKeyHi; /* Upper 8 bits of key size for keys larger than 64K bytes */
186 u8 nDataHi; /* Upper 8 bits of data size when the size is more than 64K */
drh80ff32f2001-11-04 18:32:46 +0000187 u16 nData; /* Number of bytes of data */
drh8c42ca92001-06-22 19:15:00 +0000188};
drh58a11682001-11-10 13:51:08 +0000189
190/*
191** The key and data size are split into a lower 16-bit segment and an
192** upper 8-bit segment in order to pack them together into a smaller
193** space. The following macros reassembly a key or data size back
194** into an integer.
195*/
drh0d316a42002-08-11 20:10:47 +0000196#define NKEY(b,h) (SWAB16(b,h.nKey) + h.nKeyHi*65536)
197#define NDATA(b,h) (SWAB16(b,h.nData) + h.nDataHi*65536)
drh3b7511c2001-05-26 13:15:44 +0000198
199/*
200** The minimum size of a complete Cell. The Cell must contain a header
drhbd03cae2001-06-02 02:40:57 +0000201** and at least 4 bytes of payload.
drh3b7511c2001-05-26 13:15:44 +0000202*/
203#define MIN_CELL_SIZE (sizeof(CellHdr)+4)
204
205/*
206** The maximum number of database entries that can be held in a single
207** page of the database.
208*/
209#define MX_CELL ((SQLITE_PAGE_SIZE-sizeof(PageHdr))/MIN_CELL_SIZE)
210
211/*
drh6019e162001-07-02 17:51:45 +0000212** The amount of usable space on a single page of the BTree. This is the
213** page size minus the overhead of the page header.
214*/
215#define USABLE_SPACE (SQLITE_PAGE_SIZE - sizeof(PageHdr))
216
217/*
drh8c42ca92001-06-22 19:15:00 +0000218** The maximum amount of payload (in bytes) that can be stored locally for
219** a database entry. If the entry contains more data than this, the
drh3b7511c2001-05-26 13:15:44 +0000220** extra goes onto overflow pages.
drhbd03cae2001-06-02 02:40:57 +0000221**
222** This number is chosen so that at least 4 cells will fit on every page.
drh3b7511c2001-05-26 13:15:44 +0000223*/
drh6019e162001-07-02 17:51:45 +0000224#define MX_LOCAL_PAYLOAD ((USABLE_SPACE/4-(sizeof(CellHdr)+sizeof(Pgno)))&~3)
drh3b7511c2001-05-26 13:15:44 +0000225
drh306dc212001-05-21 13:45:10 +0000226/*
227** Data on a database page is stored as a linked list of Cell structures.
drh5e2f8b92001-05-28 00:41:15 +0000228** Both the key and the data are stored in aPayload[]. The key always comes
229** first. The aPayload[] field grows as necessary to hold the key and data,
drh306dc212001-05-21 13:45:10 +0000230** up to a maximum of MX_LOCAL_PAYLOAD bytes. If the size of the key and
drh3b7511c2001-05-26 13:15:44 +0000231** data combined exceeds MX_LOCAL_PAYLOAD bytes, then Cell.ovfl is the
232** page number of the first overflow page.
233**
234** Though this structure is fixed in size, the Cell on the database
drhbd03cae2001-06-02 02:40:57 +0000235** page varies in size. Every cell has a CellHdr and at least 4 bytes
drh3b7511c2001-05-26 13:15:44 +0000236** of payload space. Additional payload bytes (up to the maximum of
237** MX_LOCAL_PAYLOAD) and the Cell.ovfl value are allocated only as
238** needed.
drh306dc212001-05-21 13:45:10 +0000239*/
drh365d68f2001-05-11 11:02:46 +0000240struct Cell {
drh5e2f8b92001-05-28 00:41:15 +0000241 CellHdr h; /* The cell header */
242 char aPayload[MX_LOCAL_PAYLOAD]; /* Key and data */
243 Pgno ovfl; /* The first overflow page */
drh365d68f2001-05-11 11:02:46 +0000244};
drh306dc212001-05-21 13:45:10 +0000245
246/*
247** Free space on a page is remembered using a linked list of the FreeBlk
248** structures. Space on a database page is allocated in increments of
drh72f82862001-05-24 21:06:34 +0000249** at least 4 bytes and is always aligned to a 4-byte boundry. The
drh8b2f49b2001-06-08 00:21:52 +0000250** linked list of FreeBlks is always kept in order by address.
drh306dc212001-05-21 13:45:10 +0000251*/
drh365d68f2001-05-11 11:02:46 +0000252struct FreeBlk {
drh72f82862001-05-24 21:06:34 +0000253 u16 iSize; /* Number of bytes in this block of free space */
drh14acc042001-06-10 19:56:58 +0000254 u16 iNext; /* Index in MemPage.u.aDisk[] of the next free block */
drh365d68f2001-05-11 11:02:46 +0000255};
drh306dc212001-05-21 13:45:10 +0000256
257/*
drh14acc042001-06-10 19:56:58 +0000258** The number of bytes of payload that will fit on a single overflow page.
drh3b7511c2001-05-26 13:15:44 +0000259*/
260#define OVERFLOW_SIZE (SQLITE_PAGE_SIZE-sizeof(Pgno))
261
262/*
drh306dc212001-05-21 13:45:10 +0000263** When the key and data for a single entry in the BTree will not fit in
drh8c42ca92001-06-22 19:15:00 +0000264** the MX_LOCAL_PAYLOAD bytes of space available on the database page,
drh8b2f49b2001-06-08 00:21:52 +0000265** then all extra bytes are written to a linked list of overflow pages.
drh306dc212001-05-21 13:45:10 +0000266** Each overflow page is an instance of the following structure.
267**
268** Unused pages in the database are also represented by instances of
drhbd03cae2001-06-02 02:40:57 +0000269** the OverflowPage structure. The PageOne.freeList field is the
drh306dc212001-05-21 13:45:10 +0000270** page number of the first page in a linked list of unused database
271** pages.
272*/
drh2af926b2001-05-15 00:39:25 +0000273struct OverflowPage {
drh14acc042001-06-10 19:56:58 +0000274 Pgno iNext;
drh5e2f8b92001-05-28 00:41:15 +0000275 char aPayload[OVERFLOW_SIZE];
drh7e3b0a02001-04-28 16:52:40 +0000276};
drh7e3b0a02001-04-28 16:52:40 +0000277
278/*
drh30e58752002-03-02 20:41:57 +0000279** The PageOne.freeList field points to a linked list of overflow pages
280** hold information about free pages. The aPayload section of each
281** overflow page contains an instance of the following structure. The
282** aFree[] array holds the page number of nFree unused pages in the disk
283** file.
284*/
285struct FreelistInfo {
286 int nFree;
287 Pgno aFree[(OVERFLOW_SIZE-sizeof(int))/sizeof(Pgno)];
288};
289
290/*
drh7e3b0a02001-04-28 16:52:40 +0000291** For every page in the database file, an instance of the following structure
drh14acc042001-06-10 19:56:58 +0000292** is stored in memory. The u.aDisk[] array contains the raw bits read from
drh6446c4d2001-12-15 14:22:18 +0000293** the disk. The rest is auxiliary information held in memory only. The
drhbd03cae2001-06-02 02:40:57 +0000294** auxiliary info is only valid for regular database pages - it is not
295** used for overflow pages and pages on the freelist.
drh306dc212001-05-21 13:45:10 +0000296**
drhbd03cae2001-06-02 02:40:57 +0000297** Of particular interest in the auxiliary info is the apCell[] entry. Each
drh14acc042001-06-10 19:56:58 +0000298** apCell[] entry is a pointer to a Cell structure in u.aDisk[]. The cells are
drh306dc212001-05-21 13:45:10 +0000299** put in this array so that they can be accessed in constant time, rather
drhbd03cae2001-06-02 02:40:57 +0000300** than in linear time which would be needed if we had to walk the linked
301** list on every access.
drh72f82862001-05-24 21:06:34 +0000302**
drh14acc042001-06-10 19:56:58 +0000303** Note that apCell[] contains enough space to hold up to two more Cells
304** than can possibly fit on one page. In the steady state, every apCell[]
305** points to memory inside u.aDisk[]. But in the middle of an insert
306** operation, some apCell[] entries may temporarily point to data space
307** outside of u.aDisk[]. This is a transient situation that is quickly
308** resolved. But while it is happening, it is possible for a database
309** page to hold as many as two more cells than it might otherwise hold.
drh18b81e52001-11-01 13:52:52 +0000310** The extra two entries in apCell[] are an allowance for this situation.
drh14acc042001-06-10 19:56:58 +0000311**
drh72f82862001-05-24 21:06:34 +0000312** The pParent field points back to the parent page. This allows us to
313** walk up the BTree from any leaf to the root. Care must be taken to
314** unref() the parent page pointer when this page is no longer referenced.
drhbd03cae2001-06-02 02:40:57 +0000315** The pageDestructor() routine handles that chore.
drh7e3b0a02001-04-28 16:52:40 +0000316*/
317struct MemPage {
drh14acc042001-06-10 19:56:58 +0000318 union {
319 char aDisk[SQLITE_PAGE_SIZE]; /* Page data stored on disk */
320 PageHdr hdr; /* Overlay page header */
321 } u;
drh5e2f8b92001-05-28 00:41:15 +0000322 int isInit; /* True if auxiliary data is initialized */
drh72f82862001-05-24 21:06:34 +0000323 MemPage *pParent; /* The parent of this page. NULL for root */
drh14acc042001-06-10 19:56:58 +0000324 int nFree; /* Number of free bytes in u.aDisk[] */
drh306dc212001-05-21 13:45:10 +0000325 int nCell; /* Number of entries on this page */
drh14acc042001-06-10 19:56:58 +0000326 int isOverfull; /* Some apCell[] points outside u.aDisk[] */
327 Cell *apCell[MX_CELL+2]; /* All data entires in sorted order */
drh8c42ca92001-06-22 19:15:00 +0000328};
drh7e3b0a02001-04-28 16:52:40 +0000329
330/*
drh3b7511c2001-05-26 13:15:44 +0000331** The in-memory image of a disk page has the auxiliary information appended
332** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
333** that extra information.
334*/
335#define EXTRA_SIZE (sizeof(MemPage)-SQLITE_PAGE_SIZE)
336
337/*
drha059ad02001-04-17 20:09:11 +0000338** Everything we need to know about an open database
339*/
340struct Btree {
341 Pager *pPager; /* The page cache */
drh306dc212001-05-21 13:45:10 +0000342 BtCursor *pCursor; /* A list of all open cursors */
drhbd03cae2001-06-02 02:40:57 +0000343 PageOne *page1; /* First page of the database */
drh663fc632002-02-02 18:49:19 +0000344 u8 inTrans; /* True if a transaction is in progress */
345 u8 inCkpt; /* True if there is a checkpoint on the transaction */
drh5df72a52002-06-06 23:16:05 +0000346 u8 readOnly; /* True if the underlying file is readonly */
drh0d316a42002-08-11 20:10:47 +0000347 u8 needSwab; /* Need to byte-swapping */
drhecdc7532001-09-23 02:35:53 +0000348 Hash locks; /* Key: root page number. Data: lock count */
drha059ad02001-04-17 20:09:11 +0000349};
350typedef Btree Bt;
351
drh365d68f2001-05-11 11:02:46 +0000352/*
353** A cursor is a pointer to a particular entry in the BTree.
354** The entry is identified by its MemPage and the index in
drh5e2f8b92001-05-28 00:41:15 +0000355** MemPage.apCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000356*/
drh72f82862001-05-24 21:06:34 +0000357struct BtCursor {
drh5e2f8b92001-05-28 00:41:15 +0000358 Btree *pBt; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000359 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drh8b2f49b2001-06-08 00:21:52 +0000360 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000361 MemPage *pPage; /* Page that contains the entry */
drh8c42ca92001-06-22 19:15:00 +0000362 int idx; /* Index of the entry in pPage->apCell[] */
drhecdc7532001-09-23 02:35:53 +0000363 u8 wrFlag; /* True if writable */
drh5e2f8b92001-05-28 00:41:15 +0000364 u8 bSkipNext; /* sqliteBtreeNext() is no-op if true */
365 u8 iMatch; /* compare result from last sqliteBtreeMoveto() */
drh365d68f2001-05-11 11:02:46 +0000366};
drh7e3b0a02001-04-28 16:52:40 +0000367
drha059ad02001-04-17 20:09:11 +0000368/*
drh0d316a42002-08-11 20:10:47 +0000369** Routines for byte swapping.
370*/
371u16 swab16(u16 x){
372 return ((x & 0xff)<<8) | ((x>>8)&0xff);
373}
374u32 swab32(u32 x){
375 return ((x & 0xff)<<24) | ((x & 0xff00)<<8) |
376 ((x>>8) & 0xff00) | ((x>>24)&0xff);
377}
378
379/*
drh3b7511c2001-05-26 13:15:44 +0000380** Compute the total number of bytes that a Cell needs on the main
drh5e2f8b92001-05-28 00:41:15 +0000381** database page. The number returned includes the Cell header,
382** local payload storage, and the pointer to overflow pages (if
drh8c42ca92001-06-22 19:15:00 +0000383** applicable). Additional space allocated on overflow pages
drhbd03cae2001-06-02 02:40:57 +0000384** is NOT included in the value returned from this routine.
drh3b7511c2001-05-26 13:15:44 +0000385*/
drh0d316a42002-08-11 20:10:47 +0000386static int cellSize(Btree *pBt, Cell *pCell){
387 int n = NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h);
drh3b7511c2001-05-26 13:15:44 +0000388 if( n>MX_LOCAL_PAYLOAD ){
389 n = MX_LOCAL_PAYLOAD + sizeof(Pgno);
390 }else{
391 n = ROUNDUP(n);
392 }
393 n += sizeof(CellHdr);
394 return n;
395}
396
397/*
drh72f82862001-05-24 21:06:34 +0000398** Defragment the page given. All Cells are moved to the
399** beginning of the page and all free space is collected
400** into one big FreeBlk at the end of the page.
drh365d68f2001-05-11 11:02:46 +0000401*/
drh0d316a42002-08-11 20:10:47 +0000402static void defragmentPage(Btree *pBt, MemPage *pPage){
drh14acc042001-06-10 19:56:58 +0000403 int pc, i, n;
drh2af926b2001-05-15 00:39:25 +0000404 FreeBlk *pFBlk;
405 char newPage[SQLITE_PAGE_SIZE];
406
drh6019e162001-07-02 17:51:45 +0000407 assert( sqlitepager_iswriteable(pPage) );
drh7aa128d2002-06-21 13:09:16 +0000408 assert( pPage->isInit );
drhbd03cae2001-06-02 02:40:57 +0000409 pc = sizeof(PageHdr);
drh0d316a42002-08-11 20:10:47 +0000410 pPage->u.hdr.firstCell = SWAB16(pBt, pc);
drh14acc042001-06-10 19:56:58 +0000411 memcpy(newPage, pPage->u.aDisk, pc);
drh2af926b2001-05-15 00:39:25 +0000412 for(i=0; i<pPage->nCell; i++){
drh2aa679f2001-06-25 02:11:07 +0000413 Cell *pCell = pPage->apCell[i];
drh8c42ca92001-06-22 19:15:00 +0000414
415 /* This routine should never be called on an overfull page. The
416 ** following asserts verify that constraint. */
drh7c717f72001-06-24 20:39:41 +0000417 assert( Addr(pCell) > Addr(pPage) );
418 assert( Addr(pCell) < Addr(pPage) + SQLITE_PAGE_SIZE );
drh8c42ca92001-06-22 19:15:00 +0000419
drh0d316a42002-08-11 20:10:47 +0000420 n = cellSize(pBt, pCell);
421 pCell->h.iNext = SWAB16(pBt, pc + n);
drh2af926b2001-05-15 00:39:25 +0000422 memcpy(&newPage[pc], pCell, n);
drh14acc042001-06-10 19:56:58 +0000423 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[pc];
drh2af926b2001-05-15 00:39:25 +0000424 pc += n;
425 }
drh72f82862001-05-24 21:06:34 +0000426 assert( pPage->nFree==SQLITE_PAGE_SIZE-pc );
drh14acc042001-06-10 19:56:58 +0000427 memcpy(pPage->u.aDisk, newPage, pc);
drh2aa679f2001-06-25 02:11:07 +0000428 if( pPage->nCell>0 ){
429 pPage->apCell[pPage->nCell-1]->h.iNext = 0;
430 }
drh8c42ca92001-06-22 19:15:00 +0000431 pFBlk = (FreeBlk*)&pPage->u.aDisk[pc];
drh0d316a42002-08-11 20:10:47 +0000432 pFBlk->iSize = SWAB16(pBt, SQLITE_PAGE_SIZE - pc);
drh2af926b2001-05-15 00:39:25 +0000433 pFBlk->iNext = 0;
drh0d316a42002-08-11 20:10:47 +0000434 pPage->u.hdr.firstFree = SWAB16(pBt, pc);
drh2af926b2001-05-15 00:39:25 +0000435 memset(&pFBlk[1], 0, SQLITE_PAGE_SIZE - pc - sizeof(FreeBlk));
drh365d68f2001-05-11 11:02:46 +0000436}
437
drha059ad02001-04-17 20:09:11 +0000438/*
drh8b2f49b2001-06-08 00:21:52 +0000439** Allocate nByte bytes of space on a page. nByte must be a
440** multiple of 4.
drhbd03cae2001-06-02 02:40:57 +0000441**
drh14acc042001-06-10 19:56:58 +0000442** Return the index into pPage->u.aDisk[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000443** the new allocation. Or return 0 if there is not enough free
444** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000445**
drh72f82862001-05-24 21:06:34 +0000446** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000447** nBytes of contiguous free space, then this routine automatically
448** calls defragementPage() to consolidate all free space before
449** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000450*/
drh0d316a42002-08-11 20:10:47 +0000451static int allocateSpace(Btree *pBt, MemPage *pPage, int nByte){
drh2af926b2001-05-15 00:39:25 +0000452 FreeBlk *p;
453 u16 *pIdx;
454 int start;
drh8c42ca92001-06-22 19:15:00 +0000455 int cnt = 0;
drh0d316a42002-08-11 20:10:47 +0000456 int iSize;
drh72f82862001-05-24 21:06:34 +0000457
drh6019e162001-07-02 17:51:45 +0000458 assert( sqlitepager_iswriteable(pPage) );
drh5e2f8b92001-05-28 00:41:15 +0000459 assert( nByte==ROUNDUP(nByte) );
drh7aa128d2002-06-21 13:09:16 +0000460 assert( pPage->isInit );
drh14acc042001-06-10 19:56:58 +0000461 if( pPage->nFree<nByte || pPage->isOverfull ) return 0;
462 pIdx = &pPage->u.hdr.firstFree;
drh0d316a42002-08-11 20:10:47 +0000463 p = (FreeBlk*)&pPage->u.aDisk[SWAB16(pBt, *pIdx)];
464 while( (iSize = SWAB16(pBt, p->iSize))<nByte ){
drh8c42ca92001-06-22 19:15:00 +0000465 assert( cnt++ < SQLITE_PAGE_SIZE/4 );
drh2af926b2001-05-15 00:39:25 +0000466 if( p->iNext==0 ){
drh0d316a42002-08-11 20:10:47 +0000467 defragmentPage(pBt, pPage);
drh14acc042001-06-10 19:56:58 +0000468 pIdx = &pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000469 }else{
470 pIdx = &p->iNext;
471 }
drh0d316a42002-08-11 20:10:47 +0000472 p = (FreeBlk*)&pPage->u.aDisk[SWAB16(pBt, *pIdx)];
drh2af926b2001-05-15 00:39:25 +0000473 }
drh0d316a42002-08-11 20:10:47 +0000474 if( iSize==nByte ){
475 start = SWAB16(pBt, *pIdx);
drh2af926b2001-05-15 00:39:25 +0000476 *pIdx = p->iNext;
477 }else{
drh8c42ca92001-06-22 19:15:00 +0000478 FreeBlk *pNew;
drh0d316a42002-08-11 20:10:47 +0000479 start = SWAB16(pBt, *pIdx);
drh8c42ca92001-06-22 19:15:00 +0000480 pNew = (FreeBlk*)&pPage->u.aDisk[start + nByte];
drh72f82862001-05-24 21:06:34 +0000481 pNew->iNext = p->iNext;
drh0d316a42002-08-11 20:10:47 +0000482 pNew->iSize = SWAB16(pBt, iSize - nByte);
483 *pIdx = SWAB16(pBt, start + nByte);
drh2af926b2001-05-15 00:39:25 +0000484 }
485 pPage->nFree -= nByte;
486 return start;
drh7e3b0a02001-04-28 16:52:40 +0000487}
488
489/*
drh14acc042001-06-10 19:56:58 +0000490** Return a section of the MemPage.u.aDisk[] to the freelist.
491** The first byte of the new free block is pPage->u.aDisk[start]
492** and the size of the block is "size" bytes. Size must be
493** a multiple of 4.
drh306dc212001-05-21 13:45:10 +0000494**
495** Most of the effort here is involved in coalesing adjacent
496** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000497*/
drh0d316a42002-08-11 20:10:47 +0000498static void freeSpace(Btree *pBt, MemPage *pPage, int start, int size){
drh2af926b2001-05-15 00:39:25 +0000499 int end = start + size;
500 u16 *pIdx, idx;
501 FreeBlk *pFBlk;
502 FreeBlk *pNew;
503 FreeBlk *pNext;
drh0d316a42002-08-11 20:10:47 +0000504 int iSize;
drh2af926b2001-05-15 00:39:25 +0000505
drh6019e162001-07-02 17:51:45 +0000506 assert( sqlitepager_iswriteable(pPage) );
drh2af926b2001-05-15 00:39:25 +0000507 assert( size == ROUNDUP(size) );
508 assert( start == ROUNDUP(start) );
drh7aa128d2002-06-21 13:09:16 +0000509 assert( pPage->isInit );
drh14acc042001-06-10 19:56:58 +0000510 pIdx = &pPage->u.hdr.firstFree;
drh0d316a42002-08-11 20:10:47 +0000511 idx = SWAB16(pBt, *pIdx);
drh2af926b2001-05-15 00:39:25 +0000512 while( idx!=0 && idx<start ){
drh14acc042001-06-10 19:56:58 +0000513 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +0000514 iSize = SWAB16(pBt, pFBlk->iSize);
515 if( idx + iSize == start ){
516 pFBlk->iSize = SWAB16(pBt, iSize + size);
517 if( idx + iSize + size == SWAB16(pBt, pFBlk->iNext) ){
518 pNext = (FreeBlk*)&pPage->u.aDisk[idx + iSize + size];
519 if( pBt->needSwab ){
520 pFBlk->iSize = swab16(swab16(pNext->iSize)+iSize+size);
521 }else{
522 pFBlk->iSize += pNext->iSize;
523 }
drh2af926b2001-05-15 00:39:25 +0000524 pFBlk->iNext = pNext->iNext;
525 }
526 pPage->nFree += size;
527 return;
528 }
529 pIdx = &pFBlk->iNext;
drh0d316a42002-08-11 20:10:47 +0000530 idx = SWAB16(pBt, *pIdx);
drh2af926b2001-05-15 00:39:25 +0000531 }
drh14acc042001-06-10 19:56:58 +0000532 pNew = (FreeBlk*)&pPage->u.aDisk[start];
drh2af926b2001-05-15 00:39:25 +0000533 if( idx != end ){
drh0d316a42002-08-11 20:10:47 +0000534 pNew->iSize = SWAB16(pBt, size);
535 pNew->iNext = SWAB16(pBt, idx);
drh2af926b2001-05-15 00:39:25 +0000536 }else{
drh14acc042001-06-10 19:56:58 +0000537 pNext = (FreeBlk*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +0000538 pNew->iSize = SWAB16(pBt, size + SWAB16(pBt, pNext->iSize));
drh2af926b2001-05-15 00:39:25 +0000539 pNew->iNext = pNext->iNext;
540 }
drh0d316a42002-08-11 20:10:47 +0000541 *pIdx = SWAB16(pBt, start);
drh2af926b2001-05-15 00:39:25 +0000542 pPage->nFree += size;
drh7e3b0a02001-04-28 16:52:40 +0000543}
544
545/*
546** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000547**
drhbd03cae2001-06-02 02:40:57 +0000548** The pParent parameter must be a pointer to the MemPage which
549** is the parent of the page being initialized. The root of the
drh8b2f49b2001-06-08 00:21:52 +0000550** BTree (usually page 2) has no parent and so for that page,
551** pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000552**
drh72f82862001-05-24 21:06:34 +0000553** Return SQLITE_OK on success. If we see that the page does
554** not contained a well-formed database page, then return
555** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
556** guarantee that the page is well-formed. It only shows that
557** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000558*/
drh0d316a42002-08-11 20:10:47 +0000559static int initPage(Bt *pBt, MemPage *pPage, Pgno pgnoThis, MemPage *pParent){
drh14acc042001-06-10 19:56:58 +0000560 int idx; /* An index into pPage->u.aDisk[] */
561 Cell *pCell; /* A pointer to a Cell in pPage->u.aDisk[] */
562 FreeBlk *pFBlk; /* A pointer to a free block in pPage->u.aDisk[] */
drh5e2f8b92001-05-28 00:41:15 +0000563 int sz; /* The size of a Cell in bytes */
564 int freeSpace; /* Amount of free space on the page */
drh2af926b2001-05-15 00:39:25 +0000565
drh5e2f8b92001-05-28 00:41:15 +0000566 if( pPage->pParent ){
567 assert( pPage->pParent==pParent );
568 return SQLITE_OK;
569 }
570 if( pParent ){
571 pPage->pParent = pParent;
572 sqlitepager_ref(pParent);
573 }
574 if( pPage->isInit ) return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +0000575 pPage->isInit = 1;
drh7e3b0a02001-04-28 16:52:40 +0000576 pPage->nCell = 0;
drh6019e162001-07-02 17:51:45 +0000577 freeSpace = USABLE_SPACE;
drh0d316a42002-08-11 20:10:47 +0000578 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh7e3b0a02001-04-28 16:52:40 +0000579 while( idx!=0 ){
drh8c42ca92001-06-22 19:15:00 +0000580 if( idx>SQLITE_PAGE_SIZE-MIN_CELL_SIZE ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000581 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh8c42ca92001-06-22 19:15:00 +0000582 if( idx!=ROUNDUP(idx) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000583 pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +0000584 sz = cellSize(pBt, pCell);
drh5e2f8b92001-05-28 00:41:15 +0000585 if( idx+sz > SQLITE_PAGE_SIZE ) goto page_format_error;
586 freeSpace -= sz;
587 pPage->apCell[pPage->nCell++] = pCell;
drh0d316a42002-08-11 20:10:47 +0000588 idx = SWAB16(pBt, pCell->h.iNext);
drh2af926b2001-05-15 00:39:25 +0000589 }
590 pPage->nFree = 0;
drh0d316a42002-08-11 20:10:47 +0000591 idx = SWAB16(pBt, pPage->u.hdr.firstFree);
drh2af926b2001-05-15 00:39:25 +0000592 while( idx!=0 ){
drh0d316a42002-08-11 20:10:47 +0000593 int iNext;
drh2af926b2001-05-15 00:39:25 +0000594 if( idx>SQLITE_PAGE_SIZE-sizeof(FreeBlk) ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000595 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000596 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +0000597 pPage->nFree += SWAB16(pBt, pFBlk->iSize);
598 iNext = SWAB16(pBt, pFBlk->iNext);
599 if( iNext>0 && iNext <= idx ) goto page_format_error;
600 idx = iNext;
drh7e3b0a02001-04-28 16:52:40 +0000601 }
drh8b2f49b2001-06-08 00:21:52 +0000602 if( pPage->nCell==0 && pPage->nFree==0 ){
603 /* As a special case, an uninitialized root page appears to be
604 ** an empty database */
605 return SQLITE_OK;
606 }
drh5e2f8b92001-05-28 00:41:15 +0000607 if( pPage->nFree!=freeSpace ) goto page_format_error;
drh7e3b0a02001-04-28 16:52:40 +0000608 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +0000609
610page_format_error:
611 return SQLITE_CORRUPT;
drh7e3b0a02001-04-28 16:52:40 +0000612}
613
614/*
drh8b2f49b2001-06-08 00:21:52 +0000615** Set up a raw page so that it looks like a database page holding
616** no entries.
drhbd03cae2001-06-02 02:40:57 +0000617*/
drh0d316a42002-08-11 20:10:47 +0000618static void zeroPage(Btree *pBt, MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +0000619 PageHdr *pHdr;
620 FreeBlk *pFBlk;
drh6019e162001-07-02 17:51:45 +0000621 assert( sqlitepager_iswriteable(pPage) );
drhbd03cae2001-06-02 02:40:57 +0000622 memset(pPage, 0, SQLITE_PAGE_SIZE);
drh14acc042001-06-10 19:56:58 +0000623 pHdr = &pPage->u.hdr;
drhbd03cae2001-06-02 02:40:57 +0000624 pHdr->firstCell = 0;
drh0d316a42002-08-11 20:10:47 +0000625 pHdr->firstFree = SWAB16(pBt, sizeof(*pHdr));
drhbd03cae2001-06-02 02:40:57 +0000626 pFBlk = (FreeBlk*)&pHdr[1];
627 pFBlk->iNext = 0;
drh0d316a42002-08-11 20:10:47 +0000628 pPage->nFree = SQLITE_PAGE_SIZE - sizeof(*pHdr);
629 pFBlk->iSize = SWAB16(pBt, pPage->nFree);
drh8c42ca92001-06-22 19:15:00 +0000630 pPage->nCell = 0;
631 pPage->isOverfull = 0;
drhbd03cae2001-06-02 02:40:57 +0000632}
633
634/*
drh72f82862001-05-24 21:06:34 +0000635** This routine is called when the reference count for a page
636** reaches zero. We need to unref the pParent pointer when that
637** happens.
638*/
639static void pageDestructor(void *pData){
640 MemPage *pPage = (MemPage*)pData;
641 if( pPage->pParent ){
642 MemPage *pParent = pPage->pParent;
643 pPage->pParent = 0;
644 sqlitepager_unref(pParent);
645 }
646}
647
648/*
drh306dc212001-05-21 13:45:10 +0000649** Open a new database.
650**
651** Actually, this routine just sets up the internal data structures
drh72f82862001-05-24 21:06:34 +0000652** for accessing the database. We do not open the database file
653** until the first page is loaded.
drh382c0242001-10-06 16:33:02 +0000654**
655** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +0000656** a new database with a random name is created. This randomly named
657** database file will be deleted when sqliteBtreeClose() is called.
drha059ad02001-04-17 20:09:11 +0000658*/
drh6019e162001-07-02 17:51:45 +0000659int sqliteBtreeOpen(
660 const char *zFilename, /* Name of the file containing the BTree database */
661 int mode, /* Not currently used */
662 int nCache, /* How many pages in the page cache */
663 Btree **ppBtree /* Pointer to new Btree object written here */
664){
drha059ad02001-04-17 20:09:11 +0000665 Btree *pBt;
drh8c42ca92001-06-22 19:15:00 +0000666 int rc;
drha059ad02001-04-17 20:09:11 +0000667
668 pBt = sqliteMalloc( sizeof(*pBt) );
669 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +0000670 *ppBtree = 0;
drha059ad02001-04-17 20:09:11 +0000671 return SQLITE_NOMEM;
672 }
drh6019e162001-07-02 17:51:45 +0000673 if( nCache<10 ) nCache = 10;
674 rc = sqlitepager_open(&pBt->pPager, zFilename, nCache, EXTRA_SIZE);
drha059ad02001-04-17 20:09:11 +0000675 if( rc!=SQLITE_OK ){
676 if( pBt->pPager ) sqlitepager_close(pBt->pPager);
677 sqliteFree(pBt);
678 *ppBtree = 0;
679 return rc;
680 }
drh72f82862001-05-24 21:06:34 +0000681 sqlitepager_set_destructor(pBt->pPager, pageDestructor);
drha059ad02001-04-17 20:09:11 +0000682 pBt->pCursor = 0;
683 pBt->page1 = 0;
drh5df72a52002-06-06 23:16:05 +0000684 pBt->readOnly = sqlitepager_isreadonly(pBt->pPager);
drhecdc7532001-09-23 02:35:53 +0000685 sqliteHashInit(&pBt->locks, SQLITE_HASH_INT, 0);
drha059ad02001-04-17 20:09:11 +0000686 *ppBtree = pBt;
687 return SQLITE_OK;
688}
689
690/*
691** Close an open database and invalidate all cursors.
692*/
693int sqliteBtreeClose(Btree *pBt){
694 while( pBt->pCursor ){
695 sqliteBtreeCloseCursor(pBt->pCursor);
696 }
697 sqlitepager_close(pBt->pPager);
drhecdc7532001-09-23 02:35:53 +0000698 sqliteHashClear(&pBt->locks);
drha059ad02001-04-17 20:09:11 +0000699 sqliteFree(pBt);
700 return SQLITE_OK;
701}
702
703/*
drh6446c4d2001-12-15 14:22:18 +0000704** Change the limit on the number of pages allowed the cache.
drhcd61c282002-03-06 22:01:34 +0000705**
706** The maximum number of cache pages is set to the absolute
707** value of mxPage. If mxPage is negative, the pager will
708** operate asynchronously - it will not stop to do fsync()s
709** to insure data is written to the disk surface before
710** continuing. Transactions still work if synchronous is off,
711** and the database cannot be corrupted if this program
712** crashes. But if the operating system crashes or there is
713** an abrupt power failure when synchronous is off, the database
714** could be left in an inconsistent and unrecoverable state.
715** Synchronous is on by default so database corruption is not
716** normally a worry.
drhf57b14a2001-09-14 18:54:08 +0000717*/
718int sqliteBtreeSetCacheSize(Btree *pBt, int mxPage){
719 sqlitepager_set_cachesize(pBt->pPager, mxPage);
720 return SQLITE_OK;
721}
722
723/*
drh306dc212001-05-21 13:45:10 +0000724** Get a reference to page1 of the database file. This will
725** also acquire a readlock on that file.
726**
727** SQLITE_OK is returned on success. If the file is not a
728** well-formed database file, then SQLITE_CORRUPT is returned.
729** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
730** is returned if we run out of memory. SQLITE_PROTOCOL is returned
731** if there is a locking protocol violation.
732*/
733static int lockBtree(Btree *pBt){
734 int rc;
735 if( pBt->page1 ) return SQLITE_OK;
drh8c42ca92001-06-22 19:15:00 +0000736 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pBt->page1);
drh306dc212001-05-21 13:45:10 +0000737 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +0000738
739 /* Do some checking to help insure the file we opened really is
740 ** a valid database file.
741 */
742 if( sqlitepager_pagecount(pBt->pPager)>0 ){
drhbd03cae2001-06-02 02:40:57 +0000743 PageOne *pP1 = pBt->page1;
drh0d316a42002-08-11 20:10:47 +0000744 if( strcmp(pP1->zMagic,zMagicHeader)!=0 ||
745 (pP1->iMagic!=MAGIC && swab32(pP1->iMagic)!=MAGIC) ){
drh306dc212001-05-21 13:45:10 +0000746 rc = SQLITE_CORRUPT;
drh72f82862001-05-24 21:06:34 +0000747 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +0000748 }
drh0d316a42002-08-11 20:10:47 +0000749 pBt->needSwab = pP1->iMagic!=MAGIC;
drh306dc212001-05-21 13:45:10 +0000750 }
751 return rc;
752
drh72f82862001-05-24 21:06:34 +0000753page1_init_failed:
drh306dc212001-05-21 13:45:10 +0000754 sqlitepager_unref(pBt->page1);
755 pBt->page1 = 0;
drh72f82862001-05-24 21:06:34 +0000756 return rc;
drh306dc212001-05-21 13:45:10 +0000757}
758
759/*
drhb8ca3072001-12-05 00:21:20 +0000760** If there are no outstanding cursors and we are not in the middle
761** of a transaction but there is a read lock on the database, then
762** this routine unrefs the first page of the database file which
763** has the effect of releasing the read lock.
764**
765** If there are any outstanding cursors, this routine is a no-op.
766**
767** If there is a transaction in progress, this routine is a no-op.
768*/
769static void unlockBtreeIfUnused(Btree *pBt){
770 if( pBt->inTrans==0 && pBt->pCursor==0 && pBt->page1!=0 ){
771 sqlitepager_unref(pBt->page1);
772 pBt->page1 = 0;
773 pBt->inTrans = 0;
drh663fc632002-02-02 18:49:19 +0000774 pBt->inCkpt = 0;
drhb8ca3072001-12-05 00:21:20 +0000775 }
776}
777
778/*
drh8c42ca92001-06-22 19:15:00 +0000779** Create a new database by initializing the first two pages of the
780** file.
drh8b2f49b2001-06-08 00:21:52 +0000781*/
782static int newDatabase(Btree *pBt){
783 MemPage *pRoot;
784 PageOne *pP1;
drh8c42ca92001-06-22 19:15:00 +0000785 int rc;
drh7c717f72001-06-24 20:39:41 +0000786 if( sqlitepager_pagecount(pBt->pPager)>1 ) return SQLITE_OK;
drh8b2f49b2001-06-08 00:21:52 +0000787 pP1 = pBt->page1;
788 rc = sqlitepager_write(pBt->page1);
789 if( rc ) return rc;
drh8c42ca92001-06-22 19:15:00 +0000790 rc = sqlitepager_get(pBt->pPager, 2, (void**)&pRoot);
drh8b2f49b2001-06-08 00:21:52 +0000791 if( rc ) return rc;
792 rc = sqlitepager_write(pRoot);
793 if( rc ){
794 sqlitepager_unref(pRoot);
795 return rc;
796 }
797 strcpy(pP1->zMagic, zMagicHeader);
drh0d316a42002-08-11 20:10:47 +0000798 if( btree_native_byte_order ){
799 pP1->iMagic = MAGIC;
800 pBt->needSwab = 0;
801 }else{
802 pP1->iMagic = swab32(MAGIC);
803 pBt->needSwab = 1;
804 }
drh0d316a42002-08-11 20:10:47 +0000805 zeroPage(pBt, pRoot);
drh8b2f49b2001-06-08 00:21:52 +0000806 sqlitepager_unref(pRoot);
807 return SQLITE_OK;
808}
809
810/*
drh72f82862001-05-24 21:06:34 +0000811** Attempt to start a new transaction.
drh8b2f49b2001-06-08 00:21:52 +0000812**
813** A transaction must be started before attempting any changes
814** to the database. None of the following routines will work
815** unless a transaction is started first:
816**
817** sqliteBtreeCreateTable()
drhc6b52df2002-01-04 03:09:29 +0000818** sqliteBtreeCreateIndex()
drh8b2f49b2001-06-08 00:21:52 +0000819** sqliteBtreeClearTable()
820** sqliteBtreeDropTable()
821** sqliteBtreeInsert()
822** sqliteBtreeDelete()
823** sqliteBtreeUpdateMeta()
drha059ad02001-04-17 20:09:11 +0000824*/
825int sqliteBtreeBeginTrans(Btree *pBt){
826 int rc;
827 if( pBt->inTrans ) return SQLITE_ERROR;
828 if( pBt->page1==0 ){
drh7e3b0a02001-04-28 16:52:40 +0000829 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +0000830 if( rc!=SQLITE_OK ){
831 return rc;
832 }
drha059ad02001-04-17 20:09:11 +0000833 }
drh5df72a52002-06-06 23:16:05 +0000834 if( pBt->readOnly ){
835 rc = SQLITE_OK;
836 }else{
837 rc = sqlitepager_begin(pBt->page1);
838 if( rc==SQLITE_OK ){
839 rc = newDatabase(pBt);
840 }
drha059ad02001-04-17 20:09:11 +0000841 }
drhb8ca3072001-12-05 00:21:20 +0000842 if( rc==SQLITE_OK ){
843 pBt->inTrans = 1;
drh663fc632002-02-02 18:49:19 +0000844 pBt->inCkpt = 0;
drhb8ca3072001-12-05 00:21:20 +0000845 }else{
846 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000847 }
drhb8ca3072001-12-05 00:21:20 +0000848 return rc;
drha059ad02001-04-17 20:09:11 +0000849}
850
851/*
drh2aa679f2001-06-25 02:11:07 +0000852** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +0000853**
854** This will release the write lock on the database file. If there
855** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000856*/
857int sqliteBtreeCommit(Btree *pBt){
858 int rc;
drh2aa679f2001-06-25 02:11:07 +0000859 if( pBt->inTrans==0 ) return SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +0000860 rc = pBt->readOnly ? SQLITE_OK : sqlitepager_commit(pBt->pPager);
drh7c717f72001-06-24 20:39:41 +0000861 pBt->inTrans = 0;
drh663fc632002-02-02 18:49:19 +0000862 pBt->inCkpt = 0;
drh5e00f6c2001-09-13 13:46:56 +0000863 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000864 return rc;
865}
866
867/*
drhecdc7532001-09-23 02:35:53 +0000868** Rollback the transaction in progress. All cursors will be
869** invalided by this operation. Any attempt to use a cursor
870** that was open at the beginning of this operation will result
871** in an error.
drh5e00f6c2001-09-13 13:46:56 +0000872**
873** This will release the write lock on the database file. If there
874** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000875*/
876int sqliteBtreeRollback(Btree *pBt){
877 int rc;
drhecdc7532001-09-23 02:35:53 +0000878 BtCursor *pCur;
drh7c717f72001-06-24 20:39:41 +0000879 if( pBt->inTrans==0 ) return SQLITE_OK;
880 pBt->inTrans = 0;
drh663fc632002-02-02 18:49:19 +0000881 pBt->inCkpt = 0;
drhecdc7532001-09-23 02:35:53 +0000882 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
883 if( pCur->pPage ){
884 sqlitepager_unref(pCur->pPage);
885 pCur->pPage = 0;
886 }
887 }
drh5df72a52002-06-06 23:16:05 +0000888 rc = pBt->readOnly ? SQLITE_OK : sqlitepager_rollback(pBt->pPager);
drh5e00f6c2001-09-13 13:46:56 +0000889 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000890 return rc;
891}
892
893/*
drh663fc632002-02-02 18:49:19 +0000894** Set the checkpoint for the current transaction. The checkpoint serves
895** as a sub-transaction that can be rolled back independently of the
896** main transaction. You must start a transaction before starting a
897** checkpoint. The checkpoint is ended automatically if the transaction
898** commits or rolls back.
899**
900** Only one checkpoint may be active at a time. It is an error to try
901** to start a new checkpoint if another checkpoint is already active.
902*/
903int sqliteBtreeBeginCkpt(Btree *pBt){
904 int rc;
drh0d65dc02002-02-03 00:56:09 +0000905 if( !pBt->inTrans || pBt->inCkpt ){
906 return SQLITE_ERROR;
907 }
drh5df72a52002-06-06 23:16:05 +0000908 rc = pBt->readOnly ? SQLITE_OK : sqlitepager_ckpt_begin(pBt->pPager);
drh663fc632002-02-02 18:49:19 +0000909 pBt->inCkpt = 1;
910 return rc;
911}
912
913
914/*
915** Commit a checkpoint to transaction currently in progress. If no
916** checkpoint is active, this is a no-op.
917*/
918int sqliteBtreeCommitCkpt(Btree *pBt){
919 int rc;
drh5df72a52002-06-06 23:16:05 +0000920 if( pBt->inCkpt && !pBt->readOnly ){
drh663fc632002-02-02 18:49:19 +0000921 rc = sqlitepager_ckpt_commit(pBt->pPager);
922 }else{
923 rc = SQLITE_OK;
924 }
drh0d65dc02002-02-03 00:56:09 +0000925 pBt->inCkpt = 0;
drh663fc632002-02-02 18:49:19 +0000926 return rc;
927}
928
929/*
930** Rollback the checkpoint to the current transaction. If there
931** is no active checkpoint or transaction, this routine is a no-op.
932**
933** All cursors will be invalided by this operation. Any attempt
934** to use a cursor that was open at the beginning of this operation
935** will result in an error.
936*/
937int sqliteBtreeRollbackCkpt(Btree *pBt){
938 int rc;
939 BtCursor *pCur;
drh5df72a52002-06-06 23:16:05 +0000940 if( pBt->inCkpt==0 || pBt->readOnly ) return SQLITE_OK;
drh663fc632002-02-02 18:49:19 +0000941 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
942 if( pCur->pPage ){
943 sqlitepager_unref(pCur->pPage);
944 pCur->pPage = 0;
945 }
946 }
947 rc = sqlitepager_ckpt_rollback(pBt->pPager);
drh0d65dc02002-02-03 00:56:09 +0000948 pBt->inCkpt = 0;
drh663fc632002-02-02 18:49:19 +0000949 return rc;
950}
951
952/*
drh8b2f49b2001-06-08 00:21:52 +0000953** Create a new cursor for the BTree whose root is on the page
954** iTable. The act of acquiring a cursor gets a read lock on
955** the database file.
drh1bee3d72001-10-15 00:44:35 +0000956**
957** If wrFlag==0, then the cursor can only be used for reading.
958** If wrFlag==1, then the cursor can be used for reading or writing.
959** A read/write cursor requires exclusive access to its table. There
drh6446c4d2001-12-15 14:22:18 +0000960** cannot be two or more cursors open on the same table if any one of
drh1bee3d72001-10-15 00:44:35 +0000961** cursors is a read/write cursor. But there can be two or more
962** read-only cursors open on the same table.
drh6446c4d2001-12-15 14:22:18 +0000963**
964** No checking is done to make sure that page iTable really is the
965** root page of a b-tree. If it is not, then the cursor acquired
966** will not work correctly.
drha059ad02001-04-17 20:09:11 +0000967*/
drhecdc7532001-09-23 02:35:53 +0000968int sqliteBtreeCursor(Btree *pBt, int iTable, int wrFlag, BtCursor **ppCur){
drha059ad02001-04-17 20:09:11 +0000969 int rc;
970 BtCursor *pCur;
drh5a2c2c22001-11-21 02:21:11 +0000971 ptr nLock;
drhecdc7532001-09-23 02:35:53 +0000972
drha059ad02001-04-17 20:09:11 +0000973 if( pBt->page1==0 ){
974 rc = lockBtree(pBt);
975 if( rc!=SQLITE_OK ){
976 *ppCur = 0;
977 return rc;
978 }
979 }
drh5df72a52002-06-06 23:16:05 +0000980 if( wrFlag && pBt->readOnly ){
981 *ppCur = 0;
982 return SQLITE_READONLY;
983 }
drha059ad02001-04-17 20:09:11 +0000984 pCur = sqliteMalloc( sizeof(*pCur) );
985 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +0000986 rc = SQLITE_NOMEM;
987 goto create_cursor_exception;
988 }
drh8b2f49b2001-06-08 00:21:52 +0000989 pCur->pgnoRoot = (Pgno)iTable;
drh8c42ca92001-06-22 19:15:00 +0000990 rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +0000991 if( rc!=SQLITE_OK ){
992 goto create_cursor_exception;
993 }
drh0d316a42002-08-11 20:10:47 +0000994 rc = initPage(pBt, pCur->pPage, pCur->pgnoRoot, 0);
drhbd03cae2001-06-02 02:40:57 +0000995 if( rc!=SQLITE_OK ){
996 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +0000997 }
drh5a2c2c22001-11-21 02:21:11 +0000998 nLock = (ptr)sqliteHashFind(&pBt->locks, 0, iTable);
drhecdc7532001-09-23 02:35:53 +0000999 if( nLock<0 || (nLock>0 && wrFlag) ){
1000 rc = SQLITE_LOCKED;
1001 goto create_cursor_exception;
1002 }
1003 nLock = wrFlag ? -1 : nLock+1;
1004 sqliteHashInsert(&pBt->locks, 0, iTable, (void*)nLock);
drh14acc042001-06-10 19:56:58 +00001005 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +00001006 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +00001007 pCur->idx = 0;
drha059ad02001-04-17 20:09:11 +00001008 pCur->pNext = pBt->pCursor;
1009 if( pCur->pNext ){
1010 pCur->pNext->pPrev = pCur;
1011 }
drh14acc042001-06-10 19:56:58 +00001012 pCur->pPrev = 0;
drha059ad02001-04-17 20:09:11 +00001013 pBt->pCursor = pCur;
drh2af926b2001-05-15 00:39:25 +00001014 *ppCur = pCur;
1015 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00001016
1017create_cursor_exception:
1018 *ppCur = 0;
1019 if( pCur ){
1020 if( pCur->pPage ) sqlitepager_unref(pCur->pPage);
1021 sqliteFree(pCur);
1022 }
drh5e00f6c2001-09-13 13:46:56 +00001023 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00001024 return rc;
drha059ad02001-04-17 20:09:11 +00001025}
1026
1027/*
drh5e00f6c2001-09-13 13:46:56 +00001028** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00001029** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00001030*/
1031int sqliteBtreeCloseCursor(BtCursor *pCur){
drh5a2c2c22001-11-21 02:21:11 +00001032 ptr nLock;
drha059ad02001-04-17 20:09:11 +00001033 Btree *pBt = pCur->pBt;
drha059ad02001-04-17 20:09:11 +00001034 if( pCur->pPrev ){
1035 pCur->pPrev->pNext = pCur->pNext;
1036 }else{
1037 pBt->pCursor = pCur->pNext;
1038 }
1039 if( pCur->pNext ){
1040 pCur->pNext->pPrev = pCur->pPrev;
1041 }
drhecdc7532001-09-23 02:35:53 +00001042 if( pCur->pPage ){
1043 sqlitepager_unref(pCur->pPage);
1044 }
drh5e00f6c2001-09-13 13:46:56 +00001045 unlockBtreeIfUnused(pBt);
drh5a2c2c22001-11-21 02:21:11 +00001046 nLock = (ptr)sqliteHashFind(&pBt->locks, 0, pCur->pgnoRoot);
drh6d4abfb2001-10-22 02:58:08 +00001047 assert( nLock!=0 || sqlite_malloc_failed );
drhecdc7532001-09-23 02:35:53 +00001048 nLock = nLock<0 ? 0 : nLock-1;
1049 sqliteHashInsert(&pBt->locks, 0, pCur->pgnoRoot, (void*)nLock);
drha059ad02001-04-17 20:09:11 +00001050 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +00001051 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00001052}
1053
drh7e3b0a02001-04-28 16:52:40 +00001054/*
drh5e2f8b92001-05-28 00:41:15 +00001055** Make a temporary cursor by filling in the fields of pTempCur.
1056** The temporary cursor is not on the cursor list for the Btree.
1057*/
drh14acc042001-06-10 19:56:58 +00001058static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00001059 memcpy(pTempCur, pCur, sizeof(*pCur));
1060 pTempCur->pNext = 0;
1061 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00001062 if( pTempCur->pPage ){
1063 sqlitepager_ref(pTempCur->pPage);
1064 }
drh5e2f8b92001-05-28 00:41:15 +00001065}
1066
1067/*
drhbd03cae2001-06-02 02:40:57 +00001068** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00001069** function above.
1070*/
drh14acc042001-06-10 19:56:58 +00001071static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00001072 if( pCur->pPage ){
1073 sqlitepager_unref(pCur->pPage);
1074 }
drh5e2f8b92001-05-28 00:41:15 +00001075}
1076
1077/*
drhbd03cae2001-06-02 02:40:57 +00001078** Set *pSize to the number of bytes of key in the entry the
1079** cursor currently points to. Always return SQLITE_OK.
1080** Failure is not possible. If the cursor is not currently
1081** pointing to an entry (which can happen, for example, if
1082** the database is empty) then *pSize is set to 0.
drh7e3b0a02001-04-28 16:52:40 +00001083*/
drh72f82862001-05-24 21:06:34 +00001084int sqliteBtreeKeySize(BtCursor *pCur, int *pSize){
drh2af926b2001-05-15 00:39:25 +00001085 Cell *pCell;
1086 MemPage *pPage;
1087
1088 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001089 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh72f82862001-05-24 21:06:34 +00001090 *pSize = 0;
1091 }else{
drh5e2f8b92001-05-28 00:41:15 +00001092 pCell = pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00001093 *pSize = NKEY(pCur->pBt, pCell->h);
drh72f82862001-05-24 21:06:34 +00001094 }
1095 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00001096}
drh2af926b2001-05-15 00:39:25 +00001097
drh72f82862001-05-24 21:06:34 +00001098/*
1099** Read payload information from the entry that the pCur cursor is
1100** pointing to. Begin reading the payload at "offset" and read
1101** a total of "amt" bytes. Put the result in zBuf.
1102**
1103** This routine does not make a distinction between key and data.
1104** It just reads bytes from the payload area.
1105*/
drh2af926b2001-05-15 00:39:25 +00001106static int getPayload(BtCursor *pCur, int offset, int amt, char *zBuf){
drh5e2f8b92001-05-28 00:41:15 +00001107 char *aPayload;
drh2af926b2001-05-15 00:39:25 +00001108 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +00001109 int rc;
drh0d316a42002-08-11 20:10:47 +00001110 Btree *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00001111 assert( pCur!=0 && pCur->pPage!=0 );
drh8c42ca92001-06-22 19:15:00 +00001112 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
1113 aPayload = pCur->pPage->apCell[pCur->idx]->aPayload;
drh2af926b2001-05-15 00:39:25 +00001114 if( offset<MX_LOCAL_PAYLOAD ){
1115 int a = amt;
1116 if( a+offset>MX_LOCAL_PAYLOAD ){
1117 a = MX_LOCAL_PAYLOAD - offset;
1118 }
drh5e2f8b92001-05-28 00:41:15 +00001119 memcpy(zBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +00001120 if( a==amt ){
1121 return SQLITE_OK;
1122 }
drh2aa679f2001-06-25 02:11:07 +00001123 offset = 0;
drh2af926b2001-05-15 00:39:25 +00001124 zBuf += a;
1125 amt -= a;
drhdd793422001-06-28 01:54:48 +00001126 }else{
1127 offset -= MX_LOCAL_PAYLOAD;
drhbd03cae2001-06-02 02:40:57 +00001128 }
1129 if( amt>0 ){
drh0d316a42002-08-11 20:10:47 +00001130 nextPage = SWAB32(pBt, pCur->pPage->apCell[pCur->idx]->ovfl);
drh2af926b2001-05-15 00:39:25 +00001131 }
1132 while( amt>0 && nextPage ){
1133 OverflowPage *pOvfl;
drh0d316a42002-08-11 20:10:47 +00001134 rc = sqlitepager_get(pBt->pPager, nextPage, (void**)&pOvfl);
drh2af926b2001-05-15 00:39:25 +00001135 if( rc!=0 ){
1136 return rc;
1137 }
drh0d316a42002-08-11 20:10:47 +00001138 nextPage = SWAB32(pBt, pOvfl->iNext);
drh2af926b2001-05-15 00:39:25 +00001139 if( offset<OVERFLOW_SIZE ){
1140 int a = amt;
1141 if( a + offset > OVERFLOW_SIZE ){
1142 a = OVERFLOW_SIZE - offset;
1143 }
drh5e2f8b92001-05-28 00:41:15 +00001144 memcpy(zBuf, &pOvfl->aPayload[offset], a);
drh2aa679f2001-06-25 02:11:07 +00001145 offset = 0;
drh2af926b2001-05-15 00:39:25 +00001146 amt -= a;
1147 zBuf += a;
drh2aa679f2001-06-25 02:11:07 +00001148 }else{
1149 offset -= OVERFLOW_SIZE;
drh2af926b2001-05-15 00:39:25 +00001150 }
1151 sqlitepager_unref(pOvfl);
1152 }
drha7fcb052001-12-14 15:09:55 +00001153 if( amt>0 ){
1154 return SQLITE_CORRUPT;
1155 }
1156 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00001157}
1158
drh72f82862001-05-24 21:06:34 +00001159/*
drh5e00f6c2001-09-13 13:46:56 +00001160** Read part of the key associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +00001161** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +00001162** begins at "offset". The number of bytes actually read is
1163** returned. The amount returned will be smaller than the
1164** amount requested if there are not enough bytes in the key
1165** to satisfy the request.
drh72f82862001-05-24 21:06:34 +00001166*/
1167int sqliteBtreeKey(BtCursor *pCur, int offset, int amt, char *zBuf){
1168 Cell *pCell;
1169 MemPage *pPage;
drha059ad02001-04-17 20:09:11 +00001170
drh5e00f6c2001-09-13 13:46:56 +00001171 if( amt<0 ) return 0;
1172 if( offset<0 ) return 0;
1173 if( amt==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001174 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001175 if( pPage==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001176 if( pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +00001177 return 0;
drh72f82862001-05-24 21:06:34 +00001178 }
drh5e2f8b92001-05-28 00:41:15 +00001179 pCell = pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00001180 if( amt+offset > NKEY(pCur->pBt, pCell->h) ){
1181 amt = NKEY(pCur->pBt, pCell->h) - offset;
drh5e00f6c2001-09-13 13:46:56 +00001182 if( amt<=0 ){
1183 return 0;
1184 }
drhbd03cae2001-06-02 02:40:57 +00001185 }
drh5e00f6c2001-09-13 13:46:56 +00001186 getPayload(pCur, offset, amt, zBuf);
1187 return amt;
drh72f82862001-05-24 21:06:34 +00001188}
1189
1190/*
drhbd03cae2001-06-02 02:40:57 +00001191** Set *pSize to the number of bytes of data in the entry the
1192** cursor currently points to. Always return SQLITE_OK.
1193** Failure is not possible. If the cursor is not currently
1194** pointing to an entry (which can happen, for example, if
1195** the database is empty) then *pSize is set to 0.
drh72f82862001-05-24 21:06:34 +00001196*/
1197int sqliteBtreeDataSize(BtCursor *pCur, int *pSize){
1198 Cell *pCell;
1199 MemPage *pPage;
1200
1201 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001202 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh72f82862001-05-24 21:06:34 +00001203 *pSize = 0;
1204 }else{
drh5e2f8b92001-05-28 00:41:15 +00001205 pCell = pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00001206 *pSize = NDATA(pCur->pBt, pCell->h);
drh72f82862001-05-24 21:06:34 +00001207 }
1208 return SQLITE_OK;
1209}
1210
1211/*
drh5e00f6c2001-09-13 13:46:56 +00001212** Read part of the data associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +00001213** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +00001214** begins at "offset". The number of bytes actually read is
1215** returned. The amount returned will be smaller than the
1216** amount requested if there are not enough bytes in the data
1217** to satisfy the request.
drh72f82862001-05-24 21:06:34 +00001218*/
1219int sqliteBtreeData(BtCursor *pCur, int offset, int amt, char *zBuf){
1220 Cell *pCell;
1221 MemPage *pPage;
drh0d316a42002-08-11 20:10:47 +00001222 int nData;
drh72f82862001-05-24 21:06:34 +00001223
drh5e00f6c2001-09-13 13:46:56 +00001224 if( amt<0 ) return 0;
1225 if( offset<0 ) return 0;
1226 if( amt==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001227 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001228 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +00001229 return 0;
drh72f82862001-05-24 21:06:34 +00001230 }
drh5e2f8b92001-05-28 00:41:15 +00001231 pCell = pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00001232 nData = NDATA(pCur->pBt, pCell->h);
1233 if( amt+offset > nData ){
1234 amt = nData - offset;
drh5e00f6c2001-09-13 13:46:56 +00001235 if( amt<=0 ){
1236 return 0;
1237 }
drhbd03cae2001-06-02 02:40:57 +00001238 }
drh0d316a42002-08-11 20:10:47 +00001239 getPayload(pCur, offset + NKEY(pCur->pBt, pCell->h), amt, zBuf);
drh5e00f6c2001-09-13 13:46:56 +00001240 return amt;
drh72f82862001-05-24 21:06:34 +00001241}
drha059ad02001-04-17 20:09:11 +00001242
drh2af926b2001-05-15 00:39:25 +00001243/*
drh8721ce42001-11-07 14:22:00 +00001244** Compare an external key against the key on the entry that pCur points to.
1245**
1246** The external key is pKey and is nKey bytes long. The last nIgnore bytes
1247** of the key associated with pCur are ignored, as if they do not exist.
1248** (The normal case is for nIgnore to be zero in which case the entire
1249** internal key is used in the comparison.)
1250**
1251** The comparison result is written to *pRes as follows:
drh2af926b2001-05-15 00:39:25 +00001252**
drh717e6402001-09-27 03:22:32 +00001253** *pRes<0 This means pCur<pKey
1254**
1255** *pRes==0 This means pCur==pKey for all nKey bytes
1256**
1257** *pRes>0 This means pCur>pKey
1258**
drh8721ce42001-11-07 14:22:00 +00001259** When one key is an exact prefix of the other, the shorter key is
1260** considered less than the longer one. In order to be equal the
1261** keys must be exactly the same length. (The length of the pCur key
1262** is the actual key length minus nIgnore bytes.)
drh2af926b2001-05-15 00:39:25 +00001263*/
drh717e6402001-09-27 03:22:32 +00001264int sqliteBtreeKeyCompare(
drh8721ce42001-11-07 14:22:00 +00001265 BtCursor *pCur, /* Pointer to entry to compare against */
1266 const void *pKey, /* Key to compare against entry that pCur points to */
1267 int nKey, /* Number of bytes in pKey */
1268 int nIgnore, /* Ignore this many bytes at the end of pCur */
1269 int *pResult /* Write the result here */
drh5c4d9702001-08-20 00:33:58 +00001270){
drh2af926b2001-05-15 00:39:25 +00001271 Pgno nextPage;
drh8721ce42001-11-07 14:22:00 +00001272 int n, c, rc, nLocal;
drh2af926b2001-05-15 00:39:25 +00001273 Cell *pCell;
drh0d316a42002-08-11 20:10:47 +00001274 Btree *pBt = pCur->pBt;
drh717e6402001-09-27 03:22:32 +00001275 const char *zKey = (const char*)pKey;
drh2af926b2001-05-15 00:39:25 +00001276
1277 assert( pCur->pPage );
1278 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drhbd03cae2001-06-02 02:40:57 +00001279 pCell = pCur->pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00001280 nLocal = NKEY(pBt, pCell->h) - nIgnore;
drh8721ce42001-11-07 14:22:00 +00001281 if( nLocal<0 ) nLocal = 0;
1282 n = nKey<nLocal ? nKey : nLocal;
drh2af926b2001-05-15 00:39:25 +00001283 if( n>MX_LOCAL_PAYLOAD ){
1284 n = MX_LOCAL_PAYLOAD;
1285 }
drh717e6402001-09-27 03:22:32 +00001286 c = memcmp(pCell->aPayload, zKey, n);
drh2af926b2001-05-15 00:39:25 +00001287 if( c!=0 ){
1288 *pResult = c;
1289 return SQLITE_OK;
1290 }
drh717e6402001-09-27 03:22:32 +00001291 zKey += n;
drh2af926b2001-05-15 00:39:25 +00001292 nKey -= n;
drh8721ce42001-11-07 14:22:00 +00001293 nLocal -= n;
drh0d316a42002-08-11 20:10:47 +00001294 nextPage = SWAB32(pBt, pCell->ovfl);
drh8721ce42001-11-07 14:22:00 +00001295 while( nKey>0 && nLocal>0 ){
drh2af926b2001-05-15 00:39:25 +00001296 OverflowPage *pOvfl;
1297 if( nextPage==0 ){
1298 return SQLITE_CORRUPT;
1299 }
drh0d316a42002-08-11 20:10:47 +00001300 rc = sqlitepager_get(pBt->pPager, nextPage, (void**)&pOvfl);
drh72f82862001-05-24 21:06:34 +00001301 if( rc ){
drh2af926b2001-05-15 00:39:25 +00001302 return rc;
1303 }
drh0d316a42002-08-11 20:10:47 +00001304 nextPage = SWAB32(pBt, pOvfl->iNext);
drh8721ce42001-11-07 14:22:00 +00001305 n = nKey<nLocal ? nKey : nLocal;
drh2af926b2001-05-15 00:39:25 +00001306 if( n>OVERFLOW_SIZE ){
1307 n = OVERFLOW_SIZE;
1308 }
drh717e6402001-09-27 03:22:32 +00001309 c = memcmp(pOvfl->aPayload, zKey, n);
drh2af926b2001-05-15 00:39:25 +00001310 sqlitepager_unref(pOvfl);
1311 if( c!=0 ){
1312 *pResult = c;
1313 return SQLITE_OK;
1314 }
1315 nKey -= n;
drh8721ce42001-11-07 14:22:00 +00001316 nLocal -= n;
drh717e6402001-09-27 03:22:32 +00001317 zKey += n;
drh2af926b2001-05-15 00:39:25 +00001318 }
drh717e6402001-09-27 03:22:32 +00001319 if( c==0 ){
drh8721ce42001-11-07 14:22:00 +00001320 c = nLocal - nKey;
drh717e6402001-09-27 03:22:32 +00001321 }
drh2af926b2001-05-15 00:39:25 +00001322 *pResult = c;
1323 return SQLITE_OK;
1324}
1325
drh72f82862001-05-24 21:06:34 +00001326/*
1327** Move the cursor down to a new child page.
1328*/
drh5e2f8b92001-05-28 00:41:15 +00001329static int moveToChild(BtCursor *pCur, int newPgno){
drh72f82862001-05-24 21:06:34 +00001330 int rc;
1331 MemPage *pNewPage;
drh0d316a42002-08-11 20:10:47 +00001332 Btree *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00001333
drh0d316a42002-08-11 20:10:47 +00001334 rc = sqlitepager_get(pBt->pPager, newPgno, (void**)&pNewPage);
drh6019e162001-07-02 17:51:45 +00001335 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001336 rc = initPage(pBt, pNewPage, newPgno, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00001337 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001338 sqlitepager_unref(pCur->pPage);
1339 pCur->pPage = pNewPage;
1340 pCur->idx = 0;
1341 return SQLITE_OK;
1342}
1343
1344/*
drh5e2f8b92001-05-28 00:41:15 +00001345** Move the cursor up to the parent page.
1346**
1347** pCur->idx is set to the cell index that contains the pointer
1348** to the page we are coming from. If we are coming from the
1349** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00001350** the largest cell index.
drh72f82862001-05-24 21:06:34 +00001351*/
drh5e2f8b92001-05-28 00:41:15 +00001352static int moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001353 Pgno oldPgno;
1354 MemPage *pParent;
drh8c42ca92001-06-22 19:15:00 +00001355 int i;
drh72f82862001-05-24 21:06:34 +00001356 pParent = pCur->pPage->pParent;
drhbd03cae2001-06-02 02:40:57 +00001357 if( pParent==0 ) return SQLITE_INTERNAL;
drh72f82862001-05-24 21:06:34 +00001358 oldPgno = sqlitepager_pagenumber(pCur->pPage);
drh72f82862001-05-24 21:06:34 +00001359 sqlitepager_ref(pParent);
1360 sqlitepager_unref(pCur->pPage);
1361 pCur->pPage = pParent;
drh8c42ca92001-06-22 19:15:00 +00001362 pCur->idx = pParent->nCell;
drh0d316a42002-08-11 20:10:47 +00001363 oldPgno = SWAB32(pCur->pBt, oldPgno);
drh8c42ca92001-06-22 19:15:00 +00001364 for(i=0; i<pParent->nCell; i++){
1365 if( pParent->apCell[i]->h.leftChild==oldPgno ){
drh72f82862001-05-24 21:06:34 +00001366 pCur->idx = i;
1367 break;
1368 }
1369 }
drh5e2f8b92001-05-28 00:41:15 +00001370 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00001371}
1372
1373/*
1374** Move the cursor to the root page
1375*/
drh5e2f8b92001-05-28 00:41:15 +00001376static int moveToRoot(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001377 MemPage *pNew;
drhbd03cae2001-06-02 02:40:57 +00001378 int rc;
drh0d316a42002-08-11 20:10:47 +00001379 Btree *pBt = pCur->pBt;
drhbd03cae2001-06-02 02:40:57 +00001380
drh0d316a42002-08-11 20:10:47 +00001381 rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pNew);
drhbd03cae2001-06-02 02:40:57 +00001382 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001383 rc = initPage(pBt, pNew, pCur->pgnoRoot, 0);
drh6019e162001-07-02 17:51:45 +00001384 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001385 sqlitepager_unref(pCur->pPage);
1386 pCur->pPage = pNew;
1387 pCur->idx = 0;
1388 return SQLITE_OK;
1389}
drh2af926b2001-05-15 00:39:25 +00001390
drh5e2f8b92001-05-28 00:41:15 +00001391/*
1392** Move the cursor down to the left-most leaf entry beneath the
1393** entry to which it is currently pointing.
1394*/
1395static int moveToLeftmost(BtCursor *pCur){
1396 Pgno pgno;
1397 int rc;
1398
1399 while( (pgno = pCur->pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
drh0d316a42002-08-11 20:10:47 +00001400 rc = moveToChild(pCur, SWAB32(pCur->pBt, pgno));
drh5e2f8b92001-05-28 00:41:15 +00001401 if( rc ) return rc;
1402 }
1403 return SQLITE_OK;
1404}
1405
drh5e00f6c2001-09-13 13:46:56 +00001406/* Move the cursor to the first entry in the table. Return SQLITE_OK
1407** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00001408** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00001409*/
1410int sqliteBtreeFirst(BtCursor *pCur, int *pRes){
1411 int rc;
drhecdc7532001-09-23 02:35:53 +00001412 if( pCur->pPage==0 ) return SQLITE_ABORT;
drh5e00f6c2001-09-13 13:46:56 +00001413 rc = moveToRoot(pCur);
1414 if( rc ) return rc;
1415 if( pCur->pPage->nCell==0 ){
1416 *pRes = 1;
1417 return SQLITE_OK;
1418 }
1419 *pRes = 0;
1420 rc = moveToLeftmost(pCur);
drh0ce92ed2001-12-15 02:47:28 +00001421 pCur->bSkipNext = 0;
drh5e00f6c2001-09-13 13:46:56 +00001422 return rc;
1423}
drh5e2f8b92001-05-28 00:41:15 +00001424
drh9562b552002-02-19 15:00:07 +00001425/* Move the cursor to the last entry in the table. Return SQLITE_OK
1426** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00001427** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00001428*/
1429int sqliteBtreeLast(BtCursor *pCur, int *pRes){
1430 int rc;
1431 Pgno pgno;
1432 if( pCur->pPage==0 ) return SQLITE_ABORT;
1433 rc = moveToRoot(pCur);
1434 if( rc ) return rc;
drh7aa128d2002-06-21 13:09:16 +00001435 assert( pCur->pPage->isInit );
drh9562b552002-02-19 15:00:07 +00001436 if( pCur->pPage->nCell==0 ){
1437 *pRes = 1;
1438 return SQLITE_OK;
1439 }
1440 *pRes = 0;
1441 while( (pgno = pCur->pPage->u.hdr.rightChild)!=0 ){
drh0d316a42002-08-11 20:10:47 +00001442 rc = moveToChild(pCur, SWAB32(pCur->pBt, pgno));
drh9562b552002-02-19 15:00:07 +00001443 if( rc ) return rc;
1444 }
1445 pCur->idx = pCur->pPage->nCell-1;
1446 pCur->bSkipNext = 0;
1447 return rc;
1448}
1449
drha059ad02001-04-17 20:09:11 +00001450/* Move the cursor so that it points to an entry near pKey.
drh72f82862001-05-24 21:06:34 +00001451** Return a success code.
1452**
drh5e2f8b92001-05-28 00:41:15 +00001453** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00001454** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00001455** were present. The cursor might point to an entry that comes
1456** before or after the key.
1457**
drhbd03cae2001-06-02 02:40:57 +00001458** The result of comparing the key with the entry to which the
1459** cursor is left pointing is stored in pCur->iMatch. The same
1460** value is also written to *pRes if pRes!=NULL. The meaning of
1461** this value is as follows:
1462**
1463** *pRes<0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001464** is smaller than pKey.
drhbd03cae2001-06-02 02:40:57 +00001465**
1466** *pRes==0 The cursor is left pointing at an entry that
1467** exactly matches pKey.
1468**
1469** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001470** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00001471*/
drh5c4d9702001-08-20 00:33:58 +00001472int sqliteBtreeMoveto(BtCursor *pCur, const void *pKey, int nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00001473 int rc;
drhecdc7532001-09-23 02:35:53 +00001474 if( pCur->pPage==0 ) return SQLITE_ABORT;
drh7c717f72001-06-24 20:39:41 +00001475 pCur->bSkipNext = 0;
drh5e2f8b92001-05-28 00:41:15 +00001476 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00001477 if( rc ) return rc;
1478 for(;;){
1479 int lwr, upr;
1480 Pgno chldPg;
1481 MemPage *pPage = pCur->pPage;
drh8b2f49b2001-06-08 00:21:52 +00001482 int c = -1;
drh72f82862001-05-24 21:06:34 +00001483 lwr = 0;
1484 upr = pPage->nCell-1;
1485 while( lwr<=upr ){
drh72f82862001-05-24 21:06:34 +00001486 pCur->idx = (lwr+upr)/2;
drh8721ce42001-11-07 14:22:00 +00001487 rc = sqliteBtreeKeyCompare(pCur, pKey, nKey, 0, &c);
drh72f82862001-05-24 21:06:34 +00001488 if( rc ) return rc;
1489 if( c==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001490 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001491 if( pRes ) *pRes = 0;
1492 return SQLITE_OK;
1493 }
1494 if( c<0 ){
1495 lwr = pCur->idx+1;
1496 }else{
1497 upr = pCur->idx-1;
1498 }
1499 }
1500 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00001501 assert( pPage->isInit );
drh72f82862001-05-24 21:06:34 +00001502 if( lwr>=pPage->nCell ){
drh14acc042001-06-10 19:56:58 +00001503 chldPg = pPage->u.hdr.rightChild;
drh72f82862001-05-24 21:06:34 +00001504 }else{
drh5e2f8b92001-05-28 00:41:15 +00001505 chldPg = pPage->apCell[lwr]->h.leftChild;
drh72f82862001-05-24 21:06:34 +00001506 }
1507 if( chldPg==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001508 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001509 if( pRes ) *pRes = c;
1510 return SQLITE_OK;
1511 }
drh0d316a42002-08-11 20:10:47 +00001512 rc = moveToChild(pCur, SWAB32(pCur->pBt, chldPg));
drh72f82862001-05-24 21:06:34 +00001513 if( rc ) return rc;
1514 }
drhbd03cae2001-06-02 02:40:57 +00001515 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00001516}
1517
1518/*
drhbd03cae2001-06-02 02:40:57 +00001519** Advance the cursor to the next entry in the database. If
1520** successful and pRes!=NULL then set *pRes=0. If the cursor
1521** was already pointing to the last entry in the database before
1522** this routine was called, then set *pRes=1 if pRes!=NULL.
drh72f82862001-05-24 21:06:34 +00001523*/
1524int sqliteBtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00001525 int rc;
drhecdc7532001-09-23 02:35:53 +00001526 if( pCur->pPage==0 ){
drh1bee3d72001-10-15 00:44:35 +00001527 if( pRes ) *pRes = 1;
drhecdc7532001-09-23 02:35:53 +00001528 return SQLITE_ABORT;
1529 }
drh7aa128d2002-06-21 13:09:16 +00001530 assert( pCur->pPage->isInit );
drhf5bf0a72001-11-23 00:24:12 +00001531 if( pCur->bSkipNext && pCur->idx<pCur->pPage->nCell ){
drh5e2f8b92001-05-28 00:41:15 +00001532 pCur->bSkipNext = 0;
drh72f82862001-05-24 21:06:34 +00001533 if( pRes ) *pRes = 0;
1534 return SQLITE_OK;
1535 }
drh72f82862001-05-24 21:06:34 +00001536 pCur->idx++;
drh5e2f8b92001-05-28 00:41:15 +00001537 if( pCur->idx>=pCur->pPage->nCell ){
drh8c42ca92001-06-22 19:15:00 +00001538 if( pCur->pPage->u.hdr.rightChild ){
drh0d316a42002-08-11 20:10:47 +00001539 rc = moveToChild(pCur, SWAB32(pCur->pBt, pCur->pPage->u.hdr.rightChild));
drh5e2f8b92001-05-28 00:41:15 +00001540 if( rc ) return rc;
1541 rc = moveToLeftmost(pCur);
1542 if( rc ) return rc;
1543 if( pRes ) *pRes = 0;
drh72f82862001-05-24 21:06:34 +00001544 return SQLITE_OK;
1545 }
drh5e2f8b92001-05-28 00:41:15 +00001546 do{
drh8c42ca92001-06-22 19:15:00 +00001547 if( pCur->pPage->pParent==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001548 if( pRes ) *pRes = 1;
1549 return SQLITE_OK;
1550 }
1551 rc = moveToParent(pCur);
1552 if( rc ) return rc;
1553 }while( pCur->idx>=pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00001554 if( pRes ) *pRes = 0;
1555 return SQLITE_OK;
1556 }
drh5e2f8b92001-05-28 00:41:15 +00001557 rc = moveToLeftmost(pCur);
1558 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001559 if( pRes ) *pRes = 0;
1560 return SQLITE_OK;
1561}
1562
drh3b7511c2001-05-26 13:15:44 +00001563/*
1564** Allocate a new page from the database file.
1565**
1566** The new page is marked as dirty. (In other words, sqlitepager_write()
1567** has already been called on the new page.) The new page has also
1568** been referenced and the calling routine is responsible for calling
1569** sqlitepager_unref() on the new page when it is done.
1570**
1571** SQLITE_OK is returned on success. Any other return value indicates
1572** an error. *ppPage and *pPgno are undefined in the event of an error.
1573** Do not invoke sqlitepager_unref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00001574**
drh199e3cf2002-07-18 11:01:47 +00001575** If the "nearby" parameter is not 0, then a (feeble) effort is made to
1576** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00001577** attempt to keep related pages close to each other in the database file,
1578** which in turn can make database access faster.
drh3b7511c2001-05-26 13:15:44 +00001579*/
drh199e3cf2002-07-18 11:01:47 +00001580static int allocatePage(Btree *pBt, MemPage **ppPage, Pgno *pPgno, Pgno nearby){
drhbd03cae2001-06-02 02:40:57 +00001581 PageOne *pPage1 = pBt->page1;
drh8c42ca92001-06-22 19:15:00 +00001582 int rc;
drh3b7511c2001-05-26 13:15:44 +00001583 if( pPage1->freeList ){
1584 OverflowPage *pOvfl;
drh30e58752002-03-02 20:41:57 +00001585 FreelistInfo *pInfo;
1586
drh3b7511c2001-05-26 13:15:44 +00001587 rc = sqlitepager_write(pPage1);
1588 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001589 SWAB_ADD(pBt, pPage1->nFree, -1);
1590 rc = sqlitepager_get(pBt->pPager, SWAB32(pBt, pPage1->freeList),
1591 (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001592 if( rc ) return rc;
1593 rc = sqlitepager_write(pOvfl);
1594 if( rc ){
1595 sqlitepager_unref(pOvfl);
1596 return rc;
1597 }
drh30e58752002-03-02 20:41:57 +00001598 pInfo = (FreelistInfo*)pOvfl->aPayload;
1599 if( pInfo->nFree==0 ){
drh0d316a42002-08-11 20:10:47 +00001600 *pPgno = SWAB32(pBt, pPage1->freeList);
drh30e58752002-03-02 20:41:57 +00001601 pPage1->freeList = pOvfl->iNext;
1602 *ppPage = (MemPage*)pOvfl;
1603 }else{
drh0d316a42002-08-11 20:10:47 +00001604 int closest, n;
1605 n = SWAB32(pBt, pInfo->nFree);
1606 if( n>1 && nearby>0 ){
drhbea00b92002-07-08 10:59:50 +00001607 int i, dist;
1608 closest = 0;
drh0d316a42002-08-11 20:10:47 +00001609 dist = SWAB32(pBt, pInfo->aFree[0]) - nearby;
drhbea00b92002-07-08 10:59:50 +00001610 if( dist<0 ) dist = -dist;
drh0d316a42002-08-11 20:10:47 +00001611 for(i=1; i<n; i++){
1612 int d2 = SWAB32(pBt, pInfo->aFree[i]) - nearby;
drhbea00b92002-07-08 10:59:50 +00001613 if( d2<0 ) d2 = -d2;
1614 if( d2<dist ) closest = i;
1615 }
1616 }else{
1617 closest = 0;
1618 }
drh0d316a42002-08-11 20:10:47 +00001619 SWAB_ADD(pBt, pInfo->nFree, -1);
1620 *pPgno = SWAB32(pBt, pInfo->aFree[closest]);
1621 pInfo->aFree[closest] = pInfo->aFree[n-1];
drh30e58752002-03-02 20:41:57 +00001622 rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
1623 sqlitepager_unref(pOvfl);
1624 if( rc==SQLITE_OK ){
1625 sqlitepager_dont_rollback(*ppPage);
1626 rc = sqlitepager_write(*ppPage);
1627 }
1628 }
drh3b7511c2001-05-26 13:15:44 +00001629 }else{
drh2aa679f2001-06-25 02:11:07 +00001630 *pPgno = sqlitepager_pagecount(pBt->pPager) + 1;
drh8c42ca92001-06-22 19:15:00 +00001631 rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
drh3b7511c2001-05-26 13:15:44 +00001632 if( rc ) return rc;
1633 rc = sqlitepager_write(*ppPage);
1634 }
1635 return rc;
1636}
1637
1638/*
1639** Add a page of the database file to the freelist. Either pgno or
1640** pPage but not both may be 0.
drh5e2f8b92001-05-28 00:41:15 +00001641**
drhdd793422001-06-28 01:54:48 +00001642** sqlitepager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00001643*/
1644static int freePage(Btree *pBt, void *pPage, Pgno pgno){
drhbd03cae2001-06-02 02:40:57 +00001645 PageOne *pPage1 = pBt->page1;
drh3b7511c2001-05-26 13:15:44 +00001646 OverflowPage *pOvfl = (OverflowPage*)pPage;
1647 int rc;
drhdd793422001-06-28 01:54:48 +00001648 int needUnref = 0;
1649 MemPage *pMemPage;
drh8b2f49b2001-06-08 00:21:52 +00001650
drh3b7511c2001-05-26 13:15:44 +00001651 if( pgno==0 ){
1652 assert( pOvfl!=0 );
1653 pgno = sqlitepager_pagenumber(pOvfl);
1654 }
drh2aa679f2001-06-25 02:11:07 +00001655 assert( pgno>2 );
drh193a6b42002-07-07 16:52:46 +00001656 pMemPage = (MemPage*)pPage;
1657 pMemPage->isInit = 0;
1658 if( pMemPage->pParent ){
1659 sqlitepager_unref(pMemPage->pParent);
1660 pMemPage->pParent = 0;
1661 }
drh3b7511c2001-05-26 13:15:44 +00001662 rc = sqlitepager_write(pPage1);
1663 if( rc ){
1664 return rc;
1665 }
drh0d316a42002-08-11 20:10:47 +00001666 SWAB_ADD(pBt, pPage1->nFree, 1);
1667 if( pPage1->nFree!=0 && pPage1->freeList!=0 ){
drh30e58752002-03-02 20:41:57 +00001668 OverflowPage *pFreeIdx;
drh0d316a42002-08-11 20:10:47 +00001669 rc = sqlitepager_get(pBt->pPager, SWAB32(pBt, pPage1->freeList),
1670 (void**)&pFreeIdx);
drh30e58752002-03-02 20:41:57 +00001671 if( rc==SQLITE_OK ){
1672 FreelistInfo *pInfo = (FreelistInfo*)pFreeIdx->aPayload;
drh0d316a42002-08-11 20:10:47 +00001673 int n = SWAB32(pBt, pInfo->nFree);
1674 if( n<(sizeof(pInfo->aFree)/sizeof(pInfo->aFree[0])) ){
drh30e58752002-03-02 20:41:57 +00001675 rc = sqlitepager_write(pFreeIdx);
1676 if( rc==SQLITE_OK ){
drh0d316a42002-08-11 20:10:47 +00001677 pInfo->aFree[n] = SWAB32(pBt, pgno);
1678 SWAB_ADD(pBt, pInfo->nFree, 1);
drh30e58752002-03-02 20:41:57 +00001679 sqlitepager_unref(pFreeIdx);
1680 sqlitepager_dont_write(pBt->pPager, pgno);
1681 return rc;
1682 }
1683 }
1684 sqlitepager_unref(pFreeIdx);
1685 }
1686 }
drh3b7511c2001-05-26 13:15:44 +00001687 if( pOvfl==0 ){
1688 assert( pgno>0 );
drh8c42ca92001-06-22 19:15:00 +00001689 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001690 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001691 needUnref = 1;
drh3b7511c2001-05-26 13:15:44 +00001692 }
1693 rc = sqlitepager_write(pOvfl);
1694 if( rc ){
drhdd793422001-06-28 01:54:48 +00001695 if( needUnref ) sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001696 return rc;
1697 }
drh14acc042001-06-10 19:56:58 +00001698 pOvfl->iNext = pPage1->freeList;
drh0d316a42002-08-11 20:10:47 +00001699 pPage1->freeList = SWAB32(pBt, pgno);
drh5e2f8b92001-05-28 00:41:15 +00001700 memset(pOvfl->aPayload, 0, OVERFLOW_SIZE);
drhdd793422001-06-28 01:54:48 +00001701 if( needUnref ) rc = sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001702 return rc;
1703}
1704
1705/*
1706** Erase all the data out of a cell. This involves returning overflow
1707** pages back the freelist.
1708*/
1709static int clearCell(Btree *pBt, Cell *pCell){
1710 Pager *pPager = pBt->pPager;
1711 OverflowPage *pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001712 Pgno ovfl, nextOvfl;
1713 int rc;
1714
drh0d316a42002-08-11 20:10:47 +00001715 if( NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h) <= MX_LOCAL_PAYLOAD ){
drh5e2f8b92001-05-28 00:41:15 +00001716 return SQLITE_OK;
1717 }
drh0d316a42002-08-11 20:10:47 +00001718 ovfl = SWAB32(pBt, pCell->ovfl);
drh3b7511c2001-05-26 13:15:44 +00001719 pCell->ovfl = 0;
1720 while( ovfl ){
drh8c42ca92001-06-22 19:15:00 +00001721 rc = sqlitepager_get(pPager, ovfl, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001722 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00001723 nextOvfl = SWAB32(pBt, pOvfl->iNext);
drhbd03cae2001-06-02 02:40:57 +00001724 rc = freePage(pBt, pOvfl, ovfl);
1725 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001726 sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001727 ovfl = nextOvfl;
drh3b7511c2001-05-26 13:15:44 +00001728 }
drh5e2f8b92001-05-28 00:41:15 +00001729 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00001730}
1731
1732/*
1733** Create a new cell from key and data. Overflow pages are allocated as
1734** necessary and linked to this cell.
1735*/
1736static int fillInCell(
1737 Btree *pBt, /* The whole Btree. Needed to allocate pages */
1738 Cell *pCell, /* Populate this Cell structure */
drh5c4d9702001-08-20 00:33:58 +00001739 const void *pKey, int nKey, /* The key */
1740 const void *pData,int nData /* The data */
drh3b7511c2001-05-26 13:15:44 +00001741){
drhdd793422001-06-28 01:54:48 +00001742 OverflowPage *pOvfl, *pPrior;
drh3b7511c2001-05-26 13:15:44 +00001743 Pgno *pNext;
1744 int spaceLeft;
drh8c42ca92001-06-22 19:15:00 +00001745 int n, rc;
drh3b7511c2001-05-26 13:15:44 +00001746 int nPayload;
drh5c4d9702001-08-20 00:33:58 +00001747 const char *pPayload;
drh3b7511c2001-05-26 13:15:44 +00001748 char *pSpace;
drh199e3cf2002-07-18 11:01:47 +00001749 Pgno nearby = 0;
drh3b7511c2001-05-26 13:15:44 +00001750
drh5e2f8b92001-05-28 00:41:15 +00001751 pCell->h.leftChild = 0;
drh0d316a42002-08-11 20:10:47 +00001752 pCell->h.nKey = SWAB16(pBt, nKey & 0xffff);
drh80ff32f2001-11-04 18:32:46 +00001753 pCell->h.nKeyHi = nKey >> 16;
drh0d316a42002-08-11 20:10:47 +00001754 pCell->h.nData = SWAB16(pBt, nData & 0xffff);
drh80ff32f2001-11-04 18:32:46 +00001755 pCell->h.nDataHi = nData >> 16;
drh3b7511c2001-05-26 13:15:44 +00001756 pCell->h.iNext = 0;
1757
1758 pNext = &pCell->ovfl;
drh5e2f8b92001-05-28 00:41:15 +00001759 pSpace = pCell->aPayload;
drh3b7511c2001-05-26 13:15:44 +00001760 spaceLeft = MX_LOCAL_PAYLOAD;
1761 pPayload = pKey;
1762 pKey = 0;
1763 nPayload = nKey;
drhdd793422001-06-28 01:54:48 +00001764 pPrior = 0;
drh3b7511c2001-05-26 13:15:44 +00001765 while( nPayload>0 ){
1766 if( spaceLeft==0 ){
drh199e3cf2002-07-18 11:01:47 +00001767 rc = allocatePage(pBt, (MemPage**)&pOvfl, pNext, nearby);
drh3b7511c2001-05-26 13:15:44 +00001768 if( rc ){
1769 *pNext = 0;
drhbea00b92002-07-08 10:59:50 +00001770 }else{
drh199e3cf2002-07-18 11:01:47 +00001771 nearby = *pNext;
drhdd793422001-06-28 01:54:48 +00001772 }
1773 if( pPrior ) sqlitepager_unref(pPrior);
1774 if( rc ){
drh5e2f8b92001-05-28 00:41:15 +00001775 clearCell(pBt, pCell);
drh3b7511c2001-05-26 13:15:44 +00001776 return rc;
1777 }
drh0d316a42002-08-11 20:10:47 +00001778 if( pBt->needSwab ) *pNext = swab32(*pNext);
drhdd793422001-06-28 01:54:48 +00001779 pPrior = pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001780 spaceLeft = OVERFLOW_SIZE;
drh5e2f8b92001-05-28 00:41:15 +00001781 pSpace = pOvfl->aPayload;
drh8c42ca92001-06-22 19:15:00 +00001782 pNext = &pOvfl->iNext;
drh3b7511c2001-05-26 13:15:44 +00001783 }
1784 n = nPayload;
1785 if( n>spaceLeft ) n = spaceLeft;
1786 memcpy(pSpace, pPayload, n);
1787 nPayload -= n;
1788 if( nPayload==0 && pData ){
1789 pPayload = pData;
1790 nPayload = nData;
1791 pData = 0;
1792 }else{
1793 pPayload += n;
1794 }
1795 spaceLeft -= n;
1796 pSpace += n;
1797 }
drhdd793422001-06-28 01:54:48 +00001798 *pNext = 0;
1799 if( pPrior ){
1800 sqlitepager_unref(pPrior);
1801 }
drh3b7511c2001-05-26 13:15:44 +00001802 return SQLITE_OK;
1803}
1804
1805/*
drhbd03cae2001-06-02 02:40:57 +00001806** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00001807** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00001808** pointer in the third argument.
1809*/
1810static void reparentPage(Pager *pPager, Pgno pgno, MemPage *pNewParent){
1811 MemPage *pThis;
1812
drhdd793422001-06-28 01:54:48 +00001813 if( pgno==0 ) return;
1814 assert( pPager!=0 );
drhbd03cae2001-06-02 02:40:57 +00001815 pThis = sqlitepager_lookup(pPager, pgno);
drh6019e162001-07-02 17:51:45 +00001816 if( pThis && pThis->isInit ){
drhdd793422001-06-28 01:54:48 +00001817 if( pThis->pParent!=pNewParent ){
1818 if( pThis->pParent ) sqlitepager_unref(pThis->pParent);
1819 pThis->pParent = pNewParent;
1820 if( pNewParent ) sqlitepager_ref(pNewParent);
1821 }
1822 sqlitepager_unref(pThis);
drhbd03cae2001-06-02 02:40:57 +00001823 }
1824}
1825
1826/*
1827** Reparent all children of the given page to be the given page.
1828** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00001829** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00001830**
1831** This routine gets called after you memcpy() one page into
1832** another.
1833*/
drh0d316a42002-08-11 20:10:47 +00001834static void reparentChildPages(Btree *pBt, MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00001835 int i;
drh0d316a42002-08-11 20:10:47 +00001836 Pager *pPager = pBt->pPager;
drhbd03cae2001-06-02 02:40:57 +00001837 for(i=0; i<pPage->nCell; i++){
drh0d316a42002-08-11 20:10:47 +00001838 reparentPage(pPager, SWAB32(pBt, pPage->apCell[i]->h.leftChild), pPage);
drhbd03cae2001-06-02 02:40:57 +00001839 }
drh0d316a42002-08-11 20:10:47 +00001840 reparentPage(pPager, SWAB32(pBt, pPage->u.hdr.rightChild), pPage);
drh14acc042001-06-10 19:56:58 +00001841}
1842
1843/*
1844** Remove the i-th cell from pPage. This routine effects pPage only.
1845** The cell content is not freed or deallocated. It is assumed that
1846** the cell content has been copied someplace else. This routine just
1847** removes the reference to the cell from pPage.
1848**
1849** "sz" must be the number of bytes in the cell.
1850**
1851** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001852** Only the pPage->apCell[] array is important. The relinkCellList()
1853** routine will be called soon after this routine in order to rebuild
1854** the linked list.
drh14acc042001-06-10 19:56:58 +00001855*/
drh0d316a42002-08-11 20:10:47 +00001856static void dropCell(Btree *pBt, MemPage *pPage, int idx, int sz){
drh14acc042001-06-10 19:56:58 +00001857 int j;
drh8c42ca92001-06-22 19:15:00 +00001858 assert( idx>=0 && idx<pPage->nCell );
drh0d316a42002-08-11 20:10:47 +00001859 assert( sz==cellSize(pBt, pPage->apCell[idx]) );
drh6019e162001-07-02 17:51:45 +00001860 assert( sqlitepager_iswriteable(pPage) );
drh0d316a42002-08-11 20:10:47 +00001861 freeSpace(pBt, pPage, Addr(pPage->apCell[idx]) - Addr(pPage), sz);
drh7c717f72001-06-24 20:39:41 +00001862 for(j=idx; j<pPage->nCell-1; j++){
drh14acc042001-06-10 19:56:58 +00001863 pPage->apCell[j] = pPage->apCell[j+1];
1864 }
1865 pPage->nCell--;
1866}
1867
1868/*
1869** Insert a new cell on pPage at cell index "i". pCell points to the
1870** content of the cell.
1871**
1872** If the cell content will fit on the page, then put it there. If it
1873** will not fit, then just make pPage->apCell[i] point to the content
1874** and set pPage->isOverfull.
1875**
1876** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001877** Only the pPage->apCell[] array is important. The relinkCellList()
1878** routine will be called soon after this routine in order to rebuild
1879** the linked list.
drh14acc042001-06-10 19:56:58 +00001880*/
drh0d316a42002-08-11 20:10:47 +00001881static void insertCell(Btree *pBt, MemPage *pPage, int i, Cell *pCell, int sz){
drh14acc042001-06-10 19:56:58 +00001882 int idx, j;
1883 assert( i>=0 && i<=pPage->nCell );
drh0d316a42002-08-11 20:10:47 +00001884 assert( sz==cellSize(pBt, pCell) );
drh6019e162001-07-02 17:51:45 +00001885 assert( sqlitepager_iswriteable(pPage) );
drh0d316a42002-08-11 20:10:47 +00001886 idx = allocateSpace(pBt, pPage, sz);
drh14acc042001-06-10 19:56:58 +00001887 for(j=pPage->nCell; j>i; j--){
1888 pPage->apCell[j] = pPage->apCell[j-1];
1889 }
1890 pPage->nCell++;
drh14acc042001-06-10 19:56:58 +00001891 if( idx<=0 ){
1892 pPage->isOverfull = 1;
1893 pPage->apCell[i] = pCell;
1894 }else{
1895 memcpy(&pPage->u.aDisk[idx], pCell, sz);
drh8c42ca92001-06-22 19:15:00 +00001896 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[idx];
drh14acc042001-06-10 19:56:58 +00001897 }
1898}
1899
1900/*
1901** Rebuild the linked list of cells on a page so that the cells
drh8c42ca92001-06-22 19:15:00 +00001902** occur in the order specified by the pPage->apCell[] array.
1903** Invoke this routine once to repair damage after one or more
1904** invocations of either insertCell() or dropCell().
drh14acc042001-06-10 19:56:58 +00001905*/
drh0d316a42002-08-11 20:10:47 +00001906static void relinkCellList(Btree *pBt, MemPage *pPage){
drh14acc042001-06-10 19:56:58 +00001907 int i;
1908 u16 *pIdx;
drh6019e162001-07-02 17:51:45 +00001909 assert( sqlitepager_iswriteable(pPage) );
drh14acc042001-06-10 19:56:58 +00001910 pIdx = &pPage->u.hdr.firstCell;
1911 for(i=0; i<pPage->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00001912 int idx = Addr(pPage->apCell[i]) - Addr(pPage);
drh8c42ca92001-06-22 19:15:00 +00001913 assert( idx>0 && idx<SQLITE_PAGE_SIZE );
drh0d316a42002-08-11 20:10:47 +00001914 *pIdx = SWAB16(pBt, idx);
drh14acc042001-06-10 19:56:58 +00001915 pIdx = &pPage->apCell[i]->h.iNext;
1916 }
1917 *pIdx = 0;
1918}
1919
1920/*
1921** Make a copy of the contents of pFrom into pTo. The pFrom->apCell[]
drh5e00f6c2001-09-13 13:46:56 +00001922** pointers that point into pFrom->u.aDisk[] must be adjusted to point
drhdd793422001-06-28 01:54:48 +00001923** into pTo->u.aDisk[] instead. But some pFrom->apCell[] entries might
drh14acc042001-06-10 19:56:58 +00001924** not point to pFrom->u.aDisk[]. Those are unchanged.
1925*/
1926static void copyPage(MemPage *pTo, MemPage *pFrom){
1927 uptr from, to;
1928 int i;
1929 memcpy(pTo->u.aDisk, pFrom->u.aDisk, SQLITE_PAGE_SIZE);
drhdd793422001-06-28 01:54:48 +00001930 pTo->pParent = 0;
drh14acc042001-06-10 19:56:58 +00001931 pTo->isInit = 1;
1932 pTo->nCell = pFrom->nCell;
1933 pTo->nFree = pFrom->nFree;
1934 pTo->isOverfull = pFrom->isOverfull;
drh7c717f72001-06-24 20:39:41 +00001935 to = Addr(pTo);
1936 from = Addr(pFrom);
drh14acc042001-06-10 19:56:58 +00001937 for(i=0; i<pTo->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00001938 uptr x = Addr(pFrom->apCell[i]);
drh8c42ca92001-06-22 19:15:00 +00001939 if( x>from && x<from+SQLITE_PAGE_SIZE ){
1940 *((uptr*)&pTo->apCell[i]) = x + to - from;
drhdd793422001-06-28 01:54:48 +00001941 }else{
1942 pTo->apCell[i] = pFrom->apCell[i];
drh14acc042001-06-10 19:56:58 +00001943 }
1944 }
drhbd03cae2001-06-02 02:40:57 +00001945}
1946
1947/*
drh8b2f49b2001-06-08 00:21:52 +00001948** This routine redistributes Cells on pPage and up to two siblings
1949** of pPage so that all pages have about the same amount of free space.
drh14acc042001-06-10 19:56:58 +00001950** Usually one sibling on either side of pPage is used in the balancing,
drh8b2f49b2001-06-08 00:21:52 +00001951** though both siblings might come from one side if pPage is the first
1952** or last child of its parent. If pPage has fewer than two siblings
1953** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00001954** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00001955**
1956** The number of siblings of pPage might be increased or decreased by
drh8c42ca92001-06-22 19:15:00 +00001957** one in an effort to keep pages between 66% and 100% full. The root page
1958** is special and is allowed to be less than 66% full. If pPage is
1959** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00001960** or decreased by one, as necessary, to keep the root page from being
1961** overfull or empty.
1962**
drh14acc042001-06-10 19:56:58 +00001963** This routine calls relinkCellList() on its input page regardless of
1964** whether or not it does any real balancing. Client routines will typically
1965** invoke insertCell() or dropCell() before calling this routine, so we
1966** need to call relinkCellList() to clean up the mess that those other
1967** routines left behind.
1968**
1969** pCur is left pointing to the same cell as when this routine was called
drh8c42ca92001-06-22 19:15:00 +00001970** even if that cell gets moved to a different page. pCur may be NULL.
1971** Set the pCur parameter to NULL if you do not care about keeping track
1972** of a cell as that will save this routine the work of keeping track of it.
drh14acc042001-06-10 19:56:58 +00001973**
drh8b2f49b2001-06-08 00:21:52 +00001974** Note that when this routine is called, some of the Cells on pPage
drh14acc042001-06-10 19:56:58 +00001975** might not actually be stored in pPage->u.aDisk[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00001976** if the page is overfull. Part of the job of this routine is to
drh14acc042001-06-10 19:56:58 +00001977** make sure all Cells for pPage once again fit in pPage->u.aDisk[].
1978**
drh8c42ca92001-06-22 19:15:00 +00001979** In the course of balancing the siblings of pPage, the parent of pPage
1980** might become overfull or underfull. If that happens, then this routine
1981** is called recursively on the parent.
1982**
drh5e00f6c2001-09-13 13:46:56 +00001983** If this routine fails for any reason, it might leave the database
1984** in a corrupted state. So if this routine fails, the database should
1985** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00001986*/
drh14acc042001-06-10 19:56:58 +00001987static int balance(Btree *pBt, MemPage *pPage, BtCursor *pCur){
drh8b2f49b2001-06-08 00:21:52 +00001988 MemPage *pParent; /* The parent of pPage */
drh14acc042001-06-10 19:56:58 +00001989 MemPage *apOld[3]; /* pPage and up to two siblings */
drh8b2f49b2001-06-08 00:21:52 +00001990 Pgno pgnoOld[3]; /* Page numbers for each page in apOld[] */
drh14acc042001-06-10 19:56:58 +00001991 MemPage *apNew[4]; /* pPage and up to 3 siblings after balancing */
1992 Pgno pgnoNew[4]; /* Page numbers for each page in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00001993 int idxDiv[3]; /* Indices of divider cells in pParent */
1994 Cell *apDiv[3]; /* Divider cells in pParent */
1995 int nCell; /* Number of cells in apCell[] */
1996 int nOld; /* Number of pages in apOld[] */
1997 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00001998 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00001999 int i, j, k; /* Loop counters */
2000 int idx; /* Index of pPage in pParent->apCell[] */
2001 int nxDiv; /* Next divider slot in pParent->apCell[] */
2002 int rc; /* The return code */
2003 int iCur; /* apCell[iCur] is the cell of the cursor */
drh5edc3122001-09-13 21:53:09 +00002004 MemPage *pOldCurPage; /* The cursor originally points to this page */
drh8c42ca92001-06-22 19:15:00 +00002005 int totalSize; /* Total bytes for all cells */
drh6019e162001-07-02 17:51:45 +00002006 int subtotal; /* Subtotal of bytes in cells on one page */
2007 int cntNew[4]; /* Index in apCell[] of cell after i-th page */
2008 int szNew[4]; /* Combined size of cells place on i-th page */
drh9ca7d3b2001-06-28 11:50:21 +00002009 MemPage *extraUnref = 0; /* A page that needs to be unref-ed */
drh0d316a42002-08-11 20:10:47 +00002010 Pgno pgno, swabPgno; /* Page number */
drh14acc042001-06-10 19:56:58 +00002011 Cell *apCell[MX_CELL*3+5]; /* All cells from pages being balanceed */
2012 int szCell[MX_CELL*3+5]; /* Local size of all cells */
2013 Cell aTemp[2]; /* Temporary holding area for apDiv[] */
2014 MemPage aOld[3]; /* Temporary copies of pPage and its siblings */
drh8b2f49b2001-06-08 00:21:52 +00002015
drh14acc042001-06-10 19:56:58 +00002016 /*
2017 ** Return without doing any work if pPage is neither overfull nor
2018 ** underfull.
drh8b2f49b2001-06-08 00:21:52 +00002019 */
drh6019e162001-07-02 17:51:45 +00002020 assert( sqlitepager_iswriteable(pPage) );
drha1b351a2001-09-14 16:42:12 +00002021 if( !pPage->isOverfull && pPage->nFree<SQLITE_PAGE_SIZE/2
2022 && pPage->nCell>=2){
drh0d316a42002-08-11 20:10:47 +00002023 relinkCellList(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002024 return SQLITE_OK;
2025 }
2026
2027 /*
drh14acc042001-06-10 19:56:58 +00002028 ** Find the parent of the page to be balanceed.
2029 ** If there is no parent, it means this page is the root page and
drh8b2f49b2001-06-08 00:21:52 +00002030 ** special rules apply.
2031 */
drh14acc042001-06-10 19:56:58 +00002032 pParent = pPage->pParent;
drh8b2f49b2001-06-08 00:21:52 +00002033 if( pParent==0 ){
2034 Pgno pgnoChild;
drh8c42ca92001-06-22 19:15:00 +00002035 MemPage *pChild;
drh7aa128d2002-06-21 13:09:16 +00002036 assert( pPage->isInit );
drh8b2f49b2001-06-08 00:21:52 +00002037 if( pPage->nCell==0 ){
drh14acc042001-06-10 19:56:58 +00002038 if( pPage->u.hdr.rightChild ){
2039 /*
2040 ** The root page is empty. Copy the one child page
drh8b2f49b2001-06-08 00:21:52 +00002041 ** into the root page and return. This reduces the depth
2042 ** of the BTree by one.
2043 */
drh0d316a42002-08-11 20:10:47 +00002044 pgnoChild = SWAB32(pBt, pPage->u.hdr.rightChild);
drh8c42ca92001-06-22 19:15:00 +00002045 rc = sqlitepager_get(pBt->pPager, pgnoChild, (void**)&pChild);
drh8b2f49b2001-06-08 00:21:52 +00002046 if( rc ) return rc;
2047 memcpy(pPage, pChild, SQLITE_PAGE_SIZE);
2048 pPage->isInit = 0;
drh0d316a42002-08-11 20:10:47 +00002049 rc = initPage(pBt, pPage, sqlitepager_pagenumber(pPage), 0);
drh6019e162001-07-02 17:51:45 +00002050 assert( rc==SQLITE_OK );
drh0d316a42002-08-11 20:10:47 +00002051 reparentChildPages(pBt, pPage);
drh5edc3122001-09-13 21:53:09 +00002052 if( pCur && pCur->pPage==pChild ){
2053 sqlitepager_unref(pChild);
2054 pCur->pPage = pPage;
2055 sqlitepager_ref(pPage);
2056 }
drh8b2f49b2001-06-08 00:21:52 +00002057 freePage(pBt, pChild, pgnoChild);
2058 sqlitepager_unref(pChild);
drhefc251d2001-07-01 22:12:01 +00002059 }else{
drh0d316a42002-08-11 20:10:47 +00002060 relinkCellList(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002061 }
2062 return SQLITE_OK;
2063 }
drh14acc042001-06-10 19:56:58 +00002064 if( !pPage->isOverfull ){
drh8b2f49b2001-06-08 00:21:52 +00002065 /* It is OK for the root page to be less than half full.
2066 */
drh0d316a42002-08-11 20:10:47 +00002067 relinkCellList(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002068 return SQLITE_OK;
2069 }
drh14acc042001-06-10 19:56:58 +00002070 /*
2071 ** If we get to here, it means the root page is overfull.
drh8b2f49b2001-06-08 00:21:52 +00002072 ** When this happens, Create a new child page and copy the
2073 ** contents of the root into the child. Then make the root
drh14acc042001-06-10 19:56:58 +00002074 ** page an empty page with rightChild pointing to the new
drh8b2f49b2001-06-08 00:21:52 +00002075 ** child. Then fall thru to the code below which will cause
2076 ** the overfull child page to be split.
2077 */
drh14acc042001-06-10 19:56:58 +00002078 rc = sqlitepager_write(pPage);
2079 if( rc ) return rc;
drhbea00b92002-07-08 10:59:50 +00002080 rc = allocatePage(pBt, &pChild, &pgnoChild, sqlitepager_pagenumber(pPage));
drh8b2f49b2001-06-08 00:21:52 +00002081 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002082 assert( sqlitepager_iswriteable(pChild) );
drh14acc042001-06-10 19:56:58 +00002083 copyPage(pChild, pPage);
2084 pChild->pParent = pPage;
drhdd793422001-06-28 01:54:48 +00002085 sqlitepager_ref(pPage);
drh14acc042001-06-10 19:56:58 +00002086 pChild->isOverfull = 1;
drh5edc3122001-09-13 21:53:09 +00002087 if( pCur && pCur->pPage==pPage ){
2088 sqlitepager_unref(pPage);
drh14acc042001-06-10 19:56:58 +00002089 pCur->pPage = pChild;
drh9ca7d3b2001-06-28 11:50:21 +00002090 }else{
2091 extraUnref = pChild;
drh8b2f49b2001-06-08 00:21:52 +00002092 }
drh0d316a42002-08-11 20:10:47 +00002093 zeroPage(pBt, pPage);
2094 pPage->u.hdr.rightChild = SWAB32(pBt, pgnoChild);
drh8b2f49b2001-06-08 00:21:52 +00002095 pParent = pPage;
2096 pPage = pChild;
drh8b2f49b2001-06-08 00:21:52 +00002097 }
drh6019e162001-07-02 17:51:45 +00002098 rc = sqlitepager_write(pParent);
2099 if( rc ) return rc;
drh7aa128d2002-06-21 13:09:16 +00002100 assert( pParent->isInit );
drh14acc042001-06-10 19:56:58 +00002101
drh8b2f49b2001-06-08 00:21:52 +00002102 /*
drh14acc042001-06-10 19:56:58 +00002103 ** Find the Cell in the parent page whose h.leftChild points back
2104 ** to pPage. The "idx" variable is the index of that cell. If pPage
2105 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00002106 */
2107 idx = -1;
2108 pgno = sqlitepager_pagenumber(pPage);
drh0d316a42002-08-11 20:10:47 +00002109 swabPgno = SWAB32(pBt, pgno);
drh8b2f49b2001-06-08 00:21:52 +00002110 for(i=0; i<pParent->nCell; i++){
drh0d316a42002-08-11 20:10:47 +00002111 if( pParent->apCell[i]->h.leftChild==swabPgno ){
drh8b2f49b2001-06-08 00:21:52 +00002112 idx = i;
2113 break;
2114 }
2115 }
drh0d316a42002-08-11 20:10:47 +00002116 if( idx<0 && pParent->u.hdr.rightChild==swabPgno ){
drhdd793422001-06-28 01:54:48 +00002117 idx = pParent->nCell;
drh8b2f49b2001-06-08 00:21:52 +00002118 }
2119 if( idx<0 ){
drh14acc042001-06-10 19:56:58 +00002120 return SQLITE_CORRUPT;
drh8b2f49b2001-06-08 00:21:52 +00002121 }
2122
2123 /*
drh14acc042001-06-10 19:56:58 +00002124 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00002125 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00002126 */
drh14acc042001-06-10 19:56:58 +00002127 nOld = nNew = 0;
2128 sqlitepager_ref(pParent);
2129
2130 /*
2131 ** Find sibling pages to pPage and the Cells in pParent that divide
2132 ** the siblings. An attempt is made to find one sibling on either
2133 ** side of pPage. Both siblings are taken from one side, however, if
2134 ** pPage is either the first or last child of its parent. If pParent
2135 ** has 3 or fewer children then all children of pParent are taken.
2136 */
2137 if( idx==pParent->nCell ){
2138 nxDiv = idx - 2;
drh8b2f49b2001-06-08 00:21:52 +00002139 }else{
drh14acc042001-06-10 19:56:58 +00002140 nxDiv = idx - 1;
drh8b2f49b2001-06-08 00:21:52 +00002141 }
drh14acc042001-06-10 19:56:58 +00002142 if( nxDiv<0 ) nxDiv = 0;
drh8b2f49b2001-06-08 00:21:52 +00002143 nDiv = 0;
drh14acc042001-06-10 19:56:58 +00002144 for(i=0, k=nxDiv; i<3; i++, k++){
2145 if( k<pParent->nCell ){
2146 idxDiv[i] = k;
2147 apDiv[i] = pParent->apCell[k];
drh8b2f49b2001-06-08 00:21:52 +00002148 nDiv++;
drh0d316a42002-08-11 20:10:47 +00002149 pgnoOld[i] = SWAB32(pBt, apDiv[i]->h.leftChild);
drh14acc042001-06-10 19:56:58 +00002150 }else if( k==pParent->nCell ){
drh0d316a42002-08-11 20:10:47 +00002151 pgnoOld[i] = SWAB32(pBt, pParent->u.hdr.rightChild);
drh14acc042001-06-10 19:56:58 +00002152 }else{
2153 break;
drh8b2f49b2001-06-08 00:21:52 +00002154 }
drh8c42ca92001-06-22 19:15:00 +00002155 rc = sqlitepager_get(pBt->pPager, pgnoOld[i], (void**)&apOld[i]);
drh14acc042001-06-10 19:56:58 +00002156 if( rc ) goto balance_cleanup;
drh0d316a42002-08-11 20:10:47 +00002157 rc = initPage(pBt, apOld[i], pgnoOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00002158 if( rc ) goto balance_cleanup;
drh14acc042001-06-10 19:56:58 +00002159 nOld++;
drh8b2f49b2001-06-08 00:21:52 +00002160 }
2161
2162 /*
drh14acc042001-06-10 19:56:58 +00002163 ** Set iCur to be the index in apCell[] of the cell that the cursor
2164 ** is pointing to. We will need this later on in order to keep the
drh5edc3122001-09-13 21:53:09 +00002165 ** cursor pointing at the same cell. If pCur points to a page that
2166 ** has no involvement with this rebalancing, then set iCur to a large
2167 ** number so that the iCur==j tests always fail in the main cell
2168 ** distribution loop below.
drh14acc042001-06-10 19:56:58 +00002169 */
2170 if( pCur ){
drh5edc3122001-09-13 21:53:09 +00002171 iCur = 0;
2172 for(i=0; i<nOld; i++){
2173 if( pCur->pPage==apOld[i] ){
2174 iCur += pCur->idx;
2175 break;
2176 }
2177 iCur += apOld[i]->nCell;
2178 if( i<nOld-1 && pCur->pPage==pParent && pCur->idx==idxDiv[i] ){
2179 break;
2180 }
2181 iCur++;
drh14acc042001-06-10 19:56:58 +00002182 }
drh5edc3122001-09-13 21:53:09 +00002183 pOldCurPage = pCur->pPage;
drh14acc042001-06-10 19:56:58 +00002184 }
2185
2186 /*
2187 ** Make copies of the content of pPage and its siblings into aOld[].
2188 ** The rest of this function will use data from the copies rather
2189 ** that the original pages since the original pages will be in the
2190 ** process of being overwritten.
2191 */
2192 for(i=0; i<nOld; i++){
2193 copyPage(&aOld[i], apOld[i]);
drh14acc042001-06-10 19:56:58 +00002194 }
2195
2196 /*
2197 ** Load pointers to all cells on sibling pages and the divider cells
2198 ** into the local apCell[] array. Make copies of the divider cells
2199 ** into aTemp[] and remove the the divider Cells from pParent.
drh8b2f49b2001-06-08 00:21:52 +00002200 */
2201 nCell = 0;
2202 for(i=0; i<nOld; i++){
drh6b308672002-07-08 02:16:37 +00002203 MemPage *pOld = &aOld[i];
drh8b2f49b2001-06-08 00:21:52 +00002204 for(j=0; j<pOld->nCell; j++){
drh14acc042001-06-10 19:56:58 +00002205 apCell[nCell] = pOld->apCell[j];
drh0d316a42002-08-11 20:10:47 +00002206 szCell[nCell] = cellSize(pBt, apCell[nCell]);
drh14acc042001-06-10 19:56:58 +00002207 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00002208 }
2209 if( i<nOld-1 ){
drh0d316a42002-08-11 20:10:47 +00002210 szCell[nCell] = cellSize(pBt, apDiv[i]);
drh8c42ca92001-06-22 19:15:00 +00002211 memcpy(&aTemp[i], apDiv[i], szCell[nCell]);
drh14acc042001-06-10 19:56:58 +00002212 apCell[nCell] = &aTemp[i];
drh0d316a42002-08-11 20:10:47 +00002213 dropCell(pBt, pParent, nxDiv, szCell[nCell]);
2214 assert( SWAB32(pBt, apCell[nCell]->h.leftChild)==pgnoOld[i] );
drh14acc042001-06-10 19:56:58 +00002215 apCell[nCell]->h.leftChild = pOld->u.hdr.rightChild;
2216 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00002217 }
2218 }
2219
2220 /*
drh6019e162001-07-02 17:51:45 +00002221 ** Figure out the number of pages needed to hold all nCell cells.
2222 ** Store this number in "k". Also compute szNew[] which is the total
2223 ** size of all cells on the i-th page and cntNew[] which is the index
2224 ** in apCell[] of the cell that divides path i from path i+1.
2225 ** cntNew[k] should equal nCell.
2226 **
2227 ** This little patch of code is critical for keeping the tree
2228 ** balanced.
drh8b2f49b2001-06-08 00:21:52 +00002229 */
2230 totalSize = 0;
2231 for(i=0; i<nCell; i++){
drh14acc042001-06-10 19:56:58 +00002232 totalSize += szCell[i];
drh8b2f49b2001-06-08 00:21:52 +00002233 }
drh6019e162001-07-02 17:51:45 +00002234 for(subtotal=k=i=0; i<nCell; i++){
2235 subtotal += szCell[i];
2236 if( subtotal > USABLE_SPACE ){
2237 szNew[k] = subtotal - szCell[i];
2238 cntNew[k] = i;
2239 subtotal = 0;
2240 k++;
2241 }
2242 }
2243 szNew[k] = subtotal;
2244 cntNew[k] = nCell;
2245 k++;
2246 for(i=k-1; i>0; i--){
2247 while( szNew[i]<USABLE_SPACE/2 ){
2248 cntNew[i-1]--;
2249 assert( cntNew[i-1]>0 );
2250 szNew[i] += szCell[cntNew[i-1]];
2251 szNew[i-1] -= szCell[cntNew[i-1]-1];
2252 }
2253 }
2254 assert( cntNew[0]>0 );
drh8b2f49b2001-06-08 00:21:52 +00002255
2256 /*
drh6b308672002-07-08 02:16:37 +00002257 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00002258 */
drh14acc042001-06-10 19:56:58 +00002259 for(i=0; i<k; i++){
drh6b308672002-07-08 02:16:37 +00002260 if( i<nOld ){
2261 apNew[i] = apOld[i];
2262 pgnoNew[i] = pgnoOld[i];
2263 apOld[i] = 0;
2264 sqlitepager_write(apNew[i]);
2265 }else{
drhbea00b92002-07-08 10:59:50 +00002266 rc = allocatePage(pBt, &apNew[i], &pgnoNew[i], pgnoNew[i-1]);
drh6b308672002-07-08 02:16:37 +00002267 if( rc ) goto balance_cleanup;
2268 }
drh14acc042001-06-10 19:56:58 +00002269 nNew++;
drh0d316a42002-08-11 20:10:47 +00002270 zeroPage(pBt, apNew[i]);
drh6019e162001-07-02 17:51:45 +00002271 apNew[i]->isInit = 1;
drh8b2f49b2001-06-08 00:21:52 +00002272 }
2273
drh6b308672002-07-08 02:16:37 +00002274 /* Free any old pages that were not reused as new pages.
2275 */
2276 while( i<nOld ){
2277 rc = freePage(pBt, apOld[i], pgnoOld[i]);
2278 if( rc ) goto balance_cleanup;
2279 sqlitepager_unref(apOld[i]);
2280 apOld[i] = 0;
2281 i++;
2282 }
2283
drh8b2f49b2001-06-08 00:21:52 +00002284 /*
drhf9ffac92002-03-02 19:00:31 +00002285 ** Put the new pages in accending order. This helps to
2286 ** keep entries in the disk file in order so that a scan
2287 ** of the table is a linear scan through the file. That
2288 ** in turn helps the operating system to deliver pages
2289 ** from the disk more rapidly.
2290 **
2291 ** An O(n^2) insertion sort algorithm is used, but since
2292 ** n is never more than 3, that should not be a problem.
2293 **
2294 ** This one optimization makes the database about 25%
2295 ** faster for large insertions and deletions.
2296 */
2297 for(i=0; i<k-1; i++){
2298 int minV = pgnoNew[i];
2299 int minI = i;
2300 for(j=i+1; j<k; j++){
2301 if( pgnoNew[j]<minV ){
2302 minI = j;
2303 minV = pgnoNew[j];
2304 }
2305 }
2306 if( minI>i ){
2307 int t;
2308 MemPage *pT;
2309 t = pgnoNew[i];
2310 pT = apNew[i];
2311 pgnoNew[i] = pgnoNew[minI];
2312 apNew[i] = apNew[minI];
2313 pgnoNew[minI] = t;
2314 apNew[minI] = pT;
2315 }
2316 }
2317
2318 /*
drh14acc042001-06-10 19:56:58 +00002319 ** Evenly distribute the data in apCell[] across the new pages.
2320 ** Insert divider cells into pParent as necessary.
2321 */
2322 j = 0;
2323 for(i=0; i<nNew; i++){
2324 MemPage *pNew = apNew[i];
drh6019e162001-07-02 17:51:45 +00002325 while( j<cntNew[i] ){
2326 assert( pNew->nFree>=szCell[j] );
drh14acc042001-06-10 19:56:58 +00002327 if( pCur && iCur==j ){ pCur->pPage = pNew; pCur->idx = pNew->nCell; }
drh0d316a42002-08-11 20:10:47 +00002328 insertCell(pBt, pNew, pNew->nCell, apCell[j], szCell[j]);
drh14acc042001-06-10 19:56:58 +00002329 j++;
2330 }
drh6019e162001-07-02 17:51:45 +00002331 assert( pNew->nCell>0 );
drh14acc042001-06-10 19:56:58 +00002332 assert( !pNew->isOverfull );
drh0d316a42002-08-11 20:10:47 +00002333 relinkCellList(pBt, pNew);
drh14acc042001-06-10 19:56:58 +00002334 if( i<nNew-1 && j<nCell ){
2335 pNew->u.hdr.rightChild = apCell[j]->h.leftChild;
drh0d316a42002-08-11 20:10:47 +00002336 apCell[j]->h.leftChild = SWAB32(pBt, pgnoNew[i]);
drh14acc042001-06-10 19:56:58 +00002337 if( pCur && iCur==j ){ pCur->pPage = pParent; pCur->idx = nxDiv; }
drh0d316a42002-08-11 20:10:47 +00002338 insertCell(pBt, pParent, nxDiv, apCell[j], szCell[j]);
drh14acc042001-06-10 19:56:58 +00002339 j++;
2340 nxDiv++;
2341 }
2342 }
drh6019e162001-07-02 17:51:45 +00002343 assert( j==nCell );
drh6b308672002-07-08 02:16:37 +00002344 apNew[nNew-1]->u.hdr.rightChild = aOld[nOld-1].u.hdr.rightChild;
drh14acc042001-06-10 19:56:58 +00002345 if( nxDiv==pParent->nCell ){
drh0d316a42002-08-11 20:10:47 +00002346 pParent->u.hdr.rightChild = SWAB32(pBt, pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00002347 }else{
drh0d316a42002-08-11 20:10:47 +00002348 pParent->apCell[nxDiv]->h.leftChild = SWAB32(pBt, pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00002349 }
2350 if( pCur ){
drh3fc190c2001-09-14 03:24:23 +00002351 if( j<=iCur && pCur->pPage==pParent && pCur->idx>idxDiv[nOld-1] ){
2352 assert( pCur->pPage==pOldCurPage );
2353 pCur->idx += nNew - nOld;
2354 }else{
2355 assert( pOldCurPage!=0 );
2356 sqlitepager_ref(pCur->pPage);
2357 sqlitepager_unref(pOldCurPage);
2358 }
drh14acc042001-06-10 19:56:58 +00002359 }
2360
2361 /*
2362 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00002363 */
2364 for(i=0; i<nNew; i++){
drh0d316a42002-08-11 20:10:47 +00002365 reparentChildPages(pBt, apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002366 }
drh0d316a42002-08-11 20:10:47 +00002367 reparentChildPages(pBt, pParent);
drh8b2f49b2001-06-08 00:21:52 +00002368
2369 /*
drh14acc042001-06-10 19:56:58 +00002370 ** balance the parent page.
drh8b2f49b2001-06-08 00:21:52 +00002371 */
drh5edc3122001-09-13 21:53:09 +00002372 rc = balance(pBt, pParent, pCur);
drh8b2f49b2001-06-08 00:21:52 +00002373
2374 /*
drh14acc042001-06-10 19:56:58 +00002375 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00002376 */
drh14acc042001-06-10 19:56:58 +00002377balance_cleanup:
drh9ca7d3b2001-06-28 11:50:21 +00002378 if( extraUnref ){
2379 sqlitepager_unref(extraUnref);
2380 }
drh8b2f49b2001-06-08 00:21:52 +00002381 for(i=0; i<nOld; i++){
drh6b308672002-07-08 02:16:37 +00002382 if( apOld[i]!=0 && apOld[i]!=&aOld[i] ) sqlitepager_unref(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00002383 }
drh14acc042001-06-10 19:56:58 +00002384 for(i=0; i<nNew; i++){
2385 sqlitepager_unref(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002386 }
drh14acc042001-06-10 19:56:58 +00002387 if( pCur && pCur->pPage==0 ){
2388 pCur->pPage = pParent;
2389 pCur->idx = 0;
2390 }else{
2391 sqlitepager_unref(pParent);
drh8b2f49b2001-06-08 00:21:52 +00002392 }
2393 return rc;
2394}
2395
2396/*
drh3b7511c2001-05-26 13:15:44 +00002397** Insert a new record into the BTree. The key is given by (pKey,nKey)
2398** and the data is given by (pData,nData). The cursor is used only to
2399** define what database the record should be inserted into. The cursor
drh14acc042001-06-10 19:56:58 +00002400** is left pointing at the new record.
drh3b7511c2001-05-26 13:15:44 +00002401*/
2402int sqliteBtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00002403 BtCursor *pCur, /* Insert data into the table of this cursor */
drhbe0072d2001-09-13 14:46:09 +00002404 const void *pKey, int nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00002405 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00002406){
2407 Cell newCell;
2408 int rc;
2409 int loc;
drh14acc042001-06-10 19:56:58 +00002410 int szNew;
drh3b7511c2001-05-26 13:15:44 +00002411 MemPage *pPage;
2412 Btree *pBt = pCur->pBt;
2413
drhecdc7532001-09-23 02:35:53 +00002414 if( pCur->pPage==0 ){
2415 return SQLITE_ABORT; /* A rollback destroyed this cursor */
2416 }
drh5edc3122001-09-13 21:53:09 +00002417 if( !pCur->pBt->inTrans || nKey+nData==0 ){
drh8b2f49b2001-06-08 00:21:52 +00002418 return SQLITE_ERROR; /* Must start a transaction first */
2419 }
drhecdc7532001-09-23 02:35:53 +00002420 if( !pCur->wrFlag ){
2421 return SQLITE_PERM; /* Cursor not open for writing */
2422 }
drh14acc042001-06-10 19:56:58 +00002423 rc = sqliteBtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00002424 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002425 pPage = pCur->pPage;
drh7aa128d2002-06-21 13:09:16 +00002426 assert( pPage->isInit );
drh14acc042001-06-10 19:56:58 +00002427 rc = sqlitepager_write(pPage);
drhbd03cae2001-06-02 02:40:57 +00002428 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00002429 rc = fillInCell(pBt, &newCell, pKey, nKey, pData, nData);
2430 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002431 szNew = cellSize(pBt, &newCell);
drh3b7511c2001-05-26 13:15:44 +00002432 if( loc==0 ){
drh14acc042001-06-10 19:56:58 +00002433 newCell.h.leftChild = pPage->apCell[pCur->idx]->h.leftChild;
2434 rc = clearCell(pBt, pPage->apCell[pCur->idx]);
drh5e2f8b92001-05-28 00:41:15 +00002435 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002436 dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pPage->apCell[pCur->idx]));
drh7c717f72001-06-24 20:39:41 +00002437 }else if( loc<0 && pPage->nCell>0 ){
drh14acc042001-06-10 19:56:58 +00002438 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
2439 pCur->idx++;
2440 }else{
2441 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
drh3b7511c2001-05-26 13:15:44 +00002442 }
drh0d316a42002-08-11 20:10:47 +00002443 insertCell(pBt, pPage, pCur->idx, &newCell, szNew);
drh14acc042001-06-10 19:56:58 +00002444 rc = balance(pCur->pBt, pPage, pCur);
drh3fc190c2001-09-14 03:24:23 +00002445 /* sqliteBtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
2446 /* fflush(stdout); */
drh5e2f8b92001-05-28 00:41:15 +00002447 return rc;
2448}
2449
2450/*
drhbd03cae2001-06-02 02:40:57 +00002451** Delete the entry that the cursor is pointing to.
drh5e2f8b92001-05-28 00:41:15 +00002452**
drhbd03cae2001-06-02 02:40:57 +00002453** The cursor is left pointing at either the next or the previous
2454** entry. If the cursor is left pointing to the next entry, then
2455** the pCur->bSkipNext flag is set which forces the next call to
2456** sqliteBtreeNext() to be a no-op. That way, you can always call
2457** sqliteBtreeNext() after a delete and the cursor will be left
2458** pointing to the first entry after the deleted entry.
drh3b7511c2001-05-26 13:15:44 +00002459*/
2460int sqliteBtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00002461 MemPage *pPage = pCur->pPage;
2462 Cell *pCell;
2463 int rc;
drh8c42ca92001-06-22 19:15:00 +00002464 Pgno pgnoChild;
drh0d316a42002-08-11 20:10:47 +00002465 Btree *pBt = pCur->pBt;
drh8b2f49b2001-06-08 00:21:52 +00002466
drh7aa128d2002-06-21 13:09:16 +00002467 assert( pPage->isInit );
drhecdc7532001-09-23 02:35:53 +00002468 if( pCur->pPage==0 ){
2469 return SQLITE_ABORT; /* A rollback destroyed this cursor */
2470 }
drh8b2f49b2001-06-08 00:21:52 +00002471 if( !pCur->pBt->inTrans ){
2472 return SQLITE_ERROR; /* Must start a transaction first */
2473 }
drhbd03cae2001-06-02 02:40:57 +00002474 if( pCur->idx >= pPage->nCell ){
2475 return SQLITE_ERROR; /* The cursor is not pointing to anything */
2476 }
drhecdc7532001-09-23 02:35:53 +00002477 if( !pCur->wrFlag ){
2478 return SQLITE_PERM; /* Did not open this cursor for writing */
2479 }
drhbd03cae2001-06-02 02:40:57 +00002480 rc = sqlitepager_write(pPage);
2481 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002482 pCell = pPage->apCell[pCur->idx];
drh0d316a42002-08-11 20:10:47 +00002483 pgnoChild = SWAB32(pBt, pCell->h.leftChild);
2484 clearCell(pBt, pCell);
drh14acc042001-06-10 19:56:58 +00002485 if( pgnoChild ){
2486 /*
drh5e00f6c2001-09-13 13:46:56 +00002487 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00002488 ** do something we will leave a hole on an internal page.
2489 ** We have to fill the hole by moving in a cell from a leaf. The
2490 ** next Cell after the one to be deleted is guaranteed to exist and
2491 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00002492 */
drh14acc042001-06-10 19:56:58 +00002493 BtCursor leafCur;
2494 Cell *pNext;
2495 int szNext;
2496 getTempCursor(pCur, &leafCur);
2497 rc = sqliteBtreeNext(&leafCur, 0);
2498 if( rc!=SQLITE_OK ){
2499 return SQLITE_CORRUPT;
drh5e2f8b92001-05-28 00:41:15 +00002500 }
drh6019e162001-07-02 17:51:45 +00002501 rc = sqlitepager_write(leafCur.pPage);
2502 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002503 dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pCell));
drh8c42ca92001-06-22 19:15:00 +00002504 pNext = leafCur.pPage->apCell[leafCur.idx];
drh0d316a42002-08-11 20:10:47 +00002505 szNext = cellSize(pBt, pNext);
2506 pNext->h.leftChild = SWAB32(pBt, pgnoChild);
2507 insertCell(pBt, pPage, pCur->idx, pNext, szNext);
2508 rc = balance(pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002509 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002510 pCur->bSkipNext = 1;
drh0d316a42002-08-11 20:10:47 +00002511 dropCell(pBt, leafCur.pPage, leafCur.idx, szNext);
2512 rc = balance(pBt, leafCur.pPage, pCur);
drh8c42ca92001-06-22 19:15:00 +00002513 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00002514 }else{
drh0d316a42002-08-11 20:10:47 +00002515 dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pCell));
drh5edc3122001-09-13 21:53:09 +00002516 if( pCur->idx>=pPage->nCell ){
2517 pCur->idx = pPage->nCell-1;
drhf5bf0a72001-11-23 00:24:12 +00002518 if( pCur->idx<0 ){
2519 pCur->idx = 0;
2520 pCur->bSkipNext = 1;
2521 }else{
2522 pCur->bSkipNext = 0;
2523 }
drh6019e162001-07-02 17:51:45 +00002524 }else{
2525 pCur->bSkipNext = 1;
2526 }
drh0d316a42002-08-11 20:10:47 +00002527 rc = balance(pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002528 }
drh5e2f8b92001-05-28 00:41:15 +00002529 return rc;
drh3b7511c2001-05-26 13:15:44 +00002530}
drh8b2f49b2001-06-08 00:21:52 +00002531
2532/*
drhc6b52df2002-01-04 03:09:29 +00002533** Create a new BTree table. Write into *piTable the page
2534** number for the root page of the new table.
2535**
2536** In the current implementation, BTree tables and BTree indices are the
2537** the same. But in the future, we may change this so that BTree tables
2538** are restricted to having a 4-byte integer key and arbitrary data and
2539** BTree indices are restricted to having an arbitrary key and no data.
drh8b2f49b2001-06-08 00:21:52 +00002540*/
2541int sqliteBtreeCreateTable(Btree *pBt, int *piTable){
2542 MemPage *pRoot;
2543 Pgno pgnoRoot;
2544 int rc;
2545 if( !pBt->inTrans ){
2546 return SQLITE_ERROR; /* Must start a transaction first */
2547 }
drh5df72a52002-06-06 23:16:05 +00002548 if( pBt->readOnly ){
2549 return SQLITE_READONLY;
2550 }
drhbea00b92002-07-08 10:59:50 +00002551 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 0);
drh8b2f49b2001-06-08 00:21:52 +00002552 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002553 assert( sqlitepager_iswriteable(pRoot) );
drh0d316a42002-08-11 20:10:47 +00002554 zeroPage(pBt, pRoot);
drh8b2f49b2001-06-08 00:21:52 +00002555 sqlitepager_unref(pRoot);
2556 *piTable = (int)pgnoRoot;
2557 return SQLITE_OK;
2558}
2559
2560/*
drhc6b52df2002-01-04 03:09:29 +00002561** Create a new BTree index. Write into *piTable the page
2562** number for the root page of the new index.
2563**
2564** In the current implementation, BTree tables and BTree indices are the
2565** the same. But in the future, we may change this so that BTree tables
2566** are restricted to having a 4-byte integer key and arbitrary data and
2567** BTree indices are restricted to having an arbitrary key and no data.
2568*/
2569int sqliteBtreeCreateIndex(Btree *pBt, int *piIndex){
drh5df72a52002-06-06 23:16:05 +00002570 return sqliteBtreeCreateTable(pBt, piIndex);
drhc6b52df2002-01-04 03:09:29 +00002571}
2572
2573/*
drh8b2f49b2001-06-08 00:21:52 +00002574** Erase the given database page and all its children. Return
2575** the page to the freelist.
2576*/
drh2aa679f2001-06-25 02:11:07 +00002577static int clearDatabasePage(Btree *pBt, Pgno pgno, int freePageFlag){
drh8b2f49b2001-06-08 00:21:52 +00002578 MemPage *pPage;
2579 int rc;
drh8b2f49b2001-06-08 00:21:52 +00002580 Cell *pCell;
2581 int idx;
2582
drh8c42ca92001-06-22 19:15:00 +00002583 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pPage);
drh8b2f49b2001-06-08 00:21:52 +00002584 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002585 rc = sqlitepager_write(pPage);
2586 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002587 rc = initPage(pBt, pPage, pgno, 0);
drh7aa128d2002-06-21 13:09:16 +00002588 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002589 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh8b2f49b2001-06-08 00:21:52 +00002590 while( idx>0 ){
drh14acc042001-06-10 19:56:58 +00002591 pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +00002592 idx = SWAB16(pBt, pCell->h.iNext);
drh8b2f49b2001-06-08 00:21:52 +00002593 if( pCell->h.leftChild ){
drh0d316a42002-08-11 20:10:47 +00002594 rc = clearDatabasePage(pBt, SWAB32(pBt, pCell->h.leftChild), 1);
drh8b2f49b2001-06-08 00:21:52 +00002595 if( rc ) return rc;
2596 }
drh8c42ca92001-06-22 19:15:00 +00002597 rc = clearCell(pBt, pCell);
drh8b2f49b2001-06-08 00:21:52 +00002598 if( rc ) return rc;
2599 }
drh2aa679f2001-06-25 02:11:07 +00002600 if( pPage->u.hdr.rightChild ){
drh0d316a42002-08-11 20:10:47 +00002601 rc = clearDatabasePage(pBt, SWAB32(pBt, pPage->u.hdr.rightChild), 1);
drh2aa679f2001-06-25 02:11:07 +00002602 if( rc ) return rc;
2603 }
2604 if( freePageFlag ){
2605 rc = freePage(pBt, pPage, pgno);
2606 }else{
drh0d316a42002-08-11 20:10:47 +00002607 zeroPage(pBt, pPage);
drh2aa679f2001-06-25 02:11:07 +00002608 }
drhdd793422001-06-28 01:54:48 +00002609 sqlitepager_unref(pPage);
drh2aa679f2001-06-25 02:11:07 +00002610 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002611}
2612
2613/*
2614** Delete all information from a single table in the database.
2615*/
2616int sqliteBtreeClearTable(Btree *pBt, int iTable){
2617 int rc;
drh5a2c2c22001-11-21 02:21:11 +00002618 ptr nLock;
drh8b2f49b2001-06-08 00:21:52 +00002619 if( !pBt->inTrans ){
2620 return SQLITE_ERROR; /* Must start a transaction first */
2621 }
drh5df72a52002-06-06 23:16:05 +00002622 if( pBt->readOnly ){
2623 return SQLITE_READONLY;
2624 }
drh5a2c2c22001-11-21 02:21:11 +00002625 nLock = (ptr)sqliteHashFind(&pBt->locks, 0, iTable);
drhecdc7532001-09-23 02:35:53 +00002626 if( nLock ){
2627 return SQLITE_LOCKED;
2628 }
drh2aa679f2001-06-25 02:11:07 +00002629 rc = clearDatabasePage(pBt, (Pgno)iTable, 0);
drh8b2f49b2001-06-08 00:21:52 +00002630 if( rc ){
2631 sqliteBtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00002632 }
drh8c42ca92001-06-22 19:15:00 +00002633 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002634}
2635
2636/*
2637** Erase all information in a table and add the root of the table to
2638** the freelist. Except, the root of the principle table (the one on
2639** page 2) is never added to the freelist.
2640*/
2641int sqliteBtreeDropTable(Btree *pBt, int iTable){
2642 int rc;
2643 MemPage *pPage;
2644 if( !pBt->inTrans ){
2645 return SQLITE_ERROR; /* Must start a transaction first */
2646 }
drh5df72a52002-06-06 23:16:05 +00002647 if( pBt->readOnly ){
2648 return SQLITE_READONLY;
2649 }
drh8c42ca92001-06-22 19:15:00 +00002650 rc = sqlitepager_get(pBt->pPager, (Pgno)iTable, (void**)&pPage);
drh2aa679f2001-06-25 02:11:07 +00002651 if( rc ) return rc;
2652 rc = sqliteBtreeClearTable(pBt, iTable);
2653 if( rc ) return rc;
2654 if( iTable>2 ){
2655 rc = freePage(pBt, pPage, iTable);
2656 }else{
drh0d316a42002-08-11 20:10:47 +00002657 zeroPage(pBt, pPage);
drh8b2f49b2001-06-08 00:21:52 +00002658 }
drhdd793422001-06-28 01:54:48 +00002659 sqlitepager_unref(pPage);
drh8b2f49b2001-06-08 00:21:52 +00002660 return rc;
2661}
2662
2663/*
2664** Read the meta-information out of a database file.
2665*/
2666int sqliteBtreeGetMeta(Btree *pBt, int *aMeta){
2667 PageOne *pP1;
2668 int rc;
drh0d316a42002-08-11 20:10:47 +00002669 int i;
drh8b2f49b2001-06-08 00:21:52 +00002670
drh8c42ca92001-06-22 19:15:00 +00002671 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00002672 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002673 aMeta[0] = SWAB32(pBt, pP1->nFree);
2674 for(i=0; i<sizeof(pP1->aMeta)/sizeof(pP1->aMeta[0]); i++){
2675 aMeta[i+1] = SWAB32(pBt, pP1->aMeta[i]);
2676 }
drh8b2f49b2001-06-08 00:21:52 +00002677 sqlitepager_unref(pP1);
2678 return SQLITE_OK;
2679}
2680
2681/*
2682** Write meta-information back into the database.
2683*/
2684int sqliteBtreeUpdateMeta(Btree *pBt, int *aMeta){
2685 PageOne *pP1;
drh0d316a42002-08-11 20:10:47 +00002686 int rc, i;
drh8b2f49b2001-06-08 00:21:52 +00002687 if( !pBt->inTrans ){
2688 return SQLITE_ERROR; /* Must start a transaction first */
2689 }
drh5df72a52002-06-06 23:16:05 +00002690 if( pBt->readOnly ){
2691 return SQLITE_READONLY;
2692 }
drh8b2f49b2001-06-08 00:21:52 +00002693 pP1 = pBt->page1;
2694 rc = sqlitepager_write(pP1);
drh9adf9ac2002-05-15 11:44:13 +00002695 if( rc ) return rc;
drh0d316a42002-08-11 20:10:47 +00002696 for(i=0; i<sizeof(pP1->aMeta)/sizeof(pP1->aMeta[0]); i++){
2697 pP1->aMeta[i] = SWAB32(pBt, aMeta[i+1]);
2698 }
drh8b2f49b2001-06-08 00:21:52 +00002699 return SQLITE_OK;
2700}
drh8c42ca92001-06-22 19:15:00 +00002701
drh5eddca62001-06-30 21:53:53 +00002702/******************************************************************************
2703** The complete implementation of the BTree subsystem is above this line.
2704** All the code the follows is for testing and troubleshooting the BTree
2705** subsystem. None of the code that follows is used during normal operation.
drh5eddca62001-06-30 21:53:53 +00002706******************************************************************************/
drh5eddca62001-06-30 21:53:53 +00002707
drh8c42ca92001-06-22 19:15:00 +00002708/*
2709** Print a disassembly of the given page on standard output. This routine
2710** is used for debugging and testing only.
2711*/
drhaaab5722002-02-19 13:39:21 +00002712#ifdef SQLITE_TEST
drh6019e162001-07-02 17:51:45 +00002713int sqliteBtreePageDump(Btree *pBt, int pgno, int recursive){
drh8c42ca92001-06-22 19:15:00 +00002714 int rc;
2715 MemPage *pPage;
2716 int i, j;
2717 int nFree;
2718 u16 idx;
2719 char range[20];
2720 unsigned char payload[20];
2721 rc = sqlitepager_get(pBt->pPager, (Pgno)pgno, (void**)&pPage);
2722 if( rc ){
2723 return rc;
2724 }
drh6019e162001-07-02 17:51:45 +00002725 if( recursive ) printf("PAGE %d:\n", pgno);
drh8c42ca92001-06-22 19:15:00 +00002726 i = 0;
drh0d316a42002-08-11 20:10:47 +00002727 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh8c42ca92001-06-22 19:15:00 +00002728 while( idx>0 && idx<=SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2729 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +00002730 int sz = cellSize(pBt, pCell);
drh8c42ca92001-06-22 19:15:00 +00002731 sprintf(range,"%d..%d", idx, idx+sz-1);
drh0d316a42002-08-11 20:10:47 +00002732 sz = NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h);
drh8c42ca92001-06-22 19:15:00 +00002733 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
2734 memcpy(payload, pCell->aPayload, sz);
2735 for(j=0; j<sz; j++){
2736 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
2737 }
2738 payload[sz] = 0;
2739 printf(
drh6019e162001-07-02 17:51:45 +00002740 "cell %2d: i=%-10s chld=%-4d nk=%-4d nd=%-4d payload=%s\n",
drh0d316a42002-08-11 20:10:47 +00002741 i, range, (int)pCell->h.leftChild,
2742 NKEY(pBt, pCell->h), NDATA(pBt, pCell->h),
drh2aa679f2001-06-25 02:11:07 +00002743 payload
drh8c42ca92001-06-22 19:15:00 +00002744 );
drh6019e162001-07-02 17:51:45 +00002745 if( pPage->isInit && pPage->apCell[i]!=pCell ){
drh2aa679f2001-06-25 02:11:07 +00002746 printf("**** apCell[%d] does not match on prior entry ****\n", i);
2747 }
drh7c717f72001-06-24 20:39:41 +00002748 i++;
drh0d316a42002-08-11 20:10:47 +00002749 idx = SWAB16(pBt, pCell->h.iNext);
drh8c42ca92001-06-22 19:15:00 +00002750 }
2751 if( idx!=0 ){
2752 printf("ERROR: next cell index out of range: %d\n", idx);
2753 }
drh0d316a42002-08-11 20:10:47 +00002754 printf("right_child: %d\n", SWAB32(pBt, pPage->u.hdr.rightChild));
drh8c42ca92001-06-22 19:15:00 +00002755 nFree = 0;
2756 i = 0;
drh0d316a42002-08-11 20:10:47 +00002757 idx = SWAB16(pBt, pPage->u.hdr.firstFree);
drh8c42ca92001-06-22 19:15:00 +00002758 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2759 FreeBlk *p = (FreeBlk*)&pPage->u.aDisk[idx];
2760 sprintf(range,"%d..%d", idx, idx+p->iSize-1);
drh0d316a42002-08-11 20:10:47 +00002761 nFree += SWAB16(pBt, p->iSize);
drh8c42ca92001-06-22 19:15:00 +00002762 printf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
drh0d316a42002-08-11 20:10:47 +00002763 i, range, SWAB16(pBt, p->iSize), nFree);
2764 idx = SWAB16(pBt, p->iNext);
drh2aa679f2001-06-25 02:11:07 +00002765 i++;
drh8c42ca92001-06-22 19:15:00 +00002766 }
2767 if( idx!=0 ){
2768 printf("ERROR: next freeblock index out of range: %d\n", idx);
2769 }
drh6019e162001-07-02 17:51:45 +00002770 if( recursive && pPage->u.hdr.rightChild!=0 ){
drh0d316a42002-08-11 20:10:47 +00002771 idx = SWAB16(pBt, pPage->u.hdr.firstCell);
drh6019e162001-07-02 17:51:45 +00002772 while( idx>0 && idx<SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2773 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
drh0d316a42002-08-11 20:10:47 +00002774 sqliteBtreePageDump(pBt, SWAB32(pBt, pCell->h.leftChild), 1);
2775 idx = SWAB16(pBt, pCell->h.iNext);
drh6019e162001-07-02 17:51:45 +00002776 }
drh0d316a42002-08-11 20:10:47 +00002777 sqliteBtreePageDump(pBt, SWAB32(pBt, pPage->u.hdr.rightChild), 1);
drh6019e162001-07-02 17:51:45 +00002778 }
drh8c42ca92001-06-22 19:15:00 +00002779 sqlitepager_unref(pPage);
2780 return SQLITE_OK;
2781}
drhaaab5722002-02-19 13:39:21 +00002782#endif
drh8c42ca92001-06-22 19:15:00 +00002783
drhaaab5722002-02-19 13:39:21 +00002784#ifdef SQLITE_TEST
drh8c42ca92001-06-22 19:15:00 +00002785/*
drh2aa679f2001-06-25 02:11:07 +00002786** Fill aResult[] with information about the entry and page that the
2787** cursor is pointing to.
2788**
2789** aResult[0] = The page number
2790** aResult[1] = The entry number
2791** aResult[2] = Total number of entries on this page
2792** aResult[3] = Size of this entry
2793** aResult[4] = Number of free bytes on this page
2794** aResult[5] = Number of free blocks on the page
2795** aResult[6] = Page number of the left child of this entry
2796** aResult[7] = Page number of the right child for the whole page
drh5eddca62001-06-30 21:53:53 +00002797**
2798** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00002799*/
2800int sqliteBtreeCursorDump(BtCursor *pCur, int *aResult){
drh2aa679f2001-06-25 02:11:07 +00002801 int cnt, idx;
2802 MemPage *pPage = pCur->pPage;
drh0d316a42002-08-11 20:10:47 +00002803 Btree *pBt = pCur->pBt;
drh2aa679f2001-06-25 02:11:07 +00002804 aResult[0] = sqlitepager_pagenumber(pPage);
drh8c42ca92001-06-22 19:15:00 +00002805 aResult[1] = pCur->idx;
drh2aa679f2001-06-25 02:11:07 +00002806 aResult[2] = pPage->nCell;
2807 if( pCur->idx>=0 && pCur->idx<pPage->nCell ){
drh0d316a42002-08-11 20:10:47 +00002808 aResult[3] = cellSize(pBt, pPage->apCell[pCur->idx]);
2809 aResult[6] = SWAB32(pBt, pPage->apCell[pCur->idx]->h.leftChild);
drh2aa679f2001-06-25 02:11:07 +00002810 }else{
2811 aResult[3] = 0;
2812 aResult[6] = 0;
2813 }
2814 aResult[4] = pPage->nFree;
2815 cnt = 0;
drh0d316a42002-08-11 20:10:47 +00002816 idx = SWAB16(pBt, pPage->u.hdr.firstFree);
drh2aa679f2001-06-25 02:11:07 +00002817 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2818 cnt++;
drh0d316a42002-08-11 20:10:47 +00002819 idx = SWAB16(pBt, ((FreeBlk*)&pPage->u.aDisk[idx])->iNext);
drh2aa679f2001-06-25 02:11:07 +00002820 }
2821 aResult[5] = cnt;
drh0d316a42002-08-11 20:10:47 +00002822 aResult[7] = SWAB32(pBt, pPage->u.hdr.rightChild);
drh8c42ca92001-06-22 19:15:00 +00002823 return SQLITE_OK;
2824}
drhaaab5722002-02-19 13:39:21 +00002825#endif
drhdd793422001-06-28 01:54:48 +00002826
drhaaab5722002-02-19 13:39:21 +00002827#ifdef SQLITE_TEST
drhdd793422001-06-28 01:54:48 +00002828/*
drh5eddca62001-06-30 21:53:53 +00002829** Return the pager associated with a BTree. This routine is used for
2830** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00002831*/
2832Pager *sqliteBtreePager(Btree *pBt){
2833 return pBt->pPager;
2834}
drhaaab5722002-02-19 13:39:21 +00002835#endif
drh5eddca62001-06-30 21:53:53 +00002836
2837/*
2838** This structure is passed around through all the sanity checking routines
2839** in order to keep track of some global state information.
2840*/
drhaaab5722002-02-19 13:39:21 +00002841typedef struct IntegrityCk IntegrityCk;
2842struct IntegrityCk {
drh100569d2001-10-02 13:01:48 +00002843 Btree *pBt; /* The tree being checked out */
2844 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
2845 int nPage; /* Number of pages in the database */
2846 int *anRef; /* Number of times each page is referenced */
2847 int nTreePage; /* Number of BTree pages */
2848 int nByte; /* Number of bytes of data stored on BTree pages */
2849 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00002850};
2851
2852/*
2853** Append a message to the error message string.
2854*/
drhaaab5722002-02-19 13:39:21 +00002855static void checkAppendMsg(IntegrityCk *pCheck, char *zMsg1, char *zMsg2){
drh5eddca62001-06-30 21:53:53 +00002856 if( pCheck->zErrMsg ){
2857 char *zOld = pCheck->zErrMsg;
2858 pCheck->zErrMsg = 0;
2859 sqliteSetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, 0);
2860 sqliteFree(zOld);
2861 }else{
2862 sqliteSetString(&pCheck->zErrMsg, zMsg1, zMsg2, 0);
2863 }
2864}
2865
2866/*
2867** Add 1 to the reference count for page iPage. If this is the second
2868** reference to the page, add an error message to pCheck->zErrMsg.
2869** Return 1 if there are 2 ore more references to the page and 0 if
2870** if this is the first reference to the page.
2871**
2872** Also check that the page number is in bounds.
2873*/
drhaaab5722002-02-19 13:39:21 +00002874static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00002875 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00002876 if( iPage>pCheck->nPage || iPage<0 ){
drh5eddca62001-06-30 21:53:53 +00002877 char zBuf[100];
2878 sprintf(zBuf, "invalid page number %d", iPage);
2879 checkAppendMsg(pCheck, zContext, zBuf);
2880 return 1;
2881 }
2882 if( pCheck->anRef[iPage]==1 ){
2883 char zBuf[100];
2884 sprintf(zBuf, "2nd reference to page %d", iPage);
2885 checkAppendMsg(pCheck, zContext, zBuf);
2886 return 1;
2887 }
2888 return (pCheck->anRef[iPage]++)>1;
2889}
2890
2891/*
2892** Check the integrity of the freelist or of an overflow page list.
2893** Verify that the number of pages on the list is N.
2894*/
drh30e58752002-03-02 20:41:57 +00002895static void checkList(
2896 IntegrityCk *pCheck, /* Integrity checking context */
2897 int isFreeList, /* True for a freelist. False for overflow page list */
2898 int iPage, /* Page number for first page in the list */
2899 int N, /* Expected number of pages in the list */
2900 char *zContext /* Context for error messages */
2901){
2902 int i;
drh5eddca62001-06-30 21:53:53 +00002903 char zMsg[100];
drh30e58752002-03-02 20:41:57 +00002904 while( N-- > 0 ){
drh5eddca62001-06-30 21:53:53 +00002905 OverflowPage *pOvfl;
2906 if( iPage<1 ){
2907 sprintf(zMsg, "%d pages missing from overflow list", N+1);
2908 checkAppendMsg(pCheck, zContext, zMsg);
2909 break;
2910 }
2911 if( checkRef(pCheck, iPage, zContext) ) break;
2912 if( sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
2913 sprintf(zMsg, "failed to get page %d", iPage);
2914 checkAppendMsg(pCheck, zContext, zMsg);
2915 break;
2916 }
drh30e58752002-03-02 20:41:57 +00002917 if( isFreeList ){
2918 FreelistInfo *pInfo = (FreelistInfo*)pOvfl->aPayload;
drh0d316a42002-08-11 20:10:47 +00002919 int n = SWAB32(pCheck->pBt, pInfo->nFree);
2920 for(i=0; i<n; i++){
2921 checkRef(pCheck, SWAB32(pCheck->pBt, pInfo->aFree[i]), zMsg);
drh30e58752002-03-02 20:41:57 +00002922 }
drh0d316a42002-08-11 20:10:47 +00002923 N -= n;
drh30e58752002-03-02 20:41:57 +00002924 }
drh0d316a42002-08-11 20:10:47 +00002925 iPage = SWAB32(pCheck->pBt, pOvfl->iNext);
drh5eddca62001-06-30 21:53:53 +00002926 sqlitepager_unref(pOvfl);
2927 }
2928}
2929
2930/*
drh1bffb9c2002-02-03 17:37:36 +00002931** Return negative if zKey1<zKey2.
2932** Return zero if zKey1==zKey2.
2933** Return positive if zKey1>zKey2.
2934*/
2935static int keyCompare(
2936 const char *zKey1, int nKey1,
2937 const char *zKey2, int nKey2
2938){
2939 int min = nKey1>nKey2 ? nKey2 : nKey1;
2940 int c = memcmp(zKey1, zKey2, min);
2941 if( c==0 ){
2942 c = nKey1 - nKey2;
2943 }
2944 return c;
2945}
2946
2947/*
drh5eddca62001-06-30 21:53:53 +00002948** Do various sanity checks on a single page of a tree. Return
2949** the tree depth. Root pages return 0. Parents of root pages
2950** return 1, and so forth.
2951**
2952** These checks are done:
2953**
2954** 1. Make sure that cells and freeblocks do not overlap
2955** but combine to completely cover the page.
2956** 2. Make sure cell keys are in order.
2957** 3. Make sure no key is less than or equal to zLowerBound.
2958** 4. Make sure no key is greater than or equal to zUpperBound.
2959** 5. Check the integrity of overflow pages.
2960** 6. Recursively call checkTreePage on all children.
2961** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00002962** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00002963** the root of the tree.
2964*/
2965static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00002966 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00002967 int iPage, /* Page number of the page to check */
2968 MemPage *pParent, /* Parent page */
2969 char *zParentContext, /* Parent context */
2970 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00002971 int nLower, /* Number of characters in zLowerBound */
2972 char *zUpperBound, /* All keys should be less than this, if not NULL */
2973 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00002974){
2975 MemPage *pPage;
2976 int i, rc, depth, d2, pgno;
2977 char *zKey1, *zKey2;
drh1bffb9c2002-02-03 17:37:36 +00002978 int nKey1, nKey2;
drh5eddca62001-06-30 21:53:53 +00002979 BtCursor cur;
drh0d316a42002-08-11 20:10:47 +00002980 Btree *pBt;
drh5eddca62001-06-30 21:53:53 +00002981 char zMsg[100];
2982 char zContext[100];
2983 char hit[SQLITE_PAGE_SIZE];
2984
2985 /* Check that the page exists
2986 */
drh0d316a42002-08-11 20:10:47 +00002987 cur.pBt = pBt = pCheck->pBt;
drh5eddca62001-06-30 21:53:53 +00002988 if( iPage==0 ) return 0;
2989 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
2990 sprintf(zContext, "On tree page %d: ", iPage);
2991 if( (rc = sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pPage))!=0 ){
2992 sprintf(zMsg, "unable to get the page. error code=%d", rc);
2993 checkAppendMsg(pCheck, zContext, zMsg);
2994 return 0;
2995 }
drh0d316a42002-08-11 20:10:47 +00002996 if( (rc = initPage(pBt, pPage, (Pgno)iPage, pParent))!=0 ){
drh5eddca62001-06-30 21:53:53 +00002997 sprintf(zMsg, "initPage() returns error code %d", rc);
2998 checkAppendMsg(pCheck, zContext, zMsg);
2999 sqlitepager_unref(pPage);
3000 return 0;
3001 }
3002
3003 /* Check out all the cells.
3004 */
3005 depth = 0;
drh1bffb9c2002-02-03 17:37:36 +00003006 if( zLowerBound ){
3007 zKey1 = sqliteMalloc( nLower+1 );
3008 memcpy(zKey1, zLowerBound, nLower);
3009 zKey1[nLower] = 0;
3010 }else{
3011 zKey1 = 0;
3012 }
3013 nKey1 = nLower;
drh5eddca62001-06-30 21:53:53 +00003014 cur.pPage = pPage;
drh5eddca62001-06-30 21:53:53 +00003015 for(i=0; i<pPage->nCell; i++){
3016 Cell *pCell = pPage->apCell[i];
3017 int sz;
3018
3019 /* Check payload overflow pages
3020 */
drh0d316a42002-08-11 20:10:47 +00003021 nKey2 = NKEY(pBt, pCell->h);
3022 sz = nKey2 + NDATA(pBt, pCell->h);
drh5eddca62001-06-30 21:53:53 +00003023 sprintf(zContext, "On page %d cell %d: ", iPage, i);
3024 if( sz>MX_LOCAL_PAYLOAD ){
3025 int nPage = (sz - MX_LOCAL_PAYLOAD + OVERFLOW_SIZE - 1)/OVERFLOW_SIZE;
drh0d316a42002-08-11 20:10:47 +00003026 checkList(pCheck, 0, SWAB32(pBt, pCell->ovfl), nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00003027 }
3028
3029 /* Check that keys are in the right order
3030 */
3031 cur.idx = i;
drh1bffb9c2002-02-03 17:37:36 +00003032 zKey2 = sqliteMalloc( nKey2+1 );
3033 getPayload(&cur, 0, nKey2, zKey2);
3034 if( zKey1 && keyCompare(zKey1, nKey1, zKey2, nKey2)>=0 ){
drh5eddca62001-06-30 21:53:53 +00003035 checkAppendMsg(pCheck, zContext, "Key is out of order");
3036 }
3037
3038 /* Check sanity of left child page.
3039 */
drh0d316a42002-08-11 20:10:47 +00003040 pgno = SWAB32(pBt, pCell->h.leftChild);
drh1bffb9c2002-02-03 17:37:36 +00003041 d2 = checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zKey2,nKey2);
drh5eddca62001-06-30 21:53:53 +00003042 if( i>0 && d2!=depth ){
3043 checkAppendMsg(pCheck, zContext, "Child page depth differs");
3044 }
3045 depth = d2;
3046 sqliteFree(zKey1);
3047 zKey1 = zKey2;
drh1bffb9c2002-02-03 17:37:36 +00003048 nKey1 = nKey2;
drh5eddca62001-06-30 21:53:53 +00003049 }
drh0d316a42002-08-11 20:10:47 +00003050 pgno = SWAB32(pBt, pPage->u.hdr.rightChild);
drh5eddca62001-06-30 21:53:53 +00003051 sprintf(zContext, "On page %d at right child: ", iPage);
drh1bffb9c2002-02-03 17:37:36 +00003052 checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zUpperBound,nUpper);
drh5eddca62001-06-30 21:53:53 +00003053 sqliteFree(zKey1);
3054
3055 /* Check for complete coverage of the page
3056 */
3057 memset(hit, 0, sizeof(hit));
3058 memset(hit, 1, sizeof(PageHdr));
drh0d316a42002-08-11 20:10:47 +00003059 for(i=SWAB16(pBt, pPage->u.hdr.firstCell); i>0 && i<SQLITE_PAGE_SIZE; ){
drh5eddca62001-06-30 21:53:53 +00003060 Cell *pCell = (Cell*)&pPage->u.aDisk[i];
3061 int j;
drh0d316a42002-08-11 20:10:47 +00003062 for(j=i+cellSize(pBt, pCell)-1; j>=i; j--) hit[j]++;
3063 i = SWAB16(pBt, pCell->h.iNext);
drh5eddca62001-06-30 21:53:53 +00003064 }
drh0d316a42002-08-11 20:10:47 +00003065 for(i=SWAB16(pBt,pPage->u.hdr.firstFree); i>0 && i<SQLITE_PAGE_SIZE; ){
drh5eddca62001-06-30 21:53:53 +00003066 FreeBlk *pFBlk = (FreeBlk*)&pPage->u.aDisk[i];
3067 int j;
drh0d316a42002-08-11 20:10:47 +00003068 for(j=i+SWAB16(pBt,pFBlk->iSize)-1; j>=i; j--) hit[j]++;
3069 i = SWAB16(pBt,pFBlk->iNext);
drh5eddca62001-06-30 21:53:53 +00003070 }
3071 for(i=0; i<SQLITE_PAGE_SIZE; i++){
3072 if( hit[i]==0 ){
3073 sprintf(zMsg, "Unused space at byte %d of page %d", i, iPage);
3074 checkAppendMsg(pCheck, zMsg, 0);
3075 break;
3076 }else if( hit[i]>1 ){
3077 sprintf(zMsg, "Multiple uses for byte %d of page %d", i, iPage);
3078 checkAppendMsg(pCheck, zMsg, 0);
3079 break;
3080 }
3081 }
3082
3083 /* Check that free space is kept to a minimum
3084 */
drh6019e162001-07-02 17:51:45 +00003085#if 0
3086 if( pParent && pParent->nCell>2 && pPage->nFree>3*SQLITE_PAGE_SIZE/4 ){
drh5eddca62001-06-30 21:53:53 +00003087 sprintf(zMsg, "free space (%d) greater than max (%d)", pPage->nFree,
3088 SQLITE_PAGE_SIZE/3);
3089 checkAppendMsg(pCheck, zContext, zMsg);
3090 }
drh6019e162001-07-02 17:51:45 +00003091#endif
3092
3093 /* Update freespace totals.
3094 */
3095 pCheck->nTreePage++;
3096 pCheck->nByte += USABLE_SPACE - pPage->nFree;
drh5eddca62001-06-30 21:53:53 +00003097
3098 sqlitepager_unref(pPage);
3099 return depth;
3100}
3101
3102/*
3103** This routine does a complete check of the given BTree file. aRoot[] is
3104** an array of pages numbers were each page number is the root page of
3105** a table. nRoot is the number of entries in aRoot.
3106**
3107** If everything checks out, this routine returns NULL. If something is
3108** amiss, an error message is written into memory obtained from malloc()
3109** and a pointer to that error message is returned. The calling function
3110** is responsible for freeing the error message when it is done.
3111*/
drhaaab5722002-02-19 13:39:21 +00003112char *sqliteBtreeIntegrityCheck(Btree *pBt, int *aRoot, int nRoot){
drh5eddca62001-06-30 21:53:53 +00003113 int i;
3114 int nRef;
drhaaab5722002-02-19 13:39:21 +00003115 IntegrityCk sCheck;
drh5eddca62001-06-30 21:53:53 +00003116
3117 nRef = *sqlitepager_stats(pBt->pPager);
drhefc251d2001-07-01 22:12:01 +00003118 if( lockBtree(pBt)!=SQLITE_OK ){
3119 return sqliteStrDup("Unable to acquire a read lock on the database");
3120 }
drh5eddca62001-06-30 21:53:53 +00003121 sCheck.pBt = pBt;
3122 sCheck.pPager = pBt->pPager;
3123 sCheck.nPage = sqlitepager_pagecount(sCheck.pPager);
drh0de8c112002-07-06 16:32:14 +00003124 if( sCheck.nPage==0 ){
3125 unlockBtreeIfUnused(pBt);
3126 return 0;
3127 }
drh5eddca62001-06-30 21:53:53 +00003128 sCheck.anRef = sqliteMalloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
3129 sCheck.anRef[1] = 1;
3130 for(i=2; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
3131 sCheck.zErrMsg = 0;
3132
3133 /* Check the integrity of the freelist
3134 */
drh0d316a42002-08-11 20:10:47 +00003135 checkList(&sCheck, 1, SWAB32(pBt, pBt->page1->freeList),
3136 SWAB32(pBt, pBt->page1->nFree), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00003137
3138 /* Check all the tables.
3139 */
3140 for(i=0; i<nRoot; i++){
drh4ff6dfa2002-03-03 23:06:00 +00003141 if( aRoot[i]==0 ) continue;
drh1bffb9c2002-02-03 17:37:36 +00003142 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00003143 }
3144
3145 /* Make sure every page in the file is referenced
3146 */
3147 for(i=1; i<=sCheck.nPage; i++){
3148 if( sCheck.anRef[i]==0 ){
3149 char zBuf[100];
3150 sprintf(zBuf, "Page %d is never used", i);
3151 checkAppendMsg(&sCheck, zBuf, 0);
3152 }
3153 }
3154
3155 /* Make sure this analysis did not leave any unref() pages
3156 */
drh5e00f6c2001-09-13 13:46:56 +00003157 unlockBtreeIfUnused(pBt);
drh5eddca62001-06-30 21:53:53 +00003158 if( nRef != *sqlitepager_stats(pBt->pPager) ){
3159 char zBuf[100];
3160 sprintf(zBuf,
3161 "Outstanding page count goes from %d to %d during this analysis",
3162 nRef, *sqlitepager_stats(pBt->pPager)
3163 );
3164 checkAppendMsg(&sCheck, zBuf, 0);
3165 }
3166
3167 /* Clean up and report errors.
3168 */
3169 sqliteFree(sCheck.anRef);
3170 return sCheck.zErrMsg;
3171}