blob: 4f90df6d2e5e6752cdc4d483056a311384d54a51 [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*************************************************************************
drh8c87e6e2002-02-03 19:15:02 +000012** $Id: btree.c,v 1.52 2002/02/03 19:15:02 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
drh6446c4d2001-12-15 14:22:18 +0000254** the disk. The rest is auxiliary information held in memory only. The
drhbd03cae2001-06-02 02:40:57 +0000255** 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 */
drh663fc632002-02-02 18:49:19 +0000305 u8 inTrans; /* True if a transaction is in progress */
306 u8 inCkpt; /* True if there is a checkpoint on the transaction */
drhecdc7532001-09-23 02:35:53 +0000307 Hash locks; /* Key: root page number. Data: lock count */
drha059ad02001-04-17 20:09:11 +0000308};
309typedef Btree Bt;
310
drh365d68f2001-05-11 11:02:46 +0000311/*
312** A cursor is a pointer to a particular entry in the BTree.
313** The entry is identified by its MemPage and the index in
drh5e2f8b92001-05-28 00:41:15 +0000314** MemPage.apCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000315*/
drh72f82862001-05-24 21:06:34 +0000316struct BtCursor {
drh5e2f8b92001-05-28 00:41:15 +0000317 Btree *pBt; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000318 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drh8b2f49b2001-06-08 00:21:52 +0000319 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000320 MemPage *pPage; /* Page that contains the entry */
drh8c42ca92001-06-22 19:15:00 +0000321 int idx; /* Index of the entry in pPage->apCell[] */
drhecdc7532001-09-23 02:35:53 +0000322 u8 wrFlag; /* True if writable */
drh5e2f8b92001-05-28 00:41:15 +0000323 u8 bSkipNext; /* sqliteBtreeNext() is no-op if true */
324 u8 iMatch; /* compare result from last sqliteBtreeMoveto() */
drh365d68f2001-05-11 11:02:46 +0000325};
drh7e3b0a02001-04-28 16:52:40 +0000326
drha059ad02001-04-17 20:09:11 +0000327/*
drh3b7511c2001-05-26 13:15:44 +0000328** Compute the total number of bytes that a Cell needs on the main
drh5e2f8b92001-05-28 00:41:15 +0000329** database page. The number returned includes the Cell header,
330** local payload storage, and the pointer to overflow pages (if
drh8c42ca92001-06-22 19:15:00 +0000331** applicable). Additional space allocated on overflow pages
drhbd03cae2001-06-02 02:40:57 +0000332** is NOT included in the value returned from this routine.
drh3b7511c2001-05-26 13:15:44 +0000333*/
334static int cellSize(Cell *pCell){
drh80ff32f2001-11-04 18:32:46 +0000335 int n = NKEY(pCell->h) + NDATA(pCell->h);
drh3b7511c2001-05-26 13:15:44 +0000336 if( n>MX_LOCAL_PAYLOAD ){
337 n = MX_LOCAL_PAYLOAD + sizeof(Pgno);
338 }else{
339 n = ROUNDUP(n);
340 }
341 n += sizeof(CellHdr);
342 return n;
343}
344
345/*
drh72f82862001-05-24 21:06:34 +0000346** Defragment the page given. All Cells are moved to the
347** beginning of the page and all free space is collected
348** into one big FreeBlk at the end of the page.
drh365d68f2001-05-11 11:02:46 +0000349*/
350static void defragmentPage(MemPage *pPage){
drh14acc042001-06-10 19:56:58 +0000351 int pc, i, n;
drh2af926b2001-05-15 00:39:25 +0000352 FreeBlk *pFBlk;
353 char newPage[SQLITE_PAGE_SIZE];
354
drh6019e162001-07-02 17:51:45 +0000355 assert( sqlitepager_iswriteable(pPage) );
drhbd03cae2001-06-02 02:40:57 +0000356 pc = sizeof(PageHdr);
drh14acc042001-06-10 19:56:58 +0000357 pPage->u.hdr.firstCell = pc;
358 memcpy(newPage, pPage->u.aDisk, pc);
drh2af926b2001-05-15 00:39:25 +0000359 for(i=0; i<pPage->nCell; i++){
drh2aa679f2001-06-25 02:11:07 +0000360 Cell *pCell = pPage->apCell[i];
drh8c42ca92001-06-22 19:15:00 +0000361
362 /* This routine should never be called on an overfull page. The
363 ** following asserts verify that constraint. */
drh7c717f72001-06-24 20:39:41 +0000364 assert( Addr(pCell) > Addr(pPage) );
365 assert( Addr(pCell) < Addr(pPage) + SQLITE_PAGE_SIZE );
drh8c42ca92001-06-22 19:15:00 +0000366
drh3b7511c2001-05-26 13:15:44 +0000367 n = cellSize(pCell);
drh2aa679f2001-06-25 02:11:07 +0000368 pCell->h.iNext = pc + n;
drh2af926b2001-05-15 00:39:25 +0000369 memcpy(&newPage[pc], pCell, n);
drh14acc042001-06-10 19:56:58 +0000370 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[pc];
drh2af926b2001-05-15 00:39:25 +0000371 pc += n;
372 }
drh72f82862001-05-24 21:06:34 +0000373 assert( pPage->nFree==SQLITE_PAGE_SIZE-pc );
drh14acc042001-06-10 19:56:58 +0000374 memcpy(pPage->u.aDisk, newPage, pc);
drh2aa679f2001-06-25 02:11:07 +0000375 if( pPage->nCell>0 ){
376 pPage->apCell[pPage->nCell-1]->h.iNext = 0;
377 }
drh8c42ca92001-06-22 19:15:00 +0000378 pFBlk = (FreeBlk*)&pPage->u.aDisk[pc];
drh2af926b2001-05-15 00:39:25 +0000379 pFBlk->iSize = SQLITE_PAGE_SIZE - pc;
380 pFBlk->iNext = 0;
drh14acc042001-06-10 19:56:58 +0000381 pPage->u.hdr.firstFree = pc;
drh2af926b2001-05-15 00:39:25 +0000382 memset(&pFBlk[1], 0, SQLITE_PAGE_SIZE - pc - sizeof(FreeBlk));
drh365d68f2001-05-11 11:02:46 +0000383}
384
drha059ad02001-04-17 20:09:11 +0000385/*
drh8b2f49b2001-06-08 00:21:52 +0000386** Allocate nByte bytes of space on a page. nByte must be a
387** multiple of 4.
drhbd03cae2001-06-02 02:40:57 +0000388**
drh14acc042001-06-10 19:56:58 +0000389** Return the index into pPage->u.aDisk[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000390** the new allocation. Or return 0 if there is not enough free
391** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000392**
drh72f82862001-05-24 21:06:34 +0000393** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000394** nBytes of contiguous free space, then this routine automatically
395** calls defragementPage() to consolidate all free space before
396** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000397*/
drhbd03cae2001-06-02 02:40:57 +0000398static int allocateSpace(MemPage *pPage, int nByte){
drh2af926b2001-05-15 00:39:25 +0000399 FreeBlk *p;
400 u16 *pIdx;
401 int start;
drh8c42ca92001-06-22 19:15:00 +0000402 int cnt = 0;
drh72f82862001-05-24 21:06:34 +0000403
drh6019e162001-07-02 17:51:45 +0000404 assert( sqlitepager_iswriteable(pPage) );
drh5e2f8b92001-05-28 00:41:15 +0000405 assert( nByte==ROUNDUP(nByte) );
drh14acc042001-06-10 19:56:58 +0000406 if( pPage->nFree<nByte || pPage->isOverfull ) return 0;
407 pIdx = &pPage->u.hdr.firstFree;
408 p = (FreeBlk*)&pPage->u.aDisk[*pIdx];
drh2af926b2001-05-15 00:39:25 +0000409 while( p->iSize<nByte ){
drh8c42ca92001-06-22 19:15:00 +0000410 assert( cnt++ < SQLITE_PAGE_SIZE/4 );
drh2af926b2001-05-15 00:39:25 +0000411 if( p->iNext==0 ){
412 defragmentPage(pPage);
drh14acc042001-06-10 19:56:58 +0000413 pIdx = &pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000414 }else{
415 pIdx = &p->iNext;
416 }
drh14acc042001-06-10 19:56:58 +0000417 p = (FreeBlk*)&pPage->u.aDisk[*pIdx];
drh2af926b2001-05-15 00:39:25 +0000418 }
419 if( p->iSize==nByte ){
420 start = *pIdx;
421 *pIdx = p->iNext;
422 }else{
drh8c42ca92001-06-22 19:15:00 +0000423 FreeBlk *pNew;
drh72f82862001-05-24 21:06:34 +0000424 start = *pIdx;
drh8c42ca92001-06-22 19:15:00 +0000425 pNew = (FreeBlk*)&pPage->u.aDisk[start + nByte];
drh72f82862001-05-24 21:06:34 +0000426 pNew->iNext = p->iNext;
427 pNew->iSize = p->iSize - nByte;
428 *pIdx = start + nByte;
drh2af926b2001-05-15 00:39:25 +0000429 }
430 pPage->nFree -= nByte;
431 return start;
drh7e3b0a02001-04-28 16:52:40 +0000432}
433
434/*
drh14acc042001-06-10 19:56:58 +0000435** Return a section of the MemPage.u.aDisk[] to the freelist.
436** The first byte of the new free block is pPage->u.aDisk[start]
437** and the size of the block is "size" bytes. Size must be
438** a multiple of 4.
drh306dc212001-05-21 13:45:10 +0000439**
440** Most of the effort here is involved in coalesing adjacent
441** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000442*/
443static void freeSpace(MemPage *pPage, int start, int size){
drh2af926b2001-05-15 00:39:25 +0000444 int end = start + size;
445 u16 *pIdx, idx;
446 FreeBlk *pFBlk;
447 FreeBlk *pNew;
448 FreeBlk *pNext;
449
drh6019e162001-07-02 17:51:45 +0000450 assert( sqlitepager_iswriteable(pPage) );
drh2af926b2001-05-15 00:39:25 +0000451 assert( size == ROUNDUP(size) );
452 assert( start == ROUNDUP(start) );
drh14acc042001-06-10 19:56:58 +0000453 pIdx = &pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000454 idx = *pIdx;
455 while( idx!=0 && idx<start ){
drh14acc042001-06-10 19:56:58 +0000456 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh2af926b2001-05-15 00:39:25 +0000457 if( idx + pFBlk->iSize == start ){
458 pFBlk->iSize += size;
459 if( idx + pFBlk->iSize == pFBlk->iNext ){
drh8c42ca92001-06-22 19:15:00 +0000460 pNext = (FreeBlk*)&pPage->u.aDisk[pFBlk->iNext];
drh2af926b2001-05-15 00:39:25 +0000461 pFBlk->iSize += pNext->iSize;
462 pFBlk->iNext = pNext->iNext;
463 }
464 pPage->nFree += size;
465 return;
466 }
467 pIdx = &pFBlk->iNext;
468 idx = *pIdx;
469 }
drh14acc042001-06-10 19:56:58 +0000470 pNew = (FreeBlk*)&pPage->u.aDisk[start];
drh2af926b2001-05-15 00:39:25 +0000471 if( idx != end ){
472 pNew->iSize = size;
473 pNew->iNext = idx;
474 }else{
drh14acc042001-06-10 19:56:58 +0000475 pNext = (FreeBlk*)&pPage->u.aDisk[idx];
drh2af926b2001-05-15 00:39:25 +0000476 pNew->iSize = size + pNext->iSize;
477 pNew->iNext = pNext->iNext;
478 }
479 *pIdx = start;
480 pPage->nFree += size;
drh7e3b0a02001-04-28 16:52:40 +0000481}
482
483/*
484** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000485**
drhbd03cae2001-06-02 02:40:57 +0000486** The pParent parameter must be a pointer to the MemPage which
487** is the parent of the page being initialized. The root of the
drh8b2f49b2001-06-08 00:21:52 +0000488** BTree (usually page 2) has no parent and so for that page,
489** pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000490**
drh72f82862001-05-24 21:06:34 +0000491** Return SQLITE_OK on success. If we see that the page does
492** not contained a well-formed database page, then return
493** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
494** guarantee that the page is well-formed. It only shows that
495** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000496*/
drh72f82862001-05-24 21:06:34 +0000497static int initPage(MemPage *pPage, Pgno pgnoThis, MemPage *pParent){
drh14acc042001-06-10 19:56:58 +0000498 int idx; /* An index into pPage->u.aDisk[] */
499 Cell *pCell; /* A pointer to a Cell in pPage->u.aDisk[] */
500 FreeBlk *pFBlk; /* A pointer to a free block in pPage->u.aDisk[] */
drh5e2f8b92001-05-28 00:41:15 +0000501 int sz; /* The size of a Cell in bytes */
502 int freeSpace; /* Amount of free space on the page */
drh2af926b2001-05-15 00:39:25 +0000503
drh5e2f8b92001-05-28 00:41:15 +0000504 if( pPage->pParent ){
505 assert( pPage->pParent==pParent );
506 return SQLITE_OK;
507 }
508 if( pParent ){
509 pPage->pParent = pParent;
510 sqlitepager_ref(pParent);
511 }
512 if( pPage->isInit ) return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +0000513 pPage->isInit = 1;
drh7e3b0a02001-04-28 16:52:40 +0000514 pPage->nCell = 0;
drh6019e162001-07-02 17:51:45 +0000515 freeSpace = USABLE_SPACE;
drh14acc042001-06-10 19:56:58 +0000516 idx = pPage->u.hdr.firstCell;
drh7e3b0a02001-04-28 16:52:40 +0000517 while( idx!=0 ){
drh8c42ca92001-06-22 19:15:00 +0000518 if( idx>SQLITE_PAGE_SIZE-MIN_CELL_SIZE ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000519 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh8c42ca92001-06-22 19:15:00 +0000520 if( idx!=ROUNDUP(idx) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000521 pCell = (Cell*)&pPage->u.aDisk[idx];
drh5e2f8b92001-05-28 00:41:15 +0000522 sz = cellSize(pCell);
523 if( idx+sz > SQLITE_PAGE_SIZE ) goto page_format_error;
524 freeSpace -= sz;
525 pPage->apCell[pPage->nCell++] = pCell;
drh3b7511c2001-05-26 13:15:44 +0000526 idx = pCell->h.iNext;
drh2af926b2001-05-15 00:39:25 +0000527 }
528 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +0000529 idx = pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000530 while( idx!=0 ){
531 if( idx>SQLITE_PAGE_SIZE-sizeof(FreeBlk) ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000532 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000533 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh2af926b2001-05-15 00:39:25 +0000534 pPage->nFree += pFBlk->iSize;
drh7c717f72001-06-24 20:39:41 +0000535 if( pFBlk->iNext>0 && pFBlk->iNext <= idx ) goto page_format_error;
drh2af926b2001-05-15 00:39:25 +0000536 idx = pFBlk->iNext;
drh7e3b0a02001-04-28 16:52:40 +0000537 }
drh8b2f49b2001-06-08 00:21:52 +0000538 if( pPage->nCell==0 && pPage->nFree==0 ){
539 /* As a special case, an uninitialized root page appears to be
540 ** an empty database */
541 return SQLITE_OK;
542 }
drh5e2f8b92001-05-28 00:41:15 +0000543 if( pPage->nFree!=freeSpace ) goto page_format_error;
drh7e3b0a02001-04-28 16:52:40 +0000544 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +0000545
546page_format_error:
547 return SQLITE_CORRUPT;
drh7e3b0a02001-04-28 16:52:40 +0000548}
549
550/*
drh8b2f49b2001-06-08 00:21:52 +0000551** Set up a raw page so that it looks like a database page holding
552** no entries.
drhbd03cae2001-06-02 02:40:57 +0000553*/
554static void zeroPage(MemPage *pPage){
555 PageHdr *pHdr;
556 FreeBlk *pFBlk;
drh6019e162001-07-02 17:51:45 +0000557 assert( sqlitepager_iswriteable(pPage) );
drhbd03cae2001-06-02 02:40:57 +0000558 memset(pPage, 0, SQLITE_PAGE_SIZE);
drh14acc042001-06-10 19:56:58 +0000559 pHdr = &pPage->u.hdr;
drhbd03cae2001-06-02 02:40:57 +0000560 pHdr->firstCell = 0;
561 pHdr->firstFree = sizeof(*pHdr);
562 pFBlk = (FreeBlk*)&pHdr[1];
563 pFBlk->iNext = 0;
564 pFBlk->iSize = SQLITE_PAGE_SIZE - sizeof(*pHdr);
drh8c42ca92001-06-22 19:15:00 +0000565 pPage->nFree = pFBlk->iSize;
566 pPage->nCell = 0;
567 pPage->isOverfull = 0;
drhbd03cae2001-06-02 02:40:57 +0000568}
569
570/*
drh72f82862001-05-24 21:06:34 +0000571** This routine is called when the reference count for a page
572** reaches zero. We need to unref the pParent pointer when that
573** happens.
574*/
575static void pageDestructor(void *pData){
576 MemPage *pPage = (MemPage*)pData;
577 if( pPage->pParent ){
578 MemPage *pParent = pPage->pParent;
579 pPage->pParent = 0;
580 sqlitepager_unref(pParent);
581 }
582}
583
584/*
drh306dc212001-05-21 13:45:10 +0000585** Open a new database.
586**
587** Actually, this routine just sets up the internal data structures
drh72f82862001-05-24 21:06:34 +0000588** for accessing the database. We do not open the database file
589** until the first page is loaded.
drh382c0242001-10-06 16:33:02 +0000590**
591** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +0000592** a new database with a random name is created. This randomly named
593** database file will be deleted when sqliteBtreeClose() is called.
drha059ad02001-04-17 20:09:11 +0000594*/
drh6019e162001-07-02 17:51:45 +0000595int sqliteBtreeOpen(
596 const char *zFilename, /* Name of the file containing the BTree database */
597 int mode, /* Not currently used */
598 int nCache, /* How many pages in the page cache */
599 Btree **ppBtree /* Pointer to new Btree object written here */
600){
drha059ad02001-04-17 20:09:11 +0000601 Btree *pBt;
drh8c42ca92001-06-22 19:15:00 +0000602 int rc;
drha059ad02001-04-17 20:09:11 +0000603
604 pBt = sqliteMalloc( sizeof(*pBt) );
605 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +0000606 *ppBtree = 0;
drha059ad02001-04-17 20:09:11 +0000607 return SQLITE_NOMEM;
608 }
drh6019e162001-07-02 17:51:45 +0000609 if( nCache<10 ) nCache = 10;
610 rc = sqlitepager_open(&pBt->pPager, zFilename, nCache, EXTRA_SIZE);
drha059ad02001-04-17 20:09:11 +0000611 if( rc!=SQLITE_OK ){
612 if( pBt->pPager ) sqlitepager_close(pBt->pPager);
613 sqliteFree(pBt);
614 *ppBtree = 0;
615 return rc;
616 }
drh72f82862001-05-24 21:06:34 +0000617 sqlitepager_set_destructor(pBt->pPager, pageDestructor);
drha059ad02001-04-17 20:09:11 +0000618 pBt->pCursor = 0;
619 pBt->page1 = 0;
drhecdc7532001-09-23 02:35:53 +0000620 sqliteHashInit(&pBt->locks, SQLITE_HASH_INT, 0);
drha059ad02001-04-17 20:09:11 +0000621 *ppBtree = pBt;
622 return SQLITE_OK;
623}
624
625/*
626** Close an open database and invalidate all cursors.
627*/
628int sqliteBtreeClose(Btree *pBt){
629 while( pBt->pCursor ){
630 sqliteBtreeCloseCursor(pBt->pCursor);
631 }
632 sqlitepager_close(pBt->pPager);
drhecdc7532001-09-23 02:35:53 +0000633 sqliteHashClear(&pBt->locks);
drha059ad02001-04-17 20:09:11 +0000634 sqliteFree(pBt);
635 return SQLITE_OK;
636}
637
638/*
drh6446c4d2001-12-15 14:22:18 +0000639** Change the limit on the number of pages allowed the cache.
drhf57b14a2001-09-14 18:54:08 +0000640*/
641int sqliteBtreeSetCacheSize(Btree *pBt, int mxPage){
642 sqlitepager_set_cachesize(pBt->pPager, mxPage);
643 return SQLITE_OK;
644}
645
646/*
drh306dc212001-05-21 13:45:10 +0000647** Get a reference to page1 of the database file. This will
648** also acquire a readlock on that file.
649**
650** SQLITE_OK is returned on success. If the file is not a
651** well-formed database file, then SQLITE_CORRUPT is returned.
652** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
653** is returned if we run out of memory. SQLITE_PROTOCOL is returned
654** if there is a locking protocol violation.
655*/
656static int lockBtree(Btree *pBt){
657 int rc;
658 if( pBt->page1 ) return SQLITE_OK;
drh8c42ca92001-06-22 19:15:00 +0000659 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pBt->page1);
drh306dc212001-05-21 13:45:10 +0000660 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +0000661
662 /* Do some checking to help insure the file we opened really is
663 ** a valid database file.
664 */
665 if( sqlitepager_pagecount(pBt->pPager)>0 ){
drhbd03cae2001-06-02 02:40:57 +0000666 PageOne *pP1 = pBt->page1;
drh8c42ca92001-06-22 19:15:00 +0000667 if( strcmp(pP1->zMagic,zMagicHeader)!=0 || pP1->iMagic!=MAGIC ){
drh306dc212001-05-21 13:45:10 +0000668 rc = SQLITE_CORRUPT;
drh72f82862001-05-24 21:06:34 +0000669 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +0000670 }
671 }
672 return rc;
673
drh72f82862001-05-24 21:06:34 +0000674page1_init_failed:
drh306dc212001-05-21 13:45:10 +0000675 sqlitepager_unref(pBt->page1);
676 pBt->page1 = 0;
drh72f82862001-05-24 21:06:34 +0000677 return rc;
drh306dc212001-05-21 13:45:10 +0000678}
679
680/*
drhb8ca3072001-12-05 00:21:20 +0000681** If there are no outstanding cursors and we are not in the middle
682** of a transaction but there is a read lock on the database, then
683** this routine unrefs the first page of the database file which
684** has the effect of releasing the read lock.
685**
686** If there are any outstanding cursors, this routine is a no-op.
687**
688** If there is a transaction in progress, this routine is a no-op.
689*/
690static void unlockBtreeIfUnused(Btree *pBt){
691 if( pBt->inTrans==0 && pBt->pCursor==0 && pBt->page1!=0 ){
692 sqlitepager_unref(pBt->page1);
693 pBt->page1 = 0;
694 pBt->inTrans = 0;
drh663fc632002-02-02 18:49:19 +0000695 pBt->inCkpt = 0;
drhb8ca3072001-12-05 00:21:20 +0000696 }
697}
698
699/*
drh8c42ca92001-06-22 19:15:00 +0000700** Create a new database by initializing the first two pages of the
701** file.
drh8b2f49b2001-06-08 00:21:52 +0000702*/
703static int newDatabase(Btree *pBt){
704 MemPage *pRoot;
705 PageOne *pP1;
drh8c42ca92001-06-22 19:15:00 +0000706 int rc;
drh7c717f72001-06-24 20:39:41 +0000707 if( sqlitepager_pagecount(pBt->pPager)>1 ) return SQLITE_OK;
drh8b2f49b2001-06-08 00:21:52 +0000708 pP1 = pBt->page1;
709 rc = sqlitepager_write(pBt->page1);
710 if( rc ) return rc;
drh8c42ca92001-06-22 19:15:00 +0000711 rc = sqlitepager_get(pBt->pPager, 2, (void**)&pRoot);
drh8b2f49b2001-06-08 00:21:52 +0000712 if( rc ) return rc;
713 rc = sqlitepager_write(pRoot);
714 if( rc ){
715 sqlitepager_unref(pRoot);
716 return rc;
717 }
718 strcpy(pP1->zMagic, zMagicHeader);
drh8c42ca92001-06-22 19:15:00 +0000719 pP1->iMagic = MAGIC;
drh8b2f49b2001-06-08 00:21:52 +0000720 zeroPage(pRoot);
721 sqlitepager_unref(pRoot);
722 return SQLITE_OK;
723}
724
725/*
drh72f82862001-05-24 21:06:34 +0000726** Attempt to start a new transaction.
drh8b2f49b2001-06-08 00:21:52 +0000727**
728** A transaction must be started before attempting any changes
729** to the database. None of the following routines will work
730** unless a transaction is started first:
731**
732** sqliteBtreeCreateTable()
drhc6b52df2002-01-04 03:09:29 +0000733** sqliteBtreeCreateIndex()
drh8b2f49b2001-06-08 00:21:52 +0000734** sqliteBtreeClearTable()
735** sqliteBtreeDropTable()
736** sqliteBtreeInsert()
737** sqliteBtreeDelete()
738** sqliteBtreeUpdateMeta()
drha059ad02001-04-17 20:09:11 +0000739*/
740int sqliteBtreeBeginTrans(Btree *pBt){
741 int rc;
742 if( pBt->inTrans ) return SQLITE_ERROR;
743 if( pBt->page1==0 ){
drh7e3b0a02001-04-28 16:52:40 +0000744 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +0000745 if( rc!=SQLITE_OK ){
746 return rc;
747 }
drha059ad02001-04-17 20:09:11 +0000748 }
drhb8ca3072001-12-05 00:21:20 +0000749 if( sqlitepager_isreadonly(pBt->pPager) ){
750 return SQLITE_READONLY;
751 }
752 rc = sqlitepager_write(pBt->page1);
753 if( rc==SQLITE_OK ){
drh5e00f6c2001-09-13 13:46:56 +0000754 rc = newDatabase(pBt);
drha059ad02001-04-17 20:09:11 +0000755 }
drhb8ca3072001-12-05 00:21:20 +0000756 if( rc==SQLITE_OK ){
757 pBt->inTrans = 1;
drh663fc632002-02-02 18:49:19 +0000758 pBt->inCkpt = 0;
drhb8ca3072001-12-05 00:21:20 +0000759 }else{
760 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000761 }
drhb8ca3072001-12-05 00:21:20 +0000762 return rc;
drha059ad02001-04-17 20:09:11 +0000763}
764
765/*
drh2aa679f2001-06-25 02:11:07 +0000766** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +0000767**
768** This will release the write lock on the database file. If there
769** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000770*/
771int sqliteBtreeCommit(Btree *pBt){
772 int rc;
drh2aa679f2001-06-25 02:11:07 +0000773 if( pBt->inTrans==0 ) return SQLITE_ERROR;
drha059ad02001-04-17 20:09:11 +0000774 rc = sqlitepager_commit(pBt->pPager);
drh7c717f72001-06-24 20:39:41 +0000775 pBt->inTrans = 0;
drh663fc632002-02-02 18:49:19 +0000776 pBt->inCkpt = 0;
drh5e00f6c2001-09-13 13:46:56 +0000777 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000778 return rc;
779}
780
781/*
drhecdc7532001-09-23 02:35:53 +0000782** Rollback the transaction in progress. All cursors will be
783** invalided by this operation. Any attempt to use a cursor
784** that was open at the beginning of this operation will result
785** in an error.
drh5e00f6c2001-09-13 13:46:56 +0000786**
787** This will release the write lock on the database file. If there
788** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000789*/
790int sqliteBtreeRollback(Btree *pBt){
791 int rc;
drhecdc7532001-09-23 02:35:53 +0000792 BtCursor *pCur;
drh7c717f72001-06-24 20:39:41 +0000793 if( pBt->inTrans==0 ) return SQLITE_OK;
794 pBt->inTrans = 0;
drh663fc632002-02-02 18:49:19 +0000795 pBt->inCkpt = 0;
drhecdc7532001-09-23 02:35:53 +0000796 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
797 if( pCur->pPage ){
798 sqlitepager_unref(pCur->pPage);
799 pCur->pPage = 0;
800 }
801 }
drha059ad02001-04-17 20:09:11 +0000802 rc = sqlitepager_rollback(pBt->pPager);
drh5e00f6c2001-09-13 13:46:56 +0000803 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000804 return rc;
805}
806
807/*
drh663fc632002-02-02 18:49:19 +0000808** Set the checkpoint for the current transaction. The checkpoint serves
809** as a sub-transaction that can be rolled back independently of the
810** main transaction. You must start a transaction before starting a
811** checkpoint. The checkpoint is ended automatically if the transaction
812** commits or rolls back.
813**
814** Only one checkpoint may be active at a time. It is an error to try
815** to start a new checkpoint if another checkpoint is already active.
816*/
817int sqliteBtreeBeginCkpt(Btree *pBt){
818 int rc;
drh0d65dc02002-02-03 00:56:09 +0000819 if( !pBt->inTrans || pBt->inCkpt ){
820 return SQLITE_ERROR;
821 }
drh663fc632002-02-02 18:49:19 +0000822 rc = sqlitepager_ckpt_begin(pBt->pPager);
823 pBt->inCkpt = 1;
824 return rc;
825}
826
827
828/*
829** Commit a checkpoint to transaction currently in progress. If no
830** checkpoint is active, this is a no-op.
831*/
832int sqliteBtreeCommitCkpt(Btree *pBt){
833 int rc;
834 if( pBt->inCkpt ){
835 rc = sqlitepager_ckpt_commit(pBt->pPager);
836 }else{
837 rc = SQLITE_OK;
838 }
drh0d65dc02002-02-03 00:56:09 +0000839 pBt->inCkpt = 0;
drh663fc632002-02-02 18:49:19 +0000840 return rc;
841}
842
843/*
844** Rollback the checkpoint to the current transaction. If there
845** is no active checkpoint or transaction, this routine is a no-op.
846**
847** All cursors will be invalided by this operation. Any attempt
848** to use a cursor that was open at the beginning of this operation
849** will result in an error.
850*/
851int sqliteBtreeRollbackCkpt(Btree *pBt){
852 int rc;
853 BtCursor *pCur;
854 if( pBt->inCkpt==0 ) return SQLITE_OK;
855 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
856 if( pCur->pPage ){
857 sqlitepager_unref(pCur->pPage);
858 pCur->pPage = 0;
859 }
860 }
861 rc = sqlitepager_ckpt_rollback(pBt->pPager);
drh0d65dc02002-02-03 00:56:09 +0000862 pBt->inCkpt = 0;
drh663fc632002-02-02 18:49:19 +0000863 return rc;
864}
865
866/*
drh8b2f49b2001-06-08 00:21:52 +0000867** Create a new cursor for the BTree whose root is on the page
868** iTable. The act of acquiring a cursor gets a read lock on
869** the database file.
drh1bee3d72001-10-15 00:44:35 +0000870**
871** If wrFlag==0, then the cursor can only be used for reading.
872** If wrFlag==1, then the cursor can be used for reading or writing.
873** A read/write cursor requires exclusive access to its table. There
drh6446c4d2001-12-15 14:22:18 +0000874** cannot be two or more cursors open on the same table if any one of
drh1bee3d72001-10-15 00:44:35 +0000875** cursors is a read/write cursor. But there can be two or more
876** read-only cursors open on the same table.
drh6446c4d2001-12-15 14:22:18 +0000877**
878** No checking is done to make sure that page iTable really is the
879** root page of a b-tree. If it is not, then the cursor acquired
880** will not work correctly.
drha059ad02001-04-17 20:09:11 +0000881*/
drhecdc7532001-09-23 02:35:53 +0000882int sqliteBtreeCursor(Btree *pBt, int iTable, int wrFlag, BtCursor **ppCur){
drha059ad02001-04-17 20:09:11 +0000883 int rc;
884 BtCursor *pCur;
drh5a2c2c22001-11-21 02:21:11 +0000885 ptr nLock;
drhecdc7532001-09-23 02:35:53 +0000886
drha059ad02001-04-17 20:09:11 +0000887 if( pBt->page1==0 ){
888 rc = lockBtree(pBt);
889 if( rc!=SQLITE_OK ){
890 *ppCur = 0;
891 return rc;
892 }
893 }
894 pCur = sqliteMalloc( sizeof(*pCur) );
895 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +0000896 rc = SQLITE_NOMEM;
897 goto create_cursor_exception;
898 }
drh8b2f49b2001-06-08 00:21:52 +0000899 pCur->pgnoRoot = (Pgno)iTable;
drh8c42ca92001-06-22 19:15:00 +0000900 rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +0000901 if( rc!=SQLITE_OK ){
902 goto create_cursor_exception;
903 }
drh8b2f49b2001-06-08 00:21:52 +0000904 rc = initPage(pCur->pPage, pCur->pgnoRoot, 0);
drhbd03cae2001-06-02 02:40:57 +0000905 if( rc!=SQLITE_OK ){
906 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +0000907 }
drh5a2c2c22001-11-21 02:21:11 +0000908 nLock = (ptr)sqliteHashFind(&pBt->locks, 0, iTable);
drhecdc7532001-09-23 02:35:53 +0000909 if( nLock<0 || (nLock>0 && wrFlag) ){
910 rc = SQLITE_LOCKED;
911 goto create_cursor_exception;
912 }
913 nLock = wrFlag ? -1 : nLock+1;
914 sqliteHashInsert(&pBt->locks, 0, iTable, (void*)nLock);
drh14acc042001-06-10 19:56:58 +0000915 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +0000916 pCur->wrFlag = wrFlag;
drh14acc042001-06-10 19:56:58 +0000917 pCur->idx = 0;
drha059ad02001-04-17 20:09:11 +0000918 pCur->pNext = pBt->pCursor;
919 if( pCur->pNext ){
920 pCur->pNext->pPrev = pCur;
921 }
drh14acc042001-06-10 19:56:58 +0000922 pCur->pPrev = 0;
drha059ad02001-04-17 20:09:11 +0000923 pBt->pCursor = pCur;
drh2af926b2001-05-15 00:39:25 +0000924 *ppCur = pCur;
925 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +0000926
927create_cursor_exception:
928 *ppCur = 0;
929 if( pCur ){
930 if( pCur->pPage ) sqlitepager_unref(pCur->pPage);
931 sqliteFree(pCur);
932 }
drh5e00f6c2001-09-13 13:46:56 +0000933 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +0000934 return rc;
drha059ad02001-04-17 20:09:11 +0000935}
936
937/*
drh5e00f6c2001-09-13 13:46:56 +0000938** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +0000939** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +0000940*/
941int sqliteBtreeCloseCursor(BtCursor *pCur){
drh5a2c2c22001-11-21 02:21:11 +0000942 ptr nLock;
drha059ad02001-04-17 20:09:11 +0000943 Btree *pBt = pCur->pBt;
drha059ad02001-04-17 20:09:11 +0000944 if( pCur->pPrev ){
945 pCur->pPrev->pNext = pCur->pNext;
946 }else{
947 pBt->pCursor = pCur->pNext;
948 }
949 if( pCur->pNext ){
950 pCur->pNext->pPrev = pCur->pPrev;
951 }
drhecdc7532001-09-23 02:35:53 +0000952 if( pCur->pPage ){
953 sqlitepager_unref(pCur->pPage);
954 }
drh5e00f6c2001-09-13 13:46:56 +0000955 unlockBtreeIfUnused(pBt);
drh5a2c2c22001-11-21 02:21:11 +0000956 nLock = (ptr)sqliteHashFind(&pBt->locks, 0, pCur->pgnoRoot);
drh6d4abfb2001-10-22 02:58:08 +0000957 assert( nLock!=0 || sqlite_malloc_failed );
drhecdc7532001-09-23 02:35:53 +0000958 nLock = nLock<0 ? 0 : nLock-1;
959 sqliteHashInsert(&pBt->locks, 0, pCur->pgnoRoot, (void*)nLock);
drha059ad02001-04-17 20:09:11 +0000960 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +0000961 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +0000962}
963
drh7e3b0a02001-04-28 16:52:40 +0000964/*
drh5e2f8b92001-05-28 00:41:15 +0000965** Make a temporary cursor by filling in the fields of pTempCur.
966** The temporary cursor is not on the cursor list for the Btree.
967*/
drh14acc042001-06-10 19:56:58 +0000968static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +0000969 memcpy(pTempCur, pCur, sizeof(*pCur));
970 pTempCur->pNext = 0;
971 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +0000972 if( pTempCur->pPage ){
973 sqlitepager_ref(pTempCur->pPage);
974 }
drh5e2f8b92001-05-28 00:41:15 +0000975}
976
977/*
drhbd03cae2001-06-02 02:40:57 +0000978** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +0000979** function above.
980*/
drh14acc042001-06-10 19:56:58 +0000981static void releaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +0000982 if( pCur->pPage ){
983 sqlitepager_unref(pCur->pPage);
984 }
drh5e2f8b92001-05-28 00:41:15 +0000985}
986
987/*
drhbd03cae2001-06-02 02:40:57 +0000988** Set *pSize to the number of bytes of key in the entry the
989** cursor currently points to. Always return SQLITE_OK.
990** Failure is not possible. If the cursor is not currently
991** pointing to an entry (which can happen, for example, if
992** the database is empty) then *pSize is set to 0.
drh7e3b0a02001-04-28 16:52:40 +0000993*/
drh72f82862001-05-24 21:06:34 +0000994int sqliteBtreeKeySize(BtCursor *pCur, int *pSize){
drh2af926b2001-05-15 00:39:25 +0000995 Cell *pCell;
996 MemPage *pPage;
997
998 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +0000999 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh72f82862001-05-24 21:06:34 +00001000 *pSize = 0;
1001 }else{
drh5e2f8b92001-05-28 00:41:15 +00001002 pCell = pPage->apCell[pCur->idx];
drh80ff32f2001-11-04 18:32:46 +00001003 *pSize = NKEY(pCell->h);
drh72f82862001-05-24 21:06:34 +00001004 }
1005 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00001006}
drh2af926b2001-05-15 00:39:25 +00001007
drh72f82862001-05-24 21:06:34 +00001008/*
1009** Read payload information from the entry that the pCur cursor is
1010** pointing to. Begin reading the payload at "offset" and read
1011** a total of "amt" bytes. Put the result in zBuf.
1012**
1013** This routine does not make a distinction between key and data.
1014** It just reads bytes from the payload area.
1015*/
drh2af926b2001-05-15 00:39:25 +00001016static int getPayload(BtCursor *pCur, int offset, int amt, char *zBuf){
drh5e2f8b92001-05-28 00:41:15 +00001017 char *aPayload;
drh2af926b2001-05-15 00:39:25 +00001018 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +00001019 int rc;
drh72f82862001-05-24 21:06:34 +00001020 assert( pCur!=0 && pCur->pPage!=0 );
drh8c42ca92001-06-22 19:15:00 +00001021 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
1022 aPayload = pCur->pPage->apCell[pCur->idx]->aPayload;
drh2af926b2001-05-15 00:39:25 +00001023 if( offset<MX_LOCAL_PAYLOAD ){
1024 int a = amt;
1025 if( a+offset>MX_LOCAL_PAYLOAD ){
1026 a = MX_LOCAL_PAYLOAD - offset;
1027 }
drh5e2f8b92001-05-28 00:41:15 +00001028 memcpy(zBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +00001029 if( a==amt ){
1030 return SQLITE_OK;
1031 }
drh2aa679f2001-06-25 02:11:07 +00001032 offset = 0;
drh2af926b2001-05-15 00:39:25 +00001033 zBuf += a;
1034 amt -= a;
drhdd793422001-06-28 01:54:48 +00001035 }else{
1036 offset -= MX_LOCAL_PAYLOAD;
drhbd03cae2001-06-02 02:40:57 +00001037 }
1038 if( amt>0 ){
drh8c42ca92001-06-22 19:15:00 +00001039 nextPage = pCur->pPage->apCell[pCur->idx]->ovfl;
drh2af926b2001-05-15 00:39:25 +00001040 }
1041 while( amt>0 && nextPage ){
1042 OverflowPage *pOvfl;
drh8c42ca92001-06-22 19:15:00 +00001043 rc = sqlitepager_get(pCur->pBt->pPager, nextPage, (void**)&pOvfl);
drh2af926b2001-05-15 00:39:25 +00001044 if( rc!=0 ){
1045 return rc;
1046 }
drh14acc042001-06-10 19:56:58 +00001047 nextPage = pOvfl->iNext;
drh2af926b2001-05-15 00:39:25 +00001048 if( offset<OVERFLOW_SIZE ){
1049 int a = amt;
1050 if( a + offset > OVERFLOW_SIZE ){
1051 a = OVERFLOW_SIZE - offset;
1052 }
drh5e2f8b92001-05-28 00:41:15 +00001053 memcpy(zBuf, &pOvfl->aPayload[offset], a);
drh2aa679f2001-06-25 02:11:07 +00001054 offset = 0;
drh2af926b2001-05-15 00:39:25 +00001055 amt -= a;
1056 zBuf += a;
drh2aa679f2001-06-25 02:11:07 +00001057 }else{
1058 offset -= OVERFLOW_SIZE;
drh2af926b2001-05-15 00:39:25 +00001059 }
1060 sqlitepager_unref(pOvfl);
1061 }
drha7fcb052001-12-14 15:09:55 +00001062 if( amt>0 ){
1063 return SQLITE_CORRUPT;
1064 }
1065 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +00001066}
1067
drh72f82862001-05-24 21:06:34 +00001068/*
drh5e00f6c2001-09-13 13:46:56 +00001069** Read part of the key associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +00001070** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +00001071** begins at "offset". The number of bytes actually read is
1072** returned. The amount returned will be smaller than the
1073** amount requested if there are not enough bytes in the key
1074** to satisfy the request.
drh72f82862001-05-24 21:06:34 +00001075*/
1076int sqliteBtreeKey(BtCursor *pCur, int offset, int amt, char *zBuf){
1077 Cell *pCell;
1078 MemPage *pPage;
drha059ad02001-04-17 20:09:11 +00001079
drh5e00f6c2001-09-13 13:46:56 +00001080 if( amt<0 ) return 0;
1081 if( offset<0 ) return 0;
1082 if( amt==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001083 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001084 if( pPage==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001085 if( pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +00001086 return 0;
drh72f82862001-05-24 21:06:34 +00001087 }
drh5e2f8b92001-05-28 00:41:15 +00001088 pCell = pPage->apCell[pCur->idx];
drh80ff32f2001-11-04 18:32:46 +00001089 if( amt+offset > NKEY(pCell->h) ){
1090 amt = NKEY(pCell->h) - offset;
drh5e00f6c2001-09-13 13:46:56 +00001091 if( amt<=0 ){
1092 return 0;
1093 }
drhbd03cae2001-06-02 02:40:57 +00001094 }
drh5e00f6c2001-09-13 13:46:56 +00001095 getPayload(pCur, offset, amt, zBuf);
1096 return amt;
drh72f82862001-05-24 21:06:34 +00001097}
1098
1099/*
drhbd03cae2001-06-02 02:40:57 +00001100** Set *pSize to the number of bytes of data in the entry the
1101** cursor currently points to. Always return SQLITE_OK.
1102** Failure is not possible. If the cursor is not currently
1103** pointing to an entry (which can happen, for example, if
1104** the database is empty) then *pSize is set to 0.
drh72f82862001-05-24 21:06:34 +00001105*/
1106int sqliteBtreeDataSize(BtCursor *pCur, int *pSize){
1107 Cell *pCell;
1108 MemPage *pPage;
1109
1110 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001111 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh72f82862001-05-24 21:06:34 +00001112 *pSize = 0;
1113 }else{
drh5e2f8b92001-05-28 00:41:15 +00001114 pCell = pPage->apCell[pCur->idx];
drh80ff32f2001-11-04 18:32:46 +00001115 *pSize = NDATA(pCell->h);
drh72f82862001-05-24 21:06:34 +00001116 }
1117 return SQLITE_OK;
1118}
1119
1120/*
drh5e00f6c2001-09-13 13:46:56 +00001121** Read part of the data associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +00001122** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +00001123** begins at "offset". The number of bytes actually read is
1124** returned. The amount returned will be smaller than the
1125** amount requested if there are not enough bytes in the data
1126** to satisfy the request.
drh72f82862001-05-24 21:06:34 +00001127*/
1128int sqliteBtreeData(BtCursor *pCur, int offset, int amt, char *zBuf){
1129 Cell *pCell;
1130 MemPage *pPage;
1131
drh5e00f6c2001-09-13 13:46:56 +00001132 if( amt<0 ) return 0;
1133 if( offset<0 ) return 0;
1134 if( amt==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001135 pPage = pCur->pPage;
drhecdc7532001-09-23 02:35:53 +00001136 if( pPage==0 || pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +00001137 return 0;
drh72f82862001-05-24 21:06:34 +00001138 }
drh5e2f8b92001-05-28 00:41:15 +00001139 pCell = pPage->apCell[pCur->idx];
drh80ff32f2001-11-04 18:32:46 +00001140 if( amt+offset > NDATA(pCell->h) ){
1141 amt = NDATA(pCell->h) - offset;
drh5e00f6c2001-09-13 13:46:56 +00001142 if( amt<=0 ){
1143 return 0;
1144 }
drhbd03cae2001-06-02 02:40:57 +00001145 }
drh80ff32f2001-11-04 18:32:46 +00001146 getPayload(pCur, offset + NKEY(pCell->h), amt, zBuf);
drh5e00f6c2001-09-13 13:46:56 +00001147 return amt;
drh72f82862001-05-24 21:06:34 +00001148}
drha059ad02001-04-17 20:09:11 +00001149
drh2af926b2001-05-15 00:39:25 +00001150/*
drh8721ce42001-11-07 14:22:00 +00001151** Compare an external key against the key on the entry that pCur points to.
1152**
1153** The external key is pKey and is nKey bytes long. The last nIgnore bytes
1154** of the key associated with pCur are ignored, as if they do not exist.
1155** (The normal case is for nIgnore to be zero in which case the entire
1156** internal key is used in the comparison.)
1157**
1158** The comparison result is written to *pRes as follows:
drh2af926b2001-05-15 00:39:25 +00001159**
drh717e6402001-09-27 03:22:32 +00001160** *pRes<0 This means pCur<pKey
1161**
1162** *pRes==0 This means pCur==pKey for all nKey bytes
1163**
1164** *pRes>0 This means pCur>pKey
1165**
drh8721ce42001-11-07 14:22:00 +00001166** When one key is an exact prefix of the other, the shorter key is
1167** considered less than the longer one. In order to be equal the
1168** keys must be exactly the same length. (The length of the pCur key
1169** is the actual key length minus nIgnore bytes.)
drh2af926b2001-05-15 00:39:25 +00001170*/
drh717e6402001-09-27 03:22:32 +00001171int sqliteBtreeKeyCompare(
drh8721ce42001-11-07 14:22:00 +00001172 BtCursor *pCur, /* Pointer to entry to compare against */
1173 const void *pKey, /* Key to compare against entry that pCur points to */
1174 int nKey, /* Number of bytes in pKey */
1175 int nIgnore, /* Ignore this many bytes at the end of pCur */
1176 int *pResult /* Write the result here */
drh5c4d9702001-08-20 00:33:58 +00001177){
drh2af926b2001-05-15 00:39:25 +00001178 Pgno nextPage;
drh8721ce42001-11-07 14:22:00 +00001179 int n, c, rc, nLocal;
drh2af926b2001-05-15 00:39:25 +00001180 Cell *pCell;
drh717e6402001-09-27 03:22:32 +00001181 const char *zKey = (const char*)pKey;
drh2af926b2001-05-15 00:39:25 +00001182
1183 assert( pCur->pPage );
1184 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drhbd03cae2001-06-02 02:40:57 +00001185 pCell = pCur->pPage->apCell[pCur->idx];
drh8721ce42001-11-07 14:22:00 +00001186 nLocal = NKEY(pCell->h) - nIgnore;
1187 if( nLocal<0 ) nLocal = 0;
1188 n = nKey<nLocal ? nKey : nLocal;
drh2af926b2001-05-15 00:39:25 +00001189 if( n>MX_LOCAL_PAYLOAD ){
1190 n = MX_LOCAL_PAYLOAD;
1191 }
drh717e6402001-09-27 03:22:32 +00001192 c = memcmp(pCell->aPayload, zKey, n);
drh2af926b2001-05-15 00:39:25 +00001193 if( c!=0 ){
1194 *pResult = c;
1195 return SQLITE_OK;
1196 }
drh717e6402001-09-27 03:22:32 +00001197 zKey += n;
drh2af926b2001-05-15 00:39:25 +00001198 nKey -= n;
drh8721ce42001-11-07 14:22:00 +00001199 nLocal -= n;
drh3b7511c2001-05-26 13:15:44 +00001200 nextPage = pCell->ovfl;
drh8721ce42001-11-07 14:22:00 +00001201 while( nKey>0 && nLocal>0 ){
drh2af926b2001-05-15 00:39:25 +00001202 OverflowPage *pOvfl;
1203 if( nextPage==0 ){
1204 return SQLITE_CORRUPT;
1205 }
drh8c42ca92001-06-22 19:15:00 +00001206 rc = sqlitepager_get(pCur->pBt->pPager, nextPage, (void**)&pOvfl);
drh72f82862001-05-24 21:06:34 +00001207 if( rc ){
drh2af926b2001-05-15 00:39:25 +00001208 return rc;
1209 }
drh14acc042001-06-10 19:56:58 +00001210 nextPage = pOvfl->iNext;
drh8721ce42001-11-07 14:22:00 +00001211 n = nKey<nLocal ? nKey : nLocal;
drh2af926b2001-05-15 00:39:25 +00001212 if( n>OVERFLOW_SIZE ){
1213 n = OVERFLOW_SIZE;
1214 }
drh717e6402001-09-27 03:22:32 +00001215 c = memcmp(pOvfl->aPayload, zKey, n);
drh2af926b2001-05-15 00:39:25 +00001216 sqlitepager_unref(pOvfl);
1217 if( c!=0 ){
1218 *pResult = c;
1219 return SQLITE_OK;
1220 }
1221 nKey -= n;
drh8721ce42001-11-07 14:22:00 +00001222 nLocal -= n;
drh717e6402001-09-27 03:22:32 +00001223 zKey += n;
drh2af926b2001-05-15 00:39:25 +00001224 }
drh717e6402001-09-27 03:22:32 +00001225 if( c==0 ){
drh8721ce42001-11-07 14:22:00 +00001226 c = nLocal - nKey;
drh717e6402001-09-27 03:22:32 +00001227 }
drh2af926b2001-05-15 00:39:25 +00001228 *pResult = c;
1229 return SQLITE_OK;
1230}
1231
drh72f82862001-05-24 21:06:34 +00001232/*
1233** Move the cursor down to a new child page.
1234*/
drh5e2f8b92001-05-28 00:41:15 +00001235static int moveToChild(BtCursor *pCur, int newPgno){
drh72f82862001-05-24 21:06:34 +00001236 int rc;
1237 MemPage *pNewPage;
1238
drh8c42ca92001-06-22 19:15:00 +00001239 rc = sqlitepager_get(pCur->pBt->pPager, newPgno, (void**)&pNewPage);
drh6019e162001-07-02 17:51:45 +00001240 if( rc ) return rc;
1241 rc = initPage(pNewPage, newPgno, pCur->pPage);
1242 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001243 sqlitepager_unref(pCur->pPage);
1244 pCur->pPage = pNewPage;
1245 pCur->idx = 0;
1246 return SQLITE_OK;
1247}
1248
1249/*
drh5e2f8b92001-05-28 00:41:15 +00001250** Move the cursor up to the parent page.
1251**
1252** pCur->idx is set to the cell index that contains the pointer
1253** to the page we are coming from. If we are coming from the
1254** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00001255** the largest cell index.
drh72f82862001-05-24 21:06:34 +00001256*/
drh5e2f8b92001-05-28 00:41:15 +00001257static int moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001258 Pgno oldPgno;
1259 MemPage *pParent;
drh8c42ca92001-06-22 19:15:00 +00001260 int i;
drh72f82862001-05-24 21:06:34 +00001261 pParent = pCur->pPage->pParent;
drhbd03cae2001-06-02 02:40:57 +00001262 if( pParent==0 ) return SQLITE_INTERNAL;
drh72f82862001-05-24 21:06:34 +00001263 oldPgno = sqlitepager_pagenumber(pCur->pPage);
drh72f82862001-05-24 21:06:34 +00001264 sqlitepager_ref(pParent);
1265 sqlitepager_unref(pCur->pPage);
1266 pCur->pPage = pParent;
drh8c42ca92001-06-22 19:15:00 +00001267 pCur->idx = pParent->nCell;
1268 for(i=0; i<pParent->nCell; i++){
1269 if( pParent->apCell[i]->h.leftChild==oldPgno ){
drh72f82862001-05-24 21:06:34 +00001270 pCur->idx = i;
1271 break;
1272 }
1273 }
drh5e2f8b92001-05-28 00:41:15 +00001274 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00001275}
1276
1277/*
1278** Move the cursor to the root page
1279*/
drh5e2f8b92001-05-28 00:41:15 +00001280static int moveToRoot(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001281 MemPage *pNew;
drhbd03cae2001-06-02 02:40:57 +00001282 int rc;
1283
drh8c42ca92001-06-22 19:15:00 +00001284 rc = sqlitepager_get(pCur->pBt->pPager, pCur->pgnoRoot, (void**)&pNew);
drhbd03cae2001-06-02 02:40:57 +00001285 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00001286 rc = initPage(pNew, pCur->pgnoRoot, 0);
1287 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001288 sqlitepager_unref(pCur->pPage);
1289 pCur->pPage = pNew;
1290 pCur->idx = 0;
1291 return SQLITE_OK;
1292}
drh2af926b2001-05-15 00:39:25 +00001293
drh5e2f8b92001-05-28 00:41:15 +00001294/*
1295** Move the cursor down to the left-most leaf entry beneath the
1296** entry to which it is currently pointing.
1297*/
1298static int moveToLeftmost(BtCursor *pCur){
1299 Pgno pgno;
1300 int rc;
1301
1302 while( (pgno = pCur->pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
1303 rc = moveToChild(pCur, pgno);
1304 if( rc ) return rc;
1305 }
1306 return SQLITE_OK;
1307}
1308
drh5e00f6c2001-09-13 13:46:56 +00001309/* Move the cursor to the first entry in the table. Return SQLITE_OK
1310** on success. Set *pRes to 0 if the cursor actually points to something
1311** or set *pRes to 1 if the table is empty and there is no first element.
1312*/
1313int sqliteBtreeFirst(BtCursor *pCur, int *pRes){
1314 int rc;
drhecdc7532001-09-23 02:35:53 +00001315 if( pCur->pPage==0 ) return SQLITE_ABORT;
drh5e00f6c2001-09-13 13:46:56 +00001316 rc = moveToRoot(pCur);
1317 if( rc ) return rc;
1318 if( pCur->pPage->nCell==0 ){
1319 *pRes = 1;
1320 return SQLITE_OK;
1321 }
1322 *pRes = 0;
1323 rc = moveToLeftmost(pCur);
drh0ce92ed2001-12-15 02:47:28 +00001324 pCur->bSkipNext = 0;
drh5e00f6c2001-09-13 13:46:56 +00001325 return rc;
1326}
drh5e2f8b92001-05-28 00:41:15 +00001327
drha059ad02001-04-17 20:09:11 +00001328/* Move the cursor so that it points to an entry near pKey.
drh72f82862001-05-24 21:06:34 +00001329** Return a success code.
1330**
drh5e2f8b92001-05-28 00:41:15 +00001331** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00001332** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00001333** were present. The cursor might point to an entry that comes
1334** before or after the key.
1335**
drhbd03cae2001-06-02 02:40:57 +00001336** The result of comparing the key with the entry to which the
1337** cursor is left pointing is stored in pCur->iMatch. The same
1338** value is also written to *pRes if pRes!=NULL. The meaning of
1339** this value is as follows:
1340**
1341** *pRes<0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001342** is smaller than pKey.
drhbd03cae2001-06-02 02:40:57 +00001343**
1344** *pRes==0 The cursor is left pointing at an entry that
1345** exactly matches pKey.
1346**
1347** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001348** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00001349*/
drh5c4d9702001-08-20 00:33:58 +00001350int sqliteBtreeMoveto(BtCursor *pCur, const void *pKey, int nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00001351 int rc;
drhecdc7532001-09-23 02:35:53 +00001352 if( pCur->pPage==0 ) return SQLITE_ABORT;
drh7c717f72001-06-24 20:39:41 +00001353 pCur->bSkipNext = 0;
drh5e2f8b92001-05-28 00:41:15 +00001354 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00001355 if( rc ) return rc;
1356 for(;;){
1357 int lwr, upr;
1358 Pgno chldPg;
1359 MemPage *pPage = pCur->pPage;
drh8b2f49b2001-06-08 00:21:52 +00001360 int c = -1;
drh72f82862001-05-24 21:06:34 +00001361 lwr = 0;
1362 upr = pPage->nCell-1;
1363 while( lwr<=upr ){
drh72f82862001-05-24 21:06:34 +00001364 pCur->idx = (lwr+upr)/2;
drh8721ce42001-11-07 14:22:00 +00001365 rc = sqliteBtreeKeyCompare(pCur, pKey, nKey, 0, &c);
drh72f82862001-05-24 21:06:34 +00001366 if( rc ) return rc;
1367 if( c==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001368 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001369 if( pRes ) *pRes = 0;
1370 return SQLITE_OK;
1371 }
1372 if( c<0 ){
1373 lwr = pCur->idx+1;
1374 }else{
1375 upr = pCur->idx-1;
1376 }
1377 }
1378 assert( lwr==upr+1 );
1379 if( lwr>=pPage->nCell ){
drh14acc042001-06-10 19:56:58 +00001380 chldPg = pPage->u.hdr.rightChild;
drh72f82862001-05-24 21:06:34 +00001381 }else{
drh5e2f8b92001-05-28 00:41:15 +00001382 chldPg = pPage->apCell[lwr]->h.leftChild;
drh72f82862001-05-24 21:06:34 +00001383 }
1384 if( chldPg==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001385 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001386 if( pRes ) *pRes = c;
1387 return SQLITE_OK;
1388 }
drh5e2f8b92001-05-28 00:41:15 +00001389 rc = moveToChild(pCur, chldPg);
drh72f82862001-05-24 21:06:34 +00001390 if( rc ) return rc;
1391 }
drhbd03cae2001-06-02 02:40:57 +00001392 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00001393}
1394
1395/*
drhbd03cae2001-06-02 02:40:57 +00001396** Advance the cursor to the next entry in the database. If
1397** successful and pRes!=NULL then set *pRes=0. If the cursor
1398** was already pointing to the last entry in the database before
1399** this routine was called, then set *pRes=1 if pRes!=NULL.
drh72f82862001-05-24 21:06:34 +00001400*/
1401int sqliteBtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00001402 int rc;
drhecdc7532001-09-23 02:35:53 +00001403 if( pCur->pPage==0 ){
drh1bee3d72001-10-15 00:44:35 +00001404 if( pRes ) *pRes = 1;
drhecdc7532001-09-23 02:35:53 +00001405 return SQLITE_ABORT;
1406 }
drhf5bf0a72001-11-23 00:24:12 +00001407 if( pCur->bSkipNext && pCur->idx<pCur->pPage->nCell ){
drh5e2f8b92001-05-28 00:41:15 +00001408 pCur->bSkipNext = 0;
drh72f82862001-05-24 21:06:34 +00001409 if( pRes ) *pRes = 0;
1410 return SQLITE_OK;
1411 }
drh72f82862001-05-24 21:06:34 +00001412 pCur->idx++;
drh5e2f8b92001-05-28 00:41:15 +00001413 if( pCur->idx>=pCur->pPage->nCell ){
drh8c42ca92001-06-22 19:15:00 +00001414 if( pCur->pPage->u.hdr.rightChild ){
1415 rc = moveToChild(pCur, pCur->pPage->u.hdr.rightChild);
drh5e2f8b92001-05-28 00:41:15 +00001416 if( rc ) return rc;
1417 rc = moveToLeftmost(pCur);
1418 if( rc ) return rc;
1419 if( pRes ) *pRes = 0;
drh72f82862001-05-24 21:06:34 +00001420 return SQLITE_OK;
1421 }
drh5e2f8b92001-05-28 00:41:15 +00001422 do{
drh8c42ca92001-06-22 19:15:00 +00001423 if( pCur->pPage->pParent==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001424 if( pRes ) *pRes = 1;
1425 return SQLITE_OK;
1426 }
1427 rc = moveToParent(pCur);
1428 if( rc ) return rc;
1429 }while( pCur->idx>=pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00001430 if( pRes ) *pRes = 0;
1431 return SQLITE_OK;
1432 }
drh5e2f8b92001-05-28 00:41:15 +00001433 rc = moveToLeftmost(pCur);
1434 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001435 if( pRes ) *pRes = 0;
1436 return SQLITE_OK;
1437}
1438
drh3b7511c2001-05-26 13:15:44 +00001439/*
1440** Allocate a new page from the database file.
1441**
1442** The new page is marked as dirty. (In other words, sqlitepager_write()
1443** has already been called on the new page.) The new page has also
1444** been referenced and the calling routine is responsible for calling
1445** sqlitepager_unref() on the new page when it is done.
1446**
1447** SQLITE_OK is returned on success. Any other return value indicates
1448** an error. *ppPage and *pPgno are undefined in the event of an error.
1449** Do not invoke sqlitepager_unref() on *ppPage if an error is returned.
1450*/
1451static int allocatePage(Btree *pBt, MemPage **ppPage, Pgno *pPgno){
drhbd03cae2001-06-02 02:40:57 +00001452 PageOne *pPage1 = pBt->page1;
drh8c42ca92001-06-22 19:15:00 +00001453 int rc;
drh3b7511c2001-05-26 13:15:44 +00001454 if( pPage1->freeList ){
1455 OverflowPage *pOvfl;
1456 rc = sqlitepager_write(pPage1);
1457 if( rc ) return rc;
1458 *pPgno = pPage1->freeList;
drh8c42ca92001-06-22 19:15:00 +00001459 rc = sqlitepager_get(pBt->pPager, pPage1->freeList, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001460 if( rc ) return rc;
1461 rc = sqlitepager_write(pOvfl);
1462 if( rc ){
1463 sqlitepager_unref(pOvfl);
1464 return rc;
1465 }
drh14acc042001-06-10 19:56:58 +00001466 pPage1->freeList = pOvfl->iNext;
drh2aa679f2001-06-25 02:11:07 +00001467 pPage1->nFree--;
drh3b7511c2001-05-26 13:15:44 +00001468 *ppPage = (MemPage*)pOvfl;
1469 }else{
drh2aa679f2001-06-25 02:11:07 +00001470 *pPgno = sqlitepager_pagecount(pBt->pPager) + 1;
drh8c42ca92001-06-22 19:15:00 +00001471 rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
drh3b7511c2001-05-26 13:15:44 +00001472 if( rc ) return rc;
1473 rc = sqlitepager_write(*ppPage);
1474 }
1475 return rc;
1476}
1477
1478/*
1479** Add a page of the database file to the freelist. Either pgno or
1480** pPage but not both may be 0.
drh5e2f8b92001-05-28 00:41:15 +00001481**
drhdd793422001-06-28 01:54:48 +00001482** sqlitepager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00001483*/
1484static int freePage(Btree *pBt, void *pPage, Pgno pgno){
drhbd03cae2001-06-02 02:40:57 +00001485 PageOne *pPage1 = pBt->page1;
drh3b7511c2001-05-26 13:15:44 +00001486 OverflowPage *pOvfl = (OverflowPage*)pPage;
1487 int rc;
drhdd793422001-06-28 01:54:48 +00001488 int needUnref = 0;
1489 MemPage *pMemPage;
drh8b2f49b2001-06-08 00:21:52 +00001490
drh3b7511c2001-05-26 13:15:44 +00001491 if( pgno==0 ){
1492 assert( pOvfl!=0 );
1493 pgno = sqlitepager_pagenumber(pOvfl);
1494 }
drh2aa679f2001-06-25 02:11:07 +00001495 assert( pgno>2 );
drh3b7511c2001-05-26 13:15:44 +00001496 rc = sqlitepager_write(pPage1);
1497 if( rc ){
1498 return rc;
1499 }
1500 if( pOvfl==0 ){
1501 assert( pgno>0 );
drh8c42ca92001-06-22 19:15:00 +00001502 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001503 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001504 needUnref = 1;
drh3b7511c2001-05-26 13:15:44 +00001505 }
1506 rc = sqlitepager_write(pOvfl);
1507 if( rc ){
drhdd793422001-06-28 01:54:48 +00001508 if( needUnref ) sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001509 return rc;
1510 }
drh14acc042001-06-10 19:56:58 +00001511 pOvfl->iNext = pPage1->freeList;
drh3b7511c2001-05-26 13:15:44 +00001512 pPage1->freeList = pgno;
drh2aa679f2001-06-25 02:11:07 +00001513 pPage1->nFree++;
drh5e2f8b92001-05-28 00:41:15 +00001514 memset(pOvfl->aPayload, 0, OVERFLOW_SIZE);
drhdd793422001-06-28 01:54:48 +00001515 pMemPage = (MemPage*)pPage;
1516 pMemPage->isInit = 0;
1517 if( pMemPage->pParent ){
1518 sqlitepager_unref(pMemPage->pParent);
1519 pMemPage->pParent = 0;
1520 }
1521 if( needUnref ) rc = sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001522 return rc;
1523}
1524
1525/*
1526** Erase all the data out of a cell. This involves returning overflow
1527** pages back the freelist.
1528*/
1529static int clearCell(Btree *pBt, Cell *pCell){
1530 Pager *pPager = pBt->pPager;
1531 OverflowPage *pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001532 Pgno ovfl, nextOvfl;
1533 int rc;
1534
drh80ff32f2001-11-04 18:32:46 +00001535 if( NKEY(pCell->h) + NDATA(pCell->h) <= MX_LOCAL_PAYLOAD ){
drh5e2f8b92001-05-28 00:41:15 +00001536 return SQLITE_OK;
1537 }
drh3b7511c2001-05-26 13:15:44 +00001538 ovfl = pCell->ovfl;
1539 pCell->ovfl = 0;
1540 while( ovfl ){
drh8c42ca92001-06-22 19:15:00 +00001541 rc = sqlitepager_get(pPager, ovfl, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001542 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00001543 nextOvfl = pOvfl->iNext;
drhbd03cae2001-06-02 02:40:57 +00001544 rc = freePage(pBt, pOvfl, ovfl);
1545 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001546 sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001547 ovfl = nextOvfl;
drh3b7511c2001-05-26 13:15:44 +00001548 }
drh5e2f8b92001-05-28 00:41:15 +00001549 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00001550}
1551
1552/*
1553** Create a new cell from key and data. Overflow pages are allocated as
1554** necessary and linked to this cell.
1555*/
1556static int fillInCell(
1557 Btree *pBt, /* The whole Btree. Needed to allocate pages */
1558 Cell *pCell, /* Populate this Cell structure */
drh5c4d9702001-08-20 00:33:58 +00001559 const void *pKey, int nKey, /* The key */
1560 const void *pData,int nData /* The data */
drh3b7511c2001-05-26 13:15:44 +00001561){
drhdd793422001-06-28 01:54:48 +00001562 OverflowPage *pOvfl, *pPrior;
drh3b7511c2001-05-26 13:15:44 +00001563 Pgno *pNext;
1564 int spaceLeft;
drh8c42ca92001-06-22 19:15:00 +00001565 int n, rc;
drh3b7511c2001-05-26 13:15:44 +00001566 int nPayload;
drh5c4d9702001-08-20 00:33:58 +00001567 const char *pPayload;
drh3b7511c2001-05-26 13:15:44 +00001568 char *pSpace;
1569
drh5e2f8b92001-05-28 00:41:15 +00001570 pCell->h.leftChild = 0;
drh80ff32f2001-11-04 18:32:46 +00001571 pCell->h.nKey = nKey & 0xffff;
1572 pCell->h.nKeyHi = nKey >> 16;
1573 pCell->h.nData = nData & 0xffff;
1574 pCell->h.nDataHi = nData >> 16;
drh3b7511c2001-05-26 13:15:44 +00001575 pCell->h.iNext = 0;
1576
1577 pNext = &pCell->ovfl;
drh5e2f8b92001-05-28 00:41:15 +00001578 pSpace = pCell->aPayload;
drh3b7511c2001-05-26 13:15:44 +00001579 spaceLeft = MX_LOCAL_PAYLOAD;
1580 pPayload = pKey;
1581 pKey = 0;
1582 nPayload = nKey;
drhdd793422001-06-28 01:54:48 +00001583 pPrior = 0;
drh3b7511c2001-05-26 13:15:44 +00001584 while( nPayload>0 ){
1585 if( spaceLeft==0 ){
drh8c42ca92001-06-22 19:15:00 +00001586 rc = allocatePage(pBt, (MemPage**)&pOvfl, pNext);
drh3b7511c2001-05-26 13:15:44 +00001587 if( rc ){
1588 *pNext = 0;
drhdd793422001-06-28 01:54:48 +00001589 }
1590 if( pPrior ) sqlitepager_unref(pPrior);
1591 if( rc ){
drh5e2f8b92001-05-28 00:41:15 +00001592 clearCell(pBt, pCell);
drh3b7511c2001-05-26 13:15:44 +00001593 return rc;
1594 }
drhdd793422001-06-28 01:54:48 +00001595 pPrior = pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001596 spaceLeft = OVERFLOW_SIZE;
drh5e2f8b92001-05-28 00:41:15 +00001597 pSpace = pOvfl->aPayload;
drh8c42ca92001-06-22 19:15:00 +00001598 pNext = &pOvfl->iNext;
drh3b7511c2001-05-26 13:15:44 +00001599 }
1600 n = nPayload;
1601 if( n>spaceLeft ) n = spaceLeft;
1602 memcpy(pSpace, pPayload, n);
1603 nPayload -= n;
1604 if( nPayload==0 && pData ){
1605 pPayload = pData;
1606 nPayload = nData;
1607 pData = 0;
1608 }else{
1609 pPayload += n;
1610 }
1611 spaceLeft -= n;
1612 pSpace += n;
1613 }
drhdd793422001-06-28 01:54:48 +00001614 *pNext = 0;
1615 if( pPrior ){
1616 sqlitepager_unref(pPrior);
1617 }
drh3b7511c2001-05-26 13:15:44 +00001618 return SQLITE_OK;
1619}
1620
1621/*
drhbd03cae2001-06-02 02:40:57 +00001622** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00001623** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00001624** pointer in the third argument.
1625*/
1626static void reparentPage(Pager *pPager, Pgno pgno, MemPage *pNewParent){
1627 MemPage *pThis;
1628
drhdd793422001-06-28 01:54:48 +00001629 if( pgno==0 ) return;
1630 assert( pPager!=0 );
drhbd03cae2001-06-02 02:40:57 +00001631 pThis = sqlitepager_lookup(pPager, pgno);
drh6019e162001-07-02 17:51:45 +00001632 if( pThis && pThis->isInit ){
drhdd793422001-06-28 01:54:48 +00001633 if( pThis->pParent!=pNewParent ){
1634 if( pThis->pParent ) sqlitepager_unref(pThis->pParent);
1635 pThis->pParent = pNewParent;
1636 if( pNewParent ) sqlitepager_ref(pNewParent);
1637 }
1638 sqlitepager_unref(pThis);
drhbd03cae2001-06-02 02:40:57 +00001639 }
1640}
1641
1642/*
1643** Reparent all children of the given page to be the given page.
1644** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00001645** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00001646**
1647** This routine gets called after you memcpy() one page into
1648** another.
1649*/
drh8c42ca92001-06-22 19:15:00 +00001650static void reparentChildPages(Pager *pPager, MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00001651 int i;
1652 for(i=0; i<pPage->nCell; i++){
drh8c42ca92001-06-22 19:15:00 +00001653 reparentPage(pPager, pPage->apCell[i]->h.leftChild, pPage);
drhbd03cae2001-06-02 02:40:57 +00001654 }
drh14acc042001-06-10 19:56:58 +00001655 reparentPage(pPager, pPage->u.hdr.rightChild, pPage);
1656}
1657
1658/*
1659** Remove the i-th cell from pPage. This routine effects pPage only.
1660** The cell content is not freed or deallocated. It is assumed that
1661** the cell content has been copied someplace else. This routine just
1662** removes the reference to the cell from pPage.
1663**
1664** "sz" must be the number of bytes in the cell.
1665**
1666** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001667** Only the pPage->apCell[] array is important. The relinkCellList()
1668** routine will be called soon after this routine in order to rebuild
1669** the linked list.
drh14acc042001-06-10 19:56:58 +00001670*/
drh8c42ca92001-06-22 19:15:00 +00001671static void dropCell(MemPage *pPage, int idx, int sz){
drh14acc042001-06-10 19:56:58 +00001672 int j;
drh8c42ca92001-06-22 19:15:00 +00001673 assert( idx>=0 && idx<pPage->nCell );
1674 assert( sz==cellSize(pPage->apCell[idx]) );
drh6019e162001-07-02 17:51:45 +00001675 assert( sqlitepager_iswriteable(pPage) );
drh7c717f72001-06-24 20:39:41 +00001676 freeSpace(pPage, Addr(pPage->apCell[idx]) - Addr(pPage), sz);
1677 for(j=idx; j<pPage->nCell-1; j++){
drh14acc042001-06-10 19:56:58 +00001678 pPage->apCell[j] = pPage->apCell[j+1];
1679 }
1680 pPage->nCell--;
1681}
1682
1683/*
1684** Insert a new cell on pPage at cell index "i". pCell points to the
1685** content of the cell.
1686**
1687** If the cell content will fit on the page, then put it there. If it
1688** will not fit, then just make pPage->apCell[i] point to the content
1689** and set pPage->isOverfull.
1690**
1691** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001692** Only the pPage->apCell[] array is important. The relinkCellList()
1693** routine will be called soon after this routine in order to rebuild
1694** the linked list.
drh14acc042001-06-10 19:56:58 +00001695*/
1696static void insertCell(MemPage *pPage, int i, Cell *pCell, int sz){
1697 int idx, j;
1698 assert( i>=0 && i<=pPage->nCell );
1699 assert( sz==cellSize(pCell) );
drh6019e162001-07-02 17:51:45 +00001700 assert( sqlitepager_iswriteable(pPage) );
drh2aa679f2001-06-25 02:11:07 +00001701 idx = allocateSpace(pPage, sz);
drh14acc042001-06-10 19:56:58 +00001702 for(j=pPage->nCell; j>i; j--){
1703 pPage->apCell[j] = pPage->apCell[j-1];
1704 }
1705 pPage->nCell++;
drh14acc042001-06-10 19:56:58 +00001706 if( idx<=0 ){
1707 pPage->isOverfull = 1;
1708 pPage->apCell[i] = pCell;
1709 }else{
1710 memcpy(&pPage->u.aDisk[idx], pCell, sz);
drh8c42ca92001-06-22 19:15:00 +00001711 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[idx];
drh14acc042001-06-10 19:56:58 +00001712 }
1713}
1714
1715/*
1716** Rebuild the linked list of cells on a page so that the cells
drh8c42ca92001-06-22 19:15:00 +00001717** occur in the order specified by the pPage->apCell[] array.
1718** Invoke this routine once to repair damage after one or more
1719** invocations of either insertCell() or dropCell().
drh14acc042001-06-10 19:56:58 +00001720*/
1721static void relinkCellList(MemPage *pPage){
1722 int i;
1723 u16 *pIdx;
drh6019e162001-07-02 17:51:45 +00001724 assert( sqlitepager_iswriteable(pPage) );
drh14acc042001-06-10 19:56:58 +00001725 pIdx = &pPage->u.hdr.firstCell;
1726 for(i=0; i<pPage->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00001727 int idx = Addr(pPage->apCell[i]) - Addr(pPage);
drh8c42ca92001-06-22 19:15:00 +00001728 assert( idx>0 && idx<SQLITE_PAGE_SIZE );
drh14acc042001-06-10 19:56:58 +00001729 *pIdx = idx;
1730 pIdx = &pPage->apCell[i]->h.iNext;
1731 }
1732 *pIdx = 0;
1733}
1734
1735/*
1736** Make a copy of the contents of pFrom into pTo. The pFrom->apCell[]
drh5e00f6c2001-09-13 13:46:56 +00001737** pointers that point into pFrom->u.aDisk[] must be adjusted to point
drhdd793422001-06-28 01:54:48 +00001738** into pTo->u.aDisk[] instead. But some pFrom->apCell[] entries might
drh14acc042001-06-10 19:56:58 +00001739** not point to pFrom->u.aDisk[]. Those are unchanged.
1740*/
1741static void copyPage(MemPage *pTo, MemPage *pFrom){
1742 uptr from, to;
1743 int i;
1744 memcpy(pTo->u.aDisk, pFrom->u.aDisk, SQLITE_PAGE_SIZE);
drhdd793422001-06-28 01:54:48 +00001745 pTo->pParent = 0;
drh14acc042001-06-10 19:56:58 +00001746 pTo->isInit = 1;
1747 pTo->nCell = pFrom->nCell;
1748 pTo->nFree = pFrom->nFree;
1749 pTo->isOverfull = pFrom->isOverfull;
drh7c717f72001-06-24 20:39:41 +00001750 to = Addr(pTo);
1751 from = Addr(pFrom);
drh14acc042001-06-10 19:56:58 +00001752 for(i=0; i<pTo->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00001753 uptr x = Addr(pFrom->apCell[i]);
drh8c42ca92001-06-22 19:15:00 +00001754 if( x>from && x<from+SQLITE_PAGE_SIZE ){
1755 *((uptr*)&pTo->apCell[i]) = x + to - from;
drhdd793422001-06-28 01:54:48 +00001756 }else{
1757 pTo->apCell[i] = pFrom->apCell[i];
drh14acc042001-06-10 19:56:58 +00001758 }
1759 }
drhbd03cae2001-06-02 02:40:57 +00001760}
1761
1762/*
drh8b2f49b2001-06-08 00:21:52 +00001763** This routine redistributes Cells on pPage and up to two siblings
1764** of pPage so that all pages have about the same amount of free space.
drh14acc042001-06-10 19:56:58 +00001765** Usually one sibling on either side of pPage is used in the balancing,
drh8b2f49b2001-06-08 00:21:52 +00001766** though both siblings might come from one side if pPage is the first
1767** or last child of its parent. If pPage has fewer than two siblings
1768** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00001769** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00001770**
1771** The number of siblings of pPage might be increased or decreased by
drh8c42ca92001-06-22 19:15:00 +00001772** one in an effort to keep pages between 66% and 100% full. The root page
1773** is special and is allowed to be less than 66% full. If pPage is
1774** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00001775** or decreased by one, as necessary, to keep the root page from being
1776** overfull or empty.
1777**
drh14acc042001-06-10 19:56:58 +00001778** This routine calls relinkCellList() on its input page regardless of
1779** whether or not it does any real balancing. Client routines will typically
1780** invoke insertCell() or dropCell() before calling this routine, so we
1781** need to call relinkCellList() to clean up the mess that those other
1782** routines left behind.
1783**
1784** pCur is left pointing to the same cell as when this routine was called
drh8c42ca92001-06-22 19:15:00 +00001785** even if that cell gets moved to a different page. pCur may be NULL.
1786** Set the pCur parameter to NULL if you do not care about keeping track
1787** of a cell as that will save this routine the work of keeping track of it.
drh14acc042001-06-10 19:56:58 +00001788**
drh8b2f49b2001-06-08 00:21:52 +00001789** Note that when this routine is called, some of the Cells on pPage
drh14acc042001-06-10 19:56:58 +00001790** might not actually be stored in pPage->u.aDisk[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00001791** if the page is overfull. Part of the job of this routine is to
drh14acc042001-06-10 19:56:58 +00001792** make sure all Cells for pPage once again fit in pPage->u.aDisk[].
1793**
drh8c42ca92001-06-22 19:15:00 +00001794** In the course of balancing the siblings of pPage, the parent of pPage
1795** might become overfull or underfull. If that happens, then this routine
1796** is called recursively on the parent.
1797**
drh5e00f6c2001-09-13 13:46:56 +00001798** If this routine fails for any reason, it might leave the database
1799** in a corrupted state. So if this routine fails, the database should
1800** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00001801*/
drh14acc042001-06-10 19:56:58 +00001802static int balance(Btree *pBt, MemPage *pPage, BtCursor *pCur){
drh8b2f49b2001-06-08 00:21:52 +00001803 MemPage *pParent; /* The parent of pPage */
drh14acc042001-06-10 19:56:58 +00001804 MemPage *apOld[3]; /* pPage and up to two siblings */
drh8b2f49b2001-06-08 00:21:52 +00001805 Pgno pgnoOld[3]; /* Page numbers for each page in apOld[] */
drh14acc042001-06-10 19:56:58 +00001806 MemPage *apNew[4]; /* pPage and up to 3 siblings after balancing */
1807 Pgno pgnoNew[4]; /* Page numbers for each page in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00001808 int idxDiv[3]; /* Indices of divider cells in pParent */
1809 Cell *apDiv[3]; /* Divider cells in pParent */
1810 int nCell; /* Number of cells in apCell[] */
1811 int nOld; /* Number of pages in apOld[] */
1812 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00001813 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00001814 int i, j, k; /* Loop counters */
1815 int idx; /* Index of pPage in pParent->apCell[] */
1816 int nxDiv; /* Next divider slot in pParent->apCell[] */
1817 int rc; /* The return code */
1818 int iCur; /* apCell[iCur] is the cell of the cursor */
drh5edc3122001-09-13 21:53:09 +00001819 MemPage *pOldCurPage; /* The cursor originally points to this page */
drh8c42ca92001-06-22 19:15:00 +00001820 int totalSize; /* Total bytes for all cells */
drh6019e162001-07-02 17:51:45 +00001821 int subtotal; /* Subtotal of bytes in cells on one page */
1822 int cntNew[4]; /* Index in apCell[] of cell after i-th page */
1823 int szNew[4]; /* Combined size of cells place on i-th page */
drh9ca7d3b2001-06-28 11:50:21 +00001824 MemPage *extraUnref = 0; /* A page that needs to be unref-ed */
drh8c42ca92001-06-22 19:15:00 +00001825 Pgno pgno; /* Page number */
drh14acc042001-06-10 19:56:58 +00001826 Cell *apCell[MX_CELL*3+5]; /* All cells from pages being balanceed */
1827 int szCell[MX_CELL*3+5]; /* Local size of all cells */
1828 Cell aTemp[2]; /* Temporary holding area for apDiv[] */
1829 MemPage aOld[3]; /* Temporary copies of pPage and its siblings */
drh8b2f49b2001-06-08 00:21:52 +00001830
drh14acc042001-06-10 19:56:58 +00001831 /*
1832 ** Return without doing any work if pPage is neither overfull nor
1833 ** underfull.
drh8b2f49b2001-06-08 00:21:52 +00001834 */
drh6019e162001-07-02 17:51:45 +00001835 assert( sqlitepager_iswriteable(pPage) );
drha1b351a2001-09-14 16:42:12 +00001836 if( !pPage->isOverfull && pPage->nFree<SQLITE_PAGE_SIZE/2
1837 && pPage->nCell>=2){
drh14acc042001-06-10 19:56:58 +00001838 relinkCellList(pPage);
drh8b2f49b2001-06-08 00:21:52 +00001839 return SQLITE_OK;
1840 }
1841
1842 /*
drh14acc042001-06-10 19:56:58 +00001843 ** Find the parent of the page to be balanceed.
1844 ** If there is no parent, it means this page is the root page and
drh8b2f49b2001-06-08 00:21:52 +00001845 ** special rules apply.
1846 */
drh14acc042001-06-10 19:56:58 +00001847 pParent = pPage->pParent;
drh8b2f49b2001-06-08 00:21:52 +00001848 if( pParent==0 ){
1849 Pgno pgnoChild;
drh8c42ca92001-06-22 19:15:00 +00001850 MemPage *pChild;
drh8b2f49b2001-06-08 00:21:52 +00001851 if( pPage->nCell==0 ){
drh14acc042001-06-10 19:56:58 +00001852 if( pPage->u.hdr.rightChild ){
1853 /*
1854 ** The root page is empty. Copy the one child page
drh8b2f49b2001-06-08 00:21:52 +00001855 ** into the root page and return. This reduces the depth
1856 ** of the BTree by one.
1857 */
drh14acc042001-06-10 19:56:58 +00001858 pgnoChild = pPage->u.hdr.rightChild;
drh8c42ca92001-06-22 19:15:00 +00001859 rc = sqlitepager_get(pBt->pPager, pgnoChild, (void**)&pChild);
drh8b2f49b2001-06-08 00:21:52 +00001860 if( rc ) return rc;
1861 memcpy(pPage, pChild, SQLITE_PAGE_SIZE);
1862 pPage->isInit = 0;
drh6019e162001-07-02 17:51:45 +00001863 rc = initPage(pPage, sqlitepager_pagenumber(pPage), 0);
1864 assert( rc==SQLITE_OK );
drh8b2f49b2001-06-08 00:21:52 +00001865 reparentChildPages(pBt->pPager, pPage);
drh5edc3122001-09-13 21:53:09 +00001866 if( pCur && pCur->pPage==pChild ){
1867 sqlitepager_unref(pChild);
1868 pCur->pPage = pPage;
1869 sqlitepager_ref(pPage);
1870 }
drh8b2f49b2001-06-08 00:21:52 +00001871 freePage(pBt, pChild, pgnoChild);
1872 sqlitepager_unref(pChild);
drhefc251d2001-07-01 22:12:01 +00001873 }else{
1874 relinkCellList(pPage);
drh8b2f49b2001-06-08 00:21:52 +00001875 }
1876 return SQLITE_OK;
1877 }
drh14acc042001-06-10 19:56:58 +00001878 if( !pPage->isOverfull ){
drh8b2f49b2001-06-08 00:21:52 +00001879 /* It is OK for the root page to be less than half full.
1880 */
drh14acc042001-06-10 19:56:58 +00001881 relinkCellList(pPage);
drh8b2f49b2001-06-08 00:21:52 +00001882 return SQLITE_OK;
1883 }
drh14acc042001-06-10 19:56:58 +00001884 /*
1885 ** If we get to here, it means the root page is overfull.
drh8b2f49b2001-06-08 00:21:52 +00001886 ** When this happens, Create a new child page and copy the
1887 ** contents of the root into the child. Then make the root
drh14acc042001-06-10 19:56:58 +00001888 ** page an empty page with rightChild pointing to the new
drh8b2f49b2001-06-08 00:21:52 +00001889 ** child. Then fall thru to the code below which will cause
1890 ** the overfull child page to be split.
1891 */
drh14acc042001-06-10 19:56:58 +00001892 rc = sqlitepager_write(pPage);
1893 if( rc ) return rc;
drh8b2f49b2001-06-08 00:21:52 +00001894 rc = allocatePage(pBt, &pChild, &pgnoChild);
1895 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00001896 assert( sqlitepager_iswriteable(pChild) );
drh14acc042001-06-10 19:56:58 +00001897 copyPage(pChild, pPage);
1898 pChild->pParent = pPage;
drhdd793422001-06-28 01:54:48 +00001899 sqlitepager_ref(pPage);
drh14acc042001-06-10 19:56:58 +00001900 pChild->isOverfull = 1;
drh5edc3122001-09-13 21:53:09 +00001901 if( pCur && pCur->pPage==pPage ){
1902 sqlitepager_unref(pPage);
drh14acc042001-06-10 19:56:58 +00001903 pCur->pPage = pChild;
drh9ca7d3b2001-06-28 11:50:21 +00001904 }else{
1905 extraUnref = pChild;
drh8b2f49b2001-06-08 00:21:52 +00001906 }
drh8b2f49b2001-06-08 00:21:52 +00001907 zeroPage(pPage);
drh14acc042001-06-10 19:56:58 +00001908 pPage->u.hdr.rightChild = pgnoChild;
drh8b2f49b2001-06-08 00:21:52 +00001909 pParent = pPage;
1910 pPage = pChild;
drh8b2f49b2001-06-08 00:21:52 +00001911 }
drh6019e162001-07-02 17:51:45 +00001912 rc = sqlitepager_write(pParent);
1913 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00001914
drh8b2f49b2001-06-08 00:21:52 +00001915 /*
drh14acc042001-06-10 19:56:58 +00001916 ** Find the Cell in the parent page whose h.leftChild points back
1917 ** to pPage. The "idx" variable is the index of that cell. If pPage
1918 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00001919 */
1920 idx = -1;
1921 pgno = sqlitepager_pagenumber(pPage);
1922 for(i=0; i<pParent->nCell; i++){
1923 if( pParent->apCell[i]->h.leftChild==pgno ){
1924 idx = i;
1925 break;
1926 }
1927 }
drhdd793422001-06-28 01:54:48 +00001928 if( idx<0 && pParent->u.hdr.rightChild==pgno ){
1929 idx = pParent->nCell;
drh8b2f49b2001-06-08 00:21:52 +00001930 }
1931 if( idx<0 ){
drh14acc042001-06-10 19:56:58 +00001932 return SQLITE_CORRUPT;
drh8b2f49b2001-06-08 00:21:52 +00001933 }
1934
1935 /*
drh14acc042001-06-10 19:56:58 +00001936 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00001937 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00001938 */
drh14acc042001-06-10 19:56:58 +00001939 nOld = nNew = 0;
1940 sqlitepager_ref(pParent);
1941
1942 /*
1943 ** Find sibling pages to pPage and the Cells in pParent that divide
1944 ** the siblings. An attempt is made to find one sibling on either
1945 ** side of pPage. Both siblings are taken from one side, however, if
1946 ** pPage is either the first or last child of its parent. If pParent
1947 ** has 3 or fewer children then all children of pParent are taken.
1948 */
1949 if( idx==pParent->nCell ){
1950 nxDiv = idx - 2;
drh8b2f49b2001-06-08 00:21:52 +00001951 }else{
drh14acc042001-06-10 19:56:58 +00001952 nxDiv = idx - 1;
drh8b2f49b2001-06-08 00:21:52 +00001953 }
drh14acc042001-06-10 19:56:58 +00001954 if( nxDiv<0 ) nxDiv = 0;
drh8b2f49b2001-06-08 00:21:52 +00001955 nDiv = 0;
drh14acc042001-06-10 19:56:58 +00001956 for(i=0, k=nxDiv; i<3; i++, k++){
1957 if( k<pParent->nCell ){
1958 idxDiv[i] = k;
1959 apDiv[i] = pParent->apCell[k];
drh8b2f49b2001-06-08 00:21:52 +00001960 nDiv++;
1961 pgnoOld[i] = apDiv[i]->h.leftChild;
drh14acc042001-06-10 19:56:58 +00001962 }else if( k==pParent->nCell ){
drh8c42ca92001-06-22 19:15:00 +00001963 pgnoOld[i] = pParent->u.hdr.rightChild;
drh14acc042001-06-10 19:56:58 +00001964 }else{
1965 break;
drh8b2f49b2001-06-08 00:21:52 +00001966 }
drh8c42ca92001-06-22 19:15:00 +00001967 rc = sqlitepager_get(pBt->pPager, pgnoOld[i], (void**)&apOld[i]);
drh14acc042001-06-10 19:56:58 +00001968 if( rc ) goto balance_cleanup;
drh6019e162001-07-02 17:51:45 +00001969 rc = initPage(apOld[i], pgnoOld[i], pParent);
1970 if( rc ) goto balance_cleanup;
drh14acc042001-06-10 19:56:58 +00001971 nOld++;
drh8b2f49b2001-06-08 00:21:52 +00001972 }
1973
1974 /*
drh14acc042001-06-10 19:56:58 +00001975 ** Set iCur to be the index in apCell[] of the cell that the cursor
1976 ** is pointing to. We will need this later on in order to keep the
drh5edc3122001-09-13 21:53:09 +00001977 ** cursor pointing at the same cell. If pCur points to a page that
1978 ** has no involvement with this rebalancing, then set iCur to a large
1979 ** number so that the iCur==j tests always fail in the main cell
1980 ** distribution loop below.
drh14acc042001-06-10 19:56:58 +00001981 */
1982 if( pCur ){
drh5edc3122001-09-13 21:53:09 +00001983 iCur = 0;
1984 for(i=0; i<nOld; i++){
1985 if( pCur->pPage==apOld[i] ){
1986 iCur += pCur->idx;
1987 break;
1988 }
1989 iCur += apOld[i]->nCell;
1990 if( i<nOld-1 && pCur->pPage==pParent && pCur->idx==idxDiv[i] ){
1991 break;
1992 }
1993 iCur++;
drh14acc042001-06-10 19:56:58 +00001994 }
drh5edc3122001-09-13 21:53:09 +00001995 pOldCurPage = pCur->pPage;
drh14acc042001-06-10 19:56:58 +00001996 }
1997
1998 /*
1999 ** Make copies of the content of pPage and its siblings into aOld[].
2000 ** The rest of this function will use data from the copies rather
2001 ** that the original pages since the original pages will be in the
2002 ** process of being overwritten.
2003 */
2004 for(i=0; i<nOld; i++){
2005 copyPage(&aOld[i], apOld[i]);
2006 rc = freePage(pBt, apOld[i], pgnoOld[i]);
2007 if( rc ) goto balance_cleanup;
drhdd793422001-06-28 01:54:48 +00002008 sqlitepager_unref(apOld[i]);
drh14acc042001-06-10 19:56:58 +00002009 apOld[i] = &aOld[i];
2010 }
2011
2012 /*
2013 ** Load pointers to all cells on sibling pages and the divider cells
2014 ** into the local apCell[] array. Make copies of the divider cells
2015 ** into aTemp[] and remove the the divider Cells from pParent.
drh8b2f49b2001-06-08 00:21:52 +00002016 */
2017 nCell = 0;
2018 for(i=0; i<nOld; i++){
2019 MemPage *pOld = apOld[i];
2020 for(j=0; j<pOld->nCell; j++){
drh14acc042001-06-10 19:56:58 +00002021 apCell[nCell] = pOld->apCell[j];
2022 szCell[nCell] = cellSize(apCell[nCell]);
2023 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00002024 }
2025 if( i<nOld-1 ){
drh14acc042001-06-10 19:56:58 +00002026 szCell[nCell] = cellSize(apDiv[i]);
drh8c42ca92001-06-22 19:15:00 +00002027 memcpy(&aTemp[i], apDiv[i], szCell[nCell]);
drh14acc042001-06-10 19:56:58 +00002028 apCell[nCell] = &aTemp[i];
2029 dropCell(pParent, nxDiv, szCell[nCell]);
2030 assert( apCell[nCell]->h.leftChild==pgnoOld[i] );
2031 apCell[nCell]->h.leftChild = pOld->u.hdr.rightChild;
2032 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00002033 }
2034 }
2035
2036 /*
drh6019e162001-07-02 17:51:45 +00002037 ** Figure out the number of pages needed to hold all nCell cells.
2038 ** Store this number in "k". Also compute szNew[] which is the total
2039 ** size of all cells on the i-th page and cntNew[] which is the index
2040 ** in apCell[] of the cell that divides path i from path i+1.
2041 ** cntNew[k] should equal nCell.
2042 **
2043 ** This little patch of code is critical for keeping the tree
2044 ** balanced.
drh8b2f49b2001-06-08 00:21:52 +00002045 */
2046 totalSize = 0;
2047 for(i=0; i<nCell; i++){
drh14acc042001-06-10 19:56:58 +00002048 totalSize += szCell[i];
drh8b2f49b2001-06-08 00:21:52 +00002049 }
drh6019e162001-07-02 17:51:45 +00002050 for(subtotal=k=i=0; i<nCell; i++){
2051 subtotal += szCell[i];
2052 if( subtotal > USABLE_SPACE ){
2053 szNew[k] = subtotal - szCell[i];
2054 cntNew[k] = i;
2055 subtotal = 0;
2056 k++;
2057 }
2058 }
2059 szNew[k] = subtotal;
2060 cntNew[k] = nCell;
2061 k++;
2062 for(i=k-1; i>0; i--){
2063 while( szNew[i]<USABLE_SPACE/2 ){
2064 cntNew[i-1]--;
2065 assert( cntNew[i-1]>0 );
2066 szNew[i] += szCell[cntNew[i-1]];
2067 szNew[i-1] -= szCell[cntNew[i-1]-1];
2068 }
2069 }
2070 assert( cntNew[0]>0 );
drh8b2f49b2001-06-08 00:21:52 +00002071
2072 /*
drh6019e162001-07-02 17:51:45 +00002073 ** Allocate k new pages
drh8b2f49b2001-06-08 00:21:52 +00002074 */
drh14acc042001-06-10 19:56:58 +00002075 for(i=0; i<k; i++){
drh8b2f49b2001-06-08 00:21:52 +00002076 rc = allocatePage(pBt, &apNew[i], &pgnoNew[i]);
drh14acc042001-06-10 19:56:58 +00002077 if( rc ) goto balance_cleanup;
2078 nNew++;
drh8b2f49b2001-06-08 00:21:52 +00002079 zeroPage(apNew[i]);
drh6019e162001-07-02 17:51:45 +00002080 apNew[i]->isInit = 1;
drh8b2f49b2001-06-08 00:21:52 +00002081 }
2082
2083 /*
drh14acc042001-06-10 19:56:58 +00002084 ** Evenly distribute the data in apCell[] across the new pages.
2085 ** Insert divider cells into pParent as necessary.
2086 */
2087 j = 0;
2088 for(i=0; i<nNew; i++){
2089 MemPage *pNew = apNew[i];
drh6019e162001-07-02 17:51:45 +00002090 while( j<cntNew[i] ){
2091 assert( pNew->nFree>=szCell[j] );
drh14acc042001-06-10 19:56:58 +00002092 if( pCur && iCur==j ){ pCur->pPage = pNew; pCur->idx = pNew->nCell; }
2093 insertCell(pNew, pNew->nCell, apCell[j], szCell[j]);
2094 j++;
2095 }
drh6019e162001-07-02 17:51:45 +00002096 assert( pNew->nCell>0 );
drh14acc042001-06-10 19:56:58 +00002097 assert( !pNew->isOverfull );
2098 relinkCellList(pNew);
2099 if( i<nNew-1 && j<nCell ){
2100 pNew->u.hdr.rightChild = apCell[j]->h.leftChild;
2101 apCell[j]->h.leftChild = pgnoNew[i];
2102 if( pCur && iCur==j ){ pCur->pPage = pParent; pCur->idx = nxDiv; }
2103 insertCell(pParent, nxDiv, apCell[j], szCell[j]);
2104 j++;
2105 nxDiv++;
2106 }
2107 }
drh6019e162001-07-02 17:51:45 +00002108 assert( j==nCell );
drh14acc042001-06-10 19:56:58 +00002109 apNew[nNew-1]->u.hdr.rightChild = apOld[nOld-1]->u.hdr.rightChild;
2110 if( nxDiv==pParent->nCell ){
2111 pParent->u.hdr.rightChild = pgnoNew[nNew-1];
2112 }else{
2113 pParent->apCell[nxDiv]->h.leftChild = pgnoNew[nNew-1];
2114 }
2115 if( pCur ){
drh3fc190c2001-09-14 03:24:23 +00002116 if( j<=iCur && pCur->pPage==pParent && pCur->idx>idxDiv[nOld-1] ){
2117 assert( pCur->pPage==pOldCurPage );
2118 pCur->idx += nNew - nOld;
2119 }else{
2120 assert( pOldCurPage!=0 );
2121 sqlitepager_ref(pCur->pPage);
2122 sqlitepager_unref(pOldCurPage);
2123 }
drh14acc042001-06-10 19:56:58 +00002124 }
2125
2126 /*
2127 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00002128 */
2129 for(i=0; i<nNew; i++){
drh14acc042001-06-10 19:56:58 +00002130 reparentChildPages(pBt->pPager, apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002131 }
drh14acc042001-06-10 19:56:58 +00002132 reparentChildPages(pBt->pPager, pParent);
drh8b2f49b2001-06-08 00:21:52 +00002133
2134 /*
drh14acc042001-06-10 19:56:58 +00002135 ** balance the parent page.
drh8b2f49b2001-06-08 00:21:52 +00002136 */
drh5edc3122001-09-13 21:53:09 +00002137 rc = balance(pBt, pParent, pCur);
drh8b2f49b2001-06-08 00:21:52 +00002138
2139 /*
drh14acc042001-06-10 19:56:58 +00002140 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00002141 */
drh14acc042001-06-10 19:56:58 +00002142balance_cleanup:
drh9ca7d3b2001-06-28 11:50:21 +00002143 if( extraUnref ){
2144 sqlitepager_unref(extraUnref);
2145 }
drh8b2f49b2001-06-08 00:21:52 +00002146 for(i=0; i<nOld; i++){
drhdd793422001-06-28 01:54:48 +00002147 if( apOld[i]!=&aOld[i] ) sqlitepager_unref(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00002148 }
drh14acc042001-06-10 19:56:58 +00002149 for(i=0; i<nNew; i++){
2150 sqlitepager_unref(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002151 }
drh14acc042001-06-10 19:56:58 +00002152 if( pCur && pCur->pPage==0 ){
2153 pCur->pPage = pParent;
2154 pCur->idx = 0;
2155 }else{
2156 sqlitepager_unref(pParent);
drh8b2f49b2001-06-08 00:21:52 +00002157 }
2158 return rc;
2159}
2160
2161/*
drh3b7511c2001-05-26 13:15:44 +00002162** Insert a new record into the BTree. The key is given by (pKey,nKey)
2163** and the data is given by (pData,nData). The cursor is used only to
2164** define what database the record should be inserted into. The cursor
drh14acc042001-06-10 19:56:58 +00002165** is left pointing at the new record.
drh3b7511c2001-05-26 13:15:44 +00002166*/
2167int sqliteBtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00002168 BtCursor *pCur, /* Insert data into the table of this cursor */
drhbe0072d2001-09-13 14:46:09 +00002169 const void *pKey, int nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00002170 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00002171){
2172 Cell newCell;
2173 int rc;
2174 int loc;
drh14acc042001-06-10 19:56:58 +00002175 int szNew;
drh3b7511c2001-05-26 13:15:44 +00002176 MemPage *pPage;
2177 Btree *pBt = pCur->pBt;
2178
drhecdc7532001-09-23 02:35:53 +00002179 if( pCur->pPage==0 ){
2180 return SQLITE_ABORT; /* A rollback destroyed this cursor */
2181 }
drh5edc3122001-09-13 21:53:09 +00002182 if( !pCur->pBt->inTrans || nKey+nData==0 ){
drh8b2f49b2001-06-08 00:21:52 +00002183 return SQLITE_ERROR; /* Must start a transaction first */
2184 }
drhecdc7532001-09-23 02:35:53 +00002185 if( !pCur->wrFlag ){
2186 return SQLITE_PERM; /* Cursor not open for writing */
2187 }
drh14acc042001-06-10 19:56:58 +00002188 rc = sqliteBtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00002189 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002190 pPage = pCur->pPage;
2191 rc = sqlitepager_write(pPage);
drhbd03cae2001-06-02 02:40:57 +00002192 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00002193 rc = fillInCell(pBt, &newCell, pKey, nKey, pData, nData);
2194 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002195 szNew = cellSize(&newCell);
drh3b7511c2001-05-26 13:15:44 +00002196 if( loc==0 ){
drh14acc042001-06-10 19:56:58 +00002197 newCell.h.leftChild = pPage->apCell[pCur->idx]->h.leftChild;
2198 rc = clearCell(pBt, pPage->apCell[pCur->idx]);
drh5e2f8b92001-05-28 00:41:15 +00002199 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002200 dropCell(pPage, pCur->idx, cellSize(pPage->apCell[pCur->idx]));
drh7c717f72001-06-24 20:39:41 +00002201 }else if( loc<0 && pPage->nCell>0 ){
drh14acc042001-06-10 19:56:58 +00002202 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
2203 pCur->idx++;
2204 }else{
2205 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
drh3b7511c2001-05-26 13:15:44 +00002206 }
drh7c717f72001-06-24 20:39:41 +00002207 insertCell(pPage, pCur->idx, &newCell, szNew);
drh14acc042001-06-10 19:56:58 +00002208 rc = balance(pCur->pBt, pPage, pCur);
drh3fc190c2001-09-14 03:24:23 +00002209 /* sqliteBtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
2210 /* fflush(stdout); */
drh5e2f8b92001-05-28 00:41:15 +00002211 return rc;
2212}
2213
2214/*
drhbd03cae2001-06-02 02:40:57 +00002215** Delete the entry that the cursor is pointing to.
drh5e2f8b92001-05-28 00:41:15 +00002216**
drhbd03cae2001-06-02 02:40:57 +00002217** The cursor is left pointing at either the next or the previous
2218** entry. If the cursor is left pointing to the next entry, then
2219** the pCur->bSkipNext flag is set which forces the next call to
2220** sqliteBtreeNext() to be a no-op. That way, you can always call
2221** sqliteBtreeNext() after a delete and the cursor will be left
2222** pointing to the first entry after the deleted entry.
drh3b7511c2001-05-26 13:15:44 +00002223*/
2224int sqliteBtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00002225 MemPage *pPage = pCur->pPage;
2226 Cell *pCell;
2227 int rc;
drh8c42ca92001-06-22 19:15:00 +00002228 Pgno pgnoChild;
drh8b2f49b2001-06-08 00:21:52 +00002229
drhecdc7532001-09-23 02:35:53 +00002230 if( pCur->pPage==0 ){
2231 return SQLITE_ABORT; /* A rollback destroyed this cursor */
2232 }
drh8b2f49b2001-06-08 00:21:52 +00002233 if( !pCur->pBt->inTrans ){
2234 return SQLITE_ERROR; /* Must start a transaction first */
2235 }
drhbd03cae2001-06-02 02:40:57 +00002236 if( pCur->idx >= pPage->nCell ){
2237 return SQLITE_ERROR; /* The cursor is not pointing to anything */
2238 }
drhecdc7532001-09-23 02:35:53 +00002239 if( !pCur->wrFlag ){
2240 return SQLITE_PERM; /* Did not open this cursor for writing */
2241 }
drhbd03cae2001-06-02 02:40:57 +00002242 rc = sqlitepager_write(pPage);
2243 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002244 pCell = pPage->apCell[pCur->idx];
drh14acc042001-06-10 19:56:58 +00002245 pgnoChild = pCell->h.leftChild;
drh8c42ca92001-06-22 19:15:00 +00002246 clearCell(pCur->pBt, pCell);
drh14acc042001-06-10 19:56:58 +00002247 if( pgnoChild ){
2248 /*
drh5e00f6c2001-09-13 13:46:56 +00002249 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00002250 ** do something we will leave a hole on an internal page.
2251 ** We have to fill the hole by moving in a cell from a leaf. The
2252 ** next Cell after the one to be deleted is guaranteed to exist and
2253 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00002254 */
drh14acc042001-06-10 19:56:58 +00002255 BtCursor leafCur;
2256 Cell *pNext;
2257 int szNext;
2258 getTempCursor(pCur, &leafCur);
2259 rc = sqliteBtreeNext(&leafCur, 0);
2260 if( rc!=SQLITE_OK ){
2261 return SQLITE_CORRUPT;
drh5e2f8b92001-05-28 00:41:15 +00002262 }
drh6019e162001-07-02 17:51:45 +00002263 rc = sqlitepager_write(leafCur.pPage);
2264 if( rc ) return rc;
drh9ca7d3b2001-06-28 11:50:21 +00002265 dropCell(pPage, pCur->idx, cellSize(pCell));
drh8c42ca92001-06-22 19:15:00 +00002266 pNext = leafCur.pPage->apCell[leafCur.idx];
drh14acc042001-06-10 19:56:58 +00002267 szNext = cellSize(pNext);
drh8c42ca92001-06-22 19:15:00 +00002268 pNext->h.leftChild = pgnoChild;
drh14acc042001-06-10 19:56:58 +00002269 insertCell(pPage, pCur->idx, pNext, szNext);
2270 rc = balance(pCur->pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002271 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002272 pCur->bSkipNext = 1;
drh14acc042001-06-10 19:56:58 +00002273 dropCell(leafCur.pPage, leafCur.idx, szNext);
drhf5bf0a72001-11-23 00:24:12 +00002274 rc = balance(pCur->pBt, leafCur.pPage, pCur);
drh8c42ca92001-06-22 19:15:00 +00002275 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00002276 }else{
drh9ca7d3b2001-06-28 11:50:21 +00002277 dropCell(pPage, pCur->idx, cellSize(pCell));
drh5edc3122001-09-13 21:53:09 +00002278 if( pCur->idx>=pPage->nCell ){
2279 pCur->idx = pPage->nCell-1;
drhf5bf0a72001-11-23 00:24:12 +00002280 if( pCur->idx<0 ){
2281 pCur->idx = 0;
2282 pCur->bSkipNext = 1;
2283 }else{
2284 pCur->bSkipNext = 0;
2285 }
drh6019e162001-07-02 17:51:45 +00002286 }else{
2287 pCur->bSkipNext = 1;
2288 }
drh14acc042001-06-10 19:56:58 +00002289 rc = balance(pCur->pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002290 }
drh5e2f8b92001-05-28 00:41:15 +00002291 return rc;
drh3b7511c2001-05-26 13:15:44 +00002292}
drh8b2f49b2001-06-08 00:21:52 +00002293
2294/*
drhc6b52df2002-01-04 03:09:29 +00002295** Create a new BTree table. Write into *piTable the page
2296** number for the root page of the new table.
2297**
2298** In the current implementation, BTree tables and BTree indices are the
2299** the same. But in the future, we may change this so that BTree tables
2300** are restricted to having a 4-byte integer key and arbitrary data and
2301** BTree indices are restricted to having an arbitrary key and no data.
drh8b2f49b2001-06-08 00:21:52 +00002302*/
2303int sqliteBtreeCreateTable(Btree *pBt, int *piTable){
2304 MemPage *pRoot;
2305 Pgno pgnoRoot;
2306 int rc;
2307 if( !pBt->inTrans ){
2308 return SQLITE_ERROR; /* Must start a transaction first */
2309 }
2310 rc = allocatePage(pBt, &pRoot, &pgnoRoot);
2311 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002312 assert( sqlitepager_iswriteable(pRoot) );
drh8b2f49b2001-06-08 00:21:52 +00002313 zeroPage(pRoot);
2314 sqlitepager_unref(pRoot);
2315 *piTable = (int)pgnoRoot;
2316 return SQLITE_OK;
2317}
2318
2319/*
drhc6b52df2002-01-04 03:09:29 +00002320** Create a new BTree index. Write into *piTable the page
2321** number for the root page of the new index.
2322**
2323** In the current implementation, BTree tables and BTree indices are the
2324** the same. But in the future, we may change this so that BTree tables
2325** are restricted to having a 4-byte integer key and arbitrary data and
2326** BTree indices are restricted to having an arbitrary key and no data.
2327*/
2328int sqliteBtreeCreateIndex(Btree *pBt, int *piIndex){
2329 MemPage *pRoot;
2330 Pgno pgnoRoot;
2331 int rc;
2332 if( !pBt->inTrans ){
2333 return SQLITE_ERROR; /* Must start a transaction first */
2334 }
2335 rc = allocatePage(pBt, &pRoot, &pgnoRoot);
2336 if( rc ) return rc;
2337 assert( sqlitepager_iswriteable(pRoot) );
2338 zeroPage(pRoot);
2339 sqlitepager_unref(pRoot);
2340 *piIndex = (int)pgnoRoot;
2341 return SQLITE_OK;
2342}
2343
2344/*
drh8b2f49b2001-06-08 00:21:52 +00002345** Erase the given database page and all its children. Return
2346** the page to the freelist.
2347*/
drh2aa679f2001-06-25 02:11:07 +00002348static int clearDatabasePage(Btree *pBt, Pgno pgno, int freePageFlag){
drh8b2f49b2001-06-08 00:21:52 +00002349 MemPage *pPage;
2350 int rc;
drh8b2f49b2001-06-08 00:21:52 +00002351 Cell *pCell;
2352 int idx;
2353
drh8c42ca92001-06-22 19:15:00 +00002354 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pPage);
drh8b2f49b2001-06-08 00:21:52 +00002355 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002356 rc = sqlitepager_write(pPage);
2357 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002358 idx = pPage->u.hdr.firstCell;
drh8b2f49b2001-06-08 00:21:52 +00002359 while( idx>0 ){
drh14acc042001-06-10 19:56:58 +00002360 pCell = (Cell*)&pPage->u.aDisk[idx];
drh8b2f49b2001-06-08 00:21:52 +00002361 idx = pCell->h.iNext;
2362 if( pCell->h.leftChild ){
drh2aa679f2001-06-25 02:11:07 +00002363 rc = clearDatabasePage(pBt, pCell->h.leftChild, 1);
drh8b2f49b2001-06-08 00:21:52 +00002364 if( rc ) return rc;
2365 }
drh8c42ca92001-06-22 19:15:00 +00002366 rc = clearCell(pBt, pCell);
drh8b2f49b2001-06-08 00:21:52 +00002367 if( rc ) return rc;
2368 }
drh2aa679f2001-06-25 02:11:07 +00002369 if( pPage->u.hdr.rightChild ){
2370 rc = clearDatabasePage(pBt, pPage->u.hdr.rightChild, 1);
2371 if( rc ) return rc;
2372 }
2373 if( freePageFlag ){
2374 rc = freePage(pBt, pPage, pgno);
2375 }else{
2376 zeroPage(pPage);
2377 }
drhdd793422001-06-28 01:54:48 +00002378 sqlitepager_unref(pPage);
drh2aa679f2001-06-25 02:11:07 +00002379 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002380}
2381
2382/*
2383** Delete all information from a single table in the database.
2384*/
2385int sqliteBtreeClearTable(Btree *pBt, int iTable){
2386 int rc;
drh5a2c2c22001-11-21 02:21:11 +00002387 ptr nLock;
drh8b2f49b2001-06-08 00:21:52 +00002388 if( !pBt->inTrans ){
2389 return SQLITE_ERROR; /* Must start a transaction first */
2390 }
drh5a2c2c22001-11-21 02:21:11 +00002391 nLock = (ptr)sqliteHashFind(&pBt->locks, 0, iTable);
drhecdc7532001-09-23 02:35:53 +00002392 if( nLock ){
2393 return SQLITE_LOCKED;
2394 }
drh2aa679f2001-06-25 02:11:07 +00002395 rc = clearDatabasePage(pBt, (Pgno)iTable, 0);
drh8b2f49b2001-06-08 00:21:52 +00002396 if( rc ){
2397 sqliteBtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00002398 }
drh8c42ca92001-06-22 19:15:00 +00002399 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002400}
2401
2402/*
2403** Erase all information in a table and add the root of the table to
2404** the freelist. Except, the root of the principle table (the one on
2405** page 2) is never added to the freelist.
2406*/
2407int sqliteBtreeDropTable(Btree *pBt, int iTable){
2408 int rc;
2409 MemPage *pPage;
2410 if( !pBt->inTrans ){
2411 return SQLITE_ERROR; /* Must start a transaction first */
2412 }
drh8c42ca92001-06-22 19:15:00 +00002413 rc = sqlitepager_get(pBt->pPager, (Pgno)iTable, (void**)&pPage);
drh2aa679f2001-06-25 02:11:07 +00002414 if( rc ) return rc;
2415 rc = sqliteBtreeClearTable(pBt, iTable);
2416 if( rc ) return rc;
2417 if( iTable>2 ){
2418 rc = freePage(pBt, pPage, iTable);
2419 }else{
2420 zeroPage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00002421 }
drhdd793422001-06-28 01:54:48 +00002422 sqlitepager_unref(pPage);
drh8b2f49b2001-06-08 00:21:52 +00002423 return rc;
2424}
2425
2426/*
2427** Read the meta-information out of a database file.
2428*/
2429int sqliteBtreeGetMeta(Btree *pBt, int *aMeta){
2430 PageOne *pP1;
2431 int rc;
2432
drh8c42ca92001-06-22 19:15:00 +00002433 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00002434 if( rc ) return rc;
drh2aa679f2001-06-25 02:11:07 +00002435 aMeta[0] = pP1->nFree;
2436 memcpy(&aMeta[1], pP1->aMeta, sizeof(pP1->aMeta));
drh8b2f49b2001-06-08 00:21:52 +00002437 sqlitepager_unref(pP1);
2438 return SQLITE_OK;
2439}
2440
2441/*
2442** Write meta-information back into the database.
2443*/
2444int sqliteBtreeUpdateMeta(Btree *pBt, int *aMeta){
2445 PageOne *pP1;
2446 int rc;
2447 if( !pBt->inTrans ){
2448 return SQLITE_ERROR; /* Must start a transaction first */
2449 }
2450 pP1 = pBt->page1;
2451 rc = sqlitepager_write(pP1);
drh2aa679f2001-06-25 02:11:07 +00002452 if( rc ) return rc;
2453 memcpy(pP1->aMeta, &aMeta[1], sizeof(pP1->aMeta));
drh8b2f49b2001-06-08 00:21:52 +00002454 return SQLITE_OK;
2455}
drh8c42ca92001-06-22 19:15:00 +00002456
drh5eddca62001-06-30 21:53:53 +00002457/******************************************************************************
2458** The complete implementation of the BTree subsystem is above this line.
2459** All the code the follows is for testing and troubleshooting the BTree
2460** subsystem. None of the code that follows is used during normal operation.
drh1bffb9c2002-02-03 17:37:36 +00002461** All of the following code is omitted if the library is compiled with
drh8c87e6e2002-02-03 19:15:02 +00002462** the -DNDEBUG2=1 compiler option.
drh5eddca62001-06-30 21:53:53 +00002463******************************************************************************/
drh8c87e6e2002-02-03 19:15:02 +00002464#ifndef NDEBUG2
drh5eddca62001-06-30 21:53:53 +00002465
drh8c42ca92001-06-22 19:15:00 +00002466/*
2467** Print a disassembly of the given page on standard output. This routine
2468** is used for debugging and testing only.
2469*/
drh6019e162001-07-02 17:51:45 +00002470int sqliteBtreePageDump(Btree *pBt, int pgno, int recursive){
drh8c42ca92001-06-22 19:15:00 +00002471 int rc;
2472 MemPage *pPage;
2473 int i, j;
2474 int nFree;
2475 u16 idx;
2476 char range[20];
2477 unsigned char payload[20];
2478 rc = sqlitepager_get(pBt->pPager, (Pgno)pgno, (void**)&pPage);
2479 if( rc ){
2480 return rc;
2481 }
drh6019e162001-07-02 17:51:45 +00002482 if( recursive ) printf("PAGE %d:\n", pgno);
drh8c42ca92001-06-22 19:15:00 +00002483 i = 0;
2484 idx = pPage->u.hdr.firstCell;
2485 while( idx>0 && idx<=SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2486 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
2487 int sz = cellSize(pCell);
2488 sprintf(range,"%d..%d", idx, idx+sz-1);
drh80ff32f2001-11-04 18:32:46 +00002489 sz = NKEY(pCell->h) + NDATA(pCell->h);
drh8c42ca92001-06-22 19:15:00 +00002490 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
2491 memcpy(payload, pCell->aPayload, sz);
2492 for(j=0; j<sz; j++){
2493 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
2494 }
2495 payload[sz] = 0;
2496 printf(
drh6019e162001-07-02 17:51:45 +00002497 "cell %2d: i=%-10s chld=%-4d nk=%-4d nd=%-4d payload=%s\n",
drh80ff32f2001-11-04 18:32:46 +00002498 i, range, (int)pCell->h.leftChild, NKEY(pCell->h), NDATA(pCell->h),
drh2aa679f2001-06-25 02:11:07 +00002499 payload
drh8c42ca92001-06-22 19:15:00 +00002500 );
drh6019e162001-07-02 17:51:45 +00002501 if( pPage->isInit && pPage->apCell[i]!=pCell ){
drh2aa679f2001-06-25 02:11:07 +00002502 printf("**** apCell[%d] does not match on prior entry ****\n", i);
2503 }
drh7c717f72001-06-24 20:39:41 +00002504 i++;
drh8c42ca92001-06-22 19:15:00 +00002505 idx = pCell->h.iNext;
2506 }
2507 if( idx!=0 ){
2508 printf("ERROR: next cell index out of range: %d\n", idx);
2509 }
2510 printf("right_child: %d\n", pPage->u.hdr.rightChild);
2511 nFree = 0;
2512 i = 0;
2513 idx = pPage->u.hdr.firstFree;
2514 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2515 FreeBlk *p = (FreeBlk*)&pPage->u.aDisk[idx];
2516 sprintf(range,"%d..%d", idx, idx+p->iSize-1);
2517 nFree += p->iSize;
2518 printf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
2519 i, range, p->iSize, nFree);
2520 idx = p->iNext;
drh2aa679f2001-06-25 02:11:07 +00002521 i++;
drh8c42ca92001-06-22 19:15:00 +00002522 }
2523 if( idx!=0 ){
2524 printf("ERROR: next freeblock index out of range: %d\n", idx);
2525 }
drh6019e162001-07-02 17:51:45 +00002526 if( recursive && pPage->u.hdr.rightChild!=0 ){
2527 idx = pPage->u.hdr.firstCell;
2528 while( idx>0 && idx<SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2529 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
2530 sqliteBtreePageDump(pBt, pCell->h.leftChild, 1);
2531 idx = pCell->h.iNext;
2532 }
2533 sqliteBtreePageDump(pBt, pPage->u.hdr.rightChild, 1);
2534 }
drh8c42ca92001-06-22 19:15:00 +00002535 sqlitepager_unref(pPage);
2536 return SQLITE_OK;
2537}
drh8c42ca92001-06-22 19:15:00 +00002538
drh8c42ca92001-06-22 19:15:00 +00002539/*
drh2aa679f2001-06-25 02:11:07 +00002540** Fill aResult[] with information about the entry and page that the
2541** cursor is pointing to.
2542**
2543** aResult[0] = The page number
2544** aResult[1] = The entry number
2545** aResult[2] = Total number of entries on this page
2546** aResult[3] = Size of this entry
2547** aResult[4] = Number of free bytes on this page
2548** aResult[5] = Number of free blocks on the page
2549** aResult[6] = Page number of the left child of this entry
2550** aResult[7] = Page number of the right child for the whole page
drh5eddca62001-06-30 21:53:53 +00002551**
2552** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00002553*/
2554int sqliteBtreeCursorDump(BtCursor *pCur, int *aResult){
drh2aa679f2001-06-25 02:11:07 +00002555 int cnt, idx;
2556 MemPage *pPage = pCur->pPage;
2557 aResult[0] = sqlitepager_pagenumber(pPage);
drh8c42ca92001-06-22 19:15:00 +00002558 aResult[1] = pCur->idx;
drh2aa679f2001-06-25 02:11:07 +00002559 aResult[2] = pPage->nCell;
2560 if( pCur->idx>=0 && pCur->idx<pPage->nCell ){
2561 aResult[3] = cellSize(pPage->apCell[pCur->idx]);
2562 aResult[6] = pPage->apCell[pCur->idx]->h.leftChild;
2563 }else{
2564 aResult[3] = 0;
2565 aResult[6] = 0;
2566 }
2567 aResult[4] = pPage->nFree;
2568 cnt = 0;
2569 idx = pPage->u.hdr.firstFree;
2570 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2571 cnt++;
2572 idx = ((FreeBlk*)&pPage->u.aDisk[idx])->iNext;
2573 }
2574 aResult[5] = cnt;
2575 aResult[7] = pPage->u.hdr.rightChild;
drh8c42ca92001-06-22 19:15:00 +00002576 return SQLITE_OK;
2577}
drhdd793422001-06-28 01:54:48 +00002578
drhdd793422001-06-28 01:54:48 +00002579/*
drh5eddca62001-06-30 21:53:53 +00002580** Return the pager associated with a BTree. This routine is used for
2581** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00002582*/
2583Pager *sqliteBtreePager(Btree *pBt){
2584 return pBt->pPager;
2585}
drh5eddca62001-06-30 21:53:53 +00002586
2587/*
2588** This structure is passed around through all the sanity checking routines
2589** in order to keep track of some global state information.
2590*/
2591typedef struct SanityCheck SanityCheck;
2592struct SanityCheck {
drh100569d2001-10-02 13:01:48 +00002593 Btree *pBt; /* The tree being checked out */
2594 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
2595 int nPage; /* Number of pages in the database */
2596 int *anRef; /* Number of times each page is referenced */
2597 int nTreePage; /* Number of BTree pages */
2598 int nByte; /* Number of bytes of data stored on BTree pages */
2599 char *zErrMsg; /* An error message. NULL of no errors seen. */
drh5eddca62001-06-30 21:53:53 +00002600};
2601
2602/*
2603** Append a message to the error message string.
2604*/
2605static void checkAppendMsg(SanityCheck *pCheck, char *zMsg1, char *zMsg2){
2606 if( pCheck->zErrMsg ){
2607 char *zOld = pCheck->zErrMsg;
2608 pCheck->zErrMsg = 0;
2609 sqliteSetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, 0);
2610 sqliteFree(zOld);
2611 }else{
2612 sqliteSetString(&pCheck->zErrMsg, zMsg1, zMsg2, 0);
2613 }
2614}
2615
2616/*
2617** Add 1 to the reference count for page iPage. If this is the second
2618** reference to the page, add an error message to pCheck->zErrMsg.
2619** Return 1 if there are 2 ore more references to the page and 0 if
2620** if this is the first reference to the page.
2621**
2622** Also check that the page number is in bounds.
2623*/
2624static int checkRef(SanityCheck *pCheck, int iPage, char *zContext){
2625 if( iPage==0 ) return 1;
2626 if( iPage>pCheck->nPage ){
2627 char zBuf[100];
2628 sprintf(zBuf, "invalid page number %d", iPage);
2629 checkAppendMsg(pCheck, zContext, zBuf);
2630 return 1;
2631 }
2632 if( pCheck->anRef[iPage]==1 ){
2633 char zBuf[100];
2634 sprintf(zBuf, "2nd reference to page %d", iPage);
2635 checkAppendMsg(pCheck, zContext, zBuf);
2636 return 1;
2637 }
2638 return (pCheck->anRef[iPage]++)>1;
2639}
2640
2641/*
2642** Check the integrity of the freelist or of an overflow page list.
2643** Verify that the number of pages on the list is N.
2644*/
2645static void checkList(SanityCheck *pCheck, int iPage, int N, char *zContext){
2646 char zMsg[100];
2647 while( N-- ){
2648 OverflowPage *pOvfl;
2649 if( iPage<1 ){
2650 sprintf(zMsg, "%d pages missing from overflow list", N+1);
2651 checkAppendMsg(pCheck, zContext, zMsg);
2652 break;
2653 }
2654 if( checkRef(pCheck, iPage, zContext) ) break;
2655 if( sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
2656 sprintf(zMsg, "failed to get page %d", iPage);
2657 checkAppendMsg(pCheck, zContext, zMsg);
2658 break;
2659 }
2660 iPage = (int)pOvfl->iNext;
2661 sqlitepager_unref(pOvfl);
2662 }
2663}
2664
2665/*
drh1bffb9c2002-02-03 17:37:36 +00002666** Return negative if zKey1<zKey2.
2667** Return zero if zKey1==zKey2.
2668** Return positive if zKey1>zKey2.
2669*/
2670static int keyCompare(
2671 const char *zKey1, int nKey1,
2672 const char *zKey2, int nKey2
2673){
2674 int min = nKey1>nKey2 ? nKey2 : nKey1;
2675 int c = memcmp(zKey1, zKey2, min);
2676 if( c==0 ){
2677 c = nKey1 - nKey2;
2678 }
2679 return c;
2680}
2681
2682/*
drh5eddca62001-06-30 21:53:53 +00002683** Do various sanity checks on a single page of a tree. Return
2684** the tree depth. Root pages return 0. Parents of root pages
2685** return 1, and so forth.
2686**
2687** These checks are done:
2688**
2689** 1. Make sure that cells and freeblocks do not overlap
2690** but combine to completely cover the page.
2691** 2. Make sure cell keys are in order.
2692** 3. Make sure no key is less than or equal to zLowerBound.
2693** 4. Make sure no key is greater than or equal to zUpperBound.
2694** 5. Check the integrity of overflow pages.
2695** 6. Recursively call checkTreePage on all children.
2696** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00002697** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00002698** the root of the tree.
2699*/
2700static int checkTreePage(
2701 SanityCheck *pCheck, /* Context for the sanity check */
2702 int iPage, /* Page number of the page to check */
2703 MemPage *pParent, /* Parent page */
2704 char *zParentContext, /* Parent context */
2705 char *zLowerBound, /* All keys should be greater than this, if not NULL */
drh1bffb9c2002-02-03 17:37:36 +00002706 int nLower, /* Number of characters in zLowerBound */
2707 char *zUpperBound, /* All keys should be less than this, if not NULL */
2708 int nUpper /* Number of characters in zUpperBound */
drh5eddca62001-06-30 21:53:53 +00002709){
2710 MemPage *pPage;
2711 int i, rc, depth, d2, pgno;
2712 char *zKey1, *zKey2;
drh1bffb9c2002-02-03 17:37:36 +00002713 int nKey1, nKey2;
drh5eddca62001-06-30 21:53:53 +00002714 BtCursor cur;
2715 char zMsg[100];
2716 char zContext[100];
2717 char hit[SQLITE_PAGE_SIZE];
2718
2719 /* Check that the page exists
2720 */
2721 if( iPage==0 ) return 0;
2722 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
2723 sprintf(zContext, "On tree page %d: ", iPage);
2724 if( (rc = sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pPage))!=0 ){
2725 sprintf(zMsg, "unable to get the page. error code=%d", rc);
2726 checkAppendMsg(pCheck, zContext, zMsg);
2727 return 0;
2728 }
2729 if( (rc = initPage(pPage, (Pgno)iPage, pParent))!=0 ){
2730 sprintf(zMsg, "initPage() returns error code %d", rc);
2731 checkAppendMsg(pCheck, zContext, zMsg);
2732 sqlitepager_unref(pPage);
2733 return 0;
2734 }
2735
2736 /* Check out all the cells.
2737 */
2738 depth = 0;
drh1bffb9c2002-02-03 17:37:36 +00002739 if( zLowerBound ){
2740 zKey1 = sqliteMalloc( nLower+1 );
2741 memcpy(zKey1, zLowerBound, nLower);
2742 zKey1[nLower] = 0;
2743 }else{
2744 zKey1 = 0;
2745 }
2746 nKey1 = nLower;
drh5eddca62001-06-30 21:53:53 +00002747 cur.pPage = pPage;
2748 cur.pBt = pCheck->pBt;
2749 for(i=0; i<pPage->nCell; i++){
2750 Cell *pCell = pPage->apCell[i];
2751 int sz;
2752
2753 /* Check payload overflow pages
2754 */
drh1bffb9c2002-02-03 17:37:36 +00002755 nKey2 = NKEY(pCell->h);
2756 sz = nKey2 + NDATA(pCell->h);
drh5eddca62001-06-30 21:53:53 +00002757 sprintf(zContext, "On page %d cell %d: ", iPage, i);
2758 if( sz>MX_LOCAL_PAYLOAD ){
2759 int nPage = (sz - MX_LOCAL_PAYLOAD + OVERFLOW_SIZE - 1)/OVERFLOW_SIZE;
2760 checkList(pCheck, pCell->ovfl, nPage, zContext);
2761 }
2762
2763 /* Check that keys are in the right order
2764 */
2765 cur.idx = i;
drh1bffb9c2002-02-03 17:37:36 +00002766 zKey2 = sqliteMalloc( nKey2+1 );
2767 getPayload(&cur, 0, nKey2, zKey2);
2768 if( zKey1 && keyCompare(zKey1, nKey1, zKey2, nKey2)>=0 ){
drh5eddca62001-06-30 21:53:53 +00002769 checkAppendMsg(pCheck, zContext, "Key is out of order");
2770 }
2771
2772 /* Check sanity of left child page.
2773 */
2774 pgno = (int)pCell->h.leftChild;
drh1bffb9c2002-02-03 17:37:36 +00002775 d2 = checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zKey2,nKey2);
drh5eddca62001-06-30 21:53:53 +00002776 if( i>0 && d2!=depth ){
2777 checkAppendMsg(pCheck, zContext, "Child page depth differs");
2778 }
2779 depth = d2;
2780 sqliteFree(zKey1);
2781 zKey1 = zKey2;
drh1bffb9c2002-02-03 17:37:36 +00002782 nKey1 = nKey2;
drh5eddca62001-06-30 21:53:53 +00002783 }
2784 pgno = pPage->u.hdr.rightChild;
2785 sprintf(zContext, "On page %d at right child: ", iPage);
drh1bffb9c2002-02-03 17:37:36 +00002786 checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zUpperBound,nUpper);
drh5eddca62001-06-30 21:53:53 +00002787 sqliteFree(zKey1);
2788
2789 /* Check for complete coverage of the page
2790 */
2791 memset(hit, 0, sizeof(hit));
2792 memset(hit, 1, sizeof(PageHdr));
2793 for(i=pPage->u.hdr.firstCell; i>0 && i<SQLITE_PAGE_SIZE; ){
2794 Cell *pCell = (Cell*)&pPage->u.aDisk[i];
2795 int j;
2796 for(j=i+cellSize(pCell)-1; j>=i; j--) hit[j]++;
2797 i = pCell->h.iNext;
2798 }
2799 for(i=pPage->u.hdr.firstFree; i>0 && i<SQLITE_PAGE_SIZE; ){
2800 FreeBlk *pFBlk = (FreeBlk*)&pPage->u.aDisk[i];
2801 int j;
2802 for(j=i+pFBlk->iSize-1; j>=i; j--) hit[j]++;
2803 i = pFBlk->iNext;
2804 }
2805 for(i=0; i<SQLITE_PAGE_SIZE; i++){
2806 if( hit[i]==0 ){
2807 sprintf(zMsg, "Unused space at byte %d of page %d", i, iPage);
2808 checkAppendMsg(pCheck, zMsg, 0);
2809 break;
2810 }else if( hit[i]>1 ){
2811 sprintf(zMsg, "Multiple uses for byte %d of page %d", i, iPage);
2812 checkAppendMsg(pCheck, zMsg, 0);
2813 break;
2814 }
2815 }
2816
2817 /* Check that free space is kept to a minimum
2818 */
drh6019e162001-07-02 17:51:45 +00002819#if 0
2820 if( pParent && pParent->nCell>2 && pPage->nFree>3*SQLITE_PAGE_SIZE/4 ){
drh5eddca62001-06-30 21:53:53 +00002821 sprintf(zMsg, "free space (%d) greater than max (%d)", pPage->nFree,
2822 SQLITE_PAGE_SIZE/3);
2823 checkAppendMsg(pCheck, zContext, zMsg);
2824 }
drh6019e162001-07-02 17:51:45 +00002825#endif
2826
2827 /* Update freespace totals.
2828 */
2829 pCheck->nTreePage++;
2830 pCheck->nByte += USABLE_SPACE - pPage->nFree;
drh5eddca62001-06-30 21:53:53 +00002831
2832 sqlitepager_unref(pPage);
2833 return depth;
2834}
2835
2836/*
2837** This routine does a complete check of the given BTree file. aRoot[] is
2838** an array of pages numbers were each page number is the root page of
2839** a table. nRoot is the number of entries in aRoot.
2840**
2841** If everything checks out, this routine returns NULL. If something is
2842** amiss, an error message is written into memory obtained from malloc()
2843** and a pointer to that error message is returned. The calling function
2844** is responsible for freeing the error message when it is done.
2845*/
2846char *sqliteBtreeSanityCheck(Btree *pBt, int *aRoot, int nRoot){
2847 int i;
2848 int nRef;
2849 SanityCheck sCheck;
2850
2851 nRef = *sqlitepager_stats(pBt->pPager);
drhefc251d2001-07-01 22:12:01 +00002852 if( lockBtree(pBt)!=SQLITE_OK ){
2853 return sqliteStrDup("Unable to acquire a read lock on the database");
2854 }
drh5eddca62001-06-30 21:53:53 +00002855 sCheck.pBt = pBt;
2856 sCheck.pPager = pBt->pPager;
2857 sCheck.nPage = sqlitepager_pagecount(sCheck.pPager);
2858 sCheck.anRef = sqliteMalloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
2859 sCheck.anRef[1] = 1;
2860 for(i=2; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
2861 sCheck.zErrMsg = 0;
2862
2863 /* Check the integrity of the freelist
2864 */
2865 checkList(&sCheck, pBt->page1->freeList, pBt->page1->nFree,"Main freelist: ");
2866
2867 /* Check all the tables.
2868 */
2869 for(i=0; i<nRoot; i++){
drh1bffb9c2002-02-03 17:37:36 +00002870 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
drh5eddca62001-06-30 21:53:53 +00002871 }
2872
2873 /* Make sure every page in the file is referenced
2874 */
2875 for(i=1; i<=sCheck.nPage; i++){
2876 if( sCheck.anRef[i]==0 ){
2877 char zBuf[100];
2878 sprintf(zBuf, "Page %d is never used", i);
2879 checkAppendMsg(&sCheck, zBuf, 0);
2880 }
2881 }
2882
2883 /* Make sure this analysis did not leave any unref() pages
2884 */
drh5e00f6c2001-09-13 13:46:56 +00002885 unlockBtreeIfUnused(pBt);
drh5eddca62001-06-30 21:53:53 +00002886 if( nRef != *sqlitepager_stats(pBt->pPager) ){
2887 char zBuf[100];
2888 sprintf(zBuf,
2889 "Outstanding page count goes from %d to %d during this analysis",
2890 nRef, *sqlitepager_stats(pBt->pPager)
2891 );
2892 checkAppendMsg(&sCheck, zBuf, 0);
2893 }
2894
2895 /* Clean up and report errors.
2896 */
2897 sqliteFree(sCheck.anRef);
2898 return sCheck.zErrMsg;
2899}
2900
drh1bffb9c2002-02-03 17:37:36 +00002901#endif /* !defined(NDEBUG) */