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