os/persistentdata/persistentstorage/sql/SQLite364/build.c
changeset 0 bde4ae8d615e
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/os/persistentdata/persistentstorage/sql/SQLite364/build.c	Fri Jun 15 03:10:57 2012 +0200
     1.3 @@ -0,0 +1,3519 @@
     1.4 +/*
     1.5 +** 2001 September 15
     1.6 +**
     1.7 +** The author disclaims copyright to this source code.  In place of
     1.8 +** a legal notice, here is a blessing:
     1.9 +**
    1.10 +**    May you do good and not evil.
    1.11 +**    May you find forgiveness for yourself and forgive others.
    1.12 +**    May you share freely, never taking more than you give.
    1.13 +**
    1.14 +*************************************************************************
    1.15 +** This file contains C code routines that are called by the SQLite parser
    1.16 +** when syntax rules are reduced.  The routines in this file handle the
    1.17 +** following kinds of SQL syntax:
    1.18 +**
    1.19 +**     CREATE TABLE
    1.20 +**     DROP TABLE
    1.21 +**     CREATE INDEX
    1.22 +**     DROP INDEX
    1.23 +**     creating ID lists
    1.24 +**     BEGIN TRANSACTION
    1.25 +**     COMMIT
    1.26 +**     ROLLBACK
    1.27 +**
    1.28 +** $Id: build.c,v 1.498 2008/10/06 16:18:40 danielk1977 Exp $
    1.29 +*/
    1.30 +#include "sqliteInt.h"
    1.31 +#include <ctype.h>
    1.32 +
    1.33 +/*
    1.34 +** This routine is called when a new SQL statement is beginning to
    1.35 +** be parsed.  Initialize the pParse structure as needed.
    1.36 +*/
    1.37 +void sqlite3BeginParse(Parse *pParse, int explainFlag){
    1.38 +  pParse->explain = explainFlag;
    1.39 +  pParse->nVar = 0;
    1.40 +}
    1.41 +
    1.42 +#ifndef SQLITE_OMIT_SHARED_CACHE
    1.43 +/*
    1.44 +** The TableLock structure is only used by the sqlite3TableLock() and
    1.45 +** codeTableLocks() functions.
    1.46 +*/
    1.47 +struct TableLock {
    1.48 +  int iDb;             /* The database containing the table to be locked */
    1.49 +  int iTab;            /* The root page of the table to be locked */
    1.50 +  u8 isWriteLock;      /* True for write lock.  False for a read lock */
    1.51 +  const char *zName;   /* Name of the table */
    1.52 +};
    1.53 +
    1.54 +/*
    1.55 +** Record the fact that we want to lock a table at run-time.  
    1.56 +**
    1.57 +** The table to be locked has root page iTab and is found in database iDb.
    1.58 +** A read or a write lock can be taken depending on isWritelock.
    1.59 +**
    1.60 +** This routine just records the fact that the lock is desired.  The
    1.61 +** code to make the lock occur is generated by a later call to
    1.62 +** codeTableLocks() which occurs during sqlite3FinishCoding().
    1.63 +*/
    1.64 +void sqlite3TableLock(
    1.65 +  Parse *pParse,     /* Parsing context */
    1.66 +  int iDb,           /* Index of the database containing the table to lock */
    1.67 +  int iTab,          /* Root page number of the table to be locked */
    1.68 +  u8 isWriteLock,    /* True for a write lock */
    1.69 +  const char *zName  /* Name of the table to be locked */
    1.70 +){
    1.71 +  int i;
    1.72 +  int nBytes;
    1.73 +  TableLock *p;
    1.74 +
    1.75 +  if( iDb<0 ){
    1.76 +    return;
    1.77 +  }
    1.78 +
    1.79 +  for(i=0; i<pParse->nTableLock; i++){
    1.80 +    p = &pParse->aTableLock[i];
    1.81 +    if( p->iDb==iDb && p->iTab==iTab ){
    1.82 +      p->isWriteLock = (p->isWriteLock || isWriteLock);
    1.83 +      return;
    1.84 +    }
    1.85 +  }
    1.86 +
    1.87 +  nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
    1.88 +  pParse->aTableLock = 
    1.89 +      sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
    1.90 +  if( pParse->aTableLock ){
    1.91 +    p = &pParse->aTableLock[pParse->nTableLock++];
    1.92 +    p->iDb = iDb;
    1.93 +    p->iTab = iTab;
    1.94 +    p->isWriteLock = isWriteLock;
    1.95 +    p->zName = zName;
    1.96 +  }else{
    1.97 +    pParse->nTableLock = 0;
    1.98 +    pParse->db->mallocFailed = 1;
    1.99 +  }
   1.100 +}
   1.101 +
   1.102 +/*
   1.103 +** Code an OP_TableLock instruction for each table locked by the
   1.104 +** statement (configured by calls to sqlite3TableLock()).
   1.105 +*/
   1.106 +static void codeTableLocks(Parse *pParse){
   1.107 +  int i;
   1.108 +  Vdbe *pVdbe; 
   1.109 +
   1.110 +  if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
   1.111 +    return;
   1.112 +  }
   1.113 +
   1.114 +  for(i=0; i<pParse->nTableLock; i++){
   1.115 +    TableLock *p = &pParse->aTableLock[i];
   1.116 +    int p1 = p->iDb;
   1.117 +    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
   1.118 +                      p->zName, P4_STATIC);
   1.119 +  }
   1.120 +}
   1.121 +#else
   1.122 +  #define codeTableLocks(x)
   1.123 +#endif
   1.124 +
   1.125 +/*
   1.126 +** This routine is called after a single SQL statement has been
   1.127 +** parsed and a VDBE program to execute that statement has been
   1.128 +** prepared.  This routine puts the finishing touches on the
   1.129 +** VDBE program and resets the pParse structure for the next
   1.130 +** parse.
   1.131 +**
   1.132 +** Note that if an error occurred, it might be the case that
   1.133 +** no VDBE code was generated.
   1.134 +*/
   1.135 +void sqlite3FinishCoding(Parse *pParse){
   1.136 +  sqlite3 *db;
   1.137 +  Vdbe *v;
   1.138 +
   1.139 +  db = pParse->db;
   1.140 +  if( db->mallocFailed ) return;
   1.141 +  if( pParse->nested ) return;
   1.142 +  if( pParse->nErr ) return;
   1.143 +
   1.144 +  /* Begin by generating some termination code at the end of the
   1.145 +  ** vdbe program
   1.146 +  */
   1.147 +  v = sqlite3GetVdbe(pParse);
   1.148 +  if( v ){
   1.149 +    sqlite3VdbeAddOp0(v, OP_Halt);
   1.150 +
   1.151 +    /* The cookie mask contains one bit for each database file open.
   1.152 +    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
   1.153 +    ** set for each database that is used.  Generate code to start a
   1.154 +    ** transaction on each used database and to verify the schema cookie
   1.155 +    ** on each used database.
   1.156 +    */
   1.157 +    if( pParse->cookieGoto>0 ){
   1.158 +      u32 mask;
   1.159 +      int iDb;
   1.160 +      sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
   1.161 +      for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
   1.162 +        if( (mask & pParse->cookieMask)==0 ) continue;
   1.163 +        sqlite3VdbeUsesBtree(v, iDb);
   1.164 +        sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
   1.165 +        sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
   1.166 +      }
   1.167 +#ifndef SQLITE_OMIT_VIRTUALTABLE
   1.168 +      {
   1.169 +        int i;
   1.170 +        for(i=0; i<pParse->nVtabLock; i++){
   1.171 +          char *vtab = (char *)pParse->apVtabLock[i]->pVtab;
   1.172 +          sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
   1.173 +        }
   1.174 +        pParse->nVtabLock = 0;
   1.175 +      }
   1.176 +#endif
   1.177 +
   1.178 +      /* Once all the cookies have been verified and transactions opened, 
   1.179 +      ** obtain the required table-locks. This is a no-op unless the 
   1.180 +      ** shared-cache feature is enabled.
   1.181 +      */
   1.182 +      codeTableLocks(pParse);
   1.183 +      sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
   1.184 +    }
   1.185 +
   1.186 +#ifndef SQLITE_OMIT_TRACE
   1.187 +    if( !db->init.busy ){
   1.188 +      /* Change the P4 argument of the first opcode (which will always be
   1.189 +      ** an OP_Trace) to be the complete text of the current SQL statement.
   1.190 +      */
   1.191 +      VdbeOp *pOp = sqlite3VdbeGetOp(v, 0);
   1.192 +      if( pOp && pOp->opcode==OP_Trace ){
   1.193 +        sqlite3VdbeChangeP4(v, 0, pParse->zSql, pParse->zTail-pParse->zSql);
   1.194 +      }
   1.195 +    }
   1.196 +#endif /* SQLITE_OMIT_TRACE */
   1.197 +  }
   1.198 +
   1.199 +
   1.200 +  /* Get the VDBE program ready for execution
   1.201 +  */
   1.202 +  if( v && pParse->nErr==0 && !db->mallocFailed ){
   1.203 +#ifdef SQLITE_DEBUG
   1.204 +    FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
   1.205 +    sqlite3VdbeTrace(v, trace);
   1.206 +#endif
   1.207 +    assert( pParse->disableColCache==0 );  /* Disables and re-enables match */
   1.208 +    sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
   1.209 +                         pParse->nTab+3, pParse->explain);
   1.210 +    pParse->rc = SQLITE_DONE;
   1.211 +    pParse->colNamesSet = 0;
   1.212 +  }else if( pParse->rc==SQLITE_OK ){
   1.213 +    pParse->rc = SQLITE_ERROR;
   1.214 +  }
   1.215 +  pParse->nTab = 0;
   1.216 +  pParse->nMem = 0;
   1.217 +  pParse->nSet = 0;
   1.218 +  pParse->nVar = 0;
   1.219 +  pParse->cookieMask = 0;
   1.220 +  pParse->cookieGoto = 0;
   1.221 +}
   1.222 +
   1.223 +/*
   1.224 +** Run the parser and code generator recursively in order to generate
   1.225 +** code for the SQL statement given onto the end of the pParse context
   1.226 +** currently under construction.  When the parser is run recursively
   1.227 +** this way, the final OP_Halt is not appended and other initialization
   1.228 +** and finalization steps are omitted because those are handling by the
   1.229 +** outermost parser.
   1.230 +**
   1.231 +** Not everything is nestable.  This facility is designed to permit
   1.232 +** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
   1.233 +** care if you decide to try to use this routine for some other purposes.
   1.234 +*/
   1.235 +void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
   1.236 +  va_list ap;
   1.237 +  char *zSql;
   1.238 +  char *zErrMsg = 0;
   1.239 +  sqlite3 *db = pParse->db;
   1.240 +# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
   1.241 +  char saveBuf[SAVE_SZ];
   1.242 +
   1.243 +  if( pParse->nErr ) return;
   1.244 +  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
   1.245 +  va_start(ap, zFormat);
   1.246 +  zSql = sqlite3VMPrintf(db, zFormat, ap);
   1.247 +  va_end(ap);
   1.248 +  if( zSql==0 ){
   1.249 +    return;   /* A malloc must have failed */
   1.250 +  }
   1.251 +  pParse->nested++;
   1.252 +  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
   1.253 +  memset(&pParse->nVar, 0, SAVE_SZ);
   1.254 +  sqlite3RunParser(pParse, zSql, &zErrMsg);
   1.255 +  sqlite3DbFree(db, zErrMsg);
   1.256 +  sqlite3DbFree(db, zSql);
   1.257 +  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
   1.258 +  pParse->nested--;
   1.259 +}
   1.260 +
   1.261 +/*
   1.262 +** Locate the in-memory structure that describes a particular database
   1.263 +** table given the name of that table and (optionally) the name of the
   1.264 +** database containing the table.  Return NULL if not found.
   1.265 +**
   1.266 +** If zDatabase is 0, all databases are searched for the table and the
   1.267 +** first matching table is returned.  (No checking for duplicate table
   1.268 +** names is done.)  The search order is TEMP first, then MAIN, then any
   1.269 +** auxiliary databases added using the ATTACH command.
   1.270 +**
   1.271 +** See also sqlite3LocateTable().
   1.272 +*/
   1.273 +Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
   1.274 +  Table *p = 0;
   1.275 +  int i;
   1.276 +  int nName;
   1.277 +  assert( zName!=0 );
   1.278 +  nName = sqlite3Strlen(db, zName) + 1;
   1.279 +  for(i=OMIT_TEMPDB; i<db->nDb; i++){
   1.280 +    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
   1.281 +    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
   1.282 +    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
   1.283 +    if( p ) break;
   1.284 +  }
   1.285 +  return p;
   1.286 +}
   1.287 +
   1.288 +/*
   1.289 +** Locate the in-memory structure that describes a particular database
   1.290 +** table given the name of that table and (optionally) the name of the
   1.291 +** database containing the table.  Return NULL if not found.  Also leave an
   1.292 +** error message in pParse->zErrMsg.
   1.293 +**
   1.294 +** The difference between this routine and sqlite3FindTable() is that this
   1.295 +** routine leaves an error message in pParse->zErrMsg where
   1.296 +** sqlite3FindTable() does not.
   1.297 +*/
   1.298 +Table *sqlite3LocateTable(
   1.299 +  Parse *pParse,         /* context in which to report errors */
   1.300 +  int isView,            /* True if looking for a VIEW rather than a TABLE */
   1.301 +  const char *zName,     /* Name of the table we are looking for */
   1.302 +  const char *zDbase     /* Name of the database.  Might be NULL */
   1.303 +){
   1.304 +  Table *p;
   1.305 +
   1.306 +  /* Read the database schema. If an error occurs, leave an error message
   1.307 +  ** and code in pParse and return NULL. */
   1.308 +  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   1.309 +    return 0;
   1.310 +  }
   1.311 +
   1.312 +  p = sqlite3FindTable(pParse->db, zName, zDbase);
   1.313 +  if( p==0 ){
   1.314 +    const char *zMsg = isView ? "no such view" : "no such table";
   1.315 +    if( zDbase ){
   1.316 +      sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
   1.317 +    }else{
   1.318 +      sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
   1.319 +    }
   1.320 +    pParse->checkSchema = 1;
   1.321 +  }
   1.322 +  return p;
   1.323 +}
   1.324 +
   1.325 +/*
   1.326 +** Locate the in-memory structure that describes 
   1.327 +** a particular index given the name of that index
   1.328 +** and the name of the database that contains the index.
   1.329 +** Return NULL if not found.
   1.330 +**
   1.331 +** If zDatabase is 0, all databases are searched for the
   1.332 +** table and the first matching index is returned.  (No checking
   1.333 +** for duplicate index names is done.)  The search order is
   1.334 +** TEMP first, then MAIN, then any auxiliary databases added
   1.335 +** using the ATTACH command.
   1.336 +*/
   1.337 +Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
   1.338 +  Index *p = 0;
   1.339 +  int i;
   1.340 +  int nName = sqlite3Strlen(db, zName)+1;
   1.341 +  for(i=OMIT_TEMPDB; i<db->nDb; i++){
   1.342 +    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
   1.343 +    Schema *pSchema = db->aDb[j].pSchema;
   1.344 +    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
   1.345 +    assert( pSchema || (j==1 && !db->aDb[1].pBt) );
   1.346 +    if( pSchema ){
   1.347 +      p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
   1.348 +    }
   1.349 +    if( p ) break;
   1.350 +  }
   1.351 +  return p;
   1.352 +}
   1.353 +
   1.354 +/*
   1.355 +** Reclaim the memory used by an index
   1.356 +*/
   1.357 +static void freeIndex(Index *p){
   1.358 +  sqlite3 *db = p->pTable->db;
   1.359 +  sqlite3DbFree(db, p->zColAff);
   1.360 +  sqlite3DbFree(db, p);
   1.361 +}
   1.362 +
   1.363 +/*
   1.364 +** Remove the given index from the index hash table, and free
   1.365 +** its memory structures.
   1.366 +**
   1.367 +** The index is removed from the database hash tables but
   1.368 +** it is not unlinked from the Table that it indexes.
   1.369 +** Unlinking from the Table must be done by the calling function.
   1.370 +*/
   1.371 +static void sqliteDeleteIndex(Index *p){
   1.372 +  Index *pOld;
   1.373 +  const char *zName = p->zName;
   1.374 +
   1.375 +  pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen(zName)+1, 0);
   1.376 +  assert( pOld==0 || pOld==p );
   1.377 +  freeIndex(p);
   1.378 +}
   1.379 +
   1.380 +/*
   1.381 +** For the index called zIdxName which is found in the database iDb,
   1.382 +** unlike that index from its Table then remove the index from
   1.383 +** the index hash table and free all memory structures associated
   1.384 +** with the index.
   1.385 +*/
   1.386 +void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
   1.387 +  Index *pIndex;
   1.388 +  int len;
   1.389 +  Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
   1.390 +
   1.391 +  len = sqlite3Strlen(db, zIdxName);
   1.392 +  pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
   1.393 +  if( pIndex ){
   1.394 +    if( pIndex->pTable->pIndex==pIndex ){
   1.395 +      pIndex->pTable->pIndex = pIndex->pNext;
   1.396 +    }else{
   1.397 +      Index *p;
   1.398 +      for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
   1.399 +      if( p && p->pNext==pIndex ){
   1.400 +        p->pNext = pIndex->pNext;
   1.401 +      }
   1.402 +    }
   1.403 +    freeIndex(pIndex);
   1.404 +  }
   1.405 +  db->flags |= SQLITE_InternChanges;
   1.406 +}
   1.407 +
   1.408 +/*
   1.409 +** Erase all schema information from the in-memory hash tables of
   1.410 +** a single database.  This routine is called to reclaim memory
   1.411 +** before the database closes.  It is also called during a rollback
   1.412 +** if there were schema changes during the transaction or if a
   1.413 +** schema-cookie mismatch occurs.
   1.414 +**
   1.415 +** If iDb<=0 then reset the internal schema tables for all database
   1.416 +** files.  If iDb>=2 then reset the internal schema for only the
   1.417 +** single file indicated.
   1.418 +*/
   1.419 +void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
   1.420 +  int i, j;
   1.421 +  assert( iDb>=0 && iDb<db->nDb );
   1.422 +
   1.423 +  if( iDb==0 ){
   1.424 +    sqlite3BtreeEnterAll(db);
   1.425 +  }
   1.426 +  for(i=iDb; i<db->nDb; i++){
   1.427 +    Db *pDb = &db->aDb[i];
   1.428 +    if( pDb->pSchema ){
   1.429 +      assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
   1.430 +      sqlite3SchemaFree(pDb->pSchema);
   1.431 +    }
   1.432 +    if( iDb>0 ) return;
   1.433 +  }
   1.434 +  assert( iDb==0 );
   1.435 +  db->flags &= ~SQLITE_InternChanges;
   1.436 +  sqlite3BtreeLeaveAll(db);
   1.437 +
   1.438 +  /* If one or more of the auxiliary database files has been closed,
   1.439 +  ** then remove them from the auxiliary database list.  We take the
   1.440 +  ** opportunity to do this here since we have just deleted all of the
   1.441 +  ** schema hash tables and therefore do not have to make any changes
   1.442 +  ** to any of those tables.
   1.443 +  */
   1.444 +  for(i=0; i<db->nDb; i++){
   1.445 +    struct Db *pDb = &db->aDb[i];
   1.446 +    if( pDb->pBt==0 ){
   1.447 +      if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
   1.448 +      pDb->pAux = 0;
   1.449 +    }
   1.450 +  }
   1.451 +  for(i=j=2; i<db->nDb; i++){
   1.452 +    struct Db *pDb = &db->aDb[i];
   1.453 +    if( pDb->pBt==0 ){
   1.454 +      sqlite3DbFree(db, pDb->zName);
   1.455 +      pDb->zName = 0;
   1.456 +      continue;
   1.457 +    }
   1.458 +    if( j<i ){
   1.459 +      db->aDb[j] = db->aDb[i];
   1.460 +    }
   1.461 +    j++;
   1.462 +  }
   1.463 +  memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
   1.464 +  db->nDb = j;
   1.465 +  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
   1.466 +    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
   1.467 +    sqlite3DbFree(db, db->aDb);
   1.468 +    db->aDb = db->aDbStatic;
   1.469 +  }
   1.470 +}
   1.471 +
   1.472 +/*
   1.473 +** This routine is called when a commit occurs.
   1.474 +*/
   1.475 +void sqlite3CommitInternalChanges(sqlite3 *db){
   1.476 +  db->flags &= ~SQLITE_InternChanges;
   1.477 +}
   1.478 +
   1.479 +/*
   1.480 +** Clear the column names from a table or view.
   1.481 +*/
   1.482 +static void sqliteResetColumnNames(Table *pTable){
   1.483 +  int i;
   1.484 +  Column *pCol;
   1.485 +  sqlite3 *db = pTable->db;
   1.486 +  assert( pTable!=0 );
   1.487 +  if( (pCol = pTable->aCol)!=0 ){
   1.488 +    for(i=0; i<pTable->nCol; i++, pCol++){
   1.489 +      sqlite3DbFree(db, pCol->zName);
   1.490 +      sqlite3ExprDelete(db, pCol->pDflt);
   1.491 +      sqlite3DbFree(db, pCol->zType);
   1.492 +      sqlite3DbFree(db, pCol->zColl);
   1.493 +    }
   1.494 +    sqlite3DbFree(db, pTable->aCol);
   1.495 +  }
   1.496 +  pTable->aCol = 0;
   1.497 +  pTable->nCol = 0;
   1.498 +}
   1.499 +
   1.500 +/*
   1.501 +** Remove the memory data structures associated with the given
   1.502 +** Table.  No changes are made to disk by this routine.
   1.503 +**
   1.504 +** This routine just deletes the data structure.  It does not unlink
   1.505 +** the table data structure from the hash table.  Nor does it remove
   1.506 +** foreign keys from the sqlite.aFKey hash table.  But it does destroy
   1.507 +** memory structures of the indices and foreign keys associated with 
   1.508 +** the table.
   1.509 +*/
   1.510 +void sqlite3DeleteTable(Table *pTable){
   1.511 +  Index *pIndex, *pNext;
   1.512 +  FKey *pFKey, *pNextFKey;
   1.513 +  sqlite3 *db;
   1.514 +
   1.515 +  if( pTable==0 ) return;
   1.516 +  db = pTable->db;
   1.517 +
   1.518 +  /* Do not delete the table until the reference count reaches zero. */
   1.519 +  pTable->nRef--;
   1.520 +  if( pTable->nRef>0 ){
   1.521 +    return;
   1.522 +  }
   1.523 +  assert( pTable->nRef==0 );
   1.524 +
   1.525 +  /* Delete all indices associated with this table
   1.526 +  */
   1.527 +  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
   1.528 +    pNext = pIndex->pNext;
   1.529 +    assert( pIndex->pSchema==pTable->pSchema );
   1.530 +    sqliteDeleteIndex(pIndex);
   1.531 +  }
   1.532 +
   1.533 +#ifndef SQLITE_OMIT_FOREIGN_KEY
   1.534 +  /* Delete all foreign keys associated with this table.  The keys
   1.535 +  ** should have already been unlinked from the pSchema->aFKey hash table 
   1.536 +  */
   1.537 +  for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
   1.538 +    pNextFKey = pFKey->pNextFrom;
   1.539 +    assert( sqlite3HashFind(&pTable->pSchema->aFKey,
   1.540 +                           pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
   1.541 +    sqlite3DbFree(db, pFKey);
   1.542 +  }
   1.543 +#endif
   1.544 +
   1.545 +  /* Delete the Table structure itself.
   1.546 +  */
   1.547 +  sqliteResetColumnNames(pTable);
   1.548 +  sqlite3DbFree(db, pTable->zName);
   1.549 +  sqlite3DbFree(db, pTable->zColAff);
   1.550 +  sqlite3SelectDelete(db, pTable->pSelect);
   1.551 +#ifndef SQLITE_OMIT_CHECK
   1.552 +  sqlite3ExprDelete(db, pTable->pCheck);
   1.553 +#endif
   1.554 +  sqlite3VtabClear(pTable);
   1.555 +  sqlite3DbFree(db, pTable);
   1.556 +}
   1.557 +
   1.558 +/*
   1.559 +** Unlink the given table from the hash tables and the delete the
   1.560 +** table structure with all its indices and foreign keys.
   1.561 +*/
   1.562 +void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
   1.563 +  Table *p;
   1.564 +  FKey *pF1, *pF2;
   1.565 +  Db *pDb;
   1.566 +
   1.567 +  assert( db!=0 );
   1.568 +  assert( iDb>=0 && iDb<db->nDb );
   1.569 +  assert( zTabName && zTabName[0] );
   1.570 +  pDb = &db->aDb[iDb];
   1.571 +  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
   1.572 +  if( p ){
   1.573 +#ifndef SQLITE_OMIT_FOREIGN_KEY
   1.574 +    for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
   1.575 +      int nTo = strlen(pF1->zTo) + 1;
   1.576 +      pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
   1.577 +      if( pF2==pF1 ){
   1.578 +        sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
   1.579 +      }else{
   1.580 +        while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
   1.581 +        if( pF2 ){
   1.582 +          pF2->pNextTo = pF1->pNextTo;
   1.583 +        }
   1.584 +      }
   1.585 +    }
   1.586 +#endif
   1.587 +    sqlite3DeleteTable(p);
   1.588 +  }
   1.589 +  db->flags |= SQLITE_InternChanges;
   1.590 +}
   1.591 +
   1.592 +/*
   1.593 +** Given a token, return a string that consists of the text of that
   1.594 +** token with any quotations removed.  Space to hold the returned string
   1.595 +** is obtained from sqliteMalloc() and must be freed by the calling
   1.596 +** function.
   1.597 +**
   1.598 +** Tokens are often just pointers into the original SQL text and so
   1.599 +** are not \000 terminated and are not persistent.  The returned string
   1.600 +** is \000 terminated and is persistent.
   1.601 +*/
   1.602 +char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
   1.603 +  char *zName;
   1.604 +  if( pName ){
   1.605 +    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
   1.606 +    sqlite3Dequote(zName);
   1.607 +  }else{
   1.608 +    zName = 0;
   1.609 +  }
   1.610 +  return zName;
   1.611 +}
   1.612 +
   1.613 +/*
   1.614 +** Open the sqlite_master table stored in database number iDb for
   1.615 +** writing. The table is opened using cursor 0.
   1.616 +*/
   1.617 +void sqlite3OpenMasterTable(Parse *p, int iDb){
   1.618 +  Vdbe *v = sqlite3GetVdbe(p);
   1.619 +  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
   1.620 +  sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 5);/* sqlite_master has 5 columns */
   1.621 +  sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
   1.622 +}
   1.623 +
   1.624 +/*
   1.625 +** The token *pName contains the name of a database (either "main" or
   1.626 +** "temp" or the name of an attached db). This routine returns the
   1.627 +** index of the named database in db->aDb[], or -1 if the named db 
   1.628 +** does not exist.
   1.629 +*/
   1.630 +int sqlite3FindDb(sqlite3 *db, Token *pName){
   1.631 +  int i = -1;    /* Database number */
   1.632 +  int n;         /* Number of characters in the name */
   1.633 +  Db *pDb;       /* A database whose name space is being searched */
   1.634 +  char *zName;   /* Name we are searching for */
   1.635 +
   1.636 +  zName = sqlite3NameFromToken(db, pName);
   1.637 +  if( zName ){
   1.638 +    n = strlen(zName);
   1.639 +    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
   1.640 +      if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) && 
   1.641 +          0==sqlite3StrICmp(pDb->zName, zName) ){
   1.642 +        break;
   1.643 +      }
   1.644 +    }
   1.645 +    sqlite3DbFree(db, zName);
   1.646 +  }
   1.647 +  return i;
   1.648 +}
   1.649 +
   1.650 +/* The table or view or trigger name is passed to this routine via tokens
   1.651 +** pName1 and pName2. If the table name was fully qualified, for example:
   1.652 +**
   1.653 +** CREATE TABLE xxx.yyy (...);
   1.654 +** 
   1.655 +** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
   1.656 +** the table name is not fully qualified, i.e.:
   1.657 +**
   1.658 +** CREATE TABLE yyy(...);
   1.659 +**
   1.660 +** Then pName1 is set to "yyy" and pName2 is "".
   1.661 +**
   1.662 +** This routine sets the *ppUnqual pointer to point at the token (pName1 or
   1.663 +** pName2) that stores the unqualified table name.  The index of the
   1.664 +** database "xxx" is returned.
   1.665 +*/
   1.666 +int sqlite3TwoPartName(
   1.667 +  Parse *pParse,      /* Parsing and code generating context */
   1.668 +  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
   1.669 +  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
   1.670 +  Token **pUnqual     /* Write the unqualified object name here */
   1.671 +){
   1.672 +  int iDb;                    /* Database holding the object */
   1.673 +  sqlite3 *db = pParse->db;
   1.674 +
   1.675 +  if( pName2 && pName2->n>0 ){
   1.676 +    if( db->init.busy ) {
   1.677 +      sqlite3ErrorMsg(pParse, "corrupt database");
   1.678 +      pParse->nErr++;
   1.679 +      return -1;
   1.680 +    }
   1.681 +    *pUnqual = pName2;
   1.682 +    iDb = sqlite3FindDb(db, pName1);
   1.683 +    if( iDb<0 ){
   1.684 +      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
   1.685 +      pParse->nErr++;
   1.686 +      return -1;
   1.687 +    }
   1.688 +  }else{
   1.689 +    assert( db->init.iDb==0 || db->init.busy );
   1.690 +    iDb = db->init.iDb;
   1.691 +    *pUnqual = pName1;
   1.692 +  }
   1.693 +  return iDb;
   1.694 +}
   1.695 +
   1.696 +/*
   1.697 +** This routine is used to check if the UTF-8 string zName is a legal
   1.698 +** unqualified name for a new schema object (table, index, view or
   1.699 +** trigger). All names are legal except those that begin with the string
   1.700 +** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
   1.701 +** is reserved for internal use.
   1.702 +*/
   1.703 +int sqlite3CheckObjectName(Parse *pParse, const char *zName){
   1.704 +  if( !pParse->db->init.busy && pParse->nested==0 
   1.705 +          && (pParse->db->flags & SQLITE_WriteSchema)==0
   1.706 +          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
   1.707 +    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
   1.708 +    return SQLITE_ERROR;
   1.709 +  }
   1.710 +  return SQLITE_OK;
   1.711 +}
   1.712 +
   1.713 +/*
   1.714 +** Begin constructing a new table representation in memory.  This is
   1.715 +** the first of several action routines that get called in response
   1.716 +** to a CREATE TABLE statement.  In particular, this routine is called
   1.717 +** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
   1.718 +** flag is true if the table should be stored in the auxiliary database
   1.719 +** file instead of in the main database file.  This is normally the case
   1.720 +** when the "TEMP" or "TEMPORARY" keyword occurs in between
   1.721 +** CREATE and TABLE.
   1.722 +**
   1.723 +** The new table record is initialized and put in pParse->pNewTable.
   1.724 +** As more of the CREATE TABLE statement is parsed, additional action
   1.725 +** routines will be called to add more information to this record.
   1.726 +** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
   1.727 +** is called to complete the construction of the new table record.
   1.728 +*/
   1.729 +void sqlite3StartTable(
   1.730 +  Parse *pParse,   /* Parser context */
   1.731 +  Token *pName1,   /* First part of the name of the table or view */
   1.732 +  Token *pName2,   /* Second part of the name of the table or view */
   1.733 +  int isTemp,      /* True if this is a TEMP table */
   1.734 +  int isView,      /* True if this is a VIEW */
   1.735 +  int isVirtual,   /* True if this is a VIRTUAL table */
   1.736 +  int noErr        /* Do nothing if table already exists */
   1.737 +){
   1.738 +  Table *pTable;
   1.739 +  char *zName = 0; /* The name of the new table */
   1.740 +  sqlite3 *db = pParse->db;
   1.741 +  Vdbe *v;
   1.742 +  int iDb;         /* Database number to create the table in */
   1.743 +  Token *pName;    /* Unqualified name of the table to create */
   1.744 +
   1.745 +  /* The table or view name to create is passed to this routine via tokens
   1.746 +  ** pName1 and pName2. If the table name was fully qualified, for example:
   1.747 +  **
   1.748 +  ** CREATE TABLE xxx.yyy (...);
   1.749 +  ** 
   1.750 +  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
   1.751 +  ** the table name is not fully qualified, i.e.:
   1.752 +  **
   1.753 +  ** CREATE TABLE yyy(...);
   1.754 +  **
   1.755 +  ** Then pName1 is set to "yyy" and pName2 is "".
   1.756 +  **
   1.757 +  ** The call below sets the pName pointer to point at the token (pName1 or
   1.758 +  ** pName2) that stores the unqualified table name. The variable iDb is
   1.759 +  ** set to the index of the database that the table or view is to be
   1.760 +  ** created in.
   1.761 +  */
   1.762 +  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   1.763 +  if( iDb<0 ) return;
   1.764 +  if( !OMIT_TEMPDB && isTemp && iDb>1 ){
   1.765 +    /* If creating a temp table, the name may not be qualified */
   1.766 +    sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
   1.767 +    return;
   1.768 +  }
   1.769 +  if( !OMIT_TEMPDB && isTemp ) iDb = 1;
   1.770 +
   1.771 +  pParse->sNameToken = *pName;
   1.772 +  zName = sqlite3NameFromToken(db, pName);
   1.773 +  if( zName==0 ) return;
   1.774 +  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   1.775 +    goto begin_table_error;
   1.776 +  }
   1.777 +  if( db->init.iDb==1 ) isTemp = 1;
   1.778 +#ifndef SQLITE_OMIT_AUTHORIZATION
   1.779 +  assert( (isTemp & 1)==isTemp );
   1.780 +  {
   1.781 +    int code;
   1.782 +    char *zDb = db->aDb[iDb].zName;
   1.783 +    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
   1.784 +      goto begin_table_error;
   1.785 +    }
   1.786 +    if( isView ){
   1.787 +      if( !OMIT_TEMPDB && isTemp ){
   1.788 +        code = SQLITE_CREATE_TEMP_VIEW;
   1.789 +      }else{
   1.790 +        code = SQLITE_CREATE_VIEW;
   1.791 +      }
   1.792 +    }else{
   1.793 +      if( !OMIT_TEMPDB && isTemp ){
   1.794 +        code = SQLITE_CREATE_TEMP_TABLE;
   1.795 +      }else{
   1.796 +        code = SQLITE_CREATE_TABLE;
   1.797 +      }
   1.798 +    }
   1.799 +    if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
   1.800 +      goto begin_table_error;
   1.801 +    }
   1.802 +  }
   1.803 +#endif
   1.804 +
   1.805 +  /* Make sure the new table name does not collide with an existing
   1.806 +  ** index or table name in the same database.  Issue an error message if
   1.807 +  ** it does. The exception is if the statement being parsed was passed
   1.808 +  ** to an sqlite3_declare_vtab() call. In that case only the column names
   1.809 +  ** and types will be used, so there is no need to test for namespace
   1.810 +  ** collisions.
   1.811 +  */
   1.812 +  if( !IN_DECLARE_VTAB ){
   1.813 +    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   1.814 +      goto begin_table_error;
   1.815 +    }
   1.816 +    pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
   1.817 +    if( pTable ){
   1.818 +      if( !noErr ){
   1.819 +        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
   1.820 +      }
   1.821 +      goto begin_table_error;
   1.822 +    }
   1.823 +    if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
   1.824 +      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
   1.825 +      goto begin_table_error;
   1.826 +    }
   1.827 +  }
   1.828 +
   1.829 +  pTable = sqlite3DbMallocZero(db, sizeof(Table));
   1.830 +  if( pTable==0 ){
   1.831 +    db->mallocFailed = 1;
   1.832 +    pParse->rc = SQLITE_NOMEM;
   1.833 +    pParse->nErr++;
   1.834 +    goto begin_table_error;
   1.835 +  }
   1.836 +  pTable->zName = zName;
   1.837 +  pTable->iPKey = -1;
   1.838 +  pTable->pSchema = db->aDb[iDb].pSchema;
   1.839 +  pTable->nRef = 1;
   1.840 +  pTable->db = db;
   1.841 +  if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable);
   1.842 +  pParse->pNewTable = pTable;
   1.843 +
   1.844 +  /* If this is the magic sqlite_sequence table used by autoincrement,
   1.845 +  ** then record a pointer to this table in the main database structure
   1.846 +  ** so that INSERT can find the table easily.
   1.847 +  */
   1.848 +#ifndef SQLITE_OMIT_AUTOINCREMENT
   1.849 +  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
   1.850 +    pTable->pSchema->pSeqTab = pTable;
   1.851 +  }
   1.852 +#endif
   1.853 +
   1.854 +  /* Begin generating the code that will insert the table record into
   1.855 +  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
   1.856 +  ** and allocate the record number for the table entry now.  Before any
   1.857 +  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
   1.858 +  ** indices to be created and the table record must come before the 
   1.859 +  ** indices.  Hence, the record number for the table must be allocated
   1.860 +  ** now.
   1.861 +  */
   1.862 +  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
   1.863 +    int j1;
   1.864 +    int fileFormat;
   1.865 +    int reg1, reg2, reg3;
   1.866 +    sqlite3BeginWriteOperation(pParse, 0, iDb);
   1.867 +
   1.868 +#ifndef SQLITE_OMIT_VIRTUALTABLE
   1.869 +    if( isVirtual ){
   1.870 +      sqlite3VdbeAddOp0(v, OP_VBegin);
   1.871 +    }
   1.872 +#endif
   1.873 +
   1.874 +    /* If the file format and encoding in the database have not been set, 
   1.875 +    ** set them now.
   1.876 +    */
   1.877 +    reg1 = pParse->regRowid = ++pParse->nMem;
   1.878 +    reg2 = pParse->regRoot = ++pParse->nMem;
   1.879 +    reg3 = ++pParse->nMem;
   1.880 +    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, 1);   /* file_format */
   1.881 +    sqlite3VdbeUsesBtree(v, iDb);
   1.882 +    j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
   1.883 +    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
   1.884 +                  1 : SQLITE_MAX_FILE_FORMAT;
   1.885 +    sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
   1.886 +    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, reg3);
   1.887 +    sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
   1.888 +    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 4, reg3);
   1.889 +    sqlite3VdbeJumpHere(v, j1);
   1.890 +
   1.891 +    /* This just creates a place-holder record in the sqlite_master table.
   1.892 +    ** The record created does not contain anything yet.  It will be replaced
   1.893 +    ** by the real entry in code generated at sqlite3EndTable().
   1.894 +    **
   1.895 +    ** The rowid for the new entry is left on the top of the stack.
   1.896 +    ** The rowid value is needed by the code that sqlite3EndTable will
   1.897 +    ** generate.
   1.898 +    */
   1.899 +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   1.900 +    if( isView || isVirtual ){
   1.901 +      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
   1.902 +    }else
   1.903 +#endif
   1.904 +    {
   1.905 +      sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
   1.906 +    }
   1.907 +    sqlite3OpenMasterTable(pParse, iDb);
   1.908 +    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
   1.909 +    sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
   1.910 +    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
   1.911 +    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   1.912 +    sqlite3VdbeAddOp0(v, OP_Close);
   1.913 +  }
   1.914 +
   1.915 +  /* Normal (non-error) return. */
   1.916 +  return;
   1.917 +
   1.918 +  /* If an error occurs, we jump here */
   1.919 +begin_table_error:
   1.920 +  sqlite3DbFree(db, zName);
   1.921 +  return;
   1.922 +}
   1.923 +
   1.924 +/*
   1.925 +** This macro is used to compare two strings in a case-insensitive manner.
   1.926 +** It is slightly faster than calling sqlite3StrICmp() directly, but
   1.927 +** produces larger code.
   1.928 +**
   1.929 +** WARNING: This macro is not compatible with the strcmp() family. It
   1.930 +** returns true if the two strings are equal, otherwise false.
   1.931 +*/
   1.932 +#define STRICMP(x, y) (\
   1.933 +sqlite3UpperToLower[*(unsigned char *)(x)]==   \
   1.934 +sqlite3UpperToLower[*(unsigned char *)(y)]     \
   1.935 +&& sqlite3StrICmp((x)+1,(y)+1)==0 )
   1.936 +
   1.937 +/*
   1.938 +** Add a new column to the table currently being constructed.
   1.939 +**
   1.940 +** The parser calls this routine once for each column declaration
   1.941 +** in a CREATE TABLE statement.  sqlite3StartTable() gets called
   1.942 +** first to get things going.  Then this routine is called for each
   1.943 +** column.
   1.944 +*/
   1.945 +void sqlite3AddColumn(Parse *pParse, Token *pName){
   1.946 +  Table *p;
   1.947 +  int i;
   1.948 +  char *z;
   1.949 +  Column *pCol;
   1.950 +  sqlite3 *db = pParse->db;
   1.951 +  if( (p = pParse->pNewTable)==0 ) return;
   1.952 +#if SQLITE_MAX_COLUMN
   1.953 +  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   1.954 +    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
   1.955 +    return;
   1.956 +  }
   1.957 +#endif
   1.958 +  z = sqlite3NameFromToken(pParse->db, pName);
   1.959 +  if( z==0 ) return;
   1.960 +  for(i=0; i<p->nCol; i++){
   1.961 +    if( STRICMP(z, p->aCol[i].zName) ){
   1.962 +      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
   1.963 +      sqlite3DbFree(db, z);
   1.964 +      return;
   1.965 +    }
   1.966 +  }
   1.967 +  if( (p->nCol & 0x7)==0 ){
   1.968 +    Column *aNew;
   1.969 +    aNew = sqlite3DbRealloc(pParse->db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
   1.970 +    if( aNew==0 ){
   1.971 +      sqlite3DbFree(db, z);
   1.972 +      return;
   1.973 +    }
   1.974 +    p->aCol = aNew;
   1.975 +  }
   1.976 +  pCol = &p->aCol[p->nCol];
   1.977 +  memset(pCol, 0, sizeof(p->aCol[0]));
   1.978 +  pCol->zName = z;
   1.979 + 
   1.980 +  /* If there is no type specified, columns have the default affinity
   1.981 +  ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
   1.982 +  ** be called next to set pCol->affinity correctly.
   1.983 +  */
   1.984 +  pCol->affinity = SQLITE_AFF_NONE;
   1.985 +  p->nCol++;
   1.986 +}
   1.987 +
   1.988 +/*
   1.989 +** This routine is called by the parser while in the middle of
   1.990 +** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
   1.991 +** been seen on a column.  This routine sets the notNull flag on
   1.992 +** the column currently under construction.
   1.993 +*/
   1.994 +void sqlite3AddNotNull(Parse *pParse, int onError){
   1.995 +  Table *p;
   1.996 +  int i;
   1.997 +  if( (p = pParse->pNewTable)==0 ) return;
   1.998 +  i = p->nCol-1;
   1.999 +  if( i>=0 ) p->aCol[i].notNull = onError;
  1.1000 +}
  1.1001 +
  1.1002 +/*
  1.1003 +** Scan the column type name zType (length nType) and return the
  1.1004 +** associated affinity type.
  1.1005 +**
  1.1006 +** This routine does a case-independent search of zType for the 
  1.1007 +** substrings in the following table. If one of the substrings is
  1.1008 +** found, the corresponding affinity is returned. If zType contains
  1.1009 +** more than one of the substrings, entries toward the top of 
  1.1010 +** the table take priority. For example, if zType is 'BLOBINT', 
  1.1011 +** SQLITE_AFF_INTEGER is returned.
  1.1012 +**
  1.1013 +** Substring     | Affinity
  1.1014 +** --------------------------------
  1.1015 +** 'INT'         | SQLITE_AFF_INTEGER
  1.1016 +** 'CHAR'        | SQLITE_AFF_TEXT
  1.1017 +** 'CLOB'        | SQLITE_AFF_TEXT
  1.1018 +** 'TEXT'        | SQLITE_AFF_TEXT
  1.1019 +** 'BLOB'        | SQLITE_AFF_NONE
  1.1020 +** 'REAL'        | SQLITE_AFF_REAL
  1.1021 +** 'FLOA'        | SQLITE_AFF_REAL
  1.1022 +** 'DOUB'        | SQLITE_AFF_REAL
  1.1023 +**
  1.1024 +** If none of the substrings in the above table are found,
  1.1025 +** SQLITE_AFF_NUMERIC is returned.
  1.1026 +*/
  1.1027 +char sqlite3AffinityType(const Token *pType){
  1.1028 +  u32 h = 0;
  1.1029 +  char aff = SQLITE_AFF_NUMERIC;
  1.1030 +  const unsigned char *zIn = pType->z;
  1.1031 +  const unsigned char *zEnd = &pType->z[pType->n];
  1.1032 +
  1.1033 +  while( zIn!=zEnd ){
  1.1034 +    h = (h<<8) + sqlite3UpperToLower[*zIn];
  1.1035 +    zIn++;
  1.1036 +    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
  1.1037 +      aff = SQLITE_AFF_TEXT; 
  1.1038 +    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
  1.1039 +      aff = SQLITE_AFF_TEXT;
  1.1040 +    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
  1.1041 +      aff = SQLITE_AFF_TEXT;
  1.1042 +    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
  1.1043 +        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  1.1044 +      aff = SQLITE_AFF_NONE;
  1.1045 +#ifndef SQLITE_OMIT_FLOATING_POINT
  1.1046 +    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
  1.1047 +        && aff==SQLITE_AFF_NUMERIC ){
  1.1048 +      aff = SQLITE_AFF_REAL;
  1.1049 +    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
  1.1050 +        && aff==SQLITE_AFF_NUMERIC ){
  1.1051 +      aff = SQLITE_AFF_REAL;
  1.1052 +    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
  1.1053 +        && aff==SQLITE_AFF_NUMERIC ){
  1.1054 +      aff = SQLITE_AFF_REAL;
  1.1055 +#endif
  1.1056 +    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
  1.1057 +      aff = SQLITE_AFF_INTEGER;
  1.1058 +      break;
  1.1059 +    }
  1.1060 +  }
  1.1061 +
  1.1062 +  return aff;
  1.1063 +}
  1.1064 +
  1.1065 +/*
  1.1066 +** This routine is called by the parser while in the middle of
  1.1067 +** parsing a CREATE TABLE statement.  The pFirst token is the first
  1.1068 +** token in the sequence of tokens that describe the type of the
  1.1069 +** column currently under construction.   pLast is the last token
  1.1070 +** in the sequence.  Use this information to construct a string
  1.1071 +** that contains the typename of the column and store that string
  1.1072 +** in zType.
  1.1073 +*/ 
  1.1074 +void sqlite3AddColumnType(Parse *pParse, Token *pType){
  1.1075 +  Table *p;
  1.1076 +  int i;
  1.1077 +  Column *pCol;
  1.1078 +  sqlite3 *db;
  1.1079 +
  1.1080 +  if( (p = pParse->pNewTable)==0 ) return;
  1.1081 +  i = p->nCol-1;
  1.1082 +  if( i<0 ) return;
  1.1083 +  pCol = &p->aCol[i];
  1.1084 +  db = pParse->db;
  1.1085 +  sqlite3DbFree(db, pCol->zType);
  1.1086 +  pCol->zType = sqlite3NameFromToken(db, pType);
  1.1087 +  pCol->affinity = sqlite3AffinityType(pType);
  1.1088 +}
  1.1089 +
  1.1090 +/*
  1.1091 +** The expression is the default value for the most recently added column
  1.1092 +** of the table currently under construction.
  1.1093 +**
  1.1094 +** Default value expressions must be constant.  Raise an exception if this
  1.1095 +** is not the case.
  1.1096 +**
  1.1097 +** This routine is called by the parser while in the middle of
  1.1098 +** parsing a CREATE TABLE statement.
  1.1099 +*/
  1.1100 +void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
  1.1101 +  Table *p;
  1.1102 +  Column *pCol;
  1.1103 +  sqlite3 *db = pParse->db;
  1.1104 +  if( (p = pParse->pNewTable)!=0 ){
  1.1105 +    pCol = &(p->aCol[p->nCol-1]);
  1.1106 +    if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
  1.1107 +      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  1.1108 +          pCol->zName);
  1.1109 +    }else{
  1.1110 +      Expr *pCopy;
  1.1111 +      sqlite3ExprDelete(db, pCol->pDflt);
  1.1112 +      pCol->pDflt = pCopy = sqlite3ExprDup(db, pExpr);
  1.1113 +      if( pCopy ){
  1.1114 +        sqlite3TokenCopy(db, &pCopy->span, &pExpr->span);
  1.1115 +      }
  1.1116 +    }
  1.1117 +  }
  1.1118 +  sqlite3ExprDelete(db, pExpr);
  1.1119 +}
  1.1120 +
  1.1121 +/*
  1.1122 +** Designate the PRIMARY KEY for the table.  pList is a list of names 
  1.1123 +** of columns that form the primary key.  If pList is NULL, then the
  1.1124 +** most recently added column of the table is the primary key.
  1.1125 +**
  1.1126 +** A table can have at most one primary key.  If the table already has
  1.1127 +** a primary key (and this is the second primary key) then create an
  1.1128 +** error.
  1.1129 +**
  1.1130 +** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  1.1131 +** then we will try to use that column as the rowid.  Set the Table.iPKey
  1.1132 +** field of the table under construction to be the index of the
  1.1133 +** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
  1.1134 +** no INTEGER PRIMARY KEY.
  1.1135 +**
  1.1136 +** If the key is not an INTEGER PRIMARY KEY, then create a unique
  1.1137 +** index for the key.  No index is created for INTEGER PRIMARY KEYs.
  1.1138 +*/
  1.1139 +void sqlite3AddPrimaryKey(
  1.1140 +  Parse *pParse,    /* Parsing context */
  1.1141 +  ExprList *pList,  /* List of field names to be indexed */
  1.1142 +  int onError,      /* What to do with a uniqueness conflict */
  1.1143 +  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
  1.1144 +  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  1.1145 +){
  1.1146 +  Table *pTab = pParse->pNewTable;
  1.1147 +  char *zType = 0;
  1.1148 +  int iCol = -1, i;
  1.1149 +  if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  1.1150 +  if( pTab->tabFlags & TF_HasPrimaryKey ){
  1.1151 +    sqlite3ErrorMsg(pParse, 
  1.1152 +      "table \"%s\" has more than one primary key", pTab->zName);
  1.1153 +    goto primary_key_exit;
  1.1154 +  }
  1.1155 +  pTab->tabFlags |= TF_HasPrimaryKey;
  1.1156 +  if( pList==0 ){
  1.1157 +    iCol = pTab->nCol - 1;
  1.1158 +    pTab->aCol[iCol].isPrimKey = 1;
  1.1159 +  }else{
  1.1160 +    for(i=0; i<pList->nExpr; i++){
  1.1161 +      for(iCol=0; iCol<pTab->nCol; iCol++){
  1.1162 +        if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
  1.1163 +          break;
  1.1164 +        }
  1.1165 +      }
  1.1166 +      if( iCol<pTab->nCol ){
  1.1167 +        pTab->aCol[iCol].isPrimKey = 1;
  1.1168 +      }
  1.1169 +    }
  1.1170 +    if( pList->nExpr>1 ) iCol = -1;
  1.1171 +  }
  1.1172 +  if( iCol>=0 && iCol<pTab->nCol ){
  1.1173 +    zType = pTab->aCol[iCol].zType;
  1.1174 +  }
  1.1175 +  if( zType && sqlite3StrICmp(zType, "INTEGER")==0
  1.1176 +        && sortOrder==SQLITE_SO_ASC ){
  1.1177 +    pTab->iPKey = iCol;
  1.1178 +    pTab->keyConf = onError;
  1.1179 +    assert( autoInc==0 || autoInc==1 );
  1.1180 +    pTab->tabFlags |= autoInc*TF_Autoincrement;
  1.1181 +  }else if( autoInc ){
  1.1182 +#ifndef SQLITE_OMIT_AUTOINCREMENT
  1.1183 +    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  1.1184 +       "INTEGER PRIMARY KEY");
  1.1185 +#endif
  1.1186 +  }else{
  1.1187 +    sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
  1.1188 +    pList = 0;
  1.1189 +  }
  1.1190 +
  1.1191 +primary_key_exit:
  1.1192 +  sqlite3ExprListDelete(pParse->db, pList);
  1.1193 +  return;
  1.1194 +}
  1.1195 +
  1.1196 +/*
  1.1197 +** Add a new CHECK constraint to the table currently under construction.
  1.1198 +*/
  1.1199 +void sqlite3AddCheckConstraint(
  1.1200 +  Parse *pParse,    /* Parsing context */
  1.1201 +  Expr *pCheckExpr  /* The check expression */
  1.1202 +){
  1.1203 +  sqlite3 *db = pParse->db;
  1.1204 +#ifndef SQLITE_OMIT_CHECK
  1.1205 +  Table *pTab = pParse->pNewTable;
  1.1206 +  if( pTab && !IN_DECLARE_VTAB ){
  1.1207 +    /* The CHECK expression must be duplicated so that tokens refer
  1.1208 +    ** to malloced space and not the (ephemeral) text of the CREATE TABLE
  1.1209 +    ** statement */
  1.1210 +    pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, 
  1.1211 +                                  sqlite3ExprDup(db, pCheckExpr));
  1.1212 +  }
  1.1213 +#endif
  1.1214 +  sqlite3ExprDelete(db, pCheckExpr);
  1.1215 +}
  1.1216 +
  1.1217 +/*
  1.1218 +** Set the collation function of the most recently parsed table column
  1.1219 +** to the CollSeq given.
  1.1220 +*/
  1.1221 +void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  1.1222 +  Table *p;
  1.1223 +  int i;
  1.1224 +  char *zColl;              /* Dequoted name of collation sequence */
  1.1225 +  sqlite3 *db;
  1.1226 +
  1.1227 +  if( (p = pParse->pNewTable)==0 ) return;
  1.1228 +  i = p->nCol-1;
  1.1229 +  db = pParse->db;
  1.1230 +  zColl = sqlite3NameFromToken(db, pToken);
  1.1231 +  if( !zColl ) return;
  1.1232 +
  1.1233 +  if( sqlite3LocateCollSeq(pParse, zColl, -1) ){
  1.1234 +    Index *pIdx;
  1.1235 +    p->aCol[i].zColl = zColl;
  1.1236 +  
  1.1237 +    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  1.1238 +    ** then an index may have been created on this column before the
  1.1239 +    ** collation type was added. Correct this if it is the case.
  1.1240 +    */
  1.1241 +    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  1.1242 +      assert( pIdx->nColumn==1 );
  1.1243 +      if( pIdx->aiColumn[0]==i ){
  1.1244 +        pIdx->azColl[0] = p->aCol[i].zColl;
  1.1245 +      }
  1.1246 +    }
  1.1247 +  }else{
  1.1248 +    sqlite3DbFree(db, zColl);
  1.1249 +  }
  1.1250 +}
  1.1251 +
  1.1252 +/*
  1.1253 +** This function returns the collation sequence for database native text
  1.1254 +** encoding identified by the string zName, length nName.
  1.1255 +**
  1.1256 +** If the requested collation sequence is not available, or not available
  1.1257 +** in the database native encoding, the collation factory is invoked to
  1.1258 +** request it. If the collation factory does not supply such a sequence,
  1.1259 +** and the sequence is available in another text encoding, then that is
  1.1260 +** returned instead.
  1.1261 +**
  1.1262 +** If no versions of the requested collations sequence are available, or
  1.1263 +** another error occurs, NULL is returned and an error message written into
  1.1264 +** pParse.
  1.1265 +**
  1.1266 +** This routine is a wrapper around sqlite3FindCollSeq().  This routine
  1.1267 +** invokes the collation factory if the named collation cannot be found
  1.1268 +** and generates an error message.
  1.1269 +*/
  1.1270 +CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
  1.1271 +  sqlite3 *db = pParse->db;
  1.1272 +  u8 enc = ENC(db);
  1.1273 +  u8 initbusy = db->init.busy;
  1.1274 +  CollSeq *pColl;
  1.1275 +
  1.1276 +  pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
  1.1277 +  if( !initbusy && (!pColl || !pColl->xCmp) ){
  1.1278 +    pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
  1.1279 +    if( !pColl ){
  1.1280 +      if( nName<0 ){
  1.1281 +        nName = sqlite3Strlen(db, zName);
  1.1282 +      }
  1.1283 +      sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
  1.1284 +      pColl = 0;
  1.1285 +    }
  1.1286 +  }
  1.1287 +
  1.1288 +  return pColl;
  1.1289 +}
  1.1290 +
  1.1291 +
  1.1292 +/*
  1.1293 +** Generate code that will increment the schema cookie.
  1.1294 +**
  1.1295 +** The schema cookie is used to determine when the schema for the
  1.1296 +** database changes.  After each schema change, the cookie value
  1.1297 +** changes.  When a process first reads the schema it records the
  1.1298 +** cookie.  Thereafter, whenever it goes to access the database,
  1.1299 +** it checks the cookie to make sure the schema has not changed
  1.1300 +** since it was last read.
  1.1301 +**
  1.1302 +** This plan is not completely bullet-proof.  It is possible for
  1.1303 +** the schema to change multiple times and for the cookie to be
  1.1304 +** set back to prior value.  But schema changes are infrequent
  1.1305 +** and the probability of hitting the same cookie value is only
  1.1306 +** 1 chance in 2^32.  So we're safe enough.
  1.1307 +*/
  1.1308 +void sqlite3ChangeCookie(Parse *pParse, int iDb){
  1.1309 +  int r1 = sqlite3GetTempReg(pParse);
  1.1310 +  sqlite3 *db = pParse->db;
  1.1311 +  Vdbe *v = pParse->pVdbe;
  1.1312 +  sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  1.1313 +  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 0, r1);
  1.1314 +  sqlite3ReleaseTempReg(pParse, r1);
  1.1315 +}
  1.1316 +
  1.1317 +/*
  1.1318 +** Measure the number of characters needed to output the given
  1.1319 +** identifier.  The number returned includes any quotes used
  1.1320 +** but does not include the null terminator.
  1.1321 +**
  1.1322 +** The estimate is conservative.  It might be larger that what is
  1.1323 +** really needed.
  1.1324 +*/
  1.1325 +static int identLength(const char *z){
  1.1326 +  int n;
  1.1327 +  for(n=0; *z; n++, z++){
  1.1328 +    if( *z=='"' ){ n++; }
  1.1329 +  }
  1.1330 +  return n + 2;
  1.1331 +}
  1.1332 +
  1.1333 +/*
  1.1334 +** Write an identifier onto the end of the given string.  Add
  1.1335 +** quote characters as needed.
  1.1336 +*/
  1.1337 +static void identPut(char *z, int *pIdx, char *zSignedIdent){
  1.1338 +  unsigned char *zIdent = (unsigned char*)zSignedIdent;
  1.1339 +  int i, j, needQuote;
  1.1340 +  i = *pIdx;
  1.1341 +  for(j=0; zIdent[j]; j++){
  1.1342 +    if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  1.1343 +  }
  1.1344 +  needQuote =  zIdent[j]!=0 || isdigit(zIdent[0])
  1.1345 +                  || sqlite3KeywordCode(zIdent, j)!=TK_ID;
  1.1346 +  if( needQuote ) z[i++] = '"';
  1.1347 +  for(j=0; zIdent[j]; j++){
  1.1348 +    z[i++] = zIdent[j];
  1.1349 +    if( zIdent[j]=='"' ) z[i++] = '"';
  1.1350 +  }
  1.1351 +  if( needQuote ) z[i++] = '"';
  1.1352 +  z[i] = 0;
  1.1353 +  *pIdx = i;
  1.1354 +}
  1.1355 +
  1.1356 +/*
  1.1357 +** Generate a CREATE TABLE statement appropriate for the given
  1.1358 +** table.  Memory to hold the text of the statement is obtained
  1.1359 +** from sqliteMalloc() and must be freed by the calling function.
  1.1360 +*/
  1.1361 +static char *createTableStmt(sqlite3 *db, Table *p, int isTemp){
  1.1362 +  int i, k, n;
  1.1363 +  char *zStmt;
  1.1364 +  char *zSep, *zSep2, *zEnd, *z;
  1.1365 +  Column *pCol;
  1.1366 +  n = 0;
  1.1367 +  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  1.1368 +    n += identLength(pCol->zName);
  1.1369 +    z = pCol->zType;
  1.1370 +    if( z ){
  1.1371 +      n += (strlen(z) + 1);
  1.1372 +    }
  1.1373 +  }
  1.1374 +  n += identLength(p->zName);
  1.1375 +  if( n<50 ){
  1.1376 +    zSep = "";
  1.1377 +    zSep2 = ",";
  1.1378 +    zEnd = ")";
  1.1379 +  }else{
  1.1380 +    zSep = "\n  ";
  1.1381 +    zSep2 = ",\n  ";
  1.1382 +    zEnd = "\n)";
  1.1383 +  }
  1.1384 +  n += 35 + 6*p->nCol;
  1.1385 +  zStmt = sqlite3Malloc( n );
  1.1386 +  if( zStmt==0 ){
  1.1387 +    db->mallocFailed = 1;
  1.1388 +    return 0;
  1.1389 +  }
  1.1390 +  sqlite3_snprintf(n, zStmt,
  1.1391 +                  !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
  1.1392 +  k = strlen(zStmt);
  1.1393 +  identPut(zStmt, &k, p->zName);
  1.1394 +  zStmt[k++] = '(';
  1.1395 +  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  1.1396 +    sqlite3_snprintf(n-k, &zStmt[k], zSep);
  1.1397 +    k += strlen(&zStmt[k]);
  1.1398 +    zSep = zSep2;
  1.1399 +    identPut(zStmt, &k, pCol->zName);
  1.1400 +    if( (z = pCol->zType)!=0 ){
  1.1401 +      zStmt[k++] = ' ';
  1.1402 +      assert( strlen(z)+k+1<=n );
  1.1403 +      sqlite3_snprintf(n-k, &zStmt[k], "%s", z);
  1.1404 +      k += strlen(z);
  1.1405 +    }
  1.1406 +  }
  1.1407 +  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  1.1408 +  return zStmt;
  1.1409 +}
  1.1410 +
  1.1411 +/*
  1.1412 +** This routine is called to report the final ")" that terminates
  1.1413 +** a CREATE TABLE statement.
  1.1414 +**
  1.1415 +** The table structure that other action routines have been building
  1.1416 +** is added to the internal hash tables, assuming no errors have
  1.1417 +** occurred.
  1.1418 +**
  1.1419 +** An entry for the table is made in the master table on disk, unless
  1.1420 +** this is a temporary table or db->init.busy==1.  When db->init.busy==1
  1.1421 +** it means we are reading the sqlite_master table because we just
  1.1422 +** connected to the database or because the sqlite_master table has
  1.1423 +** recently changed, so the entry for this table already exists in
  1.1424 +** the sqlite_master table.  We do not want to create it again.
  1.1425 +**
  1.1426 +** If the pSelect argument is not NULL, it means that this routine
  1.1427 +** was called to create a table generated from a 
  1.1428 +** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
  1.1429 +** the new table will match the result set of the SELECT.
  1.1430 +*/
  1.1431 +void sqlite3EndTable(
  1.1432 +  Parse *pParse,          /* Parse context */
  1.1433 +  Token *pCons,           /* The ',' token after the last column defn. */
  1.1434 +  Token *pEnd,            /* The final ')' token in the CREATE TABLE */
  1.1435 +  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
  1.1436 +){
  1.1437 +  Table *p;
  1.1438 +  sqlite3 *db = pParse->db;
  1.1439 +  int iDb;
  1.1440 +
  1.1441 +  if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) {
  1.1442 +    return;
  1.1443 +  }
  1.1444 +  p = pParse->pNewTable;
  1.1445 +  if( p==0 ) return;
  1.1446 +
  1.1447 +  assert( !db->init.busy || !pSelect );
  1.1448 +
  1.1449 +  iDb = sqlite3SchemaToIndex(db, p->pSchema);
  1.1450 +
  1.1451 +#ifndef SQLITE_OMIT_CHECK
  1.1452 +  /* Resolve names in all CHECK constraint expressions.
  1.1453 +  */
  1.1454 +  if( p->pCheck ){
  1.1455 +    SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
  1.1456 +    NameContext sNC;                /* Name context for pParse->pNewTable */
  1.1457 +
  1.1458 +    memset(&sNC, 0, sizeof(sNC));
  1.1459 +    memset(&sSrc, 0, sizeof(sSrc));
  1.1460 +    sSrc.nSrc = 1;
  1.1461 +    sSrc.a[0].zName = p->zName;
  1.1462 +    sSrc.a[0].pTab = p;
  1.1463 +    sSrc.a[0].iCursor = -1;
  1.1464 +    sNC.pParse = pParse;
  1.1465 +    sNC.pSrcList = &sSrc;
  1.1466 +    sNC.isCheck = 1;
  1.1467 +    if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
  1.1468 +      return;
  1.1469 +    }
  1.1470 +  }
  1.1471 +#endif /* !defined(SQLITE_OMIT_CHECK) */
  1.1472 +
  1.1473 +  /* If the db->init.busy is 1 it means we are reading the SQL off the
  1.1474 +  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  1.1475 +  ** So do not write to the disk again.  Extract the root page number
  1.1476 +  ** for the table from the db->init.newTnum field.  (The page number
  1.1477 +  ** should have been put there by the sqliteOpenCb routine.)
  1.1478 +  */
  1.1479 +  if( db->init.busy ){
  1.1480 +    p->tnum = db->init.newTnum;
  1.1481 +  }
  1.1482 +
  1.1483 +  /* If not initializing, then create a record for the new table
  1.1484 +  ** in the SQLITE_MASTER table of the database.  The record number
  1.1485 +  ** for the new table entry should already be on the stack.
  1.1486 +  **
  1.1487 +  ** If this is a TEMPORARY table, write the entry into the auxiliary
  1.1488 +  ** file instead of into the main database file.
  1.1489 +  */
  1.1490 +  if( !db->init.busy ){
  1.1491 +    int n;
  1.1492 +    Vdbe *v;
  1.1493 +    char *zType;    /* "view" or "table" */
  1.1494 +    char *zType2;   /* "VIEW" or "TABLE" */
  1.1495 +    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
  1.1496 +
  1.1497 +    v = sqlite3GetVdbe(pParse);
  1.1498 +    if( v==0 ) return;
  1.1499 +
  1.1500 +    sqlite3VdbeAddOp1(v, OP_Close, 0);
  1.1501 +
  1.1502 +    /* Create the rootpage for the new table and push it onto the stack.
  1.1503 +    ** A view has no rootpage, so just push a zero onto the stack for
  1.1504 +    ** views.  Initialize zType at the same time.
  1.1505 +    */
  1.1506 +    if( p->pSelect==0 ){
  1.1507 +      /* A regular table */
  1.1508 +      zType = "table";
  1.1509 +      zType2 = "TABLE";
  1.1510 +#ifndef SQLITE_OMIT_VIEW
  1.1511 +    }else{
  1.1512 +      /* A view */
  1.1513 +      zType = "view";
  1.1514 +      zType2 = "VIEW";
  1.1515 +#endif
  1.1516 +    }
  1.1517 +
  1.1518 +    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  1.1519 +    ** statement to populate the new table. The root-page number for the
  1.1520 +    ** new table is on the top of the vdbe stack.
  1.1521 +    **
  1.1522 +    ** Once the SELECT has been coded by sqlite3Select(), it is in a
  1.1523 +    ** suitable state to query for the column names and types to be used
  1.1524 +    ** by the new table.
  1.1525 +    **
  1.1526 +    ** A shared-cache write-lock is not required to write to the new table,
  1.1527 +    ** as a schema-lock must have already been obtained to create it. Since
  1.1528 +    ** a schema-lock excludes all other database users, the write-lock would
  1.1529 +    ** be redundant.
  1.1530 +    */
  1.1531 +    if( pSelect ){
  1.1532 +      SelectDest dest;
  1.1533 +      Table *pSelTab;
  1.1534 +
  1.1535 +      assert(pParse->nTab==0);
  1.1536 +      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  1.1537 +      sqlite3VdbeChangeP5(v, 1);
  1.1538 +      pParse->nTab = 2;
  1.1539 +      sqlite3SelectDestInit(&dest, SRT_Table, 1);
  1.1540 +      sqlite3Select(pParse, pSelect, &dest);
  1.1541 +      sqlite3VdbeAddOp1(v, OP_Close, 1);
  1.1542 +      if( pParse->nErr==0 ){
  1.1543 +        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  1.1544 +        if( pSelTab==0 ) return;
  1.1545 +        assert( p->aCol==0 );
  1.1546 +        p->nCol = pSelTab->nCol;
  1.1547 +        p->aCol = pSelTab->aCol;
  1.1548 +        pSelTab->nCol = 0;
  1.1549 +        pSelTab->aCol = 0;
  1.1550 +        sqlite3DeleteTable(pSelTab);
  1.1551 +      }
  1.1552 +    }
  1.1553 +
  1.1554 +    /* Compute the complete text of the CREATE statement */
  1.1555 +    if( pSelect ){
  1.1556 +      zStmt = createTableStmt(db, p, p->pSchema==db->aDb[1].pSchema);
  1.1557 +    }else{
  1.1558 +      n = pEnd->z - pParse->sNameToken.z + 1;
  1.1559 +      zStmt = sqlite3MPrintf(db, 
  1.1560 +          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  1.1561 +      );
  1.1562 +    }
  1.1563 +
  1.1564 +    /* A slot for the record has already been allocated in the 
  1.1565 +    ** SQLITE_MASTER table.  We just need to update that slot with all
  1.1566 +    ** the information we've collected.  The rowid for the preallocated
  1.1567 +    ** slot is the 2nd item on the stack.  The top of the stack is the
  1.1568 +    ** root page for the new table (or a 0 if this is a view).
  1.1569 +    */
  1.1570 +    sqlite3NestedParse(pParse,
  1.1571 +      "UPDATE %Q.%s "
  1.1572 +         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  1.1573 +       "WHERE rowid=#%d",
  1.1574 +      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  1.1575 +      zType,
  1.1576 +      p->zName,
  1.1577 +      p->zName,
  1.1578 +      pParse->regRoot,
  1.1579 +      zStmt,
  1.1580 +      pParse->regRowid
  1.1581 +    );
  1.1582 +    sqlite3DbFree(db, zStmt);
  1.1583 +    sqlite3ChangeCookie(pParse, iDb);
  1.1584 +
  1.1585 +#ifndef SQLITE_OMIT_AUTOINCREMENT
  1.1586 +    /* Check to see if we need to create an sqlite_sequence table for
  1.1587 +    ** keeping track of autoincrement keys.
  1.1588 +    */
  1.1589 +    if( p->tabFlags & TF_Autoincrement ){
  1.1590 +      Db *pDb = &db->aDb[iDb];
  1.1591 +      if( pDb->pSchema->pSeqTab==0 ){
  1.1592 +        sqlite3NestedParse(pParse,
  1.1593 +          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  1.1594 +          pDb->zName
  1.1595 +        );
  1.1596 +      }
  1.1597 +    }
  1.1598 +#endif
  1.1599 +
  1.1600 +    /* Reparse everything to update our internal data structures */
  1.1601 +    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
  1.1602 +        sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
  1.1603 +  }
  1.1604 +
  1.1605 +
  1.1606 +  /* Add the table to the in-memory representation of the database.
  1.1607 +  */
  1.1608 +  if( db->init.busy && pParse->nErr==0 ){
  1.1609 +    Table *pOld;
  1.1610 +    FKey *pFKey; 
  1.1611 +    Schema *pSchema = p->pSchema;
  1.1612 +    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
  1.1613 +    if( pOld ){
  1.1614 +      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
  1.1615 +      db->mallocFailed = 1;
  1.1616 +      return;
  1.1617 +    }
  1.1618 +#ifndef SQLITE_OMIT_FOREIGN_KEY
  1.1619 +    for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  1.1620 +      void *data;
  1.1621 +      int nTo = strlen(pFKey->zTo) + 1;
  1.1622 +      pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
  1.1623 +      data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
  1.1624 +      if( data==(void *)pFKey ){
  1.1625 +        db->mallocFailed = 1;
  1.1626 +      }
  1.1627 +    }
  1.1628 +#endif
  1.1629 +    pParse->pNewTable = 0;
  1.1630 +    db->nTable++;
  1.1631 +    db->flags |= SQLITE_InternChanges;
  1.1632 +
  1.1633 +#ifndef SQLITE_OMIT_ALTERTABLE
  1.1634 +    if( !p->pSelect ){
  1.1635 +      const char *zName = (const char *)pParse->sNameToken.z;
  1.1636 +      int nName;
  1.1637 +      assert( !pSelect && pCons && pEnd );
  1.1638 +      if( pCons->z==0 ){
  1.1639 +        pCons = pEnd;
  1.1640 +      }
  1.1641 +      nName = (const char *)pCons->z - zName;
  1.1642 +      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  1.1643 +    }
  1.1644 +#endif
  1.1645 +  }
  1.1646 +}
  1.1647 +
  1.1648 +#ifndef SQLITE_OMIT_VIEW
  1.1649 +/*
  1.1650 +** The parser calls this routine in order to create a new VIEW
  1.1651 +*/
  1.1652 +void sqlite3CreateView(
  1.1653 +  Parse *pParse,     /* The parsing context */
  1.1654 +  Token *pBegin,     /* The CREATE token that begins the statement */
  1.1655 +  Token *pName1,     /* The token that holds the name of the view */
  1.1656 +  Token *pName2,     /* The token that holds the name of the view */
  1.1657 +  Select *pSelect,   /* A SELECT statement that will become the new view */
  1.1658 +  int isTemp,        /* TRUE for a TEMPORARY view */
  1.1659 +  int noErr          /* Suppress error messages if VIEW already exists */
  1.1660 +){
  1.1661 +  Table *p;
  1.1662 +  int n;
  1.1663 +  const unsigned char *z;
  1.1664 +  Token sEnd;
  1.1665 +  DbFixer sFix;
  1.1666 +  Token *pName;
  1.1667 +  int iDb;
  1.1668 +  sqlite3 *db = pParse->db;
  1.1669 +
  1.1670 +  if( pParse->nVar>0 ){
  1.1671 +    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  1.1672 +    sqlite3SelectDelete(db, pSelect);
  1.1673 +    return;
  1.1674 +  }
  1.1675 +  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  1.1676 +  p = pParse->pNewTable;
  1.1677 +  if( p==0 || pParse->nErr ){
  1.1678 +    sqlite3SelectDelete(db, pSelect);
  1.1679 +    return;
  1.1680 +  }
  1.1681 +  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  1.1682 +  iDb = sqlite3SchemaToIndex(db, p->pSchema);
  1.1683 +  if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
  1.1684 +    && sqlite3FixSelect(&sFix, pSelect)
  1.1685 +  ){
  1.1686 +    sqlite3SelectDelete(db, pSelect);
  1.1687 +    return;
  1.1688 +  }
  1.1689 +
  1.1690 +  /* Make a copy of the entire SELECT statement that defines the view.
  1.1691 +  ** This will force all the Expr.token.z values to be dynamically
  1.1692 +  ** allocated rather than point to the input string - which means that
  1.1693 +  ** they will persist after the current sqlite3_exec() call returns.
  1.1694 +  */
  1.1695 +  p->pSelect = sqlite3SelectDup(db, pSelect);
  1.1696 +  sqlite3SelectDelete(db, pSelect);
  1.1697 +  if( db->mallocFailed ){
  1.1698 +    return;
  1.1699 +  }
  1.1700 +  if( !db->init.busy ){
  1.1701 +    sqlite3ViewGetColumnNames(pParse, p);
  1.1702 +  }
  1.1703 +
  1.1704 +  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
  1.1705 +  ** the end.
  1.1706 +  */
  1.1707 +  sEnd = pParse->sLastToken;
  1.1708 +  if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
  1.1709 +    sEnd.z += sEnd.n;
  1.1710 +  }
  1.1711 +  sEnd.n = 0;
  1.1712 +  n = sEnd.z - pBegin->z;
  1.1713 +  z = (const unsigned char*)pBegin->z;
  1.1714 +  while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
  1.1715 +  sEnd.z = &z[n-1];
  1.1716 +  sEnd.n = 1;
  1.1717 +
  1.1718 +  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  1.1719 +  sqlite3EndTable(pParse, 0, &sEnd, 0);
  1.1720 +  return;
  1.1721 +}
  1.1722 +#endif /* SQLITE_OMIT_VIEW */
  1.1723 +
  1.1724 +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  1.1725 +/*
  1.1726 +** The Table structure pTable is really a VIEW.  Fill in the names of
  1.1727 +** the columns of the view in the pTable structure.  Return the number
  1.1728 +** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
  1.1729 +*/
  1.1730 +int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  1.1731 +  Table *pSelTab;   /* A fake table from which we get the result set */
  1.1732 +  Select *pSel;     /* Copy of the SELECT that implements the view */
  1.1733 +  int nErr = 0;     /* Number of errors encountered */
  1.1734 +  int n;            /* Temporarily holds the number of cursors assigned */
  1.1735 +  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
  1.1736 +  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  1.1737 +
  1.1738 +  assert( pTable );
  1.1739 +
  1.1740 +#ifndef SQLITE_OMIT_VIRTUALTABLE
  1.1741 +  if( sqlite3VtabCallConnect(pParse, pTable) ){
  1.1742 +    return SQLITE_ERROR;
  1.1743 +  }
  1.1744 +  if( IsVirtual(pTable) ) return 0;
  1.1745 +#endif
  1.1746 +
  1.1747 +#ifndef SQLITE_OMIT_VIEW
  1.1748 +  /* A positive nCol means the columns names for this view are
  1.1749 +  ** already known.
  1.1750 +  */
  1.1751 +  if( pTable->nCol>0 ) return 0;
  1.1752 +
  1.1753 +  /* A negative nCol is a special marker meaning that we are currently
  1.1754 +  ** trying to compute the column names.  If we enter this routine with
  1.1755 +  ** a negative nCol, it means two or more views form a loop, like this:
  1.1756 +  **
  1.1757 +  **     CREATE VIEW one AS SELECT * FROM two;
  1.1758 +  **     CREATE VIEW two AS SELECT * FROM one;
  1.1759 +  **
  1.1760 +  ** Actually, this error is caught previously and so the following test
  1.1761 +  ** should always fail.  But we will leave it in place just to be safe.
  1.1762 +  */
  1.1763 +  if( pTable->nCol<0 ){
  1.1764 +    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  1.1765 +    return 1;
  1.1766 +  }
  1.1767 +  assert( pTable->nCol>=0 );
  1.1768 +
  1.1769 +  /* If we get this far, it means we need to compute the table names.
  1.1770 +  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  1.1771 +  ** "*" elements in the results set of the view and will assign cursors
  1.1772 +  ** to the elements of the FROM clause.  But we do not want these changes
  1.1773 +  ** to be permanent.  So the computation is done on a copy of the SELECT
  1.1774 +  ** statement that defines the view.
  1.1775 +  */
  1.1776 +  assert( pTable->pSelect );
  1.1777 +  pSel = sqlite3SelectDup(db, pTable->pSelect);
  1.1778 +  if( pSel ){
  1.1779 +    n = pParse->nTab;
  1.1780 +    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  1.1781 +    pTable->nCol = -1;
  1.1782 +#ifndef SQLITE_OMIT_AUTHORIZATION
  1.1783 +    xAuth = db->xAuth;
  1.1784 +    db->xAuth = 0;
  1.1785 +    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  1.1786 +    db->xAuth = xAuth;
  1.1787 +#else
  1.1788 +    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  1.1789 +#endif
  1.1790 +    pParse->nTab = n;
  1.1791 +    if( pSelTab ){
  1.1792 +      assert( pTable->aCol==0 );
  1.1793 +      pTable->nCol = pSelTab->nCol;
  1.1794 +      pTable->aCol = pSelTab->aCol;
  1.1795 +      pSelTab->nCol = 0;
  1.1796 +      pSelTab->aCol = 0;
  1.1797 +      sqlite3DeleteTable(pSelTab);
  1.1798 +      pTable->pSchema->flags |= DB_UnresetViews;
  1.1799 +    }else{
  1.1800 +      pTable->nCol = 0;
  1.1801 +      nErr++;
  1.1802 +    }
  1.1803 +    sqlite3SelectDelete(db, pSel);
  1.1804 +  } else {
  1.1805 +    nErr++;
  1.1806 +  }
  1.1807 +#endif /* SQLITE_OMIT_VIEW */
  1.1808 +  return nErr;  
  1.1809 +}
  1.1810 +#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  1.1811 +
  1.1812 +#ifndef SQLITE_OMIT_VIEW
  1.1813 +/*
  1.1814 +** Clear the column names from every VIEW in database idx.
  1.1815 +*/
  1.1816 +static void sqliteViewResetAll(sqlite3 *db, int idx){
  1.1817 +  HashElem *i;
  1.1818 +  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  1.1819 +  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  1.1820 +    Table *pTab = sqliteHashData(i);
  1.1821 +    if( pTab->pSelect ){
  1.1822 +      sqliteResetColumnNames(pTab);
  1.1823 +    }
  1.1824 +  }
  1.1825 +  DbClearProperty(db, idx, DB_UnresetViews);
  1.1826 +}
  1.1827 +#else
  1.1828 +# define sqliteViewResetAll(A,B)
  1.1829 +#endif /* SQLITE_OMIT_VIEW */
  1.1830 +
  1.1831 +/*
  1.1832 +** This function is called by the VDBE to adjust the internal schema
  1.1833 +** used by SQLite when the btree layer moves a table root page. The
  1.1834 +** root-page of a table or index in database iDb has changed from iFrom
  1.1835 +** to iTo.
  1.1836 +**
  1.1837 +** Ticket #1728:  The symbol table might still contain information
  1.1838 +** on tables and/or indices that are the process of being deleted.
  1.1839 +** If you are unlucky, one of those deleted indices or tables might
  1.1840 +** have the same rootpage number as the real table or index that is
  1.1841 +** being moved.  So we cannot stop searching after the first match 
  1.1842 +** because the first match might be for one of the deleted indices
  1.1843 +** or tables and not the table/index that is actually being moved.
  1.1844 +** We must continue looping until all tables and indices with
  1.1845 +** rootpage==iFrom have been converted to have a rootpage of iTo
  1.1846 +** in order to be certain that we got the right one.
  1.1847 +*/
  1.1848 +#ifndef SQLITE_OMIT_AUTOVACUUM
  1.1849 +void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
  1.1850 +  HashElem *pElem;
  1.1851 +  Hash *pHash;
  1.1852 +
  1.1853 +  pHash = &pDb->pSchema->tblHash;
  1.1854 +  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  1.1855 +    Table *pTab = sqliteHashData(pElem);
  1.1856 +    if( pTab->tnum==iFrom ){
  1.1857 +      pTab->tnum = iTo;
  1.1858 +    }
  1.1859 +  }
  1.1860 +  pHash = &pDb->pSchema->idxHash;
  1.1861 +  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  1.1862 +    Index *pIdx = sqliteHashData(pElem);
  1.1863 +    if( pIdx->tnum==iFrom ){
  1.1864 +      pIdx->tnum = iTo;
  1.1865 +    }
  1.1866 +  }
  1.1867 +}
  1.1868 +#endif
  1.1869 +
  1.1870 +/*
  1.1871 +** Write code to erase the table with root-page iTable from database iDb.
  1.1872 +** Also write code to modify the sqlite_master table and internal schema
  1.1873 +** if a root-page of another table is moved by the btree-layer whilst
  1.1874 +** erasing iTable (this can happen with an auto-vacuum database).
  1.1875 +*/ 
  1.1876 +static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  1.1877 +  Vdbe *v = sqlite3GetVdbe(pParse);
  1.1878 +  int r1 = sqlite3GetTempReg(pParse);
  1.1879 +  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  1.1880 +#ifndef SQLITE_OMIT_AUTOVACUUM
  1.1881 +  /* OP_Destroy stores an in integer r1. If this integer
  1.1882 +  ** is non-zero, then it is the root page number of a table moved to
  1.1883 +  ** location iTable. The following code modifies the sqlite_master table to
  1.1884 +  ** reflect this.
  1.1885 +  **
  1.1886 +  ** The "#%d" in the SQL is a special constant that means whatever value
  1.1887 +  ** is on the top of the stack.  See sqlite3RegisterExpr().
  1.1888 +  */
  1.1889 +  sqlite3NestedParse(pParse, 
  1.1890 +     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  1.1891 +     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  1.1892 +#endif
  1.1893 +  sqlite3ReleaseTempReg(pParse, r1);
  1.1894 +}
  1.1895 +
  1.1896 +/*
  1.1897 +** Write VDBE code to erase table pTab and all associated indices on disk.
  1.1898 +** Code to update the sqlite_master tables and internal schema definitions
  1.1899 +** in case a root-page belonging to another table is moved by the btree layer
  1.1900 +** is also added (this can happen with an auto-vacuum database).
  1.1901 +*/
  1.1902 +static void destroyTable(Parse *pParse, Table *pTab){
  1.1903 +#ifdef SQLITE_OMIT_AUTOVACUUM
  1.1904 +  Index *pIdx;
  1.1905 +  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  1.1906 +  destroyRootPage(pParse, pTab->tnum, iDb);
  1.1907 +  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  1.1908 +    destroyRootPage(pParse, pIdx->tnum, iDb);
  1.1909 +  }
  1.1910 +#else
  1.1911 +  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  1.1912 +  ** is not defined), then it is important to call OP_Destroy on the
  1.1913 +  ** table and index root-pages in order, starting with the numerically 
  1.1914 +  ** largest root-page number. This guarantees that none of the root-pages
  1.1915 +  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  1.1916 +  ** following were coded:
  1.1917 +  **
  1.1918 +  ** OP_Destroy 4 0
  1.1919 +  ** ...
  1.1920 +  ** OP_Destroy 5 0
  1.1921 +  **
  1.1922 +  ** and root page 5 happened to be the largest root-page number in the
  1.1923 +  ** database, then root page 5 would be moved to page 4 by the 
  1.1924 +  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  1.1925 +  ** a free-list page.
  1.1926 +  */
  1.1927 +  int iTab = pTab->tnum;
  1.1928 +  int iDestroyed = 0;
  1.1929 +
  1.1930 +  while( 1 ){
  1.1931 +    Index *pIdx;
  1.1932 +    int iLargest = 0;
  1.1933 +
  1.1934 +    if( iDestroyed==0 || iTab<iDestroyed ){
  1.1935 +      iLargest = iTab;
  1.1936 +    }
  1.1937 +    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  1.1938 +      int iIdx = pIdx->tnum;
  1.1939 +      assert( pIdx->pSchema==pTab->pSchema );
  1.1940 +      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  1.1941 +        iLargest = iIdx;
  1.1942 +      }
  1.1943 +    }
  1.1944 +    if( iLargest==0 ){
  1.1945 +      return;
  1.1946 +    }else{
  1.1947 +      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  1.1948 +      destroyRootPage(pParse, iLargest, iDb);
  1.1949 +      iDestroyed = iLargest;
  1.1950 +    }
  1.1951 +  }
  1.1952 +#endif
  1.1953 +}
  1.1954 +
  1.1955 +/*
  1.1956 +** This routine is called to do the work of a DROP TABLE statement.
  1.1957 +** pName is the name of the table to be dropped.
  1.1958 +*/
  1.1959 +void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  1.1960 +  Table *pTab;
  1.1961 +  Vdbe *v;
  1.1962 +  sqlite3 *db = pParse->db;
  1.1963 +  int iDb;
  1.1964 +
  1.1965 +  if( pParse->nErr || db->mallocFailed ){
  1.1966 +    goto exit_drop_table;
  1.1967 +  }
  1.1968 +  assert( pName->nSrc==1 );
  1.1969 +  pTab = sqlite3LocateTable(pParse, isView, 
  1.1970 +                            pName->a[0].zName, pName->a[0].zDatabase);
  1.1971 +
  1.1972 +  if( pTab==0 ){
  1.1973 +    if( noErr ){
  1.1974 +      sqlite3ErrorClear(pParse);
  1.1975 +    }
  1.1976 +    goto exit_drop_table;
  1.1977 +  }
  1.1978 +  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  1.1979 +  assert( iDb>=0 && iDb<db->nDb );
  1.1980 +
  1.1981 +  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  1.1982 +  ** it is initialized.
  1.1983 +  */
  1.1984 +  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  1.1985 +    goto exit_drop_table;
  1.1986 +  }
  1.1987 +#ifndef SQLITE_OMIT_AUTHORIZATION
  1.1988 +  {
  1.1989 +    int code;
  1.1990 +    const char *zTab = SCHEMA_TABLE(iDb);
  1.1991 +    const char *zDb = db->aDb[iDb].zName;
  1.1992 +    const char *zArg2 = 0;
  1.1993 +    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  1.1994 +      goto exit_drop_table;
  1.1995 +    }
  1.1996 +    if( isView ){
  1.1997 +      if( !OMIT_TEMPDB && iDb==1 ){
  1.1998 +        code = SQLITE_DROP_TEMP_VIEW;
  1.1999 +      }else{
  1.2000 +        code = SQLITE_DROP_VIEW;
  1.2001 +      }
  1.2002 +#ifndef SQLITE_OMIT_VIRTUALTABLE
  1.2003 +    }else if( IsVirtual(pTab) ){
  1.2004 +      code = SQLITE_DROP_VTABLE;
  1.2005 +      zArg2 = pTab->pMod->zName;
  1.2006 +#endif
  1.2007 +    }else{
  1.2008 +      if( !OMIT_TEMPDB && iDb==1 ){
  1.2009 +        code = SQLITE_DROP_TEMP_TABLE;
  1.2010 +      }else{
  1.2011 +        code = SQLITE_DROP_TABLE;
  1.2012 +      }
  1.2013 +    }
  1.2014 +    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  1.2015 +      goto exit_drop_table;
  1.2016 +    }
  1.2017 +    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  1.2018 +      goto exit_drop_table;
  1.2019 +    }
  1.2020 +  }
  1.2021 +#endif
  1.2022 +  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  1.2023 +    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  1.2024 +    goto exit_drop_table;
  1.2025 +  }
  1.2026 +
  1.2027 +#ifndef SQLITE_OMIT_VIEW
  1.2028 +  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  1.2029 +  ** on a table.
  1.2030 +  */
  1.2031 +  if( isView && pTab->pSelect==0 ){
  1.2032 +    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  1.2033 +    goto exit_drop_table;
  1.2034 +  }
  1.2035 +  if( !isView && pTab->pSelect ){
  1.2036 +    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  1.2037 +    goto exit_drop_table;
  1.2038 +  }
  1.2039 +#endif
  1.2040 +
  1.2041 +  /* Generate code to remove the table from the master table
  1.2042 +  ** on disk.
  1.2043 +  */
  1.2044 +  v = sqlite3GetVdbe(pParse);
  1.2045 +  if( v ){
  1.2046 +    Trigger *pTrigger;
  1.2047 +    Db *pDb = &db->aDb[iDb];
  1.2048 +    sqlite3BeginWriteOperation(pParse, 1, iDb);
  1.2049 +
  1.2050 +#ifndef SQLITE_OMIT_VIRTUALTABLE
  1.2051 +    if( IsVirtual(pTab) ){
  1.2052 +      Vdbe *v = sqlite3GetVdbe(pParse);
  1.2053 +      if( v ){
  1.2054 +        sqlite3VdbeAddOp0(v, OP_VBegin);
  1.2055 +      }
  1.2056 +    }
  1.2057 +#endif
  1.2058 +
  1.2059 +    /* Drop all triggers associated with the table being dropped. Code
  1.2060 +    ** is generated to remove entries from sqlite_master and/or
  1.2061 +    ** sqlite_temp_master if required.
  1.2062 +    */
  1.2063 +    pTrigger = pTab->pTrigger;
  1.2064 +    while( pTrigger ){
  1.2065 +      assert( pTrigger->pSchema==pTab->pSchema || 
  1.2066 +          pTrigger->pSchema==db->aDb[1].pSchema );
  1.2067 +      sqlite3DropTriggerPtr(pParse, pTrigger);
  1.2068 +      pTrigger = pTrigger->pNext;
  1.2069 +    }
  1.2070 +
  1.2071 +#ifndef SQLITE_OMIT_AUTOINCREMENT
  1.2072 +    /* Remove any entries of the sqlite_sequence table associated with
  1.2073 +    ** the table being dropped. This is done before the table is dropped
  1.2074 +    ** at the btree level, in case the sqlite_sequence table needs to
  1.2075 +    ** move as a result of the drop (can happen in auto-vacuum mode).
  1.2076 +    */
  1.2077 +    if( pTab->tabFlags & TF_Autoincrement ){
  1.2078 +      sqlite3NestedParse(pParse,
  1.2079 +        "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
  1.2080 +        pDb->zName, pTab->zName
  1.2081 +      );
  1.2082 +    }
  1.2083 +#endif
  1.2084 +
  1.2085 +    /* Drop all SQLITE_MASTER table and index entries that refer to the
  1.2086 +    ** table. The program name loops through the master table and deletes
  1.2087 +    ** every row that refers to a table of the same name as the one being
  1.2088 +    ** dropped. Triggers are handled seperately because a trigger can be
  1.2089 +    ** created in the temp database that refers to a table in another
  1.2090 +    ** database.
  1.2091 +    */
  1.2092 +    sqlite3NestedParse(pParse, 
  1.2093 +        "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  1.2094 +        pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  1.2095 +
  1.2096 +    /* Drop any statistics from the sqlite_stat1 table, if it exists */
  1.2097 +    if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
  1.2098 +      sqlite3NestedParse(pParse,
  1.2099 +        "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
  1.2100 +      );
  1.2101 +    }
  1.2102 +
  1.2103 +    if( !isView && !IsVirtual(pTab) ){
  1.2104 +      destroyTable(pParse, pTab);
  1.2105 +    }
  1.2106 +
  1.2107 +    /* Remove the table entry from SQLite's internal schema and modify
  1.2108 +    ** the schema cookie.
  1.2109 +    */
  1.2110 +    if( IsVirtual(pTab) ){
  1.2111 +      sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  1.2112 +    }
  1.2113 +    sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  1.2114 +    sqlite3ChangeCookie(pParse, iDb);
  1.2115 +  }
  1.2116 +  sqliteViewResetAll(db, iDb);
  1.2117 +
  1.2118 +exit_drop_table:
  1.2119 +  sqlite3SrcListDelete(db, pName);
  1.2120 +}
  1.2121 +
  1.2122 +/*
  1.2123 +** This routine is called to create a new foreign key on the table
  1.2124 +** currently under construction.  pFromCol determines which columns
  1.2125 +** in the current table point to the foreign key.  If pFromCol==0 then
  1.2126 +** connect the key to the last column inserted.  pTo is the name of
  1.2127 +** the table referred to.  pToCol is a list of tables in the other
  1.2128 +** pTo table that the foreign key points to.  flags contains all
  1.2129 +** information about the conflict resolution algorithms specified
  1.2130 +** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  1.2131 +**
  1.2132 +** An FKey structure is created and added to the table currently
  1.2133 +** under construction in the pParse->pNewTable field.  The new FKey
  1.2134 +** is not linked into db->aFKey at this point - that does not happen
  1.2135 +** until sqlite3EndTable().
  1.2136 +**
  1.2137 +** The foreign key is set for IMMEDIATE processing.  A subsequent call
  1.2138 +** to sqlite3DeferForeignKey() might change this to DEFERRED.
  1.2139 +*/
  1.2140 +void sqlite3CreateForeignKey(
  1.2141 +  Parse *pParse,       /* Parsing context */
  1.2142 +  ExprList *pFromCol,  /* Columns in this table that point to other table */
  1.2143 +  Token *pTo,          /* Name of the other table */
  1.2144 +  ExprList *pToCol,    /* Columns in the other table */
  1.2145 +  int flags            /* Conflict resolution algorithms. */
  1.2146 +){
  1.2147 +  sqlite3 *db = pParse->db;
  1.2148 +#ifndef SQLITE_OMIT_FOREIGN_KEY
  1.2149 +  FKey *pFKey = 0;
  1.2150 +  Table *p = pParse->pNewTable;
  1.2151 +  int nByte;
  1.2152 +  int i;
  1.2153 +  int nCol;
  1.2154 +  char *z;
  1.2155 +
  1.2156 +  assert( pTo!=0 );
  1.2157 +  if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
  1.2158 +  if( pFromCol==0 ){
  1.2159 +    int iCol = p->nCol-1;
  1.2160 +    if( iCol<0 ) goto fk_end;
  1.2161 +    if( pToCol && pToCol->nExpr!=1 ){
  1.2162 +      sqlite3ErrorMsg(pParse, "foreign key on %s"
  1.2163 +         " should reference only one column of table %T",
  1.2164 +         p->aCol[iCol].zName, pTo);
  1.2165 +      goto fk_end;
  1.2166 +    }
  1.2167 +    nCol = 1;
  1.2168 +  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  1.2169 +    sqlite3ErrorMsg(pParse,
  1.2170 +        "number of columns in foreign key does not match the number of "
  1.2171 +        "columns in the referenced table");
  1.2172 +    goto fk_end;
  1.2173 +  }else{
  1.2174 +    nCol = pFromCol->nExpr;
  1.2175 +  }
  1.2176 +  nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  1.2177 +  if( pToCol ){
  1.2178 +    for(i=0; i<pToCol->nExpr; i++){
  1.2179 +      nByte += strlen(pToCol->a[i].zName) + 1;
  1.2180 +    }
  1.2181 +  }
  1.2182 +  pFKey = sqlite3DbMallocZero(db, nByte );
  1.2183 +  if( pFKey==0 ){
  1.2184 +    goto fk_end;
  1.2185 +  }
  1.2186 +  pFKey->pFrom = p;
  1.2187 +  pFKey->pNextFrom = p->pFKey;
  1.2188 +  z = (char*)&pFKey[1];
  1.2189 +  pFKey->aCol = (struct sColMap*)z;
  1.2190 +  z += sizeof(struct sColMap)*nCol;
  1.2191 +  pFKey->zTo = z;
  1.2192 +  memcpy(z, pTo->z, pTo->n);
  1.2193 +  z[pTo->n] = 0;
  1.2194 +  z += pTo->n+1;
  1.2195 +  pFKey->pNextTo = 0;
  1.2196 +  pFKey->nCol = nCol;
  1.2197 +  if( pFromCol==0 ){
  1.2198 +    pFKey->aCol[0].iFrom = p->nCol-1;
  1.2199 +  }else{
  1.2200 +    for(i=0; i<nCol; i++){
  1.2201 +      int j;
  1.2202 +      for(j=0; j<p->nCol; j++){
  1.2203 +        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  1.2204 +          pFKey->aCol[i].iFrom = j;
  1.2205 +          break;
  1.2206 +        }
  1.2207 +      }
  1.2208 +      if( j>=p->nCol ){
  1.2209 +        sqlite3ErrorMsg(pParse, 
  1.2210 +          "unknown column \"%s\" in foreign key definition", 
  1.2211 +          pFromCol->a[i].zName);
  1.2212 +        goto fk_end;
  1.2213 +      }
  1.2214 +    }
  1.2215 +  }
  1.2216 +  if( pToCol ){
  1.2217 +    for(i=0; i<nCol; i++){
  1.2218 +      int n = strlen(pToCol->a[i].zName);
  1.2219 +      pFKey->aCol[i].zCol = z;
  1.2220 +      memcpy(z, pToCol->a[i].zName, n);
  1.2221 +      z[n] = 0;
  1.2222 +      z += n+1;
  1.2223 +    }
  1.2224 +  }
  1.2225 +  pFKey->isDeferred = 0;
  1.2226 +  pFKey->deleteConf = flags & 0xff;
  1.2227 +  pFKey->updateConf = (flags >> 8 ) & 0xff;
  1.2228 +  pFKey->insertConf = (flags >> 16 ) & 0xff;
  1.2229 +
  1.2230 +  /* Link the foreign key to the table as the last step.
  1.2231 +  */
  1.2232 +  p->pFKey = pFKey;
  1.2233 +  pFKey = 0;
  1.2234 +
  1.2235 +fk_end:
  1.2236 +  sqlite3DbFree(db, pFKey);
  1.2237 +#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  1.2238 +  sqlite3ExprListDelete(db, pFromCol);
  1.2239 +  sqlite3ExprListDelete(db, pToCol);
  1.2240 +}
  1.2241 +
  1.2242 +/*
  1.2243 +** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  1.2244 +** clause is seen as part of a foreign key definition.  The isDeferred
  1.2245 +** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  1.2246 +** The behavior of the most recently created foreign key is adjusted
  1.2247 +** accordingly.
  1.2248 +*/
  1.2249 +void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  1.2250 +#ifndef SQLITE_OMIT_FOREIGN_KEY
  1.2251 +  Table *pTab;
  1.2252 +  FKey *pFKey;
  1.2253 +  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  1.2254 +  pFKey->isDeferred = isDeferred;
  1.2255 +#endif
  1.2256 +}
  1.2257 +
  1.2258 +/*
  1.2259 +** Generate code that will erase and refill index *pIdx.  This is
  1.2260 +** used to initialize a newly created index or to recompute the
  1.2261 +** content of an index in response to a REINDEX command.
  1.2262 +**
  1.2263 +** if memRootPage is not negative, it means that the index is newly
  1.2264 +** created.  The register specified by memRootPage contains the
  1.2265 +** root page number of the index.  If memRootPage is negative, then
  1.2266 +** the index already exists and must be cleared before being refilled and
  1.2267 +** the root page number of the index is taken from pIndex->tnum.
  1.2268 +*/
  1.2269 +static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  1.2270 +  Table *pTab = pIndex->pTable;  /* The table that is indexed */
  1.2271 +  int iTab = pParse->nTab;       /* Btree cursor used for pTab */
  1.2272 +  int iIdx = pParse->nTab+1;     /* Btree cursor used for pIndex */
  1.2273 +  int addr1;                     /* Address of top of loop */
  1.2274 +  int tnum;                      /* Root page of index */
  1.2275 +  Vdbe *v;                       /* Generate code into this virtual machine */
  1.2276 +  KeyInfo *pKey;                 /* KeyInfo for index */
  1.2277 +  int regIdxKey;                 /* Registers containing the index key */
  1.2278 +  int regRecord;                 /* Register holding assemblied index record */
  1.2279 +  sqlite3 *db = pParse->db;      /* The database connection */
  1.2280 +  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  1.2281 +
  1.2282 +#ifndef SQLITE_OMIT_AUTHORIZATION
  1.2283 +  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  1.2284 +      db->aDb[iDb].zName ) ){
  1.2285 +    return;
  1.2286 +  }
  1.2287 +#endif
  1.2288 +
  1.2289 +  /* Require a write-lock on the table to perform this operation */
  1.2290 +  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  1.2291 +
  1.2292 +  v = sqlite3GetVdbe(pParse);
  1.2293 +  if( v==0 ) return;
  1.2294 +  if( memRootPage>=0 ){
  1.2295 +    tnum = memRootPage;
  1.2296 +  }else{
  1.2297 +    tnum = pIndex->tnum;
  1.2298 +    sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  1.2299 +  }
  1.2300 +  pKey = sqlite3IndexKeyinfo(pParse, pIndex);
  1.2301 +  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
  1.2302 +                    (char *)pKey, P4_KEYINFO_HANDOFF);
  1.2303 +  if( memRootPage>=0 ){
  1.2304 +    sqlite3VdbeChangeP5(v, 1);
  1.2305 +  }
  1.2306 +  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  1.2307 +  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
  1.2308 +  regRecord = sqlite3GetTempReg(pParse);
  1.2309 +  regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
  1.2310 +  if( pIndex->onError!=OE_None ){
  1.2311 +    int j1, j2;
  1.2312 +    int regRowid;
  1.2313 +
  1.2314 +    regRowid = regIdxKey + pIndex->nColumn;
  1.2315 +    j1 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdxKey, 0, pIndex->nColumn);
  1.2316 +    j2 = sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx,
  1.2317 +                           0, regRowid, SQLITE_INT_TO_PTR(regRecord), P4_INT32);
  1.2318 +    sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0,
  1.2319 +                    "indexed columns are not unique", P4_STATIC);
  1.2320 +    sqlite3VdbeJumpHere(v, j1);
  1.2321 +    sqlite3VdbeJumpHere(v, j2);
  1.2322 +  }
  1.2323 +  sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
  1.2324 +  sqlite3ReleaseTempReg(pParse, regRecord);
  1.2325 +  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
  1.2326 +  sqlite3VdbeJumpHere(v, addr1);
  1.2327 +  sqlite3VdbeAddOp1(v, OP_Close, iTab);
  1.2328 +  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  1.2329 +}
  1.2330 +
  1.2331 +/*
  1.2332 +** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
  1.2333 +** and pTblList is the name of the table that is to be indexed.  Both will 
  1.2334 +** be NULL for a primary key or an index that is created to satisfy a
  1.2335 +** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
  1.2336 +** as the table to be indexed.  pParse->pNewTable is a table that is
  1.2337 +** currently being constructed by a CREATE TABLE statement.
  1.2338 +**
  1.2339 +** pList is a list of columns to be indexed.  pList will be NULL if this
  1.2340 +** is a primary key or unique-constraint on the most recent column added
  1.2341 +** to the table currently under construction.  
  1.2342 +*/
  1.2343 +void sqlite3CreateIndex(
  1.2344 +  Parse *pParse,     /* All information about this parse */
  1.2345 +  Token *pName1,     /* First part of index name. May be NULL */
  1.2346 +  Token *pName2,     /* Second part of index name. May be NULL */
  1.2347 +  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  1.2348 +  ExprList *pList,   /* A list of columns to be indexed */
  1.2349 +  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  1.2350 +  Token *pStart,     /* The CREATE token that begins this statement */
  1.2351 +  Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
  1.2352 +  int sortOrder,     /* Sort order of primary key when pList==NULL */
  1.2353 +  int ifNotExist     /* Omit error if index already exists */
  1.2354 +){
  1.2355 +  Table *pTab = 0;     /* Table to be indexed */
  1.2356 +  Index *pIndex = 0;   /* The index to be created */
  1.2357 +  char *zName = 0;     /* Name of the index */
  1.2358 +  int nName;           /* Number of characters in zName */
  1.2359 +  int i, j;
  1.2360 +  Token nullId;        /* Fake token for an empty ID list */
  1.2361 +  DbFixer sFix;        /* For assigning database names to pTable */
  1.2362 +  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
  1.2363 +  sqlite3 *db = pParse->db;
  1.2364 +  Db *pDb;             /* The specific table containing the indexed database */
  1.2365 +  int iDb;             /* Index of the database that is being written */
  1.2366 +  Token *pName = 0;    /* Unqualified name of the index to create */
  1.2367 +  struct ExprList_item *pListItem; /* For looping over pList */
  1.2368 +  int nCol;
  1.2369 +  int nExtra = 0;
  1.2370 +  char *zExtra;
  1.2371 +
  1.2372 +  if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){
  1.2373 +    goto exit_create_index;
  1.2374 +  }
  1.2375 +
  1.2376 +  /*
  1.2377 +  ** Find the table that is to be indexed.  Return early if not found.
  1.2378 +  */
  1.2379 +  if( pTblName!=0 ){
  1.2380 +
  1.2381 +    /* Use the two-part index name to determine the database 
  1.2382 +    ** to search for the table. 'Fix' the table name to this db
  1.2383 +    ** before looking up the table.
  1.2384 +    */
  1.2385 +    assert( pName1 && pName2 );
  1.2386 +    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  1.2387 +    if( iDb<0 ) goto exit_create_index;
  1.2388 +
  1.2389 +#ifndef SQLITE_OMIT_TEMPDB
  1.2390 +    /* If the index name was unqualified, check if the the table
  1.2391 +    ** is a temp table. If so, set the database to 1. Do not do this
  1.2392 +    ** if initialising a database schema.
  1.2393 +    */
  1.2394 +    if( !db->init.busy ){
  1.2395 +      pTab = sqlite3SrcListLookup(pParse, pTblName);
  1.2396 +      if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  1.2397 +        iDb = 1;
  1.2398 +      }
  1.2399 +    }
  1.2400 +#endif
  1.2401 +
  1.2402 +    if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
  1.2403 +        sqlite3FixSrcList(&sFix, pTblName)
  1.2404 +    ){
  1.2405 +      /* Because the parser constructs pTblName from a single identifier,
  1.2406 +      ** sqlite3FixSrcList can never fail. */
  1.2407 +      assert(0);
  1.2408 +    }
  1.2409 +    pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
  1.2410 +        pTblName->a[0].zDatabase);
  1.2411 +    if( !pTab || db->mallocFailed ) goto exit_create_index;
  1.2412 +    assert( db->aDb[iDb].pSchema==pTab->pSchema );
  1.2413 +  }else{
  1.2414 +    assert( pName==0 );
  1.2415 +    pTab = pParse->pNewTable;
  1.2416 +    if( !pTab ) goto exit_create_index;
  1.2417 +    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  1.2418 +  }
  1.2419 +  pDb = &db->aDb[iDb];
  1.2420 +
  1.2421 +  if( pTab==0 || pParse->nErr ) goto exit_create_index;
  1.2422 +  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  1.2423 +    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  1.2424 +    goto exit_create_index;
  1.2425 +  }
  1.2426 +#ifndef SQLITE_OMIT_VIEW
  1.2427 +  if( pTab->pSelect ){
  1.2428 +    sqlite3ErrorMsg(pParse, "views may not be indexed");
  1.2429 +    goto exit_create_index;
  1.2430 +  }
  1.2431 +#endif
  1.2432 +#ifndef SQLITE_OMIT_VIRTUALTABLE
  1.2433 +  if( IsVirtual(pTab) ){
  1.2434 +    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  1.2435 +    goto exit_create_index;
  1.2436 +  }
  1.2437 +#endif
  1.2438 +
  1.2439 +  /*
  1.2440 +  ** Find the name of the index.  Make sure there is not already another
  1.2441 +  ** index or table with the same name.  
  1.2442 +  **
  1.2443 +  ** Exception:  If we are reading the names of permanent indices from the
  1.2444 +  ** sqlite_master table (because some other process changed the schema) and
  1.2445 +  ** one of the index names collides with the name of a temporary table or
  1.2446 +  ** index, then we will continue to process this index.
  1.2447 +  **
  1.2448 +  ** If pName==0 it means that we are
  1.2449 +  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
  1.2450 +  ** own name.
  1.2451 +  */
  1.2452 +  if( pName ){
  1.2453 +    zName = sqlite3NameFromToken(db, pName);
  1.2454 +    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
  1.2455 +    if( zName==0 ) goto exit_create_index;
  1.2456 +    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  1.2457 +      goto exit_create_index;
  1.2458 +    }
  1.2459 +    if( !db->init.busy ){
  1.2460 +      if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
  1.2461 +      if( sqlite3FindTable(db, zName, 0)!=0 ){
  1.2462 +        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  1.2463 +        goto exit_create_index;
  1.2464 +      }
  1.2465 +    }
  1.2466 +    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  1.2467 +      if( !ifNotExist ){
  1.2468 +        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  1.2469 +      }
  1.2470 +      goto exit_create_index;
  1.2471 +    }
  1.2472 +  }else{
  1.2473 +    int n;
  1.2474 +    Index *pLoop;
  1.2475 +    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  1.2476 +    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  1.2477 +    if( zName==0 ){
  1.2478 +      goto exit_create_index;
  1.2479 +    }
  1.2480 +  }
  1.2481 +
  1.2482 +  /* Check for authorization to create an index.
  1.2483 +  */
  1.2484 +#ifndef SQLITE_OMIT_AUTHORIZATION
  1.2485 +  {
  1.2486 +    const char *zDb = pDb->zName;
  1.2487 +    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  1.2488 +      goto exit_create_index;
  1.2489 +    }
  1.2490 +    i = SQLITE_CREATE_INDEX;
  1.2491 +    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  1.2492 +    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  1.2493 +      goto exit_create_index;
  1.2494 +    }
  1.2495 +  }
  1.2496 +#endif
  1.2497 +
  1.2498 +  /* If pList==0, it means this routine was called to make a primary
  1.2499 +  ** key out of the last column added to the table under construction.
  1.2500 +  ** So create a fake list to simulate this.
  1.2501 +  */
  1.2502 +  if( pList==0 ){
  1.2503 +    nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
  1.2504 +    nullId.n = strlen((char*)nullId.z);
  1.2505 +    pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
  1.2506 +    if( pList==0 ) goto exit_create_index;
  1.2507 +    pList->a[0].sortOrder = sortOrder;
  1.2508 +  }
  1.2509 +
  1.2510 +  /* Figure out how many bytes of space are required to store explicitly
  1.2511 +  ** specified collation sequence names.
  1.2512 +  */
  1.2513 +  for(i=0; i<pList->nExpr; i++){
  1.2514 +    Expr *pExpr;
  1.2515 +    CollSeq *pColl;
  1.2516 +    if( (pExpr = pList->a[i].pExpr)!=0 && (pColl = pExpr->pColl)!=0 ){
  1.2517 +      nExtra += (1 + strlen(pColl->zName));
  1.2518 +    }
  1.2519 +  }
  1.2520 +
  1.2521 +  /* 
  1.2522 +  ** Allocate the index structure. 
  1.2523 +  */
  1.2524 +  nName = strlen(zName);
  1.2525 +  nCol = pList->nExpr;
  1.2526 +  pIndex = sqlite3DbMallocZero(db, 
  1.2527 +      sizeof(Index) +              /* Index structure  */
  1.2528 +      sizeof(int)*nCol +           /* Index.aiColumn   */
  1.2529 +      sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
  1.2530 +      sizeof(char *)*nCol +        /* Index.azColl     */
  1.2531 +      sizeof(u8)*nCol +            /* Index.aSortOrder */
  1.2532 +      nName + 1 +                  /* Index.zName      */
  1.2533 +      nExtra                       /* Collation sequence names */
  1.2534 +  );
  1.2535 +  if( db->mallocFailed ){
  1.2536 +    goto exit_create_index;
  1.2537 +  }
  1.2538 +  pIndex->azColl = (char**)(&pIndex[1]);
  1.2539 +  pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
  1.2540 +  pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
  1.2541 +  pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
  1.2542 +  pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
  1.2543 +  zExtra = (char *)(&pIndex->zName[nName+1]);
  1.2544 +  memcpy(pIndex->zName, zName, nName+1);
  1.2545 +  pIndex->pTable = pTab;
  1.2546 +  pIndex->nColumn = pList->nExpr;
  1.2547 +  pIndex->onError = onError;
  1.2548 +  pIndex->autoIndex = pName==0;
  1.2549 +  pIndex->pSchema = db->aDb[iDb].pSchema;
  1.2550 +
  1.2551 +  /* Check to see if we should honor DESC requests on index columns
  1.2552 +  */
  1.2553 +  if( pDb->pSchema->file_format>=4 ){
  1.2554 +    sortOrderMask = -1;   /* Honor DESC */
  1.2555 +  }else{
  1.2556 +    sortOrderMask = 0;    /* Ignore DESC */
  1.2557 +  }
  1.2558 +
  1.2559 +  /* Scan the names of the columns of the table to be indexed and
  1.2560 +  ** load the column indices into the Index structure.  Report an error
  1.2561 +  ** if any column is not found.
  1.2562 +  */
  1.2563 +  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  1.2564 +    const char *zColName = pListItem->zName;
  1.2565 +    Column *pTabCol;
  1.2566 +    int requestedSortOrder;
  1.2567 +    char *zColl;                   /* Collation sequence name */
  1.2568 +
  1.2569 +    for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
  1.2570 +      if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
  1.2571 +    }
  1.2572 +    if( j>=pTab->nCol ){
  1.2573 +      sqlite3ErrorMsg(pParse, "table %s has no column named %s",
  1.2574 +        pTab->zName, zColName);
  1.2575 +      goto exit_create_index;
  1.2576 +    }
  1.2577 +    /* TODO:  Add a test to make sure that the same column is not named
  1.2578 +    ** more than once within the same index.  Only the first instance of
  1.2579 +    ** the column will ever be used by the optimizer.  Note that using the
  1.2580 +    ** same column more than once cannot be an error because that would 
  1.2581 +    ** break backwards compatibility - it needs to be a warning.
  1.2582 +    */
  1.2583 +    pIndex->aiColumn[i] = j;
  1.2584 +    if( pListItem->pExpr && pListItem->pExpr->pColl ){
  1.2585 +      assert( pListItem->pExpr->pColl );
  1.2586 +      zColl = zExtra;
  1.2587 +      sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName);
  1.2588 +      zExtra += (strlen(zColl) + 1);
  1.2589 +    }else{
  1.2590 +      zColl = pTab->aCol[j].zColl;
  1.2591 +      if( !zColl ){
  1.2592 +        zColl = db->pDfltColl->zName;
  1.2593 +      }
  1.2594 +    }
  1.2595 +    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
  1.2596 +      goto exit_create_index;
  1.2597 +    }
  1.2598 +    pIndex->azColl[i] = zColl;
  1.2599 +    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  1.2600 +    pIndex->aSortOrder[i] = requestedSortOrder;
  1.2601 +  }
  1.2602 +  sqlite3DefaultRowEst(pIndex);
  1.2603 +
  1.2604 +  if( pTab==pParse->pNewTable ){
  1.2605 +    /* This routine has been called to create an automatic index as a
  1.2606 +    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  1.2607 +    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  1.2608 +    ** i.e. one of:
  1.2609 +    **
  1.2610 +    ** CREATE TABLE t(x PRIMARY KEY, y);
  1.2611 +    ** CREATE TABLE t(x, y, UNIQUE(x, y));
  1.2612 +    **
  1.2613 +    ** Either way, check to see if the table already has such an index. If
  1.2614 +    ** so, don't bother creating this one. This only applies to
  1.2615 +    ** automatically created indices. Users can do as they wish with
  1.2616 +    ** explicit indices.
  1.2617 +    */
  1.2618 +    Index *pIdx;
  1.2619 +    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  1.2620 +      int k;
  1.2621 +      assert( pIdx->onError!=OE_None );
  1.2622 +      assert( pIdx->autoIndex );
  1.2623 +      assert( pIndex->onError!=OE_None );
  1.2624 +
  1.2625 +      if( pIdx->nColumn!=pIndex->nColumn ) continue;
  1.2626 +      for(k=0; k<pIdx->nColumn; k++){
  1.2627 +        const char *z1 = pIdx->azColl[k];
  1.2628 +        const char *z2 = pIndex->azColl[k];
  1.2629 +        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  1.2630 +        if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
  1.2631 +        if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  1.2632 +      }
  1.2633 +      if( k==pIdx->nColumn ){
  1.2634 +        if( pIdx->onError!=pIndex->onError ){
  1.2635 +          /* This constraint creates the same index as a previous
  1.2636 +          ** constraint specified somewhere in the CREATE TABLE statement.
  1.2637 +          ** However the ON CONFLICT clauses are different. If both this 
  1.2638 +          ** constraint and the previous equivalent constraint have explicit
  1.2639 +          ** ON CONFLICT clauses this is an error. Otherwise, use the
  1.2640 +          ** explicitly specified behaviour for the index.
  1.2641 +          */
  1.2642 +          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  1.2643 +            sqlite3ErrorMsg(pParse, 
  1.2644 +                "conflicting ON CONFLICT clauses specified", 0);
  1.2645 +          }
  1.2646 +          if( pIdx->onError==OE_Default ){
  1.2647 +            pIdx->onError = pIndex->onError;
  1.2648 +          }
  1.2649 +        }
  1.2650 +        goto exit_create_index;
  1.2651 +      }
  1.2652 +    }
  1.2653 +  }
  1.2654 +
  1.2655 +  /* Link the new Index structure to its table and to the other
  1.2656 +  ** in-memory database structures. 
  1.2657 +  */
  1.2658 +  if( db->init.busy ){
  1.2659 +    Index *p;
  1.2660 +    p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
  1.2661 +                         pIndex->zName, strlen(pIndex->zName)+1, pIndex);
  1.2662 +    if( p ){
  1.2663 +      assert( p==pIndex );  /* Malloc must have failed */
  1.2664 +      db->mallocFailed = 1;
  1.2665 +      goto exit_create_index;
  1.2666 +    }
  1.2667 +    db->flags |= SQLITE_InternChanges;
  1.2668 +    if( pTblName!=0 ){
  1.2669 +      pIndex->tnum = db->init.newTnum;
  1.2670 +    }
  1.2671 +  }
  1.2672 +
  1.2673 +  /* If the db->init.busy is 0 then create the index on disk.  This
  1.2674 +  ** involves writing the index into the master table and filling in the
  1.2675 +  ** index with the current table contents.
  1.2676 +  **
  1.2677 +  ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
  1.2678 +  ** command.  db->init.busy is 1 when a database is opened and 
  1.2679 +  ** CREATE INDEX statements are read out of the master table.  In
  1.2680 +  ** the latter case the index already exists on disk, which is why
  1.2681 +  ** we don't want to recreate it.
  1.2682 +  **
  1.2683 +  ** If pTblName==0 it means this index is generated as a primary key
  1.2684 +  ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
  1.2685 +  ** has just been created, it contains no data and the index initialization
  1.2686 +  ** step can be skipped.
  1.2687 +  */
  1.2688 +  else if( db->init.busy==0 ){
  1.2689 +    Vdbe *v;
  1.2690 +    char *zStmt;
  1.2691 +    int iMem = ++pParse->nMem;
  1.2692 +
  1.2693 +    v = sqlite3GetVdbe(pParse);
  1.2694 +    if( v==0 ) goto exit_create_index;
  1.2695 +
  1.2696 +
  1.2697 +    /* Create the rootpage for the index
  1.2698 +    */
  1.2699 +    sqlite3BeginWriteOperation(pParse, 1, iDb);
  1.2700 +    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  1.2701 +
  1.2702 +    /* Gather the complete text of the CREATE INDEX statement into
  1.2703 +    ** the zStmt variable
  1.2704 +    */
  1.2705 +    if( pStart && pEnd ){
  1.2706 +      /* A named index with an explicit CREATE INDEX statement */
  1.2707 +      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  1.2708 +        onError==OE_None ? "" : " UNIQUE",
  1.2709 +        pEnd->z - pName->z + 1,
  1.2710 +        pName->z);
  1.2711 +    }else{
  1.2712 +      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  1.2713 +      /* zStmt = sqlite3MPrintf(""); */
  1.2714 +      zStmt = 0;
  1.2715 +    }
  1.2716 +
  1.2717 +    /* Add an entry in sqlite_master for this index
  1.2718 +    */
  1.2719 +    sqlite3NestedParse(pParse, 
  1.2720 +        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  1.2721 +        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  1.2722 +        pIndex->zName,
  1.2723 +        pTab->zName,
  1.2724 +        iMem,
  1.2725 +        zStmt
  1.2726 +    );
  1.2727 +    sqlite3DbFree(db, zStmt);
  1.2728 +
  1.2729 +    /* Fill the index with data and reparse the schema. Code an OP_Expire
  1.2730 +    ** to invalidate all pre-compiled statements.
  1.2731 +    */
  1.2732 +    if( pTblName ){
  1.2733 +      sqlite3RefillIndex(pParse, pIndex, iMem);
  1.2734 +      sqlite3ChangeCookie(pParse, iDb);
  1.2735 +      sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
  1.2736 +         sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
  1.2737 +      sqlite3VdbeAddOp1(v, OP_Expire, 0);
  1.2738 +    }
  1.2739 +  }
  1.2740 +
  1.2741 +  /* When adding an index to the list of indices for a table, make
  1.2742 +  ** sure all indices labeled OE_Replace come after all those labeled
  1.2743 +  ** OE_Ignore.  This is necessary for the correct operation of UPDATE
  1.2744 +  ** and INSERT.
  1.2745 +  */
  1.2746 +  if( db->init.busy || pTblName==0 ){
  1.2747 +    if( onError!=OE_Replace || pTab->pIndex==0
  1.2748 +         || pTab->pIndex->onError==OE_Replace){
  1.2749 +      pIndex->pNext = pTab->pIndex;
  1.2750 +      pTab->pIndex = pIndex;
  1.2751 +    }else{
  1.2752 +      Index *pOther = pTab->pIndex;
  1.2753 +      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  1.2754 +        pOther = pOther->pNext;
  1.2755 +      }
  1.2756 +      pIndex->pNext = pOther->pNext;
  1.2757 +      pOther->pNext = pIndex;
  1.2758 +    }
  1.2759 +    pIndex = 0;
  1.2760 +  }
  1.2761 +
  1.2762 +  /* Clean up before exiting */
  1.2763 +exit_create_index:
  1.2764 +  if( pIndex ){
  1.2765 +    freeIndex(pIndex);
  1.2766 +  }
  1.2767 +  sqlite3ExprListDelete(db, pList);
  1.2768 +  sqlite3SrcListDelete(db, pTblName);
  1.2769 +  sqlite3DbFree(db, zName);
  1.2770 +  return;
  1.2771 +}
  1.2772 +
  1.2773 +/*
  1.2774 +** Generate code to make sure the file format number is at least minFormat.
  1.2775 +** The generated code will increase the file format number if necessary.
  1.2776 +*/
  1.2777 +void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  1.2778 +  Vdbe *v;
  1.2779 +  v = sqlite3GetVdbe(pParse);
  1.2780 +  if( v ){
  1.2781 +    int r1 = sqlite3GetTempReg(pParse);
  1.2782 +    int r2 = sqlite3GetTempReg(pParse);
  1.2783 +    int j1;
  1.2784 +    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, 1);
  1.2785 +    sqlite3VdbeUsesBtree(v, iDb);
  1.2786 +    sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
  1.2787 +    j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
  1.2788 +    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, r2);
  1.2789 +    sqlite3VdbeJumpHere(v, j1);
  1.2790 +    sqlite3ReleaseTempReg(pParse, r1);
  1.2791 +    sqlite3ReleaseTempReg(pParse, r2);
  1.2792 +  }
  1.2793 +}
  1.2794 +
  1.2795 +/*
  1.2796 +** Fill the Index.aiRowEst[] array with default information - information
  1.2797 +** to be used when we have not run the ANALYZE command.
  1.2798 +**
  1.2799 +** aiRowEst[0] is suppose to contain the number of elements in the index.
  1.2800 +** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
  1.2801 +** number of rows in the table that match any particular value of the
  1.2802 +** first column of the index.  aiRowEst[2] is an estimate of the number
  1.2803 +** of rows that match any particular combiniation of the first 2 columns
  1.2804 +** of the index.  And so forth.  It must always be the case that
  1.2805 +*
  1.2806 +**           aiRowEst[N]<=aiRowEst[N-1]
  1.2807 +**           aiRowEst[N]>=1
  1.2808 +**
  1.2809 +** Apart from that, we have little to go on besides intuition as to
  1.2810 +** how aiRowEst[] should be initialized.  The numbers generated here
  1.2811 +** are based on typical values found in actual indices.
  1.2812 +*/
  1.2813 +void sqlite3DefaultRowEst(Index *pIdx){
  1.2814 +  unsigned *a = pIdx->aiRowEst;
  1.2815 +  int i;
  1.2816 +  assert( a!=0 );
  1.2817 +  a[0] = 1000000;
  1.2818 +  for(i=pIdx->nColumn; i>=5; i--){
  1.2819 +    a[i] = 5;
  1.2820 +  }
  1.2821 +  while( i>=1 ){
  1.2822 +    a[i] = 11 - i;
  1.2823 +    i--;
  1.2824 +  }
  1.2825 +  if( pIdx->onError!=OE_None ){
  1.2826 +    a[pIdx->nColumn] = 1;
  1.2827 +  }
  1.2828 +}
  1.2829 +
  1.2830 +/*
  1.2831 +** This routine will drop an existing named index.  This routine
  1.2832 +** implements the DROP INDEX statement.
  1.2833 +*/
  1.2834 +void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  1.2835 +  Index *pIndex;
  1.2836 +  Vdbe *v;
  1.2837 +  sqlite3 *db = pParse->db;
  1.2838 +  int iDb;
  1.2839 +
  1.2840 +  if( pParse->nErr || db->mallocFailed ){
  1.2841 +    goto exit_drop_index;
  1.2842 +  }
  1.2843 +  assert( pName->nSrc==1 );
  1.2844 +  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  1.2845 +    goto exit_drop_index;
  1.2846 +  }
  1.2847 +  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  1.2848 +  if( pIndex==0 ){
  1.2849 +    if( !ifExists ){
  1.2850 +      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  1.2851 +    }
  1.2852 +    pParse->checkSchema = 1;
  1.2853 +    goto exit_drop_index;
  1.2854 +  }
  1.2855 +  if( pIndex->autoIndex ){
  1.2856 +    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  1.2857 +      "or PRIMARY KEY constraint cannot be dropped", 0);
  1.2858 +    goto exit_drop_index;
  1.2859 +  }
  1.2860 +  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  1.2861 +#ifndef SQLITE_OMIT_AUTHORIZATION
  1.2862 +  {
  1.2863 +    int code = SQLITE_DROP_INDEX;
  1.2864 +    Table *pTab = pIndex->pTable;
  1.2865 +    const char *zDb = db->aDb[iDb].zName;
  1.2866 +    const char *zTab = SCHEMA_TABLE(iDb);
  1.2867 +    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  1.2868 +      goto exit_drop_index;
  1.2869 +    }
  1.2870 +    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  1.2871 +    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  1.2872 +      goto exit_drop_index;
  1.2873 +    }
  1.2874 +  }
  1.2875 +#endif
  1.2876 +
  1.2877 +  /* Generate code to remove the index and from the master table */
  1.2878 +  v = sqlite3GetVdbe(pParse);
  1.2879 +  if( v ){
  1.2880 +    sqlite3BeginWriteOperation(pParse, 1, iDb);
  1.2881 +    sqlite3NestedParse(pParse,
  1.2882 +       "DELETE FROM %Q.%s WHERE name=%Q",
  1.2883 +       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  1.2884 +       pIndex->zName
  1.2885 +    );
  1.2886 +    if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
  1.2887 +      sqlite3NestedParse(pParse,
  1.2888 +        "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
  1.2889 +        db->aDb[iDb].zName, pIndex->zName
  1.2890 +      );
  1.2891 +    }
  1.2892 +    sqlite3ChangeCookie(pParse, iDb);
  1.2893 +    destroyRootPage(pParse, pIndex->tnum, iDb);
  1.2894 +    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  1.2895 +  }
  1.2896 +
  1.2897 +exit_drop_index:
  1.2898 +  sqlite3SrcListDelete(db, pName);
  1.2899 +}
  1.2900 +
  1.2901 +/*
  1.2902 +** pArray is a pointer to an array of objects.  Each object in the
  1.2903 +** array is szEntry bytes in size.  This routine allocates a new
  1.2904 +** object on the end of the array.
  1.2905 +**
  1.2906 +** *pnEntry is the number of entries already in use.  *pnAlloc is
  1.2907 +** the previously allocated size of the array.  initSize is the
  1.2908 +** suggested initial array size allocation.
  1.2909 +**
  1.2910 +** The index of the new entry is returned in *pIdx.
  1.2911 +**
  1.2912 +** This routine returns a pointer to the array of objects.  This
  1.2913 +** might be the same as the pArray parameter or it might be a different
  1.2914 +** pointer if the array was resized.
  1.2915 +*/
  1.2916 +void *sqlite3ArrayAllocate(
  1.2917 +  sqlite3 *db,      /* Connection to notify of malloc failures */
  1.2918 +  void *pArray,     /* Array of objects.  Might be reallocated */
  1.2919 +  int szEntry,      /* Size of each object in the array */
  1.2920 +  int initSize,     /* Suggested initial allocation, in elements */
  1.2921 +  int *pnEntry,     /* Number of objects currently in use */
  1.2922 +  int *pnAlloc,     /* Current size of the allocation, in elements */
  1.2923 +  int *pIdx         /* Write the index of a new slot here */
  1.2924 +){
  1.2925 +  char *z;
  1.2926 +  if( *pnEntry >= *pnAlloc ){
  1.2927 +    void *pNew;
  1.2928 +    int newSize;
  1.2929 +    newSize = (*pnAlloc)*2 + initSize;
  1.2930 +    pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
  1.2931 +    if( pNew==0 ){
  1.2932 +      *pIdx = -1;
  1.2933 +      return pArray;
  1.2934 +    }
  1.2935 +    *pnAlloc = newSize;
  1.2936 +    pArray = pNew;
  1.2937 +  }
  1.2938 +  z = (char*)pArray;
  1.2939 +  memset(&z[*pnEntry * szEntry], 0, szEntry);
  1.2940 +  *pIdx = *pnEntry;
  1.2941 +  ++*pnEntry;
  1.2942 +  return pArray;
  1.2943 +}
  1.2944 +
  1.2945 +/*
  1.2946 +** Append a new element to the given IdList.  Create a new IdList if
  1.2947 +** need be.
  1.2948 +**
  1.2949 +** A new IdList is returned, or NULL if malloc() fails.
  1.2950 +*/
  1.2951 +IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  1.2952 +  int i;
  1.2953 +  if( pList==0 ){
  1.2954 +    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  1.2955 +    if( pList==0 ) return 0;
  1.2956 +    pList->nAlloc = 0;
  1.2957 +  }
  1.2958 +  pList->a = sqlite3ArrayAllocate(
  1.2959 +      db,
  1.2960 +      pList->a,
  1.2961 +      sizeof(pList->a[0]),
  1.2962 +      5,
  1.2963 +      &pList->nId,
  1.2964 +      &pList->nAlloc,
  1.2965 +      &i
  1.2966 +  );
  1.2967 +  if( i<0 ){
  1.2968 +    sqlite3IdListDelete(db, pList);
  1.2969 +    return 0;
  1.2970 +  }
  1.2971 +  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  1.2972 +  return pList;
  1.2973 +}
  1.2974 +
  1.2975 +/*
  1.2976 +** Delete an IdList.
  1.2977 +*/
  1.2978 +void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  1.2979 +  int i;
  1.2980 +  if( pList==0 ) return;
  1.2981 +  for(i=0; i<pList->nId; i++){
  1.2982 +    sqlite3DbFree(db, pList->a[i].zName);
  1.2983 +  }
  1.2984 +  sqlite3DbFree(db, pList->a);
  1.2985 +  sqlite3DbFree(db, pList);
  1.2986 +}
  1.2987 +
  1.2988 +/*
  1.2989 +** Return the index in pList of the identifier named zId.  Return -1
  1.2990 +** if not found.
  1.2991 +*/
  1.2992 +int sqlite3IdListIndex(IdList *pList, const char *zName){
  1.2993 +  int i;
  1.2994 +  if( pList==0 ) return -1;
  1.2995 +  for(i=0; i<pList->nId; i++){
  1.2996 +    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  1.2997 +  }
  1.2998 +  return -1;
  1.2999 +}
  1.3000 +
  1.3001 +/*
  1.3002 +** Append a new table name to the given SrcList.  Create a new SrcList if
  1.3003 +** need be.  A new entry is created in the SrcList even if pToken is NULL.
  1.3004 +**
  1.3005 +** A new SrcList is returned, or NULL if malloc() fails.
  1.3006 +**
  1.3007 +** If pDatabase is not null, it means that the table has an optional
  1.3008 +** database name prefix.  Like this:  "database.table".  The pDatabase
  1.3009 +** points to the table name and the pTable points to the database name.
  1.3010 +** The SrcList.a[].zName field is filled with the table name which might
  1.3011 +** come from pTable (if pDatabase is NULL) or from pDatabase.  
  1.3012 +** SrcList.a[].zDatabase is filled with the database name from pTable,
  1.3013 +** or with NULL if no database is specified.
  1.3014 +**
  1.3015 +** In other words, if call like this:
  1.3016 +**
  1.3017 +**         sqlite3SrcListAppend(D,A,B,0);
  1.3018 +**
  1.3019 +** Then B is a table name and the database name is unspecified.  If called
  1.3020 +** like this:
  1.3021 +**
  1.3022 +**         sqlite3SrcListAppend(D,A,B,C);
  1.3023 +**
  1.3024 +** Then C is the table name and B is the database name.
  1.3025 +*/
  1.3026 +SrcList *sqlite3SrcListAppend(
  1.3027 +  sqlite3 *db,        /* Connection to notify of malloc failures */
  1.3028 +  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
  1.3029 +  Token *pTable,      /* Table to append */
  1.3030 +  Token *pDatabase    /* Database of the table */
  1.3031 +){
  1.3032 +  struct SrcList_item *pItem;
  1.3033 +  if( pList==0 ){
  1.3034 +    pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  1.3035 +    if( pList==0 ) return 0;
  1.3036 +    pList->nAlloc = 1;
  1.3037 +  }
  1.3038 +  if( pList->nSrc>=pList->nAlloc ){
  1.3039 +    SrcList *pNew;
  1.3040 +    pList->nAlloc *= 2;
  1.3041 +    pNew = sqlite3DbRealloc(db, pList,
  1.3042 +               sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
  1.3043 +    if( pNew==0 ){
  1.3044 +      sqlite3SrcListDelete(db, pList);
  1.3045 +      return 0;
  1.3046 +    }
  1.3047 +    pList = pNew;
  1.3048 +  }
  1.3049 +  pItem = &pList->a[pList->nSrc];
  1.3050 +  memset(pItem, 0, sizeof(pList->a[0]));
  1.3051 +  if( pDatabase && pDatabase->z==0 ){
  1.3052 +    pDatabase = 0;
  1.3053 +  }
  1.3054 +  if( pDatabase && pTable ){
  1.3055 +    Token *pTemp = pDatabase;
  1.3056 +    pDatabase = pTable;
  1.3057 +    pTable = pTemp;
  1.3058 +  }
  1.3059 +  pItem->zName = sqlite3NameFromToken(db, pTable);
  1.3060 +  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  1.3061 +  pItem->iCursor = -1;
  1.3062 +  pList->nSrc++;
  1.3063 +  return pList;
  1.3064 +}
  1.3065 +
  1.3066 +/*
  1.3067 +** Assign cursors to all tables in a SrcList
  1.3068 +*/
  1.3069 +void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  1.3070 +  int i;
  1.3071 +  struct SrcList_item *pItem;
  1.3072 +  assert(pList || pParse->db->mallocFailed );
  1.3073 +  if( pList ){
  1.3074 +    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  1.3075 +      if( pItem->iCursor>=0 ) break;
  1.3076 +      pItem->iCursor = pParse->nTab++;
  1.3077 +      if( pItem->pSelect ){
  1.3078 +        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  1.3079 +      }
  1.3080 +    }
  1.3081 +  }
  1.3082 +}
  1.3083 +
  1.3084 +/*
  1.3085 +** Delete an entire SrcList including all its substructure.
  1.3086 +*/
  1.3087 +void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  1.3088 +  int i;
  1.3089 +  struct SrcList_item *pItem;
  1.3090 +  if( pList==0 ) return;
  1.3091 +  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  1.3092 +    sqlite3DbFree(db, pItem->zDatabase);
  1.3093 +    sqlite3DbFree(db, pItem->zName);
  1.3094 +    sqlite3DbFree(db, pItem->zAlias);
  1.3095 +    sqlite3DbFree(db, pItem->zIndex);
  1.3096 +    sqlite3DeleteTable(pItem->pTab);
  1.3097 +    sqlite3SelectDelete(db, pItem->pSelect);
  1.3098 +    sqlite3ExprDelete(db, pItem->pOn);
  1.3099 +    sqlite3IdListDelete(db, pItem->pUsing);
  1.3100 +  }
  1.3101 +  sqlite3DbFree(db, pList);
  1.3102 +}
  1.3103 +
  1.3104 +/*
  1.3105 +** This routine is called by the parser to add a new term to the
  1.3106 +** end of a growing FROM clause.  The "p" parameter is the part of
  1.3107 +** the FROM clause that has already been constructed.  "p" is NULL
  1.3108 +** if this is the first term of the FROM clause.  pTable and pDatabase
  1.3109 +** are the name of the table and database named in the FROM clause term.
  1.3110 +** pDatabase is NULL if the database name qualifier is missing - the
  1.3111 +** usual case.  If the term has a alias, then pAlias points to the
  1.3112 +** alias token.  If the term is a subquery, then pSubquery is the
  1.3113 +** SELECT statement that the subquery encodes.  The pTable and
  1.3114 +** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
  1.3115 +** parameters are the content of the ON and USING clauses.
  1.3116 +**
  1.3117 +** Return a new SrcList which encodes is the FROM with the new
  1.3118 +** term added.
  1.3119 +*/
  1.3120 +SrcList *sqlite3SrcListAppendFromTerm(
  1.3121 +  Parse *pParse,          /* Parsing context */
  1.3122 +  SrcList *p,             /* The left part of the FROM clause already seen */
  1.3123 +  Token *pTable,          /* Name of the table to add to the FROM clause */
  1.3124 +  Token *pDatabase,       /* Name of the database containing pTable */
  1.3125 +  Token *pAlias,          /* The right-hand side of the AS subexpression */
  1.3126 +  Select *pSubquery,      /* A subquery used in place of a table name */
  1.3127 +  Expr *pOn,              /* The ON clause of a join */
  1.3128 +  IdList *pUsing          /* The USING clause of a join */
  1.3129 +){
  1.3130 +  struct SrcList_item *pItem;
  1.3131 +  sqlite3 *db = pParse->db;
  1.3132 +  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  1.3133 +  if( p==0 || p->nSrc==0 ){
  1.3134 +    sqlite3ExprDelete(db, pOn);
  1.3135 +    sqlite3IdListDelete(db, pUsing);
  1.3136 +    sqlite3SelectDelete(db, pSubquery);
  1.3137 +    return p;
  1.3138 +  }
  1.3139 +  pItem = &p->a[p->nSrc-1];
  1.3140 +  if( pAlias && pAlias->n ){
  1.3141 +    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  1.3142 +  }
  1.3143 +  pItem->pSelect = pSubquery;
  1.3144 +  pItem->pOn = pOn;
  1.3145 +  pItem->pUsing = pUsing;
  1.3146 +  return p;
  1.3147 +}
  1.3148 +
  1.3149 +/*
  1.3150 +** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
  1.3151 +** element of the source-list passed as the second argument.
  1.3152 +*/
  1.3153 +void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  1.3154 +  if( pIndexedBy && p && p->nSrc>0 ){
  1.3155 +    struct SrcList_item *pItem = &p->a[p->nSrc-1];
  1.3156 +    assert( pItem->notIndexed==0 && pItem->zIndex==0 );
  1.3157 +    if( pIndexedBy->n==1 && !pIndexedBy->z ){
  1.3158 +      /* A "NOT INDEXED" clause was supplied. See parse.y 
  1.3159 +      ** construct "indexed_opt" for details. */
  1.3160 +      pItem->notIndexed = 1;
  1.3161 +    }else{
  1.3162 +      pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
  1.3163 +    }
  1.3164 +  }
  1.3165 +}
  1.3166 +
  1.3167 +/*
  1.3168 +** When building up a FROM clause in the parser, the join operator
  1.3169 +** is initially attached to the left operand.  But the code generator
  1.3170 +** expects the join operator to be on the right operand.  This routine
  1.3171 +** Shifts all join operators from left to right for an entire FROM
  1.3172 +** clause.
  1.3173 +**
  1.3174 +** Example: Suppose the join is like this:
  1.3175 +**
  1.3176 +**           A natural cross join B
  1.3177 +**
  1.3178 +** The operator is "natural cross join".  The A and B operands are stored
  1.3179 +** in p->a[0] and p->a[1], respectively.  The parser initially stores the
  1.3180 +** operator with A.  This routine shifts that operator over to B.
  1.3181 +*/
  1.3182 +void sqlite3SrcListShiftJoinType(SrcList *p){
  1.3183 +  if( p && p->a ){
  1.3184 +    int i;
  1.3185 +    for(i=p->nSrc-1; i>0; i--){
  1.3186 +      p->a[i].jointype = p->a[i-1].jointype;
  1.3187 +    }
  1.3188 +    p->a[0].jointype = 0;
  1.3189 +  }
  1.3190 +}
  1.3191 +
  1.3192 +/*
  1.3193 +** Begin a transaction
  1.3194 +*/
  1.3195 +void sqlite3BeginTransaction(Parse *pParse, int type){
  1.3196 +  sqlite3 *db;
  1.3197 +  Vdbe *v;
  1.3198 +  int i;
  1.3199 +
  1.3200 +  if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  1.3201 +  if( pParse->nErr || db->mallocFailed ) return;
  1.3202 +  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
  1.3203 +
  1.3204 +  v = sqlite3GetVdbe(pParse);
  1.3205 +  if( !v ) return;
  1.3206 +  if( type!=TK_DEFERRED ){
  1.3207 +    for(i=0; i<db->nDb; i++){
  1.3208 +      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  1.3209 +      sqlite3VdbeUsesBtree(v, i);
  1.3210 +    }
  1.3211 +  }
  1.3212 +  sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  1.3213 +}
  1.3214 +
  1.3215 +/*
  1.3216 +** Commit a transaction
  1.3217 +*/
  1.3218 +void sqlite3CommitTransaction(Parse *pParse){
  1.3219 +  sqlite3 *db;
  1.3220 +  Vdbe *v;
  1.3221 +
  1.3222 +  if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  1.3223 +  if( pParse->nErr || db->mallocFailed ) return;
  1.3224 +  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
  1.3225 +
  1.3226 +  v = sqlite3GetVdbe(pParse);
  1.3227 +  if( v ){
  1.3228 +    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  1.3229 +  }
  1.3230 +}
  1.3231 +
  1.3232 +/*
  1.3233 +** Rollback a transaction
  1.3234 +*/
  1.3235 +void sqlite3RollbackTransaction(Parse *pParse){
  1.3236 +  sqlite3 *db;
  1.3237 +  Vdbe *v;
  1.3238 +
  1.3239 +  if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  1.3240 +  if( pParse->nErr || db->mallocFailed ) return;
  1.3241 +  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
  1.3242 +
  1.3243 +  v = sqlite3GetVdbe(pParse);
  1.3244 +  if( v ){
  1.3245 +    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  1.3246 +  }
  1.3247 +}
  1.3248 +
  1.3249 +/*
  1.3250 +** Make sure the TEMP database is open and available for use.  Return
  1.3251 +** the number of errors.  Leave any error messages in the pParse structure.
  1.3252 +*/
  1.3253 +int sqlite3OpenTempDatabase(Parse *pParse){
  1.3254 +  sqlite3 *db = pParse->db;
  1.3255 +  if( db->aDb[1].pBt==0 && !pParse->explain ){
  1.3256 +    int rc;
  1.3257 +    static const int flags = 
  1.3258 +          SQLITE_OPEN_READWRITE |
  1.3259 +          SQLITE_OPEN_CREATE |
  1.3260 +          SQLITE_OPEN_EXCLUSIVE |
  1.3261 +          SQLITE_OPEN_DELETEONCLOSE |
  1.3262 +          SQLITE_OPEN_TEMP_DB;
  1.3263 +
  1.3264 +    rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
  1.3265 +                                 &db->aDb[1].pBt);
  1.3266 +    if( rc!=SQLITE_OK ){
  1.3267 +      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  1.3268 +        "file for storing temporary tables");
  1.3269 +      pParse->rc = rc;
  1.3270 +      return 1;
  1.3271 +    }
  1.3272 +    assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit );
  1.3273 +    assert( db->aDb[1].pSchema );
  1.3274 +    sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
  1.3275 +                            db->dfltJournalMode);
  1.3276 +  }
  1.3277 +  return 0;
  1.3278 +}
  1.3279 +
  1.3280 +/*
  1.3281 +** Generate VDBE code that will verify the schema cookie and start
  1.3282 +** a read-transaction for all named database files.
  1.3283 +**
  1.3284 +** It is important that all schema cookies be verified and all
  1.3285 +** read transactions be started before anything else happens in
  1.3286 +** the VDBE program.  But this routine can be called after much other
  1.3287 +** code has been generated.  So here is what we do:
  1.3288 +**
  1.3289 +** The first time this routine is called, we code an OP_Goto that
  1.3290 +** will jump to a subroutine at the end of the program.  Then we
  1.3291 +** record every database that needs its schema verified in the
  1.3292 +** pParse->cookieMask field.  Later, after all other code has been
  1.3293 +** generated, the subroutine that does the cookie verifications and
  1.3294 +** starts the transactions will be coded and the OP_Goto P2 value
  1.3295 +** will be made to point to that subroutine.  The generation of the
  1.3296 +** cookie verification subroutine code happens in sqlite3FinishCoding().
  1.3297 +**
  1.3298 +** If iDb<0 then code the OP_Goto only - don't set flag to verify the
  1.3299 +** schema on any databases.  This can be used to position the OP_Goto
  1.3300 +** early in the code, before we know if any database tables will be used.
  1.3301 +*/
  1.3302 +void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  1.3303 +  sqlite3 *db;
  1.3304 +  Vdbe *v;
  1.3305 +  int mask;
  1.3306 +
  1.3307 +  v = sqlite3GetVdbe(pParse);
  1.3308 +  if( v==0 ) return;  /* This only happens if there was a prior error */
  1.3309 +  db = pParse->db;
  1.3310 +  if( pParse->cookieGoto==0 ){
  1.3311 +    pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
  1.3312 +  }
  1.3313 +  if( iDb>=0 ){
  1.3314 +    assert( iDb<db->nDb );
  1.3315 +    assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  1.3316 +    assert( iDb<SQLITE_MAX_ATTACHED+2 );
  1.3317 +    mask = 1<<iDb;
  1.3318 +    if( (pParse->cookieMask & mask)==0 ){
  1.3319 +      pParse->cookieMask |= mask;
  1.3320 +      pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  1.3321 +      if( !OMIT_TEMPDB && iDb==1 ){
  1.3322 +        sqlite3OpenTempDatabase(pParse);
  1.3323 +      }
  1.3324 +    }
  1.3325 +  }
  1.3326 +}
  1.3327 +
  1.3328 +/*
  1.3329 +** Generate VDBE code that prepares for doing an operation that
  1.3330 +** might change the database.
  1.3331 +**
  1.3332 +** This routine starts a new transaction if we are not already within
  1.3333 +** a transaction.  If we are already within a transaction, then a checkpoint
  1.3334 +** is set if the setStatement parameter is true.  A checkpoint should
  1.3335 +** be set for operations that might fail (due to a constraint) part of
  1.3336 +** the way through and which will need to undo some writes without having to
  1.3337 +** rollback the whole transaction.  For operations where all constraints
  1.3338 +** can be checked before any changes are made to the database, it is never
  1.3339 +** necessary to undo a write and the checkpoint should not be set.
  1.3340 +**
  1.3341 +** Only database iDb and the temp database are made writable by this call.
  1.3342 +** If iDb==0, then the main and temp databases are made writable.   If
  1.3343 +** iDb==1 then only the temp database is made writable.  If iDb>1 then the
  1.3344 +** specified auxiliary database and the temp database are made writable.
  1.3345 +*/
  1.3346 +void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  1.3347 +  Vdbe *v = sqlite3GetVdbe(pParse);
  1.3348 +  if( v==0 ) return;
  1.3349 +  sqlite3CodeVerifySchema(pParse, iDb);
  1.3350 +  pParse->writeMask |= 1<<iDb;
  1.3351 +  if( setStatement && pParse->nested==0 ){
  1.3352 +    sqlite3VdbeAddOp1(v, OP_Statement, iDb);
  1.3353 +  }
  1.3354 +  if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
  1.3355 +    sqlite3BeginWriteOperation(pParse, setStatement, 1);
  1.3356 +  }
  1.3357 +}
  1.3358 +
  1.3359 +/*
  1.3360 +** Check to see if pIndex uses the collating sequence pColl.  Return
  1.3361 +** true if it does and false if it does not.
  1.3362 +*/
  1.3363 +#ifndef SQLITE_OMIT_REINDEX
  1.3364 +static int collationMatch(const char *zColl, Index *pIndex){
  1.3365 +  int i;
  1.3366 +  for(i=0; i<pIndex->nColumn; i++){
  1.3367 +    const char *z = pIndex->azColl[i];
  1.3368 +    if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
  1.3369 +      return 1;
  1.3370 +    }
  1.3371 +  }
  1.3372 +  return 0;
  1.3373 +}
  1.3374 +#endif
  1.3375 +
  1.3376 +/*
  1.3377 +** Recompute all indices of pTab that use the collating sequence pColl.
  1.3378 +** If pColl==0 then recompute all indices of pTab.
  1.3379 +*/
  1.3380 +#ifndef SQLITE_OMIT_REINDEX
  1.3381 +static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  1.3382 +  Index *pIndex;              /* An index associated with pTab */
  1.3383 +
  1.3384 +  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  1.3385 +    if( zColl==0 || collationMatch(zColl, pIndex) ){
  1.3386 +      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  1.3387 +      sqlite3BeginWriteOperation(pParse, 0, iDb);
  1.3388 +      sqlite3RefillIndex(pParse, pIndex, -1);
  1.3389 +    }
  1.3390 +  }
  1.3391 +}
  1.3392 +#endif
  1.3393 +
  1.3394 +/*
  1.3395 +** Recompute all indices of all tables in all databases where the
  1.3396 +** indices use the collating sequence pColl.  If pColl==0 then recompute
  1.3397 +** all indices everywhere.
  1.3398 +*/
  1.3399 +#ifndef SQLITE_OMIT_REINDEX
  1.3400 +static void reindexDatabases(Parse *pParse, char const *zColl){
  1.3401 +  Db *pDb;                    /* A single database */
  1.3402 +  int iDb;                    /* The database index number */
  1.3403 +  sqlite3 *db = pParse->db;   /* The database connection */
  1.3404 +  HashElem *k;                /* For looping over tables in pDb */
  1.3405 +  Table *pTab;                /* A table in the database */
  1.3406 +
  1.3407 +  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  1.3408 +    assert( pDb!=0 );
  1.3409 +    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
  1.3410 +      pTab = (Table*)sqliteHashData(k);
  1.3411 +      reindexTable(pParse, pTab, zColl);
  1.3412 +    }
  1.3413 +  }
  1.3414 +}
  1.3415 +#endif
  1.3416 +
  1.3417 +/*
  1.3418 +** Generate code for the REINDEX command.
  1.3419 +**
  1.3420 +**        REINDEX                            -- 1
  1.3421 +**        REINDEX  <collation>               -- 2
  1.3422 +**        REINDEX  ?<database>.?<tablename>  -- 3
  1.3423 +**        REINDEX  ?<database>.?<indexname>  -- 4
  1.3424 +**
  1.3425 +** Form 1 causes all indices in all attached databases to be rebuilt.
  1.3426 +** Form 2 rebuilds all indices in all databases that use the named
  1.3427 +** collating function.  Forms 3 and 4 rebuild the named index or all
  1.3428 +** indices associated with the named table.
  1.3429 +*/
  1.3430 +#ifndef SQLITE_OMIT_REINDEX
  1.3431 +void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  1.3432 +  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
  1.3433 +  char *z;                    /* Name of a table or index */
  1.3434 +  const char *zDb;            /* Name of the database */
  1.3435 +  Table *pTab;                /* A table in the database */
  1.3436 +  Index *pIndex;              /* An index associated with pTab */
  1.3437 +  int iDb;                    /* The database index number */
  1.3438 +  sqlite3 *db = pParse->db;   /* The database connection */
  1.3439 +  Token *pObjName;            /* Name of the table or index to be reindexed */
  1.3440 +
  1.3441 +  /* Read the database schema. If an error occurs, leave an error message
  1.3442 +  ** and code in pParse and return NULL. */
  1.3443 +  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  1.3444 +    return;
  1.3445 +  }
  1.3446 +
  1.3447 +  if( pName1==0 || pName1->z==0 ){
  1.3448 +    reindexDatabases(pParse, 0);
  1.3449 +    return;
  1.3450 +  }else if( pName2==0 || pName2->z==0 ){
  1.3451 +    char *zColl;
  1.3452 +    assert( pName1->z );
  1.3453 +    zColl = sqlite3NameFromToken(pParse->db, pName1);
  1.3454 +    if( !zColl ) return;
  1.3455 +    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
  1.3456 +    if( pColl ){
  1.3457 +      if( zColl ){
  1.3458 +        reindexDatabases(pParse, zColl);
  1.3459 +        sqlite3DbFree(db, zColl);
  1.3460 +      }
  1.3461 +      return;
  1.3462 +    }
  1.3463 +    sqlite3DbFree(db, zColl);
  1.3464 +  }
  1.3465 +  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  1.3466 +  if( iDb<0 ) return;
  1.3467 +  z = sqlite3NameFromToken(db, pObjName);
  1.3468 +  if( z==0 ) return;
  1.3469 +  zDb = db->aDb[iDb].zName;
  1.3470 +  pTab = sqlite3FindTable(db, z, zDb);
  1.3471 +  if( pTab ){
  1.3472 +    reindexTable(pParse, pTab, 0);
  1.3473 +    sqlite3DbFree(db, z);
  1.3474 +    return;
  1.3475 +  }
  1.3476 +  pIndex = sqlite3FindIndex(db, z, zDb);
  1.3477 +  sqlite3DbFree(db, z);
  1.3478 +  if( pIndex ){
  1.3479 +    sqlite3BeginWriteOperation(pParse, 0, iDb);
  1.3480 +    sqlite3RefillIndex(pParse, pIndex, -1);
  1.3481 +    return;
  1.3482 +  }
  1.3483 +  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  1.3484 +}
  1.3485 +#endif
  1.3486 +
  1.3487 +/*
  1.3488 +** Return a dynamicly allocated KeyInfo structure that can be used
  1.3489 +** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
  1.3490 +**
  1.3491 +** If successful, a pointer to the new structure is returned. In this case
  1.3492 +** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
  1.3493 +** pointer. If an error occurs (out of memory or missing collation 
  1.3494 +** sequence), NULL is returned and the state of pParse updated to reflect
  1.3495 +** the error.
  1.3496 +*/
  1.3497 +KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
  1.3498 +  int i;
  1.3499 +  int nCol = pIdx->nColumn;
  1.3500 +  int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
  1.3501 +  sqlite3 *db = pParse->db;
  1.3502 +  KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
  1.3503 +
  1.3504 +  if( pKey ){
  1.3505 +    pKey->db = pParse->db;
  1.3506 +    pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
  1.3507 +    assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
  1.3508 +    for(i=0; i<nCol; i++){
  1.3509 +      char *zColl = pIdx->azColl[i];
  1.3510 +      assert( zColl );
  1.3511 +      pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
  1.3512 +      pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  1.3513 +    }
  1.3514 +    pKey->nField = nCol;
  1.3515 +  }
  1.3516 +
  1.3517 +  if( pParse->nErr ){
  1.3518 +    sqlite3DbFree(db, pKey);
  1.3519 +    pKey = 0;
  1.3520 +  }
  1.3521 +  return pKey;
  1.3522 +}