Back to index

php5  5.3.10
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 **     PRAGMA
00025 **
00026 ** $Id: build.c 195361 2005-09-07 15:11:33Z iliaa $
00027 */
00028 #include "sqliteInt.h"
00029 #include <ctype.h>
00030 
00031 /*
00032 ** This routine is called when a new SQL statement is beginning to
00033 ** be parsed.  Check to see if the schema for the database needs
00034 ** to be read from the SQLITE_MASTER and SQLITE_TEMP_MASTER tables.
00035 ** If it does, then read it.
00036 */
00037 void sqliteBeginParse(Parse *pParse, int explainFlag){
00038   sqlite *db = pParse->db;
00039   int i;
00040   pParse->explain = explainFlag;
00041   if((db->flags & SQLITE_Initialized)==0 && db->init.busy==0 ){
00042     int rc = sqliteInit(db, &pParse->zErrMsg);
00043     if( rc!=SQLITE_OK ){
00044       pParse->rc = rc;
00045       pParse->nErr++;
00046     }
00047   }
00048   for(i=0; i<db->nDb; i++){
00049     DbClearProperty(db, i, DB_Locked);
00050     if( !db->aDb[i].inTrans ){
00051       DbClearProperty(db, i, DB_Cookie);
00052     }
00053   }
00054   pParse->nVar = 0;
00055 }
00056 
00057 /*
00058 ** This routine is called after a single SQL statement has been
00059 ** parsed and we want to execute the VDBE code to implement 
00060 ** that statement.  Prior action routines should have already
00061 ** constructed VDBE code to do the work of the SQL statement.
00062 ** This routine just has to execute the VDBE code.
00063 **
00064 ** Note that if an error occurred, it might be the case that
00065 ** no VDBE code was generated.
00066 */
00067 void sqliteExec(Parse *pParse){
00068   sqlite *db = pParse->db;
00069   Vdbe *v = pParse->pVdbe;
00070 
00071   if( v==0 && (v = sqliteGetVdbe(pParse))!=0 ){
00072     sqliteVdbeAddOp(v, OP_Halt, 0, 0);
00073   }
00074   if( sqlite_malloc_failed ) return;
00075   if( v && pParse->nErr==0 ){
00076     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
00077     sqliteVdbeTrace(v, trace);
00078     sqliteVdbeMakeReady(v, pParse->nVar, pParse->explain);
00079     pParse->rc = pParse->nErr ? SQLITE_ERROR : SQLITE_DONE;
00080     pParse->colNamesSet = 0;
00081   }else if( pParse->rc==SQLITE_OK ){
00082     pParse->rc = SQLITE_ERROR;
00083   }
00084   pParse->nTab = 0;
00085   pParse->nMem = 0;
00086   pParse->nSet = 0;
00087   pParse->nAgg = 0;
00088   pParse->nVar = 0;
00089 }
00090 
00091 /*
00092 ** Locate the in-memory structure that describes 
00093 ** a particular database table given the name
00094 ** of that table and (optionally) the name of the database
00095 ** containing the table.  Return NULL if not found.
00096 **
00097 ** If zDatabase is 0, all databases are searched for the
00098 ** table and the first matching table is returned.  (No checking
00099 ** for duplicate table names is done.)  The search order is
00100 ** TEMP first, then MAIN, then any auxiliary databases added
00101 ** using the ATTACH command.
00102 **
00103 ** See also sqliteLocateTable().
00104 */
00105 Table *sqliteFindTable(sqlite *db, const char *zName, const char *zDatabase){
00106   Table *p = 0;
00107   int i;
00108   for(i=0; i<db->nDb; i++){
00109     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
00110     if( zDatabase!=0 && sqliteStrICmp(zDatabase, db->aDb[j].zName) ) continue;
00111     p = sqliteHashFind(&db->aDb[j].tblHash, zName, strlen(zName)+1);
00112     if( p ) break;
00113   }
00114   return p;
00115 }
00116 
00117 /*
00118 ** Locate the in-memory structure that describes 
00119 ** a particular database table given the name
00120 ** of that table and (optionally) the name of the database
00121 ** containing the table.  Return NULL if not found.
00122 ** Also leave an error message in pParse->zErrMsg.
00123 **
00124 ** The difference between this routine and sqliteFindTable()
00125 ** is that this routine leaves an error message in pParse->zErrMsg
00126 ** where sqliteFindTable() does not.
00127 */
00128 Table *sqliteLocateTable(Parse *pParse, const char *zName, const char *zDbase){
00129   Table *p;
00130 
00131   p = sqliteFindTable(pParse->db, zName, zDbase);
00132   if( p==0 ){
00133     if( zDbase ){
00134       sqliteErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
00135     }else if( sqliteFindTable(pParse->db, zName, 0)!=0 ){
00136       sqliteErrorMsg(pParse, "table \"%s\" is not in database \"%s\"",
00137          zName, zDbase);
00138     }else{
00139       sqliteErrorMsg(pParse, "no such table: %s", zName);
00140     }
00141   }
00142   return p;
00143 }
00144 
00145 /*
00146 ** Locate the in-memory structure that describes 
00147 ** a particular index given the name of that index
00148 ** and the name of the database that contains the index.
00149 ** Return NULL if not found.
00150 **
00151 ** If zDatabase is 0, all databases are searched for the
00152 ** table and the first matching index is returned.  (No checking
00153 ** for duplicate index names is done.)  The search order is
00154 ** TEMP first, then MAIN, then any auxiliary databases added
00155 ** using the ATTACH command.
00156 */
00157 Index *sqliteFindIndex(sqlite *db, const char *zName, const char *zDb){
00158   Index *p = 0;
00159   int i;
00160   for(i=0; i<db->nDb; i++){
00161     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
00162     if( zDb && sqliteStrICmp(zDb, db->aDb[j].zName) ) continue;
00163     p = sqliteHashFind(&db->aDb[j].idxHash, zName, strlen(zName)+1);
00164     if( p ) break;
00165   }
00166   return p;
00167 }
00168 
00169 /*
00170 ** Remove the given index from the index hash table, and free
00171 ** its memory structures.
00172 **
00173 ** The index is removed from the database hash tables but
00174 ** it is not unlinked from the Table that it indexes.
00175 ** Unlinking from the Table must be done by the calling function.
00176 */
00177 static void sqliteDeleteIndex(sqlite *db, Index *p){
00178   Index *pOld;
00179 
00180   assert( db!=0 && p->zName!=0 );
00181   pOld = sqliteHashInsert(&db->aDb[p->iDb].idxHash, p->zName,
00182                           strlen(p->zName)+1, 0);
00183   if( pOld!=0 && pOld!=p ){
00184     sqliteHashInsert(&db->aDb[p->iDb].idxHash, pOld->zName,
00185                      strlen(pOld->zName)+1, pOld);
00186   }
00187   sqliteFree(p);
00188 }
00189 
00190 /*
00191 ** Unlink the given index from its table, then remove
00192 ** the index from the index hash table and free its memory
00193 ** structures.
00194 */
00195 void sqliteUnlinkAndDeleteIndex(sqlite *db, Index *pIndex){
00196   if( pIndex->pTable->pIndex==pIndex ){
00197     pIndex->pTable->pIndex = pIndex->pNext;
00198   }else{
00199     Index *p;
00200     for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
00201     if( p && p->pNext==pIndex ){
00202       p->pNext = pIndex->pNext;
00203     }
00204   }
00205   sqliteDeleteIndex(db, pIndex);
00206 }
00207 
00208 /*
00209 ** Erase all schema information from the in-memory hash tables of
00210 ** database connection.  This routine is called to reclaim memory
00211 ** before the connection closes.  It is also called during a rollback
00212 ** if there were schema changes during the transaction.
00213 **
00214 ** If iDb<=0 then reset the internal schema tables for all database
00215 ** files.  If iDb>=2 then reset the internal schema for only the
00216 ** single file indicated.
00217 */
00218 void sqliteResetInternalSchema(sqlite *db, int iDb){
00219   HashElem *pElem;
00220   Hash temp1;
00221   Hash temp2;
00222   int i, j;
00223 
00224   assert( iDb>=0 && iDb<db->nDb );
00225   db->flags &= ~SQLITE_Initialized;
00226   for(i=iDb; i<db->nDb; i++){
00227     Db *pDb = &db->aDb[i];
00228     temp1 = pDb->tblHash;
00229     temp2 = pDb->trigHash;
00230     sqliteHashInit(&pDb->trigHash, SQLITE_HASH_STRING, 0);
00231     sqliteHashClear(&pDb->aFKey);
00232     sqliteHashClear(&pDb->idxHash);
00233     for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
00234       Trigger *pTrigger = sqliteHashData(pElem);
00235       sqliteDeleteTrigger(pTrigger);
00236     }
00237     sqliteHashClear(&temp2);
00238     sqliteHashInit(&pDb->tblHash, SQLITE_HASH_STRING, 0);
00239     for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
00240       Table *pTab = sqliteHashData(pElem);
00241       sqliteDeleteTable(db, pTab);
00242     }
00243     sqliteHashClear(&temp1);
00244     DbClearProperty(db, i, DB_SchemaLoaded);
00245     if( iDb>0 ) return;
00246   }
00247   assert( iDb==0 );
00248   db->flags &= ~SQLITE_InternChanges;
00249 
00250   /* If one or more of the auxiliary database files has been closed,
00251   ** then remove then from the auxiliary database list.  We take the
00252   ** opportunity to do this here since we have just deleted all of the
00253   ** schema hash tables and therefore do not have to make any changes
00254   ** to any of those tables.
00255   */
00256   for(i=0; i<db->nDb; i++){
00257     struct Db *pDb = &db->aDb[i];
00258     if( pDb->pBt==0 ){
00259       if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
00260       pDb->pAux = 0;
00261     }
00262   }
00263   for(i=j=2; i<db->nDb; i++){
00264     struct Db *pDb = &db->aDb[i];
00265     if( pDb->pBt==0 ){
00266       sqliteFree(pDb->zName);
00267       pDb->zName = 0;
00268       continue;
00269     }
00270     if( j<i ){
00271       db->aDb[j] = db->aDb[i];
00272     }
00273     j++;
00274   }
00275   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
00276   db->nDb = j;
00277   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
00278     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
00279     sqliteFree(db->aDb);
00280     db->aDb = db->aDbStatic;
00281   }
00282 }
00283 
00284 /*
00285 ** This routine is called whenever a rollback occurs.  If there were
00286 ** schema changes during the transaction, then we have to reset the
00287 ** internal hash tables and reload them from disk.
00288 */
00289 void sqliteRollbackInternalChanges(sqlite *db){
00290   if( db->flags & SQLITE_InternChanges ){
00291     sqliteResetInternalSchema(db, 0);
00292   }
00293 }
00294 
00295 /*
00296 ** This routine is called when a commit occurs.
00297 */
00298 void sqliteCommitInternalChanges(sqlite *db){
00299   db->aDb[0].schema_cookie = db->next_cookie;
00300   db->flags &= ~SQLITE_InternChanges;
00301 }
00302 
00303 /*
00304 ** Remove the memory data structures associated with the given
00305 ** Table.  No changes are made to disk by this routine.
00306 **
00307 ** This routine just deletes the data structure.  It does not unlink
00308 ** the table data structure from the hash table.  Nor does it remove
00309 ** foreign keys from the sqlite.aFKey hash table.  But it does destroy
00310 ** memory structures of the indices and foreign keys associated with 
00311 ** the table.
00312 **
00313 ** Indices associated with the table are unlinked from the "db"
00314 ** data structure if db!=NULL.  If db==NULL, indices attached to
00315 ** the table are deleted, but it is assumed they have already been
00316 ** unlinked.
00317 */
00318 void sqliteDeleteTable(sqlite *db, Table *pTable){
00319   int i;
00320   Index *pIndex, *pNext;
00321   FKey *pFKey, *pNextFKey;
00322 
00323   if( pTable==0 ) return;
00324 
00325   /* Delete all indices associated with this table
00326   */
00327   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
00328     pNext = pIndex->pNext;
00329     assert( pIndex->iDb==pTable->iDb || (pTable->iDb==0 && pIndex->iDb==1) );
00330     sqliteDeleteIndex(db, pIndex);
00331   }
00332 
00333   /* Delete all foreign keys associated with this table.  The keys
00334   ** should have already been unlinked from the db->aFKey hash table 
00335   */
00336   for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
00337     pNextFKey = pFKey->pNextFrom;
00338     assert( pTable->iDb<db->nDb );
00339     assert( sqliteHashFind(&db->aDb[pTable->iDb].aFKey,
00340                            pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
00341     sqliteFree(pFKey);
00342   }
00343 
00344   /* Delete the Table structure itself.
00345   */
00346   for(i=0; i<pTable->nCol; i++){
00347     sqliteFree(pTable->aCol[i].zName);
00348     sqliteFree(pTable->aCol[i].zDflt);
00349     sqliteFree(pTable->aCol[i].zType);
00350   }
00351   sqliteFree(pTable->zName);
00352   sqliteFree(pTable->aCol);
00353   sqliteSelectDelete(pTable->pSelect);
00354   sqliteFree(pTable);
00355 }
00356 
00357 /*
00358 ** Unlink the given table from the hash tables and the delete the
00359 ** table structure with all its indices and foreign keys.
00360 */
00361 static void sqliteUnlinkAndDeleteTable(sqlite *db, Table *p){
00362   Table *pOld;
00363   FKey *pF1, *pF2;
00364   int i = p->iDb;
00365   assert( db!=0 );
00366   pOld = sqliteHashInsert(&db->aDb[i].tblHash, p->zName, strlen(p->zName)+1, 0);
00367   assert( pOld==0 || pOld==p );
00368   for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
00369     int nTo = strlen(pF1->zTo) + 1;
00370     pF2 = sqliteHashFind(&db->aDb[i].aFKey, pF1->zTo, nTo);
00371     if( pF2==pF1 ){
00372       sqliteHashInsert(&db->aDb[i].aFKey, pF1->zTo, nTo, pF1->pNextTo);
00373     }else{
00374       while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
00375       if( pF2 ){
00376         pF2->pNextTo = pF1->pNextTo;
00377       }
00378     }
00379   }
00380   sqliteDeleteTable(db, p);
00381 }
00382 
00383 /*
00384 ** Construct the name of a user table or index from a token.
00385 **
00386 ** Space to hold the name is obtained from sqliteMalloc() and must
00387 ** be freed by the calling function.
00388 */
00389 char *sqliteTableNameFromToken(Token *pName){
00390   char *zName = sqliteStrNDup(pName->z, pName->n);
00391   sqliteDequote(zName);
00392   return zName;
00393 }
00394 
00395 /*
00396 ** Generate code to open the appropriate master table.  The table
00397 ** opened will be SQLITE_MASTER for persistent tables and 
00398 ** SQLITE_TEMP_MASTER for temporary tables.  The table is opened
00399 ** on cursor 0.
00400 */
00401 void sqliteOpenMasterTable(Vdbe *v, int isTemp){
00402   sqliteVdbeAddOp(v, OP_Integer, isTemp, 0);
00403   sqliteVdbeAddOp(v, OP_OpenWrite, 0, 2);
00404 }
00405 
00406 /*
00407 ** Begin constructing a new table representation in memory.  This is
00408 ** the first of several action routines that get called in response
00409 ** to a CREATE TABLE statement.  In particular, this routine is called
00410 ** after seeing tokens "CREATE" and "TABLE" and the table name.  The
00411 ** pStart token is the CREATE and pName is the table name.  The isTemp
00412 ** flag is true if the table should be stored in the auxiliary database
00413 ** file instead of in the main database file.  This is normally the case
00414 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
00415 ** CREATE and TABLE.
00416 **
00417 ** The new table record is initialized and put in pParse->pNewTable.
00418 ** As more of the CREATE TABLE statement is parsed, additional action
00419 ** routines will be called to add more information to this record.
00420 ** At the end of the CREATE TABLE statement, the sqliteEndTable() routine
00421 ** is called to complete the construction of the new table record.
00422 */
00423 void sqliteStartTable(
00424   Parse *pParse,   /* Parser context */
00425   Token *pStart,   /* The "CREATE" token */
00426   Token *pName,    /* Name of table or view to create */
00427   int isTemp,      /* True if this is a TEMP table */
00428   int isView       /* True if this is a VIEW */
00429 ){
00430   Table *pTable;
00431   Index *pIdx;
00432   char *zName;
00433   sqlite *db = pParse->db;
00434   Vdbe *v;
00435   int iDb;
00436 
00437   pParse->sFirstToken = *pStart;
00438   zName = sqliteTableNameFromToken(pName);
00439   if( zName==0 ) return;
00440   if( db->init.iDb==1 ) isTemp = 1;
00441 #ifndef SQLITE_OMIT_AUTHORIZATION
00442   assert( (isTemp & 1)==isTemp );
00443   {
00444     int code;
00445     char *zDb = isTemp ? "temp" : "main";
00446     if( sqliteAuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
00447       sqliteFree(zName);
00448       return;
00449     }
00450     if( isView ){
00451       if( isTemp ){
00452         code = SQLITE_CREATE_TEMP_VIEW;
00453       }else{
00454         code = SQLITE_CREATE_VIEW;
00455       }
00456     }else{
00457       if( isTemp ){
00458         code = SQLITE_CREATE_TEMP_TABLE;
00459       }else{
00460         code = SQLITE_CREATE_TABLE;
00461       }
00462     }
00463     if( sqliteAuthCheck(pParse, code, zName, 0, zDb) ){
00464       sqliteFree(zName);
00465       return;
00466     }
00467   }
00468 #endif
00469  
00470 
00471   /* Before trying to create a temporary table, make sure the Btree for
00472   ** holding temporary tables is open.
00473   */
00474   if( isTemp && db->aDb[1].pBt==0 && !pParse->explain ){
00475     int rc = sqliteBtreeFactory(db, 0, 0, MAX_PAGES, &db->aDb[1].pBt);
00476     if( rc!=SQLITE_OK ){
00477       sqliteErrorMsg(pParse, "unable to open a temporary database "
00478         "file for storing temporary tables");
00479       pParse->nErr++;
00480       return;
00481     }
00482     if( db->flags & SQLITE_InTrans ){
00483       rc = sqliteBtreeBeginTrans(db->aDb[1].pBt);
00484       if( rc!=SQLITE_OK ){
00485         sqliteErrorMsg(pParse, "unable to get a write lock on "
00486           "the temporary database file");
00487         return;
00488       }
00489     }
00490   }
00491 
00492   /* Make sure the new table name does not collide with an existing
00493   ** index or table name.  Issue an error message if it does.
00494   **
00495   ** If we are re-reading the sqlite_master table because of a schema
00496   ** change and a new permanent table is found whose name collides with
00497   ** an existing temporary table, that is not an error.
00498   */
00499   pTable = sqliteFindTable(db, zName, 0);
00500   iDb = isTemp ? 1 : db->init.iDb;
00501   if( pTable!=0 && (pTable->iDb==iDb || !db->init.busy) ){
00502     sqliteErrorMsg(pParse, "table %T already exists", pName);
00503     sqliteFree(zName);
00504     return;
00505   }
00506   if( (pIdx = sqliteFindIndex(db, zName, 0))!=0 &&
00507           (pIdx->iDb==0 || !db->init.busy) ){
00508     sqliteErrorMsg(pParse, "there is already an index named %s", zName);
00509     sqliteFree(zName);
00510     return;
00511   }
00512   pTable = sqliteMalloc( sizeof(Table) );
00513   if( pTable==0 ){
00514     sqliteFree(zName);
00515     return;
00516   }
00517   pTable->zName = zName;
00518   pTable->nCol = 0;
00519   pTable->aCol = 0;
00520   pTable->iPKey = -1;
00521   pTable->pIndex = 0;
00522   pTable->iDb = iDb;
00523   if( pParse->pNewTable ) sqliteDeleteTable(db, pParse->pNewTable);
00524   pParse->pNewTable = pTable;
00525 
00526   /* Begin generating the code that will insert the table record into
00527   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
00528   ** and allocate the record number for the table entry now.  Before any
00529   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
00530   ** indices to be created and the table record must come before the 
00531   ** indices.  Hence, the record number for the table must be allocated
00532   ** now.
00533   */
00534   if( !db->init.busy && (v = sqliteGetVdbe(pParse))!=0 ){
00535     sqliteBeginWriteOperation(pParse, 0, isTemp);
00536     if( !isTemp ){
00537       sqliteVdbeAddOp(v, OP_Integer, db->file_format, 0);
00538       sqliteVdbeAddOp(v, OP_SetCookie, 0, 1);
00539     }
00540     sqliteOpenMasterTable(v, isTemp);
00541     sqliteVdbeAddOp(v, OP_NewRecno, 0, 0);
00542     sqliteVdbeAddOp(v, OP_Dup, 0, 0);
00543     sqliteVdbeAddOp(v, OP_String, 0, 0);
00544     sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0);
00545   }
00546 }
00547 
00548 /*
00549 ** Add a new column to the table currently being constructed.
00550 **
00551 ** The parser calls this routine once for each column declaration
00552 ** in a CREATE TABLE statement.  sqliteStartTable() gets called
00553 ** first to get things going.  Then this routine is called for each
00554 ** column.
00555 */
00556 void sqliteAddColumn(Parse *pParse, Token *pName){
00557   Table *p;
00558   int i;
00559   char *z = 0;
00560   Column *pCol;
00561   if( (p = pParse->pNewTable)==0 ) return;
00562   sqliteSetNString(&z, pName->z, pName->n, 0);
00563   if( z==0 ) return;
00564   sqliteDequote(z);
00565   for(i=0; i<p->nCol; i++){
00566     if( sqliteStrICmp(z, p->aCol[i].zName)==0 ){
00567       sqliteErrorMsg(pParse, "duplicate column name: %s", z);
00568       sqliteFree(z);
00569       return;
00570     }
00571   }
00572   if( (p->nCol & 0x7)==0 ){
00573     Column *aNew;
00574     aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
00575     if( aNew==0 ) return;
00576     p->aCol = aNew;
00577   }
00578   pCol = &p->aCol[p->nCol];
00579   memset(pCol, 0, sizeof(p->aCol[0]));
00580   pCol->zName = z;
00581   pCol->sortOrder = SQLITE_SO_NUM;
00582   p->nCol++;
00583 }
00584 
00585 /*
00586 ** This routine is called by the parser while in the middle of
00587 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
00588 ** been seen on a column.  This routine sets the notNull flag on
00589 ** the column currently under construction.
00590 */
00591 void sqliteAddNotNull(Parse *pParse, int onError){
00592   Table *p;
00593   int i;
00594   if( (p = pParse->pNewTable)==0 ) return;
00595   i = p->nCol-1;
00596   if( i>=0 ) p->aCol[i].notNull = onError;
00597 }
00598 
00599 /*
00600 ** This routine is called by the parser while in the middle of
00601 ** parsing a CREATE TABLE statement.  The pFirst token is the first
00602 ** token in the sequence of tokens that describe the type of the
00603 ** column currently under construction.   pLast is the last token
00604 ** in the sequence.  Use this information to construct a string
00605 ** that contains the typename of the column and store that string
00606 ** in zType.
00607 */ 
00608 void sqliteAddColumnType(Parse *pParse, Token *pFirst, Token *pLast){
00609   Table *p;
00610   int i, j;
00611   int n;
00612   char *z, **pz;
00613   Column *pCol;
00614   if( (p = pParse->pNewTable)==0 ) return;
00615   i = p->nCol-1;
00616   if( i<0 ) return;
00617   pCol = &p->aCol[i];
00618   pz = &pCol->zType;
00619   n = pLast->n + Addr(pLast->z) - Addr(pFirst->z);
00620   sqliteSetNString(pz, pFirst->z, n, 0);
00621   z = *pz;
00622   if( z==0 ) return;
00623   for(i=j=0; z[i]; i++){
00624     int c = z[i];
00625     if( isspace(c) ) continue;
00626     z[j++] = c;
00627   }
00628   z[j] = 0;
00629   if( pParse->db->file_format>=4 ){
00630     pCol->sortOrder = sqliteCollateType(z, n);
00631   }else{
00632     pCol->sortOrder = SQLITE_SO_NUM;
00633   }
00634 }
00635 
00636 /*
00637 ** The given token is the default value for the last column added to
00638 ** the table currently under construction.  If "minusFlag" is true, it
00639 ** means the value token was preceded by a minus sign.
00640 **
00641 ** This routine is called by the parser while in the middle of
00642 ** parsing a CREATE TABLE statement.
00643 */
00644 void sqliteAddDefaultValue(Parse *pParse, Token *pVal, int minusFlag){
00645   Table *p;
00646   int i;
00647   char **pz;
00648   if( (p = pParse->pNewTable)==0 ) return;
00649   i = p->nCol-1;
00650   if( i<0 ) return;
00651   pz = &p->aCol[i].zDflt;
00652   if( minusFlag ){
00653     sqliteSetNString(pz, "-", 1, pVal->z, pVal->n, 0);
00654   }else{
00655     sqliteSetNString(pz, pVal->z, pVal->n, 0);
00656   }
00657   sqliteDequote(*pz);
00658 }
00659 
00660 /*
00661 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
00662 ** of columns that form the primary key.  If pList is NULL, then the
00663 ** most recently added column of the table is the primary key.
00664 **
00665 ** A table can have at most one primary key.  If the table already has
00666 ** a primary key (and this is the second primary key) then create an
00667 ** error.
00668 **
00669 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
00670 ** then we will try to use that column as the row id.  (Exception:
00671 ** For backwards compatibility with older databases, do not do this
00672 ** if the file format version number is less than 1.)  Set the Table.iPKey
00673 ** field of the table under construction to be the index of the
00674 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
00675 ** no INTEGER PRIMARY KEY.
00676 **
00677 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
00678 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
00679 */
00680 void sqliteAddPrimaryKey(Parse *pParse, IdList *pList, int onError){
00681   Table *pTab = pParse->pNewTable;
00682   char *zType = 0;
00683   int iCol = -1, i;
00684   if( pTab==0 ) goto primary_key_exit;
00685   if( pTab->hasPrimKey ){
00686     sqliteErrorMsg(pParse, 
00687       "table \"%s\" has more than one primary key", pTab->zName);
00688     goto primary_key_exit;
00689   }
00690   pTab->hasPrimKey = 1;
00691   if( pList==0 ){
00692     iCol = pTab->nCol - 1;
00693     pTab->aCol[iCol].isPrimKey = 1;
00694   }else{
00695     for(i=0; i<pList->nId; i++){
00696       for(iCol=0; iCol<pTab->nCol; iCol++){
00697         if( sqliteStrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ) break;
00698       }
00699       if( iCol<pTab->nCol ) pTab->aCol[iCol].isPrimKey = 1;
00700     }
00701     if( pList->nId>1 ) iCol = -1;
00702   }
00703   if( iCol>=0 && iCol<pTab->nCol ){
00704     zType = pTab->aCol[iCol].zType;
00705   }
00706   if( pParse->db->file_format>=1 && 
00707            zType && sqliteStrICmp(zType, "INTEGER")==0 ){
00708     pTab->iPKey = iCol;
00709     pTab->keyConf = onError;
00710   }else{
00711     sqliteCreateIndex(pParse, 0, 0, pList, onError, 0, 0);
00712     pList = 0;
00713   }
00714 
00715 primary_key_exit:
00716   sqliteIdListDelete(pList);
00717   return;
00718 }
00719 
00720 /*
00721 ** Return the appropriate collating type given a type name.
00722 **
00723 ** The collation type is text (SQLITE_SO_TEXT) if the type
00724 ** name contains the character stream "text" or "blob" or
00725 ** "clob".  Any other type name is collated as numeric
00726 ** (SQLITE_SO_NUM).
00727 */
00728 int sqliteCollateType(const char *zType, int nType){
00729   int i;
00730   for(i=0; i<nType-3; i++){
00731     int c = *(zType++) | 0x60;
00732     if( (c=='b' || c=='c') && sqliteStrNICmp(zType, "lob", 3)==0 ){
00733       return SQLITE_SO_TEXT;
00734     }
00735     if( c=='c' && sqliteStrNICmp(zType, "har", 3)==0 ){
00736       return SQLITE_SO_TEXT;
00737     }
00738     if( c=='t' && sqliteStrNICmp(zType, "ext", 3)==0 ){
00739       return SQLITE_SO_TEXT;
00740     }
00741   }
00742   return SQLITE_SO_NUM;
00743 }
00744 
00745 /*
00746 ** This routine is called by the parser while in the middle of
00747 ** parsing a CREATE TABLE statement.  A "COLLATE" clause has
00748 ** been seen on a column.  This routine sets the Column.sortOrder on
00749 ** the column currently under construction.
00750 */
00751 void sqliteAddCollateType(Parse *pParse, int collType){
00752   Table *p;
00753   int i;
00754   if( (p = pParse->pNewTable)==0 ) return;
00755   i = p->nCol-1;
00756   if( i>=0 ) p->aCol[i].sortOrder = collType;
00757 }
00758 
00759 /*
00760 ** Come up with a new random value for the schema cookie.  Make sure
00761 ** the new value is different from the old.
00762 **
00763 ** The schema cookie is used to determine when the schema for the
00764 ** database changes.  After each schema change, the cookie value
00765 ** changes.  When a process first reads the schema it records the
00766 ** cookie.  Thereafter, whenever it goes to access the database,
00767 ** it checks the cookie to make sure the schema has not changed
00768 ** since it was last read.
00769 **
00770 ** This plan is not completely bullet-proof.  It is possible for
00771 ** the schema to change multiple times and for the cookie to be
00772 ** set back to prior value.  But schema changes are infrequent
00773 ** and the probability of hitting the same cookie value is only
00774 ** 1 chance in 2^32.  So we're safe enough.
00775 */
00776 void sqliteChangeCookie(sqlite *db, Vdbe *v){
00777   if( db->next_cookie==db->aDb[0].schema_cookie ){
00778     unsigned char r;
00779     sqliteRandomness(1, &r);
00780     db->next_cookie = db->aDb[0].schema_cookie + r + 1;
00781     db->flags |= SQLITE_InternChanges;
00782     sqliteVdbeAddOp(v, OP_Integer, db->next_cookie, 0);
00783     sqliteVdbeAddOp(v, OP_SetCookie, 0, 0);
00784   }
00785 }
00786 
00787 /*
00788 ** Measure the number of characters needed to output the given
00789 ** identifier.  The number returned includes any quotes used
00790 ** but does not include the null terminator.
00791 */
00792 static int identLength(const char *z){
00793   int n;
00794   int needQuote = 0;
00795   for(n=0; *z; n++, z++){
00796     if( *z=='\'' ){ n++; needQuote=1; }
00797   }
00798   return n + needQuote*2;
00799 }
00800 
00801 /*
00802 ** Write an identifier onto the end of the given string.  Add
00803 ** quote characters as needed.
00804 */
00805 static void identPut(char *z, int *pIdx, char *zIdent){
00806   int i, j, needQuote;
00807   i = *pIdx;
00808   for(j=0; zIdent[j]; j++){
00809     if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
00810   }
00811   needQuote =  zIdent[j]!=0 || isdigit(zIdent[0])
00812                   || sqliteKeywordCode(zIdent, j)!=TK_ID;
00813   if( needQuote ) z[i++] = '\'';
00814   for(j=0; zIdent[j]; j++){
00815     z[i++] = zIdent[j];
00816     if( zIdent[j]=='\'' ) z[i++] = '\'';
00817   }
00818   if( needQuote ) z[i++] = '\'';
00819   z[i] = 0;
00820   *pIdx = i;
00821 }
00822 
00823 /*
00824 ** Generate a CREATE TABLE statement appropriate for the given
00825 ** table.  Memory to hold the text of the statement is obtained
00826 ** from sqliteMalloc() and must be freed by the calling function.
00827 */
00828 static char *createTableStmt(Table *p){
00829   int i, k, n;
00830   char *zStmt;
00831   char *zSep, *zSep2, *zEnd;
00832   n = 0;
00833   for(i=0; i<p->nCol; i++){
00834     n += identLength(p->aCol[i].zName);
00835   }
00836   n += identLength(p->zName);
00837   if( n<40 ){
00838     zSep = "";
00839     zSep2 = ",";
00840     zEnd = ")";
00841   }else{
00842     zSep = "\n  ";
00843     zSep2 = ",\n  ";
00844     zEnd = "\n)";
00845   }
00846   n += 35 + 6*p->nCol;
00847   zStmt = sqliteMallocRaw( n );
00848   if( zStmt==0 ) return 0;
00849   strcpy(zStmt, p->iDb==1 ? "CREATE TEMP TABLE " : "CREATE TABLE ");
00850   k = strlen(zStmt);
00851   identPut(zStmt, &k, p->zName);
00852   zStmt[k++] = '(';
00853   for(i=0; i<p->nCol; i++){
00854     strcpy(&zStmt[k], zSep);
00855     k += strlen(&zStmt[k]);
00856     zSep = zSep2;
00857     identPut(zStmt, &k, p->aCol[i].zName);
00858   }
00859   strcpy(&zStmt[k], zEnd);
00860   return zStmt;
00861 }
00862 
00863 /*
00864 ** This routine is called to report the final ")" that terminates
00865 ** a CREATE TABLE statement.
00866 **
00867 ** The table structure that other action routines have been building
00868 ** is added to the internal hash tables, assuming no errors have
00869 ** occurred.
00870 **
00871 ** An entry for the table is made in the master table on disk, unless
00872 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
00873 ** it means we are reading the sqlite_master table because we just
00874 ** connected to the database or because the sqlite_master table has
00875 ** recently changes, so the entry for this table already exists in
00876 ** the sqlite_master table.  We do not want to create it again.
00877 **
00878 ** If the pSelect argument is not NULL, it means that this routine
00879 ** was called to create a table generated from a 
00880 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
00881 ** the new table will match the result set of the SELECT.
00882 */
00883 void sqliteEndTable(Parse *pParse, Token *pEnd, Select *pSelect){
00884   Table *p;
00885   sqlite *db = pParse->db;
00886 
00887   if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite_malloc_failed ) return;
00888   p = pParse->pNewTable;
00889   if( p==0 ) return;
00890 
00891   /* If the table is generated from a SELECT, then construct the
00892   ** list of columns and the text of the table.
00893   */
00894   if( pSelect ){
00895     Table *pSelTab = sqliteResultSetOfSelect(pParse, 0, pSelect);
00896     if( pSelTab==0 ) return;
00897     assert( p->aCol==0 );
00898     p->nCol = pSelTab->nCol;
00899     p->aCol = pSelTab->aCol;
00900     pSelTab->nCol = 0;
00901     pSelTab->aCol = 0;
00902     sqliteDeleteTable(0, pSelTab);
00903   }
00904 
00905   /* If the db->init.busy is 1 it means we are reading the SQL off the
00906   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
00907   ** So do not write to the disk again.  Extract the root page number
00908   ** for the table from the db->init.newTnum field.  (The page number
00909   ** should have been put there by the sqliteOpenCb routine.)
00910   */
00911   if( db->init.busy ){
00912     p->tnum = db->init.newTnum;
00913   }
00914 
00915   /* If not initializing, then create a record for the new table
00916   ** in the SQLITE_MASTER table of the database.  The record number
00917   ** for the new table entry should already be on the stack.
00918   **
00919   ** If this is a TEMPORARY table, write the entry into the auxiliary
00920   ** file instead of into the main database file.
00921   */
00922   if( !db->init.busy ){
00923     int n;
00924     Vdbe *v;
00925 
00926     v = sqliteGetVdbe(pParse);
00927     if( v==0 ) return;
00928     if( p->pSelect==0 ){
00929       /* A regular table */
00930       sqliteVdbeOp3(v, OP_CreateTable, 0, p->iDb, (char*)&p->tnum, P3_POINTER);
00931     }else{
00932       /* A view */
00933       sqliteVdbeAddOp(v, OP_Integer, 0, 0);
00934     }
00935     p->tnum = 0;
00936     sqliteVdbeAddOp(v, OP_Pull, 1, 0);
00937     sqliteVdbeOp3(v, OP_String, 0, 0, p->pSelect==0?"table":"view", P3_STATIC);
00938     sqliteVdbeOp3(v, OP_String, 0, 0, p->zName, 0);
00939     sqliteVdbeOp3(v, OP_String, 0, 0, p->zName, 0);
00940     sqliteVdbeAddOp(v, OP_Dup, 4, 0);
00941     sqliteVdbeAddOp(v, OP_String, 0, 0);
00942     if( pSelect ){
00943       char *z = createTableStmt(p);
00944       n = z ? strlen(z) : 0;
00945       sqliteVdbeChangeP3(v, -1, z, n);
00946       sqliteFree(z);
00947     }else{
00948       assert( pEnd!=0 );
00949       n = Addr(pEnd->z) - Addr(pParse->sFirstToken.z) + 1;
00950       sqliteVdbeChangeP3(v, -1, pParse->sFirstToken.z, n);
00951     }
00952     sqliteVdbeAddOp(v, OP_MakeRecord, 5, 0);
00953     sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0);
00954     if( !p->iDb ){
00955       sqliteChangeCookie(db, v);
00956     }
00957     sqliteVdbeAddOp(v, OP_Close, 0, 0);
00958     if( pSelect ){
00959       sqliteVdbeAddOp(v, OP_Integer, p->iDb, 0);
00960       sqliteVdbeAddOp(v, OP_OpenWrite, 1, 0);
00961       pParse->nTab = 2;
00962       sqliteSelect(pParse, pSelect, SRT_Table, 1, 0, 0, 0);
00963     }
00964     sqliteEndWriteOperation(pParse);
00965   }
00966 
00967   /* Add the table to the in-memory representation of the database.
00968   */
00969   if( pParse->explain==0 && pParse->nErr==0 ){
00970     Table *pOld;
00971     FKey *pFKey;
00972     pOld = sqliteHashInsert(&db->aDb[p->iDb].tblHash, 
00973                             p->zName, strlen(p->zName)+1, p);
00974     if( pOld ){
00975       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
00976       return;
00977     }
00978     for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
00979       int nTo = strlen(pFKey->zTo) + 1;
00980       pFKey->pNextTo = sqliteHashFind(&db->aDb[p->iDb].aFKey, pFKey->zTo, nTo);
00981       sqliteHashInsert(&db->aDb[p->iDb].aFKey, pFKey->zTo, nTo, pFKey);
00982     }
00983     pParse->pNewTable = 0;
00984     db->nTable++;
00985     db->flags |= SQLITE_InternChanges;
00986   }
00987 }
00988 
00989 /*
00990 ** The parser calls this routine in order to create a new VIEW
00991 */
00992 void sqliteCreateView(
00993   Parse *pParse,     /* The parsing context */
00994   Token *pBegin,     /* The CREATE token that begins the statement */
00995   Token *pName,      /* The token that holds the name of the view */
00996   Select *pSelect,   /* A SELECT statement that will become the new view */
00997   int isTemp         /* TRUE for a TEMPORARY view */
00998 ){
00999   Table *p;
01000   int n;
01001   const char *z;
01002   Token sEnd;
01003   DbFixer sFix;
01004 
01005   sqliteStartTable(pParse, pBegin, pName, isTemp, 1);
01006   p = pParse->pNewTable;
01007   if( p==0 || pParse->nErr ){
01008     sqliteSelectDelete(pSelect);
01009     return;
01010   }
01011   if( sqliteFixInit(&sFix, pParse, p->iDb, "view", pName)
01012     && sqliteFixSelect(&sFix, pSelect)
01013   ){
01014     sqliteSelectDelete(pSelect);
01015     return;
01016   }
01017 
01018   /* Make a copy of the entire SELECT statement that defines the view.
01019   ** This will force all the Expr.token.z values to be dynamically
01020   ** allocated rather than point to the input string - which means that
01021   ** they will persist after the current sqlite_exec() call returns.
01022   */
01023   p->pSelect = sqliteSelectDup(pSelect);
01024   sqliteSelectDelete(pSelect);
01025   if( !pParse->db->init.busy ){
01026     sqliteViewGetColumnNames(pParse, p);
01027   }
01028 
01029   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
01030   ** the end.
01031   */
01032   sEnd = pParse->sLastToken;
01033   if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
01034     sEnd.z += sEnd.n;
01035   }
01036   sEnd.n = 0;
01037   n = sEnd.z - pBegin->z;
01038   z = pBegin->z;
01039   while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
01040   sEnd.z = &z[n-1];
01041   sEnd.n = 1;
01042 
01043   /* Use sqliteEndTable() to add the view to the SQLITE_MASTER table */
01044   sqliteEndTable(pParse, &sEnd, 0);
01045   return;
01046 }
01047 
01048 /*
01049 ** The Table structure pTable is really a VIEW.  Fill in the names of
01050 ** the columns of the view in the pTable structure.  Return the number
01051 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
01052 */
01053 int sqliteViewGetColumnNames(Parse *pParse, Table *pTable){
01054   ExprList *pEList;
01055   Select *pSel;
01056   Table *pSelTab;
01057   int nErr = 0;
01058 
01059   assert( pTable );
01060 
01061   /* A positive nCol means the columns names for this view are
01062   ** already known.
01063   */
01064   if( pTable->nCol>0 ) return 0;
01065 
01066   /* A negative nCol is a special marker meaning that we are currently
01067   ** trying to compute the column names.  If we enter this routine with
01068   ** a negative nCol, it means two or more views form a loop, like this:
01069   **
01070   **     CREATE VIEW one AS SELECT * FROM two;
01071   **     CREATE VIEW two AS SELECT * FROM one;
01072   **
01073   ** Actually, this error is caught previously and so the following test
01074   ** should always fail.  But we will leave it in place just to be safe.
01075   */
01076   if( pTable->nCol<0 ){
01077     sqliteErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
01078     return 1;
01079   }
01080 
01081   /* If we get this far, it means we need to compute the table names.
01082   */
01083   assert( pTable->pSelect ); /* If nCol==0, then pTable must be a VIEW */
01084   pSel = pTable->pSelect;
01085 
01086   /* Note that the call to sqliteResultSetOfSelect() will expand any
01087   ** "*" elements in this list.  But we will need to restore the list
01088   ** back to its original configuration afterwards, so we save a copy of
01089   ** the original in pEList.
01090   */
01091   pEList = pSel->pEList;
01092   pSel->pEList = sqliteExprListDup(pEList);
01093   if( pSel->pEList==0 ){
01094     pSel->pEList = pEList;
01095     return 1;  /* Malloc failed */
01096   }
01097   pTable->nCol = -1;
01098   pSelTab = sqliteResultSetOfSelect(pParse, 0, pSel);
01099   if( pSelTab ){
01100     assert( pTable->aCol==0 );
01101     pTable->nCol = pSelTab->nCol;
01102     pTable->aCol = pSelTab->aCol;
01103     pSelTab->nCol = 0;
01104     pSelTab->aCol = 0;
01105     sqliteDeleteTable(0, pSelTab);
01106     DbSetProperty(pParse->db, pTable->iDb, DB_UnresetViews);
01107   }else{
01108     pTable->nCol = 0;
01109     nErr++;
01110   }
01111   sqliteSelectUnbind(pSel);
01112   sqliteExprListDelete(pSel->pEList);
01113   pSel->pEList = pEList;
01114   return nErr;  
01115 }
01116 
01117 /*
01118 ** Clear the column names from the VIEW pTable.
01119 **
01120 ** This routine is called whenever any other table or view is modified.
01121 ** The view passed into this routine might depend directly or indirectly
01122 ** on the modified or deleted table so we need to clear the old column
01123 ** names so that they will be recomputed.
01124 */
01125 static void sqliteViewResetColumnNames(Table *pTable){
01126   int i;
01127   Column *pCol;
01128   assert( pTable!=0 && pTable->pSelect!=0 );
01129   for(i=0, pCol=pTable->aCol; i<pTable->nCol; i++, pCol++){
01130     sqliteFree(pCol->zName);
01131     sqliteFree(pCol->zDflt);
01132     sqliteFree(pCol->zType);
01133   }
01134   sqliteFree(pTable->aCol);
01135   pTable->aCol = 0;
01136   pTable->nCol = 0;
01137 }
01138 
01139 /*
01140 ** Clear the column names from every VIEW in database idx.
01141 */
01142 static void sqliteViewResetAll(sqlite *db, int idx){
01143   HashElem *i;
01144   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
01145   for(i=sqliteHashFirst(&db->aDb[idx].tblHash); i; i=sqliteHashNext(i)){
01146     Table *pTab = sqliteHashData(i);
01147     if( pTab->pSelect ){
01148       sqliteViewResetColumnNames(pTab);
01149     }
01150   }
01151   DbClearProperty(db, idx, DB_UnresetViews);
01152 }
01153 
01154 /*
01155 ** Given a token, look up a table with that name.  If not found, leave
01156 ** an error for the parser to find and return NULL.
01157 */
01158 Table *sqliteTableFromToken(Parse *pParse, Token *pTok){
01159   char *zName;
01160   Table *pTab;
01161   zName = sqliteTableNameFromToken(pTok);
01162   if( zName==0 ) return 0;
01163   pTab = sqliteFindTable(pParse->db, zName, 0);
01164   sqliteFree(zName);
01165   if( pTab==0 ){
01166     sqliteErrorMsg(pParse, "no such table: %T", pTok);
01167   }
01168   return pTab;
01169 }
01170 
01171 /*
01172 ** This routine is called to do the work of a DROP TABLE statement.
01173 ** pName is the name of the table to be dropped.
01174 */
01175 void sqliteDropTable(Parse *pParse, Token *pName, int isView){
01176   Table *pTable;
01177   Vdbe *v;
01178   int base;
01179   sqlite *db = pParse->db;
01180   int iDb;
01181 
01182   if( pParse->nErr || sqlite_malloc_failed ) return;
01183   pTable = sqliteTableFromToken(pParse, pName);
01184   if( pTable==0 ) return;
01185   iDb = pTable->iDb;
01186   assert( iDb>=0 && iDb<db->nDb );
01187 #ifndef SQLITE_OMIT_AUTHORIZATION
01188   {
01189     int code;
01190     const char *zTab = SCHEMA_TABLE(pTable->iDb);
01191     const char *zDb = db->aDb[pTable->iDb].zName;
01192     if( sqliteAuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
01193       return;
01194     }
01195     if( isView ){
01196       if( iDb==1 ){
01197         code = SQLITE_DROP_TEMP_VIEW;
01198       }else{
01199         code = SQLITE_DROP_VIEW;
01200       }
01201     }else{
01202       if( iDb==1 ){
01203         code = SQLITE_DROP_TEMP_TABLE;
01204       }else{
01205         code = SQLITE_DROP_TABLE;
01206       }
01207     }
01208     if( sqliteAuthCheck(pParse, code, pTable->zName, 0, zDb) ){
01209       return;
01210     }
01211     if( sqliteAuthCheck(pParse, SQLITE_DELETE, pTable->zName, 0, zDb) ){
01212       return;
01213     }
01214   }
01215 #endif
01216   if( pTable->readOnly ){
01217     sqliteErrorMsg(pParse, "table %s may not be dropped", pTable->zName);
01218     pParse->nErr++;
01219     return;
01220   }
01221   if( isView && pTable->pSelect==0 ){
01222     sqliteErrorMsg(pParse, "use DROP TABLE to delete table %s", pTable->zName);
01223     return;
01224   }
01225   if( !isView && pTable->pSelect ){
01226     sqliteErrorMsg(pParse, "use DROP VIEW to delete view %s", pTable->zName);
01227     return;
01228   }
01229 
01230   /* Generate code to remove the table from the master table
01231   ** on disk.
01232   */
01233   v = sqliteGetVdbe(pParse);
01234   if( v ){
01235     static VdbeOpList dropTable[] = {
01236       { OP_Rewind,     0, ADDR(8),  0},
01237       { OP_String,     0, 0,        0}, /* 1 */
01238       { OP_MemStore,   1, 1,        0},
01239       { OP_MemLoad,    1, 0,        0}, /* 3 */
01240       { OP_Column,     0, 2,        0},
01241       { OP_Ne,         0, ADDR(7),  0},
01242       { OP_Delete,     0, 0,        0},
01243       { OP_Next,       0, ADDR(3),  0}, /* 7 */
01244     };
01245     Index *pIdx;
01246     Trigger *pTrigger;
01247     sqliteBeginWriteOperation(pParse, 0, pTable->iDb);
01248 
01249     /* Drop all triggers associated with the table being dropped */
01250     pTrigger = pTable->pTrigger;
01251     while( pTrigger ){
01252       assert( pTrigger->iDb==pTable->iDb || pTrigger->iDb==1 );
01253       sqliteDropTriggerPtr(pParse, pTrigger, 1);
01254       if( pParse->explain ){
01255         pTrigger = pTrigger->pNext;
01256       }else{
01257         pTrigger = pTable->pTrigger;
01258       }
01259     }
01260 
01261     /* Drop all SQLITE_MASTER entries that refer to the table */
01262     sqliteOpenMasterTable(v, pTable->iDb);
01263     base = sqliteVdbeAddOpList(v, ArraySize(dropTable), dropTable);
01264     sqliteVdbeChangeP3(v, base+1, pTable->zName, 0);
01265 
01266     /* Drop all SQLITE_TEMP_MASTER entries that refer to the table */
01267     if( pTable->iDb!=1 ){
01268       sqliteOpenMasterTable(v, 1);
01269       base = sqliteVdbeAddOpList(v, ArraySize(dropTable), dropTable);
01270       sqliteVdbeChangeP3(v, base+1, pTable->zName, 0);
01271     }
01272 
01273     if( pTable->iDb==0 ){
01274       sqliteChangeCookie(db, v);
01275     }
01276     sqliteVdbeAddOp(v, OP_Close, 0, 0);
01277     if( !isView ){
01278       sqliteVdbeAddOp(v, OP_Destroy, pTable->tnum, pTable->iDb);
01279       for(pIdx=pTable->pIndex; pIdx; pIdx=pIdx->pNext){
01280         sqliteVdbeAddOp(v, OP_Destroy, pIdx->tnum, pIdx->iDb);
01281       }
01282     }
01283     sqliteEndWriteOperation(pParse);
01284   }
01285 
01286   /* Delete the in-memory description of the table.
01287   **
01288   ** Exception: if the SQL statement began with the EXPLAIN keyword,
01289   ** then no changes should be made.
01290   */
01291   if( !pParse->explain ){
01292     sqliteUnlinkAndDeleteTable(db, pTable);
01293     db->flags |= SQLITE_InternChanges;
01294   }
01295   sqliteViewResetAll(db, iDb);
01296 }
01297 
01298 /*
01299 ** This routine constructs a P3 string suitable for an OP_MakeIdxKey
01300 ** opcode and adds that P3 string to the most recently inserted instruction
01301 ** in the virtual machine.  The P3 string consists of a single character
01302 ** for each column in the index pIdx of table pTab.  If the column uses
01303 ** a numeric sort order, then the P3 string character corresponding to
01304 ** that column is 'n'.  If the column uses a text sort order, then the
01305 ** P3 string is 't'.  See the OP_MakeIdxKey opcode documentation for
01306 ** additional information.  See also the sqliteAddKeyType() routine.
01307 */
01308 void sqliteAddIdxKeyType(Vdbe *v, Index *pIdx){
01309   char *zType;
01310   Table *pTab;
01311   int i, n;
01312   assert( pIdx!=0 && pIdx->pTable!=0 );
01313   pTab = pIdx->pTable;
01314   n = pIdx->nColumn;
01315   zType = sqliteMallocRaw( n+1 );
01316   if( zType==0 ) return;
01317   for(i=0; i<n; i++){
01318     int iCol = pIdx->aiColumn[i];
01319     assert( iCol>=0 && iCol<pTab->nCol );
01320     if( (pTab->aCol[iCol].sortOrder & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
01321       zType[i] = 't';
01322     }else{
01323       zType[i] = 'n';
01324     }
01325   }
01326   zType[n] = 0;
01327   sqliteVdbeChangeP3(v, -1, zType, n);
01328   sqliteFree(zType);
01329 }
01330 
01331 /*
01332 ** This routine is called to create a new foreign key on the table
01333 ** currently under construction.  pFromCol determines which columns
01334 ** in the current table point to the foreign key.  If pFromCol==0 then
01335 ** connect the key to the last column inserted.  pTo is the name of
01336 ** the table referred to.  pToCol is a list of tables in the other
01337 ** pTo table that the foreign key points to.  flags contains all
01338 ** information about the conflict resolution algorithms specified
01339 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
01340 **
01341 ** An FKey structure is created and added to the table currently
01342 ** under construction in the pParse->pNewTable field.  The new FKey
01343 ** is not linked into db->aFKey at this point - that does not happen
01344 ** until sqliteEndTable().
01345 **
01346 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
01347 ** to sqliteDeferForeignKey() might change this to DEFERRED.
01348 */
01349 void sqliteCreateForeignKey(
01350   Parse *pParse,       /* Parsing context */
01351   IdList *pFromCol,    /* Columns in this table that point to other table */
01352   Token *pTo,          /* Name of the other table */
01353   IdList *pToCol,      /* Columns in the other table */
01354   int flags            /* Conflict resolution algorithms. */
01355 ){
01356   Table *p = pParse->pNewTable;
01357   int nByte;
01358   int i;
01359   int nCol;
01360   char *z;
01361   FKey *pFKey = 0;
01362 
01363   assert( pTo!=0 );
01364   if( p==0 || pParse->nErr ) goto fk_end;
01365   if( pFromCol==0 ){
01366     int iCol = p->nCol-1;
01367     if( iCol<0 ) goto fk_end;
01368     if( pToCol && pToCol->nId!=1 ){
01369       sqliteErrorMsg(pParse, "foreign key on %s"
01370          " should reference only one column of table %T",
01371          p->aCol[iCol].zName, pTo);
01372       goto fk_end;
01373     }
01374     nCol = 1;
01375   }else if( pToCol && pToCol->nId!=pFromCol->nId ){
01376     sqliteErrorMsg(pParse,
01377         "number of columns in foreign key does not match the number of "
01378         "columns in the referenced table");
01379     goto fk_end;
01380   }else{
01381     nCol = pFromCol->nId;
01382   }
01383   nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
01384   if( pToCol ){
01385     for(i=0; i<pToCol->nId; i++){
01386       nByte += strlen(pToCol->a[i].zName) + 1;
01387     }
01388   }
01389   pFKey = sqliteMalloc( nByte );
01390   if( pFKey==0 ) goto fk_end;
01391   pFKey->pFrom = p;
01392   pFKey->pNextFrom = p->pFKey;
01393   z = (char*)&pFKey[1];
01394   pFKey->aCol = (struct sColMap*)z;
01395   z += sizeof(struct sColMap)*nCol;
01396   pFKey->zTo = z;
01397   memcpy(z, pTo->z, pTo->n);
01398   z[pTo->n] = 0;
01399   z += pTo->n+1;
01400   pFKey->pNextTo = 0;
01401   pFKey->nCol = nCol;
01402   if( pFromCol==0 ){
01403     pFKey->aCol[0].iFrom = p->nCol-1;
01404   }else{
01405     for(i=0; i<nCol; i++){
01406       int j;
01407       for(j=0; j<p->nCol; j++){
01408         if( sqliteStrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
01409           pFKey->aCol[i].iFrom = j;
01410           break;
01411         }
01412       }
01413       if( j>=p->nCol ){
01414         sqliteErrorMsg(pParse, 
01415           "unknown column \"%s\" in foreign key definition", 
01416           pFromCol->a[i].zName);
01417         goto fk_end;
01418       }
01419     }
01420   }
01421   if( pToCol ){
01422     for(i=0; i<nCol; i++){
01423       int n = strlen(pToCol->a[i].zName);
01424       pFKey->aCol[i].zCol = z;
01425       memcpy(z, pToCol->a[i].zName, n);
01426       z[n] = 0;
01427       z += n+1;
01428     }
01429   }
01430   pFKey->isDeferred = 0;
01431   pFKey->deleteConf = flags & 0xff;
01432   pFKey->updateConf = (flags >> 8 ) & 0xff;
01433   pFKey->insertConf = (flags >> 16 ) & 0xff;
01434 
01435   /* Link the foreign key to the table as the last step.
01436   */
01437   p->pFKey = pFKey;
01438   pFKey = 0;
01439 
01440 fk_end:
01441   sqliteFree(pFKey);
01442   sqliteIdListDelete(pFromCol);
01443   sqliteIdListDelete(pToCol);
01444 }
01445 
01446 /*
01447 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
01448 ** clause is seen as part of a foreign key definition.  The isDeferred
01449 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
01450 ** The behavior of the most recently created foreign key is adjusted
01451 ** accordingly.
01452 */
01453 void sqliteDeferForeignKey(Parse *pParse, int isDeferred){
01454   Table *pTab;
01455   FKey *pFKey;
01456   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
01457   pFKey->isDeferred = isDeferred;
01458 }
01459 
01460 /*
01461 ** Create a new index for an SQL table.  pIndex is the name of the index 
01462 ** and pTable is the name of the table that is to be indexed.  Both will 
01463 ** be NULL for a primary key or an index that is created to satisfy a
01464 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
01465 ** as the table to be indexed.  pParse->pNewTable is a table that is
01466 ** currently being constructed by a CREATE TABLE statement.
01467 **
01468 ** pList is a list of columns to be indexed.  pList will be NULL if this
01469 ** is a primary key or unique-constraint on the most recent column added
01470 ** to the table currently under construction.  
01471 */
01472 void sqliteCreateIndex(
01473   Parse *pParse,   /* All information about this parse */
01474   Token *pName,    /* Name of the index.  May be NULL */
01475   SrcList *pTable, /* Name of the table to index.  Use pParse->pNewTable if 0 */
01476   IdList *pList,   /* A list of columns to be indexed */
01477   int onError,     /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
01478   Token *pStart,   /* The CREATE token that begins a CREATE TABLE statement */
01479   Token *pEnd      /* The ")" that closes the CREATE INDEX statement */
01480 ){
01481   Table *pTab;     /* Table to be indexed */
01482   Index *pIndex;   /* The index to be created */
01483   char *zName = 0;
01484   int i, j;
01485   Token nullId;    /* Fake token for an empty ID list */
01486   DbFixer sFix;    /* For assigning database names to pTable */
01487   int isTemp;      /* True for a temporary index */
01488   sqlite *db = pParse->db;
01489 
01490   if( pParse->nErr || sqlite_malloc_failed ) goto exit_create_index;
01491   if( db->init.busy 
01492      && sqliteFixInit(&sFix, pParse, db->init.iDb, "index", pName)
01493      && sqliteFixSrcList(&sFix, pTable)
01494   ){
01495     goto exit_create_index;
01496   }
01497 
01498   /*
01499   ** Find the table that is to be indexed.  Return early if not found.
01500   */
01501   if( pTable!=0 ){
01502     assert( pName!=0 );
01503     assert( pTable->nSrc==1 );
01504     pTab =  sqliteSrcListLookup(pParse, pTable);
01505   }else{
01506     assert( pName==0 );
01507     pTab =  pParse->pNewTable;
01508   }
01509   if( pTab==0 || pParse->nErr ) goto exit_create_index;
01510   if( pTab->readOnly ){
01511     sqliteErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
01512     goto exit_create_index;
01513   }
01514   if( pTab->iDb>=2 && db->init.busy==0 ){
01515     sqliteErrorMsg(pParse, "table %s may not have indices added", pTab->zName);
01516     goto exit_create_index;
01517   }
01518   if( pTab->pSelect ){
01519     sqliteErrorMsg(pParse, "views may not be indexed");
01520     goto exit_create_index;
01521   }
01522   isTemp = pTab->iDb==1;
01523 
01524   /*
01525   ** Find the name of the index.  Make sure there is not already another
01526   ** index or table with the same name.  
01527   **
01528   ** Exception:  If we are reading the names of permanent indices from the
01529   ** sqlite_master table (because some other process changed the schema) and
01530   ** one of the index names collides with the name of a temporary table or
01531   ** index, then we will continue to process this index.
01532   **
01533   ** If pName==0 it means that we are
01534   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
01535   ** own name.
01536   */
01537   if( pName && !db->init.busy ){
01538     Index *pISameName;    /* Another index with the same name */
01539     Table *pTSameName;    /* A table with same name as the index */
01540     zName = sqliteTableNameFromToken(pName);
01541     if( zName==0 ) goto exit_create_index;
01542     if( (pISameName = sqliteFindIndex(db, zName, 0))!=0 ){
01543       sqliteErrorMsg(pParse, "index %s already exists", zName);
01544       goto exit_create_index;
01545     }
01546     if( (pTSameName = sqliteFindTable(db, zName, 0))!=0 ){
01547       sqliteErrorMsg(pParse, "there is already a table named %s", zName);
01548       goto exit_create_index;
01549     }
01550   }else if( pName==0 ){
01551     char zBuf[30];
01552     int n;
01553     Index *pLoop;
01554     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
01555     sprintf(zBuf,"%d)",n);
01556     zName = 0;
01557     sqliteSetString(&zName, "(", pTab->zName, " autoindex ", zBuf, (char*)0);
01558     if( zName==0 ) goto exit_create_index;
01559   }else{
01560     zName = sqliteTableNameFromToken(pName);
01561   }
01562 
01563   /* Check for authorization to create an index.
01564   */
01565 #ifndef SQLITE_OMIT_AUTHORIZATION
01566   {
01567     const char *zDb = db->aDb[pTab->iDb].zName;
01568 
01569     assert( pTab->iDb==db->init.iDb || isTemp );
01570     if( sqliteAuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
01571       goto exit_create_index;
01572     }
01573     i = SQLITE_CREATE_INDEX;
01574     if( isTemp ) i = SQLITE_CREATE_TEMP_INDEX;
01575     if( sqliteAuthCheck(pParse, i, zName, pTab->zName, zDb) ){
01576       goto exit_create_index;
01577     }
01578   }
01579 #endif
01580 
01581   /* If pList==0, it means this routine was called to make a primary
01582   ** key out of the last column added to the table under construction.
01583   ** So create a fake list to simulate this.
01584   */
01585   if( pList==0 ){
01586     nullId.z = pTab->aCol[pTab->nCol-1].zName;
01587     nullId.n = strlen(nullId.z);
01588     pList = sqliteIdListAppend(0, &nullId);
01589     if( pList==0 ) goto exit_create_index;
01590   }
01591 
01592   /* 
01593   ** Allocate the index structure. 
01594   */
01595   pIndex = sqliteMalloc( sizeof(Index) + strlen(zName) + 1 +
01596                         sizeof(int)*pList->nId );
01597   if( pIndex==0 ) goto exit_create_index;
01598   pIndex->aiColumn = (int*)&pIndex[1];
01599   pIndex->zName = (char*)&pIndex->aiColumn[pList->nId];
01600   strcpy(pIndex->zName, zName);
01601   pIndex->pTable = pTab;
01602   pIndex->nColumn = pList->nId;
01603   pIndex->onError = onError;
01604   pIndex->autoIndex = pName==0;
01605   pIndex->iDb = isTemp ? 1 : db->init.iDb;
01606 
01607   /* Scan the names of the columns of the table to be indexed and
01608   ** load the column indices into the Index structure.  Report an error
01609   ** if any column is not found.
01610   */
01611   for(i=0; i<pList->nId; i++){
01612     for(j=0; j<pTab->nCol; j++){
01613       if( sqliteStrICmp(pList->a[i].zName, pTab->aCol[j].zName)==0 ) break;
01614     }
01615     if( j>=pTab->nCol ){
01616       sqliteErrorMsg(pParse, "table %s has no column named %s",
01617         pTab->zName, pList->a[i].zName);
01618       sqliteFree(pIndex);
01619       goto exit_create_index;
01620     }
01621     pIndex->aiColumn[i] = j;
01622   }
01623 
01624   /* Link the new Index structure to its table and to the other
01625   ** in-memory database structures. 
01626   */
01627   if( !pParse->explain ){
01628     Index *p;
01629     p = sqliteHashInsert(&db->aDb[pIndex->iDb].idxHash, 
01630                          pIndex->zName, strlen(pIndex->zName)+1, pIndex);
01631     if( p ){
01632       assert( p==pIndex );  /* Malloc must have failed */
01633       sqliteFree(pIndex);
01634       goto exit_create_index;
01635     }
01636     db->flags |= SQLITE_InternChanges;
01637   }
01638 
01639   /* When adding an index to the list of indices for a table, make
01640   ** sure all indices labeled OE_Replace come after all those labeled
01641   ** OE_Ignore.  This is necessary for the correct operation of UPDATE
01642   ** and INSERT.
01643   */
01644   if( onError!=OE_Replace || pTab->pIndex==0
01645        || pTab->pIndex->onError==OE_Replace){
01646     pIndex->pNext = pTab->pIndex;
01647     pTab->pIndex = pIndex;
01648   }else{
01649     Index *pOther = pTab->pIndex;
01650     while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
01651       pOther = pOther->pNext;
01652     }
01653     pIndex->pNext = pOther->pNext;
01654     pOther->pNext = pIndex;
01655   }
01656 
01657   /* If the db->init.busy is 1 it means we are reading the SQL off the
01658   ** "sqlite_master" table on the disk.  So do not write to the disk
01659   ** again.  Extract the table number from the db->init.newTnum field.
01660   */
01661   if( db->init.busy && pTable!=0 ){
01662     pIndex->tnum = db->init.newTnum;
01663   }
01664 
01665   /* If the db->init.busy is 0 then create the index on disk.  This
01666   ** involves writing the index into the master table and filling in the
01667   ** index with the current table contents.
01668   **
01669   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
01670   ** command.  db->init.busy is 1 when a database is opened and 
01671   ** CREATE INDEX statements are read out of the master table.  In
01672   ** the latter case the index already exists on disk, which is why
01673   ** we don't want to recreate it.
01674   **
01675   ** If pTable==0 it means this index is generated as a primary key
01676   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
01677   ** has just been created, it contains no data and the index initialization
01678   ** step can be skipped.
01679   */
01680   else if( db->init.busy==0 ){
01681     int n;
01682     Vdbe *v;
01683     int lbl1, lbl2;
01684     int i;
01685     int addr;
01686 
01687     v = sqliteGetVdbe(pParse);
01688     if( v==0 ) goto exit_create_index;
01689     if( pTable!=0 ){
01690       sqliteBeginWriteOperation(pParse, 0, isTemp);
01691       sqliteOpenMasterTable(v, isTemp);
01692     }
01693     sqliteVdbeAddOp(v, OP_NewRecno, 0, 0);
01694     sqliteVdbeOp3(v, OP_String, 0, 0, "index", P3_STATIC);
01695     sqliteVdbeOp3(v, OP_String, 0, 0, pIndex->zName, 0);
01696     sqliteVdbeOp3(v, OP_String, 0, 0, pTab->zName, 0);
01697     sqliteVdbeOp3(v, OP_CreateIndex, 0, isTemp,(char*)&pIndex->tnum,P3_POINTER);
01698     pIndex->tnum = 0;
01699     if( pTable ){
01700       sqliteVdbeCode(v,
01701           OP_Dup,       0,      0,
01702           OP_Integer,   isTemp, 0,
01703           OP_OpenWrite, 1,      0,
01704       0);
01705     }
01706     addr = sqliteVdbeAddOp(v, OP_String, 0, 0);
01707     if( pStart && pEnd ){
01708       n = Addr(pEnd->z) - Addr(pStart->z) + 1;
01709       sqliteVdbeChangeP3(v, addr, pStart->z, n);
01710     }
01711     sqliteVdbeAddOp(v, OP_MakeRecord, 5, 0);
01712     sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0);
01713     if( pTable ){
01714       sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
01715       sqliteVdbeOp3(v, OP_OpenRead, 2, pTab->tnum, pTab->zName, 0);
01716       lbl2 = sqliteVdbeMakeLabel(v);
01717       sqliteVdbeAddOp(v, OP_Rewind, 2, lbl2);
01718       lbl1 = sqliteVdbeAddOp(v, OP_Recno, 2, 0);
01719       for(i=0; i<pIndex->nColumn; i++){
01720         int iCol = pIndex->aiColumn[i];
01721         if( pTab->iPKey==iCol ){
01722           sqliteVdbeAddOp(v, OP_Dup, i, 0);
01723         }else{
01724           sqliteVdbeAddOp(v, OP_Column, 2, iCol);
01725         }
01726       }
01727       sqliteVdbeAddOp(v, OP_MakeIdxKey, pIndex->nColumn, 0);
01728       if( db->file_format>=4 ) sqliteAddIdxKeyType(v, pIndex);
01729       sqliteVdbeOp3(v, OP_IdxPut, 1, pIndex->onError!=OE_None,
01730                       "indexed columns are not unique", P3_STATIC);
01731       sqliteVdbeAddOp(v, OP_Next, 2, lbl1);
01732       sqliteVdbeResolveLabel(v, lbl2);
01733       sqliteVdbeAddOp(v, OP_Close, 2, 0);
01734       sqliteVdbeAddOp(v, OP_Close, 1, 0);
01735     }
01736     if( pTable!=0 ){
01737       if( !isTemp ){
01738         sqliteChangeCookie(db, v);
01739       }
01740       sqliteVdbeAddOp(v, OP_Close, 0, 0);
01741       sqliteEndWriteOperation(pParse);
01742     }
01743   }
01744 
01745   /* Clean up before exiting */
01746 exit_create_index:
01747   sqliteIdListDelete(pList);
01748   sqliteSrcListDelete(pTable);
01749   sqliteFree(zName);
01750   return;
01751 }
01752 
01753 /*
01754 ** This routine will drop an existing named index.  This routine
01755 ** implements the DROP INDEX statement.
01756 */
01757 void sqliteDropIndex(Parse *pParse, SrcList *pName){
01758   Index *pIndex;
01759   Vdbe *v;
01760   sqlite *db = pParse->db;
01761 
01762   if( pParse->nErr || sqlite_malloc_failed ) return;
01763   assert( pName->nSrc==1 );
01764   pIndex = sqliteFindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
01765   if( pIndex==0 ){
01766     sqliteErrorMsg(pParse, "no such index: %S", pName, 0);
01767     goto exit_drop_index;
01768   }
01769   if( pIndex->autoIndex ){
01770     sqliteErrorMsg(pParse, "index associated with UNIQUE "
01771       "or PRIMARY KEY constraint cannot be dropped", 0);
01772     goto exit_drop_index;
01773   }
01774   if( pIndex->iDb>1 ){
01775     sqliteErrorMsg(pParse, "cannot alter schema of attached "
01776        "databases", 0);
01777     goto exit_drop_index;
01778   }
01779 #ifndef SQLITE_OMIT_AUTHORIZATION
01780   {
01781     int code = SQLITE_DROP_INDEX;
01782     Table *pTab = pIndex->pTable;
01783     const char *zDb = db->aDb[pIndex->iDb].zName;
01784     const char *zTab = SCHEMA_TABLE(pIndex->iDb);
01785     if( sqliteAuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
01786       goto exit_drop_index;
01787     }
01788     if( pIndex->iDb ) code = SQLITE_DROP_TEMP_INDEX;
01789     if( sqliteAuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
01790       goto exit_drop_index;
01791     }
01792   }
01793 #endif
01794 
01795   /* Generate code to remove the index and from the master table */
01796   v = sqliteGetVdbe(pParse);
01797   if( v ){
01798     static VdbeOpList dropIndex[] = {
01799       { OP_Rewind,     0, ADDR(9), 0}, 
01800       { OP_String,     0, 0,       0}, /* 1 */
01801       { OP_MemStore,   1, 1,       0},
01802       { OP_MemLoad,    1, 0,       0}, /* 3 */
01803       { OP_Column,     0, 1,       0},
01804       { OP_Eq,         0, ADDR(8), 0},
01805       { OP_Next,       0, ADDR(3), 0},
01806       { OP_Goto,       0, ADDR(9), 0},
01807       { OP_Delete,     0, 0,       0}, /* 8 */
01808     };
01809     int base;
01810 
01811     sqliteBeginWriteOperation(pParse, 0, pIndex->iDb);
01812     sqliteOpenMasterTable(v, pIndex->iDb);
01813     base = sqliteVdbeAddOpList(v, ArraySize(dropIndex), dropIndex);
01814     sqliteVdbeChangeP3(v, base+1, pIndex->zName, 0);
01815     if( pIndex->iDb==0 ){
01816       sqliteChangeCookie(db, v);
01817     }
01818     sqliteVdbeAddOp(v, OP_Close, 0, 0);
01819     sqliteVdbeAddOp(v, OP_Destroy, pIndex->tnum, pIndex->iDb);
01820     sqliteEndWriteOperation(pParse);
01821   }
01822 
01823   /* Delete the in-memory description of this index.
01824   */
01825   if( !pParse->explain ){
01826     sqliteUnlinkAndDeleteIndex(db, pIndex);
01827     db->flags |= SQLITE_InternChanges;
01828   }
01829 
01830 exit_drop_index:
01831   sqliteSrcListDelete(pName);
01832 }
01833 
01834 /*
01835 ** Append a new element to the given IdList.  Create a new IdList if
01836 ** need be.
01837 **
01838 ** A new IdList is returned, or NULL if malloc() fails.
01839 */
01840 IdList *sqliteIdListAppend(IdList *pList, Token *pToken){
01841   if( pList==0 ){
01842     pList = sqliteMalloc( sizeof(IdList) );
01843     if( pList==0 ) return 0;
01844     pList->nAlloc = 0;
01845   }
01846   if( pList->nId>=pList->nAlloc ){
01847     struct IdList_item *a;
01848     pList->nAlloc = pList->nAlloc*2 + 5;
01849     a = sqliteRealloc(pList->a, pList->nAlloc*sizeof(pList->a[0]) );
01850     if( a==0 ){
01851       sqliteIdListDelete(pList);
01852       return 0;
01853     }
01854     pList->a = a;
01855   }
01856   memset(&pList->a[pList->nId], 0, sizeof(pList->a[0]));
01857   if( pToken ){
01858     char **pz = &pList->a[pList->nId].zName;
01859     sqliteSetNString(pz, pToken->z, pToken->n, 0);
01860     if( *pz==0 ){
01861       sqliteIdListDelete(pList);
01862       return 0;
01863     }else{
01864       sqliteDequote(*pz);
01865     }
01866   }
01867   pList->nId++;
01868   return pList;
01869 }
01870 
01871 /*
01872 ** Append a new table name to the given SrcList.  Create a new SrcList if
01873 ** need be.  A new entry is created in the SrcList even if pToken is NULL.
01874 **
01875 ** A new SrcList is returned, or NULL if malloc() fails.
01876 **
01877 ** If pDatabase is not null, it means that the table has an optional
01878 ** database name prefix.  Like this:  "database.table".  The pDatabase
01879 ** points to the table name and the pTable points to the database name.
01880 ** The SrcList.a[].zName field is filled with the table name which might
01881 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
01882 ** SrcList.a[].zDatabase is filled with the database name from pTable,
01883 ** or with NULL if no database is specified.
01884 **
01885 ** In other words, if call like this:
01886 **
01887 **         sqliteSrcListAppend(A,B,0);
01888 **
01889 ** Then B is a table name and the database name is unspecified.  If called
01890 ** like this:
01891 **
01892 **         sqliteSrcListAppend(A,B,C);
01893 **
01894 ** Then C is the table name and B is the database name.
01895 */
01896 SrcList *sqliteSrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
01897   if( pList==0 ){
01898     pList = sqliteMalloc( sizeof(SrcList) );
01899     if( pList==0 ) return 0;
01900     pList->nAlloc = 1;
01901   }
01902   if( pList->nSrc>=pList->nAlloc ){
01903     SrcList *pNew;
01904     pList->nAlloc *= 2;
01905     pNew = sqliteRealloc(pList,
01906                sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
01907     if( pNew==0 ){
01908       sqliteSrcListDelete(pList);
01909       return 0;
01910     }
01911     pList = pNew;
01912   }
01913   memset(&pList->a[pList->nSrc], 0, sizeof(pList->a[0]));
01914   if( pDatabase && pDatabase->z==0 ){
01915     pDatabase = 0;
01916   }
01917   if( pDatabase && pTable ){
01918     Token *pTemp = pDatabase;
01919     pDatabase = pTable;
01920     pTable = pTemp;
01921   }
01922   if( pTable ){
01923     char **pz = &pList->a[pList->nSrc].zName;
01924     sqliteSetNString(pz, pTable->z, pTable->n, 0);
01925     if( *pz==0 ){
01926       sqliteSrcListDelete(pList);
01927       return 0;
01928     }else{
01929       sqliteDequote(*pz);
01930     }
01931   }
01932   if( pDatabase ){
01933     char **pz = &pList->a[pList->nSrc].zDatabase;
01934     sqliteSetNString(pz, pDatabase->z, pDatabase->n, 0);
01935     if( *pz==0 ){
01936       sqliteSrcListDelete(pList);
01937       return 0;
01938     }else{
01939       sqliteDequote(*pz);
01940     }
01941   }
01942   pList->a[pList->nSrc].iCursor = -1;
01943   pList->nSrc++;
01944   return pList;
01945 }
01946 
01947 /*
01948 ** Assign cursors to all tables in a SrcList
01949 */
01950 void sqliteSrcListAssignCursors(Parse *pParse, SrcList *pList){
01951   int i;
01952   for(i=0; i<pList->nSrc; i++){
01953     if( pList->a[i].iCursor<0 ){
01954       pList->a[i].iCursor = pParse->nTab++;
01955     }
01956   }
01957 }
01958 
01959 /*
01960 ** Add an alias to the last identifier on the given identifier list.
01961 */
01962 void sqliteSrcListAddAlias(SrcList *pList, Token *pToken){
01963   if( pList && pList->nSrc>0 ){
01964     int i = pList->nSrc - 1;
01965     sqliteSetNString(&pList->a[i].zAlias, pToken->z, pToken->n, 0);
01966     sqliteDequote(pList->a[i].zAlias);
01967   }
01968 }
01969 
01970 /*
01971 ** Delete an IdList.
01972 */
01973 void sqliteIdListDelete(IdList *pList){
01974   int i;
01975   if( pList==0 ) return;
01976   for(i=0; i<pList->nId; i++){
01977     sqliteFree(pList->a[i].zName);
01978   }
01979   sqliteFree(pList->a);
01980   sqliteFree(pList);
01981 }
01982 
01983 /*
01984 ** Return the index in pList of the identifier named zId.  Return -1
01985 ** if not found.
01986 */
01987 int sqliteIdListIndex(IdList *pList, const char *zName){
01988   int i;
01989   if( pList==0 ) return -1;
01990   for(i=0; i<pList->nId; i++){
01991     if( sqliteStrICmp(pList->a[i].zName, zName)==0 ) return i;
01992   }
01993   return -1;
01994 }
01995 
01996 /*
01997 ** Delete an entire SrcList including all its substructure.
01998 */
01999 void sqliteSrcListDelete(SrcList *pList){
02000   int i;
02001   if( pList==0 ) return;
02002   for(i=0; i<pList->nSrc; i++){
02003     sqliteFree(pList->a[i].zDatabase);
02004     sqliteFree(pList->a[i].zName);
02005     sqliteFree(pList->a[i].zAlias);
02006     if( pList->a[i].pTab && pList->a[i].pTab->isTransient ){
02007       sqliteDeleteTable(0, pList->a[i].pTab);
02008     }
02009     sqliteSelectDelete(pList->a[i].pSelect);
02010     sqliteExprDelete(pList->a[i].pOn);
02011     sqliteIdListDelete(pList->a[i].pUsing);
02012   }
02013   sqliteFree(pList);
02014 }
02015 
02016 /*
02017 ** Begin a transaction
02018 */
02019 void sqliteBeginTransaction(Parse *pParse, int onError){
02020   sqlite *db;
02021 
02022   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
02023   if( pParse->nErr || sqlite_malloc_failed ) return;
02024   if( sqliteAuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
02025   if( db->flags & SQLITE_InTrans ){
02026     sqliteErrorMsg(pParse, "cannot start a transaction within a transaction");
02027     return;
02028   }
02029   sqliteBeginWriteOperation(pParse, 0, 0);
02030   if( !pParse->explain ){
02031     db->flags |= SQLITE_InTrans;
02032     db->onError = onError;
02033   }
02034 }
02035 
02036 /*
02037 ** Commit a transaction
02038 */
02039 void sqliteCommitTransaction(Parse *pParse){
02040   sqlite *db;
02041 
02042   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
02043   if( pParse->nErr || sqlite_malloc_failed ) return;
02044   if( sqliteAuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
02045   if( (db->flags & SQLITE_InTrans)==0 ){
02046     sqliteErrorMsg(pParse, "cannot commit - no transaction is active");
02047     return;
02048   }
02049   if( !pParse->explain ){
02050     db->flags &= ~SQLITE_InTrans;
02051   }
02052   sqliteEndWriteOperation(pParse);
02053   if( !pParse->explain ){
02054     db->onError = OE_Default;
02055   }
02056 }
02057 
02058 /*
02059 ** Rollback a transaction
02060 */
02061 void sqliteRollbackTransaction(Parse *pParse){
02062   sqlite *db;
02063   Vdbe *v;
02064 
02065   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
02066   if( pParse->nErr || sqlite_malloc_failed ) return;
02067   if( sqliteAuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
02068   if( (db->flags & SQLITE_InTrans)==0 ){
02069     sqliteErrorMsg(pParse, "cannot rollback - no transaction is active");
02070     return; 
02071   }
02072   v = sqliteGetVdbe(pParse);
02073   if( v ){
02074     sqliteVdbeAddOp(v, OP_Rollback, 0, 0);
02075   }
02076   if( !pParse->explain ){
02077     db->flags &= ~SQLITE_InTrans;
02078     db->onError = OE_Default;
02079   }
02080 }
02081 
02082 /*
02083 ** Generate VDBE code that will verify the schema cookie for all
02084 ** named database files.
02085 */
02086 void sqliteCodeVerifySchema(Parse *pParse, int iDb){
02087   sqlite *db = pParse->db;
02088   Vdbe *v = sqliteGetVdbe(pParse);
02089   assert( iDb>=0 && iDb<db->nDb );
02090   assert( db->aDb[iDb].pBt!=0 );
02091   if( iDb!=1 && !DbHasProperty(db, iDb, DB_Cookie) ){
02092     sqliteVdbeAddOp(v, OP_VerifyCookie, iDb, db->aDb[iDb].schema_cookie);
02093     DbSetProperty(db, iDb, DB_Cookie);
02094   }
02095 }
02096 
02097 /*
02098 ** Generate VDBE code that prepares for doing an operation that
02099 ** might change the database.
02100 **
02101 ** This routine starts a new transaction if we are not already within
02102 ** a transaction.  If we are already within a transaction, then a checkpoint
02103 ** is set if the setCheckpoint parameter is true.  A checkpoint should
02104 ** be set for operations that might fail (due to a constraint) part of
02105 ** the way through and which will need to undo some writes without having to
02106 ** rollback the whole transaction.  For operations where all constraints
02107 ** can be checked before any changes are made to the database, it is never
02108 ** necessary to undo a write and the checkpoint should not be set.
02109 **
02110 ** Only database iDb and the temp database are made writable by this call.
02111 ** If iDb==0, then the main and temp databases are made writable.   If
02112 ** iDb==1 then only the temp database is made writable.  If iDb>1 then the
02113 ** specified auxiliary database and the temp database are made writable.
02114 */
02115 void sqliteBeginWriteOperation(Parse *pParse, int setCheckpoint, int iDb){
02116   Vdbe *v;
02117   sqlite *db = pParse->db;
02118   if( DbHasProperty(db, iDb, DB_Locked) ) return;
02119   v = sqliteGetVdbe(pParse);
02120   if( v==0 ) return;
02121   if( !db->aDb[iDb].inTrans ){
02122     sqliteVdbeAddOp(v, OP_Transaction, iDb, 0);
02123     DbSetProperty(db, iDb, DB_Locked);
02124     sqliteCodeVerifySchema(pParse, iDb);
02125     if( iDb!=1 ){
02126       sqliteBeginWriteOperation(pParse, setCheckpoint, 1);
02127     }
02128   }else if( setCheckpoint ){
02129     sqliteVdbeAddOp(v, OP_Checkpoint, iDb, 0);
02130     DbSetProperty(db, iDb, DB_Locked);
02131   }
02132 }
02133 
02134 /*
02135 ** Generate code that concludes an operation that may have changed
02136 ** the database.  If a statement transaction was started, then emit
02137 ** an OP_Commit that will cause the changes to be committed to disk.
02138 **
02139 ** Note that checkpoints are automatically committed at the end of
02140 ** a statement.  Note also that there can be multiple calls to 
02141 ** sqliteBeginWriteOperation() but there should only be a single
02142 ** call to sqliteEndWriteOperation() at the conclusion of the statement.
02143 */
02144 void sqliteEndWriteOperation(Parse *pParse){
02145   Vdbe *v;
02146   sqlite *db = pParse->db;
02147   if( pParse->trigStack ) return; /* if this is in a trigger */
02148   v = sqliteGetVdbe(pParse);
02149   if( v==0 ) return;
02150   if( db->flags & SQLITE_InTrans ){
02151     /* A BEGIN has executed.  Do not commit until we see an explicit
02152     ** COMMIT statement. */
02153   }else{
02154     sqliteVdbeAddOp(v, OP_Commit, 0, 0);
02155   }
02156 }