ds@1952: /* ds@1952: ** 2004 April 6 ds@1952: ** ds@1952: ** The author disclaims copyright to this source code. In place of ds@1952: ** a legal notice, here is a blessing: ds@1952: ** ds@1952: ** May you do good and not evil. ds@1952: ** May you find forgiveness for yourself and forgive others. ds@1952: ** May you share freely, never taking more than you give. ds@1952: ** ds@1952: ************************************************************************* ds@1952: ** $Id$ ds@1952: ** ds@1952: ** This file implements a external (disk-based) database using BTrees. ds@1952: ** For a detailed discussion of BTrees, refer to ds@1952: ** ds@1952: ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3: ds@1952: ** "Sorting And Searching", pages 473-480. Addison-Wesley ds@1952: ** Publishing Company, Reading, Massachusetts. ds@1952: ** ds@1952: ** The basic idea is that each page of the file contains N database ds@1952: ** entries and N+1 pointers to subpages. ds@1952: ** ds@1952: ** ---------------------------------------------------------------- ds@1952: ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) | ds@1952: ** ---------------------------------------------------------------- ds@1952: ** ds@1952: ** All of the keys on the page that Ptr(0) points to have values less ds@1952: ** than Key(0). All of the keys on page Ptr(1) and its subpages have ds@1952: ** values greater than Key(0) and less than Key(1). All of the keys ds@1952: ** on Ptr(N) and its subpages have values greater than Key(N-1). And ds@1952: ** so forth. ds@1952: ** ds@1952: ** Finding a particular key requires reading O(log(M)) pages from the ds@1952: ** disk where M is the number of entries in the tree. ds@1952: ** ds@1952: ** In this implementation, a single file can hold one or more separate ds@1952: ** BTrees. Each BTree is identified by the index of its root page. The ds@1952: ** key and data for any entry are combined to form the "payload". A ds@1952: ** fixed amount of payload can be carried directly on the database ds@1952: ** page. If the payload is larger than the preset amount then surplus ds@1952: ** bytes are stored on overflow pages. The payload for an entry ds@1952: ** and the preceding pointer are combined to form a "Cell". Each ds@1952: ** page has a small header which contains the Ptr(N) pointer and other ds@1952: ** information such as the size of key and data. ds@1952: ** ds@1952: ** FORMAT DETAILS ds@1952: ** ds@1952: ** The file is divided into pages. The first page is called page 1, ds@1952: ** the second is page 2, and so forth. A page number of zero indicates ds@1952: ** "no such page". The page size can be anything between 512 and 65536. ds@1952: ** Each page can be either a btree page, a freelist page or an overflow ds@1952: ** page. ds@1952: ** ds@1952: ** The first page is always a btree page. The first 100 bytes of the first ds@1952: ** page contain a special header (the "file header") that describes the file. ds@1952: ** The format of the file header is as follows: ds@1952: ** ds@1952: ** OFFSET SIZE DESCRIPTION ds@1952: ** 0 16 Header string: "SQLite format 3\000" ds@1952: ** 16 2 Page size in bytes. ds@1952: ** 18 1 File format write version ds@1952: ** 19 1 File format read version ds@1952: ** 20 1 Bytes of unused space at the end of each page ds@1952: ** 21 1 Max embedded payload fraction ds@1952: ** 22 1 Min embedded payload fraction ds@1952: ** 23 1 Min leaf payload fraction ds@1952: ** 24 4 File change counter ds@1952: ** 28 4 Reserved for future use ds@1952: ** 32 4 First freelist page ds@1952: ** 36 4 Number of freelist pages in the file ds@1952: ** 40 60 15 4-byte meta values passed to higher layers ds@1952: ** ds@1952: ** All of the integer values are big-endian (most significant byte first). ds@1952: ** ds@1952: ** The file change counter is incremented when the database is changed ds@1952: ** This counter allows other processes to know when the file has changed ds@1952: ** and thus when they need to flush their cache. ds@1952: ** ds@1952: ** The max embedded payload fraction is the amount of the total usable ds@1952: ** space in a page that can be consumed by a single cell for standard ds@1952: ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default ds@1952: ** is to limit the maximum cell size so that at least 4 cells will fit ds@1952: ** on one page. Thus the default max embedded payload fraction is 64. ds@1952: ** ds@1952: ** If the payload for a cell is larger than the max payload, then extra ds@1952: ** payload is spilled to overflow pages. Once an overflow page is allocated, ds@1952: ** as many bytes as possible are moved into the overflow pages without letting ds@1952: ** the cell size drop below the min embedded payload fraction. ds@1952: ** ds@1952: ** The min leaf payload fraction is like the min embedded payload fraction ds@1952: ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum ds@1952: ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it ds@1952: ** not specified in the header. ds@1952: ** ds@1952: ** Each btree pages is divided into three sections: The header, the ds@1952: ** cell pointer array, and the cell content area. Page 1 also has a 100-byte ds@1952: ** file header that occurs before the page header. ds@1952: ** ds@1952: ** |----------------| ds@1952: ** | file header | 100 bytes. Page 1 only. ds@1952: ** |----------------| ds@1952: ** | page header | 8 bytes for leaves. 12 bytes for interior nodes ds@1952: ** |----------------| ds@1952: ** | cell pointer | | 2 bytes per cell. Sorted order. ds@1952: ** | array | | Grows downward ds@1952: ** | | v ds@1952: ** |----------------| ds@1952: ** | unallocated | ds@1952: ** | space | ds@1952: ** |----------------| ^ Grows upwards ds@1952: ** | cell content | | Arbitrary order interspersed with freeblocks. ds@1952: ** | area | | and free space fragments. ds@1952: ** |----------------| ds@1952: ** ds@1952: ** The page headers looks like this: ds@1952: ** ds@1952: ** OFFSET SIZE DESCRIPTION ds@1952: ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf ds@1952: ** 1 2 byte offset to the first freeblock ds@1952: ** 3 2 number of cells on this page ds@1952: ** 5 2 first byte of the cell content area ds@1952: ** 7 1 number of fragmented free bytes ds@1952: ** 8 4 Right child (the Ptr(N) value). Omitted on leaves. ds@1952: ** ds@1952: ** The flags define the format of this btree page. The leaf flag means that ds@1952: ** this page has no children. The zerodata flag means that this page carries ds@1952: ** only keys and no data. The intkey flag means that the key is a integer ds@1952: ** which is stored in the key size entry of the cell header rather than in ds@1952: ** the payload area. ds@1952: ** ds@1952: ** The cell pointer array begins on the first byte after the page header. ds@1952: ** The cell pointer array contains zero or more 2-byte numbers which are ds@1952: ** offsets from the beginning of the page to the cell content in the cell ds@1952: ** content area. The cell pointers occur in sorted order. The system strives ds@1952: ** to keep free space after the last cell pointer so that new cells can ds@1952: ** be easily added without having to defragment the page. ds@1952: ** ds@1952: ** Cell content is stored at the very end of the page and grows toward the ds@1952: ** beginning of the page. ds@1952: ** ds@1952: ** Unused space within the cell content area is collected into a linked list of ds@1952: ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset ds@1952: ** to the first freeblock is given in the header. Freeblocks occur in ds@1952: ** increasing order. Because a freeblock must be at least 4 bytes in size, ds@1952: ** any group of 3 or fewer unused bytes in the cell content area cannot ds@1952: ** exist on the freeblock chain. A group of 3 or fewer free bytes is called ds@1952: ** a fragment. The total number of bytes in all fragments is recorded. ds@1952: ** in the page header at offset 7. ds@1952: ** ds@1952: ** SIZE DESCRIPTION ds@1952: ** 2 Byte offset of the next freeblock ds@1952: ** 2 Bytes in this freeblock ds@1952: ** ds@1952: ** Cells are of variable length. Cells are stored in the cell content area at ds@1952: ** the end of the page. Pointers to the cells are in the cell pointer array ds@1952: ** that immediately follows the page header. Cells is not necessarily ds@1952: ** contiguous or in order, but cell pointers are contiguous and in order. ds@1952: ** ds@1952: ** Cell content makes use of variable length integers. A variable ds@1952: ** length integer is 1 to 9 bytes where the lower 7 bits of each ds@1952: ** byte are used. The integer consists of all bytes that have bit 8 set and ds@1952: ** the first byte with bit 8 clear. The most significant byte of the integer ds@1952: ** appears first. A variable-length integer may not be more than 9 bytes long. ds@1952: ** As a special case, all 8 bytes of the 9th byte are used as data. This ds@1952: ** allows a 64-bit integer to be encoded in 9 bytes. ds@1952: ** ds@1952: ** 0x00 becomes 0x00000000 ds@1952: ** 0x7f becomes 0x0000007f ds@1952: ** 0x81 0x00 becomes 0x00000080 ds@1952: ** 0x82 0x00 becomes 0x00000100 ds@1952: ** 0x80 0x7f becomes 0x0000007f ds@1952: ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678 ds@1952: ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081 ds@1952: ** ds@1952: ** Variable length integers are used for rowids and to hold the number of ds@1952: ** bytes of key and data in a btree cell. ds@1952: ** ds@1952: ** The content of a cell looks like this: ds@1952: ** ds@1952: ** SIZE DESCRIPTION ds@1952: ** 4 Page number of the left child. Omitted if leaf flag is set. ds@1952: ** var Number of bytes of data. Omitted if the zerodata flag is set. ds@1952: ** var Number of bytes of key. Or the key itself if intkey flag is set. ds@1952: ** * Payload ds@1952: ** 4 First page of the overflow chain. Omitted if no overflow ds@1952: ** ds@1952: ** Overflow pages form a linked list. Each page except the last is completely ds@1952: ** filled with data (pagesize - 4 bytes). The last page can have as little ds@1952: ** as 1 byte of data. ds@1952: ** ds@1952: ** SIZE DESCRIPTION ds@1952: ** 4 Page number of next overflow page ds@1952: ** * Data ds@1952: ** ds@1952: ** Freelist pages come in two subtypes: trunk pages and leaf pages. The ds@1952: ** file header points to the first in a linked list of trunk page. Each trunk ds@1952: ** page points to multiple leaf pages. The content of a leaf page is ds@1952: ** unspecified. A trunk page looks like this: ds@1952: ** ds@1952: ** SIZE DESCRIPTION ds@1952: ** 4 Page number of next trunk page ds@1952: ** 4 Number of leaf pointers on this page ds@1952: ** * zero or more pages numbers of leaves ds@1952: */ ds@1952: #include "sqliteInt.h" ds@1952: #include "pager.h" ds@1952: #include "btree.h" ds@1952: #include "os.h" ds@1952: #include ds@1952: ds@1952: /* Round up a number to the next larger multiple of 8. This is used ds@1952: ** to force 8-byte alignment on 64-bit architectures. ds@1952: */ ds@1952: #define ROUND8(x) ((x+7)&~7) ds@1952: ds@1952: ds@1952: /* The following value is the maximum cell size assuming a maximum page ds@1952: ** size give above. ds@1952: */ ds@1952: #define MX_CELL_SIZE(pBt) (pBt->pageSize-8) ds@1952: ds@1952: /* The maximum number of cells on a single page of the database. This ds@1952: ** assumes a minimum cell size of 3 bytes. Such small cells will be ds@1952: ** exceedingly rare, but they are possible. ds@1952: */ ds@1952: #define MX_CELL(pBt) ((pBt->pageSize-8)/3) ds@1952: ds@1952: /* Forward declarations */ ds@1952: typedef struct MemPage MemPage; ds@1952: typedef struct BtLock BtLock; ds@1952: ds@1952: /* ds@1952: ** This is a magic string that appears at the beginning of every ds@1952: ** SQLite database in order to identify the file as a real database. ds@1952: ** ds@1952: ** You can change this value at compile-time by specifying a ds@1952: ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The ds@1952: ** header must be exactly 16 bytes including the zero-terminator so ds@1952: ** the string itself should be 15 characters long. If you change ds@1952: ** the header, then your custom library will not be able to read ds@1952: ** databases generated by the standard tools and the standard tools ds@1952: ** will not be able to read databases created by your custom library. ds@1952: */ ds@1952: #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */ ds@1952: # define SQLITE_FILE_HEADER "SQLite format 3" ds@1952: #endif ds@1952: ds@1952: /* ds@1952: ** Page type flags. An ORed combination of these flags appear as the ds@1952: ** first byte of on-disk image of every BTree page. ds@1952: */ ds@1952: #define PTF_INTKEY 0x01 ds@1952: #define PTF_ZERODATA 0x02 ds@1952: #define PTF_LEAFDATA 0x04 ds@1952: #define PTF_LEAF 0x08 ds@1952: ds@1952: /* ds@1952: ** As each page of the file is loaded into memory, an instance of the following ds@1952: ** structure is appended and initialized to zero. This structure stores ds@1952: ** information about the page that is decoded from the raw file page. ds@1952: ** ds@1952: ** The pParent field points back to the parent page. This allows us to ds@1952: ** walk up the BTree from any leaf to the root. Care must be taken to ds@1952: ** unref() the parent page pointer when this page is no longer referenced. ds@1952: ** The pageDestructor() routine handles that chore. ds@1952: ** ds@1952: ** Access to all fields of this structure is controlled by the mutex ds@1952: ** stored in MemPage.pBt->mutex. ds@1952: */ ds@1952: struct MemPage { ds@1952: u8 isInit; /* True if previously initialized. MUST BE FIRST! */ ds@1952: u8 idxShift; /* True if Cell indices have changed */ ds@1952: u8 nOverflow; /* Number of overflow cell bodies in aCell[] */ ds@1952: u8 intKey; /* True if intkey flag is set */ ds@1952: u8 leaf; /* True if leaf flag is set */ ds@1952: u8 zeroData; /* True if table stores keys only */ ds@1952: u8 leafData; /* True if tables stores data on leaves only */ ds@1952: u8 hasData; /* True if this page stores data */ ds@1952: u8 hdrOffset; /* 100 for page 1. 0 otherwise */ ds@1952: u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */ ds@1952: u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */ ds@1952: u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */ ds@1952: u16 cellOffset; /* Index in aData of first cell pointer */ ds@1952: u16 idxParent; /* Index in parent of this node */ ds@1952: u16 nFree; /* Number of free bytes on the page */ ds@1952: u16 nCell; /* Number of cells on this page, local and ovfl */ ds@1952: struct _OvflCell { /* Cells that will not fit on aData[] */ ds@1952: u8 *pCell; /* Pointers to the body of the overflow cell */ ds@1952: u16 idx; /* Insert this cell before idx-th non-overflow cell */ ds@1952: } aOvfl[5]; ds@1952: BtShared *pBt; /* Pointer to BtShared that this page is part of */ ds@1952: u8 *aData; /* Pointer to disk image of the page data */ ds@1952: DbPage *pDbPage; /* Pager page handle */ ds@1952: Pgno pgno; /* Page number for this page */ ds@1952: MemPage *pParent; /* The parent of this page. NULL for root */ ds@1952: }; ds@1952: ds@1952: /* ds@1952: ** The in-memory image of a disk page has the auxiliary information appended ds@1952: ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold ds@1952: ** that extra information. ds@1952: */ ds@1952: #define EXTRA_SIZE sizeof(MemPage) ds@1952: ds@1952: /* A Btree handle ds@1952: ** ds@1952: ** A database connection contains a pointer to an instance of ds@1952: ** this object for every database file that it has open. This structure ds@1952: ** is opaque to the database connection. The database connection cannot ds@1952: ** see the internals of this structure and only deals with pointers to ds@1952: ** this structure. ds@1952: ** ds@1952: ** For some database files, the same underlying database cache might be ds@1952: ** shared between multiple connections. In that case, each contection ds@1952: ** has it own pointer to this object. But each instance of this object ds@1952: ** points to the same BtShared object. The database cache and the ds@1952: ** schema associated with the database file are all contained within ds@1952: ** the BtShared object. ds@1952: ** ds@1952: ** All fields in this structure are accessed under sqlite3.mutex. ds@1952: ** The pBt pointer itself may not be changed while there exists cursors ds@1952: ** in the referenced BtShared that point back to this Btree since those ds@1952: ** cursors have to do go through this Btree to find their BtShared and ds@1952: ** they often do so without holding sqlite3.mutex. ds@1952: */ ds@1952: struct Btree { ds@1952: sqlite3 *pSqlite; /* The database connection holding this btree */ ds@1952: BtShared *pBt; /* Sharable content of this btree */ ds@1952: u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */ ds@1952: u8 sharable; /* True if we can share pBt with other pSqlite */ ds@1952: u8 locked; /* True if pSqlite currently has pBt locked */ ds@1952: int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */ ds@1952: Btree *pNext; /* List of other sharable Btrees from the same pSqlite */ ds@1952: Btree *pPrev; /* Back pointer of the same list */ ds@1952: }; ds@1952: ds@1952: /* ds@1952: ** Btree.inTrans may take one of the following values. ds@1952: ** ds@1952: ** If the shared-data extension is enabled, there may be multiple users ds@1952: ** of the Btree structure. At most one of these may open a write transaction, ds@1952: ** but any number may have active read transactions. ds@1952: */ ds@1952: #define TRANS_NONE 0 ds@1952: #define TRANS_READ 1 ds@1952: #define TRANS_WRITE 2 ds@1952: ds@1952: /* ds@1952: ** An instance of this object represents a single database file. ds@1952: ** ds@1952: ** A single database file can be in use as the same time by two ds@1952: ** or more database connections. When two or more connections are ds@1952: ** sharing the same database file, each connection has it own ds@1952: ** private Btree object for the file and each of those Btrees points ds@1952: ** to this one BtShared object. BtShared.nRef is the number of ds@1952: ** connections currently sharing this database file. ds@1952: ** ds@1952: ** Fields in this structure are accessed under the BtShared.mutex ds@1952: ** mutex, except for nRef and pNext which are accessed under the ds@1952: ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field ds@1952: ** may not be modified once it is initially set as long as nRef>0. ds@1952: ** The pSchema field may be set once under BtShared.mutex and ds@1952: ** thereafter is unchanged as long as nRef>0. ds@1952: */ ds@1952: struct BtShared { ds@1952: Pager *pPager; /* The page cache */ ds@1952: BtCursor *pCursor; /* A list of all open cursors */ ds@1952: MemPage *pPage1; /* First page of the database */ ds@1952: u8 inStmt; /* True if we are in a statement subtransaction */ ds@1952: u8 readOnly; /* True if the underlying file is readonly */ ds@1952: u8 maxEmbedFrac; /* Maximum payload as % of total page size */ ds@1952: u8 minEmbedFrac; /* Minimum payload as % of total page size */ ds@1952: u8 minLeafFrac; /* Minimum leaf payload as % of total page size */ ds@1952: u8 pageSizeFixed; /* True if the page size can no longer be changed */ ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: u8 autoVacuum; /* True if auto-vacuum is enabled */ ds@1952: u8 incrVacuum; /* True if incr-vacuum is enabled */ ds@1952: Pgno nTrunc; /* Non-zero if the db will be truncated (incr vacuum) */ ds@1952: #endif ds@1952: u16 pageSize; /* Total number of bytes on a page */ ds@1952: u16 usableSize; /* Number of usable bytes on each page */ ds@1952: int maxLocal; /* Maximum local payload in non-LEAFDATA tables */ ds@1952: int minLocal; /* Minimum local payload in non-LEAFDATA tables */ ds@1952: int maxLeaf; /* Maximum local payload in a LEAFDATA table */ ds@1952: int minLeaf; /* Minimum local payload in a LEAFDATA table */ ds@1952: BusyHandler *pBusyHandler; /* Callback for when there is lock contention */ ds@1952: u8 inTransaction; /* Transaction state */ ds@1952: int nTransaction; /* Number of open transactions (read + write) */ ds@1952: void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */ ds@1952: void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */ ds@1952: sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */ ds@1952: #ifndef SQLITE_OMIT_SHARED_CACHE ds@1952: int nRef; /* Number of references to this structure */ ds@1952: BtShared *pNext; /* Next on a list of sharable BtShared structs */ ds@1952: BtLock *pLock; /* List of locks held on this shared-btree struct */ ds@1952: #endif ds@1952: }; ds@1952: ds@1952: /* ds@1952: ** An instance of the following structure is used to hold information ds@1952: ** about a cell. The parseCellPtr() function fills in this structure ds@1952: ** based on information extract from the raw disk page. ds@1952: */ ds@1952: typedef struct CellInfo CellInfo; ds@1952: struct CellInfo { ds@1952: u8 *pCell; /* Pointer to the start of cell content */ ds@1952: i64 nKey; /* The key for INTKEY tables, or number of bytes in key */ ds@1952: u32 nData; /* Number of bytes of data */ ds@1952: u32 nPayload; /* Total amount of payload */ ds@1952: u16 nHeader; /* Size of the cell content header in bytes */ ds@1952: u16 nLocal; /* Amount of payload held locally */ ds@1952: u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */ ds@1952: u16 nSize; /* Size of the cell content on the main b-tree page */ ds@1952: }; ds@1952: ds@1952: /* ds@1952: ** A cursor is a pointer to a particular entry within a particular ds@1952: ** b-tree within a database file. ds@1952: ** ds@1952: ** The entry is identified by its MemPage and the index in ds@1952: ** MemPage.aCell[] of the entry. ds@1952: ** ds@1952: ** When a single database file can shared by two more database connections, ds@1952: ** but cursors cannot be shared. Each cursor is associated with a ds@1952: ** particular database connection identified BtCursor.pBtree.pSqlite. ds@1952: ** ds@1952: ** Fields in this structure are accessed under the BtShared.mutex ds@1952: ** found at self->pBt->mutex. ds@1952: */ ds@1952: struct BtCursor { ds@1952: Btree *pBtree; /* The Btree to which this cursor belongs */ ds@1952: BtShared *pBt; /* The BtShared this cursor points to */ ds@1952: BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */ ds@1952: int (*xCompare)(void*,int,const void*,int,const void*); /* Key comp func */ ds@1952: void *pArg; /* First arg to xCompare() */ ds@1952: Pgno pgnoRoot; /* The root page of this tree */ ds@1952: MemPage *pPage; /* Page that contains the entry */ ds@1952: int idx; /* Index of the entry in pPage->aCell[] */ ds@1952: CellInfo info; /* A parse of the cell we are pointing at */ ds@1952: u8 wrFlag; /* True if writable */ ds@1952: u8 eState; /* One of the CURSOR_XXX constants (see below) */ ds@1952: void *pKey; /* Saved key that was cursor's last known position */ ds@1952: i64 nKey; /* Size of pKey, or last integer key */ ds@1952: int skip; /* (skip<0) -> Prev() is a no-op. (skip>0) -> Next() is */ ds@1952: #ifndef SQLITE_OMIT_INCRBLOB ds@1952: u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */ ds@1952: Pgno *aOverflow; /* Cache of overflow page locations */ ds@1952: #endif ds@1952: }; ds@1952: ds@1952: /* ds@1952: ** Potential values for BtCursor.eState. ds@1952: ** ds@1952: ** CURSOR_VALID: ds@1952: ** Cursor points to a valid entry. getPayload() etc. may be called. ds@1952: ** ds@1952: ** CURSOR_INVALID: ds@1952: ** Cursor does not point to a valid entry. This can happen (for example) ds@1952: ** because the table is empty or because BtreeCursorFirst() has not been ds@1952: ** called. ds@1952: ** ds@1952: ** CURSOR_REQUIRESEEK: ds@1952: ** The table that this cursor was opened on still exists, but has been ds@1952: ** modified since the cursor was last used. The cursor position is saved ds@1952: ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in ds@1952: ** this state, restoreOrClearCursorPosition() can be called to attempt to ds@1952: ** seek the cursor to the saved position. ds@1952: ** ds@1952: ** CURSOR_FAULT: ds@1952: ** A unrecoverable error (an I/O error or a malloc failure) has occurred ds@1952: ** on a different connection that shares the BtShared cache with this ds@1952: ** cursor. The error has left the cache in an inconsistent state. ds@1952: ** Do nothing else with this cursor. Any attempt to use the cursor ds@1952: ** should return the error code stored in BtCursor.skip ds@1952: */ ds@1952: #define CURSOR_INVALID 0 ds@1952: #define CURSOR_VALID 1 ds@1952: #define CURSOR_REQUIRESEEK 2 ds@1952: #define CURSOR_FAULT 3 ds@1952: ds@1952: /* ds@1952: ** The TRACE macro will print high-level status information about the ds@1952: ** btree operation when the global variable sqlite3_btree_trace is ds@1952: ** enabled. ds@1952: */ ds@1952: #if SQLITE_TEST ds@1952: # define TRACE(X) if( sqlite3_btree_trace ){ printf X; fflush(stdout); } ds@1952: #else ds@1952: # define TRACE(X) ds@1952: #endif ds@1952: ds@1952: /* ds@1952: ** Routines to read and write variable-length integers. These used to ds@1952: ** be defined locally, but now we use the varint routines in the util.c ds@1952: ** file. ds@1952: */ ds@1952: #define getVarint sqlite3GetVarint ds@1952: #define getVarint32(A,B) ((*B=*(A))<=0x7f?1:sqlite3GetVarint32(A,B)) ds@1952: #define putVarint sqlite3PutVarint ds@1952: ds@1952: /* The database page the PENDING_BYTE occupies. This page is never used. ds@1952: ** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They ds@1952: ** should possibly be consolidated (presumably in pager.h). ds@1952: ** ds@1952: ** If disk I/O is omitted (meaning that the database is stored purely ds@1952: ** in memory) then there is no pending byte. ds@1952: */ ds@1952: #ifdef SQLITE_OMIT_DISKIO ds@1952: # define PENDING_BYTE_PAGE(pBt) 0x7fffffff ds@1952: #else ds@1952: # define PENDING_BYTE_PAGE(pBt) ((PENDING_BYTE/(pBt)->pageSize)+1) ds@1952: #endif ds@1952: ds@1952: /* ds@1952: ** A linked list of the following structures is stored at BtShared.pLock. ds@1952: ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor ds@1952: ** is opened on the table with root page BtShared.iTable. Locks are removed ds@1952: ** from this list when a transaction is committed or rolled back, or when ds@1952: ** a btree handle is closed. ds@1952: */ ds@1952: struct BtLock { ds@1952: Btree *pBtree; /* Btree handle holding this lock */ ds@1952: Pgno iTable; /* Root page of table */ ds@1952: u8 eLock; /* READ_LOCK or WRITE_LOCK */ ds@1952: BtLock *pNext; /* Next in BtShared.pLock list */ ds@1952: }; ds@1952: ds@1952: /* Candidate values for BtLock.eLock */ ds@1952: #define READ_LOCK 1 ds@1952: #define WRITE_LOCK 2 ds@1952: ds@1952: /* ds@1952: ** These macros define the location of the pointer-map entry for a ds@1952: ** database page. The first argument to each is the number of usable ds@1952: ** bytes on each page of the database (often 1024). The second is the ds@1952: ** page number to look up in the pointer map. ds@1952: ** ds@1952: ** PTRMAP_PAGENO returns the database page number of the pointer-map ds@1952: ** page that stores the required pointer. PTRMAP_PTROFFSET returns ds@1952: ** the offset of the requested map entry. ds@1952: ** ds@1952: ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page, ds@1952: ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be ds@1952: ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements ds@1952: ** this test. ds@1952: */ ds@1952: #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno) ds@1952: #define PTRMAP_PTROFFSET(pBt, pgno) (5*(pgno-ptrmapPageno(pBt, pgno)-1)) ds@1952: #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno)) ds@1952: ds@1952: /* ds@1952: ** The pointer map is a lookup table that identifies the parent page for ds@1952: ** each child page in the database file. The parent page is the page that ds@1952: ** contains a pointer to the child. Every page in the database contains ds@1952: ** 0 or 1 parent pages. (In this context 'database page' refers ds@1952: ** to any page that is not part of the pointer map itself.) Each pointer map ds@1952: ** entry consists of a single byte 'type' and a 4 byte parent page number. ds@1952: ** The PTRMAP_XXX identifiers below are the valid types. ds@1952: ** ds@1952: ** The purpose of the pointer map is to facility moving pages from one ds@1952: ** position in the file to another as part of autovacuum. When a page ds@1952: ** is moved, the pointer in its parent must be updated to point to the ds@1952: ** new location. The pointer map is used to locate the parent page quickly. ds@1952: ** ds@1952: ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not ds@1952: ** used in this case. ds@1952: ** ds@1952: ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number ds@1952: ** is not used in this case. ds@1952: ** ds@1952: ** PTRMAP_OVERFLOW1: The database page is the first page in a list of ds@1952: ** overflow pages. The page number identifies the page that ds@1952: ** contains the cell with a pointer to this overflow page. ds@1952: ** ds@1952: ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of ds@1952: ** overflow pages. The page-number identifies the previous ds@1952: ** page in the overflow page list. ds@1952: ** ds@1952: ** PTRMAP_BTREE: The database page is a non-root btree page. The page number ds@1952: ** identifies the parent page in the btree. ds@1952: */ ds@1952: #define PTRMAP_ROOTPAGE 1 ds@1952: #define PTRMAP_FREEPAGE 2 ds@1952: #define PTRMAP_OVERFLOW1 3 ds@1952: #define PTRMAP_OVERFLOW2 4 ds@1952: #define PTRMAP_BTREE 5 ds@1952: ds@1952: /* A bunch of assert() statements to check the transaction state variables ds@1952: ** of handle p (type Btree*) are internally consistent. ds@1952: */ ds@1952: #define btreeIntegrity(p) \ ds@1952: assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \ ds@1952: assert( p->pBt->inTransaction>=p->inTrans ); ds@1952: ds@1952: ds@1952: /* ds@1952: ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine ds@1952: ** if the database supports auto-vacuum or not. Because it is used ds@1952: ** within an expression that is an argument to another macro ds@1952: ** (sqliteMallocRaw), it is not possible to use conditional compilation. ds@1952: ** So, this macro is defined instead. ds@1952: */ ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: #define ISAUTOVACUUM (pBt->autoVacuum) ds@1952: #else ds@1952: #define ISAUTOVACUUM 0 ds@1952: #endif ds@1952: ds@1952: ds@1952: /* ds@1952: ** This structure is passed around through all the sanity checking routines ds@1952: ** in order to keep track of some global state information. ds@1952: */ ds@1952: typedef struct IntegrityCk IntegrityCk; ds@1952: struct IntegrityCk { ds@1952: BtShared *pBt; /* The tree being checked out */ ds@1952: Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */ ds@1952: int nPage; /* Number of pages in the database */ ds@1952: int *anRef; /* Number of times each page is referenced */ ds@1952: int mxErr; /* Stop accumulating errors when this reaches zero */ ds@1952: char *zErrMsg; /* An error message. NULL if no errors seen. */ ds@1952: int nErr; /* Number of messages written to zErrMsg so far */ ds@1952: }; ds@1952: ds@1952: /* ds@1952: ** Read or write a two- and four-byte big-endian integer values. ds@1952: */ ds@1952: #define get2byte(x) ((x)[0]<<8 | (x)[1]) ds@1952: #define put2byte(p,v) ((p)[0] = (v)>>8, (p)[1] = (v)) ds@1952: #define get4byte sqlite3Get4byte ds@1952: #define put4byte sqlite3Put4byte ds@1952: ds@1952: /* ds@1952: ** Internal routines that should be accessed by the btree layer only. ds@1952: */ ds@1952: int sqlite3BtreeGetPage(BtShared*, Pgno, MemPage**, int); ds@1952: int sqlite3BtreeInitPage(MemPage *pPage, MemPage *pParent); ds@1952: void sqlite3BtreeParseCellPtr(MemPage*, u8*, CellInfo*); ds@1952: void sqlite3BtreeParseCell(MemPage*, int, CellInfo*); ds@1952: #ifdef SQLITE_TEST ds@1952: u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell); ds@1952: #endif ds@1952: int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur); ds@1952: void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur); ds@1952: void sqlite3BtreeReleaseTempCursor(BtCursor *pCur); ds@1952: int sqlite3BtreeIsRootPage(MemPage *pPage); ds@1952: void sqlite3BtreeMoveToParent(BtCursor *pCur);