]> granicus.if.org Git - php/commitdiff
Bundle relevant parts of sqlite 2.8.0.
authorWez Furlong <wez@php.net>
Thu, 17 Apr 2003 11:27:30 +0000 (11:27 +0000)
committerWez Furlong <wez@php.net>
Thu, 17 Apr 2003 11:27:30 +0000 (11:27 +0000)
# sqlite has a completely non-restrictive license

36 files changed:
ext/sqlite/libsqlite/README [new file with mode: 0644]
ext/sqlite/libsqlite/VERSION [new file with mode: 0644]
ext/sqlite/libsqlite/src/auth.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/btree.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/btree.h [new file with mode: 0644]
ext/sqlite/libsqlite/src/build.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/delete.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/encode.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/expr.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/func.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/hash.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/hash.h [new file with mode: 0644]
ext/sqlite/libsqlite/src/insert.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/main.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/opcodes.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/opcodes.h [new file with mode: 0644]
ext/sqlite/libsqlite/src/os.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/os.h [new file with mode: 0644]
ext/sqlite/libsqlite/src/pager.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/pager.h [new file with mode: 0644]
ext/sqlite/libsqlite/src/parse.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/parse.h [new file with mode: 0644]
ext/sqlite/libsqlite/src/parse.y [new file with mode: 0644]
ext/sqlite/libsqlite/src/printf.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/random.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/select.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/sqlite.h.in [new file with mode: 0644]
ext/sqlite/libsqlite/src/sqliteInt.h [new file with mode: 0644]
ext/sqlite/libsqlite/src/table.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/tokenize.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/trigger.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/update.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/util.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/vdbe.c [new file with mode: 0644]
ext/sqlite/libsqlite/src/vdbe.h [new file with mode: 0644]
ext/sqlite/libsqlite/src/where.c [new file with mode: 0644]

diff --git a/ext/sqlite/libsqlite/README b/ext/sqlite/libsqlite/README
new file mode 100644 (file)
index 0000000..326f3aa
--- /dev/null
@@ -0,0 +1,37 @@
+This directory contains source code to 
+
+    SQLite: An Embeddable SQL Database Engine
+
+To compile the project, first create a directory in which to place
+the build products.  It is recommended, but not required, that the
+build directory be separate from the source directory.  Cd into the
+build directory and then from the build directory run the configure
+script found at the root of the source tree.  Then run "make".
+
+For example:
+
+    tar xzf sqlite.tar.gz    ;#  Unpack the source tree into "sqlite"
+    mkdir bld                ;#  Build will occur in a sibling directory
+    cd bld                   ;#  Change to the build directory
+    ../sqlite/configure      ;#  Run the configure script
+    make                     ;#  Run the makefile.
+
+The configure script uses autoconf 2.50 and libtool.  If the configure
+script does not work out for you, there is a generic makefile named
+"Makefile.linux-gcc" in the top directory of the source tree that you
+can copy and edit to suite your needs.  Comments on the generic makefile
+show what changes are needed.
+
+The linux binaries on the website are created using the generic makefile,
+not the configure script.  The configure script is unmaintained.  (You
+can volunteer to take over maintenance of the configure script, if you want!)
+The windows binaries on the website are created using MinGW32 configured
+as a cross-compiler running under Linux.  For details, see the ./publish.sh
+script at the top-level of the source tree.
+
+Contacts:
+
+   http://www.sqlite.org/
+   http://www.hwaci.com/sw/sqlite/
+   http://groups.yahoo.com/group/sqlite/
+   drh@hwaci.com
diff --git a/ext/sqlite/libsqlite/VERSION b/ext/sqlite/libsqlite/VERSION
new file mode 100644 (file)
index 0000000..834f262
--- /dev/null
@@ -0,0 +1 @@
+2.8.0
diff --git a/ext/sqlite/libsqlite/src/auth.c b/ext/sqlite/libsqlite/src/auth.c
new file mode 100644 (file)
index 0000000..76518e7
--- /dev/null
@@ -0,0 +1,152 @@
+/*
+** 2003 January 11
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains code used to implement the sqlite_set_authorizer()
+** API.  This facility is an optional feature of the library.  Embedded
+** systems that do not need this facility may omit it by recompiling
+** the library with -DSQLITE_OMIT_AUTHORIZATION=1
+**
+** $Id$
+*/
+#include "sqliteInt.h"
+
+/*
+** All of the code in this file may be omitted by defining a single
+** macro.
+*/
+#ifndef SQLITE_OMIT_AUTHORIZATION
+
+/*
+** Set or clear the access authorization function.
+**
+** The access authorization function is be called during the compilation
+** phase to verify that the user has read and/or write access permission
+** various fields of the database.  The first argument to the auth function
+** is a copy of the 3rd argument to this routine.  The second argument
+** to the auth function is one of these constants:
+**
+**        SQLITE_READ_COLUMN
+**        SQLITE_WRITE_COLUMN
+**        SQLITE_DELETE_ROW
+**        SQLITE_INSERT_ROW
+**
+** The third and fourth arguments to the auth function are the name of
+** the table and the column that are being accessed.  The auth function
+** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
+** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
+** means that the SQL statement will never-run - the sqlite_exec() call
+** will return with an error.  SQLITE_IGNORE means that the SQL statement
+** should run but attempts to read the specified column will return NULL
+** and attempts to write the column will be ignored.
+**
+** Setting the auth function to NULL disables this hook.  The default
+** setting of the auth function is NULL.
+*/
+int sqlite_set_authorizer(
+  sqlite *db,
+  int (*xAuth)(void*,int,const char*,const char*),
+  void *pArg
+){
+  db->xAuth = xAuth;
+  db->pAuthArg = pArg;
+  return SQLITE_OK;
+}
+
+/*
+** Write an error message into pParse->zErrMsg that explains that the
+** user-supplied authorization function returned an illegal value.
+*/
+static void sqliteAuthBadReturnCode(Parse *pParse, int rc){
+  char zBuf[20];
+  sprintf(zBuf, "(%d)", rc);
+  sqliteSetString(&pParse->zErrMsg, "illegal return value ", zBuf,
+    " from the authorization function - should be SQLITE_OK, "
+    "SQLITE_IGNORE, or SQLITE_DENY", 0);
+  pParse->nErr++;
+  pParse->rc = SQLITE_MISUSE;
+}
+
+/*
+** The pExpr should be a TK_COLUMN expression.  The table referred to
+** is in pTabList with an offset of base.  Check to see if it is OK to read
+** this particular column.
+**
+** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
+** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
+** then generate an error.
+*/
+void sqliteAuthRead(
+  Parse *pParse,        /* The parser context */
+  Expr *pExpr,          /* The expression to check authorization on */
+  SrcList *pTabList,    /* All table that pExpr might refer to */
+  int base              /* Offset of pTabList relative to pExpr */
+){
+  sqlite *db = pParse->db;
+  int rc;
+  Table *pTab;
+  const char *zCol;
+  if( db->xAuth==0 ) return;
+  assert( pExpr->op==TK_COLUMN );
+  assert( pExpr->iTable>=base && pExpr->iTable<base+pTabList->nSrc );
+  pTab = pTabList->a[pExpr->iTable-base].pTab;
+  if( pTab==0 ) return;
+  if( pExpr->iColumn>=0 ){
+    assert( pExpr->iColumn<pTab->nCol );
+    zCol = pTab->aCol[pExpr->iColumn].zName;
+  }else if( pTab->iPKey>=0 ){
+    assert( pTab->iPKey<pTab->nCol );
+    zCol = pTab->aCol[pTab->iPKey].zName;
+  }else{
+    zCol = "ROWID";
+  }
+  rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol);
+  if( rc==SQLITE_IGNORE ){
+    pExpr->op = TK_NULL;
+  }else if( rc==SQLITE_DENY ){
+    sqliteSetString(&pParse->zErrMsg,"access to ",
+        pTab->zName, ".", zCol, " is prohibited", 0);
+    pParse->nErr++;
+    pParse->rc = SQLITE_AUTH;
+  }else if( rc!=SQLITE_OK ){
+    sqliteAuthBadReturnCode(pParse, rc);
+  }
+}
+
+/*
+** Do an authorization check using the code and arguments given.  Return
+** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
+** is returned, then the error count and error message in pParse are
+** modified appropriately.
+*/
+int sqliteAuthCheck(
+  Parse *pParse,
+  int code,
+  const char *zArg1,
+  const char *zArg2
+){
+  sqlite *db = pParse->db;
+  int rc;
+  if( db->xAuth==0 ){
+    return SQLITE_OK;
+  }
+  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2);
+  if( rc==SQLITE_DENY ){
+    sqliteSetString(&pParse->zErrMsg, "not authorized", 0);
+    pParse->rc = SQLITE_AUTH;
+    pParse->nErr++;
+  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
+    rc = SQLITE_DENY;
+    sqliteAuthBadReturnCode(pParse, rc);
+  }
+  return rc;
+}
+
+#endif /* SQLITE_OMIT_AUTHORIZATION */
diff --git a/ext/sqlite/libsqlite/src/btree.c b/ext/sqlite/libsqlite/src/btree.c
new file mode 100644 (file)
index 0000000..41913fc
--- /dev/null
@@ -0,0 +1,3382 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** $Id$
+**
+** This file implements a external (disk-based) database using BTrees.
+** For a detailed discussion of BTrees, refer to
+**
+**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
+**     "Sorting And Searching", pages 473-480. Addison-Wesley
+**     Publishing Company, Reading, Massachusetts.
+**
+** The basic idea is that each page of the file contains N database
+** entries and N+1 pointers to subpages.
+**
+**   ----------------------------------------------------------------
+**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N) | Ptr(N+1) |
+**   ----------------------------------------------------------------
+**
+** All of the keys on the page that Ptr(0) points to have values less
+** than Key(0).  All of the keys on page Ptr(1) and its subpages have
+** values greater than Key(0) and less than Key(1).  All of the keys
+** on Ptr(N+1) and its subpages have values greater than Key(N).  And
+** so forth.
+**
+** Finding a particular key requires reading O(log(M)) pages from the 
+** disk where M is the number of entries in the tree.
+**
+** In this implementation, a single file can hold one or more separate 
+** BTrees.  Each BTree is identified by the index of its root page.  The
+** key and data for any entry are combined to form the "payload".  Up to
+** MX_LOCAL_PAYLOAD bytes of payload can be carried directly on the
+** database page.  If the payload is larger than MX_LOCAL_PAYLOAD bytes
+** then surplus bytes are stored on overflow pages.  The payload for an
+** entry and the preceding pointer are combined to form a "Cell".  Each 
+** page has a small header which contains the Ptr(N+1) pointer.
+**
+** The first page of the file contains a magic string used to verify that
+** the file really is a valid BTree database, a pointer to a list of unused
+** pages in the file, and some meta information.  The root of the first
+** BTree begins on page 2 of the file.  (Pages are numbered beginning with
+** 1, not 0.)  Thus a minimum database contains 2 pages.
+*/
+#include "sqliteInt.h"
+#include "pager.h"
+#include "btree.h"
+#include <assert.h>
+
+/*
+** Macros used for byteswapping.  B is a pointer to the Btree
+** structure.  This is needed to access the Btree.needSwab boolean
+** in order to tell if byte swapping is needed or not.
+** X is an unsigned integer.  SWAB16 byte swaps a 16-bit integer.
+** SWAB32 byteswaps a 32-bit integer.
+*/
+#define SWAB16(B,X)   ((B)->needSwab? swab16(X) : (X))
+#define SWAB32(B,X)   ((B)->needSwab? swab32(X) : (X))
+#define SWAB_ADD(B,X,A) \
+   if((B)->needSwab){ X=swab32(swab32(X)+A); }else{ X += (A); }
+
+/*
+** The following global variable - available only if SQLITE_TEST is
+** defined - is used to determine whether new databases are created in
+** native byte order or in non-native byte order.  Non-native byte order
+** databases are created for testing purposes only.  Under normal operation,
+** only native byte-order databases should be created, but we should be
+** able to read or write existing databases regardless of the byteorder.
+*/
+#ifdef SQLITE_TEST
+int btree_native_byte_order = 1;
+#else
+# define btree_native_byte_order 1
+#endif
+
+/*
+** Forward declarations of structures used only in this file.
+*/
+typedef struct PageOne PageOne;
+typedef struct MemPage MemPage;
+typedef struct PageHdr PageHdr;
+typedef struct Cell Cell;
+typedef struct CellHdr CellHdr;
+typedef struct FreeBlk FreeBlk;
+typedef struct OverflowPage OverflowPage;
+typedef struct FreelistInfo FreelistInfo;
+
+/*
+** All structures on a database page are aligned to 4-byte boundries.
+** This routine rounds up a number of bytes to the next multiple of 4.
+**
+** This might need to change for computer architectures that require
+** and 8-byte alignment boundry for structures.
+*/
+#define ROUNDUP(X)  ((X+3) & ~3)
+
+/*
+** This is a magic string that appears at the beginning of every
+** SQLite database in order to identify the file as a real database.
+*/
+static const char zMagicHeader[] = 
+   "** This file contains an SQLite 2.1 database **";
+#define MAGIC_SIZE (sizeof(zMagicHeader))
+
+/*
+** This is a magic integer also used to test the integrity of the database
+** file.  This integer is used in addition to the string above so that
+** if the file is written on a little-endian architecture and read
+** on a big-endian architectures (or vice versa) we can detect the
+** problem.
+**
+** The number used was obtained at random and has no special
+** significance other than the fact that it represents a different
+** integer on little-endian and big-endian machines.
+*/
+#define MAGIC 0xdae37528
+
+/*
+** The first page of the database file contains a magic header string
+** to identify the file as an SQLite database file.  It also contains
+** a pointer to the first free page of the file.  Page 2 contains the
+** root of the principle BTree.  The file might contain other BTrees
+** rooted on pages above 2.
+**
+** The first page also contains SQLITE_N_BTREE_META integers that
+** can be used by higher-level routines.
+**
+** Remember that pages are numbered beginning with 1.  (See pager.c
+** for additional information.)  Page 0 does not exist and a page
+** number of 0 is used to mean "no such page".
+*/
+struct PageOne {
+  char zMagic[MAGIC_SIZE]; /* String that identifies the file as a database */
+  int iMagic;              /* Integer to verify correct byte order */
+  Pgno freeList;           /* First free page in a list of all free pages */
+  int nFree;               /* Number of pages on the free list */
+  int aMeta[SQLITE_N_BTREE_META-1];  /* User defined integers */
+};
+
+/*
+** Each database page has a header that is an instance of this
+** structure.
+**
+** PageHdr.firstFree is 0 if there is no free space on this page.
+** Otherwise, PageHdr.firstFree is the index in MemPage.u.aDisk[] of a 
+** FreeBlk structure that describes the first block of free space.  
+** All free space is defined by a linked list of FreeBlk structures.
+**
+** Data is stored in a linked list of Cell structures.  PageHdr.firstCell
+** is the index into MemPage.u.aDisk[] of the first cell on the page.  The
+** Cells are kept in sorted order.
+**
+** A Cell contains all information about a database entry and a pointer
+** to a child page that contains other entries less than itself.  In
+** other words, the i-th Cell contains both Ptr(i) and Key(i).  The
+** right-most pointer of the page is contained in PageHdr.rightChild.
+*/
+struct PageHdr {
+  Pgno rightChild;  /* Child page that comes after all cells on this page */
+  u16 firstCell;    /* Index in MemPage.u.aDisk[] of the first cell */
+  u16 firstFree;    /* Index in MemPage.u.aDisk[] of the first free block */
+};
+
+/*
+** Entries on a page of the database are called "Cells".  Each Cell
+** has a header and data.  This structure defines the header.  The
+** key and data (collectively the "payload") follow this header on
+** the database page.
+**
+** A definition of the complete Cell structure is given below.  The
+** header for the cell must be defined first in order to do some
+** of the sizing #defines that follow.
+*/
+struct CellHdr {
+  Pgno leftChild; /* Child page that comes before this cell */
+  u16 nKey;       /* Number of bytes in the key */
+  u16 iNext;      /* Index in MemPage.u.aDisk[] of next cell in sorted order */
+  u8 nKeyHi;      /* Upper 8 bits of key size for keys larger than 64K bytes */
+  u8 nDataHi;     /* Upper 8 bits of data size when the size is more than 64K */
+  u16 nData;      /* Number of bytes of data */
+};
+
+/*
+** The key and data size are split into a lower 16-bit segment and an
+** upper 8-bit segment in order to pack them together into a smaller
+** space.  The following macros reassembly a key or data size back
+** into an integer.
+*/
+#define NKEY(b,h)  (SWAB16(b,h.nKey) + h.nKeyHi*65536)
+#define NDATA(b,h) (SWAB16(b,h.nData) + h.nDataHi*65536)
+
+/*
+** The minimum size of a complete Cell.  The Cell must contain a header
+** and at least 4 bytes of payload.
+*/
+#define MIN_CELL_SIZE  (sizeof(CellHdr)+4)
+
+/*
+** The maximum number of database entries that can be held in a single
+** page of the database. 
+*/
+#define MX_CELL ((SQLITE_PAGE_SIZE-sizeof(PageHdr))/MIN_CELL_SIZE)
+
+/*
+** The amount of usable space on a single page of the BTree.  This is the
+** page size minus the overhead of the page header.
+*/
+#define USABLE_SPACE  (SQLITE_PAGE_SIZE - sizeof(PageHdr))
+
+/*
+** The maximum amount of payload (in bytes) that can be stored locally for
+** a database entry.  If the entry contains more data than this, the
+** extra goes onto overflow pages.
+**
+** This number is chosen so that at least 4 cells will fit on every page.
+*/
+#define MX_LOCAL_PAYLOAD ((USABLE_SPACE/4-(sizeof(CellHdr)+sizeof(Pgno)))&~3)
+
+/*
+** Data on a database page is stored as a linked list of Cell structures.
+** Both the key and the data are stored in aPayload[].  The key always comes
+** first.  The aPayload[] field grows as necessary to hold the key and data,
+** up to a maximum of MX_LOCAL_PAYLOAD bytes.  If the size of the key and
+** data combined exceeds MX_LOCAL_PAYLOAD bytes, then Cell.ovfl is the
+** page number of the first overflow page.
+**
+** Though this structure is fixed in size, the Cell on the database
+** page varies in size.  Every cell has a CellHdr and at least 4 bytes
+** of payload space.  Additional payload bytes (up to the maximum of
+** MX_LOCAL_PAYLOAD) and the Cell.ovfl value are allocated only as
+** needed.
+*/
+struct Cell {
+  CellHdr h;                        /* The cell header */
+  char aPayload[MX_LOCAL_PAYLOAD];  /* Key and data */
+  Pgno ovfl;                        /* The first overflow page */
+};
+
+/*
+** Free space on a page is remembered using a linked list of the FreeBlk
+** structures.  Space on a database page is allocated in increments of
+** at least 4 bytes and is always aligned to a 4-byte boundry.  The
+** linked list of FreeBlks is always kept in order by address.
+*/
+struct FreeBlk {
+  u16 iSize;      /* Number of bytes in this block of free space */
+  u16 iNext;      /* Index in MemPage.u.aDisk[] of the next free block */
+};
+
+/*
+** The number of bytes of payload that will fit on a single overflow page.
+*/
+#define OVERFLOW_SIZE (SQLITE_PAGE_SIZE-sizeof(Pgno))
+
+/*
+** When the key and data for a single entry in the BTree will not fit in
+** the MX_LOCAL_PAYLOAD bytes of space available on the database page,
+** then all extra bytes are written to a linked list of overflow pages.
+** Each overflow page is an instance of the following structure.
+**
+** Unused pages in the database are also represented by instances of
+** the OverflowPage structure.  The PageOne.freeList field is the
+** page number of the first page in a linked list of unused database
+** pages.
+*/
+struct OverflowPage {
+  Pgno iNext;
+  char aPayload[OVERFLOW_SIZE];
+};
+
+/*
+** The PageOne.freeList field points to a linked list of overflow pages
+** hold information about free pages.  The aPayload section of each
+** overflow page contains an instance of the following structure.  The
+** aFree[] array holds the page number of nFree unused pages in the disk
+** file.
+*/
+struct FreelistInfo {
+  int nFree;
+  Pgno aFree[(OVERFLOW_SIZE-sizeof(int))/sizeof(Pgno)];
+};
+
+/*
+** For every page in the database file, an instance of the following structure
+** is stored in memory.  The u.aDisk[] array contains the raw bits read from
+** the disk.  The rest is auxiliary information held in memory only. The
+** auxiliary info is only valid for regular database pages - it is not
+** used for overflow pages and pages on the freelist.
+**
+** Of particular interest in the auxiliary info is the apCell[] entry.  Each
+** apCell[] entry is a pointer to a Cell structure in u.aDisk[].  The cells are
+** put in this array so that they can be accessed in constant time, rather
+** than in linear time which would be needed if we had to walk the linked 
+** list on every access.
+**
+** Note that apCell[] contains enough space to hold up to two more Cells
+** than can possibly fit on one page.  In the steady state, every apCell[]
+** points to memory inside u.aDisk[].  But in the middle of an insert
+** operation, some apCell[] entries may temporarily point to data space
+** outside of u.aDisk[].  This is a transient situation that is quickly
+** resolved.  But while it is happening, it is possible for a database
+** page to hold as many as two more cells than it might otherwise hold.
+** The extra two entries in apCell[] are an allowance for this situation.
+**
+** The pParent field points back to the parent page.  This allows us to
+** walk up the BTree from any leaf to the root.  Care must be taken to
+** unref() the parent page pointer when this page is no longer referenced.
+** The pageDestructor() routine handles that chore.
+*/
+struct MemPage {
+  union {
+    char aDisk[SQLITE_PAGE_SIZE];  /* Page data stored on disk */
+    PageHdr hdr;                   /* Overlay page header */
+  } u;
+  u8 isInit;                     /* True if auxiliary data is initialized */
+  u8 idxShift;                   /* True if apCell[] indices have changed */
+  u8 isOverfull;                 /* Some apCell[] points outside u.aDisk[] */
+  MemPage *pParent;              /* The parent of this page.  NULL for root */
+  int idxParent;                 /* Index in pParent->apCell[] of this node */
+  int nFree;                     /* Number of free bytes in u.aDisk[] */
+  int nCell;                     /* Number of entries on this page */
+  Cell *apCell[MX_CELL+2];       /* All data entires in sorted order */
+};
+
+/*
+** The in-memory image of a disk page has the auxiliary information appended
+** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
+** that extra information.
+*/
+#define EXTRA_SIZE (sizeof(MemPage)-SQLITE_PAGE_SIZE)
+
+/*
+** Everything we need to know about an open database
+*/
+struct Btree {
+  Pager *pPager;        /* The page cache */
+  BtCursor *pCursor;    /* A list of all open cursors */
+  PageOne *page1;       /* First page of the database */
+  u8 inTrans;           /* True if a transaction is in progress */
+  u8 inCkpt;            /* True if there is a checkpoint on the transaction */
+  u8 readOnly;          /* True if the underlying file is readonly */
+  u8 needSwab;          /* Need to byte-swapping */
+};
+typedef Btree Bt;
+
+/*
+** A cursor is a pointer to a particular entry in the BTree.
+** The entry is identified by its MemPage and the index in
+** MemPage.apCell[] of the entry.
+*/
+struct BtCursor {
+  Btree *pBt;               /* The Btree to which this cursor belongs */
+  BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
+  BtCursor *pShared;        /* Loop of cursors with the same root page */
+  Pgno pgnoRoot;            /* The root page of this tree */
+  MemPage *pPage;           /* Page that contains the entry */
+  int idx;                  /* Index of the entry in pPage->apCell[] */
+  u8 wrFlag;                /* True if writable */
+  u8 eSkip;                 /* Determines if next step operation is a no-op */
+  u8 iMatch;                /* compare result from last sqliteBtreeMoveto() */
+};
+
+/*
+** Legal values for BtCursor.eSkip.
+*/
+#define SKIP_NONE     0   /* Always step the cursor */
+#define SKIP_NEXT     1   /* The next sqliteBtreeNext() is a no-op */
+#define SKIP_PREV     2   /* The next sqliteBtreePrevious() is a no-op */
+#define SKIP_INVALID  3   /* Calls to Next() and Previous() are invalid */
+
+/*
+** Routines for byte swapping.
+*/
+u16 swab16(u16 x){
+  return ((x & 0xff)<<8) | ((x>>8)&0xff);
+}
+u32 swab32(u32 x){
+  return ((x & 0xff)<<24) | ((x & 0xff00)<<8) |
+         ((x>>8) & 0xff00) | ((x>>24)&0xff);
+}
+
+/*
+** Compute the total number of bytes that a Cell needs on the main
+** database page.  The number returned includes the Cell header,
+** local payload storage, and the pointer to overflow pages (if
+** applicable).  Additional space allocated on overflow pages
+** is NOT included in the value returned from this routine.
+*/
+static int cellSize(Btree *pBt, Cell *pCell){
+  int n = NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h);
+  if( n>MX_LOCAL_PAYLOAD ){
+    n = MX_LOCAL_PAYLOAD + sizeof(Pgno);
+  }else{
+    n = ROUNDUP(n);
+  }
+  n += sizeof(CellHdr);
+  return n;
+}
+
+/*
+** Defragment the page given.  All Cells are moved to the
+** beginning of the page and all free space is collected 
+** into one big FreeBlk at the end of the page.
+*/
+static void defragmentPage(Btree *pBt, MemPage *pPage){
+  int pc, i, n;
+  FreeBlk *pFBlk;
+  char newPage[SQLITE_PAGE_SIZE];
+
+  assert( sqlitepager_iswriteable(pPage) );
+  assert( pPage->isInit );
+  pc = sizeof(PageHdr);
+  pPage->u.hdr.firstCell = SWAB16(pBt, pc);
+  memcpy(newPage, pPage->u.aDisk, pc);
+  for(i=0; i<pPage->nCell; i++){
+    Cell *pCell = pPage->apCell[i];
+
+    /* This routine should never be called on an overfull page.  The
+    ** following asserts verify that constraint. */
+    assert( Addr(pCell) > Addr(pPage) );
+    assert( Addr(pCell) < Addr(pPage) + SQLITE_PAGE_SIZE );
+
+    n = cellSize(pBt, pCell);
+    pCell->h.iNext = SWAB16(pBt, pc + n);
+    memcpy(&newPage[pc], pCell, n);
+    pPage->apCell[i] = (Cell*)&pPage->u.aDisk[pc];
+    pc += n;
+  }
+  assert( pPage->nFree==SQLITE_PAGE_SIZE-pc );
+  memcpy(pPage->u.aDisk, newPage, pc);
+  if( pPage->nCell>0 ){
+    pPage->apCell[pPage->nCell-1]->h.iNext = 0;
+  }
+  pFBlk = (FreeBlk*)&pPage->u.aDisk[pc];
+  pFBlk->iSize = SWAB16(pBt, SQLITE_PAGE_SIZE - pc);
+  pFBlk->iNext = 0;
+  pPage->u.hdr.firstFree = SWAB16(pBt, pc);
+  memset(&pFBlk[1], 0, SQLITE_PAGE_SIZE - pc - sizeof(FreeBlk));
+}
+
+/*
+** Allocate nByte bytes of space on a page.  nByte must be a 
+** multiple of 4.
+**
+** Return the index into pPage->u.aDisk[] of the first byte of
+** the new allocation. Or return 0 if there is not enough free
+** space on the page to satisfy the allocation request.
+**
+** If the page contains nBytes of free space but does not contain
+** nBytes of contiguous free space, then this routine automatically
+** calls defragementPage() to consolidate all free space before 
+** allocating the new chunk.
+*/
+static int allocateSpace(Btree *pBt, MemPage *pPage, int nByte){
+  FreeBlk *p;
+  u16 *pIdx;
+  int start;
+  int cnt = 0;
+  int iSize;
+
+  assert( sqlitepager_iswriteable(pPage) );
+  assert( nByte==ROUNDUP(nByte) );
+  assert( pPage->isInit );
+  if( pPage->nFree<nByte || pPage->isOverfull ) return 0;
+  pIdx = &pPage->u.hdr.firstFree;
+  p = (FreeBlk*)&pPage->u.aDisk[SWAB16(pBt, *pIdx)];
+  while( (iSize = SWAB16(pBt, p->iSize))<nByte ){
+    assert( cnt++ < SQLITE_PAGE_SIZE/4 );
+    if( p->iNext==0 ){
+      defragmentPage(pBt, pPage);
+      pIdx = &pPage->u.hdr.firstFree;
+    }else{
+      pIdx = &p->iNext;
+    }
+    p = (FreeBlk*)&pPage->u.aDisk[SWAB16(pBt, *pIdx)];
+  }
+  if( iSize==nByte ){
+    start = SWAB16(pBt, *pIdx);
+    *pIdx = p->iNext;
+  }else{
+    FreeBlk *pNew;
+    start = SWAB16(pBt, *pIdx);
+    pNew = (FreeBlk*)&pPage->u.aDisk[start + nByte];
+    pNew->iNext = p->iNext;
+    pNew->iSize = SWAB16(pBt, iSize - nByte);
+    *pIdx = SWAB16(pBt, start + nByte);
+  }
+  pPage->nFree -= nByte;
+  return start;
+}
+
+/*
+** Return a section of the MemPage.u.aDisk[] to the freelist.
+** The first byte of the new free block is pPage->u.aDisk[start]
+** and the size of the block is "size" bytes.  Size must be
+** a multiple of 4.
+**
+** Most of the effort here is involved in coalesing adjacent
+** free blocks into a single big free block.
+*/
+static void freeSpace(Btree *pBt, MemPage *pPage, int start, int size){
+  int end = start + size;
+  u16 *pIdx, idx;
+  FreeBlk *pFBlk;
+  FreeBlk *pNew;
+  FreeBlk *pNext;
+  int iSize;
+
+  assert( sqlitepager_iswriteable(pPage) );
+  assert( size == ROUNDUP(size) );
+  assert( start == ROUNDUP(start) );
+  assert( pPage->isInit );
+  pIdx = &pPage->u.hdr.firstFree;
+  idx = SWAB16(pBt, *pIdx);
+  while( idx!=0 && idx<start ){
+    pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
+    iSize = SWAB16(pBt, pFBlk->iSize);
+    if( idx + iSize == start ){
+      pFBlk->iSize = SWAB16(pBt, iSize + size);
+      if( idx + iSize + size == SWAB16(pBt, pFBlk->iNext) ){
+        pNext = (FreeBlk*)&pPage->u.aDisk[idx + iSize + size];
+        if( pBt->needSwab ){
+          pFBlk->iSize = swab16(swab16(pNext->iSize)+iSize+size);
+        }else{
+          pFBlk->iSize += pNext->iSize;
+        }
+        pFBlk->iNext = pNext->iNext;
+      }
+      pPage->nFree += size;
+      return;
+    }
+    pIdx = &pFBlk->iNext;
+    idx = SWAB16(pBt, *pIdx);
+  }
+  pNew = (FreeBlk*)&pPage->u.aDisk[start];
+  if( idx != end ){
+    pNew->iSize = SWAB16(pBt, size);
+    pNew->iNext = SWAB16(pBt, idx);
+  }else{
+    pNext = (FreeBlk*)&pPage->u.aDisk[idx];
+    pNew->iSize = SWAB16(pBt, size + SWAB16(pBt, pNext->iSize));
+    pNew->iNext = pNext->iNext;
+  }
+  *pIdx = SWAB16(pBt, start);
+  pPage->nFree += size;
+}
+
+/*
+** Initialize the auxiliary information for a disk block.
+**
+** The pParent parameter must be a pointer to the MemPage which
+** is the parent of the page being initialized.  The root of the
+** BTree (usually page 2) has no parent and so for that page, 
+** pParent==NULL.
+**
+** Return SQLITE_OK on success.  If we see that the page does
+** not contain a well-formed database page, then return 
+** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
+** guarantee that the page is well-formed.  It only shows that
+** we failed to detect any corruption.
+*/
+static int initPage(Bt *pBt, MemPage *pPage, Pgno pgnoThis, MemPage *pParent){
+  int idx;           /* An index into pPage->u.aDisk[] */
+  Cell *pCell;       /* A pointer to a Cell in pPage->u.aDisk[] */
+  FreeBlk *pFBlk;    /* A pointer to a free block in pPage->u.aDisk[] */
+  int sz;            /* The size of a Cell in bytes */
+  int freeSpace;     /* Amount of free space on the page */
+
+  if( pPage->pParent ){
+    assert( pPage->pParent==pParent );
+    return SQLITE_OK;
+  }
+  if( pParent ){
+    pPage->pParent = pParent;
+    sqlitepager_ref(pParent);
+  }
+  if( pPage->isInit ) return SQLITE_OK;
+  pPage->isInit = 1;
+  pPage->nCell = 0;
+  freeSpace = USABLE_SPACE;
+  idx = SWAB16(pBt, pPage->u.hdr.firstCell);
+  while( idx!=0 ){
+    if( idx>SQLITE_PAGE_SIZE-MIN_CELL_SIZE ) goto page_format_error;
+    if( idx<sizeof(PageHdr) ) goto page_format_error;
+    if( idx!=ROUNDUP(idx) ) goto page_format_error;
+    pCell = (Cell*)&pPage->u.aDisk[idx];
+    sz = cellSize(pBt, pCell);
+    if( idx+sz > SQLITE_PAGE_SIZE ) goto page_format_error;
+    freeSpace -= sz;
+    pPage->apCell[pPage->nCell++] = pCell;
+    idx = SWAB16(pBt, pCell->h.iNext);
+  }
+  pPage->nFree = 0;
+  idx = SWAB16(pBt, pPage->u.hdr.firstFree);
+  while( idx!=0 ){
+    int iNext;
+    if( idx>SQLITE_PAGE_SIZE-sizeof(FreeBlk) ) goto page_format_error;
+    if( idx<sizeof(PageHdr) ) goto page_format_error;
+    pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
+    pPage->nFree += SWAB16(pBt, pFBlk->iSize);
+    iNext = SWAB16(pBt, pFBlk->iNext);
+    if( iNext>0 && iNext <= idx ) goto page_format_error;
+    idx = iNext;
+  }
+  if( pPage->nCell==0 && pPage->nFree==0 ){
+    /* As a special case, an uninitialized root page appears to be
+    ** an empty database */
+    return SQLITE_OK;
+  }
+  if( pPage->nFree!=freeSpace ) goto page_format_error;
+  return SQLITE_OK;
+
+page_format_error:
+  return SQLITE_CORRUPT;
+}
+
+/*
+** Set up a raw page so that it looks like a database page holding
+** no entries.
+*/
+static void zeroPage(Btree *pBt, MemPage *pPage){
+  PageHdr *pHdr;
+  FreeBlk *pFBlk;
+  assert( sqlitepager_iswriteable(pPage) );
+  memset(pPage, 0, SQLITE_PAGE_SIZE);
+  pHdr = &pPage->u.hdr;
+  pHdr->firstCell = 0;
+  pHdr->firstFree = SWAB16(pBt, sizeof(*pHdr));
+  pFBlk = (FreeBlk*)&pHdr[1];
+  pFBlk->iNext = 0;
+  pPage->nFree = SQLITE_PAGE_SIZE - sizeof(*pHdr);
+  pFBlk->iSize = SWAB16(pBt, pPage->nFree);
+  pPage->nCell = 0;
+  pPage->isOverfull = 0;
+}
+
+/*
+** This routine is called when the reference count for a page
+** reaches zero.  We need to unref the pParent pointer when that
+** happens.
+*/
+static void pageDestructor(void *pData){
+  MemPage *pPage = (MemPage*)pData;
+  if( pPage->pParent ){
+    MemPage *pParent = pPage->pParent;
+    pPage->pParent = 0;
+    sqlitepager_unref(pParent);
+  }
+}
+
+/*
+** Open a new database.
+**
+** Actually, this routine just sets up the internal data structures
+** for accessing the database.  We do not open the database file 
+** until the first page is loaded.
+**
+** zFilename is the name of the database file.  If zFilename is NULL
+** a new database with a random name is created.  This randomly named
+** database file will be deleted when sqliteBtreeClose() is called.
+*/
+int sqliteBtreeOpen(
+  const char *zFilename,    /* Name of the file containing the BTree database */
+  int omitJournal,          /* if TRUE then do not journal this file */
+  int nCache,               /* How many pages in the page cache */
+  Btree **ppBtree           /* Pointer to new Btree object written here */
+){
+  Btree *pBt;
+  int rc;
+
+  /*
+  ** The following asserts make sure that structures used by the btree are
+  ** the right size.  This is to guard against size changes that result
+  ** when compiling on a different architecture.
+  */
+  assert( sizeof(u32)==4 );
+  assert( sizeof(u16)==2 );
+  assert( sizeof(Pgno)==4 );
+  assert( sizeof(PageHdr)==8 );
+  assert( sizeof(CellHdr)==12 );
+  assert( sizeof(FreeBlk)==4 );
+  assert( sizeof(OverflowPage)==SQLITE_PAGE_SIZE );
+  assert( sizeof(FreelistInfo)==OVERFLOW_SIZE );
+  assert( sizeof(ptr)==sizeof(char*) );
+  assert( sizeof(uptr)==sizeof(ptr) );
+
+  pBt = sqliteMalloc( sizeof(*pBt) );
+  if( pBt==0 ){
+    *ppBtree = 0;
+    return SQLITE_NOMEM;
+  }
+  if( nCache<10 ) nCache = 10;
+  rc = sqlitepager_open(&pBt->pPager, zFilename, nCache, EXTRA_SIZE,
+                        !omitJournal);
+  if( rc!=SQLITE_OK ){
+    if( pBt->pPager ) sqlitepager_close(pBt->pPager);
+    sqliteFree(pBt);
+    *ppBtree = 0;
+    return rc;
+  }
+  sqlitepager_set_destructor(pBt->pPager, pageDestructor);
+  pBt->pCursor = 0;
+  pBt->page1 = 0;
+  pBt->readOnly = sqlitepager_isreadonly(pBt->pPager);
+  *ppBtree = pBt;
+  return SQLITE_OK;
+}
+
+/*
+** Close an open database and invalidate all cursors.
+*/
+int sqliteBtreeClose(Btree *pBt){
+  while( pBt->pCursor ){
+    sqliteBtreeCloseCursor(pBt->pCursor);
+  }
+  sqlitepager_close(pBt->pPager);
+  sqliteFree(pBt);
+  return SQLITE_OK;
+}
+
+/*
+** Change the limit on the number of pages allowed in the cache.
+**
+** The maximum number of cache pages is set to the absolute
+** value of mxPage.  If mxPage is negative, the pager will
+** operate asynchronously - it will not stop to do fsync()s
+** to insure data is written to the disk surface before
+** continuing.  Transactions still work if synchronous is off,
+** and the database cannot be corrupted if this program
+** crashes.  But if the operating system crashes or there is
+** an abrupt power failure when synchronous is off, the database
+** could be left in an inconsistent and unrecoverable state.
+** Synchronous is on by default so database corruption is not
+** normally a worry.
+*/
+int sqliteBtreeSetCacheSize(Btree *pBt, int mxPage){
+  sqlitepager_set_cachesize(pBt->pPager, mxPage);
+  return SQLITE_OK;
+}
+
+/*
+** Change the way data is synced to disk in order to increase or decrease
+** how well the database resists damage due to OS crashes and power
+** failures.  Level 1 is the same as asynchronous (no syncs() occur and
+** there is a high probability of damage)  Level 2 is the default.  There
+** is a very low but non-zero probability of damage.  Level 3 reduces the
+** probability of damage to near zero but with a write performance reduction.
+*/
+int sqliteBtreeSetSafetyLevel(Btree *pBt, int level){
+  sqlitepager_set_safety_level(pBt->pPager, level);
+  return SQLITE_OK;
+}
+
+/*
+** Get a reference to page1 of the database file.  This will
+** also acquire a readlock on that file.
+**
+** SQLITE_OK is returned on success.  If the file is not a
+** well-formed database file, then SQLITE_CORRUPT is returned.
+** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
+** is returned if we run out of memory.  SQLITE_PROTOCOL is returned
+** if there is a locking protocol violation.
+*/
+static int lockBtree(Btree *pBt){
+  int rc;
+  if( pBt->page1 ) return SQLITE_OK;
+  rc = sqlitepager_get(pBt->pPager, 1, (void**)&pBt->page1);
+  if( rc!=SQLITE_OK ) return rc;
+
+  /* Do some checking to help insure the file we opened really is
+  ** a valid database file. 
+  */
+  if( sqlitepager_pagecount(pBt->pPager)>0 ){
+    PageOne *pP1 = pBt->page1;
+    if( strcmp(pP1->zMagic,zMagicHeader)!=0 ||
+          (pP1->iMagic!=MAGIC && swab32(pP1->iMagic)!=MAGIC) ){
+      rc = SQLITE_CORRUPT;
+      goto page1_init_failed;
+    }
+    pBt->needSwab = pP1->iMagic!=MAGIC;
+  }
+  return rc;
+
+page1_init_failed:
+  sqlitepager_unref(pBt->page1);
+  pBt->page1 = 0;
+  return rc;
+}
+
+/*
+** If there are no outstanding cursors and we are not in the middle
+** of a transaction but there is a read lock on the database, then
+** this routine unrefs the first page of the database file which 
+** has the effect of releasing the read lock.
+**
+** If there are any outstanding cursors, this routine is a no-op.
+**
+** If there is a transaction in progress, this routine is a no-op.
+*/
+static void unlockBtreeIfUnused(Btree *pBt){
+  if( pBt->inTrans==0 && pBt->pCursor==0 && pBt->page1!=0 ){
+    sqlitepager_unref(pBt->page1);
+    pBt->page1 = 0;
+    pBt->inTrans = 0;
+    pBt->inCkpt = 0;
+  }
+}
+
+/*
+** Create a new database by initializing the first two pages of the
+** file.
+*/
+static int newDatabase(Btree *pBt){
+  MemPage *pRoot;
+  PageOne *pP1;
+  int rc;
+  if( sqlitepager_pagecount(pBt->pPager)>1 ) return SQLITE_OK;
+  pP1 = pBt->page1;
+  rc = sqlitepager_write(pBt->page1);
+  if( rc ) return rc;
+  rc = sqlitepager_get(pBt->pPager, 2, (void**)&pRoot);
+  if( rc ) return rc;
+  rc = sqlitepager_write(pRoot);
+  if( rc ){
+    sqlitepager_unref(pRoot);
+    return rc;
+  }
+  strcpy(pP1->zMagic, zMagicHeader);
+  if( btree_native_byte_order ){
+    pP1->iMagic = MAGIC;
+    pBt->needSwab = 0;
+  }else{
+    pP1->iMagic = swab32(MAGIC);
+    pBt->needSwab = 1;
+  }
+  zeroPage(pBt, pRoot);
+  sqlitepager_unref(pRoot);
+  return SQLITE_OK;
+}
+
+/*
+** Attempt to start a new transaction.
+**
+** A transaction must be started before attempting any changes
+** to the database.  None of the following routines will work
+** unless a transaction is started first:
+**
+**      sqliteBtreeCreateTable()
+**      sqliteBtreeCreateIndex()
+**      sqliteBtreeClearTable()
+**      sqliteBtreeDropTable()
+**      sqliteBtreeInsert()
+**      sqliteBtreeDelete()
+**      sqliteBtreeUpdateMeta()
+*/
+int sqliteBtreeBeginTrans(Btree *pBt){
+  int rc;
+  if( pBt->inTrans ) return SQLITE_ERROR;
+  if( pBt->readOnly ) return SQLITE_READONLY;
+  if( pBt->page1==0 ){
+    rc = lockBtree(pBt);
+    if( rc!=SQLITE_OK ){
+      return rc;
+    }
+  }
+  rc = sqlitepager_begin(pBt->page1);
+  if( rc==SQLITE_OK ){
+    rc = newDatabase(pBt);
+  }
+  if( rc==SQLITE_OK ){
+    pBt->inTrans = 1;
+    pBt->inCkpt = 0;
+  }else{
+    unlockBtreeIfUnused(pBt);
+  }
+  return rc;
+}
+
+/*
+** Commit the transaction currently in progress.
+**
+** This will release the write lock on the database file.  If there
+** are no active cursors, it also releases the read lock.
+*/
+int sqliteBtreeCommit(Btree *pBt){
+  int rc;
+  rc = pBt->readOnly ? SQLITE_OK : sqlitepager_commit(pBt->pPager);
+  pBt->inTrans = 0;
+  pBt->inCkpt = 0;
+  unlockBtreeIfUnused(pBt);
+  return rc;
+}
+
+/*
+** Rollback the transaction in progress.  All cursors will be
+** invalided by this operation.  Any attempt to use a cursor
+** that was open at the beginning of this operation will result
+** in an error.
+**
+** This will release the write lock on the database file.  If there
+** are no active cursors, it also releases the read lock.
+*/
+int sqliteBtreeRollback(Btree *pBt){
+  int rc;
+  BtCursor *pCur;
+  if( pBt->inTrans==0 ) return SQLITE_OK;
+  pBt->inTrans = 0;
+  pBt->inCkpt = 0;
+  rc = pBt->readOnly ? SQLITE_OK : sqlitepager_rollback(pBt->pPager);
+  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
+    if( pCur->pPage && pCur->pPage->isInit==0 ){
+      sqlitepager_unref(pCur->pPage);
+      pCur->pPage = 0;
+    }
+  }
+  unlockBtreeIfUnused(pBt);
+  return rc;
+}
+
+/*
+** Set the checkpoint for the current transaction.  The checkpoint serves
+** as a sub-transaction that can be rolled back independently of the
+** main transaction.  You must start a transaction before starting a
+** checkpoint.  The checkpoint is ended automatically if the transaction
+** commits or rolls back.
+**
+** Only one checkpoint may be active at a time.  It is an error to try
+** to start a new checkpoint if another checkpoint is already active.
+*/
+int sqliteBtreeBeginCkpt(Btree *pBt){
+  int rc;
+  if( !pBt->inTrans || pBt->inCkpt ){
+    return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
+  }
+  rc = pBt->readOnly ? SQLITE_OK : sqlitepager_ckpt_begin(pBt->pPager);
+  pBt->inCkpt = 1;
+  return rc;
+}
+
+
+/*
+** Commit a checkpoint to transaction currently in progress.  If no
+** checkpoint is active, this is a no-op.
+*/
+int sqliteBtreeCommitCkpt(Btree *pBt){
+  int rc;
+  if( pBt->inCkpt && !pBt->readOnly ){
+    rc = sqlitepager_ckpt_commit(pBt->pPager);
+  }else{
+    rc = SQLITE_OK;
+  }
+  pBt->inCkpt = 0;
+  return rc;
+}
+
+/*
+** Rollback the checkpoint to the current transaction.  If there
+** is no active checkpoint or transaction, this routine is a no-op.
+**
+** All cursors will be invalided by this operation.  Any attempt
+** to use a cursor that was open at the beginning of this operation
+** will result in an error.
+*/
+int sqliteBtreeRollbackCkpt(Btree *pBt){
+  int rc;
+  BtCursor *pCur;
+  if( pBt->inCkpt==0 || pBt->readOnly ) return SQLITE_OK;
+  rc = sqlitepager_ckpt_rollback(pBt->pPager);
+  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
+    if( pCur->pPage && pCur->pPage->isInit==0 ){
+      sqlitepager_unref(pCur->pPage);
+      pCur->pPage = 0;
+    }
+  }
+  pBt->inCkpt = 0;
+  return rc;
+}
+
+/*
+** Create a new cursor for the BTree whose root is on the page
+** iTable.  The act of acquiring a cursor gets a read lock on 
+** the database file.
+**
+** If wrFlag==0, then the cursor can only be used for reading.
+** If wrFlag==1, then the cursor can be used for reading or for
+** writing if other conditions for writing are also met.  These
+** are the conditions that must be met in order for writing to
+** be allowed:
+**
+** 1:  The cursor must have been opened with wrFlag==1
+**
+** 2:  No other cursors may be open with wrFlag==0 on the same table
+**
+** 3:  The database must be writable (not on read-only media)
+**
+** 4:  There must be an active transaction.
+**
+** Condition 2 warrants further discussion.  If any cursor is opened
+** on a table with wrFlag==0, that prevents all other cursors from
+** writing to that table.  This is a kind of "read-lock".  When a cursor
+** is opened with wrFlag==0 it is guaranteed that the table will not
+** change as long as the cursor is open.  This allows the cursor to
+** do a sequential scan of the table without having to worry about
+** entries being inserted or deleted during the scan.  Cursors should
+** be opened with wrFlag==0 only if this read-lock property is needed.
+** That is to say, cursors should be opened with wrFlag==0 only if they
+** intend to use the sqliteBtreeNext() system call.  All other cursors
+** should be opened with wrFlag==1 even if they never really intend
+** to write.
+** 
+** No checking is done to make sure that page iTable really is the
+** root page of a b-tree.  If it is not, then the cursor acquired
+** will not work correctly.
+*/
+int sqliteBtreeCursor(Btree *pBt, int iTable, int wrFlag, BtCursor **ppCur){
+  int rc;
+  BtCursor *pCur, *pRing;
+
+  if( pBt->page1==0 ){
+    rc = lockBtree(pBt);
+    if( rc!=SQLITE_OK ){
+      *ppCur = 0;
+      return rc;
+    }
+  }
+  pCur = sqliteMalloc( sizeof(*pCur) );
+  if( pCur==0 ){
+    rc = SQLITE_NOMEM;
+    goto create_cursor_exception;
+  }
+  pCur->pgnoRoot = (Pgno)iTable;
+  rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pCur->pPage);
+  if( rc!=SQLITE_OK ){
+    goto create_cursor_exception;
+  }
+  rc = initPage(pBt, pCur->pPage, pCur->pgnoRoot, 0);
+  if( rc!=SQLITE_OK ){
+    goto create_cursor_exception;
+  }
+  pCur->pBt = pBt;
+  pCur->wrFlag = wrFlag;
+  pCur->idx = 0;
+  pCur->eSkip = SKIP_INVALID;
+  pCur->pNext = pBt->pCursor;
+  if( pCur->pNext ){
+    pCur->pNext->pPrev = pCur;
+  }
+  pCur->pPrev = 0;
+  pRing = pBt->pCursor;
+  while( pRing && pRing->pgnoRoot!=pCur->pgnoRoot ){ pRing = pRing->pNext; }
+  if( pRing ){
+    pCur->pShared = pRing->pShared;
+    pRing->pShared = pCur;
+  }else{
+    pCur->pShared = pCur;
+  }
+  pBt->pCursor = pCur;
+  *ppCur = pCur;
+  return SQLITE_OK;
+
+create_cursor_exception:
+  *ppCur = 0;
+  if( pCur ){
+    if( pCur->pPage ) sqlitepager_unref(pCur->pPage);
+    sqliteFree(pCur);
+  }
+  unlockBtreeIfUnused(pBt);
+  return rc;
+}
+
+/*
+** Close a cursor.  The read lock on the database file is released
+** when the last cursor is closed.
+*/
+int sqliteBtreeCloseCursor(BtCursor *pCur){
+  Btree *pBt = pCur->pBt;
+  if( pCur->pPrev ){
+    pCur->pPrev->pNext = pCur->pNext;
+  }else{
+    pBt->pCursor = pCur->pNext;
+  }
+  if( pCur->pNext ){
+    pCur->pNext->pPrev = pCur->pPrev;
+  }
+  if( pCur->pPage ){
+    sqlitepager_unref(pCur->pPage);
+  }
+  if( pCur->pShared!=pCur ){
+    BtCursor *pRing = pCur->pShared;
+    while( pRing->pShared!=pCur ){ pRing = pRing->pShared; }
+    pRing->pShared = pCur->pShared;
+  }
+  unlockBtreeIfUnused(pBt);
+  sqliteFree(pCur);
+  return SQLITE_OK;
+}
+
+/*
+** Make a temporary cursor by filling in the fields of pTempCur.
+** The temporary cursor is not on the cursor list for the Btree.
+*/
+static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
+  memcpy(pTempCur, pCur, sizeof(*pCur));
+  pTempCur->pNext = 0;
+  pTempCur->pPrev = 0;
+  if( pTempCur->pPage ){
+    sqlitepager_ref(pTempCur->pPage);
+  }
+}
+
+/*
+** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
+** function above.
+*/
+static void releaseTempCursor(BtCursor *pCur){
+  if( pCur->pPage ){
+    sqlitepager_unref(pCur->pPage);
+  }
+}
+
+/*
+** Set *pSize to the number of bytes of key in the entry the
+** cursor currently points to.  Always return SQLITE_OK.
+** Failure is not possible.  If the cursor is not currently
+** pointing to an entry (which can happen, for example, if
+** the database is empty) then *pSize is set to 0.
+*/
+int sqliteBtreeKeySize(BtCursor *pCur, int *pSize){
+  Cell *pCell;
+  MemPage *pPage;
+
+  pPage = pCur->pPage;
+  assert( pPage!=0 );
+  if( pCur->idx >= pPage->nCell ){
+    *pSize = 0;
+  }else{
+    pCell = pPage->apCell[pCur->idx];
+    *pSize = NKEY(pCur->pBt, pCell->h);
+  }
+  return SQLITE_OK;
+}
+
+/*
+** Read payload information from the entry that the pCur cursor is
+** pointing to.  Begin reading the payload at "offset" and read
+** a total of "amt" bytes.  Put the result in zBuf.
+**
+** This routine does not make a distinction between key and data.
+** It just reads bytes from the payload area.
+*/
+static int getPayload(BtCursor *pCur, int offset, int amt, char *zBuf){
+  char *aPayload;
+  Pgno nextPage;
+  int rc;
+  Btree *pBt = pCur->pBt;
+  assert( pCur!=0 && pCur->pPage!=0 );
+  assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
+  aPayload = pCur->pPage->apCell[pCur->idx]->aPayload;
+  if( offset<MX_LOCAL_PAYLOAD ){
+    int a = amt;
+    if( a+offset>MX_LOCAL_PAYLOAD ){
+      a = MX_LOCAL_PAYLOAD - offset;
+    }
+    memcpy(zBuf, &aPayload[offset], a);
+    if( a==amt ){
+      return SQLITE_OK;
+    }
+    offset = 0;
+    zBuf += a;
+    amt -= a;
+  }else{
+    offset -= MX_LOCAL_PAYLOAD;
+  }
+  if( amt>0 ){
+    nextPage = SWAB32(pBt, pCur->pPage->apCell[pCur->idx]->ovfl);
+  }
+  while( amt>0 && nextPage ){
+    OverflowPage *pOvfl;
+    rc = sqlitepager_get(pBt->pPager, nextPage, (void**)&pOvfl);
+    if( rc!=0 ){
+      return rc;
+    }
+    nextPage = SWAB32(pBt, pOvfl->iNext);
+    if( offset<OVERFLOW_SIZE ){
+      int a = amt;
+      if( a + offset > OVERFLOW_SIZE ){
+        a = OVERFLOW_SIZE - offset;
+      }
+      memcpy(zBuf, &pOvfl->aPayload[offset], a);
+      offset = 0;
+      amt -= a;
+      zBuf += a;
+    }else{
+      offset -= OVERFLOW_SIZE;
+    }
+    sqlitepager_unref(pOvfl);
+  }
+  if( amt>0 ){
+    return SQLITE_CORRUPT;
+  }
+  return SQLITE_OK;
+}
+
+/*
+** Read part of the key associated with cursor pCur.  A maximum
+** of "amt" bytes will be transfered into zBuf[].  The transfer
+** begins at "offset".  The number of bytes actually read is
+** returned. 
+**
+** Change:  It used to be that the amount returned will be smaller
+** than the amount requested if there are not enough bytes in the key
+** to satisfy the request.  But now, it must be the case that there
+** is enough data available to satisfy the request.  If not, an exception
+** is raised.  The change was made in an effort to boost performance
+** by eliminating unneeded tests.
+*/
+int sqliteBtreeKey(BtCursor *pCur, int offset, int amt, char *zBuf){
+  MemPage *pPage;
+
+  assert( amt>=0 );
+  assert( offset>=0 );
+  assert( pCur->pPage!=0 );
+  pPage = pCur->pPage;
+  if( pCur->idx >= pPage->nCell ){
+    return 0;
+  }
+  assert( amt+offset <= NKEY(pCur->pBt, pPage->apCell[pCur->idx]->h) );
+  getPayload(pCur, offset, amt, zBuf);
+  return amt;
+}
+
+/*
+** Set *pSize to the number of bytes of data in the entry the
+** cursor currently points to.  Always return SQLITE_OK.
+** Failure is not possible.  If the cursor is not currently
+** pointing to an entry (which can happen, for example, if
+** the database is empty) then *pSize is set to 0.
+*/
+int sqliteBtreeDataSize(BtCursor *pCur, int *pSize){
+  Cell *pCell;
+  MemPage *pPage;
+
+  pPage = pCur->pPage;
+  assert( pPage!=0 );
+  if( pCur->idx >= pPage->nCell ){
+    *pSize = 0;
+  }else{
+    pCell = pPage->apCell[pCur->idx];
+    *pSize = NDATA(pCur->pBt, pCell->h);
+  }
+  return SQLITE_OK;
+}
+
+/*
+** Read part of the data associated with cursor pCur.  A maximum
+** of "amt" bytes will be transfered into zBuf[].  The transfer
+** begins at "offset".  The number of bytes actually read is
+** returned.  The amount returned will be smaller than the
+** amount requested if there are not enough bytes in the data
+** to satisfy the request.
+*/
+int sqliteBtreeData(BtCursor *pCur, int offset, int amt, char *zBuf){
+  Cell *pCell;
+  MemPage *pPage;
+
+  assert( amt>=0 );
+  assert( offset>=0 );
+  assert( pCur->pPage!=0 );
+  pPage = pCur->pPage;
+  if( pCur->idx >= pPage->nCell ){
+    return 0;
+  }
+  pCell = pPage->apCell[pCur->idx];
+  assert( amt+offset <= NDATA(pCur->pBt, pCell->h) );
+  getPayload(pCur, offset + NKEY(pCur->pBt, pCell->h), amt, zBuf);
+  return amt;
+}
+
+/*
+** Compare an external key against the key on the entry that pCur points to.
+**
+** The external key is pKey and is nKey bytes long.  The last nIgnore bytes
+** of the key associated with pCur are ignored, as if they do not exist.
+** (The normal case is for nIgnore to be zero in which case the entire
+** internal key is used in the comparison.)
+**
+** The comparison result is written to *pRes as follows:
+**
+**    *pRes<0    This means pCur<pKey
+**
+**    *pRes==0   This means pCur==pKey for all nKey bytes
+**
+**    *pRes>0    This means pCur>pKey
+**
+** When one key is an exact prefix of the other, the shorter key is
+** considered less than the longer one.  In order to be equal the
+** keys must be exactly the same length. (The length of the pCur key
+** is the actual key length minus nIgnore bytes.)
+*/
+int sqliteBtreeKeyCompare(
+  BtCursor *pCur,       /* Pointer to entry to compare against */
+  const void *pKey,     /* Key to compare against entry that pCur points to */
+  int nKey,             /* Number of bytes in pKey */
+  int nIgnore,          /* Ignore this many bytes at the end of pCur */
+  int *pResult          /* Write the result here */
+){
+  Pgno nextPage;
+  int n, c, rc, nLocal;
+  Cell *pCell;
+  Btree *pBt = pCur->pBt;
+  const char *zKey  = (const char*)pKey;
+
+  assert( pCur->pPage );
+  assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
+  pCell = pCur->pPage->apCell[pCur->idx];
+  nLocal = NKEY(pBt, pCell->h) - nIgnore;
+  if( nLocal<0 ) nLocal = 0;
+  n = nKey<nLocal ? nKey : nLocal;
+  if( n>MX_LOCAL_PAYLOAD ){
+    n = MX_LOCAL_PAYLOAD;
+  }
+  c = memcmp(pCell->aPayload, zKey, n);
+  if( c!=0 ){
+    *pResult = c;
+    return SQLITE_OK;
+  }
+  zKey += n;
+  nKey -= n;
+  nLocal -= n;
+  nextPage = SWAB32(pBt, pCell->ovfl);
+  while( nKey>0 && nLocal>0 ){
+    OverflowPage *pOvfl;
+    if( nextPage==0 ){
+      return SQLITE_CORRUPT;
+    }
+    rc = sqlitepager_get(pBt->pPager, nextPage, (void**)&pOvfl);
+    if( rc ){
+      return rc;
+    }
+    nextPage = SWAB32(pBt, pOvfl->iNext);
+    n = nKey<nLocal ? nKey : nLocal;
+    if( n>OVERFLOW_SIZE ){
+      n = OVERFLOW_SIZE;
+    }
+    c = memcmp(pOvfl->aPayload, zKey, n);
+    sqlitepager_unref(pOvfl);
+    if( c!=0 ){
+      *pResult = c;
+      return SQLITE_OK;
+    }
+    nKey -= n;
+    nLocal -= n;
+    zKey += n;
+  }
+  if( c==0 ){
+    c = nLocal - nKey;
+  }
+  *pResult = c;
+  return SQLITE_OK;
+}
+
+/*
+** Move the cursor down to a new child page.  The newPgno argument is the
+** page number of the child page in the byte order of the disk image.
+*/
+static int moveToChild(BtCursor *pCur, int newPgno){
+  int rc;
+  MemPage *pNewPage;
+  Btree *pBt = pCur->pBt;
+
+  newPgno = SWAB32(pBt, newPgno);
+  rc = sqlitepager_get(pBt->pPager, newPgno, (void**)&pNewPage);
+  if( rc ) return rc;
+  rc = initPage(pBt, pNewPage, newPgno, pCur->pPage);
+  if( rc ) return rc;
+  assert( pCur->idx>=pCur->pPage->nCell
+          || pCur->pPage->apCell[pCur->idx]->h.leftChild==SWAB32(pBt,newPgno) );
+  assert( pCur->idx<pCur->pPage->nCell
+          || pCur->pPage->u.hdr.rightChild==SWAB32(pBt,newPgno) );
+  pNewPage->idxParent = pCur->idx;
+  pCur->pPage->idxShift = 0;
+  sqlitepager_unref(pCur->pPage);
+  pCur->pPage = pNewPage;
+  pCur->idx = 0;
+  return SQLITE_OK;
+}
+
+/*
+** Move the cursor up to the parent page.
+**
+** pCur->idx is set to the cell index that contains the pointer
+** to the page we are coming from.  If we are coming from the
+** right-most child page then pCur->idx is set to one more than
+** the largest cell index.
+*/
+static void moveToParent(BtCursor *pCur){
+  Pgno oldPgno;
+  MemPage *pParent;
+  MemPage *pPage;
+  int idxParent;
+  pPage = pCur->pPage;
+  assert( pPage!=0 );
+  pParent = pPage->pParent;
+  assert( pParent!=0 );
+  idxParent = pPage->idxParent;
+  sqlitepager_ref(pParent);
+  sqlitepager_unref(pPage);
+  pCur->pPage = pParent;
+  assert( pParent->idxShift==0 );
+  if( pParent->idxShift==0 ){
+    pCur->idx = idxParent;
+#ifndef NDEBUG  
+    /* Verify that pCur->idx is the correct index to point back to the child
+    ** page we just came from 
+    */
+    oldPgno = SWAB32(pCur->pBt, sqlitepager_pagenumber(pPage));
+    if( pCur->idx<pParent->nCell ){
+      assert( pParent->apCell[idxParent]->h.leftChild==oldPgno );
+    }else{
+      assert( pParent->u.hdr.rightChild==oldPgno );
+    }
+#endif
+  }else{
+    /* The MemPage.idxShift flag indicates that cell indices might have 
+    ** changed since idxParent was set and hence idxParent might be out
+    ** of date.  So recompute the parent cell index by scanning all cells
+    ** and locating the one that points to the child we just came from.
+    */
+    int i;
+    pCur->idx = pParent->nCell;
+    oldPgno = SWAB32(pCur->pBt, sqlitepager_pagenumber(pPage));
+    for(i=0; i<pParent->nCell; i++){
+      if( pParent->apCell[i]->h.leftChild==oldPgno ){
+        pCur->idx = i;
+        break;
+      }
+    }
+  }
+}
+
+/*
+** Move the cursor to the root page
+*/
+static int moveToRoot(BtCursor *pCur){
+  MemPage *pNew;
+  int rc;
+  Btree *pBt = pCur->pBt;
+
+  rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pNew);
+  if( rc ) return rc;
+  rc = initPage(pBt, pNew, pCur->pgnoRoot, 0);
+  if( rc ) return rc;
+  sqlitepager_unref(pCur->pPage);
+  pCur->pPage = pNew;
+  pCur->idx = 0;
+  return SQLITE_OK;
+}
+
+/*
+** Move the cursor down to the left-most leaf entry beneath the
+** entry to which it is currently pointing.
+*/
+static int moveToLeftmost(BtCursor *pCur){
+  Pgno pgno;
+  int rc;
+
+  while( (pgno = pCur->pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
+    rc = moveToChild(pCur, pgno);
+    if( rc ) return rc;
+  }
+  return SQLITE_OK;
+}
+
+/*
+** Move the cursor down to the right-most leaf entry beneath the
+** page to which it is currently pointing.  Notice the difference
+** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
+** finds the left-most entry beneath the *entry* whereas moveToRightmost()
+** finds the right-most entry beneath the *page*.
+*/
+static int moveToRightmost(BtCursor *pCur){
+  Pgno pgno;
+  int rc;
+
+  while( (pgno = pCur->pPage->u.hdr.rightChild)!=0 ){
+    pCur->idx = pCur->pPage->nCell;
+    rc = moveToChild(pCur, pgno);
+    if( rc ) return rc;
+  }
+  pCur->idx = pCur->pPage->nCell - 1;
+  return SQLITE_OK;
+}
+
+/* Move the cursor to the first entry in the table.  Return SQLITE_OK
+** on success.  Set *pRes to 0 if the cursor actually points to something
+** or set *pRes to 1 if the table is empty.
+*/
+int sqliteBtreeFirst(BtCursor *pCur, int *pRes){
+  int rc;
+  if( pCur->pPage==0 ) return SQLITE_ABORT;
+  rc = moveToRoot(pCur);
+  if( rc ) return rc;
+  if( pCur->pPage->nCell==0 ){
+    *pRes = 1;
+    return SQLITE_OK;
+  }
+  *pRes = 0;
+  rc = moveToLeftmost(pCur);
+  pCur->eSkip = SKIP_NONE;
+  return rc;
+}
+
+/* Move the cursor to the last entry in the table.  Return SQLITE_OK
+** on success.  Set *pRes to 0 if the cursor actually points to something
+** or set *pRes to 1 if the table is empty.
+*/
+int sqliteBtreeLast(BtCursor *pCur, int *pRes){
+  int rc;
+  if( pCur->pPage==0 ) return SQLITE_ABORT;
+  rc = moveToRoot(pCur);
+  if( rc ) return rc;
+  assert( pCur->pPage->isInit );
+  if( pCur->pPage->nCell==0 ){
+    *pRes = 1;
+    return SQLITE_OK;
+  }
+  *pRes = 0;
+  rc = moveToRightmost(pCur);
+  pCur->eSkip = SKIP_NONE;
+  return rc;
+}
+
+/* Move the cursor so that it points to an entry near pKey.
+** Return a success code.
+**
+** If an exact match is not found, then the cursor is always
+** left pointing at a leaf page which would hold the entry if it
+** were present.  The cursor might point to an entry that comes
+** before or after the key.
+**
+** The result of comparing the key with the entry to which the
+** cursor is left pointing is stored in pCur->iMatch.  The same
+** value is also written to *pRes if pRes!=NULL.  The meaning of
+** this value is as follows:
+**
+**     *pRes<0      The cursor is left pointing at an entry that
+**                  is smaller than pKey or if the table is empty
+**                  and the cursor is therefore left point to nothing.
+**
+**     *pRes==0     The cursor is left pointing at an entry that
+**                  exactly matches pKey.
+**
+**     *pRes>0      The cursor is left pointing at an entry that
+**                  is larger than pKey.
+*/
+int sqliteBtreeMoveto(BtCursor *pCur, const void *pKey, int nKey, int *pRes){
+  int rc;
+  if( pCur->pPage==0 ) return SQLITE_ABORT;
+  pCur->eSkip = SKIP_NONE;
+  rc = moveToRoot(pCur);
+  if( rc ) return rc;
+  for(;;){
+    int lwr, upr;
+    Pgno chldPg;
+    MemPage *pPage = pCur->pPage;
+    int c = -1;  /* pRes return if table is empty must be -1 */
+    lwr = 0;
+    upr = pPage->nCell-1;
+    while( lwr<=upr ){
+      pCur->idx = (lwr+upr)/2;
+      rc = sqliteBtreeKeyCompare(pCur, pKey, nKey, 0, &c);
+      if( rc ) return rc;
+      if( c==0 ){
+        pCur->iMatch = c;
+        if( pRes ) *pRes = 0;
+        return SQLITE_OK;
+      }
+      if( c<0 ){
+        lwr = pCur->idx+1;
+      }else{
+        upr = pCur->idx-1;
+      }
+    }
+    assert( lwr==upr+1 );
+    assert( pPage->isInit );
+    if( lwr>=pPage->nCell ){
+      chldPg = pPage->u.hdr.rightChild;
+    }else{
+      chldPg = pPage->apCell[lwr]->h.leftChild;
+    }
+    if( chldPg==0 ){
+      pCur->iMatch = c;
+      if( pRes ) *pRes = c;
+      return SQLITE_OK;
+    }
+    pCur->idx = lwr;
+    rc = moveToChild(pCur, chldPg);
+    if( rc ) return rc;
+  }
+  /* NOT REACHED */
+}
+
+/*
+** Advance the cursor to the next entry in the database.  If
+** successful then set *pRes=0.  If the cursor
+** was already pointing to the last entry in the database before
+** this routine was called, then set *pRes=1.
+*/
+int sqliteBtreeNext(BtCursor *pCur, int *pRes){
+  int rc;
+  MemPage *pPage = pCur->pPage;
+  assert( pRes!=0 );
+  if( pPage==0 ){
+    *pRes = 1;
+    return SQLITE_ABORT;
+  }
+  assert( pPage->isInit );
+  assert( pCur->eSkip!=SKIP_INVALID );
+  if( pPage->nCell==0 ){
+    *pRes = 1;
+    return SQLITE_OK;
+  }
+  assert( pCur->idx<pPage->nCell );
+  if( pCur->eSkip==SKIP_NEXT ){
+    pCur->eSkip = SKIP_NONE;
+    *pRes = 0;
+    return SQLITE_OK;
+  }
+  pCur->eSkip = SKIP_NONE;
+  pCur->idx++;
+  if( pCur->idx>=pPage->nCell ){
+    if( pPage->u.hdr.rightChild ){
+      rc = moveToChild(pCur, pPage->u.hdr.rightChild);
+      if( rc ) return rc;
+      rc = moveToLeftmost(pCur);
+      *pRes = 0;
+      return rc;
+    }
+    do{
+      if( pPage->pParent==0 ){
+        *pRes = 1;
+        return SQLITE_OK;
+      }
+      moveToParent(pCur);
+      pPage = pCur->pPage;
+    }while( pCur->idx>=pPage->nCell );
+    *pRes = 0;
+    return SQLITE_OK;
+  }
+  *pRes = 0;
+  if( pPage->u.hdr.rightChild==0 ){
+    return SQLITE_OK;
+  }
+  rc = moveToLeftmost(pCur);
+  return rc;
+}
+
+/*
+** Step the cursor to the back to the previous entry in the database.  If
+** successful then set *pRes=0.  If the cursor
+** was already pointing to the first entry in the database before
+** this routine was called, then set *pRes=1.
+*/
+int sqliteBtreePrevious(BtCursor *pCur, int *pRes){
+  int rc;
+  Pgno pgno;
+  MemPage *pPage;
+  pPage = pCur->pPage;
+  if( pPage==0 ){
+    *pRes = 1;
+    return SQLITE_ABORT;
+  }
+  assert( pPage->isInit );
+  assert( pCur->eSkip!=SKIP_INVALID );
+  if( pPage->nCell==0 ){
+    *pRes = 1;
+    return SQLITE_OK;
+  }
+  if( pCur->eSkip==SKIP_PREV ){
+    pCur->eSkip = SKIP_NONE;
+    *pRes = 0;
+    return SQLITE_OK;
+  }
+  pCur->eSkip = SKIP_NONE;
+  assert( pCur->idx>=0 );
+  if( (pgno = pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
+    rc = moveToChild(pCur, pgno);
+    if( rc ) return rc;
+    rc = moveToRightmost(pCur);
+  }else{
+    while( pCur->idx==0 ){
+      if( pPage->pParent==0 ){
+        if( pRes ) *pRes = 1;
+        return SQLITE_OK;
+      }
+      moveToParent(pCur);
+      pPage = pCur->pPage;
+    }
+    pCur->idx--;
+    rc = SQLITE_OK;
+  }
+  *pRes = 0;
+  return rc;
+}
+
+/*
+** Allocate a new page from the database file.
+**
+** The new page is marked as dirty.  (In other words, sqlitepager_write()
+** has already been called on the new page.)  The new page has also
+** been referenced and the calling routine is responsible for calling
+** sqlitepager_unref() on the new page when it is done.
+**
+** SQLITE_OK is returned on success.  Any other return value indicates
+** an error.  *ppPage and *pPgno are undefined in the event of an error.
+** Do not invoke sqlitepager_unref() on *ppPage if an error is returned.
+**
+** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
+** locate a page close to the page number "nearby".  This can be used in an
+** attempt to keep related pages close to each other in the database file,
+** which in turn can make database access faster.
+*/
+static int allocatePage(Btree *pBt, MemPage **ppPage, Pgno *pPgno, Pgno nearby){
+  PageOne *pPage1 = pBt->page1;
+  int rc;
+  if( pPage1->freeList ){
+    OverflowPage *pOvfl;
+    FreelistInfo *pInfo;
+
+    rc = sqlitepager_write(pPage1);
+    if( rc ) return rc;
+    SWAB_ADD(pBt, pPage1->nFree, -1);
+    rc = sqlitepager_get(pBt->pPager, SWAB32(pBt, pPage1->freeList),
+                        (void**)&pOvfl);
+    if( rc ) return rc;
+    rc = sqlitepager_write(pOvfl);
+    if( rc ){
+      sqlitepager_unref(pOvfl);
+      return rc;
+    }
+    pInfo = (FreelistInfo*)pOvfl->aPayload;
+    if( pInfo->nFree==0 ){
+      *pPgno = SWAB32(pBt, pPage1->freeList);
+      pPage1->freeList = pOvfl->iNext;
+      *ppPage = (MemPage*)pOvfl;
+    }else{
+      int closest, n;
+      n = SWAB32(pBt, pInfo->nFree);
+      if( n>1 && nearby>0 ){
+        int i, dist;
+        closest = 0;
+        dist = SWAB32(pBt, pInfo->aFree[0]) - nearby;
+        if( dist<0 ) dist = -dist;
+        for(i=1; i<n; i++){
+          int d2 = SWAB32(pBt, pInfo->aFree[i]) - nearby;
+          if( d2<0 ) d2 = -d2;
+          if( d2<dist ) closest = i;
+        }
+      }else{
+        closest = 0;
+      }
+      SWAB_ADD(pBt, pInfo->nFree, -1);
+      *pPgno = SWAB32(pBt, pInfo->aFree[closest]);
+      pInfo->aFree[closest] = pInfo->aFree[n-1];
+      rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
+      sqlitepager_unref(pOvfl);
+      if( rc==SQLITE_OK ){
+        sqlitepager_dont_rollback(*ppPage);
+        rc = sqlitepager_write(*ppPage);
+      }
+    }
+  }else{
+    *pPgno = sqlitepager_pagecount(pBt->pPager) + 1;
+    rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
+    if( rc ) return rc;
+    rc = sqlitepager_write(*ppPage);
+  }
+  return rc;
+}
+
+/*
+** Add a page of the database file to the freelist.  Either pgno or
+** pPage but not both may be 0. 
+**
+** sqlitepager_unref() is NOT called for pPage.
+*/
+static int freePage(Btree *pBt, void *pPage, Pgno pgno){
+  PageOne *pPage1 = pBt->page1;
+  OverflowPage *pOvfl = (OverflowPage*)pPage;
+  int rc;
+  int needUnref = 0;
+  MemPage *pMemPage;
+
+  if( pgno==0 ){
+    assert( pOvfl!=0 );
+    pgno = sqlitepager_pagenumber(pOvfl);
+  }
+  assert( pgno>2 );
+  assert( sqlitepager_pagenumber(pOvfl)==pgno );
+  pMemPage = (MemPage*)pPage;
+  pMemPage->isInit = 0;
+  if( pMemPage->pParent ){
+    sqlitepager_unref(pMemPage->pParent);
+    pMemPage->pParent = 0;
+  }
+  rc = sqlitepager_write(pPage1);
+  if( rc ){
+    return rc;
+  }
+  SWAB_ADD(pBt, pPage1->nFree, 1);
+  if( pPage1->nFree!=0 && pPage1->freeList!=0 ){
+    OverflowPage *pFreeIdx;
+    rc = sqlitepager_get(pBt->pPager, SWAB32(pBt, pPage1->freeList),
+                        (void**)&pFreeIdx);
+    if( rc==SQLITE_OK ){
+      FreelistInfo *pInfo = (FreelistInfo*)pFreeIdx->aPayload;
+      int n = SWAB32(pBt, pInfo->nFree);
+      if( n<(sizeof(pInfo->aFree)/sizeof(pInfo->aFree[0])) ){
+        rc = sqlitepager_write(pFreeIdx);
+        if( rc==SQLITE_OK ){
+          pInfo->aFree[n] = SWAB32(pBt, pgno);
+          SWAB_ADD(pBt, pInfo->nFree, 1);
+          sqlitepager_unref(pFreeIdx);
+          sqlitepager_dont_write(pBt->pPager, pgno);
+          return rc;
+        }
+      }
+      sqlitepager_unref(pFreeIdx);
+    }
+  }
+  if( pOvfl==0 ){
+    assert( pgno>0 );
+    rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pOvfl);
+    if( rc ) return rc;
+    needUnref = 1;
+  }
+  rc = sqlitepager_write(pOvfl);
+  if( rc ){
+    if( needUnref ) sqlitepager_unref(pOvfl);
+    return rc;
+  }
+  pOvfl->iNext = pPage1->freeList;
+  pPage1->freeList = SWAB32(pBt, pgno);
+  memset(pOvfl->aPayload, 0, OVERFLOW_SIZE);
+  if( needUnref ) rc = sqlitepager_unref(pOvfl);
+  return rc;
+}
+
+/*
+** Erase all the data out of a cell.  This involves returning overflow
+** pages back the freelist.
+*/
+static int clearCell(Btree *pBt, Cell *pCell){
+  Pager *pPager = pBt->pPager;
+  OverflowPage *pOvfl;
+  Pgno ovfl, nextOvfl;
+  int rc;
+
+  if( NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h) <= MX_LOCAL_PAYLOAD ){
+    return SQLITE_OK;
+  }
+  ovfl = SWAB32(pBt, pCell->ovfl);
+  pCell->ovfl = 0;
+  while( ovfl ){
+    rc = sqlitepager_get(pPager, ovfl, (void**)&pOvfl);
+    if( rc ) return rc;
+    nextOvfl = SWAB32(pBt, pOvfl->iNext);
+    rc = freePage(pBt, pOvfl, ovfl);
+    if( rc ) return rc;
+    sqlitepager_unref(pOvfl);
+    ovfl = nextOvfl;
+  }
+  return SQLITE_OK;
+}
+
+/*
+** Create a new cell from key and data.  Overflow pages are allocated as
+** necessary and linked to this cell.  
+*/
+static int fillInCell(
+  Btree *pBt,              /* The whole Btree.  Needed to allocate pages */
+  Cell *pCell,             /* Populate this Cell structure */
+  const void *pKey, int nKey,    /* The key */
+  const void *pData,int nData    /* The data */
+){
+  OverflowPage *pOvfl, *pPrior;
+  Pgno *pNext;
+  int spaceLeft;
+  int n, rc;
+  int nPayload;
+  const char *pPayload;
+  char *pSpace;
+  Pgno nearby = 0;
+
+  pCell->h.leftChild = 0;
+  pCell->h.nKey = SWAB16(pBt, nKey & 0xffff);
+  pCell->h.nKeyHi = nKey >> 16;
+  pCell->h.nData = SWAB16(pBt, nData & 0xffff);
+  pCell->h.nDataHi = nData >> 16;
+  pCell->h.iNext = 0;
+
+  pNext = &pCell->ovfl;
+  pSpace = pCell->aPayload;
+  spaceLeft = MX_LOCAL_PAYLOAD;
+  pPayload = pKey;
+  pKey = 0;
+  nPayload = nKey;
+  pPrior = 0;
+  while( nPayload>0 ){
+    if( spaceLeft==0 ){
+      rc = allocatePage(pBt, (MemPage**)&pOvfl, pNext, nearby);
+      if( rc ){
+        *pNext = 0;
+      }else{
+        nearby = *pNext;
+      }
+      if( pPrior ) sqlitepager_unref(pPrior);
+      if( rc ){
+        clearCell(pBt, pCell);
+        return rc;
+      }
+      if( pBt->needSwab ) *pNext = swab32(*pNext);
+      pPrior = pOvfl;
+      spaceLeft = OVERFLOW_SIZE;
+      pSpace = pOvfl->aPayload;
+      pNext = &pOvfl->iNext;
+    }
+    n = nPayload;
+    if( n>spaceLeft ) n = spaceLeft;
+    memcpy(pSpace, pPayload, n);
+    nPayload -= n;
+    if( nPayload==0 && pData ){
+      pPayload = pData;
+      nPayload = nData;
+      pData = 0;
+    }else{
+      pPayload += n;
+    }
+    spaceLeft -= n;
+    pSpace += n;
+  }
+  *pNext = 0;
+  if( pPrior ){
+    sqlitepager_unref(pPrior);
+  }
+  return SQLITE_OK;
+}
+
+/*
+** Change the MemPage.pParent pointer on the page whose number is
+** given in the second argument so that MemPage.pParent holds the
+** pointer in the third argument.
+*/
+static void reparentPage(Pager *pPager, Pgno pgno, MemPage *pNewParent,int idx){
+  MemPage *pThis;
+
+  if( pgno==0 ) return;
+  assert( pPager!=0 );
+  pThis = sqlitepager_lookup(pPager, pgno);
+  if( pThis && pThis->isInit ){
+    if( pThis->pParent!=pNewParent ){
+      if( pThis->pParent ) sqlitepager_unref(pThis->pParent);
+      pThis->pParent = pNewParent;
+      if( pNewParent ) sqlitepager_ref(pNewParent);
+    }
+    pThis->idxParent = idx;
+    sqlitepager_unref(pThis);
+  }
+}
+
+/*
+** Reparent all children of the given page to be the given page.
+** In other words, for every child of pPage, invoke reparentPage()
+** to make sure that each child knows that pPage is its parent.
+**
+** This routine gets called after you memcpy() one page into
+** another.
+*/
+static void reparentChildPages(Btree *pBt, MemPage *pPage){
+  int i;
+  Pager *pPager = pBt->pPager;
+  for(i=0; i<pPage->nCell; i++){
+    reparentPage(pPager, SWAB32(pBt, pPage->apCell[i]->h.leftChild), pPage, i);
+  }
+  reparentPage(pPager, SWAB32(pBt, pPage->u.hdr.rightChild), pPage, i);
+  pPage->idxShift = 0;
+}
+
+/*
+** Remove the i-th cell from pPage.  This routine effects pPage only.
+** The cell content is not freed or deallocated.  It is assumed that
+** the cell content has been copied someplace else.  This routine just
+** removes the reference to the cell from pPage.
+**
+** "sz" must be the number of bytes in the cell.
+**
+** Do not bother maintaining the integrity of the linked list of Cells.
+** Only the pPage->apCell[] array is important.  The relinkCellList() 
+** routine will be called soon after this routine in order to rebuild 
+** the linked list.
+*/
+static void dropCell(Btree *pBt, MemPage *pPage, int idx, int sz){
+  int j;
+  assert( idx>=0 && idx<pPage->nCell );
+  assert( sz==cellSize(pBt, pPage->apCell[idx]) );
+  assert( sqlitepager_iswriteable(pPage) );
+  freeSpace(pBt, pPage, Addr(pPage->apCell[idx]) - Addr(pPage), sz);
+  for(j=idx; j<pPage->nCell-1; j++){
+    pPage->apCell[j] = pPage->apCell[j+1];
+  }
+  pPage->nCell--;
+  pPage->idxShift = 1;
+}
+
+/*
+** Insert a new cell on pPage at cell index "i".  pCell points to the
+** content of the cell.
+**
+** If the cell content will fit on the page, then put it there.  If it
+** will not fit, then just make pPage->apCell[i] point to the content
+** and set pPage->isOverfull.  
+**
+** Do not bother maintaining the integrity of the linked list of Cells.
+** Only the pPage->apCell[] array is important.  The relinkCellList() 
+** routine will be called soon after this routine in order to rebuild 
+** the linked list.
+*/
+static void insertCell(Btree *pBt, MemPage *pPage, int i, Cell *pCell, int sz){
+  int idx, j;
+  assert( i>=0 && i<=pPage->nCell );
+  assert( sz==cellSize(pBt, pCell) );
+  assert( sqlitepager_iswriteable(pPage) );
+  idx = allocateSpace(pBt, pPage, sz);
+  for(j=pPage->nCell; j>i; j--){
+    pPage->apCell[j] = pPage->apCell[j-1];
+  }
+  pPage->nCell++;
+  if( idx<=0 ){
+    pPage->isOverfull = 1;
+    pPage->apCell[i] = pCell;
+  }else{
+    memcpy(&pPage->u.aDisk[idx], pCell, sz);
+    pPage->apCell[i] = (Cell*)&pPage->u.aDisk[idx];
+  }
+  pPage->idxShift = 1;
+}
+
+/*
+** Rebuild the linked list of cells on a page so that the cells
+** occur in the order specified by the pPage->apCell[] array.  
+** Invoke this routine once to repair damage after one or more
+** invocations of either insertCell() or dropCell().
+*/
+static void relinkCellList(Btree *pBt, MemPage *pPage){
+  int i;
+  u16 *pIdx;
+  assert( sqlitepager_iswriteable(pPage) );
+  pIdx = &pPage->u.hdr.firstCell;
+  for(i=0; i<pPage->nCell; i++){
+    int idx = Addr(pPage->apCell[i]) - Addr(pPage);
+    assert( idx>0 && idx<SQLITE_PAGE_SIZE );
+    *pIdx = SWAB16(pBt, idx);
+    pIdx = &pPage->apCell[i]->h.iNext;
+  }
+  *pIdx = 0;
+}
+
+/*
+** Make a copy of the contents of pFrom into pTo.  The pFrom->apCell[]
+** pointers that point into pFrom->u.aDisk[] must be adjusted to point
+** into pTo->u.aDisk[] instead.  But some pFrom->apCell[] entries might
+** not point to pFrom->u.aDisk[].  Those are unchanged.
+*/
+static void copyPage(MemPage *pTo, MemPage *pFrom){
+  uptr from, to;
+  int i;
+  memcpy(pTo->u.aDisk, pFrom->u.aDisk, SQLITE_PAGE_SIZE);
+  pTo->pParent = 0;
+  pTo->isInit = 1;
+  pTo->nCell = pFrom->nCell;
+  pTo->nFree = pFrom->nFree;
+  pTo->isOverfull = pFrom->isOverfull;
+  to = Addr(pTo);
+  from = Addr(pFrom);
+  for(i=0; i<pTo->nCell; i++){
+    uptr x = Addr(pFrom->apCell[i]);
+    if( x>from && x<from+SQLITE_PAGE_SIZE ){
+      *((uptr*)&pTo->apCell[i]) = x + to - from;
+    }else{
+      pTo->apCell[i] = pFrom->apCell[i];
+    }
+  }
+}
+
+/*
+** The following parameters determine how many adjacent pages get involved
+** in a balancing operation.  NN is the number of neighbors on either side
+** of the page that participate in the balancing operation.  NB is the
+** total number of pages that participate, including the target page and
+** NN neighbors on either side.
+**
+** The minimum value of NN is 1 (of course).  Increasing NN above 1
+** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
+** in exchange for a larger degradation in INSERT and UPDATE performance.
+** The value of NN appears to give the best results overall.
+*/
+#define NN 1             /* Number of neighbors on either side of pPage */
+#define NB (NN*2+1)      /* Total pages involved in the balance */
+
+/*
+** This routine redistributes Cells on pPage and up to two siblings
+** of pPage so that all pages have about the same amount of free space.
+** Usually one sibling on either side of pPage is used in the balancing,
+** though both siblings might come from one side if pPage is the first
+** or last child of its parent.  If pPage has fewer than two siblings
+** (something which can only happen if pPage is the root page or a 
+** child of root) then all available siblings participate in the balancing.
+**
+** The number of siblings of pPage might be increased or decreased by
+** one in an effort to keep pages between 66% and 100% full. The root page
+** is special and is allowed to be less than 66% full. If pPage is 
+** the root page, then the depth of the tree might be increased
+** or decreased by one, as necessary, to keep the root page from being
+** overfull or empty.
+**
+** This routine calls relinkCellList() on its input page regardless of
+** whether or not it does any real balancing.  Client routines will typically
+** invoke insertCell() or dropCell() before calling this routine, so we
+** need to call relinkCellList() to clean up the mess that those other
+** routines left behind.
+**
+** pCur is left pointing to the same cell as when this routine was called
+** even if that cell gets moved to a different page.  pCur may be NULL.
+** Set the pCur parameter to NULL if you do not care about keeping track
+** of a cell as that will save this routine the work of keeping track of it.
+**
+** Note that when this routine is called, some of the Cells on pPage
+** might not actually be stored in pPage->u.aDisk[].  This can happen
+** if the page is overfull.  Part of the job of this routine is to
+** make sure all Cells for pPage once again fit in pPage->u.aDisk[].
+**
+** In the course of balancing the siblings of pPage, the parent of pPage
+** might become overfull or underfull.  If that happens, then this routine
+** is called recursively on the parent.
+**
+** If this routine fails for any reason, it might leave the database
+** in a corrupted state.  So if this routine fails, the database should
+** be rolled back.
+*/
+static int balance(Btree *pBt, MemPage *pPage, BtCursor *pCur){
+  MemPage *pParent;            /* The parent of pPage */
+  int nCell;                   /* Number of cells in apCell[] */
+  int nOld;                    /* Number of pages in apOld[] */
+  int nNew;                    /* Number of pages in apNew[] */
+  int nDiv;                    /* Number of cells in apDiv[] */
+  int i, j, k;                 /* Loop counters */
+  int idx;                     /* Index of pPage in pParent->apCell[] */
+  int nxDiv;                   /* Next divider slot in pParent->apCell[] */
+  int rc;                      /* The return code */
+  int iCur;                    /* apCell[iCur] is the cell of the cursor */
+  MemPage *pOldCurPage;        /* The cursor originally points to this page */
+  int subtotal;                /* Subtotal of bytes in cells on one page */
+  MemPage *extraUnref = 0;     /* A page that needs to be unref-ed */
+  MemPage *apOld[NB];          /* pPage and up to two siblings */
+  Pgno pgnoOld[NB];            /* Page numbers for each page in apOld[] */
+  MemPage *apNew[NB+1];        /* pPage and up to NB siblings after balancing */
+  Pgno pgnoNew[NB+1];          /* Page numbers for each page in apNew[] */
+  int idxDiv[NB];              /* Indices of divider cells in pParent */
+  Cell *apDiv[NB];             /* Divider cells in pParent */
+  Cell aTemp[NB];              /* Temporary holding area for apDiv[] */
+  int cntNew[NB+1];            /* Index in apCell[] of cell after i-th page */
+  int szNew[NB+1];             /* Combined size of cells place on i-th page */
+  MemPage aOld[NB];            /* Temporary copies of pPage and its siblings */
+  Cell *apCell[(MX_CELL+2)*NB]; /* All cells from pages being balanced */
+  int szCell[(MX_CELL+2)*NB];  /* Local size of all cells */
+
+  /* 
+  ** Return without doing any work if pPage is neither overfull nor
+  ** underfull.
+  */
+  assert( sqlitepager_iswriteable(pPage) );
+  if( !pPage->isOverfull && pPage->nFree<SQLITE_PAGE_SIZE/2 
+        && pPage->nCell>=2){
+    relinkCellList(pBt, pPage);
+    return SQLITE_OK;
+  }
+
+  /*
+  ** Find the parent of the page to be balanceed.
+  ** If there is no parent, it means this page is the root page and
+  ** special rules apply.
+  */
+  pParent = pPage->pParent;
+  if( pParent==0 ){
+    Pgno pgnoChild;
+    MemPage *pChild;
+    assert( pPage->isInit );
+    if( pPage->nCell==0 ){
+      if( pPage->u.hdr.rightChild ){
+        /*
+        ** The root page is empty.  Copy the one child page
+        ** into the root page and return.  This reduces the depth
+        ** of the BTree by one.
+        */
+        pgnoChild = SWAB32(pBt, pPage->u.hdr.rightChild);
+        rc = sqlitepager_get(pBt->pPager, pgnoChild, (void**)&pChild);
+        if( rc ) return rc;
+        memcpy(pPage, pChild, SQLITE_PAGE_SIZE);
+        pPage->isInit = 0;
+        rc = initPage(pBt, pPage, sqlitepager_pagenumber(pPage), 0);
+        assert( rc==SQLITE_OK );
+        reparentChildPages(pBt, pPage);
+        if( pCur && pCur->pPage==pChild ){
+          sqlitepager_unref(pChild);
+          pCur->pPage = pPage;
+          sqlitepager_ref(pPage);
+        }
+        freePage(pBt, pChild, pgnoChild);
+        sqlitepager_unref(pChild);
+      }else{
+        relinkCellList(pBt, pPage);
+      }
+      return SQLITE_OK;
+    }
+    if( !pPage->isOverfull ){
+      /* It is OK for the root page to be less than half full.
+      */
+      relinkCellList(pBt, pPage);
+      return SQLITE_OK;
+    }
+    /*
+    ** If we get to here, it means the root page is overfull.
+    ** When this happens, Create a new child page and copy the
+    ** contents of the root into the child.  Then make the root
+    ** page an empty page with rightChild pointing to the new
+    ** child.  Then fall thru to the code below which will cause
+    ** the overfull child page to be split.
+    */
+    rc = sqlitepager_write(pPage);
+    if( rc ) return rc;
+    rc = allocatePage(pBt, &pChild, &pgnoChild, sqlitepager_pagenumber(pPage));
+    if( rc ) return rc;
+    assert( sqlitepager_iswriteable(pChild) );
+    copyPage(pChild, pPage);
+    pChild->pParent = pPage;
+    pChild->idxParent = 0;
+    sqlitepager_ref(pPage);
+    pChild->isOverfull = 1;
+    if( pCur && pCur->pPage==pPage ){
+      sqlitepager_unref(pPage);
+      pCur->pPage = pChild;
+    }else{
+      extraUnref = pChild;
+    }
+    zeroPage(pBt, pPage);
+    pPage->u.hdr.rightChild = SWAB32(pBt, pgnoChild);
+    pParent = pPage;
+    pPage = pChild;
+  }
+  rc = sqlitepager_write(pParent);
+  if( rc ) return rc;
+  assert( pParent->isInit );
+  
+  /*
+  ** Find the Cell in the parent page whose h.leftChild points back
+  ** to pPage.  The "idx" variable is the index of that cell.  If pPage
+  ** is the rightmost child of pParent then set idx to pParent->nCell 
+  */
+  if( pParent->idxShift ){
+    Pgno pgno, swabPgno;
+    pgno = sqlitepager_pagenumber(pPage);
+    swabPgno = SWAB32(pBt, pgno);
+    for(idx=0; idx<pParent->nCell; idx++){
+      if( pParent->apCell[idx]->h.leftChild==swabPgno ){
+        break;
+      }
+    }
+    assert( idx<pParent->nCell || pParent->u.hdr.rightChild==swabPgno );
+  }else{
+    idx = pPage->idxParent;
+  }
+
+  /*
+  ** Initialize variables so that it will be safe to jump
+  ** directly to balance_cleanup at any moment.
+  */
+  nOld = nNew = 0;
+  sqlitepager_ref(pParent);
+
+  /*
+  ** Find sibling pages to pPage and the Cells in pParent that divide
+  ** the siblings.  An attempt is made to find NN siblings on either
+  ** side of pPage.  More siblings are taken from one side, however, if
+  ** pPage there are fewer than NN siblings on the other side.  If pParent
+  ** has NB or fewer children then all children of pParent are taken.
+  */
+  nxDiv = idx - NN;
+  if( nxDiv + NB > pParent->nCell ){
+    nxDiv = pParent->nCell - NB + 1;
+  }
+  if( nxDiv<0 ){
+    nxDiv = 0;
+  }
+  nDiv = 0;
+  for(i=0, k=nxDiv; i<NB; i++, k++){
+    if( k<pParent->nCell ){
+      idxDiv[i] = k;
+      apDiv[i] = pParent->apCell[k];
+      nDiv++;
+      pgnoOld[i] = SWAB32(pBt, apDiv[i]->h.leftChild);
+    }else if( k==pParent->nCell ){
+      pgnoOld[i] = SWAB32(pBt, pParent->u.hdr.rightChild);
+    }else{
+      break;
+    }
+    rc = sqlitepager_get(pBt->pPager, pgnoOld[i], (void**)&apOld[i]);
+    if( rc ) goto balance_cleanup;
+    rc = initPage(pBt, apOld[i], pgnoOld[i], pParent);
+    if( rc ) goto balance_cleanup;
+    apOld[i]->idxParent = k;
+    nOld++;
+  }
+
+  /*
+  ** Set iCur to be the index in apCell[] of the cell that the cursor
+  ** is pointing to.  We will need this later on in order to keep the
+  ** cursor pointing at the same cell.  If pCur points to a page that
+  ** has no involvement with this rebalancing, then set iCur to a large
+  ** number so that the iCur==j tests always fail in the main cell
+  ** distribution loop below.
+  */
+  if( pCur ){
+    iCur = 0;
+    for(i=0; i<nOld; i++){
+      if( pCur->pPage==apOld[i] ){
+        iCur += pCur->idx;
+        break;
+      }
+      iCur += apOld[i]->nCell;
+      if( i<nOld-1 && pCur->pPage==pParent && pCur->idx==idxDiv[i] ){
+        break;
+      }
+      iCur++;
+    }
+    pOldCurPage = pCur->pPage;
+  }
+
+  /*
+  ** Make copies of the content of pPage and its siblings into aOld[].
+  ** The rest of this function will use data from the copies rather
+  ** that the original pages since the original pages will be in the
+  ** process of being overwritten.
+  */
+  for(i=0; i<nOld; i++){
+    copyPage(&aOld[i], apOld[i]);
+  }
+
+  /*
+  ** Load pointers to all cells on sibling pages and the divider cells
+  ** into the local apCell[] array.  Make copies of the divider cells
+  ** into aTemp[] and remove the the divider Cells from pParent.
+  */
+  nCell = 0;
+  for(i=0; i<nOld; i++){
+    MemPage *pOld = &aOld[i];
+    for(j=0; j<pOld->nCell; j++){
+      apCell[nCell] = pOld->apCell[j];
+      szCell[nCell] = cellSize(pBt, apCell[nCell]);
+      nCell++;
+    }
+    if( i<nOld-1 ){
+      szCell[nCell] = cellSize(pBt, apDiv[i]);
+      memcpy(&aTemp[i], apDiv[i], szCell[nCell]);
+      apCell[nCell] = &aTemp[i];
+      dropCell(pBt, pParent, nxDiv, szCell[nCell]);
+      assert( SWAB32(pBt, apCell[nCell]->h.leftChild)==pgnoOld[i] );
+      apCell[nCell]->h.leftChild = pOld->u.hdr.rightChild;
+      nCell++;
+    }
+  }
+
+  /*
+  ** Figure out the number of pages needed to hold all nCell cells.
+  ** Store this number in "k".  Also compute szNew[] which is the total
+  ** size of all cells on the i-th page and cntNew[] which is the index
+  ** in apCell[] of the cell that divides path i from path i+1.  
+  ** cntNew[k] should equal nCell.
+  **
+  ** This little patch of code is critical for keeping the tree
+  ** balanced. 
+  */
+  for(subtotal=k=i=0; i<nCell; i++){
+    subtotal += szCell[i];
+    if( subtotal > USABLE_SPACE ){
+      szNew[k] = subtotal - szCell[i];
+      cntNew[k] = i;
+      subtotal = 0;
+      k++;
+    }
+  }
+  szNew[k] = subtotal;
+  cntNew[k] = nCell;
+  k++;
+  for(i=k-1; i>0; i--){
+    while( szNew[i]<USABLE_SPACE/2 ){
+      cntNew[i-1]--;
+      assert( cntNew[i-1]>0 );
+      szNew[i] += szCell[cntNew[i-1]];
+      szNew[i-1] -= szCell[cntNew[i-1]-1];
+    }
+  }
+  assert( cntNew[0]>0 );
+
+  /*
+  ** Allocate k new pages.  Reuse old pages where possible.
+  */
+  for(i=0; i<k; i++){
+    if( i<nOld ){
+      apNew[i] = apOld[i];
+      pgnoNew[i] = pgnoOld[i];
+      apOld[i] = 0;
+      sqlitepager_write(apNew[i]);
+    }else{
+      rc = allocatePage(pBt, &apNew[i], &pgnoNew[i], pgnoNew[i-1]);
+      if( rc ) goto balance_cleanup;
+    }
+    nNew++;
+    zeroPage(pBt, apNew[i]);
+    apNew[i]->isInit = 1;
+  }
+
+  /* Free any old pages that were not reused as new pages.
+  */
+  while( i<nOld ){
+    rc = freePage(pBt, apOld[i], pgnoOld[i]);
+    if( rc ) goto balance_cleanup;
+    sqlitepager_unref(apOld[i]);
+    apOld[i] = 0;
+    i++;
+  }
+
+  /*
+  ** Put the new pages in accending order.  This helps to
+  ** keep entries in the disk file in order so that a scan
+  ** of the table is a linear scan through the file.  That
+  ** in turn helps the operating system to deliver pages
+  ** from the disk more rapidly.
+  **
+  ** An O(n^2) insertion sort algorithm is used, but since
+  ** n is never more than NB (a small constant), that should
+  ** not be a problem.
+  **
+  ** When NB==3, this one optimization makes the database
+  ** about 25% faster for large insertions and deletions.
+  */
+  for(i=0; i<k-1; i++){
+    int minV = pgnoNew[i];
+    int minI = i;
+    for(j=i+1; j<k; j++){
+      if( pgnoNew[j]<minV ){
+        minI = j;
+        minV = pgnoNew[j];
+      }
+    }
+    if( minI>i ){
+      int t;
+      MemPage *pT;
+      t = pgnoNew[i];
+      pT = apNew[i];
+      pgnoNew[i] = pgnoNew[minI];
+      apNew[i] = apNew[minI];
+      pgnoNew[minI] = t;
+      apNew[minI] = pT;
+    }
+  }
+
+  /*
+  ** Evenly distribute the data in apCell[] across the new pages.
+  ** Insert divider cells into pParent as necessary.
+  */
+  j = 0;
+  for(i=0; i<nNew; i++){
+    MemPage *pNew = apNew[i];
+    while( j<cntNew[i] ){
+      assert( pNew->nFree>=szCell[j] );
+      if( pCur && iCur==j ){ pCur->pPage = pNew; pCur->idx = pNew->nCell; }
+      insertCell(pBt, pNew, pNew->nCell, apCell[j], szCell[j]);
+      j++;
+    }
+    assert( pNew->nCell>0 );
+    assert( !pNew->isOverfull );
+    relinkCellList(pBt, pNew);
+    if( i<nNew-1 && j<nCell ){
+      pNew->u.hdr.rightChild = apCell[j]->h.leftChild;
+      apCell[j]->h.leftChild = SWAB32(pBt, pgnoNew[i]);
+      if( pCur && iCur==j ){ pCur->pPage = pParent; pCur->idx = nxDiv; }
+      insertCell(pBt, pParent, nxDiv, apCell[j], szCell[j]);
+      j++;
+      nxDiv++;
+    }
+  }
+  assert( j==nCell );
+  apNew[nNew-1]->u.hdr.rightChild = aOld[nOld-1].u.hdr.rightChild;
+  if( nxDiv==pParent->nCell ){
+    pParent->u.hdr.rightChild = SWAB32(pBt, pgnoNew[nNew-1]);
+  }else{
+    pParent->apCell[nxDiv]->h.leftChild = SWAB32(pBt, pgnoNew[nNew-1]);
+  }
+  if( pCur ){
+    if( j<=iCur && pCur->pPage==pParent && pCur->idx>idxDiv[nOld-1] ){
+      assert( pCur->pPage==pOldCurPage );
+      pCur->idx += nNew - nOld;
+    }else{
+      assert( pOldCurPage!=0 );
+      sqlitepager_ref(pCur->pPage);
+      sqlitepager_unref(pOldCurPage);
+    }
+  }
+
+  /*
+  ** Reparent children of all cells.
+  */
+  for(i=0; i<nNew; i++){
+    reparentChildPages(pBt, apNew[i]);
+  }
+  reparentChildPages(pBt, pParent);
+
+  /*
+  ** balance the parent page.
+  */
+  rc = balance(pBt, pParent, pCur);
+
+  /*
+  ** Cleanup before returning.
+  */
+balance_cleanup:
+  if( extraUnref ){
+    sqlitepager_unref(extraUnref);
+  }
+  for(i=0; i<nOld; i++){
+    if( apOld[i]!=0 && apOld[i]!=&aOld[i] ) sqlitepager_unref(apOld[i]);
+  }
+  for(i=0; i<nNew; i++){
+    sqlitepager_unref(apNew[i]);
+  }
+  if( pCur && pCur->pPage==0 ){
+    pCur->pPage = pParent;
+    pCur->idx = 0;
+  }else{
+    sqlitepager_unref(pParent);
+  }
+  return rc;
+}
+
+/*
+** This routine checks all cursors that point to the same table
+** as pCur points to.  If any of those cursors were opened with
+** wrFlag==0 then this routine returns SQLITE_LOCKED.  If all
+** cursors point to the same table were opened with wrFlag==1
+** then this routine returns SQLITE_OK.
+**
+** In addition to checking for read-locks (where a read-lock 
+** means a cursor opened with wrFlag==0) this routine also moves
+** all cursors other than pCur so that they are pointing to the 
+** first Cell on root page.  This is necessary because an insert 
+** or delete might change the number of cells on a page or delete
+** a page entirely and we do not want to leave any cursors 
+** pointing to non-existant pages or cells.
+*/
+static int checkReadLocks(BtCursor *pCur){
+  BtCursor *p;
+  assert( pCur->wrFlag );
+  for(p=pCur->pShared; p!=pCur; p=p->pShared){
+    assert( p );
+    assert( p->pgnoRoot==pCur->pgnoRoot );
+    if( p->wrFlag==0 ) return SQLITE_LOCKED;
+    if( sqlitepager_pagenumber(p->pPage)!=p->pgnoRoot ){
+      moveToRoot(p);
+    }
+  }
+  return SQLITE_OK;
+}
+
+/*
+** Insert a new record into the BTree.  The key is given by (pKey,nKey)
+** and the data is given by (pData,nData).  The cursor is used only to
+** define what database the record should be inserted into.  The cursor
+** is left pointing at the new record.
+*/
+int sqliteBtreeInsert(
+  BtCursor *pCur,                /* Insert data into the table of this cursor */
+  const void *pKey, int nKey,    /* The key of the new record */
+  const void *pData, int nData   /* The data of the new record */
+){
+  Cell newCell;
+  int rc;
+  int loc;
+  int szNew;
+  MemPage *pPage;
+  Btree *pBt = pCur->pBt;
+
+  if( pCur->pPage==0 ){
+    return SQLITE_ABORT;  /* A rollback destroyed this cursor */
+  }
+  if( !pBt->inTrans || nKey+nData==0 ){
+    /* Must start a transaction before doing an insert */
+    return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
+  }
+  assert( !pBt->readOnly );
+  if( !pCur->wrFlag ){
+    return SQLITE_PERM;   /* Cursor not open for writing */
+  }
+  if( checkReadLocks(pCur) ){
+    return SQLITE_LOCKED; /* The table pCur points to has a read lock */
+  }
+  rc = sqliteBtreeMoveto(pCur, pKey, nKey, &loc);
+  if( rc ) return rc;
+  pPage = pCur->pPage;
+  assert( pPage->isInit );
+  rc = sqlitepager_write(pPage);
+  if( rc ) return rc;
+  rc = fillInCell(pBt, &newCell, pKey, nKey, pData, nData);
+  if( rc ) return rc;
+  szNew = cellSize(pBt, &newCell);
+  if( loc==0 ){
+    newCell.h.leftChild = pPage->apCell[pCur->idx]->h.leftChild;
+    rc = clearCell(pBt, pPage->apCell[pCur->idx]);
+    if( rc ) return rc;
+    dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pPage->apCell[pCur->idx]));
+  }else if( loc<0 && pPage->nCell>0 ){
+    assert( pPage->u.hdr.rightChild==0 );  /* Must be a leaf page */
+    pCur->idx++;
+  }else{
+    assert( pPage->u.hdr.rightChild==0 );  /* Must be a leaf page */
+  }
+  insertCell(pBt, pPage, pCur->idx, &newCell, szNew);
+  rc = balance(pCur->pBt, pPage, pCur);
+  /* sqliteBtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
+  /* fflush(stdout); */
+  pCur->eSkip = SKIP_INVALID;
+  return rc;
+}
+
+/*
+** Delete the entry that the cursor is pointing to.
+**
+** The cursor is left pointing at either the next or the previous
+** entry.  If the cursor is left pointing to the next entry, then 
+** the pCur->eSkip flag is set to SKIP_NEXT which forces the next call to 
+** sqliteBtreeNext() to be a no-op.  That way, you can always call
+** sqliteBtreeNext() after a delete and the cursor will be left
+** pointing to the first entry after the deleted entry.  Similarly,
+** pCur->eSkip is set to SKIP_PREV is the cursor is left pointing to
+** the entry prior to the deleted entry so that a subsequent call to
+** sqliteBtreePrevious() will always leave the cursor pointing at the
+** entry immediately before the one that was deleted.
+*/
+int sqliteBtreeDelete(BtCursor *pCur){
+  MemPage *pPage = pCur->pPage;
+  Cell *pCell;
+  int rc;
+  Pgno pgnoChild;
+  Btree *pBt = pCur->pBt;
+
+  assert( pPage->isInit );
+  if( pCur->pPage==0 ){
+    return SQLITE_ABORT;  /* A rollback destroyed this cursor */
+  }
+  if( !pBt->inTrans ){
+    /* Must start a transaction before doing a delete */
+    return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
+  }
+  assert( !pBt->readOnly );
+  if( pCur->idx >= pPage->nCell ){
+    return SQLITE_ERROR;  /* The cursor is not pointing to anything */
+  }
+  if( !pCur->wrFlag ){
+    return SQLITE_PERM;   /* Did not open this cursor for writing */
+  }
+  if( checkReadLocks(pCur) ){
+    return SQLITE_LOCKED; /* The table pCur points to has a read lock */
+  }
+  rc = sqlitepager_write(pPage);
+  if( rc ) return rc;
+  pCell = pPage->apCell[pCur->idx];
+  pgnoChild = SWAB32(pBt, pCell->h.leftChild);
+  clearCell(pBt, pCell);
+  if( pgnoChild ){
+    /*
+    ** The entry we are about to delete is not a leaf so if we do not
+    ** do something we will leave a hole on an internal page.
+    ** We have to fill the hole by moving in a cell from a leaf.  The
+    ** next Cell after the one to be deleted is guaranteed to exist and
+    ** to be a leaf so we can use it.
+    */
+    BtCursor leafCur;
+    Cell *pNext;
+    int szNext;
+    int notUsed;
+    getTempCursor(pCur, &leafCur);
+    rc = sqliteBtreeNext(&leafCur, &notUsed);
+    if( rc!=SQLITE_OK ){
+      return SQLITE_CORRUPT;
+    }
+    rc = sqlitepager_write(leafCur.pPage);
+    if( rc ) return rc;
+    dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pCell));
+    pNext = leafCur.pPage->apCell[leafCur.idx];
+    szNext = cellSize(pBt, pNext);
+    pNext->h.leftChild = SWAB32(pBt, pgnoChild);
+    insertCell(pBt, pPage, pCur->idx, pNext, szNext);
+    rc = balance(pBt, pPage, pCur);
+    if( rc ) return rc;
+    pCur->eSkip = SKIP_NEXT;
+    dropCell(pBt, leafCur.pPage, leafCur.idx, szNext);
+    rc = balance(pBt, leafCur.pPage, pCur);
+    releaseTempCursor(&leafCur);
+  }else{
+    dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pCell));
+    if( pCur->idx>=pPage->nCell ){
+      pCur->idx = pPage->nCell-1;
+      if( pCur->idx<0 ){ 
+        pCur->idx = 0;
+        pCur->eSkip = SKIP_NEXT;
+      }else{
+        pCur->eSkip = SKIP_PREV;
+      }
+    }else{
+      pCur->eSkip = SKIP_NEXT;
+    }
+    rc = balance(pBt, pPage, pCur);
+  }
+  return rc;
+}
+
+/*
+** Create a new BTree table.  Write into *piTable the page
+** number for the root page of the new table.
+**
+** In the current implementation, BTree tables and BTree indices are the 
+** the same.  But in the future, we may change this so that BTree tables
+** are restricted to having a 4-byte integer key and arbitrary data and
+** BTree indices are restricted to having an arbitrary key and no data.
+*/
+int sqliteBtreeCreateTable(Btree *pBt, int *piTable){
+  MemPage *pRoot;
+  Pgno pgnoRoot;
+  int rc;
+  if( !pBt->inTrans ){
+    /* Must start a transaction first */
+    return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
+  }
+  if( pBt->readOnly ){
+    return SQLITE_READONLY;
+  }
+  rc = allocatePage(pBt, &pRoot, &pgnoRoot, 0);
+  if( rc ) return rc;
+  assert( sqlitepager_iswriteable(pRoot) );
+  zeroPage(pBt, pRoot);
+  sqlitepager_unref(pRoot);
+  *piTable = (int)pgnoRoot;
+  return SQLITE_OK;
+}
+
+/*
+** Create a new BTree index.  Write into *piTable the page
+** number for the root page of the new index.
+**
+** In the current implementation, BTree tables and BTree indices are the 
+** the same.  But in the future, we may change this so that BTree tables
+** are restricted to having a 4-byte integer key and arbitrary data and
+** BTree indices are restricted to having an arbitrary key and no data.
+*/
+int sqliteBtreeCreateIndex(Btree *pBt, int *piIndex){
+  return sqliteBtreeCreateTable(pBt, piIndex);
+}
+
+/*
+** Erase the given database page and all its children.  Return
+** the page to the freelist.
+*/
+static int clearDatabasePage(Btree *pBt, Pgno pgno, int freePageFlag){
+  MemPage *pPage;
+  int rc;
+  Cell *pCell;
+  int idx;
+
+  rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pPage);
+  if( rc ) return rc;
+  rc = sqlitepager_write(pPage);
+  if( rc ) return rc;
+  rc = initPage(pBt, pPage, pgno, 0);
+  if( rc ) return rc;
+  idx = SWAB16(pBt, pPage->u.hdr.firstCell);
+  while( idx>0 ){
+    pCell = (Cell*)&pPage->u.aDisk[idx];
+    idx = SWAB16(pBt, pCell->h.iNext);
+    if( pCell->h.leftChild ){
+      rc = clearDatabasePage(pBt, SWAB32(pBt, pCell->h.leftChild), 1);
+      if( rc ) return rc;
+    }
+    rc = clearCell(pBt, pCell);
+    if( rc ) return rc;
+  }
+  if( pPage->u.hdr.rightChild ){
+    rc = clearDatabasePage(pBt, SWAB32(pBt, pPage->u.hdr.rightChild), 1);
+    if( rc ) return rc;
+  }
+  if( freePageFlag ){
+    rc = freePage(pBt, pPage, pgno);
+  }else{
+    zeroPage(pBt, pPage);
+  }
+  sqlitepager_unref(pPage);
+  return rc;
+}
+
+/*
+** Delete all information from a single table in the database.
+*/
+int sqliteBtreeClearTable(Btree *pBt, int iTable){
+  int rc;
+  BtCursor *pCur;
+  if( !pBt->inTrans ){
+    return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
+  }
+  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
+    if( pCur->pgnoRoot==(Pgno)iTable ){
+      if( pCur->wrFlag==0 ) return SQLITE_LOCKED;
+      moveToRoot(pCur);
+    }
+  }
+  rc = clearDatabasePage(pBt, (Pgno)iTable, 0);
+  if( rc ){
+    sqliteBtreeRollback(pBt);
+  }
+  return rc;
+}
+
+/*
+** Erase all information in a table and add the root of the table to
+** the freelist.  Except, the root of the principle table (the one on
+** page 2) is never added to the freelist.
+*/
+int sqliteBtreeDropTable(Btree *pBt, int iTable){
+  int rc;
+  MemPage *pPage;
+  BtCursor *pCur;
+  if( !pBt->inTrans ){
+    return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
+  }
+  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
+    if( pCur->pgnoRoot==(Pgno)iTable ){
+      return SQLITE_LOCKED;  /* Cannot drop a table that has a cursor */
+    }
+  }
+  rc = sqlitepager_get(pBt->pPager, (Pgno)iTable, (void**)&pPage);
+  if( rc ) return rc;
+  rc = sqliteBtreeClearTable(pBt, iTable);
+  if( rc ) return rc;
+  if( iTable>2 ){
+    rc = freePage(pBt, pPage, iTable);
+  }else{
+    zeroPage(pBt, pPage);
+  }
+  sqlitepager_unref(pPage);
+  return rc;  
+}
+
+/*
+** Read the meta-information out of a database file.
+*/
+int sqliteBtreeGetMeta(Btree *pBt, int *aMeta){
+  PageOne *pP1;
+  int rc;
+  int i;
+
+  rc = sqlitepager_get(pBt->pPager, 1, (void**)&pP1);
+  if( rc ) return rc;
+  aMeta[0] = SWAB32(pBt, pP1->nFree);
+  for(i=0; i<sizeof(pP1->aMeta)/sizeof(pP1->aMeta[0]); i++){
+    aMeta[i+1] = SWAB32(pBt, pP1->aMeta[i]);
+  }
+  sqlitepager_unref(pP1);
+  return SQLITE_OK;
+}
+
+/*
+** Write meta-information back into the database.
+*/
+int sqliteBtreeUpdateMeta(Btree *pBt, int *aMeta){
+  PageOne *pP1;
+  int rc, i;
+  if( !pBt->inTrans ){
+    return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
+  }
+  pP1 = pBt->page1;
+  rc = sqlitepager_write(pP1);
+  if( rc ) return rc;   
+  for(i=0; i<sizeof(pP1->aMeta)/sizeof(pP1->aMeta[0]); i++){
+    pP1->aMeta[i] = SWAB32(pBt, aMeta[i+1]);
+  }
+  return SQLITE_OK;
+}
+
+/******************************************************************************
+** The complete implementation of the BTree subsystem is above this line.
+** All the code the follows is for testing and troubleshooting the BTree
+** subsystem.  None of the code that follows is used during normal operation.
+******************************************************************************/
+
+/*
+** Print a disassembly of the given page on standard output.  This routine
+** is used for debugging and testing only.
+*/
+#ifdef SQLITE_TEST
+int sqliteBtreePageDump(Btree *pBt, int pgno, int recursive){
+  int rc;
+  MemPage *pPage;
+  int i, j;
+  int nFree;
+  u16 idx;
+  char range[20];
+  unsigned char payload[20];
+  rc = sqlitepager_get(pBt->pPager, (Pgno)pgno, (void**)&pPage);
+  if( rc ){
+    return rc;
+  }
+  if( recursive ) printf("PAGE %d:\n", pgno);
+  i = 0;
+  idx = SWAB16(pBt, pPage->u.hdr.firstCell);
+  while( idx>0 && idx<=SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
+    Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
+    int sz = cellSize(pBt, pCell);
+    sprintf(range,"%d..%d", idx, idx+sz-1);
+    sz = NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h);
+    if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
+    memcpy(payload, pCell->aPayload, sz);
+    for(j=0; j<sz; j++){
+      if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
+    }
+    payload[sz] = 0;
+    printf(
+      "cell %2d: i=%-10s chld=%-4d nk=%-4d nd=%-4d payload=%s\n",
+      i, range, (int)pCell->h.leftChild, 
+      NKEY(pBt, pCell->h), NDATA(pBt, pCell->h),
+      payload
+    );
+    if( pPage->isInit && pPage->apCell[i]!=pCell ){
+      printf("**** apCell[%d] does not match on prior entry ****\n", i);
+    }
+    i++;
+    idx = SWAB16(pBt, pCell->h.iNext);
+  }
+  if( idx!=0 ){
+    printf("ERROR: next cell index out of range: %d\n", idx);
+  }
+  printf("right_child: %d\n", SWAB32(pBt, pPage->u.hdr.rightChild));
+  nFree = 0;
+  i = 0;
+  idx = SWAB16(pBt, pPage->u.hdr.firstFree);
+  while( idx>0 && idx<SQLITE_PAGE_SIZE ){
+    FreeBlk *p = (FreeBlk*)&pPage->u.aDisk[idx];
+    sprintf(range,"%d..%d", idx, idx+p->iSize-1);
+    nFree += SWAB16(pBt, p->iSize);
+    printf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
+       i, range, SWAB16(pBt, p->iSize), nFree);
+    idx = SWAB16(pBt, p->iNext);
+    i++;
+  }
+  if( idx!=0 ){
+    printf("ERROR: next freeblock index out of range: %d\n", idx);
+  }
+  if( recursive && pPage->u.hdr.rightChild!=0 ){
+    idx = SWAB16(pBt, pPage->u.hdr.firstCell);
+    while( idx>0 && idx<SQLITE_PAGE_SIZE-MIN_CELL_SIZE ){
+      Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
+      sqliteBtreePageDump(pBt, SWAB32(pBt, pCell->h.leftChild), 1);
+      idx = SWAB16(pBt, pCell->h.iNext);
+    }
+    sqliteBtreePageDump(pBt, SWAB32(pBt, pPage->u.hdr.rightChild), 1);
+  }
+  sqlitepager_unref(pPage);
+  return SQLITE_OK;
+}
+#endif
+
+#ifdef SQLITE_TEST
+/*
+** Fill aResult[] with information about the entry and page that the
+** cursor is pointing to.
+** 
+**   aResult[0] =  The page number
+**   aResult[1] =  The entry number
+**   aResult[2] =  Total number of entries on this page
+**   aResult[3] =  Size of this entry
+**   aResult[4] =  Number of free bytes on this page
+**   aResult[5] =  Number of free blocks on the page
+**   aResult[6] =  Page number of the left child of this entry
+**   aResult[7] =  Page number of the right child for the whole page
+**
+** This routine is used for testing and debugging only.
+*/
+int sqliteBtreeCursorDump(BtCursor *pCur, int *aResult){
+  int cnt, idx;
+  MemPage *pPage = pCur->pPage;
+  Btree *pBt = pCur->pBt;
+  aResult[0] = sqlitepager_pagenumber(pPage);
+  aResult[1] = pCur->idx;
+  aResult[2] = pPage->nCell;
+  if( pCur->idx>=0 && pCur->idx<pPage->nCell ){
+    aResult[3] = cellSize(pBt, pPage->apCell[pCur->idx]);
+    aResult[6] = SWAB32(pBt, pPage->apCell[pCur->idx]->h.leftChild);
+  }else{
+    aResult[3] = 0;
+    aResult[6] = 0;
+  }
+  aResult[4] = pPage->nFree;
+  cnt = 0;
+  idx = SWAB16(pBt, pPage->u.hdr.firstFree);
+  while( idx>0 && idx<SQLITE_PAGE_SIZE ){
+    cnt++;
+    idx = SWAB16(pBt, ((FreeBlk*)&pPage->u.aDisk[idx])->iNext);
+  }
+  aResult[5] = cnt;
+  aResult[7] = SWAB32(pBt, pPage->u.hdr.rightChild);
+  return SQLITE_OK;
+}
+#endif
+
+#ifdef SQLITE_TEST
+/*
+** Return the pager associated with a BTree.  This routine is used for
+** testing and debugging only.
+*/
+Pager *sqliteBtreePager(Btree *pBt){
+  return pBt->pPager;
+}
+#endif
+
+/*
+** This structure is passed around through all the sanity checking routines
+** in order to keep track of some global state information.
+*/
+typedef struct IntegrityCk IntegrityCk;
+struct IntegrityCk {
+  Btree *pBt;    /* The tree being checked out */
+  Pager *pPager; /* The associated pager.  Also accessible by pBt->pPager */
+  int nPage;     /* Number of pages in the database */
+  int *anRef;    /* Number of times each page is referenced */
+  int nTreePage; /* Number of BTree pages */
+  int nByte;     /* Number of bytes of data stored on BTree pages */
+  char *zErrMsg; /* An error message.  NULL of no errors seen. */
+};
+
+/*
+** Append a message to the error message string.
+*/
+static void checkAppendMsg(IntegrityCk *pCheck, char *zMsg1, char *zMsg2){
+  if( pCheck->zErrMsg ){
+    char *zOld = pCheck->zErrMsg;
+    pCheck->zErrMsg = 0;
+    sqliteSetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, 0);
+    sqliteFree(zOld);
+  }else{
+    sqliteSetString(&pCheck->zErrMsg, zMsg1, zMsg2, 0);
+  }
+}
+
+/*
+** Add 1 to the reference count for page iPage.  If this is the second
+** reference to the page, add an error message to pCheck->zErrMsg.
+** Return 1 if there are 2 ore more references to the page and 0 if
+** if this is the first reference to the page.
+**
+** Also check that the page number is in bounds.
+*/
+static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
+  if( iPage==0 ) return 1;
+  if( iPage>pCheck->nPage || iPage<0 ){
+    char zBuf[100];
+    sprintf(zBuf, "invalid page number %d", iPage);
+    checkAppendMsg(pCheck, zContext, zBuf);
+    return 1;
+  }
+  if( pCheck->anRef[iPage]==1 ){
+    char zBuf[100];
+    sprintf(zBuf, "2nd reference to page %d", iPage);
+    checkAppendMsg(pCheck, zContext, zBuf);
+    return 1;
+  }
+  return  (pCheck->anRef[iPage]++)>1;
+}
+
+/*
+** Check the integrity of the freelist or of an overflow page list.
+** Verify that the number of pages on the list is N.
+*/
+static void checkList(
+  IntegrityCk *pCheck,  /* Integrity checking context */
+  int isFreeList,       /* True for a freelist.  False for overflow page list */
+  int iPage,            /* Page number for first page in the list */
+  int N,                /* Expected number of pages in the list */
+  char *zContext        /* Context for error messages */
+){
+  int i;
+  char zMsg[100];
+  while( N-- > 0 ){
+    OverflowPage *pOvfl;
+    if( iPage<1 ){
+      sprintf(zMsg, "%d pages missing from overflow list", N+1);
+      checkAppendMsg(pCheck, zContext, zMsg);
+      break;
+    }
+    if( checkRef(pCheck, iPage, zContext) ) break;
+    if( sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
+      sprintf(zMsg, "failed to get page %d", iPage);
+      checkAppendMsg(pCheck, zContext, zMsg);
+      break;
+    }
+    if( isFreeList ){
+      FreelistInfo *pInfo = (FreelistInfo*)pOvfl->aPayload;
+      int n = SWAB32(pCheck->pBt, pInfo->nFree);
+      for(i=0; i<n; i++){
+        checkRef(pCheck, SWAB32(pCheck->pBt, pInfo->aFree[i]), zMsg);
+      }
+      N -= n;
+    }
+    iPage = SWAB32(pCheck->pBt, pOvfl->iNext);
+    sqlitepager_unref(pOvfl);
+  }
+}
+
+/*
+** Return negative if zKey1<zKey2.
+** Return zero if zKey1==zKey2.
+** Return positive if zKey1>zKey2.
+*/
+static int keyCompare(
+  const char *zKey1, int nKey1,
+  const char *zKey2, int nKey2
+){
+  int min = nKey1>nKey2 ? nKey2 : nKey1;
+  int c = memcmp(zKey1, zKey2, min);
+  if( c==0 ){
+    c = nKey1 - nKey2;
+  }
+  return c;
+}
+
+/*
+** Do various sanity checks on a single page of a tree.  Return
+** the tree depth.  Root pages return 0.  Parents of root pages
+** return 1, and so forth.
+** 
+** These checks are done:
+**
+**      1.  Make sure that cells and freeblocks do not overlap
+**          but combine to completely cover the page.
+**      2.  Make sure cell keys are in order.
+**      3.  Make sure no key is less than or equal to zLowerBound.
+**      4.  Make sure no key is greater than or equal to zUpperBound.
+**      5.  Check the integrity of overflow pages.
+**      6.  Recursively call checkTreePage on all children.
+**      7.  Verify that the depth of all children is the same.
+**      8.  Make sure this page is at least 33% full or else it is
+**          the root of the tree.
+*/
+static int checkTreePage(
+  IntegrityCk *pCheck,  /* Context for the sanity check */
+  int iPage,            /* Page number of the page to check */
+  MemPage *pParent,     /* Parent page */
+  char *zParentContext, /* Parent context */
+  char *zLowerBound,    /* All keys should be greater than this, if not NULL */
+  int nLower,           /* Number of characters in zLowerBound */
+  char *zUpperBound,    /* All keys should be less than this, if not NULL */
+  int nUpper            /* Number of characters in zUpperBound */
+){
+  MemPage *pPage;
+  int i, rc, depth, d2, pgno;
+  char *zKey1, *zKey2;
+  int nKey1, nKey2;
+  BtCursor cur;
+  Btree *pBt;
+  char zMsg[100];
+  char zContext[100];
+  char hit[SQLITE_PAGE_SIZE];
+
+  /* Check that the page exists
+  */
+  cur.pBt = pBt = pCheck->pBt;
+  if( iPage==0 ) return 0;
+  if( checkRef(pCheck, iPage, zParentContext) ) return 0;
+  sprintf(zContext, "On tree page %d: ", iPage);
+  if( (rc = sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pPage))!=0 ){
+    sprintf(zMsg, "unable to get the page. error code=%d", rc);
+    checkAppendMsg(pCheck, zContext, zMsg);
+    return 0;
+  }
+  if( (rc = initPage(pBt, pPage, (Pgno)iPage, pParent))!=0 ){
+    sprintf(zMsg, "initPage() returns error code %d", rc);
+    checkAppendMsg(pCheck, zContext, zMsg);
+    sqlitepager_unref(pPage);
+    return 0;
+  }
+
+  /* Check out all the cells.
+  */
+  depth = 0;
+  if( zLowerBound ){
+    zKey1 = sqliteMalloc( nLower+1 );
+    memcpy(zKey1, zLowerBound, nLower);
+    zKey1[nLower] = 0;
+  }else{
+    zKey1 = 0;
+  }
+  nKey1 = nLower;
+  cur.pPage = pPage;
+  for(i=0; i<pPage->nCell; i++){
+    Cell *pCell = pPage->apCell[i];
+    int sz;
+
+    /* Check payload overflow pages
+    */
+    nKey2 = NKEY(pBt, pCell->h);
+    sz = nKey2 + NDATA(pBt, pCell->h);
+    sprintf(zContext, "On page %d cell %d: ", iPage, i);
+    if( sz>MX_LOCAL_PAYLOAD ){
+      int nPage = (sz - MX_LOCAL_PAYLOAD + OVERFLOW_SIZE - 1)/OVERFLOW_SIZE;
+      checkList(pCheck, 0, SWAB32(pBt, pCell->ovfl), nPage, zContext);
+    }
+
+    /* Check that keys are in the right order
+    */
+    cur.idx = i;
+    zKey2 = sqliteMallocRaw( nKey2+1 );
+    getPayload(&cur, 0, nKey2, zKey2);
+    if( zKey1 && keyCompare(zKey1, nKey1, zKey2, nKey2)>=0 ){
+      checkAppendMsg(pCheck, zContext, "Key is out of order");
+    }
+
+    /* Check sanity of left child page.
+    */
+    pgno = SWAB32(pBt, pCell->h.leftChild);
+    d2 = checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zKey2,nKey2);
+    if( i>0 && d2!=depth ){
+      checkAppendMsg(pCheck, zContext, "Child page depth differs");
+    }
+    depth = d2;
+    sqliteFree(zKey1);
+    zKey1 = zKey2;
+    nKey1 = nKey2;
+  }
+  pgno = SWAB32(pBt, pPage->u.hdr.rightChild);
+  sprintf(zContext, "On page %d at right child: ", iPage);
+  checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zUpperBound,nUpper);
+  sqliteFree(zKey1);
+  /* Check for complete coverage of the page
+  */
+  memset(hit, 0, sizeof(hit));
+  memset(hit, 1, sizeof(PageHdr));
+  for(i=SWAB16(pBt, pPage->u.hdr.firstCell); i>0 && i<SQLITE_PAGE_SIZE; ){
+    Cell *pCell = (Cell*)&pPage->u.aDisk[i];
+    int j;
+    for(j=i+cellSize(pBt, pCell)-1; j>=i; j--) hit[j]++;
+    i = SWAB16(pBt, pCell->h.iNext);
+  }
+  for(i=SWAB16(pBt,pPage->u.hdr.firstFree); i>0 && i<SQLITE_PAGE_SIZE; ){
+    FreeBlk *pFBlk = (FreeBlk*)&pPage->u.aDisk[i];
+    int j;
+    for(j=i+SWAB16(pBt,pFBlk->iSize)-1; j>=i; j--) hit[j]++;
+    i = SWAB16(pBt,pFBlk->iNext);
+  }
+  for(i=0; i<SQLITE_PAGE_SIZE; i++){
+    if( hit[i]==0 ){
+      sprintf(zMsg, "Unused space at byte %d of page %d", i, iPage);
+      checkAppendMsg(pCheck, zMsg, 0);
+      break;
+    }else if( hit[i]>1 ){
+      sprintf(zMsg, "Multiple uses for byte %d of page %d", i, iPage);
+      checkAppendMsg(pCheck, zMsg, 0);
+      break;
+    }
+  }
+
+  /* Check that free space is kept to a minimum
+  */
+#if 0
+  if( pParent && pParent->nCell>2 && pPage->nFree>3*SQLITE_PAGE_SIZE/4 ){
+    sprintf(zMsg, "free space (%d) greater than max (%d)", pPage->nFree,
+       SQLITE_PAGE_SIZE/3);
+    checkAppendMsg(pCheck, zContext, zMsg);
+  }
+#endif
+
+  /* Update freespace totals.
+  */
+  pCheck->nTreePage++;
+  pCheck->nByte += USABLE_SPACE - pPage->nFree;
+
+  sqlitepager_unref(pPage);
+  return depth;
+}
+
+/*
+** This routine does a complete check of the given BTree file.  aRoot[] is
+** an array of pages numbers were each page number is the root page of
+** a table.  nRoot is the number of entries in aRoot.
+**
+** If everything checks out, this routine returns NULL.  If something is
+** amiss, an error message is written into memory obtained from malloc()
+** and a pointer to that error message is returned.  The calling function
+** is responsible for freeing the error message when it is done.
+*/
+char *sqliteBtreeIntegrityCheck(Btree *pBt, int *aRoot, int nRoot){
+  int i;
+  int nRef;
+  IntegrityCk sCheck;
+
+  nRef = *sqlitepager_stats(pBt->pPager);
+  if( lockBtree(pBt)!=SQLITE_OK ){
+    return sqliteStrDup("Unable to acquire a read lock on the database");
+  }
+  sCheck.pBt = pBt;
+  sCheck.pPager = pBt->pPager;
+  sCheck.nPage = sqlitepager_pagecount(sCheck.pPager);
+  if( sCheck.nPage==0 ){
+    unlockBtreeIfUnused(pBt);
+    return 0;
+  }
+  sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
+  sCheck.anRef[1] = 1;
+  for(i=2; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
+  sCheck.zErrMsg = 0;
+
+  /* Check the integrity of the freelist
+  */
+  checkList(&sCheck, 1, SWAB32(pBt, pBt->page1->freeList),
+            SWAB32(pBt, pBt->page1->nFree), "Main freelist: ");
+
+  /* Check all the tables.
+  */
+  for(i=0; i<nRoot; i++){
+    if( aRoot[i]==0 ) continue;
+    checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
+  }
+
+  /* Make sure every page in the file is referenced
+  */
+  for(i=1; i<=sCheck.nPage; i++){
+    if( sCheck.anRef[i]==0 ){
+      char zBuf[100];
+      sprintf(zBuf, "Page %d is never used", i);
+      checkAppendMsg(&sCheck, zBuf, 0);
+    }
+  }
+
+  /* Make sure this analysis did not leave any unref() pages
+  */
+  unlockBtreeIfUnused(pBt);
+  if( nRef != *sqlitepager_stats(pBt->pPager) ){
+    char zBuf[100];
+    sprintf(zBuf, 
+      "Outstanding page count goes from %d to %d during this analysis",
+      nRef, *sqlitepager_stats(pBt->pPager)
+    );
+    checkAppendMsg(&sCheck, zBuf, 0);
+  }
+
+  /* Clean  up and report errors.
+  */
+  sqliteFree(sCheck.anRef);
+  return sCheck.zErrMsg;
+}
diff --git a/ext/sqlite/libsqlite/src/btree.h b/ext/sqlite/libsqlite/src/btree.h
new file mode 100644 (file)
index 0000000..84c80c5
--- /dev/null
@@ -0,0 +1,71 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This header file defines the interface that the sqlite B-Tree file
+** subsystem.  See comments in the source code for a detailed description
+** of what each interface routine does.
+**
+** @(#) $Id$
+*/
+#ifndef _BTREE_H_
+#define _BTREE_H_
+
+typedef struct Btree Btree;
+typedef struct BtCursor BtCursor;
+
+int sqliteBtreeOpen(const char *zFilename, int mode, int nPg, Btree **ppBtree);
+int sqliteBtreeClose(Btree*);
+int sqliteBtreeSetCacheSize(Btree*, int);
+int sqliteBtreeSetSafetyLevel(Btree*, int);
+
+int sqliteBtreeBeginTrans(Btree*);
+int sqliteBtreeCommit(Btree*);
+int sqliteBtreeRollback(Btree*);
+int sqliteBtreeBeginCkpt(Btree*);
+int sqliteBtreeCommitCkpt(Btree*);
+int sqliteBtreeRollbackCkpt(Btree*);
+
+int sqliteBtreeCreateTable(Btree*, int*);
+int sqliteBtreeCreateIndex(Btree*, int*);
+int sqliteBtreeDropTable(Btree*, int);
+int sqliteBtreeClearTable(Btree*, int);
+
+int sqliteBtreeCursor(Btree*, int iTable, int wrFlag, BtCursor **ppCur);
+int sqliteBtreeMoveto(BtCursor*, const void *pKey, int nKey, int *pRes);
+int sqliteBtreeDelete(BtCursor*);
+int sqliteBtreeInsert(BtCursor*, const void *pKey, int nKey,
+                                 const void *pData, int nData);
+int sqliteBtreeFirst(BtCursor*, int *pRes);
+int sqliteBtreeLast(BtCursor*, int *pRes);
+int sqliteBtreeNext(BtCursor*, int *pRes);
+int sqliteBtreePrevious(BtCursor*, int *pRes);
+int sqliteBtreeKeySize(BtCursor*, int *pSize);
+int sqliteBtreeKey(BtCursor*, int offset, int amt, char *zBuf);
+int sqliteBtreeKeyCompare(BtCursor*, const void *pKey, int nKey,
+                          int nIgnore, int *pRes);
+int sqliteBtreeDataSize(BtCursor*, int *pSize);
+int sqliteBtreeData(BtCursor*, int offset, int amt, char *zBuf);
+int sqliteBtreeCloseCursor(BtCursor*);
+
+#define SQLITE_N_BTREE_META 10
+int sqliteBtreeGetMeta(Btree*, int*);
+int sqliteBtreeUpdateMeta(Btree*, int*);
+
+char *sqliteBtreeIntegrityCheck(Btree*, int*, int);
+
+#ifdef SQLITE_TEST
+int sqliteBtreePageDump(Btree*, int, int);
+int sqliteBtreeCursorDump(BtCursor*, int*);
+struct Pager *sqliteBtreePager(Btree*);
+int btree_native_byte_order;
+#endif
+
+#endif /* _BTREE_H_ */
diff --git a/ext/sqlite/libsqlite/src/build.c b/ext/sqlite/libsqlite/src/build.c
new file mode 100644 (file)
index 0000000..afa3f16
--- /dev/null
@@ -0,0 +1,2569 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains C code routines that are called by the SQLite parser
+** when syntax rules are reduced.  The routines in this file handle the
+** following kinds of SQL syntax:
+**
+**     CREATE TABLE
+**     DROP TABLE
+**     CREATE INDEX
+**     DROP INDEX
+**     creating ID lists
+**     COPY
+**     VACUUM
+**     BEGIN TRANSACTION
+**     COMMIT
+**     ROLLBACK
+**     PRAGMA
+**
+** $Id$
+*/
+#include "sqliteInt.h"
+#include <ctype.h>
+
+/*
+** This routine is called when a new SQL statement is beginning to
+** be parsed.  Check to see if the schema for the database needs
+** to be read from the SQLITE_MASTER and SQLITE_TEMP_MASTER tables.
+** If it does, then read it.
+*/
+void sqliteBeginParse(Parse *pParse, int explainFlag){
+  sqlite *db = pParse->db;
+  pParse->explain = explainFlag;
+  if((db->flags & SQLITE_Initialized)==0 && pParse->initFlag==0 ){
+    int rc = sqliteInit(db, &pParse->zErrMsg);
+    if( rc!=SQLITE_OK ){
+      pParse->rc = rc;
+      pParse->nErr++;
+    }
+  }
+}
+
+/*
+** This is a fake callback procedure used when sqlite_exec() is
+** invoked with a NULL callback pointer.  If we pass a NULL callback
+** pointer into sqliteVdbeExec() it will return at every OP_Callback,
+** which we do not want it to do.  So we substitute a pointer to this
+** procedure in place of the NULL.
+*/
+static int fakeCallback(void *NotUsed, int n, char **az1, char **az2){
+  return 0;
+}
+
+/*
+** This routine is called after a single SQL statement has been
+** parsed and we want to execute the VDBE code to implement 
+** that statement.  Prior action routines should have already
+** constructed VDBE code to do the work of the SQL statement.
+** This routine just has to execute the VDBE code.
+**
+** Note that if an error occurred, it might be the case that
+** no VDBE code was generated.
+*/
+void sqliteExec(Parse *pParse){
+  int rc = SQLITE_OK;
+  sqlite *db = pParse->db;
+  Vdbe *v = pParse->pVdbe;
+  int (*xCallback)(void*,int,char**,char**);
+
+  if( sqlite_malloc_failed ) return;
+  xCallback = pParse->xCallback;
+  if( xCallback==0 && pParse->useCallback ) xCallback = fakeCallback;
+  if( v && pParse->nErr==0 ){
+    FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
+    sqliteVdbeTrace(v, trace);
+    sqliteVdbeMakeReady(v, xCallback, pParse->pArg, pParse->explain);
+    if( pParse->useCallback ){
+      if( pParse->explain ){
+        rc = sqliteVdbeList(v);
+        db->next_cookie = db->schema_cookie;
+      }else{
+        sqliteVdbeExec(v);
+      }
+      rc = sqliteVdbeFinalize(v, &pParse->zErrMsg);
+      if( rc ) pParse->nErr++;
+      pParse->pVdbe = 0;
+      pParse->rc = rc;
+      if( rc ) pParse->nErr++;
+    }else{
+      pParse->rc = pParse->nErr ? SQLITE_ERROR : SQLITE_DONE;
+    }
+    pParse->colNamesSet = 0;
+    pParse->schemaVerified = 0;
+  }else if( pParse->useCallback==0 ){
+    pParse->rc = SQLITE_ERROR;
+  }
+  pParse->nTab = 0;
+  pParse->nMem = 0;
+  pParse->nSet = 0;
+  pParse->nAgg = 0;
+}
+
+/*
+** Locate the in-memory structure that describes 
+** a particular database table given the name
+** of that table.  Return NULL if not found.
+*/
+Table *sqliteFindTable(sqlite *db, const char *zName){
+  Table *p;
+  p = sqliteHashFind(&db->tblHash, zName, strlen(zName)+1);
+  return p;
+}
+
+/*
+** Locate the in-memory structure that describes 
+** a particular index given the name of that index.
+** Return NULL if not found.
+*/
+Index *sqliteFindIndex(sqlite *db, const char *zName){
+  Index *p;
+  p = sqliteHashFind(&db->idxHash, zName, strlen(zName)+1);
+  return p;
+}
+
+/*
+** Remove the given index from the index hash table, and free
+** its memory structures.
+**
+** The index is removed from the database hash tables but
+** it is not unlinked from the Table that it indexes.
+** Unlinking from the Table must be done by the calling function.
+*/
+static void sqliteDeleteIndex(sqlite *db, Index *p){
+  Index *pOld;
+  assert( db!=0 && p->zName!=0 );
+  pOld = sqliteHashInsert(&db->idxHash, p->zName, strlen(p->zName)+1, 0);
+  if( pOld!=0 && pOld!=p ){
+    sqliteHashInsert(&db->idxHash, pOld->zName, strlen(pOld->zName)+1, pOld);
+  }
+  sqliteFree(p);
+}
+
+/*
+** Unlink the given index from its table, then remove
+** the index from the index hash table and free its memory
+** structures.
+*/
+void sqliteUnlinkAndDeleteIndex(sqlite *db, Index *pIndex){
+  if( pIndex->pTable->pIndex==pIndex ){
+    pIndex->pTable->pIndex = pIndex->pNext;
+  }else{
+    Index *p;
+    for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
+    if( p && p->pNext==pIndex ){
+      p->pNext = pIndex->pNext;
+    }
+  }
+  sqliteDeleteIndex(db, pIndex);
+}
+
+/*
+** Erase all schema information from the in-memory hash tables of
+** database connection.  This routine is called to reclaim memory
+** before the connection closes.  It is also called during a rollback
+** if there were schema changes during the transaction.
+*/
+void sqliteResetInternalSchema(sqlite *db){
+  HashElem *pElem;
+  Hash temp1;
+  Hash temp2;
+
+  sqliteHashClear(&db->aFKey);
+  temp1 = db->tblHash;
+  temp2 = db->trigHash;
+  sqliteHashInit(&db->trigHash, SQLITE_HASH_STRING, 0);
+  sqliteHashClear(&db->idxHash);
+  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
+    Trigger *pTrigger = sqliteHashData(pElem);
+    sqliteDeleteTrigger(pTrigger);
+  }
+  sqliteHashClear(&temp2);
+  sqliteHashInit(&db->tblHash, SQLITE_HASH_STRING, 0);
+  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
+    Table *pTab = sqliteHashData(pElem);
+    sqliteDeleteTable(db, pTab);
+  }
+  sqliteHashClear(&temp1);
+  db->flags &= ~(SQLITE_Initialized|SQLITE_InternChanges);
+}
+
+/*
+** This routine is called whenever a rollback occurs.  If there were
+** schema changes during the transaction, then we have to reset the
+** internal hash tables and reload them from disk.
+*/
+void sqliteRollbackInternalChanges(sqlite *db){
+  if( db->flags & SQLITE_InternChanges ){
+    sqliteResetInternalSchema(db);
+  }
+}
+
+/*
+** This routine is called when a commit occurs.
+*/
+void sqliteCommitInternalChanges(sqlite *db){
+  db->schema_cookie = db->next_cookie;
+  db->flags &= ~SQLITE_InternChanges;
+}
+
+/*
+** Remove the memory data structures associated with the given
+** Table.  No changes are made to disk by this routine.
+**
+** This routine just deletes the data structure.  It does not unlink
+** the table data structure from the hash table.  Nor does it remove
+** foreign keys from the sqlite.aFKey hash table.  But it does destroy
+** memory structures of the indices and foreign keys associated with 
+** the table.
+**
+** Indices associated with the table are unlinked from the "db"
+** data structure if db!=NULL.  If db==NULL, indices attached to
+** the table are deleted, but it is assumed they have already been
+** unlinked.
+*/
+void sqliteDeleteTable(sqlite *db, Table *pTable){
+  int i;
+  Index *pIndex, *pNext;
+  FKey *pFKey, *pNextFKey;
+
+  if( pTable==0 ) return;
+
+  /* Delete all indices associated with this table
+  */
+  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
+    pNext = pIndex->pNext;
+    sqliteDeleteIndex(db, pIndex);
+  }
+
+  /* Delete all foreign keys associated with this table.  The keys
+  ** should have already been unlinked from the db->aFKey hash table 
+  */
+  for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
+    pNextFKey = pFKey->pNextFrom;
+    assert( sqliteHashFind(&db->aFKey,pFKey->zTo,strlen(pFKey->zTo)+1)!=pFKey );
+    sqliteFree(pFKey);
+  }
+
+  /* Delete the Table structure itself.
+  */
+  for(i=0; i<pTable->nCol; i++){
+    sqliteFree(pTable->aCol[i].zName);
+    sqliteFree(pTable->aCol[i].zDflt);
+    sqliteFree(pTable->aCol[i].zType);
+  }
+  sqliteFree(pTable->zName);
+  sqliteFree(pTable->aCol);
+  sqliteSelectDelete(pTable->pSelect);
+  sqliteFree(pTable);
+}
+
+/*
+** Unlink the given table from the hash tables and the delete the
+** table structure with all its indices and foreign keys.
+*/
+static void sqliteUnlinkAndDeleteTable(sqlite *db, Table *p){
+  Table *pOld;
+  FKey *pF1, *pF2;
+  assert( db!=0 );
+  pOld = sqliteHashInsert(&db->tblHash, p->zName, strlen(p->zName)+1, 0);
+  assert( pOld==0 || pOld==p );
+  for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
+    int nTo = strlen(pF1->zTo) + 1;
+    pF2 = sqliteHashFind(&db->aFKey, pF1->zTo, nTo);
+    if( pF2==pF1 ){
+      sqliteHashInsert(&db->aFKey, pF1->zTo, nTo, pF1->pNextTo);
+    }else{
+      while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
+      if( pF2 ){
+        pF2->pNextTo = pF1->pNextTo;
+      }
+    }
+  }
+  sqliteDeleteTable(db, p);
+}
+
+/*
+** Construct the name of a user table or index from a token.
+**
+** Space to hold the name is obtained from sqliteMalloc() and must
+** be freed by the calling function.
+*/
+char *sqliteTableNameFromToken(Token *pName){
+  char *zName = sqliteStrNDup(pName->z, pName->n);
+  sqliteDequote(zName);
+  return zName;
+}
+
+/*
+** Generate code to open the appropriate master table.  The table
+** opened will be SQLITE_MASTER for persistent tables and 
+** SQLITE_TEMP_MASTER for temporary tables.  The table is opened
+** on cursor 0.
+*/
+void sqliteOpenMasterTable(Vdbe *v, int isTemp){
+  if( isTemp ){
+    sqliteVdbeAddOp(v, OP_OpenWrAux, 0, 2);
+    sqliteVdbeChangeP3(v, -1, TEMP_MASTER_NAME, P3_STATIC);
+  }else{
+    sqliteVdbeAddOp(v, OP_OpenWrite, 0, 2);
+    sqliteVdbeChangeP3(v, -1, MASTER_NAME, P3_STATIC);
+  }
+}
+
+/*
+** Begin constructing a new table representation in memory.  This is
+** the first of several action routines that get called in response
+** to a CREATE TABLE statement.  In particular, this routine is called
+** after seeing tokens "CREATE" and "TABLE" and the table name.  The
+** pStart token is the CREATE and pName is the table name.  The isTemp
+** flag is true if the table should be stored in the auxiliary database
+** file instead of in the main database file.  This is normally the case
+** when the "TEMP" or "TEMPORARY" keyword occurs in between
+** CREATE and TABLE.
+**
+** The new table record is initialized and put in pParse->pNewTable.
+** As more of the CREATE TABLE statement is parsed, additional action
+** routines will be called to add more information to this record.
+** At the end of the CREATE TABLE statement, the sqliteEndTable() routine
+** is called to complete the construction of the new table record.
+*/
+void sqliteStartTable(
+  Parse *pParse,   /* Parser context */
+  Token *pStart,   /* The "CREATE" token */
+  Token *pName,    /* Name of table or view to create */
+  int isTemp,      /* True if this is a TEMP table */
+  int isView       /* True if this is a VIEW */
+){
+  Table *pTable;
+  Index *pIdx;
+  char *zName;
+  sqlite *db = pParse->db;
+  Vdbe *v;
+
+  pParse->sFirstToken = *pStart;
+  zName = sqliteTableNameFromToken(pName);
+  if( zName==0 ) return;
+#ifndef SQLITE_OMIT_AUTHORIZATION
+  if( sqliteAuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0) ){
+    sqliteFree(zName);
+    return;
+  }
+  {
+    int code;
+    if( isView ){
+      if( isTemp ){
+        code = SQLITE_CREATE_TEMP_VIEW;
+      }else{
+        code = SQLITE_CREATE_VIEW;
+      }
+    }else{
+      if( isTemp ){
+        code = SQLITE_CREATE_TEMP_TABLE;
+      }else{
+        code = SQLITE_CREATE_TABLE;
+      }
+    }
+    if( sqliteAuthCheck(pParse, code, zName, 0) ){
+      sqliteFree(zName);
+      return;
+    }
+  }
+#endif
+
+  /* Before trying to create a temporary table, make sure the Btree for
+  ** holding temporary tables is open.
+  */
+  if( isTemp && db->pBeTemp==0 ){
+    int rc = sqliteBtreeOpen(0, 0, MAX_PAGES, &db->pBeTemp);
+    if( rc!=SQLITE_OK ){
+      sqliteSetString(&pParse->zErrMsg, "unable to open a temporary database "
+        "file for storing temporary tables", 0);
+      pParse->nErr++;
+      return;
+    }
+    if( db->flags & SQLITE_InTrans ){
+      rc = sqliteBtreeBeginTrans(db->pBeTemp);
+      if( rc!=SQLITE_OK ){
+        sqliteSetNString(&pParse->zErrMsg, "unable to get a write lock on "
+          "the temporary database file", 0);
+        pParse->nErr++;
+        return;
+      }
+    }
+  }
+
+  /* Make sure the new table name does not collide with an existing
+  ** index or table name.  Issue an error message if it does.
+  **
+  ** If we are re-reading the sqlite_master table because of a schema
+  ** change and a new permanent table is found whose name collides with
+  ** an existing temporary table, then ignore the new permanent table.
+  ** We will continue parsing, but the pParse->nameClash flag will be set
+  ** so we will know to discard the table record once parsing has finished.
+  */
+  pTable = sqliteFindTable(db, zName);
+  if( pTable!=0 ){
+    if( pTable->isTemp && pParse->initFlag ){
+      pParse->nameClash = 1;
+    }else{
+      sqliteSetNString(&pParse->zErrMsg, "table ", 0, pName->z, pName->n,
+          " already exists", 0, 0);
+      sqliteFree(zName);
+      pParse->nErr++;
+      return;
+    }
+  }else{
+    pParse->nameClash = 0;
+  }
+  if( (pIdx = sqliteFindIndex(db, zName))!=0 &&
+          (!pIdx->pTable->isTemp || !pParse->initFlag) ){
+    sqliteSetString(&pParse->zErrMsg, "there is already an index named ", 
+       zName, 0);
+    sqliteFree(zName);
+    pParse->nErr++;
+    return;
+  }
+  pTable = sqliteMalloc( sizeof(Table) );
+  if( pTable==0 ){
+    sqliteFree(zName);
+    return;
+  }
+  pTable->zName = zName;
+  pTable->nCol = 0;
+  pTable->aCol = 0;
+  pTable->iPKey = -1;
+  pTable->pIndex = 0;
+  pTable->isTemp = isTemp;
+  if( pParse->pNewTable ) sqliteDeleteTable(db, pParse->pNewTable);
+  pParse->pNewTable = pTable;
+
+  /* Begin generating the code that will insert the table record into
+  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
+  ** and allocate the record number for the table entry now.  Before any
+  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
+  ** indices to be created and the table record must come before the 
+  ** indices.  Hence, the record number for the table must be allocated
+  ** now.
+  */
+  if( !pParse->initFlag && (v = sqliteGetVdbe(pParse))!=0 ){
+    sqliteBeginWriteOperation(pParse, 0, isTemp);
+    if( !isTemp ){
+      sqliteVdbeAddOp(v, OP_Integer, db->file_format, 0);
+      sqliteVdbeAddOp(v, OP_SetCookie, 0, 1);
+    }
+    sqliteOpenMasterTable(v, isTemp);
+    sqliteVdbeAddOp(v, OP_NewRecno, 0, 0);
+    sqliteVdbeAddOp(v, OP_Dup, 0, 0);
+    sqliteVdbeAddOp(v, OP_String, 0, 0);
+    sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0);
+  }
+}
+
+/*
+** Add a new column to the table currently being constructed.
+**
+** The parser calls this routine once for each column declaration
+** in a CREATE TABLE statement.  sqliteStartTable() gets called
+** first to get things going.  Then this routine is called for each
+** column.
+*/
+void sqliteAddColumn(Parse *pParse, Token *pName){
+  Table *p;
+  int i;
+  char *z = 0;
+  Column *pCol;
+  if( (p = pParse->pNewTable)==0 ) return;
+  sqliteSetNString(&z, pName->z, pName->n, 0);
+  if( z==0 ) return;
+  sqliteDequote(z);
+  for(i=0; i<p->nCol; i++){
+    if( sqliteStrICmp(z, p->aCol[i].zName)==0 ){
+      sqliteSetString(&pParse->zErrMsg, "duplicate column name: ", z, 0);
+      pParse->nErr++;
+      sqliteFree(z);
+      return;
+    }
+  }
+  if( (p->nCol & 0x7)==0 ){
+    Column *aNew;
+    aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
+    if( aNew==0 ) return;
+    p->aCol = aNew;
+  }
+  pCol = &p->aCol[p->nCol];
+  memset(pCol, 0, sizeof(p->aCol[0]));
+  pCol->zName = z;
+  pCol->sortOrder = SQLITE_SO_NUM;
+  p->nCol++;
+}
+
+/*
+** This routine is called by the parser while in the middle of
+** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
+** been seen on a column.  This routine sets the notNull flag on
+** the column currently under construction.
+*/
+void sqliteAddNotNull(Parse *pParse, int onError){
+  Table *p;
+  int i;
+  if( (p = pParse->pNewTable)==0 ) return;
+  i = p->nCol-1;
+  if( i>=0 ) p->aCol[i].notNull = onError;
+}
+
+/*
+** This routine is called by the parser while in the middle of
+** parsing a CREATE TABLE statement.  The pFirst token is the first
+** token in the sequence of tokens that describe the type of the
+** column currently under construction.   pLast is the last token
+** in the sequence.  Use this information to construct a string
+** that contains the typename of the column and store that string
+** in zType.
+*/ 
+void sqliteAddColumnType(Parse *pParse, Token *pFirst, Token *pLast){
+  Table *p;
+  int i, j;
+  int n;
+  char *z, **pz;
+  Column *pCol;
+  if( (p = pParse->pNewTable)==0 ) return;
+  i = p->nCol-1;
+  if( i<0 ) return;
+  pCol = &p->aCol[i];
+  pz = &pCol->zType;
+  n = pLast->n + Addr(pLast->z) - Addr(pFirst->z);
+  sqliteSetNString(pz, pFirst->z, n, 0);
+  z = *pz;
+  if( z==0 ) return;
+  for(i=j=0; z[i]; i++){
+    int c = z[i];
+    if( isspace(c) ) continue;
+    z[j++] = c;
+  }
+  z[j] = 0;
+  if( pParse->db->file_format>=4 ){
+    pCol->sortOrder = sqliteCollateType(z, n);
+  }else{
+    pCol->sortOrder = SQLITE_SO_NUM;
+  }
+}
+
+/*
+** The given token is the default value for the last column added to
+** the table currently under construction.  If "minusFlag" is true, it
+** means the value token was preceded by a minus sign.
+**
+** This routine is called by the parser while in the middle of
+** parsing a CREATE TABLE statement.
+*/
+void sqliteAddDefaultValue(Parse *pParse, Token *pVal, int minusFlag){
+  Table *p;
+  int i;
+  char **pz;
+  if( (p = pParse->pNewTable)==0 ) return;
+  i = p->nCol-1;
+  if( i<0 ) return;
+  pz = &p->aCol[i].zDflt;
+  if( minusFlag ){
+    sqliteSetNString(pz, "-", 1, pVal->z, pVal->n, 0);
+  }else{
+    sqliteSetNString(pz, pVal->z, pVal->n, 0);
+  }
+  sqliteDequote(*pz);
+}
+
+/*
+** Designate the PRIMARY KEY for the table.  pList is a list of names 
+** of columns that form the primary key.  If pList is NULL, then the
+** most recently added column of the table is the primary key.
+**
+** A table can have at most one primary key.  If the table already has
+** a primary key (and this is the second primary key) then create an
+** error.
+**
+** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
+** then we will try to use that column as the row id.  (Exception:
+** For backwards compatibility with older databases, do not do this
+** if the file format version number is less than 1.)  Set the Table.iPKey
+** field of the table under construction to be the index of the
+** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
+** no INTEGER PRIMARY KEY.
+**
+** If the key is not an INTEGER PRIMARY KEY, then create a unique
+** index for the key.  No index is created for INTEGER PRIMARY KEYs.
+*/
+void sqliteAddPrimaryKey(Parse *pParse, IdList *pList, int onError){
+  Table *pTab = pParse->pNewTable;
+  char *zType = 0;
+  int iCol = -1;
+  if( pTab==0 ) return;
+  if( pTab->hasPrimKey ){
+    sqliteSetString(&pParse->zErrMsg, "table \"", pTab->zName, 
+        "\" has more than one primary key", 0);
+    pParse->nErr++;
+    return;
+  }
+  pTab->hasPrimKey = 1;
+  if( pList==0 ){
+    iCol = pTab->nCol - 1;
+  }else if( pList->nId==1 ){
+    for(iCol=0; iCol<pTab->nCol; iCol++){
+      if( sqliteStrICmp(pList->a[0].zName, pTab->aCol[iCol].zName)==0 ) break;
+    }
+  }
+  if( iCol>=0 && iCol<pTab->nCol ){
+    zType = pTab->aCol[iCol].zType;
+  }
+  if( pParse->db->file_format>=1 && 
+           zType && sqliteStrICmp(zType, "INTEGER")==0 ){
+    pTab->iPKey = iCol;
+    pTab->keyConf = onError;
+  }else{
+    sqliteCreateIndex(pParse, 0, 0, pList, onError, 0, 0);
+  }
+}
+
+/*
+** Return the appropriate collating type given a type name.
+**
+** The collation type is text (SQLITE_SO_TEXT) if the type
+** name contains the character stream "text" or "blob" or
+** "clob".  Any other type name is collated as numeric
+** (SQLITE_SO_NUM).
+*/
+int sqliteCollateType(const char *zType, int nType){
+  int i;
+  for(i=0; i<nType-1; i++){
+    switch( zType[i] ){
+      case 'b':
+      case 'B': {
+        if( i<nType-3 && sqliteStrNICmp(&zType[i],"blob",4)==0 ){
+          return SQLITE_SO_TEXT;
+        }
+        break;
+      }
+      case 'c':
+      case 'C': {
+        if( i<nType-3 && (sqliteStrNICmp(&zType[i],"char",4)==0 ||
+                           sqliteStrNICmp(&zType[i],"clob",4)==0)
+        ){
+          return SQLITE_SO_TEXT;
+        }
+        break;
+      }
+      case 'x':
+      case 'X': {
+        if( i>=2 && sqliteStrNICmp(&zType[i-2],"text",4)==0 ){
+          return SQLITE_SO_TEXT;
+        }
+        break;
+      }
+      default: {
+        break;
+      }
+    }
+  }
+  return SQLITE_SO_NUM;
+}
+
+/*
+** This routine is called by the parser while in the middle of
+** parsing a CREATE TABLE statement.  A "COLLATE" clause has
+** been seen on a column.  This routine sets the Column.sortOrder on
+** the column currently under construction.
+*/
+void sqliteAddCollateType(Parse *pParse, int collType){
+  Table *p;
+  int i;
+  if( (p = pParse->pNewTable)==0 ) return;
+  i = p->nCol-1;
+  if( i>=0 ) p->aCol[i].sortOrder = collType;
+}
+
+/*
+** Come up with a new random value for the schema cookie.  Make sure
+** the new value is different from the old.
+**
+** The schema cookie is used to determine when the schema for the
+** database changes.  After each schema change, the cookie value
+** changes.  When a process first reads the schema it records the
+** cookie.  Thereafter, whenever it goes to access the database,
+** it checks the cookie to make sure the schema has not changed
+** since it was last read.
+**
+** This plan is not completely bullet-proof.  It is possible for
+** the schema to change multiple times and for the cookie to be
+** set back to prior value.  But schema changes are infrequent
+** and the probability of hitting the same cookie value is only
+** 1 chance in 2^32.  So we're safe enough.
+*/
+void sqliteChangeCookie(sqlite *db, Vdbe *v){
+  if( db->next_cookie==db->schema_cookie ){
+    db->next_cookie = db->schema_cookie + sqliteRandomByte() + 1;
+    db->flags |= SQLITE_InternChanges;
+    sqliteVdbeAddOp(v, OP_Integer, db->next_cookie, 0);
+    sqliteVdbeAddOp(v, OP_SetCookie, 0, 0);
+  }
+}
+
+/*
+** Measure the number of characters needed to output the given
+** identifier.  The number returned includes any quotes used
+** but does not include the null terminator.
+*/
+static int identLength(const char *z){
+  int n;
+  int needQuote = 0;
+  for(n=0; *z; n++, z++){
+    if( *z=='\'' ){ n++; needQuote=1; }
+  }
+  return n + needQuote*2;
+}
+
+/*
+** Write an identifier onto the end of the given string.  Add
+** quote characters as needed.
+*/
+static void identPut(char *z, int *pIdx, char *zIdent){
+  int i, j, needQuote;
+  i = *pIdx;
+  for(j=0; zIdent[j]; j++){
+    if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
+  }
+  needQuote =  zIdent[j]!=0 || isdigit(zIdent[0])
+                  || sqliteKeywordCode(zIdent, j)!=TK_ID;
+  if( needQuote ) z[i++] = '\'';
+  for(j=0; zIdent[j]; j++){
+    z[i++] = zIdent[j];
+    if( zIdent[j]=='\'' ) z[i++] = '\'';
+  }
+  if( needQuote ) z[i++] = '\'';
+  z[i] = 0;
+  *pIdx = i;
+}
+
+/*
+** Generate a CREATE TABLE statement appropriate for the given
+** table.  Memory to hold the text of the statement is obtained
+** from sqliteMalloc() and must be freed by the calling function.
+*/
+static char *createTableStmt(Table *p){
+  int i, k, n;
+  char *zStmt;
+  char *zSep, *zSep2, *zEnd;
+  n = 0;
+  for(i=0; i<p->nCol; i++){
+    n += identLength(p->aCol[i].zName);
+  }
+  n += identLength(p->zName);
+  if( n<40 ){
+    zSep = "";
+    zSep2 = ",";
+    zEnd = ")";
+  }else{
+    zSep = "\n  ";
+    zSep2 = ",\n  ";
+    zEnd = "\n)";
+  }
+  n += 35 + 6*p->nCol;
+  zStmt = sqliteMallocRaw( n );
+  if( zStmt==0 ) return 0;
+  strcpy(zStmt, p->isTemp ? "CREATE TEMP TABLE " : "CREATE TABLE ");
+  k = strlen(zStmt);
+  identPut(zStmt, &k, p->zName);
+  zStmt[k++] = '(';
+  for(i=0; i<p->nCol; i++){
+    strcpy(&zStmt[k], zSep);
+    k += strlen(&zStmt[k]);
+    zSep = zSep2;
+    identPut(zStmt, &k, p->aCol[i].zName);
+  }
+  strcpy(&zStmt[k], zEnd);
+  return zStmt;
+}
+
+/*
+** This routine is called to report the final ")" that terminates
+** a CREATE TABLE statement.
+**
+** The table structure that other action routines have been building
+** is added to the internal hash tables, assuming no errors have
+** occurred.
+**
+** An entry for the table is made in the master table on disk,
+** unless this is a temporary table or initFlag==1.  When initFlag==1,
+** it means we are reading the sqlite_master table because we just
+** connected to the database or because the sqlite_master table has
+** recently changes, so the entry for this table already exists in
+** the sqlite_master table.  We do not want to create it again.
+**
+** If the pSelect argument is not NULL, it means that this routine
+** was called to create a table generated from a 
+** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
+** the new table will match the result set of the SELECT.
+*/
+void sqliteEndTable(Parse *pParse, Token *pEnd, Select *pSelect){
+  Table *p;
+  sqlite *db = pParse->db;
+
+  if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite_malloc_failed ) return;
+  p = pParse->pNewTable;
+  if( p==0 ) return;
+
+  /* If the table is generated from a SELECT, then construct the
+  ** list of columns and the text of the table.
+  */
+  if( pSelect ){
+    Table *pSelTab = sqliteResultSetOfSelect(pParse, 0, pSelect);
+    if( pSelTab==0 ) return;
+    assert( p->aCol==0 );
+    p->nCol = pSelTab->nCol;
+    p->aCol = pSelTab->aCol;
+    pSelTab->nCol = 0;
+    pSelTab->aCol = 0;
+    sqliteDeleteTable(0, pSelTab);
+  }
+
+  /* If the initFlag is 1 it means we are reading the SQL off the
+  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
+  ** So do not write to the disk again.  Extract the root page number
+  ** for the table from the pParse->newTnum field.  (The page number
+  ** should have been put there by the sqliteOpenCb routine.)
+  */
+  if( pParse->initFlag ){
+    p->tnum = pParse->newTnum;
+  }
+
+  /* If not initializing, then create a record for the new table
+  ** in the SQLITE_MASTER table of the database.  The record number
+  ** for the new table entry should already be on the stack.
+  **
+  ** If this is a TEMPORARY table, write the entry into the auxiliary
+  ** file instead of into the main database file.
+  */
+  if( !pParse->initFlag ){
+    int n;
+    Vdbe *v;
+
+    v = sqliteGetVdbe(pParse);
+    if( v==0 ) return;
+    if( p->pSelect==0 ){
+      /* A regular table */
+      sqliteVdbeAddOp(v, OP_CreateTable, 0, p->isTemp);
+      sqliteVdbeChangeP3(v, -1, (char *)&p->tnum, P3_POINTER);
+    }else{
+      /* A view */
+      sqliteVdbeAddOp(v, OP_Integer, 0, 0);
+    }
+    p->tnum = 0;
+    sqliteVdbeAddOp(v, OP_Pull, 1, 0);
+    sqliteVdbeAddOp(v, OP_String, 0, 0);
+    if( p->pSelect==0 ){
+      sqliteVdbeChangeP3(v, -1, "table", P3_STATIC);
+    }else{
+      sqliteVdbeChangeP3(v, -1, "view", P3_STATIC);
+    }
+    sqliteVdbeAddOp(v, OP_String, 0, 0);
+    sqliteVdbeChangeP3(v, -1, p->zName, P3_STATIC);
+    sqliteVdbeAddOp(v, OP_String, 0, 0);
+    sqliteVdbeChangeP3(v, -1, p->zName, P3_STATIC);
+    sqliteVdbeAddOp(v, OP_Dup, 4, 0);
+    sqliteVdbeAddOp(v, OP_String, 0, 0);
+    if( pSelect ){
+      char *z = createTableStmt(p);
+      n = z ? strlen(z) : 0;
+      sqliteVdbeChangeP3(v, -1, z, n);
+      sqliteFree(z);
+    }else{
+      assert( pEnd!=0 );
+      n = Addr(pEnd->z) - Addr(pParse->sFirstToken.z) + 1;
+      sqliteVdbeChangeP3(v, -1, pParse->sFirstToken.z, n);
+    }
+    sqliteVdbeAddOp(v, OP_MakeRecord, 5, 0);
+    sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0);
+    if( !p->isTemp ){
+      sqliteChangeCookie(db, v);
+    }
+    sqliteVdbeAddOp(v, OP_Close, 0, 0);
+    if( pSelect ){
+      int op = p->isTemp ? OP_OpenWrAux : OP_OpenWrite;
+      sqliteVdbeAddOp(v, op, 1, 0);
+      pParse->nTab = 2;
+      sqliteSelect(pParse, pSelect, SRT_Table, 1, 0, 0, 0);
+    }
+    sqliteEndWriteOperation(pParse);
+  }
+
+  /* Add the table to the in-memory representation of the database.
+  */
+  assert( pParse->nameClash==0 || pParse->initFlag==1 );
+  if( pParse->explain==0 && pParse->nameClash==0 && pParse->nErr==0 ){
+    Table *pOld;
+    FKey *pFKey;
+    pOld = sqliteHashInsert(&db->tblHash, p->zName, strlen(p->zName)+1, p);
+    if( pOld ){
+      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
+      return;
+    }
+    for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
+      int nTo = strlen(pFKey->zTo) + 1;
+      pFKey->pNextTo = sqliteHashFind(&db->aFKey, pFKey->zTo, nTo);
+      sqliteHashInsert(&db->aFKey, pFKey->zTo, nTo, pFKey);
+    }
+    pParse->pNewTable = 0;
+    db->nTable++;
+    db->flags |= SQLITE_InternChanges;
+  }
+}
+
+/*
+** The parser calls this routine in order to create a new VIEW
+*/
+void sqliteCreateView(
+  Parse *pParse,     /* The parsing context */
+  Token *pBegin,     /* The CREATE token that begins the statement */
+  Token *pName,      /* The token that holds the name of the view */
+  Select *pSelect,   /* A SELECT statement that will become the new view */
+  int isTemp         /* TRUE for a TEMPORARY view */
+){
+  Table *p;
+  int n;
+  const char *z;
+  Token sEnd;
+
+  sqliteStartTable(pParse, pBegin, pName, isTemp, 1);
+  p = pParse->pNewTable;
+  if( p==0 || pParse->nErr ){
+    sqliteSelectDelete(pSelect);
+    return;
+  }
+
+  /* Make a copy of the entire SELECT statement that defines the view.
+  ** This will force all the Expr.token.z values to be dynamically
+  ** allocated rather than point to the input string - which means that
+  ** they will persist after the current sqlite_exec() call returns.
+  */
+  p->pSelect = sqliteSelectDup(pSelect);
+  sqliteSelectDelete(pSelect);
+  if( !pParse->initFlag ){
+    sqliteViewGetColumnNames(pParse, p);
+  }
+
+  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
+  ** the end.
+  */
+  sEnd = pParse->sLastToken;
+  if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
+    sEnd.z += sEnd.n;
+  }
+  sEnd.n = 0;
+  n = ((int)sEnd.z) - (int)pBegin->z;
+  z = pBegin->z;
+  while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
+  sEnd.z = &z[n-1];
+  sEnd.n = 1;
+
+  /* Use sqliteEndTable() to add the view to the SQLITE_MASTER table */
+  sqliteEndTable(pParse, &sEnd, 0);
+  return;
+}
+
+/*
+** The Table structure pTable is really a VIEW.  Fill in the names of
+** the columns of the view in the pTable structure.  Return the number
+** of errors.  If an error is seen leave an error message in pPare->zErrMsg.
+*/
+int sqliteViewGetColumnNames(Parse *pParse, Table *pTable){
+  ExprList *pEList;
+  Select *pSel;
+  Table *pSelTab;
+  int nErr = 0;
+
+  assert( pTable );
+
+  /* A positive nCol means the columns names for this view are
+  ** already known.
+  */
+  if( pTable->nCol>0 ) return 0;
+
+  /* A negative nCol is a special marker meaning that we are currently
+  ** trying to compute the column names.  If we enter this routine with
+  ** a negative nCol, it means two or more views form a loop, like this:
+  **
+  **     CREATE VIEW one AS SELECT * FROM two;
+  **     CREATE VIEW two AS SELECT * FROM one;
+  **
+  ** Actually, this error is caught previously and so the following test
+  ** should always fail.  But we will leave it in place just to be safe.
+  */
+  if( pTable->nCol<0 ){
+    sqliteSetString(&pParse->zErrMsg, "view ", pTable->zName,
+         " is circularly defined", 0);
+    pParse->nErr++;
+    return 1;
+  }
+
+  /* If we get this far, it means we need to compute the table names.
+  */
+  assert( pTable->pSelect ); /* If nCol==0, then pTable must be a VIEW */
+  pSel = pTable->pSelect;
+
+  /* Note that the call to sqliteResultSetOfSelect() will expand any
+  ** "*" elements in this list.  But we will need to restore the list
+  ** back to its original configuration afterwards, so we save a copy of
+  ** the original in pEList.
+  */
+  pEList = pSel->pEList;
+  pSel->pEList = sqliteExprListDup(pEList);
+  if( pSel->pEList==0 ){
+    pSel->pEList = pEList;
+    return 1;  /* Malloc failed */
+  }
+  pTable->nCol = -1;
+  pSelTab = sqliteResultSetOfSelect(pParse, 0, pSel);
+  if( pSelTab ){
+    assert( pTable->aCol==0 );
+    pTable->nCol = pSelTab->nCol;
+    pTable->aCol = pSelTab->aCol;
+    pSelTab->nCol = 0;
+    pSelTab->aCol = 0;
+    sqliteDeleteTable(0, pSelTab);
+    pParse->db->flags |= SQLITE_UnresetViews;
+  }else{
+    pTable->nCol = 0;
+    nErr++;
+  }
+  sqliteSelectUnbind(pSel);
+  sqliteExprListDelete(pSel->pEList);
+  pSel->pEList = pEList;
+  return nErr;  
+}
+
+/*
+** Clear the column names from the VIEW pTable.
+**
+** This routine is called whenever any other table or view is modified.
+** The view passed into this routine might depend directly or indirectly
+** on the modified or deleted table so we need to clear the old column
+** names so that they will be recomputed.
+*/
+static void sqliteViewResetColumnNames(Table *pTable){
+  int i;
+  if( pTable==0 || pTable->pSelect==0 ) return;
+  if( pTable->nCol==0 ) return;
+  for(i=0; i<pTable->nCol; i++){
+    sqliteFree(pTable->aCol[i].zName);
+    sqliteFree(pTable->aCol[i].zDflt);
+    sqliteFree(pTable->aCol[i].zType);
+  }
+  sqliteFree(pTable->aCol);
+  pTable->aCol = 0;
+  pTable->nCol = 0;
+}
+
+/*
+** Clear the column names from every VIEW.
+*/
+void sqliteViewResetAll(sqlite *db){
+  HashElem *i;
+  if( (db->flags & SQLITE_UnresetViews)==0 ) return;
+  for(i=sqliteHashFirst(&db->tblHash); i; i=sqliteHashNext(i)){
+    Table *pTab = sqliteHashData(i);
+    if( pTab->pSelect ){
+      sqliteViewResetColumnNames(pTab);
+    }
+  }
+  db->flags &= ~SQLITE_UnresetViews;
+}
+
+/*
+** Given a token, look up a table with that name.  If not found, leave
+** an error for the parser to find and return NULL.
+*/
+Table *sqliteTableFromToken(Parse *pParse, Token *pTok){
+  char *zName;
+  Table *pTab;
+  zName = sqliteTableNameFromToken(pTok);
+  if( zName==0 ) return 0;
+  pTab = sqliteFindTable(pParse->db, zName);
+  sqliteFree(zName);
+  if( pTab==0 ){
+    sqliteSetNString(&pParse->zErrMsg, "no such table: ", 0, 
+        pTok->z, pTok->n, 0);
+    pParse->nErr++;
+  }
+  return pTab;
+}
+
+/*
+** This routine is called to do the work of a DROP TABLE statement.
+** pName is the name of the table to be dropped.
+*/
+void sqliteDropTable(Parse *pParse, Token *pName, int isView){
+  Table *pTable;
+  Vdbe *v;
+  int base;
+  sqlite *db = pParse->db;
+
+  if( pParse->nErr || sqlite_malloc_failed ) return;
+  pTable = sqliteTableFromToken(pParse, pName);
+  if( pTable==0 ) return;
+#ifndef SQLITE_OMIT_AUTHORIZATION
+  if( sqliteAuthCheck(pParse, SQLITE_DELETE, SCHEMA_TABLE(pTable->isTemp),0)){
+    return;
+  }
+  {
+    int code;
+    if( isView ){
+      if( pTable->isTemp ){
+        code = SQLITE_DROP_TEMP_VIEW;
+      }else{
+        code = SQLITE_DROP_VIEW;
+      }
+    }else{
+      if( pTable->isTemp ){
+        code = SQLITE_DROP_TEMP_TABLE;
+      }else{
+        code = SQLITE_DROP_TABLE;
+      }
+    }
+    if( sqliteAuthCheck(pParse, code, pTable->zName, 0) ){
+      return;
+    }
+    if( sqliteAuthCheck(pParse, SQLITE_DELETE, pTable->zName, 0) ){
+      return;
+    }
+  }
+#endif
+  if( pTable->readOnly ){
+    sqliteSetString(&pParse->zErrMsg, "table ", pTable->zName, 
+       " may not be dropped", 0);
+    pParse->nErr++;
+    return;
+  }
+  if( isView && pTable->pSelect==0 ){
+    sqliteSetString(&pParse->zErrMsg, "use DROP TABLE to delete table ",
+      pTable->zName, 0);
+    pParse->nErr++;
+    return;
+  }
+  if( !isView && pTable->pSelect ){
+    sqliteSetString(&pParse->zErrMsg, "use DROP VIEW to delete view ",
+      pTable->zName, 0);
+    pParse->nErr++;
+    return;
+  }
+
+  /* Generate code to remove the table from the master table
+  ** on disk.
+  */
+  v = sqliteGetVdbe(pParse);
+  if( v ){
+    static VdbeOp dropTable[] = {
+      { OP_Rewind,     0, ADDR(8),  0},
+      { OP_String,     0, 0,        0}, /* 1 */
+      { OP_MemStore,   1, 1,        0},
+      { OP_MemLoad,    1, 0,        0}, /* 3 */
+      { OP_Column,     0, 2,        0},
+      { OP_Ne,         0, ADDR(7),  0},
+      { OP_Delete,     0, 0,        0},
+      { OP_Next,       0, ADDR(3),  0}, /* 7 */
+    };
+    Index *pIdx;
+    Trigger *pTrigger;
+    sqliteBeginWriteOperation(pParse, 0, pTable->isTemp);
+    sqliteOpenMasterTable(v, pTable->isTemp);
+    /* Drop all triggers associated with the table being dropped */
+    pTrigger = pTable->pTrigger;
+    while( pTrigger ){
+      Token tt;
+      tt.z = pTable->pTrigger->name;
+      tt.n = strlen(pTable->pTrigger->name);
+      sqliteDropTrigger(pParse, &tt, 1);
+      if( pParse->explain ){
+        pTrigger = pTrigger->pNext;
+      }else{
+        pTrigger = pTable->pTrigger;
+      }
+    }
+    base = sqliteVdbeAddOpList(v, ArraySize(dropTable), dropTable);
+    sqliteVdbeChangeP3(v, base+1, pTable->zName, 0);
+    if( !pTable->isTemp ){
+      sqliteChangeCookie(db, v);
+    }
+    sqliteVdbeAddOp(v, OP_Close, 0, 0);
+    if( !isView ){
+      sqliteVdbeAddOp(v, OP_Destroy, pTable->tnum, pTable->isTemp);
+      for(pIdx=pTable->pIndex; pIdx; pIdx=pIdx->pNext){
+        sqliteVdbeAddOp(v, OP_Destroy, pIdx->tnum, pTable->isTemp);
+      }
+    }
+    sqliteEndWriteOperation(pParse);
+  }
+
+  /* Delete the in-memory description of the table.
+  **
+  ** Exception: if the SQL statement began with the EXPLAIN keyword,
+  ** then no changes should be made.
+  */
+  if( !pParse->explain ){
+    sqliteUnlinkAndDeleteTable(db, pTable);
+    db->flags |= SQLITE_InternChanges;
+  }
+  sqliteViewResetAll(db);
+}
+
+/*
+** This routine constructs a P3 string suitable for an OP_MakeIdxKey
+** opcode and adds that P3 string to the most recently inserted instruction
+** in the virtual machine.  The P3 string consists of a single character
+** for each column in the index pIdx of table pTab.  If the column uses
+** a numeric sort order, then the P3 string character corresponding to
+** that column is 'n'.  If the column uses a text sort order, then the
+** P3 string is 't'.  See the OP_MakeIdxKey opcode documentation for
+** additional information.  See also the sqliteAddKeyType() routine.
+*/
+void sqliteAddIdxKeyType(Vdbe *v, Index *pIdx){
+  char *zType;
+  Table *pTab;
+  int i, n;
+  assert( pIdx!=0 && pIdx->pTable!=0 );
+  pTab = pIdx->pTable;
+  n = pIdx->nColumn;
+  zType = sqliteMallocRaw( n+1 );
+  if( zType==0 ) return;
+  for(i=0; i<n; i++){
+    int iCol = pIdx->aiColumn[i];
+    assert( iCol>=0 && iCol<pTab->nCol );
+    if( (pTab->aCol[iCol].sortOrder & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
+      zType[i] = 't';
+    }else{
+      zType[i] = 'n';
+    }
+  }
+  zType[n] = 0;
+  sqliteVdbeChangeP3(v, -1, zType, n);
+  sqliteFree(zType);
+}
+
+/*
+** This routine is called to create a new foreign key on the table
+** currently under construction.  pFromCol determines which columns
+** in the current table point to the foreign key.  If pFromCol==0 then
+** connect the key to the last column inserted.  pTo is the name of
+** the table referred to.  pToCol is a list of tables in the other
+** pTo table that the foreign key points to.  flags contains all
+** information about the conflict resolution algorithms specified
+** in the ON DELETE, ON UPDATE and ON INSERT clauses.
+**
+** An FKey structure is created and added to the table currently
+** under construction in the pParse->pNewTable field.  The new FKey
+** is not linked into db->aFKey at this point - that does not happen
+** until sqliteEndTable().
+**
+** The foreign key is set for IMMEDIATE processing.  A subsequent call
+** to sqliteDeferForeignKey() might change this to DEFERRED.
+*/
+void sqliteCreateForeignKey(
+  Parse *pParse,       /* Parsing context */
+  IdList *pFromCol,    /* Columns in this table that point to other table */
+  Token *pTo,          /* Name of the other table */
+  IdList *pToCol,      /* Columns in the other table */
+  int flags            /* Conflict resolution algorithms. */
+){
+  Table *p = pParse->pNewTable;
+  int nByte;
+  int i;
+  int nCol;
+  char *z;
+  FKey *pFKey = 0;
+
+  assert( pTo!=0 );
+  if( p==0 || pParse->nErr ) goto fk_end;
+  if( pFromCol==0 ){
+    int iCol = p->nCol-1;
+    if( iCol<0 ) goto fk_end;
+    if( pToCol && pToCol->nId!=1 ){
+      sqliteSetNString(&pParse->zErrMsg, "foreign key on ", -1,
+         p->aCol[iCol].zName, -1, 
+         " should reference only one column of table ", -1,
+         pTo->z, pTo->n, 0);
+      pParse->nErr++;
+      goto fk_end;
+    }
+    nCol = 1;
+  }else if( pToCol && pToCol->nId!=pFromCol->nId ){
+    sqliteSetString(&pParse->zErrMsg, 
+        "number of columns in foreign key does not match the number of "
+        "columns in the referenced table", 0);
+    pParse->nErr++;
+    goto fk_end;
+  }else{
+    nCol = pFromCol->nId;
+  }
+  nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
+  if( pToCol ){
+    for(i=0; i<pToCol->nId; i++){
+      nByte += strlen(pToCol->a[i].zName) + 1;
+    }
+  }
+  pFKey = sqliteMalloc( nByte );
+  if( pFKey==0 ) goto fk_end;
+  pFKey->pFrom = p;
+  pFKey->pNextFrom = p->pFKey;
+  z = (char*)&pFKey[1];
+  pFKey->aCol = (struct sColMap*)z;
+  z += sizeof(struct sColMap)*nCol;
+  pFKey->zTo = z;
+  memcpy(z, pTo->z, pTo->n);
+  z[pTo->n] = 0;
+  z += pTo->n+1;
+  pFKey->pNextTo = 0;
+  pFKey->nCol = nCol;
+  if( pFromCol==0 ){
+    pFKey->aCol[0].iFrom = p->nCol-1;
+  }else{
+    for(i=0; i<nCol; i++){
+      int j;
+      for(j=0; j<p->nCol; j++){
+        if( sqliteStrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
+          pFKey->aCol[i].iFrom = j;
+          break;
+        }
+      }
+      if( j>=p->nCol ){
+        sqliteSetString(&pParse->zErrMsg, "unknown column \"", 
+          pFromCol->a[i].zName, "\" in foreign key definition", 0);
+        pParse->nErr++;
+        goto fk_end;
+      }
+    }
+  }
+  if( pToCol ){
+    for(i=0; i<nCol; i++){
+      int n = strlen(pToCol->a[i].zName);
+      pFKey->aCol[i].zCol = z;
+      memcpy(z, pToCol->a[i].zName, n);
+      z[n] = 0;
+      z += n+1;
+    }
+  }
+  pFKey->isDeferred = 0;
+  pFKey->deleteConf = flags & 0xff;
+  pFKey->updateConf = (flags >> 8 ) & 0xff;
+  pFKey->insertConf = (flags >> 16 ) & 0xff;
+
+  /* Link the foreign key to the table as the last step.
+  */
+  p->pFKey = pFKey;
+  pFKey = 0;
+
+fk_end:
+  sqliteFree(pFKey);
+  sqliteIdListDelete(pFromCol);
+  sqliteIdListDelete(pToCol);
+}
+
+/*
+** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
+** clause is seen as part of a foreign key definition.  The isDeferred
+** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
+** The behavior of the most recently created foreign key is adjusted
+** accordingly.
+*/
+void sqliteDeferForeignKey(Parse *pParse, int isDeferred){
+  Table *pTab;
+  FKey *pFKey;
+  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
+  pFKey->isDeferred = isDeferred;
+}
+
+/*
+** Create a new index for an SQL table.  pIndex is the name of the index 
+** and pTable is the name of the table that is to be indexed.  Both will 
+** be NULL for a primary key or an index that is created to satisfy a
+** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
+** as the table to be indexed.  pParse->pNewTable is a table that is
+** currently being constructed by a CREATE TABLE statement.
+**
+** pList is a list of columns to be indexed.  pList will be NULL if this
+** is a primary key or unique-constraint on the most recent column added
+** to the table currently under construction.  
+*/
+void sqliteCreateIndex(
+  Parse *pParse,   /* All information about this parse */
+  Token *pName,    /* Name of the index.  May be NULL */
+  Token *pTable,   /* Name of the table to index.  Use pParse->pNewTable if 0 */
+  IdList *pList,   /* A list of columns to be indexed */
+  int onError,     /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
+  Token *pStart,   /* The CREATE token that begins a CREATE TABLE statement */
+  Token *pEnd      /* The ")" that closes the CREATE INDEX statement */
+){
+  Table *pTab;     /* Table to be indexed */
+  Index *pIndex;   /* The index to be created */
+  char *zName = 0;
+  int i, j;
+  Token nullId;             /* Fake token for an empty ID list */
+  sqlite *db = pParse->db;
+  int hideName = 0;         /* Do not put table name in the hash table */
+
+  if( pParse->nErr || sqlite_malloc_failed ) goto exit_create_index;
+
+  /*
+  ** Find the table that is to be indexed.  Return early if not found.
+  */
+  if( pTable!=0 ){
+    assert( pName!=0 );
+    pTab =  sqliteTableFromToken(pParse, pTable);
+  }else{
+    assert( pName==0 );
+    pTab =  pParse->pNewTable;
+  }
+  if( pTab==0 || pParse->nErr ) goto exit_create_index;
+  if( pTab->readOnly ){
+    sqliteSetString(&pParse->zErrMsg, "table ", pTab->zName, 
+      " may not have new indices added", 0);
+    pParse->nErr++;
+    goto exit_create_index;
+  }
+  if( pTab->pSelect ){
+    sqliteSetString(&pParse->zErrMsg, "views may not be indexed", 0);
+    pParse->nErr++;
+    goto exit_create_index;
+  }
+
+  /* If this index is created while re-reading the schema from sqlite_master
+  ** but the table associated with this index is a temporary table, it can
+  ** only mean that the table that this index is really associated with is
+  ** one whose name is hidden behind a temporary table with the same name.
+  ** Since its table has been suppressed, we need to also suppress the
+  ** index.
+  */
+  if( pParse->initFlag && !pParse->isTemp && pTab->isTemp ){
+    goto exit_create_index;
+  }
+
+  /*
+  ** Find the name of the index.  Make sure there is not already another
+  ** index or table with the same name.  
+  **
+  ** Exception:  If we are reading the names of permanent indices from the
+  ** sqlite_master table (because some other process changed the schema) and
+  ** one of the index names collides with the name of a temporary table or
+  ** index, then we will continue to process this index, but we will not
+  ** store its name in the hash table.  Set the hideName flag to accomplish
+  ** this.
+  **
+  ** If pName==0 it means that we are
+  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
+  ** own name.
+  */
+  if( pName ){
+    Index *pISameName;    /* Another index with the same name */
+    Table *pTSameName;    /* A table with same name as the index */
+    zName = sqliteTableNameFromToken(pName);
+    if( zName==0 ) goto exit_create_index;
+    if( (pISameName = sqliteFindIndex(db, zName))!=0 ){
+      if( pISameName->pTable->isTemp && pParse->initFlag ){
+        hideName = 1;
+      }else{
+        sqliteSetString(&pParse->zErrMsg, "index ", zName, 
+           " already exists", 0);
+        pParse->nErr++;
+        goto exit_create_index;
+      }
+    }
+    if( (pTSameName = sqliteFindTable(db, zName))!=0 ){
+      if( pTSameName->isTemp && pParse->initFlag ){
+        hideName = 1;
+      }else{
+        sqliteSetString(&pParse->zErrMsg, "there is already a table named ",
+           zName, 0);
+        pParse->nErr++;
+        goto exit_create_index;
+      }
+    }
+  }else{
+    char zBuf[30];
+    int n;
+    Index *pLoop;
+    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
+    sprintf(zBuf,"%d)",n);
+    zName = 0;
+    sqliteSetString(&zName, "(", pTab->zName, " autoindex ", zBuf, 0);
+    if( zName==0 ) goto exit_create_index;
+    hideName = sqliteFindIndex(db, zName)!=0;
+  }
+
+  /* Check for authorization to create an index.
+  */
+#ifndef SQLITE_OMIT_AUTHORIZATION
+  if( sqliteAuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(pTab->isTemp), 0) ){
+    goto exit_create_index;
+  }
+  i = SQLITE_CREATE_INDEX;
+  if( pTab->isTemp ) i = SQLITE_CREATE_TEMP_INDEX;
+  if( sqliteAuthCheck(pParse, i, zName, pTab->zName) ){
+    goto exit_create_index;
+  }
+#endif
+
+  /* If pList==0, it means this routine was called to make a primary
+  ** key out of the last column added to the table under construction.
+  ** So create a fake list to simulate this.
+  */
+  if( pList==0 ){
+    nullId.z = pTab->aCol[pTab->nCol-1].zName;
+    nullId.n = strlen(nullId.z);
+    pList = sqliteIdListAppend(0, &nullId);
+    if( pList==0 ) goto exit_create_index;
+  }
+
+  /* 
+  ** Allocate the index structure. 
+  */
+  pIndex = sqliteMalloc( sizeof(Index) + strlen(zName) + 1 +
+                        sizeof(int)*pList->nId );
+  if( pIndex==0 ) goto exit_create_index;
+  pIndex->aiColumn = (int*)&pIndex[1];
+  pIndex->zName = (char*)&pIndex->aiColumn[pList->nId];
+  strcpy(pIndex->zName, zName);
+  pIndex->pTable = pTab;
+  pIndex->nColumn = pList->nId;
+  pIndex->onError = pIndex->isUnique = onError;
+  pIndex->autoIndex = pName==0;
+
+  /* Scan the names of the columns of the table to be indexed and
+  ** load the column indices into the Index structure.  Report an error
+  ** if any column is not found.
+  */
+  for(i=0; i<pList->nId; i++){
+    for(j=0; j<pTab->nCol; j++){
+      if( sqliteStrICmp(pList->a[i].zName, pTab->aCol[j].zName)==0 ) break;
+    }
+    if( j>=pTab->nCol ){
+      sqliteSetString(&pParse->zErrMsg, "table ", pTab->zName, 
+        " has no column named ", pList->a[i].zName, 0);
+      pParse->nErr++;
+      sqliteFree(pIndex);
+      goto exit_create_index;
+    }
+    pIndex->aiColumn[i] = j;
+  }
+
+  /* Link the new Index structure to its table and to the other
+  ** in-memory database structures. 
+  */
+  if( !pParse->explain && !hideName ){
+    Index *p;
+    p = sqliteHashInsert(&db->idxHash, pIndex->zName, strlen(zName)+1, pIndex);
+    if( p ){
+      assert( p==pIndex );  /* Malloc must have failed */
+      sqliteFree(pIndex);
+      goto exit_create_index;
+    }
+    db->flags |= SQLITE_InternChanges;
+  }
+
+  /* When adding an index to the list of indices for a table, make
+  ** sure all indices labeled OE_Replace come after all those labeled
+  ** OE_Ignore.  This is necessary for the correct operation of UPDATE
+  ** and INSERT.
+  */
+  if( onError!=OE_Replace || pTab->pIndex==0
+       || pTab->pIndex->onError==OE_Replace){
+    pIndex->pNext = pTab->pIndex;
+    pTab->pIndex = pIndex;
+  }else{
+    Index *pOther = pTab->pIndex;
+    while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
+      pOther = pOther->pNext;
+    }
+    pIndex->pNext = pOther->pNext;
+    pOther->pNext = pIndex;
+  }
+
+  /* If the initFlag is 1 it means we are reading the SQL off the
+  ** "sqlite_master" table on the disk.  So do not write to the disk
+  ** again.  Extract the table number from the pParse->newTnum field.
+  */
+  if( pParse->initFlag && pTable!=0 ){
+    pIndex->tnum = pParse->newTnum;
+  }
+
+  /* If the initFlag is 0 then create the index on disk.  This
+  ** involves writing the index into the master table and filling in the
+  ** index with the current table contents.
+  **
+  ** The initFlag is 0 when the user first enters a CREATE INDEX 
+  ** command.  The initFlag is 1 when a database is opened and 
+  ** CREATE INDEX statements are read out of the master table.  In
+  ** the latter case the index already exists on disk, which is why
+  ** we don't want to recreate it.
+  **
+  ** If pTable==0 it means this index is generated as a primary key
+  ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
+  ** has just been created, it contains no data and the index initialization
+  ** step can be skipped.
+  */
+  else if( pParse->initFlag==0 ){
+    int n;
+    Vdbe *v;
+    int lbl1, lbl2;
+    int i;
+    int addr;
+    int isTemp = pTab->isTemp;
+
+    v = sqliteGetVdbe(pParse);
+    if( v==0 ) goto exit_create_index;
+    if( pTable!=0 ){
+      sqliteBeginWriteOperation(pParse, 0, isTemp);
+      sqliteOpenMasterTable(v, isTemp);
+    }
+    sqliteVdbeAddOp(v, OP_NewRecno, 0, 0);
+    sqliteVdbeAddOp(v, OP_String, 0, 0);
+    sqliteVdbeChangeP3(v, -1, "index", P3_STATIC);
+    sqliteVdbeAddOp(v, OP_String, 0, 0);
+    sqliteVdbeChangeP3(v, -1, pIndex->zName, P3_STATIC);
+    sqliteVdbeAddOp(v, OP_String, 0, 0);
+    sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
+    addr = sqliteVdbeAddOp(v, OP_CreateIndex, 0, isTemp);
+    sqliteVdbeChangeP3(v, addr, (char*)&pIndex->tnum, P3_POINTER);
+    pIndex->tnum = 0;
+    if( pTable ){
+      sqliteVdbeAddOp(v, OP_Dup, 0, 0);
+      if( isTemp ){
+        sqliteVdbeAddOp(v, OP_OpenWrAux, 1, 0);
+      }else{
+        sqliteVdbeAddOp(v, OP_OpenWrite, 1, 0);
+      }
+    }
+    addr = sqliteVdbeAddOp(v, OP_String, 0, 0);
+    if( pStart && pEnd ){
+      n = Addr(pEnd->z) - Addr(pStart->z) + 1;
+      sqliteVdbeChangeP3(v, addr, pStart->z, n);
+    }
+    sqliteVdbeAddOp(v, OP_MakeRecord, 5, 0);
+    sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0);
+    if( pTable ){
+      sqliteVdbeAddOp(v, isTemp ? OP_OpenAux : OP_Open, 2, pTab->tnum);
+      sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
+      lbl2 = sqliteVdbeMakeLabel(v);
+      sqliteVdbeAddOp(v, OP_Rewind, 2, lbl2);
+      lbl1 = sqliteVdbeAddOp(v, OP_Recno, 2, 0);
+      for(i=0; i<pIndex->nColumn; i++){
+        sqliteVdbeAddOp(v, OP_Column, 2, pIndex->aiColumn[i]);
+      }
+      sqliteVdbeAddOp(v, OP_MakeIdxKey, pIndex->nColumn, 0);
+      if( db->file_format>=4 ) sqliteAddIdxKeyType(v, pIndex);
+      sqliteVdbeAddOp(v, OP_IdxPut, 1, pIndex->onError!=OE_None);
+      sqliteVdbeChangeP3(v, -1, "indexed columns are not unique", P3_STATIC);
+      sqliteVdbeAddOp(v, OP_Next, 2, lbl1);
+      sqliteVdbeResolveLabel(v, lbl2);
+      sqliteVdbeAddOp(v, OP_Close, 2, 0);
+      sqliteVdbeAddOp(v, OP_Close, 1, 0);
+    }
+    if( pTable!=0 ){
+      if( !isTemp ){
+        sqliteChangeCookie(db, v);
+      }
+      sqliteVdbeAddOp(v, OP_Close, 0, 0);
+      sqliteEndWriteOperation(pParse);
+    }
+  }
+
+  /* Clean up before exiting */
+exit_create_index:
+  sqliteIdListDelete(pList);
+  sqliteFree(zName);
+  return;
+}
+
+/*
+** This routine will drop an existing named index.  This routine
+** implements the DROP INDEX statement.
+*/
+void sqliteDropIndex(Parse *pParse, Token *pName){
+  Index *pIndex;
+  char *zName;
+  Vdbe *v;
+  sqlite *db = pParse->db;
+
+  if( pParse->nErr || sqlite_malloc_failed ) return;
+  zName = sqliteTableNameFromToken(pName);
+  if( zName==0 ) return;
+  pIndex = sqliteFindIndex(db, zName);
+  sqliteFree(zName);
+  if( pIndex==0 ){
+    sqliteSetNString(&pParse->zErrMsg, "no such index: ", 0, 
+        pName->z, pName->n, 0);
+    pParse->nErr++;
+    return;
+  }
+  if( pIndex->autoIndex ){
+    sqliteSetString(&pParse->zErrMsg, "index associated with UNIQUE "
+      "or PRIMARY KEY constraint cannot be dropped", 0);
+    pParse->nErr++;
+    return;
+  }
+#ifndef SQLITE_OMIT_AUTHORIZATION
+  {
+    int code = SQLITE_DROP_INDEX;
+    Table *pTab = pIndex->pTable;
+    if( sqliteAuthCheck(pParse, SQLITE_DELETE, SCHEMA_TABLE(pTab->isTemp), 0) ){
+      return;
+    }
+    if( pTab->isTemp ) code = SQLITE_DROP_TEMP_INDEX;
+    if( sqliteAuthCheck(pParse, code, pIndex->zName, pTab->zName) ){
+      return;
+    }
+  }
+#endif
+
+  /* Generate code to remove the index and from the master table */
+  v = sqliteGetVdbe(pParse);
+  if( v ){
+    static VdbeOp dropIndex[] = {
+      { OP_Rewind,     0, ADDR(9), 0}, 
+      { OP_String,     0, 0,       0}, /* 1 */
+      { OP_MemStore,   1, 1,       0},
+      { OP_MemLoad,    1, 0,       0}, /* 3 */
+      { OP_Column,     0, 1,       0},
+      { OP_Eq,         0, ADDR(8), 0},
+      { OP_Next,       0, ADDR(3), 0},
+      { OP_Goto,       0, ADDR(9), 0},
+      { OP_Delete,     0, 0,       0}, /* 8 */
+    };
+    int base;
+    Table *pTab = pIndex->pTable;
+
+    sqliteBeginWriteOperation(pParse, 0, pTab->isTemp);
+    sqliteOpenMasterTable(v, pTab->isTemp);
+    base = sqliteVdbeAddOpList(v, ArraySize(dropIndex), dropIndex);
+    sqliteVdbeChangeP3(v, base+1, pIndex->zName, 0);
+    if( !pTab->isTemp ){
+      sqliteChangeCookie(db, v);
+    }
+    sqliteVdbeAddOp(v, OP_Close, 0, 0);
+    sqliteVdbeAddOp(v, OP_Destroy, pIndex->tnum, pTab->isTemp);
+    sqliteEndWriteOperation(pParse);
+  }
+
+  /* Delete the in-memory description of this index.
+  */
+  if( !pParse->explain ){
+    sqliteUnlinkAndDeleteIndex(db, pIndex);
+    db->flags |= SQLITE_InternChanges;
+  }
+}
+
+/*
+** Append a new element to the given IdList.  Create a new IdList if
+** need be.
+**
+** A new IdList is returned, or NULL if malloc() fails.
+*/
+IdList *sqliteIdListAppend(IdList *pList, Token *pToken){
+  if( pList==0 ){
+    pList = sqliteMalloc( sizeof(IdList) );
+    if( pList==0 ) return 0;
+  }
+  if( (pList->nId & 7)==0 ){
+    struct IdList_item *a;
+    a = sqliteRealloc(pList->a, (pList->nId+8)*sizeof(pList->a[0]) );
+    if( a==0 ){
+      sqliteIdListDelete(pList);
+      return 0;
+    }
+    pList->a = a;
+  }
+  memset(&pList->a[pList->nId], 0, sizeof(pList->a[0]));
+  if( pToken ){
+    char **pz = &pList->a[pList->nId].zName;
+    sqliteSetNString(pz, pToken->z, pToken->n, 0);
+    if( *pz==0 ){
+      sqliteIdListDelete(pList);
+      return 0;
+    }else{
+      sqliteDequote(*pz);
+    }
+  }
+  pList->nId++;
+  return pList;
+}
+
+/*
+** Append a new table name to the given SrcList.  Create a new SrcList if
+** need be.  A new entry is created in the SrcList even if pToken is NULL.
+**
+** A new SrcList is returned, or NULL if malloc() fails.
+*/
+SrcList *sqliteSrcListAppend(SrcList *pList, Token *pToken){
+  if( pList==0 ){
+    pList = sqliteMalloc( sizeof(IdList) );
+    if( pList==0 ) return 0;
+  }
+  if( (pList->nSrc & 7)==0 ){
+    struct SrcList_item *a;
+    a = sqliteRealloc(pList->a, (pList->nSrc+8)*sizeof(pList->a[0]) );
+    if( a==0 ){
+      sqliteSrcListDelete(pList);
+      return 0;
+    }
+    pList->a = a;
+  }
+  memset(&pList->a[pList->nSrc], 0, sizeof(pList->a[0]));
+  if( pToken ){
+    char **pz = &pList->a[pList->nSrc].zName;
+    sqliteSetNString(pz, pToken->z, pToken->n, 0);
+    if( *pz==0 ){
+      sqliteSrcListDelete(pList);
+      return 0;
+    }else{
+      sqliteDequote(*pz);
+    }
+  }
+  pList->nSrc++;
+  return pList;
+}
+
+/*
+** Add an alias to the last identifier on the given identifier list.
+*/
+void sqliteSrcListAddAlias(SrcList *pList, Token *pToken){
+  if( pList && pList->nSrc>0 ){
+    int i = pList->nSrc - 1;
+    sqliteSetNString(&pList->a[i].zAlias, pToken->z, pToken->n, 0);
+    sqliteDequote(pList->a[i].zAlias);
+  }
+}
+
+/*
+** Delete an IdList.
+*/
+void sqliteIdListDelete(IdList *pList){
+  int i;
+  if( pList==0 ) return;
+  for(i=0; i<pList->nId; i++){
+    sqliteFree(pList->a[i].zName);
+  }
+  sqliteFree(pList->a);
+  sqliteFree(pList);
+}
+
+/*
+** Return the index in pList of the identifier named zId.  Return -1
+** if not found.
+*/
+int sqliteIdListIndex(IdList *pList, const char *zName){
+  int i;
+  if( pList==0 ) return -1;
+  for(i=0; i<pList->nId; i++){
+    if( sqliteStrICmp(pList->a[i].zName, zName)==0 ) return i;
+  }
+  return -1;
+}
+
+/*
+** Delete an entire SrcList including all its substructure.
+*/
+void sqliteSrcListDelete(SrcList *pList){
+  int i;
+  if( pList==0 ) return;
+  for(i=0; i<pList->nSrc; i++){
+    sqliteFree(pList->a[i].zName);
+    sqliteFree(pList->a[i].zAlias);
+    if( pList->a[i].pTab && pList->a[i].pTab->isTransient ){
+      sqliteDeleteTable(0, pList->a[i].pTab);
+    }
+    sqliteSelectDelete(pList->a[i].pSelect);
+    sqliteExprDelete(pList->a[i].pOn);
+    sqliteIdListDelete(pList->a[i].pUsing);
+  }
+  sqliteFree(pList->a);
+  sqliteFree(pList);
+}
+
+/*
+** The COPY command is for compatibility with PostgreSQL and specificially
+** for the ability to read the output of pg_dump.  The format is as
+** follows:
+**
+**    COPY table FROM file [USING DELIMITERS string]
+**
+** "table" is an existing table name.  We will read lines of code from
+** file to fill this table with data.  File might be "stdin".  The optional
+** delimiter string identifies the field separators.  The default is a tab.
+*/
+void sqliteCopy(
+  Parse *pParse,       /* The parser context */
+  Token *pTableName,   /* The name of the table into which we will insert */
+  Token *pFilename,    /* The file from which to obtain information */
+  Token *pDelimiter,   /* Use this as the field delimiter */
+  int onError          /* What to do if a constraint fails */
+){
+  Table *pTab;
+  char *zTab;
+  int i;
+  Vdbe *v;
+  int addr, end;
+  Index *pIdx;
+  char *zFile = 0;
+  sqlite *db = pParse->db;
+
+
+  zTab = sqliteTableNameFromToken(pTableName);
+  if( sqlite_malloc_failed || zTab==0 ) goto copy_cleanup;
+  pTab = sqliteTableNameToTable(pParse, zTab);
+  sqliteFree(zTab);
+  if( pTab==0 ) goto copy_cleanup;
+  zFile = sqliteStrNDup(pFilename->z, pFilename->n);
+  sqliteDequote(zFile);
+  if( sqliteAuthCheck(pParse, SQLITE_INSERT, pTab->zName, zFile)
+      || sqliteAuthCheck(pParse, SQLITE_COPY, pTab->zName, zFile) ){
+    goto copy_cleanup;
+  }
+  v = sqliteGetVdbe(pParse);
+  if( v ){
+    int openOp;
+    sqliteBeginWriteOperation(pParse, 1, pTab->isTemp);
+    addr = sqliteVdbeAddOp(v, OP_FileOpen, 0, 0);
+    sqliteVdbeChangeP3(v, addr, pFilename->z, pFilename->n);
+    sqliteVdbeDequoteP3(v, addr);
+    openOp = pTab->isTemp ? OP_OpenWrAux : OP_OpenWrite;
+    sqliteVdbeAddOp(v, openOp, 0, pTab->tnum);
+    sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
+    for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
+      sqliteVdbeAddOp(v, openOp, i, pIdx->tnum);
+      sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
+    }
+    if( db->flags & SQLITE_CountRows ){
+      sqliteVdbeAddOp(v, OP_Integer, 0, 0);  /* Initialize the row count */
+    }
+    end = sqliteVdbeMakeLabel(v);
+    addr = sqliteVdbeAddOp(v, OP_FileRead, pTab->nCol, end);
+    if( pDelimiter ){
+      sqliteVdbeChangeP3(v, addr, pDelimiter->z, pDelimiter->n);
+      sqliteVdbeDequoteP3(v, addr);
+    }else{
+      sqliteVdbeChangeP3(v, addr, "\t", 1);
+    }
+    if( pTab->iPKey>=0 ){
+      sqliteVdbeAddOp(v, OP_FileColumn, pTab->iPKey, 0);
+      sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
+    }else{
+      sqliteVdbeAddOp(v, OP_NewRecno, 0, 0);
+    }
+    for(i=0; i<pTab->nCol; i++){
+      if( i==pTab->iPKey ){
+        /* The integer primary key column is filled with NULL since its
+        ** value is always pulled from the record number */
+        sqliteVdbeAddOp(v, OP_String, 0, 0);
+      }else{
+        sqliteVdbeAddOp(v, OP_FileColumn, i, 0);
+      }
+    }
+    sqliteGenerateConstraintChecks(pParse, pTab, 0, 0, 0, 0, onError, addr);
+    sqliteCompleteInsertion(pParse, pTab, 0, 0, 0, 0);
+    if( (db->flags & SQLITE_CountRows)!=0 ){
+      sqliteVdbeAddOp(v, OP_AddImm, 1, 0);  /* Increment row count */
+    }
+    sqliteVdbeAddOp(v, OP_Goto, 0, addr);
+    sqliteVdbeResolveLabel(v, end);
+    sqliteVdbeAddOp(v, OP_Noop, 0, 0);
+    sqliteEndWriteOperation(pParse);
+    if( db->flags & SQLITE_CountRows ){
+      sqliteVdbeAddOp(v, OP_ColumnName, 0, 0);
+      sqliteVdbeChangeP3(v, -1, "rows inserted", P3_STATIC);
+      sqliteVdbeAddOp(v, OP_Callback, 1, 0);
+    }
+  }
+  
+copy_cleanup:
+  sqliteFree(zFile);
+  return;
+}
+
+/*
+** The non-standard VACUUM command is used to clean up the database,
+** collapse free space, etc.  It is modelled after the VACUUM command
+** in PostgreSQL.
+**
+** In version 1.0.x of SQLite, the VACUUM command would call
+** gdbm_reorganize() on all the database tables.  But beginning
+** with 2.0.0, SQLite no longer uses GDBM so this command has
+** become a no-op.
+*/
+void sqliteVacuum(Parse *pParse, Token *pTableName){
+  /* Do nothing */
+}
+
+/*
+** Begin a transaction
+*/
+void sqliteBeginTransaction(Parse *pParse, int onError){
+  sqlite *db;
+
+  if( pParse==0 || (db=pParse->db)==0 || db->pBe==0 ) return;
+  if( pParse->nErr || sqlite_malloc_failed ) return;
+  if( sqliteAuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0) ) return;
+  if( db->flags & SQLITE_InTrans ){
+    pParse->nErr++;
+    sqliteSetString(&pParse->zErrMsg, "cannot start a transaction "
+       "within a transaction", 0);
+    return;
+  }
+  sqliteBeginWriteOperation(pParse, 0, 0);
+  db->flags |= SQLITE_InTrans;
+  db->onError = onError;
+}
+
+/*
+** Commit a transaction
+*/
+void sqliteCommitTransaction(Parse *pParse){
+  sqlite *db;
+
+  if( pParse==0 || (db=pParse->db)==0 || db->pBe==0 ) return;
+  if( pParse->nErr || sqlite_malloc_failed ) return;
+  if( sqliteAuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0) ) return;
+  if( (db->flags & SQLITE_InTrans)==0 ){
+    pParse->nErr++;
+    sqliteSetString(&pParse->zErrMsg, 
+       "cannot commit - no transaction is active", 0);
+    return;
+  }
+  db->flags &= ~SQLITE_InTrans;
+  sqliteEndWriteOperation(pParse);
+  db->onError = OE_Default;
+}
+
+/*
+** Rollback a transaction
+*/
+void sqliteRollbackTransaction(Parse *pParse){
+  sqlite *db;
+  Vdbe *v;
+
+  if( pParse==0 || (db=pParse->db)==0 || db->pBe==0 ) return;
+  if( pParse->nErr || sqlite_malloc_failed ) return;
+  if( sqliteAuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0) ) return;
+  if( (db->flags & SQLITE_InTrans)==0 ){
+    pParse->nErr++;
+    sqliteSetString(&pParse->zErrMsg,
+       "cannot rollback - no transaction is active", 0);
+    return; 
+  }
+  v = sqliteGetVdbe(pParse);
+  if( v ){
+    sqliteVdbeAddOp(v, OP_Rollback, 0, 0);
+  }
+  db->flags &= ~SQLITE_InTrans;
+  db->onError = OE_Default;
+}
+
+/*
+** Generate VDBE code that prepares for doing an operation that
+** might change the database.
+**
+** This routine starts a new transaction if we are not already within
+** a transaction.  If we are already within a transaction, then a checkpoint
+** is set if the setCheckpoint parameter is true.  A checkpoint should
+** be set for operations that might fail (due to a constraint) part of
+** the way through and which will need to undo some writes without having to
+** rollback the whole transaction.  For operations where all constraints
+** can be checked before any changes are made to the database, it is never
+** necessary to undo a write and the checkpoint should not be set.
+**
+** The tempOnly flag indicates that only temporary tables will be changed
+** during this write operation.  The primary database table is not
+** write-locked.  Only the temporary database file gets a write lock.
+** Other processes can continue to read or write the primary database file.
+*/
+void sqliteBeginWriteOperation(Parse *pParse, int setCheckpoint, int tempOnly){
+  Vdbe *v;
+  v = sqliteGetVdbe(pParse);
+  if( v==0 ) return;
+  if( pParse->trigStack ) return; /* if this is in a trigger */
+  if( (pParse->db->flags & SQLITE_InTrans)==0 ){
+    sqliteVdbeAddOp(v, OP_Transaction, tempOnly, 0);
+    if( !tempOnly ){
+      sqliteVdbeAddOp(v, OP_VerifyCookie, pParse->db->schema_cookie, 0);
+      pParse->schemaVerified = 1;
+    }
+  }else if( setCheckpoint ){
+    sqliteVdbeAddOp(v, OP_Checkpoint, 0, 0);
+  }
+}
+
+/*
+** Generate code that concludes an operation that may have changed
+** the database.  This is a companion function to BeginWriteOperation().
+** If a transaction was started, then commit it.  If a checkpoint was
+** started then commit that.
+*/
+void sqliteEndWriteOperation(Parse *pParse){
+  Vdbe *v;
+  if( pParse->trigStack ) return; /* if this is in a trigger */
+  v = sqliteGetVdbe(pParse);
+  if( v==0 ) return;
+  if( pParse->db->flags & SQLITE_InTrans ){
+    /* Do Nothing */
+  }else{
+    sqliteVdbeAddOp(v, OP_Commit, 0, 0);
+  }
+}
+
+
+/*
+** Interpret the given string as a boolean value.
+*/
+static int getBoolean(char *z){
+  static char *azTrue[] = { "yes", "on", "true" };
+  int i;
+  if( z[0]==0 ) return 0;
+  if( isdigit(z[0]) || (z[0]=='-' && isdigit(z[1])) ){
+    return atoi(z);
+  }
+  for(i=0; i<sizeof(azTrue)/sizeof(azTrue[0]); i++){
+    if( sqliteStrICmp(z,azTrue[i])==0 ) return 1;
+  }
+  return 0;
+}
+
+/*
+** Interpret the given string as a safety level.  Return 0 for OFF,
+** 1 for ON or NORMAL and 2 for FULL.
+**
+** Note that the values returned are one less that the values that
+** should be passed into sqliteBtreeSetSafetyLevel().  The is done
+** to support legacy SQL code.  The safety level used to be boolean
+** and older scripts may have used numbers 0 for OFF and 1 for ON.
+*/
+static int getSafetyLevel(char *z){
+  static const struct {
+    const char *zWord;
+    int val;
+  } aKey[] = {
+    { "no",    0 },
+    { "off",   0 },
+    { "false", 0 },
+    { "yes",   1 },
+    { "on",    1 },
+    { "true",  1 },
+    { "full",  2 },
+  };
+  int i;
+  if( z[0]==0 ) return 1;
+  if( isdigit(z[0]) || (z[0]=='-' && isdigit(z[1])) ){
+    return atoi(z);
+  }
+  for(i=0; i<sizeof(aKey)/sizeof(aKey[0]); i++){
+    if( sqliteStrICmp(z,aKey[i].zWord)==0 ) return aKey[i].val;
+  }
+  return 1;
+}
+
+/*
+** Process a pragma statement.  
+**
+** Pragmas are of this form:
+**
+**      PRAGMA id = value
+**
+** The identifier might also be a string.  The value is a string, and
+** identifier, or a number.  If minusFlag is true, then the value is
+** a number that was preceded by a minus sign.
+*/
+void sqlitePragma(Parse *pParse, Token *pLeft, Token *pRight, int minusFlag){
+  char *zLeft = 0;
+  char *zRight = 0;
+  sqlite *db = pParse->db;
+
+  zLeft = sqliteStrNDup(pLeft->z, pLeft->n);
+  sqliteDequote(zLeft);
+  if( minusFlag ){
+    zRight = 0;
+    sqliteSetNString(&zRight, "-", 1, pRight->z, pRight->n, 0);
+  }else{
+    zRight = sqliteStrNDup(pRight->z, pRight->n);
+    sqliteDequote(zRight);
+  }
+  if( sqliteAuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight) ){
+    sqliteFree(zLeft);
+    sqliteFree(zRight);
+    return;
+  }
+  /*
+  **  PRAGMA default_cache_size
+  **  PRAGMA default_cache_size=N
+  **
+  ** The first form reports the current persistent setting for the
+  ** page cache size.  The value returned is the maximum number of
+  ** pages in the page cache.  The second form sets both the current
+  ** page cache size value and the persistent page cache size value
+  ** stored in the database file.
+  **
+  ** The default cache size is stored in meta-value 2 of page 1 of the
+  ** database file.  The cache size is actually the absolute value of
+  ** this memory location.  The sign of meta-value 2 determines the
+  ** synchronous setting.  A negative value means synchronous is off
+  ** and a positive value means synchronous is on.
+  */
+  if( sqliteStrICmp(zLeft,"default_cache_size")==0 ){
+    static VdbeOp getCacheSize[] = {
+      { OP_ReadCookie,  0, 2,        0},
+      { OP_AbsValue,    0, 0,        0},
+      { OP_Dup,         0, 0,        0},
+      { OP_Integer,     0, 0,        0},
+      { OP_Ne,          0, 6,        0},
+      { OP_Integer,     MAX_PAGES,0, 0},
+      { OP_ColumnName,  0, 0,        "cache_size"},
+      { OP_Callback,    1, 0,        0},
+    };
+    Vdbe *v = sqliteGetVdbe(pParse);
+    if( v==0 ) return;
+    if( pRight->z==pLeft->z ){
+      sqliteVdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
+    }else{
+      int addr;
+      int size = atoi(zRight);
+      if( size<0 ) size = -size;
+      sqliteBeginWriteOperation(pParse, 0, 0);
+      sqliteVdbeAddOp(v, OP_Integer, size, 0);
+      sqliteVdbeAddOp(v, OP_ReadCookie, 0, 2);
+      addr = sqliteVdbeAddOp(v, OP_Integer, 0, 0);
+      sqliteVdbeAddOp(v, OP_Ge, 0, addr+3);
+      sqliteVdbeAddOp(v, OP_Negative, 0, 0);
+      sqliteVdbeAddOp(v, OP_SetCookie, 0, 2);
+      sqliteEndWriteOperation(pParse);
+      db->cache_size = db->cache_size<0 ? -size : size;
+      sqliteBtreeSetCacheSize(db->pBe, db->cache_size);
+    }
+  }else
+
+  /*
+  **  PRAGMA cache_size
+  **  PRAGMA cache_size=N
+  **
+  ** The first form reports the current local setting for the
+  ** page cache size.  The local setting can be different from
+  ** the persistent cache size value that is stored in the database
+  ** file itself.  The value returned is the maximum number of
+  ** pages in the page cache.  The second form sets the local
+  ** page cache size value.  It does not change the persistent
+  ** cache size stored on the disk so the cache size will revert
+  ** to its default value when the database is closed and reopened.
+  ** N should be a positive integer.
+  */
+  if( sqliteStrICmp(zLeft,"cache_size")==0 ){
+    static VdbeOp getCacheSize[] = {
+      { OP_ColumnName,  0, 0,        "cache_size"},
+      { OP_Callback,    1, 0,        0},
+    };
+    Vdbe *v = sqliteGetVdbe(pParse);
+    if( v==0 ) return;
+    if( pRight->z==pLeft->z ){
+      int size = db->cache_size;;
+      if( size<0 ) size = -size;
+      sqliteVdbeAddOp(v, OP_Integer, size, 0);
+      sqliteVdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
+    }else{
+      int size = atoi(zRight);
+      if( size<0 ) size = -size;
+      if( db->cache_size<0 ) size = -size;
+      db->cache_size = size;
+      sqliteBtreeSetCacheSize(db->pBe, db->cache_size);
+    }
+  }else
+
+  /*
+  **  PRAGMA default_synchronous
+  **  PRAGMA default_synchronous=ON|OFF|NORMAL|FULL
+  **
+  ** The first form returns the persistent value of the "synchronous" setting
+  ** that is stored in the database.  This is the synchronous setting that
+  ** is used whenever the database is opened unless overridden by a separate
+  ** "synchronous" pragma.  The second form changes the persistent and the
+  ** local synchronous setting to the value given.
+  **
+  ** If synchronous is OFF, SQLite does not attempt any fsync() systems calls
+  ** to make sure data is committed to disk.  Write operations are very fast,
+  ** but a power failure can leave the database in an inconsistent state.
+  ** If synchronous is ON or NORMAL, SQLite will do an fsync() system call to
+  ** make sure data is being written to disk.  The risk of corruption due to
+  ** a power loss in this mode is negligible but non-zero.  If synchronous
+  ** is FULL, extra fsync()s occur to reduce the risk of corruption to near
+  ** zero, but with a write performance penalty.  The default mode is NORMAL.
+  */
+  if( sqliteStrICmp(zLeft,"default_synchronous")==0 ){
+    static VdbeOp getSync[] = {
+      { OP_ColumnName,  0, 0,        "synchronous"},
+      { OP_ReadCookie,  0, 3,        0},
+      { OP_Dup,         0, 0,        0},
+      { OP_If,          0, 0,        0},  /* 3 */
+      { OP_ReadCookie,  0, 2,        0},
+      { OP_Integer,     0, 0,        0},
+      { OP_Lt,          0, 5,        0},
+      { OP_AddImm,      1, 0,        0},
+      { OP_Callback,    1, 0,        0},
+      { OP_Halt,        0, 0,        0},
+      { OP_AddImm,     -1, 0,        0},  /* 10 */
+      { OP_Callback,    1, 0,        0}
+    };
+    Vdbe *v = sqliteGetVdbe(pParse);
+    if( v==0 ) return;
+    if( pRight->z==pLeft->z ){
+      int addr = sqliteVdbeAddOpList(v, ArraySize(getSync), getSync);
+      sqliteVdbeChangeP2(v, addr+3, addr+10);
+    }else{
+      int addr;
+      int size = db->cache_size;
+      if( size<0 ) size = -size;
+      sqliteBeginWriteOperation(pParse, 0, 0);
+      sqliteVdbeAddOp(v, OP_ReadCookie, 0, 2);
+      sqliteVdbeAddOp(v, OP_Dup, 0, 0);
+      addr = sqliteVdbeAddOp(v, OP_Integer, 0, 0);
+      sqliteVdbeAddOp(v, OP_Ne, 0, addr+3);
+      sqliteVdbeAddOp(v, OP_AddImm, MAX_PAGES, 0);
+      sqliteVdbeAddOp(v, OP_AbsValue, 0, 0);
+      db->safety_level = getSafetyLevel(zRight)+1;
+      if( db->safety_level==1 ){
+        sqliteVdbeAddOp(v, OP_Negative, 0, 0);
+        size = -size;
+      }
+      sqliteVdbeAddOp(v, OP_SetCookie, 0, 2);
+      sqliteVdbeAddOp(v, OP_Integer, db->safety_level, 0);
+      sqliteVdbeAddOp(v, OP_SetCookie, 0, 3);
+      sqliteEndWriteOperation(pParse);
+      db->cache_size = size;
+      sqliteBtreeSetCacheSize(db->pBe, db->cache_size);
+      sqliteBtreeSetSafetyLevel(db->pBe, db->safety_level);
+    }
+  }else
+
+  /*
+  **   PRAGMA synchronous
+  **   PRAGMA synchronous=OFF|ON|NORMAL|FULL
+  **
+  ** Return or set the local value of the synchronous flag.  Changing
+  ** the local value does not make changes to the disk file and the
+  ** default value will be restored the next time the database is
+  ** opened.
+  */
+  if( sqliteStrICmp(zLeft,"synchronous")==0 ){
+    static VdbeOp getSync[] = {
+      { OP_ColumnName,  0, 0,        "synchronous"},
+      { OP_Callback,    1, 0,        0},
+    };
+    Vdbe *v = sqliteGetVdbe(pParse);
+    if( v==0 ) return;
+    if( pRight->z==pLeft->z ){
+      sqliteVdbeAddOp(v, OP_Integer, db->safety_level-1, 0);
+      sqliteVdbeAddOpList(v, ArraySize(getSync), getSync);
+    }else{
+      int size = db->cache_size;
+      if( size<0 ) size = -size;
+      db->safety_level = getSafetyLevel(zRight)+1;
+      if( db->safety_level==1 ) size = -size;
+      db->cache_size = size;
+      sqliteBtreeSetCacheSize(db->pBe, db->cache_size);
+      sqliteBtreeSetSafetyLevel(db->pBe, db->safety_level);
+    }
+  }else
+
+  if( sqliteStrICmp(zLeft, "trigger_overhead_test")==0 ){
+    if( getBoolean(zRight) ){
+      always_code_trigger_setup = 1;
+    }else{
+      always_code_trigger_setup = 0;
+    }
+  }else
+
+  if( sqliteStrICmp(zLeft, "vdbe_trace")==0 ){
+    if( getBoolean(zRight) ){
+      db->flags |= SQLITE_VdbeTrace;
+    }else{
+      db->flags &= ~SQLITE_VdbeTrace;
+    }
+  }else
+
+  if( sqliteStrICmp(zLeft, "full_column_names")==0 ){
+    if( getBoolean(zRight) ){
+      db->flags |= SQLITE_FullColNames;
+    }else{
+      db->flags &= ~SQLITE_FullColNames;
+    }
+  }else
+
+  if( sqliteStrICmp(zLeft, "show_datatypes")==0 ){
+    if( getBoolean(zRight) ){
+      db->flags |= SQLITE_ReportTypes;
+    }else{
+      db->flags &= ~SQLITE_ReportTypes;
+    }
+  }else
+
+  if( sqliteStrICmp(zLeft, "result_set_details")==0 ){
+    if( getBoolean(zRight) ){
+      db->flags |= SQLITE_ResultDetails;
+    }else{
+      db->flags &= ~SQLITE_ResultDetails;
+    }
+  }else
+
+  if( sqliteStrICmp(zLeft, "count_changes")==0 ){
+    if( getBoolean(zRight) ){
+      db->flags |= SQLITE_CountRows;
+    }else{
+      db->flags &= ~SQLITE_CountRows;
+    }
+  }else
+
+  if( sqliteStrICmp(zLeft, "empty_result_callbacks")==0 ){
+    if( getBoolean(zRight) ){
+      db->flags |= SQLITE_NullCallback;
+    }else{
+      db->flags &= ~SQLITE_NullCallback;
+    }
+  }else
+
+  if( sqliteStrICmp(zLeft, "table_info")==0 ){
+    Table *pTab;
+    Vdbe *v;
+    pTab = sqliteFindTable(db, zRight);
+    if( pTab ) v = sqliteGetVdbe(pParse);
+    if( pTab && v ){
+      static VdbeOp tableInfoPreface[] = {
+        { OP_ColumnName,  0, 0,       "cid"},
+        { OP_ColumnName,  1, 0,       "name"},
+        { OP_ColumnName,  2, 0,       "type"},
+        { OP_ColumnName,  3, 0,       "notnull"},
+        { OP_ColumnName,  4, 0,       "dflt_value"},
+      };
+      int i;
+      sqliteVdbeAddOpList(v, ArraySize(tableInfoPreface), tableInfoPreface);
+      sqliteViewGetColumnNames(pParse, pTab);
+      for(i=0; i<pTab->nCol; i++){
+        sqliteVdbeAddOp(v, OP_Integer, i, 0);
+        sqliteVdbeAddOp(v, OP_String, 0, 0);
+        sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zName, P3_STATIC);
+        sqliteVdbeAddOp(v, OP_String, 0, 0);
+        sqliteVdbeChangeP3(v, -1, 
+           pTab->aCol[i].zType ? pTab->aCol[i].zType : "numeric", P3_STATIC);
+        sqliteVdbeAddOp(v, OP_Integer, pTab->aCol[i].notNull, 0);
+        sqliteVdbeAddOp(v, OP_String, 0, 0);
+        sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
+        sqliteVdbeAddOp(v, OP_Callback, 5, 0);
+      }
+    }
+  }else
+
+  if( sqliteStrICmp(zLeft, "index_info")==0 ){
+    Index *pIdx;
+    Table *pTab;
+    Vdbe *v;
+    pIdx = sqliteFindIndex(db, zRight);
+    if( pIdx ) v = sqliteGetVdbe(pParse);
+    if( pIdx && v ){
+      static VdbeOp tableInfoPreface[] = {
+        { OP_ColumnName,  0, 0,       "seqno"},
+        { OP_ColumnName,  1, 0,       "cid"},
+        { OP_ColumnName,  2, 0,       "name"},
+      };
+      int i;
+      pTab = pIdx->pTable;
+      sqliteVdbeAddOpList(v, ArraySize(tableInfoPreface), tableInfoPreface);
+      for(i=0; i<pIdx->nColumn; i++){
+        int cnum = pIdx->aiColumn[i];
+        sqliteVdbeAddOp(v, OP_Integer, i, 0);
+        sqliteVdbeAddOp(v, OP_Integer, cnum, 0);
+        sqliteVdbeAddOp(v, OP_String, 0, 0);
+        assert( pTab->nCol>cnum );
+        sqliteVdbeChangeP3(v, -1, pTab->aCol[cnum].zName, P3_STATIC);
+        sqliteVdbeAddOp(v, OP_Callback, 3, 0);
+      }
+    }
+  }else
+
+  if( sqliteStrICmp(zLeft, "index_list")==0 ){
+    Index *pIdx;
+    Table *pTab;
+    Vdbe *v;
+    pTab = sqliteFindTable(db, zRight);
+    if( pTab ){
+      v = sqliteGetVdbe(pParse);
+      pIdx = pTab->pIndex;
+    }
+    if( pTab && pIdx && v ){
+      int i = 0; 
+      static VdbeOp indexListPreface[] = {
+        { OP_ColumnName,  0, 0,       "seq"},
+        { OP_ColumnName,  1, 0,       "name"},
+        { OP_ColumnName,  2, 0,       "unique"},
+      };
+
+      sqliteVdbeAddOpList(v, ArraySize(indexListPreface), indexListPreface);
+      while(pIdx){
+        sqliteVdbeAddOp(v, OP_Integer, i, 0);
+        sqliteVdbeAddOp(v, OP_String, 0, 0);
+        sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
+        sqliteVdbeAddOp(v, OP_Integer, pIdx->onError!=OE_None, 0);
+        sqliteVdbeAddOp(v, OP_Callback, 3, 0);
+        ++i;
+        pIdx = pIdx->pNext;
+      }
+    }
+  }else
+
+#ifndef NDEBUG
+  if( sqliteStrICmp(zLeft, "parser_trace")==0 ){
+    extern void sqliteParserTrace(FILE*, char *);
+    if( getBoolean(zRight) ){
+      sqliteParserTrace(stdout, "parser: ");
+    }else{
+      sqliteParserTrace(0, 0);
+    }
+  }else
+#endif
+
+  if( sqliteStrICmp(zLeft, "integrity_check")==0 ){
+    static VdbeOp checkDb[] = {
+      { OP_SetInsert,   0, 0,        "2"},
+      { OP_Open,        0, 2,        0},
+      { OP_Rewind,      0, 6,        0},
+      { OP_Column,      0, 3,        0},    /* 3 */
+      { OP_SetInsert,   0, 0,        0},
+      { OP_Next,        0, 3,        0},
+      { OP_IntegrityCk, 0, 0,        0},    /* 6 */
+      { OP_ColumnName,  0, 0,        "integrity_check"},
+      { OP_Callback,    1, 0,        0},
+      { OP_SetInsert,   1, 0,        "2"},
+      { OP_OpenAux,     1, 2,        0},
+      { OP_Rewind,      1, 15,       0},
+      { OP_Column,      1, 3,        0},    /* 12 */
+      { OP_SetInsert,   1, 0,        0},
+      { OP_Next,        1, 12,       0},
+      { OP_IntegrityCk, 1, 1,        0},    /* 15 */
+      { OP_Callback,    1, 0,        0},
+    };
+    Vdbe *v = sqliteGetVdbe(pParse);
+    if( v==0 ) return;
+    sqliteVdbeAddOpList(v, ArraySize(checkDb), checkDb);
+  }else
+
+  {}
+  sqliteFree(zLeft);
+  sqliteFree(zRight);
+}
diff --git a/ext/sqlite/libsqlite/src/delete.c b/ext/sqlite/libsqlite/src/delete.c
new file mode 100644 (file)
index 0000000..a235b6c
--- /dev/null
@@ -0,0 +1,389 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains C code routines that are called by the parser
+** to handle DELETE FROM statements.
+**
+** $Id$
+*/
+#include "sqliteInt.h"
+
+
+/*
+** Given a table name, find the corresponding table and make sure the
+** table is writeable.  Generate an error and return NULL if not.  If
+** everything checks out, return a pointer to the Table structure.
+*/
+Table *sqliteTableNameToTable(Parse *pParse, const char *zTab){
+  Table *pTab;
+  pTab = sqliteFindTable(pParse->db, zTab);
+  if( pTab==0 ){
+    sqliteSetString(&pParse->zErrMsg, "no such table: ", zTab, 0);
+    pParse->nErr++;
+    return 0;
+  }
+  if( pTab->readOnly || pTab->pSelect ){
+    sqliteSetString(&pParse->zErrMsg, 
+      pTab->pSelect ? "view " : "table ",
+      zTab,
+      " may not be modified", 0);
+    pParse->nErr++;
+    return 0;      
+  }
+  return pTab;
+}
+
+/*
+** Given a table name, check to make sure the table exists, is writable
+** and is not a view.  If everything is OK, construct an SrcList holding
+** the table and return a pointer to the SrcList.  The calling function
+** is responsible for freeing the SrcList when it has finished with it.
+** If there is an error, leave a message on pParse->zErrMsg and return
+** NULL.
+*/
+SrcList *sqliteTableTokenToSrcList(Parse *pParse, Token *pTableName){
+  Table *pTab;
+  SrcList *pTabList;
+
+  pTabList = sqliteSrcListAppend(0, pTableName);
+  if( pTabList==0 ) return 0;
+  assert( pTabList->nSrc==1 );
+  pTab = sqliteTableNameToTable(pParse, pTabList->a[0].zName);
+  if( pTab==0 ){
+    sqliteSrcListDelete(pTabList);
+    return 0;
+  }
+  pTabList->a[0].pTab = pTab;
+  return pTabList;
+}
+
+/*
+** Process a DELETE FROM statement.
+*/
+void sqliteDeleteFrom(
+  Parse *pParse,         /* The parser context */
+  Token *pTableName,     /* The table from which we should delete things */
+  Expr *pWhere           /* The WHERE clause.  May be null */
+){
+  Vdbe *v;               /* The virtual database engine */
+  Table *pTab;           /* The table from which records will be deleted */
+  char *zTab;            /* Name of the table from which we are deleting */
+  SrcList *pTabList;     /* A fake FROM clause holding just pTab */
+  int end, addr;         /* A couple addresses of generated code */
+  int i;                 /* Loop counter */
+  WhereInfo *pWInfo;     /* Information about the WHERE clause */
+  Index *pIdx;           /* For looping over indices of the table */
+  int base;              /* Index of the first available table cursor */
+  sqlite *db;            /* Main database structure */
+  int openOp;            /* Opcode used to open a cursor to the table */
+
+  int row_triggers_exist = 0;
+  int oldIdx = -1;
+
+  if( pParse->nErr || sqlite_malloc_failed ){
+    pTabList = 0;
+    goto delete_from_cleanup;
+  }
+  db = pParse->db;
+
+  /* Check for the special case of a VIEW with one or more ON DELETE triggers 
+  ** defined 
+  */
+  zTab = sqliteTableNameFromToken(pTableName);
+  if( zTab != 0 ){
+    pTab = sqliteFindTable(pParse->db, zTab);
+    if( pTab ){
+      row_triggers_exist = 
+        sqliteTriggersExist(pParse, pTab->pTrigger, 
+            TK_DELETE, TK_BEFORE, TK_ROW, 0) ||
+        sqliteTriggersExist(pParse, pTab->pTrigger, 
+            TK_DELETE, TK_AFTER, TK_ROW, 0);
+    }
+    sqliteFree(zTab);
+    if( row_triggers_exist &&  pTab->pSelect ){
+      /* Just fire VIEW triggers */
+      sqliteViewTriggers(pParse, pTab, pWhere, OE_Replace, 0);
+      return;
+    }
+  }
+
+  /* Locate the table which we want to delete.  This table has to be
+  ** put in an SrcList structure because some of the subroutines we
+  ** will be calling are designed to work with multiple tables and expect
+  ** an SrcList* parameter instead of just a Table* parameter.
+  */
+  pTabList = sqliteTableTokenToSrcList(pParse, pTableName);
+  if( pTabList==0 ) goto delete_from_cleanup;
+  assert( pTabList->nSrc==1 );
+  pTab = pTabList->a[0].pTab;
+  assert( pTab->pSelect==0 );  /* This table is not a view */
+  if( sqliteAuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0) ){
+    goto delete_from_cleanup;
+  }
+
+  /* Allocate a cursor used to store the old.* data for a trigger.
+  */
+  if( row_triggers_exist ){ 
+    oldIdx = pParse->nTab++;
+  }
+
+  /* Resolve the column names in all the expressions.
+  */
+  base = pParse->nTab++;
+  if( pWhere ){
+    if( sqliteExprResolveIds(pParse, base, pTabList, 0, pWhere) ){
+      goto delete_from_cleanup;
+    }
+    if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
+      goto delete_from_cleanup;
+    }
+  }
+
+  /* Begin generating code.
+  */
+  v = sqliteGetVdbe(pParse);
+  if( v==0 ){
+    goto delete_from_cleanup;
+  }
+  sqliteBeginWriteOperation(pParse, row_triggers_exist,
+       !row_triggers_exist && pTab->isTemp);
+
+  /* Initialize the counter of the number of rows deleted, if
+  ** we are counting rows.
+  */
+  if( db->flags & SQLITE_CountRows ){
+    sqliteVdbeAddOp(v, OP_Integer, 0, 0);
+  }
+
+  /* Special case: A DELETE without a WHERE clause deletes everything.
+  ** It is easier just to erase the whole table.  Note, however, that
+  ** this means that the row change count will be incorrect.
+  */
+  if( pWhere==0 && !row_triggers_exist ){
+    if( db->flags & SQLITE_CountRows ){
+      /* If counting rows deleted, just count the total number of
+      ** entries in the table. */
+      int endOfLoop = sqliteVdbeMakeLabel(v);
+      int addr;
+      openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
+      sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
+      sqliteVdbeAddOp(v, OP_Rewind, base, sqliteVdbeCurrentAddr(v)+2);
+      addr = sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
+      sqliteVdbeAddOp(v, OP_Next, base, addr);
+      sqliteVdbeResolveLabel(v, endOfLoop);
+      sqliteVdbeAddOp(v, OP_Close, base, 0);
+    }
+    sqliteVdbeAddOp(v, OP_Clear, pTab->tnum, pTab->isTemp);
+    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+      sqliteVdbeAddOp(v, OP_Clear, pIdx->tnum, pTab->isTemp);
+    }
+  }
+
+  /* The usual case: There is a WHERE clause so we have to scan through
+  ** the table an pick which records to delete.
+  */
+  else{
+    /* Begin the database scan
+    */
+    pWInfo = sqliteWhereBegin(pParse, base, pTabList, pWhere, 1, 0);
+    if( pWInfo==0 ) goto delete_from_cleanup;
+
+    /* Remember the key of every item to be deleted.
+    */
+    sqliteVdbeAddOp(v, OP_ListWrite, 0, 0);
+    if( db->flags & SQLITE_CountRows ){
+      sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
+    }
+
+    /* End the database scan loop.
+    */
+    sqliteWhereEnd(pWInfo);
+
+    /* Delete every item whose key was written to the list during the
+    ** database scan.  We have to delete items after the scan is complete
+    ** because deleting an item can change the scan order.
+    */
+    sqliteVdbeAddOp(v, OP_ListRewind, 0, 0);
+    end = sqliteVdbeMakeLabel(v);
+
+    /* This is the beginning of the delete loop when there are
+    ** row triggers.
+    */
+    if( row_triggers_exist ){
+      addr = sqliteVdbeAddOp(v, OP_ListRead, 0, end);
+      sqliteVdbeAddOp(v, OP_Dup, 0, 0);
+
+      openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
+      sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
+      sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
+      sqliteVdbeAddOp(v, OP_OpenTemp, oldIdx, 0);
+
+      sqliteVdbeAddOp(v, OP_Integer, 13, 0);
+      for(i = 0; i<pTab->nCol; i++){
+        if( i==pTab->iPKey ){ 
+          sqliteVdbeAddOp(v, OP_Recno, base, 0);
+       } else {
+          sqliteVdbeAddOp(v, OP_Column, base, i);
+       }
+      }
+      sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
+      sqliteVdbeAddOp(v, OP_PutIntKey, oldIdx, 0);
+      sqliteVdbeAddOp(v, OP_Close, base, 0);
+      sqliteVdbeAddOp(v, OP_Rewind, oldIdx, 0);
+
+      sqliteCodeRowTrigger(pParse, TK_DELETE, 0, TK_BEFORE, pTab, -1, 
+          oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
+         addr);
+    }
+
+    /* Open cursors for the table we are deleting from and all its
+    ** indices.  If there are row triggers, this happens inside the
+    ** OP_ListRead loop because the cursor have to all be closed
+    ** before the trigger fires.  If there are no row triggers, the
+    ** cursors are opened only once on the outside the loop.
+    */
+    pParse->nTab = base + 1;
+    openOp = pTab->isTemp ? OP_OpenWrAux : OP_OpenWrite;
+    sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
+    for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
+      sqliteVdbeAddOp(v, openOp, pParse->nTab++, pIdx->tnum);
+    }
+
+    /* This is the beginning of the delete loop when there are no
+    ** row triggers */
+    if( !row_triggers_exist ){ 
+      addr = sqliteVdbeAddOp(v, OP_ListRead, 0, end);
+    }
+
+    /* Delete the row */
+    sqliteGenerateRowDelete(db, v, pTab, base, pParse->trigStack==0);
+
+    /* If there are row triggers, close all cursors then invoke
+    ** the AFTER triggers
+    */
+    if( row_triggers_exist ){
+      for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
+        sqliteVdbeAddOp(v, OP_Close, base + i, pIdx->tnum);
+      }
+      sqliteVdbeAddOp(v, OP_Close, base, 0);
+      sqliteCodeRowTrigger(pParse, TK_DELETE, 0, TK_AFTER, pTab, -1, 
+          oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
+         addr);
+    }
+
+    /* End of the delete loop */
+    sqliteVdbeAddOp(v, OP_Goto, 0, addr);
+    sqliteVdbeResolveLabel(v, end);
+    sqliteVdbeAddOp(v, OP_ListReset, 0, 0);
+
+    /* Close the cursors after the loop if there are no row triggers */
+    if( !row_triggers_exist ){
+      for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
+        sqliteVdbeAddOp(v, OP_Close, base + i, pIdx->tnum);
+      }
+      sqliteVdbeAddOp(v, OP_Close, base, 0);
+      pParse->nTab = base;
+    }
+  }
+  sqliteEndWriteOperation(pParse);
+
+  /*
+  ** Return the number of rows that were deleted.
+  */
+  if( db->flags & SQLITE_CountRows ){
+    sqliteVdbeAddOp(v, OP_ColumnName, 0, 0);
+    sqliteVdbeChangeP3(v, -1, "rows deleted", P3_STATIC);
+    sqliteVdbeAddOp(v, OP_Callback, 1, 0);
+  }
+
+delete_from_cleanup:
+  sqliteSrcListDelete(pTabList);
+  sqliteExprDelete(pWhere);
+  return;
+}
+
+/*
+** This routine generates VDBE code that causes a single row of a
+** single table to be deleted.
+**
+** The VDBE must be in a particular state when this routine is called.
+** These are the requirements:
+**
+**   1.  A read/write cursor pointing to pTab, the table containing the row
+**       to be deleted, must be opened as cursor number "base".
+**
+**   2.  Read/write cursors for all indices of pTab must be open as
+**       cursor number base+i for the i-th index.
+**
+**   3.  The record number of the row to be deleted must be on the top
+**       of the stack.
+**
+** This routine pops the top of the stack to remove the record number
+** and then generates code to remove both the table record and all index
+** entries that point to that record.
+*/
+void sqliteGenerateRowDelete(
+  sqlite *db,        /* The database containing the index */
+  Vdbe *v,           /* Generate code into this VDBE */
+  Table *pTab,       /* Table containing the row to be deleted */
+  int base,          /* Cursor number for the table */
+  int count          /* Increment the row change counter */
+){
+  int addr;
+  addr = sqliteVdbeAddOp(v, OP_NotExists, base, 0);
+  sqliteGenerateRowIndexDelete(db, v, pTab, base, 0);
+  sqliteVdbeAddOp(v, OP_Delete, base, count);
+  sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
+}
+
+/*
+** This routine generates VDBE code that causes the deletion of all
+** index entries associated with a single row of a single table.
+**
+** The VDBE must be in a particular state when this routine is called.
+** These are the requirements:
+**
+**   1.  A read/write cursor pointing to pTab, the table containing the row
+**       to be deleted, must be opened as cursor number "base".
+**
+**   2.  Read/write cursors for all indices of pTab must be open as
+**       cursor number base+i for the i-th index.
+**
+**   3.  The "base" cursor must be pointing to the row that is to be
+**       deleted.
+*/
+void sqliteGenerateRowIndexDelete(
+  sqlite *db,        /* The database containing the index */
+  Vdbe *v,           /* Generate code into this VDBE */
+  Table *pTab,       /* Table containing the row to be deleted */
+  int base,          /* Cursor number for the table */
+  char *aIdxUsed     /* Only delete if aIdxUsed!=0 && aIdxUsed[i]!=0 */
+){
+  int i;
+  Index *pIdx;
+
+  for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
+    int j;
+    if( aIdxUsed!=0 && aIdxUsed[i-1]==0 ) continue;
+    sqliteVdbeAddOp(v, OP_Recno, base, 0);
+    for(j=0; j<pIdx->nColumn; j++){
+      int idx = pIdx->aiColumn[j];
+      if( idx==pTab->iPKey ){
+        sqliteVdbeAddOp(v, OP_Dup, j, 0);
+      }else{
+        sqliteVdbeAddOp(v, OP_Column, base, idx);
+      }
+    }
+    sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
+    if( db->file_format>=4 ) sqliteAddIdxKeyType(v, pIdx);
+    sqliteVdbeAddOp(v, OP_IdxDelete, base+i, 0);
+  }
+}
diff --git a/ext/sqlite/libsqlite/src/encode.c b/ext/sqlite/libsqlite/src/encode.c
new file mode 100644 (file)
index 0000000..6ad100c
--- /dev/null
@@ -0,0 +1,165 @@
+/*
+** 2002 April 25
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains helper routines used to translate binary data into
+** a null-terminated string (suitable for use in SQLite) and back again.
+** These are convenience routines for use by people who want to store binary
+** data in an SQLite database.  The code in this file is not used by any other
+** part of the SQLite library.
+**
+** $Id$
+*/
+#include <string.h>
+
+/*
+** Encode a binary buffer "in" of size n bytes so that it contains
+** no instances of characters '\'' or '\000'.  The output is 
+** null-terminated and can be used as a string value in an INSERT
+** or UPDATE statement.  Use sqlite_decode_binary() to convert the
+** string back into its original binary.
+**
+** The result is written into a preallocated output buffer "out".
+** "out" must be able to hold at least (256*n + 1262)/253 bytes.
+** In other words, the output will be expanded by as much as 3
+** bytes for every 253 bytes of input plus 2 bytes of fixed overhead.
+** (This is approximately 2 + 1.019*n or about a 2% size increase.)
+**
+** The return value is the number of characters in the encoded
+** string, excluding the "\000" terminator.
+*/
+int sqlite_encode_binary(const unsigned char *in, int n, unsigned char *out){
+  int i, j, e, m;
+  int cnt[256];
+  if( n<=0 ){
+    out[0] = 'x';
+    out[1] = 0;
+    return 1;
+  }
+  memset(cnt, 0, sizeof(cnt));
+  for(i=n-1; i>=0; i--){ cnt[in[i]]++; }
+  m = n;
+  for(i=1; i<256; i++){
+    int sum;
+    if( i=='\'' ) continue;
+    sum = cnt[i] + cnt[(i+1)&0xff] + cnt[(i+'\'')&0xff];
+    if( sum<m ){
+      m = sum;
+      e = i;
+      if( m==0 ) break;
+    }
+  }
+  out[0] = e;
+  j = 1;
+  for(i=0; i<n; i++){
+    int c = (in[i] - e)&0xff;
+    if( c==0 ){
+      out[j++] = 1;
+      out[j++] = 1;
+    }else if( c==1 ){
+      out[j++] = 1;
+      out[j++] = 2;
+    }else if( c=='\'' ){
+      out[j++] = 1;
+      out[j++] = 3;
+    }else{
+      out[j++] = c;
+    }
+  }
+  out[j] = 0;
+  return j;
+}
+
+/*
+** Decode the string "in" into binary data and write it into "out".
+** This routine reverses the encoded created by sqlite_encode_binary().
+** The output will always be a few bytes less than the input.  The number
+** of bytes of output is returned.  If the input is not a well-formed
+** encoding, -1 is returned.
+**
+** The "in" and "out" parameters may point to the same buffer in order
+** to decode a string in place.
+*/
+int sqlite_decode_binary(const unsigned char *in, unsigned char *out){
+  int i, c, e;
+  e = *(in++);
+  i = 0;
+  while( (c = *(in++))!=0 ){
+    if( c==1 ){
+      c = *(in++);
+      if( c==1 ){
+        c = 0;
+      }else if( c==2 ){
+        c = 1;
+      }else if( c==3 ){
+        c = '\'';
+      }else{
+        return -1;
+      }
+    }
+    out[i++] = (c + e)&0xff;
+  }
+  return i;
+}
+
+#ifdef ENCODER_TEST
+/*
+** The subroutines above are not tested by the usual test suite.  To test
+** these routines, compile just this one file with a -DENCODER_TEST=1 option
+** and run the result.
+*/
+int main(int argc, char **argv){
+  int i, j, n, m, nOut;
+  unsigned char in[30000];
+  unsigned char out[33000];
+
+  for(i=0; i<sizeof(in); i++){
+    printf("Test %d: ", i+1);
+    n = rand() % (i+1);
+    if( i%100==0 ){
+      int k;
+      for(j=k=0; j<n; j++){
+        /* if( k==0 || k=='\'' ) k++; */
+        in[j] = k;
+        k = (k+1)&0xff;
+      }
+    }else{
+      for(j=0; j<n; j++) in[j] = rand() & 0xff;
+    }
+    nOut = sqlite_encode_binary(in, n, out);
+    if( nOut!=strlen(out) ){
+      printf(" ERROR return value is %d instead of %d\n", nOut, strlen(out));
+      exit(1);
+    }
+    m = (256*n + 1262)/253;
+    printf("size %d->%d (max %d)", n, strlen(out)+1, m);
+    if( strlen(out)+1>m ){
+      printf(" ERROR output too big\n");
+      exit(1);
+    }
+    for(j=0; out[j]; j++){
+      if( out[j]=='\'' ){
+        printf(" ERROR contains (')\n");
+        exit(1);
+      }
+    }
+    j = sqlite_decode_binary(out, out);
+    if( j!=n ){
+      printf(" ERROR decode size %d\n", j);
+      exit(1);
+    }
+    if( memcmp(in, out, n)!=0 ){
+      printf(" ERROR decode mismatch\n");
+      exit(1);
+    }
+    printf(" OK\n");
+  }
+}
+#endif /* ENCODER_TEST */
diff --git a/ext/sqlite/libsqlite/src/expr.c b/ext/sqlite/libsqlite/src/expr.c
new file mode 100644 (file)
index 0000000..478bfeb
--- /dev/null
@@ -0,0 +1,1595 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains routines used for analyzing expressions and
+** for generating VDBE code that evaluates expressions in SQLite.
+**
+** $Id$
+*/
+#include "sqliteInt.h"
+#include <ctype.h>
+
+/*
+** Construct a new expression node and return a pointer to it.  Memory
+** for this node is obtained from sqliteMalloc().  The calling function
+** is responsible for making sure the node eventually gets freed.
+*/
+Expr *sqliteExpr(int op, Expr *pLeft, Expr *pRight, Token *pToken){
+  Expr *pNew;
+  pNew = sqliteMalloc( sizeof(Expr) );
+  if( pNew==0 ){
+    sqliteExprDelete(pLeft);
+    sqliteExprDelete(pRight);
+    return 0;
+  }
+  pNew->op = op;
+  pNew->pLeft = pLeft;
+  pNew->pRight = pRight;
+  if( pToken ){
+    assert( pToken->dyn==0 );
+    pNew->token = *pToken;
+    pNew->span = *pToken;
+  }else{
+    pNew->token.dyn = 0;
+    pNew->token.z = 0;
+    pNew->token.n = 0;
+    if( pLeft && pRight ){
+      sqliteExprSpan(pNew, &pLeft->span, &pRight->span);
+    }else{
+      pNew->span = pNew->token;
+    }
+  }
+  return pNew;
+}
+
+/*
+** Set the Expr.span field of the given expression to span all
+** text between the two given tokens.
+*/
+void sqliteExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
+  if( pExpr && pRight && pRight->z && pLeft && pLeft->z ){
+    if( pLeft->dyn==0 && pRight->dyn==0 ){
+      pExpr->span.z = pLeft->z;
+      pExpr->span.n = pRight->n + Addr(pRight->z) - Addr(pLeft->z);
+    }else{
+      pExpr->span.z = 0;
+      pExpr->span.n = 0;
+      pExpr->span.dyn = 0;
+    }
+  }
+}
+
+/*
+** Construct a new expression node for a function with multiple
+** arguments.
+*/
+Expr *sqliteExprFunction(ExprList *pList, Token *pToken){
+  Expr *pNew;
+  pNew = sqliteMalloc( sizeof(Expr) );
+  if( pNew==0 ){
+    sqliteExprListDelete(pList);
+    return 0;
+  }
+  pNew->op = TK_FUNCTION;
+  pNew->pList = pList;
+  pNew->token.dyn = 0;
+  if( pToken ){
+    assert( pToken->dyn==0 );
+    pNew->token = *pToken;
+  }else{
+    pNew->token.z = 0;
+    pNew->token.n = 0;
+  }
+  pNew->span = pNew->token;
+  return pNew;
+}
+
+/*
+** Recursively delete an expression tree.
+*/
+void sqliteExprDelete(Expr *p){
+  if( p==0 ) return;
+  if( p->span.dyn && p->span.z ) sqliteFree((char*)p->span.z);
+  if( p->token.dyn && p->token.z ) sqliteFree((char*)p->token.z);
+  if( p->pLeft ) sqliteExprDelete(p->pLeft);
+  if( p->pRight ) sqliteExprDelete(p->pRight);
+  if( p->pList ) sqliteExprListDelete(p->pList);
+  if( p->pSelect ) sqliteSelectDelete(p->pSelect);
+  sqliteFree(p);
+}
+
+
+/*
+** The following group of routines make deep copies of expressions,
+** expression lists, ID lists, and select statements.  The copies can
+** be deleted (by being passed to their respective ...Delete() routines)
+** without effecting the originals.
+**
+** The expression list, ID, and source lists return by sqliteExprListDup(),
+** sqliteIdListDup(), and sqliteSrcListDup() can not be further expanded 
+** by subsequent calls to sqlite*ListAppend() routines.
+**
+** Any tables that the SrcList might point to are not duplicated.
+*/
+Expr *sqliteExprDup(Expr *p){
+  Expr *pNew;
+  if( p==0 ) return 0;
+  pNew = sqliteMallocRaw( sizeof(*p) );
+  if( pNew==0 ) return 0;
+  memcpy(pNew, p, sizeof(*pNew));
+  if( p->token.z!=0 ){
+    pNew->token.z = sqliteStrDup(p->token.z);
+    pNew->token.dyn = 1;
+  }else{
+    pNew->token.z = 0;
+    pNew->token.n = 0;
+    pNew->token.dyn = 0;
+  }
+  pNew->span.z = 0;
+  pNew->span.n = 0;
+  pNew->span.dyn = 0;
+  pNew->pLeft = sqliteExprDup(p->pLeft);
+  pNew->pRight = sqliteExprDup(p->pRight);
+  pNew->pList = sqliteExprListDup(p->pList);
+  pNew->pSelect = sqliteSelectDup(p->pSelect);
+  return pNew;
+}
+void sqliteTokenCopy(Token *pTo, Token *pFrom){
+  if( pTo->dyn ) sqliteFree((char*)pTo->z);
+  if( pFrom->z ){
+    pTo->n = pFrom->n;
+    pTo->z = sqliteStrNDup(pFrom->z, pFrom->n);
+    pTo->dyn = 1;
+  }else{
+    pTo->n = 0;
+    pTo->z = 0;
+    pTo->dyn = 0;
+  }
+}
+ExprList *sqliteExprListDup(ExprList *p){
+  ExprList *pNew;
+  int i;
+  if( p==0 ) return 0;
+  pNew = sqliteMalloc( sizeof(*pNew) );
+  if( pNew==0 ) return 0;
+  pNew->nExpr = p->nExpr;
+  pNew->a = sqliteMalloc( p->nExpr*sizeof(p->a[0]) );
+  if( pNew->a==0 ) return 0;
+  for(i=0; i<p->nExpr; i++){
+    Expr *pNewExpr, *pOldExpr;
+    pNew->a[i].pExpr = pNewExpr = sqliteExprDup(pOldExpr = p->a[i].pExpr);
+    if( pOldExpr->span.z!=0 && pNewExpr ){
+      /* Always make a copy of the span for top-level expressions in the
+      ** expression list.  The logic in SELECT processing that determines
+      ** the names of columns in the result set needs this information */
+      sqliteTokenCopy(&pNewExpr->span, &pOldExpr->span);
+    }
+    assert( pNewExpr==0 || pNewExpr->span.z!=0 
+            || pOldExpr->span.z==0 || sqlite_malloc_failed );
+    pNew->a[i].zName = sqliteStrDup(p->a[i].zName);
+    pNew->a[i].sortOrder = p->a[i].sortOrder;
+    pNew->a[i].isAgg = p->a[i].isAgg;
+    pNew->a[i].done = 0;
+  }
+  return pNew;
+}
+SrcList *sqliteSrcListDup(SrcList *p){
+  SrcList *pNew;
+  int i;
+  if( p==0 ) return 0;
+  pNew = sqliteMalloc( sizeof(*pNew) );
+  if( pNew==0 ) return 0;
+  pNew->nSrc = p->nSrc;
+  pNew->a = sqliteMalloc( p->nSrc*sizeof(p->a[0]) );
+  if( pNew->a==0 && p->nSrc != 0 ) return 0;
+  for(i=0; i<p->nSrc; i++){
+    pNew->a[i].zName = sqliteStrDup(p->a[i].zName);
+    pNew->a[i].zAlias = sqliteStrDup(p->a[i].zAlias);
+    pNew->a[i].jointype = p->a[i].jointype;
+    pNew->a[i].pTab = 0;
+    pNew->a[i].pSelect = sqliteSelectDup(p->a[i].pSelect);
+    pNew->a[i].pOn = sqliteExprDup(p->a[i].pOn);
+    pNew->a[i].pUsing = sqliteIdListDup(p->a[i].pUsing);
+  }
+  return pNew;
+}
+IdList *sqliteIdListDup(IdList *p){
+  IdList *pNew;
+  int i;
+  if( p==0 ) return 0;
+  pNew = sqliteMalloc( sizeof(*pNew) );
+  if( pNew==0 ) return 0;
+  pNew->nId = p->nId;
+  pNew->a = sqliteMalloc( p->nId*sizeof(p->a[0]) );
+  if( pNew->a==0 ) return 0;
+  for(i=0; i<p->nId; i++){
+    pNew->a[i].zName = sqliteStrDup(p->a[i].zName);
+    pNew->a[i].idx = p->a[i].idx;
+  }
+  return pNew;
+}
+Select *sqliteSelectDup(Select *p){
+  Select *pNew;
+  if( p==0 ) return 0;
+  pNew = sqliteMalloc( sizeof(*p) );
+  if( pNew==0 ) return 0;
+  pNew->isDistinct = p->isDistinct;
+  pNew->pEList = sqliteExprListDup(p->pEList);
+  pNew->pSrc = sqliteSrcListDup(p->pSrc);
+  pNew->pWhere = sqliteExprDup(p->pWhere);
+  pNew->pGroupBy = sqliteExprListDup(p->pGroupBy);
+  pNew->pHaving = sqliteExprDup(p->pHaving);
+  pNew->pOrderBy = sqliteExprListDup(p->pOrderBy);
+  pNew->op = p->op;
+  pNew->pPrior = sqliteSelectDup(p->pPrior);
+  pNew->nLimit = p->nLimit;
+  pNew->nOffset = p->nOffset;
+  pNew->zSelect = 0;
+  return pNew;
+}
+
+
+/*
+** Add a new element to the end of an expression list.  If pList is
+** initially NULL, then create a new expression list.
+*/
+ExprList *sqliteExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
+  int i;
+  if( pList==0 ){
+    pList = sqliteMalloc( sizeof(ExprList) );
+    if( pList==0 ){
+      sqliteExprDelete(pExpr);
+      return 0;
+    }
+  }
+  if( (pList->nExpr & 7)==0 ){
+    int n = pList->nExpr + 8;
+    struct ExprList_item *a;
+    a = sqliteRealloc(pList->a, n*sizeof(pList->a[0]));
+    if( a==0 ){
+      sqliteExprDelete(pExpr);
+      return pList;
+    }
+    pList->a = a;
+  }
+  if( pExpr || pName ){
+    i = pList->nExpr++;
+    pList->a[i].pExpr = pExpr;
+    pList->a[i].zName = 0;
+    if( pName ){
+      sqliteSetNString(&pList->a[i].zName, pName->z, pName->n, 0);
+      sqliteDequote(pList->a[i].zName);
+    }
+  }
+  return pList;
+}
+
+/*
+** Delete an entire expression list.
+*/
+void sqliteExprListDelete(ExprList *pList){
+  int i;
+  if( pList==0 ) return;
+  for(i=0; i<pList->nExpr; i++){
+    sqliteExprDelete(pList->a[i].pExpr);
+    sqliteFree(pList->a[i].zName);
+  }
+  sqliteFree(pList->a);
+  sqliteFree(pList);
+}
+
+/*
+** Walk an expression tree.  Return 1 if the expression is constant
+** and 0 if it involves variables.
+**
+** For the purposes of this function, a double-quoted string (ex: "abc")
+** is considered a variable but a single-quoted string (ex: 'abc') is
+** a constant.
+*/
+int sqliteExprIsConstant(Expr *p){
+  switch( p->op ){
+    case TK_ID:
+    case TK_COLUMN:
+    case TK_DOT:
+      return 0;
+    case TK_STRING:
+    case TK_INTEGER:
+    case TK_FLOAT:
+      return 1;
+    default: {
+      if( p->pLeft && !sqliteExprIsConstant(p->pLeft) ) return 0;
+      if( p->pRight && !sqliteExprIsConstant(p->pRight) ) return 0;
+      if( p->pList ){
+        int i;
+        for(i=0; i<p->pList->nExpr; i++){
+          if( !sqliteExprIsConstant(p->pList->a[i].pExpr) ) return 0;
+        }
+      }
+      return p->pLeft!=0 || p->pRight!=0 || (p->pList && p->pList->nExpr>0);
+    }
+  }
+  return 0;
+}
+
+/*
+** If the given expression codes a constant integer, return 1 and put
+** the value of the integer in *pValue.  If the expression is not an
+** integer, return 0 and leave *pValue unchanged.
+*/
+int sqliteExprIsInteger(Expr *p, int *pValue){
+  switch( p->op ){
+    case TK_INTEGER: {
+      *pValue = atoi(p->token.z);
+      return 1;
+    }
+    case TK_STRING: {
+      const char *z = p->token.z;
+      int n = p->token.n;
+      if( n>0 && z[0]=='-' ){ z++; n--; }
+      while( n>0 && *z && isdigit(*z) ){ z++; n--; }
+      if( n==0 ){
+        *pValue = atoi(p->token.z);
+        return 1;
+      }
+      break;
+    }
+    case TK_UPLUS: {
+      return sqliteExprIsInteger(p->pLeft, pValue);
+    }
+    case TK_UMINUS: {
+      int v;
+      if( sqliteExprIsInteger(p->pLeft, &v) ){
+        *pValue = -v;
+        return 1;
+      }
+      break;
+    }
+    default: break;
+  }
+  return 0;
+}
+
+/*
+** Return TRUE if the given string is a row-id column name.
+*/
+int sqliteIsRowid(const char *z){
+  if( sqliteStrICmp(z, "_ROWID_")==0 ) return 1;
+  if( sqliteStrICmp(z, "ROWID")==0 ) return 1;
+  if( sqliteStrICmp(z, "OID")==0 ) return 1;
+  return 0;
+}
+
+/*
+** This routine walks an expression tree and resolves references to
+** table columns.  Nodes of the form ID.ID or ID resolve into an
+** index to the table in the table list and a column offset.  The 
+** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
+** value is changed to the index of the referenced table in pTabList
+** plus the "base" value.  The base value will ultimately become the
+** VDBE cursor number for a cursor that is pointing into the referenced
+** table.  The Expr.iColumn value is changed to the index of the column 
+** of the referenced table.  The Expr.iColumn value for the special
+** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
+** alias for ROWID.
+**
+** We also check for instances of the IN operator.  IN comes in two
+** forms:
+**
+**           expr IN (exprlist)
+** and
+**           expr IN (SELECT ...)
+**
+** The first form is handled by creating a set holding the list
+** of allowed values.  The second form causes the SELECT to generate 
+** a temporary table.
+**
+** This routine also looks for scalar SELECTs that are part of an expression.
+** If it finds any, it generates code to write the value of that select
+** into a memory cell.
+**
+** Unknown columns or tables provoke an error.  The function returns
+** the number of errors seen and leaves an error message on pParse->zErrMsg.
+*/
+int sqliteExprResolveIds(
+  Parse *pParse,     /* The parser context */
+  int base,          /* VDBE cursor number for first entry in pTabList */
+  SrcList *pTabList, /* List of tables used to resolve column names */
+  ExprList *pEList,  /* List of expressions used to resolve "AS" */
+  Expr *pExpr        /* The expression to be analyzed. */
+){
+  if( pExpr==0 || pTabList==0 ) return 0;
+  assert( base+pTabList->nSrc<=pParse->nTab );
+  switch( pExpr->op ){
+    /* Double-quoted strings (ex: "abc") are used as identifiers if
+    ** possible.  Otherwise they remain as strings.  Single-quoted
+    ** strings (ex: 'abc') are always string literals.
+    */
+    case TK_STRING: {
+      if( pExpr->token.z[0]=='\'' ) break;
+      /* Fall thru into the TK_ID case if this is a double-quoted string */
+    }
+    /* A lone identifier.  Try and match it as follows:
+    **
+    **     1.  To the name of a column of one of the tables in pTabList
+    **
+    **     2.  To the right side of an AS keyword in the column list of
+    **         a SELECT statement.  (For example, match against 'x' in
+    **         "SELECT a+b AS 'x' FROM t1".)
+    **
+    **     3.  One of the special names "ROWID", "OID", or "_ROWID_".
+    */
+    case TK_ID: {
+      int cnt = 0;      /* Number of matches */
+      int i;            /* Loop counter */
+      char *z;
+      assert( pExpr->token.z );
+      z = sqliteStrNDup(pExpr->token.z, pExpr->token.n);
+      sqliteDequote(z);
+      if( z==0 ) return 1;
+      for(i=0; i<pTabList->nSrc; i++){
+        int j;
+        Table *pTab = pTabList->a[i].pTab;
+        if( pTab==0 ) continue;
+        assert( pTab->nCol>0 );
+        for(j=0; j<pTab->nCol; j++){
+          if( sqliteStrICmp(pTab->aCol[j].zName, z)==0 ){
+            cnt++;
+            pExpr->iTable = i + base;
+            if( j==pTab->iPKey ){
+              /* Substitute the record number for the INTEGER PRIMARY KEY */
+              pExpr->iColumn = -1;
+              pExpr->dataType = SQLITE_SO_NUM;
+            }else{
+              pExpr->iColumn = j;
+              pExpr->dataType = pTab->aCol[j].sortOrder & SQLITE_SO_TYPEMASK;
+            }
+            pExpr->op = TK_COLUMN;
+          }
+        }
+      }
+      if( cnt==0 && pEList!=0 ){
+        int j;
+        for(j=0; j<pEList->nExpr; j++){
+          char *zAs = pEList->a[j].zName;
+          if( zAs!=0 && sqliteStrICmp(zAs, z)==0 ){
+            cnt++;
+            assert( pExpr->pLeft==0 && pExpr->pRight==0 );
+            pExpr->op = TK_AS;
+            pExpr->iColumn = j;
+            pExpr->pLeft = sqliteExprDup(pEList->a[j].pExpr);
+          }
+        } 
+      }
+      if( cnt==0 && sqliteIsRowid(z) ){
+        pExpr->iColumn = -1;
+        pExpr->iTable = base;
+        cnt = 1 + (pTabList->nSrc>1);
+        pExpr->op = TK_COLUMN;
+        pExpr->dataType = SQLITE_SO_NUM;
+      }
+      sqliteFree(z);
+      if( cnt==0 && pExpr->token.z[0]!='"' ){
+        sqliteSetNString(&pParse->zErrMsg, "no such column: ", -1,  
+          pExpr->token.z, pExpr->token.n, 0);
+        pParse->nErr++;
+        return 1;
+      }else if( cnt>1 ){
+        sqliteSetNString(&pParse->zErrMsg, "ambiguous column name: ", -1,  
+          pExpr->token.z, pExpr->token.n, 0);
+        pParse->nErr++;
+        return 1;
+      }
+      if( pExpr->op==TK_COLUMN ){
+        sqliteAuthRead(pParse, pExpr, pTabList, base);
+      }
+      break; 
+    }
+  
+    /* A table name and column name:  ID.ID */
+    case TK_DOT: {
+      int cnt = 0;             /* Number of matches */
+      int cntTab = 0;          /* Number of matching tables */
+      int i;                   /* Loop counter */
+      Expr *pLeft, *pRight;    /* Left and right subbranches of the expr */
+      char *zLeft, *zRight;    /* Text of an identifier */
+
+      pLeft = pExpr->pLeft;
+      pRight = pExpr->pRight;
+      assert( pLeft && pLeft->op==TK_ID && pLeft->token.z );
+      assert( pRight && pRight->op==TK_ID && pRight->token.z );
+      zLeft = sqliteStrNDup(pLeft->token.z, pLeft->token.n);
+      zRight = sqliteStrNDup(pRight->token.z, pRight->token.n);
+      if( zLeft==0 || zRight==0 ){
+        sqliteFree(zLeft);
+        sqliteFree(zRight);
+        return 1;
+      }
+      sqliteDequote(zLeft);
+      sqliteDequote(zRight);
+      pExpr->iTable = -1;
+      for(i=0; i<pTabList->nSrc; i++){
+        int j;
+        char *zTab;
+        Table *pTab = pTabList->a[i].pTab;
+        if( pTab==0 ) continue;
+        assert( pTab->nCol>0 );
+        if( pTabList->a[i].zAlias ){
+          zTab = pTabList->a[i].zAlias;
+        }else{
+          zTab = pTab->zName;
+        }
+        if( zTab==0 || sqliteStrICmp(zTab, zLeft)!=0 ) continue;
+        if( 0==(cntTab++) ) pExpr->iTable = i + base;
+        for(j=0; j<pTab->nCol; j++){
+          if( sqliteStrICmp(pTab->aCol[j].zName, zRight)==0 ){
+            cnt++;
+            pExpr->iTable = i + base;
+            if( j==pTab->iPKey ){
+              /* Substitute the record number for the INTEGER PRIMARY KEY */
+              pExpr->iColumn = -1;
+            }else{
+              pExpr->iColumn = j;
+            }
+            pExpr->dataType = pTab->aCol[j].sortOrder & SQLITE_SO_TYPEMASK;
+          }
+        }
+      }
+
+      /* If we have not already resolved this *.* expression, then maybe 
+       * it is a new.* or old.* trigger argument reference */
+      if( cnt == 0 && pParse->trigStack != 0 ){
+        TriggerStack *pTriggerStack = pParse->trigStack;
+        int t = 0;
+        if( pTriggerStack->newIdx != -1 && sqliteStrICmp("new", zLeft) == 0 ){
+          pExpr->iTable = pTriggerStack->newIdx;
+          cntTab++;
+          t = 1;
+        }
+        if( pTriggerStack->oldIdx != -1 && sqliteStrICmp("old", zLeft) == 0 ){
+          pExpr->iTable = pTriggerStack->oldIdx;
+          cntTab++;
+          t = 1;
+        }
+
+        if( t ){ 
+         int j;
+          Table *pTab = pTriggerStack->pTab;
+          for(j=0; j < pTab->nCol; j++) {
+            if( sqliteStrICmp(pTab->aCol[j].zName, zRight)==0 ){
+              cnt++;
+              pExpr->iColumn = j;
+              pExpr->dataType = pTab->aCol[j].sortOrder & SQLITE_SO_TYPEMASK;
+            }
+          }
+       }
+      }
+
+      if( cnt==0 && cntTab==1 && sqliteIsRowid(zRight) ){
+        cnt = 1;
+        pExpr->iColumn = -1;
+        pExpr->dataType = SQLITE_SO_NUM;
+      }
+      sqliteFree(zLeft);
+      sqliteFree(zRight);
+      if( cnt==0 ){
+        sqliteSetNString(&pParse->zErrMsg, "no such column: ", -1,  
+          pLeft->token.z, pLeft->token.n, ".", 1, 
+          pRight->token.z, pRight->token.n, 0);
+        pParse->nErr++;
+        return 1;
+      }else if( cnt>1 ){
+        sqliteSetNString(&pParse->zErrMsg, "ambiguous column name: ", -1,  
+          pLeft->token.z, pLeft->token.n, ".", 1,
+          pRight->token.z, pRight->token.n, 0);
+        pParse->nErr++;
+        return 1;
+      }
+      sqliteExprDelete(pLeft);
+      pExpr->pLeft = 0;
+      sqliteExprDelete(pRight);
+      pExpr->pRight = 0;
+      pExpr->op = TK_COLUMN;
+      sqliteAuthRead(pParse, pExpr, pTabList, base);
+      break;
+    }
+
+    case TK_IN: {
+      Vdbe *v = sqliteGetVdbe(pParse);
+      if( v==0 ) return 1;
+      if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pExpr->pLeft) ){
+        return 1;
+      }
+      if( pExpr->pSelect ){
+        /* Case 1:     expr IN (SELECT ...)
+        **
+        ** Generate code to write the results of the select into a temporary
+        ** table.  The cursor number of the temporary table has already
+        ** been put in iTable by sqliteExprResolveInSelect().
+        */
+        pExpr->iTable = pParse->nTab++;
+        sqliteVdbeAddOp(v, OP_OpenTemp, pExpr->iTable, 1);
+        sqliteSelect(pParse, pExpr->pSelect, SRT_Set, pExpr->iTable, 0,0,0);
+      }else if( pExpr->pList ){
+        /* Case 2:     expr IN (exprlist)
+        **
+        ** Create a set to put the exprlist values in.  The Set id is stored
+        ** in iTable.
+        */
+        int i, iSet;
+        for(i=0; i<pExpr->pList->nExpr; i++){
+          Expr *pE2 = pExpr->pList->a[i].pExpr;
+          if( !sqliteExprIsConstant(pE2) ){
+            sqliteSetString(&pParse->zErrMsg,
+              "right-hand side of IN operator must be constant", 0);
+            pParse->nErr++;
+            return 1;
+          }
+          if( sqliteExprCheck(pParse, pE2, 0, 0) ){
+            return 1;
+          }
+        }
+        iSet = pExpr->iTable = pParse->nSet++;
+        for(i=0; i<pExpr->pList->nExpr; i++){
+          Expr *pE2 = pExpr->pList->a[i].pExpr;
+          switch( pE2->op ){
+            case TK_FLOAT:
+            case TK_INTEGER:
+            case TK_STRING: {
+              int addr = sqliteVdbeAddOp(v, OP_SetInsert, iSet, 0);
+              assert( pE2->token.z );
+              sqliteVdbeChangeP3(v, addr, pE2->token.z, pE2->token.n);
+              sqliteVdbeDequoteP3(v, addr);
+              break;
+            }
+            default: {
+              sqliteExprCode(pParse, pE2);
+              sqliteVdbeAddOp(v, OP_SetInsert, iSet, 0);
+              break;
+            }
+          }
+        }
+      }
+      break;
+    }
+
+    case TK_SELECT: {
+      /* This has to be a scalar SELECT.  Generate code to put the
+      ** value of this select in a memory cell and record the number
+      ** of the memory cell in iColumn.
+      */
+      pExpr->iColumn = pParse->nMem++;
+      if( sqliteSelect(pParse, pExpr->pSelect, SRT_Mem, pExpr->iColumn,0,0,0) ){
+        return 1;
+      }
+      break;
+    }
+
+    /* For all else, just recursively walk the tree */
+    default: {
+      if( pExpr->pLeft
+      && sqliteExprResolveIds(pParse, base, pTabList, pEList, pExpr->pLeft) ){
+        return 1;
+      }
+      if( pExpr->pRight 
+      && sqliteExprResolveIds(pParse, base, pTabList, pEList, pExpr->pRight) ){
+        return 1;
+      }
+      if( pExpr->pList ){
+        int i;
+        ExprList *pList = pExpr->pList;
+        for(i=0; i<pList->nExpr; i++){
+          Expr *pArg = pList->a[i].pExpr;
+          if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pArg) ){
+            return 1;
+          }
+        }
+      }
+    }
+  }
+  return 0;
+}
+
+/*
+** pExpr is a node that defines a function of some kind.  It might
+** be a syntactic function like "count(x)" or it might be a function
+** that implements an operator, like "a LIKE b".  
+**
+** This routine makes *pzName point to the name of the function and 
+** *pnName hold the number of characters in the function name.
+*/
+static void getFunctionName(Expr *pExpr, const char **pzName, int *pnName){
+  switch( pExpr->op ){
+    case TK_FUNCTION: {
+      *pzName = pExpr->token.z;
+      *pnName = pExpr->token.n;
+      break;
+    }
+    case TK_LIKE: {
+      *pzName = "like";
+      *pnName = 4;
+      break;
+    }
+    case TK_GLOB: {
+      *pzName = "glob";
+      *pnName = 4;
+      break;
+    }
+    default: {
+      *pzName = "can't happen";
+      *pnName = 12;
+      break;
+    }
+  }
+}
+
+/*
+** Error check the functions in an expression.  Make sure all
+** function names are recognized and all functions have the correct
+** number of arguments.  Leave an error message in pParse->zErrMsg
+** if anything is amiss.  Return the number of errors.
+**
+** if pIsAgg is not null and this expression is an aggregate function
+** (like count(*) or max(value)) then write a 1 into *pIsAgg.
+*/
+int sqliteExprCheck(Parse *pParse, Expr *pExpr, int allowAgg, int *pIsAgg){
+  int nErr = 0;
+  if( pExpr==0 ) return 0;
+  switch( pExpr->op ){
+    case TK_GLOB:
+    case TK_LIKE:
+    case TK_FUNCTION: {
+      int n = pExpr->pList ? pExpr->pList->nExpr : 0;  /* Number of arguments */
+      int no_such_func = 0;       /* True if no such function exists */
+      int is_type_of = 0;         /* True if is the special TypeOf() function */
+      int wrong_num_args = 0;     /* True if wrong number of arguments */
+      int is_agg = 0;             /* True if is an aggregate function */
+      int i;
+      int nId;                    /* Number of characters in function name */
+      const char *zId;            /* The function name. */
+      FuncDef *pDef;
+
+      getFunctionName(pExpr, &zId, &nId);
+      pDef = sqliteFindFunction(pParse->db, zId, nId, n, 0);
+      if( pDef==0 ){
+        pDef = sqliteFindFunction(pParse->db, zId, nId, -1, 0);
+        if( pDef==0 ){
+          if( n==1 && nId==6 && sqliteStrNICmp(zId, "typeof", 6)==0 ){
+            is_type_of = 1;
+          }else {
+            no_such_func = 1;
+          }
+        }else{
+          wrong_num_args = 1;
+        }
+      }else{
+        is_agg = pDef->xFunc==0;
+      }
+      if( is_agg && !allowAgg ){
+        sqliteSetNString(&pParse->zErrMsg, "misuse of aggregate function ", -1,
+           zId, nId, "()", 2, 0);
+        pParse->nErr++;
+        nErr++;
+        is_agg = 0;
+      }else if( no_such_func ){
+        sqliteSetNString(&pParse->zErrMsg, "no such function: ", -1, zId,nId,0);
+        pParse->nErr++;
+        nErr++;
+      }else if( wrong_num_args ){
+        sqliteSetNString(&pParse->zErrMsg, 
+           "wrong number of arguments to function ", -1, zId, nId, "()", 2, 0);
+        pParse->nErr++;
+        nErr++;
+      }
+      if( is_agg ) pExpr->op = TK_AGG_FUNCTION;
+      if( is_agg && pIsAgg ) *pIsAgg = 1;
+      for(i=0; nErr==0 && i<n; i++){
+        nErr = sqliteExprCheck(pParse, pExpr->pList->a[i].pExpr,
+                               allowAgg && !is_agg, pIsAgg);
+      }
+      if( pDef==0 ){
+        if( is_type_of ){
+          pExpr->op = TK_STRING;
+          if( sqliteExprType(pExpr->pList->a[0].pExpr)==SQLITE_SO_NUM ){
+            pExpr->token.z = "numeric";
+            pExpr->token.n = 7;
+          }else{
+            pExpr->token.z = "text";
+            pExpr->token.n = 4;
+          }
+        }
+      }else if( pDef->dataType>=0 ){
+        if( pDef->dataType<n ){
+          pExpr->dataType = 
+             sqliteExprType(pExpr->pList->a[pDef->dataType].pExpr);
+        }else{
+          pExpr->dataType = SQLITE_SO_NUM;
+        }
+      }else if( pDef->dataType==SQLITE_ARGS ){
+        pDef->dataType = SQLITE_SO_TEXT;
+        for(i=0; i<n; i++){
+          if( sqliteExprType(pExpr->pList->a[i].pExpr)==SQLITE_SO_NUM ){
+            pExpr->dataType = SQLITE_SO_NUM;
+            break;
+          }
+        }
+      }else if( pDef->dataType==SQLITE_NUMERIC ){
+        pExpr->dataType = SQLITE_SO_NUM;
+      }else{
+        pExpr->dataType = SQLITE_SO_TEXT;
+      }
+    }
+    default: {
+      if( pExpr->pLeft ){
+        nErr = sqliteExprCheck(pParse, pExpr->pLeft, allowAgg, pIsAgg);
+      }
+      if( nErr==0 && pExpr->pRight ){
+        nErr = sqliteExprCheck(pParse, pExpr->pRight, allowAgg, pIsAgg);
+      }
+      if( nErr==0 && pExpr->pList ){
+        int n = pExpr->pList->nExpr;
+        int i;
+        for(i=0; nErr==0 && i<n; i++){
+          Expr *pE2 = pExpr->pList->a[i].pExpr;
+          nErr = sqliteExprCheck(pParse, pE2, allowAgg, pIsAgg);
+        }
+      }
+      break;
+    }
+  }
+  return nErr;
+}
+
+/*
+** Return either SQLITE_SO_NUM or SQLITE_SO_TEXT to indicate whether the
+** given expression should sort as numeric values or as text.
+**
+** The sqliteExprResolveIds() and sqliteExprCheck() routines must have
+** both been called on the expression before it is passed to this routine.
+*/
+int sqliteExprType(Expr *p){
+  if( p==0 ) return SQLITE_SO_NUM;
+  while( p ) switch( p->op ){
+    case TK_PLUS:
+    case TK_MINUS:
+    case TK_STAR:
+    case TK_SLASH:
+    case TK_AND:
+    case TK_OR:
+    case TK_ISNULL:
+    case TK_NOTNULL:
+    case TK_NOT:
+    case TK_UMINUS:
+    case TK_UPLUS:
+    case TK_BITAND:
+    case TK_BITOR:
+    case TK_BITNOT:
+    case TK_LSHIFT:
+    case TK_RSHIFT:
+    case TK_REM:
+    case TK_INTEGER:
+    case TK_FLOAT:
+    case TK_IN:
+    case TK_BETWEEN:
+    case TK_GLOB:
+    case TK_LIKE:
+      return SQLITE_SO_NUM;
+
+    case TK_STRING:
+    case TK_NULL:
+    case TK_CONCAT:
+      return SQLITE_SO_TEXT;
+
+    case TK_LT:
+    case TK_LE:
+    case TK_GT:
+    case TK_GE:
+    case TK_NE:
+    case TK_EQ:
+      if( sqliteExprType(p->pLeft)==SQLITE_SO_NUM ){
+        return SQLITE_SO_NUM;
+      }
+      p = p->pRight;
+      break;
+
+    case TK_AS:
+      p = p->pLeft;
+      break;
+
+    case TK_COLUMN:
+    case TK_FUNCTION:
+    case TK_AGG_FUNCTION:
+      return p->dataType;
+
+    case TK_SELECT:
+      assert( p->pSelect );
+      assert( p->pSelect->pEList );
+      assert( p->pSelect->pEList->nExpr>0 );
+      p = p->pSelect->pEList->a[0].pExpr;
+      break;
+
+    case TK_CASE: {
+      if( p->pRight && sqliteExprType(p->pRight)==SQLITE_SO_NUM ){
+        return SQLITE_SO_NUM;
+      }
+      if( p->pList ){
+        int i;
+        ExprList *pList = p->pList;
+        for(i=1; i<pList->nExpr; i+=2){
+          if( sqliteExprType(pList->a[i].pExpr)==SQLITE_SO_NUM ){
+            return SQLITE_SO_NUM;
+          }
+        }
+      }
+      return SQLITE_SO_TEXT;
+    }
+
+    default:
+      assert( p->op==TK_ABORT );  /* Can't Happen */
+      break;
+  }
+  return SQLITE_SO_NUM;
+}
+
+/*
+** Generate code into the current Vdbe to evaluate the given
+** expression and leave the result on the top of stack.
+*/
+void sqliteExprCode(Parse *pParse, Expr *pExpr){
+  Vdbe *v = pParse->pVdbe;
+  int op;
+  if( v==0 || pExpr==0 ) return;
+  switch( pExpr->op ){
+    case TK_PLUS:     op = OP_Add;      break;
+    case TK_MINUS:    op = OP_Subtract; break;
+    case TK_STAR:     op = OP_Multiply; break;
+    case TK_SLASH:    op = OP_Divide;   break;
+    case TK_AND:      op = OP_And;      break;
+    case TK_OR:       op = OP_Or;       break;
+    case TK_LT:       op = OP_Lt;       break;
+    case TK_LE:       op = OP_Le;       break;
+    case TK_GT:       op = OP_Gt;       break;
+    case TK_GE:       op = OP_Ge;       break;
+    case TK_NE:       op = OP_Ne;       break;
+    case TK_EQ:       op = OP_Eq;       break;
+    case TK_ISNULL:   op = OP_IsNull;   break;
+    case TK_NOTNULL:  op = OP_NotNull;  break;
+    case TK_NOT:      op = OP_Not;      break;
+    case TK_UMINUS:   op = OP_Negative; break;
+    case TK_BITAND:   op = OP_BitAnd;   break;
+    case TK_BITOR:    op = OP_BitOr;    break;
+    case TK_BITNOT:   op = OP_BitNot;   break;
+    case TK_LSHIFT:   op = OP_ShiftLeft;  break;
+    case TK_RSHIFT:   op = OP_ShiftRight; break;
+    case TK_REM:      op = OP_Remainder;  break;
+    default: break;
+  }
+  switch( pExpr->op ){
+    case TK_COLUMN: {
+      if( pParse->useAgg ){
+        sqliteVdbeAddOp(v, OP_AggGet, 0, pExpr->iAgg);
+      }else if( pExpr->iColumn>=0 ){
+        sqliteVdbeAddOp(v, OP_Column, pExpr->iTable, pExpr->iColumn);
+      }else{
+        sqliteVdbeAddOp(v, OP_Recno, pExpr->iTable, 0);
+      }
+      break;
+    }
+    case TK_INTEGER: {
+      int iVal = atoi(pExpr->token.z);
+      char zBuf[30];
+      sprintf(zBuf,"%d",iVal);
+      if( strlen(zBuf)!=pExpr->token.n 
+            || strncmp(pExpr->token.z,zBuf,pExpr->token.n)!=0 ){
+        /* If the integer value cannot be represented exactly in 32 bits,
+        ** then code it as a string instead. */
+        sqliteVdbeAddOp(v, OP_String, 0, 0);
+      }else{
+        sqliteVdbeAddOp(v, OP_Integer, iVal, 0);
+      }
+      sqliteVdbeChangeP3(v, -1, pExpr->token.z, pExpr->token.n);
+      break;
+    }
+    case TK_FLOAT: {
+      sqliteVdbeAddOp(v, OP_String, 0, 0);
+      assert( pExpr->token.z );
+      sqliteVdbeChangeP3(v, -1, pExpr->token.z, pExpr->token.n);
+      break;
+    }
+    case TK_STRING: {
+      int addr = sqliteVdbeAddOp(v, OP_String, 0, 0);
+      assert( pExpr->token.z );
+      sqliteVdbeChangeP3(v, addr, pExpr->token.z, pExpr->token.n);
+      sqliteVdbeDequoteP3(v, addr);
+      break;
+    }
+    case TK_NULL: {
+      sqliteVdbeAddOp(v, OP_String, 0, 0);
+      break;
+    }
+    case TK_LT:
+    case TK_LE:
+    case TK_GT:
+    case TK_GE:
+    case TK_NE:
+    case TK_EQ: {
+      if( pParse->db->file_format>=4 && sqliteExprType(pExpr)==SQLITE_SO_TEXT ){
+        op += 6;  /* Convert numeric opcodes to text opcodes */
+      }
+      /* Fall through into the next case */
+    }
+    case TK_AND:
+    case TK_OR:
+    case TK_PLUS:
+    case TK_STAR:
+    case TK_MINUS:
+    case TK_REM:
+    case TK_BITAND:
+    case TK_BITOR:
+    case TK_SLASH: {
+      sqliteExprCode(pParse, pExpr->pLeft);
+      sqliteExprCode(pParse, pExpr->pRight);
+      sqliteVdbeAddOp(v, op, 0, 0);
+      break;
+    }
+    case TK_LSHIFT:
+    case TK_RSHIFT: {
+      sqliteExprCode(pParse, pExpr->pRight);
+      sqliteExprCode(pParse, pExpr->pLeft);
+      sqliteVdbeAddOp(v, op, 0, 0);
+      break;
+    }
+    case TK_CONCAT: {
+      sqliteExprCode(pParse, pExpr->pLeft);
+      sqliteExprCode(pParse, pExpr->pRight);
+      sqliteVdbeAddOp(v, OP_Concat, 2, 0);
+      break;
+    }
+    case TK_UPLUS: {
+      Expr *pLeft = pExpr->pLeft;
+      if( pLeft && pLeft->op==TK_INTEGER ){
+        sqliteVdbeAddOp(v, OP_Integer, atoi(pLeft->token.z), 0);
+        sqliteVdbeChangeP3(v, -1, pLeft->token.z, pLeft->token.n);
+      }else if( pLeft && pLeft->op==TK_FLOAT ){
+        sqliteVdbeAddOp(v, OP_String, 0, 0);
+        sqliteVdbeChangeP3(v, -1, pLeft->token.z, pLeft->token.n);
+      }else{
+        sqliteExprCode(pParse, pExpr->pLeft);
+      }
+      break;
+    }
+    case TK_UMINUS: {
+      assert( pExpr->pLeft );
+      if( pExpr->pLeft->op==TK_FLOAT || pExpr->pLeft->op==TK_INTEGER ){
+        Token *p = &pExpr->pLeft->token;
+        char *z = sqliteMalloc( p->n + 2 );
+        sprintf(z, "-%.*s", p->n, p->z);
+        if( pExpr->pLeft->op==TK_INTEGER ){
+          sqliteVdbeAddOp(v, OP_Integer, atoi(z), 0);
+        }else{
+          sqliteVdbeAddOp(v, OP_String, 0, 0);
+        }
+        sqliteVdbeChangeP3(v, -1, z, p->n+1);
+        sqliteFree(z);
+        break;
+      }
+      /* Fall through into TK_NOT */
+    }
+    case TK_BITNOT:
+    case TK_NOT: {
+      sqliteExprCode(pParse, pExpr->pLeft);
+      sqliteVdbeAddOp(v, op, 0, 0);
+      break;
+    }
+    case TK_ISNULL:
+    case TK_NOTNULL: {
+      int dest;
+      sqliteVdbeAddOp(v, OP_Integer, 1, 0);
+      sqliteExprCode(pParse, pExpr->pLeft);
+      dest = sqliteVdbeCurrentAddr(v) + 2;
+      sqliteVdbeAddOp(v, op, 1, dest);
+      sqliteVdbeAddOp(v, OP_AddImm, -1, 0);
+      break;
+    }
+    case TK_AGG_FUNCTION: {
+      sqliteVdbeAddOp(v, OP_AggGet, 0, pExpr->iAgg);
+      break;
+    }
+    case TK_GLOB:
+    case TK_LIKE:
+    case TK_FUNCTION: {
+      int i;
+      ExprList *pList = pExpr->pList;
+      int nExpr = pList ? pList->nExpr : 0;
+      FuncDef *pDef;
+      int nId;
+      const char *zId;
+      getFunctionName(pExpr, &zId, &nId);
+      pDef = sqliteFindFunction(pParse->db, zId, nId, nExpr, 0);
+      assert( pDef!=0 );
+      for(i=0; i<nExpr; i++){
+        sqliteExprCode(pParse, pList->a[i].pExpr);
+      }
+      sqliteVdbeAddOp(v, OP_Function, nExpr, 0);
+      sqliteVdbeChangeP3(v, -1, (char*)pDef, P3_POINTER);
+      break;
+    }
+    case TK_SELECT: {
+      sqliteVdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
+      break;
+    }
+    case TK_IN: {
+      int addr;
+      sqliteVdbeAddOp(v, OP_Integer, 1, 0);
+      sqliteExprCode(pParse, pExpr->pLeft);
+      addr = sqliteVdbeCurrentAddr(v);
+      sqliteVdbeAddOp(v, OP_NotNull, -1, addr+4);
+      sqliteVdbeAddOp(v, OP_Pop, 1, 0);
+      sqliteVdbeAddOp(v, OP_String, 0, 0);
+      sqliteVdbeAddOp(v, OP_Goto, 0, addr+6);
+      if( pExpr->pSelect ){
+        sqliteVdbeAddOp(v, OP_Found, pExpr->iTable, addr+6);
+      }else{
+        sqliteVdbeAddOp(v, OP_SetFound, pExpr->iTable, addr+6);
+      }
+      sqliteVdbeAddOp(v, OP_AddImm, -1, 0);
+      break;
+    }
+    case TK_BETWEEN: {
+      sqliteExprCode(pParse, pExpr->pLeft);
+      sqliteVdbeAddOp(v, OP_Dup, 0, 0);
+      sqliteExprCode(pParse, pExpr->pList->a[0].pExpr);
+      sqliteVdbeAddOp(v, OP_Ge, 0, 0);
+      sqliteVdbeAddOp(v, OP_Pull, 1, 0);
+      sqliteExprCode(pParse, pExpr->pList->a[1].pExpr);
+      sqliteVdbeAddOp(v, OP_Le, 0, 0);
+      sqliteVdbeAddOp(v, OP_And, 0, 0);
+      break;
+    }
+    case TK_AS: {
+      sqliteExprCode(pParse, pExpr->pLeft);
+      break;
+    }
+    case TK_CASE: {
+      int expr_end_label;
+      int jumpInst;
+      int addr;
+      int nExpr;
+      int i;
+
+      assert(pExpr->pList);
+      assert((pExpr->pList->nExpr % 2) == 0);
+      assert(pExpr->pList->nExpr > 0);
+      nExpr = pExpr->pList->nExpr;
+      expr_end_label = sqliteVdbeMakeLabel(v);
+      if( pExpr->pLeft ){
+        sqliteExprCode(pParse, pExpr->pLeft);
+      }
+      for(i=0; i<nExpr; i=i+2){
+        sqliteExprCode(pParse, pExpr->pList->a[i].pExpr);
+        if( pExpr->pLeft ){
+          sqliteVdbeAddOp(v, OP_Dup, 1, 1);
+          jumpInst = sqliteVdbeAddOp(v, OP_Ne, 1, 0);
+          sqliteVdbeAddOp(v, OP_Pop, 1, 0);
+        }else{
+          jumpInst = sqliteVdbeAddOp(v, OP_IfNot, 1, 0);
+        }
+        sqliteExprCode(pParse, pExpr->pList->a[i+1].pExpr);
+        sqliteVdbeAddOp(v, OP_Goto, 0, expr_end_label);
+        addr = sqliteVdbeCurrentAddr(v);
+        sqliteVdbeChangeP2(v, jumpInst, addr);
+      }
+      if( pExpr->pLeft ){
+        sqliteVdbeAddOp(v, OP_Pop, 1, 0);
+      }
+      if( pExpr->pRight ){
+        sqliteExprCode(pParse, pExpr->pRight);
+      }else{
+        sqliteVdbeAddOp(v, OP_String, 0, 0);
+      }
+      sqliteVdbeResolveLabel(v, expr_end_label);
+      break;
+    }
+    case TK_RAISE: {
+      if( !pParse->trigStack ){
+        sqliteSetNString(&pParse->zErrMsg, 
+               "RAISE() may only be used within a trigger-program", -1, 0);
+        pParse->nErr++;
+       return;
+      }
+      if( pExpr->iColumn == OE_Rollback ||
+         pExpr->iColumn == OE_Abort ||
+         pExpr->iColumn == OE_Fail ){
+         char * msg = sqliteStrNDup(pExpr->token.z, pExpr->token.n);
+         sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn);
+         sqliteDequote(msg);
+         sqliteVdbeChangeP3(v, -1, msg, 0);
+         sqliteFree(msg);
+      } else {
+         assert( pExpr->iColumn == OE_Ignore );
+         sqliteVdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
+         sqliteVdbeChangeP3(v, -1, "(IGNORE jump)", 0);
+      }
+    }
+    break;
+  }
+}
+
+/*
+** Generate code for a boolean expression such that a jump is made
+** to the label "dest" if the expression is true but execution
+** continues straight thru if the expression is false.
+**
+** If the expression evaluates to NULL (neither true nor false), then
+** take the jump if the jumpIfNull flag is true.
+*/
+void sqliteExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
+  Vdbe *v = pParse->pVdbe;
+  int op = 0;
+  if( v==0 || pExpr==0 ) return;
+  switch( pExpr->op ){
+    case TK_LT:       op = OP_Lt;       break;
+    case TK_LE:       op = OP_Le;       break;
+    case TK_GT:       op = OP_Gt;       break;
+    case TK_GE:       op = OP_Ge;       break;
+    case TK_NE:       op = OP_Ne;       break;
+    case TK_EQ:       op = OP_Eq;       break;
+    case TK_ISNULL:   op = OP_IsNull;   break;
+    case TK_NOTNULL:  op = OP_NotNull;  break;
+    default:  break;
+  }
+  switch( pExpr->op ){
+    case TK_AND: {
+      int d2 = sqliteVdbeMakeLabel(v);
+      sqliteExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
+      sqliteExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
+      sqliteVdbeResolveLabel(v, d2);
+      break;
+    }
+    case TK_OR: {
+      sqliteExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
+      sqliteExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
+      break;
+    }
+    case TK_NOT: {
+      sqliteExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
+      break;
+    }
+    case TK_LT:
+    case TK_LE:
+    case TK_GT:
+    case TK_GE:
+    case TK_NE:
+    case TK_EQ: {
+      sqliteExprCode(pParse, pExpr->pLeft);
+      sqliteExprCode(pParse, pExpr->pRight);
+      if( pParse->db->file_format>=4 && sqliteExprType(pExpr)==SQLITE_SO_TEXT ){
+        op += 6;  /* Convert numeric opcodes to text opcodes */
+      }
+      sqliteVdbeAddOp(v, op, jumpIfNull, dest);
+      break;
+    }
+    case TK_ISNULL:
+    case TK_NOTNULL: {
+      sqliteExprCode(pParse, pExpr->pLeft);
+      sqliteVdbeAddOp(v, op, 1, dest);
+      break;
+    }
+    case TK_IN: {
+      int addr;
+      sqliteExprCode(pParse, pExpr->pLeft);
+      addr = sqliteVdbeCurrentAddr(v);
+      sqliteVdbeAddOp(v, OP_NotNull, -1, addr+3);
+      sqliteVdbeAddOp(v, OP_Pop, 1, 0);
+      sqliteVdbeAddOp(v, OP_Goto, 0, jumpIfNull ? dest : addr+4);
+      if( pExpr->pSelect ){
+        sqliteVdbeAddOp(v, OP_Found, pExpr->iTable, dest);
+      }else{
+        sqliteVdbeAddOp(v, OP_SetFound, pExpr->iTable, dest);
+      }
+      break;
+    }
+    case TK_BETWEEN: {
+      int addr;
+      sqliteExprCode(pParse, pExpr->pLeft);
+      sqliteVdbeAddOp(v, OP_Dup, 0, 0);
+      sqliteExprCode(pParse, pExpr->pList->a[0].pExpr);
+      addr = sqliteVdbeAddOp(v, OP_Lt, !jumpIfNull, 0);
+      sqliteExprCode(pParse, pExpr->pList->a[1].pExpr);
+      sqliteVdbeAddOp(v, OP_Le, jumpIfNull, dest);
+      sqliteVdbeAddOp(v, OP_Integer, 0, 0);
+      sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
+      sqliteVdbeAddOp(v, OP_Pop, 1, 0);
+      break;
+    }
+    default: {
+      sqliteExprCode(pParse, pExpr);
+      sqliteVdbeAddOp(v, OP_If, jumpIfNull, dest);
+      break;
+    }
+  }
+}
+
+/*
+** Generate code for a boolean expression such that a jump is made
+** to the label "dest" if the expression is false but execution
+** continues straight thru if the expression is true.
+**
+** If the expression evaluates to NULL (neither true nor false) then
+** jump if jumpIfNull is true or fall through if jumpIfNull is false.
+*/
+void sqliteExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
+  Vdbe *v = pParse->pVdbe;
+  int op = 0;
+  if( v==0 || pExpr==0 ) return;
+  switch( pExpr->op ){
+    case TK_LT:       op = OP_Ge;       break;
+    case TK_LE:       op = OP_Gt;       break;
+    case TK_GT:       op = OP_Le;       break;
+    case TK_GE:       op = OP_Lt;       break;
+    case TK_NE:       op = OP_Eq;       break;
+    case TK_EQ:       op = OP_Ne;       break;
+    case TK_ISNULL:   op = OP_NotNull;  break;
+    case TK_NOTNULL:  op = OP_IsNull;   break;
+    default:  break;
+  }
+  switch( pExpr->op ){
+    case TK_AND: {
+      sqliteExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
+      sqliteExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
+      break;
+    }
+    case TK_OR: {
+      int d2 = sqliteVdbeMakeLabel(v);
+      sqliteExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
+      sqliteExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
+      sqliteVdbeResolveLabel(v, d2);
+      break;
+    }
+    case TK_NOT: {
+      sqliteExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
+      break;
+    }
+    case TK_LT:
+    case TK_LE:
+    case TK_GT:
+    case TK_GE:
+    case TK_NE:
+    case TK_EQ: {
+      if( pParse->db->file_format>=4 && sqliteExprType(pExpr)==SQLITE_SO_TEXT ){
+        /* Convert numeric comparison opcodes into text comparison opcodes.
+        ** This step depends on the fact that the text comparision opcodes are
+        ** always 6 greater than their corresponding numeric comparison
+        ** opcodes.
+        */
+        assert( OP_Eq+6 == OP_StrEq );
+        op += 6;
+      }
+      sqliteExprCode(pParse, pExpr->pLeft);
+      sqliteExprCode(pParse, pExpr->pRight);
+      sqliteVdbeAddOp(v, op, jumpIfNull, dest);
+      break;
+    }
+    case TK_ISNULL:
+    case TK_NOTNULL: {
+      sqliteExprCode(pParse, pExpr->pLeft);
+      sqliteVdbeAddOp(v, op, 1, dest);
+      break;
+    }
+    case TK_IN: {
+      int addr;
+      sqliteExprCode(pParse, pExpr->pLeft);
+      addr = sqliteVdbeCurrentAddr(v);
+      sqliteVdbeAddOp(v, OP_NotNull, -1, addr+3);
+      sqliteVdbeAddOp(v, OP_Pop, 1, 0);
+      sqliteVdbeAddOp(v, OP_Goto, 0, jumpIfNull ? dest : addr+4);
+      if( pExpr->pSelect ){
+        sqliteVdbeAddOp(v, OP_NotFound, pExpr->iTable, dest);
+      }else{
+        sqliteVdbeAddOp(v, OP_SetNotFound, pExpr->iTable, dest);
+      }
+      break;
+    }
+    case TK_BETWEEN: {
+      int addr;
+      sqliteExprCode(pParse, pExpr->pLeft);
+      sqliteVdbeAddOp(v, OP_Dup, 0, 0);
+      sqliteExprCode(pParse, pExpr->pList->a[0].pExpr);
+      addr = sqliteVdbeCurrentAddr(v);
+      sqliteVdbeAddOp(v, OP_Ge, !jumpIfNull, addr+3);
+      sqliteVdbeAddOp(v, OP_Pop, 1, 0);
+      sqliteVdbeAddOp(v, OP_Goto, 0, dest);
+      sqliteExprCode(pParse, pExpr->pList->a[1].pExpr);
+      sqliteVdbeAddOp(v, OP_Gt, jumpIfNull, dest);
+      break;
+    }
+    default: {
+      sqliteExprCode(pParse, pExpr);
+      sqliteVdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
+      break;
+    }
+  }
+}
+
+/*
+** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
+** if they are identical and return FALSE if they differ in any way.
+*/
+int sqliteExprCompare(Expr *pA, Expr *pB){
+  int i;
+  if( pA==0 ){
+    return pB==0;
+  }else if( pB==0 ){
+    return 0;
+  }
+  if( pA->op!=pB->op ) return 0;
+  if( !sqliteExprCompare(pA->pLeft, pB->pLeft) ) return 0;
+  if( !sqliteExprCompare(pA->pRight, pB->pRight) ) return 0;
+  if( pA->pList ){
+    if( pB->pList==0 ) return 0;
+    if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
+    for(i=0; i<pA->pList->nExpr; i++){
+      if( !sqliteExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
+        return 0;
+      }
+    }
+  }else if( pB->pList ){
+    return 0;
+  }
+  if( pA->pSelect || pB->pSelect ) return 0;
+  if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
+  if( pA->token.z ){
+    if( pB->token.z==0 ) return 0;
+    if( pB->token.n!=pA->token.n ) return 0;
+    if( sqliteStrNICmp(pA->token.z, pB->token.z, pB->token.n)!=0 ) return 0;
+  }
+  return 1;
+}
+
+/*
+** Add a new element to the pParse->aAgg[] array and return its index.
+*/
+static int appendAggInfo(Parse *pParse){
+  if( (pParse->nAgg & 0x7)==0 ){
+    int amt = pParse->nAgg + 8;
+    AggExpr *aAgg = sqliteRealloc(pParse->aAgg, amt*sizeof(pParse->aAgg[0]));
+    if( aAgg==0 ){
+      return -1;
+    }
+    pParse->aAgg = aAgg;
+  }
+  memset(&pParse->aAgg[pParse->nAgg], 0, sizeof(pParse->aAgg[0]));
+  return pParse->nAgg++;
+}
+
+/*
+** Analyze the given expression looking for aggregate functions and
+** for variables that need to be added to the pParse->aAgg[] array.
+** Make additional entries to the pParse->aAgg[] array as necessary.
+**
+** This routine should only be called after the expression has been
+** analyzed by sqliteExprResolveIds() and sqliteExprCheck().
+**
+** If errors are seen, leave an error message in zErrMsg and return
+** the number of errors.
+*/
+int sqliteExprAnalyzeAggregates(Parse *pParse, Expr *pExpr){
+  int i;
+  AggExpr *aAgg;
+  int nErr = 0;
+
+  if( pExpr==0 ) return 0;
+  switch( pExpr->op ){
+    case TK_COLUMN: {
+      aAgg = pParse->aAgg;
+      for(i=0; i<pParse->nAgg; i++){
+        if( aAgg[i].isAgg ) continue;
+        if( aAgg[i].pExpr->iTable==pExpr->iTable
+         && aAgg[i].pExpr->iColumn==pExpr->iColumn ){
+          break;
+        }
+      }
+      if( i>=pParse->nAgg ){
+        i = appendAggInfo(pParse);
+        if( i<0 ) return 1;
+        pParse->aAgg[i].isAgg = 0;
+        pParse->aAgg[i].pExpr = pExpr;
+      }
+      pExpr->iAgg = i;
+      break;
+    }
+    case TK_AGG_FUNCTION: {
+      aAgg = pParse->aAgg;
+      for(i=0; i<pParse->nAgg; i++){
+        if( !aAgg[i].isAgg ) continue;
+        if( sqliteExprCompare(aAgg[i].pExpr, pExpr) ){
+          break;
+        }
+      }
+      if( i>=pParse->nAgg ){
+        i = appendAggInfo(pParse);
+        if( i<0 ) return 1;
+        pParse->aAgg[i].isAgg = 1;
+        pParse->aAgg[i].pExpr = pExpr;
+        pParse->aAgg[i].pFunc = sqliteFindFunction(pParse->db,
+             pExpr->token.z, pExpr->token.n,
+             pExpr->pList ? pExpr->pList->nExpr : 0, 0);
+      }
+      pExpr->iAgg = i;
+      break;
+    }
+    default: {
+      if( pExpr->pLeft ){
+        nErr = sqliteExprAnalyzeAggregates(pParse, pExpr->pLeft);
+      }
+      if( nErr==0 && pExpr->pRight ){
+        nErr = sqliteExprAnalyzeAggregates(pParse, pExpr->pRight);
+      }
+      if( nErr==0 && pExpr->pList ){
+        int n = pExpr->pList->nExpr;
+        int i;
+        for(i=0; nErr==0 && i<n; i++){
+          nErr = sqliteExprAnalyzeAggregates(pParse, pExpr->pList->a[i].pExpr);
+        }
+      }
+      break;
+    }
+  }
+  return nErr;
+}
+
+/*
+** Locate a user function given a name and a number of arguments.
+** Return a pointer to the FuncDef structure that defines that
+** function, or return NULL if the function does not exist.
+**
+** If the createFlag argument is true, then a new (blank) FuncDef
+** structure is created and liked into the "db" structure if a
+** no matching function previously existed.  When createFlag is true
+** and the nArg parameter is -1, then only a function that accepts
+** any number of arguments will be returned.
+**
+** If createFlag is false and nArg is -1, then the first valid
+** function found is returned.  A function is valid if either xFunc
+** or xStep is non-zero.
+*/
+FuncDef *sqliteFindFunction(
+  sqlite *db,        /* An open database */
+  const char *zName, /* Name of the function.  Not null-terminated */
+  int nName,         /* Number of characters in the name */
+  int nArg,          /* Number of arguments.  -1 means any number */
+  int createFlag     /* Create new entry if true and does not otherwise exist */
+){
+  FuncDef *pFirst, *p, *pMaybe;
+  pFirst = p = (FuncDef*)sqliteHashFind(&db->aFunc, zName, nName);
+  if( p && !createFlag && nArg<0 ){
+    while( p && p->xFunc==0 && p->xStep==0 ){ p = p->pNext; }
+    return p;
+  }
+  pMaybe = 0;
+  while( p && p->nArg!=nArg ){
+    if( p->nArg<0 && !createFlag && (p->xFunc || p->xStep) ) pMaybe = p;
+    p = p->pNext;
+  }
+  if( p && !createFlag && p->xFunc==0 && p->xStep==0 ){
+    return 0;
+  }
+  if( p==0 && pMaybe ){
+    assert( createFlag==0 );
+    return pMaybe;
+  }
+  if( p==0 && createFlag && (p = sqliteMalloc(sizeof(*p)))!=0 ){
+    p->nArg = nArg;
+    p->pNext = pFirst;
+    p->dataType = pFirst ? pFirst->dataType : SQLITE_NUMERIC;
+    sqliteHashInsert(&db->aFunc, zName, nName, (void*)p);
+  }
+  return p;
+}
diff --git a/ext/sqlite/libsqlite/src/func.c b/ext/sqlite/libsqlite/src/func.c
new file mode 100644 (file)
index 0000000..a865de0
--- /dev/null
@@ -0,0 +1,531 @@
+/*
+** 2002 February 23
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains the C functions that implement various SQL
+** functions of SQLite.  
+**
+** There is only one exported symbol in this file - the function
+** sqliteRegisterBuildinFunctions() found at the bottom of the file.
+** All other code has file scope.
+**
+** $Id$
+*/
+#include <ctype.h>
+#include <math.h>
+#include <stdlib.h>
+#include <assert.h>
+#include "sqliteInt.h"
+
+/*
+** Implementation of the non-aggregate min() and max() functions
+*/
+static void minFunc(sqlite_func *context, int argc, const char **argv){
+  const char *zBest; 
+  int i;
+
+  if( argc==0 ) return;
+  zBest = argv[0];
+  if( zBest==0 ) return;
+  for(i=1; i<argc; i++){
+    if( argv[i]==0 ) return;
+    if( sqliteCompare(argv[i], zBest)<0 ){
+      zBest = argv[i];
+    }
+  }
+  sqlite_set_result_string(context, zBest, -1);
+}
+static void maxFunc(sqlite_func *context, int argc, const char **argv){
+  const char *zBest; 
+  int i;
+
+  if( argc==0 ) return;
+  zBest = argv[0];
+  if( zBest==0 ) return;
+  for(i=1; i<argc; i++){
+    if( argv[i]==0 ) return;
+    if( sqliteCompare(argv[i], zBest)>0 ){
+      zBest = argv[i];
+    }
+  }
+  sqlite_set_result_string(context, zBest, -1);
+}
+
+/*
+** Implementation of the length() function
+*/
+static void lengthFunc(sqlite_func *context, int argc, const char **argv){
+  const char *z;
+  int len;
+
+  assert( argc==1 );
+  z = argv[0];
+  if( z==0 ) return;
+#ifdef SQLITE_UTF8
+  for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
+#else
+  len = strlen(z);
+#endif
+  sqlite_set_result_int(context, len);
+}
+
+/*
+** Implementation of the abs() function
+*/
+static void absFunc(sqlite_func *context, int argc, const char **argv){
+  const char *z;
+  assert( argc==1 );
+  z = argv[0];
+  if( z==0 ) return;
+  if( z[0]=='-' && isdigit(z[1]) ) z++;
+  sqlite_set_result_string(context, z, -1);
+}
+
+/*
+** Implementation of the substr() function
+*/
+static void substrFunc(sqlite_func *context, int argc, const char **argv){
+  const char *z;
+#ifdef SQLITE_UTF8
+  const char *z2;
+  int i;
+#endif
+  int p1, p2, len;
+  assert( argc==3 );
+  z = argv[0];
+  if( z==0 ) return;
+  p1 = atoi(argv[1]?argv[1]:0);
+  p2 = atoi(argv[2]?argv[2]:0);
+#ifdef SQLITE_UTF8
+  for(len=0, z2=z; *z2; z2++){ if( (0xc0&*z2)!=0x80 ) len++; }
+#else
+  len = strlen(z);
+#endif
+  if( p1<0 ){
+    p1 += len;
+    if( p1<0 ){
+      p2 += p1;
+      p1 = 0;
+    }
+  }else if( p1>0 ){
+    p1--;
+  }
+  if( p1+p2>len ){
+    p2 = len-p1;
+  }
+#ifdef SQLITE_UTF8
+  for(i=0; i<p1; i++){
+    assert( z[i] );
+    if( (z[i]&0xc0)==0x80 ) p1++;
+  }
+  while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p1++; }
+  for(; i<p1+p2; i++){
+    assert( z[i] );
+    if( (z[i]&0xc0)==0x80 ) p2++;
+  }
+  while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p2++; }
+#endif
+  if( p2<0 ) p2 = 0;
+  sqlite_set_result_string(context, &z[p1], p2);
+}
+
+/*
+** Implementation of the round() function
+*/
+static void roundFunc(sqlite_func *context, int argc, const char **argv){
+  int n;
+  double r;
+  char zBuf[100];
+  assert( argc==1 || argc==2 );
+  if( argv[0]==0 || (argc==2 && argv[1]==0) ) return;
+  n = argc==2 ? atoi(argv[1]) : 0;
+  if( n>30 ) n = 30;
+  if( n<0 ) n = 0;
+  r = atof(argv[0]);
+  sprintf(zBuf,"%.*f",n,r);
+  sqlite_set_result_string(context, zBuf, -1);
+}
+
+/*
+** Implementation of the upper() and lower() SQL functions.
+*/
+static void upperFunc(sqlite_func *context, int argc, const char **argv){
+  char *z;
+  int i;
+  if( argc<1 || argv[0]==0 ) return;
+  z = sqlite_set_result_string(context, argv[0], -1);
+  if( z==0 ) return;
+  for(i=0; z[i]; i++){
+    if( islower(z[i]) ) z[i] = toupper(z[i]);
+  }
+}
+static void lowerFunc(sqlite_func *context, int argc, const char **argv){
+  char *z;
+  int i;
+  if( argc<1 || argv[0]==0 ) return;
+  z = sqlite_set_result_string(context, argv[0], -1);
+  if( z==0 ) return;
+  for(i=0; z[i]; i++){
+    if( isupper(z[i]) ) z[i] = tolower(z[i]);
+  }
+}
+
+/*
+** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
+** All three do the same thing.  They return the first argument
+** non-NULL argument.
+*/
+static void ifnullFunc(sqlite_func *context, int argc, const char **argv){
+  int i;
+  for(i=0; i<argc; i++){
+    if( argv[i] ){
+      sqlite_set_result_string(context, argv[i], -1);
+      break;
+    }
+  }
+}
+
+/*
+** Implementation of random().  Return a random integer.  
+*/
+static void randomFunc(sqlite_func *context, int argc, const char **argv){
+  sqlite_set_result_int(context, sqliteRandomInteger());
+}
+
+/*
+** Implementation of the last_insert_rowid() SQL function.  The return
+** value is the same as the sqlite_last_insert_rowid() API function.
+*/
+static void last_insert_rowid(sqlite_func *context, int arg, const char **argv){
+  sqlite *db = sqlite_user_data(context);
+  sqlite_set_result_int(context, sqlite_last_insert_rowid(db));
+}
+
+/*
+** Implementation of the like() SQL function.  This function implements
+** the build-in LIKE operator.  The first argument to the function is the
+** string and the second argument is the pattern.  So, the SQL statements:
+**
+**       A LIKE B
+**
+** is implemented as like(A,B).
+*/
+static void likeFunc(sqlite_func *context, int arg, const char **argv){
+  if( argv[0]==0 || argv[1]==0 ) return;
+  sqlite_set_result_int(context, sqliteLikeCompare(argv[0], argv[1]));
+}
+
+/*
+** Implementation of the glob() SQL function.  This function implements
+** the build-in GLOB operator.  The first argument to the function is the
+** string and the second argument is the pattern.  So, the SQL statements:
+**
+**       A GLOB B
+**
+** is implemented as glob(A,B).
+*/
+static void globFunc(sqlite_func *context, int arg, const char **argv){
+  if( argv[0]==0 || argv[1]==0 ) return;
+  sqlite_set_result_int(context, sqliteGlobCompare(argv[0], argv[1]));
+}
+
+/*
+** Implementation of the NULLIF(x,y) function.  The result is the first
+** argument if the arguments are different.  The result is NULL if the
+** arguments are equal to each other.
+*/
+static void nullifFunc(sqlite_func *context, int argc, const char **argv){
+  if( argv[0]!=0 && sqliteCompare(argv[0],argv[1])!=0 ){
+    sqlite_set_result_string(context, argv[0], -1);
+  }
+}
+
+/*
+** Implementation of the VERSION(*) function.  The result is the version
+** of the SQLite library that is running.
+*/
+static void versionFunc(sqlite_func *context, int argc, const char **argv){
+  sqlite_set_result_string(context, sqlite_version, -1);
+}
+
+#ifdef SQLITE_TEST
+/*
+** This function generates a string of random characters.  Used for
+** generating test data.
+*/
+static void randStr(sqlite_func *context, int argc, const char **argv){
+  static const char zSrc[] = 
+     "abcdefghijklmnopqrstuvwxyz"
+     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+     "0123456789"
+     ".-!,:*^+=_|?/<> ";
+  int iMin, iMax, n, r, i;
+  char zBuf[1000];
+  if( argc>=1 ){
+    iMin = atoi(argv[0]);
+    if( iMin<0 ) iMin = 0;
+    if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
+  }else{
+    iMin = 1;
+  }
+  if( argc>=2 ){
+    iMax = atoi(argv[1]);
+    if( iMax<iMin ) iMax = iMin;
+    if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf);
+  }else{
+    iMax = 50;
+  }
+  n = iMin;
+  if( iMax>iMin ){
+    r = sqliteRandomInteger();
+    if( r<0 ) r = -r;
+    n += r%(iMax + 1 - iMin);
+  }
+  r = 0;
+  for(i=0; i<n; i++){
+    r = (r + sqliteRandomByte())% (sizeof(zSrc)-1);
+    zBuf[i] = zSrc[r];
+  }
+  zBuf[n] = 0;
+  sqlite_set_result_string(context, zBuf, n);
+}
+#endif
+
+/*
+** An instance of the following structure holds the context of a
+** sum() or avg() aggregate computation.
+*/
+typedef struct SumCtx SumCtx;
+struct SumCtx {
+  double sum;     /* Sum of terms */
+  int cnt;        /* Number of elements summed */
+};
+
+/*
+** Routines used to compute the sum or average.
+*/
+static void sumStep(sqlite_func *context, int argc, const char **argv){
+  SumCtx *p;
+  if( argc<1 ) return;
+  p = sqlite_aggregate_context(context, sizeof(*p));
+  if( p && argv[0] ){
+    p->sum += atof(argv[0]);
+    p->cnt++;
+  }
+}
+static void sumFinalize(sqlite_func *context){
+  SumCtx *p;
+  p = sqlite_aggregate_context(context, sizeof(*p));
+  sqlite_set_result_double(context, p ? p->sum : 0.0);
+}
+static void avgFinalize(sqlite_func *context){
+  SumCtx *p;
+  p = sqlite_aggregate_context(context, sizeof(*p));
+  if( p && p->cnt>0 ){
+    sqlite_set_result_double(context, p->sum/(double)p->cnt);
+  }
+}
+
+/*
+** An instance of the following structure holds the context of a
+** variance or standard deviation computation.
+*/
+typedef struct StdDevCtx StdDevCtx;
+struct StdDevCtx {
+  double sum;     /* Sum of terms */
+  double sum2;    /* Sum of the squares of terms */
+  int cnt;        /* Number of terms counted */
+};
+
+#if 0   /* Omit because math library is required */
+/*
+** Routines used to compute the standard deviation as an aggregate.
+*/
+static void stdDevStep(sqlite_func *context, int argc, const char **argv){
+  StdDevCtx *p;
+  double x;
+  if( argc<1 ) return;
+  p = sqlite_aggregate_context(context, sizeof(*p));
+  if( p && argv[0] ){
+    x = atof(argv[0]);
+    p->sum += x;
+    p->sum2 += x*x;
+    p->cnt++;
+  }
+}
+static void stdDevFinalize(sqlite_func *context){
+  double rN = sqlite_aggregate_count(context);
+  StdDevCtx *p = sqlite_aggregate_context(context, sizeof(*p));
+  if( p && p->cnt>1 ){
+    double rCnt = cnt;
+    sqlite_set_result_double(context, 
+       sqrt((p->sum2 - p->sum*p->sum/rCnt)/(rCnt-1.0)));
+  }
+}
+#endif
+
+/*
+** The following structure keeps track of state information for the
+** count() aggregate function.
+*/
+typedef struct CountCtx CountCtx;
+struct CountCtx {
+  int n;
+};
+
+/*
+** Routines to implement the count() aggregate function.
+*/
+static void countStep(sqlite_func *context, int argc, const char **argv){
+  CountCtx *p;
+  p = sqlite_aggregate_context(context, sizeof(*p));
+  if( (argc==0 || argv[0]) && p ){
+    p->n++;
+  }
+}   
+static void countFinalize(sqlite_func *context){
+  CountCtx *p;
+  p = sqlite_aggregate_context(context, sizeof(*p));
+  sqlite_set_result_int(context, p ? p->n : 0);
+}
+
+/*
+** This function tracks state information for the min() and max()
+** aggregate functions.
+*/
+typedef struct MinMaxCtx MinMaxCtx;
+struct MinMaxCtx {
+  char *z;         /* The best so far */
+  char zBuf[28];   /* Space that can be used for storage */
+};
+
+/*
+** Routines to implement min() and max() aggregate functions.
+*/
+static void minStep(sqlite_func *context, int argc, const char **argv){
+  MinMaxCtx *p;
+  p = sqlite_aggregate_context(context, sizeof(*p));
+  if( p==0 || argc<1 || argv[0]==0 ) return;
+  if( p->z==0 || sqliteCompare(argv[0],p->z)<0 ){
+    int len;
+    if( p->z && p->z!=p->zBuf ){
+      sqliteFree(p->z);
+    }
+    len = strlen(argv[0]);
+    if( len < sizeof(p->zBuf) ){
+      p->z = p->zBuf;
+    }else{
+      p->z = sqliteMalloc( len+1 );
+      if( p->z==0 ) return;
+    }
+    strcpy(p->z, argv[0]);
+  }
+}
+static void maxStep(sqlite_func *context, int argc, const char **argv){
+  MinMaxCtx *p;
+  p = sqlite_aggregate_context(context, sizeof(*p));
+  if( p==0 || argc<1 || argv[0]==0 ) return;
+  if( p->z==0 || sqliteCompare(argv[0],p->z)>0 ){
+    int len;
+    if( p->z && p->z!=p->zBuf ){
+      sqliteFree(p->z);
+    }
+    len = strlen(argv[0]);
+    if( len < sizeof(p->zBuf) ){
+      p->z = p->zBuf;
+    }else{
+      p->z = sqliteMalloc( len+1 );
+      if( p->z==0 ) return;
+    }
+    strcpy(p->z, argv[0]);
+  }
+}
+static void minMaxFinalize(sqlite_func *context){
+  MinMaxCtx *p;
+  p = sqlite_aggregate_context(context, sizeof(*p));
+  if( p && p->z ){
+    sqlite_set_result_string(context, p->z, strlen(p->z));
+  }
+  if( p && p->z && p->z!=p->zBuf ){
+    sqliteFree(p->z);
+  }
+}
+
+/*
+** This function registered all of the above C functions as SQL
+** functions.  This should be the only routine in this file with
+** external linkage.
+*/
+void sqliteRegisterBuiltinFunctions(sqlite *db){
+  static struct {
+     char *zName;
+     int nArg;
+     int dataType;
+     void (*xFunc)(sqlite_func*,int,const char**);
+  } aFuncs[] = {
+    { "min",       -1, SQLITE_ARGS,    minFunc    },
+    { "min",        0, 0,              0          },
+    { "max",       -1, SQLITE_ARGS,    maxFunc    },
+    { "max",        0, 0,              0          },
+    { "length",     1, SQLITE_NUMERIC, lengthFunc },
+    { "substr",     3, SQLITE_TEXT,    substrFunc },
+    { "abs",        1, SQLITE_NUMERIC, absFunc    },
+    { "round",      1, SQLITE_NUMERIC, roundFunc  },
+    { "round",      2, SQLITE_NUMERIC, roundFunc  },
+    { "upper",      1, SQLITE_TEXT,    upperFunc  },
+    { "lower",      1, SQLITE_TEXT,    lowerFunc  },
+    { "coalesce",  -1, SQLITE_ARGS,    ifnullFunc },
+    { "coalesce",   0, 0,              0          },
+    { "coalesce",   1, 0,              0          },
+    { "ifnull",     2, SQLITE_ARGS,    ifnullFunc },
+    { "random",    -1, SQLITE_NUMERIC, randomFunc },
+    { "like",       2, SQLITE_NUMERIC, likeFunc   },
+    { "glob",       2, SQLITE_NUMERIC, globFunc   },
+    { "nullif",     2, SQLITE_ARGS,    nullifFunc },
+    { "sqlite_version",0,SQLITE_TEXT,  versionFunc},
+#ifdef SQLITE_TEST
+    { "randstr",    2, SQLITE_TEXT,    randStr    },
+#endif
+  };
+  static struct {
+    char *zName;
+    int nArg;
+    int dataType;
+    void (*xStep)(sqlite_func*,int,const char**);
+    void (*xFinalize)(sqlite_func*);
+  } aAggs[] = {
+    { "min",    1, 0,              minStep,      minMaxFinalize },
+    { "max",    1, 0,              maxStep,      minMaxFinalize },
+    { "sum",    1, SQLITE_NUMERIC, sumStep,      sumFinalize    },
+    { "avg",    1, SQLITE_NUMERIC, sumStep,      avgFinalize    },
+    { "count",  0, SQLITE_NUMERIC, countStep,    countFinalize  },
+    { "count",  1, SQLITE_NUMERIC, countStep,    countFinalize  },
+#if 0
+    { "stddev", 1, SQLITE_NUMERIC, stdDevStep,   stdDevFinalize },
+#endif
+  };
+  int i;
+
+  for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
+    sqlite_create_function(db, aFuncs[i].zName,
+           aFuncs[i].nArg, aFuncs[i].xFunc, 0);
+    if( aFuncs[i].xFunc ){
+      sqlite_function_type(db, aFuncs[i].zName, aFuncs[i].dataType);
+    }
+  }
+  sqlite_create_function(db, "last_insert_rowid", 0, 
+           last_insert_rowid, db);
+  sqlite_function_type(db, "last_insert_rowid", SQLITE_NUMERIC);
+  for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
+    sqlite_create_aggregate(db, aAggs[i].zName,
+           aAggs[i].nArg, aAggs[i].xStep, aAggs[i].xFinalize, 0);
+    sqlite_function_type(db, aAggs[i].zName, aAggs[i].dataType);
+  }
+}
diff --git a/ext/sqlite/libsqlite/src/hash.c b/ext/sqlite/libsqlite/src/hash.c
new file mode 100644 (file)
index 0000000..60de7aa
--- /dev/null
@@ -0,0 +1,355 @@
+/*
+** 2001 September 22
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This is the implementation of generic hash-tables
+** used in SQLite.
+**
+** $Id$
+*/
+#include "sqliteInt.h"
+#include <assert.h>
+
+/* Turn bulk memory into a hash table object by initializing the
+** fields of the Hash structure.
+**
+** "new" is a pointer to the hash table that is to be initialized.
+** keyClass is one of the constants SQLITE_HASH_INT, SQLITE_HASH_POINTER,
+** SQLITE_HASH_BINARY, or SQLITE_HASH_STRING.  The value of keyClass 
+** determines what kind of key the hash table will use.  "copyKey" is
+** true if the hash table should make its own private copy of keys and
+** false if it should just use the supplied pointer.  CopyKey only makes
+** sense for SQLITE_HASH_STRING and SQLITE_HASH_BINARY and is ignored
+** for other key classes.
+*/
+void sqliteHashInit(Hash *new, int keyClass, int copyKey){
+  assert( new!=0 );
+  assert( keyClass>=SQLITE_HASH_INT && keyClass<=SQLITE_HASH_BINARY );
+  new->keyClass = keyClass;
+  new->copyKey = copyKey &&
+                (keyClass==SQLITE_HASH_STRING || keyClass==SQLITE_HASH_BINARY);
+  new->first = 0;
+  new->count = 0;
+  new->htsize = 0;
+  new->ht = 0;
+}
+
+/* Remove all entries from a hash table.  Reclaim all memory.
+** Call this routine to delete a hash table or to reset a hash table
+** to the empty state.
+*/
+void sqliteHashClear(Hash *pH){
+  HashElem *elem;         /* For looping over all elements of the table */
+
+  assert( pH!=0 );
+  elem = pH->first;
+  pH->first = 0;
+  if( pH->ht ) sqliteFree(pH->ht);
+  pH->ht = 0;
+  pH->htsize = 0;
+  while( elem ){
+    HashElem *next_elem = elem->next;
+    if( pH->copyKey && elem->pKey ){
+      sqliteFree(elem->pKey);
+    }
+    sqliteFree(elem);
+    elem = next_elem;
+  }
+  pH->count = 0;
+}
+
+/*
+** Hash and comparison functions when the mode is SQLITE_HASH_INT
+*/
+static int intHash(const void *pKey, int nKey){
+  return nKey ^ (nKey<<8) ^ (nKey>>8);
+}
+static int intCompare(const void *pKey1, int n1, const void *pKey2, int n2){
+  return n2 - n1;
+}
+
+/*
+** Hash and comparison functions when the mode is SQLITE_HASH_POINTER
+*/
+static int ptrHash(const void *pKey, int nKey){
+  uptr x = Addr(pKey);
+  return x ^ (x<<8) ^ (x>>8);
+}
+static int ptrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
+  if( pKey1==pKey2 ) return 0;
+  if( pKey1<pKey2 ) return -1;
+  return 1;
+}
+
+/*
+** Hash and comparison functions when the mode is SQLITE_HASH_STRING
+*/
+static int strHash(const void *pKey, int nKey){
+  return sqliteHashNoCase((const char*)pKey, nKey); 
+}
+static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
+  if( n1!=n2 ) return n2-n1;
+  return sqliteStrNICmp((const char*)pKey1,(const char*)pKey2,n1);
+}
+
+/*
+** Hash and comparison functions when the mode is SQLITE_HASH_BINARY
+*/
+static int binHash(const void *pKey, int nKey){
+  int h = 0;
+  const char *z = (const char *)pKey;
+  while( nKey-- > 0 ){
+    h = (h<<3) ^ h ^ *(z++);
+  }
+  if( h<0 ) h = -h;
+  return h;
+}
+static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){
+  if( n1!=n2 ) return n2-n1;
+  return memcmp(pKey1,pKey2,n1);
+}
+
+/*
+** Return a pointer to the appropriate hash function given the key class.
+**
+** The C syntax in this function definition may be unfamilar to some 
+** programmers, so we provide the following additional explanation:
+**
+** The name of the function is "hashFunction".  The function takes a
+** single parameter "keyClass".  The return value of hashFunction()
+** is a pointer to another function.  Specifically, the return value
+** of hashFunction() is a pointer to a function that takes two parameters
+** with types "const void*" and "int" and returns an "int".
+*/
+static int (*hashFunction(int keyClass))(const void*,int){
+  switch( keyClass ){
+    case SQLITE_HASH_INT:     return &intHash;
+    case SQLITE_HASH_POINTER: return &ptrHash;
+    case SQLITE_HASH_STRING:  return &strHash;
+    case SQLITE_HASH_BINARY:  return &binHash;;
+    default: break;
+  }
+  return 0;
+}
+
+/*
+** Return a pointer to the appropriate hash function given the key class.
+**
+** For help in interpreted the obscure C code in the function definition,
+** see the header comment on the previous function.
+*/
+static int (*compareFunction(int keyClass))(const void*,int,const void*,int){
+  switch( keyClass ){
+    case SQLITE_HASH_INT:     return &intCompare;
+    case SQLITE_HASH_POINTER: return &ptrCompare;
+    case SQLITE_HASH_STRING:  return &strCompare;
+    case SQLITE_HASH_BINARY:  return &binCompare;
+    default: break;
+  }
+  return 0;
+}
+
+
+/* Resize the hash table so that it cantains "new_size" buckets.
+** "new_size" must be a power of 2.  The hash table might fail 
+** to resize if sqliteMalloc() fails.
+*/
+static void rehash(Hash *pH, int new_size){
+  struct _ht *new_ht;            /* The new hash table */
+  HashElem *elem, *next_elem;    /* For looping over existing elements */
+  HashElem *x;                   /* Element being copied to new hash table */
+  int (*xHash)(const void*,int); /* The hash function */
+
+  assert( (new_size & (new_size-1))==0 );
+  new_ht = (struct _ht *)sqliteMalloc( new_size*sizeof(struct _ht) );
+  if( new_ht==0 ) return;
+  if( pH->ht ) sqliteFree(pH->ht);
+  pH->ht = new_ht;
+  pH->htsize = new_size;
+  xHash = hashFunction(pH->keyClass);
+  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
+    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
+    next_elem = elem->next;
+    x = new_ht[h].chain;
+    if( x ){
+      elem->next = x;
+      elem->prev = x->prev;
+      if( x->prev ) x->prev->next = elem;
+      else          pH->first = elem;
+      x->prev = elem;
+    }else{
+      elem->next = pH->first;
+      if( pH->first ) pH->first->prev = elem;
+      elem->prev = 0;
+      pH->first = elem;
+    }
+    new_ht[h].chain = elem;
+    new_ht[h].count++;
+  }
+}
+
+/* This function (for internal use only) locates an element in an
+** hash table that matches the given key.  The hash for this key has
+** already been computed and is passed as the 4th parameter.
+*/
+static HashElem *findElementGivenHash(
+  const Hash *pH,     /* The pH to be searched */
+  const void *pKey,   /* The key we are searching for */
+  int nKey,
+  int h               /* The hash for this key. */
+){
+  HashElem *elem;                /* Used to loop thru the element list */
+  int count;                     /* Number of elements left to test */
+  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
+
+  if( pH->ht ){
+    elem = pH->ht[h].chain;
+    count = pH->ht[h].count;
+    xCompare = compareFunction(pH->keyClass);
+    while( count-- && elem ){
+      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
+        return elem;
+      }
+      elem = elem->next;
+    }
+  }
+  return 0;
+}
+
+/* Remove a single entry from the hash table given a pointer to that
+** element and a hash on the element's key.
+*/
+static void removeElementGivenHash(
+  Hash *pH,         /* The pH containing "elem" */
+  HashElem* elem,   /* The element to be removed from the pH */
+  int h             /* Hash value for the element */
+){
+  if( elem->prev ){
+    elem->prev->next = elem->next; 
+  }else{
+    pH->first = elem->next;
+  }
+  if( elem->next ){
+    elem->next->prev = elem->prev;
+  }
+  if( pH->ht[h].chain==elem ){
+    pH->ht[h].chain = elem->next;
+  }
+  pH->ht[h].count--;
+  if( pH->ht[h].count<=0 ){
+    pH->ht[h].chain = 0;
+  }
+  if( pH->copyKey && elem->pKey ){
+    sqliteFree(elem->pKey);
+  }
+  sqliteFree( elem );
+  pH->count--;
+}
+
+/* Attempt to locate an element of the hash table pH with a key
+** that matches pKey,nKey.  Return the data for this element if it is
+** found, or NULL if there is no match.
+*/
+void *sqliteHashFind(const Hash *pH, const void *pKey, int nKey){
+  int h;             /* A hash on key */
+  HashElem *elem;    /* The element that matches key */
+  int (*xHash)(const void*,int);  /* The hash function */
+
+  if( pH==0 || pH->ht==0 ) return 0;
+  xHash = hashFunction(pH->keyClass);
+  assert( xHash!=0 );
+  h = (*xHash)(pKey,nKey);
+  assert( (pH->htsize & (pH->htsize-1))==0 );
+  elem = findElementGivenHash(pH,pKey,nKey, h & (pH->htsize-1));
+  return elem ? elem->data : 0;
+}
+
+/* Insert an element into the hash table pH.  The key is pKey,nKey
+** and the data is "data".
+**
+** If no element exists with a matching key, then a new
+** element is created.  A copy of the key is made if the copyKey
+** flag is set.  NULL is returned.
+**
+** If another element already exists with the same key, then the
+** new data replaces the old data and the old data is returned.
+** The key is not copied in this instance.  If a malloc fails, then
+** the new data is returned and the hash table is unchanged.
+**
+** If the "data" parameter to this function is NULL, then the
+** element corresponding to "key" is removed from the hash table.
+*/
+void *sqliteHashInsert(Hash *pH, const void *pKey, int nKey, void *data){
+  int hraw;             /* Raw hash value of the key */
+  int h;                /* the hash of the key modulo hash table size */
+  HashElem *elem;       /* Used to loop thru the element list */
+  HashElem *new_elem;   /* New element added to the pH */
+  int (*xHash)(const void*,int);  /* The hash function */
+
+  assert( pH!=0 );
+  xHash = hashFunction(pH->keyClass);
+  assert( xHash!=0 );
+  hraw = (*xHash)(pKey, nKey);
+  assert( (pH->htsize & (pH->htsize-1))==0 );
+  h = hraw & (pH->htsize-1);
+  elem = findElementGivenHash(pH,pKey,nKey,h);
+  if( elem ){
+    void *old_data = elem->data;
+    if( data==0 ){
+      removeElementGivenHash(pH,elem,h);
+    }else{
+      elem->data = data;
+    }
+    return old_data;
+  }
+  if( data==0 ) return 0;
+  new_elem = (HashElem*)sqliteMalloc( sizeof(HashElem) );
+  if( new_elem==0 ) return data;
+  if( pH->copyKey && pKey!=0 ){
+    new_elem->pKey = sqliteMallocRaw( nKey );
+    if( new_elem->pKey==0 ){
+      sqliteFree(new_elem);
+      return data;
+    }
+    memcpy((void*)new_elem->pKey, pKey, nKey);
+  }else{
+    new_elem->pKey = (void*)pKey;
+  }
+  new_elem->nKey = nKey;
+  pH->count++;
+  if( pH->htsize==0 ) rehash(pH,8);
+  if( pH->htsize==0 ){
+    pH->count = 0;
+    sqliteFree(new_elem);
+    return data;
+  }
+  if( pH->count > pH->htsize ){
+    rehash(pH,pH->htsize*2);
+  }
+  assert( (pH->htsize & (pH->htsize-1))==0 );
+  h = hraw & (pH->htsize-1);
+  elem = pH->ht[h].chain;
+  if( elem ){
+    new_elem->next = elem;
+    new_elem->prev = elem->prev;
+    if( elem->prev ){ elem->prev->next = new_elem; }
+    else            { pH->first = new_elem; }
+    elem->prev = new_elem;
+  }else{
+    new_elem->next = pH->first;
+    new_elem->prev = 0;
+    if( pH->first ){ pH->first->prev = new_elem; }
+    pH->first = new_elem;
+  }
+  pH->ht[h].count++;
+  pH->ht[h].chain = new_elem;
+  new_elem->data = data;
+  return 0;
+}
diff --git a/ext/sqlite/libsqlite/src/hash.h b/ext/sqlite/libsqlite/src/hash.h
new file mode 100644 (file)
index 0000000..053fa70
--- /dev/null
@@ -0,0 +1,109 @@
+/*
+** 2001 September 22
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This is the header file for the generic hash-table implemenation
+** used in SQLite.
+**
+** $Id$
+*/
+#ifndef _SQLITE_HASH_H_
+#define _SQLITE_HASH_H_
+
+/* Forward declarations of structures. */
+typedef struct Hash Hash;
+typedef struct HashElem HashElem;
+
+/* A complete hash table is an instance of the following structure.
+** The internals of this structure are intended to be opaque -- client
+** code should not attempt to access or modify the fields of this structure
+** directly.  Change this structure only by using the routines below.
+** However, many of the "procedures" and "functions" for modifying and
+** accessing this structure are really macros, so we can't really make
+** this structure opaque.
+*/
+struct Hash {
+  char keyClass;          /* SQLITE_HASH_INT, _POINTER, _STRING, _BINARY */
+  char copyKey;           /* True if copy of key made on insert */
+  int count;              /* Number of entries in this table */
+  HashElem *first;        /* The first element of the array */
+  int htsize;             /* Number of buckets in the hash table */
+  struct _ht {            /* the hash table */
+    int count;               /* Number of entries with this hash */
+    HashElem *chain;         /* Pointer to first entry with this hash */
+  } *ht;
+};
+
+/* Each element in the hash table is an instance of the following 
+** structure.  All elements are stored on a single doubly-linked list.
+**
+** Again, this structure is intended to be opaque, but it can't really
+** be opaque because it is used by macros.
+*/
+struct HashElem {
+  HashElem *next, *prev;   /* Next and previous elements in the table */
+  void *data;              /* Data associated with this element */
+  void *pKey; int nKey;    /* Key associated with this element */
+};
+
+/*
+** There are 4 different modes of operation for a hash table:
+**
+**   SQLITE_HASH_INT         nKey is used as the key and pKey is ignored.
+**
+**   SQLITE_HASH_POINTER     pKey is used as the key and nKey is ignored.
+**
+**   SQLITE_HASH_STRING      pKey points to a string that is nKey bytes long
+**                           (including the null-terminator, if any).  Case
+**                           is ignored in comparisons.
+**
+**   SQLITE_HASH_BINARY      pKey points to binary data nKey bytes long. 
+**                           memcmp() is used to compare keys.
+**
+** A copy of the key is made for SQLITE_HASH_STRING and SQLITE_HASH_BINARY
+** if the copyKey parameter to HashInit is 1.  
+*/
+#define SQLITE_HASH_INT       1
+#define SQLITE_HASH_POINTER   2
+#define SQLITE_HASH_STRING    3
+#define SQLITE_HASH_BINARY    4
+
+/*
+** Access routines.  To delete, insert a NULL pointer.
+*/
+void sqliteHashInit(Hash*, int keytype, int copyKey);
+void *sqliteHashInsert(Hash*, const void *pKey, int nKey, void *pData);
+void *sqliteHashFind(const Hash*, const void *pKey, int nKey);
+void sqliteHashClear(Hash*);
+
+/*
+** Macros for looping over all elements of a hash table.  The idiom is
+** like this:
+**
+**   Hash h;
+**   HashElem *p;
+**   ...
+**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
+**     SomeStructure *pData = sqliteHashData(p);
+**     // do something with pData
+**   }
+*/
+#define sqliteHashFirst(H)  ((H)->first)
+#define sqliteHashNext(E)   ((E)->next)
+#define sqliteHashData(E)   ((E)->data)
+#define sqliteHashKey(E)    ((E)->pKey)
+#define sqliteHashKeysize(E) ((E)->nKey)
+
+/*
+** Number of entries in a hash table
+*/
+#define sqliteHashCount(H)  ((H)->count)
+
+#endif /* _SQLITE_HASH_H_ */
diff --git a/ext/sqlite/libsqlite/src/insert.c b/ext/sqlite/libsqlite/src/insert.c
new file mode 100644 (file)
index 0000000..f625ffc
--- /dev/null
@@ -0,0 +1,832 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains C code routines that are called by the parser
+** to handle INSERT statements in SQLite.
+**
+** $Id$
+*/
+#include "sqliteInt.h"
+
+/*
+** This routine is call to handle SQL of the following forms:
+**
+**    insert into TABLE (IDLIST) values(EXPRLIST)
+**    insert into TABLE (IDLIST) select
+**
+** The IDLIST following the table name is always optional.  If omitted,
+** then a list of all columns for the table is substituted.  The IDLIST
+** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
+**
+** The pList parameter holds EXPRLIST in the first form of the INSERT
+** statement above, and pSelect is NULL.  For the second form, pList is
+** NULL and pSelect is a pointer to the select statement used to generate
+** data for the insert.
+**
+** The code generated follows one of three templates.  For a simple
+** select with data coming from a VALUES clause, the code executes
+** once straight down through.  The template looks like this:
+**
+**         open write cursor to <table> and its indices
+**         puts VALUES clause expressions onto the stack
+**         write the resulting record into <table>
+**         cleanup
+**
+** If the statement is of the form
+**
+**   INSERT INTO <table> SELECT ...
+**
+** And the SELECT clause does not read from <table> at any time, then
+** the generated code follows this template:
+**
+**         goto B
+**      A: setup for the SELECT
+**         loop over the tables in the SELECT
+**           gosub C
+**         end loop
+**         cleanup after the SELECT
+**         goto D
+**      B: open write cursor to <table> and its indices
+**         goto A
+**      C: insert the select result into <table>
+**         return
+**      D: cleanup
+**
+** The third template is used if the insert statement takes its
+** values from a SELECT but the data is being inserted into a table
+** that is also read as part of the SELECT.  In the third form,
+** we have to use a intermediate table to store the results of
+** the select.  The template is like this:
+**
+**         goto B
+**      A: setup for the SELECT
+**         loop over the tables in the SELECT
+**           gosub C
+**         end loop
+**         cleanup after the SELECT
+**         goto D
+**      C: insert the select result into the intermediate table
+**         return
+**      B: open a cursor to an intermediate table
+**         goto A
+**      D: open write cursor to <table> and its indices
+**         loop over the intermediate table
+**           transfer values form intermediate table into <table>
+**         end the loop
+**         cleanup
+*/
+void sqliteInsert(
+  Parse *pParse,        /* Parser context */
+  Token *pTableName,    /* Name of table into which we are inserting */
+  ExprList *pList,      /* List of values to be inserted */
+  Select *pSelect,      /* A SELECT statement to use as the data source */
+  IdList *pColumn,      /* Column names corresponding to IDLIST. */
+  int onError           /* How to handle constraint errors */
+){
+  Table *pTab;          /* The table to insert into */
+  char *zTab = 0;       /* Name of the table into which we are inserting */
+  int i, j, idx;        /* Loop counters */
+  Vdbe *v;              /* Generate code into this virtual machine */
+  Index *pIdx;          /* For looping over indices of the table */
+  int nColumn;          /* Number of columns in the data */
+  int base;             /* First available cursor */
+  int iCont, iBreak;    /* Beginning and end of the loop over srcTab */
+  sqlite *db;           /* The main database structure */
+  int openOp;           /* Opcode used to open cursors */
+  int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
+  int endOfLoop;        /* Label for the end of the insertion loop */
+  int useTempTable;     /* Store SELECT results in intermediate table */
+  int srcTab;           /* Data comes from this temporary cursor if >=0 */
+  int iSelectLoop;      /* Address of code that implements the SELECT */
+  int iCleanup;         /* Address of the cleanup code */
+  int iInsertBlock;     /* Address of the subroutine used to insert data */
+  int iCntMem;          /* Memory cell used for the row counter */
+
+  int row_triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
+  int newIdx = -1;
+
+  if( pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
+  db = pParse->db;
+
+  /* Locate the table into which we will be inserting new information.
+  */
+  zTab = sqliteTableNameFromToken(pTableName);
+  if( zTab==0 ) goto insert_cleanup;
+  pTab = sqliteFindTable(pParse->db, zTab);
+  if( pTab==0 ){
+    sqliteSetString(&pParse->zErrMsg, "no such table: ", zTab, 0);
+    pParse->nErr++;
+    goto insert_cleanup;
+  }
+  if( sqliteAuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0) ){
+    goto insert_cleanup;
+  }
+
+  /* Ensure that:
+  *  (a) the table is not read-only, 
+  *  (b) that if it is a view then ON INSERT triggers exist
+  */
+  row_triggers_exist = 
+    sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT, 
+        TK_BEFORE, TK_ROW, 0) ||
+    sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT, TK_AFTER, TK_ROW, 0);
+  if( pTab->readOnly || (pTab->pSelect && !row_triggers_exist) ){
+    sqliteSetString(&pParse->zErrMsg, 
+      pTab->pSelect ? "view " : "table ",
+      zTab,
+      " may not be modified", 0);
+    pParse->nErr++;
+    goto insert_cleanup;
+  }
+  sqliteFree(zTab);
+  zTab = 0;
+
+  if( pTab==0 ) goto insert_cleanup;
+
+  /* If pTab is really a view, make sure it has been initialized.
+  */
+  if( pTab->pSelect ){
+    if( sqliteViewGetColumnNames(pParse, pTab) ){
+      goto insert_cleanup;
+    }
+  }
+
+  /* Allocate a VDBE
+  */
+  v = sqliteGetVdbe(pParse);
+  if( v==0 ) goto insert_cleanup;
+  sqliteBeginWriteOperation(pParse, pSelect || row_triggers_exist,
+         !row_triggers_exist && pTab->isTemp);
+
+  /* if there are row triggers, allocate a temp table for new.* references. */
+  if( row_triggers_exist ){
+    newIdx = pParse->nTab++;
+  }
+
+  /* Figure out how many columns of data are supplied.  If the data
+  ** is coming from a SELECT statement, then this step also generates
+  ** all the code to implement the SELECT statement and invoke a subroutine
+  ** to process each row of the result. (Template 2.) If the SELECT
+  ** statement uses the the table that is being inserted into, then the
+  ** subroutine is also coded here.  That subroutine stores the SELECT
+  ** results in a temporary table. (Template 3.)
+  */
+  if( pSelect ){
+    /* Data is coming from a SELECT.  Generate code to implement that SELECT
+    */
+    int rc, iInitCode;
+    int opCode;
+    iInitCode = sqliteVdbeAddOp(v, OP_Goto, 0, 0);
+    iSelectLoop = sqliteVdbeCurrentAddr(v);
+    iInsertBlock = sqliteVdbeMakeLabel(v);
+    rc = sqliteSelect(pParse, pSelect, SRT_Subroutine, iInsertBlock, 0,0,0);
+    if( rc || pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
+    iCleanup = sqliteVdbeMakeLabel(v);
+    sqliteVdbeAddOp(v, OP_Goto, 0, iCleanup);
+    assert( pSelect->pEList );
+    nColumn = pSelect->pEList->nExpr;
+
+    /* Set useTempTable to TRUE if the result of the SELECT statement
+    ** should be written into a temporary table.  Set to FALSE if each
+    ** row of the SELECT can be written directly into the result table.
+    */
+    opCode = pTab->isTemp ? OP_OpenTemp : OP_Open;
+    useTempTable = row_triggers_exist || sqliteVdbeFindOp(v,opCode,pTab->tnum);
+
+    if( useTempTable ){
+      /* Generate the subroutine that SELECT calls to process each row of
+      ** the result.  Store the result in a temporary table
+      */
+      srcTab = pParse->nTab++;
+      sqliteVdbeResolveLabel(v, iInsertBlock);
+      sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
+      sqliteVdbeAddOp(v, OP_NewRecno, srcTab, 0);
+      sqliteVdbeAddOp(v, OP_Pull, 1, 0);
+      sqliteVdbeAddOp(v, OP_PutIntKey, srcTab, 0);
+      sqliteVdbeAddOp(v, OP_Return, 0, 0);
+
+      /* The following code runs first because the GOTO at the very top
+      ** of the program jumps to it.  Create the temporary table, then jump
+      ** back up and execute the SELECT code above.
+      */
+      sqliteVdbeChangeP2(v, iInitCode, sqliteVdbeCurrentAddr(v));
+      sqliteVdbeAddOp(v, OP_OpenTemp, srcTab, 0);
+      sqliteVdbeAddOp(v, OP_Goto, 0, iSelectLoop);
+      sqliteVdbeResolveLabel(v, iCleanup);
+    }else{
+      sqliteVdbeChangeP2(v, iInitCode, sqliteVdbeCurrentAddr(v));
+    }
+  }else{
+    /* This is the case if the data for the INSERT is coming from a VALUES
+    ** clause
+    */
+    SrcList dummy;
+    assert( pList!=0 );
+    srcTab = -1;
+    useTempTable = 0;
+    assert( pList );
+    nColumn = pList->nExpr;
+    dummy.nSrc = 0;
+    for(i=0; i<nColumn; i++){
+      if( sqliteExprResolveIds(pParse, 0, &dummy, 0, pList->a[i].pExpr) ){
+        goto insert_cleanup;
+      }
+      if( sqliteExprCheck(pParse, pList->a[i].pExpr, 0, 0) ){
+        goto insert_cleanup;
+      }
+    }
+  }
+
+  /* Make sure the number of columns in the source data matches the number
+  ** of columns to be inserted into the table.
+  */
+  if( pColumn==0 && nColumn!=pTab->nCol ){
+    char zNum1[30];
+    char zNum2[30];
+    sprintf(zNum1,"%d", nColumn);
+    sprintf(zNum2,"%d", pTab->nCol);
+    sqliteSetString(&pParse->zErrMsg, "table ", pTab->zName,
+       " has ", zNum2, " columns but ",
+       zNum1, " values were supplied", 0);
+    pParse->nErr++;
+    goto insert_cleanup;
+  }
+  if( pColumn!=0 && nColumn!=pColumn->nId ){
+    char zNum1[30];
+    char zNum2[30];
+    sprintf(zNum1,"%d", nColumn);
+    sprintf(zNum2,"%d", pColumn->nId);
+    sqliteSetString(&pParse->zErrMsg, zNum1, " values for ",
+       zNum2, " columns", 0);
+    pParse->nErr++;
+    goto insert_cleanup;
+  }
+
+  /* If the INSERT statement included an IDLIST term, then make sure
+  ** all elements of the IDLIST really are columns of the table and 
+  ** remember the column indices.
+  **
+  ** If the table has an INTEGER PRIMARY KEY column and that column
+  ** is named in the IDLIST, then record in the keyColumn variable
+  ** the index into IDLIST of the primary key column.  keyColumn is
+  ** the index of the primary key as it appears in IDLIST, not as
+  ** is appears in the original table.  (The index of the primary
+  ** key in the original table is pTab->iPKey.)
+  */
+  if( pColumn ){
+    for(i=0; i<pColumn->nId; i++){
+      pColumn->a[i].idx = -1;
+    }
+    for(i=0; i<pColumn->nId; i++){
+      for(j=0; j<pTab->nCol; j++){
+        if( sqliteStrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
+          pColumn->a[i].idx = j;
+          if( j==pTab->iPKey ){
+            keyColumn = i;
+          }
+          break;
+        }
+      }
+      if( j>=pTab->nCol ){
+        sqliteSetString(&pParse->zErrMsg, "table ", pTab->zName,
+           " has no column named ", pColumn->a[i].zName, 0);
+        pParse->nErr++;
+        goto insert_cleanup;
+      }
+    }
+  }
+
+  /* If there is no IDLIST term but the table has an integer primary
+  ** key, the set the keyColumn variable to the primary key column index
+  ** in the original table definition.
+  */
+  if( pColumn==0 ){
+    keyColumn = pTab->iPKey;
+  }
+
+  /* Open the temp table for FOR EACH ROW triggers
+  */
+  if( row_triggers_exist ){
+    sqliteVdbeAddOp(v, OP_OpenTemp, newIdx, 0);
+  }
+    
+  /* Initialize the count of rows to be inserted
+  */
+  if( db->flags & SQLITE_CountRows ){
+    iCntMem = pParse->nMem++;
+    sqliteVdbeAddOp(v, OP_Integer, 0, 0);
+    sqliteVdbeAddOp(v, OP_MemStore, iCntMem, 1);
+  }
+
+  /* Open tables and indices if there are no row triggers */
+  if( !row_triggers_exist ){
+    base = pParse->nTab;
+    openOp = pTab->isTemp ? OP_OpenWrAux : OP_OpenWrite;
+    sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
+    sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
+    for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
+      sqliteVdbeAddOp(v, openOp, idx+base, pIdx->tnum);
+      sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
+    }
+    pParse->nTab += idx;
+  }
+
+  /* If the data source is a temporary table, then we have to create
+  ** a loop because there might be multiple rows of data.  If the data
+  ** source is a subroutine call from the SELECT statement, then we need
+  ** to launch the SELECT statement processing.
+  */
+  if( useTempTable ){
+    iBreak = sqliteVdbeMakeLabel(v);
+    sqliteVdbeAddOp(v, OP_Rewind, srcTab, iBreak);
+    iCont = sqliteVdbeCurrentAddr(v);
+  }else if( pSelect ){
+    sqliteVdbeAddOp(v, OP_Goto, 0, iSelectLoop);
+    sqliteVdbeResolveLabel(v, iInsertBlock);
+  }
+
+  endOfLoop = sqliteVdbeMakeLabel(v);
+  if( row_triggers_exist ){
+
+    /* build the new.* reference row */
+    sqliteVdbeAddOp(v, OP_Integer, 13, 0);
+    for(i=0; i<pTab->nCol; i++){
+      if( pColumn==0 ){
+        j = i;
+      }else{
+        for(j=0; j<pColumn->nId; j++){
+          if( pColumn->a[j].idx==i ) break;
+        }
+      }
+      if( pColumn && j>=pColumn->nId ){
+        sqliteVdbeAddOp(v, OP_String, 0, 0);
+        sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
+      }else if( useTempTable ){
+        sqliteVdbeAddOp(v, OP_Column, srcTab, j); 
+      }else if( pSelect ){
+        sqliteVdbeAddOp(v, OP_Dup, nColumn-j-1, 1);
+      }else{
+        sqliteExprCode(pParse, pList->a[j].pExpr);
+      }
+    }
+    sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
+    sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
+    sqliteVdbeAddOp(v, OP_Rewind, newIdx, 0);
+
+    /* Fire BEFORE triggers */
+    if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_BEFORE, pTab, newIdx, -1, 
+        onError, endOfLoop) ){
+      goto insert_cleanup;
+    }
+
+    /* Open the tables and indices for the INSERT */
+    if( !pTab->pSelect ){
+      base = pParse->nTab;
+      openOp = pTab->isTemp ? OP_OpenWrAux : OP_OpenWrite;
+      sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
+      sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
+      for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
+        sqliteVdbeAddOp(v, openOp, idx+base, pIdx->tnum);
+        sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
+      }
+      pParse->nTab += idx;
+    }
+  }
+
+  /* Push the record number for the new entry onto the stack.  The
+  ** record number is a randomly generate integer created by NewRecno
+  ** except when the table has an INTEGER PRIMARY KEY column, in which
+  ** case the record number is the same as that column. 
+  */
+  if( !pTab->pSelect ){
+    if( keyColumn>=0 ){
+      if( useTempTable ){
+        sqliteVdbeAddOp(v, OP_Column, srcTab, keyColumn);
+      }else if( pSelect ){
+        sqliteVdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
+      }else{
+        sqliteExprCode(pParse, pList->a[keyColumn].pExpr);
+      }
+      /* If the PRIMARY KEY expression is NULL, then use OP_NewRecno
+      ** to generate a unique primary key value.
+      */
+      sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
+      sqliteVdbeAddOp(v, OP_Pop, 1, 0);
+      sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
+      sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
+    }else{
+      sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
+    }
+
+    /* Push onto the stack, data for all columns of the new entry, beginning
+    ** with the first column.
+    */
+    for(i=0; i<pTab->nCol; i++){
+      if( i==pTab->iPKey ){
+        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
+        ** Whenever this column is read, the record number will be substituted
+        ** in its place.  So will fill this column with a NULL to avoid
+        ** taking up data space with information that will never be used. */
+        sqliteVdbeAddOp(v, OP_String, 0, 0);
+        continue;
+      }
+      if( pColumn==0 ){
+        j = i;
+      }else{
+        for(j=0; j<pColumn->nId; j++){
+          if( pColumn->a[j].idx==i ) break;
+        }
+      }
+      if( pColumn && j>=pColumn->nId ){
+        sqliteVdbeAddOp(v, OP_String, 0, 0);
+        sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
+      }else if( useTempTable ){
+        sqliteVdbeAddOp(v, OP_Column, srcTab, j); 
+      }else if( pSelect ){
+        sqliteVdbeAddOp(v, OP_Dup, i+nColumn-j, 1);
+      }else{
+        sqliteExprCode(pParse, pList->a[j].pExpr);
+      }
+    }
+
+    /* Generate code to check constraints and generate index keys and
+    ** do the insertion.
+    */
+    sqliteGenerateConstraintChecks(pParse, pTab, base, 0,0,0,onError,endOfLoop);
+    sqliteCompleteInsertion(pParse, pTab, base, 0,0,0);
+
+    /* Update the count of rows that are inserted
+    */
+    if( (db->flags & SQLITE_CountRows)!=0 ){
+      sqliteVdbeAddOp(v, OP_MemIncr, iCntMem, 0);
+    }
+  }
+
+  if( row_triggers_exist ){
+    /* Close all tables opened */
+    if( !pTab->pSelect ){
+      sqliteVdbeAddOp(v, OP_Close, base, 0);
+      for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
+        sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
+      }
+    }
+
+    /* Code AFTER triggers */
+    if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_AFTER, pTab, newIdx, -1, 
+          onError, endOfLoop) ){
+      goto insert_cleanup;
+    }
+  }
+
+  /* The bottom of the loop, if the data source is a SELECT statement
+  */
+  sqliteVdbeResolveLabel(v, endOfLoop);
+  if( useTempTable ){
+    sqliteVdbeAddOp(v, OP_Next, srcTab, iCont);
+    sqliteVdbeResolveLabel(v, iBreak);
+    sqliteVdbeAddOp(v, OP_Close, srcTab, 0);
+  }else if( pSelect ){
+    sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
+    sqliteVdbeAddOp(v, OP_Return, 0, 0);
+    sqliteVdbeResolveLabel(v, iCleanup);
+  }
+
+  if( !row_triggers_exist ){
+    /* Close all tables opened */
+    sqliteVdbeAddOp(v, OP_Close, base, 0);
+    for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
+      sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
+    }
+  }
+
+  sqliteEndWriteOperation(pParse);
+
+  /*
+  ** Return the number of rows inserted.
+  */
+  if( db->flags & SQLITE_CountRows ){
+    sqliteVdbeAddOp(v, OP_ColumnName, 0, 0);
+    sqliteVdbeChangeP3(v, -1, "rows inserted", P3_STATIC);
+    sqliteVdbeAddOp(v, OP_MemLoad, iCntMem, 0);
+    sqliteVdbeAddOp(v, OP_Callback, 1, 0);
+  }
+
+insert_cleanup:
+  if( pList ) sqliteExprListDelete(pList);
+  if( pSelect ) sqliteSelectDelete(pSelect);
+  if ( zTab ) sqliteFree(zTab);
+  sqliteIdListDelete(pColumn);
+}
+
+/*
+** Generate code to do a constraint check prior to an INSERT or an UPDATE.
+**
+** When this routine is called, the stack contains (from bottom to top)
+** the following values:
+**
+**    1.  The recno of the row to be updated before it is updated.  This
+**        value is omitted unless we are doing an UPDATE that involves a
+**        change to the record number.
+**
+**    2.  The recno of the row after the update.
+**
+**    3.  The data in the first column of the entry after the update.
+**
+**    i.  Data from middle columns...
+**
+**    N.  The data in the last column of the entry after the update.
+**
+** The old recno shown as entry (1) above is omitted unless both isUpdate
+** and recnoChng are 1.  isUpdate is true for UPDATEs and false for
+** INSERTs and recnoChng is true if the record number is being changed.
+**
+** The code generated by this routine pushes additional entries onto
+** the stack which are the keys for new index entries for the new record.
+** The order of index keys is the same as the order of the indices on
+** the pTable->pIndex list.  A key is only created for index i if 
+** aIdxUsed!=0 and aIdxUsed[i]!=0.
+**
+** This routine also generates code to check constraints.  NOT NULL,
+** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
+** then the appropriate action is performed.  There are five possible
+** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
+**
+**  Constraint type  Action       What Happens
+**  ---------------  ----------   ----------------------------------------
+**  any              ROLLBACK     The current transaction is rolled back and
+**                                sqlite_exec() returns immediately with a
+**                                return code of SQLITE_CONSTRAINT.
+**
+**  any              ABORT        Back out changes from the current command
+**                                only (do not do a complete rollback) then
+**                                cause sqlite_exec() to return immediately
+**                                with SQLITE_CONSTRAINT.
+**
+**  any              FAIL         Sqlite_exec() returns immediately with a
+**                                return code of SQLITE_CONSTRAINT.  The
+**                                transaction is not rolled back and any
+**                                prior changes are retained.
+**
+**  any              IGNORE       The record number and data is popped from
+**                                the stack and there is an immediate jump
+**                                to label ignoreDest.
+**
+**  NOT NULL         REPLACE      The NULL value is replace by the default
+**                                value for that column.  If the default value
+**                                is NULL, the action is the same as ABORT.
+**
+**  UNIQUE           REPLACE      The other row that conflicts with the row
+**                                being inserted is removed.
+**
+**  CHECK            REPLACE      Illegal.  The results in an exception.
+**
+** Which action to take is determined by the overrideError parameter.
+** Or if overrideError==OE_Default, then the pParse->onError parameter
+** is used.  Or if pParse->onError==OE_Default then the onError value
+** for the constraint is used.
+**
+** The calling routine must open a read/write cursor for pTab with
+** cursor number "base".  All indices of pTab must also have open
+** read/write cursors with cursor number base+i for the i-th cursor.
+** Except, if there is no possibility of a REPLACE action then
+** cursors do not need to be open for indices where aIdxUsed[i]==0.
+**
+** If the isUpdate flag is true, it means that the "base" cursor is
+** initially pointing to an entry that is being updated.  The isUpdate
+** flag causes extra code to be generated so that the "base" cursor
+** is still pointing at the same entry after the routine returns.
+** Without the isUpdate flag, the "base" cursor might be moved.
+*/
+void sqliteGenerateConstraintChecks(
+  Parse *pParse,      /* The parser context */
+  Table *pTab,        /* the table into which we are inserting */
+  int base,           /* Index of a read/write cursor pointing at pTab */
+  char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
+  int recnoChng,      /* True if the record number will change */
+  int isUpdate,       /* True for UPDATE, False for INSERT */
+  int overrideError,  /* Override onError to this if not OE_Default */
+  int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
+){
+  int i;
+  Vdbe *v;
+  int nCol;
+  int onError;
+  int addr;
+  int extra;
+  int iCur;
+  Index *pIdx;
+  int seenReplace = 0;
+  int jumpInst1, jumpInst2;
+  int contAddr;
+  int hasTwoRecnos = (isUpdate && recnoChng);
+
+  v = sqliteGetVdbe(pParse);
+  assert( v!=0 );
+  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
+  nCol = pTab->nCol;
+
+  /* Test all NOT NULL constraints.
+  */
+  for(i=0; i<nCol; i++){
+    if( i==pTab->iPKey ){
+      /* Fix me: Make sure the INTEGER PRIMARY KEY is not NULL. */
+      continue;
+    }
+    onError = pTab->aCol[i].notNull;
+    if( onError==OE_None ) continue;
+    if( overrideError!=OE_Default ){
+      onError = overrideError;
+    }else if( onError==OE_Default ){
+      onError = pParse->db->onError;
+      if( onError==OE_Default ) onError = OE_Abort;
+    }
+    if( onError==OE_Replace && pTab->aCol[i].zDflt==0 ){
+      onError = OE_Abort;
+    }
+    sqliteVdbeAddOp(v, OP_Dup, nCol-1-i, 1);
+    addr = sqliteVdbeAddOp(v, OP_NotNull, 1, 0);
+    switch( onError ){
+      case OE_Rollback:
+      case OE_Abort:
+      case OE_Fail: {
+        char *zMsg = 0;
+        sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
+        sqliteSetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
+                        " may not be NULL", 0);
+        sqliteVdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
+        break;
+      }
+      case OE_Ignore: {
+        sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
+        sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
+        break;
+      }
+      case OE_Replace: {
+        sqliteVdbeAddOp(v, OP_String, 0, 0);
+        sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
+        sqliteVdbeAddOp(v, OP_Push, nCol-i, 0);
+        break;
+      }
+      default: assert(0);
+    }
+    sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
+  }
+
+  /* Test all CHECK constraints
+  */
+  /**** TBD ****/
+
+  /* If we have an INTEGER PRIMARY KEY, make sure the primary key
+  ** of the new record does not previously exist.  Except, if this
+  ** is an UPDATE and the primary key is not changing, that is OK.
+  ** Also, if the conflict resolution policy is REPLACE, then we
+  ** can skip this test.
+  */
+  if( (recnoChng || !isUpdate) && pTab->iPKey>=0 ){
+    onError = pTab->keyConf;
+    if( overrideError!=OE_Default ){
+      onError = overrideError;
+    }else if( onError==OE_Default ){
+      onError = pParse->db->onError;
+      if( onError==OE_Default ) onError = OE_Abort;
+    }
+    if( onError!=OE_Replace ){
+      if( isUpdate ){
+        sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
+        sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
+        jumpInst1 = sqliteVdbeAddOp(v, OP_Eq, 0, 0);
+      }
+      sqliteVdbeAddOp(v, OP_Dup, nCol, 1);
+      jumpInst2 = sqliteVdbeAddOp(v, OP_NotExists, base, 0);
+      switch( onError ){
+        case OE_Rollback:
+        case OE_Abort:
+        case OE_Fail: {
+          sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
+          sqliteVdbeChangeP3(v, -1, "PRIMARY KEY must be unique", P3_STATIC);
+          break;
+        }
+        case OE_Ignore: {
+          sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
+          sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
+          break;
+        }
+        default: assert(0);
+      }
+      contAddr = sqliteVdbeCurrentAddr(v);
+      sqliteVdbeChangeP2(v, jumpInst2, contAddr);
+      if( isUpdate ){
+        sqliteVdbeChangeP2(v, jumpInst1, contAddr);
+        sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
+        sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
+      }
+    }
+  }
+
+  /* Test all UNIQUE constraints by creating entries for each UNIQUE
+  ** index and making sure that duplicate entries do not already exist.
+  ** Add the new records to the indices as we go.
+  */
+  extra = 0;
+  for(extra=(-1), iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
+    if( aIdxUsed && aIdxUsed[iCur]==0 ) continue;
+    extra++;    
+    sqliteVdbeAddOp(v, OP_Dup, nCol+extra, 1);
+    for(i=0; i<pIdx->nColumn; i++){
+      int idx = pIdx->aiColumn[i];
+      if( idx==pTab->iPKey ){
+        sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
+      }else{
+        sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
+      }
+    }
+    jumpInst1 = sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
+    if( pParse->db->file_format>=4 ) sqliteAddIdxKeyType(v, pIdx);
+    onError = pIdx->onError;
+    if( onError==OE_None ) continue;
+    if( overrideError!=OE_Default ){
+      onError = overrideError;
+    }else if( onError==OE_Default ){
+      onError = pParse->db->onError;
+      if( onError==OE_Default ) onError = OE_Abort;
+    }
+    sqliteVdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRecnos, 1);
+    jumpInst2 = sqliteVdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
+    switch( onError ){
+      case OE_Rollback:
+      case OE_Abort:
+      case OE_Fail: {
+        sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
+        sqliteVdbeChangeP3(v, -1, "uniqueness constraint failed", P3_STATIC);
+        break;
+      }
+      case OE_Ignore: {
+        assert( seenReplace==0 );
+        sqliteVdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRecnos, 0);
+        sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
+        break;
+      }
+      case OE_Replace: {
+        sqliteGenerateRowDelete(pParse->db, v, pTab, base, 0);
+        if( isUpdate ){
+          sqliteVdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRecnos, 1);
+          sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
+        }
+        seenReplace = 1;
+        break;
+      }
+      default: assert(0);
+    }
+    contAddr = sqliteVdbeCurrentAddr(v);
+#if NULL_DISTINCT_FOR_UNIQUE
+    sqliteVdbeChangeP2(v, jumpInst1, contAddr);
+#endif
+    sqliteVdbeChangeP2(v, jumpInst2, contAddr);
+  }
+}
+
+/*
+** This routine generates code to finish the INSERT or UPDATE operation
+** that was started by a prior call to sqliteGenerateConstraintChecks.
+** The stack must contain keys for all active indices followed by data
+** and the recno for the new entry.  This routine creates the new
+** entries in all indices and in the main table.
+**
+** The arguments to this routine should be the same as the first six
+** arguments to sqliteGenerateConstraintChecks.
+*/
+void sqliteCompleteInsertion(
+  Parse *pParse,      /* The parser context */
+  Table *pTab,        /* the table into which we are inserting */
+  int base,           /* Index of a read/write cursor pointing at pTab */
+  char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
+  int recnoChng,      /* True if the record number will change */
+  int isUpdate        /* True for UPDATE, False for INSERT */
+){
+  int i;
+  Vdbe *v;
+  int nIdx;
+  Index *pIdx;
+
+  v = sqliteGetVdbe(pParse);
+  assert( v!=0 );
+  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
+  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
+  for(i=nIdx-1; i>=0; i--){
+    if( aIdxUsed && aIdxUsed[i]==0 ) continue;
+    sqliteVdbeAddOp(v, OP_IdxPut, base+i+1, 0);
+  }
+  sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
+  sqliteVdbeAddOp(v, OP_PutIntKey, base, pParse->trigStack?0:1);
+  if( isUpdate && recnoChng ){
+    sqliteVdbeAddOp(v, OP_Pop, 1, 0);
+  }
+}
diff --git a/ext/sqlite/libsqlite/src/main.c b/ext/sqlite/libsqlite/src/main.c
new file mode 100644 (file)
index 0000000..b708b00
--- /dev/null
@@ -0,0 +1,989 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** Main file for the SQLite library.  The routines in this file
+** implement the programmer interface to the library.  Routines in
+** other files are for internal use by SQLite and should not be
+** accessed by users of the library.
+**
+** $Id$
+*/
+#include "sqliteInt.h"
+#include "os.h"
+#include <ctype.h>
+
+/*
+** A pointer to this structure is used to communicate information
+** from sqliteInit into the sqliteInitCallback.
+*/
+typedef struct {
+  sqlite *db;         /* The database being initialized */
+  char **pzErrMsg;    /* Error message stored here */
+} InitData;
+
+
+/*
+** This is the callback routine for the code that initializes the
+** database.  See sqliteInit() below for additional information.
+**
+** Each callback contains the following information:
+**
+**     argv[0] = "file-format" or "schema-cookie" or "table" or "index"
+**     argv[1] = table or index name or meta statement type.
+**     argv[2] = root page number for table or index.  NULL for meta.
+**     argv[3] = SQL text for a CREATE TABLE or CREATE INDEX statement.
+**     argv[4] = "1" for temporary files, "0" for main database
+**
+*/
+static
+int sqliteInitCallback(void *pInit, int argc, char **argv, char **azColName){
+  InitData *pData = (InitData*)pInit;
+  Parse sParse;
+  int nErr = 0;
+
+  /* TODO: Do some validity checks on all fields.  In particular,
+  ** make sure fields do not contain NULLs. Otherwise we might core
+  ** when attempting to initialize from a corrupt database file. */
+
+  assert( argc==5 );
+  switch( argv[0][0] ){
+    case 'v':
+    case 'i':
+    case 't': {  /* CREATE TABLE, CREATE INDEX, or CREATE VIEW statements */
+      if( argv[3] && argv[3][0] ){
+        /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
+        ** But because sParse.initFlag is set to 1, no VDBE code is generated
+        ** or executed.  All the parser does is build the internal data
+        ** structures that describe the table, index, or view.
+        */
+        memset(&sParse, 0, sizeof(sParse));
+        sParse.db = pData->db;
+        sParse.initFlag = 1;
+        sParse.isTemp = argv[4][0] - '0';
+        sParse.newTnum = atoi(argv[2]);
+        sParse.useCallback = 1;
+        sqliteRunParser(&sParse, argv[3], pData->pzErrMsg);
+      }else{
+        /* If the SQL column is blank it means this is an index that
+        ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
+        ** constraint for a CREATE TABLE.  The index should have already
+        ** been created when we processed the CREATE TABLE.  All we have
+        ** to do here is record the root page number for that index.
+        */
+        Index *pIndex = sqliteFindIndex(pData->db, argv[1]);
+        if( pIndex==0 || pIndex->tnum!=0 ){
+          /* This can occur if there exists an index on a TEMP table which
+          ** has the same name as another index on a permanent index.  Since
+          ** the permanent table is hidden by the TEMP table, we can also
+          ** safely ignore the index on the permanent table.
+          */
+          /* Do Nothing */;
+        }else{
+          pIndex->tnum = atoi(argv[2]);
+        }
+      }
+      break;
+    }
+    default: {
+      /* This can not happen! */
+      nErr = 1;
+      assert( nErr==0 );
+    }
+  }
+  return nErr;
+}
+
+/*
+** This is a callback procedure used to reconstruct a table.  The
+** name of the table to be reconstructed is passed in as argv[0].
+**
+** This routine is used to automatically upgrade a database from
+** format version 1 or 2 to version 3.  The correct operation of
+** this routine relys on the fact that no indices are used when
+** copying a table out to a temporary file.
+*/
+static
+int upgrade_3_callback(void *pInit, int argc, char **argv, char **NotUsed){
+  InitData *pData = (InitData*)pInit;
+  int rc;
+  Table *pTab;
+  Trigger *pTrig;
+  char *zErr = 0;
+
+  pTab = sqliteFindTable(pData->db, argv[0]);
+  assert( pTab!=0 );
+  assert( sqliteStrICmp(pTab->zName, argv[0])==0 );
+  if( pTab ){
+    pTrig = pTab->pTrigger;
+    pTab->pTrigger = 0;  /* Disable all triggers before rebuilding the table */
+  }
+  rc = sqlite_exec_printf(pData->db,
+    "CREATE TEMP TABLE sqlite_x AS SELECT * FROM '%q'; "
+    "DELETE FROM '%q'; "
+    "INSERT INTO '%q' SELECT * FROM sqlite_x; "
+    "DROP TABLE sqlite_x;",
+    0, 0, &zErr, argv[0], argv[0], argv[0]);
+  if( zErr ){
+    sqliteSetString(pData->pzErrMsg, zErr, 0);
+    sqlite_freemem(zErr);
+  }
+
+  /* If an error occurred in the SQL above, then the transaction will
+  ** rollback which will delete the internal symbol tables.  This will
+  ** cause the structure that pTab points to be deleted.  In case that
+  ** happened, we need to refetch pTab.
+  */
+  pTab = sqliteFindTable(pData->db, argv[0]);
+  if( pTab ){
+    assert( sqliteStrICmp(pTab->zName, argv[0])==0 );
+    pTab->pTrigger = pTrig;  /* Re-enable triggers */
+  }
+  return rc!=SQLITE_OK;
+}
+
+
+
+/*
+** Attempt to read the database schema and initialize internal
+** data structures.  Return one of the SQLITE_ error codes to
+** indicate success or failure.
+**
+** After the database is initialized, the SQLITE_Initialized
+** bit is set in the flags field of the sqlite structure.  An
+** attempt is made to initialize the database as soon as it
+** is opened.  If that fails (perhaps because another process
+** has the sqlite_master table locked) than another attempt
+** is made the first time the database is accessed.
+*/
+int sqliteInit(sqlite *db, char **pzErrMsg){
+  int rc;
+  BtCursor *curMain;
+  int size;
+  Table *pTab;
+  char *azArg[6];
+  int meta[SQLITE_N_BTREE_META];
+  Parse sParse;
+  InitData initData;
+
+  /*
+  ** The master database table has a structure like this
+  */
+  static char master_schema[] = 
+     "CREATE TABLE sqlite_master(\n"
+     "  type text,\n"
+     "  name text,\n"
+     "  tbl_name text,\n"
+     "  rootpage integer,\n"
+     "  sql text\n"
+     ")"
+  ;
+  static char temp_master_schema[] = 
+     "CREATE TEMP TABLE sqlite_temp_master(\n"
+     "  type text,\n"
+     "  name text,\n"
+     "  tbl_name text,\n"
+     "  rootpage integer,\n"
+     "  sql text\n"
+     ")"
+  ;
+
+  /* The following SQL will read the schema from the master tables.
+  ** The first version works with SQLite file formats 2 or greater.
+  ** The second version is for format 1 files.
+  **
+  ** Beginning with file format 2, the rowid for new table entries
+  ** (including entries in sqlite_master) is an increasing integer.
+  ** So for file format 2 and later, we can play back sqlite_master
+  ** and all the CREATE statements will appear in the right order.
+  ** But with file format 1, table entries were random and so we
+  ** have to make sure the CREATE TABLEs occur before their corresponding
+  ** CREATE INDEXs.  (We don't have to deal with CREATE VIEW or
+  ** CREATE TRIGGER in file format 1 because those constructs did
+  ** not exist then.) 
+  */
+  static char init_script[] = 
+     "SELECT type, name, rootpage, sql, 1 FROM sqlite_temp_master "
+     "UNION ALL "
+     "SELECT type, name, rootpage, sql, 0 FROM sqlite_master";
+  static char older_init_script[] = 
+     "SELECT type, name, rootpage, sql, 1 FROM sqlite_temp_master "
+     "UNION ALL "
+     "SELECT type, name, rootpage, sql, 0 FROM sqlite_master "
+     "WHERE type='table' "
+     "UNION ALL "
+     "SELECT type, name, rootpage, sql, 0 FROM sqlite_master "
+     "WHERE type='index'";
+
+
+  /* Construct the schema tables: sqlite_master and sqlite_temp_master
+  */
+  azArg[0] = "table";
+  azArg[1] = MASTER_NAME;
+  azArg[2] = "2";
+  azArg[3] = master_schema;
+  azArg[4] = "0";
+  azArg[5] = 0;
+  initData.db = db;
+  initData.pzErrMsg = pzErrMsg;
+  sqliteInitCallback(&initData, 5, azArg, 0);
+  pTab = sqliteFindTable(db, MASTER_NAME);
+  if( pTab ){
+    pTab->readOnly = 1;
+  }
+  azArg[1] = TEMP_MASTER_NAME;
+  azArg[3] = temp_master_schema;
+  azArg[4] = "1";
+  sqliteInitCallback(&initData, 5, azArg, 0);
+  pTab = sqliteFindTable(db, TEMP_MASTER_NAME);
+  if( pTab ){
+    pTab->readOnly = 1;
+  }
+
+  /* Create a cursor to hold the database open
+  */
+  if( db->pBe==0 ) return SQLITE_OK;
+  rc = sqliteBtreeCursor(db->pBe, 2, 0, &curMain);
+  if( rc ){
+    sqliteSetString(pzErrMsg, sqlite_error_string(rc), 0);
+    sqliteResetInternalSchema(db);
+    return rc;
+  }
+
+  /* Get the database meta information
+  */
+  rc = sqliteBtreeGetMeta(db->pBe, meta);
+  if( rc ){
+    sqliteSetString(pzErrMsg, sqlite_error_string(rc), 0);
+    sqliteResetInternalSchema(db);
+    sqliteBtreeCloseCursor(curMain);
+    return rc;
+  }
+  db->schema_cookie = meta[1];
+  db->next_cookie = db->schema_cookie;
+  db->file_format = meta[2];
+  size = meta[3];
+  if( size==0 ){ size = MAX_PAGES; }
+  db->cache_size = size;
+  sqliteBtreeSetCacheSize(db->pBe, size);
+  db->safety_level = meta[4];
+  if( db->safety_level==0 ) db->safety_level = 2;
+  sqliteBtreeSetSafetyLevel(db->pBe, db->safety_level);
+
+  /*
+  **     file_format==1    Version 2.1.0.
+  **     file_format==2    Version 2.2.0. Add support for INTEGER PRIMARY KEY.
+  **     file_format==3    Version 2.6.0. Fix empty-string index bug.
+  **     file_format==4    Version 2.7.0. Add support for separate numeric and
+  **                       text datatypes.
+  */
+  if( db->file_format==0 ){
+    /* This happens if the database was initially empty */
+    db->file_format = 4;
+  }else if( db->file_format>4 ){
+    sqliteBtreeCloseCursor(curMain);
+    sqliteSetString(pzErrMsg, "unsupported file format", 0);
+    return SQLITE_ERROR;
+  }
+
+  /* Read the schema information out of the schema tables
+  */
+  memset(&sParse, 0, sizeof(sParse));
+  sParse.db = db;
+  sParse.pBe = db->pBe;
+  sParse.xCallback = sqliteInitCallback;
+  sParse.pArg = (void*)&initData;
+  sParse.initFlag = 1;
+  sParse.useCallback = 1;
+  sqliteRunParser(&sParse,
+      db->file_format>=2 ? init_script : older_init_script,
+      pzErrMsg);
+  if( sqlite_malloc_failed ){
+    sqliteSetString(pzErrMsg, "out of memory", 0);
+    sParse.rc = SQLITE_NOMEM;
+    sqliteBtreeRollback(db->pBe);
+    sqliteResetInternalSchema(db);
+  }
+  if( sParse.rc==SQLITE_OK ){
+    db->flags |= SQLITE_Initialized;
+    sqliteCommitInternalChanges(db);
+  }else{
+    db->flags &= ~SQLITE_Initialized;
+    sqliteResetInternalSchema(db);
+  }
+  sqliteBtreeCloseCursor(curMain);
+  return sParse.rc;
+}
+
+/*
+** The version of the library
+*/
+const char rcsid[] = "@(#) \044Id: SQLite version " SQLITE_VERSION " $";
+const char sqlite_version[] = SQLITE_VERSION;
+
+/*
+** Does the library expect data to be encoded as UTF-8 or iso8859?  The
+** following global constant always lets us know.
+*/
+#ifdef SQLITE_UTF8
+const char sqlite_encoding[] = "UTF-8";
+#else
+const char sqlite_encoding[] = "iso8859";
+#endif
+
+/*
+** Open a new SQLite database.  Construct an "sqlite" structure to define
+** the state of this database and return a pointer to that structure.
+**
+** An attempt is made to initialize the in-memory data structures that
+** hold the database schema.  But if this fails (because the schema file
+** is locked) then that step is deferred until the first call to
+** sqlite_exec().
+*/
+sqlite *sqlite_open(const char *zFilename, int mode, char **pzErrMsg){
+  sqlite *db;
+  int rc;
+
+  /* Allocate the sqlite data structure */
+  db = sqliteMalloc( sizeof(sqlite) );
+  if( pzErrMsg ) *pzErrMsg = 0;
+  if( db==0 ) goto no_mem_on_open;
+  sqliteHashInit(&db->tblHash, SQLITE_HASH_STRING, 0);
+  sqliteHashInit(&db->idxHash, SQLITE_HASH_STRING, 0);
+  sqliteHashInit(&db->trigHash, SQLITE_HASH_STRING, 0);
+  sqliteHashInit(&db->aFunc, SQLITE_HASH_STRING, 1);
+  sqliteHashInit(&db->aFKey, SQLITE_HASH_STRING, 1);
+  db->onError = OE_Default;
+  db->priorNewRowid = 0;
+  db->magic = SQLITE_MAGIC_BUSY;
+  
+  /* Open the backend database driver */
+  rc = sqliteBtreeOpen(zFilename, 0, MAX_PAGES, &db->pBe);
+  if( rc!=SQLITE_OK ){
+    switch( rc ){
+      default: {
+        sqliteSetString(pzErrMsg, "unable to open database: ", zFilename, 0);
+      }
+    }
+    sqliteFree(db);
+    sqliteStrRealloc(pzErrMsg);
+    return 0;
+  }
+
+  /* Attempt to read the schema */
+  sqliteRegisterBuiltinFunctions(db);
+  rc = sqliteInit(db, pzErrMsg);
+  db->magic = SQLITE_MAGIC_OPEN;
+  if( sqlite_malloc_failed ){
+    sqlite_close(db);
+    goto no_mem_on_open;
+  }else if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
+    sqlite_close(db);
+    sqliteStrRealloc(pzErrMsg);
+    return 0;
+  }else if( pzErrMsg ){
+    sqliteFree(*pzErrMsg);
+    *pzErrMsg = 0;
+  }
+
+  /* If the database is in formats 1 or 2, then upgrade it to
+  ** version 3.  This will reconstruct all indices.  If the
+  ** upgrade fails for any reason (ex: out of disk space, database
+  ** is read only, interrupt received, etc.) then refuse to open.
+  */
+  if( rc==SQLITE_OK && db->file_format<3 ){
+    char *zErr = 0;
+    InitData initData;
+    int meta[SQLITE_N_BTREE_META];
+
+    initData.db = db;
+    initData.pzErrMsg = &zErr;
+    db->file_format = 3;
+    rc = sqlite_exec(db,
+      "BEGIN; SELECT name FROM sqlite_master WHERE type='table';",
+      upgrade_3_callback,
+      &initData,
+      &zErr);
+    if( rc==SQLITE_OK ){
+      sqliteBtreeGetMeta(db->pBe, meta);
+      meta[2] = 4;
+      sqliteBtreeUpdateMeta(db->pBe, meta);
+      sqlite_exec(db, "COMMIT", 0, 0, 0);
+    }
+    if( rc!=SQLITE_OK ){
+      sqliteSetString(pzErrMsg, 
+        "unable to upgrade database to the version 2.6 format",
+        zErr ? ": " : 0, zErr, 0);
+      sqlite_freemem(zErr);
+      sqliteStrRealloc(pzErrMsg);
+      sqlite_close(db);
+      return 0;
+    }
+    sqlite_freemem(zErr);
+  }
+
+  /* Return a pointer to the newly opened database structure */
+  return db;
+
+no_mem_on_open:
+  sqliteSetString(pzErrMsg, "out of memory", 0);
+  sqliteStrRealloc(pzErrMsg);
+  return 0;
+}
+
+/*
+** Return the ROWID of the most recent insert
+*/
+int sqlite_last_insert_rowid(sqlite *db){
+  return db->lastRowid;
+}
+
+/*
+** Return the number of changes in the most recent call to sqlite_exec().
+*/
+int sqlite_changes(sqlite *db){
+  return db->nChange;
+}
+
+/*
+** Close an existing SQLite database
+*/
+void sqlite_close(sqlite *db){
+  HashElem *i;
+  db->want_to_close = 1;
+  if( sqliteSafetyCheck(db) || sqliteSafetyOn(db) ){
+    /* printf("DID NOT CLOSE\n"); fflush(stdout); */
+    return;
+  }
+  db->magic = SQLITE_MAGIC_CLOSED;
+  sqliteBtreeClose(db->pBe);
+  sqliteResetInternalSchema(db);
+  if( db->pBeTemp ){
+    sqliteBtreeClose(db->pBeTemp);
+  }
+  for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
+    FuncDef *pFunc, *pNext;
+    for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){
+      pNext = pFunc->pNext;
+      sqliteFree(pFunc);
+    }
+  }
+  sqliteHashClear(&db->aFunc);
+  sqliteHashClear(&db->aFKey);
+  sqliteFree(db);
+}
+
+/*
+** Return TRUE if the given SQL string ends in a semicolon.
+**
+** Special handling is require for CREATE TRIGGER statements.
+** Whenever the CREATE TRIGGER keywords are seen, the statement
+** must end with ";END;".
+*/
+int sqlite_complete(const char *zSql){
+  int isComplete = 1;
+  int requireEnd = 0;
+  int seenText = 0;
+  int seenCreate = 0;
+  while( *zSql ){
+    switch( *zSql ){
+      case ';': {
+        isComplete = 1;
+        seenText = 1;
+        seenCreate = 0;
+        break;
+      }
+      case ' ':
+      case '\t':
+      case '\n':
+      case '\f': {
+        break;
+      }
+      case '[': {
+        isComplete = 0;
+        seenText = 1;
+        seenCreate = 0;
+        zSql++;
+        while( *zSql && *zSql!=']' ){ zSql++; }
+        if( *zSql==0 ) return 0;
+        break;
+      }
+      case '"':
+      case '\'': {
+        int c = *zSql;
+        isComplete = 0;
+        seenText = 1;
+        seenCreate = 0;
+        zSql++;
+        while( *zSql && *zSql!=c ){ zSql++; }
+        if( *zSql==0 ) return 0;
+        break;
+      }
+      case '-': {
+        if( zSql[1]!='-' ){
+          isComplete = 0;
+          seenCreate = 0;
+          break;
+        }
+        while( *zSql && *zSql!='\n' ){ zSql++; }
+        if( *zSql==0 ) return seenText && isComplete && requireEnd==0;
+        break;
+      }
+      case 'c':
+      case 'C': {
+        seenText = 1;
+        if( !isComplete ) break;
+        isComplete = 0;
+        if( sqliteStrNICmp(zSql, "create", 6)!=0 ) break;
+        if( !isspace(zSql[6]) ) break;
+        zSql += 5;
+        seenCreate = 1;
+        while( isspace(zSql[1]) ) zSql++;
+        if( sqliteStrNICmp(&zSql[1],"trigger", 7)!=0 ) break;
+        zSql += 7;
+        requireEnd++;
+        break;
+      }
+      case 't':
+      case 'T': {
+        seenText = 1;
+        if( !seenCreate ) break;
+        seenCreate = 0;
+        isComplete = 0;
+        if( sqliteStrNICmp(zSql, "trigger", 7)!=0 ) break;
+        if( !isspace(zSql[7]) ) break;
+        zSql += 6;
+        requireEnd++;
+        break;
+      }
+      case 'e':
+      case 'E': {
+        seenCreate = 0;
+        seenText = 1;
+        if( !isComplete ) break;
+        isComplete = 0;
+        if( requireEnd==0 ) break;
+        if( sqliteStrNICmp(zSql, "end", 3)!=0 ) break;
+        zSql += 2;
+        while( isspace(zSql[1]) ) zSql++;
+        if( zSql[1]==';' ){
+          zSql++;
+          isComplete = 1;
+          requireEnd--;
+        }
+        break;
+      }
+      default: {
+        seenCreate = 0;
+        seenText = 1;
+        isComplete = 0;
+        break;
+      }
+    }
+    zSql++;
+  }
+  return seenText && isComplete && requireEnd==0;
+}
+
+/*
+** This routine does the work of either sqlite_exec() or sqlite_compile().
+** It works like sqlite_exec() if pVm==NULL and it works like sqlite_compile()
+** otherwise.
+*/
+static int sqliteMain(
+  sqlite *db,                 /* The database on which the SQL executes */
+  const char *zSql,           /* The SQL to be executed */
+  sqlite_callback xCallback,  /* Invoke this callback routine */
+  void *pArg,                 /* First argument to xCallback() */
+  const char **pzTail,        /* OUT: Next statement after the first */
+  sqlite_vm **ppVm,           /* OUT: The virtual machine */
+  char **pzErrMsg             /* OUT: Write error messages here */
+){
+  Parse sParse;
+
+  if( pzErrMsg ) *pzErrMsg = 0;
+  if( sqliteSafetyOn(db) ) goto exec_misuse;
+  if( (db->flags & SQLITE_Initialized)==0 ){
+    int rc, cnt = 1;
+    while( (rc = sqliteInit(db, pzErrMsg))==SQLITE_BUSY
+       && db->xBusyCallback && db->xBusyCallback(db->pBusyArg, "", cnt++)!=0 ){}
+    if( rc!=SQLITE_OK ){
+      sqliteStrRealloc(pzErrMsg);
+      sqliteSafetyOff(db);
+      return rc;
+    }
+    if( pzErrMsg ){
+      sqliteFree(*pzErrMsg);
+      *pzErrMsg = 0;
+    }
+  }
+  if( db->file_format<3 ){
+    sqliteSafetyOff(db);
+    sqliteSetString(pzErrMsg, "obsolete database file format", 0);
+    return SQLITE_ERROR;
+  }
+  if( db->pVdbe==0 ){ db->nChange = 0; }
+  memset(&sParse, 0, sizeof(sParse));
+  sParse.db = db;
+  sParse.pBe = db->pBe;
+  sParse.xCallback = xCallback;
+  sParse.pArg = pArg;
+  sParse.useCallback = ppVm==0;
+#ifndef SQLITE_OMIT_TRACE
+  if( db->xTrace ) db->xTrace(db->pTraceArg, zSql);
+#endif
+  sqliteRunParser(&sParse, zSql, pzErrMsg);
+  if( sqlite_malloc_failed ){
+    sqliteSetString(pzErrMsg, "out of memory", 0);
+    sParse.rc = SQLITE_NOMEM;
+    sqliteBtreeRollback(db->pBe);
+    if( db->pBeTemp ) sqliteBtreeRollback(db->pBeTemp);
+    db->flags &= ~SQLITE_InTrans;
+    sqliteResetInternalSchema(db);
+  }
+  if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
+  if( sParse.rc!=SQLITE_OK && pzErrMsg && *pzErrMsg==0 ){
+    sqliteSetString(pzErrMsg, sqlite_error_string(sParse.rc), 0);
+  }
+  sqliteStrRealloc(pzErrMsg);
+  if( sParse.rc==SQLITE_SCHEMA ){
+    sqliteResetInternalSchema(db);
+  }
+  if( sParse.useCallback==0 ){
+    assert( ppVm );
+    *ppVm = (sqlite_vm*)sParse.pVdbe;
+    *pzTail = sParse.zTail;
+  }
+  if( sqliteSafetyOff(db) ) goto exec_misuse;
+  return sParse.rc;
+
+exec_misuse:
+  if( pzErrMsg ){
+    *pzErrMsg = 0;
+    sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), 0);
+    sqliteStrRealloc(pzErrMsg);
+  }
+  return SQLITE_MISUSE;
+}
+
+/*
+** Execute SQL code.  Return one of the SQLITE_ success/failure
+** codes.  Also write an error message into memory obtained from
+** malloc() and make *pzErrMsg point to that message.
+**
+** If the SQL is a query, then for each row in the query result
+** the xCallback() function is called.  pArg becomes the first
+** argument to xCallback().  If xCallback=NULL then no callback
+** is invoked, even for queries.
+*/
+int sqlite_exec(
+  sqlite *db,                 /* The database on which the SQL executes */
+  const char *zSql,           /* The SQL to be executed */
+  sqlite_callback xCallback,  /* Invoke this callback routine */
+  void *pArg,                 /* First argument to xCallback() */
+  char **pzErrMsg             /* Write error messages here */
+){
+  return sqliteMain(db, zSql, xCallback, pArg, 0, 0, pzErrMsg);
+}
+
+/*
+** Compile a single statement of SQL into a virtual machine.  Return one
+** of the SQLITE_ success/failure codes.  Also write an error message into
+** memory obtained from malloc() and make *pzErrMsg point to that message.
+*/
+int sqlite_compile(
+  sqlite *db,                 /* The database on which the SQL executes */
+  const char *zSql,           /* The SQL to be executed */
+  const char **pzTail,        /* OUT: Next statement after the first */
+  sqlite_vm **ppVm,           /* OUT: The virtual machine */
+  char **pzErrMsg             /* OUT: Write error messages here */
+){
+  return sqliteMain(db, zSql, 0, 0, pzTail, ppVm, pzErrMsg);
+}
+
+/*
+** The following routine destroys a virtual machine that is created by
+** the sqlite_compile() routine.
+**
+** The integer returned is an SQLITE_ success/failure code that describes
+** the result of executing the virtual machine.  An error message is
+** written into memory obtained from malloc and *pzErrMsg is made to
+** point to that error if pzErrMsg is not NULL.  The calling routine
+** should use sqlite_freemem() to delete the message when it has finished
+** with it.
+*/
+int sqlite_finalize(
+  sqlite_vm *pVm,            /* The virtual machine to be destroyed */
+  char **pzErrMsg            /* OUT: Write error messages here */
+){
+  int rc = sqliteVdbeFinalize((Vdbe*)pVm, pzErrMsg);
+  sqliteStrRealloc(pzErrMsg);
+  return rc;
+}
+
+/*
+** Return a static string that describes the kind of error specified in the
+** argument.
+*/
+const char *sqlite_error_string(int rc){
+  const char *z;
+  switch( rc ){
+    case SQLITE_OK:         z = "not an error";                          break;
+    case SQLITE_ERROR:      z = "SQL logic error or missing database";   break;
+    case SQLITE_INTERNAL:   z = "internal SQLite implementation flaw";   break;
+    case SQLITE_PERM:       z = "access permission denied";              break;
+    case SQLITE_ABORT:      z = "callback requested query abort";        break;
+    case SQLITE_BUSY:       z = "database is locked";                    break;
+    case SQLITE_LOCKED:     z = "database table is locked";              break;
+    case SQLITE_NOMEM:      z = "out of memory";                         break;
+    case SQLITE_READONLY:   z = "attempt to write a readonly database";  break;
+    case SQLITE_INTERRUPT:  z = "interrupted";                           break;
+    case SQLITE_IOERR:      z = "disk I/O error";                        break;
+    case SQLITE_CORRUPT:    z = "database disk image is malformed";      break;
+    case SQLITE_NOTFOUND:   z = "table or record not found";             break;
+    case SQLITE_FULL:       z = "database is full";                      break;
+    case SQLITE_CANTOPEN:   z = "unable to open database file";          break;
+    case SQLITE_PROTOCOL:   z = "database locking protocol failure";     break;
+    case SQLITE_EMPTY:      z = "table contains no data";                break;
+    case SQLITE_SCHEMA:     z = "database schema has changed";           break;
+    case SQLITE_TOOBIG:     z = "too much data for one table row";       break;
+    case SQLITE_CONSTRAINT: z = "constraint failed";                     break;
+    case SQLITE_MISMATCH:   z = "datatype mismatch";                     break;
+    case SQLITE_MISUSE:     z = "library routine called out of sequence";break;
+    case SQLITE_NOLFS:      z = "kernel lacks large file support";       break;
+    case SQLITE_AUTH:       z = "authorization denied";                  break;
+    default:                z = "unknown error";                         break;
+  }
+  return z;
+}
+
+/*
+** This routine implements a busy callback that sleeps and tries
+** again until a timeout value is reached.  The timeout value is
+** an integer number of milliseconds passed in as the first
+** argument.
+*/
+static int sqliteDefaultBusyCallback(
+ void *Timeout,           /* Maximum amount of time to wait */
+ const char *NotUsed,     /* The name of the table that is busy */
+ int count                /* Number of times table has been busy */
+){
+#if SQLITE_MIN_SLEEP_MS==1
+  int delay = 10;
+  int prior_delay = 0;
+  int timeout = (int)Timeout;
+  int i;
+
+  for(i=1; i<count; i++){ 
+    prior_delay += delay;
+    delay = delay*2;
+    if( delay>=1000 ){
+      delay = 1000;
+      prior_delay += 1000*(count - i - 1);
+      break;
+    }
+  }
+  if( prior_delay + delay > timeout ){
+    delay = timeout - prior_delay;
+    if( delay<=0 ) return 0;
+  }
+  sqliteOsSleep(delay);
+  return 1;
+#else
+  int timeout = (int)Timeout;
+  if( (count+1)*1000 > timeout ){
+    return 0;
+  }
+  sqliteOsSleep(1000);
+  return 1;
+#endif
+}
+
+/*
+** This routine sets the busy callback for an Sqlite database to the
+** given callback function with the given argument.
+*/
+void sqlite_busy_handler(
+  sqlite *db,
+  int (*xBusy)(void*,const char*,int),
+  void *pArg
+){
+  db->xBusyCallback = xBusy;
+  db->pBusyArg = pArg;
+}
+
+/*
+** This routine installs a default busy handler that waits for the
+** specified number of milliseconds before returning 0.
+*/
+void sqlite_busy_timeout(sqlite *db, int ms){
+  if( ms>0 ){
+    sqlite_busy_handler(db, sqliteDefaultBusyCallback, (void*)ms);
+  }else{
+    sqlite_busy_handler(db, 0, 0);
+  }
+}
+
+/*
+** Cause any pending operation to stop at its earliest opportunity.
+*/
+void sqlite_interrupt(sqlite *db){
+  db->flags |= SQLITE_Interrupt;
+}
+
+/*
+** Windows systems should call this routine to free memory that
+** is returned in the in the errmsg parameter of sqlite_open() when
+** SQLite is a DLL.  For some reason, it does not work to call free()
+** directly.
+**
+** Note that we need to call free() not sqliteFree() here, since every
+** string that is exported from SQLite should have already passed through
+** sqliteStrRealloc().
+*/
+void sqlite_freemem(void *p){ free(p); }
+
+/*
+** Windows systems need functions to call to return the sqlite_version
+** and sqlite_encoding strings since they are unable to access constants
+** within DLLs.
+*/
+const char *sqlite_libversion(void){ return sqlite_version; }
+const char *sqlite_libencoding(void){ return sqlite_encoding; }
+
+/*
+** Create new user-defined functions.  The sqlite_create_function()
+** routine creates a regular function and sqlite_create_aggregate()
+** creates an aggregate function.
+**
+** Passing a NULL xFunc argument or NULL xStep and xFinalize arguments
+** disables the function.  Calling sqlite_create_function() with the
+** same name and number of arguments as a prior call to
+** sqlite_create_aggregate() disables the prior call to
+** sqlite_create_aggregate(), and vice versa.
+**
+** If nArg is -1 it means that this function will accept any number
+** of arguments, including 0.
+*/
+int sqlite_create_function(
+  sqlite *db,          /* Add the function to this database connection */
+  const char *zName,   /* Name of the function to add */
+  int nArg,            /* Number of arguments */
+  void (*xFunc)(sqlite_func*,int,const char**),  /* The implementation */
+  void *pUserData      /* User data */
+){
+  FuncDef *p;
+  int nName;
+  if( db==0 || zName==0 || sqliteSafetyCheck(db) ) return 1;
+  nName = strlen(zName);
+  if( nName>255 ) return 1;
+  p = sqliteFindFunction(db, zName, nName, nArg, 1);
+  if( p==0 ) return 1;
+  p->xFunc = xFunc;
+  p->xStep = 0;
+  p->xFinalize = 0;
+  p->pUserData = pUserData;
+  return 0;
+}
+int sqlite_create_aggregate(
+  sqlite *db,          /* Add the function to this database connection */
+  const char *zName,   /* Name of the function to add */
+  int nArg,            /* Number of arguments */
+  void (*xStep)(sqlite_func*,int,const char**), /* The step function */
+  void (*xFinalize)(sqlite_func*),              /* The finalizer */
+  void *pUserData      /* User data */
+){
+  FuncDef *p;
+  int nName;
+  if( db==0 || zName==0 || sqliteSafetyCheck(db) ) return 1;
+  nName = strlen(zName);
+  if( nName>255 ) return 1;
+  p = sqliteFindFunction(db, zName, nName, nArg, 1);
+  if( p==0 ) return 1;
+  p->xFunc = 0;
+  p->xStep = xStep;
+  p->xFinalize = xFinalize;
+  p->pUserData = pUserData;
+  return 0;
+}
+
+/*
+** Change the datatype for all functions with a given name.  See the
+** header comment for the prototype of this function in sqlite.h for
+** additional information.
+*/
+int sqlite_function_type(sqlite *db, const char *zName, int dataType){
+  FuncDef *p = (FuncDef*)sqliteHashFind(&db->aFunc, zName, strlen(zName));
+  while( p ){
+    p->dataType = dataType; 
+    p = p->pNext;
+  }
+  return SQLITE_OK;
+}
+
+/*
+** Register a trace function.  The pArg from the previously registered trace
+** is returned.  
+**
+** A NULL trace function means that no tracing is executes.  A non-NULL
+** trace is a pointer to a function that is invoked at the start of each
+** sqlite_exec().
+*/
+void *sqlite_trace(sqlite *db, void (*xTrace)(void*,const char*), void *pArg){
+#ifndef SQLITE_OMIT_TRACE
+  void *pOld = db->pTraceArg;
+  db->xTrace = xTrace;
+  db->pTraceArg = pArg;
+  return pOld;
+#else
+  return 0;
+#endif
+}
+
+
+/*
+** Attempt to open the file named in the argument as the auxiliary database
+** file.  The auxiliary database file is used to store TEMP tables.  But
+** by using this API, it is possible to trick SQLite into opening two
+** separate databases and acting on them as if they were one.
+**
+** This routine closes the existing auxiliary database file, which will
+** cause any previously created TEMP tables to be dropped.
+**
+** The zName parameter can be a NULL pointer or an empty string to cause
+** a temporary file to be opened and automatically deleted when closed.
+*/
+int sqlite_open_aux_file(sqlite *db, const char *zName, char **pzErrMsg){
+  int rc;
+  if( zName && zName[0]==0 ) zName = 0;
+  if( sqliteSafetyOn(db) ) goto openaux_misuse;
+  sqliteResetInternalSchema(db);
+  if( db->pBeTemp!=0 ){
+    sqliteBtreeClose(db->pBeTemp);
+  }
+  rc = sqliteBtreeOpen(zName, 0, MAX_PAGES, &db->pBeTemp);
+  if( rc ){
+    if( zName==0 ) zName = "a temporary file";
+    sqliteSetString(pzErrMsg, "unable to open ", zName, 
+      ": ", sqlite_error_string(rc), 0);
+    sqliteStrRealloc(pzErrMsg);
+    sqliteSafetyOff(db);
+    return rc;
+  }
+  rc = sqliteInit(db, pzErrMsg);
+  if( sqliteSafetyOff(db) ) goto openaux_misuse;
+  sqliteStrRealloc(pzErrMsg);
+  return rc;
+
+openaux_misuse:
+  sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), 0);
+  sqliteStrRealloc(pzErrMsg);
+  return SQLITE_MISUSE;
+}
diff --git a/ext/sqlite/libsqlite/src/opcodes.c b/ext/sqlite/libsqlite/src/opcodes.c
new file mode 100644 (file)
index 0000000..0e611ab
--- /dev/null
@@ -0,0 +1,132 @@
+/* Automatically generated file.  Do not edit */
+char *sqliteOpcodeNames[] = { "???", 
+  "Goto", 
+  "Gosub", 
+  "Return", 
+  "Halt", 
+  "Integer", 
+  "String", 
+  "Pop", 
+  "Dup", 
+  "Pull", 
+  "Push", 
+  "ColumnName", 
+  "Callback", 
+  "NullCallback", 
+  "Concat", 
+  "Add", 
+  "Subtract", 
+  "Multiply", 
+  "Divide", 
+  "Remainder", 
+  "Function", 
+  "BitAnd", 
+  "BitOr", 
+  "ShiftLeft", 
+  "ShiftRight", 
+  "AddImm", 
+  "MustBeInt", 
+  "Eq", 
+  "Ne", 
+  "Lt", 
+  "Le", 
+  "Gt", 
+  "Ge", 
+  "StrEq", 
+  "StrNe", 
+  "StrLt", 
+  "StrLe", 
+  "StrGt", 
+  "StrGe", 
+  "And", 
+  "Or", 
+  "Negative", 
+  "AbsValue", 
+  "Not", 
+  "BitNot", 
+  "Noop", 
+  "If", 
+  "IfNot", 
+  "IsNull", 
+  "NotNull", 
+  "MakeRecord", 
+  "MakeIdxKey", 
+  "MakeKey", 
+  "IncrKey", 
+  "Checkpoint", 
+  "Transaction", 
+  "Commit", 
+  "Rollback", 
+  "ReadCookie", 
+  "SetCookie", 
+  "VerifyCookie", 
+  "OpenAux", 
+  "OpenWrAux", 
+  "OpenWrite", 
+  "Open", 
+  "OpenTemp", 
+  "RenameCursor", 
+  "Close", 
+  "MoveLt", 
+  "MoveTo", 
+  "Distinct", 
+  "NotFound", 
+  "Found", 
+  "IsUnique", 
+  "NotExists", 
+  "NewRecno", 
+  "PutIntKey", 
+  "PutStrKey", 
+  "Delete", 
+  "KeyAsData", 
+  "Column", 
+  "Recno", 
+  "FullKey", 
+  "NullRow", 
+  "Last", 
+  "Rewind", 
+  "Prev", 
+  "Next", 
+  "IdxPut", 
+  "IdxDelete", 
+  "IdxRecno", 
+  "IdxLT", 
+  "IdxGT", 
+  "IdxGE", 
+  "Destroy", 
+  "Clear", 
+  "CreateIndex", 
+  "CreateTable", 
+  "IntegrityCk", 
+  "ListWrite", 
+  "ListRewind", 
+  "ListRead", 
+  "ListReset", 
+  "ListPush", 
+  "ListPop", 
+  "SortPut", 
+  "SortMakeRec", 
+  "SortMakeKey", 
+  "Sort", 
+  "SortNext", 
+  "SortCallback", 
+  "SortReset", 
+  "FileOpen", 
+  "FileRead", 
+  "FileColumn", 
+  "MemStore", 
+  "MemLoad", 
+  "MemIncr", 
+  "AggReset", 
+  "AggInit", 
+  "AggFunc", 
+  "AggFocus", 
+  "AggSet", 
+  "AggGet", 
+  "AggNext", 
+  "SetInsert", 
+  "SetFound", 
+  "SetNotFound", 
+  "SetFirst", 
+  "SetNext", 
+};
diff --git a/ext/sqlite/libsqlite/src/opcodes.h b/ext/sqlite/libsqlite/src/opcodes.h
new file mode 100644 (file)
index 0000000..5e0a9f8
--- /dev/null
@@ -0,0 +1,130 @@
+/* Automatically generated file.  Do not edit */
+#define OP_Goto                          1
+#define OP_Gosub                         2
+#define OP_Return                        3
+#define OP_Halt                          4
+#define OP_Integer                       5
+#define OP_String                        6
+#define OP_Pop                           7
+#define OP_Dup                           8
+#define OP_Pull                          9
+#define OP_Push                         10
+#define OP_ColumnName                   11
+#define OP_Callback                     12
+#define OP_NullCallback                 13
+#define OP_Concat                       14
+#define OP_Add                          15
+#define OP_Subtract                     16
+#define OP_Multiply                     17
+#define OP_Divide                       18
+#define OP_Remainder                    19
+#define OP_Function                     20
+#define OP_BitAnd                       21
+#define OP_BitOr                        22
+#define OP_ShiftLeft                    23
+#define OP_ShiftRight                   24
+#define OP_AddImm                       25
+#define OP_MustBeInt                    26
+#define OP_Eq                           27
+#define OP_Ne                           28
+#define OP_Lt                           29
+#define OP_Le                           30
+#define OP_Gt                           31
+#define OP_Ge                           32
+#define OP_StrEq                        33
+#define OP_StrNe                        34
+#define OP_StrLt                        35
+#define OP_StrLe                        36
+#define OP_StrGt                        37
+#define OP_StrGe                        38
+#define OP_And                          39
+#define OP_Or                           40
+#define OP_Negative                     41
+#define OP_AbsValue                     42
+#define OP_Not                          43
+#define OP_BitNot                       44
+#define OP_Noop                         45
+#define OP_If                           46
+#define OP_IfNot                        47
+#define OP_IsNull                       48
+#define OP_NotNull                      49
+#define OP_MakeRecord                   50
+#define OP_MakeIdxKey                   51
+#define OP_MakeKey                      52
+#define OP_IncrKey                      53
+#define OP_Checkpoint                   54
+#define OP_Transaction                  55
+#define OP_Commit                       56
+#define OP_Rollback                     57
+#define OP_ReadCookie                   58
+#define OP_SetCookie                    59
+#define OP_VerifyCookie                 60
+#define OP_OpenAux                      61
+#define OP_OpenWrAux                    62
+#define OP_OpenWrite                    63
+#define OP_Open                         64
+#define OP_OpenTemp                     65
+#define OP_RenameCursor                 66
+#define OP_Close                        67
+#define OP_MoveLt                       68
+#define OP_MoveTo                       69
+#define OP_Distinct                     70
+#define OP_NotFound                     71
+#define OP_Found                        72
+#define OP_IsUnique                     73
+#define OP_NotExists                    74
+#define OP_NewRecno                     75
+#define OP_PutIntKey                    76
+#define OP_PutStrKey                    77
+#define OP_Delete                       78
+#define OP_KeyAsData                    79
+#define OP_Column                       80
+#define OP_Recno                        81
+#define OP_FullKey                      82
+#define OP_NullRow                      83
+#define OP_Last                         84
+#define OP_Rewind                       85
+#define OP_Prev                         86
+#define OP_Next                         87
+#define OP_IdxPut                       88
+#define OP_IdxDelete                    89
+#define OP_IdxRecno                     90
+#define OP_IdxLT                        91
+#define OP_IdxGT                        92
+#define OP_IdxGE                        93
+#define OP_Destroy                      94
+#define OP_Clear                        95
+#define OP_CreateIndex                  96
+#define OP_CreateTable                  97
+#define OP_IntegrityCk                  98
+#define OP_ListWrite                    99
+#define OP_ListRewind                  100
+#define OP_ListRead                    101
+#define OP_ListReset                   102
+#define OP_ListPush                    103
+#define OP_ListPop                     104
+#define OP_SortPut                     105
+#define OP_SortMakeRec                 106
+#define OP_SortMakeKey                 107
+#define OP_Sort                        108
+#define OP_SortNext                    109
+#define OP_SortCallback                110
+#define OP_SortReset                   111
+#define OP_FileOpen                    112
+#define OP_FileRead                    113
+#define OP_FileColumn                  114
+#define OP_MemStore                    115
+#define OP_MemLoad                     116
+#define OP_MemIncr                     117
+#define OP_AggReset                    118
+#define OP_AggInit                     119
+#define OP_AggFunc                     120
+#define OP_AggFocus                    121
+#define OP_AggSet                      122
+#define OP_AggGet                      123
+#define OP_AggNext                     124
+#define OP_SetInsert                   125
+#define OP_SetFound                    126
+#define OP_SetNotFound                 127
+#define OP_SetFirst                    128
+#define OP_SetNext                     129
diff --git a/ext/sqlite/libsqlite/src/os.c b/ext/sqlite/libsqlite/src/os.c
new file mode 100644 (file)
index 0000000..d0b50dc
--- /dev/null
@@ -0,0 +1,1477 @@
+/*
+** 2001 September 16
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains code that is specific to particular operating
+** systems.  The purpose of this file is to provide a uniform abstraction
+** on which the rest of SQLite can operate.
+*/
+#include "os.h"          /* Must be first to enable large file support */
+#include "sqliteInt.h"
+
+#if OS_UNIX
+# include <time.h>
+# include <errno.h>
+# include <unistd.h>
+# ifndef O_LARGEFILE
+#  define O_LARGEFILE 0
+# endif
+# ifdef SQLITE_DISABLE_LFS
+#  undef O_LARGEFILE
+#  define O_LARGEFILE 0
+# endif
+# ifndef O_NOFOLLOW
+#  define O_NOFOLLOW 0
+# endif
+#endif
+
+#if OS_WIN
+# include <winbase.h>
+#endif
+
+#if OS_MAC
+# include <extras.h>
+# include <path2fss.h>
+# include <TextUtils.h>
+# include <FinderRegistry.h>
+# include <Folders.h>
+# include <Timer.h>
+# include <OSUtils.h>
+#endif
+
+/*
+** Macros for performance tracing.  Normally turned off
+*/
+#if 0
+static int last_page = 0;
+__inline__ unsigned long long int hwtime(void){
+  unsigned long long int x;
+  __asm__("rdtsc\n\t"
+          "mov %%edx, %%ecx\n\t"
+          :"=A" (x));
+  return x;
+}
+static unsigned long long int g_start;
+static unsigned int elapse;
+#define TIMER_START       g_start=hwtime()
+#define TIMER_END         elapse=hwtime()-g_start
+#define SEEK(X)           last_page=(X)
+#define TRACE1(X)         fprintf(stderr,X)
+#define TRACE2(X,Y)       fprintf(stderr,X,Y)
+#define TRACE3(X,Y,Z)     fprintf(stderr,X,Y,Z)
+#define TRACE4(X,Y,Z,A)   fprintf(stderr,X,Y,Z,A)
+#define TRACE5(X,Y,Z,A,B) fprintf(stderr,X,Y,Z,A,B)
+#else
+#define TIMER_START
+#define TIMER_END
+#define SEEK(X)
+#define TRACE1(X)
+#define TRACE2(X,Y)
+#define TRACE3(X,Y,Z)
+#define TRACE4(X,Y,Z,A)
+#define TRACE5(X,Y,Z,A,B)
+#endif
+
+
+#if OS_UNIX
+/*
+** Here is the dirt on POSIX advisory locks:  ANSI STD 1003.1 (1996)
+** section 6.5.2.2 lines 483 through 490 specify that when a process
+** sets or clears a lock, that operation overrides any prior locks set
+** by the same process.  It does not explicitly say so, but this implies
+** that it overrides locks set by the same process using a different
+** file descriptor.  Consider this test case:
+**
+**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
+**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
+**
+** Suppose ./file1 and ./file2 are really be the same file (because
+** one is a hard or symbolic link to the other) then if you set
+** an exclusive lock on fd1, then try to get an exclusive lock
+** on fd2, it works.  I would have expected the second lock to
+** fail since there was already a lock on the file due to fd1.
+** But not so.  Since both locks came from the same process, the
+** second overrides the first, even though they were on different
+** file descriptors opened on different file names.
+**
+** Bummer.  If you ask me, this is broken.  Badly broken.  It means
+** that we cannot use POSIX locks to synchronize file access among
+** competing threads of the same process.  POSIX locks will work fine
+** to synchronize access for threads in separate processes, but not
+** threads within the same process.
+**
+** To work around the problem, SQLite has to manage file locks internally
+** on its own.  Whenever a new database is opened, we have to find the
+** specific inode of the database file (the inode is determined by the
+** st_dev and st_ino fields of the stat structure that fstat() fills in)
+** and check for locks already existing on that inode.  When locks are
+** created or removed, we have to look at our own internal record of the
+** locks to see if another thread has previously set a lock on that same
+** inode.
+**
+** The OsFile structure for POSIX is no longer just an integer file
+** descriptor.  It is now a structure that holds the integer file
+** descriptor and a pointer to a structure that describes the internal
+** locks on the corresponding inode.  There is one locking structure
+** per inode, so if the same inode is opened twice, both OsFile structures
+** point to the same locking structure.  The locking structure keeps
+** a reference count (so we will know when to delete it) and a "cnt"
+** field that tells us its internal lock status.  cnt==0 means the
+** file is unlocked.  cnt==-1 means the file has an exclusive lock.
+** cnt>0 means there are cnt shared locks on the file.
+**
+** Any attempt to lock or unlock a file first checks the locking
+** structure.  The fcntl() system call is only invoked to set a 
+** POSIX lock if the internal lock structure transitions between
+** a locked and an unlocked state.
+*/
+
+/*
+** An instance of the following structure serves as the key used
+** to locate a particular lockInfo structure given its inode. 
+*/
+struct inodeKey {
+  dev_t dev;   /* Device number */
+  ino_t ino;   /* Inode number */
+};
+
+/*
+** An instance of the following structure is allocated for each inode.
+** A single inode can have multiple file descriptors, so each OsFile
+** structure contains a pointer to an instance of this object and this
+** object keeps a count of the number of OsFiles pointing to it.
+*/
+struct lockInfo {
+  struct inodeKey key;  /* The lookup key */
+  int cnt;              /* 0: unlocked.  -1: write lock.  1...: read lock. */
+  int nRef;             /* Number of pointers to this structure */
+};
+
+/* 
+** This hash table maps inodes (in the form of inodeKey structures) into
+** pointers to lockInfo structures.
+*/
+static Hash lockHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
+
+/*
+** Given a file descriptor, locate a lockInfo structure that describes
+** that file descriptor.  Create a new one if necessary.  NULL might
+** be returned if malloc() fails.
+*/
+static struct lockInfo *findLockInfo(int fd){
+  int rc;
+  struct inodeKey key;
+  struct stat statbuf;
+  struct lockInfo *pInfo;
+  rc = fstat(fd, &statbuf);
+  if( rc!=0 ) return 0;
+  memset(&key, 0, sizeof(key));
+  key.dev = statbuf.st_dev;
+  key.ino = statbuf.st_ino;
+  pInfo = (struct lockInfo*)sqliteHashFind(&lockHash, &key, sizeof(key));
+  if( pInfo==0 ){
+    struct lockInfo *pOld;
+    pInfo = sqliteMalloc( sizeof(*pInfo) );
+    if( pInfo==0 ) return 0;
+    pInfo->key = key;
+    pInfo->nRef = 1;
+    pInfo->cnt = 0;
+    pOld = sqliteHashInsert(&lockHash, &pInfo->key, sizeof(key), pInfo);
+    if( pOld!=0 ){
+      assert( pOld==pInfo );
+      sqliteFree(pInfo);
+      pInfo = 0;
+    }
+  }else{
+    pInfo->nRef++;
+  }
+  return pInfo;
+}
+
+/*
+** Release a lockInfo structure previously allocated by findLockInfo().
+*/
+static void releaseLockInfo(struct lockInfo *pInfo){
+  pInfo->nRef--;
+  if( pInfo->nRef==0 ){
+    sqliteHashInsert(&lockHash, &pInfo->key, sizeof(pInfo->key), 0);
+    sqliteFree(pInfo);
+  }
+}
+#endif  /** POSIX advisory lock work-around **/
+
+/*
+** If we compile with the SQLITE_TEST macro set, then the following block
+** of code will give us the ability to simulate a disk I/O error.  This
+** is used for testing the I/O recovery logic.
+*/
+#ifdef SQLITE_TEST
+int sqlite_io_error_pending = 0;
+#define SimulateIOError(A)  \
+   if( sqlite_io_error_pending ) \
+     if( sqlite_io_error_pending-- == 1 ){ local_ioerr(); return A; }
+static void local_ioerr(){
+  sqlite_io_error_pending = 0;  /* Really just a place to set a breakpoint */
+}
+#else
+#define SimulateIOError(A)
+#endif
+
+/*
+** When testing, keep a count of the number of open files.
+*/
+#ifdef SQLITE_TEST
+int sqlite_open_file_count = 0;
+#define OpenCounter(X)  sqlite_open_file_count+=(X)
+#else
+#define OpenCounter(X)
+#endif
+
+
+/*
+** Delete the named file
+*/
+int sqliteOsDelete(const char *zFilename){
+#if OS_UNIX
+  unlink(zFilename);
+#endif
+#if OS_WIN
+  DeleteFile(zFilename);
+#endif
+#if OS_MAC
+  unlink(zFilename);
+#endif
+  return SQLITE_OK;
+}
+
+/*
+** Return TRUE if the named file exists.
+*/
+int sqliteOsFileExists(const char *zFilename){
+#if OS_UNIX
+  return access(zFilename, 0)==0;
+#endif
+#if OS_WIN
+  return GetFileAttributes(zFilename) != 0xffffffff;
+#endif
+#if OS_MAC
+  return access(zFilename, 0)==0;
+#endif
+}
+
+
+/*
+** Attempt to open a file for both reading and writing.  If that
+** fails, try opening it read-only.  If the file does not exist,
+** try to create it.
+**
+** On success, a handle for the open file is written to *id
+** and *pReadonly is set to 0 if the file was opened for reading and
+** writing or 1 if the file was opened read-only.  The function returns
+** SQLITE_OK.
+**
+** On failure, the function returns SQLITE_CANTOPEN and leaves
+** *id and *pReadonly unchanged.
+*/
+int sqliteOsOpenReadWrite(
+  const char *zFilename,
+  OsFile *id,
+  int *pReadonly
+){
+#if OS_UNIX
+  id->fd = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE, 0644);
+  if( id->fd<0 ){
+    id->fd = open(zFilename, O_RDONLY|O_LARGEFILE);
+    if( id->fd<0 ){
+      return SQLITE_CANTOPEN; 
+    }
+    *pReadonly = 1;
+  }else{
+    *pReadonly = 0;
+  }
+  sqliteOsEnterMutex();
+  id->pLock = findLockInfo(id->fd);
+  sqliteOsLeaveMutex();
+  if( id->pLock==0 ){
+    close(id->fd);
+    return SQLITE_NOMEM;
+  }
+  id->locked = 0;
+  TRACE3("OPEN    %-3d %s\n", id->fd, zFilename);
+  OpenCounter(+1);
+  return SQLITE_OK;
+#endif
+#if OS_WIN
+  HANDLE h = CreateFile(zFilename,
+     GENERIC_READ | GENERIC_WRITE,
+     FILE_SHARE_READ | FILE_SHARE_WRITE,
+     NULL,
+     OPEN_ALWAYS,
+     FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
+     NULL
+  );
+  if( h==INVALID_HANDLE_VALUE ){
+    h = CreateFile(zFilename,
+       GENERIC_READ,
+       FILE_SHARE_READ,
+       NULL,
+       OPEN_ALWAYS,
+       FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
+       NULL
+    );
+    if( h==INVALID_HANDLE_VALUE ){
+      return SQLITE_CANTOPEN;
+    }
+    *pReadonly = 1;
+  }else{
+    *pReadonly = 0;
+  }
+  id->h = h;
+  id->locked = 0;
+  OpenCounter(+1);
+  return SQLITE_OK;
+#endif
+#if OS_MAC
+  FSSpec fsSpec;
+# ifdef _LARGE_FILE
+  HFSUniStr255 dfName;
+  FSRef fsRef;
+  if( __path2fss(zFilename, &fsSpec) != noErr ){
+    if( HCreate(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, 'SQLI', cDocumentFile) != noErr )
+      return SQLITE_CANTOPEN;
+  }
+  if( FSpMakeFSRef(&fsSpec, &fsRef) != noErr )
+    return SQLITE_CANTOPEN;
+  FSGetDataForkName(&dfName);
+  if( FSOpenFork(&fsRef, dfName.length, dfName.unicode,
+                 fsRdWrShPerm, &(id->refNum)) != noErr ){
+    if( FSOpenFork(&fsRef, dfName.length, dfName.unicode,
+                   fsRdWrPerm, &(id->refNum)) != noErr ){
+      if (FSOpenFork(&fsRef, dfName.length, dfName.unicode,
+                   fsRdPerm, &(id->refNum)) != noErr )
+        return SQLITE_CANTOPEN;
+      else
+        *pReadonly = 1;
+    } else
+      *pReadonly = 0;
+  } else
+    *pReadonly = 0;
+# else
+  __path2fss(zFilename, &fsSpec);
+  if( !sqliteOsFileExists(zFilename) ){
+    if( HCreate(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, 'SQLI', cDocumentFile) != noErr )
+      return SQLITE_CANTOPEN;
+  }
+  if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrShPerm, &(id->refNum)) != noErr ){
+    if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrPerm, &(id->refNum)) != noErr ){
+      if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdPerm, &(id->refNum)) != noErr )
+        return SQLITE_CANTOPEN;
+      else
+        *pReadonly = 1;
+    } else
+      *pReadonly = 0;
+  } else
+    *pReadonly = 0;
+# endif
+  if( HOpenRF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrShPerm, &(id->refNumRF)) != noErr){
+    id->refNumRF = -1;
+  }
+  id->locked = 0;
+  id->delOnClose = 0;
+  OpenCounter(+1);
+  return SQLITE_OK;
+#endif
+}
+
+
+/*
+** Attempt to open a new file for exclusive access by this process.
+** The file will be opened for both reading and writing.  To avoid
+** a potential security problem, we do not allow the file to have
+** previously existed.  Nor do we allow the file to be a symbolic
+** link.
+**
+** If delFlag is true, then make arrangements to automatically delete
+** the file when it is closed.
+**
+** On success, write the file handle into *id and return SQLITE_OK.
+**
+** On failure, return SQLITE_CANTOPEN.
+*/
+int sqliteOsOpenExclusive(const char *zFilename, OsFile *id, int delFlag){
+#if OS_UNIX
+  if( access(zFilename, 0)==0 ){
+    return SQLITE_CANTOPEN;
+  }
+  id->fd = open(zFilename, O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE, 0600);
+  if( id->fd<0 ){
+    return SQLITE_CANTOPEN;
+  }
+  sqliteOsEnterMutex();
+  id->pLock = findLockInfo(id->fd);
+  sqliteOsLeaveMutex();
+  if( id->pLock==0 ){
+    close(id->fd);
+    unlink(zFilename);
+    return SQLITE_NOMEM;
+  }
+  id->locked = 0;
+  if( delFlag ){
+    unlink(zFilename);
+  }
+  TRACE3("OPEN-EX %-3d %s\n", id->fd, zFilename);
+  OpenCounter(+1);
+  return SQLITE_OK;
+#endif
+#if OS_WIN
+  HANDLE h;
+  int fileflags;
+  if( delFlag ){
+    fileflags = FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_RANDOM_ACCESS 
+                     | FILE_FLAG_DELETE_ON_CLOSE;
+  }else{
+    fileflags = FILE_FLAG_RANDOM_ACCESS;
+  }
+  h = CreateFile(zFilename,
+     GENERIC_READ | GENERIC_WRITE,
+     0,
+     NULL,
+     CREATE_ALWAYS,
+     fileflags,
+     NULL
+  );
+  if( h==INVALID_HANDLE_VALUE ){
+    return SQLITE_CANTOPEN;
+  }
+  id->h = h;
+  id->locked = 0;
+  OpenCounter(+1);
+  return SQLITE_OK;
+#endif
+#if OS_MAC
+  FSSpec fsSpec;
+# ifdef _LARGE_FILE
+  HFSUniStr255 dfName;
+  FSRef fsRef;
+  __path2fss(zFilename, &fsSpec);
+  if( HCreate(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, 'SQLI', cDocumentFile) != noErr )
+    return SQLITE_CANTOPEN;
+  if( FSpMakeFSRef(&fsSpec, &fsRef) != noErr )
+    return SQLITE_CANTOPEN;
+  FSGetDataForkName(&dfName);
+  if( FSOpenFork(&fsRef, dfName.length, dfName.unicode,
+                 fsRdWrPerm, &(id->refNum)) != noErr )
+    return SQLITE_CANTOPEN;
+# else
+  __path2fss(zFilename, &fsSpec);
+  if( HCreate(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, 'SQLI', cDocumentFile) != noErr )
+    return SQLITE_CANTOPEN;
+  if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrPerm, &(id->refNum)) != noErr )
+    return SQLITE_CANTOPEN;
+# endif
+  id->refNumRF = -1;
+  id->locked = 0;
+  id->delOnClose = delFlag;
+  if (delFlag)
+    id->pathToDel = sqliteOsFullPathname(zFilename);
+  OpenCounter(+1);
+  return SQLITE_OK;
+#endif
+}
+
+/*
+** Attempt to open a new file for read-only access.
+**
+** On success, write the file handle into *id and return SQLITE_OK.
+**
+** On failure, return SQLITE_CANTOPEN.
+*/
+int sqliteOsOpenReadOnly(const char *zFilename, OsFile *id){
+#if OS_UNIX
+  id->fd = open(zFilename, O_RDONLY|O_LARGEFILE);
+  if( id->fd<0 ){
+    return SQLITE_CANTOPEN;
+  }
+  sqliteOsEnterMutex();
+  id->pLock = findLockInfo(id->fd);
+  sqliteOsLeaveMutex();
+  if( id->pLock==0 ){
+    close(id->fd);
+    return SQLITE_NOMEM;
+  }
+  id->locked = 0;
+  TRACE3("OPEN-RO %-3d %s\n", id->fd, zFilename);
+  OpenCounter(+1);
+  return SQLITE_OK;
+#endif
+#if OS_WIN
+  HANDLE h = CreateFile(zFilename,
+     GENERIC_READ,
+     0,
+     NULL,
+     OPEN_EXISTING,
+     FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
+     NULL
+  );
+  if( h==INVALID_HANDLE_VALUE ){
+    return SQLITE_CANTOPEN;
+  }
+  id->h = h;
+  id->locked = 0;
+  OpenCounter(+1);
+  return SQLITE_OK;
+#endif
+#if OS_MAC
+  FSSpec fsSpec;
+# ifdef _LARGE_FILE
+  HFSUniStr255 dfName;
+  FSRef fsRef;
+  if( __path2fss(zFilename, &fsSpec) != noErr )
+    return SQLITE_CANTOPEN;
+  if( FSpMakeFSRef(&fsSpec, &fsRef) != noErr )
+    return SQLITE_CANTOPEN;
+  FSGetDataForkName(&dfName);
+  if( FSOpenFork(&fsRef, dfName.length, dfName.unicode,
+                 fsRdPerm, &(id->refNum)) != noErr )
+    return SQLITE_CANTOPEN;
+# else
+  __path2fss(zFilename, &fsSpec);
+  if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdPerm, &(id->refNum)) != noErr )
+    return SQLITE_CANTOPEN;
+# endif
+  if( HOpenRF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrShPerm, &(id->refNumRF)) != noErr){
+    id->refNumRF = -1;
+  }
+  id->locked = 0;
+  id->delOnClose = 0;
+  OpenCounter(+1);
+  return SQLITE_OK;
+#endif
+}
+
+/*
+** Create a temporary file name in zBuf.  zBuf must be big enough to
+** hold at least SQLITE_TEMPNAME_SIZE characters.
+*/
+int sqliteOsTempFileName(char *zBuf){
+#if OS_UNIX
+  static const char *azDirs[] = {
+     "/var/tmp",
+     "/usr/tmp",
+     "/tmp",
+     ".",
+  };
+  static char zChars[] =
+    "abcdefghijklmnopqrstuvwxyz"
+    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+    "0123456789";
+  int i, j;
+  struct stat buf;
+  const char *zDir = ".";
+  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
+    if( stat(azDirs[i], &buf) ) continue;
+    if( !S_ISDIR(buf.st_mode) ) continue;
+    if( access(azDirs[i], 07) ) continue;
+    zDir = azDirs[i];
+    break;
+  }
+  do{
+    sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
+    j = strlen(zBuf);
+    for(i=0; i<15; i++){
+      int n = sqliteRandomByte() % (sizeof(zChars)-1);
+      zBuf[j++] = zChars[n];
+    }
+    zBuf[j] = 0;
+  }while( access(zBuf,0)==0 );
+#endif
+#if OS_WIN
+  static char zChars[] =
+    "abcdefghijklmnopqrstuvwxyz"
+    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+    "0123456789";
+  int i, j;
+  char zTempPath[SQLITE_TEMPNAME_SIZE];
+  GetTempPath(SQLITE_TEMPNAME_SIZE-30, zTempPath);
+  for(i=strlen(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
+  zTempPath[i] = 0;
+  for(;;){
+    sprintf(zBuf, "%s\\"TEMP_FILE_PREFIX, zTempPath);
+    j = strlen(zBuf);
+    for(i=0; i<15; i++){
+      int n = sqliteRandomByte() % sizeof(zChars);
+      zBuf[j++] = zChars[n];
+    }
+    zBuf[j] = 0;
+    if( !sqliteOsFileExists(zBuf) ) break;
+  }
+#endif
+#if OS_MAC
+  static char zChars[] =
+    "abcdefghijklmnopqrstuvwxyz"
+    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+    "0123456789";
+  int i, j;
+  char zTempPath[SQLITE_TEMPNAME_SIZE];
+  char zdirName[32];
+  CInfoPBRec infoRec;
+  Str31 dirName;
+  memset(&infoRec, 0, sizeof(infoRec));
+  memset(zTempPath, 0, SQLITE_TEMPNAME_SIZE);
+  if( FindFolder(kOnSystemDisk, kTemporaryFolderType,  kCreateFolder,
+       &(infoRec.dirInfo.ioVRefNum), &(infoRec.dirInfo.ioDrParID)) == noErr ){
+    infoRec.dirInfo.ioNamePtr = dirName;
+    do{
+      infoRec.dirInfo.ioFDirIndex = -1;
+      infoRec.dirInfo.ioDrDirID = infoRec.dirInfo.ioDrParID;
+      if( PBGetCatInfoSync(&infoRec) == noErr ){
+        CopyPascalStringToC(dirName, zdirName);
+        i = strlen(zdirName);
+        memmove(&(zTempPath[i+1]), zTempPath, strlen(zTempPath));
+        strcpy(zTempPath, zdirName);
+        zTempPath[i] = ':';
+      }else{
+        *zTempPath = 0;
+        break;
+      }
+    } while( infoRec.dirInfo.ioDrDirID != fsRtDirID );
+  }
+  if( *zTempPath == 0 )
+    getcwd(zTempPath, SQLITE_TEMPNAME_SIZE-24);
+  for(;;){
+    sprintf(zBuf, "%s"TEMP_FILE_PREFIX, zTempPath);
+    j = strlen(zBuf);
+    for(i=0; i<15; i++){
+      int n = sqliteRandomByte() % sizeof(zChars);
+      zBuf[j++] = zChars[n];
+    }
+    zBuf[j] = 0;
+    if( !sqliteOsFileExists(zBuf) ) break;
+  }
+#endif
+  return SQLITE_OK; 
+}
+
+/*
+** Close a file
+*/
+int sqliteOsClose(OsFile *id){
+#if OS_UNIX
+  close(id->fd);
+  sqliteOsEnterMutex();
+  releaseLockInfo(id->pLock);
+  sqliteOsLeaveMutex();
+  TRACE2("CLOSE   %-3d\n", id->fd);
+  OpenCounter(-1);
+  return SQLITE_OK;
+#endif
+#if OS_WIN
+  CloseHandle(id->h);
+  OpenCounter(-1);
+  return SQLITE_OK;
+#endif
+#if OS_MAC
+  if( id->refNumRF!=-1 )
+    FSClose(id->refNumRF);
+# ifdef _LARGE_FILE
+  FSCloseFork(id->refNum);
+# else
+  FSClose(id->refNum);
+# endif
+  if( id->delOnClose ){
+    unlink(id->pathToDel);
+    sqliteFree(id->pathToDel);
+  }
+  OpenCounter(-1);
+  return SQLITE_OK;
+#endif
+}
+
+/*
+** Read data from a file into a buffer.  Return SQLITE_OK if all
+** bytes were read successfully and SQLITE_IOERR if anything goes
+** wrong.
+*/
+int sqliteOsRead(OsFile *id, void *pBuf, int amt){
+#if OS_UNIX
+  int got;
+  SimulateIOError(SQLITE_IOERR);
+  TIMER_START;
+  got = read(id->fd, pBuf, amt);
+  TIMER_END;
+  TRACE4("READ    %-3d %7d %d\n", id->fd, last_page, elapse);
+  SEEK(0);
+  /* if( got<0 ) got = 0; */
+  if( got==amt ){
+    return SQLITE_OK;
+  }else{
+    return SQLITE_IOERR;
+  }
+#endif
+#if OS_WIN
+  DWORD got;
+  SimulateIOError(SQLITE_IOERR);
+  TRACE2("READ %d\n", last_page);
+  if( !ReadFile(id->h, pBuf, amt, &got, 0) ){
+    got = 0;
+  }
+  if( got==(DWORD)amt ){
+    return SQLITE_OK;
+  }else{
+    return SQLITE_IOERR;
+  }
+#endif
+#if OS_MAC
+  int got;
+  SimulateIOError(SQLITE_IOERR);
+  TRACE2("READ %d\n", last_page);
+# ifdef _LARGE_FILE
+  FSReadFork(id->refNum, fsAtMark, 0, (ByteCount)amt, pBuf, (ByteCount*)&got);
+# else
+  got = amt;
+  FSRead(id->refNum, &got, pBuf);
+# endif
+  if( got==amt ){
+    return SQLITE_OK;
+  }else{
+    return SQLITE_IOERR;
+  }
+#endif
+}
+
+/*
+** Write data from a buffer into a file.  Return SQLITE_OK on success
+** or some other error code on failure.
+*/
+int sqliteOsWrite(OsFile *id, const void *pBuf, int amt){
+#if OS_UNIX
+  int wrote = 0;
+  SimulateIOError(SQLITE_IOERR);
+  TIMER_START;
+  while( amt>0 && (wrote = write(id->fd, pBuf, amt))>0 ){
+    amt -= wrote;
+    pBuf = &((char*)pBuf)[wrote];
+  }
+  TIMER_END;
+  TRACE4("WRITE   %-3d %7d %d\n", id->fd, last_page, elapse);
+  SEEK(0);
+  if( amt>0 ){
+    return SQLITE_FULL;
+  }
+  return SQLITE_OK;
+#endif
+#if OS_WIN
+  int rc;
+  DWORD wrote;
+  SimulateIOError(SQLITE_IOERR);
+  TRACE2("WRITE %d\n", last_page);
+  while( amt>0 && (rc = WriteFile(id->h, pBuf, amt, &wrote, 0))!=0 && wrote>0 ){
+    amt -= wrote;
+    pBuf = &((char*)pBuf)[wrote];
+  }
+  if( !rc || amt>(int)wrote ){
+    return SQLITE_FULL;
+  }
+  return SQLITE_OK;
+#endif
+#if OS_MAC
+  OSErr oserr;
+  int wrote = 0;
+  SimulateIOError(SQLITE_IOERR);
+  TRACE2("WRITE %d\n", last_page);
+  while( amt>0 ){
+# ifdef _LARGE_FILE
+    oserr = FSWriteFork(id->refNum, fsAtMark, 0,
+                        (ByteCount)amt, pBuf, (ByteCount*)&wrote);
+# else
+    wrote = amt;
+    oserr = FSWrite(id->refNum, &wrote, pBuf);
+# endif
+    if( wrote == 0 || oserr != noErr)
+      break;
+    amt -= wrote;
+    pBuf = &((char*)pBuf)[wrote];
+  }
+  if( oserr != noErr || amt>wrote ){
+    return SQLITE_FULL;
+  }
+  return SQLITE_OK;
+#endif
+}
+
+/*
+** Move the read/write pointer in a file.
+*/
+int sqliteOsSeek(OsFile *id, off_t offset){
+  SEEK(offset/1024 + 1);
+#if OS_UNIX
+  lseek(id->fd, offset, SEEK_SET);
+  return SQLITE_OK;
+#endif
+#if OS_WIN
+  {
+    LONG upperBits = offset>>32;
+    LONG lowerBits = offset & 0xffffffff;
+    DWORD rc;
+    rc = SetFilePointer(id->h, lowerBits, &upperBits, FILE_BEGIN);
+    /* TRACE3("SEEK rc=0x%x upper=0x%x\n", rc, upperBits); */
+  }
+  return SQLITE_OK;
+#endif
+#if OS_MAC
+  {
+    off_t curSize;
+    if( sqliteOsFileSize(id, &curSize) != SQLITE_OK ){
+      return SQLITE_IOERR;
+    }
+    if( offset >= curSize ){
+      if( sqliteOsTruncate(id, offset+1) != SQLITE_OK ){
+        return SQLITE_IOERR;
+      }
+    }
+# ifdef _LARGE_FILE
+    if( FSSetForkPosition(id->refNum, fsFromStart, offset) != noErr ){
+# else
+    if( SetFPos(id->refNum, fsFromStart, offset) != noErr ){
+# endif
+      return SQLITE_IOERR;
+    }else{
+      return SQLITE_OK;
+    }
+  }
+#endif
+}
+
+/*
+** Make sure all writes to a particular file are committed to disk.
+*/
+int sqliteOsSync(OsFile *id){
+#if OS_UNIX
+  SimulateIOError(SQLITE_IOERR);
+  TRACE2("SYNC    %-3d\n", id->fd);
+  if( fsync(id->fd) ){
+    return SQLITE_IOERR;
+  }else{
+    return SQLITE_OK;
+  }
+#endif
+#if OS_WIN
+  if( FlushFileBuffers(id->h) ){
+    return SQLITE_OK;
+  }else{
+    return SQLITE_IOERR;
+  }
+#endif
+#if OS_MAC
+# ifdef _LARGE_FILE
+  if( FSFlushFork(id->refNum) != noErr ){
+# else
+  ParamBlockRec params;
+  memset(&params, 0, sizeof(ParamBlockRec));
+  params.ioParam.ioRefNum = id->refNum;
+  if( PBFlushFileSync(&params) != noErr ){
+# endif
+    return SQLITE_IOERR;
+  }else{
+    return SQLITE_OK;
+  }
+#endif
+}
+
+/*
+** Truncate an open file to a specified size
+*/
+int sqliteOsTruncate(OsFile *id, off_t nByte){
+  SimulateIOError(SQLITE_IOERR);
+#if OS_UNIX
+  return ftruncate(id->fd, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
+#endif
+#if OS_WIN
+  {
+    LONG upperBits = nByte>>32;
+    SetFilePointer(id->h, nByte, &upperBits, FILE_BEGIN);
+    SetEndOfFile(id->h);
+  }
+  return SQLITE_OK;
+#endif
+#if OS_MAC
+# ifdef _LARGE_FILE
+  if( FSSetForkSize(id->refNum, fsFromStart, nByte) != noErr){
+# else
+  if( SetEOF(id->refNum, nByte) != noErr ){
+# endif
+    return SQLITE_IOERR;
+  }else{
+    return SQLITE_OK;
+  }
+#endif
+}
+
+/*
+** Determine the current size of a file in bytes
+*/
+int sqliteOsFileSize(OsFile *id, off_t *pSize){
+#if OS_UNIX
+  struct stat buf;
+  SimulateIOError(SQLITE_IOERR);
+  if( fstat(id->fd, &buf)!=0 ){
+    return SQLITE_IOERR;
+  }
+  *pSize = buf.st_size;
+  return SQLITE_OK;
+#endif
+#if OS_WIN
+  DWORD upperBits, lowerBits;
+  SimulateIOError(SQLITE_IOERR);
+  lowerBits = GetFileSize(id->h, &upperBits);
+  *pSize = (((off_t)upperBits)<<32) + lowerBits;
+  return SQLITE_OK;
+#endif
+#if OS_MAC
+# ifdef _LARGE_FILE
+  if( FSGetForkSize(id->refNum, pSize) != noErr){
+# else
+  if( GetEOF(id->refNum, pSize) != noErr ){
+# endif
+    return SQLITE_IOERR;
+  }else{
+    return SQLITE_OK;
+  }
+#endif
+}
+
+#if OS_WIN
+/*
+** Return true (non-zero) if we are running under WinNT, Win2K or WinXP.
+** Return false (zero) for Win95, Win98, or WinME.
+*/
+int isNT(void){
+  static osType = 0;   /* 0=unknown 1=win95 2=winNT */
+  if( osType==0 ){
+    OSVERSIONINFO sInfo;
+    sInfo.dwOSVersionInfoSize = sizeof(sInfo);
+    GetVersionEx(&sInfo);
+    osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
+  }
+  return osType==2;
+}
+#endif
+
+/*
+** Windows file locking notes:  [the same/equivalent applies to MacOS]
+**
+** We cannot use LockFileEx() or UnlockFileEx() because those functions
+** are not available under Win95/98/ME.  So we use only LockFile() and
+** UnlockFile().
+**
+** LockFile() prevents not just writing but also reading by other processes.
+** (This is a design error on the part of Windows, but there is nothing
+** we can do about that.)  So the region used for locking is at the
+** end of the file where it is unlikely to ever interfere with an
+** actual read attempt.
+**
+** A database read lock is obtained by locking a single randomly-chosen 
+** byte out of a specific range of bytes. The lock byte is obtained at 
+** random so two separate readers can probably access the file at the 
+** same time, unless they are unlucky and choose the same lock byte.
+** A database write lock is obtained by locking all bytes in the range.
+** There can only be one writer.
+**
+** A lock is obtained on the first byte of the lock range before acquiring
+** either a read lock or a write lock.  This prevents two processes from
+** attempting to get a lock at a same time.  The semantics of 
+** sqliteOsReadLock() require that if there is already a write lock, that
+** lock is converted into a read lock atomically.  The lock on the first
+** byte allows us to drop the old write lock and get the read lock without
+** another process jumping into the middle and messing us up.  The same
+** argument applies to sqliteOsWriteLock().
+**
+** Note: On MacOS we use the resource fork for locking.
+**
+** The following #defines specify the range of bytes used for locking.
+** N_LOCKBYTE is the number of bytes available for doing the locking.
+** The first byte used to hold the lock while the lock is changing does
+** not count toward this number.  FIRST_LOCKBYTE is the address of
+** the first byte in the range of bytes used for locking.
+*/
+#define N_LOCKBYTE       10239
+#if OS_MAC
+# define FIRST_LOCKBYTE   (0x000fffff - N_LOCKBYTE)
+#else
+# define FIRST_LOCKBYTE   (0xffffffff - N_LOCKBYTE)
+#endif
+
+/*
+** Change the status of the lock on the file "id" to be a readlock.
+** If the file was write locked, then this reduces the lock to a read.
+** If the file was read locked, then this acquires a new read lock.
+**
+** Return SQLITE_OK on success and SQLITE_BUSY on failure.  If this
+** library was compiled with large file support (LFS) but LFS is not
+** available on the host, then an SQLITE_NOLFS is returned.
+*/
+int sqliteOsReadLock(OsFile *id){
+#if OS_UNIX
+  int rc;
+  sqliteOsEnterMutex();
+  if( id->pLock->cnt>0 ){
+    if( !id->locked ){
+      id->pLock->cnt++;
+      id->locked = 1;
+    }
+    rc = SQLITE_OK;
+  }else if( id->locked || id->pLock->cnt==0 ){
+    struct flock lock;
+    int s;
+    lock.l_type = F_RDLCK;
+    lock.l_whence = SEEK_SET;
+    lock.l_start = lock.l_len = 0L;
+    s = fcntl(id->fd, F_SETLK, &lock);
+    if( s!=0 ){
+      rc = (s==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
+    }else{
+      rc = SQLITE_OK;
+      id->pLock->cnt = 1;
+      id->locked = 1;
+    }
+  }else{
+    rc = SQLITE_BUSY;
+  }
+  sqliteOsLeaveMutex();
+  return rc;
+#endif
+#if OS_WIN
+  int rc;
+  if( id->locked>0 ){
+    rc = SQLITE_OK;
+  }else{
+    int lk = (sqliteRandomInteger() & 0x7ffffff)%N_LOCKBYTE+1;
+    int res;
+    int cnt = 100;
+    int page = isNT() ? 0xffffffff : 0;
+    while( cnt-->0 && (res = LockFile(id->h, FIRST_LOCKBYTE, page, 1, 0))==0 ){
+      Sleep(1);
+    }
+    if( res ){
+      UnlockFile(id->h, FIRST_LOCKBYTE+1, page, N_LOCKBYTE, 0);
+      res = LockFile(id->h, FIRST_LOCKBYTE+lk, page, 1, 0);
+      UnlockFile(id->h, FIRST_LOCKBYTE, page, 1, 0);
+    }
+    if( res ){
+      id->locked = lk;
+      rc = SQLITE_OK;
+    }else{
+      rc = SQLITE_BUSY;
+    }
+  }
+  return rc;
+#endif
+#if OS_MAC
+  int rc;
+  if( id->locked>0 || id->refNumRF == -1 ){
+    rc = SQLITE_OK;
+  }else{
+    int lk = (sqliteRandomInteger() & 0x7ffffff)%N_LOCKBYTE+1;
+    OSErr res;
+    int cnt = 5;
+    ParamBlockRec params;
+    memset(&params, 0, sizeof(params));
+    params.ioParam.ioRefNum = id->refNumRF;
+    params.ioParam.ioPosMode = fsFromStart;
+    params.ioParam.ioPosOffset = FIRST_LOCKBYTE;
+    params.ioParam.ioReqCount = 1;
+    while( cnt-->0 && (res = PBLockRangeSync(&params))!=noErr ){
+      UInt32 finalTicks;
+      Delay(1, &finalTicks); /* 1/60 sec */
+    }
+    if( res == noErr ){
+      params.ioParam.ioPosOffset = FIRST_LOCKBYTE+1;
+      params.ioParam.ioReqCount = N_LOCKBYTE;
+      PBUnlockRangeSync(&params);
+      params.ioParam.ioPosOffset = FIRST_LOCKBYTE+lk;
+      params.ioParam.ioReqCount = 1;
+      res = PBLockRangeSync(&params);
+      params.ioParam.ioPosOffset = FIRST_LOCKBYTE;
+      params.ioParam.ioReqCount = 1;
+      PBUnlockRangeSync(&params);
+    }
+    if( res == noErr ){
+      id->locked = lk;
+      rc = SQLITE_OK;
+    }else{
+      rc = SQLITE_BUSY;
+    }
+  }
+  return rc;
+#endif
+}
+
+/*
+** Change the lock status to be an exclusive or write lock.  Return
+** SQLITE_OK on success and SQLITE_BUSY on a failure.  If this
+** library was compiled with large file support (LFS) but LFS is not
+** available on the host, then an SQLITE_NOLFS is returned.
+*/
+int sqliteOsWriteLock(OsFile *id){
+#if OS_UNIX
+  int rc;
+  sqliteOsEnterMutex();
+  if( id->pLock->cnt==0 || (id->pLock->cnt==1 && id->locked==1) ){
+    struct flock lock;
+    int s;
+    lock.l_type = F_WRLCK;
+    lock.l_whence = SEEK_SET;
+    lock.l_start = lock.l_len = 0L;
+    s = fcntl(id->fd, F_SETLK, &lock);
+    if( s!=0 ){
+      rc = (s==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
+    }else{
+      rc = SQLITE_OK;
+      id->pLock->cnt = -1;
+      id->locked = 1;
+    }
+  }else{
+    rc = SQLITE_BUSY;
+  }
+  sqliteOsLeaveMutex();
+  return rc;
+#endif
+#if OS_WIN
+  int rc;
+  if( id->locked<0 ){
+    rc = SQLITE_OK;
+  }else{
+    int res;
+    int cnt = 100;
+    int page = isNT() ? 0xffffffff : 0;
+    while( cnt-->0 && (res = LockFile(id->h, FIRST_LOCKBYTE, page, 1, 0))==0 ){
+      Sleep(1);
+    }
+    if( res ){
+      if( id->locked==0 
+            || UnlockFile(id->h, FIRST_LOCKBYTE + id->locked, page, 1, 0) ){
+        res = LockFile(id->h, FIRST_LOCKBYTE+1, page, N_LOCKBYTE, 0);
+      }else{
+        res = 0;
+      }
+      UnlockFile(id->h, FIRST_LOCKBYTE, page, 1, 0);
+    }
+    if( res ){
+      id->locked = -1;
+      rc = SQLITE_OK;
+    }else{
+      rc = SQLITE_BUSY;
+    }
+  }
+  return rc;
+#endif
+#if OS_MAC
+  int rc;
+  if( id->locked<0 || id->refNumRF == -1 ){
+    rc = SQLITE_OK;
+  }else{
+    OSErr res;
+    int cnt = 5;
+    ParamBlockRec params;
+    memset(&params, 0, sizeof(params));
+    params.ioParam.ioRefNum = id->refNumRF;
+    params.ioParam.ioPosMode = fsFromStart;
+    params.ioParam.ioPosOffset = FIRST_LOCKBYTE;
+    params.ioParam.ioReqCount = 1;
+    while( cnt-->0 && (res = PBLockRangeSync(&params))!=noErr ){
+      UInt32 finalTicks;
+      Delay(1, &finalTicks); /* 1/60 sec */
+    }
+    if( res == noErr ){
+      params.ioParam.ioPosOffset = FIRST_LOCKBYTE + id->locked;
+      params.ioParam.ioReqCount = 1;
+      if( id->locked==0 
+            || PBUnlockRangeSync(&params)==noErr ){
+        params.ioParam.ioPosOffset = FIRST_LOCKBYTE+1;
+        params.ioParam.ioReqCount = N_LOCKBYTE;
+        res = PBLockRangeSync(&params);
+      }else{
+        res = afpRangeNotLocked;
+      }
+      params.ioParam.ioPosOffset = FIRST_LOCKBYTE;
+      params.ioParam.ioReqCount = 1;
+      PBUnlockRangeSync(&params);
+    }
+    if( res == noErr ){
+      id->locked = -1;
+      rc = SQLITE_OK;
+    }else{
+      rc = SQLITE_BUSY;
+    }
+  }
+  return rc;
+#endif
+}
+
+/*
+** Unlock the given file descriptor.  If the file descriptor was
+** not previously locked, then this routine is a no-op.  If this
+** library was compiled with large file support (LFS) but LFS is not
+** available on the host, then an SQLITE_NOLFS is returned.
+*/
+int sqliteOsUnlock(OsFile *id){
+#if OS_UNIX
+  int rc;
+  if( !id->locked ) return SQLITE_OK;
+  sqliteOsEnterMutex();
+  assert( id->pLock->cnt!=0 );
+  if( id->pLock->cnt>1 ){
+    id->pLock->cnt--;
+    rc = SQLITE_OK;
+  }else{
+    struct flock lock;
+    int s;
+    lock.l_type = F_UNLCK;
+    lock.l_whence = SEEK_SET;
+    lock.l_start = lock.l_len = 0L;
+    s = fcntl(id->fd, F_SETLK, &lock);
+    if( s!=0 ){
+      rc = (s==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
+    }else{
+      rc = SQLITE_OK;
+      id->pLock->cnt = 0;
+    }
+  }
+  sqliteOsLeaveMutex();
+  id->locked = 0;
+  return rc;
+#endif
+#if OS_WIN
+  int rc;
+  int page = isNT() ? 0xffffffff : 0;
+  if( id->locked==0 ){
+    rc = SQLITE_OK;
+  }else if( id->locked<0 ){
+    UnlockFile(id->h, FIRST_LOCKBYTE+1, page, N_LOCKBYTE, 0);
+    rc = SQLITE_OK;
+    id->locked = 0;
+  }else{
+    UnlockFile(id->h, FIRST_LOCKBYTE+id->locked, page, 1, 0);
+    rc = SQLITE_OK;
+    id->locked = 0;
+  }
+  return rc;
+#endif
+#if OS_MAC
+  int rc;
+  ParamBlockRec params;
+  memset(&params, 0, sizeof(params));
+  params.ioParam.ioRefNum = id->refNumRF;
+  params.ioParam.ioPosMode = fsFromStart;
+  if( id->locked==0 || id->refNumRF == -1 ){
+    rc = SQLITE_OK;
+  }else if( id->locked<0 ){
+    params.ioParam.ioPosOffset = FIRST_LOCKBYTE+1;
+    params.ioParam.ioReqCount = N_LOCKBYTE;
+    PBUnlockRangeSync(&params);
+    rc = SQLITE_OK;
+    id->locked = 0;
+  }else{
+    params.ioParam.ioPosOffset = FIRST_LOCKBYTE+id->locked;
+    params.ioParam.ioReqCount = 1;
+    PBUnlockRangeSync(&params);
+    rc = SQLITE_OK;
+    id->locked = 0;
+  }
+  return rc;
+#endif
+}
+
+/*
+** Get information to seed the random number generator.  The seed
+** is written into the buffer zBuf[256].  The calling function must
+** supply a sufficiently large buffer.
+*/
+int sqliteOsRandomSeed(char *zBuf){
+#ifdef SQLITE_TEST
+  /* When testing, always use the same random number sequence.
+  ** This makes the tests repeatable.
+  */
+  memset(zBuf, 0, 256);
+#endif
+#if OS_UNIX && !defined(SQLITE_TEST)
+  int pid;
+  time((time_t*)zBuf);
+  pid = getpid();
+  memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
+#endif
+#if OS_WIN && !defined(SQLITE_TEST)
+  GetSystemTime((LPSYSTEMTIME)zBuf);
+#endif
+#if OS_MAC
+  int pid;
+  Microseconds((UnsignedWide*)zBuf);
+  pid = getpid();
+  memcpy(&zBuf[sizeof(UnsignedWide)], &pid, sizeof(pid));
+#endif
+  return SQLITE_OK;
+}
+
+/*
+** Sleep for a little while.  Return the amount of time slept.
+*/
+int sqliteOsSleep(int ms){
+#if OS_UNIX
+#if defined(HAVE_USLEEP) && HAVE_USLEEP
+  usleep(ms*1000);
+  return ms;
+#else
+  sleep((ms+999)/1000);
+  return 1000*((ms+999)/1000);
+#endif
+#endif
+#if OS_WIN
+  Sleep(ms);
+  return ms;
+#endif
+#if OS_MAC
+  UInt32 finalTicks;
+  UInt32 ticks = (((UInt32)ms+16)*3)/50;  /* 1/60 sec per tick */
+  Delay(ticks, &finalTicks);
+  return (int)((ticks*50)/3);
+#endif
+}
+
+/*
+** Macros used to determine whether or not to use threads.  The
+** SQLITE_UNIX_THREADS macro is defined if we are synchronizing for
+** Posix threads and SQLITE_W32_THREADS is defined if we are
+** synchronizing using Win32 threads.
+*/
+#if OS_UNIX && defined(THREADSAFE) && THREADSAFE
+# include <pthread.h>
+# define SQLITE_UNIX_THREADS 1
+#endif
+#if OS_WIN && defined(THREADSAFE) && THREADSAFE
+# define SQLITE_W32_THREADS 1
+#endif
+#if OS_MAC && defined(THREADSAFE) && THREADSAFE
+# include <Multiprocessing.h>
+# define SQLITE_MACOS_MULTITASKING 1
+#endif
+
+/*
+** Static variables used for thread synchronization
+*/
+static int inMutex = 0;
+#ifdef SQLITE_UNIX_THREADS
+  static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+#endif
+#ifdef SQLITE_W32_THREADS
+  static CRITICAL_SECTION cs;
+#endif
+#ifdef SQLITE_MACOS_MULTITASKING
+  static MPCriticalRegionID criticalRegion;
+#endif
+
+/*
+** The following pair of routine implement mutual exclusion for
+** multi-threaded processes.  Only a single thread is allowed to
+** executed code that is surrounded by EnterMutex() and LeaveMutex().
+**
+** SQLite uses only a single Mutex.  There is not much critical
+** code and what little there is executes quickly and without blocking.
+*/
+void sqliteOsEnterMutex(){
+#ifdef SQLITE_UNIX_THREADS
+  pthread_mutex_lock(&mutex);
+#endif
+#ifdef SQLITE_W32_THREADS
+  static int isInit = 0;
+  while( !isInit ){
+    static long lock = 0;
+    if( InterlockedIncrement(&lock)==1 ){
+      InitializeCriticalSection(&cs);
+      isInit = 1;
+    }else{
+      Sleep(1);
+    }
+  }
+  EnterCriticalSection(&cs);
+#endif
+#ifdef SQLITE_MACOS_MULTITASKING
+  static volatile int notInit = 1;
+  if( notInit ){
+    if( notInit == 2 ) /* as close as you can get to thread safe init */
+      MPYield();
+    else{
+      notInit = 2;
+      MPCreateCriticalRegion(&criticalRegion);
+      notInit = 0;
+    }
+  }
+  MPEnterCriticalRegion(criticalRegion, kDurationForever);
+#endif
+  assert( !inMutex );
+  inMutex = 1;
+}
+void sqliteOsLeaveMutex(){
+  assert( inMutex );
+  inMutex = 0;
+#ifdef SQLITE_UNIX_THREADS
+  pthread_mutex_unlock(&mutex);
+#endif
+#ifdef SQLITE_W32_THREADS
+  LeaveCriticalSection(&cs);
+#endif
+#ifdef SQLITE_MACOS_MULTITASKING
+  MPExitCriticalRegion(criticalRegion);
+#endif
+}
+
+/*
+** Turn a relative pathname into a full pathname.  Return a pointer
+** to the full pathname stored in space obtained from sqliteMalloc().
+** The calling function is responsible for freeing this space once it
+** is no longer needed.
+*/
+char *sqliteOsFullPathname(const char *zRelative){
+#if OS_UNIX
+  char *zFull = 0;
+  if( zRelative[0]=='/' ){
+    sqliteSetString(&zFull, zRelative, 0);
+  }else{
+    char zBuf[5000];
+    sqliteSetString(&zFull, getcwd(zBuf, sizeof(zBuf)), "/", zRelative, 0);
+  }
+  return zFull;
+#endif
+#if OS_WIN
+  char *zNotUsed;
+  char *zFull;
+  int nByte;
+  nByte = GetFullPathName(zRelative, 0, 0, &zNotUsed) + 1;
+  zFull = sqliteMalloc( nByte );
+  if( zFull==0 ) return 0;
+  GetFullPathName(zRelative, nByte, zFull, &zNotUsed);
+  return zFull;
+#endif
+#if OS_MAC
+  char *zFull = 0;
+  if( zRelative[0]==':' ){
+    char zBuf[_MAX_PATH+1];
+    sqliteSetString(&zFull, getcwd(zBuf, sizeof(zBuf)), &(zRelative[1]), 0);
+  }else{
+    if( strchr(zRelative, ':') ){
+      sqliteSetString(&zFull, zRelative, 0);
+    }else{
+    char zBuf[_MAX_PATH+1];
+      sqliteSetString(&zFull, getcwd(zBuf, sizeof(zBuf)), zRelative, 0);
+    }
+  }
+  return zFull;
+#endif
+}
diff --git a/ext/sqlite/libsqlite/src/os.h b/ext/sqlite/libsqlite/src/os.h
new file mode 100644 (file)
index 0000000..8491d90
--- /dev/null
@@ -0,0 +1,172 @@
+/*
+** 2001 September 16
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This header file (together with is companion C source-code file
+** "os.c") attempt to abstract the underlying operating system so that
+** the SQLite library will work on both POSIX and windows systems.
+*/
+#ifndef _SQLITE_OS_H_
+#define _SQLITE_OS_H_
+
+/*
+** These #defines should enable >2GB file support on Posix if the
+** underlying operating system supports it.  If the OS lacks
+** large file support, or if the OS is windows, these should be no-ops.
+**
+** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
+** on the compiler command line.  This is necessary if you are compiling
+** on a recent machine (ex: RedHat 7.2) but you want your code to work
+** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
+** without this option, LFS is enable.  But LFS does not exist in the kernel
+** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
+** portability you should omit LFS.
+**
+** Similar is true for MacOS.  LFS is only supported on MacOS 9 and later.
+*/
+#ifndef SQLITE_DISABLE_LFS
+# define _LARGE_FILE       1
+# define _FILE_OFFSET_BITS 64
+# define _LARGEFILE_SOURCE 1
+#endif
+
+/*
+** Temporary files are named starting with this prefix followed by 16 random
+** alphanumeric characters, and no file extension. They are stored in the
+** OS's standard temporary file directory, and are deleted prior to exit.
+** If sqlite is being embedded in another program, you may wish to change the
+** prefix to reflect your program's name, so that if your program exits
+** prematurely, old temporary files can be easily identified. This can be done
+** using -DTEMP_FILE_PREFIX=myprefix_ on the compiler command line.
+*/
+#ifndef TEMP_FILE_PREFIX
+# define TEMP_FILE_PREFIX "sqlite_"
+#endif
+
+/*
+** Figure out if we are dealing with Unix, Windows or MacOS.
+**
+** N.B. MacOS means Mac Classic (or Carbon). Treat Darwin (OS X) as Unix.
+**      The MacOS build is designed to use CodeWarrior (tested with v8)
+*/
+#ifndef OS_UNIX
+# ifndef OS_WIN
+#  ifndef OS_MAC
+#    if defined(__MACOS__)
+#      define OS_MAC 1
+#      define OS_WIN 0
+#      define OS_UNIX 0
+#    elif defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
+#      define OS_MAC 0
+#      define OS_WIN 1
+#      define OS_UNIX 0
+#    else
+#      define OS_MAC 0
+#      define OS_WIN 0
+#      define OS_UNIX 1
+#    endif
+#  else
+#    define OS_WIN 0
+#    define OS_UNIX 0
+#  endif
+# else
+#  define OS_MAC 0
+#  define OS_UNIX 0
+# endif
+#else
+# define OS_MAC 0
+# define OS_WIN 0
+#endif
+
+/*
+** A handle for an open file is stored in an OsFile object.
+*/
+#if OS_UNIX
+# include <sys/types.h>
+# include <sys/stat.h>
+# include <fcntl.h>
+# include <unistd.h>
+  typedef struct OsFile OsFile;
+  struct OsFile {
+    struct lockInfo *pLock;  /* Information about locks on this inode */
+    int fd;                  /* The file descriptor */
+    int locked;              /* True if this user holds the lock */
+  };
+# define SQLITE_TEMPNAME_SIZE 200
+# if defined(HAVE_USLEEP) && HAVE_USLEEP
+#  define SQLITE_MIN_SLEEP_MS 1
+# else
+#  define SQLITE_MIN_SLEEP_MS 1000
+# endif
+#endif
+
+#if OS_WIN
+#include <windows.h>
+#include <winbase.h>
+  typedef struct OsFile OsFile;
+  struct OsFile {
+    HANDLE h;               /* Handle for accessing the file */
+    int locked;             /* 0: unlocked, <0: write lock, >0: read lock */
+  };
+# if defined(_MSC_VER) || defined(__BORLANDC__)
+    typedef __int64 off_t;
+# else
+    typedef long long off_t;
+# endif
+# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
+# define SQLITE_MIN_SLEEP_MS 1
+#endif
+
+#if OS_MAC
+# include <unistd.h>
+# include <Files.h>
+  typedef struct OsFile OsFile;
+  struct OsFile {
+    SInt16 refNum;           /* Data fork/file reference number */
+    SInt16 refNumRF;         /* Resource fork reference number (for locking) */
+    int locked;              /* 0: unlocked, <0: write lock, >0: read lock */
+    int delOnClose;          /* True if file is to be deleted on close */
+    char *pathToDel;         /* Name of file to delete on close */
+  };
+# ifdef _LARGE_FILE
+    typedef SInt64 off_t;
+# else
+    typedef SInt32 off_t;
+# endif
+# define SQLITE_TEMPNAME_SIZE _MAX_PATH
+# define SQLITE_MIN_SLEEP_MS 17
+#endif
+
+int sqliteOsDelete(const char*);
+int sqliteOsFileExists(const char*);
+int sqliteOsOpenReadWrite(const char*, OsFile*, int*);
+int sqliteOsOpenExclusive(const char*, OsFile*, int);
+int sqliteOsOpenReadOnly(const char*, OsFile*);
+int sqliteOsTempFileName(char*);
+int sqliteOsClose(OsFile*);
+int sqliteOsRead(OsFile*, void*, int amt);
+int sqliteOsWrite(OsFile*, const void*, int amt);
+int sqliteOsSeek(OsFile*, off_t offset);
+int sqliteOsSync(OsFile*);
+int sqliteOsTruncate(OsFile*, off_t size);
+int sqliteOsFileSize(OsFile*, off_t *pSize);
+int sqliteOsReadLock(OsFile*);
+int sqliteOsWriteLock(OsFile*);
+int sqliteOsUnlock(OsFile*);
+int sqliteOsRandomSeed(char*);
+int sqliteOsSleep(int ms);
+void sqliteOsEnterMutex(void);
+void sqliteOsLeaveMutex(void);
+char *sqliteOsFullPathname(const char*);
+
+
+
+#endif /* _SQLITE_OS_H_ */
diff --git a/ext/sqlite/libsqlite/src/pager.c b/ext/sqlite/libsqlite/src/pager.c
new file mode 100644 (file)
index 0000000..7b32f6e
--- /dev/null
@@ -0,0 +1,2022 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This is the implementation of the page cache subsystem or "pager".
+** 
+** The pager is used to access a database disk file.  It implements
+** atomic commit and rollback through the use of a journal file that
+** is separate from the database file.  The pager also implements file
+** locking to prevent two processes from writing the same database
+** file simultaneously, or one process from reading the database while
+** another is writing.
+**
+** @(#) $Id$
+*/
+#include "os.h"         /* Must be first to enable large file support */
+#include "sqliteInt.h"
+#include "pager.h"
+#include <assert.h>
+#include <string.h>
+
+/*
+** Macros for troubleshooting.  Normally turned off
+*/
+#if 0
+static Pager *mainPager = 0;
+#define SET_PAGER(X)  if( mainPager==0 ) mainPager = (X)
+#define CLR_PAGER(X)  if( mainPager==(X) ) mainPager = 0
+#define TRACE1(X)     if( pPager==mainPager ) fprintf(stderr,X)
+#define TRACE2(X,Y)   if( pPager==mainPager ) fprintf(stderr,X,Y)
+#define TRACE3(X,Y,Z) if( pPager==mainPager ) fprintf(stderr,X,Y,Z)
+#else
+#define SET_PAGER(X)
+#define CLR_PAGER(X)
+#define TRACE1(X)
+#define TRACE2(X,Y)
+#define TRACE3(X,Y,Z)
+#endif
+
+
+/*
+** The page cache as a whole is always in one of the following
+** states:
+**
+**   SQLITE_UNLOCK       The page cache is not currently reading or 
+**                       writing the database file.  There is no
+**                       data held in memory.  This is the initial
+**                       state.
+**
+**   SQLITE_READLOCK     The page cache is reading the database.
+**                       Writing is not permitted.  There can be
+**                       multiple readers accessing the same database
+**                       file at the same time.
+**
+**   SQLITE_WRITELOCK    The page cache is writing the database.
+**                       Access is exclusive.  No other processes or
+**                       threads can be reading or writing while one
+**                       process is writing.
+**
+** The page cache comes up in SQLITE_UNLOCK.  The first time a
+** sqlite_page_get() occurs, the state transitions to SQLITE_READLOCK.
+** After all pages have been released using sqlite_page_unref(),
+** the state transitions back to SQLITE_UNLOCK.  The first time
+** that sqlite_page_write() is called, the state transitions to
+** SQLITE_WRITELOCK.  (Note that sqlite_page_write() can only be
+** called on an outstanding page which means that the pager must
+** be in SQLITE_READLOCK before it transitions to SQLITE_WRITELOCK.)
+** The sqlite_page_rollback() and sqlite_page_commit() functions 
+** transition the state from SQLITE_WRITELOCK back to SQLITE_READLOCK.
+*/
+#define SQLITE_UNLOCK      0
+#define SQLITE_READLOCK    1
+#define SQLITE_WRITELOCK   2
+
+
+/*
+** Each in-memory image of a page begins with the following header.
+** This header is only visible to this pager module.  The client
+** code that calls pager sees only the data that follows the header.
+*/
+typedef struct PgHdr PgHdr;
+struct PgHdr {
+  Pager *pPager;                 /* The pager to which this page belongs */
+  Pgno pgno;                     /* The page number for this page */
+  PgHdr *pNextHash, *pPrevHash;  /* Hash collision chain for PgHdr.pgno */
+  int nRef;                      /* Number of users of this page */
+  PgHdr *pNextFree, *pPrevFree;  /* Freelist of pages where nRef==0 */
+  PgHdr *pNextAll, *pPrevAll;    /* A list of all pages */
+  PgHdr *pNextCkpt, *pPrevCkpt;  /* List of pages in the checkpoint journal */
+  u8 inJournal;                  /* TRUE if has been written to journal */
+  u8 inCkpt;                     /* TRUE if written to the checkpoint journal */
+  u8 dirty;                      /* TRUE if we need to write back changes */
+  u8 needSync;                   /* Sync journal before writing this page */
+  u8 alwaysRollback;             /* Disable dont_rollback() for this page */
+  PgHdr *pDirty;                 /* Dirty pages sorted by PgHdr.pgno */
+  /* SQLITE_PAGE_SIZE bytes of page data follow this header */
+  /* Pager.nExtra bytes of local data follow the page data */
+};
+
+/*
+** Convert a pointer to a PgHdr into a pointer to its data
+** and back again.
+*/
+#define PGHDR_TO_DATA(P)  ((void*)(&(P)[1]))
+#define DATA_TO_PGHDR(D)  (&((PgHdr*)(D))[-1])
+#define PGHDR_TO_EXTRA(P) ((void*)&((char*)(&(P)[1]))[SQLITE_PAGE_SIZE])
+
+/*
+** How big to make the hash table used for locating in-memory pages
+** by page number.
+*/
+#define N_PG_HASH 2048
+
+/*
+** Hash a page number
+*/
+#define pager_hash(PN)  ((PN)&(N_PG_HASH-1))
+
+/*
+** A open page cache is an instance of the following structure.
+*/
+struct Pager {
+  char *zFilename;            /* Name of the database file */
+  char *zJournal;             /* Name of the journal file */
+  OsFile fd, jfd;             /* File descriptors for database and journal */
+  OsFile cpfd;                /* File descriptor for the checkpoint journal */
+  int dbSize;                 /* Number of pages in the file */
+  int origDbSize;             /* dbSize before the current change */
+  int ckptSize;               /* Size of database (in pages) at ckpt_begin() */
+  off_t ckptJSize;            /* Size of journal at ckpt_begin() */
+  int nRec;                   /* Number of pages written to the journal */
+  u32 cksumInit;              /* Quasi-random value added to every checksum */
+  int ckptNRec;               /* Number of records in the checkpoint journal */
+  int nExtra;                 /* Add this many bytes to each in-memory page */
+  void (*xDestructor)(void*); /* Call this routine when freeing pages */
+  int nPage;                  /* Total number of in-memory pages */
+  int nRef;                   /* Number of in-memory pages with PgHdr.nRef>0 */
+  int mxPage;                 /* Maximum number of pages to hold in cache */
+  int nHit, nMiss, nOvfl;     /* Cache hits, missing, and LRU overflows */
+  u8 journalOpen;             /* True if journal file descriptors is valid */
+  u8 journalStarted;          /* True if initial magic of journal is synced */
+  u8 useJournal;              /* Do not use a rollback journal on this file */
+  u8 ckptOpen;                /* True if the checkpoint journal is open */
+  u8 ckptInUse;               /* True we are in a checkpoint */
+  u8 ckptAutoopen;            /* Open ckpt journal when main journal is opened*/
+  u8 noSync;                  /* Do not sync the journal if true */
+  u8 fullSync;                /* Do extra syncs of the journal for robustness */
+  u8 state;                   /* SQLITE_UNLOCK, _READLOCK or _WRITELOCK */
+  u8 errMask;                 /* One of several kinds of errors */
+  u8 tempFile;                /* zFilename is a temporary file */
+  u8 readOnly;                /* True for a read-only database */
+  u8 needSync;                /* True if an fsync() is needed on the journal */
+  u8 dirtyFile;               /* True if database file has changed in any way */
+  u8 alwaysRollback;          /* Disable dont_rollback() for all pages */
+  u8 *aInJournal;             /* One bit for each page in the database file */
+  u8 *aInCkpt;                /* One bit for each page in the database */
+  PgHdr *pFirst, *pLast;      /* List of free pages */
+  PgHdr *pFirstSynced;        /* First free page with PgHdr.needSync==0 */
+  PgHdr *pAll;                /* List of all pages */
+  PgHdr *pCkpt;               /* List of pages in the checkpoint journal */
+  PgHdr *aHash[N_PG_HASH];    /* Hash table to map page number of PgHdr */
+};
+
+/*
+** These are bits that can be set in Pager.errMask.
+*/
+#define PAGER_ERR_FULL     0x01  /* a write() failed */
+#define PAGER_ERR_MEM      0x02  /* malloc() failed */
+#define PAGER_ERR_LOCK     0x04  /* error in the locking protocol */
+#define PAGER_ERR_CORRUPT  0x08  /* database or journal corruption */
+#define PAGER_ERR_DISK     0x10  /* general disk I/O error - bad hard drive? */
+
+/*
+** The journal file contains page records in the following
+** format.
+**
+** Actually, this structure is the complete page record for pager
+** formats less than 3.  Beginning with format 3, this record is surrounded
+** by two checksums.
+*/
+typedef struct PageRecord PageRecord;
+struct PageRecord {
+  Pgno pgno;                     /* The page number */
+  char aData[SQLITE_PAGE_SIZE];  /* Original data for page pgno */
+};
+
+/*
+** Journal files begin with the following magic string.  The data
+** was obtained from /dev/random.  It is used only as a sanity check.
+**
+** There are three journal formats (so far). The 1st journal format writes
+** 32-bit integers in the byte-order of the host machine.  New
+** formats writes integers as big-endian.  All new journals use the
+** new format, but we have to be able to read an older journal in order
+** to rollback journals created by older versions of the library.
+**
+** The 3rd journal format (added for 2.8.0) adds additional sanity
+** checking information to the journal.  If the power fails while the
+** journal is being written, semi-random garbage data might appear in
+** the journal file after power is restored.  If an attempt is then made
+** to roll the journal back, the database could be corrupted.  The additional
+** sanity checking data is an attempt to discover the garbage in the
+** journal and ignore it.
+**
+** The sanity checking information for the 3rd journal format consists
+** of a 32-bit checksum on each page of data.  The checksum covers both
+** the page number and the SQLITE_PAGE_SIZE bytes of data for the page.
+** This cksum is initialized to a 32-bit random value that appears in the
+** journal file right after the header.  The random initializer is important,
+** because garbage data that appears at the end of a journal is likely
+** data that was once in other files that have now been deleted.  If the
+** garbage data came from an obsolete journal file, the checksums might
+** be correct.  But by initializing the checksum to random value which
+** is different for every journal, we minimize that risk.
+*/
+static const unsigned char aJournalMagic1[] = {
+  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd4,
+};
+static const unsigned char aJournalMagic2[] = {
+  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd5,
+};
+static const unsigned char aJournalMagic3[] = {
+  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd6,
+};
+#define JOURNAL_FORMAT_1 1
+#define JOURNAL_FORMAT_2 2
+#define JOURNAL_FORMAT_3 3
+
+/*
+** The following integer determines what format to use when creating
+** new primary journal files.  By default we always use format 3.
+** When testing, we can set this value to older journal formats in order to
+** make sure that newer versions of the library are able to rollback older
+** journal files.
+**
+** Note that checkpoint journals always use format 2 and omit the header.
+*/
+#ifdef SQLITE_TEST
+int journal_format = 3;
+#else
+# define journal_format 3
+#endif
+
+/*
+** The size of the header and of each page in the journal varies according
+** to which journal format is being used.  The following macros figure out
+** the sizes based on format numbers.
+*/
+#define JOURNAL_HDR_SZ(X) \
+   (sizeof(aJournalMagic1) + sizeof(Pgno) + ((X)>=3)*2*sizeof(u32))
+#define JOURNAL_PG_SZ(X) \
+   (SQLITE_PAGE_SIZE + sizeof(Pgno) + ((X)>=3)*sizeof(u32))
+
+/*
+** Enable reference count tracking here:
+*/
+#ifdef SQLITE_TEST
+  int pager_refinfo_enable = 0;
+  static void pager_refinfo(PgHdr *p){
+    static int cnt = 0;
+    if( !pager_refinfo_enable ) return;
+    printf(
+       "REFCNT: %4d addr=0x%08x nRef=%d\n",
+       p->pgno, (int)PGHDR_TO_DATA(p), p->nRef
+    );
+    cnt++;   /* Something to set a breakpoint on */
+  }
+# define REFINFO(X)  pager_refinfo(X)
+#else
+# define REFINFO(X)
+#endif
+
+/*
+** Read a 32-bit integer from the given file descriptor
+*/
+static int read32bits(int format, OsFile *fd, u32 *pRes){
+  u32 res;
+  int rc;
+  rc = sqliteOsRead(fd, &res, sizeof(res));
+  if( rc==SQLITE_OK && format>JOURNAL_FORMAT_1 ){
+    unsigned char ac[4];
+    memcpy(ac, &res, 4);
+    res = (ac[0]<<24) | (ac[1]<<16) | (ac[2]<<8) | ac[3];
+  }
+  *pRes = res;
+  return rc;
+}
+
+/*
+** Write a 32-bit integer into the given file descriptor.  Writing
+** is always done using the new journal format.
+*/
+static int write32bits(OsFile *fd, u32 val){
+  unsigned char ac[4];
+  if( journal_format<=1 ){
+    return sqliteOsWrite(fd, &val, 4);
+  }
+  ac[0] = (val>>24) & 0xff;
+  ac[1] = (val>>16) & 0xff;
+  ac[2] = (val>>8) & 0xff;
+  ac[3] = val & 0xff;
+  return sqliteOsWrite(fd, ac, 4);
+}
+
+/*
+** Write a 32-bit integer into a page header right before the
+** page data.  This will overwrite the PgHdr.pDirty pointer.
+*/
+static void store32bits(u32 val, PgHdr *p, int offset){
+  unsigned char *ac;
+  ac = &((char*)PGHDR_TO_DATA(p))[offset];
+  if( journal_format<=1 ){
+    memcpy(ac, &val, 4);
+  }else{
+    ac[0] = (val>>24) & 0xff;
+    ac[1] = (val>>16) & 0xff;
+    ac[2] = (val>>8) & 0xff;
+    ac[3] = val & 0xff;
+  }
+}
+
+
+/*
+** Convert the bits in the pPager->errMask into an approprate
+** return code.
+*/
+static int pager_errcode(Pager *pPager){
+  int rc = SQLITE_OK;
+  if( pPager->errMask & PAGER_ERR_LOCK )    rc = SQLITE_PROTOCOL;
+  if( pPager->errMask & PAGER_ERR_DISK )    rc = SQLITE_IOERR;
+  if( pPager->errMask & PAGER_ERR_FULL )    rc = SQLITE_FULL;
+  if( pPager->errMask & PAGER_ERR_MEM )     rc = SQLITE_NOMEM;
+  if( pPager->errMask & PAGER_ERR_CORRUPT ) rc = SQLITE_CORRUPT;
+  return rc;
+}
+
+/*
+** Add or remove a page from the list of all pages that are in the
+** checkpoint journal.
+**
+** The Pager keeps a separate list of pages that are currently in
+** the checkpoint journal.  This helps the sqlitepager_ckpt_commit()
+** routine run MUCH faster for the common case where there are many
+** pages in memory but only a few are in the checkpoint journal.
+*/
+static void page_add_to_ckpt_list(PgHdr *pPg){
+  Pager *pPager = pPg->pPager;
+  if( pPg->inCkpt ) return;
+  assert( pPg->pPrevCkpt==0 && pPg->pNextCkpt==0 );
+  pPg->pPrevCkpt = 0;
+  if( pPager->pCkpt ){
+    pPager->pCkpt->pPrevCkpt = pPg;
+  }
+  pPg->pNextCkpt = pPager->pCkpt;
+  pPager->pCkpt = pPg;
+  pPg->inCkpt = 1;
+}
+static void page_remove_from_ckpt_list(PgHdr *pPg){
+  if( !pPg->inCkpt ) return;
+  if( pPg->pPrevCkpt ){
+    assert( pPg->pPrevCkpt->pNextCkpt==pPg );
+    pPg->pPrevCkpt->pNextCkpt = pPg->pNextCkpt;
+  }else{
+    assert( pPg->pPager->pCkpt==pPg );
+    pPg->pPager->pCkpt = pPg->pNextCkpt;
+  }
+  if( pPg->pNextCkpt ){
+    assert( pPg->pNextCkpt->pPrevCkpt==pPg );
+    pPg->pNextCkpt->pPrevCkpt = pPg->pPrevCkpt;
+  }
+  pPg->pNextCkpt = 0;
+  pPg->pPrevCkpt = 0;
+  pPg->inCkpt = 0;
+}
+
+/*
+** Find a page in the hash table given its page number.  Return
+** a pointer to the page or NULL if not found.
+*/
+static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
+  PgHdr *p = pPager->aHash[pager_hash(pgno)];
+  while( p && p->pgno!=pgno ){
+    p = p->pNextHash;
+  }
+  return p;
+}
+
+/*
+** Unlock the database and clear the in-memory cache.  This routine
+** sets the state of the pager back to what it was when it was first
+** opened.  Any outstanding pages are invalidated and subsequent attempts
+** to access those pages will likely result in a coredump.
+*/
+static void pager_reset(Pager *pPager){
+  PgHdr *pPg, *pNext;
+  for(pPg=pPager->pAll; pPg; pPg=pNext){
+    pNext = pPg->pNextAll;
+    sqliteFree(pPg);
+  }
+  pPager->pFirst = 0;
+  pPager->pFirstSynced = 0;
+  pPager->pLast = 0;
+  pPager->pAll = 0;
+  memset(pPager->aHash, 0, sizeof(pPager->aHash));
+  pPager->nPage = 0;
+  if( pPager->state>=SQLITE_WRITELOCK ){
+    sqlitepager_rollback(pPager);
+  }
+  sqliteOsUnlock(&pPager->fd);
+  pPager->state = SQLITE_UNLOCK;
+  pPager->dbSize = -1;
+  pPager->nRef = 0;
+  assert( pPager->journalOpen==0 );
+}
+
+/*
+** When this routine is called, the pager has the journal file open and
+** a write lock on the database.  This routine releases the database
+** write lock and acquires a read lock in its place.  The journal file
+** is deleted and closed.
+*/
+static int pager_unwritelock(Pager *pPager){
+  int rc;
+  PgHdr *pPg;
+  if( pPager->state<SQLITE_WRITELOCK ) return SQLITE_OK;
+  sqlitepager_ckpt_commit(pPager);
+  if( pPager->ckptOpen ){
+    sqliteOsClose(&pPager->cpfd);
+    pPager->ckptOpen = 0;
+  }
+  if( pPager->journalOpen ){
+    sqliteOsClose(&pPager->jfd);
+    pPager->journalOpen = 0;
+    sqliteOsDelete(pPager->zJournal);
+    sqliteFree( pPager->aInJournal );
+    pPager->aInJournal = 0;
+    for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
+      pPg->inJournal = 0;
+      pPg->dirty = 0;
+      pPg->needSync = 0;
+    }
+  }else{
+    assert( pPager->dirtyFile==0 || pPager->useJournal==0 );
+  }
+  rc = sqliteOsReadLock(&pPager->fd);
+  if( rc==SQLITE_OK ){
+    pPager->state = SQLITE_READLOCK;
+  }else{
+    /* This can only happen if a process does a BEGIN, then forks and the
+    ** child process does the COMMIT.  Because of the semantics of unix
+    ** file locking, the unlock will fail.
+    */
+    pPager->state = SQLITE_UNLOCK;
+  }
+  return rc;
+}
+
+/*
+** Compute and return a checksum for the page of data.
+*/
+static u32 pager_cksum(Pager *pPager, Pgno pgno, const char *aData){
+  u32 cksum = pPager->cksumInit + pgno;
+  return cksum;
+}
+
+/*
+** Read a single page from the journal file opened on file descriptor
+** jfd.  Playback this one page.
+**
+** There are three different journal formats.  The format parameter determines
+** which format is used by the journal that is played back.
+*/
+static int pager_playback_one_page(Pager *pPager, OsFile *jfd, int format){
+  int rc;
+  PgHdr *pPg;              /* An existing page in the cache */
+  PageRecord pgRec;
+  u32 cksum;
+
+  rc = read32bits(format, jfd, &pgRec.pgno);
+  if( rc!=SQLITE_OK ) return rc;
+  rc = sqliteOsRead(jfd, &pgRec.aData, sizeof(pgRec.aData));
+  if( rc!=SQLITE_OK ) return rc;
+
+  /* Sanity checking on the page.  This is more important that I originally
+  ** thought.  If a power failure occurs while the journal is being written,
+  ** it could cause invalid data to be written into the journal.  We need to
+  ** detect this invalid data (with high probability) and ignore it.
+  */
+  if( pgRec.pgno==0 ){
+    return SQLITE_DONE;
+  }
+  if( pgRec.pgno>pPager->dbSize ){
+    return SQLITE_OK;
+  }
+  if( format>=JOURNAL_FORMAT_3 ){
+    rc = read32bits(format, jfd, &cksum);
+    if( rc ) return rc;
+    if( pager_cksum(pPager, pgRec.pgno, pgRec.aData)!=cksum ){
+      return SQLITE_DONE;
+    }
+  }
+
+  /* Playback the page.  Update the in-memory copy of the page
+  ** at the same time, if there is one.
+  */
+  pPg = pager_lookup(pPager, pgRec.pgno);
+  TRACE2("PLAYBACK %d\n", pgRec.pgno);
+  sqliteOsSeek(&pPager->fd, (pgRec.pgno-1)*(off_t)SQLITE_PAGE_SIZE);
+  rc = sqliteOsWrite(&pPager->fd, pgRec.aData, SQLITE_PAGE_SIZE);
+  if( pPg ){
+    if( pPg->nRef==0 ||
+        memcmp(PGHDR_TO_DATA(pPg), pgRec.aData, SQLITE_PAGE_SIZE)==0
+    ){
+      /* Do not update the data on this page if the page is in use
+      ** and the page has never been modified.  This avoids resetting
+      ** the "extra" data.  That in turn avoids invalidating BTree cursors
+      ** in trees that have never been modified.  The end result is that
+      ** you can have a SELECT going on in one table and ROLLBACK changes
+      ** to a different table and the SELECT is unaffected by the ROLLBACK.
+      */
+      memcpy(PGHDR_TO_DATA(pPg), pgRec.aData, SQLITE_PAGE_SIZE);
+      memset(PGHDR_TO_EXTRA(pPg), 0, pPager->nExtra);
+    }
+    pPg->dirty = 0;
+    pPg->needSync = 0;
+  }
+  return rc;
+}
+
+/*
+** Playback the journal and thus restore the database file to
+** the state it was in before we started making changes.  
+**
+** The journal file format is as follows:  There is an initial
+** file-type string for sanity checking.  Then there is a single
+** Pgno number which is the number of pages in the database before
+** changes were made.  The database is truncated to this size.
+** Next come zero or more page records where each page record
+** consists of a Pgno and SQLITE_PAGE_SIZE bytes of data.  See
+** the PageRecord structure for details.
+**
+** If the file opened as the journal file is not a well-formed
+** journal file (as determined by looking at the magic number
+** at the beginning) then this routine returns SQLITE_PROTOCOL.
+** If any other errors occur during playback, the database will
+** likely be corrupted, so the PAGER_ERR_CORRUPT bit is set in
+** pPager->errMask and SQLITE_CORRUPT is returned.  If it all
+** works, then this routine returns SQLITE_OK.
+*/
+static int pager_playback(Pager *pPager, int useJournalSize){
+  off_t szJ;               /* Size of the journal file in bytes */
+  int nRec;                /* Number of Records in the journal */
+  int i;                   /* Loop counter */
+  Pgno mxPg = 0;           /* Size of the original file in pages */
+  int format;              /* Format of the journal file. */
+  unsigned char aMagic[sizeof(aJournalMagic1)];
+  int rc;
+
+  /* Figure out how many records are in the journal.  Abort early if
+  ** the journal is empty.
+  */
+  assert( pPager->journalOpen );
+  sqliteOsSeek(&pPager->jfd, 0);
+  rc = sqliteOsFileSize(&pPager->jfd, &szJ);
+  if( rc!=SQLITE_OK ){
+    goto end_playback;
+  }
+  if( szJ < sizeof(aMagic)+sizeof(Pgno) ){
+    goto end_playback;
+  }
+
+  /* Read the beginning of the journal and truncate the
+  ** database file back to its original size.
+  */
+  rc = sqliteOsRead(&pPager->jfd, aMagic, sizeof(aMagic));
+  if( rc!=SQLITE_OK ){
+    rc = SQLITE_PROTOCOL;
+    goto end_playback;
+  }
+  if( memcmp(aMagic, aJournalMagic3, sizeof(aMagic))==0 ){
+    format = JOURNAL_FORMAT_3;
+  }else if( memcmp(aMagic, aJournalMagic2, sizeof(aMagic))==0 ){
+    format = JOURNAL_FORMAT_2;
+  }else if( memcmp(aMagic, aJournalMagic1, sizeof(aMagic))==0 ){
+    format = JOURNAL_FORMAT_1;
+  }else{
+    rc = SQLITE_PROTOCOL;
+    goto end_playback;
+  }
+  if( format>=JOURNAL_FORMAT_3 ){
+    rc = read32bits(format, &pPager->jfd, &nRec);
+    if( rc ) goto end_playback;
+    rc = read32bits(format, &pPager->jfd, &pPager->cksumInit);
+    if( rc ) goto end_playback;
+    if( nRec==0xffffffff || useJournalSize ){
+      nRec = (szJ - JOURNAL_HDR_SZ(3))/JOURNAL_PG_SZ(3);
+    }
+  }else{
+    nRec = (szJ - JOURNAL_HDR_SZ(2))/JOURNAL_PG_SZ(2);
+    assert( nRec*JOURNAL_PG_SZ(2)+JOURNAL_HDR_SZ(2)==szJ );
+  }
+  rc = read32bits(format, &pPager->jfd, &mxPg);
+  if( rc!=SQLITE_OK ){
+    goto end_playback;
+  }
+  assert( pPager->origDbSize==0 || pPager->origDbSize==mxPg );
+  rc = sqliteOsTruncate(&pPager->fd, SQLITE_PAGE_SIZE*(off_t)mxPg);
+  if( rc!=SQLITE_OK ){
+    goto end_playback;
+  }
+  pPager->dbSize = mxPg;
+  
+  /* Copy original pages out of the journal and back into the database file.
+  */
+  for(i=0; i<nRec; i++){
+    rc = pager_playback_one_page(pPager, &pPager->jfd, format);
+    if( rc!=SQLITE_OK ){
+      if( rc==SQLITE_DONE ){
+        rc = SQLITE_OK;
+      }
+      break;
+    }
+  }
+
+  /* Pages that have been written to the journal but never synced
+  ** where not restored by the loop above.  We have to restore those
+  ** pages by reading the back from the original database.
+  */
+  if( rc==SQLITE_OK ){
+    PgHdr *pPg;
+    for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
+      char zBuf[SQLITE_PAGE_SIZE];
+      if( !pPg->dirty ) continue;
+      if( (int)pPg->pgno <= pPager->origDbSize ){
+        sqliteOsSeek(&pPager->fd, SQLITE_PAGE_SIZE*(off_t)(pPg->pgno-1));
+        rc = sqliteOsRead(&pPager->fd, zBuf, SQLITE_PAGE_SIZE);
+        if( rc ) break;
+      }else{
+        memset(zBuf, 0, SQLITE_PAGE_SIZE);
+      }
+      if( pPg->nRef==0 || memcmp(zBuf, PGHDR_TO_DATA(pPg), SQLITE_PAGE_SIZE) ){
+        memcpy(PGHDR_TO_DATA(pPg), zBuf, SQLITE_PAGE_SIZE);
+        memset(PGHDR_TO_EXTRA(pPg), 0, pPager->nExtra);
+      }
+      pPg->needSync = 0;
+      pPg->dirty = 0;
+    }
+  }
+
+end_playback:
+  if( rc!=SQLITE_OK ){
+    pager_unwritelock(pPager);
+    pPager->errMask |= PAGER_ERR_CORRUPT;
+    rc = SQLITE_CORRUPT;
+  }else{
+    rc = pager_unwritelock(pPager);
+  }
+  return rc;
+}
+
+/*
+** Playback the checkpoint journal.
+**
+** This is similar to playing back the transaction journal but with
+** a few extra twists.
+**
+**    (1)  The number of pages in the database file at the start of
+**         the checkpoint is stored in pPager->ckptSize, not in the
+**         journal file itself.
+**
+**    (2)  In addition to playing back the checkpoint journal, also
+**         playback all pages of the transaction journal beginning
+**         at offset pPager->ckptJSize.
+*/
+static int pager_ckpt_playback(Pager *pPager){
+  off_t szJ;               /* Size of the full journal */
+  int nRec;                /* Number of Records */
+  int i;                   /* Loop counter */
+  int rc;
+
+  /* Truncate the database back to its original size.
+  */
+  rc = sqliteOsTruncate(&pPager->fd, SQLITE_PAGE_SIZE*(off_t)pPager->ckptSize);
+  pPager->dbSize = pPager->ckptSize;
+
+  /* Figure out how many records are in the checkpoint journal.
+  */
+  assert( pPager->ckptInUse && pPager->journalOpen );
+  sqliteOsSeek(&pPager->cpfd, 0);
+  nRec = pPager->ckptNRec;
+  
+  /* Copy original pages out of the checkpoint journal and back into the
+  ** database file.  Note that the checkpoint journal always uses format
+  ** 2 instead of format 3 since it does not need to be concerned with
+  ** power failures corrupting the journal and can thus omit the checksums.
+  */
+  for(i=nRec-1; i>=0; i--){
+    rc = pager_playback_one_page(pPager, &pPager->cpfd, 2);
+    assert( rc!=SQLITE_DONE );
+    if( rc!=SQLITE_OK ) goto end_ckpt_playback;
+  }
+
+  /* Figure out how many pages need to be copied out of the transaction
+  ** journal.
+  */
+  rc = sqliteOsSeek(&pPager->jfd, pPager->ckptJSize);
+  if( rc!=SQLITE_OK ){
+    goto end_ckpt_playback;
+  }
+  rc = sqliteOsFileSize(&pPager->jfd, &szJ);
+  if( rc!=SQLITE_OK ){
+    goto end_ckpt_playback;
+  }
+  nRec = (szJ - pPager->ckptJSize)/JOURNAL_PG_SZ(journal_format);
+  for(i=nRec-1; i>=0; i--){
+    rc = pager_playback_one_page(pPager, &pPager->jfd, journal_format);
+    if( rc!=SQLITE_OK ){
+      assert( rc!=SQLITE_DONE );
+      goto end_ckpt_playback;
+    }
+  }
+  
+end_ckpt_playback:
+  if( rc!=SQLITE_OK ){
+    pPager->errMask |= PAGER_ERR_CORRUPT;
+    rc = SQLITE_CORRUPT;
+  }
+  return rc;
+}
+
+/*
+** Change the maximum number of in-memory pages that are allowed.
+**
+** The maximum number is the absolute value of the mxPage parameter.
+** If mxPage is negative, the noSync flag is also set.  noSync bypasses
+** calls to sqliteOsSync().  The pager runs much faster with noSync on,
+** but if the operating system crashes or there is an abrupt power 
+** failure, the database file might be left in an inconsistent and
+** unrepairable state.  
+*/
+void sqlitepager_set_cachesize(Pager *pPager, int mxPage){
+  if( mxPage>=0 ){
+    pPager->noSync = pPager->tempFile;
+  }else{
+    pPager->noSync = 1;
+    mxPage = -mxPage;
+  }
+  if( mxPage>10 ){
+    pPager->mxPage = mxPage;
+  }
+}
+
+/*
+** Adjust the robustness of the database to damage due to OS crashes
+** or power failures by changing the number of syncs()s when writing
+** the rollback journal.  There are three levels:
+**
+**    OFF       sqliteOsSync() is never called.  This is the default
+**              for temporary and transient files.
+**
+**    NORMAL    The journal is synced once before writes begin on the
+**              database.  This is normally adequate protection, but
+**              it is theoretically possible, though very unlikely,
+**              that an inopertune power failure could leave the journal
+**              in a state which would cause damage to the database
+**              when it is rolled back.
+**
+**    FULL      The journal is synced twice before writes begin on the
+**              database (with some additional information being written
+**              in between the two syncs.  If we assume that writing a
+**              single disk sector is atomic, then this mode provides
+**              assurance that the journal will not be corrupted to the
+**              point of causing damage to the database during rollback.
+**
+** Numeric values associated with these states are OFF==1, NORMAL=2,
+** and FULL=3.
+*/
+void sqlitepager_set_safety_level(Pager *pPager, int level){
+  pPager->noSync =  level==1 || pPager->tempFile;
+  pPager->fullSync = level==3 && !pPager->tempFile;
+}
+
+/*
+** Open a temporary file.  Write the name of the file into zName
+** (zName must be at least SQLITE_TEMPNAME_SIZE bytes long.)  Write
+** the file descriptor into *fd.  Return SQLITE_OK on success or some
+** other error code if we fail.
+**
+** The OS will automatically delete the temporary file when it is
+** closed.
+*/
+static int sqlitepager_opentemp(char *zFile, OsFile *fd){
+  int cnt = 8;
+  int rc;
+  do{
+    cnt--;
+    sqliteOsTempFileName(zFile);
+    rc = sqliteOsOpenExclusive(zFile, fd, 1);
+  }while( cnt>0 && rc!=SQLITE_OK );
+  return rc;
+}
+
+/*
+** Create a new page cache and put a pointer to the page cache in *ppPager.
+** The file to be cached need not exist.  The file is not locked until
+** the first call to sqlitepager_get() and is only held open until the
+** last page is released using sqlitepager_unref().
+**
+** If zFilename is NULL then a randomly-named temporary file is created
+** and used as the file to be cached.  The file will be deleted
+** automatically when it is closed.
+*/
+int sqlitepager_open(
+  Pager **ppPager,         /* Return the Pager structure here */
+  const char *zFilename,   /* Name of the database file to open */
+  int mxPage,              /* Max number of in-memory cache pages */
+  int nExtra,              /* Extra bytes append to each in-memory page */
+  int useJournal           /* TRUE to use a rollback journal on this file */
+){
+  Pager *pPager;
+  char *zFullPathname;
+  int nameLen;
+  OsFile fd;
+  int rc;
+  int tempFile;
+  int readOnly = 0;
+  char zTemp[SQLITE_TEMPNAME_SIZE];
+
+  *ppPager = 0;
+  if( sqlite_malloc_failed ){
+    return SQLITE_NOMEM;
+  }
+  if( zFilename ){
+    zFullPathname = sqliteOsFullPathname(zFilename);
+    rc = sqliteOsOpenReadWrite(zFullPathname, &fd, &readOnly);
+    tempFile = 0;
+  }else{
+    rc = sqlitepager_opentemp(zTemp, &fd);
+    zFilename = zTemp;
+    zFullPathname = sqliteOsFullPathname(zFilename);
+    tempFile = 1;
+  }
+  if( sqlite_malloc_failed ){
+    return SQLITE_NOMEM;
+  }
+  if( rc!=SQLITE_OK ){
+    sqliteFree(zFullPathname);
+    return SQLITE_CANTOPEN;
+  }
+  nameLen = strlen(zFullPathname);
+  pPager = sqliteMalloc( sizeof(*pPager) + nameLen*2 + 30 );
+  if( pPager==0 ){
+    sqliteOsClose(&fd);
+    sqliteFree(zFullPathname);
+    return SQLITE_NOMEM;
+  }
+  SET_PAGER(pPager);
+  pPager->zFilename = (char*)&pPager[1];
+  pPager->zJournal = &pPager->zFilename[nameLen+1];
+  strcpy(pPager->zFilename, zFullPathname);
+  strcpy(pPager->zJournal, zFullPathname);
+  sqliteFree(zFullPathname);
+  strcpy(&pPager->zJournal[nameLen], "-journal");
+  pPager->fd = fd;
+  pPager->journalOpen = 0;
+  pPager->useJournal = useJournal;
+  pPager->ckptOpen = 0;
+  pPager->ckptInUse = 0;
+  pPager->nRef = 0;
+  pPager->dbSize = -1;
+  pPager->ckptSize = 0;
+  pPager->ckptJSize = 0;
+  pPager->nPage = 0;
+  pPager->mxPage = mxPage>5 ? mxPage : 10;
+  pPager->state = SQLITE_UNLOCK;
+  pPager->errMask = 0;
+  pPager->tempFile = tempFile;
+  pPager->readOnly = readOnly;
+  pPager->needSync = 0;
+  pPager->noSync = pPager->tempFile || !useJournal;
+  pPager->pFirst = 0;
+  pPager->pFirstSynced = 0;
+  pPager->pLast = 0;
+  pPager->nExtra = nExtra;
+  memset(pPager->aHash, 0, sizeof(pPager->aHash));
+  *ppPager = pPager;
+  return SQLITE_OK;
+}
+
+/*
+** Set the destructor for this pager.  If not NULL, the destructor is called
+** when the reference count on each page reaches zero.  The destructor can
+** be used to clean up information in the extra segment appended to each page.
+**
+** The destructor is not called as a result sqlitepager_close().  
+** Destructors are only called by sqlitepager_unref().
+*/
+void sqlitepager_set_destructor(Pager *pPager, void (*xDesc)(void*)){
+  pPager->xDestructor = xDesc;
+}
+
+/*
+** Return the total number of pages in the disk file associated with
+** pPager.
+*/
+int sqlitepager_pagecount(Pager *pPager){
+  off_t n;
+  assert( pPager!=0 );
+  if( pPager->dbSize>=0 ){
+    return pPager->dbSize;
+  }
+  if( sqliteOsFileSize(&pPager->fd, &n)!=SQLITE_OK ){
+    pPager->errMask |= PAGER_ERR_DISK;
+    return 0;
+  }
+  n /= SQLITE_PAGE_SIZE;
+  if( pPager->state!=SQLITE_UNLOCK ){
+    pPager->dbSize = n;
+  }
+  return n;
+}
+
+/*
+** Shutdown the page cache.  Free all memory and close all files.
+**
+** If a transaction was in progress when this routine is called, that
+** transaction is rolled back.  All outstanding pages are invalidated
+** and their memory is freed.  Any attempt to use a page associated
+** with this page cache after this function returns will likely
+** result in a coredump.
+*/
+int sqlitepager_close(Pager *pPager){
+  PgHdr *pPg, *pNext;
+  switch( pPager->state ){
+    case SQLITE_WRITELOCK: {
+      sqlitepager_rollback(pPager);
+      sqliteOsUnlock(&pPager->fd);
+      assert( pPager->journalOpen==0 );
+      break;
+    }
+    case SQLITE_READLOCK: {
+      sqliteOsUnlock(&pPager->fd);
+      break;
+    }
+    default: {
+      /* Do nothing */
+      break;
+    }
+  }
+  for(pPg=pPager->pAll; pPg; pPg=pNext){
+    pNext = pPg->pNextAll;
+    sqliteFree(pPg);
+  }
+  sqliteOsClose(&pPager->fd);
+  assert( pPager->journalOpen==0 );
+  /* Temp files are automatically deleted by the OS
+  ** if( pPager->tempFile ){
+  **   sqliteOsDelete(pPager->zFilename);
+  ** }
+  */
+  CLR_PAGER(pPager);
+  sqliteFree(pPager);
+  return SQLITE_OK;
+}
+
+/*
+** Return the page number for the given page data.
+*/
+Pgno sqlitepager_pagenumber(void *pData){
+  PgHdr *p = DATA_TO_PGHDR(pData);
+  return p->pgno;
+}
+
+/*
+** Increment the reference count for a page.  If the page is
+** currently on the freelist (the reference count is zero) then
+** remove it from the freelist.
+*/
+#define page_ref(P)   ((P)->nRef==0?_page_ref(P):(void)(P)->nRef++)
+static void _page_ref(PgHdr *pPg){
+  if( pPg->nRef==0 ){
+    /* The page is currently on the freelist.  Remove it. */
+    if( pPg==pPg->pPager->pFirstSynced ){
+      PgHdr *p = pPg->pNextFree;
+      while( p && p->needSync ){ p = p->pNextFree; }
+      pPg->pPager->pFirstSynced = p;
+    }
+    if( pPg->pPrevFree ){
+      pPg->pPrevFree->pNextFree = pPg->pNextFree;
+    }else{
+      pPg->pPager->pFirst = pPg->pNextFree;
+    }
+    if( pPg->pNextFree ){
+      pPg->pNextFree->pPrevFree = pPg->pPrevFree;
+    }else{
+      pPg->pPager->pLast = pPg->pPrevFree;
+    }
+    pPg->pPager->nRef++;
+  }
+  pPg->nRef++;
+  REFINFO(pPg);
+}
+
+/*
+** Increment the reference count for a page.  The input pointer is
+** a reference to the page data.
+*/
+int sqlitepager_ref(void *pData){
+  PgHdr *pPg = DATA_TO_PGHDR(pData);
+  page_ref(pPg);
+  return SQLITE_OK;
+}
+
+/*
+** Sync the journal and then write all free dirty pages to the database
+** file.
+**
+** Writing all free dirty pages to the database after the sync is a
+** non-obvious optimization.  fsync() is an expensive operation so we
+** want to minimize the number ot times it is called. After an fsync() call,
+** we are free to write dirty pages back to the database.  It is best
+** to go ahead and write as many dirty pages as possible to minimize 
+** the risk of having to do another fsync() later on.  Writing dirty
+** free pages in this way was observed to make database operations go
+** up to 10 times faster.
+**
+** If we are writing to temporary database, there is no need to preserve
+** the integrity of the journal file, so we can save time and skip the
+** fsync().
+*/
+static int syncAllPages(Pager *pPager){
+  PgHdr *pPg;
+  int rc = SQLITE_OK;
+
+  /* Sync the journal before modifying the main database
+  ** (assuming there is a journal and it needs to be synced.)
+  */
+  if( pPager->needSync ){
+    if( !pPager->tempFile ){
+      assert( pPager->journalOpen );
+      assert( !pPager->noSync );
+#ifndef NDEBUG
+      {
+        off_t hdrSz, pgSz, jSz;
+        hdrSz = JOURNAL_HDR_SZ(journal_format);
+        pgSz = JOURNAL_PG_SZ(journal_format);
+        rc = sqliteOsFileSize(&pPager->jfd, &jSz);
+        if( rc!=0 ) return rc;
+        assert( pPager->nRec*pgSz+hdrSz==jSz );
+      }
+#endif
+      if( journal_format>=3 ){
+        off_t szJ;
+        if( pPager->fullSync ){
+          TRACE1("SYNC\n");
+          rc = sqliteOsSync(&pPager->jfd);
+          if( rc!=0 ) return rc;
+        }
+        sqliteOsSeek(&pPager->jfd, sizeof(aJournalMagic1));
+        rc = write32bits(&pPager->jfd, pPager->nRec);
+        if( rc ) return rc;
+        szJ = JOURNAL_HDR_SZ(journal_format) +
+                 pPager->nRec*JOURNAL_PG_SZ(journal_format);
+        sqliteOsSeek(&pPager->jfd, szJ);
+      }
+      TRACE1("SYNC\n");
+      rc = sqliteOsSync(&pPager->jfd);
+      if( rc!=0 ) return rc;
+      pPager->journalStarted = 1;
+    }
+    pPager->needSync = 0;
+
+    /* Erase the needSync flag from every page.
+    */
+    for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
+      pPg->needSync = 0;
+    }
+    pPager->pFirstSynced = pPager->pFirst;
+  }
+
+#ifndef NDEBUG
+  /* If the Pager.needSync flag is clear then the PgHdr.needSync
+  ** flag must also be clear for all pages.  Verify that this
+  ** invariant is true.
+  */
+  else{
+    for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
+      assert( pPg->needSync==0 );
+    }
+    assert( pPager->pFirstSynced==pPager->pFirst );
+  }
+#endif
+
+  return rc;
+}
+
+/*
+** Given a list of pages (connected by the PgHdr.pDirty pointer) write
+** every one of those pages out to the database file and mark them all
+** as clean.
+*/
+static int pager_write_pagelist(PgHdr *pList){
+  Pager *pPager;
+  int rc;
+
+  if( pList==0 ) return SQLITE_OK;
+  pPager = pList->pPager;
+  while( pList ){
+    assert( pList->dirty );
+    sqliteOsSeek(&pPager->fd, (pList->pgno-1)*(off_t)SQLITE_PAGE_SIZE);
+    rc = sqliteOsWrite(&pPager->fd, PGHDR_TO_DATA(pList), SQLITE_PAGE_SIZE);
+    if( rc ) return rc;
+    pList->dirty = 0;
+    pList = pList->pDirty;
+  }
+  return SQLITE_OK;
+}
+
+/*
+** Collect every dirty page into a dirty list and
+** return a pointer to the head of that list.  All pages are
+** collected even if they are still in use.
+*/
+static PgHdr *pager_get_all_dirty_pages(Pager *pPager){
+  PgHdr *p, *pList;
+  pList = 0;
+  for(p=pPager->pAll; p; p=p->pNextAll){
+    if( p->dirty ){
+      p->pDirty = pList;
+      pList = p;
+    }
+  }
+  return pList;
+}
+
+/*
+** Acquire a page.
+**
+** A read lock on the disk file is obtained when the first page is acquired. 
+** This read lock is dropped when the last page is released.
+**
+** A _get works for any page number greater than 0.  If the database
+** file is smaller than the requested page, then no actual disk
+** read occurs and the memory image of the page is initialized to
+** all zeros.  The extra data appended to a page is always initialized
+** to zeros the first time a page is loaded into memory.
+**
+** The acquisition might fail for several reasons.  In all cases,
+** an appropriate error code is returned and *ppPage is set to NULL.
+**
+** See also sqlitepager_lookup().  Both this routine and _lookup() attempt
+** to find a page in the in-memory cache first.  If the page is not already
+** in memory, this routine goes to disk to read it in whereas _lookup()
+** just returns 0.  This routine acquires a read-lock the first time it
+** has to go to disk, and could also playback an old journal if necessary.
+** Since _lookup() never goes to disk, it never has to deal with locks
+** or journal files.
+*/
+int sqlitepager_get(Pager *pPager, Pgno pgno, void **ppPage){
+  PgHdr *pPg;
+  int rc;
+
+  /* Make sure we have not hit any critical errors.
+  */ 
+  assert( pPager!=0 );
+  assert( pgno!=0 );
+  if( pPager->errMask & ~(PAGER_ERR_FULL) ){
+    return pager_errcode(pPager);
+  }
+
+  /* If this is the first page accessed, then get a read lock
+  ** on the database file.
+  */
+  if( pPager->nRef==0 ){
+    rc = sqliteOsReadLock(&pPager->fd);
+    if( rc!=SQLITE_OK ){
+      *ppPage = 0;
+      return rc;
+    }
+    pPager->state = SQLITE_READLOCK;
+
+    /* If a journal file exists, try to play it back.
+    */
+    if( pPager->useJournal && sqliteOsFileExists(pPager->zJournal) ){
+       int rc, dummy;
+
+       /* Get a write lock on the database
+       */
+       rc = sqliteOsWriteLock(&pPager->fd);
+       if( rc!=SQLITE_OK ){
+         if( sqliteOsUnlock(&pPager->fd)!=SQLITE_OK ){
+           /* This should never happen! */
+           rc = SQLITE_INTERNAL;
+         }
+         *ppPage = 0;
+         return rc;
+       }
+       pPager->state = SQLITE_WRITELOCK;
+
+       /* Open the journal for exclusive access.  Return SQLITE_BUSY if
+       ** we cannot get exclusive access to the journal file. 
+       **
+       ** Even though we will only be reading from the journal, not writing,
+       ** we have to open the journal for writing in order to obtain an
+       ** exclusive access lock.
+       */
+       rc = sqliteOsOpenReadWrite(pPager->zJournal, &pPager->jfd, &dummy);
+       if( rc!=SQLITE_OK ){
+         rc = sqliteOsUnlock(&pPager->fd);
+         assert( rc==SQLITE_OK );
+         *ppPage = 0;
+         return SQLITE_BUSY;
+       }
+       pPager->journalOpen = 1;
+       pPager->journalStarted = 0;
+
+       /* Playback and delete the journal.  Drop the database write
+       ** lock and reacquire the read lock.
+       */
+       rc = pager_playback(pPager, 0);
+       if( rc!=SQLITE_OK ){
+         return rc;
+       }
+    }
+    pPg = 0;
+  }else{
+    /* Search for page in cache */
+    pPg = pager_lookup(pPager, pgno);
+  }
+  if( pPg==0 ){
+    /* The requested page is not in the page cache. */
+    int h;
+    pPager->nMiss++;
+    if( pPager->nPage<pPager->mxPage || pPager->pFirst==0 ){
+      /* Create a new page */
+      pPg = sqliteMallocRaw( sizeof(*pPg) + SQLITE_PAGE_SIZE 
+                              + sizeof(u32) + pPager->nExtra );
+      if( pPg==0 ){
+        *ppPage = 0;
+        pager_unwritelock(pPager);
+        pPager->errMask |= PAGER_ERR_MEM;
+        return SQLITE_NOMEM;
+      }
+      memset(pPg, 0, sizeof(*pPg));
+      pPg->pPager = pPager;
+      pPg->pNextAll = pPager->pAll;
+      if( pPager->pAll ){
+        pPager->pAll->pPrevAll = pPg;
+      }
+      pPg->pPrevAll = 0;
+      pPager->pAll = pPg;
+      pPager->nPage++;
+    }else{
+      /* Find a page to recycle.  Try to locate a page that does not
+      ** require us to do an fsync() on the journal.
+      */
+      pPg = pPager->pFirstSynced;
+
+      /* If we could not find a page that does not require an fsync()
+      ** on the journal file then fsync the journal file.  This is a
+      ** very slow operation, so we work hard to avoid it.  But sometimes
+      ** it can't be helped.
+      */
+      if( pPg==0 ){
+        int rc = syncAllPages(pPager);
+        if( rc!=0 ){
+          sqlitepager_rollback(pPager);
+          *ppPage = 0;
+          return SQLITE_IOERR;
+        }
+        pPg = pPager->pFirst;
+      }
+      assert( pPg->nRef==0 );
+
+      /* Write the page to the database file if it is dirty.
+      */
+      if( pPg->dirty ){
+        assert( pPg->needSync==0 );
+        pPg->pDirty = 0;
+        rc = pager_write_pagelist( pPg );
+        if( rc!=SQLITE_OK ){
+          sqlitepager_rollback(pPager);
+          *ppPage = 0;
+          return SQLITE_IOERR;
+        }
+      }
+      assert( pPg->dirty==0 );
+
+      /* If the page we are recycling is marked as alwaysRollback, then
+      ** set the global alwaysRollback flag, thus disabling the
+      ** sqlite_dont_rollback() optimization for the rest of this transaction.
+      ** It is necessary to do this because the page marked alwaysRollback
+      ** might be reloaded at a later time but at that point we won't remember
+      ** that is was marked alwaysRollback.  This means that all pages must
+      ** be marked as alwaysRollback from here on out.
+      */
+      if( pPg->alwaysRollback ){
+        pPager->alwaysRollback = 1;
+      }
+
+      /* Unlink the old page from the free list and the hash table
+      */
+      if( pPg==pPager->pFirstSynced ){
+        PgHdr *p = pPg->pNextFree;
+        while( p && p->needSync ){ p = p->pNextFree; }
+        pPager->pFirstSynced = p;
+      }
+      if( pPg->pPrevFree ){
+        pPg->pPrevFree->pNextFree = pPg->pNextFree;
+      }else{
+        assert( pPager->pFirst==pPg );
+        pPager->pFirst = pPg->pNextFree;
+      }
+      if( pPg->pNextFree ){
+        pPg->pNextFree->pPrevFree = pPg->pPrevFree;
+      }else{
+        assert( pPager->pLast==pPg );
+        pPager->pLast = pPg->pPrevFree;
+      }
+      pPg->pNextFree = pPg->pPrevFree = 0;
+      if( pPg->pNextHash ){
+        pPg->pNextHash->pPrevHash = pPg->pPrevHash;
+      }
+      if( pPg->pPrevHash ){
+        pPg->pPrevHash->pNextHash = pPg->pNextHash;
+      }else{
+        h = pager_hash(pPg->pgno);
+        assert( pPager->aHash[h]==pPg );
+        pPager->aHash[h] = pPg->pNextHash;
+      }
+      pPg->pNextHash = pPg->pPrevHash = 0;
+      pPager->nOvfl++;
+    }
+    pPg->pgno = pgno;
+    if( pPager->aInJournal && (int)pgno<=pPager->origDbSize ){
+      sqliteCheckMemory(pPager->aInJournal, pgno/8);
+      assert( pPager->journalOpen );
+      pPg->inJournal = (pPager->aInJournal[pgno/8] & (1<<(pgno&7)))!=0;
+      pPg->needSync = 0;
+    }else{
+      pPg->inJournal = 0;
+      pPg->needSync = 0;
+    }
+    if( pPager->aInCkpt && (int)pgno<=pPager->ckptSize
+             && (pPager->aInCkpt[pgno/8] & (1<<(pgno&7)))!=0 ){
+      page_add_to_ckpt_list(pPg);
+    }else{
+      page_remove_from_ckpt_list(pPg);
+    }
+    pPg->dirty = 0;
+    pPg->nRef = 1;
+    REFINFO(pPg);
+    pPager->nRef++;
+    h = pager_hash(pgno);
+    pPg->pNextHash = pPager->aHash[h];
+    pPager->aHash[h] = pPg;
+    if( pPg->pNextHash ){
+      assert( pPg->pNextHash->pPrevHash==0 );
+      pPg->pNextHash->pPrevHash = pPg;
+    }
+    if( pPager->dbSize<0 ) sqlitepager_pagecount(pPager);
+    if( pPager->dbSize<(int)pgno ){
+      memset(PGHDR_TO_DATA(pPg), 0, SQLITE_PAGE_SIZE);
+    }else{
+      int rc;
+      sqliteOsSeek(&pPager->fd, (pgno-1)*(off_t)SQLITE_PAGE_SIZE);
+      rc = sqliteOsRead(&pPager->fd, PGHDR_TO_DATA(pPg), SQLITE_PAGE_SIZE);
+      if( rc!=SQLITE_OK ){
+        off_t fileSize;
+        if( sqliteOsFileSize(&pPager->fd,&fileSize)!=SQLITE_OK
+               || fileSize>=pgno*SQLITE_PAGE_SIZE ){
+          return rc;
+        }else{
+          memset(PGHDR_TO_DATA(pPg), 0, SQLITE_PAGE_SIZE);
+        }
+      }
+    }
+    if( pPager->nExtra>0 ){
+      memset(PGHDR_TO_EXTRA(pPg), 0, pPager->nExtra);
+    }
+  }else{
+    /* The requested page is in the page cache. */
+    pPager->nHit++;
+    page_ref(pPg);
+  }
+  *ppPage = PGHDR_TO_DATA(pPg);
+  return SQLITE_OK;
+}
+
+/*
+** Acquire a page if it is already in the in-memory cache.  Do
+** not read the page from disk.  Return a pointer to the page,
+** or 0 if the page is not in cache.
+**
+** See also sqlitepager_get().  The difference between this routine
+** and sqlitepager_get() is that _get() will go to the disk and read
+** in the page if the page is not already in cache.  This routine
+** returns NULL if the page is not in cache or if a disk I/O error 
+** has ever happened.
+*/
+void *sqlitepager_lookup(Pager *pPager, Pgno pgno){
+  PgHdr *pPg;
+
+  assert( pPager!=0 );
+  assert( pgno!=0 );
+  if( pPager->errMask & ~(PAGER_ERR_FULL) ){
+    return 0;
+  }
+  /* if( pPager->nRef==0 ){
+  **  return 0;
+  ** }
+  */
+  pPg = pager_lookup(pPager, pgno);
+  if( pPg==0 ) return 0;
+  page_ref(pPg);
+  return PGHDR_TO_DATA(pPg);
+}
+
+/*
+** Release a page.
+**
+** If the number of references to the page drop to zero, then the
+** page is added to the LRU list.  When all references to all pages
+** are released, a rollback occurs and the lock on the database is
+** removed.
+*/
+int sqlitepager_unref(void *pData){
+  PgHdr *pPg;
+
+  /* Decrement the reference count for this page
+  */
+  pPg = DATA_TO_PGHDR(pData);
+  assert( pPg->nRef>0 );
+  pPg->nRef--;
+  REFINFO(pPg);
+
+  /* When the number of references to a page reach 0, call the
+  ** destructor and add the page to the freelist.
+  */
+  if( pPg->nRef==0 ){
+    Pager *pPager;
+    pPager = pPg->pPager;
+    pPg->pNextFree = 0;
+    pPg->pPrevFree = pPager->pLast;
+    pPager->pLast = pPg;
+    if( pPg->pPrevFree ){
+      pPg->pPrevFree->pNextFree = pPg;
+    }else{
+      pPager->pFirst = pPg;
+    }
+    if( pPg->needSync==0 && pPager->pFirstSynced==0 ){
+      pPager->pFirstSynced = pPg;
+    }
+    if( pPager->xDestructor ){
+      pPager->xDestructor(pData);
+    }
+  
+    /* When all pages reach the freelist, drop the read lock from
+    ** the database file.
+    */
+    pPager->nRef--;
+    assert( pPager->nRef>=0 );
+    if( pPager->nRef==0 ){
+      pager_reset(pPager);
+    }
+  }
+  return SQLITE_OK;
+}
+
+/*
+** Create a journal file for pPager.  There should already be a write
+** lock on the database file when this routine is called.
+**
+** Return SQLITE_OK if everything.  Return an error code and release the
+** write lock if anything goes wrong.
+*/
+static int pager_open_journal(Pager *pPager){
+  int rc;
+  assert( pPager->state==SQLITE_WRITELOCK );
+  assert( pPager->journalOpen==0 );
+  assert( pPager->useJournal );
+  pPager->aInJournal = sqliteMalloc( pPager->dbSize/8 + 1 );
+  if( pPager->aInJournal==0 ){
+    sqliteOsReadLock(&pPager->fd);
+    pPager->state = SQLITE_READLOCK;
+    return SQLITE_NOMEM;
+  }
+  rc = sqliteOsOpenExclusive(pPager->zJournal, &pPager->jfd,pPager->tempFile);
+  if( rc!=SQLITE_OK ){
+    sqliteFree(pPager->aInJournal);
+    pPager->aInJournal = 0;
+    sqliteOsReadLock(&pPager->fd);
+    pPager->state = SQLITE_READLOCK;
+    return SQLITE_CANTOPEN;
+  }
+  pPager->journalOpen = 1;
+  pPager->journalStarted = 0;
+  pPager->needSync = 0;
+  pPager->alwaysRollback = 0;
+  pPager->nRec = 0;
+  sqlitepager_pagecount(pPager);
+  pPager->origDbSize = pPager->dbSize;
+  if( journal_format==JOURNAL_FORMAT_3 ){
+    rc = sqliteOsWrite(&pPager->jfd, aJournalMagic3, sizeof(aJournalMagic3));
+    if( rc==SQLITE_OK ){
+      rc = write32bits(&pPager->jfd, pPager->noSync ? 0xffffffff : 0);
+    }
+    if( rc==SQLITE_OK ){
+      pPager->cksumInit = (u32)sqliteRandomInteger();
+      rc = write32bits(&pPager->jfd, pPager->cksumInit);
+    }
+  }else if( journal_format==JOURNAL_FORMAT_2 ){
+    rc = sqliteOsWrite(&pPager->jfd, aJournalMagic2, sizeof(aJournalMagic2));
+  }else{
+    assert( journal_format==JOURNAL_FORMAT_1 );
+    rc = sqliteOsWrite(&pPager->jfd, aJournalMagic1, sizeof(aJournalMagic1));
+  }
+  if( rc==SQLITE_OK ){
+    rc = write32bits(&pPager->jfd, pPager->dbSize);
+  }
+  if( pPager->ckptAutoopen && rc==SQLITE_OK ){
+    rc = sqlitepager_ckpt_begin(pPager);
+  }
+  if( rc!=SQLITE_OK ){
+    rc = pager_unwritelock(pPager);
+    if( rc==SQLITE_OK ){
+      rc = SQLITE_FULL;
+    }
+  }
+  return rc;  
+}
+
+/*
+** Acquire a write-lock on the database.  The lock is removed when
+** the any of the following happen:
+**
+**   *  sqlitepager_commit() is called.
+**   *  sqlitepager_rollback() is called.
+**   *  sqlitepager_close() is called.
+**   *  sqlitepager_unref() is called to on every outstanding page.
+**
+** The parameter to this routine is a pointer to any open page of the
+** database file.  Nothing changes about the page - it is used merely
+** to acquire a pointer to the Pager structure and as proof that there
+** is already a read-lock on the database.
+**
+** A journal file is opened if this is not a temporary file.  For
+** temporary files, the opening of the journal file is deferred until
+** there is an actual need to write to the journal.
+**
+** If the database is already write-locked, this routine is a no-op.
+*/
+int sqlitepager_begin(void *pData){
+  PgHdr *pPg = DATA_TO_PGHDR(pData);
+  Pager *pPager = pPg->pPager;
+  int rc = SQLITE_OK;
+  assert( pPg->nRef>0 );
+  assert( pPager->state!=SQLITE_UNLOCK );
+  if( pPager->state==SQLITE_READLOCK ){
+    assert( pPager->aInJournal==0 );
+    rc = sqliteOsWriteLock(&pPager->fd);
+    if( rc!=SQLITE_OK ){
+      return rc;
+    }
+    pPager->state = SQLITE_WRITELOCK;
+    pPager->dirtyFile = 0;
+    TRACE1("TRANSACTION\n");
+    if( pPager->useJournal && !pPager->tempFile ){
+      rc = pager_open_journal(pPager);
+    }
+  }
+  return rc;
+}
+
+/*
+** Mark a data page as writeable.  The page is written into the journal 
+** if it is not there already.  This routine must be called before making
+** changes to a page.
+**
+** The first time this routine is called, the pager creates a new
+** journal and acquires a write lock on the database.  If the write
+** lock could not be acquired, this routine returns SQLITE_BUSY.  The
+** calling routine must check for that return value and be careful not to
+** change any page data until this routine returns SQLITE_OK.
+**
+** If the journal file could not be written because the disk is full,
+** then this routine returns SQLITE_FULL and does an immediate rollback.
+** All subsequent write attempts also return SQLITE_FULL until there
+** is a call to sqlitepager_commit() or sqlitepager_rollback() to
+** reset.
+*/
+int sqlitepager_write(void *pData){
+  PgHdr *pPg = DATA_TO_PGHDR(pData);
+  Pager *pPager = pPg->pPager;
+  int rc = SQLITE_OK;
+
+  /* Check for errors
+  */
+  if( pPager->errMask ){ 
+    return pager_errcode(pPager);
+  }
+  if( pPager->readOnly ){
+    return SQLITE_PERM;
+  }
+
+  /* Mark the page as dirty.  If the page has already been written
+  ** to the journal then we can return right away.
+  */
+  pPg->dirty = 1;
+  if( pPg->inJournal && (pPg->inCkpt || pPager->ckptInUse==0) ){
+    pPager->dirtyFile = 1;
+    return SQLITE_OK;
+  }
+
+  /* If we get this far, it means that the page needs to be
+  ** written to the transaction journal or the ckeckpoint journal
+  ** or both.
+  **
+  ** First check to see that the transaction journal exists and
+  ** create it if it does not.
+  */
+  assert( pPager->state!=SQLITE_UNLOCK );
+  rc = sqlitepager_begin(pData);
+  if( rc!=SQLITE_OK ){
+    return rc;
+  }
+  assert( pPager->state==SQLITE_WRITELOCK );
+  if( !pPager->journalOpen && pPager->useJournal ){
+    rc = pager_open_journal(pPager);
+    if( rc!=SQLITE_OK ) return rc;
+  }
+  assert( pPager->journalOpen || !pPager->useJournal );
+  pPager->dirtyFile = 1;
+
+  /* The transaction journal now exists and we have a write lock on the
+  ** main database file.  Write the current page to the transaction 
+  ** journal if it is not there already.
+  */
+  if( !pPg->inJournal && pPager->useJournal ){
+    if( (int)pPg->pgno <= pPager->origDbSize ){
+      int szPg;
+      u32 saved;
+      if( journal_format>=JOURNAL_FORMAT_3 ){
+        u32 cksum = pager_cksum(pPager, pPg->pgno, pData);
+        saved = *(u32*)PGHDR_TO_EXTRA(pPg);
+        store32bits(cksum, pPg, SQLITE_PAGE_SIZE);
+        szPg = SQLITE_PAGE_SIZE+8;
+      }else{
+        szPg = SQLITE_PAGE_SIZE+4;
+      }
+      store32bits(pPg->pgno, pPg, -4);
+      rc = sqliteOsWrite(&pPager->jfd, &((char*)pData)[-4], szPg);
+      if( journal_format>=JOURNAL_FORMAT_3 ){
+        *(u32*)PGHDR_TO_EXTRA(pPg) = saved;
+      }
+      if( rc!=SQLITE_OK ){
+        sqlitepager_rollback(pPager);
+        pPager->errMask |= PAGER_ERR_FULL;
+        return rc;
+      }
+      pPager->nRec++;
+      assert( pPager->aInJournal!=0 );
+      pPager->aInJournal[pPg->pgno/8] |= 1<<(pPg->pgno&7);
+      pPg->needSync = !pPager->noSync;
+      pPg->inJournal = 1;
+      if( pPager->ckptInUse ){
+        pPager->aInCkpt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
+        page_add_to_ckpt_list(pPg);
+      }
+      TRACE3("JOURNAL %d %d\n", pPg->pgno, pPg->needSync);
+    }else{
+      pPg->needSync = !pPager->journalStarted && !pPager->noSync;
+      TRACE3("APPEND %d %d\n", pPg->pgno, pPg->needSync);
+    }
+    if( pPg->needSync ){
+      pPager->needSync = 1;
+    }
+  }
+
+  /* If the checkpoint journal is open and the page is not in it,
+  ** then write the current page to the checkpoint journal.  Note that
+  ** the checkpoint journal always uses the simplier format 2 that lacks
+  ** checksums.  The header is also omitted from the checkpoint journal.
+  */
+  if( pPager->ckptInUse && !pPg->inCkpt && (int)pPg->pgno<=pPager->ckptSize ){
+    assert( pPg->inJournal || (int)pPg->pgno>pPager->origDbSize );
+    store32bits(pPg->pgno, pPg, -4);
+    rc = sqliteOsWrite(&pPager->cpfd, &((char*)pData)[-4], SQLITE_PAGE_SIZE+4);
+    if( rc!=SQLITE_OK ){
+      sqlitepager_rollback(pPager);
+      pPager->errMask |= PAGER_ERR_FULL;
+      return rc;
+    }
+    pPager->ckptNRec++;
+    assert( pPager->aInCkpt!=0 );
+    pPager->aInCkpt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
+    page_add_to_ckpt_list(pPg);
+  }
+
+  /* Update the database size and return.
+  */
+  if( pPager->dbSize<(int)pPg->pgno ){
+    pPager->dbSize = pPg->pgno;
+  }
+  return rc;
+}
+
+/*
+** Return TRUE if the page given in the argument was previously passed
+** to sqlitepager_write().  In other words, return TRUE if it is ok
+** to change the content of the page.
+*/
+int sqlitepager_iswriteable(void *pData){
+  PgHdr *pPg = DATA_TO_PGHDR(pData);
+  return pPg->dirty;
+}
+
+/*
+** A call to this routine tells the pager that it is not necessary to
+** write the information on page "pgno" back to the disk, even though
+** that page might be marked as dirty.
+**
+** The overlying software layer calls this routine when all of the data
+** on the given page is unused.  The pager marks the page as clean so
+** that it does not get written to disk.
+**
+** Tests show that this optimization, together with the
+** sqlitepager_dont_rollback() below, more than double the speed
+** of large INSERT operations and quadruple the speed of large DELETEs.
+**
+** When this routine is called, set the alwaysRollback flag to true.
+** Subsequent calls to sqlitepager_dont_rollback() for the same page
+** will thereafter be ignored.  This is necessary to avoid a problem
+** where a page with data is added to the freelist during one part of
+** a transaction then removed from the freelist during a later part
+** of the same transaction and reused for some other purpose.  When it
+** is first added to the freelist, this routine is called.  When reused,
+** the dont_rollback() routine is called.  But because the page contains
+** critical data, we still need to be sure it gets rolled back in spite
+** of the dont_rollback() call.
+*/
+void sqlitepager_dont_write(Pager *pPager, Pgno pgno){
+  PgHdr *pPg;
+
+  pPg = pager_lookup(pPager, pgno);
+  pPg->alwaysRollback = 1;
+  if( pPg && pPg->dirty ){
+    if( pPager->dbSize==(int)pPg->pgno && pPager->origDbSize<pPager->dbSize ){
+      /* If this pages is the last page in the file and the file has grown
+      ** during the current transaction, then do NOT mark the page as clean.
+      ** When the database file grows, we must make sure that the last page
+      ** gets written at least once so that the disk file will be the correct
+      ** size. If you do not write this page and the size of the file
+      ** on the disk ends up being too small, that can lead to database
+      ** corruption during the next transaction.
+      */
+    }else{
+      TRACE2("DONT_WRITE %d\n", pgno);
+      pPg->dirty = 0;
+    }
+  }
+}
+
+/*
+** A call to this routine tells the pager that if a rollback occurs,
+** it is not necessary to restore the data on the given page.  This
+** means that the pager does not have to record the given page in the
+** rollback journal.
+*/
+void sqlitepager_dont_rollback(void *pData){
+  PgHdr *pPg = DATA_TO_PGHDR(pData);
+  Pager *pPager = pPg->pPager;
+
+  if( pPager->state!=SQLITE_WRITELOCK || pPager->journalOpen==0 ) return;
+  if( pPg->alwaysRollback || pPager->alwaysRollback ) return;
+  if( !pPg->inJournal && (int)pPg->pgno <= pPager->origDbSize ){
+    assert( pPager->aInJournal!=0 );
+    pPager->aInJournal[pPg->pgno/8] |= 1<<(pPg->pgno&7);
+    pPg->inJournal = 1;
+    if( pPager->ckptInUse ){
+      pPager->aInCkpt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
+      page_add_to_ckpt_list(pPg);
+    }
+    TRACE2("DONT_ROLLBACK %d\n", pPg->pgno);
+  }
+  if( pPager->ckptInUse && !pPg->inCkpt && (int)pPg->pgno<=pPager->ckptSize ){
+    assert( pPg->inJournal || (int)pPg->pgno>pPager->origDbSize );
+    assert( pPager->aInCkpt!=0 );
+    pPager->aInCkpt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
+    page_add_to_ckpt_list(pPg);
+  }
+}
+
+/*
+** Commit all changes to the database and release the write lock.
+**
+** If the commit fails for any reason, a rollback attempt is made
+** and an error code is returned.  If the commit worked, SQLITE_OK
+** is returned.
+*/
+int sqlitepager_commit(Pager *pPager){
+  int rc;
+  PgHdr *pPg;
+
+  if( pPager->errMask==PAGER_ERR_FULL ){
+    rc = sqlitepager_rollback(pPager);
+    if( rc==SQLITE_OK ){
+      rc = SQLITE_FULL;
+    }
+    return rc;
+  }
+  if( pPager->errMask!=0 ){
+    rc = pager_errcode(pPager);
+    return rc;
+  }
+  if( pPager->state!=SQLITE_WRITELOCK ){
+    return SQLITE_ERROR;
+  }
+  TRACE1("COMMIT\n");
+  if( pPager->dirtyFile==0 ){
+    /* Exit early (without doing the time-consuming sqliteOsSync() calls)
+    ** if there have been no changes to the database file. */
+    assert( pPager->needSync==0 );
+    rc = pager_unwritelock(pPager);
+    pPager->dbSize = -1;
+    return rc;
+  }
+  assert( pPager->journalOpen );
+  if( pPager->needSync && sqliteOsSync(&pPager->jfd)!=SQLITE_OK ){
+    goto commit_abort;
+  }
+  pPg = pager_get_all_dirty_pages(pPager);
+  if( pPg ){
+    rc = pager_write_pagelist(pPg);
+    if( rc || (!pPager->noSync && sqliteOsSync(&pPager->fd)!=SQLITE_OK) ){
+      goto commit_abort;
+    }
+  }
+  rc = pager_unwritelock(pPager);
+  pPager->dbSize = -1;
+  return rc;
+
+  /* Jump here if anything goes wrong during the commit process.
+  */
+commit_abort:
+  rc = sqlitepager_rollback(pPager);
+  if( rc==SQLITE_OK ){
+    rc = SQLITE_FULL;
+  }
+  return rc;
+}
+
+/*
+** Rollback all changes.  The database falls back to read-only mode.
+** All in-memory cache pages revert to their original data contents.
+** The journal is deleted.
+**
+** This routine cannot fail unless some other process is not following
+** the correct locking protocol (SQLITE_PROTOCOL) or unless some other
+** process is writing trash into the journal file (SQLITE_CORRUPT) or
+** unless a prior malloc() failed (SQLITE_NOMEM).  Appropriate error
+** codes are returned for all these occasions.  Otherwise,
+** SQLITE_OK is returned.
+*/
+int sqlitepager_rollback(Pager *pPager){
+  int rc;
+  TRACE1("ROLLBACK\n");
+  if( !pPager->dirtyFile || !pPager->journalOpen ){
+    rc = pager_unwritelock(pPager);
+    pPager->dbSize = -1;
+    return rc;
+  }
+
+  if( pPager->errMask!=0 && pPager->errMask!=PAGER_ERR_FULL ){
+    if( pPager->state>=SQLITE_WRITELOCK ){
+      pager_playback(pPager, 1);
+    }
+    return pager_errcode(pPager);
+  }
+  if( pPager->state!=SQLITE_WRITELOCK ){
+    return SQLITE_OK;
+  }
+  rc = pager_playback(pPager, 1);
+  if( rc!=SQLITE_OK ){
+    rc = SQLITE_CORRUPT;
+    pPager->errMask |= PAGER_ERR_CORRUPT;
+  }
+  pPager->dbSize = -1;
+  return rc;
+}
+
+/*
+** Return TRUE if the database file is opened read-only.  Return FALSE
+** if the database is (in theory) writable.
+*/
+int sqlitepager_isreadonly(Pager *pPager){
+  return pPager->readOnly;
+}
+
+/*
+** This routine is used for testing and analysis only.
+*/
+int *sqlitepager_stats(Pager *pPager){
+  static int a[9];
+  a[0] = pPager->nRef;
+  a[1] = pPager->nPage;
+  a[2] = pPager->mxPage;
+  a[3] = pPager->dbSize;
+  a[4] = pPager->state;
+  a[5] = pPager->errMask;
+  a[6] = pPager->nHit;
+  a[7] = pPager->nMiss;
+  a[8] = pPager->nOvfl;
+  return a;
+}
+
+/*
+** Set the checkpoint.
+**
+** This routine should be called with the transaction journal already
+** open.  A new checkpoint journal is created that can be used to rollback
+** changes of a single SQL command within a larger transaction.
+*/
+int sqlitepager_ckpt_begin(Pager *pPager){
+  int rc;
+  char zTemp[SQLITE_TEMPNAME_SIZE];
+  if( !pPager->journalOpen ){
+    pPager->ckptAutoopen = 1;
+    return SQLITE_OK;
+  }
+  assert( pPager->journalOpen );
+  assert( !pPager->ckptInUse );
+  pPager->aInCkpt = sqliteMalloc( pPager->dbSize/8 + 1 );
+  if( pPager->aInCkpt==0 ){
+    sqliteOsReadLock(&pPager->fd);
+    return SQLITE_NOMEM;
+  }
+#ifndef NDEBUG
+  rc = sqliteOsFileSize(&pPager->jfd, &pPager->ckptJSize);
+  if( rc ) goto ckpt_begin_failed;
+  assert( pPager->ckptJSize == 
+    pPager->nRec*JOURNAL_PG_SZ(journal_format)+JOURNAL_HDR_SZ(journal_format) );
+#endif
+  pPager->ckptJSize = pPager->nRec*JOURNAL_PG_SZ(journal_format)
+                         + JOURNAL_HDR_SZ(journal_format);
+  pPager->ckptSize = pPager->dbSize;
+  if( !pPager->ckptOpen ){
+    rc = sqlitepager_opentemp(zTemp, &pPager->cpfd);
+    if( rc ) goto ckpt_begin_failed;
+    pPager->ckptOpen = 1;
+    pPager->ckptNRec = 0;
+  }
+  pPager->ckptInUse = 1;
+  return SQLITE_OK;
+ckpt_begin_failed:
+  if( pPager->aInCkpt ){
+    sqliteFree(pPager->aInCkpt);
+    pPager->aInCkpt = 0;
+  }
+  return rc;
+}
+
+/*
+** Commit a checkpoint.
+*/
+int sqlitepager_ckpt_commit(Pager *pPager){
+  if( pPager->ckptInUse ){
+    PgHdr *pPg, *pNext;
+    sqliteOsSeek(&pPager->cpfd, 0);
+    /* sqliteOsTruncate(&pPager->cpfd, 0); */
+    pPager->ckptNRec = 0;
+    pPager->ckptInUse = 0;
+    sqliteFree( pPager->aInCkpt );
+    pPager->aInCkpt = 0;
+    for(pPg=pPager->pCkpt; pPg; pPg=pNext){
+      pNext = pPg->pNextCkpt;
+      assert( pPg->inCkpt );
+      pPg->inCkpt = 0;
+      pPg->pPrevCkpt = pPg->pNextCkpt = 0;
+    }
+    pPager->pCkpt = 0;
+  }
+  pPager->ckptAutoopen = 0;
+  return SQLITE_OK;
+}
+
+/*
+** Rollback a checkpoint.
+*/
+int sqlitepager_ckpt_rollback(Pager *pPager){
+  int rc;
+  if( pPager->ckptInUse ){
+    rc = pager_ckpt_playback(pPager);
+    sqlitepager_ckpt_commit(pPager);
+  }else{
+    rc = SQLITE_OK;
+  }
+  pPager->ckptAutoopen = 0;
+  return rc;
+}
+
+#ifdef SQLITE_TEST
+/*
+** Print a listing of all referenced pages and their ref count.
+*/
+void sqlitepager_refdump(Pager *pPager){
+  PgHdr *pPg;
+  for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
+    if( pPg->nRef<=0 ) continue;
+    printf("PAGE %3d addr=0x%08x nRef=%d\n", 
+       pPg->pgno, (int)PGHDR_TO_DATA(pPg), pPg->nRef);
+  }
+}
+#endif
diff --git a/ext/sqlite/libsqlite/src/pager.h b/ext/sqlite/libsqlite/src/pager.h
new file mode 100644 (file)
index 0000000..a2f08d3
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This header file defines the interface that the sqlite page cache
+** subsystem.  The page cache subsystem reads and writes a file a page
+** at a time and provides a journal for rollback.
+**
+** @(#) $Id$
+*/
+
+/*
+** The size of one page
+**
+** You can change this value to another (reasonable) power of two
+** such as 512, 2048, 4096, or 8192 and things will still work.  But
+** experiments show that a page size of 1024 gives the best speed.
+** (The speed differences are minimal.)
+*/
+#define SQLITE_PAGE_SIZE 1024
+
+/*
+** Maximum number of pages in one database.  (This is a limitation of
+** imposed by 4GB files size limits.)
+*/
+#define SQLITE_MAX_PAGE 1073741823
+
+/*
+** The type used to represent a page number.  The first page in a file
+** is called page 1.  0 is used to represent "not a page".
+*/
+typedef unsigned int Pgno;
+
+/*
+** Each open file is managed by a separate instance of the "Pager" structure.
+*/
+typedef struct Pager Pager;
+
+/*
+** See source code comments for a detailed description of the following
+** routines:
+*/
+int sqlitepager_open(Pager **ppPager, const char *zFilename,
+                     int nPage, int nExtra, int useJournal);
+void sqlitepager_set_destructor(Pager*, void(*)(void*));
+void sqlitepager_set_cachesize(Pager*, int);
+int sqlitepager_close(Pager *pPager);
+int sqlitepager_get(Pager *pPager, Pgno pgno, void **ppPage);
+void *sqlitepager_lookup(Pager *pPager, Pgno pgno);
+int sqlitepager_ref(void*);
+int sqlitepager_unref(void*);
+Pgno sqlitepager_pagenumber(void*);
+int sqlitepager_write(void*);
+int sqlitepager_iswriteable(void*);
+int sqlitepager_pagecount(Pager*);
+int sqlitepager_begin(void*);
+int sqlitepager_commit(Pager*);
+int sqlitepager_rollback(Pager*);
+int sqlitepager_isreadonly(Pager*);
+int sqlitepager_ckpt_begin(Pager*);
+int sqlitepager_ckpt_commit(Pager*);
+int sqlitepager_ckpt_rollback(Pager*);
+void sqlitepager_dont_rollback(void*);
+void sqlitepager_dont_write(Pager*, Pgno);
+int *sqlitepager_stats(Pager*);
+void sqlitepager_set_safety_level(Pager*,int);
+
+#ifdef SQLITE_TEST
+void sqlitepager_refdump(Pager*);
+int pager_refinfo_enable;
+int journal_format;
+#endif
diff --git a/ext/sqlite/libsqlite/src/parse.c b/ext/sqlite/libsqlite/src/parse.c
new file mode 100644 (file)
index 0000000..60468f7
--- /dev/null
@@ -0,0 +1,6894 @@
+/* Driver template for the LEMON parser generator.
+** The author disclaims copyright to this source code.
+*/
+/* First off, code is include which follows the "include" declaration
+** in the input file. */
+#include <stdio.h>
+#line 35 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+
+#include "sqliteInt.h"
+#include "parse.h"
+
+/*
+** An instance of this structure holds information about the
+** LIMIT clause of a SELECT statement.
+*/
+struct LimitVal {
+  int limit;    /* The LIMIT value.  -1 if there is no limit */
+  int offset;   /* The OFFSET.  0 if there is none */
+};
+
+/*
+** An instance of the following structure describes the event of a
+** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
+** TK_DELETE, or TK_INSTEAD.  If the event is of the form
+**
+**      UPDATE ON (a,b,c)
+**
+** Then the "b" IdList records the list "a,b,c".
+*/
+struct TrigEvent { int a; IdList * b; };
+
+
+#line 34 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+/* Next is all token values, in a form suitable for use by makeheaders.
+** This section will be null unless lemon is run with the -m switch.
+*/
+/* 
+** These constants (all generated automatically by the parser generator)
+** specify the various kinds of tokens (terminals) that the parser
+** understands. 
+**
+** Each symbol here is a terminal symbol in the grammar.
+*/
+/* Make sure the INTERFACE macro is defined.
+*/
+#ifndef INTERFACE
+# define INTERFACE 1
+#endif
+/* The next thing included is series of defines which control
+** various aspects of the generated parser.
+**    YYCODETYPE         is the data type used for storing terminal
+**                       and nonterminal numbers.  "unsigned char" is
+**                       used if there are fewer than 250 terminals
+**                       and nonterminals.  "int" is used otherwise.
+**    YYNOCODE           is a number of type YYCODETYPE which corresponds
+**                       to no legal terminal or nonterminal number.  This
+**                       number is used to fill in empty slots of the hash 
+**                       table.
+**    YYFALLBACK         If defined, this indicates that one or more tokens
+**                       have fall-back values which should be used if the
+**                       original value of the token will not parse.
+**    YYACTIONTYPE       is the data type used for storing terminal
+**                       and nonterminal numbers.  "unsigned char" is
+**                       used if there are fewer than 250 rules and
+**                       states combined.  "int" is used otherwise.
+**    sqliteParserTOKENTYPE     is the data type used for minor tokens given 
+**                       directly to the parser from the tokenizer.
+**    YYMINORTYPE        is the data type used for all minor tokens.
+**                       This is typically a union of many types, one of
+**                       which is sqliteParserTOKENTYPE.  The entry in the union
+**                       for base tokens is called "yy0".
+**    YYSTACKDEPTH       is the maximum depth of the parser's stack.
+**    sqliteParserARG_SDECL     A static variable declaration for the %extra_argument
+**    sqliteParserARG_PDECL     A parameter declaration for the %extra_argument
+**    sqliteParserARG_STORE     Code to store %extra_argument into yypParser
+**    sqliteParserARG_FETCH     Code to extract %extra_argument from yypParser
+**    YYNSTATE           the combined number of states.
+**    YYNRULE            the number of rules in the grammar
+**    YYERRORSYMBOL      is the code number of the error symbol.  If not
+**                       defined, then do no error processing.
+*/
+/* \ 1 */
+#define YYCODETYPE unsigned char
+#define YYNOCODE 214
+#define YYACTIONTYPE unsigned short int
+#define sqliteParserTOKENTYPE Token
+typedef union {
+  sqliteParserTOKENTYPE yy0;
+  struct TrigEvent yy72;
+  struct {int value; int mask;} yy83;
+  int yy136;
+  ExprList* yy168;
+  Expr * yy176;
+  Select* yy207;
+  TriggerStep * yy209;
+  IdList* yy268;
+  Expr* yy272;
+  SrcList* yy289;
+  Token yy324;
+  struct LimitVal yy336;
+  int yy427;
+} YYMINORTYPE;
+#define YYSTACKDEPTH 100
+#define sqliteParserARG_SDECL Parse *pParse;
+#define sqliteParserARG_PDECL ,Parse *pParse
+#define sqliteParserARG_FETCH Parse *pParse = yypParser->pParse
+#define sqliteParserARG_STORE yypParser->pParse = pParse
+#define YYNSTATE 531
+#define YYNRULE 280
+#define YYERRORSYMBOL 150
+#define YYERRSYMDT yy427
+#define YYFALLBACK 1
+#define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
+#define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
+#define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
+/* Next is the action table.  Each entry in this table contains
+**
+**  +  An integer which is the number representing the look-ahead
+**     token
+**
+**  +  An integer indicating what action to take.  Number (N) between
+**     0 and YYNSTATE-1 mean shift the look-ahead and go to state N.
+**     Numbers between YYNSTATE and YYNSTATE+YYNRULE-1 mean reduce by
+**     rule N-YYNSTATE.  Number YYNSTATE+YYNRULE means that a syntax
+**     error has occurred.  Number YYNSTATE+YYNRULE+1 means the parser
+**     accepts its input.
+**
+**  +  A pointer to the next entry with the same hash value.
+**
+** The action table is really a series of hash tables.  Each hash
+** table contains a number of entries which is a power of two.  The
+** "state" table (which follows) contains information about the starting
+** point and size of each hash table.
+*/
+struct yyActionEntry {
+  YYCODETYPE   lookahead;   /* The value of the look-ahead token */
+  YYCODETYPE   next;        /* Next entry + 1. Zero at end of collision chain */
+  YYACTIONTYPE action;      /* Action to take for this look-ahead */
+};
+typedef struct yyActionEntry yyActionEntry;
+static const yyActionEntry yyActionTable[] = {
+/* State 0 */
+  {  44,   0, 529}, /*  1:                EXPLAIN shift  529 */
+  { 151,   0,   3}, /*  2:                explain shift  3 */
+  { 104,   1, 528}, /*  3:                   SEMI shift  528 */
+  { 165,   0, 812}, /*  4:                  input accept */
+  { 136,   0,   1}, /*  5:                cmdlist shift  1 */
+  { 149,   0, 530}, /*  6:                   ecmd shift  530 */
+/* State 1 */
+  {   0,   0, 531}, /*  1:                      $ reduce 0 */
+  { 151,   0,   3}, /*  2:                explain shift  3 */
+  { 104,   4, 528}, /*  3:                   SEMI shift  528 */
+  {  44,   0, 529}, /*  4:                EXPLAIN shift  529 */
+  { 149,   3,   2}, /*  5:                   ecmd shift  2 */
+/* State 3 */
+  { 120,   3, 483}, /*  1:                 UPDATE shift  483 */
+  { 181,   0,  69}, /*  2:              oneselect shift  69 */
+  {  40,   0,  25}, /*  3:                    END shift  25 */
+  { 123,   6, 509}, /*  4:                 VACUUM shift  509 */
+  { 144,   0,  29}, /*  5:           create_table shift  29 */
+  { 103,   7,  73}, /*  6:                 SELECT shift  73 */
+  {  63,  11, 498}, /*  7:                 INSERT shift  498 */
+  {  27,   0, 501}, /*  8:                   COPY shift  501 */
+  { 168,  12, 489}, /*  9:             insert_cmd shift  489 */
+  {   9,   0,   7}, /* 10:                  BEGIN shift  7 */
+  {  23,   0,  23}, /* 11:                 COMMIT shift  23 */
+  {  28,   0, 382}, /* 12:                 CREATE shift  382 */
+  { 192,  14, 478}, /* 13:                 select shift  478 */
+  {  92,  15, 511}, /* 14:                 PRAGMA shift  511 */
+  {  32,   0, 479}, /* 15:                 DELETE shift  479 */
+  { 135,   0,   6}, /* 16:                    cmd shift  6 */
+  {  97,  19, 500}, /* 17:                REPLACE shift  500 */
+  { 137,  17,   4}, /* 18:                   cmdx shift  4 */
+  {  37,   0, 469}, /* 19:                   DROP shift  469 */
+  {  99,   0,  27}, /* 20:               ROLLBACK shift  27 */
+/* State 4 */
+  { 104,   0,   5}, /*  1:                   SEMI shift  5 */
+/* State 6 */
+  { 104,   0, 536}, /*  1:                   SEMI reduce 5 */
+/* State 7 */
+  { 202,   2,   8}, /*  1:              trans_opt shift  8 */
+  { 114,   0,  18}, /*  2:            TRANSACTION shift  18 */
+/* State 8 */
+  { 180,   2,   9}, /*  1:                 onconf shift  9 */
+  {  87,   0,  10}, /*  2:                     ON shift  10 */
+  { 104,   0, 619}, /*  3:                   SEMI reduce 88 */
+/* State 9 */
+  { 104,   0, 539}, /*  1:                   SEMI reduce 8 */
+/* State 10 */
+  {  25,   0,  11}, /*  1:               CONFLICT shift  11 */
+/* State 11 */
+  {   1,   0,  14}, /*  1:                  ABORT shift  14 */
+  {  97,   1,  17}, /*  2:                REPLACE shift  17 */
+  {  99,   5,  13}, /*  3:               ROLLBACK shift  13 */
+  { 189,   3,  12}, /*  4:            resolvetype shift  12 */
+  {  57,   6,  16}, /*  5:                 IGNORE shift  16 */
+  {  45,   0,  15}, /*  6:                   FAIL shift  15 */
+/* State 18 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0,  19}, /*  2:                     nm shift  19 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 23 */
+  { 114,   0,  18}, /*  1:            TRANSACTION shift  18 */
+  { 202,   0,  24}, /*  2:              trans_opt shift  24 */
+  { 104,   0, 540}, /*  3:                   SEMI reduce 9 */
+/* State 24 */
+  { 104,   0, 543}, /*  1:                   SEMI reduce 12 */
+/* State 25 */
+  { 114,   0,  18}, /*  1:            TRANSACTION shift  18 */
+  { 202,   0,  26}, /*  2:              trans_opt shift  26 */
+  { 104,   0, 540}, /*  3:                   SEMI reduce 9 */
+/* State 26 */
+  { 104,   0, 544}, /*  1:                   SEMI reduce 13 */
+/* State 27 */
+  { 114,   0,  18}, /*  1:            TRANSACTION shift  18 */
+  { 202,   0,  28}, /*  2:              trans_opt shift  28 */
+  { 104,   0, 540}, /*  3:                   SEMI reduce 9 */
+/* State 28 */
+  { 104,   0, 545}, /*  1:                   SEMI reduce 14 */
+/* State 29 */
+  {   6,   0, 380}, /*  1:                     AS shift  380 */
+  { 145,   3,  30}, /*  2:      create_table_args shift  30 */
+  {  76,   0,  31}, /*  3:                     LP shift  31 */
+/* State 30 */
+  { 104,   0, 546}, /*  1:                   SEMI reduce 15 */
+/* State 31 */
+  { 140,   4,  37}, /*  1:               columnid shift  37 */
+  { 141,   5,  32}, /*  2:             columnlist shift  32 */
+  { 177,   0, 345}, /*  3:                     nm shift  345 */
+  {  56,   0,  20}, /*  4:                     ID shift  20 */
+  {  71,   0,  22}, /*  5:                JOIN_KW shift  22 */
+  { 110,   0,  21}, /*  6:                 STRING shift  21 */
+  { 139,   0, 379}, /*  7:                 column shift  379 */
+/* State 32 */
+  {  21,   0,  35}, /*  1:                  COMMA shift  35 */
+  { 101,   0, 607}, /*  2:                     RP reduce 76 */
+  { 143,   2,  33}, /*  3:           conslist_opt shift  33 */
+/* State 33 */
+  { 101,   0,  34}, /*  1:                     RP shift  34 */
+/* State 34 */
+  { 104,   0, 550}, /*  1:                   SEMI reduce 19 */
+/* State 35 */
+  {  26,   0, 349}, /*  1:             CONSTRAINT shift  349 */
+  {  93,   0, 351}, /*  2:                PRIMARY shift  351 */
+  { 119,   2, 357}, /*  3:                 UNIQUE shift  357 */
+  {  17,   0, 362}, /*  4:                  CHECK shift  362 */
+  {  56,   4,  20}, /*  5:                     ID shift  20 */
+  { 200,   0, 378}, /*  6:                  tcons shift  378 */
+  { 110,   8,  21}, /*  7:                 STRING shift  21 */
+  {  71,   0,  22}, /*  8:                JOIN_KW shift  22 */
+  { 177,   0, 345}, /*  9:                     nm shift  345 */
+  { 139,  12,  36}, /* 10:                 column shift  36 */
+  { 140,   0,  37}, /* 11:               columnid shift  37 */
+  {  48,   0, 365}, /* 12:                FOREIGN shift  365 */
+  { 142,   0, 346}, /* 13:               conslist shift  346 */
+/* State 37 */
+  { 160,   5, 344}, /*  1:                    ids shift  344 */
+  {  56,   0, 248}, /*  2:                     ID shift  248 */
+  { 207,   0,  38}, /*  3:                   type shift  38 */
+  { 208,   0, 331}, /*  4:               typename shift  331 */
+  { 110,   0, 249}, /*  5:                 STRING shift  249 */
+/* State 38 */
+  { 130,   0,  39}, /*  1:               carglist shift  39 */
+/* State 39 */
+  {  26,   0,  41}, /*  1:             CONSTRAINT shift  41 */
+  {  93,   0,  54}, /*  2:                PRIMARY shift  54 */
+  { 119,   2,  60}, /*  3:                 UNIQUE shift  60 */
+  { 146,   6, 313}, /*  4:        defer_subclause shift  313 */
+  { 134,   8, 318}, /*  5:                  ccons shift  318 */
+  {  29,   0, 319}, /*  6:                DEFAULT shift  319 */
+  {  84,   9,  44}, /*  7:                   NULL shift  44 */
+  {  95,  10, 291}, /*  8:             REFERENCES shift  291 */
+  {  19,   0, 314}, /*  9:                COLLATE shift  314 */
+  {  82,  11,  46}, /* 10:                    NOT shift  46 */
+  {  30,  12, 316}, /* 11:             DEFERRABLE shift  316 */
+  {  17,   0,  62}, /* 12:                  CHECK shift  62 */
+  { 129,   0,  40}, /* 13:                   carg shift  40 */
+/* State 41 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0,  42}, /*  2:                     nm shift  42 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 42 */
+  {  30,   0, 316}, /*  1:             DEFERRABLE shift  316 */
+  {  84,   0,  44}, /*  2:                   NULL shift  44 */
+  {  82,   0,  46}, /*  3:                    NOT shift  46 */
+  {  93,   0,  54}, /*  4:                PRIMARY shift  54 */
+  { 134,   2,  43}, /*  5:                  ccons shift  43 */
+  {  95,   0, 291}, /*  6:             REFERENCES shift  291 */
+  { 146,   0, 313}, /*  7:        defer_subclause shift  313 */
+  {  17,   0,  62}, /*  8:                  CHECK shift  62 */
+  {  19,   0, 314}, /*  9:                COLLATE shift  314 */
+  { 119,   9,  60}, /* 10:                 UNIQUE shift  60 */
+/* State 44 */
+  { 180,   0,  45}, /*  1:                 onconf shift  45 */
+  {  87,   0,  10}, /*  2:                     ON shift  10 */
+/* State 46 */
+  {  84,   2,  47}, /*  1:                   NULL shift  47 */
+  {  30,   0,  49}, /*  2:             DEFERRABLE shift  49 */
+/* State 47 */
+  { 180,   0,  48}, /*  1:                 onconf shift  48 */
+  {  87,   0,  10}, /*  2:                     ON shift  10 */
+/* State 49 */
+  { 164,   2,  50}, /*  1: init_deferred_pred_opt shift  50 */
+  {  62,   0,  51}, /*  2:              INITIALLY shift  51 */
+/* State 51 */
+  {  31,   0,  52}, /*  1:               DEFERRED shift  52 */
+  {  59,   1,  53}, /*  2:              IMMEDIATE shift  53 */
+/* State 54 */
+  {  72,   0,  55}, /*  1:                    KEY shift  55 */
+/* State 55 */
+  { 198,   0,  56}, /*  1:              sortorder shift  56 */
+  {  34,   3,  59}, /*  2:                   DESC shift  59 */
+  {   7,   0,  58}, /*  3:                    ASC shift  58 */
+/* State 56 */
+  { 180,   0,  57}, /*  1:                 onconf shift  57 */
+  {  87,   0,  10}, /*  2:                     ON shift  10 */
+/* State 60 */
+  { 180,   0,  61}, /*  1:                 onconf shift  61 */
+  {  87,   0,  10}, /*  2:                     ON shift  10 */
+/* State 62 */
+  {  76,   0,  63}, /*  1:                     LP shift  63 */
+/* State 63 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 288}, /*  3:                   expr shift  288 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 64 */
+  {  76,   2,  65}, /*  1:                     LP shift  65 */
+  {  36,   0, 559}, /*  2:                    DOT reduce 28 */
+/* State 65 */
+  { 108,   0, 286}, /*  1:                   STAR shift  286 */
+  {  91,   0, 174}, /*  2:                   PLUS shift  174 */
+  { 110,   4,  66}, /*  3:                 STRING shift  66 */
+  {  56,   0,  64}, /*  4:                     ID shift  64 */
+  {  94,   6, 186}, /*  5:                  RAISE shift  186 */
+  {  76,   0,  68}, /*  6:                     LP shift  68 */
+  {  80,   0, 172}, /*  7:                  MINUS shift  172 */
+  {  82,  14, 168}, /*  8:                    NOT shift  168 */
+  { 152,   7, 165}, /*  9:                   expr shift  165 */
+  { 153,   0, 212}, /* 10:               expritem shift  212 */
+  { 154,   8, 284}, /* 11:               exprlist shift  284 */
+  {  65,   0, 166}, /* 12:                INTEGER shift  166 */
+  {  84,  15, 101}, /* 13:                   NULL shift  101 */
+  {  46,   0, 167}, /* 14:                  FLOAT shift  167 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+  { 177,   0, 102}, /* 16:                     nm shift  102 */
+  {  16,   0, 176}, /* 17:                   CASE shift  176 */
+  {  71,   0,  67}, /* 18:                JOIN_KW shift  67 */
+/* State 66 */
+  {  36,   0, 560}, /*  1:                    DOT reduce 29 */
+/* State 67 */
+  {  36,   0, 561}, /*  1:                    DOT reduce 30 */
+/* State 68 */
+  {  91,   0, 174}, /*  1:                   PLUS shift  174 */
+  { 181,   1,  69}, /*  2:              oneselect shift  69 */
+  { 110,   4,  66}, /*  3:                 STRING shift  66 */
+  {  56,   0,  64}, /*  4:                     ID shift  64 */
+  {  94,   6, 186}, /*  5:                  RAISE shift  186 */
+  {  76,   0,  68}, /*  6:                     LP shift  68 */
+  {  80,   0, 172}, /*  7:                  MINUS shift  172 */
+  {  46,   0, 167}, /*  8:                  FLOAT shift  167 */
+  { 152,   7, 282}, /*  9:                   expr shift  282 */
+  {  84,  15, 101}, /* 10:                   NULL shift  101 */
+  {  82,   8, 168}, /* 11:                    NOT shift  168 */
+  {  65,   0, 166}, /* 12:                INTEGER shift  166 */
+  { 192,  10,  70}, /* 13:                 select shift  70 */
+  { 103,   0,  73}, /* 14:                 SELECT shift  73 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+  { 177,   0, 102}, /* 16:                     nm shift  102 */
+  {  16,   0, 176}, /* 17:                   CASE shift  176 */
+  {  71,   0,  67}, /* 18:                JOIN_KW shift  67 */
+/* State 70 */
+  { 101,   3, 281}, /*  1:                     RP shift  281 */
+  { 176,   1,  71}, /*  2:         multiselect_op shift  71 */
+  {  66,   0, 162}, /*  3:              INTERSECT shift  162 */
+  { 118,   5, 160}, /*  4:                  UNION shift  160 */
+  {  43,   0, 163}, /*  5:                 EXCEPT shift  163 */
+/* State 71 */
+  { 103,   0,  73}, /*  1:                 SELECT shift  73 */
+  { 181,   1,  72}, /*  2:              oneselect shift  72 */
+/* State 73 */
+  {   4,   0, 280}, /*  1:                    ALL shift  280 */
+  { 148,   1,  74}, /*  2:               distinct shift  74 */
+  {  35,   0, 279}, /*  3:               DISTINCT shift  279 */
+/* State 74 */
+  { 190,   0, 272}, /*  1:                   sclp shift  272 */
+  { 191,   0,  75}, /*  2:             selcollist shift  75 */
+/* State 75 */
+  { 156,   3,  76}, /*  1:                   from shift  76 */
+  {  49,   0, 235}, /*  2:                   FROM shift  235 */
+  {  21,   0, 234}, /*  3:                  COMMA shift  234 */
+/* State 76 */
+  { 212,   0,  77}, /*  1:              where_opt shift  77 */
+  { 127,   0, 232}, /*  2:                  WHERE shift  232 */
+/* State 77 */
+  {  53,   0, 229}, /*  1:                  GROUP shift  229 */
+  { 157,   1,  78}, /*  2:            groupby_opt shift  78 */
+/* State 78 */
+  { 158,   0,  79}, /*  1:             having_opt shift  79 */
+  {  55,   0, 227}, /*  2:                 HAVING shift  227 */
+/* State 79 */
+  {  90,   0,  88}, /*  1:                  ORDER shift  88 */
+  { 183,   0,  80}, /*  2:            orderby_opt shift  80 */
+/* State 80 */
+  {  75,   0,  82}, /*  1:                  LIMIT shift  82 */
+  { 173,   1,  81}, /*  2:              limit_opt shift  81 */
+/* State 82 */
+  {  65,   0,  83}, /*  1:                INTEGER shift  83 */
+/* State 83 */
+  { 174,   2,  84}, /*  1:              limit_sep shift  84 */
+  {  21,   0,  87}, /*  2:                  COMMA shift  87 */
+  {  86,   0,  86}, /*  3:                 OFFSET shift  86 */
+/* State 84 */
+  {  65,   0,  85}, /*  1:                INTEGER shift  85 */
+/* State 86 */
+  {  65,   0, 682}, /*  1:                INTEGER reduce 151 */
+/* State 87 */
+  {  65,   0, 683}, /*  1:                INTEGER reduce 152 */
+/* State 88 */
+  {  14,   0,  89}, /*  1:                     BY shift  89 */
+/* State 89 */
+  {  76,   0,  68}, /*  1:                     LP shift  68 */
+  {  94,   0, 186}, /*  2:                  RAISE shift  186 */
+  {  46,   5, 167}, /*  3:                  FLOAT shift  167 */
+  {  71,   0,  67}, /*  4:                JOIN_KW shift  67 */
+  {  12,   0, 170}, /*  5:                 BITNOT shift  170 */
+  {  56,   0,  64}, /*  6:                     ID shift  64 */
+  {  91,   0, 174}, /*  7:                   PLUS shift  174 */
+  { 177,   0, 102}, /*  8:                     nm shift  102 */
+  { 110,   1,  66}, /*  9:                 STRING shift  66 */
+  { 196,   2, 224}, /* 10:               sortitem shift  224 */
+  { 197,   0,  90}, /* 11:               sortlist shift  90 */
+  {  65,   0, 166}, /* 12:                INTEGER shift  166 */
+  {  80,   3, 172}, /* 13:                  MINUS shift  172 */
+  {  84,  16, 101}, /* 14:                   NULL shift  101 */
+  {  82,  12, 168}, /* 15:                    NOT shift  168 */
+  {  16,   0, 176}, /* 16:                   CASE shift  176 */
+  { 152,  14,  98}, /* 17:                   expr shift  98 */
+/* State 90 */
+  {  21,   0,  91}, /*  1:                  COMMA shift  91 */
+/* State 91 */
+  {  80,   4, 172}, /*  1:                  MINUS shift  172 */
+  { 177,   6, 102}, /*  2:                     nm shift  102 */
+  {  82,   0, 168}, /*  3:                    NOT shift  168 */
+  {  16,   0, 176}, /*  4:                   CASE shift  176 */
+  { 196,   7,  92}, /*  5:               sortitem shift  92 */
+  {  65,   0, 166}, /*  6:                INTEGER shift  166 */
+  {  84,   0, 101}, /*  7:                   NULL shift  101 */
+  {  71,   0,  67}, /*  8:                JOIN_KW shift  67 */
+  { 152,  10,  98}, /*  9:                   expr shift  98 */
+  {  56,   0,  64}, /* 10:                     ID shift  64 */
+  {  12,   0, 170}, /* 11:                 BITNOT shift  170 */
+  {  91,   0, 174}, /* 12:                   PLUS shift  174 */
+  {  76,  11,  68}, /* 13:                     LP shift  68 */
+  {  94,  16, 186}, /* 14:                  RAISE shift  186 */
+  { 110,  14,  66}, /* 15:                 STRING shift  66 */
+  {  46,   0, 167}, /* 16:                  FLOAT shift  167 */
+/* State 92 */
+  { 138,   0,  93}, /*  1:                collate shift  93 */
+  {  19,   0,  95}, /*  2:                COLLATE shift  95 */
+/* State 93 */
+  { 198,   0,  94}, /*  1:              sortorder shift  94 */
+  {  34,   3,  59}, /*  2:                   DESC shift  59 */
+  {   7,   0,  58}, /*  3:                    ASC shift  58 */
+/* State 95 */
+  {  56,   0,  96}, /*  1:                     ID shift  96 */
+  { 159,   0,  97}, /*  2:                     id shift  97 */
+/* State 98 */
+  {  88,   2, 106}, /*  1:                     OR shift  106 */
+  {  60,   0, 157}, /*  2:                     IN shift  157 */
+  {   5,   0, 100}, /*  3:                    AND shift  100 */
+  {  68,   0, 148}, /*  4:                     IS shift  148 */
+  { 172,   1, 128}, /*  5:                 likeop shift  128 */
+  {  89,   3,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+  {  13,   0, 122}, /*  7:                  BITOR shift  122 */
+  {  91,   0, 135}, /*  8:                   PLUS shift  135 */
+  {  74,   0, 133}, /*  9:                   LIKE shift  133 */
+  {  78,   0, 108}, /* 10:                     LT shift  108 */
+  {  10,   0, 153}, /* 11:                BETWEEN shift  153 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+  {  96,   4, 143}, /* 13:                    REM shift  143 */
+  {  69,   7, 147}, /* 14:                 ISNULL shift  147 */
+  {  42,   0, 118}, /* 15:                     EQ shift  118 */
+  {  80,  17, 137}, /* 16:                  MINUS shift  137 */
+  {  52,  20, 134}, /* 17:                   GLOB shift  134 */
+  {  73,   0, 112}, /* 18:                     LE shift  112 */
+  { 102,   9, 126}, /* 19:                 RSHIFT shift  126 */
+  {  24,   0, 145}, /* 20:                 CONCAT shift  145 */
+  {  54,   0, 110}, /* 21:                     GT shift  110 */
+  {  77,   0, 124}, /* 22:                 LSHIFT shift  124 */
+  { 106,  10, 141}, /* 23:                  SLASH shift  141 */
+  {  51,   0, 114}, /* 24:                     GE shift  114 */
+  { 108,  16, 139}, /* 25:                   STAR shift  139 */
+  {  81,   0, 116}, /* 26:                     NE shift  116 */
+  {  82,  21, 130}, /* 27:                    NOT shift  130 */
+  {  83,   0, 152}, /* 28:                NOTNULL shift  152 */
+/* State 100 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 105}, /*  3:                   expr shift  105 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 102 */
+  {  36,   0, 103}, /*  1:                    DOT shift  103 */
+/* State 103 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 104}, /*  2:                     nm shift  104 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 105 */
+  {  78,   2, 108}, /*  1:                     LT shift  108 */
+  {  52,   0, 134}, /*  2:                   GLOB shift  134 */
+  { 106,   7, 141}, /*  3:                  SLASH shift  141 */
+  {  81,   0, 116}, /*  4:                     NE shift  116 */
+  { 108,   8, 139}, /*  5:                   STAR shift  139 */
+  {  83,   0, 152}, /*  6:                NOTNULL shift  152 */
+  {  80,  10, 137}, /*  7:                  MINUS shift  137 */
+  {  82,   0, 130}, /*  8:                    NOT shift  130 */
+  {  60,   0, 157}, /*  9:                     IN shift  157 */
+  {  54,   0, 110}, /* 10:                     GT shift  110 */
+  {  10,   0, 153}, /* 11:                BETWEEN shift  153 */
+  {  89,  13,  99}, /* 12:      ORACLE_OUTER_JOIN shift  99 */
+  {  11,   0, 120}, /* 13:                 BITAND shift  120 */
+  {  91,  15, 135}, /* 14:                   PLUS shift  135 */
+  {  13,   0, 122}, /* 15:                  BITOR shift  122 */
+  {  68,  20, 148}, /* 16:                     IS shift  148 */
+  { 172,  16, 128}, /* 17:                 likeop shift  128 */
+  {  69,   0, 147}, /* 18:                 ISNULL shift  147 */
+  {  96,   0, 143}, /* 19:                    REM shift  143 */
+  {  42,   0, 118}, /* 20:                     EQ shift  118 */
+  {  24,   0, 145}, /* 21:                 CONCAT shift  145 */
+  {  73,   0, 112}, /* 22:                     LE shift  112 */
+  {  74,   0, 133}, /* 23:                   LIKE shift  133 */
+  {  51,   0, 114}, /* 24:                     GE shift  114 */
+  { 102,  21, 126}, /* 25:                 RSHIFT shift  126 */
+  {  77,  24, 124}, /* 26:                 LSHIFT shift  124 */
+/* State 106 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 107}, /*  3:                   expr shift  107 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 107 */
+  { 108,   4, 139}, /*  1:                   STAR shift  139 */
+  {  82,   0, 130}, /*  2:                    NOT shift  130 */
+  {  83,   0, 152}, /*  3:                NOTNULL shift  152 */
+  {  81,   5, 116}, /*  4:                     NE shift  116 */
+  {  54,   0, 110}, /*  5:                     GT shift  110 */
+  {   5,   0, 100}, /*  6:                    AND shift  100 */
+  {  60,   0, 157}, /*  7:                     IN shift  157 */
+  {  91,  10, 135}, /*  8:                   PLUS shift  135 */
+  {  89,   0,  99}, /*  9:      ORACLE_OUTER_JOIN shift  99 */
+  {  10,   0, 153}, /* 10:                BETWEEN shift  153 */
+  { 172,   8, 128}, /* 11:                 likeop shift  128 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+  {  69,  17, 147}, /* 13:                 ISNULL shift  147 */
+  {  13,   0, 122}, /* 14:                  BITOR shift  122 */
+  {  68,   0, 148}, /* 15:                     IS shift  148 */
+  {  96,  13, 143}, /* 16:                    REM shift  143 */
+  {  42,   0, 118}, /* 17:                     EQ shift  118 */
+  {  51,  19, 114}, /* 18:                     GE shift  114 */
+  {  24,   0, 145}, /* 19:                 CONCAT shift  145 */
+  {  73,   0, 112}, /* 20:                     LE shift  112 */
+  {  74,   0, 133}, /* 21:                   LIKE shift  133 */
+  { 102,   0, 126}, /* 22:                 RSHIFT shift  126 */
+  {  52,   0, 134}, /* 23:                   GLOB shift  134 */
+  {  77,   0, 124}, /* 24:                 LSHIFT shift  124 */
+  {  78,  18, 108}, /* 25:                     LT shift  108 */
+  { 106,  23, 141}, /* 26:                  SLASH shift  141 */
+  {  80,   0, 137}, /* 27:                  MINUS shift  137 */
+/* State 108 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 109}, /*  3:                   expr shift  109 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 109 */
+  { 108,   3, 139}, /*  1:                   STAR shift  139 */
+  {  13,   0, 122}, /*  2:                  BITOR shift  122 */
+  {  96,   4, 143}, /*  3:                    REM shift  143 */
+  {  24,   0, 145}, /*  4:                 CONCAT shift  145 */
+  { 172,   0, 128}, /*  5:                 likeop shift  128 */
+  {  89,  10,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+  { 102,   0, 126}, /*  7:                 RSHIFT shift  126 */
+  {  91,   0, 135}, /*  8:                   PLUS shift  135 */
+  {  80,   0, 137}, /*  9:                  MINUS shift  137 */
+  {  77,   0, 124}, /* 10:                 LSHIFT shift  124 */
+  { 106,   0, 141}, /* 11:                  SLASH shift  141 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+/* State 110 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 111}, /*  3:                   expr shift  111 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 111 */
+  { 108,   3, 139}, /*  1:                   STAR shift  139 */
+  {  13,   0, 122}, /*  2:                  BITOR shift  122 */
+  {  96,   4, 143}, /*  3:                    REM shift  143 */
+  {  24,   0, 145}, /*  4:                 CONCAT shift  145 */
+  { 172,   0, 128}, /*  5:                 likeop shift  128 */
+  {  89,  10,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+  { 102,   0, 126}, /*  7:                 RSHIFT shift  126 */
+  {  91,   0, 135}, /*  8:                   PLUS shift  135 */
+  {  80,   0, 137}, /*  9:                  MINUS shift  137 */
+  {  77,   0, 124}, /* 10:                 LSHIFT shift  124 */
+  { 106,   0, 141}, /* 11:                  SLASH shift  141 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+/* State 112 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 113}, /*  3:                   expr shift  113 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 113 */
+  { 108,   3, 139}, /*  1:                   STAR shift  139 */
+  {  13,   0, 122}, /*  2:                  BITOR shift  122 */
+  {  96,   4, 143}, /*  3:                    REM shift  143 */
+  {  24,   0, 145}, /*  4:                 CONCAT shift  145 */
+  { 172,   0, 128}, /*  5:                 likeop shift  128 */
+  {  89,  10,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+  { 102,   0, 126}, /*  7:                 RSHIFT shift  126 */
+  {  91,   0, 135}, /*  8:                   PLUS shift  135 */
+  {  80,   0, 137}, /*  9:                  MINUS shift  137 */
+  {  77,   0, 124}, /* 10:                 LSHIFT shift  124 */
+  { 106,   0, 141}, /* 11:                  SLASH shift  141 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+/* State 114 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 115}, /*  3:                   expr shift  115 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 115 */
+  { 108,   3, 139}, /*  1:                   STAR shift  139 */
+  {  13,   0, 122}, /*  2:                  BITOR shift  122 */
+  {  96,   4, 143}, /*  3:                    REM shift  143 */
+  {  24,   0, 145}, /*  4:                 CONCAT shift  145 */
+  { 172,   0, 128}, /*  5:                 likeop shift  128 */
+  {  89,  10,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+  { 102,   0, 126}, /*  7:                 RSHIFT shift  126 */
+  {  91,   0, 135}, /*  8:                   PLUS shift  135 */
+  {  80,   0, 137}, /*  9:                  MINUS shift  137 */
+  {  77,   0, 124}, /* 10:                 LSHIFT shift  124 */
+  { 106,   0, 141}, /* 11:                  SLASH shift  141 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+/* State 116 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 117}, /*  3:                   expr shift  117 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 117 */
+  {  96,   2, 143}, /*  1:                    REM shift  143 */
+  {  80,   0, 137}, /*  2:                  MINUS shift  137 */
+  {  54,   0, 110}, /*  3:                     GT shift  110 */
+  {  51,   0, 114}, /*  4:                     GE shift  114 */
+  {  73,   0, 112}, /*  5:                     LE shift  112 */
+  {  11,   0, 120}, /*  6:                 BITAND shift  120 */
+  { 102,   3, 126}, /*  7:                 RSHIFT shift  126 */
+  { 108,   0, 139}, /*  8:                   STAR shift  139 */
+  {  24,   0, 145}, /*  9:                 CONCAT shift  145 */
+  {  89,   5,  99}, /* 10:      ORACLE_OUTER_JOIN shift  99 */
+  { 106,   0, 141}, /* 11:                  SLASH shift  141 */
+  {  91,   6, 135}, /* 12:                   PLUS shift  135 */
+  { 172,   8, 128}, /* 13:                 likeop shift  128 */
+  {  77,  16, 124}, /* 14:                 LSHIFT shift  124 */
+  {  78,   0, 108}, /* 15:                     LT shift  108 */
+  {  13,   0, 122}, /* 16:                  BITOR shift  122 */
+/* State 118 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 119}, /*  3:                   expr shift  119 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 119 */
+  {  96,   2, 143}, /*  1:                    REM shift  143 */
+  {  80,   0, 137}, /*  2:                  MINUS shift  137 */
+  {  54,   0, 110}, /*  3:                     GT shift  110 */
+  {  51,   0, 114}, /*  4:                     GE shift  114 */
+  {  73,   0, 112}, /*  5:                     LE shift  112 */
+  {  11,   0, 120}, /*  6:                 BITAND shift  120 */
+  { 102,   3, 126}, /*  7:                 RSHIFT shift  126 */
+  { 108,   0, 139}, /*  8:                   STAR shift  139 */
+  {  24,   0, 145}, /*  9:                 CONCAT shift  145 */
+  {  89,   5,  99}, /* 10:      ORACLE_OUTER_JOIN shift  99 */
+  { 106,   0, 141}, /* 11:                  SLASH shift  141 */
+  {  91,   6, 135}, /* 12:                   PLUS shift  135 */
+  { 172,   8, 128}, /* 13:                 likeop shift  128 */
+  {  77,  16, 124}, /* 14:                 LSHIFT shift  124 */
+  {  78,   0, 108}, /* 15:                     LT shift  108 */
+  {  13,   0, 122}, /* 16:                  BITOR shift  122 */
+/* State 120 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 121}, /*  3:                   expr shift  121 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 121 */
+  {  96,   6, 143}, /*  1:                    REM shift  143 */
+  {  89,   0,  99}, /*  2:      ORACLE_OUTER_JOIN shift  99 */
+  { 106,   0, 141}, /*  3:                  SLASH shift  141 */
+  {  91,   0, 135}, /*  4:                   PLUS shift  135 */
+  { 172,   7, 128}, /*  5:                 likeop shift  128 */
+  {  80,   8, 137}, /*  6:                  MINUS shift  137 */
+  { 108,   0, 139}, /*  7:                   STAR shift  139 */
+  {  24,   0, 145}, /*  8:                 CONCAT shift  145 */
+/* State 122 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 123}, /*  3:                   expr shift  123 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 123 */
+  {  96,   6, 143}, /*  1:                    REM shift  143 */
+  {  89,   0,  99}, /*  2:      ORACLE_OUTER_JOIN shift  99 */
+  { 106,   0, 141}, /*  3:                  SLASH shift  141 */
+  {  91,   0, 135}, /*  4:                   PLUS shift  135 */
+  { 172,   7, 128}, /*  5:                 likeop shift  128 */
+  {  80,   8, 137}, /*  6:                  MINUS shift  137 */
+  { 108,   0, 139}, /*  7:                   STAR shift  139 */
+  {  24,   0, 145}, /*  8:                 CONCAT shift  145 */
+/* State 124 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 125}, /*  3:                   expr shift  125 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 125 */
+  {  96,   6, 143}, /*  1:                    REM shift  143 */
+  {  89,   0,  99}, /*  2:      ORACLE_OUTER_JOIN shift  99 */
+  { 106,   0, 141}, /*  3:                  SLASH shift  141 */
+  {  91,   0, 135}, /*  4:                   PLUS shift  135 */
+  { 172,   7, 128}, /*  5:                 likeop shift  128 */
+  {  80,   8, 137}, /*  6:                  MINUS shift  137 */
+  { 108,   0, 139}, /*  7:                   STAR shift  139 */
+  {  24,   0, 145}, /*  8:                 CONCAT shift  145 */
+/* State 126 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 127}, /*  3:                   expr shift  127 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 127 */
+  {  96,   6, 143}, /*  1:                    REM shift  143 */
+  {  89,   0,  99}, /*  2:      ORACLE_OUTER_JOIN shift  99 */
+  { 106,   0, 141}, /*  3:                  SLASH shift  141 */
+  {  91,   0, 135}, /*  4:                   PLUS shift  135 */
+  { 172,   7, 128}, /*  5:                 likeop shift  128 */
+  {  80,   8, 137}, /*  6:                  MINUS shift  137 */
+  { 108,   0, 139}, /*  7:                   STAR shift  139 */
+  {  24,   0, 145}, /*  8:                 CONCAT shift  145 */
+/* State 128 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 129}, /*  3:                   expr shift  129 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 129 */
+  {  96,   2, 143}, /*  1:                    REM shift  143 */
+  {  80,   0, 137}, /*  2:                  MINUS shift  137 */
+  {  54,   0, 110}, /*  3:                     GT shift  110 */
+  {  51,   0, 114}, /*  4:                     GE shift  114 */
+  {  73,   0, 112}, /*  5:                     LE shift  112 */
+  {  11,   0, 120}, /*  6:                 BITAND shift  120 */
+  { 102,   3, 126}, /*  7:                 RSHIFT shift  126 */
+  { 108,   0, 139}, /*  8:                   STAR shift  139 */
+  {  24,   0, 145}, /*  9:                 CONCAT shift  145 */
+  {  89,   5,  99}, /* 10:      ORACLE_OUTER_JOIN shift  99 */
+  { 106,   0, 141}, /* 11:                  SLASH shift  141 */
+  {  91,   6, 135}, /* 12:                   PLUS shift  135 */
+  { 172,   8, 128}, /* 13:                 likeop shift  128 */
+  {  77,  16, 124}, /* 14:                 LSHIFT shift  124 */
+  {  78,   0, 108}, /* 15:                     LT shift  108 */
+  {  13,   0, 122}, /* 16:                  BITOR shift  122 */
+/* State 130 */
+  {  84,   2, 213}, /*  1:                   NULL shift  213 */
+  {  60,   0, 218}, /*  2:                     IN shift  218 */
+  {  74,   0, 133}, /*  3:                   LIKE shift  133 */
+  {  52,   6, 134}, /*  4:                   GLOB shift  134 */
+  { 172,   4, 131}, /*  5:                 likeop shift  131 */
+  {  10,   0, 214}, /*  6:                BETWEEN shift  214 */
+/* State 131 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 132}, /*  3:                   expr shift  132 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 132 */
+  {  96,   2, 143}, /*  1:                    REM shift  143 */
+  {  80,   0, 137}, /*  2:                  MINUS shift  137 */
+  {  54,   0, 110}, /*  3:                     GT shift  110 */
+  {  51,   0, 114}, /*  4:                     GE shift  114 */
+  {  73,   0, 112}, /*  5:                     LE shift  112 */
+  {  11,   0, 120}, /*  6:                 BITAND shift  120 */
+  { 102,   3, 126}, /*  7:                 RSHIFT shift  126 */
+  { 108,   0, 139}, /*  8:                   STAR shift  139 */
+  {  24,   0, 145}, /*  9:                 CONCAT shift  145 */
+  {  89,   5,  99}, /* 10:      ORACLE_OUTER_JOIN shift  99 */
+  { 106,   0, 141}, /* 11:                  SLASH shift  141 */
+  {  91,   6, 135}, /* 12:                   PLUS shift  135 */
+  { 172,   8, 128}, /* 13:                 likeop shift  128 */
+  {  77,  16, 124}, /* 14:                 LSHIFT shift  124 */
+  {  78,   0, 108}, /* 15:                     LT shift  108 */
+  {  13,   0, 122}, /* 16:                  BITOR shift  122 */
+/* State 135 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 136}, /*  3:                   expr shift  136 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 136 */
+  { 108,   2, 139}, /*  1:                   STAR shift  139 */
+  {  96,   3, 143}, /*  2:                    REM shift  143 */
+  {  24,   0, 145}, /*  3:                 CONCAT shift  145 */
+  { 106,   0, 141}, /*  4:                  SLASH shift  141 */
+  { 172,   4, 128}, /*  5:                 likeop shift  128 */
+  {  89,   0,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+/* State 137 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 138}, /*  3:                   expr shift  138 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 138 */
+  { 108,   2, 139}, /*  1:                   STAR shift  139 */
+  {  96,   3, 143}, /*  2:                    REM shift  143 */
+  {  24,   0, 145}, /*  3:                 CONCAT shift  145 */
+  { 106,   0, 141}, /*  4:                  SLASH shift  141 */
+  { 172,   4, 128}, /*  5:                 likeop shift  128 */
+  {  89,   0,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+/* State 139 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 140}, /*  3:                   expr shift  140 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 140 */
+  {  24,   0, 145}, /*  1:                 CONCAT shift  145 */
+  { 172,   0, 128}, /*  2:                 likeop shift  128 */
+  {  89,   0,  99}, /*  3:      ORACLE_OUTER_JOIN shift  99 */
+/* State 141 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 142}, /*  3:                   expr shift  142 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 142 */
+  {  24,   0, 145}, /*  1:                 CONCAT shift  145 */
+  { 172,   0, 128}, /*  2:                 likeop shift  128 */
+  {  89,   0,  99}, /*  3:      ORACLE_OUTER_JOIN shift  99 */
+/* State 143 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 144}, /*  3:                   expr shift  144 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 144 */
+  {  24,   0, 145}, /*  1:                 CONCAT shift  145 */
+  { 172,   0, 128}, /*  2:                 likeop shift  128 */
+  {  89,   0,  99}, /*  3:      ORACLE_OUTER_JOIN shift  99 */
+/* State 145 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 146}, /*  3:                   expr shift  146 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 146 */
+  { 172,   0, 128}, /*  1:                 likeop shift  128 */
+  {  89,   0,  99}, /*  2:      ORACLE_OUTER_JOIN shift  99 */
+/* State 148 */
+  {  84,   2, 149}, /*  1:                   NULL shift  149 */
+  {  82,   0, 150}, /*  2:                    NOT shift  150 */
+/* State 150 */
+  {  84,   0, 151}, /*  1:                   NULL shift  151 */
+/* State 153 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 154}, /*  3:                   expr shift  154 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 154 */
+  {  88,   2, 106}, /*  1:                     OR shift  106 */
+  {  60,   0, 157}, /*  2:                     IN shift  157 */
+  {   5,   0, 155}, /*  3:                    AND shift  155 */
+  {  68,   0, 148}, /*  4:                     IS shift  148 */
+  { 172,   1, 128}, /*  5:                 likeop shift  128 */
+  {  89,   3,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+  {  13,   0, 122}, /*  7:                  BITOR shift  122 */
+  {  91,   0, 135}, /*  8:                   PLUS shift  135 */
+  {  74,   0, 133}, /*  9:                   LIKE shift  133 */
+  {  78,   0, 108}, /* 10:                     LT shift  108 */
+  {  10,   0, 153}, /* 11:                BETWEEN shift  153 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+  {  96,   4, 143}, /* 13:                    REM shift  143 */
+  {  69,   7, 147}, /* 14:                 ISNULL shift  147 */
+  {  42,   0, 118}, /* 15:                     EQ shift  118 */
+  {  80,  17, 137}, /* 16:                  MINUS shift  137 */
+  {  52,  20, 134}, /* 17:                   GLOB shift  134 */
+  {  73,   0, 112}, /* 18:                     LE shift  112 */
+  { 102,   9, 126}, /* 19:                 RSHIFT shift  126 */
+  {  24,   0, 145}, /* 20:                 CONCAT shift  145 */
+  {  54,   0, 110}, /* 21:                     GT shift  110 */
+  {  77,   0, 124}, /* 22:                 LSHIFT shift  124 */
+  { 106,  10, 141}, /* 23:                  SLASH shift  141 */
+  {  51,   0, 114}, /* 24:                     GE shift  114 */
+  { 108,  16, 139}, /* 25:                   STAR shift  139 */
+  {  81,   0, 116}, /* 26:                     NE shift  116 */
+  {  82,  21, 130}, /* 27:                    NOT shift  130 */
+  {  83,   0, 152}, /* 28:                NOTNULL shift  152 */
+/* State 155 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 156}, /*  3:                   expr shift  156 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 156 */
+  {  96,   2, 143}, /*  1:                    REM shift  143 */
+  {  80,   0, 137}, /*  2:                  MINUS shift  137 */
+  {  54,   0, 110}, /*  3:                     GT shift  110 */
+  {  51,   0, 114}, /*  4:                     GE shift  114 */
+  {  73,   0, 112}, /*  5:                     LE shift  112 */
+  {  11,   0, 120}, /*  6:                 BITAND shift  120 */
+  { 102,   3, 126}, /*  7:                 RSHIFT shift  126 */
+  { 108,   0, 139}, /*  8:                   STAR shift  139 */
+  {  24,   0, 145}, /*  9:                 CONCAT shift  145 */
+  {  89,   5,  99}, /* 10:      ORACLE_OUTER_JOIN shift  99 */
+  { 106,   0, 141}, /* 11:                  SLASH shift  141 */
+  {  91,   6, 135}, /* 12:                   PLUS shift  135 */
+  { 172,   8, 128}, /* 13:                 likeop shift  128 */
+  {  77,  16, 124}, /* 14:                 LSHIFT shift  124 */
+  {  78,   0, 108}, /* 15:                     LT shift  108 */
+  {  13,   0, 122}, /* 16:                  BITOR shift  122 */
+/* State 157 */
+  {  76,   0, 158}, /*  1:                     LP shift  158 */
+/* State 158 */
+  {  80,   0, 172}, /*  1:                  MINUS shift  172 */
+  { 181,   0,  69}, /*  2:              oneselect shift  69 */
+  {  82,   0, 168}, /*  3:                    NOT shift  168 */
+  { 103,   0,  73}, /*  4:                 SELECT shift  73 */
+  {  84,   0, 101}, /*  5:                   NULL shift  101 */
+  {  65,   0, 166}, /*  6:                INTEGER shift  166 */
+  {  46,   0, 167}, /*  7:                  FLOAT shift  167 */
+  {  71,   0,  67}, /*  8:                JOIN_KW shift  67 */
+  { 152,  10, 165}, /*  9:                   expr shift  165 */
+  {  12,   0, 170}, /* 10:                 BITNOT shift  170 */
+  { 110,   0,  66}, /* 11:                 STRING shift  66 */
+  {  91,   8, 174}, /* 12:                   PLUS shift  174 */
+  { 192,   9, 159}, /* 13:                 select shift  159 */
+  { 153,   0, 212}, /* 14:               expritem shift  212 */
+  { 154,  16, 208}, /* 15:               exprlist shift  208 */
+  {  94,   0, 186}, /* 16:                  RAISE shift  186 */
+  {  76,  19,  68}, /* 17:                     LP shift  68 */
+  { 177,   0, 102}, /* 18:                     nm shift  102 */
+  {  56,  20,  64}, /* 19:                     ID shift  64 */
+  {  16,   0, 176}, /* 20:                   CASE shift  176 */
+/* State 159 */
+  { 101,   3, 164}, /*  1:                     RP shift  164 */
+  { 176,   1,  71}, /*  2:         multiselect_op shift  71 */
+  {  66,   0, 162}, /*  3:              INTERSECT shift  162 */
+  { 118,   5, 160}, /*  4:                  UNION shift  160 */
+  {  43,   0, 163}, /*  5:                 EXCEPT shift  163 */
+/* State 160 */
+  {   4,   0, 161}, /*  1:                    ALL shift  161 */
+  { 103,   0, 634}, /*  2:                 SELECT reduce 103 */
+/* State 161 */
+  { 103,   0, 635}, /*  1:                 SELECT reduce 104 */
+/* State 162 */
+  { 103,   0, 636}, /*  1:                 SELECT reduce 105 */
+/* State 163 */
+  { 103,   0, 637}, /*  1:                 SELECT reduce 106 */
+/* State 165 */
+  {  88,   2, 106}, /*  1:                     OR shift  106 */
+  {  60,   0, 157}, /*  2:                     IN shift  157 */
+  {   5,   0, 100}, /*  3:                    AND shift  100 */
+  {  68,   0, 148}, /*  4:                     IS shift  148 */
+  { 172,   1, 128}, /*  5:                 likeop shift  128 */
+  {  89,   3,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+  {  13,   0, 122}, /*  7:                  BITOR shift  122 */
+  {  91,   0, 135}, /*  8:                   PLUS shift  135 */
+  {  74,   0, 133}, /*  9:                   LIKE shift  133 */
+  {  78,   0, 108}, /* 10:                     LT shift  108 */
+  {  10,   0, 153}, /* 11:                BETWEEN shift  153 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+  {  96,   4, 143}, /* 13:                    REM shift  143 */
+  {  69,   7, 147}, /* 14:                 ISNULL shift  147 */
+  {  42,   0, 118}, /* 15:                     EQ shift  118 */
+  {  80,  17, 137}, /* 16:                  MINUS shift  137 */
+  {  52,  20, 134}, /* 17:                   GLOB shift  134 */
+  {  73,   0, 112}, /* 18:                     LE shift  112 */
+  { 102,   9, 126}, /* 19:                 RSHIFT shift  126 */
+  {  24,   0, 145}, /* 20:                 CONCAT shift  145 */
+  {  54,   0, 110}, /* 21:                     GT shift  110 */
+  {  77,   0, 124}, /* 22:                 LSHIFT shift  124 */
+  { 106,  10, 141}, /* 23:                  SLASH shift  141 */
+  {  51,   0, 114}, /* 24:                     GE shift  114 */
+  { 108,  16, 139}, /* 25:                   STAR shift  139 */
+  {  81,   0, 116}, /* 26:                     NE shift  116 */
+  {  82,  21, 130}, /* 27:                    NOT shift  130 */
+  {  83,   0, 152}, /* 28:                NOTNULL shift  152 */
+/* State 168 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 169}, /*  3:                   expr shift  169 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 169 */
+  {  78,   2, 108}, /*  1:                     LT shift  108 */
+  {  52,   0, 134}, /*  2:                   GLOB shift  134 */
+  { 106,   7, 141}, /*  3:                  SLASH shift  141 */
+  {  81,   0, 116}, /*  4:                     NE shift  116 */
+  { 108,   8, 139}, /*  5:                   STAR shift  139 */
+  {  83,   0, 152}, /*  6:                NOTNULL shift  152 */
+  {  80,  10, 137}, /*  7:                  MINUS shift  137 */
+  {  82,   0, 130}, /*  8:                    NOT shift  130 */
+  {  60,   0, 157}, /*  9:                     IN shift  157 */
+  {  54,   0, 110}, /* 10:                     GT shift  110 */
+  {  10,   0, 153}, /* 11:                BETWEEN shift  153 */
+  {  89,  13,  99}, /* 12:      ORACLE_OUTER_JOIN shift  99 */
+  {  11,   0, 120}, /* 13:                 BITAND shift  120 */
+  {  91,  15, 135}, /* 14:                   PLUS shift  135 */
+  {  13,   0, 122}, /* 15:                  BITOR shift  122 */
+  {  68,  20, 148}, /* 16:                     IS shift  148 */
+  { 172,  16, 128}, /* 17:                 likeop shift  128 */
+  {  69,   0, 147}, /* 18:                 ISNULL shift  147 */
+  {  96,   0, 143}, /* 19:                    REM shift  143 */
+  {  42,   0, 118}, /* 20:                     EQ shift  118 */
+  {  24,   0, 145}, /* 21:                 CONCAT shift  145 */
+  {  73,   0, 112}, /* 22:                     LE shift  112 */
+  {  74,   0, 133}, /* 23:                   LIKE shift  133 */
+  {  51,   0, 114}, /* 24:                     GE shift  114 */
+  { 102,  21, 126}, /* 25:                 RSHIFT shift  126 */
+  {  77,  24, 124}, /* 26:                 LSHIFT shift  124 */
+/* State 170 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 171}, /*  3:                   expr shift  171 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 171 */
+  { 172,   0, 128}, /*  1:                 likeop shift  128 */
+  {  89,   0,  99}, /*  2:      ORACLE_OUTER_JOIN shift  99 */
+/* State 172 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 173}, /*  3:                   expr shift  173 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 173 */
+  { 172,   0, 128}, /*  1:                 likeop shift  128 */
+  {  89,   0,  99}, /*  2:      ORACLE_OUTER_JOIN shift  99 */
+/* State 174 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 175}, /*  3:                   expr shift  175 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 175 */
+  { 172,   0, 128}, /*  1:                 likeop shift  128 */
+  {  89,   0,  99}, /*  2:      ORACLE_OUTER_JOIN shift  99 */
+/* State 176 */
+  { 126,   0, 755}, /*  1:                   WHEN reduce 224 */
+  {  76,   0,  68}, /*  2:                     LP shift  68 */
+  {  46,   5, 167}, /*  3:                  FLOAT shift  167 */
+  {  71,   0,  67}, /*  4:                JOIN_KW shift  67 */
+  {  12,   0, 170}, /*  5:                 BITNOT shift  170 */
+  {  56,   0,  64}, /*  6:                     ID shift  64 */
+  {  91,   0, 174}, /*  7:                   PLUS shift  174 */
+  { 177,   1, 102}, /*  8:                     nm shift  102 */
+  { 110,   2,  66}, /*  9:                 STRING shift  66 */
+  {  94,   0, 186}, /* 10:                  RAISE shift  186 */
+  {  82,  12, 168}, /* 11:                    NOT shift  168 */
+  {  65,   0, 166}, /* 12:                INTEGER shift  166 */
+  {  80,   3, 172}, /* 13:                  MINUS shift  172 */
+  {  84,  16, 101}, /* 14:                   NULL shift  101 */
+  { 133,  11, 178}, /* 15:           case_operand shift  178 */
+  {  16,   0, 176}, /* 16:                   CASE shift  176 */
+  { 152,  14, 177}, /* 17:                   expr shift  177 */
+/* State 177 */
+  {  60,   0, 157}, /*  1:                     IN shift  157 */
+  {  88,   0, 106}, /*  2:                     OR shift  106 */
+  {  89,   1,  99}, /*  3:      ORACLE_OUTER_JOIN shift  99 */
+  {  68,   7, 148}, /*  4:                     IS shift  148 */
+  {  91,   0, 135}, /*  5:                   PLUS shift  135 */
+  {   5,   0, 100}, /*  6:                    AND shift  100 */
+  {  10,   0, 153}, /*  7:                BETWEEN shift  153 */
+  {  11,   0, 120}, /*  8:                 BITAND shift  120 */
+  {  13,   0, 122}, /*  9:                  BITOR shift  122 */
+  {  96,   0, 143}, /* 10:                    REM shift  143 */
+  { 126,   4, 754}, /* 11:                   WHEN reduce 223 */
+  {  69,   8, 147}, /* 12:                 ISNULL shift  147 */
+  {  73,   0, 112}, /* 13:                     LE shift  112 */
+  {  42,   9, 118}, /* 14:                     EQ shift  118 */
+  {  77,   0, 124}, /* 15:                 LSHIFT shift  124 */
+  { 102,  13, 126}, /* 16:                 RSHIFT shift  126 */
+  {  74,   0, 133}, /* 17:                   LIKE shift  133 */
+  {  51,   0, 114}, /* 18:                     GE shift  114 */
+  {  52,   0, 134}, /* 19:                   GLOB shift  134 */
+  { 106,  15, 141}, /* 20:                  SLASH shift  141 */
+  {  78,   0, 108}, /* 21:                     LT shift  108 */
+  { 108,   0, 139}, /* 22:                   STAR shift  139 */
+  {  80,  18, 137}, /* 23:                  MINUS shift  137 */
+  {  81,  19, 116}, /* 24:                     NE shift  116 */
+  {  82,  27, 130}, /* 25:                    NOT shift  130 */
+  {  83,  29, 152}, /* 26:                NOTNULL shift  152 */
+  {  24,   0, 145}, /* 27:                 CONCAT shift  145 */
+  { 172,   0, 128}, /* 28:                 likeop shift  128 */
+  {  54,   0, 110}, /* 29:                     GT shift  110 */
+/* State 178 */
+  { 132,   2, 179}, /*  1:          case_exprlist shift  179 */
+  { 126,   0, 204}, /*  2:                   WHEN shift  204 */
+/* State 179 */
+  {  40,   0, 753}, /*  1:                    END reduce 222 */
+  {  39,   0, 202}, /*  2:                   ELSE shift  202 */
+  { 126,   0, 182}, /*  3:                   WHEN shift  182 */
+  { 131,   2, 180}, /*  4:              case_else shift  180 */
+/* State 180 */
+  {  40,   0, 181}, /*  1:                    END shift  181 */
+/* State 182 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 183}, /*  3:                   expr shift  183 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 183 */
+  {  60,   0, 157}, /*  1:                     IN shift  157 */
+  {  88,   0, 106}, /*  2:                     OR shift  106 */
+  {  89,   1,  99}, /*  3:      ORACLE_OUTER_JOIN shift  99 */
+  {  10,   0, 153}, /*  4:                BETWEEN shift  153 */
+  {  91,   0, 135}, /*  5:                   PLUS shift  135 */
+  {   5,   0, 100}, /*  6:                    AND shift  100 */
+  {  11,   0, 120}, /*  7:                 BITAND shift  120 */
+  {  13,   0, 122}, /*  8:                  BITOR shift  122 */
+  {  73,   0, 112}, /*  9:                     LE shift  112 */
+  {  96,   0, 143}, /* 10:                    REM shift  143 */
+  {  68,   4, 148}, /* 11:                     IS shift  148 */
+  {  69,   7, 147}, /* 12:                 ISNULL shift  147 */
+  {  77,   0, 124}, /* 13:                 LSHIFT shift  124 */
+  {  42,   8, 118}, /* 14:                     EQ shift  118 */
+  {  51,   0, 114}, /* 15:                     GE shift  114 */
+  { 102,   9, 126}, /* 16:                 RSHIFT shift  126 */
+  {  74,   0, 133}, /* 17:                   LIKE shift  133 */
+  {  52,   0, 134}, /* 18:                   GLOB shift  134 */
+  {  24,   0, 145}, /* 19:                 CONCAT shift  145 */
+  { 106,  13, 141}, /* 20:                  SLASH shift  141 */
+  {  78,   0, 108}, /* 21:                     LT shift  108 */
+  { 108,   0, 139}, /* 22:                   STAR shift  139 */
+  {  80,  15, 137}, /* 23:                  MINUS shift  137 */
+  {  81,  18, 116}, /* 24:                     NE shift  116 */
+  {  82,  19, 130}, /* 25:                    NOT shift  130 */
+  {  83,  29, 152}, /* 26:                NOTNULL shift  152 */
+  { 113,   0, 184}, /* 27:                   THEN shift  184 */
+  { 172,   0, 128}, /* 28:                 likeop shift  128 */
+  {  54,   0, 110}, /* 29:                     GT shift  110 */
+/* State 184 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 185}, /*  3:                   expr shift  185 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 185 */
+  {  88,   2, 106}, /*  1:                     OR shift  106 */
+  {  60,   0, 157}, /*  2:                     IN shift  157 */
+  {   5,   0, 100}, /*  3:                    AND shift  100 */
+  {  68,   0, 148}, /*  4:                     IS shift  148 */
+  { 172,   1, 128}, /*  5:                 likeop shift  128 */
+  {  89,   3,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+  {  13,   0, 122}, /*  7:                  BITOR shift  122 */
+  {  91,   0, 135}, /*  8:                   PLUS shift  135 */
+  {  74,   0, 133}, /*  9:                   LIKE shift  133 */
+  {  78,   0, 108}, /* 10:                     LT shift  108 */
+  {  10,   0, 153}, /* 11:                BETWEEN shift  153 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+  {  96,   4, 143}, /* 13:                    REM shift  143 */
+  {  69,   7, 147}, /* 14:                 ISNULL shift  147 */
+  {  42,   0, 118}, /* 15:                     EQ shift  118 */
+  {  80,  17, 137}, /* 16:                  MINUS shift  137 */
+  {  52,  20, 134}, /* 17:                   GLOB shift  134 */
+  {  73,   0, 112}, /* 18:                     LE shift  112 */
+  { 102,   9, 126}, /* 19:                 RSHIFT shift  126 */
+  {  24,   0, 145}, /* 20:                 CONCAT shift  145 */
+  {  54,   0, 110}, /* 21:                     GT shift  110 */
+  {  77,   0, 124}, /* 22:                 LSHIFT shift  124 */
+  { 106,  10, 141}, /* 23:                  SLASH shift  141 */
+  {  51,   0, 114}, /* 24:                     GE shift  114 */
+  { 108,  16, 139}, /* 25:                   STAR shift  139 */
+  {  81,   0, 116}, /* 26:                     NE shift  116 */
+  {  82,  21, 130}, /* 27:                    NOT shift  130 */
+  {  83,   0, 152}, /* 28:                NOTNULL shift  152 */
+/* State 186 */
+  {  76,   0, 187}, /*  1:                     LP shift  187 */
+/* State 187 */
+  {  45,   3, 198}, /*  1:                   FAIL shift  198 */
+  {  57,   1, 188}, /*  2:                 IGNORE shift  188 */
+  {   1,   0, 194}, /*  3:                  ABORT shift  194 */
+  {  99,   0, 190}, /*  4:               ROLLBACK shift  190 */
+/* State 188 */
+  { 101,   0, 189}, /*  1:                     RP shift  189 */
+/* State 190 */
+  {  21,   0, 191}, /*  1:                  COMMA shift  191 */
+/* State 191 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 192}, /*  2:                     nm shift  192 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 192 */
+  { 101,   0, 193}, /*  1:                     RP shift  193 */
+/* State 194 */
+  {  21,   0, 195}, /*  1:                  COMMA shift  195 */
+/* State 195 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 196}, /*  2:                     nm shift  196 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 196 */
+  { 101,   0, 197}, /*  1:                     RP shift  197 */
+/* State 198 */
+  {  21,   0, 199}, /*  1:                  COMMA shift  199 */
+/* State 199 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 200}, /*  2:                     nm shift  200 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 200 */
+  { 101,   0, 201}, /*  1:                     RP shift  201 */
+/* State 202 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 203}, /*  3:                   expr shift  203 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 203 */
+  {  60,   0, 157}, /*  1:                     IN shift  157 */
+  {  88,   0, 106}, /*  2:                     OR shift  106 */
+  {  89,   1,  99}, /*  3:      ORACLE_OUTER_JOIN shift  99 */
+  {  10,   0, 153}, /*  4:                BETWEEN shift  153 */
+  {  91,   0, 135}, /*  5:                   PLUS shift  135 */
+  {   5,   0, 100}, /*  6:                    AND shift  100 */
+  {  40,   8, 752}, /*  7:                    END reduce 221 */
+  {  11,   0, 120}, /*  8:                 BITAND shift  120 */
+  {  13,   0, 122}, /*  9:                  BITOR shift  122 */
+  {  96,   0, 143}, /* 10:                    REM shift  143 */
+  {  68,   4, 148}, /* 11:                     IS shift  148 */
+  {  69,   7, 147}, /* 12:                 ISNULL shift  147 */
+  {  73,   0, 112}, /* 13:                     LE shift  112 */
+  {  42,   9, 118}, /* 14:                     EQ shift  118 */
+  {  77,   0, 124}, /* 15:                 LSHIFT shift  124 */
+  { 102,  13, 126}, /* 16:                 RSHIFT shift  126 */
+  {  74,   0, 133}, /* 17:                   LIKE shift  133 */
+  {  51,   0, 114}, /* 18:                     GE shift  114 */
+  {  52,   0, 134}, /* 19:                   GLOB shift  134 */
+  { 106,  15, 141}, /* 20:                  SLASH shift  141 */
+  {  78,   0, 108}, /* 21:                     LT shift  108 */
+  { 108,   0, 139}, /* 22:                   STAR shift  139 */
+  {  80,  18, 137}, /* 23:                  MINUS shift  137 */
+  {  81,  19, 116}, /* 24:                     NE shift  116 */
+  {  82,  27, 130}, /* 25:                    NOT shift  130 */
+  {  83,  29, 152}, /* 26:                NOTNULL shift  152 */
+  {  24,   0, 145}, /* 27:                 CONCAT shift  145 */
+  { 172,   0, 128}, /* 28:                 likeop shift  128 */
+  {  54,   0, 110}, /* 29:                     GT shift  110 */
+/* State 204 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 205}, /*  3:                   expr shift  205 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 205 */
+  {  60,   0, 157}, /*  1:                     IN shift  157 */
+  {  88,   0, 106}, /*  2:                     OR shift  106 */
+  {  89,   1,  99}, /*  3:      ORACLE_OUTER_JOIN shift  99 */
+  {  10,   0, 153}, /*  4:                BETWEEN shift  153 */
+  {  91,   0, 135}, /*  5:                   PLUS shift  135 */
+  {   5,   0, 100}, /*  6:                    AND shift  100 */
+  {  11,   0, 120}, /*  7:                 BITAND shift  120 */
+  {  13,   0, 122}, /*  8:                  BITOR shift  122 */
+  {  73,   0, 112}, /*  9:                     LE shift  112 */
+  {  96,   0, 143}, /* 10:                    REM shift  143 */
+  {  68,   4, 148}, /* 11:                     IS shift  148 */
+  {  69,   7, 147}, /* 12:                 ISNULL shift  147 */
+  {  77,   0, 124}, /* 13:                 LSHIFT shift  124 */
+  {  42,   8, 118}, /* 14:                     EQ shift  118 */
+  {  51,   0, 114}, /* 15:                     GE shift  114 */
+  { 102,   9, 126}, /* 16:                 RSHIFT shift  126 */
+  {  74,   0, 133}, /* 17:                   LIKE shift  133 */
+  {  52,   0, 134}, /* 18:                   GLOB shift  134 */
+  {  24,   0, 145}, /* 19:                 CONCAT shift  145 */
+  { 106,  13, 141}, /* 20:                  SLASH shift  141 */
+  {  78,   0, 108}, /* 21:                     LT shift  108 */
+  { 108,   0, 139}, /* 22:                   STAR shift  139 */
+  {  80,  15, 137}, /* 23:                  MINUS shift  137 */
+  {  81,  18, 116}, /* 24:                     NE shift  116 */
+  {  82,  19, 130}, /* 25:                    NOT shift  130 */
+  {  83,  29, 152}, /* 26:                NOTNULL shift  152 */
+  { 113,   0, 206}, /* 27:                   THEN shift  206 */
+  { 172,   0, 128}, /* 28:                 likeop shift  128 */
+  {  54,   0, 110}, /* 29:                     GT shift  110 */
+/* State 206 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 207}, /*  3:                   expr shift  207 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 207 */
+  {  88,   2, 106}, /*  1:                     OR shift  106 */
+  {  60,   0, 157}, /*  2:                     IN shift  157 */
+  {   5,   0, 100}, /*  3:                    AND shift  100 */
+  {  68,   0, 148}, /*  4:                     IS shift  148 */
+  { 172,   1, 128}, /*  5:                 likeop shift  128 */
+  {  89,   3,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+  {  13,   0, 122}, /*  7:                  BITOR shift  122 */
+  {  91,   0, 135}, /*  8:                   PLUS shift  135 */
+  {  74,   0, 133}, /*  9:                   LIKE shift  133 */
+  {  78,   0, 108}, /* 10:                     LT shift  108 */
+  {  10,   0, 153}, /* 11:                BETWEEN shift  153 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+  {  96,   4, 143}, /* 13:                    REM shift  143 */
+  {  69,   7, 147}, /* 14:                 ISNULL shift  147 */
+  {  42,   0, 118}, /* 15:                     EQ shift  118 */
+  {  80,  17, 137}, /* 16:                  MINUS shift  137 */
+  {  52,  20, 134}, /* 17:                   GLOB shift  134 */
+  {  73,   0, 112}, /* 18:                     LE shift  112 */
+  { 102,   9, 126}, /* 19:                 RSHIFT shift  126 */
+  {  24,   0, 145}, /* 20:                 CONCAT shift  145 */
+  {  54,   0, 110}, /* 21:                     GT shift  110 */
+  {  77,   0, 124}, /* 22:                 LSHIFT shift  124 */
+  { 106,  10, 141}, /* 23:                  SLASH shift  141 */
+  {  51,   0, 114}, /* 24:                     GE shift  114 */
+  { 108,  16, 139}, /* 25:                   STAR shift  139 */
+  {  81,   0, 116}, /* 26:                     NE shift  116 */
+  {  82,  21, 130}, /* 27:                    NOT shift  130 */
+  {  83,   0, 152}, /* 28:                NOTNULL shift  152 */
+/* State 208 */
+  {  21,   0, 210}, /*  1:                  COMMA shift  210 */
+  { 101,   1, 209}, /*  2:                     RP shift  209 */
+/* State 210 */
+  {  80,   4, 172}, /*  1:                  MINUS shift  172 */
+  { 177,   6, 102}, /*  2:                     nm shift  102 */
+  {  82,   0, 168}, /*  3:                    NOT shift  168 */
+  {  16,   0, 176}, /*  4:                   CASE shift  176 */
+  {  84,   0, 101}, /*  5:                   NULL shift  101 */
+  {  65,   0, 166}, /*  6:                INTEGER shift  166 */
+  {  56,   0,  64}, /*  7:                     ID shift  64 */
+  {  71,   0,  67}, /*  8:                JOIN_KW shift  67 */
+  { 152,   7, 165}, /*  9:                   expr shift  165 */
+  { 153,   0, 211}, /* 10:               expritem shift  211 */
+  {  12,   0, 170}, /* 11:                 BITNOT shift  170 */
+  {  91,   0, 174}, /* 12:                   PLUS shift  174 */
+  {  76,  11,  68}, /* 13:                     LP shift  68 */
+  {  94,  16, 186}, /* 14:                  RAISE shift  186 */
+  { 110,  14,  66}, /* 15:                 STRING shift  66 */
+  {  46,   0, 167}, /* 16:                  FLOAT shift  167 */
+/* State 214 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 215}, /*  3:                   expr shift  215 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 215 */
+  {  88,   2, 106}, /*  1:                     OR shift  106 */
+  {  60,   0, 157}, /*  2:                     IN shift  157 */
+  {   5,   0, 216}, /*  3:                    AND shift  216 */
+  {  68,   0, 148}, /*  4:                     IS shift  148 */
+  { 172,   1, 128}, /*  5:                 likeop shift  128 */
+  {  89,   3,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+  {  13,   0, 122}, /*  7:                  BITOR shift  122 */
+  {  91,   0, 135}, /*  8:                   PLUS shift  135 */
+  {  74,   0, 133}, /*  9:                   LIKE shift  133 */
+  {  78,   0, 108}, /* 10:                     LT shift  108 */
+  {  10,   0, 153}, /* 11:                BETWEEN shift  153 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+  {  96,   4, 143}, /* 13:                    REM shift  143 */
+  {  69,   7, 147}, /* 14:                 ISNULL shift  147 */
+  {  42,   0, 118}, /* 15:                     EQ shift  118 */
+  {  80,  17, 137}, /* 16:                  MINUS shift  137 */
+  {  52,  20, 134}, /* 17:                   GLOB shift  134 */
+  {  73,   0, 112}, /* 18:                     LE shift  112 */
+  { 102,   9, 126}, /* 19:                 RSHIFT shift  126 */
+  {  24,   0, 145}, /* 20:                 CONCAT shift  145 */
+  {  54,   0, 110}, /* 21:                     GT shift  110 */
+  {  77,   0, 124}, /* 22:                 LSHIFT shift  124 */
+  { 106,  10, 141}, /* 23:                  SLASH shift  141 */
+  {  51,   0, 114}, /* 24:                     GE shift  114 */
+  { 108,  16, 139}, /* 25:                   STAR shift  139 */
+  {  81,   0, 116}, /* 26:                     NE shift  116 */
+  {  82,  21, 130}, /* 27:                    NOT shift  130 */
+  {  83,   0, 152}, /* 28:                NOTNULL shift  152 */
+/* State 216 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 217}, /*  3:                   expr shift  217 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 217 */
+  {  78,   2, 108}, /*  1:                     LT shift  108 */
+  {  52,   0, 134}, /*  2:                   GLOB shift  134 */
+  { 106,   7, 141}, /*  3:                  SLASH shift  141 */
+  {  81,   0, 116}, /*  4:                     NE shift  116 */
+  { 108,   8, 139}, /*  5:                   STAR shift  139 */
+  {  83,   0, 152}, /*  6:                NOTNULL shift  152 */
+  {  80,  10, 137}, /*  7:                  MINUS shift  137 */
+  {  82,   0, 130}, /*  8:                    NOT shift  130 */
+  {  60,   0, 157}, /*  9:                     IN shift  157 */
+  {  54,   0, 110}, /* 10:                     GT shift  110 */
+  {  10,   0, 153}, /* 11:                BETWEEN shift  153 */
+  {  89,  13,  99}, /* 12:      ORACLE_OUTER_JOIN shift  99 */
+  {  11,   0, 120}, /* 13:                 BITAND shift  120 */
+  {  91,  15, 135}, /* 14:                   PLUS shift  135 */
+  {  13,   0, 122}, /* 15:                  BITOR shift  122 */
+  {  68,  20, 148}, /* 16:                     IS shift  148 */
+  { 172,  16, 128}, /* 17:                 likeop shift  128 */
+  {  69,   0, 147}, /* 18:                 ISNULL shift  147 */
+  {  96,   0, 143}, /* 19:                    REM shift  143 */
+  {  42,   0, 118}, /* 20:                     EQ shift  118 */
+  {  24,   0, 145}, /* 21:                 CONCAT shift  145 */
+  {  73,   0, 112}, /* 22:                     LE shift  112 */
+  {  74,   0, 133}, /* 23:                   LIKE shift  133 */
+  {  51,   0, 114}, /* 24:                     GE shift  114 */
+  { 102,  21, 126}, /* 25:                 RSHIFT shift  126 */
+  {  77,  24, 124}, /* 26:                 LSHIFT shift  124 */
+/* State 218 */
+  {  76,   0, 219}, /*  1:                     LP shift  219 */
+/* State 219 */
+  {  80,   0, 172}, /*  1:                  MINUS shift  172 */
+  { 181,   0,  69}, /*  2:              oneselect shift  69 */
+  {  82,   0, 168}, /*  3:                    NOT shift  168 */
+  { 103,   0,  73}, /*  4:                 SELECT shift  73 */
+  {  84,   0, 101}, /*  5:                   NULL shift  101 */
+  {  65,   0, 166}, /*  6:                INTEGER shift  166 */
+  {  46,   0, 167}, /*  7:                  FLOAT shift  167 */
+  {  71,   0,  67}, /*  8:                JOIN_KW shift  67 */
+  { 152,  10, 165}, /*  9:                   expr shift  165 */
+  {  12,   0, 170}, /* 10:                 BITNOT shift  170 */
+  { 110,   0,  66}, /* 11:                 STRING shift  66 */
+  {  91,   8, 174}, /* 12:                   PLUS shift  174 */
+  { 192,   9, 220}, /* 13:                 select shift  220 */
+  { 153,   0, 212}, /* 14:               expritem shift  212 */
+  { 154,  16, 222}, /* 15:               exprlist shift  222 */
+  {  94,   0, 186}, /* 16:                  RAISE shift  186 */
+  {  76,  19,  68}, /* 17:                     LP shift  68 */
+  { 177,   0, 102}, /* 18:                     nm shift  102 */
+  {  56,  20,  64}, /* 19:                     ID shift  64 */
+  {  16,   0, 176}, /* 20:                   CASE shift  176 */
+/* State 220 */
+  { 101,   3, 221}, /*  1:                     RP shift  221 */
+  { 176,   1,  71}, /*  2:         multiselect_op shift  71 */
+  {  66,   0, 162}, /*  3:              INTERSECT shift  162 */
+  { 118,   5, 160}, /*  4:                  UNION shift  160 */
+  {  43,   0, 163}, /*  5:                 EXCEPT shift  163 */
+/* State 222 */
+  {  21,   0, 210}, /*  1:                  COMMA shift  210 */
+  { 101,   1, 223}, /*  2:                     RP shift  223 */
+/* State 224 */
+  { 138,   0, 225}, /*  1:                collate shift  225 */
+  {  19,   0,  95}, /*  2:                COLLATE shift  95 */
+/* State 225 */
+  { 198,   0, 226}, /*  1:              sortorder shift  226 */
+  {  34,   3,  59}, /*  2:                   DESC shift  59 */
+  {   7,   0,  58}, /*  3:                    ASC shift  58 */
+/* State 227 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 228}, /*  3:                   expr shift  228 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 228 */
+  {  88,   2, 106}, /*  1:                     OR shift  106 */
+  {  60,   0, 157}, /*  2:                     IN shift  157 */
+  {   5,   0, 100}, /*  3:                    AND shift  100 */
+  {  68,   0, 148}, /*  4:                     IS shift  148 */
+  { 172,   1, 128}, /*  5:                 likeop shift  128 */
+  {  89,   3,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+  {  13,   0, 122}, /*  7:                  BITOR shift  122 */
+  {  91,   0, 135}, /*  8:                   PLUS shift  135 */
+  {  74,   0, 133}, /*  9:                   LIKE shift  133 */
+  {  78,   0, 108}, /* 10:                     LT shift  108 */
+  {  10,   0, 153}, /* 11:                BETWEEN shift  153 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+  {  96,   4, 143}, /* 13:                    REM shift  143 */
+  {  69,   7, 147}, /* 14:                 ISNULL shift  147 */
+  {  42,   0, 118}, /* 15:                     EQ shift  118 */
+  {  80,  17, 137}, /* 16:                  MINUS shift  137 */
+  {  52,  20, 134}, /* 17:                   GLOB shift  134 */
+  {  73,   0, 112}, /* 18:                     LE shift  112 */
+  { 102,   9, 126}, /* 19:                 RSHIFT shift  126 */
+  {  24,   0, 145}, /* 20:                 CONCAT shift  145 */
+  {  54,   0, 110}, /* 21:                     GT shift  110 */
+  {  77,   0, 124}, /* 22:                 LSHIFT shift  124 */
+  { 106,  10, 141}, /* 23:                  SLASH shift  141 */
+  {  51,   0, 114}, /* 24:                     GE shift  114 */
+  { 108,  16, 139}, /* 25:                   STAR shift  139 */
+  {  81,   0, 116}, /* 26:                     NE shift  116 */
+  {  82,  21, 130}, /* 27:                    NOT shift  130 */
+  {  83,   0, 152}, /* 28:                NOTNULL shift  152 */
+/* State 229 */
+  {  14,   0, 230}, /*  1:                     BY shift  230 */
+/* State 230 */
+  { 153,   0, 212}, /*  1:               expritem shift  212 */
+  { 154,   0, 231}, /*  2:               exprlist shift  231 */
+  {  76,   0,  68}, /*  3:                     LP shift  68 */
+  {  71,   0,  67}, /*  4:                JOIN_KW shift  67 */
+  {  46,  11, 167}, /*  5:                  FLOAT shift  167 */
+  {  56,   0,  64}, /*  6:                     ID shift  64 */
+  {  91,   0, 174}, /*  7:                   PLUS shift  174 */
+  { 177,   0, 102}, /*  8:                     nm shift  102 */
+  { 110,   3,  66}, /*  9:                 STRING shift  66 */
+  {  94,   0, 186}, /* 10:                  RAISE shift  186 */
+  {  12,   0, 170}, /* 11:                 BITNOT shift  170 */
+  {  65,   0, 166}, /* 12:                INTEGER shift  166 */
+  {  80,   5, 172}, /* 13:                  MINUS shift  172 */
+  {  84,  16, 101}, /* 14:                   NULL shift  101 */
+  {  82,  12, 168}, /* 15:                    NOT shift  168 */
+  {  16,   0, 176}, /* 16:                   CASE shift  176 */
+  { 152,  14, 165}, /* 17:                   expr shift  165 */
+/* State 231 */
+  {  21,   0, 210}, /*  1:                  COMMA shift  210 */
+/* State 232 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 233}, /*  3:                   expr shift  233 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 233 */
+  {  88,   2, 106}, /*  1:                     OR shift  106 */
+  {  60,   0, 157}, /*  2:                     IN shift  157 */
+  {   5,   0, 100}, /*  3:                    AND shift  100 */
+  {  68,   0, 148}, /*  4:                     IS shift  148 */
+  { 172,   1, 128}, /*  5:                 likeop shift  128 */
+  {  89,   3,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+  {  13,   0, 122}, /*  7:                  BITOR shift  122 */
+  {  91,   0, 135}, /*  8:                   PLUS shift  135 */
+  {  74,   0, 133}, /*  9:                   LIKE shift  133 */
+  {  78,   0, 108}, /* 10:                     LT shift  108 */
+  {  10,   0, 153}, /* 11:                BETWEEN shift  153 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+  {  96,   4, 143}, /* 13:                    REM shift  143 */
+  {  69,   7, 147}, /* 14:                 ISNULL shift  147 */
+  {  42,   0, 118}, /* 15:                     EQ shift  118 */
+  {  80,  17, 137}, /* 16:                  MINUS shift  137 */
+  {  52,  20, 134}, /* 17:                   GLOB shift  134 */
+  {  73,   0, 112}, /* 18:                     LE shift  112 */
+  { 102,   9, 126}, /* 19:                 RSHIFT shift  126 */
+  {  24,   0, 145}, /* 20:                 CONCAT shift  145 */
+  {  54,   0, 110}, /* 21:                     GT shift  110 */
+  {  77,   0, 124}, /* 22:                 LSHIFT shift  124 */
+  { 106,  10, 141}, /* 23:                  SLASH shift  141 */
+  {  51,   0, 114}, /* 24:                     GE shift  114 */
+  { 108,  16, 139}, /* 25:                   STAR shift  139 */
+  {  81,   0, 116}, /* 26:                     NE shift  116 */
+  {  82,  21, 130}, /* 27:                    NOT shift  130 */
+  {  83,   0, 152}, /* 28:                NOTNULL shift  152 */
+/* State 235 */
+  { 193,   0, 236}, /*  1:             seltablist shift  236 */
+  { 199,   1, 246}, /*  2:             stl_prefix shift  246 */
+/* State 236 */
+  {  70,   0, 239}, /*  1:                   JOIN shift  239 */
+  {  21,   0, 238}, /*  2:                  COMMA shift  238 */
+  { 170,   1, 237}, /*  3:                 joinop shift  237 */
+  {  71,   0, 240}, /*  4:                JOIN_KW shift  240 */
+/* State 240 */
+  { 110,   4,  21}, /*  1:                 STRING shift  21 */
+  {  71,   5,  22}, /*  2:                JOIN_KW shift  22 */
+  { 177,   0, 242}, /*  3:                     nm shift  242 */
+  {  70,   0, 241}, /*  4:                   JOIN shift  241 */
+  {  56,   0,  20}, /*  5:                     ID shift  20 */
+/* State 242 */
+  { 110,   4,  21}, /*  1:                 STRING shift  21 */
+  {  71,   5,  22}, /*  2:                JOIN_KW shift  22 */
+  { 177,   0, 244}, /*  3:                     nm shift  244 */
+  {  70,   0, 243}, /*  4:                   JOIN shift  243 */
+  {  56,   0,  20}, /*  5:                     ID shift  20 */
+/* State 244 */
+  {  70,   0, 245}, /*  1:                   JOIN shift  245 */
+/* State 246 */
+  { 110,   0,  21}, /*  1:                 STRING shift  21 */
+  {  76,   4, 266}, /*  2:                     LP shift  266 */
+  { 177,   0, 247}, /*  3:                     nm shift  247 */
+  {  71,   5,  22}, /*  4:                JOIN_KW shift  22 */
+  {  56,   0,  20}, /*  5:                     ID shift  20 */
+/* State 247 */
+  { 160,   3, 252}, /*  1:                    ids shift  252 */
+  {  56,   5, 248}, /*  2:                     ID shift  248 */
+  { 110,   0, 249}, /*  3:                 STRING shift  249 */
+  { 128,   0, 253}, /*  4:                     as shift  253 */
+  {   6,   0, 250}, /*  5:                     AS shift  250 */
+/* State 250 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 251}, /*  2:                     nm shift  251 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 253 */
+  {  87,   0, 264}, /*  1:                     ON shift  264 */
+  { 179,   1, 254}, /*  2:                 on_opt shift  254 */
+/* State 254 */
+  { 210,   2, 255}, /*  1:              using_opt shift  255 */
+  { 122,   0, 256}, /*  2:                  USING shift  256 */
+/* State 256 */
+  {  76,   0, 257}, /*  1:                     LP shift  257 */
+/* State 257 */
+  { 162,   0, 258}, /*  1:                idxlist shift  258 */
+  {  56,   0,  20}, /*  2:                     ID shift  20 */
+  { 110,   2,  21}, /*  3:                 STRING shift  21 */
+  { 177,   0, 262}, /*  4:                     nm shift  262 */
+  {  71,   0,  22}, /*  5:                JOIN_KW shift  22 */
+  { 161,   5, 263}, /*  6:                idxitem shift  263 */
+/* State 258 */
+  {  21,   0, 260}, /*  1:                  COMMA shift  260 */
+  { 101,   1, 259}, /*  2:                     RP shift  259 */
+/* State 260 */
+  { 110,   0,  21}, /*  1:                 STRING shift  21 */
+  { 161,   4, 261}, /*  2:                idxitem shift  261 */
+  { 177,   0, 262}, /*  3:                     nm shift  262 */
+  {  71,   5,  22}, /*  4:                JOIN_KW shift  22 */
+  {  56,   0,  20}, /*  5:                     ID shift  20 */
+/* State 264 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 265}, /*  3:                   expr shift  265 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 265 */
+  {  88,   2, 106}, /*  1:                     OR shift  106 */
+  {  60,   0, 157}, /*  2:                     IN shift  157 */
+  {   5,   0, 100}, /*  3:                    AND shift  100 */
+  {  68,   0, 148}, /*  4:                     IS shift  148 */
+  { 172,   1, 128}, /*  5:                 likeop shift  128 */
+  {  89,   3,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+  {  13,   0, 122}, /*  7:                  BITOR shift  122 */
+  {  91,   0, 135}, /*  8:                   PLUS shift  135 */
+  {  74,   0, 133}, /*  9:                   LIKE shift  133 */
+  {  78,   0, 108}, /* 10:                     LT shift  108 */
+  {  10,   0, 153}, /* 11:                BETWEEN shift  153 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+  {  96,   4, 143}, /* 13:                    REM shift  143 */
+  {  69,   7, 147}, /* 14:                 ISNULL shift  147 */
+  {  42,   0, 118}, /* 15:                     EQ shift  118 */
+  {  80,  17, 137}, /* 16:                  MINUS shift  137 */
+  {  52,  20, 134}, /* 17:                   GLOB shift  134 */
+  {  73,   0, 112}, /* 18:                     LE shift  112 */
+  { 102,   9, 126}, /* 19:                 RSHIFT shift  126 */
+  {  24,   0, 145}, /* 20:                 CONCAT shift  145 */
+  {  54,   0, 110}, /* 21:                     GT shift  110 */
+  {  77,   0, 124}, /* 22:                 LSHIFT shift  124 */
+  { 106,  10, 141}, /* 23:                  SLASH shift  141 */
+  {  51,   0, 114}, /* 24:                     GE shift  114 */
+  { 108,  16, 139}, /* 25:                   STAR shift  139 */
+  {  81,   0, 116}, /* 26:                     NE shift  116 */
+  {  82,  21, 130}, /* 27:                    NOT shift  130 */
+  {  83,   0, 152}, /* 28:                NOTNULL shift  152 */
+/* State 266 */
+  { 192,   0, 267}, /*  1:                 select shift  267 */
+  { 181,   3,  69}, /*  2:              oneselect shift  69 */
+  { 103,   0,  73}, /*  3:                 SELECT shift  73 */
+/* State 267 */
+  { 101,   3, 268}, /*  1:                     RP shift  268 */
+  { 176,   1,  71}, /*  2:         multiselect_op shift  71 */
+  {  66,   0, 162}, /*  3:              INTERSECT shift  162 */
+  { 118,   5, 160}, /*  4:                  UNION shift  160 */
+  {  43,   0, 163}, /*  5:                 EXCEPT shift  163 */
+/* State 268 */
+  { 160,   3, 252}, /*  1:                    ids shift  252 */
+  {  56,   5, 248}, /*  2:                     ID shift  248 */
+  { 110,   0, 249}, /*  3:                 STRING shift  249 */
+  { 128,   0, 269}, /*  4:                     as shift  269 */
+  {   6,   0, 250}, /*  5:                     AS shift  250 */
+/* State 269 */
+  {  87,   0, 264}, /*  1:                     ON shift  264 */
+  { 179,   1, 270}, /*  2:                 on_opt shift  270 */
+/* State 270 */
+  { 210,   2, 271}, /*  1:              using_opt shift  271 */
+  { 122,   0, 256}, /*  2:                  USING shift  256 */
+/* State 272 */
+  {  80,   4, 172}, /*  1:                  MINUS shift  172 */
+  { 177,   6, 276}, /*  2:                     nm shift  276 */
+  {  82,   0, 168}, /*  3:                    NOT shift  168 */
+  {  16,   0, 176}, /*  4:                   CASE shift  176 */
+  {  84,   0, 101}, /*  5:                   NULL shift  101 */
+  {  65,   0, 166}, /*  6:                INTEGER shift  166 */
+  {  56,   0,  64}, /*  7:                     ID shift  64 */
+  {  71,   0,  67}, /*  8:                JOIN_KW shift  67 */
+  { 152,   7, 273}, /*  9:                   expr shift  273 */
+  {  76,  11,  68}, /* 10:                     LP shift  68 */
+  {  12,   0, 170}, /* 11:                 BITNOT shift  170 */
+  {  91,   0, 174}, /* 12:                   PLUS shift  174 */
+  { 108,  10, 275}, /* 13:                   STAR shift  275 */
+  {  94,  16, 186}, /* 14:                  RAISE shift  186 */
+  { 110,  14,  66}, /* 15:                 STRING shift  66 */
+  {  46,   0, 167}, /* 16:                  FLOAT shift  167 */
+/* State 273 */
+  {  69,   0, 147}, /*  1:                 ISNULL shift  147 */
+  { 106,   5, 141}, /*  2:                  SLASH shift  141 */
+  {  68,   0, 148}, /*  3:                     IS shift  148 */
+  { 102,   1, 126}, /*  4:                 RSHIFT shift  126 */
+  {  73,   0, 112}, /*  5:                     LE shift  112 */
+  {   5,   0, 100}, /*  6:                    AND shift  100 */
+  {   6,   0, 250}, /*  7:                     AS shift  250 */
+  { 172,   2, 128}, /*  8:                 likeop shift  128 */
+  {  74,   0, 133}, /*  9:                   LIKE shift  133 */
+  { 108,  21, 139}, /* 10:                   STAR shift  139 */
+  {  10,   0, 153}, /* 11:                BETWEEN shift  153 */
+  { 110,  27, 249}, /* 12:                 STRING shift  249 */
+  {  78,   0, 108}, /* 13:                     LT shift  108 */
+  {  13,   0, 122}, /* 14:                  BITOR shift  122 */
+  {  80,   0, 137}, /* 15:                  MINUS shift  137 */
+  {  81,   0, 116}, /* 16:                     NE shift  116 */
+  {  82,   0, 130}, /* 17:                    NOT shift  130 */
+  {  83,   0, 152}, /* 18:                NOTNULL shift  152 */
+  {  51,   0, 114}, /* 19:                     GE shift  114 */
+  {  52,   0, 134}, /* 20:                   GLOB shift  134 */
+  {  42,   0, 118}, /* 21:                     EQ shift  118 */
+  {  54,   0, 110}, /* 22:                     GT shift  110 */
+  {  88,   0, 106}, /* 23:                     OR shift  106 */
+  {  89,  32,  99}, /* 24:      ORACLE_OUTER_JOIN shift  99 */
+  {  24,   0, 145}, /* 25:                 CONCAT shift  145 */
+  {  91,   0, 135}, /* 26:                   PLUS shift  135 */
+  {  77,  33, 124}, /* 27:                 LSHIFT shift  124 */
+  {  60,   0, 157}, /* 28:                     IN shift  157 */
+  { 160,   0, 252}, /* 29:                    ids shift  252 */
+  { 128,   0, 274}, /* 30:                     as shift  274 */
+  {  96,   0, 143}, /* 31:                    REM shift  143 */
+  {  56,   0, 248}, /* 32:                     ID shift  248 */
+  {  11,   0, 120}, /* 33:                 BITAND shift  120 */
+/* State 276 */
+  {  36,   0, 277}, /*  1:                    DOT shift  277 */
+/* State 277 */
+  { 110,   0,  21}, /*  1:                 STRING shift  21 */
+  {  71,   5,  22}, /*  2:                JOIN_KW shift  22 */
+  { 177,   0, 104}, /*  3:                     nm shift  104 */
+  { 108,   0, 278}, /*  4:                   STAR shift  278 */
+  {  56,   0,  20}, /*  5:                     ID shift  20 */
+/* State 282 */
+  {  60,   0, 157}, /*  1:                     IN shift  157 */
+  {  88,   0, 106}, /*  2:                     OR shift  106 */
+  {  89,   1,  99}, /*  3:      ORACLE_OUTER_JOIN shift  99 */
+  {  10,   0, 153}, /*  4:                BETWEEN shift  153 */
+  {  91,   0, 135}, /*  5:                   PLUS shift  135 */
+  {   5,   0, 100}, /*  6:                    AND shift  100 */
+  {  11,   0, 120}, /*  7:                 BITAND shift  120 */
+  {  13,   0, 122}, /*  8:                  BITOR shift  122 */
+  {  73,   0, 112}, /*  9:                     LE shift  112 */
+  {  96,   0, 143}, /* 10:                    REM shift  143 */
+  {  68,   4, 148}, /* 11:                     IS shift  148 */
+  {  69,   7, 147}, /* 12:                 ISNULL shift  147 */
+  {  77,   0, 124}, /* 13:                 LSHIFT shift  124 */
+  {  42,   8, 118}, /* 14:                     EQ shift  118 */
+  { 101,   0, 283}, /* 15:                     RP shift  283 */
+  { 102,   9, 126}, /* 16:                 RSHIFT shift  126 */
+  {  74,   0, 133}, /* 17:                   LIKE shift  133 */
+  {  51,   0, 114}, /* 18:                     GE shift  114 */
+  {  52,   0, 134}, /* 19:                   GLOB shift  134 */
+  { 106,  13, 141}, /* 20:                  SLASH shift  141 */
+  {  78,   0, 108}, /* 21:                     LT shift  108 */
+  { 108,   0, 139}, /* 22:                   STAR shift  139 */
+  {  80,  18, 137}, /* 23:                  MINUS shift  137 */
+  {  81,  19, 116}, /* 24:                     NE shift  116 */
+  {  82,  27, 130}, /* 25:                    NOT shift  130 */
+  {  83,  29, 152}, /* 26:                NOTNULL shift  152 */
+  {  24,   0, 145}, /* 27:                 CONCAT shift  145 */
+  { 172,   0, 128}, /* 28:                 likeop shift  128 */
+  {  54,   0, 110}, /* 29:                     GT shift  110 */
+/* State 284 */
+  {  21,   0, 210}, /*  1:                  COMMA shift  210 */
+  { 101,   1, 285}, /*  2:                     RP shift  285 */
+/* State 286 */
+  { 101,   0, 287}, /*  1:                     RP shift  287 */
+/* State 288 */
+  {  60,   0, 157}, /*  1:                     IN shift  157 */
+  {  88,   0, 106}, /*  2:                     OR shift  106 */
+  {  89,   1,  99}, /*  3:      ORACLE_OUTER_JOIN shift  99 */
+  {  10,   0, 153}, /*  4:                BETWEEN shift  153 */
+  {  91,   0, 135}, /*  5:                   PLUS shift  135 */
+  {   5,   0, 100}, /*  6:                    AND shift  100 */
+  {  11,   0, 120}, /*  7:                 BITAND shift  120 */
+  {  13,   0, 122}, /*  8:                  BITOR shift  122 */
+  {  73,   0, 112}, /*  9:                     LE shift  112 */
+  {  96,   0, 143}, /* 10:                    REM shift  143 */
+  {  68,   4, 148}, /* 11:                     IS shift  148 */
+  {  69,   7, 147}, /* 12:                 ISNULL shift  147 */
+  {  77,   0, 124}, /* 13:                 LSHIFT shift  124 */
+  {  42,   8, 118}, /* 14:                     EQ shift  118 */
+  { 101,   0, 289}, /* 15:                     RP shift  289 */
+  { 102,   9, 126}, /* 16:                 RSHIFT shift  126 */
+  {  74,   0, 133}, /* 17:                   LIKE shift  133 */
+  {  51,   0, 114}, /* 18:                     GE shift  114 */
+  {  52,   0, 134}, /* 19:                   GLOB shift  134 */
+  { 106,  13, 141}, /* 20:                  SLASH shift  141 */
+  {  78,   0, 108}, /* 21:                     LT shift  108 */
+  { 108,   0, 139}, /* 22:                   STAR shift  139 */
+  {  80,  18, 137}, /* 23:                  MINUS shift  137 */
+  {  81,  19, 116}, /* 24:                     NE shift  116 */
+  {  82,  27, 130}, /* 25:                    NOT shift  130 */
+  {  83,  29, 152}, /* 26:                NOTNULL shift  152 */
+  {  24,   0, 145}, /* 27:                 CONCAT shift  145 */
+  { 172,   0, 128}, /* 28:                 likeop shift  128 */
+  {  54,   0, 110}, /* 29:                     GT shift  110 */
+/* State 289 */
+  { 180,   0, 290}, /*  1:                 onconf shift  290 */
+  {  87,   0,  10}, /*  2:                     ON shift  10 */
+/* State 291 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 292}, /*  2:                     nm shift  292 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 292 */
+  {  76,   0, 310}, /*  1:                     LP shift  310 */
+  { 163,   0, 293}, /*  2:            idxlist_opt shift  293 */
+/* State 293 */
+  { 188,   0, 294}, /*  1:                refargs shift  294 */
+/* State 294 */
+  {  87,   0, 298}, /*  1:                     ON shift  298 */
+  { 187,   3, 295}, /*  2:                 refarg shift  295 */
+  {  79,   0, 296}, /*  3:                  MATCH shift  296 */
+/* State 296 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 297}, /*  2:                     nm shift  297 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 298 */
+  { 120,   2, 306}, /*  1:                 UPDATE shift  306 */
+  {  63,   0, 308}, /*  2:                 INSERT shift  308 */
+  {  32,   0, 299}, /*  3:                 DELETE shift  299 */
+/* State 299 */
+  {  98,   0, 305}, /*  1:               RESTRICT shift  305 */
+  { 105,   0, 301}, /*  2:                    SET shift  301 */
+  { 186,   1, 300}, /*  3:                 refact shift  300 */
+  {  15,   0, 304}, /*  4:                CASCADE shift  304 */
+/* State 301 */
+  {  84,   0, 302}, /*  1:                   NULL shift  302 */
+  {  29,   0, 303}, /*  2:                DEFAULT shift  303 */
+/* State 306 */
+  {  98,   0, 305}, /*  1:               RESTRICT shift  305 */
+  { 105,   0, 301}, /*  2:                    SET shift  301 */
+  { 186,   1, 307}, /*  3:                 refact shift  307 */
+  {  15,   0, 304}, /*  4:                CASCADE shift  304 */
+/* State 308 */
+  {  98,   0, 305}, /*  1:               RESTRICT shift  305 */
+  { 105,   0, 301}, /*  2:                    SET shift  301 */
+  { 186,   1, 309}, /*  3:                 refact shift  309 */
+  {  15,   0, 304}, /*  4:                CASCADE shift  304 */
+/* State 310 */
+  { 162,   0, 311}, /*  1:                idxlist shift  311 */
+  {  56,   0,  20}, /*  2:                     ID shift  20 */
+  { 110,   2,  21}, /*  3:                 STRING shift  21 */
+  { 177,   0, 262}, /*  4:                     nm shift  262 */
+  {  71,   0,  22}, /*  5:                JOIN_KW shift  22 */
+  { 161,   5, 263}, /*  6:                idxitem shift  263 */
+/* State 311 */
+  {  21,   0, 260}, /*  1:                  COMMA shift  260 */
+  { 101,   1, 312}, /*  2:                     RP shift  312 */
+/* State 314 */
+  {  56,   0,  96}, /*  1:                     ID shift  96 */
+  { 159,   0, 315}, /*  2:                     id shift  315 */
+/* State 316 */
+  { 164,   2, 317}, /*  1: init_deferred_pred_opt shift  317 */
+  {  62,   0,  51}, /*  2:              INITIALLY shift  51 */
+/* State 319 */
+  {  91,   2, 323}, /*  1:                   PLUS shift  323 */
+  {  84,   7, 330}, /*  2:                   NULL shift  330 */
+  {  65,   0, 322}, /*  3:                INTEGER shift  322 */
+  {  80,   0, 326}, /*  4:                  MINUS shift  326 */
+  {  46,   0, 329}, /*  5:                  FLOAT shift  329 */
+  { 110,   0, 320}, /*  6:                 STRING shift  320 */
+  {  56,   0, 321}, /*  7:                     ID shift  321 */
+/* State 323 */
+  {  46,   0, 325}, /*  1:                  FLOAT shift  325 */
+  {  65,   0, 324}, /*  2:                INTEGER shift  324 */
+/* State 326 */
+  {  46,   0, 328}, /*  1:                  FLOAT shift  328 */
+  {  65,   0, 327}, /*  2:                INTEGER shift  327 */
+/* State 331 */
+  { 160,   2, 343}, /*  1:                    ids shift  343 */
+  {  76,   4, 332}, /*  2:                     LP shift  332 */
+  { 110,   0, 249}, /*  3:                 STRING shift  249 */
+  {  56,   0, 248}, /*  4:                     ID shift  248 */
+/* State 332 */
+  {  80,   0, 341}, /*  1:                  MINUS shift  341 */
+  {  65,   0, 338}, /*  2:                INTEGER shift  338 */
+  {  91,   0, 339}, /*  3:                   PLUS shift  339 */
+  { 195,   3, 333}, /*  4:                 signed shift  333 */
+/* State 333 */
+  {  21,   0, 335}, /*  1:                  COMMA shift  335 */
+  { 101,   1, 334}, /*  2:                     RP shift  334 */
+/* State 335 */
+  {  80,   0, 341}, /*  1:                  MINUS shift  341 */
+  {  65,   0, 338}, /*  2:                INTEGER shift  338 */
+  {  91,   0, 339}, /*  3:                   PLUS shift  339 */
+  { 195,   3, 336}, /*  4:                 signed shift  336 */
+/* State 336 */
+  { 101,   0, 337}, /*  1:                     RP shift  337 */
+/* State 339 */
+  {  65,   0, 340}, /*  1:                INTEGER shift  340 */
+/* State 341 */
+  {  65,   0, 342}, /*  1:                INTEGER shift  342 */
+/* State 346 */
+  { 200,   4, 377}, /*  1:                  tcons shift  377 */
+  {  17,   0, 362}, /*  2:                  CHECK shift  362 */
+  {  26,   0, 349}, /*  3:             CONSTRAINT shift  349 */
+  {  48,   0, 365}, /*  4:                FOREIGN shift  365 */
+  {  93,   7, 351}, /*  5:                PRIMARY shift  351 */
+  { 101,   5, 608}, /*  6:                     RP reduce 77 */
+  {  21,   0, 347}, /*  7:                  COMMA shift  347 */
+  { 119,   0, 357}, /*  8:                 UNIQUE shift  357 */
+/* State 347 */
+  {  48,   0, 365}, /*  1:                FOREIGN shift  365 */
+  {  26,   0, 349}, /*  2:             CONSTRAINT shift  349 */
+  { 200,   2, 348}, /*  3:                  tcons shift  348 */
+  {  93,   0, 351}, /*  4:                PRIMARY shift  351 */
+  {  17,   0, 362}, /*  5:                  CHECK shift  362 */
+  { 119,   5, 357}, /*  6:                 UNIQUE shift  357 */
+/* State 349 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 350}, /*  2:                     nm shift  350 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 351 */
+  {  72,   0, 352}, /*  1:                    KEY shift  352 */
+/* State 352 */
+  {  76,   0, 353}, /*  1:                     LP shift  353 */
+/* State 353 */
+  { 162,   0, 354}, /*  1:                idxlist shift  354 */
+  {  56,   0,  20}, /*  2:                     ID shift  20 */
+  { 110,   2,  21}, /*  3:                 STRING shift  21 */
+  { 177,   0, 262}, /*  4:                     nm shift  262 */
+  {  71,   0,  22}, /*  5:                JOIN_KW shift  22 */
+  { 161,   5, 263}, /*  6:                idxitem shift  263 */
+/* State 354 */
+  {  21,   0, 260}, /*  1:                  COMMA shift  260 */
+  { 101,   1, 355}, /*  2:                     RP shift  355 */
+/* State 355 */
+  { 180,   0, 356}, /*  1:                 onconf shift  356 */
+  {  87,   0,  10}, /*  2:                     ON shift  10 */
+/* State 357 */
+  {  76,   0, 358}, /*  1:                     LP shift  358 */
+/* State 358 */
+  { 162,   0, 359}, /*  1:                idxlist shift  359 */
+  {  56,   0,  20}, /*  2:                     ID shift  20 */
+  { 110,   2,  21}, /*  3:                 STRING shift  21 */
+  { 177,   0, 262}, /*  4:                     nm shift  262 */
+  {  71,   0,  22}, /*  5:                JOIN_KW shift  22 */
+  { 161,   5, 263}, /*  6:                idxitem shift  263 */
+/* State 359 */
+  {  21,   0, 260}, /*  1:                  COMMA shift  260 */
+  { 101,   1, 360}, /*  2:                     RP shift  360 */
+/* State 360 */
+  { 180,   0, 361}, /*  1:                 onconf shift  361 */
+  {  87,   0,  10}, /*  2:                     ON shift  10 */
+/* State 362 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 363}, /*  3:                   expr shift  363 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 363 */
+  { 180,   3, 364}, /*  1:                 onconf shift  364 */
+  {  91,   0, 135}, /*  2:                   PLUS shift  135 */
+  {  60,   0, 157}, /*  3:                     IN shift  157 */
+  {  42,   0, 118}, /*  4:                     EQ shift  118 */
+  {  13,   0, 122}, /*  5:                  BITOR shift  122 */
+  {   5,   0, 100}, /*  6:                    AND shift  100 */
+  {  96,   0, 143}, /*  7:                    REM shift  143 */
+  {  78,   0, 108}, /*  8:                     LT shift  108 */
+  {  68,   0, 148}, /*  9:                     IS shift  148 */
+  {  69,   0, 147}, /* 10:                 ISNULL shift  147 */
+  {  10,   0, 153}, /* 11:                BETWEEN shift  153 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+  { 102,   4, 126}, /* 13:                 RSHIFT shift  126 */
+  {  73,   5, 112}, /* 14:                     LE shift  112 */
+  {  74,   0, 133}, /* 15:                   LIKE shift  133 */
+  {  51,   0, 114}, /* 16:                     GE shift  114 */
+  { 106,   0, 141}, /* 17:                  SLASH shift  141 */
+  {  77,   0, 124}, /* 18:                 LSHIFT shift  124 */
+  { 108,   8, 139}, /* 19:                   STAR shift  139 */
+  {  82,  26, 130}, /* 20:                    NOT shift  130 */
+  {  80,   0, 137}, /* 21:                  MINUS shift  137 */
+  {  81,  16, 116}, /* 22:                     NE shift  116 */
+  { 172,  20, 128}, /* 23:                 likeop shift  128 */
+  {  83,   0, 152}, /* 24:                NOTNULL shift  152 */
+  {  54,  27, 110}, /* 25:                     GT shift  110 */
+  {  52,   0, 134}, /* 26:                   GLOB shift  134 */
+  {  24,   0, 145}, /* 27:                 CONCAT shift  145 */
+  {  87,   0,  10}, /* 28:                     ON shift  10 */
+  {  88,   0, 106}, /* 29:                     OR shift  106 */
+  {  89,   0,  99}, /* 30:      ORACLE_OUTER_JOIN shift  99 */
+/* State 365 */
+  {  72,   0, 366}, /*  1:                    KEY shift  366 */
+/* State 366 */
+  {  76,   0, 367}, /*  1:                     LP shift  367 */
+/* State 367 */
+  { 162,   0, 368}, /*  1:                idxlist shift  368 */
+  {  56,   0,  20}, /*  2:                     ID shift  20 */
+  { 110,   2,  21}, /*  3:                 STRING shift  21 */
+  { 177,   0, 262}, /*  4:                     nm shift  262 */
+  {  71,   0,  22}, /*  5:                JOIN_KW shift  22 */
+  { 161,   5, 263}, /*  6:                idxitem shift  263 */
+/* State 368 */
+  {  21,   0, 260}, /*  1:                  COMMA shift  260 */
+  { 101,   1, 369}, /*  2:                     RP shift  369 */
+/* State 369 */
+  {  95,   0, 370}, /*  1:             REFERENCES shift  370 */
+/* State 370 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 371}, /*  2:                     nm shift  371 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 371 */
+  {  76,   0, 310}, /*  1:                     LP shift  310 */
+  { 163,   0, 372}, /*  2:            idxlist_opt shift  372 */
+/* State 372 */
+  { 188,   0, 373}, /*  1:                refargs shift  373 */
+/* State 373 */
+  { 147,   0, 375}, /*  1:    defer_subclause_opt shift  375 */
+  {  30,   0, 316}, /*  2:             DEFERRABLE shift  316 */
+  {  79,   2, 296}, /*  3:                  MATCH shift  296 */
+  {  87,   0, 298}, /*  4:                     ON shift  298 */
+  {  82,   0, 374}, /*  5:                    NOT shift  374 */
+  { 187,   5, 295}, /*  6:                 refarg shift  295 */
+  { 146,   0, 376}, /*  7:        defer_subclause shift  376 */
+/* State 374 */
+  {  30,   0,  49}, /*  1:             DEFERRABLE shift  49 */
+/* State 380 */
+  { 192,   0, 381}, /*  1:                 select shift  381 */
+  { 181,   3,  69}, /*  2:              oneselect shift  69 */
+  { 103,   0,  73}, /*  3:                 SELECT shift  73 */
+/* State 381 */
+  {  66,   0, 162}, /*  1:              INTERSECT shift  162 */
+  { 176,   1,  71}, /*  2:         multiselect_op shift  71 */
+  {  43,   0, 163}, /*  3:                 EXCEPT shift  163 */
+  { 118,   3, 160}, /*  4:                  UNION shift  160 */
+  { 104,   0, 551}, /*  5:                   SEMI reduce 20 */
+/* State 382 */
+  {  61,   0, 762}, /*  1:                  INDEX reduce 231 */
+  { 115,   1, 401}, /*  2:                TRIGGER shift  401 */
+  { 119,   0, 400}, /*  3:                 UNIQUE shift  400 */
+  { 201,   0, 383}, /*  4:                   temp shift  383 */
+  { 112,   0, 390}, /*  5:                   TEMP shift  390 */
+  { 209,   3, 391}, /*  6:             uniqueflag shift  391 */
+/* State 383 */
+  { 111,   0, 384}, /*  1:                  TABLE shift  384 */
+  { 125,   1, 386}, /*  2:                   VIEW shift  386 */
+/* State 384 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 385}, /*  2:                     nm shift  385 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 386 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 387}, /*  2:                     nm shift  387 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 387 */
+  {   6,   0, 388}, /*  1:                     AS shift  388 */
+/* State 388 */
+  { 192,   0, 389}, /*  1:                 select shift  389 */
+  { 181,   3,  69}, /*  2:              oneselect shift  69 */
+  { 103,   0,  73}, /*  3:                 SELECT shift  73 */
+/* State 389 */
+  {  66,   0, 162}, /*  1:              INTERSECT shift  162 */
+  { 176,   1,  71}, /*  2:         multiselect_op shift  71 */
+  {  43,   0, 163}, /*  3:                 EXCEPT shift  163 */
+  { 118,   3, 160}, /*  4:                  UNION shift  160 */
+  { 104,   0, 629}, /*  5:                   SEMI reduce 98 */
+/* State 391 */
+  {  61,   0, 392}, /*  1:                  INDEX shift  392 */
+/* State 392 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 393}, /*  2:                     nm shift  393 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 393 */
+  {  87,   0, 394}, /*  1:                     ON shift  394 */
+/* State 394 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 395}, /*  2:                     nm shift  395 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 395 */
+  {  76,   0, 396}, /*  1:                     LP shift  396 */
+/* State 396 */
+  { 162,   0, 397}, /*  1:                idxlist shift  397 */
+  {  56,   0,  20}, /*  2:                     ID shift  20 */
+  { 110,   2,  21}, /*  3:                 STRING shift  21 */
+  { 177,   0, 262}, /*  4:                     nm shift  262 */
+  {  71,   0,  22}, /*  5:                JOIN_KW shift  22 */
+  { 161,   5, 263}, /*  6:                idxitem shift  263 */
+/* State 397 */
+  {  21,   0, 260}, /*  1:                  COMMA shift  260 */
+  { 101,   1, 398}, /*  2:                     RP shift  398 */
+/* State 398 */
+  { 180,   2, 399}, /*  1:                 onconf shift  399 */
+  {  87,   0,  10}, /*  2:                     ON shift  10 */
+  { 104,   0, 619}, /*  3:                   SEMI reduce 88 */
+/* State 399 */
+  { 104,   0, 760}, /*  1:                   SEMI reduce 229 */
+/* State 400 */
+  {  61,   0, 761}, /*  1:                  INDEX reduce 230 */
+/* State 401 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 402}, /*  2:                     nm shift  402 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 402 */
+  {  64,   2, 467}, /*  1:                INSTEAD shift  467 */
+  {   8,   0, 465}, /*  2:                 BEFORE shift  465 */
+  { 206,   4, 403}, /*  3:           trigger_time shift  403 */
+  {   2,   0, 466}, /*  4:                  AFTER shift  466 */
+/* State 403 */
+  { 120,   3, 462}, /*  1:                 UPDATE shift  462 */
+  { 205,   0, 404}, /*  2:          trigger_event shift  404 */
+  {  32,   0, 460}, /*  3:                 DELETE shift  460 */
+  {  63,   0, 461}, /*  4:                 INSERT shift  461 */
+/* State 404 */
+  {  87,   0, 405}, /*  1:                     ON shift  405 */
+/* State 405 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 406}, /*  2:                     nm shift  406 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 406 */
+  {  47,   0, 456}, /*  1:                    FOR shift  456 */
+  { 155,   1, 407}, /*  2:         foreach_clause shift  407 */
+/* State 407 */
+  { 126,   3, 454}, /*  1:                   WHEN shift  454 */
+  { 211,   0, 408}, /*  2:            when_clause shift  408 */
+  {   9,   0, 797}, /*  3:                  BEGIN reduce 266 */
+/* State 408 */
+  {   9,   0, 409}, /*  1:                  BEGIN shift  409 */
+/* State 409 */
+  {  63,   0, 431}, /*  1:                 INSERT shift  431 */
+  { 181,   0,  69}, /*  2:              oneselect shift  69 */
+  { 120,   0, 416}, /*  3:                 UPDATE shift  416 */
+  { 192,   3, 410}, /*  4:                 select shift  410 */
+  { 103,   8,  73}, /*  5:                 SELECT shift  73 */
+  { 203,   9, 413}, /*  6:            trigger_cmd shift  413 */
+  { 204,   0, 411}, /*  7:       trigger_cmd_list shift  411 */
+  {  40,   0, 800}, /*  8:                    END reduce 269 */
+  {  32,   0, 450}, /*  9:                 DELETE shift  450 */
+/* State 410 */
+  {  66,   0, 162}, /*  1:              INTERSECT shift  162 */
+  { 176,   1,  71}, /*  2:         multiselect_op shift  71 */
+  {  43,   0, 163}, /*  3:                 EXCEPT shift  163 */
+  { 118,   3, 160}, /*  4:                  UNION shift  160 */
+  { 104,   0, 805}, /*  5:                   SEMI reduce 274 */
+/* State 411 */
+  {  40,   0, 412}, /*  1:                    END shift  412 */
+/* State 412 */
+  { 104,   0, 785}, /*  1:                   SEMI reduce 254 */
+/* State 413 */
+  { 104,   0, 414}, /*  1:                   SEMI shift  414 */
+/* State 414 */
+  {  63,   0, 431}, /*  1:                 INSERT shift  431 */
+  { 181,   0,  69}, /*  2:              oneselect shift  69 */
+  { 120,   0, 416}, /*  3:                 UPDATE shift  416 */
+  { 192,   3, 410}, /*  4:                 select shift  410 */
+  { 103,   8,  73}, /*  5:                 SELECT shift  73 */
+  { 203,   9, 413}, /*  6:            trigger_cmd shift  413 */
+  { 204,   0, 415}, /*  7:       trigger_cmd_list shift  415 */
+  {  40,   0, 800}, /*  8:                    END reduce 269 */
+  {  32,   0, 450}, /*  9:                 DELETE shift  450 */
+/* State 415 */
+  {  40,   0, 799}, /*  1:                    END reduce 268 */
+/* State 416 */
+  { 182,   2, 419}, /*  1:                 orconf shift  419 */
+  {  88,   0, 417}, /*  2:                     OR shift  417 */
+/* State 417 */
+  {   1,   0,  14}, /*  1:                  ABORT shift  14 */
+  {  97,   1,  17}, /*  2:                REPLACE shift  17 */
+  {  99,   5,  13}, /*  3:               ROLLBACK shift  13 */
+  { 189,   3, 418}, /*  4:            resolvetype shift  418 */
+  {  57,   6,  16}, /*  5:                 IGNORE shift  16 */
+  {  45,   0,  15}, /*  6:                   FAIL shift  15 */
+/* State 419 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 420}, /*  2:                     nm shift  420 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 420 */
+  { 105,   0, 421}, /*  1:                    SET shift  421 */
+/* State 421 */
+  { 110,   0,  21}, /*  1:                 STRING shift  21 */
+  {  71,   4,  22}, /*  2:                JOIN_KW shift  22 */
+  { 177,   0, 428}, /*  3:                     nm shift  428 */
+  {  56,   0,  20}, /*  4:                     ID shift  20 */
+  { 194,   0, 422}, /*  5:                setlist shift  422 */
+/* State 422 */
+  { 212,   3, 427}, /*  1:              where_opt shift  427 */
+  {  21,   0, 423}, /*  2:                  COMMA shift  423 */
+  { 104,   0, 685}, /*  3:                   SEMI reduce 154 */
+  { 127,   0, 232}, /*  4:                  WHERE shift  232 */
+/* State 423 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 424}, /*  2:                     nm shift  424 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 424 */
+  {  42,   0, 425}, /*  1:                     EQ shift  425 */
+/* State 425 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 426}, /*  3:                   expr shift  426 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 426 */
+  {  88,   2, 106}, /*  1:                     OR shift  106 */
+  {  60,   0, 157}, /*  2:                     IN shift  157 */
+  {   5,   0, 100}, /*  3:                    AND shift  100 */
+  {  68,   0, 148}, /*  4:                     IS shift  148 */
+  { 172,   1, 128}, /*  5:                 likeop shift  128 */
+  {  89,   3,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+  {  13,   0, 122}, /*  7:                  BITOR shift  122 */
+  {  91,   0, 135}, /*  8:                   PLUS shift  135 */
+  {  74,   0, 133}, /*  9:                   LIKE shift  133 */
+  {  78,   0, 108}, /* 10:                     LT shift  108 */
+  {  10,   0, 153}, /* 11:                BETWEEN shift  153 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+  {  96,   4, 143}, /* 13:                    REM shift  143 */
+  {  69,   7, 147}, /* 14:                 ISNULL shift  147 */
+  {  42,   0, 118}, /* 15:                     EQ shift  118 */
+  {  80,  17, 137}, /* 16:                  MINUS shift  137 */
+  {  52,  20, 134}, /* 17:                   GLOB shift  134 */
+  {  73,   0, 112}, /* 18:                     LE shift  112 */
+  { 102,   9, 126}, /* 19:                 RSHIFT shift  126 */
+  {  24,   0, 145}, /* 20:                 CONCAT shift  145 */
+  {  54,   0, 110}, /* 21:                     GT shift  110 */
+  {  77,   0, 124}, /* 22:                 LSHIFT shift  124 */
+  { 106,  10, 141}, /* 23:                  SLASH shift  141 */
+  {  51,   0, 114}, /* 24:                     GE shift  114 */
+  { 108,  16, 139}, /* 25:                   STAR shift  139 */
+  {  81,   0, 116}, /* 26:                     NE shift  116 */
+  {  82,  21, 130}, /* 27:                    NOT shift  130 */
+  {  83,   0, 152}, /* 28:                NOTNULL shift  152 */
+/* State 427 */
+  { 104,   0, 801}, /*  1:                   SEMI reduce 270 */
+/* State 428 */
+  {  42,   0, 429}, /*  1:                     EQ shift  429 */
+/* State 429 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 430}, /*  3:                   expr shift  430 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 430 */
+  {  88,   2, 106}, /*  1:                     OR shift  106 */
+  {  60,   0, 157}, /*  2:                     IN shift  157 */
+  {   5,   0, 100}, /*  3:                    AND shift  100 */
+  {  68,   0, 148}, /*  4:                     IS shift  148 */
+  { 172,   1, 128}, /*  5:                 likeop shift  128 */
+  {  89,   3,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+  {  13,   0, 122}, /*  7:                  BITOR shift  122 */
+  {  91,   0, 135}, /*  8:                   PLUS shift  135 */
+  {  74,   0, 133}, /*  9:                   LIKE shift  133 */
+  {  78,   0, 108}, /* 10:                     LT shift  108 */
+  {  10,   0, 153}, /* 11:                BETWEEN shift  153 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+  {  96,   4, 143}, /* 13:                    REM shift  143 */
+  {  69,   7, 147}, /* 14:                 ISNULL shift  147 */
+  {  42,   0, 118}, /* 15:                     EQ shift  118 */
+  {  80,  17, 137}, /* 16:                  MINUS shift  137 */
+  {  52,  20, 134}, /* 17:                   GLOB shift  134 */
+  {  73,   0, 112}, /* 18:                     LE shift  112 */
+  { 102,   9, 126}, /* 19:                 RSHIFT shift  126 */
+  {  24,   0, 145}, /* 20:                 CONCAT shift  145 */
+  {  54,   0, 110}, /* 21:                     GT shift  110 */
+  {  77,   0, 124}, /* 22:                 LSHIFT shift  124 */
+  { 106,  10, 141}, /* 23:                  SLASH shift  141 */
+  {  51,   0, 114}, /* 24:                     GE shift  114 */
+  { 108,  16, 139}, /* 25:                   STAR shift  139 */
+  {  81,   0, 116}, /* 26:                     NE shift  116 */
+  {  82,  21, 130}, /* 27:                    NOT shift  130 */
+  {  83,   0, 152}, /* 28:                NOTNULL shift  152 */
+/* State 431 */
+  {  67,   0, 621}, /*  1:                   INTO reduce 90 */
+  {  88,   1, 417}, /*  2:                     OR shift  417 */
+  { 182,   0, 432}, /*  3:                 orconf shift  432 */
+/* State 432 */
+  {  67,   0, 433}, /*  1:                   INTO shift  433 */
+/* State 433 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 434}, /*  2:                     nm shift  434 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 434 */
+  {  76,   0, 435}, /*  1:                     LP shift  435 */
+  { 167,   0, 441}, /*  2:         inscollist_opt shift  441 */
+/* State 435 */
+  { 110,   0,  21}, /*  1:                 STRING shift  21 */
+  { 166,   4, 436}, /*  2:             inscollist shift  436 */
+  { 177,   0, 440}, /*  3:                     nm shift  440 */
+  {  71,   5,  22}, /*  4:                JOIN_KW shift  22 */
+  {  56,   0,  20}, /*  5:                     ID shift  20 */
+/* State 436 */
+  {  21,   0, 438}, /*  1:                  COMMA shift  438 */
+  { 101,   1, 437}, /*  2:                     RP shift  437 */
+/* State 438 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 439}, /*  2:                     nm shift  439 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 441 */
+  { 192,   3, 442}, /*  1:                 select shift  442 */
+  { 181,   0,  69}, /*  2:              oneselect shift  69 */
+  { 124,   0, 443}, /*  3:                 VALUES shift  443 */
+  { 103,   0,  73}, /*  4:                 SELECT shift  73 */
+/* State 442 */
+  {  66,   0, 162}, /*  1:              INTERSECT shift  162 */
+  { 176,   1,  71}, /*  2:         multiselect_op shift  71 */
+  {  43,   0, 163}, /*  3:                 EXCEPT shift  163 */
+  { 118,   3, 160}, /*  4:                  UNION shift  160 */
+  { 104,   0, 803}, /*  5:                   SEMI reduce 272 */
+/* State 443 */
+  {  76,   0, 444}, /*  1:                     LP shift  444 */
+/* State 444 */
+  {  80,   4, 172}, /*  1:                  MINUS shift  172 */
+  { 177,   6, 102}, /*  2:                     nm shift  102 */
+  {  82,   0, 168}, /*  3:                    NOT shift  168 */
+  {  16,   0, 176}, /*  4:                   CASE shift  176 */
+  {  84,   0, 101}, /*  5:                   NULL shift  101 */
+  {  65,   0, 166}, /*  6:                INTEGER shift  166 */
+  {  56,   0,  64}, /*  7:                     ID shift  64 */
+  {  71,   0,  67}, /*  8:                JOIN_KW shift  67 */
+  { 152,   7, 449}, /*  9:                   expr shift  449 */
+  { 169,   0, 445}, /* 10:               itemlist shift  445 */
+  {  12,   0, 170}, /* 11:                 BITNOT shift  170 */
+  {  91,   0, 174}, /* 12:                   PLUS shift  174 */
+  {  76,  11,  68}, /* 13:                     LP shift  68 */
+  {  94,  16, 186}, /* 14:                  RAISE shift  186 */
+  { 110,  14,  66}, /* 15:                 STRING shift  66 */
+  {  46,   0, 167}, /* 16:                  FLOAT shift  167 */
+/* State 445 */
+  {  21,   0, 446}, /*  1:                  COMMA shift  446 */
+  { 101,   1, 448}, /*  2:                     RP shift  448 */
+/* State 446 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 447}, /*  3:                   expr shift  447 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 447 */
+  {  88,   2, 106}, /*  1:                     OR shift  106 */
+  {  60,   0, 157}, /*  2:                     IN shift  157 */
+  {   5,   0, 100}, /*  3:                    AND shift  100 */
+  {  68,   0, 148}, /*  4:                     IS shift  148 */
+  { 172,   1, 128}, /*  5:                 likeop shift  128 */
+  {  89,   3,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+  {  13,   0, 122}, /*  7:                  BITOR shift  122 */
+  {  91,   0, 135}, /*  8:                   PLUS shift  135 */
+  {  74,   0, 133}, /*  9:                   LIKE shift  133 */
+  {  78,   0, 108}, /* 10:                     LT shift  108 */
+  {  10,   0, 153}, /* 11:                BETWEEN shift  153 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+  {  96,   4, 143}, /* 13:                    REM shift  143 */
+  {  69,   7, 147}, /* 14:                 ISNULL shift  147 */
+  {  42,   0, 118}, /* 15:                     EQ shift  118 */
+  {  80,  17, 137}, /* 16:                  MINUS shift  137 */
+  {  52,  20, 134}, /* 17:                   GLOB shift  134 */
+  {  73,   0, 112}, /* 18:                     LE shift  112 */
+  { 102,   9, 126}, /* 19:                 RSHIFT shift  126 */
+  {  24,   0, 145}, /* 20:                 CONCAT shift  145 */
+  {  54,   0, 110}, /* 21:                     GT shift  110 */
+  {  77,   0, 124}, /* 22:                 LSHIFT shift  124 */
+  { 106,  10, 141}, /* 23:                  SLASH shift  141 */
+  {  51,   0, 114}, /* 24:                     GE shift  114 */
+  { 108,  16, 139}, /* 25:                   STAR shift  139 */
+  {  81,   0, 116}, /* 26:                     NE shift  116 */
+  {  82,  21, 130}, /* 27:                    NOT shift  130 */
+  {  83,   0, 152}, /* 28:                NOTNULL shift  152 */
+/* State 448 */
+  { 104,   0, 802}, /*  1:                   SEMI reduce 271 */
+/* State 449 */
+  {  88,   2, 106}, /*  1:                     OR shift  106 */
+  {  60,   0, 157}, /*  2:                     IN shift  157 */
+  {   5,   0, 100}, /*  3:                    AND shift  100 */
+  {  68,   0, 148}, /*  4:                     IS shift  148 */
+  { 172,   1, 128}, /*  5:                 likeop shift  128 */
+  {  89,   3,  99}, /*  6:      ORACLE_OUTER_JOIN shift  99 */
+  {  13,   0, 122}, /*  7:                  BITOR shift  122 */
+  {  91,   0, 135}, /*  8:                   PLUS shift  135 */
+  {  74,   0, 133}, /*  9:                   LIKE shift  133 */
+  {  78,   0, 108}, /* 10:                     LT shift  108 */
+  {  10,   0, 153}, /* 11:                BETWEEN shift  153 */
+  {  11,   0, 120}, /* 12:                 BITAND shift  120 */
+  {  96,   4, 143}, /* 13:                    REM shift  143 */
+  {  69,   7, 147}, /* 14:                 ISNULL shift  147 */
+  {  42,   0, 118}, /* 15:                     EQ shift  118 */
+  {  80,  17, 137}, /* 16:                  MINUS shift  137 */
+  {  52,  20, 134}, /* 17:                   GLOB shift  134 */
+  {  73,   0, 112}, /* 18:                     LE shift  112 */
+  { 102,   9, 126}, /* 19:                 RSHIFT shift  126 */
+  {  24,   0, 145}, /* 20:                 CONCAT shift  145 */
+  {  54,   0, 110}, /* 21:                     GT shift  110 */
+  {  77,   0, 124}, /* 22:                 LSHIFT shift  124 */
+  { 106,  10, 141}, /* 23:                  SLASH shift  141 */
+  {  51,   0, 114}, /* 24:                     GE shift  114 */
+  { 108,  16, 139}, /* 25:                   STAR shift  139 */
+  {  81,   0, 116}, /* 26:                     NE shift  116 */
+  {  82,  21, 130}, /* 27:                    NOT shift  130 */
+  {  83,   0, 152}, /* 28:                NOTNULL shift  152 */
+/* State 450 */
+  {  49,   0, 451}, /*  1:                   FROM shift  451 */
+/* State 451 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 452}, /*  2:                     nm shift  452 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 452 */
+  { 104,   0, 685}, /*  1:                   SEMI reduce 154 */
+  { 127,   0, 232}, /*  2:                  WHERE shift  232 */
+  { 212,   1, 453}, /*  3:              where_opt shift  453 */
+/* State 453 */
+  { 104,   0, 804}, /*  1:                   SEMI reduce 273 */
+/* State 454 */
+  {  76,   4,  68}, /*  1:                     LP shift  68 */
+  {  91,   1, 174}, /*  2:                   PLUS shift  174 */
+  { 152,   0, 455}, /*  3:                   expr shift  455 */
+  {  46,   7, 167}, /*  4:                  FLOAT shift  167 */
+  {  94,   0, 186}, /*  5:                  RAISE shift  186 */
+  { 110,   9,  66}, /*  6:                 STRING shift  66 */
+  {  16,   0, 176}, /*  7:                   CASE shift  176 */
+  {  82,   0, 168}, /*  8:                    NOT shift  168 */
+  {  80,  11, 172}, /*  9:                  MINUS shift  172 */
+  {  84,   0, 101}, /* 10:                   NULL shift  101 */
+  {  65,   0, 166}, /* 11:                INTEGER shift  166 */
+  {  71,  14,  67}, /* 12:                JOIN_KW shift  67 */
+  { 177,  15, 102}, /* 13:                     nm shift  102 */
+  {  56,   0,  64}, /* 14:                     ID shift  64 */
+  {  12,   0, 170}, /* 15:                 BITNOT shift  170 */
+/* State 455 */
+  {  60,   0, 157}, /*  1:                     IN shift  157 */
+  {  88,   0, 106}, /*  2:                     OR shift  106 */
+  {  89,   1,  99}, /*  3:      ORACLE_OUTER_JOIN shift  99 */
+  {   9,   0, 798}, /*  4:                  BEGIN reduce 267 */
+  {  91,   0, 135}, /*  5:                   PLUS shift  135 */
+  {   5,   0, 100}, /*  6:                    AND shift  100 */
+  {  10,   0, 153}, /*  7:                BETWEEN shift  153 */
+  {  11,   0, 120}, /*  8:                 BITAND shift  120 */
+  {  13,   0, 122}, /*  9:                  BITOR shift  122 */
+  {  96,   4, 143}, /* 10:                    REM shift  143 */
+  {  68,   7, 148}, /* 11:                     IS shift  148 */
+  {  69,   8, 147}, /* 12:                 ISNULL shift  147 */
+  {  73,   0, 112}, /* 13:                     LE shift  112 */
+  {  42,   9, 118}, /* 14:                     EQ shift  118 */
+  {  77,   0, 124}, /* 15:                 LSHIFT shift  124 */
+  { 102,  13, 126}, /* 16:                 RSHIFT shift  126 */
+  {  74,   0, 133}, /* 17:                   LIKE shift  133 */
+  {  51,   0, 114}, /* 18:                     GE shift  114 */
+  {  52,   0, 134}, /* 19:                   GLOB shift  134 */
+  { 106,  15, 141}, /* 20:                  SLASH shift  141 */
+  {  78,   0, 108}, /* 21:                     LT shift  108 */
+  { 108,   0, 139}, /* 22:                   STAR shift  139 */
+  {  80,  18, 137}, /* 23:                  MINUS shift  137 */
+  {  81,  19, 116}, /* 24:                     NE shift  116 */
+  {  82,  27, 130}, /* 25:                    NOT shift  130 */
+  {  83,  29, 152}, /* 26:                NOTNULL shift  152 */
+  {  24,   0, 145}, /* 27:                 CONCAT shift  145 */
+  { 172,   0, 128}, /* 28:                 likeop shift  128 */
+  {  54,   0, 110}, /* 29:                     GT shift  110 */
+/* State 456 */
+  {  38,   0, 457}, /*  1:                   EACH shift  457 */
+/* State 457 */
+  { 100,   0, 458}, /*  1:                    ROW shift  458 */
+  { 109,   0, 459}, /*  2:              STATEMENT shift  459 */
+/* State 460 */
+  {  87,   0, 790}, /*  1:                     ON reduce 259 */
+/* State 461 */
+  {  87,   0, 791}, /*  1:                     ON reduce 260 */
+/* State 462 */
+  {  85,   0, 463}, /*  1:                     OF shift  463 */
+  {  87,   1, 792}, /*  2:                     ON reduce 261 */
+/* State 463 */
+  { 110,   0,  21}, /*  1:                 STRING shift  21 */
+  { 166,   4, 464}, /*  2:             inscollist shift  464 */
+  { 177,   0, 440}, /*  3:                     nm shift  440 */
+  {  71,   5,  22}, /*  4:                JOIN_KW shift  22 */
+  {  56,   0,  20}, /*  5:                     ID shift  20 */
+/* State 464 */
+  {  21,   0, 438}, /*  1:                  COMMA shift  438 */
+  {  87,   1, 793}, /*  2:                     ON reduce 262 */
+/* State 467 */
+  {  85,   0, 468}, /*  1:                     OF shift  468 */
+/* State 469 */
+  {  61,   0, 474}, /*  1:                  INDEX shift  474 */
+  { 125,   1, 472}, /*  2:                   VIEW shift  472 */
+  { 111,   0, 470}, /*  3:                  TABLE shift  470 */
+  { 115,   3, 476}, /*  4:                TRIGGER shift  476 */
+/* State 470 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 471}, /*  2:                     nm shift  471 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 471 */
+  { 104,   0, 628}, /*  1:                   SEMI reduce 97 */
+/* State 472 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 473}, /*  2:                     nm shift  473 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 473 */
+  { 104,   0, 630}, /*  1:                   SEMI reduce 99 */
+/* State 474 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 475}, /*  2:                     nm shift  475 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 475 */
+  { 104,   0, 768}, /*  1:                   SEMI reduce 237 */
+/* State 476 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 477}, /*  2:                     nm shift  477 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 477 */
+  { 104,   0, 810}, /*  1:                   SEMI reduce 279 */
+/* State 478 */
+  {  66,   0, 162}, /*  1:              INTERSECT shift  162 */
+  { 176,   1,  71}, /*  2:         multiselect_op shift  71 */
+  {  43,   0, 163}, /*  3:                 EXCEPT shift  163 */
+  { 118,   3, 160}, /*  4:                  UNION shift  160 */
+  { 104,   0, 631}, /*  5:                   SEMI reduce 100 */
+/* State 479 */
+  {  49,   0, 480}, /*  1:                   FROM shift  480 */
+/* State 480 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 481}, /*  2:                     nm shift  481 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 481 */
+  { 104,   0, 685}, /*  1:                   SEMI reduce 154 */
+  { 127,   0, 232}, /*  2:                  WHERE shift  232 */
+  { 212,   1, 482}, /*  3:              where_opt shift  482 */
+/* State 482 */
+  { 104,   0, 684}, /*  1:                   SEMI reduce 153 */
+/* State 483 */
+  { 182,   2, 484}, /*  1:                 orconf shift  484 */
+  {  88,   0, 417}, /*  2:                     OR shift  417 */
+/* State 484 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 485}, /*  2:                     nm shift  485 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 485 */
+  { 105,   0, 486}, /*  1:                    SET shift  486 */
+/* State 486 */
+  { 110,   0,  21}, /*  1:                 STRING shift  21 */
+  {  71,   4,  22}, /*  2:                JOIN_KW shift  22 */
+  { 177,   0, 428}, /*  3:                     nm shift  428 */
+  {  56,   0,  20}, /*  4:                     ID shift  20 */
+  { 194,   0, 487}, /*  5:                setlist shift  487 */
+/* State 487 */
+  { 212,   3, 488}, /*  1:              where_opt shift  488 */
+  {  21,   0, 423}, /*  2:                  COMMA shift  423 */
+  { 104,   0, 685}, /*  3:                   SEMI reduce 154 */
+  { 127,   0, 232}, /*  4:                  WHERE shift  232 */
+/* State 488 */
+  { 104,   0, 687}, /*  1:                   SEMI reduce 156 */
+/* State 489 */
+  {  67,   0, 490}, /*  1:                   INTO shift  490 */
+/* State 490 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 491}, /*  2:                     nm shift  491 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 491 */
+  {  76,   0, 435}, /*  1:                     LP shift  435 */
+  { 167,   0, 492}, /*  2:         inscollist_opt shift  492 */
+/* State 492 */
+  { 192,   3, 493}, /*  1:                 select shift  493 */
+  { 181,   0,  69}, /*  2:              oneselect shift  69 */
+  { 124,   0, 494}, /*  3:                 VALUES shift  494 */
+  { 103,   0,  73}, /*  4:                 SELECT shift  73 */
+/* State 493 */
+  {  66,   0, 162}, /*  1:              INTERSECT shift  162 */
+  { 176,   1,  71}, /*  2:         multiselect_op shift  71 */
+  {  43,   0, 163}, /*  3:                 EXCEPT shift  163 */
+  { 118,   3, 160}, /*  4:                  UNION shift  160 */
+  { 104,   0, 691}, /*  5:                   SEMI reduce 160 */
+/* State 494 */
+  {  76,   0, 495}, /*  1:                     LP shift  495 */
+/* State 495 */
+  {  80,   4, 172}, /*  1:                  MINUS shift  172 */
+  { 177,   6, 102}, /*  2:                     nm shift  102 */
+  {  82,   0, 168}, /*  3:                    NOT shift  168 */
+  {  16,   0, 176}, /*  4:                   CASE shift  176 */
+  {  84,   0, 101}, /*  5:                   NULL shift  101 */
+  {  65,   0, 166}, /*  6:                INTEGER shift  166 */
+  {  56,   0,  64}, /*  7:                     ID shift  64 */
+  {  71,   0,  67}, /*  8:                JOIN_KW shift  67 */
+  { 152,   7, 449}, /*  9:                   expr shift  449 */
+  { 169,   0, 496}, /* 10:               itemlist shift  496 */
+  {  12,   0, 170}, /* 11:                 BITNOT shift  170 */
+  {  91,   0, 174}, /* 12:                   PLUS shift  174 */
+  {  76,  11,  68}, /* 13:                     LP shift  68 */
+  {  94,  16, 186}, /* 14:                  RAISE shift  186 */
+  { 110,  14,  66}, /* 15:                 STRING shift  66 */
+  {  46,   0, 167}, /* 16:                  FLOAT shift  167 */
+/* State 496 */
+  {  21,   0, 446}, /*  1:                  COMMA shift  446 */
+  { 101,   1, 497}, /*  2:                     RP shift  497 */
+/* State 497 */
+  { 104,   0, 690}, /*  1:                   SEMI reduce 159 */
+/* State 498 */
+  {  67,   0, 621}, /*  1:                   INTO reduce 90 */
+  {  88,   1, 417}, /*  2:                     OR shift  417 */
+  { 182,   0, 499}, /*  3:                 orconf shift  499 */
+/* State 499 */
+  {  67,   0, 692}, /*  1:                   INTO reduce 161 */
+/* State 500 */
+  {  67,   0, 693}, /*  1:                   INTO reduce 162 */
+/* State 501 */
+  { 182,   2, 502}, /*  1:                 orconf shift  502 */
+  {  88,   0, 417}, /*  2:                     OR shift  417 */
+/* State 502 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 503}, /*  2:                     nm shift  503 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 503 */
+  {  49,   0, 504}, /*  1:                   FROM shift  504 */
+/* State 504 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 505}, /*  2:                     nm shift  505 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 505 */
+  { 122,   2, 506}, /*  1:                  USING shift  506 */
+  { 104,   0, 770}, /*  2:                   SEMI reduce 239 */
+/* State 506 */
+  {  33,   0, 507}, /*  1:             DELIMITERS shift  507 */
+/* State 507 */
+  { 110,   0, 508}, /*  1:                 STRING shift  508 */
+/* State 508 */
+  { 104,   0, 769}, /*  1:                   SEMI reduce 238 */
+/* State 509 */
+  { 110,   0,  21}, /*  1:                 STRING shift  21 */
+  {  71,   4,  22}, /*  2:                JOIN_KW shift  22 */
+  { 177,   0, 510}, /*  3:                     nm shift  510 */
+  {  56,   0,  20}, /*  4:                     ID shift  20 */
+  { 104,   0, 771}, /*  5:                   SEMI reduce 240 */
+/* State 510 */
+  { 104,   0, 772}, /*  1:                   SEMI reduce 241 */
+/* State 511 */
+  {  56,   0, 248}, /*  1:                     ID shift  248 */
+  { 160,   0, 512}, /*  2:                    ids shift  512 */
+  { 110,   1, 249}, /*  3:                 STRING shift  249 */
+/* State 512 */
+  {  42,   0, 513}, /*  1:                     EQ shift  513 */
+  {  76,   0, 525}, /*  2:                     LP shift  525 */
+  { 104,   0, 778}, /*  3:                   SEMI reduce 247 */
+/* State 513 */
+  { 110,   3,  21}, /*  1:                 STRING shift  21 */
+  {  91,   4, 524}, /*  2:                   PLUS shift  524 */
+  {  80,   0, 522}, /*  3:                  MINUS shift  522 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+  { 184,   0, 516}, /*  5:               plus_num shift  516 */
+  { 185,   9, 518}, /*  6:               plus_opt shift  518 */
+  {  56,   0,  20}, /*  7:                     ID shift  20 */
+  { 177,  10, 514}, /*  8:                     nm shift  514 */
+  { 175,   0, 517}, /*  9:              minus_num shift  517 */
+  {  87,   0, 515}, /* 10:                     ON shift  515 */
+/* State 514 */
+  { 104,   0, 773}, /*  1:                   SEMI reduce 242 */
+/* State 515 */
+  { 104,   0, 774}, /*  1:                   SEMI reduce 243 */
+/* State 516 */
+  { 104,   0, 775}, /*  1:                   SEMI reduce 244 */
+/* State 517 */
+  { 104,   0, 776}, /*  1:                   SEMI reduce 245 */
+/* State 518 */
+  {  46,   0, 521}, /*  1:                  FLOAT shift  521 */
+  { 178,   1, 519}, /*  2:                 number shift  519 */
+  {  65,   0, 520}, /*  3:                INTEGER shift  520 */
+/* State 519 */
+  { 104,   0, 779}, /*  1:                   SEMI reduce 248 */
+/* State 520 */
+  { 104,   0, 781}, /*  1:                   SEMI reduce 250 */
+/* State 521 */
+  { 104,   0, 782}, /*  1:                   SEMI reduce 251 */
+/* State 522 */
+  {  46,   0, 521}, /*  1:                  FLOAT shift  521 */
+  { 178,   1, 523}, /*  2:                 number shift  523 */
+  {  65,   0, 520}, /*  3:                INTEGER shift  520 */
+/* State 523 */
+  { 104,   0, 780}, /*  1:                   SEMI reduce 249 */
+/* State 525 */
+  {  56,   0,  20}, /*  1:                     ID shift  20 */
+  { 177,   0, 526}, /*  2:                     nm shift  526 */
+  { 110,   0,  21}, /*  3:                 STRING shift  21 */
+  {  71,   0,  22}, /*  4:                JOIN_KW shift  22 */
+/* State 526 */
+  { 101,   0, 527}, /*  1:                     RP shift  527 */
+/* State 527 */
+  { 104,   0, 777}, /*  1:                   SEMI reduce 246 */
+};
+
+/* The state table contains information needed to look up the correct
+** action in the action table, given the current state of the parser.
+** Information needed includes:
+**
+**  +  A pointer to the start of the action hash table in yyActionTable.
+**
+**  +  The number of entries in the action hash table.
+**
+**  +  The default action.  This is the action to take if no entry for
+**     the given look-ahead is found in the action hash table.
+*/
+struct yyStateEntry {
+  const yyActionEntry *hashtbl;  /* Start of the hash table in yyActionTable */
+  YYCODETYPE nEntry;             /* Number of entries in action hash table */
+  YYACTIONTYPE actionDefault;    /* Default action if look-ahead not found */
+};
+typedef struct yyStateEntry yyStateEntry;
+static const yyStateEntry yyStateTable[] = {
+  { &yyActionTable[0],   6, 538 },
+  { &yyActionTable[6],   5, 538 },
+  { &yyActionTable[11],   0, 533 },
+  { &yyActionTable[11],  20, 811 },
+  { &yyActionTable[31],   1, 811 },
+  { &yyActionTable[32],   0, 534 },
+  { &yyActionTable[32],   1, 811 },
+  { &yyActionTable[33],   2, 540 },
+  { &yyActionTable[35],   3, 811 },
+  { &yyActionTable[38],   1, 811 },
+  { &yyActionTable[39],   1, 811 },
+  { &yyActionTable[40],   6, 811 },
+  { &yyActionTable[46],   0, 620 },
+  { &yyActionTable[46],   0, 623 },
+  { &yyActionTable[46],   0, 624 },
+  { &yyActionTable[46],   0, 625 },
+  { &yyActionTable[46],   0, 626 },
+  { &yyActionTable[46],   0, 627 },
+  { &yyActionTable[46],   4, 541 },
+  { &yyActionTable[50],   0, 542 },
+  { &yyActionTable[50],   0, 559 },
+  { &yyActionTable[50],   0, 560 },
+  { &yyActionTable[50],   0, 561 },
+  { &yyActionTable[50],   3, 811 },
+  { &yyActionTable[53],   1, 811 },
+  { &yyActionTable[54],   3, 811 },
+  { &yyActionTable[57],   1, 811 },
+  { &yyActionTable[58],   3, 811 },
+  { &yyActionTable[61],   1, 811 },
+  { &yyActionTable[62],   3, 811 },
+  { &yyActionTable[65],   1, 811 },
+  { &yyActionTable[66],   7, 811 },
+  { &yyActionTable[73],   3, 811 },
+  { &yyActionTable[76],   1, 811 },
+  { &yyActionTable[77],   1, 811 },
+  { &yyActionTable[78],  13, 811 },
+  { &yyActionTable[91],   0, 552 },
+  { &yyActionTable[91],   5, 562 },
+  { &yyActionTable[96],   1, 572 },
+  { &yyActionTable[97],  13, 554 },
+  { &yyActionTable[110],   0, 571 },
+  { &yyActionTable[110],   4, 811 },
+  { &yyActionTable[114],  10, 811 },
+  { &yyActionTable[124],   0, 573 },
+  { &yyActionTable[124],   2, 619 },
+  { &yyActionTable[126],   0, 584 },
+  { &yyActionTable[126],   2, 811 },
+  { &yyActionTable[128],   2, 619 },
+  { &yyActionTable[130],   0, 585 },
+  { &yyActionTable[130],   2, 604 },
+  { &yyActionTable[132],   0, 602 },
+  { &yyActionTable[132],   2, 811 },
+  { &yyActionTable[134],   0, 605 },
+  { &yyActionTable[134],   0, 606 },
+  { &yyActionTable[134],   1, 811 },
+  { &yyActionTable[135],   3, 672 },
+  { &yyActionTable[138],   2, 619 },
+  { &yyActionTable[140],   0, 586 },
+  { &yyActionTable[140],   0, 670 },
+  { &yyActionTable[140],   0, 671 },
+  { &yyActionTable[140],   2, 619 },
+  { &yyActionTable[142],   0, 587 },
+  { &yyActionTable[142],   1, 811 },
+  { &yyActionTable[143],  15, 811 },
+  { &yyActionTable[158],   2, 702 },
+  { &yyActionTable[160],  18, 759 },
+  { &yyActionTable[178],   1, 708 },
+  { &yyActionTable[179],   1, 703 },
+  { &yyActionTable[180],  18, 811 },
+  { &yyActionTable[198],   0, 632 },
+  { &yyActionTable[198],   5, 811 },
+  { &yyActionTable[203],   2, 811 },
+  { &yyActionTable[205],   0, 633 },
+  { &yyActionTable[205],   3, 641 },
+  { &yyActionTable[208],   2, 643 },
+  { &yyActionTable[210],   3, 650 },
+  { &yyActionTable[213],   2, 685 },
+  { &yyActionTable[215],   2, 675 },
+  { &yyActionTable[217],   2, 677 },
+  { &yyActionTable[219],   2, 665 },
+  { &yyActionTable[221],   2, 679 },
+  { &yyActionTable[223],   0, 638 },
+  { &yyActionTable[223],   1, 811 },
+  { &yyActionTable[224],   3, 680 },
+  { &yyActionTable[227],   1, 811 },
+  { &yyActionTable[228],   0, 681 },
+  { &yyActionTable[228],   1, 811 },
+  { &yyActionTable[229],   1, 811 },
+  { &yyActionTable[230],   1, 811 },
+  { &yyActionTable[231],  17, 811 },
+  { &yyActionTable[248],   1, 666 },
+  { &yyActionTable[249],  16, 811 },
+  { &yyActionTable[265],   2, 673 },
+  { &yyActionTable[267],   3, 672 },
+  { &yyActionTable[270],   0, 667 },
+  { &yyActionTable[270],   2, 811 },
+  { &yyActionTable[272],   0, 556 },
+  { &yyActionTable[272],   0, 674 },
+  { &yyActionTable[272],  28, 669 },
+  { &yyActionTable[300],   0, 705 },
+  { &yyActionTable[300],  15, 811 },
+  { &yyActionTable[315],   0, 701 },
+  { &yyActionTable[315],   1, 811 },
+  { &yyActionTable[316],   4, 811 },
+  { &yyActionTable[320],   0, 704 },
+  { &yyActionTable[320],  26, 711 },
+  { &yyActionTable[346],  15, 811 },
+  { &yyActionTable[361],  27, 712 },
+  { &yyActionTable[388],  15, 811 },
+  { &yyActionTable[403],  12, 713 },
+  { &yyActionTable[415],  15, 811 },
+  { &yyActionTable[430],  12, 714 },
+  { &yyActionTable[442],  15, 811 },
+  { &yyActionTable[457],  12, 715 },
+  { &yyActionTable[469],  15, 811 },
+  { &yyActionTable[484],  12, 716 },
+  { &yyActionTable[496],  15, 811 },
+  { &yyActionTable[511],  16, 717 },
+  { &yyActionTable[527],  15, 811 },
+  { &yyActionTable[542],  16, 718 },
+  { &yyActionTable[558],  15, 811 },
+  { &yyActionTable[573],   8, 719 },
+  { &yyActionTable[581],  15, 811 },
+  { &yyActionTable[596],   8, 720 },
+  { &yyActionTable[604],  15, 811 },
+  { &yyActionTable[619],   8, 721 },
+  { &yyActionTable[627],  15, 811 },
+  { &yyActionTable[642],   8, 722 },
+  { &yyActionTable[650],  15, 811 },
+  { &yyActionTable[665],  16, 723 },
+  { &yyActionTable[681],   6, 811 },
+  { &yyActionTable[687],  15, 811 },
+  { &yyActionTable[702],  16, 724 },
+  { &yyActionTable[718],   0, 725 },
+  { &yyActionTable[718],   0, 726 },
+  { &yyActionTable[718],  15, 811 },
+  { &yyActionTable[733],   6, 727 },
+  { &yyActionTable[739],  15, 811 },
+  { &yyActionTable[754],   6, 728 },
+  { &yyActionTable[760],  15, 811 },
+  { &yyActionTable[775],   3, 729 },
+  { &yyActionTable[778],  15, 811 },
+  { &yyActionTable[793],   3, 730 },
+  { &yyActionTable[796],  15, 811 },
+  { &yyActionTable[811],   3, 731 },
+  { &yyActionTable[814],  15, 811 },
+  { &yyActionTable[829],   2, 732 },
+  { &yyActionTable[831],   0, 733 },
+  { &yyActionTable[831],   2, 811 },
+  { &yyActionTable[833],   0, 734 },
+  { &yyActionTable[833],   1, 811 },
+  { &yyActionTable[834],   0, 737 },
+  { &yyActionTable[834],   0, 735 },
+  { &yyActionTable[834],  15, 811 },
+  { &yyActionTable[849],  28, 811 },
+  { &yyActionTable[877],  15, 811 },
+  { &yyActionTable[892],  16, 743 },
+  { &yyActionTable[908],   1, 811 },
+  { &yyActionTable[909],  20, 759 },
+  { &yyActionTable[929],   5, 811 },
+  { &yyActionTable[934],   2, 811 },
+  { &yyActionTable[936],   1, 811 },
+  { &yyActionTable[937],   1, 811 },
+  { &yyActionTable[938],   1, 811 },
+  { &yyActionTable[939],   0, 746 },
+  { &yyActionTable[939],  28, 758 },
+  { &yyActionTable[967],   0, 706 },
+  { &yyActionTable[967],   0, 707 },
+  { &yyActionTable[967],  15, 811 },
+  { &yyActionTable[982],  26, 738 },
+  { &yyActionTable[1008],  15, 811 },
+  { &yyActionTable[1023],   2, 739 },
+  { &yyActionTable[1025],  15, 811 },
+  { &yyActionTable[1040],   2, 740 },
+  { &yyActionTable[1042],  15, 811 },
+  { &yyActionTable[1057],   2, 741 },
+  { &yyActionTable[1059],  17, 811 },
+  { &yyActionTable[1076],  29, 811 },
+  { &yyActionTable[1105],   2, 811 },
+  { &yyActionTable[1107],   4, 811 },
+  { &yyActionTable[1111],   1, 811 },
+  { &yyActionTable[1112],   0, 749 },
+  { &yyActionTable[1112],  15, 811 },
+  { &yyActionTable[1127],  29, 811 },
+  { &yyActionTable[1156],  15, 811 },
+  { &yyActionTable[1171],  28, 750 },
+  { &yyActionTable[1199],   1, 811 },
+  { &yyActionTable[1200],   4, 811 },
+  { &yyActionTable[1204],   1, 811 },
+  { &yyActionTable[1205],   0, 806 },
+  { &yyActionTable[1205],   1, 811 },
+  { &yyActionTable[1206],   4, 811 },
+  { &yyActionTable[1210],   1, 811 },
+  { &yyActionTable[1211],   0, 807 },
+  { &yyActionTable[1211],   1, 811 },
+  { &yyActionTable[1212],   4, 811 },
+  { &yyActionTable[1216],   1, 811 },
+  { &yyActionTable[1217],   0, 808 },
+  { &yyActionTable[1217],   1, 811 },
+  { &yyActionTable[1218],   4, 811 },
+  { &yyActionTable[1222],   1, 811 },
+  { &yyActionTable[1223],   0, 809 },
+  { &yyActionTable[1223],  15, 811 },
+  { &yyActionTable[1238],  29, 811 },
+  { &yyActionTable[1267],  15, 811 },
+  { &yyActionTable[1282],  29, 811 },
+  { &yyActionTable[1311],  15, 811 },
+  { &yyActionTable[1326],  28, 751 },
+  { &yyActionTable[1354],   2, 811 },
+  { &yyActionTable[1356],   0, 745 },
+  { &yyActionTable[1356],  16, 759 },
+  { &yyActionTable[1372],   0, 756 },
+  { &yyActionTable[1372],   0, 757 },
+  { &yyActionTable[1372],   0, 736 },
+  { &yyActionTable[1372],  15, 811 },
+  { &yyActionTable[1387],  28, 811 },
+  { &yyActionTable[1415],  15, 811 },
+  { &yyActionTable[1430],  26, 744 },
+  { &yyActionTable[1456],   1, 811 },
+  { &yyActionTable[1457],  20, 759 },
+  { &yyActionTable[1477],   5, 811 },
+  { &yyActionTable[1482],   0, 748 },
+  { &yyActionTable[1482],   2, 811 },
+  { &yyActionTable[1484],   0, 747 },
+  { &yyActionTable[1484],   2, 673 },
+  { &yyActionTable[1486],   3, 672 },
+  { &yyActionTable[1489],   0, 668 },
+  { &yyActionTable[1489],  15, 811 },
+  { &yyActionTable[1504],  28, 678 },
+  { &yyActionTable[1532],   1, 811 },
+  { &yyActionTable[1533],  17, 759 },
+  { &yyActionTable[1550],   1, 676 },
+  { &yyActionTable[1551],  15, 811 },
+  { &yyActionTable[1566],  28, 686 },
+  { &yyActionTable[1594],   0, 642 },
+  { &yyActionTable[1594],   2, 653 },
+  { &yyActionTable[1596],   4, 651 },
+  { &yyActionTable[1600],   0, 652 },
+  { &yyActionTable[1600],   0, 656 },
+  { &yyActionTable[1600],   0, 657 },
+  { &yyActionTable[1600],   5, 811 },
+  { &yyActionTable[1605],   0, 658 },
+  { &yyActionTable[1605],   5, 811 },
+  { &yyActionTable[1610],   0, 659 },
+  { &yyActionTable[1610],   1, 811 },
+  { &yyActionTable[1611],   0, 660 },
+  { &yyActionTable[1611],   5, 811 },
+  { &yyActionTable[1616],   5, 649 },
+  { &yyActionTable[1621],   0, 557 },
+  { &yyActionTable[1621],   0, 558 },
+  { &yyActionTable[1621],   4, 811 },
+  { &yyActionTable[1625],   0, 647 },
+  { &yyActionTable[1625],   0, 648 },
+  { &yyActionTable[1625],   2, 662 },
+  { &yyActionTable[1627],   2, 664 },
+  { &yyActionTable[1629],   0, 654 },
+  { &yyActionTable[1629],   1, 811 },
+  { &yyActionTable[1630],   6, 811 },
+  { &yyActionTable[1636],   2, 811 },
+  { &yyActionTable[1638],   0, 663 },
+  { &yyActionTable[1638],   5, 811 },
+  { &yyActionTable[1643],   0, 765 },
+  { &yyActionTable[1643],   0, 767 },
+  { &yyActionTable[1643],   0, 766 },
+  { &yyActionTable[1643],  15, 811 },
+  { &yyActionTable[1658],  28, 661 },
+  { &yyActionTable[1686],   3, 811 },
+  { &yyActionTable[1689],   5, 811 },
+  { &yyActionTable[1694],   5, 649 },
+  { &yyActionTable[1699],   2, 662 },
+  { &yyActionTable[1701],   2, 664 },
+  { &yyActionTable[1703],   0, 655 },
+  { &yyActionTable[1703],  16, 811 },
+  { &yyActionTable[1719],  33, 649 },
+  { &yyActionTable[1752],   0, 644 },
+  { &yyActionTable[1752],   0, 645 },
+  { &yyActionTable[1752],   1, 811 },
+  { &yyActionTable[1753],   5, 811 },
+  { &yyActionTable[1758],   0, 646 },
+  { &yyActionTable[1758],   0, 639 },
+  { &yyActionTable[1758],   0, 640 },
+  { &yyActionTable[1758],   0, 742 },
+  { &yyActionTable[1758],  29, 811 },
+  { &yyActionTable[1787],   0, 700 },
+  { &yyActionTable[1787],   2, 811 },
+  { &yyActionTable[1789],   0, 709 },
+  { &yyActionTable[1789],   1, 811 },
+  { &yyActionTable[1790],   0, 710 },
+  { &yyActionTable[1790],  29, 811 },
+  { &yyActionTable[1819],   2, 619 },
+  { &yyActionTable[1821],   0, 588 },
+  { &yyActionTable[1821],   4, 811 },
+  { &yyActionTable[1825],   2, 763 },
+  { &yyActionTable[1827],   1, 592 },
+  { &yyActionTable[1828],   3, 589 },
+  { &yyActionTable[1831],   0, 593 },
+  { &yyActionTable[1831],   4, 811 },
+  { &yyActionTable[1835],   0, 594 },
+  { &yyActionTable[1835],   3, 811 },
+  { &yyActionTable[1838],   4, 811 },
+  { &yyActionTable[1842],   0, 595 },
+  { &yyActionTable[1842],   2, 811 },
+  { &yyActionTable[1844],   0, 598 },
+  { &yyActionTable[1844],   0, 599 },
+  { &yyActionTable[1844],   0, 600 },
+  { &yyActionTable[1844],   0, 601 },
+  { &yyActionTable[1844],   4, 811 },
+  { &yyActionTable[1848],   0, 596 },
+  { &yyActionTable[1848],   4, 811 },
+  { &yyActionTable[1852],   0, 597 },
+  { &yyActionTable[1852],   6, 811 },
+  { &yyActionTable[1858],   2, 811 },
+  { &yyActionTable[1860],   0, 764 },
+  { &yyActionTable[1860],   0, 590 },
+  { &yyActionTable[1860],   2, 811 },
+  { &yyActionTable[1862],   0, 591 },
+  { &yyActionTable[1862],   2, 604 },
+  { &yyActionTable[1864],   0, 603 },
+  { &yyActionTable[1864],   0, 574 },
+  { &yyActionTable[1864],   7, 811 },
+  { &yyActionTable[1871],   0, 575 },
+  { &yyActionTable[1871],   0, 576 },
+  { &yyActionTable[1871],   0, 577 },
+  { &yyActionTable[1871],   2, 811 },
+  { &yyActionTable[1873],   0, 578 },
+  { &yyActionTable[1873],   0, 581 },
+  { &yyActionTable[1873],   2, 811 },
+  { &yyActionTable[1875],   0, 579 },
+  { &yyActionTable[1875],   0, 582 },
+  { &yyActionTable[1875],   0, 580 },
+  { &yyActionTable[1875],   0, 583 },
+  { &yyActionTable[1875],   4, 563 },
+  { &yyActionTable[1879],   4, 811 },
+  { &yyActionTable[1883],   2, 811 },
+  { &yyActionTable[1885],   0, 564 },
+  { &yyActionTable[1885],   4, 811 },
+  { &yyActionTable[1889],   1, 811 },
+  { &yyActionTable[1890],   0, 565 },
+  { &yyActionTable[1890],   0, 568 },
+  { &yyActionTable[1890],   1, 811 },
+  { &yyActionTable[1891],   0, 569 },
+  { &yyActionTable[1891],   1, 811 },
+  { &yyActionTable[1892],   0, 570 },
+  { &yyActionTable[1892],   0, 567 },
+  { &yyActionTable[1892],   0, 566 },
+  { &yyActionTable[1892],   0, 555 },
+  { &yyActionTable[1892],   8, 811 },
+  { &yyActionTable[1900],   6, 811 },
+  { &yyActionTable[1906],   0, 609 },
+  { &yyActionTable[1906],   4, 811 },
+  { &yyActionTable[1910],   0, 612 },
+  { &yyActionTable[1910],   1, 811 },
+  { &yyActionTable[1911],   1, 811 },
+  { &yyActionTable[1912],   6, 811 },
+  { &yyActionTable[1918],   2, 811 },
+  { &yyActionTable[1920],   2, 619 },
+  { &yyActionTable[1922],   0, 613 },
+  { &yyActionTable[1922],   1, 811 },
+  { &yyActionTable[1923],   6, 811 },
+  { &yyActionTable[1929],   2, 811 },
+  { &yyActionTable[1931],   2, 619 },
+  { &yyActionTable[1933],   0, 614 },
+  { &yyActionTable[1933],  15, 811 },
+  { &yyActionTable[1948],  30, 619 },
+  { &yyActionTable[1978],   0, 615 },
+  { &yyActionTable[1978],   1, 811 },
+  { &yyActionTable[1979],   1, 811 },
+  { &yyActionTable[1980],   6, 811 },
+  { &yyActionTable[1986],   2, 811 },
+  { &yyActionTable[1988],   1, 811 },
+  { &yyActionTable[1989],   4, 811 },
+  { &yyActionTable[1993],   2, 763 },
+  { &yyActionTable[1995],   1, 592 },
+  { &yyActionTable[1996],   7, 617 },
+  { &yyActionTable[2003],   1, 811 },
+  { &yyActionTable[2004],   0, 616 },
+  { &yyActionTable[2004],   0, 618 },
+  { &yyActionTable[2004],   0, 610 },
+  { &yyActionTable[2004],   0, 611 },
+  { &yyActionTable[2004],   0, 553 },
+  { &yyActionTable[2004],   3, 811 },
+  { &yyActionTable[2007],   5, 811 },
+  { &yyActionTable[2012],   6, 549 },
+  { &yyActionTable[2018],   2, 811 },
+  { &yyActionTable[2020],   4, 811 },
+  { &yyActionTable[2024],   0, 547 },
+  { &yyActionTable[2024],   4, 811 },
+  { &yyActionTable[2028],   1, 811 },
+  { &yyActionTable[2029],   3, 811 },
+  { &yyActionTable[2032],   5, 811 },
+  { &yyActionTable[2037],   0, 548 },
+  { &yyActionTable[2037],   1, 811 },
+  { &yyActionTable[2038],   4, 811 },
+  { &yyActionTable[2042],   1, 811 },
+  { &yyActionTable[2043],   4, 811 },
+  { &yyActionTable[2047],   1, 811 },
+  { &yyActionTable[2048],   6, 811 },
+  { &yyActionTable[2054],   2, 811 },
+  { &yyActionTable[2056],   3, 811 },
+  { &yyActionTable[2059],   1, 811 },
+  { &yyActionTable[2060],   1, 811 },
+  { &yyActionTable[2061],   4, 811 },
+  { &yyActionTable[2065],   4, 789 },
+  { &yyActionTable[2069],   4, 811 },
+  { &yyActionTable[2073],   1, 811 },
+  { &yyActionTable[2074],   4, 811 },
+  { &yyActionTable[2078],   2, 794 },
+  { &yyActionTable[2080],   3, 811 },
+  { &yyActionTable[2083],   1, 811 },
+  { &yyActionTable[2084],   9, 811 },
+  { &yyActionTable[2093],   5, 811 },
+  { &yyActionTable[2098],   1, 811 },
+  { &yyActionTable[2099],   1, 811 },
+  { &yyActionTable[2100],   1, 811 },
+  { &yyActionTable[2101],   9, 811 },
+  { &yyActionTable[2110],   1, 811 },
+  { &yyActionTable[2111],   2, 621 },
+  { &yyActionTable[2113],   6, 811 },
+  { &yyActionTable[2119],   0, 622 },
+  { &yyActionTable[2119],   4, 811 },
+  { &yyActionTable[2123],   1, 811 },
+  { &yyActionTable[2124],   5, 811 },
+  { &yyActionTable[2129],   4, 811 },
+  { &yyActionTable[2133],   4, 811 },
+  { &yyActionTable[2137],   1, 811 },
+  { &yyActionTable[2138],  15, 811 },
+  { &yyActionTable[2153],  28, 688 },
+  { &yyActionTable[2181],   1, 811 },
+  { &yyActionTable[2182],   1, 811 },
+  { &yyActionTable[2183],  15, 811 },
+  { &yyActionTable[2198],  28, 689 },
+  { &yyActionTable[2226],   3, 811 },
+  { &yyActionTable[2229],   1, 811 },
+  { &yyActionTable[2230],   4, 811 },
+  { &yyActionTable[2234],   2, 696 },
+  { &yyActionTable[2236],   5, 811 },
+  { &yyActionTable[2241],   2, 811 },
+  { &yyActionTable[2243],   0, 697 },
+  { &yyActionTable[2243],   4, 811 },
+  { &yyActionTable[2247],   0, 698 },
+  { &yyActionTable[2247],   0, 699 },
+  { &yyActionTable[2247],   4, 811 },
+  { &yyActionTable[2251],   5, 811 },
+  { &yyActionTable[2256],   1, 811 },
+  { &yyActionTable[2257],  16, 811 },
+  { &yyActionTable[2273],   2, 811 },
+  { &yyActionTable[2275],  15, 811 },
+  { &yyActionTable[2290],  28, 694 },
+  { &yyActionTable[2318],   1, 811 },
+  { &yyActionTable[2319],  28, 695 },
+  { &yyActionTable[2347],   1, 811 },
+  { &yyActionTable[2348],   4, 811 },
+  { &yyActionTable[2352],   3, 811 },
+  { &yyActionTable[2355],   1, 811 },
+  { &yyActionTable[2356],  15, 811 },
+  { &yyActionTable[2371],  29, 811 },
+  { &yyActionTable[2400],   1, 811 },
+  { &yyActionTable[2401],   2, 811 },
+  { &yyActionTable[2403],   0, 795 },
+  { &yyActionTable[2403],   0, 796 },
+  { &yyActionTable[2403],   1, 811 },
+  { &yyActionTable[2404],   1, 811 },
+  { &yyActionTable[2405],   2, 811 },
+  { &yyActionTable[2407],   5, 811 },
+  { &yyActionTable[2412],   2, 811 },
+  { &yyActionTable[2414],   0, 786 },
+  { &yyActionTable[2414],   0, 787 },
+  { &yyActionTable[2414],   1, 811 },
+  { &yyActionTable[2415],   0, 788 },
+  { &yyActionTable[2415],   4, 811 },
+  { &yyActionTable[2419],   4, 811 },
+  { &yyActionTable[2423],   1, 811 },
+  { &yyActionTable[2424],   4, 811 },
+  { &yyActionTable[2428],   1, 811 },
+  { &yyActionTable[2429],   4, 811 },
+  { &yyActionTable[2433],   1, 811 },
+  { &yyActionTable[2434],   4, 811 },
+  { &yyActionTable[2438],   1, 811 },
+  { &yyActionTable[2439],   5, 811 },
+  { &yyActionTable[2444],   1, 811 },
+  { &yyActionTable[2445],   4, 811 },
+  { &yyActionTable[2449],   3, 811 },
+  { &yyActionTable[2452],   1, 811 },
+  { &yyActionTable[2453],   2, 621 },
+  { &yyActionTable[2455],   4, 811 },
+  { &yyActionTable[2459],   1, 811 },
+  { &yyActionTable[2460],   5, 811 },
+  { &yyActionTable[2465],   4, 811 },
+  { &yyActionTable[2469],   1, 811 },
+  { &yyActionTable[2470],   1, 811 },
+  { &yyActionTable[2471],   4, 811 },
+  { &yyActionTable[2475],   2, 696 },
+  { &yyActionTable[2477],   4, 811 },
+  { &yyActionTable[2481],   5, 811 },
+  { &yyActionTable[2486],   1, 811 },
+  { &yyActionTable[2487],  16, 811 },
+  { &yyActionTable[2503],   2, 811 },
+  { &yyActionTable[2505],   1, 811 },
+  { &yyActionTable[2506],   3, 811 },
+  { &yyActionTable[2509],   1, 811 },
+  { &yyActionTable[2510],   1, 811 },
+  { &yyActionTable[2511],   2, 621 },
+  { &yyActionTable[2513],   4, 811 },
+  { &yyActionTable[2517],   1, 811 },
+  { &yyActionTable[2518],   4, 811 },
+  { &yyActionTable[2522],   2, 811 },
+  { &yyActionTable[2524],   1, 811 },
+  { &yyActionTable[2525],   1, 811 },
+  { &yyActionTable[2526],   1, 811 },
+  { &yyActionTable[2527],   5, 811 },
+  { &yyActionTable[2532],   1, 811 },
+  { &yyActionTable[2533],   3, 811 },
+  { &yyActionTable[2536],   3, 811 },
+  { &yyActionTable[2539],  10, 784 },
+  { &yyActionTable[2549],   1, 811 },
+  { &yyActionTable[2550],   1, 811 },
+  { &yyActionTable[2551],   1, 811 },
+  { &yyActionTable[2552],   1, 811 },
+  { &yyActionTable[2553],   3, 811 },
+  { &yyActionTable[2556],   1, 811 },
+  { &yyActionTable[2557],   1, 811 },
+  { &yyActionTable[2558],   1, 811 },
+  { &yyActionTable[2559],   3, 811 },
+  { &yyActionTable[2562],   1, 811 },
+  { &yyActionTable[2563],   0, 783 },
+  { &yyActionTable[2563],   4, 811 },
+  { &yyActionTable[2567],   1, 811 },
+  { &yyActionTable[2568],   1, 811 },
+  { &yyActionTable[2569],   0, 535 },
+  { &yyActionTable[2569],   0, 537 },
+  { &yyActionTable[2569],   0, 532 },
+};
+
+/* The next table maps tokens into fallback tokens.  If a construct
+** like the following:
+** 
+**      %fallback ID X Y Z.
+**
+** appears in the grammer, then ID becomes a fallback token for X, Y,
+** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
+** but it does not parse, the type of the token is changed to ID and
+** the parse is retried before an error is thrown.
+*/
+#ifdef YYFALLBACK
+static const YYCODETYPE yyFallback[] = {
+    0,  /*          $ => nothing */
+   56,  /*      ABORT => ID */
+   56,  /*      AFTER => ID */
+    0,  /* AGG_FUNCTION => nothing */
+    0,  /*        ALL => nothing */
+    0,  /*        AND => nothing */
+    0,  /*         AS => nothing */
+   56,  /*        ASC => ID */
+   56,  /*     BEFORE => ID */
+   56,  /*      BEGIN => ID */
+    0,  /*    BETWEEN => nothing */
+    0,  /*     BITAND => nothing */
+    0,  /*     BITNOT => nothing */
+    0,  /*      BITOR => nothing */
+    0,  /*         BY => nothing */
+   56,  /*    CASCADE => ID */
+    0,  /*       CASE => nothing */
+    0,  /*      CHECK => nothing */
+   56,  /*    CLUSTER => ID */
+    0,  /*    COLLATE => nothing */
+    0,  /*     COLUMN => nothing */
+    0,  /*      COMMA => nothing */
+    0,  /*    COMMENT => nothing */
+    0,  /*     COMMIT => nothing */
+    0,  /*     CONCAT => nothing */
+   56,  /*   CONFLICT => ID */
+    0,  /* CONSTRAINT => nothing */
+   56,  /*       COPY => ID */
+    0,  /*     CREATE => nothing */
+    0,  /*    DEFAULT => nothing */
+    0,  /* DEFERRABLE => nothing */
+   56,  /*   DEFERRED => ID */
+    0,  /*     DELETE => nothing */
+   56,  /* DELIMITERS => ID */
+   56,  /*       DESC => ID */
+    0,  /*   DISTINCT => nothing */
+    0,  /*        DOT => nothing */
+    0,  /*       DROP => nothing */
+   56,  /*       EACH => ID */
+    0,  /*       ELSE => nothing */
+   56,  /*        END => ID */
+    0,  /* END_OF_FILE => nothing */
+    0,  /*         EQ => nothing */
+    0,  /*     EXCEPT => nothing */
+   56,  /*    EXPLAIN => ID */
+   56,  /*       FAIL => ID */
+    0,  /*      FLOAT => nothing */
+   56,  /*        FOR => ID */
+    0,  /*    FOREIGN => nothing */
+    0,  /*       FROM => nothing */
+    0,  /*   FUNCTION => nothing */
+    0,  /*         GE => nothing */
+    0,  /*       GLOB => nothing */
+    0,  /*      GROUP => nothing */
+    0,  /*         GT => nothing */
+    0,  /*     HAVING => nothing */
+    0,  /*         ID => nothing */
+   56,  /*     IGNORE => ID */
+    0,  /*    ILLEGAL => nothing */
+   56,  /*  IMMEDIATE => ID */
+    0,  /*         IN => nothing */
+    0,  /*      INDEX => nothing */
+   56,  /*  INITIALLY => ID */
+    0,  /*     INSERT => nothing */
+   56,  /*    INSTEAD => ID */
+    0,  /*    INTEGER => nothing */
+    0,  /*  INTERSECT => nothing */
+    0,  /*       INTO => nothing */
+    0,  /*         IS => nothing */
+    0,  /*     ISNULL => nothing */
+    0,  /*       JOIN => nothing */
+    0,  /*    JOIN_KW => nothing */
+   56,  /*        KEY => ID */
+    0,  /*         LE => nothing */
+    0,  /*       LIKE => nothing */
+    0,  /*      LIMIT => nothing */
+    0,  /*         LP => nothing */
+    0,  /*     LSHIFT => nothing */
+    0,  /*         LT => nothing */
+   56,  /*      MATCH => ID */
+    0,  /*      MINUS => nothing */
+    0,  /*         NE => nothing */
+    0,  /*        NOT => nothing */
+    0,  /*    NOTNULL => nothing */
+    0,  /*       NULL => nothing */
+   56,  /*         OF => ID */
+   56,  /*     OFFSET => ID */
+    0,  /*         ON => nothing */
+    0,  /*         OR => nothing */
+    0,  /* ORACLE_OUTER_JOIN => nothing */
+    0,  /*      ORDER => nothing */
+    0,  /*       PLUS => nothing */
+   56,  /*     PRAGMA => ID */
+    0,  /*    PRIMARY => nothing */
+   56,  /*      RAISE => ID */
+    0,  /* REFERENCES => nothing */
+    0,  /*        REM => nothing */
+   56,  /*    REPLACE => ID */
+   56,  /*   RESTRICT => ID */
+    0,  /*   ROLLBACK => nothing */
+   56,  /*        ROW => ID */
+    0,  /*         RP => nothing */
+    0,  /*     RSHIFT => nothing */
+    0,  /*     SELECT => nothing */
+    0,  /*       SEMI => nothing */
+    0,  /*        SET => nothing */
+    0,  /*      SLASH => nothing */
+    0,  /*      SPACE => nothing */
+    0,  /*       STAR => nothing */
+   56,  /*  STATEMENT => ID */
+    0,  /*     STRING => nothing */
+    0,  /*      TABLE => nothing */
+   56,  /*       TEMP => ID */
+    0,  /*       THEN => nothing */
+    0,  /* TRANSACTION => nothing */
+   56,  /*    TRIGGER => ID */
+    0,  /*     UMINUS => nothing */
+    0,  /* UNCLOSED_STRING => nothing */
+    0,  /*      UNION => nothing */
+    0,  /*     UNIQUE => nothing */
+    0,  /*     UPDATE => nothing */
+    0,  /*      UPLUS => nothing */
+    0,  /*      USING => nothing */
+   56,  /*     VACUUM => ID */
+    0,  /*     VALUES => nothing */
+   56,  /*       VIEW => ID */
+    0,  /*       WHEN => nothing */
+    0,  /*      WHERE => nothing */
+};
+#endif /* YYFALLBACK */
+
+/* The following structure represents a single element of the
+** parser's stack.  Information stored includes:
+**
+**   +  The state number for the parser at this level of the stack.
+**
+**   +  The value of the token stored at this level of the stack.
+**      (In other words, the "major" token.)
+**
+**   +  The semantic value stored at this level of the stack.  This is
+**      the information used by the action routines in the grammar.
+**      It is sometimes called the "minor" token.
+*/
+struct yyStackEntry {
+  int stateno;       /* The state-number */
+  int major;         /* The major token value.  This is the code
+                     ** number for the token at this stack level */
+  YYMINORTYPE minor; /* The user-supplied minor token value.  This
+                     ** is the value of the token  */
+};
+typedef struct yyStackEntry yyStackEntry;
+
+/* The state of the parser is completely contained in an instance of
+** the following structure */
+struct yyParser {
+  int yyidx;                    /* Index of top element in stack */
+  int yyerrcnt;                 /* Shifts left before out of the error */
+  yyStackEntry *yytop;          /* Pointer to the top stack element */
+  sqliteParserARG_SDECL                /* A place to hold %extra_argument */
+  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
+};
+typedef struct yyParser yyParser;
+
+#ifndef NDEBUG
+#include <stdio.h>
+static FILE *yyTraceFILE = 0;
+static char *yyTracePrompt = 0;
+#endif /* NDEBUG */
+
+#ifndef NDEBUG
+/* 
+** Turn parser tracing on by giving a stream to which to write the trace
+** and a prompt to preface each trace message.  Tracing is turned off
+** by making either argument NULL 
+**
+** Inputs:
+** <ul>
+** <li> A FILE* to which trace output should be written.
+**      If NULL, then tracing is turned off.
+** <li> A prefix string written at the beginning of every
+**      line of trace output.  If NULL, then tracing is
+**      turned off.
+** </ul>
+**
+** Outputs:
+** None.
+*/
+void sqliteParserTrace(FILE *TraceFILE, char *zTracePrompt){
+  yyTraceFILE = TraceFILE;
+  yyTracePrompt = zTracePrompt;
+  if( yyTraceFILE==0 ) yyTracePrompt = 0;
+  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
+}
+#endif /* NDEBUG */
+
+#ifndef NDEBUG
+/* For tracing shifts, the names of all terminals and nonterminals
+** are required.  The following table supplies these names */
+static const char *yyTokenName[] = { 
+  "$",             "ABORT",         "AFTER",         "AGG_FUNCTION",
+  "ALL",           "AND",           "AS",            "ASC",         
+  "BEFORE",        "BEGIN",         "BETWEEN",       "BITAND",      
+  "BITNOT",        "BITOR",         "BY",            "CASCADE",     
+  "CASE",          "CHECK",         "CLUSTER",       "COLLATE",     
+  "COLUMN",        "COMMA",         "COMMENT",       "COMMIT",      
+  "CONCAT",        "CONFLICT",      "CONSTRAINT",    "COPY",        
+  "CREATE",        "DEFAULT",       "DEFERRABLE",    "DEFERRED",    
+  "DELETE",        "DELIMITERS",    "DESC",          "DISTINCT",    
+  "DOT",           "DROP",          "EACH",          "ELSE",        
+  "END",           "END_OF_FILE",   "EQ",            "EXCEPT",      
+  "EXPLAIN",       "FAIL",          "FLOAT",         "FOR",         
+  "FOREIGN",       "FROM",          "FUNCTION",      "GE",          
+  "GLOB",          "GROUP",         "GT",            "HAVING",      
+  "ID",            "IGNORE",        "ILLEGAL",       "IMMEDIATE",   
+  "IN",            "INDEX",         "INITIALLY",     "INSERT",      
+  "INSTEAD",       "INTEGER",       "INTERSECT",     "INTO",        
+  "IS",            "ISNULL",        "JOIN",          "JOIN_KW",     
+  "KEY",           "LE",            "LIKE",          "LIMIT",       
+  "LP",            "LSHIFT",        "LT",            "MATCH",       
+  "MINUS",         "NE",            "NOT",           "NOTNULL",     
+  "NULL",          "OF",            "OFFSET",        "ON",          
+  "OR",            "ORACLE_OUTER_JOIN",  "ORDER",         "PLUS",        
+  "PRAGMA",        "PRIMARY",       "RAISE",         "REFERENCES",  
+  "REM",           "REPLACE",       "RESTRICT",      "ROLLBACK",    
+  "ROW",           "RP",            "RSHIFT",        "SELECT",      
+  "SEMI",          "SET",           "SLASH",         "SPACE",       
+  "STAR",          "STATEMENT",     "STRING",        "TABLE",       
+  "TEMP",          "THEN",          "TRANSACTION",   "TRIGGER",     
+  "UMINUS",        "UNCLOSED_STRING",  "UNION",         "UNIQUE",      
+  "UPDATE",        "UPLUS",         "USING",         "VACUUM",      
+  "VALUES",        "VIEW",          "WHEN",          "WHERE",       
+  "as",            "carg",          "carglist",      "case_else",   
+  "case_exprlist",  "case_operand",  "ccons",         "cmd",         
+  "cmdlist",       "cmdx",          "collate",       "column",      
+  "columnid",      "columnlist",    "conslist",      "conslist_opt",
+  "create_table",  "create_table_args",  "defer_subclause",  "defer_subclause_opt",
+  "distinct",      "ecmd",          "error",         "explain",     
+  "expr",          "expritem",      "exprlist",      "foreach_clause",
+  "from",          "groupby_opt",   "having_opt",    "id",          
+  "ids",           "idxitem",       "idxlist",       "idxlist_opt", 
+  "init_deferred_pred_opt",  "input",         "inscollist",    "inscollist_opt",
+  "insert_cmd",    "itemlist",      "joinop",        "joinop2",     
+  "likeop",        "limit_opt",     "limit_sep",     "minus_num",   
+  "multiselect_op",  "nm",            "number",        "on_opt",      
+  "onconf",        "oneselect",     "orconf",        "orderby_opt", 
+  "plus_num",      "plus_opt",      "refact",        "refarg",      
+  "refargs",       "resolvetype",   "sclp",          "selcollist",  
+  "select",        "seltablist",    "setlist",       "signed",      
+  "sortitem",      "sortlist",      "sortorder",     "stl_prefix",  
+  "tcons",         "temp",          "trans_opt",     "trigger_cmd", 
+  "trigger_cmd_list",  "trigger_event",  "trigger_time",  "type",        
+  "typename",      "uniqueflag",    "using_opt",     "when_clause", 
+  "where_opt",   
+};
+#endif /* NDEBUG */
+
+#ifndef NDEBUG
+/* For tracing reduce actions, the names of all rules are required.
+*/
+static const char *yyRuleName[] = {
+ /*   0 */ "input ::= cmdlist",
+ /*   1 */ "cmdlist ::= ecmd",
+ /*   2 */ "cmdlist ::= cmdlist ecmd",
+ /*   3 */ "ecmd ::= explain cmdx SEMI",
+ /*   4 */ "ecmd ::= SEMI",
+ /*   5 */ "cmdx ::= cmd",
+ /*   6 */ "explain ::= EXPLAIN",
+ /*   7 */ "explain ::=",
+ /*   8 */ "cmd ::= BEGIN trans_opt onconf",
+ /*   9 */ "trans_opt ::=",
+ /*  10 */ "trans_opt ::= TRANSACTION",
+ /*  11 */ "trans_opt ::= TRANSACTION nm",
+ /*  12 */ "cmd ::= COMMIT trans_opt",
+ /*  13 */ "cmd ::= END trans_opt",
+ /*  14 */ "cmd ::= ROLLBACK trans_opt",
+ /*  15 */ "cmd ::= create_table create_table_args",
+ /*  16 */ "create_table ::= CREATE temp TABLE nm",
+ /*  17 */ "temp ::= TEMP",
+ /*  18 */ "temp ::=",
+ /*  19 */ "create_table_args ::= LP columnlist conslist_opt RP",
+ /*  20 */ "create_table_args ::= AS select",
+ /*  21 */ "columnlist ::= columnlist COMMA column",
+ /*  22 */ "columnlist ::= column",
+ /*  23 */ "column ::= columnid type carglist",
+ /*  24 */ "columnid ::= nm",
+ /*  25 */ "id ::= ID",
+ /*  26 */ "ids ::= ID",
+ /*  27 */ "ids ::= STRING",
+ /*  28 */ "nm ::= ID",
+ /*  29 */ "nm ::= STRING",
+ /*  30 */ "nm ::= JOIN_KW",
+ /*  31 */ "type ::=",
+ /*  32 */ "type ::= typename",
+ /*  33 */ "type ::= typename LP signed RP",
+ /*  34 */ "type ::= typename LP signed COMMA signed RP",
+ /*  35 */ "typename ::= ids",
+ /*  36 */ "typename ::= typename ids",
+ /*  37 */ "signed ::= INTEGER",
+ /*  38 */ "signed ::= PLUS INTEGER",
+ /*  39 */ "signed ::= MINUS INTEGER",
+ /*  40 */ "carglist ::= carglist carg",
+ /*  41 */ "carglist ::=",
+ /*  42 */ "carg ::= CONSTRAINT nm ccons",
+ /*  43 */ "carg ::= ccons",
+ /*  44 */ "carg ::= DEFAULT STRING",
+ /*  45 */ "carg ::= DEFAULT ID",
+ /*  46 */ "carg ::= DEFAULT INTEGER",
+ /*  47 */ "carg ::= DEFAULT PLUS INTEGER",
+ /*  48 */ "carg ::= DEFAULT MINUS INTEGER",
+ /*  49 */ "carg ::= DEFAULT FLOAT",
+ /*  50 */ "carg ::= DEFAULT PLUS FLOAT",
+ /*  51 */ "carg ::= DEFAULT MINUS FLOAT",
+ /*  52 */ "carg ::= DEFAULT NULL",
+ /*  53 */ "ccons ::= NULL onconf",
+ /*  54 */ "ccons ::= NOT NULL onconf",
+ /*  55 */ "ccons ::= PRIMARY KEY sortorder onconf",
+ /*  56 */ "ccons ::= UNIQUE onconf",
+ /*  57 */ "ccons ::= CHECK LP expr RP onconf",
+ /*  58 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
+ /*  59 */ "ccons ::= defer_subclause",
+ /*  60 */ "ccons ::= COLLATE id",
+ /*  61 */ "refargs ::=",
+ /*  62 */ "refargs ::= refargs refarg",
+ /*  63 */ "refarg ::= MATCH nm",
+ /*  64 */ "refarg ::= ON DELETE refact",
+ /*  65 */ "refarg ::= ON UPDATE refact",
+ /*  66 */ "refarg ::= ON INSERT refact",
+ /*  67 */ "refact ::= SET NULL",
+ /*  68 */ "refact ::= SET DEFAULT",
+ /*  69 */ "refact ::= CASCADE",
+ /*  70 */ "refact ::= RESTRICT",
+ /*  71 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
+ /*  72 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
+ /*  73 */ "init_deferred_pred_opt ::=",
+ /*  74 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
+ /*  75 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
+ /*  76 */ "conslist_opt ::=",
+ /*  77 */ "conslist_opt ::= COMMA conslist",
+ /*  78 */ "conslist ::= conslist COMMA tcons",
+ /*  79 */ "conslist ::= conslist tcons",
+ /*  80 */ "conslist ::= tcons",
+ /*  81 */ "tcons ::= CONSTRAINT nm",
+ /*  82 */ "tcons ::= PRIMARY KEY LP idxlist RP onconf",
+ /*  83 */ "tcons ::= UNIQUE LP idxlist RP onconf",
+ /*  84 */ "tcons ::= CHECK expr onconf",
+ /*  85 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
+ /*  86 */ "defer_subclause_opt ::=",
+ /*  87 */ "defer_subclause_opt ::= defer_subclause",
+ /*  88 */ "onconf ::=",
+ /*  89 */ "onconf ::= ON CONFLICT resolvetype",
+ /*  90 */ "orconf ::=",
+ /*  91 */ "orconf ::= OR resolvetype",
+ /*  92 */ "resolvetype ::= ROLLBACK",
+ /*  93 */ "resolvetype ::= ABORT",
+ /*  94 */ "resolvetype ::= FAIL",
+ /*  95 */ "resolvetype ::= IGNORE",
+ /*  96 */ "resolvetype ::= REPLACE",
+ /*  97 */ "cmd ::= DROP TABLE nm",
+ /*  98 */ "cmd ::= CREATE temp VIEW nm AS select",
+ /*  99 */ "cmd ::= DROP VIEW nm",
+ /* 100 */ "cmd ::= select",
+ /* 101 */ "select ::= oneselect",
+ /* 102 */ "select ::= select multiselect_op oneselect",
+ /* 103 */ "multiselect_op ::= UNION",
+ /* 104 */ "multiselect_op ::= UNION ALL",
+ /* 105 */ "multiselect_op ::= INTERSECT",
+ /* 106 */ "multiselect_op ::= EXCEPT",
+ /* 107 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
+ /* 108 */ "distinct ::= DISTINCT",
+ /* 109 */ "distinct ::= ALL",
+ /* 110 */ "distinct ::=",
+ /* 111 */ "sclp ::= selcollist COMMA",
+ /* 112 */ "sclp ::=",
+ /* 113 */ "selcollist ::= sclp expr as",
+ /* 114 */ "selcollist ::= sclp STAR",
+ /* 115 */ "selcollist ::= sclp nm DOT STAR",
+ /* 116 */ "as ::= AS nm",
+ /* 117 */ "as ::= ids",
+ /* 118 */ "as ::=",
+ /* 119 */ "from ::=",
+ /* 120 */ "from ::= FROM seltablist",
+ /* 121 */ "stl_prefix ::= seltablist joinop",
+ /* 122 */ "stl_prefix ::=",
+ /* 123 */ "seltablist ::= stl_prefix nm as on_opt using_opt",
+ /* 124 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
+ /* 125 */ "joinop ::= COMMA",
+ /* 126 */ "joinop ::= JOIN",
+ /* 127 */ "joinop ::= JOIN_KW JOIN",
+ /* 128 */ "joinop ::= JOIN_KW nm JOIN",
+ /* 129 */ "joinop ::= JOIN_KW nm nm JOIN",
+ /* 130 */ "on_opt ::= ON expr",
+ /* 131 */ "on_opt ::=",
+ /* 132 */ "using_opt ::= USING LP idxlist RP",
+ /* 133 */ "using_opt ::=",
+ /* 134 */ "orderby_opt ::=",
+ /* 135 */ "orderby_opt ::= ORDER BY sortlist",
+ /* 136 */ "sortlist ::= sortlist COMMA sortitem collate sortorder",
+ /* 137 */ "sortlist ::= sortitem collate sortorder",
+ /* 138 */ "sortitem ::= expr",
+ /* 139 */ "sortorder ::= ASC",
+ /* 140 */ "sortorder ::= DESC",
+ /* 141 */ "sortorder ::=",
+ /* 142 */ "collate ::=",
+ /* 143 */ "collate ::= COLLATE id",
+ /* 144 */ "groupby_opt ::=",
+ /* 145 */ "groupby_opt ::= GROUP BY exprlist",
+ /* 146 */ "having_opt ::=",
+ /* 147 */ "having_opt ::= HAVING expr",
+ /* 148 */ "limit_opt ::=",
+ /* 149 */ "limit_opt ::= LIMIT INTEGER",
+ /* 150 */ "limit_opt ::= LIMIT INTEGER limit_sep INTEGER",
+ /* 151 */ "limit_sep ::= OFFSET",
+ /* 152 */ "limit_sep ::= COMMA",
+ /* 153 */ "cmd ::= DELETE FROM nm where_opt",
+ /* 154 */ "where_opt ::=",
+ /* 155 */ "where_opt ::= WHERE expr",
+ /* 156 */ "cmd ::= UPDATE orconf nm SET setlist where_opt",
+ /* 157 */ "setlist ::= setlist COMMA nm EQ expr",
+ /* 158 */ "setlist ::= nm EQ expr",
+ /* 159 */ "cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP",
+ /* 160 */ "cmd ::= insert_cmd INTO nm inscollist_opt select",
+ /* 161 */ "insert_cmd ::= INSERT orconf",
+ /* 162 */ "insert_cmd ::= REPLACE",
+ /* 163 */ "itemlist ::= itemlist COMMA expr",
+ /* 164 */ "itemlist ::= expr",
+ /* 165 */ "inscollist_opt ::=",
+ /* 166 */ "inscollist_opt ::= LP inscollist RP",
+ /* 167 */ "inscollist ::= inscollist COMMA nm",
+ /* 168 */ "inscollist ::= nm",
+ /* 169 */ "expr ::= LP expr RP",
+ /* 170 */ "expr ::= NULL",
+ /* 171 */ "expr ::= ID",
+ /* 172 */ "expr ::= JOIN_KW",
+ /* 173 */ "expr ::= nm DOT nm",
+ /* 174 */ "expr ::= expr ORACLE_OUTER_JOIN",
+ /* 175 */ "expr ::= INTEGER",
+ /* 176 */ "expr ::= FLOAT",
+ /* 177 */ "expr ::= STRING",
+ /* 178 */ "expr ::= ID LP exprlist RP",
+ /* 179 */ "expr ::= ID LP STAR RP",
+ /* 180 */ "expr ::= expr AND expr",
+ /* 181 */ "expr ::= expr OR expr",
+ /* 182 */ "expr ::= expr LT expr",
+ /* 183 */ "expr ::= expr GT expr",
+ /* 184 */ "expr ::= expr LE expr",
+ /* 185 */ "expr ::= expr GE expr",
+ /* 186 */ "expr ::= expr NE expr",
+ /* 187 */ "expr ::= expr EQ expr",
+ /* 188 */ "expr ::= expr BITAND expr",
+ /* 189 */ "expr ::= expr BITOR expr",
+ /* 190 */ "expr ::= expr LSHIFT expr",
+ /* 191 */ "expr ::= expr RSHIFT expr",
+ /* 192 */ "expr ::= expr likeop expr",
+ /* 193 */ "expr ::= expr NOT likeop expr",
+ /* 194 */ "likeop ::= LIKE",
+ /* 195 */ "likeop ::= GLOB",
+ /* 196 */ "expr ::= expr PLUS expr",
+ /* 197 */ "expr ::= expr MINUS expr",
+ /* 198 */ "expr ::= expr STAR expr",
+ /* 199 */ "expr ::= expr SLASH expr",
+ /* 200 */ "expr ::= expr REM expr",
+ /* 201 */ "expr ::= expr CONCAT expr",
+ /* 202 */ "expr ::= expr ISNULL",
+ /* 203 */ "expr ::= expr IS NULL",
+ /* 204 */ "expr ::= expr NOTNULL",
+ /* 205 */ "expr ::= expr NOT NULL",
+ /* 206 */ "expr ::= expr IS NOT NULL",
+ /* 207 */ "expr ::= NOT expr",
+ /* 208 */ "expr ::= BITNOT expr",
+ /* 209 */ "expr ::= MINUS expr",
+ /* 210 */ "expr ::= PLUS expr",
+ /* 211 */ "expr ::= LP select RP",
+ /* 212 */ "expr ::= expr BETWEEN expr AND expr",
+ /* 213 */ "expr ::= expr NOT BETWEEN expr AND expr",
+ /* 214 */ "expr ::= expr IN LP exprlist RP",
+ /* 215 */ "expr ::= expr IN LP select RP",
+ /* 216 */ "expr ::= expr NOT IN LP exprlist RP",
+ /* 217 */ "expr ::= expr NOT IN LP select RP",
+ /* 218 */ "expr ::= CASE case_operand case_exprlist case_else END",
+ /* 219 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
+ /* 220 */ "case_exprlist ::= WHEN expr THEN expr",
+ /* 221 */ "case_else ::= ELSE expr",
+ /* 222 */ "case_else ::=",
+ /* 223 */ "case_operand ::= expr",
+ /* 224 */ "case_operand ::=",
+ /* 225 */ "exprlist ::= exprlist COMMA expritem",
+ /* 226 */ "exprlist ::= expritem",
+ /* 227 */ "expritem ::= expr",
+ /* 228 */ "expritem ::=",
+ /* 229 */ "cmd ::= CREATE uniqueflag INDEX nm ON nm LP idxlist RP onconf",
+ /* 230 */ "uniqueflag ::= UNIQUE",
+ /* 231 */ "uniqueflag ::=",
+ /* 232 */ "idxlist_opt ::=",
+ /* 233 */ "idxlist_opt ::= LP idxlist RP",
+ /* 234 */ "idxlist ::= idxlist COMMA idxitem",
+ /* 235 */ "idxlist ::= idxitem",
+ /* 236 */ "idxitem ::= nm",
+ /* 237 */ "cmd ::= DROP INDEX nm",
+ /* 238 */ "cmd ::= COPY orconf nm FROM nm USING DELIMITERS STRING",
+ /* 239 */ "cmd ::= COPY orconf nm FROM nm",
+ /* 240 */ "cmd ::= VACUUM",
+ /* 241 */ "cmd ::= VACUUM nm",
+ /* 242 */ "cmd ::= PRAGMA ids EQ nm",
+ /* 243 */ "cmd ::= PRAGMA ids EQ ON",
+ /* 244 */ "cmd ::= PRAGMA ids EQ plus_num",
+ /* 245 */ "cmd ::= PRAGMA ids EQ minus_num",
+ /* 246 */ "cmd ::= PRAGMA ids LP nm RP",
+ /* 247 */ "cmd ::= PRAGMA ids",
+ /* 248 */ "plus_num ::= plus_opt number",
+ /* 249 */ "minus_num ::= MINUS number",
+ /* 250 */ "number ::= INTEGER",
+ /* 251 */ "number ::= FLOAT",
+ /* 252 */ "plus_opt ::= PLUS",
+ /* 253 */ "plus_opt ::=",
+ /* 254 */ "cmd ::= CREATE TRIGGER nm trigger_time trigger_event ON nm foreach_clause when_clause BEGIN trigger_cmd_list END",
+ /* 255 */ "trigger_time ::= BEFORE",
+ /* 256 */ "trigger_time ::= AFTER",
+ /* 257 */ "trigger_time ::= INSTEAD OF",
+ /* 258 */ "trigger_time ::=",
+ /* 259 */ "trigger_event ::= DELETE",
+ /* 260 */ "trigger_event ::= INSERT",
+ /* 261 */ "trigger_event ::= UPDATE",
+ /* 262 */ "trigger_event ::= UPDATE OF inscollist",
+ /* 263 */ "foreach_clause ::=",
+ /* 264 */ "foreach_clause ::= FOR EACH ROW",
+ /* 265 */ "foreach_clause ::= FOR EACH STATEMENT",
+ /* 266 */ "when_clause ::=",
+ /* 267 */ "when_clause ::= WHEN expr",
+ /* 268 */ "trigger_cmd_list ::= trigger_cmd SEMI trigger_cmd_list",
+ /* 269 */ "trigger_cmd_list ::=",
+ /* 270 */ "trigger_cmd ::= UPDATE orconf nm SET setlist where_opt",
+ /* 271 */ "trigger_cmd ::= INSERT orconf INTO nm inscollist_opt VALUES LP itemlist RP",
+ /* 272 */ "trigger_cmd ::= INSERT orconf INTO nm inscollist_opt select",
+ /* 273 */ "trigger_cmd ::= DELETE FROM nm where_opt",
+ /* 274 */ "trigger_cmd ::= select",
+ /* 275 */ "expr ::= RAISE LP IGNORE RP",
+ /* 276 */ "expr ::= RAISE LP ROLLBACK COMMA nm RP",
+ /* 277 */ "expr ::= RAISE LP ABORT COMMA nm RP",
+ /* 278 */ "expr ::= RAISE LP FAIL COMMA nm RP",
+ /* 279 */ "cmd ::= DROP TRIGGER nm",
+};
+#endif /* NDEBUG */
+
+/*
+** This function returns the symbolic name associated with a token
+** value.
+*/
+const char *sqliteParserTokenName(int tokenType){
+#ifndef NDEBUG
+  if( tokenType>0 && tokenType<(sizeof(yyTokenName)/sizeof(yyTokenName[0])) ){
+    return yyTokenName[tokenType];
+  }else{
+    return "Unknown";
+  }
+#else
+  return "";
+#endif
+}
+
+/* 
+** This function allocates a new parser.
+** The only argument is a pointer to a function which works like
+** malloc.
+**
+** Inputs:
+** A pointer to the function used to allocate memory.
+**
+** Outputs:
+** A pointer to a parser.  This pointer is used in subsequent calls
+** to sqliteParser and sqliteParserFree.
+*/
+void *sqliteParserAlloc(void *(*mallocProc)(size_t)){
+  yyParser *pParser;
+  pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
+  if( pParser ){
+    pParser->yyidx = -1;
+  }
+  return pParser;
+}
+
+/* The following function deletes the value associated with a
+** symbol.  The symbol can be either a terminal or nonterminal.
+** "yymajor" is the symbol code, and "yypminor" is a pointer to
+** the value.
+*/
+static void yy_destructor(YYCODETYPE yymajor, YYMINORTYPE *yypminor){
+  switch( yymajor ){
+    /* Here is inserted the actions which take place when a
+    ** terminal or non-terminal is destroyed.  This can happen
+    ** when the symbol is popped from the stack during a
+    ** reduce or during error processing or when a parser is 
+    ** being destroyed before it is finished parsing.
+    **
+    ** Note: during a reduce, the only symbols destroyed are those
+    ** which appear on the RHS of the rule, but which are not used
+    ** inside the C code.
+    */
+    case 132:
+#line 660 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteExprListDelete((yypminor->yy168));}
+#line 4269 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 152:
+#line 514 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteExprDelete((yypminor->yy272));}
+#line 4274 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 153:
+#line 679 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteExprDelete((yypminor->yy272));}
+#line 4279 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 154:
+#line 677 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteExprListDelete((yypminor->yy168));}
+#line 4284 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 156:
+#line 341 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteSrcListDelete((yypminor->yy289));}
+#line 4289 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 157:
+#line 431 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteExprListDelete((yypminor->yy168));}
+#line 4294 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 158:
+#line 436 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteExprDelete((yypminor->yy272));}
+#line 4299 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 162:
+#line 701 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteIdListDelete((yypminor->yy268));}
+#line 4304 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 163:
+#line 703 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteIdListDelete((yypminor->yy268));}
+#line 4309 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 166:
+#line 492 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteIdListDelete((yypminor->yy268));}
+#line 4314 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 167:
+#line 490 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteIdListDelete((yypminor->yy268));}
+#line 4319 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 169:
+#line 484 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteExprListDelete((yypminor->yy168));}
+#line 4324 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 179:
+#line 392 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteExprDelete((yypminor->yy272));}
+#line 4329 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 181:
+#line 276 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteSelectDelete((yypminor->yy207));}
+#line 4334 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 183:
+#line 403 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteExprListDelete((yypminor->yy168));}
+#line 4339 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 190:
+#line 312 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteExprListDelete((yypminor->yy168));}
+#line 4344 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 191:
+#line 310 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteExprListDelete((yypminor->yy168));}
+#line 4349 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 192:
+#line 274 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteSelectDelete((yypminor->yy207));}
+#line 4354 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 193:
+#line 337 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteSrcListDelete((yypminor->yy289));}
+#line 4359 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 194:
+#line 460 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteExprListDelete((yypminor->yy168));}
+#line 4364 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 196:
+#line 407 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteExprDelete((yypminor->yy272));}
+#line 4369 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 197:
+#line 405 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteExprListDelete((yypminor->yy168));}
+#line 4374 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 199:
+#line 339 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteSrcListDelete((yypminor->yy289));}
+#line 4379 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 205:
+#line 762 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteIdListDelete((yypminor->yy72).b);}
+#line 4384 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 210:
+#line 397 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteIdListDelete((yypminor->yy268));}
+#line 4389 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    case 212:
+#line 454 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteExprDelete((yypminor->yy272));}
+#line 4394 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+      break;
+    default:  break;   /* If no destructor action specified: do nothing */
+  }
+}
+
+/*
+** Pop the parser's stack once.
+**
+** If there is a destructor routine associated with the token which
+** is popped from the stack, then call it.
+**
+** Return the major token number for the symbol popped.
+*/
+static int yy_pop_parser_stack(yyParser *pParser){
+  YYCODETYPE yymajor;
+
+  if( pParser->yyidx<0 ) return 0;
+#ifndef NDEBUG
+  if( yyTraceFILE && pParser->yyidx>=0 ){
+    fprintf(yyTraceFILE,"%sPopping %s\n",
+      yyTracePrompt,
+      yyTokenName[pParser->yytop->major]);
+  }
+#endif
+  yymajor = pParser->yytop->major;
+  yy_destructor( yymajor, &pParser->yytop->minor);
+  pParser->yyidx--;
+  pParser->yytop--;
+  return yymajor;
+}
+
+/* 
+** Deallocate and destroy a parser.  Destructors are all called for
+** all stack elements before shutting the parser down.
+**
+** Inputs:
+** <ul>
+** <li>  A pointer to the parser.  This should be a pointer
+**       obtained from sqliteParserAlloc.
+** <li>  A pointer to a function used to reclaim memory obtained
+**       from malloc.
+** </ul>
+*/
+void sqliteParserFree(
+  void *p,                    /* The parser to be deleted */
+  void (*freeProc)(void*)     /* Function used to reclaim memory */
+){
+  yyParser *pParser = (yyParser*)p;
+  if( pParser==0 ) return;
+  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
+  (*freeProc)((void*)pParser);
+}
+
+/*
+** Find the appropriate action for a parser given the look-ahead token.
+**
+** If the look-ahead token is YYNOCODE, then check to see if the action is
+** independent of the look-ahead.  If it is, return the action, otherwise
+** return YY_NO_ACTION.
+*/
+static int yy_find_parser_action(
+  yyParser *pParser,        /* The parser */
+  int iLookAhead             /* The look-ahead token */
+){
+  const yyStateEntry *pState;   /* Appropriate entry in the state table */
+  const yyActionEntry *pAction; /* Action appropriate for the look-ahead */
+  int iFallback;                /* Fallback token */
+  /* if( pParser->yyidx<0 ) return YY_NO_ACTION;  */
+  pState = &yyStateTable[pParser->yytop->stateno];
+  if( pState->nEntry==0 ){
+    return pState->actionDefault;
+  }else if( iLookAhead!=YYNOCODE ){
+    pAction = &pState->hashtbl[iLookAhead % pState->nEntry];
+    while( 1 ){
+      if( pAction->lookahead==iLookAhead ) return pAction->action;
+      if( pAction->next==0 ) break;
+      pAction = &pState->hashtbl[pAction->next-1];
+    }
+#ifdef YYFALLBACK
+    if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
+           && (iFallback = yyFallback[iLookAhead])!=0 ){
+#ifndef NDEBUG
+      if( yyTraceFILE ){
+        fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
+           yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
+      }
+#endif
+      return yy_find_parser_action(pParser, iFallback);
+    }
+#endif
+  }else if( pState->hashtbl->lookahead!=YYNOCODE ){
+    return YY_NO_ACTION;
+  }
+  return pState->actionDefault;
+}
+
+/*
+** Perform a shift action.
+*/
+static void yy_shift(
+  yyParser *yypParser,          /* The parser to be shifted */
+  int yyNewState,               /* The new state to shift in */
+  int yyMajor,                  /* The major token to shift in */
+  YYMINORTYPE *yypMinor         /* Pointer ot the minor token to shift in */
+){
+  yypParser->yyidx++;
+  yypParser->yytop++;
+  if( yypParser->yyidx>=YYSTACKDEPTH ){
+     sqliteParserARG_FETCH;
+     yypParser->yyidx--;
+     yypParser->yytop--;
+#ifndef NDEBUG
+     if( yyTraceFILE ){
+       fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
+     }
+#endif
+     while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
+     /* Here code is inserted which will execute if the parser
+     ** stack every overflows */
+     sqliteParserARG_STORE; /* Suppress warning about unused %extra_argument var */
+     return;
+  }
+  yypParser->yytop->stateno = yyNewState;
+  yypParser->yytop->major = yyMajor;
+  yypParser->yytop->minor = *yypMinor;
+#ifndef NDEBUG
+  if( yyTraceFILE && yypParser->yyidx>0 ){
+    int i;
+    fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
+    fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
+    for(i=1; i<=yypParser->yyidx; i++)
+      fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
+    fprintf(yyTraceFILE,"\n");
+  }
+#endif
+}
+
+/* The following table contains information about every rule that
+** is used during the reduce.
+*/
+static struct {
+  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
+  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
+} yyRuleInfo[] = {
+  { 165, 1 },
+  { 136, 1 },
+  { 136, 2 },
+  { 149, 3 },
+  { 149, 1 },
+  { 137, 1 },
+  { 151, 1 },
+  { 151, 0 },
+  { 135, 3 },
+  { 202, 0 },
+  { 202, 1 },
+  { 202, 2 },
+  { 135, 2 },
+  { 135, 2 },
+  { 135, 2 },
+  { 135, 2 },
+  { 144, 4 },
+  { 201, 1 },
+  { 201, 0 },
+  { 145, 4 },
+  { 145, 2 },
+  { 141, 3 },
+  { 141, 1 },
+  { 139, 3 },
+  { 140, 1 },
+  { 159, 1 },
+  { 160, 1 },
+  { 160, 1 },
+  { 177, 1 },
+  { 177, 1 },
+  { 177, 1 },
+  { 207, 0 },
+  { 207, 1 },
+  { 207, 4 },
+  { 207, 6 },
+  { 208, 1 },
+  { 208, 2 },
+  { 195, 1 },
+  { 195, 2 },
+  { 195, 2 },
+  { 130, 2 },
+  { 130, 0 },
+  { 129, 3 },
+  { 129, 1 },
+  { 129, 2 },
+  { 129, 2 },
+  { 129, 2 },
+  { 129, 3 },
+  { 129, 3 },
+  { 129, 2 },
+  { 129, 3 },
+  { 129, 3 },
+  { 129, 2 },
+  { 134, 2 },
+  { 134, 3 },
+  { 134, 4 },
+  { 134, 2 },
+  { 134, 5 },
+  { 134, 4 },
+  { 134, 1 },
+  { 134, 2 },
+  { 188, 0 },
+  { 188, 2 },
+  { 187, 2 },
+  { 187, 3 },
+  { 187, 3 },
+  { 187, 3 },
+  { 186, 2 },
+  { 186, 2 },
+  { 186, 1 },
+  { 186, 1 },
+  { 146, 3 },
+  { 146, 2 },
+  { 164, 0 },
+  { 164, 2 },
+  { 164, 2 },
+  { 143, 0 },
+  { 143, 2 },
+  { 142, 3 },
+  { 142, 2 },
+  { 142, 1 },
+  { 200, 2 },
+  { 200, 6 },
+  { 200, 5 },
+  { 200, 3 },
+  { 200, 10 },
+  { 147, 0 },
+  { 147, 1 },
+  { 180, 0 },
+  { 180, 3 },
+  { 182, 0 },
+  { 182, 2 },
+  { 189, 1 },
+  { 189, 1 },
+  { 189, 1 },
+  { 189, 1 },
+  { 189, 1 },
+  { 135, 3 },
+  { 135, 6 },
+  { 135, 3 },
+  { 135, 1 },
+  { 192, 1 },
+  { 192, 3 },
+  { 176, 1 },
+  { 176, 2 },
+  { 176, 1 },
+  { 176, 1 },
+  { 181, 9 },
+  { 148, 1 },
+  { 148, 1 },
+  { 148, 0 },
+  { 190, 2 },
+  { 190, 0 },
+  { 191, 3 },
+  { 191, 2 },
+  { 191, 4 },
+  { 128, 2 },
+  { 128, 1 },
+  { 128, 0 },
+  { 156, 0 },
+  { 156, 2 },
+  { 199, 2 },
+  { 199, 0 },
+  { 193, 5 },
+  { 193, 7 },
+  { 170, 1 },
+  { 170, 1 },
+  { 170, 2 },
+  { 170, 3 },
+  { 170, 4 },
+  { 179, 2 },
+  { 179, 0 },
+  { 210, 4 },
+  { 210, 0 },
+  { 183, 0 },
+  { 183, 3 },
+  { 197, 5 },
+  { 197, 3 },
+  { 196, 1 },
+  { 198, 1 },
+  { 198, 1 },
+  { 198, 0 },
+  { 138, 0 },
+  { 138, 2 },
+  { 157, 0 },
+  { 157, 3 },
+  { 158, 0 },
+  { 158, 2 },
+  { 173, 0 },
+  { 173, 2 },
+  { 173, 4 },
+  { 174, 1 },
+  { 174, 1 },
+  { 135, 4 },
+  { 212, 0 },
+  { 212, 2 },
+  { 135, 6 },
+  { 194, 5 },
+  { 194, 3 },
+  { 135, 8 },
+  { 135, 5 },
+  { 168, 2 },
+  { 168, 1 },
+  { 169, 3 },
+  { 169, 1 },
+  { 167, 0 },
+  { 167, 3 },
+  { 166, 3 },
+  { 166, 1 },
+  { 152, 3 },
+  { 152, 1 },
+  { 152, 1 },
+  { 152, 1 },
+  { 152, 3 },
+  { 152, 2 },
+  { 152, 1 },
+  { 152, 1 },
+  { 152, 1 },
+  { 152, 4 },
+  { 152, 4 },
+  { 152, 3 },
+  { 152, 3 },
+  { 152, 3 },
+  { 152, 3 },
+  { 152, 3 },
+  { 152, 3 },
+  { 152, 3 },
+  { 152, 3 },
+  { 152, 3 },
+  { 152, 3 },
+  { 152, 3 },
+  { 152, 3 },
+  { 152, 3 },
+  { 152, 4 },
+  { 172, 1 },
+  { 172, 1 },
+  { 152, 3 },
+  { 152, 3 },
+  { 152, 3 },
+  { 152, 3 },
+  { 152, 3 },
+  { 152, 3 },
+  { 152, 2 },
+  { 152, 3 },
+  { 152, 2 },
+  { 152, 3 },
+  { 152, 4 },
+  { 152, 2 },
+  { 152, 2 },
+  { 152, 2 },
+  { 152, 2 },
+  { 152, 3 },
+  { 152, 5 },
+  { 152, 6 },
+  { 152, 5 },
+  { 152, 5 },
+  { 152, 6 },
+  { 152, 6 },
+  { 152, 5 },
+  { 132, 5 },
+  { 132, 4 },
+  { 131, 2 },
+  { 131, 0 },
+  { 133, 1 },
+  { 133, 0 },
+  { 154, 3 },
+  { 154, 1 },
+  { 153, 1 },
+  { 153, 0 },
+  { 135, 10 },
+  { 209, 1 },
+  { 209, 0 },
+  { 163, 0 },
+  { 163, 3 },
+  { 162, 3 },
+  { 162, 1 },
+  { 161, 1 },
+  { 135, 3 },
+  { 135, 8 },
+  { 135, 5 },
+  { 135, 1 },
+  { 135, 2 },
+  { 135, 4 },
+  { 135, 4 },
+  { 135, 4 },
+  { 135, 4 },
+  { 135, 5 },
+  { 135, 2 },
+  { 184, 2 },
+  { 175, 2 },
+  { 178, 1 },
+  { 178, 1 },
+  { 185, 1 },
+  { 185, 0 },
+  { 135, 12 },
+  { 206, 1 },
+  { 206, 1 },
+  { 206, 2 },
+  { 206, 0 },
+  { 205, 1 },
+  { 205, 1 },
+  { 205, 1 },
+  { 205, 3 },
+  { 155, 0 },
+  { 155, 3 },
+  { 155, 3 },
+  { 211, 0 },
+  { 211, 2 },
+  { 204, 3 },
+  { 204, 0 },
+  { 203, 6 },
+  { 203, 9 },
+  { 203, 6 },
+  { 203, 4 },
+  { 203, 1 },
+  { 152, 4 },
+  { 152, 6 },
+  { 152, 6 },
+  { 152, 6 },
+  { 135, 3 },
+};
+
+static void yy_accept(yyParser*);  /* Forward Declaration */
+
+/*
+** Perform a reduce action and the shift that must immediately
+** follow the reduce.
+*/
+static void yy_reduce(
+  yyParser *yypParser,         /* The parser */
+  int yyruleno                 /* Number of the rule by which to reduce */
+){
+  int yygoto;                     /* The next state */
+  int yyact;                      /* The next action */
+  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
+  yyStackEntry *yymsp;            /* The top of the parser's stack */
+  int yysize;                     /* Amount to pop the stack */
+  sqliteParserARG_FETCH;
+  yymsp = yypParser->yytop;
+#ifndef NDEBUG
+  if( yyTraceFILE && yyruleno>=0 
+        && yyruleno<sizeof(yyRuleName)/sizeof(yyRuleName[0]) ){
+    fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
+      yyRuleName[yyruleno]);
+  }
+#endif /* NDEBUG */
+
+  switch( yyruleno ){
+  /* Beginning here are the reduction cases.  A typical example
+  ** follows:
+  **   case 0:
+  **  #line <lineno> <grammarfile>
+  **     { ... }           // User supplied code
+  **  #line <lineno> <thisfile>
+  **     break;
+  */
+      case 0:
+        /* No destructor defined for cmdlist */
+        break;
+      case 1:
+        /* No destructor defined for ecmd */
+        break;
+      case 2:
+        /* No destructor defined for cmdlist */
+        /* No destructor defined for ecmd */
+        break;
+      case 3:
+        /* No destructor defined for explain */
+        /* No destructor defined for cmdx */
+        /* No destructor defined for SEMI */
+        break;
+      case 4:
+        /* No destructor defined for SEMI */
+        break;
+      case 5:
+#line 77 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ sqliteExec(pParse); }
+#line 4877 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for cmd */
+        break;
+      case 6:
+#line 78 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ sqliteBeginParse(pParse, 1); }
+#line 4883 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for EXPLAIN */
+        break;
+      case 7:
+#line 79 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ sqliteBeginParse(pParse, 0); }
+#line 4889 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 8:
+#line 84 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteBeginTransaction(pParse,yymsp[0].minor.yy136);}
+#line 4894 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for BEGIN */
+        /* No destructor defined for trans_opt */
+        break;
+      case 9:
+        break;
+      case 10:
+        /* No destructor defined for TRANSACTION */
+        break;
+      case 11:
+        /* No destructor defined for TRANSACTION */
+        /* No destructor defined for nm */
+        break;
+      case 12:
+#line 88 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteCommitTransaction(pParse);}
+#line 4910 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for COMMIT */
+        /* No destructor defined for trans_opt */
+        break;
+      case 13:
+#line 89 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteCommitTransaction(pParse);}
+#line 4917 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for END */
+        /* No destructor defined for trans_opt */
+        break;
+      case 14:
+#line 90 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteRollbackTransaction(pParse);}
+#line 4924 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for ROLLBACK */
+        /* No destructor defined for trans_opt */
+        break;
+      case 15:
+        /* No destructor defined for create_table */
+        /* No destructor defined for create_table_args */
+        break;
+      case 16:
+#line 95 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+   sqliteStartTable(pParse,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy324,yymsp[-2].minor.yy136,0);
+}
+#line 4937 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for TABLE */
+        break;
+      case 17:
+#line 99 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = pParse->isTemp || !pParse->initFlag;}
+#line 4943 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for TEMP */
+        break;
+      case 18:
+#line 100 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = pParse->isTemp;}
+#line 4949 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 19:
+#line 101 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  sqliteEndTable(pParse,&yymsp[0].minor.yy0,0);
+}
+#line 4956 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for LP */
+        /* No destructor defined for columnlist */
+        /* No destructor defined for conslist_opt */
+        break;
+      case 20:
+#line 104 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  sqliteEndTable(pParse,0,yymsp[0].minor.yy207);
+  sqliteSelectDelete(yymsp[0].minor.yy207);
+}
+#line 4967 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for AS */
+        break;
+      case 21:
+        /* No destructor defined for columnlist */
+        /* No destructor defined for COMMA */
+        /* No destructor defined for column */
+        break;
+      case 22:
+        /* No destructor defined for column */
+        break;
+      case 23:
+        /* No destructor defined for columnid */
+        /* No destructor defined for type */
+        /* No destructor defined for carglist */
+        break;
+      case 24:
+#line 116 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteAddColumn(pParse,&yymsp[0].minor.yy324);}
+#line 4986 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 25:
+#line 122 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy324 = yymsp[0].minor.yy0;}
+#line 4991 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 26:
+#line 138 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy324 = yymsp[0].minor.yy0;}
+#line 4996 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 27:
+#line 139 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy324 = yymsp[0].minor.yy0;}
+#line 5001 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 28:
+#line 144 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy324 = yymsp[0].minor.yy0;}
+#line 5006 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 29:
+#line 145 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy324 = yymsp[0].minor.yy0;}
+#line 5011 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 30:
+#line 146 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy324 = yymsp[0].minor.yy0;}
+#line 5016 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 31:
+        break;
+      case 32:
+#line 149 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteAddColumnType(pParse,&yymsp[0].minor.yy324,&yymsp[0].minor.yy324);}
+#line 5023 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 33:
+#line 150 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteAddColumnType(pParse,&yymsp[-3].minor.yy324,&yymsp[0].minor.yy0);}
+#line 5028 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for LP */
+        /* No destructor defined for signed */
+        break;
+      case 34:
+#line 152 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteAddColumnType(pParse,&yymsp[-5].minor.yy324,&yymsp[0].minor.yy0);}
+#line 5035 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for LP */
+        /* No destructor defined for signed */
+        /* No destructor defined for COMMA */
+        /* No destructor defined for signed */
+        break;
+      case 35:
+#line 154 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy324 = yymsp[0].minor.yy324;}
+#line 5044 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 36:
+#line 155 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy324 = yymsp[-1].minor.yy324;}
+#line 5049 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for ids */
+        break;
+      case 37:
+        /* No destructor defined for INTEGER */
+        break;
+      case 38:
+        /* No destructor defined for PLUS */
+        /* No destructor defined for INTEGER */
+        break;
+      case 39:
+        /* No destructor defined for MINUS */
+        /* No destructor defined for INTEGER */
+        break;
+      case 40:
+        /* No destructor defined for carglist */
+        /* No destructor defined for carg */
+        break;
+      case 41:
+        break;
+      case 42:
+        /* No destructor defined for CONSTRAINT */
+        /* No destructor defined for nm */
+        /* No destructor defined for ccons */
+        break;
+      case 43:
+        /* No destructor defined for ccons */
+        break;
+      case 44:
+#line 163 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteAddDefaultValue(pParse,&yymsp[0].minor.yy0,0);}
+#line 5080 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DEFAULT */
+        break;
+      case 45:
+#line 164 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteAddDefaultValue(pParse,&yymsp[0].minor.yy0,0);}
+#line 5086 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DEFAULT */
+        break;
+      case 46:
+#line 165 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteAddDefaultValue(pParse,&yymsp[0].minor.yy0,0);}
+#line 5092 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DEFAULT */
+        break;
+      case 47:
+#line 166 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteAddDefaultValue(pParse,&yymsp[0].minor.yy0,0);}
+#line 5098 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DEFAULT */
+        /* No destructor defined for PLUS */
+        break;
+      case 48:
+#line 167 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteAddDefaultValue(pParse,&yymsp[0].minor.yy0,1);}
+#line 5105 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DEFAULT */
+        /* No destructor defined for MINUS */
+        break;
+      case 49:
+#line 168 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteAddDefaultValue(pParse,&yymsp[0].minor.yy0,0);}
+#line 5112 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DEFAULT */
+        break;
+      case 50:
+#line 169 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteAddDefaultValue(pParse,&yymsp[0].minor.yy0,0);}
+#line 5118 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DEFAULT */
+        /* No destructor defined for PLUS */
+        break;
+      case 51:
+#line 170 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteAddDefaultValue(pParse,&yymsp[0].minor.yy0,1);}
+#line 5125 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DEFAULT */
+        /* No destructor defined for MINUS */
+        break;
+      case 52:
+        /* No destructor defined for DEFAULT */
+        /* No destructor defined for NULL */
+        break;
+      case 53:
+        /* No destructor defined for NULL */
+        /* No destructor defined for onconf */
+        break;
+      case 54:
+#line 177 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteAddNotNull(pParse, yymsp[0].minor.yy136);}
+#line 5140 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for NOT */
+        /* No destructor defined for NULL */
+        break;
+      case 55:
+#line 178 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteAddPrimaryKey(pParse,0,yymsp[0].minor.yy136);}
+#line 5147 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for PRIMARY */
+        /* No destructor defined for KEY */
+        /* No destructor defined for sortorder */
+        break;
+      case 56:
+#line 179 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteCreateIndex(pParse,0,0,0,yymsp[0].minor.yy136,0,0);}
+#line 5155 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for UNIQUE */
+        break;
+      case 57:
+        /* No destructor defined for CHECK */
+        /* No destructor defined for LP */
+  yy_destructor(152,&yymsp[-2].minor);
+        /* No destructor defined for RP */
+        /* No destructor defined for onconf */
+        break;
+      case 58:
+#line 182 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteCreateForeignKey(pParse,0,&yymsp[-2].minor.yy324,yymsp[-1].minor.yy268,yymsp[0].minor.yy136);}
+#line 5168 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for REFERENCES */
+        break;
+      case 59:
+#line 183 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteDeferForeignKey(pParse,yymsp[0].minor.yy136);}
+#line 5174 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 60:
+#line 184 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+   sqliteAddCollateType(pParse, sqliteCollateType(yymsp[0].minor.yy324.z, yymsp[0].minor.yy324.n));
+}
+#line 5181 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for COLLATE */
+        break;
+      case 61:
+#line 194 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = OE_Restrict * 0x010101; }
+#line 5187 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 62:
+#line 195 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = (yymsp[-1].minor.yy136 & yymsp[0].minor.yy83.mask) | yymsp[0].minor.yy83.value; }
+#line 5192 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 63:
+#line 197 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy83.value = 0;     yygotominor.yy83.mask = 0x000000; }
+#line 5197 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for MATCH */
+        /* No destructor defined for nm */
+        break;
+      case 64:
+#line 198 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy83.value = yymsp[0].minor.yy136;     yygotominor.yy83.mask = 0x0000ff; }
+#line 5204 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for ON */
+        /* No destructor defined for DELETE */
+        break;
+      case 65:
+#line 199 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy83.value = yymsp[0].minor.yy136<<8;  yygotominor.yy83.mask = 0x00ff00; }
+#line 5211 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for ON */
+        /* No destructor defined for UPDATE */
+        break;
+      case 66:
+#line 200 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy83.value = yymsp[0].minor.yy136<<16; yygotominor.yy83.mask = 0xff0000; }
+#line 5218 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for ON */
+        /* No destructor defined for INSERT */
+        break;
+      case 67:
+#line 202 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = OE_SetNull; }
+#line 5225 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for SET */
+        /* No destructor defined for NULL */
+        break;
+      case 68:
+#line 203 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = OE_SetDflt; }
+#line 5232 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for SET */
+        /* No destructor defined for DEFAULT */
+        break;
+      case 69:
+#line 204 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = OE_Cascade; }
+#line 5239 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for CASCADE */
+        break;
+      case 70:
+#line 205 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = OE_Restrict; }
+#line 5245 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for RESTRICT */
+        break;
+      case 71:
+#line 207 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = yymsp[0].minor.yy136;}
+#line 5251 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for NOT */
+        /* No destructor defined for DEFERRABLE */
+        break;
+      case 72:
+#line 208 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = yymsp[0].minor.yy136;}
+#line 5258 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DEFERRABLE */
+        break;
+      case 73:
+#line 210 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = 0;}
+#line 5264 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 74:
+#line 211 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = 1;}
+#line 5269 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for INITIALLY */
+        /* No destructor defined for DEFERRED */
+        break;
+      case 75:
+#line 212 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = 0;}
+#line 5276 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for INITIALLY */
+        /* No destructor defined for IMMEDIATE */
+        break;
+      case 76:
+        break;
+      case 77:
+        /* No destructor defined for COMMA */
+        /* No destructor defined for conslist */
+        break;
+      case 78:
+        /* No destructor defined for conslist */
+        /* No destructor defined for COMMA */
+        /* No destructor defined for tcons */
+        break;
+      case 79:
+        /* No destructor defined for conslist */
+        /* No destructor defined for tcons */
+        break;
+      case 80:
+        /* No destructor defined for tcons */
+        break;
+      case 81:
+        /* No destructor defined for CONSTRAINT */
+        /* No destructor defined for nm */
+        break;
+      case 82:
+#line 224 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteAddPrimaryKey(pParse,yymsp[-2].minor.yy268,yymsp[0].minor.yy136);}
+#line 5305 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for PRIMARY */
+        /* No destructor defined for KEY */
+        /* No destructor defined for LP */
+        /* No destructor defined for RP */
+        break;
+      case 83:
+#line 226 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteCreateIndex(pParse,0,0,yymsp[-2].minor.yy268,yymsp[0].minor.yy136,0,0);}
+#line 5314 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for UNIQUE */
+        /* No destructor defined for LP */
+        /* No destructor defined for RP */
+        break;
+      case 84:
+        /* No destructor defined for CHECK */
+  yy_destructor(152,&yymsp[-1].minor);
+        /* No destructor defined for onconf */
+        break;
+      case 85:
+#line 229 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+    sqliteCreateForeignKey(pParse, yymsp[-6].minor.yy268, &yymsp[-3].minor.yy324, yymsp[-2].minor.yy268, yymsp[-1].minor.yy136);
+    sqliteDeferForeignKey(pParse, yymsp[0].minor.yy136);
+}
+#line 5330 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for FOREIGN */
+        /* No destructor defined for KEY */
+        /* No destructor defined for LP */
+        /* No destructor defined for RP */
+        /* No destructor defined for REFERENCES */
+        break;
+      case 86:
+#line 234 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = 0;}
+#line 5340 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 87:
+#line 235 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = yymsp[0].minor.yy136;}
+#line 5345 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 88:
+#line 243 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = OE_Default; }
+#line 5350 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 89:
+#line 244 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = yymsp[0].minor.yy136; }
+#line 5355 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for ON */
+        /* No destructor defined for CONFLICT */
+        break;
+      case 90:
+#line 245 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = OE_Default; }
+#line 5362 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 91:
+#line 246 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = yymsp[0].minor.yy136; }
+#line 5367 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for OR */
+        break;
+      case 92:
+#line 247 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = OE_Rollback; }
+#line 5373 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for ROLLBACK */
+        break;
+      case 93:
+#line 248 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = OE_Abort; }
+#line 5379 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for ABORT */
+        break;
+      case 94:
+#line 249 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = OE_Fail; }
+#line 5385 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for FAIL */
+        break;
+      case 95:
+#line 250 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = OE_Ignore; }
+#line 5391 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for IGNORE */
+        break;
+      case 96:
+#line 251 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = OE_Replace; }
+#line 5397 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for REPLACE */
+        break;
+      case 97:
+#line 255 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteDropTable(pParse,&yymsp[0].minor.yy324,0);}
+#line 5403 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DROP */
+        /* No destructor defined for TABLE */
+        break;
+      case 98:
+#line 259 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  sqliteCreateView(pParse, &yymsp[-5].minor.yy0, &yymsp[-2].minor.yy324, yymsp[0].minor.yy207, yymsp[-4].minor.yy136);
+}
+#line 5412 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for VIEW */
+        /* No destructor defined for AS */
+        break;
+      case 99:
+#line 262 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  sqliteDropTable(pParse, &yymsp[0].minor.yy324, 1);
+}
+#line 5421 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DROP */
+        /* No destructor defined for VIEW */
+        break;
+      case 100:
+#line 268 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  sqliteSelect(pParse, yymsp[0].minor.yy207, SRT_Callback, 0, 0, 0, 0);
+  sqliteSelectDelete(yymsp[0].minor.yy207);
+}
+#line 5431 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 101:
+#line 278 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy207 = yymsp[0].minor.yy207;}
+#line 5436 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 102:
+#line 279 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  if( yymsp[0].minor.yy207 ){
+    yymsp[0].minor.yy207->op = yymsp[-1].minor.yy136;
+    yymsp[0].minor.yy207->pPrior = yymsp[-2].minor.yy207;
+  }
+  yygotominor.yy207 = yymsp[0].minor.yy207;
+}
+#line 5447 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 103:
+#line 287 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = TK_UNION;}
+#line 5452 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for UNION */
+        break;
+      case 104:
+#line 288 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = TK_ALL;}
+#line 5458 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for UNION */
+        /* No destructor defined for ALL */
+        break;
+      case 105:
+#line 289 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = TK_INTERSECT;}
+#line 5465 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for INTERSECT */
+        break;
+      case 106:
+#line 290 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = TK_EXCEPT;}
+#line 5471 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for EXCEPT */
+        break;
+      case 107:
+#line 292 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy207 = sqliteSelectNew(yymsp[-6].minor.yy168,yymsp[-5].minor.yy289,yymsp[-4].minor.yy272,yymsp[-3].minor.yy168,yymsp[-2].minor.yy272,yymsp[-1].minor.yy168,yymsp[-7].minor.yy136,yymsp[0].minor.yy336.limit,yymsp[0].minor.yy336.offset);
+}
+#line 5479 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for SELECT */
+        break;
+      case 108:
+#line 300 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = 1;}
+#line 5485 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DISTINCT */
+        break;
+      case 109:
+#line 301 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = 0;}
+#line 5491 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for ALL */
+        break;
+      case 110:
+#line 302 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = 0;}
+#line 5497 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 111:
+#line 313 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy168 = yymsp[-1].minor.yy168;}
+#line 5502 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for COMMA */
+        break;
+      case 112:
+#line 314 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy168 = 0;}
+#line 5508 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 113:
+#line 315 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+   yygotominor.yy168 = sqliteExprListAppend(yymsp[-2].minor.yy168,yymsp[-1].minor.yy272,yymsp[0].minor.yy324.n?&yymsp[0].minor.yy324:0);
+}
+#line 5515 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 114:
+#line 318 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy168 = sqliteExprListAppend(yymsp[-1].minor.yy168, sqliteExpr(TK_ALL, 0, 0, 0), 0);
+}
+#line 5522 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for STAR */
+        break;
+      case 115:
+#line 321 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  Expr *pRight = sqliteExpr(TK_ALL, 0, 0, 0);
+  Expr *pLeft = sqliteExpr(TK_ID, 0, 0, &yymsp[-2].minor.yy324);
+  yygotominor.yy168 = sqliteExprListAppend(yymsp[-3].minor.yy168, sqliteExpr(TK_DOT, pLeft, pRight, 0), 0);
+}
+#line 5532 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DOT */
+        /* No destructor defined for STAR */
+        break;
+      case 116:
+#line 331 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy324 = yymsp[0].minor.yy324; }
+#line 5539 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for AS */
+        break;
+      case 117:
+#line 332 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy324 = yymsp[0].minor.yy324; }
+#line 5545 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 118:
+#line 333 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy324.n = 0; }
+#line 5550 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 119:
+#line 345 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy289 = sqliteMalloc(sizeof(*yygotominor.yy289));}
+#line 5555 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 120:
+#line 346 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy289 = yymsp[0].minor.yy289;}
+#line 5560 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for FROM */
+        break;
+      case 121:
+#line 351 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+   yygotominor.yy289 = yymsp[-1].minor.yy289;
+   if( yygotominor.yy289 && yygotominor.yy289->nSrc>0 ) yygotominor.yy289->a[yygotominor.yy289->nSrc-1].jointype = yymsp[0].minor.yy136;
+}
+#line 5569 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 122:
+#line 355 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy289 = 0;}
+#line 5574 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 123:
+#line 356 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy289 = sqliteSrcListAppend(yymsp[-4].minor.yy289,&yymsp[-3].minor.yy324);
+  if( yymsp[-2].minor.yy324.n ) sqliteSrcListAddAlias(yygotominor.yy289,&yymsp[-2].minor.yy324);
+  if( yymsp[-1].minor.yy272 ){
+    if( yygotominor.yy289 && yygotominor.yy289->nSrc>1 ){ yygotominor.yy289->a[yygotominor.yy289->nSrc-2].pOn = yymsp[-1].minor.yy272; }
+    else { sqliteExprDelete(yymsp[-1].minor.yy272); }
+  }
+  if( yymsp[0].minor.yy268 ){
+    if( yygotominor.yy289 && yygotominor.yy289->nSrc>1 ){ yygotominor.yy289->a[yygotominor.yy289->nSrc-2].pUsing = yymsp[0].minor.yy268; }
+    else { sqliteIdListDelete(yymsp[0].minor.yy268); }
+  }
+}
+#line 5590 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 124:
+#line 368 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy289 = sqliteSrcListAppend(yymsp[-6].minor.yy289,0);
+  yygotominor.yy289->a[yygotominor.yy289->nSrc-1].pSelect = yymsp[-4].minor.yy207;
+  if( yymsp[-2].minor.yy324.n ) sqliteSrcListAddAlias(yygotominor.yy289,&yymsp[-2].minor.yy324);
+  if( yymsp[-1].minor.yy272 ){
+    if( yygotominor.yy289 && yygotominor.yy289->nSrc>1 ){ yygotominor.yy289->a[yygotominor.yy289->nSrc-2].pOn = yymsp[-1].minor.yy272; }
+    else { sqliteExprDelete(yymsp[-1].minor.yy272); }
+  }
+  if( yymsp[0].minor.yy268 ){
+    if( yygotominor.yy289 && yygotominor.yy289->nSrc>1 ){ yygotominor.yy289->a[yygotominor.yy289->nSrc-2].pUsing = yymsp[0].minor.yy268; }
+    else { sqliteIdListDelete(yymsp[0].minor.yy268); }
+  }
+}
+#line 5607 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for LP */
+        /* No destructor defined for RP */
+        break;
+      case 125:
+#line 384 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = JT_INNER; }
+#line 5614 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for COMMA */
+        break;
+      case 126:
+#line 385 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = JT_INNER; }
+#line 5620 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for JOIN */
+        break;
+      case 127:
+#line 386 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = sqliteJoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
+#line 5626 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for JOIN */
+        break;
+      case 128:
+#line 387 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = sqliteJoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy324,0); }
+#line 5632 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for JOIN */
+        break;
+      case 129:
+#line 389 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = sqliteJoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy324,&yymsp[-1].minor.yy324); }
+#line 5638 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for JOIN */
+        break;
+      case 130:
+#line 393 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = yymsp[0].minor.yy272;}
+#line 5644 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for ON */
+        break;
+      case 131:
+#line 394 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = 0;}
+#line 5650 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 132:
+#line 398 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy268 = yymsp[-1].minor.yy268;}
+#line 5655 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for USING */
+        /* No destructor defined for LP */
+        /* No destructor defined for RP */
+        break;
+      case 133:
+#line 399 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy268 = 0;}
+#line 5663 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 134:
+#line 409 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy168 = 0;}
+#line 5668 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 135:
+#line 410 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy168 = yymsp[0].minor.yy168;}
+#line 5673 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for ORDER */
+        /* No destructor defined for BY */
+        break;
+      case 136:
+#line 411 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy168 = sqliteExprListAppend(yymsp[-4].minor.yy168,yymsp[-2].minor.yy272,0);
+  if( yygotominor.yy168 ) yygotominor.yy168->a[yygotominor.yy168->nExpr-1].sortOrder = yymsp[-1].minor.yy136+yymsp[0].minor.yy136;
+}
+#line 5683 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for COMMA */
+        break;
+      case 137:
+#line 415 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy168 = sqliteExprListAppend(0,yymsp[-2].minor.yy272,0);
+  if( yygotominor.yy168 ) yygotominor.yy168->a[0].sortOrder = yymsp[-1].minor.yy136+yymsp[0].minor.yy136;
+}
+#line 5692 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 138:
+#line 419 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = yymsp[0].minor.yy272;}
+#line 5697 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 139:
+#line 424 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = SQLITE_SO_ASC;}
+#line 5702 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for ASC */
+        break;
+      case 140:
+#line 425 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = SQLITE_SO_DESC;}
+#line 5708 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DESC */
+        break;
+      case 141:
+#line 426 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = SQLITE_SO_ASC;}
+#line 5714 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 142:
+#line 427 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = SQLITE_SO_UNK;}
+#line 5719 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 143:
+#line 428 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = sqliteCollateType(yymsp[0].minor.yy324.z, yymsp[0].minor.yy324.n);}
+#line 5724 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for COLLATE */
+        break;
+      case 144:
+#line 432 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy168 = 0;}
+#line 5730 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 145:
+#line 433 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy168 = yymsp[0].minor.yy168;}
+#line 5735 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for GROUP */
+        /* No destructor defined for BY */
+        break;
+      case 146:
+#line 437 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = 0;}
+#line 5742 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 147:
+#line 438 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = yymsp[0].minor.yy272;}
+#line 5747 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for HAVING */
+        break;
+      case 148:
+#line 441 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy336.limit = -1; yygotominor.yy336.offset = 0;}
+#line 5753 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 149:
+#line 442 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy336.limit = atoi(yymsp[0].minor.yy0.z); yygotominor.yy336.offset = 0;}
+#line 5758 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for LIMIT */
+        break;
+      case 150:
+#line 444 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy336.limit = atoi(yymsp[-2].minor.yy0.z); yygotominor.yy336.offset = atoi(yymsp[0].minor.yy0.z);}
+#line 5764 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for LIMIT */
+        /* No destructor defined for limit_sep */
+        break;
+      case 151:
+        /* No destructor defined for OFFSET */
+        break;
+      case 152:
+        /* No destructor defined for COMMA */
+        break;
+      case 153:
+#line 451 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteDeleteFrom(pParse, &yymsp[-1].minor.yy324, yymsp[0].minor.yy272);}
+#line 5777 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DELETE */
+        /* No destructor defined for FROM */
+        break;
+      case 154:
+#line 456 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = 0;}
+#line 5784 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 155:
+#line 457 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = yymsp[0].minor.yy272;}
+#line 5789 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for WHERE */
+        break;
+      case 156:
+#line 465 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteUpdate(pParse,&yymsp[-3].minor.yy324,yymsp[-1].minor.yy168,yymsp[0].minor.yy272,yymsp[-4].minor.yy136);}
+#line 5795 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for UPDATE */
+        /* No destructor defined for SET */
+        break;
+      case 157:
+#line 468 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy168 = sqliteExprListAppend(yymsp[-4].minor.yy168,yymsp[0].minor.yy272,&yymsp[-2].minor.yy324);}
+#line 5802 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for COMMA */
+        /* No destructor defined for EQ */
+        break;
+      case 158:
+#line 469 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy168 = sqliteExprListAppend(0,yymsp[0].minor.yy272,&yymsp[-2].minor.yy324);}
+#line 5809 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for EQ */
+        break;
+      case 159:
+#line 474 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteInsert(pParse, &yymsp[-5].minor.yy324, yymsp[-1].minor.yy168, 0, yymsp[-4].minor.yy268, yymsp[-7].minor.yy136);}
+#line 5815 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for INTO */
+        /* No destructor defined for VALUES */
+        /* No destructor defined for LP */
+        /* No destructor defined for RP */
+        break;
+      case 160:
+#line 476 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteInsert(pParse, &yymsp[-2].minor.yy324, 0, yymsp[0].minor.yy207, yymsp[-1].minor.yy268, yymsp[-4].minor.yy136);}
+#line 5824 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for INTO */
+        break;
+      case 161:
+#line 479 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = yymsp[0].minor.yy136;}
+#line 5830 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for INSERT */
+        break;
+      case 162:
+#line 480 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = OE_Replace;}
+#line 5836 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for REPLACE */
+        break;
+      case 163:
+#line 486 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy168 = sqliteExprListAppend(yymsp[-2].minor.yy168,yymsp[0].minor.yy272,0);}
+#line 5842 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for COMMA */
+        break;
+      case 164:
+#line 487 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy168 = sqliteExprListAppend(0,yymsp[0].minor.yy272,0);}
+#line 5848 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 165:
+#line 494 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy268 = 0;}
+#line 5853 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 166:
+#line 495 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy268 = yymsp[-1].minor.yy268;}
+#line 5858 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for LP */
+        /* No destructor defined for RP */
+        break;
+      case 167:
+#line 496 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy268 = sqliteIdListAppend(yymsp[-2].minor.yy268,&yymsp[0].minor.yy324);}
+#line 5865 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for COMMA */
+        break;
+      case 168:
+#line 497 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy268 = sqliteIdListAppend(0,&yymsp[0].minor.yy324);}
+#line 5871 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 169:
+#line 516 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = yymsp[-1].minor.yy272; sqliteExprSpan(yygotominor.yy272,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); }
+#line 5876 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 170:
+#line 517 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_NULL, 0, 0, &yymsp[0].minor.yy0);}
+#line 5881 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 171:
+#line 518 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_ID, 0, 0, &yymsp[0].minor.yy0);}
+#line 5886 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 172:
+#line 519 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_ID, 0, 0, &yymsp[0].minor.yy0);}
+#line 5891 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 173:
+#line 520 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  Expr *temp1 = sqliteExpr(TK_ID, 0, 0, &yymsp[-2].minor.yy324);
+  Expr *temp2 = sqliteExpr(TK_ID, 0, 0, &yymsp[0].minor.yy324);
+  yygotominor.yy272 = sqliteExpr(TK_DOT, temp1, temp2, 0);
+}
+#line 5900 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DOT */
+        break;
+      case 174:
+#line 526 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = yymsp[-1].minor.yy272; ExprSetProperty(yygotominor.yy272,EP_Oracle8Join);}
+#line 5906 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for ORACLE_OUTER_JOIN */
+        break;
+      case 175:
+#line 527 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_INTEGER, 0, 0, &yymsp[0].minor.yy0);}
+#line 5912 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 176:
+#line 528 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_FLOAT, 0, 0, &yymsp[0].minor.yy0);}
+#line 5917 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 177:
+#line 529 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_STRING, 0, 0, &yymsp[0].minor.yy0);}
+#line 5922 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 178:
+#line 530 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExprFunction(yymsp[-1].minor.yy168, &yymsp[-3].minor.yy0);
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
+}
+#line 5930 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for LP */
+        break;
+      case 179:
+#line 534 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExprFunction(0, &yymsp[-3].minor.yy0);
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
+}
+#line 5939 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for LP */
+        /* No destructor defined for STAR */
+        break;
+      case 180:
+#line 538 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_AND, yymsp[-2].minor.yy272, yymsp[0].minor.yy272, 0);}
+#line 5946 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for AND */
+        break;
+      case 181:
+#line 539 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_OR, yymsp[-2].minor.yy272, yymsp[0].minor.yy272, 0);}
+#line 5952 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for OR */
+        break;
+      case 182:
+#line 540 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_LT, yymsp[-2].minor.yy272, yymsp[0].minor.yy272, 0);}
+#line 5958 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for LT */
+        break;
+      case 183:
+#line 541 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_GT, yymsp[-2].minor.yy272, yymsp[0].minor.yy272, 0);}
+#line 5964 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for GT */
+        break;
+      case 184:
+#line 542 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_LE, yymsp[-2].minor.yy272, yymsp[0].minor.yy272, 0);}
+#line 5970 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for LE */
+        break;
+      case 185:
+#line 543 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_GE, yymsp[-2].minor.yy272, yymsp[0].minor.yy272, 0);}
+#line 5976 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for GE */
+        break;
+      case 186:
+#line 544 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_NE, yymsp[-2].minor.yy272, yymsp[0].minor.yy272, 0);}
+#line 5982 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for NE */
+        break;
+      case 187:
+#line 545 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_EQ, yymsp[-2].minor.yy272, yymsp[0].minor.yy272, 0);}
+#line 5988 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for EQ */
+        break;
+      case 188:
+#line 546 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_BITAND, yymsp[-2].minor.yy272, yymsp[0].minor.yy272, 0);}
+#line 5994 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for BITAND */
+        break;
+      case 189:
+#line 547 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_BITOR, yymsp[-2].minor.yy272, yymsp[0].minor.yy272, 0);}
+#line 6000 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for BITOR */
+        break;
+      case 190:
+#line 548 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_LSHIFT, yymsp[-2].minor.yy272, yymsp[0].minor.yy272, 0);}
+#line 6006 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for LSHIFT */
+        break;
+      case 191:
+#line 549 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_RSHIFT, yymsp[-2].minor.yy272, yymsp[0].minor.yy272, 0);}
+#line 6012 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for RSHIFT */
+        break;
+      case 192:
+#line 550 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  ExprList *pList = sqliteExprListAppend(0, yymsp[0].minor.yy272, 0);
+  pList = sqliteExprListAppend(pList, yymsp[-2].minor.yy272, 0);
+  yygotominor.yy272 = sqliteExprFunction(pList, 0);
+  if( yygotominor.yy272 ) yygotominor.yy272->op = yymsp[-1].minor.yy136;
+  sqliteExprSpan(yygotominor.yy272, &yymsp[-2].minor.yy272->span, &yymsp[0].minor.yy272->span);
+}
+#line 6024 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 193:
+#line 557 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  ExprList *pList = sqliteExprListAppend(0, yymsp[0].minor.yy272, 0);
+  pList = sqliteExprListAppend(pList, yymsp[-3].minor.yy272, 0);
+  yygotominor.yy272 = sqliteExprFunction(pList, 0);
+  if( yygotominor.yy272 ) yygotominor.yy272->op = yymsp[-1].minor.yy136;
+  yygotominor.yy272 = sqliteExpr(TK_NOT, yygotominor.yy272, 0, 0);
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-3].minor.yy272->span,&yymsp[0].minor.yy272->span);
+}
+#line 6036 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for NOT */
+        break;
+      case 194:
+#line 566 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = TK_LIKE;}
+#line 6042 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for LIKE */
+        break;
+      case 195:
+#line 567 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy136 = TK_GLOB;}
+#line 6048 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for GLOB */
+        break;
+      case 196:
+#line 568 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_PLUS, yymsp[-2].minor.yy272, yymsp[0].minor.yy272, 0);}
+#line 6054 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for PLUS */
+        break;
+      case 197:
+#line 569 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_MINUS, yymsp[-2].minor.yy272, yymsp[0].minor.yy272, 0);}
+#line 6060 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for MINUS */
+        break;
+      case 198:
+#line 570 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_STAR, yymsp[-2].minor.yy272, yymsp[0].minor.yy272, 0);}
+#line 6066 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for STAR */
+        break;
+      case 199:
+#line 571 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_SLASH, yymsp[-2].minor.yy272, yymsp[0].minor.yy272, 0);}
+#line 6072 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for SLASH */
+        break;
+      case 200:
+#line 572 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_REM, yymsp[-2].minor.yy272, yymsp[0].minor.yy272, 0);}
+#line 6078 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for REM */
+        break;
+      case 201:
+#line 573 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = sqliteExpr(TK_CONCAT, yymsp[-2].minor.yy272, yymsp[0].minor.yy272, 0);}
+#line 6084 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for CONCAT */
+        break;
+      case 202:
+#line 574 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_ISNULL, yymsp[-1].minor.yy272, 0, 0);
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-1].minor.yy272->span,&yymsp[0].minor.yy0);
+}
+#line 6093 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 203:
+#line 578 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_ISNULL, yymsp[-2].minor.yy272, 0, 0);
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-2].minor.yy272->span,&yymsp[0].minor.yy0);
+}
+#line 6101 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for IS */
+        break;
+      case 204:
+#line 582 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_NOTNULL, yymsp[-1].minor.yy272, 0, 0);
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-1].minor.yy272->span,&yymsp[0].minor.yy0);
+}
+#line 6110 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 205:
+#line 586 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_NOTNULL, yymsp[-2].minor.yy272, 0, 0);
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-2].minor.yy272->span,&yymsp[0].minor.yy0);
+}
+#line 6118 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for NOT */
+        break;
+      case 206:
+#line 590 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_NOTNULL, yymsp[-3].minor.yy272, 0, 0);
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-3].minor.yy272->span,&yymsp[0].minor.yy0);
+}
+#line 6127 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for IS */
+        /* No destructor defined for NOT */
+        break;
+      case 207:
+#line 594 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_NOT, yymsp[0].minor.yy272, 0, 0);
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy272->span);
+}
+#line 6137 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 208:
+#line 598 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_BITNOT, yymsp[0].minor.yy272, 0, 0);
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy272->span);
+}
+#line 6145 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 209:
+#line 602 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_UMINUS, yymsp[0].minor.yy272, 0, 0);
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy272->span);
+}
+#line 6153 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 210:
+#line 606 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_UPLUS, yymsp[0].minor.yy272, 0, 0);
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy272->span);
+}
+#line 6161 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 211:
+#line 610 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_SELECT, 0, 0, 0);
+  if( yygotominor.yy272 ) yygotominor.yy272->pSelect = yymsp[-1].minor.yy207;
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
+}
+#line 6170 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 212:
+#line 615 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  ExprList *pList = sqliteExprListAppend(0, yymsp[-2].minor.yy272, 0);
+  pList = sqliteExprListAppend(pList, yymsp[0].minor.yy272, 0);
+  yygotominor.yy272 = sqliteExpr(TK_BETWEEN, yymsp[-4].minor.yy272, 0, 0);
+  if( yygotominor.yy272 ) yygotominor.yy272->pList = pList;
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-4].minor.yy272->span,&yymsp[0].minor.yy272->span);
+}
+#line 6181 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for BETWEEN */
+        /* No destructor defined for AND */
+        break;
+      case 213:
+#line 622 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  ExprList *pList = sqliteExprListAppend(0, yymsp[-2].minor.yy272, 0);
+  pList = sqliteExprListAppend(pList, yymsp[0].minor.yy272, 0);
+  yygotominor.yy272 = sqliteExpr(TK_BETWEEN, yymsp[-5].minor.yy272, 0, 0);
+  if( yygotominor.yy272 ) yygotominor.yy272->pList = pList;
+  yygotominor.yy272 = sqliteExpr(TK_NOT, yygotominor.yy272, 0, 0);
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-5].minor.yy272->span,&yymsp[0].minor.yy272->span);
+}
+#line 6195 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for NOT */
+        /* No destructor defined for BETWEEN */
+        /* No destructor defined for AND */
+        break;
+      case 214:
+#line 630 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_IN, yymsp[-4].minor.yy272, 0, 0);
+  if( yygotominor.yy272 ) yygotominor.yy272->pList = yymsp[-1].minor.yy168;
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-4].minor.yy272->span,&yymsp[0].minor.yy0);
+}
+#line 6207 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for IN */
+        /* No destructor defined for LP */
+        break;
+      case 215:
+#line 635 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_IN, yymsp[-4].minor.yy272, 0, 0);
+  if( yygotominor.yy272 ) yygotominor.yy272->pSelect = yymsp[-1].minor.yy207;
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-4].minor.yy272->span,&yymsp[0].minor.yy0);
+}
+#line 6218 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for IN */
+        /* No destructor defined for LP */
+        break;
+      case 216:
+#line 640 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_IN, yymsp[-5].minor.yy272, 0, 0);
+  if( yygotominor.yy272 ) yygotominor.yy272->pList = yymsp[-1].minor.yy168;
+  yygotominor.yy272 = sqliteExpr(TK_NOT, yygotominor.yy272, 0, 0);
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-5].minor.yy272->span,&yymsp[0].minor.yy0);
+}
+#line 6230 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for NOT */
+        /* No destructor defined for IN */
+        /* No destructor defined for LP */
+        break;
+      case 217:
+#line 646 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_IN, yymsp[-5].minor.yy272, 0, 0);
+  if( yygotominor.yy272 ) yygotominor.yy272->pSelect = yymsp[-1].minor.yy207;
+  yygotominor.yy272 = sqliteExpr(TK_NOT, yygotominor.yy272, 0, 0);
+  sqliteExprSpan(yygotominor.yy272,&yymsp[-5].minor.yy272->span,&yymsp[0].minor.yy0);
+}
+#line 6243 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for NOT */
+        /* No destructor defined for IN */
+        /* No destructor defined for LP */
+        break;
+      case 218:
+#line 654 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_CASE, yymsp[-3].minor.yy272, yymsp[-1].minor.yy272, 0);
+  if( yygotominor.yy272 ) yygotominor.yy272->pList = yymsp[-2].minor.yy168;
+  sqliteExprSpan(yygotominor.yy272, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
+}
+#line 6255 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 219:
+#line 661 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy168 = sqliteExprListAppend(yymsp[-4].minor.yy168, yymsp[-2].minor.yy272, 0);
+  yygotominor.yy168 = sqliteExprListAppend(yygotominor.yy168, yymsp[0].minor.yy272, 0);
+}
+#line 6263 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for WHEN */
+        /* No destructor defined for THEN */
+        break;
+      case 220:
+#line 665 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy168 = sqliteExprListAppend(0, yymsp[-2].minor.yy272, 0);
+  yygotominor.yy168 = sqliteExprListAppend(yygotominor.yy168, yymsp[0].minor.yy272, 0);
+}
+#line 6273 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for WHEN */
+        /* No destructor defined for THEN */
+        break;
+      case 221:
+#line 670 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = yymsp[0].minor.yy272;}
+#line 6280 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for ELSE */
+        break;
+      case 222:
+#line 671 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = 0;}
+#line 6286 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 223:
+#line 673 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = yymsp[0].minor.yy272;}
+#line 6291 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 224:
+#line 674 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = 0;}
+#line 6296 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 225:
+#line 682 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy168 = sqliteExprListAppend(yymsp[-2].minor.yy168,yymsp[0].minor.yy272,0);}
+#line 6301 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for COMMA */
+        break;
+      case 226:
+#line 683 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy168 = sqliteExprListAppend(0,yymsp[0].minor.yy272,0);}
+#line 6307 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 227:
+#line 684 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = yymsp[0].minor.yy272;}
+#line 6312 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 228:
+#line 685 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy272 = 0;}
+#line 6317 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 229:
+#line 690 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  if( yymsp[-8].minor.yy136!=OE_None ) yymsp[-8].minor.yy136 = yymsp[0].minor.yy136;
+  if( yymsp[-8].minor.yy136==OE_Default) yymsp[-8].minor.yy136 = OE_Abort;
+  sqliteCreateIndex(pParse, &yymsp[-6].minor.yy324, &yymsp[-4].minor.yy324, yymsp[-2].minor.yy268, yymsp[-8].minor.yy136, &yymsp[-9].minor.yy0, &yymsp[-1].minor.yy0);
+}
+#line 6326 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for INDEX */
+        /* No destructor defined for ON */
+        /* No destructor defined for LP */
+        break;
+      case 230:
+#line 697 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = OE_Abort; }
+#line 6334 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for UNIQUE */
+        break;
+      case 231:
+#line 698 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = OE_None; }
+#line 6340 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 232:
+#line 706 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy268 = 0;}
+#line 6345 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 233:
+#line 707 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy268 = yymsp[-1].minor.yy268;}
+#line 6350 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for LP */
+        /* No destructor defined for RP */
+        break;
+      case 234:
+#line 708 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy268 = sqliteIdListAppend(yymsp[-2].minor.yy268,&yymsp[0].minor.yy324);}
+#line 6357 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for COMMA */
+        break;
+      case 235:
+#line 709 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy268 = sqliteIdListAppend(0,&yymsp[0].minor.yy324);}
+#line 6363 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 236:
+#line 710 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy324 = yymsp[0].minor.yy324;}
+#line 6368 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 237:
+#line 715 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteDropIndex(pParse, &yymsp[0].minor.yy324);}
+#line 6373 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DROP */
+        /* No destructor defined for INDEX */
+        break;
+      case 238:
+#line 721 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteCopy(pParse,&yymsp[-5].minor.yy324,&yymsp[-3].minor.yy324,&yymsp[0].minor.yy0,yymsp[-6].minor.yy136);}
+#line 6380 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for COPY */
+        /* No destructor defined for FROM */
+        /* No destructor defined for USING */
+        /* No destructor defined for DELIMITERS */
+        break;
+      case 239:
+#line 723 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteCopy(pParse,&yymsp[-2].minor.yy324,&yymsp[0].minor.yy324,0,yymsp[-3].minor.yy136);}
+#line 6389 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for COPY */
+        /* No destructor defined for FROM */
+        break;
+      case 240:
+#line 727 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteVacuum(pParse,0);}
+#line 6396 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for VACUUM */
+        break;
+      case 241:
+#line 728 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqliteVacuum(pParse,&yymsp[0].minor.yy324);}
+#line 6402 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for VACUUM */
+        break;
+      case 242:
+#line 732 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqlitePragma(pParse,&yymsp[-2].minor.yy324,&yymsp[0].minor.yy324,0);}
+#line 6408 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for PRAGMA */
+        /* No destructor defined for EQ */
+        break;
+      case 243:
+#line 733 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqlitePragma(pParse,&yymsp[-2].minor.yy324,&yymsp[0].minor.yy0,0);}
+#line 6415 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for PRAGMA */
+        /* No destructor defined for EQ */
+        break;
+      case 244:
+#line 734 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqlitePragma(pParse,&yymsp[-2].minor.yy324,&yymsp[0].minor.yy324,0);}
+#line 6422 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for PRAGMA */
+        /* No destructor defined for EQ */
+        break;
+      case 245:
+#line 735 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqlitePragma(pParse,&yymsp[-2].minor.yy324,&yymsp[0].minor.yy324,1);}
+#line 6429 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for PRAGMA */
+        /* No destructor defined for EQ */
+        break;
+      case 246:
+#line 736 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqlitePragma(pParse,&yymsp[-3].minor.yy324,&yymsp[-1].minor.yy324,0);}
+#line 6436 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for PRAGMA */
+        /* No destructor defined for LP */
+        /* No destructor defined for RP */
+        break;
+      case 247:
+#line 737 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{sqlitePragma(pParse,&yymsp[0].minor.yy324,&yymsp[0].minor.yy324,0);}
+#line 6444 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for PRAGMA */
+        break;
+      case 248:
+#line 738 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy324 = yymsp[0].minor.yy324;}
+#line 6450 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for plus_opt */
+        break;
+      case 249:
+#line 739 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy324 = yymsp[0].minor.yy324;}
+#line 6456 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for MINUS */
+        break;
+      case 250:
+#line 740 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy324 = yymsp[0].minor.yy0;}
+#line 6462 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 251:
+#line 741 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy324 = yymsp[0].minor.yy0;}
+#line 6467 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 252:
+        /* No destructor defined for PLUS */
+        break;
+      case 253:
+        break;
+      case 254:
+#line 748 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  Token all;
+  all.z = yymsp[-11].minor.yy0.z;
+  all.n = (yymsp[0].minor.yy0.z - yymsp[-11].minor.yy0.z) + yymsp[0].minor.yy0.n;
+  sqliteCreateTrigger(pParse, &yymsp[-9].minor.yy324, yymsp[-8].minor.yy136, yymsp[-7].minor.yy72.a, yymsp[-7].minor.yy72.b, &yymsp[-5].minor.yy324, yymsp[-4].minor.yy136, yymsp[-3].minor.yy176, yymsp[-1].minor.yy209, &all);
+}
+#line 6482 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for TRIGGER */
+        /* No destructor defined for ON */
+        /* No destructor defined for BEGIN */
+        break;
+      case 255:
+#line 756 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = TK_BEFORE; }
+#line 6490 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for BEFORE */
+        break;
+      case 256:
+#line 757 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = TK_AFTER;  }
+#line 6496 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for AFTER */
+        break;
+      case 257:
+#line 758 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = TK_INSTEAD;}
+#line 6502 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for INSTEAD */
+        /* No destructor defined for OF */
+        break;
+      case 258:
+#line 759 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = TK_BEFORE; }
+#line 6509 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 259:
+#line 763 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy72.a = TK_DELETE; yygotominor.yy72.b = 0; }
+#line 6514 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DELETE */
+        break;
+      case 260:
+#line 764 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy72.a = TK_INSERT; yygotominor.yy72.b = 0; }
+#line 6520 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for INSERT */
+        break;
+      case 261:
+#line 765 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy72.a = TK_UPDATE; yygotominor.yy72.b = 0;}
+#line 6526 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for UPDATE */
+        break;
+      case 262:
+#line 766 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy72.a = TK_UPDATE; yygotominor.yy72.b = yymsp[0].minor.yy268; }
+#line 6532 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for UPDATE */
+        /* No destructor defined for OF */
+        break;
+      case 263:
+#line 769 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = TK_ROW; }
+#line 6539 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 264:
+#line 770 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = TK_ROW; }
+#line 6544 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for FOR */
+        /* No destructor defined for EACH */
+        /* No destructor defined for ROW */
+        break;
+      case 265:
+#line 771 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy136 = TK_STATEMENT; }
+#line 6552 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for FOR */
+        /* No destructor defined for EACH */
+        /* No destructor defined for STATEMENT */
+        break;
+      case 266:
+#line 774 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy176 = 0; }
+#line 6560 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 267:
+#line 775 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy176 = yymsp[0].minor.yy272; }
+#line 6565 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for WHEN */
+        break;
+      case 268:
+#line 778 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yymsp[-2].minor.yy209->pNext = yymsp[0].minor.yy209 ; yygotominor.yy209 = yymsp[-2].minor.yy209; }
+#line 6572 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for SEMI */
+        break;
+      case 269:
+#line 780 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy209 = 0; }
+#line 6578 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 270:
+#line 785 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{ yygotominor.yy209 = sqliteTriggerUpdateStep(&yymsp[-3].minor.yy324, yymsp[-1].minor.yy168, yymsp[0].minor.yy272, yymsp[-4].minor.yy136); }
+#line 6583 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for UPDATE */
+        /* No destructor defined for SET */
+        break;
+      case 271:
+#line 790 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy209 = sqliteTriggerInsertStep(&yymsp[-5].minor.yy324, yymsp[-4].minor.yy268, yymsp[-1].minor.yy168, 0, yymsp[-7].minor.yy136);}
+#line 6590 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for INSERT */
+        /* No destructor defined for INTO */
+        /* No destructor defined for VALUES */
+        /* No destructor defined for LP */
+        /* No destructor defined for RP */
+        break;
+      case 272:
+#line 793 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy209 = sqliteTriggerInsertStep(&yymsp[-2].minor.yy324, yymsp[-1].minor.yy268, 0, yymsp[0].minor.yy207, yymsp[-4].minor.yy136);}
+#line 6600 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for INSERT */
+        /* No destructor defined for INTO */
+        break;
+      case 273:
+#line 797 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy209 = sqliteTriggerDeleteStep(&yymsp[-1].minor.yy324, yymsp[0].minor.yy272);}
+#line 6607 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DELETE */
+        /* No destructor defined for FROM */
+        break;
+      case 274:
+#line 800 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{yygotominor.yy209 = sqliteTriggerSelectStep(yymsp[0].minor.yy207); }
+#line 6614 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        break;
+      case 275:
+#line 803 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_RAISE, 0, 0, 0); 
+  yygotominor.yy272->iColumn = OE_Ignore;
+  sqliteExprSpan(yygotominor.yy272, &yymsp[-3].minor.yy0, &yymsp[0].minor.yy0);
+}
+#line 6623 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for LP */
+        /* No destructor defined for IGNORE */
+        break;
+      case 276:
+#line 808 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_RAISE, 0, 0, &yymsp[-1].minor.yy324); 
+  yygotominor.yy272->iColumn = OE_Rollback;
+  sqliteExprSpan(yygotominor.yy272, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
+}
+#line 6634 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for LP */
+        /* No destructor defined for ROLLBACK */
+        /* No destructor defined for COMMA */
+        break;
+      case 277:
+#line 813 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_RAISE, 0, 0, &yymsp[-1].minor.yy324); 
+  yygotominor.yy272->iColumn = OE_Abort;
+  sqliteExprSpan(yygotominor.yy272, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
+}
+#line 6646 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for LP */
+        /* No destructor defined for ABORT */
+        /* No destructor defined for COMMA */
+        break;
+      case 278:
+#line 818 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+  yygotominor.yy272 = sqliteExpr(TK_RAISE, 0, 0, &yymsp[-1].minor.yy324); 
+  yygotominor.yy272->iColumn = OE_Fail;
+  sqliteExprSpan(yygotominor.yy272, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
+}
+#line 6658 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for LP */
+        /* No destructor defined for FAIL */
+        /* No destructor defined for COMMA */
+        break;
+      case 279:
+#line 825 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+{
+    sqliteDropTrigger(pParse,&yymsp[0].minor.yy324,0);
+}
+#line 6668 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+        /* No destructor defined for DROP */
+        /* No destructor defined for TRIGGER */
+        break;
+  };
+  yygoto = yyRuleInfo[yyruleno].lhs;
+  yysize = yyRuleInfo[yyruleno].nrhs;
+  yypParser->yyidx -= yysize;
+  yypParser->yytop -= yysize;
+  yyact = yy_find_parser_action(yypParser,yygoto);
+  if( yyact < YYNSTATE ){
+    yy_shift(yypParser,yyact,yygoto,&yygotominor);
+  }else if( yyact == YYNSTATE + YYNRULE + 1 ){
+    yy_accept(yypParser);
+  }
+}
+
+/*
+** The following code executes when the parse fails
+*/
+static void yy_parse_failed(
+  yyParser *yypParser           /* The parser */
+){
+  sqliteParserARG_FETCH;
+#ifndef NDEBUG
+  if( yyTraceFILE ){
+    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
+  }
+#endif
+  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
+  /* Here code is inserted which will be executed whenever the
+  ** parser fails */
+  sqliteParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
+}
+
+/*
+** The following code executes when a syntax error first occurs.
+*/
+static void yy_syntax_error(
+  yyParser *yypParser,           /* The parser */
+  int yymajor,                   /* The major type of the error token */
+  YYMINORTYPE yyminor            /* The minor type of the error token */
+){
+  sqliteParserARG_FETCH;
+#define TOKEN (yyminor.yy0)
+#line 23 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.y"
+
+  if( pParse->zErrMsg==0 ){
+    if( TOKEN.z[0] ){
+      sqliteSetNString(&pParse->zErrMsg, 
+          "near \"", -1, TOKEN.z, TOKEN.n, "\": syntax error", -1, 0);
+    }else{
+      sqliteSetString(&pParse->zErrMsg, "incomplete SQL statement", 0);
+    }
+  }
+  pParse->nErr++;
+
+#line 6725 "/home/wez/src/php/pear/PECL/sqlite/libsqlite/src/parse.c"
+  sqliteParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
+}
+
+/*
+** The following is executed when the parser accepts
+*/
+static void yy_accept(
+  yyParser *yypParser           /* The parser */
+){
+  sqliteParserARG_FETCH;
+#ifndef NDEBUG
+  if( yyTraceFILE ){
+    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
+  }
+#endif
+  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
+  /* Here code is inserted which will be executed whenever the
+  ** parser accepts */
+  sqliteParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
+}
+
+/* The main parser program.
+** The first argument is a pointer to a structure obtained from
+** "sqliteParserAlloc" which describes the current state of the parser.
+** The second argument is the major token number.  The third is
+** the minor token.  The fourth optional argument is whatever the
+** user wants (and specified in the grammar) and is available for
+** use by the action routines.
+**
+** Inputs:
+** <ul>
+** <li> A pointer to the parser (an opaque structure.)
+** <li> The major token number.
+** <li> The minor token number.
+** <li> An option argument of a grammar-specified type.
+** </ul>
+**
+** Outputs:
+** None.
+*/
+void sqliteParser(
+  void *yyp,                   /* The parser */
+  int yymajor,                 /* The major token code number */
+  sqliteParserTOKENTYPE yyminor       /* The value for the token */
+  sqliteParserARG_PDECL               /* Optional %extra_argument parameter */
+){
+  YYMINORTYPE yyminorunion;
+  int yyact;            /* The parser action. */
+  int yyendofinput;     /* True if we are at the end of input */
+  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
+  yyParser *yypParser;  /* The parser */
+
+  /* (re)initialize the parser, if necessary */
+  yypParser = (yyParser*)yyp;
+  if( yypParser->yyidx<0 ){
+    if( yymajor==0 ) return;
+    yypParser->yyidx = 0;
+    yypParser->yyerrcnt = -1;
+    yypParser->yytop = &yypParser->yystack[0];
+    yypParser->yytop->stateno = 0;
+    yypParser->yytop->major = 0;
+  }
+  yyminorunion.yy0 = yyminor;
+  yyendofinput = (yymajor==0);
+  sqliteParserARG_STORE;
+
+#ifndef NDEBUG
+  if( yyTraceFILE ){
+    fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
+  }
+#endif
+
+  do{
+    yyact = yy_find_parser_action(yypParser,yymajor);
+    if( yyact<YYNSTATE ){
+      yy_shift(yypParser,yyact,yymajor,&yyminorunion);
+      yypParser->yyerrcnt--;
+      if( yyendofinput && yypParser->yyidx>=0 ){
+        yymajor = 0;
+      }else{
+        yymajor = YYNOCODE;
+      }
+    }else if( yyact < YYNSTATE + YYNRULE ){
+      yy_reduce(yypParser,yyact-YYNSTATE);
+    }else if( yyact == YY_ERROR_ACTION ){
+#ifndef NDEBUG
+      if( yyTraceFILE ){
+        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
+      }
+#endif
+#ifdef YYERRORSYMBOL
+      /* A syntax error has occurred.
+      ** The response to an error depends upon whether or not the
+      ** grammar defines an error token "ERROR".  
+      **
+      ** This is what we do if the grammar does define ERROR:
+      **
+      **  * Call the %syntax_error function.
+      **
+      **  * Begin popping the stack until we enter a state where
+      **    it is legal to shift the error symbol, then shift
+      **    the error symbol.
+      **
+      **  * Set the error count to three.
+      **
+      **  * Begin accepting and shifting new tokens.  No new error
+      **    processing will occur until three tokens have been
+      **    shifted successfully.
+      **
+      */
+      if( yypParser->yyerrcnt<0 ){
+        yy_syntax_error(yypParser,yymajor,yyminorunion);
+      }
+      if( yypParser->yytop->major==YYERRORSYMBOL || yyerrorhit ){
+#ifndef NDEBUG
+        if( yyTraceFILE ){
+          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
+             yyTracePrompt,yyTokenName[yymajor]);
+        }
+#endif
+        yy_destructor(yymajor,&yyminorunion);
+        yymajor = YYNOCODE;
+      }else{
+         while(
+          yypParser->yyidx >= 0 &&
+          yypParser->yytop->major != YYERRORSYMBOL &&
+          (yyact = yy_find_parser_action(yypParser,YYERRORSYMBOL)) >= YYNSTATE
+        ){
+          yy_pop_parser_stack(yypParser);
+        }
+        if( yypParser->yyidx < 0 || yymajor==0 ){
+          yy_destructor(yymajor,&yyminorunion);
+          yy_parse_failed(yypParser);
+          yymajor = YYNOCODE;
+        }else if( yypParser->yytop->major!=YYERRORSYMBOL ){
+          YYMINORTYPE u2;
+          u2.YYERRSYMDT = 0;
+          yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
+        }
+      }
+      yypParser->yyerrcnt = 3;
+      yyerrorhit = 1;
+#else  /* YYERRORSYMBOL is not defined */
+      /* This is what we do if the grammar does not define ERROR:
+      **
+      **  * Report an error message, and throw away the input token.
+      **
+      **  * If the input token is $, then fail the parse.
+      **
+      ** As before, subsequent error messages are suppressed until
+      ** three input tokens have been successfully shifted.
+      */
+      if( yypParser->yyerrcnt<=0 ){
+        yy_syntax_error(yypParser,yymajor,yyminorunion);
+      }
+      yypParser->yyerrcnt = 3;
+      yy_destructor(yymajor,&yyminorunion);
+      if( yyendofinput ){
+        yy_parse_failed(yypParser);
+      }
+      yymajor = YYNOCODE;
+#endif
+    }else{
+      yy_accept(yypParser);
+      yymajor = YYNOCODE;
+    }
+  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
+  return;
+}
diff --git a/ext/sqlite/libsqlite/src/parse.h b/ext/sqlite/libsqlite/src/parse.h
new file mode 100644 (file)
index 0000000..16dd234
--- /dev/null
@@ -0,0 +1,127 @@
+#define TK_ABORT                           1
+#define TK_AFTER                           2
+#define TK_AGG_FUNCTION                    3
+#define TK_ALL                             4
+#define TK_AND                             5
+#define TK_AS                              6
+#define TK_ASC                             7
+#define TK_BEFORE                          8
+#define TK_BEGIN                           9
+#define TK_BETWEEN                        10
+#define TK_BITAND                         11
+#define TK_BITNOT                         12
+#define TK_BITOR                          13
+#define TK_BY                             14
+#define TK_CASCADE                        15
+#define TK_CASE                           16
+#define TK_CHECK                          17
+#define TK_CLUSTER                        18
+#define TK_COLLATE                        19
+#define TK_COLUMN                         20
+#define TK_COMMA                          21
+#define TK_COMMENT                        22
+#define TK_COMMIT                         23
+#define TK_CONCAT                         24
+#define TK_CONFLICT                       25
+#define TK_CONSTRAINT                     26
+#define TK_COPY                           27
+#define TK_CREATE                         28
+#define TK_DEFAULT                        29
+#define TK_DEFERRABLE                     30
+#define TK_DEFERRED                       31
+#define TK_DELETE                         32
+#define TK_DELIMITERS                     33
+#define TK_DESC                           34
+#define TK_DISTINCT                       35
+#define TK_DOT                            36
+#define TK_DROP                           37
+#define TK_EACH                           38
+#define TK_ELSE                           39
+#define TK_END                            40
+#define TK_END_OF_FILE                    41
+#define TK_EQ                             42
+#define TK_EXCEPT                         43
+#define TK_EXPLAIN                        44
+#define TK_FAIL                           45
+#define TK_FLOAT                          46
+#define TK_FOR                            47
+#define TK_FOREIGN                        48
+#define TK_FROM                           49
+#define TK_FUNCTION                       50
+#define TK_GE                             51
+#define TK_GLOB                           52
+#define TK_GROUP                          53
+#define TK_GT                             54
+#define TK_HAVING                         55
+#define TK_ID                             56
+#define TK_IGNORE                         57
+#define TK_ILLEGAL                        58
+#define TK_IMMEDIATE                      59
+#define TK_IN                             60
+#define TK_INDEX                          61
+#define TK_INITIALLY                      62
+#define TK_INSERT                         63
+#define TK_INSTEAD                        64
+#define TK_INTEGER                        65
+#define TK_INTERSECT                      66
+#define TK_INTO                           67
+#define TK_IS                             68
+#define TK_ISNULL                         69
+#define TK_JOIN                           70
+#define TK_JOIN_KW                        71
+#define TK_KEY                            72
+#define TK_LE                             73
+#define TK_LIKE                           74
+#define TK_LIMIT                          75
+#define TK_LP                             76
+#define TK_LSHIFT                         77
+#define TK_LT                             78
+#define TK_MATCH                          79
+#define TK_MINUS                          80
+#define TK_NE                             81
+#define TK_NOT                            82
+#define TK_NOTNULL                        83
+#define TK_NULL                           84
+#define TK_OF                             85
+#define TK_OFFSET                         86
+#define TK_ON                             87
+#define TK_OR                             88
+#define TK_ORACLE_OUTER_JOIN              89
+#define TK_ORDER                          90
+#define TK_PLUS                           91
+#define TK_PRAGMA                         92
+#define TK_PRIMARY                        93
+#define TK_RAISE                          94
+#define TK_REFERENCES                     95
+#define TK_REM                            96
+#define TK_REPLACE                        97
+#define TK_RESTRICT                       98
+#define TK_ROLLBACK                       99
+#define TK_ROW                            100
+#define TK_RP                             101
+#define TK_RSHIFT                         102
+#define TK_SELECT                         103
+#define TK_SEMI                           104
+#define TK_SET                            105
+#define TK_SLASH                          106
+#define TK_SPACE                          107
+#define TK_STAR                           108
+#define TK_STATEMENT                      109
+#define TK_STRING                         110
+#define TK_TABLE                          111
+#define TK_TEMP                           112
+#define TK_THEN                           113
+#define TK_TRANSACTION                    114
+#define TK_TRIGGER                        115
+#define TK_UMINUS                         116
+#define TK_UNCLOSED_STRING                117
+#define TK_UNION                          118
+#define TK_UNIQUE                         119
+#define TK_UPDATE                         120
+#define TK_UPLUS                          121
+#define TK_USING                          122
+#define TK_VACUUM                         123
+#define TK_VALUES                         124
+#define TK_VIEW                           125
+#define TK_WHEN                           126
+#define TK_WHERE                          127
diff --git a/ext/sqlite/libsqlite/src/parse.y b/ext/sqlite/libsqlite/src/parse.y
new file mode 100644 (file)
index 0000000..598dc37
--- /dev/null
@@ -0,0 +1,827 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains SQLite's grammar for SQL.  Process this file
+** using the lemon parser generator to generate C code that runs
+** the parser.  Lemon will also generate a header file containing
+** numeric codes for all of the tokens.
+**
+** @(#) $Id$
+*/
+%token_prefix TK_
+%token_type {Token}
+%default_type {Token}
+%extra_argument {Parse *pParse}
+%syntax_error {
+  if( pParse->zErrMsg==0 ){
+    if( TOKEN.z[0] ){
+      sqliteSetNString(&pParse->zErrMsg, 
+          "near \"", -1, TOKEN.z, TOKEN.n, "\": syntax error", -1, 0);
+    }else{
+      sqliteSetString(&pParse->zErrMsg, "incomplete SQL statement", 0);
+    }
+  }
+  pParse->nErr++;
+}
+%name sqliteParser
+%include {
+#include "sqliteInt.h"
+#include "parse.h"
+
+/*
+** An instance of this structure holds information about the
+** LIMIT clause of a SELECT statement.
+*/
+struct LimitVal {
+  int limit;    /* The LIMIT value.  -1 if there is no limit */
+  int offset;   /* The OFFSET.  0 if there is none */
+};
+
+/*
+** An instance of the following structure describes the event of a
+** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
+** TK_DELETE, or TK_INSTEAD.  If the event is of the form
+**
+**      UPDATE ON (a,b,c)
+**
+** Then the "b" IdList records the list "a,b,c".
+*/
+struct TrigEvent { int a; IdList * b; };
+
+} // end %include
+
+// These are extra tokens used by the lexer but never seen by the
+// parser.  We put them in a rule so that the parser generator will
+// add them to the parse.h output file.
+//
+%nonassoc END_OF_FILE ILLEGAL SPACE UNCLOSED_STRING COMMENT FUNCTION
+          COLUMN AGG_FUNCTION.
+
+// Input is zero or more commands.
+input ::= cmdlist.
+
+// A list of commands is zero or more commands
+//
+cmdlist ::= ecmd.
+cmdlist ::= cmdlist ecmd.
+ecmd ::= explain cmdx SEMI.
+ecmd ::= SEMI.
+cmdx ::= cmd.           { sqliteExec(pParse); }
+explain ::= EXPLAIN.    { sqliteBeginParse(pParse, 1); }
+explain ::= .           { sqliteBeginParse(pParse, 0); }
+
+///////////////////// Begin and end transactions. ////////////////////////////
+//
+
+cmd ::= BEGIN trans_opt onconf(R).  {sqliteBeginTransaction(pParse,R);}
+trans_opt ::= .
+trans_opt ::= TRANSACTION.
+trans_opt ::= TRANSACTION nm.
+cmd ::= COMMIT trans_opt.      {sqliteCommitTransaction(pParse);}
+cmd ::= END trans_opt.         {sqliteCommitTransaction(pParse);}
+cmd ::= ROLLBACK trans_opt.    {sqliteRollbackTransaction(pParse);}
+
+///////////////////// The CREATE TABLE statement ////////////////////////////
+//
+cmd ::= create_table create_table_args.
+create_table ::= CREATE(X) temp(T) TABLE nm(Y). {
+   sqliteStartTable(pParse,&X,&Y,T,0);
+}
+%type temp {int}
+temp(A) ::= TEMP.  {A = pParse->isTemp || !pParse->initFlag;}
+temp(A) ::= .      {A = pParse->isTemp;}
+create_table_args ::= LP columnlist conslist_opt RP(X). {
+  sqliteEndTable(pParse,&X,0);
+}
+create_table_args ::= AS select(S). {
+  sqliteEndTable(pParse,0,S);
+  sqliteSelectDelete(S);
+}
+columnlist ::= columnlist COMMA column.
+columnlist ::= column.
+
+// About the only information used for a column is the name of the
+// column.  The type is always just "text".  But the code will accept
+// an elaborate typename.  Perhaps someday we'll do something with it.
+//
+column ::= columnid type carglist. 
+columnid ::= nm(X).                {sqliteAddColumn(pParse,&X);}
+
+// An IDENTIFIER can be a generic identifier, or one of several
+// keywords.  Any non-standard keyword can also be an identifier.
+//
+%type id {Token}
+id(A) ::= ID(X).         {A = X;}
+
+// The following directive causes tokens ABORT, AFTER, ASC, etc. to
+// fallback to ID if they will not parse as their original value.
+// This obviates the need for the "id" nonterminal.
+//
+%fallback ID 
+  ABORT AFTER ASC BEFORE BEGIN CASCADE CLUSTER CONFLICT
+  COPY DEFERRED DELIMITERS DESC EACH END EXPLAIN FAIL FOR
+  IGNORE IMMEDIATE INITIALLY INSTEAD MATCH KEY
+  OF OFFSET PRAGMA RAISE REPLACE RESTRICT ROW STATEMENT
+  TEMP TRIGGER VACUUM VIEW.
+
+// And "ids" is an identifer-or-string.
+//
+%type ids {Token}
+ids(A) ::= ID(X).        {A = X;}
+ids(A) ::= STRING(X).    {A = X;}
+
+// The name of a column or table can be any of the following:
+//
+%type nm {Token}
+nm(A) ::= ID(X).         {A = X;}
+nm(A) ::= STRING(X).     {A = X;}
+nm(A) ::= JOIN_KW(X).    {A = X;}
+
+type ::= .
+type ::= typename(X).                    {sqliteAddColumnType(pParse,&X,&X);}
+type ::= typename(X) LP signed RP(Y).    {sqliteAddColumnType(pParse,&X,&Y);}
+type ::= typename(X) LP signed COMMA signed RP(Y).
+                                         {sqliteAddColumnType(pParse,&X,&Y);}
+%type typename {Token}
+typename(A) ::= ids(X).           {A = X;}
+typename(A) ::= typename(X) ids.  {A = X;}
+signed ::= INTEGER.
+signed ::= PLUS INTEGER.
+signed ::= MINUS INTEGER.
+carglist ::= carglist carg.
+carglist ::= .
+carg ::= CONSTRAINT nm ccons.
+carg ::= ccons.
+carg ::= DEFAULT STRING(X).          {sqliteAddDefaultValue(pParse,&X,0);}
+carg ::= DEFAULT ID(X).              {sqliteAddDefaultValue(pParse,&X,0);}
+carg ::= DEFAULT INTEGER(X).         {sqliteAddDefaultValue(pParse,&X,0);}
+carg ::= DEFAULT PLUS INTEGER(X).    {sqliteAddDefaultValue(pParse,&X,0);}
+carg ::= DEFAULT MINUS INTEGER(X).   {sqliteAddDefaultValue(pParse,&X,1);}
+carg ::= DEFAULT FLOAT(X).           {sqliteAddDefaultValue(pParse,&X,0);}
+carg ::= DEFAULT PLUS FLOAT(X).      {sqliteAddDefaultValue(pParse,&X,0);}
+carg ::= DEFAULT MINUS FLOAT(X).     {sqliteAddDefaultValue(pParse,&X,1);}
+carg ::= DEFAULT NULL. 
+
+// In addition to the type name, we also care about the primary key and
+// UNIQUE constraints.
+//
+ccons ::= NULL onconf.
+ccons ::= NOT NULL onconf(R).               {sqliteAddNotNull(pParse, R);}
+ccons ::= PRIMARY KEY sortorder onconf(R).  {sqliteAddPrimaryKey(pParse,0,R);}
+ccons ::= UNIQUE onconf(R).            {sqliteCreateIndex(pParse,0,0,0,R,0,0);}
+ccons ::= CHECK LP expr RP onconf.
+ccons ::= REFERENCES nm(T) idxlist_opt(TA) refargs(R).
+                                {sqliteCreateForeignKey(pParse,0,&T,TA,R);}
+ccons ::= defer_subclause(D).   {sqliteDeferForeignKey(pParse,D);}
+ccons ::= COLLATE id(C).  {
+   sqliteAddCollateType(pParse, sqliteCollateType(C.z, C.n));
+}
+
+// The next group of rules parses the arguments to a REFERENCES clause
+// that determine if the referential integrity checking is deferred or
+// or immediate and which determine what action to take if a ref-integ
+// check fails.
+//
+%type refargs {int}
+refargs(A) ::= .                     { A = OE_Restrict * 0x010101; }
+refargs(A) ::= refargs(X) refarg(Y). { A = (X & Y.mask) | Y.value; }
+%type refarg {struct {int value; int mask;}}
+refarg(A) ::= MATCH nm.              { A.value = 0;     A.mask = 0x000000; }
+refarg(A) ::= ON DELETE refact(X).   { A.value = X;     A.mask = 0x0000ff; }
+refarg(A) ::= ON UPDATE refact(X).   { A.value = X<<8;  A.mask = 0x00ff00; }
+refarg(A) ::= ON INSERT refact(X).   { A.value = X<<16; A.mask = 0xff0000; }
+%type refact {int}
+refact(A) ::= SET NULL.              { A = OE_SetNull; }
+refact(A) ::= SET DEFAULT.           { A = OE_SetDflt; }
+refact(A) ::= CASCADE.               { A = OE_Cascade; }
+refact(A) ::= RESTRICT.              { A = OE_Restrict; }
+%type defer_subclause {int}
+defer_subclause(A) ::= NOT DEFERRABLE init_deferred_pred_opt(X).  {A = X;}
+defer_subclause(A) ::= DEFERRABLE init_deferred_pred_opt(X).      {A = X;}
+%type init_deferred_pred_opt {int}
+init_deferred_pred_opt(A) ::= .                       {A = 0;}
+init_deferred_pred_opt(A) ::= INITIALLY DEFERRED.     {A = 1;}
+init_deferred_pred_opt(A) ::= INITIALLY IMMEDIATE.    {A = 0;}
+
+// For the time being, the only constraint we care about is the primary
+// key and UNIQUE.  Both create indices.
+//
+conslist_opt ::= .
+conslist_opt ::= COMMA conslist.
+conslist ::= conslist COMMA tcons.
+conslist ::= conslist tcons.
+conslist ::= tcons.
+tcons ::= CONSTRAINT nm.
+tcons ::= PRIMARY KEY LP idxlist(X) RP onconf(R).
+                                             {sqliteAddPrimaryKey(pParse,X,R);}
+tcons ::= UNIQUE LP idxlist(X) RP onconf(R).
+                                       {sqliteCreateIndex(pParse,0,0,X,R,0,0);}
+tcons ::= CHECK expr onconf.
+tcons ::= FOREIGN KEY LP idxlist(FA) RP
+          REFERENCES nm(T) idxlist_opt(TA) refargs(R) defer_subclause_opt(D). {
+    sqliteCreateForeignKey(pParse, FA, &T, TA, R);
+    sqliteDeferForeignKey(pParse, D);
+}
+%type defer_subclause_opt {int}
+defer_subclause_opt(A) ::= .                    {A = 0;}
+defer_subclause_opt(A) ::= defer_subclause(X).  {A = X;}
+
+// The following is a non-standard extension that allows us to declare the
+// default behavior when there is a constraint conflict.
+//
+%type onconf {int}
+%type orconf {int}
+%type resolvetype {int}
+onconf(A) ::= .                              { A = OE_Default; }
+onconf(A) ::= ON CONFLICT resolvetype(X).    { A = X; }
+orconf(A) ::= .                              { A = OE_Default; }
+orconf(A) ::= OR resolvetype(X).             { A = X; }
+resolvetype(A) ::= ROLLBACK.                 { A = OE_Rollback; }
+resolvetype(A) ::= ABORT.                    { A = OE_Abort; }
+resolvetype(A) ::= FAIL.                     { A = OE_Fail; }
+resolvetype(A) ::= IGNORE.                   { A = OE_Ignore; }
+resolvetype(A) ::= REPLACE.                  { A = OE_Replace; }
+
+////////////////////////// The DROP TABLE /////////////////////////////////////
+//
+cmd ::= DROP TABLE nm(X).          {sqliteDropTable(pParse,&X,0);}
+
+///////////////////// The CREATE VIEW statement /////////////////////////////
+//
+cmd ::= CREATE(X) temp(T) VIEW nm(Y) AS select(S). {
+  sqliteCreateView(pParse, &X, &Y, S, T);
+}
+cmd ::= DROP VIEW nm(X). {
+  sqliteDropTable(pParse, &X, 1);
+}
+
+//////////////////////// The SELECT statement /////////////////////////////////
+//
+cmd ::= select(X).  {
+  sqliteSelect(pParse, X, SRT_Callback, 0, 0, 0, 0);
+  sqliteSelectDelete(X);
+}
+
+%type select {Select*}
+%destructor select {sqliteSelectDelete($$);}
+%type oneselect {Select*}
+%destructor oneselect {sqliteSelectDelete($$);}
+
+select(A) ::= oneselect(X).                      {A = X;}
+select(A) ::= select(X) multiselect_op(Y) oneselect(Z).  {
+  if( Z ){
+    Z->op = Y;
+    Z->pPrior = X;
+  }
+  A = Z;
+}
+%type multiselect_op {int}
+multiselect_op(A) ::= UNION.      {A = TK_UNION;}
+multiselect_op(A) ::= UNION ALL.  {A = TK_ALL;}
+multiselect_op(A) ::= INTERSECT.  {A = TK_INTERSECT;}
+multiselect_op(A) ::= EXCEPT.     {A = TK_EXCEPT;}
+oneselect(A) ::= SELECT distinct(D) selcollist(W) from(X) where_opt(Y)
+                 groupby_opt(P) having_opt(Q) orderby_opt(Z) limit_opt(L). {
+  A = sqliteSelectNew(W,X,Y,P,Q,Z,D,L.limit,L.offset);
+}
+
+// The "distinct" nonterminal is true (1) if the DISTINCT keyword is
+// present and false (0) if it is not.
+//
+%type distinct {int}
+distinct(A) ::= DISTINCT.   {A = 1;}
+distinct(A) ::= ALL.        {A = 0;}
+distinct(A) ::= .           {A = 0;}
+
+// selcollist is a list of expressions that are to become the return
+// values of the SELECT statement.  The "*" in statements like
+// "SELECT * FROM ..." is encoded as a special expression with an
+// opcode of TK_ALL.
+//
+%type selcollist {ExprList*}
+%destructor selcollist {sqliteExprListDelete($$);}
+%type sclp {ExprList*}
+%destructor sclp {sqliteExprListDelete($$);}
+sclp(A) ::= selcollist(X) COMMA.             {A = X;}
+sclp(A) ::= .                                {A = 0;}
+selcollist(A) ::= sclp(P) expr(X) as(Y).     {
+   A = sqliteExprListAppend(P,X,Y.n?&Y:0);
+}
+selcollist(A) ::= sclp(P) STAR. {
+  A = sqliteExprListAppend(P, sqliteExpr(TK_ALL, 0, 0, 0), 0);
+}
+selcollist(A) ::= sclp(P) nm(X) DOT STAR. {
+  Expr *pRight = sqliteExpr(TK_ALL, 0, 0, 0);
+  Expr *pLeft = sqliteExpr(TK_ID, 0, 0, &X);
+  A = sqliteExprListAppend(P, sqliteExpr(TK_DOT, pLeft, pRight, 0), 0);
+}
+
+// An option "AS <id>" phrase that can follow one of the expressions that
+// define the result set, or one of the tables in the FROM clause.
+//
+%type as {Token}
+as(X) ::= AS nm(Y).    { X = Y; }
+as(X) ::= ids(Y).      { X = Y; }
+as(X) ::= .            { X.n = 0; }
+
+
+%type seltablist {SrcList*}
+%destructor seltablist {sqliteSrcListDelete($$);}
+%type stl_prefix {SrcList*}
+%destructor stl_prefix {sqliteSrcListDelete($$);}
+%type from {SrcList*}
+%destructor from {sqliteSrcListDelete($$);}
+
+// A complete FROM clause.
+//
+from(A) ::= .                                 {A = sqliteMalloc(sizeof(*A));}
+from(A) ::= FROM seltablist(X).               {A = X;}
+
+// "seltablist" is a "Select Table List" - the content of the FROM clause
+// in a SELECT statement.  "stl_prefix" is a prefix of this list.
+//
+stl_prefix(A) ::= seltablist(X) joinop(Y).    {
+   A = X;
+   if( A && A->nSrc>0 ) A->a[A->nSrc-1].jointype = Y;
+}
+stl_prefix(A) ::= .                           {A = 0;}
+seltablist(A) ::= stl_prefix(X) nm(Y) as(Z) on_opt(N) using_opt(U). {
+  A = sqliteSrcListAppend(X,&Y);
+  if( Z.n ) sqliteSrcListAddAlias(A,&Z);
+  if( N ){
+    if( A && A->nSrc>1 ){ A->a[A->nSrc-2].pOn = N; }
+    else { sqliteExprDelete(N); }
+  }
+  if( U ){
+    if( A && A->nSrc>1 ){ A->a[A->nSrc-2].pUsing = U; }
+    else { sqliteIdListDelete(U); }
+  }
+}
+seltablist(A) ::= stl_prefix(X) LP select(S) RP as(Z) on_opt(N) using_opt(U). {
+  A = sqliteSrcListAppend(X,0);
+  A->a[A->nSrc-1].pSelect = S;
+  if( Z.n ) sqliteSrcListAddAlias(A,&Z);
+  if( N ){
+    if( A && A->nSrc>1 ){ A->a[A->nSrc-2].pOn = N; }
+    else { sqliteExprDelete(N); }
+  }
+  if( U ){
+    if( A && A->nSrc>1 ){ A->a[A->nSrc-2].pUsing = U; }
+    else { sqliteIdListDelete(U); }
+  }
+}
+
+%type joinop {int}
+%type joinop2 {int}
+joinop(X) ::= COMMA.                   { X = JT_INNER; }
+joinop(X) ::= JOIN.                    { X = JT_INNER; }
+joinop(X) ::= JOIN_KW(A) JOIN.         { X = sqliteJoinType(pParse,&A,0,0); }
+joinop(X) ::= JOIN_KW(A) nm(B) JOIN.   { X = sqliteJoinType(pParse,&A,&B,0); }
+joinop(X) ::= JOIN_KW(A) nm(B) nm(C) JOIN.
+                                       { X = sqliteJoinType(pParse,&A,&B,&C); }
+
+%type on_opt {Expr*}
+%destructor on_opt {sqliteExprDelete($$);}
+on_opt(N) ::= ON expr(E).   {N = E;}
+on_opt(N) ::= .             {N = 0;}
+
+%type using_opt {IdList*}
+%destructor using_opt {sqliteIdListDelete($$);}
+using_opt(U) ::= USING LP idxlist(L) RP.  {U = L;}
+using_opt(U) ::= .                        {U = 0;}
+
+
+%type orderby_opt {ExprList*}
+%destructor orderby_opt {sqliteExprListDelete($$);}
+%type sortlist {ExprList*}
+%destructor sortlist {sqliteExprListDelete($$);}
+%type sortitem {Expr*}
+%destructor sortitem {sqliteExprDelete($$);}
+
+orderby_opt(A) ::= .                          {A = 0;}
+orderby_opt(A) ::= ORDER BY sortlist(X).      {A = X;}
+sortlist(A) ::= sortlist(X) COMMA sortitem(Y) collate(C) sortorder(Z). {
+  A = sqliteExprListAppend(X,Y,0);
+  if( A ) A->a[A->nExpr-1].sortOrder = C+Z;
+}
+sortlist(A) ::= sortitem(Y) collate(C) sortorder(Z). {
+  A = sqliteExprListAppend(0,Y,0);
+  if( A ) A->a[0].sortOrder = C+Z;
+}
+sortitem(A) ::= expr(X).   {A = X;}
+
+%type sortorder {int}
+%type collate {int}
+
+sortorder(A) ::= ASC.           {A = SQLITE_SO_ASC;}
+sortorder(A) ::= DESC.          {A = SQLITE_SO_DESC;}
+sortorder(A) ::= .              {A = SQLITE_SO_ASC;}
+collate(C) ::= .                {C = SQLITE_SO_UNK;}
+collate(C) ::= COLLATE id(X).   {C = sqliteCollateType(X.z, X.n);}
+
+%type groupby_opt {ExprList*}
+%destructor groupby_opt {sqliteExprListDelete($$);}
+groupby_opt(A) ::= .                      {A = 0;}
+groupby_opt(A) ::= GROUP BY exprlist(X).  {A = X;}
+
+%type having_opt {Expr*}
+%destructor having_opt {sqliteExprDelete($$);}
+having_opt(A) ::= .                {A = 0;}
+having_opt(A) ::= HAVING expr(X).  {A = X;}
+
+%type limit_opt {struct LimitVal}
+limit_opt(A) ::= .                  {A.limit = -1; A.offset = 0;}
+limit_opt(A) ::= LIMIT INTEGER(X).  {A.limit = atoi(X.z); A.offset = 0;}
+limit_opt(A) ::= LIMIT INTEGER(X) limit_sep INTEGER(Y). 
+                                    {A.limit = atoi(X.z); A.offset = atoi(Y.z);}
+limit_sep ::= OFFSET.
+limit_sep ::= COMMA.
+
+/////////////////////////// The DELETE statement /////////////////////////////
+//
+cmd ::= DELETE FROM nm(X) where_opt(Y).
+    {sqliteDeleteFrom(pParse, &X, Y);}
+
+%type where_opt {Expr*}
+%destructor where_opt {sqliteExprDelete($$);}
+
+where_opt(A) ::= .                    {A = 0;}
+where_opt(A) ::= WHERE expr(X).       {A = X;}
+
+%type setlist {ExprList*}
+%destructor setlist {sqliteExprListDelete($$);}
+
+////////////////////////// The UPDATE command ////////////////////////////////
+//
+cmd ::= UPDATE orconf(R) nm(X) SET setlist(Y) where_opt(Z).
+    {sqliteUpdate(pParse,&X,Y,Z,R);}
+
+setlist(A) ::= setlist(Z) COMMA nm(X) EQ expr(Y).
+    {A = sqliteExprListAppend(Z,Y,&X);}
+setlist(A) ::= nm(X) EQ expr(Y).   {A = sqliteExprListAppend(0,Y,&X);}
+
+////////////////////////// The INSERT command /////////////////////////////////
+//
+cmd ::= insert_cmd(R) INTO nm(X) inscollist_opt(F) VALUES LP itemlist(Y) RP.
+               {sqliteInsert(pParse, &X, Y, 0, F, R);}
+cmd ::= insert_cmd(R) INTO nm(X) inscollist_opt(F) select(S).
+               {sqliteInsert(pParse, &X, 0, S, F, R);}
+
+%type insert_cmd {int}
+insert_cmd(A) ::= INSERT orconf(R).   {A = R;}
+insert_cmd(A) ::= REPLACE.            {A = OE_Replace;}
+
+
+%type itemlist {ExprList*}
+%destructor itemlist {sqliteExprListDelete($$);}
+
+itemlist(A) ::= itemlist(X) COMMA expr(Y).  {A = sqliteExprListAppend(X,Y,0);}
+itemlist(A) ::= expr(X).                    {A = sqliteExprListAppend(0,X,0);}
+
+%type inscollist_opt {IdList*}
+%destructor inscollist_opt {sqliteIdListDelete($$);}
+%type inscollist {IdList*}
+%destructor inscollist {sqliteIdListDelete($$);}
+
+inscollist_opt(A) ::= .                       {A = 0;}
+inscollist_opt(A) ::= LP inscollist(X) RP.    {A = X;}
+inscollist(A) ::= inscollist(X) COMMA nm(Y).  {A = sqliteIdListAppend(X,&Y);}
+inscollist(A) ::= nm(Y).                      {A = sqliteIdListAppend(0,&Y);}
+
+/////////////////////////// Expression Processing /////////////////////////////
+//
+%left OR.
+%left AND.
+%right NOT.
+%left EQ NE ISNULL NOTNULL IS LIKE GLOB BETWEEN IN.
+%left GT GE LT LE.
+%left BITAND BITOR LSHIFT RSHIFT.
+%left PLUS MINUS.
+%left STAR SLASH REM.
+%left CONCAT.
+%right UMINUS UPLUS BITNOT.
+%right ORACLE_OUTER_JOIN.
+
+%type expr {Expr*}
+%destructor expr {sqliteExprDelete($$);}
+
+expr(A) ::= LP(B) expr(X) RP(E). {A = X; sqliteExprSpan(A,&B,&E); }
+expr(A) ::= NULL(X).             {A = sqliteExpr(TK_NULL, 0, 0, &X);}
+expr(A) ::= ID(X).               {A = sqliteExpr(TK_ID, 0, 0, &X);}
+expr(A) ::= JOIN_KW(X).          {A = sqliteExpr(TK_ID, 0, 0, &X);}
+expr(A) ::= nm(X) DOT nm(Y). {
+  Expr *temp1 = sqliteExpr(TK_ID, 0, 0, &X);
+  Expr *temp2 = sqliteExpr(TK_ID, 0, 0, &Y);
+  A = sqliteExpr(TK_DOT, temp1, temp2, 0);
+}
+expr(A) ::= expr(B) ORACLE_OUTER_JOIN. 
+                             {A = B; ExprSetProperty(A,EP_Oracle8Join);}
+expr(A) ::= INTEGER(X).      {A = sqliteExpr(TK_INTEGER, 0, 0, &X);}
+expr(A) ::= FLOAT(X).        {A = sqliteExpr(TK_FLOAT, 0, 0, &X);}
+expr(A) ::= STRING(X).       {A = sqliteExpr(TK_STRING, 0, 0, &X);}
+expr(A) ::= ID(X) LP exprlist(Y) RP(E). {
+  A = sqliteExprFunction(Y, &X);
+  sqliteExprSpan(A,&X,&E);
+}
+expr(A) ::= ID(X) LP STAR RP(E). {
+  A = sqliteExprFunction(0, &X);
+  sqliteExprSpan(A,&X,&E);
+}
+expr(A) ::= expr(X) AND expr(Y).   {A = sqliteExpr(TK_AND, X, Y, 0);}
+expr(A) ::= expr(X) OR expr(Y).    {A = sqliteExpr(TK_OR, X, Y, 0);}
+expr(A) ::= expr(X) LT expr(Y).    {A = sqliteExpr(TK_LT, X, Y, 0);}
+expr(A) ::= expr(X) GT expr(Y).    {A = sqliteExpr(TK_GT, X, Y, 0);}
+expr(A) ::= expr(X) LE expr(Y).    {A = sqliteExpr(TK_LE, X, Y, 0);}
+expr(A) ::= expr(X) GE expr(Y).    {A = sqliteExpr(TK_GE, X, Y, 0);}
+expr(A) ::= expr(X) NE expr(Y).    {A = sqliteExpr(TK_NE, X, Y, 0);}
+expr(A) ::= expr(X) EQ expr(Y).    {A = sqliteExpr(TK_EQ, X, Y, 0);}
+expr(A) ::= expr(X) BITAND expr(Y). {A = sqliteExpr(TK_BITAND, X, Y, 0);}
+expr(A) ::= expr(X) BITOR expr(Y).  {A = sqliteExpr(TK_BITOR, X, Y, 0);}
+expr(A) ::= expr(X) LSHIFT expr(Y). {A = sqliteExpr(TK_LSHIFT, X, Y, 0);}
+expr(A) ::= expr(X) RSHIFT expr(Y). {A = sqliteExpr(TK_RSHIFT, X, Y, 0);}
+expr(A) ::= expr(X) likeop(OP) expr(Y).  [LIKE]  {
+  ExprList *pList = sqliteExprListAppend(0, Y, 0);
+  pList = sqliteExprListAppend(pList, X, 0);
+  A = sqliteExprFunction(pList, 0);
+  if( A ) A->op = OP;
+  sqliteExprSpan(A, &X->span, &Y->span);
+}
+expr(A) ::= expr(X) NOT likeop(OP) expr(Y). [LIKE] {
+  ExprList *pList = sqliteExprListAppend(0, Y, 0);
+  pList = sqliteExprListAppend(pList, X, 0);
+  A = sqliteExprFunction(pList, 0);
+  if( A ) A->op = OP;
+  A = sqliteExpr(TK_NOT, A, 0, 0);
+  sqliteExprSpan(A,&X->span,&Y->span);
+}
+%type likeop {int}
+likeop(A) ::= LIKE. {A = TK_LIKE;}
+likeop(A) ::= GLOB. {A = TK_GLOB;}
+expr(A) ::= expr(X) PLUS expr(Y).  {A = sqliteExpr(TK_PLUS, X, Y, 0);}
+expr(A) ::= expr(X) MINUS expr(Y). {A = sqliteExpr(TK_MINUS, X, Y, 0);}
+expr(A) ::= expr(X) STAR expr(Y).  {A = sqliteExpr(TK_STAR, X, Y, 0);}
+expr(A) ::= expr(X) SLASH expr(Y). {A = sqliteExpr(TK_SLASH, X, Y, 0);}
+expr(A) ::= expr(X) REM expr(Y).   {A = sqliteExpr(TK_REM, X, Y, 0);}
+expr(A) ::= expr(X) CONCAT expr(Y). {A = sqliteExpr(TK_CONCAT, X, Y, 0);}
+expr(A) ::= expr(X) ISNULL(E). {
+  A = sqliteExpr(TK_ISNULL, X, 0, 0);
+  sqliteExprSpan(A,&X->span,&E);
+}
+expr(A) ::= expr(X) IS NULL(E). {
+  A = sqliteExpr(TK_ISNULL, X, 0, 0);
+  sqliteExprSpan(A,&X->span,&E);
+}
+expr(A) ::= expr(X) NOTNULL(E). {
+  A = sqliteExpr(TK_NOTNULL, X, 0, 0);
+  sqliteExprSpan(A,&X->span,&E);
+}
+expr(A) ::= expr(X) NOT NULL(E). {
+  A = sqliteExpr(TK_NOTNULL, X, 0, 0);
+  sqliteExprSpan(A,&X->span,&E);
+}
+expr(A) ::= expr(X) IS NOT NULL(E). {
+  A = sqliteExpr(TK_NOTNULL, X, 0, 0);
+  sqliteExprSpan(A,&X->span,&E);
+}
+expr(A) ::= NOT(B) expr(X). {
+  A = sqliteExpr(TK_NOT, X, 0, 0);
+  sqliteExprSpan(A,&B,&X->span);
+}
+expr(A) ::= BITNOT(B) expr(X). {
+  A = sqliteExpr(TK_BITNOT, X, 0, 0);
+  sqliteExprSpan(A,&B,&X->span);
+}
+expr(A) ::= MINUS(B) expr(X). [UMINUS] {
+  A = sqliteExpr(TK_UMINUS, X, 0, 0);
+  sqliteExprSpan(A,&B,&X->span);
+}
+expr(A) ::= PLUS(B) expr(X). [UPLUS] {
+  A = sqliteExpr(TK_UPLUS, X, 0, 0);
+  sqliteExprSpan(A,&B,&X->span);
+}
+expr(A) ::= LP(B) select(X) RP(E). {
+  A = sqliteExpr(TK_SELECT, 0, 0, 0);
+  if( A ) A->pSelect = X;
+  sqliteExprSpan(A,&B,&E);
+}
+expr(A) ::= expr(W) BETWEEN expr(X) AND expr(Y). {
+  ExprList *pList = sqliteExprListAppend(0, X, 0);
+  pList = sqliteExprListAppend(pList, Y, 0);
+  A = sqliteExpr(TK_BETWEEN, W, 0, 0);
+  if( A ) A->pList = pList;
+  sqliteExprSpan(A,&W->span,&Y->span);
+}
+expr(A) ::= expr(W) NOT BETWEEN expr(X) AND expr(Y). {
+  ExprList *pList = sqliteExprListAppend(0, X, 0);
+  pList = sqliteExprListAppend(pList, Y, 0);
+  A = sqliteExpr(TK_BETWEEN, W, 0, 0);
+  if( A ) A->pList = pList;
+  A = sqliteExpr(TK_NOT, A, 0, 0);
+  sqliteExprSpan(A,&W->span,&Y->span);
+}
+expr(A) ::= expr(X) IN LP exprlist(Y) RP(E).  {
+  A = sqliteExpr(TK_IN, X, 0, 0);
+  if( A ) A->pList = Y;
+  sqliteExprSpan(A,&X->span,&E);
+}
+expr(A) ::= expr(X) IN LP select(Y) RP(E).  {
+  A = sqliteExpr(TK_IN, X, 0, 0);
+  if( A ) A->pSelect = Y;
+  sqliteExprSpan(A,&X->span,&E);
+}
+expr(A) ::= expr(X) NOT IN LP exprlist(Y) RP(E).  {
+  A = sqliteExpr(TK_IN, X, 0, 0);
+  if( A ) A->pList = Y;
+  A = sqliteExpr(TK_NOT, A, 0, 0);
+  sqliteExprSpan(A,&X->span,&E);
+}
+expr(A) ::= expr(X) NOT IN LP select(Y) RP(E).  {
+  A = sqliteExpr(TK_IN, X, 0, 0);
+  if( A ) A->pSelect = Y;
+  A = sqliteExpr(TK_NOT, A, 0, 0);
+  sqliteExprSpan(A,&X->span,&E);
+}
+
+/* CASE expressions */
+expr(A) ::= CASE(C) case_operand(X) case_exprlist(Y) case_else(Z) END(E). {
+  A = sqliteExpr(TK_CASE, X, Z, 0);
+  if( A ) A->pList = Y;
+  sqliteExprSpan(A, &C, &E);
+}
+%type case_exprlist {ExprList*}
+%destructor case_exprlist {sqliteExprListDelete($$);}
+case_exprlist(A) ::= case_exprlist(X) WHEN expr(Y) THEN expr(Z). {
+  A = sqliteExprListAppend(X, Y, 0);
+  A = sqliteExprListAppend(A, Z, 0);
+}
+case_exprlist(A) ::= WHEN expr(Y) THEN expr(Z). {
+  A = sqliteExprListAppend(0, Y, 0);
+  A = sqliteExprListAppend(A, Z, 0);
+}
+%type case_else {Expr*}
+case_else(A) ::=  ELSE expr(X).         {A = X;}
+case_else(A) ::=  .                     {A = 0;} 
+%type case_operand {Expr*}
+case_operand(A) ::= expr(X).            {A = X;} 
+case_operand(A) ::= .                   {A = 0;} 
+
+%type exprlist {ExprList*}
+%destructor exprlist {sqliteExprListDelete($$);}
+%type expritem {Expr*}
+%destructor expritem {sqliteExprDelete($$);}
+
+exprlist(A) ::= exprlist(X) COMMA expritem(Y). 
+   {A = sqliteExprListAppend(X,Y,0);}
+exprlist(A) ::= expritem(X).            {A = sqliteExprListAppend(0,X,0);}
+expritem(A) ::= expr(X).                {A = X;}
+expritem(A) ::= .                       {A = 0;}
+
+///////////////////////////// The CREATE INDEX command ///////////////////////
+//
+cmd ::= CREATE(S) uniqueflag(U) INDEX nm(X)
+        ON nm(Y) LP idxlist(Z) RP(E) onconf(R). {
+  if( U!=OE_None ) U = R;
+  if( U==OE_Default) U = OE_Abort;
+  sqliteCreateIndex(pParse, &X, &Y, Z, U, &S, &E);
+}
+
+%type uniqueflag {int}
+uniqueflag(A) ::= UNIQUE.  { A = OE_Abort; }
+uniqueflag(A) ::= .        { A = OE_None; }
+
+%type idxlist {IdList*}
+%destructor idxlist {sqliteIdListDelete($$);}
+%type idxlist_opt {IdList*}
+%destructor idxlist_opt {sqliteIdListDelete($$);}
+%type idxitem {Token}
+
+idxlist_opt(A) ::= .                         {A = 0;}
+idxlist_opt(A) ::= LP idxlist(X) RP.         {A = X;}
+idxlist(A) ::= idxlist(X) COMMA idxitem(Y).  {A = sqliteIdListAppend(X,&Y);}
+idxlist(A) ::= idxitem(Y).                   {A = sqliteIdListAppend(0,&Y);}
+idxitem(A) ::= nm(X).                        {A = X;}
+
+///////////////////////////// The DROP INDEX command /////////////////////////
+//
+
+cmd ::= DROP INDEX nm(X).      {sqliteDropIndex(pParse, &X);}
+
+
+///////////////////////////// The COPY command ///////////////////////////////
+//
+cmd ::= COPY orconf(R) nm(X) FROM nm(Y) USING DELIMITERS STRING(Z).
+    {sqliteCopy(pParse,&X,&Y,&Z,R);}
+cmd ::= COPY orconf(R) nm(X) FROM nm(Y).
+    {sqliteCopy(pParse,&X,&Y,0,R);}
+
+///////////////////////////// The VACUUM command /////////////////////////////
+//
+cmd ::= VACUUM.                {sqliteVacuum(pParse,0);}
+cmd ::= VACUUM nm(X).         {sqliteVacuum(pParse,&X);}
+
+///////////////////////////// The PRAGMA command /////////////////////////////
+//
+cmd ::= PRAGMA ids(X) EQ nm(Y).         {sqlitePragma(pParse,&X,&Y,0);}
+cmd ::= PRAGMA ids(X) EQ ON(Y).          {sqlitePragma(pParse,&X,&Y,0);}
+cmd ::= PRAGMA ids(X) EQ plus_num(Y).    {sqlitePragma(pParse,&X,&Y,0);}
+cmd ::= PRAGMA ids(X) EQ minus_num(Y).   {sqlitePragma(pParse,&X,&Y,1);}
+cmd ::= PRAGMA ids(X) LP nm(Y) RP.      {sqlitePragma(pParse,&X,&Y,0);}
+cmd ::= PRAGMA ids(X).                   {sqlitePragma(pParse,&X,&X,0);}
+plus_num(A) ::= plus_opt number(X).   {A = X;}
+minus_num(A) ::= MINUS number(X).     {A = X;}
+number(A) ::= INTEGER(X).  {A = X;}
+number(A) ::= FLOAT(X).    {A = X;}
+plus_opt ::= PLUS.
+plus_opt ::= .
+
+//////////////////////////// The CREATE TRIGGER command /////////////////////
+cmd ::= CREATE(A) TRIGGER nm(B) trigger_time(C) trigger_event(D) ON nm(E) 
+                  foreach_clause(F) when_clause(G)
+                  BEGIN trigger_cmd_list(S) END(Z). {
+  Token all;
+  all.z = A.z;
+  all.n = (Z.z - A.z) + Z.n;
+  sqliteCreateTrigger(pParse, &B, C, D.a, D.b, &E, F, G, S, &all);
+}
+
+%type trigger_time  {int}
+trigger_time(A) ::= BEFORE.      { A = TK_BEFORE; }
+trigger_time(A) ::= AFTER.       { A = TK_AFTER;  }
+trigger_time(A) ::= INSTEAD OF.  { A = TK_INSTEAD;}
+trigger_time(A) ::= .            { A = TK_BEFORE; }
+
+%type trigger_event {struct TrigEvent}
+%destructor trigger_event {sqliteIdListDelete($$.b);}
+trigger_event(A) ::= DELETE. { A.a = TK_DELETE; A.b = 0; }
+trigger_event(A) ::= INSERT. { A.a = TK_INSERT; A.b = 0; }
+trigger_event(A) ::= UPDATE. { A.a = TK_UPDATE; A.b = 0;}
+trigger_event(A) ::= UPDATE OF inscollist(X). {A.a = TK_UPDATE; A.b = X; }
+
+%type foreach_clause {int}
+foreach_clause(A) ::= .                   { A = TK_ROW; }
+foreach_clause(A) ::= FOR EACH ROW.       { A = TK_ROW; }
+foreach_clause(A) ::= FOR EACH STATEMENT. { A = TK_STATEMENT; }
+
+%type when_clause {Expr *}
+when_clause(A) ::= .             { A = 0; }
+when_clause(A) ::= WHEN expr(X). { A = X; }
+
+%type trigger_cmd_list {TriggerStep *}
+trigger_cmd_list(A) ::= trigger_cmd(X) SEMI trigger_cmd_list(Y). {
+  X->pNext = Y ; A = X; }
+trigger_cmd_list(A) ::= . { A = 0; }
+
+%type trigger_cmd {TriggerStep *}
+// UPDATE 
+trigger_cmd(A) ::= UPDATE orconf(R) nm(X) SET setlist(Y) where_opt(Z).  
+               { A = sqliteTriggerUpdateStep(&X, Y, Z, R); }
+
+// INSERT
+trigger_cmd(A) ::= INSERT orconf(R) INTO nm(X) inscollist_opt(F) 
+  VALUES LP itemlist(Y) RP.  
+{A = sqliteTriggerInsertStep(&X, F, Y, 0, R);}
+
+trigger_cmd(A) ::= INSERT orconf(R) INTO nm(X) inscollist_opt(F) select(S).
+               {A = sqliteTriggerInsertStep(&X, F, 0, S, R);}
+
+// DELETE
+trigger_cmd(A) ::= DELETE FROM nm(X) where_opt(Y).
+               {A = sqliteTriggerDeleteStep(&X, Y);}
+
+// SELECT
+trigger_cmd(A) ::= select(X).  {A = sqliteTriggerSelectStep(X); }
+
+// The special RAISE expression that may occur in trigger programs
+expr(A) ::= RAISE(X) LP IGNORE RP(Y).  {
+  A = sqliteExpr(TK_RAISE, 0, 0, 0); 
+  A->iColumn = OE_Ignore;
+  sqliteExprSpan(A, &X, &Y);
+}
+expr(A) ::= RAISE(X) LP ROLLBACK COMMA nm(Z) RP(Y).  {
+  A = sqliteExpr(TK_RAISE, 0, 0, &Z); 
+  A->iColumn = OE_Rollback;
+  sqliteExprSpan(A, &X, &Y);
+}
+expr(A) ::= RAISE(X) LP ABORT COMMA nm(Z) RP(Y).  {
+  A = sqliteExpr(TK_RAISE, 0, 0, &Z); 
+  A->iColumn = OE_Abort;
+  sqliteExprSpan(A, &X, &Y);
+}
+expr(A) ::= RAISE(X) LP FAIL COMMA nm(Z) RP(Y).  {
+  A = sqliteExpr(TK_RAISE, 0, 0, &Z); 
+  A->iColumn = OE_Fail;
+  sqliteExprSpan(A, &X, &Y);
+}
+
+////////////////////////  DROP TRIGGER statement //////////////////////////////
+cmd ::= DROP TRIGGER nm(X). {
+    sqliteDropTrigger(pParse,&X,0);
+}
diff --git a/ext/sqlite/libsqlite/src/printf.c b/ext/sqlite/libsqlite/src/printf.c
new file mode 100644 (file)
index 0000000..387ea1c
--- /dev/null
@@ -0,0 +1,824 @@
+/*
+** The "printf" code that follows dates from the 1980's.  It is in
+** the public domain.  The original comments are included here for
+** completeness.  They are slightly out-of-date.
+**
+** The following modules is an enhanced replacement for the "printf" subroutines
+** found in the standard C library.  The following enhancements are
+** supported:
+**
+**      +  Additional functions.  The standard set of "printf" functions
+**         includes printf, fprintf, sprintf, vprintf, vfprintf, and
+**         vsprintf.  This module adds the following:
+**
+**           *  snprintf -- Works like sprintf, but has an extra argument
+**                          which is the size of the buffer written to.
+**
+**           *  mprintf --  Similar to sprintf.  Writes output to memory
+**                          obtained from malloc.
+**
+**           *  xprintf --  Calls a function to dispose of output.
+**
+**           *  nprintf --  No output, but returns the number of characters
+**                          that would have been output by printf.
+**
+**           *  A v- version (ex: vsnprintf) of every function is also
+**              supplied.
+**
+**      +  A few extensions to the formatting notation are supported:
+**
+**           *  The "=" flag (similar to "-") causes the output to be
+**              be centered in the appropriately sized field.
+**
+**           *  The %b field outputs an integer in binary notation.
+**
+**           *  The %c field now accepts a precision.  The character output
+**              is repeated by the number of times the precision specifies.
+**
+**           *  The %' field works like %c, but takes as its character the
+**              next character of the format string, instead of the next
+**              argument.  For example,  printf("%.78'-")  prints 78 minus
+**              signs, the same as  printf("%.78c",'-').
+**
+**      +  When compiled using GCC on a SPARC, this version of printf is
+**         faster than the library printf for SUN OS 4.1.
+**
+**      +  All functions are fully reentrant.
+**
+*/
+#include "sqliteInt.h"
+
+/*
+** Undefine COMPATIBILITY to make some slight changes in the way things
+** work.  I think the changes are an improvement, but they are not
+** backwards compatible.
+*/
+/* #define COMPATIBILITY       / * Compatible with SUN OS 4.1 */
+
+/*
+** Conversion types fall into various categories as defined by the
+** following enumeration.
+*/
+enum et_type {    /* The type of the format field */
+   etRADIX,            /* Integer types.  %d, %x, %o, and so forth */
+   etFLOAT,            /* Floating point.  %f */
+   etEXP,              /* Exponentional notation. %e and %E */
+   etGENERIC,          /* Floating or exponential, depending on exponent. %g */
+   etSIZE,             /* Return number of characters processed so far. %n */
+   etSTRING,           /* Strings. %s */
+   etPERCENT,          /* Percent symbol. %% */
+   etCHARX,            /* Characters. %c */
+   etERROR,            /* Used to indicate no such conversion type */
+/* The rest are extensions, not normally found in printf() */
+   etCHARLIT,          /* Literal characters.  %' */
+   etSQLESCAPE,        /* Strings with '\'' doubled.  %q */
+   etSQLESCAPE2,       /* Strings with '\'' doubled and enclosed in '',
+                          NULL pointers replaced by SQL NULL.  %Q */
+   etORDINAL           /* 1st, 2nd, 3rd and so forth */
+};
+
+/*
+** Each builtin conversion character (ex: the 'd' in "%d") is described
+** by an instance of the following structure
+*/
+typedef struct et_info {   /* Information about each format field */
+  int  fmttype;              /* The format field code letter */
+  int  base;                 /* The base for radix conversion */
+  char *charset;             /* The character set for conversion */
+  int  flag_signed;          /* Is the quantity signed? */
+  char *prefix;              /* Prefix on non-zero values in alt format */
+  enum et_type type;          /* Conversion paradigm */
+} et_info;
+
+/*
+** The following table is searched linearly, so it is good to put the
+** most frequently used conversion types first.
+*/
+static et_info fmtinfo[] = {
+  { 'd',  10,  "0123456789",       1,    0, etRADIX,      },
+  { 's',   0,  0,                  0,    0, etSTRING,     }, 
+  { 'q',   0,  0,                  0,    0, etSQLESCAPE,  },
+  { 'Q',   0,  0,                  0,    0, etSQLESCAPE2, },
+  { 'c',   0,  0,                  0,    0, etCHARX,      },
+  { 'o',   8,  "01234567",         0,  "0", etRADIX,      },
+  { 'u',  10,  "0123456789",       0,    0, etRADIX,      },
+  { 'x',  16,  "0123456789abcdef", 0, "x0", etRADIX,      },
+  { 'X',  16,  "0123456789ABCDEF", 0, "X0", etRADIX,      },
+  { 'r',  10,  "0123456789",       0,    0, etORDINAL,    },
+  { 'f',   0,  0,                  1,    0, etFLOAT,      },
+  { 'e',   0,  "e",                1,    0, etEXP,        },
+  { 'E',   0,  "E",                1,    0, etEXP,        },
+  { 'g',   0,  "e",                1,    0, etGENERIC,    },
+  { 'G',   0,  "E",                1,    0, etGENERIC,    },
+  { 'i',  10,  "0123456789",       1,    0, etRADIX,      },
+  { 'n',   0,  0,                  0,    0, etSIZE,       },
+  { '%',   0,  0,                  0,    0, etPERCENT,    },
+  { 'b',   2,  "01",               0, "b0", etRADIX,      }, /* Binary */
+  { 'p',  10,  "0123456789",       0,    0, etRADIX,      }, /* Pointers */
+  { '\'',  0,  0,                  0,    0, etCHARLIT,    }, /* Literal char */
+};
+#define etNINFO  (sizeof(fmtinfo)/sizeof(fmtinfo[0]))
+
+/*
+** If NOFLOATINGPOINT is defined, then none of the floating point
+** conversions will work.
+*/
+#ifndef etNOFLOATINGPOINT
+/*
+** "*val" is a double such that 0.1 <= *val < 10.0
+** Return the ascii code for the leading digit of *val, then
+** multiply "*val" by 10.0 to renormalize.
+**
+** Example:
+**     input:     *val = 3.14159
+**     output:    *val = 1.4159    function return = '3'
+**
+** The counter *cnt is incremented each time.  After counter exceeds
+** 16 (the number of significant digits in a 64-bit float) '0' is
+** always returned.
+*/
+static int et_getdigit(double *val, int *cnt){
+  int digit;
+  double d;
+  if( (*cnt)++ >= 16 ) return '0';
+  digit = (int)*val;
+  d = digit;
+  digit += '0';
+  *val = (*val - d)*10.0;
+  return digit;
+}
+#endif
+
+#define etBUFSIZE 1000  /* Size of the output buffer */
+
+/*
+** The root program.  All variations call this core.
+**
+** INPUTS:
+**   func   This is a pointer to a function taking three arguments
+**            1. A pointer to anything.  Same as the "arg" parameter.
+**            2. A pointer to the list of characters to be output
+**               (Note, this list is NOT null terminated.)
+**            3. An integer number of characters to be output.
+**               (Note: This number might be zero.)
+**
+**   arg    This is the pointer to anything which will be passed as the
+**          first argument to "func".  Use it for whatever you like.
+**
+**   fmt    This is the format string, as in the usual print.
+**
+**   ap     This is a pointer to a list of arguments.  Same as in
+**          vfprint.
+**
+** OUTPUTS:
+**          The return value is the total number of characters sent to
+**          the function "func".  Returns -1 on a error.
+**
+** Note that the order in which automatic variables are declared below
+** seems to make a big difference in determining how fast this beast
+** will run.
+*/
+static int vxprintf(
+  void (*func)(void*,char*,int),
+  void *arg,
+  const char *format,
+  va_list ap
+){
+  register const char *fmt; /* The format string. */
+  register int c;           /* Next character in the format string */
+  register char *bufpt;     /* Pointer to the conversion buffer */
+  register int  precision;  /* Precision of the current field */
+  register int  length;     /* Length of the field */
+  register int  idx;        /* A general purpose loop counter */
+  int count;                /* Total number of characters output */
+  int width;                /* Width of the current field */
+  int flag_leftjustify;     /* True if "-" flag is present */
+  int flag_plussign;        /* True if "+" flag is present */
+  int flag_blanksign;       /* True if " " flag is present */
+  int flag_alternateform;   /* True if "#" flag is present */
+  int flag_zeropad;         /* True if field width constant starts with zero */
+  int flag_long;            /* True if "l" flag is present */
+  int flag_center;          /* True if "=" flag is present */
+  unsigned long longvalue;  /* Value for integer types */
+  double realvalue;         /* Value for real types */
+  et_info *infop;           /* Pointer to the appropriate info structure */
+  char buf[etBUFSIZE];      /* Conversion buffer */
+  char prefix;              /* Prefix character.  "+" or "-" or " " or '\0'. */
+  int  errorflag = 0;       /* True if an error is encountered */
+  enum et_type xtype;       /* Conversion paradigm */
+  char *zExtra;             /* Extra memory used for etTCLESCAPE conversions */
+  static char spaces[] = "                                                  "
+     "                                                                      ";
+#define etSPACESIZE (sizeof(spaces)-1)
+#ifndef etNOFLOATINGPOINT
+  int  exp;                 /* exponent of real numbers */
+  double rounder;           /* Used for rounding floating point values */
+  int flag_dp;              /* True if decimal point should be shown */
+  int flag_rtz;             /* True if trailing zeros should be removed */
+  int flag_exp;             /* True to force display of the exponent */
+  int nsd;                  /* Number of significant digits returned */
+#endif
+
+  fmt = format;                     /* Put in a register for speed */
+  count = length = 0;
+  bufpt = 0;
+  for(; (c=(*fmt))!=0; ++fmt){
+    if( c!='%' ){
+      register int amt;
+      bufpt = (char *)fmt;
+      amt = 1;
+      while( (c=(*++fmt))!='%' && c!=0 ) amt++;
+      (*func)(arg,bufpt,amt);
+      count += amt;
+      if( c==0 ) break;
+    }
+    if( (c=(*++fmt))==0 ){
+      errorflag = 1;
+      (*func)(arg,"%",1);
+      count++;
+      break;
+    }
+    /* Find out what flags are present */
+    flag_leftjustify = flag_plussign = flag_blanksign = 
+     flag_alternateform = flag_zeropad = flag_center = 0;
+    do{
+      switch( c ){
+        case '-':   flag_leftjustify = 1;     c = 0;   break;
+        case '+':   flag_plussign = 1;        c = 0;   break;
+        case ' ':   flag_blanksign = 1;       c = 0;   break;
+        case '#':   flag_alternateform = 1;   c = 0;   break;
+        case '0':   flag_zeropad = 1;         c = 0;   break;
+        case '=':   flag_center = 1;          c = 0;   break;
+        default:                                       break;
+      }
+    }while( c==0 && (c=(*++fmt))!=0 );
+    if( flag_center ) flag_leftjustify = 0;
+    /* Get the field width */
+    width = 0;
+    if( c=='*' ){
+      width = va_arg(ap,int);
+      if( width<0 ){
+        flag_leftjustify = 1;
+        width = -width;
+      }
+      c = *++fmt;
+    }else{
+      while( c>='0' && c<='9' ){
+        width = width*10 + c - '0';
+        c = *++fmt;
+      }
+    }
+    if( width > etBUFSIZE-10 ){
+      width = etBUFSIZE-10;
+    }
+    /* Get the precision */
+    if( c=='.' ){
+      precision = 0;
+      c = *++fmt;
+      if( c=='*' ){
+        precision = va_arg(ap,int);
+#ifndef etCOMPATIBILITY
+        /* This is sensible, but SUN OS 4.1 doesn't do it. */
+        if( precision<0 ) precision = -precision;
+#endif
+        c = *++fmt;
+      }else{
+        while( c>='0' && c<='9' ){
+          precision = precision*10 + c - '0';
+          c = *++fmt;
+        }
+      }
+      /* Limit the precision to prevent overflowing buf[] during conversion */
+      if( precision>etBUFSIZE-40 ) precision = etBUFSIZE-40;
+    }else{
+      precision = -1;
+    }
+    /* Get the conversion type modifier */
+    if( c=='l' ){
+      flag_long = 1;
+      c = *++fmt;
+    }else{
+      flag_long = 0;
+    }
+    /* Fetch the info entry for the field */
+    infop = 0;
+    for(idx=0; idx<etNINFO; idx++){
+      if( c==fmtinfo[idx].fmttype ){
+        infop = &fmtinfo[idx];
+        break;
+      }
+    }
+    /* No info entry found.  It must be an error. */
+    if( infop==0 ){
+      xtype = etERROR;
+    }else{
+      xtype = infop->type;
+    }
+    zExtra = 0;
+
+    /*
+    ** At this point, variables are initialized as follows:
+    **
+    **   flag_alternateform          TRUE if a '#' is present.
+    **   flag_plussign               TRUE if a '+' is present.
+    **   flag_leftjustify            TRUE if a '-' is present or if the
+    **                               field width was negative.
+    **   flag_zeropad                TRUE if the width began with 0.
+    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
+    **                               the conversion character.
+    **   flag_blanksign              TRUE if a ' ' is present.
+    **   width                       The specified field width.  This is
+    **                               always non-negative.  Zero is the default.
+    **   precision                   The specified precision.  The default
+    **                               is -1.
+    **   xtype                       The class of the conversion.
+    **   infop                       Pointer to the appropriate info struct.
+    */
+    switch( xtype ){
+      case etORDINAL:
+      case etRADIX:
+        if( flag_long )  longvalue = va_arg(ap,long);
+        else             longvalue = va_arg(ap,int);
+#ifdef etCOMPATIBILITY
+        /* For the format %#x, the value zero is printed "0" not "0x0".
+        ** I think this is stupid. */
+        if( longvalue==0 ) flag_alternateform = 0;
+#else
+        /* More sensible: turn off the prefix for octal (to prevent "00"),
+        ** but leave the prefix for hex. */
+        if( longvalue==0 && infop->base==8 ) flag_alternateform = 0;
+#endif
+        if( infop->flag_signed ){
+          if( *(long*)&longvalue<0 ){
+            longvalue = -*(long*)&longvalue;
+            prefix = '-';
+          }else if( flag_plussign )  prefix = '+';
+          else if( flag_blanksign )  prefix = ' ';
+          else                       prefix = 0;
+        }else                        prefix = 0;
+        if( flag_zeropad && precision<width-(prefix!=0) ){
+          precision = width-(prefix!=0);
+        }
+        bufpt = &buf[etBUFSIZE];
+        if( xtype==etORDINAL ){
+          long a,b;
+          a = longvalue%10;
+          b = longvalue%100;
+          bufpt -= 2;
+          if( a==0 || a>3 || (b>10 && b<14) ){
+            bufpt[0] = 't';
+            bufpt[1] = 'h';
+          }else if( a==1 ){
+            bufpt[0] = 's';
+            bufpt[1] = 't';
+          }else if( a==2 ){
+            bufpt[0] = 'n';
+            bufpt[1] = 'd';
+          }else if( a==3 ){
+            bufpt[0] = 'r';
+            bufpt[1] = 'd';
+          }
+        }
+        {
+          register char *cset;      /* Use registers for speed */
+          register int base;
+          cset = infop->charset;
+          base = infop->base;
+          do{                                           /* Convert to ascii */
+            *(--bufpt) = cset[longvalue%base];
+            longvalue = longvalue/base;
+          }while( longvalue>0 );
+        }
+        length = (long)&buf[etBUFSIZE]-(long)bufpt;
+        for(idx=precision-length; idx>0; idx--){
+          *(--bufpt) = '0';                             /* Zero pad */
+        }
+        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
+        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
+          char *pre, x;
+          pre = infop->prefix;
+          if( *bufpt!=pre[0] ){
+            for(pre=infop->prefix; (x=(*pre))!=0; pre++) *(--bufpt) = x;
+          }
+        }
+        length = (long)&buf[etBUFSIZE]-(long)bufpt;
+        break;
+      case etFLOAT:
+      case etEXP:
+      case etGENERIC:
+        realvalue = va_arg(ap,double);
+#ifndef etNOFLOATINGPOINT
+        if( precision<0 ) precision = 6;         /* Set default precision */
+        if( precision>etBUFSIZE-10 ) precision = etBUFSIZE-10;
+        if( realvalue<0.0 ){
+          realvalue = -realvalue;
+          prefix = '-';
+        }else{
+          if( flag_plussign )          prefix = '+';
+          else if( flag_blanksign )    prefix = ' ';
+          else                         prefix = 0;
+        }
+        if( infop->type==etGENERIC && precision>0 ) precision--;
+        rounder = 0.0;
+#ifdef COMPATIBILITY
+        /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
+        for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
+#else
+        /* It makes more sense to use 0.5 */
+        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1);
+#endif
+        if( infop->type==etFLOAT ) realvalue += rounder;
+        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
+        exp = 0;
+        if( realvalue>0.0 ){
+          int k = 0;
+          while( realvalue>=1e8 && k++<100 ){ realvalue *= 1e-8; exp+=8; }
+          while( realvalue>=10.0 && k++<100 ){ realvalue *= 0.1; exp++; }
+          while( realvalue<1e-8 && k++<100 ){ realvalue *= 1e8; exp-=8; }
+          while( realvalue<1.0 && k++<100 ){ realvalue *= 10.0; exp--; }
+          if( k>=100 ){
+            bufpt = "NaN";
+            length = 3;
+            break;
+          }
+        }
+        bufpt = buf;
+        /*
+        ** If the field type is etGENERIC, then convert to either etEXP
+        ** or etFLOAT, as appropriate.
+        */
+        flag_exp = xtype==etEXP;
+        if( xtype!=etFLOAT ){
+          realvalue += rounder;
+          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
+        }
+        if( xtype==etGENERIC ){
+          flag_rtz = !flag_alternateform;
+          if( exp<-4 || exp>precision ){
+            xtype = etEXP;
+          }else{
+            precision = precision - exp;
+            xtype = etFLOAT;
+          }
+        }else{
+          flag_rtz = 0;
+        }
+        /*
+        ** The "exp+precision" test causes output to be of type etEXP if
+        ** the precision is too large to fit in buf[].
+        */
+        nsd = 0;
+        if( xtype==etFLOAT && exp+precision<etBUFSIZE-30 ){
+          flag_dp = (precision>0 || flag_alternateform);
+          if( prefix ) *(bufpt++) = prefix;         /* Sign */
+          if( exp<0 )  *(bufpt++) = '0';            /* Digits before "." */
+          else for(; exp>=0; exp--) *(bufpt++) = et_getdigit(&realvalue,&nsd);
+          if( flag_dp ) *(bufpt++) = '.';           /* The decimal point */
+          for(exp++; exp<0 && precision>0; precision--, exp++){
+            *(bufpt++) = '0';
+          }
+          while( (precision--)>0 ) *(bufpt++) = et_getdigit(&realvalue,&nsd);
+          *(bufpt--) = 0;                           /* Null terminate */
+          if( flag_rtz && flag_dp ){     /* Remove trailing zeros and "." */
+            while( bufpt>=buf && *bufpt=='0' ) *(bufpt--) = 0;
+            if( bufpt>=buf && *bufpt=='.' ) *(bufpt--) = 0;
+          }
+          bufpt++;                            /* point to next free slot */
+        }else{    /* etEXP or etGENERIC */
+          flag_dp = (precision>0 || flag_alternateform);
+          if( prefix ) *(bufpt++) = prefix;   /* Sign */
+          *(bufpt++) = et_getdigit(&realvalue,&nsd);  /* First digit */
+          if( flag_dp ) *(bufpt++) = '.';     /* Decimal point */
+          while( (precision--)>0 ) *(bufpt++) = et_getdigit(&realvalue,&nsd);
+          bufpt--;                            /* point to last digit */
+          if( flag_rtz && flag_dp ){          /* Remove tail zeros */
+            while( bufpt>=buf && *bufpt=='0' ) *(bufpt--) = 0;
+            if( bufpt>=buf && *bufpt=='.' ) *(bufpt--) = 0;
+          }
+          bufpt++;                            /* point to next free slot */
+          if( exp || flag_exp ){
+            *(bufpt++) = infop->charset[0];
+            if( exp<0 ){ *(bufpt++) = '-'; exp = -exp; } /* sign of exp */
+            else       { *(bufpt++) = '+'; }
+            if( exp>=100 ){
+              *(bufpt++) = (exp/100)+'0';                /* 100's digit */
+              exp %= 100;
+            }
+            *(bufpt++) = exp/10+'0';                     /* 10's digit */
+            *(bufpt++) = exp%10+'0';                     /* 1's digit */
+          }
+        }
+        /* The converted number is in buf[] and zero terminated. Output it.
+        ** Note that the number is in the usual order, not reversed as with
+        ** integer conversions. */
+        length = (long)bufpt-(long)buf;
+        bufpt = buf;
+
+        /* Special case:  Add leading zeros if the flag_zeropad flag is
+        ** set and we are not left justified */
+        if( flag_zeropad && !flag_leftjustify && length < width){
+          int i;
+          int nPad = width - length;
+          for(i=width; i>=nPad; i--){
+            bufpt[i] = bufpt[i-nPad];
+          }
+          i = prefix!=0;
+          while( nPad-- ) bufpt[i++] = '0';
+          length = width;
+        }
+#endif
+        break;
+      case etSIZE:
+        *(va_arg(ap,int*)) = count;
+        length = width = 0;
+        break;
+      case etPERCENT:
+        buf[0] = '%';
+        bufpt = buf;
+        length = 1;
+        break;
+      case etCHARLIT:
+      case etCHARX:
+        c = buf[0] = (xtype==etCHARX ? va_arg(ap,int) : *++fmt);
+        if( precision>=0 ){
+          for(idx=1; idx<precision; idx++) buf[idx] = c;
+          length = precision;
+        }else{
+          length =1;
+        }
+        bufpt = buf;
+        break;
+      case etSTRING:
+        bufpt = va_arg(ap,char*);
+        if( bufpt==0 ) bufpt = "(null)";
+        length = strlen(bufpt);
+        if( precision>=0 && precision<length ) length = precision;
+        break;
+      case etSQLESCAPE:
+      case etSQLESCAPE2:
+        {
+          int i, j, n, c, isnull;
+          char *arg = va_arg(ap,char*);
+          isnull = arg==0;
+          if( isnull ) arg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
+          for(i=n=0; (c=arg[i])!=0; i++){
+            if( c=='\'' )  n++;
+          }
+          n += i + 1 + ((!isnull && xtype==etSQLESCAPE2) ? 2 : 0);
+          if( n>etBUFSIZE ){
+            bufpt = zExtra = sqliteMalloc( n );
+            if( bufpt==0 ) return -1;
+          }else{
+            bufpt = buf;
+          }
+          j = 0;
+          if( !isnull && xtype==etSQLESCAPE2 ) bufpt[j++] = '\'';
+          for(i=0; (c=arg[i])!=0; i++){
+            bufpt[j++] = c;
+            if( c=='\'' ) bufpt[j++] = c;
+          }
+          if( !isnull && xtype==etSQLESCAPE2 ) bufpt[j++] = '\'';
+          bufpt[j] = 0;
+          length = j;
+          if( precision>=0 && precision<length ) length = precision;
+        }
+        break;
+      case etERROR:
+        buf[0] = '%';
+        buf[1] = c;
+        errorflag = 0;
+        idx = 1+(c!=0);
+        (*func)(arg,"%",idx);
+        count += idx;
+        if( c==0 ) fmt--;
+        break;
+    }/* End switch over the format type */
+    /*
+    ** The text of the conversion is pointed to by "bufpt" and is
+    ** "length" characters long.  The field width is "width".  Do
+    ** the output.
+    */
+    if( !flag_leftjustify ){
+      register int nspace;
+      nspace = width-length;
+      if( nspace>0 ){
+        if( flag_center ){
+          nspace = nspace/2;
+          width -= nspace;
+          flag_leftjustify = 1;
+        }
+        count += nspace;
+        while( nspace>=etSPACESIZE ){
+          (*func)(arg,spaces,etSPACESIZE);
+          nspace -= etSPACESIZE;
+        }
+        if( nspace>0 ) (*func)(arg,spaces,nspace);
+      }
+    }
+    if( length>0 ){
+      (*func)(arg,bufpt,length);
+      count += length;
+    }
+    if( flag_leftjustify ){
+      register int nspace;
+      nspace = width-length;
+      if( nspace>0 ){
+        count += nspace;
+        while( nspace>=etSPACESIZE ){
+          (*func)(arg,spaces,etSPACESIZE);
+          nspace -= etSPACESIZE;
+        }
+        if( nspace>0 ) (*func)(arg,spaces,nspace);
+      }
+    }
+    if( zExtra ){
+      sqliteFree(zExtra);
+    }
+  }/* End for loop over the format string */
+  return errorflag ? -1 : count;
+} /* End of function */
+
+
+/* This structure is used to store state information about the
+** write to memory that is currently in progress.
+*/
+struct sgMprintf {
+  char *zBase;     /* A base allocation */
+  char *zText;     /* The string collected so far */
+  int  nChar;      /* Length of the string so far */
+  int  nAlloc;     /* Amount of space allocated in zText */
+};
+
+/* 
+** This function implements the callback from vxprintf. 
+**
+** This routine add nNewChar characters of text in zNewText to
+** the sgMprintf structure pointed to by "arg".
+*/
+static void mout(void *arg, char *zNewText, int nNewChar){
+  struct sgMprintf *pM = (struct sgMprintf*)arg;
+  if( pM->nChar + nNewChar + 1 > pM->nAlloc ){
+    pM->nAlloc = pM->nChar + nNewChar*2 + 1;
+    if( pM->zText==pM->zBase ){
+      pM->zText = sqliteMalloc(pM->nAlloc);
+      if( pM->zText && pM->nChar ) memcpy(pM->zText,pM->zBase,pM->nChar);
+    }else{
+      char *z = sqliteRealloc(pM->zText, pM->nAlloc);
+      if( z==0 ){
+        sqliteFree(pM->zText);
+        pM->nChar = 0;
+        pM->nAlloc = 0;
+      }
+      pM->zText = z;
+    }
+  }
+  if( pM->zText ){
+    memcpy(&pM->zText[pM->nChar], zNewText, nNewChar);
+    pM->nChar += nNewChar;
+    pM->zText[pM->nChar] = 0;
+  }
+}
+
+/*
+** sqlite_mprintf() works like printf(), but allocations memory to hold the
+** resulting string and returns a pointer to the allocated memory.  Use
+** sqliteFree() to release the memory allocated.
+*/
+char *sqliteMPrintf(const char *zFormat, ...){
+  va_list ap;
+  struct sgMprintf sMprintf;
+  char *zNew;
+  char zBuf[200];
+
+  sMprintf.nChar = 0;
+  sMprintf.nAlloc = sizeof(zBuf);
+  sMprintf.zText = zBuf;
+  sMprintf.zBase = zBuf;
+  va_start(ap,zFormat);
+  vxprintf(mout,&sMprintf,zFormat,ap);
+  va_end(ap);
+  sMprintf.zText[sMprintf.nChar] = 0;
+  return sqliteRealloc(sMprintf.zText, sMprintf.nChar+1);
+}
+
+/*
+** sqlite_mprintf() works like printf(), but allocations memory to hold the
+** resulting string and returns a pointer to the allocated memory.  Use
+** sqliteFree() to release the memory allocated.
+*/
+char *sqlite_mprintf(const char *zFormat, ...){
+  va_list ap;
+  struct sgMprintf sMprintf;
+  char *zNew;
+  char zBuf[200];
+
+  sMprintf.nChar = 0;
+  sMprintf.nAlloc = sizeof(zBuf);
+  sMprintf.zText = zBuf;
+  sMprintf.zBase = zBuf;
+  va_start(ap,zFormat);
+  vxprintf(mout,&sMprintf,zFormat,ap);
+  va_end(ap);
+  sMprintf.zText[sMprintf.nChar] = 0;
+  zNew = malloc( sMprintf.nChar+1 );
+  if( zNew ) strcpy(zNew,sMprintf.zText);
+  if( sMprintf.zText!=sMprintf.zBase ){
+    sqliteFree(sMprintf.zText);
+  }
+  return zNew;
+}
+
+/* This is the varargs version of sqlite_mprintf.  
+*/
+char *sqlite_vmprintf(const char *zFormat, va_list ap){
+  struct sgMprintf sMprintf;
+  char *zNew;
+  char zBuf[200];
+  sMprintf.nChar = 0;
+  sMprintf.zText = zBuf;
+  sMprintf.nAlloc = sizeof(zBuf);
+  sMprintf.zBase = zBuf;
+  vxprintf(mout,&sMprintf,zFormat,ap);
+  sMprintf.zText[sMprintf.nChar] = 0;
+  zNew = malloc( sMprintf.nChar+1 );
+  if( zNew ) strcpy(zNew,sMprintf.zText);
+  if( sMprintf.zText!=sMprintf.zBase ){
+    sqliteFree(sMprintf.zText);
+  }
+  return zNew;
+}
+
+/*
+** The following four routines implement the varargs versions of the
+** sqlite_exec() and sqlite_get_table() interfaces.  See the sqlite.h
+** header files for a more detailed description of how these interfaces
+** work.
+**
+** These routines are all just simple wrappers.
+*/
+int sqlite_exec_printf(
+  sqlite *db,                   /* An open database */
+  const char *sqlFormat,        /* printf-style format string for the SQL */
+  sqlite_callback xCallback,    /* Callback function */
+  void *pArg,                   /* 1st argument to callback function */
+  char **errmsg,                /* Error msg written here */
+  ...                           /* Arguments to the format string. */
+){
+  va_list ap;
+  int rc;
+
+  va_start(ap, errmsg);
+  rc = sqlite_exec_vprintf(db, sqlFormat, xCallback, pArg, errmsg, ap);
+  va_end(ap);
+  return rc;
+}
+int sqlite_exec_vprintf(
+  sqlite *db,                   /* An open database */
+  const char *sqlFormat,        /* printf-style format string for the SQL */
+  sqlite_callback xCallback,    /* Callback function */
+  void *pArg,                   /* 1st argument to callback function */
+  char **errmsg,                /* Error msg written here */
+  va_list ap                    /* Arguments to the format string. */
+){
+  char *zSql;
+  int rc;
+
+  zSql = sqlite_vmprintf(sqlFormat, ap);
+  rc = sqlite_exec(db, zSql, xCallback, pArg, errmsg);
+  free(zSql);
+  return rc;
+}
+int sqlite_get_table_printf(
+  sqlite *db,            /* An open database */
+  const char *sqlFormat, /* printf-style format string for the SQL */
+  char ***resultp,       /* Result written to a char *[]  that this points to */
+  int *nrow,             /* Number of result rows written here */
+  int *ncol,             /* Number of result columns written here */
+  char **errmsg,         /* Error msg written here */
+  ...                    /* Arguments to the format string */
+){
+  va_list ap;
+  int rc;
+
+  va_start(ap, errmsg);
+  rc = sqlite_get_table_vprintf(db, sqlFormat, resultp, nrow, ncol, errmsg, ap);
+  va_end(ap);
+  return rc;
+}
+int sqlite_get_table_vprintf(
+  sqlite *db,            /* An open database */
+  const char *sqlFormat, /* printf-style format string for the SQL */
+  char ***resultp,       /* Result written to a char *[]  that this points to */
+  int *nrow,             /* Number of result rows written here */
+  int *ncolumn,          /* Number of result columns written here */
+  char **errmsg,         /* Error msg written here */
+  va_list ap             /* Arguments to the format string */
+){
+  char *zSql;
+  int rc;
+
+  zSql = sqlite_vmprintf(sqlFormat, ap);
+  rc = sqlite_get_table(db, zSql, resultp, nrow, ncolumn, errmsg);
+  free(zSql);
+  return rc;
+}
diff --git a/ext/sqlite/libsqlite/src/random.c b/ext/sqlite/libsqlite/src/random.c
new file mode 100644 (file)
index 0000000..d18bebf
--- /dev/null
@@ -0,0 +1,113 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains code to implement a pseudo-random number
+** generator (PRNG) for SQLite.
+**
+** Random numbers are used by some of the database backends in order
+** to generate random integer keys for tables or random filenames.
+**
+** $Id$
+*/
+#include "sqliteInt.h"
+#include "os.h"
+
+
+/*
+** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
+** must be held while executing this routine.
+**
+** Why not just use a library random generator like lrand48() for this?
+** Because the OP_NewRecno opcode in the VDBE depends on having a very
+** good source of random numbers.  The lrand48() library function may
+** well be good enough.  But maybe not.  Or maybe lrand48() has some
+** subtle problems on some systems that could cause problems.  It is hard
+** to know.  To minimize the risk of problems due to bad lrand48()
+** implementations, SQLite uses this random number generator based
+** on RC4, which we know works very well.
+*/
+static int randomByte(){
+  int t;
+
+  /* All threads share a single random number generator.
+  ** This structure is the current state of the generator.
+  */
+  static struct {
+    int isInit;          /* True if initialized */
+    int i, j;            /* State variables */
+    int s[256];          /* State variables */
+  } prng;
+
+  /* Initialize the state of the random number generator once,
+  ** the first time this routine is called.  The seed value does
+  ** not need to contain a lot of randomness since we are not
+  ** trying to do secure encryption or anything like that...
+  **
+  ** Nothing in this file or anywhere else in SQLite does any kind of
+  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
+  ** number generator) not as an encryption device.
+  */
+  if( !prng.isInit ){
+    int i;
+    char k[256];
+    prng.j = 0;
+    prng.i = 0;
+    sqliteOsRandomSeed(k);
+    for(i=0; i<256; i++){
+      prng.s[i] = i;
+    }
+    for(i=0; i<256; i++){
+      int t;
+      prng.j = (prng.j + prng.s[i] + k[i]) & 0xff;
+      t = prng.s[prng.j];
+      prng.s[prng.j] = prng.s[i];
+      prng.s[i] = t;
+    }
+    prng.isInit = 1;
+  }
+
+  /* Generate and return single random byte
+  */
+  prng.i = (prng.i + 1) & 0xff;
+  prng.j = (prng.j + prng.s[prng.i]) & 0xff;
+  t = prng.s[prng.i];
+  prng.s[prng.i] = prng.s[prng.j];
+  prng.s[prng.j] = t;
+  t = prng.s[prng.i] + prng.s[prng.j];
+  return prng.s[t & 0xff];
+}
+
+/*
+** Return an random 8-bit integer.
+*/
+int sqliteRandomByte(){
+  int r;
+  sqliteOsEnterMutex();
+  r = randomByte();
+  sqliteOsLeaveMutex();
+  return r;
+}
+
+/*
+** Return a random 32-bit integer.  The integer is generated by making
+** 4 calls to sqliteRandomByte().
+*/
+int sqliteRandomInteger(){
+  int r;
+  int i;
+  sqliteOsEnterMutex();
+  r = randomByte();
+  for(i=1; i<4; i++){
+    r = (r<<8) + randomByte();
+  }
+  sqliteOsLeaveMutex();
+  return r;
+}
diff --git a/ext/sqlite/libsqlite/src/select.c b/ext/sqlite/libsqlite/src/select.c
new file mode 100644 (file)
index 0000000..03eb861
--- /dev/null
@@ -0,0 +1,2347 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains C code routines that are called by the parser
+** to handle SELECT statements in SQLite.
+**
+** $Id$
+*/
+#include "sqliteInt.h"
+
+
+/*
+** Allocate a new Select structure and return a pointer to that
+** structure.
+*/
+Select *sqliteSelectNew(
+  ExprList *pEList,     /* which columns to include in the result */
+  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
+  Expr *pWhere,         /* the WHERE clause */
+  ExprList *pGroupBy,   /* the GROUP BY clause */
+  Expr *pHaving,        /* the HAVING clause */
+  ExprList *pOrderBy,   /* the ORDER BY clause */
+  int isDistinct,       /* true if the DISTINCT keyword is present */
+  int nLimit,           /* LIMIT value.  -1 means not used */
+  int nOffset           /* OFFSET value.  -1 means not used */
+){
+  Select *pNew;
+  pNew = sqliteMalloc( sizeof(*pNew) );
+  if( pNew==0 ){
+    sqliteExprListDelete(pEList);
+    sqliteSrcListDelete(pSrc);
+    sqliteExprDelete(pWhere);
+    sqliteExprListDelete(pGroupBy);
+    sqliteExprDelete(pHaving);
+    sqliteExprListDelete(pOrderBy);
+  }else{
+    pNew->pEList = pEList;
+    pNew->pSrc = pSrc;
+    pNew->pWhere = pWhere;
+    pNew->pGroupBy = pGroupBy;
+    pNew->pHaving = pHaving;
+    pNew->pOrderBy = pOrderBy;
+    pNew->isDistinct = isDistinct;
+    pNew->op = TK_SELECT;
+    pNew->nLimit = nLimit;
+    pNew->nOffset = nOffset;
+  }
+  return pNew;
+}
+
+/*
+** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
+** type of join.  Return an integer constant that expresses that type
+** in terms of the following bit values:
+**
+**     JT_INNER
+**     JT_OUTER
+**     JT_NATURAL
+**     JT_LEFT
+**     JT_RIGHT
+**
+** A full outer join is the combination of JT_LEFT and JT_RIGHT.
+**
+** If an illegal or unsupported join type is seen, then still return
+** a join type, but put an error in the pParse structure.
+*/
+int sqliteJoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
+  int jointype = 0;
+  Token *apAll[3];
+  Token *p;
+  static struct {
+    const char *zKeyword;
+    int nChar;
+    int code;
+  } keywords[] = {
+    { "natural", 7, JT_NATURAL },
+    { "left",    4, JT_LEFT|JT_OUTER },
+    { "right",   5, JT_RIGHT|JT_OUTER },
+    { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
+    { "outer",   5, JT_OUTER },
+    { "inner",   5, JT_INNER },
+    { "cross",   5, JT_INNER },
+  };
+  int i, j;
+  apAll[0] = pA;
+  apAll[1] = pB;
+  apAll[2] = pC;
+  for(i=0; i<3 && apAll[i]; i++){
+    p = apAll[i];
+    for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
+      if( p->n==keywords[j].nChar 
+          && sqliteStrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
+        jointype |= keywords[j].code;
+        break;
+      }
+    }
+    if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
+      jointype |= JT_ERROR;
+      break;
+    }
+  }
+  if(
+     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
+     (jointype & JT_ERROR)!=0
+  ){
+    static Token dummy = { 0, 0 };
+    char *zSp1 = " ", *zSp2 = " ";
+    if( pB==0 ){ pB = &dummy; zSp1 = 0; }
+    if( pC==0 ){ pC = &dummy; zSp2 = 0; }
+    sqliteSetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0,
+       pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0);
+    pParse->nErr++;
+    jointype = JT_INNER;
+  }else if( jointype & JT_RIGHT ){
+    sqliteSetString(&pParse->zErrMsg, 
+      "RIGHT and FULL OUTER JOINs are not currently supported", 0);
+    pParse->nErr++;
+    jointype = JT_INNER;
+  }
+  return jointype;
+}
+
+/*
+** Return the index of a column in a table.  Return -1 if the column
+** is not contained in the table.
+*/
+static int columnIndex(Table *pTab, const char *zCol){
+  int i;
+  for(i=0; i<pTab->nCol; i++){
+    if( sqliteStrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
+  }
+  return -1;
+}
+
+/*
+** Add a term to the WHERE expression in *ppExpr that requires the
+** zCol column to be equal in the two tables pTab1 and pTab2.
+*/
+static void addWhereTerm(
+  const char *zCol,        /* Name of the column */
+  const Table *pTab1,      /* First table */
+  const Table *pTab2,      /* Second table */
+  Expr **ppExpr            /* Add the equality term to this expression */
+){
+  Token dummy;
+  Expr *pE1a, *pE1b, *pE1c;
+  Expr *pE2a, *pE2b, *pE2c;
+  Expr *pE;
+
+  dummy.z = zCol;
+  dummy.n = strlen(zCol);
+  dummy.dyn = 0;
+  pE1a = sqliteExpr(TK_ID, 0, 0, &dummy);
+  pE2a = sqliteExpr(TK_ID, 0, 0, &dummy);
+  dummy.z = pTab1->zName;
+  dummy.n = strlen(dummy.z);
+  pE1b = sqliteExpr(TK_ID, 0, 0, &dummy);
+  dummy.z = pTab2->zName;
+  dummy.n = strlen(dummy.z);
+  pE2b = sqliteExpr(TK_ID, 0, 0, &dummy);
+  pE1c = sqliteExpr(TK_DOT, pE1b, pE1a, 0);
+  pE2c = sqliteExpr(TK_DOT, pE2b, pE2a, 0);
+  pE = sqliteExpr(TK_EQ, pE1c, pE2c, 0);
+  ExprSetProperty(pE, EP_FromJoin);
+  if( *ppExpr ){
+    *ppExpr = sqliteExpr(TK_AND, *ppExpr, pE, 0);
+  }else{
+    *ppExpr = pE;
+  }
+}
+
+/*
+** Set the EP_FromJoin property on all terms of the given expression.
+**
+** The EP_FromJoin property is used on terms of an expression to tell
+** the LEFT OUTER JOIN processing logic that this term is part of the
+** join restriction specified in the ON or USING clause and not a part
+** of the more general WHERE clause.  These terms are moved over to the
+** WHERE clause during join processing but we need to remember that they
+** originated in the ON or USING clause.
+*/
+static void setJoinExpr(Expr *p){
+  while( p ){
+    ExprSetProperty(p, EP_FromJoin);
+    setJoinExpr(p->pLeft);
+    p = p->pRight;
+  } 
+}
+
+/*
+** This routine processes the join information for a SELECT statement.
+** ON and USING clauses are converted into extra terms of the WHERE clause.
+** NATURAL joins also create extra WHERE clause terms.
+**
+** This routine returns the number of errors encountered.
+*/
+static int sqliteProcessJoin(Parse *pParse, Select *p){
+  SrcList *pSrc;
+  int i, j;
+  pSrc = p->pSrc;
+  for(i=0; i<pSrc->nSrc-1; i++){
+    struct SrcList_item *pTerm = &pSrc->a[i];
+    struct SrcList_item *pOther = &pSrc->a[i+1];
+
+    if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
+
+    /* When the NATURAL keyword is present, add WHERE clause terms for
+    ** every column that the two tables have in common.
+    */
+    if( pTerm->jointype & JT_NATURAL ){
+      Table *pTab;
+      if( pTerm->pOn || pTerm->pUsing ){
+        sqliteSetString(&pParse->zErrMsg, "a NATURAL join may not have "
+           "an ON or USING clause", 0);
+        pParse->nErr++;
+        return 1;
+      }
+      pTab = pTerm->pTab;
+      for(j=0; j<pTab->nCol; j++){
+        if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
+          addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
+        }
+      }
+    }
+
+    /* Disallow both ON and USING clauses in the same join
+    */
+    if( pTerm->pOn && pTerm->pUsing ){
+      sqliteSetString(&pParse->zErrMsg, "cannot have both ON and USING "
+        "clauses in the same join", 0);
+      pParse->nErr++;
+      return 1;
+    }
+
+    /* Add the ON clause to the end of the WHERE clause, connected by
+    ** and AND operator.
+    */
+    if( pTerm->pOn ){
+      setJoinExpr(pTerm->pOn);
+      if( p->pWhere==0 ){
+        p->pWhere = pTerm->pOn;
+      }else{
+        p->pWhere = sqliteExpr(TK_AND, p->pWhere, pTerm->pOn, 0);
+      }
+      pTerm->pOn = 0;
+    }
+
+    /* Create extra terms on the WHERE clause for each column named
+    ** in the USING clause.  Example: If the two tables to be joined are 
+    ** A and B and the USING clause names X, Y, and Z, then add this
+    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
+    ** Report an error if any column mentioned in the USING clause is
+    ** not contained in both tables to be joined.
+    */
+    if( pTerm->pUsing ){
+      IdList *pList;
+      int j;
+      assert( i<pSrc->nSrc-1 );
+      pList = pTerm->pUsing;
+      for(j=0; j<pList->nId; j++){
+        if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 ||
+            columnIndex(pOther->pTab, pList->a[j].zName)<0 ){
+          sqliteSetString(&pParse->zErrMsg, "cannot join using column ",
+            pList->a[j].zName, " - column not present in both tables", 0);
+          pParse->nErr++;
+          return 1;
+        }
+        addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
+      }
+    }
+  }
+  return 0;
+}
+
+/*
+** This routine implements a minimal Oracle8 join syntax immulation.
+** The precise oracle8 syntax is not implemented - it is easy enough
+** to get this routine confused.  But this routine does make it possible
+** to write a single SQL statement that does a left outer join in both
+** oracle8 and in SQLite.
+**
+** This routine looks for TK_COLUMN expression nodes that are marked
+** with the EP_Oracle8Join property.  Such nodes are generated by a
+** column name (either "column" or "table.column") that is followed by
+** the special "(+)" operator.  If the table of the column marked with
+** the (+) operator is the second are subsequent table in a join, then
+** that table becomes the left table in a LEFT OUTER JOIN.  The expression
+** that uses that table becomes part of the ON clause for the join.
+**
+** It is important to enphasize that this is not exactly how oracle8
+** works.  But it is close enough so that one can construct queries that
+** will work correctly for both SQLite and Oracle8.
+*/
+static int sqliteOracle8JoinFixup(
+  int base,         /* VDBE cursor number for first table in pSrc */
+  SrcList *pSrc,    /* List of tables being joined */
+  Expr *pWhere      /* The WHERE clause of the SELECT statement */
+){
+  int rc = 0;
+  if( ExprHasProperty(pWhere, EP_Oracle8Join) && pWhere->op==TK_COLUMN ){
+    int idx = pWhere->iTable - base;
+    assert( idx>=0 && idx<pSrc->nSrc );
+    if( idx>0 ){
+      pSrc->a[idx-1].jointype &= ~JT_INNER;
+      pSrc->a[idx-1].jointype |= JT_OUTER|JT_LEFT;
+      return 1;
+    }
+  }
+  if( pWhere->pRight ){
+    rc = sqliteOracle8JoinFixup(base, pSrc, pWhere->pRight);
+  }
+  if( pWhere->pLeft ){
+    rc |= sqliteOracle8JoinFixup(base, pSrc, pWhere->pLeft);
+  }
+  if( pWhere->pList ){
+    int i;
+    ExprList *pList = pWhere->pList;
+    for(i=0; i<pList->nExpr && rc==0; i++){
+      rc |= sqliteOracle8JoinFixup(base, pSrc, pList->a[i].pExpr);
+    }
+  }
+  if( rc==1 && (pWhere->op==TK_AND || pWhere->op==TK_EQ) ){
+    setJoinExpr(pWhere);
+    rc = 0;
+  }
+  return rc;
+}
+
+/*
+** Delete the given Select structure and all of its substructures.
+*/
+void sqliteSelectDelete(Select *p){
+  if( p==0 ) return;
+  sqliteExprListDelete(p->pEList);
+  sqliteSrcListDelete(p->pSrc);
+  sqliteExprDelete(p->pWhere);
+  sqliteExprListDelete(p->pGroupBy);
+  sqliteExprDelete(p->pHaving);
+  sqliteExprListDelete(p->pOrderBy);
+  sqliteSelectDelete(p->pPrior);
+  sqliteFree(p->zSelect);
+  sqliteFree(p);
+}
+
+/*
+** Delete the aggregate information from the parse structure.
+*/
+static void sqliteAggregateInfoReset(Parse *pParse){
+  sqliteFree(pParse->aAgg);
+  pParse->aAgg = 0;
+  pParse->nAgg = 0;
+  pParse->useAgg = 0;
+}
+
+/*
+** Insert code into "v" that will push the record on the top of the
+** stack into the sorter.
+*/
+static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
+  char *zSortOrder;
+  int i;
+  zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
+  if( zSortOrder==0 ) return;
+  for(i=0; i<pOrderBy->nExpr; i++){
+    int order = pOrderBy->a[i].sortOrder;
+    int type;
+    int c;
+    if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
+      type = SQLITE_SO_TEXT;
+    }else if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_NUM ){
+      type = SQLITE_SO_NUM;
+    }else if( pParse->db->file_format>=4 ){
+      type = sqliteExprType(pOrderBy->a[i].pExpr);
+    }else{
+      type = SQLITE_SO_NUM;
+    }
+    if( (order & SQLITE_SO_DIRMASK)==SQLITE_SO_ASC ){
+      c = type==SQLITE_SO_TEXT ? 'A' : '+';
+    }else{
+      c = type==SQLITE_SO_TEXT ? 'D' : '-';
+    }
+    zSortOrder[i] = c;
+    sqliteExprCode(pParse, pOrderBy->a[i].pExpr);
+  }
+  zSortOrder[pOrderBy->nExpr] = 0;
+  sqliteVdbeAddOp(v, OP_SortMakeKey, pOrderBy->nExpr, 0);
+  sqliteVdbeChangeP3(v, -1, zSortOrder, strlen(zSortOrder));
+  sqliteFree(zSortOrder);
+  sqliteVdbeAddOp(v, OP_SortPut, 0, 0);
+}
+
+/*
+** This routine adds a P3 argument to the last VDBE opcode that was
+** inserted. The P3 argument added is a string suitable for the 
+** OP_MakeKey or OP_MakeIdxKey opcodes.  The string consists of
+** characters 't' or 'n' depending on whether or not the various
+** fields of the key to be generated should be treated as numeric
+** or as text.  See the OP_MakeKey and OP_MakeIdxKey opcode
+** documentation for additional information about the P3 string.
+** See also the sqliteAddIdxKeyType() routine.
+*/
+void sqliteAddKeyType(Vdbe *v, ExprList *pEList){
+  int nColumn = pEList->nExpr;
+  char *zType = sqliteMalloc( nColumn+1 );
+  int i;
+  if( zType==0 ) return;
+  for(i=0; i<nColumn; i++){
+    zType[i] = sqliteExprType(pEList->a[i].pExpr)==SQLITE_SO_NUM ? 'n' : 't';
+  }
+  zType[i] = 0;
+  sqliteVdbeChangeP3(v, -1, zType, nColumn);
+  sqliteFree(zType);
+}
+
+/*
+** This routine generates the code for the inside of the inner loop
+** of a SELECT.
+**
+** If srcTab and nColumn are both zero, then the pEList expressions
+** are evaluated in order to get the data for this row.  If nColumn>0
+** then data is pulled from srcTab and pEList is used only to get the
+** datatypes for each column.
+*/
+static int selectInnerLoop(
+  Parse *pParse,          /* The parser context */
+  Select *p,              /* The complete select statement being coded */
+  ExprList *pEList,       /* List of values being extracted */
+  int srcTab,             /* Pull data from this table */
+  int nColumn,            /* Number of columns in the source table */
+  ExprList *pOrderBy,     /* If not NULL, sort results using this key */
+  int distinct,           /* If >=0, make sure results are distinct */
+  int eDest,              /* How to dispose of the results */
+  int iParm,              /* An argument to the disposal method */
+  int iContinue,          /* Jump here to continue with next row */
+  int iBreak              /* Jump here to break out of the inner loop */
+){
+  Vdbe *v = pParse->pVdbe;
+  int i;
+
+  if( v==0 ) return 0;
+  assert( pEList!=0 );
+
+  /* If there was a LIMIT clause on the SELECT statement, then do the check
+  ** to see if this row should be output.
+  */
+  if( pOrderBy==0 ){
+    if( p->nOffset>0 ){
+      int addr = sqliteVdbeCurrentAddr(v);
+      sqliteVdbeAddOp(v, OP_MemIncr, p->nOffset, addr+2);
+      sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
+    }
+    if( p->nLimit>=0 ){
+      sqliteVdbeAddOp(v, OP_MemIncr, p->nLimit, iBreak);
+    }
+  }
+
+  /* Pull the requested columns.
+  */
+  if( nColumn>0 ){
+    for(i=0; i<nColumn; i++){
+      sqliteVdbeAddOp(v, OP_Column, srcTab, i);
+    }
+  }else{
+    nColumn = pEList->nExpr;
+    for(i=0; i<pEList->nExpr; i++){
+      sqliteExprCode(pParse, pEList->a[i].pExpr);
+    }
+  }
+
+  /* If the DISTINCT keyword was present on the SELECT statement
+  ** and this row has been seen before, then do not make this row
+  ** part of the result.
+  */
+  if( distinct>=0 && pEList && pEList->nExpr>0 ){
+#if NULL_ALWAYS_DISTINCT
+    sqliteVdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqliteVdbeCurrentAddr(v)+7);
+#endif
+    sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
+    if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pEList);
+    sqliteVdbeAddOp(v, OP_Distinct, distinct, sqliteVdbeCurrentAddr(v)+3);
+    sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
+    sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
+    sqliteVdbeAddOp(v, OP_String, 0, 0);
+    sqliteVdbeAddOp(v, OP_PutStrKey, distinct, 0);
+  }
+
+  switch( eDest ){
+    /* In this mode, write each query result to the key of the temporary
+    ** table iParm.
+    */
+    case SRT_Union: {
+      sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
+      sqliteVdbeAddOp(v, OP_String, 0, 0);
+      sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
+      break;
+    }
+
+    /* Store the result as data using a unique key.
+    */
+    case SRT_Table:
+    case SRT_TempTable: {
+      sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
+      if( pOrderBy ){
+        pushOntoSorter(pParse, v, pOrderBy);
+      }else{
+        sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
+        sqliteVdbeAddOp(v, OP_Pull, 1, 0);
+        sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
+      }
+      break;
+    }
+
+    /* Construct a record from the query result, but instead of
+    ** saving that record, use it as a key to delete elements from
+    ** the temporary table iParm.
+    */
+    case SRT_Except: {
+      int addr;
+      addr = sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
+      sqliteVdbeAddOp(v, OP_NotFound, iParm, addr+3);
+      sqliteVdbeAddOp(v, OP_Delete, iParm, 0);
+      break;
+    }
+
+    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
+    ** then there should be a single item on the stack.  Write this
+    ** item into the set table with bogus data.
+    */
+    case SRT_Set: {
+      int lbl = sqliteVdbeMakeLabel(v);
+      assert( nColumn==1 );
+      sqliteVdbeAddOp(v, OP_IsNull, -1, lbl);
+      if( pOrderBy ){
+        pushOntoSorter(pParse, v, pOrderBy);
+      }else{
+        sqliteVdbeAddOp(v, OP_String, 0, 0);
+        sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
+      }
+      sqliteVdbeResolveLabel(v, lbl);
+      break;
+    }
+
+    /* If this is a scalar select that is part of an expression, then
+    ** store the results in the appropriate memory cell and break out
+    ** of the scan loop.
+    */
+    case SRT_Mem: {
+      assert( nColumn==1 );
+      if( pOrderBy ){
+        pushOntoSorter(pParse, v, pOrderBy);
+      }else{
+        sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
+        sqliteVdbeAddOp(v, OP_Goto, 0, iBreak);
+      }
+      break;
+    }
+
+    /* Send the data to the callback function.
+    */
+    case SRT_Callback:
+    case SRT_Sorter: {
+      if( pOrderBy ){
+        sqliteVdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
+        pushOntoSorter(pParse, v, pOrderBy);
+      }else{
+        assert( eDest==SRT_Callback );
+        sqliteVdbeAddOp(v, OP_Callback, nColumn, 0);
+      }
+      break;
+    }
+
+    /* Invoke a subroutine to handle the results.  The subroutine itself
+    ** is responsible for popping the results off of the stack.
+    */
+    case SRT_Subroutine: {
+      if( pOrderBy ){
+        sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
+        pushOntoSorter(pParse, v, pOrderBy);
+      }else{
+        sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
+      }
+      break;
+    }
+
+    /* Discard the results.  This is used for SELECT statements inside
+    ** the body of a TRIGGER.  The purpose of such selects is to call
+    ** user-defined functions that have side effects.  We do not care
+    ** about the actual results of the select.
+    */
+    default: {
+      assert( eDest==SRT_Discard );
+      sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
+      break;
+    }
+  }
+  return 0;
+}
+
+/*
+** If the inner loop was generated using a non-null pOrderBy argument,
+** then the results were placed in a sorter.  After the loop is terminated
+** we need to run the sorter and output the results.  The following
+** routine generates the code needed to do that.
+*/
+static void generateSortTail(
+  Select *p,       /* The SELECT statement */
+  Vdbe *v,         /* Generate code into this VDBE */
+  int nColumn,     /* Number of columns of data */
+  int eDest,       /* Write the sorted results here */
+  int iParm        /* Optional parameter associated with eDest */
+){
+  int end = sqliteVdbeMakeLabel(v);
+  int addr;
+  if( eDest==SRT_Sorter ) return;
+  sqliteVdbeAddOp(v, OP_Sort, 0, 0);
+  addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end);
+  if( p->nOffset>0 ){
+    sqliteVdbeAddOp(v, OP_MemIncr, p->nOffset, addr+4);
+    sqliteVdbeAddOp(v, OP_Pop, 1, 0);
+    sqliteVdbeAddOp(v, OP_Goto, 0, addr);
+  }
+  if( p->nLimit>=0 ){
+    sqliteVdbeAddOp(v, OP_MemIncr, p->nLimit, end);
+  }
+  switch( eDest ){
+    case SRT_Callback: {
+      sqliteVdbeAddOp(v, OP_SortCallback, nColumn, 0);
+      break;
+    }
+    case SRT_Table:
+    case SRT_TempTable: {
+      sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
+      sqliteVdbeAddOp(v, OP_Pull, 1, 0);
+      sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
+      break;
+    }
+    case SRT_Set: {
+      assert( nColumn==1 );
+      sqliteVdbeAddOp(v, OP_IsNull, -1, sqliteVdbeCurrentAddr(v)+3);
+      sqliteVdbeAddOp(v, OP_String, 0, 0);
+      sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
+      break;
+    }
+    case SRT_Mem: {
+      assert( nColumn==1 );
+      sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
+      sqliteVdbeAddOp(v, OP_Goto, 0, end);
+      break;
+    }
+    case SRT_Subroutine: {
+      int i;
+      for(i=0; i<nColumn; i++){
+        sqliteVdbeAddOp(v, OP_Column, -1-i, i);
+      }
+      sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
+      sqliteVdbeAddOp(v, OP_Pop, 1, 0);
+      break;
+    }
+    default: {
+      /* Do nothing */
+      break;
+    }
+  }
+  sqliteVdbeAddOp(v, OP_Goto, 0, addr);
+  sqliteVdbeResolveLabel(v, end);
+  sqliteVdbeAddOp(v, OP_SortReset, 0, 0);
+}
+
+/*
+** Generate code that will tell the VDBE the datatypes of
+** columns in the result set.
+**
+** This routine only generates code if the "PRAGMA show_datatypes=on"
+** has been executed.  The datatypes are reported out in the azCol
+** parameter to the callback function.  The first N azCol[] entries
+** are the names of the columns, and the second N entries are the
+** datatypes for the columns.
+**
+** The "datatype" for a result that is a column of a type is the
+** datatype definition extracted from the CREATE TABLE statement.
+** The datatype for an expression is either TEXT or NUMERIC.  The
+** datatype for a ROWID field is INTEGER.
+*/
+static void generateColumnTypes(
+  Parse *pParse,      /* Parser context */
+  int base,           /* VDBE cursor corresponding to first entry in pTabList */
+  SrcList *pTabList,  /* List of tables */
+  ExprList *pEList    /* Expressions defining the result set */
+){
+  Vdbe *v = pParse->pVdbe;
+  int i;
+  if( pParse->useCallback && (pParse->db->flags & SQLITE_ReportTypes)==0 ){
+    return;
+  }
+  for(i=0; i<pEList->nExpr; i++){
+    Expr *p = pEList->a[i].pExpr;
+    char *zType = 0;
+    if( p==0 ) continue;
+    if( p->op==TK_COLUMN && pTabList ){
+      Table *pTab = pTabList->a[p->iTable - base].pTab;
+      int iCol = p->iColumn;
+      if( iCol<0 ) iCol = pTab->iPKey;
+      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
+      if( iCol<0 ){
+        zType = "INTEGER";
+      }else{
+        zType = pTab->aCol[iCol].zType;
+      }
+    }else{
+      if( sqliteExprType(p)==SQLITE_SO_TEXT ){
+        zType = "TEXT";
+      }else{
+        zType = "NUMERIC";
+      }
+    }
+    sqliteVdbeAddOp(v, OP_ColumnName, i + pEList->nExpr, 0);
+    sqliteVdbeChangeP3(v, -1, zType, P3_STATIC);
+  }
+}
+
+/*
+** Generate code that will tell the VDBE the names of columns
+** in the result set.  This information is used to provide the
+** azCol[] vaolues in the callback.
+*/
+static void generateColumnNames(
+  Parse *pParse,      /* Parser context */
+  int base,           /* VDBE cursor corresponding to first entry in pTabList */
+  SrcList *pTabList,  /* List of tables */
+  ExprList *pEList    /* Expressions defining the result set */
+){
+  Vdbe *v = pParse->pVdbe;
+  int i;
+  if( pParse->colNamesSet || v==0 || sqlite_malloc_failed ) return;
+  pParse->colNamesSet = 1;
+  for(i=0; i<pEList->nExpr; i++){
+    Expr *p;
+    char *zType = 0;
+    int showFullNames;
+    p = pEList->a[i].pExpr;
+    if( p==0 ) continue;
+    if( pEList->a[i].zName ){
+      char *zName = pEList->a[i].zName;
+      sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
+      sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
+      continue;
+    }
+    showFullNames = (pParse->db->flags & SQLITE_FullColNames)!=0;
+    if( p->op==TK_COLUMN && pTabList ){
+      Table *pTab = pTabList->a[p->iTable - base].pTab;
+      char *zCol;
+      int iCol = p->iColumn;
+      if( iCol<0 ) iCol = pTab->iPKey;
+      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
+      if( iCol<0 ){
+        zCol = "_ROWID_";
+        zType = "INTEGER";
+      }else{
+        zCol = pTab->aCol[iCol].zName;
+        zType = pTab->aCol[iCol].zType;
+      }
+      if( p->span.z && p->span.z[0] && !showFullNames ){
+        int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
+        sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
+        sqliteVdbeCompressSpace(v, addr);
+      }else if( pTabList->nSrc>1 || showFullNames ){
+        char *zName = 0;
+        char *zTab;
+        zTab = pTabList->a[p->iTable - base].zAlias;
+        if( showFullNames || zTab==0 ) zTab = pTab->zName;
+        sqliteSetString(&zName, zTab, ".", zCol, 0);
+        sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
+        sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
+        sqliteFree(zName);
+      }else{
+        sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
+        sqliteVdbeChangeP3(v, -1, zCol, 0);
+      }
+    }else if( p->span.z && p->span.z[0] ){
+      int addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0);
+      sqliteVdbeChangeP3(v, -1, p->span.z, p->span.n);
+      sqliteVdbeCompressSpace(v, addr);
+    }else{
+      char zName[30];
+      assert( p->op!=TK_COLUMN || pTabList==0 );
+      sprintf(zName, "column%d", i+1);
+      sqliteVdbeAddOp(v, OP_ColumnName, i, 0);
+      sqliteVdbeChangeP3(v, -1, zName, strlen(zName));
+    }
+  }
+}
+
+/*
+** Name of the connection operator, used for error messages.
+*/
+static const char *selectOpName(int id){
+  char *z;
+  switch( id ){
+    case TK_ALL:       z = "UNION ALL";   break;
+    case TK_INTERSECT: z = "INTERSECT";   break;
+    case TK_EXCEPT:    z = "EXCEPT";      break;
+    default:           z = "UNION";       break;
+  }
+  return z;
+}
+
+/*
+** Forward declaration
+*/
+static int fillInColumnList(Parse*, Select*);
+
+/*
+** Given a SELECT statement, generate a Table structure that describes
+** the result set of that SELECT.
+*/
+Table *sqliteResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
+  Table *pTab;
+  int i;
+  ExprList *pEList;
+
+  if( fillInColumnList(pParse, pSelect) ){
+    return 0;
+  }
+  pTab = sqliteMalloc( sizeof(Table) );
+  if( pTab==0 ){
+    return 0;
+  }
+  pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
+  pEList = pSelect->pEList;
+  pTab->nCol = pEList->nExpr;
+  assert( pTab->nCol>0 );
+  pTab->aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
+  for(i=0; i<pTab->nCol; i++){
+    Expr *p;
+    if( pEList->a[i].zName ){
+      pTab->aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
+    }else if( (p=pEList->a[i].pExpr)->span.z && p->span.z[0] ){
+      sqliteSetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
+    }else if( p->op==TK_DOT && p->pRight && p->pRight->token.z &&
+           p->pRight->token.z[0] ){
+      sqliteSetNString(&pTab->aCol[i].zName, 
+           p->pRight->token.z, p->pRight->token.n, 0);
+    }else{
+      char zBuf[30];
+      sprintf(zBuf, "column%d", i+1);
+      pTab->aCol[i].zName = sqliteStrDup(zBuf);
+    }
+  }
+  pTab->iPKey = -1;
+  return pTab;
+}
+
+/*
+** For the given SELECT statement, do three things.
+**
+**    (1)  Fill in the pTabList->a[].pTab fields in the SrcList that 
+**         defines the set of tables that should be scanned. 
+**
+**    (2)  Add terms to the WHERE clause to accomodate the NATURAL keyword
+**         on joins and the ON and USING clause of joins.
+**
+**    (3)  Scan the list of columns in the result set (pEList) looking
+**         for instances of the "*" operator or the TABLE.* operator.
+**         If found, expand each "*" to be every column in every table
+**         and TABLE.* to be every column in TABLE.
+**
+** Return 0 on success.  If there are problems, leave an error message
+** in pParse and return non-zero.
+*/
+static int fillInColumnList(Parse *pParse, Select *p){
+  int i, j, k, rc;
+  SrcList *pTabList;
+  ExprList *pEList;
+  Table *pTab;
+
+  if( p==0 || p->pSrc==0 ) return 1;
+  pTabList = p->pSrc;
+  pEList = p->pEList;
+
+  /* Look up every table in the table list.
+  */
+  for(i=0; i<pTabList->nSrc; i++){
+    if( pTabList->a[i].pTab ){
+      /* This routine has run before!  No need to continue */
+      return 0;
+    }
+    if( pTabList->a[i].zName==0 ){
+      /* A sub-query in the FROM clause of a SELECT */
+      assert( pTabList->a[i].pSelect!=0 );
+      if( pTabList->a[i].zAlias==0 ){
+        char zFakeName[60];
+        sprintf(zFakeName, "sqlite_subquery_%p_",
+           (void*)pTabList->a[i].pSelect);
+        sqliteSetString(&pTabList->a[i].zAlias, zFakeName, 0);
+      }
+      pTabList->a[i].pTab = pTab = 
+        sqliteResultSetOfSelect(pParse, pTabList->a[i].zAlias,
+                                        pTabList->a[i].pSelect);
+      if( pTab==0 ){
+        return 1;
+      }
+      pTab->isTransient = 1;
+    }else{
+      /* An ordinary table or view name in the FROM clause */
+      pTabList->a[i].pTab = pTab = 
+        sqliteFindTable(pParse->db, pTabList->a[i].zName);
+      if( pTab==0 ){
+        sqliteSetString(&pParse->zErrMsg, "no such table: ", 
+           pTabList->a[i].zName, 0);
+        pParse->nErr++;
+        return 1;
+      }
+      if( pTab->pSelect ){
+        if( sqliteViewGetColumnNames(pParse, pTab) ){
+          return 1;
+        }
+        sqliteSelectDelete(pTabList->a[i].pSelect);
+        pTabList->a[i].pSelect = sqliteSelectDup(pTab->pSelect);
+      }
+    }
+  }
+
+  /* Process NATURAL keywords, and ON and USING clauses of joins.
+  */
+  if( sqliteProcessJoin(pParse, p) ) return 1;
+
+  /* For every "*" that occurs in the column list, insert the names of
+  ** all columns in all tables.  And for every TABLE.* insert the names
+  ** of all columns in TABLE.  The parser inserted a special expression
+  ** with the TK_ALL operator for each "*" that it found in the column list.
+  ** The following code just has to locate the TK_ALL expressions and expand
+  ** each one to the list of all columns in all tables.
+  **
+  ** The first loop just checks to see if there are any "*" operators
+  ** that need expanding.
+  */
+  for(k=0; k<pEList->nExpr; k++){
+    Expr *pE = pEList->a[k].pExpr;
+    if( pE->op==TK_ALL ) break;
+    if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
+         && pE->pLeft && pE->pLeft->op==TK_ID ) break;
+  }
+  rc = 0;
+  if( k<pEList->nExpr ){
+    /*
+    ** If we get here it means the result set contains one or more "*"
+    ** operators that need to be expanded.  Loop through each expression
+    ** in the result set and expand them one by one.
+    */
+    struct ExprList_item *a = pEList->a;
+    ExprList *pNew = 0;
+    for(k=0; k<pEList->nExpr; k++){
+      Expr *pE = a[k].pExpr;
+      if( pE->op!=TK_ALL &&
+           (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
+        /* This particular expression does not need to be expanded.
+        */
+        pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0);
+        pNew->a[pNew->nExpr-1].zName = a[k].zName;
+        a[k].pExpr = 0;
+        a[k].zName = 0;
+      }else{
+        /* This expression is a "*" or a "TABLE.*" and needs to be
+        ** expanded. */
+        int tableSeen = 0;      /* Set to 1 when TABLE matches */
+        Token *pName;           /* text of name of TABLE */
+        if( pE->op==TK_DOT && pE->pLeft ){
+          pName = &pE->pLeft->token;
+        }else{
+          pName = 0;
+        }
+        for(i=0; i<pTabList->nSrc; i++){
+          Table *pTab = pTabList->a[i].pTab;
+          char *zTabName = pTabList->a[i].zAlias;
+          if( zTabName==0 || zTabName[0]==0 ){ 
+            zTabName = pTab->zName;
+          }
+          if( pName && (zTabName==0 || zTabName[0]==0 || 
+                 sqliteStrNICmp(pName->z, zTabName, pName->n)!=0 ||
+                 zTabName[pName->n]!=0) ){
+            continue;
+          }
+          tableSeen = 1;
+          for(j=0; j<pTab->nCol; j++){
+            Expr *pExpr, *pLeft, *pRight;
+            char *zName = pTab->aCol[j].zName;
+
+            if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
+                columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
+              /* In a NATURAL join, omit the join columns from the 
+              ** table on the right */
+              continue;
+            }
+            if( i>0 && sqliteIdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
+              /* In a join with a USING clause, omit columns in the
+              ** using clause from the table on the right. */
+              continue;
+            }
+            pRight = sqliteExpr(TK_ID, 0, 0, 0);
+            if( pRight==0 ) break;
+            pRight->token.z = zName;
+            pRight->token.n = strlen(zName);
+            pRight->token.dyn = 0;
+            if( zTabName && pTabList->nSrc>1 ){
+              pLeft = sqliteExpr(TK_ID, 0, 0, 0);
+              pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0);
+              if( pExpr==0 ) break;
+              pLeft->token.z = zTabName;
+              pLeft->token.n = strlen(zTabName);
+              pLeft->token.dyn = 0;
+              sqliteSetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
+              pExpr->span.n = strlen(pExpr->span.z);
+              pExpr->span.dyn = 1;
+              pExpr->token.z = 0;
+              pExpr->token.n = 0;
+              pExpr->token.dyn = 0;
+            }else{
+              pExpr = pRight;
+              pExpr->span = pExpr->token;
+            }
+            pNew = sqliteExprListAppend(pNew, pExpr, 0);
+          }
+        }
+        if( !tableSeen ){
+          if( pName ){
+            sqliteSetNString(&pParse->zErrMsg, "no such table: ", -1, 
+              pName->z, pName->n, 0);
+          }else{
+            sqliteSetString(&pParse->zErrMsg, "no tables specified", 0);
+          }
+          rc = 1;
+        }
+      }
+    }
+    sqliteExprListDelete(pEList);
+    p->pEList = pNew;
+  }
+  return rc;
+}
+
+/*
+** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
+** in a select structure.  It just sets the pointers to NULL.  This
+** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
+** pointer is not NULL, this routine is called recursively on that pointer.
+**
+** This routine is called on the Select structure that defines a
+** VIEW in order to undo any bindings to tables.  This is necessary
+** because those tables might be DROPed by a subsequent SQL command.
+*/
+void sqliteSelectUnbind(Select *p){
+  int i;
+  SrcList *pSrc = p->pSrc;
+  Table *pTab;
+  if( p==0 ) return;
+  for(i=0; i<pSrc->nSrc; i++){
+    if( (pTab = pSrc->a[i].pTab)!=0 ){
+      if( pTab->isTransient ){
+        sqliteDeleteTable(0, pTab);
+#if 0
+        sqliteSelectDelete(pSrc->a[i].pSelect);
+        pSrc->a[i].pSelect = 0;
+#endif
+      }
+      pSrc->a[i].pTab = 0;
+      if( pSrc->a[i].pSelect ){
+        sqliteSelectUnbind(pSrc->a[i].pSelect);
+      }
+    }
+  }
+}
+
+/*
+** This routine associates entries in an ORDER BY expression list with
+** columns in a result.  For each ORDER BY expression, the opcode of
+** the top-level node is changed to TK_COLUMN and the iColumn value of
+** the top-level node is filled in with column number and the iTable
+** value of the top-level node is filled with iTable parameter.
+**
+** If there are prior SELECT clauses, they are processed first.  A match
+** in an earlier SELECT takes precedence over a later SELECT.
+**
+** Any entry that does not match is flagged as an error.  The number
+** of errors is returned.
+**
+** This routine does NOT correctly initialize the Expr.dataType  field
+** of the ORDER BY expressions.  The multiSelectSortOrder() routine
+** must be called to do that after the individual select statements
+** have all been analyzed.  This routine is unable to compute Expr.dataType
+** because it must be called before the individual select statements
+** have been analyzed.
+*/
+static int matchOrderbyToColumn(
+  Parse *pParse,          /* A place to leave error messages */
+  Select *pSelect,        /* Match to result columns of this SELECT */
+  ExprList *pOrderBy,     /* The ORDER BY values to match against columns */
+  int iTable,             /* Insert this value in iTable */
+  int mustComplete        /* If TRUE all ORDER BYs must match */
+){
+  int nErr = 0;
+  int i, j;
+  ExprList *pEList;
+
+  if( pSelect==0 || pOrderBy==0 ) return 1;
+  if( mustComplete ){
+    for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
+  }
+  if( fillInColumnList(pParse, pSelect) ){
+    return 1;
+  }
+  if( pSelect->pPrior ){
+    if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
+      return 1;
+    }
+  }
+  pEList = pSelect->pEList;
+  for(i=0; i<pOrderBy->nExpr; i++){
+    Expr *pE = pOrderBy->a[i].pExpr;
+    int iCol = -1;
+    if( pOrderBy->a[i].done ) continue;
+    if( sqliteExprIsInteger(pE, &iCol) ){
+      if( iCol<=0 || iCol>pEList->nExpr ){
+        char zBuf[200];
+        sprintf(zBuf,"ORDER BY position %d should be between 1 and %d",
+           iCol, pEList->nExpr);
+        sqliteSetString(&pParse->zErrMsg, zBuf, 0);
+        pParse->nErr++;
+        nErr++;
+        break;
+      }
+      if( !mustComplete ) continue;
+      iCol--;
+    }
+    for(j=0; iCol<0 && j<pEList->nExpr; j++){
+      if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
+        char *zName, *zLabel;
+        zName = pEList->a[j].zName;
+        assert( pE->token.z );
+        zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
+        sqliteDequote(zLabel);
+        if( sqliteStrICmp(zName, zLabel)==0 ){ 
+          iCol = j;
+        }
+        sqliteFree(zLabel);
+      }
+      if( iCol<0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
+        iCol = j;
+      }
+    }
+    if( iCol>=0 ){
+      pE->op = TK_COLUMN;
+      pE->iColumn = iCol;
+      pE->iTable = iTable;
+      pOrderBy->a[i].done = 1;
+    }
+    if( iCol<0 && mustComplete ){
+      char zBuf[30];
+      sprintf(zBuf,"%d",i+1);
+      sqliteSetString(&pParse->zErrMsg, "ORDER BY term number ", zBuf, 
+        " does not match any result column", 0);
+      pParse->nErr++;
+      nErr++;
+      break;
+    }
+  }
+  return nErr;  
+}
+
+/*
+** Get a VDBE for the given parser context.  Create a new one if necessary.
+** If an error occurs, return NULL and leave a message in pParse.
+*/
+Vdbe *sqliteGetVdbe(Parse *pParse){
+  Vdbe *v = pParse->pVdbe;
+  if( v==0 ){
+    v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
+  }
+  return v;
+}
+
+/*
+** This routine sets the Expr.dataType field on all elements of
+** the pOrderBy expression list.  The pOrderBy list will have been
+** set up by matchOrderbyToColumn().  Hence each expression has
+** a TK_COLUMN as its root node.  The Expr.iColumn refers to a 
+** column in the result set.   The datatype is set to SQLITE_SO_TEXT
+** if the corresponding column in p and every SELECT to the left of
+** p has a datatype of SQLITE_SO_TEXT.  If the cooressponding column
+** in p or any of the left SELECTs is SQLITE_SO_NUM, then the datatype
+** of the order-by expression is set to SQLITE_SO_NUM.
+**
+** Examples:
+**
+**     CREATE TABLE one(a INTEGER, b TEXT);
+**     CREATE TABLE two(c VARCHAR(5), d FLOAT);
+**
+**     SELECT b, b FROM one UNION SELECT d, c FROM two ORDER BY 1, 2;
+**
+** The primary sort key will use SQLITE_SO_NUM because the "d" in
+** the second SELECT is numeric.  The 1st column of the first SELECT
+** is text but that does not matter because a numeric always overrides
+** a text.
+**
+** The secondary key will use the SQLITE_SO_TEXT sort order because
+** both the (second) "b" in the first SELECT and the "c" in the second
+** SELECT have a datatype of text.
+*/ 
+static void multiSelectSortOrder(Select *p, ExprList *pOrderBy){
+  int i;
+  ExprList *pEList;
+  if( pOrderBy==0 ) return;
+  if( p==0 ){
+    for(i=0; i<pOrderBy->nExpr; i++){
+      pOrderBy->a[i].pExpr->dataType = SQLITE_SO_TEXT;
+    }
+    return;
+  }
+  multiSelectSortOrder(p->pPrior, pOrderBy);
+  pEList = p->pEList;
+  for(i=0; i<pOrderBy->nExpr; i++){
+    Expr *pE = pOrderBy->a[i].pExpr;
+    if( pE->dataType==SQLITE_SO_NUM ) continue;
+    assert( pE->iColumn>=0 );
+    if( pEList->nExpr>pE->iColumn ){
+      pE->dataType = sqliteExprType(pEList->a[pE->iColumn].pExpr);
+    }
+  }
+}
+
+/*
+** This routine is called to process a query that is really the union
+** or intersection of two or more separate queries.
+**
+** "p" points to the right-most of the two queries.  the query on the
+** left is p->pPrior.  The left query could also be a compound query
+** in which case this routine will be called recursively. 
+**
+** The results of the total query are to be written into a destination
+** of type eDest with parameter iParm.
+**
+** Example 1:  Consider a three-way compound SQL statement.
+**
+**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
+**
+** This statement is parsed up as follows:
+**
+**     SELECT c FROM t3
+**      |
+**      `----->  SELECT b FROM t2
+**                |
+**                `------>  SELECT c FROM t1
+**
+** The arrows in the diagram above represent the Select.pPrior pointer.
+** So if this routine is called with p equal to the t3 query, then
+** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
+**
+** Notice that because of the way SQLite parses compound SELECTs, the
+** individual selects always group from left to right.
+*/
+static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
+  int rc;             /* Success code from a subroutine */
+  Select *pPrior;     /* Another SELECT immediately to our left */
+  Vdbe *v;            /* Generate code to this VDBE */
+
+  /* Make sure there is no ORDER BY clause on prior SELECTs.  Only the 
+  ** last SELECT in the series may have an ORDER BY.
+  */
+  if( p==0 || p->pPrior==0 ) return 1;
+  pPrior = p->pPrior;
+  if( pPrior->pOrderBy ){
+    sqliteSetString(&pParse->zErrMsg,"ORDER BY clause should come after ",
+      selectOpName(p->op), " not before", 0);
+    pParse->nErr++;
+    return 1;
+  }
+
+  /* Make sure we have a valid query engine.  If not, create a new one.
+  */
+  v = sqliteGetVdbe(pParse);
+  if( v==0 ) return 1;
+
+  /* Create the destination temporary table if necessary
+  */
+  if( eDest==SRT_TempTable ){
+    sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
+    eDest = SRT_Table;
+  }
+
+  /* Generate code for the left and right SELECT statements.
+  */
+  switch( p->op ){
+    case TK_ALL: {
+      if( p->pOrderBy==0 ){
+        rc = sqliteSelect(pParse, pPrior, eDest, iParm, 0, 0, 0);
+        if( rc ) return rc;
+        p->pPrior = 0;
+        rc = sqliteSelect(pParse, p, eDest, iParm, 0, 0, 0);
+        p->pPrior = pPrior;
+        if( rc ) return rc;
+        break;
+      }
+      /* For UNION ALL ... ORDER BY fall through to the next case */
+    }
+    case TK_EXCEPT:
+    case TK_UNION: {
+      int unionTab;    /* Cursor number of the temporary table holding result */
+      int op;          /* One of the SRT_ operations to apply to self */
+      int priorOp;     /* The SRT_ operation to apply to prior selects */
+      ExprList *pOrderBy;  /* The ORDER BY clause for the right SELECT */
+
+      priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
+      if( eDest==priorOp && p->pOrderBy==0 ){
+        /* We can reuse a temporary table generated by a SELECT to our
+        ** right.
+        */
+        unionTab = iParm;
+      }else{
+        /* We will need to create our own temporary table to hold the
+        ** intermediate results.
+        */
+        unionTab = pParse->nTab++;
+        if( p->pOrderBy 
+        && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
+          return 1;
+        }
+        if( p->op!=TK_ALL ){
+          sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1);
+          sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1);
+        }else{
+          sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0);
+        }
+      }
+
+      /* Code the SELECT statements to our left
+      */
+      rc = sqliteSelect(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
+      if( rc ) return rc;
+
+      /* Code the current SELECT statement
+      */
+      switch( p->op ){
+         case TK_EXCEPT:  op = SRT_Except;   break;
+         case TK_UNION:   op = SRT_Union;    break;
+         case TK_ALL:     op = SRT_Table;    break;
+      }
+      p->pPrior = 0;
+      pOrderBy = p->pOrderBy;
+      p->pOrderBy = 0;
+      rc = sqliteSelect(pParse, p, op, unionTab, 0, 0, 0);
+      p->pPrior = pPrior;
+      p->pOrderBy = pOrderBy;
+      if( rc ) return rc;
+
+      /* Convert the data in the temporary table into whatever form
+      ** it is that we currently need.
+      */      
+      if( eDest!=priorOp || unionTab!=iParm ){
+        int iCont, iBreak, iStart;
+        assert( p->pEList );
+        if( eDest==SRT_Callback ){
+          generateColumnNames(pParse, p->base, 0, p->pEList);
+          generateColumnTypes(pParse, p->base, p->pSrc, p->pEList);
+        }
+        iBreak = sqliteVdbeMakeLabel(v);
+        iCont = sqliteVdbeMakeLabel(v);
+        sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak);
+        iStart = sqliteVdbeCurrentAddr(v);
+        multiSelectSortOrder(p, p->pOrderBy);
+        rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
+                             p->pOrderBy, -1, eDest, iParm, 
+                             iCont, iBreak);
+        if( rc ) return 1;
+        sqliteVdbeResolveLabel(v, iCont);
+        sqliteVdbeAddOp(v, OP_Next, unionTab, iStart);
+        sqliteVdbeResolveLabel(v, iBreak);
+        sqliteVdbeAddOp(v, OP_Close, unionTab, 0);
+        if( p->pOrderBy ){
+          generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
+        }
+      }
+      break;
+    }
+    case TK_INTERSECT: {
+      int tab1, tab2;
+      int iCont, iBreak, iStart;
+
+      /* INTERSECT is different from the others since it requires
+      ** two temporary tables.  Hence it has its own case.  Begin
+      ** by allocating the tables we will need.
+      */
+      tab1 = pParse->nTab++;
+      tab2 = pParse->nTab++;
+      if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
+        return 1;
+      }
+      sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1);
+      sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1);
+
+      /* Code the SELECTs to our left into temporary table "tab1".
+      */
+      rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
+      if( rc ) return rc;
+
+      /* Code the current SELECT into temporary table "tab2"
+      */
+      sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1);
+      sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1);
+      p->pPrior = 0;
+      rc = sqliteSelect(pParse, p, SRT_Union, tab2, 0, 0, 0);
+      p->pPrior = pPrior;
+      if( rc ) return rc;
+
+      /* Generate code to take the intersection of the two temporary
+      ** tables.
+      */
+      assert( p->pEList );
+      if( eDest==SRT_Callback ){
+        generateColumnNames(pParse, p->base, 0, p->pEList);
+        generateColumnTypes(pParse, p->base, p->pSrc, p->pEList);
+      }
+      iBreak = sqliteVdbeMakeLabel(v);
+      iCont = sqliteVdbeMakeLabel(v);
+      sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak);
+      iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0);
+      sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont);
+      multiSelectSortOrder(p, p->pOrderBy);
+      rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
+                             p->pOrderBy, -1, eDest, iParm, 
+                             iCont, iBreak);
+      if( rc ) return 1;
+      sqliteVdbeResolveLabel(v, iCont);
+      sqliteVdbeAddOp(v, OP_Next, tab1, iStart);
+      sqliteVdbeResolveLabel(v, iBreak);
+      sqliteVdbeAddOp(v, OP_Close, tab2, 0);
+      sqliteVdbeAddOp(v, OP_Close, tab1, 0);
+      if( p->pOrderBy ){
+        generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
+      }
+      break;
+    }
+  }
+  assert( p->pEList && pPrior->pEList );
+  if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
+    sqliteSetString(&pParse->zErrMsg, "SELECTs to the left and right of ",
+      selectOpName(p->op), " do not have the same number of result columns", 0);
+    pParse->nErr++;
+    return 1;
+  }
+
+  /* Issue a null callback if that is what the user wants.
+  */
+  if( eDest==SRT_Callback &&
+    (pParse->useCallback==0 || (pParse->db->flags & SQLITE_NullCallback)!=0)
+  ){
+    sqliteVdbeAddOp(v, OP_NullCallback, p->pEList->nExpr, 0);
+  }
+  return 0;
+}
+
+/*
+** Recursively scan through an expression tree.  For every reference
+** to a column in table number iFrom, change that reference to the
+** same column in table number iTo.
+*/
+static void changeTablesInList(ExprList*, int, int);  /* Forward Declaration */
+static void changeTables(Expr *pExpr, int iFrom, int iTo){
+  if( pExpr==0 ) return;
+  if( pExpr->op==TK_COLUMN && pExpr->iTable==iFrom ){
+    pExpr->iTable = iTo;
+  }else{
+    changeTables(pExpr->pLeft, iFrom, iTo);
+    changeTables(pExpr->pRight, iFrom, iTo);
+    changeTablesInList(pExpr->pList, iFrom, iTo);
+  }
+}
+static void changeTablesInList(ExprList *pList, int iFrom, int iTo){
+  if( pList ){
+    int i;
+    for(i=0; i<pList->nExpr; i++){
+      changeTables(pList->a[i].pExpr, iFrom, iTo);
+    }
+  }
+}
+
+/*
+** Scan through the expression pExpr.  Replace every reference to
+** a column in table number iTable with a copy of the corresponding
+** entry in pEList.  (But leave references to the ROWID column 
+** unchanged.)  When making a copy of an expression in pEList, change
+** references to columns in table iSub into references to table iTable.
+**
+** This routine is part of the flattening procedure.  A subquery
+** whose result set is defined by pEList appears as entry in the
+** FROM clause of a SELECT such that the VDBE cursor assigned to that
+** FORM clause entry is iTable.  This routine make the necessary 
+** changes to pExpr so that it refers directly to the source table
+** of the subquery rather the result set of the subquery.
+*/
+static void substExprList(ExprList*,int,ExprList*,int);  /* Forward Decl */
+static void substExpr(Expr *pExpr, int iTable, ExprList *pEList, int iSub){
+  if( pExpr==0 ) return;
+  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable && pExpr->iColumn>=0 ){
+    Expr *pNew;
+    assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
+    assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
+    pNew = pEList->a[pExpr->iColumn].pExpr;
+    assert( pNew!=0 );
+    pExpr->op = pNew->op;
+    pExpr->dataType = pNew->dataType;
+    assert( pExpr->pLeft==0 );
+    pExpr->pLeft = sqliteExprDup(pNew->pLeft);
+    assert( pExpr->pRight==0 );
+    pExpr->pRight = sqliteExprDup(pNew->pRight);
+    assert( pExpr->pList==0 );
+    pExpr->pList = sqliteExprListDup(pNew->pList);
+    pExpr->iTable = pNew->iTable;
+    pExpr->iColumn = pNew->iColumn;
+    pExpr->iAgg = pNew->iAgg;
+    sqliteTokenCopy(&pExpr->token, &pNew->token);
+    sqliteTokenCopy(&pExpr->span, &pNew->span);
+    if( iSub!=iTable ){
+      changeTables(pExpr, iSub, iTable);
+    }
+  }else{
+    substExpr(pExpr->pLeft, iTable, pEList, iSub);
+    substExpr(pExpr->pRight, iTable, pEList, iSub);
+    substExprList(pExpr->pList, iTable, pEList, iSub);
+  }
+}
+static void 
+substExprList(ExprList *pList, int iTable, ExprList *pEList, int iSub){
+  int i;
+  if( pList==0 ) return;
+  for(i=0; i<pList->nExpr; i++){
+    substExpr(pList->a[i].pExpr, iTable, pEList, iSub);
+  }
+}
+
+/*
+** This routine attempts to flatten subqueries in order to speed
+** execution.  It returns 1 if it makes changes and 0 if no flattening
+** occurs.
+**
+** To understand the concept of flattening, consider the following
+** query:
+**
+**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
+**
+** The default way of implementing this query is to execute the
+** subquery first and store the results in a temporary table, then
+** run the outer query on that temporary table.  This requires two
+** passes over the data.  Furthermore, because the temporary table
+** has no indices, the WHERE clause on the outer query cannot be
+** optimized.
+**
+** This routine attempts to rewrite queries such as the above into
+** a single flat select, like this:
+**
+**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
+**
+** The code generated for this simpification gives the same result
+** but only has to scan the data once.  And because indices might 
+** exist on the table t1, a complete scan of the data might be
+** avoided.
+**
+** Flattening is only attempted if all of the following are true:
+**
+**   (1)  The subquery and the outer query do not both use aggregates.
+**
+**   (2)  The subquery is not an aggregate or the outer query is not a join.
+**
+**   (3)  The subquery is not a join.
+**
+**   (4)  The subquery is not DISTINCT or the outer query is not a join.
+**
+**   (5)  The subquery is not DISTINCT or the outer query does not use
+**        aggregates.
+**
+**   (6)  The subquery does not use aggregates or the outer query is not
+**        DISTINCT.
+**
+**   (7)  The subquery has a FROM clause.
+**
+**   (8)  The subquery does not use LIMIT or the outer query is not a join.
+**
+**   (9)  The subquery does not use LIMIT or the outer query does not use
+**        aggregates.
+**
+**  (10)  The subquery does not use aggregates or the outer query does not
+**        use LIMIT.
+**
+**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
+**
+** In this routine, the "p" parameter is a pointer to the outer query.
+** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
+** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
+**
+** If flattening is not attempted, this routine is a no-op and return 0.
+** If flattening is attempted this routine returns 1.
+**
+** All of the expression analysis must occur on both the outer query and
+** the subquery before this routine runs.
+*/
+static int flattenSubquery(
+  Parse *pParse,       /* The parsing context */
+  Select *p,           /* The parent or outer SELECT statement */
+  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
+  int isAgg,           /* True if outer SELECT uses aggregate functions */
+  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
+){
+  Select *pSub;       /* The inner query or "subquery" */
+  SrcList *pSrc;      /* The FROM clause of the outer query */
+  SrcList *pSubSrc;   /* The FROM clause of the subquery */
+  ExprList *pList;    /* The result set of the outer query */
+  int i;
+  int iParent, iSub;
+  Expr *pWhere;
+
+  /* Check to see if flattening is permitted.  Return 0 if not.
+  */
+  if( p==0 ) return 0;
+  pSrc = p->pSrc;
+  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
+  pSub = pSrc->a[iFrom].pSelect;
+  assert( pSub!=0 );
+  if( isAgg && subqueryIsAgg ) return 0;
+  if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
+  pSubSrc = pSub->pSrc;
+  assert( pSubSrc );
+  if( pSubSrc->nSrc!=1 ) return 0;
+  if( (pSub->isDistinct || pSub->nLimit>=0) &&  (pSrc->nSrc>1 || isAgg) ){
+     return 0;
+  }
+  if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
+  if( p->pOrderBy && pSub->pOrderBy ) return 0;
+
+  /* If we reach this point, it means flattening is permitted for the
+  ** i-th entry of the FROM clause in the outer query.
+  */
+  iParent = p->base + iFrom;
+  iSub = pSub->base;
+  substExprList(p->pEList, iParent, pSub->pEList, iSub);
+  pList = p->pEList;
+  for(i=0; i<pList->nExpr; i++){
+    Expr *pExpr;
+    if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
+      pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
+    }
+  }
+  if( isAgg ){
+    substExprList(p->pGroupBy, iParent, pSub->pEList, iSub);
+    substExpr(p->pHaving, iParent, pSub->pEList, iSub);
+  }
+  if( pSub->pOrderBy ){
+    assert( p->pOrderBy==0 );
+    p->pOrderBy = pSub->pOrderBy;
+    pSub->pOrderBy = 0;
+    changeTablesInList(p->pOrderBy, iSub, iParent);
+  }else if( p->pOrderBy ){
+    substExprList(p->pOrderBy, iParent, pSub->pEList, iSub);
+  }
+  if( pSub->pWhere ){
+    pWhere = sqliteExprDup(pSub->pWhere);
+    if( iParent!=iSub ){
+      changeTables(pWhere, iSub, iParent);
+    }
+  }else{
+    pWhere = 0;
+  }
+  if( subqueryIsAgg ){
+    assert( p->pHaving==0 );
+    p->pHaving = p->pWhere;
+    p->pWhere = pWhere;
+    substExpr(p->pHaving, iParent, pSub->pEList, iSub);
+    if( pSub->pHaving ){
+      Expr *pHaving = sqliteExprDup(pSub->pHaving);
+      if( iParent!=iSub ){
+        changeTables(pHaving, iSub, iParent);
+      }
+      if( p->pHaving ){
+        p->pHaving = sqliteExpr(TK_AND, p->pHaving, pHaving, 0);
+      }else{
+        p->pHaving = pHaving;
+      }
+    }
+    assert( p->pGroupBy==0 );
+    p->pGroupBy = sqliteExprListDup(pSub->pGroupBy);
+    if( iParent!=iSub ){
+      changeTablesInList(p->pGroupBy, iSub, iParent);
+    }
+  }else if( p->pWhere==0 ){
+    p->pWhere = pWhere;
+  }else{
+    substExpr(p->pWhere, iParent, pSub->pEList, iSub);
+    if( pWhere ){
+      p->pWhere = sqliteExpr(TK_AND, p->pWhere, pWhere, 0);
+    }
+  }
+  p->isDistinct = p->isDistinct || pSub->isDistinct;
+
+  if( pSub->nLimit>=0 ){
+    if( p->nLimit<0 ){
+      p->nLimit = pSub->nLimit;
+    }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
+      p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
+    }
+  }
+  p->nOffset += pSub->nOffset;
+
+  /* If the subquery contains subqueries of its own, that were not
+  ** flattened, then code will have already been generated to put
+  ** the results of those sub-subqueries into VDBE cursors relative
+  ** to the subquery.  We must translate the cursor number into values
+  ** suitable for use by the outer query.
+  */
+  for(i=0; i<pSubSrc->nSrc; i++){
+    Vdbe *v;
+    if( pSubSrc->a[i].pSelect==0 ) continue;
+    v = sqliteGetVdbe(pParse);
+    sqliteVdbeAddOp(v, OP_RenameCursor, pSub->base+i, p->base+i);
+  }
+
+  if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
+    sqliteDeleteTable(0, pSrc->a[iFrom].pTab);
+  }
+  pSrc->a[iFrom].pTab = pSubSrc->a[0].pTab;
+  pSubSrc->a[0].pTab = 0;
+  assert( pSrc->a[iFrom].pSelect==pSub );
+  pSrc->a[iFrom].pSelect = pSubSrc->a[0].pSelect;
+  pSubSrc->a[0].pSelect = 0;
+  sqliteSelectDelete(pSub);
+  return 1;
+}
+
+/*
+** Analyze the SELECT statement passed in as an argument to see if it
+** is a simple min() or max() query.  If it is and this query can be
+** satisfied using a single seek to the beginning or end of an index,
+** then generate the code for this SELECT and return 1.  If this is not a 
+** simple min() or max() query, then return 0;
+**
+** A simply min() or max() query looks like this:
+**
+**    SELECT min(a) FROM table;
+**    SELECT max(a) FROM table;
+**
+** The query may have only a single table in its FROM argument.  There
+** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
+** be the min() or max() of a single column of the table.  The column
+** in the min() or max() function must be indexed.
+**
+** The parameters to this routine are the same as for sqliteSelect().
+** See the header comment on that routine for additional information.
+*/
+static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
+  Expr *pExpr;
+  int iCol;
+  Table *pTab;
+  Index *pIdx;
+  int base;
+  Vdbe *v;
+  int openOp;
+  int seekOp;
+  int cont;
+  ExprList eList;
+  struct ExprList_item eListItem;
+
+  /* Check to see if this query is a simple min() or max() query.  Return
+  ** zero if it is  not.
+  */
+  if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
+  if( p->pSrc->nSrc!=1 ) return 0;
+  if( p->pEList->nExpr!=1 ) return 0;
+  pExpr = p->pEList->a[0].pExpr;
+  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
+  if( pExpr->pList==0 || pExpr->pList->nExpr!=1 ) return 0;
+  if( pExpr->token.n!=3 ) return 0;
+  if( sqliteStrNICmp(pExpr->token.z,"min",3)==0 ){
+    seekOp = OP_Rewind;
+  }else if( sqliteStrNICmp(pExpr->token.z,"max",3)==0 ){
+    seekOp = OP_Last;
+  }else{
+    return 0;
+  }
+  pExpr = pExpr->pList->a[0].pExpr;
+  if( pExpr->op!=TK_COLUMN ) return 0;
+  iCol = pExpr->iColumn;
+  pTab = p->pSrc->a[0].pTab;
+
+  /* If we get to here, it means the query is of the correct form.
+  ** Check to make sure we have an index and make pIdx point to the
+  ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
+  ** key column, no index is necessary so set pIdx to NULL.  If no
+  ** usable index is found, return 0.
+  */
+  if( iCol<0 ){
+    pIdx = 0;
+  }else{
+    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+      assert( pIdx->nColumn>=1 );
+      if( pIdx->aiColumn[0]==iCol ) break;
+    }
+    if( pIdx==0 ) return 0;
+  }
+
+  /* Identify column names if we will be using the callback.  This
+  ** step is skipped if the output is going to a table or a memory cell.
+  */
+  v = sqliteGetVdbe(pParse);
+  if( v==0 ) return 0;
+  if( eDest==SRT_Callback ){
+    generateColumnNames(pParse, p->base, p->pSrc, p->pEList);
+    generateColumnTypes(pParse, p->base, p->pSrc, p->pEList);
+  }
+
+  /* Generating code to find the min or the max.  Basically all we have
+  ** to do is find the first or the last entry in the chosen index.  If
+  ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
+  ** or last entry in the main table.
+  */
+  if( !pParse->schemaVerified && (pParse->db->flags & SQLITE_InTrans)==0 ){
+    sqliteVdbeAddOp(v, OP_VerifyCookie, pParse->db->schema_cookie, 0);
+    pParse->schemaVerified = 1;
+  }
+  openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
+  base = p->base;
+  sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
+  sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
+  if( pIdx==0 ){
+    sqliteVdbeAddOp(v, seekOp, base, 0);
+  }else{
+    sqliteVdbeAddOp(v, openOp, base+1, pIdx->tnum);
+    sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
+    sqliteVdbeAddOp(v, seekOp, base+1, 0);
+    sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0);
+    sqliteVdbeAddOp(v, OP_Close, base+1, 0);
+    sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
+  }
+  eList.nExpr = 1;
+  memset(&eListItem, 0, sizeof(eListItem));
+  eList.a = &eListItem;
+  eList.a[0].pExpr = pExpr;
+  cont = sqliteVdbeMakeLabel(v);
+  selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont);
+  sqliteVdbeResolveLabel(v, cont);
+  sqliteVdbeAddOp(v, OP_Close, base, 0);
+  return 1;
+}
+
+/*
+** Generate code for the given SELECT statement.
+**
+** The results are distributed in various ways depending on the
+** value of eDest and iParm.
+**
+**     eDest Value       Result
+**     ------------    -------------------------------------------
+**     SRT_Callback    Invoke the callback for each row of the result.
+**
+**     SRT_Mem         Store first result in memory cell iParm
+**
+**     SRT_Set         Store results as keys of a table with cursor iParm
+**
+**     SRT_Union       Store results as a key in a temporary table iParm
+**
+**     SRT_Except      Remove results form the temporary table iParm.
+**
+**     SRT_Table       Store results in temporary table iParm
+**
+** The table above is incomplete.  Additional eDist value have be added
+** since this comment was written.  See the selectInnerLoop() function for
+** a complete listing of the allowed values of eDest and their meanings.
+**
+** This routine returns the number of errors.  If any errors are
+** encountered, then an appropriate error message is left in
+** pParse->zErrMsg.
+**
+** This routine does NOT free the Select structure passed in.  The
+** calling function needs to do that.
+**
+** The pParent, parentTab, and *pParentAgg fields are filled in if this
+** SELECT is a subquery.  This routine may try to combine this SELECT
+** with its parent to form a single flat query.  In so doing, it might
+** change the parent query from a non-aggregate to an aggregate query.
+** For that reason, the pParentAgg flag is passed as a pointer, so it
+** can be changed.
+**
+** Example 1:   The meaning of the pParent parameter.
+**
+**    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
+**    \                      \_______ subquery _______/        /
+**     \                                                      /
+**      \____________________ outer query ___________________/
+**
+** This routine is called for the outer query first.   For that call,
+** pParent will be NULL.  During the processing of the outer query, this 
+** routine is called recursively to handle the subquery.  For the recursive
+** call, pParent will point to the outer query.  Because the subquery is
+** the second element in a three-way join, the parentTab parameter will
+** be 1 (the 2nd value of a 0-indexed array.)
+*/
+int sqliteSelect(
+  Parse *pParse,         /* The parser context */
+  Select *p,             /* The SELECT statement being coded. */
+  int eDest,             /* How to dispose of the results */
+  int iParm,             /* A parameter used by the eDest disposal method */
+  Select *pParent,       /* Another SELECT for which this is a sub-query */
+  int parentTab,         /* Index in pParent->pSrc of this query */
+  int *pParentAgg        /* True if pParent uses aggregate functions */
+){
+  int i;
+  WhereInfo *pWInfo;
+  Vdbe *v;
+  int isAgg = 0;         /* True for select lists like "count(*)" */
+  ExprList *pEList;      /* List of columns to extract. */
+  SrcList *pTabList;     /* List of tables to select from */
+  Expr *pWhere;          /* The WHERE clause.  May be NULL */
+  ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
+  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
+  Expr *pHaving;         /* The HAVING clause.  May be NULL */
+  int isDistinct;        /* True if the DISTINCT keyword is present */
+  int distinct;          /* Table to use for the distinct set */
+  int base;              /* First cursor available for use */
+  int rc = 1;            /* Value to return from this function */
+
+  if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
+  if( sqliteAuthCheck(pParse, SQLITE_SELECT, 0, 0) ) return 1;
+
+  /* If there is are a sequence of queries, do the earlier ones first.
+  */
+  if( p->pPrior ){
+    return multiSelect(pParse, p, eDest, iParm);
+  }
+
+  /* Make local copies of the parameters for this query.
+  */
+  pTabList = p->pSrc;
+  pWhere = p->pWhere;
+  pOrderBy = p->pOrderBy;
+  pGroupBy = p->pGroupBy;
+  pHaving = p->pHaving;
+  isDistinct = p->isDistinct;
+
+  /* Allocate a block of VDBE cursors, one for each table in the FROM clause.
+  ** The WHERE processing requires that the cursors for the tables in the
+  ** FROM clause be consecutive.
+  */
+  base = p->base = pParse->nTab;
+  pParse->nTab += pTabList->nSrc;
+
+  /* 
+  ** Do not even attempt to generate any code if we have already seen
+  ** errors before this routine starts.
+  */
+  if( pParse->nErr>0 ) goto select_end;
+
+  /* Expand any "*" terms in the result set.  (For example the "*" in
+  ** "SELECT * FROM t1")  The fillInColumnlist() routine also does some
+  ** other housekeeping - see the header comment for details.
+  */
+  if( fillInColumnList(pParse, p) ){
+    goto select_end;
+  }
+  pWhere = p->pWhere;
+  pEList = p->pEList;
+  if( pEList==0 ) goto select_end;
+
+  /* If writing to memory or generating a set
+  ** only a single column may be output.
+  */
+  if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
+    sqliteSetString(&pParse->zErrMsg, "only a single result allowed for "
+       "a SELECT that is part of an expression", 0);
+    pParse->nErr++;
+    goto select_end;
+  }
+
+  /* ORDER BY is ignored for some destinations.
+  */
+  switch( eDest ){
+    case SRT_Union:
+    case SRT_Except:
+    case SRT_Discard:
+      pOrderBy = 0;
+      break;
+    default:
+      break;
+  }
+
+  /* At this point, we should have allocated all the cursors that we
+  ** need to handle subquerys and temporary tables.  
+  **
+  ** Resolve the column names and do a semantics check on all the expressions.
+  */
+  for(i=0; i<pEList->nExpr; i++){
+    if( sqliteExprResolveIds(pParse, base, pTabList, 0, pEList->a[i].pExpr) ){
+      goto select_end;
+    }
+    if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
+      goto select_end;
+    }
+  }
+  if( pWhere ){
+    if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pWhere) ){
+      goto select_end;
+    }
+    if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
+      goto select_end;
+    }
+    sqliteOracle8JoinFixup(base, pTabList, pWhere);
+  }
+  if( pHaving ){
+    if( pGroupBy==0 ){
+      sqliteSetString(&pParse->zErrMsg, "a GROUP BY clause is required "
+         "before HAVING", 0);
+      pParse->nErr++;
+      goto select_end;
+    }
+    if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pHaving) ){
+      goto select_end;
+    }
+    if( sqliteExprCheck(pParse, pHaving, 1, &isAgg) ){
+      goto select_end;
+    }
+  }
+  if( pOrderBy ){
+    for(i=0; i<pOrderBy->nExpr; i++){
+      int iCol;
+      Expr *pE = pOrderBy->a[i].pExpr;
+      if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
+        sqliteExprDelete(pE);
+        pE = pOrderBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
+      }
+      if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
+        goto select_end;
+      }
+      if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
+        goto select_end;
+      }
+      if( sqliteExprIsConstant(pE) ){
+        if( sqliteExprIsInteger(pE, &iCol)==0 ){
+          sqliteSetString(&pParse->zErrMsg, 
+               "ORDER BY terms must not be non-integer constants", 0);
+          pParse->nErr++;
+          goto select_end;
+        }else if( iCol<=0 || iCol>pEList->nExpr ){
+          char zBuf[2000];
+          sprintf(zBuf,"ORDER BY column number %d out of range - should be "
+             "between 1 and %d", iCol, pEList->nExpr);
+          sqliteSetString(&pParse->zErrMsg, zBuf, 0);
+          pParse->nErr++;
+          goto select_end;
+        }
+      }
+    }
+  }
+  if( pGroupBy ){
+    for(i=0; i<pGroupBy->nExpr; i++){
+      int iCol;
+      Expr *pE = pGroupBy->a[i].pExpr;
+      if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
+        sqliteExprDelete(pE);
+        pE = pGroupBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
+      }
+      if( sqliteExprResolveIds(pParse, base, pTabList, pEList, pE) ){
+        goto select_end;
+      }
+      if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
+        goto select_end;
+      }
+      if( sqliteExprIsConstant(pE) ){
+        if( sqliteExprIsInteger(pE, &iCol)==0 ){
+          sqliteSetString(&pParse->zErrMsg, 
+               "GROUP BY terms must not be non-integer constants", 0);
+          pParse->nErr++;
+          goto select_end;
+        }else if( iCol<=0 || iCol>pEList->nExpr ){
+          char zBuf[2000];
+          sprintf(zBuf,"GROUP BY column number %d out of range - should be "
+             "between 1 and %d", iCol, pEList->nExpr);
+          sqliteSetString(&pParse->zErrMsg, zBuf, 0);
+          pParse->nErr++;
+          goto select_end;
+        }
+      }
+    }
+  }
+
+  /* Check for the special case of a min() or max() function by itself
+  ** in the result set.
+  */
+  if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
+    rc = 0;
+    goto select_end;
+  }
+
+  /* Begin generating code.
+  */
+  v = sqliteGetVdbe(pParse);
+  if( v==0 ) goto select_end;
+
+  /* Identify column names if we will be using them in a callback.  This
+  ** step is skipped if the output is going to some other destination.
+  */
+  if( eDest==SRT_Callback ){
+    generateColumnNames(pParse, p->base, pTabList, pEList);
+  }
+
+  /* Set the limiter
+  */
+  if( p->nLimit<=0 ){
+    p->nLimit = -1;
+    p->nOffset = 0;
+  }else{
+    int iMem = pParse->nMem++;
+    sqliteVdbeAddOp(v, OP_Integer, -p->nLimit, 0);
+    sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
+    p->nLimit = iMem;
+    if( p->nOffset<=0 ){
+      p->nOffset = 0;
+    }else{
+      iMem = pParse->nMem++;
+      sqliteVdbeAddOp(v, OP_Integer, -p->nOffset, 0);
+      sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
+      p->nOffset = iMem;
+    }
+  }
+
+  /* Generate code for all sub-queries in the FROM clause
+  */
+  for(i=0; i<pTabList->nSrc; i++){
+    if( pTabList->a[i].pSelect==0 ) continue;
+    sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_TempTable, base+i,
+                 p, i, &isAgg);
+    pTabList = p->pSrc;
+    pWhere = p->pWhere;
+    if( eDest==SRT_Callback ){
+      pOrderBy = p->pOrderBy;
+    }
+    pGroupBy = p->pGroupBy;
+    pHaving = p->pHaving;
+    isDistinct = p->isDistinct;
+  }
+
+  /* Check to see if this is a subquery that can be "flattened" into its parent.
+  ** If flattening is a possiblity, do so and return immediately.  
+  */
+  if( pParent && pParentAgg &&
+      flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
+    if( isAgg ) *pParentAgg = 1;
+    return rc;
+  }
+
+  /* Identify column types if we will be using a callback.  This
+  ** step is skipped if the output is going to a destination other
+  ** than a callback.
+  */
+  if( eDest==SRT_Callback ){
+    generateColumnTypes(pParse, p->base, pTabList, pEList);
+  }
+
+  /* If the output is destined for a temporary table, open that table.
+  */
+  if( eDest==SRT_TempTable ){
+    sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
+  }
+
+  /* Do an analysis of aggregate expressions.
+  */
+  sqliteAggregateInfoReset(pParse);
+  if( isAgg || pGroupBy ){
+    assert( pParse->nAgg==0 );
+    isAgg = 1;
+    for(i=0; i<pEList->nExpr; i++){
+      if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
+        goto select_end;
+      }
+    }
+    if( pGroupBy ){
+      for(i=0; i<pGroupBy->nExpr; i++){
+        if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
+          goto select_end;
+        }
+      }
+    }
+    if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
+      goto select_end;
+    }
+    if( pOrderBy ){
+      for(i=0; i<pOrderBy->nExpr; i++){
+        if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
+          goto select_end;
+        }
+      }
+    }
+  }
+
+  /* Reset the aggregator
+  */
+  if( isAgg ){
+    sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
+    for(i=0; i<pParse->nAgg; i++){
+      FuncDef *pFunc;
+      if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
+        sqliteVdbeAddOp(v, OP_AggInit, 0, i);
+        sqliteVdbeChangeP3(v, -1, (char*)pFunc, P3_POINTER);
+      }
+    }
+    if( pGroupBy==0 ){
+      sqliteVdbeAddOp(v, OP_String, 0, 0);
+      sqliteVdbeAddOp(v, OP_AggFocus, 0, 0);
+    }
+  }
+
+  /* Initialize the memory cell to NULL
+  */
+  if( eDest==SRT_Mem ){
+    sqliteVdbeAddOp(v, OP_String, 0, 0);
+    sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
+  }
+
+  /* Open a temporary table to use for the distinct set.
+  */
+  if( isDistinct ){
+    distinct = pParse->nTab++;
+    sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1);
+  }else{
+    distinct = -1;
+  }
+
+  /* Begin the database scan
+  */
+  pWInfo = sqliteWhereBegin(pParse, p->base, pTabList, pWhere, 0, 
+                            pGroupBy ? 0 : &pOrderBy);
+  if( pWInfo==0 ) goto select_end;
+
+  /* Use the standard inner loop if we are not dealing with
+  ** aggregates
+  */
+  if( !isAgg ){
+    if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
+                    iParm, pWInfo->iContinue, pWInfo->iBreak) ){
+       goto select_end;
+    }
+  }
+
+  /* If we are dealing with aggregates, then do the special aggregate
+  ** processing.  
+  */
+  else{
+    if( pGroupBy ){
+      int lbl1;
+      for(i=0; i<pGroupBy->nExpr; i++){
+        sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
+      }
+      sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
+      if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pGroupBy);
+      lbl1 = sqliteVdbeMakeLabel(v);
+      sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1);
+      for(i=0; i<pParse->nAgg; i++){
+        if( pParse->aAgg[i].isAgg ) continue;
+        sqliteExprCode(pParse, pParse->aAgg[i].pExpr);
+        sqliteVdbeAddOp(v, OP_AggSet, 0, i);
+      }
+      sqliteVdbeResolveLabel(v, lbl1);
+    }
+    for(i=0; i<pParse->nAgg; i++){
+      Expr *pE;
+      int j;
+      if( !pParse->aAgg[i].isAgg ) continue;
+      pE = pParse->aAgg[i].pExpr;
+      assert( pE->op==TK_AGG_FUNCTION );
+      if( pE->pList ){
+        for(j=0; j<pE->pList->nExpr; j++){
+          sqliteExprCode(pParse, pE->pList->a[j].pExpr);
+        }
+      }
+      sqliteVdbeAddOp(v, OP_Integer, i, 0);
+      sqliteVdbeAddOp(v, OP_AggFunc, 0, pE->pList ? pE->pList->nExpr : 0);
+      assert( pParse->aAgg[i].pFunc!=0 );
+      assert( pParse->aAgg[i].pFunc->xStep!=0 );
+      sqliteVdbeChangeP3(v, -1, (char*)pParse->aAgg[i].pFunc, P3_POINTER);
+    }
+  }
+
+  /* End the database scan loop.
+  */
+  sqliteWhereEnd(pWInfo);
+
+  /* If we are processing aggregates, we need to set up a second loop
+  ** over all of the aggregate values and process them.
+  */
+  if( isAgg ){
+    int endagg = sqliteVdbeMakeLabel(v);
+    int startagg;
+    startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg);
+    pParse->useAgg = 1;
+    if( pHaving ){
+      sqliteExprIfFalse(pParse, pHaving, startagg, 1);
+    }
+    if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
+                    iParm, startagg, endagg) ){
+      goto select_end;
+    }
+    sqliteVdbeAddOp(v, OP_Goto, 0, startagg);
+    sqliteVdbeResolveLabel(v, endagg);
+    sqliteVdbeAddOp(v, OP_Noop, 0, 0);
+    pParse->useAgg = 0;
+  }
+
+  /* If there is an ORDER BY clause, then we need to sort the results
+  ** and send them to the callback one by one.
+  */
+  if( pOrderBy ){
+    generateSortTail(p, v, pEList->nExpr, eDest, iParm);
+  }
+
+
+  /* Issue a null callback if that is what the user wants.
+  */
+  if( eDest==SRT_Callback &&
+    (pParse->useCallback==0 || (pParse->db->flags & SQLITE_NullCallback)!=0)
+  ){
+    sqliteVdbeAddOp(v, OP_NullCallback, pEList->nExpr, 0);
+  }
+
+  /* The SELECT was successfully coded.   Set the return code to 0
+  ** to indicate no errors.
+  */
+  rc = 0;
+
+  /* Control jumps to here if an error is encountered above, or upon
+  ** successful coding of the SELECT.
+  */
+select_end:
+  sqliteAggregateInfoReset(pParse);
+  return rc;
+}
diff --git a/ext/sqlite/libsqlite/src/sqlite.h.in b/ext/sqlite/libsqlite/src/sqlite.h.in
new file mode 100644 (file)
index 0000000..b567a1a
--- /dev/null
@@ -0,0 +1,692 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This header file defines the interface that the SQLite library
+** presents to client programs.
+**
+** @(#) $Id$
+*/
+#ifndef _SQLITE_H_
+#define _SQLITE_H_
+#include <stdarg.h>     /* Needed for the definition of va_list */
+
+/*
+** Make sure we can call this stuff from C++.
+*/
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+** The version of the SQLite library.
+*/
+#define SQLITE_VERSION         "--VERS--"
+
+/*
+** The version string is also compiled into the library so that a program
+** can check to make sure that the lib*.a file and the *.h file are from
+** the same version.
+*/
+extern const char sqlite_version[];
+
+/*
+** The SQLITE_UTF8 macro is defined if the library expects to see
+** UTF-8 encoded data.  The SQLITE_ISO8859 macro is defined if the
+** iso8859 encoded should be used.
+*/
+#define SQLITE_--ENCODING-- 1
+
+/*
+** The following constant holds one of two strings, "UTF-8" or "iso8859",
+** depending on which character encoding the SQLite library expects to
+** see.  The character encoding makes a difference for the LIKE and GLOB
+** operators and for the LENGTH() and SUBSTR() functions.
+*/
+extern const char sqlite_encoding[];
+
+/*
+** Each open sqlite database is represented by an instance of the
+** following opaque structure.
+*/
+typedef struct sqlite sqlite;
+
+/*
+** A function to open a new sqlite database.  
+**
+** If the database does not exist and mode indicates write
+** permission, then a new database is created.  If the database
+** does not exist and mode does not indicate write permission,
+** then the open fails, an error message generated (if errmsg!=0)
+** and the function returns 0.
+** 
+** If mode does not indicates user write permission, then the 
+** database is opened read-only.
+**
+** The Truth:  As currently implemented, all databases are opened
+** for writing all the time.  Maybe someday we will provide the
+** ability to open a database readonly.  The mode parameters is
+** provided in anticipation of that enhancement.
+*/
+sqlite *sqlite_open(const char *filename, int mode, char **errmsg);
+
+/*
+** A function to close the database.
+**
+** Call this function with a pointer to a structure that was previously
+** returned from sqlite_open() and the corresponding database will by closed.
+*/
+void sqlite_close(sqlite *);
+
+/*
+** The type for a callback function.
+*/
+typedef int (*sqlite_callback)(void*,int,char**, char**);
+
+/*
+** A function to executes one or more statements of SQL.
+**
+** If one or more of the SQL statements are queries, then
+** the callback function specified by the 3rd parameter is
+** invoked once for each row of the query result.  This callback
+** should normally return 0.  If the callback returns a non-zero
+** value then the query is aborted, all subsequent SQL statements
+** are skipped and the sqlite_exec() function returns the SQLITE_ABORT.
+**
+** The 4th parameter is an arbitrary pointer that is passed
+** to the callback function as its first parameter.
+**
+** The 2nd parameter to the callback function is the number of
+** columns in the query result.  The 3rd parameter to the callback
+** is an array of strings holding the values for each column.
+** The 4th parameter to the callback is an array of strings holding
+** the names of each column.
+**
+** The callback function may be NULL, even for queries.  A NULL
+** callback is not an error.  It just means that no callback
+** will be invoked.
+**
+** If an error occurs while parsing or evaluating the SQL (but
+** not while executing the callback) then an appropriate error
+** message is written into memory obtained from malloc() and
+** *errmsg is made to point to that message.  The calling function
+** is responsible for freeing the memory that holds the error
+** message.   Use sqlite_freemem() for this.  If errmsg==NULL,
+** then no error message is ever written.
+**
+** The return value is is SQLITE_OK if there are no errors and
+** some other return code if there is an error.  The particular
+** return value depends on the type of error. 
+**
+** If the query could not be executed because a database file is
+** locked or busy, then this function returns SQLITE_BUSY.  (This
+** behavior can be modified somewhat using the sqlite_busy_handler()
+** and sqlite_busy_timeout() functions below.)
+*/
+int sqlite_exec(
+  sqlite*,                      /* An open database */
+  const char *sql,              /* SQL to be executed */
+  sqlite_callback,              /* Callback function */
+  void *,                       /* 1st argument to callback function */
+  char **errmsg                 /* Error msg written here */
+);
+
+/*
+** Return values for sqlite_exec() and sqlite_step()
+*/
+#define SQLITE_OK           0   /* Successful result */
+#define SQLITE_ERROR        1   /* SQL error or missing database */
+#define SQLITE_INTERNAL     2   /* An internal logic error in SQLite */
+#define SQLITE_PERM         3   /* Access permission denied */
+#define SQLITE_ABORT        4   /* Callback routine requested an abort */
+#define SQLITE_BUSY         5   /* The database file is locked */
+#define SQLITE_LOCKED       6   /* A table in the database is locked */
+#define SQLITE_NOMEM        7   /* A malloc() failed */
+#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
+#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite_interrupt() */
+#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
+#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
+#define SQLITE_NOTFOUND    12   /* (Internal Only) Table or record not found */
+#define SQLITE_FULL        13   /* Insertion failed because database is full */
+#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
+#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
+#define SQLITE_EMPTY       16   /* (Internal Only) Database table is empty */
+#define SQLITE_SCHEMA      17   /* The database schema changed */
+#define SQLITE_TOOBIG      18   /* Too much data for one row of a table */
+#define SQLITE_CONSTRAINT  19   /* Abort due to contraint violation */
+#define SQLITE_MISMATCH    20   /* Data type mismatch */
+#define SQLITE_MISUSE      21   /* Library used incorrectly */
+#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
+#define SQLITE_AUTH        23   /* Authorization denied */
+#define SQLITE_ROW         100  /* sqlite_step() has another row ready */
+#define SQLITE_DONE        101  /* sqlite_step() has finished executing */
+
+/*
+** Each entry in an SQLite table has a unique integer key.  (The key is
+** the value of the INTEGER PRIMARY KEY column if there is such a column,
+** otherwise the key is generated at random.  The unique key is always
+** available as the ROWID, OID, or _ROWID_ column.)  The following routine
+** returns the integer key of the most recent insert in the database.
+**
+** This function is similar to the mysql_insert_id() function from MySQL.
+*/
+int sqlite_last_insert_rowid(sqlite*);
+
+/*
+** This function returns the number of database rows that were changed
+** (or inserted or deleted) by the most recent called sqlite_exec().
+**
+** All changes are counted, even if they were later undone by a
+** ROLLBACK or ABORT.  Except, changes associated with creating and
+** dropping tables are not counted.
+**
+** If a callback invokes sqlite_exec() recursively, then the changes
+** in the inner, recursive call are counted together with the changes
+** in the outer call.
+**
+** SQLite implements the command "DELETE FROM table" without a WHERE clause
+** by dropping and recreating the table.  (This is much faster than going
+** through and deleting individual elements form the table.)  Because of
+** this optimization, the change count for "DELETE FROM table" will be
+** zero regardless of the number of elements that were originally in the
+** table. To get an accurate count of the number of rows deleted, use
+** "DELETE FROM table WHERE 1" instead.
+*/
+int sqlite_changes(sqlite*);
+
+/* If the parameter to this routine is one of the return value constants
+** defined above, then this routine returns a constant text string which
+** descripts (in English) the meaning of the return value.
+*/
+const char *sqlite_error_string(int);
+#define sqliteErrStr sqlite_error_string  /* Legacy. Do not use in new code. */
+
+/* This function causes any pending database operation to abort and
+** return at its earliest opportunity.  This routine is typically
+** called in response to a user action such as pressing "Cancel"
+** or Ctrl-C where the user wants a long query operation to halt
+** immediately.
+*/
+void sqlite_interrupt(sqlite*);
+
+
+/* This function returns true if the given input string comprises
+** one or more complete SQL statements.
+**
+** The algorithm is simple.  If the last token other than spaces
+** and comments is a semicolon, then return true.  otherwise return
+** false.
+*/
+int sqlite_complete(const char *sql);
+
+/*
+** This routine identifies a callback function that is invoked
+** whenever an attempt is made to open a database table that is
+** currently locked by another process or thread.  If the busy callback
+** is NULL, then sqlite_exec() returns SQLITE_BUSY immediately if
+** it finds a locked table.  If the busy callback is not NULL, then
+** sqlite_exec() invokes the callback with three arguments.  The
+** second argument is the name of the locked table and the third
+** argument is the number of times the table has been busy.  If the
+** busy callback returns 0, then sqlite_exec() immediately returns
+** SQLITE_BUSY.  If the callback returns non-zero, then sqlite_exec()
+** tries to open the table again and the cycle repeats.
+**
+** The default busy callback is NULL.
+**
+** Sqlite is re-entrant, so the busy handler may start a new query. 
+** (It is not clear why anyone would every want to do this, but it
+** is allowed, in theory.)  But the busy handler may not close the
+** database.  Closing the database from a busy handler will delete 
+** data structures out from under the executing query and will 
+** probably result in a coredump.
+*/
+void sqlite_busy_handler(sqlite*, int(*)(void*,const char*,int), void*);
+
+/*
+** This routine sets a busy handler that sleeps for a while when a
+** table is locked.  The handler will sleep multiple times until 
+** at least "ms" milleseconds of sleeping have been done.  After
+** "ms" milleseconds of sleeping, the handler returns 0 which
+** causes sqlite_exec() to return SQLITE_BUSY.
+**
+** Calling this routine with an argument less than or equal to zero
+** turns off all busy handlers.
+*/
+void sqlite_busy_timeout(sqlite*, int ms);
+
+/*
+** This next routine is really just a wrapper around sqlite_exec().
+** Instead of invoking a user-supplied callback for each row of the
+** result, this routine remembers each row of the result in memory
+** obtained from malloc(), then returns all of the result after the
+** query has finished. 
+**
+** As an example, suppose the query result where this table:
+**
+**        Name        | Age
+**        -----------------------
+**        Alice       | 43
+**        Bob         | 28
+**        Cindy       | 21
+**
+** If the 3rd argument were &azResult then after the function returns
+** azResult will contain the following data:
+**
+**        azResult[0] = "Name";
+**        azResult[1] = "Age";
+**        azResult[2] = "Alice";
+**        azResult[3] = "43";
+**        azResult[4] = "Bob";
+**        azResult[5] = "28";
+**        azResult[6] = "Cindy";
+**        azResult[7] = "21";
+**
+** Notice that there is an extra row of data containing the column
+** headers.  But the *nrow return value is still 3.  *ncolumn is
+** set to 2.  In general, the number of values inserted into azResult
+** will be ((*nrow) + 1)*(*ncolumn).
+**
+** After the calling function has finished using the result, it should 
+** pass the result data pointer to sqlite_free_table() in order to 
+** release the memory that was malloc-ed.  Because of the way the 
+** malloc() happens, the calling function must not try to call 
+** malloc() directly.  Only sqlite_free_table() is able to release 
+** the memory properly and safely.
+**
+** The return value of this routine is the same as from sqlite_exec().
+*/
+int sqlite_get_table(
+  sqlite*,               /* An open database */
+  const char *sql,       /* SQL to be executed */
+  char ***resultp,       /* Result written to a char *[]  that this points to */
+  int *nrow,             /* Number of result rows written here */
+  int *ncolumn,          /* Number of result columns written here */
+  char **errmsg          /* Error msg written here */
+);
+
+/*
+** Call this routine to free the memory that sqlite_get_table() allocated.
+*/
+void sqlite_free_table(char **result);
+
+/*
+** The following routines are wrappers around sqlite_exec() and
+** sqlite_get_table().  The only difference between the routines that
+** follow and the originals is that the second argument to the 
+** routines that follow is really a printf()-style format
+** string describing the SQL to be executed.  Arguments to the format
+** string appear at the end of the argument list.
+**
+** All of the usual printf formatting options apply.  In addition, there
+** is a "%q" option.  %q works like %s in that it substitutes a null-terminated
+** string from the argument list.  But %q also doubles every '\'' character.
+** %q is designed for use inside a string literal.  By doubling each '\''
+** character it escapes that character and allows it to be inserted into
+** the string.
+**
+** For example, so some string variable contains text as follows:
+**
+**      char *zText = "It's a happy day!";
+**
+** We can use this text in an SQL statement as follows:
+**
+**      sqlite_exec_printf(db, "INSERT INTO table VALUES('%q')",
+**          callback1, 0, 0, zText);
+**
+** Because the %q format string is used, the '\'' character in zText
+** is escaped and the SQL generated is as follows:
+**
+**      INSERT INTO table1 VALUES('It''s a happy day!')
+**
+** This is correct.  Had we used %s instead of %q, the generated SQL
+** would have looked like this:
+**
+**      INSERT INTO table1 VALUES('It's a happy day!');
+**
+** This second example is an SQL syntax error.  As a general rule you
+** should always use %q instead of %s when inserting text into a string 
+** literal.
+*/
+int sqlite_exec_printf(
+  sqlite*,                      /* An open database */
+  const char *sqlFormat,        /* printf-style format string for the SQL */
+  sqlite_callback,              /* Callback function */
+  void *,                       /* 1st argument to callback function */
+  char **errmsg,                /* Error msg written here */
+  ...                           /* Arguments to the format string. */
+);
+int sqlite_exec_vprintf(
+  sqlite*,                      /* An open database */
+  const char *sqlFormat,        /* printf-style format string for the SQL */
+  sqlite_callback,              /* Callback function */
+  void *,                       /* 1st argument to callback function */
+  char **errmsg,                /* Error msg written here */
+  va_list ap                    /* Arguments to the format string. */
+);
+int sqlite_get_table_printf(
+  sqlite*,               /* An open database */
+  const char *sqlFormat, /* printf-style format string for the SQL */
+  char ***resultp,       /* Result written to a char *[]  that this points to */
+  int *nrow,             /* Number of result rows written here */
+  int *ncolumn,          /* Number of result columns written here */
+  char **errmsg,         /* Error msg written here */
+  ...                    /* Arguments to the format string */
+);
+int sqlite_get_table_vprintf(
+  sqlite*,               /* An open database */
+  const char *sqlFormat, /* printf-style format string for the SQL */
+  char ***resultp,       /* Result written to a char *[]  that this points to */
+  int *nrow,             /* Number of result rows written here */
+  int *ncolumn,          /* Number of result columns written here */
+  char **errmsg,         /* Error msg written here */
+  va_list ap             /* Arguments to the format string */
+);
+char *sqlite_mprintf(const char*,...);
+
+/*
+** Windows systems should call this routine to free memory that
+** is returned in the in the errmsg parameter of sqlite_open() when
+** SQLite is a DLL.  For some reason, it does not work to call free()
+** directly.
+*/
+void sqlite_freemem(void *p);
+
+/*
+** Windows systems need functions to call to return the sqlite_version
+** and sqlite_encoding strings.
+*/
+const char *sqlite_libversion(void);
+const char *sqlite_libencoding(void);
+
+/*
+** A pointer to the following structure is used to communicate with
+** the implementations of user-defined functions.
+*/
+typedef struct sqlite_func sqlite_func;
+
+/*
+** Use the following routines to create new user-defined functions.  See
+** the documentation for details.
+*/
+int sqlite_create_function(
+  sqlite*,                  /* Database where the new function is registered */
+  const char *zName,        /* Name of the new function */
+  int nArg,                 /* Number of arguments.  -1 means any number */
+  void (*xFunc)(sqlite_func*,int,const char**),  /* C code to implement */
+  void *pUserData           /* Available via the sqlite_user_data() call */
+);
+int sqlite_create_aggregate(
+  sqlite*,                  /* Database where the new function is registered */
+  const char *zName,        /* Name of the function */
+  int nArg,                 /* Number of arguments */
+  void (*xStep)(sqlite_func*,int,const char**), /* Called for each row */
+  void (*xFinalize)(sqlite_func*),       /* Called once to get final result */
+  void *pUserData           /* Available via the sqlite_user_data() call */
+);
+
+/*
+** Use the following routine to define the datatype returned by a
+** user-defined function.  The second argument can be one of the
+** constants SQLITE_NUMERIC, SQLITE_TEXT, or SQLITE_ARGS or it
+** can be an integer greater than or equal to zero.  The datatype
+** will be numeric or text (the only two types supported) if the
+** argument is SQLITE_NUMERIC or SQLITE_TEXT.  If the argument is
+** SQLITE_ARGS, then the datatype is numeric if any argument to the
+** function is numeric and is text otherwise.  If the second argument
+** is an integer, then the datatype of the result is the same as the
+** parameter to the function that corresponds to that integer.
+*/
+int sqlite_function_type(
+  sqlite *db,               /* The database there the function is registered */
+  const char *zName,        /* Name of the function */
+  int datatype              /* The datatype for this function */
+);
+#define SQLITE_NUMERIC     (-1)
+#define SQLITE_TEXT        (-2)
+#define SQLITE_ARGS        (-3)
+
+/*
+** The user function implementations call one of the following four routines
+** in order to return their results.  The first parameter to each of these
+** routines is a copy of the first argument to xFunc() or xFinialize().
+** The second parameter to these routines is the result to be returned.
+** A NULL can be passed as the second parameter to sqlite_set_result_string()
+** in order to return a NULL result.
+**
+** The 3rd argument to _string and _error is the number of characters to
+** take from the string.  If this argument is negative, then all characters
+** up to and including the first '\000' are used.
+**
+** The sqlite_set_result_string() function allocates a buffer to hold the
+** result and returns a pointer to this buffer.  The calling routine
+** (that is, the implmentation of a user function) can alter the content
+** of this buffer if desired.
+*/
+char *sqlite_set_result_string(sqlite_func*,const char*,int);
+void sqlite_set_result_int(sqlite_func*,int);
+void sqlite_set_result_double(sqlite_func*,double);
+void sqlite_set_result_error(sqlite_func*,const char*,int);
+
+/*
+** The pUserData parameter to the sqlite_create_function() and
+** sqlite_create_aggregate() routines used to register user functions
+** is available to the implementation of the function using this
+** call.
+*/
+void *sqlite_user_data(sqlite_func*);
+
+/*
+** Aggregate functions use the following routine to allocate
+** a structure for storing their state.  The first time this routine
+** is called for a particular aggregate, a new structure of size nBytes
+** is allocated, zeroed, and returned.  On subsequent calls (for the
+** same aggregate instance) the same buffer is returned.  The implementation
+** of the aggregate can use the returned buffer to accumulate data.
+**
+** The buffer allocated is freed automatically be SQLite.
+*/
+void *sqlite_aggregate_context(sqlite_func*, int nBytes);
+
+/*
+** The next routine returns the number of calls to xStep for a particular
+** aggregate function instance.  The current call to xStep counts so this
+** routine always returns at least 1.
+*/
+int sqlite_aggregate_count(sqlite_func*);
+
+/*
+** This routine registers a callback with the SQLite library.  The
+** callback is invoked (at compile-time, not at run-time) for each
+** attempt to access a column of a table in the database.  The callback
+** returns SQLITE_OK if access is allowed, SQLITE_DENY if the entire
+** SQL statement should be aborted with an error and SQLITE_IGNORE
+** if the column should be treated as a NULL value.
+*/
+int sqlite_set_authorizer(
+  sqlite*,
+  int (*xAuth)(void*,int,const char*,const char*),
+  void *pUserData
+);
+
+/*
+** The second parameter to the access authorization function above will
+** be one of the values below.  These values signify what kind of operation
+** is to be authorized.  The 3rd and 4th parameters to the authorization
+** function will be parameters or NULL depending on which of the following
+** codes is used as the second parameter.
+**
+**                                          Arg-3           Arg-4
+*/
+#define SQLITE_COPY                  0   /* Table Name      File Name       */
+#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
+#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
+#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
+#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
+#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
+#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
+#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
+#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
+#define SQLITE_DELETE                9   /* Table Name      NULL            */
+#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
+#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
+#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
+#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
+#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
+#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
+#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
+#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
+#define SQLITE_INSERT               18   /* Table Name      NULL            */
+#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
+#define SQLITE_READ                 20   /* Table Name      Column Name     */
+#define SQLITE_SELECT               21   /* NULL            NULL            */
+#define SQLITE_TRANSACTION          22   /* NULL            NULL            */
+#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
+
+/*
+** The return value of the authorization function should be one of the
+** following constants:
+*/
+/* #define SQLITE_OK  0   // Allow access (This is actually defined above) */
+#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
+#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
+
+/*
+** Register a function that is called at every invocation of sqlite_exec()
+** or sqlite_compile().  This function can be used (for example) to generate
+** a log file of all SQL executed against a database.
+*/
+void *sqlite_trace(sqlite*, void(*xTrace)(void*,const char*), void*);
+
+/*** The Callback-Free API
+** 
+** The following routines implement a new way to access SQLite that does not
+** involve the use of callbacks.
+**
+** An sqlite_vm is an opaque object that represents a single SQL statement
+** that is ready to be executed.
+*/
+typedef struct sqlite_vm sqlite_vm;
+
+/*
+** To execute an SQLite query without the use of callbacks, you first have
+** to compile the SQL using this routine.  The 1st parameter "db" is a pointer
+** to an sqlite object obtained from sqlite_open().  The 2nd parameter
+** "zSql" is the text of the SQL to be compiled.   The remaining parameters
+** are all outputs.
+**
+** *pzTail is made to point to the first character past the end of the first
+** SQL statement in zSql.  This routine only compiles the first statement
+** in zSql, so *pzTail is left pointing to what remains uncompiled.
+**
+** *ppVm is left pointing to a "virtual machine" that can be used to execute
+** the compiled statement.  Or if there is an error, *ppVm may be set to NULL.
+** If the input text contained no SQL (if the input is and empty string or
+** a comment) then *ppVm is set to NULL.
+**
+** If any errors are detected during compilation, an error message is written
+** into space obtained from malloc() and *pzErrMsg is made to point to that
+** error message.  The calling routine is responsible for freeing the text
+** of this message when it has finished with it.  Use sqlite_freemem() to
+** free the message.  pzErrMsg may be NULL in which case no error message
+** will be generated.
+**
+** On success, SQLITE_OK is returned.  Otherwise and error code is returned.
+*/
+int sqlite_compile(
+  sqlite *db,                   /* The open database */
+  const char *zSql,             /* SQL statement to be compiled */
+  const char **pzTail,          /* OUT: uncompiled tail of zSql */
+  sqlite_vm **ppVm,             /* OUT: the virtual machine to execute zSql */
+  char **pzErrmsg               /* OUT: Error message. */
+);
+
+/*
+** After an SQL statement has been compiled, it is handed to this routine
+** to be executed.  This routine executes the statement as far as it can
+** go then returns.  The return value will be one of SQLITE_DONE,
+** SQLITE_ERROR, SQLITE_BUSY, SQLITE_ROW, or SQLITE_MISUSE.
+**
+** SQLITE_DONE means that the execute of the SQL statement is complete
+** an no errors have occurred.  sqlite_step() should not be called again
+** for the same virtual machine.  *pN is set to the number of columns in
+** the result set and *pazColName is set to an array of strings that
+** describe the column names and datatypes.  The name of the i-th column
+** is (*pazColName)[i] and the datatype of the i-th column is
+** (*pazColName)[i+*pN].  *pazValue is set to NULL.
+**
+** SQLITE_ERROR means that the virtual machine encountered a run-time
+** error.  sqlite_step() should not be called again for the same
+** virtual machine.  *pN is set to 0 and *pazColName and *pazValue are set
+** to NULL.  Use sqlite_finalize() to obtain the specific error code
+** and the error message text for the error.
+**
+** SQLITE_BUSY means that an attempt to open the database failed because
+** another thread or process is holding a lock.  The calling routine
+** can try again to open the database by calling sqlite_step() again.
+** The return code will only be SQLITE_BUSY if no busy handler is registered
+** using the sqlite_busy_handler() or sqlite_busy_timeout() routines.  If
+** a busy handler callback has been registered but returns 0, then this
+** routine will return SQLITE_ERROR and sqltie_finalize() will return
+** SQLITE_BUSY when it is called.
+**
+** SQLITE_ROW means that a single row of the result is now available.
+** The data is contained in *pazValue.  The value of the i-th column is
+** (*azValue)[i].  *pN and *pazColName are set as described in SQLITE_DONE.
+** Invoke sqlite_step() again to advance to the next row.
+**
+** SQLITE_MISUSE is returned if sqlite_step() is called incorrectly.
+** For example, if you call sqlite_step() after the virtual machine
+** has halted (after a prior call to sqlite_step() has returned SQLITE_DONE)
+** or if you call sqlite_step() with an incorrectly initialized virtual
+** machine or a virtual machine that has been deleted or that is associated
+** with an sqlite structure that has been closed.
+*/
+int sqlite_step(
+  sqlite_vm *pVm,              /* The virtual machine to execute */
+  int *pN,                     /* OUT: Number of columns in result */
+  const char ***pazValue,      /* OUT: Column data */
+  const char ***pazColName     /* OUT: Column names and datatypes */
+);
+
+/*
+** This routine is called to delete a virtual machine after it has finished
+** executing.  The return value is the result code.  SQLITE_OK is returned
+** if the statement executed successfully and some other value is returned if
+** there was any kind of error.  If an error occurred and pzErrMsg is not
+** NULL, then an error message is written into memory obtained from malloc()
+** and *pzErrMsg is made to point to that error message.  The calling routine
+** should use sqlite_freemem() to delete this message when it has finished
+** with it.
+**
+** This routine can be called at any point during the execution of the
+** virtual machine.  If the virtual machine has not completed execution
+** when this routine is called, that is like encountering an error or
+** an interrupt.  (See sqlite_interrupt().)  Incomplete updates may be
+** rolled back and transactions cancelled,  depending on the circumstances,
+** and the result code returned will be SQLITE_ABORT.
+*/
+int sqlite_finalize(sqlite_vm*, char **pzErrMsg);
+
+/*
+** Attempt to open the file named in the argument as the auxiliary database
+** file.  The auxiliary database file is used to store TEMP tables.  But
+** by using this API, it is possible to trick SQLite into opening two
+** separate databases and acting on them as if they were one.
+**
+****** THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE. ******
+*/
+int sqlite_open_aux_file(sqlite *db, const char *zName, char **pzErrMsg);
+
+#ifdef __cplusplus
+}  /* End of the 'extern "C"' block */
+#endif
+
+#endif /* _SQLITE_H_ */
diff --git a/ext/sqlite/libsqlite/src/sqliteInt.h b/ext/sqlite/libsqlite/src/sqliteInt.h
new file mode 100644 (file)
index 0000000..17fa478
--- /dev/null
@@ -0,0 +1,1051 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** Internal interface definitions for SQLite.
+**
+** @(#) $Id$
+*/
+#include "config.h"
+#include "sqlite.h"
+#include "hash.h"
+#include "vdbe.h"
+#include "parse.h"
+#include "btree.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+/*
+** The maximum number of in-memory pages to use for the main database
+** table and for temporary tables.
+*/
+#define MAX_PAGES   2000
+#define TEMP_PAGES   500
+
+/*
+** If the following macro is set to 1, then NULL values are considered
+** distinct for the SELECT DISTINCT statement and for UNION or EXCEPT
+** compound queries.  No other SQL database engine (among those tested) 
+** works this way except for OCELOT.  But the SQL92 spec implies that
+** this is how things should work.
+**
+** If the following macro is set to 0, then NULLs are indistinct for
+** SELECT DISTINCT and for UNION.
+*/
+#define NULL_ALWAYS_DISTINCT 0
+
+/*
+** If the following macro is set to 1, then NULL values are considered
+** distinct when determining whether or not two entries are the same
+** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
+** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
+** is the way things are suppose to work.
+**
+** If the following macro is set to 0, the NULLs are indistinct for
+** a UNIQUE index.  In this mode, you can only have a single NULL entry
+** for a column declared UNIQUE.  This is the way Informix and SQL Server
+** work.
+*/
+#define NULL_DISTINCT_FOR_UNIQUE 1
+
+/*
+** Integers of known sizes.  These typedefs might change for architectures
+** where the sizes very.  Preprocessor macros are available so that the
+** types can be conveniently redefined at compile-type.  Like this:
+**
+**         cc '-DUINTPTR_TYPE=long long int' ...
+*/
+#ifndef UINT32_TYPE
+# define UINT32_TYPE unsigned int
+#endif
+#ifndef UINT16_TYPE
+# define UINT16_TYPE unsigned short int
+#endif
+#ifndef UINT8_TYPE
+# define UINT8_TYPE unsigned char
+#endif
+#ifndef INTPTR_TYPE
+# if SQLITE_PTR_SZ==4
+#   define INTPTR_TYPE int
+# else
+#   define INTPTR_TYPE long long
+# endif
+#endif
+typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
+typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
+typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
+typedef INTPTR_TYPE ptr;           /* Big enough to hold a pointer */
+typedef unsigned INTPTR_TYPE uptr; /* Big enough to hold a pointer */
+
+/*
+** This macro casts a pointer to an integer.  Useful for doing
+** pointer arithmetic.
+*/
+#define Addr(X)  ((uptr)X)
+
+/*
+** The maximum number of bytes of data that can be put into a single
+** row of a single table.  The upper bound on this limit is 16777215
+** bytes (or 16MB-1).  We have arbitrarily set the limit to just 1MB
+** here because the overflow page chain is inefficient for really big
+** records and we want to discourage people from thinking that 
+** multi-megabyte records are OK.  If your needs are different, you can
+** change this define and recompile to increase or decrease the record
+** size.
+*/
+#define MAX_BYTES_PER_ROW  1048576
+
+/*
+** If memory allocation problems are found, recompile with
+**
+**      -DMEMORY_DEBUG=1
+**
+** to enable some sanity checking on malloc() and free().  To
+** check for memory leaks, recompile with
+**
+**      -DMEMORY_DEBUG=2
+**
+** and a line of text will be written to standard error for
+** each malloc() and free().  This output can be analyzed
+** by an AWK script to determine if there are any leaks.
+*/
+#ifdef MEMORY_DEBUG
+# define sqliteMalloc(X)    sqliteMalloc_(X,1,__FILE__,__LINE__)
+# define sqliteMallocRaw(X) sqliteMalloc_(X,0,__FILE__,__LINE__)
+# define sqliteFree(X)      sqliteFree_(X,__FILE__,__LINE__)
+# define sqliteRealloc(X,Y) sqliteRealloc_(X,Y,__FILE__,__LINE__)
+# define sqliteStrDup(X)    sqliteStrDup_(X,__FILE__,__LINE__)
+# define sqliteStrNDup(X,Y) sqliteStrNDup_(X,Y,__FILE__,__LINE__)
+  void sqliteStrRealloc(char**);
+#else
+# define sqliteStrRealloc(X)
+#endif
+
+/*
+** This variable gets set if malloc() ever fails.  After it gets set,
+** the SQLite library shuts down permanently.
+*/
+extern int sqlite_malloc_failed;
+
+/*
+** The following global variables are used for testing and debugging
+** only.  They only work if MEMORY_DEBUG is defined.
+*/
+#ifdef MEMORY_DEBUG
+extern int sqlite_nMalloc;       /* Number of sqliteMalloc() calls */
+extern int sqlite_nFree;         /* Number of sqliteFree() calls */
+extern int sqlite_iMallocFail;   /* Fail sqliteMalloc() after this many calls */
+#endif
+
+/*
+** Name of the master database table.  The master database table
+** is a special table that holds the names and attributes of all
+** user tables and indices.
+*/
+#define MASTER_NAME       "sqlite_master"
+#define TEMP_MASTER_NAME  "sqlite_temp_master"
+
+/*
+** The name of the schema table.
+*/
+#define SCHEMA_TABLE(x)  (x?TEMP_MASTER_NAME:MASTER_NAME)
+
+/*
+** A convenience macro that returns the number of elements in
+** an array.
+*/
+#define ArraySize(X)    (sizeof(X)/sizeof(X[0]))
+
+/*
+** Forward references to structures
+*/
+typedef struct Column Column;
+typedef struct Table Table;
+typedef struct Index Index;
+typedef struct Instruction Instruction;
+typedef struct Expr Expr;
+typedef struct ExprList ExprList;
+typedef struct Parse Parse;
+typedef struct Token Token;
+typedef struct IdList IdList;
+typedef struct SrcList SrcList;
+typedef struct WhereInfo WhereInfo;
+typedef struct WhereLevel WhereLevel;
+typedef struct Select Select;
+typedef struct AggExpr AggExpr;
+typedef struct FuncDef FuncDef;
+typedef struct Trigger Trigger;
+typedef struct TriggerStep TriggerStep;
+typedef struct TriggerStack TriggerStack;
+typedef struct FKey FKey;
+
+/*
+** Each database is an instance of the following structure.
+**
+** The sqlite.file_format is initialized by the database file
+** and helps determines how the data in the database file is
+** represented.  This field allows newer versions of the library
+** to read and write older databases.  The various file formats
+** are as follows:
+**
+**     file_format==1    Version 2.1.0.
+**     file_format==2    Version 2.2.0. Add support for INTEGER PRIMARY KEY.
+**     file_format==3    Version 2.6.0. Fix empty-string index bug.
+**     file_format==4    Version 2.7.0. Add support for separate numeric and
+**                       text datatypes.
+*/
+struct sqlite {
+  Btree *pBe;                   /* The B*Tree backend */
+  Btree *pBeTemp;               /* Backend for session temporary tables */
+  int flags;                    /* Miscellanous flags. See below */
+  u8 file_format;               /* What file format version is this database? */
+  u8 safety_level;              /* How aggressive at synching data to disk */
+  u8 want_to_close;             /* Close after all VDBEs are deallocated */
+  int schema_cookie;            /* Magic number that changes with the schema */
+  int next_cookie;              /* Value of schema_cookie after commit */
+  int cache_size;               /* Number of pages to use in the cache */
+  int nTable;                   /* Number of tables in the database */
+  void *pBusyArg;               /* 1st Argument to the busy callback */
+  int (*xBusyCallback)(void *,const char*,int);  /* The busy callback */
+  Hash tblHash;                 /* All tables indexed by name */
+  Hash idxHash;                 /* All (named) indices indexed by name */
+  Hash trigHash;                /* All triggers indexed by name */
+  Hash aFunc;                   /* All functions that can be in SQL exprs */
+  Hash aFKey;                   /* Foreign keys indexed by to-table */
+  int lastRowid;                /* ROWID of most recent insert */
+  int priorNewRowid;            /* Last randomly generated ROWID */
+  int onError;                  /* Default conflict algorithm */
+  int magic;                    /* Magic number for detect library misuse */
+  int nChange;                  /* Number of rows changed */
+  struct Vdbe *pVdbe;           /* List of active virtual machines */
+#ifndef SQLITE_OMIT_TRACE
+  void (*xTrace)(void*,const char*);     /* Trace function */
+  void *pTraceArg;                       /* Argument to the trace function */
+#endif
+#ifndef SQLITE_OMIT_AUTHORIZATION
+  int (*xAuth)(void*,int,const char*,const char*); /* Access Auth function */
+  void *pAuthArg;               /* 1st argument to the access auth function */
+#endif
+};
+
+/*
+** Possible values for the sqlite.flags.
+*/
+#define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
+#define SQLITE_Initialized    0x00000002  /* True after initialization */
+#define SQLITE_Interrupt      0x00000004  /* Cancel current operation */
+#define SQLITE_InTrans        0x00000008  /* True if in a transaction */
+#define SQLITE_InternChanges  0x00000010  /* Uncommitted Hash table changes */
+#define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
+#define SQLITE_CountRows      0x00000040  /* Count rows changed by INSERT, */
+                                          /*   DELETE, or UPDATE and return */
+                                          /*   the count using a callback. */
+#define SQLITE_NullCallback   0x00000080  /* Invoke the callback once if the */
+                                          /*   result set is empty */
+#define SQLITE_ResultDetails  0x00000100  /* Details added to result set */
+#define SQLITE_UnresetViews   0x00000200  /* True if one or more views have */
+                                          /*   defined column names */
+#define SQLITE_ReportTypes    0x00000400  /* Include information on datatypes */
+                                          /*   in 4th argument of callback */
+
+/*
+** Possible values for the sqlite.magic field.
+** The numbers are obtained at random and have no special meaning, other
+** than being distinct from one another.
+*/
+#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
+#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
+#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
+#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
+
+/*
+** Each SQL function is defined by an instance of the following
+** structure.  A pointer to this structure is stored in the sqlite.aFunc
+** hash table.  When multiple functions have the same name, the hash table
+** points to a linked list of these structures.
+*/
+struct FuncDef {
+  void (*xFunc)(sqlite_func*,int,const char**);  /* Regular function */
+  void (*xStep)(sqlite_func*,int,const char**);  /* Aggregate function step */
+  void (*xFinalize)(sqlite_func*);           /* Aggregate function finializer */
+  int nArg;                                  /* Number of arguments */
+  int dataType;                              /* Datatype of the result */
+  void *pUserData;                           /* User data parameter */
+  FuncDef *pNext;                            /* Next function with same name */
+};
+
+/*
+** information about each column of an SQL table is held in an instance
+** of this structure.
+*/
+struct Column {
+  char *zName;     /* Name of this column */
+  char *zDflt;     /* Default value of this column */
+  char *zType;     /* Data type for this column */
+  u8 notNull;      /* True if there is a NOT NULL constraint */
+  u8 isPrimKey;    /* True if this column is an INTEGER PRIMARY KEY */
+  u8 sortOrder;    /* Some combination of SQLITE_SO_... values */
+};
+
+/*
+** The allowed sort orders.
+**
+** The TEXT and NUM values use bits that do not overlap with DESC and ASC.
+** That way the two can be combined into a single number.
+*/
+#define SQLITE_SO_UNK       0  /* Use the default collating type.  (SCT_NUM) */
+#define SQLITE_SO_TEXT      2  /* Sort using memcmp() */
+#define SQLITE_SO_NUM       4  /* Sort using sqliteCompare() */
+#define SQLITE_SO_TYPEMASK  6  /* Mask to extract the collating sequence */
+#define SQLITE_SO_ASC       0  /* Sort in ascending order */
+#define SQLITE_SO_DESC      1  /* Sort in descending order */
+#define SQLITE_SO_DIRMASK   1  /* Mask to extract the sort direction */
+
+/*
+** Each SQL table is represented in memory by an instance of the
+** following structure.
+**
+** Expr.zName is the name of the table.  The case of the original
+** CREATE TABLE statement is stored, but case is not significant for
+** comparisons.
+**
+** Expr.nCol is the number of columns in this table.  Expr.aCol is a
+** pointer to an array of Column structures, one for each column.
+**
+** If the table has an INTEGER PRIMARY KEY, then Expr.iPKey is the index of
+** the column that is that key.   Otherwise Expr.iPKey is negative.  Note
+** that the datatype of the PRIMARY KEY must be INTEGER for this field to
+** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
+** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
+** is generated for each row of the table.  Expr.hasPrimKey is true if
+** the table has any PRIMARY KEY, INTEGER or otherwise.
+**
+** Expr.tnum is the page number for the root BTree page of the table in the
+** database file.  If Expr.isTemp is true, then this page occurs in the
+** auxiliary database file, not the main database file.  If Expr.isTransient
+** is true, then the table is stored in a file that is automatically deleted
+** when the VDBE cursor to the table is closed.  In this case Expr.tnum 
+** refers VDBE cursor number that holds the table open, not to the root
+** page number.  Transient tables are used to hold the results of a
+** sub-query that appears instead of a real table name in the FROM clause 
+** of a SELECT statement.
+*/
+struct Table {
+  char *zName;     /* Name of the table */
+  int nCol;        /* Number of columns in this table */
+  Column *aCol;    /* Information about each column */
+  int iPKey;       /* If not less then 0, use aCol[iPKey] as the primary key */
+  Index *pIndex;   /* List of SQL indexes on this table. */
+  int tnum;        /* Root BTree node for this table (see note above) */
+  Select *pSelect; /* NULL for tables.  Points to definition if a view. */
+  u8 readOnly;     /* True if this table should not be written by the user */
+  u8 isTemp;       /* True if stored in db->pBeTemp instead of db->pBe */
+  u8 isTransient;  /* True if automatically deleted when VDBE finishes */
+  u8 hasPrimKey;   /* True if there exists a primary key */
+  u8 keyConf;      /* What to do in case of uniqueness conflict on iPKey */
+  Trigger *pTrigger; /* List of SQL triggers on this table */
+  FKey *pFKey;       /* Linked list of all foreign keys in this table */
+};
+
+/*
+** Each foreign key constraint is an instance of the following structure.
+**
+** A foreign key is associated with two tables.  The "from" table is
+** the table that contains the REFERENCES clause that creates the foreign
+** key.  The "to" table is the table that is named in the REFERENCES clause.
+** Consider this example:
+**
+**     CREATE TABLE ex1(
+**       a INTEGER PRIMARY KEY,
+**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
+**     );
+**
+** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
+**
+** Each REFERENCES clause generates an instance of the following structure
+** which is attached to the from-table.  The to-table need not exist when
+** the from-table is created.  The existance of the to-table is not checked
+** until an attempt is made to insert data into the from-table.
+**
+** The sqlite.aFKey hash table stores pointers to to this structure
+** given the name of a to-table.  For each to-table, all foreign keys
+** associated with that table are on a linked list using the FKey.pNextTo
+** field.
+*/
+struct FKey {
+  Table *pFrom;     /* The table that constains the REFERENCES clause */
+  FKey *pNextFrom;  /* Next foreign key in pFrom */
+  char *zTo;        /* Name of table that the key points to */
+  FKey *pNextTo;    /* Next foreign key that points to zTo */
+  int nCol;         /* Number of columns in this key */
+  struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
+    int iFrom;         /* Index of column in pFrom */
+    char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
+  } *aCol;          /* One entry for each of nCol column s */
+  u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
+  u8 updateConf;    /* How to resolve conflicts that occur on UPDATE */
+  u8 deleteConf;    /* How to resolve conflicts that occur on DELETE */
+  u8 insertConf;    /* How to resolve conflicts that occur on INSERT */
+};
+
+/*
+** SQLite supports many different ways to resolve a contraint
+** error.  ROLLBACK processing means that a constraint violation
+** causes the operation in process to fail and for the current transaction
+** to be rolled back.  ABORT processing means the operation in process
+** fails and any prior changes from that one operation are backed out,
+** but the transaction is not rolled back.  FAIL processing means that
+** the operation in progress stops and returns an error code.  But prior
+** changes due to the same operation are not backed out and no rollback
+** occurs.  IGNORE means that the particular row that caused the constraint
+** error is not inserted or updated.  Processing continues and no error
+** is returned.  REPLACE means that preexisting database rows that caused
+** a UNIQUE constraint violation are removed so that the new insert or
+** update can proceed.  Processing continues and no error is reported.
+**
+** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
+** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
+** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
+** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
+** referenced table row is propagated into the row that holds the
+** foreign key.
+** 
+** The following symbolic values are used to record which type
+** of action to take.
+*/
+#define OE_None     0   /* There is no constraint to check */
+#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
+#define OE_Abort    2   /* Back out changes but do no rollback transaction */
+#define OE_Fail     3   /* Stop the operation but leave all prior changes */
+#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
+#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
+
+#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
+#define OE_SetNull  7   /* Set the foreign key value to NULL */
+#define OE_SetDflt  8   /* Set the foreign key value to its default */
+#define OE_Cascade  9   /* Cascade the changes */
+
+#define OE_Default  99  /* Do whatever the default action is */
+
+/*
+** Each SQL index is represented in memory by an
+** instance of the following structure.
+**
+** The columns of the table that are to be indexed are described
+** by the aiColumn[] field of this structure.  For example, suppose
+** we have the following table and index:
+**
+**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
+**     CREATE INDEX Ex2 ON Ex1(c3,c1);
+**
+** In the Table structure describing Ex1, nCol==3 because there are
+** three columns in the table.  In the Index structure describing
+** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
+** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
+** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
+** The second column to be indexed (c1) has an index of 0 in
+** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
+*/
+struct Index {
+  char *zName;     /* Name of this index */
+  int nColumn;     /* Number of columns in the table used by this index */
+  int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
+  Table *pTable;   /* The SQL table being indexed */
+  int tnum;        /* Page containing root of this index in database file */
+  u8 isUnique;     /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
+  u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
+  u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
+  Index *pNext;    /* The next index associated with the same table */
+};
+
+/*
+** Each token coming out of the lexer is an instance of
+** this structure.  Tokens are also used as part of an expression.
+*/
+struct Token {
+  const char *z;      /* Text of the token.  Not NULL-terminated! */
+  unsigned dyn  : 1;  /* True for malloced memory, false for static */
+  unsigned n    : 31; /* Number of characters in this token */
+};
+
+/*
+** Each node of an expression in the parse tree is an instance
+** of this structure.
+**
+** Expr.op is the opcode.  The integer parser token codes are reused
+** as opcodes here.  For example, the parser defines TK_GE to be an integer
+** code representing the ">=" operator.  This same integer code is reused
+** to represent the greater-than-or-equal-to operator in the expression
+** tree.
+**
+** Expr.pRight and Expr.pLeft are subexpressions.  Expr.pList is a list
+** of argument if the expression is a function.
+**
+** Expr.token is the operator token for this node.  For some expressions
+** that have subexpressions, Expr.token can be the complete text that gave
+** rise to the Expr.  In the latter case, the token is marked as being
+** a compound token.
+**
+** An expression of the form ID or ID.ID refers to a column in a table.
+** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
+** the integer cursor number of a VDBE cursor pointing to that table and
+** Expr.iColumn is the column number for the specific column.  If the
+** expression is used as a result in an aggregate SELECT, then the
+** value is also stored in the Expr.iAgg column in the aggregate so that
+** it can be accessed after all aggregates are computed.
+**
+** If the expression is a function, the Expr.iTable is an integer code
+** representing which function.
+**
+** The Expr.pSelect field points to a SELECT statement.  The SELECT might
+** be the right operand of an IN operator.  Or, if a scalar SELECT appears
+** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
+** operand.
+*/
+struct Expr {
+  u8 op;                 /* Operation performed by this node */
+  u8 dataType;           /* Either SQLITE_SO_TEXT or SQLITE_SO_NUM */
+  u16 flags;             /* Various flags.  See below */
+  Expr *pLeft, *pRight;  /* Left and right subnodes */
+  ExprList *pList;       /* A list of expressions used as function arguments
+                         ** or in "<expr> IN (<expr-list)" */
+  Token token;           /* An operand token */
+  Token span;            /* Complete text of the expression */
+  int iTable, iColumn;   /* When op==TK_COLUMN, then this expr node means the
+                         ** iColumn-th field of the iTable-th table. */
+  int iAgg;              /* When op==TK_COLUMN and pParse->useAgg==TRUE, pull
+                         ** result from the iAgg-th element of the aggregator */
+  Select *pSelect;       /* When the expression is a sub-select.  Also the
+                         ** right side of "<expr> IN (<select>)" */
+};
+
+/*
+** The following are the meanings of bits in the Expr.flags field.
+*/
+#define EP_FromJoin     0x0001  /* Originated in ON or USING clause of a join */
+#define EP_Oracle8Join  0x0002  /* Carries the Oracle8 "(+)" join operator */
+
+/*
+** These macros can be used to test, set, or clear bits in the 
+** Expr.flags field.
+*/
+#define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
+#define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
+#define ExprSetProperty(E,P)     (E)->flags|=(P)
+#define ExprClearProperty(E,P)   (E)->flags&=~(P)
+
+/*
+** A list of expressions.  Each expression may optionally have a
+** name.  An expr/name combination can be used in several ways, such
+** as the list of "expr AS ID" fields following a "SELECT" or in the
+** list of "ID = expr" items in an UPDATE.  A list of expressions can
+** also be used as the argument to a function, in which case the a.zName
+** field is not used.
+*/
+struct ExprList {
+  int nExpr;             /* Number of expressions on the list */
+  struct ExprList_item {
+    Expr *pExpr;           /* The list of expressions */
+    char *zName;           /* Token associated with this expression */
+    u8 sortOrder;          /* 1 for DESC or 0 for ASC */
+    u8 isAgg;              /* True if this is an aggregate like count(*) */
+    u8 done;               /* A flag to indicate when processing is finished */
+  } *a;                  /* One entry for each expression */
+};
+
+/*
+** An instance of this structure can hold a simple list of identifiers,
+** such as the list "a,b,c" in the following statements:
+**
+**      INSERT INTO t(a,b,c) VALUES ...;
+**      CREATE INDEX idx ON t(a,b,c);
+**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
+**
+** The IdList.a.idx field is used when the IdList represents the list of
+** column names after a table name in an INSERT statement.  In the statement
+**
+**     INSERT INTO t(a,b,c) ...
+**
+** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
+*/
+struct IdList {
+  int nId;         /* Number of identifiers on the list */
+  struct IdList_item {
+    char *zName;      /* Name of the identifier */
+    int idx;          /* Index in some Table.aCol[] of a column named zName */
+  } *a;
+};
+
+/*
+** The following structure describes the FROM clause of a SELECT statement.
+** Each table or subquery in the FROM clause is a separate element of
+** the SrcList.a[] array.
+*/
+struct SrcList {
+  int nSrc;        /* Number of tables or subqueries in the FROM clause */
+  struct SrcList_item {
+    char *zName;      /* Name of the table */
+    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
+    Table *pTab;      /* An SQL table corresponding to zName */
+    Select *pSelect;  /* A SELECT statement used in place of a table name */
+    int jointype;     /* Type of join between this table and the next */
+    Expr *pOn;        /* The ON clause of a join */
+    IdList *pUsing;   /* The USING clause of a join */
+  } *a;            /* One entry for each identifier on the list */
+};
+
+/*
+** Permitted values of the SrcList.a.jointype field
+*/
+#define JT_INNER     0x0001    /* Any kind of inner or cross join */
+#define JT_NATURAL   0x0002    /* True for a "natural" join */
+#define JT_LEFT      0x0004    /* Left outer join */
+#define JT_RIGHT     0x0008    /* Right outer join */
+#define JT_OUTER     0x0010    /* The "OUTER" keyword is present */
+#define JT_ERROR     0x0020    /* unknown or unsupported join type */
+
+/*
+** For each nested loop in a WHERE clause implementation, the WhereInfo
+** structure contains a single instance of this structure.  This structure
+** is intended to be private the the where.c module and should not be
+** access or modified by other modules.
+*/
+struct WhereLevel {
+  int iMem;            /* Memory cell used by this level */
+  Index *pIdx;         /* Index used */
+  int iCur;            /* Cursor number used for this index */
+  int score;           /* How well this indexed scored */
+  int brk;             /* Jump here to break out of the loop */
+  int cont;            /* Jump here to continue with the next loop cycle */
+  int op, p1, p2;      /* Opcode used to terminate the loop */
+  int iLeftJoin;       /* Memory cell used to implement LEFT OUTER JOIN */
+  int top;             /* First instruction of interior of the loop */
+  int inOp, inP1, inP2;/* Opcode used to implement an IN operator */
+  int bRev;            /* Do the scan in the reverse direction */
+};
+
+/*
+** The WHERE clause processing routine has two halves.  The
+** first part does the start of the WHERE loop and the second
+** half does the tail of the WHERE loop.  An instance of
+** this structure is returned by the first half and passed
+** into the second half to give some continuity.
+*/
+struct WhereInfo {
+  Parse *pParse;
+  SrcList *pTabList;   /* List of tables in the join */
+  int iContinue;       /* Jump here to continue with next record */
+  int iBreak;          /* Jump here to break out of the loop */
+  int base;            /* Index of first Open opcode */
+  int nLevel;          /* Number of nested loop */
+  int savedNTab;       /* Value of pParse->nTab before WhereBegin() */
+  int peakNTab;        /* Value of pParse->nTab after WhereBegin() */
+  WhereLevel a[1];     /* Information about each nest loop in the WHERE */
+};
+
+/*
+** An instance of the following structure contains all information
+** needed to generate code for a single SELECT statement.
+**
+** The zSelect field is used when the Select structure must be persistent.
+** Normally, the expression tree points to tokens in the original input
+** string that encodes the select.  But if the Select structure must live
+** longer than its input string (for example when it is used to describe
+** a VIEW) we have to make a copy of the input string so that the nodes
+** of the expression tree will have something to point to.  zSelect is used
+** to hold that copy.
+**
+** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
+** If there is a LIMIT clause, the parser sets nLimit to the value of the
+** limit and nOffset to the value of the offset (or 0 if there is not
+** offset).  But later on, nLimit and nOffset become the memory locations
+** in the VDBE that record the limit and offset counters.
+*/
+struct Select {
+  int isDistinct;        /* True if the DISTINCT keyword is present */
+  ExprList *pEList;      /* The fields of the result */
+  SrcList *pSrc;         /* The FROM clause */
+  Expr *pWhere;          /* The WHERE clause */
+  ExprList *pGroupBy;    /* The GROUP BY clause */
+  Expr *pHaving;         /* The HAVING clause */
+  ExprList *pOrderBy;    /* The ORDER BY clause */
+  int op;                /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
+  Select *pPrior;        /* Prior select in a compound select statement */
+  int nLimit, nOffset;   /* LIMIT and OFFSET values.  -1 means not used */
+  char *zSelect;         /* Complete text of the SELECT command */
+  int base;              /* Index of VDBE cursor for left-most FROM table */
+};
+
+/*
+** The results of a select can be distributed in several ways.
+*/
+#define SRT_Callback     1  /* Invoke a callback with each row of result */
+#define SRT_Mem          2  /* Store result in a memory cell */
+#define SRT_Set          3  /* Store result as unique keys in a table */
+#define SRT_Union        5  /* Store result as keys in a table */
+#define SRT_Except       6  /* Remove result from a UNION table */
+#define SRT_Table        7  /* Store result as data with a unique key */
+#define SRT_TempTable    8  /* Store result in a trasient table */
+#define SRT_Discard      9  /* Do not save the results anywhere */
+#define SRT_Sorter      10  /* Store results in the sorter */
+#define SRT_Subroutine  11  /* Call a subroutine to handle results */
+
+/*
+** When a SELECT uses aggregate functions (like "count(*)" or "avg(f1)")
+** we have to do some additional analysis of expressions.  An instance
+** of the following structure holds information about a single subexpression
+** somewhere in the SELECT statement.  An array of these structures holds
+** all the information we need to generate code for aggregate
+** expressions.
+**
+** Note that when analyzing a SELECT containing aggregates, both
+** non-aggregate field variables and aggregate functions are stored
+** in the AggExpr array of the Parser structure.
+**
+** The pExpr field points to an expression that is part of either the
+** field list, the GROUP BY clause, the HAVING clause or the ORDER BY
+** clause.  The expression will be freed when those clauses are cleaned
+** up.  Do not try to delete the expression attached to AggExpr.pExpr.
+**
+** If AggExpr.pExpr==0, that means the expression is "count(*)".
+*/
+struct AggExpr {
+  int isAgg;        /* if TRUE contains an aggregate function */
+  Expr *pExpr;      /* The expression */
+  FuncDef *pFunc;   /* Information about the aggregate function */
+};
+
+/*
+** An SQL parser context.  A copy of this structure is passed through
+** the parser and down into all the parser action routine in order to
+** carry around information that is global to the entire parse.
+*/
+struct Parse {
+  sqlite *db;          /* The main database structure */
+  Btree *pBe;          /* The database backend */
+  int rc;              /* Return code from execution */
+  sqlite_callback xCallback;  /* The callback function */
+  void *pArg;          /* First argument to the callback function */
+  char *zErrMsg;       /* An error message */
+  Token sErrToken;     /* The token at which the error occurred */
+  Token sFirstToken;   /* The first token parsed */
+  Token sLastToken;    /* The last token parsed */
+  const char *zTail;   /* All SQL text past the last semicolon parsed */
+  Table *pNewTable;    /* A table being constructed by CREATE TABLE */
+  Vdbe *pVdbe;         /* An engine for executing database bytecode */
+  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
+  u8 explain;          /* True if the EXPLAIN flag is found on the query */
+  u8 initFlag;         /* True if reparsing CREATE TABLEs */
+  u8 nameClash;        /* A permanent table name clashes with temp table name */
+  u8 useAgg;           /* If true, extract field values from the aggregator
+                       ** while generating expressions.  Normally false */
+  u8 schemaVerified;   /* True if an OP_VerifySchema has been coded someplace
+                       ** other than after an OP_Transaction */
+  u8 isTemp;           /* True if parsing temporary tables */
+  u8 useCallback;      /* True if callbacks should be used to report results */
+  int newTnum;         /* Table number to use when reparsing CREATE TABLEs */
+  int nErr;            /* Number of errors seen */
+  int nTab;            /* Number of previously allocated VDBE cursors */
+  int nMem;            /* Number of memory cells used so far */
+  int nSet;            /* Number of sets used so far */
+  int nAgg;            /* Number of aggregate expressions */
+  AggExpr *aAgg;       /* An array of aggregate expressions */
+  TriggerStack *trigStack;
+};
+
+/*
+ * Each trigger present in the database schema is stored as an instance of
+ * struct Trigger. 
+ *
+ * Pointers to instances of struct Trigger are stored in two ways.
+ * 1. In the "trigHash" hash table (part of the sqlite* that represents the 
+ *    database). This allows Trigger structures to be retrieved by name.
+ * 2. All triggers associated with a single table form a linked list, using the
+ *    pNext member of struct Trigger. A pointer to the first element of the
+ *    linked list is stored as the "pTrigger" member of the associated
+ *    struct Table.
+ *
+ * The "step_list" member points to the first element of a linked list
+ * containing the SQL statements specified as the trigger program.
+ *
+ * When a trigger is initially created, the "isCommit" member is set to FALSE.
+ * When a transaction is rolled back, any Trigger structures with "isCommit" set
+ * to FALSE are deleted by the logic in sqliteRollbackInternalChanges(). When
+ * a transaction is commited, the "isCommit" member is set to TRUE for any
+ * Trigger structures for which it is FALSE.
+ *
+ * When a trigger is dropped, using the sqliteDropTrigger() interfaced, it is 
+ * removed from the trigHash hash table and added to the trigDrop hash table.
+ * If the transaction is rolled back, the trigger is re-added into the trigHash
+ * hash table (and hence the database schema). If the transaction is commited,
+ * then the Trigger structure is deleted permanently.
+ */
+struct Trigger {
+  char *name;             /* The name of the trigger                        */
+  char *table;            /* The table or view to which the trigger applies */
+  int op;                 /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
+  int tr_tm;              /* One of TK_BEFORE, TK_AFTER */
+  Expr *pWhen;            /* The WHEN clause of the expresion (may be NULL) */
+  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
+                             the <column-list> is stored here */
+  int foreach;            /* One of TK_ROW or TK_STATEMENT */
+
+  TriggerStep *step_list; /* Link list of trigger program steps             */
+  Trigger *pNext;         /* Next trigger associated with the table */
+};
+
+/*
+ * An instance of struct TriggerStep is used to store a single SQL statement
+ * that is a part of a trigger-program. 
+ *
+ * Instances of struct TriggerStep are stored in a singly linked list (linked
+ * using the "pNext" member) referenced by the "step_list" member of the 
+ * associated struct Trigger instance. The first element of the linked list is
+ * the first step of the trigger-program.
+ * 
+ * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
+ * "SELECT" statement. The meanings of the other members is determined by the 
+ * value of "op" as follows:
+ *
+ * (op == TK_INSERT)
+ * orconf    -> stores the ON CONFLICT algorithm
+ * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
+ *              this stores a pointer to the SELECT statement. Otherwise NULL.
+ * target    -> A token holding the name of the table to insert into.
+ * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
+ *              this stores values to be inserted. Otherwise NULL.
+ * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
+ *              statement, then this stores the column-names to be
+ *              inserted into.
+ *
+ * (op == TK_DELETE)
+ * target    -> A token holding the name of the table to delete from.
+ * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
+ *              Otherwise NULL.
+ * 
+ * (op == TK_UPDATE)
+ * target    -> A token holding the name of the table to update rows of.
+ * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
+ *              Otherwise NULL.
+ * pExprList -> A list of the columns to update and the expressions to update
+ *              them to. See sqliteUpdate() documentation of "pChanges"
+ *              argument.
+ * 
+ */
+struct TriggerStep {
+  int op;              /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
+  int orconf;          /* OE_Rollback etc. */
+
+  Select *pSelect;     /* Valid for SELECT and sometimes 
+                         INSERT steps (when pExprList == 0) */
+  Token target;        /* Valid for DELETE, UPDATE, INSERT steps */
+  Expr *pWhere;        /* Valid for DELETE, UPDATE steps */
+  ExprList *pExprList; /* Valid for UPDATE statements and sometimes 
+                          INSERT steps (when pSelect == 0)         */
+  IdList *pIdList;     /* Valid for INSERT statements only */
+
+  TriggerStep * pNext; /* Next in the link-list */
+};
+
+/*
+ * An instance of struct TriggerStack stores information required during code
+ * generation of a single trigger program. While the trigger program is being
+ * coded, its associated TriggerStack instance is pointed to by the
+ * "pTriggerStack" member of the Parse structure.
+ *
+ * The pTab member points to the table that triggers are being coded on. The 
+ * newIdx member contains the index of the vdbe cursor that points at the temp
+ * table that stores the new.* references. If new.* references are not valid
+ * for the trigger being coded (for example an ON DELETE trigger), then newIdx
+ * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
+ *
+ * The ON CONFLICT policy to be used for the trigger program steps is stored 
+ * as the orconf member. If this is OE_Default, then the ON CONFLICT clause 
+ * specified for individual triggers steps is used.
+ *
+ * struct TriggerStack has a "pNext" member, to allow linked lists to be
+ * constructed. When coding nested triggers (triggers fired by other triggers)
+ * each nested trigger stores its parent trigger's TriggerStack as the "pNext" 
+ * pointer. Once the nested trigger has been coded, the pNext value is restored
+ * to the pTriggerStack member of the Parse stucture and coding of the parent
+ * trigger continues.
+ *
+ * Before a nested trigger is coded, the linked list pointed to by the 
+ * pTriggerStack is scanned to ensure that the trigger is not about to be coded
+ * recursively. If this condition is detected, the nested trigger is not coded.
+ */
+struct TriggerStack {
+  Table *pTab;         /* Table that triggers are currently being coded on */
+  int newIdx;          /* Index of vdbe cursor to "new" temp table */
+  int oldIdx;          /* Index of vdbe cursor to "old" temp table */
+  int orconf;          /* Current orconf policy */
+  int ignoreJump;      /* where to jump to for a RAISE(IGNORE) */
+  Trigger *pTrigger;
+
+  TriggerStack *pNext;
+};
+
+/*
+ * This global flag is set for performance testing of triggers. When it is set
+ * SQLite will perform the overhead of building new and old trigger references 
+ * even when no triggers exist
+ */
+extern int always_code_trigger_setup;
+
+/*
+** Internal function prototypes
+*/
+int sqliteStrICmp(const char *, const char *);
+int sqliteStrNICmp(const char *, const char *, int);
+int sqliteHashNoCase(const char *, int);
+int sqliteCompare(const char *, const char *);
+int sqliteSortCompare(const char *, const char *);
+void sqliteRealToSortable(double r, char *);
+#ifdef MEMORY_DEBUG
+  void *sqliteMalloc_(int,int,char*,int);
+  void sqliteFree_(void*,char*,int);
+  void *sqliteRealloc_(void*,int,char*,int);
+  char *sqliteStrDup_(const char*,char*,int);
+  char *sqliteStrNDup_(const char*, int,char*,int);
+  void sqliteCheckMemory(void*,int);
+#else
+  void *sqliteMalloc(int);
+  void *sqliteMallocRaw(int);
+  void sqliteFree(void*);
+  void *sqliteRealloc(void*,int);
+  char *sqliteStrDup(const char*);
+  char *sqliteStrNDup(const char*, int);
+# define sqliteCheckMemory(a,b)
+#endif
+char *sqliteMPrintf(const char *,...);
+void sqliteSetString(char **, const char *, ...);
+void sqliteSetNString(char **, ...);
+void sqliteDequote(char*);
+int sqliteKeywordCode(const char*, int);
+int sqliteRunParser(Parse*, const char*, char **);
+void sqliteExec(Parse*);
+Expr *sqliteExpr(int, Expr*, Expr*, Token*);
+void sqliteExprSpan(Expr*,Token*,Token*);
+Expr *sqliteExprFunction(ExprList*, Token*);
+void sqliteExprDelete(Expr*);
+ExprList *sqliteExprListAppend(ExprList*,Expr*,Token*);
+void sqliteExprListDelete(ExprList*);
+void sqlitePragma(Parse*,Token*,Token*,int);
+void sqliteResetInternalSchema(sqlite*);
+int sqliteInit(sqlite*, char**);
+void sqliteBeginParse(Parse*,int);
+void sqliteRollbackInternalChanges(sqlite*);
+void sqliteCommitInternalChanges(sqlite*);
+Table *sqliteResultSetOfSelect(Parse*,char*,Select*);
+void sqliteOpenMasterTable(Vdbe *v, int);
+void sqliteStartTable(Parse*,Token*,Token*,int,int);
+void sqliteAddColumn(Parse*,Token*);
+void sqliteAddNotNull(Parse*, int);
+void sqliteAddPrimaryKey(Parse*, IdList*, int);
+void sqliteAddColumnType(Parse*,Token*,Token*);
+void sqliteAddDefaultValue(Parse*,Token*,int);
+int sqliteCollateType(const char*, int);
+void sqliteAddCollateType(Parse*, int);
+void sqliteEndTable(Parse*,Token*,Select*);
+void sqliteCreateView(Parse*,Token*,Token*,Select*,int);
+int sqliteViewGetColumnNames(Parse*,Table*);
+void sqliteViewResetAll(sqlite*);
+void sqliteDropTable(Parse*, Token*, int);
+void sqliteDeleteTable(sqlite*, Table*);
+void sqliteInsert(Parse*, Token*, ExprList*, Select*, IdList*, int);
+IdList *sqliteIdListAppend(IdList*, Token*);
+int sqliteIdListIndex(IdList*,const char*);
+SrcList *sqliteSrcListAppend(SrcList*, Token*);
+void sqliteSrcListAddAlias(SrcList*, Token*);
+void sqliteIdListDelete(IdList*);
+void sqliteSrcListDelete(SrcList*);
+void sqliteCreateIndex(Parse*, Token*, Token*, IdList*, int, Token*, Token*);
+void sqliteDropIndex(Parse*, Token*);
+void sqliteAddKeyType(Vdbe*, ExprList*);
+void sqliteAddIdxKeyType(Vdbe*, Index*);
+int sqliteSelect(Parse*, Select*, int, int, Select*, int, int*);
+Select *sqliteSelectNew(ExprList*,SrcList*,Expr*,ExprList*,Expr*,ExprList*,
+                        int,int,int);
+void sqliteSelectDelete(Select*);
+void sqliteSelectUnbind(Select*);
+Table *sqliteTableNameToTable(Parse*, const char*);
+SrcList *sqliteTableTokenToSrcList(Parse*, Token*);
+void sqliteDeleteFrom(Parse*, Token*, Expr*);
+void sqliteUpdate(Parse*, Token*, ExprList*, Expr*, int);
+WhereInfo *sqliteWhereBegin(Parse*, int, SrcList*, Expr*, int, ExprList**);
+void sqliteWhereEnd(WhereInfo*);
+void sqliteExprCode(Parse*, Expr*);
+void sqliteExprIfTrue(Parse*, Expr*, int, int);
+void sqliteExprIfFalse(Parse*, Expr*, int, int);
+Table *sqliteFindTable(sqlite*,const char*);
+Index *sqliteFindIndex(sqlite*,const char*);
+void sqliteUnlinkAndDeleteIndex(sqlite*,Index*);
+void sqliteCopy(Parse*, Token*, Token*, Token*, int);
+void sqliteVacuum(Parse*, Token*);
+int sqliteGlobCompare(const unsigned char*,const unsigned char*);
+int sqliteLikeCompare(const unsigned char*,const unsigned char*);
+char *sqliteTableNameFromToken(Token*);
+int sqliteExprCheck(Parse*, Expr*, int, int*);
+int sqliteExprType(Expr*);
+int sqliteExprCompare(Expr*, Expr*);
+int sqliteFuncId(Token*);
+int sqliteExprResolveIds(Parse*, int, SrcList*, ExprList*, Expr*);
+int sqliteExprAnalyzeAggregates(Parse*, Expr*);
+Vdbe *sqliteGetVdbe(Parse*);
+int sqliteRandomByte(void);
+int sqliteRandomInteger(void);
+void sqliteBeginTransaction(Parse*, int);
+void sqliteCommitTransaction(Parse*);
+void sqliteRollbackTransaction(Parse*);
+int sqliteExprIsConstant(Expr*);
+int sqliteExprIsInteger(Expr*, int*);
+int sqliteIsRowid(const char*);
+void sqliteGenerateRowDelete(sqlite*, Vdbe*, Table*, int, int);
+void sqliteGenerateRowIndexDelete(sqlite*, Vdbe*, Table*, int, char*);
+void sqliteGenerateConstraintChecks(Parse*,Table*,int,char*,int,int,int,int);
+void sqliteCompleteInsertion(Parse*, Table*, int, char*, int, int);
+void sqliteBeginWriteOperation(Parse*, int, int);
+void sqliteEndWriteOperation(Parse*);
+Expr *sqliteExprDup(Expr*);
+void sqliteTokenCopy(Token*, Token*);
+ExprList *sqliteExprListDup(ExprList*);
+SrcList *sqliteSrcListDup(SrcList*);
+IdList *sqliteIdListDup(IdList*);
+Select *sqliteSelectDup(Select*);
+FuncDef *sqliteFindFunction(sqlite*,const char*,int,int,int);
+void sqliteRegisterBuiltinFunctions(sqlite*);
+int sqliteSafetyOn(sqlite*);
+int sqliteSafetyOff(sqlite*);
+int sqliteSafetyCheck(sqlite*);
+void sqliteChangeCookie(sqlite*, Vdbe*);
+void sqliteCreateTrigger(Parse*, Token*, int, int, IdList*, Token*, 
+                         int, Expr*, TriggerStep*, Token*);
+void sqliteDropTrigger(Parse*, Token*, int);
+int sqliteTriggersExist(Parse* , Trigger* , int , int , int, ExprList*);
+int sqliteCodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int, 
+                         int, int);
+void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
+TriggerStep *sqliteTriggerSelectStep(Select*);
+TriggerStep *sqliteTriggerInsertStep(Token*, IdList*, ExprList*, Select*, int);
+TriggerStep *sqliteTriggerUpdateStep(Token*, ExprList*, Expr*, int);
+TriggerStep *sqliteTriggerDeleteStep(Token*, Expr*);
+void sqliteDeleteTrigger(Trigger*);
+int sqliteJoinType(Parse*, Token*, Token*, Token*);
+void sqliteCreateForeignKey(Parse*, IdList*, Token*, IdList*, int);
+void sqliteDeferForeignKey(Parse*, int);
+#ifndef SQLITE_OMIT_AUTHORIZATION
+  void sqliteAuthRead(Parse*,Expr*,SrcList*,int);
+  int sqliteAuthCheck(Parse*,int, const char*, const char*);
+#else
+# define sqliteAuthRead(a,b,c,d)
+# define sqliteAuthCheck(a,b,c,d)    SQLITE_OK
+#endif
diff --git a/ext/sqlite/libsqlite/src/table.c b/ext/sqlite/libsqlite/src/table.c
new file mode 100644 (file)
index 0000000..eb3118f
--- /dev/null
@@ -0,0 +1,200 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains the sqlite_get_table() and sqlite_free_table()
+** interface routines.  These are just wrappers around the main
+** interface routine of sqlite_exec().
+**
+** These routines are in a separate files so that they will not be linked
+** if they are not used.
+*/
+#include <stdlib.h>
+#include <string.h>
+#include "sqliteInt.h"
+
+/*
+** This structure is used to pass data from sqlite_get_table() through
+** to the callback function is uses to build the result.
+*/
+typedef struct TabResult {
+  char **azResult;
+  char *zErrMsg;
+  int nResult;
+  int nAlloc;
+  int nRow;
+  int nColumn;
+  int nData;
+  int rc;
+} TabResult;
+
+/*
+** This routine is called once for each row in the result table.  Its job
+** is to fill in the TabResult structure appropriately, allocating new
+** memory as necessary.
+*/
+static int sqlite_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
+  TabResult *p = (TabResult*)pArg;
+  int need;
+  int i;
+  char *z;
+
+  /* Make sure there is enough space in p->azResult to hold everything
+  ** we need to remember from this invocation of the callback.
+  */
+  if( p->nRow==0 && argv!=0 ){
+    need = nCol*2;
+  }else{
+    need = nCol;
+  }
+  if( p->nData + need >= p->nAlloc ){
+    char **azNew;
+    p->nAlloc = p->nAlloc*2 + need + 1;
+    azNew = realloc( p->azResult, sizeof(char*)*p->nAlloc );
+    if( azNew==0 ){
+      p->rc = SQLITE_NOMEM;
+      return 1;
+    }
+    p->azResult = azNew;
+  }
+
+  /* If this is the first row, then generate an extra row containing
+  ** the names of all columns.
+  */
+  if( p->nRow==0 ){
+    p->nColumn = nCol;
+    for(i=0; i<nCol; i++){
+      if( colv[i]==0 ){
+        z = 0;
+      }else{
+        z = malloc( strlen(colv[i])+1 );
+        if( z==0 ){
+          p->rc = SQLITE_NOMEM;
+          return 1;
+        }
+        strcpy(z, colv[i]);
+      }
+      p->azResult[p->nData++] = z;
+    }
+  }else if( p->nColumn!=nCol ){
+    sqliteSetString(&p->zErrMsg,
+       "sqlite_get_table() called with two or more incompatible queries", 0);
+    p->rc = SQLITE_ERROR;
+    return 1;
+  }
+
+  /* Copy over the row data
+  */
+  if( argv!=0 ){
+    for(i=0; i<nCol; i++){
+      if( argv[i]==0 ){
+        z = 0;
+      }else{
+        z = malloc( strlen(argv[i])+1 );
+        if( z==0 ){
+          p->rc = SQLITE_NOMEM;
+          return 1;
+        }
+        strcpy(z, argv[i]);
+      }
+      p->azResult[p->nData++] = z;
+    }
+    p->nRow++;
+  }
+  return 0;
+}
+
+/*
+** Query the database.  But instead of invoking a callback for each row,
+** malloc() for space to hold the result and return the entire results
+** at the conclusion of the call.
+**
+** The result that is written to ***pazResult is held in memory obtained
+** from malloc().  But the caller cannot free this memory directly.  
+** Instead, the entire table should be passed to sqlite_free_table() when
+** the calling procedure is finished using it.
+*/
+int sqlite_get_table(
+  sqlite *db,                 /* The database on which the SQL executes */
+  const char *zSql,           /* The SQL to be executed */
+  char ***pazResult,          /* Write the result table here */
+  int *pnRow,                 /* Write the number of rows in the result here */
+  int *pnColumn,              /* Write the number of columns of result here */
+  char **pzErrMsg             /* Write error messages here */
+){
+  int rc;
+  TabResult res;
+  if( pazResult==0 ){ return SQLITE_ERROR; }
+  *pazResult = 0;
+  if( pnColumn ) *pnColumn = 0;
+  if( pnRow ) *pnRow = 0;
+  res.zErrMsg = 0;
+  res.nResult = 0;
+  res.nRow = 0;
+  res.nColumn = 0;
+  res.nData = 1;
+  res.nAlloc = 20;
+  res.rc = SQLITE_OK;
+  res.azResult = malloc( sizeof(char*)*res.nAlloc );
+  if( res.azResult==0 ){
+    return SQLITE_NOMEM;
+  }
+  res.azResult[0] = 0;
+  rc = sqlite_exec(db, zSql, sqlite_get_table_cb, &res, pzErrMsg);
+  if( res.azResult ){
+    res.azResult[0] = (char*)res.nData;
+  }
+  if( rc==SQLITE_ABORT ){
+    sqlite_free_table(&res.azResult[1]);
+    if( res.zErrMsg ){
+      if( pzErrMsg ){
+        free(*pzErrMsg);
+        *pzErrMsg = res.zErrMsg;
+        sqliteStrRealloc(pzErrMsg);
+      }else{
+        sqliteFree(res.zErrMsg);
+      }
+    }
+    return res.rc;
+  }
+  sqliteFree(res.zErrMsg);
+  if( rc!=SQLITE_OK ){
+    sqlite_free_table(&res.azResult[1]);
+    return rc;
+  }
+  if( res.nAlloc>res.nData ){
+    char **azNew;
+    azNew = realloc( res.azResult, sizeof(char*)*(res.nData+1) );
+    if( res.azResult==0 ){
+      sqlite_free_table(&res.azResult[1]);
+      return SQLITE_NOMEM;
+    }
+    res.azResult = azNew;
+  }
+  *pazResult = &res.azResult[1];
+  if( pnColumn ) *pnColumn = res.nColumn;
+  if( pnRow ) *pnRow = res.nRow;
+  return rc;
+}
+
+/*
+** This routine frees the space the sqlite_get_table() malloced.
+*/
+void sqlite_free_table(
+  char **azResult             /* Result returned from from sqlite_get_table() */
+){
+  if( azResult ){
+    int i, n;
+    azResult--;
+    n = (int)azResult[0];
+    for(i=1; i<n; i++){ if( azResult[i] ) free(azResult[i]); }
+    free(azResult);
+  }
+}
diff --git a/ext/sqlite/libsqlite/src/tokenize.c b/ext/sqlite/libsqlite/src/tokenize.c
new file mode 100644 (file)
index 0000000..f24da9e
--- /dev/null
@@ -0,0 +1,496 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** An tokenizer for SQL
+**
+** This file contains C code that splits an SQL input string up into
+** individual tokens and sends those tokens one-by-one over to the
+** parser for analysis.
+**
+** $Id$
+*/
+#include "sqliteInt.h"
+#include "os.h"
+#include <ctype.h>
+#include <stdlib.h>
+
+/*
+** All the keywords of the SQL language are stored as in a hash
+** table composed of instances of the following structure.
+*/
+typedef struct Keyword Keyword;
+struct Keyword {
+  char *zName;             /* The keyword name */
+  int len;                 /* Number of characters in the keyword */
+  int tokenType;           /* The token value for this keyword */
+  Keyword *pNext;          /* Next keyword with the same hash */
+};
+
+/*
+** These are the keywords
+*/
+static Keyword aKeywordTable[] = {
+  { "ABORT",             0, TK_ABORT,            0 },
+  { "AFTER",             0, TK_AFTER,            0 },
+  { "ALL",               0, TK_ALL,              0 },
+  { "AND",               0, TK_AND,              0 },
+  { "AS",                0, TK_AS,               0 },
+  { "ASC",               0, TK_ASC,              0 },
+  { "BEFORE",            0, TK_BEFORE,           0 },
+  { "BEGIN",             0, TK_BEGIN,            0 },
+  { "BETWEEN",           0, TK_BETWEEN,          0 },
+  { "BY",                0, TK_BY,               0 },
+  { "CASCADE",           0, TK_CASCADE,          0 },
+  { "CASE",              0, TK_CASE,             0 },
+  { "CHECK",             0, TK_CHECK,            0 },
+  { "CLUSTER",           0, TK_CLUSTER,          0 },
+  { "COLLATE",           0, TK_COLLATE,          0 },
+  { "COMMIT",            0, TK_COMMIT,           0 },
+  { "CONFLICT",          0, TK_CONFLICT,         0 },
+  { "CONSTRAINT",        0, TK_CONSTRAINT,       0 },
+  { "COPY",              0, TK_COPY,             0 },
+  { "CREATE",            0, TK_CREATE,           0 },
+  { "CROSS",             0, TK_JOIN_KW,          0 },
+  { "DEFAULT",           0, TK_DEFAULT,          0 },
+  { "DEFERRED",          0, TK_DEFERRED,         0 },
+  { "DEFERRABLE",        0, TK_DEFERRABLE,       0 },
+  { "DELETE",            0, TK_DELETE,           0 },
+  { "DELIMITERS",        0, TK_DELIMITERS,       0 },
+  { "DESC",              0, TK_DESC,             0 },
+  { "DISTINCT",          0, TK_DISTINCT,         0 },
+  { "DROP",              0, TK_DROP,             0 },
+  { "END",               0, TK_END,              0 },
+  { "EACH",              0, TK_EACH,             0 },
+  { "ELSE",              0, TK_ELSE,             0 },
+  { "EXCEPT",            0, TK_EXCEPT,           0 },
+  { "EXPLAIN",           0, TK_EXPLAIN,          0 },
+  { "FAIL",              0, TK_FAIL,             0 },
+  { "FOR",               0, TK_FOR,              0 },
+  { "FOREIGN",           0, TK_FOREIGN,          0 },
+  { "FROM",              0, TK_FROM,             0 },
+  { "FULL",              0, TK_JOIN_KW,          0 },
+  { "GLOB",              0, TK_GLOB,             0 },
+  { "GROUP",             0, TK_GROUP,            0 },
+  { "HAVING",            0, TK_HAVING,           0 },
+  { "IGNORE",            0, TK_IGNORE,           0 },
+  { "IMMEDIATE",         0, TK_IMMEDIATE,        0 },
+  { "IN",                0, TK_IN,               0 },
+  { "INDEX",             0, TK_INDEX,            0 },
+  { "INITIALLY",         0, TK_INITIALLY,        0 },
+  { "INNER",             0, TK_JOIN_KW,          0 },
+  { "INSERT",            0, TK_INSERT,           0 },
+  { "INSTEAD",           0, TK_INSTEAD,          0 },
+  { "INTERSECT",         0, TK_INTERSECT,        0 },
+  { "INTO",              0, TK_INTO,             0 },
+  { "IS",                0, TK_IS,               0 },
+  { "ISNULL",            0, TK_ISNULL,           0 },
+  { "JOIN",              0, TK_JOIN,             0 },
+  { "KEY",               0, TK_KEY,              0 },
+  { "LEFT",              0, TK_JOIN_KW,          0 },
+  { "LIKE",              0, TK_LIKE,             0 },
+  { "LIMIT",             0, TK_LIMIT,            0 },
+  { "MATCH",             0, TK_MATCH,            0 },
+  { "NATURAL",           0, TK_JOIN_KW,          0 },
+  { "NOT",               0, TK_NOT,              0 },
+  { "NOTNULL",           0, TK_NOTNULL,          0 },
+  { "NULL",              0, TK_NULL,             0 },
+  { "OF",                0, TK_OF,               0 },
+  { "OFFSET",            0, TK_OFFSET,           0 },
+  { "ON",                0, TK_ON,               0 },
+  { "OR",                0, TK_OR,               0 },
+  { "ORDER",             0, TK_ORDER,            0 },
+  { "OUTER",             0, TK_JOIN_KW,          0 },
+  { "PRAGMA",            0, TK_PRAGMA,           0 },
+  { "PRIMARY",           0, TK_PRIMARY,          0 },
+  { "RAISE",             0, TK_RAISE,            0 },
+  { "REFERENCES",        0, TK_REFERENCES,       0 },
+  { "REPLACE",           0, TK_REPLACE,          0 },
+  { "RESTRICT",          0, TK_RESTRICT,         0 },
+  { "RIGHT",             0, TK_JOIN_KW,          0 },
+  { "ROLLBACK",          0, TK_ROLLBACK,         0 },
+  { "ROW",               0, TK_ROW,              0 },
+  { "SELECT",            0, TK_SELECT,           0 },
+  { "SET",               0, TK_SET,              0 },
+  { "STATEMENT",         0, TK_STATEMENT,        0 },
+  { "TABLE",             0, TK_TABLE,            0 },
+  { "TEMP",              0, TK_TEMP,             0 },
+  { "TEMPORARY",         0, TK_TEMP,             0 },
+  { "THEN",              0, TK_THEN,             0 },
+  { "TRANSACTION",       0, TK_TRANSACTION,      0 },
+  { "TRIGGER",           0, TK_TRIGGER,          0 },
+  { "UNION",             0, TK_UNION,            0 },
+  { "UNIQUE",            0, TK_UNIQUE,           0 },
+  { "UPDATE",            0, TK_UPDATE,           0 },
+  { "USING",             0, TK_USING,            0 },
+  { "VACUUM",            0, TK_VACUUM,           0 },
+  { "VALUES",            0, TK_VALUES,           0 },
+  { "VIEW",              0, TK_VIEW,             0 },
+  { "WHEN",              0, TK_WHEN,             0 },
+  { "WHERE",             0, TK_WHERE,            0 },
+};
+
+/*
+** This is the hash table
+*/
+#define KEY_HASH_SIZE 71
+static Keyword *apHashTable[KEY_HASH_SIZE];
+
+
+/*
+** This function looks up an identifier to determine if it is a
+** keyword.  If it is a keyword, the token code of that keyword is 
+** returned.  If the input is not a keyword, TK_ID is returned.
+*/
+int sqliteKeywordCode(const char *z, int n){
+  int h;
+  Keyword *p;
+  if( aKeywordTable[0].len==0 ){
+    /* Initialize the keyword hash table */
+    sqliteOsEnterMutex();
+    if( aKeywordTable[0].len==0 ){
+      int i;
+      int n;
+      n = sizeof(aKeywordTable)/sizeof(aKeywordTable[0]);
+      for(i=0; i<n; i++){
+        aKeywordTable[i].len = strlen(aKeywordTable[i].zName);
+        h = sqliteHashNoCase(aKeywordTable[i].zName, aKeywordTable[i].len);
+        h %= KEY_HASH_SIZE;
+        aKeywordTable[i].pNext = apHashTable[h];
+        apHashTable[h] = &aKeywordTable[i];
+      }
+    }
+    sqliteOsLeaveMutex();
+  }
+  h = sqliteHashNoCase(z, n) % KEY_HASH_SIZE;
+  for(p=apHashTable[h]; p; p=p->pNext){
+    if( p->len==n && sqliteStrNICmp(p->zName, z, n)==0 ){
+      return p->tokenType;
+    }
+  }
+  return TK_ID;
+}
+
+
+/*
+** If X is a character that can be used in an identifier then
+** isIdChar[X] will be 1.  Otherwise isIdChar[X] will be 0.
+**
+** In this implementation, an identifier can be a string of
+** alphabetic characters, digits, and "_" plus any character
+** with the high-order bit set.  The latter rule means that
+** any sequence of UTF-8 characters or characters taken from
+** an extended ISO8859 character set can form an identifier.
+*/
+static const char isIdChar[] = {
+/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
+    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
+    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 8x */
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 9x */
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* Ax */
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* Bx */
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* Cx */
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* Dx */
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* Ex */
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* Fx */
+};
+
+
+/*
+** Return the length of the token that begins at z[0].  Return
+** -1 if the token is (or might be) incomplete.  Store the token
+** type in *tokenType before returning.
+*/
+static int sqliteGetToken(const unsigned char *z, int *tokenType){
+  int i;
+  switch( *z ){
+    case ' ': case '\t': case '\n': case '\f': case '\r': {
+      for(i=1; isspace(z[i]); i++){}
+      *tokenType = TK_SPACE;
+      return i;
+    }
+    case '-': {
+      if( z[1]==0 ) return -1;
+      if( z[1]=='-' ){
+        for(i=2; z[i] && z[i]!='\n'; i++){}
+        *tokenType = TK_COMMENT;
+        return i;
+      }
+      *tokenType = TK_MINUS;
+      return 1;
+    }
+    case '(': {
+      if( z[1]=='+' && z[2]==')' ){
+        *tokenType = TK_ORACLE_OUTER_JOIN;
+        return 3;
+      }else{
+        *tokenType = TK_LP;
+        return 1;
+      }
+    }
+    case ')': {
+      *tokenType = TK_RP;
+      return 1;
+    }
+    case ';': {
+      *tokenType = TK_SEMI;
+      return 1;
+    }
+    case '+': {
+      *tokenType = TK_PLUS;
+      return 1;
+    }
+    case '*': {
+      *tokenType = TK_STAR;
+      return 1;
+    }
+    case '/': {
+      if( z[1]!='*' || z[2]==0 ){
+        *tokenType = TK_SLASH;
+        return 1;
+      }
+      for(i=3; z[i] && (z[i]!='/' || z[i-1]!='*'); i++){}
+      if( z[i] ) i++;
+      *tokenType = TK_COMMENT;
+      return i;
+    }
+    case '%': {
+      *tokenType = TK_REM;
+      return 1;
+    }
+    case '=': {
+      *tokenType = TK_EQ;
+      return 1 + (z[1]=='=');
+    }
+    case '<': {
+      if( z[1]=='=' ){
+        *tokenType = TK_LE;
+        return 2;
+      }else if( z[1]=='>' ){
+        *tokenType = TK_NE;
+        return 2;
+      }else if( z[1]=='<' ){
+        *tokenType = TK_LSHIFT;
+        return 2;
+      }else{
+        *tokenType = TK_LT;
+        return 1;
+      }
+    }
+    case '>': {
+      if( z[1]=='=' ){
+        *tokenType = TK_GE;
+        return 2;
+      }else if( z[1]=='>' ){
+        *tokenType = TK_RSHIFT;
+        return 2;
+      }else{
+        *tokenType = TK_GT;
+        return 1;
+      }
+    }
+    case '!': {
+      if( z[1]!='=' ){
+        *tokenType = TK_ILLEGAL;
+        return 2;
+      }else{
+        *tokenType = TK_NE;
+        return 2;
+      }
+    }
+    case '|': {
+      if( z[1]!='|' ){
+        *tokenType = TK_BITOR;
+        return 1;
+      }else{
+        *tokenType = TK_CONCAT;
+        return 2;
+      }
+    }
+    case ',': {
+      *tokenType = TK_COMMA;
+      return 1;
+    }
+    case '&': {
+      *tokenType = TK_BITAND;
+      return 1;
+    }
+    case '~': {
+      *tokenType = TK_BITNOT;
+      return 1;
+    }
+    case '\'': case '"': {
+      int delim = z[0];
+      for(i=1; z[i]; i++){
+        if( z[i]==delim ){
+          if( z[i+1]==delim ){
+            i++;
+          }else{
+            break;
+          }
+        }
+      }
+      if( z[i] ) i++;
+      *tokenType = TK_STRING;
+      return i;
+    }
+    case '.': {
+      if( !isdigit(z[1]) ){
+        *tokenType = TK_DOT;
+        return 1;
+      }
+      /* Fall thru into the next case */
+    }
+    case '0': case '1': case '2': case '3': case '4':
+    case '5': case '6': case '7': case '8': case '9': {
+      *tokenType = TK_INTEGER;
+      for(i=1; isdigit(z[i]); i++){}
+      if( z[i]=='.' ){
+        i++;
+        while( isdigit(z[i]) ){ i++; }
+        *tokenType = TK_FLOAT;
+      }
+      if( (z[i]=='e' || z[i]=='E') &&
+           ( isdigit(z[i+1]) 
+            || ((z[i+1]=='+' || z[i+1]=='-') && isdigit(z[i+2]))
+           )
+      ){
+        i += 2;
+        while( isdigit(z[i]) ){ i++; }
+        *tokenType = TK_FLOAT;
+      }else if( z[0]=='.' ){
+        *tokenType = TK_FLOAT;
+      }
+      return i;
+    }
+    case '[': {
+      for(i=1; z[i] && z[i-1]!=']'; i++){}
+      *tokenType = TK_ID;
+      return i;
+    }
+    default: {
+      if( !isIdChar[*z] ){
+        break;
+      }
+      for(i=1; isIdChar[z[i]]; i++){}
+      *tokenType = sqliteKeywordCode((char*)z, i);
+      return i;
+    }
+  }
+  *tokenType = TK_ILLEGAL;
+  return 1;
+}
+
+/*
+** Run the parser on the given SQL string.  The parser structure is
+** passed in.  An SQLITE_ status code is returned.  If an error occurs
+** and pzErrMsg!=NULL then an error message might be written into 
+** memory obtained from malloc() and *pzErrMsg made to point to that
+** error message.  Or maybe not.
+*/
+int sqliteRunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
+  int nErr = 0;
+  int i;
+  void *pEngine;
+  int tokenType;
+  int lastTokenParsed = -1;
+  sqlite *db = pParse->db;
+  extern void *sqliteParserAlloc(void*(*)(int));
+  extern void sqliteParserFree(void*, void(*)(void*));
+  extern int sqliteParser(void*, int, Token, Parse*);
+
+  db->flags &= ~SQLITE_Interrupt;
+  pParse->rc = SQLITE_OK;
+  i = 0;
+  pEngine = sqliteParserAlloc((void*(*)(int))malloc);
+  if( pEngine==0 ){
+    sqliteSetString(pzErrMsg, "out of memory", 0);
+    return 1;
+  }
+  pParse->sLastToken.dyn = 0;
+  pParse->zTail = zSql;
+  while( sqlite_malloc_failed==0 && zSql[i]!=0 ){
+    
+    assert( i>=0 );
+    pParse->sLastToken.z = &zSql[i];
+    assert( pParse->sLastToken.dyn==0 );
+    pParse->sLastToken.n = sqliteGetToken((unsigned char*)&zSql[i], &tokenType);
+    i += pParse->sLastToken.n;
+    switch( tokenType ){
+      case TK_SPACE:
+      case TK_COMMENT: {
+        if( (db->flags & SQLITE_Interrupt)!=0 ){
+          pParse->rc = SQLITE_INTERRUPT;
+          sqliteSetString(pzErrMsg, "interrupt", 0);
+          goto abort_parse;
+        }
+        break;
+      }
+      case TK_ILLEGAL: {
+        sqliteSetNString(pzErrMsg, "unrecognized token: \"", -1, 
+           pParse->sLastToken.z, pParse->sLastToken.n, "\"", 1, 0);
+        nErr++;
+        goto abort_parse;
+      }
+      case TK_SEMI: {
+        pParse->zTail = &zSql[i];
+        /* Fall thru into the default case */
+      }
+      default: {
+        sqliteParser(pEngine, tokenType, pParse->sLastToken, pParse);
+        lastTokenParsed = tokenType;
+        if( pParse->rc!=SQLITE_OK ){
+          goto abort_parse;
+        }
+        break;
+      }
+    }
+  }
+abort_parse:
+  if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
+    if( lastTokenParsed!=TK_SEMI ){
+      sqliteParser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
+      pParse->zTail = &zSql[i];
+    }
+    sqliteParser(pEngine, 0, pParse->sLastToken, pParse);
+  }
+  sqliteParserFree(pEngine, free);
+  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
+    sqliteSetString(&pParse->zErrMsg, sqlite_error_string(pParse->rc), 0);
+  }
+  if( pParse->zErrMsg ){
+    if( pzErrMsg && *pzErrMsg==0 ){
+      *pzErrMsg = pParse->zErrMsg;
+    }else{
+      sqliteFree(pParse->zErrMsg);
+    }
+    pParse->zErrMsg = 0;
+    if( !nErr ) nErr++;
+  }
+  if( pParse->pVdbe && (pParse->useCallback || pParse->nErr>0) ){
+    sqliteVdbeDelete(pParse->pVdbe);
+    pParse->pVdbe = 0;
+  }
+  if( pParse->pNewTable ){
+    sqliteDeleteTable(pParse->db, pParse->pNewTable);
+    pParse->pNewTable = 0;
+  }
+  if( nErr>0 && (pParse->rc==SQLITE_OK || pParse->rc==SQLITE_DONE) ){
+    pParse->rc = SQLITE_ERROR;
+  }
+  return nErr;
+}
diff --git a/ext/sqlite/libsqlite/src/trigger.c b/ext/sqlite/libsqlite/src/trigger.c
new file mode 100644 (file)
index 0000000..03032fe
--- /dev/null
@@ -0,0 +1,793 @@
+/*
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+*
+*/
+#include "sqliteInt.h"
+
+/*
+** Delete a linked list of TriggerStep structures.
+*/
+static void sqliteDeleteTriggerStep(TriggerStep *pTriggerStep){
+  while( pTriggerStep ){
+    TriggerStep * pTmp = pTriggerStep;
+    pTriggerStep = pTriggerStep->pNext;
+
+    if( pTmp->target.dyn ) sqliteFree((char*)pTmp->target.z);
+    sqliteExprDelete(pTmp->pWhere);
+    sqliteExprListDelete(pTmp->pExprList);
+    sqliteSelectDelete(pTmp->pSelect);
+    sqliteIdListDelete(pTmp->pIdList);
+
+    sqliteFree(pTmp);
+  }
+}
+
+/*
+** This is called by the parser when it sees a CREATE TRIGGER statement. See
+** comments surrounding struct Trigger in sqliteInt.h for a description of 
+** how triggers are stored.
+*/
+void sqliteCreateTrigger(
+  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
+  Token *pName,       /* The name of the trigger */
+  int tr_tm,          /* One of TK_BEFORE, TK_AFTER , TK_INSTEAD */
+  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
+  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
+  Token *pTableName,  /* The name of the table/view the trigger applies to */
+  int foreach,        /* One of TK_ROW or TK_STATEMENT */
+  Expr *pWhen,        /* WHEN clause */
+  TriggerStep *pStepList, /* The triggered program */
+  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
+){
+  Trigger *nt;
+  Table   *tab;
+  char *zName = 0;    /* Name of the trigger */
+
+  /* Check that: 
+  ** 1. the trigger name does not already exist.
+  ** 2. the table (or view) does exist.
+  ** 3. that we are not trying to create a trigger on the sqlite_master table
+  ** 4. That we are not trying to create an INSTEAD OF trigger on a table.
+  ** 5. That we are not trying to create a BEFORE or AFTER trigger on a view.
+  */
+  zName = sqliteStrNDup(pName->z, pName->n);
+  if( sqliteHashFind(&(pParse->db->trigHash), zName, pName->n + 1) ){
+    sqliteSetNString(&pParse->zErrMsg, "trigger ", -1,
+        pName->z, pName->n, " already exists", -1, 0);
+    pParse->nErr++;
+    goto trigger_cleanup;
+  }
+  {
+    char *tmp_str = sqliteStrNDup(pTableName->z, pTableName->n);
+    if( tmp_str==0 ) goto trigger_cleanup;
+    tab = sqliteFindTable(pParse->db, tmp_str);
+    sqliteFree(tmp_str);
+    if( !tab ){
+      sqliteSetNString(&pParse->zErrMsg, "no such table: ", -1,
+          pTableName->z, pTableName->n, 0);
+      pParse->nErr++;
+      goto trigger_cleanup;
+    }
+    if( sqliteStrICmp(tab->zName, MASTER_NAME)==0 ){
+      sqliteSetString(&pParse->zErrMsg, "cannot create trigger on system "
+         "table: " MASTER_NAME, 0);
+      pParse->nErr++;
+      goto trigger_cleanup;
+    }
+    if( sqliteStrICmp(tab->zName, TEMP_MASTER_NAME)==0 ){
+      sqliteSetString(&pParse->zErrMsg, "cannot create trigger on system "
+         "table: " TEMP_MASTER_NAME, 0);
+      pParse->nErr++;
+      goto trigger_cleanup;
+    }
+    if( tab->pSelect && tr_tm != TK_INSTEAD ){
+      sqliteSetNString(&pParse->zErrMsg, "cannot create ", -1,
+         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", -1, " trigger on view: ", -1
+          , pTableName->z, pTableName->n, 0);
+      goto trigger_cleanup;
+    }
+    if( !tab->pSelect && tr_tm == TK_INSTEAD ){
+      sqliteSetNString(&pParse->zErrMsg, "cannot create INSTEAD OF", -1, 
+         " trigger on table: ", -1, pTableName->z, pTableName->n, 0);
+      goto trigger_cleanup;
+    }
+#ifndef SQLITE_OMIT_AUTHORIZATION
+    {
+      int code = SQLITE_CREATE_TRIGGER;
+      if( tab->isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
+      if( sqliteAuthCheck(pParse, code, zName, tab->zName) ){
+        goto trigger_cleanup;
+      }
+      if( sqliteAuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(tab->isTemp), 0)){
+        goto trigger_cleanup;
+      }
+    }
+#endif
+  }
+
+  if (tr_tm == TK_INSTEAD){
+    tr_tm = TK_BEFORE;
+  }
+
+  /* Build the Trigger object */
+  nt = (Trigger*)sqliteMalloc(sizeof(Trigger));
+  if( nt==0 ) goto trigger_cleanup;
+  nt->name = zName;
+  zName = 0;
+  nt->table = sqliteStrNDup(pTableName->z, pTableName->n);
+  if( sqlite_malloc_failed ) goto trigger_cleanup;
+  nt->op = op;
+  nt->tr_tm = tr_tm;
+  nt->pWhen = sqliteExprDup(pWhen);
+  sqliteExprDelete(pWhen);
+  nt->pColumns = sqliteIdListDup(pColumns);
+  sqliteIdListDelete(pColumns);
+  nt->foreach = foreach;
+  nt->step_list = pStepList;
+
+  /* if we are not initializing, and this trigger is not on a TEMP table, 
+  ** build the sqlite_master entry
+  */
+  if( !pParse->initFlag ){
+    static VdbeOp insertTrig[] = {
+      { OP_NewRecno,   0, 0,  0          },
+      { OP_String,     0, 0,  "trigger"  },
+      { OP_String,     0, 0,  0          },  /* 2: trigger name */
+      { OP_String,     0, 0,  0          },  /* 3: table name */
+      { OP_Integer,    0, 0,  0          },
+      { OP_String,     0, 0,  0          },  /* 5: SQL */
+      { OP_MakeRecord, 5, 0,  0          },
+      { OP_PutIntKey,  0, 0,  0          },
+    };
+    int addr;
+    Vdbe *v;
+
+    /* Make an entry in the sqlite_master table */
+    v = sqliteGetVdbe(pParse);
+    if( v==0 ) goto trigger_cleanup;
+    sqliteBeginWriteOperation(pParse, 0, 0);
+    sqliteOpenMasterTable(v, tab->isTemp);
+    addr = sqliteVdbeAddOpList(v, ArraySize(insertTrig), insertTrig);
+    sqliteVdbeChangeP3(v, addr, tab->isTemp ? TEMP_MASTER_NAME : MASTER_NAME,
+                       P3_STATIC);
+    sqliteVdbeChangeP3(v, addr+2, nt->name, 0); 
+    sqliteVdbeChangeP3(v, addr+3, nt->table, 0); 
+    sqliteVdbeChangeP3(v, addr+5, pAll->z, pAll->n);
+    if( !tab->isTemp ){
+      sqliteChangeCookie(pParse->db, v);
+    }
+    sqliteVdbeAddOp(v, OP_Close, 0, 0);
+    sqliteEndWriteOperation(pParse);
+  }
+
+  if( !pParse->explain ){
+    /* Stick it in the hash-table */
+    sqliteHashInsert(&(pParse->db->trigHash), nt->name, pName->n + 1, nt);
+
+    /* Attach it to the table object */
+    nt->pNext = tab->pTrigger;
+    tab->pTrigger = nt;
+    return;
+  }else{
+    sqliteFree(nt->name);
+    sqliteFree(nt->table);
+    sqliteFree(nt);
+  }
+
+trigger_cleanup:
+
+  sqliteFree(zName);
+  sqliteIdListDelete(pColumns);
+  sqliteExprDelete(pWhen);
+  sqliteDeleteTriggerStep(pStepList);
+}
+
+/*
+** Make a copy of all components of the given trigger step.  This has
+** the effect of copying all Expr.token.z values into memory obtained
+** from sqliteMalloc().  As initially created, the Expr.token.z values
+** all point to the input string that was fed to the parser.  But that
+** string is ephemeral - it will go away as soon as the sqlite_exec()
+** call that started the parser exits.  This routine makes a persistent
+** copy of all the Expr.token.z strings so that the TriggerStep structure
+** will be valid even after the sqlite_exec() call returns.
+*/
+static void sqlitePersistTriggerStep(TriggerStep *p){
+  if( p->target.z ){
+    p->target.z = sqliteStrNDup(p->target.z, p->target.n);
+    p->target.dyn = 1;
+  }
+  if( p->pSelect ){
+    Select *pNew = sqliteSelectDup(p->pSelect);
+    sqliteSelectDelete(p->pSelect);
+    p->pSelect = pNew;
+  }
+  if( p->pWhere ){
+    Expr *pNew = sqliteExprDup(p->pWhere);
+    sqliteExprDelete(p->pWhere);
+    p->pWhere = pNew;
+  }
+  if( p->pExprList ){
+    ExprList *pNew = sqliteExprListDup(p->pExprList);
+    sqliteExprListDelete(p->pExprList);
+    p->pExprList = pNew;
+  }
+  if( p->pIdList ){
+    IdList *pNew = sqliteIdListDup(p->pIdList);
+    sqliteIdListDelete(p->pIdList);
+    p->pIdList = pNew;
+  }
+}
+
+/*
+** Turn a SELECT statement (that the pSelect parameter points to) into
+** a trigger step.  Return a pointer to a TriggerStep structure.
+**
+** The parser calls this routine when it finds a SELECT statement in
+** body of a TRIGGER.  
+*/
+TriggerStep *sqliteTriggerSelectStep(Select *pSelect){
+  TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
+  if( pTriggerStep==0 ) return 0;
+
+  pTriggerStep->op = TK_SELECT;
+  pTriggerStep->pSelect = pSelect;
+  pTriggerStep->orconf = OE_Default;
+  sqlitePersistTriggerStep(pTriggerStep);
+
+  return pTriggerStep;
+}
+
+/*
+** Build a trigger step out of an INSERT statement.  Return a pointer
+** to the new trigger step.
+**
+** The parser calls this routine when it sees an INSERT inside the
+** body of a trigger.
+*/
+TriggerStep *sqliteTriggerInsertStep(
+  Token *pTableName,  /* Name of the table into which we insert */
+  IdList *pColumn,    /* List of columns in pTableName to insert into */
+  ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
+  Select *pSelect,    /* A SELECT statement that supplies values */
+  int orconf          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
+){
+  TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
+  if( pTriggerStep==0 ) return 0;
+
+  assert(pEList == 0 || pSelect == 0);
+  assert(pEList != 0 || pSelect != 0);
+
+  pTriggerStep->op = TK_INSERT;
+  pTriggerStep->pSelect = pSelect;
+  pTriggerStep->target  = *pTableName;
+  pTriggerStep->pIdList = pColumn;
+  pTriggerStep->pExprList = pEList;
+  pTriggerStep->orconf = orconf;
+  sqlitePersistTriggerStep(pTriggerStep);
+
+  return pTriggerStep;
+}
+
+/*
+** Construct a trigger step that implements an UPDATE statement and return
+** a pointer to that trigger step.  The parser calls this routine when it
+** sees an UPDATE statement inside the body of a CREATE TRIGGER.
+*/
+TriggerStep *sqliteTriggerUpdateStep(
+  Token *pTableName,   /* Name of the table to be updated */
+  ExprList *pEList,    /* The SET clause: list of column and new values */
+  Expr *pWhere,        /* The WHERE clause */
+  int orconf           /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
+){
+  TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
+  if( pTriggerStep==0 ) return 0;
+
+  pTriggerStep->op = TK_UPDATE;
+  pTriggerStep->target  = *pTableName;
+  pTriggerStep->pExprList = pEList;
+  pTriggerStep->pWhere = pWhere;
+  pTriggerStep->orconf = orconf;
+  sqlitePersistTriggerStep(pTriggerStep);
+
+  return pTriggerStep;
+}
+
+/*
+** Construct a trigger step that implements a DELETE statement and return
+** a pointer to that trigger step.  The parser calls this routine when it
+** sees a DELETE statement inside the body of a CREATE TRIGGER.
+*/
+TriggerStep *sqliteTriggerDeleteStep(Token *pTableName, Expr *pWhere){
+  TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
+  if( pTriggerStep==0 ) return 0;
+
+  pTriggerStep->op = TK_DELETE;
+  pTriggerStep->target  = *pTableName;
+  pTriggerStep->pWhere = pWhere;
+  pTriggerStep->orconf = OE_Default;
+  sqlitePersistTriggerStep(pTriggerStep);
+
+  return pTriggerStep;
+}
+
+/* 
+** Recursively delete a Trigger structure
+*/
+void sqliteDeleteTrigger(Trigger *pTrigger){
+  sqliteDeleteTriggerStep(pTrigger->step_list);
+  sqliteFree(pTrigger->name);
+  sqliteFree(pTrigger->table);
+  sqliteExprDelete(pTrigger->pWhen);
+  sqliteIdListDelete(pTrigger->pColumns);
+  sqliteFree(pTrigger);
+}
+
+/*
+ * This function is called to drop a trigger from the database schema. 
+ *
+ * This may be called directly from the parser, or from within 
+ * sqliteDropTable(). In the latter case the "nested" argument is true.
+ *
+ * Note that this function does not delete the trigger entirely. Instead it
+ * removes it from the internal schema and places it in the trigDrop hash 
+ * table. This is so that the trigger can be restored into the database schema
+ * if the transaction is rolled back.
+ */
+void sqliteDropTrigger(Parse *pParse, Token *pName, int nested){
+  char *zName;
+  Trigger *pTrigger;
+  Table   *pTable;
+  Vdbe *v;
+
+  zName = sqliteStrNDup(pName->z, pName->n);
+
+  /* ensure that the trigger being dropped exists */
+  pTrigger = sqliteHashFind(&(pParse->db->trigHash), zName, pName->n + 1); 
+  if( !pTrigger ){
+    sqliteSetNString(&pParse->zErrMsg, "no such trigger: ", -1,
+        zName, -1, 0);
+    sqliteFree(zName);
+    return;
+  }
+  pTable = sqliteFindTable(pParse->db, pTrigger->table);
+  assert(pTable);
+#ifndef SQLITE_OMIT_AUTHORIZATION
+  {
+    int code = SQLITE_DROP_TRIGGER;
+    if( pTable->isTemp ) code = SQLITE_DROP_TEMP_TRIGGER;
+    if( sqliteAuthCheck(pParse, code, pTrigger->name, pTable->zName) ||
+      sqliteAuthCheck(pParse, SQLITE_DELETE, SCHEMA_TABLE(pTable->isTemp),0) ){
+      sqliteFree(zName);
+      return;
+    }
+  }
+#endif
+
+  /*
+   * If this is not an "explain", then delete the trigger structure.
+   */
+  if( !pParse->explain ){
+    if( pTable->pTrigger == pTrigger ){
+      pTable->pTrigger = pTrigger->pNext;
+    }else{
+      Trigger *cc = pTable->pTrigger;
+      while( cc ){ 
+        if( cc->pNext == pTrigger ){
+          cc->pNext = cc->pNext->pNext;
+          break;
+        }
+        cc = cc->pNext;
+      }
+      assert(cc);
+    }
+    sqliteHashInsert(&(pParse->db->trigHash), zName, pName->n + 1, NULL);
+    sqliteDeleteTrigger(pTrigger);
+  }
+
+  /* Generate code to destroy the database record of the trigger.
+  */
+  if( pTable!=0 && !nested && (v = sqliteGetVdbe(pParse))!=0 ){
+    int base;
+    static VdbeOp dropTrigger[] = {
+      { OP_Rewind,     0, ADDR(8),  0},
+      { OP_String,     0, 0,        0}, /* 1 */
+      { OP_MemStore,   1, 1,        0},
+      { OP_MemLoad,    1, 0,        0}, /* 3 */
+      { OP_Column,     0, 1,        0},
+      { OP_Ne,         0, ADDR(7),  0},
+      { OP_Delete,     0, 0,        0},
+      { OP_Next,       0, ADDR(3),  0}, /* 7 */
+    };
+
+    sqliteBeginWriteOperation(pParse, 0, 0);
+    sqliteOpenMasterTable(v, pTable->isTemp);
+    base = sqliteVdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
+    sqliteVdbeChangeP3(v, base+1, zName, 0);
+    if( !pTable->isTemp ){
+      sqliteChangeCookie(pParse->db, v);
+    }
+    sqliteVdbeAddOp(v, OP_Close, 0, 0);
+    sqliteEndWriteOperation(pParse);
+  }
+
+  sqliteFree(zName);
+}
+
+/*
+** pEList is the SET clause of an UPDATE statement.  Each entry
+** in pEList is of the format <id>=<expr>.  If any of the entries
+** in pEList have an <id> which matches an identifier in pIdList,
+** then return TRUE.  If pIdList==NULL, then it is considered a
+** wildcard that matches anything.  Likewise if pEList==NULL then
+** it matches anything so always return true.  Return false only
+** if there is no match.
+*/
+static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
+  int e;
+  if( !pIdList || !pEList ) return 1;
+  for(e=0; e<pEList->nExpr; e++){
+    if( sqliteIdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
+  }
+  return 0; 
+}
+
+/* A global variable that is TRUE if we should always set up temp tables for
+ * for triggers, even if there are no triggers to code. This is used to test 
+ * how much overhead the triggers algorithm is causing.
+ *
+ * This flag can be set or cleared using the "trigger_overhead_test" pragma.
+ * The pragma is not documented since it is not really part of the interface
+ * to SQLite, just the test procedure.
+*/
+int always_code_trigger_setup = 0;
+
+/*
+ * Returns true if a trigger matching op, tr_tm and foreach that is NOT already
+ * on the Parse objects trigger-stack (to prevent recursive trigger firing) is
+ * found in the list specified as pTrigger.
+ */
+int sqliteTriggersExist(
+  Parse *pParse,          /* Used to check for recursive triggers */
+  Trigger *pTrigger,      /* A list of triggers associated with a table */
+  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
+  int tr_tm,              /* one of TK_BEFORE, TK_AFTER */
+  int foreach,            /* one of TK_ROW or TK_STATEMENT */
+  ExprList *pChanges      /* Columns that change in an UPDATE statement */
+){
+  Trigger * pTriggerCursor;
+
+  if( always_code_trigger_setup ){
+    return 1;
+  }
+
+  pTriggerCursor = pTrigger;
+  while( pTriggerCursor ){
+    if( pTriggerCursor->op == op && 
+       pTriggerCursor->tr_tm == tr_tm && 
+       pTriggerCursor->foreach == foreach &&
+       checkColumnOverLap(pTriggerCursor->pColumns, pChanges) ){
+      TriggerStack * ss;
+      ss = pParse->trigStack;
+      while( ss && ss->pTrigger != pTrigger ){
+       ss = ss->pNext;
+      }
+      if( !ss )return 1;
+    }
+    pTriggerCursor = pTriggerCursor->pNext;
+  }
+
+  return 0;
+}
+
+/*
+** Generate VDBE code for zero or more statements inside the body of a
+** trigger.  
+*/
+static int codeTriggerProgram(
+  Parse *pParse,            /* The parser context */
+  TriggerStep *pStepList,   /* List of statements inside the trigger body */
+  int orconfin              /* Conflict algorithm. (OE_Abort, etc) */  
+){
+  TriggerStep * pTriggerStep = pStepList;
+  int orconf;
+
+  while( pTriggerStep ){
+    int saveNTab = pParse->nTab;
+    orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
+    pParse->trigStack->orconf = orconf;
+    switch( pTriggerStep->op ){
+      case TK_SELECT: {
+       Select * ss = sqliteSelectDup(pTriggerStep->pSelect);             
+       assert(ss);
+       assert(ss->pSrc);
+       sqliteSelect(pParse, ss, SRT_Discard, 0, 0, 0, 0);
+       sqliteSelectDelete(ss);
+       break;
+      }
+      case TK_UPDATE: {
+        sqliteVdbeAddOp(pParse->pVdbe, OP_ListPush, 0, 0);
+        sqliteUpdate(pParse, &pTriggerStep->target, 
+               sqliteExprListDup(pTriggerStep->pExprList), 
+               sqliteExprDup(pTriggerStep->pWhere), orconf);
+        sqliteVdbeAddOp(pParse->pVdbe, OP_ListPop, 0, 0);
+        break;
+      }
+      case TK_INSERT: {
+        sqliteInsert(pParse, &pTriggerStep->target, 
+        sqliteExprListDup(pTriggerStep->pExprList), 
+        sqliteSelectDup(pTriggerStep->pSelect), 
+        sqliteIdListDup(pTriggerStep->pIdList), orconf);
+        break;
+      }
+      case TK_DELETE: {
+        sqliteVdbeAddOp(pParse->pVdbe, OP_ListPush, 0, 0);
+        sqliteDeleteFrom(pParse, &pTriggerStep->target, 
+           sqliteExprDup(pTriggerStep->pWhere));
+        sqliteVdbeAddOp(pParse->pVdbe, OP_ListPop, 0, 0);
+        break;
+      }
+      default:
+        assert(0);
+    } 
+    pParse->nTab = saveNTab;
+    pTriggerStep = pTriggerStep->pNext;
+  }
+
+  return 0;
+}
+
+/*
+** This is called to code FOR EACH ROW triggers.
+**
+** When the code that this function generates is executed, the following 
+** must be true:
+**
+** 1. No cursors may be open in the main database.  (But newIdx and oldIdx
+**    can be indices of cursors in temporary tables.  See below.)
+**
+** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
+**    a temporary vdbe cursor (index newIdx) must be open and pointing at
+**    a row containing values to be substituted for new.* expressions in the
+**    trigger program(s).
+**
+** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
+**    a temporary vdbe cursor (index oldIdx) must be open and pointing at
+**    a row containing values to be substituted for old.* expressions in the
+**    trigger program(s).
+**
+*/
+int sqliteCodeRowTrigger(
+  Parse *pParse,       /* Parse context */
+  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
+  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
+  int tr_tm,           /* One of TK_BEFORE, TK_AFTER */
+  Table *pTab,         /* The table to code triggers from */
+  int newIdx,          /* The indice of the "new" row to access */
+  int oldIdx,          /* The indice of the "old" row to access */
+  int orconf,          /* ON CONFLICT policy */
+  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
+){
+  Trigger * pTrigger;
+  TriggerStack * pTriggerStack;
+
+  assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
+  assert(tr_tm == TK_BEFORE || tr_tm == TK_AFTER);
+
+  assert(newIdx != -1 || oldIdx != -1);
+
+  pTrigger = pTab->pTrigger;
+  while( pTrigger ){
+    int fire_this = 0;
+
+    /* determine whether we should code this trigger */
+    if( pTrigger->op == op && pTrigger->tr_tm == tr_tm && 
+        pTrigger->foreach == TK_ROW ){
+      fire_this = 1;
+      pTriggerStack = pParse->trigStack;
+      while( pTriggerStack ){
+        if( pTriggerStack->pTrigger == pTrigger ){
+         fire_this = 0;
+       }
+        pTriggerStack = pTriggerStack->pNext;
+      }
+      if( op == TK_UPDATE && pTrigger->pColumns &&
+          !checkColumnOverLap(pTrigger->pColumns, pChanges) ){
+        fire_this = 0;
+      }
+    }
+
+    if( fire_this && (pTriggerStack = sqliteMalloc(sizeof(TriggerStack)))!=0 ){
+      int endTrigger;
+      SrcList dummyTablist;
+      Expr * whenExpr;
+
+      dummyTablist.nSrc = 0;
+      dummyTablist.a = 0;
+
+      /* Push an entry on to the trigger stack */
+      pTriggerStack->pTrigger = pTrigger;
+      pTriggerStack->newIdx = newIdx;
+      pTriggerStack->oldIdx = oldIdx;
+      pTriggerStack->pTab = pTab;
+      pTriggerStack->pNext = pParse->trigStack;
+      pTriggerStack->ignoreJump = ignoreJump;
+      pParse->trigStack = pTriggerStack;
+
+      /* code the WHEN clause */
+      endTrigger = sqliteVdbeMakeLabel(pParse->pVdbe);
+      whenExpr = sqliteExprDup(pTrigger->pWhen);
+      if( sqliteExprResolveIds(pParse, 0, &dummyTablist, 0, whenExpr) ){
+        pParse->trigStack = pParse->trigStack->pNext;
+        sqliteFree(pTriggerStack);
+        sqliteExprDelete(whenExpr);
+        return 1;
+      }
+      sqliteExprIfFalse(pParse, whenExpr, endTrigger, 1);
+      sqliteExprDelete(whenExpr);
+
+      codeTriggerProgram(pParse, pTrigger->step_list, orconf); 
+
+      /* Pop the entry off the trigger stack */
+      pParse->trigStack = pParse->trigStack->pNext;
+      sqliteFree(pTriggerStack);
+
+      sqliteVdbeResolveLabel(pParse->pVdbe, endTrigger);
+    }
+    pTrigger = pTrigger->pNext;
+  }
+
+  return 0;
+}
+
+/*
+ * This function is called to code ON UPDATE and ON DELETE triggers on 
+ * views. 
+ *
+ * This function deletes the data pointed at by the pWhere and pChanges
+ * arguments before it completes.
+ */
+void sqliteViewTriggers(
+  Parse *pParse, 
+  Table *pTab,         /* The view to code triggers on */
+  Expr *pWhere,        /* The WHERE clause of the statement causing triggers*/
+  int orconf,          /* The ON CONFLICT policy specified as part of the
+                         statement causing these triggers */
+  ExprList *pChanges   /* If this is an statement causing triggers to fire
+                         is an UPDATE, then this list holds the columns
+                         to update and the expressions to update them to.
+                         See comments for sqliteUpdate(). */
+){
+  int oldIdx = -1;
+  int newIdx = -1;
+  int *aXRef = 0;   
+  Vdbe *v;
+  int endOfLoop;
+  int startOfLoop;
+  Select theSelect;
+  Token tblNameToken;
+
+  assert(pTab->pSelect);
+
+  tblNameToken.z = pTab->zName;
+  tblNameToken.n = strlen(pTab->zName);
+
+  theSelect.isDistinct = 0;
+  theSelect.pEList = sqliteExprListAppend(0, sqliteExpr(TK_ALL, 0, 0, 0), 0);
+  theSelect.pSrc   = sqliteSrcListAppend(0, &tblNameToken);
+  theSelect.pWhere = pWhere;    pWhere = 0;
+  theSelect.pGroupBy = 0;
+  theSelect.pHaving = 0;
+  theSelect.pOrderBy = 0;
+  theSelect.op = TK_SELECT; /* ?? */
+  theSelect.pPrior = 0;
+  theSelect.nLimit = -1;
+  theSelect.nOffset = -1;
+  theSelect.zSelect = 0;
+  theSelect.base = 0;
+
+  v = sqliteGetVdbe(pParse);
+  assert(v);
+  sqliteBeginWriteOperation(pParse, 1, 0);
+
+  /* Allocate temp tables */
+  oldIdx = pParse->nTab++;
+  sqliteVdbeAddOp(v, OP_OpenTemp, oldIdx, 0);
+  if( pChanges ){
+    newIdx = pParse->nTab++;
+    sqliteVdbeAddOp(v, OP_OpenTemp, newIdx, 0);
+  }
+
+  /* Snapshot the view */
+  if( sqliteSelect(pParse, &theSelect, SRT_Table, oldIdx, 0, 0, 0) ){
+    goto trigger_cleanup;
+  }
+
+  /* loop thru the view snapshot, executing triggers for each row */
+  endOfLoop = sqliteVdbeMakeLabel(v);
+  sqliteVdbeAddOp(v, OP_Rewind, oldIdx, endOfLoop);
+
+  /* Loop thru the view snapshot, executing triggers for each row */
+  startOfLoop = sqliteVdbeCurrentAddr(v);
+
+  /* Build the updated row if required */
+  if( pChanges ){
+    int ii;
+
+    aXRef = sqliteMalloc( sizeof(int) * pTab->nCol );
+    if( aXRef==0 ) goto trigger_cleanup;
+    for(ii = 0; ii < pTab->nCol; ii++){
+      aXRef[ii] = -1;
+    }
+
+    for(ii=0; ii<pChanges->nExpr; ii++){
+      int jj;
+      if( sqliteExprResolveIds(pParse, oldIdx, theSelect.pSrc , 0, 
+            pChanges->a[ii].pExpr) ){
+        goto trigger_cleanup;
+      }
+
+      if( sqliteExprCheck(pParse, pChanges->a[ii].pExpr, 0, 0) )
+        goto trigger_cleanup;
+
+      for(jj=0; jj<pTab->nCol; jj++){
+        if( sqliteStrICmp(pTab->aCol[jj].zName, pChanges->a[ii].zName)==0 ){
+          aXRef[jj] = ii;
+          break;
+        }
+      }
+      if( jj>=pTab->nCol ){
+        sqliteSetString(&pParse->zErrMsg, "no such column: ", 
+            pChanges->a[ii].zName, 0);
+        pParse->nErr++;
+        goto trigger_cleanup;
+      }
+    }
+
+    sqliteVdbeAddOp(v, OP_Integer, 13, 0);
+
+    for(ii = 0; ii<pTab->nCol; ii++){
+      if( aXRef[ii] < 0 ){ 
+        sqliteVdbeAddOp(v, OP_Column, oldIdx, ii);
+      }else{
+        sqliteExprCode(pParse, pChanges->a[aXRef[ii]].pExpr);
+      }
+    }
+
+    sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
+    sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
+    sqliteVdbeAddOp(v, OP_Rewind, newIdx, 0);
+
+    sqliteCodeRowTrigger(pParse, TK_UPDATE, pChanges, TK_BEFORE, 
+        pTab, newIdx, oldIdx, orconf, endOfLoop);
+    sqliteCodeRowTrigger(pParse, TK_UPDATE, pChanges, TK_AFTER, 
+        pTab, newIdx, oldIdx, orconf, endOfLoop);
+  }else{
+    sqliteCodeRowTrigger(pParse, TK_DELETE, 0, TK_BEFORE, pTab, -1, oldIdx, 
+        orconf, endOfLoop);
+    sqliteCodeRowTrigger(pParse, TK_DELETE, 0, TK_AFTER, pTab, -1, oldIdx, 
+        orconf, endOfLoop);
+  }
+
+  sqliteVdbeAddOp(v, OP_Next, oldIdx, startOfLoop);
+
+  sqliteVdbeResolveLabel(v, endOfLoop);
+  sqliteEndWriteOperation(pParse);
+
+trigger_cleanup:
+  sqliteFree(aXRef);
+  sqliteExprListDelete(pChanges);
+  sqliteExprDelete(pWhere);
+  sqliteExprListDelete(theSelect.pEList);
+  sqliteSrcListDelete(theSelect.pSrc);
+  sqliteExprDelete(theSelect.pWhere);
+  return;
+}
diff --git a/ext/sqlite/libsqlite/src/update.c b/ext/sqlite/libsqlite/src/update.c
new file mode 100644 (file)
index 0000000..b5825dd
--- /dev/null
@@ -0,0 +1,415 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This file contains C code routines that are called by the parser
+** to handle UPDATE statements.
+**
+** $Id$
+*/
+#include "sqliteInt.h"
+
+/*
+** Process an UPDATE statement.
+*/
+void sqliteUpdate(
+  Parse *pParse,         /* The parser context */
+  Token *pTableName,     /* The table in which we should change things */
+  ExprList *pChanges,    /* Things to be changed */
+  Expr *pWhere,          /* The WHERE clause.  May be null */
+  int onError            /* How to handle constraint errors */
+){
+  int i, j;              /* Loop counters */
+  Table *pTab;           /* The table to be updated */
+  SrcList *pTabList = 0; /* Fake FROM clause containing only pTab */
+  int addr;              /* VDBE instruction address of the start of the loop */
+  WhereInfo *pWInfo;     /* Information about the WHERE clause */
+  Vdbe *v;               /* The virtual database engine */
+  Index *pIdx;           /* For looping over indices */
+  int nIdx;              /* Number of indices that need updating */
+  int nIdxTotal;         /* Total number of indices */
+  int base;              /* Index of first available table cursor */
+  sqlite *db;            /* The database structure */
+  Index **apIdx = 0;     /* An array of indices that need updating too */
+  char *aIdxUsed = 0;    /* aIdxUsed[i] if the i-th index is used */
+  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
+                         ** an expression for the i-th column of the table.
+                         ** aXRef[i]==-1 if the i-th column is not changed. */
+  int openOp;            /* Opcode used to open tables */
+  int chngRecno;         /* True if the record number is being changed */
+  Expr *pRecnoExpr;      /* Expression defining the new record number */
+  int openAll;           /* True if all indices need to be opened */
+
+  int row_triggers_exist = 0;
+
+  int newIdx      = -1;  /* index of trigger "new" temp table       */
+  int oldIdx      = -1;  /* index of trigger "old" temp table       */
+
+  if( pParse->nErr || sqlite_malloc_failed ) goto update_cleanup;
+  db = pParse->db;
+
+  /* Check for the special case of a VIEW with one or more ON UPDATE triggers 
+   * defined 
+   */
+  {
+    char *zTab = sqliteTableNameFromToken(pTableName);
+
+    if( zTab != 0 ){
+      pTab = sqliteFindTable(pParse->db, zTab);
+      if( pTab ){
+        row_triggers_exist = 
+          sqliteTriggersExist(pParse, pTab->pTrigger, 
+              TK_UPDATE, TK_BEFORE, TK_ROW, pChanges) ||
+          sqliteTriggersExist(pParse, pTab->pTrigger, 
+              TK_UPDATE, TK_AFTER, TK_ROW, pChanges);
+      }
+      sqliteFree(zTab);
+      if( row_triggers_exist &&  pTab->pSelect ){
+        /* Just fire VIEW triggers */
+        sqliteViewTriggers(pParse, pTab, pWhere, onError, pChanges);
+        return;
+      }
+    }
+  }
+
+  /* Locate the table which we want to update.  This table has to be
+  ** put in an SrcList structure because some of the subroutines we
+  ** will be calling are designed to work with multiple tables and expect
+  ** an SrcList* parameter instead of just a Table* parameter.
+  */
+  pTabList = sqliteTableTokenToSrcList(pParse, pTableName);
+  if( pTabList==0 ) goto update_cleanup;
+  pTab = pTabList->a[0].pTab;
+  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
+  aXRef = sqliteMalloc( sizeof(int) * pTab->nCol );
+  if( aXRef==0 ) goto update_cleanup;
+  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
+
+  /* If there are FOR EACH ROW triggers, allocate temp tables */
+  if( row_triggers_exist ){
+    newIdx = pParse->nTab++;
+    oldIdx = pParse->nTab++;
+  }
+
+  /* Allocate a cursors for the main database table and for all indices.
+  ** The index cursors might not be used, but if they are used they
+  ** need to occur right after the database cursor.  So go ahead and
+  ** allocate enough space, just in case.
+  */
+  base = pParse->nTab++;
+  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+    pParse->nTab++;
+  }
+
+  /* Resolve the column names in all the expressions in both the
+  ** WHERE clause and in the new values.  Also find the column index
+  ** for each column to be updated in the pChanges array.  For each
+  ** column to be updated, make sure we have authorization to change
+  ** that column.
+  */
+  if( pWhere ){
+    if( sqliteExprResolveIds(pParse, base, pTabList, 0, pWhere) ){
+      goto update_cleanup;
+    }
+    if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
+      goto update_cleanup;
+    }
+  }
+  chngRecno = 0;
+  for(i=0; i<pChanges->nExpr; i++){
+    if( sqliteExprResolveIds(pParse, base, pTabList, 0, pChanges->a[i].pExpr) ){
+      goto update_cleanup;
+    }
+    if( sqliteExprCheck(pParse, pChanges->a[i].pExpr, 0, 0) ){
+      goto update_cleanup;
+    }
+    for(j=0; j<pTab->nCol; j++){
+      if( sqliteStrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
+        if( j==pTab->iPKey ){
+          chngRecno = 1;
+          pRecnoExpr = pChanges->a[i].pExpr;
+        }
+        aXRef[j] = i;
+        break;
+      }
+    }
+    if( j>=pTab->nCol ){
+      sqliteSetString(&pParse->zErrMsg, "no such column: ", 
+         pChanges->a[i].zName, 0);
+      pParse->nErr++;
+      goto update_cleanup;
+    }
+#ifndef SQLITE_OMIT_AUTHORIZATION
+    {
+      int rc;
+      rc = sqliteAuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
+                           pTab->aCol[j].zName);
+      if( rc==SQLITE_DENY ){
+        goto update_cleanup;
+      }else if( rc==SQLITE_IGNORE ){
+        aXRef[j] = -1;
+      }
+    }
+#endif
+  }
+
+  /* Allocate memory for the array apIdx[] and fill it with pointers to every
+  ** index that needs to be updated.  Indices only need updating if their
+  ** key includes one of the columns named in pChanges or if the record
+  ** number of the original table entry is changing.
+  */
+  for(nIdx=nIdxTotal=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdxTotal++){
+    if( chngRecno ){
+      i = 0;
+    }else {
+      for(i=0; i<pIdx->nColumn; i++){
+        if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
+      }
+    }
+    if( i<pIdx->nColumn ) nIdx++;
+  }
+  if( nIdxTotal>0 ){
+    apIdx = sqliteMalloc( sizeof(Index*) * nIdx + nIdxTotal );
+    if( apIdx==0 ) goto update_cleanup;
+    aIdxUsed = (char*)&apIdx[nIdx];
+  }
+  for(nIdx=j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
+    if( chngRecno ){
+      i = 0;
+    }else{
+      for(i=0; i<pIdx->nColumn; i++){
+        if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
+      }
+    }
+    if( i<pIdx->nColumn ){
+      apIdx[nIdx++] = pIdx;
+      aIdxUsed[j] = 1;
+    }else{
+      aIdxUsed[j] = 0;
+    }
+  }
+
+  /* Begin generating code.
+  */
+  v = sqliteGetVdbe(pParse);
+  if( v==0 ) goto update_cleanup;
+  sqliteBeginWriteOperation(pParse, 1, !row_triggers_exist && pTab->isTemp);
+
+  /* Begin the database scan
+  */
+  pWInfo = sqliteWhereBegin(pParse, base, pTabList, pWhere, 1, 0);
+  if( pWInfo==0 ) goto update_cleanup;
+
+  /* Remember the index of every item to be updated.
+  */
+  sqliteVdbeAddOp(v, OP_ListWrite, 0, 0);
+
+  /* End the database scan loop.
+  */
+  sqliteWhereEnd(pWInfo);
+
+  /* Initialize the count of updated rows
+  */
+  if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
+    sqliteVdbeAddOp(v, OP_Integer, 0, 0);
+  }
+
+  if( row_triggers_exist ){
+    int ii;
+
+    sqliteVdbeAddOp(v, OP_OpenTemp, oldIdx, 0);
+    sqliteVdbeAddOp(v, OP_OpenTemp, newIdx, 0);
+
+    sqliteVdbeAddOp(v, OP_ListRewind, 0, 0);
+    addr = sqliteVdbeAddOp(v, OP_ListRead, 0, 0);
+    sqliteVdbeAddOp(v, OP_Dup, 0, 0);
+
+    sqliteVdbeAddOp(v, OP_Dup, 0, 0);
+    sqliteVdbeAddOp(v, (pTab->isTemp?OP_OpenAux:OP_Open), base, pTab->tnum);
+    sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
+
+    sqliteVdbeAddOp(v, OP_Integer, 13, 0);
+    for(ii = 0; ii < pTab->nCol; ii++){
+      if( ii == pTab->iPKey ){
+       sqliteVdbeAddOp(v, OP_Recno, base, 0);
+      }else{
+       sqliteVdbeAddOp(v, OP_Column, base, ii);
+      }
+    }
+    sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
+    sqliteVdbeAddOp(v, OP_PutIntKey, oldIdx, 0);
+
+    sqliteVdbeAddOp(v, OP_Integer, 13, 0);
+    for(ii = 0; ii < pTab->nCol; ii++){
+      if( aXRef[ii] < 0 ){
+        if( ii == pTab->iPKey ){
+          sqliteVdbeAddOp(v, OP_Recno, base, 0);
+       }else{
+          sqliteVdbeAddOp(v, OP_Column, base, ii);
+       }
+      }else{
+        sqliteExprCode(pParse, pChanges->a[aXRef[ii]].pExpr);
+      }
+    }
+    sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
+    sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
+    sqliteVdbeAddOp(v, OP_Close, base, 0);
+
+    sqliteVdbeAddOp(v, OP_Rewind, oldIdx, 0);
+    sqliteVdbeAddOp(v, OP_Rewind, newIdx, 0);
+
+    if( sqliteCodeRowTrigger(pParse, TK_UPDATE, pChanges, TK_BEFORE, pTab, 
+          newIdx, oldIdx, onError, addr) ){
+      goto update_cleanup;
+    }
+  }
+
+  /* Rewind the list of records that need to be updated and
+  ** open every index that needs updating.  Note that if any
+  ** index could potentially invoke a REPLACE conflict resolution 
+  ** action, then we need to open all indices because we might need
+  ** to be deleting some records.
+  */
+  openOp = pTab->isTemp ? OP_OpenWrAux : OP_OpenWrite;
+  sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
+  if( onError==OE_Replace ){
+    openAll = 1;
+  }else{
+    openAll = 0;
+    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+      if( pIdx->onError==OE_Replace ){
+        openAll = 1;
+        break;
+      }
+    }
+  }
+  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
+    if( openAll || aIdxUsed[i] ){
+      sqliteVdbeAddOp(v, openOp, base+i+1, pIdx->tnum);
+      assert( pParse->nTab>base+i+1 );
+    }
+  }
+
+  /* Loop over every record that needs updating.  We have to load
+  ** the old data for each record to be updated because some columns
+  ** might not change and we will need to copy the old value.
+  ** Also, the old data is needed to delete the old index entires.
+  ** So make the cursor point at the old record.
+  */
+  if( !row_triggers_exist ){
+    sqliteVdbeAddOp(v, OP_ListRewind, 0, 0);
+    addr = sqliteVdbeAddOp(v, OP_ListRead, 0, 0);
+    sqliteVdbeAddOp(v, OP_Dup, 0, 0);
+  }
+  sqliteVdbeAddOp(v, OP_NotExists, base, addr);
+
+  /* If the record number will change, push the record number as it
+  ** will be after the update. (The old record number is currently
+  ** on top of the stack.)
+  */
+  if( chngRecno ){
+    sqliteExprCode(pParse, pRecnoExpr);
+    sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
+  }
+
+  /* Compute new data for this record.  
+  */
+  for(i=0; i<pTab->nCol; i++){
+    if( i==pTab->iPKey ){
+      sqliteVdbeAddOp(v, OP_String, 0, 0);
+      continue;
+    }
+    j = aXRef[i];
+    if( j<0 ){
+      sqliteVdbeAddOp(v, OP_Column, base, i);
+    }else{
+      sqliteExprCode(pParse, pChanges->a[j].pExpr);
+    }
+  }
+
+  /* Do constraint checks
+  */
+  sqliteGenerateConstraintChecks(pParse, pTab, base, aIdxUsed, chngRecno, 1,
+                                 onError, addr);
+
+  /* Delete the old indices for the current record.
+  */
+  sqliteGenerateRowIndexDelete(db, v, pTab, base, aIdxUsed);
+
+  /* If changing the record number, delete the old record.
+  */
+  if( chngRecno ){
+    sqliteVdbeAddOp(v, OP_Delete, base, 0);
+  }
+
+  /* Create the new index entries and the new record.
+  */
+  sqliteCompleteInsertion(pParse, pTab, base, aIdxUsed, chngRecno, 1);
+
+  /* Increment the row counter 
+  */
+  if( db->flags & SQLITE_CountRows && !pParse->trigStack){
+    sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
+  }
+
+  if( row_triggers_exist ){
+    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
+      if( openAll || aIdxUsed[i] )
+        sqliteVdbeAddOp(v, OP_Close, base+i+1, 0);
+    }
+    sqliteVdbeAddOp(v, OP_Close, base, 0);
+    pParse->nTab = base;
+
+    if( sqliteCodeRowTrigger(pParse, TK_UPDATE, pChanges, TK_AFTER, pTab, 
+          newIdx, oldIdx, onError, addr) ){
+      goto update_cleanup;
+    }
+  }
+
+  /* Repeat the above with the next record to be updated, until
+  ** all record selected by the WHERE clause have been updated.
+  */
+  sqliteVdbeAddOp(v, OP_Goto, 0, addr);
+  sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
+  sqliteVdbeAddOp(v, OP_ListReset, 0, 0);
+
+  /* Close all tables if there were no FOR EACH ROW triggers */
+  if( !row_triggers_exist ){
+    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
+      if( openAll || aIdxUsed[i] ){
+        sqliteVdbeAddOp(v, OP_Close, base+i+1, 0);
+      }
+    }
+    sqliteVdbeAddOp(v, OP_Close, base, 0);
+    pParse->nTab = base;
+  }else{
+    sqliteVdbeAddOp(v, OP_Close, newIdx, 0);
+    sqliteVdbeAddOp(v, OP_Close, oldIdx, 0);
+  }
+
+  sqliteEndWriteOperation(pParse);
+
+  /*
+  ** Return the number of rows that were changed.
+  */
+  if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
+    sqliteVdbeAddOp(v, OP_ColumnName, 0, 0);
+    sqliteVdbeChangeP3(v, -1, "rows updated", P3_STATIC);
+    sqliteVdbeAddOp(v, OP_Callback, 1, 0);
+  }
+
+update_cleanup:
+  sqliteFree(apIdx);
+  sqliteFree(aXRef);
+  sqliteSrcListDelete(pTabList);
+  sqliteExprListDelete(pChanges);
+  sqliteExprDelete(pWhere);
+  return;
+}
diff --git a/ext/sqlite/libsqlite/src/util.c b/ext/sqlite/libsqlite/src/util.c
new file mode 100644 (file)
index 0000000..292df5d
--- /dev/null
@@ -0,0 +1,1206 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** Utility functions used throughout sqlite.
+**
+** This file contains functions for allocating memory, comparing
+** strings, and stuff like that.
+**
+** $Id$
+*/
+#include "sqliteInt.h"
+#include <stdarg.h>
+#include <ctype.h>
+
+/*
+** If malloc() ever fails, this global variable gets set to 1.
+** This causes the library to abort and never again function.
+*/
+int sqlite_malloc_failed = 0;
+
+/*
+** If MEMORY_DEBUG is defined, then use versions of malloc() and
+** free() that track memory usage and check for buffer overruns.
+*/
+#ifdef MEMORY_DEBUG
+
+/*
+** For keeping track of the number of mallocs and frees.   This
+** is used to check for memory leaks.
+*/
+int sqlite_nMalloc;         /* Number of sqliteMalloc() calls */
+int sqlite_nFree;           /* Number of sqliteFree() calls */
+int sqlite_iMallocFail;     /* Fail sqliteMalloc() after this many calls */
+#if MEMORY_DEBUG>1
+static int memcnt = 0;
+#endif
+
+
+/*
+** Allocate new memory and set it to zero.  Return NULL if
+** no memory is available.
+*/
+void *sqliteMalloc_(int n, int bZero, char *zFile, int line){
+  void *p;
+  int *pi;
+  int k;
+  if( sqlite_iMallocFail>=0 ){
+    sqlite_iMallocFail--;
+    if( sqlite_iMallocFail==0 ){
+      sqlite_malloc_failed++;
+#if MEMORY_DEBUG>1
+      fprintf(stderr,"**** failed to allocate %d bytes at %s:%d\n",
+              n, zFile,line);
+#endif
+      sqlite_iMallocFail--;
+      return 0;
+    }
+  }
+  if( n==0 ) return 0;
+  k = (n+sizeof(int)-1)/sizeof(int);
+  pi = malloc( (3+k)*sizeof(int));
+  if( pi==0 ){
+    sqlite_malloc_failed++;
+    return 0;
+  }
+  sqlite_nMalloc++;
+  pi[0] = 0xdead1122;
+  pi[1] = n;
+  pi[k+2] = 0xdead3344;
+  p = &pi[2];
+  memset(p, bZero==0, n);
+#if MEMORY_DEBUG>1
+  fprintf(stderr,"%06d malloc %d bytes at 0x%x from %s:%d\n",
+      ++memcnt, n, (int)p, zFile,line);
+#endif
+  return p;
+}
+
+/*
+** Check to see if the given pointer was obtained from sqliteMalloc()
+** and is able to hold at least N bytes.  Raise an exception if this
+** is not the case.
+**
+** This routine is used for testing purposes only.
+*/
+void sqliteCheckMemory(void *p, int N){
+  int *pi = p;
+  int n, k;
+  pi -= 2;
+  assert( pi[0]==0xdead1122 );
+  n = pi[1];
+  assert( N>=0 && N<n );
+  k = (n+sizeof(int)-1)/sizeof(int);
+  assert( pi[k+2]==0xdead3344 );
+}
+
+/*
+** Free memory previously obtained from sqliteMalloc()
+*/
+void sqliteFree_(void *p, char *zFile, int line){
+  if( p ){
+    int *pi, k, n;
+    pi = p;
+    pi -= 2;
+    sqlite_nFree++;
+    if( pi[0]!=0xdead1122 ){
+      fprintf(stderr,"Low-end memory corruption at 0x%x\n", (int)p);
+      return;
+    }
+    n = pi[1];
+    k = (n+sizeof(int)-1)/sizeof(int);
+    if( pi[k+2]!=0xdead3344 ){
+      fprintf(stderr,"High-end memory corruption at 0x%x\n", (int)p);
+      return;
+    }
+    memset(pi, 0xff, (k+3)*sizeof(int));
+#if MEMORY_DEBUG>1
+    fprintf(stderr,"%06d free %d bytes at 0x%x from %s:%d\n",
+         ++memcnt, n, (int)p, zFile,line);
+#endif
+    free(pi);
+  }
+}
+
+/*
+** Resize a prior allocation.  If p==0, then this routine
+** works just like sqliteMalloc().  If n==0, then this routine
+** works just like sqliteFree().
+*/
+void *sqliteRealloc_(void *oldP, int n, char *zFile, int line){
+  int *oldPi, *pi, k, oldN, oldK;
+  void *p;
+  if( oldP==0 ){
+    return sqliteMalloc_(n,1,zFile,line);
+  }
+  if( n==0 ){
+    sqliteFree_(oldP,zFile,line);
+    return 0;
+  }
+  oldPi = oldP;
+  oldPi -= 2;
+  if( oldPi[0]!=0xdead1122 ){
+    fprintf(stderr,"Low-end memory corruption in realloc at 0x%x\n", (int)p);
+    return 0;
+  }
+  oldN = oldPi[1];
+  oldK = (oldN+sizeof(int)-1)/sizeof(int);
+  if( oldPi[oldK+2]!=0xdead3344 ){
+    fprintf(stderr,"High-end memory corruption in realloc at 0x%x\n", (int)p);
+    return 0;
+  }
+  k = (n + sizeof(int) - 1)/sizeof(int);
+  pi = malloc( (k+3)*sizeof(int) );
+  if( pi==0 ){
+    sqlite_malloc_failed++;
+    return 0;
+  }
+  pi[0] = 0xdead1122;
+  pi[1] = n;
+  pi[k+2] = 0xdead3344;
+  p = &pi[2];
+  memcpy(p, oldP, n>oldN ? oldN : n);
+  if( n>oldN ){
+    memset(&((char*)p)[oldN], 0, n-oldN);
+  }
+  memset(oldPi, 0xab, (oldK+3)*sizeof(int));
+  free(oldPi);
+#if MEMORY_DEBUG>1
+  fprintf(stderr,"%06d realloc %d to %d bytes at 0x%x to 0x%x at %s:%d\n",
+    ++memcnt, oldN, n, (int)oldP, (int)p, zFile, line);
+#endif
+  return p;
+}
+
+/*
+** Make a duplicate of a string into memory obtained from malloc()
+** Free the original string using sqliteFree().
+**
+** This routine is called on all strings that are passed outside of
+** the SQLite library.  That way clients can free the string using free()
+** rather than having to call sqliteFree().
+*/
+void sqliteStrRealloc(char **pz){
+  char *zNew;
+  if( pz==0 || *pz==0 ) return;
+  zNew = malloc( strlen(*pz) + 1 );
+  if( zNew==0 ){
+    sqlite_malloc_failed++;
+    sqliteFree(*pz);
+    *pz = 0;
+  }
+  strcpy(zNew, *pz);
+  sqliteFree(*pz);
+  *pz = zNew;
+}
+
+/*
+** Make a copy of a string in memory obtained from sqliteMalloc()
+*/
+char *sqliteStrDup_(const char *z, char *zFile, int line){
+  char *zNew;
+  if( z==0 ) return 0;
+  zNew = sqliteMalloc_(strlen(z)+1, 0, zFile, line);
+  if( zNew ) strcpy(zNew, z);
+  return zNew;
+}
+char *sqliteStrNDup_(const char *z, int n, char *zFile, int line){
+  char *zNew;
+  if( z==0 ) return 0;
+  zNew = sqliteMalloc_(n+1, 0, zFile, line);
+  if( zNew ){
+    memcpy(zNew, z, n);
+    zNew[n] = 0;
+  }
+  return zNew;
+}
+#endif /* MEMORY_DEBUG */
+
+/*
+** The following versions of malloc() and free() are for use in a
+** normal build.
+*/
+#if !defined(MEMORY_DEBUG)
+
+/*
+** Allocate new memory and set it to zero.  Return NULL if
+** no memory is available.  See also sqliteMallocRaw().
+*/
+void *sqliteMalloc(int n){
+  void *p;
+  if( n==0 ) return 0;
+  p = malloc(n);
+  if( p==0 ){
+    sqlite_malloc_failed++;
+    return 0;
+  }
+  memset(p, 0, n);
+  return p;
+}
+
+/*
+** Allocate new memory but do not set it to zero.  Return NULL if
+** no memory is available.  See also sqliteMalloc().
+*/
+void *sqliteMallocRaw(int n){
+  void *p;
+  if( n==0 ) return 0;
+  p = malloc(n);
+  if( p==0 ){
+    sqlite_malloc_failed++;
+    return 0;
+  }
+  return p;
+}
+
+/*
+** Free memory previously obtained from sqliteMalloc()
+*/
+void sqliteFree(void *p){
+  if( p ){
+    free(p);
+  }
+}
+
+/*
+** Resize a prior allocation.  If p==0, then this routine
+** works just like sqliteMalloc().  If n==0, then this routine
+** works just like sqliteFree().
+*/
+void *sqliteRealloc(void *p, int n){
+  void *p2;
+  if( p==0 ){
+    return sqliteMalloc(n);
+  }
+  if( n==0 ){
+    sqliteFree(p);
+    return 0;
+  }
+  p2 = realloc(p, n);
+  if( p2==0 ){
+    sqlite_malloc_failed++;
+  }
+  return p2;
+}
+
+/*
+** Make a copy of a string in memory obtained from sqliteMalloc()
+*/
+char *sqliteStrDup(const char *z){
+  char *zNew;
+  if( z==0 ) return 0;
+  zNew = sqliteMallocRaw(strlen(z)+1);
+  if( zNew ) strcpy(zNew, z);
+  return zNew;
+}
+char *sqliteStrNDup(const char *z, int n){
+  char *zNew;
+  if( z==0 ) return 0;
+  zNew = sqliteMallocRaw(n+1);
+  if( zNew ){
+    memcpy(zNew, z, n);
+    zNew[n] = 0;
+  }
+  return zNew;
+}
+#endif /* !defined(MEMORY_DEBUG) */
+
+/*
+** Create a string from the 2nd and subsequent arguments (up to the
+** first NULL argument), store the string in memory obtained from
+** sqliteMalloc() and make the pointer indicated by the 1st argument
+** point to that string.
+*/
+void sqliteSetString(char **pz, const char *zFirst, ...){
+  va_list ap;
+  int nByte;
+  const char *z;
+  char *zResult;
+
+  if( pz==0 ) return;
+  nByte = strlen(zFirst) + 1;
+  va_start(ap, zFirst);
+  while( (z = va_arg(ap, const char*))!=0 ){
+    nByte += strlen(z);
+  }
+  va_end(ap);
+  sqliteFree(*pz);
+  *pz = zResult = sqliteMallocRaw( nByte );
+  if( zResult==0 ){
+    return;
+  }
+  strcpy(zResult, zFirst);
+  zResult += strlen(zResult);
+  va_start(ap, zFirst);
+  while( (z = va_arg(ap, const char*))!=0 ){
+    strcpy(zResult, z);
+    zResult += strlen(zResult);
+  }
+  va_end(ap);
+#ifdef MEMORY_DEBUG
+#if MEMORY_DEBUG>1
+  fprintf(stderr,"string at 0x%x is %s\n", (int)*pz, *pz);
+#endif
+#endif
+}
+
+/*
+** Works like sqliteSetString, but each string is now followed by
+** a length integer which specifies how much of the source string 
+** to copy (in bytes).  -1 means use the whole string.
+*/
+void sqliteSetNString(char **pz, ...){
+  va_list ap;
+  int nByte;
+  const char *z;
+  char *zResult;
+  int n;
+
+  if( pz==0 ) return;
+  nByte = 0;
+  va_start(ap, pz);
+  while( (z = va_arg(ap, const char*))!=0 ){
+    n = va_arg(ap, int);
+    if( n<=0 ) n = strlen(z);
+    nByte += n;
+  }
+  va_end(ap);
+  sqliteFree(*pz);
+  *pz = zResult = sqliteMallocRaw( nByte + 1 );
+  if( zResult==0 ) return;
+  va_start(ap, pz);
+  while( (z = va_arg(ap, const char*))!=0 ){
+    n = va_arg(ap, int);
+    if( n<=0 ) n = strlen(z);
+    strncpy(zResult, z, n);
+    zResult += n;
+  }
+  *zResult = 0;
+#ifdef MEMORY_DEBUG
+#if MEMORY_DEBUG>1
+  fprintf(stderr,"string at 0x%x is %s\n", (int)*pz, *pz);
+#endif
+#endif
+  va_end(ap);
+}
+
+/*
+** Convert an SQL-style quoted string into a normal string by removing
+** the quote characters.  The conversion is done in-place.  If the
+** input does not begin with a quote character, then this routine
+** is a no-op.
+**
+** 2002-Feb-14: This routine is extended to remove MS-Access style
+** brackets from around identifers.  For example:  "[a-b-c]" becomes
+** "a-b-c".
+*/
+void sqliteDequote(char *z){
+  int quote;
+  int i, j;
+  if( z==0 ) return;
+  quote = z[0];
+  switch( quote ){
+    case '\'':  break;
+    case '"':   break;
+    case '[':   quote = ']';  break;
+    default:    return;
+  }
+  for(i=1, j=0; z[i]; i++){
+    if( z[i]==quote ){
+      if( z[i+1]==quote ){
+        z[j++] = quote;
+        i++;
+      }else{
+        z[j++] = 0;
+        break;
+      }
+    }else{
+      z[j++] = z[i];
+    }
+  }
+}
+
+/* An array to map all upper-case characters into their corresponding
+** lower-case character. 
+*/
+static unsigned char UpperToLower[] = {
+      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
+     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
+     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
+     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
+    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
+    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
+    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
+    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
+    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
+    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
+    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
+    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
+    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
+    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
+    252,253,254,255
+};
+
+/*
+** This function computes a hash on the name of a keyword.
+** Case is not significant.
+*/
+int sqliteHashNoCase(const char *z, int n){
+  int h = 0;
+  if( n<=0 ) n = strlen(z);
+  while( n > 0  ){
+    h = (h<<3) ^ h ^ UpperToLower[(unsigned char)*z++];
+    n--;
+  }
+  if( h<0 ) h = -h;
+  return h;
+}
+
+/*
+** Some systems have stricmp().  Others have strcasecmp().  Because
+** there is no consistency, we will define our own.
+*/
+int sqliteStrICmp(const char *zLeft, const char *zRight){
+  register unsigned char *a, *b;
+  a = (unsigned char *)zLeft;
+  b = (unsigned char *)zRight;
+  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
+  return *a - *b;
+}
+int sqliteStrNICmp(const char *zLeft, const char *zRight, int N){
+  register unsigned char *a, *b;
+  a = (unsigned char *)zLeft;
+  b = (unsigned char *)zRight;
+  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
+  return N<0 ? 0 : *a - *b;
+}
+
+#if 0  /* NOT USED */
+/* 
+** The sortStrCmp() function below is used to order elements according
+** to the ORDER BY clause of a SELECT.  The sort order is a little different
+** from what one might expect.  This note attempts to describe what is
+** going on.
+**
+** We want the main string comparision function used for sorting to
+** sort both numbers and alphanumeric words into the correct sequence.
+** The same routine should do both without prior knowledge of which
+** type of text the input represents.  It should even work for strings
+** which are a mixture of text and numbers.  (It does not work for
+** numeric substrings in exponential notation, however.)
+**
+** To accomplish this, we keep track of a state number while scanning
+** the two strings.  The states are as follows:
+**
+**    1      Beginning of word
+**    2      Arbitrary text
+**    3      Integer
+**    4      Negative integer
+**    5      Real number
+**    6      Negative real
+**
+** The scan begins in state 1, beginning of word.  Transitions to other
+** states are determined by characters seen, as shown in the following
+** chart:
+**
+**      Current State         Character Seen  New State
+**      --------------------  --------------  -------------------
+**      0 Beginning of word   "-"             3 Negative integer
+**                            digit           2 Integer
+**                            space           0 Beginning of word
+**                            otherwise       1 Arbitrary text
+**
+**      1 Arbitrary text      space           0 Beginning of word
+**                            digit           2 Integer
+**                            otherwise       1 Arbitrary text
+**
+**      2 Integer             space           0 Beginning of word
+**                            "."             4 Real number
+**                            digit           2 Integer
+**                            otherwise       1 Arbitrary text
+**
+**      3 Negative integer    space           0 Beginning of word
+**                            "."             5 Negative Real num
+**                            digit           3 Negative integer
+**                            otherwise       1 Arbitrary text
+**
+**      4 Real number         space           0 Beginning of word
+**                            digit           4 Real number
+**                            otherwise       1 Arbitrary text
+**
+**      5 Negative real num   space           0 Beginning of word
+**                            digit           5 Negative real num
+**                            otherwise       1 Arbitrary text
+**
+** To implement this state machine, we first classify each character
+** into on of the following categories:
+**
+**      0  Text
+**      1  Space
+**      2  Digit
+**      3  "-"
+**      4  "."
+**
+** Given an arbitrary character, the array charClass[] maps that character
+** into one of the atove categories.
+*/
+static const unsigned char charClass[] = {
+        /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
+/* 0x */   0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0,
+/* 1x */   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+/* 2x */   1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 0,
+/* 3x */   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0,
+/* 4x */   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+/* 5x */   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+/* 6x */   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+/* 7x */   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+/* 8x */   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+/* 9x */   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+/* Ax */   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+/* Bx */   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+/* Cx */   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+/* Dx */   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+/* Ex */   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+/* Fx */   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+};
+#define N_CHAR_CLASS 5
+
+/*
+** Given the current state number (0 thru 5), this array figures
+** the new state number given the character class.
+*/
+static const unsigned char stateMachine[] = {
+ /* Text,  Space, Digit, "-", "." */
+      1,      0,    2,    3,   1,      /* State 0: Beginning of word */
+      1,      0,    2,    1,   1,      /* State 1: Arbitrary text */
+      1,      0,    2,    1,   4,      /* State 2: Integer */
+      1,      0,    3,    1,   5,      /* State 3: Negative integer */
+      1,      0,    4,    1,   1,      /* State 4: Real number */
+      1,      0,    5,    1,   1,      /* State 5: Negative real num */
+};
+
+/* This routine does a comparison of two strings.  Case is used only
+** if useCase!=0.  Numeric substrings compare in numerical order for the
+** most part but this routine does not understand exponential notation.
+*/
+static int sortStrCmp(const char *atext, const char *btext, int useCase){
+  register unsigned char *a, *b, *map, ca, cb;
+  int result;
+  register int cclass = 0;
+
+  a = (unsigned char *)atext;
+  b = (unsigned char *)btext;
+  if( useCase ){
+    do{
+      if( (ca= *a++)!=(cb= *b++) ) break;
+      cclass = stateMachine[cclass*N_CHAR_CLASS + charClass[ca]];
+    }while( ca!=0 );
+  }else{
+    map = UpperToLower;
+    do{
+      if( (ca=map[*a++])!=(cb=map[*b++]) ) break;
+      cclass = stateMachine[cclass*N_CHAR_CLASS + charClass[ca]];
+    }while( ca!=0 );
+    if( ca>='[' && ca<='`' ) cb = b[-1];
+    if( cb>='[' && cb<='`' ) ca = a[-1];
+  }
+  switch( cclass ){
+    case 0:
+    case 1: {
+      if( isdigit(ca) && isdigit(cb) ){
+        cclass = 2;
+      }
+      break;
+    }
+    default: {
+      break;
+    }
+  }
+  switch( cclass ){
+    case 2:
+    case 3: {
+      if( isdigit(ca) ){
+        if( isdigit(cb) ){
+          int acnt, bcnt;
+          acnt = bcnt = 0;
+          while( isdigit(*a++) ) acnt++;
+          while( isdigit(*b++) ) bcnt++;
+          result = acnt - bcnt;
+          if( result==0 ) result = ca-cb;
+        }else{
+          result = 1;
+        }
+      }else if( isdigit(cb) ){
+        result = -1;
+      }else if( ca=='.' ){
+        result = 1;
+      }else if( cb=='.' ){
+        result = -1;
+      }else{
+        result = ca - cb;
+        cclass = 2;
+      }
+      if( cclass==3 ) result = -result;
+      break;
+    }
+    case 0:
+    case 1:
+    case 4: {
+      result = ca - cb;
+      break;
+    }
+    case 5: {
+      result = cb - ca;
+    };
+  }
+  return result;
+}
+#endif /* NOT USED */
+
+/*
+** Return TRUE if z is a pure numeric string.  Return FALSE if the
+** string contains any character which is not part of a number.
+**
+** Am empty string is considered numeric.
+*/
+static int sqliteIsNumber(const char *z){
+  if( *z=='-' || *z=='+' ) z++;
+  if( !isdigit(*z) ){
+    return *z==0;
+  }
+  z++;
+  while( isdigit(*z) ){ z++; }
+  if( *z=='.' ){
+    z++;
+    if( !isdigit(*z) ) return 0;
+    while( isdigit(*z) ){ z++; }
+    if( *z=='e' || *z=='E' ){
+      z++;
+      if( *z=='+' || *z=='-' ) z++;
+      if( !isdigit(*z) ) return 0;
+      while( isdigit(*z) ){ z++; }
+    }
+  }
+  return *z==0;
+}
+
+/* This comparison routine is what we use for comparison operations
+** between numeric values in an SQL expression.  "Numeric" is a little
+** bit misleading here.  What we mean is that the strings have a
+** type of "numeric" from the point of view of SQL.  The strings
+** do not necessarily contain numbers.  They could contain text.
+**
+** If the input strings both look like actual numbers then they
+** compare in numerical order.  Numerical strings are always less 
+** than non-numeric strings so if one input string looks like a
+** number and the other does not, then the one that looks like
+** a number is the smaller.  Non-numeric strings compare in 
+** lexigraphical order (the same order as strcmp()).
+*/
+int sqliteCompare(const char *atext, const char *btext){
+  int result;
+  int isNumA, isNumB;
+  if( atext==0 ){
+    return -1;
+  }else if( btext==0 ){
+    return 1;
+  }
+  isNumA = sqliteIsNumber(atext);
+  isNumB = sqliteIsNumber(btext);
+  if( isNumA ){
+    if( !isNumB ){
+      result = -1;
+    }else{
+      double rA, rB;
+      rA = atof(atext);
+      rB = atof(btext);
+      if( rA<rB ){
+        result = -1;
+      }else if( rA>rB ){
+        result = +1;
+      }else{
+        result = 0;
+      }
+    }
+  }else if( isNumB ){
+    result = +1;
+  }else {
+    result = strcmp(atext, btext);
+  }
+  return result; 
+}
+
+/*
+** This routine is used for sorting.  Each key is a list of one or more
+** null-terminated elements.  The list is terminated by two nulls in
+** a row.  For example, the following text is a key with three elements
+**
+**            Aone\000Dtwo\000Athree\000\000
+**
+** All elements begin with one of the characters "+-AD" and end with "\000"
+** with zero or more text elements in between.  Except, NULL elements
+** consist of the special two-character sequence "N\000".
+**
+** Both arguments will have the same number of elements.  This routine
+** returns negative, zero, or positive if the first argument is less
+** than, equal to, or greater than the first.  (Result is a-b).
+**
+** Each element begins with one of the characters "+", "-", "A", "D".
+** This character determines the sort order and collating sequence:
+**
+**     +      Sort numerically in ascending order
+**     -      Sort numerically in descending order
+**     A      Sort as strings in ascending order
+**     D      Sort as strings in descending order.
+**
+** For the "+" and "-" sorting, pure numeric strings (strings for which the
+** isNum() function above returns TRUE) always compare less than strings
+** that are not pure numerics.  Non-numeric strings compare in memcmp()
+** order.  This is the same sort order as the sqliteCompare() function
+** above generates.
+**
+** The last point is a change from version 2.6.3 to version 2.7.0.  In
+** version 2.6.3 and earlier, substrings of digits compare in numerical 
+** and case was used only to break a tie.
+**
+** Elements that begin with 'A' or 'D' compare in memcmp() order regardless
+** of whether or not they look like a number.
+**
+** Note that the sort order imposed by the rules above is the same
+** from the ordering defined by the "<", "<=", ">", and ">=" operators
+** of expressions and for indices.  This was not the case for version
+** 2.6.3 and earlier.
+*/
+int sqliteSortCompare(const char *a, const char *b){
+  int len;
+  int res = 0;
+  int isNumA, isNumB;
+  int dir = 0;
+
+  while( res==0 && *a && *b ){
+    if( a[0]=='N' || b[0]=='N' ){
+      if( a[0]==b[0] ){
+        a += 2;
+        b += 2;
+        continue;
+      }
+      if( a[0]=='N' ){
+        dir = b[0];
+        res = -1;
+      }else{
+        dir = a[0];
+        res = +1;
+      }
+      break;
+    }
+    assert( a[0]==b[0] );
+    if( (dir=a[0])=='A' || a[0]=='D' ){
+      res = strcmp(&a[1],&b[1]);
+      if( res ) break;
+    }else{
+      isNumA = sqliteIsNumber(&a[1]);
+      isNumB = sqliteIsNumber(&b[1]);
+      if( isNumA ){
+        double rA, rB;
+        if( !isNumB ){
+          res = -1;
+          break;
+        }
+        rA = atof(&a[1]);
+        rB = atof(&b[1]);
+        if( rA<rB ){
+          res = -1;
+          break;
+        }
+        if( rA>rB ){
+          res = +1;
+          break;
+        }
+      }else if( isNumB ){
+        res = +1;
+        break;
+      }else{
+        res = strcmp(&a[1],&b[1]);
+        if( res ) break;
+      }
+    }
+    len = strlen(&a[1]) + 2;
+    a += len;
+    b += len;
+  }
+  if( dir=='-' || dir=='D' ) res = -res;
+  return res;
+}
+
+/*
+** Some powers of 64.  These constants are needed in the
+** sqliteRealToSortable() routine below.
+*/
+#define _64e3  (64.0 * 64.0 * 64.0)
+#define _64e4  (64.0 * 64.0 * 64.0 * 64.0)
+#define _64e15 (_64e3 * _64e4 * _64e4 * _64e4)
+#define _64e16 (_64e4 * _64e4 * _64e4 * _64e4)
+#define _64e63 (_64e15 * _64e16 * _64e16 * _64e16)
+#define _64e64 (_64e16 * _64e16 * _64e16 * _64e16)
+
+/*
+** The following procedure converts a double-precision floating point
+** number into a string.  The resulting string has the property that
+** two such strings comparied using strcmp() or memcmp() will give the
+** same results as a numeric comparison of the original floating point
+** numbers.
+**
+** This routine is used to generate database keys from floating point
+** numbers such that the keys sort in the same order as the original
+** floating point numbers even though the keys are compared using
+** memcmp().
+**
+** The calling function should have allocated at least 14 characters
+** of space for the buffer z[].
+*/
+void sqliteRealToSortable(double r, char *z){
+  int neg;
+  int exp;
+  int cnt = 0;
+
+  /* This array maps integers between 0 and 63 into base-64 digits.
+  ** The digits must be chosen such at their ASCII codes are increasing.
+  ** This means we can not use the traditional base-64 digit set. */
+  static const char zDigit[] = 
+     "0123456789"
+     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+     "abcdefghijklmnopqrstuvwxyz"
+     "|~";
+  if( r<0.0 ){
+    neg = 1;
+    r = -r;
+    *z++ = '-';
+  } else {
+    neg = 0;
+    *z++ = '0';
+  }
+  exp = 0;
+
+  if( r==0.0 ){
+    exp = -1024;
+  }else if( r<(0.5/64.0) ){
+    while( r < 0.5/_64e64 && exp > -961  ){ r *= _64e64;  exp -= 64; }
+    while( r < 0.5/_64e16 && exp > -1009 ){ r *= _64e16;  exp -= 16; }
+    while( r < 0.5/_64e4  && exp > -1021 ){ r *= _64e4;   exp -= 4; }
+    while( r < 0.5/64.0   && exp > -1024 ){ r *= 64.0;    exp -= 1; }
+  }else if( r>=0.5 ){
+    while( r >= 0.5*_64e63 && exp < 960  ){ r *= 1.0/_64e64; exp += 64; }
+    while( r >= 0.5*_64e15 && exp < 1008 ){ r *= 1.0/_64e16; exp += 16; }
+    while( r >= 0.5*_64e3  && exp < 1020 ){ r *= 1.0/_64e4;  exp += 4; }
+    while( r >= 0.5        && exp < 1023 ){ r *= 1.0/64.0;   exp += 1; }
+  }
+  if( neg ){
+    exp = -exp;
+    r = -r;
+  }
+  exp += 1024;
+  r += 0.5;
+  if( exp<0 ) return;
+  if( exp>=2048 || r>=1.0 ){
+    strcpy(z, "~~~~~~~~~~~~");
+    return;
+  }
+  *z++ = zDigit[(exp>>6)&0x3f];
+  *z++ = zDigit[exp & 0x3f];
+  while( r>0.0 && cnt<10 ){
+    int digit;
+    r *= 64.0;
+    digit = (int)r;
+    assert( digit>=0 && digit<64 );
+    *z++ = zDigit[digit & 0x3f];
+    r -= digit;
+    cnt++;
+  }
+  *z = 0;
+}
+
+#ifdef SQLITE_UTF8
+/*
+** X is a pointer to the first byte of a UTF-8 character.  Increment
+** X so that it points to the next character.  This only works right
+** if X points to a well-formed UTF-8 string.
+*/
+#define sqliteNextChar(X)  while( (0xc0&*++(X))==0x80 ){}
+#define sqliteCharVal(X)   sqlite_utf8_to_int(X)
+
+#else /* !defined(SQLITE_UTF8) */
+/*
+** For iso8859 encoding, the next character is just the next byte.
+*/
+#define sqliteNextChar(X)  (++(X));
+#define sqliteCharVal(X)   ((int)*(X))
+
+#endif /* defined(SQLITE_UTF8) */
+
+
+#ifdef SQLITE_UTF8
+/*
+** Convert the UTF-8 character to which z points into a 31-bit
+** UCS character.  This only works right if z points to a well-formed
+** UTF-8 string.
+*/
+static int sqlite_utf8_to_int(const unsigned char *z){
+  int c;
+  static const int initVal[] = {
+      0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12,  13,  14,
+     15,  16,  17,  18,  19,  20,  21,  22,  23,  24,  25,  26,  27,  28,  29,
+     30,  31,  32,  33,  34,  35,  36,  37,  38,  39,  40,  41,  42,  43,  44,
+     45,  46,  47,  48,  49,  50,  51,  52,  53,  54,  55,  56,  57,  58,  59,
+     60,  61,  62,  63,  64,  65,  66,  67,  68,  69,  70,  71,  72,  73,  74,
+     75,  76,  77,  78,  79,  80,  81,  82,  83,  84,  85,  86,  87,  88,  89,
+     90,  91,  92,  93,  94,  95,  96,  97,  98,  99, 100, 101, 102, 103, 104,
+    105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
+    120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
+    135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
+    150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
+    165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
+    180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,   0,   1,   2,
+      3,   4,   5,   6,   7,   8,   9,  10,  11,  12,  13,  14,  15,  16,  17,
+     18,  19,  20,  21,  22,  23,  24,  25,  26,  27,  28,  29,  30,  31,   0,
+      1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12,  13,  14,  15,
+      0,   1,   2,   3,   4,   5,   6,   7,   0,   1,   2,   3,   0,   1, 254,
+    255,
+  };
+  c = initVal[*(z++)];
+  while( (0xc0&*z)==0x80 ){
+    c = (c<<6) | (0x3f&*(z++));
+  }
+  return c;
+}
+#endif
+
+/*
+** Compare two UTF-8 strings for equality where the first string can
+** potentially be a "glob" expression.  Return true (1) if they
+** are the same and false (0) if they are different.
+**
+** Globbing rules:
+**
+**      '*'       Matches any sequence of zero or more characters.
+**
+**      '?'       Matches exactly one character.
+**
+**     [...]      Matches one character from the enclosed list of
+**                characters.
+**
+**     [^...]     Matches one character not in the enclosed list.
+**
+** With the [...] and [^...] matching, a ']' character can be included
+** in the list by making it the first character after '[' or '^'.  A
+** range of characters can be specified using '-'.  Example:
+** "[a-z]" matches any single lower-case letter.  To match a '-', make
+** it the last character in the list.
+**
+** This routine is usually quick, but can be N**2 in the worst case.
+**
+** Hints: to match '*' or '?', put them in "[]".  Like this:
+**
+**         abc[*]xyz        Matches "abc*xyz" only
+*/
+int 
+sqliteGlobCompare(const unsigned char *zPattern, const unsigned char *zString){
+  register int c;
+  int invert;
+  int seen;
+  int c2;
+
+  while( (c = *zPattern)!=0 ){
+    switch( c ){
+      case '*':
+        while( (c=zPattern[1]) == '*' || c == '?' ){
+          if( c=='?' ){
+            if( *zString==0 ) return 0;
+            sqliteNextChar(zString);
+          }
+          zPattern++;
+        }
+        if( c==0 ) return 1;
+        if( c=='[' ){
+          while( *zString && sqliteGlobCompare(&zPattern[1],zString)==0 ){
+            sqliteNextChar(zString);
+          }
+          return *zString!=0;
+        }else{
+          while( (c2 = *zString)!=0 ){
+            while( c2 != 0 && c2 != c ){ c2 = *++zString; }
+            if( c2==0 ) return 0;
+            if( sqliteGlobCompare(&zPattern[1],zString) ) return 1;
+            sqliteNextChar(zString);
+          }
+          return 0;
+        }
+      case '?': {
+        if( *zString==0 ) return 0;
+        sqliteNextChar(zString);
+        zPattern++;
+        break;
+      }
+      case '[': {
+        int prior_c = 0;
+        seen = 0;
+        invert = 0;
+        c = sqliteCharVal(zString);
+        if( c==0 ) return 0;
+        c2 = *++zPattern;
+        if( c2=='^' ){ invert = 1; c2 = *++zPattern; }
+        if( c2==']' ){
+          if( c==']' ) seen = 1;
+          c2 = *++zPattern;
+        }
+        while( (c2 = sqliteCharVal(zPattern))!=0 && c2!=']' ){
+          if( c2=='-' && zPattern[1]!=']' && zPattern[1]!=0 && prior_c>0 ){
+            zPattern++;
+            c2 = sqliteCharVal(zPattern);
+            if( c>=prior_c && c<=c2 ) seen = 1;
+            prior_c = 0;
+          }else if( c==c2 ){
+            seen = 1;
+            prior_c = c2;
+          }else{
+            prior_c = c2;
+          }
+          sqliteNextChar(zPattern);
+        }
+        if( c2==0 || (seen ^ invert)==0 ) return 0;
+        sqliteNextChar(zString);
+        zPattern++;
+        break;
+      }
+      default: {
+        if( c != *zString ) return 0;
+        zPattern++;
+        zString++;
+        break;
+      }
+    }
+  }
+  return *zString==0;
+}
+
+/*
+** Compare two UTF-8 strings for equality using the "LIKE" operator of
+** SQL.  The '%' character matches any sequence of 0 or more
+** characters and '_' matches any single character.  Case is
+** not significant.
+**
+** This routine is just an adaptation of the sqliteGlobCompare()
+** routine above.
+*/
+int 
+sqliteLikeCompare(const unsigned char *zPattern, const unsigned char *zString){
+  register int c;
+  int c2;
+
+  while( (c = UpperToLower[*zPattern])!=0 ){
+    switch( c ){
+      case '%': {
+        while( (c=zPattern[1]) == '%' || c == '_' ){
+          if( c=='_' ){
+            if( *zString==0 ) return 0;
+            sqliteNextChar(zString);
+          }
+          zPattern++;
+        }
+        if( c==0 ) return 1;
+        c = UpperToLower[c];
+        while( (c2=UpperToLower[*zString])!=0 ){
+          while( c2 != 0 && c2 != c ){ c2 = UpperToLower[*++zString]; }
+          if( c2==0 ) return 0;
+          if( sqliteLikeCompare(&zPattern[1],zString) ) return 1;
+          sqliteNextChar(zString);
+        }
+        return 0;
+      }
+      case '_': {
+        if( *zString==0 ) return 0;
+        sqliteNextChar(zString);
+        zPattern++;
+        break;
+      }
+      default: {
+        if( c != UpperToLower[*zString] ) return 0;
+        zPattern++;
+        zString++;
+        break;
+      }
+    }
+  }
+  return *zString==0;
+}
+
+/*
+** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
+** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
+** when this routine is called.
+**
+** This routine is a attempt to detect if two threads use the
+** same sqlite* pointer at the same time.  There is a race 
+** condition so it is possible that the error is not detected.
+** But usually the problem will be seen.  The result will be an
+** error which can be used to debug the application that is
+** using SQLite incorrectly.
+**
+** Ticket #202:  If db->magic is not a valid open value, take care not
+** to modify the db structure at all.  It could be that db is a stale
+** pointer.  In other words, it could be that there has been a prior
+** call to sqlite_close(db) and db has been deallocated.  And we do
+** not want to write into deallocated memory.
+*/
+int sqliteSafetyOn(sqlite *db){
+  if( db->magic==SQLITE_MAGIC_OPEN ){
+    db->magic = SQLITE_MAGIC_BUSY;
+    return 0;
+  }else if( db->magic==SQLITE_MAGIC_BUSY || db->magic==SQLITE_MAGIC_ERROR
+             || db->want_to_close ){
+    db->magic = SQLITE_MAGIC_ERROR;
+    db->flags |= SQLITE_Interrupt;
+  }
+  return 1;
+}
+
+/*
+** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
+** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
+** when this routine is called.
+*/
+int sqliteSafetyOff(sqlite *db){
+  if( db->magic==SQLITE_MAGIC_BUSY ){
+    db->magic = SQLITE_MAGIC_OPEN;
+    return 0;
+  }else if( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ERROR
+             || db->want_to_close ){
+    db->magic = SQLITE_MAGIC_ERROR;
+    db->flags |= SQLITE_Interrupt;
+  }
+  return 1;
+}
+
+/*
+** Check to make sure we are not currently executing an sqlite_exec().
+** If we are currently in an sqlite_exec(), return true and set
+** sqlite.magic to SQLITE_MAGIC_ERROR.  This will cause a complete
+** shutdown of the database.
+**
+** This routine is used to try to detect when API routines are called
+** at the wrong time or in the wrong sequence.
+*/
+int sqliteSafetyCheck(sqlite *db){
+  if( db->pVdbe!=0 ){
+    db->magic = SQLITE_MAGIC_ERROR;
+    return 1;
+  }
+  return 0;
+}
diff --git a/ext/sqlite/libsqlite/src/vdbe.c b/ext/sqlite/libsqlite/src/vdbe.c
new file mode 100644 (file)
index 0000000..f9b9482
--- /dev/null
@@ -0,0 +1,5748 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** The code in this file implements the Virtual Database Engine (VDBE)
+**
+** The SQL parser generates a program which is then executed by
+** the VDBE to do the work of the SQL statement.  VDBE programs are 
+** similar in form to assembly language.  The program consists of
+** a linear sequence of operations.  Each operation has an opcode 
+** and 3 operands.  Operands P1 and P2 are integers.  Operand P3 
+** is a null-terminated string.   The P2 operand must be non-negative.
+** Opcodes will typically ignore one or more operands.  Many opcodes
+** ignore all three operands.
+**
+** Computation results are stored on a stack.  Each entry on the
+** stack is either an integer, a null-terminated string, a floating point
+** number, or the SQL "NULL" value.  An inplicit conversion from one
+** type to the other occurs as necessary.
+** 
+** Most of the code in this file is taken up by the sqliteVdbeExec()
+** function which does the work of interpreting a VDBE program.
+** But other routines are also provided to help in building up
+** a program instruction by instruction.
+**
+** Various scripts scan this source file in order to generate HTML
+** documentation, headers files, or other derived files.  The formatting
+** of the code in this file is, therefore, important.  See other comments
+** in this file for details.  If in doubt, do not deviate from existing
+** commenting and indentation practices when changing or adding code.
+**
+** $Id$
+*/
+#include "sqliteInt.h"
+#include <ctype.h>
+
+/*
+** The makefile scans this source file and creates the following
+** array of string constants which are the names of all VDBE opcodes.
+** This array is defined in a separate source code file named opcode.c
+** which is automatically generated by the makefile.
+*/
+extern char *sqliteOpcodeNames[];
+
+/*
+** The following global variable is incremented every time a cursor
+** moves, either by the OP_MoveTo or the OP_Next opcode.  The test
+** procedures use this information to make sure that indices are
+** working correctly.  This variable has no function other than to
+** help verify the correct operation of the library.
+*/
+int sqlite_search_count = 0;
+
+/*
+** SQL is translated into a sequence of instructions to be
+** executed by a virtual machine.  Each instruction is an instance
+** of the following structure.
+*/
+typedef struct VdbeOp Op;
+
+/*
+** Boolean values
+*/
+typedef unsigned char Bool;
+
+/*
+** A cursor is a pointer into a single BTree within a database file.
+** The cursor can seek to a BTree entry with a particular key, or
+** loop over all entries of the Btree.  You can also insert new BTree
+** entries or retrieve the key or data from the entry that the cursor
+** is currently pointing to.
+** 
+** Every cursor that the virtual machine has open is represented by an
+** instance of the following structure.
+*/
+struct Cursor {
+  BtCursor *pCursor;    /* The cursor structure of the backend */
+  int lastRecno;        /* Last recno from a Next or NextIdx operation */
+  int nextRowid;        /* Next rowid returned by OP_NewRowid */
+  Bool recnoIsValid;    /* True if lastRecno is valid */
+  Bool keyAsData;       /* The OP_Column command works on key instead of data */
+  Bool atFirst;         /* True if pointing to first entry */
+  Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
+  Bool nullRow;         /* True if pointing to a row with no data */
+  Bool nextRowidValid;  /* True if the nextRowid field is valid */
+  Btree *pBt;           /* Separate file holding temporary table */
+};
+typedef struct Cursor Cursor;
+
+/*
+** A sorter builds a list of elements to be sorted.  Each element of
+** the list is an instance of the following structure.
+*/
+typedef struct Sorter Sorter;
+struct Sorter {
+  int nKey;           /* Number of bytes in the key */
+  char *zKey;         /* The key by which we will sort */
+  int nData;          /* Number of bytes in the data */
+  char *pData;        /* The data associated with this key */
+  Sorter *pNext;      /* Next in the list */
+};
+
+/* 
+** Number of buckets used for merge-sort.  
+*/
+#define NSORT 30
+
+/*
+** Number of bytes of string storage space available to each stack
+** layer without having to malloc.  NBFS is short for Number of Bytes
+** For Strings.
+*/
+#define NBFS 32
+
+/*
+** A single level of the stack is an instance of the following
+** structure.  Except, string values are stored on a separate
+** list of of pointers to character.  The reason for storing
+** strings separately is so that they can be easily passed
+** to the callback function.
+*/
+struct Stack {
+  int i;         /* Integer value */
+  int n;         /* Number of characters in string value, including '\0' */
+  int flags;     /* Some combination of STK_Null, STK_Str, STK_Dyn, etc. */
+  double r;      /* Real value */
+  char z[NBFS];  /* Space for short strings */
+};
+typedef struct Stack Stack;
+
+/*
+** Memory cells use the same structure as the stack except that space
+** for an arbitrary string is added.
+*/
+struct Mem {
+  Stack s;       /* All values of the memory cell besides string */
+  char *z;       /* String value for this memory cell */
+};
+typedef struct Mem Mem;
+
+/*
+** Allowed values for Stack.flags
+*/
+#define STK_Null      0x0001   /* Value is NULL */
+#define STK_Str       0x0002   /* Value is a string */
+#define STK_Int       0x0004   /* Value is an integer */
+#define STK_Real      0x0008   /* Value is a real number */
+#define STK_Dyn       0x0010   /* Need to call sqliteFree() on zStack[] */
+#define STK_Static    0x0020   /* zStack[] points to a static string */
+#define STK_Ephem     0x0040   /* zStack[] points to an ephemeral string */
+
+/* The following STK_ value appears only in AggElem.aMem.s.flag fields.
+** It indicates that the corresponding AggElem.aMem.z points to a
+** aggregate function context that needs to be finalized.
+*/
+#define STK_AggCtx    0x0040   /* zStack[] points to an agg function context */
+
+/*
+** The "context" argument for a installable function.  A pointer to an
+** instance of this structure is the first argument to the routines used
+** implement the SQL functions.
+**
+** There is a typedef for this structure in sqlite.h.  So all routines,
+** even the public interface to SQLite, can use a pointer to this structure.
+** But this file is the only place where the internal details of this
+** structure are known.
+**
+** This structure is defined inside of vdbe.c because it uses substructures
+** (Stack) which are only defined there.
+*/
+struct sqlite_func {
+  FuncDef *pFunc;   /* Pointer to function information.  MUST BE FIRST */
+  Stack s;          /* Small strings, ints, and double values go here */
+  char *z;          /* Space for holding dynamic string results */
+  void *pAgg;       /* Aggregate context */
+  u8 isError;       /* Set to true for an error */
+  u8 isStep;        /* Current in the step function */
+  int cnt;          /* Number of times that the step function has been called */
+};
+
+/*
+** An Agg structure describes an Aggregator.  Each Agg consists of
+** zero or more Aggregator elements (AggElem).  Each AggElem contains
+** a key and one or more values.  The values are used in processing
+** aggregate functions in a SELECT.  The key is used to implement
+** the GROUP BY clause of a select.
+*/
+typedef struct Agg Agg;
+typedef struct AggElem AggElem;
+struct Agg {
+  int nMem;            /* Number of values stored in each AggElem */
+  AggElem *pCurrent;   /* The AggElem currently in focus */
+  HashElem *pSearch;   /* The hash element for pCurrent */
+  Hash hash;           /* Hash table of all aggregate elements */
+  FuncDef **apFunc;    /* Information about aggregate functions */
+};
+struct AggElem {
+  char *zKey;          /* The key to this AggElem */
+  int nKey;            /* Number of bytes in the key, including '\0' at end */
+  Mem aMem[1];         /* The values for this AggElem */
+};
+
+/*
+** A Set structure is used for quick testing to see if a value
+** is part of a small set.  Sets are used to implement code like
+** this:
+**            x.y IN ('hi','hoo','hum')
+*/
+typedef struct Set Set;
+struct Set {
+  Hash hash;             /* A set is just a hash table */
+  HashElem *prev;        /* Previously accessed hash elemen */
+};
+
+/*
+** A Keylist is a bunch of keys into a table.  The keylist can
+** grow without bound.  The keylist stores the ROWIDs of database
+** records that need to be deleted or updated.
+*/
+typedef struct Keylist Keylist;
+struct Keylist {
+  int nKey;         /* Number of slots in aKey[] */
+  int nUsed;        /* Next unwritten slot in aKey[] */
+  int nRead;        /* Next unread slot in aKey[] */
+  Keylist *pNext;   /* Next block of keys */
+  int aKey[1];      /* One or more keys.  Extra space allocated as needed */
+};
+
+/*
+** An instance of the virtual machine.  This structure contains the complete
+** state of the virtual machine.
+**
+** The "sqlite_vm" structure pointer that is returned by sqlite_compile()
+** is really a pointer to an instance of this structure.
+*/
+struct Vdbe {
+  sqlite *db;         /* The whole database */
+  Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
+  Btree *pBt;         /* Opaque context structure used by DB backend */
+  FILE *trace;        /* Write an execution trace here, if not NULL */
+  int nOp;            /* Number of instructions in the program */
+  int nOpAlloc;       /* Number of slots allocated for aOp[] */
+  Op *aOp;            /* Space to hold the virtual machine's program */
+  int nLabel;         /* Number of labels used */
+  int nLabelAlloc;    /* Number of slots allocated in aLabel[] */
+  int *aLabel;        /* Space to hold the labels */
+  int tos;            /* Index of top of stack */
+  Stack *aStack;      /* The operand stack, except string values */
+  char **zStack;      /* Text or binary values of the stack */
+  char **azColName;   /* Becomes the 4th parameter to callbacks */
+  int nCursor;        /* Number of slots in aCsr[] */
+  Cursor *aCsr;       /* One element of this array for each open cursor */
+  Sorter *pSort;      /* A linked list of objects to be sorted */
+  FILE *pFile;        /* At most one open file handler */
+  int nField;         /* Number of file fields */
+  char **azField;     /* Data for each file field */
+  char *zLine;            /* A single line from the input file */
+  int magic;              /* Magic number for sanity checking */
+  int nLineAlloc;         /* Number of spaces allocated for zLine */
+  int nMem;               /* Number of memory locations currently allocated */
+  Mem *aMem;              /* The memory locations */
+  Agg agg;                /* Aggregate information */
+  int nSet;               /* Number of sets allocated */
+  Set *aSet;              /* An array of sets */
+  int nCallback;          /* Number of callbacks invoked so far */
+  Keylist *pList;         /* A list of ROWIDs */
+  int keylistStackDepth;  /* The size of the "keylist" stack */
+  Keylist **keylistStack; /* The stack used by opcodes ListPush & ListPop */
+  int pc;                 /* The program counter */
+  int rc;                 /* Value to return */
+  unsigned uniqueCnt;     /* Used by OP_MakeRecord when P2!=0 */
+  int errorAction;        /* Recovery action to do in case of an error */
+  int undoTransOnError;   /* If error, either ROLLBACK or COMMIT */
+  int inTempTrans;        /* True if temp database is transactioned */
+  int returnStack[100];   /* Return address stack for OP_Gosub & OP_Return */
+  int returnDepth;        /* Next unused element in returnStack[] */
+  int nResColumn;         /* Number of columns in one row of the result set */
+  char **azResColumn;                        /* Values for one row of result */ 
+  int (*xCallback)(void*,int,char**,char**); /* Callback for SELECT results */
+  void *pCbArg;                              /* First argument to xCallback() */
+  int popStack;           /* Pop the stack this much on entry to VdbeExec() */
+  char *zErrMsg;          /* Error message written here */
+  u8 explain;             /* True if EXPLAIN present on SQL command */
+};
+
+/*
+** The following are allowed values for Vdbe.magic
+*/
+#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
+#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
+#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
+#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
+
+/*
+** When debugging the code generator in a symbolic debugger, one can
+** set the sqlite_vdbe_addop_trace to 1 and all opcodes will be printed
+** as they are added to the instruction stream.
+*/
+#ifndef NDEBUG
+int sqlite_vdbe_addop_trace = 0;
+static void vdbePrintOp(FILE*, int, Op*);
+#endif
+
+/*
+** Create a new virtual database engine.
+*/
+Vdbe *sqliteVdbeCreate(sqlite *db){
+  Vdbe *p;
+  p = sqliteMalloc( sizeof(Vdbe) );
+  if( p==0 ) return 0;
+  p->pBt = db->pBe;
+  p->db = db;
+  if( db->pVdbe ){
+    db->pVdbe->pPrev = p;
+  }
+  p->pNext = db->pVdbe;
+  p->pPrev = 0;
+  db->pVdbe = p;
+  p->magic = VDBE_MAGIC_INIT;
+  return p;
+}
+
+/*
+** Turn tracing on or off
+*/
+void sqliteVdbeTrace(Vdbe *p, FILE *trace){
+  p->trace = trace;
+}
+
+/*
+** Add a new instruction to the list of instructions current in the
+** VDBE.  Return the address of the new instruction.
+**
+** Parameters:
+**
+**    p               Pointer to the VDBE
+**
+**    op              The opcode for this instruction
+**
+**    p1, p2          First two of the three possible operands.
+**
+** Use the sqliteVdbeResolveLabel() function to fix an address and
+** the sqliteVdbeChangeP3() function to change the value of the P3
+** operand.
+*/
+int sqliteVdbeAddOp(Vdbe *p, int op, int p1, int p2){
+  int i;
+
+  i = p->nOp;
+  p->nOp++;
+  assert( p->magic==VDBE_MAGIC_INIT );
+  if( i>=p->nOpAlloc ){
+    int oldSize = p->nOpAlloc;
+    Op *aNew;
+    p->nOpAlloc = p->nOpAlloc*2 + 100;
+    aNew = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
+    if( aNew==0 ){
+      p->nOpAlloc = oldSize;
+      return 0;
+    }
+    p->aOp = aNew;
+    memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
+  }
+  p->aOp[i].opcode = op;
+  p->aOp[i].p1 = p1;
+  if( p2<0 && (-1-p2)<p->nLabel && p->aLabel[-1-p2]>=0 ){
+    p2 = p->aLabel[-1-p2];
+  }
+  p->aOp[i].p2 = p2;
+  p->aOp[i].p3 = 0;
+  p->aOp[i].p3type = P3_NOTUSED;
+#ifndef NDEBUG
+  if( sqlite_vdbe_addop_trace ) vdbePrintOp(0, i, &p->aOp[i]);
+#endif
+  return i;
+}
+
+/*
+** Create a new symbolic label for an instruction that has yet to be
+** coded.  The symbolic label is really just a negative number.  The
+** label can be used as the P2 value of an operation.  Later, when
+** the label is resolved to a specific address, the VDBE will scan
+** through its operation list and change all values of P2 which match
+** the label into the resolved address.
+**
+** The VDBE knows that a P2 value is a label because labels are
+** always negative and P2 values are suppose to be non-negative.
+** Hence, a negative P2 value is a label that has yet to be resolved.
+*/
+int sqliteVdbeMakeLabel(Vdbe *p){
+  int i;
+  i = p->nLabel++;
+  assert( p->magic==VDBE_MAGIC_INIT );
+  if( i>=p->nLabelAlloc ){
+    int *aNew;
+    p->nLabelAlloc = p->nLabelAlloc*2 + 10;
+    aNew = sqliteRealloc( p->aLabel, p->nLabelAlloc*sizeof(p->aLabel[0]));
+    if( aNew==0 ){
+      sqliteFree(p->aLabel);
+    }
+    p->aLabel = aNew;
+  }
+  if( p->aLabel==0 ){
+    p->nLabel = 0;
+    p->nLabelAlloc = 0;
+    return 0;
+  }
+  p->aLabel[i] = -1;
+  return -1-i;
+}
+
+/*
+** Resolve label "x" to be the address of the next instruction to
+** be inserted.  The parameter "x" must have been obtained from
+** a prior call to sqliteVdbeMakeLabel().
+*/
+void sqliteVdbeResolveLabel(Vdbe *p, int x){
+  int j;
+  assert( p->magic==VDBE_MAGIC_INIT );
+  if( x<0 && (-x)<=p->nLabel && p->aOp ){
+    if( p->aLabel[-1-x]==p->nOp ) return;
+    assert( p->aLabel[-1-x]<0 );
+    p->aLabel[-1-x] = p->nOp;
+    for(j=0; j<p->nOp; j++){
+      if( p->aOp[j].p2==x ) p->aOp[j].p2 = p->nOp;
+    }
+  }
+}
+
+/*
+** Return the address of the next instruction to be inserted.
+*/
+int sqliteVdbeCurrentAddr(Vdbe *p){
+  assert( p->magic==VDBE_MAGIC_INIT );
+  return p->nOp;
+}
+
+/*
+** Add a whole list of operations to the operation stack.  Return the
+** address of the first operation added.
+*/
+int sqliteVdbeAddOpList(Vdbe *p, int nOp, VdbeOp const *aOp){
+  int addr;
+  assert( p->magic==VDBE_MAGIC_INIT );
+  if( p->nOp + nOp >= p->nOpAlloc ){
+    int oldSize = p->nOpAlloc;
+    Op *aNew;
+    p->nOpAlloc = p->nOpAlloc*2 + nOp + 10;
+    aNew = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
+    if( aNew==0 ){
+      p->nOpAlloc = oldSize;
+      return 0;
+    }
+    p->aOp = aNew;
+    memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
+  }
+  addr = p->nOp;
+  if( nOp>0 ){
+    int i;
+    for(i=0; i<nOp; i++){
+      int p2 = aOp[i].p2;
+      p->aOp[i+addr] = aOp[i];
+      if( p2<0 ) p->aOp[i+addr].p2 = addr + ADDR(p2);
+      p->aOp[i+addr].p3type = aOp[i].p3 ? P3_STATIC : P3_NOTUSED;
+#ifndef NDEBUG
+      if( sqlite_vdbe_addop_trace ) vdbePrintOp(0, i+addr, &p->aOp[i+addr]);
+#endif
+    }
+    p->nOp += nOp;
+  }
+  return addr;
+}
+
+/*
+** Change the value of the P1 operand for a specific instruction.
+** This routine is useful when a large program is loaded from a
+** static array using sqliteVdbeAddOpList but we want to make a
+** few minor changes to the program.
+*/
+void sqliteVdbeChangeP1(Vdbe *p, int addr, int val){
+  assert( p->magic==VDBE_MAGIC_INIT );
+  if( p && addr>=0 && p->nOp>addr && p->aOp ){
+    p->aOp[addr].p1 = val;
+  }
+}
+
+/*
+** Change the value of the P2 operand for a specific instruction.
+** This routine is useful for setting a jump destination.
+*/
+void sqliteVdbeChangeP2(Vdbe *p, int addr, int val){
+  assert( val>=0 );
+  assert( p->magic==VDBE_MAGIC_INIT );
+  if( p && addr>=0 && p->nOp>addr && p->aOp ){
+    p->aOp[addr].p2 = val;
+  }
+}
+
+/*
+** Change the value of the P3 operand for a specific instruction.
+** This routine is useful when a large program is loaded from a
+** static array using sqliteVdbeAddOpList but we want to make a
+** few minor changes to the program.
+**
+** If n>=0 then the P3 operand is dynamic, meaning that a copy of
+** the string is made into memory obtained from sqliteMalloc().
+** A value of n==0 means copy bytes of zP3 up to and including the
+** first null byte.  If n>0 then copy n+1 bytes of zP3.
+**
+** If n==P3_STATIC  it means that zP3 is a pointer to a constant static
+** string and we can just copy the pointer.  n==P3_POINTER means zP3 is
+** a pointer to some object other than a string.
+**
+** If addr<0 then change P3 on the most recently inserted instruction.
+*/
+void sqliteVdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
+  Op *pOp;
+  assert( p->magic==VDBE_MAGIC_INIT );
+  if( p==0 || p->aOp==0 ) return;
+  if( addr<0 || addr>=p->nOp ){
+    addr = p->nOp - 1;
+    if( addr<0 ) return;
+  }
+  pOp = &p->aOp[addr];
+  if( pOp->p3 && pOp->p3type==P3_DYNAMIC ){
+    sqliteFree(pOp->p3);
+    pOp->p3 = 0;
+  }
+  if( zP3==0 ){
+    pOp->p3 = 0;
+    pOp->p3type = P3_NOTUSED;
+  }else if( n<0 ){
+    pOp->p3 = (char*)zP3;
+    pOp->p3type = n;
+  }else{
+    sqliteSetNString(&pOp->p3, zP3, n, 0);
+    pOp->p3type = P3_DYNAMIC;
+  }
+}
+
+/*
+** If the P3 operand to the specified instruction appears
+** to be a quoted string token, then this procedure removes 
+** the quotes.
+**
+** The quoting operator can be either a grave ascent (ASCII 0x27)
+** or a double quote character (ASCII 0x22).  Two quotes in a row
+** resolve to be a single actual quote character within the string.
+*/
+void sqliteVdbeDequoteP3(Vdbe *p, int addr){
+  Op *pOp;
+  assert( p->magic==VDBE_MAGIC_INIT );
+  if( p->aOp==0 || addr<0 || addr>=p->nOp ) return;
+  pOp = &p->aOp[addr];
+  if( pOp->p3==0 || pOp->p3[0]==0 ) return;
+  if( pOp->p3type==P3_POINTER ) return;
+  if( pOp->p3type!=P3_DYNAMIC ){
+    pOp->p3 = sqliteStrDup(pOp->p3);
+    pOp->p3type = P3_DYNAMIC;
+  }
+  sqliteDequote(pOp->p3);
+}
+
+/*
+** On the P3 argument of the given instruction, change all
+** strings of whitespace characters into a single space and
+** delete leading and trailing whitespace.
+*/
+void sqliteVdbeCompressSpace(Vdbe *p, int addr){
+  char *z;
+  int i, j;
+  Op *pOp;
+  assert( p->magic==VDBE_MAGIC_INIT );
+  if( p->aOp==0 || addr<0 || addr>=p->nOp ) return;
+  pOp = &p->aOp[addr];
+  if( pOp->p3type==P3_POINTER ){
+    return;
+  }
+  if( pOp->p3type!=P3_DYNAMIC ){
+    pOp->p3 = sqliteStrDup(pOp->p3);
+    pOp->p3type = P3_DYNAMIC;
+  }
+  z = pOp->p3;
+  if( z==0 ) return;
+  i = j = 0;
+  while( isspace(z[i]) ){ i++; }
+  while( z[i] ){
+    if( isspace(z[i]) ){
+      z[j++] = ' ';
+      while( isspace(z[++i]) ){}
+    }else{
+      z[j++] = z[i++];
+    }
+  }
+  while( j>0 && isspace(z[j-1]) ){ j--; }
+  z[j] = 0;
+}
+
+/*
+** Search for the current program for the given opcode and P2
+** value.  Return 1 if found and 0 if not found.
+*/
+int sqliteVdbeFindOp(Vdbe *p, int op, int p2){
+  int i;
+  assert( p->magic==VDBE_MAGIC_INIT );
+  for(i=0; i<p->nOp; i++){
+    if( p->aOp[i].opcode==op && p->aOp[i].p2==p2 ) return 1;
+  }
+  return 0;
+}
+
+/*
+** The following group or routines are employed by installable functions
+** to return their results.
+**
+** The sqlite_set_result_string() routine can be used to return a string
+** value or to return a NULL.  To return a NULL, pass in NULL for zResult.
+** A copy is made of the string before this routine returns so it is safe
+** to pass in an ephemeral string.
+**
+** sqlite_set_result_error() works like sqlite_set_result_string() except
+** that it signals a fatal error.  The string argument, if any, is the
+** error message.  If the argument is NULL a generic substitute error message
+** is used.
+**
+** The sqlite_set_result_int() and sqlite_set_result_double() set the return
+** value of the user function to an integer or a double.
+**
+** These routines are defined here in vdbe.c because they depend on knowing
+** the internals of the sqlite_func structure which is only defined in 
+** this source file.
+*/
+char *sqlite_set_result_string(sqlite_func *p, const char *zResult, int n){
+  assert( !p->isStep );
+  if( p->s.flags & STK_Dyn ){
+    sqliteFree(p->z);
+  }
+  if( zResult==0 ){
+    p->s.flags = STK_Null;
+    n = 0;
+    p->z = 0;
+    p->s.n = 0;
+  }else{
+    if( n<0 ) n = strlen(zResult);
+    if( n<NBFS-1 ){
+      memcpy(p->s.z, zResult, n);
+      p->s.z[n] = 0;
+      p->s.flags = STK_Str;
+      p->z = p->s.z;
+    }else{
+      p->z = sqliteMallocRaw( n+1 );
+      if( p->z ){
+        memcpy(p->z, zResult, n);
+        p->z[n] = 0;
+      }
+      p->s.flags = STK_Str | STK_Dyn;
+    }
+    p->s.n = n+1;
+  }
+  return p->z;
+}
+void sqlite_set_result_int(sqlite_func *p, int iResult){
+  assert( !p->isStep );
+  if( p->s.flags & STK_Dyn ){
+    sqliteFree(p->z);
+  }
+  p->s.i = iResult;
+  p->s.flags = STK_Int;
+}
+void sqlite_set_result_double(sqlite_func *p, double rResult){
+  assert( !p->isStep );
+  if( p->s.flags & STK_Dyn ){
+    sqliteFree(p->z);
+  }
+  p->s.r = rResult;
+  p->s.flags = STK_Real;
+}
+void sqlite_set_result_error(sqlite_func *p, const char *zMsg, int n){
+  assert( !p->isStep );
+  sqlite_set_result_string(p, zMsg, n);
+  p->isError = 1;
+}
+
+/*
+** Extract the user data from a sqlite_func structure and return a
+** pointer to it.
+**
+** This routine is defined here in vdbe.c because it depends on knowing
+** the internals of the sqlite_func structure which is only defined in 
+** this source file.
+*/
+void *sqlite_user_data(sqlite_func *p){
+  assert( p && p->pFunc );
+  return p->pFunc->pUserData;
+}
+
+/*
+** Allocate or return the aggregate context for a user function.  A new
+** context is allocated on the first call.  Subsequent calls return the
+** same context that was returned on prior calls.
+**
+** This routine is defined here in vdbe.c because it depends on knowing
+** the internals of the sqlite_func structure which is only defined in
+** this source file.
+*/
+void *sqlite_aggregate_context(sqlite_func *p, int nByte){
+  assert( p && p->pFunc && p->pFunc->xStep );
+  if( p->pAgg==0 ){
+    if( nByte<=NBFS ){
+      p->pAgg = (void*)p->z;
+    }else{
+      p->pAgg = sqliteMalloc( nByte );
+    }
+  }
+  return p->pAgg;
+}
+
+/*
+** Return the number of times the Step function of a aggregate has been 
+** called.
+**
+** This routine is defined here in vdbe.c because it depends on knowing
+** the internals of the sqlite_func structure which is only defined in
+** this source file.
+*/
+int sqlite_aggregate_count(sqlite_func *p){
+  assert( p && p->pFunc && p->pFunc->xStep );
+  return p->cnt;
+}
+
+/*
+** Advance the virtual machine to the next output row.
+**
+** The return vale will be either SQLITE_BUSY, SQLITE_DONE, 
+** SQLITE_ROW, SQLITE_ERROR, or SQLITE_MISUSE.
+**
+** SQLITE_BUSY means that the virtual machine attempted to open
+** a locked database and there is no busy callback registered.
+** Call sqlite_step() again to retry the open.  *pN is set to 0
+** and *pazColName and *pazValue are both set to NULL.
+**
+** SQLITE_DONE means that the virtual machine has finished
+** executing.  sqlite_step() should not be called again on this
+** virtual machine.  *pN and *pazColName are set appropriately
+** but *pazValue is set to NULL.
+**
+** SQLITE_ROW means that the virtual machine has generated another
+** row of the result set.  *pN is set to the number of columns in
+** the row.  *pazColName is set to the names of the columns followed
+** by the column datatypes.  *pazValue is set to the values of each
+** column in the row.  The value of the i-th column is (*pazValue)[i].
+** The name of the i-th column is (*pazColName)[i] and the datatype
+** of the i-th column is (*pazColName)[i+*pN].
+**
+** SQLITE_ERROR means that a run-time error (such as a constraint
+** violation) has occurred.  The details of the error will be returned
+** by the next call to sqlite_finalize().  sqlite_step() should not
+** be called again on the VM.
+**
+** SQLITE_MISUSE means that the this routine was called inappropriately.
+** Perhaps it was called on a virtual machine that had already been
+** finalized or on one that had previously returned SQLITE_ERROR or
+** SQLITE_DONE.  Or it could be the case the the same database connection
+** is being used simulataneously by two or more threads.
+*/
+int sqlite_step(
+  sqlite_vm *pVm,              /* The virtual machine to execute */
+  int *pN,                     /* OUT: Number of columns in result */
+  const char ***pazValue,      /* OUT: Column data */
+  const char ***pazColName     /* OUT: Column names and datatypes */
+){
+  Vdbe *p = (Vdbe*)pVm;
+  sqlite *db;
+  int rc;
+
+  if( p->magic!=VDBE_MAGIC_RUN ){
+    return SQLITE_MISUSE;
+  }
+  db = p->db;
+  if( sqliteSafetyOn(db) ){
+    return SQLITE_MISUSE;
+  }
+  if( p->explain ){
+    rc = sqliteVdbeList(p);
+  }else{
+    rc = sqliteVdbeExec(p);
+  }
+  if( rc==SQLITE_DONE || rc==SQLITE_ROW ){
+    *pazColName = (const char**)p->azColName;
+    *pN = p->nResColumn;
+  }else{
+    *pN = 0;
+    *pazColName = 0;
+  }
+  if( rc==SQLITE_ROW ){
+    *pazValue = (const char**)p->azResColumn;
+  }else{
+    *pazValue = 0;
+  }
+  if( sqliteSafetyOff(db) ){
+    return SQLITE_MISUSE;
+  }
+  return rc;
+}
+
+/*
+** Reset an Agg structure.  Delete all its contents. 
+**
+** For installable aggregate functions, if the step function has been
+** called, make sure the finalizer function has also been called.  The
+** finalizer might need to free memory that was allocated as part of its
+** private context.  If the finalizer has not been called yet, call it
+** now.
+*/
+static void AggReset(Agg *pAgg){
+  int i;
+  HashElem *p;
+  for(p = sqliteHashFirst(&pAgg->hash); p; p = sqliteHashNext(p)){
+    AggElem *pElem = sqliteHashData(p);
+    assert( pAgg->apFunc!=0 );
+    for(i=0; i<pAgg->nMem; i++){
+      Mem *pMem = &pElem->aMem[i];
+      if( pAgg->apFunc[i] && (pMem->s.flags & STK_AggCtx)!=0 ){
+        sqlite_func ctx;
+        ctx.pFunc = pAgg->apFunc[i];
+        ctx.s.flags = STK_Null;
+        ctx.z = 0;
+        ctx.pAgg = pMem->z;
+        ctx.cnt = pMem->s.i;
+        ctx.isStep = 0;
+        ctx.isError = 0;
+        (*pAgg->apFunc[i]->xFinalize)(&ctx);
+        if( pMem->z!=0 && pMem->z!=pMem->s.z ){
+          sqliteFree(pMem->z);
+        }
+      }else if( pMem->s.flags & STK_Dyn ){
+        sqliteFree(pMem->z);
+      }
+    }
+    sqliteFree(pElem);
+  }
+  sqliteHashClear(&pAgg->hash);
+  sqliteFree(pAgg->apFunc);
+  pAgg->apFunc = 0;
+  pAgg->pCurrent = 0;
+  pAgg->pSearch = 0;
+  pAgg->nMem = 0;
+}
+
+/*
+** Insert a new aggregate element and make it the element that
+** has focus.
+**
+** Return 0 on success and 1 if memory is exhausted.
+*/
+static int AggInsert(Agg *p, char *zKey, int nKey){
+  AggElem *pElem, *pOld;
+  int i;
+  pElem = sqliteMalloc( sizeof(AggElem) + nKey +
+                        (p->nMem-1)*sizeof(pElem->aMem[0]) );
+  if( pElem==0 ) return 1;
+  pElem->zKey = (char*)&pElem->aMem[p->nMem];
+  memcpy(pElem->zKey, zKey, nKey);
+  pElem->nKey = nKey;
+  pOld = sqliteHashInsert(&p->hash, pElem->zKey, pElem->nKey, pElem);
+  if( pOld!=0 ){
+    assert( pOld==pElem );  /* Malloc failed on insert */
+    sqliteFree(pOld);
+    return 0;
+  }
+  for(i=0; i<p->nMem; i++){
+    pElem->aMem[i].s.flags = STK_Null;
+  }
+  p->pCurrent = pElem;
+  return 0;
+}
+
+/*
+** Get the AggElem currently in focus
+*/
+#define AggInFocus(P)   ((P).pCurrent ? (P).pCurrent : _AggInFocus(&(P)))
+static AggElem *_AggInFocus(Agg *p){
+  HashElem *pElem = sqliteHashFirst(&p->hash);
+  if( pElem==0 ){
+    AggInsert(p,"",1);
+    pElem = sqliteHashFirst(&p->hash);
+  }
+  return pElem ? sqliteHashData(pElem) : 0;
+}
+
+/*
+** Convert the given stack entity into a string if it isn't one
+** already.
+*/
+#define Stringify(P,I) if((aStack[I].flags & STK_Str)==0){hardStringify(P,I);}
+static int hardStringify(Vdbe *p, int i){
+  Stack *pStack = &p->aStack[i];
+  int fg = pStack->flags;
+  if( fg & STK_Real ){
+    sprintf(pStack->z,"%.15g",pStack->r);
+  }else if( fg & STK_Int ){
+    sprintf(pStack->z,"%d",pStack->i);
+  }else{
+    pStack->z[0] = 0;
+  }
+  p->zStack[i] = pStack->z;
+  pStack->n = strlen(pStack->z)+1;
+  pStack->flags = STK_Str;
+  return 0;
+}
+
+/*
+** Convert the given stack entity into a string that has been obtained
+** from sqliteMalloc().  This is different from Stringify() above in that
+** Stringify() will use the NBFS bytes of static string space if the string
+** will fit but this routine always mallocs for space.
+** Return non-zero if we run out of memory.
+*/
+#define Dynamicify(P,I) ((aStack[I].flags & STK_Dyn)==0 ? hardDynamicify(P,I):0)
+static int hardDynamicify(Vdbe *p, int i){
+  Stack *pStack = &p->aStack[i];
+  int fg = pStack->flags;
+  char *z;
+  if( (fg & STK_Str)==0 ){
+    hardStringify(p, i);
+  }
+  assert( (fg & STK_Dyn)==0 );
+  z = sqliteMallocRaw( pStack->n );
+  if( z==0 ) return 1;
+  memcpy(z, p->zStack[i], pStack->n);
+  p->zStack[i] = z;
+  pStack->flags |= STK_Dyn;
+  return 0;
+}
+
+/*
+** An ephemeral string value (signified by the STK_Ephem flag) contains
+** a pointer to a dynamically allocated string where some other entity
+** is responsible for deallocating that string.  Because the stack entry
+** does not control the string, it might be deleted without the stack
+** entry knowing it.
+**
+** This routine converts an ephemeral string into a dynamically allocated
+** string that the stack entry itself controls.  In other words, it
+** converts an STK_Ephem string into an STK_Dyn string.
+*/
+#define Deephemeralize(P,I) \
+   if( ((P)->aStack[I].flags&STK_Ephem)!=0 && hardDeephem(P,I) ){ goto no_mem;}
+static int hardDeephem(Vdbe *p, int i){
+  Stack *pStack = &p->aStack[i];
+  char **pzStack = &p->zStack[i];
+  char *z;
+  assert( (pStack->flags & STK_Ephem)!=0 );
+  z = sqliteMallocRaw( pStack->n );
+  if( z==0 ) return 1;
+  memcpy(z, *pzStack, pStack->n);
+  *pzStack = z;
+  return 0;
+}
+
+/*
+** Release the memory associated with the given stack level
+*/
+#define Release(P,I)  if((P)->aStack[I].flags&STK_Dyn){ hardRelease(P,I); }
+static void hardRelease(Vdbe *p, int i){
+  sqliteFree(p->zStack[i]);
+  p->zStack[i] = 0;
+  p->aStack[i].flags &= ~(STK_Str|STK_Dyn|STK_Static|STK_Ephem);
+}
+
+/*
+** Return TRUE if zNum is an integer and write
+** the value of the integer into *pNum.
+**
+** Under Linux (RedHat 7.2) this routine is much faster than atoi()
+** for converting strings into integers.
+*/
+static int toInt(const char *zNum, int *pNum){
+  int v = 0;
+  int neg;
+  if( *zNum=='-' ){
+    neg = 1;
+    zNum++;
+  }else if( *zNum=='+' ){
+    neg = 0;
+    zNum++;
+  }else{
+    neg = 0;
+  }
+  while( isdigit(*zNum) ){
+    v = v*10 + *zNum - '0';
+    zNum++;
+  }
+  *pNum = neg ? -v : v;
+  return *zNum==0;
+}
+
+/*
+** Convert the given stack entity into a integer if it isn't one
+** already.
+**
+** Any prior string or real representation is invalidated.  
+** NULLs are converted into 0.
+*/
+#define Integerify(P,I) \
+    if(((P)->aStack[(I)].flags&STK_Int)==0){ hardIntegerify(P,I); }
+static void hardIntegerify(Vdbe *p, int i){
+  if( p->aStack[i].flags & STK_Real ){
+    p->aStack[i].i = (int)p->aStack[i].r;
+    Release(p, i);
+  }else if( p->aStack[i].flags & STK_Str ){
+    toInt(p->zStack[i], &p->aStack[i].i);
+    Release(p, i);
+  }else{
+    p->aStack[i].i = 0;
+  }
+  p->aStack[i].flags = STK_Int;
+}
+
+/*
+** Get a valid Real representation for the given stack element.
+**
+** Any prior string or integer representation is retained.
+** NULLs are converted into 0.0.
+*/
+#define Realify(P,I) \
+    if(((P)->aStack[(I)].flags&STK_Real)==0){ hardRealify(P,I); }
+static void hardRealify(Vdbe *p, int i){
+  if( p->aStack[i].flags & STK_Str ){
+    p->aStack[i].r = atof(p->zStack[i]);
+  }else if( p->aStack[i].flags & STK_Int ){
+    p->aStack[i].r = p->aStack[i].i;
+  }else{
+    p->aStack[i].r = 0.0;
+  }
+  p->aStack[i].flags |= STK_Real;
+}
+
+/*
+** Pop the stack N times.  Free any memory associated with the
+** popped stack elements.
+*/
+static void PopStack(Vdbe *p, int N){
+  assert( N>=0 );
+  if( p->zStack==0 ) return;
+  assert( p->aStack || sqlite_malloc_failed );
+  if( p->aStack==0 ) return;
+  while( N-- > 0 ){
+    if( p->aStack[p->tos].flags & STK_Dyn ){
+      sqliteFree(p->zStack[p->tos]);
+    }
+    p->aStack[p->tos].flags = 0;
+    p->zStack[p->tos] = 0;
+    p->tos--;
+  }
+}
+
+/*
+** Here is a macro to handle the common case of popping the stack
+** once.  This macro only works from within the sqliteVdbeExec()
+** function.
+*/
+#define POPSTACK \
+  assert(p->tos>=0); \
+  if( aStack[p->tos].flags & STK_Dyn ) sqliteFree(zStack[p->tos]); \
+  p->tos--;
+
+/*
+** Return TRUE if zNum is a floating-point or integer number.
+*/
+static int isNumber(const char *zNum){
+  if( *zNum=='-' || *zNum=='+' ) zNum++;
+  if( !isdigit(*zNum) ) return 0;
+  while( isdigit(*zNum) ) zNum++;
+  if( *zNum==0 ) return 1;
+  if( *zNum!='.' ) return 0;
+  zNum++;
+  if( !isdigit(*zNum) ) return 0;
+  while( isdigit(*zNum) ) zNum++;
+  if( *zNum==0 ) return 1;
+  if( *zNum!='e' && *zNum!='E' ) return 0;
+  zNum++;
+  if( *zNum=='-' || *zNum=='+' ) zNum++;
+  if( !isdigit(*zNum) ) return 0;
+  while( isdigit(*zNum) ) zNum++;
+  return *zNum==0;
+}
+
+/*
+** Delete a keylist
+*/
+static void KeylistFree(Keylist *p){
+  while( p ){
+    Keylist *pNext = p->pNext;
+    sqliteFree(p);
+    p = pNext;
+  }
+}
+
+/*
+** Close a cursor and release all the resources that cursor happens
+** to hold.
+*/
+static void cleanupCursor(Cursor *pCx){
+  if( pCx->pCursor ){
+    sqliteBtreeCloseCursor(pCx->pCursor);
+  }
+  if( pCx->pBt ){
+    sqliteBtreeClose(pCx->pBt);
+  }
+  memset(pCx, 0, sizeof(Cursor));
+}
+
+/*
+** Close all cursors
+*/
+static void closeAllCursors(Vdbe *p){
+  int i;
+  for(i=0; i<p->nCursor; i++){
+    cleanupCursor(&p->aCsr[i]);
+  }
+  sqliteFree(p->aCsr);
+  p->aCsr = 0;
+  p->nCursor = 0;
+}
+
+/*
+** Remove any elements that remain on the sorter for the VDBE given.
+*/
+static void SorterReset(Vdbe *p){
+  while( p->pSort ){
+    Sorter *pSorter = p->pSort;
+    p->pSort = pSorter->pNext;
+    sqliteFree(pSorter->zKey);
+    sqliteFree(pSorter->pData);
+    sqliteFree(pSorter);
+  }
+}
+
+/*
+** Clean up the VM after execution.
+**
+** This routine will automatically close any cursors, lists, and/or
+** sorters that were left open.
+*/
+static void Cleanup(Vdbe *p){
+  int i;
+  PopStack(p, p->tos+1);
+  closeAllCursors(p);
+  if( p->aMem ){
+    for(i=0; i<p->nMem; i++){
+      if( p->aMem[i].s.flags & STK_Dyn ){
+        sqliteFree(p->aMem[i].z);
+      }
+    }
+  }
+  sqliteFree(p->aMem);
+  p->aMem = 0;
+  p->nMem = 0;
+  if( p->pList ){
+    KeylistFree(p->pList);
+    p->pList = 0;
+  }
+  SorterReset(p);
+  if( p->pFile ){
+    if( p->pFile!=stdin ) fclose(p->pFile);
+    p->pFile = 0;
+  }
+  if( p->azField ){
+    sqliteFree(p->azField);
+    p->azField = 0;
+  }
+  p->nField = 0;
+  if( p->zLine ){
+    sqliteFree(p->zLine);
+    p->zLine = 0;
+  }
+  p->nLineAlloc = 0;
+  AggReset(&p->agg);
+  if( p->aSet ){
+    for(i=0; i<p->nSet; i++){
+      sqliteHashClear(&p->aSet[i].hash);
+    }
+  }
+  sqliteFree(p->aSet);
+  p->aSet = 0;
+  p->nSet = 0;
+  if( p->keylistStack ){
+    int ii;
+    for(ii = 0; ii < p->keylistStackDepth; ii++){
+      KeylistFree(p->keylistStack[ii]);
+    }
+    sqliteFree(p->keylistStack);
+    p->keylistStackDepth = 0;
+    p->keylistStack = 0;
+  }
+  sqliteFree(p->zErrMsg);
+  p->zErrMsg = 0;
+  p->magic = VDBE_MAGIC_DEAD;
+}
+
+/*
+** Delete an entire VDBE.
+*/
+void sqliteVdbeDelete(Vdbe *p){
+  int i;
+  if( p==0 ) return;
+  Cleanup(p);
+  if( p->pPrev ){
+    p->pPrev->pNext = p->pNext;
+  }else{
+    assert( p->db->pVdbe==p );
+    p->db->pVdbe = p->pNext;
+  }
+  if( p->pNext ){
+    p->pNext->pPrev = p->pPrev;
+  }
+  p->pPrev = p->pNext = 0;
+  if( p->nOpAlloc==0 ){
+    p->aOp = 0;
+    p->nOp = 0;
+  }
+  for(i=0; i<p->nOp; i++){
+    if( p->aOp[i].p3type==P3_DYNAMIC ){
+      sqliteFree(p->aOp[i].p3);
+    }
+  }
+  sqliteFree(p->aOp);
+  sqliteFree(p->aLabel);
+  sqliteFree(p->aStack);
+  sqliteFree(p);
+}
+
+/*
+** Give a listing of the program in the virtual machine.
+**
+** The interface is the same as sqliteVdbeExec().  But instead of
+** running the code, it invokes the callback once for each instruction.
+** This feature is used to implement "EXPLAIN".
+*/
+int sqliteVdbeList(
+  Vdbe *p                   /* The VDBE */
+){
+  sqlite *db = p->db;
+  int i;
+  static char *azColumnNames[] = {
+     "addr", "opcode", "p1",  "p2",  "p3", 
+     "int",  "text",   "int", "int", "text",
+     0
+  };
+
+  assert( p->popStack==0 );
+  assert( p->explain );
+  p->azColName = azColumnNames;
+  p->azResColumn = p->zStack;
+  for(i=0; i<5; i++) p->zStack[i] = p->aStack[i].z;
+  p->rc = SQLITE_OK;
+  for(i=p->pc; p->rc==SQLITE_OK && i<p->nOp; i++){
+    if( db->flags & SQLITE_Interrupt ){
+      db->flags &= ~SQLITE_Interrupt;
+      if( db->magic!=SQLITE_MAGIC_BUSY ){
+        p->rc = SQLITE_MISUSE;
+      }else{
+        p->rc = SQLITE_INTERRUPT;
+      }
+      sqliteSetString(&p->zErrMsg, sqlite_error_string(p->rc), 0);
+      break;
+    }
+    sprintf(p->zStack[0],"%d",i);
+    sprintf(p->zStack[2],"%d", p->aOp[i].p1);
+    sprintf(p->zStack[3],"%d", p->aOp[i].p2);
+    if( p->aOp[i].p3type==P3_POINTER ){
+      sprintf(p->aStack[4].z, "ptr(%#x)", (int)p->aOp[i].p3);
+      p->zStack[4] = p->aStack[4].z;
+    }else{
+      p->zStack[4] = p->aOp[i].p3;
+    }
+    p->zStack[1] = sqliteOpcodeNames[p->aOp[i].opcode];
+    if( p->xCallback==0 ){
+      p->pc = i+1;
+      p->azResColumn = p->zStack;
+      p->nResColumn = 5;
+      return SQLITE_ROW;
+    }
+    if( sqliteSafetyOff(db) ){
+      p->rc = SQLITE_MISUSE;
+      break;
+    }
+    if( p->xCallback(p->pCbArg, 5, p->zStack, p->azColName) ){
+      p->rc = SQLITE_ABORT;
+    }
+    if( sqliteSafetyOn(db) ){
+      p->rc = SQLITE_MISUSE;
+    }
+  }
+  return p->rc==SQLITE_OK ? SQLITE_OK : SQLITE_ERROR;
+}
+
+/*
+** The parameters are pointers to the head of two sorted lists
+** of Sorter structures.  Merge these two lists together and return
+** a single sorted list.  This routine forms the core of the merge-sort
+** algorithm.
+**
+** In the case of a tie, left sorts in front of right.
+*/
+static Sorter *Merge(Sorter *pLeft, Sorter *pRight){
+  Sorter sHead;
+  Sorter *pTail;
+  pTail = &sHead;
+  pTail->pNext = 0;
+  while( pLeft && pRight ){
+    int c = sqliteSortCompare(pLeft->zKey, pRight->zKey);
+    if( c<=0 ){
+      pTail->pNext = pLeft;
+      pLeft = pLeft->pNext;
+    }else{
+      pTail->pNext = pRight;
+      pRight = pRight->pNext;
+    }
+    pTail = pTail->pNext;
+  }
+  if( pLeft ){
+    pTail->pNext = pLeft;
+  }else if( pRight ){
+    pTail->pNext = pRight;
+  }
+  return sHead.pNext;
+}
+
+/*
+** Convert an integer in between the native integer format and
+** the bigEndian format used as the record number for tables.
+**
+** The bigEndian format (most significant byte first) is used for
+** record numbers so that records will sort into the correct order
+** even though memcmp() is used to compare the keys.  On machines
+** whose native integer format is little endian (ex: i486) the
+** order of bytes is reversed.  On native big-endian machines
+** (ex: Alpha, Sparc, Motorola) the byte order is the same.
+**
+** This function is its own inverse.  In other words
+**
+**         X == byteSwap(byteSwap(X))
+*/
+static int byteSwap(int x){
+  union {
+     char zBuf[sizeof(int)];
+     int i;
+  } ux;
+  ux.zBuf[3] = x&0xff;
+  ux.zBuf[2] = (x>>8)&0xff;
+  ux.zBuf[1] = (x>>16)&0xff;
+  ux.zBuf[0] = (x>>24)&0xff;
+  return ux.i;
+}
+
+/*
+** When converting from the native format to the key format and back
+** again, in addition to changing the byte order we invert the high-order
+** bit of the most significant byte.  This causes negative numbers to
+** sort before positive numbers in the memcmp() function.
+*/
+#define keyToInt(X)   (byteSwap(X) ^ 0x80000000)
+#define intToKey(X)   (byteSwap((X) ^ 0x80000000))
+
+/*
+** Code contained within the VERIFY() macro is not needed for correct
+** execution.  It is there only to catch errors.  So when we compile
+** with NDEBUG=1, the VERIFY() code is omitted.
+*/
+#ifdef NDEBUG
+# define VERIFY(X)
+#else
+# define VERIFY(X) X
+#endif
+
+/*
+** The following routine works like a replacement for the standard
+** library routine fgets().  The difference is in how end-of-line (EOL)
+** is handled.  Standard fgets() uses LF for EOL under unix, CRLF
+** under windows, and CR under mac.  This routine accepts any of these
+** character sequences as an EOL mark.  The EOL mark is replaced by
+** a single LF character in zBuf.
+*/
+static char *vdbe_fgets(char *zBuf, int nBuf, FILE *in){
+  int i, c;
+  for(i=0; i<nBuf-1 && (c=getc(in))!=EOF; i++){
+    zBuf[i] = c;
+    if( c=='\r' || c=='\n' ){
+      if( c=='\r' ){
+        zBuf[i] = '\n';
+        c = getc(in);
+        if( c!=EOF && c!='\n' ) ungetc(c, in);
+      }
+      i++;
+      break;
+    }
+  }
+  zBuf[i]  = 0;
+  return i>0 ? zBuf : 0;
+}
+
+#if !defined(NDEBUG) || defined(VDBE_PROFILE)
+/*
+** Print a single opcode.  This routine is used for debugging only.
+*/
+static void vdbePrintOp(FILE *pOut, int pc, Op *pOp){
+  char *zP3;
+  char zPtr[40];
+  if( pOp->p3type==P3_POINTER ){
+    sprintf(zPtr, "ptr(%#x)", (int)pOp->p3);
+    zP3 = zPtr;
+  }else{
+    zP3 = pOp->p3;
+  }
+  if( pOut==0 ) pOut = stdout;
+  fprintf(pOut,"%4d %-12s %4d %4d %s\n",
+      pc, sqliteOpcodeNames[pOp->opcode], pOp->p1, pOp->p2, zP3 ? zP3 : "");
+  fflush(pOut);
+}
+#endif
+
+/*
+** Make sure there is space in the Vdbe structure to hold at least
+** mxCursor cursors.  If there is not currently enough space, then
+** allocate more.
+**
+** If a memory allocation error occurs, return 1.  Return 0 if
+** everything works.
+*/
+static int expandCursorArraySize(Vdbe *p, int mxCursor){
+  if( mxCursor>=p->nCursor ){
+    Cursor *aCsr = sqliteRealloc( p->aCsr, (mxCursor+1)*sizeof(Cursor) );
+    if( aCsr==0 ) return 1;
+    p->aCsr = aCsr;
+    memset(&p->aCsr[p->nCursor], 0, sizeof(Cursor)*(mxCursor+1-p->nCursor));
+    p->nCursor = mxCursor+1;
+  }
+  return 0;
+}
+
+#ifdef VDBE_PROFILE
+/*
+** The following routine only works on pentium-class processors.
+** It uses the RDTSC opcode to read cycle count value out of the
+** processor and returns that value.  This can be used for high-res
+** profiling.
+*/
+__inline__ unsigned long long int hwtime(void){
+  unsigned long long int x;
+  __asm__("rdtsc\n\t"
+          "mov %%edx, %%ecx\n\t"
+          :"=A" (x));
+  return x;
+}
+#endif
+
+/*
+** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
+** sqlite_interrupt() routine has been called.  If it has been, then
+** processing of the VDBE program is interrupted.
+**
+** This macro added to every instruction that does a jump in order to
+** implement a loop.  This test used to be on every single instruction,
+** but that meant we more testing that we needed.  By only testing the
+** flag on jump instructions, we get a (small) speed improvement.
+*/
+#define CHECK_FOR_INTERRUPT \
+   if( db->flags & SQLITE_Interrupt ) goto abort_due_to_interrupt;
+
+
+/*
+** Prepare a virtual machine for execution.  This involves things such
+** as allocating stack space and initializing the program counter.
+** After the VDBE has be prepped, it can be executed by one or more
+** calls to sqliteVdbeExec().  
+**
+** The behavior of sqliteVdbeExec() is influenced by the parameters to
+** this routine.  If xCallback is NULL, then sqliteVdbeExec() will return
+** with SQLITE_ROW whenever there is a row of the result set ready
+** to be delivered.  p->azResColumn will point to the row and 
+** p->nResColumn gives the number of columns in the row.  If xCallback
+** is not NULL, then the xCallback() routine is invoked to process each
+** row in the result set.
+*/
+void sqliteVdbeMakeReady(
+  Vdbe *p,                       /* The VDBE */
+  sqlite_callback xCallback,     /* Result callback */
+  void *pCallbackArg,            /* 1st argument to xCallback() */
+  int isExplain                  /* True if the EXPLAIN keywords is present */
+){
+  int n;
+
+  assert( p!=0 );
+  assert( p->aStack==0 );
+  assert( p->magic==VDBE_MAGIC_INIT );
+
+  /* Add a HALT instruction to the very end of the program.
+  */
+  sqliteVdbeAddOp(p, OP_Halt, 0, 0);
+
+  /* No instruction ever pushes more than a single element onto the
+  ** stack.  And the stack never grows on successive executions of the
+  ** same loop.  So the total number of instructions is an upper bound
+  ** on the maximum stack depth required.
+  **
+  ** Allocation all the stack space we will ever need.
+  */
+  n = isExplain ? 10 : p->nOp;
+  p->aStack = sqliteMalloc( n*(sizeof(p->aStack[0]) + 2*sizeof(char*)) );
+  p->zStack = (char**)&p->aStack[n];
+  p->azColName = (char**)&p->zStack[n];
+
+  sqliteHashInit(&p->agg.hash, SQLITE_HASH_BINARY, 0);
+  p->agg.pSearch = 0;
+#ifdef MEMORY_DEBUG
+  if( access("vdbe_trace",0)==0 ){
+    p->trace = stdout;
+  }
+#endif
+  p->tos = -1;
+  p->pc = 0;
+  p->rc = SQLITE_OK;
+  p->uniqueCnt = 0;
+  p->returnDepth = 0;
+  p->errorAction = OE_Abort;
+  p->undoTransOnError = 0;
+  p->xCallback = xCallback;
+  p->pCbArg = pCallbackArg;
+  p->popStack =  0;
+  p->explain = isExplain;
+  p->magic = VDBE_MAGIC_RUN;
+#ifdef VDBE_PROFILE
+  for(i=0; i<p->nOp; i++){
+    p->aOp[i].cnt = 0;
+    p->aOp[i].cycles = 0;
+  }
+#endif
+}
+
+/*
+** Execute as much of a VDBE program as we can then return.
+**
+** sqliteVdbeMakeReady() must be called before this routine in order to
+** close the program with a final OP_Halt and to set up the callbacks
+** and the error message pointer.
+**
+** Whenever a row or result data is available, this routine will either
+** invoke the result callback (if there is one) or return with
+** SQLITE_ROW.
+**
+** If an attempt is made to open a locked database, then this routine
+** will either invoke the busy callback (if there is one) or it will
+** return SQLITE_BUSY.
+**
+** If an error occurs, an error message is written to memory obtained
+** from sqliteMalloc() and p->zErrMsg is made to point to that memory.
+** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
+**
+** If the callback ever returns non-zero, then the program exits
+** immediately.  There will be no error message but the p->rc field is
+** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
+**
+** A memory allocation error causes p->rc to be set SQLITE_NOMEM and this
+** routien to return SQLITE_ERROR.
+**
+** Other fatal errors return SQLITE_ERROR.
+**
+** After this routine has finished, sqliteVdbeFinalize() should be
+** used to clean up the mess that was left behind.
+*/
+int sqliteVdbeExec(
+  Vdbe *p                    /* The VDBE */
+){
+  int pc;                    /* The program counter */
+  Op *pOp;                   /* Current operation */
+  int rc = SQLITE_OK;        /* Value to return */
+  Btree *pBt = p->pBt;       /* The backend driver */
+  sqlite *db = p->db;        /* The database */
+  char **zStack = p->zStack; /* Text stack */
+  Stack *aStack = p->aStack; /* Additional stack information */
+  char zBuf[100];            /* Space to sprintf() an integer */
+#ifdef VDBE_PROFILE
+  unsigned long long start;  /* CPU clock count at start of opcode */
+  int origPc;                /* Program counter at start of opcode */
+#endif
+
+  if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
+  assert( db->magic==SQLITE_MAGIC_BUSY );
+  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
+  p->rc = SQLITE_OK;
+  assert( p->explain==0 );
+  if( sqlite_malloc_failed ) goto no_mem;
+  if( p->popStack ){
+    PopStack(p, p->popStack);
+    p->popStack = 0;
+  }
+  for(pc=p->pc; rc==SQLITE_OK; pc++){
+    assert( pc>=0 && pc<p->nOp );
+#ifdef VDBE_PROFILE
+    origPc = pc;
+    start = hwtime();
+#endif
+    pOp = &p->aOp[pc];
+
+    /* Only allow tracing if NDEBUG is not defined.
+    */
+#ifndef NDEBUG
+    if( p->trace ){
+      vdbePrintOp(p->trace, pc, pOp);
+    }
+#endif
+
+    switch( pOp->opcode ){
+
+/*****************************************************************************
+** What follows is a massive switch statement where each case implements a
+** separate instruction in the virtual machine.  If we follow the usual
+** indentation conventions, each case should be indented by 6 spaces.  But
+** that is a lot of wasted space on the left margin.  So the code within
+** the switch statement will break with convention and be flush-left. Another
+** big comment (similar to this one) will mark the point in the code where
+** we transition back to normal indentation.
+**
+** The formatting of each case is important.  The makefile for SQLite
+** generates two C files "opcodes.h" and "opcodes.c" by scanning this
+** file looking for lines that begin with "case OP_".  The opcodes.h files
+** will be filled with #defines that give unique integer values to each
+** opcode and the opcodes.c file is filled with an array of strings where
+** each string is the symbolic name for the corresponding opcode.
+**
+** Documentation about VDBE opcodes is generated by scanning this file
+** for lines of that contain "Opcode:".  That line and all subsequent
+** comment lines are used in the generation of the opcode.html documentation
+** file.
+**
+** SUMMARY:
+**
+**     Formatting is important to scripts that scan this file.
+**     Do not deviate from the formatting style currently in use.
+**
+*****************************************************************************/
+
+/* Opcode:  Goto * P2 *
+**
+** An unconditional jump to address P2.
+** The next instruction executed will be 
+** the one at index P2 from the beginning of
+** the program.
+*/
+case OP_Goto: {
+  CHECK_FOR_INTERRUPT;
+  pc = pOp->p2 - 1;
+  break;
+}
+
+/* Opcode:  Gosub * P2 *
+**
+** Push the current address plus 1 onto the return address stack
+** and then jump to address P2.
+**
+** The return address stack is of limited depth.  If too many
+** OP_Gosub operations occur without intervening OP_Returns, then
+** the return address stack will fill up and processing will abort
+** with a fatal error.
+*/
+case OP_Gosub: {
+  if( p->returnDepth>=sizeof(p->returnStack)/sizeof(p->returnStack[0]) ){
+    sqliteSetString(&p->zErrMsg, "return address stack overflow", 0);
+    p->rc = SQLITE_INTERNAL;
+    return SQLITE_ERROR;
+  }
+  p->returnStack[p->returnDepth++] = pc+1;
+  pc = pOp->p2 - 1;
+  break;
+}
+
+/* Opcode:  Return * * *
+**
+** Jump immediately to the next instruction after the last unreturned
+** OP_Gosub.  If an OP_Return has occurred for all OP_Gosubs, then
+** processing aborts with a fatal error.
+*/
+case OP_Return: {
+  if( p->returnDepth<=0 ){
+    sqliteSetString(&p->zErrMsg, "return address stack underflow", 0);
+    p->rc = SQLITE_INTERNAL;
+    return SQLITE_ERROR;
+  }
+  p->returnDepth--;
+  pc = p->returnStack[p->returnDepth] - 1;
+  break;
+}
+
+/* Opcode:  Halt P1 P2 *
+**
+** Exit immediately.  All open cursors, Lists, Sorts, etc are closed
+** automatically.
+**
+** P1 is the result code returned by sqlite_exec().  For a normal
+** halt, this should be SQLITE_OK (0).  For errors, it can be some
+** other value.  If P1!=0 then P2 will determine whether or not to
+** rollback the current transaction.  Do not rollback if P2==OE_Fail.
+** Do the rollback if P2==OE_Rollback.  If P2==OE_Abort, then back
+** out all changes that have occurred during this execution of the
+** VDBE, but do not rollback the transaction. 
+**
+** There is an implied "Halt 0 0 0" instruction inserted at the very end of
+** every program.  So a jump past the last instruction of the program
+** is the same as executing Halt.
+*/
+case OP_Halt: {
+  p->magic = VDBE_MAGIC_HALT;
+  if( pOp->p1!=SQLITE_OK ){
+    p->rc = pOp->p1;
+    p->errorAction = pOp->p2;
+    if( pOp->p3 ){
+      sqliteSetString(&p->zErrMsg, pOp->p3, 0);
+    }
+    return SQLITE_ERROR;
+  }else{
+    p->rc = SQLITE_OK;
+    return SQLITE_DONE;
+  }
+}
+
+/* Opcode: Integer P1 * P3
+**
+** The integer value P1 is pushed onto the stack.  If P3 is not zero
+** then it is assumed to be a string representation of the same integer.
+*/
+case OP_Integer: {
+  int i = ++p->tos;
+  aStack[i].i = pOp->p1;
+  aStack[i].flags = STK_Int;
+  if( pOp->p3 ){
+    zStack[i] = pOp->p3;
+    aStack[i].flags |= STK_Str | STK_Static;
+    aStack[i].n = strlen(pOp->p3)+1;
+  }
+  break;
+}
+
+/* Opcode: String * * P3
+**
+** The string value P3 is pushed onto the stack.  If P3==0 then a
+** NULL is pushed onto the stack.
+*/
+case OP_String: {
+  int i = ++p->tos;
+  char *z;
+  z = pOp->p3;
+  if( z==0 ){
+    zStack[i] = 0;
+    aStack[i].n = 0;
+    aStack[i].flags = STK_Null;
+  }else{
+    zStack[i] = z;
+    aStack[i].n = strlen(z) + 1;
+    aStack[i].flags = STK_Str | STK_Static;
+  }
+  break;
+}
+
+/* Opcode: Pop P1 * *
+**
+** P1 elements are popped off of the top of stack and discarded.
+*/
+case OP_Pop: {
+  assert( p->tos+1>=pOp->p1 );
+  PopStack(p, pOp->p1);
+  break;
+}
+
+/* Opcode: Dup P1 P2 *
+**
+** A copy of the P1-th element of the stack 
+** is made and pushed onto the top of the stack.
+** The top of the stack is element 0.  So the
+** instruction "Dup 0 0 0" will make a copy of the
+** top of the stack.
+**
+** If the content of the P1-th element is a dynamically
+** allocated string, then a new copy of that string
+** is made if P2==0.  If P2!=0, then just a pointer
+** to the string is copied.
+**
+** Also see the Pull instruction.
+*/
+case OP_Dup: {
+  int i = p->tos - pOp->p1;
+  int j = ++p->tos;
+  VERIFY( if( i<0 ) goto not_enough_stack; )
+  memcpy(&aStack[j], &aStack[i], sizeof(aStack[i])-NBFS);
+  if( aStack[j].flags & STK_Str ){
+    int isStatic = (aStack[j].flags & STK_Static)!=0;
+    if( pOp->p2 || isStatic ){
+      zStack[j] = zStack[i];
+      aStack[j].flags &= ~STK_Dyn;
+      if( !isStatic ) aStack[j].flags |= STK_Ephem;
+    }else if( aStack[i].n<=NBFS ){
+      memcpy(aStack[j].z, zStack[i], aStack[j].n);
+      zStack[j] = aStack[j].z;
+      aStack[j].flags &= ~(STK_Static|STK_Dyn|STK_Ephem);
+    }else{
+      zStack[j] = sqliteMallocRaw( aStack[j].n );
+      if( zStack[j]==0 ) goto no_mem;
+      memcpy(zStack[j], zStack[i], aStack[j].n);
+      aStack[j].flags &= ~(STK_Static|STK_Ephem);
+      aStack[j].flags |= STK_Dyn;
+    }
+  }
+  break;
+}
+
+/* Opcode: Pull P1 * *
+**
+** The P1-th element is removed from its current location on 
+** the stack and pushed back on top of the stack.  The
+** top of the stack is element 0, so "Pull 0 0 0" is
+** a no-op.  "Pull 1 0 0" swaps the top two elements of
+** the stack.
+**
+** See also the Dup instruction.
+*/
+case OP_Pull: {
+  int from = p->tos - pOp->p1;
+  int to = p->tos;
+  int i;
+  Stack ts;
+  char *tz;
+  VERIFY( if( from<0 ) goto not_enough_stack; )
+  ts = aStack[from];
+  tz = zStack[from];
+  Deephemeralize(p, to);
+  for(i=from; i<to; i++){
+    Deephemeralize(p, i);
+    aStack[i] = aStack[i+1];
+    assert( (aStack[i].flags & STK_Ephem)==0 );
+    if( aStack[i].flags & (STK_Dyn|STK_Static) ){
+      zStack[i] = zStack[i+1];
+    }else{
+      zStack[i] = aStack[i].z;
+    }
+  }
+  aStack[to] = ts;
+  assert( (aStack[to].flags & STK_Ephem)==0 );
+  if( aStack[to].flags & (STK_Dyn|STK_Static) ){
+    zStack[to] = tz;
+  }else{
+    zStack[to] = aStack[to].z;
+  }
+  break;
+}
+
+/* Opcode: Push P1 * *
+**
+** Overwrite the value of the P1-th element down on the
+** stack (P1==0 is the top of the stack) with the value
+** of the top of the stack.  Then pop the top of the stack.
+*/
+case OP_Push: {
+  int from = p->tos;
+  int to = p->tos - pOp->p1;
+
+  VERIFY( if( to<0 ) goto not_enough_stack; )
+  if( aStack[to].flags & STK_Dyn ){
+    sqliteFree(zStack[to]);
+  }
+  Deephemeralize(p, from);
+  aStack[to] = aStack[from];
+  if( aStack[to].flags & (STK_Dyn|STK_Static|STK_Ephem) ){
+    zStack[to] = zStack[from];
+  }else{
+    zStack[to] = aStack[to].z;
+  }
+  aStack[from].flags = 0;
+  p->tos--;
+  break;
+}
+
+/* Opcode: ColumnName P1 * P3
+**
+** P3 becomes the P1-th column name (first is 0).  An array of pointers
+** to all column names is passed as the 4th parameter to the callback.
+*/
+case OP_ColumnName: {
+  p->azColName[pOp->p1] = pOp->p3;
+  p->nCallback = 0;
+  break;
+}
+
+/* Opcode: Callback P1 * *
+**
+** Pop P1 values off the stack and form them into an array.  Then
+** invoke the callback function using the newly formed array as the
+** 3rd parameter.
+*/
+case OP_Callback: {
+  int i = p->tos - pOp->p1 + 1;
+  int j;
+  VERIFY( if( i<0 ) goto not_enough_stack; )
+  for(j=i; j<=p->tos; j++){
+    if( aStack[j].flags & STK_Null ){
+      zStack[j] = 0;
+    }else{
+      Stringify(p, j);
+    }
+  }
+  zStack[p->tos+1] = 0;
+  if( p->xCallback==0 ){
+    p->azResColumn = &zStack[i];
+    p->nResColumn = pOp->p1;
+    p->popStack = pOp->p1;
+    p->pc = pc + 1;
+    return SQLITE_ROW;
+  }
+  if( sqliteSafetyOff(db) ) goto abort_due_to_misuse; 
+  if( p->xCallback(p->pCbArg, pOp->p1, &zStack[i], p->azColName)!=0 ){
+    rc = SQLITE_ABORT;
+  }
+  if( sqliteSafetyOn(db) ) goto abort_due_to_misuse;
+  p->nCallback++;
+  PopStack(p, pOp->p1);
+  if( sqlite_malloc_failed ) goto no_mem;
+  break;
+}
+
+/* Opcode: NullCallback P1 * *
+**
+** Invoke the callback function once with the 2nd argument (the
+** number of columns) equal to P1 and with the 4th argument (the
+** names of the columns) set according to prior OP_ColumnName
+** instructions.  This is all like the regular
+** OP_Callback or OP_SortCallback opcodes.  But the 3rd argument
+** which normally contains a pointer to an array of pointers to
+** data is NULL.
+**
+** The callback is only invoked if there have been no prior calls
+** to OP_Callback or OP_SortCallback.
+**
+** This opcode is used to report the number and names of columns
+** in cases where the result set is empty.
+*/
+case OP_NullCallback: {
+  if( p->nCallback==0 && p->xCallback!=0 ){
+    if( sqliteSafetyOff(db) ) goto abort_due_to_misuse; 
+    if( p->xCallback(p->pCbArg, pOp->p1, 0, p->azColName)!=0 ){
+      rc = SQLITE_ABORT;
+    }
+    if( sqliteSafetyOn(db) ) goto abort_due_to_misuse;
+    p->nCallback++;
+    if( sqlite_malloc_failed ) goto no_mem;
+  }
+  p->nResColumn = pOp->p1;
+  break;
+}
+
+/* Opcode: Concat P1 P2 P3
+**
+** Look at the first P1 elements of the stack.  Append them all 
+** together with the lowest element first.  Use P3 as a separator.  
+** Put the result on the top of the stack.  The original P1 elements
+** are popped from the stack if P2==0 and retained if P2==1.  If
+** any element of the stack is NULL, then the result is NULL.
+**
+** If P3 is NULL, then use no separator.  When P1==1, this routine
+** makes a copy of the top stack element into memory obtained
+** from sqliteMalloc().
+*/
+case OP_Concat: {
+  char *zNew;
+  int nByte;
+  int nField;
+  int i, j;
+  char *zSep;
+  int nSep;
+
+  nField = pOp->p1;
+  zSep = pOp->p3;
+  if( zSep==0 ) zSep = "";
+  nSep = strlen(zSep);
+  VERIFY( if( p->tos+1<nField ) goto not_enough_stack; )
+  nByte = 1 - nSep;
+  for(i=p->tos-nField+1; i<=p->tos; i++){
+    if( aStack[i].flags & STK_Null ){
+      nByte = -1;
+      break;
+    }else{
+      Stringify(p, i);
+      nByte += aStack[i].n - 1 + nSep;
+    }
+  }
+  if( nByte<0 ){
+    if( pOp->p2==0 ) PopStack(p, nField);
+    p->tos++;
+    aStack[p->tos].flags = STK_Null;
+    zStack[p->tos] = 0;
+    break;
+  }
+  zNew = sqliteMallocRaw( nByte );
+  if( zNew==0 ) goto no_mem;
+  j = 0;
+  for(i=p->tos-nField+1; i<=p->tos; i++){
+    if( (aStack[i].flags & STK_Null)==0 ){
+      memcpy(&zNew[j], zStack[i], aStack[i].n-1);
+      j += aStack[i].n-1;
+    }
+    if( nSep>0 && i<p->tos ){
+      memcpy(&zNew[j], zSep, nSep);
+      j += nSep;
+    }
+  }
+  zNew[j] = 0;
+  if( pOp->p2==0 ) PopStack(p, nField);
+  p->tos++;
+  aStack[p->tos].n = nByte;
+  aStack[p->tos].flags = STK_Str|STK_Dyn;
+  zStack[p->tos] = zNew;
+  break;
+}
+
+/* Opcode: Add * * *
+**
+** Pop the top two elements from the stack, add them together,
+** and push the result back onto the stack.  If either element
+** is a string then it is converted to a double using the atof()
+** function before the addition.
+** If either operand is NULL, the result is NULL.
+*/
+/* Opcode: Multiply * * *
+**
+** Pop the top two elements from the stack, multiply them together,
+** and push the result back onto the stack.  If either element
+** is a string then it is converted to a double using the atof()
+** function before the multiplication.
+** If either operand is NULL, the result is NULL.
+*/
+/* Opcode: Subtract * * *
+**
+** Pop the top two elements from the stack, subtract the
+** first (what was on top of the stack) from the second (the
+** next on stack)
+** and push the result back onto the stack.  If either element
+** is a string then it is converted to a double using the atof()
+** function before the subtraction.
+** If either operand is NULL, the result is NULL.
+*/
+/* Opcode: Divide * * *
+**
+** Pop the top two elements from the stack, divide the
+** first (what was on top of the stack) from the second (the
+** next on stack)
+** and push the result back onto the stack.  If either element
+** is a string then it is converted to a double using the atof()
+** function before the division.  Division by zero returns NULL.
+** If either operand is NULL, the result is NULL.
+*/
+/* Opcode: Remainder * * *
+**
+** Pop the top two elements from the stack, divide the
+** first (what was on top of the stack) from the second (the
+** next on stack)
+** and push the remainder after division onto the stack.  If either element
+** is a string then it is converted to a double using the atof()
+** function before the division.  Division by zero returns NULL.
+** If either operand is NULL, the result is NULL.
+*/
+case OP_Add:
+case OP_Subtract:
+case OP_Multiply:
+case OP_Divide:
+case OP_Remainder: {
+  int tos = p->tos;
+  int nos = tos - 1;
+  VERIFY( if( nos<0 ) goto not_enough_stack; )
+  if( ((aStack[tos].flags | aStack[nos].flags) & STK_Null)!=0 ){
+    POPSTACK;
+    Release(p, nos);
+    aStack[nos].flags = STK_Null;
+  }else if( (aStack[tos].flags & aStack[nos].flags & STK_Int)==STK_Int ){
+    int a, b;
+    a = aStack[tos].i;
+    b = aStack[nos].i;
+    switch( pOp->opcode ){
+      case OP_Add:         b += a;       break;
+      case OP_Subtract:    b -= a;       break;
+      case OP_Multiply:    b *= a;       break;
+      case OP_Divide: {
+        if( a==0 ) goto divide_by_zero;
+        b /= a;
+        break;
+      }
+      default: {
+        if( a==0 ) goto divide_by_zero;
+        b %= a;
+        break;
+      }
+    }
+    POPSTACK;
+    Release(p, nos);
+    aStack[nos].i = b;
+    aStack[nos].flags = STK_Int;
+  }else{
+    double a, b;
+    Realify(p, tos);
+    Realify(p, nos);
+    a = aStack[tos].r;
+    b = aStack[nos].r;
+    switch( pOp->opcode ){
+      case OP_Add:         b += a;       break;
+      case OP_Subtract:    b -= a;       break;
+      case OP_Multiply:    b *= a;       break;
+      case OP_Divide: {
+        if( a==0.0 ) goto divide_by_zero;
+        b /= a;
+        break;
+      }
+      default: {
+        int ia = (int)a;
+        int ib = (int)b;
+        if( ia==0.0 ) goto divide_by_zero;
+        b = ib % ia;
+        break;
+      }
+    }
+    POPSTACK;
+    Release(p, nos);
+    aStack[nos].r = b;
+    aStack[nos].flags = STK_Real;
+  }
+  break;
+
+divide_by_zero:
+  PopStack(p, 2);
+  p->tos = nos;
+  aStack[nos].flags = STK_Null;
+  break;
+}
+
+/* Opcode: Function P1 * P3
+**
+** Invoke a user function (P3 is a pointer to a Function structure that
+** defines the function) with P1 string arguments taken from the stack.
+** Pop all arguments from the stack and push back the result.
+**
+** See also: AggFunc
+*/
+case OP_Function: {
+  int n, i;
+  sqlite_func ctx;
+
+  n = pOp->p1;
+  VERIFY( if( n<0 ) goto bad_instruction; )
+  VERIFY( if( p->tos+1<n ) goto not_enough_stack; )
+  for(i=p->tos-n+1; i<=p->tos; i++){
+    if( aStack[i].flags & STK_Null ){
+      zStack[i] = 0;
+    }else{
+      Stringify(p, i);
+    }
+  }
+  ctx.pFunc = (FuncDef*)pOp->p3;
+  ctx.s.flags = STK_Null;
+  ctx.z = 0;
+  ctx.isError = 0;
+  ctx.isStep = 0;
+  (*ctx.pFunc->xFunc)(&ctx, n, (const char**)&zStack[p->tos-n+1]);
+  PopStack(p, n);
+  p->tos++;
+  aStack[p->tos] = ctx.s;
+  if( ctx.s.flags & STK_Dyn ){
+    zStack[p->tos] = ctx.z;
+  }else if( ctx.s.flags & STK_Str ){
+    zStack[p->tos] = aStack[p->tos].z;
+  }else{
+    zStack[p->tos] = 0;
+  }
+  if( ctx.isError ){
+    sqliteSetString(&p->zErrMsg, 
+       zStack[p->tos] ? zStack[p->tos] : "user function error", 0);
+    rc = SQLITE_ERROR;
+  }
+  break;
+}
+
+/* Opcode: BitAnd * * *
+**
+** Pop the top two elements from the stack.  Convert both elements
+** to integers.  Push back onto the stack the bit-wise AND of the
+** two elements.
+** If either operand is NULL, the result is NULL.
+*/
+/* Opcode: BitOr * * *
+**
+** Pop the top two elements from the stack.  Convert both elements
+** to integers.  Push back onto the stack the bit-wise OR of the
+** two elements.
+** If either operand is NULL, the result is NULL.
+*/
+/* Opcode: ShiftLeft * * *
+**
+** Pop the top two elements from the stack.  Convert both elements
+** to integers.  Push back onto the stack the top element shifted
+** left by N bits where N is the second element on the stack.
+** If either operand is NULL, the result is NULL.
+*/
+/* Opcode: ShiftRight * * *
+**
+** Pop the top two elements from the stack.  Convert both elements
+** to integers.  Push back onto the stack the top element shifted
+** right by N bits where N is the second element on the stack.
+** If either operand is NULL, the result is NULL.
+*/
+case OP_BitAnd:
+case OP_BitOr:
+case OP_ShiftLeft:
+case OP_ShiftRight: {
+  int tos = p->tos;
+  int nos = tos - 1;
+  int a, b;
+  VERIFY( if( nos<0 ) goto not_enough_stack; )
+  if( (aStack[tos].flags | aStack[nos].flags) & STK_Null ){
+    POPSTACK;
+    Release(p,nos);
+    aStack[nos].flags = STK_Null;
+    break;
+  }
+  Integerify(p, tos);
+  Integerify(p, nos);
+  a = aStack[tos].i;
+  b = aStack[nos].i;
+  switch( pOp->opcode ){
+    case OP_BitAnd:      a &= b;     break;
+    case OP_BitOr:       a |= b;     break;
+    case OP_ShiftLeft:   a <<= b;    break;
+    case OP_ShiftRight:  a >>= b;    break;
+    default:   /* CANT HAPPEN */     break;
+  }
+  POPSTACK;
+  Release(p, nos);
+  aStack[nos].i = a;
+  aStack[nos].flags = STK_Int;
+  break;
+}
+
+/* Opcode: AddImm  P1 * *
+** 
+** Add the value P1 to whatever is on top of the stack.  The result
+** is always an integer.
+**
+** To force the top of the stack to be an integer, just add 0.
+*/
+case OP_AddImm: {
+  int tos = p->tos;
+  VERIFY( if( tos<0 ) goto not_enough_stack; )
+  Integerify(p, tos);
+  aStack[tos].i += pOp->p1;
+  break;
+}
+
+/* Opcode: MustBeInt P1 P2 *
+** 
+** Force the top of the stack to be an integer.  If the top of the
+** stack is not an integer and cannot be converted into an integer
+** with out data loss, then jump immediately to P2, or if P2==0
+** raise an SQLITE_MISMATCH exception.
+**
+** If the top of the stack is not an integer and P2 is not zero and
+** P1 is 1, then the stack is popped.  In all other cases, the depth
+** of the stack is unchanged.
+*/
+case OP_MustBeInt: {
+  int tos = p->tos;
+  VERIFY( if( tos<0 ) goto not_enough_stack; )
+  if( aStack[tos].flags & STK_Int ){
+    /* Do nothing */
+  }else if( aStack[tos].flags & STK_Real ){
+    int i = aStack[tos].r;
+    double r = i;
+    if( r!=aStack[tos].r ){
+      goto mismatch;
+    }
+    aStack[tos].i = i;
+  }else if( aStack[tos].flags & STK_Str ){
+    int v;
+    if( !toInt(zStack[tos], &v) ){
+      goto mismatch;
+    }
+    p->aStack[tos].i = v;
+  }else{
+    goto mismatch;
+  }
+  Release(p, tos);
+  p->aStack[tos].flags = STK_Int;
+  break;
+
+mismatch:
+  if( pOp->p2==0 ){
+    rc = SQLITE_MISMATCH;
+    goto abort_due_to_error;
+  }else{
+    if( pOp->p1 ) POPSTACK;
+    pc = pOp->p2 - 1;
+  }
+  break;
+}
+
+/* Opcode: Eq P1 P2 *
+**
+** Pop the top two elements from the stack.  If they are equal, then
+** jump to instruction P2.  Otherwise, continue to the next instruction.
+**
+** If either operand is NULL (and thus if the result is unknown) then
+** take the jump if P1 is true.
+**
+** If both values are numeric, they are converted to doubles using atof()
+** and compared for equality that way.  Otherwise the strcmp() library
+** routine is used for the comparison.  For a pure text comparison
+** use OP_StrEq.
+**
+** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
+** stack if the jump would have been taken, or a 0 if not.  Push a
+** NULL if either operand was NULL.
+*/
+/* Opcode: Ne P1 P2 *
+**
+** Pop the top two elements from the stack.  If they are not equal, then
+** jump to instruction P2.  Otherwise, continue to the next instruction.
+**
+** If either operand is NULL (and thus if the result is unknown) then
+** take the jump if P1 is true.
+**
+** If both values are numeric, they are converted to doubles using atof()
+** and compared in that format.  Otherwise the strcmp() library
+** routine is used for the comparison.  For a pure text comparison
+** use OP_StrNe.
+**
+** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
+** stack if the jump would have been taken, or a 0 if not.  Push a
+** NULL if either operand was NULL.
+*/
+/* Opcode: Lt P1 P2 *
+**
+** Pop the top two elements from the stack.  If second element (the
+** next on stack) is less than the first (the top of stack), then
+** jump to instruction P2.  Otherwise, continue to the next instruction.
+** In other words, jump if NOS<TOS.
+**
+** If either operand is NULL (and thus if the result is unknown) then
+** take the jump if P1 is true.
+**
+** If both values are numeric, they are converted to doubles using atof()
+** and compared in that format.  Numeric values are always less than
+** non-numeric values.  If both operands are non-numeric, the strcmp() library
+** routine is used for the comparison.  For a pure text comparison
+** use OP_StrLt.
+**
+** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
+** stack if the jump would have been taken, or a 0 if not.  Push a
+** NULL if either operand was NULL.
+*/
+/* Opcode: Le P1 P2 *
+**
+** Pop the top two elements from the stack.  If second element (the
+** next on stack) is less than or equal to the first (the top of stack),
+** then jump to instruction P2. In other words, jump if NOS<=TOS.
+**
+** If either operand is NULL (and thus if the result is unknown) then
+** take the jump if P1 is true.
+**
+** If both values are numeric, they are converted to doubles using atof()
+** and compared in that format.  Numeric values are always less than
+** non-numeric values.  If both operands are non-numeric, the strcmp() library
+** routine is used for the comparison.  For a pure text comparison
+** use OP_StrLe.
+**
+** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
+** stack if the jump would have been taken, or a 0 if not.  Push a
+** NULL if either operand was NULL.
+*/
+/* Opcode: Gt P1 P2 *
+**
+** Pop the top two elements from the stack.  If second element (the
+** next on stack) is greater than the first (the top of stack),
+** then jump to instruction P2. In other words, jump if NOS>TOS.
+**
+** If either operand is NULL (and thus if the result is unknown) then
+** take the jump if P1 is true.
+**
+** If both values are numeric, they are converted to doubles using atof()
+** and compared in that format.  Numeric values are always less than
+** non-numeric values.  If both operands are non-numeric, the strcmp() library
+** routine is used for the comparison.  For a pure text comparison
+** use OP_StrGt.
+**
+** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
+** stack if the jump would have been taken, or a 0 if not.  Push a
+** NULL if either operand was NULL.
+*/
+/* Opcode: Ge P1 P2 *
+**
+** Pop the top two elements from the stack.  If second element (the next
+** on stack) is greater than or equal to the first (the top of stack),
+** then jump to instruction P2. In other words, jump if NOS>=TOS.
+**
+** If either operand is NULL (and thus if the result is unknown) then
+** take the jump if P1 is true.
+**
+** If both values are numeric, they are converted to doubles using atof()
+** and compared in that format.  Numeric values are always less than
+** non-numeric values.  If both operands are non-numeric, the strcmp() library
+** routine is used for the comparison.  For a pure text comparison
+** use OP_StrGe.
+**
+** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
+** stack if the jump would have been taken, or a 0 if not.  Push a
+** NULL if either operand was NULL.
+*/
+case OP_Eq:
+case OP_Ne:
+case OP_Lt:
+case OP_Le:
+case OP_Gt:
+case OP_Ge: {
+  int tos = p->tos;
+  int nos = tos - 1;
+  int c, v;
+  int ft, fn;
+  VERIFY( if( nos<0 ) goto not_enough_stack; )
+  ft = aStack[tos].flags;
+  fn = aStack[nos].flags;
+  if( (ft | fn) & STK_Null ){
+    POPSTACK;
+    POPSTACK;
+    if( pOp->p2 ){
+      if( pOp->p1 ) pc = pOp->p2-1;
+    }else{
+      p->tos++;
+      aStack[nos].flags = STK_Null;
+    }
+    break;
+  }else if( (ft & fn & STK_Int)==STK_Int ){
+    c = aStack[nos].i - aStack[tos].i;
+  }else if( (ft & STK_Int)!=0 && (fn & STK_Str)!=0 && toInt(zStack[nos],&v) ){
+    Release(p, nos);
+    aStack[nos].i = v;
+    aStack[nos].flags = STK_Int;
+    c = aStack[nos].i - aStack[tos].i;
+  }else if( (fn & STK_Int)!=0 && (ft & STK_Str)!=0 && toInt(zStack[tos],&v) ){
+    Release(p, tos);
+    aStack[tos].i = v;
+    aStack[tos].flags = STK_Int;
+    c = aStack[nos].i - aStack[tos].i;
+  }else{
+    Stringify(p, tos);
+    Stringify(p, nos);
+    c = sqliteCompare(zStack[nos], zStack[tos]);
+  }
+  switch( pOp->opcode ){
+    case OP_Eq:    c = c==0;     break;
+    case OP_Ne:    c = c!=0;     break;
+    case OP_Lt:    c = c<0;      break;
+    case OP_Le:    c = c<=0;     break;
+    case OP_Gt:    c = c>0;      break;
+    default:       c = c>=0;     break;
+  }
+  POPSTACK;
+  POPSTACK;
+  if( pOp->p2 ){
+    if( c ) pc = pOp->p2-1;
+  }else{
+    p->tos++;
+    aStack[nos].flags = STK_Int;
+    aStack[nos].i = c;
+  }
+  break;
+}
+/* INSERT NO CODE HERE!
+**
+** The opcode numbers are extracted from this source file by doing
+**
+**    grep '^case OP_' vdbe.c | ... >opcodes.h
+**
+** The opcodes are numbered in the order that they appear in this file.
+** But in order for the expression generating code to work right, the
+** string comparison operators that follow must be numbered exactly 6
+** greater than the numeric comparison opcodes above.  So no other
+** cases can appear between the two.
+*/
+/* Opcode: StrEq P1 P2 *
+**
+** Pop the top two elements from the stack.  If they are equal, then
+** jump to instruction P2.  Otherwise, continue to the next instruction.
+**
+** If either operand is NULL (and thus if the result is unknown) then
+** take the jump if P1 is true.
+**
+** The strcmp() library routine is used for the comparison.  For a
+** numeric comparison, use OP_Eq.
+**
+** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
+** stack if the jump would have been taken, or a 0 if not.  Push a
+** NULL if either operand was NULL.
+*/
+/* Opcode: StrNe P1 P2 *
+**
+** Pop the top two elements from the stack.  If they are not equal, then
+** jump to instruction P2.  Otherwise, continue to the next instruction.
+**
+** If either operand is NULL (and thus if the result is unknown) then
+** take the jump if P1 is true.
+**
+** The strcmp() library routine is used for the comparison.  For a
+** numeric comparison, use OP_Ne.
+**
+** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
+** stack if the jump would have been taken, or a 0 if not.  Push a
+** NULL if either operand was NULL.
+*/
+/* Opcode: StrLt P1 P2 *
+**
+** Pop the top two elements from the stack.  If second element (the
+** next on stack) is less than the first (the top of stack), then
+** jump to instruction P2.  Otherwise, continue to the next instruction.
+** In other words, jump if NOS<TOS.
+**
+** If either operand is NULL (and thus if the result is unknown) then
+** take the jump if P1 is true.
+**
+** The strcmp() library routine is used for the comparison.  For a
+** numeric comparison, use OP_Lt.
+**
+** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
+** stack if the jump would have been taken, or a 0 if not.  Push a
+** NULL if either operand was NULL.
+*/
+/* Opcode: StrLe P1 P2 *
+**
+** Pop the top two elements from the stack.  If second element (the
+** next on stack) is less than or equal to the first (the top of stack),
+** then jump to instruction P2. In other words, jump if NOS<=TOS.
+**
+** If either operand is NULL (and thus if the result is unknown) then
+** take the jump if P1 is true.
+**
+** The strcmp() library routine is used for the comparison.  For a
+** numeric comparison, use OP_Le.
+**
+** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
+** stack if the jump would have been taken, or a 0 if not.  Push a
+** NULL if either operand was NULL.
+*/
+/* Opcode: StrGt P1 P2 *
+**
+** Pop the top two elements from the stack.  If second element (the
+** next on stack) is greater than the first (the top of stack),
+** then jump to instruction P2. In other words, jump if NOS>TOS.
+**
+** If either operand is NULL (and thus if the result is unknown) then
+** take the jump if P1 is true.
+**
+** The strcmp() library routine is used for the comparison.  For a
+** numeric comparison, use OP_Gt.
+**
+** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
+** stack if the jump would have been taken, or a 0 if not.  Push a
+** NULL if either operand was NULL.
+*/
+/* Opcode: StrGe P1 P2 *
+**
+** Pop the top two elements from the stack.  If second element (the next
+** on stack) is greater than or equal to the first (the top of stack),
+** then jump to instruction P2. In other words, jump if NOS>=TOS.
+**
+** If either operand is NULL (and thus if the result is unknown) then
+** take the jump if P1 is true.
+**
+** The strcmp() library routine is used for the comparison.  For a
+** numeric comparison, use OP_Ge.
+**
+** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
+** stack if the jump would have been taken, or a 0 if not.  Push a
+** NULL if either operand was NULL.
+*/
+case OP_StrEq:
+case OP_StrNe:
+case OP_StrLt:
+case OP_StrLe:
+case OP_StrGt:
+case OP_StrGe: {
+  int tos = p->tos;
+  int nos = tos - 1;
+  int c;
+  VERIFY( if( nos<0 ) goto not_enough_stack; )
+  if( (aStack[nos].flags | aStack[tos].flags) & STK_Null ){
+    POPSTACK;
+    POPSTACK;
+    if( pOp->p2 ){
+      if( pOp->p1 ) pc = pOp->p2-1;
+    }else{
+      p->tos++;
+      aStack[nos].flags = STK_Null;
+    }
+    break;
+  }else{
+    Stringify(p, tos);
+    Stringify(p, nos);
+    c = strcmp(zStack[nos], zStack[tos]);
+  }
+  /* The asserts on each case of the following switch are there to verify
+  ** that string comparison opcodes are always exactly 6 greater than the
+  ** corresponding numeric comparison opcodes.  The code generator depends
+  ** on this fact.
+  */
+  switch( pOp->opcode ){
+    case OP_StrEq:    c = c==0;    assert( pOp->opcode-6==OP_Eq );   break;
+    case OP_StrNe:    c = c!=0;    assert( pOp->opcode-6==OP_Ne );   break;
+    case OP_StrLt:    c = c<0;     assert( pOp->opcode-6==OP_Lt );   break;
+    case OP_StrLe:    c = c<=0;    assert( pOp->opcode-6==OP_Le );   break;
+    case OP_StrGt:    c = c>0;     assert( pOp->opcode-6==OP_Gt );   break;
+    default:          c = c>=0;    assert( pOp->opcode-6==OP_Ge );   break;
+  }
+  POPSTACK;
+  POPSTACK;
+  if( pOp->p2 ){
+    if( c ) pc = pOp->p2-1;
+  }else{
+    p->tos++;
+    aStack[nos].flags = STK_Int;
+    aStack[nos].i = c;
+  }
+  break;
+}
+
+/* Opcode: And * * *
+**
+** Pop two values off the stack.  Take the logical AND of the
+** two values and push the resulting boolean value back onto the
+** stack. 
+*/
+/* Opcode: Or * * *
+**
+** Pop two values off the stack.  Take the logical OR of the
+** two values and push the resulting boolean value back onto the
+** stack. 
+*/
+case OP_And:
+case OP_Or: {
+  int tos = p->tos;
+  int nos = tos - 1;
+  int v1, v2;    /* 0==TRUE, 1==FALSE, 2==UNKNOWN or NULL */
+
+  VERIFY( if( nos<0 ) goto not_enough_stack; )
+  if( aStack[tos].flags & STK_Null ){
+    v1 = 2;
+  }else{
+    Integerify(p, tos);
+    v1 = aStack[tos].i==0;
+  }
+  if( aStack[nos].flags & STK_Null ){
+    v2 = 2;
+  }else{
+    Integerify(p, nos);
+    v2 = aStack[nos].i==0;
+  }
+  if( pOp->opcode==OP_And ){
+    static const unsigned char and_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
+    v1 = and_logic[v1*3+v2];
+  }else{
+    static const unsigned char or_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
+    v1 = or_logic[v1*3+v2];
+  }
+  POPSTACK;
+  Release(p, nos);
+  if( v1==2 ){
+    aStack[nos].flags = STK_Null;
+  }else{
+    aStack[nos].i = v1==0;
+    aStack[nos].flags = STK_Int;
+  }
+  break;
+}
+
+/* Opcode: Negative * * *
+**
+** Treat the top of the stack as a numeric quantity.  Replace it
+** with its additive inverse.  If the top of the stack is NULL
+** its value is unchanged.
+*/
+/* Opcode: AbsValue * * *
+**
+** Treat the top of the stack as a numeric quantity.  Replace it
+** with its absolute value. If the top of the stack is NULL
+** its value is unchanged.
+*/
+case OP_Negative:
+case OP_AbsValue: {
+  int tos = p->tos;
+  VERIFY( if( tos<0 ) goto not_enough_stack; )
+  if( aStack[tos].flags & STK_Real ){
+    Release(p, tos);
+    if( pOp->opcode==OP_Negative || aStack[tos].r<0.0 ){
+      aStack[tos].r = -aStack[tos].r;
+    }
+    aStack[tos].flags = STK_Real;
+  }else if( aStack[tos].flags & STK_Int ){
+    Release(p, tos);
+    if( pOp->opcode==OP_Negative ||  aStack[tos].i<0 ){
+      aStack[tos].i = -aStack[tos].i;
+    }
+    aStack[tos].flags = STK_Int;
+  }else if( aStack[tos].flags & STK_Null ){
+    /* Do nothing */
+  }else{
+    Realify(p, tos);
+    Release(p, tos);
+    if( pOp->opcode==OP_Negative ||  aStack[tos].r<0.0 ){
+      aStack[tos].r = -aStack[tos].r;
+    }
+    aStack[tos].flags = STK_Real;
+  }
+  break;
+}
+
+/* Opcode: Not * * *
+**
+** Interpret the top of the stack as a boolean value.  Replace it
+** with its complement.  If the top of the stack is NULL its value
+** is unchanged.
+*/
+case OP_Not: {
+  int tos = p->tos;
+  VERIFY( if( p->tos<0 ) goto not_enough_stack; )
+  if( aStack[tos].flags & STK_Null ) break;  /* Do nothing to NULLs */
+  Integerify(p, tos);
+  Release(p, tos);
+  aStack[tos].i = !aStack[tos].i;
+  aStack[tos].flags = STK_Int;
+  break;
+}
+
+/* Opcode: BitNot * * *
+**
+** Interpret the top of the stack as an value.  Replace it
+** with its ones-complement.  If the top of the stack is NULL its
+** value is unchanged.
+*/
+case OP_BitNot: {
+  int tos = p->tos;
+  VERIFY( if( p->tos<0 ) goto not_enough_stack; )
+  if( aStack[tos].flags & STK_Null ) break;  /* Do nothing to NULLs */
+  Integerify(p, tos);
+  Release(p, tos);
+  aStack[tos].i = ~aStack[tos].i;
+  aStack[tos].flags = STK_Int;
+  break;
+}
+
+/* Opcode: Noop * * *
+**
+** Do nothing.  This instruction is often useful as a jump
+** destination.
+*/
+case OP_Noop: {
+  break;
+}
+
+/* Opcode: If P1 P2 *
+**
+** Pop a single boolean from the stack.  If the boolean popped is
+** true, then jump to p2.  Otherwise continue to the next instruction.
+** An integer is false if zero and true otherwise.  A string is
+** false if it has zero length and true otherwise.
+**
+** If the value popped of the stack is NULL, then take the jump if P1
+** is true and fall through if P1 is false.
+*/
+/* Opcode: IfNot P1 P2 *
+**
+** Pop a single boolean from the stack.  If the boolean popped is
+** false, then jump to p2.  Otherwise continue to the next instruction.
+** An integer is false if zero and true otherwise.  A string is
+** false if it has zero length and true otherwise.
+**
+** If the value popped of the stack is NULL, then take the jump if P1
+** is true and fall through if P1 is false.
+*/
+case OP_If:
+case OP_IfNot: {
+  int c;
+  VERIFY( if( p->tos<0 ) goto not_enough_stack; )
+  if( aStack[p->tos].flags & STK_Null ){
+    c = pOp->p1;
+  }else{
+    Integerify(p, p->tos);
+    c = aStack[p->tos].i;
+    if( pOp->opcode==OP_IfNot ) c = !c;
+  }
+  POPSTACK;
+  if( c ) pc = pOp->p2-1;
+  break;
+}
+
+/* Opcode: IsNull P1 P2 *
+**
+** If any of the top abs(P1) values on the stack are NULL, then jump
+** to P2.  The stack is popped P1 times if P1>0.  If P1<0 then all values
+** are left unchanged on the stack.
+*/
+case OP_IsNull: {
+  int i, cnt;
+  cnt = pOp->p1;
+  if( cnt<0 ) cnt = -cnt;
+  VERIFY( if( p->tos+1-cnt<0 ) goto not_enough_stack; )
+  for(i=0; i<cnt; i++){
+    if( aStack[p->tos-i].flags & STK_Null ){
+      pc = pOp->p2-1;
+      break;
+    }
+  }
+  if( pOp->p1>0 ) PopStack(p, cnt);
+  break;
+}
+
+/* Opcode: NotNull P1 P2 *
+**
+** Jump to P2 if the top value on the stack is not NULL.  Pop the
+** stack if P1 is greater than zero.  If P1 is less than or equal to
+** zero then leave the value on the stack.
+*/
+case OP_NotNull: {
+  VERIFY( if( p->tos<0 ) goto not_enough_stack; )
+  if( (aStack[p->tos].flags & STK_Null)==0 ) pc = pOp->p2-1;
+  if( pOp->p1>0 ){ POPSTACK; }
+  break;
+}
+
+/* Opcode: MakeRecord P1 P2 *
+**
+** Convert the top P1 entries of the stack into a single entry
+** suitable for use as a data record in a database table.  The
+** details of the format are irrelavant as long as the OP_Column
+** opcode can decode the record later.  Refer to source code
+** comments for the details of the record format.
+**
+** If P2 is true (non-zero) and one or more of the P1 entries
+** that go into building the record is NULL, then add some extra
+** bytes to the record to make it distinct for other entries created
+** during the same run of the VDBE.  The extra bytes added are a
+** counter that is reset with each run of the VDBE, so records
+** created this way will not necessarily be distinct across runs.
+** But they should be distinct for transient tables (created using
+** OP_OpenTemp) which is what they are intended for.
+**
+** (Later:) The P2==1 option was intended to make NULLs distinct
+** for the UNION operator.  But I have since discovered that NULLs
+** are indistinct for UNION.  So this option is never used.
+*/
+case OP_MakeRecord: {
+  char *zNewRecord;
+  int nByte;
+  int nField;
+  int i, j;
+  int idxWidth;
+  u32 addr;
+  int addUnique = 0;   /* True to cause bytes to be added to make the
+                       ** generated record distinct */
+  char zTemp[NBFS];    /* Temp space for small records */
+
+  /* Assuming the record contains N fields, the record format looks
+  ** like this:
+  **
+  **   -------------------------------------------------------------------
+  **   | idx0 | idx1 | ... | idx(N-1) | idx(N) | data0 | ... | data(N-1) |
+  **   -------------------------------------------------------------------
+  **
+  ** All data fields are converted to strings before being stored and
+  ** are stored with their null terminators.  NULL entries omit the
+  ** null terminator.  Thus an empty string uses 1 byte and a NULL uses
+  ** zero bytes.  Data(0) is taken from the lowest element of the stack
+  ** and data(N-1) is the top of the stack.
+  **
+  ** Each of the idx() entries is either 1, 2, or 3 bytes depending on
+  ** how big the total record is.  Idx(0) contains the offset to the start
+  ** of data(0).  Idx(k) contains the offset to the start of data(k).
+  ** Idx(N) contains the total number of bytes in the record.
+  */
+  nField = pOp->p1;
+  VERIFY( if( p->tos+1<nField ) goto not_enough_stack; )
+  nByte = 0;
+  for(i=p->tos-nField+1; i<=p->tos; i++){
+    if( (aStack[i].flags & STK_Null) ){
+      addUnique = pOp->p2;
+    }else{
+      Stringify(p, i);
+      nByte += aStack[i].n;
+    }
+  }
+  if( addUnique ) nByte += sizeof(p->uniqueCnt);
+  if( nByte + nField + 1 < 256 ){
+    idxWidth = 1;
+  }else if( nByte + 2*nField + 2 < 65536 ){
+    idxWidth = 2;
+  }else{
+    idxWidth = 3;
+  }
+  nByte += idxWidth*(nField + 1);
+  if( nByte>MAX_BYTES_PER_ROW ){
+    rc = SQLITE_TOOBIG;
+    goto abort_due_to_error;
+  }
+  if( nByte<=NBFS ){
+    zNewRecord = zTemp;
+  }else{
+    zNewRecord = sqliteMallocRaw( nByte );
+    if( zNewRecord==0 ) goto no_mem;
+  }
+  j = 0;
+  addr = idxWidth*(nField+1) + addUnique*sizeof(p->uniqueCnt);
+  for(i=p->tos-nField+1; i<=p->tos; i++){
+    zNewRecord[j++] = addr & 0xff;
+    if( idxWidth>1 ){
+      zNewRecord[j++] = (addr>>8)&0xff;
+      if( idxWidth>2 ){
+        zNewRecord[j++] = (addr>>16)&0xff;
+      }
+    }
+    if( (aStack[i].flags & STK_Null)==0 ){
+      addr += aStack[i].n;
+    }
+  }
+  zNewRecord[j++] = addr & 0xff;
+  if( idxWidth>1 ){
+    zNewRecord[j++] = (addr>>8)&0xff;
+    if( idxWidth>2 ){
+      zNewRecord[j++] = (addr>>16)&0xff;
+    }
+  }
+  if( addUnique ){
+    memcpy(&zNewRecord[j], &p->uniqueCnt, sizeof(p->uniqueCnt));
+    p->uniqueCnt++;
+    j += sizeof(p->uniqueCnt);
+  }
+  for(i=p->tos-nField+1; i<=p->tos; i++){
+    if( (aStack[i].flags & STK_Null)==0 ){
+      memcpy(&zNewRecord[j], zStack[i], aStack[i].n);
+      j += aStack[i].n;
+    }
+  }
+  PopStack(p, nField);
+  p->tos++;
+  aStack[p->tos].n = nByte;
+  if( nByte<=NBFS ){
+    assert( zNewRecord==zTemp );
+    memcpy(aStack[p->tos].z, zTemp, nByte);
+    zStack[p->tos] = aStack[p->tos].z;
+    aStack[p->tos].flags = STK_Str;
+  }else{
+    assert( zNewRecord!=zTemp );
+    aStack[p->tos].flags = STK_Str | STK_Dyn;
+    zStack[p->tos] = zNewRecord;
+  }
+  break;
+}
+
+/* Opcode: MakeKey P1 P2 P3
+**
+** Convert the top P1 entries of the stack into a single entry suitable
+** for use as the key in an index.  The top P1 records are
+** converted to strings and merged.  The null-terminators 
+** are retained and used as separators.
+** The lowest entry in the stack is the first field and the top of the
+** stack becomes the last.
+**
+** If P2 is not zero, then the original entries remain on the stack
+** and the new key is pushed on top.  If P2 is zero, the original
+** data is popped off the stack first then the new key is pushed
+** back in its place.
+**
+** P3 is a string that is P1 characters long.  Each character is either
+** an 'n' or a 't' to indicates if the argument should be numeric or
+** text.  The first character corresponds to the lowest element on the
+** stack.  If P3 is NULL then all arguments are assumed to be numeric.
+**
+** The key is a concatenation of fields.  Each field is terminated by
+** a single 0x00 character.  A NULL field is introduced by an 'a' and
+** is followed immediately by its 0x00 terminator.  A numeric field is
+** introduced by a single character 'b' and is followed by a sequence
+** of characters that represent the number such that a comparison of
+** the character string using memcpy() sorts the numbers in numerical
+** order.  The character strings for numbers are generated using the
+** sqliteRealToSortable() function.  A text field is introduced by a
+** 'c' character and is followed by the exact text of the field.  The
+** use of an 'a', 'b', or 'c' character at the beginning of each field
+** guarantees that NULL sort before numbers and that numbers sort
+** before text.  0x00 characters do not occur except as separators
+** between fields.
+**
+** See also: MakeIdxKey, SortMakeKey
+*/
+/* Opcode: MakeIdxKey P1 P2 P3
+**
+** Convert the top P1 entries of the stack into a single entry suitable
+** for use as the key in an index.  In addition, take one additional integer
+** off of the stack, treat that integer as a four-byte record number, and
+** append the four bytes to the key.  Thus a total of P1+1 entries are
+** popped from the stack for this instruction and a single entry is pushed
+** back.  The first P1 entries that are popped are strings and the last
+** entry (the lowest on the stack) is an integer record number.
+**
+** The converstion of the first P1 string entries occurs just like in
+** MakeKey.  Each entry is separated from the others by a null.
+** The entire concatenation is null-terminated.  The lowest entry
+** in the stack is the first field and the top of the stack becomes the
+** last.
+**
+** If P2 is not zero and one or more of the P1 entries that go into the
+** generated key is NULL, then jump to P2 after the new key has been
+** pushed on the stack.  In other words, jump to P2 if the key is
+** guaranteed to be unique.  This jump can be used to skip a subsequent
+** uniqueness test.
+**
+** P3 is a string that is P1 characters long.  Each character is either
+** an 'n' or a 't' to indicates if the argument should be numeric or
+** text.  The first character corresponds to the lowest element on the
+** stack.  If P3 is null then all arguments are assumed to be numeric.
+**
+** See also:  MakeKey, SortMakeKey
+*/
+case OP_MakeIdxKey:
+case OP_MakeKey: {
+  char *zNewKey;
+  int nByte;
+  int nField;
+  int addRowid;
+  int i, j;
+  int containsNull = 0;
+  char zTemp[NBFS];
+
+  addRowid = pOp->opcode==OP_MakeIdxKey;
+  nField = pOp->p1;
+  VERIFY( if( p->tos+1+addRowid<nField ) goto not_enough_stack; )
+  nByte = 0;
+  for(j=0, i=p->tos-nField+1; i<=p->tos; i++, j++){
+    int flags = aStack[i].flags;
+    int len;
+    char *z;
+    if( flags & STK_Null ){
+      nByte += 2;
+      containsNull = 1;
+    }else if( pOp->p3 && pOp->p3[j]=='t' ){
+      Stringify(p, i);
+      aStack[i].flags &= ~(STK_Int|STK_Real);
+      nByte += aStack[i].n+1;
+    }else if( (flags & (STK_Real|STK_Int))!=0 || isNumber(zStack[i]) ){
+      if( (flags & (STK_Real|STK_Int))==STK_Int ){
+        aStack[i].r = aStack[i].i;
+      }else if( (flags & (STK_Real|STK_Int))==0 ){
+        aStack[i].r = atof(zStack[i]);
+      }
+      Release(p, i);
+      z = aStack[i].z;
+      sqliteRealToSortable(aStack[i].r, z);
+      len = strlen(z);
+      zStack[i] = 0;
+      aStack[i].flags = STK_Real;
+      aStack[i].n = len+1;
+      nByte += aStack[i].n+1;
+    }else{
+      nByte += aStack[i].n+1;
+    }
+  }
+  if( nByte+sizeof(u32)>MAX_BYTES_PER_ROW ){
+    rc = SQLITE_TOOBIG;
+    goto abort_due_to_error;
+  }
+  if( addRowid ) nByte += sizeof(u32);
+  if( nByte<=NBFS ){
+    zNewKey = zTemp;
+  }else{
+    zNewKey = sqliteMallocRaw( nByte );
+    if( zNewKey==0 ) goto no_mem;
+  }
+  j = 0;
+  for(i=p->tos-nField+1; i<=p->tos; i++){
+    if( aStack[i].flags & STK_Null ){
+      zNewKey[j++] = 'a';
+      zNewKey[j++] = 0;
+    }else{
+      if( aStack[i].flags & (STK_Int|STK_Real) ){
+        zNewKey[j++] = 'b';
+      }else{
+        zNewKey[j++] = 'c';
+      }
+      memcpy(&zNewKey[j], zStack[i] ? zStack[i] : aStack[i].z, aStack[i].n);
+      j += aStack[i].n;
+    }
+  }
+  if( addRowid ){
+    u32 iKey;
+    Integerify(p, p->tos-nField);
+    iKey = intToKey(aStack[p->tos-nField].i);
+    memcpy(&zNewKey[j], &iKey, sizeof(u32));
+    PopStack(p, nField+1);
+    if( pOp->p2 && containsNull ) pc = pOp->p2 - 1;
+  }else{
+    if( pOp->p2==0 ) PopStack(p, nField+addRowid);
+  }
+  p->tos++;
+  aStack[p->tos].n = nByte;
+  if( nByte<=NBFS ){
+    assert( zNewKey==zTemp );
+    zStack[p->tos] = aStack[p->tos].z;
+    memcpy(zStack[p->tos], zTemp, nByte);
+    aStack[p->tos].flags = STK_Str;
+  }else{
+    aStack[p->tos].flags = STK_Str|STK_Dyn;
+    zStack[p->tos] = zNewKey;
+  }
+  break;
+}
+
+/* Opcode: IncrKey * * *
+**
+** The top of the stack should contain an index key generated by
+** The MakeKey opcode.  This routine increases the least significant
+** byte of that key by one.  This is used so that the MoveTo opcode
+** will move to the first entry greater than the key rather than to
+** the key itself.
+*/
+case OP_IncrKey: {
+  int tos = p->tos;
+
+  VERIFY( if( tos<0 ) goto bad_instruction );
+  Stringify(p, tos);
+  if( aStack[tos].flags & (STK_Static|STK_Ephem) ){
+    /* CANT HAPPEN.  The IncrKey opcode is only applied to keys
+    ** generated by MakeKey or MakeIdxKey and the results of those
+    ** operands are always dynamic strings.
+    */
+    goto abort_due_to_error;
+  }
+  zStack[tos][aStack[tos].n-1]++;
+  break;
+}
+
+/* Opcode: Checkpoint * * *
+**
+** Begin a checkpoint.  A checkpoint is the beginning of a operation that
+** is part of a larger transaction but which might need to be rolled back
+** itself without effecting the containing transaction.  A checkpoint will
+** be automatically committed or rollback when the VDBE halts.
+*/
+case OP_Checkpoint: {
+  rc = sqliteBtreeBeginCkpt(pBt);
+  if( rc==SQLITE_OK && db->pBeTemp ){
+     rc = sqliteBtreeBeginCkpt(db->pBeTemp);
+  }
+  break;
+}
+
+/* Opcode: Transaction P1 * *
+**
+** Begin a transaction.  The transaction ends when a Commit or Rollback
+** opcode is encountered.  Depending on the ON CONFLICT setting, the
+** transaction might also be rolled back if an error is encountered.
+**
+** If P1 is true, then the transaction is started on the temporary
+** tables of the database only.  The main database file is not write
+** locked and other processes can continue to read the main database
+** file.
+**
+** A write lock is obtained on the database file when a transaction is
+** started.  No other process can read or write the file while the
+** transaction is underway.  Starting a transaction also creates a
+** rollback journal.  A transaction must be started before any changes
+** can be made to the database.
+*/
+case OP_Transaction: {
+  int busy = 1;
+  if( db->pBeTemp && !p->inTempTrans ){
+    rc = sqliteBtreeBeginTrans(db->pBeTemp);
+    if( rc!=SQLITE_OK ){
+      goto abort_due_to_error;
+    }
+    p->inTempTrans = 1;
+  }
+  while( pOp->p1==0 && busy ){
+    rc = sqliteBtreeBeginTrans(pBt);
+    switch( rc ){
+      case SQLITE_BUSY: {
+        if( db->xBusyCallback==0 ){
+          p->pc = pc;
+          p->undoTransOnError = 1;
+          p->rc = SQLITE_BUSY;
+          return SQLITE_BUSY;
+        }else if( (*db->xBusyCallback)(db->pBusyArg, "", busy++)==0 ){
+          sqliteSetString(&p->zErrMsg, sqlite_error_string(rc), 0);
+          busy = 0;
+        }
+        break;
+      }
+      case SQLITE_READONLY: {
+        rc = SQLITE_OK;
+        /* Fall thru into the next case */
+      }
+      case SQLITE_OK: {
+        p->inTempTrans = 0;
+        busy = 0;
+        break;
+      }
+      default: {
+        goto abort_due_to_error;
+      }
+    }
+  }
+  p->undoTransOnError = 1;
+  break;
+}
+
+/* Opcode: Commit * * *
+**
+** Cause all modifications to the database that have been made since the
+** last Transaction to actually take effect.  No additional modifications
+** are allowed until another transaction is started.  The Commit instruction
+** deletes the journal file and releases the write lock on the database.
+** A read lock continues to be held if there are still cursors open.
+*/
+case OP_Commit: {
+  if( db->pBeTemp==0 || (rc = sqliteBtreeCommit(db->pBeTemp))==SQLITE_OK ){
+    rc = p->inTempTrans ? SQLITE_OK : sqliteBtreeCommit(pBt);
+  }
+  if( rc==SQLITE_OK ){
+    sqliteCommitInternalChanges(db);
+  }else{
+    if( db->pBeTemp ) sqliteBtreeRollback(db->pBeTemp);
+    sqliteBtreeRollback(pBt);
+    sqliteRollbackInternalChanges(db);
+  }
+  p->inTempTrans = 0;
+  break;
+}
+
+/* Opcode: Rollback * * *
+**
+** Cause all modifications to the database that have been made since the
+** last Transaction to be undone. The database is restored to its state
+** before the Transaction opcode was executed.  No additional modifications
+** are allowed until another transaction is started.
+**
+** This instruction automatically closes all cursors and releases both
+** the read and write locks on the database.
+*/
+case OP_Rollback: {
+  if( db->pBeTemp ){
+    sqliteBtreeRollback(db->pBeTemp);
+  }
+  rc = sqliteBtreeRollback(pBt);
+  sqliteRollbackInternalChanges(db);
+  break;
+}
+
+/* Opcode: ReadCookie * P2 *
+**
+** When P2==0, 
+** read the schema cookie from the database file and push it onto the
+** stack.  The schema cookie is an integer that is used like a version
+** number for the database schema.  Everytime the schema changes, the
+** cookie changes to a new random value.  This opcode is used during
+** initialization to read the initial cookie value so that subsequent
+** database accesses can verify that the cookie has not changed.
+**
+** If P2>0, then read global database parameter number P2.  There is
+** a small fixed number of global database parameters.  P2==1 is the
+** database version number.  P2==2 is the recommended pager cache size.
+** Other parameters are currently unused.
+**
+** There must be a read-lock on the database (either a transaction
+** must be started or there must be an open cursor) before
+** executing this instruction.
+*/
+case OP_ReadCookie: {
+  int i = ++p->tos;
+  int aMeta[SQLITE_N_BTREE_META];
+  assert( pOp->p2<SQLITE_N_BTREE_META );
+  rc = sqliteBtreeGetMeta(pBt, aMeta);
+  aStack[i].i = aMeta[1+pOp->p2];
+  aStack[i].flags = STK_Int;
+  break;
+}
+
+/* Opcode: SetCookie * P2 *
+**
+** When P2==0,
+** this operation changes the value of the schema cookie on the database.
+** The new value is top of the stack.
+** When P2>0, the value of global database parameter
+** number P2 is changed.  See ReadCookie for more information about
+** global database parametes.
+**
+** The schema cookie changes its value whenever the database schema changes.
+** That way, other processes can recognize when the schema has changed
+** and reread it.
+**
+** A transaction must be started before executing this opcode.
+*/
+case OP_SetCookie: {
+  int aMeta[SQLITE_N_BTREE_META];
+  assert( pOp->p2<SQLITE_N_BTREE_META );
+  VERIFY( if( p->tos<0 ) goto not_enough_stack; )
+  Integerify(p, p->tos)
+  rc = sqliteBtreeGetMeta(pBt, aMeta);
+  if( rc==SQLITE_OK ){
+    aMeta[1+pOp->p2] = aStack[p->tos].i;
+    rc = sqliteBtreeUpdateMeta(pBt, aMeta);
+  }
+  POPSTACK;
+  break;
+}
+
+/* Opcode: VerifyCookie P1 P2 *
+**
+** Check the value of global database parameter number P2 and make
+** sure it is equal to P1.  P2==0 is the schema cookie.  P1==1 is
+** the database version.  If the values do not match, abort with
+** an SQLITE_SCHEMA error.
+**
+** The cookie changes its value whenever the database schema changes.
+** This operation is used to detect when that the cookie has changed
+** and that the current process needs to reread the schema.
+**
+** Either a transaction needs to have been started or an OP_Open needs
+** to be executed (to establish a read lock) before this opcode is
+** invoked.
+*/
+case OP_VerifyCookie: {
+  int aMeta[SQLITE_N_BTREE_META];
+  assert( pOp->p2<SQLITE_N_BTREE_META );
+  rc = sqliteBtreeGetMeta(pBt, aMeta);
+  if( rc==SQLITE_OK && aMeta[1+pOp->p2]!=pOp->p1 ){
+    sqliteSetString(&p->zErrMsg, "database schema has changed", 0);
+    rc = SQLITE_SCHEMA;
+  }
+  break;
+}
+
+/* Opcode: Open P1 P2 P3
+**
+** Open a read-only cursor for the database table whose root page is
+** P2 in the main database file.  Give the new cursor an identifier
+** of P1.  The P1 values need not be contiguous but all P1 values
+** should be small integers.  It is an error for P1 to be negative.
+**
+** If P2==0 then take the root page number from the top of the stack.
+**
+** There will be a read lock on the database whenever there is an
+** open cursor.  If the database was unlocked prior to this instruction
+** then a read lock is acquired as part of this instruction.  A read
+** lock allows other processes to read the database but prohibits
+** any other process from modifying the database.  The read lock is
+** released when all cursors are closed.  If this instruction attempts
+** to get a read lock but fails, the script terminates with an
+** SQLITE_BUSY error code.
+**
+** The P3 value is the name of the table or index being opened.
+** The P3 value is not actually used by this opcode and may be
+** omitted.  But the code generator usually inserts the index or
+** table name into P3 to make the code easier to read.
+**
+** See also OpenAux and OpenWrite.
+*/
+/* Opcode: OpenAux P1 P2 P3
+**
+** Open a read-only cursor in the auxiliary table set.  This opcode
+** works exactly like OP_Open except that it opens the cursor on the
+** auxiliary table set (the file used to store tables created using
+** CREATE TEMPORARY TABLE) instead of in the main database file.
+** See OP_Open for additional information.
+*/
+/* Opcode: OpenWrite P1 P2 P3
+**
+** Open a read/write cursor named P1 on the table or index whose root
+** page is P2.  If P2==0 then take the root page number from the stack.
+**
+** This instruction works just like Open except that it opens the cursor
+** in read/write mode.  For a given table, there can be one or more read-only
+** cursors or a single read/write cursor but not both.
+**
+** See also OpWrAux.
+*/
+/* Opcode: OpenWrAux P1 P2 P3
+**
+** Open a read/write cursor in the auxiliary table set.  This opcode works
+** just like OpenWrite except that the auxiliary table set (the file used
+** to store tables created using CREATE TEMPORARY TABLE) is used in place
+** of the main database file.
+*/
+case OP_OpenAux:
+case OP_OpenWrAux:
+case OP_OpenWrite:
+case OP_Open: {
+  int busy = 0;
+  int i = pOp->p1;
+  int tos = p->tos;
+  int p2 = pOp->p2;
+  int wrFlag;
+  Btree *pX;
+  switch( pOp->opcode ){
+    case OP_Open:        wrFlag = 0;  pX = pBt;          break;
+    case OP_OpenWrite:   wrFlag = 1;  pX = pBt;          break;
+    case OP_OpenAux:     wrFlag = 0;  pX = db->pBeTemp;  break;
+    case OP_OpenWrAux:   wrFlag = 1;  pX = db->pBeTemp;  break;
+  }
+  if( p2<=0 ){
+    if( tos<0 ) goto not_enough_stack;
+    Integerify(p, tos);
+    p2 = p->aStack[tos].i;
+    POPSTACK;
+    if( p2<2 ){
+      sqliteSetString(&p->zErrMsg, "root page number less than 2", 0);
+      rc = SQLITE_INTERNAL;
+      break;
+    }
+  }
+  VERIFY( if( i<0 ) goto bad_instruction; )
+  if( expandCursorArraySize(p, i) ) goto no_mem;
+  cleanupCursor(&p->aCsr[i]);
+  memset(&p->aCsr[i], 0, sizeof(Cursor));
+  p->aCsr[i].nullRow = 1;
+  if( pX==0 ) break;
+  do{
+    rc = sqliteBtreeCursor(pX, p2, wrFlag, &p->aCsr[i].pCursor);
+    switch( rc ){
+      case SQLITE_BUSY: {
+        if( db->xBusyCallback==0 ){
+          p->pc = pc;
+          p->rc = SQLITE_BUSY;
+          return SQLITE_BUSY;
+        }else if( (*db->xBusyCallback)(db->pBusyArg, pOp->p3, ++busy)==0 ){
+          sqliteSetString(&p->zErrMsg, sqlite_error_string(rc), 0);
+          busy = 0;
+        }
+        break;
+      }
+      case SQLITE_OK: {
+        busy = 0;
+        break;
+      }
+      default: {
+        goto abort_due_to_error;
+      }
+    }
+  }while( busy );
+  if( p2<=0 ){
+    POPSTACK;
+  }
+  break;
+}
+
+/* Opcode: OpenTemp P1 P2 *
+**
+** Open a new cursor that points to a table or index in a temporary
+** database file.  The temporary file is opened read/write even if 
+** the main database is read-only.  The temporary file is deleted
+** when the cursor is closed.
+**
+** The cursor points to a BTree table if P2==0 and to a BTree index
+** if P2==1.  A BTree table must have an integer key and can have arbitrary
+** data.  A BTree index has no data but can have an arbitrary key.
+**
+** This opcode is used for tables that exist for the duration of a single
+** SQL statement only.  Tables created using CREATE TEMPORARY TABLE
+** are opened using OP_OpenAux or OP_OpenWrAux.  "Temporary" in the
+** context of this opcode means for the duration of a single SQL statement
+** whereas "Temporary" in the context of CREATE TABLE means for the duration
+** of the connection to the database.  Same word; different meanings.
+*/
+case OP_OpenTemp: {
+  int i = pOp->p1;
+  Cursor *pCx;
+  VERIFY( if( i<0 ) goto bad_instruction; )
+  if( expandCursorArraySize(p, i) ) goto no_mem;
+  pCx = &p->aCsr[i];
+  cleanupCursor(pCx);
+  memset(pCx, 0, sizeof(*pCx));
+  pCx->nullRow = 1;
+  rc = sqliteBtreeOpen(0, 1, TEMP_PAGES, &pCx->pBt);
+  if( rc==SQLITE_OK ){
+    rc = sqliteBtreeBeginTrans(pCx->pBt);
+  }
+  if( rc==SQLITE_OK ){
+    if( pOp->p2 ){
+      int pgno;
+      rc = sqliteBtreeCreateIndex(pCx->pBt, &pgno);
+      if( rc==SQLITE_OK ){
+        rc = sqliteBtreeCursor(pCx->pBt, pgno, 1, &pCx->pCursor);
+      }
+    }else{
+      rc = sqliteBtreeCursor(pCx->pBt, 2, 1, &pCx->pCursor);
+    }
+  }
+  break;
+}
+
+/*
+** Opcode: RenameCursor P1 P2 *
+**
+** Rename cursor number P1 as cursor number P2.  If P2 was previously
+** opened is is closed before the renaming occurs.
+*/
+case OP_RenameCursor: {
+  int from = pOp->p1;
+  int to = pOp->p2;
+  VERIFY( if( from<0 || to<0 ) goto bad_instruction; )
+  if( to<p->nCursor && p->aCsr[to].pCursor ){
+    cleanupCursor(&p->aCsr[to]);
+  }
+  expandCursorArraySize(p, to);
+  if( from<p->nCursor ){
+    memcpy(&p->aCsr[to], &p->aCsr[from], sizeof(p->aCsr[0]));
+    memset(&p->aCsr[from], 0, sizeof(p->aCsr[0]));
+  }
+  break;
+}
+
+/* Opcode: Close P1 * *
+**
+** Close a cursor previously opened as P1.  If P1 is not
+** currently open, this instruction is a no-op.
+*/
+case OP_Close: {
+  int i = pOp->p1;
+  if( i>=0 && i<p->nCursor && p->aCsr[i].pCursor ){
+    cleanupCursor(&p->aCsr[i]);
+  }
+  break;
+}
+
+/* Opcode: MoveTo P1 P2 *
+**
+** Pop the top of the stack and use its value as a key.  Reposition
+** cursor P1 so that it points to an entry with a matching key.  If
+** the table contains no record with a matching key, then the cursor
+** is left pointing at the first record that is greater than the key.
+** If there are no records greater than the key and P2 is not zero,
+** then an immediate jump to P2 is made.
+**
+** See also: Found, NotFound, Distinct, MoveLt
+*/
+/* Opcode: MoveLt P1 P2 *
+**
+** Pop the top of the stack and use its value as a key.  Reposition
+** cursor P1 so that it points to the entry with the largest key that is
+** less than the key popped from the stack.
+** If there are no records less than than the key and P2
+** is not zero then an immediate jump to P2 is made.
+**
+** See also: MoveTo
+*/
+case OP_MoveLt:
+case OP_MoveTo: {
+  int i = pOp->p1;
+  int tos = p->tos;
+  Cursor *pC;
+
+  VERIFY( if( tos<0 ) goto not_enough_stack; )
+  if( i>=0 && i<p->nCursor && (pC = &p->aCsr[i])->pCursor!=0 ){
+    int res, oc;
+    if( aStack[tos].flags & STK_Int ){
+      int iKey = intToKey(aStack[tos].i);
+      sqliteBtreeMoveto(pC->pCursor, (char*)&iKey, sizeof(int), &res);
+      pC->lastRecno = aStack[tos].i;
+      pC->recnoIsValid = res==0;
+    }else{
+      Stringify(p, tos);
+      sqliteBtreeMoveto(pC->pCursor, zStack[tos], aStack[tos].n, &res);
+      pC->recnoIsValid = 0;
+    }
+    pC->nullRow = 0;
+    sqlite_search_count++;
+    oc = pOp->opcode;
+    if( oc==OP_MoveTo && res<0 ){
+      sqliteBtreeNext(pC->pCursor, &res);
+      pC->recnoIsValid = 0;
+      if( res && pOp->p2>0 ){
+        pc = pOp->p2 - 1;
+      }
+    }else if( oc==OP_MoveLt ){
+      if( res>=0 ){
+        sqliteBtreePrevious(pC->pCursor, &res);
+        pC->recnoIsValid = 0;
+      }else{
+        /* res might be negative because the table is empty.  Check to
+        ** see if this is the case.
+        */
+        int keysize;
+        res = sqliteBtreeKeySize(pC->pCursor,&keysize)!=0 || keysize==0;
+      }
+      if( res && pOp->p2>0 ){
+        pc = pOp->p2 - 1;
+      }
+    }
+  }
+  POPSTACK;
+  break;
+}
+
+/* Opcode: Distinct P1 P2 *
+**
+** Use the top of the stack as a string key.  If a record with that key does
+** not exist in the table of cursor P1, then jump to P2.  If the record
+** does already exist, then fall thru.  The cursor is left pointing
+** at the record if it exists. The key is not popped from the stack.
+**
+** This operation is similar to NotFound except that this operation
+** does not pop the key from the stack.
+**
+** See also: Found, NotFound, MoveTo, IsUnique, NotExists
+*/
+/* Opcode: Found P1 P2 *
+**
+** Use the top of the stack as a string key.  If a record with that key
+** does exist in table of P1, then jump to P2.  If the record
+** does not exist, then fall thru.  The cursor is left pointing
+** to the record if it exists.  The key is popped from the stack.
+**
+** See also: Distinct, NotFound, MoveTo, IsUnique, NotExists
+*/
+/* Opcode: NotFound P1 P2 *
+**
+** Use the top of the stack as a string key.  If a record with that key
+** does not exist in table of P1, then jump to P2.  If the record
+** does exist, then fall thru.  The cursor is left pointing to the
+** record if it exists.  The key is popped from the stack.
+**
+** The difference between this operation and Distinct is that
+** Distinct does not pop the key from the stack.
+**
+** See also: Distinct, Found, MoveTo, NotExists, IsUnique
+*/
+case OP_Distinct:
+case OP_NotFound:
+case OP_Found: {
+  int i = pOp->p1;
+  int tos = p->tos;
+  int alreadyExists = 0;
+  Cursor *pC;
+  VERIFY( if( tos<0 ) goto not_enough_stack; )
+  if( VERIFY( i>=0 && i<p->nCursor && ) (pC = &p->aCsr[i])->pCursor!=0 ){
+    int res, rx;
+    Stringify(p, tos);
+    rx = sqliteBtreeMoveto(pC->pCursor, zStack[tos], aStack[tos].n, &res);
+    alreadyExists = rx==SQLITE_OK && res==0;
+  }
+  if( pOp->opcode==OP_Found ){
+    if( alreadyExists ) pc = pOp->p2 - 1;
+  }else{
+    if( !alreadyExists ) pc = pOp->p2 - 1;
+  }
+  if( pOp->opcode!=OP_Distinct ){
+    POPSTACK;
+  }
+  break;
+}
+
+/* Opcode: IsUnique P1 P2 *
+**
+** The top of the stack is an integer record number.  Call this
+** record number R.  The next on the stack is an index key created
+** using MakeIdxKey.  Call it K.  This instruction pops R from the
+** stack but it leaves K unchanged.
+**
+** P1 is an index.  So all but the last four bytes of K are an
+** index string.  The last four bytes of K are a record number.
+**
+** This instruction asks if there is an entry in P1 where the
+** index string matches K but the record number is different
+** from R.  If there is no such entry, then there is an immediate
+** jump to P2.  If any entry does exist where the index string
+** matches K but the record number is not R, then the record
+** number for that entry is pushed onto the stack and control
+** falls through to the next instruction.
+**
+** See also: Distinct, NotFound, NotExists, Found
+*/
+case OP_IsUnique: {
+  int i = pOp->p1;
+  int tos = p->tos;
+  int nos = tos-1;
+  BtCursor *pCrsr;
+  int R;
+
+  /* Pop the value R off the top of the stack
+  */
+  VERIFY( if( nos<0 ) goto not_enough_stack; )
+  Integerify(p, tos);
+  R = aStack[tos].i;   
+  POPSTACK;
+  if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
+    int res, rc;
+    int v;         /* The record number on the P1 entry that matches K */
+    char *zKey;    /* The value of K */
+    int nKey;      /* Number of bytes in K */
+
+    /* Make sure K is a string and make zKey point to K
+    */
+    Stringify(p, nos);
+    zKey = zStack[nos];
+    nKey = aStack[nos].n;
+    assert( nKey >= 4 );
+
+    /* Search for an entry in P1 where all but the last four bytes match K.
+    ** If there is no such entry, jump immediately to P2.
+    */
+    rc = sqliteBtreeMoveto(pCrsr, zKey, nKey-4, &res);
+    if( rc!=SQLITE_OK ) goto abort_due_to_error;
+    if( res<0 ){
+      rc = sqliteBtreeNext(pCrsr, &res);
+      if( res ){
+        pc = pOp->p2 - 1;
+        break;
+      }
+    }
+    rc = sqliteBtreeKeyCompare(pCrsr, zKey, nKey-4, 4, &res);
+    if( rc!=SQLITE_OK ) goto abort_due_to_error;
+    if( res>0 ){
+      pc = pOp->p2 - 1;
+      break;
+    }
+
+    /* At this point, pCrsr is pointing to an entry in P1 where all but
+    ** the last for bytes of the key match K.  Check to see if the last
+    ** four bytes of the key are different from R.  If the last four
+    ** bytes equal R then jump immediately to P2.
+    */
+    sqliteBtreeKey(pCrsr, nKey - 4, 4, (char*)&v);
+    v = keyToInt(v);
+    if( v==R ){
+      pc = pOp->p2 - 1;
+      break;
+    }
+
+    /* The last four bytes of the key are different from R.  Convert the
+    ** last four bytes of the key into an integer and push it onto the
+    ** stack.  (These bytes are the record number of an entry that
+    ** violates a UNIQUE constraint.)
+    */
+    p->tos++;
+    aStack[tos].i = v;
+    aStack[tos].flags = STK_Int;
+  }
+  break;
+}
+
+/* Opcode: NotExists P1 P2 *
+**
+** Use the top of the stack as a integer key.  If a record with that key
+** does not exist in table of P1, then jump to P2.  If the record
+** does exist, then fall thru.  The cursor is left pointing to the
+** record if it exists.  The integer key is popped from the stack.
+**
+** The difference between this operation and NotFound is that this
+** operation assumes the key is an integer and NotFound assumes it
+** is a string.
+**
+** See also: Distinct, Found, MoveTo, NotFound, IsUnique
+*/
+case OP_NotExists: {
+  int i = pOp->p1;
+  int tos = p->tos;
+  BtCursor *pCrsr;
+  VERIFY( if( tos<0 ) goto not_enough_stack; )
+  if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
+    int res, rx, iKey;
+    assert( aStack[tos].flags & STK_Int );
+    iKey = intToKey(aStack[tos].i);
+    rx = sqliteBtreeMoveto(pCrsr, (char*)&iKey, sizeof(int), &res);
+    p->aCsr[i].lastRecno = aStack[tos].i;
+    p->aCsr[i].recnoIsValid = res==0;
+    p->aCsr[i].nullRow = 0;
+    if( rx!=SQLITE_OK || res!=0 ){
+      pc = pOp->p2 - 1;
+      p->aCsr[i].recnoIsValid = 0;
+    }
+  }
+  POPSTACK;
+  break;
+}
+
+/* Opcode: NewRecno P1 * *
+**
+** Get a new integer record number used as the key to a table.
+** The record number is not previously used as a key in the database
+** table that cursor P1 points to.  The new record number is pushed 
+** onto the stack.
+*/
+case OP_NewRecno: {
+  int i = pOp->p1;
+  int v = 0;
+  Cursor *pC;
+  if( VERIFY( i<0 || i>=p->nCursor || ) (pC = &p->aCsr[i])->pCursor==0 ){
+    v = 0;
+  }else{
+    /* The next rowid or record number (different terms for the same
+    ** thing) is obtained in a two-step algorithm.
+    **
+    ** First we attempt to find the largest existing rowid and add one
+    ** to that.  But if the largest existing rowid is already the maximum
+    ** positive integer, we have to fall through to the second
+    ** probabilistic algorithm
+    **
+    ** The second algorithm is to select a rowid at random and see if
+    ** it already exists in the table.  If it does not exist, we have
+    ** succeeded.  If the random rowid does exist, we select a new one
+    ** and try again, up to 1000 times.
+    **
+    ** For a table with less than 2 billion entries, the probability
+    ** of not finding a unused rowid is about 1.0e-300.  This is a 
+    ** non-zero probability, but it is still vanishingly small and should
+    ** never cause a problem.  You are much, much more likely to have a
+    ** hardware failure than for this algorithm to fail.
+    **
+    ** The analysis in the previous paragraph assumes that you have a good
+    ** source of random numbers.  Is a library function like lrand48()
+    ** good enough?  Maybe. Maybe not. It's hard to know whether there
+    ** might be subtle bugs is some implementations of lrand48() that
+    ** could cause problems. To avoid uncertainty, SQLite uses its own 
+    ** random number generator based on the RC4 algorithm.
+    **
+    ** To promote locality of reference for repetitive inserts, the
+    ** first few attempts at chosing a random rowid pick values just a little
+    ** larger than the previous rowid.  This has been shown experimentally
+    ** to double the speed of the COPY operation.
+    */
+    int res, rx, cnt, x;
+    cnt = 0;
+    if( !pC->useRandomRowid ){
+      if( pC->nextRowidValid ){
+        v = pC->nextRowid;
+      }else{
+        rx = sqliteBtreeLast(pC->pCursor, &res);
+        if( res ){
+          v = 1;
+        }else{
+          sqliteBtreeKey(pC->pCursor, 0, sizeof(v), (void*)&v);
+          v = keyToInt(v);
+          if( v==0x7fffffff ){
+            pC->useRandomRowid = 1;
+          }else{
+            v++;
+          }
+        }
+      }
+      if( v<0x7fffffff ){
+        pC->nextRowidValid = 1;
+        pC->nextRowid = v+1;
+      }else{
+        pC->nextRowidValid = 0;
+      }
+    }
+    if( pC->useRandomRowid ){
+      v = db->priorNewRowid;
+      cnt = 0;
+      do{
+        if( v==0 || cnt>2 ){
+          v = sqliteRandomInteger();
+          if( cnt<5 ) v &= 0xffffff;
+        }else{
+          v += sqliteRandomByte() + 1;
+        }
+        if( v==0 ) continue;
+        x = intToKey(v);
+        rx = sqliteBtreeMoveto(pC->pCursor, &x, sizeof(int), &res);
+        cnt++;
+      }while( cnt<1000 && rx==SQLITE_OK && res==0 );
+      db->priorNewRowid = v;
+      if( rx==SQLITE_OK && res==0 ){
+        rc = SQLITE_FULL;
+        goto abort_due_to_error;
+      }
+    }
+    pC->recnoIsValid = 0;
+  }
+  p->tos++;
+  aStack[p->tos].i = v;
+  aStack[p->tos].flags = STK_Int;
+  break;
+}
+
+/* Opcode: PutIntKey P1 P2 *
+**
+** Write an entry into the database file P1.  A new entry is
+** created if it doesn't already exist or the data for an existing
+** entry is overwritten.  The data is the value on the top of the
+** stack.  The key is the next value down on the stack.  The key must
+** be an integer.  The stack is popped twice by this instruction.
+**
+** If P2==1 then the row change count is incremented.  If P2==0 the
+** row change count is unmodified.
+*/
+/* Opcode: PutStrKey P1 * *
+**
+** Write an entry into the database file P1.  A new entry is
+** created if it doesn't already exist or the data for an existing
+** entry is overwritten.  The data is the value on the top of the
+** stack.  The key is the next value down on the stack.  The key must
+** be a string.  The stack is popped twice by this instruction.
+*/
+case OP_PutIntKey:
+case OP_PutStrKey: {
+  int tos = p->tos;
+  int nos = p->tos-1;
+  int i = pOp->p1;
+  Cursor *pC;
+  VERIFY( if( nos<0 ) goto not_enough_stack; )
+  if( VERIFY( i>=0 && i<p->nCursor && ) (pC = &p->aCsr[i])->pCursor!=0 ){
+    char *zKey;
+    int nKey, iKey;
+    if( pOp->opcode==OP_PutStrKey ){
+      Stringify(p, nos);
+      nKey = aStack[nos].n;
+      zKey = zStack[nos];
+    }else{
+      assert( aStack[nos].flags & STK_Int );
+      nKey = sizeof(int);
+      iKey = intToKey(aStack[nos].i);
+      zKey = (char*)&iKey;
+      db->lastRowid = aStack[nos].i;
+      if( pOp->p2 ) db->nChange++;
+      if( pC->nextRowidValid && aStack[nos].i>=pC->nextRowid ){
+        pC->nextRowidValid = 0;
+      }
+    }
+    rc = sqliteBtreeInsert(pC->pCursor, zKey, nKey,
+                        zStack[tos], aStack[tos].n);
+    pC->recnoIsValid = 0;
+  }
+  POPSTACK;
+  POPSTACK;
+  break;
+}
+
+/* Opcode: Delete P1 P2 *
+**
+** Delete the record at which the P1 cursor is currently pointing.
+**
+** The cursor will be left pointing at either the next or the previous
+** record in the table. If it is left pointing at the next record, then
+** the next Next instruction will be a no-op.  Hence it is OK to delete
+** a record from within an Next loop.
+**
+** The row change counter is incremented if P2==1 and is unmodified
+** if P2==0.
+*/
+case OP_Delete: {
+  int i = pOp->p1;
+  Cursor *pC;
+  if( VERIFY( i>=0 && i<p->nCursor && ) (pC = &p->aCsr[i])->pCursor!=0 ){
+    rc = sqliteBtreeDelete(pC->pCursor);
+    pC->nextRowidValid = 0;
+  }
+  if( pOp->p2 ) db->nChange++;
+  break;
+}
+
+/* Opcode: KeyAsData P1 P2 *
+**
+** Turn the key-as-data mode for cursor P1 either on (if P2==1) or
+** off (if P2==0).  In key-as-data mode, the Field opcode pulls
+** data off of the key rather than the data.  This is useful for
+** processing compound selects.
+*/
+case OP_KeyAsData: {
+  int i = pOp->p1;
+  if( VERIFY( i>=0 && i<p->nCursor && ) p->aCsr[i].pCursor!=0 ){
+    p->aCsr[i].keyAsData = pOp->p2;
+  }
+  break;
+}
+
+/* Opcode: Column P1 P2 *
+**
+** Interpret the data that cursor P1 points to as
+** a structure built using the MakeRecord instruction.
+** (See the MakeRecord opcode for additional information about
+** the format of the data.)
+** Push onto the stack the value of the P2-th column contained
+** in the data.
+**
+** If the KeyAsData opcode has previously executed on this cursor,
+** then the field might be extracted from the key rather than the
+** data.
+**
+** If P1 is negative, then the record is stored on the stack rather
+** than in a table.  For P1==-1, the top of the stack is used.
+** For P1==-2, the next on the stack is used.  And so forth.  The
+** value pushed is always just a pointer into the record which is
+** stored further down on the stack.  The column value is not copied.
+*/
+case OP_Column: {
+  int amt, offset, end, payloadSize;
+  int i = pOp->p1;
+  int p2 = pOp->p2;
+  int tos = p->tos+1;
+  Cursor *pC;
+  char *zRec;
+  BtCursor *pCrsr;
+  int idxWidth;
+  unsigned char aHdr[10];
+
+  if( i<0 ){
+    VERIFY( if( tos+i<0 ) goto bad_instruction; )
+    VERIFY( if( (aStack[tos+i].flags & STK_Str)==0 ) goto bad_instruction; )
+    zRec = zStack[tos+i];
+    payloadSize = aStack[tos+i].n;
+  }else if( VERIFY( i>=0 && i<p->nCursor && ) (pC = &p->aCsr[i])->pCursor!=0 ){
+    zRec = 0;
+    pCrsr = pC->pCursor;
+    if( pC->nullRow ){
+      payloadSize = 0;
+    }else if( pC->keyAsData ){
+      sqliteBtreeKeySize(pCrsr, &payloadSize);
+    }else{
+      sqliteBtreeDataSize(pCrsr, &payloadSize);
+    }
+  }else{
+    payloadSize = 0;
+  }
+
+  /* Figure out how many bytes in the column data and where the column
+  ** data begins.
+  */
+  if( payloadSize==0 ){
+    aStack[tos].flags = STK_Null;
+    p->tos = tos;
+    break;
+  }else if( payloadSize<256 ){
+    idxWidth = 1;
+  }else if( payloadSize<65536 ){
+    idxWidth = 2;
+  }else{
+    idxWidth = 3;
+  }
+
+  /* Figure out where the requested column is stored and how big it is.
+  */
+  if( payloadSize < idxWidth*(p2+1) ){
+    rc = SQLITE_CORRUPT;
+    goto abort_due_to_error;
+  }
+  if( zRec ){
+    memcpy(aHdr, &zRec[idxWidth*p2], idxWidth*2);
+  }else if( pC->keyAsData ){
+    sqliteBtreeKey(pCrsr, idxWidth*p2, idxWidth*2, (char*)aHdr);
+  }else{
+    sqliteBtreeData(pCrsr, idxWidth*p2, idxWidth*2, (char*)aHdr);
+  }
+  offset = aHdr[0];
+  end = aHdr[idxWidth];
+  if( idxWidth>1 ){
+    offset |= aHdr[1]<<8;
+    end |= aHdr[idxWidth+1]<<8;
+    if( idxWidth>2 ){
+      offset |= aHdr[2]<<16;
+      end |= aHdr[idxWidth+2]<<16;
+    }
+  }
+  amt = end - offset;
+  if( amt<0 || offset<0 || end>payloadSize ){
+    rc = SQLITE_CORRUPT;
+    goto abort_due_to_error;
+  }
+
+  /* amt and offset now hold the offset to the start of data and the
+  ** amount of data.  Go get the data and put it on the stack.
+  */
+  if( amt==0 ){
+    aStack[tos].flags = STK_Null;
+  }else if( zRec ){
+    aStack[tos].flags = STK_Str | STK_Ephem;
+    aStack[tos].n = amt;
+    zStack[tos] = &zRec[offset];
+  }else{
+    if( amt<=NBFS ){
+      aStack[tos].flags = STK_Str;
+      zStack[tos] = aStack[tos].z;
+      aStack[tos].n = amt;
+    }else{
+      char *z = sqliteMallocRaw( amt );
+      if( z==0 ) goto no_mem;
+      aStack[tos].flags = STK_Str | STK_Dyn;
+      zStack[tos] = z;
+      aStack[tos].n = amt;
+    }
+    if( pC->keyAsData ){
+      sqliteBtreeKey(pCrsr, offset, amt, zStack[tos]);
+    }else{
+      sqliteBtreeData(pCrsr, offset, amt, zStack[tos]);
+    }
+  }
+  p->tos = tos;
+  break;
+}
+
+/* Opcode: Recno P1 * *
+**
+** Push onto the stack an integer which is the first 4 bytes of the
+** the key to the current entry in a sequential scan of the database
+** file P1.  The sequential scan should have been started using the 
+** Next opcode.
+*/
+case OP_Recno: {
+  int i = pOp->p1;
+  int tos = ++p->tos;
+  BtCursor *pCrsr;
+
+  if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
+    int v;
+    if( p->aCsr[i].recnoIsValid ){
+      v = p->aCsr[i].lastRecno;
+    }else if( p->aCsr[i].nullRow ){
+      aStack[tos].flags = STK_Null;
+      break;
+    }else{
+      sqliteBtreeKey(pCrsr, 0, sizeof(u32), (char*)&v);
+      v = keyToInt(v);
+    }
+    aStack[tos].i = v;
+    aStack[tos].flags = STK_Int;
+  }
+  break;
+}
+
+/* Opcode: FullKey P1 * *
+**
+** Extract the complete key from the record that cursor P1 is currently
+** pointing to and push the key onto the stack as a string.
+**
+** Compare this opcode to Recno.  The Recno opcode extracts the first
+** 4 bytes of the key and pushes those bytes onto the stack as an
+** integer.  This instruction pushes the entire key as a string.
+*/
+case OP_FullKey: {
+  int i = pOp->p1;
+  int tos = ++p->tos;
+  BtCursor *pCrsr;
+
+  VERIFY( if( !p->aCsr[i].keyAsData ) goto bad_instruction; )
+  if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
+    int amt;
+    char *z;
+
+    sqliteBtreeKeySize(pCrsr, &amt);
+    if( amt<=0 ){
+      rc = SQLITE_CORRUPT;
+      goto abort_due_to_error;
+    }
+    if( amt>NBFS ){
+      z = sqliteMallocRaw( amt );
+      if( z==0 ) goto no_mem;
+      aStack[tos].flags = STK_Str | STK_Dyn;
+    }else{
+      z = aStack[tos].z;
+      aStack[tos].flags = STK_Str;
+    }
+    sqliteBtreeKey(pCrsr, 0, amt, z);
+    zStack[tos] = z;
+    aStack[tos].n = amt;
+  }
+  break;
+}
+
+/* Opcode: NullRow P1 * *
+**
+** Move the cursor P1 to a null row.  Any OP_Column operations
+** that occur while the cursor is on the null row will always push 
+** a NULL onto the stack.
+*/
+case OP_NullRow: {
+  int i = pOp->p1;
+  BtCursor *pCrsr;
+
+  if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
+    p->aCsr[i].nullRow = 1;
+  }
+  break;
+}
+
+/* Opcode: Last P1 P2 *
+**
+** The next use of the Recno or Column or Next instruction for P1 
+** will refer to the last entry in the database table or index.
+** If the table or index is empty and P2>0, then jump immediately to P2.
+** If P2 is 0 or if the table or index is not empty, fall through
+** to the following instruction.
+*/
+case OP_Last: {
+  int i = pOp->p1;
+  BtCursor *pCrsr;
+
+  if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
+    int res;
+    sqliteBtreeLast(pCrsr, &res);
+    p->aCsr[i].nullRow = res;
+    if( res && pOp->p2>0 ){
+      pc = pOp->p2 - 1;
+    }
+  }
+  break;
+}
+
+/* Opcode: Rewind P1 P2 *
+**
+** The next use of the Recno or Column or Next instruction for P1 
+** will refer to the first entry in the database table or index.
+** If the table or index is empty and P2>0, then jump immediately to P2.
+** If P2 is 0 or if the table or index is not empty, fall through
+** to the following instruction.
+*/
+case OP_Rewind: {
+  int i = pOp->p1;
+  BtCursor *pCrsr;
+
+  if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
+    int res;
+    sqliteBtreeFirst(pCrsr, &res);
+    p->aCsr[i].atFirst = res==0;
+    p->aCsr[i].nullRow = res;
+    if( res && pOp->p2>0 ){
+      pc = pOp->p2 - 1;
+    }
+  }
+  break;
+}
+
+/* Opcode: Next P1 P2 *
+**
+** Advance cursor P1 so that it points to the next key/data pair in its
+** table or index.  If there are no more key/value pairs then fall through
+** to the following instruction.  But if the cursor advance was successful,
+** jump immediately to P2.
+**
+** See also: Prev
+*/
+/* Opcode: Prev P1 P2 *
+**
+** Back up cursor P1 so that it points to the previous key/data pair in its
+** table or index.  If there is no previous key/value pairs then fall through
+** to the following instruction.  But if the cursor backup was successful,
+** jump immediately to P2.
+*/
+case OP_Prev:
+case OP_Next: {
+  Cursor *pC;
+  BtCursor *pCrsr;
+
+  CHECK_FOR_INTERRUPT;
+  if( VERIFY( pOp->p1>=0 && pOp->p1<p->nCursor && ) 
+      (pCrsr = (pC = &p->aCsr[pOp->p1])->pCursor)!=0 ){
+    int res;
+    if( pC->nullRow ){
+      res = 1;
+    }else{
+      rc = pOp->opcode==OP_Next ? sqliteBtreeNext(pCrsr, &res) :
+                                  sqliteBtreePrevious(pCrsr, &res);
+      pC->nullRow = res;
+    }
+    if( res==0 ){
+      pc = pOp->p2 - 1;
+      sqlite_search_count++;
+    }
+    pC->recnoIsValid = 0;
+  }
+  break;
+}
+
+/* Opcode: IdxPut P1 P2 P3
+**
+** The top of the stack hold an SQL index key made using the
+** MakeIdxKey instruction.  This opcode writes that key into the
+** index P1.  Data for the entry is nil.
+**
+** If P2==1, then the key must be unique.  If the key is not unique,
+** the program aborts with a SQLITE_CONSTRAINT error and the database
+** is rolled back.  If P3 is not null, then it because part of the
+** error message returned with the SQLITE_CONSTRAINT.
+*/
+case OP_IdxPut: {
+  int i = pOp->p1;
+  int tos = p->tos;
+  BtCursor *pCrsr;
+  VERIFY( if( tos<0 ) goto not_enough_stack; )
+  if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
+    int nKey = aStack[tos].n;
+    const char *zKey = zStack[tos];
+    if( pOp->p2 ){
+      int res, n;
+      assert( aStack[tos].n >= 4 );
+      rc = sqliteBtreeMoveto(pCrsr, zKey, nKey-4, &res);
+      if( rc!=SQLITE_OK ) goto abort_due_to_error;
+      while( res!=0 ){
+        int c;
+        sqliteBtreeKeySize(pCrsr, &n);
+        if( n==nKey
+           && sqliteBtreeKeyCompare(pCrsr, zKey, nKey-4, 4, &c)==SQLITE_OK
+           && c==0
+        ){
+          rc = SQLITE_CONSTRAINT;
+          if( pOp->p3 && pOp->p3[0] ){
+            sqliteSetString(&p->zErrMsg, pOp->p3, 0);
+          }
+          goto abort_due_to_error;
+        }
+        if( res<0 ){
+          sqliteBtreeNext(pCrsr, &res);
+          res = +1;
+        }else{
+          break;
+        }
+      }
+    }
+    rc = sqliteBtreeInsert(pCrsr, zKey, nKey, "", 0);
+  }
+  POPSTACK;
+  break;
+}
+
+/* Opcode: IdxDelete P1 * *
+**
+** The top of the stack is an index key built using the MakeIdxKey opcode.
+** This opcode removes that entry from the index.
+*/
+case OP_IdxDelete: {
+  int i = pOp->p1;
+  int tos = p->tos;
+  BtCursor *pCrsr;
+  VERIFY( if( tos<0 ) goto not_enough_stack; )
+  if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
+    int rx, res;
+    rx = sqliteBtreeMoveto(pCrsr, zStack[tos], aStack[tos].n, &res);
+    if( rx==SQLITE_OK && res==0 ){
+      rc = sqliteBtreeDelete(pCrsr);
+    }
+  }
+  POPSTACK;
+  break;
+}
+
+/* Opcode: IdxRecno P1 * *
+**
+** Push onto the stack an integer which is the last 4 bytes of the
+** the key to the current entry in index P1.  These 4 bytes should
+** be the record number of the table entry to which this index entry
+** points.
+**
+** See also: Recno, MakeIdxKey.
+*/
+case OP_IdxRecno: {
+  int i = pOp->p1;
+  int tos = ++p->tos;
+  BtCursor *pCrsr;
+
+  if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
+    int v;
+    int sz;
+    sqliteBtreeKeySize(pCrsr, &sz);
+    sqliteBtreeKey(pCrsr, sz - sizeof(u32), sizeof(u32), (char*)&v);
+    v = keyToInt(v);
+    aStack[tos].i = v;
+    aStack[tos].flags = STK_Int;
+  }
+  break;
+}
+
+/* Opcode: IdxGT P1 P2 *
+**
+** Compare the top of the stack against the key on the index entry that
+** cursor P1 is currently pointing to.  Ignore the last 4 bytes of the
+** index entry.  If the index entry is greater than the top of the stack
+** then jump to P2.  Otherwise fall through to the next instruction.
+** In either case, the stack is popped once.
+*/
+/* Opcode: IdxGE P1 P2 *
+**
+** Compare the top of the stack against the key on the index entry that
+** cursor P1 is currently pointing to.  Ignore the last 4 bytes of the
+** index entry.  If the index entry is greater than or equal to 
+** the top of the stack
+** then jump to P2.  Otherwise fall through to the next instruction.
+** In either case, the stack is popped once.
+*/
+/* Opcode: IdxLT P1 P2 *
+**
+** Compare the top of the stack against the key on the index entry that
+** cursor P1 is currently pointing to.  Ignore the last 4 bytes of the
+** index entry.  If the index entry is less than the top of the stack
+** then jump to P2.  Otherwise fall through to the next instruction.
+** In either case, the stack is popped once.
+*/
+case OP_IdxLT:
+case OP_IdxGT:
+case OP_IdxGE: {
+  int i= pOp->p1;
+  int tos = p->tos;
+  BtCursor *pCrsr;
+
+  if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
+    int res, rc;
+    Stringify(p, tos);
+    rc = sqliteBtreeKeyCompare(pCrsr, zStack[tos], aStack[tos].n, 4, &res);
+    if( rc!=SQLITE_OK ){
+      break;
+    }
+    if( pOp->opcode==OP_IdxLT ){
+      res = -res;
+    }else if( pOp->opcode==OP_IdxGE ){
+      res++;
+    }
+    if( res>0 ){
+      pc = pOp->p2 - 1 ;
+    }
+  }
+  POPSTACK;
+  break;
+}
+
+/* Opcode: Destroy P1 P2 *
+**
+** Delete an entire database table or index whose root page in the database
+** file is given by P1.
+**
+** The table being destroyed is in the main database file if P2==0.  If
+** P2==1 then the table to be clear is in the auxiliary database file
+** that is used to store tables create using CREATE TEMPORARY TABLE.
+**
+** See also: Clear
+*/
+case OP_Destroy: {
+  sqliteBtreeDropTable(pOp->p2 ? db->pBeTemp : pBt, pOp->p1);
+  break;
+}
+
+/* Opcode: Clear P1 P2 *
+**
+** Delete all contents of the database table or index whose root page
+** in the database file is given by P1.  But, unlike Destroy, do not
+** remove the table or index from the database file.
+**
+** The table being clear is in the main database file if P2==0.  If
+** P2==1 then the table to be clear is in the auxiliary database file
+** that is used to store tables create using CREATE TEMPORARY TABLE.
+**
+** See also: Destroy
+*/
+case OP_Clear: {
+  sqliteBtreeClearTable(pOp->p2 ? db->pBeTemp : pBt, pOp->p1);
+  break;
+}
+
+/* Opcode: CreateTable * P2 P3
+**
+** Allocate a new table in the main database file if P2==0 or in the
+** auxiliary database file if P2==1.  Push the page number
+** for the root page of the new table onto the stack.
+**
+** The root page number is also written to a memory location that P3
+** points to.  This is the mechanism is used to write the root page
+** number into the parser's internal data structures that describe the
+** new table.
+**
+** The difference between a table and an index is this:  A table must
+** have a 4-byte integer key and can have arbitrary data.  An index
+** has an arbitrary key but no data.
+**
+** See also: CreateIndex
+*/
+/* Opcode: CreateIndex * P2 P3
+**
+** Allocate a new index in the main database file if P2==0 or in the
+** auxiliary database file if P2==1.  Push the page number of the
+** root page of the new index onto the stack.
+**
+** See documentation on OP_CreateTable for additional information.
+*/
+case OP_CreateIndex:
+case OP_CreateTable: {
+  int i = ++p->tos;
+  int pgno;
+  assert( pOp->p3!=0 && pOp->p3type==P3_POINTER );
+  if( pOp->opcode==OP_CreateTable ){
+    rc = sqliteBtreeCreateTable(pOp->p2 ? db->pBeTemp : pBt, &pgno);
+  }else{
+    rc = sqliteBtreeCreateIndex(pOp->p2 ? db->pBeTemp : pBt, &pgno);
+  }
+  if( rc==SQLITE_OK ){
+    aStack[i].i = pgno;
+    aStack[i].flags = STK_Int;
+    *(u32*)pOp->p3 = pgno;
+    pOp->p3 = 0;
+  }
+  break;
+}
+
+/* Opcode: IntegrityCk P1 P2 *
+**
+** Do an analysis of the currently open database.  Push onto the
+** stack the text of an error message describing any problems.
+** If there are no errors, push a "ok" onto the stack.
+**
+** P1 is the index of a set that contains the root page numbers
+** for all tables and indices in the main database file.
+**
+** If P2 is not zero, the check is done on the auxiliary database
+** file, not the main database file.
+**
+** This opcode is used for testing purposes only.
+*/
+case OP_IntegrityCk: {
+  int nRoot;
+  int *aRoot;
+  int tos = ++p->tos;
+  int iSet = pOp->p1;
+  Set *pSet;
+  int j;
+  HashElem *i;
+  char *z;
+
+  VERIFY( if( iSet<0 || iSet>=p->nSet ) goto bad_instruction; )
+  pSet = &p->aSet[iSet];
+  nRoot = sqliteHashCount(&pSet->hash);
+  aRoot = sqliteMallocRaw( sizeof(int)*(nRoot+1) );
+  if( aRoot==0 ) goto no_mem;
+  for(j=0, i=sqliteHashFirst(&pSet->hash); i; i=sqliteHashNext(i), j++){
+    toInt((char*)sqliteHashKey(i), &aRoot[j]);
+  }
+  aRoot[j] = 0;
+  z = sqliteBtreeIntegrityCheck(pOp->p2 ? db->pBeTemp : pBt, aRoot, nRoot);
+  if( z==0 || z[0]==0 ){
+    if( z ) sqliteFree(z);
+    zStack[tos] = "ok";
+    aStack[tos].n = 3;
+    aStack[tos].flags = STK_Str | STK_Static;
+  }else{
+    zStack[tos] = z;
+    aStack[tos].n = strlen(z) + 1;
+    aStack[tos].flags = STK_Str | STK_Dyn;
+  }
+  sqliteFree(aRoot);
+  break;
+}
+
+/* Opcode: ListWrite * * *
+**
+** Write the integer on the top of the stack
+** into the temporary storage list.
+*/
+case OP_ListWrite: {
+  Keylist *pKeylist;
+  VERIFY( if( p->tos<0 ) goto not_enough_stack; )
+  pKeylist = p->pList;
+  if( pKeylist==0 || pKeylist->nUsed>=pKeylist->nKey ){
+    pKeylist = sqliteMallocRaw( sizeof(Keylist)+999*sizeof(pKeylist->aKey[0]) );
+    if( pKeylist==0 ) goto no_mem;
+    pKeylist->nKey = 1000;
+    pKeylist->nRead = 0;
+    pKeylist->nUsed = 0;
+    pKeylist->pNext = p->pList;
+    p->pList = pKeylist;
+  }
+  Integerify(p, p->tos);
+  pKeylist->aKey[pKeylist->nUsed++] = aStack[p->tos].i;
+  POPSTACK;
+  break;
+}
+
+/* Opcode: ListRewind * * *
+**
+** Rewind the temporary buffer back to the beginning.
+*/
+case OP_ListRewind: {
+  /* This is now a no-op */
+  break;
+}
+
+/* Opcode: ListRead * P2 *
+**
+** Attempt to read an integer from the temporary storage buffer
+** and push it onto the stack.  If the storage buffer is empty, 
+** push nothing but instead jump to P2.
+*/
+case OP_ListRead: {
+  Keylist *pKeylist;
+  CHECK_FOR_INTERRUPT;
+  pKeylist = p->pList;
+  if( pKeylist!=0 ){
+    VERIFY(
+      if( pKeylist->nRead<0 
+        || pKeylist->nRead>=pKeylist->nUsed
+        || pKeylist->nRead>=pKeylist->nKey ) goto bad_instruction;
+    )
+    p->tos++;
+    aStack[p->tos].i = pKeylist->aKey[pKeylist->nRead++];
+    aStack[p->tos].flags = STK_Int;
+    zStack[p->tos] = 0;
+    if( pKeylist->nRead>=pKeylist->nUsed ){
+      p->pList = pKeylist->pNext;
+      sqliteFree(pKeylist);
+    }
+  }else{
+    pc = pOp->p2 - 1;
+  }
+  break;
+}
+
+/* Opcode: ListReset * * *
+**
+** Reset the temporary storage buffer so that it holds nothing.
+*/
+case OP_ListReset: {
+  if( p->pList ){
+    KeylistFree(p->pList);
+    p->pList = 0;
+  }
+  break;
+}
+
+/* Opcode: ListPush * * * 
+**
+** Save the current Vdbe list such that it can be restored by a ListPop
+** opcode. The list is empty after this is executed.
+*/
+case OP_ListPush: {
+  p->keylistStackDepth++;
+  assert(p->keylistStackDepth > 0);
+  p->keylistStack = sqliteRealloc(p->keylistStack, 
+          sizeof(Keylist *) * p->keylistStackDepth);
+  if( p->keylistStack==0 ) goto no_mem;
+  p->keylistStack[p->keylistStackDepth - 1] = p->pList;
+  p->pList = 0;
+  break;
+}
+
+/* Opcode: ListPop * * * 
+**
+** Restore the Vdbe list to the state it was in when ListPush was last
+** executed.
+*/
+case OP_ListPop: {
+  assert(p->keylistStackDepth > 0);
+  p->keylistStackDepth--;
+  KeylistFree(p->pList);
+  p->pList = p->keylistStack[p->keylistStackDepth];
+  p->keylistStack[p->keylistStackDepth] = 0;
+  if( p->keylistStackDepth == 0 ){
+    sqliteFree(p->keylistStack);
+    p->keylistStack = 0;
+  }
+  break;
+}
+
+/* Opcode: SortPut * * *
+**
+** The TOS is the key and the NOS is the data.  Pop both from the stack
+** and put them on the sorter.  The key and data should have been
+** made using SortMakeKey and SortMakeRec, respectively.
+*/
+case OP_SortPut: {
+  int tos = p->tos;
+  int nos = tos - 1;
+  Sorter *pSorter;
+  VERIFY( if( tos<1 ) goto not_enough_stack; )
+  if( Dynamicify(p, tos) || Dynamicify(p, nos) ) goto no_mem;
+  pSorter = sqliteMallocRaw( sizeof(Sorter) );
+  if( pSorter==0 ) goto no_mem;
+  pSorter->pNext = p->pSort;
+  p->pSort = pSorter;
+  assert( aStack[tos].flags & STK_Dyn );
+  pSorter->nKey = aStack[tos].n;
+  pSorter->zKey = zStack[tos];
+  pSorter->nData = aStack[nos].n;
+  if( aStack[nos].flags & STK_Dyn ){
+    pSorter->pData = zStack[nos];
+  }else{
+    pSorter->pData = sqliteStrDup(zStack[nos]);
+  }
+  aStack[tos].flags = 0;
+  aStack[nos].flags = 0;
+  zStack[tos] = 0;
+  zStack[nos] = 0;
+  p->tos -= 2;
+  break;
+}
+
+/* Opcode: SortMakeRec P1 * *
+**
+** The top P1 elements are the arguments to a callback.  Form these
+** elements into a single data entry that can be stored on a sorter
+** using SortPut and later fed to a callback using SortCallback.
+*/
+case OP_SortMakeRec: {
+  char *z;
+  char **azArg;
+  int nByte;
+  int nField;
+  int i, j;
+
+  nField = pOp->p1;
+  VERIFY( if( p->tos+1<nField ) goto not_enough_stack; )
+  nByte = 0;
+  for(i=p->tos-nField+1; i<=p->tos; i++){
+    if( (aStack[i].flags & STK_Null)==0 ){
+      Stringify(p, i);
+      nByte += aStack[i].n;
+    }
+  }
+  nByte += sizeof(char*)*(nField+1);
+  azArg = sqliteMallocRaw( nByte );
+  if( azArg==0 ) goto no_mem;
+  z = (char*)&azArg[nField+1];
+  for(j=0, i=p->tos-nField+1; i<=p->tos; i++, j++){
+    if( aStack[i].flags & STK_Null ){
+      azArg[j] = 0;
+    }else{
+      azArg[j] = z;
+      strcpy(z, zStack[i]);
+      z += aStack[i].n;
+    }
+  }
+  PopStack(p, nField);
+  p->tos++;
+  aStack[p->tos].n = nByte;
+  zStack[p->tos] = (char*)azArg;
+  aStack[p->tos].flags = STK_Str|STK_Dyn;
+  break;
+}
+
+/* Opcode: SortMakeKey * * P3
+**
+** Convert the top few entries of the stack into a sort key.  The
+** number of stack entries consumed is the number of characters in 
+** the string P3.  One character from P3 is prepended to each entry.
+** The first character of P3 is prepended to the element lowest in
+** the stack and the last character of P3 is prepended to the top of
+** the stack.  All stack entries are separated by a \000 character
+** in the result.  The whole key is terminated by two \000 characters
+** in a row.
+**
+** "N" is substituted in place of the P3 character for NULL values.
+**
+** See also the MakeKey and MakeIdxKey opcodes.
+*/
+case OP_SortMakeKey: {
+  char *zNewKey;
+  int nByte;
+  int nField;
+  int i, j, k;
+
+  nField = strlen(pOp->p3);
+  VERIFY( if( p->tos+1<nField ) goto not_enough_stack; )
+  nByte = 1;
+  for(i=p->tos-nField+1; i<=p->tos; i++){
+    if( (aStack[i].flags & STK_Null)!=0 ){
+      nByte += 2;
+    }else{
+      Stringify(p, i);
+      nByte += aStack[i].n+2;
+    }
+  }
+  zNewKey = sqliteMallocRaw( nByte );
+  if( zNewKey==0 ) goto no_mem;
+  j = 0;
+  k = 0;
+  for(i=p->tos-nField+1; i<=p->tos; i++){
+    if( (aStack[i].flags & STK_Null)!=0 ){
+      zNewKey[j++] = 'N';
+      zNewKey[j++] = 0;
+      k++;
+    }else{
+      zNewKey[j++] = pOp->p3[k++];
+      memcpy(&zNewKey[j], zStack[i], aStack[i].n-1);
+      j += aStack[i].n-1;
+      zNewKey[j++] = 0;
+    }
+  }
+  zNewKey[j] = 0;
+  assert( j<nByte );
+  PopStack(p, nField);
+  p->tos++;
+  aStack[p->tos].n = nByte;
+  aStack[p->tos].flags = STK_Str|STK_Dyn;
+  zStack[p->tos] = zNewKey;
+  break;
+}
+
+/* Opcode: Sort * * *
+**
+** Sort all elements on the sorter.  The algorithm is a
+** mergesort.
+*/
+case OP_Sort: {
+  int i;
+  Sorter *pElem;
+  Sorter *apSorter[NSORT];
+  for(i=0; i<NSORT; i++){
+    apSorter[i] = 0;
+  }
+  while( p->pSort ){
+    pElem = p->pSort;
+    p->pSort = pElem->pNext;
+    pElem->pNext = 0;
+    for(i=0; i<NSORT-1; i++){
+    if( apSorter[i]==0 ){
+        apSorter[i] = pElem;
+        break;
+      }else{
+        pElem = Merge(apSorter[i], pElem);
+        apSorter[i] = 0;
+      }
+    }
+    if( i>=NSORT-1 ){
+      apSorter[NSORT-1] = Merge(apSorter[NSORT-1],pElem);
+    }
+  }
+  pElem = 0;
+  for(i=0; i<NSORT; i++){
+    pElem = Merge(apSorter[i], pElem);
+  }
+  p->pSort = pElem;
+  break;
+}
+
+/* Opcode: SortNext * P2 *
+**
+** Push the data for the topmost element in the sorter onto the
+** stack, then remove the element from the sorter.  If the sorter
+** is empty, push nothing on the stack and instead jump immediately 
+** to instruction P2.
+*/
+case OP_SortNext: {
+  Sorter *pSorter = p->pSort;
+  CHECK_FOR_INTERRUPT;
+  if( pSorter!=0 ){
+    p->pSort = pSorter->pNext;
+    p->tos++;
+    zStack[p->tos] = pSorter->pData;
+    aStack[p->tos].n = pSorter->nData;
+    aStack[p->tos].flags = STK_Str|STK_Dyn;
+    sqliteFree(pSorter->zKey);
+    sqliteFree(pSorter);
+  }else{
+    pc = pOp->p2 - 1;
+  }
+  break;
+}
+
+/* Opcode: SortCallback P1 * *
+**
+** The top of the stack contains a callback record built using
+** the SortMakeRec operation with the same P1 value as this
+** instruction.  Pop this record from the stack and invoke the
+** callback on it.
+*/
+case OP_SortCallback: {
+  int i = p->tos;
+  VERIFY( if( i<0 ) goto not_enough_stack; )
+  if( p->xCallback==0 ){
+    p->pc = pc+1;
+    p->azResColumn = (char**)zStack[i];
+    p->nResColumn = pOp->p1;
+    p->popStack = 1;
+    return SQLITE_ROW;
+  }else{
+    if( sqliteSafetyOff(db) ) goto abort_due_to_misuse;
+    if( p->xCallback(p->pCbArg, pOp->p1, (char**)zStack[i], p->azColName)!=0 ){
+      rc = SQLITE_ABORT;
+    }
+    if( sqliteSafetyOn(db) ) goto abort_due_to_misuse;
+    p->nCallback++;
+  }
+  POPSTACK;
+  if( sqlite_malloc_failed ) goto no_mem;
+  break;
+}
+
+/* Opcode: SortReset * * *
+**
+** Remove any elements that remain on the sorter.
+*/
+case OP_SortReset: {
+  SorterReset(p);
+  break;
+}
+
+/* Opcode: FileOpen * * P3
+**
+** Open the file named by P3 for reading using the FileRead opcode.
+** If P3 is "stdin" then open standard input for reading.
+*/
+case OP_FileOpen: {
+  VERIFY( if( pOp->p3==0 ) goto bad_instruction; )
+  if( p->pFile ){
+    if( p->pFile!=stdin ) fclose(p->pFile);
+    p->pFile = 0;
+  }
+  if( sqliteStrICmp(pOp->p3,"stdin")==0 ){
+    p->pFile = stdin;
+  }else{
+    p->pFile = fopen(pOp->p3, "r");
+  }
+  if( p->pFile==0 ){
+    sqliteSetString(&p->zErrMsg,"unable to open file: ", pOp->p3, 0);
+    rc = SQLITE_ERROR;
+  }
+  break;
+}
+
+/* Opcode: FileRead P1 P2 P3
+**
+** Read a single line of input from the open file (the file opened using
+** FileOpen).  If we reach end-of-file, jump immediately to P2.  If
+** we are able to get another line, split the line apart using P3 as
+** a delimiter.  There should be P1 fields.  If the input line contains
+** more than P1 fields, ignore the excess.  If the input line contains
+** fewer than P1 fields, assume the remaining fields contain NULLs.
+**
+** Input ends if a line consists of just "\.".  A field containing only
+** "\N" is a null field.  The backslash \ character can be used be used
+** to escape newlines or the delimiter.
+*/
+case OP_FileRead: {
+  int n, eol, nField, i, c, nDelim;
+  char *zDelim, *z;
+  CHECK_FOR_INTERRUPT;
+  if( p->pFile==0 ) goto fileread_jump;
+  nField = pOp->p1;
+  if( nField<=0 ) goto fileread_jump;
+  if( nField!=p->nField || p->azField==0 ){
+    char **azField = sqliteRealloc(p->azField, sizeof(char*)*nField+1);
+    if( azField==0 ){ goto no_mem; }
+    p->azField = azField;
+    p->nField = nField;
+  }
+  n = 0;
+  eol = 0;
+  while( eol==0 ){
+    if( p->zLine==0 || n+200>p->nLineAlloc ){
+      char *zLine;
+      p->nLineAlloc = p->nLineAlloc*2 + 300;
+      zLine = sqliteRealloc(p->zLine, p->nLineAlloc);
+      if( zLine==0 ){
+        p->nLineAlloc = 0;
+        sqliteFree(p->zLine);
+        p->zLine = 0;
+        goto no_mem;
+      }
+      p->zLine = zLine;
+    }
+    if( vdbe_fgets(&p->zLine[n], p->nLineAlloc-n, p->pFile)==0 ){
+      eol = 1;
+      p->zLine[n] = 0;
+    }else{
+      int c;
+      while( (c = p->zLine[n])!=0 ){
+        if( c=='\\' ){
+          if( p->zLine[n+1]==0 ) break;
+          n += 2;
+        }else if( c=='\n' ){
+          p->zLine[n] = 0;
+          eol = 1;
+          break;
+        }else{
+          n++;
+        }
+      }
+    }
+  }
+  if( n==0 ) goto fileread_jump;
+  z = p->zLine;
+  if( z[0]=='\\' && z[1]=='.' && z[2]==0 ){
+    goto fileread_jump;
+  }
+  zDelim = pOp->p3;
+  if( zDelim==0 ) zDelim = "\t";
+  c = zDelim[0];
+  nDelim = strlen(zDelim);
+  p->azField[0] = z;
+  for(i=1; *z!=0 && i<=nField; i++){
+    int from, to;
+    from = to = 0;
+    if( z[0]=='\\' && z[1]=='N' 
+       && (z[2]==0 || strncmp(&z[2],zDelim,nDelim)==0) ){
+      if( i<=nField ) p->azField[i-1] = 0;
+      z += 2 + nDelim;
+      if( i<nField ) p->azField[i] = z;
+      continue;
+    }
+    while( z[from] ){
+      if( z[from]=='\\' && z[from+1]!=0 ){
+        z[to++] = z[from+1];
+        from += 2;
+        continue;
+      }
+      if( z[from]==c && strncmp(&z[from],zDelim,nDelim)==0 ) break;
+      z[to++] = z[from++];
+    }
+    if( z[from] ){
+      z[to] = 0;
+      z += from + nDelim;
+      if( i<nField ) p->azField[i] = z;
+    }else{
+      z[to] = 0;
+      z = "";
+    }
+  }
+  while( i<nField ){
+    p->azField[i++] = 0;
+  }
+  break;
+
+  /* If we reach end-of-file, or if anything goes wrong, jump here.
+  ** This code will cause a jump to P2 */
+fileread_jump:
+  pc = pOp->p2 - 1;
+  break;
+}
+
+/* Opcode: FileColumn P1 * *
+**
+** Push onto the stack the P1-th column of the most recently read line
+** from the input file.
+*/
+case OP_FileColumn: {
+  int i = pOp->p1;
+  char *z;
+  if( VERIFY( i>=0 && i<p->nField && ) p->azField ){
+    z = p->azField[i];
+  }else{
+    z = 0;
+  }
+  p->tos++;
+  if( z ){
+    aStack[p->tos].n = strlen(z) + 1;
+    zStack[p->tos] = z;
+    aStack[p->tos].flags = STK_Str;
+  }else{
+    aStack[p->tos].n = 0;
+    zStack[p->tos] = 0;
+    aStack[p->tos].flags = STK_Null;
+  }
+  break;
+}
+
+/* Opcode: MemStore P1 P2 *
+**
+** Write the top of the stack into memory location P1.
+** P1 should be a small integer since space is allocated
+** for all memory locations between 0 and P1 inclusive.
+**
+** After the data is stored in the memory location, the
+** stack is popped once if P2 is 1.  If P2 is zero, then
+** the original data remains on the stack.
+*/
+case OP_MemStore: {
+  int i = pOp->p1;
+  int tos = p->tos;
+  char *zOld;
+  Mem *pMem;
+  int flags;
+  VERIFY( if( tos<0 ) goto not_enough_stack; )
+  if( i>=p->nMem ){
+    int nOld = p->nMem;
+    Mem *aMem;
+    p->nMem = i + 5;
+    aMem = sqliteRealloc(p->aMem, p->nMem*sizeof(p->aMem[0]));
+    if( aMem==0 ) goto no_mem;
+    if( aMem!=p->aMem ){
+      int j;
+      for(j=0; j<nOld; j++){
+        if( aMem[j].z==p->aMem[j].s.z ){
+          aMem[j].z = aMem[j].s.z;
+        }
+      }
+    }
+    p->aMem = aMem;
+    if( nOld<p->nMem ){
+      memset(&p->aMem[nOld], 0, sizeof(p->aMem[0])*(p->nMem-nOld));
+    }
+  }
+  pMem = &p->aMem[i];
+  flags = pMem->s.flags;
+  if( flags & STK_Dyn ){
+    zOld = pMem->z;
+  }else{
+    zOld = 0;
+  }
+  pMem->s = aStack[tos];
+  flags = pMem->s.flags;
+  if( flags & (STK_Static|STK_Dyn|STK_Ephem) ){
+    if( (flags & STK_Static)!=0 || (pOp->p2 && (flags & STK_Dyn)!=0) ){
+      pMem->z = zStack[tos];
+    }else if( flags & STK_Str ){
+      pMem->z = sqliteMallocRaw( pMem->s.n );
+      if( pMem->z==0 ) goto no_mem;
+      memcpy(pMem->z, zStack[tos], pMem->s.n);
+      pMem->s.flags |= STK_Dyn;
+      pMem->s.flags &= ~(STK_Static|STK_Ephem);
+    }
+  }else{
+    pMem->z = pMem->s.z;
+  }
+  if( zOld ) sqliteFree(zOld);
+  if( pOp->p2 ){
+    zStack[tos] = 0;
+    aStack[tos].flags = 0;
+    POPSTACK;
+  }
+  break;
+}
+
+/* Opcode: MemLoad P1 * *
+**
+** Push a copy of the value in memory location P1 onto the stack.
+**
+** If the value is a string, then the value pushed is a pointer to
+** the string that is stored in the memory location.  If the memory
+** location is subsequently changed (using OP_MemStore) then the
+** value pushed onto the stack will change too.
+*/
+case OP_MemLoad: {
+  int tos = ++p->tos;
+  int i = pOp->p1;
+  VERIFY( if( i<0 || i>=p->nMem ) goto bad_instruction; )
+  memcpy(&aStack[tos], &p->aMem[i].s, sizeof(aStack[tos])-NBFS);;
+  if( aStack[tos].flags & STK_Str ){
+    zStack[tos] = p->aMem[i].z;
+    aStack[tos].flags |= STK_Ephem;
+    aStack[tos].flags &= ~(STK_Dyn|STK_Static);
+  }
+  break;
+}
+
+/* Opcode: MemIncr P1 P2 *
+**
+** Increment the integer valued memory cell P1 by 1.  If P2 is not zero
+** and the result after the increment is greater than zero, then jump
+** to P2.
+**
+** This instruction throws an error if the memory cell is not initially
+** an integer.
+*/
+case OP_MemIncr: {
+  int i = pOp->p1;
+  Mem *pMem;
+  VERIFY( if( i<0 || i>=p->nMem ) goto bad_instruction; )
+  pMem = &p->aMem[i];
+  VERIFY( if( pMem->s.flags != STK_Int ) goto bad_instruction; )
+  pMem->s.i++;
+  if( pOp->p2>0 && pMem->s.i>0 ){
+     pc = pOp->p2 - 1;
+  }
+  break;
+}
+
+/* Opcode: AggReset * P2 *
+**
+** Reset the aggregator so that it no longer contains any data.
+** Future aggregator elements will contain P2 values each.
+*/
+case OP_AggReset: {
+  AggReset(&p->agg);
+  p->agg.nMem = pOp->p2;
+  p->agg.apFunc = sqliteMalloc( p->agg.nMem*sizeof(p->agg.apFunc[0]) );
+  if( p->agg.apFunc==0 ) goto no_mem;
+  break;
+}
+
+/* Opcode: AggInit * P2 P3
+**
+** Initialize the function parameters for an aggregate function.
+** The aggregate will operate out of aggregate column P2.
+** P3 is a pointer to the FuncDef structure for the function.
+*/
+case OP_AggInit: {
+  int i = pOp->p2;
+  VERIFY( if( i<0 || i>=p->agg.nMem ) goto bad_instruction; )
+  p->agg.apFunc[i] = (FuncDef*)pOp->p3;
+  break;
+}
+
+/* Opcode: AggFunc * P2 P3
+**
+** Execute the step function for an aggregate.  The
+** function has P2 arguments.  P3 is a pointer to the FuncDef
+** structure that specifies the function.
+**
+** The top of the stack must be an integer which is the index of
+** the aggregate column that corresponds to this aggregate function.
+** Ideally, this index would be another parameter, but there are
+** no free parameters left.  The integer is popped from the stack.
+*/
+case OP_AggFunc: {
+  int n = pOp->p2;
+  int i;
+  Mem *pMem;
+  sqlite_func ctx;
+
+  VERIFY( if( n<0 ) goto bad_instruction; )
+  VERIFY( if( p->tos+1<n ) goto not_enough_stack; )
+  VERIFY( if( aStack[p->tos].flags!=STK_Int ) goto bad_instruction; )
+  for(i=p->tos-n; i<p->tos; i++){
+    if( aStack[i].flags & STK_Null ){
+      zStack[i] = 0;
+    }else{
+      Stringify(p, i);
+    }
+  }
+  i = aStack[p->tos].i;
+  VERIFY( if( i<0 || i>=p->agg.nMem ) goto bad_instruction; )
+  ctx.pFunc = (FuncDef*)pOp->p3;
+  pMem = &p->agg.pCurrent->aMem[i];
+  ctx.z = pMem->s.z;
+  ctx.pAgg = pMem->z;
+  ctx.cnt = ++pMem->s.i;
+  ctx.isError = 0;
+  ctx.isStep = 1;
+  (ctx.pFunc->xStep)(&ctx, n, (const char**)&zStack[p->tos-n]);
+  pMem->z = ctx.pAgg;
+  pMem->s.flags = STK_AggCtx;
+  PopStack(p, n+1);
+  if( ctx.isError ){
+    rc = SQLITE_ERROR;
+  }
+  break;
+}
+
+/* Opcode: AggFocus * P2 *
+**
+** Pop the top of the stack and use that as an aggregator key.  If
+** an aggregator with that same key already exists, then make the
+** aggregator the current aggregator and jump to P2.  If no aggregator
+** with the given key exists, create one and make it current but
+** do not jump.
+**
+** The order of aggregator opcodes is important.  The order is:
+** AggReset AggFocus AggNext.  In other words, you must execute
+** AggReset first, then zero or more AggFocus operations, then
+** zero or more AggNext operations.  You must not execute an AggFocus
+** in between an AggNext and an AggReset.
+*/
+case OP_AggFocus: {
+  int tos = p->tos;
+  AggElem *pElem;
+  char *zKey;
+  int nKey;
+
+  VERIFY( if( tos<0 ) goto not_enough_stack; )
+  Stringify(p, tos);
+  zKey = zStack[tos]; 
+  nKey = aStack[tos].n;
+  pElem = sqliteHashFind(&p->agg.hash, zKey, nKey);
+  if( pElem ){
+    p->agg.pCurrent = pElem;
+    pc = pOp->p2 - 1;
+  }else{
+    AggInsert(&p->agg, zKey, nKey);
+    if( sqlite_malloc_failed ) goto no_mem;
+  }
+  POPSTACK;
+  break; 
+}
+
+/* Opcode: AggSet * P2 *
+**
+** Move the top of the stack into the P2-th field of the current
+** aggregate.  String values are duplicated into new memory.
+*/
+case OP_AggSet: {
+  AggElem *pFocus = AggInFocus(p->agg);
+  int i = pOp->p2;
+  int tos = p->tos;
+  VERIFY( if( tos<0 ) goto not_enough_stack; )
+  if( pFocus==0 ) goto no_mem;
+  if( VERIFY( i>=0 && ) i<p->agg.nMem ){
+    Mem *pMem = &pFocus->aMem[i];
+    char *zOld;
+    if( pMem->s.flags & STK_Dyn ){
+      zOld = pMem->z;
+    }else{
+      zOld = 0;
+    }
+    Deephemeralize(p, tos);
+    pMem->s = aStack[tos];
+    if( pMem->s.flags & STK_Dyn ){
+      pMem->z = zStack[tos];
+      zStack[tos] = 0;
+      aStack[tos].flags = 0;
+    }else if( pMem->s.flags & (STK_Static|STK_AggCtx) ){
+      pMem->z = zStack[tos];
+    }else if( pMem->s.flags & STK_Str ){
+      pMem->z = pMem->s.z;
+    }
+    if( zOld ) sqliteFree(zOld);
+  }
+  POPSTACK;
+  break;
+}
+
+/* Opcode: AggGet * P2 *
+**
+** Push a new entry onto the stack which is a copy of the P2-th field
+** of the current aggregate.  Strings are not duplicated so
+** string values will be ephemeral.
+*/
+case OP_AggGet: {
+  AggElem *pFocus = AggInFocus(p->agg);
+  int i = pOp->p2;
+  int tos = ++p->tos;
+  if( pFocus==0 ) goto no_mem;
+  if( VERIFY( i>=0 && ) i<p->agg.nMem ){
+    Mem *pMem = &pFocus->aMem[i];
+    aStack[tos] = pMem->s;
+    zStack[tos] = pMem->z;
+    aStack[tos].flags &= ~STK_Dyn;
+    aStack[tos].flags |= STK_Ephem;
+  }
+  break;
+}
+
+/* Opcode: AggNext * P2 *
+**
+** Make the next aggregate value the current aggregate.  The prior
+** aggregate is deleted.  If all aggregate values have been consumed,
+** jump to P2.
+**
+** The order of aggregator opcodes is important.  The order is:
+** AggReset AggFocus AggNext.  In other words, you must execute
+** AggReset first, then zero or more AggFocus operations, then
+** zero or more AggNext operations.  You must not execute an AggFocus
+** in between an AggNext and an AggReset.
+*/
+case OP_AggNext: {
+  CHECK_FOR_INTERRUPT;
+  if( p->agg.pSearch==0 ){
+    p->agg.pSearch = sqliteHashFirst(&p->agg.hash);
+  }else{
+    p->agg.pSearch = sqliteHashNext(p->agg.pSearch);
+  }
+  if( p->agg.pSearch==0 ){
+    pc = pOp->p2 - 1;
+  } else {
+    int i;
+    sqlite_func ctx;
+    Mem *aMem;
+    p->agg.pCurrent = sqliteHashData(p->agg.pSearch);
+    aMem = p->agg.pCurrent->aMem;
+    for(i=0; i<p->agg.nMem; i++){
+      int freeCtx;
+      if( p->agg.apFunc[i]==0 ) continue;
+      if( p->agg.apFunc[i]->xFinalize==0 ) continue;
+      ctx.s.flags = STK_Null;
+      ctx.z = 0;
+      ctx.pAgg = (void*)aMem[i].z;
+      freeCtx = aMem[i].z && aMem[i].z!=aMem[i].s.z;
+      ctx.cnt = aMem[i].s.i;
+      ctx.isStep = 0;
+      ctx.pFunc = p->agg.apFunc[i];
+      (*p->agg.apFunc[i]->xFinalize)(&ctx);
+      if( freeCtx ){
+        sqliteFree( aMem[i].z );
+      }
+      aMem[i].s = ctx.s;
+      aMem[i].z = ctx.z;
+      if( (aMem[i].s.flags & STK_Str) &&
+              (aMem[i].s.flags & (STK_Dyn|STK_Static|STK_Ephem))==0 ){
+        aMem[i].z = aMem[i].s.z;
+      }
+    }
+  }
+  break;
+}
+
+/* Opcode: SetInsert P1 * P3
+**
+** If Set P1 does not exist then create it.  Then insert value
+** P3 into that set.  If P3 is NULL, then insert the top of the
+** stack into the set.
+*/
+case OP_SetInsert: {
+  int i = pOp->p1;
+  if( p->nSet<=i ){
+    int k;
+    Set *aSet = sqliteRealloc(p->aSet, (i+1)*sizeof(p->aSet[0]) );
+    if( aSet==0 ) goto no_mem;
+    p->aSet = aSet;
+    for(k=p->nSet; k<=i; k++){
+      sqliteHashInit(&p->aSet[k].hash, SQLITE_HASH_BINARY, 1);
+    }
+    p->nSet = i+1;
+  }
+  if( pOp->p3 ){
+    sqliteHashInsert(&p->aSet[i].hash, pOp->p3, strlen(pOp->p3)+1, p);
+  }else{
+    int tos = p->tos;
+    if( tos<0 ) goto not_enough_stack;
+    Stringify(p, tos);
+    sqliteHashInsert(&p->aSet[i].hash, zStack[tos], aStack[tos].n, p);
+    POPSTACK;
+  }
+  if( sqlite_malloc_failed ) goto no_mem;
+  break;
+}
+
+/* Opcode: SetFound P1 P2 *
+**
+** Pop the stack once and compare the value popped off with the
+** contents of set P1.  If the element popped exists in set P1,
+** then jump to P2.  Otherwise fall through.
+*/
+case OP_SetFound: {
+  int i = pOp->p1;
+  int tos = p->tos;
+  VERIFY( if( tos<0 ) goto not_enough_stack; )
+  Stringify(p, tos);
+  if( i>=0 && i<p->nSet &&
+       sqliteHashFind(&p->aSet[i].hash, zStack[tos], aStack[tos].n)){
+    pc = pOp->p2 - 1;
+  }
+  POPSTACK;
+  break;
+}
+
+/* Opcode: SetNotFound P1 P2 *
+**
+** Pop the stack once and compare the value popped off with the
+** contents of set P1.  If the element popped does not exists in 
+** set P1, then jump to P2.  Otherwise fall through.
+*/
+case OP_SetNotFound: {
+  int i = pOp->p1;
+  int tos = p->tos;
+  VERIFY( if( tos<0 ) goto not_enough_stack; )
+  Stringify(p, tos);
+  if( i<0 || i>=p->nSet ||
+       sqliteHashFind(&p->aSet[i].hash, zStack[tos], aStack[tos].n)==0 ){
+    pc = pOp->p2 - 1;
+  }
+  POPSTACK;
+  break;
+}
+
+/* Opcode: SetFirst P1 P2 *
+**
+** Read the first element from set P1 and push it onto the stack.  If the
+** set is empty, push nothing and jump immediately to P2.  This opcode is
+** used in combination with OP_SetNext to loop over all elements of a set.
+*/
+/* Opcode: SetNext P1 P2 *
+**
+** Read the next element from set P1 and push it onto the stack.  If there
+** are no more elements in the set, do not do the push and fall through.
+** Otherwise, jump to P2 after pushing the next set element.
+*/
+case OP_SetFirst: 
+case OP_SetNext: {
+  Set *pSet;
+  int tos;
+  CHECK_FOR_INTERRUPT;
+  if( pOp->p1<0 || pOp->p1>=p->nSet ){
+    if( pOp->opcode==OP_SetFirst ) pc = pOp->p2 - 1;
+    break;
+  }
+  pSet = &p->aSet[pOp->p1];
+  if( pOp->opcode==OP_SetFirst ){
+    pSet->prev = sqliteHashFirst(&pSet->hash);
+    if( pSet->prev==0 ){
+      pc = pOp->p2 - 1;
+      break;
+    }
+  }else{
+    VERIFY( if( pSet->prev==0 ) goto bad_instruction; )
+    pSet->prev = sqliteHashNext(pSet->prev);
+    if( pSet->prev==0 ){
+      break;
+    }else{
+      pc = pOp->p2 - 1;
+    }
+  }
+  tos = ++p->tos;
+  zStack[tos] = sqliteHashKey(pSet->prev);
+  aStack[tos].n = sqliteHashKeysize(pSet->prev);
+  aStack[tos].flags = STK_Str | STK_Ephem;
+  break;
+}
+
+/* An other opcode is illegal...
+*/
+default: {
+  sprintf(zBuf,"%d",pOp->opcode);
+  sqliteSetString(&p->zErrMsg, "unknown opcode ", zBuf, 0);
+  rc = SQLITE_INTERNAL;
+  break;
+}
+
+/*****************************************************************************
+** The cases of the switch statement above this line should all be indented
+** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
+** readability.  From this point on down, the normal indentation rules are
+** restored.
+*****************************************************************************/
+    }
+
+#ifdef VDBE_PROFILE
+    {
+      long long elapse = hwtime() - start;
+      pOp->cycles += elapse;
+      pOp->cnt++;
+#if 0
+        fprintf(stdout, "%10lld ", elapse);
+        vdbePrintOp(stdout, origPc, &p->aOp[origPc]);
+#endif
+    }
+#endif
+
+    /* The following code adds nothing to the actual functionality
+    ** of the program.  It is only here for testing and debugging.
+    ** On the other hand, it does burn CPU cycles every time through
+    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
+    */
+#ifndef NDEBUG
+    if( pc<-1 || pc>=p->nOp ){
+      sqliteSetString(&p->zErrMsg, "jump destination out of range", 0);
+      rc = SQLITE_INTERNAL;
+    }
+    if( p->trace && p->tos>=0 ){
+      int i;
+      fprintf(p->trace, "Stack:");
+      for(i=p->tos; i>=0 && i>p->tos-5; i--){
+        if( aStack[i].flags & STK_Null ){
+          fprintf(p->trace, " NULL");
+        }else if( (aStack[i].flags & (STK_Int|STK_Str))==(STK_Int|STK_Str) ){
+          fprintf(p->trace, " si:%d", aStack[i].i);
+        }else if( aStack[i].flags & STK_Int ){
+          fprintf(p->trace, " i:%d", aStack[i].i);
+        }else if( aStack[i].flags & STK_Real ){
+          fprintf(p->trace, " r:%g", aStack[i].r);
+        }else if( aStack[i].flags & STK_Str ){
+          int j, k;
+          char zBuf[100];
+          zBuf[0] = ' ';
+          if( aStack[i].flags & STK_Dyn ){
+            zBuf[1] = 'z';
+            assert( (aStack[i].flags & (STK_Static|STK_Ephem))==0 );
+          }else if( aStack[i].flags & STK_Static ){
+            zBuf[1] = 't';
+            assert( (aStack[i].flags & (STK_Dyn|STK_Ephem))==0 );
+          }else if( aStack[i].flags & STK_Ephem ){
+            zBuf[1] = 'e';
+            assert( (aStack[i].flags & (STK_Static|STK_Dyn))==0 );
+          }else{
+            zBuf[1] = 's';
+          }
+          zBuf[2] = '[';
+          k = 3;
+          for(j=0; j<20 && j<aStack[i].n; j++){
+            int c = zStack[i][j];
+            if( c==0 && j==aStack[i].n-1 ) break;
+            if( isprint(c) && !isspace(c) ){
+              zBuf[k++] = c;
+            }else{
+              zBuf[k++] = '.';
+            }
+          }
+          zBuf[k++] = ']';
+          zBuf[k++] = 0;
+          fprintf(p->trace, "%s", zBuf);
+        }else{
+          fprintf(p->trace, " ???");
+        }
+      }
+      if( rc!=0 ) fprintf(p->trace," rc=%d",rc);
+      fprintf(p->trace,"\n");
+    }
+#endif
+  }  /* The end of the for(;;) loop the loops through opcodes */
+
+  /* If we reach this point, it means that execution is finished.
+  */
+vdbe_halt:
+  if( rc ){
+    p->rc = rc;
+    rc = SQLITE_ERROR;
+  }else{
+    rc = SQLITE_DONE;
+  }
+  p->magic = VDBE_MAGIC_HALT;
+  return rc;
+
+  /* Jump to here if a malloc() fails.  It's hard to get a malloc()
+  ** to fail on a modern VM computer, so this code is untested.
+  */
+no_mem:
+  sqliteSetString(&p->zErrMsg, "out of memory", 0);
+  rc = SQLITE_NOMEM;
+  goto vdbe_halt;
+
+  /* Jump to here for an SQLITE_MISUSE error.
+  */
+abort_due_to_misuse:
+  rc = SQLITE_MISUSE;
+  /* Fall thru into abort_due_to_error */
+
+  /* Jump to here for any other kind of fatal error.  The "rc" variable
+  ** should hold the error number.
+  */
+abort_due_to_error:
+  if( p->zErrMsg==0 ){
+    sqliteSetString(&p->zErrMsg, sqlite_error_string(rc), 0);
+  }
+  goto vdbe_halt;
+
+  /* Jump to here if the sqlite_interrupt() API sets the interrupt
+  ** flag.
+  */
+abort_due_to_interrupt:
+  assert( db->flags & SQLITE_Interrupt );
+  db->flags &= ~SQLITE_Interrupt;
+  if( db->magic!=SQLITE_MAGIC_BUSY ){
+    rc = SQLITE_MISUSE;
+  }else{
+    rc = SQLITE_INTERRUPT;
+  }
+  sqliteSetString(&p->zErrMsg, sqlite_error_string(rc), 0);
+  goto vdbe_halt;
+
+  /* Jump to here if a operator is encountered that requires more stack
+  ** operands than are currently available on the stack.
+  */
+not_enough_stack:
+  sprintf(zBuf,"%d",pc);
+  sqliteSetString(&p->zErrMsg, "too few operands on stack at ", zBuf, 0);
+  rc = SQLITE_INTERNAL;
+  goto vdbe_halt;
+
+  /* Jump here if an illegal or illformed instruction is executed.
+  */
+VERIFY(
+bad_instruction:
+  sprintf(zBuf,"%d",pc);
+  sqliteSetString(&p->zErrMsg, "illegal operation at ", zBuf, 0);
+  rc = SQLITE_INTERNAL;
+  goto vdbe_halt;
+)
+}
+
+
+/*
+** Clean up the VDBE after execution.  Return an integer which is the
+** result code.
+*/
+int sqliteVdbeFinalize(Vdbe *p, char **pzErrMsg){
+  sqlite *db = p->db;
+  Btree *pBt = p->pBt;
+  int rc;
+
+  if( p->magic!=VDBE_MAGIC_RUN && p->magic!=VDBE_MAGIC_HALT ){
+    sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), 0);
+    return SQLITE_MISUSE;
+  }
+  if( p->zErrMsg ){
+    if( pzErrMsg && *pzErrMsg==0 ){
+      *pzErrMsg = p->zErrMsg;
+    }else{
+      sqliteFree(p->zErrMsg);
+    }
+    p->zErrMsg = 0;
+  }
+  Cleanup(p);
+  if( p->rc!=SQLITE_OK ){
+    switch( p->errorAction ){
+      case OE_Abort: {
+        if( !p->undoTransOnError ){
+          sqliteBtreeRollbackCkpt(pBt);
+          if( db->pBeTemp ) sqliteBtreeRollbackCkpt(db->pBeTemp);
+          break;
+        }
+        /* Fall through to ROLLBACK */
+      }
+      case OE_Rollback: {
+        sqliteBtreeRollback(pBt);
+        if( db->pBeTemp ) sqliteBtreeRollback(db->pBeTemp);
+        db->flags &= ~SQLITE_InTrans;
+        db->onError = OE_Default;
+        break;
+      }
+      default: {
+        if( p->undoTransOnError ){
+          sqliteBtreeCommit(pBt);
+          if( db->pBeTemp ) sqliteBtreeCommit(db->pBeTemp);
+          db->flags &= ~SQLITE_InTrans;
+          db->onError = OE_Default;
+        }
+        break;
+      }
+    }
+    sqliteRollbackInternalChanges(db);
+  }
+  sqliteBtreeCommitCkpt(pBt);
+  if( db->pBeTemp ) sqliteBtreeCommitCkpt(db->pBeTemp);
+  assert( p->tos<p->pc || sqlite_malloc_failed==1 );
+#ifdef VDBE_PROFILE
+  {
+    FILE *out = fopen("vdbe_profile.out", "a");
+    if( out ){
+      int i;
+      fprintf(out, "---- ");
+      for(i=0; i<p->nOp; i++){
+        fprintf(out, "%02x", p->aOp[i].opcode);
+      }
+      fprintf(out, "\n");
+      for(i=0; i<p->nOp; i++){
+        fprintf(out, "%6d %10lld %8lld ",
+           p->aOp[i].cnt,
+           p->aOp[i].cycles,
+           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
+        );
+        vdbePrintOp(out, i, &p->aOp[i]);
+      }
+      fclose(out);
+    }
+  }
+#endif
+  rc = p->rc;
+  sqliteVdbeDelete(p);
+  if( db->want_to_close && db->pVdbe==0 ){
+    sqlite_close(db);
+  }
+  return rc;
+}
diff --git a/ext/sqlite/libsqlite/src/vdbe.h b/ext/sqlite/libsqlite/src/vdbe.h
new file mode 100644 (file)
index 0000000..0a885e4
--- /dev/null
@@ -0,0 +1,95 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** Header file for the Virtual DataBase Engine (VDBE)
+**
+** This header defines the interface to the virtual database engine
+** or VDBE.  The VDBE implements an abstract machine that runs a
+** simple program to access and modify the underlying database.
+**
+** $Id$
+*/
+#ifndef _SQLITE_VDBE_H_
+#define _SQLITE_VDBE_H_
+#include <stdio.h>
+
+/*
+** A single VDBE is an opaque structure named "Vdbe".  Only routines
+** in the source file sqliteVdbe.c are allowed to see the insides
+** of this structure.
+*/
+typedef struct Vdbe Vdbe;
+
+/*
+** A single instruction of the virtual machine has an opcode
+** and as many as three operands.  The instruction is recorded
+** as an instance of the following structure:
+*/
+struct VdbeOp {
+  int opcode;         /* What operation to perform */
+  int p1;             /* First operand */
+  int p2;             /* Second parameter (often the jump destination) */
+  char *p3;           /* Third parameter */
+  int p3type;         /* P3_STATIC, P3_DYNAMIC or P3_POINTER */
+#ifdef VDBE_PROFILE
+  int cnt;            /* Number of times this instruction was executed */
+  long long cycles;   /* Total time spend executing this instruction */
+#endif
+};
+typedef struct VdbeOp VdbeOp;
+
+/*
+** Allowed values of VdbeOp.p3type
+*/
+#define P3_NOTUSED    0   /* The P3 parameter is not used */
+#define P3_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
+#define P3_STATIC   (-2)  /* Pointer to a static string */
+#define P3_POINTER  (-3)  /* P3 is a pointer to some structure or object */
+
+/*
+** The following macro converts a relative address in the p2 field
+** of a VdbeOp structure into a negative number so that 
+** sqliteVdbeAddOpList() knows that the address is relative.  Calling
+** the macro again restores the address.
+*/
+#define ADDR(X)  (-1-(X))
+
+/*
+** The makefile scans the vdbe.c source file and creates the "opcodes.h"
+** header file that defines a number for each opcode used by the VDBE.
+*/
+#include "opcodes.h"
+
+/*
+** Prototypes for the VDBE interface.  See comments on the implementation
+** for a description of what each of these routines does.
+*/
+Vdbe *sqliteVdbeCreate(sqlite*);
+void sqliteVdbeCreateCallback(Vdbe*, int*);
+int sqliteVdbeAddOp(Vdbe*,int,int,int);
+int sqliteVdbeAddOpList(Vdbe*, int nOp, VdbeOp const *aOp);
+void sqliteVdbeChangeP1(Vdbe*, int addr, int P1);
+void sqliteVdbeChangeP2(Vdbe*, int addr, int P2);
+void sqliteVdbeChangeP3(Vdbe*, int addr, const char *zP1, int N);
+void sqliteVdbeDequoteP3(Vdbe*, int addr);
+int sqliteVdbeFindOp(Vdbe*, int, int);
+int sqliteVdbeMakeLabel(Vdbe*);
+void sqliteVdbeDelete(Vdbe*);
+void sqliteVdbeMakeReady(Vdbe*,sqlite_callback,void*,int);
+int sqliteVdbeExec(Vdbe*);
+int sqliteVdbeList(Vdbe*);
+int sqliteVdbeFinalize(Vdbe*,char**);
+void sqliteVdbeResolveLabel(Vdbe*, int);
+int sqliteVdbeCurrentAddr(Vdbe*);
+void sqliteVdbeTrace(Vdbe*,FILE*);
+void sqliteVdbeCompressSpace(Vdbe*,int);
+
+#endif
diff --git a/ext/sqlite/libsqlite/src/where.c b/ext/sqlite/libsqlite/src/where.c
new file mode 100644 (file)
index 0000000..682b33c
--- /dev/null
@@ -0,0 +1,1162 @@
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This module contains C code that generates VDBE code used to process
+** the WHERE clause of SQL statements.  Also found here are subroutines
+** to generate VDBE code to evaluate expressions.
+**
+** $Id$
+*/
+#include "sqliteInt.h"
+
+/*
+** The query generator uses an array of instances of this structure to
+** help it analyze the subexpressions of the WHERE clause.  Each WHERE
+** clause subexpression is separated from the others by an AND operator.
+*/
+typedef struct ExprInfo ExprInfo;
+struct ExprInfo {
+  Expr *p;                /* Pointer to the subexpression */
+  u8 indexable;           /* True if this subexprssion is usable by an index */
+  u8 oracle8join;         /* -1 if left side contains "(+)".  +1 if right side
+                          ** contains "(+)".  0 if neither contains "(+)" */
+  short int idxLeft;      /* p->pLeft is a column in this table number. -1 if
+                          ** p->pLeft is not the column of any table */
+  short int idxRight;     /* p->pRight is a column in this table number. -1 if
+                          ** p->pRight is not the column of any table */
+  unsigned prereqLeft;    /* Bitmask of tables referenced by p->pLeft */
+  unsigned prereqRight;   /* Bitmask of tables referenced by p->pRight */
+  unsigned prereqAll;     /* Bitmask of tables referenced by p */
+};
+
+/*
+** Determine the number of elements in an array.
+*/
+#define ARRAYSIZE(X)  (sizeof(X)/sizeof(X[0]))
+
+/*
+** This routine is used to divide the WHERE expression into subexpressions
+** separated by the AND operator.
+**
+** aSlot[] is an array of subexpressions structures.
+** There are nSlot spaces left in this array.  This routine attempts to
+** split pExpr into subexpressions and fills aSlot[] with those subexpressions.
+** The return value is the number of slots filled.
+*/
+static int exprSplit(int nSlot, ExprInfo *aSlot, Expr *pExpr){
+  int cnt = 0;
+  if( pExpr==0 || nSlot<1 ) return 0;
+  if( nSlot==1 || pExpr->op!=TK_AND ){
+    aSlot[0].p = pExpr;
+    return 1;
+  }
+  if( pExpr->pLeft->op!=TK_AND ){
+    aSlot[0].p = pExpr->pLeft;
+    cnt = 1 + exprSplit(nSlot-1, &aSlot[1], pExpr->pRight);
+  }else{
+    cnt = exprSplit(nSlot, aSlot, pExpr->pLeft);
+    cnt += exprSplit(nSlot-cnt, &aSlot[cnt], pExpr->pRight);
+  }
+  return cnt;
+}
+
+/*
+** This routine walks (recursively) an expression tree and generates
+** a bitmask indicating which tables are used in that expression
+** tree.  Bit 0 of the mask is set if table base+0 is used.  Bit 1
+** is set if table base+1 is used.  And so forth.
+**
+** In order for this routine to work, the calling function must have
+** previously invoked sqliteExprResolveIds() on the expression.  See
+** the header comment on that routine for additional information.
+**
+** "base" is the cursor number (the value of the iTable field) that
+** corresponds to the first entry in the list of tables that appear
+** in the FROM clause of a SELECT.  For UPDATE and DELETE statements
+** there is just a single table with "base" as the cursor number.
+*/
+static int exprTableUsage(int base, Expr *p){
+  unsigned int mask = 0;
+  if( p==0 ) return 0;
+  if( p->op==TK_COLUMN ){
+    return 1<< (p->iTable - base);
+  }
+  if( p->pRight ){
+    mask = exprTableUsage(base, p->pRight);
+  }
+  if( p->pLeft ){
+    mask |= exprTableUsage(base, p->pLeft);
+  }
+  if( p->pList ){
+    int i;
+    for(i=0; i<p->pList->nExpr; i++){
+      mask |= exprTableUsage(base, p->pList->a[i].pExpr);
+    }
+  }
+  return mask;
+}
+
+/*
+** Return TRUE if the given operator is one of the operators that is
+** allowed for an indexable WHERE clause.  The allowed operators are
+** "=", "<", ">", "<=", ">=", and "IN".
+*/
+static int allowedOp(int op){
+  switch( op ){
+    case TK_LT:
+    case TK_LE:
+    case TK_GT:
+    case TK_GE:
+    case TK_EQ:
+    case TK_IN:
+      return 1;
+    default:
+      return 0;
+  }
+}
+
+/*
+** The input to this routine is an ExprInfo structure with only the
+** "p" field filled in.  The job of this routine is to analyze the
+** subexpression and populate all the other fields of the ExprInfo
+** structure.
+**
+** "base" is the cursor number (the value of the iTable field) that
+** corresponds to the first entry in the table list.
+*/
+static void exprAnalyze(int base, ExprInfo *pInfo){
+  Expr *pExpr = pInfo->p;
+  pInfo->prereqLeft = exprTableUsage(base, pExpr->pLeft);
+  pInfo->prereqRight = exprTableUsage(base, pExpr->pRight);
+  pInfo->prereqAll = exprTableUsage(base, pExpr);
+  pInfo->indexable = 0;
+  pInfo->idxLeft = -1;
+  pInfo->idxRight = -1;
+  if( allowedOp(pExpr->op) && (pInfo->prereqRight & pInfo->prereqLeft)==0 ){
+    if( pExpr->pRight && pExpr->pRight->op==TK_COLUMN ){
+      pInfo->idxRight = pExpr->pRight->iTable - base;
+      pInfo->indexable = 1;
+    }
+    if( pExpr->pLeft->op==TK_COLUMN ){
+      pInfo->idxLeft = pExpr->pLeft->iTable - base;
+      pInfo->indexable = 1;
+    }
+  }
+}
+
+/*
+** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
+** left-most table in the FROM clause of that same SELECT statement and
+** the table has a cursor number of "base".
+**
+** This routine attempts to find an index for pTab that generates the
+** correct record sequence for the given ORDER BY clause.  The return value
+** is a pointer to an index that does the job.  NULL is returned if the
+** table has no index that will generate the correct sort order.
+**
+** If there are two or more indices that generate the correct sort order
+** and pPreferredIdx is one of those indices, then return pPreferredIdx.
+**
+** nEqCol is the number of columns of pPreferredIdx that are used as
+** equality constraints.  Any index returned must have exactly this same
+** set of columns.  The ORDER BY clause only matches index columns beyond the
+** the first nEqCol columns.
+**
+** All terms of the ORDER BY clause must be either ASC or DESC.  The
+** *pbRev value is set to 1 if the ORDER BY clause is all DESC and it is
+** set to 0 if the ORDER BY clause is all ASC.
+*/
+static Index *findSortingIndex(
+  Table *pTab,            /* The table to be sorted */
+  int base,               /* Cursor number for pTab */
+  ExprList *pOrderBy,     /* The ORDER BY clause */
+  Index *pPreferredIdx,   /* Use this index, if possible and not NULL */
+  int nEqCol,             /* Number of index columns used with == constraints */
+  int *pbRev              /* Set to 1 if ORDER BY is DESC */
+){
+  int i, j;
+  Index *pMatch;
+  Index *pIdx;
+  int sortOrder;
+
+  assert( pOrderBy!=0 );
+  assert( pOrderBy->nExpr>0 );
+  sortOrder = pOrderBy->a[0].sortOrder & SQLITE_SO_DIRMASK;
+  for(i=0; i<pOrderBy->nExpr; i++){
+    Expr *p;
+    if( (pOrderBy->a[i].sortOrder & SQLITE_SO_DIRMASK)!=sortOrder ){
+      /* Indices can only be used if all ORDER BY terms are either
+      ** DESC or ASC.  Indices cannot be used on a mixture. */
+      return 0;
+    }
+    if( (pOrderBy->a[i].sortOrder & SQLITE_SO_TYPEMASK)!=SQLITE_SO_UNK ){
+      /* Do not sort by index if there is a COLLATE clause */
+      return 0;
+    }
+    p = pOrderBy->a[i].pExpr;
+    if( p->op!=TK_COLUMN || p->iTable!=base ){
+      /* Can not use an index sort on anything that is not a column in the
+      ** left-most table of the FROM clause */
+      return 0;
+    }
+  }
+  
+  /* If we get this far, it means the ORDER BY clause consists only of
+  ** ascending columns in the left-most table of the FROM clause.  Now
+  ** check for a matching index.
+  */
+  pMatch = 0;
+  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+    int nExpr = pOrderBy->nExpr;
+    if( pIdx->nColumn < nEqCol || pIdx->nColumn < nExpr ) continue;
+    for(i=j=0; i<nEqCol; i++){
+      if( pPreferredIdx->aiColumn[i]!=pIdx->aiColumn[i] ) break;
+      if( j<nExpr && pOrderBy->a[j].pExpr->iColumn==pIdx->aiColumn[i] ){ j++; }
+    }
+    if( i<nEqCol ) continue;
+    for(i=0; i+j<nExpr; i++){
+      if( pOrderBy->a[i+j].pExpr->iColumn!=pIdx->aiColumn[i+nEqCol] ) break;
+    }
+    if( i+j>=nExpr ){
+      pMatch = pIdx;
+      if( pIdx==pPreferredIdx ) break;
+    }
+  }
+  if( pMatch && pbRev ){
+    *pbRev = sortOrder==SQLITE_SO_DESC;
+  }
+  return pMatch;
+}
+
+/*
+** Generate the beginning of the loop used for WHERE clause processing.
+** The return value is a pointer to an (opaque) structure that contains
+** information needed to terminate the loop.  Later, the calling routine
+** should invoke sqliteWhereEnd() with the return value of this function
+** in order to complete the WHERE clause processing.
+**
+** If an error occurs, this routine returns NULL.
+**
+** The basic idea is to do a nested loop, one loop for each table in
+** the FROM clause of a select.  (INSERT and UPDATE statements are the
+** same as a SELECT with only a single table in the FROM clause.)  For
+** example, if the SQL is this:
+**
+**       SELECT * FROM t1, t2, t3 WHERE ...;
+**
+** Then the code generated is conceptually like the following:
+**
+**      foreach row1 in t1 do       \    Code generated
+**        foreach row2 in t2 do      |-- by sqliteWhereBegin()
+**          foreach row3 in t3 do   /
+**            ...
+**          end                     \    Code generated
+**        end                        |-- by sqliteWhereEnd()
+**      end                         /
+**
+** There are Btree cursors associated with each table.  t1 uses cursor
+** "base".  t2 uses cursor "base+1".  And so forth.  This routine generates
+** the code to open those cursors.  sqliteWhereEnd() generates the code
+** to close them.
+**
+** If the WHERE clause is empty, the foreach loops must each scan their
+** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
+** the tables have indices and there are terms in the WHERE clause that
+** refer to those indices, a complete table scan can be avoided and the
+** code will run much faster.  Most of the work of this routine is checking
+** to see if there are indices that can be used to speed up the loop.
+**
+** Terms of the WHERE clause are also used to limit which rows actually
+** make it to the "..." in the middle of the loop.  After each "foreach",
+** terms of the WHERE clause that use only terms in that loop and outer
+** loops are evaluated and if false a jump is made around all subsequent
+** inner loops (or around the "..." if the test occurs within the inner-
+** most loop)
+**
+** OUTER JOINS
+**
+** An outer join of tables t1 and t2 is conceptally coded as follows:
+**
+**    foreach row1 in t1 do
+**      flag = 0
+**      foreach row2 in t2 do
+**        start:
+**          ...
+**          flag = 1
+**      end
+**      if flag==0 then
+**        move the row2 cursor to a null row
+**        goto start
+**      fi
+**    end
+**
+** ORDER BY CLAUSE PROCESSING
+**
+** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
+** if there is one.  If there is no ORDER BY clause or if this routine
+** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
+**
+** If an index can be used so that the natural output order of the table
+** scan is correct for the ORDER BY clause, then that index is used and
+** *ppOrderBy is set to NULL.  This is an optimization that prevents an
+** unnecessary sort of the result set if an index appropriate for the
+** ORDER BY clause already exists.
+**
+** If the where clause loops cannot be arranged to provide the correct
+** output order, then the *ppOrderBy is unchanged.
+*/
+WhereInfo *sqliteWhereBegin(
+  Parse *pParse,       /* The parser context */
+  int base,            /* VDBE cursor index for left-most table in pTabList */
+  SrcList *pTabList,   /* A list of all tables to be scanned */
+  Expr *pWhere,        /* The WHERE clause */
+  int pushKey,         /* If TRUE, leave the table key on the stack */
+  ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
+){
+  int i;                     /* Loop counter */
+  WhereInfo *pWInfo;         /* Will become the return value of this function */
+  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
+  int brk, cont;             /* Addresses used during code generation */
+  int nExpr;           /* Number of subexpressions in the WHERE clause */
+  int loopMask;        /* One bit set for each outer loop */
+  int haveKey;         /* True if KEY is on the stack */
+  int iDirectEq[32];   /* Term of the form ROWID==X for the N-th table */
+  int iDirectLt[32];   /* Term of the form ROWID<X or ROWID<=X */
+  int iDirectGt[32];   /* Term of the form ROWID>X or ROWID>=X */
+  ExprInfo aExpr[101]; /* The WHERE clause is divided into these expressions */
+
+  /* pushKey is only allowed if there is a single table (as in an INSERT or
+  ** UPDATE statement)
+  */
+  assert( pushKey==0 || pTabList->nSrc==1 );
+
+  /* Split the WHERE clause into separate subexpressions where each
+  ** subexpression is separated by an AND operator.  If the aExpr[]
+  ** array fills up, the last entry might point to an expression which
+  ** contains additional unfactored AND operators.
+  */
+  memset(aExpr, 0, sizeof(aExpr));
+  nExpr = exprSplit(ARRAYSIZE(aExpr), aExpr, pWhere);
+  if( nExpr==ARRAYSIZE(aExpr) ){
+    char zBuf[50];
+    sprintf(zBuf, "%d", (int)ARRAYSIZE(aExpr)-1);
+    sqliteSetString(&pParse->zErrMsg, "WHERE clause too complex - no more "
+       "than ", zBuf, " terms allowed", 0);
+    pParse->nErr++;
+    return 0;
+  }
+  
+  /* Allocate and initialize the WhereInfo structure that will become the
+  ** return value.
+  */
+  pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
+  if( sqlite_malloc_failed ){
+    sqliteFree(pWInfo);
+    return 0;
+  }
+  pWInfo->pParse = pParse;
+  pWInfo->pTabList = pTabList;
+  pWInfo->base = base;
+  pWInfo->peakNTab = pWInfo->savedNTab = pParse->nTab;
+  pWInfo->iBreak = sqliteVdbeMakeLabel(v);
+
+  /* Special case: a WHERE clause that is constant.  Evaluate the
+  ** expression and either jump over all of the code or fall thru.
+  */
+  if( pWhere && sqliteExprIsConstant(pWhere) ){
+    sqliteExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
+    pWhere = 0;
+  }
+
+  /* Analyze all of the subexpressions.
+  */
+  for(i=0; i<nExpr; i++){
+    exprAnalyze(base, &aExpr[i]);
+
+    /* If we are executing a trigger body, remove all references to
+    ** new.* and old.* tables from the prerequisite masks.
+    */
+    if( pParse->trigStack ){
+      int x;
+      if( (x = pParse->trigStack->newIdx) >= 0 ){
+        int mask = ~(1 << (x - base));
+        aExpr[i].prereqRight &= mask;
+        aExpr[i].prereqLeft &= mask;
+        aExpr[i].prereqAll &= mask;
+      }
+      if( (x = pParse->trigStack->oldIdx) >= 0 ){
+        int mask = ~(1 << (x - base));
+        aExpr[i].prereqRight &= mask;
+        aExpr[i].prereqLeft &= mask;
+        aExpr[i].prereqAll &= mask;
+      }
+    }
+  }
+
+  /* Figure out what index to use (if any) for each nested loop.
+  ** Make pWInfo->a[i].pIdx point to the index to use for the i-th nested
+  ** loop where i==0 is the outer loop and i==pTabList->nSrc-1 is the inner
+  ** loop. 
+  **
+  ** If terms exist that use the ROWID of any table, then set the
+  ** iDirectEq[], iDirectLt[], or iDirectGt[] elements for that table
+  ** to the index of the term containing the ROWID.  We always prefer
+  ** to use a ROWID which can directly access a table rather than an
+  ** index which requires reading an index first to get the rowid then
+  ** doing a second read of the actual database table.
+  **
+  ** Actually, if there are more than 32 tables in the join, only the
+  ** first 32 tables are candidates for indices.  This is (again) due
+  ** to the limit of 32 bits in an integer bitmask.
+  */
+  loopMask = 0;
+  for(i=0; i<pTabList->nSrc && i<ARRAYSIZE(iDirectEq); i++){
+    int j;
+    int idx = i;
+    Table *pTab = pTabList->a[idx].pTab;
+    Index *pIdx;
+    Index *pBestIdx = 0;
+    int bestScore = 0;
+
+    /* Check to see if there is an expression that uses only the
+    ** ROWID field of this table.  For terms of the form ROWID==expr
+    ** set iDirectEq[i] to the index of the term.  For terms of the
+    ** form ROWID<expr or ROWID<=expr set iDirectLt[i] to the term index.
+    ** For terms like ROWID>expr or ROWID>=expr set iDirectGt[i].
+    **
+    ** (Added:) Treat ROWID IN expr like ROWID=expr.
+    */
+    pWInfo->a[i].iCur = -1;
+    iDirectEq[i] = -1;
+    iDirectLt[i] = -1;
+    iDirectGt[i] = -1;
+    for(j=0; j<nExpr; j++){
+      if( aExpr[j].idxLeft==idx && aExpr[j].p->pLeft->iColumn<0
+            && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
+        switch( aExpr[j].p->op ){
+          case TK_IN:
+          case TK_EQ: iDirectEq[i] = j; break;
+          case TK_LE:
+          case TK_LT: iDirectLt[i] = j; break;
+          case TK_GE:
+          case TK_GT: iDirectGt[i] = j;  break;
+        }
+      }
+      if( aExpr[j].idxRight==idx && aExpr[j].p->pRight->iColumn<0
+            && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
+        switch( aExpr[j].p->op ){
+          case TK_EQ: iDirectEq[i] = j;  break;
+          case TK_LE:
+          case TK_LT: iDirectGt[i] = j;  break;
+          case TK_GE:
+          case TK_GT: iDirectLt[i] = j;  break;
+        }
+      }
+    }
+    if( iDirectEq[i]>=0 ){
+      loopMask |= 1<<idx;
+      pWInfo->a[i].pIdx = 0;
+      continue;
+    }
+
+    /* Do a search for usable indices.  Leave pBestIdx pointing to
+    ** the "best" index.  pBestIdx is left set to NULL if no indices
+    ** are usable.
+    **
+    ** The best index is determined as follows.  For each of the
+    ** left-most terms that is fixed by an equality operator, add
+    ** 8 to the score.  The right-most term of the index may be
+    ** constrained by an inequality.  Add 1 if for an "x<..." constraint
+    ** and add 2 for an "x>..." constraint.  Chose the index that
+    ** gives the best score.
+    **
+    ** This scoring system is designed so that the score can later be
+    ** used to determine how the index is used.  If the score&7 is 0
+    ** then all constraints are equalities.  If score&1 is not 0 then
+    ** there is an inequality used as a termination key.  (ex: "x<...")
+    ** If score&2 is not 0 then there is an inequality used as the
+    ** start key.  (ex: "x>...").  A score or 4 is the special case
+    ** of an IN operator constraint.  (ex:  "x IN ...").
+    **
+    ** The IN operator (as in "<expr> IN (...)") is treated the same as
+    ** an equality comparison except that it can only be used on the
+    ** left-most column of an index and other terms of the WHERE clause
+    ** cannot be used in conjunction with the IN operator to help satisfy
+    ** other columns of the index.
+    */
+    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+      int eqMask = 0;  /* Index columns covered by an x=... term */
+      int ltMask = 0;  /* Index columns covered by an x<... term */
+      int gtMask = 0;  /* Index columns covered by an x>... term */
+      int inMask = 0;  /* Index columns covered by an x IN .. term */
+      int nEq, m, score;
+
+      if( pIdx->nColumn>32 ) continue;  /* Ignore indices too many columns */
+      for(j=0; j<nExpr; j++){
+        if( aExpr[j].idxLeft==idx 
+             && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
+          int iColumn = aExpr[j].p->pLeft->iColumn;
+          int k;
+          for(k=0; k<pIdx->nColumn; k++){
+            if( pIdx->aiColumn[k]==iColumn ){
+              switch( aExpr[j].p->op ){
+                case TK_IN: {
+                  if( k==0 ) inMask |= 1;
+                  break;
+                }
+                case TK_EQ: {
+                  eqMask |= 1<<k;
+                  break;
+                }
+                case TK_LE:
+                case TK_LT: {
+                  ltMask |= 1<<k;
+                  break;
+                }
+                case TK_GE:
+                case TK_GT: {
+                  gtMask |= 1<<k;
+                  break;
+                }
+                default: {
+                  /* CANT_HAPPEN */
+                  assert( 0 );
+                  break;
+                }
+              }
+              break;
+            }
+          }
+        }
+        if( aExpr[j].idxRight==idx 
+             && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
+          int iColumn = aExpr[j].p->pRight->iColumn;
+          int k;
+          for(k=0; k<pIdx->nColumn; k++){
+            if( pIdx->aiColumn[k]==iColumn ){
+              switch( aExpr[j].p->op ){
+                case TK_EQ: {
+                  eqMask |= 1<<k;
+                  break;
+                }
+                case TK_LE:
+                case TK_LT: {
+                  gtMask |= 1<<k;
+                  break;
+                }
+                case TK_GE:
+                case TK_GT: {
+                  ltMask |= 1<<k;
+                  break;
+                }
+                default: {
+                  /* CANT_HAPPEN */
+                  assert( 0 );
+                  break;
+                }
+              }
+              break;
+            }
+          }
+        }
+      }
+
+      /* The following loop ends with nEq set to the number of columns
+      ** on the left of the index with == constraints.
+      */
+      for(nEq=0; nEq<pIdx->nColumn; nEq++){
+        m = (1<<(nEq+1))-1;
+        if( (m & eqMask)!=m ) break;
+      }
+      score = nEq*8;   /* Base score is 8 times number of == constraints */
+      m = 1<<nEq;
+      if( m & ltMask ) score++;    /* Increase score for a < constraint */
+      if( m & gtMask ) score+=2;   /* Increase score for a > constraint */
+      if( score==0 && inMask ) score = 4;  /* Default score for IN constraint */
+      if( score>bestScore ){
+        pBestIdx = pIdx;
+        bestScore = score;
+      }
+    }
+    pWInfo->a[i].pIdx = pBestIdx;
+    pWInfo->a[i].score = bestScore;
+    pWInfo->a[i].bRev = 0;
+    loopMask |= 1<<idx;
+    if( pBestIdx ){
+      pWInfo->a[i].iCur = pParse->nTab++;
+      pWInfo->peakNTab = pParse->nTab;
+    }
+  }
+
+  /* Check to see if the ORDER BY clause is or can be satisfied by the
+  ** use of an index on the first table.
+  */
+  if( ppOrderBy && *ppOrderBy && pTabList->nSrc>0 ){
+     Index *pSortIdx;
+     Index *pIdx;
+     Table *pTab;
+     int bRev = 0;
+
+     pTab = pTabList->a[0].pTab;
+     pIdx = pWInfo->a[0].pIdx;
+     if( pIdx && pWInfo->a[0].score==4 ){
+       /* If there is already an IN index on the left-most table,
+       ** it will not give the correct sort order.
+       ** So, pretend that no suitable index is found.
+       */
+       pSortIdx = 0;
+     }else if( iDirectEq[0]>=0 || iDirectLt[0]>=0 || iDirectGt[0]>=0 ){
+       /* If the left-most column is accessed using its ROWID, then do
+       ** not try to sort by index.
+       */
+       pSortIdx = 0;
+     }else{
+       int nEqCol = (pWInfo->a[0].score+4)/8;
+       pSortIdx = findSortingIndex(pTab, base, *ppOrderBy, pIdx, nEqCol, &bRev);
+     }
+     if( pSortIdx && (pIdx==0 || pIdx==pSortIdx) ){
+       if( pIdx==0 ){
+         pWInfo->a[0].pIdx = pSortIdx;
+         pWInfo->a[0].iCur = pParse->nTab++;
+         pWInfo->peakNTab = pParse->nTab;
+       }
+       pWInfo->a[0].bRev = bRev;
+       *ppOrderBy = 0;
+     }
+  }
+
+  /* Open all tables in the pTabList and all indices used by those tables.
+  */
+  for(i=0; i<pTabList->nSrc; i++){
+    int openOp;
+    Table *pTab;
+
+    pTab = pTabList->a[i].pTab;
+    if( pTab->isTransient || pTab->pSelect ) continue;
+    openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
+    sqliteVdbeAddOp(v, openOp, base+i, pTab->tnum);
+    sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
+    if( i==0 && !pParse->schemaVerified &&
+          (pParse->db->flags & SQLITE_InTrans)==0 ){
+      sqliteVdbeAddOp(v, OP_VerifyCookie, pParse->db->schema_cookie, 0);
+      pParse->schemaVerified = 1;
+    }
+    if( pWInfo->a[i].pIdx!=0 ){
+      sqliteVdbeAddOp(v, openOp, pWInfo->a[i].iCur, pWInfo->a[i].pIdx->tnum);
+      sqliteVdbeChangeP3(v, -1, pWInfo->a[i].pIdx->zName, P3_STATIC);
+    }
+  }
+
+  /* Generate the code to do the search
+  */
+  loopMask = 0;
+  for(i=0; i<pTabList->nSrc; i++){
+    int j, k;
+    int idx = i;
+    Index *pIdx;
+    WhereLevel *pLevel = &pWInfo->a[i];
+
+    /* If this is the right table of a LEFT OUTER JOIN, allocate and
+    ** initialize a memory cell that records if this table matches any
+    ** row of the left table of the join.
+    */
+    if( i>0 && (pTabList->a[i-1].jointype & JT_LEFT)!=0 ){
+      if( !pParse->nMem ) pParse->nMem++;
+      pLevel->iLeftJoin = pParse->nMem++;
+      sqliteVdbeAddOp(v, OP_String, 0, 0);
+      sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
+    }
+
+    pIdx = pLevel->pIdx;
+    pLevel->inOp = OP_Noop;
+    if( i<ARRAYSIZE(iDirectEq) && iDirectEq[i]>=0 ){
+      /* Case 1:  We can directly reference a single row using an
+      **          equality comparison against the ROWID field.  Or
+      **          we reference multiple rows using a "rowid IN (...)"
+      **          construct.
+      */
+      k = iDirectEq[i];
+      assert( k<nExpr );
+      assert( aExpr[k].p!=0 );
+      assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
+      brk = pLevel->brk = sqliteVdbeMakeLabel(v);
+      if( aExpr[k].idxLeft==idx ){
+        Expr *pX = aExpr[k].p;
+        if( pX->op!=TK_IN ){
+          sqliteExprCode(pParse, aExpr[k].p->pRight);
+        }else if( pX->pList ){
+          sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
+          pLevel->inOp = OP_SetNext;
+          pLevel->inP1 = pX->iTable;
+          pLevel->inP2 = sqliteVdbeCurrentAddr(v);
+        }else{
+          assert( pX->pSelect );
+          sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
+          sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
+          pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
+          pLevel->inOp = OP_Next;
+          pLevel->inP1 = pX->iTable;
+        }
+      }else{
+        sqliteExprCode(pParse, aExpr[k].p->pLeft);
+      }
+      aExpr[k].p = 0;
+      cont = pLevel->cont = sqliteVdbeMakeLabel(v);
+      sqliteVdbeAddOp(v, OP_MustBeInt, 1, brk);
+      haveKey = 0;
+      sqliteVdbeAddOp(v, OP_NotExists, base+idx, brk);
+      pLevel->op = OP_Noop;
+    }else if( pIdx!=0 && pLevel->score>0 && pLevel->score%4==0 ){
+      /* Case 2:  There is an index and all terms of the WHERE clause that
+      **          refer to the index use the "==" or "IN" operators.
+      */
+      int start;
+      int testOp;
+      int nColumn = (pLevel->score+4)/8;
+      brk = pLevel->brk = sqliteVdbeMakeLabel(v);
+      for(j=0; j<nColumn; j++){
+        for(k=0; k<nExpr; k++){
+          Expr *pX = aExpr[k].p;
+          if( pX==0 ) continue;
+          if( aExpr[k].idxLeft==idx 
+             && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight 
+             && pX->pLeft->iColumn==pIdx->aiColumn[j]
+          ){
+            if( pX->op==TK_EQ ){
+              sqliteExprCode(pParse, pX->pRight);
+              aExpr[k].p = 0;
+              break;
+            }
+            if( pX->op==TK_IN && nColumn==1 ){
+              if( pX->pList ){
+                sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
+                pLevel->inOp = OP_SetNext;
+                pLevel->inP1 = pX->iTable;
+                pLevel->inP2 = sqliteVdbeCurrentAddr(v);
+              }else{
+                assert( pX->pSelect );
+                sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
+                sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
+                pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
+                pLevel->inOp = OP_Next;
+                pLevel->inP1 = pX->iTable;
+              }
+              aExpr[k].p = 0;
+              break;
+            }
+          }
+          if( aExpr[k].idxRight==idx 
+             && aExpr[k].p->op==TK_EQ
+             && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
+             && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
+          ){
+            sqliteExprCode(pParse, aExpr[k].p->pLeft);
+            aExpr[k].p = 0;
+            break;
+          }
+        }
+      }
+      pLevel->iMem = pParse->nMem++;
+      cont = pLevel->cont = sqliteVdbeMakeLabel(v);
+      sqliteVdbeAddOp(v, OP_MakeKey, nColumn, 0);
+      sqliteAddIdxKeyType(v, pIdx);
+      if( nColumn==pIdx->nColumn || pLevel->bRev ){
+        sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
+        testOp = OP_IdxGT;
+      }else{
+        sqliteVdbeAddOp(v, OP_Dup, 0, 0);
+        sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
+        sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
+        testOp = OP_IdxGE;
+      }
+      if( pLevel->bRev ){
+        /* Scan in reverse order */
+        sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
+        sqliteVdbeAddOp(v, OP_MoveLt, pLevel->iCur, brk);
+        start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
+        sqliteVdbeAddOp(v, OP_IdxLT, pLevel->iCur, brk);
+        sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
+        pLevel->op = OP_Prev;
+      }else{
+        /* Scan in the forward order */
+        sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
+        start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
+        sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
+        sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
+        pLevel->op = OP_Next;
+      }
+      if( i==pTabList->nSrc-1 && pushKey ){
+        haveKey = 1;
+      }else{
+        sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
+        haveKey = 0;
+      }
+      pLevel->p1 = pLevel->iCur;
+      pLevel->p2 = start;
+    }else if( i<ARRAYSIZE(iDirectLt) && (iDirectLt[i]>=0 || iDirectGt[i]>=0) ){
+      /* Case 3:  We have an inequality comparison against the ROWID field.
+      */
+      int testOp = OP_Noop;
+      int start;
+
+      brk = pLevel->brk = sqliteVdbeMakeLabel(v);
+      cont = pLevel->cont = sqliteVdbeMakeLabel(v);
+      if( iDirectGt[i]>=0 ){
+        k = iDirectGt[i];
+        assert( k<nExpr );
+        assert( aExpr[k].p!=0 );
+        assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
+        if( aExpr[k].idxLeft==idx ){
+          sqliteExprCode(pParse, aExpr[k].p->pRight);
+        }else{
+          sqliteExprCode(pParse, aExpr[k].p->pLeft);
+        }
+        sqliteVdbeAddOp(v, OP_MustBeInt, 1, brk);
+        if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
+          sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
+        }
+        sqliteVdbeAddOp(v, OP_MoveTo, base+idx, brk);
+        aExpr[k].p = 0;
+      }else{
+        sqliteVdbeAddOp(v, OP_Rewind, base+idx, brk);
+      }
+      if( iDirectLt[i]>=0 ){
+        k = iDirectLt[i];
+        assert( k<nExpr );
+        assert( aExpr[k].p!=0 );
+        assert( aExpr[k].idxLeft==idx || aExpr[k].idxRight==idx );
+        if( aExpr[k].idxLeft==idx ){
+          sqliteExprCode(pParse, aExpr[k].p->pRight);
+        }else{
+          sqliteExprCode(pParse, aExpr[k].p->pLeft);
+        }
+        sqliteVdbeAddOp(v, OP_MustBeInt, 1, sqliteVdbeCurrentAddr(v)+1);
+        pLevel->iMem = pParse->nMem++;
+        sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
+        if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
+          testOp = OP_Ge;
+        }else{
+          testOp = OP_Gt;
+        }
+        aExpr[k].p = 0;
+      }
+      start = sqliteVdbeCurrentAddr(v);
+      pLevel->op = OP_Next;
+      pLevel->p1 = base+idx;
+      pLevel->p2 = start;
+      if( testOp!=OP_Noop ){
+        sqliteVdbeAddOp(v, OP_Recno, base+idx, 0);
+        sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
+        sqliteVdbeAddOp(v, testOp, 0, brk);
+      }
+      haveKey = 0;
+    }else if( pIdx==0 ){
+      /* Case 4:  There is no usable index.  We must do a complete
+      **          scan of the entire database table.
+      */
+      int start;
+
+      brk = pLevel->brk = sqliteVdbeMakeLabel(v);
+      cont = pLevel->cont = sqliteVdbeMakeLabel(v);
+      sqliteVdbeAddOp(v, OP_Rewind, base+idx, brk);
+      start = sqliteVdbeCurrentAddr(v);
+      pLevel->op = OP_Next;
+      pLevel->p1 = base+idx;
+      pLevel->p2 = start;
+      haveKey = 0;
+    }else{
+      /* Case 5: The WHERE clause term that refers to the right-most
+      **         column of the index is an inequality.  For example, if
+      **         the index is on (x,y,z) and the WHERE clause is of the
+      **         form "x=5 AND y<10" then this case is used.  Only the
+      **         right-most column can be an inequality - the rest must
+      **         use the "==" operator.
+      **
+      **         This case is also used when there are no WHERE clause
+      **         constraints but an index is selected anyway, in order
+      **         to force the output order to conform to an ORDER BY.
+      */
+      int score = pLevel->score;
+      int nEqColumn = score/8;
+      int start;
+      int leFlag, geFlag;
+      int testOp;
+
+      /* Evaluate the equality constraints
+      */
+      for(j=0; j<nEqColumn; j++){
+        for(k=0; k<nExpr; k++){
+          if( aExpr[k].p==0 ) continue;
+          if( aExpr[k].idxLeft==idx 
+             && aExpr[k].p->op==TK_EQ
+             && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight 
+             && aExpr[k].p->pLeft->iColumn==pIdx->aiColumn[j]
+          ){
+            sqliteExprCode(pParse, aExpr[k].p->pRight);
+            aExpr[k].p = 0;
+            break;
+          }
+          if( aExpr[k].idxRight==idx 
+             && aExpr[k].p->op==TK_EQ
+             && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
+             && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
+          ){
+            sqliteExprCode(pParse, aExpr[k].p->pLeft);
+            aExpr[k].p = 0;
+            break;
+          }
+        }
+      }
+
+      /* Duplicate the equality term values because they will all be
+      ** used twice: once to make the termination key and once to make the
+      ** start key.
+      */
+      for(j=0; j<nEqColumn; j++){
+        sqliteVdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
+      }
+
+      /* Labels for the beginning and end of the loop
+      */
+      cont = pLevel->cont = sqliteVdbeMakeLabel(v);
+      brk = pLevel->brk = sqliteVdbeMakeLabel(v);
+
+      /* Generate the termination key.  This is the key value that
+      ** will end the search.  There is no termination key if there
+      ** are no equality terms and no "X<..." term.
+      **
+      ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
+      ** key computed here really ends up being the start key.
+      */
+      if( (score & 1)!=0 ){
+        for(k=0; k<nExpr; k++){
+          Expr *pExpr = aExpr[k].p;
+          if( pExpr==0 ) continue;
+          if( aExpr[k].idxLeft==idx 
+             && (pExpr->op==TK_LT || pExpr->op==TK_LE)
+             && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight 
+             && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
+          ){
+            sqliteExprCode(pParse, pExpr->pRight);
+            leFlag = pExpr->op==TK_LE;
+            aExpr[k].p = 0;
+            break;
+          }
+          if( aExpr[k].idxRight==idx 
+             && (pExpr->op==TK_GT || pExpr->op==TK_GE)
+             && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
+             && pExpr->pRight->iColumn==pIdx->aiColumn[j]
+          ){
+            sqliteExprCode(pParse, pExpr->pLeft);
+            leFlag = pExpr->op==TK_GE;
+            aExpr[k].p = 0;
+            break;
+          }
+        }
+        testOp = OP_IdxGE;
+      }else{
+        testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
+        leFlag = 1;
+      }
+      if( testOp!=OP_Noop ){
+        pLevel->iMem = pParse->nMem++;
+        sqliteVdbeAddOp(v, OP_MakeKey, nEqColumn + (score & 1), 0);
+        sqliteAddIdxKeyType(v, pIdx);
+        if( leFlag ){
+          sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
+        }
+        if( pLevel->bRev ){
+          sqliteVdbeAddOp(v, OP_MoveLt, pLevel->iCur, brk);
+        }else{
+          sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
+        }
+      }else if( pLevel->bRev ){
+        sqliteVdbeAddOp(v, OP_Last, pLevel->iCur, brk);
+      }
+
+      /* Generate the start key.  This is the key that defines the lower
+      ** bound on the search.  There is no start key if there are no
+      ** equality terms and if there is no "X>..." term.  In
+      ** that case, generate a "Rewind" instruction in place of the
+      ** start key search.
+      **
+      ** 2002-Dec-04: In the case of a reverse-order search, the so-called
+      ** "start" key really ends up being used as the termination key.
+      */
+      if( (score & 2)!=0 ){
+        for(k=0; k<nExpr; k++){
+          Expr *pExpr = aExpr[k].p;
+          if( pExpr==0 ) continue;
+          if( aExpr[k].idxLeft==idx 
+             && (pExpr->op==TK_GT || pExpr->op==TK_GE)
+             && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight 
+             && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
+          ){
+            sqliteExprCode(pParse, pExpr->pRight);
+            geFlag = pExpr->op==TK_GE;
+            aExpr[k].p = 0;
+            break;
+          }
+          if( aExpr[k].idxRight==idx 
+             && (pExpr->op==TK_LT || pExpr->op==TK_LE)
+             && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
+             && pExpr->pRight->iColumn==pIdx->aiColumn[j]
+          ){
+            sqliteExprCode(pParse, pExpr->pLeft);
+            geFlag = pExpr->op==TK_LE;
+            aExpr[k].p = 0;
+            break;
+          }
+        }
+      }else{
+        geFlag = 1;
+      }
+      if( nEqColumn>0 || (score&2)!=0 ){
+        sqliteVdbeAddOp(v, OP_MakeKey, nEqColumn + ((score&2)!=0), 0);
+        sqliteAddIdxKeyType(v, pIdx);
+        if( !geFlag ){
+          sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
+        }
+        if( pLevel->bRev ){
+          pLevel->iMem = pParse->nMem++;
+          sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
+          testOp = OP_IdxLT;
+        }else{
+          sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
+        }
+      }else if( pLevel->bRev ){
+        testOp = OP_Noop;
+      }else{
+        sqliteVdbeAddOp(v, OP_Rewind, pLevel->iCur, brk);
+      }
+
+      /* Generate the the top of the loop.  If there is a termination
+      ** key we have to test for that key and abort at the top of the
+      ** loop.
+      */
+      start = sqliteVdbeCurrentAddr(v);
+      if( testOp!=OP_Noop ){
+        sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
+        sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
+      }
+      sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
+      if( i==pTabList->nSrc-1 && pushKey ){
+        haveKey = 1;
+      }else{
+        sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
+        haveKey = 0;
+      }
+
+      /* Record the instruction used to terminate the loop.
+      */
+      pLevel->op = pLevel->bRev ? OP_Prev : OP_Next;
+      pLevel->p1 = pLevel->iCur;
+      pLevel->p2 = start;
+    }
+    loopMask |= 1<<idx;
+
+    /* Insert code to test every subexpression that can be completely
+    ** computed using the current set of tables.
+    */
+    for(j=0; j<nExpr; j++){
+      if( aExpr[j].p==0 ) continue;
+      if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
+      if( pLevel->iLeftJoin && !ExprHasProperty(aExpr[j].p,EP_FromJoin) ){
+        continue;
+      }
+      if( haveKey ){
+        haveKey = 0;
+        sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
+      }
+      sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
+      aExpr[j].p = 0;
+    }
+    brk = cont;
+
+    /* For a LEFT OUTER JOIN, generate code that will record the fact that
+    ** at least one row of the right table has matched the left table.  
+    */
+    if( pLevel->iLeftJoin ){
+      pLevel->top = sqliteVdbeCurrentAddr(v);
+      sqliteVdbeAddOp(v, OP_Integer, 1, 0);
+      sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
+      for(j=0; j<nExpr; j++){
+        if( aExpr[j].p==0 ) continue;
+        if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
+        if( haveKey ){
+          /* Cannot happen.  "haveKey" can only be true if pushKey is true
+          ** an pushKey can only be true for DELETE and UPDATE and there are
+          ** no outer joins with DELETE and UPDATE.
+          */
+          haveKey = 0;
+          sqliteVdbeAddOp(v, OP_MoveTo, base+idx, 0);
+        }
+        sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
+        aExpr[j].p = 0;
+      }
+    }
+  }
+  pWInfo->iContinue = cont;
+  if( pushKey && !haveKey ){
+    sqliteVdbeAddOp(v, OP_Recno, base, 0);
+  }
+  return pWInfo;
+}
+
+/*
+** Generate the end of the WHERE loop.  See comments on 
+** sqliteWhereBegin() for additional information.
+*/
+void sqliteWhereEnd(WhereInfo *pWInfo){
+  Vdbe *v = pWInfo->pParse->pVdbe;
+  int i;
+  int base = pWInfo->base;
+  WhereLevel *pLevel;
+  SrcList *pTabList = pWInfo->pTabList;
+
+  for(i=pTabList->nSrc-1; i>=0; i--){
+    pLevel = &pWInfo->a[i];
+    sqliteVdbeResolveLabel(v, pLevel->cont);
+    if( pLevel->op!=OP_Noop ){
+      sqliteVdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
+    }
+    sqliteVdbeResolveLabel(v, pLevel->brk);
+    if( pLevel->inOp!=OP_Noop ){
+      sqliteVdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
+    }
+    if( pLevel->iLeftJoin ){
+      int addr;
+      addr = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
+      sqliteVdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iCur>=0));
+      sqliteVdbeAddOp(v, OP_NullRow, base+i, 0);
+      if( pLevel->iCur>=0 ){
+        sqliteVdbeAddOp(v, OP_NullRow, pLevel->iCur, 0);
+      }
+      sqliteVdbeAddOp(v, OP_Goto, 0, pLevel->top);
+    }
+  }
+  sqliteVdbeResolveLabel(v, pWInfo->iBreak);
+  for(i=0; i<pTabList->nSrc; i++){
+    if( pTabList->a[i].pTab->isTransient ) continue;
+    pLevel = &pWInfo->a[i];
+    sqliteVdbeAddOp(v, OP_Close, base+i, 0);
+    if( pLevel->pIdx!=0 ){
+      sqliteVdbeAddOp(v, OP_Close, pLevel->iCur, 0);
+    }
+  }
+#if 0  /* Never reuse a cursor */
+  if( pWInfo->pParse->nTab==pWInfo->peakNTab ){
+    pWInfo->pParse->nTab = pWInfo->savedNTab;
+  }
+#endif
+  sqliteFree(pWInfo);
+  return;
+}