PHP  
 PHP: Test and Code Coverage Analysis
downloads | QA | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
 

LTP GCOV extension - code coverage report
Current view: directory - pdo_sqlite/sqlite/src - build.c
Test: PHP Code Coverage
Date: 2009-11-19 Instrumented lines: 1286
Code covered: 51.9 % Executed lines: 667
Legend: not executed executed

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

Generated by: LTP GCOV extension version 1.5

Generated at Thu, 19 Nov 2009 08:20:16 +0000 (5 days ago)

Copyright © 2005-2009 The PHP Group
All rights reserved.