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