blob: 2dc2d4c6762cf15c9220e7162f2d248f879e04a3 [file] [log] [blame]
drha059ad02001-04-17 20:09:11 +00001/*
2** Copyright (c) 2001 D. Richard Hipp
3**
4** This program is free software; you can redistribute it and/or
5** modify it under the terms of the GNU General Public
6** License as published by the Free Software Foundation; either
7** version 2 of the License, or (at your option) any later version.
8**
9** This program is distributed in the hope that it will be useful,
10** but WITHOUT ANY WARRANTY; without even the implied warranty of
11** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12** General Public License for more details.
13**
14** You should have received a copy of the GNU General Public
15** License along with this library; if not, write to the
16** Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17** Boston, MA 02111-1307, USA.
18**
19** Author contact information:
20** drh@hwaci.com
21** http://www.hwaci.com/drh/
22**
23*************************************************************************
drh092d0352001-09-15 13:15:12 +000024** $Id: btree.c,v 1.28 2001/09/15 13:15:13 drh Exp $
drh8b2f49b2001-06-08 00:21:52 +000025**
26** This file implements a external (disk-based) database using BTrees.
27** For a detailed discussion of BTrees, refer to
28**
29** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
30** "Sorting And Searching", pages 473-480. Addison-Wesley
31** Publishing Company, Reading, Massachusetts.
32**
33** The basic idea is that each page of the file contains N database
34** entries and N+1 pointers to subpages.
35**
36** ----------------------------------------------------------------
37** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N) | Ptr(N+1) |
38** ----------------------------------------------------------------
39**
40** All of the keys on the page that Ptr(0) points to have values less
41** than Key(0). All of the keys on page Ptr(1) and its subpages have
42** values greater than Key(0) and less than Key(1). All of the keys
43** on Ptr(N+1) and its subpages have values greater than Key(N). And
44** so forth.
45**
drh5e00f6c2001-09-13 13:46:56 +000046** Finding a particular key requires reading O(log(M)) pages from the
47** disk where M is the number of entries in the tree.
drh8b2f49b2001-06-08 00:21:52 +000048**
49** In this implementation, a single file can hold one or more separate
50** BTrees. Each BTree is identified by the index of its root page. The
51** key and data for any entry are combined to form the "payload". Up to
52** MX_LOCAL_PAYLOAD bytes of payload can be carried directly on the
53** database page. If the payload is larger than MX_LOCAL_PAYLOAD bytes
54** then surplus bytes are stored on overflow pages. The payload for an
55** entry and the preceding pointer are combined to form a "Cell". Each
56** page has a smaller header which contains the Ptr(N+1) pointer.
57**
58** The first page of the file contains a magic string used to verify that
59** the file really is a valid BTree database, a pointer to a list of unused
60** pages in the file, and some meta information. The root of the first
61** BTree begins on page 2 of the file. (Pages are numbered beginning with
62** 1, not 0.) Thus a minimum database contains 2 pages.
drha059ad02001-04-17 20:09:11 +000063*/
64#include "sqliteInt.h"
65#include "pager.h"
66#include "btree.h"
67#include <assert.h>
68
drh2af926b2001-05-15 00:39:25 +000069
drh2af926b2001-05-15 00:39:25 +000070/*
71** Primitive data types. u32 must be 4 bytes and u16 must be 2 bytes.
drh14acc042001-06-10 19:56:58 +000072** The uptr type must be big enough to hold a pointer.
drh306dc212001-05-21 13:45:10 +000073** Change these typedefs when porting to new architectures.
drh2af926b2001-05-15 00:39:25 +000074*/
drh14acc042001-06-10 19:56:58 +000075typedef unsigned int uptr;
drh092d0352001-09-15 13:15:12 +000076
77/* There are already definedin sqliteInt.h...
78** typedef unsigned int u32;
79** typedef unsigned short int u16;
80** typedef unsigned char u8;
81*/
drh365d68f2001-05-11 11:02:46 +000082
83/*
drh8c42ca92001-06-22 19:15:00 +000084** This macro casts a pointer to an integer. Useful for doing
85** pointer arithmetic.
86*/
drh7c717f72001-06-24 20:39:41 +000087#define Addr(X) ((uptr)X)
drh8c42ca92001-06-22 19:15:00 +000088
89/*
drh365d68f2001-05-11 11:02:46 +000090** Forward declarations of structures used only in this file.
91*/
drhbd03cae2001-06-02 02:40:57 +000092typedef struct PageOne PageOne;
drh2af926b2001-05-15 00:39:25 +000093typedef struct MemPage MemPage;
drh365d68f2001-05-11 11:02:46 +000094typedef struct PageHdr PageHdr;
95typedef struct Cell Cell;
drh3b7511c2001-05-26 13:15:44 +000096typedef struct CellHdr CellHdr;
drh365d68f2001-05-11 11:02:46 +000097typedef struct FreeBlk FreeBlk;
drh2af926b2001-05-15 00:39:25 +000098typedef struct OverflowPage OverflowPage;
99
100/*
101** All structures on a database page are aligned to 4-byte boundries.
102** This routine rounds up a number of bytes to the next multiple of 4.
drh306dc212001-05-21 13:45:10 +0000103**
104** This might need to change for computer architectures that require
105** and 8-byte alignment boundry for structures.
drh2af926b2001-05-15 00:39:25 +0000106*/
107#define ROUNDUP(X) ((X+3) & ~3)
drha059ad02001-04-17 20:09:11 +0000108
drh08ed44e2001-04-29 23:32:55 +0000109/*
drhbd03cae2001-06-02 02:40:57 +0000110** This is a magic string that appears at the beginning of every
drh8c42ca92001-06-22 19:15:00 +0000111** SQLite database in order to identify the file as a real database.
drh08ed44e2001-04-29 23:32:55 +0000112*/
drhbd03cae2001-06-02 02:40:57 +0000113static const char zMagicHeader[] =
drh8c42ca92001-06-22 19:15:00 +0000114 "** This file contains an SQLite 2.0 database **";
drhbd03cae2001-06-02 02:40:57 +0000115#define MAGIC_SIZE (sizeof(zMagicHeader))
drh08ed44e2001-04-29 23:32:55 +0000116
117/*
drh5e00f6c2001-09-13 13:46:56 +0000118** This is a magic integer also used to test the integrity of the database
drh8c42ca92001-06-22 19:15:00 +0000119** file. This integer is used in addition to the string above so that
120** if the file is written on a little-endian architecture and read
121** on a big-endian architectures (or vice versa) we can detect the
122** problem.
123**
124** The number used was obtained at random and has no special
125** significance.
126*/
127#define MAGIC 0xdae37528
128
129/*
drhbd03cae2001-06-02 02:40:57 +0000130** The first page of the database file contains a magic header string
131** to identify the file as an SQLite database file. It also contains
132** a pointer to the first free page of the file. Page 2 contains the
drh8b2f49b2001-06-08 00:21:52 +0000133** root of the principle BTree. The file might contain other BTrees
134** rooted on pages above 2.
135**
136** The first page also contains SQLITE_N_BTREE_META integers that
137** can be used by higher-level routines.
drh08ed44e2001-04-29 23:32:55 +0000138**
drhbd03cae2001-06-02 02:40:57 +0000139** Remember that pages are numbered beginning with 1. (See pager.c
140** for additional information.) Page 0 does not exist and a page
141** number of 0 is used to mean "no such page".
142*/
143struct PageOne {
144 char zMagic[MAGIC_SIZE]; /* String that identifies the file as a database */
drh8c42ca92001-06-22 19:15:00 +0000145 int iMagic; /* Integer to verify correct byte order */
146 Pgno freeList; /* First free page in a list of all free pages */
drh2aa679f2001-06-25 02:11:07 +0000147 int nFree; /* Number of pages on the free list */
148 int aMeta[SQLITE_N_BTREE_META-1]; /* User defined integers */
drhbd03cae2001-06-02 02:40:57 +0000149};
150
151/*
152** Each database page has a header that is an instance of this
153** structure.
drh08ed44e2001-04-29 23:32:55 +0000154**
drh8b2f49b2001-06-08 00:21:52 +0000155** PageHdr.firstFree is 0 if there is no free space on this page.
drh14acc042001-06-10 19:56:58 +0000156** Otherwise, PageHdr.firstFree is the index in MemPage.u.aDisk[] of a
drh8b2f49b2001-06-08 00:21:52 +0000157** FreeBlk structure that describes the first block of free space.
158** All free space is defined by a linked list of FreeBlk structures.
drh08ed44e2001-04-29 23:32:55 +0000159**
drh8b2f49b2001-06-08 00:21:52 +0000160** Data is stored in a linked list of Cell structures. PageHdr.firstCell
drh14acc042001-06-10 19:56:58 +0000161** is the index into MemPage.u.aDisk[] of the first cell on the page. The
drh306dc212001-05-21 13:45:10 +0000162** Cells are kept in sorted order.
drh8b2f49b2001-06-08 00:21:52 +0000163**
164** A Cell contains all information about a database entry and a pointer
165** to a child page that contains other entries less than itself. In
166** other words, the i-th Cell contains both Ptr(i) and Key(i). The
167** right-most pointer of the page is contained in PageHdr.rightChild.
drh08ed44e2001-04-29 23:32:55 +0000168*/
drh365d68f2001-05-11 11:02:46 +0000169struct PageHdr {
drh5e2f8b92001-05-28 00:41:15 +0000170 Pgno rightChild; /* Child page that comes after all cells on this page */
drh14acc042001-06-10 19:56:58 +0000171 u16 firstCell; /* Index in MemPage.u.aDisk[] of the first cell */
172 u16 firstFree; /* Index in MemPage.u.aDisk[] of the first free block */
drh365d68f2001-05-11 11:02:46 +0000173};
drh306dc212001-05-21 13:45:10 +0000174
drh3b7511c2001-05-26 13:15:44 +0000175/*
176** Entries on a page of the database are called "Cells". Each Cell
177** has a header and data. This structure defines the header. The
drhbd03cae2001-06-02 02:40:57 +0000178** key and data (collectively the "payload") follow this header on
179** the database page.
180**
181** A definition of the complete Cell structure is given below. The
drh8c42ca92001-06-22 19:15:00 +0000182** header for the cell must be defined first in order to do some
drhbd03cae2001-06-02 02:40:57 +0000183** of the sizing #defines that follow.
drh3b7511c2001-05-26 13:15:44 +0000184*/
185struct CellHdr {
drh5e2f8b92001-05-28 00:41:15 +0000186 Pgno leftChild; /* Child page that comes before this cell */
drh3b7511c2001-05-26 13:15:44 +0000187 u16 nKey; /* Number of bytes in the key */
drh14acc042001-06-10 19:56:58 +0000188 u16 iNext; /* Index in MemPage.u.aDisk[] of next cell in sorted order */
drh3b7511c2001-05-26 13:15:44 +0000189 u32 nData; /* Number of bytes of data */
drh8c42ca92001-06-22 19:15:00 +0000190};
drh3b7511c2001-05-26 13:15:44 +0000191
192/*
193** The minimum size of a complete Cell. The Cell must contain a header
drhbd03cae2001-06-02 02:40:57 +0000194** and at least 4 bytes of payload.
drh3b7511c2001-05-26 13:15:44 +0000195*/
196#define MIN_CELL_SIZE (sizeof(CellHdr)+4)
197
198/*
199** The maximum number of database entries that can be held in a single
200** page of the database.
201*/
202#define MX_CELL ((SQLITE_PAGE_SIZE-sizeof(PageHdr))/MIN_CELL_SIZE)
203
204/*
drh6019e162001-07-02 17:51:45 +0000205** The amount of usable space on a single page of the BTree. This is the
206** page size minus the overhead of the page header.
207*/
208#define USABLE_SPACE (SQLITE_PAGE_SIZE - sizeof(PageHdr))
209
210/*
drh8c42ca92001-06-22 19:15:00 +0000211** The maximum amount of payload (in bytes) that can be stored locally for
212** a database entry. If the entry contains more data than this, the
drh3b7511c2001-05-26 13:15:44 +0000213** extra goes onto overflow pages.
drhbd03cae2001-06-02 02:40:57 +0000214**
215** This number is chosen so that at least 4 cells will fit on every page.
drh3b7511c2001-05-26 13:15:44 +0000216*/
drh6019e162001-07-02 17:51:45 +0000217#define MX_LOCAL_PAYLOAD ((USABLE_SPACE/4-(sizeof(CellHdr)+sizeof(Pgno)))&~3)
drh3b7511c2001-05-26 13:15:44 +0000218
drh306dc212001-05-21 13:45:10 +0000219/*
220** Data on a database page is stored as a linked list of Cell structures.
drh5e2f8b92001-05-28 00:41:15 +0000221** Both the key and the data are stored in aPayload[]. The key always comes
222** first. The aPayload[] field grows as necessary to hold the key and data,
drh306dc212001-05-21 13:45:10 +0000223** up to a maximum of MX_LOCAL_PAYLOAD bytes. If the size of the key and
drh3b7511c2001-05-26 13:15:44 +0000224** data combined exceeds MX_LOCAL_PAYLOAD bytes, then Cell.ovfl is the
225** page number of the first overflow page.
226**
227** Though this structure is fixed in size, the Cell on the database
drhbd03cae2001-06-02 02:40:57 +0000228** page varies in size. Every cell has a CellHdr and at least 4 bytes
drh3b7511c2001-05-26 13:15:44 +0000229** of payload space. Additional payload bytes (up to the maximum of
230** MX_LOCAL_PAYLOAD) and the Cell.ovfl value are allocated only as
231** needed.
drh306dc212001-05-21 13:45:10 +0000232*/
drh365d68f2001-05-11 11:02:46 +0000233struct Cell {
drh5e2f8b92001-05-28 00:41:15 +0000234 CellHdr h; /* The cell header */
235 char aPayload[MX_LOCAL_PAYLOAD]; /* Key and data */
236 Pgno ovfl; /* The first overflow page */
drh365d68f2001-05-11 11:02:46 +0000237};
drh306dc212001-05-21 13:45:10 +0000238
239/*
240** Free space on a page is remembered using a linked list of the FreeBlk
241** structures. Space on a database page is allocated in increments of
drh72f82862001-05-24 21:06:34 +0000242** at least 4 bytes and is always aligned to a 4-byte boundry. The
drh8b2f49b2001-06-08 00:21:52 +0000243** linked list of FreeBlks is always kept in order by address.
drh306dc212001-05-21 13:45:10 +0000244*/
drh365d68f2001-05-11 11:02:46 +0000245struct FreeBlk {
drh72f82862001-05-24 21:06:34 +0000246 u16 iSize; /* Number of bytes in this block of free space */
drh14acc042001-06-10 19:56:58 +0000247 u16 iNext; /* Index in MemPage.u.aDisk[] of the next free block */
drh365d68f2001-05-11 11:02:46 +0000248};
drh306dc212001-05-21 13:45:10 +0000249
250/*
drh14acc042001-06-10 19:56:58 +0000251** The number of bytes of payload that will fit on a single overflow page.
drh3b7511c2001-05-26 13:15:44 +0000252*/
253#define OVERFLOW_SIZE (SQLITE_PAGE_SIZE-sizeof(Pgno))
254
255/*
drh306dc212001-05-21 13:45:10 +0000256** When the key and data for a single entry in the BTree will not fit in
drh8c42ca92001-06-22 19:15:00 +0000257** the MX_LOCAL_PAYLOAD bytes of space available on the database page,
drh8b2f49b2001-06-08 00:21:52 +0000258** then all extra bytes are written to a linked list of overflow pages.
drh306dc212001-05-21 13:45:10 +0000259** Each overflow page is an instance of the following structure.
260**
261** Unused pages in the database are also represented by instances of
drhbd03cae2001-06-02 02:40:57 +0000262** the OverflowPage structure. The PageOne.freeList field is the
drh306dc212001-05-21 13:45:10 +0000263** page number of the first page in a linked list of unused database
264** pages.
265*/
drh2af926b2001-05-15 00:39:25 +0000266struct OverflowPage {
drh14acc042001-06-10 19:56:58 +0000267 Pgno iNext;
drh5e2f8b92001-05-28 00:41:15 +0000268 char aPayload[OVERFLOW_SIZE];
drh7e3b0a02001-04-28 16:52:40 +0000269};
drh7e3b0a02001-04-28 16:52:40 +0000270
271/*
272** For every page in the database file, an instance of the following structure
drh14acc042001-06-10 19:56:58 +0000273** is stored in memory. The u.aDisk[] array contains the raw bits read from
drhbd03cae2001-06-02 02:40:57 +0000274** the disk. The rest is auxiliary information that held in memory only. The
275** auxiliary info is only valid for regular database pages - it is not
276** used for overflow pages and pages on the freelist.
drh306dc212001-05-21 13:45:10 +0000277**
drhbd03cae2001-06-02 02:40:57 +0000278** Of particular interest in the auxiliary info is the apCell[] entry. Each
drh14acc042001-06-10 19:56:58 +0000279** apCell[] entry is a pointer to a Cell structure in u.aDisk[]. The cells are
drh306dc212001-05-21 13:45:10 +0000280** put in this array so that they can be accessed in constant time, rather
drhbd03cae2001-06-02 02:40:57 +0000281** than in linear time which would be needed if we had to walk the linked
282** list on every access.
drh72f82862001-05-24 21:06:34 +0000283**
drh14acc042001-06-10 19:56:58 +0000284** Note that apCell[] contains enough space to hold up to two more Cells
285** than can possibly fit on one page. In the steady state, every apCell[]
286** points to memory inside u.aDisk[]. But in the middle of an insert
287** operation, some apCell[] entries may temporarily point to data space
288** outside of u.aDisk[]. This is a transient situation that is quickly
289** resolved. But while it is happening, it is possible for a database
290** page to hold as many as two more cells than it might otherwise hold.
291** The extra too entries in apCell[] are an allowance for this situation.
292**
drh72f82862001-05-24 21:06:34 +0000293** The pParent field points back to the parent page. This allows us to
294** walk up the BTree from any leaf to the root. Care must be taken to
295** unref() the parent page pointer when this page is no longer referenced.
drhbd03cae2001-06-02 02:40:57 +0000296** The pageDestructor() routine handles that chore.
drh7e3b0a02001-04-28 16:52:40 +0000297*/
298struct MemPage {
drh14acc042001-06-10 19:56:58 +0000299 union {
300 char aDisk[SQLITE_PAGE_SIZE]; /* Page data stored on disk */
301 PageHdr hdr; /* Overlay page header */
302 } u;
drh5e2f8b92001-05-28 00:41:15 +0000303 int isInit; /* True if auxiliary data is initialized */
drh72f82862001-05-24 21:06:34 +0000304 MemPage *pParent; /* The parent of this page. NULL for root */
drh14acc042001-06-10 19:56:58 +0000305 int nFree; /* Number of free bytes in u.aDisk[] */
drh306dc212001-05-21 13:45:10 +0000306 int nCell; /* Number of entries on this page */
drh14acc042001-06-10 19:56:58 +0000307 int isOverfull; /* Some apCell[] points outside u.aDisk[] */
308 Cell *apCell[MX_CELL+2]; /* All data entires in sorted order */
drh8c42ca92001-06-22 19:15:00 +0000309};
drh7e3b0a02001-04-28 16:52:40 +0000310
311/*
drh3b7511c2001-05-26 13:15:44 +0000312** The in-memory image of a disk page has the auxiliary information appended
313** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
314** that extra information.
315*/
316#define EXTRA_SIZE (sizeof(MemPage)-SQLITE_PAGE_SIZE)
317
318/*
drha059ad02001-04-17 20:09:11 +0000319** Everything we need to know about an open database
320*/
321struct Btree {
322 Pager *pPager; /* The page cache */
drh306dc212001-05-21 13:45:10 +0000323 BtCursor *pCursor; /* A list of all open cursors */
drhbd03cae2001-06-02 02:40:57 +0000324 PageOne *page1; /* First page of the database */
drh306dc212001-05-21 13:45:10 +0000325 int inTrans; /* True if a transaction is in progress */
drha059ad02001-04-17 20:09:11 +0000326};
327typedef Btree Bt;
328
drh365d68f2001-05-11 11:02:46 +0000329/*
330** A cursor is a pointer to a particular entry in the BTree.
331** The entry is identified by its MemPage and the index in
drh5e2f8b92001-05-28 00:41:15 +0000332** MemPage.apCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000333*/
drh72f82862001-05-24 21:06:34 +0000334struct BtCursor {
drh5e2f8b92001-05-28 00:41:15 +0000335 Btree *pBt; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000336 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drh8b2f49b2001-06-08 00:21:52 +0000337 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000338 MemPage *pPage; /* Page that contains the entry */
drh8c42ca92001-06-22 19:15:00 +0000339 int idx; /* Index of the entry in pPage->apCell[] */
drh5e2f8b92001-05-28 00:41:15 +0000340 u8 bSkipNext; /* sqliteBtreeNext() is no-op if true */
341 u8 iMatch; /* compare result from last sqliteBtreeMoveto() */
drh365d68f2001-05-11 11:02:46 +0000342};
drh7e3b0a02001-04-28 16:52:40 +0000343
drha059ad02001-04-17 20:09:11 +0000344/*
drh3b7511c2001-05-26 13:15:44 +0000345** Compute the total number of bytes that a Cell needs on the main
drh5e2f8b92001-05-28 00:41:15 +0000346** database page. The number returned includes the Cell header,
347** local payload storage, and the pointer to overflow pages (if
drh8c42ca92001-06-22 19:15:00 +0000348** applicable). Additional space allocated on overflow pages
drhbd03cae2001-06-02 02:40:57 +0000349** is NOT included in the value returned from this routine.
drh3b7511c2001-05-26 13:15:44 +0000350*/
351static int cellSize(Cell *pCell){
352 int n = pCell->h.nKey + pCell->h.nData;
353 if( n>MX_LOCAL_PAYLOAD ){
354 n = MX_LOCAL_PAYLOAD + sizeof(Pgno);
355 }else{
356 n = ROUNDUP(n);
357 }
358 n += sizeof(CellHdr);
359 return n;
360}
361
362/*
drh72f82862001-05-24 21:06:34 +0000363** Defragment the page given. All Cells are moved to the
364** beginning of the page and all free space is collected
365** into one big FreeBlk at the end of the page.
drh365d68f2001-05-11 11:02:46 +0000366*/
367static void defragmentPage(MemPage *pPage){
drh14acc042001-06-10 19:56:58 +0000368 int pc, i, n;
drh2af926b2001-05-15 00:39:25 +0000369 FreeBlk *pFBlk;
370 char newPage[SQLITE_PAGE_SIZE];
371
drh6019e162001-07-02 17:51:45 +0000372 assert( sqlitepager_iswriteable(pPage) );
drhbd03cae2001-06-02 02:40:57 +0000373 pc = sizeof(PageHdr);
drh14acc042001-06-10 19:56:58 +0000374 pPage->u.hdr.firstCell = pc;
375 memcpy(newPage, pPage->u.aDisk, pc);
drh2af926b2001-05-15 00:39:25 +0000376 for(i=0; i<pPage->nCell; i++){
drh2aa679f2001-06-25 02:11:07 +0000377 Cell *pCell = pPage->apCell[i];
drh8c42ca92001-06-22 19:15:00 +0000378
379 /* This routine should never be called on an overfull page. The
380 ** following asserts verify that constraint. */
drh7c717f72001-06-24 20:39:41 +0000381 assert( Addr(pCell) > Addr(pPage) );
382 assert( Addr(pCell) < Addr(pPage) + SQLITE_PAGE_SIZE );
drh8c42ca92001-06-22 19:15:00 +0000383
drh3b7511c2001-05-26 13:15:44 +0000384 n = cellSize(pCell);
drh2aa679f2001-06-25 02:11:07 +0000385 pCell->h.iNext = pc + n;
drh2af926b2001-05-15 00:39:25 +0000386 memcpy(&newPage[pc], pCell, n);
drh14acc042001-06-10 19:56:58 +0000387 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[pc];
drh2af926b2001-05-15 00:39:25 +0000388 pc += n;
389 }
drh72f82862001-05-24 21:06:34 +0000390 assert( pPage->nFree==SQLITE_PAGE_SIZE-pc );
drh14acc042001-06-10 19:56:58 +0000391 memcpy(pPage->u.aDisk, newPage, pc);
drh2aa679f2001-06-25 02:11:07 +0000392 if( pPage->nCell>0 ){
393 pPage->apCell[pPage->nCell-1]->h.iNext = 0;
394 }
drh8c42ca92001-06-22 19:15:00 +0000395 pFBlk = (FreeBlk*)&pPage->u.aDisk[pc];
drh2af926b2001-05-15 00:39:25 +0000396 pFBlk->iSize = SQLITE_PAGE_SIZE - pc;
397 pFBlk->iNext = 0;
drh14acc042001-06-10 19:56:58 +0000398 pPage->u.hdr.firstFree = pc;
drh2af926b2001-05-15 00:39:25 +0000399 memset(&pFBlk[1], 0, SQLITE_PAGE_SIZE - pc - sizeof(FreeBlk));
drh365d68f2001-05-11 11:02:46 +0000400}
401
drha059ad02001-04-17 20:09:11 +0000402/*
drh8b2f49b2001-06-08 00:21:52 +0000403** Allocate nByte bytes of space on a page. nByte must be a
404** multiple of 4.
drhbd03cae2001-06-02 02:40:57 +0000405**
drh14acc042001-06-10 19:56:58 +0000406** Return the index into pPage->u.aDisk[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000407** the new allocation. Or return 0 if there is not enough free
408** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000409**
drh72f82862001-05-24 21:06:34 +0000410** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000411** nBytes of contiguous free space, then this routine automatically
412** calls defragementPage() to consolidate all free space before
413** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000414*/
drhbd03cae2001-06-02 02:40:57 +0000415static int allocateSpace(MemPage *pPage, int nByte){
drh2af926b2001-05-15 00:39:25 +0000416 FreeBlk *p;
417 u16 *pIdx;
418 int start;
drh8c42ca92001-06-22 19:15:00 +0000419 int cnt = 0;
drh72f82862001-05-24 21:06:34 +0000420
drh6019e162001-07-02 17:51:45 +0000421 assert( sqlitepager_iswriteable(pPage) );
drh5e2f8b92001-05-28 00:41:15 +0000422 assert( nByte==ROUNDUP(nByte) );
drh14acc042001-06-10 19:56:58 +0000423 if( pPage->nFree<nByte || pPage->isOverfull ) return 0;
424 pIdx = &pPage->u.hdr.firstFree;
425 p = (FreeBlk*)&pPage->u.aDisk[*pIdx];
drh2af926b2001-05-15 00:39:25 +0000426 while( p->iSize<nByte ){
drh8c42ca92001-06-22 19:15:00 +0000427 assert( cnt++ < SQLITE_PAGE_SIZE/4 );
drh2af926b2001-05-15 00:39:25 +0000428 if( p->iNext==0 ){
429 defragmentPage(pPage);
drh14acc042001-06-10 19:56:58 +0000430 pIdx = &pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000431 }else{
432 pIdx = &p->iNext;
433 }
drh14acc042001-06-10 19:56:58 +0000434 p = (FreeBlk*)&pPage->u.aDisk[*pIdx];
drh2af926b2001-05-15 00:39:25 +0000435 }
436 if( p->iSize==nByte ){
437 start = *pIdx;
438 *pIdx = p->iNext;
439 }else{
drh8c42ca92001-06-22 19:15:00 +0000440 FreeBlk *pNew;
drh72f82862001-05-24 21:06:34 +0000441 start = *pIdx;
drh8c42ca92001-06-22 19:15:00 +0000442 pNew = (FreeBlk*)&pPage->u.aDisk[start + nByte];
drh72f82862001-05-24 21:06:34 +0000443 pNew->iNext = p->iNext;
444 pNew->iSize = p->iSize - nByte;
445 *pIdx = start + nByte;
drh2af926b2001-05-15 00:39:25 +0000446 }
447 pPage->nFree -= nByte;
448 return start;
drh7e3b0a02001-04-28 16:52:40 +0000449}
450
451/*
drh14acc042001-06-10 19:56:58 +0000452** Return a section of the MemPage.u.aDisk[] to the freelist.
453** The first byte of the new free block is pPage->u.aDisk[start]
454** and the size of the block is "size" bytes. Size must be
455** a multiple of 4.
drh306dc212001-05-21 13:45:10 +0000456**
457** Most of the effort here is involved in coalesing adjacent
458** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000459*/
460static void freeSpace(MemPage *pPage, int start, int size){
drh2af926b2001-05-15 00:39:25 +0000461 int end = start + size;
462 u16 *pIdx, idx;
463 FreeBlk *pFBlk;
464 FreeBlk *pNew;
465 FreeBlk *pNext;
466
drh6019e162001-07-02 17:51:45 +0000467 assert( sqlitepager_iswriteable(pPage) );
drh2af926b2001-05-15 00:39:25 +0000468 assert( size == ROUNDUP(size) );
469 assert( start == ROUNDUP(start) );
drh14acc042001-06-10 19:56:58 +0000470 pIdx = &pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000471 idx = *pIdx;
472 while( idx!=0 && idx<start ){
drh14acc042001-06-10 19:56:58 +0000473 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh2af926b2001-05-15 00:39:25 +0000474 if( idx + pFBlk->iSize == start ){
475 pFBlk->iSize += size;
476 if( idx + pFBlk->iSize == pFBlk->iNext ){
drh8c42ca92001-06-22 19:15:00 +0000477 pNext = (FreeBlk*)&pPage->u.aDisk[pFBlk->iNext];
drh2af926b2001-05-15 00:39:25 +0000478 pFBlk->iSize += pNext->iSize;
479 pFBlk->iNext = pNext->iNext;
480 }
481 pPage->nFree += size;
482 return;
483 }
484 pIdx = &pFBlk->iNext;
485 idx = *pIdx;
486 }
drh14acc042001-06-10 19:56:58 +0000487 pNew = (FreeBlk*)&pPage->u.aDisk[start];
drh2af926b2001-05-15 00:39:25 +0000488 if( idx != end ){
489 pNew->iSize = size;
490 pNew->iNext = idx;
491 }else{
drh14acc042001-06-10 19:56:58 +0000492 pNext = (FreeBlk*)&pPage->u.aDisk[idx];
drh2af926b2001-05-15 00:39:25 +0000493 pNew->iSize = size + pNext->iSize;
494 pNew->iNext = pNext->iNext;
495 }
496 *pIdx = start;
497 pPage->nFree += size;
drh7e3b0a02001-04-28 16:52:40 +0000498}
499
500/*
501** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000502**
drhbd03cae2001-06-02 02:40:57 +0000503** The pParent parameter must be a pointer to the MemPage which
504** is the parent of the page being initialized. The root of the
drh8b2f49b2001-06-08 00:21:52 +0000505** BTree (usually page 2) has no parent and so for that page,
506** pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000507**
drh72f82862001-05-24 21:06:34 +0000508** Return SQLITE_OK on success. If we see that the page does
509** not contained a well-formed database page, then return
510** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
511** guarantee that the page is well-formed. It only shows that
512** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000513*/
drh72f82862001-05-24 21:06:34 +0000514static int initPage(MemPage *pPage, Pgno pgnoThis, MemPage *pParent){
drh14acc042001-06-10 19:56:58 +0000515 int idx; /* An index into pPage->u.aDisk[] */
516 Cell *pCell; /* A pointer to a Cell in pPage->u.aDisk[] */
517 FreeBlk *pFBlk; /* A pointer to a free block in pPage->u.aDisk[] */
drh5e2f8b92001-05-28 00:41:15 +0000518 int sz; /* The size of a Cell in bytes */
519 int freeSpace; /* Amount of free space on the page */
drh2af926b2001-05-15 00:39:25 +0000520
drh5e2f8b92001-05-28 00:41:15 +0000521 if( pPage->pParent ){
522 assert( pPage->pParent==pParent );
523 return SQLITE_OK;
524 }
525 if( pParent ){
526 pPage->pParent = pParent;
527 sqlitepager_ref(pParent);
528 }
529 if( pPage->isInit ) return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +0000530 pPage->isInit = 1;
drh7e3b0a02001-04-28 16:52:40 +0000531 pPage->nCell = 0;
drh6019e162001-07-02 17:51:45 +0000532 freeSpace = USABLE_SPACE;
drh14acc042001-06-10 19:56:58 +0000533 idx = pPage->u.hdr.firstCell;
drh7e3b0a02001-04-28 16:52:40 +0000534 while( idx!=0 ){
drh8c42ca92001-06-22 19:15:00 +0000535 if( idx>SQLITE_PAGE_SIZE-MIN_CELL_SIZE ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000536 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh8c42ca92001-06-22 19:15:00 +0000537 if( idx!=ROUNDUP(idx) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000538 pCell = (Cell*)&pPage->u.aDisk[idx];
drh5e2f8b92001-05-28 00:41:15 +0000539 sz = cellSize(pCell);
540 if( idx+sz > SQLITE_PAGE_SIZE ) goto page_format_error;
541 freeSpace -= sz;
542 pPage->apCell[pPage->nCell++] = pCell;
drh3b7511c2001-05-26 13:15:44 +0000543 idx = pCell->h.iNext;
drh2af926b2001-05-15 00:39:25 +0000544 }
545 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +0000546 idx = pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000547 while( idx!=0 ){
548 if( idx>SQLITE_PAGE_SIZE-sizeof(FreeBlk) ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000549 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000550 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh2af926b2001-05-15 00:39:25 +0000551 pPage->nFree += pFBlk->iSize;
drh7c717f72001-06-24 20:39:41 +0000552 if( pFBlk->iNext>0 && pFBlk->iNext <= idx ) goto page_format_error;
drh2af926b2001-05-15 00:39:25 +0000553 idx = pFBlk->iNext;
drh7e3b0a02001-04-28 16:52:40 +0000554 }
drh8b2f49b2001-06-08 00:21:52 +0000555 if( pPage->nCell==0 && pPage->nFree==0 ){
556 /* As a special case, an uninitialized root page appears to be
557 ** an empty database */
558 return SQLITE_OK;
559 }
drh5e2f8b92001-05-28 00:41:15 +0000560 if( pPage->nFree!=freeSpace ) goto page_format_error;
drh7e3b0a02001-04-28 16:52:40 +0000561 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +0000562
563page_format_error:
564 return SQLITE_CORRUPT;
drh7e3b0a02001-04-28 16:52:40 +0000565}
566
567/*
drh8b2f49b2001-06-08 00:21:52 +0000568** Set up a raw page so that it looks like a database page holding
569** no entries.
drhbd03cae2001-06-02 02:40:57 +0000570*/
571static void zeroPage(MemPage *pPage){
572 PageHdr *pHdr;
573 FreeBlk *pFBlk;
drh6019e162001-07-02 17:51:45 +0000574 assert( sqlitepager_iswriteable(pPage) );
drhbd03cae2001-06-02 02:40:57 +0000575 memset(pPage, 0, SQLITE_PAGE_SIZE);
drh14acc042001-06-10 19:56:58 +0000576 pHdr = &pPage->u.hdr;
drhbd03cae2001-06-02 02:40:57 +0000577 pHdr->firstCell = 0;
578 pHdr->firstFree = sizeof(*pHdr);
579 pFBlk = (FreeBlk*)&pHdr[1];
580 pFBlk->iNext = 0;
581 pFBlk->iSize = SQLITE_PAGE_SIZE - sizeof(*pHdr);
drh8c42ca92001-06-22 19:15:00 +0000582 pPage->nFree = pFBlk->iSize;
583 pPage->nCell = 0;
584 pPage->isOverfull = 0;
drhbd03cae2001-06-02 02:40:57 +0000585}
586
587/*
drh72f82862001-05-24 21:06:34 +0000588** This routine is called when the reference count for a page
589** reaches zero. We need to unref the pParent pointer when that
590** happens.
591*/
592static void pageDestructor(void *pData){
593 MemPage *pPage = (MemPage*)pData;
594 if( pPage->pParent ){
595 MemPage *pParent = pPage->pParent;
596 pPage->pParent = 0;
597 sqlitepager_unref(pParent);
598 }
599}
600
601/*
drh306dc212001-05-21 13:45:10 +0000602** Open a new database.
603**
604** Actually, this routine just sets up the internal data structures
drh72f82862001-05-24 21:06:34 +0000605** for accessing the database. We do not open the database file
606** until the first page is loaded.
drha059ad02001-04-17 20:09:11 +0000607*/
drh6019e162001-07-02 17:51:45 +0000608int sqliteBtreeOpen(
609 const char *zFilename, /* Name of the file containing the BTree database */
610 int mode, /* Not currently used */
611 int nCache, /* How many pages in the page cache */
612 Btree **ppBtree /* Pointer to new Btree object written here */
613){
drha059ad02001-04-17 20:09:11 +0000614 Btree *pBt;
drh8c42ca92001-06-22 19:15:00 +0000615 int rc;
drha059ad02001-04-17 20:09:11 +0000616
617 pBt = sqliteMalloc( sizeof(*pBt) );
618 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +0000619 *ppBtree = 0;
drha059ad02001-04-17 20:09:11 +0000620 return SQLITE_NOMEM;
621 }
drh6019e162001-07-02 17:51:45 +0000622 if( nCache<10 ) nCache = 10;
623 rc = sqlitepager_open(&pBt->pPager, zFilename, nCache, EXTRA_SIZE);
drha059ad02001-04-17 20:09:11 +0000624 if( rc!=SQLITE_OK ){
625 if( pBt->pPager ) sqlitepager_close(pBt->pPager);
626 sqliteFree(pBt);
627 *ppBtree = 0;
628 return rc;
629 }
drh72f82862001-05-24 21:06:34 +0000630 sqlitepager_set_destructor(pBt->pPager, pageDestructor);
drha059ad02001-04-17 20:09:11 +0000631 pBt->pCursor = 0;
632 pBt->page1 = 0;
633 *ppBtree = pBt;
634 return SQLITE_OK;
635}
636
637/*
638** Close an open database and invalidate all cursors.
639*/
640int sqliteBtreeClose(Btree *pBt){
641 while( pBt->pCursor ){
642 sqliteBtreeCloseCursor(pBt->pCursor);
643 }
644 sqlitepager_close(pBt->pPager);
645 sqliteFree(pBt);
646 return SQLITE_OK;
647}
648
649/*
drhf57b14a2001-09-14 18:54:08 +0000650** Change the number of pages in the cache.
651*/
652int sqliteBtreeSetCacheSize(Btree *pBt, int mxPage){
653 sqlitepager_set_cachesize(pBt->pPager, mxPage);
654 return SQLITE_OK;
655}
656
657/*
drh306dc212001-05-21 13:45:10 +0000658** Get a reference to page1 of the database file. This will
659** also acquire a readlock on that file.
660**
661** SQLITE_OK is returned on success. If the file is not a
662** well-formed database file, then SQLITE_CORRUPT is returned.
663** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
664** is returned if we run out of memory. SQLITE_PROTOCOL is returned
665** if there is a locking protocol violation.
666*/
667static int lockBtree(Btree *pBt){
668 int rc;
669 if( pBt->page1 ) return SQLITE_OK;
drh8c42ca92001-06-22 19:15:00 +0000670 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pBt->page1);
drh306dc212001-05-21 13:45:10 +0000671 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +0000672
673 /* Do some checking to help insure the file we opened really is
674 ** a valid database file.
675 */
676 if( sqlitepager_pagecount(pBt->pPager)>0 ){
drhbd03cae2001-06-02 02:40:57 +0000677 PageOne *pP1 = pBt->page1;
drh8c42ca92001-06-22 19:15:00 +0000678 if( strcmp(pP1->zMagic,zMagicHeader)!=0 || pP1->iMagic!=MAGIC ){
drh306dc212001-05-21 13:45:10 +0000679 rc = SQLITE_CORRUPT;
drh72f82862001-05-24 21:06:34 +0000680 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +0000681 }
682 }
683 return rc;
684
drh72f82862001-05-24 21:06:34 +0000685page1_init_failed:
drh306dc212001-05-21 13:45:10 +0000686 sqlitepager_unref(pBt->page1);
687 pBt->page1 = 0;
drh72f82862001-05-24 21:06:34 +0000688 return rc;
drh306dc212001-05-21 13:45:10 +0000689}
690
691/*
drh8c42ca92001-06-22 19:15:00 +0000692** Create a new database by initializing the first two pages of the
693** file.
drh8b2f49b2001-06-08 00:21:52 +0000694*/
695static int newDatabase(Btree *pBt){
696 MemPage *pRoot;
697 PageOne *pP1;
drh8c42ca92001-06-22 19:15:00 +0000698 int rc;
drh7c717f72001-06-24 20:39:41 +0000699 if( sqlitepager_pagecount(pBt->pPager)>1 ) return SQLITE_OK;
drh8b2f49b2001-06-08 00:21:52 +0000700 pP1 = pBt->page1;
701 rc = sqlitepager_write(pBt->page1);
702 if( rc ) return rc;
drh8c42ca92001-06-22 19:15:00 +0000703 rc = sqlitepager_get(pBt->pPager, 2, (void**)&pRoot);
drh8b2f49b2001-06-08 00:21:52 +0000704 if( rc ) return rc;
705 rc = sqlitepager_write(pRoot);
706 if( rc ){
707 sqlitepager_unref(pRoot);
708 return rc;
709 }
710 strcpy(pP1->zMagic, zMagicHeader);
drh8c42ca92001-06-22 19:15:00 +0000711 pP1->iMagic = MAGIC;
drh8b2f49b2001-06-08 00:21:52 +0000712 zeroPage(pRoot);
713 sqlitepager_unref(pRoot);
714 return SQLITE_OK;
715}
716
717/*
drh72f82862001-05-24 21:06:34 +0000718** Attempt to start a new transaction.
drh8b2f49b2001-06-08 00:21:52 +0000719**
720** A transaction must be started before attempting any changes
721** to the database. None of the following routines will work
722** unless a transaction is started first:
723**
724** sqliteBtreeCreateTable()
725** sqliteBtreeClearTable()
726** sqliteBtreeDropTable()
727** sqliteBtreeInsert()
728** sqliteBtreeDelete()
729** sqliteBtreeUpdateMeta()
drha059ad02001-04-17 20:09:11 +0000730*/
731int sqliteBtreeBeginTrans(Btree *pBt){
732 int rc;
733 if( pBt->inTrans ) return SQLITE_ERROR;
734 if( pBt->page1==0 ){
drh7e3b0a02001-04-28 16:52:40 +0000735 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +0000736 if( rc!=SQLITE_OK ){
737 return rc;
738 }
drha059ad02001-04-17 20:09:11 +0000739 }
drhbe0072d2001-09-13 14:46:09 +0000740 if( !sqlitepager_isreadonly(pBt->pPager) ){
drh5e00f6c2001-09-13 13:46:56 +0000741 rc = sqlitepager_write(pBt->page1);
742 if( rc!=SQLITE_OK ){
743 return rc;
744 }
745 rc = newDatabase(pBt);
drha059ad02001-04-17 20:09:11 +0000746 }
drh8c42ca92001-06-22 19:15:00 +0000747 pBt->inTrans = 1;
drh8c42ca92001-06-22 19:15:00 +0000748 return rc;
drha059ad02001-04-17 20:09:11 +0000749}
750
751/*
drh5e00f6c2001-09-13 13:46:56 +0000752** If there are no outstanding cursors and we are not in the middle
753** of a transaction but there is a read lock on the database, then
754** this routine unrefs the first page of the database file which
755** has the effect of releasing the read lock.
756**
757** If there are any outstanding cursors, this routine is a no-op.
758**
759** If there is a transaction in progress, this routine is a no-op.
drha059ad02001-04-17 20:09:11 +0000760*/
drh5e00f6c2001-09-13 13:46:56 +0000761static void unlockBtreeIfUnused(Btree *pBt){
drh7c717f72001-06-24 20:39:41 +0000762 if( pBt->inTrans==0 && pBt->pCursor==0 && pBt->page1!=0 ){
drha059ad02001-04-17 20:09:11 +0000763 sqlitepager_unref(pBt->page1);
764 pBt->page1 = 0;
765 pBt->inTrans = 0;
766 }
767}
768
769/*
drh2aa679f2001-06-25 02:11:07 +0000770** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +0000771**
772** This will release the write lock on the database file. If there
773** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000774*/
775int sqliteBtreeCommit(Btree *pBt){
776 int rc;
drh2aa679f2001-06-25 02:11:07 +0000777 if( pBt->inTrans==0 ) return SQLITE_ERROR;
drha059ad02001-04-17 20:09:11 +0000778 rc = sqlitepager_commit(pBt->pPager);
drh7c717f72001-06-24 20:39:41 +0000779 pBt->inTrans = 0;
drh5e00f6c2001-09-13 13:46:56 +0000780 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000781 return rc;
782}
783
784/*
785** Rollback the transaction in progress. All cursors must be
786** closed before this routine is called.
drh5e00f6c2001-09-13 13:46:56 +0000787**
788** This will release the write lock on the database file. If there
789** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000790*/
791int sqliteBtreeRollback(Btree *pBt){
792 int rc;
drh72f82862001-05-24 21:06:34 +0000793 if( pBt->pCursor!=0 ) return SQLITE_ERROR;
drh7c717f72001-06-24 20:39:41 +0000794 if( pBt->inTrans==0 ) return SQLITE_OK;
795 pBt->inTrans = 0;
drha059ad02001-04-17 20:09:11 +0000796 rc = sqlitepager_rollback(pBt->pPager);
drh5e00f6c2001-09-13 13:46:56 +0000797 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000798 return rc;
799}
800
801/*
drh8b2f49b2001-06-08 00:21:52 +0000802** Create a new cursor for the BTree whose root is on the page
803** iTable. The act of acquiring a cursor gets a read lock on
804** the database file.
drha059ad02001-04-17 20:09:11 +0000805*/
drh8b2f49b2001-06-08 00:21:52 +0000806int sqliteBtreeCursor(Btree *pBt, int iTable, BtCursor **ppCur){
drha059ad02001-04-17 20:09:11 +0000807 int rc;
808 BtCursor *pCur;
809 if( pBt->page1==0 ){
810 rc = lockBtree(pBt);
811 if( rc!=SQLITE_OK ){
812 *ppCur = 0;
813 return rc;
814 }
815 }
816 pCur = sqliteMalloc( sizeof(*pCur) );
817 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +0000818 rc = SQLITE_NOMEM;
819 goto create_cursor_exception;
820 }
drh8b2f49b2001-06-08 00:21:52 +0000821 pCur->pgnoRoot = (Pgno)iTable;
drh8c42ca92001-06-22 19:15:00 +0000822 rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +0000823 if( rc!=SQLITE_OK ){
824 goto create_cursor_exception;
825 }
drh8b2f49b2001-06-08 00:21:52 +0000826 rc = initPage(pCur->pPage, pCur->pgnoRoot, 0);
drhbd03cae2001-06-02 02:40:57 +0000827 if( rc!=SQLITE_OK ){
828 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +0000829 }
drh14acc042001-06-10 19:56:58 +0000830 pCur->pBt = pBt;
831 pCur->idx = 0;
drha059ad02001-04-17 20:09:11 +0000832 pCur->pNext = pBt->pCursor;
833 if( pCur->pNext ){
834 pCur->pNext->pPrev = pCur;
835 }
drh14acc042001-06-10 19:56:58 +0000836 pCur->pPrev = 0;
drha059ad02001-04-17 20:09:11 +0000837 pBt->pCursor = pCur;
drh2af926b2001-05-15 00:39:25 +0000838 *ppCur = pCur;
839 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +0000840
841create_cursor_exception:
842 *ppCur = 0;
843 if( pCur ){
844 if( pCur->pPage ) sqlitepager_unref(pCur->pPage);
845 sqliteFree(pCur);
846 }
drh5e00f6c2001-09-13 13:46:56 +0000847 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +0000848 return rc;
drha059ad02001-04-17 20:09:11 +0000849}
850
851/*
drh5e00f6c2001-09-13 13:46:56 +0000852** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +0000853** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +0000854*/
855int sqliteBtreeCloseCursor(BtCursor *pCur){
856 Btree *pBt = pCur->pBt;
drha059ad02001-04-17 20:09:11 +0000857 if( pCur->pPrev ){
858 pCur->pPrev->pNext = pCur->pNext;
859 }else{
860 pBt->pCursor = pCur->pNext;
861 }
862 if( pCur->pNext ){
863 pCur->pNext->pPrev = pCur->pPrev;
864 }
drh2af926b2001-05-15 00:39:25 +0000865 sqlitepager_unref(pCur->pPage);
drh5e00f6c2001-09-13 13:46:56 +0000866 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000867 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +0000868 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +0000869}
870
drh7e3b0a02001-04-28 16:52:40 +0000871/*
drh5e2f8b92001-05-28 00:41:15 +0000872** Make a temporary cursor by filling in the fields of pTempCur.
873** The temporary cursor is not on the cursor list for the Btree.
874*/
drh14acc042001-06-10 19:56:58 +0000875static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +0000876 memcpy(pTempCur, pCur, sizeof(*pCur));
877 pTempCur->pNext = 0;
878 pTempCur->pPrev = 0;
879 sqlitepager_ref(pTempCur->pPage);
880}
881
882/*
drhbd03cae2001-06-02 02:40:57 +0000883** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +0000884** function above.
885*/
drh14acc042001-06-10 19:56:58 +0000886static void releaseTempCursor(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +0000887 sqlitepager_unref(pCur->pPage);
888}
889
890/*
drhbd03cae2001-06-02 02:40:57 +0000891** Set *pSize to the number of bytes of key in the entry the
892** cursor currently points to. Always return SQLITE_OK.
893** Failure is not possible. If the cursor is not currently
894** pointing to an entry (which can happen, for example, if
895** the database is empty) then *pSize is set to 0.
drh7e3b0a02001-04-28 16:52:40 +0000896*/
drh72f82862001-05-24 21:06:34 +0000897int sqliteBtreeKeySize(BtCursor *pCur, int *pSize){
drh2af926b2001-05-15 00:39:25 +0000898 Cell *pCell;
899 MemPage *pPage;
900
901 pPage = pCur->pPage;
drh72f82862001-05-24 21:06:34 +0000902 assert( pPage!=0 );
903 if( pCur->idx >= pPage->nCell ){
904 *pSize = 0;
905 }else{
drh5e2f8b92001-05-28 00:41:15 +0000906 pCell = pPage->apCell[pCur->idx];
drh8c42ca92001-06-22 19:15:00 +0000907 *pSize = pCell->h.nKey;
drh72f82862001-05-24 21:06:34 +0000908 }
909 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +0000910}
drh2af926b2001-05-15 00:39:25 +0000911
drh72f82862001-05-24 21:06:34 +0000912/*
913** Read payload information from the entry that the pCur cursor is
914** pointing to. Begin reading the payload at "offset" and read
915** a total of "amt" bytes. Put the result in zBuf.
916**
917** This routine does not make a distinction between key and data.
918** It just reads bytes from the payload area.
919*/
drh2af926b2001-05-15 00:39:25 +0000920static int getPayload(BtCursor *pCur, int offset, int amt, char *zBuf){
drh5e2f8b92001-05-28 00:41:15 +0000921 char *aPayload;
drh2af926b2001-05-15 00:39:25 +0000922 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +0000923 int rc;
drh72f82862001-05-24 21:06:34 +0000924 assert( pCur!=0 && pCur->pPage!=0 );
drh8c42ca92001-06-22 19:15:00 +0000925 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
926 aPayload = pCur->pPage->apCell[pCur->idx]->aPayload;
drh2af926b2001-05-15 00:39:25 +0000927 if( offset<MX_LOCAL_PAYLOAD ){
928 int a = amt;
929 if( a+offset>MX_LOCAL_PAYLOAD ){
930 a = MX_LOCAL_PAYLOAD - offset;
931 }
drh5e2f8b92001-05-28 00:41:15 +0000932 memcpy(zBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +0000933 if( a==amt ){
934 return SQLITE_OK;
935 }
drh2aa679f2001-06-25 02:11:07 +0000936 offset = 0;
drh2af926b2001-05-15 00:39:25 +0000937 zBuf += a;
938 amt -= a;
drhdd793422001-06-28 01:54:48 +0000939 }else{
940 offset -= MX_LOCAL_PAYLOAD;
drhbd03cae2001-06-02 02:40:57 +0000941 }
942 if( amt>0 ){
drh8c42ca92001-06-22 19:15:00 +0000943 nextPage = pCur->pPage->apCell[pCur->idx]->ovfl;
drh2af926b2001-05-15 00:39:25 +0000944 }
945 while( amt>0 && nextPage ){
946 OverflowPage *pOvfl;
drh8c42ca92001-06-22 19:15:00 +0000947 rc = sqlitepager_get(pCur->pBt->pPager, nextPage, (void**)&pOvfl);
drh2af926b2001-05-15 00:39:25 +0000948 if( rc!=0 ){
949 return rc;
950 }
drh14acc042001-06-10 19:56:58 +0000951 nextPage = pOvfl->iNext;
drh2af926b2001-05-15 00:39:25 +0000952 if( offset<OVERFLOW_SIZE ){
953 int a = amt;
954 if( a + offset > OVERFLOW_SIZE ){
955 a = OVERFLOW_SIZE - offset;
956 }
drh5e2f8b92001-05-28 00:41:15 +0000957 memcpy(zBuf, &pOvfl->aPayload[offset], a);
drh2aa679f2001-06-25 02:11:07 +0000958 offset = 0;
drh2af926b2001-05-15 00:39:25 +0000959 amt -= a;
960 zBuf += a;
drh2aa679f2001-06-25 02:11:07 +0000961 }else{
962 offset -= OVERFLOW_SIZE;
drh2af926b2001-05-15 00:39:25 +0000963 }
964 sqlitepager_unref(pOvfl);
965 }
966 return amt==0 ? SQLITE_OK : SQLITE_CORRUPT;
967}
968
drh72f82862001-05-24 21:06:34 +0000969/*
drh5e00f6c2001-09-13 13:46:56 +0000970** Read part of the key associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +0000971** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +0000972** begins at "offset". The number of bytes actually read is
973** returned. The amount returned will be smaller than the
974** amount requested if there are not enough bytes in the key
975** to satisfy the request.
drh72f82862001-05-24 21:06:34 +0000976*/
977int sqliteBtreeKey(BtCursor *pCur, int offset, int amt, char *zBuf){
978 Cell *pCell;
979 MemPage *pPage;
drha059ad02001-04-17 20:09:11 +0000980
drh5e00f6c2001-09-13 13:46:56 +0000981 if( amt<0 ) return 0;
982 if( offset<0 ) return 0;
983 if( amt==0 ) return 0;
drh72f82862001-05-24 21:06:34 +0000984 pPage = pCur->pPage;
985 assert( pPage!=0 );
986 if( pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +0000987 return 0;
drh72f82862001-05-24 21:06:34 +0000988 }
drh5e2f8b92001-05-28 00:41:15 +0000989 pCell = pPage->apCell[pCur->idx];
drh3b7511c2001-05-26 13:15:44 +0000990 if( amt+offset > pCell->h.nKey ){
drh5e00f6c2001-09-13 13:46:56 +0000991 amt = pCell->h.nKey - offset;
992 if( amt<=0 ){
993 return 0;
994 }
drhbd03cae2001-06-02 02:40:57 +0000995 }
drh5e00f6c2001-09-13 13:46:56 +0000996 getPayload(pCur, offset, amt, zBuf);
997 return amt;
drh72f82862001-05-24 21:06:34 +0000998}
999
1000/*
drhbd03cae2001-06-02 02:40:57 +00001001** Set *pSize to the number of bytes of data in the entry the
1002** cursor currently points to. Always return SQLITE_OK.
1003** Failure is not possible. If the cursor is not currently
1004** pointing to an entry (which can happen, for example, if
1005** the database is empty) then *pSize is set to 0.
drh72f82862001-05-24 21:06:34 +00001006*/
1007int sqliteBtreeDataSize(BtCursor *pCur, int *pSize){
1008 Cell *pCell;
1009 MemPage *pPage;
1010
1011 pPage = pCur->pPage;
1012 assert( pPage!=0 );
1013 if( pCur->idx >= pPage->nCell ){
1014 *pSize = 0;
1015 }else{
drh5e2f8b92001-05-28 00:41:15 +00001016 pCell = pPage->apCell[pCur->idx];
drh3b7511c2001-05-26 13:15:44 +00001017 *pSize = pCell->h.nData;
drh72f82862001-05-24 21:06:34 +00001018 }
1019 return SQLITE_OK;
1020}
1021
1022/*
drh5e00f6c2001-09-13 13:46:56 +00001023** Read part of the data associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +00001024** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +00001025** begins at "offset". The number of bytes actually read is
1026** returned. The amount returned will be smaller than the
1027** amount requested if there are not enough bytes in the data
1028** to satisfy the request.
drh72f82862001-05-24 21:06:34 +00001029*/
1030int sqliteBtreeData(BtCursor *pCur, int offset, int amt, char *zBuf){
1031 Cell *pCell;
1032 MemPage *pPage;
1033
drh5e00f6c2001-09-13 13:46:56 +00001034 if( amt<0 ) return 0;
1035 if( offset<0 ) return 0;
1036 if( amt==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001037 pPage = pCur->pPage;
1038 assert( pPage!=0 );
1039 if( pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +00001040 return 0;
drh72f82862001-05-24 21:06:34 +00001041 }
drh5e2f8b92001-05-28 00:41:15 +00001042 pCell = pPage->apCell[pCur->idx];
drhbd03cae2001-06-02 02:40:57 +00001043 if( amt+offset > pCell->h.nData ){
drh5e00f6c2001-09-13 13:46:56 +00001044 amt = pCell->h.nData - offset;
1045 if( amt<=0 ){
1046 return 0;
1047 }
drhbd03cae2001-06-02 02:40:57 +00001048 }
drh5e00f6c2001-09-13 13:46:56 +00001049 getPayload(pCur, offset + pCell->h.nKey, amt, zBuf);
1050 return amt;
drh72f82862001-05-24 21:06:34 +00001051}
drha059ad02001-04-17 20:09:11 +00001052
drh2af926b2001-05-15 00:39:25 +00001053/*
1054** Compare the key for the entry that pCur points to against the
1055** given key (pKey,nKeyOrig). Put the comparison result in *pResult.
1056** The result is negative if pCur<pKey, zero if they are equal and
1057** positive if pCur>pKey.
1058**
1059** SQLITE_OK is returned on success. If part of the cursor key
1060** is on overflow pages and we are unable to access those overflow
1061** pages, then some other value might be returned to indicate the
1062** reason for the error.
1063*/
drh5c4d9702001-08-20 00:33:58 +00001064static int compareKey(
1065 BtCursor *pCur, /* Points to the entry against which we are comparing */
1066 const char *pKey, /* The comparison key */
1067 int nKeyOrig, /* Number of bytes in the comparison key */
1068 int *pResult /* Write the comparison results here */
1069){
drh2af926b2001-05-15 00:39:25 +00001070 Pgno nextPage;
1071 int nKey = nKeyOrig;
drh8c42ca92001-06-22 19:15:00 +00001072 int n, c, rc;
drh2af926b2001-05-15 00:39:25 +00001073 Cell *pCell;
1074
1075 assert( pCur->pPage );
1076 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drhbd03cae2001-06-02 02:40:57 +00001077 pCell = pCur->pPage->apCell[pCur->idx];
drh3b7511c2001-05-26 13:15:44 +00001078 if( nKey > pCell->h.nKey ){
1079 nKey = pCell->h.nKey;
drh2af926b2001-05-15 00:39:25 +00001080 }
1081 n = nKey;
1082 if( n>MX_LOCAL_PAYLOAD ){
1083 n = MX_LOCAL_PAYLOAD;
1084 }
drh5e2f8b92001-05-28 00:41:15 +00001085 c = memcmp(pCell->aPayload, pKey, n);
drh2af926b2001-05-15 00:39:25 +00001086 if( c!=0 ){
1087 *pResult = c;
1088 return SQLITE_OK;
1089 }
1090 pKey += n;
1091 nKey -= n;
drh3b7511c2001-05-26 13:15:44 +00001092 nextPage = pCell->ovfl;
drh2af926b2001-05-15 00:39:25 +00001093 while( nKey>0 ){
1094 OverflowPage *pOvfl;
1095 if( nextPage==0 ){
1096 return SQLITE_CORRUPT;
1097 }
drh8c42ca92001-06-22 19:15:00 +00001098 rc = sqlitepager_get(pCur->pBt->pPager, nextPage, (void**)&pOvfl);
drh72f82862001-05-24 21:06:34 +00001099 if( rc ){
drh2af926b2001-05-15 00:39:25 +00001100 return rc;
1101 }
drh14acc042001-06-10 19:56:58 +00001102 nextPage = pOvfl->iNext;
drh2af926b2001-05-15 00:39:25 +00001103 n = nKey;
1104 if( n>OVERFLOW_SIZE ){
1105 n = OVERFLOW_SIZE;
1106 }
drh5e2f8b92001-05-28 00:41:15 +00001107 c = memcmp(pOvfl->aPayload, pKey, n);
drh2af926b2001-05-15 00:39:25 +00001108 sqlitepager_unref(pOvfl);
1109 if( c!=0 ){
1110 *pResult = c;
1111 return SQLITE_OK;
1112 }
1113 nKey -= n;
1114 pKey += n;
1115 }
drh3b7511c2001-05-26 13:15:44 +00001116 c = pCell->h.nKey - nKeyOrig;
drh2af926b2001-05-15 00:39:25 +00001117 *pResult = c;
1118 return SQLITE_OK;
1119}
1120
drh72f82862001-05-24 21:06:34 +00001121/*
1122** Move the cursor down to a new child page.
1123*/
drh5e2f8b92001-05-28 00:41:15 +00001124static int moveToChild(BtCursor *pCur, int newPgno){
drh72f82862001-05-24 21:06:34 +00001125 int rc;
1126 MemPage *pNewPage;
1127
drh8c42ca92001-06-22 19:15:00 +00001128 rc = sqlitepager_get(pCur->pBt->pPager, newPgno, (void**)&pNewPage);
drh6019e162001-07-02 17:51:45 +00001129 if( rc ) return rc;
1130 rc = initPage(pNewPage, newPgno, pCur->pPage);
1131 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001132 sqlitepager_unref(pCur->pPage);
1133 pCur->pPage = pNewPage;
1134 pCur->idx = 0;
1135 return SQLITE_OK;
1136}
1137
1138/*
drh5e2f8b92001-05-28 00:41:15 +00001139** Move the cursor up to the parent page.
1140**
1141** pCur->idx is set to the cell index that contains the pointer
1142** to the page we are coming from. If we are coming from the
1143** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00001144** the largest cell index.
drh72f82862001-05-24 21:06:34 +00001145*/
drh5e2f8b92001-05-28 00:41:15 +00001146static int moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001147 Pgno oldPgno;
1148 MemPage *pParent;
drh8c42ca92001-06-22 19:15:00 +00001149 int i;
drh72f82862001-05-24 21:06:34 +00001150 pParent = pCur->pPage->pParent;
drhbd03cae2001-06-02 02:40:57 +00001151 if( pParent==0 ) return SQLITE_INTERNAL;
drh72f82862001-05-24 21:06:34 +00001152 oldPgno = sqlitepager_pagenumber(pCur->pPage);
drh72f82862001-05-24 21:06:34 +00001153 sqlitepager_ref(pParent);
1154 sqlitepager_unref(pCur->pPage);
1155 pCur->pPage = pParent;
drh8c42ca92001-06-22 19:15:00 +00001156 pCur->idx = pParent->nCell;
1157 for(i=0; i<pParent->nCell; i++){
1158 if( pParent->apCell[i]->h.leftChild==oldPgno ){
drh72f82862001-05-24 21:06:34 +00001159 pCur->idx = i;
1160 break;
1161 }
1162 }
drh5e2f8b92001-05-28 00:41:15 +00001163 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00001164}
1165
1166/*
1167** Move the cursor to the root page
1168*/
drh5e2f8b92001-05-28 00:41:15 +00001169static int moveToRoot(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001170 MemPage *pNew;
drhbd03cae2001-06-02 02:40:57 +00001171 int rc;
1172
drh8c42ca92001-06-22 19:15:00 +00001173 rc = sqlitepager_get(pCur->pBt->pPager, pCur->pgnoRoot, (void**)&pNew);
drhbd03cae2001-06-02 02:40:57 +00001174 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00001175 rc = initPage(pNew, pCur->pgnoRoot, 0);
1176 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001177 sqlitepager_unref(pCur->pPage);
1178 pCur->pPage = pNew;
1179 pCur->idx = 0;
1180 return SQLITE_OK;
1181}
drh2af926b2001-05-15 00:39:25 +00001182
drh5e2f8b92001-05-28 00:41:15 +00001183/*
1184** Move the cursor down to the left-most leaf entry beneath the
1185** entry to which it is currently pointing.
1186*/
1187static int moveToLeftmost(BtCursor *pCur){
1188 Pgno pgno;
1189 int rc;
1190
1191 while( (pgno = pCur->pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
1192 rc = moveToChild(pCur, pgno);
1193 if( rc ) return rc;
1194 }
1195 return SQLITE_OK;
1196}
1197
drh5e00f6c2001-09-13 13:46:56 +00001198/* Move the cursor to the first entry in the table. Return SQLITE_OK
1199** on success. Set *pRes to 0 if the cursor actually points to something
1200** or set *pRes to 1 if the table is empty and there is no first element.
1201*/
1202int sqliteBtreeFirst(BtCursor *pCur, int *pRes){
1203 int rc;
1204 rc = moveToRoot(pCur);
1205 if( rc ) return rc;
1206 if( pCur->pPage->nCell==0 ){
1207 *pRes = 1;
1208 return SQLITE_OK;
1209 }
1210 *pRes = 0;
1211 rc = moveToLeftmost(pCur);
1212 return rc;
1213}
drh5e2f8b92001-05-28 00:41:15 +00001214
drha059ad02001-04-17 20:09:11 +00001215/* Move the cursor so that it points to an entry near pKey.
drh72f82862001-05-24 21:06:34 +00001216** Return a success code.
1217**
drh5e2f8b92001-05-28 00:41:15 +00001218** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00001219** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00001220** were present. The cursor might point to an entry that comes
1221** before or after the key.
1222**
drhbd03cae2001-06-02 02:40:57 +00001223** The result of comparing the key with the entry to which the
1224** cursor is left pointing is stored in pCur->iMatch. The same
1225** value is also written to *pRes if pRes!=NULL. The meaning of
1226** this value is as follows:
1227**
1228** *pRes<0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001229** is smaller than pKey.
drhbd03cae2001-06-02 02:40:57 +00001230**
1231** *pRes==0 The cursor is left pointing at an entry that
1232** exactly matches pKey.
1233**
1234** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001235** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00001236*/
drh5c4d9702001-08-20 00:33:58 +00001237int sqliteBtreeMoveto(BtCursor *pCur, const void *pKey, int nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00001238 int rc;
drh7c717f72001-06-24 20:39:41 +00001239 pCur->bSkipNext = 0;
drh5e2f8b92001-05-28 00:41:15 +00001240 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00001241 if( rc ) return rc;
1242 for(;;){
1243 int lwr, upr;
1244 Pgno chldPg;
1245 MemPage *pPage = pCur->pPage;
drh8b2f49b2001-06-08 00:21:52 +00001246 int c = -1;
drh72f82862001-05-24 21:06:34 +00001247 lwr = 0;
1248 upr = pPage->nCell-1;
1249 while( lwr<=upr ){
drh72f82862001-05-24 21:06:34 +00001250 pCur->idx = (lwr+upr)/2;
1251 rc = compareKey(pCur, pKey, nKey, &c);
1252 if( rc ) return rc;
1253 if( c==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001254 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001255 if( pRes ) *pRes = 0;
1256 return SQLITE_OK;
1257 }
1258 if( c<0 ){
1259 lwr = pCur->idx+1;
1260 }else{
1261 upr = pCur->idx-1;
1262 }
1263 }
1264 assert( lwr==upr+1 );
1265 if( lwr>=pPage->nCell ){
drh14acc042001-06-10 19:56:58 +00001266 chldPg = pPage->u.hdr.rightChild;
drh72f82862001-05-24 21:06:34 +00001267 }else{
drh5e2f8b92001-05-28 00:41:15 +00001268 chldPg = pPage->apCell[lwr]->h.leftChild;
drh72f82862001-05-24 21:06:34 +00001269 }
1270 if( chldPg==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001271 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001272 if( pRes ) *pRes = c;
1273 return SQLITE_OK;
1274 }
drh5e2f8b92001-05-28 00:41:15 +00001275 rc = moveToChild(pCur, chldPg);
drh72f82862001-05-24 21:06:34 +00001276 if( rc ) return rc;
1277 }
drhbd03cae2001-06-02 02:40:57 +00001278 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00001279}
1280
1281/*
drhbd03cae2001-06-02 02:40:57 +00001282** Advance the cursor to the next entry in the database. If
1283** successful and pRes!=NULL then set *pRes=0. If the cursor
1284** was already pointing to the last entry in the database before
1285** this routine was called, then set *pRes=1 if pRes!=NULL.
drh72f82862001-05-24 21:06:34 +00001286*/
1287int sqliteBtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00001288 int rc;
drh5e2f8b92001-05-28 00:41:15 +00001289 if( pCur->bSkipNext ){
1290 pCur->bSkipNext = 0;
drh72f82862001-05-24 21:06:34 +00001291 if( pRes ) *pRes = 0;
1292 return SQLITE_OK;
1293 }
drh72f82862001-05-24 21:06:34 +00001294 pCur->idx++;
drh5e2f8b92001-05-28 00:41:15 +00001295 if( pCur->idx>=pCur->pPage->nCell ){
drh8c42ca92001-06-22 19:15:00 +00001296 if( pCur->pPage->u.hdr.rightChild ){
1297 rc = moveToChild(pCur, pCur->pPage->u.hdr.rightChild);
drh5e2f8b92001-05-28 00:41:15 +00001298 if( rc ) return rc;
1299 rc = moveToLeftmost(pCur);
1300 if( rc ) return rc;
1301 if( pRes ) *pRes = 0;
drh72f82862001-05-24 21:06:34 +00001302 return SQLITE_OK;
1303 }
drh5e2f8b92001-05-28 00:41:15 +00001304 do{
drh8c42ca92001-06-22 19:15:00 +00001305 if( pCur->pPage->pParent==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001306 if( pRes ) *pRes = 1;
1307 return SQLITE_OK;
1308 }
1309 rc = moveToParent(pCur);
1310 if( rc ) return rc;
1311 }while( pCur->idx>=pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00001312 if( pRes ) *pRes = 0;
1313 return SQLITE_OK;
1314 }
drh5e2f8b92001-05-28 00:41:15 +00001315 rc = moveToLeftmost(pCur);
1316 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001317 if( pRes ) *pRes = 0;
1318 return SQLITE_OK;
1319}
1320
drh3b7511c2001-05-26 13:15:44 +00001321/*
1322** Allocate a new page from the database file.
1323**
1324** The new page is marked as dirty. (In other words, sqlitepager_write()
1325** has already been called on the new page.) The new page has also
1326** been referenced and the calling routine is responsible for calling
1327** sqlitepager_unref() on the new page when it is done.
1328**
1329** SQLITE_OK is returned on success. Any other return value indicates
1330** an error. *ppPage and *pPgno are undefined in the event of an error.
1331** Do not invoke sqlitepager_unref() on *ppPage if an error is returned.
1332*/
1333static int allocatePage(Btree *pBt, MemPage **ppPage, Pgno *pPgno){
drhbd03cae2001-06-02 02:40:57 +00001334 PageOne *pPage1 = pBt->page1;
drh8c42ca92001-06-22 19:15:00 +00001335 int rc;
drh3b7511c2001-05-26 13:15:44 +00001336 if( pPage1->freeList ){
1337 OverflowPage *pOvfl;
1338 rc = sqlitepager_write(pPage1);
1339 if( rc ) return rc;
1340 *pPgno = pPage1->freeList;
drh8c42ca92001-06-22 19:15:00 +00001341 rc = sqlitepager_get(pBt->pPager, pPage1->freeList, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001342 if( rc ) return rc;
1343 rc = sqlitepager_write(pOvfl);
1344 if( rc ){
1345 sqlitepager_unref(pOvfl);
1346 return rc;
1347 }
drh14acc042001-06-10 19:56:58 +00001348 pPage1->freeList = pOvfl->iNext;
drh2aa679f2001-06-25 02:11:07 +00001349 pPage1->nFree--;
drh3b7511c2001-05-26 13:15:44 +00001350 *ppPage = (MemPage*)pOvfl;
1351 }else{
drh2aa679f2001-06-25 02:11:07 +00001352 *pPgno = sqlitepager_pagecount(pBt->pPager) + 1;
drh8c42ca92001-06-22 19:15:00 +00001353 rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
drh3b7511c2001-05-26 13:15:44 +00001354 if( rc ) return rc;
1355 rc = sqlitepager_write(*ppPage);
1356 }
1357 return rc;
1358}
1359
1360/*
1361** Add a page of the database file to the freelist. Either pgno or
1362** pPage but not both may be 0.
drh5e2f8b92001-05-28 00:41:15 +00001363**
drhdd793422001-06-28 01:54:48 +00001364** sqlitepager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00001365*/
1366static int freePage(Btree *pBt, void *pPage, Pgno pgno){
drhbd03cae2001-06-02 02:40:57 +00001367 PageOne *pPage1 = pBt->page1;
drh3b7511c2001-05-26 13:15:44 +00001368 OverflowPage *pOvfl = (OverflowPage*)pPage;
1369 int rc;
drhdd793422001-06-28 01:54:48 +00001370 int needUnref = 0;
1371 MemPage *pMemPage;
drh8b2f49b2001-06-08 00:21:52 +00001372
drh3b7511c2001-05-26 13:15:44 +00001373 if( pgno==0 ){
1374 assert( pOvfl!=0 );
1375 pgno = sqlitepager_pagenumber(pOvfl);
1376 }
drh2aa679f2001-06-25 02:11:07 +00001377 assert( pgno>2 );
drh3b7511c2001-05-26 13:15:44 +00001378 rc = sqlitepager_write(pPage1);
1379 if( rc ){
1380 return rc;
1381 }
1382 if( pOvfl==0 ){
1383 assert( pgno>0 );
drh8c42ca92001-06-22 19:15:00 +00001384 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001385 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001386 needUnref = 1;
drh3b7511c2001-05-26 13:15:44 +00001387 }
1388 rc = sqlitepager_write(pOvfl);
1389 if( rc ){
drhdd793422001-06-28 01:54:48 +00001390 if( needUnref ) sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001391 return rc;
1392 }
drh14acc042001-06-10 19:56:58 +00001393 pOvfl->iNext = pPage1->freeList;
drh3b7511c2001-05-26 13:15:44 +00001394 pPage1->freeList = pgno;
drh2aa679f2001-06-25 02:11:07 +00001395 pPage1->nFree++;
drh5e2f8b92001-05-28 00:41:15 +00001396 memset(pOvfl->aPayload, 0, OVERFLOW_SIZE);
drhdd793422001-06-28 01:54:48 +00001397 pMemPage = (MemPage*)pPage;
1398 pMemPage->isInit = 0;
1399 if( pMemPage->pParent ){
1400 sqlitepager_unref(pMemPage->pParent);
1401 pMemPage->pParent = 0;
1402 }
1403 if( needUnref ) rc = sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001404 return rc;
1405}
1406
1407/*
1408** Erase all the data out of a cell. This involves returning overflow
1409** pages back the freelist.
1410*/
1411static int clearCell(Btree *pBt, Cell *pCell){
1412 Pager *pPager = pBt->pPager;
1413 OverflowPage *pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001414 Pgno ovfl, nextOvfl;
1415 int rc;
1416
drh5e2f8b92001-05-28 00:41:15 +00001417 if( pCell->h.nKey + pCell->h.nData <= MX_LOCAL_PAYLOAD ){
1418 return SQLITE_OK;
1419 }
drh3b7511c2001-05-26 13:15:44 +00001420 ovfl = pCell->ovfl;
1421 pCell->ovfl = 0;
1422 while( ovfl ){
drh8c42ca92001-06-22 19:15:00 +00001423 rc = sqlitepager_get(pPager, ovfl, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001424 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00001425 nextOvfl = pOvfl->iNext;
drhbd03cae2001-06-02 02:40:57 +00001426 rc = freePage(pBt, pOvfl, ovfl);
1427 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001428 sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001429 ovfl = nextOvfl;
drh3b7511c2001-05-26 13:15:44 +00001430 }
drh5e2f8b92001-05-28 00:41:15 +00001431 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00001432}
1433
1434/*
1435** Create a new cell from key and data. Overflow pages are allocated as
1436** necessary and linked to this cell.
1437*/
1438static int fillInCell(
1439 Btree *pBt, /* The whole Btree. Needed to allocate pages */
1440 Cell *pCell, /* Populate this Cell structure */
drh5c4d9702001-08-20 00:33:58 +00001441 const void *pKey, int nKey, /* The key */
1442 const void *pData,int nData /* The data */
drh3b7511c2001-05-26 13:15:44 +00001443){
drhdd793422001-06-28 01:54:48 +00001444 OverflowPage *pOvfl, *pPrior;
drh3b7511c2001-05-26 13:15:44 +00001445 Pgno *pNext;
1446 int spaceLeft;
drh8c42ca92001-06-22 19:15:00 +00001447 int n, rc;
drh3b7511c2001-05-26 13:15:44 +00001448 int nPayload;
drh5c4d9702001-08-20 00:33:58 +00001449 const char *pPayload;
drh3b7511c2001-05-26 13:15:44 +00001450 char *pSpace;
1451
drh5e2f8b92001-05-28 00:41:15 +00001452 pCell->h.leftChild = 0;
drh3b7511c2001-05-26 13:15:44 +00001453 pCell->h.nKey = nKey;
1454 pCell->h.nData = nData;
1455 pCell->h.iNext = 0;
1456
1457 pNext = &pCell->ovfl;
drh5e2f8b92001-05-28 00:41:15 +00001458 pSpace = pCell->aPayload;
drh3b7511c2001-05-26 13:15:44 +00001459 spaceLeft = MX_LOCAL_PAYLOAD;
1460 pPayload = pKey;
1461 pKey = 0;
1462 nPayload = nKey;
drhdd793422001-06-28 01:54:48 +00001463 pPrior = 0;
drh3b7511c2001-05-26 13:15:44 +00001464 while( nPayload>0 ){
1465 if( spaceLeft==0 ){
drh8c42ca92001-06-22 19:15:00 +00001466 rc = allocatePage(pBt, (MemPage**)&pOvfl, pNext);
drh3b7511c2001-05-26 13:15:44 +00001467 if( rc ){
1468 *pNext = 0;
drhdd793422001-06-28 01:54:48 +00001469 }
1470 if( pPrior ) sqlitepager_unref(pPrior);
1471 if( rc ){
drh5e2f8b92001-05-28 00:41:15 +00001472 clearCell(pBt, pCell);
drh3b7511c2001-05-26 13:15:44 +00001473 return rc;
1474 }
drhdd793422001-06-28 01:54:48 +00001475 pPrior = pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001476 spaceLeft = OVERFLOW_SIZE;
drh5e2f8b92001-05-28 00:41:15 +00001477 pSpace = pOvfl->aPayload;
drh8c42ca92001-06-22 19:15:00 +00001478 pNext = &pOvfl->iNext;
drh3b7511c2001-05-26 13:15:44 +00001479 }
1480 n = nPayload;
1481 if( n>spaceLeft ) n = spaceLeft;
1482 memcpy(pSpace, pPayload, n);
1483 nPayload -= n;
1484 if( nPayload==0 && pData ){
1485 pPayload = pData;
1486 nPayload = nData;
1487 pData = 0;
1488 }else{
1489 pPayload += n;
1490 }
1491 spaceLeft -= n;
1492 pSpace += n;
1493 }
drhdd793422001-06-28 01:54:48 +00001494 *pNext = 0;
1495 if( pPrior ){
1496 sqlitepager_unref(pPrior);
1497 }
drh3b7511c2001-05-26 13:15:44 +00001498 return SQLITE_OK;
1499}
1500
1501/*
drhbd03cae2001-06-02 02:40:57 +00001502** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00001503** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00001504** pointer in the third argument.
1505*/
1506static void reparentPage(Pager *pPager, Pgno pgno, MemPage *pNewParent){
1507 MemPage *pThis;
1508
drhdd793422001-06-28 01:54:48 +00001509 if( pgno==0 ) return;
1510 assert( pPager!=0 );
drhbd03cae2001-06-02 02:40:57 +00001511 pThis = sqlitepager_lookup(pPager, pgno);
drh6019e162001-07-02 17:51:45 +00001512 if( pThis && pThis->isInit ){
drhdd793422001-06-28 01:54:48 +00001513 if( pThis->pParent!=pNewParent ){
1514 if( pThis->pParent ) sqlitepager_unref(pThis->pParent);
1515 pThis->pParent = pNewParent;
1516 if( pNewParent ) sqlitepager_ref(pNewParent);
1517 }
1518 sqlitepager_unref(pThis);
drhbd03cae2001-06-02 02:40:57 +00001519 }
1520}
1521
1522/*
1523** Reparent all children of the given page to be the given page.
1524** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00001525** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00001526**
1527** This routine gets called after you memcpy() one page into
1528** another.
1529*/
drh8c42ca92001-06-22 19:15:00 +00001530static void reparentChildPages(Pager *pPager, MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00001531 int i;
1532 for(i=0; i<pPage->nCell; i++){
drh8c42ca92001-06-22 19:15:00 +00001533 reparentPage(pPager, pPage->apCell[i]->h.leftChild, pPage);
drhbd03cae2001-06-02 02:40:57 +00001534 }
drh14acc042001-06-10 19:56:58 +00001535 reparentPage(pPager, pPage->u.hdr.rightChild, pPage);
1536}
1537
1538/*
1539** Remove the i-th cell from pPage. This routine effects pPage only.
1540** The cell content is not freed or deallocated. It is assumed that
1541** the cell content has been copied someplace else. This routine just
1542** removes the reference to the cell from pPage.
1543**
1544** "sz" must be the number of bytes in the cell.
1545**
1546** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001547** Only the pPage->apCell[] array is important. The relinkCellList()
1548** routine will be called soon after this routine in order to rebuild
1549** the linked list.
drh14acc042001-06-10 19:56:58 +00001550*/
drh8c42ca92001-06-22 19:15:00 +00001551static void dropCell(MemPage *pPage, int idx, int sz){
drh14acc042001-06-10 19:56:58 +00001552 int j;
drh8c42ca92001-06-22 19:15:00 +00001553 assert( idx>=0 && idx<pPage->nCell );
1554 assert( sz==cellSize(pPage->apCell[idx]) );
drh6019e162001-07-02 17:51:45 +00001555 assert( sqlitepager_iswriteable(pPage) );
drh7c717f72001-06-24 20:39:41 +00001556 freeSpace(pPage, Addr(pPage->apCell[idx]) - Addr(pPage), sz);
1557 for(j=idx; j<pPage->nCell-1; j++){
drh14acc042001-06-10 19:56:58 +00001558 pPage->apCell[j] = pPage->apCell[j+1];
1559 }
1560 pPage->nCell--;
1561}
1562
1563/*
1564** Insert a new cell on pPage at cell index "i". pCell points to the
1565** content of the cell.
1566**
1567** If the cell content will fit on the page, then put it there. If it
1568** will not fit, then just make pPage->apCell[i] point to the content
1569** and set pPage->isOverfull.
1570**
1571** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001572** Only the pPage->apCell[] array is important. The relinkCellList()
1573** routine will be called soon after this routine in order to rebuild
1574** the linked list.
drh14acc042001-06-10 19:56:58 +00001575*/
1576static void insertCell(MemPage *pPage, int i, Cell *pCell, int sz){
1577 int idx, j;
1578 assert( i>=0 && i<=pPage->nCell );
1579 assert( sz==cellSize(pCell) );
drh6019e162001-07-02 17:51:45 +00001580 assert( sqlitepager_iswriteable(pPage) );
drh2aa679f2001-06-25 02:11:07 +00001581 idx = allocateSpace(pPage, sz);
drh14acc042001-06-10 19:56:58 +00001582 for(j=pPage->nCell; j>i; j--){
1583 pPage->apCell[j] = pPage->apCell[j-1];
1584 }
1585 pPage->nCell++;
drh14acc042001-06-10 19:56:58 +00001586 if( idx<=0 ){
1587 pPage->isOverfull = 1;
1588 pPage->apCell[i] = pCell;
1589 }else{
1590 memcpy(&pPage->u.aDisk[idx], pCell, sz);
drh8c42ca92001-06-22 19:15:00 +00001591 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[idx];
drh14acc042001-06-10 19:56:58 +00001592 }
1593}
1594
1595/*
1596** Rebuild the linked list of cells on a page so that the cells
drh8c42ca92001-06-22 19:15:00 +00001597** occur in the order specified by the pPage->apCell[] array.
1598** Invoke this routine once to repair damage after one or more
1599** invocations of either insertCell() or dropCell().
drh14acc042001-06-10 19:56:58 +00001600*/
1601static void relinkCellList(MemPage *pPage){
1602 int i;
1603 u16 *pIdx;
drh6019e162001-07-02 17:51:45 +00001604 assert( sqlitepager_iswriteable(pPage) );
drh14acc042001-06-10 19:56:58 +00001605 pIdx = &pPage->u.hdr.firstCell;
1606 for(i=0; i<pPage->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00001607 int idx = Addr(pPage->apCell[i]) - Addr(pPage);
drh8c42ca92001-06-22 19:15:00 +00001608 assert( idx>0 && idx<SQLITE_PAGE_SIZE );
drh14acc042001-06-10 19:56:58 +00001609 *pIdx = idx;
1610 pIdx = &pPage->apCell[i]->h.iNext;
1611 }
1612 *pIdx = 0;
1613}
1614
1615/*
1616** Make a copy of the contents of pFrom into pTo. The pFrom->apCell[]
drh5e00f6c2001-09-13 13:46:56 +00001617** pointers that point into pFrom->u.aDisk[] must be adjusted to point
drhdd793422001-06-28 01:54:48 +00001618** into pTo->u.aDisk[] instead. But some pFrom->apCell[] entries might
drh14acc042001-06-10 19:56:58 +00001619** not point to pFrom->u.aDisk[]. Those are unchanged.
1620*/
1621static void copyPage(MemPage *pTo, MemPage *pFrom){
1622 uptr from, to;
1623 int i;
1624 memcpy(pTo->u.aDisk, pFrom->u.aDisk, SQLITE_PAGE_SIZE);
drhdd793422001-06-28 01:54:48 +00001625 pTo->pParent = 0;
drh14acc042001-06-10 19:56:58 +00001626 pTo->isInit = 1;
1627 pTo->nCell = pFrom->nCell;
1628 pTo->nFree = pFrom->nFree;
1629 pTo->isOverfull = pFrom->isOverfull;
drh7c717f72001-06-24 20:39:41 +00001630 to = Addr(pTo);
1631 from = Addr(pFrom);
drh14acc042001-06-10 19:56:58 +00001632 for(i=0; i<pTo->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00001633 uptr x = Addr(pFrom->apCell[i]);
drh8c42ca92001-06-22 19:15:00 +00001634 if( x>from && x<from+SQLITE_PAGE_SIZE ){
1635 *((uptr*)&pTo->apCell[i]) = x + to - from;
drhdd793422001-06-28 01:54:48 +00001636 }else{
1637 pTo->apCell[i] = pFrom->apCell[i];
drh14acc042001-06-10 19:56:58 +00001638 }
1639 }
drhbd03cae2001-06-02 02:40:57 +00001640}
1641
1642/*
drh8b2f49b2001-06-08 00:21:52 +00001643** This routine redistributes Cells on pPage and up to two siblings
1644** of pPage so that all pages have about the same amount of free space.
drh14acc042001-06-10 19:56:58 +00001645** Usually one sibling on either side of pPage is used in the balancing,
drh8b2f49b2001-06-08 00:21:52 +00001646** though both siblings might come from one side if pPage is the first
1647** or last child of its parent. If pPage has fewer than two siblings
1648** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00001649** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00001650**
1651** The number of siblings of pPage might be increased or decreased by
drh8c42ca92001-06-22 19:15:00 +00001652** one in an effort to keep pages between 66% and 100% full. The root page
1653** is special and is allowed to be less than 66% full. If pPage is
1654** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00001655** or decreased by one, as necessary, to keep the root page from being
1656** overfull or empty.
1657**
drh14acc042001-06-10 19:56:58 +00001658** This routine calls relinkCellList() on its input page regardless of
1659** whether or not it does any real balancing. Client routines will typically
1660** invoke insertCell() or dropCell() before calling this routine, so we
1661** need to call relinkCellList() to clean up the mess that those other
1662** routines left behind.
1663**
1664** pCur is left pointing to the same cell as when this routine was called
drh8c42ca92001-06-22 19:15:00 +00001665** even if that cell gets moved to a different page. pCur may be NULL.
1666** Set the pCur parameter to NULL if you do not care about keeping track
1667** of a cell as that will save this routine the work of keeping track of it.
drh14acc042001-06-10 19:56:58 +00001668**
drh8b2f49b2001-06-08 00:21:52 +00001669** Note that when this routine is called, some of the Cells on pPage
drh14acc042001-06-10 19:56:58 +00001670** might not actually be stored in pPage->u.aDisk[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00001671** if the page is overfull. Part of the job of this routine is to
drh14acc042001-06-10 19:56:58 +00001672** make sure all Cells for pPage once again fit in pPage->u.aDisk[].
1673**
drh8c42ca92001-06-22 19:15:00 +00001674** In the course of balancing the siblings of pPage, the parent of pPage
1675** might become overfull or underfull. If that happens, then this routine
1676** is called recursively on the parent.
1677**
drh5e00f6c2001-09-13 13:46:56 +00001678** If this routine fails for any reason, it might leave the database
1679** in a corrupted state. So if this routine fails, the database should
1680** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00001681*/
drh14acc042001-06-10 19:56:58 +00001682static int balance(Btree *pBt, MemPage *pPage, BtCursor *pCur){
drh8b2f49b2001-06-08 00:21:52 +00001683 MemPage *pParent; /* The parent of pPage */
drh14acc042001-06-10 19:56:58 +00001684 MemPage *apOld[3]; /* pPage and up to two siblings */
drh8b2f49b2001-06-08 00:21:52 +00001685 Pgno pgnoOld[3]; /* Page numbers for each page in apOld[] */
drh14acc042001-06-10 19:56:58 +00001686 MemPage *apNew[4]; /* pPage and up to 3 siblings after balancing */
1687 Pgno pgnoNew[4]; /* Page numbers for each page in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00001688 int idxDiv[3]; /* Indices of divider cells in pParent */
1689 Cell *apDiv[3]; /* Divider cells in pParent */
1690 int nCell; /* Number of cells in apCell[] */
1691 int nOld; /* Number of pages in apOld[] */
1692 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00001693 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00001694 int i, j, k; /* Loop counters */
1695 int idx; /* Index of pPage in pParent->apCell[] */
1696 int nxDiv; /* Next divider slot in pParent->apCell[] */
1697 int rc; /* The return code */
1698 int iCur; /* apCell[iCur] is the cell of the cursor */
drh5edc3122001-09-13 21:53:09 +00001699 MemPage *pOldCurPage; /* The cursor originally points to this page */
drh8c42ca92001-06-22 19:15:00 +00001700 int totalSize; /* Total bytes for all cells */
drh6019e162001-07-02 17:51:45 +00001701 int subtotal; /* Subtotal of bytes in cells on one page */
1702 int cntNew[4]; /* Index in apCell[] of cell after i-th page */
1703 int szNew[4]; /* Combined size of cells place on i-th page */
drh9ca7d3b2001-06-28 11:50:21 +00001704 MemPage *extraUnref = 0; /* A page that needs to be unref-ed */
drh8c42ca92001-06-22 19:15:00 +00001705 Pgno pgno; /* Page number */
drh14acc042001-06-10 19:56:58 +00001706 Cell *apCell[MX_CELL*3+5]; /* All cells from pages being balanceed */
1707 int szCell[MX_CELL*3+5]; /* Local size of all cells */
1708 Cell aTemp[2]; /* Temporary holding area for apDiv[] */
1709 MemPage aOld[3]; /* Temporary copies of pPage and its siblings */
drh8b2f49b2001-06-08 00:21:52 +00001710
drh14acc042001-06-10 19:56:58 +00001711 /*
1712 ** Return without doing any work if pPage is neither overfull nor
1713 ** underfull.
drh8b2f49b2001-06-08 00:21:52 +00001714 */
drh6019e162001-07-02 17:51:45 +00001715 assert( sqlitepager_iswriteable(pPage) );
drha1b351a2001-09-14 16:42:12 +00001716 if( !pPage->isOverfull && pPage->nFree<SQLITE_PAGE_SIZE/2
1717 && pPage->nCell>=2){
drh14acc042001-06-10 19:56:58 +00001718 relinkCellList(pPage);
drh8b2f49b2001-06-08 00:21:52 +00001719 return SQLITE_OK;
1720 }
1721
1722 /*
drh14acc042001-06-10 19:56:58 +00001723 ** Find the parent of the page to be balanceed.
1724 ** If there is no parent, it means this page is the root page and
drh8b2f49b2001-06-08 00:21:52 +00001725 ** special rules apply.
1726 */
drh14acc042001-06-10 19:56:58 +00001727 pParent = pPage->pParent;
drh8b2f49b2001-06-08 00:21:52 +00001728 if( pParent==0 ){
1729 Pgno pgnoChild;
drh8c42ca92001-06-22 19:15:00 +00001730 MemPage *pChild;
drh8b2f49b2001-06-08 00:21:52 +00001731 if( pPage->nCell==0 ){
drh14acc042001-06-10 19:56:58 +00001732 if( pPage->u.hdr.rightChild ){
1733 /*
1734 ** The root page is empty. Copy the one child page
drh8b2f49b2001-06-08 00:21:52 +00001735 ** into the root page and return. This reduces the depth
1736 ** of the BTree by one.
1737 */
drh14acc042001-06-10 19:56:58 +00001738 pgnoChild = pPage->u.hdr.rightChild;
drh8c42ca92001-06-22 19:15:00 +00001739 rc = sqlitepager_get(pBt->pPager, pgnoChild, (void**)&pChild);
drh8b2f49b2001-06-08 00:21:52 +00001740 if( rc ) return rc;
1741 memcpy(pPage, pChild, SQLITE_PAGE_SIZE);
1742 pPage->isInit = 0;
drh6019e162001-07-02 17:51:45 +00001743 rc = initPage(pPage, sqlitepager_pagenumber(pPage), 0);
1744 assert( rc==SQLITE_OK );
drh8b2f49b2001-06-08 00:21:52 +00001745 reparentChildPages(pBt->pPager, pPage);
drh5edc3122001-09-13 21:53:09 +00001746 if( pCur && pCur->pPage==pChild ){
1747 sqlitepager_unref(pChild);
1748 pCur->pPage = pPage;
1749 sqlitepager_ref(pPage);
1750 }
drh8b2f49b2001-06-08 00:21:52 +00001751 freePage(pBt, pChild, pgnoChild);
1752 sqlitepager_unref(pChild);
drhefc251d2001-07-01 22:12:01 +00001753 }else{
1754 relinkCellList(pPage);
drh8b2f49b2001-06-08 00:21:52 +00001755 }
1756 return SQLITE_OK;
1757 }
drh14acc042001-06-10 19:56:58 +00001758 if( !pPage->isOverfull ){
drh8b2f49b2001-06-08 00:21:52 +00001759 /* It is OK for the root page to be less than half full.
1760 */
drh14acc042001-06-10 19:56:58 +00001761 relinkCellList(pPage);
drh8b2f49b2001-06-08 00:21:52 +00001762 return SQLITE_OK;
1763 }
drh14acc042001-06-10 19:56:58 +00001764 /*
1765 ** If we get to here, it means the root page is overfull.
drh8b2f49b2001-06-08 00:21:52 +00001766 ** When this happens, Create a new child page and copy the
1767 ** contents of the root into the child. Then make the root
drh14acc042001-06-10 19:56:58 +00001768 ** page an empty page with rightChild pointing to the new
drh8b2f49b2001-06-08 00:21:52 +00001769 ** child. Then fall thru to the code below which will cause
1770 ** the overfull child page to be split.
1771 */
drh14acc042001-06-10 19:56:58 +00001772 rc = sqlitepager_write(pPage);
1773 if( rc ) return rc;
drh8b2f49b2001-06-08 00:21:52 +00001774 rc = allocatePage(pBt, &pChild, &pgnoChild);
1775 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00001776 assert( sqlitepager_iswriteable(pChild) );
drh14acc042001-06-10 19:56:58 +00001777 copyPage(pChild, pPage);
1778 pChild->pParent = pPage;
drhdd793422001-06-28 01:54:48 +00001779 sqlitepager_ref(pPage);
drh14acc042001-06-10 19:56:58 +00001780 pChild->isOverfull = 1;
drh5edc3122001-09-13 21:53:09 +00001781 if( pCur && pCur->pPage==pPage ){
1782 sqlitepager_unref(pPage);
drh14acc042001-06-10 19:56:58 +00001783 pCur->pPage = pChild;
drh9ca7d3b2001-06-28 11:50:21 +00001784 }else{
1785 extraUnref = pChild;
drh8b2f49b2001-06-08 00:21:52 +00001786 }
drh8b2f49b2001-06-08 00:21:52 +00001787 zeroPage(pPage);
drh14acc042001-06-10 19:56:58 +00001788 pPage->u.hdr.rightChild = pgnoChild;
drh8b2f49b2001-06-08 00:21:52 +00001789 pParent = pPage;
1790 pPage = pChild;
drh8b2f49b2001-06-08 00:21:52 +00001791 }
drh6019e162001-07-02 17:51:45 +00001792 rc = sqlitepager_write(pParent);
1793 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00001794
drh8b2f49b2001-06-08 00:21:52 +00001795 /*
drh14acc042001-06-10 19:56:58 +00001796 ** Find the Cell in the parent page whose h.leftChild points back
1797 ** to pPage. The "idx" variable is the index of that cell. If pPage
1798 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00001799 */
1800 idx = -1;
1801 pgno = sqlitepager_pagenumber(pPage);
1802 for(i=0; i<pParent->nCell; i++){
1803 if( pParent->apCell[i]->h.leftChild==pgno ){
1804 idx = i;
1805 break;
1806 }
1807 }
drhdd793422001-06-28 01:54:48 +00001808 if( idx<0 && pParent->u.hdr.rightChild==pgno ){
1809 idx = pParent->nCell;
drh8b2f49b2001-06-08 00:21:52 +00001810 }
1811 if( idx<0 ){
drh14acc042001-06-10 19:56:58 +00001812 return SQLITE_CORRUPT;
drh8b2f49b2001-06-08 00:21:52 +00001813 }
1814
1815 /*
drh14acc042001-06-10 19:56:58 +00001816 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00001817 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00001818 */
drh14acc042001-06-10 19:56:58 +00001819 nOld = nNew = 0;
1820 sqlitepager_ref(pParent);
1821
1822 /*
1823 ** Find sibling pages to pPage and the Cells in pParent that divide
1824 ** the siblings. An attempt is made to find one sibling on either
1825 ** side of pPage. Both siblings are taken from one side, however, if
1826 ** pPage is either the first or last child of its parent. If pParent
1827 ** has 3 or fewer children then all children of pParent are taken.
1828 */
1829 if( idx==pParent->nCell ){
1830 nxDiv = idx - 2;
drh8b2f49b2001-06-08 00:21:52 +00001831 }else{
drh14acc042001-06-10 19:56:58 +00001832 nxDiv = idx - 1;
drh8b2f49b2001-06-08 00:21:52 +00001833 }
drh14acc042001-06-10 19:56:58 +00001834 if( nxDiv<0 ) nxDiv = 0;
drh8b2f49b2001-06-08 00:21:52 +00001835 nDiv = 0;
drh14acc042001-06-10 19:56:58 +00001836 for(i=0, k=nxDiv; i<3; i++, k++){
1837 if( k<pParent->nCell ){
1838 idxDiv[i] = k;
1839 apDiv[i] = pParent->apCell[k];
drh8b2f49b2001-06-08 00:21:52 +00001840 nDiv++;
1841 pgnoOld[i] = apDiv[i]->h.leftChild;
drh14acc042001-06-10 19:56:58 +00001842 }else if( k==pParent->nCell ){
drh8c42ca92001-06-22 19:15:00 +00001843 pgnoOld[i] = pParent->u.hdr.rightChild;
drh14acc042001-06-10 19:56:58 +00001844 }else{
1845 break;
drh8b2f49b2001-06-08 00:21:52 +00001846 }
drh8c42ca92001-06-22 19:15:00 +00001847 rc = sqlitepager_get(pBt->pPager, pgnoOld[i], (void**)&apOld[i]);
drh14acc042001-06-10 19:56:58 +00001848 if( rc ) goto balance_cleanup;
drh6019e162001-07-02 17:51:45 +00001849 rc = initPage(apOld[i], pgnoOld[i], pParent);
1850 if( rc ) goto balance_cleanup;
drh14acc042001-06-10 19:56:58 +00001851 nOld++;
drh8b2f49b2001-06-08 00:21:52 +00001852 }
1853
1854 /*
drh14acc042001-06-10 19:56:58 +00001855 ** Set iCur to be the index in apCell[] of the cell that the cursor
1856 ** is pointing to. We will need this later on in order to keep the
drh5edc3122001-09-13 21:53:09 +00001857 ** cursor pointing at the same cell. If pCur points to a page that
1858 ** has no involvement with this rebalancing, then set iCur to a large
1859 ** number so that the iCur==j tests always fail in the main cell
1860 ** distribution loop below.
drh14acc042001-06-10 19:56:58 +00001861 */
1862 if( pCur ){
drh5edc3122001-09-13 21:53:09 +00001863 iCur = 0;
1864 for(i=0; i<nOld; i++){
1865 if( pCur->pPage==apOld[i] ){
1866 iCur += pCur->idx;
1867 break;
1868 }
1869 iCur += apOld[i]->nCell;
1870 if( i<nOld-1 && pCur->pPage==pParent && pCur->idx==idxDiv[i] ){
1871 break;
1872 }
1873 iCur++;
drh14acc042001-06-10 19:56:58 +00001874 }
drh5edc3122001-09-13 21:53:09 +00001875 pOldCurPage = pCur->pPage;
drh14acc042001-06-10 19:56:58 +00001876 }
1877
1878 /*
1879 ** Make copies of the content of pPage and its siblings into aOld[].
1880 ** The rest of this function will use data from the copies rather
1881 ** that the original pages since the original pages will be in the
1882 ** process of being overwritten.
1883 */
1884 for(i=0; i<nOld; i++){
1885 copyPage(&aOld[i], apOld[i]);
1886 rc = freePage(pBt, apOld[i], pgnoOld[i]);
1887 if( rc ) goto balance_cleanup;
drhdd793422001-06-28 01:54:48 +00001888 sqlitepager_unref(apOld[i]);
drh14acc042001-06-10 19:56:58 +00001889 apOld[i] = &aOld[i];
1890 }
1891
1892 /*
1893 ** Load pointers to all cells on sibling pages and the divider cells
1894 ** into the local apCell[] array. Make copies of the divider cells
1895 ** into aTemp[] and remove the the divider Cells from pParent.
drh8b2f49b2001-06-08 00:21:52 +00001896 */
1897 nCell = 0;
1898 for(i=0; i<nOld; i++){
1899 MemPage *pOld = apOld[i];
1900 for(j=0; j<pOld->nCell; j++){
drh14acc042001-06-10 19:56:58 +00001901 apCell[nCell] = pOld->apCell[j];
1902 szCell[nCell] = cellSize(apCell[nCell]);
1903 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00001904 }
1905 if( i<nOld-1 ){
drh14acc042001-06-10 19:56:58 +00001906 szCell[nCell] = cellSize(apDiv[i]);
drh8c42ca92001-06-22 19:15:00 +00001907 memcpy(&aTemp[i], apDiv[i], szCell[nCell]);
drh14acc042001-06-10 19:56:58 +00001908 apCell[nCell] = &aTemp[i];
1909 dropCell(pParent, nxDiv, szCell[nCell]);
1910 assert( apCell[nCell]->h.leftChild==pgnoOld[i] );
1911 apCell[nCell]->h.leftChild = pOld->u.hdr.rightChild;
1912 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00001913 }
1914 }
1915
1916 /*
drh6019e162001-07-02 17:51:45 +00001917 ** Figure out the number of pages needed to hold all nCell cells.
1918 ** Store this number in "k". Also compute szNew[] which is the total
1919 ** size of all cells on the i-th page and cntNew[] which is the index
1920 ** in apCell[] of the cell that divides path i from path i+1.
1921 ** cntNew[k] should equal nCell.
1922 **
1923 ** This little patch of code is critical for keeping the tree
1924 ** balanced.
drh8b2f49b2001-06-08 00:21:52 +00001925 */
1926 totalSize = 0;
1927 for(i=0; i<nCell; i++){
drh14acc042001-06-10 19:56:58 +00001928 totalSize += szCell[i];
drh8b2f49b2001-06-08 00:21:52 +00001929 }
drh6019e162001-07-02 17:51:45 +00001930 for(subtotal=k=i=0; i<nCell; i++){
1931 subtotal += szCell[i];
1932 if( subtotal > USABLE_SPACE ){
1933 szNew[k] = subtotal - szCell[i];
1934 cntNew[k] = i;
1935 subtotal = 0;
1936 k++;
1937 }
1938 }
1939 szNew[k] = subtotal;
1940 cntNew[k] = nCell;
1941 k++;
1942 for(i=k-1; i>0; i--){
1943 while( szNew[i]<USABLE_SPACE/2 ){
1944 cntNew[i-1]--;
1945 assert( cntNew[i-1]>0 );
1946 szNew[i] += szCell[cntNew[i-1]];
1947 szNew[i-1] -= szCell[cntNew[i-1]-1];
1948 }
1949 }
1950 assert( cntNew[0]>0 );
drh8b2f49b2001-06-08 00:21:52 +00001951
1952 /*
drh6019e162001-07-02 17:51:45 +00001953 ** Allocate k new pages
drh8b2f49b2001-06-08 00:21:52 +00001954 */
drh14acc042001-06-10 19:56:58 +00001955 for(i=0; i<k; i++){
drh8b2f49b2001-06-08 00:21:52 +00001956 rc = allocatePage(pBt, &apNew[i], &pgnoNew[i]);
drh14acc042001-06-10 19:56:58 +00001957 if( rc ) goto balance_cleanup;
1958 nNew++;
drh8b2f49b2001-06-08 00:21:52 +00001959 zeroPage(apNew[i]);
drh6019e162001-07-02 17:51:45 +00001960 apNew[i]->isInit = 1;
drh8b2f49b2001-06-08 00:21:52 +00001961 }
1962
1963 /*
drh14acc042001-06-10 19:56:58 +00001964 ** Evenly distribute the data in apCell[] across the new pages.
1965 ** Insert divider cells into pParent as necessary.
1966 */
1967 j = 0;
1968 for(i=0; i<nNew; i++){
1969 MemPage *pNew = apNew[i];
drh6019e162001-07-02 17:51:45 +00001970 while( j<cntNew[i] ){
1971 assert( pNew->nFree>=szCell[j] );
drh14acc042001-06-10 19:56:58 +00001972 if( pCur && iCur==j ){ pCur->pPage = pNew; pCur->idx = pNew->nCell; }
1973 insertCell(pNew, pNew->nCell, apCell[j], szCell[j]);
1974 j++;
1975 }
drh6019e162001-07-02 17:51:45 +00001976 assert( pNew->nCell>0 );
drh14acc042001-06-10 19:56:58 +00001977 assert( !pNew->isOverfull );
1978 relinkCellList(pNew);
1979 if( i<nNew-1 && j<nCell ){
1980 pNew->u.hdr.rightChild = apCell[j]->h.leftChild;
1981 apCell[j]->h.leftChild = pgnoNew[i];
1982 if( pCur && iCur==j ){ pCur->pPage = pParent; pCur->idx = nxDiv; }
1983 insertCell(pParent, nxDiv, apCell[j], szCell[j]);
1984 j++;
1985 nxDiv++;
1986 }
1987 }
drh6019e162001-07-02 17:51:45 +00001988 assert( j==nCell );
drh14acc042001-06-10 19:56:58 +00001989 apNew[nNew-1]->u.hdr.rightChild = apOld[nOld-1]->u.hdr.rightChild;
1990 if( nxDiv==pParent->nCell ){
1991 pParent->u.hdr.rightChild = pgnoNew[nNew-1];
1992 }else{
1993 pParent->apCell[nxDiv]->h.leftChild = pgnoNew[nNew-1];
1994 }
1995 if( pCur ){
drh3fc190c2001-09-14 03:24:23 +00001996 if( j<=iCur && pCur->pPage==pParent && pCur->idx>idxDiv[nOld-1] ){
1997 assert( pCur->pPage==pOldCurPage );
1998 pCur->idx += nNew - nOld;
1999 }else{
2000 assert( pOldCurPage!=0 );
2001 sqlitepager_ref(pCur->pPage);
2002 sqlitepager_unref(pOldCurPage);
2003 }
drh14acc042001-06-10 19:56:58 +00002004 }
2005
2006 /*
2007 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00002008 */
2009 for(i=0; i<nNew; i++){
drh14acc042001-06-10 19:56:58 +00002010 reparentChildPages(pBt->pPager, apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002011 }
drh14acc042001-06-10 19:56:58 +00002012 reparentChildPages(pBt->pPager, pParent);
drh8b2f49b2001-06-08 00:21:52 +00002013
2014 /*
drh14acc042001-06-10 19:56:58 +00002015 ** balance the parent page.
drh8b2f49b2001-06-08 00:21:52 +00002016 */
drh5edc3122001-09-13 21:53:09 +00002017 rc = balance(pBt, pParent, pCur);
drh8b2f49b2001-06-08 00:21:52 +00002018
2019 /*
drh14acc042001-06-10 19:56:58 +00002020 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00002021 */
drh14acc042001-06-10 19:56:58 +00002022balance_cleanup:
drh9ca7d3b2001-06-28 11:50:21 +00002023 if( extraUnref ){
2024 sqlitepager_unref(extraUnref);
2025 }
drh8b2f49b2001-06-08 00:21:52 +00002026 for(i=0; i<nOld; i++){
drhdd793422001-06-28 01:54:48 +00002027 if( apOld[i]!=&aOld[i] ) sqlitepager_unref(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00002028 }
drh14acc042001-06-10 19:56:58 +00002029 for(i=0; i<nNew; i++){
2030 sqlitepager_unref(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002031 }
drh14acc042001-06-10 19:56:58 +00002032 if( pCur && pCur->pPage==0 ){
2033 pCur->pPage = pParent;
2034 pCur->idx = 0;
2035 }else{
2036 sqlitepager_unref(pParent);
drh8b2f49b2001-06-08 00:21:52 +00002037 }
2038 return rc;
2039}
2040
2041/*
drh3b7511c2001-05-26 13:15:44 +00002042** Insert a new record into the BTree. The key is given by (pKey,nKey)
2043** and the data is given by (pData,nData). The cursor is used only to
2044** define what database the record should be inserted into. The cursor
drh14acc042001-06-10 19:56:58 +00002045** is left pointing at the new record.
drh3b7511c2001-05-26 13:15:44 +00002046*/
2047int sqliteBtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00002048 BtCursor *pCur, /* Insert data into the table of this cursor */
drhbe0072d2001-09-13 14:46:09 +00002049 const void *pKey, int nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00002050 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00002051){
2052 Cell newCell;
2053 int rc;
2054 int loc;
drh14acc042001-06-10 19:56:58 +00002055 int szNew;
drh3b7511c2001-05-26 13:15:44 +00002056 MemPage *pPage;
2057 Btree *pBt = pCur->pBt;
2058
drh5edc3122001-09-13 21:53:09 +00002059 if( !pCur->pBt->inTrans || nKey+nData==0 ){
drh8b2f49b2001-06-08 00:21:52 +00002060 return SQLITE_ERROR; /* Must start a transaction first */
2061 }
drh14acc042001-06-10 19:56:58 +00002062 rc = sqliteBtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00002063 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002064 pPage = pCur->pPage;
2065 rc = sqlitepager_write(pPage);
drhbd03cae2001-06-02 02:40:57 +00002066 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00002067 rc = fillInCell(pBt, &newCell, pKey, nKey, pData, nData);
2068 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002069 szNew = cellSize(&newCell);
drh3b7511c2001-05-26 13:15:44 +00002070 if( loc==0 ){
drh14acc042001-06-10 19:56:58 +00002071 newCell.h.leftChild = pPage->apCell[pCur->idx]->h.leftChild;
2072 rc = clearCell(pBt, pPage->apCell[pCur->idx]);
drh5e2f8b92001-05-28 00:41:15 +00002073 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002074 dropCell(pPage, pCur->idx, cellSize(pPage->apCell[pCur->idx]));
drh7c717f72001-06-24 20:39:41 +00002075 }else if( loc<0 && pPage->nCell>0 ){
drh14acc042001-06-10 19:56:58 +00002076 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
2077 pCur->idx++;
2078 }else{
2079 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
drh3b7511c2001-05-26 13:15:44 +00002080 }
drh7c717f72001-06-24 20:39:41 +00002081 insertCell(pPage, pCur->idx, &newCell, szNew);
drh14acc042001-06-10 19:56:58 +00002082 rc = balance(pCur->pBt, pPage, pCur);
drh3fc190c2001-09-14 03:24:23 +00002083 /* sqliteBtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
2084 /* fflush(stdout); */
drh5e2f8b92001-05-28 00:41:15 +00002085 return rc;
2086}
2087
2088/*
drhbd03cae2001-06-02 02:40:57 +00002089** Delete the entry that the cursor is pointing to.
drh5e2f8b92001-05-28 00:41:15 +00002090**
drhbd03cae2001-06-02 02:40:57 +00002091** The cursor is left pointing at either the next or the previous
2092** entry. If the cursor is left pointing to the next entry, then
2093** the pCur->bSkipNext flag is set which forces the next call to
2094** sqliteBtreeNext() to be a no-op. That way, you can always call
2095** sqliteBtreeNext() after a delete and the cursor will be left
2096** pointing to the first entry after the deleted entry.
drh3b7511c2001-05-26 13:15:44 +00002097*/
2098int sqliteBtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00002099 MemPage *pPage = pCur->pPage;
2100 Cell *pCell;
2101 int rc;
drh8c42ca92001-06-22 19:15:00 +00002102 Pgno pgnoChild;
drh8b2f49b2001-06-08 00:21:52 +00002103
2104 if( !pCur->pBt->inTrans ){
2105 return SQLITE_ERROR; /* Must start a transaction first */
2106 }
drhbd03cae2001-06-02 02:40:57 +00002107 if( pCur->idx >= pPage->nCell ){
2108 return SQLITE_ERROR; /* The cursor is not pointing to anything */
2109 }
2110 rc = sqlitepager_write(pPage);
2111 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002112 pCell = pPage->apCell[pCur->idx];
drh14acc042001-06-10 19:56:58 +00002113 pgnoChild = pCell->h.leftChild;
drh8c42ca92001-06-22 19:15:00 +00002114 clearCell(pCur->pBt, pCell);
drh14acc042001-06-10 19:56:58 +00002115 if( pgnoChild ){
2116 /*
drh5e00f6c2001-09-13 13:46:56 +00002117 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00002118 ** do something we will leave a hole on an internal page.
2119 ** We have to fill the hole by moving in a cell from a leaf. The
2120 ** next Cell after the one to be deleted is guaranteed to exist and
2121 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00002122 */
drh14acc042001-06-10 19:56:58 +00002123 BtCursor leafCur;
2124 Cell *pNext;
2125 int szNext;
2126 getTempCursor(pCur, &leafCur);
2127 rc = sqliteBtreeNext(&leafCur, 0);
2128 if( rc!=SQLITE_OK ){
2129 return SQLITE_CORRUPT;
drh5e2f8b92001-05-28 00:41:15 +00002130 }
drh6019e162001-07-02 17:51:45 +00002131 rc = sqlitepager_write(leafCur.pPage);
2132 if( rc ) return rc;
drh9ca7d3b2001-06-28 11:50:21 +00002133 dropCell(pPage, pCur->idx, cellSize(pCell));
drh8c42ca92001-06-22 19:15:00 +00002134 pNext = leafCur.pPage->apCell[leafCur.idx];
drh14acc042001-06-10 19:56:58 +00002135 szNext = cellSize(pNext);
drh8c42ca92001-06-22 19:15:00 +00002136 pNext->h.leftChild = pgnoChild;
drh14acc042001-06-10 19:56:58 +00002137 insertCell(pPage, pCur->idx, pNext, szNext);
2138 rc = balance(pCur->pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002139 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002140 pCur->bSkipNext = 1;
drh14acc042001-06-10 19:56:58 +00002141 dropCell(leafCur.pPage, leafCur.idx, szNext);
2142 rc = balance(pCur->pBt, leafCur.pPage, 0);
drh8c42ca92001-06-22 19:15:00 +00002143 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00002144 }else{
drh9ca7d3b2001-06-28 11:50:21 +00002145 dropCell(pPage, pCur->idx, cellSize(pCell));
drh5edc3122001-09-13 21:53:09 +00002146 if( pCur->idx>=pPage->nCell ){
2147 pCur->idx = pPage->nCell-1;
2148 if( pCur->idx<0 ){ pCur->idx = 0; }
2149 pCur->bSkipNext = 0;
drh6019e162001-07-02 17:51:45 +00002150 }else{
2151 pCur->bSkipNext = 1;
2152 }
drh14acc042001-06-10 19:56:58 +00002153 rc = balance(pCur->pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002154 }
drh5e2f8b92001-05-28 00:41:15 +00002155 return rc;
drh3b7511c2001-05-26 13:15:44 +00002156}
drh8b2f49b2001-06-08 00:21:52 +00002157
2158/*
2159** Create a new BTree in the same file. Write into *piTable the index
2160** of the root page of the new table.
2161*/
2162int sqliteBtreeCreateTable(Btree *pBt, int *piTable){
2163 MemPage *pRoot;
2164 Pgno pgnoRoot;
2165 int rc;
2166 if( !pBt->inTrans ){
2167 return SQLITE_ERROR; /* Must start a transaction first */
2168 }
2169 rc = allocatePage(pBt, &pRoot, &pgnoRoot);
2170 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002171 assert( sqlitepager_iswriteable(pRoot) );
drh8b2f49b2001-06-08 00:21:52 +00002172 zeroPage(pRoot);
2173 sqlitepager_unref(pRoot);
2174 *piTable = (int)pgnoRoot;
2175 return SQLITE_OK;
2176}
2177
2178/*
2179** Erase the given database page and all its children. Return
2180** the page to the freelist.
2181*/
drh2aa679f2001-06-25 02:11:07 +00002182static int clearDatabasePage(Btree *pBt, Pgno pgno, int freePageFlag){
drh8b2f49b2001-06-08 00:21:52 +00002183 MemPage *pPage;
2184 int rc;
drh8b2f49b2001-06-08 00:21:52 +00002185 Cell *pCell;
2186 int idx;
2187
drh8c42ca92001-06-22 19:15:00 +00002188 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pPage);
drh8b2f49b2001-06-08 00:21:52 +00002189 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002190 rc = sqlitepager_write(pPage);
2191 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002192 idx = pPage->u.hdr.firstCell;
drh8b2f49b2001-06-08 00:21:52 +00002193 while( idx>0 ){
drh14acc042001-06-10 19:56:58 +00002194 pCell = (Cell*)&pPage->u.aDisk[idx];
drh8b2f49b2001-06-08 00:21:52 +00002195 idx = pCell->h.iNext;
2196 if( pCell->h.leftChild ){
drh2aa679f2001-06-25 02:11:07 +00002197 rc = clearDatabasePage(pBt, pCell->h.leftChild, 1);
drh8b2f49b2001-06-08 00:21:52 +00002198 if( rc ) return rc;
2199 }
drh8c42ca92001-06-22 19:15:00 +00002200 rc = clearCell(pBt, pCell);
drh8b2f49b2001-06-08 00:21:52 +00002201 if( rc ) return rc;
2202 }
drh2aa679f2001-06-25 02:11:07 +00002203 if( pPage->u.hdr.rightChild ){
2204 rc = clearDatabasePage(pBt, pPage->u.hdr.rightChild, 1);
2205 if( rc ) return rc;
2206 }
2207 if( freePageFlag ){
2208 rc = freePage(pBt, pPage, pgno);
2209 }else{
2210 zeroPage(pPage);
2211 }
drhdd793422001-06-28 01:54:48 +00002212 sqlitepager_unref(pPage);
drh2aa679f2001-06-25 02:11:07 +00002213 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002214}
2215
2216/*
2217** Delete all information from a single table in the database.
2218*/
2219int sqliteBtreeClearTable(Btree *pBt, int iTable){
2220 int rc;
2221 if( !pBt->inTrans ){
2222 return SQLITE_ERROR; /* Must start a transaction first */
2223 }
drh2aa679f2001-06-25 02:11:07 +00002224 rc = clearDatabasePage(pBt, (Pgno)iTable, 0);
drh8b2f49b2001-06-08 00:21:52 +00002225 if( rc ){
2226 sqliteBtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00002227 }
drh8c42ca92001-06-22 19:15:00 +00002228 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002229}
2230
2231/*
2232** Erase all information in a table and add the root of the table to
2233** the freelist. Except, the root of the principle table (the one on
2234** page 2) is never added to the freelist.
2235*/
2236int sqliteBtreeDropTable(Btree *pBt, int iTable){
2237 int rc;
2238 MemPage *pPage;
2239 if( !pBt->inTrans ){
2240 return SQLITE_ERROR; /* Must start a transaction first */
2241 }
drh8c42ca92001-06-22 19:15:00 +00002242 rc = sqlitepager_get(pBt->pPager, (Pgno)iTable, (void**)&pPage);
drh2aa679f2001-06-25 02:11:07 +00002243 if( rc ) return rc;
2244 rc = sqliteBtreeClearTable(pBt, iTable);
2245 if( rc ) return rc;
2246 if( iTable>2 ){
2247 rc = freePage(pBt, pPage, iTable);
2248 }else{
2249 zeroPage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00002250 }
drhdd793422001-06-28 01:54:48 +00002251 sqlitepager_unref(pPage);
drh8b2f49b2001-06-08 00:21:52 +00002252 return rc;
2253}
2254
2255/*
2256** Read the meta-information out of a database file.
2257*/
2258int sqliteBtreeGetMeta(Btree *pBt, int *aMeta){
2259 PageOne *pP1;
2260 int rc;
2261
drh8c42ca92001-06-22 19:15:00 +00002262 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00002263 if( rc ) return rc;
drh2aa679f2001-06-25 02:11:07 +00002264 aMeta[0] = pP1->nFree;
2265 memcpy(&aMeta[1], pP1->aMeta, sizeof(pP1->aMeta));
drh8b2f49b2001-06-08 00:21:52 +00002266 sqlitepager_unref(pP1);
2267 return SQLITE_OK;
2268}
2269
2270/*
2271** Write meta-information back into the database.
2272*/
2273int sqliteBtreeUpdateMeta(Btree *pBt, int *aMeta){
2274 PageOne *pP1;
2275 int rc;
2276 if( !pBt->inTrans ){
2277 return SQLITE_ERROR; /* Must start a transaction first */
2278 }
2279 pP1 = pBt->page1;
2280 rc = sqlitepager_write(pP1);
drh2aa679f2001-06-25 02:11:07 +00002281 if( rc ) return rc;
2282 memcpy(pP1->aMeta, &aMeta[1], sizeof(pP1->aMeta));
drh8b2f49b2001-06-08 00:21:52 +00002283 return SQLITE_OK;
2284}
drh8c42ca92001-06-22 19:15:00 +00002285
drh5eddca62001-06-30 21:53:53 +00002286/******************************************************************************
2287** The complete implementation of the BTree subsystem is above this line.
2288** All the code the follows is for testing and troubleshooting the BTree
2289** subsystem. None of the code that follows is used during normal operation.
2290** All of the following code is omitted unless the library is compiled with
2291** the -DSQLITE_TEST=1 compiler option.
2292******************************************************************************/
drh5edc3122001-09-13 21:53:09 +00002293#if 1
drh5eddca62001-06-30 21:53:53 +00002294
drh8c42ca92001-06-22 19:15:00 +00002295/*
2296** Print a disassembly of the given page on standard output. This routine
2297** is used for debugging and testing only.
2298*/
drh6019e162001-07-02 17:51:45 +00002299int sqliteBtreePageDump(Btree *pBt, int pgno, int recursive){
drh8c42ca92001-06-22 19:15:00 +00002300 int rc;
2301 MemPage *pPage;
2302 int i, j;
2303 int nFree;
2304 u16 idx;
2305 char range[20];
2306 unsigned char payload[20];
2307 rc = sqlitepager_get(pBt->pPager, (Pgno)pgno, (void**)&pPage);
2308 if( rc ){
2309 return rc;
2310 }
drh6019e162001-07-02 17:51:45 +00002311 if( recursive ) printf("PAGE %d:\n", pgno);
drh8c42ca92001-06-22 19:15:00 +00002312 i = 0;
2313 idx = pPage->u.hdr.firstCell;
2314 while( idx>0 && idx<=SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2315 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
2316 int sz = cellSize(pCell);
2317 sprintf(range,"%d..%d", idx, idx+sz-1);
drh2aa679f2001-06-25 02:11:07 +00002318 sz = pCell->h.nKey + pCell->h.nData;
drh8c42ca92001-06-22 19:15:00 +00002319 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
2320 memcpy(payload, pCell->aPayload, sz);
2321 for(j=0; j<sz; j++){
2322 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
2323 }
2324 payload[sz] = 0;
2325 printf(
drh6019e162001-07-02 17:51:45 +00002326 "cell %2d: i=%-10s chld=%-4d nk=%-4d nd=%-4d payload=%s\n",
drh8c42ca92001-06-22 19:15:00 +00002327 i, range, (int)pCell->h.leftChild, pCell->h.nKey, pCell->h.nData,
drh2aa679f2001-06-25 02:11:07 +00002328 payload
drh8c42ca92001-06-22 19:15:00 +00002329 );
drh6019e162001-07-02 17:51:45 +00002330 if( pPage->isInit && pPage->apCell[i]!=pCell ){
drh2aa679f2001-06-25 02:11:07 +00002331 printf("**** apCell[%d] does not match on prior entry ****\n", i);
2332 }
drh7c717f72001-06-24 20:39:41 +00002333 i++;
drh8c42ca92001-06-22 19:15:00 +00002334 idx = pCell->h.iNext;
2335 }
2336 if( idx!=0 ){
2337 printf("ERROR: next cell index out of range: %d\n", idx);
2338 }
2339 printf("right_child: %d\n", pPage->u.hdr.rightChild);
2340 nFree = 0;
2341 i = 0;
2342 idx = pPage->u.hdr.firstFree;
2343 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2344 FreeBlk *p = (FreeBlk*)&pPage->u.aDisk[idx];
2345 sprintf(range,"%d..%d", idx, idx+p->iSize-1);
2346 nFree += p->iSize;
2347 printf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
2348 i, range, p->iSize, nFree);
2349 idx = p->iNext;
drh2aa679f2001-06-25 02:11:07 +00002350 i++;
drh8c42ca92001-06-22 19:15:00 +00002351 }
2352 if( idx!=0 ){
2353 printf("ERROR: next freeblock index out of range: %d\n", idx);
2354 }
drh6019e162001-07-02 17:51:45 +00002355 if( recursive && pPage->u.hdr.rightChild!=0 ){
2356 idx = pPage->u.hdr.firstCell;
2357 while( idx>0 && idx<SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2358 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
2359 sqliteBtreePageDump(pBt, pCell->h.leftChild, 1);
2360 idx = pCell->h.iNext;
2361 }
2362 sqliteBtreePageDump(pBt, pPage->u.hdr.rightChild, 1);
2363 }
drh8c42ca92001-06-22 19:15:00 +00002364 sqlitepager_unref(pPage);
2365 return SQLITE_OK;
2366}
drh8c42ca92001-06-22 19:15:00 +00002367
drh8c42ca92001-06-22 19:15:00 +00002368/*
drh2aa679f2001-06-25 02:11:07 +00002369** Fill aResult[] with information about the entry and page that the
2370** cursor is pointing to.
2371**
2372** aResult[0] = The page number
2373** aResult[1] = The entry number
2374** aResult[2] = Total number of entries on this page
2375** aResult[3] = Size of this entry
2376** aResult[4] = Number of free bytes on this page
2377** aResult[5] = Number of free blocks on the page
2378** aResult[6] = Page number of the left child of this entry
2379** aResult[7] = Page number of the right child for the whole page
drh5eddca62001-06-30 21:53:53 +00002380**
2381** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00002382*/
2383int sqliteBtreeCursorDump(BtCursor *pCur, int *aResult){
drh2aa679f2001-06-25 02:11:07 +00002384 int cnt, idx;
2385 MemPage *pPage = pCur->pPage;
2386 aResult[0] = sqlitepager_pagenumber(pPage);
drh8c42ca92001-06-22 19:15:00 +00002387 aResult[1] = pCur->idx;
drh2aa679f2001-06-25 02:11:07 +00002388 aResult[2] = pPage->nCell;
2389 if( pCur->idx>=0 && pCur->idx<pPage->nCell ){
2390 aResult[3] = cellSize(pPage->apCell[pCur->idx]);
2391 aResult[6] = pPage->apCell[pCur->idx]->h.leftChild;
2392 }else{
2393 aResult[3] = 0;
2394 aResult[6] = 0;
2395 }
2396 aResult[4] = pPage->nFree;
2397 cnt = 0;
2398 idx = pPage->u.hdr.firstFree;
2399 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2400 cnt++;
2401 idx = ((FreeBlk*)&pPage->u.aDisk[idx])->iNext;
2402 }
2403 aResult[5] = cnt;
2404 aResult[7] = pPage->u.hdr.rightChild;
drh8c42ca92001-06-22 19:15:00 +00002405 return SQLITE_OK;
2406}
drhdd793422001-06-28 01:54:48 +00002407
drhdd793422001-06-28 01:54:48 +00002408/*
drh5eddca62001-06-30 21:53:53 +00002409** Return the pager associated with a BTree. This routine is used for
2410** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00002411*/
2412Pager *sqliteBtreePager(Btree *pBt){
2413 return pBt->pPager;
2414}
drh5eddca62001-06-30 21:53:53 +00002415
2416/*
2417** This structure is passed around through all the sanity checking routines
2418** in order to keep track of some global state information.
2419*/
2420typedef struct SanityCheck SanityCheck;
2421struct SanityCheck {
2422 Btree *pBt; // The tree being checked out
2423 Pager *pPager; // The associated pager. Also accessible by pBt->pPager
2424 int nPage; // Number of pages in the database
2425 int *anRef; // Number of times each page is referenced
drh6019e162001-07-02 17:51:45 +00002426 int nTreePage; // Number of BTree pages
2427 int nByte; // Number of bytes of data stored on BTree pages
drh5eddca62001-06-30 21:53:53 +00002428 char *zErrMsg; // An error message. NULL of no errors seen.
2429};
2430
2431/*
2432** Append a message to the error message string.
2433*/
2434static void checkAppendMsg(SanityCheck *pCheck, char *zMsg1, char *zMsg2){
2435 if( pCheck->zErrMsg ){
2436 char *zOld = pCheck->zErrMsg;
2437 pCheck->zErrMsg = 0;
2438 sqliteSetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, 0);
2439 sqliteFree(zOld);
2440 }else{
2441 sqliteSetString(&pCheck->zErrMsg, zMsg1, zMsg2, 0);
2442 }
2443}
2444
2445/*
2446** Add 1 to the reference count for page iPage. If this is the second
2447** reference to the page, add an error message to pCheck->zErrMsg.
2448** Return 1 if there are 2 ore more references to the page and 0 if
2449** if this is the first reference to the page.
2450**
2451** Also check that the page number is in bounds.
2452*/
2453static int checkRef(SanityCheck *pCheck, int iPage, char *zContext){
2454 if( iPage==0 ) return 1;
2455 if( iPage>pCheck->nPage ){
2456 char zBuf[100];
2457 sprintf(zBuf, "invalid page number %d", iPage);
2458 checkAppendMsg(pCheck, zContext, zBuf);
2459 return 1;
2460 }
2461 if( pCheck->anRef[iPage]==1 ){
2462 char zBuf[100];
2463 sprintf(zBuf, "2nd reference to page %d", iPage);
2464 checkAppendMsg(pCheck, zContext, zBuf);
2465 return 1;
2466 }
2467 return (pCheck->anRef[iPage]++)>1;
2468}
2469
2470/*
2471** Check the integrity of the freelist or of an overflow page list.
2472** Verify that the number of pages on the list is N.
2473*/
2474static void checkList(SanityCheck *pCheck, int iPage, int N, char *zContext){
2475 char zMsg[100];
2476 while( N-- ){
2477 OverflowPage *pOvfl;
2478 if( iPage<1 ){
2479 sprintf(zMsg, "%d pages missing from overflow list", N+1);
2480 checkAppendMsg(pCheck, zContext, zMsg);
2481 break;
2482 }
2483 if( checkRef(pCheck, iPage, zContext) ) break;
2484 if( sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
2485 sprintf(zMsg, "failed to get page %d", iPage);
2486 checkAppendMsg(pCheck, zContext, zMsg);
2487 break;
2488 }
2489 iPage = (int)pOvfl->iNext;
2490 sqlitepager_unref(pOvfl);
2491 }
2492}
2493
2494/*
2495** Do various sanity checks on a single page of a tree. Return
2496** the tree depth. Root pages return 0. Parents of root pages
2497** return 1, and so forth.
2498**
2499** These checks are done:
2500**
2501** 1. Make sure that cells and freeblocks do not overlap
2502** but combine to completely cover the page.
2503** 2. Make sure cell keys are in order.
2504** 3. Make sure no key is less than or equal to zLowerBound.
2505** 4. Make sure no key is greater than or equal to zUpperBound.
2506** 5. Check the integrity of overflow pages.
2507** 6. Recursively call checkTreePage on all children.
2508** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00002509** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00002510** the root of the tree.
2511*/
2512static int checkTreePage(
2513 SanityCheck *pCheck, /* Context for the sanity check */
2514 int iPage, /* Page number of the page to check */
2515 MemPage *pParent, /* Parent page */
2516 char *zParentContext, /* Parent context */
2517 char *zLowerBound, /* All keys should be greater than this, if not NULL */
2518 char *zUpperBound /* All keys should be less than this, if not NULL */
2519){
2520 MemPage *pPage;
2521 int i, rc, depth, d2, pgno;
2522 char *zKey1, *zKey2;
2523 BtCursor cur;
2524 char zMsg[100];
2525 char zContext[100];
2526 char hit[SQLITE_PAGE_SIZE];
2527
2528 /* Check that the page exists
2529 */
2530 if( iPage==0 ) return 0;
2531 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
2532 sprintf(zContext, "On tree page %d: ", iPage);
2533 if( (rc = sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pPage))!=0 ){
2534 sprintf(zMsg, "unable to get the page. error code=%d", rc);
2535 checkAppendMsg(pCheck, zContext, zMsg);
2536 return 0;
2537 }
2538 if( (rc = initPage(pPage, (Pgno)iPage, pParent))!=0 ){
2539 sprintf(zMsg, "initPage() returns error code %d", rc);
2540 checkAppendMsg(pCheck, zContext, zMsg);
2541 sqlitepager_unref(pPage);
2542 return 0;
2543 }
2544
2545 /* Check out all the cells.
2546 */
2547 depth = 0;
2548 zKey1 = zLowerBound ? sqliteStrDup(zLowerBound) : 0;
2549 cur.pPage = pPage;
2550 cur.pBt = pCheck->pBt;
2551 for(i=0; i<pPage->nCell; i++){
2552 Cell *pCell = pPage->apCell[i];
2553 int sz;
2554
2555 /* Check payload overflow pages
2556 */
2557 sz = pCell->h.nKey + pCell->h.nData;
2558 sprintf(zContext, "On page %d cell %d: ", iPage, i);
2559 if( sz>MX_LOCAL_PAYLOAD ){
2560 int nPage = (sz - MX_LOCAL_PAYLOAD + OVERFLOW_SIZE - 1)/OVERFLOW_SIZE;
2561 checkList(pCheck, pCell->ovfl, nPage, zContext);
2562 }
2563
2564 /* Check that keys are in the right order
2565 */
2566 cur.idx = i;
2567 zKey2 = sqliteMalloc( pCell->h.nKey+1 );
2568 getPayload(&cur, 0, pCell->h.nKey, zKey2);
2569 if( zKey1 && strcmp(zKey1,zKey2)>=0 ){
2570 checkAppendMsg(pCheck, zContext, "Key is out of order");
2571 }
2572
2573 /* Check sanity of left child page.
2574 */
2575 pgno = (int)pCell->h.leftChild;
2576 d2 = checkTreePage(pCheck, pgno, pPage, zContext, zKey1, zKey2);
2577 if( i>0 && d2!=depth ){
2578 checkAppendMsg(pCheck, zContext, "Child page depth differs");
2579 }
2580 depth = d2;
2581 sqliteFree(zKey1);
2582 zKey1 = zKey2;
2583 }
2584 pgno = pPage->u.hdr.rightChild;
2585 sprintf(zContext, "On page %d at right child: ", iPage);
2586 checkTreePage(pCheck, pgno, pPage, zContext, zKey1, zUpperBound);
2587 sqliteFree(zKey1);
2588
2589 /* Check for complete coverage of the page
2590 */
2591 memset(hit, 0, sizeof(hit));
2592 memset(hit, 1, sizeof(PageHdr));
2593 for(i=pPage->u.hdr.firstCell; i>0 && i<SQLITE_PAGE_SIZE; ){
2594 Cell *pCell = (Cell*)&pPage->u.aDisk[i];
2595 int j;
2596 for(j=i+cellSize(pCell)-1; j>=i; j--) hit[j]++;
2597 i = pCell->h.iNext;
2598 }
2599 for(i=pPage->u.hdr.firstFree; i>0 && i<SQLITE_PAGE_SIZE; ){
2600 FreeBlk *pFBlk = (FreeBlk*)&pPage->u.aDisk[i];
2601 int j;
2602 for(j=i+pFBlk->iSize-1; j>=i; j--) hit[j]++;
2603 i = pFBlk->iNext;
2604 }
2605 for(i=0; i<SQLITE_PAGE_SIZE; i++){
2606 if( hit[i]==0 ){
2607 sprintf(zMsg, "Unused space at byte %d of page %d", i, iPage);
2608 checkAppendMsg(pCheck, zMsg, 0);
2609 break;
2610 }else if( hit[i]>1 ){
2611 sprintf(zMsg, "Multiple uses for byte %d of page %d", i, iPage);
2612 checkAppendMsg(pCheck, zMsg, 0);
2613 break;
2614 }
2615 }
2616
2617 /* Check that free space is kept to a minimum
2618 */
drh6019e162001-07-02 17:51:45 +00002619#if 0
2620 if( pParent && pParent->nCell>2 && pPage->nFree>3*SQLITE_PAGE_SIZE/4 ){
drh5eddca62001-06-30 21:53:53 +00002621 sprintf(zMsg, "free space (%d) greater than max (%d)", pPage->nFree,
2622 SQLITE_PAGE_SIZE/3);
2623 checkAppendMsg(pCheck, zContext, zMsg);
2624 }
drh6019e162001-07-02 17:51:45 +00002625#endif
2626
2627 /* Update freespace totals.
2628 */
2629 pCheck->nTreePage++;
2630 pCheck->nByte += USABLE_SPACE - pPage->nFree;
drh5eddca62001-06-30 21:53:53 +00002631
2632 sqlitepager_unref(pPage);
2633 return depth;
2634}
2635
2636/*
2637** This routine does a complete check of the given BTree file. aRoot[] is
2638** an array of pages numbers were each page number is the root page of
2639** a table. nRoot is the number of entries in aRoot.
2640**
2641** If everything checks out, this routine returns NULL. If something is
2642** amiss, an error message is written into memory obtained from malloc()
2643** and a pointer to that error message is returned. The calling function
2644** is responsible for freeing the error message when it is done.
2645*/
2646char *sqliteBtreeSanityCheck(Btree *pBt, int *aRoot, int nRoot){
2647 int i;
2648 int nRef;
2649 SanityCheck sCheck;
2650
2651 nRef = *sqlitepager_stats(pBt->pPager);
drhefc251d2001-07-01 22:12:01 +00002652 if( lockBtree(pBt)!=SQLITE_OK ){
2653 return sqliteStrDup("Unable to acquire a read lock on the database");
2654 }
drh5eddca62001-06-30 21:53:53 +00002655 sCheck.pBt = pBt;
2656 sCheck.pPager = pBt->pPager;
2657 sCheck.nPage = sqlitepager_pagecount(sCheck.pPager);
2658 sCheck.anRef = sqliteMalloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
2659 sCheck.anRef[1] = 1;
2660 for(i=2; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
2661 sCheck.zErrMsg = 0;
2662
2663 /* Check the integrity of the freelist
2664 */
2665 checkList(&sCheck, pBt->page1->freeList, pBt->page1->nFree,"Main freelist: ");
2666
2667 /* Check all the tables.
2668 */
2669 for(i=0; i<nRoot; i++){
2670 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0, 0);
2671 }
2672
2673 /* Make sure every page in the file is referenced
2674 */
2675 for(i=1; i<=sCheck.nPage; i++){
2676 if( sCheck.anRef[i]==0 ){
2677 char zBuf[100];
2678 sprintf(zBuf, "Page %d is never used", i);
2679 checkAppendMsg(&sCheck, zBuf, 0);
2680 }
2681 }
2682
2683 /* Make sure this analysis did not leave any unref() pages
2684 */
drh5e00f6c2001-09-13 13:46:56 +00002685 unlockBtreeIfUnused(pBt);
drh5eddca62001-06-30 21:53:53 +00002686 if( nRef != *sqlitepager_stats(pBt->pPager) ){
2687 char zBuf[100];
2688 sprintf(zBuf,
2689 "Outstanding page count goes from %d to %d during this analysis",
2690 nRef, *sqlitepager_stats(pBt->pPager)
2691 );
2692 checkAppendMsg(&sCheck, zBuf, 0);
2693 }
2694
2695 /* Clean up and report errors.
2696 */
2697 sqliteFree(sCheck.anRef);
2698 return sCheck.zErrMsg;
2699}
2700
2701#endif /* SQLITE_TEST */