blob: e381f92e6d18ce5ccf9a9f80e765966fbae88c82 [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*************************************************************************
drh5a2c2c22001-11-21 02:21:11 +000012** $Id: btree.c,v 1.40 2001/11/21 02:21:12 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;
67
68/*
69** All structures on a database page are aligned to 4-byte boundries.
70** This routine rounds up a number of bytes to the next multiple of 4.
drh306dc212001-05-21 13:45:10 +000071**
72** This might need to change for computer architectures that require
73** and 8-byte alignment boundry for structures.
drh2af926b2001-05-15 00:39:25 +000074*/
75#define ROUNDUP(X) ((X+3) & ~3)
drha059ad02001-04-17 20:09:11 +000076
drh08ed44e2001-04-29 23:32:55 +000077/*
drhbd03cae2001-06-02 02:40:57 +000078** This is a magic string that appears at the beginning of every
drh8c42ca92001-06-22 19:15:00 +000079** SQLite database in order to identify the file as a real database.
drh08ed44e2001-04-29 23:32:55 +000080*/
drhbd03cae2001-06-02 02:40:57 +000081static const char zMagicHeader[] =
drh80ff32f2001-11-04 18:32:46 +000082 "** This file contains an SQLite 2.1 database **";
drhbd03cae2001-06-02 02:40:57 +000083#define MAGIC_SIZE (sizeof(zMagicHeader))
drh08ed44e2001-04-29 23:32:55 +000084
85/*
drh5e00f6c2001-09-13 13:46:56 +000086** This is a magic integer also used to test the integrity of the database
drh8c42ca92001-06-22 19:15:00 +000087** file. This integer is used in addition to the string above so that
88** if the file is written on a little-endian architecture and read
89** on a big-endian architectures (or vice versa) we can detect the
90** problem.
91**
92** The number used was obtained at random and has no special
drhb19a2bc2001-09-16 00:13:26 +000093** significance other than the fact that it represents a different
94** integer on little-endian and big-endian machines.
drh8c42ca92001-06-22 19:15:00 +000095*/
96#define MAGIC 0xdae37528
97
98/*
drhbd03cae2001-06-02 02:40:57 +000099** The first page of the database file contains a magic header string
100** to identify the file as an SQLite database file. It also contains
101** a pointer to the first free page of the file. Page 2 contains the
drh8b2f49b2001-06-08 00:21:52 +0000102** root of the principle BTree. The file might contain other BTrees
103** rooted on pages above 2.
104**
105** The first page also contains SQLITE_N_BTREE_META integers that
106** can be used by higher-level routines.
drh08ed44e2001-04-29 23:32:55 +0000107**
drhbd03cae2001-06-02 02:40:57 +0000108** Remember that pages are numbered beginning with 1. (See pager.c
109** for additional information.) Page 0 does not exist and a page
110** number of 0 is used to mean "no such page".
111*/
112struct PageOne {
113 char zMagic[MAGIC_SIZE]; /* String that identifies the file as a database */
drh8c42ca92001-06-22 19:15:00 +0000114 int iMagic; /* Integer to verify correct byte order */
115 Pgno freeList; /* First free page in a list of all free pages */
drh2aa679f2001-06-25 02:11:07 +0000116 int nFree; /* Number of pages on the free list */
117 int aMeta[SQLITE_N_BTREE_META-1]; /* User defined integers */
drhbd03cae2001-06-02 02:40:57 +0000118};
119
120/*
121** Each database page has a header that is an instance of this
122** structure.
drh08ed44e2001-04-29 23:32:55 +0000123**
drh8b2f49b2001-06-08 00:21:52 +0000124** PageHdr.firstFree is 0 if there is no free space on this page.
drh14acc042001-06-10 19:56:58 +0000125** Otherwise, PageHdr.firstFree is the index in MemPage.u.aDisk[] of a
drh8b2f49b2001-06-08 00:21:52 +0000126** FreeBlk structure that describes the first block of free space.
127** All free space is defined by a linked list of FreeBlk structures.
drh08ed44e2001-04-29 23:32:55 +0000128**
drh8b2f49b2001-06-08 00:21:52 +0000129** Data is stored in a linked list of Cell structures. PageHdr.firstCell
drh14acc042001-06-10 19:56:58 +0000130** is the index into MemPage.u.aDisk[] of the first cell on the page. The
drh306dc212001-05-21 13:45:10 +0000131** Cells are kept in sorted order.
drh8b2f49b2001-06-08 00:21:52 +0000132**
133** A Cell contains all information about a database entry and a pointer
134** to a child page that contains other entries less than itself. In
135** other words, the i-th Cell contains both Ptr(i) and Key(i). The
136** right-most pointer of the page is contained in PageHdr.rightChild.
drh08ed44e2001-04-29 23:32:55 +0000137*/
drh365d68f2001-05-11 11:02:46 +0000138struct PageHdr {
drh5e2f8b92001-05-28 00:41:15 +0000139 Pgno rightChild; /* Child page that comes after all cells on this page */
drh14acc042001-06-10 19:56:58 +0000140 u16 firstCell; /* Index in MemPage.u.aDisk[] of the first cell */
141 u16 firstFree; /* Index in MemPage.u.aDisk[] of the first free block */
drh365d68f2001-05-11 11:02:46 +0000142};
drh306dc212001-05-21 13:45:10 +0000143
drh3b7511c2001-05-26 13:15:44 +0000144/*
145** Entries on a page of the database are called "Cells". Each Cell
146** has a header and data. This structure defines the header. The
drhbd03cae2001-06-02 02:40:57 +0000147** key and data (collectively the "payload") follow this header on
148** the database page.
149**
150** A definition of the complete Cell structure is given below. The
drh8c42ca92001-06-22 19:15:00 +0000151** header for the cell must be defined first in order to do some
drhbd03cae2001-06-02 02:40:57 +0000152** of the sizing #defines that follow.
drh3b7511c2001-05-26 13:15:44 +0000153*/
154struct CellHdr {
drh5e2f8b92001-05-28 00:41:15 +0000155 Pgno leftChild; /* Child page that comes before this cell */
drh3b7511c2001-05-26 13:15:44 +0000156 u16 nKey; /* Number of bytes in the key */
drh14acc042001-06-10 19:56:58 +0000157 u16 iNext; /* Index in MemPage.u.aDisk[] of next cell in sorted order */
drh58a11682001-11-10 13:51:08 +0000158 u8 nKeyHi; /* Upper 8 bits of key size for keys larger than 64K bytes */
159 u8 nDataHi; /* Upper 8 bits of data size when the size is more than 64K */
drh80ff32f2001-11-04 18:32:46 +0000160 u16 nData; /* Number of bytes of data */
drh8c42ca92001-06-22 19:15:00 +0000161};
drh58a11682001-11-10 13:51:08 +0000162
163/*
164** The key and data size are split into a lower 16-bit segment and an
165** upper 8-bit segment in order to pack them together into a smaller
166** space. The following macros reassembly a key or data size back
167** into an integer.
168*/
drh80ff32f2001-11-04 18:32:46 +0000169#define NKEY(h) (h.nKey + h.nKeyHi*65536)
170#define NDATA(h) (h.nData + h.nDataHi*65536)
drh3b7511c2001-05-26 13:15:44 +0000171
172/*
173** The minimum size of a complete Cell. The Cell must contain a header
drhbd03cae2001-06-02 02:40:57 +0000174** and at least 4 bytes of payload.
drh3b7511c2001-05-26 13:15:44 +0000175*/
176#define MIN_CELL_SIZE (sizeof(CellHdr)+4)
177
178/*
179** The maximum number of database entries that can be held in a single
180** page of the database.
181*/
182#define MX_CELL ((SQLITE_PAGE_SIZE-sizeof(PageHdr))/MIN_CELL_SIZE)
183
184/*
drh6019e162001-07-02 17:51:45 +0000185** The amount of usable space on a single page of the BTree. This is the
186** page size minus the overhead of the page header.
187*/
188#define USABLE_SPACE (SQLITE_PAGE_SIZE - sizeof(PageHdr))
189
190/*
drh8c42ca92001-06-22 19:15:00 +0000191** The maximum amount of payload (in bytes) that can be stored locally for
192** a database entry. If the entry contains more data than this, the
drh3b7511c2001-05-26 13:15:44 +0000193** extra goes onto overflow pages.
drhbd03cae2001-06-02 02:40:57 +0000194**
195** This number is chosen so that at least 4 cells will fit on every page.
drh3b7511c2001-05-26 13:15:44 +0000196*/
drh6019e162001-07-02 17:51:45 +0000197#define MX_LOCAL_PAYLOAD ((USABLE_SPACE/4-(sizeof(CellHdr)+sizeof(Pgno)))&~3)
drh3b7511c2001-05-26 13:15:44 +0000198
drh306dc212001-05-21 13:45:10 +0000199/*
200** Data on a database page is stored as a linked list of Cell structures.
drh5e2f8b92001-05-28 00:41:15 +0000201** Both the key and the data are stored in aPayload[]. The key always comes
202** first. The aPayload[] field grows as necessary to hold the key and data,
drh306dc212001-05-21 13:45:10 +0000203** up to a maximum of MX_LOCAL_PAYLOAD bytes. If the size of the key and
drh3b7511c2001-05-26 13:15:44 +0000204** data combined exceeds MX_LOCAL_PAYLOAD bytes, then Cell.ovfl is the
205** page number of the first overflow page.
206**
207** Though this structure is fixed in size, the Cell on the database
drhbd03cae2001-06-02 02:40:57 +0000208** page varies in size. Every cell has a CellHdr and at least 4 bytes
drh3b7511c2001-05-26 13:15:44 +0000209** of payload space. Additional payload bytes (up to the maximum of
210** MX_LOCAL_PAYLOAD) and the Cell.ovfl value are allocated only as
211** needed.
drh306dc212001-05-21 13:45:10 +0000212*/
drh365d68f2001-05-11 11:02:46 +0000213struct Cell {
drh5e2f8b92001-05-28 00:41:15 +0000214 CellHdr h; /* The cell header */
215 char aPayload[MX_LOCAL_PAYLOAD]; /* Key and data */
216 Pgno ovfl; /* The first overflow page */
drh365d68f2001-05-11 11:02:46 +0000217};
drh306dc212001-05-21 13:45:10 +0000218
219/*
220** Free space on a page is remembered using a linked list of the FreeBlk
221** structures. Space on a database page is allocated in increments of
drh72f82862001-05-24 21:06:34 +0000222** at least 4 bytes and is always aligned to a 4-byte boundry. The
drh8b2f49b2001-06-08 00:21:52 +0000223** linked list of FreeBlks is always kept in order by address.
drh306dc212001-05-21 13:45:10 +0000224*/
drh365d68f2001-05-11 11:02:46 +0000225struct FreeBlk {
drh72f82862001-05-24 21:06:34 +0000226 u16 iSize; /* Number of bytes in this block of free space */
drh14acc042001-06-10 19:56:58 +0000227 u16 iNext; /* Index in MemPage.u.aDisk[] of the next free block */
drh365d68f2001-05-11 11:02:46 +0000228};
drh306dc212001-05-21 13:45:10 +0000229
230/*
drh14acc042001-06-10 19:56:58 +0000231** The number of bytes of payload that will fit on a single overflow page.
drh3b7511c2001-05-26 13:15:44 +0000232*/
233#define OVERFLOW_SIZE (SQLITE_PAGE_SIZE-sizeof(Pgno))
234
235/*
drh306dc212001-05-21 13:45:10 +0000236** When the key and data for a single entry in the BTree will not fit in
drh8c42ca92001-06-22 19:15:00 +0000237** the MX_LOCAL_PAYLOAD bytes of space available on the database page,
drh8b2f49b2001-06-08 00:21:52 +0000238** then all extra bytes are written to a linked list of overflow pages.
drh306dc212001-05-21 13:45:10 +0000239** Each overflow page is an instance of the following structure.
240**
241** Unused pages in the database are also represented by instances of
drhbd03cae2001-06-02 02:40:57 +0000242** the OverflowPage structure. The PageOne.freeList field is the
drh306dc212001-05-21 13:45:10 +0000243** page number of the first page in a linked list of unused database
244** pages.
245*/
drh2af926b2001-05-15 00:39:25 +0000246struct OverflowPage {
drh14acc042001-06-10 19:56:58 +0000247 Pgno iNext;
drh5e2f8b92001-05-28 00:41:15 +0000248 char aPayload[OVERFLOW_SIZE];
drh7e3b0a02001-04-28 16:52:40 +0000249};
drh7e3b0a02001-04-28 16:52:40 +0000250
251/*
252** For every page in the database file, an instance of the following structure
drh14acc042001-06-10 19:56:58 +0000253** is stored in memory. The u.aDisk[] array contains the raw bits read from
drhbd03cae2001-06-02 02:40:57 +0000254** the disk. The rest is auxiliary information that held in memory only. The
255** auxiliary info is only valid for regular database pages - it is not
256** used for overflow pages and pages on the freelist.
drh306dc212001-05-21 13:45:10 +0000257**
drhbd03cae2001-06-02 02:40:57 +0000258** Of particular interest in the auxiliary info is the apCell[] entry. Each
drh14acc042001-06-10 19:56:58 +0000259** apCell[] entry is a pointer to a Cell structure in u.aDisk[]. The cells are
drh306dc212001-05-21 13:45:10 +0000260** put in this array so that they can be accessed in constant time, rather
drhbd03cae2001-06-02 02:40:57 +0000261** than in linear time which would be needed if we had to walk the linked
262** list on every access.
drh72f82862001-05-24 21:06:34 +0000263**
drh14acc042001-06-10 19:56:58 +0000264** Note that apCell[] contains enough space to hold up to two more Cells
265** than can possibly fit on one page. In the steady state, every apCell[]
266** points to memory inside u.aDisk[]. But in the middle of an insert
267** operation, some apCell[] entries may temporarily point to data space
268** outside of u.aDisk[]. This is a transient situation that is quickly
269** resolved. But while it is happening, it is possible for a database
270** page to hold as many as two more cells than it might otherwise hold.
drh18b81e52001-11-01 13:52:52 +0000271** The extra two entries in apCell[] are an allowance for this situation.
drh14acc042001-06-10 19:56:58 +0000272**
drh72f82862001-05-24 21:06:34 +0000273** The pParent field points back to the parent page. This allows us to
274** walk up the BTree from any leaf to the root. Care must be taken to
275** unref() the parent page pointer when this page is no longer referenced.
drhbd03cae2001-06-02 02:40:57 +0000276** The pageDestructor() routine handles that chore.
drh7e3b0a02001-04-28 16:52:40 +0000277*/
278struct MemPage {
drh14acc042001-06-10 19:56:58 +0000279 union {
280 char aDisk[SQLITE_PAGE_SIZE]; /* Page data stored on disk */
281 PageHdr hdr; /* Overlay page header */
282 } u;
drh5e2f8b92001-05-28 00:41:15 +0000283 int isInit; /* True if auxiliary data is initialized */
drh72f82862001-05-24 21:06:34 +0000284 MemPage *pParent; /* The parent of this page. NULL for root */
drh14acc042001-06-10 19:56:58 +0000285 int nFree; /* Number of free bytes in u.aDisk[] */
drh306dc212001-05-21 13:45:10 +0000286 int nCell; /* Number of entries on this page */
drh14acc042001-06-10 19:56:58 +0000287 int isOverfull; /* Some apCell[] points outside u.aDisk[] */
288 Cell *apCell[MX_CELL+2]; /* All data entires in sorted order */
drh8c42ca92001-06-22 19:15:00 +0000289};
drh7e3b0a02001-04-28 16:52:40 +0000290
291/*
drh3b7511c2001-05-26 13:15:44 +0000292** The in-memory image of a disk page has the auxiliary information appended
293** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
294** that extra information.
295*/
296#define EXTRA_SIZE (sizeof(MemPage)-SQLITE_PAGE_SIZE)
297
298/*
drha059ad02001-04-17 20:09:11 +0000299** Everything we need to know about an open database
300*/
301struct Btree {
302 Pager *pPager; /* The page cache */
drh306dc212001-05-21 13:45:10 +0000303 BtCursor *pCursor; /* A list of all open cursors */
drhbd03cae2001-06-02 02:40:57 +0000304 PageOne *page1; /* First page of the database */
drh306dc212001-05-21 13:45:10 +0000305 int inTrans; /* True if a transaction is in progress */
drhecdc7532001-09-23 02:35:53 +0000306 Hash locks; /* Key: root page number. Data: lock count */
drha059ad02001-04-17 20:09:11 +0000307};
308typedef Btree Bt;
309
drh365d68f2001-05-11 11:02:46 +0000310/*
311** A cursor is a pointer to a particular entry in the BTree.
312** The entry is identified by its MemPage and the index in
drh5e2f8b92001-05-28 00:41:15 +0000313** MemPage.apCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000314*/
drh72f82862001-05-24 21:06:34 +0000315struct BtCursor {
drh5e2f8b92001-05-28 00:41:15 +0000316 Btree *pBt; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000317 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drh8b2f49b2001-06-08 00:21:52 +0000318 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000319 MemPage *pPage; /* Page that contains the entry */
drh8c42ca92001-06-22 19:15:00 +0000320 int idx; /* Index of the entry in pPage->apCell[] */
drhecdc7532001-09-23 02:35:53 +0000321 u8 wrFlag; /* True if writable */
drh5e2f8b92001-05-28 00:41:15 +0000322 u8 bSkipNext; /* sqliteBtreeNext() is no-op if true */
323 u8 iMatch; /* compare result from last sqliteBtreeMoveto() */
drh365d68f2001-05-11 11:02:46 +0000324};
drh7e3b0a02001-04-28 16:52:40 +0000325
drha059ad02001-04-17 20:09:11 +0000326/*
drh3b7511c2001-05-26 13:15:44 +0000327** Compute the total number of bytes that a Cell needs on the main
drh5e2f8b92001-05-28 00:41:15 +0000328** database page. The number returned includes the Cell header,
329** local payload storage, and the pointer to overflow pages (if
drh8c42ca92001-06-22 19:15:00 +0000330** applicable). Additional space allocated on overflow pages
drhbd03cae2001-06-02 02:40:57 +0000331** is NOT included in the value returned from this routine.
drh3b7511c2001-05-26 13:15:44 +0000332*/
333static int cellSize(Cell *pCell){
drh80ff32f2001-11-04 18:32:46 +0000334 int n = NKEY(pCell->h) + NDATA(pCell->h);
drh3b7511c2001-05-26 13:15:44 +0000335 if( n>MX_LOCAL_PAYLOAD ){
336 n = MX_LOCAL_PAYLOAD + sizeof(Pgno);
337 }else{
338 n = ROUNDUP(n);
339 }
340 n += sizeof(CellHdr);
341 return n;
342}
343
344/*
drh72f82862001-05-24 21:06:34 +0000345** Defragment the page given. All Cells are moved to the
346** beginning of the page and all free space is collected
347** into one big FreeBlk at the end of the page.
drh365d68f2001-05-11 11:02:46 +0000348*/
349static void defragmentPage(MemPage *pPage){
drh14acc042001-06-10 19:56:58 +0000350 int pc, i, n;
drh2af926b2001-05-15 00:39:25 +0000351 FreeBlk *pFBlk;
352 char newPage[SQLITE_PAGE_SIZE];
353
drh6019e162001-07-02 17:51:45 +0000354 assert( sqlitepager_iswriteable(pPage) );
drhbd03cae2001-06-02 02:40:57 +0000355 pc = sizeof(PageHdr);
drh14acc042001-06-10 19:56:58 +0000356 pPage->u.hdr.firstCell = pc;
357 memcpy(newPage, pPage->u.aDisk, pc);
drh2af926b2001-05-15 00:39:25 +0000358 for(i=0; i<pPage->nCell; i++){
drh2aa679f2001-06-25 02:11:07 +0000359 Cell *pCell = pPage->apCell[i];
drh8c42ca92001-06-22 19:15:00 +0000360
361 /* This routine should never be called on an overfull page. The
362 ** following asserts verify that constraint. */
drh7c717f72001-06-24 20:39:41 +0000363 assert( Addr(pCell) > Addr(pPage) );
364 assert( Addr(pCell) < Addr(pPage) + SQLITE_PAGE_SIZE );
drh8c42ca92001-06-22 19:15:00 +0000365
drh3b7511c2001-05-26 13:15:44 +0000366 n = cellSize(pCell);
drh2aa679f2001-06-25 02:11:07 +0000367 pCell->h.iNext = pc + n;
drh2af926b2001-05-15 00:39:25 +0000368 memcpy(&newPage[pc], pCell, n);
drh14acc042001-06-10 19:56:58 +0000369 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[pc];
drh2af926b2001-05-15 00:39:25 +0000370 pc += n;
371 }
drh72f82862001-05-24 21:06:34 +0000372 assert( pPage->nFree==SQLITE_PAGE_SIZE-pc );
drh14acc042001-06-10 19:56:58 +0000373 memcpy(pPage->u.aDisk, newPage, pc);
drh2aa679f2001-06-25 02:11:07 +0000374 if( pPage->nCell>0 ){
375 pPage->apCell[pPage->nCell-1]->h.iNext = 0;
376 }
drh8c42ca92001-06-22 19:15:00 +0000377 pFBlk = (FreeBlk*)&pPage->u.aDisk[pc];
drh2af926b2001-05-15 00:39:25 +0000378 pFBlk->iSize = SQLITE_PAGE_SIZE - pc;
379 pFBlk->iNext = 0;
drh14acc042001-06-10 19:56:58 +0000380 pPage->u.hdr.firstFree = pc;
drh2af926b2001-05-15 00:39:25 +0000381 memset(&pFBlk[1], 0, SQLITE_PAGE_SIZE - pc - sizeof(FreeBlk));
drh365d68f2001-05-11 11:02:46 +0000382}
383
drha059ad02001-04-17 20:09:11 +0000384/*
drh8b2f49b2001-06-08 00:21:52 +0000385** Allocate nByte bytes of space on a page. nByte must be a
386** multiple of 4.
drhbd03cae2001-06-02 02:40:57 +0000387**
drh14acc042001-06-10 19:56:58 +0000388** Return the index into pPage->u.aDisk[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000389** the new allocation. Or return 0 if there is not enough free
390** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000391**
drh72f82862001-05-24 21:06:34 +0000392** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000393** nBytes of contiguous free space, then this routine automatically
394** calls defragementPage() to consolidate all free space before
395** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000396*/
drhbd03cae2001-06-02 02:40:57 +0000397static int allocateSpace(MemPage *pPage, int nByte){
drh2af926b2001-05-15 00:39:25 +0000398 FreeBlk *p;
399 u16 *pIdx;
400 int start;
drh8c42ca92001-06-22 19:15:00 +0000401 int cnt = 0;
drh72f82862001-05-24 21:06:34 +0000402
drh6019e162001-07-02 17:51:45 +0000403 assert( sqlitepager_iswriteable(pPage) );
drh5e2f8b92001-05-28 00:41:15 +0000404 assert( nByte==ROUNDUP(nByte) );
drh14acc042001-06-10 19:56:58 +0000405 if( pPage->nFree<nByte || pPage->isOverfull ) return 0;
406 pIdx = &pPage->u.hdr.firstFree;
407 p = (FreeBlk*)&pPage->u.aDisk[*pIdx];
drh2af926b2001-05-15 00:39:25 +0000408 while( p->iSize<nByte ){
drh8c42ca92001-06-22 19:15:00 +0000409 assert( cnt++ < SQLITE_PAGE_SIZE/4 );
drh2af926b2001-05-15 00:39:25 +0000410 if( p->iNext==0 ){
411 defragmentPage(pPage);
drh14acc042001-06-10 19:56:58 +0000412 pIdx = &pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000413 }else{
414 pIdx = &p->iNext;
415 }
drh14acc042001-06-10 19:56:58 +0000416 p = (FreeBlk*)&pPage->u.aDisk[*pIdx];
drh2af926b2001-05-15 00:39:25 +0000417 }
418 if( p->iSize==nByte ){
419 start = *pIdx;
420 *pIdx = p->iNext;
421 }else{
drh8c42ca92001-06-22 19:15:00 +0000422 FreeBlk *pNew;
drh72f82862001-05-24 21:06:34 +0000423 start = *pIdx;
drh8c42ca92001-06-22 19:15:00 +0000424 pNew = (FreeBlk*)&pPage->u.aDisk[start + nByte];
drh72f82862001-05-24 21:06:34 +0000425 pNew->iNext = p->iNext;
426 pNew->iSize = p->iSize - nByte;
427 *pIdx = start + nByte;
drh2af926b2001-05-15 00:39:25 +0000428 }
429 pPage->nFree -= nByte;
430 return start;
drh7e3b0a02001-04-28 16:52:40 +0000431}
432
433/*
drh14acc042001-06-10 19:56:58 +0000434** Return a section of the MemPage.u.aDisk[] to the freelist.
435** The first byte of the new free block is pPage->u.aDisk[start]
436** and the size of the block is "size" bytes. Size must be
437** a multiple of 4.
drh306dc212001-05-21 13:45:10 +0000438**
439** Most of the effort here is involved in coalesing adjacent
440** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000441*/
442static void freeSpace(MemPage *pPage, int start, int size){
drh2af926b2001-05-15 00:39:25 +0000443 int end = start + size;
444 u16 *pIdx, idx;
445 FreeBlk *pFBlk;
446 FreeBlk *pNew;
447 FreeBlk *pNext;
448
drh6019e162001-07-02 17:51:45 +0000449 assert( sqlitepager_iswriteable(pPage) );
drh2af926b2001-05-15 00:39:25 +0000450 assert( size == ROUNDUP(size) );
451 assert( start == ROUNDUP(start) );
drh14acc042001-06-10 19:56:58 +0000452 pIdx = &pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000453 idx = *pIdx;
454 while( idx!=0 && idx<start ){
drh14acc042001-06-10 19:56:58 +0000455 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh2af926b2001-05-15 00:39:25 +0000456 if( idx + pFBlk->iSize == start ){
457 pFBlk->iSize += size;
458 if( idx + pFBlk->iSize == pFBlk->iNext ){
drh8c42ca92001-06-22 19:15:00 +0000459 pNext = (FreeBlk*)&pPage->u.aDisk[pFBlk->iNext];
drh2af926b2001-05-15 00:39:25 +0000460 pFBlk->iSize += pNext->iSize;
461 pFBlk->iNext = pNext->iNext;
462 }
463 pPage->nFree += size;
464 return;
465 }
466 pIdx = &pFBlk->iNext;
467 idx = *pIdx;
468 }
drh14acc042001-06-10 19:56:58 +0000469 pNew = (FreeBlk*)&pPage->u.aDisk[start];
drh2af926b2001-05-15 00:39:25 +0000470 if( idx != end ){
471 pNew->iSize = size;
472 pNew->iNext = idx;
473 }else{
drh14acc042001-06-10 19:56:58 +0000474 pNext = (FreeBlk*)&pPage->u.aDisk[idx];
drh2af926b2001-05-15 00:39:25 +0000475 pNew->iSize = size + pNext->iSize;
476 pNew->iNext = pNext->iNext;
477 }
478 *pIdx = start;
479 pPage->nFree += size;
drh7e3b0a02001-04-28 16:52:40 +0000480}
481
482/*
483** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000484**
drhbd03cae2001-06-02 02:40:57 +0000485** The pParent parameter must be a pointer to the MemPage which
486** is the parent of the page being initialized. The root of the
drh8b2f49b2001-06-08 00:21:52 +0000487** BTree (usually page 2) has no parent and so for that page,
488** pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000489**
drh72f82862001-05-24 21:06:34 +0000490** Return SQLITE_OK on success. If we see that the page does
491** not contained a well-formed database page, then return
492** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
493** guarantee that the page is well-formed. It only shows that
494** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000495*/
drh72f82862001-05-24 21:06:34 +0000496static int initPage(MemPage *pPage, Pgno pgnoThis, MemPage *pParent){
drh14acc042001-06-10 19:56:58 +0000497 int idx; /* An index into pPage->u.aDisk[] */
498 Cell *pCell; /* A pointer to a Cell in pPage->u.aDisk[] */
499 FreeBlk *pFBlk; /* A pointer to a free block in pPage->u.aDisk[] */
drh5e2f8b92001-05-28 00:41:15 +0000500 int sz; /* The size of a Cell in bytes */
501 int freeSpace; /* Amount of free space on the page */
drh2af926b2001-05-15 00:39:25 +0000502
drh5e2f8b92001-05-28 00:41:15 +0000503 if( pPage->pParent ){
504 assert( pPage->pParent==pParent );
505 return SQLITE_OK;
506 }
507 if( pParent ){
508 pPage->pParent = pParent;
509 sqlitepager_ref(pParent);
510 }
511 if( pPage->isInit ) return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +0000512 pPage->isInit = 1;
drh7e3b0a02001-04-28 16:52:40 +0000513 pPage->nCell = 0;
drh6019e162001-07-02 17:51:45 +0000514 freeSpace = USABLE_SPACE;
drh14acc042001-06-10 19:56:58 +0000515 idx = pPage->u.hdr.firstCell;
drh7e3b0a02001-04-28 16:52:40 +0000516 while( idx!=0 ){
drh8c42ca92001-06-22 19:15:00 +0000517 if( idx>SQLITE_PAGE_SIZE-MIN_CELL_SIZE ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000518 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh8c42ca92001-06-22 19:15:00 +0000519 if( idx!=ROUNDUP(idx) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000520 pCell = (Cell*)&pPage->u.aDisk[idx];
drh5e2f8b92001-05-28 00:41:15 +0000521 sz = cellSize(pCell);
522 if( idx+sz > SQLITE_PAGE_SIZE ) goto page_format_error;
523 freeSpace -= sz;
524 pPage->apCell[pPage->nCell++] = pCell;
drh3b7511c2001-05-26 13:15:44 +0000525 idx = pCell->h.iNext;
drh2af926b2001-05-15 00:39:25 +0000526 }
527 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +0000528 idx = pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000529 while( idx!=0 ){
530 if( idx>SQLITE_PAGE_SIZE-sizeof(FreeBlk) ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000531 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000532 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh2af926b2001-05-15 00:39:25 +0000533 pPage->nFree += pFBlk->iSize;
drh7c717f72001-06-24 20:39:41 +0000534 if( pFBlk->iNext>0 && pFBlk->iNext <= idx ) goto page_format_error;
drh2af926b2001-05-15 00:39:25 +0000535 idx = pFBlk->iNext;
drh7e3b0a02001-04-28 16:52:40 +0000536 }
drh8b2f49b2001-06-08 00:21:52 +0000537 if( pPage->nCell==0 && pPage->nFree==0 ){
538 /* As a special case, an uninitialized root page appears to be
539 ** an empty database */
540 return SQLITE_OK;
541 }
drh5e2f8b92001-05-28 00:41:15 +0000542 if( pPage->nFree!=freeSpace ) goto page_format_error;
drh7e3b0a02001-04-28 16:52:40 +0000543 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +0000544
545page_format_error:
546 return SQLITE_CORRUPT;
drh7e3b0a02001-04-28 16:52:40 +0000547}
548
549/*
drh8b2f49b2001-06-08 00:21:52 +0000550** Set up a raw page so that it looks like a database page holding
551** no entries.
drhbd03cae2001-06-02 02:40:57 +0000552*/
553static void zeroPage(MemPage *pPage){
554 PageHdr *pHdr;
555 FreeBlk *pFBlk;
drh6019e162001-07-02 17:51:45 +0000556 assert( sqlitepager_iswriteable(pPage) );
drhbd03cae2001-06-02 02:40:57 +0000557 memset(pPage, 0, SQLITE_PAGE_SIZE);
drh14acc042001-06-10 19:56:58 +0000558 pHdr = &pPage->u.hdr;
drhbd03cae2001-06-02 02:40:57 +0000559 pHdr->firstCell = 0;
560 pHdr->firstFree = sizeof(*pHdr);
561 pFBlk = (FreeBlk*)&pHdr[1];
562 pFBlk->iNext = 0;
563 pFBlk->iSize = SQLITE_PAGE_SIZE - sizeof(*pHdr);
drh8c42ca92001-06-22 19:15:00 +0000564 pPage->nFree = pFBlk->iSize;
565 pPage->nCell = 0;
566 pPage->isOverfull = 0;
drhbd03cae2001-06-02 02:40:57 +0000567}
568
569/*
drh72f82862001-05-24 21:06:34 +0000570** This routine is called when the reference count for a page
571** reaches zero. We need to unref the pParent pointer when that
572** happens.
573*/
574static void pageDestructor(void *pData){
575 MemPage *pPage = (MemPage*)pData;
576 if( pPage->pParent ){
577 MemPage *pParent = pPage->pParent;
578 pPage->pParent = 0;
579 sqlitepager_unref(pParent);
580 }
581}
582
583/*
drh306dc212001-05-21 13:45:10 +0000584** Open a new database.
585**
586** Actually, this routine just sets up the internal data structures
drh72f82862001-05-24 21:06:34 +0000587** for accessing the database. We do not open the database file
588** until the first page is loaded.
drh382c0242001-10-06 16:33:02 +0000589**
590** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +0000591** a new database with a random name is created. This randomly named
592** database file will be deleted when sqliteBtreeClose() is called.
drha059ad02001-04-17 20:09:11 +0000593*/
drh6019e162001-07-02 17:51:45 +0000594int sqliteBtreeOpen(
595 const char *zFilename, /* Name of the file containing the BTree database */
596 int mode, /* Not currently used */
597 int nCache, /* How many pages in the page cache */
598 Btree **ppBtree /* Pointer to new Btree object written here */
599){
drha059ad02001-04-17 20:09:11 +0000600 Btree *pBt;
drh8c42ca92001-06-22 19:15:00 +0000601 int rc;
drha059ad02001-04-17 20:09:11 +0000602
603 pBt = sqliteMalloc( sizeof(*pBt) );
604 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +0000605 *ppBtree = 0;
drha059ad02001-04-17 20:09:11 +0000606 return SQLITE_NOMEM;
607 }
drh6019e162001-07-02 17:51:45 +0000608 if( nCache<10 ) nCache = 10;
609 rc = sqlitepager_open(&pBt->pPager, zFilename, nCache, EXTRA_SIZE);
drha059ad02001-04-17 20:09:11 +0000610 if( rc!=SQLITE_OK ){
611 if( pBt->pPager ) sqlitepager_close(pBt->pPager);
612 sqliteFree(pBt);
613 *ppBtree = 0;
614 return rc;
615 }
drh72f82862001-05-24 21:06:34 +0000616 sqlitepager_set_destructor(pBt->pPager, pageDestructor);
drha059ad02001-04-17 20:09:11 +0000617 pBt->pCursor = 0;
618 pBt->page1 = 0;
drhecdc7532001-09-23 02:35:53 +0000619 sqliteHashInit(&pBt->locks, SQLITE_HASH_INT, 0);
drha059ad02001-04-17 20:09:11 +0000620 *ppBtree = pBt;
621 return SQLITE_OK;
622}
623
624/*
625** Close an open database and invalidate all cursors.
626*/
627int sqliteBtreeClose(Btree *pBt){
628 while( pBt->pCursor ){
629 sqliteBtreeCloseCursor(pBt->pCursor);
630 }
631 sqlitepager_close(pBt->pPager);
drhecdc7532001-09-23 02:35:53 +0000632 sqliteHashClear(&pBt->locks);
drha059ad02001-04-17 20:09:11 +0000633 sqliteFree(pBt);
634 return SQLITE_OK;
635}
636
637/*
drhf57b14a2001-09-14 18:54:08 +0000638** Change the number of pages in the cache.
639*/
640int sqliteBtreeSetCacheSize(Btree *pBt, int mxPage){
641 sqlitepager_set_cachesize(pBt->pPager, mxPage);
642 return SQLITE_OK;
643}
644
645/*
drh306dc212001-05-21 13:45:10 +0000646** Get a reference to page1 of the database file. This will
647** also acquire a readlock on that file.
648**
649** SQLITE_OK is returned on success. If the file is not a
650** well-formed database file, then SQLITE_CORRUPT is returned.
651** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
652** is returned if we run out of memory. SQLITE_PROTOCOL is returned
653** if there is a locking protocol violation.
654*/
655static int lockBtree(Btree *pBt){
656 int rc;
657 if( pBt->page1 ) return SQLITE_OK;
drh8c42ca92001-06-22 19:15:00 +0000658 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pBt->page1);
drh306dc212001-05-21 13:45:10 +0000659 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +0000660
661 /* Do some checking to help insure the file we opened really is
662 ** a valid database file.
663 */
664 if( sqlitepager_pagecount(pBt->pPager)>0 ){
drhbd03cae2001-06-02 02:40:57 +0000665 PageOne *pP1 = pBt->page1;
drh8c42ca92001-06-22 19:15:00 +0000666 if( strcmp(pP1->zMagic,zMagicHeader)!=0 || pP1->iMagic!=MAGIC ){
drh306dc212001-05-21 13:45:10 +0000667 rc = SQLITE_CORRUPT;
drh72f82862001-05-24 21:06:34 +0000668 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +0000669 }
670 }
671 return rc;
672
drh72f82862001-05-24 21:06:34 +0000673page1_init_failed:
drh306dc212001-05-21 13:45:10 +0000674 sqlitepager_unref(pBt->page1);
675 pBt->page1 = 0;
drh72f82862001-05-24 21:06:34 +0000676 return rc;
drh306dc212001-05-21 13:45:10 +0000677}
678
679/*
drh8c42ca92001-06-22 19:15:00 +0000680** Create a new database by initializing the first two pages of the
681** file.
drh8b2f49b2001-06-08 00:21:52 +0000682*/
683static int newDatabase(Btree *pBt){
684 MemPage *pRoot;
685 PageOne *pP1;
drh8c42ca92001-06-22 19:15:00 +0000686 int rc;
drh7c717f72001-06-24 20:39:41 +0000687 if( sqlitepager_pagecount(pBt->pPager)>1 ) return SQLITE_OK;
drh8b2f49b2001-06-08 00:21:52 +0000688 pP1 = pBt->page1;
689 rc = sqlitepager_write(pBt->page1);
690 if( rc ) return rc;
drh8c42ca92001-06-22 19:15:00 +0000691 rc = sqlitepager_get(pBt->pPager, 2, (void**)&pRoot);
drh8b2f49b2001-06-08 00:21:52 +0000692 if( rc ) return rc;
693 rc = sqlitepager_write(pRoot);
694 if( rc ){
695 sqlitepager_unref(pRoot);
696 return rc;
697 }
698 strcpy(pP1->zMagic, zMagicHeader);
drh8c42ca92001-06-22 19:15:00 +0000699 pP1->iMagic = MAGIC;
drh8b2f49b2001-06-08 00:21:52 +0000700 zeroPage(pRoot);
701 sqlitepager_unref(pRoot);
702 return SQLITE_OK;
703}
704
705/*
drh72f82862001-05-24 21:06:34 +0000706** Attempt to start a new transaction.
drh8b2f49b2001-06-08 00:21:52 +0000707**
708** A transaction must be started before attempting any changes
709** to the database. None of the following routines will work
710** unless a transaction is started first:
711**
712** sqliteBtreeCreateTable()
713** sqliteBtreeClearTable()
714** sqliteBtreeDropTable()
715** sqliteBtreeInsert()
716** sqliteBtreeDelete()
717** sqliteBtreeUpdateMeta()
drha059ad02001-04-17 20:09:11 +0000718*/
719int sqliteBtreeBeginTrans(Btree *pBt){
720 int rc;
721 if( pBt->inTrans ) return SQLITE_ERROR;
722 if( pBt->page1==0 ){
drh7e3b0a02001-04-28 16:52:40 +0000723 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +0000724 if( rc!=SQLITE_OK ){
725 return rc;
726 }
drha059ad02001-04-17 20:09:11 +0000727 }
drhbe0072d2001-09-13 14:46:09 +0000728 if( !sqlitepager_isreadonly(pBt->pPager) ){
drh5e00f6c2001-09-13 13:46:56 +0000729 rc = sqlitepager_write(pBt->page1);
730 if( rc!=SQLITE_OK ){
731 return rc;
732 }
733 rc = newDatabase(pBt);
drha059ad02001-04-17 20:09:11 +0000734 }
drh8c42ca92001-06-22 19:15:00 +0000735 pBt->inTrans = 1;
drh8c42ca92001-06-22 19:15:00 +0000736 return rc;
drha059ad02001-04-17 20:09:11 +0000737}
738
739/*
drh5e00f6c2001-09-13 13:46:56 +0000740** If there are no outstanding cursors and we are not in the middle
741** of a transaction but there is a read lock on the database, then
742** this routine unrefs the first page of the database file which
743** has the effect of releasing the read lock.
744**
745** If there are any outstanding cursors, this routine is a no-op.
746**
747** If there is a transaction in progress, this routine is a no-op.
drha059ad02001-04-17 20:09:11 +0000748*/
drh5e00f6c2001-09-13 13:46:56 +0000749static void unlockBtreeIfUnused(Btree *pBt){
drh7c717f72001-06-24 20:39:41 +0000750 if( pBt->inTrans==0 && pBt->pCursor==0 && pBt->page1!=0 ){
drha059ad02001-04-17 20:09:11 +0000751 sqlitepager_unref(pBt->page1);
752 pBt->page1 = 0;
753 pBt->inTrans = 0;
754 }
755}
756
757/*
drh2aa679f2001-06-25 02:11:07 +0000758** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +0000759**
760** This will release the write lock on the database file. If there
761** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000762*/
763int sqliteBtreeCommit(Btree *pBt){
764 int rc;
drh2aa679f2001-06-25 02:11:07 +0000765 if( pBt->inTrans==0 ) return SQLITE_ERROR;
drha059ad02001-04-17 20:09:11 +0000766 rc = sqlitepager_commit(pBt->pPager);
drh7c717f72001-06-24 20:39:41 +0000767 pBt->inTrans = 0;
drh5e00f6c2001-09-13 13:46:56 +0000768 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000769 return rc;
770}
771
772/*
drhecdc7532001-09-23 02:35:53 +0000773** Rollback the transaction in progress. All cursors will be
774** invalided by this operation. Any attempt to use a cursor
775** that was open at the beginning of this operation will result
776** in an error.
drh5e00f6c2001-09-13 13:46:56 +0000777**
778** This will release the write lock on the database file. If there
779** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000780*/
781int sqliteBtreeRollback(Btree *pBt){
782 int rc;
drhecdc7532001-09-23 02:35:53 +0000783 BtCursor *pCur;
drh7c717f72001-06-24 20:39:41 +0000784 if( pBt->inTrans==0 ) return SQLITE_OK;
785 pBt->inTrans = 0;
drhecdc7532001-09-23 02:35:53 +0000786 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
787 if( pCur->pPage ){
788 sqlitepager_unref(pCur->pPage);
789 pCur->pPage = 0;
790 }
791 }
drha059ad02001-04-17 20:09:11 +0000792 rc = sqlitepager_rollback(pBt->pPager);
drh5e00f6c2001-09-13 13:46:56 +0000793 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000794 return rc;
795}
796
797/*
drh8b2f49b2001-06-08 00:21:52 +0000798** Create a new cursor for the BTree whose root is on the page
799** iTable. The act of acquiring a cursor gets a read lock on
800** the database file.
drh1bee3d72001-10-15 00:44:35 +0000801**
802** If wrFlag==0, then the cursor can only be used for reading.
803** If wrFlag==1, then the cursor can be used for reading or writing.
804** A read/write cursor requires exclusive access to its table. There
805** cannot be two or more cursors open on the same table is any one of
806** cursors is a read/write cursor. But there can be two or more
807** read-only cursors open on the same table.
drha059ad02001-04-17 20:09:11 +0000808*/
drhecdc7532001-09-23 02:35:53 +0000809int sqliteBtreeCursor(Btree *pBt, int iTable, int wrFlag, BtCursor **ppCur){
drha059ad02001-04-17 20:09:11 +0000810 int rc;
811 BtCursor *pCur;
drh5a2c2c22001-11-21 02:21:11 +0000812 ptr nLock;
drhecdc7532001-09-23 02:35:53 +0000813
drha059ad02001-04-17 20:09:11 +0000814 if( pBt->page1==0 ){
815 rc = lockBtree(pBt);
816 if( rc!=SQLITE_OK ){
817 *ppCur = 0;
818 return rc;
819 }
820 }
821 pCur = sqliteMalloc( sizeof(*pCur) );
822 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +0000823 rc = SQLITE_NOMEM;
824 goto create_cursor_exception;
825 }
drh8b2f49b2001-06-08 00:21:52 +0000826 pCur->pgnoRoot = (Pgno)iTable;
drh8c42ca92001-06-22 19:15:00 +0000827 rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +0000828 if( rc!=SQLITE_OK ){
829 goto create_cursor_exception;
830 }
drh8b2f49b2001-06-08 00:21:52 +0000831 rc = initPage(pCur->pPage, pCur->pgnoRoot, 0);
drhbd03cae2001-06-02 02:40:57 +0000832 if( rc!=SQLITE_OK ){
833 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +0000834 }
drh5a2c2c22001-11-21 02:21:11 +0000835 nLock = (ptr)sqliteHashFind(&pBt->locks, 0, iTable);
drhecdc7532001-09-23 02:35:53 +0000836 if( nLock<0 || (nLock>0 && wrFlag) ){
837 rc = SQLITE_LOCKED;
838 goto create_cursor_exception;
839 }
840 nLock = wrFlag ? -1 : nLock+1;
841 sqliteHashInsert(&pBt->locks, 0, iTable, (void*)nLock);
drh14acc042001-06-10 19:56:58 +0000842 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +0000843 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +0000844 pCur->idx = 0;
drha059ad02001-04-17 20:09:11 +0000845 pCur->pNext = pBt->pCursor;
846 if( pCur->pNext ){
847 pCur->pNext->pPrev = pCur;
848 }
drh14acc042001-06-10 19:56:58 +0000849 pCur->pPrev = 0;
drha059ad02001-04-17 20:09:11 +0000850 pBt->pCursor = pCur;
drh2af926b2001-05-15 00:39:25 +0000851 *ppCur = pCur;
852 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +0000853
854create_cursor_exception:
855 *ppCur = 0;
856 if( pCur ){
857 if( pCur->pPage ) sqlitepager_unref(pCur->pPage);
858 sqliteFree(pCur);
859 }
drh5e00f6c2001-09-13 13:46:56 +0000860 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +0000861 return rc;
drha059ad02001-04-17 20:09:11 +0000862}
863
864/*
drh5e00f6c2001-09-13 13:46:56 +0000865** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +0000866** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +0000867*/
868int sqliteBtreeCloseCursor(BtCursor *pCur){
drh5a2c2c22001-11-21 02:21:11 +0000869 ptr nLock;
drha059ad02001-04-17 20:09:11 +0000870 Btree *pBt = pCur->pBt;
drha059ad02001-04-17 20:09:11 +0000871 if( pCur->pPrev ){
872 pCur->pPrev->pNext = pCur->pNext;
873 }else{
874 pBt->pCursor = pCur->pNext;
875 }
876 if( pCur->pNext ){
877 pCur->pNext->pPrev = pCur->pPrev;
878 }
drhecdc7532001-09-23 02:35:53 +0000879 if( pCur->pPage ){
880 sqlitepager_unref(pCur->pPage);
881 }
drh5e00f6c2001-09-13 13:46:56 +0000882 unlockBtreeIfUnused(pBt);
drh5a2c2c22001-11-21 02:21:11 +0000883 nLock = (ptr)sqliteHashFind(&pBt->locks, 0, pCur->pgnoRoot);
drh6d4abfb2001-10-22 02:58:08 +0000884 assert( nLock!=0 || sqlite_malloc_failed );
drhecdc7532001-09-23 02:35:53 +0000885 nLock = nLock<0 ? 0 : nLock-1;
886 sqliteHashInsert(&pBt->locks, 0, pCur->pgnoRoot, (void*)nLock);
drha059ad02001-04-17 20:09:11 +0000887 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +0000888 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +0000889}
890
drh7e3b0a02001-04-28 16:52:40 +0000891/*
drh5e2f8b92001-05-28 00:41:15 +0000892** Make a temporary cursor by filling in the fields of pTempCur.
893** The temporary cursor is not on the cursor list for the Btree.
894*/
drh14acc042001-06-10 19:56:58 +0000895static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +0000896 memcpy(pTempCur, pCur, sizeof(*pCur));
897 pTempCur->pNext = 0;
898 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +0000899 if( pTempCur->pPage ){
900 sqlitepager_ref(pTempCur->pPage);
901 }
drh5e2f8b92001-05-28 00:41:15 +0000902}
903
904/*
drhbd03cae2001-06-02 02:40:57 +0000905** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +0000906** function above.
907*/
drh14acc042001-06-10 19:56:58 +0000908static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +0000909 if( pCur->pPage ){
910 sqlitepager_unref(pCur->pPage);
911 }
drh5e2f8b92001-05-28 00:41:15 +0000912}
913
914/*
drhbd03cae2001-06-02 02:40:57 +0000915** Set *pSize to the number of bytes of key in the entry the
916** cursor currently points to. Always return SQLITE_OK.
917** Failure is not possible. If the cursor is not currently
918** pointing to an entry (which can happen, for example, if
919** the database is empty) then *pSize is set to 0.
drh7e3b0a02001-04-28 16:52:40 +0000920*/
drh72f82862001-05-24 21:06:34 +0000921int sqliteBtreeKeySize(BtCursor *pCur, int *pSize){
drh2af926b2001-05-15 00:39:25 +0000922 Cell *pCell;
923 MemPage *pPage;
924
925 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +0000926 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh72f82862001-05-24 21:06:34 +0000927 *pSize = 0;
928 }else{
drh5e2f8b92001-05-28 00:41:15 +0000929 pCell = pPage->apCell[pCur->idx];
drh80ff32f2001-11-04 18:32:46 +0000930 *pSize = NKEY(pCell->h);
drh72f82862001-05-24 21:06:34 +0000931 }
932 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +0000933}
drh2af926b2001-05-15 00:39:25 +0000934
drh72f82862001-05-24 21:06:34 +0000935/*
936** Read payload information from the entry that the pCur cursor is
937** pointing to. Begin reading the payload at "offset" and read
938** a total of "amt" bytes. Put the result in zBuf.
939**
940** This routine does not make a distinction between key and data.
941** It just reads bytes from the payload area.
942*/
drh2af926b2001-05-15 00:39:25 +0000943static int getPayload(BtCursor *pCur, int offset, int amt, char *zBuf){
drh5e2f8b92001-05-28 00:41:15 +0000944 char *aPayload;
drh2af926b2001-05-15 00:39:25 +0000945 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +0000946 int rc;
drh72f82862001-05-24 21:06:34 +0000947 assert( pCur!=0 && pCur->pPage!=0 );
drh8c42ca92001-06-22 19:15:00 +0000948 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
949 aPayload = pCur->pPage->apCell[pCur->idx]->aPayload;
drh2af926b2001-05-15 00:39:25 +0000950 if( offset<MX_LOCAL_PAYLOAD ){
951 int a = amt;
952 if( a+offset>MX_LOCAL_PAYLOAD ){
953 a = MX_LOCAL_PAYLOAD - offset;
954 }
drh5e2f8b92001-05-28 00:41:15 +0000955 memcpy(zBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +0000956 if( a==amt ){
957 return SQLITE_OK;
958 }
drh2aa679f2001-06-25 02:11:07 +0000959 offset = 0;
drh2af926b2001-05-15 00:39:25 +0000960 zBuf += a;
961 amt -= a;
drhdd793422001-06-28 01:54:48 +0000962 }else{
963 offset -= MX_LOCAL_PAYLOAD;
drhbd03cae2001-06-02 02:40:57 +0000964 }
965 if( amt>0 ){
drh8c42ca92001-06-22 19:15:00 +0000966 nextPage = pCur->pPage->apCell[pCur->idx]->ovfl;
drh2af926b2001-05-15 00:39:25 +0000967 }
968 while( amt>0 && nextPage ){
969 OverflowPage *pOvfl;
drh8c42ca92001-06-22 19:15:00 +0000970 rc = sqlitepager_get(pCur->pBt->pPager, nextPage, (void**)&pOvfl);
drh2af926b2001-05-15 00:39:25 +0000971 if( rc!=0 ){
972 return rc;
973 }
drh14acc042001-06-10 19:56:58 +0000974 nextPage = pOvfl->iNext;
drh2af926b2001-05-15 00:39:25 +0000975 if( offset<OVERFLOW_SIZE ){
976 int a = amt;
977 if( a + offset > OVERFLOW_SIZE ){
978 a = OVERFLOW_SIZE - offset;
979 }
drh5e2f8b92001-05-28 00:41:15 +0000980 memcpy(zBuf, &pOvfl->aPayload[offset], a);
drh2aa679f2001-06-25 02:11:07 +0000981 offset = 0;
drh2af926b2001-05-15 00:39:25 +0000982 amt -= a;
983 zBuf += a;
drh2aa679f2001-06-25 02:11:07 +0000984 }else{
985 offset -= OVERFLOW_SIZE;
drh2af926b2001-05-15 00:39:25 +0000986 }
987 sqlitepager_unref(pOvfl);
988 }
989 return amt==0 ? SQLITE_OK : SQLITE_CORRUPT;
990}
991
drh72f82862001-05-24 21:06:34 +0000992/*
drh5e00f6c2001-09-13 13:46:56 +0000993** Read part of the key associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +0000994** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +0000995** begins at "offset". The number of bytes actually read is
996** returned. The amount returned will be smaller than the
997** amount requested if there are not enough bytes in the key
998** to satisfy the request.
drh72f82862001-05-24 21:06:34 +0000999*/
1000int sqliteBtreeKey(BtCursor *pCur, int offset, int amt, char *zBuf){
1001 Cell *pCell;
1002 MemPage *pPage;
drha059ad02001-04-17 20:09:11 +00001003
drh5e00f6c2001-09-13 13:46:56 +00001004 if( amt<0 ) return 0;
1005 if( offset<0 ) return 0;
1006 if( amt==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001007 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001008 if( pPage==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001009 if( pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +00001010 return 0;
drh72f82862001-05-24 21:06:34 +00001011 }
drh5e2f8b92001-05-28 00:41:15 +00001012 pCell = pPage->apCell[pCur->idx];
drh80ff32f2001-11-04 18:32:46 +00001013 if( amt+offset > NKEY(pCell->h) ){
1014 amt = NKEY(pCell->h) - offset;
drh5e00f6c2001-09-13 13:46:56 +00001015 if( amt<=0 ){
1016 return 0;
1017 }
drhbd03cae2001-06-02 02:40:57 +00001018 }
drh5e00f6c2001-09-13 13:46:56 +00001019 getPayload(pCur, offset, amt, zBuf);
1020 return amt;
drh72f82862001-05-24 21:06:34 +00001021}
1022
1023/*
drhbd03cae2001-06-02 02:40:57 +00001024** Set *pSize to the number of bytes of data in the entry the
1025** cursor currently points to. Always return SQLITE_OK.
1026** Failure is not possible. If the cursor is not currently
1027** pointing to an entry (which can happen, for example, if
1028** the database is empty) then *pSize is set to 0.
drh72f82862001-05-24 21:06:34 +00001029*/
1030int sqliteBtreeDataSize(BtCursor *pCur, int *pSize){
1031 Cell *pCell;
1032 MemPage *pPage;
1033
1034 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001035 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh72f82862001-05-24 21:06:34 +00001036 *pSize = 0;
1037 }else{
drh5e2f8b92001-05-28 00:41:15 +00001038 pCell = pPage->apCell[pCur->idx];
drh80ff32f2001-11-04 18:32:46 +00001039 *pSize = NDATA(pCell->h);
drh72f82862001-05-24 21:06:34 +00001040 }
1041 return SQLITE_OK;
1042}
1043
1044/*
drh5e00f6c2001-09-13 13:46:56 +00001045** Read part of the data associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +00001046** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +00001047** begins at "offset". The number of bytes actually read is
1048** returned. The amount returned will be smaller than the
1049** amount requested if there are not enough bytes in the data
1050** to satisfy the request.
drh72f82862001-05-24 21:06:34 +00001051*/
1052int sqliteBtreeData(BtCursor *pCur, int offset, int amt, char *zBuf){
1053 Cell *pCell;
1054 MemPage *pPage;
1055
drh5e00f6c2001-09-13 13:46:56 +00001056 if( amt<0 ) return 0;
1057 if( offset<0 ) return 0;
1058 if( amt==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001059 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001060 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +00001061 return 0;
drh72f82862001-05-24 21:06:34 +00001062 }
drh5e2f8b92001-05-28 00:41:15 +00001063 pCell = pPage->apCell[pCur->idx];
drh80ff32f2001-11-04 18:32:46 +00001064 if( amt+offset > NDATA(pCell->h) ){
1065 amt = NDATA(pCell->h) - offset;
drh5e00f6c2001-09-13 13:46:56 +00001066 if( amt<=0 ){
1067 return 0;
1068 }
drhbd03cae2001-06-02 02:40:57 +00001069 }
drh80ff32f2001-11-04 18:32:46 +00001070 getPayload(pCur, offset + NKEY(pCell->h), amt, zBuf);
drh5e00f6c2001-09-13 13:46:56 +00001071 return amt;
drh72f82862001-05-24 21:06:34 +00001072}
drha059ad02001-04-17 20:09:11 +00001073
drh2af926b2001-05-15 00:39:25 +00001074/*
drh8721ce42001-11-07 14:22:00 +00001075** Compare an external key against the key on the entry that pCur points to.
1076**
1077** The external key is pKey and is nKey bytes long. The last nIgnore bytes
1078** of the key associated with pCur are ignored, as if they do not exist.
1079** (The normal case is for nIgnore to be zero in which case the entire
1080** internal key is used in the comparison.)
1081**
1082** The comparison result is written to *pRes as follows:
drh2af926b2001-05-15 00:39:25 +00001083**
drh717e6402001-09-27 03:22:32 +00001084** *pRes<0 This means pCur<pKey
1085**
1086** *pRes==0 This means pCur==pKey for all nKey bytes
1087**
1088** *pRes>0 This means pCur>pKey
1089**
drh8721ce42001-11-07 14:22:00 +00001090** When one key is an exact prefix of the other, the shorter key is
1091** considered less than the longer one. In order to be equal the
1092** keys must be exactly the same length. (The length of the pCur key
1093** is the actual key length minus nIgnore bytes.)
drh2af926b2001-05-15 00:39:25 +00001094*/
drh717e6402001-09-27 03:22:32 +00001095int sqliteBtreeKeyCompare(
drh8721ce42001-11-07 14:22:00 +00001096 BtCursor *pCur, /* Pointer to entry to compare against */
1097 const void *pKey, /* Key to compare against entry that pCur points to */
1098 int nKey, /* Number of bytes in pKey */
1099 int nIgnore, /* Ignore this many bytes at the end of pCur */
1100 int *pResult /* Write the result here */
drh5c4d9702001-08-20 00:33:58 +00001101){
drh2af926b2001-05-15 00:39:25 +00001102 Pgno nextPage;
drh8721ce42001-11-07 14:22:00 +00001103 int n, c, rc, nLocal;
drh2af926b2001-05-15 00:39:25 +00001104 Cell *pCell;
drh717e6402001-09-27 03:22:32 +00001105 const char *zKey = (const char*)pKey;
drh2af926b2001-05-15 00:39:25 +00001106
1107 assert( pCur->pPage );
1108 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drhbd03cae2001-06-02 02:40:57 +00001109 pCell = pCur->pPage->apCell[pCur->idx];
drh8721ce42001-11-07 14:22:00 +00001110 nLocal = NKEY(pCell->h) - nIgnore;
1111 if( nLocal<0 ) nLocal = 0;
1112 n = nKey<nLocal ? nKey : nLocal;
drh2af926b2001-05-15 00:39:25 +00001113 if( n>MX_LOCAL_PAYLOAD ){
1114 n = MX_LOCAL_PAYLOAD;
1115 }
drh717e6402001-09-27 03:22:32 +00001116 c = memcmp(pCell->aPayload, zKey, n);
drh2af926b2001-05-15 00:39:25 +00001117 if( c!=0 ){
1118 *pResult = c;
1119 return SQLITE_OK;
1120 }
drh717e6402001-09-27 03:22:32 +00001121 zKey += n;
drh2af926b2001-05-15 00:39:25 +00001122 nKey -= n;
drh8721ce42001-11-07 14:22:00 +00001123 nLocal -= n;
drh3b7511c2001-05-26 13:15:44 +00001124 nextPage = pCell->ovfl;
drh8721ce42001-11-07 14:22:00 +00001125 while( nKey>0 && nLocal>0 ){
drh2af926b2001-05-15 00:39:25 +00001126 OverflowPage *pOvfl;
1127 if( nextPage==0 ){
1128 return SQLITE_CORRUPT;
1129 }
drh8c42ca92001-06-22 19:15:00 +00001130 rc = sqlitepager_get(pCur->pBt->pPager, nextPage, (void**)&pOvfl);
drh72f82862001-05-24 21:06:34 +00001131 if( rc ){
drh2af926b2001-05-15 00:39:25 +00001132 return rc;
1133 }
drh14acc042001-06-10 19:56:58 +00001134 nextPage = pOvfl->iNext;
drh8721ce42001-11-07 14:22:00 +00001135 n = nKey<nLocal ? nKey : nLocal;
drh2af926b2001-05-15 00:39:25 +00001136 if( n>OVERFLOW_SIZE ){
1137 n = OVERFLOW_SIZE;
1138 }
drh717e6402001-09-27 03:22:32 +00001139 c = memcmp(pOvfl->aPayload, zKey, n);
drh2af926b2001-05-15 00:39:25 +00001140 sqlitepager_unref(pOvfl);
1141 if( c!=0 ){
1142 *pResult = c;
1143 return SQLITE_OK;
1144 }
1145 nKey -= n;
drh8721ce42001-11-07 14:22:00 +00001146 nLocal -= n;
drh717e6402001-09-27 03:22:32 +00001147 zKey += n;
drh2af926b2001-05-15 00:39:25 +00001148 }
drh717e6402001-09-27 03:22:32 +00001149 if( c==0 ){
drh8721ce42001-11-07 14:22:00 +00001150 c = nLocal - nKey;
drh717e6402001-09-27 03:22:32 +00001151 }
drh2af926b2001-05-15 00:39:25 +00001152 *pResult = c;
1153 return SQLITE_OK;
1154}
1155
drh72f82862001-05-24 21:06:34 +00001156/*
1157** Move the cursor down to a new child page.
1158*/
drh5e2f8b92001-05-28 00:41:15 +00001159static int moveToChild(BtCursor *pCur, int newPgno){
drh72f82862001-05-24 21:06:34 +00001160 int rc;
1161 MemPage *pNewPage;
1162
drh8c42ca92001-06-22 19:15:00 +00001163 rc = sqlitepager_get(pCur->pBt->pPager, newPgno, (void**)&pNewPage);
drh6019e162001-07-02 17:51:45 +00001164 if( rc ) return rc;
1165 rc = initPage(pNewPage, newPgno, pCur->pPage);
1166 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001167 sqlitepager_unref(pCur->pPage);
1168 pCur->pPage = pNewPage;
1169 pCur->idx = 0;
1170 return SQLITE_OK;
1171}
1172
1173/*
drh5e2f8b92001-05-28 00:41:15 +00001174** Move the cursor up to the parent page.
1175**
1176** pCur->idx is set to the cell index that contains the pointer
1177** to the page we are coming from. If we are coming from the
1178** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00001179** the largest cell index.
drh72f82862001-05-24 21:06:34 +00001180*/
drh5e2f8b92001-05-28 00:41:15 +00001181static int moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001182 Pgno oldPgno;
1183 MemPage *pParent;
drh8c42ca92001-06-22 19:15:00 +00001184 int i;
drh72f82862001-05-24 21:06:34 +00001185 pParent = pCur->pPage->pParent;
drhbd03cae2001-06-02 02:40:57 +00001186 if( pParent==0 ) return SQLITE_INTERNAL;
drh72f82862001-05-24 21:06:34 +00001187 oldPgno = sqlitepager_pagenumber(pCur->pPage);
drh72f82862001-05-24 21:06:34 +00001188 sqlitepager_ref(pParent);
1189 sqlitepager_unref(pCur->pPage);
1190 pCur->pPage = pParent;
drh8c42ca92001-06-22 19:15:00 +00001191 pCur->idx = pParent->nCell;
1192 for(i=0; i<pParent->nCell; i++){
1193 if( pParent->apCell[i]->h.leftChild==oldPgno ){
drh72f82862001-05-24 21:06:34 +00001194 pCur->idx = i;
1195 break;
1196 }
1197 }
drh5e2f8b92001-05-28 00:41:15 +00001198 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00001199}
1200
1201/*
1202** Move the cursor to the root page
1203*/
drh5e2f8b92001-05-28 00:41:15 +00001204static int moveToRoot(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001205 MemPage *pNew;
drhbd03cae2001-06-02 02:40:57 +00001206 int rc;
1207
drh8c42ca92001-06-22 19:15:00 +00001208 rc = sqlitepager_get(pCur->pBt->pPager, pCur->pgnoRoot, (void**)&pNew);
drhbd03cae2001-06-02 02:40:57 +00001209 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00001210 rc = initPage(pNew, pCur->pgnoRoot, 0);
1211 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001212 sqlitepager_unref(pCur->pPage);
1213 pCur->pPage = pNew;
1214 pCur->idx = 0;
1215 return SQLITE_OK;
1216}
drh2af926b2001-05-15 00:39:25 +00001217
drh5e2f8b92001-05-28 00:41:15 +00001218/*
1219** Move the cursor down to the left-most leaf entry beneath the
1220** entry to which it is currently pointing.
1221*/
1222static int moveToLeftmost(BtCursor *pCur){
1223 Pgno pgno;
1224 int rc;
1225
1226 while( (pgno = pCur->pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
1227 rc = moveToChild(pCur, pgno);
1228 if( rc ) return rc;
1229 }
1230 return SQLITE_OK;
1231}
1232
drh5e00f6c2001-09-13 13:46:56 +00001233/* Move the cursor to the first entry in the table. Return SQLITE_OK
1234** on success. Set *pRes to 0 if the cursor actually points to something
1235** or set *pRes to 1 if the table is empty and there is no first element.
1236*/
1237int sqliteBtreeFirst(BtCursor *pCur, int *pRes){
1238 int rc;
drhecdc7532001-09-23 02:35:53 +00001239 if( pCur->pPage==0 ) return SQLITE_ABORT;
drh5e00f6c2001-09-13 13:46:56 +00001240 rc = moveToRoot(pCur);
1241 if( rc ) return rc;
1242 if( pCur->pPage->nCell==0 ){
1243 *pRes = 1;
1244 return SQLITE_OK;
1245 }
1246 *pRes = 0;
1247 rc = moveToLeftmost(pCur);
1248 return rc;
1249}
drh5e2f8b92001-05-28 00:41:15 +00001250
drha059ad02001-04-17 20:09:11 +00001251/* Move the cursor so that it points to an entry near pKey.
drh72f82862001-05-24 21:06:34 +00001252** Return a success code.
1253**
drh5e2f8b92001-05-28 00:41:15 +00001254** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00001255** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00001256** were present. The cursor might point to an entry that comes
1257** before or after the key.
1258**
drhbd03cae2001-06-02 02:40:57 +00001259** The result of comparing the key with the entry to which the
1260** cursor is left pointing is stored in pCur->iMatch. The same
1261** value is also written to *pRes if pRes!=NULL. The meaning of
1262** this value is as follows:
1263**
1264** *pRes<0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001265** is smaller than pKey.
drhbd03cae2001-06-02 02:40:57 +00001266**
1267** *pRes==0 The cursor is left pointing at an entry that
1268** exactly matches pKey.
1269**
1270** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001271** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00001272*/
drh5c4d9702001-08-20 00:33:58 +00001273int sqliteBtreeMoveto(BtCursor *pCur, const void *pKey, int nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00001274 int rc;
drhecdc7532001-09-23 02:35:53 +00001275 if( pCur->pPage==0 ) return SQLITE_ABORT;
drh7c717f72001-06-24 20:39:41 +00001276 pCur->bSkipNext = 0;
drh5e2f8b92001-05-28 00:41:15 +00001277 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00001278 if( rc ) return rc;
1279 for(;;){
1280 int lwr, upr;
1281 Pgno chldPg;
1282 MemPage *pPage = pCur->pPage;
drh8b2f49b2001-06-08 00:21:52 +00001283 int c = -1;
drh72f82862001-05-24 21:06:34 +00001284 lwr = 0;
1285 upr = pPage->nCell-1;
1286 while( lwr<=upr ){
drh72f82862001-05-24 21:06:34 +00001287 pCur->idx = (lwr+upr)/2;
drh8721ce42001-11-07 14:22:00 +00001288 rc = sqliteBtreeKeyCompare(pCur, pKey, nKey, 0, &c);
drh72f82862001-05-24 21:06:34 +00001289 if( rc ) return rc;
1290 if( c==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001291 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001292 if( pRes ) *pRes = 0;
1293 return SQLITE_OK;
1294 }
1295 if( c<0 ){
1296 lwr = pCur->idx+1;
1297 }else{
1298 upr = pCur->idx-1;
1299 }
1300 }
1301 assert( lwr==upr+1 );
1302 if( lwr>=pPage->nCell ){
drh14acc042001-06-10 19:56:58 +00001303 chldPg = pPage->u.hdr.rightChild;
drh72f82862001-05-24 21:06:34 +00001304 }else{
drh5e2f8b92001-05-28 00:41:15 +00001305 chldPg = pPage->apCell[lwr]->h.leftChild;
drh72f82862001-05-24 21:06:34 +00001306 }
1307 if( chldPg==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001308 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001309 if( pRes ) *pRes = c;
1310 return SQLITE_OK;
1311 }
drh5e2f8b92001-05-28 00:41:15 +00001312 rc = moveToChild(pCur, chldPg);
drh72f82862001-05-24 21:06:34 +00001313 if( rc ) return rc;
1314 }
drhbd03cae2001-06-02 02:40:57 +00001315 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00001316}
1317
1318/*
drhbd03cae2001-06-02 02:40:57 +00001319** Advance the cursor to the next entry in the database. If
1320** successful and pRes!=NULL then set *pRes=0. If the cursor
1321** was already pointing to the last entry in the database before
1322** this routine was called, then set *pRes=1 if pRes!=NULL.
drh72f82862001-05-24 21:06:34 +00001323*/
1324int sqliteBtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00001325 int rc;
drhecdc7532001-09-23 02:35:53 +00001326 if( pCur->pPage==0 ){
drh1bee3d72001-10-15 00:44:35 +00001327 if( pRes ) *pRes = 1;
drhecdc7532001-09-23 02:35:53 +00001328 return SQLITE_ABORT;
1329 }
drh5e2f8b92001-05-28 00:41:15 +00001330 if( pCur->bSkipNext ){
1331 pCur->bSkipNext = 0;
drh72f82862001-05-24 21:06:34 +00001332 if( pRes ) *pRes = 0;
1333 return SQLITE_OK;
1334 }
drh72f82862001-05-24 21:06:34 +00001335 pCur->idx++;
drh5e2f8b92001-05-28 00:41:15 +00001336 if( pCur->idx>=pCur->pPage->nCell ){
drh8c42ca92001-06-22 19:15:00 +00001337 if( pCur->pPage->u.hdr.rightChild ){
1338 rc = moveToChild(pCur, pCur->pPage->u.hdr.rightChild);
drh5e2f8b92001-05-28 00:41:15 +00001339 if( rc ) return rc;
1340 rc = moveToLeftmost(pCur);
1341 if( rc ) return rc;
1342 if( pRes ) *pRes = 0;
drh72f82862001-05-24 21:06:34 +00001343 return SQLITE_OK;
1344 }
drh5e2f8b92001-05-28 00:41:15 +00001345 do{
drh8c42ca92001-06-22 19:15:00 +00001346 if( pCur->pPage->pParent==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001347 if( pRes ) *pRes = 1;
1348 return SQLITE_OK;
1349 }
1350 rc = moveToParent(pCur);
1351 if( rc ) return rc;
1352 }while( pCur->idx>=pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00001353 if( pRes ) *pRes = 0;
1354 return SQLITE_OK;
1355 }
drh5e2f8b92001-05-28 00:41:15 +00001356 rc = moveToLeftmost(pCur);
1357 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001358 if( pRes ) *pRes = 0;
1359 return SQLITE_OK;
1360}
1361
drh3b7511c2001-05-26 13:15:44 +00001362/*
1363** Allocate a new page from the database file.
1364**
1365** The new page is marked as dirty. (In other words, sqlitepager_write()
1366** has already been called on the new page.) The new page has also
1367** been referenced and the calling routine is responsible for calling
1368** sqlitepager_unref() on the new page when it is done.
1369**
1370** SQLITE_OK is returned on success. Any other return value indicates
1371** an error. *ppPage and *pPgno are undefined in the event of an error.
1372** Do not invoke sqlitepager_unref() on *ppPage if an error is returned.
1373*/
1374static int allocatePage(Btree *pBt, MemPage **ppPage, Pgno *pPgno){
drhbd03cae2001-06-02 02:40:57 +00001375 PageOne *pPage1 = pBt->page1;
drh8c42ca92001-06-22 19:15:00 +00001376 int rc;
drh3b7511c2001-05-26 13:15:44 +00001377 if( pPage1->freeList ){
1378 OverflowPage *pOvfl;
1379 rc = sqlitepager_write(pPage1);
1380 if( rc ) return rc;
1381 *pPgno = pPage1->freeList;
drh8c42ca92001-06-22 19:15:00 +00001382 rc = sqlitepager_get(pBt->pPager, pPage1->freeList, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001383 if( rc ) return rc;
1384 rc = sqlitepager_write(pOvfl);
1385 if( rc ){
1386 sqlitepager_unref(pOvfl);
1387 return rc;
1388 }
drh14acc042001-06-10 19:56:58 +00001389 pPage1->freeList = pOvfl->iNext;
drh2aa679f2001-06-25 02:11:07 +00001390 pPage1->nFree--;
drh3b7511c2001-05-26 13:15:44 +00001391 *ppPage = (MemPage*)pOvfl;
1392 }else{
drh2aa679f2001-06-25 02:11:07 +00001393 *pPgno = sqlitepager_pagecount(pBt->pPager) + 1;
drh8c42ca92001-06-22 19:15:00 +00001394 rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
drh3b7511c2001-05-26 13:15:44 +00001395 if( rc ) return rc;
1396 rc = sqlitepager_write(*ppPage);
1397 }
1398 return rc;
1399}
1400
1401/*
1402** Add a page of the database file to the freelist. Either pgno or
1403** pPage but not both may be 0.
drh5e2f8b92001-05-28 00:41:15 +00001404**
drhdd793422001-06-28 01:54:48 +00001405** sqlitepager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00001406*/
1407static int freePage(Btree *pBt, void *pPage, Pgno pgno){
drhbd03cae2001-06-02 02:40:57 +00001408 PageOne *pPage1 = pBt->page1;
drh3b7511c2001-05-26 13:15:44 +00001409 OverflowPage *pOvfl = (OverflowPage*)pPage;
1410 int rc;
drhdd793422001-06-28 01:54:48 +00001411 int needUnref = 0;
1412 MemPage *pMemPage;
drh8b2f49b2001-06-08 00:21:52 +00001413
drh3b7511c2001-05-26 13:15:44 +00001414 if( pgno==0 ){
1415 assert( pOvfl!=0 );
1416 pgno = sqlitepager_pagenumber(pOvfl);
1417 }
drh2aa679f2001-06-25 02:11:07 +00001418 assert( pgno>2 );
drh3b7511c2001-05-26 13:15:44 +00001419 rc = sqlitepager_write(pPage1);
1420 if( rc ){
1421 return rc;
1422 }
1423 if( pOvfl==0 ){
1424 assert( pgno>0 );
drh8c42ca92001-06-22 19:15:00 +00001425 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001426 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001427 needUnref = 1;
drh3b7511c2001-05-26 13:15:44 +00001428 }
1429 rc = sqlitepager_write(pOvfl);
1430 if( rc ){
drhdd793422001-06-28 01:54:48 +00001431 if( needUnref ) sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001432 return rc;
1433 }
drh14acc042001-06-10 19:56:58 +00001434 pOvfl->iNext = pPage1->freeList;
drh3b7511c2001-05-26 13:15:44 +00001435 pPage1->freeList = pgno;
drh2aa679f2001-06-25 02:11:07 +00001436 pPage1->nFree++;
drh5e2f8b92001-05-28 00:41:15 +00001437 memset(pOvfl->aPayload, 0, OVERFLOW_SIZE);
drhdd793422001-06-28 01:54:48 +00001438 pMemPage = (MemPage*)pPage;
1439 pMemPage->isInit = 0;
1440 if( pMemPage->pParent ){
1441 sqlitepager_unref(pMemPage->pParent);
1442 pMemPage->pParent = 0;
1443 }
1444 if( needUnref ) rc = sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001445 return rc;
1446}
1447
1448/*
1449** Erase all the data out of a cell. This involves returning overflow
1450** pages back the freelist.
1451*/
1452static int clearCell(Btree *pBt, Cell *pCell){
1453 Pager *pPager = pBt->pPager;
1454 OverflowPage *pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001455 Pgno ovfl, nextOvfl;
1456 int rc;
1457
drh80ff32f2001-11-04 18:32:46 +00001458 if( NKEY(pCell->h) + NDATA(pCell->h) <= MX_LOCAL_PAYLOAD ){
drh5e2f8b92001-05-28 00:41:15 +00001459 return SQLITE_OK;
1460 }
drh3b7511c2001-05-26 13:15:44 +00001461 ovfl = pCell->ovfl;
1462 pCell->ovfl = 0;
1463 while( ovfl ){
drh8c42ca92001-06-22 19:15:00 +00001464 rc = sqlitepager_get(pPager, ovfl, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001465 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00001466 nextOvfl = pOvfl->iNext;
drhbd03cae2001-06-02 02:40:57 +00001467 rc = freePage(pBt, pOvfl, ovfl);
1468 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001469 sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001470 ovfl = nextOvfl;
drh3b7511c2001-05-26 13:15:44 +00001471 }
drh5e2f8b92001-05-28 00:41:15 +00001472 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00001473}
1474
1475/*
1476** Create a new cell from key and data. Overflow pages are allocated as
1477** necessary and linked to this cell.
1478*/
1479static int fillInCell(
1480 Btree *pBt, /* The whole Btree. Needed to allocate pages */
1481 Cell *pCell, /* Populate this Cell structure */
drh5c4d9702001-08-20 00:33:58 +00001482 const void *pKey, int nKey, /* The key */
1483 const void *pData,int nData /* The data */
drh3b7511c2001-05-26 13:15:44 +00001484){
drhdd793422001-06-28 01:54:48 +00001485 OverflowPage *pOvfl, *pPrior;
drh3b7511c2001-05-26 13:15:44 +00001486 Pgno *pNext;
1487 int spaceLeft;
drh8c42ca92001-06-22 19:15:00 +00001488 int n, rc;
drh3b7511c2001-05-26 13:15:44 +00001489 int nPayload;
drh5c4d9702001-08-20 00:33:58 +00001490 const char *pPayload;
drh3b7511c2001-05-26 13:15:44 +00001491 char *pSpace;
1492
drh5e2f8b92001-05-28 00:41:15 +00001493 pCell->h.leftChild = 0;
drh80ff32f2001-11-04 18:32:46 +00001494 pCell->h.nKey = nKey & 0xffff;
1495 pCell->h.nKeyHi = nKey >> 16;
1496 pCell->h.nData = nData & 0xffff;
1497 pCell->h.nDataHi = nData >> 16;
drh3b7511c2001-05-26 13:15:44 +00001498 pCell->h.iNext = 0;
1499
1500 pNext = &pCell->ovfl;
drh5e2f8b92001-05-28 00:41:15 +00001501 pSpace = pCell->aPayload;
drh3b7511c2001-05-26 13:15:44 +00001502 spaceLeft = MX_LOCAL_PAYLOAD;
1503 pPayload = pKey;
1504 pKey = 0;
1505 nPayload = nKey;
drhdd793422001-06-28 01:54:48 +00001506 pPrior = 0;
drh3b7511c2001-05-26 13:15:44 +00001507 while( nPayload>0 ){
1508 if( spaceLeft==0 ){
drh8c42ca92001-06-22 19:15:00 +00001509 rc = allocatePage(pBt, (MemPage**)&pOvfl, pNext);
drh3b7511c2001-05-26 13:15:44 +00001510 if( rc ){
1511 *pNext = 0;
drhdd793422001-06-28 01:54:48 +00001512 }
1513 if( pPrior ) sqlitepager_unref(pPrior);
1514 if( rc ){
drh5e2f8b92001-05-28 00:41:15 +00001515 clearCell(pBt, pCell);
drh3b7511c2001-05-26 13:15:44 +00001516 return rc;
1517 }
drhdd793422001-06-28 01:54:48 +00001518 pPrior = pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001519 spaceLeft = OVERFLOW_SIZE;
drh5e2f8b92001-05-28 00:41:15 +00001520 pSpace = pOvfl->aPayload;
drh8c42ca92001-06-22 19:15:00 +00001521 pNext = &pOvfl->iNext;
drh3b7511c2001-05-26 13:15:44 +00001522 }
1523 n = nPayload;
1524 if( n>spaceLeft ) n = spaceLeft;
1525 memcpy(pSpace, pPayload, n);
1526 nPayload -= n;
1527 if( nPayload==0 && pData ){
1528 pPayload = pData;
1529 nPayload = nData;
1530 pData = 0;
1531 }else{
1532 pPayload += n;
1533 }
1534 spaceLeft -= n;
1535 pSpace += n;
1536 }
drhdd793422001-06-28 01:54:48 +00001537 *pNext = 0;
1538 if( pPrior ){
1539 sqlitepager_unref(pPrior);
1540 }
drh3b7511c2001-05-26 13:15:44 +00001541 return SQLITE_OK;
1542}
1543
1544/*
drhbd03cae2001-06-02 02:40:57 +00001545** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00001546** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00001547** pointer in the third argument.
1548*/
1549static void reparentPage(Pager *pPager, Pgno pgno, MemPage *pNewParent){
1550 MemPage *pThis;
1551
drhdd793422001-06-28 01:54:48 +00001552 if( pgno==0 ) return;
1553 assert( pPager!=0 );
drhbd03cae2001-06-02 02:40:57 +00001554 pThis = sqlitepager_lookup(pPager, pgno);
drh6019e162001-07-02 17:51:45 +00001555 if( pThis && pThis->isInit ){
drhdd793422001-06-28 01:54:48 +00001556 if( pThis->pParent!=pNewParent ){
1557 if( pThis->pParent ) sqlitepager_unref(pThis->pParent);
1558 pThis->pParent = pNewParent;
1559 if( pNewParent ) sqlitepager_ref(pNewParent);
1560 }
1561 sqlitepager_unref(pThis);
drhbd03cae2001-06-02 02:40:57 +00001562 }
1563}
1564
1565/*
1566** Reparent all children of the given page to be the given page.
1567** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00001568** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00001569**
1570** This routine gets called after you memcpy() one page into
1571** another.
1572*/
drh8c42ca92001-06-22 19:15:00 +00001573static void reparentChildPages(Pager *pPager, MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00001574 int i;
1575 for(i=0; i<pPage->nCell; i++){
drh8c42ca92001-06-22 19:15:00 +00001576 reparentPage(pPager, pPage->apCell[i]->h.leftChild, pPage);
drhbd03cae2001-06-02 02:40:57 +00001577 }
drh14acc042001-06-10 19:56:58 +00001578 reparentPage(pPager, pPage->u.hdr.rightChild, pPage);
1579}
1580
1581/*
1582** Remove the i-th cell from pPage. This routine effects pPage only.
1583** The cell content is not freed or deallocated. It is assumed that
1584** the cell content has been copied someplace else. This routine just
1585** removes the reference to the cell from pPage.
1586**
1587** "sz" must be the number of bytes in the cell.
1588**
1589** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001590** Only the pPage->apCell[] array is important. The relinkCellList()
1591** routine will be called soon after this routine in order to rebuild
1592** the linked list.
drh14acc042001-06-10 19:56:58 +00001593*/
drh8c42ca92001-06-22 19:15:00 +00001594static void dropCell(MemPage *pPage, int idx, int sz){
drh14acc042001-06-10 19:56:58 +00001595 int j;
drh8c42ca92001-06-22 19:15:00 +00001596 assert( idx>=0 && idx<pPage->nCell );
1597 assert( sz==cellSize(pPage->apCell[idx]) );
drh6019e162001-07-02 17:51:45 +00001598 assert( sqlitepager_iswriteable(pPage) );
drh7c717f72001-06-24 20:39:41 +00001599 freeSpace(pPage, Addr(pPage->apCell[idx]) - Addr(pPage), sz);
1600 for(j=idx; j<pPage->nCell-1; j++){
drh14acc042001-06-10 19:56:58 +00001601 pPage->apCell[j] = pPage->apCell[j+1];
1602 }
1603 pPage->nCell--;
1604}
1605
1606/*
1607** Insert a new cell on pPage at cell index "i". pCell points to the
1608** content of the cell.
1609**
1610** If the cell content will fit on the page, then put it there. If it
1611** will not fit, then just make pPage->apCell[i] point to the content
1612** and set pPage->isOverfull.
1613**
1614** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001615** Only the pPage->apCell[] array is important. The relinkCellList()
1616** routine will be called soon after this routine in order to rebuild
1617** the linked list.
drh14acc042001-06-10 19:56:58 +00001618*/
1619static void insertCell(MemPage *pPage, int i, Cell *pCell, int sz){
1620 int idx, j;
1621 assert( i>=0 && i<=pPage->nCell );
1622 assert( sz==cellSize(pCell) );
drh6019e162001-07-02 17:51:45 +00001623 assert( sqlitepager_iswriteable(pPage) );
drh2aa679f2001-06-25 02:11:07 +00001624 idx = allocateSpace(pPage, sz);
drh14acc042001-06-10 19:56:58 +00001625 for(j=pPage->nCell; j>i; j--){
1626 pPage->apCell[j] = pPage->apCell[j-1];
1627 }
1628 pPage->nCell++;
drh14acc042001-06-10 19:56:58 +00001629 if( idx<=0 ){
1630 pPage->isOverfull = 1;
1631 pPage->apCell[i] = pCell;
1632 }else{
1633 memcpy(&pPage->u.aDisk[idx], pCell, sz);
drh8c42ca92001-06-22 19:15:00 +00001634 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[idx];
drh14acc042001-06-10 19:56:58 +00001635 }
1636}
1637
1638/*
1639** Rebuild the linked list of cells on a page so that the cells
drh8c42ca92001-06-22 19:15:00 +00001640** occur in the order specified by the pPage->apCell[] array.
1641** Invoke this routine once to repair damage after one or more
1642** invocations of either insertCell() or dropCell().
drh14acc042001-06-10 19:56:58 +00001643*/
1644static void relinkCellList(MemPage *pPage){
1645 int i;
1646 u16 *pIdx;
drh6019e162001-07-02 17:51:45 +00001647 assert( sqlitepager_iswriteable(pPage) );
drh14acc042001-06-10 19:56:58 +00001648 pIdx = &pPage->u.hdr.firstCell;
1649 for(i=0; i<pPage->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00001650 int idx = Addr(pPage->apCell[i]) - Addr(pPage);
drh8c42ca92001-06-22 19:15:00 +00001651 assert( idx>0 && idx<SQLITE_PAGE_SIZE );
drh14acc042001-06-10 19:56:58 +00001652 *pIdx = idx;
1653 pIdx = &pPage->apCell[i]->h.iNext;
1654 }
1655 *pIdx = 0;
1656}
1657
1658/*
1659** Make a copy of the contents of pFrom into pTo. The pFrom->apCell[]
drh5e00f6c2001-09-13 13:46:56 +00001660** pointers that point into pFrom->u.aDisk[] must be adjusted to point
drhdd793422001-06-28 01:54:48 +00001661** into pTo->u.aDisk[] instead. But some pFrom->apCell[] entries might
drh14acc042001-06-10 19:56:58 +00001662** not point to pFrom->u.aDisk[]. Those are unchanged.
1663*/
1664static void copyPage(MemPage *pTo, MemPage *pFrom){
1665 uptr from, to;
1666 int i;
1667 memcpy(pTo->u.aDisk, pFrom->u.aDisk, SQLITE_PAGE_SIZE);
drhdd793422001-06-28 01:54:48 +00001668 pTo->pParent = 0;
drh14acc042001-06-10 19:56:58 +00001669 pTo->isInit = 1;
1670 pTo->nCell = pFrom->nCell;
1671 pTo->nFree = pFrom->nFree;
1672 pTo->isOverfull = pFrom->isOverfull;
drh7c717f72001-06-24 20:39:41 +00001673 to = Addr(pTo);
1674 from = Addr(pFrom);
drh14acc042001-06-10 19:56:58 +00001675 for(i=0; i<pTo->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00001676 uptr x = Addr(pFrom->apCell[i]);
drh8c42ca92001-06-22 19:15:00 +00001677 if( x>from && x<from+SQLITE_PAGE_SIZE ){
1678 *((uptr*)&pTo->apCell[i]) = x + to - from;
drhdd793422001-06-28 01:54:48 +00001679 }else{
1680 pTo->apCell[i] = pFrom->apCell[i];
drh14acc042001-06-10 19:56:58 +00001681 }
1682 }
drhbd03cae2001-06-02 02:40:57 +00001683}
1684
1685/*
drh8b2f49b2001-06-08 00:21:52 +00001686** This routine redistributes Cells on pPage and up to two siblings
1687** of pPage so that all pages have about the same amount of free space.
drh14acc042001-06-10 19:56:58 +00001688** Usually one sibling on either side of pPage is used in the balancing,
drh8b2f49b2001-06-08 00:21:52 +00001689** though both siblings might come from one side if pPage is the first
1690** or last child of its parent. If pPage has fewer than two siblings
1691** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00001692** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00001693**
1694** The number of siblings of pPage might be increased or decreased by
drh8c42ca92001-06-22 19:15:00 +00001695** one in an effort to keep pages between 66% and 100% full. The root page
1696** is special and is allowed to be less than 66% full. If pPage is
1697** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00001698** or decreased by one, as necessary, to keep the root page from being
1699** overfull or empty.
1700**
drh14acc042001-06-10 19:56:58 +00001701** This routine calls relinkCellList() on its input page regardless of
1702** whether or not it does any real balancing. Client routines will typically
1703** invoke insertCell() or dropCell() before calling this routine, so we
1704** need to call relinkCellList() to clean up the mess that those other
1705** routines left behind.
1706**
1707** pCur is left pointing to the same cell as when this routine was called
drh8c42ca92001-06-22 19:15:00 +00001708** even if that cell gets moved to a different page. pCur may be NULL.
1709** Set the pCur parameter to NULL if you do not care about keeping track
1710** of a cell as that will save this routine the work of keeping track of it.
drh14acc042001-06-10 19:56:58 +00001711**
drh8b2f49b2001-06-08 00:21:52 +00001712** Note that when this routine is called, some of the Cells on pPage
drh14acc042001-06-10 19:56:58 +00001713** might not actually be stored in pPage->u.aDisk[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00001714** if the page is overfull. Part of the job of this routine is to
drh14acc042001-06-10 19:56:58 +00001715** make sure all Cells for pPage once again fit in pPage->u.aDisk[].
1716**
drh8c42ca92001-06-22 19:15:00 +00001717** In the course of balancing the siblings of pPage, the parent of pPage
1718** might become overfull or underfull. If that happens, then this routine
1719** is called recursively on the parent.
1720**
drh5e00f6c2001-09-13 13:46:56 +00001721** If this routine fails for any reason, it might leave the database
1722** in a corrupted state. So if this routine fails, the database should
1723** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00001724*/
drh14acc042001-06-10 19:56:58 +00001725static int balance(Btree *pBt, MemPage *pPage, BtCursor *pCur){
drh8b2f49b2001-06-08 00:21:52 +00001726 MemPage *pParent; /* The parent of pPage */
drh14acc042001-06-10 19:56:58 +00001727 MemPage *apOld[3]; /* pPage and up to two siblings */
drh8b2f49b2001-06-08 00:21:52 +00001728 Pgno pgnoOld[3]; /* Page numbers for each page in apOld[] */
drh14acc042001-06-10 19:56:58 +00001729 MemPage *apNew[4]; /* pPage and up to 3 siblings after balancing */
1730 Pgno pgnoNew[4]; /* Page numbers for each page in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00001731 int idxDiv[3]; /* Indices of divider cells in pParent */
1732 Cell *apDiv[3]; /* Divider cells in pParent */
1733 int nCell; /* Number of cells in apCell[] */
1734 int nOld; /* Number of pages in apOld[] */
1735 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00001736 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00001737 int i, j, k; /* Loop counters */
1738 int idx; /* Index of pPage in pParent->apCell[] */
1739 int nxDiv; /* Next divider slot in pParent->apCell[] */
1740 int rc; /* The return code */
1741 int iCur; /* apCell[iCur] is the cell of the cursor */
drh5edc3122001-09-13 21:53:09 +00001742 MemPage *pOldCurPage; /* The cursor originally points to this page */
drh8c42ca92001-06-22 19:15:00 +00001743 int totalSize; /* Total bytes for all cells */
drh6019e162001-07-02 17:51:45 +00001744 int subtotal; /* Subtotal of bytes in cells on one page */
1745 int cntNew[4]; /* Index in apCell[] of cell after i-th page */
1746 int szNew[4]; /* Combined size of cells place on i-th page */
drh9ca7d3b2001-06-28 11:50:21 +00001747 MemPage *extraUnref = 0; /* A page that needs to be unref-ed */
drh8c42ca92001-06-22 19:15:00 +00001748 Pgno pgno; /* Page number */
drh14acc042001-06-10 19:56:58 +00001749 Cell *apCell[MX_CELL*3+5]; /* All cells from pages being balanceed */
1750 int szCell[MX_CELL*3+5]; /* Local size of all cells */
1751 Cell aTemp[2]; /* Temporary holding area for apDiv[] */
1752 MemPage aOld[3]; /* Temporary copies of pPage and its siblings */
drh8b2f49b2001-06-08 00:21:52 +00001753
drh14acc042001-06-10 19:56:58 +00001754 /*
1755 ** Return without doing any work if pPage is neither overfull nor
1756 ** underfull.
drh8b2f49b2001-06-08 00:21:52 +00001757 */
drh6019e162001-07-02 17:51:45 +00001758 assert( sqlitepager_iswriteable(pPage) );
drha1b351a2001-09-14 16:42:12 +00001759 if( !pPage->isOverfull && pPage->nFree<SQLITE_PAGE_SIZE/2
1760 && pPage->nCell>=2){
drh14acc042001-06-10 19:56:58 +00001761 relinkCellList(pPage);
drh8b2f49b2001-06-08 00:21:52 +00001762 return SQLITE_OK;
1763 }
1764
1765 /*
drh14acc042001-06-10 19:56:58 +00001766 ** Find the parent of the page to be balanceed.
1767 ** If there is no parent, it means this page is the root page and
drh8b2f49b2001-06-08 00:21:52 +00001768 ** special rules apply.
1769 */
drh14acc042001-06-10 19:56:58 +00001770 pParent = pPage->pParent;
drh8b2f49b2001-06-08 00:21:52 +00001771 if( pParent==0 ){
1772 Pgno pgnoChild;
drh8c42ca92001-06-22 19:15:00 +00001773 MemPage *pChild;
drh8b2f49b2001-06-08 00:21:52 +00001774 if( pPage->nCell==0 ){
drh14acc042001-06-10 19:56:58 +00001775 if( pPage->u.hdr.rightChild ){
1776 /*
1777 ** The root page is empty. Copy the one child page
drh8b2f49b2001-06-08 00:21:52 +00001778 ** into the root page and return. This reduces the depth
1779 ** of the BTree by one.
1780 */
drh14acc042001-06-10 19:56:58 +00001781 pgnoChild = pPage->u.hdr.rightChild;
drh8c42ca92001-06-22 19:15:00 +00001782 rc = sqlitepager_get(pBt->pPager, pgnoChild, (void**)&pChild);
drh8b2f49b2001-06-08 00:21:52 +00001783 if( rc ) return rc;
1784 memcpy(pPage, pChild, SQLITE_PAGE_SIZE);
1785 pPage->isInit = 0;
drh6019e162001-07-02 17:51:45 +00001786 rc = initPage(pPage, sqlitepager_pagenumber(pPage), 0);
1787 assert( rc==SQLITE_OK );
drh8b2f49b2001-06-08 00:21:52 +00001788 reparentChildPages(pBt->pPager, pPage);
drh5edc3122001-09-13 21:53:09 +00001789 if( pCur && pCur->pPage==pChild ){
1790 sqlitepager_unref(pChild);
1791 pCur->pPage = pPage;
1792 sqlitepager_ref(pPage);
1793 }
drh8b2f49b2001-06-08 00:21:52 +00001794 freePage(pBt, pChild, pgnoChild);
1795 sqlitepager_unref(pChild);
drhefc251d2001-07-01 22:12:01 +00001796 }else{
1797 relinkCellList(pPage);
drh8b2f49b2001-06-08 00:21:52 +00001798 }
1799 return SQLITE_OK;
1800 }
drh14acc042001-06-10 19:56:58 +00001801 if( !pPage->isOverfull ){
drh8b2f49b2001-06-08 00:21:52 +00001802 /* It is OK for the root page to be less than half full.
1803 */
drh14acc042001-06-10 19:56:58 +00001804 relinkCellList(pPage);
drh8b2f49b2001-06-08 00:21:52 +00001805 return SQLITE_OK;
1806 }
drh14acc042001-06-10 19:56:58 +00001807 /*
1808 ** If we get to here, it means the root page is overfull.
drh8b2f49b2001-06-08 00:21:52 +00001809 ** When this happens, Create a new child page and copy the
1810 ** contents of the root into the child. Then make the root
drh14acc042001-06-10 19:56:58 +00001811 ** page an empty page with rightChild pointing to the new
drh8b2f49b2001-06-08 00:21:52 +00001812 ** child. Then fall thru to the code below which will cause
1813 ** the overfull child page to be split.
1814 */
drh14acc042001-06-10 19:56:58 +00001815 rc = sqlitepager_write(pPage);
1816 if( rc ) return rc;
drh8b2f49b2001-06-08 00:21:52 +00001817 rc = allocatePage(pBt, &pChild, &pgnoChild);
1818 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00001819 assert( sqlitepager_iswriteable(pChild) );
drh14acc042001-06-10 19:56:58 +00001820 copyPage(pChild, pPage);
1821 pChild->pParent = pPage;
drhdd793422001-06-28 01:54:48 +00001822 sqlitepager_ref(pPage);
drh14acc042001-06-10 19:56:58 +00001823 pChild->isOverfull = 1;
drh5edc3122001-09-13 21:53:09 +00001824 if( pCur && pCur->pPage==pPage ){
1825 sqlitepager_unref(pPage);
drh14acc042001-06-10 19:56:58 +00001826 pCur->pPage = pChild;
drh9ca7d3b2001-06-28 11:50:21 +00001827 }else{
1828 extraUnref = pChild;
drh8b2f49b2001-06-08 00:21:52 +00001829 }
drh8b2f49b2001-06-08 00:21:52 +00001830 zeroPage(pPage);
drh14acc042001-06-10 19:56:58 +00001831 pPage->u.hdr.rightChild = pgnoChild;
drh8b2f49b2001-06-08 00:21:52 +00001832 pParent = pPage;
1833 pPage = pChild;
drh8b2f49b2001-06-08 00:21:52 +00001834 }
drh6019e162001-07-02 17:51:45 +00001835 rc = sqlitepager_write(pParent);
1836 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00001837
drh8b2f49b2001-06-08 00:21:52 +00001838 /*
drh14acc042001-06-10 19:56:58 +00001839 ** Find the Cell in the parent page whose h.leftChild points back
1840 ** to pPage. The "idx" variable is the index of that cell. If pPage
1841 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00001842 */
1843 idx = -1;
1844 pgno = sqlitepager_pagenumber(pPage);
1845 for(i=0; i<pParent->nCell; i++){
1846 if( pParent->apCell[i]->h.leftChild==pgno ){
1847 idx = i;
1848 break;
1849 }
1850 }
drhdd793422001-06-28 01:54:48 +00001851 if( idx<0 && pParent->u.hdr.rightChild==pgno ){
1852 idx = pParent->nCell;
drh8b2f49b2001-06-08 00:21:52 +00001853 }
1854 if( idx<0 ){
drh14acc042001-06-10 19:56:58 +00001855 return SQLITE_CORRUPT;
drh8b2f49b2001-06-08 00:21:52 +00001856 }
1857
1858 /*
drh14acc042001-06-10 19:56:58 +00001859 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00001860 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00001861 */
drh14acc042001-06-10 19:56:58 +00001862 nOld = nNew = 0;
1863 sqlitepager_ref(pParent);
1864
1865 /*
1866 ** Find sibling pages to pPage and the Cells in pParent that divide
1867 ** the siblings. An attempt is made to find one sibling on either
1868 ** side of pPage. Both siblings are taken from one side, however, if
1869 ** pPage is either the first or last child of its parent. If pParent
1870 ** has 3 or fewer children then all children of pParent are taken.
1871 */
1872 if( idx==pParent->nCell ){
1873 nxDiv = idx - 2;
drh8b2f49b2001-06-08 00:21:52 +00001874 }else{
drh14acc042001-06-10 19:56:58 +00001875 nxDiv = idx - 1;
drh8b2f49b2001-06-08 00:21:52 +00001876 }
drh14acc042001-06-10 19:56:58 +00001877 if( nxDiv<0 ) nxDiv = 0;
drh8b2f49b2001-06-08 00:21:52 +00001878 nDiv = 0;
drh14acc042001-06-10 19:56:58 +00001879 for(i=0, k=nxDiv; i<3; i++, k++){
1880 if( k<pParent->nCell ){
1881 idxDiv[i] = k;
1882 apDiv[i] = pParent->apCell[k];
drh8b2f49b2001-06-08 00:21:52 +00001883 nDiv++;
1884 pgnoOld[i] = apDiv[i]->h.leftChild;
drh14acc042001-06-10 19:56:58 +00001885 }else if( k==pParent->nCell ){
drh8c42ca92001-06-22 19:15:00 +00001886 pgnoOld[i] = pParent->u.hdr.rightChild;
drh14acc042001-06-10 19:56:58 +00001887 }else{
1888 break;
drh8b2f49b2001-06-08 00:21:52 +00001889 }
drh8c42ca92001-06-22 19:15:00 +00001890 rc = sqlitepager_get(pBt->pPager, pgnoOld[i], (void**)&apOld[i]);
drh14acc042001-06-10 19:56:58 +00001891 if( rc ) goto balance_cleanup;
drh6019e162001-07-02 17:51:45 +00001892 rc = initPage(apOld[i], pgnoOld[i], pParent);
1893 if( rc ) goto balance_cleanup;
drh14acc042001-06-10 19:56:58 +00001894 nOld++;
drh8b2f49b2001-06-08 00:21:52 +00001895 }
1896
1897 /*
drh14acc042001-06-10 19:56:58 +00001898 ** Set iCur to be the index in apCell[] of the cell that the cursor
1899 ** is pointing to. We will need this later on in order to keep the
drh5edc3122001-09-13 21:53:09 +00001900 ** cursor pointing at the same cell. If pCur points to a page that
1901 ** has no involvement with this rebalancing, then set iCur to a large
1902 ** number so that the iCur==j tests always fail in the main cell
1903 ** distribution loop below.
drh14acc042001-06-10 19:56:58 +00001904 */
1905 if( pCur ){
drh5edc3122001-09-13 21:53:09 +00001906 iCur = 0;
1907 for(i=0; i<nOld; i++){
1908 if( pCur->pPage==apOld[i] ){
1909 iCur += pCur->idx;
1910 break;
1911 }
1912 iCur += apOld[i]->nCell;
1913 if( i<nOld-1 && pCur->pPage==pParent && pCur->idx==idxDiv[i] ){
1914 break;
1915 }
1916 iCur++;
drh14acc042001-06-10 19:56:58 +00001917 }
drh5edc3122001-09-13 21:53:09 +00001918 pOldCurPage = pCur->pPage;
drh14acc042001-06-10 19:56:58 +00001919 }
1920
1921 /*
1922 ** Make copies of the content of pPage and its siblings into aOld[].
1923 ** The rest of this function will use data from the copies rather
1924 ** that the original pages since the original pages will be in the
1925 ** process of being overwritten.
1926 */
1927 for(i=0; i<nOld; i++){
1928 copyPage(&aOld[i], apOld[i]);
1929 rc = freePage(pBt, apOld[i], pgnoOld[i]);
1930 if( rc ) goto balance_cleanup;
drhdd793422001-06-28 01:54:48 +00001931 sqlitepager_unref(apOld[i]);
drh14acc042001-06-10 19:56:58 +00001932 apOld[i] = &aOld[i];
1933 }
1934
1935 /*
1936 ** Load pointers to all cells on sibling pages and the divider cells
1937 ** into the local apCell[] array. Make copies of the divider cells
1938 ** into aTemp[] and remove the the divider Cells from pParent.
drh8b2f49b2001-06-08 00:21:52 +00001939 */
1940 nCell = 0;
1941 for(i=0; i<nOld; i++){
1942 MemPage *pOld = apOld[i];
1943 for(j=0; j<pOld->nCell; j++){
drh14acc042001-06-10 19:56:58 +00001944 apCell[nCell] = pOld->apCell[j];
1945 szCell[nCell] = cellSize(apCell[nCell]);
1946 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00001947 }
1948 if( i<nOld-1 ){
drh14acc042001-06-10 19:56:58 +00001949 szCell[nCell] = cellSize(apDiv[i]);
drh8c42ca92001-06-22 19:15:00 +00001950 memcpy(&aTemp[i], apDiv[i], szCell[nCell]);
drh14acc042001-06-10 19:56:58 +00001951 apCell[nCell] = &aTemp[i];
1952 dropCell(pParent, nxDiv, szCell[nCell]);
1953 assert( apCell[nCell]->h.leftChild==pgnoOld[i] );
1954 apCell[nCell]->h.leftChild = pOld->u.hdr.rightChild;
1955 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00001956 }
1957 }
1958
1959 /*
drh6019e162001-07-02 17:51:45 +00001960 ** Figure out the number of pages needed to hold all nCell cells.
1961 ** Store this number in "k". Also compute szNew[] which is the total
1962 ** size of all cells on the i-th page and cntNew[] which is the index
1963 ** in apCell[] of the cell that divides path i from path i+1.
1964 ** cntNew[k] should equal nCell.
1965 **
1966 ** This little patch of code is critical for keeping the tree
1967 ** balanced.
drh8b2f49b2001-06-08 00:21:52 +00001968 */
1969 totalSize = 0;
1970 for(i=0; i<nCell; i++){
drh14acc042001-06-10 19:56:58 +00001971 totalSize += szCell[i];
drh8b2f49b2001-06-08 00:21:52 +00001972 }
drh6019e162001-07-02 17:51:45 +00001973 for(subtotal=k=i=0; i<nCell; i++){
1974 subtotal += szCell[i];
1975 if( subtotal > USABLE_SPACE ){
1976 szNew[k] = subtotal - szCell[i];
1977 cntNew[k] = i;
1978 subtotal = 0;
1979 k++;
1980 }
1981 }
1982 szNew[k] = subtotal;
1983 cntNew[k] = nCell;
1984 k++;
1985 for(i=k-1; i>0; i--){
1986 while( szNew[i]<USABLE_SPACE/2 ){
1987 cntNew[i-1]--;
1988 assert( cntNew[i-1]>0 );
1989 szNew[i] += szCell[cntNew[i-1]];
1990 szNew[i-1] -= szCell[cntNew[i-1]-1];
1991 }
1992 }
1993 assert( cntNew[0]>0 );
drh8b2f49b2001-06-08 00:21:52 +00001994
1995 /*
drh6019e162001-07-02 17:51:45 +00001996 ** Allocate k new pages
drh8b2f49b2001-06-08 00:21:52 +00001997 */
drh14acc042001-06-10 19:56:58 +00001998 for(i=0; i<k; i++){
drh8b2f49b2001-06-08 00:21:52 +00001999 rc = allocatePage(pBt, &apNew[i], &pgnoNew[i]);
drh14acc042001-06-10 19:56:58 +00002000 if( rc ) goto balance_cleanup;
2001 nNew++;
drh8b2f49b2001-06-08 00:21:52 +00002002 zeroPage(apNew[i]);
drh6019e162001-07-02 17:51:45 +00002003 apNew[i]->isInit = 1;
drh8b2f49b2001-06-08 00:21:52 +00002004 }
2005
2006 /*
drh14acc042001-06-10 19:56:58 +00002007 ** Evenly distribute the data in apCell[] across the new pages.
2008 ** Insert divider cells into pParent as necessary.
2009 */
2010 j = 0;
2011 for(i=0; i<nNew; i++){
2012 MemPage *pNew = apNew[i];
drh6019e162001-07-02 17:51:45 +00002013 while( j<cntNew[i] ){
2014 assert( pNew->nFree>=szCell[j] );
drh14acc042001-06-10 19:56:58 +00002015 if( pCur && iCur==j ){ pCur->pPage = pNew; pCur->idx = pNew->nCell; }
2016 insertCell(pNew, pNew->nCell, apCell[j], szCell[j]);
2017 j++;
2018 }
drh6019e162001-07-02 17:51:45 +00002019 assert( pNew->nCell>0 );
drh14acc042001-06-10 19:56:58 +00002020 assert( !pNew->isOverfull );
2021 relinkCellList(pNew);
2022 if( i<nNew-1 && j<nCell ){
2023 pNew->u.hdr.rightChild = apCell[j]->h.leftChild;
2024 apCell[j]->h.leftChild = pgnoNew[i];
2025 if( pCur && iCur==j ){ pCur->pPage = pParent; pCur->idx = nxDiv; }
2026 insertCell(pParent, nxDiv, apCell[j], szCell[j]);
2027 j++;
2028 nxDiv++;
2029 }
2030 }
drh6019e162001-07-02 17:51:45 +00002031 assert( j==nCell );
drh14acc042001-06-10 19:56:58 +00002032 apNew[nNew-1]->u.hdr.rightChild = apOld[nOld-1]->u.hdr.rightChild;
2033 if( nxDiv==pParent->nCell ){
2034 pParent->u.hdr.rightChild = pgnoNew[nNew-1];
2035 }else{
2036 pParent->apCell[nxDiv]->h.leftChild = pgnoNew[nNew-1];
2037 }
2038 if( pCur ){
drh3fc190c2001-09-14 03:24:23 +00002039 if( j<=iCur && pCur->pPage==pParent && pCur->idx>idxDiv[nOld-1] ){
2040 assert( pCur->pPage==pOldCurPage );
2041 pCur->idx += nNew - nOld;
2042 }else{
2043 assert( pOldCurPage!=0 );
2044 sqlitepager_ref(pCur->pPage);
2045 sqlitepager_unref(pOldCurPage);
2046 }
drh14acc042001-06-10 19:56:58 +00002047 }
2048
2049 /*
2050 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00002051 */
2052 for(i=0; i<nNew; i++){
drh14acc042001-06-10 19:56:58 +00002053 reparentChildPages(pBt->pPager, apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002054 }
drh14acc042001-06-10 19:56:58 +00002055 reparentChildPages(pBt->pPager, pParent);
drh8b2f49b2001-06-08 00:21:52 +00002056
2057 /*
drh14acc042001-06-10 19:56:58 +00002058 ** balance the parent page.
drh8b2f49b2001-06-08 00:21:52 +00002059 */
drh5edc3122001-09-13 21:53:09 +00002060 rc = balance(pBt, pParent, pCur);
drh8b2f49b2001-06-08 00:21:52 +00002061
2062 /*
drh14acc042001-06-10 19:56:58 +00002063 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00002064 */
drh14acc042001-06-10 19:56:58 +00002065balance_cleanup:
drh9ca7d3b2001-06-28 11:50:21 +00002066 if( extraUnref ){
2067 sqlitepager_unref(extraUnref);
2068 }
drh8b2f49b2001-06-08 00:21:52 +00002069 for(i=0; i<nOld; i++){
drhdd793422001-06-28 01:54:48 +00002070 if( apOld[i]!=&aOld[i] ) sqlitepager_unref(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00002071 }
drh14acc042001-06-10 19:56:58 +00002072 for(i=0; i<nNew; i++){
2073 sqlitepager_unref(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002074 }
drh14acc042001-06-10 19:56:58 +00002075 if( pCur && pCur->pPage==0 ){
2076 pCur->pPage = pParent;
2077 pCur->idx = 0;
2078 }else{
2079 sqlitepager_unref(pParent);
drh8b2f49b2001-06-08 00:21:52 +00002080 }
2081 return rc;
2082}
2083
2084/*
drh3b7511c2001-05-26 13:15:44 +00002085** Insert a new record into the BTree. The key is given by (pKey,nKey)
2086** and the data is given by (pData,nData). The cursor is used only to
2087** define what database the record should be inserted into. The cursor
drh14acc042001-06-10 19:56:58 +00002088** is left pointing at the new record.
drh3b7511c2001-05-26 13:15:44 +00002089*/
2090int sqliteBtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00002091 BtCursor *pCur, /* Insert data into the table of this cursor */
drhbe0072d2001-09-13 14:46:09 +00002092 const void *pKey, int nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00002093 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00002094){
2095 Cell newCell;
2096 int rc;
2097 int loc;
drh14acc042001-06-10 19:56:58 +00002098 int szNew;
drh3b7511c2001-05-26 13:15:44 +00002099 MemPage *pPage;
2100 Btree *pBt = pCur->pBt;
2101
drhecdc7532001-09-23 02:35:53 +00002102 if( pCur->pPage==0 ){
2103 return SQLITE_ABORT; /* A rollback destroyed this cursor */
2104 }
drh5edc3122001-09-13 21:53:09 +00002105 if( !pCur->pBt->inTrans || nKey+nData==0 ){
drh8b2f49b2001-06-08 00:21:52 +00002106 return SQLITE_ERROR; /* Must start a transaction first */
2107 }
drhecdc7532001-09-23 02:35:53 +00002108 if( !pCur->wrFlag ){
2109 return SQLITE_PERM; /* Cursor not open for writing */
2110 }
drh14acc042001-06-10 19:56:58 +00002111 rc = sqliteBtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00002112 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002113 pPage = pCur->pPage;
2114 rc = sqlitepager_write(pPage);
drhbd03cae2001-06-02 02:40:57 +00002115 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00002116 rc = fillInCell(pBt, &newCell, pKey, nKey, pData, nData);
2117 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002118 szNew = cellSize(&newCell);
drh3b7511c2001-05-26 13:15:44 +00002119 if( loc==0 ){
drh14acc042001-06-10 19:56:58 +00002120 newCell.h.leftChild = pPage->apCell[pCur->idx]->h.leftChild;
2121 rc = clearCell(pBt, pPage->apCell[pCur->idx]);
drh5e2f8b92001-05-28 00:41:15 +00002122 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002123 dropCell(pPage, pCur->idx, cellSize(pPage->apCell[pCur->idx]));
drh7c717f72001-06-24 20:39:41 +00002124 }else if( loc<0 && pPage->nCell>0 ){
drh14acc042001-06-10 19:56:58 +00002125 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
2126 pCur->idx++;
2127 }else{
2128 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
drh3b7511c2001-05-26 13:15:44 +00002129 }
drh7c717f72001-06-24 20:39:41 +00002130 insertCell(pPage, pCur->idx, &newCell, szNew);
drh14acc042001-06-10 19:56:58 +00002131 rc = balance(pCur->pBt, pPage, pCur);
drh3fc190c2001-09-14 03:24:23 +00002132 /* sqliteBtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
2133 /* fflush(stdout); */
drh5e2f8b92001-05-28 00:41:15 +00002134 return rc;
2135}
2136
2137/*
drhbd03cae2001-06-02 02:40:57 +00002138** Delete the entry that the cursor is pointing to.
drh5e2f8b92001-05-28 00:41:15 +00002139**
drhbd03cae2001-06-02 02:40:57 +00002140** The cursor is left pointing at either the next or the previous
2141** entry. If the cursor is left pointing to the next entry, then
2142** the pCur->bSkipNext flag is set which forces the next call to
2143** sqliteBtreeNext() to be a no-op. That way, you can always call
2144** sqliteBtreeNext() after a delete and the cursor will be left
2145** pointing to the first entry after the deleted entry.
drh3b7511c2001-05-26 13:15:44 +00002146*/
2147int sqliteBtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00002148 MemPage *pPage = pCur->pPage;
2149 Cell *pCell;
2150 int rc;
drh8c42ca92001-06-22 19:15:00 +00002151 Pgno pgnoChild;
drh8b2f49b2001-06-08 00:21:52 +00002152
drhecdc7532001-09-23 02:35:53 +00002153 if( pCur->pPage==0 ){
2154 return SQLITE_ABORT; /* A rollback destroyed this cursor */
2155 }
drh8b2f49b2001-06-08 00:21:52 +00002156 if( !pCur->pBt->inTrans ){
2157 return SQLITE_ERROR; /* Must start a transaction first */
2158 }
drhbd03cae2001-06-02 02:40:57 +00002159 if( pCur->idx >= pPage->nCell ){
2160 return SQLITE_ERROR; /* The cursor is not pointing to anything */
2161 }
drhecdc7532001-09-23 02:35:53 +00002162 if( !pCur->wrFlag ){
2163 return SQLITE_PERM; /* Did not open this cursor for writing */
2164 }
drhbd03cae2001-06-02 02:40:57 +00002165 rc = sqlitepager_write(pPage);
2166 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002167 pCell = pPage->apCell[pCur->idx];
drh14acc042001-06-10 19:56:58 +00002168 pgnoChild = pCell->h.leftChild;
drh8c42ca92001-06-22 19:15:00 +00002169 clearCell(pCur->pBt, pCell);
drh14acc042001-06-10 19:56:58 +00002170 if( pgnoChild ){
2171 /*
drh5e00f6c2001-09-13 13:46:56 +00002172 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00002173 ** do something we will leave a hole on an internal page.
2174 ** We have to fill the hole by moving in a cell from a leaf. The
2175 ** next Cell after the one to be deleted is guaranteed to exist and
2176 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00002177 */
drh14acc042001-06-10 19:56:58 +00002178 BtCursor leafCur;
2179 Cell *pNext;
2180 int szNext;
2181 getTempCursor(pCur, &leafCur);
2182 rc = sqliteBtreeNext(&leafCur, 0);
2183 if( rc!=SQLITE_OK ){
2184 return SQLITE_CORRUPT;
drh5e2f8b92001-05-28 00:41:15 +00002185 }
drh6019e162001-07-02 17:51:45 +00002186 rc = sqlitepager_write(leafCur.pPage);
2187 if( rc ) return rc;
drh9ca7d3b2001-06-28 11:50:21 +00002188 dropCell(pPage, pCur->idx, cellSize(pCell));
drh8c42ca92001-06-22 19:15:00 +00002189 pNext = leafCur.pPage->apCell[leafCur.idx];
drh14acc042001-06-10 19:56:58 +00002190 szNext = cellSize(pNext);
drh8c42ca92001-06-22 19:15:00 +00002191 pNext->h.leftChild = pgnoChild;
drh14acc042001-06-10 19:56:58 +00002192 insertCell(pPage, pCur->idx, pNext, szNext);
2193 rc = balance(pCur->pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002194 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002195 pCur->bSkipNext = 1;
drh14acc042001-06-10 19:56:58 +00002196 dropCell(leafCur.pPage, leafCur.idx, szNext);
2197 rc = balance(pCur->pBt, leafCur.pPage, 0);
drh8c42ca92001-06-22 19:15:00 +00002198 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00002199 }else{
drh9ca7d3b2001-06-28 11:50:21 +00002200 dropCell(pPage, pCur->idx, cellSize(pCell));
drh5edc3122001-09-13 21:53:09 +00002201 if( pCur->idx>=pPage->nCell ){
2202 pCur->idx = pPage->nCell-1;
2203 if( pCur->idx<0 ){ pCur->idx = 0; }
2204 pCur->bSkipNext = 0;
drh6019e162001-07-02 17:51:45 +00002205 }else{
2206 pCur->bSkipNext = 1;
2207 }
drh14acc042001-06-10 19:56:58 +00002208 rc = balance(pCur->pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002209 }
drh5e2f8b92001-05-28 00:41:15 +00002210 return rc;
drh3b7511c2001-05-26 13:15:44 +00002211}
drh8b2f49b2001-06-08 00:21:52 +00002212
2213/*
2214** Create a new BTree in the same file. Write into *piTable the index
2215** of the root page of the new table.
2216*/
2217int sqliteBtreeCreateTable(Btree *pBt, int *piTable){
2218 MemPage *pRoot;
2219 Pgno pgnoRoot;
2220 int rc;
2221 if( !pBt->inTrans ){
2222 return SQLITE_ERROR; /* Must start a transaction first */
2223 }
2224 rc = allocatePage(pBt, &pRoot, &pgnoRoot);
2225 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002226 assert( sqlitepager_iswriteable(pRoot) );
drh8b2f49b2001-06-08 00:21:52 +00002227 zeroPage(pRoot);
2228 sqlitepager_unref(pRoot);
2229 *piTable = (int)pgnoRoot;
2230 return SQLITE_OK;
2231}
2232
2233/*
2234** Erase the given database page and all its children. Return
2235** the page to the freelist.
2236*/
drh2aa679f2001-06-25 02:11:07 +00002237static int clearDatabasePage(Btree *pBt, Pgno pgno, int freePageFlag){
drh8b2f49b2001-06-08 00:21:52 +00002238 MemPage *pPage;
2239 int rc;
drh8b2f49b2001-06-08 00:21:52 +00002240 Cell *pCell;
2241 int idx;
2242
drh8c42ca92001-06-22 19:15:00 +00002243 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pPage);
drh8b2f49b2001-06-08 00:21:52 +00002244 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002245 rc = sqlitepager_write(pPage);
2246 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002247 idx = pPage->u.hdr.firstCell;
drh8b2f49b2001-06-08 00:21:52 +00002248 while( idx>0 ){
drh14acc042001-06-10 19:56:58 +00002249 pCell = (Cell*)&pPage->u.aDisk[idx];
drh8b2f49b2001-06-08 00:21:52 +00002250 idx = pCell->h.iNext;
2251 if( pCell->h.leftChild ){
drh2aa679f2001-06-25 02:11:07 +00002252 rc = clearDatabasePage(pBt, pCell->h.leftChild, 1);
drh8b2f49b2001-06-08 00:21:52 +00002253 if( rc ) return rc;
2254 }
drh8c42ca92001-06-22 19:15:00 +00002255 rc = clearCell(pBt, pCell);
drh8b2f49b2001-06-08 00:21:52 +00002256 if( rc ) return rc;
2257 }
drh2aa679f2001-06-25 02:11:07 +00002258 if( pPage->u.hdr.rightChild ){
2259 rc = clearDatabasePage(pBt, pPage->u.hdr.rightChild, 1);
2260 if( rc ) return rc;
2261 }
2262 if( freePageFlag ){
2263 rc = freePage(pBt, pPage, pgno);
2264 }else{
2265 zeroPage(pPage);
2266 }
drhdd793422001-06-28 01:54:48 +00002267 sqlitepager_unref(pPage);
drh2aa679f2001-06-25 02:11:07 +00002268 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002269}
2270
2271/*
2272** Delete all information from a single table in the database.
2273*/
2274int sqliteBtreeClearTable(Btree *pBt, int iTable){
2275 int rc;
drh5a2c2c22001-11-21 02:21:11 +00002276 ptr nLock;
drh8b2f49b2001-06-08 00:21:52 +00002277 if( !pBt->inTrans ){
2278 return SQLITE_ERROR; /* Must start a transaction first */
2279 }
drh5a2c2c22001-11-21 02:21:11 +00002280 nLock = (ptr)sqliteHashFind(&pBt->locks, 0, iTable);
drhecdc7532001-09-23 02:35:53 +00002281 if( nLock ){
2282 return SQLITE_LOCKED;
2283 }
drh2aa679f2001-06-25 02:11:07 +00002284 rc = clearDatabasePage(pBt, (Pgno)iTable, 0);
drh8b2f49b2001-06-08 00:21:52 +00002285 if( rc ){
2286 sqliteBtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00002287 }
drh8c42ca92001-06-22 19:15:00 +00002288 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002289}
2290
2291/*
2292** Erase all information in a table and add the root of the table to
2293** the freelist. Except, the root of the principle table (the one on
2294** page 2) is never added to the freelist.
2295*/
2296int sqliteBtreeDropTable(Btree *pBt, int iTable){
2297 int rc;
2298 MemPage *pPage;
2299 if( !pBt->inTrans ){
2300 return SQLITE_ERROR; /* Must start a transaction first */
2301 }
drh8c42ca92001-06-22 19:15:00 +00002302 rc = sqlitepager_get(pBt->pPager, (Pgno)iTable, (void**)&pPage);
drh2aa679f2001-06-25 02:11:07 +00002303 if( rc ) return rc;
2304 rc = sqliteBtreeClearTable(pBt, iTable);
2305 if( rc ) return rc;
2306 if( iTable>2 ){
2307 rc = freePage(pBt, pPage, iTable);
2308 }else{
2309 zeroPage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00002310 }
drhdd793422001-06-28 01:54:48 +00002311 sqlitepager_unref(pPage);
drh8b2f49b2001-06-08 00:21:52 +00002312 return rc;
2313}
2314
2315/*
2316** Read the meta-information out of a database file.
2317*/
2318int sqliteBtreeGetMeta(Btree *pBt, int *aMeta){
2319 PageOne *pP1;
2320 int rc;
2321
drh8c42ca92001-06-22 19:15:00 +00002322 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00002323 if( rc ) return rc;
drh2aa679f2001-06-25 02:11:07 +00002324 aMeta[0] = pP1->nFree;
2325 memcpy(&aMeta[1], pP1->aMeta, sizeof(pP1->aMeta));
drh8b2f49b2001-06-08 00:21:52 +00002326 sqlitepager_unref(pP1);
2327 return SQLITE_OK;
2328}
2329
2330/*
2331** Write meta-information back into the database.
2332*/
2333int sqliteBtreeUpdateMeta(Btree *pBt, int *aMeta){
2334 PageOne *pP1;
2335 int rc;
2336 if( !pBt->inTrans ){
2337 return SQLITE_ERROR; /* Must start a transaction first */
2338 }
2339 pP1 = pBt->page1;
2340 rc = sqlitepager_write(pP1);
drh2aa679f2001-06-25 02:11:07 +00002341 if( rc ) return rc;
2342 memcpy(pP1->aMeta, &aMeta[1], sizeof(pP1->aMeta));
drh8b2f49b2001-06-08 00:21:52 +00002343 return SQLITE_OK;
2344}
drh8c42ca92001-06-22 19:15:00 +00002345
drh5eddca62001-06-30 21:53:53 +00002346/******************************************************************************
2347** The complete implementation of the BTree subsystem is above this line.
2348** All the code the follows is for testing and troubleshooting the BTree
2349** subsystem. None of the code that follows is used during normal operation.
2350** All of the following code is omitted unless the library is compiled with
2351** the -DSQLITE_TEST=1 compiler option.
2352******************************************************************************/
drh5edc3122001-09-13 21:53:09 +00002353#if 1
drh5eddca62001-06-30 21:53:53 +00002354
drh8c42ca92001-06-22 19:15:00 +00002355/*
2356** Print a disassembly of the given page on standard output. This routine
2357** is used for debugging and testing only.
2358*/
drh6019e162001-07-02 17:51:45 +00002359int sqliteBtreePageDump(Btree *pBt, int pgno, int recursive){
drh8c42ca92001-06-22 19:15:00 +00002360 int rc;
2361 MemPage *pPage;
2362 int i, j;
2363 int nFree;
2364 u16 idx;
2365 char range[20];
2366 unsigned char payload[20];
2367 rc = sqlitepager_get(pBt->pPager, (Pgno)pgno, (void**)&pPage);
2368 if( rc ){
2369 return rc;
2370 }
drh6019e162001-07-02 17:51:45 +00002371 if( recursive ) printf("PAGE %d:\n", pgno);
drh8c42ca92001-06-22 19:15:00 +00002372 i = 0;
2373 idx = pPage->u.hdr.firstCell;
2374 while( idx>0 && idx<=SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2375 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
2376 int sz = cellSize(pCell);
2377 sprintf(range,"%d..%d", idx, idx+sz-1);
drh80ff32f2001-11-04 18:32:46 +00002378 sz = NKEY(pCell->h) + NDATA(pCell->h);
drh8c42ca92001-06-22 19:15:00 +00002379 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
2380 memcpy(payload, pCell->aPayload, sz);
2381 for(j=0; j<sz; j++){
2382 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
2383 }
2384 payload[sz] = 0;
2385 printf(
drh6019e162001-07-02 17:51:45 +00002386 "cell %2d: i=%-10s chld=%-4d nk=%-4d nd=%-4d payload=%s\n",
drh80ff32f2001-11-04 18:32:46 +00002387 i, range, (int)pCell->h.leftChild, NKEY(pCell->h), NDATA(pCell->h),
drh2aa679f2001-06-25 02:11:07 +00002388 payload
drh8c42ca92001-06-22 19:15:00 +00002389 );
drh6019e162001-07-02 17:51:45 +00002390 if( pPage->isInit && pPage->apCell[i]!=pCell ){
drh2aa679f2001-06-25 02:11:07 +00002391 printf("**** apCell[%d] does not match on prior entry ****\n", i);
2392 }
drh7c717f72001-06-24 20:39:41 +00002393 i++;
drh8c42ca92001-06-22 19:15:00 +00002394 idx = pCell->h.iNext;
2395 }
2396 if( idx!=0 ){
2397 printf("ERROR: next cell index out of range: %d\n", idx);
2398 }
2399 printf("right_child: %d\n", pPage->u.hdr.rightChild);
2400 nFree = 0;
2401 i = 0;
2402 idx = pPage->u.hdr.firstFree;
2403 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2404 FreeBlk *p = (FreeBlk*)&pPage->u.aDisk[idx];
2405 sprintf(range,"%d..%d", idx, idx+p->iSize-1);
2406 nFree += p->iSize;
2407 printf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
2408 i, range, p->iSize, nFree);
2409 idx = p->iNext;
drh2aa679f2001-06-25 02:11:07 +00002410 i++;
drh8c42ca92001-06-22 19:15:00 +00002411 }
2412 if( idx!=0 ){
2413 printf("ERROR: next freeblock index out of range: %d\n", idx);
2414 }
drh6019e162001-07-02 17:51:45 +00002415 if( recursive && pPage->u.hdr.rightChild!=0 ){
2416 idx = pPage->u.hdr.firstCell;
2417 while( idx>0 && idx<SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2418 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
2419 sqliteBtreePageDump(pBt, pCell->h.leftChild, 1);
2420 idx = pCell->h.iNext;
2421 }
2422 sqliteBtreePageDump(pBt, pPage->u.hdr.rightChild, 1);
2423 }
drh8c42ca92001-06-22 19:15:00 +00002424 sqlitepager_unref(pPage);
2425 return SQLITE_OK;
2426}
drh8c42ca92001-06-22 19:15:00 +00002427
drh8c42ca92001-06-22 19:15:00 +00002428/*
drh2aa679f2001-06-25 02:11:07 +00002429** Fill aResult[] with information about the entry and page that the
2430** cursor is pointing to.
2431**
2432** aResult[0] = The page number
2433** aResult[1] = The entry number
2434** aResult[2] = Total number of entries on this page
2435** aResult[3] = Size of this entry
2436** aResult[4] = Number of free bytes on this page
2437** aResult[5] = Number of free blocks on the page
2438** aResult[6] = Page number of the left child of this entry
2439** aResult[7] = Page number of the right child for the whole page
drh5eddca62001-06-30 21:53:53 +00002440**
2441** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00002442*/
2443int sqliteBtreeCursorDump(BtCursor *pCur, int *aResult){
drh2aa679f2001-06-25 02:11:07 +00002444 int cnt, idx;
2445 MemPage *pPage = pCur->pPage;
2446 aResult[0] = sqlitepager_pagenumber(pPage);
drh8c42ca92001-06-22 19:15:00 +00002447 aResult[1] = pCur->idx;
drh2aa679f2001-06-25 02:11:07 +00002448 aResult[2] = pPage->nCell;
2449 if( pCur->idx>=0 && pCur->idx<pPage->nCell ){
2450 aResult[3] = cellSize(pPage->apCell[pCur->idx]);
2451 aResult[6] = pPage->apCell[pCur->idx]->h.leftChild;
2452 }else{
2453 aResult[3] = 0;
2454 aResult[6] = 0;
2455 }
2456 aResult[4] = pPage->nFree;
2457 cnt = 0;
2458 idx = pPage->u.hdr.firstFree;
2459 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2460 cnt++;
2461 idx = ((FreeBlk*)&pPage->u.aDisk[idx])->iNext;
2462 }
2463 aResult[5] = cnt;
2464 aResult[7] = pPage->u.hdr.rightChild;
drh8c42ca92001-06-22 19:15:00 +00002465 return SQLITE_OK;
2466}
drhdd793422001-06-28 01:54:48 +00002467
drhdd793422001-06-28 01:54:48 +00002468/*
drh5eddca62001-06-30 21:53:53 +00002469** Return the pager associated with a BTree. This routine is used for
2470** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00002471*/
2472Pager *sqliteBtreePager(Btree *pBt){
2473 return pBt->pPager;
2474}
drh5eddca62001-06-30 21:53:53 +00002475
2476/*
2477** This structure is passed around through all the sanity checking routines
2478** in order to keep track of some global state information.
2479*/
2480typedef struct SanityCheck SanityCheck;
2481struct SanityCheck {
drh100569d2001-10-02 13:01:48 +00002482 Btree *pBt; /* The tree being checked out */
2483 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
2484 int nPage; /* Number of pages in the database */
2485 int *anRef; /* Number of times each page is referenced */
2486 int nTreePage; /* Number of BTree pages */
2487 int nByte; /* Number of bytes of data stored on BTree pages */
2488 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00002489};
2490
2491/*
2492** Append a message to the error message string.
2493*/
2494static void checkAppendMsg(SanityCheck *pCheck, char *zMsg1, char *zMsg2){
2495 if( pCheck->zErrMsg ){
2496 char *zOld = pCheck->zErrMsg;
2497 pCheck->zErrMsg = 0;
2498 sqliteSetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, 0);
2499 sqliteFree(zOld);
2500 }else{
2501 sqliteSetString(&pCheck->zErrMsg, zMsg1, zMsg2, 0);
2502 }
2503}
2504
2505/*
2506** Add 1 to the reference count for page iPage. If this is the second
2507** reference to the page, add an error message to pCheck->zErrMsg.
2508** Return 1 if there are 2 ore more references to the page and 0 if
2509** if this is the first reference to the page.
2510**
2511** Also check that the page number is in bounds.
2512*/
2513static int checkRef(SanityCheck *pCheck, int iPage, char *zContext){
2514 if( iPage==0 ) return 1;
2515 if( iPage>pCheck->nPage ){
2516 char zBuf[100];
2517 sprintf(zBuf, "invalid page number %d", iPage);
2518 checkAppendMsg(pCheck, zContext, zBuf);
2519 return 1;
2520 }
2521 if( pCheck->anRef[iPage]==1 ){
2522 char zBuf[100];
2523 sprintf(zBuf, "2nd reference to page %d", iPage);
2524 checkAppendMsg(pCheck, zContext, zBuf);
2525 return 1;
2526 }
2527 return (pCheck->anRef[iPage]++)>1;
2528}
2529
2530/*
2531** Check the integrity of the freelist or of an overflow page list.
2532** Verify that the number of pages on the list is N.
2533*/
2534static void checkList(SanityCheck *pCheck, int iPage, int N, char *zContext){
2535 char zMsg[100];
2536 while( N-- ){
2537 OverflowPage *pOvfl;
2538 if( iPage<1 ){
2539 sprintf(zMsg, "%d pages missing from overflow list", N+1);
2540 checkAppendMsg(pCheck, zContext, zMsg);
2541 break;
2542 }
2543 if( checkRef(pCheck, iPage, zContext) ) break;
2544 if( sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
2545 sprintf(zMsg, "failed to get page %d", iPage);
2546 checkAppendMsg(pCheck, zContext, zMsg);
2547 break;
2548 }
2549 iPage = (int)pOvfl->iNext;
2550 sqlitepager_unref(pOvfl);
2551 }
2552}
2553
2554/*
2555** Do various sanity checks on a single page of a tree. Return
2556** the tree depth. Root pages return 0. Parents of root pages
2557** return 1, and so forth.
2558**
2559** These checks are done:
2560**
2561** 1. Make sure that cells and freeblocks do not overlap
2562** but combine to completely cover the page.
2563** 2. Make sure cell keys are in order.
2564** 3. Make sure no key is less than or equal to zLowerBound.
2565** 4. Make sure no key is greater than or equal to zUpperBound.
2566** 5. Check the integrity of overflow pages.
2567** 6. Recursively call checkTreePage on all children.
2568** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00002569** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00002570** the root of the tree.
2571*/
2572static int checkTreePage(
2573 SanityCheck *pCheck, /* Context for the sanity check */
2574 int iPage, /* Page number of the page to check */
2575 MemPage *pParent, /* Parent page */
2576 char *zParentContext, /* Parent context */
2577 char *zLowerBound, /* All keys should be greater than this, if not NULL */
2578 char *zUpperBound /* All keys should be less than this, if not NULL */
2579){
2580 MemPage *pPage;
2581 int i, rc, depth, d2, pgno;
2582 char *zKey1, *zKey2;
2583 BtCursor cur;
2584 char zMsg[100];
2585 char zContext[100];
2586 char hit[SQLITE_PAGE_SIZE];
2587
2588 /* Check that the page exists
2589 */
2590 if( iPage==0 ) return 0;
2591 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
2592 sprintf(zContext, "On tree page %d: ", iPage);
2593 if( (rc = sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pPage))!=0 ){
2594 sprintf(zMsg, "unable to get the page. error code=%d", rc);
2595 checkAppendMsg(pCheck, zContext, zMsg);
2596 return 0;
2597 }
2598 if( (rc = initPage(pPage, (Pgno)iPage, pParent))!=0 ){
2599 sprintf(zMsg, "initPage() returns error code %d", rc);
2600 checkAppendMsg(pCheck, zContext, zMsg);
2601 sqlitepager_unref(pPage);
2602 return 0;
2603 }
2604
2605 /* Check out all the cells.
2606 */
2607 depth = 0;
2608 zKey1 = zLowerBound ? sqliteStrDup(zLowerBound) : 0;
2609 cur.pPage = pPage;
2610 cur.pBt = pCheck->pBt;
2611 for(i=0; i<pPage->nCell; i++){
2612 Cell *pCell = pPage->apCell[i];
2613 int sz;
2614
2615 /* Check payload overflow pages
2616 */
drh80ff32f2001-11-04 18:32:46 +00002617 sz = NKEY(pCell->h) + NDATA(pCell->h);
drh5eddca62001-06-30 21:53:53 +00002618 sprintf(zContext, "On page %d cell %d: ", iPage, i);
2619 if( sz>MX_LOCAL_PAYLOAD ){
2620 int nPage = (sz - MX_LOCAL_PAYLOAD + OVERFLOW_SIZE - 1)/OVERFLOW_SIZE;
2621 checkList(pCheck, pCell->ovfl, nPage, zContext);
2622 }
2623
2624 /* Check that keys are in the right order
2625 */
2626 cur.idx = i;
drh80ff32f2001-11-04 18:32:46 +00002627 zKey2 = sqliteMalloc( NKEY(pCell->h)+1 );
2628 getPayload(&cur, 0, NKEY(pCell->h), zKey2);
drh5eddca62001-06-30 21:53:53 +00002629 if( zKey1 && strcmp(zKey1,zKey2)>=0 ){
2630 checkAppendMsg(pCheck, zContext, "Key is out of order");
2631 }
2632
2633 /* Check sanity of left child page.
2634 */
2635 pgno = (int)pCell->h.leftChild;
2636 d2 = checkTreePage(pCheck, pgno, pPage, zContext, zKey1, zKey2);
2637 if( i>0 && d2!=depth ){
2638 checkAppendMsg(pCheck, zContext, "Child page depth differs");
2639 }
2640 depth = d2;
2641 sqliteFree(zKey1);
2642 zKey1 = zKey2;
2643 }
2644 pgno = pPage->u.hdr.rightChild;
2645 sprintf(zContext, "On page %d at right child: ", iPage);
2646 checkTreePage(pCheck, pgno, pPage, zContext, zKey1, zUpperBound);
2647 sqliteFree(zKey1);
2648
2649 /* Check for complete coverage of the page
2650 */
2651 memset(hit, 0, sizeof(hit));
2652 memset(hit, 1, sizeof(PageHdr));
2653 for(i=pPage->u.hdr.firstCell; i>0 && i<SQLITE_PAGE_SIZE; ){
2654 Cell *pCell = (Cell*)&pPage->u.aDisk[i];
2655 int j;
2656 for(j=i+cellSize(pCell)-1; j>=i; j--) hit[j]++;
2657 i = pCell->h.iNext;
2658 }
2659 for(i=pPage->u.hdr.firstFree; i>0 && i<SQLITE_PAGE_SIZE; ){
2660 FreeBlk *pFBlk = (FreeBlk*)&pPage->u.aDisk[i];
2661 int j;
2662 for(j=i+pFBlk->iSize-1; j>=i; j--) hit[j]++;
2663 i = pFBlk->iNext;
2664 }
2665 for(i=0; i<SQLITE_PAGE_SIZE; i++){
2666 if( hit[i]==0 ){
2667 sprintf(zMsg, "Unused space at byte %d of page %d", i, iPage);
2668 checkAppendMsg(pCheck, zMsg, 0);
2669 break;
2670 }else if( hit[i]>1 ){
2671 sprintf(zMsg, "Multiple uses for byte %d of page %d", i, iPage);
2672 checkAppendMsg(pCheck, zMsg, 0);
2673 break;
2674 }
2675 }
2676
2677 /* Check that free space is kept to a minimum
2678 */
drh6019e162001-07-02 17:51:45 +00002679#if 0
2680 if( pParent && pParent->nCell>2 && pPage->nFree>3*SQLITE_PAGE_SIZE/4 ){
drh5eddca62001-06-30 21:53:53 +00002681 sprintf(zMsg, "free space (%d) greater than max (%d)", pPage->nFree,
2682 SQLITE_PAGE_SIZE/3);
2683 checkAppendMsg(pCheck, zContext, zMsg);
2684 }
drh6019e162001-07-02 17:51:45 +00002685#endif
2686
2687 /* Update freespace totals.
2688 */
2689 pCheck->nTreePage++;
2690 pCheck->nByte += USABLE_SPACE - pPage->nFree;
drh5eddca62001-06-30 21:53:53 +00002691
2692 sqlitepager_unref(pPage);
2693 return depth;
2694}
2695
2696/*
2697** This routine does a complete check of the given BTree file. aRoot[] is
2698** an array of pages numbers were each page number is the root page of
2699** a table. nRoot is the number of entries in aRoot.
2700**
2701** If everything checks out, this routine returns NULL. If something is
2702** amiss, an error message is written into memory obtained from malloc()
2703** and a pointer to that error message is returned. The calling function
2704** is responsible for freeing the error message when it is done.
2705*/
2706char *sqliteBtreeSanityCheck(Btree *pBt, int *aRoot, int nRoot){
2707 int i;
2708 int nRef;
2709 SanityCheck sCheck;
2710
2711 nRef = *sqlitepager_stats(pBt->pPager);
drhefc251d2001-07-01 22:12:01 +00002712 if( lockBtree(pBt)!=SQLITE_OK ){
2713 return sqliteStrDup("Unable to acquire a read lock on the database");
2714 }
drh5eddca62001-06-30 21:53:53 +00002715 sCheck.pBt = pBt;
2716 sCheck.pPager = pBt->pPager;
2717 sCheck.nPage = sqlitepager_pagecount(sCheck.pPager);
2718 sCheck.anRef = sqliteMalloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
2719 sCheck.anRef[1] = 1;
2720 for(i=2; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
2721 sCheck.zErrMsg = 0;
2722
2723 /* Check the integrity of the freelist
2724 */
2725 checkList(&sCheck, pBt->page1->freeList, pBt->page1->nFree,"Main freelist: ");
2726
2727 /* Check all the tables.
2728 */
2729 for(i=0; i<nRoot; i++){
2730 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0, 0);
2731 }
2732
2733 /* Make sure every page in the file is referenced
2734 */
2735 for(i=1; i<=sCheck.nPage; i++){
2736 if( sCheck.anRef[i]==0 ){
2737 char zBuf[100];
2738 sprintf(zBuf, "Page %d is never used", i);
2739 checkAppendMsg(&sCheck, zBuf, 0);
2740 }
2741 }
2742
2743 /* Make sure this analysis did not leave any unref() pages
2744 */
drh5e00f6c2001-09-13 13:46:56 +00002745 unlockBtreeIfUnused(pBt);
drh5eddca62001-06-30 21:53:53 +00002746 if( nRef != *sqlitepager_stats(pBt->pPager) ){
2747 char zBuf[100];
2748 sprintf(zBuf,
2749 "Outstanding page count goes from %d to %d during this analysis",
2750 nRef, *sqlitepager_stats(pBt->pPager)
2751 );
2752 checkAppendMsg(&sCheck, zBuf, 0);
2753 }
2754
2755 /* Clean up and report errors.
2756 */
2757 sqliteFree(sCheck.anRef);
2758 return sCheck.zErrMsg;
2759}
2760
2761#endif /* SQLITE_TEST */