blob: 253ad0e5854edbe3214a877fbd388c87f9682168 [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*************************************************************************
drhbea00b92002-07-08 10:59:50 +000012** $Id: btree.c,v 1.67 2002/07/08 10:59:51 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/*
drh365d68f2001-05-11 11:02:46 +000058** Forward declarations of structures used only in this file.
59*/
drhbd03cae2001-06-02 02:40:57 +000060typedef struct PageOne PageOne;
drh2af926b2001-05-15 00:39:25 +000061typedef struct MemPage MemPage;
drh365d68f2001-05-11 11:02:46 +000062typedef struct PageHdr PageHdr;
63typedef struct Cell Cell;
drh3b7511c2001-05-26 13:15:44 +000064typedef struct CellHdr CellHdr;
drh365d68f2001-05-11 11:02:46 +000065typedef struct FreeBlk FreeBlk;
drh2af926b2001-05-15 00:39:25 +000066typedef struct OverflowPage OverflowPage;
drh30e58752002-03-02 20:41:57 +000067typedef struct FreelistInfo FreelistInfo;
drh2af926b2001-05-15 00:39:25 +000068
69/*
70** All structures on a database page are aligned to 4-byte boundries.
71** This routine rounds up a number of bytes to the next multiple of 4.
drh306dc212001-05-21 13:45:10 +000072**
73** This might need to change for computer architectures that require
74** and 8-byte alignment boundry for structures.
drh2af926b2001-05-15 00:39:25 +000075*/
76#define ROUNDUP(X) ((X+3) & ~3)
drha059ad02001-04-17 20:09:11 +000077
drh08ed44e2001-04-29 23:32:55 +000078/*
drhbd03cae2001-06-02 02:40:57 +000079** This is a magic string that appears at the beginning of every
drh8c42ca92001-06-22 19:15:00 +000080** SQLite database in order to identify the file as a real database.
drh08ed44e2001-04-29 23:32:55 +000081*/
drhbd03cae2001-06-02 02:40:57 +000082static const char zMagicHeader[] =
drh80ff32f2001-11-04 18:32:46 +000083 "** This file contains an SQLite 2.1 database **";
drhbd03cae2001-06-02 02:40:57 +000084#define MAGIC_SIZE (sizeof(zMagicHeader))
drh08ed44e2001-04-29 23:32:55 +000085
86/*
drh5e00f6c2001-09-13 13:46:56 +000087** This is a magic integer also used to test the integrity of the database
drh8c42ca92001-06-22 19:15:00 +000088** file. This integer is used in addition to the string above so that
89** if the file is written on a little-endian architecture and read
90** on a big-endian architectures (or vice versa) we can detect the
91** problem.
92**
93** The number used was obtained at random and has no special
drhb19a2bc2001-09-16 00:13:26 +000094** significance other than the fact that it represents a different
95** integer on little-endian and big-endian machines.
drh8c42ca92001-06-22 19:15:00 +000096*/
97#define MAGIC 0xdae37528
98
99/*
drhbd03cae2001-06-02 02:40:57 +0000100** The first page of the database file contains a magic header string
101** to identify the file as an SQLite database file. It also contains
102** a pointer to the first free page of the file. Page 2 contains the
drh8b2f49b2001-06-08 00:21:52 +0000103** root of the principle BTree. The file might contain other BTrees
104** rooted on pages above 2.
105**
106** The first page also contains SQLITE_N_BTREE_META integers that
107** can be used by higher-level routines.
drh08ed44e2001-04-29 23:32:55 +0000108**
drhbd03cae2001-06-02 02:40:57 +0000109** Remember that pages are numbered beginning with 1. (See pager.c
110** for additional information.) Page 0 does not exist and a page
111** number of 0 is used to mean "no such page".
112*/
113struct PageOne {
114 char zMagic[MAGIC_SIZE]; /* String that identifies the file as a database */
drh8c42ca92001-06-22 19:15:00 +0000115 int iMagic; /* Integer to verify correct byte order */
116 Pgno freeList; /* First free page in a list of all free pages */
drh2aa679f2001-06-25 02:11:07 +0000117 int nFree; /* Number of pages on the free list */
118 int aMeta[SQLITE_N_BTREE_META-1]; /* User defined integers */
drhbd03cae2001-06-02 02:40:57 +0000119};
120
121/*
122** Each database page has a header that is an instance of this
123** structure.
drh08ed44e2001-04-29 23:32:55 +0000124**
drh8b2f49b2001-06-08 00:21:52 +0000125** PageHdr.firstFree is 0 if there is no free space on this page.
drh14acc042001-06-10 19:56:58 +0000126** Otherwise, PageHdr.firstFree is the index in MemPage.u.aDisk[] of a
drh8b2f49b2001-06-08 00:21:52 +0000127** FreeBlk structure that describes the first block of free space.
128** All free space is defined by a linked list of FreeBlk structures.
drh08ed44e2001-04-29 23:32:55 +0000129**
drh8b2f49b2001-06-08 00:21:52 +0000130** Data is stored in a linked list of Cell structures. PageHdr.firstCell
drh14acc042001-06-10 19:56:58 +0000131** is the index into MemPage.u.aDisk[] of the first cell on the page. The
drh306dc212001-05-21 13:45:10 +0000132** Cells are kept in sorted order.
drh8b2f49b2001-06-08 00:21:52 +0000133**
134** A Cell contains all information about a database entry and a pointer
135** to a child page that contains other entries less than itself. In
136** other words, the i-th Cell contains both Ptr(i) and Key(i). The
137** right-most pointer of the page is contained in PageHdr.rightChild.
drh08ed44e2001-04-29 23:32:55 +0000138*/
drh365d68f2001-05-11 11:02:46 +0000139struct PageHdr {
drh5e2f8b92001-05-28 00:41:15 +0000140 Pgno rightChild; /* Child page that comes after all cells on this page */
drh14acc042001-06-10 19:56:58 +0000141 u16 firstCell; /* Index in MemPage.u.aDisk[] of the first cell */
142 u16 firstFree; /* Index in MemPage.u.aDisk[] of the first free block */
drh365d68f2001-05-11 11:02:46 +0000143};
drh306dc212001-05-21 13:45:10 +0000144
drh3b7511c2001-05-26 13:15:44 +0000145/*
146** Entries on a page of the database are called "Cells". Each Cell
147** has a header and data. This structure defines the header. The
drhbd03cae2001-06-02 02:40:57 +0000148** key and data (collectively the "payload") follow this header on
149** the database page.
150**
151** A definition of the complete Cell structure is given below. The
drh8c42ca92001-06-22 19:15:00 +0000152** header for the cell must be defined first in order to do some
drhbd03cae2001-06-02 02:40:57 +0000153** of the sizing #defines that follow.
drh3b7511c2001-05-26 13:15:44 +0000154*/
155struct CellHdr {
drh5e2f8b92001-05-28 00:41:15 +0000156 Pgno leftChild; /* Child page that comes before this cell */
drh3b7511c2001-05-26 13:15:44 +0000157 u16 nKey; /* Number of bytes in the key */
drh14acc042001-06-10 19:56:58 +0000158 u16 iNext; /* Index in MemPage.u.aDisk[] of next cell in sorted order */
drh58a11682001-11-10 13:51:08 +0000159 u8 nKeyHi; /* Upper 8 bits of key size for keys larger than 64K bytes */
160 u8 nDataHi; /* Upper 8 bits of data size when the size is more than 64K */
drh80ff32f2001-11-04 18:32:46 +0000161 u16 nData; /* Number of bytes of data */
drh8c42ca92001-06-22 19:15:00 +0000162};
drh58a11682001-11-10 13:51:08 +0000163
164/*
165** The key and data size are split into a lower 16-bit segment and an
166** upper 8-bit segment in order to pack them together into a smaller
167** space. The following macros reassembly a key or data size back
168** into an integer.
169*/
drh80ff32f2001-11-04 18:32:46 +0000170#define NKEY(h) (h.nKey + h.nKeyHi*65536)
171#define NDATA(h) (h.nData + h.nDataHi*65536)
drh3b7511c2001-05-26 13:15:44 +0000172
173/*
174** The minimum size of a complete Cell. The Cell must contain a header
drhbd03cae2001-06-02 02:40:57 +0000175** and at least 4 bytes of payload.
drh3b7511c2001-05-26 13:15:44 +0000176*/
177#define MIN_CELL_SIZE (sizeof(CellHdr)+4)
178
179/*
180** The maximum number of database entries that can be held in a single
181** page of the database.
182*/
183#define MX_CELL ((SQLITE_PAGE_SIZE-sizeof(PageHdr))/MIN_CELL_SIZE)
184
185/*
drh6019e162001-07-02 17:51:45 +0000186** The amount of usable space on a single page of the BTree. This is the
187** page size minus the overhead of the page header.
188*/
189#define USABLE_SPACE (SQLITE_PAGE_SIZE - sizeof(PageHdr))
190
191/*
drh8c42ca92001-06-22 19:15:00 +0000192** The maximum amount of payload (in bytes) that can be stored locally for
193** a database entry. If the entry contains more data than this, the
drh3b7511c2001-05-26 13:15:44 +0000194** extra goes onto overflow pages.
drhbd03cae2001-06-02 02:40:57 +0000195**
196** This number is chosen so that at least 4 cells will fit on every page.
drh3b7511c2001-05-26 13:15:44 +0000197*/
drh6019e162001-07-02 17:51:45 +0000198#define MX_LOCAL_PAYLOAD ((USABLE_SPACE/4-(sizeof(CellHdr)+sizeof(Pgno)))&~3)
drh3b7511c2001-05-26 13:15:44 +0000199
drh306dc212001-05-21 13:45:10 +0000200/*
201** Data on a database page is stored as a linked list of Cell structures.
drh5e2f8b92001-05-28 00:41:15 +0000202** Both the key and the data are stored in aPayload[]. The key always comes
203** first. The aPayload[] field grows as necessary to hold the key and data,
drh306dc212001-05-21 13:45:10 +0000204** up to a maximum of MX_LOCAL_PAYLOAD bytes. If the size of the key and
drh3b7511c2001-05-26 13:15:44 +0000205** data combined exceeds MX_LOCAL_PAYLOAD bytes, then Cell.ovfl is the
206** page number of the first overflow page.
207**
208** Though this structure is fixed in size, the Cell on the database
drhbd03cae2001-06-02 02:40:57 +0000209** page varies in size. Every cell has a CellHdr and at least 4 bytes
drh3b7511c2001-05-26 13:15:44 +0000210** of payload space. Additional payload bytes (up to the maximum of
211** MX_LOCAL_PAYLOAD) and the Cell.ovfl value are allocated only as
212** needed.
drh306dc212001-05-21 13:45:10 +0000213*/
drh365d68f2001-05-11 11:02:46 +0000214struct Cell {
drh5e2f8b92001-05-28 00:41:15 +0000215 CellHdr h; /* The cell header */
216 char aPayload[MX_LOCAL_PAYLOAD]; /* Key and data */
217 Pgno ovfl; /* The first overflow page */
drh365d68f2001-05-11 11:02:46 +0000218};
drh306dc212001-05-21 13:45:10 +0000219
220/*
221** Free space on a page is remembered using a linked list of the FreeBlk
222** structures. Space on a database page is allocated in increments of
drh72f82862001-05-24 21:06:34 +0000223** at least 4 bytes and is always aligned to a 4-byte boundry. The
drh8b2f49b2001-06-08 00:21:52 +0000224** linked list of FreeBlks is always kept in order by address.
drh306dc212001-05-21 13:45:10 +0000225*/
drh365d68f2001-05-11 11:02:46 +0000226struct FreeBlk {
drh72f82862001-05-24 21:06:34 +0000227 u16 iSize; /* Number of bytes in this block of free space */
drh14acc042001-06-10 19:56:58 +0000228 u16 iNext; /* Index in MemPage.u.aDisk[] of the next free block */
drh365d68f2001-05-11 11:02:46 +0000229};
drh306dc212001-05-21 13:45:10 +0000230
231/*
drh14acc042001-06-10 19:56:58 +0000232** The number of bytes of payload that will fit on a single overflow page.
drh3b7511c2001-05-26 13:15:44 +0000233*/
234#define OVERFLOW_SIZE (SQLITE_PAGE_SIZE-sizeof(Pgno))
235
236/*
drh306dc212001-05-21 13:45:10 +0000237** When the key and data for a single entry in the BTree will not fit in
drh8c42ca92001-06-22 19:15:00 +0000238** the MX_LOCAL_PAYLOAD bytes of space available on the database page,
drh8b2f49b2001-06-08 00:21:52 +0000239** then all extra bytes are written to a linked list of overflow pages.
drh306dc212001-05-21 13:45:10 +0000240** Each overflow page is an instance of the following structure.
241**
242** Unused pages in the database are also represented by instances of
drhbd03cae2001-06-02 02:40:57 +0000243** the OverflowPage structure. The PageOne.freeList field is the
drh306dc212001-05-21 13:45:10 +0000244** page number of the first page in a linked list of unused database
245** pages.
246*/
drh2af926b2001-05-15 00:39:25 +0000247struct OverflowPage {
drh14acc042001-06-10 19:56:58 +0000248 Pgno iNext;
drh5e2f8b92001-05-28 00:41:15 +0000249 char aPayload[OVERFLOW_SIZE];
drh7e3b0a02001-04-28 16:52:40 +0000250};
drh7e3b0a02001-04-28 16:52:40 +0000251
252/*
drh30e58752002-03-02 20:41:57 +0000253** The PageOne.freeList field points to a linked list of overflow pages
254** hold information about free pages. The aPayload section of each
255** overflow page contains an instance of the following structure. The
256** aFree[] array holds the page number of nFree unused pages in the disk
257** file.
258*/
259struct FreelistInfo {
260 int nFree;
261 Pgno aFree[(OVERFLOW_SIZE-sizeof(int))/sizeof(Pgno)];
262};
263
264/*
drh7e3b0a02001-04-28 16:52:40 +0000265** For every page in the database file, an instance of the following structure
drh14acc042001-06-10 19:56:58 +0000266** is stored in memory. The u.aDisk[] array contains the raw bits read from
drh6446c4d2001-12-15 14:22:18 +0000267** the disk. The rest is auxiliary information held in memory only. The
drhbd03cae2001-06-02 02:40:57 +0000268** auxiliary info is only valid for regular database pages - it is not
269** used for overflow pages and pages on the freelist.
drh306dc212001-05-21 13:45:10 +0000270**
drhbd03cae2001-06-02 02:40:57 +0000271** Of particular interest in the auxiliary info is the apCell[] entry. Each
drh14acc042001-06-10 19:56:58 +0000272** apCell[] entry is a pointer to a Cell structure in u.aDisk[]. The cells are
drh306dc212001-05-21 13:45:10 +0000273** put in this array so that they can be accessed in constant time, rather
drhbd03cae2001-06-02 02:40:57 +0000274** than in linear time which would be needed if we had to walk the linked
275** list on every access.
drh72f82862001-05-24 21:06:34 +0000276**
drh14acc042001-06-10 19:56:58 +0000277** Note that apCell[] contains enough space to hold up to two more Cells
278** than can possibly fit on one page. In the steady state, every apCell[]
279** points to memory inside u.aDisk[]. But in the middle of an insert
280** operation, some apCell[] entries may temporarily point to data space
281** outside of u.aDisk[]. This is a transient situation that is quickly
282** resolved. But while it is happening, it is possible for a database
283** page to hold as many as two more cells than it might otherwise hold.
drh18b81e52001-11-01 13:52:52 +0000284** The extra two entries in apCell[] are an allowance for this situation.
drh14acc042001-06-10 19:56:58 +0000285**
drh72f82862001-05-24 21:06:34 +0000286** The pParent field points back to the parent page. This allows us to
287** walk up the BTree from any leaf to the root. Care must be taken to
288** unref() the parent page pointer when this page is no longer referenced.
drhbd03cae2001-06-02 02:40:57 +0000289** The pageDestructor() routine handles that chore.
drh7e3b0a02001-04-28 16:52:40 +0000290*/
291struct MemPage {
drh14acc042001-06-10 19:56:58 +0000292 union {
293 char aDisk[SQLITE_PAGE_SIZE]; /* Page data stored on disk */
294 PageHdr hdr; /* Overlay page header */
295 } u;
drh5e2f8b92001-05-28 00:41:15 +0000296 int isInit; /* True if auxiliary data is initialized */
drh72f82862001-05-24 21:06:34 +0000297 MemPage *pParent; /* The parent of this page. NULL for root */
drh14acc042001-06-10 19:56:58 +0000298 int nFree; /* Number of free bytes in u.aDisk[] */
drh306dc212001-05-21 13:45:10 +0000299 int nCell; /* Number of entries on this page */
drh14acc042001-06-10 19:56:58 +0000300 int isOverfull; /* Some apCell[] points outside u.aDisk[] */
301 Cell *apCell[MX_CELL+2]; /* All data entires in sorted order */
drh8c42ca92001-06-22 19:15:00 +0000302};
drh7e3b0a02001-04-28 16:52:40 +0000303
304/*
drh3b7511c2001-05-26 13:15:44 +0000305** The in-memory image of a disk page has the auxiliary information appended
306** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
307** that extra information.
308*/
309#define EXTRA_SIZE (sizeof(MemPage)-SQLITE_PAGE_SIZE)
310
311/*
drha059ad02001-04-17 20:09:11 +0000312** Everything we need to know about an open database
313*/
314struct Btree {
315 Pager *pPager; /* The page cache */
drh306dc212001-05-21 13:45:10 +0000316 BtCursor *pCursor; /* A list of all open cursors */
drhbd03cae2001-06-02 02:40:57 +0000317 PageOne *page1; /* First page of the database */
drh663fc632002-02-02 18:49:19 +0000318 u8 inTrans; /* True if a transaction is in progress */
319 u8 inCkpt; /* True if there is a checkpoint on the transaction */
drh5df72a52002-06-06 23:16:05 +0000320 u8 readOnly; /* True if the underlying file is readonly */
drhecdc7532001-09-23 02:35:53 +0000321 Hash locks; /* Key: root page number. Data: lock count */
drha059ad02001-04-17 20:09:11 +0000322};
323typedef Btree Bt;
324
drh365d68f2001-05-11 11:02:46 +0000325/*
326** A cursor is a pointer to a particular entry in the BTree.
327** The entry is identified by its MemPage and the index in
drh5e2f8b92001-05-28 00:41:15 +0000328** MemPage.apCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000329*/
drh72f82862001-05-24 21:06:34 +0000330struct BtCursor {
drh5e2f8b92001-05-28 00:41:15 +0000331 Btree *pBt; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000332 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drh8b2f49b2001-06-08 00:21:52 +0000333 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000334 MemPage *pPage; /* Page that contains the entry */
drh8c42ca92001-06-22 19:15:00 +0000335 int idx; /* Index of the entry in pPage->apCell[] */
drhecdc7532001-09-23 02:35:53 +0000336 u8 wrFlag; /* True if writable */
drh5e2f8b92001-05-28 00:41:15 +0000337 u8 bSkipNext; /* sqliteBtreeNext() is no-op if true */
338 u8 iMatch; /* compare result from last sqliteBtreeMoveto() */
drh365d68f2001-05-11 11:02:46 +0000339};
drh7e3b0a02001-04-28 16:52:40 +0000340
drha059ad02001-04-17 20:09:11 +0000341/*
drh3b7511c2001-05-26 13:15:44 +0000342** Compute the total number of bytes that a Cell needs on the main
drh5e2f8b92001-05-28 00:41:15 +0000343** database page. The number returned includes the Cell header,
344** local payload storage, and the pointer to overflow pages (if
drh8c42ca92001-06-22 19:15:00 +0000345** applicable). Additional space allocated on overflow pages
drhbd03cae2001-06-02 02:40:57 +0000346** is NOT included in the value returned from this routine.
drh3b7511c2001-05-26 13:15:44 +0000347*/
348static int cellSize(Cell *pCell){
drh80ff32f2001-11-04 18:32:46 +0000349 int n = NKEY(pCell->h) + NDATA(pCell->h);
drh3b7511c2001-05-26 13:15:44 +0000350 if( n>MX_LOCAL_PAYLOAD ){
351 n = MX_LOCAL_PAYLOAD + sizeof(Pgno);
352 }else{
353 n = ROUNDUP(n);
354 }
355 n += sizeof(CellHdr);
356 return n;
357}
358
359/*
drh72f82862001-05-24 21:06:34 +0000360** Defragment the page given. All Cells are moved to the
361** beginning of the page and all free space is collected
362** into one big FreeBlk at the end of the page.
drh365d68f2001-05-11 11:02:46 +0000363*/
364static void defragmentPage(MemPage *pPage){
drh14acc042001-06-10 19:56:58 +0000365 int pc, i, n;
drh2af926b2001-05-15 00:39:25 +0000366 FreeBlk *pFBlk;
367 char newPage[SQLITE_PAGE_SIZE];
368
drh6019e162001-07-02 17:51:45 +0000369 assert( sqlitepager_iswriteable(pPage) );
drh7aa128d2002-06-21 13:09:16 +0000370 assert( pPage->isInit );
drhbd03cae2001-06-02 02:40:57 +0000371 pc = sizeof(PageHdr);
drh14acc042001-06-10 19:56:58 +0000372 pPage->u.hdr.firstCell = pc;
373 memcpy(newPage, pPage->u.aDisk, pc);
drh2af926b2001-05-15 00:39:25 +0000374 for(i=0; i<pPage->nCell; i++){
drh2aa679f2001-06-25 02:11:07 +0000375 Cell *pCell = pPage->apCell[i];
drh8c42ca92001-06-22 19:15:00 +0000376
377 /* This routine should never be called on an overfull page. The
378 ** following asserts verify that constraint. */
drh7c717f72001-06-24 20:39:41 +0000379 assert( Addr(pCell) > Addr(pPage) );
380 assert( Addr(pCell) < Addr(pPage) + SQLITE_PAGE_SIZE );
drh8c42ca92001-06-22 19:15:00 +0000381
drh3b7511c2001-05-26 13:15:44 +0000382 n = cellSize(pCell);
drh2aa679f2001-06-25 02:11:07 +0000383 pCell->h.iNext = pc + n;
drh2af926b2001-05-15 00:39:25 +0000384 memcpy(&newPage[pc], pCell, n);
drh14acc042001-06-10 19:56:58 +0000385 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[pc];
drh2af926b2001-05-15 00:39:25 +0000386 pc += n;
387 }
drh72f82862001-05-24 21:06:34 +0000388 assert( pPage->nFree==SQLITE_PAGE_SIZE-pc );
drh14acc042001-06-10 19:56:58 +0000389 memcpy(pPage->u.aDisk, newPage, pc);
drh2aa679f2001-06-25 02:11:07 +0000390 if( pPage->nCell>0 ){
391 pPage->apCell[pPage->nCell-1]->h.iNext = 0;
392 }
drh8c42ca92001-06-22 19:15:00 +0000393 pFBlk = (FreeBlk*)&pPage->u.aDisk[pc];
drh2af926b2001-05-15 00:39:25 +0000394 pFBlk->iSize = SQLITE_PAGE_SIZE - pc;
395 pFBlk->iNext = 0;
drh14acc042001-06-10 19:56:58 +0000396 pPage->u.hdr.firstFree = pc;
drh2af926b2001-05-15 00:39:25 +0000397 memset(&pFBlk[1], 0, SQLITE_PAGE_SIZE - pc - sizeof(FreeBlk));
drh365d68f2001-05-11 11:02:46 +0000398}
399
drha059ad02001-04-17 20:09:11 +0000400/*
drh8b2f49b2001-06-08 00:21:52 +0000401** Allocate nByte bytes of space on a page. nByte must be a
402** multiple of 4.
drhbd03cae2001-06-02 02:40:57 +0000403**
drh14acc042001-06-10 19:56:58 +0000404** Return the index into pPage->u.aDisk[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000405** the new allocation. Or return 0 if there is not enough free
406** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000407**
drh72f82862001-05-24 21:06:34 +0000408** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000409** nBytes of contiguous free space, then this routine automatically
410** calls defragementPage() to consolidate all free space before
411** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000412*/
drhbd03cae2001-06-02 02:40:57 +0000413static int allocateSpace(MemPage *pPage, int nByte){
drh2af926b2001-05-15 00:39:25 +0000414 FreeBlk *p;
415 u16 *pIdx;
416 int start;
drh8c42ca92001-06-22 19:15:00 +0000417 int cnt = 0;
drh72f82862001-05-24 21:06:34 +0000418
drh6019e162001-07-02 17:51:45 +0000419 assert( sqlitepager_iswriteable(pPage) );
drh5e2f8b92001-05-28 00:41:15 +0000420 assert( nByte==ROUNDUP(nByte) );
drh7aa128d2002-06-21 13:09:16 +0000421 assert( pPage->isInit );
drh14acc042001-06-10 19:56:58 +0000422 if( pPage->nFree<nByte || pPage->isOverfull ) return 0;
423 pIdx = &pPage->u.hdr.firstFree;
424 p = (FreeBlk*)&pPage->u.aDisk[*pIdx];
drh2af926b2001-05-15 00:39:25 +0000425 while( p->iSize<nByte ){
drh8c42ca92001-06-22 19:15:00 +0000426 assert( cnt++ < SQLITE_PAGE_SIZE/4 );
drh2af926b2001-05-15 00:39:25 +0000427 if( p->iNext==0 ){
428 defragmentPage(pPage);
drh14acc042001-06-10 19:56:58 +0000429 pIdx = &pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000430 }else{
431 pIdx = &p->iNext;
432 }
drh14acc042001-06-10 19:56:58 +0000433 p = (FreeBlk*)&pPage->u.aDisk[*pIdx];
drh2af926b2001-05-15 00:39:25 +0000434 }
435 if( p->iSize==nByte ){
436 start = *pIdx;
437 *pIdx = p->iNext;
438 }else{
drh8c42ca92001-06-22 19:15:00 +0000439 FreeBlk *pNew;
drh72f82862001-05-24 21:06:34 +0000440 start = *pIdx;
drh8c42ca92001-06-22 19:15:00 +0000441 pNew = (FreeBlk*)&pPage->u.aDisk[start + nByte];
drh72f82862001-05-24 21:06:34 +0000442 pNew->iNext = p->iNext;
443 pNew->iSize = p->iSize - nByte;
444 *pIdx = start + nByte;
drh2af926b2001-05-15 00:39:25 +0000445 }
446 pPage->nFree -= nByte;
447 return start;
drh7e3b0a02001-04-28 16:52:40 +0000448}
449
450/*
drh14acc042001-06-10 19:56:58 +0000451** Return a section of the MemPage.u.aDisk[] to the freelist.
452** The first byte of the new free block is pPage->u.aDisk[start]
453** and the size of the block is "size" bytes. Size must be
454** a multiple of 4.
drh306dc212001-05-21 13:45:10 +0000455**
456** Most of the effort here is involved in coalesing adjacent
457** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000458*/
459static void freeSpace(MemPage *pPage, int start, int size){
drh2af926b2001-05-15 00:39:25 +0000460 int end = start + size;
461 u16 *pIdx, idx;
462 FreeBlk *pFBlk;
463 FreeBlk *pNew;
464 FreeBlk *pNext;
465
drh6019e162001-07-02 17:51:45 +0000466 assert( sqlitepager_iswriteable(pPage) );
drh2af926b2001-05-15 00:39:25 +0000467 assert( size == ROUNDUP(size) );
468 assert( start == ROUNDUP(start) );
drh7aa128d2002-06-21 13:09:16 +0000469 assert( pPage->isInit );
drh14acc042001-06-10 19:56:58 +0000470 pIdx = &pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000471 idx = *pIdx;
472 while( idx!=0 && idx<start ){
drh14acc042001-06-10 19:56:58 +0000473 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh2af926b2001-05-15 00:39:25 +0000474 if( idx + pFBlk->iSize == start ){
475 pFBlk->iSize += size;
476 if( idx + pFBlk->iSize == pFBlk->iNext ){
drh8c42ca92001-06-22 19:15:00 +0000477 pNext = (FreeBlk*)&pPage->u.aDisk[pFBlk->iNext];
drh2af926b2001-05-15 00:39:25 +0000478 pFBlk->iSize += pNext->iSize;
479 pFBlk->iNext = pNext->iNext;
480 }
481 pPage->nFree += size;
482 return;
483 }
484 pIdx = &pFBlk->iNext;
485 idx = *pIdx;
486 }
drh14acc042001-06-10 19:56:58 +0000487 pNew = (FreeBlk*)&pPage->u.aDisk[start];
drh2af926b2001-05-15 00:39:25 +0000488 if( idx != end ){
489 pNew->iSize = size;
490 pNew->iNext = idx;
491 }else{
drh14acc042001-06-10 19:56:58 +0000492 pNext = (FreeBlk*)&pPage->u.aDisk[idx];
drh2af926b2001-05-15 00:39:25 +0000493 pNew->iSize = size + pNext->iSize;
494 pNew->iNext = pNext->iNext;
495 }
496 *pIdx = start;
497 pPage->nFree += size;
drh7e3b0a02001-04-28 16:52:40 +0000498}
499
500/*
501** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000502**
drhbd03cae2001-06-02 02:40:57 +0000503** The pParent parameter must be a pointer to the MemPage which
504** is the parent of the page being initialized. The root of the
drh8b2f49b2001-06-08 00:21:52 +0000505** BTree (usually page 2) has no parent and so for that page,
506** pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000507**
drh72f82862001-05-24 21:06:34 +0000508** Return SQLITE_OK on success. If we see that the page does
509** not contained a well-formed database page, then return
510** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
511** guarantee that the page is well-formed. It only shows that
512** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000513*/
drh72f82862001-05-24 21:06:34 +0000514static int initPage(MemPage *pPage, Pgno pgnoThis, MemPage *pParent){
drh14acc042001-06-10 19:56:58 +0000515 int idx; /* An index into pPage->u.aDisk[] */
516 Cell *pCell; /* A pointer to a Cell in pPage->u.aDisk[] */
517 FreeBlk *pFBlk; /* A pointer to a free block in pPage->u.aDisk[] */
drh5e2f8b92001-05-28 00:41:15 +0000518 int sz; /* The size of a Cell in bytes */
519 int freeSpace; /* Amount of free space on the page */
drh2af926b2001-05-15 00:39:25 +0000520
drh5e2f8b92001-05-28 00:41:15 +0000521 if( pPage->pParent ){
522 assert( pPage->pParent==pParent );
523 return SQLITE_OK;
524 }
525 if( pParent ){
526 pPage->pParent = pParent;
527 sqlitepager_ref(pParent);
528 }
529 if( pPage->isInit ) return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +0000530 pPage->isInit = 1;
drh7e3b0a02001-04-28 16:52:40 +0000531 pPage->nCell = 0;
drh6019e162001-07-02 17:51:45 +0000532 freeSpace = USABLE_SPACE;
drh14acc042001-06-10 19:56:58 +0000533 idx = pPage->u.hdr.firstCell;
drh7e3b0a02001-04-28 16:52:40 +0000534 while( idx!=0 ){
drh8c42ca92001-06-22 19:15:00 +0000535 if( idx>SQLITE_PAGE_SIZE-MIN_CELL_SIZE ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000536 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh8c42ca92001-06-22 19:15:00 +0000537 if( idx!=ROUNDUP(idx) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000538 pCell = (Cell*)&pPage->u.aDisk[idx];
drh5e2f8b92001-05-28 00:41:15 +0000539 sz = cellSize(pCell);
540 if( idx+sz > SQLITE_PAGE_SIZE ) goto page_format_error;
541 freeSpace -= sz;
542 pPage->apCell[pPage->nCell++] = pCell;
drh3b7511c2001-05-26 13:15:44 +0000543 idx = pCell->h.iNext;
drh2af926b2001-05-15 00:39:25 +0000544 }
545 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +0000546 idx = pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000547 while( idx!=0 ){
548 if( idx>SQLITE_PAGE_SIZE-sizeof(FreeBlk) ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000549 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000550 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh2af926b2001-05-15 00:39:25 +0000551 pPage->nFree += pFBlk->iSize;
drh7c717f72001-06-24 20:39:41 +0000552 if( pFBlk->iNext>0 && pFBlk->iNext <= idx ) goto page_format_error;
drh2af926b2001-05-15 00:39:25 +0000553 idx = pFBlk->iNext;
drh7e3b0a02001-04-28 16:52:40 +0000554 }
drh8b2f49b2001-06-08 00:21:52 +0000555 if( pPage->nCell==0 && pPage->nFree==0 ){
556 /* As a special case, an uninitialized root page appears to be
557 ** an empty database */
558 return SQLITE_OK;
559 }
drh5e2f8b92001-05-28 00:41:15 +0000560 if( pPage->nFree!=freeSpace ) goto page_format_error;
drh7e3b0a02001-04-28 16:52:40 +0000561 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +0000562
563page_format_error:
564 return SQLITE_CORRUPT;
drh7e3b0a02001-04-28 16:52:40 +0000565}
566
567/*
drh8b2f49b2001-06-08 00:21:52 +0000568** Set up a raw page so that it looks like a database page holding
569** no entries.
drhbd03cae2001-06-02 02:40:57 +0000570*/
571static void zeroPage(MemPage *pPage){
572 PageHdr *pHdr;
573 FreeBlk *pFBlk;
drh6019e162001-07-02 17:51:45 +0000574 assert( sqlitepager_iswriteable(pPage) );
drhbd03cae2001-06-02 02:40:57 +0000575 memset(pPage, 0, SQLITE_PAGE_SIZE);
drh14acc042001-06-10 19:56:58 +0000576 pHdr = &pPage->u.hdr;
drhbd03cae2001-06-02 02:40:57 +0000577 pHdr->firstCell = 0;
578 pHdr->firstFree = sizeof(*pHdr);
579 pFBlk = (FreeBlk*)&pHdr[1];
580 pFBlk->iNext = 0;
581 pFBlk->iSize = SQLITE_PAGE_SIZE - sizeof(*pHdr);
drh8c42ca92001-06-22 19:15:00 +0000582 pPage->nFree = pFBlk->iSize;
583 pPage->nCell = 0;
584 pPage->isOverfull = 0;
drhbd03cae2001-06-02 02:40:57 +0000585}
586
587/*
drh72f82862001-05-24 21:06:34 +0000588** This routine is called when the reference count for a page
589** reaches zero. We need to unref the pParent pointer when that
590** happens.
591*/
592static void pageDestructor(void *pData){
593 MemPage *pPage = (MemPage*)pData;
594 if( pPage->pParent ){
595 MemPage *pParent = pPage->pParent;
596 pPage->pParent = 0;
597 sqlitepager_unref(pParent);
598 }
599}
600
601/*
drh306dc212001-05-21 13:45:10 +0000602** Open a new database.
603**
604** Actually, this routine just sets up the internal data structures
drh72f82862001-05-24 21:06:34 +0000605** for accessing the database. We do not open the database file
606** until the first page is loaded.
drh382c0242001-10-06 16:33:02 +0000607**
608** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +0000609** a new database with a random name is created. This randomly named
610** database file will be deleted when sqliteBtreeClose() is called.
drha059ad02001-04-17 20:09:11 +0000611*/
drh6019e162001-07-02 17:51:45 +0000612int sqliteBtreeOpen(
613 const char *zFilename, /* Name of the file containing the BTree database */
614 int mode, /* Not currently used */
615 int nCache, /* How many pages in the page cache */
616 Btree **ppBtree /* Pointer to new Btree object written here */
617){
drha059ad02001-04-17 20:09:11 +0000618 Btree *pBt;
drh8c42ca92001-06-22 19:15:00 +0000619 int rc;
drha059ad02001-04-17 20:09:11 +0000620
621 pBt = sqliteMalloc( sizeof(*pBt) );
622 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +0000623 *ppBtree = 0;
drha059ad02001-04-17 20:09:11 +0000624 return SQLITE_NOMEM;
625 }
drh6019e162001-07-02 17:51:45 +0000626 if( nCache<10 ) nCache = 10;
627 rc = sqlitepager_open(&pBt->pPager, zFilename, nCache, EXTRA_SIZE);
drha059ad02001-04-17 20:09:11 +0000628 if( rc!=SQLITE_OK ){
629 if( pBt->pPager ) sqlitepager_close(pBt->pPager);
630 sqliteFree(pBt);
631 *ppBtree = 0;
632 return rc;
633 }
drh72f82862001-05-24 21:06:34 +0000634 sqlitepager_set_destructor(pBt->pPager, pageDestructor);
drha059ad02001-04-17 20:09:11 +0000635 pBt->pCursor = 0;
636 pBt->page1 = 0;
drh5df72a52002-06-06 23:16:05 +0000637 pBt->readOnly = sqlitepager_isreadonly(pBt->pPager);
drhecdc7532001-09-23 02:35:53 +0000638 sqliteHashInit(&pBt->locks, SQLITE_HASH_INT, 0);
drha059ad02001-04-17 20:09:11 +0000639 *ppBtree = pBt;
640 return SQLITE_OK;
641}
642
643/*
644** Close an open database and invalidate all cursors.
645*/
646int sqliteBtreeClose(Btree *pBt){
647 while( pBt->pCursor ){
648 sqliteBtreeCloseCursor(pBt->pCursor);
649 }
650 sqlitepager_close(pBt->pPager);
drhecdc7532001-09-23 02:35:53 +0000651 sqliteHashClear(&pBt->locks);
drha059ad02001-04-17 20:09:11 +0000652 sqliteFree(pBt);
653 return SQLITE_OK;
654}
655
656/*
drh6446c4d2001-12-15 14:22:18 +0000657** Change the limit on the number of pages allowed the cache.
drhcd61c282002-03-06 22:01:34 +0000658**
659** The maximum number of cache pages is set to the absolute
660** value of mxPage. If mxPage is negative, the pager will
661** operate asynchronously - it will not stop to do fsync()s
662** to insure data is written to the disk surface before
663** continuing. Transactions still work if synchronous is off,
664** and the database cannot be corrupted if this program
665** crashes. But if the operating system crashes or there is
666** an abrupt power failure when synchronous is off, the database
667** could be left in an inconsistent and unrecoverable state.
668** Synchronous is on by default so database corruption is not
669** normally a worry.
drhf57b14a2001-09-14 18:54:08 +0000670*/
671int sqliteBtreeSetCacheSize(Btree *pBt, int mxPage){
672 sqlitepager_set_cachesize(pBt->pPager, mxPage);
673 return SQLITE_OK;
674}
675
676/*
drh306dc212001-05-21 13:45:10 +0000677** Get a reference to page1 of the database file. This will
678** also acquire a readlock on that file.
679**
680** SQLITE_OK is returned on success. If the file is not a
681** well-formed database file, then SQLITE_CORRUPT is returned.
682** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
683** is returned if we run out of memory. SQLITE_PROTOCOL is returned
684** if there is a locking protocol violation.
685*/
686static int lockBtree(Btree *pBt){
687 int rc;
688 if( pBt->page1 ) return SQLITE_OK;
drh8c42ca92001-06-22 19:15:00 +0000689 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pBt->page1);
drh306dc212001-05-21 13:45:10 +0000690 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +0000691
692 /* Do some checking to help insure the file we opened really is
693 ** a valid database file.
694 */
695 if( sqlitepager_pagecount(pBt->pPager)>0 ){
drhbd03cae2001-06-02 02:40:57 +0000696 PageOne *pP1 = pBt->page1;
drh8c42ca92001-06-22 19:15:00 +0000697 if( strcmp(pP1->zMagic,zMagicHeader)!=0 || pP1->iMagic!=MAGIC ){
drh306dc212001-05-21 13:45:10 +0000698 rc = SQLITE_CORRUPT;
drh72f82862001-05-24 21:06:34 +0000699 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +0000700 }
701 }
702 return rc;
703
drh72f82862001-05-24 21:06:34 +0000704page1_init_failed:
drh306dc212001-05-21 13:45:10 +0000705 sqlitepager_unref(pBt->page1);
706 pBt->page1 = 0;
drh72f82862001-05-24 21:06:34 +0000707 return rc;
drh306dc212001-05-21 13:45:10 +0000708}
709
710/*
drhb8ca3072001-12-05 00:21:20 +0000711** If there are no outstanding cursors and we are not in the middle
712** of a transaction but there is a read lock on the database, then
713** this routine unrefs the first page of the database file which
714** has the effect of releasing the read lock.
715**
716** If there are any outstanding cursors, this routine is a no-op.
717**
718** If there is a transaction in progress, this routine is a no-op.
719*/
720static void unlockBtreeIfUnused(Btree *pBt){
721 if( pBt->inTrans==0 && pBt->pCursor==0 && pBt->page1!=0 ){
722 sqlitepager_unref(pBt->page1);
723 pBt->page1 = 0;
724 pBt->inTrans = 0;
drh663fc632002-02-02 18:49:19 +0000725 pBt->inCkpt = 0;
drhb8ca3072001-12-05 00:21:20 +0000726 }
727}
728
729/*
drh8c42ca92001-06-22 19:15:00 +0000730** Create a new database by initializing the first two pages of the
731** file.
drh8b2f49b2001-06-08 00:21:52 +0000732*/
733static int newDatabase(Btree *pBt){
734 MemPage *pRoot;
735 PageOne *pP1;
drh8c42ca92001-06-22 19:15:00 +0000736 int rc;
drh7c717f72001-06-24 20:39:41 +0000737 if( sqlitepager_pagecount(pBt->pPager)>1 ) return SQLITE_OK;
drh8b2f49b2001-06-08 00:21:52 +0000738 pP1 = pBt->page1;
739 rc = sqlitepager_write(pBt->page1);
740 if( rc ) return rc;
drh8c42ca92001-06-22 19:15:00 +0000741 rc = sqlitepager_get(pBt->pPager, 2, (void**)&pRoot);
drh8b2f49b2001-06-08 00:21:52 +0000742 if( rc ) return rc;
743 rc = sqlitepager_write(pRoot);
744 if( rc ){
745 sqlitepager_unref(pRoot);
746 return rc;
747 }
748 strcpy(pP1->zMagic, zMagicHeader);
drh8c42ca92001-06-22 19:15:00 +0000749 pP1->iMagic = MAGIC;
drh8b2f49b2001-06-08 00:21:52 +0000750 zeroPage(pRoot);
751 sqlitepager_unref(pRoot);
752 return SQLITE_OK;
753}
754
755/*
drh72f82862001-05-24 21:06:34 +0000756** Attempt to start a new transaction.
drh8b2f49b2001-06-08 00:21:52 +0000757**
758** A transaction must be started before attempting any changes
759** to the database. None of the following routines will work
760** unless a transaction is started first:
761**
762** sqliteBtreeCreateTable()
drhc6b52df2002-01-04 03:09:29 +0000763** sqliteBtreeCreateIndex()
drh8b2f49b2001-06-08 00:21:52 +0000764** sqliteBtreeClearTable()
765** sqliteBtreeDropTable()
766** sqliteBtreeInsert()
767** sqliteBtreeDelete()
768** sqliteBtreeUpdateMeta()
drha059ad02001-04-17 20:09:11 +0000769*/
770int sqliteBtreeBeginTrans(Btree *pBt){
771 int rc;
772 if( pBt->inTrans ) return SQLITE_ERROR;
773 if( pBt->page1==0 ){
drh7e3b0a02001-04-28 16:52:40 +0000774 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +0000775 if( rc!=SQLITE_OK ){
776 return rc;
777 }
drha059ad02001-04-17 20:09:11 +0000778 }
drh5df72a52002-06-06 23:16:05 +0000779 if( pBt->readOnly ){
780 rc = SQLITE_OK;
781 }else{
782 rc = sqlitepager_begin(pBt->page1);
783 if( rc==SQLITE_OK ){
784 rc = newDatabase(pBt);
785 }
drha059ad02001-04-17 20:09:11 +0000786 }
drhb8ca3072001-12-05 00:21:20 +0000787 if( rc==SQLITE_OK ){
788 pBt->inTrans = 1;
drh663fc632002-02-02 18:49:19 +0000789 pBt->inCkpt = 0;
drhb8ca3072001-12-05 00:21:20 +0000790 }else{
791 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000792 }
drhb8ca3072001-12-05 00:21:20 +0000793 return rc;
drha059ad02001-04-17 20:09:11 +0000794}
795
796/*
drh2aa679f2001-06-25 02:11:07 +0000797** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +0000798**
799** This will release the write lock on the database file. If there
800** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000801*/
802int sqliteBtreeCommit(Btree *pBt){
803 int rc;
drh2aa679f2001-06-25 02:11:07 +0000804 if( pBt->inTrans==0 ) return SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +0000805 rc = pBt->readOnly ? SQLITE_OK : sqlitepager_commit(pBt->pPager);
drh7c717f72001-06-24 20:39:41 +0000806 pBt->inTrans = 0;
drh663fc632002-02-02 18:49:19 +0000807 pBt->inCkpt = 0;
drh5e00f6c2001-09-13 13:46:56 +0000808 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000809 return rc;
810}
811
812/*
drhecdc7532001-09-23 02:35:53 +0000813** Rollback the transaction in progress. All cursors will be
814** invalided by this operation. Any attempt to use a cursor
815** that was open at the beginning of this operation will result
816** in an error.
drh5e00f6c2001-09-13 13:46:56 +0000817**
818** This will release the write lock on the database file. If there
819** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000820*/
821int sqliteBtreeRollback(Btree *pBt){
822 int rc;
drhecdc7532001-09-23 02:35:53 +0000823 BtCursor *pCur;
drh7c717f72001-06-24 20:39:41 +0000824 if( pBt->inTrans==0 ) return SQLITE_OK;
825 pBt->inTrans = 0;
drh663fc632002-02-02 18:49:19 +0000826 pBt->inCkpt = 0;
drhecdc7532001-09-23 02:35:53 +0000827 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
828 if( pCur->pPage ){
829 sqlitepager_unref(pCur->pPage);
830 pCur->pPage = 0;
831 }
832 }
drh5df72a52002-06-06 23:16:05 +0000833 rc = pBt->readOnly ? SQLITE_OK : sqlitepager_rollback(pBt->pPager);
drh5e00f6c2001-09-13 13:46:56 +0000834 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000835 return rc;
836}
837
838/*
drh663fc632002-02-02 18:49:19 +0000839** Set the checkpoint for the current transaction. The checkpoint serves
840** as a sub-transaction that can be rolled back independently of the
841** main transaction. You must start a transaction before starting a
842** checkpoint. The checkpoint is ended automatically if the transaction
843** commits or rolls back.
844**
845** Only one checkpoint may be active at a time. It is an error to try
846** to start a new checkpoint if another checkpoint is already active.
847*/
848int sqliteBtreeBeginCkpt(Btree *pBt){
849 int rc;
drh0d65dc02002-02-03 00:56:09 +0000850 if( !pBt->inTrans || pBt->inCkpt ){
851 return SQLITE_ERROR;
852 }
drh5df72a52002-06-06 23:16:05 +0000853 rc = pBt->readOnly ? SQLITE_OK : sqlitepager_ckpt_begin(pBt->pPager);
drh663fc632002-02-02 18:49:19 +0000854 pBt->inCkpt = 1;
855 return rc;
856}
857
858
859/*
860** Commit a checkpoint to transaction currently in progress. If no
861** checkpoint is active, this is a no-op.
862*/
863int sqliteBtreeCommitCkpt(Btree *pBt){
864 int rc;
drh5df72a52002-06-06 23:16:05 +0000865 if( pBt->inCkpt && !pBt->readOnly ){
drh663fc632002-02-02 18:49:19 +0000866 rc = sqlitepager_ckpt_commit(pBt->pPager);
867 }else{
868 rc = SQLITE_OK;
869 }
drh0d65dc02002-02-03 00:56:09 +0000870 pBt->inCkpt = 0;
drh663fc632002-02-02 18:49:19 +0000871 return rc;
872}
873
874/*
875** Rollback the checkpoint to the current transaction. If there
876** is no active checkpoint or transaction, this routine is a no-op.
877**
878** All cursors will be invalided by this operation. Any attempt
879** to use a cursor that was open at the beginning of this operation
880** will result in an error.
881*/
882int sqliteBtreeRollbackCkpt(Btree *pBt){
883 int rc;
884 BtCursor *pCur;
drh5df72a52002-06-06 23:16:05 +0000885 if( pBt->inCkpt==0 || pBt->readOnly ) return SQLITE_OK;
drh663fc632002-02-02 18:49:19 +0000886 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
887 if( pCur->pPage ){
888 sqlitepager_unref(pCur->pPage);
889 pCur->pPage = 0;
890 }
891 }
892 rc = sqlitepager_ckpt_rollback(pBt->pPager);
drh0d65dc02002-02-03 00:56:09 +0000893 pBt->inCkpt = 0;
drh663fc632002-02-02 18:49:19 +0000894 return rc;
895}
896
897/*
drh8b2f49b2001-06-08 00:21:52 +0000898** Create a new cursor for the BTree whose root is on the page
899** iTable. The act of acquiring a cursor gets a read lock on
900** the database file.
drh1bee3d72001-10-15 00:44:35 +0000901**
902** If wrFlag==0, then the cursor can only be used for reading.
903** If wrFlag==1, then the cursor can be used for reading or writing.
904** A read/write cursor requires exclusive access to its table. There
drh6446c4d2001-12-15 14:22:18 +0000905** cannot be two or more cursors open on the same table if any one of
drh1bee3d72001-10-15 00:44:35 +0000906** cursors is a read/write cursor. But there can be two or more
907** read-only cursors open on the same table.
drh6446c4d2001-12-15 14:22:18 +0000908**
909** No checking is done to make sure that page iTable really is the
910** root page of a b-tree. If it is not, then the cursor acquired
911** will not work correctly.
drha059ad02001-04-17 20:09:11 +0000912*/
drhecdc7532001-09-23 02:35:53 +0000913int sqliteBtreeCursor(Btree *pBt, int iTable, int wrFlag, BtCursor **ppCur){
drha059ad02001-04-17 20:09:11 +0000914 int rc;
915 BtCursor *pCur;
drh5a2c2c22001-11-21 02:21:11 +0000916 ptr nLock;
drhecdc7532001-09-23 02:35:53 +0000917
drha059ad02001-04-17 20:09:11 +0000918 if( pBt->page1==0 ){
919 rc = lockBtree(pBt);
920 if( rc!=SQLITE_OK ){
921 *ppCur = 0;
922 return rc;
923 }
924 }
drh5df72a52002-06-06 23:16:05 +0000925 if( wrFlag && pBt->readOnly ){
926 *ppCur = 0;
927 return SQLITE_READONLY;
928 }
drha059ad02001-04-17 20:09:11 +0000929 pCur = sqliteMalloc( sizeof(*pCur) );
930 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +0000931 rc = SQLITE_NOMEM;
932 goto create_cursor_exception;
933 }
drh8b2f49b2001-06-08 00:21:52 +0000934 pCur->pgnoRoot = (Pgno)iTable;
drh8c42ca92001-06-22 19:15:00 +0000935 rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +0000936 if( rc!=SQLITE_OK ){
937 goto create_cursor_exception;
938 }
drh8b2f49b2001-06-08 00:21:52 +0000939 rc = initPage(pCur->pPage, pCur->pgnoRoot, 0);
drhbd03cae2001-06-02 02:40:57 +0000940 if( rc!=SQLITE_OK ){
941 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +0000942 }
drh5a2c2c22001-11-21 02:21:11 +0000943 nLock = (ptr)sqliteHashFind(&pBt->locks, 0, iTable);
drhecdc7532001-09-23 02:35:53 +0000944 if( nLock<0 || (nLock>0 && wrFlag) ){
945 rc = SQLITE_LOCKED;
946 goto create_cursor_exception;
947 }
948 nLock = wrFlag ? -1 : nLock+1;
949 sqliteHashInsert(&pBt->locks, 0, iTable, (void*)nLock);
drh14acc042001-06-10 19:56:58 +0000950 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +0000951 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +0000952 pCur->idx = 0;
drha059ad02001-04-17 20:09:11 +0000953 pCur->pNext = pBt->pCursor;
954 if( pCur->pNext ){
955 pCur->pNext->pPrev = pCur;
956 }
drh14acc042001-06-10 19:56:58 +0000957 pCur->pPrev = 0;
drha059ad02001-04-17 20:09:11 +0000958 pBt->pCursor = pCur;
drh2af926b2001-05-15 00:39:25 +0000959 *ppCur = pCur;
960 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +0000961
962create_cursor_exception:
963 *ppCur = 0;
964 if( pCur ){
965 if( pCur->pPage ) sqlitepager_unref(pCur->pPage);
966 sqliteFree(pCur);
967 }
drh5e00f6c2001-09-13 13:46:56 +0000968 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +0000969 return rc;
drha059ad02001-04-17 20:09:11 +0000970}
971
972/*
drh5e00f6c2001-09-13 13:46:56 +0000973** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +0000974** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +0000975*/
976int sqliteBtreeCloseCursor(BtCursor *pCur){
drh5a2c2c22001-11-21 02:21:11 +0000977 ptr nLock;
drha059ad02001-04-17 20:09:11 +0000978 Btree *pBt = pCur->pBt;
drha059ad02001-04-17 20:09:11 +0000979 if( pCur->pPrev ){
980 pCur->pPrev->pNext = pCur->pNext;
981 }else{
982 pBt->pCursor = pCur->pNext;
983 }
984 if( pCur->pNext ){
985 pCur->pNext->pPrev = pCur->pPrev;
986 }
drhecdc7532001-09-23 02:35:53 +0000987 if( pCur->pPage ){
988 sqlitepager_unref(pCur->pPage);
989 }
drh5e00f6c2001-09-13 13:46:56 +0000990 unlockBtreeIfUnused(pBt);
drh5a2c2c22001-11-21 02:21:11 +0000991 nLock = (ptr)sqliteHashFind(&pBt->locks, 0, pCur->pgnoRoot);
drh6d4abfb2001-10-22 02:58:08 +0000992 assert( nLock!=0 || sqlite_malloc_failed );
drhecdc7532001-09-23 02:35:53 +0000993 nLock = nLock<0 ? 0 : nLock-1;
994 sqliteHashInsert(&pBt->locks, 0, pCur->pgnoRoot, (void*)nLock);
drha059ad02001-04-17 20:09:11 +0000995 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +0000996 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +0000997}
998
drh7e3b0a02001-04-28 16:52:40 +0000999/*
drh5e2f8b92001-05-28 00:41:15 +00001000** Make a temporary cursor by filling in the fields of pTempCur.
1001** The temporary cursor is not on the cursor list for the Btree.
1002*/
drh14acc042001-06-10 19:56:58 +00001003static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00001004 memcpy(pTempCur, pCur, sizeof(*pCur));
1005 pTempCur->pNext = 0;
1006 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00001007 if( pTempCur->pPage ){
1008 sqlitepager_ref(pTempCur->pPage);
1009 }
drh5e2f8b92001-05-28 00:41:15 +00001010}
1011
1012/*
drhbd03cae2001-06-02 02:40:57 +00001013** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00001014** function above.
1015*/
drh14acc042001-06-10 19:56:58 +00001016static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00001017 if( pCur->pPage ){
1018 sqlitepager_unref(pCur->pPage);
1019 }
drh5e2f8b92001-05-28 00:41:15 +00001020}
1021
1022/*
drhbd03cae2001-06-02 02:40:57 +00001023** Set *pSize to the number of bytes of key in the entry the
1024** cursor currently points to. Always return SQLITE_OK.
1025** Failure is not possible. If the cursor is not currently
1026** pointing to an entry (which can happen, for example, if
1027** the database is empty) then *pSize is set to 0.
drh7e3b0a02001-04-28 16:52:40 +00001028*/
drh72f82862001-05-24 21:06:34 +00001029int sqliteBtreeKeySize(BtCursor *pCur, int *pSize){
drh2af926b2001-05-15 00:39:25 +00001030 Cell *pCell;
1031 MemPage *pPage;
1032
1033 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001034 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh72f82862001-05-24 21:06:34 +00001035 *pSize = 0;
1036 }else{
drh5e2f8b92001-05-28 00:41:15 +00001037 pCell = pPage->apCell[pCur->idx];
drh80ff32f2001-11-04 18:32:46 +00001038 *pSize = NKEY(pCell->h);
drh72f82862001-05-24 21:06:34 +00001039 }
1040 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00001041}
drh2af926b2001-05-15 00:39:25 +00001042
drh72f82862001-05-24 21:06:34 +00001043/*
1044** Read payload information from the entry that the pCur cursor is
1045** pointing to. Begin reading the payload at "offset" and read
1046** a total of "amt" bytes. Put the result in zBuf.
1047**
1048** This routine does not make a distinction between key and data.
1049** It just reads bytes from the payload area.
1050*/
drh2af926b2001-05-15 00:39:25 +00001051static int getPayload(BtCursor *pCur, int offset, int amt, char *zBuf){
drh5e2f8b92001-05-28 00:41:15 +00001052 char *aPayload;
drh2af926b2001-05-15 00:39:25 +00001053 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +00001054 int rc;
drh72f82862001-05-24 21:06:34 +00001055 assert( pCur!=0 && pCur->pPage!=0 );
drh8c42ca92001-06-22 19:15:00 +00001056 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
1057 aPayload = pCur->pPage->apCell[pCur->idx]->aPayload;
drh2af926b2001-05-15 00:39:25 +00001058 if( offset<MX_LOCAL_PAYLOAD ){
1059 int a = amt;
1060 if( a+offset>MX_LOCAL_PAYLOAD ){
1061 a = MX_LOCAL_PAYLOAD - offset;
1062 }
drh5e2f8b92001-05-28 00:41:15 +00001063 memcpy(zBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +00001064 if( a==amt ){
1065 return SQLITE_OK;
1066 }
drh2aa679f2001-06-25 02:11:07 +00001067 offset = 0;
drh2af926b2001-05-15 00:39:25 +00001068 zBuf += a;
1069 amt -= a;
drhdd793422001-06-28 01:54:48 +00001070 }else{
1071 offset -= MX_LOCAL_PAYLOAD;
drhbd03cae2001-06-02 02:40:57 +00001072 }
1073 if( amt>0 ){
drh8c42ca92001-06-22 19:15:00 +00001074 nextPage = pCur->pPage->apCell[pCur->idx]->ovfl;
drh2af926b2001-05-15 00:39:25 +00001075 }
1076 while( amt>0 && nextPage ){
1077 OverflowPage *pOvfl;
drh8c42ca92001-06-22 19:15:00 +00001078 rc = sqlitepager_get(pCur->pBt->pPager, nextPage, (void**)&pOvfl);
drh2af926b2001-05-15 00:39:25 +00001079 if( rc!=0 ){
1080 return rc;
1081 }
drh14acc042001-06-10 19:56:58 +00001082 nextPage = pOvfl->iNext;
drh2af926b2001-05-15 00:39:25 +00001083 if( offset<OVERFLOW_SIZE ){
1084 int a = amt;
1085 if( a + offset > OVERFLOW_SIZE ){
1086 a = OVERFLOW_SIZE - offset;
1087 }
drh5e2f8b92001-05-28 00:41:15 +00001088 memcpy(zBuf, &pOvfl->aPayload[offset], a);
drh2aa679f2001-06-25 02:11:07 +00001089 offset = 0;
drh2af926b2001-05-15 00:39:25 +00001090 amt -= a;
1091 zBuf += a;
drh2aa679f2001-06-25 02:11:07 +00001092 }else{
1093 offset -= OVERFLOW_SIZE;
drh2af926b2001-05-15 00:39:25 +00001094 }
1095 sqlitepager_unref(pOvfl);
1096 }
drha7fcb052001-12-14 15:09:55 +00001097 if( amt>0 ){
1098 return SQLITE_CORRUPT;
1099 }
1100 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00001101}
1102
drh72f82862001-05-24 21:06:34 +00001103/*
drh5e00f6c2001-09-13 13:46:56 +00001104** Read part of the key associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +00001105** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +00001106** begins at "offset". The number of bytes actually read is
1107** returned. The amount returned will be smaller than the
1108** amount requested if there are not enough bytes in the key
1109** to satisfy the request.
drh72f82862001-05-24 21:06:34 +00001110*/
1111int sqliteBtreeKey(BtCursor *pCur, int offset, int amt, char *zBuf){
1112 Cell *pCell;
1113 MemPage *pPage;
drha059ad02001-04-17 20:09:11 +00001114
drh5e00f6c2001-09-13 13:46:56 +00001115 if( amt<0 ) return 0;
1116 if( offset<0 ) return 0;
1117 if( amt==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001118 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001119 if( pPage==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001120 if( pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +00001121 return 0;
drh72f82862001-05-24 21:06:34 +00001122 }
drh5e2f8b92001-05-28 00:41:15 +00001123 pCell = pPage->apCell[pCur->idx];
drh80ff32f2001-11-04 18:32:46 +00001124 if( amt+offset > NKEY(pCell->h) ){
1125 amt = NKEY(pCell->h) - offset;
drh5e00f6c2001-09-13 13:46:56 +00001126 if( amt<=0 ){
1127 return 0;
1128 }
drhbd03cae2001-06-02 02:40:57 +00001129 }
drh5e00f6c2001-09-13 13:46:56 +00001130 getPayload(pCur, offset, amt, zBuf);
1131 return amt;
drh72f82862001-05-24 21:06:34 +00001132}
1133
1134/*
drhbd03cae2001-06-02 02:40:57 +00001135** Set *pSize to the number of bytes of data in the entry the
1136** cursor currently points to. Always return SQLITE_OK.
1137** Failure is not possible. If the cursor is not currently
1138** pointing to an entry (which can happen, for example, if
1139** the database is empty) then *pSize is set to 0.
drh72f82862001-05-24 21:06:34 +00001140*/
1141int sqliteBtreeDataSize(BtCursor *pCur, int *pSize){
1142 Cell *pCell;
1143 MemPage *pPage;
1144
1145 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001146 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh72f82862001-05-24 21:06:34 +00001147 *pSize = 0;
1148 }else{
drh5e2f8b92001-05-28 00:41:15 +00001149 pCell = pPage->apCell[pCur->idx];
drh80ff32f2001-11-04 18:32:46 +00001150 *pSize = NDATA(pCell->h);
drh72f82862001-05-24 21:06:34 +00001151 }
1152 return SQLITE_OK;
1153}
1154
1155/*
drh5e00f6c2001-09-13 13:46:56 +00001156** Read part of the data associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +00001157** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +00001158** begins at "offset". The number of bytes actually read is
1159** returned. The amount returned will be smaller than the
1160** amount requested if there are not enough bytes in the data
1161** to satisfy the request.
drh72f82862001-05-24 21:06:34 +00001162*/
1163int sqliteBtreeData(BtCursor *pCur, int offset, int amt, char *zBuf){
1164 Cell *pCell;
1165 MemPage *pPage;
1166
drh5e00f6c2001-09-13 13:46:56 +00001167 if( amt<0 ) return 0;
1168 if( offset<0 ) return 0;
1169 if( amt==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001170 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001171 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +00001172 return 0;
drh72f82862001-05-24 21:06:34 +00001173 }
drh5e2f8b92001-05-28 00:41:15 +00001174 pCell = pPage->apCell[pCur->idx];
drh80ff32f2001-11-04 18:32:46 +00001175 if( amt+offset > NDATA(pCell->h) ){
1176 amt = NDATA(pCell->h) - offset;
drh5e00f6c2001-09-13 13:46:56 +00001177 if( amt<=0 ){
1178 return 0;
1179 }
drhbd03cae2001-06-02 02:40:57 +00001180 }
drh80ff32f2001-11-04 18:32:46 +00001181 getPayload(pCur, offset + NKEY(pCell->h), amt, zBuf);
drh5e00f6c2001-09-13 13:46:56 +00001182 return amt;
drh72f82862001-05-24 21:06:34 +00001183}
drha059ad02001-04-17 20:09:11 +00001184
drh2af926b2001-05-15 00:39:25 +00001185/*
drh8721ce42001-11-07 14:22:00 +00001186** Compare an external key against the key on the entry that pCur points to.
1187**
1188** The external key is pKey and is nKey bytes long. The last nIgnore bytes
1189** of the key associated with pCur are ignored, as if they do not exist.
1190** (The normal case is for nIgnore to be zero in which case the entire
1191** internal key is used in the comparison.)
1192**
1193** The comparison result is written to *pRes as follows:
drh2af926b2001-05-15 00:39:25 +00001194**
drh717e6402001-09-27 03:22:32 +00001195** *pRes<0 This means pCur<pKey
1196**
1197** *pRes==0 This means pCur==pKey for all nKey bytes
1198**
1199** *pRes>0 This means pCur>pKey
1200**
drh8721ce42001-11-07 14:22:00 +00001201** When one key is an exact prefix of the other, the shorter key is
1202** considered less than the longer one. In order to be equal the
1203** keys must be exactly the same length. (The length of the pCur key
1204** is the actual key length minus nIgnore bytes.)
drh2af926b2001-05-15 00:39:25 +00001205*/
drh717e6402001-09-27 03:22:32 +00001206int sqliteBtreeKeyCompare(
drh8721ce42001-11-07 14:22:00 +00001207 BtCursor *pCur, /* Pointer to entry to compare against */
1208 const void *pKey, /* Key to compare against entry that pCur points to */
1209 int nKey, /* Number of bytes in pKey */
1210 int nIgnore, /* Ignore this many bytes at the end of pCur */
1211 int *pResult /* Write the result here */
drh5c4d9702001-08-20 00:33:58 +00001212){
drh2af926b2001-05-15 00:39:25 +00001213 Pgno nextPage;
drh8721ce42001-11-07 14:22:00 +00001214 int n, c, rc, nLocal;
drh2af926b2001-05-15 00:39:25 +00001215 Cell *pCell;
drh717e6402001-09-27 03:22:32 +00001216 const char *zKey = (const char*)pKey;
drh2af926b2001-05-15 00:39:25 +00001217
1218 assert( pCur->pPage );
1219 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drhbd03cae2001-06-02 02:40:57 +00001220 pCell = pCur->pPage->apCell[pCur->idx];
drh8721ce42001-11-07 14:22:00 +00001221 nLocal = NKEY(pCell->h) - nIgnore;
1222 if( nLocal<0 ) nLocal = 0;
1223 n = nKey<nLocal ? nKey : nLocal;
drh2af926b2001-05-15 00:39:25 +00001224 if( n>MX_LOCAL_PAYLOAD ){
1225 n = MX_LOCAL_PAYLOAD;
1226 }
drh717e6402001-09-27 03:22:32 +00001227 c = memcmp(pCell->aPayload, zKey, n);
drh2af926b2001-05-15 00:39:25 +00001228 if( c!=0 ){
1229 *pResult = c;
1230 return SQLITE_OK;
1231 }
drh717e6402001-09-27 03:22:32 +00001232 zKey += n;
drh2af926b2001-05-15 00:39:25 +00001233 nKey -= n;
drh8721ce42001-11-07 14:22:00 +00001234 nLocal -= n;
drh3b7511c2001-05-26 13:15:44 +00001235 nextPage = pCell->ovfl;
drh8721ce42001-11-07 14:22:00 +00001236 while( nKey>0 && nLocal>0 ){
drh2af926b2001-05-15 00:39:25 +00001237 OverflowPage *pOvfl;
1238 if( nextPage==0 ){
1239 return SQLITE_CORRUPT;
1240 }
drh8c42ca92001-06-22 19:15:00 +00001241 rc = sqlitepager_get(pCur->pBt->pPager, nextPage, (void**)&pOvfl);
drh72f82862001-05-24 21:06:34 +00001242 if( rc ){
drh2af926b2001-05-15 00:39:25 +00001243 return rc;
1244 }
drh14acc042001-06-10 19:56:58 +00001245 nextPage = pOvfl->iNext;
drh8721ce42001-11-07 14:22:00 +00001246 n = nKey<nLocal ? nKey : nLocal;
drh2af926b2001-05-15 00:39:25 +00001247 if( n>OVERFLOW_SIZE ){
1248 n = OVERFLOW_SIZE;
1249 }
drh717e6402001-09-27 03:22:32 +00001250 c = memcmp(pOvfl->aPayload, zKey, n);
drh2af926b2001-05-15 00:39:25 +00001251 sqlitepager_unref(pOvfl);
1252 if( c!=0 ){
1253 *pResult = c;
1254 return SQLITE_OK;
1255 }
1256 nKey -= n;
drh8721ce42001-11-07 14:22:00 +00001257 nLocal -= n;
drh717e6402001-09-27 03:22:32 +00001258 zKey += n;
drh2af926b2001-05-15 00:39:25 +00001259 }
drh717e6402001-09-27 03:22:32 +00001260 if( c==0 ){
drh8721ce42001-11-07 14:22:00 +00001261 c = nLocal - nKey;
drh717e6402001-09-27 03:22:32 +00001262 }
drh2af926b2001-05-15 00:39:25 +00001263 *pResult = c;
1264 return SQLITE_OK;
1265}
1266
drh72f82862001-05-24 21:06:34 +00001267/*
1268** Move the cursor down to a new child page.
1269*/
drh5e2f8b92001-05-28 00:41:15 +00001270static int moveToChild(BtCursor *pCur, int newPgno){
drh72f82862001-05-24 21:06:34 +00001271 int rc;
1272 MemPage *pNewPage;
1273
drh8c42ca92001-06-22 19:15:00 +00001274 rc = sqlitepager_get(pCur->pBt->pPager, newPgno, (void**)&pNewPage);
drh6019e162001-07-02 17:51:45 +00001275 if( rc ) return rc;
1276 rc = initPage(pNewPage, newPgno, pCur->pPage);
1277 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001278 sqlitepager_unref(pCur->pPage);
1279 pCur->pPage = pNewPage;
1280 pCur->idx = 0;
1281 return SQLITE_OK;
1282}
1283
1284/*
drh5e2f8b92001-05-28 00:41:15 +00001285** Move the cursor up to the parent page.
1286**
1287** pCur->idx is set to the cell index that contains the pointer
1288** to the page we are coming from. If we are coming from the
1289** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00001290** the largest cell index.
drh72f82862001-05-24 21:06:34 +00001291*/
drh5e2f8b92001-05-28 00:41:15 +00001292static int moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001293 Pgno oldPgno;
1294 MemPage *pParent;
drh8c42ca92001-06-22 19:15:00 +00001295 int i;
drh72f82862001-05-24 21:06:34 +00001296 pParent = pCur->pPage->pParent;
drhbd03cae2001-06-02 02:40:57 +00001297 if( pParent==0 ) return SQLITE_INTERNAL;
drh72f82862001-05-24 21:06:34 +00001298 oldPgno = sqlitepager_pagenumber(pCur->pPage);
drh72f82862001-05-24 21:06:34 +00001299 sqlitepager_ref(pParent);
1300 sqlitepager_unref(pCur->pPage);
1301 pCur->pPage = pParent;
drh8c42ca92001-06-22 19:15:00 +00001302 pCur->idx = pParent->nCell;
1303 for(i=0; i<pParent->nCell; i++){
1304 if( pParent->apCell[i]->h.leftChild==oldPgno ){
drh72f82862001-05-24 21:06:34 +00001305 pCur->idx = i;
1306 break;
1307 }
1308 }
drh5e2f8b92001-05-28 00:41:15 +00001309 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00001310}
1311
1312/*
1313** Move the cursor to the root page
1314*/
drh5e2f8b92001-05-28 00:41:15 +00001315static int moveToRoot(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001316 MemPage *pNew;
drhbd03cae2001-06-02 02:40:57 +00001317 int rc;
1318
drh8c42ca92001-06-22 19:15:00 +00001319 rc = sqlitepager_get(pCur->pBt->pPager, pCur->pgnoRoot, (void**)&pNew);
drhbd03cae2001-06-02 02:40:57 +00001320 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00001321 rc = initPage(pNew, pCur->pgnoRoot, 0);
1322 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001323 sqlitepager_unref(pCur->pPage);
1324 pCur->pPage = pNew;
1325 pCur->idx = 0;
1326 return SQLITE_OK;
1327}
drh2af926b2001-05-15 00:39:25 +00001328
drh5e2f8b92001-05-28 00:41:15 +00001329/*
1330** Move the cursor down to the left-most leaf entry beneath the
1331** entry to which it is currently pointing.
1332*/
1333static int moveToLeftmost(BtCursor *pCur){
1334 Pgno pgno;
1335 int rc;
1336
1337 while( (pgno = pCur->pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
1338 rc = moveToChild(pCur, pgno);
1339 if( rc ) return rc;
1340 }
1341 return SQLITE_OK;
1342}
1343
drh5e00f6c2001-09-13 13:46:56 +00001344/* Move the cursor to the first entry in the table. Return SQLITE_OK
1345** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00001346** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00001347*/
1348int sqliteBtreeFirst(BtCursor *pCur, int *pRes){
1349 int rc;
drhecdc7532001-09-23 02:35:53 +00001350 if( pCur->pPage==0 ) return SQLITE_ABORT;
drh5e00f6c2001-09-13 13:46:56 +00001351 rc = moveToRoot(pCur);
1352 if( rc ) return rc;
1353 if( pCur->pPage->nCell==0 ){
1354 *pRes = 1;
1355 return SQLITE_OK;
1356 }
1357 *pRes = 0;
1358 rc = moveToLeftmost(pCur);
drh0ce92ed2001-12-15 02:47:28 +00001359 pCur->bSkipNext = 0;
drh5e00f6c2001-09-13 13:46:56 +00001360 return rc;
1361}
drh5e2f8b92001-05-28 00:41:15 +00001362
drh9562b552002-02-19 15:00:07 +00001363/* Move the cursor to the last entry in the table. Return SQLITE_OK
1364** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00001365** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00001366*/
1367int sqliteBtreeLast(BtCursor *pCur, int *pRes){
1368 int rc;
1369 Pgno pgno;
1370 if( pCur->pPage==0 ) return SQLITE_ABORT;
1371 rc = moveToRoot(pCur);
1372 if( rc ) return rc;
drh7aa128d2002-06-21 13:09:16 +00001373 assert( pCur->pPage->isInit );
drh9562b552002-02-19 15:00:07 +00001374 if( pCur->pPage->nCell==0 ){
1375 *pRes = 1;
1376 return SQLITE_OK;
1377 }
1378 *pRes = 0;
1379 while( (pgno = pCur->pPage->u.hdr.rightChild)!=0 ){
1380 rc = moveToChild(pCur, pgno);
1381 if( rc ) return rc;
1382 }
1383 pCur->idx = pCur->pPage->nCell-1;
1384 pCur->bSkipNext = 0;
1385 return rc;
1386}
1387
drha059ad02001-04-17 20:09:11 +00001388/* Move the cursor so that it points to an entry near pKey.
drh72f82862001-05-24 21:06:34 +00001389** Return a success code.
1390**
drh5e2f8b92001-05-28 00:41:15 +00001391** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00001392** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00001393** were present. The cursor might point to an entry that comes
1394** before or after the key.
1395**
drhbd03cae2001-06-02 02:40:57 +00001396** The result of comparing the key with the entry to which the
1397** cursor is left pointing is stored in pCur->iMatch. The same
1398** value is also written to *pRes if pRes!=NULL. The meaning of
1399** this value is as follows:
1400**
1401** *pRes<0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001402** is smaller than pKey.
drhbd03cae2001-06-02 02:40:57 +00001403**
1404** *pRes==0 The cursor is left pointing at an entry that
1405** exactly matches pKey.
1406**
1407** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001408** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00001409*/
drh5c4d9702001-08-20 00:33:58 +00001410int sqliteBtreeMoveto(BtCursor *pCur, const void *pKey, int nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00001411 int rc;
drhecdc7532001-09-23 02:35:53 +00001412 if( pCur->pPage==0 ) return SQLITE_ABORT;
drh7c717f72001-06-24 20:39:41 +00001413 pCur->bSkipNext = 0;
drh5e2f8b92001-05-28 00:41:15 +00001414 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00001415 if( rc ) return rc;
1416 for(;;){
1417 int lwr, upr;
1418 Pgno chldPg;
1419 MemPage *pPage = pCur->pPage;
drh8b2f49b2001-06-08 00:21:52 +00001420 int c = -1;
drh72f82862001-05-24 21:06:34 +00001421 lwr = 0;
1422 upr = pPage->nCell-1;
1423 while( lwr<=upr ){
drh72f82862001-05-24 21:06:34 +00001424 pCur->idx = (lwr+upr)/2;
drh8721ce42001-11-07 14:22:00 +00001425 rc = sqliteBtreeKeyCompare(pCur, pKey, nKey, 0, &c);
drh72f82862001-05-24 21:06:34 +00001426 if( rc ) return rc;
1427 if( c==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001428 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001429 if( pRes ) *pRes = 0;
1430 return SQLITE_OK;
1431 }
1432 if( c<0 ){
1433 lwr = pCur->idx+1;
1434 }else{
1435 upr = pCur->idx-1;
1436 }
1437 }
1438 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00001439 assert( pPage->isInit );
drh72f82862001-05-24 21:06:34 +00001440 if( lwr>=pPage->nCell ){
drh14acc042001-06-10 19:56:58 +00001441 chldPg = pPage->u.hdr.rightChild;
drh72f82862001-05-24 21:06:34 +00001442 }else{
drh5e2f8b92001-05-28 00:41:15 +00001443 chldPg = pPage->apCell[lwr]->h.leftChild;
drh72f82862001-05-24 21:06:34 +00001444 }
1445 if( chldPg==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001446 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001447 if( pRes ) *pRes = c;
1448 return SQLITE_OK;
1449 }
drh5e2f8b92001-05-28 00:41:15 +00001450 rc = moveToChild(pCur, chldPg);
drh72f82862001-05-24 21:06:34 +00001451 if( rc ) return rc;
1452 }
drhbd03cae2001-06-02 02:40:57 +00001453 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00001454}
1455
1456/*
drhbd03cae2001-06-02 02:40:57 +00001457** Advance the cursor to the next entry in the database. If
1458** successful and pRes!=NULL then set *pRes=0. If the cursor
1459** was already pointing to the last entry in the database before
1460** this routine was called, then set *pRes=1 if pRes!=NULL.
drh72f82862001-05-24 21:06:34 +00001461*/
1462int sqliteBtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00001463 int rc;
drhecdc7532001-09-23 02:35:53 +00001464 if( pCur->pPage==0 ){
drh1bee3d72001-10-15 00:44:35 +00001465 if( pRes ) *pRes = 1;
drhecdc7532001-09-23 02:35:53 +00001466 return SQLITE_ABORT;
1467 }
drh7aa128d2002-06-21 13:09:16 +00001468 assert( pCur->pPage->isInit );
drhf5bf0a72001-11-23 00:24:12 +00001469 if( pCur->bSkipNext && pCur->idx<pCur->pPage->nCell ){
drh5e2f8b92001-05-28 00:41:15 +00001470 pCur->bSkipNext = 0;
drh72f82862001-05-24 21:06:34 +00001471 if( pRes ) *pRes = 0;
1472 return SQLITE_OK;
1473 }
drh72f82862001-05-24 21:06:34 +00001474 pCur->idx++;
drh5e2f8b92001-05-28 00:41:15 +00001475 if( pCur->idx>=pCur->pPage->nCell ){
drh8c42ca92001-06-22 19:15:00 +00001476 if( pCur->pPage->u.hdr.rightChild ){
1477 rc = moveToChild(pCur, pCur->pPage->u.hdr.rightChild);
drh5e2f8b92001-05-28 00:41:15 +00001478 if( rc ) return rc;
1479 rc = moveToLeftmost(pCur);
1480 if( rc ) return rc;
1481 if( pRes ) *pRes = 0;
drh72f82862001-05-24 21:06:34 +00001482 return SQLITE_OK;
1483 }
drh5e2f8b92001-05-28 00:41:15 +00001484 do{
drh8c42ca92001-06-22 19:15:00 +00001485 if( pCur->pPage->pParent==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001486 if( pRes ) *pRes = 1;
1487 return SQLITE_OK;
1488 }
1489 rc = moveToParent(pCur);
1490 if( rc ) return rc;
1491 }while( pCur->idx>=pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00001492 if( pRes ) *pRes = 0;
1493 return SQLITE_OK;
1494 }
drh5e2f8b92001-05-28 00:41:15 +00001495 rc = moveToLeftmost(pCur);
1496 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001497 if( pRes ) *pRes = 0;
1498 return SQLITE_OK;
1499}
1500
drh3b7511c2001-05-26 13:15:44 +00001501/*
1502** Allocate a new page from the database file.
1503**
1504** The new page is marked as dirty. (In other words, sqlitepager_write()
1505** has already been called on the new page.) The new page has also
1506** been referenced and the calling routine is responsible for calling
1507** sqlitepager_unref() on the new page when it is done.
1508**
1509** SQLITE_OK is returned on success. Any other return value indicates
1510** an error. *ppPage and *pPgno are undefined in the event of an error.
1511** Do not invoke sqlitepager_unref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00001512**
1513** If the "near" parameter is not 0, then a (feeble) effort is made to
1514** locate a page close to the page number "near". This can be used in an
1515** attempt to keep related pages close to each other in the database file,
1516** which in turn can make database access faster.
drh3b7511c2001-05-26 13:15:44 +00001517*/
drhbea00b92002-07-08 10:59:50 +00001518static int allocatePage(Btree *pBt, MemPage **ppPage, Pgno *pPgno, Pgno near){
drhbd03cae2001-06-02 02:40:57 +00001519 PageOne *pPage1 = pBt->page1;
drh8c42ca92001-06-22 19:15:00 +00001520 int rc;
drh3b7511c2001-05-26 13:15:44 +00001521 if( pPage1->freeList ){
1522 OverflowPage *pOvfl;
drh30e58752002-03-02 20:41:57 +00001523 FreelistInfo *pInfo;
1524
drh3b7511c2001-05-26 13:15:44 +00001525 rc = sqlitepager_write(pPage1);
1526 if( rc ) return rc;
drh30e58752002-03-02 20:41:57 +00001527 pPage1->nFree--;
drh8c42ca92001-06-22 19:15:00 +00001528 rc = sqlitepager_get(pBt->pPager, pPage1->freeList, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001529 if( rc ) return rc;
1530 rc = sqlitepager_write(pOvfl);
1531 if( rc ){
1532 sqlitepager_unref(pOvfl);
1533 return rc;
1534 }
drh30e58752002-03-02 20:41:57 +00001535 pInfo = (FreelistInfo*)pOvfl->aPayload;
1536 if( pInfo->nFree==0 ){
1537 *pPgno = pPage1->freeList;
1538 pPage1->freeList = pOvfl->iNext;
1539 *ppPage = (MemPage*)pOvfl;
1540 }else{
drhbea00b92002-07-08 10:59:50 +00001541 int closest;
1542 if( pInfo->nFree>1 && near>0 ){
1543 int i, dist;
1544 closest = 0;
1545 dist = pInfo->aFree[0] - near;
1546 if( dist<0 ) dist = -dist;
1547 for(i=1; i<pInfo->nFree; i++){
1548 int d2 = pInfo->aFree[i] - near;
1549 if( d2<0 ) d2 = -d2;
1550 if( d2<dist ) closest = i;
1551 }
1552 }else{
1553 closest = 0;
1554 }
drh30e58752002-03-02 20:41:57 +00001555 pInfo->nFree--;
drhbea00b92002-07-08 10:59:50 +00001556 *pPgno = pInfo->aFree[closest];
1557 pInfo->aFree[closest] = pInfo->aFree[pInfo->nFree];
drh30e58752002-03-02 20:41:57 +00001558 rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
1559 sqlitepager_unref(pOvfl);
1560 if( rc==SQLITE_OK ){
1561 sqlitepager_dont_rollback(*ppPage);
1562 rc = sqlitepager_write(*ppPage);
1563 }
1564 }
drh3b7511c2001-05-26 13:15:44 +00001565 }else{
drh2aa679f2001-06-25 02:11:07 +00001566 *pPgno = sqlitepager_pagecount(pBt->pPager) + 1;
drh8c42ca92001-06-22 19:15:00 +00001567 rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
drh3b7511c2001-05-26 13:15:44 +00001568 if( rc ) return rc;
1569 rc = sqlitepager_write(*ppPage);
1570 }
1571 return rc;
1572}
1573
1574/*
1575** Add a page of the database file to the freelist. Either pgno or
1576** pPage but not both may be 0.
drh5e2f8b92001-05-28 00:41:15 +00001577**
drhdd793422001-06-28 01:54:48 +00001578** sqlitepager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00001579*/
1580static int freePage(Btree *pBt, void *pPage, Pgno pgno){
drhbd03cae2001-06-02 02:40:57 +00001581 PageOne *pPage1 = pBt->page1;
drh3b7511c2001-05-26 13:15:44 +00001582 OverflowPage *pOvfl = (OverflowPage*)pPage;
1583 int rc;
drhdd793422001-06-28 01:54:48 +00001584 int needUnref = 0;
1585 MemPage *pMemPage;
drh8b2f49b2001-06-08 00:21:52 +00001586
drh3b7511c2001-05-26 13:15:44 +00001587 if( pgno==0 ){
1588 assert( pOvfl!=0 );
1589 pgno = sqlitepager_pagenumber(pOvfl);
1590 }
drh2aa679f2001-06-25 02:11:07 +00001591 assert( pgno>2 );
drh193a6b42002-07-07 16:52:46 +00001592 pMemPage = (MemPage*)pPage;
1593 pMemPage->isInit = 0;
1594 if( pMemPage->pParent ){
1595 sqlitepager_unref(pMemPage->pParent);
1596 pMemPage->pParent = 0;
1597 }
drh3b7511c2001-05-26 13:15:44 +00001598 rc = sqlitepager_write(pPage1);
1599 if( rc ){
1600 return rc;
1601 }
drh30e58752002-03-02 20:41:57 +00001602 pPage1->nFree++;
1603 if( pPage1->nFree>0 && pPage1->freeList ){
1604 OverflowPage *pFreeIdx;
1605 rc = sqlitepager_get(pBt->pPager, pPage1->freeList, (void**)&pFreeIdx);
1606 if( rc==SQLITE_OK ){
1607 FreelistInfo *pInfo = (FreelistInfo*)pFreeIdx->aPayload;
1608 if( pInfo->nFree<(sizeof(pInfo->aFree)/sizeof(pInfo->aFree[0])) ){
1609 rc = sqlitepager_write(pFreeIdx);
1610 if( rc==SQLITE_OK ){
1611 pInfo->aFree[pInfo->nFree] = pgno;
1612 pInfo->nFree++;
1613 sqlitepager_unref(pFreeIdx);
1614 sqlitepager_dont_write(pBt->pPager, pgno);
1615 return rc;
1616 }
1617 }
1618 sqlitepager_unref(pFreeIdx);
1619 }
1620 }
drh3b7511c2001-05-26 13:15:44 +00001621 if( pOvfl==0 ){
1622 assert( pgno>0 );
drh8c42ca92001-06-22 19:15:00 +00001623 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001624 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001625 needUnref = 1;
drh3b7511c2001-05-26 13:15:44 +00001626 }
1627 rc = sqlitepager_write(pOvfl);
1628 if( rc ){
drhdd793422001-06-28 01:54:48 +00001629 if( needUnref ) sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001630 return rc;
1631 }
drh14acc042001-06-10 19:56:58 +00001632 pOvfl->iNext = pPage1->freeList;
drh3b7511c2001-05-26 13:15:44 +00001633 pPage1->freeList = pgno;
drh5e2f8b92001-05-28 00:41:15 +00001634 memset(pOvfl->aPayload, 0, OVERFLOW_SIZE);
drhdd793422001-06-28 01:54:48 +00001635 if( needUnref ) rc = sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001636 return rc;
1637}
1638
1639/*
1640** Erase all the data out of a cell. This involves returning overflow
1641** pages back the freelist.
1642*/
1643static int clearCell(Btree *pBt, Cell *pCell){
1644 Pager *pPager = pBt->pPager;
1645 OverflowPage *pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001646 Pgno ovfl, nextOvfl;
1647 int rc;
1648
drh80ff32f2001-11-04 18:32:46 +00001649 if( NKEY(pCell->h) + NDATA(pCell->h) <= MX_LOCAL_PAYLOAD ){
drh5e2f8b92001-05-28 00:41:15 +00001650 return SQLITE_OK;
1651 }
drh3b7511c2001-05-26 13:15:44 +00001652 ovfl = pCell->ovfl;
1653 pCell->ovfl = 0;
1654 while( ovfl ){
drh8c42ca92001-06-22 19:15:00 +00001655 rc = sqlitepager_get(pPager, ovfl, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001656 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00001657 nextOvfl = pOvfl->iNext;
drhbd03cae2001-06-02 02:40:57 +00001658 rc = freePage(pBt, pOvfl, ovfl);
1659 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001660 sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001661 ovfl = nextOvfl;
drh3b7511c2001-05-26 13:15:44 +00001662 }
drh5e2f8b92001-05-28 00:41:15 +00001663 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00001664}
1665
1666/*
1667** Create a new cell from key and data. Overflow pages are allocated as
1668** necessary and linked to this cell.
1669*/
1670static int fillInCell(
1671 Btree *pBt, /* The whole Btree. Needed to allocate pages */
1672 Cell *pCell, /* Populate this Cell structure */
drh5c4d9702001-08-20 00:33:58 +00001673 const void *pKey, int nKey, /* The key */
1674 const void *pData,int nData /* The data */
drh3b7511c2001-05-26 13:15:44 +00001675){
drhdd793422001-06-28 01:54:48 +00001676 OverflowPage *pOvfl, *pPrior;
drh3b7511c2001-05-26 13:15:44 +00001677 Pgno *pNext;
1678 int spaceLeft;
drh8c42ca92001-06-22 19:15:00 +00001679 int n, rc;
drh3b7511c2001-05-26 13:15:44 +00001680 int nPayload;
drh5c4d9702001-08-20 00:33:58 +00001681 const char *pPayload;
drh3b7511c2001-05-26 13:15:44 +00001682 char *pSpace;
drhbea00b92002-07-08 10:59:50 +00001683 Pgno near = 0;
drh3b7511c2001-05-26 13:15:44 +00001684
drh5e2f8b92001-05-28 00:41:15 +00001685 pCell->h.leftChild = 0;
drh80ff32f2001-11-04 18:32:46 +00001686 pCell->h.nKey = nKey & 0xffff;
1687 pCell->h.nKeyHi = nKey >> 16;
1688 pCell->h.nData = nData & 0xffff;
1689 pCell->h.nDataHi = nData >> 16;
drh3b7511c2001-05-26 13:15:44 +00001690 pCell->h.iNext = 0;
1691
1692 pNext = &pCell->ovfl;
drh5e2f8b92001-05-28 00:41:15 +00001693 pSpace = pCell->aPayload;
drh3b7511c2001-05-26 13:15:44 +00001694 spaceLeft = MX_LOCAL_PAYLOAD;
1695 pPayload = pKey;
1696 pKey = 0;
1697 nPayload = nKey;
drhdd793422001-06-28 01:54:48 +00001698 pPrior = 0;
drh3b7511c2001-05-26 13:15:44 +00001699 while( nPayload>0 ){
1700 if( spaceLeft==0 ){
drhbea00b92002-07-08 10:59:50 +00001701 rc = allocatePage(pBt, (MemPage**)&pOvfl, pNext, near);
drh3b7511c2001-05-26 13:15:44 +00001702 if( rc ){
1703 *pNext = 0;
drhbea00b92002-07-08 10:59:50 +00001704 }else{
1705 near = *pNext;
drhdd793422001-06-28 01:54:48 +00001706 }
1707 if( pPrior ) sqlitepager_unref(pPrior);
1708 if( rc ){
drh5e2f8b92001-05-28 00:41:15 +00001709 clearCell(pBt, pCell);
drh3b7511c2001-05-26 13:15:44 +00001710 return rc;
1711 }
drhdd793422001-06-28 01:54:48 +00001712 pPrior = pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001713 spaceLeft = OVERFLOW_SIZE;
drh5e2f8b92001-05-28 00:41:15 +00001714 pSpace = pOvfl->aPayload;
drh8c42ca92001-06-22 19:15:00 +00001715 pNext = &pOvfl->iNext;
drh3b7511c2001-05-26 13:15:44 +00001716 }
1717 n = nPayload;
1718 if( n>spaceLeft ) n = spaceLeft;
1719 memcpy(pSpace, pPayload, n);
1720 nPayload -= n;
1721 if( nPayload==0 && pData ){
1722 pPayload = pData;
1723 nPayload = nData;
1724 pData = 0;
1725 }else{
1726 pPayload += n;
1727 }
1728 spaceLeft -= n;
1729 pSpace += n;
1730 }
drhdd793422001-06-28 01:54:48 +00001731 *pNext = 0;
1732 if( pPrior ){
1733 sqlitepager_unref(pPrior);
1734 }
drh3b7511c2001-05-26 13:15:44 +00001735 return SQLITE_OK;
1736}
1737
1738/*
drhbd03cae2001-06-02 02:40:57 +00001739** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00001740** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00001741** pointer in the third argument.
1742*/
1743static void reparentPage(Pager *pPager, Pgno pgno, MemPage *pNewParent){
1744 MemPage *pThis;
1745
drhdd793422001-06-28 01:54:48 +00001746 if( pgno==0 ) return;
1747 assert( pPager!=0 );
drhbd03cae2001-06-02 02:40:57 +00001748 pThis = sqlitepager_lookup(pPager, pgno);
drh6019e162001-07-02 17:51:45 +00001749 if( pThis && pThis->isInit ){
drhdd793422001-06-28 01:54:48 +00001750 if( pThis->pParent!=pNewParent ){
1751 if( pThis->pParent ) sqlitepager_unref(pThis->pParent);
1752 pThis->pParent = pNewParent;
1753 if( pNewParent ) sqlitepager_ref(pNewParent);
1754 }
1755 sqlitepager_unref(pThis);
drhbd03cae2001-06-02 02:40:57 +00001756 }
1757}
1758
1759/*
1760** Reparent all children of the given page to be the given page.
1761** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00001762** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00001763**
1764** This routine gets called after you memcpy() one page into
1765** another.
1766*/
drh8c42ca92001-06-22 19:15:00 +00001767static void reparentChildPages(Pager *pPager, MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00001768 int i;
1769 for(i=0; i<pPage->nCell; i++){
drh8c42ca92001-06-22 19:15:00 +00001770 reparentPage(pPager, pPage->apCell[i]->h.leftChild, pPage);
drhbd03cae2001-06-02 02:40:57 +00001771 }
drh14acc042001-06-10 19:56:58 +00001772 reparentPage(pPager, pPage->u.hdr.rightChild, pPage);
1773}
1774
1775/*
1776** Remove the i-th cell from pPage. This routine effects pPage only.
1777** The cell content is not freed or deallocated. It is assumed that
1778** the cell content has been copied someplace else. This routine just
1779** removes the reference to the cell from pPage.
1780**
1781** "sz" must be the number of bytes in the cell.
1782**
1783** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001784** Only the pPage->apCell[] array is important. The relinkCellList()
1785** routine will be called soon after this routine in order to rebuild
1786** the linked list.
drh14acc042001-06-10 19:56:58 +00001787*/
drh8c42ca92001-06-22 19:15:00 +00001788static void dropCell(MemPage *pPage, int idx, int sz){
drh14acc042001-06-10 19:56:58 +00001789 int j;
drh8c42ca92001-06-22 19:15:00 +00001790 assert( idx>=0 && idx<pPage->nCell );
1791 assert( sz==cellSize(pPage->apCell[idx]) );
drh6019e162001-07-02 17:51:45 +00001792 assert( sqlitepager_iswriteable(pPage) );
drh7c717f72001-06-24 20:39:41 +00001793 freeSpace(pPage, Addr(pPage->apCell[idx]) - Addr(pPage), sz);
1794 for(j=idx; j<pPage->nCell-1; j++){
drh14acc042001-06-10 19:56:58 +00001795 pPage->apCell[j] = pPage->apCell[j+1];
1796 }
1797 pPage->nCell--;
1798}
1799
1800/*
1801** Insert a new cell on pPage at cell index "i". pCell points to the
1802** content of the cell.
1803**
1804** If the cell content will fit on the page, then put it there. If it
1805** will not fit, then just make pPage->apCell[i] point to the content
1806** and set pPage->isOverfull.
1807**
1808** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001809** Only the pPage->apCell[] array is important. The relinkCellList()
1810** routine will be called soon after this routine in order to rebuild
1811** the linked list.
drh14acc042001-06-10 19:56:58 +00001812*/
1813static void insertCell(MemPage *pPage, int i, Cell *pCell, int sz){
1814 int idx, j;
1815 assert( i>=0 && i<=pPage->nCell );
1816 assert( sz==cellSize(pCell) );
drh6019e162001-07-02 17:51:45 +00001817 assert( sqlitepager_iswriteable(pPage) );
drh2aa679f2001-06-25 02:11:07 +00001818 idx = allocateSpace(pPage, sz);
drh14acc042001-06-10 19:56:58 +00001819 for(j=pPage->nCell; j>i; j--){
1820 pPage->apCell[j] = pPage->apCell[j-1];
1821 }
1822 pPage->nCell++;
drh14acc042001-06-10 19:56:58 +00001823 if( idx<=0 ){
1824 pPage->isOverfull = 1;
1825 pPage->apCell[i] = pCell;
1826 }else{
1827 memcpy(&pPage->u.aDisk[idx], pCell, sz);
drh8c42ca92001-06-22 19:15:00 +00001828 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[idx];
drh14acc042001-06-10 19:56:58 +00001829 }
1830}
1831
1832/*
1833** Rebuild the linked list of cells on a page so that the cells
drh8c42ca92001-06-22 19:15:00 +00001834** occur in the order specified by the pPage->apCell[] array.
1835** Invoke this routine once to repair damage after one or more
1836** invocations of either insertCell() or dropCell().
drh14acc042001-06-10 19:56:58 +00001837*/
1838static void relinkCellList(MemPage *pPage){
1839 int i;
1840 u16 *pIdx;
drh6019e162001-07-02 17:51:45 +00001841 assert( sqlitepager_iswriteable(pPage) );
drh14acc042001-06-10 19:56:58 +00001842 pIdx = &pPage->u.hdr.firstCell;
1843 for(i=0; i<pPage->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00001844 int idx = Addr(pPage->apCell[i]) - Addr(pPage);
drh8c42ca92001-06-22 19:15:00 +00001845 assert( idx>0 && idx<SQLITE_PAGE_SIZE );
drh14acc042001-06-10 19:56:58 +00001846 *pIdx = idx;
1847 pIdx = &pPage->apCell[i]->h.iNext;
1848 }
1849 *pIdx = 0;
1850}
1851
1852/*
1853** Make a copy of the contents of pFrom into pTo. The pFrom->apCell[]
drh5e00f6c2001-09-13 13:46:56 +00001854** pointers that point into pFrom->u.aDisk[] must be adjusted to point
drhdd793422001-06-28 01:54:48 +00001855** into pTo->u.aDisk[] instead. But some pFrom->apCell[] entries might
drh14acc042001-06-10 19:56:58 +00001856** not point to pFrom->u.aDisk[]. Those are unchanged.
1857*/
1858static void copyPage(MemPage *pTo, MemPage *pFrom){
1859 uptr from, to;
1860 int i;
1861 memcpy(pTo->u.aDisk, pFrom->u.aDisk, SQLITE_PAGE_SIZE);
drhdd793422001-06-28 01:54:48 +00001862 pTo->pParent = 0;
drh14acc042001-06-10 19:56:58 +00001863 pTo->isInit = 1;
1864 pTo->nCell = pFrom->nCell;
1865 pTo->nFree = pFrom->nFree;
1866 pTo->isOverfull = pFrom->isOverfull;
drh7c717f72001-06-24 20:39:41 +00001867 to = Addr(pTo);
1868 from = Addr(pFrom);
drh14acc042001-06-10 19:56:58 +00001869 for(i=0; i<pTo->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00001870 uptr x = Addr(pFrom->apCell[i]);
drh8c42ca92001-06-22 19:15:00 +00001871 if( x>from && x<from+SQLITE_PAGE_SIZE ){
1872 *((uptr*)&pTo->apCell[i]) = x + to - from;
drhdd793422001-06-28 01:54:48 +00001873 }else{
1874 pTo->apCell[i] = pFrom->apCell[i];
drh14acc042001-06-10 19:56:58 +00001875 }
1876 }
drhbd03cae2001-06-02 02:40:57 +00001877}
1878
1879/*
drh8b2f49b2001-06-08 00:21:52 +00001880** This routine redistributes Cells on pPage and up to two siblings
1881** of pPage so that all pages have about the same amount of free space.
drh14acc042001-06-10 19:56:58 +00001882** Usually one sibling on either side of pPage is used in the balancing,
drh8b2f49b2001-06-08 00:21:52 +00001883** though both siblings might come from one side if pPage is the first
1884** or last child of its parent. If pPage has fewer than two siblings
1885** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00001886** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00001887**
1888** The number of siblings of pPage might be increased or decreased by
drh8c42ca92001-06-22 19:15:00 +00001889** one in an effort to keep pages between 66% and 100% full. The root page
1890** is special and is allowed to be less than 66% full. If pPage is
1891** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00001892** or decreased by one, as necessary, to keep the root page from being
1893** overfull or empty.
1894**
drh14acc042001-06-10 19:56:58 +00001895** This routine calls relinkCellList() on its input page regardless of
1896** whether or not it does any real balancing. Client routines will typically
1897** invoke insertCell() or dropCell() before calling this routine, so we
1898** need to call relinkCellList() to clean up the mess that those other
1899** routines left behind.
1900**
1901** pCur is left pointing to the same cell as when this routine was called
drh8c42ca92001-06-22 19:15:00 +00001902** even if that cell gets moved to a different page. pCur may be NULL.
1903** Set the pCur parameter to NULL if you do not care about keeping track
1904** of a cell as that will save this routine the work of keeping track of it.
drh14acc042001-06-10 19:56:58 +00001905**
drh8b2f49b2001-06-08 00:21:52 +00001906** Note that when this routine is called, some of the Cells on pPage
drh14acc042001-06-10 19:56:58 +00001907** might not actually be stored in pPage->u.aDisk[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00001908** if the page is overfull. Part of the job of this routine is to
drh14acc042001-06-10 19:56:58 +00001909** make sure all Cells for pPage once again fit in pPage->u.aDisk[].
1910**
drh8c42ca92001-06-22 19:15:00 +00001911** In the course of balancing the siblings of pPage, the parent of pPage
1912** might become overfull or underfull. If that happens, then this routine
1913** is called recursively on the parent.
1914**
drh5e00f6c2001-09-13 13:46:56 +00001915** If this routine fails for any reason, it might leave the database
1916** in a corrupted state. So if this routine fails, the database should
1917** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00001918*/
drh14acc042001-06-10 19:56:58 +00001919static int balance(Btree *pBt, MemPage *pPage, BtCursor *pCur){
drh8b2f49b2001-06-08 00:21:52 +00001920 MemPage *pParent; /* The parent of pPage */
drh14acc042001-06-10 19:56:58 +00001921 MemPage *apOld[3]; /* pPage and up to two siblings */
drh8b2f49b2001-06-08 00:21:52 +00001922 Pgno pgnoOld[3]; /* Page numbers for each page in apOld[] */
drh14acc042001-06-10 19:56:58 +00001923 MemPage *apNew[4]; /* pPage and up to 3 siblings after balancing */
1924 Pgno pgnoNew[4]; /* Page numbers for each page in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00001925 int idxDiv[3]; /* Indices of divider cells in pParent */
1926 Cell *apDiv[3]; /* Divider cells in pParent */
1927 int nCell; /* Number of cells in apCell[] */
1928 int nOld; /* Number of pages in apOld[] */
1929 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00001930 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00001931 int i, j, k; /* Loop counters */
1932 int idx; /* Index of pPage in pParent->apCell[] */
1933 int nxDiv; /* Next divider slot in pParent->apCell[] */
1934 int rc; /* The return code */
1935 int iCur; /* apCell[iCur] is the cell of the cursor */
drh5edc3122001-09-13 21:53:09 +00001936 MemPage *pOldCurPage; /* The cursor originally points to this page */
drh8c42ca92001-06-22 19:15:00 +00001937 int totalSize; /* Total bytes for all cells */
drh6019e162001-07-02 17:51:45 +00001938 int subtotal; /* Subtotal of bytes in cells on one page */
1939 int cntNew[4]; /* Index in apCell[] of cell after i-th page */
1940 int szNew[4]; /* Combined size of cells place on i-th page */
drh9ca7d3b2001-06-28 11:50:21 +00001941 MemPage *extraUnref = 0; /* A page that needs to be unref-ed */
drh8c42ca92001-06-22 19:15:00 +00001942 Pgno pgno; /* Page number */
drh14acc042001-06-10 19:56:58 +00001943 Cell *apCell[MX_CELL*3+5]; /* All cells from pages being balanceed */
1944 int szCell[MX_CELL*3+5]; /* Local size of all cells */
1945 Cell aTemp[2]; /* Temporary holding area for apDiv[] */
1946 MemPage aOld[3]; /* Temporary copies of pPage and its siblings */
drh8b2f49b2001-06-08 00:21:52 +00001947
drh14acc042001-06-10 19:56:58 +00001948 /*
1949 ** Return without doing any work if pPage is neither overfull nor
1950 ** underfull.
drh8b2f49b2001-06-08 00:21:52 +00001951 */
drh6019e162001-07-02 17:51:45 +00001952 assert( sqlitepager_iswriteable(pPage) );
drha1b351a2001-09-14 16:42:12 +00001953 if( !pPage->isOverfull && pPage->nFree<SQLITE_PAGE_SIZE/2
1954 && pPage->nCell>=2){
drh14acc042001-06-10 19:56:58 +00001955 relinkCellList(pPage);
drh8b2f49b2001-06-08 00:21:52 +00001956 return SQLITE_OK;
1957 }
1958
1959 /*
drh14acc042001-06-10 19:56:58 +00001960 ** Find the parent of the page to be balanceed.
1961 ** If there is no parent, it means this page is the root page and
drh8b2f49b2001-06-08 00:21:52 +00001962 ** special rules apply.
1963 */
drh14acc042001-06-10 19:56:58 +00001964 pParent = pPage->pParent;
drh8b2f49b2001-06-08 00:21:52 +00001965 if( pParent==0 ){
1966 Pgno pgnoChild;
drh8c42ca92001-06-22 19:15:00 +00001967 MemPage *pChild;
drh7aa128d2002-06-21 13:09:16 +00001968 assert( pPage->isInit );
drh8b2f49b2001-06-08 00:21:52 +00001969 if( pPage->nCell==0 ){
drh14acc042001-06-10 19:56:58 +00001970 if( pPage->u.hdr.rightChild ){
1971 /*
1972 ** The root page is empty. Copy the one child page
drh8b2f49b2001-06-08 00:21:52 +00001973 ** into the root page and return. This reduces the depth
1974 ** of the BTree by one.
1975 */
drh14acc042001-06-10 19:56:58 +00001976 pgnoChild = pPage->u.hdr.rightChild;
drh8c42ca92001-06-22 19:15:00 +00001977 rc = sqlitepager_get(pBt->pPager, pgnoChild, (void**)&pChild);
drh8b2f49b2001-06-08 00:21:52 +00001978 if( rc ) return rc;
1979 memcpy(pPage, pChild, SQLITE_PAGE_SIZE);
1980 pPage->isInit = 0;
drh6019e162001-07-02 17:51:45 +00001981 rc = initPage(pPage, sqlitepager_pagenumber(pPage), 0);
1982 assert( rc==SQLITE_OK );
drh8b2f49b2001-06-08 00:21:52 +00001983 reparentChildPages(pBt->pPager, pPage);
drh5edc3122001-09-13 21:53:09 +00001984 if( pCur && pCur->pPage==pChild ){
1985 sqlitepager_unref(pChild);
1986 pCur->pPage = pPage;
1987 sqlitepager_ref(pPage);
1988 }
drh8b2f49b2001-06-08 00:21:52 +00001989 freePage(pBt, pChild, pgnoChild);
1990 sqlitepager_unref(pChild);
drhefc251d2001-07-01 22:12:01 +00001991 }else{
1992 relinkCellList(pPage);
drh8b2f49b2001-06-08 00:21:52 +00001993 }
1994 return SQLITE_OK;
1995 }
drh14acc042001-06-10 19:56:58 +00001996 if( !pPage->isOverfull ){
drh8b2f49b2001-06-08 00:21:52 +00001997 /* It is OK for the root page to be less than half full.
1998 */
drh14acc042001-06-10 19:56:58 +00001999 relinkCellList(pPage);
drh8b2f49b2001-06-08 00:21:52 +00002000 return SQLITE_OK;
2001 }
drh14acc042001-06-10 19:56:58 +00002002 /*
2003 ** If we get to here, it means the root page is overfull.
drh8b2f49b2001-06-08 00:21:52 +00002004 ** When this happens, Create a new child page and copy the
2005 ** contents of the root into the child. Then make the root
drh14acc042001-06-10 19:56:58 +00002006 ** page an empty page with rightChild pointing to the new
drh8b2f49b2001-06-08 00:21:52 +00002007 ** child. Then fall thru to the code below which will cause
2008 ** the overfull child page to be split.
2009 */
drh14acc042001-06-10 19:56:58 +00002010 rc = sqlitepager_write(pPage);
2011 if( rc ) return rc;
drhbea00b92002-07-08 10:59:50 +00002012 rc = allocatePage(pBt, &pChild, &pgnoChild, sqlitepager_pagenumber(pPage));
drh8b2f49b2001-06-08 00:21:52 +00002013 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002014 assert( sqlitepager_iswriteable(pChild) );
drh14acc042001-06-10 19:56:58 +00002015 copyPage(pChild, pPage);
2016 pChild->pParent = pPage;
drhdd793422001-06-28 01:54:48 +00002017 sqlitepager_ref(pPage);
drh14acc042001-06-10 19:56:58 +00002018 pChild->isOverfull = 1;
drh5edc3122001-09-13 21:53:09 +00002019 if( pCur && pCur->pPage==pPage ){
2020 sqlitepager_unref(pPage);
drh14acc042001-06-10 19:56:58 +00002021 pCur->pPage = pChild;
drh9ca7d3b2001-06-28 11:50:21 +00002022 }else{
2023 extraUnref = pChild;
drh8b2f49b2001-06-08 00:21:52 +00002024 }
drh8b2f49b2001-06-08 00:21:52 +00002025 zeroPage(pPage);
drh14acc042001-06-10 19:56:58 +00002026 pPage->u.hdr.rightChild = pgnoChild;
drh8b2f49b2001-06-08 00:21:52 +00002027 pParent = pPage;
2028 pPage = pChild;
drh8b2f49b2001-06-08 00:21:52 +00002029 }
drh6019e162001-07-02 17:51:45 +00002030 rc = sqlitepager_write(pParent);
2031 if( rc ) return rc;
drh7aa128d2002-06-21 13:09:16 +00002032 assert( pParent->isInit );
drh14acc042001-06-10 19:56:58 +00002033
drh8b2f49b2001-06-08 00:21:52 +00002034 /*
drh14acc042001-06-10 19:56:58 +00002035 ** Find the Cell in the parent page whose h.leftChild points back
2036 ** to pPage. The "idx" variable is the index of that cell. If pPage
2037 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00002038 */
2039 idx = -1;
2040 pgno = sqlitepager_pagenumber(pPage);
2041 for(i=0; i<pParent->nCell; i++){
2042 if( pParent->apCell[i]->h.leftChild==pgno ){
2043 idx = i;
2044 break;
2045 }
2046 }
drhdd793422001-06-28 01:54:48 +00002047 if( idx<0 && pParent->u.hdr.rightChild==pgno ){
2048 idx = pParent->nCell;
drh8b2f49b2001-06-08 00:21:52 +00002049 }
2050 if( idx<0 ){
drh14acc042001-06-10 19:56:58 +00002051 return SQLITE_CORRUPT;
drh8b2f49b2001-06-08 00:21:52 +00002052 }
2053
2054 /*
drh14acc042001-06-10 19:56:58 +00002055 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00002056 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00002057 */
drh14acc042001-06-10 19:56:58 +00002058 nOld = nNew = 0;
2059 sqlitepager_ref(pParent);
2060
2061 /*
2062 ** Find sibling pages to pPage and the Cells in pParent that divide
2063 ** the siblings. An attempt is made to find one sibling on either
2064 ** side of pPage. Both siblings are taken from one side, however, if
2065 ** pPage is either the first or last child of its parent. If pParent
2066 ** has 3 or fewer children then all children of pParent are taken.
2067 */
2068 if( idx==pParent->nCell ){
2069 nxDiv = idx - 2;
drh8b2f49b2001-06-08 00:21:52 +00002070 }else{
drh14acc042001-06-10 19:56:58 +00002071 nxDiv = idx - 1;
drh8b2f49b2001-06-08 00:21:52 +00002072 }
drh14acc042001-06-10 19:56:58 +00002073 if( nxDiv<0 ) nxDiv = 0;
drh8b2f49b2001-06-08 00:21:52 +00002074 nDiv = 0;
drh14acc042001-06-10 19:56:58 +00002075 for(i=0, k=nxDiv; i<3; i++, k++){
2076 if( k<pParent->nCell ){
2077 idxDiv[i] = k;
2078 apDiv[i] = pParent->apCell[k];
drh8b2f49b2001-06-08 00:21:52 +00002079 nDiv++;
2080 pgnoOld[i] = apDiv[i]->h.leftChild;
drh14acc042001-06-10 19:56:58 +00002081 }else if( k==pParent->nCell ){
drh8c42ca92001-06-22 19:15:00 +00002082 pgnoOld[i] = pParent->u.hdr.rightChild;
drh14acc042001-06-10 19:56:58 +00002083 }else{
2084 break;
drh8b2f49b2001-06-08 00:21:52 +00002085 }
drh8c42ca92001-06-22 19:15:00 +00002086 rc = sqlitepager_get(pBt->pPager, pgnoOld[i], (void**)&apOld[i]);
drh14acc042001-06-10 19:56:58 +00002087 if( rc ) goto balance_cleanup;
drh6019e162001-07-02 17:51:45 +00002088 rc = initPage(apOld[i], pgnoOld[i], pParent);
2089 if( rc ) goto balance_cleanup;
drh14acc042001-06-10 19:56:58 +00002090 nOld++;
drh8b2f49b2001-06-08 00:21:52 +00002091 }
2092
2093 /*
drh14acc042001-06-10 19:56:58 +00002094 ** Set iCur to be the index in apCell[] of the cell that the cursor
2095 ** is pointing to. We will need this later on in order to keep the
drh5edc3122001-09-13 21:53:09 +00002096 ** cursor pointing at the same cell. If pCur points to a page that
2097 ** has no involvement with this rebalancing, then set iCur to a large
2098 ** number so that the iCur==j tests always fail in the main cell
2099 ** distribution loop below.
drh14acc042001-06-10 19:56:58 +00002100 */
2101 if( pCur ){
drh5edc3122001-09-13 21:53:09 +00002102 iCur = 0;
2103 for(i=0; i<nOld; i++){
2104 if( pCur->pPage==apOld[i] ){
2105 iCur += pCur->idx;
2106 break;
2107 }
2108 iCur += apOld[i]->nCell;
2109 if( i<nOld-1 && pCur->pPage==pParent && pCur->idx==idxDiv[i] ){
2110 break;
2111 }
2112 iCur++;
drh14acc042001-06-10 19:56:58 +00002113 }
drh5edc3122001-09-13 21:53:09 +00002114 pOldCurPage = pCur->pPage;
drh14acc042001-06-10 19:56:58 +00002115 }
2116
2117 /*
2118 ** Make copies of the content of pPage and its siblings into aOld[].
2119 ** The rest of this function will use data from the copies rather
2120 ** that the original pages since the original pages will be in the
2121 ** process of being overwritten.
2122 */
2123 for(i=0; i<nOld; i++){
2124 copyPage(&aOld[i], apOld[i]);
drh14acc042001-06-10 19:56:58 +00002125 }
2126
2127 /*
2128 ** Load pointers to all cells on sibling pages and the divider cells
2129 ** into the local apCell[] array. Make copies of the divider cells
2130 ** into aTemp[] and remove the the divider Cells from pParent.
drh8b2f49b2001-06-08 00:21:52 +00002131 */
2132 nCell = 0;
2133 for(i=0; i<nOld; i++){
drh6b308672002-07-08 02:16:37 +00002134 MemPage *pOld = &aOld[i];
drh8b2f49b2001-06-08 00:21:52 +00002135 for(j=0; j<pOld->nCell; j++){
drh14acc042001-06-10 19:56:58 +00002136 apCell[nCell] = pOld->apCell[j];
2137 szCell[nCell] = cellSize(apCell[nCell]);
2138 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00002139 }
2140 if( i<nOld-1 ){
drh14acc042001-06-10 19:56:58 +00002141 szCell[nCell] = cellSize(apDiv[i]);
drh8c42ca92001-06-22 19:15:00 +00002142 memcpy(&aTemp[i], apDiv[i], szCell[nCell]);
drh14acc042001-06-10 19:56:58 +00002143 apCell[nCell] = &aTemp[i];
2144 dropCell(pParent, nxDiv, szCell[nCell]);
2145 assert( apCell[nCell]->h.leftChild==pgnoOld[i] );
2146 apCell[nCell]->h.leftChild = pOld->u.hdr.rightChild;
2147 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00002148 }
2149 }
2150
2151 /*
drh6019e162001-07-02 17:51:45 +00002152 ** Figure out the number of pages needed to hold all nCell cells.
2153 ** Store this number in "k". Also compute szNew[] which is the total
2154 ** size of all cells on the i-th page and cntNew[] which is the index
2155 ** in apCell[] of the cell that divides path i from path i+1.
2156 ** cntNew[k] should equal nCell.
2157 **
2158 ** This little patch of code is critical for keeping the tree
2159 ** balanced.
drh8b2f49b2001-06-08 00:21:52 +00002160 */
2161 totalSize = 0;
2162 for(i=0; i<nCell; i++){
drh14acc042001-06-10 19:56:58 +00002163 totalSize += szCell[i];
drh8b2f49b2001-06-08 00:21:52 +00002164 }
drh6019e162001-07-02 17:51:45 +00002165 for(subtotal=k=i=0; i<nCell; i++){
2166 subtotal += szCell[i];
2167 if( subtotal > USABLE_SPACE ){
2168 szNew[k] = subtotal - szCell[i];
2169 cntNew[k] = i;
2170 subtotal = 0;
2171 k++;
2172 }
2173 }
2174 szNew[k] = subtotal;
2175 cntNew[k] = nCell;
2176 k++;
2177 for(i=k-1; i>0; i--){
2178 while( szNew[i]<USABLE_SPACE/2 ){
2179 cntNew[i-1]--;
2180 assert( cntNew[i-1]>0 );
2181 szNew[i] += szCell[cntNew[i-1]];
2182 szNew[i-1] -= szCell[cntNew[i-1]-1];
2183 }
2184 }
2185 assert( cntNew[0]>0 );
drh8b2f49b2001-06-08 00:21:52 +00002186
2187 /*
drh6b308672002-07-08 02:16:37 +00002188 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00002189 */
drh14acc042001-06-10 19:56:58 +00002190 for(i=0; i<k; i++){
drh6b308672002-07-08 02:16:37 +00002191 if( i<nOld ){
2192 apNew[i] = apOld[i];
2193 pgnoNew[i] = pgnoOld[i];
2194 apOld[i] = 0;
2195 sqlitepager_write(apNew[i]);
2196 }else{
drhbea00b92002-07-08 10:59:50 +00002197 rc = allocatePage(pBt, &apNew[i], &pgnoNew[i], pgnoNew[i-1]);
drh6b308672002-07-08 02:16:37 +00002198 if( rc ) goto balance_cleanup;
2199 }
drh14acc042001-06-10 19:56:58 +00002200 nNew++;
drh8b2f49b2001-06-08 00:21:52 +00002201 zeroPage(apNew[i]);
drh6019e162001-07-02 17:51:45 +00002202 apNew[i]->isInit = 1;
drh8b2f49b2001-06-08 00:21:52 +00002203 }
2204
drh6b308672002-07-08 02:16:37 +00002205 /* Free any old pages that were not reused as new pages.
2206 */
2207 while( i<nOld ){
2208 rc = freePage(pBt, apOld[i], pgnoOld[i]);
2209 if( rc ) goto balance_cleanup;
2210 sqlitepager_unref(apOld[i]);
2211 apOld[i] = 0;
2212 i++;
2213 }
2214
drh8b2f49b2001-06-08 00:21:52 +00002215 /*
drhf9ffac92002-03-02 19:00:31 +00002216 ** Put the new pages in accending order. This helps to
2217 ** keep entries in the disk file in order so that a scan
2218 ** of the table is a linear scan through the file. That
2219 ** in turn helps the operating system to deliver pages
2220 ** from the disk more rapidly.
2221 **
2222 ** An O(n^2) insertion sort algorithm is used, but since
2223 ** n is never more than 3, that should not be a problem.
2224 **
2225 ** This one optimization makes the database about 25%
2226 ** faster for large insertions and deletions.
2227 */
2228 for(i=0; i<k-1; i++){
2229 int minV = pgnoNew[i];
2230 int minI = i;
2231 for(j=i+1; j<k; j++){
2232 if( pgnoNew[j]<minV ){
2233 minI = j;
2234 minV = pgnoNew[j];
2235 }
2236 }
2237 if( minI>i ){
2238 int t;
2239 MemPage *pT;
2240 t = pgnoNew[i];
2241 pT = apNew[i];
2242 pgnoNew[i] = pgnoNew[minI];
2243 apNew[i] = apNew[minI];
2244 pgnoNew[minI] = t;
2245 apNew[minI] = pT;
2246 }
2247 }
2248
2249 /*
drh14acc042001-06-10 19:56:58 +00002250 ** Evenly distribute the data in apCell[] across the new pages.
2251 ** Insert divider cells into pParent as necessary.
2252 */
2253 j = 0;
2254 for(i=0; i<nNew; i++){
2255 MemPage *pNew = apNew[i];
drh6019e162001-07-02 17:51:45 +00002256 while( j<cntNew[i] ){
2257 assert( pNew->nFree>=szCell[j] );
drh14acc042001-06-10 19:56:58 +00002258 if( pCur && iCur==j ){ pCur->pPage = pNew; pCur->idx = pNew->nCell; }
2259 insertCell(pNew, pNew->nCell, apCell[j], szCell[j]);
2260 j++;
2261 }
drh6019e162001-07-02 17:51:45 +00002262 assert( pNew->nCell>0 );
drh14acc042001-06-10 19:56:58 +00002263 assert( !pNew->isOverfull );
2264 relinkCellList(pNew);
2265 if( i<nNew-1 && j<nCell ){
2266 pNew->u.hdr.rightChild = apCell[j]->h.leftChild;
2267 apCell[j]->h.leftChild = pgnoNew[i];
2268 if( pCur && iCur==j ){ pCur->pPage = pParent; pCur->idx = nxDiv; }
2269 insertCell(pParent, nxDiv, apCell[j], szCell[j]);
2270 j++;
2271 nxDiv++;
2272 }
2273 }
drh6019e162001-07-02 17:51:45 +00002274 assert( j==nCell );
drh6b308672002-07-08 02:16:37 +00002275 apNew[nNew-1]->u.hdr.rightChild = aOld[nOld-1].u.hdr.rightChild;
drh14acc042001-06-10 19:56:58 +00002276 if( nxDiv==pParent->nCell ){
2277 pParent->u.hdr.rightChild = pgnoNew[nNew-1];
2278 }else{
2279 pParent->apCell[nxDiv]->h.leftChild = pgnoNew[nNew-1];
2280 }
2281 if( pCur ){
drh3fc190c2001-09-14 03:24:23 +00002282 if( j<=iCur && pCur->pPage==pParent && pCur->idx>idxDiv[nOld-1] ){
2283 assert( pCur->pPage==pOldCurPage );
2284 pCur->idx += nNew - nOld;
2285 }else{
2286 assert( pOldCurPage!=0 );
2287 sqlitepager_ref(pCur->pPage);
2288 sqlitepager_unref(pOldCurPage);
2289 }
drh14acc042001-06-10 19:56:58 +00002290 }
2291
2292 /*
2293 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00002294 */
2295 for(i=0; i<nNew; i++){
drh14acc042001-06-10 19:56:58 +00002296 reparentChildPages(pBt->pPager, apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002297 }
drh14acc042001-06-10 19:56:58 +00002298 reparentChildPages(pBt->pPager, pParent);
drh8b2f49b2001-06-08 00:21:52 +00002299
2300 /*
drh14acc042001-06-10 19:56:58 +00002301 ** balance the parent page.
drh8b2f49b2001-06-08 00:21:52 +00002302 */
drh5edc3122001-09-13 21:53:09 +00002303 rc = balance(pBt, pParent, pCur);
drh8b2f49b2001-06-08 00:21:52 +00002304
2305 /*
drh14acc042001-06-10 19:56:58 +00002306 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00002307 */
drh14acc042001-06-10 19:56:58 +00002308balance_cleanup:
drh9ca7d3b2001-06-28 11:50:21 +00002309 if( extraUnref ){
2310 sqlitepager_unref(extraUnref);
2311 }
drh8b2f49b2001-06-08 00:21:52 +00002312 for(i=0; i<nOld; i++){
drh6b308672002-07-08 02:16:37 +00002313 if( apOld[i]!=0 && apOld[i]!=&aOld[i] ) sqlitepager_unref(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00002314 }
drh14acc042001-06-10 19:56:58 +00002315 for(i=0; i<nNew; i++){
2316 sqlitepager_unref(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002317 }
drh14acc042001-06-10 19:56:58 +00002318 if( pCur && pCur->pPage==0 ){
2319 pCur->pPage = pParent;
2320 pCur->idx = 0;
2321 }else{
2322 sqlitepager_unref(pParent);
drh8b2f49b2001-06-08 00:21:52 +00002323 }
2324 return rc;
2325}
2326
2327/*
drh3b7511c2001-05-26 13:15:44 +00002328** Insert a new record into the BTree. The key is given by (pKey,nKey)
2329** and the data is given by (pData,nData). The cursor is used only to
2330** define what database the record should be inserted into. The cursor
drh14acc042001-06-10 19:56:58 +00002331** is left pointing at the new record.
drh3b7511c2001-05-26 13:15:44 +00002332*/
2333int sqliteBtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00002334 BtCursor *pCur, /* Insert data into the table of this cursor */
drhbe0072d2001-09-13 14:46:09 +00002335 const void *pKey, int nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00002336 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00002337){
2338 Cell newCell;
2339 int rc;
2340 int loc;
drh14acc042001-06-10 19:56:58 +00002341 int szNew;
drh3b7511c2001-05-26 13:15:44 +00002342 MemPage *pPage;
2343 Btree *pBt = pCur->pBt;
2344
drhecdc7532001-09-23 02:35:53 +00002345 if( pCur->pPage==0 ){
2346 return SQLITE_ABORT; /* A rollback destroyed this cursor */
2347 }
drh5edc3122001-09-13 21:53:09 +00002348 if( !pCur->pBt->inTrans || nKey+nData==0 ){
drh8b2f49b2001-06-08 00:21:52 +00002349 return SQLITE_ERROR; /* Must start a transaction first */
2350 }
drhecdc7532001-09-23 02:35:53 +00002351 if( !pCur->wrFlag ){
2352 return SQLITE_PERM; /* Cursor not open for writing */
2353 }
drh14acc042001-06-10 19:56:58 +00002354 rc = sqliteBtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00002355 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002356 pPage = pCur->pPage;
drh7aa128d2002-06-21 13:09:16 +00002357 assert( pPage->isInit );
drh14acc042001-06-10 19:56:58 +00002358 rc = sqlitepager_write(pPage);
drhbd03cae2001-06-02 02:40:57 +00002359 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00002360 rc = fillInCell(pBt, &newCell, pKey, nKey, pData, nData);
2361 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002362 szNew = cellSize(&newCell);
drh3b7511c2001-05-26 13:15:44 +00002363 if( loc==0 ){
drh14acc042001-06-10 19:56:58 +00002364 newCell.h.leftChild = pPage->apCell[pCur->idx]->h.leftChild;
2365 rc = clearCell(pBt, pPage->apCell[pCur->idx]);
drh5e2f8b92001-05-28 00:41:15 +00002366 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002367 dropCell(pPage, pCur->idx, cellSize(pPage->apCell[pCur->idx]));
drh7c717f72001-06-24 20:39:41 +00002368 }else if( loc<0 && pPage->nCell>0 ){
drh14acc042001-06-10 19:56:58 +00002369 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
2370 pCur->idx++;
2371 }else{
2372 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
drh3b7511c2001-05-26 13:15:44 +00002373 }
drh7c717f72001-06-24 20:39:41 +00002374 insertCell(pPage, pCur->idx, &newCell, szNew);
drh14acc042001-06-10 19:56:58 +00002375 rc = balance(pCur->pBt, pPage, pCur);
drh3fc190c2001-09-14 03:24:23 +00002376 /* sqliteBtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
2377 /* fflush(stdout); */
drh5e2f8b92001-05-28 00:41:15 +00002378 return rc;
2379}
2380
2381/*
drhbd03cae2001-06-02 02:40:57 +00002382** Delete the entry that the cursor is pointing to.
drh5e2f8b92001-05-28 00:41:15 +00002383**
drhbd03cae2001-06-02 02:40:57 +00002384** The cursor is left pointing at either the next or the previous
2385** entry. If the cursor is left pointing to the next entry, then
2386** the pCur->bSkipNext flag is set which forces the next call to
2387** sqliteBtreeNext() to be a no-op. That way, you can always call
2388** sqliteBtreeNext() after a delete and the cursor will be left
2389** pointing to the first entry after the deleted entry.
drh3b7511c2001-05-26 13:15:44 +00002390*/
2391int sqliteBtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00002392 MemPage *pPage = pCur->pPage;
2393 Cell *pCell;
2394 int rc;
drh8c42ca92001-06-22 19:15:00 +00002395 Pgno pgnoChild;
drh8b2f49b2001-06-08 00:21:52 +00002396
drh7aa128d2002-06-21 13:09:16 +00002397 assert( pPage->isInit );
drhecdc7532001-09-23 02:35:53 +00002398 if( pCur->pPage==0 ){
2399 return SQLITE_ABORT; /* A rollback destroyed this cursor */
2400 }
drh8b2f49b2001-06-08 00:21:52 +00002401 if( !pCur->pBt->inTrans ){
2402 return SQLITE_ERROR; /* Must start a transaction first */
2403 }
drhbd03cae2001-06-02 02:40:57 +00002404 if( pCur->idx >= pPage->nCell ){
2405 return SQLITE_ERROR; /* The cursor is not pointing to anything */
2406 }
drhecdc7532001-09-23 02:35:53 +00002407 if( !pCur->wrFlag ){
2408 return SQLITE_PERM; /* Did not open this cursor for writing */
2409 }
drhbd03cae2001-06-02 02:40:57 +00002410 rc = sqlitepager_write(pPage);
2411 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002412 pCell = pPage->apCell[pCur->idx];
drh14acc042001-06-10 19:56:58 +00002413 pgnoChild = pCell->h.leftChild;
drh8c42ca92001-06-22 19:15:00 +00002414 clearCell(pCur->pBt, pCell);
drh14acc042001-06-10 19:56:58 +00002415 if( pgnoChild ){
2416 /*
drh5e00f6c2001-09-13 13:46:56 +00002417 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00002418 ** do something we will leave a hole on an internal page.
2419 ** We have to fill the hole by moving in a cell from a leaf. The
2420 ** next Cell after the one to be deleted is guaranteed to exist and
2421 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00002422 */
drh14acc042001-06-10 19:56:58 +00002423 BtCursor leafCur;
2424 Cell *pNext;
2425 int szNext;
2426 getTempCursor(pCur, &leafCur);
2427 rc = sqliteBtreeNext(&leafCur, 0);
2428 if( rc!=SQLITE_OK ){
2429 return SQLITE_CORRUPT;
drh5e2f8b92001-05-28 00:41:15 +00002430 }
drh6019e162001-07-02 17:51:45 +00002431 rc = sqlitepager_write(leafCur.pPage);
2432 if( rc ) return rc;
drh9ca7d3b2001-06-28 11:50:21 +00002433 dropCell(pPage, pCur->idx, cellSize(pCell));
drh8c42ca92001-06-22 19:15:00 +00002434 pNext = leafCur.pPage->apCell[leafCur.idx];
drh14acc042001-06-10 19:56:58 +00002435 szNext = cellSize(pNext);
drh8c42ca92001-06-22 19:15:00 +00002436 pNext->h.leftChild = pgnoChild;
drh14acc042001-06-10 19:56:58 +00002437 insertCell(pPage, pCur->idx, pNext, szNext);
2438 rc = balance(pCur->pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002439 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002440 pCur->bSkipNext = 1;
drh14acc042001-06-10 19:56:58 +00002441 dropCell(leafCur.pPage, leafCur.idx, szNext);
drhf5bf0a72001-11-23 00:24:12 +00002442 rc = balance(pCur->pBt, leafCur.pPage, pCur);
drh8c42ca92001-06-22 19:15:00 +00002443 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00002444 }else{
drh9ca7d3b2001-06-28 11:50:21 +00002445 dropCell(pPage, pCur->idx, cellSize(pCell));
drh5edc3122001-09-13 21:53:09 +00002446 if( pCur->idx>=pPage->nCell ){
2447 pCur->idx = pPage->nCell-1;
drhf5bf0a72001-11-23 00:24:12 +00002448 if( pCur->idx<0 ){
2449 pCur->idx = 0;
2450 pCur->bSkipNext = 1;
2451 }else{
2452 pCur->bSkipNext = 0;
2453 }
drh6019e162001-07-02 17:51:45 +00002454 }else{
2455 pCur->bSkipNext = 1;
2456 }
drh14acc042001-06-10 19:56:58 +00002457 rc = balance(pCur->pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002458 }
drh5e2f8b92001-05-28 00:41:15 +00002459 return rc;
drh3b7511c2001-05-26 13:15:44 +00002460}
drh8b2f49b2001-06-08 00:21:52 +00002461
2462/*
drhc6b52df2002-01-04 03:09:29 +00002463** Create a new BTree table. Write into *piTable the page
2464** number for the root page of the new table.
2465**
2466** In the current implementation, BTree tables and BTree indices are the
2467** the same. But in the future, we may change this so that BTree tables
2468** are restricted to having a 4-byte integer key and arbitrary data and
2469** BTree indices are restricted to having an arbitrary key and no data.
drh8b2f49b2001-06-08 00:21:52 +00002470*/
2471int sqliteBtreeCreateTable(Btree *pBt, int *piTable){
2472 MemPage *pRoot;
2473 Pgno pgnoRoot;
2474 int rc;
2475 if( !pBt->inTrans ){
2476 return SQLITE_ERROR; /* Must start a transaction first */
2477 }
drh5df72a52002-06-06 23:16:05 +00002478 if( pBt->readOnly ){
2479 return SQLITE_READONLY;
2480 }
drhbea00b92002-07-08 10:59:50 +00002481 rc = allocatePage(pBt, &pRoot, &pgnoRoot, 0);
drh8b2f49b2001-06-08 00:21:52 +00002482 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002483 assert( sqlitepager_iswriteable(pRoot) );
drh8b2f49b2001-06-08 00:21:52 +00002484 zeroPage(pRoot);
2485 sqlitepager_unref(pRoot);
2486 *piTable = (int)pgnoRoot;
2487 return SQLITE_OK;
2488}
2489
2490/*
drhc6b52df2002-01-04 03:09:29 +00002491** Create a new BTree index. Write into *piTable the page
2492** number for the root page of the new index.
2493**
2494** In the current implementation, BTree tables and BTree indices are the
2495** the same. But in the future, we may change this so that BTree tables
2496** are restricted to having a 4-byte integer key and arbitrary data and
2497** BTree indices are restricted to having an arbitrary key and no data.
2498*/
2499int sqliteBtreeCreateIndex(Btree *pBt, int *piIndex){
drh5df72a52002-06-06 23:16:05 +00002500 return sqliteBtreeCreateTable(pBt, piIndex);
drhc6b52df2002-01-04 03:09:29 +00002501}
2502
2503/*
drh8b2f49b2001-06-08 00:21:52 +00002504** Erase the given database page and all its children. Return
2505** the page to the freelist.
2506*/
drh2aa679f2001-06-25 02:11:07 +00002507static int clearDatabasePage(Btree *pBt, Pgno pgno, int freePageFlag){
drh8b2f49b2001-06-08 00:21:52 +00002508 MemPage *pPage;
2509 int rc;
drh8b2f49b2001-06-08 00:21:52 +00002510 Cell *pCell;
2511 int idx;
2512
drh8c42ca92001-06-22 19:15:00 +00002513 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pPage);
drh8b2f49b2001-06-08 00:21:52 +00002514 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002515 rc = sqlitepager_write(pPage);
2516 if( rc ) return rc;
drh7aa128d2002-06-21 13:09:16 +00002517 rc = initPage(pPage, pgno, 0);
2518 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002519 idx = pPage->u.hdr.firstCell;
drh8b2f49b2001-06-08 00:21:52 +00002520 while( idx>0 ){
drh14acc042001-06-10 19:56:58 +00002521 pCell = (Cell*)&pPage->u.aDisk[idx];
drh8b2f49b2001-06-08 00:21:52 +00002522 idx = pCell->h.iNext;
2523 if( pCell->h.leftChild ){
drh2aa679f2001-06-25 02:11:07 +00002524 rc = clearDatabasePage(pBt, pCell->h.leftChild, 1);
drh8b2f49b2001-06-08 00:21:52 +00002525 if( rc ) return rc;
2526 }
drh8c42ca92001-06-22 19:15:00 +00002527 rc = clearCell(pBt, pCell);
drh8b2f49b2001-06-08 00:21:52 +00002528 if( rc ) return rc;
2529 }
drh2aa679f2001-06-25 02:11:07 +00002530 if( pPage->u.hdr.rightChild ){
2531 rc = clearDatabasePage(pBt, pPage->u.hdr.rightChild, 1);
2532 if( rc ) return rc;
2533 }
2534 if( freePageFlag ){
2535 rc = freePage(pBt, pPage, pgno);
2536 }else{
2537 zeroPage(pPage);
2538 }
drhdd793422001-06-28 01:54:48 +00002539 sqlitepager_unref(pPage);
drh2aa679f2001-06-25 02:11:07 +00002540 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002541}
2542
2543/*
2544** Delete all information from a single table in the database.
2545*/
2546int sqliteBtreeClearTable(Btree *pBt, int iTable){
2547 int rc;
drh5a2c2c22001-11-21 02:21:11 +00002548 ptr nLock;
drh8b2f49b2001-06-08 00:21:52 +00002549 if( !pBt->inTrans ){
2550 return SQLITE_ERROR; /* Must start a transaction first */
2551 }
drh5df72a52002-06-06 23:16:05 +00002552 if( pBt->readOnly ){
2553 return SQLITE_READONLY;
2554 }
drh5a2c2c22001-11-21 02:21:11 +00002555 nLock = (ptr)sqliteHashFind(&pBt->locks, 0, iTable);
drhecdc7532001-09-23 02:35:53 +00002556 if( nLock ){
2557 return SQLITE_LOCKED;
2558 }
drh2aa679f2001-06-25 02:11:07 +00002559 rc = clearDatabasePage(pBt, (Pgno)iTable, 0);
drh8b2f49b2001-06-08 00:21:52 +00002560 if( rc ){
2561 sqliteBtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00002562 }
drh8c42ca92001-06-22 19:15:00 +00002563 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002564}
2565
2566/*
2567** Erase all information in a table and add the root of the table to
2568** the freelist. Except, the root of the principle table (the one on
2569** page 2) is never added to the freelist.
2570*/
2571int sqliteBtreeDropTable(Btree *pBt, int iTable){
2572 int rc;
2573 MemPage *pPage;
2574 if( !pBt->inTrans ){
2575 return SQLITE_ERROR; /* Must start a transaction first */
2576 }
drh5df72a52002-06-06 23:16:05 +00002577 if( pBt->readOnly ){
2578 return SQLITE_READONLY;
2579 }
drh8c42ca92001-06-22 19:15:00 +00002580 rc = sqlitepager_get(pBt->pPager, (Pgno)iTable, (void**)&pPage);
drh2aa679f2001-06-25 02:11:07 +00002581 if( rc ) return rc;
2582 rc = sqliteBtreeClearTable(pBt, iTable);
2583 if( rc ) return rc;
2584 if( iTable>2 ){
2585 rc = freePage(pBt, pPage, iTable);
2586 }else{
2587 zeroPage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00002588 }
drhdd793422001-06-28 01:54:48 +00002589 sqlitepager_unref(pPage);
drh8b2f49b2001-06-08 00:21:52 +00002590 return rc;
2591}
2592
2593/*
2594** Read the meta-information out of a database file.
2595*/
2596int sqliteBtreeGetMeta(Btree *pBt, int *aMeta){
2597 PageOne *pP1;
2598 int rc;
2599
drh8c42ca92001-06-22 19:15:00 +00002600 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00002601 if( rc ) return rc;
drh2aa679f2001-06-25 02:11:07 +00002602 aMeta[0] = pP1->nFree;
2603 memcpy(&aMeta[1], pP1->aMeta, sizeof(pP1->aMeta));
drh8b2f49b2001-06-08 00:21:52 +00002604 sqlitepager_unref(pP1);
2605 return SQLITE_OK;
2606}
2607
2608/*
2609** Write meta-information back into the database.
2610*/
2611int sqliteBtreeUpdateMeta(Btree *pBt, int *aMeta){
2612 PageOne *pP1;
2613 int rc;
2614 if( !pBt->inTrans ){
2615 return SQLITE_ERROR; /* Must start a transaction first */
2616 }
drh5df72a52002-06-06 23:16:05 +00002617 if( pBt->readOnly ){
2618 return SQLITE_READONLY;
2619 }
drh8b2f49b2001-06-08 00:21:52 +00002620 pP1 = pBt->page1;
2621 rc = sqlitepager_write(pP1);
drh9adf9ac2002-05-15 11:44:13 +00002622 if( rc ) return rc;
drh2aa679f2001-06-25 02:11:07 +00002623 memcpy(pP1->aMeta, &aMeta[1], sizeof(pP1->aMeta));
drh8b2f49b2001-06-08 00:21:52 +00002624 return SQLITE_OK;
2625}
drh8c42ca92001-06-22 19:15:00 +00002626
drh5eddca62001-06-30 21:53:53 +00002627/******************************************************************************
2628** The complete implementation of the BTree subsystem is above this line.
2629** All the code the follows is for testing and troubleshooting the BTree
2630** subsystem. None of the code that follows is used during normal operation.
drh5eddca62001-06-30 21:53:53 +00002631******************************************************************************/
drh5eddca62001-06-30 21:53:53 +00002632
drh8c42ca92001-06-22 19:15:00 +00002633/*
2634** Print a disassembly of the given page on standard output. This routine
2635** is used for debugging and testing only.
2636*/
drhaaab5722002-02-19 13:39:21 +00002637#ifdef SQLITE_TEST
drh6019e162001-07-02 17:51:45 +00002638int sqliteBtreePageDump(Btree *pBt, int pgno, int recursive){
drh8c42ca92001-06-22 19:15:00 +00002639 int rc;
2640 MemPage *pPage;
2641 int i, j;
2642 int nFree;
2643 u16 idx;
2644 char range[20];
2645 unsigned char payload[20];
2646 rc = sqlitepager_get(pBt->pPager, (Pgno)pgno, (void**)&pPage);
2647 if( rc ){
2648 return rc;
2649 }
drh6019e162001-07-02 17:51:45 +00002650 if( recursive ) printf("PAGE %d:\n", pgno);
drh8c42ca92001-06-22 19:15:00 +00002651 i = 0;
2652 idx = pPage->u.hdr.firstCell;
2653 while( idx>0 && idx<=SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2654 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
2655 int sz = cellSize(pCell);
2656 sprintf(range,"%d..%d", idx, idx+sz-1);
drh80ff32f2001-11-04 18:32:46 +00002657 sz = NKEY(pCell->h) + NDATA(pCell->h);
drh8c42ca92001-06-22 19:15:00 +00002658 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
2659 memcpy(payload, pCell->aPayload, sz);
2660 for(j=0; j<sz; j++){
2661 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
2662 }
2663 payload[sz] = 0;
2664 printf(
drh6019e162001-07-02 17:51:45 +00002665 "cell %2d: i=%-10s chld=%-4d nk=%-4d nd=%-4d payload=%s\n",
drh80ff32f2001-11-04 18:32:46 +00002666 i, range, (int)pCell->h.leftChild, NKEY(pCell->h), NDATA(pCell->h),
drh2aa679f2001-06-25 02:11:07 +00002667 payload
drh8c42ca92001-06-22 19:15:00 +00002668 );
drh6019e162001-07-02 17:51:45 +00002669 if( pPage->isInit && pPage->apCell[i]!=pCell ){
drh2aa679f2001-06-25 02:11:07 +00002670 printf("**** apCell[%d] does not match on prior entry ****\n", i);
2671 }
drh7c717f72001-06-24 20:39:41 +00002672 i++;
drh8c42ca92001-06-22 19:15:00 +00002673 idx = pCell->h.iNext;
2674 }
2675 if( idx!=0 ){
2676 printf("ERROR: next cell index out of range: %d\n", idx);
2677 }
2678 printf("right_child: %d\n", pPage->u.hdr.rightChild);
2679 nFree = 0;
2680 i = 0;
2681 idx = pPage->u.hdr.firstFree;
2682 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2683 FreeBlk *p = (FreeBlk*)&pPage->u.aDisk[idx];
2684 sprintf(range,"%d..%d", idx, idx+p->iSize-1);
2685 nFree += p->iSize;
2686 printf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
2687 i, range, p->iSize, nFree);
2688 idx = p->iNext;
drh2aa679f2001-06-25 02:11:07 +00002689 i++;
drh8c42ca92001-06-22 19:15:00 +00002690 }
2691 if( idx!=0 ){
2692 printf("ERROR: next freeblock index out of range: %d\n", idx);
2693 }
drh6019e162001-07-02 17:51:45 +00002694 if( recursive && pPage->u.hdr.rightChild!=0 ){
2695 idx = pPage->u.hdr.firstCell;
2696 while( idx>0 && idx<SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2697 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
2698 sqliteBtreePageDump(pBt, pCell->h.leftChild, 1);
2699 idx = pCell->h.iNext;
2700 }
2701 sqliteBtreePageDump(pBt, pPage->u.hdr.rightChild, 1);
2702 }
drh8c42ca92001-06-22 19:15:00 +00002703 sqlitepager_unref(pPage);
2704 return SQLITE_OK;
2705}
drhaaab5722002-02-19 13:39:21 +00002706#endif
drh8c42ca92001-06-22 19:15:00 +00002707
drhaaab5722002-02-19 13:39:21 +00002708#ifdef SQLITE_TEST
drh8c42ca92001-06-22 19:15:00 +00002709/*
drh2aa679f2001-06-25 02:11:07 +00002710** Fill aResult[] with information about the entry and page that the
2711** cursor is pointing to.
2712**
2713** aResult[0] = The page number
2714** aResult[1] = The entry number
2715** aResult[2] = Total number of entries on this page
2716** aResult[3] = Size of this entry
2717** aResult[4] = Number of free bytes on this page
2718** aResult[5] = Number of free blocks on the page
2719** aResult[6] = Page number of the left child of this entry
2720** aResult[7] = Page number of the right child for the whole page
drh5eddca62001-06-30 21:53:53 +00002721**
2722** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00002723*/
2724int sqliteBtreeCursorDump(BtCursor *pCur, int *aResult){
drh2aa679f2001-06-25 02:11:07 +00002725 int cnt, idx;
2726 MemPage *pPage = pCur->pPage;
2727 aResult[0] = sqlitepager_pagenumber(pPage);
drh8c42ca92001-06-22 19:15:00 +00002728 aResult[1] = pCur->idx;
drh2aa679f2001-06-25 02:11:07 +00002729 aResult[2] = pPage->nCell;
2730 if( pCur->idx>=0 && pCur->idx<pPage->nCell ){
2731 aResult[3] = cellSize(pPage->apCell[pCur->idx]);
2732 aResult[6] = pPage->apCell[pCur->idx]->h.leftChild;
2733 }else{
2734 aResult[3] = 0;
2735 aResult[6] = 0;
2736 }
2737 aResult[4] = pPage->nFree;
2738 cnt = 0;
2739 idx = pPage->u.hdr.firstFree;
2740 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2741 cnt++;
2742 idx = ((FreeBlk*)&pPage->u.aDisk[idx])->iNext;
2743 }
2744 aResult[5] = cnt;
2745 aResult[7] = pPage->u.hdr.rightChild;
drh8c42ca92001-06-22 19:15:00 +00002746 return SQLITE_OK;
2747}
drhaaab5722002-02-19 13:39:21 +00002748#endif
drhdd793422001-06-28 01:54:48 +00002749
drhaaab5722002-02-19 13:39:21 +00002750#ifdef SQLITE_TEST
drhdd793422001-06-28 01:54:48 +00002751/*
drh5eddca62001-06-30 21:53:53 +00002752** Return the pager associated with a BTree. This routine is used for
2753** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00002754*/
2755Pager *sqliteBtreePager(Btree *pBt){
2756 return pBt->pPager;
2757}
drhaaab5722002-02-19 13:39:21 +00002758#endif
drh5eddca62001-06-30 21:53:53 +00002759
2760/*
2761** This structure is passed around through all the sanity checking routines
2762** in order to keep track of some global state information.
2763*/
drhaaab5722002-02-19 13:39:21 +00002764typedef struct IntegrityCk IntegrityCk;
2765struct IntegrityCk {
drh100569d2001-10-02 13:01:48 +00002766 Btree *pBt; /* The tree being checked out */
2767 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
2768 int nPage; /* Number of pages in the database */
2769 int *anRef; /* Number of times each page is referenced */
2770 int nTreePage; /* Number of BTree pages */
2771 int nByte; /* Number of bytes of data stored on BTree pages */
2772 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00002773};
2774
2775/*
2776** Append a message to the error message string.
2777*/
drhaaab5722002-02-19 13:39:21 +00002778static void checkAppendMsg(IntegrityCk *pCheck, char *zMsg1, char *zMsg2){
drh5eddca62001-06-30 21:53:53 +00002779 if( pCheck->zErrMsg ){
2780 char *zOld = pCheck->zErrMsg;
2781 pCheck->zErrMsg = 0;
2782 sqliteSetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, 0);
2783 sqliteFree(zOld);
2784 }else{
2785 sqliteSetString(&pCheck->zErrMsg, zMsg1, zMsg2, 0);
2786 }
2787}
2788
2789/*
2790** Add 1 to the reference count for page iPage. If this is the second
2791** reference to the page, add an error message to pCheck->zErrMsg.
2792** Return 1 if there are 2 ore more references to the page and 0 if
2793** if this is the first reference to the page.
2794**
2795** Also check that the page number is in bounds.
2796*/
drhaaab5722002-02-19 13:39:21 +00002797static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00002798 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00002799 if( iPage>pCheck->nPage || iPage<0 ){
drh5eddca62001-06-30 21:53:53 +00002800 char zBuf[100];
2801 sprintf(zBuf, "invalid page number %d", iPage);
2802 checkAppendMsg(pCheck, zContext, zBuf);
2803 return 1;
2804 }
2805 if( pCheck->anRef[iPage]==1 ){
2806 char zBuf[100];
2807 sprintf(zBuf, "2nd reference to page %d", iPage);
2808 checkAppendMsg(pCheck, zContext, zBuf);
2809 return 1;
2810 }
2811 return (pCheck->anRef[iPage]++)>1;
2812}
2813
2814/*
2815** Check the integrity of the freelist or of an overflow page list.
2816** Verify that the number of pages on the list is N.
2817*/
drh30e58752002-03-02 20:41:57 +00002818static void checkList(
2819 IntegrityCk *pCheck, /* Integrity checking context */
2820 int isFreeList, /* True for a freelist. False for overflow page list */
2821 int iPage, /* Page number for first page in the list */
2822 int N, /* Expected number of pages in the list */
2823 char *zContext /* Context for error messages */
2824){
2825 int i;
drh5eddca62001-06-30 21:53:53 +00002826 char zMsg[100];
drh30e58752002-03-02 20:41:57 +00002827 while( N-- > 0 ){
drh5eddca62001-06-30 21:53:53 +00002828 OverflowPage *pOvfl;
2829 if( iPage<1 ){
2830 sprintf(zMsg, "%d pages missing from overflow list", N+1);
2831 checkAppendMsg(pCheck, zContext, zMsg);
2832 break;
2833 }
2834 if( checkRef(pCheck, iPage, zContext) ) break;
2835 if( sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
2836 sprintf(zMsg, "failed to get page %d", iPage);
2837 checkAppendMsg(pCheck, zContext, zMsg);
2838 break;
2839 }
drh30e58752002-03-02 20:41:57 +00002840 if( isFreeList ){
2841 FreelistInfo *pInfo = (FreelistInfo*)pOvfl->aPayload;
2842 for(i=0; i<pInfo->nFree; i++){
2843 checkRef(pCheck, pInfo->aFree[i], zMsg);
2844 }
2845 N -= pInfo->nFree;
2846 }
drh5eddca62001-06-30 21:53:53 +00002847 iPage = (int)pOvfl->iNext;
2848 sqlitepager_unref(pOvfl);
2849 }
2850}
2851
2852/*
drh1bffb9c2002-02-03 17:37:36 +00002853** Return negative if zKey1<zKey2.
2854** Return zero if zKey1==zKey2.
2855** Return positive if zKey1>zKey2.
2856*/
2857static int keyCompare(
2858 const char *zKey1, int nKey1,
2859 const char *zKey2, int nKey2
2860){
2861 int min = nKey1>nKey2 ? nKey2 : nKey1;
2862 int c = memcmp(zKey1, zKey2, min);
2863 if( c==0 ){
2864 c = nKey1 - nKey2;
2865 }
2866 return c;
2867}
2868
2869/*
drh5eddca62001-06-30 21:53:53 +00002870** Do various sanity checks on a single page of a tree. Return
2871** the tree depth. Root pages return 0. Parents of root pages
2872** return 1, and so forth.
2873**
2874** These checks are done:
2875**
2876** 1. Make sure that cells and freeblocks do not overlap
2877** but combine to completely cover the page.
2878** 2. Make sure cell keys are in order.
2879** 3. Make sure no key is less than or equal to zLowerBound.
2880** 4. Make sure no key is greater than or equal to zUpperBound.
2881** 5. Check the integrity of overflow pages.
2882** 6. Recursively call checkTreePage on all children.
2883** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00002884** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00002885** the root of the tree.
2886*/
2887static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00002888 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00002889 int iPage, /* Page number of the page to check */
2890 MemPage *pParent, /* Parent page */
2891 char *zParentContext, /* Parent context */
2892 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00002893 int nLower, /* Number of characters in zLowerBound */
2894 char *zUpperBound, /* All keys should be less than this, if not NULL */
2895 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00002896){
2897 MemPage *pPage;
2898 int i, rc, depth, d2, pgno;
2899 char *zKey1, *zKey2;
drh1bffb9c2002-02-03 17:37:36 +00002900 int nKey1, nKey2;
drh5eddca62001-06-30 21:53:53 +00002901 BtCursor cur;
2902 char zMsg[100];
2903 char zContext[100];
2904 char hit[SQLITE_PAGE_SIZE];
2905
2906 /* Check that the page exists
2907 */
2908 if( iPage==0 ) return 0;
2909 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
2910 sprintf(zContext, "On tree page %d: ", iPage);
2911 if( (rc = sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pPage))!=0 ){
2912 sprintf(zMsg, "unable to get the page. error code=%d", rc);
2913 checkAppendMsg(pCheck, zContext, zMsg);
2914 return 0;
2915 }
2916 if( (rc = initPage(pPage, (Pgno)iPage, pParent))!=0 ){
2917 sprintf(zMsg, "initPage() returns error code %d", rc);
2918 checkAppendMsg(pCheck, zContext, zMsg);
2919 sqlitepager_unref(pPage);
2920 return 0;
2921 }
2922
2923 /* Check out all the cells.
2924 */
2925 depth = 0;
drh1bffb9c2002-02-03 17:37:36 +00002926 if( zLowerBound ){
2927 zKey1 = sqliteMalloc( nLower+1 );
2928 memcpy(zKey1, zLowerBound, nLower);
2929 zKey1[nLower] = 0;
2930 }else{
2931 zKey1 = 0;
2932 }
2933 nKey1 = nLower;
drh5eddca62001-06-30 21:53:53 +00002934 cur.pPage = pPage;
2935 cur.pBt = pCheck->pBt;
2936 for(i=0; i<pPage->nCell; i++){
2937 Cell *pCell = pPage->apCell[i];
2938 int sz;
2939
2940 /* Check payload overflow pages
2941 */
drh1bffb9c2002-02-03 17:37:36 +00002942 nKey2 = NKEY(pCell->h);
2943 sz = nKey2 + NDATA(pCell->h);
drh5eddca62001-06-30 21:53:53 +00002944 sprintf(zContext, "On page %d cell %d: ", iPage, i);
2945 if( sz>MX_LOCAL_PAYLOAD ){
2946 int nPage = (sz - MX_LOCAL_PAYLOAD + OVERFLOW_SIZE - 1)/OVERFLOW_SIZE;
drh30e58752002-03-02 20:41:57 +00002947 checkList(pCheck, 0, pCell->ovfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00002948 }
2949
2950 /* Check that keys are in the right order
2951 */
2952 cur.idx = i;
drh1bffb9c2002-02-03 17:37:36 +00002953 zKey2 = sqliteMalloc( nKey2+1 );
2954 getPayload(&cur, 0, nKey2, zKey2);
2955 if( zKey1 && keyCompare(zKey1, nKey1, zKey2, nKey2)>=0 ){
drh5eddca62001-06-30 21:53:53 +00002956 checkAppendMsg(pCheck, zContext, "Key is out of order");
2957 }
2958
2959 /* Check sanity of left child page.
2960 */
2961 pgno = (int)pCell->h.leftChild;
drh1bffb9c2002-02-03 17:37:36 +00002962 d2 = checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zKey2,nKey2);
drh5eddca62001-06-30 21:53:53 +00002963 if( i>0 && d2!=depth ){
2964 checkAppendMsg(pCheck, zContext, "Child page depth differs");
2965 }
2966 depth = d2;
2967 sqliteFree(zKey1);
2968 zKey1 = zKey2;
drh1bffb9c2002-02-03 17:37:36 +00002969 nKey1 = nKey2;
drh5eddca62001-06-30 21:53:53 +00002970 }
2971 pgno = pPage->u.hdr.rightChild;
2972 sprintf(zContext, "On page %d at right child: ", iPage);
drh1bffb9c2002-02-03 17:37:36 +00002973 checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zUpperBound,nUpper);
drh5eddca62001-06-30 21:53:53 +00002974 sqliteFree(zKey1);
2975
2976 /* Check for complete coverage of the page
2977 */
2978 memset(hit, 0, sizeof(hit));
2979 memset(hit, 1, sizeof(PageHdr));
2980 for(i=pPage->u.hdr.firstCell; i>0 && i<SQLITE_PAGE_SIZE; ){
2981 Cell *pCell = (Cell*)&pPage->u.aDisk[i];
2982 int j;
2983 for(j=i+cellSize(pCell)-1; j>=i; j--) hit[j]++;
2984 i = pCell->h.iNext;
2985 }
2986 for(i=pPage->u.hdr.firstFree; i>0 && i<SQLITE_PAGE_SIZE; ){
2987 FreeBlk *pFBlk = (FreeBlk*)&pPage->u.aDisk[i];
2988 int j;
2989 for(j=i+pFBlk->iSize-1; j>=i; j--) hit[j]++;
2990 i = pFBlk->iNext;
2991 }
2992 for(i=0; i<SQLITE_PAGE_SIZE; i++){
2993 if( hit[i]==0 ){
2994 sprintf(zMsg, "Unused space at byte %d of page %d", i, iPage);
2995 checkAppendMsg(pCheck, zMsg, 0);
2996 break;
2997 }else if( hit[i]>1 ){
2998 sprintf(zMsg, "Multiple uses for byte %d of page %d", i, iPage);
2999 checkAppendMsg(pCheck, zMsg, 0);
3000 break;
3001 }
3002 }
3003
3004 /* Check that free space is kept to a minimum
3005 */
drh6019e162001-07-02 17:51:45 +00003006#if 0
3007 if( pParent && pParent->nCell>2 && pPage->nFree>3*SQLITE_PAGE_SIZE/4 ){
drh5eddca62001-06-30 21:53:53 +00003008 sprintf(zMsg, "free space (%d) greater than max (%d)", pPage->nFree,
3009 SQLITE_PAGE_SIZE/3);
3010 checkAppendMsg(pCheck, zContext, zMsg);
3011 }
drh6019e162001-07-02 17:51:45 +00003012#endif
3013
3014 /* Update freespace totals.
3015 */
3016 pCheck->nTreePage++;
3017 pCheck->nByte += USABLE_SPACE - pPage->nFree;
drh5eddca62001-06-30 21:53:53 +00003018
3019 sqlitepager_unref(pPage);
3020 return depth;
3021}
3022
3023/*
3024** This routine does a complete check of the given BTree file. aRoot[] is
3025** an array of pages numbers were each page number is the root page of
3026** a table. nRoot is the number of entries in aRoot.
3027**
3028** If everything checks out, this routine returns NULL. If something is
3029** amiss, an error message is written into memory obtained from malloc()
3030** and a pointer to that error message is returned. The calling function
3031** is responsible for freeing the error message when it is done.
3032*/
drhaaab5722002-02-19 13:39:21 +00003033char *sqliteBtreeIntegrityCheck(Btree *pBt, int *aRoot, int nRoot){
drh5eddca62001-06-30 21:53:53 +00003034 int i;
3035 int nRef;
drhaaab5722002-02-19 13:39:21 +00003036 IntegrityCk sCheck;
drh5eddca62001-06-30 21:53:53 +00003037
3038 nRef = *sqlitepager_stats(pBt->pPager);
drhefc251d2001-07-01 22:12:01 +00003039 if( lockBtree(pBt)!=SQLITE_OK ){
3040 return sqliteStrDup("Unable to acquire a read lock on the database");
3041 }
drh5eddca62001-06-30 21:53:53 +00003042 sCheck.pBt = pBt;
3043 sCheck.pPager = pBt->pPager;
3044 sCheck.nPage = sqlitepager_pagecount(sCheck.pPager);
drh0de8c112002-07-06 16:32:14 +00003045 if( sCheck.nPage==0 ){
3046 unlockBtreeIfUnused(pBt);
3047 return 0;
3048 }
drh5eddca62001-06-30 21:53:53 +00003049 sCheck.anRef = sqliteMalloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
3050 sCheck.anRef[1] = 1;
3051 for(i=2; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
3052 sCheck.zErrMsg = 0;
3053
3054 /* Check the integrity of the freelist
3055 */
drh30e58752002-03-02 20:41:57 +00003056 checkList(&sCheck, 1, pBt->page1->freeList, pBt->page1->nFree,
3057 "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00003058
3059 /* Check all the tables.
3060 */
3061 for(i=0; i<nRoot; i++){
drh4ff6dfa2002-03-03 23:06:00 +00003062 if( aRoot[i]==0 ) continue;
drh1bffb9c2002-02-03 17:37:36 +00003063 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00003064 }
3065
3066 /* Make sure every page in the file is referenced
3067 */
3068 for(i=1; i<=sCheck.nPage; i++){
3069 if( sCheck.anRef[i]==0 ){
3070 char zBuf[100];
3071 sprintf(zBuf, "Page %d is never used", i);
3072 checkAppendMsg(&sCheck, zBuf, 0);
3073 }
3074 }
3075
3076 /* Make sure this analysis did not leave any unref() pages
3077 */
drh5e00f6c2001-09-13 13:46:56 +00003078 unlockBtreeIfUnused(pBt);
drh5eddca62001-06-30 21:53:53 +00003079 if( nRef != *sqlitepager_stats(pBt->pPager) ){
3080 char zBuf[100];
3081 sprintf(zBuf,
3082 "Outstanding page count goes from %d to %d during this analysis",
3083 nRef, *sqlitepager_stats(pBt->pPager)
3084 );
3085 checkAppendMsg(&sCheck, zBuf, 0);
3086 }
3087
3088 /* Clean up and report errors.
3089 */
3090 sqliteFree(sCheck.anRef);
3091 return sCheck.zErrMsg;
3092}