Back to index

lightning-sunbird  0.9+nobinonly
build.c
Go to the documentation of this file.
00001 /*
00002 ** 2001 September 15
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** This file contains C code routines that are called by the SQLite parser
00013 ** when syntax rules are reduced.  The routines in this file handle the
00014 ** following kinds of SQL syntax:
00015 **
00016 **     CREATE TABLE
00017 **     DROP TABLE
00018 **     CREATE INDEX
00019 **     DROP INDEX
00020 **     creating ID lists
00021 **     BEGIN TRANSACTION
00022 **     COMMIT
00023 **     ROLLBACK
00024 **
00025 ** $Id: build.c,v 1.394 2006/05/11 23:14:59 drh Exp $
00026 */
00027 #include "sqliteInt.h"
00028 #include <ctype.h>
00029 
00030 #include "pager.h"
00031 #include "btree.h"
00032 
00033 /*
00034 ** This routine is called when a new SQL statement is beginning to
00035 ** be parsed.  Initialize the pParse structure as needed.
00036 */
00037 void sqlite3BeginParse(Parse *pParse, int explainFlag){
00038   pParse->explain = explainFlag;
00039   pParse->nVar = 0;
00040 }
00041 
00042 #ifndef SQLITE_OMIT_SHARED_CACHE
00043 /*
00044 ** The TableLock structure is only used by the sqlite3TableLock() and
00045 ** codeTableLocks() functions.
00046 */
00047 struct TableLock {
00048   int iDb;             /* The database containing the table to be locked */
00049   int iTab;            /* The root page of the table to be locked */
00050   u8 isWriteLock;      /* True for write lock.  False for a read lock */
00051   const char *zName;   /* Name of the table */
00052 };
00053 
00054 /*
00055 ** Record the fact that we want to lock a table at run-time.  
00056 **
00057 ** The table to be locked has root page iTab and is found in database iDb.
00058 ** A read or a write lock can be taken depending on isWritelock.
00059 **
00060 ** This routine just records the fact that the lock is desired.  The
00061 ** code to make the lock occur is generated by a later call to
00062 ** codeTableLocks() which occurs during sqlite3FinishCoding().
00063 */
00064 void sqlite3TableLock(
00065   Parse *pParse,     /* Parsing context */
00066   int iDb,           /* Index of the database containing the table to lock */
00067   int iTab,          /* Root page number of the table to be locked */
00068   u8 isWriteLock,    /* True for a write lock */
00069   const char *zName  /* Name of the table to be locked */
00070 ){
00071   int i;
00072   int nBytes;
00073   TableLock *p;
00074 
00075   if( 0==sqlite3ThreadDataReadOnly()->useSharedData || iDb<0 ){
00076     return;
00077   }
00078 
00079   for(i=0; i<pParse->nTableLock; i++){
00080     p = &pParse->aTableLock[i];
00081     if( p->iDb==iDb && p->iTab==iTab ){
00082       p->isWriteLock = (p->isWriteLock || isWriteLock);
00083       return;
00084     }
00085   }
00086 
00087   nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
00088   sqliteReallocOrFree((void **)&pParse->aTableLock, nBytes);
00089   if( pParse->aTableLock ){
00090     p = &pParse->aTableLock[pParse->nTableLock++];
00091     p->iDb = iDb;
00092     p->iTab = iTab;
00093     p->isWriteLock = isWriteLock;
00094     p->zName = zName;
00095   }
00096 }
00097 
00098 /*
00099 ** Code an OP_TableLock instruction for each table locked by the
00100 ** statement (configured by calls to sqlite3TableLock()).
00101 */
00102 static void codeTableLocks(Parse *pParse){
00103   int i;
00104   Vdbe *pVdbe; 
00105   assert( sqlite3ThreadDataReadOnly()->useSharedData || pParse->nTableLock==0 );
00106 
00107   if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
00108     return;
00109   }
00110 
00111   for(i=0; i<pParse->nTableLock; i++){
00112     TableLock *p = &pParse->aTableLock[i];
00113     int p1 = p->iDb;
00114     if( p->isWriteLock ){
00115       p1 = -1*(p1+1);
00116     }
00117     sqlite3VdbeOp3(pVdbe, OP_TableLock, p1, p->iTab, p->zName, P3_STATIC);
00118   }
00119 }
00120 #else
00121   #define codeTableLocks(x)
00122 #endif
00123 
00124 /*
00125 ** This routine is called after a single SQL statement has been
00126 ** parsed and a VDBE program to execute that statement has been
00127 ** prepared.  This routine puts the finishing touches on the
00128 ** VDBE program and resets the pParse structure for the next
00129 ** parse.
00130 **
00131 ** Note that if an error occurred, it might be the case that
00132 ** no VDBE code was generated.
00133 */
00134 void sqlite3FinishCoding(Parse *pParse){
00135   sqlite3 *db;
00136   Vdbe *v;
00137 
00138   if( sqlite3MallocFailed() ) return;
00139   if( pParse->nested ) return;
00140   if( !pParse->pVdbe ){
00141     if( pParse->rc==SQLITE_OK && pParse->nErr ){
00142       pParse->rc = SQLITE_ERROR;
00143       return;
00144     }
00145   }
00146 
00147   /* Begin by generating some termination code at the end of the
00148   ** vdbe program
00149   */
00150   db = pParse->db;
00151   v = sqlite3GetVdbe(pParse);
00152   if( v ){
00153     sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
00154 
00155     /* The cookie mask contains one bit for each database file open.
00156     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
00157     ** set for each database that is used.  Generate code to start a
00158     ** transaction on each used database and to verify the schema cookie
00159     ** on each used database.
00160     */
00161     if( pParse->cookieGoto>0 ){
00162       u32 mask;
00163       int iDb;
00164       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
00165       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
00166         if( (mask & pParse->cookieMask)==0 ) continue;
00167         sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
00168         sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
00169       }
00170 
00171       /* Once all the cookies have been verified and transactions opened, 
00172       ** obtain the required table-locks. This is a no-op unless the 
00173       ** shared-cache feature is enabled.
00174       */
00175       codeTableLocks(pParse);
00176       sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto);
00177     }
00178 
00179 #ifndef SQLITE_OMIT_TRACE
00180     /* Add a No-op that contains the complete text of the compiled SQL
00181     ** statement as its P3 argument.  This does not change the functionality
00182     ** of the program. 
00183     **
00184     ** This is used to implement sqlite3_trace().
00185     */
00186     sqlite3VdbeOp3(v, OP_Noop, 0, 0, pParse->zSql, pParse->zTail-pParse->zSql);
00187 #endif /* SQLITE_OMIT_TRACE */
00188   }
00189 
00190 
00191   /* Get the VDBE program ready for execution
00192   */
00193   if( v && pParse->nErr==0 && !sqlite3MallocFailed() ){
00194     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
00195     sqlite3VdbeTrace(v, trace);
00196     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
00197                          pParse->nTab+3, pParse->explain);
00198     pParse->rc = SQLITE_DONE;
00199     pParse->colNamesSet = 0;
00200   }else if( pParse->rc==SQLITE_OK ){
00201     pParse->rc = SQLITE_ERROR;
00202   }
00203   pParse->nTab = 0;
00204   pParse->nMem = 0;
00205   pParse->nSet = 0;
00206   pParse->nVar = 0;
00207   pParse->cookieMask = 0;
00208   pParse->cookieGoto = 0;
00209 }
00210 
00211 /*
00212 ** Run the parser and code generator recursively in order to generate
00213 ** code for the SQL statement given onto the end of the pParse context
00214 ** currently under construction.  When the parser is run recursively
00215 ** this way, the final OP_Halt is not appended and other initialization
00216 ** and finalization steps are omitted because those are handling by the
00217 ** outermost parser.
00218 **
00219 ** Not everything is nestable.  This facility is designed to permit
00220 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
00221 ** care if you decide to try to use this routine for some other purposes.
00222 */
00223 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
00224   va_list ap;
00225   char *zSql;
00226 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
00227   char saveBuf[SAVE_SZ];
00228 
00229   if( pParse->nErr ) return;
00230   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
00231   va_start(ap, zFormat);
00232   zSql = sqlite3VMPrintf(zFormat, ap);
00233   va_end(ap);
00234   if( zSql==0 ){
00235     return;   /* A malloc must have failed */
00236   }
00237   pParse->nested++;
00238   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
00239   memset(&pParse->nVar, 0, SAVE_SZ);
00240   sqlite3RunParser(pParse, zSql, 0);
00241   sqliteFree(zSql);
00242   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
00243   pParse->nested--;
00244 }
00245 
00246 /*
00247 ** Locate the in-memory structure that describes a particular database
00248 ** table given the name of that table and (optionally) the name of the
00249 ** database containing the table.  Return NULL if not found.
00250 **
00251 ** If zDatabase is 0, all databases are searched for the table and the
00252 ** first matching table is returned.  (No checking for duplicate table
00253 ** names is done.)  The search order is TEMP first, then MAIN, then any
00254 ** auxiliary databases added using the ATTACH command.
00255 **
00256 ** See also sqlite3LocateTable().
00257 */
00258 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
00259   Table *p = 0;
00260   int i;
00261   assert( zName!=0 );
00262   for(i=OMIT_TEMPDB; i<db->nDb; i++){
00263     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
00264     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
00265     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, strlen(zName)+1);
00266     if( p ) break;
00267   }
00268   return p;
00269 }
00270 
00271 /*
00272 ** Locate the in-memory structure that describes a particular database
00273 ** table given the name of that table and (optionally) the name of the
00274 ** database containing the table.  Return NULL if not found.  Also leave an
00275 ** error message in pParse->zErrMsg.
00276 **
00277 ** The difference between this routine and sqlite3FindTable() is that this
00278 ** routine leaves an error message in pParse->zErrMsg where
00279 ** sqlite3FindTable() does not.
00280 */
00281 Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){
00282   Table *p;
00283 
00284   /* Read the database schema. If an error occurs, leave an error message
00285   ** and code in pParse and return NULL. */
00286   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
00287     return 0;
00288   }
00289 
00290   p = sqlite3FindTable(pParse->db, zName, zDbase);
00291   if( p==0 ){
00292     if( zDbase ){
00293       sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
00294     }else{
00295       sqlite3ErrorMsg(pParse, "no such table: %s", zName);
00296     }
00297     pParse->checkSchema = 1;
00298   }
00299   return p;
00300 }
00301 
00302 /*
00303 ** Locate the in-memory structure that describes 
00304 ** a particular index given the name of that index
00305 ** and the name of the database that contains the index.
00306 ** Return NULL if not found.
00307 **
00308 ** If zDatabase is 0, all databases are searched for the
00309 ** table and the first matching index is returned.  (No checking
00310 ** for duplicate index names is done.)  The search order is
00311 ** TEMP first, then MAIN, then any auxiliary databases added
00312 ** using the ATTACH command.
00313 */
00314 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
00315   Index *p = 0;
00316   int i;
00317   for(i=OMIT_TEMPDB; i<db->nDb; i++){
00318     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
00319     Schema *pSchema = db->aDb[j].pSchema;
00320     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
00321     assert( pSchema || (j==1 && !db->aDb[1].pBt) );
00322     if( pSchema ){
00323       p = sqlite3HashFind(&pSchema->idxHash, zName, strlen(zName)+1);
00324     }
00325     if( p ) break;
00326   }
00327   return p;
00328 }
00329 
00330 /*
00331 ** Reclaim the memory used by an index
00332 */
00333 static void freeIndex(Index *p){
00334   sqliteFree(p->zColAff);
00335   sqliteFree(p);
00336 }
00337 
00338 /*
00339 ** Remove the given index from the index hash table, and free
00340 ** its memory structures.
00341 **
00342 ** The index is removed from the database hash tables but
00343 ** it is not unlinked from the Table that it indexes.
00344 ** Unlinking from the Table must be done by the calling function.
00345 */
00346 static void sqliteDeleteIndex(Index *p){
00347   Index *pOld;
00348   const char *zName = p->zName;
00349 
00350   pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen( zName)+1, 0);
00351   assert( pOld==0 || pOld==p );
00352   freeIndex(p);
00353 }
00354 
00355 /*
00356 ** For the index called zIdxName which is found in the database iDb,
00357 ** unlike that index from its Table then remove the index from
00358 ** the index hash table and free all memory structures associated
00359 ** with the index.
00360 */
00361 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
00362   Index *pIndex;
00363   int len;
00364   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
00365 
00366   len = strlen(zIdxName);
00367   pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
00368   if( pIndex ){
00369     if( pIndex->pTable->pIndex==pIndex ){
00370       pIndex->pTable->pIndex = pIndex->pNext;
00371     }else{
00372       Index *p;
00373       for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
00374       if( p && p->pNext==pIndex ){
00375         p->pNext = pIndex->pNext;
00376       }
00377     }
00378     freeIndex(pIndex);
00379   }
00380   db->flags |= SQLITE_InternChanges;
00381 }
00382 
00383 /*
00384 ** Erase all schema information from the in-memory hash tables of
00385 ** a single database.  This routine is called to reclaim memory
00386 ** before the database closes.  It is also called during a rollback
00387 ** if there were schema changes during the transaction or if a
00388 ** schema-cookie mismatch occurs.
00389 **
00390 ** If iDb<=0 then reset the internal schema tables for all database
00391 ** files.  If iDb>=2 then reset the internal schema for only the
00392 ** single file indicated.
00393 */
00394 void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
00395   int i, j;
00396 
00397   assert( iDb>=0 && iDb<db->nDb );
00398   for(i=iDb; i<db->nDb; i++){
00399     Db *pDb = &db->aDb[i];
00400     if( pDb->pSchema ){
00401       sqlite3SchemaFree(pDb->pSchema);
00402     }
00403     if( iDb>0 ) return;
00404   }
00405   assert( iDb==0 );
00406   db->flags &= ~SQLITE_InternChanges;
00407 
00408   /* If one or more of the auxiliary database files has been closed,
00409   ** then remove them from the auxiliary database list.  We take the
00410   ** opportunity to do this here since we have just deleted all of the
00411   ** schema hash tables and therefore do not have to make any changes
00412   ** to any of those tables.
00413   */
00414   for(i=0; i<db->nDb; i++){
00415     struct Db *pDb = &db->aDb[i];
00416     if( pDb->pBt==0 ){
00417       if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
00418       pDb->pAux = 0;
00419     }
00420   }
00421   for(i=j=2; i<db->nDb; i++){
00422     struct Db *pDb = &db->aDb[i];
00423     if( pDb->pBt==0 ){
00424       sqliteFree(pDb->zName);
00425       pDb->zName = 0;
00426       continue;
00427     }
00428     if( j<i ){
00429       db->aDb[j] = db->aDb[i];
00430     }
00431     j++;
00432   }
00433   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
00434   db->nDb = j;
00435   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
00436     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
00437     sqliteFree(db->aDb);
00438     db->aDb = db->aDbStatic;
00439   }
00440 }
00441 
00442 /*
00443 ** This routine is called whenever a rollback occurs.  If there were
00444 ** schema changes during the transaction, then we have to reset the
00445 ** internal hash tables and reload them from disk.
00446 */
00447 void sqlite3RollbackInternalChanges(sqlite3 *db){
00448   if( db->flags & SQLITE_InternChanges ){
00449     sqlite3ResetInternalSchema(db, 0);
00450   }
00451 }
00452 
00453 /*
00454 ** This routine is called when a commit occurs.
00455 */
00456 void sqlite3CommitInternalChanges(sqlite3 *db){
00457   db->flags &= ~SQLITE_InternChanges;
00458 }
00459 
00460 /*
00461 ** Clear the column names from a table or view.
00462 */
00463 static void sqliteResetColumnNames(Table *pTable){
00464   int i;
00465   Column *pCol;
00466   assert( pTable!=0 );
00467   if( (pCol = pTable->aCol)!=0 ){
00468     for(i=0; i<pTable->nCol; i++, pCol++){
00469       sqliteFree(pCol->zName);
00470       sqlite3ExprDelete(pCol->pDflt);
00471       sqliteFree(pCol->zType);
00472       sqliteFree(pCol->zColl);
00473     }
00474     sqliteFree(pTable->aCol);
00475   }
00476   pTable->aCol = 0;
00477   pTable->nCol = 0;
00478 }
00479 
00480 /*
00481 ** Remove the memory data structures associated with the given
00482 ** Table.  No changes are made to disk by this routine.
00483 **
00484 ** This routine just deletes the data structure.  It does not unlink
00485 ** the table data structure from the hash table.  Nor does it remove
00486 ** foreign keys from the sqlite.aFKey hash table.  But it does destroy
00487 ** memory structures of the indices and foreign keys associated with 
00488 ** the table.
00489 **
00490 ** Indices associated with the table are unlinked from the "db"
00491 ** data structure if db!=NULL.  If db==NULL, indices attached to
00492 ** the table are deleted, but it is assumed they have already been
00493 ** unlinked.
00494 */
00495 void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
00496   Index *pIndex, *pNext;
00497   FKey *pFKey, *pNextFKey;
00498 
00499   db = 0;
00500 
00501   if( pTable==0 ) return;
00502 
00503   /* Do not delete the table until the reference count reaches zero. */
00504   pTable->nRef--;
00505   if( pTable->nRef>0 ){
00506     return;
00507   }
00508   assert( pTable->nRef==0 );
00509 
00510   /* Delete all indices associated with this table
00511   */
00512   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
00513     pNext = pIndex->pNext;
00514     assert( pIndex->pSchema==pTable->pSchema );
00515     sqliteDeleteIndex(pIndex);
00516   }
00517 
00518 #ifndef SQLITE_OMIT_FOREIGN_KEY
00519   /* Delete all foreign keys associated with this table.  The keys
00520   ** should have already been unlinked from the db->aFKey hash table 
00521   */
00522   for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
00523     pNextFKey = pFKey->pNextFrom;
00524     assert( sqlite3HashFind(&pTable->pSchema->aFKey,
00525                            pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
00526     sqliteFree(pFKey);
00527   }
00528 #endif
00529 
00530   /* Delete the Table structure itself.
00531   */
00532   sqliteResetColumnNames(pTable);
00533   sqliteFree(pTable->zName);
00534   sqliteFree(pTable->zColAff);
00535   sqlite3SelectDelete(pTable->pSelect);
00536 #ifndef SQLITE_OMIT_CHECK
00537   sqlite3ExprDelete(pTable->pCheck);
00538 #endif
00539   sqliteFree(pTable);
00540 }
00541 
00542 /*
00543 ** Unlink the given table from the hash tables and the delete the
00544 ** table structure with all its indices and foreign keys.
00545 */
00546 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
00547   Table *p;
00548   FKey *pF1, *pF2;
00549   Db *pDb;
00550 
00551   assert( db!=0 );
00552   assert( iDb>=0 && iDb<db->nDb );
00553   assert( zTabName && zTabName[0] );
00554   pDb = &db->aDb[iDb];
00555   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
00556   if( p ){
00557 #ifndef SQLITE_OMIT_FOREIGN_KEY
00558     for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
00559       int nTo = strlen(pF1->zTo) + 1;
00560       pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
00561       if( pF2==pF1 ){
00562         sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
00563       }else{
00564         while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
00565         if( pF2 ){
00566           pF2->pNextTo = pF1->pNextTo;
00567         }
00568       }
00569     }
00570 #endif
00571     sqlite3DeleteTable(db, p);
00572   }
00573   db->flags |= SQLITE_InternChanges;
00574 }
00575 
00576 /*
00577 ** Given a token, return a string that consists of the text of that
00578 ** token with any quotations removed.  Space to hold the returned string
00579 ** is obtained from sqliteMalloc() and must be freed by the calling
00580 ** function.
00581 **
00582 ** Tokens are often just pointers into the original SQL text and so
00583 ** are not \000 terminated and are not persistent.  The returned string
00584 ** is \000 terminated and is persistent.
00585 */
00586 char *sqlite3NameFromToken(Token *pName){
00587   char *zName;
00588   if( pName ){
00589     zName = sqliteStrNDup((char*)pName->z, pName->n);
00590     sqlite3Dequote(zName);
00591   }else{
00592     zName = 0;
00593   }
00594   return zName;
00595 }
00596 
00597 /*
00598 ** Open the sqlite_master table stored in database number iDb for
00599 ** writing. The table is opened using cursor 0.
00600 */
00601 void sqlite3OpenMasterTable(Parse *p, int iDb){
00602   Vdbe *v = sqlite3GetVdbe(p);
00603   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
00604   sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
00605   sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT);
00606   sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */
00607 }
00608 
00609 /*
00610 ** The token *pName contains the name of a database (either "main" or
00611 ** "temp" or the name of an attached db). This routine returns the
00612 ** index of the named database in db->aDb[], or -1 if the named db 
00613 ** does not exist.
00614 */
00615 int sqlite3FindDb(sqlite3 *db, Token *pName){
00616   int i = -1;    /* Database number */
00617   int n;         /* Number of characters in the name */
00618   Db *pDb;       /* A database whose name space is being searched */
00619   char *zName;   /* Name we are searching for */
00620 
00621   zName = sqlite3NameFromToken(pName);
00622   if( zName ){
00623     n = strlen(zName);
00624     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
00625       if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) && 
00626           0==sqlite3StrICmp(pDb->zName, zName) ){
00627         break;
00628       }
00629     }
00630     sqliteFree(zName);
00631   }
00632   return i;
00633 }
00634 
00635 /* The table or view or trigger name is passed to this routine via tokens
00636 ** pName1 and pName2. If the table name was fully qualified, for example:
00637 **
00638 ** CREATE TABLE xxx.yyy (...);
00639 ** 
00640 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
00641 ** the table name is not fully qualified, i.e.:
00642 **
00643 ** CREATE TABLE yyy(...);
00644 **
00645 ** Then pName1 is set to "yyy" and pName2 is "".
00646 **
00647 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
00648 ** pName2) that stores the unqualified table name.  The index of the
00649 ** database "xxx" is returned.
00650 */
00651 int sqlite3TwoPartName(
00652   Parse *pParse,      /* Parsing and code generating context */
00653   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
00654   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
00655   Token **pUnqual     /* Write the unqualified object name here */
00656 ){
00657   int iDb;                    /* Database holding the object */
00658   sqlite3 *db = pParse->db;
00659 
00660   if( pName2 && pName2->n>0 ){
00661     assert( !db->init.busy );
00662     *pUnqual = pName2;
00663     iDb = sqlite3FindDb(db, pName1);
00664     if( iDb<0 ){
00665       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
00666       pParse->nErr++;
00667       return -1;
00668     }
00669   }else{
00670     assert( db->init.iDb==0 || db->init.busy );
00671     iDb = db->init.iDb;
00672     *pUnqual = pName1;
00673   }
00674   return iDb;
00675 }
00676 
00677 /*
00678 ** This routine is used to check if the UTF-8 string zName is a legal
00679 ** unqualified name for a new schema object (table, index, view or
00680 ** trigger). All names are legal except those that begin with the string
00681 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
00682 ** is reserved for internal use.
00683 */
00684 int sqlite3CheckObjectName(Parse *pParse, const char *zName){
00685   if( !pParse->db->init.busy && pParse->nested==0 
00686           && (pParse->db->flags & SQLITE_WriteSchema)==0
00687           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
00688     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
00689     return SQLITE_ERROR;
00690   }
00691   return SQLITE_OK;
00692 }
00693 
00694 /*
00695 ** Begin constructing a new table representation in memory.  This is
00696 ** the first of several action routines that get called in response
00697 ** to a CREATE TABLE statement.  In particular, this routine is called
00698 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
00699 ** flag is true if the table should be stored in the auxiliary database
00700 ** file instead of in the main database file.  This is normally the case
00701 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
00702 ** CREATE and TABLE.
00703 **
00704 ** The new table record is initialized and put in pParse->pNewTable.
00705 ** As more of the CREATE TABLE statement is parsed, additional action
00706 ** routines will be called to add more information to this record.
00707 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
00708 ** is called to complete the construction of the new table record.
00709 */
00710 void sqlite3StartTable(
00711   Parse *pParse,   /* Parser context */
00712   Token *pName1,   /* First part of the name of the table or view */
00713   Token *pName2,   /* Second part of the name of the table or view */
00714   int isTemp,      /* True if this is a TEMP table */
00715   int isView,      /* True if this is a VIEW */
00716   int noErr        /* Do nothing if table already exists */
00717 ){
00718   Table *pTable;
00719   char *zName = 0; /* The name of the new table */
00720   sqlite3 *db = pParse->db;
00721   Vdbe *v;
00722   int iDb;         /* Database number to create the table in */
00723   Token *pName;    /* Unqualified name of the table to create */
00724 
00725   /* The table or view name to create is passed to this routine via tokens
00726   ** pName1 and pName2. If the table name was fully qualified, for example:
00727   **
00728   ** CREATE TABLE xxx.yyy (...);
00729   ** 
00730   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
00731   ** the table name is not fully qualified, i.e.:
00732   **
00733   ** CREATE TABLE yyy(...);
00734   **
00735   ** Then pName1 is set to "yyy" and pName2 is "".
00736   **
00737   ** The call below sets the pName pointer to point at the token (pName1 or
00738   ** pName2) that stores the unqualified table name. The variable iDb is
00739   ** set to the index of the database that the table or view is to be
00740   ** created in.
00741   */
00742   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
00743   if( iDb<0 ) return;
00744   if( !OMIT_TEMPDB && isTemp && iDb>1 ){
00745     /* If creating a temp table, the name may not be qualified */
00746     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
00747     return;
00748   }
00749   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
00750 
00751   pParse->sNameToken = *pName;
00752   zName = sqlite3NameFromToken(pName);
00753   if( zName==0 ) return;
00754   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
00755     goto begin_table_error;
00756   }
00757   if( db->init.iDb==1 ) isTemp = 1;
00758 #ifndef SQLITE_OMIT_AUTHORIZATION
00759   assert( (isTemp & 1)==isTemp );
00760   {
00761     int code;
00762     char *zDb = db->aDb[iDb].zName;
00763     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
00764       goto begin_table_error;
00765     }
00766     if( isView ){
00767       if( !OMIT_TEMPDB && isTemp ){
00768         code = SQLITE_CREATE_TEMP_VIEW;
00769       }else{
00770         code = SQLITE_CREATE_VIEW;
00771       }
00772     }else{
00773       if( !OMIT_TEMPDB && isTemp ){
00774         code = SQLITE_CREATE_TEMP_TABLE;
00775       }else{
00776         code = SQLITE_CREATE_TABLE;
00777       }
00778     }
00779     if( sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
00780       goto begin_table_error;
00781     }
00782   }
00783 #endif
00784 
00785   /* Make sure the new table name does not collide with an existing
00786   ** index or table name in the same database.  Issue an error message if
00787   ** it does.
00788   */
00789   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
00790     goto begin_table_error;
00791   }
00792   pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
00793   if( pTable ){
00794     if( !noErr ){
00795       sqlite3ErrorMsg(pParse, "table %T already exists", pName);
00796     }
00797     goto begin_table_error;
00798   }
00799   if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
00800     sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
00801     goto begin_table_error;
00802   }
00803   pTable = sqliteMalloc( sizeof(Table) );
00804   if( pTable==0 ){
00805     pParse->rc = SQLITE_NOMEM;
00806     pParse->nErr++;
00807     goto begin_table_error;
00808   }
00809   pTable->zName = zName;
00810   pTable->nCol = 0;
00811   pTable->aCol = 0;
00812   pTable->iPKey = -1;
00813   pTable->pIndex = 0;
00814   pTable->pSchema = db->aDb[iDb].pSchema;
00815   pTable->nRef = 1;
00816   if( pParse->pNewTable ) sqlite3DeleteTable(db, pParse->pNewTable);
00817   pParse->pNewTable = pTable;
00818 
00819   /* If this is the magic sqlite_sequence table used by autoincrement,
00820   ** then record a pointer to this table in the main database structure
00821   ** so that INSERT can find the table easily.
00822   */
00823 #ifndef SQLITE_OMIT_AUTOINCREMENT
00824   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
00825     pTable->pSchema->pSeqTab = pTable;
00826   }
00827 #endif
00828 
00829   /* Begin generating the code that will insert the table record into
00830   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
00831   ** and allocate the record number for the table entry now.  Before any
00832   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
00833   ** indices to be created and the table record must come before the 
00834   ** indices.  Hence, the record number for the table must be allocated
00835   ** now.
00836   */
00837   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
00838     int lbl;
00839     int fileFormat;
00840     sqlite3BeginWriteOperation(pParse, 0, iDb);
00841 
00842     /* If the file format and encoding in the database have not been set, 
00843     ** set them now.
00844     */
00845     sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1);   /* file_format */
00846     lbl = sqlite3VdbeMakeLabel(v);
00847     sqlite3VdbeAddOp(v, OP_If, 0, lbl);
00848     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
00849                   1 : SQLITE_DEFAULT_FILE_FORMAT;
00850     sqlite3VdbeAddOp(v, OP_Integer, fileFormat, 0);
00851     sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
00852     sqlite3VdbeAddOp(v, OP_Integer, ENC(db), 0);
00853     sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4);
00854     sqlite3VdbeResolveLabel(v, lbl);
00855 
00856     /* This just creates a place-holder record in the sqlite_master table.
00857     ** The record created does not contain anything yet.  It will be replaced
00858     ** by the real entry in code generated at sqlite3EndTable().
00859     **
00860     ** The rowid for the new entry is left on the top of the stack.
00861     ** The rowid value is needed by the code that sqlite3EndTable will
00862     ** generate.
00863     */
00864 #ifndef SQLITE_OMIT_VIEW
00865     if( isView ){
00866       sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
00867     }else
00868 #endif
00869     {
00870       sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0);
00871     }
00872     sqlite3OpenMasterTable(pParse, iDb);
00873     sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0);
00874     sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
00875     sqlite3VdbeAddOp(v, OP_Null, 0, 0);
00876     sqlite3VdbeAddOp(v, OP_Insert, 0, 0);
00877     sqlite3VdbeAddOp(v, OP_Close, 0, 0);
00878     sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
00879   }
00880 
00881   /* Normal (non-error) return. */
00882   return;
00883 
00884   /* If an error occurs, we jump here */
00885 begin_table_error:
00886   sqliteFree(zName);
00887   return;
00888 }
00889 
00890 /*
00891 ** This macro is used to compare two strings in a case-insensitive manner.
00892 ** It is slightly faster than calling sqlite3StrICmp() directly, but
00893 ** produces larger code.
00894 **
00895 ** WARNING: This macro is not compatible with the strcmp() family. It
00896 ** returns true if the two strings are equal, otherwise false.
00897 */
00898 #define STRICMP(x, y) (\
00899 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
00900 sqlite3UpperToLower[*(unsigned char *)(y)]     \
00901 && sqlite3StrICmp((x)+1,(y)+1)==0 )
00902 
00903 /*
00904 ** Add a new column to the table currently being constructed.
00905 **
00906 ** The parser calls this routine once for each column declaration
00907 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
00908 ** first to get things going.  Then this routine is called for each
00909 ** column.
00910 */
00911 void sqlite3AddColumn(Parse *pParse, Token *pName){
00912   Table *p;
00913   int i;
00914   char *z;
00915   Column *pCol;
00916   if( (p = pParse->pNewTable)==0 ) return;
00917   z = sqlite3NameFromToken(pName);
00918   if( z==0 ) return;
00919   for(i=0; i<p->nCol; i++){
00920     if( STRICMP(z, p->aCol[i].zName) ){
00921       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
00922       sqliteFree(z);
00923       return;
00924     }
00925   }
00926   if( (p->nCol & 0x7)==0 ){
00927     Column *aNew;
00928     aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
00929     if( aNew==0 ){
00930       sqliteFree(z);
00931       return;
00932     }
00933     p->aCol = aNew;
00934   }
00935   pCol = &p->aCol[p->nCol];
00936   memset(pCol, 0, sizeof(p->aCol[0]));
00937   pCol->zName = z;
00938  
00939   /* If there is no type specified, columns have the default affinity
00940   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
00941   ** be called next to set pCol->affinity correctly.
00942   */
00943   pCol->affinity = SQLITE_AFF_NONE;
00944   p->nCol++;
00945 }
00946 
00947 /*
00948 ** This routine is called by the parser while in the middle of
00949 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
00950 ** been seen on a column.  This routine sets the notNull flag on
00951 ** the column currently under construction.
00952 */
00953 void sqlite3AddNotNull(Parse *pParse, int onError){
00954   Table *p;
00955   int i;
00956   if( (p = pParse->pNewTable)==0 ) return;
00957   i = p->nCol-1;
00958   if( i>=0 ) p->aCol[i].notNull = onError;
00959 }
00960 
00961 /*
00962 ** Scan the column type name zType (length nType) and return the
00963 ** associated affinity type.
00964 **
00965 ** This routine does a case-independent search of zType for the 
00966 ** substrings in the following table. If one of the substrings is
00967 ** found, the corresponding affinity is returned. If zType contains
00968 ** more than one of the substrings, entries toward the top of 
00969 ** the table take priority. For example, if zType is 'BLOBINT', 
00970 ** SQLITE_AFF_INTEGER is returned.
00971 **
00972 ** Substring     | Affinity
00973 ** --------------------------------
00974 ** 'INT'         | SQLITE_AFF_INTEGER
00975 ** 'CHAR'        | SQLITE_AFF_TEXT
00976 ** 'CLOB'        | SQLITE_AFF_TEXT
00977 ** 'TEXT'        | SQLITE_AFF_TEXT
00978 ** 'BLOB'        | SQLITE_AFF_NONE
00979 ** 'REAL'        | SQLITE_AFF_REAL
00980 ** 'FLOA'        | SQLITE_AFF_REAL
00981 ** 'DOUB'        | SQLITE_AFF_REAL
00982 **
00983 ** If none of the substrings in the above table are found,
00984 ** SQLITE_AFF_NUMERIC is returned.
00985 */
00986 char sqlite3AffinityType(const Token *pType){
00987   u32 h = 0;
00988   char aff = SQLITE_AFF_NUMERIC;
00989   const unsigned char *zIn = pType->z;
00990   const unsigned char *zEnd = &pType->z[pType->n];
00991 
00992   while( zIn!=zEnd ){
00993     h = (h<<8) + sqlite3UpperToLower[*zIn];
00994     zIn++;
00995     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
00996       aff = SQLITE_AFF_TEXT; 
00997     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
00998       aff = SQLITE_AFF_TEXT;
00999     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
01000       aff = SQLITE_AFF_TEXT;
01001     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
01002         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
01003       aff = SQLITE_AFF_NONE;
01004 #ifndef SQLITE_OMIT_FLOATING_POINT
01005     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
01006         && aff==SQLITE_AFF_NUMERIC ){
01007       aff = SQLITE_AFF_REAL;
01008     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
01009         && aff==SQLITE_AFF_NUMERIC ){
01010       aff = SQLITE_AFF_REAL;
01011     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
01012         && aff==SQLITE_AFF_NUMERIC ){
01013       aff = SQLITE_AFF_REAL;
01014 #endif
01015     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
01016       aff = SQLITE_AFF_INTEGER;
01017       break;
01018     }
01019   }
01020 
01021   return aff;
01022 }
01023 
01024 /*
01025 ** This routine is called by the parser while in the middle of
01026 ** parsing a CREATE TABLE statement.  The pFirst token is the first
01027 ** token in the sequence of tokens that describe the type of the
01028 ** column currently under construction.   pLast is the last token
01029 ** in the sequence.  Use this information to construct a string
01030 ** that contains the typename of the column and store that string
01031 ** in zType.
01032 */ 
01033 void sqlite3AddColumnType(Parse *pParse, Token *pType){
01034   Table *p;
01035   int i;
01036   Column *pCol;
01037 
01038   if( (p = pParse->pNewTable)==0 ) return;
01039   i = p->nCol-1;
01040   if( i<0 ) return;
01041   pCol = &p->aCol[i];
01042   sqliteFree(pCol->zType);
01043   pCol->zType = sqlite3NameFromToken(pType);
01044   pCol->affinity = sqlite3AffinityType(pType);
01045 }
01046 
01047 /*
01048 ** The expression is the default value for the most recently added column
01049 ** of the table currently under construction.
01050 **
01051 ** Default value expressions must be constant.  Raise an exception if this
01052 ** is not the case.
01053 **
01054 ** This routine is called by the parser while in the middle of
01055 ** parsing a CREATE TABLE statement.
01056 */
01057 void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
01058   Table *p;
01059   Column *pCol;
01060   if( (p = pParse->pNewTable)!=0 ){
01061     pCol = &(p->aCol[p->nCol-1]);
01062     if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
01063       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
01064           pCol->zName);
01065     }else{
01066       sqlite3ExprDelete(pCol->pDflt);
01067       pCol->pDflt = sqlite3ExprDup(pExpr);
01068     }
01069   }
01070   sqlite3ExprDelete(pExpr);
01071 }
01072 
01073 /*
01074 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
01075 ** of columns that form the primary key.  If pList is NULL, then the
01076 ** most recently added column of the table is the primary key.
01077 **
01078 ** A table can have at most one primary key.  If the table already has
01079 ** a primary key (and this is the second primary key) then create an
01080 ** error.
01081 **
01082 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
01083 ** then we will try to use that column as the rowid.  Set the Table.iPKey
01084 ** field of the table under construction to be the index of the
01085 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
01086 ** no INTEGER PRIMARY KEY.
01087 **
01088 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
01089 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
01090 */
01091 void sqlite3AddPrimaryKey(
01092   Parse *pParse,    /* Parsing context */
01093   ExprList *pList,  /* List of field names to be indexed */
01094   int onError,      /* What to do with a uniqueness conflict */
01095   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
01096   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
01097 ){
01098   Table *pTab = pParse->pNewTable;
01099   char *zType = 0;
01100   int iCol = -1, i;
01101   if( pTab==0 ) goto primary_key_exit;
01102   if( pTab->hasPrimKey ){
01103     sqlite3ErrorMsg(pParse, 
01104       "table \"%s\" has more than one primary key", pTab->zName);
01105     goto primary_key_exit;
01106   }
01107   pTab->hasPrimKey = 1;
01108   if( pList==0 ){
01109     iCol = pTab->nCol - 1;
01110     pTab->aCol[iCol].isPrimKey = 1;
01111   }else{
01112     for(i=0; i<pList->nExpr; i++){
01113       for(iCol=0; iCol<pTab->nCol; iCol++){
01114         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
01115           break;
01116         }
01117       }
01118       if( iCol<pTab->nCol ){
01119         pTab->aCol[iCol].isPrimKey = 1;
01120       }
01121     }
01122     if( pList->nExpr>1 ) iCol = -1;
01123   }
01124   if( iCol>=0 && iCol<pTab->nCol ){
01125     zType = pTab->aCol[iCol].zType;
01126   }
01127   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
01128         && sortOrder==SQLITE_SO_ASC ){
01129     pTab->iPKey = iCol;
01130     pTab->keyConf = onError;
01131     pTab->autoInc = autoInc;
01132   }else if( autoInc ){
01133 #ifndef SQLITE_OMIT_AUTOINCREMENT
01134     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
01135        "INTEGER PRIMARY KEY");
01136 #endif
01137   }else{
01138     sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
01139     pList = 0;
01140   }
01141 
01142 primary_key_exit:
01143   sqlite3ExprListDelete(pList);
01144   return;
01145 }
01146 
01147 /*
01148 ** Add a new CHECK constraint to the table currently under construction.
01149 */
01150 void sqlite3AddCheckConstraint(
01151   Parse *pParse,    /* Parsing context */
01152   Expr *pCheckExpr  /* The check expression */
01153 ){
01154 #ifndef SQLITE_OMIT_CHECK
01155   Table *pTab = pParse->pNewTable;
01156   if( pTab ){
01157     /* The CHECK expression must be duplicated so that tokens refer
01158     ** to malloced space and not the (ephemeral) text of the CREATE TABLE
01159     ** statement */
01160     pTab->pCheck = sqlite3ExprAnd(pTab->pCheck, sqlite3ExprDup(pCheckExpr));
01161   }
01162 #endif
01163   sqlite3ExprDelete(pCheckExpr);
01164 }
01165 
01166 /*
01167 ** Set the collation function of the most recently parsed table column
01168 ** to the CollSeq given.
01169 */
01170 void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){
01171   Table *p;
01172   int i;
01173 
01174   if( (p = pParse->pNewTable)==0 ) return;
01175   i = p->nCol-1;
01176 
01177   if( sqlite3LocateCollSeq(pParse, zType, nType) ){
01178     Index *pIdx;
01179     p->aCol[i].zColl = sqliteStrNDup(zType, nType);
01180   
01181     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
01182     ** then an index may have been created on this column before the
01183     ** collation type was added. Correct this if it is the case.
01184     */
01185     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
01186       assert( pIdx->nColumn==1 );
01187       if( pIdx->aiColumn[0]==i ){
01188         pIdx->azColl[0] = p->aCol[i].zColl;
01189       }
01190     }
01191   }
01192 }
01193 
01194 /*
01195 ** This function returns the collation sequence for database native text
01196 ** encoding identified by the string zName, length nName.
01197 **
01198 ** If the requested collation sequence is not available, or not available
01199 ** in the database native encoding, the collation factory is invoked to
01200 ** request it. If the collation factory does not supply such a sequence,
01201 ** and the sequence is available in another text encoding, then that is
01202 ** returned instead.
01203 **
01204 ** If no versions of the requested collations sequence are available, or
01205 ** another error occurs, NULL is returned and an error message written into
01206 ** pParse.
01207 */
01208 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
01209   sqlite3 *db = pParse->db;
01210   u8 enc = ENC(db);
01211   u8 initbusy = db->init.busy;
01212   CollSeq *pColl;
01213 
01214   pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
01215   if( !initbusy && (!pColl || !pColl->xCmp) ){
01216     pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
01217     if( !pColl ){
01218       if( nName<0 ){
01219         nName = strlen(zName);
01220       }
01221       sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
01222       pColl = 0;
01223     }
01224   }
01225 
01226   return pColl;
01227 }
01228 
01229 
01230 /*
01231 ** Generate code that will increment the schema cookie.
01232 **
01233 ** The schema cookie is used to determine when the schema for the
01234 ** database changes.  After each schema change, the cookie value
01235 ** changes.  When a process first reads the schema it records the
01236 ** cookie.  Thereafter, whenever it goes to access the database,
01237 ** it checks the cookie to make sure the schema has not changed
01238 ** since it was last read.
01239 **
01240 ** This plan is not completely bullet-proof.  It is possible for
01241 ** the schema to change multiple times and for the cookie to be
01242 ** set back to prior value.  But schema changes are infrequent
01243 ** and the probability of hitting the same cookie value is only
01244 ** 1 chance in 2^32.  So we're safe enough.
01245 */
01246 void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){
01247   sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, 0);
01248   sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0);
01249 }
01250 
01251 /*
01252 ** Measure the number of characters needed to output the given
01253 ** identifier.  The number returned includes any quotes used
01254 ** but does not include the null terminator.
01255 **
01256 ** The estimate is conservative.  It might be larger that what is
01257 ** really needed.
01258 */
01259 static int identLength(const char *z){
01260   int n;
01261   for(n=0; *z; n++, z++){
01262     if( *z=='"' ){ n++; }
01263   }
01264   return n + 2;
01265 }
01266 
01267 /*
01268 ** Write an identifier onto the end of the given string.  Add
01269 ** quote characters as needed.
01270 */
01271 static void identPut(char *z, int *pIdx, char *zSignedIdent){
01272   unsigned char *zIdent = (unsigned char*)zSignedIdent;
01273   int i, j, needQuote;
01274   i = *pIdx;
01275   for(j=0; zIdent[j]; j++){
01276     if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
01277   }
01278   needQuote =  zIdent[j]!=0 || isdigit(zIdent[0])
01279                   || sqlite3KeywordCode(zIdent, j)!=TK_ID;
01280   if( needQuote ) z[i++] = '"';
01281   for(j=0; zIdent[j]; j++){
01282     z[i++] = zIdent[j];
01283     if( zIdent[j]=='"' ) z[i++] = '"';
01284   }
01285   if( needQuote ) z[i++] = '"';
01286   z[i] = 0;
01287   *pIdx = i;
01288 }
01289 
01290 /*
01291 ** Generate a CREATE TABLE statement appropriate for the given
01292 ** table.  Memory to hold the text of the statement is obtained
01293 ** from sqliteMalloc() and must be freed by the calling function.
01294 */
01295 static char *createTableStmt(Table *p, int isTemp){
01296   int i, k, n;
01297   char *zStmt;
01298   char *zSep, *zSep2, *zEnd, *z;
01299   Column *pCol;
01300   n = 0;
01301   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
01302     n += identLength(pCol->zName);
01303     z = pCol->zType;
01304     if( z ){
01305       n += (strlen(z) + 1);
01306     }
01307   }
01308   n += identLength(p->zName);
01309   if( n<50 ){
01310     zSep = "";
01311     zSep2 = ",";
01312     zEnd = ")";
01313   }else{
01314     zSep = "\n  ";
01315     zSep2 = ",\n  ";
01316     zEnd = "\n)";
01317   }
01318   n += 35 + 6*p->nCol;
01319   zStmt = sqliteMallocRaw( n );
01320   if( zStmt==0 ) return 0;
01321   strcpy(zStmt, !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
01322   k = strlen(zStmt);
01323   identPut(zStmt, &k, p->zName);
01324   zStmt[k++] = '(';
01325   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
01326     strcpy(&zStmt[k], zSep);
01327     k += strlen(&zStmt[k]);
01328     zSep = zSep2;
01329     identPut(zStmt, &k, pCol->zName);
01330     if( (z = pCol->zType)!=0 ){
01331       zStmt[k++] = ' ';
01332       strcpy(&zStmt[k], z);
01333       k += strlen(z);
01334     }
01335   }
01336   strcpy(&zStmt[k], zEnd);
01337   return zStmt;
01338 }
01339 
01340 /*
01341 ** This routine is called to report the final ")" that terminates
01342 ** a CREATE TABLE statement.
01343 **
01344 ** The table structure that other action routines have been building
01345 ** is added to the internal hash tables, assuming no errors have
01346 ** occurred.
01347 **
01348 ** An entry for the table is made in the master table on disk, unless
01349 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
01350 ** it means we are reading the sqlite_master table because we just
01351 ** connected to the database or because the sqlite_master table has
01352 ** recently changed, so the entry for this table already exists in
01353 ** the sqlite_master table.  We do not want to create it again.
01354 **
01355 ** If the pSelect argument is not NULL, it means that this routine
01356 ** was called to create a table generated from a 
01357 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
01358 ** the new table will match the result set of the SELECT.
01359 */
01360 void sqlite3EndTable(
01361   Parse *pParse,          /* Parse context */
01362   Token *pCons,           /* The ',' token after the last column defn. */
01363   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
01364   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
01365 ){
01366   Table *p;
01367   sqlite3 *db = pParse->db;
01368   int iDb;
01369 
01370   if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite3MallocFailed() ) {
01371     return;
01372   }
01373   p = pParse->pNewTable;
01374   if( p==0 ) return;
01375 
01376   assert( !db->init.busy || !pSelect );
01377 
01378   iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
01379 
01380 #ifndef SQLITE_OMIT_CHECK
01381   /* Resolve names in all CHECK constraint expressions.
01382   */
01383   if( p->pCheck ){
01384     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
01385     NameContext sNC;                /* Name context for pParse->pNewTable */
01386 
01387     memset(&sNC, 0, sizeof(sNC));
01388     memset(&sSrc, 0, sizeof(sSrc));
01389     sSrc.nSrc = 1;
01390     sSrc.a[0].zName = p->zName;
01391     sSrc.a[0].pTab = p;
01392     sSrc.a[0].iCursor = -1;
01393     sNC.pParse = pParse;
01394     sNC.pSrcList = &sSrc;
01395     sNC.isCheck = 1;
01396     if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){
01397       return;
01398     }
01399   }
01400 #endif /* !defined(SQLITE_OMIT_CHECK) */
01401 
01402   /* If the db->init.busy is 1 it means we are reading the SQL off the
01403   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
01404   ** So do not write to the disk again.  Extract the root page number
01405   ** for the table from the db->init.newTnum field.  (The page number
01406   ** should have been put there by the sqliteOpenCb routine.)
01407   */
01408   if( db->init.busy ){
01409     p->tnum = db->init.newTnum;
01410   }
01411 
01412   /* If not initializing, then create a record for the new table
01413   ** in the SQLITE_MASTER table of the database.  The record number
01414   ** for the new table entry should already be on the stack.
01415   **
01416   ** If this is a TEMPORARY table, write the entry into the auxiliary
01417   ** file instead of into the main database file.
01418   */
01419   if( !db->init.busy ){
01420     int n;
01421     Vdbe *v;
01422     char *zType;    /* "view" or "table" */
01423     char *zType2;   /* "VIEW" or "TABLE" */
01424     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
01425 
01426     v = sqlite3GetVdbe(pParse);
01427     if( v==0 ) return;
01428 
01429     sqlite3VdbeAddOp(v, OP_Close, 0, 0);
01430 
01431     /* Create the rootpage for the new table and push it onto the stack.
01432     ** A view has no rootpage, so just push a zero onto the stack for
01433     ** views.  Initialize zType at the same time.
01434     */
01435     if( p->pSelect==0 ){
01436       /* A regular table */
01437       zType = "table";
01438       zType2 = "TABLE";
01439 #ifndef SQLITE_OMIT_VIEW
01440     }else{
01441       /* A view */
01442       zType = "view";
01443       zType2 = "VIEW";
01444 #endif
01445     }
01446 
01447     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
01448     ** statement to populate the new table. The root-page number for the
01449     ** new table is on the top of the vdbe stack.
01450     **
01451     ** Once the SELECT has been coded by sqlite3Select(), it is in a
01452     ** suitable state to query for the column names and types to be used
01453     ** by the new table.
01454     **
01455     ** A shared-cache write-lock is not required to write to the new table,
01456     ** as a schema-lock must have already been obtained to create it. Since
01457     ** a schema-lock excludes all other database users, the write-lock would
01458     ** be redundant.
01459     */
01460     if( pSelect ){
01461       Table *pSelTab;
01462       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
01463       sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
01464       sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0);
01465       pParse->nTab = 2;
01466       sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0);
01467       sqlite3VdbeAddOp(v, OP_Close, 1, 0);
01468       if( pParse->nErr==0 ){
01469         pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
01470         if( pSelTab==0 ) return;
01471         assert( p->aCol==0 );
01472         p->nCol = pSelTab->nCol;
01473         p->aCol = pSelTab->aCol;
01474         pSelTab->nCol = 0;
01475         pSelTab->aCol = 0;
01476         sqlite3DeleteTable(0, pSelTab);
01477       }
01478     }
01479 
01480     /* Compute the complete text of the CREATE statement */
01481     if( pSelect ){
01482       zStmt = createTableStmt(p, p->pSchema==pParse->db->aDb[1].pSchema);
01483     }else{
01484       n = pEnd->z - pParse->sNameToken.z + 1;
01485       zStmt = sqlite3MPrintf("CREATE %s %.*s", zType2, n, pParse->sNameToken.z);
01486     }
01487 
01488     /* A slot for the record has already been allocated in the 
01489     ** SQLITE_MASTER table.  We just need to update that slot with all
01490     ** the information we've collected.  The rowid for the preallocated
01491     ** slot is the 2nd item on the stack.  The top of the stack is the
01492     ** root page for the new table (or a 0 if this is a view).
01493     */
01494     sqlite3NestedParse(pParse,
01495       "UPDATE %Q.%s "
01496          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q "
01497        "WHERE rowid=#1",
01498       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
01499       zType,
01500       p->zName,
01501       p->zName,
01502       zStmt
01503     );
01504     sqliteFree(zStmt);
01505     sqlite3ChangeCookie(db, v, iDb);
01506 
01507 #ifndef SQLITE_OMIT_AUTOINCREMENT
01508     /* Check to see if we need to create an sqlite_sequence table for
01509     ** keeping track of autoincrement keys.
01510     */
01511     if( p->autoInc ){
01512       Db *pDb = &db->aDb[iDb];
01513       if( pDb->pSchema->pSeqTab==0 ){
01514         sqlite3NestedParse(pParse,
01515           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
01516           pDb->zName
01517         );
01518       }
01519     }
01520 #endif
01521 
01522     /* Reparse everything to update our internal data structures */
01523     sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
01524         sqlite3MPrintf("tbl_name='%q'",p->zName), P3_DYNAMIC);
01525   }
01526 
01527 
01528   /* Add the table to the in-memory representation of the database.
01529   */
01530   if( db->init.busy && pParse->nErr==0 ){
01531     Table *pOld;
01532     FKey *pFKey; 
01533     Schema *pSchema = p->pSchema;
01534     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
01535     if( pOld ){
01536       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
01537       return;
01538     }
01539 #ifndef SQLITE_OMIT_FOREIGN_KEY
01540     for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
01541       int nTo = strlen(pFKey->zTo) + 1;
01542       pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
01543       sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
01544     }
01545 #endif
01546     pParse->pNewTable = 0;
01547     db->nTable++;
01548     db->flags |= SQLITE_InternChanges;
01549 
01550 #ifndef SQLITE_OMIT_ALTERTABLE
01551     if( !p->pSelect ){
01552       const char *zName = (const char *)pParse->sNameToken.z;
01553       int nName;
01554       assert( !pSelect && pCons && pEnd );
01555       if( pCons->z==0 ){
01556         pCons = pEnd;
01557       }
01558       nName = (const char *)pCons->z - zName;
01559       p->addColOffset = 13 + sqlite3utf8CharLen(zName, nName);
01560     }
01561 #endif
01562   }
01563 }
01564 
01565 #ifndef SQLITE_OMIT_VIEW
01566 /*
01567 ** The parser calls this routine in order to create a new VIEW
01568 */
01569 void sqlite3CreateView(
01570   Parse *pParse,     /* The parsing context */
01571   Token *pBegin,     /* The CREATE token that begins the statement */
01572   Token *pName1,     /* The token that holds the name of the view */
01573   Token *pName2,     /* The token that holds the name of the view */
01574   Select *pSelect,   /* A SELECT statement that will become the new view */
01575   int isTemp         /* TRUE for a TEMPORARY view */
01576 ){
01577   Table *p;
01578   int n;
01579   const unsigned char *z;
01580   Token sEnd;
01581   DbFixer sFix;
01582   Token *pName;
01583   int iDb;
01584 
01585   if( pParse->nVar>0 ){
01586     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
01587     sqlite3SelectDelete(pSelect);
01588     return;
01589   }
01590   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0);
01591   p = pParse->pNewTable;
01592   if( p==0 || pParse->nErr ){
01593     sqlite3SelectDelete(pSelect);
01594     return;
01595   }
01596   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
01597   iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
01598   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
01599     && sqlite3FixSelect(&sFix, pSelect)
01600   ){
01601     sqlite3SelectDelete(pSelect);
01602     return;
01603   }
01604 
01605   /* Make a copy of the entire SELECT statement that defines the view.
01606   ** This will force all the Expr.token.z values to be dynamically
01607   ** allocated rather than point to the input string - which means that
01608   ** they will persist after the current sqlite3_exec() call returns.
01609   */
01610   p->pSelect = sqlite3SelectDup(pSelect);
01611   sqlite3SelectDelete(pSelect);
01612   if( sqlite3MallocFailed() ){
01613     return;
01614   }
01615   if( !pParse->db->init.busy ){
01616     sqlite3ViewGetColumnNames(pParse, p);
01617   }
01618 
01619   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
01620   ** the end.
01621   */
01622   sEnd = pParse->sLastToken;
01623   if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
01624     sEnd.z += sEnd.n;
01625   }
01626   sEnd.n = 0;
01627   n = sEnd.z - pBegin->z;
01628   z = (const unsigned char*)pBegin->z;
01629   while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
01630   sEnd.z = &z[n-1];
01631   sEnd.n = 1;
01632 
01633   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
01634   sqlite3EndTable(pParse, 0, &sEnd, 0);
01635   return;
01636 }
01637 #endif /* SQLITE_OMIT_VIEW */
01638 
01639 #ifndef SQLITE_OMIT_VIEW
01640 /*
01641 ** The Table structure pTable is really a VIEW.  Fill in the names of
01642 ** the columns of the view in the pTable structure.  Return the number
01643 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
01644 */
01645 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
01646   Table *pSelTab;   /* A fake table from which we get the result set */
01647   Select *pSel;     /* Copy of the SELECT that implements the view */
01648   int nErr = 0;     /* Number of errors encountered */
01649   int n;            /* Temporarily holds the number of cursors assigned */
01650 
01651   assert( pTable );
01652 
01653   /* A positive nCol means the columns names for this view are
01654   ** already known.
01655   */
01656   if( pTable->nCol>0 ) return 0;
01657 
01658   /* A negative nCol is a special marker meaning that we are currently
01659   ** trying to compute the column names.  If we enter this routine with
01660   ** a negative nCol, it means two or more views form a loop, like this:
01661   **
01662   **     CREATE VIEW one AS SELECT * FROM two;
01663   **     CREATE VIEW two AS SELECT * FROM one;
01664   **
01665   ** Actually, this error is caught previously and so the following test
01666   ** should always fail.  But we will leave it in place just to be safe.
01667   */
01668   if( pTable->nCol<0 ){
01669     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
01670     return 1;
01671   }
01672   assert( pTable->nCol>=0 );
01673 
01674   /* If we get this far, it means we need to compute the table names.
01675   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
01676   ** "*" elements in the results set of the view and will assign cursors
01677   ** to the elements of the FROM clause.  But we do not want these changes
01678   ** to be permanent.  So the computation is done on a copy of the SELECT
01679   ** statement that defines the view.
01680   */
01681   assert( pTable->pSelect );
01682   pSel = sqlite3SelectDup(pTable->pSelect);
01683   if( pSel ){
01684     n = pParse->nTab;
01685     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
01686     pTable->nCol = -1;
01687     pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
01688     pParse->nTab = n;
01689     if( pSelTab ){
01690       assert( pTable->aCol==0 );
01691       pTable->nCol = pSelTab->nCol;
01692       pTable->aCol = pSelTab->aCol;
01693       pSelTab->nCol = 0;
01694       pSelTab->aCol = 0;
01695       sqlite3DeleteTable(0, pSelTab);
01696       pTable->pSchema->flags |= DB_UnresetViews;
01697     }else{
01698       pTable->nCol = 0;
01699       nErr++;
01700     }
01701     sqlite3SelectDelete(pSel);
01702   } else {
01703     nErr++;
01704   }
01705   return nErr;  
01706 }
01707 #endif /* SQLITE_OMIT_VIEW */
01708 
01709 #ifndef SQLITE_OMIT_VIEW
01710 /*
01711 ** Clear the column names from every VIEW in database idx.
01712 */
01713 static void sqliteViewResetAll(sqlite3 *db, int idx){
01714   HashElem *i;
01715   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
01716   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
01717     Table *pTab = sqliteHashData(i);
01718     if( pTab->pSelect ){
01719       sqliteResetColumnNames(pTab);
01720     }
01721   }
01722   DbClearProperty(db, idx, DB_UnresetViews);
01723 }
01724 #else
01725 # define sqliteViewResetAll(A,B)
01726 #endif /* SQLITE_OMIT_VIEW */
01727 
01728 /*
01729 ** This function is called by the VDBE to adjust the internal schema
01730 ** used by SQLite when the btree layer moves a table root page. The
01731 ** root-page of a table or index in database iDb has changed from iFrom
01732 ** to iTo.
01733 **
01734 ** Ticket #1728:  The symbol table might still contain information
01735 ** on tables and/or indices that are the process of being deleted.
01736 ** If you are unlucky, one of those deleted indices or tables might
01737 ** have the same rootpage number as the real table or index that is
01738 ** being moved.  So we cannot stop searching after the first match 
01739 ** because the first match might be for one of the deleted indices
01740 ** or tables and not the table/index that is actually being moved.
01741 ** We must continue looping until all tables and indices with
01742 ** rootpage==iFrom have been converted to have a rootpage of iTo
01743 ** in order to be certain that we got the right one.
01744 */
01745 #ifndef SQLITE_OMIT_AUTOVACUUM
01746 void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
01747   HashElem *pElem;
01748   Hash *pHash;
01749 
01750   pHash = &pDb->pSchema->tblHash;
01751   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
01752     Table *pTab = sqliteHashData(pElem);
01753     if( pTab->tnum==iFrom ){
01754       pTab->tnum = iTo;
01755     }
01756   }
01757   pHash = &pDb->pSchema->idxHash;
01758   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
01759     Index *pIdx = sqliteHashData(pElem);
01760     if( pIdx->tnum==iFrom ){
01761       pIdx->tnum = iTo;
01762     }
01763   }
01764 }
01765 #endif
01766 
01767 /*
01768 ** Write code to erase the table with root-page iTable from database iDb.
01769 ** Also write code to modify the sqlite_master table and internal schema
01770 ** if a root-page of another table is moved by the btree-layer whilst
01771 ** erasing iTable (this can happen with an auto-vacuum database).
01772 */ 
01773 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
01774   Vdbe *v = sqlite3GetVdbe(pParse);
01775   sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb);
01776 #ifndef SQLITE_OMIT_AUTOVACUUM
01777   /* OP_Destroy pushes an integer onto the stack. If this integer
01778   ** is non-zero, then it is the root page number of a table moved to
01779   ** location iTable. The following code modifies the sqlite_master table to
01780   ** reflect this.
01781   **
01782   ** The "#0" in the SQL is a special constant that means whatever value
01783   ** is on the top of the stack.  See sqlite3RegisterExpr().
01784   */
01785   sqlite3NestedParse(pParse, 
01786      "UPDATE %Q.%s SET rootpage=%d WHERE #0 AND rootpage=#0",
01787      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable);
01788 #endif
01789 }
01790 
01791 /*
01792 ** Write VDBE code to erase table pTab and all associated indices on disk.
01793 ** Code to update the sqlite_master tables and internal schema definitions
01794 ** in case a root-page belonging to another table is moved by the btree layer
01795 ** is also added (this can happen with an auto-vacuum database).
01796 */
01797 static void destroyTable(Parse *pParse, Table *pTab){
01798 #ifdef SQLITE_OMIT_AUTOVACUUM
01799   Index *pIdx;
01800   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
01801   destroyRootPage(pParse, pTab->tnum, iDb);
01802   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
01803     destroyRootPage(pParse, pIdx->tnum, iDb);
01804   }
01805 #else
01806   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
01807   ** is not defined), then it is important to call OP_Destroy on the
01808   ** table and index root-pages in order, starting with the numerically 
01809   ** largest root-page number. This guarantees that none of the root-pages
01810   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
01811   ** following were coded:
01812   **
01813   ** OP_Destroy 4 0
01814   ** ...
01815   ** OP_Destroy 5 0
01816   **
01817   ** and root page 5 happened to be the largest root-page number in the
01818   ** database, then root page 5 would be moved to page 4 by the 
01819   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
01820   ** a free-list page.
01821   */
01822   int iTab = pTab->tnum;
01823   int iDestroyed = 0;
01824 
01825   while( 1 ){
01826     Index *pIdx;
01827     int iLargest = 0;
01828 
01829     if( iDestroyed==0 || iTab<iDestroyed ){
01830       iLargest = iTab;
01831     }
01832     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
01833       int iIdx = pIdx->tnum;
01834       assert( pIdx->pSchema==pTab->pSchema );
01835       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
01836         iLargest = iIdx;
01837       }
01838     }
01839     if( iLargest==0 ){
01840       return;
01841     }else{
01842       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
01843       destroyRootPage(pParse, iLargest, iDb);
01844       iDestroyed = iLargest;
01845     }
01846   }
01847 #endif
01848 }
01849 
01850 /*
01851 ** This routine is called to do the work of a DROP TABLE statement.
01852 ** pName is the name of the table to be dropped.
01853 */
01854 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
01855   Table *pTab;
01856   Vdbe *v;
01857   sqlite3 *db = pParse->db;
01858   int iDb;
01859 
01860   if( pParse->nErr || sqlite3MallocFailed() ){
01861     goto exit_drop_table;
01862   }
01863   assert( pName->nSrc==1 );
01864   pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);
01865 
01866   if( pTab==0 ){
01867     if( noErr ){
01868       sqlite3ErrorClear(pParse);
01869     }
01870     goto exit_drop_table;
01871   }
01872   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
01873   assert( iDb>=0 && iDb<db->nDb );
01874 #ifndef SQLITE_OMIT_AUTHORIZATION
01875   {
01876     int code;
01877     const char *zTab = SCHEMA_TABLE(iDb);
01878     const char *zDb = db->aDb[iDb].zName;
01879     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
01880       goto exit_drop_table;
01881     }
01882     if( isView ){
01883       if( !OMIT_TEMPDB && iDb==1 ){
01884         code = SQLITE_DROP_TEMP_VIEW;
01885       }else{
01886         code = SQLITE_DROP_VIEW;
01887       }
01888     }else{
01889       if( !OMIT_TEMPDB && iDb==1 ){
01890         code = SQLITE_DROP_TEMP_TABLE;
01891       }else{
01892         code = SQLITE_DROP_TABLE;
01893       }
01894     }
01895     if( sqlite3AuthCheck(pParse, code, pTab->zName, 0, zDb) ){
01896       goto exit_drop_table;
01897     }
01898     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
01899       goto exit_drop_table;
01900     }
01901   }
01902 #endif
01903   if( pTab->readOnly || pTab==db->aDb[iDb].pSchema->pSeqTab ){
01904     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
01905     goto exit_drop_table;
01906   }
01907 
01908 #ifndef SQLITE_OMIT_VIEW
01909   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
01910   ** on a table.
01911   */
01912   if( isView && pTab->pSelect==0 ){
01913     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
01914     goto exit_drop_table;
01915   }
01916   if( !isView && pTab->pSelect ){
01917     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
01918     goto exit_drop_table;
01919   }
01920 #endif
01921 
01922   /* Generate code to remove the table from the master table
01923   ** on disk.
01924   */
01925   v = sqlite3GetVdbe(pParse);
01926   if( v ){
01927     Trigger *pTrigger;
01928     Db *pDb = &db->aDb[iDb];
01929     sqlite3BeginWriteOperation(pParse, 0, iDb);
01930 
01931     /* Drop all triggers associated with the table being dropped. Code
01932     ** is generated to remove entries from sqlite_master and/or
01933     ** sqlite_temp_master if required.
01934     */
01935     pTrigger = pTab->pTrigger;
01936     while( pTrigger ){
01937       assert( pTrigger->pSchema==pTab->pSchema || 
01938           pTrigger->pSchema==db->aDb[1].pSchema );
01939       sqlite3DropTriggerPtr(pParse, pTrigger);
01940       pTrigger = pTrigger->pNext;
01941     }
01942 
01943 #ifndef SQLITE_OMIT_AUTOINCREMENT
01944     /* Remove any entries of the sqlite_sequence table associated with
01945     ** the table being dropped. This is done before the table is dropped
01946     ** at the btree level, in case the sqlite_sequence table needs to
01947     ** move as a result of the drop (can happen in auto-vacuum mode).
01948     */
01949     if( pTab->autoInc ){
01950       sqlite3NestedParse(pParse,
01951         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
01952         pDb->zName, pTab->zName
01953       );
01954     }
01955 #endif
01956 
01957     /* Drop all SQLITE_MASTER table and index entries that refer to the
01958     ** table. The program name loops through the master table and deletes
01959     ** every row that refers to a table of the same name as the one being
01960     ** dropped. Triggers are handled seperately because a trigger can be
01961     ** created in the temp database that refers to a table in another
01962     ** database.
01963     */
01964     sqlite3NestedParse(pParse, 
01965         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
01966         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
01967     if( !isView ){
01968       destroyTable(pParse, pTab);
01969     }
01970 
01971     /* Remove the table entry from SQLite's internal schema and modify
01972     ** the schema cookie.
01973     */
01974     sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
01975     sqlite3ChangeCookie(db, v, iDb);
01976   }
01977   sqliteViewResetAll(db, iDb);
01978 
01979 exit_drop_table:
01980   sqlite3SrcListDelete(pName);
01981 }
01982 
01983 /*
01984 ** This routine is called to create a new foreign key on the table
01985 ** currently under construction.  pFromCol determines which columns
01986 ** in the current table point to the foreign key.  If pFromCol==0 then
01987 ** connect the key to the last column inserted.  pTo is the name of
01988 ** the table referred to.  pToCol is a list of tables in the other
01989 ** pTo table that the foreign key points to.  flags contains all
01990 ** information about the conflict resolution algorithms specified
01991 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
01992 **
01993 ** An FKey structure is created and added to the table currently
01994 ** under construction in the pParse->pNewTable field.  The new FKey
01995 ** is not linked into db->aFKey at this point - that does not happen
01996 ** until sqlite3EndTable().
01997 **
01998 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
01999 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
02000 */
02001 void sqlite3CreateForeignKey(
02002   Parse *pParse,       /* Parsing context */
02003   ExprList *pFromCol,  /* Columns in this table that point to other table */
02004   Token *pTo,          /* Name of the other table */
02005   ExprList *pToCol,    /* Columns in the other table */
02006   int flags            /* Conflict resolution algorithms. */
02007 ){
02008 #ifndef SQLITE_OMIT_FOREIGN_KEY
02009   FKey *pFKey = 0;
02010   Table *p = pParse->pNewTable;
02011   int nByte;
02012   int i;
02013   int nCol;
02014   char *z;
02015 
02016   assert( pTo!=0 );
02017   if( p==0 || pParse->nErr ) goto fk_end;
02018   if( pFromCol==0 ){
02019     int iCol = p->nCol-1;
02020     if( iCol<0 ) goto fk_end;
02021     if( pToCol && pToCol->nExpr!=1 ){
02022       sqlite3ErrorMsg(pParse, "foreign key on %s"
02023          " should reference only one column of table %T",
02024          p->aCol[iCol].zName, pTo);
02025       goto fk_end;
02026     }
02027     nCol = 1;
02028   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
02029     sqlite3ErrorMsg(pParse,
02030         "number of columns in foreign key does not match the number of "
02031         "columns in the referenced table");
02032     goto fk_end;
02033   }else{
02034     nCol = pFromCol->nExpr;
02035   }
02036   nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
02037   if( pToCol ){
02038     for(i=0; i<pToCol->nExpr; i++){
02039       nByte += strlen(pToCol->a[i].zName) + 1;
02040     }
02041   }
02042   pFKey = sqliteMalloc( nByte );
02043   if( pFKey==0 ) goto fk_end;
02044   pFKey->pFrom = p;
02045   pFKey->pNextFrom = p->pFKey;
02046   z = (char*)&pFKey[1];
02047   pFKey->aCol = (struct sColMap*)z;
02048   z += sizeof(struct sColMap)*nCol;
02049   pFKey->zTo = z;
02050   memcpy(z, pTo->z, pTo->n);
02051   z[pTo->n] = 0;
02052   z += pTo->n+1;
02053   pFKey->pNextTo = 0;
02054   pFKey->nCol = nCol;
02055   if( pFromCol==0 ){
02056     pFKey->aCol[0].iFrom = p->nCol-1;
02057   }else{
02058     for(i=0; i<nCol; i++){
02059       int j;
02060       for(j=0; j<p->nCol; j++){
02061         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
02062           pFKey->aCol[i].iFrom = j;
02063           break;
02064         }
02065       }
02066       if( j>=p->nCol ){
02067         sqlite3ErrorMsg(pParse, 
02068           "unknown column \"%s\" in foreign key definition", 
02069           pFromCol->a[i].zName);
02070         goto fk_end;
02071       }
02072     }
02073   }
02074   if( pToCol ){
02075     for(i=0; i<nCol; i++){
02076       int n = strlen(pToCol->a[i].zName);
02077       pFKey->aCol[i].zCol = z;
02078       memcpy(z, pToCol->a[i].zName, n);
02079       z[n] = 0;
02080       z += n+1;
02081     }
02082   }
02083   pFKey->isDeferred = 0;
02084   pFKey->deleteConf = flags & 0xff;
02085   pFKey->updateConf = (flags >> 8 ) & 0xff;
02086   pFKey->insertConf = (flags >> 16 ) & 0xff;
02087 
02088   /* Link the foreign key to the table as the last step.
02089   */
02090   p->pFKey = pFKey;
02091   pFKey = 0;
02092 
02093 fk_end:
02094   sqliteFree(pFKey);
02095 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
02096   sqlite3ExprListDelete(pFromCol);
02097   sqlite3ExprListDelete(pToCol);
02098 }
02099 
02100 /*
02101 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
02102 ** clause is seen as part of a foreign key definition.  The isDeferred
02103 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
02104 ** The behavior of the most recently created foreign key is adjusted
02105 ** accordingly.
02106 */
02107 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
02108 #ifndef SQLITE_OMIT_FOREIGN_KEY
02109   Table *pTab;
02110   FKey *pFKey;
02111   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
02112   pFKey->isDeferred = isDeferred;
02113 #endif
02114 }
02115 
02116 /*
02117 ** Generate code that will erase and refill index *pIdx.  This is
02118 ** used to initialize a newly created index or to recompute the
02119 ** content of an index in response to a REINDEX command.
02120 **
02121 ** if memRootPage is not negative, it means that the index is newly
02122 ** created.  The memory cell specified by memRootPage contains the
02123 ** root page number of the index.  If memRootPage is negative, then
02124 ** the index already exists and must be cleared before being refilled and
02125 ** the root page number of the index is taken from pIndex->tnum.
02126 */
02127 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
02128   Table *pTab = pIndex->pTable;  /* The table that is indexed */
02129   int iTab = pParse->nTab;       /* Btree cursor used for pTab */
02130   int iIdx = pParse->nTab+1;     /* Btree cursor used for pIndex */
02131   int addr1;                     /* Address of top of loop */
02132   int tnum;                      /* Root page of index */
02133   Vdbe *v;                       /* Generate code into this virtual machine */
02134   KeyInfo *pKey;                 /* KeyInfo for index */
02135   int iDb = sqlite3SchemaToIndex(pParse->db, pIndex->pSchema);
02136 
02137 #ifndef SQLITE_OMIT_AUTHORIZATION
02138   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
02139       pParse->db->aDb[iDb].zName ) ){
02140     return;
02141   }
02142 #endif
02143 
02144   /* Require a write-lock on the table to perform this operation */
02145   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
02146 
02147   v = sqlite3GetVdbe(pParse);
02148   if( v==0 ) return;
02149   if( memRootPage>=0 ){
02150     sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0);
02151     tnum = 0;
02152   }else{
02153     tnum = pIndex->tnum;
02154     sqlite3VdbeAddOp(v, OP_Clear, tnum, iDb);
02155   }
02156   sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
02157   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
02158   sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum, (char *)pKey, P3_KEYINFO_HANDOFF);
02159   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
02160   addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
02161   sqlite3GenerateIndexKey(v, pIndex, iTab);
02162   if( pIndex->onError!=OE_None ){
02163     int curaddr = sqlite3VdbeCurrentAddr(v);
02164     int addr2 = curaddr+4;
02165     sqlite3VdbeChangeP2(v, curaddr-1, addr2);
02166     sqlite3VdbeAddOp(v, OP_Rowid, iTab, 0);
02167     sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
02168     sqlite3VdbeAddOp(v, OP_IsUnique, iIdx, addr2);
02169     sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort,
02170                     "indexed columns are not unique", P3_STATIC);
02171     assert( addr2==sqlite3VdbeCurrentAddr(v) );
02172   }
02173   sqlite3VdbeAddOp(v, OP_IdxInsert, iIdx, 0);
02174   sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1);
02175   sqlite3VdbeJumpHere(v, addr1);
02176   sqlite3VdbeAddOp(v, OP_Close, iTab, 0);
02177   sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
02178 }
02179 
02180 /*
02181 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
02182 ** and pTblList is the name of the table that is to be indexed.  Both will 
02183 ** be NULL for a primary key or an index that is created to satisfy a
02184 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
02185 ** as the table to be indexed.  pParse->pNewTable is a table that is
02186 ** currently being constructed by a CREATE TABLE statement.
02187 **
02188 ** pList is a list of columns to be indexed.  pList will be NULL if this
02189 ** is a primary key or unique-constraint on the most recent column added
02190 ** to the table currently under construction.  
02191 */
02192 void sqlite3CreateIndex(
02193   Parse *pParse,     /* All information about this parse */
02194   Token *pName1,     /* First part of index name. May be NULL */
02195   Token *pName2,     /* Second part of index name. May be NULL */
02196   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
02197   ExprList *pList,   /* A list of columns to be indexed */
02198   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
02199   Token *pStart,     /* The CREATE token that begins a CREATE TABLE statement */
02200   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
02201   int sortOrder,     /* Sort order of primary key when pList==NULL */
02202   int ifNotExist     /* Omit error if index already exists */
02203 ){
02204   Table *pTab = 0;     /* Table to be indexed */
02205   Index *pIndex = 0;   /* The index to be created */
02206   char *zName = 0;     /* Name of the index */
02207   int nName;           /* Number of characters in zName */
02208   int i, j;
02209   Token nullId;        /* Fake token for an empty ID list */
02210   DbFixer sFix;        /* For assigning database names to pTable */
02211   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
02212   sqlite3 *db = pParse->db;
02213   Db *pDb;             /* The specific table containing the indexed database */
02214   int iDb;             /* Index of the database that is being written */
02215   Token *pName = 0;    /* Unqualified name of the index to create */
02216   struct ExprList_item *pListItem; /* For looping over pList */
02217   int nCol;
02218   int nExtra = 0;
02219   char *zExtra;
02220 
02221   if( pParse->nErr || sqlite3MallocFailed() ){
02222     goto exit_create_index;
02223   }
02224 
02225   /*
02226   ** Find the table that is to be indexed.  Return early if not found.
02227   */
02228   if( pTblName!=0 ){
02229 
02230     /* Use the two-part index name to determine the database 
02231     ** to search for the table. 'Fix' the table name to this db
02232     ** before looking up the table.
02233     */
02234     assert( pName1 && pName2 );
02235     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
02236     if( iDb<0 ) goto exit_create_index;
02237 
02238 #ifndef SQLITE_OMIT_TEMPDB
02239     /* If the index name was unqualified, check if the the table
02240     ** is a temp table. If so, set the database to 1.
02241     */
02242     pTab = sqlite3SrcListLookup(pParse, pTblName);
02243     if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
02244       iDb = 1;
02245     }
02246 #endif
02247 
02248     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
02249         sqlite3FixSrcList(&sFix, pTblName)
02250     ){
02251       /* Because the parser constructs pTblName from a single identifier,
02252       ** sqlite3FixSrcList can never fail. */
02253       assert(0);
02254     }
02255     pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName, 
02256         pTblName->a[0].zDatabase);
02257     if( !pTab ) goto exit_create_index;
02258     assert( db->aDb[iDb].pSchema==pTab->pSchema );
02259   }else{
02260     assert( pName==0 );
02261     pTab = pParse->pNewTable;
02262     if( !pTab ) goto exit_create_index;
02263     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
02264   }
02265   pDb = &db->aDb[iDb];
02266 
02267   if( pTab==0 || pParse->nErr ) goto exit_create_index;
02268   if( pTab->readOnly ){
02269     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
02270     goto exit_create_index;
02271   }
02272 #ifndef SQLITE_OMIT_VIEW
02273   if( pTab->pSelect ){
02274     sqlite3ErrorMsg(pParse, "views may not be indexed");
02275     goto exit_create_index;
02276   }
02277 #endif
02278 
02279   /*
02280   ** Find the name of the index.  Make sure there is not already another
02281   ** index or table with the same name.  
02282   **
02283   ** Exception:  If we are reading the names of permanent indices from the
02284   ** sqlite_master table (because some other process changed the schema) and
02285   ** one of the index names collides with the name of a temporary table or
02286   ** index, then we will continue to process this index.
02287   **
02288   ** If pName==0 it means that we are
02289   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
02290   ** own name.
02291   */
02292   if( pName ){
02293     zName = sqlite3NameFromToken(pName);
02294     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
02295     if( zName==0 ) goto exit_create_index;
02296     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
02297       goto exit_create_index;
02298     }
02299     if( !db->init.busy ){
02300       if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
02301       if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
02302         if( !ifNotExist ){
02303           sqlite3ErrorMsg(pParse, "index %s already exists", zName);
02304         }
02305         goto exit_create_index;
02306       }
02307       if( sqlite3FindTable(db, zName, 0)!=0 ){
02308         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
02309         goto exit_create_index;
02310       }
02311     }
02312   }else{
02313     char zBuf[30];
02314     int n;
02315     Index *pLoop;
02316     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
02317     sprintf(zBuf,"_%d",n);
02318     zName = 0;
02319     sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0);
02320     if( zName==0 ) goto exit_create_index;
02321   }
02322 
02323   /* Check for authorization to create an index.
02324   */
02325 #ifndef SQLITE_OMIT_AUTHORIZATION
02326   {
02327     const char *zDb = pDb->zName;
02328     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
02329       goto exit_create_index;
02330     }
02331     i = SQLITE_CREATE_INDEX;
02332     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
02333     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
02334       goto exit_create_index;
02335     }
02336   }
02337 #endif
02338 
02339   /* If pList==0, it means this routine was called to make a primary
02340   ** key out of the last column added to the table under construction.
02341   ** So create a fake list to simulate this.
02342   */
02343   if( pList==0 ){
02344     nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
02345     nullId.n = strlen((char*)nullId.z);
02346     pList = sqlite3ExprListAppend(0, 0, &nullId);
02347     if( pList==0 ) goto exit_create_index;
02348     pList->a[0].sortOrder = sortOrder;
02349   }
02350 
02351   /* Figure out how many bytes of space are required to store explicitly
02352   ** specified collation sequence names.
02353   */
02354   for(i=0; i<pList->nExpr; i++){
02355     Expr *pExpr = pList->a[i].pExpr;
02356     if( pExpr ){
02357       nExtra += (1 + strlen(pExpr->pColl->zName));
02358     }
02359   }
02360 
02361   /* 
02362   ** Allocate the index structure. 
02363   */
02364   nName = strlen(zName);
02365   nCol = pList->nExpr;
02366   pIndex = sqliteMalloc( 
02367       sizeof(Index) +              /* Index structure  */
02368       sizeof(int)*nCol +           /* Index.aiColumn   */
02369       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
02370       sizeof(char *)*nCol +        /* Index.azColl     */
02371       sizeof(u8)*nCol +            /* Index.aSortOrder */
02372       nName + 1 +                  /* Index.zName      */
02373       nExtra                       /* Collation sequence names */
02374   );
02375   if( sqlite3MallocFailed() ) goto exit_create_index;
02376   pIndex->azColl = (char**)(&pIndex[1]);
02377   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
02378   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
02379   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
02380   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
02381   zExtra = (char *)(&pIndex->zName[nName+1]);
02382   strcpy(pIndex->zName, zName);
02383   pIndex->pTable = pTab;
02384   pIndex->nColumn = pList->nExpr;
02385   pIndex->onError = onError;
02386   pIndex->autoIndex = pName==0;
02387   pIndex->pSchema = db->aDb[iDb].pSchema;
02388 
02389   /* Check to see if we should honor DESC requests on index columns
02390   */
02391   if( pDb->pSchema->file_format>=4 ){
02392     sortOrderMask = -1;   /* Honor DESC */
02393   }else{
02394     sortOrderMask = 0;    /* Ignore DESC */
02395   }
02396 
02397   /* Scan the names of the columns of the table to be indexed and
02398   ** load the column indices into the Index structure.  Report an error
02399   ** if any column is not found.
02400   */
02401   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
02402     const char *zColName = pListItem->zName;
02403     Column *pTabCol;
02404     int requestedSortOrder;
02405     char *zColl;                   /* Collation sequence */
02406 
02407     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
02408       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
02409     }
02410     if( j>=pTab->nCol ){
02411       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
02412         pTab->zName, zColName);
02413       goto exit_create_index;
02414     }
02415     pIndex->aiColumn[i] = j;
02416     if( pListItem->pExpr ){
02417       assert( pListItem->pExpr->pColl );
02418       zColl = zExtra;
02419       strcpy(zExtra, pListItem->pExpr->pColl->zName);
02420       zExtra += (strlen(zColl) + 1);
02421     }else{
02422       zColl = pTab->aCol[j].zColl;
02423       if( !zColl ){
02424         zColl = db->pDfltColl->zName;
02425       }
02426     }
02427     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
02428       goto exit_create_index;
02429     }
02430     pIndex->azColl[i] = zColl;
02431     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
02432     pIndex->aSortOrder[i] = requestedSortOrder;
02433   }
02434   sqlite3DefaultRowEst(pIndex);
02435 
02436   if( pTab==pParse->pNewTable ){
02437     /* This routine has been called to create an automatic index as a
02438     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
02439     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
02440     ** i.e. one of:
02441     **
02442     ** CREATE TABLE t(x PRIMARY KEY, y);
02443     ** CREATE TABLE t(x, y, UNIQUE(x, y));
02444     **
02445     ** Either way, check to see if the table already has such an index. If
02446     ** so, don't bother creating this one. This only applies to
02447     ** automatically created indices. Users can do as they wish with
02448     ** explicit indices.
02449     */
02450     Index *pIdx;
02451     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
02452       int k;
02453       assert( pIdx->onError!=OE_None );
02454       assert( pIdx->autoIndex );
02455       assert( pIndex->onError!=OE_None );
02456 
02457       if( pIdx->nColumn!=pIndex->nColumn ) continue;
02458       for(k=0; k<pIdx->nColumn; k++){
02459         const char *z1 = pIdx->azColl[k];
02460         const char *z2 = pIndex->azColl[k];
02461         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
02462         if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
02463         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
02464       }
02465       if( k==pIdx->nColumn ){
02466         if( pIdx->onError!=pIndex->onError ){
02467           /* This constraint creates the same index as a previous
02468           ** constraint specified somewhere in the CREATE TABLE statement.
02469           ** However the ON CONFLICT clauses are different. If both this 
02470           ** constraint and the previous equivalent constraint have explicit
02471           ** ON CONFLICT clauses this is an error. Otherwise, use the
02472           ** explicitly specified behaviour for the index.
02473           */
02474           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
02475             sqlite3ErrorMsg(pParse, 
02476                 "conflicting ON CONFLICT clauses specified", 0);
02477           }
02478           if( pIdx->onError==OE_Default ){
02479             pIdx->onError = pIndex->onError;
02480           }
02481         }
02482         goto exit_create_index;
02483       }
02484     }
02485   }
02486 
02487   /* Link the new Index structure to its table and to the other
02488   ** in-memory database structures. 
02489   */
02490   if( db->init.busy ){
02491     Index *p;
02492     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
02493                          pIndex->zName, strlen(pIndex->zName)+1, pIndex);
02494     if( p ){
02495       assert( p==pIndex );  /* Malloc must have failed */
02496       goto exit_create_index;
02497     }
02498     db->flags |= SQLITE_InternChanges;
02499     if( pTblName!=0 ){
02500       pIndex->tnum = db->init.newTnum;
02501     }
02502   }
02503 
02504   /* If the db->init.busy is 0 then create the index on disk.  This
02505   ** involves writing the index into the master table and filling in the
02506   ** index with the current table contents.
02507   **
02508   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
02509   ** command.  db->init.busy is 1 when a database is opened and 
02510   ** CREATE INDEX statements are read out of the master table.  In
02511   ** the latter case the index already exists on disk, which is why
02512   ** we don't want to recreate it.
02513   **
02514   ** If pTblName==0 it means this index is generated as a primary key
02515   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
02516   ** has just been created, it contains no data and the index initialization
02517   ** step can be skipped.
02518   */
02519   else if( db->init.busy==0 ){
02520     Vdbe *v;
02521     char *zStmt;
02522     int iMem = pParse->nMem++;
02523 
02524     v = sqlite3GetVdbe(pParse);
02525     if( v==0 ) goto exit_create_index;
02526 
02527 
02528     /* Create the rootpage for the index
02529     */
02530     sqlite3BeginWriteOperation(pParse, 1, iDb);
02531     sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0);
02532     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
02533 
02534     /* Gather the complete text of the CREATE INDEX statement into
02535     ** the zStmt variable
02536     */
02537     if( pStart && pEnd ){
02538       /* A named index with an explicit CREATE INDEX statement */
02539       zStmt = sqlite3MPrintf("CREATE%s INDEX %.*s",
02540         onError==OE_None ? "" : " UNIQUE",
02541         pEnd->z - pName->z + 1,
02542         pName->z);
02543     }else{
02544       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
02545       /* zStmt = sqlite3MPrintf(""); */
02546       zStmt = 0;
02547     }
02548 
02549     /* Add an entry in sqlite_master for this index
02550     */
02551     sqlite3NestedParse(pParse, 
02552         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);",
02553         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
02554         pIndex->zName,
02555         pTab->zName,
02556         zStmt
02557     );
02558     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
02559     sqliteFree(zStmt);
02560 
02561     /* Fill the index with data and reparse the schema. Code an OP_Expire
02562     ** to invalidate all pre-compiled statements.
02563     */
02564     if( pTblName ){
02565       sqlite3RefillIndex(pParse, pIndex, iMem);
02566       sqlite3ChangeCookie(db, v, iDb);
02567       sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
02568          sqlite3MPrintf("name='%q'", pIndex->zName), P3_DYNAMIC);
02569       sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
02570     }
02571   }
02572 
02573   /* When adding an index to the list of indices for a table, make
02574   ** sure all indices labeled OE_Replace come after all those labeled
02575   ** OE_Ignore.  This is necessary for the correct operation of UPDATE
02576   ** and INSERT.
02577   */
02578   if( db->init.busy || pTblName==0 ){
02579     if( onError!=OE_Replace || pTab->pIndex==0
02580          || pTab->pIndex->onError==OE_Replace){
02581       pIndex->pNext = pTab->pIndex;
02582       pTab->pIndex = pIndex;
02583     }else{
02584       Index *pOther = pTab->pIndex;
02585       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
02586         pOther = pOther->pNext;
02587       }
02588       pIndex->pNext = pOther->pNext;
02589       pOther->pNext = pIndex;
02590     }
02591     pIndex = 0;
02592   }
02593 
02594   /* Clean up before exiting */
02595 exit_create_index:
02596   if( pIndex ){
02597     freeIndex(pIndex);
02598   }
02599   sqlite3ExprListDelete(pList);
02600   sqlite3SrcListDelete(pTblName);
02601   sqliteFree(zName);
02602   return;
02603 }
02604 
02605 /*
02606 ** Generate code to make sure the file format number is at least minFormat.
02607 ** The generated code will increase the file format number if necessary.
02608 */
02609 void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
02610   Vdbe *v;
02611   v = sqlite3GetVdbe(pParse);
02612   if( v ){
02613     sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1);
02614     sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
02615     sqlite3VdbeAddOp(v, OP_Ge, 0, sqlite3VdbeCurrentAddr(v)+3);
02616     sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
02617     sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
02618   }
02619 }
02620 
02621 /*
02622 ** Fill the Index.aiRowEst[] array with default information - information
02623 ** to be used when we have not run the ANALYZE command.
02624 **
02625 ** aiRowEst[0] is suppose to contain the number of elements in the index.
02626 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
02627 ** number of rows in the table that match any particular value of the
02628 ** first column of the index.  aiRowEst[2] is an estimate of the number
02629 ** of rows that match any particular combiniation of the first 2 columns
02630 ** of the index.  And so forth.  It must always be the case that
02631 *
02632 **           aiRowEst[N]<=aiRowEst[N-1]
02633 **           aiRowEst[N]>=1
02634 **
02635 ** Apart from that, we have little to go on besides intuition as to
02636 ** how aiRowEst[] should be initialized.  The numbers generated here
02637 ** are based on typical values found in actual indices.
02638 */
02639 void sqlite3DefaultRowEst(Index *pIdx){
02640   unsigned *a = pIdx->aiRowEst;
02641   int i;
02642   assert( a!=0 );
02643   a[0] = 1000000;
02644   for(i=pIdx->nColumn; i>=5; i--){
02645     a[i] = 5;
02646   }
02647   while( i>=1 ){
02648     a[i] = 11 - i;
02649     i--;
02650   }
02651   if( pIdx->onError!=OE_None ){
02652     a[pIdx->nColumn] = 1;
02653   }
02654 }
02655 
02656 /*
02657 ** This routine will drop an existing named index.  This routine
02658 ** implements the DROP INDEX statement.
02659 */
02660 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
02661   Index *pIndex;
02662   Vdbe *v;
02663   sqlite3 *db = pParse->db;
02664   int iDb;
02665 
02666   if( pParse->nErr || sqlite3MallocFailed() ){
02667     goto exit_drop_index;
02668   }
02669   assert( pName->nSrc==1 );
02670   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
02671     goto exit_drop_index;
02672   }
02673   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
02674   if( pIndex==0 ){
02675     if( !ifExists ){
02676       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
02677     }
02678     pParse->checkSchema = 1;
02679     goto exit_drop_index;
02680   }
02681   if( pIndex->autoIndex ){
02682     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
02683       "or PRIMARY KEY constraint cannot be dropped", 0);
02684     goto exit_drop_index;
02685   }
02686   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
02687 #ifndef SQLITE_OMIT_AUTHORIZATION
02688   {
02689     int code = SQLITE_DROP_INDEX;
02690     Table *pTab = pIndex->pTable;
02691     const char *zDb = db->aDb[iDb].zName;
02692     const char *zTab = SCHEMA_TABLE(iDb);
02693     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
02694       goto exit_drop_index;
02695     }
02696     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
02697     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
02698       goto exit_drop_index;
02699     }
02700   }
02701 #endif
02702 
02703   /* Generate code to remove the index and from the master table */
02704   v = sqlite3GetVdbe(pParse);
02705   if( v ){
02706     sqlite3NestedParse(pParse,
02707        "DELETE FROM %Q.%s WHERE name=%Q",
02708        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
02709        pIndex->zName
02710     );
02711     sqlite3ChangeCookie(db, v, iDb);
02712     destroyRootPage(pParse, pIndex->tnum, iDb);
02713     sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0);
02714   }
02715 
02716 exit_drop_index:
02717   sqlite3SrcListDelete(pName);
02718 }
02719 
02720 /*
02721 ** ppArray points into a structure where there is an array pointer
02722 ** followed by two integers. The first integer is the
02723 ** number of elements in the structure array.  The second integer
02724 ** is the number of allocated slots in the array.
02725 **
02726 ** In other words, the structure looks something like this:
02727 **
02728 **        struct Example1 {
02729 **          struct subElem *aEntry;
02730 **          int nEntry;
02731 **          int nAlloc;
02732 **        }
02733 **
02734 ** The pnEntry parameter points to the equivalent of Example1.nEntry.
02735 **
02736 ** This routine allocates a new slot in the array, zeros it out,
02737 ** and returns its index.  If malloc fails a negative number is returned.
02738 **
02739 ** szEntry is the sizeof of a single array entry.  initSize is the 
02740 ** number of array entries allocated on the initial allocation.
02741 */
02742 int sqlite3ArrayAllocate(void **ppArray, int szEntry, int initSize){
02743   char *p;
02744   int *an = (int*)&ppArray[1];
02745   if( an[0]>=an[1] ){
02746     void *pNew;
02747     int newSize;
02748     newSize = an[1]*2 + initSize;
02749     pNew = sqliteRealloc(*ppArray, newSize*szEntry);
02750     if( pNew==0 ){
02751       return -1;
02752     }
02753     an[1] = newSize;
02754     *ppArray = pNew;
02755   }
02756   p = *ppArray;
02757   memset(&p[an[0]*szEntry], 0, szEntry);
02758   return an[0]++;
02759 }
02760 
02761 /*
02762 ** Append a new element to the given IdList.  Create a new IdList if
02763 ** need be.
02764 **
02765 ** A new IdList is returned, or NULL if malloc() fails.
02766 */
02767 IdList *sqlite3IdListAppend(IdList *pList, Token *pToken){
02768   int i;
02769   if( pList==0 ){
02770     pList = sqliteMalloc( sizeof(IdList) );
02771     if( pList==0 ) return 0;
02772     pList->nAlloc = 0;
02773   }
02774   i = sqlite3ArrayAllocate((void**)&pList->a, sizeof(pList->a[0]), 5);
02775   if( i<0 ){
02776     sqlite3IdListDelete(pList);
02777     return 0;
02778   }
02779   pList->a[i].zName = sqlite3NameFromToken(pToken);
02780   return pList;
02781 }
02782 
02783 /*
02784 ** Delete an IdList.
02785 */
02786 void sqlite3IdListDelete(IdList *pList){
02787   int i;
02788   if( pList==0 ) return;
02789   for(i=0; i<pList->nId; i++){
02790     sqliteFree(pList->a[i].zName);
02791   }
02792   sqliteFree(pList->a);
02793   sqliteFree(pList);
02794 }
02795 
02796 /*
02797 ** Return the index in pList of the identifier named zId.  Return -1
02798 ** if not found.
02799 */
02800 int sqlite3IdListIndex(IdList *pList, const char *zName){
02801   int i;
02802   if( pList==0 ) return -1;
02803   for(i=0; i<pList->nId; i++){
02804     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
02805   }
02806   return -1;
02807 }
02808 
02809 /*
02810 ** Append a new table name to the given SrcList.  Create a new SrcList if
02811 ** need be.  A new entry is created in the SrcList even if pToken is NULL.
02812 **
02813 ** A new SrcList is returned, or NULL if malloc() fails.
02814 **
02815 ** If pDatabase is not null, it means that the table has an optional
02816 ** database name prefix.  Like this:  "database.table".  The pDatabase
02817 ** points to the table name and the pTable points to the database name.
02818 ** The SrcList.a[].zName field is filled with the table name which might
02819 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
02820 ** SrcList.a[].zDatabase is filled with the database name from pTable,
02821 ** or with NULL if no database is specified.
02822 **
02823 ** In other words, if call like this:
02824 **
02825 **         sqlite3SrcListAppend(A,B,0);
02826 **
02827 ** Then B is a table name and the database name is unspecified.  If called
02828 ** like this:
02829 **
02830 **         sqlite3SrcListAppend(A,B,C);
02831 **
02832 ** Then C is the table name and B is the database name.
02833 */
02834 SrcList *sqlite3SrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
02835   struct SrcList_item *pItem;
02836   if( pList==0 ){
02837     pList = sqliteMalloc( sizeof(SrcList) );
02838     if( pList==0 ) return 0;
02839     pList->nAlloc = 1;
02840   }
02841   if( pList->nSrc>=pList->nAlloc ){
02842     SrcList *pNew;
02843     pList->nAlloc *= 2;
02844     pNew = sqliteRealloc(pList,
02845                sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
02846     if( pNew==0 ){
02847       sqlite3SrcListDelete(pList);
02848       return 0;
02849     }
02850     pList = pNew;
02851   }
02852   pItem = &pList->a[pList->nSrc];
02853   memset(pItem, 0, sizeof(pList->a[0]));
02854   if( pDatabase && pDatabase->z==0 ){
02855     pDatabase = 0;
02856   }
02857   if( pDatabase && pTable ){
02858     Token *pTemp = pDatabase;
02859     pDatabase = pTable;
02860     pTable = pTemp;
02861   }
02862   pItem->zName = sqlite3NameFromToken(pTable);
02863   pItem->zDatabase = sqlite3NameFromToken(pDatabase);
02864   pItem->iCursor = -1;
02865   pItem->isPopulated = 0;
02866   pList->nSrc++;
02867   return pList;
02868 }
02869 
02870 /*
02871 ** Assign cursors to all tables in a SrcList
02872 */
02873 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
02874   int i;
02875   struct SrcList_item *pItem;
02876   assert(pList || sqlite3MallocFailed() );
02877   if( pList ){
02878     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
02879       if( pItem->iCursor>=0 ) break;
02880       pItem->iCursor = pParse->nTab++;
02881       if( pItem->pSelect ){
02882         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
02883       }
02884     }
02885   }
02886 }
02887 
02888 /*
02889 ** Add an alias to the last identifier on the given identifier list.
02890 */
02891 void sqlite3SrcListAddAlias(SrcList *pList, Token *pToken){
02892   if( pList && pList->nSrc>0 ){
02893     pList->a[pList->nSrc-1].zAlias = sqlite3NameFromToken(pToken);
02894   }
02895 }
02896 
02897 /*
02898 ** Delete an entire SrcList including all its substructure.
02899 */
02900 void sqlite3SrcListDelete(SrcList *pList){
02901   int i;
02902   struct SrcList_item *pItem;
02903   if( pList==0 ) return;
02904   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
02905     sqliteFree(pItem->zDatabase);
02906     sqliteFree(pItem->zName);
02907     sqliteFree(pItem->zAlias);
02908     sqlite3DeleteTable(0, pItem->pTab);
02909     sqlite3SelectDelete(pItem->pSelect);
02910     sqlite3ExprDelete(pItem->pOn);
02911     sqlite3IdListDelete(pItem->pUsing);
02912   }
02913   sqliteFree(pList);
02914 }
02915 
02916 /*
02917 ** Begin a transaction
02918 */
02919 void sqlite3BeginTransaction(Parse *pParse, int type){
02920   sqlite3 *db;
02921   Vdbe *v;
02922   int i;
02923 
02924   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
02925   if( pParse->nErr || sqlite3MallocFailed() ) return;
02926   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
02927 
02928   v = sqlite3GetVdbe(pParse);
02929   if( !v ) return;
02930   if( type!=TK_DEFERRED ){
02931     for(i=0; i<db->nDb; i++){
02932       sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
02933     }
02934   }
02935   sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0);
02936 }
02937 
02938 /*
02939 ** Commit a transaction
02940 */
02941 void sqlite3CommitTransaction(Parse *pParse){
02942   sqlite3 *db;
02943   Vdbe *v;
02944 
02945   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
02946   if( pParse->nErr || sqlite3MallocFailed() ) return;
02947   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
02948 
02949   v = sqlite3GetVdbe(pParse);
02950   if( v ){
02951     sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
02952   }
02953 }
02954 
02955 /*
02956 ** Rollback a transaction
02957 */
02958 void sqlite3RollbackTransaction(Parse *pParse){
02959   sqlite3 *db;
02960   Vdbe *v;
02961 
02962   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
02963   if( pParse->nErr || sqlite3MallocFailed() ) return;
02964   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
02965 
02966   v = sqlite3GetVdbe(pParse);
02967   if( v ){
02968     sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
02969   }
02970 }
02971 
02972 /*
02973 ** Make sure the TEMP database is open and available for use.  Return
02974 ** the number of errors.  Leave any error messages in the pParse structure.
02975 */
02976 int sqlite3OpenTempDatabase(Parse *pParse){
02977   sqlite3 *db = pParse->db;
02978   if( db->aDb[1].pBt==0 && !pParse->explain ){
02979     int rc = sqlite3BtreeFactory(db, 0, 0, MAX_PAGES, &db->aDb[1].pBt);
02980     if( rc!=SQLITE_OK ){
02981       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
02982         "file for storing temporary tables");
02983       pParse->rc = rc;
02984       return 1;
02985     }
02986     if( db->flags & !db->autoCommit ){
02987       rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1);
02988       if( rc!=SQLITE_OK ){
02989         sqlite3ErrorMsg(pParse, "unable to get a write lock on "
02990           "the temporary database file");
02991         pParse->rc = rc;
02992         return 1;
02993       }
02994     }
02995     assert( db->aDb[1].pSchema );
02996   }
02997   return 0;
02998 }
02999 
03000 /*
03001 ** Generate VDBE code that will verify the schema cookie and start
03002 ** a read-transaction for all named database files.
03003 **
03004 ** It is important that all schema cookies be verified and all
03005 ** read transactions be started before anything else happens in
03006 ** the VDBE program.  But this routine can be called after much other
03007 ** code has been generated.  So here is what we do:
03008 **
03009 ** The first time this routine is called, we code an OP_Goto that
03010 ** will jump to a subroutine at the end of the program.  Then we
03011 ** record every database that needs its schema verified in the
03012 ** pParse->cookieMask field.  Later, after all other code has been
03013 ** generated, the subroutine that does the cookie verifications and
03014 ** starts the transactions will be coded and the OP_Goto P2 value
03015 ** will be made to point to that subroutine.  The generation of the
03016 ** cookie verification subroutine code happens in sqlite3FinishCoding().
03017 **
03018 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
03019 ** schema on any databases.  This can be used to position the OP_Goto
03020 ** early in the code, before we know if any database tables will be used.
03021 */
03022 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
03023   sqlite3 *db;
03024   Vdbe *v;
03025   int mask;
03026 
03027   v = sqlite3GetVdbe(pParse);
03028   if( v==0 ) return;  /* This only happens if there was a prior error */
03029   db = pParse->db;
03030   if( pParse->cookieGoto==0 ){
03031     pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1;
03032   }
03033   if( iDb>=0 ){
03034     assert( iDb<db->nDb );
03035     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
03036     assert( iDb<MAX_ATTACHED+2 );
03037     mask = 1<<iDb;
03038     if( (pParse->cookieMask & mask)==0 ){
03039       pParse->cookieMask |= mask;
03040       pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
03041       if( !OMIT_TEMPDB && iDb==1 ){
03042         sqlite3OpenTempDatabase(pParse);
03043       }
03044     }
03045   }
03046 }
03047 
03048 /*
03049 ** Generate VDBE code that prepares for doing an operation that
03050 ** might change the database.
03051 **
03052 ** This routine starts a new transaction if we are not already within
03053 ** a transaction.  If we are already within a transaction, then a checkpoint
03054 ** is set if the setStatement parameter is true.  A checkpoint should
03055 ** be set for operations that might fail (due to a constraint) part of
03056 ** the way through and which will need to undo some writes without having to
03057 ** rollback the whole transaction.  For operations where all constraints
03058 ** can be checked before any changes are made to the database, it is never
03059 ** necessary to undo a write and the checkpoint should not be set.
03060 **
03061 ** Only database iDb and the temp database are made writable by this call.
03062 ** If iDb==0, then the main and temp databases are made writable.   If
03063 ** iDb==1 then only the temp database is made writable.  If iDb>1 then the
03064 ** specified auxiliary database and the temp database are made writable.
03065 */
03066 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
03067   Vdbe *v = sqlite3GetVdbe(pParse);
03068   if( v==0 ) return;
03069   sqlite3CodeVerifySchema(pParse, iDb);
03070   pParse->writeMask |= 1<<iDb;
03071   if( setStatement && pParse->nested==0 ){
03072     sqlite3VdbeAddOp(v, OP_Statement, iDb, 0);
03073   }
03074   if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
03075     sqlite3BeginWriteOperation(pParse, setStatement, 1);
03076   }
03077 }
03078 
03079 /*
03080 ** Check to see if pIndex uses the collating sequence pColl.  Return
03081 ** true if it does and false if it does not.
03082 */
03083 #ifndef SQLITE_OMIT_REINDEX
03084 static int collationMatch(const char *zColl, Index *pIndex){
03085   int i;
03086   for(i=0; i<pIndex->nColumn; i++){
03087     const char *z = pIndex->azColl[i];
03088     if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
03089       return 1;
03090     }
03091   }
03092   return 0;
03093 }
03094 #endif
03095 
03096 /*
03097 ** Recompute all indices of pTab that use the collating sequence pColl.
03098 ** If pColl==0 then recompute all indices of pTab.
03099 */
03100 #ifndef SQLITE_OMIT_REINDEX
03101 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
03102   Index *pIndex;              /* An index associated with pTab */
03103 
03104   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
03105     if( zColl==0 || collationMatch(zColl, pIndex) ){
03106       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
03107       sqlite3BeginWriteOperation(pParse, 0, iDb);
03108       sqlite3RefillIndex(pParse, pIndex, -1);
03109     }
03110   }
03111 }
03112 #endif
03113 
03114 /*
03115 ** Recompute all indices of all tables in all databases where the
03116 ** indices use the collating sequence pColl.  If pColl==0 then recompute
03117 ** all indices everywhere.
03118 */
03119 #ifndef SQLITE_OMIT_REINDEX
03120 static void reindexDatabases(Parse *pParse, char const *zColl){
03121   Db *pDb;                    /* A single database */
03122   int iDb;                    /* The database index number */
03123   sqlite3 *db = pParse->db;   /* The database connection */
03124   HashElem *k;                /* For looping over tables in pDb */
03125   Table *pTab;                /* A table in the database */
03126 
03127   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
03128     assert( pDb!=0 );
03129     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
03130       pTab = (Table*)sqliteHashData(k);
03131       reindexTable(pParse, pTab, zColl);
03132     }
03133   }
03134 }
03135 #endif
03136 
03137 /*
03138 ** Generate code for the REINDEX command.
03139 **
03140 **        REINDEX                            -- 1
03141 **        REINDEX  <collation>               -- 2
03142 **        REINDEX  ?<database>.?<tablename>  -- 3
03143 **        REINDEX  ?<database>.?<indexname>  -- 4
03144 **
03145 ** Form 1 causes all indices in all attached databases to be rebuilt.
03146 ** Form 2 rebuilds all indices in all databases that use the named
03147 ** collating function.  Forms 3 and 4 rebuild the named index or all
03148 ** indices associated with the named table.
03149 */
03150 #ifndef SQLITE_OMIT_REINDEX
03151 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
03152   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
03153   char *z;                    /* Name of a table or index */
03154   const char *zDb;            /* Name of the database */
03155   Table *pTab;                /* A table in the database */
03156   Index *pIndex;              /* An index associated with pTab */
03157   int iDb;                    /* The database index number */
03158   sqlite3 *db = pParse->db;   /* The database connection */
03159   Token *pObjName;            /* Name of the table or index to be reindexed */
03160 
03161   /* Read the database schema. If an error occurs, leave an error message
03162   ** and code in pParse and return NULL. */
03163   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
03164     return;
03165   }
03166 
03167   if( pName1==0 || pName1->z==0 ){
03168     reindexDatabases(pParse, 0);
03169     return;
03170   }else if( pName2==0 || pName2->z==0 ){
03171     assert( pName1->z );
03172     pColl = sqlite3FindCollSeq(db, ENC(db), (char*)pName1->z, pName1->n, 0);
03173     if( pColl ){
03174       char *zColl = sqliteStrNDup((const char *)pName1->z, pName1->n);
03175       if( zColl ){
03176         reindexDatabases(pParse, zColl);
03177         sqliteFree(zColl);
03178       }
03179       return;
03180     }
03181   }
03182   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
03183   if( iDb<0 ) return;
03184   z = sqlite3NameFromToken(pObjName);
03185   zDb = db->aDb[iDb].zName;
03186   pTab = sqlite3FindTable(db, z, zDb);
03187   if( pTab ){
03188     reindexTable(pParse, pTab, 0);
03189     sqliteFree(z);
03190     return;
03191   }
03192   pIndex = sqlite3FindIndex(db, z, zDb);
03193   sqliteFree(z);
03194   if( pIndex ){
03195     sqlite3BeginWriteOperation(pParse, 0, iDb);
03196     sqlite3RefillIndex(pParse, pIndex, -1);
03197     return;
03198   }
03199   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
03200 }
03201 #endif
03202 
03203 /*
03204 ** Return a dynamicly allocated KeyInfo structure that can be used
03205 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
03206 **
03207 ** If successful, a pointer to the new structure is returned. In this case
03208 ** the caller is responsible for calling sqliteFree() on the returned 
03209 ** pointer. If an error occurs (out of memory or missing collation 
03210 ** sequence), NULL is returned and the state of pParse updated to reflect
03211 ** the error.
03212 */
03213 KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
03214   int i;
03215   int nCol = pIdx->nColumn;
03216   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
03217   KeyInfo *pKey = (KeyInfo *)sqliteMalloc(nBytes);
03218 
03219   if( pKey ){
03220     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
03221     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
03222     for(i=0; i<nCol; i++){
03223       char *zColl = pIdx->azColl[i];
03224       assert( zColl );
03225       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
03226       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
03227     }
03228     pKey->nField = nCol;
03229   }
03230 
03231   if( pParse->nErr ){
03232     sqliteFree(pKey);
03233     pKey = 0;
03234   }
03235   return pKey;
03236 }
03237 
03238 
03239 /* See declaration in sqlite3.h for information */
03240 int sqlite3Preload(sqlite3* db)
03241 {
03242   Pager* pPager;
03243   Btree* pBt;
03244   int rc;
03245   int i;
03246   int dbsLoaded = 0;
03247 
03248   for (i = 0; i < db->nDb; i ++) {
03249     pBt = db->aDb[i].pBt;
03250     if (! pBt)
03251       continue;
03252     pPager = sqlite3BtreePager(pBt);
03253     if (pPager) {
03254       rc = sqlite3pager_loadall(pPager);
03255       if (rc == SQLITE_OK)
03256         dbsLoaded ++;
03257     }
03258   }
03259   if (dbsLoaded == 0)
03260     return SQLITE_ERROR;
03261   return SQLITE_OK;
03262 }