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