blob: 0508d997105c69b0cb10b23609d15df5ca4f17a2 [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*************************************************************************
drh5edc3122001-09-13 21:53:09 +000024** $Id: btree.c,v 1.24 2001/09/13 21:53:09 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;
drh8c42ca92001-06-22 19:15:00 +000076/* typedef unsigned int u32; -- already defined in sqliteInt.h */
drh365d68f2001-05-11 11:02:46 +000077typedef unsigned short int u16;
drh5e2f8b92001-05-28 00:41:15 +000078typedef unsigned char u8;
drh365d68f2001-05-11 11:02:46 +000079
80/*
drh8c42ca92001-06-22 19:15:00 +000081** This macro casts a pointer to an integer. Useful for doing
82** pointer arithmetic.
83*/
drh7c717f72001-06-24 20:39:41 +000084#define Addr(X) ((uptr)X)
drh8c42ca92001-06-22 19:15:00 +000085
86/*
drh365d68f2001-05-11 11:02:46 +000087** Forward declarations of structures used only in this file.
88*/
drhbd03cae2001-06-02 02:40:57 +000089typedef struct PageOne PageOne;
drh2af926b2001-05-15 00:39:25 +000090typedef struct MemPage MemPage;
drh365d68f2001-05-11 11:02:46 +000091typedef struct PageHdr PageHdr;
92typedef struct Cell Cell;
drh3b7511c2001-05-26 13:15:44 +000093typedef struct CellHdr CellHdr;
drh365d68f2001-05-11 11:02:46 +000094typedef struct FreeBlk FreeBlk;
drh2af926b2001-05-15 00:39:25 +000095typedef struct OverflowPage OverflowPage;
96
97/*
98** All structures on a database page are aligned to 4-byte boundries.
99** This routine rounds up a number of bytes to the next multiple of 4.
drh306dc212001-05-21 13:45:10 +0000100**
101** This might need to change for computer architectures that require
102** and 8-byte alignment boundry for structures.
drh2af926b2001-05-15 00:39:25 +0000103*/
104#define ROUNDUP(X) ((X+3) & ~3)
drha059ad02001-04-17 20:09:11 +0000105
drh08ed44e2001-04-29 23:32:55 +0000106/*
drhbd03cae2001-06-02 02:40:57 +0000107** This is a magic string that appears at the beginning of every
drh8c42ca92001-06-22 19:15:00 +0000108** SQLite database in order to identify the file as a real database.
drh08ed44e2001-04-29 23:32:55 +0000109*/
drhbd03cae2001-06-02 02:40:57 +0000110static const char zMagicHeader[] =
drh8c42ca92001-06-22 19:15:00 +0000111 "** This file contains an SQLite 2.0 database **";
drhbd03cae2001-06-02 02:40:57 +0000112#define MAGIC_SIZE (sizeof(zMagicHeader))
drh08ed44e2001-04-29 23:32:55 +0000113
114/*
drh5e00f6c2001-09-13 13:46:56 +0000115** This is a magic integer also used to test the integrity of the database
drh8c42ca92001-06-22 19:15:00 +0000116** file. This integer is used in addition to the string above so that
117** if the file is written on a little-endian architecture and read
118** on a big-endian architectures (or vice versa) we can detect the
119** problem.
120**
121** The number used was obtained at random and has no special
122** significance.
123*/
124#define MAGIC 0xdae37528
125
126/*
drhbd03cae2001-06-02 02:40:57 +0000127** The first page of the database file contains a magic header string
128** to identify the file as an SQLite database file. It also contains
129** a pointer to the first free page of the file. Page 2 contains the
drh8b2f49b2001-06-08 00:21:52 +0000130** root of the principle BTree. The file might contain other BTrees
131** rooted on pages above 2.
132**
133** The first page also contains SQLITE_N_BTREE_META integers that
134** can be used by higher-level routines.
drh08ed44e2001-04-29 23:32:55 +0000135**
drhbd03cae2001-06-02 02:40:57 +0000136** Remember that pages are numbered beginning with 1. (See pager.c
137** for additional information.) Page 0 does not exist and a page
138** number of 0 is used to mean "no such page".
139*/
140struct PageOne {
141 char zMagic[MAGIC_SIZE]; /* String that identifies the file as a database */
drh8c42ca92001-06-22 19:15:00 +0000142 int iMagic; /* Integer to verify correct byte order */
143 Pgno freeList; /* First free page in a list of all free pages */
drh2aa679f2001-06-25 02:11:07 +0000144 int nFree; /* Number of pages on the free list */
145 int aMeta[SQLITE_N_BTREE_META-1]; /* User defined integers */
drhbd03cae2001-06-02 02:40:57 +0000146};
147
148/*
149** Each database page has a header that is an instance of this
150** structure.
drh08ed44e2001-04-29 23:32:55 +0000151**
drh8b2f49b2001-06-08 00:21:52 +0000152** PageHdr.firstFree is 0 if there is no free space on this page.
drh14acc042001-06-10 19:56:58 +0000153** Otherwise, PageHdr.firstFree is the index in MemPage.u.aDisk[] of a
drh8b2f49b2001-06-08 00:21:52 +0000154** FreeBlk structure that describes the first block of free space.
155** All free space is defined by a linked list of FreeBlk structures.
drh08ed44e2001-04-29 23:32:55 +0000156**
drh8b2f49b2001-06-08 00:21:52 +0000157** Data is stored in a linked list of Cell structures. PageHdr.firstCell
drh14acc042001-06-10 19:56:58 +0000158** is the index into MemPage.u.aDisk[] of the first cell on the page. The
drh306dc212001-05-21 13:45:10 +0000159** Cells are kept in sorted order.
drh8b2f49b2001-06-08 00:21:52 +0000160**
161** A Cell contains all information about a database entry and a pointer
162** to a child page that contains other entries less than itself. In
163** other words, the i-th Cell contains both Ptr(i) and Key(i). The
164** right-most pointer of the page is contained in PageHdr.rightChild.
drh08ed44e2001-04-29 23:32:55 +0000165*/
drh365d68f2001-05-11 11:02:46 +0000166struct PageHdr {
drh5e2f8b92001-05-28 00:41:15 +0000167 Pgno rightChild; /* Child page that comes after all cells on this page */
drh14acc042001-06-10 19:56:58 +0000168 u16 firstCell; /* Index in MemPage.u.aDisk[] of the first cell */
169 u16 firstFree; /* Index in MemPage.u.aDisk[] of the first free block */
drh365d68f2001-05-11 11:02:46 +0000170};
drh306dc212001-05-21 13:45:10 +0000171
drh3b7511c2001-05-26 13:15:44 +0000172/*
173** Entries on a page of the database are called "Cells". Each Cell
174** has a header and data. This structure defines the header. The
drhbd03cae2001-06-02 02:40:57 +0000175** key and data (collectively the "payload") follow this header on
176** the database page.
177**
178** A definition of the complete Cell structure is given below. The
drh8c42ca92001-06-22 19:15:00 +0000179** header for the cell must be defined first in order to do some
drhbd03cae2001-06-02 02:40:57 +0000180** of the sizing #defines that follow.
drh3b7511c2001-05-26 13:15:44 +0000181*/
182struct CellHdr {
drh5e2f8b92001-05-28 00:41:15 +0000183 Pgno leftChild; /* Child page that comes before this cell */
drh3b7511c2001-05-26 13:15:44 +0000184 u16 nKey; /* Number of bytes in the key */
drh14acc042001-06-10 19:56:58 +0000185 u16 iNext; /* Index in MemPage.u.aDisk[] of next cell in sorted order */
drh3b7511c2001-05-26 13:15:44 +0000186 u32 nData; /* Number of bytes of data */
drh8c42ca92001-06-22 19:15:00 +0000187};
drh3b7511c2001-05-26 13:15:44 +0000188
189/*
190** The minimum size of a complete Cell. The Cell must contain a header
drhbd03cae2001-06-02 02:40:57 +0000191** and at least 4 bytes of payload.
drh3b7511c2001-05-26 13:15:44 +0000192*/
193#define MIN_CELL_SIZE (sizeof(CellHdr)+4)
194
195/*
196** The maximum number of database entries that can be held in a single
197** page of the database.
198*/
199#define MX_CELL ((SQLITE_PAGE_SIZE-sizeof(PageHdr))/MIN_CELL_SIZE)
200
201/*
drh6019e162001-07-02 17:51:45 +0000202** The amount of usable space on a single page of the BTree. This is the
203** page size minus the overhead of the page header.
204*/
205#define USABLE_SPACE (SQLITE_PAGE_SIZE - sizeof(PageHdr))
206
207/*
drh8c42ca92001-06-22 19:15:00 +0000208** The maximum amount of payload (in bytes) that can be stored locally for
209** a database entry. If the entry contains more data than this, the
drh3b7511c2001-05-26 13:15:44 +0000210** extra goes onto overflow pages.
drhbd03cae2001-06-02 02:40:57 +0000211**
212** This number is chosen so that at least 4 cells will fit on every page.
drh3b7511c2001-05-26 13:15:44 +0000213*/
drh6019e162001-07-02 17:51:45 +0000214#define MX_LOCAL_PAYLOAD ((USABLE_SPACE/4-(sizeof(CellHdr)+sizeof(Pgno)))&~3)
drh3b7511c2001-05-26 13:15:44 +0000215
drh306dc212001-05-21 13:45:10 +0000216/*
217** Data on a database page is stored as a linked list of Cell structures.
drh5e2f8b92001-05-28 00:41:15 +0000218** Both the key and the data are stored in aPayload[]. The key always comes
219** first. The aPayload[] field grows as necessary to hold the key and data,
drh306dc212001-05-21 13:45:10 +0000220** up to a maximum of MX_LOCAL_PAYLOAD bytes. If the size of the key and
drh3b7511c2001-05-26 13:15:44 +0000221** data combined exceeds MX_LOCAL_PAYLOAD bytes, then Cell.ovfl is the
222** page number of the first overflow page.
223**
224** Though this structure is fixed in size, the Cell on the database
drhbd03cae2001-06-02 02:40:57 +0000225** page varies in size. Every cell has a CellHdr and at least 4 bytes
drh3b7511c2001-05-26 13:15:44 +0000226** of payload space. Additional payload bytes (up to the maximum of
227** MX_LOCAL_PAYLOAD) and the Cell.ovfl value are allocated only as
228** needed.
drh306dc212001-05-21 13:45:10 +0000229*/
drh365d68f2001-05-11 11:02:46 +0000230struct Cell {
drh5e2f8b92001-05-28 00:41:15 +0000231 CellHdr h; /* The cell header */
232 char aPayload[MX_LOCAL_PAYLOAD]; /* Key and data */
233 Pgno ovfl; /* The first overflow page */
drh365d68f2001-05-11 11:02:46 +0000234};
drh306dc212001-05-21 13:45:10 +0000235
236/*
237** Free space on a page is remembered using a linked list of the FreeBlk
238** structures. Space on a database page is allocated in increments of
drh72f82862001-05-24 21:06:34 +0000239** at least 4 bytes and is always aligned to a 4-byte boundry. The
drh8b2f49b2001-06-08 00:21:52 +0000240** linked list of FreeBlks is always kept in order by address.
drh306dc212001-05-21 13:45:10 +0000241*/
drh365d68f2001-05-11 11:02:46 +0000242struct FreeBlk {
drh72f82862001-05-24 21:06:34 +0000243 u16 iSize; /* Number of bytes in this block of free space */
drh14acc042001-06-10 19:56:58 +0000244 u16 iNext; /* Index in MemPage.u.aDisk[] of the next free block */
drh365d68f2001-05-11 11:02:46 +0000245};
drh306dc212001-05-21 13:45:10 +0000246
247/*
drh14acc042001-06-10 19:56:58 +0000248** The number of bytes of payload that will fit on a single overflow page.
drh3b7511c2001-05-26 13:15:44 +0000249*/
250#define OVERFLOW_SIZE (SQLITE_PAGE_SIZE-sizeof(Pgno))
251
252/*
drh306dc212001-05-21 13:45:10 +0000253** When the key and data for a single entry in the BTree will not fit in
drh8c42ca92001-06-22 19:15:00 +0000254** the MX_LOCAL_PAYLOAD bytes of space available on the database page,
drh8b2f49b2001-06-08 00:21:52 +0000255** then all extra bytes are written to a linked list of overflow pages.
drh306dc212001-05-21 13:45:10 +0000256** Each overflow page is an instance of the following structure.
257**
258** Unused pages in the database are also represented by instances of
drhbd03cae2001-06-02 02:40:57 +0000259** the OverflowPage structure. The PageOne.freeList field is the
drh306dc212001-05-21 13:45:10 +0000260** page number of the first page in a linked list of unused database
261** pages.
262*/
drh2af926b2001-05-15 00:39:25 +0000263struct OverflowPage {
drh14acc042001-06-10 19:56:58 +0000264 Pgno iNext;
drh5e2f8b92001-05-28 00:41:15 +0000265 char aPayload[OVERFLOW_SIZE];
drh7e3b0a02001-04-28 16:52:40 +0000266};
drh7e3b0a02001-04-28 16:52:40 +0000267
268/*
269** For every page in the database file, an instance of the following structure
drh14acc042001-06-10 19:56:58 +0000270** is stored in memory. The u.aDisk[] array contains the raw bits read from
drhbd03cae2001-06-02 02:40:57 +0000271** the disk. The rest is auxiliary information that held in memory only. The
272** auxiliary info is only valid for regular database pages - it is not
273** used for overflow pages and pages on the freelist.
drh306dc212001-05-21 13:45:10 +0000274**
drhbd03cae2001-06-02 02:40:57 +0000275** Of particular interest in the auxiliary info is the apCell[] entry. Each
drh14acc042001-06-10 19:56:58 +0000276** apCell[] entry is a pointer to a Cell structure in u.aDisk[]. The cells are
drh306dc212001-05-21 13:45:10 +0000277** put in this array so that they can be accessed in constant time, rather
drhbd03cae2001-06-02 02:40:57 +0000278** than in linear time which would be needed if we had to walk the linked
279** list on every access.
drh72f82862001-05-24 21:06:34 +0000280**
drh14acc042001-06-10 19:56:58 +0000281** Note that apCell[] contains enough space to hold up to two more Cells
282** than can possibly fit on one page. In the steady state, every apCell[]
283** points to memory inside u.aDisk[]. But in the middle of an insert
284** operation, some apCell[] entries may temporarily point to data space
285** outside of u.aDisk[]. This is a transient situation that is quickly
286** resolved. But while it is happening, it is possible for a database
287** page to hold as many as two more cells than it might otherwise hold.
288** The extra too entries in apCell[] are an allowance for this situation.
289**
drh72f82862001-05-24 21:06:34 +0000290** The pParent field points back to the parent page. This allows us to
291** walk up the BTree from any leaf to the root. Care must be taken to
292** unref() the parent page pointer when this page is no longer referenced.
drhbd03cae2001-06-02 02:40:57 +0000293** The pageDestructor() routine handles that chore.
drh7e3b0a02001-04-28 16:52:40 +0000294*/
295struct MemPage {
drh14acc042001-06-10 19:56:58 +0000296 union {
297 char aDisk[SQLITE_PAGE_SIZE]; /* Page data stored on disk */
298 PageHdr hdr; /* Overlay page header */
299 } u;
drh5e2f8b92001-05-28 00:41:15 +0000300 int isInit; /* True if auxiliary data is initialized */
drh72f82862001-05-24 21:06:34 +0000301 MemPage *pParent; /* The parent of this page. NULL for root */
drh14acc042001-06-10 19:56:58 +0000302 int nFree; /* Number of free bytes in u.aDisk[] */
drh306dc212001-05-21 13:45:10 +0000303 int nCell; /* Number of entries on this page */
drh14acc042001-06-10 19:56:58 +0000304 int isOverfull; /* Some apCell[] points outside u.aDisk[] */
305 Cell *apCell[MX_CELL+2]; /* All data entires in sorted order */
drh8c42ca92001-06-22 19:15:00 +0000306};
drh7e3b0a02001-04-28 16:52:40 +0000307
308/*
drh3b7511c2001-05-26 13:15:44 +0000309** The in-memory image of a disk page has the auxiliary information appended
310** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
311** that extra information.
312*/
313#define EXTRA_SIZE (sizeof(MemPage)-SQLITE_PAGE_SIZE)
314
315/*
drha059ad02001-04-17 20:09:11 +0000316** Everything we need to know about an open database
317*/
318struct Btree {
319 Pager *pPager; /* The page cache */
drh306dc212001-05-21 13:45:10 +0000320 BtCursor *pCursor; /* A list of all open cursors */
drhbd03cae2001-06-02 02:40:57 +0000321 PageOne *page1; /* First page of the database */
drh306dc212001-05-21 13:45:10 +0000322 int inTrans; /* True if a transaction is in progress */
drha059ad02001-04-17 20:09:11 +0000323};
324typedef Btree Bt;
325
drh365d68f2001-05-11 11:02:46 +0000326/*
327** A cursor is a pointer to a particular entry in the BTree.
328** The entry is identified by its MemPage and the index in
drh5e2f8b92001-05-28 00:41:15 +0000329** MemPage.apCell[] of the entry.
drh365d68f2001-05-11 11:02:46 +0000330*/
drh72f82862001-05-24 21:06:34 +0000331struct BtCursor {
drh5e2f8b92001-05-28 00:41:15 +0000332 Btree *pBt; /* The Btree to which this cursor belongs */
drh14acc042001-06-10 19:56:58 +0000333 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
drh8b2f49b2001-06-08 00:21:52 +0000334 Pgno pgnoRoot; /* The root page of this tree */
drh5e2f8b92001-05-28 00:41:15 +0000335 MemPage *pPage; /* Page that contains the entry */
drh8c42ca92001-06-22 19:15:00 +0000336 int idx; /* Index of the entry in pPage->apCell[] */
drh5e2f8b92001-05-28 00:41:15 +0000337 u8 bSkipNext; /* sqliteBtreeNext() is no-op if true */
338 u8 iMatch; /* compare result from last sqliteBtreeMoveto() */
drh365d68f2001-05-11 11:02:46 +0000339};
drh7e3b0a02001-04-28 16:52:40 +0000340
drha059ad02001-04-17 20:09:11 +0000341/*
drh3b7511c2001-05-26 13:15:44 +0000342** Compute the total number of bytes that a Cell needs on the main
drh5e2f8b92001-05-28 00:41:15 +0000343** database page. The number returned includes the Cell header,
344** local payload storage, and the pointer to overflow pages (if
drh8c42ca92001-06-22 19:15:00 +0000345** applicable). Additional space allocated on overflow pages
drhbd03cae2001-06-02 02:40:57 +0000346** is NOT included in the value returned from this routine.
drh3b7511c2001-05-26 13:15:44 +0000347*/
348static int cellSize(Cell *pCell){
349 int n = pCell->h.nKey + pCell->h.nData;
350 if( n>MX_LOCAL_PAYLOAD ){
351 n = MX_LOCAL_PAYLOAD + sizeof(Pgno);
352 }else{
353 n = ROUNDUP(n);
354 }
355 n += sizeof(CellHdr);
356 return n;
357}
358
359/*
drh72f82862001-05-24 21:06:34 +0000360** Defragment the page given. All Cells are moved to the
361** beginning of the page and all free space is collected
362** into one big FreeBlk at the end of the page.
drh365d68f2001-05-11 11:02:46 +0000363*/
364static void defragmentPage(MemPage *pPage){
drh14acc042001-06-10 19:56:58 +0000365 int pc, i, n;
drh2af926b2001-05-15 00:39:25 +0000366 FreeBlk *pFBlk;
367 char newPage[SQLITE_PAGE_SIZE];
368
drh6019e162001-07-02 17:51:45 +0000369 assert( sqlitepager_iswriteable(pPage) );
drhbd03cae2001-06-02 02:40:57 +0000370 pc = sizeof(PageHdr);
drh14acc042001-06-10 19:56:58 +0000371 pPage->u.hdr.firstCell = pc;
372 memcpy(newPage, pPage->u.aDisk, pc);
drh2af926b2001-05-15 00:39:25 +0000373 for(i=0; i<pPage->nCell; i++){
drh2aa679f2001-06-25 02:11:07 +0000374 Cell *pCell = pPage->apCell[i];
drh8c42ca92001-06-22 19:15:00 +0000375
376 /* This routine should never be called on an overfull page. The
377 ** following asserts verify that constraint. */
drh7c717f72001-06-24 20:39:41 +0000378 assert( Addr(pCell) > Addr(pPage) );
379 assert( Addr(pCell) < Addr(pPage) + SQLITE_PAGE_SIZE );
drh8c42ca92001-06-22 19:15:00 +0000380
drh3b7511c2001-05-26 13:15:44 +0000381 n = cellSize(pCell);
drh2aa679f2001-06-25 02:11:07 +0000382 pCell->h.iNext = pc + n;
drh2af926b2001-05-15 00:39:25 +0000383 memcpy(&newPage[pc], pCell, n);
drh14acc042001-06-10 19:56:58 +0000384 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[pc];
drh2af926b2001-05-15 00:39:25 +0000385 pc += n;
386 }
drh72f82862001-05-24 21:06:34 +0000387 assert( pPage->nFree==SQLITE_PAGE_SIZE-pc );
drh14acc042001-06-10 19:56:58 +0000388 memcpy(pPage->u.aDisk, newPage, pc);
drh2aa679f2001-06-25 02:11:07 +0000389 if( pPage->nCell>0 ){
390 pPage->apCell[pPage->nCell-1]->h.iNext = 0;
391 }
drh8c42ca92001-06-22 19:15:00 +0000392 pFBlk = (FreeBlk*)&pPage->u.aDisk[pc];
drh2af926b2001-05-15 00:39:25 +0000393 pFBlk->iSize = SQLITE_PAGE_SIZE - pc;
394 pFBlk->iNext = 0;
drh14acc042001-06-10 19:56:58 +0000395 pPage->u.hdr.firstFree = pc;
drh2af926b2001-05-15 00:39:25 +0000396 memset(&pFBlk[1], 0, SQLITE_PAGE_SIZE - pc - sizeof(FreeBlk));
drh365d68f2001-05-11 11:02:46 +0000397}
398
drha059ad02001-04-17 20:09:11 +0000399/*
drh8b2f49b2001-06-08 00:21:52 +0000400** Allocate nByte bytes of space on a page. nByte must be a
401** multiple of 4.
drhbd03cae2001-06-02 02:40:57 +0000402**
drh14acc042001-06-10 19:56:58 +0000403** Return the index into pPage->u.aDisk[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000404** the new allocation. Or return 0 if there is not enough free
405** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000406**
drh72f82862001-05-24 21:06:34 +0000407** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000408** nBytes of contiguous free space, then this routine automatically
409** calls defragementPage() to consolidate all free space before
410** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000411*/
drhbd03cae2001-06-02 02:40:57 +0000412static int allocateSpace(MemPage *pPage, int nByte){
drh2af926b2001-05-15 00:39:25 +0000413 FreeBlk *p;
414 u16 *pIdx;
415 int start;
drh8c42ca92001-06-22 19:15:00 +0000416 int cnt = 0;
drh72f82862001-05-24 21:06:34 +0000417
drh6019e162001-07-02 17:51:45 +0000418 assert( sqlitepager_iswriteable(pPage) );
drh5e2f8b92001-05-28 00:41:15 +0000419 assert( nByte==ROUNDUP(nByte) );
drh14acc042001-06-10 19:56:58 +0000420 if( pPage->nFree<nByte || pPage->isOverfull ) return 0;
421 pIdx = &pPage->u.hdr.firstFree;
422 p = (FreeBlk*)&pPage->u.aDisk[*pIdx];
drh2af926b2001-05-15 00:39:25 +0000423 while( p->iSize<nByte ){
drh8c42ca92001-06-22 19:15:00 +0000424 assert( cnt++ < SQLITE_PAGE_SIZE/4 );
drh2af926b2001-05-15 00:39:25 +0000425 if( p->iNext==0 ){
426 defragmentPage(pPage);
drh14acc042001-06-10 19:56:58 +0000427 pIdx = &pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000428 }else{
429 pIdx = &p->iNext;
430 }
drh14acc042001-06-10 19:56:58 +0000431 p = (FreeBlk*)&pPage->u.aDisk[*pIdx];
drh2af926b2001-05-15 00:39:25 +0000432 }
433 if( p->iSize==nByte ){
434 start = *pIdx;
435 *pIdx = p->iNext;
436 }else{
drh8c42ca92001-06-22 19:15:00 +0000437 FreeBlk *pNew;
drh72f82862001-05-24 21:06:34 +0000438 start = *pIdx;
drh8c42ca92001-06-22 19:15:00 +0000439 pNew = (FreeBlk*)&pPage->u.aDisk[start + nByte];
drh72f82862001-05-24 21:06:34 +0000440 pNew->iNext = p->iNext;
441 pNew->iSize = p->iSize - nByte;
442 *pIdx = start + nByte;
drh2af926b2001-05-15 00:39:25 +0000443 }
444 pPage->nFree -= nByte;
445 return start;
drh7e3b0a02001-04-28 16:52:40 +0000446}
447
448/*
drh14acc042001-06-10 19:56:58 +0000449** Return a section of the MemPage.u.aDisk[] to the freelist.
450** The first byte of the new free block is pPage->u.aDisk[start]
451** and the size of the block is "size" bytes. Size must be
452** a multiple of 4.
drh306dc212001-05-21 13:45:10 +0000453**
454** Most of the effort here is involved in coalesing adjacent
455** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000456*/
457static void freeSpace(MemPage *pPage, int start, int size){
drh2af926b2001-05-15 00:39:25 +0000458 int end = start + size;
459 u16 *pIdx, idx;
460 FreeBlk *pFBlk;
461 FreeBlk *pNew;
462 FreeBlk *pNext;
463
drh6019e162001-07-02 17:51:45 +0000464 assert( sqlitepager_iswriteable(pPage) );
drh2af926b2001-05-15 00:39:25 +0000465 assert( size == ROUNDUP(size) );
466 assert( start == ROUNDUP(start) );
drh14acc042001-06-10 19:56:58 +0000467 pIdx = &pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000468 idx = *pIdx;
469 while( idx!=0 && idx<start ){
drh14acc042001-06-10 19:56:58 +0000470 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh2af926b2001-05-15 00:39:25 +0000471 if( idx + pFBlk->iSize == start ){
472 pFBlk->iSize += size;
473 if( idx + pFBlk->iSize == pFBlk->iNext ){
drh8c42ca92001-06-22 19:15:00 +0000474 pNext = (FreeBlk*)&pPage->u.aDisk[pFBlk->iNext];
drh2af926b2001-05-15 00:39:25 +0000475 pFBlk->iSize += pNext->iSize;
476 pFBlk->iNext = pNext->iNext;
477 }
478 pPage->nFree += size;
479 return;
480 }
481 pIdx = &pFBlk->iNext;
482 idx = *pIdx;
483 }
drh14acc042001-06-10 19:56:58 +0000484 pNew = (FreeBlk*)&pPage->u.aDisk[start];
drh2af926b2001-05-15 00:39:25 +0000485 if( idx != end ){
486 pNew->iSize = size;
487 pNew->iNext = idx;
488 }else{
drh14acc042001-06-10 19:56:58 +0000489 pNext = (FreeBlk*)&pPage->u.aDisk[idx];
drh2af926b2001-05-15 00:39:25 +0000490 pNew->iSize = size + pNext->iSize;
491 pNew->iNext = pNext->iNext;
492 }
493 *pIdx = start;
494 pPage->nFree += size;
drh7e3b0a02001-04-28 16:52:40 +0000495}
496
497/*
498** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000499**
drhbd03cae2001-06-02 02:40:57 +0000500** The pParent parameter must be a pointer to the MemPage which
501** is the parent of the page being initialized. The root of the
drh8b2f49b2001-06-08 00:21:52 +0000502** BTree (usually page 2) has no parent and so for that page,
503** pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000504**
drh72f82862001-05-24 21:06:34 +0000505** Return SQLITE_OK on success. If we see that the page does
506** not contained a well-formed database page, then return
507** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
508** guarantee that the page is well-formed. It only shows that
509** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000510*/
drh72f82862001-05-24 21:06:34 +0000511static int initPage(MemPage *pPage, Pgno pgnoThis, MemPage *pParent){
drh14acc042001-06-10 19:56:58 +0000512 int idx; /* An index into pPage->u.aDisk[] */
513 Cell *pCell; /* A pointer to a Cell in pPage->u.aDisk[] */
514 FreeBlk *pFBlk; /* A pointer to a free block in pPage->u.aDisk[] */
drh5e2f8b92001-05-28 00:41:15 +0000515 int sz; /* The size of a Cell in bytes */
516 int freeSpace; /* Amount of free space on the page */
drh2af926b2001-05-15 00:39:25 +0000517
drh5e2f8b92001-05-28 00:41:15 +0000518 if( pPage->pParent ){
519 assert( pPage->pParent==pParent );
520 return SQLITE_OK;
521 }
522 if( pParent ){
523 pPage->pParent = pParent;
524 sqlitepager_ref(pParent);
525 }
526 if( pPage->isInit ) return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +0000527 pPage->isInit = 1;
drh7e3b0a02001-04-28 16:52:40 +0000528 pPage->nCell = 0;
drh6019e162001-07-02 17:51:45 +0000529 freeSpace = USABLE_SPACE;
drh14acc042001-06-10 19:56:58 +0000530 idx = pPage->u.hdr.firstCell;
drh7e3b0a02001-04-28 16:52:40 +0000531 while( idx!=0 ){
drh8c42ca92001-06-22 19:15:00 +0000532 if( idx>SQLITE_PAGE_SIZE-MIN_CELL_SIZE ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000533 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh8c42ca92001-06-22 19:15:00 +0000534 if( idx!=ROUNDUP(idx) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000535 pCell = (Cell*)&pPage->u.aDisk[idx];
drh5e2f8b92001-05-28 00:41:15 +0000536 sz = cellSize(pCell);
537 if( idx+sz > SQLITE_PAGE_SIZE ) goto page_format_error;
538 freeSpace -= sz;
539 pPage->apCell[pPage->nCell++] = pCell;
drh3b7511c2001-05-26 13:15:44 +0000540 idx = pCell->h.iNext;
drh2af926b2001-05-15 00:39:25 +0000541 }
542 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +0000543 idx = pPage->u.hdr.firstFree;
drh2af926b2001-05-15 00:39:25 +0000544 while( idx!=0 ){
545 if( idx>SQLITE_PAGE_SIZE-sizeof(FreeBlk) ) goto page_format_error;
drhbd03cae2001-06-02 02:40:57 +0000546 if( idx<sizeof(PageHdr) ) goto page_format_error;
drh14acc042001-06-10 19:56:58 +0000547 pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
drh2af926b2001-05-15 00:39:25 +0000548 pPage->nFree += pFBlk->iSize;
drh7c717f72001-06-24 20:39:41 +0000549 if( pFBlk->iNext>0 && pFBlk->iNext <= idx ) goto page_format_error;
drh2af926b2001-05-15 00:39:25 +0000550 idx = pFBlk->iNext;
drh7e3b0a02001-04-28 16:52:40 +0000551 }
drh8b2f49b2001-06-08 00:21:52 +0000552 if( pPage->nCell==0 && pPage->nFree==0 ){
553 /* As a special case, an uninitialized root page appears to be
554 ** an empty database */
555 return SQLITE_OK;
556 }
drh5e2f8b92001-05-28 00:41:15 +0000557 if( pPage->nFree!=freeSpace ) goto page_format_error;
drh7e3b0a02001-04-28 16:52:40 +0000558 return SQLITE_OK;
drh2af926b2001-05-15 00:39:25 +0000559
560page_format_error:
561 return SQLITE_CORRUPT;
drh7e3b0a02001-04-28 16:52:40 +0000562}
563
564/*
drh8b2f49b2001-06-08 00:21:52 +0000565** Set up a raw page so that it looks like a database page holding
566** no entries.
drhbd03cae2001-06-02 02:40:57 +0000567*/
568static void zeroPage(MemPage *pPage){
569 PageHdr *pHdr;
570 FreeBlk *pFBlk;
drh6019e162001-07-02 17:51:45 +0000571 assert( sqlitepager_iswriteable(pPage) );
drhbd03cae2001-06-02 02:40:57 +0000572 memset(pPage, 0, SQLITE_PAGE_SIZE);
drh14acc042001-06-10 19:56:58 +0000573 pHdr = &pPage->u.hdr;
drhbd03cae2001-06-02 02:40:57 +0000574 pHdr->firstCell = 0;
575 pHdr->firstFree = sizeof(*pHdr);
576 pFBlk = (FreeBlk*)&pHdr[1];
577 pFBlk->iNext = 0;
578 pFBlk->iSize = SQLITE_PAGE_SIZE - sizeof(*pHdr);
drh8c42ca92001-06-22 19:15:00 +0000579 pPage->nFree = pFBlk->iSize;
580 pPage->nCell = 0;
581 pPage->isOverfull = 0;
drhbd03cae2001-06-02 02:40:57 +0000582}
583
584/*
drh72f82862001-05-24 21:06:34 +0000585** This routine is called when the reference count for a page
586** reaches zero. We need to unref the pParent pointer when that
587** happens.
588*/
589static void pageDestructor(void *pData){
590 MemPage *pPage = (MemPage*)pData;
591 if( pPage->pParent ){
592 MemPage *pParent = pPage->pParent;
593 pPage->pParent = 0;
594 sqlitepager_unref(pParent);
595 }
596}
597
598/*
drh306dc212001-05-21 13:45:10 +0000599** Open a new database.
600**
601** Actually, this routine just sets up the internal data structures
drh72f82862001-05-24 21:06:34 +0000602** for accessing the database. We do not open the database file
603** until the first page is loaded.
drha059ad02001-04-17 20:09:11 +0000604*/
drh6019e162001-07-02 17:51:45 +0000605int sqliteBtreeOpen(
606 const char *zFilename, /* Name of the file containing the BTree database */
607 int mode, /* Not currently used */
608 int nCache, /* How many pages in the page cache */
609 Btree **ppBtree /* Pointer to new Btree object written here */
610){
drha059ad02001-04-17 20:09:11 +0000611 Btree *pBt;
drh8c42ca92001-06-22 19:15:00 +0000612 int rc;
drha059ad02001-04-17 20:09:11 +0000613
614 pBt = sqliteMalloc( sizeof(*pBt) );
615 if( pBt==0 ){
drh8c42ca92001-06-22 19:15:00 +0000616 *ppBtree = 0;
drha059ad02001-04-17 20:09:11 +0000617 return SQLITE_NOMEM;
618 }
drh6019e162001-07-02 17:51:45 +0000619 if( nCache<10 ) nCache = 10;
620 rc = sqlitepager_open(&pBt->pPager, zFilename, nCache, EXTRA_SIZE);
drha059ad02001-04-17 20:09:11 +0000621 if( rc!=SQLITE_OK ){
622 if( pBt->pPager ) sqlitepager_close(pBt->pPager);
623 sqliteFree(pBt);
624 *ppBtree = 0;
625 return rc;
626 }
drh72f82862001-05-24 21:06:34 +0000627 sqlitepager_set_destructor(pBt->pPager, pageDestructor);
drha059ad02001-04-17 20:09:11 +0000628 pBt->pCursor = 0;
629 pBt->page1 = 0;
630 *ppBtree = pBt;
631 return SQLITE_OK;
632}
633
634/*
635** Close an open database and invalidate all cursors.
636*/
637int sqliteBtreeClose(Btree *pBt){
638 while( pBt->pCursor ){
639 sqliteBtreeCloseCursor(pBt->pCursor);
640 }
641 sqlitepager_close(pBt->pPager);
642 sqliteFree(pBt);
643 return SQLITE_OK;
644}
645
646/*
drh306dc212001-05-21 13:45:10 +0000647** Get a reference to page1 of the database file. This will
648** also acquire a readlock on that file.
649**
650** SQLITE_OK is returned on success. If the file is not a
651** well-formed database file, then SQLITE_CORRUPT is returned.
652** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
653** is returned if we run out of memory. SQLITE_PROTOCOL is returned
654** if there is a locking protocol violation.
655*/
656static int lockBtree(Btree *pBt){
657 int rc;
658 if( pBt->page1 ) return SQLITE_OK;
drh8c42ca92001-06-22 19:15:00 +0000659 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pBt->page1);
drh306dc212001-05-21 13:45:10 +0000660 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +0000661
662 /* Do some checking to help insure the file we opened really is
663 ** a valid database file.
664 */
665 if( sqlitepager_pagecount(pBt->pPager)>0 ){
drhbd03cae2001-06-02 02:40:57 +0000666 PageOne *pP1 = pBt->page1;
drh8c42ca92001-06-22 19:15:00 +0000667 if( strcmp(pP1->zMagic,zMagicHeader)!=0 || pP1->iMagic!=MAGIC ){
drh306dc212001-05-21 13:45:10 +0000668 rc = SQLITE_CORRUPT;
drh72f82862001-05-24 21:06:34 +0000669 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +0000670 }
671 }
672 return rc;
673
drh72f82862001-05-24 21:06:34 +0000674page1_init_failed:
drh306dc212001-05-21 13:45:10 +0000675 sqlitepager_unref(pBt->page1);
676 pBt->page1 = 0;
drh72f82862001-05-24 21:06:34 +0000677 return rc;
drh306dc212001-05-21 13:45:10 +0000678}
679
680/*
drh8c42ca92001-06-22 19:15:00 +0000681** Create a new database by initializing the first two pages of the
682** file.
drh8b2f49b2001-06-08 00:21:52 +0000683*/
684static int newDatabase(Btree *pBt){
685 MemPage *pRoot;
686 PageOne *pP1;
drh8c42ca92001-06-22 19:15:00 +0000687 int rc;
drh7c717f72001-06-24 20:39:41 +0000688 if( sqlitepager_pagecount(pBt->pPager)>1 ) return SQLITE_OK;
drh8b2f49b2001-06-08 00:21:52 +0000689 pP1 = pBt->page1;
690 rc = sqlitepager_write(pBt->page1);
691 if( rc ) return rc;
drh8c42ca92001-06-22 19:15:00 +0000692 rc = sqlitepager_get(pBt->pPager, 2, (void**)&pRoot);
drh8b2f49b2001-06-08 00:21:52 +0000693 if( rc ) return rc;
694 rc = sqlitepager_write(pRoot);
695 if( rc ){
696 sqlitepager_unref(pRoot);
697 return rc;
698 }
699 strcpy(pP1->zMagic, zMagicHeader);
drh8c42ca92001-06-22 19:15:00 +0000700 pP1->iMagic = MAGIC;
drh8b2f49b2001-06-08 00:21:52 +0000701 zeroPage(pRoot);
702 sqlitepager_unref(pRoot);
703 return SQLITE_OK;
704}
705
706/*
drh72f82862001-05-24 21:06:34 +0000707** Attempt to start a new transaction.
drh8b2f49b2001-06-08 00:21:52 +0000708**
709** A transaction must be started before attempting any changes
710** to the database. None of the following routines will work
711** unless a transaction is started first:
712**
713** sqliteBtreeCreateTable()
714** sqliteBtreeClearTable()
715** sqliteBtreeDropTable()
716** sqliteBtreeInsert()
717** sqliteBtreeDelete()
718** sqliteBtreeUpdateMeta()
drha059ad02001-04-17 20:09:11 +0000719*/
720int sqliteBtreeBeginTrans(Btree *pBt){
721 int rc;
722 if( pBt->inTrans ) return SQLITE_ERROR;
723 if( pBt->page1==0 ){
drh7e3b0a02001-04-28 16:52:40 +0000724 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +0000725 if( rc!=SQLITE_OK ){
726 return rc;
727 }
drha059ad02001-04-17 20:09:11 +0000728 }
drhbe0072d2001-09-13 14:46:09 +0000729 if( !sqlitepager_isreadonly(pBt->pPager) ){
drh5e00f6c2001-09-13 13:46:56 +0000730 rc = sqlitepager_write(pBt->page1);
731 if( rc!=SQLITE_OK ){
732 return rc;
733 }
734 rc = newDatabase(pBt);
drha059ad02001-04-17 20:09:11 +0000735 }
drh8c42ca92001-06-22 19:15:00 +0000736 pBt->inTrans = 1;
drh8c42ca92001-06-22 19:15:00 +0000737 return rc;
drha059ad02001-04-17 20:09:11 +0000738}
739
740/*
drh5e00f6c2001-09-13 13:46:56 +0000741** If there are no outstanding cursors and we are not in the middle
742** of a transaction but there is a read lock on the database, then
743** this routine unrefs the first page of the database file which
744** has the effect of releasing the read lock.
745**
746** If there are any outstanding cursors, this routine is a no-op.
747**
748** If there is a transaction in progress, this routine is a no-op.
drha059ad02001-04-17 20:09:11 +0000749*/
drh5e00f6c2001-09-13 13:46:56 +0000750static void unlockBtreeIfUnused(Btree *pBt){
drh7c717f72001-06-24 20:39:41 +0000751 if( pBt->inTrans==0 && pBt->pCursor==0 && pBt->page1!=0 ){
drha059ad02001-04-17 20:09:11 +0000752 sqlitepager_unref(pBt->page1);
753 pBt->page1 = 0;
754 pBt->inTrans = 0;
755 }
756}
757
758/*
drh2aa679f2001-06-25 02:11:07 +0000759** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +0000760**
761** This will release the write lock on the database file. If there
762** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000763*/
764int sqliteBtreeCommit(Btree *pBt){
765 int rc;
drh2aa679f2001-06-25 02:11:07 +0000766 if( pBt->inTrans==0 ) return SQLITE_ERROR;
drha059ad02001-04-17 20:09:11 +0000767 rc = sqlitepager_commit(pBt->pPager);
drh7c717f72001-06-24 20:39:41 +0000768 pBt->inTrans = 0;
drh5e00f6c2001-09-13 13:46:56 +0000769 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000770 return rc;
771}
772
773/*
774** Rollback the transaction in progress. All cursors must be
775** closed before this routine is called.
drh5e00f6c2001-09-13 13:46:56 +0000776**
777** This will release the write lock on the database file. If there
778** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +0000779*/
780int sqliteBtreeRollback(Btree *pBt){
781 int rc;
drh72f82862001-05-24 21:06:34 +0000782 if( pBt->pCursor!=0 ) return SQLITE_ERROR;
drh7c717f72001-06-24 20:39:41 +0000783 if( pBt->inTrans==0 ) return SQLITE_OK;
784 pBt->inTrans = 0;
drha059ad02001-04-17 20:09:11 +0000785 rc = sqlitepager_rollback(pBt->pPager);
drh5e00f6c2001-09-13 13:46:56 +0000786 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000787 return rc;
788}
789
790/*
drh8b2f49b2001-06-08 00:21:52 +0000791** Create a new cursor for the BTree whose root is on the page
792** iTable. The act of acquiring a cursor gets a read lock on
793** the database file.
drha059ad02001-04-17 20:09:11 +0000794*/
drh8b2f49b2001-06-08 00:21:52 +0000795int sqliteBtreeCursor(Btree *pBt, int iTable, BtCursor **ppCur){
drha059ad02001-04-17 20:09:11 +0000796 int rc;
797 BtCursor *pCur;
798 if( pBt->page1==0 ){
799 rc = lockBtree(pBt);
800 if( rc!=SQLITE_OK ){
801 *ppCur = 0;
802 return rc;
803 }
804 }
805 pCur = sqliteMalloc( sizeof(*pCur) );
806 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +0000807 rc = SQLITE_NOMEM;
808 goto create_cursor_exception;
809 }
drh8b2f49b2001-06-08 00:21:52 +0000810 pCur->pgnoRoot = (Pgno)iTable;
drh8c42ca92001-06-22 19:15:00 +0000811 rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +0000812 if( rc!=SQLITE_OK ){
813 goto create_cursor_exception;
814 }
drh8b2f49b2001-06-08 00:21:52 +0000815 rc = initPage(pCur->pPage, pCur->pgnoRoot, 0);
drhbd03cae2001-06-02 02:40:57 +0000816 if( rc!=SQLITE_OK ){
817 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +0000818 }
drh14acc042001-06-10 19:56:58 +0000819 pCur->pBt = pBt;
820 pCur->idx = 0;
drha059ad02001-04-17 20:09:11 +0000821 pCur->pNext = pBt->pCursor;
822 if( pCur->pNext ){
823 pCur->pNext->pPrev = pCur;
824 }
drh14acc042001-06-10 19:56:58 +0000825 pCur->pPrev = 0;
drha059ad02001-04-17 20:09:11 +0000826 pBt->pCursor = pCur;
drh2af926b2001-05-15 00:39:25 +0000827 *ppCur = pCur;
828 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +0000829
830create_cursor_exception:
831 *ppCur = 0;
832 if( pCur ){
833 if( pCur->pPage ) sqlitepager_unref(pCur->pPage);
834 sqliteFree(pCur);
835 }
drh5e00f6c2001-09-13 13:46:56 +0000836 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +0000837 return rc;
drha059ad02001-04-17 20:09:11 +0000838}
839
840/*
drh5e00f6c2001-09-13 13:46:56 +0000841** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +0000842** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +0000843*/
844int sqliteBtreeCloseCursor(BtCursor *pCur){
845 Btree *pBt = pCur->pBt;
drha059ad02001-04-17 20:09:11 +0000846 if( pCur->pPrev ){
847 pCur->pPrev->pNext = pCur->pNext;
848 }else{
849 pBt->pCursor = pCur->pNext;
850 }
851 if( pCur->pNext ){
852 pCur->pNext->pPrev = pCur->pPrev;
853 }
drh2af926b2001-05-15 00:39:25 +0000854 sqlitepager_unref(pCur->pPage);
drh5e00f6c2001-09-13 13:46:56 +0000855 unlockBtreeIfUnused(pBt);
drha059ad02001-04-17 20:09:11 +0000856 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +0000857 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +0000858}
859
drh7e3b0a02001-04-28 16:52:40 +0000860/*
drh5e2f8b92001-05-28 00:41:15 +0000861** Make a temporary cursor by filling in the fields of pTempCur.
862** The temporary cursor is not on the cursor list for the Btree.
863*/
drh14acc042001-06-10 19:56:58 +0000864static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +0000865 memcpy(pTempCur, pCur, sizeof(*pCur));
866 pTempCur->pNext = 0;
867 pTempCur->pPrev = 0;
868 sqlitepager_ref(pTempCur->pPage);
869}
870
871/*
drhbd03cae2001-06-02 02:40:57 +0000872** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +0000873** function above.
874*/
drh14acc042001-06-10 19:56:58 +0000875static void releaseTempCursor(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +0000876 sqlitepager_unref(pCur->pPage);
877}
878
879/*
drhbd03cae2001-06-02 02:40:57 +0000880** Set *pSize to the number of bytes of key in the entry the
881** cursor currently points to. Always return SQLITE_OK.
882** Failure is not possible. If the cursor is not currently
883** pointing to an entry (which can happen, for example, if
884** the database is empty) then *pSize is set to 0.
drh7e3b0a02001-04-28 16:52:40 +0000885*/
drh72f82862001-05-24 21:06:34 +0000886int sqliteBtreeKeySize(BtCursor *pCur, int *pSize){
drh2af926b2001-05-15 00:39:25 +0000887 Cell *pCell;
888 MemPage *pPage;
889
890 pPage = pCur->pPage;
drh72f82862001-05-24 21:06:34 +0000891 assert( pPage!=0 );
892 if( pCur->idx >= pPage->nCell ){
893 *pSize = 0;
894 }else{
drh5e2f8b92001-05-28 00:41:15 +0000895 pCell = pPage->apCell[pCur->idx];
drh8c42ca92001-06-22 19:15:00 +0000896 *pSize = pCell->h.nKey;
drh72f82862001-05-24 21:06:34 +0000897 }
898 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +0000899}
drh2af926b2001-05-15 00:39:25 +0000900
drh72f82862001-05-24 21:06:34 +0000901/*
902** Read payload information from the entry that the pCur cursor is
903** pointing to. Begin reading the payload at "offset" and read
904** a total of "amt" bytes. Put the result in zBuf.
905**
906** This routine does not make a distinction between key and data.
907** It just reads bytes from the payload area.
908*/
drh2af926b2001-05-15 00:39:25 +0000909static int getPayload(BtCursor *pCur, int offset, int amt, char *zBuf){
drh5e2f8b92001-05-28 00:41:15 +0000910 char *aPayload;
drh2af926b2001-05-15 00:39:25 +0000911 Pgno nextPage;
drh8c42ca92001-06-22 19:15:00 +0000912 int rc;
drh72f82862001-05-24 21:06:34 +0000913 assert( pCur!=0 && pCur->pPage!=0 );
drh8c42ca92001-06-22 19:15:00 +0000914 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
915 aPayload = pCur->pPage->apCell[pCur->idx]->aPayload;
drh2af926b2001-05-15 00:39:25 +0000916 if( offset<MX_LOCAL_PAYLOAD ){
917 int a = amt;
918 if( a+offset>MX_LOCAL_PAYLOAD ){
919 a = MX_LOCAL_PAYLOAD - offset;
920 }
drh5e2f8b92001-05-28 00:41:15 +0000921 memcpy(zBuf, &aPayload[offset], a);
drh2af926b2001-05-15 00:39:25 +0000922 if( a==amt ){
923 return SQLITE_OK;
924 }
drh2aa679f2001-06-25 02:11:07 +0000925 offset = 0;
drh2af926b2001-05-15 00:39:25 +0000926 zBuf += a;
927 amt -= a;
drhdd793422001-06-28 01:54:48 +0000928 }else{
929 offset -= MX_LOCAL_PAYLOAD;
drhbd03cae2001-06-02 02:40:57 +0000930 }
931 if( amt>0 ){
drh8c42ca92001-06-22 19:15:00 +0000932 nextPage = pCur->pPage->apCell[pCur->idx]->ovfl;
drh2af926b2001-05-15 00:39:25 +0000933 }
934 while( amt>0 && nextPage ){
935 OverflowPage *pOvfl;
drh8c42ca92001-06-22 19:15:00 +0000936 rc = sqlitepager_get(pCur->pBt->pPager, nextPage, (void**)&pOvfl);
drh2af926b2001-05-15 00:39:25 +0000937 if( rc!=0 ){
938 return rc;
939 }
drh14acc042001-06-10 19:56:58 +0000940 nextPage = pOvfl->iNext;
drh2af926b2001-05-15 00:39:25 +0000941 if( offset<OVERFLOW_SIZE ){
942 int a = amt;
943 if( a + offset > OVERFLOW_SIZE ){
944 a = OVERFLOW_SIZE - offset;
945 }
drh5e2f8b92001-05-28 00:41:15 +0000946 memcpy(zBuf, &pOvfl->aPayload[offset], a);
drh2aa679f2001-06-25 02:11:07 +0000947 offset = 0;
drh2af926b2001-05-15 00:39:25 +0000948 amt -= a;
949 zBuf += a;
drh2aa679f2001-06-25 02:11:07 +0000950 }else{
951 offset -= OVERFLOW_SIZE;
drh2af926b2001-05-15 00:39:25 +0000952 }
953 sqlitepager_unref(pOvfl);
954 }
955 return amt==0 ? SQLITE_OK : SQLITE_CORRUPT;
956}
957
drh72f82862001-05-24 21:06:34 +0000958/*
drh5e00f6c2001-09-13 13:46:56 +0000959** Read part of the key associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +0000960** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +0000961** begins at "offset". The number of bytes actually read is
962** returned. The amount returned will be smaller than the
963** amount requested if there are not enough bytes in the key
964** to satisfy the request.
drh72f82862001-05-24 21:06:34 +0000965*/
966int sqliteBtreeKey(BtCursor *pCur, int offset, int amt, char *zBuf){
967 Cell *pCell;
968 MemPage *pPage;
drha059ad02001-04-17 20:09:11 +0000969
drh5e00f6c2001-09-13 13:46:56 +0000970 if( amt<0 ) return 0;
971 if( offset<0 ) return 0;
972 if( amt==0 ) return 0;
drh72f82862001-05-24 21:06:34 +0000973 pPage = pCur->pPage;
974 assert( pPage!=0 );
975 if( pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +0000976 return 0;
drh72f82862001-05-24 21:06:34 +0000977 }
drh5e2f8b92001-05-28 00:41:15 +0000978 pCell = pPage->apCell[pCur->idx];
drh3b7511c2001-05-26 13:15:44 +0000979 if( amt+offset > pCell->h.nKey ){
drh5e00f6c2001-09-13 13:46:56 +0000980 amt = pCell->h.nKey - offset;
981 if( amt<=0 ){
982 return 0;
983 }
drhbd03cae2001-06-02 02:40:57 +0000984 }
drh5e00f6c2001-09-13 13:46:56 +0000985 getPayload(pCur, offset, amt, zBuf);
986 return amt;
drh72f82862001-05-24 21:06:34 +0000987}
988
989/*
drhbd03cae2001-06-02 02:40:57 +0000990** Set *pSize to the number of bytes of data in the entry the
991** cursor currently points to. Always return SQLITE_OK.
992** Failure is not possible. If the cursor is not currently
993** pointing to an entry (which can happen, for example, if
994** the database is empty) then *pSize is set to 0.
drh72f82862001-05-24 21:06:34 +0000995*/
996int sqliteBtreeDataSize(BtCursor *pCur, int *pSize){
997 Cell *pCell;
998 MemPage *pPage;
999
1000 pPage = pCur->pPage;
1001 assert( pPage!=0 );
1002 if( pCur->idx >= pPage->nCell ){
1003 *pSize = 0;
1004 }else{
drh5e2f8b92001-05-28 00:41:15 +00001005 pCell = pPage->apCell[pCur->idx];
drh3b7511c2001-05-26 13:15:44 +00001006 *pSize = pCell->h.nData;
drh72f82862001-05-24 21:06:34 +00001007 }
1008 return SQLITE_OK;
1009}
1010
1011/*
drh5e00f6c2001-09-13 13:46:56 +00001012** Read part of the data associated with cursor pCur. A maximum
drh72f82862001-05-24 21:06:34 +00001013** of "amt" bytes will be transfered into zBuf[]. The transfer
drh5e00f6c2001-09-13 13:46:56 +00001014** begins at "offset". The number of bytes actually read is
1015** returned. The amount returned will be smaller than the
1016** amount requested if there are not enough bytes in the data
1017** to satisfy the request.
drh72f82862001-05-24 21:06:34 +00001018*/
1019int sqliteBtreeData(BtCursor *pCur, int offset, int amt, char *zBuf){
1020 Cell *pCell;
1021 MemPage *pPage;
1022
drh5e00f6c2001-09-13 13:46:56 +00001023 if( amt<0 ) return 0;
1024 if( offset<0 ) return 0;
1025 if( amt==0 ) return 0;
drh72f82862001-05-24 21:06:34 +00001026 pPage = pCur->pPage;
1027 assert( pPage!=0 );
1028 if( pCur->idx >= pPage->nCell ){
drh5e00f6c2001-09-13 13:46:56 +00001029 return 0;
drh72f82862001-05-24 21:06:34 +00001030 }
drh5e2f8b92001-05-28 00:41:15 +00001031 pCell = pPage->apCell[pCur->idx];
drhbd03cae2001-06-02 02:40:57 +00001032 if( amt+offset > pCell->h.nData ){
drh5e00f6c2001-09-13 13:46:56 +00001033 amt = pCell->h.nData - offset;
1034 if( amt<=0 ){
1035 return 0;
1036 }
drhbd03cae2001-06-02 02:40:57 +00001037 }
drh5e00f6c2001-09-13 13:46:56 +00001038 getPayload(pCur, offset + pCell->h.nKey, amt, zBuf);
1039 return amt;
drh72f82862001-05-24 21:06:34 +00001040}
drha059ad02001-04-17 20:09:11 +00001041
drh2af926b2001-05-15 00:39:25 +00001042/*
1043** Compare the key for the entry that pCur points to against the
1044** given key (pKey,nKeyOrig). Put the comparison result in *pResult.
1045** The result is negative if pCur<pKey, zero if they are equal and
1046** positive if pCur>pKey.
1047**
1048** SQLITE_OK is returned on success. If part of the cursor key
1049** is on overflow pages and we are unable to access those overflow
1050** pages, then some other value might be returned to indicate the
1051** reason for the error.
1052*/
drh5c4d9702001-08-20 00:33:58 +00001053static int compareKey(
1054 BtCursor *pCur, /* Points to the entry against which we are comparing */
1055 const char *pKey, /* The comparison key */
1056 int nKeyOrig, /* Number of bytes in the comparison key */
1057 int *pResult /* Write the comparison results here */
1058){
drh2af926b2001-05-15 00:39:25 +00001059 Pgno nextPage;
1060 int nKey = nKeyOrig;
drh8c42ca92001-06-22 19:15:00 +00001061 int n, c, rc;
drh2af926b2001-05-15 00:39:25 +00001062 Cell *pCell;
1063
1064 assert( pCur->pPage );
1065 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drhbd03cae2001-06-02 02:40:57 +00001066 pCell = pCur->pPage->apCell[pCur->idx];
drh3b7511c2001-05-26 13:15:44 +00001067 if( nKey > pCell->h.nKey ){
1068 nKey = pCell->h.nKey;
drh2af926b2001-05-15 00:39:25 +00001069 }
1070 n = nKey;
1071 if( n>MX_LOCAL_PAYLOAD ){
1072 n = MX_LOCAL_PAYLOAD;
1073 }
drh5e2f8b92001-05-28 00:41:15 +00001074 c = memcmp(pCell->aPayload, pKey, n);
drh2af926b2001-05-15 00:39:25 +00001075 if( c!=0 ){
1076 *pResult = c;
1077 return SQLITE_OK;
1078 }
1079 pKey += n;
1080 nKey -= n;
drh3b7511c2001-05-26 13:15:44 +00001081 nextPage = pCell->ovfl;
drh2af926b2001-05-15 00:39:25 +00001082 while( nKey>0 ){
1083 OverflowPage *pOvfl;
1084 if( nextPage==0 ){
1085 return SQLITE_CORRUPT;
1086 }
drh8c42ca92001-06-22 19:15:00 +00001087 rc = sqlitepager_get(pCur->pBt->pPager, nextPage, (void**)&pOvfl);
drh72f82862001-05-24 21:06:34 +00001088 if( rc ){
drh2af926b2001-05-15 00:39:25 +00001089 return rc;
1090 }
drh14acc042001-06-10 19:56:58 +00001091 nextPage = pOvfl->iNext;
drh2af926b2001-05-15 00:39:25 +00001092 n = nKey;
1093 if( n>OVERFLOW_SIZE ){
1094 n = OVERFLOW_SIZE;
1095 }
drh5e2f8b92001-05-28 00:41:15 +00001096 c = memcmp(pOvfl->aPayload, pKey, n);
drh2af926b2001-05-15 00:39:25 +00001097 sqlitepager_unref(pOvfl);
1098 if( c!=0 ){
1099 *pResult = c;
1100 return SQLITE_OK;
1101 }
1102 nKey -= n;
1103 pKey += n;
1104 }
drh3b7511c2001-05-26 13:15:44 +00001105 c = pCell->h.nKey - nKeyOrig;
drh2af926b2001-05-15 00:39:25 +00001106 *pResult = c;
1107 return SQLITE_OK;
1108}
1109
drh72f82862001-05-24 21:06:34 +00001110/*
1111** Move the cursor down to a new child page.
1112*/
drh5e2f8b92001-05-28 00:41:15 +00001113static int moveToChild(BtCursor *pCur, int newPgno){
drh72f82862001-05-24 21:06:34 +00001114 int rc;
1115 MemPage *pNewPage;
1116
drh8c42ca92001-06-22 19:15:00 +00001117 rc = sqlitepager_get(pCur->pBt->pPager, newPgno, (void**)&pNewPage);
drh6019e162001-07-02 17:51:45 +00001118 if( rc ) return rc;
1119 rc = initPage(pNewPage, newPgno, pCur->pPage);
1120 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001121 sqlitepager_unref(pCur->pPage);
1122 pCur->pPage = pNewPage;
1123 pCur->idx = 0;
1124 return SQLITE_OK;
1125}
1126
1127/*
drh5e2f8b92001-05-28 00:41:15 +00001128** Move the cursor up to the parent page.
1129**
1130** pCur->idx is set to the cell index that contains the pointer
1131** to the page we are coming from. If we are coming from the
1132** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00001133** the largest cell index.
drh72f82862001-05-24 21:06:34 +00001134*/
drh5e2f8b92001-05-28 00:41:15 +00001135static int moveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001136 Pgno oldPgno;
1137 MemPage *pParent;
drh8c42ca92001-06-22 19:15:00 +00001138 int i;
drh72f82862001-05-24 21:06:34 +00001139 pParent = pCur->pPage->pParent;
drhbd03cae2001-06-02 02:40:57 +00001140 if( pParent==0 ) return SQLITE_INTERNAL;
drh72f82862001-05-24 21:06:34 +00001141 oldPgno = sqlitepager_pagenumber(pCur->pPage);
drh72f82862001-05-24 21:06:34 +00001142 sqlitepager_ref(pParent);
1143 sqlitepager_unref(pCur->pPage);
1144 pCur->pPage = pParent;
drh8c42ca92001-06-22 19:15:00 +00001145 pCur->idx = pParent->nCell;
1146 for(i=0; i<pParent->nCell; i++){
1147 if( pParent->apCell[i]->h.leftChild==oldPgno ){
drh72f82862001-05-24 21:06:34 +00001148 pCur->idx = i;
1149 break;
1150 }
1151 }
drh5e2f8b92001-05-28 00:41:15 +00001152 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00001153}
1154
1155/*
1156** Move the cursor to the root page
1157*/
drh5e2f8b92001-05-28 00:41:15 +00001158static int moveToRoot(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00001159 MemPage *pNew;
drhbd03cae2001-06-02 02:40:57 +00001160 int rc;
1161
drh8c42ca92001-06-22 19:15:00 +00001162 rc = sqlitepager_get(pCur->pBt->pPager, pCur->pgnoRoot, (void**)&pNew);
drhbd03cae2001-06-02 02:40:57 +00001163 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00001164 rc = initPage(pNew, pCur->pgnoRoot, 0);
1165 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001166 sqlitepager_unref(pCur->pPage);
1167 pCur->pPage = pNew;
1168 pCur->idx = 0;
1169 return SQLITE_OK;
1170}
drh2af926b2001-05-15 00:39:25 +00001171
drh5e2f8b92001-05-28 00:41:15 +00001172/*
1173** Move the cursor down to the left-most leaf entry beneath the
1174** entry to which it is currently pointing.
1175*/
1176static int moveToLeftmost(BtCursor *pCur){
1177 Pgno pgno;
1178 int rc;
1179
1180 while( (pgno = pCur->pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
1181 rc = moveToChild(pCur, pgno);
1182 if( rc ) return rc;
1183 }
1184 return SQLITE_OK;
1185}
1186
drh5e00f6c2001-09-13 13:46:56 +00001187/* Move the cursor to the first entry in the table. Return SQLITE_OK
1188** on success. Set *pRes to 0 if the cursor actually points to something
1189** or set *pRes to 1 if the table is empty and there is no first element.
1190*/
1191int sqliteBtreeFirst(BtCursor *pCur, int *pRes){
1192 int rc;
1193 rc = moveToRoot(pCur);
1194 if( rc ) return rc;
1195 if( pCur->pPage->nCell==0 ){
1196 *pRes = 1;
1197 return SQLITE_OK;
1198 }
1199 *pRes = 0;
1200 rc = moveToLeftmost(pCur);
1201 return rc;
1202}
drh5e2f8b92001-05-28 00:41:15 +00001203
drha059ad02001-04-17 20:09:11 +00001204/* Move the cursor so that it points to an entry near pKey.
drh72f82862001-05-24 21:06:34 +00001205** Return a success code.
1206**
drh5e2f8b92001-05-28 00:41:15 +00001207** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00001208** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00001209** were present. The cursor might point to an entry that comes
1210** before or after the key.
1211**
drhbd03cae2001-06-02 02:40:57 +00001212** The result of comparing the key with the entry to which the
1213** cursor is left pointing is stored in pCur->iMatch. The same
1214** value is also written to *pRes if pRes!=NULL. The meaning of
1215** this value is as follows:
1216**
1217** *pRes<0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001218** is smaller than pKey.
drhbd03cae2001-06-02 02:40:57 +00001219**
1220** *pRes==0 The cursor is left pointing at an entry that
1221** exactly matches pKey.
1222**
1223** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00001224** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00001225*/
drh5c4d9702001-08-20 00:33:58 +00001226int sqliteBtreeMoveto(BtCursor *pCur, const void *pKey, int nKey, int *pRes){
drh72f82862001-05-24 21:06:34 +00001227 int rc;
drh7c717f72001-06-24 20:39:41 +00001228 pCur->bSkipNext = 0;
drh5e2f8b92001-05-28 00:41:15 +00001229 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00001230 if( rc ) return rc;
1231 for(;;){
1232 int lwr, upr;
1233 Pgno chldPg;
1234 MemPage *pPage = pCur->pPage;
drh8b2f49b2001-06-08 00:21:52 +00001235 int c = -1;
drh72f82862001-05-24 21:06:34 +00001236 lwr = 0;
1237 upr = pPage->nCell-1;
1238 while( lwr<=upr ){
drh72f82862001-05-24 21:06:34 +00001239 pCur->idx = (lwr+upr)/2;
1240 rc = compareKey(pCur, pKey, nKey, &c);
1241 if( rc ) return rc;
1242 if( c==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001243 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001244 if( pRes ) *pRes = 0;
1245 return SQLITE_OK;
1246 }
1247 if( c<0 ){
1248 lwr = pCur->idx+1;
1249 }else{
1250 upr = pCur->idx-1;
1251 }
1252 }
1253 assert( lwr==upr+1 );
1254 if( lwr>=pPage->nCell ){
drh14acc042001-06-10 19:56:58 +00001255 chldPg = pPage->u.hdr.rightChild;
drh72f82862001-05-24 21:06:34 +00001256 }else{
drh5e2f8b92001-05-28 00:41:15 +00001257 chldPg = pPage->apCell[lwr]->h.leftChild;
drh72f82862001-05-24 21:06:34 +00001258 }
1259 if( chldPg==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001260 pCur->iMatch = c;
drh72f82862001-05-24 21:06:34 +00001261 if( pRes ) *pRes = c;
1262 return SQLITE_OK;
1263 }
drh5e2f8b92001-05-28 00:41:15 +00001264 rc = moveToChild(pCur, chldPg);
drh72f82862001-05-24 21:06:34 +00001265 if( rc ) return rc;
1266 }
drhbd03cae2001-06-02 02:40:57 +00001267 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00001268}
1269
1270/*
drhbd03cae2001-06-02 02:40:57 +00001271** Advance the cursor to the next entry in the database. If
1272** successful and pRes!=NULL then set *pRes=0. If the cursor
1273** was already pointing to the last entry in the database before
1274** this routine was called, then set *pRes=1 if pRes!=NULL.
drh72f82862001-05-24 21:06:34 +00001275*/
1276int sqliteBtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00001277 int rc;
drh5e2f8b92001-05-28 00:41:15 +00001278 if( pCur->bSkipNext ){
1279 pCur->bSkipNext = 0;
drh72f82862001-05-24 21:06:34 +00001280 if( pRes ) *pRes = 0;
1281 return SQLITE_OK;
1282 }
drh72f82862001-05-24 21:06:34 +00001283 pCur->idx++;
drh5e2f8b92001-05-28 00:41:15 +00001284 if( pCur->idx>=pCur->pPage->nCell ){
drh8c42ca92001-06-22 19:15:00 +00001285 if( pCur->pPage->u.hdr.rightChild ){
1286 rc = moveToChild(pCur, pCur->pPage->u.hdr.rightChild);
drh5e2f8b92001-05-28 00:41:15 +00001287 if( rc ) return rc;
1288 rc = moveToLeftmost(pCur);
1289 if( rc ) return rc;
1290 if( pRes ) *pRes = 0;
drh72f82862001-05-24 21:06:34 +00001291 return SQLITE_OK;
1292 }
drh5e2f8b92001-05-28 00:41:15 +00001293 do{
drh8c42ca92001-06-22 19:15:00 +00001294 if( pCur->pPage->pParent==0 ){
drh5e2f8b92001-05-28 00:41:15 +00001295 if( pRes ) *pRes = 1;
1296 return SQLITE_OK;
1297 }
1298 rc = moveToParent(pCur);
1299 if( rc ) return rc;
1300 }while( pCur->idx>=pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00001301 if( pRes ) *pRes = 0;
1302 return SQLITE_OK;
1303 }
drh5e2f8b92001-05-28 00:41:15 +00001304 rc = moveToLeftmost(pCur);
1305 if( rc ) return rc;
drh72f82862001-05-24 21:06:34 +00001306 if( pRes ) *pRes = 0;
1307 return SQLITE_OK;
1308}
1309
drh3b7511c2001-05-26 13:15:44 +00001310/*
1311** Allocate a new page from the database file.
1312**
1313** The new page is marked as dirty. (In other words, sqlitepager_write()
1314** has already been called on the new page.) The new page has also
1315** been referenced and the calling routine is responsible for calling
1316** sqlitepager_unref() on the new page when it is done.
1317**
1318** SQLITE_OK is returned on success. Any other return value indicates
1319** an error. *ppPage and *pPgno are undefined in the event of an error.
1320** Do not invoke sqlitepager_unref() on *ppPage if an error is returned.
1321*/
1322static int allocatePage(Btree *pBt, MemPage **ppPage, Pgno *pPgno){
drhbd03cae2001-06-02 02:40:57 +00001323 PageOne *pPage1 = pBt->page1;
drh8c42ca92001-06-22 19:15:00 +00001324 int rc;
drh3b7511c2001-05-26 13:15:44 +00001325 if( pPage1->freeList ){
1326 OverflowPage *pOvfl;
1327 rc = sqlitepager_write(pPage1);
1328 if( rc ) return rc;
1329 *pPgno = pPage1->freeList;
drh8c42ca92001-06-22 19:15:00 +00001330 rc = sqlitepager_get(pBt->pPager, pPage1->freeList, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001331 if( rc ) return rc;
1332 rc = sqlitepager_write(pOvfl);
1333 if( rc ){
1334 sqlitepager_unref(pOvfl);
1335 return rc;
1336 }
drh14acc042001-06-10 19:56:58 +00001337 pPage1->freeList = pOvfl->iNext;
drh2aa679f2001-06-25 02:11:07 +00001338 pPage1->nFree--;
drh3b7511c2001-05-26 13:15:44 +00001339 *ppPage = (MemPage*)pOvfl;
1340 }else{
drh2aa679f2001-06-25 02:11:07 +00001341 *pPgno = sqlitepager_pagecount(pBt->pPager) + 1;
drh8c42ca92001-06-22 19:15:00 +00001342 rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
drh3b7511c2001-05-26 13:15:44 +00001343 if( rc ) return rc;
1344 rc = sqlitepager_write(*ppPage);
1345 }
1346 return rc;
1347}
1348
1349/*
1350** Add a page of the database file to the freelist. Either pgno or
1351** pPage but not both may be 0.
drh5e2f8b92001-05-28 00:41:15 +00001352**
drhdd793422001-06-28 01:54:48 +00001353** sqlitepager_unref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00001354*/
1355static int freePage(Btree *pBt, void *pPage, Pgno pgno){
drhbd03cae2001-06-02 02:40:57 +00001356 PageOne *pPage1 = pBt->page1;
drh3b7511c2001-05-26 13:15:44 +00001357 OverflowPage *pOvfl = (OverflowPage*)pPage;
1358 int rc;
drhdd793422001-06-28 01:54:48 +00001359 int needUnref = 0;
1360 MemPage *pMemPage;
drh8b2f49b2001-06-08 00:21:52 +00001361
drh3b7511c2001-05-26 13:15:44 +00001362 if( pgno==0 ){
1363 assert( pOvfl!=0 );
1364 pgno = sqlitepager_pagenumber(pOvfl);
1365 }
drh2aa679f2001-06-25 02:11:07 +00001366 assert( pgno>2 );
drh3b7511c2001-05-26 13:15:44 +00001367 rc = sqlitepager_write(pPage1);
1368 if( rc ){
1369 return rc;
1370 }
1371 if( pOvfl==0 ){
1372 assert( pgno>0 );
drh8c42ca92001-06-22 19:15:00 +00001373 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001374 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001375 needUnref = 1;
drh3b7511c2001-05-26 13:15:44 +00001376 }
1377 rc = sqlitepager_write(pOvfl);
1378 if( rc ){
drhdd793422001-06-28 01:54:48 +00001379 if( needUnref ) sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001380 return rc;
1381 }
drh14acc042001-06-10 19:56:58 +00001382 pOvfl->iNext = pPage1->freeList;
drh3b7511c2001-05-26 13:15:44 +00001383 pPage1->freeList = pgno;
drh2aa679f2001-06-25 02:11:07 +00001384 pPage1->nFree++;
drh5e2f8b92001-05-28 00:41:15 +00001385 memset(pOvfl->aPayload, 0, OVERFLOW_SIZE);
drhdd793422001-06-28 01:54:48 +00001386 pMemPage = (MemPage*)pPage;
1387 pMemPage->isInit = 0;
1388 if( pMemPage->pParent ){
1389 sqlitepager_unref(pMemPage->pParent);
1390 pMemPage->pParent = 0;
1391 }
1392 if( needUnref ) rc = sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001393 return rc;
1394}
1395
1396/*
1397** Erase all the data out of a cell. This involves returning overflow
1398** pages back the freelist.
1399*/
1400static int clearCell(Btree *pBt, Cell *pCell){
1401 Pager *pPager = pBt->pPager;
1402 OverflowPage *pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001403 Pgno ovfl, nextOvfl;
1404 int rc;
1405
drh5e2f8b92001-05-28 00:41:15 +00001406 if( pCell->h.nKey + pCell->h.nData <= MX_LOCAL_PAYLOAD ){
1407 return SQLITE_OK;
1408 }
drh3b7511c2001-05-26 13:15:44 +00001409 ovfl = pCell->ovfl;
1410 pCell->ovfl = 0;
1411 while( ovfl ){
drh8c42ca92001-06-22 19:15:00 +00001412 rc = sqlitepager_get(pPager, ovfl, (void**)&pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001413 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00001414 nextOvfl = pOvfl->iNext;
drhbd03cae2001-06-02 02:40:57 +00001415 rc = freePage(pBt, pOvfl, ovfl);
1416 if( rc ) return rc;
drhdd793422001-06-28 01:54:48 +00001417 sqlitepager_unref(pOvfl);
drh3b7511c2001-05-26 13:15:44 +00001418 ovfl = nextOvfl;
drh3b7511c2001-05-26 13:15:44 +00001419 }
drh5e2f8b92001-05-28 00:41:15 +00001420 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00001421}
1422
1423/*
1424** Create a new cell from key and data. Overflow pages are allocated as
1425** necessary and linked to this cell.
1426*/
1427static int fillInCell(
1428 Btree *pBt, /* The whole Btree. Needed to allocate pages */
1429 Cell *pCell, /* Populate this Cell structure */
drh5c4d9702001-08-20 00:33:58 +00001430 const void *pKey, int nKey, /* The key */
1431 const void *pData,int nData /* The data */
drh3b7511c2001-05-26 13:15:44 +00001432){
drhdd793422001-06-28 01:54:48 +00001433 OverflowPage *pOvfl, *pPrior;
drh3b7511c2001-05-26 13:15:44 +00001434 Pgno *pNext;
1435 int spaceLeft;
drh8c42ca92001-06-22 19:15:00 +00001436 int n, rc;
drh3b7511c2001-05-26 13:15:44 +00001437 int nPayload;
drh5c4d9702001-08-20 00:33:58 +00001438 const char *pPayload;
drh3b7511c2001-05-26 13:15:44 +00001439 char *pSpace;
1440
drh5e2f8b92001-05-28 00:41:15 +00001441 pCell->h.leftChild = 0;
drh3b7511c2001-05-26 13:15:44 +00001442 pCell->h.nKey = nKey;
1443 pCell->h.nData = nData;
1444 pCell->h.iNext = 0;
1445
1446 pNext = &pCell->ovfl;
drh5e2f8b92001-05-28 00:41:15 +00001447 pSpace = pCell->aPayload;
drh3b7511c2001-05-26 13:15:44 +00001448 spaceLeft = MX_LOCAL_PAYLOAD;
1449 pPayload = pKey;
1450 pKey = 0;
1451 nPayload = nKey;
drhdd793422001-06-28 01:54:48 +00001452 pPrior = 0;
drh3b7511c2001-05-26 13:15:44 +00001453 while( nPayload>0 ){
1454 if( spaceLeft==0 ){
drh8c42ca92001-06-22 19:15:00 +00001455 rc = allocatePage(pBt, (MemPage**)&pOvfl, pNext);
drh3b7511c2001-05-26 13:15:44 +00001456 if( rc ){
1457 *pNext = 0;
drhdd793422001-06-28 01:54:48 +00001458 }
1459 if( pPrior ) sqlitepager_unref(pPrior);
1460 if( rc ){
drh5e2f8b92001-05-28 00:41:15 +00001461 clearCell(pBt, pCell);
drh3b7511c2001-05-26 13:15:44 +00001462 return rc;
1463 }
drhdd793422001-06-28 01:54:48 +00001464 pPrior = pOvfl;
drh3b7511c2001-05-26 13:15:44 +00001465 spaceLeft = OVERFLOW_SIZE;
drh5e2f8b92001-05-28 00:41:15 +00001466 pSpace = pOvfl->aPayload;
drh8c42ca92001-06-22 19:15:00 +00001467 pNext = &pOvfl->iNext;
drh3b7511c2001-05-26 13:15:44 +00001468 }
1469 n = nPayload;
1470 if( n>spaceLeft ) n = spaceLeft;
1471 memcpy(pSpace, pPayload, n);
1472 nPayload -= n;
1473 if( nPayload==0 && pData ){
1474 pPayload = pData;
1475 nPayload = nData;
1476 pData = 0;
1477 }else{
1478 pPayload += n;
1479 }
1480 spaceLeft -= n;
1481 pSpace += n;
1482 }
drhdd793422001-06-28 01:54:48 +00001483 *pNext = 0;
1484 if( pPrior ){
1485 sqlitepager_unref(pPrior);
1486 }
drh3b7511c2001-05-26 13:15:44 +00001487 return SQLITE_OK;
1488}
1489
1490/*
drhbd03cae2001-06-02 02:40:57 +00001491** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00001492** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00001493** pointer in the third argument.
1494*/
1495static void reparentPage(Pager *pPager, Pgno pgno, MemPage *pNewParent){
1496 MemPage *pThis;
1497
drhdd793422001-06-28 01:54:48 +00001498 if( pgno==0 ) return;
1499 assert( pPager!=0 );
drhbd03cae2001-06-02 02:40:57 +00001500 pThis = sqlitepager_lookup(pPager, pgno);
drh6019e162001-07-02 17:51:45 +00001501 if( pThis && pThis->isInit ){
drhdd793422001-06-28 01:54:48 +00001502 if( pThis->pParent!=pNewParent ){
1503 if( pThis->pParent ) sqlitepager_unref(pThis->pParent);
1504 pThis->pParent = pNewParent;
1505 if( pNewParent ) sqlitepager_ref(pNewParent);
1506 }
1507 sqlitepager_unref(pThis);
drhbd03cae2001-06-02 02:40:57 +00001508 }
1509}
1510
1511/*
1512** Reparent all children of the given page to be the given page.
1513** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00001514** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00001515**
1516** This routine gets called after you memcpy() one page into
1517** another.
1518*/
drh8c42ca92001-06-22 19:15:00 +00001519static void reparentChildPages(Pager *pPager, MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00001520 int i;
1521 for(i=0; i<pPage->nCell; i++){
drh8c42ca92001-06-22 19:15:00 +00001522 reparentPage(pPager, pPage->apCell[i]->h.leftChild, pPage);
drhbd03cae2001-06-02 02:40:57 +00001523 }
drh14acc042001-06-10 19:56:58 +00001524 reparentPage(pPager, pPage->u.hdr.rightChild, pPage);
1525}
1526
1527/*
1528** Remove the i-th cell from pPage. This routine effects pPage only.
1529** The cell content is not freed or deallocated. It is assumed that
1530** the cell content has been copied someplace else. This routine just
1531** removes the reference to the cell from pPage.
1532**
1533** "sz" must be the number of bytes in the cell.
1534**
1535** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001536** Only the pPage->apCell[] array is important. The relinkCellList()
1537** routine will be called soon after this routine in order to rebuild
1538** the linked list.
drh14acc042001-06-10 19:56:58 +00001539*/
drh8c42ca92001-06-22 19:15:00 +00001540static void dropCell(MemPage *pPage, int idx, int sz){
drh14acc042001-06-10 19:56:58 +00001541 int j;
drh8c42ca92001-06-22 19:15:00 +00001542 assert( idx>=0 && idx<pPage->nCell );
1543 assert( sz==cellSize(pPage->apCell[idx]) );
drh6019e162001-07-02 17:51:45 +00001544 assert( sqlitepager_iswriteable(pPage) );
drh7c717f72001-06-24 20:39:41 +00001545 freeSpace(pPage, Addr(pPage->apCell[idx]) - Addr(pPage), sz);
1546 for(j=idx; j<pPage->nCell-1; j++){
drh14acc042001-06-10 19:56:58 +00001547 pPage->apCell[j] = pPage->apCell[j+1];
1548 }
1549 pPage->nCell--;
1550}
1551
1552/*
1553** Insert a new cell on pPage at cell index "i". pCell points to the
1554** content of the cell.
1555**
1556** If the cell content will fit on the page, then put it there. If it
1557** will not fit, then just make pPage->apCell[i] point to the content
1558** and set pPage->isOverfull.
1559**
1560** Do not bother maintaining the integrity of the linked list of Cells.
drh8c42ca92001-06-22 19:15:00 +00001561** Only the pPage->apCell[] array is important. The relinkCellList()
1562** routine will be called soon after this routine in order to rebuild
1563** the linked list.
drh14acc042001-06-10 19:56:58 +00001564*/
1565static void insertCell(MemPage *pPage, int i, Cell *pCell, int sz){
1566 int idx, j;
1567 assert( i>=0 && i<=pPage->nCell );
1568 assert( sz==cellSize(pCell) );
drh6019e162001-07-02 17:51:45 +00001569 assert( sqlitepager_iswriteable(pPage) );
drh2aa679f2001-06-25 02:11:07 +00001570 idx = allocateSpace(pPage, sz);
drh14acc042001-06-10 19:56:58 +00001571 for(j=pPage->nCell; j>i; j--){
1572 pPage->apCell[j] = pPage->apCell[j-1];
1573 }
1574 pPage->nCell++;
drh14acc042001-06-10 19:56:58 +00001575 if( idx<=0 ){
1576 pPage->isOverfull = 1;
1577 pPage->apCell[i] = pCell;
1578 }else{
1579 memcpy(&pPage->u.aDisk[idx], pCell, sz);
drh8c42ca92001-06-22 19:15:00 +00001580 pPage->apCell[i] = (Cell*)&pPage->u.aDisk[idx];
drh14acc042001-06-10 19:56:58 +00001581 }
1582}
1583
1584/*
1585** Rebuild the linked list of cells on a page so that the cells
drh8c42ca92001-06-22 19:15:00 +00001586** occur in the order specified by the pPage->apCell[] array.
1587** Invoke this routine once to repair damage after one or more
1588** invocations of either insertCell() or dropCell().
drh14acc042001-06-10 19:56:58 +00001589*/
1590static void relinkCellList(MemPage *pPage){
1591 int i;
1592 u16 *pIdx;
drh6019e162001-07-02 17:51:45 +00001593 assert( sqlitepager_iswriteable(pPage) );
drh14acc042001-06-10 19:56:58 +00001594 pIdx = &pPage->u.hdr.firstCell;
1595 for(i=0; i<pPage->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00001596 int idx = Addr(pPage->apCell[i]) - Addr(pPage);
drh8c42ca92001-06-22 19:15:00 +00001597 assert( idx>0 && idx<SQLITE_PAGE_SIZE );
drh14acc042001-06-10 19:56:58 +00001598 *pIdx = idx;
1599 pIdx = &pPage->apCell[i]->h.iNext;
1600 }
1601 *pIdx = 0;
1602}
1603
1604/*
1605** Make a copy of the contents of pFrom into pTo. The pFrom->apCell[]
drh5e00f6c2001-09-13 13:46:56 +00001606** pointers that point into pFrom->u.aDisk[] must be adjusted to point
drhdd793422001-06-28 01:54:48 +00001607** into pTo->u.aDisk[] instead. But some pFrom->apCell[] entries might
drh14acc042001-06-10 19:56:58 +00001608** not point to pFrom->u.aDisk[]. Those are unchanged.
1609*/
1610static void copyPage(MemPage *pTo, MemPage *pFrom){
1611 uptr from, to;
1612 int i;
1613 memcpy(pTo->u.aDisk, pFrom->u.aDisk, SQLITE_PAGE_SIZE);
drhdd793422001-06-28 01:54:48 +00001614 pTo->pParent = 0;
drh14acc042001-06-10 19:56:58 +00001615 pTo->isInit = 1;
1616 pTo->nCell = pFrom->nCell;
1617 pTo->nFree = pFrom->nFree;
1618 pTo->isOverfull = pFrom->isOverfull;
drh7c717f72001-06-24 20:39:41 +00001619 to = Addr(pTo);
1620 from = Addr(pFrom);
drh14acc042001-06-10 19:56:58 +00001621 for(i=0; i<pTo->nCell; i++){
drh7c717f72001-06-24 20:39:41 +00001622 uptr x = Addr(pFrom->apCell[i]);
drh8c42ca92001-06-22 19:15:00 +00001623 if( x>from && x<from+SQLITE_PAGE_SIZE ){
1624 *((uptr*)&pTo->apCell[i]) = x + to - from;
drhdd793422001-06-28 01:54:48 +00001625 }else{
1626 pTo->apCell[i] = pFrom->apCell[i];
drh14acc042001-06-10 19:56:58 +00001627 }
1628 }
drhbd03cae2001-06-02 02:40:57 +00001629}
1630
1631/*
drh8b2f49b2001-06-08 00:21:52 +00001632** This routine redistributes Cells on pPage and up to two siblings
1633** of pPage so that all pages have about the same amount of free space.
drh14acc042001-06-10 19:56:58 +00001634** Usually one sibling on either side of pPage is used in the balancing,
drh8b2f49b2001-06-08 00:21:52 +00001635** though both siblings might come from one side if pPage is the first
1636** or last child of its parent. If pPage has fewer than two siblings
1637** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00001638** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00001639**
1640** The number of siblings of pPage might be increased or decreased by
drh8c42ca92001-06-22 19:15:00 +00001641** one in an effort to keep pages between 66% and 100% full. The root page
1642** is special and is allowed to be less than 66% full. If pPage is
1643** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00001644** or decreased by one, as necessary, to keep the root page from being
1645** overfull or empty.
1646**
drh14acc042001-06-10 19:56:58 +00001647** This routine calls relinkCellList() on its input page regardless of
1648** whether or not it does any real balancing. Client routines will typically
1649** invoke insertCell() or dropCell() before calling this routine, so we
1650** need to call relinkCellList() to clean up the mess that those other
1651** routines left behind.
1652**
1653** pCur is left pointing to the same cell as when this routine was called
drh8c42ca92001-06-22 19:15:00 +00001654** even if that cell gets moved to a different page. pCur may be NULL.
1655** Set the pCur parameter to NULL if you do not care about keeping track
1656** of a cell as that will save this routine the work of keeping track of it.
drh14acc042001-06-10 19:56:58 +00001657**
drh8b2f49b2001-06-08 00:21:52 +00001658** Note that when this routine is called, some of the Cells on pPage
drh14acc042001-06-10 19:56:58 +00001659** might not actually be stored in pPage->u.aDisk[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00001660** if the page is overfull. Part of the job of this routine is to
drh14acc042001-06-10 19:56:58 +00001661** make sure all Cells for pPage once again fit in pPage->u.aDisk[].
1662**
drh8c42ca92001-06-22 19:15:00 +00001663** In the course of balancing the siblings of pPage, the parent of pPage
1664** might become overfull or underfull. If that happens, then this routine
1665** is called recursively on the parent.
1666**
drh5e00f6c2001-09-13 13:46:56 +00001667** If this routine fails for any reason, it might leave the database
1668** in a corrupted state. So if this routine fails, the database should
1669** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00001670*/
drh14acc042001-06-10 19:56:58 +00001671static int balance(Btree *pBt, MemPage *pPage, BtCursor *pCur){
drh8b2f49b2001-06-08 00:21:52 +00001672 MemPage *pParent; /* The parent of pPage */
drh14acc042001-06-10 19:56:58 +00001673 MemPage *apOld[3]; /* pPage and up to two siblings */
drh8b2f49b2001-06-08 00:21:52 +00001674 Pgno pgnoOld[3]; /* Page numbers for each page in apOld[] */
drh14acc042001-06-10 19:56:58 +00001675 MemPage *apNew[4]; /* pPage and up to 3 siblings after balancing */
1676 Pgno pgnoNew[4]; /* Page numbers for each page in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00001677 int idxDiv[3]; /* Indices of divider cells in pParent */
1678 Cell *apDiv[3]; /* Divider cells in pParent */
1679 int nCell; /* Number of cells in apCell[] */
1680 int nOld; /* Number of pages in apOld[] */
1681 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00001682 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00001683 int i, j, k; /* Loop counters */
1684 int idx; /* Index of pPage in pParent->apCell[] */
1685 int nxDiv; /* Next divider slot in pParent->apCell[] */
1686 int rc; /* The return code */
1687 int iCur; /* apCell[iCur] is the cell of the cursor */
drh5edc3122001-09-13 21:53:09 +00001688 MemPage *pOldCurPage; /* The cursor originally points to this page */
drh8c42ca92001-06-22 19:15:00 +00001689 int totalSize; /* Total bytes for all cells */
drh6019e162001-07-02 17:51:45 +00001690 int subtotal; /* Subtotal of bytes in cells on one page */
1691 int cntNew[4]; /* Index in apCell[] of cell after i-th page */
1692 int szNew[4]; /* Combined size of cells place on i-th page */
drh9ca7d3b2001-06-28 11:50:21 +00001693 MemPage *extraUnref = 0; /* A page that needs to be unref-ed */
drh8c42ca92001-06-22 19:15:00 +00001694 Pgno pgno; /* Page number */
drh14acc042001-06-10 19:56:58 +00001695 Cell *apCell[MX_CELL*3+5]; /* All cells from pages being balanceed */
1696 int szCell[MX_CELL*3+5]; /* Local size of all cells */
1697 Cell aTemp[2]; /* Temporary holding area for apDiv[] */
1698 MemPage aOld[3]; /* Temporary copies of pPage and its siblings */
drh8b2f49b2001-06-08 00:21:52 +00001699
drh14acc042001-06-10 19:56:58 +00001700 /*
1701 ** Return without doing any work if pPage is neither overfull nor
1702 ** underfull.
drh8b2f49b2001-06-08 00:21:52 +00001703 */
drh6019e162001-07-02 17:51:45 +00001704 assert( sqlitepager_iswriteable(pPage) );
1705 if( !pPage->isOverfull && pPage->nFree<SQLITE_PAGE_SIZE/3 ){
drh14acc042001-06-10 19:56:58 +00001706 relinkCellList(pPage);
drh8b2f49b2001-06-08 00:21:52 +00001707 return SQLITE_OK;
1708 }
1709
1710 /*
drh14acc042001-06-10 19:56:58 +00001711 ** Find the parent of the page to be balanceed.
1712 ** If there is no parent, it means this page is the root page and
drh8b2f49b2001-06-08 00:21:52 +00001713 ** special rules apply.
1714 */
drh14acc042001-06-10 19:56:58 +00001715 pParent = pPage->pParent;
drh8b2f49b2001-06-08 00:21:52 +00001716 if( pParent==0 ){
1717 Pgno pgnoChild;
drh8c42ca92001-06-22 19:15:00 +00001718 MemPage *pChild;
drh8b2f49b2001-06-08 00:21:52 +00001719 if( pPage->nCell==0 ){
drh14acc042001-06-10 19:56:58 +00001720 if( pPage->u.hdr.rightChild ){
1721 /*
1722 ** The root page is empty. Copy the one child page
drh8b2f49b2001-06-08 00:21:52 +00001723 ** into the root page and return. This reduces the depth
1724 ** of the BTree by one.
1725 */
drh14acc042001-06-10 19:56:58 +00001726 pgnoChild = pPage->u.hdr.rightChild;
drh8c42ca92001-06-22 19:15:00 +00001727 rc = sqlitepager_get(pBt->pPager, pgnoChild, (void**)&pChild);
drh8b2f49b2001-06-08 00:21:52 +00001728 if( rc ) return rc;
1729 memcpy(pPage, pChild, SQLITE_PAGE_SIZE);
1730 pPage->isInit = 0;
drh6019e162001-07-02 17:51:45 +00001731 rc = initPage(pPage, sqlitepager_pagenumber(pPage), 0);
1732 assert( rc==SQLITE_OK );
drh8b2f49b2001-06-08 00:21:52 +00001733 reparentChildPages(pBt->pPager, pPage);
drh5edc3122001-09-13 21:53:09 +00001734 if( pCur && pCur->pPage==pChild ){
1735 sqlitepager_unref(pChild);
1736 pCur->pPage = pPage;
1737 sqlitepager_ref(pPage);
1738 }
drh8b2f49b2001-06-08 00:21:52 +00001739 freePage(pBt, pChild, pgnoChild);
1740 sqlitepager_unref(pChild);
drhefc251d2001-07-01 22:12:01 +00001741 }else{
1742 relinkCellList(pPage);
drh8b2f49b2001-06-08 00:21:52 +00001743 }
1744 return SQLITE_OK;
1745 }
drh14acc042001-06-10 19:56:58 +00001746 if( !pPage->isOverfull ){
drh8b2f49b2001-06-08 00:21:52 +00001747 /* It is OK for the root page to be less than half full.
1748 */
drh14acc042001-06-10 19:56:58 +00001749 relinkCellList(pPage);
drh8b2f49b2001-06-08 00:21:52 +00001750 return SQLITE_OK;
1751 }
drh14acc042001-06-10 19:56:58 +00001752 /*
1753 ** If we get to here, it means the root page is overfull.
drh8b2f49b2001-06-08 00:21:52 +00001754 ** When this happens, Create a new child page and copy the
1755 ** contents of the root into the child. Then make the root
drh14acc042001-06-10 19:56:58 +00001756 ** page an empty page with rightChild pointing to the new
drh8b2f49b2001-06-08 00:21:52 +00001757 ** child. Then fall thru to the code below which will cause
1758 ** the overfull child page to be split.
1759 */
drh14acc042001-06-10 19:56:58 +00001760 rc = sqlitepager_write(pPage);
1761 if( rc ) return rc;
drh8b2f49b2001-06-08 00:21:52 +00001762 rc = allocatePage(pBt, &pChild, &pgnoChild);
1763 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00001764 assert( sqlitepager_iswriteable(pChild) );
drh14acc042001-06-10 19:56:58 +00001765 copyPage(pChild, pPage);
1766 pChild->pParent = pPage;
drhdd793422001-06-28 01:54:48 +00001767 sqlitepager_ref(pPage);
drh14acc042001-06-10 19:56:58 +00001768 pChild->isOverfull = 1;
drh5edc3122001-09-13 21:53:09 +00001769 if( pCur && pCur->pPage==pPage ){
1770 sqlitepager_unref(pPage);
drh14acc042001-06-10 19:56:58 +00001771 pCur->pPage = pChild;
drh9ca7d3b2001-06-28 11:50:21 +00001772 }else{
1773 extraUnref = pChild;
drh8b2f49b2001-06-08 00:21:52 +00001774 }
drh8b2f49b2001-06-08 00:21:52 +00001775 zeroPage(pPage);
drh14acc042001-06-10 19:56:58 +00001776 pPage->u.hdr.rightChild = pgnoChild;
drh8b2f49b2001-06-08 00:21:52 +00001777 pParent = pPage;
1778 pPage = pChild;
drh8b2f49b2001-06-08 00:21:52 +00001779 }
drh6019e162001-07-02 17:51:45 +00001780 rc = sqlitepager_write(pParent);
1781 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00001782
drh8b2f49b2001-06-08 00:21:52 +00001783 /*
drh14acc042001-06-10 19:56:58 +00001784 ** Find the Cell in the parent page whose h.leftChild points back
1785 ** to pPage. The "idx" variable is the index of that cell. If pPage
1786 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00001787 */
1788 idx = -1;
1789 pgno = sqlitepager_pagenumber(pPage);
1790 for(i=0; i<pParent->nCell; i++){
1791 if( pParent->apCell[i]->h.leftChild==pgno ){
1792 idx = i;
1793 break;
1794 }
1795 }
drhdd793422001-06-28 01:54:48 +00001796 if( idx<0 && pParent->u.hdr.rightChild==pgno ){
1797 idx = pParent->nCell;
drh8b2f49b2001-06-08 00:21:52 +00001798 }
1799 if( idx<0 ){
drh14acc042001-06-10 19:56:58 +00001800 return SQLITE_CORRUPT;
drh8b2f49b2001-06-08 00:21:52 +00001801 }
1802
1803 /*
drh14acc042001-06-10 19:56:58 +00001804 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00001805 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00001806 */
drh14acc042001-06-10 19:56:58 +00001807 nOld = nNew = 0;
1808 sqlitepager_ref(pParent);
1809
1810 /*
1811 ** Find sibling pages to pPage and the Cells in pParent that divide
1812 ** the siblings. An attempt is made to find one sibling on either
1813 ** side of pPage. Both siblings are taken from one side, however, if
1814 ** pPage is either the first or last child of its parent. If pParent
1815 ** has 3 or fewer children then all children of pParent are taken.
1816 */
1817 if( idx==pParent->nCell ){
1818 nxDiv = idx - 2;
drh8b2f49b2001-06-08 00:21:52 +00001819 }else{
drh14acc042001-06-10 19:56:58 +00001820 nxDiv = idx - 1;
drh8b2f49b2001-06-08 00:21:52 +00001821 }
drh14acc042001-06-10 19:56:58 +00001822 if( nxDiv<0 ) nxDiv = 0;
drh8b2f49b2001-06-08 00:21:52 +00001823 nDiv = 0;
drh14acc042001-06-10 19:56:58 +00001824 for(i=0, k=nxDiv; i<3; i++, k++){
1825 if( k<pParent->nCell ){
1826 idxDiv[i] = k;
1827 apDiv[i] = pParent->apCell[k];
drh8b2f49b2001-06-08 00:21:52 +00001828 nDiv++;
1829 pgnoOld[i] = apDiv[i]->h.leftChild;
drh14acc042001-06-10 19:56:58 +00001830 }else if( k==pParent->nCell ){
drh8c42ca92001-06-22 19:15:00 +00001831 pgnoOld[i] = pParent->u.hdr.rightChild;
drh14acc042001-06-10 19:56:58 +00001832 }else{
1833 break;
drh8b2f49b2001-06-08 00:21:52 +00001834 }
drh8c42ca92001-06-22 19:15:00 +00001835 rc = sqlitepager_get(pBt->pPager, pgnoOld[i], (void**)&apOld[i]);
drh14acc042001-06-10 19:56:58 +00001836 if( rc ) goto balance_cleanup;
drh6019e162001-07-02 17:51:45 +00001837 rc = initPage(apOld[i], pgnoOld[i], pParent);
1838 if( rc ) goto balance_cleanup;
drh14acc042001-06-10 19:56:58 +00001839 nOld++;
drh8b2f49b2001-06-08 00:21:52 +00001840 }
1841
1842 /*
drh14acc042001-06-10 19:56:58 +00001843 ** Set iCur to be the index in apCell[] of the cell that the cursor
1844 ** is pointing to. We will need this later on in order to keep the
drh5edc3122001-09-13 21:53:09 +00001845 ** cursor pointing at the same cell. If pCur points to a page that
1846 ** has no involvement with this rebalancing, then set iCur to a large
1847 ** number so that the iCur==j tests always fail in the main cell
1848 ** distribution loop below.
drh14acc042001-06-10 19:56:58 +00001849 */
1850 if( pCur ){
drh5edc3122001-09-13 21:53:09 +00001851 iCur = 0;
1852 for(i=0; i<nOld; i++){
1853 if( pCur->pPage==apOld[i] ){
1854 iCur += pCur->idx;
1855 break;
1856 }
1857 iCur += apOld[i]->nCell;
1858 if( i<nOld-1 && pCur->pPage==pParent && pCur->idx==idxDiv[i] ){
1859 break;
1860 }
1861 iCur++;
drh14acc042001-06-10 19:56:58 +00001862 }
drh5edc3122001-09-13 21:53:09 +00001863 pOldCurPage = pCur->pPage;
drh14acc042001-06-10 19:56:58 +00001864 }
1865
1866 /*
1867 ** Make copies of the content of pPage and its siblings into aOld[].
1868 ** The rest of this function will use data from the copies rather
1869 ** that the original pages since the original pages will be in the
1870 ** process of being overwritten.
1871 */
1872 for(i=0; i<nOld; i++){
1873 copyPage(&aOld[i], apOld[i]);
1874 rc = freePage(pBt, apOld[i], pgnoOld[i]);
1875 if( rc ) goto balance_cleanup;
drhdd793422001-06-28 01:54:48 +00001876 sqlitepager_unref(apOld[i]);
drh14acc042001-06-10 19:56:58 +00001877 apOld[i] = &aOld[i];
1878 }
1879
1880 /*
1881 ** Load pointers to all cells on sibling pages and the divider cells
1882 ** into the local apCell[] array. Make copies of the divider cells
1883 ** into aTemp[] and remove the the divider Cells from pParent.
drh8b2f49b2001-06-08 00:21:52 +00001884 */
1885 nCell = 0;
1886 for(i=0; i<nOld; i++){
1887 MemPage *pOld = apOld[i];
1888 for(j=0; j<pOld->nCell; j++){
drh14acc042001-06-10 19:56:58 +00001889 apCell[nCell] = pOld->apCell[j];
1890 szCell[nCell] = cellSize(apCell[nCell]);
1891 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00001892 }
1893 if( i<nOld-1 ){
drh14acc042001-06-10 19:56:58 +00001894 szCell[nCell] = cellSize(apDiv[i]);
drh8c42ca92001-06-22 19:15:00 +00001895 memcpy(&aTemp[i], apDiv[i], szCell[nCell]);
drh14acc042001-06-10 19:56:58 +00001896 apCell[nCell] = &aTemp[i];
1897 dropCell(pParent, nxDiv, szCell[nCell]);
1898 assert( apCell[nCell]->h.leftChild==pgnoOld[i] );
1899 apCell[nCell]->h.leftChild = pOld->u.hdr.rightChild;
1900 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00001901 }
1902 }
1903
1904 /*
drh6019e162001-07-02 17:51:45 +00001905 ** Figure out the number of pages needed to hold all nCell cells.
1906 ** Store this number in "k". Also compute szNew[] which is the total
1907 ** size of all cells on the i-th page and cntNew[] which is the index
1908 ** in apCell[] of the cell that divides path i from path i+1.
1909 ** cntNew[k] should equal nCell.
1910 **
1911 ** This little patch of code is critical for keeping the tree
1912 ** balanced.
drh8b2f49b2001-06-08 00:21:52 +00001913 */
1914 totalSize = 0;
1915 for(i=0; i<nCell; i++){
drh14acc042001-06-10 19:56:58 +00001916 totalSize += szCell[i];
drh8b2f49b2001-06-08 00:21:52 +00001917 }
drh6019e162001-07-02 17:51:45 +00001918 for(subtotal=k=i=0; i<nCell; i++){
1919 subtotal += szCell[i];
1920 if( subtotal > USABLE_SPACE ){
1921 szNew[k] = subtotal - szCell[i];
1922 cntNew[k] = i;
1923 subtotal = 0;
1924 k++;
1925 }
1926 }
1927 szNew[k] = subtotal;
1928 cntNew[k] = nCell;
1929 k++;
1930 for(i=k-1; i>0; i--){
1931 while( szNew[i]<USABLE_SPACE/2 ){
1932 cntNew[i-1]--;
1933 assert( cntNew[i-1]>0 );
1934 szNew[i] += szCell[cntNew[i-1]];
1935 szNew[i-1] -= szCell[cntNew[i-1]-1];
1936 }
1937 }
1938 assert( cntNew[0]>0 );
drh8b2f49b2001-06-08 00:21:52 +00001939
1940 /*
drh6019e162001-07-02 17:51:45 +00001941 ** Allocate k new pages
drh8b2f49b2001-06-08 00:21:52 +00001942 */
drh14acc042001-06-10 19:56:58 +00001943 for(i=0; i<k; i++){
drh8b2f49b2001-06-08 00:21:52 +00001944 rc = allocatePage(pBt, &apNew[i], &pgnoNew[i]);
drh14acc042001-06-10 19:56:58 +00001945 if( rc ) goto balance_cleanup;
1946 nNew++;
drh8b2f49b2001-06-08 00:21:52 +00001947 zeroPage(apNew[i]);
drh6019e162001-07-02 17:51:45 +00001948 apNew[i]->isInit = 1;
drh8b2f49b2001-06-08 00:21:52 +00001949 }
1950
1951 /*
drh14acc042001-06-10 19:56:58 +00001952 ** Evenly distribute the data in apCell[] across the new pages.
1953 ** Insert divider cells into pParent as necessary.
1954 */
1955 j = 0;
1956 for(i=0; i<nNew; i++){
1957 MemPage *pNew = apNew[i];
drh6019e162001-07-02 17:51:45 +00001958 while( j<cntNew[i] ){
1959 assert( pNew->nFree>=szCell[j] );
drh14acc042001-06-10 19:56:58 +00001960 if( pCur && iCur==j ){ pCur->pPage = pNew; pCur->idx = pNew->nCell; }
1961 insertCell(pNew, pNew->nCell, apCell[j], szCell[j]);
1962 j++;
1963 }
drh6019e162001-07-02 17:51:45 +00001964 assert( pNew->nCell>0 );
drh14acc042001-06-10 19:56:58 +00001965 assert( !pNew->isOverfull );
1966 relinkCellList(pNew);
1967 if( i<nNew-1 && j<nCell ){
1968 pNew->u.hdr.rightChild = apCell[j]->h.leftChild;
1969 apCell[j]->h.leftChild = pgnoNew[i];
1970 if( pCur && iCur==j ){ pCur->pPage = pParent; pCur->idx = nxDiv; }
1971 insertCell(pParent, nxDiv, apCell[j], szCell[j]);
1972 j++;
1973 nxDiv++;
1974 }
1975 }
drh6019e162001-07-02 17:51:45 +00001976 assert( j==nCell );
drh14acc042001-06-10 19:56:58 +00001977 apNew[nNew-1]->u.hdr.rightChild = apOld[nOld-1]->u.hdr.rightChild;
1978 if( nxDiv==pParent->nCell ){
1979 pParent->u.hdr.rightChild = pgnoNew[nNew-1];
1980 }else{
1981 pParent->apCell[nxDiv]->h.leftChild = pgnoNew[nNew-1];
1982 }
1983 if( pCur ){
drh5edc3122001-09-13 21:53:09 +00001984 assert( pOldCurPage!=0 );
drh14acc042001-06-10 19:56:58 +00001985 sqlitepager_ref(pCur->pPage);
drh5edc3122001-09-13 21:53:09 +00001986 sqlitepager_unref(pOldCurPage);
drh14acc042001-06-10 19:56:58 +00001987 }
1988
1989 /*
1990 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00001991 */
1992 for(i=0; i<nNew; i++){
drh14acc042001-06-10 19:56:58 +00001993 reparentChildPages(pBt->pPager, apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00001994 }
drh14acc042001-06-10 19:56:58 +00001995 reparentChildPages(pBt->pPager, pParent);
drh8b2f49b2001-06-08 00:21:52 +00001996
1997 /*
drh14acc042001-06-10 19:56:58 +00001998 ** balance the parent page.
drh8b2f49b2001-06-08 00:21:52 +00001999 */
drh5edc3122001-09-13 21:53:09 +00002000 rc = balance(pBt, pParent, pCur);
drh8b2f49b2001-06-08 00:21:52 +00002001
2002 /*
drh14acc042001-06-10 19:56:58 +00002003 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00002004 */
drh14acc042001-06-10 19:56:58 +00002005balance_cleanup:
drh9ca7d3b2001-06-28 11:50:21 +00002006 if( extraUnref ){
2007 sqlitepager_unref(extraUnref);
2008 }
drh8b2f49b2001-06-08 00:21:52 +00002009 for(i=0; i<nOld; i++){
drhdd793422001-06-28 01:54:48 +00002010 if( apOld[i]!=&aOld[i] ) sqlitepager_unref(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00002011 }
drh14acc042001-06-10 19:56:58 +00002012 for(i=0; i<nNew; i++){
2013 sqlitepager_unref(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00002014 }
drh14acc042001-06-10 19:56:58 +00002015 if( pCur && pCur->pPage==0 ){
2016 pCur->pPage = pParent;
2017 pCur->idx = 0;
2018 }else{
2019 sqlitepager_unref(pParent);
drh8b2f49b2001-06-08 00:21:52 +00002020 }
2021 return rc;
2022}
2023
2024/*
drh3b7511c2001-05-26 13:15:44 +00002025** Insert a new record into the BTree. The key is given by (pKey,nKey)
2026** and the data is given by (pData,nData). The cursor is used only to
2027** define what database the record should be inserted into. The cursor
drh14acc042001-06-10 19:56:58 +00002028** is left pointing at the new record.
drh3b7511c2001-05-26 13:15:44 +00002029*/
2030int sqliteBtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00002031 BtCursor *pCur, /* Insert data into the table of this cursor */
drhbe0072d2001-09-13 14:46:09 +00002032 const void *pKey, int nKey, /* The key of the new record */
drh5c4d9702001-08-20 00:33:58 +00002033 const void *pData, int nData /* The data of the new record */
drh3b7511c2001-05-26 13:15:44 +00002034){
2035 Cell newCell;
2036 int rc;
2037 int loc;
drh14acc042001-06-10 19:56:58 +00002038 int szNew;
drh3b7511c2001-05-26 13:15:44 +00002039 MemPage *pPage;
2040 Btree *pBt = pCur->pBt;
2041
drh5edc3122001-09-13 21:53:09 +00002042 if( !pCur->pBt->inTrans || nKey+nData==0 ){
drh8b2f49b2001-06-08 00:21:52 +00002043 return SQLITE_ERROR; /* Must start a transaction first */
2044 }
drh14acc042001-06-10 19:56:58 +00002045 rc = sqliteBtreeMoveto(pCur, pKey, nKey, &loc);
drh3b7511c2001-05-26 13:15:44 +00002046 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002047 pPage = pCur->pPage;
2048 rc = sqlitepager_write(pPage);
drhbd03cae2001-06-02 02:40:57 +00002049 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00002050 rc = fillInCell(pBt, &newCell, pKey, nKey, pData, nData);
2051 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002052 szNew = cellSize(&newCell);
drh3b7511c2001-05-26 13:15:44 +00002053 if( loc==0 ){
drh14acc042001-06-10 19:56:58 +00002054 newCell.h.leftChild = pPage->apCell[pCur->idx]->h.leftChild;
2055 rc = clearCell(pBt, pPage->apCell[pCur->idx]);
drh5e2f8b92001-05-28 00:41:15 +00002056 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002057 dropCell(pPage, pCur->idx, cellSize(pPage->apCell[pCur->idx]));
drh7c717f72001-06-24 20:39:41 +00002058 }else if( loc<0 && pPage->nCell>0 ){
drh14acc042001-06-10 19:56:58 +00002059 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
2060 pCur->idx++;
2061 }else{
2062 assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
drh3b7511c2001-05-26 13:15:44 +00002063 }
drh7c717f72001-06-24 20:39:41 +00002064 insertCell(pPage, pCur->idx, &newCell, szNew);
drh14acc042001-06-10 19:56:58 +00002065 rc = balance(pCur->pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002066 return rc;
2067}
2068
2069/*
drhbd03cae2001-06-02 02:40:57 +00002070** Delete the entry that the cursor is pointing to.
drh5e2f8b92001-05-28 00:41:15 +00002071**
drhbd03cae2001-06-02 02:40:57 +00002072** The cursor is left pointing at either the next or the previous
2073** entry. If the cursor is left pointing to the next entry, then
2074** the pCur->bSkipNext flag is set which forces the next call to
2075** sqliteBtreeNext() to be a no-op. That way, you can always call
2076** sqliteBtreeNext() after a delete and the cursor will be left
2077** pointing to the first entry after the deleted entry.
drh3b7511c2001-05-26 13:15:44 +00002078*/
2079int sqliteBtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00002080 MemPage *pPage = pCur->pPage;
2081 Cell *pCell;
2082 int rc;
drh8c42ca92001-06-22 19:15:00 +00002083 Pgno pgnoChild;
drh8b2f49b2001-06-08 00:21:52 +00002084
2085 if( !pCur->pBt->inTrans ){
2086 return SQLITE_ERROR; /* Must start a transaction first */
2087 }
drhbd03cae2001-06-02 02:40:57 +00002088 if( pCur->idx >= pPage->nCell ){
2089 return SQLITE_ERROR; /* The cursor is not pointing to anything */
2090 }
2091 rc = sqlitepager_write(pPage);
2092 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002093 pCell = pPage->apCell[pCur->idx];
drh14acc042001-06-10 19:56:58 +00002094 pgnoChild = pCell->h.leftChild;
drh8c42ca92001-06-22 19:15:00 +00002095 clearCell(pCur->pBt, pCell);
drh14acc042001-06-10 19:56:58 +00002096 if( pgnoChild ){
2097 /*
drh5e00f6c2001-09-13 13:46:56 +00002098 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00002099 ** do something we will leave a hole on an internal page.
2100 ** We have to fill the hole by moving in a cell from a leaf. The
2101 ** next Cell after the one to be deleted is guaranteed to exist and
2102 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00002103 */
drh14acc042001-06-10 19:56:58 +00002104 BtCursor leafCur;
2105 Cell *pNext;
2106 int szNext;
2107 getTempCursor(pCur, &leafCur);
2108 rc = sqliteBtreeNext(&leafCur, 0);
2109 if( rc!=SQLITE_OK ){
2110 return SQLITE_CORRUPT;
drh5e2f8b92001-05-28 00:41:15 +00002111 }
drh6019e162001-07-02 17:51:45 +00002112 rc = sqlitepager_write(leafCur.pPage);
2113 if( rc ) return rc;
drh9ca7d3b2001-06-28 11:50:21 +00002114 dropCell(pPage, pCur->idx, cellSize(pCell));
drh8c42ca92001-06-22 19:15:00 +00002115 pNext = leafCur.pPage->apCell[leafCur.idx];
drh14acc042001-06-10 19:56:58 +00002116 szNext = cellSize(pNext);
drh8c42ca92001-06-22 19:15:00 +00002117 pNext->h.leftChild = pgnoChild;
drh14acc042001-06-10 19:56:58 +00002118 insertCell(pPage, pCur->idx, pNext, szNext);
2119 rc = balance(pCur->pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002120 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00002121 pCur->bSkipNext = 1;
drh14acc042001-06-10 19:56:58 +00002122 dropCell(leafCur.pPage, leafCur.idx, szNext);
2123 rc = balance(pCur->pBt, leafCur.pPage, 0);
drh8c42ca92001-06-22 19:15:00 +00002124 releaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00002125 }else{
drh9ca7d3b2001-06-28 11:50:21 +00002126 dropCell(pPage, pCur->idx, cellSize(pCell));
drh5edc3122001-09-13 21:53:09 +00002127 if( pCur->idx>=pPage->nCell ){
2128 pCur->idx = pPage->nCell-1;
2129 if( pCur->idx<0 ){ pCur->idx = 0; }
2130 pCur->bSkipNext = 0;
drh6019e162001-07-02 17:51:45 +00002131 }else{
2132 pCur->bSkipNext = 1;
2133 }
drh14acc042001-06-10 19:56:58 +00002134 rc = balance(pCur->pBt, pPage, pCur);
drh5e2f8b92001-05-28 00:41:15 +00002135 }
drh5e2f8b92001-05-28 00:41:15 +00002136 return rc;
drh3b7511c2001-05-26 13:15:44 +00002137}
drh8b2f49b2001-06-08 00:21:52 +00002138
2139/*
2140** Create a new BTree in the same file. Write into *piTable the index
2141** of the root page of the new table.
2142*/
2143int sqliteBtreeCreateTable(Btree *pBt, int *piTable){
2144 MemPage *pRoot;
2145 Pgno pgnoRoot;
2146 int rc;
2147 if( !pBt->inTrans ){
2148 return SQLITE_ERROR; /* Must start a transaction first */
2149 }
2150 rc = allocatePage(pBt, &pRoot, &pgnoRoot);
2151 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002152 assert( sqlitepager_iswriteable(pRoot) );
drh8b2f49b2001-06-08 00:21:52 +00002153 zeroPage(pRoot);
2154 sqlitepager_unref(pRoot);
2155 *piTable = (int)pgnoRoot;
2156 return SQLITE_OK;
2157}
2158
2159/*
2160** Erase the given database page and all its children. Return
2161** the page to the freelist.
2162*/
drh2aa679f2001-06-25 02:11:07 +00002163static int clearDatabasePage(Btree *pBt, Pgno pgno, int freePageFlag){
drh8b2f49b2001-06-08 00:21:52 +00002164 MemPage *pPage;
2165 int rc;
drh8b2f49b2001-06-08 00:21:52 +00002166 Cell *pCell;
2167 int idx;
2168
drh8c42ca92001-06-22 19:15:00 +00002169 rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pPage);
drh8b2f49b2001-06-08 00:21:52 +00002170 if( rc ) return rc;
drh6019e162001-07-02 17:51:45 +00002171 rc = sqlitepager_write(pPage);
2172 if( rc ) return rc;
drh14acc042001-06-10 19:56:58 +00002173 idx = pPage->u.hdr.firstCell;
drh8b2f49b2001-06-08 00:21:52 +00002174 while( idx>0 ){
drh14acc042001-06-10 19:56:58 +00002175 pCell = (Cell*)&pPage->u.aDisk[idx];
drh8b2f49b2001-06-08 00:21:52 +00002176 idx = pCell->h.iNext;
2177 if( pCell->h.leftChild ){
drh2aa679f2001-06-25 02:11:07 +00002178 rc = clearDatabasePage(pBt, pCell->h.leftChild, 1);
drh8b2f49b2001-06-08 00:21:52 +00002179 if( rc ) return rc;
2180 }
drh8c42ca92001-06-22 19:15:00 +00002181 rc = clearCell(pBt, pCell);
drh8b2f49b2001-06-08 00:21:52 +00002182 if( rc ) return rc;
2183 }
drh2aa679f2001-06-25 02:11:07 +00002184 if( pPage->u.hdr.rightChild ){
2185 rc = clearDatabasePage(pBt, pPage->u.hdr.rightChild, 1);
2186 if( rc ) return rc;
2187 }
2188 if( freePageFlag ){
2189 rc = freePage(pBt, pPage, pgno);
2190 }else{
2191 zeroPage(pPage);
2192 }
drhdd793422001-06-28 01:54:48 +00002193 sqlitepager_unref(pPage);
drh2aa679f2001-06-25 02:11:07 +00002194 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002195}
2196
2197/*
2198** Delete all information from a single table in the database.
2199*/
2200int sqliteBtreeClearTable(Btree *pBt, int iTable){
2201 int rc;
2202 if( !pBt->inTrans ){
2203 return SQLITE_ERROR; /* Must start a transaction first */
2204 }
drh2aa679f2001-06-25 02:11:07 +00002205 rc = clearDatabasePage(pBt, (Pgno)iTable, 0);
drh8b2f49b2001-06-08 00:21:52 +00002206 if( rc ){
2207 sqliteBtreeRollback(pBt);
drh8b2f49b2001-06-08 00:21:52 +00002208 }
drh8c42ca92001-06-22 19:15:00 +00002209 return rc;
drh8b2f49b2001-06-08 00:21:52 +00002210}
2211
2212/*
2213** Erase all information in a table and add the root of the table to
2214** the freelist. Except, the root of the principle table (the one on
2215** page 2) is never added to the freelist.
2216*/
2217int sqliteBtreeDropTable(Btree *pBt, int iTable){
2218 int rc;
2219 MemPage *pPage;
2220 if( !pBt->inTrans ){
2221 return SQLITE_ERROR; /* Must start a transaction first */
2222 }
drh8c42ca92001-06-22 19:15:00 +00002223 rc = sqlitepager_get(pBt->pPager, (Pgno)iTable, (void**)&pPage);
drh2aa679f2001-06-25 02:11:07 +00002224 if( rc ) return rc;
2225 rc = sqliteBtreeClearTable(pBt, iTable);
2226 if( rc ) return rc;
2227 if( iTable>2 ){
2228 rc = freePage(pBt, pPage, iTable);
2229 }else{
2230 zeroPage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00002231 }
drhdd793422001-06-28 01:54:48 +00002232 sqlitepager_unref(pPage);
drh8b2f49b2001-06-08 00:21:52 +00002233 return rc;
2234}
2235
2236/*
2237** Read the meta-information out of a database file.
2238*/
2239int sqliteBtreeGetMeta(Btree *pBt, int *aMeta){
2240 PageOne *pP1;
2241 int rc;
2242
drh8c42ca92001-06-22 19:15:00 +00002243 rc = sqlitepager_get(pBt->pPager, 1, (void**)&pP1);
drh8b2f49b2001-06-08 00:21:52 +00002244 if( rc ) return rc;
drh2aa679f2001-06-25 02:11:07 +00002245 aMeta[0] = pP1->nFree;
2246 memcpy(&aMeta[1], pP1->aMeta, sizeof(pP1->aMeta));
drh8b2f49b2001-06-08 00:21:52 +00002247 sqlitepager_unref(pP1);
2248 return SQLITE_OK;
2249}
2250
2251/*
2252** Write meta-information back into the database.
2253*/
2254int sqliteBtreeUpdateMeta(Btree *pBt, int *aMeta){
2255 PageOne *pP1;
2256 int rc;
2257 if( !pBt->inTrans ){
2258 return SQLITE_ERROR; /* Must start a transaction first */
2259 }
2260 pP1 = pBt->page1;
2261 rc = sqlitepager_write(pP1);
drh2aa679f2001-06-25 02:11:07 +00002262 if( rc ) return rc;
2263 memcpy(pP1->aMeta, &aMeta[1], sizeof(pP1->aMeta));
drh8b2f49b2001-06-08 00:21:52 +00002264 return SQLITE_OK;
2265}
drh8c42ca92001-06-22 19:15:00 +00002266
drh5eddca62001-06-30 21:53:53 +00002267/******************************************************************************
2268** The complete implementation of the BTree subsystem is above this line.
2269** All the code the follows is for testing and troubleshooting the BTree
2270** subsystem. None of the code that follows is used during normal operation.
2271** All of the following code is omitted unless the library is compiled with
2272** the -DSQLITE_TEST=1 compiler option.
2273******************************************************************************/
drh5edc3122001-09-13 21:53:09 +00002274#if 1
drh5eddca62001-06-30 21:53:53 +00002275
drh8c42ca92001-06-22 19:15:00 +00002276/*
2277** Print a disassembly of the given page on standard output. This routine
2278** is used for debugging and testing only.
2279*/
drh6019e162001-07-02 17:51:45 +00002280int sqliteBtreePageDump(Btree *pBt, int pgno, int recursive){
drh8c42ca92001-06-22 19:15:00 +00002281 int rc;
2282 MemPage *pPage;
2283 int i, j;
2284 int nFree;
2285 u16 idx;
2286 char range[20];
2287 unsigned char payload[20];
2288 rc = sqlitepager_get(pBt->pPager, (Pgno)pgno, (void**)&pPage);
2289 if( rc ){
2290 return rc;
2291 }
drh6019e162001-07-02 17:51:45 +00002292 if( recursive ) printf("PAGE %d:\n", pgno);
drh8c42ca92001-06-22 19:15:00 +00002293 i = 0;
2294 idx = pPage->u.hdr.firstCell;
2295 while( idx>0 && idx<=SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2296 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
2297 int sz = cellSize(pCell);
2298 sprintf(range,"%d..%d", idx, idx+sz-1);
drh2aa679f2001-06-25 02:11:07 +00002299 sz = pCell->h.nKey + pCell->h.nData;
drh8c42ca92001-06-22 19:15:00 +00002300 if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
2301 memcpy(payload, pCell->aPayload, sz);
2302 for(j=0; j<sz; j++){
2303 if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
2304 }
2305 payload[sz] = 0;
2306 printf(
drh6019e162001-07-02 17:51:45 +00002307 "cell %2d: i=%-10s chld=%-4d nk=%-4d nd=%-4d payload=%s\n",
drh8c42ca92001-06-22 19:15:00 +00002308 i, range, (int)pCell->h.leftChild, pCell->h.nKey, pCell->h.nData,
drh2aa679f2001-06-25 02:11:07 +00002309 payload
drh8c42ca92001-06-22 19:15:00 +00002310 );
drh6019e162001-07-02 17:51:45 +00002311 if( pPage->isInit && pPage->apCell[i]!=pCell ){
drh2aa679f2001-06-25 02:11:07 +00002312 printf("**** apCell[%d] does not match on prior entry ****\n", i);
2313 }
drh7c717f72001-06-24 20:39:41 +00002314 i++;
drh8c42ca92001-06-22 19:15:00 +00002315 idx = pCell->h.iNext;
2316 }
2317 if( idx!=0 ){
2318 printf("ERROR: next cell index out of range: %d\n", idx);
2319 }
2320 printf("right_child: %d\n", pPage->u.hdr.rightChild);
2321 nFree = 0;
2322 i = 0;
2323 idx = pPage->u.hdr.firstFree;
2324 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2325 FreeBlk *p = (FreeBlk*)&pPage->u.aDisk[idx];
2326 sprintf(range,"%d..%d", idx, idx+p->iSize-1);
2327 nFree += p->iSize;
2328 printf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
2329 i, range, p->iSize, nFree);
2330 idx = p->iNext;
drh2aa679f2001-06-25 02:11:07 +00002331 i++;
drh8c42ca92001-06-22 19:15:00 +00002332 }
2333 if( idx!=0 ){
2334 printf("ERROR: next freeblock index out of range: %d\n", idx);
2335 }
drh6019e162001-07-02 17:51:45 +00002336 if( recursive && pPage->u.hdr.rightChild!=0 ){
2337 idx = pPage->u.hdr.firstCell;
2338 while( idx>0 && idx<SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
2339 Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
2340 sqliteBtreePageDump(pBt, pCell->h.leftChild, 1);
2341 idx = pCell->h.iNext;
2342 }
2343 sqliteBtreePageDump(pBt, pPage->u.hdr.rightChild, 1);
2344 }
drh8c42ca92001-06-22 19:15:00 +00002345 sqlitepager_unref(pPage);
2346 return SQLITE_OK;
2347}
drh8c42ca92001-06-22 19:15:00 +00002348
drh8c42ca92001-06-22 19:15:00 +00002349/*
drh2aa679f2001-06-25 02:11:07 +00002350** Fill aResult[] with information about the entry and page that the
2351** cursor is pointing to.
2352**
2353** aResult[0] = The page number
2354** aResult[1] = The entry number
2355** aResult[2] = Total number of entries on this page
2356** aResult[3] = Size of this entry
2357** aResult[4] = Number of free bytes on this page
2358** aResult[5] = Number of free blocks on the page
2359** aResult[6] = Page number of the left child of this entry
2360** aResult[7] = Page number of the right child for the whole page
drh5eddca62001-06-30 21:53:53 +00002361**
2362** This routine is used for testing and debugging only.
drh8c42ca92001-06-22 19:15:00 +00002363*/
2364int sqliteBtreeCursorDump(BtCursor *pCur, int *aResult){
drh2aa679f2001-06-25 02:11:07 +00002365 int cnt, idx;
2366 MemPage *pPage = pCur->pPage;
2367 aResult[0] = sqlitepager_pagenumber(pPage);
drh8c42ca92001-06-22 19:15:00 +00002368 aResult[1] = pCur->idx;
drh2aa679f2001-06-25 02:11:07 +00002369 aResult[2] = pPage->nCell;
2370 if( pCur->idx>=0 && pCur->idx<pPage->nCell ){
2371 aResult[3] = cellSize(pPage->apCell[pCur->idx]);
2372 aResult[6] = pPage->apCell[pCur->idx]->h.leftChild;
2373 }else{
2374 aResult[3] = 0;
2375 aResult[6] = 0;
2376 }
2377 aResult[4] = pPage->nFree;
2378 cnt = 0;
2379 idx = pPage->u.hdr.firstFree;
2380 while( idx>0 && idx<SQLITE_PAGE_SIZE ){
2381 cnt++;
2382 idx = ((FreeBlk*)&pPage->u.aDisk[idx])->iNext;
2383 }
2384 aResult[5] = cnt;
2385 aResult[7] = pPage->u.hdr.rightChild;
drh8c42ca92001-06-22 19:15:00 +00002386 return SQLITE_OK;
2387}
drhdd793422001-06-28 01:54:48 +00002388
drhdd793422001-06-28 01:54:48 +00002389/*
drh5eddca62001-06-30 21:53:53 +00002390** Return the pager associated with a BTree. This routine is used for
2391** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00002392*/
2393Pager *sqliteBtreePager(Btree *pBt){
2394 return pBt->pPager;
2395}
drh5eddca62001-06-30 21:53:53 +00002396
2397/*
2398** This structure is passed around through all the sanity checking routines
2399** in order to keep track of some global state information.
2400*/
2401typedef struct SanityCheck SanityCheck;
2402struct SanityCheck {
2403 Btree *pBt; // The tree being checked out
2404 Pager *pPager; // The associated pager. Also accessible by pBt->pPager
2405 int nPage; // Number of pages in the database
2406 int *anRef; // Number of times each page is referenced
drh6019e162001-07-02 17:51:45 +00002407 int nTreePage; // Number of BTree pages
2408 int nByte; // Number of bytes of data stored on BTree pages
drh5eddca62001-06-30 21:53:53 +00002409 char *zErrMsg; // An error message. NULL of no errors seen.
2410};
2411
2412/*
2413** Append a message to the error message string.
2414*/
2415static void checkAppendMsg(SanityCheck *pCheck, char *zMsg1, char *zMsg2){
2416 if( pCheck->zErrMsg ){
2417 char *zOld = pCheck->zErrMsg;
2418 pCheck->zErrMsg = 0;
2419 sqliteSetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, 0);
2420 sqliteFree(zOld);
2421 }else{
2422 sqliteSetString(&pCheck->zErrMsg, zMsg1, zMsg2, 0);
2423 }
2424}
2425
2426/*
2427** Add 1 to the reference count for page iPage. If this is the second
2428** reference to the page, add an error message to pCheck->zErrMsg.
2429** Return 1 if there are 2 ore more references to the page and 0 if
2430** if this is the first reference to the page.
2431**
2432** Also check that the page number is in bounds.
2433*/
2434static int checkRef(SanityCheck *pCheck, int iPage, char *zContext){
2435 if( iPage==0 ) return 1;
2436 if( iPage>pCheck->nPage ){
2437 char zBuf[100];
2438 sprintf(zBuf, "invalid page number %d", iPage);
2439 checkAppendMsg(pCheck, zContext, zBuf);
2440 return 1;
2441 }
2442 if( pCheck->anRef[iPage]==1 ){
2443 char zBuf[100];
2444 sprintf(zBuf, "2nd reference to page %d", iPage);
2445 checkAppendMsg(pCheck, zContext, zBuf);
2446 return 1;
2447 }
2448 return (pCheck->anRef[iPage]++)>1;
2449}
2450
2451/*
2452** Check the integrity of the freelist or of an overflow page list.
2453** Verify that the number of pages on the list is N.
2454*/
2455static void checkList(SanityCheck *pCheck, int iPage, int N, char *zContext){
2456 char zMsg[100];
2457 while( N-- ){
2458 OverflowPage *pOvfl;
2459 if( iPage<1 ){
2460 sprintf(zMsg, "%d pages missing from overflow list", N+1);
2461 checkAppendMsg(pCheck, zContext, zMsg);
2462 break;
2463 }
2464 if( checkRef(pCheck, iPage, zContext) ) break;
2465 if( sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
2466 sprintf(zMsg, "failed to get page %d", iPage);
2467 checkAppendMsg(pCheck, zContext, zMsg);
2468 break;
2469 }
2470 iPage = (int)pOvfl->iNext;
2471 sqlitepager_unref(pOvfl);
2472 }
2473}
2474
2475/*
2476** Do various sanity checks on a single page of a tree. Return
2477** the tree depth. Root pages return 0. Parents of root pages
2478** return 1, and so forth.
2479**
2480** These checks are done:
2481**
2482** 1. Make sure that cells and freeblocks do not overlap
2483** but combine to completely cover the page.
2484** 2. Make sure cell keys are in order.
2485** 3. Make sure no key is less than or equal to zLowerBound.
2486** 4. Make sure no key is greater than or equal to zUpperBound.
2487** 5. Check the integrity of overflow pages.
2488** 6. Recursively call checkTreePage on all children.
2489** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00002490** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00002491** the root of the tree.
2492*/
2493static int checkTreePage(
2494 SanityCheck *pCheck, /* Context for the sanity check */
2495 int iPage, /* Page number of the page to check */
2496 MemPage *pParent, /* Parent page */
2497 char *zParentContext, /* Parent context */
2498 char *zLowerBound, /* All keys should be greater than this, if not NULL */
2499 char *zUpperBound /* All keys should be less than this, if not NULL */
2500){
2501 MemPage *pPage;
2502 int i, rc, depth, d2, pgno;
2503 char *zKey1, *zKey2;
2504 BtCursor cur;
2505 char zMsg[100];
2506 char zContext[100];
2507 char hit[SQLITE_PAGE_SIZE];
2508
2509 /* Check that the page exists
2510 */
2511 if( iPage==0 ) return 0;
2512 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
2513 sprintf(zContext, "On tree page %d: ", iPage);
2514 if( (rc = sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pPage))!=0 ){
2515 sprintf(zMsg, "unable to get the page. error code=%d", rc);
2516 checkAppendMsg(pCheck, zContext, zMsg);
2517 return 0;
2518 }
2519 if( (rc = initPage(pPage, (Pgno)iPage, pParent))!=0 ){
2520 sprintf(zMsg, "initPage() returns error code %d", rc);
2521 checkAppendMsg(pCheck, zContext, zMsg);
2522 sqlitepager_unref(pPage);
2523 return 0;
2524 }
2525
2526 /* Check out all the cells.
2527 */
2528 depth = 0;
2529 zKey1 = zLowerBound ? sqliteStrDup(zLowerBound) : 0;
2530 cur.pPage = pPage;
2531 cur.pBt = pCheck->pBt;
2532 for(i=0; i<pPage->nCell; i++){
2533 Cell *pCell = pPage->apCell[i];
2534 int sz;
2535
2536 /* Check payload overflow pages
2537 */
2538 sz = pCell->h.nKey + pCell->h.nData;
2539 sprintf(zContext, "On page %d cell %d: ", iPage, i);
2540 if( sz>MX_LOCAL_PAYLOAD ){
2541 int nPage = (sz - MX_LOCAL_PAYLOAD + OVERFLOW_SIZE - 1)/OVERFLOW_SIZE;
2542 checkList(pCheck, pCell->ovfl, nPage, zContext);
2543 }
2544
2545 /* Check that keys are in the right order
2546 */
2547 cur.idx = i;
2548 zKey2 = sqliteMalloc( pCell->h.nKey+1 );
2549 getPayload(&cur, 0, pCell->h.nKey, zKey2);
2550 if( zKey1 && strcmp(zKey1,zKey2)>=0 ){
2551 checkAppendMsg(pCheck, zContext, "Key is out of order");
2552 }
2553
2554 /* Check sanity of left child page.
2555 */
2556 pgno = (int)pCell->h.leftChild;
2557 d2 = checkTreePage(pCheck, pgno, pPage, zContext, zKey1, zKey2);
2558 if( i>0 && d2!=depth ){
2559 checkAppendMsg(pCheck, zContext, "Child page depth differs");
2560 }
2561 depth = d2;
2562 sqliteFree(zKey1);
2563 zKey1 = zKey2;
2564 }
2565 pgno = pPage->u.hdr.rightChild;
2566 sprintf(zContext, "On page %d at right child: ", iPage);
2567 checkTreePage(pCheck, pgno, pPage, zContext, zKey1, zUpperBound);
2568 sqliteFree(zKey1);
2569
2570 /* Check for complete coverage of the page
2571 */
2572 memset(hit, 0, sizeof(hit));
2573 memset(hit, 1, sizeof(PageHdr));
2574 for(i=pPage->u.hdr.firstCell; i>0 && i<SQLITE_PAGE_SIZE; ){
2575 Cell *pCell = (Cell*)&pPage->u.aDisk[i];
2576 int j;
2577 for(j=i+cellSize(pCell)-1; j>=i; j--) hit[j]++;
2578 i = pCell->h.iNext;
2579 }
2580 for(i=pPage->u.hdr.firstFree; i>0 && i<SQLITE_PAGE_SIZE; ){
2581 FreeBlk *pFBlk = (FreeBlk*)&pPage->u.aDisk[i];
2582 int j;
2583 for(j=i+pFBlk->iSize-1; j>=i; j--) hit[j]++;
2584 i = pFBlk->iNext;
2585 }
2586 for(i=0; i<SQLITE_PAGE_SIZE; i++){
2587 if( hit[i]==0 ){
2588 sprintf(zMsg, "Unused space at byte %d of page %d", i, iPage);
2589 checkAppendMsg(pCheck, zMsg, 0);
2590 break;
2591 }else if( hit[i]>1 ){
2592 sprintf(zMsg, "Multiple uses for byte %d of page %d", i, iPage);
2593 checkAppendMsg(pCheck, zMsg, 0);
2594 break;
2595 }
2596 }
2597
2598 /* Check that free space is kept to a minimum
2599 */
drh6019e162001-07-02 17:51:45 +00002600#if 0
2601 if( pParent && pParent->nCell>2 && pPage->nFree>3*SQLITE_PAGE_SIZE/4 ){
drh5eddca62001-06-30 21:53:53 +00002602 sprintf(zMsg, "free space (%d) greater than max (%d)", pPage->nFree,
2603 SQLITE_PAGE_SIZE/3);
2604 checkAppendMsg(pCheck, zContext, zMsg);
2605 }
drh6019e162001-07-02 17:51:45 +00002606#endif
2607
2608 /* Update freespace totals.
2609 */
2610 pCheck->nTreePage++;
2611 pCheck->nByte += USABLE_SPACE - pPage->nFree;
drh5eddca62001-06-30 21:53:53 +00002612
2613 sqlitepager_unref(pPage);
2614 return depth;
2615}
2616
2617/*
2618** This routine does a complete check of the given BTree file. aRoot[] is
2619** an array of pages numbers were each page number is the root page of
2620** a table. nRoot is the number of entries in aRoot.
2621**
2622** If everything checks out, this routine returns NULL. If something is
2623** amiss, an error message is written into memory obtained from malloc()
2624** and a pointer to that error message is returned. The calling function
2625** is responsible for freeing the error message when it is done.
2626*/
2627char *sqliteBtreeSanityCheck(Btree *pBt, int *aRoot, int nRoot){
2628 int i;
2629 int nRef;
2630 SanityCheck sCheck;
2631
2632 nRef = *sqlitepager_stats(pBt->pPager);
drhefc251d2001-07-01 22:12:01 +00002633 if( lockBtree(pBt)!=SQLITE_OK ){
2634 return sqliteStrDup("Unable to acquire a read lock on the database");
2635 }
drh5eddca62001-06-30 21:53:53 +00002636 sCheck.pBt = pBt;
2637 sCheck.pPager = pBt->pPager;
2638 sCheck.nPage = sqlitepager_pagecount(sCheck.pPager);
2639 sCheck.anRef = sqliteMalloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
2640 sCheck.anRef[1] = 1;
2641 for(i=2; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
2642 sCheck.zErrMsg = 0;
2643
2644 /* Check the integrity of the freelist
2645 */
2646 checkList(&sCheck, pBt->page1->freeList, pBt->page1->nFree,"Main freelist: ");
2647
2648 /* Check all the tables.
2649 */
2650 for(i=0; i<nRoot; i++){
2651 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0, 0);
2652 }
2653
2654 /* Make sure every page in the file is referenced
2655 */
2656 for(i=1; i<=sCheck.nPage; i++){
2657 if( sCheck.anRef[i]==0 ){
2658 char zBuf[100];
2659 sprintf(zBuf, "Page %d is never used", i);
2660 checkAppendMsg(&sCheck, zBuf, 0);
2661 }
2662 }
2663
2664 /* Make sure this analysis did not leave any unref() pages
2665 */
drh5e00f6c2001-09-13 13:46:56 +00002666 unlockBtreeIfUnused(pBt);
drh5eddca62001-06-30 21:53:53 +00002667 if( nRef != *sqlitepager_stats(pBt->pPager) ){
2668 char zBuf[100];
2669 sprintf(zBuf,
2670 "Outstanding page count goes from %d to %d during this analysis",
2671 nRef, *sqlitepager_stats(pBt->pPager)
2672 );
2673 checkAppendMsg(&sCheck, zBuf, 0);
2674 }
2675
2676 /* Clean up and report errors.
2677 */
2678 sqliteFree(sCheck.anRef);
2679 return sCheck.zErrMsg;
2680}
2681
2682#endif /* SQLITE_TEST */