persistentstorage/sql/SQLite/build.c
changeset 0 08ec8eefde2f
equal deleted inserted replaced
-1:000000000000 0:08ec8eefde2f
       
     1 /*
       
     2 ** 2001 September 15
       
     3 **
       
     4 ** The author disclaims copyright to this source code.  In place of
       
     5 ** a legal notice, here is a blessing:
       
     6 **
       
     7 **    May you do good and not evil.
       
     8 **    May you find forgiveness for yourself and forgive others.
       
     9 **    May you share freely, never taking more than you give.
       
    10 **
       
    11 *************************************************************************
       
    12 ** This file contains C code routines that are called by the SQLite parser
       
    13 ** when syntax rules are reduced.  The routines in this file handle the
       
    14 ** following kinds of SQL syntax:
       
    15 **
       
    16 **     CREATE TABLE
       
    17 **     DROP TABLE
       
    18 **     CREATE INDEX
       
    19 **     DROP INDEX
       
    20 **     creating ID lists
       
    21 **     BEGIN TRANSACTION
       
    22 **     COMMIT
       
    23 **     ROLLBACK
       
    24 **
       
    25 ** $Id: build.c,v 1.493 2008/08/04 04:39:49 danielk1977 Exp $
       
    26 */
       
    27 #include "sqliteInt.h"
       
    28 #include <ctype.h>
       
    29 
       
    30 /*
       
    31 ** This routine is called when a new SQL statement is beginning to
       
    32 ** be parsed.  Initialize the pParse structure as needed.
       
    33 */
       
    34 void sqlite3BeginParse(Parse *pParse, int explainFlag){
       
    35   pParse->explain = explainFlag;
       
    36   pParse->nVar = 0;
       
    37 }
       
    38 
       
    39 #ifndef SQLITE_OMIT_SHARED_CACHE
       
    40 /*
       
    41 ** The TableLock structure is only used by the sqlite3TableLock() and
       
    42 ** codeTableLocks() functions.
       
    43 */
       
    44 struct TableLock {
       
    45   int iDb;             /* The database containing the table to be locked */
       
    46   int iTab;            /* The root page of the table to be locked */
       
    47   u8 isWriteLock;      /* True for write lock.  False for a read lock */
       
    48   const char *zName;   /* Name of the table */
       
    49 };
       
    50 
       
    51 /*
       
    52 ** Record the fact that we want to lock a table at run-time.  
       
    53 **
       
    54 ** The table to be locked has root page iTab and is found in database iDb.
       
    55 ** A read or a write lock can be taken depending on isWritelock.
       
    56 **
       
    57 ** This routine just records the fact that the lock is desired.  The
       
    58 ** code to make the lock occur is generated by a later call to
       
    59 ** codeTableLocks() which occurs during sqlite3FinishCoding().
       
    60 */
       
    61 void sqlite3TableLock(
       
    62   Parse *pParse,     /* Parsing context */
       
    63   int iDb,           /* Index of the database containing the table to lock */
       
    64   int iTab,          /* Root page number of the table to be locked */
       
    65   u8 isWriteLock,    /* True for a write lock */
       
    66   const char *zName  /* Name of the table to be locked */
       
    67 ){
       
    68   int i;
       
    69   int nBytes;
       
    70   TableLock *p;
       
    71 
       
    72   if( iDb<0 ){
       
    73     return;
       
    74   }
       
    75 
       
    76   for(i=0; i<pParse->nTableLock; i++){
       
    77     p = &pParse->aTableLock[i];
       
    78     if( p->iDb==iDb && p->iTab==iTab ){
       
    79       p->isWriteLock = (p->isWriteLock || isWriteLock);
       
    80       return;
       
    81     }
       
    82   }
       
    83 
       
    84   nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
       
    85   pParse->aTableLock = 
       
    86       sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
       
    87   if( pParse->aTableLock ){
       
    88     p = &pParse->aTableLock[pParse->nTableLock++];
       
    89     p->iDb = iDb;
       
    90     p->iTab = iTab;
       
    91     p->isWriteLock = isWriteLock;
       
    92     p->zName = zName;
       
    93   }else{
       
    94     pParse->nTableLock = 0;
       
    95     pParse->db->mallocFailed = 1;
       
    96   }
       
    97 }
       
    98 
       
    99 /*
       
   100 ** Code an OP_TableLock instruction for each table locked by the
       
   101 ** statement (configured by calls to sqlite3TableLock()).
       
   102 */
       
   103 static void codeTableLocks(Parse *pParse){
       
   104   int i;
       
   105   Vdbe *pVdbe; 
       
   106 
       
   107   if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
       
   108     return;
       
   109   }
       
   110 
       
   111   for(i=0; i<pParse->nTableLock; i++){
       
   112     TableLock *p = &pParse->aTableLock[i];
       
   113     int p1 = p->iDb;
       
   114     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
       
   115                       p->zName, P4_STATIC);
       
   116   }
       
   117 }
       
   118 #else
       
   119   #define codeTableLocks(x)
       
   120 #endif
       
   121 
       
   122 /*
       
   123 ** This routine is called after a single SQL statement has been
       
   124 ** parsed and a VDBE program to execute that statement has been
       
   125 ** prepared.  This routine puts the finishing touches on the
       
   126 ** VDBE program and resets the pParse structure for the next
       
   127 ** parse.
       
   128 **
       
   129 ** Note that if an error occurred, it might be the case that
       
   130 ** no VDBE code was generated.
       
   131 */
       
   132 void sqlite3FinishCoding(Parse *pParse){
       
   133   sqlite3 *db;
       
   134   Vdbe *v;
       
   135 
       
   136   db = pParse->db;
       
   137   if( db->mallocFailed ) return;
       
   138   if( pParse->nested ) return;
       
   139   if( pParse->nErr ) return;
       
   140 
       
   141   /* Begin by generating some termination code at the end of the
       
   142   ** vdbe program
       
   143   */
       
   144   v = sqlite3GetVdbe(pParse);
       
   145   if( v ){
       
   146     sqlite3VdbeAddOp0(v, OP_Halt);
       
   147 
       
   148     /* The cookie mask contains one bit for each database file open.
       
   149     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
       
   150     ** set for each database that is used.  Generate code to start a
       
   151     ** transaction on each used database and to verify the schema cookie
       
   152     ** on each used database.
       
   153     */
       
   154     if( pParse->cookieGoto>0 ){
       
   155       u32 mask;
       
   156       int iDb;
       
   157       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
       
   158       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
       
   159         if( (mask & pParse->cookieMask)==0 ) continue;
       
   160         sqlite3VdbeUsesBtree(v, iDb);
       
   161         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
       
   162         sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
       
   163       }
       
   164 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
   165       {
       
   166         int i;
       
   167         for(i=0; i<pParse->nVtabLock; i++){
       
   168           char *vtab = (char *)pParse->apVtabLock[i]->pVtab;
       
   169           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
       
   170         }
       
   171         pParse->nVtabLock = 0;
       
   172       }
       
   173 #endif
       
   174 
       
   175       /* Once all the cookies have been verified and transactions opened, 
       
   176       ** obtain the required table-locks. This is a no-op unless the 
       
   177       ** shared-cache feature is enabled.
       
   178       */
       
   179       codeTableLocks(pParse);
       
   180       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
       
   181     }
       
   182 
       
   183 #ifndef SQLITE_OMIT_TRACE
       
   184     if( !db->init.busy ){
       
   185       /* Change the P4 argument of the first opcode (which will always be
       
   186       ** an OP_Trace) to be the complete text of the current SQL statement.
       
   187       */
       
   188       VdbeOp *pOp = sqlite3VdbeGetOp(v, 0);
       
   189       if( pOp && pOp->opcode==OP_Trace ){
       
   190         sqlite3VdbeChangeP4(v, 0, pParse->zSql, pParse->zTail-pParse->zSql);
       
   191       }
       
   192     }
       
   193 #endif /* SQLITE_OMIT_TRACE */
       
   194   }
       
   195 
       
   196 
       
   197   /* Get the VDBE program ready for execution
       
   198   */
       
   199   if( v && pParse->nErr==0 && !db->mallocFailed ){
       
   200 #ifdef SQLITE_DEBUG
       
   201     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
       
   202     sqlite3VdbeTrace(v, trace);
       
   203 #endif
       
   204     assert( pParse->disableColCache==0 );  /* Disables and re-enables match */
       
   205     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
       
   206                          pParse->nTab+3, pParse->explain);
       
   207     pParse->rc = SQLITE_DONE;
       
   208     pParse->colNamesSet = 0;
       
   209   }else if( pParse->rc==SQLITE_OK ){
       
   210     pParse->rc = SQLITE_ERROR;
       
   211   }
       
   212   pParse->nTab = 0;
       
   213   pParse->nMem = 0;
       
   214   pParse->nSet = 0;
       
   215   pParse->nVar = 0;
       
   216   pParse->cookieMask = 0;
       
   217   pParse->cookieGoto = 0;
       
   218 }
       
   219 
       
   220 /*
       
   221 ** Run the parser and code generator recursively in order to generate
       
   222 ** code for the SQL statement given onto the end of the pParse context
       
   223 ** currently under construction.  When the parser is run recursively
       
   224 ** this way, the final OP_Halt is not appended and other initialization
       
   225 ** and finalization steps are omitted because those are handling by the
       
   226 ** outermost parser.
       
   227 **
       
   228 ** Not everything is nestable.  This facility is designed to permit
       
   229 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
       
   230 ** care if you decide to try to use this routine for some other purposes.
       
   231 */
       
   232 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
       
   233   va_list ap;
       
   234   char *zSql;
       
   235   char *zErrMsg = 0;
       
   236   sqlite3 *db = pParse->db;
       
   237 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
       
   238   char saveBuf[SAVE_SZ];
       
   239 
       
   240   if( pParse->nErr ) return;
       
   241   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
       
   242   va_start(ap, zFormat);
       
   243   zSql = sqlite3VMPrintf(db, zFormat, ap);
       
   244   va_end(ap);
       
   245   if( zSql==0 ){
       
   246     return;   /* A malloc must have failed */
       
   247   }
       
   248   pParse->nested++;
       
   249   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
       
   250   memset(&pParse->nVar, 0, SAVE_SZ);
       
   251   sqlite3RunParser(pParse, zSql, &zErrMsg);
       
   252   sqlite3DbFree(db, zErrMsg);
       
   253   sqlite3DbFree(db, zSql);
       
   254   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
       
   255   pParse->nested--;
       
   256 }
       
   257 
       
   258 /*
       
   259 ** Locate the in-memory structure that describes a particular database
       
   260 ** table given the name of that table and (optionally) the name of the
       
   261 ** database containing the table.  Return NULL if not found.
       
   262 **
       
   263 ** If zDatabase is 0, all databases are searched for the table and the
       
   264 ** first matching table is returned.  (No checking for duplicate table
       
   265 ** names is done.)  The search order is TEMP first, then MAIN, then any
       
   266 ** auxiliary databases added using the ATTACH command.
       
   267 **
       
   268 ** See also sqlite3LocateTable().
       
   269 */
       
   270 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
       
   271   Table *p = 0;
       
   272   int i;
       
   273   int nName;
       
   274   assert( zName!=0 );
       
   275   nName = sqlite3Strlen(db, zName) + 1;
       
   276   for(i=OMIT_TEMPDB; i<db->nDb; i++){
       
   277     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
       
   278     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
       
   279     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
       
   280     if( p ) break;
       
   281   }
       
   282   return p;
       
   283 }
       
   284 
       
   285 /*
       
   286 ** Locate the in-memory structure that describes a particular database
       
   287 ** table given the name of that table and (optionally) the name of the
       
   288 ** database containing the table.  Return NULL if not found.  Also leave an
       
   289 ** error message in pParse->zErrMsg.
       
   290 **
       
   291 ** The difference between this routine and sqlite3FindTable() is that this
       
   292 ** routine leaves an error message in pParse->zErrMsg where
       
   293 ** sqlite3FindTable() does not.
       
   294 */
       
   295 Table *sqlite3LocateTable(
       
   296   Parse *pParse,         /* context in which to report errors */
       
   297   int isView,            /* True if looking for a VIEW rather than a TABLE */
       
   298   const char *zName,     /* Name of the table we are looking for */
       
   299   const char *zDbase     /* Name of the database.  Might be NULL */
       
   300 ){
       
   301   Table *p;
       
   302 
       
   303   /* Read the database schema. If an error occurs, leave an error message
       
   304   ** and code in pParse and return NULL. */
       
   305   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
       
   306     return 0;
       
   307   }
       
   308 
       
   309   p = sqlite3FindTable(pParse->db, zName, zDbase);
       
   310   if( p==0 ){
       
   311     const char *zMsg = isView ? "no such view" : "no such table";
       
   312     if( zDbase ){
       
   313       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
       
   314     }else{
       
   315       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
       
   316     }
       
   317     pParse->checkSchema = 1;
       
   318   }
       
   319   return p;
       
   320 }
       
   321 
       
   322 /*
       
   323 ** Locate the in-memory structure that describes 
       
   324 ** a particular index given the name of that index
       
   325 ** and the name of the database that contains the index.
       
   326 ** Return NULL if not found.
       
   327 **
       
   328 ** If zDatabase is 0, all databases are searched for the
       
   329 ** table and the first matching index is returned.  (No checking
       
   330 ** for duplicate index names is done.)  The search order is
       
   331 ** TEMP first, then MAIN, then any auxiliary databases added
       
   332 ** using the ATTACH command.
       
   333 */
       
   334 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
       
   335   Index *p = 0;
       
   336   int i;
       
   337   int nName = sqlite3Strlen(db, zName)+1;
       
   338   for(i=OMIT_TEMPDB; i<db->nDb; i++){
       
   339     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
       
   340     Schema *pSchema = db->aDb[j].pSchema;
       
   341     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
       
   342     assert( pSchema || (j==1 && !db->aDb[1].pBt) );
       
   343     if( pSchema ){
       
   344       p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
       
   345     }
       
   346     if( p ) break;
       
   347   }
       
   348   return p;
       
   349 }
       
   350 
       
   351 /*
       
   352 ** Reclaim the memory used by an index
       
   353 */
       
   354 static void freeIndex(Index *p){
       
   355   sqlite3 *db = p->pTable->db;
       
   356   sqlite3DbFree(db, p->zColAff);
       
   357   sqlite3DbFree(db, p);
       
   358 }
       
   359 
       
   360 /*
       
   361 ** Remove the given index from the index hash table, and free
       
   362 ** its memory structures.
       
   363 **
       
   364 ** The index is removed from the database hash tables but
       
   365 ** it is not unlinked from the Table that it indexes.
       
   366 ** Unlinking from the Table must be done by the calling function.
       
   367 */
       
   368 static void sqliteDeleteIndex(Index *p){
       
   369   Index *pOld;
       
   370   const char *zName = p->zName;
       
   371 
       
   372   pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen(zName)+1, 0);
       
   373   assert( pOld==0 || pOld==p );
       
   374   freeIndex(p);
       
   375 }
       
   376 
       
   377 /*
       
   378 ** For the index called zIdxName which is found in the database iDb,
       
   379 ** unlike that index from its Table then remove the index from
       
   380 ** the index hash table and free all memory structures associated
       
   381 ** with the index.
       
   382 */
       
   383 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
       
   384   Index *pIndex;
       
   385   int len;
       
   386   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
       
   387 
       
   388   len = sqlite3Strlen(db, zIdxName);
       
   389   pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
       
   390   if( pIndex ){
       
   391     if( pIndex->pTable->pIndex==pIndex ){
       
   392       pIndex->pTable->pIndex = pIndex->pNext;
       
   393     }else{
       
   394       Index *p;
       
   395       for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
       
   396       if( p && p->pNext==pIndex ){
       
   397         p->pNext = pIndex->pNext;
       
   398       }
       
   399     }
       
   400     freeIndex(pIndex);
       
   401   }
       
   402   db->flags |= SQLITE_InternChanges;
       
   403 }
       
   404 
       
   405 /*
       
   406 ** Erase all schema information from the in-memory hash tables of
       
   407 ** a single database.  This routine is called to reclaim memory
       
   408 ** before the database closes.  It is also called during a rollback
       
   409 ** if there were schema changes during the transaction or if a
       
   410 ** schema-cookie mismatch occurs.
       
   411 **
       
   412 ** If iDb<=0 then reset the internal schema tables for all database
       
   413 ** files.  If iDb>=2 then reset the internal schema for only the
       
   414 ** single file indicated.
       
   415 */
       
   416 void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
       
   417   int i, j;
       
   418   assert( iDb>=0 && iDb<db->nDb );
       
   419 
       
   420   if( iDb==0 ){
       
   421     sqlite3BtreeEnterAll(db);
       
   422   }
       
   423   for(i=iDb; i<db->nDb; i++){
       
   424     Db *pDb = &db->aDb[i];
       
   425     if( pDb->pSchema ){
       
   426       assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
       
   427       sqlite3SchemaFree(pDb->pSchema);
       
   428     }
       
   429     if( iDb>0 ) return;
       
   430   }
       
   431   assert( iDb==0 );
       
   432   db->flags &= ~SQLITE_InternChanges;
       
   433   sqlite3BtreeLeaveAll(db);
       
   434 
       
   435   /* If one or more of the auxiliary database files has been closed,
       
   436   ** then remove them from the auxiliary database list.  We take the
       
   437   ** opportunity to do this here since we have just deleted all of the
       
   438   ** schema hash tables and therefore do not have to make any changes
       
   439   ** to any of those tables.
       
   440   */
       
   441   for(i=0; i<db->nDb; i++){
       
   442     struct Db *pDb = &db->aDb[i];
       
   443     if( pDb->pBt==0 ){
       
   444       if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
       
   445       pDb->pAux = 0;
       
   446     }
       
   447   }
       
   448   for(i=j=2; i<db->nDb; i++){
       
   449     struct Db *pDb = &db->aDb[i];
       
   450     if( pDb->pBt==0 ){
       
   451       sqlite3DbFree(db, pDb->zName);
       
   452       pDb->zName = 0;
       
   453       continue;
       
   454     }
       
   455     if( j<i ){
       
   456       db->aDb[j] = db->aDb[i];
       
   457     }
       
   458     j++;
       
   459   }
       
   460   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
       
   461   db->nDb = j;
       
   462   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
       
   463     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
       
   464     sqlite3DbFree(db, db->aDb);
       
   465     db->aDb = db->aDbStatic;
       
   466   }
       
   467 }
       
   468 
       
   469 /*
       
   470 ** This routine is called when a commit occurs.
       
   471 */
       
   472 void sqlite3CommitInternalChanges(sqlite3 *db){
       
   473   db->flags &= ~SQLITE_InternChanges;
       
   474 }
       
   475 
       
   476 /*
       
   477 ** Clear the column names from a table or view.
       
   478 */
       
   479 static void sqliteResetColumnNames(Table *pTable){
       
   480   int i;
       
   481   Column *pCol;
       
   482   sqlite3 *db = pTable->db;
       
   483   assert( pTable!=0 );
       
   484   if( (pCol = pTable->aCol)!=0 ){
       
   485     for(i=0; i<pTable->nCol; i++, pCol++){
       
   486       sqlite3DbFree(db, pCol->zName);
       
   487       sqlite3ExprDelete(db, pCol->pDflt);
       
   488       sqlite3DbFree(db, pCol->zType);
       
   489       sqlite3DbFree(db, pCol->zColl);
       
   490     }
       
   491     sqlite3DbFree(db, pTable->aCol);
       
   492   }
       
   493   pTable->aCol = 0;
       
   494   pTable->nCol = 0;
       
   495 }
       
   496 
       
   497 /*
       
   498 ** Remove the memory data structures associated with the given
       
   499 ** Table.  No changes are made to disk by this routine.
       
   500 **
       
   501 ** This routine just deletes the data structure.  It does not unlink
       
   502 ** the table data structure from the hash table.  Nor does it remove
       
   503 ** foreign keys from the sqlite.aFKey hash table.  But it does destroy
       
   504 ** memory structures of the indices and foreign keys associated with 
       
   505 ** the table.
       
   506 */
       
   507 void sqlite3DeleteTable(Table *pTable){
       
   508   Index *pIndex, *pNext;
       
   509   FKey *pFKey, *pNextFKey;
       
   510   sqlite3 *db;
       
   511 
       
   512   if( pTable==0 ) return;
       
   513   db = pTable->db;
       
   514 
       
   515   /* Do not delete the table until the reference count reaches zero. */
       
   516   pTable->nRef--;
       
   517   if( pTable->nRef>0 ){
       
   518     return;
       
   519   }
       
   520   assert( pTable->nRef==0 );
       
   521 
       
   522   /* Delete all indices associated with this table
       
   523   */
       
   524   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
       
   525     pNext = pIndex->pNext;
       
   526     assert( pIndex->pSchema==pTable->pSchema );
       
   527     sqliteDeleteIndex(pIndex);
       
   528   }
       
   529 
       
   530 #ifndef SQLITE_OMIT_FOREIGN_KEY
       
   531   /* Delete all foreign keys associated with this table.  The keys
       
   532   ** should have already been unlinked from the pSchema->aFKey hash table 
       
   533   */
       
   534   for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
       
   535     pNextFKey = pFKey->pNextFrom;
       
   536     assert( sqlite3HashFind(&pTable->pSchema->aFKey,
       
   537                            pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
       
   538     sqlite3DbFree(db, pFKey);
       
   539   }
       
   540 #endif
       
   541 
       
   542   /* Delete the Table structure itself.
       
   543   */
       
   544   sqliteResetColumnNames(pTable);
       
   545   sqlite3DbFree(db, pTable->zName);
       
   546   sqlite3DbFree(db, pTable->zColAff);
       
   547   sqlite3SelectDelete(db, pTable->pSelect);
       
   548 #ifndef SQLITE_OMIT_CHECK
       
   549   sqlite3ExprDelete(db, pTable->pCheck);
       
   550 #endif
       
   551   sqlite3VtabClear(pTable);
       
   552   sqlite3DbFree(db, pTable);
       
   553 }
       
   554 
       
   555 /*
       
   556 ** Unlink the given table from the hash tables and the delete the
       
   557 ** table structure with all its indices and foreign keys.
       
   558 */
       
   559 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
       
   560   Table *p;
       
   561   FKey *pF1, *pF2;
       
   562   Db *pDb;
       
   563 
       
   564   assert( db!=0 );
       
   565   assert( iDb>=0 && iDb<db->nDb );
       
   566   assert( zTabName && zTabName[0] );
       
   567   pDb = &db->aDb[iDb];
       
   568   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
       
   569   if( p ){
       
   570 #ifndef SQLITE_OMIT_FOREIGN_KEY
       
   571     for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
       
   572       int nTo = strlen(pF1->zTo) + 1;
       
   573       pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
       
   574       if( pF2==pF1 ){
       
   575         sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
       
   576       }else{
       
   577         while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
       
   578         if( pF2 ){
       
   579           pF2->pNextTo = pF1->pNextTo;
       
   580         }
       
   581       }
       
   582     }
       
   583 #endif
       
   584     sqlite3DeleteTable(p);
       
   585   }
       
   586   db->flags |= SQLITE_InternChanges;
       
   587 }
       
   588 
       
   589 /*
       
   590 ** Given a token, return a string that consists of the text of that
       
   591 ** token with any quotations removed.  Space to hold the returned string
       
   592 ** is obtained from sqliteMalloc() and must be freed by the calling
       
   593 ** function.
       
   594 **
       
   595 ** Tokens are often just pointers into the original SQL text and so
       
   596 ** are not \000 terminated and are not persistent.  The returned string
       
   597 ** is \000 terminated and is persistent.
       
   598 */
       
   599 char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
       
   600   char *zName;
       
   601   if( pName ){
       
   602     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
       
   603     sqlite3Dequote(zName);
       
   604   }else{
       
   605     zName = 0;
       
   606   }
       
   607   return zName;
       
   608 }
       
   609 
       
   610 /*
       
   611 ** Open the sqlite_master table stored in database number iDb for
       
   612 ** writing. The table is opened using cursor 0.
       
   613 */
       
   614 void sqlite3OpenMasterTable(Parse *p, int iDb){
       
   615   Vdbe *v = sqlite3GetVdbe(p);
       
   616   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
       
   617   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 5);/* sqlite_master has 5 columns */
       
   618   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
       
   619 }
       
   620 
       
   621 /*
       
   622 ** The token *pName contains the name of a database (either "main" or
       
   623 ** "temp" or the name of an attached db). This routine returns the
       
   624 ** index of the named database in db->aDb[], or -1 if the named db 
       
   625 ** does not exist.
       
   626 */
       
   627 int sqlite3FindDb(sqlite3 *db, Token *pName){
       
   628   int i = -1;    /* Database number */
       
   629   int n;         /* Number of characters in the name */
       
   630   Db *pDb;       /* A database whose name space is being searched */
       
   631   char *zName;   /* Name we are searching for */
       
   632 
       
   633   zName = sqlite3NameFromToken(db, pName);
       
   634   if( zName ){
       
   635     n = strlen(zName);
       
   636     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
       
   637       if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) && 
       
   638           0==sqlite3StrICmp(pDb->zName, zName) ){
       
   639         break;
       
   640       }
       
   641     }
       
   642     sqlite3DbFree(db, zName);
       
   643   }
       
   644   return i;
       
   645 }
       
   646 
       
   647 /* The table or view or trigger name is passed to this routine via tokens
       
   648 ** pName1 and pName2. If the table name was fully qualified, for example:
       
   649 **
       
   650 ** CREATE TABLE xxx.yyy (...);
       
   651 ** 
       
   652 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
       
   653 ** the table name is not fully qualified, i.e.:
       
   654 **
       
   655 ** CREATE TABLE yyy(...);
       
   656 **
       
   657 ** Then pName1 is set to "yyy" and pName2 is "".
       
   658 **
       
   659 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
       
   660 ** pName2) that stores the unqualified table name.  The index of the
       
   661 ** database "xxx" is returned.
       
   662 */
       
   663 int sqlite3TwoPartName(
       
   664   Parse *pParse,      /* Parsing and code generating context */
       
   665   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
       
   666   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
       
   667   Token **pUnqual     /* Write the unqualified object name here */
       
   668 ){
       
   669   int iDb;                    /* Database holding the object */
       
   670   sqlite3 *db = pParse->db;
       
   671 
       
   672   if( pName2 && pName2->n>0 ){
       
   673     assert( !db->init.busy );
       
   674     *pUnqual = pName2;
       
   675     iDb = sqlite3FindDb(db, pName1);
       
   676     if( iDb<0 ){
       
   677       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
       
   678       pParse->nErr++;
       
   679       return -1;
       
   680     }
       
   681   }else{
       
   682     assert( db->init.iDb==0 || db->init.busy );
       
   683     iDb = db->init.iDb;
       
   684     *pUnqual = pName1;
       
   685   }
       
   686   return iDb;
       
   687 }
       
   688 
       
   689 /*
       
   690 ** This routine is used to check if the UTF-8 string zName is a legal
       
   691 ** unqualified name for a new schema object (table, index, view or
       
   692 ** trigger). All names are legal except those that begin with the string
       
   693 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
       
   694 ** is reserved for internal use.
       
   695 */
       
   696 int sqlite3CheckObjectName(Parse *pParse, const char *zName){
       
   697   if( !pParse->db->init.busy && pParse->nested==0 
       
   698           && (pParse->db->flags & SQLITE_WriteSchema)==0
       
   699           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
       
   700     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
       
   701     return SQLITE_ERROR;
       
   702   }
       
   703   return SQLITE_OK;
       
   704 }
       
   705 
       
   706 /*
       
   707 ** Begin constructing a new table representation in memory.  This is
       
   708 ** the first of several action routines that get called in response
       
   709 ** to a CREATE TABLE statement.  In particular, this routine is called
       
   710 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
       
   711 ** flag is true if the table should be stored in the auxiliary database
       
   712 ** file instead of in the main database file.  This is normally the case
       
   713 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
       
   714 ** CREATE and TABLE.
       
   715 **
       
   716 ** The new table record is initialized and put in pParse->pNewTable.
       
   717 ** As more of the CREATE TABLE statement is parsed, additional action
       
   718 ** routines will be called to add more information to this record.
       
   719 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
       
   720 ** is called to complete the construction of the new table record.
       
   721 */
       
   722 void sqlite3StartTable(
       
   723   Parse *pParse,   /* Parser context */
       
   724   Token *pName1,   /* First part of the name of the table or view */
       
   725   Token *pName2,   /* Second part of the name of the table or view */
       
   726   int isTemp,      /* True if this is a TEMP table */
       
   727   int isView,      /* True if this is a VIEW */
       
   728   int isVirtual,   /* True if this is a VIRTUAL table */
       
   729   int noErr        /* Do nothing if table already exists */
       
   730 ){
       
   731   Table *pTable;
       
   732   char *zName = 0; /* The name of the new table */
       
   733   sqlite3 *db = pParse->db;
       
   734   Vdbe *v;
       
   735   int iDb;         /* Database number to create the table in */
       
   736   Token *pName;    /* Unqualified name of the table to create */
       
   737 
       
   738   /* The table or view name to create is passed to this routine via tokens
       
   739   ** pName1 and pName2. If the table name was fully qualified, for example:
       
   740   **
       
   741   ** CREATE TABLE xxx.yyy (...);
       
   742   ** 
       
   743   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
       
   744   ** the table name is not fully qualified, i.e.:
       
   745   **
       
   746   ** CREATE TABLE yyy(...);
       
   747   **
       
   748   ** Then pName1 is set to "yyy" and pName2 is "".
       
   749   **
       
   750   ** The call below sets the pName pointer to point at the token (pName1 or
       
   751   ** pName2) that stores the unqualified table name. The variable iDb is
       
   752   ** set to the index of the database that the table or view is to be
       
   753   ** created in.
       
   754   */
       
   755   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
       
   756   if( iDb<0 ) return;
       
   757   if( !OMIT_TEMPDB && isTemp && iDb>1 ){
       
   758     /* If creating a temp table, the name may not be qualified */
       
   759     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
       
   760     return;
       
   761   }
       
   762   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
       
   763 
       
   764   pParse->sNameToken = *pName;
       
   765   zName = sqlite3NameFromToken(db, pName);
       
   766   if( zName==0 ) return;
       
   767   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
       
   768     goto begin_table_error;
       
   769   }
       
   770   if( db->init.iDb==1 ) isTemp = 1;
       
   771 #ifndef SQLITE_OMIT_AUTHORIZATION
       
   772   assert( (isTemp & 1)==isTemp );
       
   773   {
       
   774     int code;
       
   775     char *zDb = db->aDb[iDb].zName;
       
   776     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
       
   777       goto begin_table_error;
       
   778     }
       
   779     if( isView ){
       
   780       if( !OMIT_TEMPDB && isTemp ){
       
   781         code = SQLITE_CREATE_TEMP_VIEW;
       
   782       }else{
       
   783         code = SQLITE_CREATE_VIEW;
       
   784       }
       
   785     }else{
       
   786       if( !OMIT_TEMPDB && isTemp ){
       
   787         code = SQLITE_CREATE_TEMP_TABLE;
       
   788       }else{
       
   789         code = SQLITE_CREATE_TABLE;
       
   790       }
       
   791     }
       
   792     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
       
   793       goto begin_table_error;
       
   794     }
       
   795   }
       
   796 #endif
       
   797 
       
   798   /* Make sure the new table name does not collide with an existing
       
   799   ** index or table name in the same database.  Issue an error message if
       
   800   ** it does. The exception is if the statement being parsed was passed
       
   801   ** to an sqlite3_declare_vtab() call. In that case only the column names
       
   802   ** and types will be used, so there is no need to test for namespace
       
   803   ** collisions.
       
   804   */
       
   805   if( !IN_DECLARE_VTAB ){
       
   806     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
       
   807       goto begin_table_error;
       
   808     }
       
   809     pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
       
   810     if( pTable ){
       
   811       if( !noErr ){
       
   812         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
       
   813       }
       
   814       goto begin_table_error;
       
   815     }
       
   816     if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
       
   817       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
       
   818       goto begin_table_error;
       
   819     }
       
   820   }
       
   821 
       
   822   pTable = sqlite3DbMallocZero(db, sizeof(Table));
       
   823   if( pTable==0 ){
       
   824     db->mallocFailed = 1;
       
   825     pParse->rc = SQLITE_NOMEM;
       
   826     pParse->nErr++;
       
   827     goto begin_table_error;
       
   828   }
       
   829   pTable->zName = zName;
       
   830   pTable->iPKey = -1;
       
   831   pTable->pSchema = db->aDb[iDb].pSchema;
       
   832   pTable->nRef = 1;
       
   833   pTable->db = db;
       
   834   if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable);
       
   835   pParse->pNewTable = pTable;
       
   836 
       
   837   /* If this is the magic sqlite_sequence table used by autoincrement,
       
   838   ** then record a pointer to this table in the main database structure
       
   839   ** so that INSERT can find the table easily.
       
   840   */
       
   841 #ifndef SQLITE_OMIT_AUTOINCREMENT
       
   842   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
       
   843     pTable->pSchema->pSeqTab = pTable;
       
   844   }
       
   845 #endif
       
   846 
       
   847   /* Begin generating the code that will insert the table record into
       
   848   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
       
   849   ** and allocate the record number for the table entry now.  Before any
       
   850   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
       
   851   ** indices to be created and the table record must come before the 
       
   852   ** indices.  Hence, the record number for the table must be allocated
       
   853   ** now.
       
   854   */
       
   855   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
       
   856     int j1;
       
   857     int fileFormat;
       
   858     int reg1, reg2, reg3;
       
   859     sqlite3BeginWriteOperation(pParse, 0, iDb);
       
   860 
       
   861 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
   862     if( isVirtual ){
       
   863       sqlite3VdbeAddOp0(v, OP_VBegin);
       
   864     }
       
   865 #endif
       
   866 
       
   867     /* If the file format and encoding in the database have not been set, 
       
   868     ** set them now.
       
   869     */
       
   870     reg1 = pParse->regRowid = ++pParse->nMem;
       
   871     reg2 = pParse->regRoot = ++pParse->nMem;
       
   872     reg3 = ++pParse->nMem;
       
   873     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, 1);   /* file_format */
       
   874     sqlite3VdbeUsesBtree(v, iDb);
       
   875     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
       
   876     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
       
   877                   1 : SQLITE_MAX_FILE_FORMAT;
       
   878     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
       
   879     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, reg3);
       
   880     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
       
   881     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 4, reg3);
       
   882     sqlite3VdbeJumpHere(v, j1);
       
   883 
       
   884     /* This just creates a place-holder record in the sqlite_master table.
       
   885     ** The record created does not contain anything yet.  It will be replaced
       
   886     ** by the real entry in code generated at sqlite3EndTable().
       
   887     **
       
   888     ** The rowid for the new entry is left on the top of the stack.
       
   889     ** The rowid value is needed by the code that sqlite3EndTable will
       
   890     ** generate.
       
   891     */
       
   892 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
       
   893     if( isView || isVirtual ){
       
   894       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
       
   895     }else
       
   896 #endif
       
   897     {
       
   898       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
       
   899     }
       
   900     sqlite3OpenMasterTable(pParse, iDb);
       
   901     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
       
   902     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
       
   903     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
       
   904     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
       
   905     sqlite3VdbeAddOp0(v, OP_Close);
       
   906   }
       
   907 
       
   908   /* Normal (non-error) return. */
       
   909   return;
       
   910 
       
   911   /* If an error occurs, we jump here */
       
   912 begin_table_error:
       
   913   sqlite3DbFree(db, zName);
       
   914   return;
       
   915 }
       
   916 
       
   917 /*
       
   918 ** This macro is used to compare two strings in a case-insensitive manner.
       
   919 ** It is slightly faster than calling sqlite3StrICmp() directly, but
       
   920 ** produces larger code.
       
   921 **
       
   922 ** WARNING: This macro is not compatible with the strcmp() family. It
       
   923 ** returns true if the two strings are equal, otherwise false.
       
   924 */
       
   925 #define STRICMP(x, y) (\
       
   926 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
       
   927 sqlite3UpperToLower[*(unsigned char *)(y)]     \
       
   928 && sqlite3StrICmp((x)+1,(y)+1)==0 )
       
   929 
       
   930 /*
       
   931 ** Add a new column to the table currently being constructed.
       
   932 **
       
   933 ** The parser calls this routine once for each column declaration
       
   934 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
       
   935 ** first to get things going.  Then this routine is called for each
       
   936 ** column.
       
   937 */
       
   938 void sqlite3AddColumn(Parse *pParse, Token *pName){
       
   939   Table *p;
       
   940   int i;
       
   941   char *z;
       
   942   Column *pCol;
       
   943   sqlite3 *db = pParse->db;
       
   944   if( (p = pParse->pNewTable)==0 ) return;
       
   945 #if SQLITE_MAX_COLUMN
       
   946   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
       
   947     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
       
   948     return;
       
   949   }
       
   950 #endif
       
   951   z = sqlite3NameFromToken(pParse->db, pName);
       
   952   if( z==0 ) return;
       
   953   for(i=0; i<p->nCol; i++){
       
   954     if( STRICMP(z, p->aCol[i].zName) ){
       
   955       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
       
   956       sqlite3DbFree(db, z);
       
   957       return;
       
   958     }
       
   959   }
       
   960   if( (p->nCol & 0x7)==0 ){
       
   961     Column *aNew;
       
   962     aNew = sqlite3DbRealloc(pParse->db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
       
   963     if( aNew==0 ){
       
   964       sqlite3DbFree(db, z);
       
   965       return;
       
   966     }
       
   967     p->aCol = aNew;
       
   968   }
       
   969   pCol = &p->aCol[p->nCol];
       
   970   memset(pCol, 0, sizeof(p->aCol[0]));
       
   971   pCol->zName = z;
       
   972  
       
   973   /* If there is no type specified, columns have the default affinity
       
   974   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
       
   975   ** be called next to set pCol->affinity correctly.
       
   976   */
       
   977   pCol->affinity = SQLITE_AFF_NONE;
       
   978   p->nCol++;
       
   979 }
       
   980 
       
   981 /*
       
   982 ** This routine is called by the parser while in the middle of
       
   983 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
       
   984 ** been seen on a column.  This routine sets the notNull flag on
       
   985 ** the column currently under construction.
       
   986 */
       
   987 void sqlite3AddNotNull(Parse *pParse, int onError){
       
   988   Table *p;
       
   989   int i;
       
   990   if( (p = pParse->pNewTable)==0 ) return;
       
   991   i = p->nCol-1;
       
   992   if( i>=0 ) p->aCol[i].notNull = onError;
       
   993 }
       
   994 
       
   995 /*
       
   996 ** Scan the column type name zType (length nType) and return the
       
   997 ** associated affinity type.
       
   998 **
       
   999 ** This routine does a case-independent search of zType for the 
       
  1000 ** substrings in the following table. If one of the substrings is
       
  1001 ** found, the corresponding affinity is returned. If zType contains
       
  1002 ** more than one of the substrings, entries toward the top of 
       
  1003 ** the table take priority. For example, if zType is 'BLOBINT', 
       
  1004 ** SQLITE_AFF_INTEGER is returned.
       
  1005 **
       
  1006 ** Substring     | Affinity
       
  1007 ** --------------------------------
       
  1008 ** 'INT'         | SQLITE_AFF_INTEGER
       
  1009 ** 'CHAR'        | SQLITE_AFF_TEXT
       
  1010 ** 'CLOB'        | SQLITE_AFF_TEXT
       
  1011 ** 'TEXT'        | SQLITE_AFF_TEXT
       
  1012 ** 'BLOB'        | SQLITE_AFF_NONE
       
  1013 ** 'REAL'        | SQLITE_AFF_REAL
       
  1014 ** 'FLOA'        | SQLITE_AFF_REAL
       
  1015 ** 'DOUB'        | SQLITE_AFF_REAL
       
  1016 **
       
  1017 ** If none of the substrings in the above table are found,
       
  1018 ** SQLITE_AFF_NUMERIC is returned.
       
  1019 */
       
  1020 char sqlite3AffinityType(const Token *pType){
       
  1021   u32 h = 0;
       
  1022   char aff = SQLITE_AFF_NUMERIC;
       
  1023   const unsigned char *zIn = pType->z;
       
  1024   const unsigned char *zEnd = &pType->z[pType->n];
       
  1025 
       
  1026   while( zIn!=zEnd ){
       
  1027     h = (h<<8) + sqlite3UpperToLower[*zIn];
       
  1028     zIn++;
       
  1029     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
       
  1030       aff = SQLITE_AFF_TEXT; 
       
  1031     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
       
  1032       aff = SQLITE_AFF_TEXT;
       
  1033     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
       
  1034       aff = SQLITE_AFF_TEXT;
       
  1035     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
       
  1036         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
       
  1037       aff = SQLITE_AFF_NONE;
       
  1038 #ifndef SQLITE_OMIT_FLOATING_POINT
       
  1039     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
       
  1040         && aff==SQLITE_AFF_NUMERIC ){
       
  1041       aff = SQLITE_AFF_REAL;
       
  1042     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
       
  1043         && aff==SQLITE_AFF_NUMERIC ){
       
  1044       aff = SQLITE_AFF_REAL;
       
  1045     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
       
  1046         && aff==SQLITE_AFF_NUMERIC ){
       
  1047       aff = SQLITE_AFF_REAL;
       
  1048 #endif
       
  1049     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
       
  1050       aff = SQLITE_AFF_INTEGER;
       
  1051       break;
       
  1052     }
       
  1053   }
       
  1054 
       
  1055   return aff;
       
  1056 }
       
  1057 
       
  1058 /*
       
  1059 ** This routine is called by the parser while in the middle of
       
  1060 ** parsing a CREATE TABLE statement.  The pFirst token is the first
       
  1061 ** token in the sequence of tokens that describe the type of the
       
  1062 ** column currently under construction.   pLast is the last token
       
  1063 ** in the sequence.  Use this information to construct a string
       
  1064 ** that contains the typename of the column and store that string
       
  1065 ** in zType.
       
  1066 */ 
       
  1067 void sqlite3AddColumnType(Parse *pParse, Token *pType){
       
  1068   Table *p;
       
  1069   int i;
       
  1070   Column *pCol;
       
  1071   sqlite3 *db;
       
  1072 
       
  1073   if( (p = pParse->pNewTable)==0 ) return;
       
  1074   i = p->nCol-1;
       
  1075   if( i<0 ) return;
       
  1076   pCol = &p->aCol[i];
       
  1077   db = pParse->db;
       
  1078   sqlite3DbFree(db, pCol->zType);
       
  1079   pCol->zType = sqlite3NameFromToken(db, pType);
       
  1080   pCol->affinity = sqlite3AffinityType(pType);
       
  1081 }
       
  1082 
       
  1083 /*
       
  1084 ** The expression is the default value for the most recently added column
       
  1085 ** of the table currently under construction.
       
  1086 **
       
  1087 ** Default value expressions must be constant.  Raise an exception if this
       
  1088 ** is not the case.
       
  1089 **
       
  1090 ** This routine is called by the parser while in the middle of
       
  1091 ** parsing a CREATE TABLE statement.
       
  1092 */
       
  1093 void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
       
  1094   Table *p;
       
  1095   Column *pCol;
       
  1096   sqlite3 *db = pParse->db;
       
  1097   if( (p = pParse->pNewTable)!=0 ){
       
  1098     pCol = &(p->aCol[p->nCol-1]);
       
  1099     if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
       
  1100       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
       
  1101           pCol->zName);
       
  1102     }else{
       
  1103       Expr *pCopy;
       
  1104       sqlite3ExprDelete(db, pCol->pDflt);
       
  1105       pCol->pDflt = pCopy = sqlite3ExprDup(db, pExpr);
       
  1106       if( pCopy ){
       
  1107         sqlite3TokenCopy(db, &pCopy->span, &pExpr->span);
       
  1108       }
       
  1109     }
       
  1110   }
       
  1111   sqlite3ExprDelete(db, pExpr);
       
  1112 }
       
  1113 
       
  1114 /*
       
  1115 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
       
  1116 ** of columns that form the primary key.  If pList is NULL, then the
       
  1117 ** most recently added column of the table is the primary key.
       
  1118 **
       
  1119 ** A table can have at most one primary key.  If the table already has
       
  1120 ** a primary key (and this is the second primary key) then create an
       
  1121 ** error.
       
  1122 **
       
  1123 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
       
  1124 ** then we will try to use that column as the rowid.  Set the Table.iPKey
       
  1125 ** field of the table under construction to be the index of the
       
  1126 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
       
  1127 ** no INTEGER PRIMARY KEY.
       
  1128 **
       
  1129 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
       
  1130 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
       
  1131 */
       
  1132 void sqlite3AddPrimaryKey(
       
  1133   Parse *pParse,    /* Parsing context */
       
  1134   ExprList *pList,  /* List of field names to be indexed */
       
  1135   int onError,      /* What to do with a uniqueness conflict */
       
  1136   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
       
  1137   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
       
  1138 ){
       
  1139   Table *pTab = pParse->pNewTable;
       
  1140   char *zType = 0;
       
  1141   int iCol = -1, i;
       
  1142   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
       
  1143   if( pTab->hasPrimKey ){
       
  1144     sqlite3ErrorMsg(pParse, 
       
  1145       "table \"%s\" has more than one primary key", pTab->zName);
       
  1146     goto primary_key_exit;
       
  1147   }
       
  1148   pTab->hasPrimKey = 1;
       
  1149   if( pList==0 ){
       
  1150     iCol = pTab->nCol - 1;
       
  1151     pTab->aCol[iCol].isPrimKey = 1;
       
  1152   }else{
       
  1153     for(i=0; i<pList->nExpr; i++){
       
  1154       for(iCol=0; iCol<pTab->nCol; iCol++){
       
  1155         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
       
  1156           break;
       
  1157         }
       
  1158       }
       
  1159       if( iCol<pTab->nCol ){
       
  1160         pTab->aCol[iCol].isPrimKey = 1;
       
  1161       }
       
  1162     }
       
  1163     if( pList->nExpr>1 ) iCol = -1;
       
  1164   }
       
  1165   if( iCol>=0 && iCol<pTab->nCol ){
       
  1166     zType = pTab->aCol[iCol].zType;
       
  1167   }
       
  1168   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
       
  1169         && sortOrder==SQLITE_SO_ASC ){
       
  1170     pTab->iPKey = iCol;
       
  1171     pTab->keyConf = onError;
       
  1172     pTab->autoInc = autoInc;
       
  1173   }else if( autoInc ){
       
  1174 #ifndef SQLITE_OMIT_AUTOINCREMENT
       
  1175     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
       
  1176        "INTEGER PRIMARY KEY");
       
  1177 #endif
       
  1178   }else{
       
  1179     sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
       
  1180     pList = 0;
       
  1181   }
       
  1182 
       
  1183 primary_key_exit:
       
  1184   sqlite3ExprListDelete(pParse->db, pList);
       
  1185   return;
       
  1186 }
       
  1187 
       
  1188 /*
       
  1189 ** Add a new CHECK constraint to the table currently under construction.
       
  1190 */
       
  1191 void sqlite3AddCheckConstraint(
       
  1192   Parse *pParse,    /* Parsing context */
       
  1193   Expr *pCheckExpr  /* The check expression */
       
  1194 ){
       
  1195   sqlite3 *db = pParse->db;
       
  1196 #ifndef SQLITE_OMIT_CHECK
       
  1197   Table *pTab = pParse->pNewTable;
       
  1198   if( pTab && !IN_DECLARE_VTAB ){
       
  1199     /* The CHECK expression must be duplicated so that tokens refer
       
  1200     ** to malloced space and not the (ephemeral) text of the CREATE TABLE
       
  1201     ** statement */
       
  1202     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, 
       
  1203                                   sqlite3ExprDup(db, pCheckExpr));
       
  1204   }
       
  1205 #endif
       
  1206   sqlite3ExprDelete(db, pCheckExpr);
       
  1207 }
       
  1208 
       
  1209 /*
       
  1210 ** Set the collation function of the most recently parsed table column
       
  1211 ** to the CollSeq given.
       
  1212 */
       
  1213 void sqlite3AddCollateType(Parse *pParse, Token *pToken){
       
  1214   Table *p;
       
  1215   int i;
       
  1216   char *zColl;              /* Dequoted name of collation sequence */
       
  1217   sqlite3 *db;
       
  1218 
       
  1219   if( (p = pParse->pNewTable)==0 ) return;
       
  1220   i = p->nCol-1;
       
  1221   db = pParse->db;
       
  1222   zColl = sqlite3NameFromToken(db, pToken);
       
  1223   if( !zColl ) return;
       
  1224 
       
  1225   if( sqlite3LocateCollSeq(pParse, zColl, -1) ){
       
  1226     Index *pIdx;
       
  1227     p->aCol[i].zColl = zColl;
       
  1228   
       
  1229     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
       
  1230     ** then an index may have been created on this column before the
       
  1231     ** collation type was added. Correct this if it is the case.
       
  1232     */
       
  1233     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
       
  1234       assert( pIdx->nColumn==1 );
       
  1235       if( pIdx->aiColumn[0]==i ){
       
  1236         pIdx->azColl[0] = p->aCol[i].zColl;
       
  1237       }
       
  1238     }
       
  1239   }else{
       
  1240     sqlite3DbFree(db, zColl);
       
  1241   }
       
  1242 }
       
  1243 
       
  1244 /*
       
  1245 ** This function returns the collation sequence for database native text
       
  1246 ** encoding identified by the string zName, length nName.
       
  1247 **
       
  1248 ** If the requested collation sequence is not available, or not available
       
  1249 ** in the database native encoding, the collation factory is invoked to
       
  1250 ** request it. If the collation factory does not supply such a sequence,
       
  1251 ** and the sequence is available in another text encoding, then that is
       
  1252 ** returned instead.
       
  1253 **
       
  1254 ** If no versions of the requested collations sequence are available, or
       
  1255 ** another error occurs, NULL is returned and an error message written into
       
  1256 ** pParse.
       
  1257 **
       
  1258 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
       
  1259 ** invokes the collation factory if the named collation cannot be found
       
  1260 ** and generates an error message.
       
  1261 */
       
  1262 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
       
  1263   sqlite3 *db = pParse->db;
       
  1264   u8 enc = ENC(db);
       
  1265   u8 initbusy = db->init.busy;
       
  1266   CollSeq *pColl;
       
  1267 
       
  1268   pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
       
  1269   if( !initbusy && (!pColl || !pColl->xCmp) ){
       
  1270     pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
       
  1271     if( !pColl ){
       
  1272       if( nName<0 ){
       
  1273         nName = sqlite3Strlen(db, zName);
       
  1274       }
       
  1275       sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
       
  1276       pColl = 0;
       
  1277     }
       
  1278   }
       
  1279 
       
  1280   return pColl;
       
  1281 }
       
  1282 
       
  1283 
       
  1284 /*
       
  1285 ** Generate code that will increment the schema cookie.
       
  1286 **
       
  1287 ** The schema cookie is used to determine when the schema for the
       
  1288 ** database changes.  After each schema change, the cookie value
       
  1289 ** changes.  When a process first reads the schema it records the
       
  1290 ** cookie.  Thereafter, whenever it goes to access the database,
       
  1291 ** it checks the cookie to make sure the schema has not changed
       
  1292 ** since it was last read.
       
  1293 **
       
  1294 ** This plan is not completely bullet-proof.  It is possible for
       
  1295 ** the schema to change multiple times and for the cookie to be
       
  1296 ** set back to prior value.  But schema changes are infrequent
       
  1297 ** and the probability of hitting the same cookie value is only
       
  1298 ** 1 chance in 2^32.  So we're safe enough.
       
  1299 */
       
  1300 void sqlite3ChangeCookie(Parse *pParse, int iDb){
       
  1301   int r1 = sqlite3GetTempReg(pParse);
       
  1302   sqlite3 *db = pParse->db;
       
  1303   Vdbe *v = pParse->pVdbe;
       
  1304   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
       
  1305   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 0, r1);
       
  1306   sqlite3ReleaseTempReg(pParse, r1);
       
  1307 }
       
  1308 
       
  1309 /*
       
  1310 ** Measure the number of characters needed to output the given
       
  1311 ** identifier.  The number returned includes any quotes used
       
  1312 ** but does not include the null terminator.
       
  1313 **
       
  1314 ** The estimate is conservative.  It might be larger that what is
       
  1315 ** really needed.
       
  1316 */
       
  1317 static int identLength(const char *z){
       
  1318   int n;
       
  1319   for(n=0; *z; n++, z++){
       
  1320     if( *z=='"' ){ n++; }
       
  1321   }
       
  1322   return n + 2;
       
  1323 }
       
  1324 
       
  1325 /*
       
  1326 ** Write an identifier onto the end of the given string.  Add
       
  1327 ** quote characters as needed.
       
  1328 */
       
  1329 static void identPut(char *z, int *pIdx, char *zSignedIdent){
       
  1330   unsigned char *zIdent = (unsigned char*)zSignedIdent;
       
  1331   int i, j, needQuote;
       
  1332   i = *pIdx;
       
  1333   for(j=0; zIdent[j]; j++){
       
  1334     if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
       
  1335   }
       
  1336   needQuote =  zIdent[j]!=0 || isdigit(zIdent[0])
       
  1337                   || sqlite3KeywordCode(zIdent, j)!=TK_ID;
       
  1338   if( needQuote ) z[i++] = '"';
       
  1339   for(j=0; zIdent[j]; j++){
       
  1340     z[i++] = zIdent[j];
       
  1341     if( zIdent[j]=='"' ) z[i++] = '"';
       
  1342   }
       
  1343   if( needQuote ) z[i++] = '"';
       
  1344   z[i] = 0;
       
  1345   *pIdx = i;
       
  1346 }
       
  1347 
       
  1348 /*
       
  1349 ** Generate a CREATE TABLE statement appropriate for the given
       
  1350 ** table.  Memory to hold the text of the statement is obtained
       
  1351 ** from sqliteMalloc() and must be freed by the calling function.
       
  1352 */
       
  1353 static char *createTableStmt(sqlite3 *db, Table *p, int isTemp){
       
  1354   int i, k, n;
       
  1355   char *zStmt;
       
  1356   char *zSep, *zSep2, *zEnd, *z;
       
  1357   Column *pCol;
       
  1358   n = 0;
       
  1359   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
       
  1360     n += identLength(pCol->zName);
       
  1361     z = pCol->zType;
       
  1362     if( z ){
       
  1363       n += (strlen(z) + 1);
       
  1364     }
       
  1365   }
       
  1366   n += identLength(p->zName);
       
  1367   if( n<50 ){
       
  1368     zSep = "";
       
  1369     zSep2 = ",";
       
  1370     zEnd = ")";
       
  1371   }else{
       
  1372     zSep = "\n  ";
       
  1373     zSep2 = ",\n  ";
       
  1374     zEnd = "\n)";
       
  1375   }
       
  1376   n += 35 + 6*p->nCol;
       
  1377   zStmt = sqlite3Malloc( n );
       
  1378   if( zStmt==0 ){
       
  1379     db->mallocFailed = 1;
       
  1380     return 0;
       
  1381   }
       
  1382   sqlite3_snprintf(n, zStmt,
       
  1383                   !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
       
  1384   k = strlen(zStmt);
       
  1385   identPut(zStmt, &k, p->zName);
       
  1386   zStmt[k++] = '(';
       
  1387   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
       
  1388     sqlite3_snprintf(n-k, &zStmt[k], zSep);
       
  1389     k += strlen(&zStmt[k]);
       
  1390     zSep = zSep2;
       
  1391     identPut(zStmt, &k, pCol->zName);
       
  1392     if( (z = pCol->zType)!=0 ){
       
  1393       zStmt[k++] = ' ';
       
  1394       assert( strlen(z)+k+1<=n );
       
  1395       sqlite3_snprintf(n-k, &zStmt[k], "%s", z);
       
  1396       k += strlen(z);
       
  1397     }
       
  1398   }
       
  1399   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
       
  1400   return zStmt;
       
  1401 }
       
  1402 
       
  1403 /*
       
  1404 ** This routine is called to report the final ")" that terminates
       
  1405 ** a CREATE TABLE statement.
       
  1406 **
       
  1407 ** The table structure that other action routines have been building
       
  1408 ** is added to the internal hash tables, assuming no errors have
       
  1409 ** occurred.
       
  1410 **
       
  1411 ** An entry for the table is made in the master table on disk, unless
       
  1412 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
       
  1413 ** it means we are reading the sqlite_master table because we just
       
  1414 ** connected to the database or because the sqlite_master table has
       
  1415 ** recently changed, so the entry for this table already exists in
       
  1416 ** the sqlite_master table.  We do not want to create it again.
       
  1417 **
       
  1418 ** If the pSelect argument is not NULL, it means that this routine
       
  1419 ** was called to create a table generated from a 
       
  1420 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
       
  1421 ** the new table will match the result set of the SELECT.
       
  1422 */
       
  1423 void sqlite3EndTable(
       
  1424   Parse *pParse,          /* Parse context */
       
  1425   Token *pCons,           /* The ',' token after the last column defn. */
       
  1426   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
       
  1427   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
       
  1428 ){
       
  1429   Table *p;
       
  1430   sqlite3 *db = pParse->db;
       
  1431   int iDb;
       
  1432 
       
  1433   if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) {
       
  1434     return;
       
  1435   }
       
  1436   p = pParse->pNewTable;
       
  1437   if( p==0 ) return;
       
  1438 
       
  1439   assert( !db->init.busy || !pSelect );
       
  1440 
       
  1441   iDb = sqlite3SchemaToIndex(db, p->pSchema);
       
  1442 
       
  1443 #ifndef SQLITE_OMIT_CHECK
       
  1444   /* Resolve names in all CHECK constraint expressions.
       
  1445   */
       
  1446   if( p->pCheck ){
       
  1447     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
       
  1448     NameContext sNC;                /* Name context for pParse->pNewTable */
       
  1449 
       
  1450     memset(&sNC, 0, sizeof(sNC));
       
  1451     memset(&sSrc, 0, sizeof(sSrc));
       
  1452     sSrc.nSrc = 1;
       
  1453     sSrc.a[0].zName = p->zName;
       
  1454     sSrc.a[0].pTab = p;
       
  1455     sSrc.a[0].iCursor = -1;
       
  1456     sNC.pParse = pParse;
       
  1457     sNC.pSrcList = &sSrc;
       
  1458     sNC.isCheck = 1;
       
  1459     if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){
       
  1460       return;
       
  1461     }
       
  1462   }
       
  1463 #endif /* !defined(SQLITE_OMIT_CHECK) */
       
  1464 
       
  1465   /* If the db->init.busy is 1 it means we are reading the SQL off the
       
  1466   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
       
  1467   ** So do not write to the disk again.  Extract the root page number
       
  1468   ** for the table from the db->init.newTnum field.  (The page number
       
  1469   ** should have been put there by the sqliteOpenCb routine.)
       
  1470   */
       
  1471   if( db->init.busy ){
       
  1472     p->tnum = db->init.newTnum;
       
  1473   }
       
  1474 
       
  1475   /* If not initializing, then create a record for the new table
       
  1476   ** in the SQLITE_MASTER table of the database.  The record number
       
  1477   ** for the new table entry should already be on the stack.
       
  1478   **
       
  1479   ** If this is a TEMPORARY table, write the entry into the auxiliary
       
  1480   ** file instead of into the main database file.
       
  1481   */
       
  1482   if( !db->init.busy ){
       
  1483     int n;
       
  1484     Vdbe *v;
       
  1485     char *zType;    /* "view" or "table" */
       
  1486     char *zType2;   /* "VIEW" or "TABLE" */
       
  1487     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
       
  1488 
       
  1489     v = sqlite3GetVdbe(pParse);
       
  1490     if( v==0 ) return;
       
  1491 
       
  1492     sqlite3VdbeAddOp1(v, OP_Close, 0);
       
  1493 
       
  1494     /* Create the rootpage for the new table and push it onto the stack.
       
  1495     ** A view has no rootpage, so just push a zero onto the stack for
       
  1496     ** views.  Initialize zType at the same time.
       
  1497     */
       
  1498     if( p->pSelect==0 ){
       
  1499       /* A regular table */
       
  1500       zType = "table";
       
  1501       zType2 = "TABLE";
       
  1502 #ifndef SQLITE_OMIT_VIEW
       
  1503     }else{
       
  1504       /* A view */
       
  1505       zType = "view";
       
  1506       zType2 = "VIEW";
       
  1507 #endif
       
  1508     }
       
  1509 
       
  1510     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
       
  1511     ** statement to populate the new table. The root-page number for the
       
  1512     ** new table is on the top of the vdbe stack.
       
  1513     **
       
  1514     ** Once the SELECT has been coded by sqlite3Select(), it is in a
       
  1515     ** suitable state to query for the column names and types to be used
       
  1516     ** by the new table.
       
  1517     **
       
  1518     ** A shared-cache write-lock is not required to write to the new table,
       
  1519     ** as a schema-lock must have already been obtained to create it. Since
       
  1520     ** a schema-lock excludes all other database users, the write-lock would
       
  1521     ** be redundant.
       
  1522     */
       
  1523     if( pSelect ){
       
  1524       SelectDest dest;
       
  1525       Table *pSelTab;
       
  1526 
       
  1527       assert(pParse->nTab==0);
       
  1528       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
       
  1529       sqlite3VdbeChangeP5(v, 1);
       
  1530       pParse->nTab = 2;
       
  1531       sqlite3SelectDestInit(&dest, SRT_Table, 1);
       
  1532       sqlite3Select(pParse, pSelect, &dest, 0, 0, 0);
       
  1533       sqlite3VdbeAddOp1(v, OP_Close, 1);
       
  1534       if( pParse->nErr==0 ){
       
  1535         pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
       
  1536         if( pSelTab==0 ) return;
       
  1537         assert( p->aCol==0 );
       
  1538         p->nCol = pSelTab->nCol;
       
  1539         p->aCol = pSelTab->aCol;
       
  1540         pSelTab->nCol = 0;
       
  1541         pSelTab->aCol = 0;
       
  1542         sqlite3DeleteTable(pSelTab);
       
  1543       }
       
  1544     }
       
  1545 
       
  1546     /* Compute the complete text of the CREATE statement */
       
  1547     if( pSelect ){
       
  1548       zStmt = createTableStmt(db, p, p->pSchema==db->aDb[1].pSchema);
       
  1549     }else{
       
  1550       n = pEnd->z - pParse->sNameToken.z + 1;
       
  1551       zStmt = sqlite3MPrintf(db, 
       
  1552           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
       
  1553       );
       
  1554     }
       
  1555 
       
  1556     /* A slot for the record has already been allocated in the 
       
  1557     ** SQLITE_MASTER table.  We just need to update that slot with all
       
  1558     ** the information we've collected.  The rowid for the preallocated
       
  1559     ** slot is the 2nd item on the stack.  The top of the stack is the
       
  1560     ** root page for the new table (or a 0 if this is a view).
       
  1561     */
       
  1562     sqlite3NestedParse(pParse,
       
  1563       "UPDATE %Q.%s "
       
  1564          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
       
  1565        "WHERE rowid=#%d",
       
  1566       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
       
  1567       zType,
       
  1568       p->zName,
       
  1569       p->zName,
       
  1570       pParse->regRoot,
       
  1571       zStmt,
       
  1572       pParse->regRowid
       
  1573     );
       
  1574     sqlite3DbFree(db, zStmt);
       
  1575     sqlite3ChangeCookie(pParse, iDb);
       
  1576 
       
  1577 #ifndef SQLITE_OMIT_AUTOINCREMENT
       
  1578     /* Check to see if we need to create an sqlite_sequence table for
       
  1579     ** keeping track of autoincrement keys.
       
  1580     */
       
  1581     if( p->autoInc ){
       
  1582       Db *pDb = &db->aDb[iDb];
       
  1583       if( pDb->pSchema->pSeqTab==0 ){
       
  1584         sqlite3NestedParse(pParse,
       
  1585           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
       
  1586           pDb->zName
       
  1587         );
       
  1588       }
       
  1589     }
       
  1590 #endif
       
  1591 
       
  1592     /* Reparse everything to update our internal data structures */
       
  1593     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
       
  1594         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
       
  1595   }
       
  1596 
       
  1597 
       
  1598   /* Add the table to the in-memory representation of the database.
       
  1599   */
       
  1600   if( db->init.busy && pParse->nErr==0 ){
       
  1601     Table *pOld;
       
  1602     FKey *pFKey; 
       
  1603     Schema *pSchema = p->pSchema;
       
  1604     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
       
  1605     if( pOld ){
       
  1606       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
       
  1607       db->mallocFailed = 1;
       
  1608       return;
       
  1609     }
       
  1610 #ifndef SQLITE_OMIT_FOREIGN_KEY
       
  1611     for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
       
  1612       void *data;
       
  1613       int nTo = strlen(pFKey->zTo) + 1;
       
  1614       pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
       
  1615       data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
       
  1616       if( data==(void *)pFKey ){
       
  1617         db->mallocFailed = 1;
       
  1618       }
       
  1619     }
       
  1620 #endif
       
  1621     pParse->pNewTable = 0;
       
  1622     db->nTable++;
       
  1623     db->flags |= SQLITE_InternChanges;
       
  1624 
       
  1625 #ifndef SQLITE_OMIT_ALTERTABLE
       
  1626     if( !p->pSelect ){
       
  1627       const char *zName = (const char *)pParse->sNameToken.z;
       
  1628       int nName;
       
  1629       assert( !pSelect && pCons && pEnd );
       
  1630       if( pCons->z==0 ){
       
  1631         pCons = pEnd;
       
  1632       }
       
  1633       nName = (const char *)pCons->z - zName;
       
  1634       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
       
  1635     }
       
  1636 #endif
       
  1637   }
       
  1638 }
       
  1639 
       
  1640 #ifndef SQLITE_OMIT_VIEW
       
  1641 /*
       
  1642 ** The parser calls this routine in order to create a new VIEW
       
  1643 */
       
  1644 void sqlite3CreateView(
       
  1645   Parse *pParse,     /* The parsing context */
       
  1646   Token *pBegin,     /* The CREATE token that begins the statement */
       
  1647   Token *pName1,     /* The token that holds the name of the view */
       
  1648   Token *pName2,     /* The token that holds the name of the view */
       
  1649   Select *pSelect,   /* A SELECT statement that will become the new view */
       
  1650   int isTemp,        /* TRUE for a TEMPORARY view */
       
  1651   int noErr          /* Suppress error messages if VIEW already exists */
       
  1652 ){
       
  1653   Table *p;
       
  1654   int n;
       
  1655   const unsigned char *z;
       
  1656   Token sEnd;
       
  1657   DbFixer sFix;
       
  1658   Token *pName;
       
  1659   int iDb;
       
  1660   sqlite3 *db = pParse->db;
       
  1661 
       
  1662   if( pParse->nVar>0 ){
       
  1663     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
       
  1664     sqlite3SelectDelete(db, pSelect);
       
  1665     return;
       
  1666   }
       
  1667   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
       
  1668   p = pParse->pNewTable;
       
  1669   if( p==0 || pParse->nErr ){
       
  1670     sqlite3SelectDelete(db, pSelect);
       
  1671     return;
       
  1672   }
       
  1673   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
       
  1674   iDb = sqlite3SchemaToIndex(db, p->pSchema);
       
  1675   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
       
  1676     && sqlite3FixSelect(&sFix, pSelect)
       
  1677   ){
       
  1678     sqlite3SelectDelete(db, pSelect);
       
  1679     return;
       
  1680   }
       
  1681 
       
  1682   /* Make a copy of the entire SELECT statement that defines the view.
       
  1683   ** This will force all the Expr.token.z values to be dynamically
       
  1684   ** allocated rather than point to the input string - which means that
       
  1685   ** they will persist after the current sqlite3_exec() call returns.
       
  1686   */
       
  1687   p->pSelect = sqlite3SelectDup(db, pSelect);
       
  1688   sqlite3SelectDelete(db, pSelect);
       
  1689   if( db->mallocFailed ){
       
  1690     return;
       
  1691   }
       
  1692   if( !db->init.busy ){
       
  1693     sqlite3ViewGetColumnNames(pParse, p);
       
  1694   }
       
  1695 
       
  1696   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
       
  1697   ** the end.
       
  1698   */
       
  1699   sEnd = pParse->sLastToken;
       
  1700   if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
       
  1701     sEnd.z += sEnd.n;
       
  1702   }
       
  1703   sEnd.n = 0;
       
  1704   n = sEnd.z - pBegin->z;
       
  1705   z = (const unsigned char*)pBegin->z;
       
  1706   while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
       
  1707   sEnd.z = &z[n-1];
       
  1708   sEnd.n = 1;
       
  1709 
       
  1710   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
       
  1711   sqlite3EndTable(pParse, 0, &sEnd, 0);
       
  1712   return;
       
  1713 }
       
  1714 #endif /* SQLITE_OMIT_VIEW */
       
  1715 
       
  1716 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
       
  1717 /*
       
  1718 ** The Table structure pTable is really a VIEW.  Fill in the names of
       
  1719 ** the columns of the view in the pTable structure.  Return the number
       
  1720 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
       
  1721 */
       
  1722 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
       
  1723   Table *pSelTab;   /* A fake table from which we get the result set */
       
  1724   Select *pSel;     /* Copy of the SELECT that implements the view */
       
  1725   int nErr = 0;     /* Number of errors encountered */
       
  1726   int n;            /* Temporarily holds the number of cursors assigned */
       
  1727   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
       
  1728   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
       
  1729 
       
  1730   assert( pTable );
       
  1731 
       
  1732 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
  1733   if( sqlite3VtabCallConnect(pParse, pTable) ){
       
  1734     return SQLITE_ERROR;
       
  1735   }
       
  1736   if( IsVirtual(pTable) ) return 0;
       
  1737 #endif
       
  1738 
       
  1739 #ifndef SQLITE_OMIT_VIEW
       
  1740   /* A positive nCol means the columns names for this view are
       
  1741   ** already known.
       
  1742   */
       
  1743   if( pTable->nCol>0 ) return 0;
       
  1744 
       
  1745   /* A negative nCol is a special marker meaning that we are currently
       
  1746   ** trying to compute the column names.  If we enter this routine with
       
  1747   ** a negative nCol, it means two or more views form a loop, like this:
       
  1748   **
       
  1749   **     CREATE VIEW one AS SELECT * FROM two;
       
  1750   **     CREATE VIEW two AS SELECT * FROM one;
       
  1751   **
       
  1752   ** Actually, this error is caught previously and so the following test
       
  1753   ** should always fail.  But we will leave it in place just to be safe.
       
  1754   */
       
  1755   if( pTable->nCol<0 ){
       
  1756     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
       
  1757     return 1;
       
  1758   }
       
  1759   assert( pTable->nCol>=0 );
       
  1760 
       
  1761   /* If we get this far, it means we need to compute the table names.
       
  1762   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
       
  1763   ** "*" elements in the results set of the view and will assign cursors
       
  1764   ** to the elements of the FROM clause.  But we do not want these changes
       
  1765   ** to be permanent.  So the computation is done on a copy of the SELECT
       
  1766   ** statement that defines the view.
       
  1767   */
       
  1768   assert( pTable->pSelect );
       
  1769   pSel = sqlite3SelectDup(db, pTable->pSelect);
       
  1770   if( pSel ){
       
  1771     n = pParse->nTab;
       
  1772     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
       
  1773     pTable->nCol = -1;
       
  1774 #ifndef SQLITE_OMIT_AUTHORIZATION
       
  1775     xAuth = db->xAuth;
       
  1776     db->xAuth = 0;
       
  1777     pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
       
  1778     db->xAuth = xAuth;
       
  1779 #else
       
  1780     pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
       
  1781 #endif
       
  1782     pParse->nTab = n;
       
  1783     if( pSelTab ){
       
  1784       assert( pTable->aCol==0 );
       
  1785       pTable->nCol = pSelTab->nCol;
       
  1786       pTable->aCol = pSelTab->aCol;
       
  1787       pSelTab->nCol = 0;
       
  1788       pSelTab->aCol = 0;
       
  1789       sqlite3DeleteTable(pSelTab);
       
  1790       pTable->pSchema->flags |= DB_UnresetViews;
       
  1791     }else{
       
  1792       pTable->nCol = 0;
       
  1793       nErr++;
       
  1794     }
       
  1795     sqlite3SelectDelete(db, pSel);
       
  1796   } else {
       
  1797     nErr++;
       
  1798   }
       
  1799 #endif /* SQLITE_OMIT_VIEW */
       
  1800   return nErr;  
       
  1801 }
       
  1802 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
       
  1803 
       
  1804 #ifndef SQLITE_OMIT_VIEW
       
  1805 /*
       
  1806 ** Clear the column names from every VIEW in database idx.
       
  1807 */
       
  1808 static void sqliteViewResetAll(sqlite3 *db, int idx){
       
  1809   HashElem *i;
       
  1810   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
       
  1811   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
       
  1812     Table *pTab = sqliteHashData(i);
       
  1813     if( pTab->pSelect ){
       
  1814       sqliteResetColumnNames(pTab);
       
  1815     }
       
  1816   }
       
  1817   DbClearProperty(db, idx, DB_UnresetViews);
       
  1818 }
       
  1819 #else
       
  1820 # define sqliteViewResetAll(A,B)
       
  1821 #endif /* SQLITE_OMIT_VIEW */
       
  1822 
       
  1823 /*
       
  1824 ** This function is called by the VDBE to adjust the internal schema
       
  1825 ** used by SQLite when the btree layer moves a table root page. The
       
  1826 ** root-page of a table or index in database iDb has changed from iFrom
       
  1827 ** to iTo.
       
  1828 **
       
  1829 ** Ticket #1728:  The symbol table might still contain information
       
  1830 ** on tables and/or indices that are the process of being deleted.
       
  1831 ** If you are unlucky, one of those deleted indices or tables might
       
  1832 ** have the same rootpage number as the real table or index that is
       
  1833 ** being moved.  So we cannot stop searching after the first match 
       
  1834 ** because the first match might be for one of the deleted indices
       
  1835 ** or tables and not the table/index that is actually being moved.
       
  1836 ** We must continue looping until all tables and indices with
       
  1837 ** rootpage==iFrom have been converted to have a rootpage of iTo
       
  1838 ** in order to be certain that we got the right one.
       
  1839 */
       
  1840 #ifndef SQLITE_OMIT_AUTOVACUUM
       
  1841 void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
       
  1842   HashElem *pElem;
       
  1843   Hash *pHash;
       
  1844 
       
  1845   pHash = &pDb->pSchema->tblHash;
       
  1846   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
       
  1847     Table *pTab = sqliteHashData(pElem);
       
  1848     if( pTab->tnum==iFrom ){
       
  1849       pTab->tnum = iTo;
       
  1850     }
       
  1851   }
       
  1852   pHash = &pDb->pSchema->idxHash;
       
  1853   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
       
  1854     Index *pIdx = sqliteHashData(pElem);
       
  1855     if( pIdx->tnum==iFrom ){
       
  1856       pIdx->tnum = iTo;
       
  1857     }
       
  1858   }
       
  1859 }
       
  1860 #endif
       
  1861 
       
  1862 /*
       
  1863 ** Write code to erase the table with root-page iTable from database iDb.
       
  1864 ** Also write code to modify the sqlite_master table and internal schema
       
  1865 ** if a root-page of another table is moved by the btree-layer whilst
       
  1866 ** erasing iTable (this can happen with an auto-vacuum database).
       
  1867 */ 
       
  1868 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
       
  1869   Vdbe *v = sqlite3GetVdbe(pParse);
       
  1870   int r1 = sqlite3GetTempReg(pParse);
       
  1871   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
       
  1872 #ifndef SQLITE_OMIT_AUTOVACUUM
       
  1873   /* OP_Destroy stores an in integer r1. If this integer
       
  1874   ** is non-zero, then it is the root page number of a table moved to
       
  1875   ** location iTable. The following code modifies the sqlite_master table to
       
  1876   ** reflect this.
       
  1877   **
       
  1878   ** The "#%d" in the SQL is a special constant that means whatever value
       
  1879   ** is on the top of the stack.  See sqlite3RegisterExpr().
       
  1880   */
       
  1881   sqlite3NestedParse(pParse, 
       
  1882      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
       
  1883      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
       
  1884 #endif
       
  1885   sqlite3ReleaseTempReg(pParse, r1);
       
  1886 }
       
  1887 
       
  1888 /*
       
  1889 ** Write VDBE code to erase table pTab and all associated indices on disk.
       
  1890 ** Code to update the sqlite_master tables and internal schema definitions
       
  1891 ** in case a root-page belonging to another table is moved by the btree layer
       
  1892 ** is also added (this can happen with an auto-vacuum database).
       
  1893 */
       
  1894 static void destroyTable(Parse *pParse, Table *pTab){
       
  1895 #ifdef SQLITE_OMIT_AUTOVACUUM
       
  1896   Index *pIdx;
       
  1897   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
       
  1898   destroyRootPage(pParse, pTab->tnum, iDb);
       
  1899   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
       
  1900     destroyRootPage(pParse, pIdx->tnum, iDb);
       
  1901   }
       
  1902 #else
       
  1903   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
       
  1904   ** is not defined), then it is important to call OP_Destroy on the
       
  1905   ** table and index root-pages in order, starting with the numerically 
       
  1906   ** largest root-page number. This guarantees that none of the root-pages
       
  1907   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
       
  1908   ** following were coded:
       
  1909   **
       
  1910   ** OP_Destroy 4 0
       
  1911   ** ...
       
  1912   ** OP_Destroy 5 0
       
  1913   **
       
  1914   ** and root page 5 happened to be the largest root-page number in the
       
  1915   ** database, then root page 5 would be moved to page 4 by the 
       
  1916   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
       
  1917   ** a free-list page.
       
  1918   */
       
  1919   int iTab = pTab->tnum;
       
  1920   int iDestroyed = 0;
       
  1921 
       
  1922   while( 1 ){
       
  1923     Index *pIdx;
       
  1924     int iLargest = 0;
       
  1925 
       
  1926     if( iDestroyed==0 || iTab<iDestroyed ){
       
  1927       iLargest = iTab;
       
  1928     }
       
  1929     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
       
  1930       int iIdx = pIdx->tnum;
       
  1931       assert( pIdx->pSchema==pTab->pSchema );
       
  1932       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
       
  1933         iLargest = iIdx;
       
  1934       }
       
  1935     }
       
  1936     if( iLargest==0 ){
       
  1937       return;
       
  1938     }else{
       
  1939       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
       
  1940       destroyRootPage(pParse, iLargest, iDb);
       
  1941       iDestroyed = iLargest;
       
  1942     }
       
  1943   }
       
  1944 #endif
       
  1945 }
       
  1946 
       
  1947 /*
       
  1948 ** This routine is called to do the work of a DROP TABLE statement.
       
  1949 ** pName is the name of the table to be dropped.
       
  1950 */
       
  1951 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
       
  1952   Table *pTab;
       
  1953   Vdbe *v;
       
  1954   sqlite3 *db = pParse->db;
       
  1955   int iDb;
       
  1956 
       
  1957   if( pParse->nErr || db->mallocFailed ){
       
  1958     goto exit_drop_table;
       
  1959   }
       
  1960   assert( pName->nSrc==1 );
       
  1961   pTab = sqlite3LocateTable(pParse, isView, 
       
  1962                             pName->a[0].zName, pName->a[0].zDatabase);
       
  1963 
       
  1964   if( pTab==0 ){
       
  1965     if( noErr ){
       
  1966       sqlite3ErrorClear(pParse);
       
  1967     }
       
  1968     goto exit_drop_table;
       
  1969   }
       
  1970   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
       
  1971   assert( iDb>=0 && iDb<db->nDb );
       
  1972 
       
  1973   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
       
  1974   ** it is initialized.
       
  1975   */
       
  1976   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
       
  1977     goto exit_drop_table;
       
  1978   }
       
  1979 #ifndef SQLITE_OMIT_AUTHORIZATION
       
  1980   {
       
  1981     int code;
       
  1982     const char *zTab = SCHEMA_TABLE(iDb);
       
  1983     const char *zDb = db->aDb[iDb].zName;
       
  1984     const char *zArg2 = 0;
       
  1985     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
       
  1986       goto exit_drop_table;
       
  1987     }
       
  1988     if( isView ){
       
  1989       if( !OMIT_TEMPDB && iDb==1 ){
       
  1990         code = SQLITE_DROP_TEMP_VIEW;
       
  1991       }else{
       
  1992         code = SQLITE_DROP_VIEW;
       
  1993       }
       
  1994 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
  1995     }else if( IsVirtual(pTab) ){
       
  1996       code = SQLITE_DROP_VTABLE;
       
  1997       zArg2 = pTab->pMod->zName;
       
  1998 #endif
       
  1999     }else{
       
  2000       if( !OMIT_TEMPDB && iDb==1 ){
       
  2001         code = SQLITE_DROP_TEMP_TABLE;
       
  2002       }else{
       
  2003         code = SQLITE_DROP_TABLE;
       
  2004       }
       
  2005     }
       
  2006     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
       
  2007       goto exit_drop_table;
       
  2008     }
       
  2009     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
       
  2010       goto exit_drop_table;
       
  2011     }
       
  2012   }
       
  2013 #endif
       
  2014   if( pTab->readOnly || pTab==db->aDb[iDb].pSchema->pSeqTab ){
       
  2015     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
       
  2016     goto exit_drop_table;
       
  2017   }
       
  2018 
       
  2019 #ifndef SQLITE_OMIT_VIEW
       
  2020   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
       
  2021   ** on a table.
       
  2022   */
       
  2023   if( isView && pTab->pSelect==0 ){
       
  2024     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
       
  2025     goto exit_drop_table;
       
  2026   }
       
  2027   if( !isView && pTab->pSelect ){
       
  2028     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
       
  2029     goto exit_drop_table;
       
  2030   }
       
  2031 #endif
       
  2032 
       
  2033   /* Generate code to remove the table from the master table
       
  2034   ** on disk.
       
  2035   */
       
  2036   v = sqlite3GetVdbe(pParse);
       
  2037   if( v ){
       
  2038     Trigger *pTrigger;
       
  2039     Db *pDb = &db->aDb[iDb];
       
  2040     sqlite3BeginWriteOperation(pParse, 1, iDb);
       
  2041 
       
  2042 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
  2043     if( IsVirtual(pTab) ){
       
  2044       Vdbe *v = sqlite3GetVdbe(pParse);
       
  2045       if( v ){
       
  2046         sqlite3VdbeAddOp0(v, OP_VBegin);
       
  2047       }
       
  2048     }
       
  2049 #endif
       
  2050 
       
  2051     /* Drop all triggers associated with the table being dropped. Code
       
  2052     ** is generated to remove entries from sqlite_master and/or
       
  2053     ** sqlite_temp_master if required.
       
  2054     */
       
  2055     pTrigger = pTab->pTrigger;
       
  2056     while( pTrigger ){
       
  2057       assert( pTrigger->pSchema==pTab->pSchema || 
       
  2058           pTrigger->pSchema==db->aDb[1].pSchema );
       
  2059       sqlite3DropTriggerPtr(pParse, pTrigger);
       
  2060       pTrigger = pTrigger->pNext;
       
  2061     }
       
  2062 
       
  2063 #ifndef SQLITE_OMIT_AUTOINCREMENT
       
  2064     /* Remove any entries of the sqlite_sequence table associated with
       
  2065     ** the table being dropped. This is done before the table is dropped
       
  2066     ** at the btree level, in case the sqlite_sequence table needs to
       
  2067     ** move as a result of the drop (can happen in auto-vacuum mode).
       
  2068     */
       
  2069     if( pTab->autoInc ){
       
  2070       sqlite3NestedParse(pParse,
       
  2071         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
       
  2072         pDb->zName, pTab->zName
       
  2073       );
       
  2074     }
       
  2075 #endif
       
  2076 
       
  2077     /* Drop all SQLITE_MASTER table and index entries that refer to the
       
  2078     ** table. The program name loops through the master table and deletes
       
  2079     ** every row that refers to a table of the same name as the one being
       
  2080     ** dropped. Triggers are handled seperately because a trigger can be
       
  2081     ** created in the temp database that refers to a table in another
       
  2082     ** database.
       
  2083     */
       
  2084     sqlite3NestedParse(pParse, 
       
  2085         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
       
  2086         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
       
  2087 
       
  2088     /* Drop any statistics from the sqlite_stat1 table, if it exists */
       
  2089     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
       
  2090       sqlite3NestedParse(pParse,
       
  2091         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
       
  2092       );
       
  2093     }
       
  2094 
       
  2095     if( !isView && !IsVirtual(pTab) ){
       
  2096       destroyTable(pParse, pTab);
       
  2097     }
       
  2098 
       
  2099     /* Remove the table entry from SQLite's internal schema and modify
       
  2100     ** the schema cookie.
       
  2101     */
       
  2102     if( IsVirtual(pTab) ){
       
  2103       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
       
  2104     }
       
  2105     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
       
  2106     sqlite3ChangeCookie(pParse, iDb);
       
  2107   }
       
  2108   sqliteViewResetAll(db, iDb);
       
  2109 
       
  2110 exit_drop_table:
       
  2111   sqlite3SrcListDelete(db, pName);
       
  2112 }
       
  2113 
       
  2114 /*
       
  2115 ** This routine is called to create a new foreign key on the table
       
  2116 ** currently under construction.  pFromCol determines which columns
       
  2117 ** in the current table point to the foreign key.  If pFromCol==0 then
       
  2118 ** connect the key to the last column inserted.  pTo is the name of
       
  2119 ** the table referred to.  pToCol is a list of tables in the other
       
  2120 ** pTo table that the foreign key points to.  flags contains all
       
  2121 ** information about the conflict resolution algorithms specified
       
  2122 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
       
  2123 **
       
  2124 ** An FKey structure is created and added to the table currently
       
  2125 ** under construction in the pParse->pNewTable field.  The new FKey
       
  2126 ** is not linked into db->aFKey at this point - that does not happen
       
  2127 ** until sqlite3EndTable().
       
  2128 **
       
  2129 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
       
  2130 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
       
  2131 */
       
  2132 void sqlite3CreateForeignKey(
       
  2133   Parse *pParse,       /* Parsing context */
       
  2134   ExprList *pFromCol,  /* Columns in this table that point to other table */
       
  2135   Token *pTo,          /* Name of the other table */
       
  2136   ExprList *pToCol,    /* Columns in the other table */
       
  2137   int flags            /* Conflict resolution algorithms. */
       
  2138 ){
       
  2139 #ifndef SQLITE_OMIT_FOREIGN_KEY
       
  2140   FKey *pFKey = 0;
       
  2141   Table *p = pParse->pNewTable;
       
  2142   int nByte;
       
  2143   int i;
       
  2144   int nCol;
       
  2145   char *z;
       
  2146   sqlite3 *db;
       
  2147 
       
  2148   assert( pTo!=0 );
       
  2149   db = pParse->db;
       
  2150   if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
       
  2151   if( pFromCol==0 ){
       
  2152     int iCol = p->nCol-1;
       
  2153     if( iCol<0 ) goto fk_end;
       
  2154     if( pToCol && pToCol->nExpr!=1 ){
       
  2155       sqlite3ErrorMsg(pParse, "foreign key on %s"
       
  2156          " should reference only one column of table %T",
       
  2157          p->aCol[iCol].zName, pTo);
       
  2158       goto fk_end;
       
  2159     }
       
  2160     nCol = 1;
       
  2161   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
       
  2162     sqlite3ErrorMsg(pParse,
       
  2163         "number of columns in foreign key does not match the number of "
       
  2164         "columns in the referenced table");
       
  2165     goto fk_end;
       
  2166   }else{
       
  2167     nCol = pFromCol->nExpr;
       
  2168   }
       
  2169   nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
       
  2170   if( pToCol ){
       
  2171     for(i=0; i<pToCol->nExpr; i++){
       
  2172       nByte += strlen(pToCol->a[i].zName) + 1;
       
  2173     }
       
  2174   }
       
  2175   pFKey = sqlite3DbMallocZero(db, nByte );
       
  2176   if( pFKey==0 ){
       
  2177     goto fk_end;
       
  2178   }
       
  2179   pFKey->pFrom = p;
       
  2180   pFKey->pNextFrom = p->pFKey;
       
  2181   z = (char*)&pFKey[1];
       
  2182   pFKey->aCol = (struct sColMap*)z;
       
  2183   z += sizeof(struct sColMap)*nCol;
       
  2184   pFKey->zTo = z;
       
  2185   memcpy(z, pTo->z, pTo->n);
       
  2186   z[pTo->n] = 0;
       
  2187   z += pTo->n+1;
       
  2188   pFKey->pNextTo = 0;
       
  2189   pFKey->nCol = nCol;
       
  2190   if( pFromCol==0 ){
       
  2191     pFKey->aCol[0].iFrom = p->nCol-1;
       
  2192   }else{
       
  2193     for(i=0; i<nCol; i++){
       
  2194       int j;
       
  2195       for(j=0; j<p->nCol; j++){
       
  2196         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
       
  2197           pFKey->aCol[i].iFrom = j;
       
  2198           break;
       
  2199         }
       
  2200       }
       
  2201       if( j>=p->nCol ){
       
  2202         sqlite3ErrorMsg(pParse, 
       
  2203           "unknown column \"%s\" in foreign key definition", 
       
  2204           pFromCol->a[i].zName);
       
  2205         goto fk_end;
       
  2206       }
       
  2207     }
       
  2208   }
       
  2209   if( pToCol ){
       
  2210     for(i=0; i<nCol; i++){
       
  2211       int n = strlen(pToCol->a[i].zName);
       
  2212       pFKey->aCol[i].zCol = z;
       
  2213       memcpy(z, pToCol->a[i].zName, n);
       
  2214       z[n] = 0;
       
  2215       z += n+1;
       
  2216     }
       
  2217   }
       
  2218   pFKey->isDeferred = 0;
       
  2219   pFKey->deleteConf = flags & 0xff;
       
  2220   pFKey->updateConf = (flags >> 8 ) & 0xff;
       
  2221   pFKey->insertConf = (flags >> 16 ) & 0xff;
       
  2222 
       
  2223   /* Link the foreign key to the table as the last step.
       
  2224   */
       
  2225   p->pFKey = pFKey;
       
  2226   pFKey = 0;
       
  2227 
       
  2228 fk_end:
       
  2229   sqlite3DbFree(db, pFKey);
       
  2230 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
       
  2231   sqlite3ExprListDelete(db, pFromCol);
       
  2232   sqlite3ExprListDelete(db, pToCol);
       
  2233 }
       
  2234 
       
  2235 /*
       
  2236 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
       
  2237 ** clause is seen as part of a foreign key definition.  The isDeferred
       
  2238 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
       
  2239 ** The behavior of the most recently created foreign key is adjusted
       
  2240 ** accordingly.
       
  2241 */
       
  2242 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
       
  2243 #ifndef SQLITE_OMIT_FOREIGN_KEY
       
  2244   Table *pTab;
       
  2245   FKey *pFKey;
       
  2246   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
       
  2247   pFKey->isDeferred = isDeferred;
       
  2248 #endif
       
  2249 }
       
  2250 
       
  2251 /*
       
  2252 ** Generate code that will erase and refill index *pIdx.  This is
       
  2253 ** used to initialize a newly created index or to recompute the
       
  2254 ** content of an index in response to a REINDEX command.
       
  2255 **
       
  2256 ** if memRootPage is not negative, it means that the index is newly
       
  2257 ** created.  The register specified by memRootPage contains the
       
  2258 ** root page number of the index.  If memRootPage is negative, then
       
  2259 ** the index already exists and must be cleared before being refilled and
       
  2260 ** the root page number of the index is taken from pIndex->tnum.
       
  2261 */
       
  2262 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
       
  2263   Table *pTab = pIndex->pTable;  /* The table that is indexed */
       
  2264   int iTab = pParse->nTab;       /* Btree cursor used for pTab */
       
  2265   int iIdx = pParse->nTab+1;     /* Btree cursor used for pIndex */
       
  2266   int addr1;                     /* Address of top of loop */
       
  2267   int tnum;                      /* Root page of index */
       
  2268   Vdbe *v;                       /* Generate code into this virtual machine */
       
  2269   KeyInfo *pKey;                 /* KeyInfo for index */
       
  2270   int regIdxKey;                 /* Registers containing the index key */
       
  2271   int regRecord;                 /* Register holding assemblied index record */
       
  2272   sqlite3 *db = pParse->db;      /* The database connection */
       
  2273   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
       
  2274 
       
  2275 #ifndef SQLITE_OMIT_AUTHORIZATION
       
  2276   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
       
  2277       db->aDb[iDb].zName ) ){
       
  2278     return;
       
  2279   }
       
  2280 #endif
       
  2281 
       
  2282   /* Require a write-lock on the table to perform this operation */
       
  2283   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
       
  2284 
       
  2285   v = sqlite3GetVdbe(pParse);
       
  2286   if( v==0 ) return;
       
  2287   if( memRootPage>=0 ){
       
  2288     tnum = memRootPage;
       
  2289   }else{
       
  2290     tnum = pIndex->tnum;
       
  2291     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
       
  2292   }
       
  2293   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
       
  2294   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
       
  2295                     (char *)pKey, P4_KEYINFO_HANDOFF);
       
  2296   if( memRootPage>=0 ){
       
  2297     sqlite3VdbeChangeP5(v, 1);
       
  2298   }
       
  2299   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
       
  2300   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
       
  2301   regRecord = sqlite3GetTempReg(pParse);
       
  2302   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
       
  2303   if( pIndex->onError!=OE_None ){
       
  2304     int j1, j2;
       
  2305     int regRowid;
       
  2306 
       
  2307     regRowid = regIdxKey + pIndex->nColumn;
       
  2308     j1 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdxKey, 0, pIndex->nColumn);
       
  2309     j2 = sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx,
       
  2310                            0, regRowid, SQLITE_INT_TO_PTR(regRecord), P4_INT32);
       
  2311     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0,
       
  2312                     "indexed columns are not unique", P4_STATIC);
       
  2313     sqlite3VdbeJumpHere(v, j1);
       
  2314     sqlite3VdbeJumpHere(v, j2);
       
  2315   }
       
  2316   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
       
  2317   sqlite3ReleaseTempReg(pParse, regRecord);
       
  2318   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
       
  2319   sqlite3VdbeJumpHere(v, addr1);
       
  2320   sqlite3VdbeAddOp1(v, OP_Close, iTab);
       
  2321   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
       
  2322 }
       
  2323 
       
  2324 /*
       
  2325 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
       
  2326 ** and pTblList is the name of the table that is to be indexed.  Both will 
       
  2327 ** be NULL for a primary key or an index that is created to satisfy a
       
  2328 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
       
  2329 ** as the table to be indexed.  pParse->pNewTable is a table that is
       
  2330 ** currently being constructed by a CREATE TABLE statement.
       
  2331 **
       
  2332 ** pList is a list of columns to be indexed.  pList will be NULL if this
       
  2333 ** is a primary key or unique-constraint on the most recent column added
       
  2334 ** to the table currently under construction.  
       
  2335 */
       
  2336 void sqlite3CreateIndex(
       
  2337   Parse *pParse,     /* All information about this parse */
       
  2338   Token *pName1,     /* First part of index name. May be NULL */
       
  2339   Token *pName2,     /* Second part of index name. May be NULL */
       
  2340   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
       
  2341   ExprList *pList,   /* A list of columns to be indexed */
       
  2342   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
       
  2343   Token *pStart,     /* The CREATE token that begins this statement */
       
  2344   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
       
  2345   int sortOrder,     /* Sort order of primary key when pList==NULL */
       
  2346   int ifNotExist     /* Omit error if index already exists */
       
  2347 ){
       
  2348   Table *pTab = 0;     /* Table to be indexed */
       
  2349   Index *pIndex = 0;   /* The index to be created */
       
  2350   char *zName = 0;     /* Name of the index */
       
  2351   int nName;           /* Number of characters in zName */
       
  2352   int i, j;
       
  2353   Token nullId;        /* Fake token for an empty ID list */
       
  2354   DbFixer sFix;        /* For assigning database names to pTable */
       
  2355   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
       
  2356   sqlite3 *db = pParse->db;
       
  2357   Db *pDb;             /* The specific table containing the indexed database */
       
  2358   int iDb;             /* Index of the database that is being written */
       
  2359   Token *pName = 0;    /* Unqualified name of the index to create */
       
  2360   struct ExprList_item *pListItem; /* For looping over pList */
       
  2361   int nCol;
       
  2362   int nExtra = 0;
       
  2363   char *zExtra;
       
  2364 
       
  2365   if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){
       
  2366     goto exit_create_index;
       
  2367   }
       
  2368 
       
  2369   /*
       
  2370   ** Find the table that is to be indexed.  Return early if not found.
       
  2371   */
       
  2372   if( pTblName!=0 ){
       
  2373 
       
  2374     /* Use the two-part index name to determine the database 
       
  2375     ** to search for the table. 'Fix' the table name to this db
       
  2376     ** before looking up the table.
       
  2377     */
       
  2378     assert( pName1 && pName2 );
       
  2379     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
       
  2380     if( iDb<0 ) goto exit_create_index;
       
  2381 
       
  2382 #ifndef SQLITE_OMIT_TEMPDB
       
  2383     /* If the index name was unqualified, check if the the table
       
  2384     ** is a temp table. If so, set the database to 1. Do not do this
       
  2385     ** if initialising a database schema.
       
  2386     */
       
  2387     if( !db->init.busy ){
       
  2388       pTab = sqlite3SrcListLookup(pParse, pTblName);
       
  2389       if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
       
  2390         iDb = 1;
       
  2391       }
       
  2392     }
       
  2393 #endif
       
  2394 
       
  2395     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
       
  2396         sqlite3FixSrcList(&sFix, pTblName)
       
  2397     ){
       
  2398       /* Because the parser constructs pTblName from a single identifier,
       
  2399       ** sqlite3FixSrcList can never fail. */
       
  2400       assert(0);
       
  2401     }
       
  2402     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
       
  2403         pTblName->a[0].zDatabase);
       
  2404     if( !pTab ) goto exit_create_index;
       
  2405     assert( db->aDb[iDb].pSchema==pTab->pSchema );
       
  2406   }else{
       
  2407     assert( pName==0 );
       
  2408     pTab = pParse->pNewTable;
       
  2409     if( !pTab ) goto exit_create_index;
       
  2410     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
       
  2411   }
       
  2412   pDb = &db->aDb[iDb];
       
  2413 
       
  2414   if( pTab==0 || pParse->nErr ) goto exit_create_index;
       
  2415   if( pTab->readOnly ){
       
  2416     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
       
  2417     goto exit_create_index;
       
  2418   }
       
  2419 #ifndef SQLITE_OMIT_VIEW
       
  2420   if( pTab->pSelect ){
       
  2421     sqlite3ErrorMsg(pParse, "views may not be indexed");
       
  2422     goto exit_create_index;
       
  2423   }
       
  2424 #endif
       
  2425 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
  2426   if( IsVirtual(pTab) ){
       
  2427     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
       
  2428     goto exit_create_index;
       
  2429   }
       
  2430 #endif
       
  2431 
       
  2432   /*
       
  2433   ** Find the name of the index.  Make sure there is not already another
       
  2434   ** index or table with the same name.  
       
  2435   **
       
  2436   ** Exception:  If we are reading the names of permanent indices from the
       
  2437   ** sqlite_master table (because some other process changed the schema) and
       
  2438   ** one of the index names collides with the name of a temporary table or
       
  2439   ** index, then we will continue to process this index.
       
  2440   **
       
  2441   ** If pName==0 it means that we are
       
  2442   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
       
  2443   ** own name.
       
  2444   */
       
  2445   if( pName ){
       
  2446     zName = sqlite3NameFromToken(db, pName);
       
  2447     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
       
  2448     if( zName==0 ) goto exit_create_index;
       
  2449     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
       
  2450       goto exit_create_index;
       
  2451     }
       
  2452     if( !db->init.busy ){
       
  2453       if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
       
  2454       if( sqlite3FindTable(db, zName, 0)!=0 ){
       
  2455         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
       
  2456         goto exit_create_index;
       
  2457       }
       
  2458     }
       
  2459     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
       
  2460       if( !ifNotExist ){
       
  2461         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
       
  2462       }
       
  2463       goto exit_create_index;
       
  2464     }
       
  2465   }else{
       
  2466     int n;
       
  2467     Index *pLoop;
       
  2468     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
       
  2469     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
       
  2470     if( zName==0 ){
       
  2471       goto exit_create_index;
       
  2472     }
       
  2473   }
       
  2474 
       
  2475   /* Check for authorization to create an index.
       
  2476   */
       
  2477 #ifndef SQLITE_OMIT_AUTHORIZATION
       
  2478   {
       
  2479     const char *zDb = pDb->zName;
       
  2480     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
       
  2481       goto exit_create_index;
       
  2482     }
       
  2483     i = SQLITE_CREATE_INDEX;
       
  2484     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
       
  2485     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
       
  2486       goto exit_create_index;
       
  2487     }
       
  2488   }
       
  2489 #endif
       
  2490 
       
  2491   /* If pList==0, it means this routine was called to make a primary
       
  2492   ** key out of the last column added to the table under construction.
       
  2493   ** So create a fake list to simulate this.
       
  2494   */
       
  2495   if( pList==0 ){
       
  2496     nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
       
  2497     nullId.n = strlen((char*)nullId.z);
       
  2498     pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
       
  2499     if( pList==0 ) goto exit_create_index;
       
  2500     pList->a[0].sortOrder = sortOrder;
       
  2501   }
       
  2502 
       
  2503   /* Figure out how many bytes of space are required to store explicitly
       
  2504   ** specified collation sequence names.
       
  2505   */
       
  2506   for(i=0; i<pList->nExpr; i++){
       
  2507     Expr *pExpr = pList->a[i].pExpr;
       
  2508     if( pExpr ){
       
  2509       nExtra += (1 + strlen(pExpr->pColl->zName));
       
  2510     }
       
  2511   }
       
  2512 
       
  2513   /* 
       
  2514   ** Allocate the index structure. 
       
  2515   */
       
  2516   nName = strlen(zName);
       
  2517   nCol = pList->nExpr;
       
  2518   pIndex = sqlite3DbMallocZero(db, 
       
  2519       sizeof(Index) +              /* Index structure  */
       
  2520       sizeof(int)*nCol +           /* Index.aiColumn   */
       
  2521       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
       
  2522       sizeof(char *)*nCol +        /* Index.azColl     */
       
  2523       sizeof(u8)*nCol +            /* Index.aSortOrder */
       
  2524       nName + 1 +                  /* Index.zName      */
       
  2525       nExtra                       /* Collation sequence names */
       
  2526   );
       
  2527   if( db->mallocFailed ){
       
  2528     goto exit_create_index;
       
  2529   }
       
  2530   pIndex->azColl = (char**)(&pIndex[1]);
       
  2531   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
       
  2532   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
       
  2533   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
       
  2534   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
       
  2535   zExtra = (char *)(&pIndex->zName[nName+1]);
       
  2536   memcpy(pIndex->zName, zName, nName+1);
       
  2537   pIndex->pTable = pTab;
       
  2538   pIndex->nColumn = pList->nExpr;
       
  2539   pIndex->onError = onError;
       
  2540   pIndex->autoIndex = pName==0;
       
  2541   pIndex->pSchema = db->aDb[iDb].pSchema;
       
  2542 
       
  2543   /* Check to see if we should honor DESC requests on index columns
       
  2544   */
       
  2545   if( pDb->pSchema->file_format>=4 ){
       
  2546     sortOrderMask = -1;   /* Honor DESC */
       
  2547   }else{
       
  2548     sortOrderMask = 0;    /* Ignore DESC */
       
  2549   }
       
  2550 
       
  2551   /* Scan the names of the columns of the table to be indexed and
       
  2552   ** load the column indices into the Index structure.  Report an error
       
  2553   ** if any column is not found.
       
  2554   */
       
  2555   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
       
  2556     const char *zColName = pListItem->zName;
       
  2557     Column *pTabCol;
       
  2558     int requestedSortOrder;
       
  2559     char *zColl;                   /* Collation sequence name */
       
  2560 
       
  2561     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
       
  2562       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
       
  2563     }
       
  2564     if( j>=pTab->nCol ){
       
  2565       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
       
  2566         pTab->zName, zColName);
       
  2567       goto exit_create_index;
       
  2568     }
       
  2569     /* TODO:  Add a test to make sure that the same column is not named
       
  2570     ** more than once within the same index.  Only the first instance of
       
  2571     ** the column will ever be used by the optimizer.  Note that using the
       
  2572     ** same column more than once cannot be an error because that would 
       
  2573     ** break backwards compatibility - it needs to be a warning.
       
  2574     */
       
  2575     pIndex->aiColumn[i] = j;
       
  2576     if( pListItem->pExpr ){
       
  2577       assert( pListItem->pExpr->pColl );
       
  2578       zColl = zExtra;
       
  2579       sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName);
       
  2580       zExtra += (strlen(zColl) + 1);
       
  2581     }else{
       
  2582       zColl = pTab->aCol[j].zColl;
       
  2583       if( !zColl ){
       
  2584         zColl = db->pDfltColl->zName;
       
  2585       }
       
  2586     }
       
  2587     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
       
  2588       goto exit_create_index;
       
  2589     }
       
  2590     pIndex->azColl[i] = zColl;
       
  2591     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
       
  2592     pIndex->aSortOrder[i] = requestedSortOrder;
       
  2593   }
       
  2594   sqlite3DefaultRowEst(pIndex);
       
  2595 
       
  2596   if( pTab==pParse->pNewTable ){
       
  2597     /* This routine has been called to create an automatic index as a
       
  2598     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
       
  2599     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
       
  2600     ** i.e. one of:
       
  2601     **
       
  2602     ** CREATE TABLE t(x PRIMARY KEY, y);
       
  2603     ** CREATE TABLE t(x, y, UNIQUE(x, y));
       
  2604     **
       
  2605     ** Either way, check to see if the table already has such an index. If
       
  2606     ** so, don't bother creating this one. This only applies to
       
  2607     ** automatically created indices. Users can do as they wish with
       
  2608     ** explicit indices.
       
  2609     */
       
  2610     Index *pIdx;
       
  2611     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
       
  2612       int k;
       
  2613       assert( pIdx->onError!=OE_None );
       
  2614       assert( pIdx->autoIndex );
       
  2615       assert( pIndex->onError!=OE_None );
       
  2616 
       
  2617       if( pIdx->nColumn!=pIndex->nColumn ) continue;
       
  2618       for(k=0; k<pIdx->nColumn; k++){
       
  2619         const char *z1 = pIdx->azColl[k];
       
  2620         const char *z2 = pIndex->azColl[k];
       
  2621         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
       
  2622         if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
       
  2623         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
       
  2624       }
       
  2625       if( k==pIdx->nColumn ){
       
  2626         if( pIdx->onError!=pIndex->onError ){
       
  2627           /* This constraint creates the same index as a previous
       
  2628           ** constraint specified somewhere in the CREATE TABLE statement.
       
  2629           ** However the ON CONFLICT clauses are different. If both this 
       
  2630           ** constraint and the previous equivalent constraint have explicit
       
  2631           ** ON CONFLICT clauses this is an error. Otherwise, use the
       
  2632           ** explicitly specified behaviour for the index.
       
  2633           */
       
  2634           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
       
  2635             sqlite3ErrorMsg(pParse, 
       
  2636                 "conflicting ON CONFLICT clauses specified", 0);
       
  2637           }
       
  2638           if( pIdx->onError==OE_Default ){
       
  2639             pIdx->onError = pIndex->onError;
       
  2640           }
       
  2641         }
       
  2642         goto exit_create_index;
       
  2643       }
       
  2644     }
       
  2645   }
       
  2646 
       
  2647   /* Link the new Index structure to its table and to the other
       
  2648   ** in-memory database structures. 
       
  2649   */
       
  2650   if( db->init.busy ){
       
  2651     Index *p;
       
  2652     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
       
  2653                          pIndex->zName, strlen(pIndex->zName)+1, pIndex);
       
  2654     if( p ){
       
  2655       assert( p==pIndex );  /* Malloc must have failed */
       
  2656       db->mallocFailed = 1;
       
  2657       goto exit_create_index;
       
  2658     }
       
  2659     db->flags |= SQLITE_InternChanges;
       
  2660     if( pTblName!=0 ){
       
  2661       pIndex->tnum = db->init.newTnum;
       
  2662     }
       
  2663   }
       
  2664 
       
  2665   /* If the db->init.busy is 0 then create the index on disk.  This
       
  2666   ** involves writing the index into the master table and filling in the
       
  2667   ** index with the current table contents.
       
  2668   **
       
  2669   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
       
  2670   ** command.  db->init.busy is 1 when a database is opened and 
       
  2671   ** CREATE INDEX statements are read out of the master table.  In
       
  2672   ** the latter case the index already exists on disk, which is why
       
  2673   ** we don't want to recreate it.
       
  2674   **
       
  2675   ** If pTblName==0 it means this index is generated as a primary key
       
  2676   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
       
  2677   ** has just been created, it contains no data and the index initialization
       
  2678   ** step can be skipped.
       
  2679   */
       
  2680   else if( db->init.busy==0 ){
       
  2681     Vdbe *v;
       
  2682     char *zStmt;
       
  2683     int iMem = ++pParse->nMem;
       
  2684 
       
  2685     v = sqlite3GetVdbe(pParse);
       
  2686     if( v==0 ) goto exit_create_index;
       
  2687 
       
  2688 
       
  2689     /* Create the rootpage for the index
       
  2690     */
       
  2691     sqlite3BeginWriteOperation(pParse, 1, iDb);
       
  2692     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
       
  2693 
       
  2694     /* Gather the complete text of the CREATE INDEX statement into
       
  2695     ** the zStmt variable
       
  2696     */
       
  2697     if( pStart && pEnd ){
       
  2698       /* A named index with an explicit CREATE INDEX statement */
       
  2699       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
       
  2700         onError==OE_None ? "" : " UNIQUE",
       
  2701         pEnd->z - pName->z + 1,
       
  2702         pName->z);
       
  2703     }else{
       
  2704       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
       
  2705       /* zStmt = sqlite3MPrintf(""); */
       
  2706       zStmt = 0;
       
  2707     }
       
  2708 
       
  2709     /* Add an entry in sqlite_master for this index
       
  2710     */
       
  2711     sqlite3NestedParse(pParse, 
       
  2712         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
       
  2713         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
       
  2714         pIndex->zName,
       
  2715         pTab->zName,
       
  2716         iMem,
       
  2717         zStmt
       
  2718     );
       
  2719     sqlite3DbFree(db, zStmt);
       
  2720 
       
  2721     /* Fill the index with data and reparse the schema. Code an OP_Expire
       
  2722     ** to invalidate all pre-compiled statements.
       
  2723     */
       
  2724     if( pTblName ){
       
  2725       sqlite3RefillIndex(pParse, pIndex, iMem);
       
  2726       sqlite3ChangeCookie(pParse, iDb);
       
  2727       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
       
  2728          sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
       
  2729       sqlite3VdbeAddOp1(v, OP_Expire, 0);
       
  2730     }
       
  2731   }
       
  2732 
       
  2733   /* When adding an index to the list of indices for a table, make
       
  2734   ** sure all indices labeled OE_Replace come after all those labeled
       
  2735   ** OE_Ignore.  This is necessary for the correct operation of UPDATE
       
  2736   ** and INSERT.
       
  2737   */
       
  2738   if( db->init.busy || pTblName==0 ){
       
  2739     if( onError!=OE_Replace || pTab->pIndex==0
       
  2740          || pTab->pIndex->onError==OE_Replace){
       
  2741       pIndex->pNext = pTab->pIndex;
       
  2742       pTab->pIndex = pIndex;
       
  2743     }else{
       
  2744       Index *pOther = pTab->pIndex;
       
  2745       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
       
  2746         pOther = pOther->pNext;
       
  2747       }
       
  2748       pIndex->pNext = pOther->pNext;
       
  2749       pOther->pNext = pIndex;
       
  2750     }
       
  2751     pIndex = 0;
       
  2752   }
       
  2753 
       
  2754   /* Clean up before exiting */
       
  2755 exit_create_index:
       
  2756   if( pIndex ){
       
  2757     sqlite3_free(pIndex->zColAff);
       
  2758     sqlite3DbFree(db, pIndex);  
       
  2759   }
       
  2760   sqlite3ExprListDelete(db, pList);
       
  2761   sqlite3SrcListDelete(db, pTblName);
       
  2762   sqlite3DbFree(db, zName);
       
  2763   return;
       
  2764 }
       
  2765 
       
  2766 /*
       
  2767 ** Generate code to make sure the file format number is at least minFormat.
       
  2768 ** The generated code will increase the file format number if necessary.
       
  2769 */
       
  2770 void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
       
  2771   Vdbe *v;
       
  2772   v = sqlite3GetVdbe(pParse);
       
  2773   if( v ){
       
  2774     int r1 = sqlite3GetTempReg(pParse);
       
  2775     int r2 = sqlite3GetTempReg(pParse);
       
  2776     int j1;
       
  2777     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, 1);
       
  2778     sqlite3VdbeUsesBtree(v, iDb);
       
  2779     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
       
  2780     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
       
  2781     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, r2);
       
  2782     sqlite3VdbeJumpHere(v, j1);
       
  2783     sqlite3ReleaseTempReg(pParse, r1);
       
  2784     sqlite3ReleaseTempReg(pParse, r2);
       
  2785   }
       
  2786 }
       
  2787 
       
  2788 /*
       
  2789 ** Fill the Index.aiRowEst[] array with default information - information
       
  2790 ** to be used when we have not run the ANALYZE command.
       
  2791 **
       
  2792 ** aiRowEst[0] is suppose to contain the number of elements in the index.
       
  2793 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
       
  2794 ** number of rows in the table that match any particular value of the
       
  2795 ** first column of the index.  aiRowEst[2] is an estimate of the number
       
  2796 ** of rows that match any particular combiniation of the first 2 columns
       
  2797 ** of the index.  And so forth.  It must always be the case that
       
  2798 *
       
  2799 **           aiRowEst[N]<=aiRowEst[N-1]
       
  2800 **           aiRowEst[N]>=1
       
  2801 **
       
  2802 ** Apart from that, we have little to go on besides intuition as to
       
  2803 ** how aiRowEst[] should be initialized.  The numbers generated here
       
  2804 ** are based on typical values found in actual indices.
       
  2805 */
       
  2806 void sqlite3DefaultRowEst(Index *pIdx){
       
  2807   unsigned *a = pIdx->aiRowEst;
       
  2808   int i;
       
  2809   assert( a!=0 );
       
  2810   a[0] = 1000000;
       
  2811   for(i=pIdx->nColumn; i>=5; i--){
       
  2812     a[i] = 5;
       
  2813   }
       
  2814   while( i>=1 ){
       
  2815     a[i] = 11 - i;
       
  2816     i--;
       
  2817   }
       
  2818   if( pIdx->onError!=OE_None ){
       
  2819     a[pIdx->nColumn] = 1;
       
  2820   }
       
  2821 }
       
  2822 
       
  2823 /*
       
  2824 ** This routine will drop an existing named index.  This routine
       
  2825 ** implements the DROP INDEX statement.
       
  2826 */
       
  2827 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
       
  2828   Index *pIndex;
       
  2829   Vdbe *v;
       
  2830   sqlite3 *db = pParse->db;
       
  2831   int iDb;
       
  2832 
       
  2833   if( pParse->nErr || db->mallocFailed ){
       
  2834     goto exit_drop_index;
       
  2835   }
       
  2836   assert( pName->nSrc==1 );
       
  2837   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
       
  2838     goto exit_drop_index;
       
  2839   }
       
  2840   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
       
  2841   if( pIndex==0 ){
       
  2842     if( !ifExists ){
       
  2843       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
       
  2844     }
       
  2845     pParse->checkSchema = 1;
       
  2846     goto exit_drop_index;
       
  2847   }
       
  2848   if( pIndex->autoIndex ){
       
  2849     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
       
  2850       "or PRIMARY KEY constraint cannot be dropped", 0);
       
  2851     goto exit_drop_index;
       
  2852   }
       
  2853   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
       
  2854 #ifndef SQLITE_OMIT_AUTHORIZATION
       
  2855   {
       
  2856     int code = SQLITE_DROP_INDEX;
       
  2857     Table *pTab = pIndex->pTable;
       
  2858     const char *zDb = db->aDb[iDb].zName;
       
  2859     const char *zTab = SCHEMA_TABLE(iDb);
       
  2860     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
       
  2861       goto exit_drop_index;
       
  2862     }
       
  2863     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
       
  2864     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
       
  2865       goto exit_drop_index;
       
  2866     }
       
  2867   }
       
  2868 #endif
       
  2869 
       
  2870   /* Generate code to remove the index and from the master table */
       
  2871   v = sqlite3GetVdbe(pParse);
       
  2872   if( v ){
       
  2873     sqlite3BeginWriteOperation(pParse, 1, iDb);
       
  2874     sqlite3NestedParse(pParse,
       
  2875        "DELETE FROM %Q.%s WHERE name=%Q",
       
  2876        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
       
  2877        pIndex->zName
       
  2878     );
       
  2879     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
       
  2880       sqlite3NestedParse(pParse,
       
  2881         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
       
  2882         db->aDb[iDb].zName, pIndex->zName
       
  2883       );
       
  2884     }
       
  2885     sqlite3ChangeCookie(pParse, iDb);
       
  2886     destroyRootPage(pParse, pIndex->tnum, iDb);
       
  2887     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
       
  2888   }
       
  2889 
       
  2890 exit_drop_index:
       
  2891   sqlite3SrcListDelete(db, pName);
       
  2892 }
       
  2893 
       
  2894 /*
       
  2895 ** pArray is a pointer to an array of objects.  Each object in the
       
  2896 ** array is szEntry bytes in size.  This routine allocates a new
       
  2897 ** object on the end of the array.
       
  2898 **
       
  2899 ** *pnEntry is the number of entries already in use.  *pnAlloc is
       
  2900 ** the previously allocated size of the array.  initSize is the
       
  2901 ** suggested initial array size allocation.
       
  2902 **
       
  2903 ** The index of the new entry is returned in *pIdx.
       
  2904 **
       
  2905 ** This routine returns a pointer to the array of objects.  This
       
  2906 ** might be the same as the pArray parameter or it might be a different
       
  2907 ** pointer if the array was resized.
       
  2908 */
       
  2909 void *sqlite3ArrayAllocate(
       
  2910   sqlite3 *db,      /* Connection to notify of malloc failures */
       
  2911   void *pArray,     /* Array of objects.  Might be reallocated */
       
  2912   int szEntry,      /* Size of each object in the array */
       
  2913   int initSize,     /* Suggested initial allocation, in elements */
       
  2914   int *pnEntry,     /* Number of objects currently in use */
       
  2915   int *pnAlloc,     /* Current size of the allocation, in elements */
       
  2916   int *pIdx         /* Write the index of a new slot here */
       
  2917 ){
       
  2918   char *z;
       
  2919   if( *pnEntry >= *pnAlloc ){
       
  2920     void *pNew;
       
  2921     int newSize;
       
  2922     newSize = (*pnAlloc)*2 + initSize;
       
  2923     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
       
  2924     if( pNew==0 ){
       
  2925       *pIdx = -1;
       
  2926       return pArray;
       
  2927     }
       
  2928     *pnAlloc = newSize;
       
  2929     pArray = pNew;
       
  2930   }
       
  2931   z = (char*)pArray;
       
  2932   memset(&z[*pnEntry * szEntry], 0, szEntry);
       
  2933   *pIdx = *pnEntry;
       
  2934   ++*pnEntry;
       
  2935   return pArray;
       
  2936 }
       
  2937 
       
  2938 /*
       
  2939 ** Append a new element to the given IdList.  Create a new IdList if
       
  2940 ** need be.
       
  2941 **
       
  2942 ** A new IdList is returned, or NULL if malloc() fails.
       
  2943 */
       
  2944 IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
       
  2945   int i;
       
  2946   if( pList==0 ){
       
  2947     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
       
  2948     if( pList==0 ) return 0;
       
  2949     pList->nAlloc = 0;
       
  2950   }
       
  2951   pList->a = sqlite3ArrayAllocate(
       
  2952       db,
       
  2953       pList->a,
       
  2954       sizeof(pList->a[0]),
       
  2955       5,
       
  2956       &pList->nId,
       
  2957       &pList->nAlloc,
       
  2958       &i
       
  2959   );
       
  2960   if( i<0 ){
       
  2961     sqlite3IdListDelete(db, pList);
       
  2962     return 0;
       
  2963   }
       
  2964   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
       
  2965   return pList;
       
  2966 }
       
  2967 
       
  2968 /*
       
  2969 ** Delete an IdList.
       
  2970 */
       
  2971 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
       
  2972   int i;
       
  2973   if( pList==0 ) return;
       
  2974   for(i=0; i<pList->nId; i++){
       
  2975     sqlite3DbFree(db, pList->a[i].zName);
       
  2976   }
       
  2977   sqlite3DbFree(db, pList->a);
       
  2978   sqlite3DbFree(db, pList);
       
  2979 }
       
  2980 
       
  2981 /*
       
  2982 ** Return the index in pList of the identifier named zId.  Return -1
       
  2983 ** if not found.
       
  2984 */
       
  2985 int sqlite3IdListIndex(IdList *pList, const char *zName){
       
  2986   int i;
       
  2987   if( pList==0 ) return -1;
       
  2988   for(i=0; i<pList->nId; i++){
       
  2989     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
       
  2990   }
       
  2991   return -1;
       
  2992 }
       
  2993 
       
  2994 /*
       
  2995 ** Append a new table name to the given SrcList.  Create a new SrcList if
       
  2996 ** need be.  A new entry is created in the SrcList even if pToken is NULL.
       
  2997 **
       
  2998 ** A new SrcList is returned, or NULL if malloc() fails.
       
  2999 **
       
  3000 ** If pDatabase is not null, it means that the table has an optional
       
  3001 ** database name prefix.  Like this:  "database.table".  The pDatabase
       
  3002 ** points to the table name and the pTable points to the database name.
       
  3003 ** The SrcList.a[].zName field is filled with the table name which might
       
  3004 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
       
  3005 ** SrcList.a[].zDatabase is filled with the database name from pTable,
       
  3006 ** or with NULL if no database is specified.
       
  3007 **
       
  3008 ** In other words, if call like this:
       
  3009 **
       
  3010 **         sqlite3SrcListAppend(D,A,B,0);
       
  3011 **
       
  3012 ** Then B is a table name and the database name is unspecified.  If called
       
  3013 ** like this:
       
  3014 **
       
  3015 **         sqlite3SrcListAppend(D,A,B,C);
       
  3016 **
       
  3017 ** Then C is the table name and B is the database name.
       
  3018 */
       
  3019 SrcList *sqlite3SrcListAppend(
       
  3020   sqlite3 *db,        /* Connection to notify of malloc failures */
       
  3021   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
       
  3022   Token *pTable,      /* Table to append */
       
  3023   Token *pDatabase    /* Database of the table */
       
  3024 ){
       
  3025   struct SrcList_item *pItem;
       
  3026   if( pList==0 ){
       
  3027     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
       
  3028     if( pList==0 ) return 0;
       
  3029     pList->nAlloc = 1;
       
  3030   }
       
  3031   if( pList->nSrc>=pList->nAlloc ){
       
  3032     SrcList *pNew;
       
  3033     pList->nAlloc *= 2;
       
  3034     pNew = sqlite3DbRealloc(db, pList,
       
  3035                sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
       
  3036     if( pNew==0 ){
       
  3037       sqlite3SrcListDelete(db, pList);
       
  3038       return 0;
       
  3039     }
       
  3040     pList = pNew;
       
  3041   }
       
  3042   pItem = &pList->a[pList->nSrc];
       
  3043   memset(pItem, 0, sizeof(pList->a[0]));
       
  3044   if( pDatabase && pDatabase->z==0 ){
       
  3045     pDatabase = 0;
       
  3046   }
       
  3047   if( pDatabase && pTable ){
       
  3048     Token *pTemp = pDatabase;
       
  3049     pDatabase = pTable;
       
  3050     pTable = pTemp;
       
  3051   }
       
  3052   pItem->zName = sqlite3NameFromToken(db, pTable);
       
  3053   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
       
  3054   pItem->iCursor = -1;
       
  3055   pItem->isPopulated = 0;
       
  3056   pList->nSrc++;
       
  3057   return pList;
       
  3058 }
       
  3059 
       
  3060 /*
       
  3061 ** Assign cursors to all tables in a SrcList
       
  3062 */
       
  3063 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
       
  3064   int i;
       
  3065   struct SrcList_item *pItem;
       
  3066   assert(pList || pParse->db->mallocFailed );
       
  3067   if( pList ){
       
  3068     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
       
  3069       if( pItem->iCursor>=0 ) break;
       
  3070       pItem->iCursor = pParse->nTab++;
       
  3071       if( pItem->pSelect ){
       
  3072         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
       
  3073       }
       
  3074     }
       
  3075   }
       
  3076 }
       
  3077 
       
  3078 /*
       
  3079 ** Delete an entire SrcList including all its substructure.
       
  3080 */
       
  3081 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
       
  3082   int i;
       
  3083   struct SrcList_item *pItem;
       
  3084   if( pList==0 ) return;
       
  3085   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
       
  3086     sqlite3DbFree(db, pItem->zDatabase);
       
  3087     sqlite3DbFree(db, pItem->zName);
       
  3088     sqlite3DbFree(db, pItem->zAlias);
       
  3089     sqlite3DeleteTable(pItem->pTab);
       
  3090     sqlite3SelectDelete(db, pItem->pSelect);
       
  3091     sqlite3ExprDelete(db, pItem->pOn);
       
  3092     sqlite3IdListDelete(db, pItem->pUsing);
       
  3093   }
       
  3094   sqlite3DbFree(db, pList);
       
  3095 }
       
  3096 
       
  3097 /*
       
  3098 ** This routine is called by the parser to add a new term to the
       
  3099 ** end of a growing FROM clause.  The "p" parameter is the part of
       
  3100 ** the FROM clause that has already been constructed.  "p" is NULL
       
  3101 ** if this is the first term of the FROM clause.  pTable and pDatabase
       
  3102 ** are the name of the table and database named in the FROM clause term.
       
  3103 ** pDatabase is NULL if the database name qualifier is missing - the
       
  3104 ** usual case.  If the term has a alias, then pAlias points to the
       
  3105 ** alias token.  If the term is a subquery, then pSubquery is the
       
  3106 ** SELECT statement that the subquery encodes.  The pTable and
       
  3107 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
       
  3108 ** parameters are the content of the ON and USING clauses.
       
  3109 **
       
  3110 ** Return a new SrcList which encodes is the FROM with the new
       
  3111 ** term added.
       
  3112 */
       
  3113 SrcList *sqlite3SrcListAppendFromTerm(
       
  3114   Parse *pParse,          /* Parsing context */
       
  3115   SrcList *p,             /* The left part of the FROM clause already seen */
       
  3116   Token *pTable,          /* Name of the table to add to the FROM clause */
       
  3117   Token *pDatabase,       /* Name of the database containing pTable */
       
  3118   Token *pAlias,          /* The right-hand side of the AS subexpression */
       
  3119   Select *pSubquery,      /* A subquery used in place of a table name */
       
  3120   Expr *pOn,              /* The ON clause of a join */
       
  3121   IdList *pUsing          /* The USING clause of a join */
       
  3122 ){
       
  3123   struct SrcList_item *pItem;
       
  3124   sqlite3 *db = pParse->db;
       
  3125   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
       
  3126   if( p==0 || p->nSrc==0 ){
       
  3127     sqlite3ExprDelete(db, pOn);
       
  3128     sqlite3IdListDelete(db, pUsing);
       
  3129     sqlite3SelectDelete(db, pSubquery);
       
  3130     return p;
       
  3131   }
       
  3132   pItem = &p->a[p->nSrc-1];
       
  3133   if( pAlias && pAlias->n ){
       
  3134     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
       
  3135   }
       
  3136   pItem->pSelect = pSubquery;
       
  3137   pItem->pOn = pOn;
       
  3138   pItem->pUsing = pUsing;
       
  3139   return p;
       
  3140 }
       
  3141 
       
  3142 /*
       
  3143 ** When building up a FROM clause in the parser, the join operator
       
  3144 ** is initially attached to the left operand.  But the code generator
       
  3145 ** expects the join operator to be on the right operand.  This routine
       
  3146 ** Shifts all join operators from left to right for an entire FROM
       
  3147 ** clause.
       
  3148 **
       
  3149 ** Example: Suppose the join is like this:
       
  3150 **
       
  3151 **           A natural cross join B
       
  3152 **
       
  3153 ** The operator is "natural cross join".  The A and B operands are stored
       
  3154 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
       
  3155 ** operator with A.  This routine shifts that operator over to B.
       
  3156 */
       
  3157 void sqlite3SrcListShiftJoinType(SrcList *p){
       
  3158   if( p && p->a ){
       
  3159     int i;
       
  3160     for(i=p->nSrc-1; i>0; i--){
       
  3161       p->a[i].jointype = p->a[i-1].jointype;
       
  3162     }
       
  3163     p->a[0].jointype = 0;
       
  3164   }
       
  3165 }
       
  3166 
       
  3167 /*
       
  3168 ** Begin a transaction
       
  3169 */
       
  3170 void sqlite3BeginTransaction(Parse *pParse, int type){
       
  3171   sqlite3 *db;
       
  3172   Vdbe *v;
       
  3173   int i;
       
  3174 
       
  3175   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
       
  3176   if( pParse->nErr || db->mallocFailed ) return;
       
  3177   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
       
  3178 
       
  3179   v = sqlite3GetVdbe(pParse);
       
  3180   if( !v ) return;
       
  3181   if( type!=TK_DEFERRED ){
       
  3182     for(i=0; i<db->nDb; i++){
       
  3183       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
       
  3184       sqlite3VdbeUsesBtree(v, i);
       
  3185     }
       
  3186   }
       
  3187   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
       
  3188 }
       
  3189 
       
  3190 /*
       
  3191 ** Commit a transaction
       
  3192 */
       
  3193 void sqlite3CommitTransaction(Parse *pParse){
       
  3194   sqlite3 *db;
       
  3195   Vdbe *v;
       
  3196 
       
  3197   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
       
  3198   if( pParse->nErr || db->mallocFailed ) return;
       
  3199   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
       
  3200 
       
  3201   v = sqlite3GetVdbe(pParse);
       
  3202   if( v ){
       
  3203     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
       
  3204   }
       
  3205 }
       
  3206 
       
  3207 /*
       
  3208 ** Rollback a transaction
       
  3209 */
       
  3210 void sqlite3RollbackTransaction(Parse *pParse){
       
  3211   sqlite3 *db;
       
  3212   Vdbe *v;
       
  3213 
       
  3214   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
       
  3215   if( pParse->nErr || db->mallocFailed ) return;
       
  3216   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
       
  3217 
       
  3218   v = sqlite3GetVdbe(pParse);
       
  3219   if( v ){
       
  3220     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
       
  3221   }
       
  3222 }
       
  3223 
       
  3224 /*
       
  3225 ** Make sure the TEMP database is open and available for use.  Return
       
  3226 ** the number of errors.  Leave any error messages in the pParse structure.
       
  3227 */
       
  3228 int sqlite3OpenTempDatabase(Parse *pParse){
       
  3229   sqlite3 *db = pParse->db;
       
  3230   if( db->aDb[1].pBt==0 && !pParse->explain ){
       
  3231     int rc;
       
  3232     static const int flags = 
       
  3233           SQLITE_OPEN_READWRITE |
       
  3234           SQLITE_OPEN_CREATE |
       
  3235           SQLITE_OPEN_EXCLUSIVE |
       
  3236           SQLITE_OPEN_DELETEONCLOSE |
       
  3237           SQLITE_OPEN_TEMP_DB;
       
  3238 
       
  3239     rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
       
  3240                                  &db->aDb[1].pBt);
       
  3241     if( rc!=SQLITE_OK ){
       
  3242       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
       
  3243         "file for storing temporary tables");
       
  3244       pParse->rc = rc;
       
  3245       return 1;
       
  3246     }
       
  3247     assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit );
       
  3248     assert( db->aDb[1].pSchema );
       
  3249     sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
       
  3250                             db->dfltJournalMode);
       
  3251   }
       
  3252   return 0;
       
  3253 }
       
  3254 
       
  3255 /*
       
  3256 ** Generate VDBE code that will verify the schema cookie and start
       
  3257 ** a read-transaction for all named database files.
       
  3258 **
       
  3259 ** It is important that all schema cookies be verified and all
       
  3260 ** read transactions be started before anything else happens in
       
  3261 ** the VDBE program.  But this routine can be called after much other
       
  3262 ** code has been generated.  So here is what we do:
       
  3263 **
       
  3264 ** The first time this routine is called, we code an OP_Goto that
       
  3265 ** will jump to a subroutine at the end of the program.  Then we
       
  3266 ** record every database that needs its schema verified in the
       
  3267 ** pParse->cookieMask field.  Later, after all other code has been
       
  3268 ** generated, the subroutine that does the cookie verifications and
       
  3269 ** starts the transactions will be coded and the OP_Goto P2 value
       
  3270 ** will be made to point to that subroutine.  The generation of the
       
  3271 ** cookie verification subroutine code happens in sqlite3FinishCoding().
       
  3272 **
       
  3273 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
       
  3274 ** schema on any databases.  This can be used to position the OP_Goto
       
  3275 ** early in the code, before we know if any database tables will be used.
       
  3276 */
       
  3277 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
       
  3278   sqlite3 *db;
       
  3279   Vdbe *v;
       
  3280   int mask;
       
  3281 
       
  3282   v = sqlite3GetVdbe(pParse);
       
  3283   if( v==0 ) return;  /* This only happens if there was a prior error */
       
  3284   db = pParse->db;
       
  3285   if( pParse->cookieGoto==0 ){
       
  3286     pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
       
  3287   }
       
  3288   if( iDb>=0 ){
       
  3289     assert( iDb<db->nDb );
       
  3290     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
       
  3291     assert( iDb<SQLITE_MAX_ATTACHED+2 );
       
  3292     mask = 1<<iDb;
       
  3293     if( (pParse->cookieMask & mask)==0 ){
       
  3294       pParse->cookieMask |= mask;
       
  3295       pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
       
  3296       if( !OMIT_TEMPDB && iDb==1 ){
       
  3297         sqlite3OpenTempDatabase(pParse);
       
  3298       }
       
  3299     }
       
  3300   }
       
  3301 }
       
  3302 
       
  3303 /*
       
  3304 ** Generate VDBE code that prepares for doing an operation that
       
  3305 ** might change the database.
       
  3306 **
       
  3307 ** This routine starts a new transaction if we are not already within
       
  3308 ** a transaction.  If we are already within a transaction, then a checkpoint
       
  3309 ** is set if the setStatement parameter is true.  A checkpoint should
       
  3310 ** be set for operations that might fail (due to a constraint) part of
       
  3311 ** the way through and which will need to undo some writes without having to
       
  3312 ** rollback the whole transaction.  For operations where all constraints
       
  3313 ** can be checked before any changes are made to the database, it is never
       
  3314 ** necessary to undo a write and the checkpoint should not be set.
       
  3315 **
       
  3316 ** Only database iDb and the temp database are made writable by this call.
       
  3317 ** If iDb==0, then the main and temp databases are made writable.   If
       
  3318 ** iDb==1 then only the temp database is made writable.  If iDb>1 then the
       
  3319 ** specified auxiliary database and the temp database are made writable.
       
  3320 */
       
  3321 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
       
  3322   Vdbe *v = sqlite3GetVdbe(pParse);
       
  3323   if( v==0 ) return;
       
  3324   sqlite3CodeVerifySchema(pParse, iDb);
       
  3325   pParse->writeMask |= 1<<iDb;
       
  3326   if( setStatement && pParse->nested==0 ){
       
  3327     sqlite3VdbeAddOp1(v, OP_Statement, iDb);
       
  3328   }
       
  3329   if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
       
  3330     sqlite3BeginWriteOperation(pParse, setStatement, 1);
       
  3331   }
       
  3332 }
       
  3333 
       
  3334 /*
       
  3335 ** Check to see if pIndex uses the collating sequence pColl.  Return
       
  3336 ** true if it does and false if it does not.
       
  3337 */
       
  3338 #ifndef SQLITE_OMIT_REINDEX
       
  3339 static int collationMatch(const char *zColl, Index *pIndex){
       
  3340   int i;
       
  3341   for(i=0; i<pIndex->nColumn; i++){
       
  3342     const char *z = pIndex->azColl[i];
       
  3343     if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
       
  3344       return 1;
       
  3345     }
       
  3346   }
       
  3347   return 0;
       
  3348 }
       
  3349 #endif
       
  3350 
       
  3351 /*
       
  3352 ** Recompute all indices of pTab that use the collating sequence pColl.
       
  3353 ** If pColl==0 then recompute all indices of pTab.
       
  3354 */
       
  3355 #ifndef SQLITE_OMIT_REINDEX
       
  3356 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
       
  3357   Index *pIndex;              /* An index associated with pTab */
       
  3358 
       
  3359   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
       
  3360     if( zColl==0 || collationMatch(zColl, pIndex) ){
       
  3361       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
       
  3362       sqlite3BeginWriteOperation(pParse, 0, iDb);
       
  3363       sqlite3RefillIndex(pParse, pIndex, -1);
       
  3364     }
       
  3365   }
       
  3366 }
       
  3367 #endif
       
  3368 
       
  3369 /*
       
  3370 ** Recompute all indices of all tables in all databases where the
       
  3371 ** indices use the collating sequence pColl.  If pColl==0 then recompute
       
  3372 ** all indices everywhere.
       
  3373 */
       
  3374 #ifndef SQLITE_OMIT_REINDEX
       
  3375 static void reindexDatabases(Parse *pParse, char const *zColl){
       
  3376   Db *pDb;                    /* A single database */
       
  3377   int iDb;                    /* The database index number */
       
  3378   sqlite3 *db = pParse->db;   /* The database connection */
       
  3379   HashElem *k;                /* For looping over tables in pDb */
       
  3380   Table *pTab;                /* A table in the database */
       
  3381 
       
  3382   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
       
  3383     assert( pDb!=0 );
       
  3384     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
       
  3385       pTab = (Table*)sqliteHashData(k);
       
  3386       reindexTable(pParse, pTab, zColl);
       
  3387     }
       
  3388   }
       
  3389 }
       
  3390 #endif
       
  3391 
       
  3392 /*
       
  3393 ** Generate code for the REINDEX command.
       
  3394 **
       
  3395 **        REINDEX                            -- 1
       
  3396 **        REINDEX  <collation>               -- 2
       
  3397 **        REINDEX  ?<database>.?<tablename>  -- 3
       
  3398 **        REINDEX  ?<database>.?<indexname>  -- 4
       
  3399 **
       
  3400 ** Form 1 causes all indices in all attached databases to be rebuilt.
       
  3401 ** Form 2 rebuilds all indices in all databases that use the named
       
  3402 ** collating function.  Forms 3 and 4 rebuild the named index or all
       
  3403 ** indices associated with the named table.
       
  3404 */
       
  3405 #ifndef SQLITE_OMIT_REINDEX
       
  3406 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
       
  3407   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
       
  3408   char *z;                    /* Name of a table or index */
       
  3409   const char *zDb;            /* Name of the database */
       
  3410   Table *pTab;                /* A table in the database */
       
  3411   Index *pIndex;              /* An index associated with pTab */
       
  3412   int iDb;                    /* The database index number */
       
  3413   sqlite3 *db = pParse->db;   /* The database connection */
       
  3414   Token *pObjName;            /* Name of the table or index to be reindexed */
       
  3415 
       
  3416   /* Read the database schema. If an error occurs, leave an error message
       
  3417   ** and code in pParse and return NULL. */
       
  3418   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
       
  3419     return;
       
  3420   }
       
  3421 
       
  3422   if( pName1==0 || pName1->z==0 ){
       
  3423     reindexDatabases(pParse, 0);
       
  3424     return;
       
  3425   }else if( pName2==0 || pName2->z==0 ){
       
  3426     char *zColl;
       
  3427     assert( pName1->z );
       
  3428     zColl = sqlite3NameFromToken(pParse->db, pName1);
       
  3429     if( !zColl ) return;
       
  3430     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
       
  3431     if( pColl ){
       
  3432       if( zColl ){
       
  3433         reindexDatabases(pParse, zColl);
       
  3434         sqlite3DbFree(db, zColl);
       
  3435       }
       
  3436       return;
       
  3437     }
       
  3438     sqlite3DbFree(db, zColl);
       
  3439   }
       
  3440   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
       
  3441   if( iDb<0 ) return;
       
  3442   z = sqlite3NameFromToken(db, pObjName);
       
  3443   if( z==0 ) return;
       
  3444   zDb = db->aDb[iDb].zName;
       
  3445   pTab = sqlite3FindTable(db, z, zDb);
       
  3446   if( pTab ){
       
  3447     reindexTable(pParse, pTab, 0);
       
  3448     sqlite3DbFree(db, z);
       
  3449     return;
       
  3450   }
       
  3451   pIndex = sqlite3FindIndex(db, z, zDb);
       
  3452   sqlite3DbFree(db, z);
       
  3453   if( pIndex ){
       
  3454     sqlite3BeginWriteOperation(pParse, 0, iDb);
       
  3455     sqlite3RefillIndex(pParse, pIndex, -1);
       
  3456     return;
       
  3457   }
       
  3458   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
       
  3459 }
       
  3460 #endif
       
  3461 
       
  3462 /*
       
  3463 ** Return a dynamicly allocated KeyInfo structure that can be used
       
  3464 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
       
  3465 **
       
  3466 ** If successful, a pointer to the new structure is returned. In this case
       
  3467 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
       
  3468 ** pointer. If an error occurs (out of memory or missing collation 
       
  3469 ** sequence), NULL is returned and the state of pParse updated to reflect
       
  3470 ** the error.
       
  3471 */
       
  3472 KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
       
  3473   int i;
       
  3474   int nCol = pIdx->nColumn;
       
  3475   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
       
  3476   sqlite3 *db = pParse->db;
       
  3477   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
       
  3478 
       
  3479   if( pKey ){
       
  3480     pKey->db = pParse->db;
       
  3481     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
       
  3482     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
       
  3483     for(i=0; i<nCol; i++){
       
  3484       char *zColl = pIdx->azColl[i];
       
  3485       assert( zColl );
       
  3486       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
       
  3487       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
       
  3488     }
       
  3489     pKey->nField = nCol;
       
  3490   }
       
  3491 
       
  3492   if( pParse->nErr ){
       
  3493     sqlite3DbFree(db, pKey);
       
  3494     pKey = 0;
       
  3495   }
       
  3496   return pKey;
       
  3497 }